iwlwifi: replace restricted_reg with prph
[safe/jmp/linux-2.6] / drivers / net / wireless / iwlwifi / iwl-4965.c
1 /******************************************************************************
2  *
3  * Copyright(c) 2003 - 2007 Intel Corporation. All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of version 2 of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  *
14  * You should have received a copy of the GNU General Public License along with
15  * this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
17  *
18  * The full GNU General Public License is included in this distribution in the
19  * file called LICENSE.
20  *
21  * Contact Information:
22  * James P. Ketrenos <ipw2100-admin@linux.intel.com>
23  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
24  *
25  *****************************************************************************/
26
27 #include <linux/kernel.h>
28 #include <linux/module.h>
29 #include <linux/version.h>
30 #include <linux/init.h>
31 #include <linux/pci.h>
32 #include <linux/dma-mapping.h>
33 #include <linux/delay.h>
34 #include <linux/skbuff.h>
35 #include <linux/netdevice.h>
36 #include <linux/wireless.h>
37 #include <net/mac80211.h>
38 #include <linux/etherdevice.h>
39
40 #define IWL 4965
41
42 #include "iwlwifi.h"
43 #include "iwl-4965.h"
44 #include "iwl-helpers.h"
45
46 #define IWL_DECLARE_RATE_INFO(r, s, ip, in, rp, rn, pp, np)    \
47         [IWL_RATE_##r##M_INDEX] = { IWL_RATE_##r##M_PLCP,      \
48                                     IWL_RATE_SISO_##s##M_PLCP, \
49                                     IWL_RATE_MIMO_##s##M_PLCP, \
50                                     IWL_RATE_##r##M_IEEE,      \
51                                     IWL_RATE_##ip##M_INDEX,    \
52                                     IWL_RATE_##in##M_INDEX,    \
53                                     IWL_RATE_##rp##M_INDEX,    \
54                                     IWL_RATE_##rn##M_INDEX,    \
55                                     IWL_RATE_##pp##M_INDEX,    \
56                                     IWL_RATE_##np##M_INDEX }
57
58 /*
59  * Parameter order:
60  *   rate, ht rate, prev rate, next rate, prev tgg rate, next tgg rate
61  *
62  * If there isn't a valid next or previous rate then INV is used which
63  * maps to IWL_RATE_INVALID
64  *
65  */
66 const struct iwl_rate_info iwl_rates[IWL_RATE_COUNT] = {
67         IWL_DECLARE_RATE_INFO(1, INV, INV, 2, INV, 2, INV, 2),    /*  1mbps */
68         IWL_DECLARE_RATE_INFO(2, INV, 1, 5, 1, 5, 1, 5),          /*  2mbps */
69         IWL_DECLARE_RATE_INFO(5, INV, 2, 6, 2, 11, 2, 11),        /*5.5mbps */
70         IWL_DECLARE_RATE_INFO(11, INV, 9, 12, 9, 12, 5, 18),      /* 11mbps */
71         IWL_DECLARE_RATE_INFO(6, 6, 5, 9, 5, 11, 5, 11),        /*  6mbps */
72         IWL_DECLARE_RATE_INFO(9, 6, 6, 11, 6, 11, 5, 11),       /*  9mbps */
73         IWL_DECLARE_RATE_INFO(12, 12, 11, 18, 11, 18, 11, 18),   /* 12mbps */
74         IWL_DECLARE_RATE_INFO(18, 18, 12, 24, 12, 24, 11, 24),   /* 18mbps */
75         IWL_DECLARE_RATE_INFO(24, 24, 18, 36, 18, 36, 18, 36),   /* 24mbps */
76         IWL_DECLARE_RATE_INFO(36, 36, 24, 48, 24, 48, 24, 48),   /* 36mbps */
77         IWL_DECLARE_RATE_INFO(48, 48, 36, 54, 36, 54, 36, 54),   /* 48mbps */
78         IWL_DECLARE_RATE_INFO(54, 54, 48, INV, 48, INV, 48, INV),/* 54mbps */
79         IWL_DECLARE_RATE_INFO(60, 60, 48, INV, 48, INV, 48, INV),/* 60mbps */
80 };
81
82 static int is_fat_channel(__le32 rxon_flags)
83 {
84         return (rxon_flags & RXON_FLG_CHANNEL_MODE_PURE_40_MSK) ||
85                 (rxon_flags & RXON_FLG_CHANNEL_MODE_MIXED_MSK);
86 }
87
88 static u8 is_single_stream(struct iwl_priv *priv)
89 {
90 #ifdef CONFIG_IWLWIFI_HT
91         if (!priv->is_ht_enabled || !priv->current_assoc_ht.is_ht ||
92             (priv->active_rate_ht[1] == 0) ||
93             (priv->ps_mode == IWL_MIMO_PS_STATIC))
94                 return 1;
95 #else
96         return 1;
97 #endif  /*CONFIG_IWLWIFI_HT */
98         return 0;
99 }
100
101 /*
102  * Determine how many receiver/antenna chains to use.
103  * More provides better reception via diversity.  Fewer saves power.
104  * MIMO (dual stream) requires at least 2, but works better with 3.
105  * This does not determine *which* chains to use, just how many.
106  */
107 static int iwl4965_get_rx_chain_counter(struct iwl_priv *priv,
108                                         u8 *idle_state, u8 *rx_state)
109 {
110         u8 is_single = is_single_stream(priv);
111         u8 is_cam = test_bit(STATUS_POWER_PMI, &priv->status) ? 0 : 1;
112
113         /* # of Rx chains to use when expecting MIMO. */
114         if (is_single || (!is_cam && (priv->ps_mode == IWL_MIMO_PS_STATIC)))
115                 *rx_state = 2;
116         else
117                 *rx_state = 3;
118
119         /* # Rx chains when idling and maybe trying to save power */
120         switch (priv->ps_mode) {
121         case IWL_MIMO_PS_STATIC:
122         case IWL_MIMO_PS_DYNAMIC:
123                 *idle_state = (is_cam) ? 2 : 1;
124                 break;
125         case IWL_MIMO_PS_NONE:
126                 *idle_state = (is_cam) ? *rx_state : 1;
127                 break;
128         default:
129                 *idle_state = 1;
130                 break;
131         }
132
133         return 0;
134 }
135
136 int iwl_hw_rxq_stop(struct iwl_priv *priv)
137 {
138         int rc;
139         unsigned long flags;
140
141         spin_lock_irqsave(&priv->lock, flags);
142         rc = iwl_grab_restricted_access(priv);
143         if (rc) {
144                 spin_unlock_irqrestore(&priv->lock, flags);
145                 return rc;
146         }
147
148         /* stop HW */
149         iwl_write_restricted(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0);
150         rc = iwl_poll_restricted_bit(priv, FH_MEM_RSSR_RX_STATUS_REG,
151                                      (1 << 24), 1000);
152         if (rc < 0)
153                 IWL_ERROR("Can't stop Rx DMA.\n");
154
155         iwl_release_restricted_access(priv);
156         spin_unlock_irqrestore(&priv->lock, flags);
157
158         return 0;
159 }
160
161 u8 iwl_hw_find_station(struct iwl_priv *priv, const u8 *addr)
162 {
163         int i;
164         int start = 0;
165         int ret = IWL_INVALID_STATION;
166         unsigned long flags;
167         DECLARE_MAC_BUF(mac);
168
169         if ((priv->iw_mode == IEEE80211_IF_TYPE_IBSS) ||
170             (priv->iw_mode == IEEE80211_IF_TYPE_AP))
171                 start = IWL_STA_ID;
172
173         if (is_broadcast_ether_addr(addr))
174                 return IWL4965_BROADCAST_ID;
175
176         spin_lock_irqsave(&priv->sta_lock, flags);
177         for (i = start; i < priv->hw_setting.max_stations; i++)
178                 if ((priv->stations[i].used) &&
179                     (!compare_ether_addr
180                      (priv->stations[i].sta.sta.addr, addr))) {
181                         ret = i;
182                         goto out;
183                 }
184
185         IWL_DEBUG_ASSOC_LIMIT("can not find STA %s total %d\n",
186                         print_mac(mac, addr), priv->num_stations);
187
188  out:
189         spin_unlock_irqrestore(&priv->sta_lock, flags);
190         return ret;
191 }
192
193 static int iwl4965_nic_set_pwr_src(struct iwl_priv *priv, int pwr_max)
194 {
195         int ret;
196         unsigned long flags;
197
198         spin_lock_irqsave(&priv->lock, flags);
199         ret = iwl_grab_restricted_access(priv);
200         if (ret) {
201                 spin_unlock_irqrestore(&priv->lock, flags);
202                 return ret;
203         }
204
205         if (!pwr_max) {
206                 u32 val;
207
208                 ret = pci_read_config_dword(priv->pci_dev, PCI_POWER_SOURCE,
209                                            &val);
210
211                 if (val & PCI_CFG_PMC_PME_FROM_D3COLD_SUPPORT)
212                         iwl_set_bits_mask_prph(priv, APMG_PS_CTRL_REG,
213                                 APMG_PS_CTRL_VAL_PWR_SRC_VAUX,
214                                 ~APMG_PS_CTRL_MSK_PWR_SRC);
215         } else
216                 iwl_set_bits_mask_prph(priv, APMG_PS_CTRL_REG,
217                         APMG_PS_CTRL_VAL_PWR_SRC_VMAIN,
218                         ~APMG_PS_CTRL_MSK_PWR_SRC);
219
220         iwl_release_restricted_access(priv);
221         spin_unlock_irqrestore(&priv->lock, flags);
222
223         return ret;
224 }
225
226 static int iwl4965_rx_init(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
227 {
228         int rc;
229         unsigned long flags;
230
231         spin_lock_irqsave(&priv->lock, flags);
232         rc = iwl_grab_restricted_access(priv);
233         if (rc) {
234                 spin_unlock_irqrestore(&priv->lock, flags);
235                 return rc;
236         }
237
238         /* stop HW */
239         iwl_write_restricted(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0);
240
241         iwl_write_restricted(priv, FH_RSCSR_CHNL0_RBDCB_WPTR_REG, 0);
242         iwl_write_restricted(priv, FH_RSCSR_CHNL0_RBDCB_BASE_REG,
243                              rxq->dma_addr >> 8);
244
245         iwl_write_restricted(priv, FH_RSCSR_CHNL0_STTS_WPTR_REG,
246                              (priv->hw_setting.shared_phys +
247                               offsetof(struct iwl_shared, val0)) >> 4);
248
249         iwl_write_restricted(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG,
250                              FH_RCSR_RX_CONFIG_CHNL_EN_ENABLE_VAL |
251                              FH_RCSR_CHNL0_RX_CONFIG_IRQ_DEST_INT_HOST_VAL |
252                              IWL_FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_4K |
253                              /*0x10 << 4 | */
254                              (RX_QUEUE_SIZE_LOG <<
255                               FH_RCSR_RX_CONFIG_RBDCB_SIZE_BITSHIFT));
256
257         /*
258          * iwl_write32(priv,CSR_INT_COAL_REG,0);
259          */
260
261         iwl_release_restricted_access(priv);
262         spin_unlock_irqrestore(&priv->lock, flags);
263
264         return 0;
265 }
266
267 static int iwl4965_kw_init(struct iwl_priv *priv)
268 {
269         unsigned long flags;
270         int rc;
271
272         spin_lock_irqsave(&priv->lock, flags);
273         rc = iwl_grab_restricted_access(priv);
274         if (rc)
275                 goto out;
276
277         iwl_write_restricted(priv, IWL_FH_KW_MEM_ADDR_REG,
278                              priv->kw.dma_addr >> 4);
279         iwl_release_restricted_access(priv);
280 out:
281         spin_unlock_irqrestore(&priv->lock, flags);
282         return rc;
283 }
284
285 static int iwl4965_kw_alloc(struct iwl_priv *priv)
286 {
287         struct pci_dev *dev = priv->pci_dev;
288         struct iwl_kw *kw = &priv->kw;
289
290         kw->size = IWL4965_KW_SIZE;     /* TBW need set somewhere else */
291         kw->v_addr = pci_alloc_consistent(dev, kw->size, &kw->dma_addr);
292         if (!kw->v_addr)
293                 return -ENOMEM;
294
295         return 0;
296 }
297
298 #define CHECK_AND_PRINT(x) ((eeprom_ch->flags & EEPROM_CHANNEL_##x) \
299                             ? # x " " : "")
300
301 int iwl4965_set_fat_chan_info(struct iwl_priv *priv, int phymode, u16 channel,
302                               const struct iwl_eeprom_channel *eeprom_ch,
303                               u8 fat_extension_channel)
304 {
305         struct iwl_channel_info *ch_info;
306
307         ch_info = (struct iwl_channel_info *)
308                         iwl_get_channel_info(priv, phymode, channel);
309
310         if (!is_channel_valid(ch_info))
311                 return -1;
312
313         IWL_DEBUG_INFO("FAT Ch. %d [%sGHz] %s%s%s%s%s%s(0x%02x"
314                         " %ddBm): Ad-Hoc %ssupported\n",
315                         ch_info->channel,
316                         is_channel_a_band(ch_info) ?
317                         "5.2" : "2.4",
318                         CHECK_AND_PRINT(IBSS),
319                         CHECK_AND_PRINT(ACTIVE),
320                         CHECK_AND_PRINT(RADAR),
321                         CHECK_AND_PRINT(WIDE),
322                         CHECK_AND_PRINT(NARROW),
323                         CHECK_AND_PRINT(DFS),
324                         eeprom_ch->flags,
325                         eeprom_ch->max_power_avg,
326                         ((eeprom_ch->flags & EEPROM_CHANNEL_IBSS)
327                          && !(eeprom_ch->flags & EEPROM_CHANNEL_RADAR)) ?
328                         "" : "not ");
329
330         ch_info->fat_eeprom = *eeprom_ch;
331         ch_info->fat_max_power_avg = eeprom_ch->max_power_avg;
332         ch_info->fat_curr_txpow = eeprom_ch->max_power_avg;
333         ch_info->fat_min_power = 0;
334         ch_info->fat_scan_power = eeprom_ch->max_power_avg;
335         ch_info->fat_flags = eeprom_ch->flags;
336         ch_info->fat_extension_channel = fat_extension_channel;
337
338         return 0;
339 }
340
341 static void iwl4965_kw_free(struct iwl_priv *priv)
342 {
343         struct pci_dev *dev = priv->pci_dev;
344         struct iwl_kw *kw = &priv->kw;
345
346         if (kw->v_addr) {
347                 pci_free_consistent(dev, kw->size, kw->v_addr, kw->dma_addr);
348                 memset(kw, 0, sizeof(*kw));
349         }
350 }
351
352 /**
353  * iwl4965_txq_ctx_reset - Reset TX queue context
354  * Destroys all DMA structures and initialise them again
355  *
356  * @param priv
357  * @return error code
358  */
359 static int iwl4965_txq_ctx_reset(struct iwl_priv *priv)
360 {
361         int rc = 0;
362         int txq_id, slots_num;
363         unsigned long flags;
364
365         iwl4965_kw_free(priv);
366
367         iwl_hw_txq_ctx_free(priv);
368
369         /* Tx CMD queue */
370         rc = iwl4965_kw_alloc(priv);
371         if (rc) {
372                 IWL_ERROR("Keep Warm allocation failed");
373                 goto error_kw;
374         }
375
376         spin_lock_irqsave(&priv->lock, flags);
377
378         rc = iwl_grab_restricted_access(priv);
379         if (unlikely(rc)) {
380                 IWL_ERROR("TX reset failed");
381                 spin_unlock_irqrestore(&priv->lock, flags);
382                 goto error_reset;
383         }
384
385         iwl_write_prph(priv, SCD_TXFACT, 0);
386         iwl_release_restricted_access(priv);
387         spin_unlock_irqrestore(&priv->lock, flags);
388
389         rc = iwl4965_kw_init(priv);
390         if (rc) {
391                 IWL_ERROR("kw_init failed\n");
392                 goto error_reset;
393         }
394
395         /* Tx queue(s) */
396         for (txq_id = 0; txq_id < priv->hw_setting.max_txq_num; txq_id++) {
397                 slots_num = (txq_id == IWL_CMD_QUEUE_NUM) ?
398                                         TFD_CMD_SLOTS : TFD_TX_CMD_SLOTS;
399                 rc = iwl_tx_queue_init(priv, &priv->txq[txq_id], slots_num,
400                                        txq_id);
401                 if (rc) {
402                         IWL_ERROR("Tx %d queue init failed\n", txq_id);
403                         goto error;
404                 }
405         }
406
407         return rc;
408
409  error:
410         iwl_hw_txq_ctx_free(priv);
411  error_reset:
412         iwl4965_kw_free(priv);
413  error_kw:
414         return rc;
415 }
416
417 int iwl_hw_nic_init(struct iwl_priv *priv)
418 {
419         int rc;
420         unsigned long flags;
421         struct iwl_rx_queue *rxq = &priv->rxq;
422         u8 rev_id;
423         u32 val;
424         u8 val_link;
425
426         iwl_power_init_handle(priv);
427
428         /* nic_init */
429         spin_lock_irqsave(&priv->lock, flags);
430
431         iwl_set_bit(priv, CSR_GIO_CHICKEN_BITS,
432                     CSR_GIO_CHICKEN_BITS_REG_BIT_DIS_L0S_EXIT_TIMER);
433
434         iwl_set_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
435         rc = iwl_poll_bit(priv, CSR_GP_CNTRL,
436                           CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY,
437                           CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY, 25000);
438         if (rc < 0) {
439                 spin_unlock_irqrestore(&priv->lock, flags);
440                 IWL_DEBUG_INFO("Failed to init the card\n");
441                 return rc;
442         }
443
444         rc = iwl_grab_restricted_access(priv);
445         if (rc) {
446                 spin_unlock_irqrestore(&priv->lock, flags);
447                 return rc;
448         }
449
450         iwl_read_prph(priv, APMG_CLK_CTRL_REG);
451
452         iwl_write_prph(priv, APMG_CLK_CTRL_REG,
453                                  APMG_CLK_VAL_DMA_CLK_RQT |
454                                  APMG_CLK_VAL_BSM_CLK_RQT);
455         iwl_read_prph(priv, APMG_CLK_CTRL_REG);
456
457         udelay(20);
458
459         iwl_set_bits_prph(priv, APMG_PCIDEV_STT_REG,
460                                     APMG_PCIDEV_STT_VAL_L1_ACT_DIS);
461
462         iwl_release_restricted_access(priv);
463         iwl_write32(priv, CSR_INT_COALESCING, 512 / 32);
464         spin_unlock_irqrestore(&priv->lock, flags);
465
466         /* Determine HW type */
467         rc = pci_read_config_byte(priv->pci_dev, PCI_REVISION_ID, &rev_id);
468         if (rc)
469                 return rc;
470
471         IWL_DEBUG_INFO("HW Revision ID = 0x%X\n", rev_id);
472
473         iwl4965_nic_set_pwr_src(priv, 1);
474         spin_lock_irqsave(&priv->lock, flags);
475
476         if ((rev_id & 0x80) == 0x80 && (rev_id & 0x7f) < 8) {
477                 pci_read_config_dword(priv->pci_dev, PCI_REG_WUM8, &val);
478                 /* Enable No Snoop field */
479                 pci_write_config_dword(priv->pci_dev, PCI_REG_WUM8,
480                                        val & ~(1 << 11));
481         }
482
483         spin_unlock_irqrestore(&priv->lock, flags);
484
485         /* Read the EEPROM */
486         rc = iwl_eeprom_init(priv);
487         if (rc)
488                 return rc;
489
490         if (priv->eeprom.calib_version < EEPROM_TX_POWER_VERSION_NEW) {
491                 IWL_ERROR("Older EEPROM detected!  Aborting.\n");
492                 return -EINVAL;
493         }
494
495         pci_read_config_byte(priv->pci_dev, PCI_LINK_CTRL, &val_link);
496
497         /* disable L1 entry -- workaround for pre-B1 */
498         pci_write_config_byte(priv->pci_dev, PCI_LINK_CTRL, val_link & ~0x02);
499
500         spin_lock_irqsave(&priv->lock, flags);
501
502         /* set CSR_HW_CONFIG_REG for uCode use */
503
504         iwl_set_bit(priv, CSR_SW_VER, CSR_HW_IF_CONFIG_REG_BIT_KEDRON_R |
505                     CSR_HW_IF_CONFIG_REG_BIT_RADIO_SI |
506                     CSR_HW_IF_CONFIG_REG_BIT_MAC_SI);
507
508         rc = iwl_grab_restricted_access(priv);
509         if (rc < 0) {
510                 spin_unlock_irqrestore(&priv->lock, flags);
511                 IWL_DEBUG_INFO("Failed to init the card\n");
512                 return rc;
513         }
514
515         iwl_read_prph(priv, APMG_PS_CTRL_REG);
516         iwl_set_bits_prph(priv, APMG_PS_CTRL_REG,
517                                     APMG_PS_CTRL_VAL_RESET_REQ);
518         udelay(5);
519         iwl_clear_bits_prph(priv, APMG_PS_CTRL_REG,
520                                       APMG_PS_CTRL_VAL_RESET_REQ);
521
522         iwl_release_restricted_access(priv);
523         spin_unlock_irqrestore(&priv->lock, flags);
524
525         iwl_hw_card_show_info(priv);
526
527         /* end nic_init */
528
529         /* Allocate the RX queue, or reset if it is already allocated */
530         if (!rxq->bd) {
531                 rc = iwl_rx_queue_alloc(priv);
532                 if (rc) {
533                         IWL_ERROR("Unable to initialize Rx queue\n");
534                         return -ENOMEM;
535                 }
536         } else
537                 iwl_rx_queue_reset(priv, rxq);
538
539         iwl_rx_replenish(priv);
540
541         iwl4965_rx_init(priv, rxq);
542
543         spin_lock_irqsave(&priv->lock, flags);
544
545         rxq->need_update = 1;
546         iwl_rx_queue_update_write_ptr(priv, rxq);
547
548         spin_unlock_irqrestore(&priv->lock, flags);
549         rc = iwl4965_txq_ctx_reset(priv);
550         if (rc)
551                 return rc;
552
553         if (priv->eeprom.sku_cap & EEPROM_SKU_CAP_SW_RF_KILL_ENABLE)
554                 IWL_DEBUG_RF_KILL("SW RF KILL supported in EEPROM.\n");
555
556         if (priv->eeprom.sku_cap & EEPROM_SKU_CAP_HW_RF_KILL_ENABLE)
557                 IWL_DEBUG_RF_KILL("HW RF KILL supported in EEPROM.\n");
558
559         set_bit(STATUS_INIT, &priv->status);
560
561         return 0;
562 }
563
564 int iwl_hw_nic_stop_master(struct iwl_priv *priv)
565 {
566         int rc = 0;
567         u32 reg_val;
568         unsigned long flags;
569
570         spin_lock_irqsave(&priv->lock, flags);
571
572         /* set stop master bit */
573         iwl_set_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_STOP_MASTER);
574
575         reg_val = iwl_read32(priv, CSR_GP_CNTRL);
576
577         if (CSR_GP_CNTRL_REG_FLAG_MAC_POWER_SAVE ==
578             (reg_val & CSR_GP_CNTRL_REG_MSK_POWER_SAVE_TYPE))
579                 IWL_DEBUG_INFO("Card in power save, master is already "
580                                "stopped\n");
581         else {
582                 rc = iwl_poll_bit(priv, CSR_RESET,
583                                   CSR_RESET_REG_FLAG_MASTER_DISABLED,
584                                   CSR_RESET_REG_FLAG_MASTER_DISABLED, 100);
585                 if (rc < 0) {
586                         spin_unlock_irqrestore(&priv->lock, flags);
587                         return rc;
588                 }
589         }
590
591         spin_unlock_irqrestore(&priv->lock, flags);
592         IWL_DEBUG_INFO("stop master\n");
593
594         return rc;
595 }
596
597 void iwl_hw_txq_ctx_stop(struct iwl_priv *priv)
598 {
599
600         int txq_id;
601         unsigned long flags;
602
603         /* reset TFD queues */
604         for (txq_id = 0; txq_id < priv->hw_setting.max_txq_num; txq_id++) {
605                 spin_lock_irqsave(&priv->lock, flags);
606                 if (iwl_grab_restricted_access(priv)) {
607                         spin_unlock_irqrestore(&priv->lock, flags);
608                         continue;
609                 }
610
611                 iwl_write_restricted(priv,
612                                      IWL_FH_TCSR_CHNL_TX_CONFIG_REG(txq_id),
613                                      0x0);
614                 iwl_poll_restricted_bit(priv, IWL_FH_TSSR_TX_STATUS_REG,
615                                         IWL_FH_TSSR_TX_STATUS_REG_MSK_CHNL_IDLE
616                                         (txq_id), 200);
617                 iwl_release_restricted_access(priv);
618                 spin_unlock_irqrestore(&priv->lock, flags);
619         }
620
621         iwl_hw_txq_ctx_free(priv);
622 }
623
624 int iwl_hw_nic_reset(struct iwl_priv *priv)
625 {
626         int rc = 0;
627         unsigned long flags;
628
629         iwl_hw_nic_stop_master(priv);
630
631         spin_lock_irqsave(&priv->lock, flags);
632
633         iwl_set_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_SW_RESET);
634
635         udelay(10);
636
637         iwl_set_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
638         rc = iwl_poll_bit(priv, CSR_RESET,
639                           CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY,
640                           CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY, 25);
641
642         udelay(10);
643
644         rc = iwl_grab_restricted_access(priv);
645         if (!rc) {
646                 iwl_write_prph(priv, APMG_CLK_EN_REG,
647                                          APMG_CLK_VAL_DMA_CLK_RQT |
648                                          APMG_CLK_VAL_BSM_CLK_RQT);
649
650                 udelay(10);
651
652                 iwl_set_bits_prph(priv, APMG_PCIDEV_STT_REG,
653                                 APMG_PCIDEV_STT_VAL_L1_ACT_DIS);
654
655                 iwl_release_restricted_access(priv);
656         }
657
658         clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
659         wake_up_interruptible(&priv->wait_command_queue);
660
661         spin_unlock_irqrestore(&priv->lock, flags);
662
663         return rc;
664
665 }
666
667 #define REG_RECALIB_PERIOD (60)
668
669 /**
670  * iwl4965_bg_statistics_periodic - Timer callback to queue statistics
671  *
672  * This callback is provided in order to queue the statistics_work
673  * in work_queue context (v. softirq)
674  *
675  * This timer function is continually reset to execute within
676  * REG_RECALIB_PERIOD seconds since the last STATISTICS_NOTIFICATION
677  * was received.  We need to ensure we receive the statistics in order
678  * to update the temperature used for calibrating the TXPOWER.  However,
679  * we can't send the statistics command from softirq context (which
680  * is the context which timers run at) so we have to queue off the
681  * statistics_work to actually send the command to the hardware.
682  */
683 static void iwl4965_bg_statistics_periodic(unsigned long data)
684 {
685         struct iwl_priv *priv = (struct iwl_priv *)data;
686
687         queue_work(priv->workqueue, &priv->statistics_work);
688 }
689
690 /**
691  * iwl4965_bg_statistics_work - Send the statistics request to the hardware.
692  *
693  * This is queued by iwl_bg_statistics_periodic.
694  */
695 static void iwl4965_bg_statistics_work(struct work_struct *work)
696 {
697         struct iwl_priv *priv = container_of(work, struct iwl_priv,
698                                              statistics_work);
699
700         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
701                 return;
702
703         mutex_lock(&priv->mutex);
704         iwl_send_statistics_request(priv);
705         mutex_unlock(&priv->mutex);
706 }
707
708 #define CT_LIMIT_CONST          259
709 #define TM_CT_KILL_THRESHOLD    110
710
711 void iwl4965_rf_kill_ct_config(struct iwl_priv *priv)
712 {
713         struct iwl_ct_kill_config cmd;
714         u32 R1, R2, R3;
715         u32 temp_th;
716         u32 crit_temperature;
717         unsigned long flags;
718         int rc = 0;
719
720         spin_lock_irqsave(&priv->lock, flags);
721         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR,
722                     CSR_UCODE_DRV_GP1_REG_BIT_CT_KILL_EXIT);
723         spin_unlock_irqrestore(&priv->lock, flags);
724
725         if (priv->statistics.flag & STATISTICS_REPLY_FLG_FAT_MODE_MSK) {
726                 R1 = (s32)le32_to_cpu(priv->card_alive_init.therm_r1[1]);
727                 R2 = (s32)le32_to_cpu(priv->card_alive_init.therm_r2[1]);
728                 R3 = (s32)le32_to_cpu(priv->card_alive_init.therm_r3[1]);
729         } else {
730                 R1 = (s32)le32_to_cpu(priv->card_alive_init.therm_r1[0]);
731                 R2 = (s32)le32_to_cpu(priv->card_alive_init.therm_r2[0]);
732                 R3 = (s32)le32_to_cpu(priv->card_alive_init.therm_r3[0]);
733         }
734
735         temp_th = CELSIUS_TO_KELVIN(TM_CT_KILL_THRESHOLD);
736
737         crit_temperature = ((temp_th * (R3-R1))/CT_LIMIT_CONST) + R2;
738         cmd.critical_temperature_R =  cpu_to_le32(crit_temperature);
739         rc = iwl_send_cmd_pdu(priv,
740                               REPLY_CT_KILL_CONFIG_CMD, sizeof(cmd), &cmd);
741         if (rc)
742                 IWL_ERROR("REPLY_CT_KILL_CONFIG_CMD failed\n");
743         else
744                 IWL_DEBUG_INFO("REPLY_CT_KILL_CONFIG_CMD succeeded\n");
745 }
746
747 #ifdef CONFIG_IWLWIFI_SENSITIVITY
748
749 /* "false alarms" are signals that our DSP tries to lock onto,
750  *   but then determines that they are either noise, or transmissions
751  *   from a distant wireless network (also "noise", really) that get
752  *   "stepped on" by stronger transmissions within our own network.
753  * This algorithm attempts to set a sensitivity level that is high
754  *   enough to receive all of our own network traffic, but not so
755  *   high that our DSP gets too busy trying to lock onto non-network
756  *   activity/noise. */
757 static int iwl4965_sens_energy_cck(struct iwl_priv *priv,
758                                    u32 norm_fa,
759                                    u32 rx_enable_time,
760                                    struct statistics_general_data *rx_info)
761 {
762         u32 max_nrg_cck = 0;
763         int i = 0;
764         u8 max_silence_rssi = 0;
765         u32 silence_ref = 0;
766         u8 silence_rssi_a = 0;
767         u8 silence_rssi_b = 0;
768         u8 silence_rssi_c = 0;
769         u32 val;
770
771         /* "false_alarms" values below are cross-multiplications to assess the
772          *   numbers of false alarms within the measured period of actual Rx
773          *   (Rx is off when we're txing), vs the min/max expected false alarms
774          *   (some should be expected if rx is sensitive enough) in a
775          *   hypothetical listening period of 200 time units (TU), 204.8 msec:
776          *
777          * MIN_FA/fixed-time < false_alarms/actual-rx-time < MAX_FA/beacon-time
778          *
779          * */
780         u32 false_alarms = norm_fa * 200 * 1024;
781         u32 max_false_alarms = MAX_FA_CCK * rx_enable_time;
782         u32 min_false_alarms = MIN_FA_CCK * rx_enable_time;
783         struct iwl_sensitivity_data *data = NULL;
784
785         data = &(priv->sensitivity_data);
786
787         data->nrg_auto_corr_silence_diff = 0;
788
789         /* Find max silence rssi among all 3 receivers.
790          * This is background noise, which may include transmissions from other
791          *    networks, measured during silence before our network's beacon */
792         silence_rssi_a = (u8)((rx_info->beacon_silence_rssi_a &
793                             ALL_BAND_FILTER)>>8);
794         silence_rssi_b = (u8)((rx_info->beacon_silence_rssi_b &
795                             ALL_BAND_FILTER)>>8);
796         silence_rssi_c = (u8)((rx_info->beacon_silence_rssi_c &
797                             ALL_BAND_FILTER)>>8);
798
799         val = max(silence_rssi_b, silence_rssi_c);
800         max_silence_rssi = max(silence_rssi_a, (u8) val);
801
802         /* Store silence rssi in 20-beacon history table */
803         data->nrg_silence_rssi[data->nrg_silence_idx] = max_silence_rssi;
804         data->nrg_silence_idx++;
805         if (data->nrg_silence_idx >= NRG_NUM_PREV_STAT_L)
806                 data->nrg_silence_idx = 0;
807
808         /* Find max silence rssi across 20 beacon history */
809         for (i = 0; i < NRG_NUM_PREV_STAT_L; i++) {
810                 val = data->nrg_silence_rssi[i];
811                 silence_ref = max(silence_ref, val);
812         }
813         IWL_DEBUG_CALIB("silence a %u, b %u, c %u, 20-bcn max %u\n",
814                         silence_rssi_a, silence_rssi_b, silence_rssi_c,
815                         silence_ref);
816
817         /* Find max rx energy (min value!) among all 3 receivers,
818          *   measured during beacon frame.
819          * Save it in 10-beacon history table. */
820         i = data->nrg_energy_idx;
821         val = min(rx_info->beacon_energy_b, rx_info->beacon_energy_c);
822         data->nrg_value[i] = min(rx_info->beacon_energy_a, val);
823
824         data->nrg_energy_idx++;
825         if (data->nrg_energy_idx >= 10)
826                 data->nrg_energy_idx = 0;
827
828         /* Find min rx energy (max value) across 10 beacon history.
829          * This is the minimum signal level that we want to receive well.
830          * Add backoff (margin so we don't miss slightly lower energy frames).
831          * This establishes an upper bound (min value) for energy threshold. */
832         max_nrg_cck = data->nrg_value[0];
833         for (i = 1; i < 10; i++)
834                 max_nrg_cck = (u32) max(max_nrg_cck, (data->nrg_value[i]));
835         max_nrg_cck += 6;
836
837         IWL_DEBUG_CALIB("rx energy a %u, b %u, c %u, 10-bcn max/min %u\n",
838                         rx_info->beacon_energy_a, rx_info->beacon_energy_b,
839                         rx_info->beacon_energy_c, max_nrg_cck - 6);
840
841         /* Count number of consecutive beacons with fewer-than-desired
842          *   false alarms. */
843         if (false_alarms < min_false_alarms)
844                 data->num_in_cck_no_fa++;
845         else
846                 data->num_in_cck_no_fa = 0;
847         IWL_DEBUG_CALIB("consecutive bcns with few false alarms = %u\n",
848                         data->num_in_cck_no_fa);
849
850         /* If we got too many false alarms this time, reduce sensitivity */
851         if (false_alarms > max_false_alarms) {
852                 IWL_DEBUG_CALIB("norm FA %u > max FA %u\n",
853                              false_alarms, max_false_alarms);
854                 IWL_DEBUG_CALIB("... reducing sensitivity\n");
855                 data->nrg_curr_state = IWL_FA_TOO_MANY;
856
857                 if (data->auto_corr_cck > AUTO_CORR_MAX_TH_CCK) {
858                         /* Store for "fewer than desired" on later beacon */
859                         data->nrg_silence_ref = silence_ref;
860
861                         /* increase energy threshold (reduce nrg value)
862                          *   to decrease sensitivity */
863                         if (data->nrg_th_cck > (NRG_MAX_CCK + NRG_STEP_CCK))
864                                 data->nrg_th_cck = data->nrg_th_cck
865                                                          - NRG_STEP_CCK;
866                 }
867
868                 /* increase auto_corr values to decrease sensitivity */
869                 if (data->auto_corr_cck < AUTO_CORR_MAX_TH_CCK)
870                         data->auto_corr_cck = AUTO_CORR_MAX_TH_CCK + 1;
871                 else {
872                         val = data->auto_corr_cck + AUTO_CORR_STEP_CCK;
873                         data->auto_corr_cck = min((u32)AUTO_CORR_MAX_CCK, val);
874                 }
875                 val = data->auto_corr_cck_mrc + AUTO_CORR_STEP_CCK;
876                 data->auto_corr_cck_mrc = min((u32)AUTO_CORR_MAX_CCK_MRC, val);
877
878         /* Else if we got fewer than desired, increase sensitivity */
879         } else if (false_alarms < min_false_alarms) {
880                 data->nrg_curr_state = IWL_FA_TOO_FEW;
881
882                 /* Compare silence level with silence level for most recent
883                  *   healthy number or too many false alarms */
884                 data->nrg_auto_corr_silence_diff = (s32)data->nrg_silence_ref -
885                                                    (s32)silence_ref;
886
887                 IWL_DEBUG_CALIB("norm FA %u < min FA %u, silence diff %d\n",
888                          false_alarms, min_false_alarms,
889                          data->nrg_auto_corr_silence_diff);
890
891                 /* Increase value to increase sensitivity, but only if:
892                  * 1a) previous beacon did *not* have *too many* false alarms
893                  * 1b) AND there's a significant difference in Rx levels
894                  *      from a previous beacon with too many, or healthy # FAs
895                  * OR 2) We've seen a lot of beacons (100) with too few
896                  *       false alarms */
897                 if ((data->nrg_prev_state != IWL_FA_TOO_MANY) &&
898                         ((data->nrg_auto_corr_silence_diff > NRG_DIFF) ||
899                         (data->num_in_cck_no_fa > MAX_NUMBER_CCK_NO_FA))) {
900
901                         IWL_DEBUG_CALIB("... increasing sensitivity\n");
902                         /* Increase nrg value to increase sensitivity */
903                         val = data->nrg_th_cck + NRG_STEP_CCK;
904                         data->nrg_th_cck = min((u32)NRG_MIN_CCK, val);
905
906                         /* Decrease auto_corr values to increase sensitivity */
907                         val = data->auto_corr_cck - AUTO_CORR_STEP_CCK;
908                         data->auto_corr_cck = max((u32)AUTO_CORR_MIN_CCK, val);
909
910                         val = data->auto_corr_cck_mrc - AUTO_CORR_STEP_CCK;
911                         data->auto_corr_cck_mrc =
912                                          max((u32)AUTO_CORR_MIN_CCK_MRC, val);
913
914                 } else
915                         IWL_DEBUG_CALIB("... but not changing sensitivity\n");
916
917         /* Else we got a healthy number of false alarms, keep status quo */
918         } else {
919                 IWL_DEBUG_CALIB(" FA in safe zone\n");
920                 data->nrg_curr_state = IWL_FA_GOOD_RANGE;
921
922                 /* Store for use in "fewer than desired" with later beacon */
923                 data->nrg_silence_ref = silence_ref;
924
925                 /* If previous beacon had too many false alarms,
926                  *   give it some extra margin by reducing sensitivity again
927                  *   (but don't go below measured energy of desired Rx) */
928                 if (IWL_FA_TOO_MANY == data->nrg_prev_state) {
929                         IWL_DEBUG_CALIB("... increasing margin\n");
930                         data->nrg_th_cck -= NRG_MARGIN;
931                 }
932         }
933
934         /* Make sure the energy threshold does not go above the measured
935          * energy of the desired Rx signals (reduced by backoff margin),
936          * or else we might start missing Rx frames.
937          * Lower value is higher energy, so we use max()!
938          */
939         data->nrg_th_cck = max(max_nrg_cck, data->nrg_th_cck);
940         IWL_DEBUG_CALIB("new nrg_th_cck %u\n", data->nrg_th_cck);
941
942         data->nrg_prev_state = data->nrg_curr_state;
943
944         return 0;
945 }
946
947
948 static int iwl4965_sens_auto_corr_ofdm(struct iwl_priv *priv,
949                                        u32 norm_fa,
950                                        u32 rx_enable_time)
951 {
952         u32 val;
953         u32 false_alarms = norm_fa * 200 * 1024;
954         u32 max_false_alarms = MAX_FA_OFDM * rx_enable_time;
955         u32 min_false_alarms = MIN_FA_OFDM * rx_enable_time;
956         struct iwl_sensitivity_data *data = NULL;
957
958         data = &(priv->sensitivity_data);
959
960         /* If we got too many false alarms this time, reduce sensitivity */
961         if (false_alarms > max_false_alarms) {
962
963                 IWL_DEBUG_CALIB("norm FA %u > max FA %u)\n",
964                              false_alarms, max_false_alarms);
965
966                 val = data->auto_corr_ofdm + AUTO_CORR_STEP_OFDM;
967                 data->auto_corr_ofdm =
968                                 min((u32)AUTO_CORR_MAX_OFDM, val);
969
970                 val = data->auto_corr_ofdm_mrc + AUTO_CORR_STEP_OFDM;
971                 data->auto_corr_ofdm_mrc =
972                                 min((u32)AUTO_CORR_MAX_OFDM_MRC, val);
973
974                 val = data->auto_corr_ofdm_x1 + AUTO_CORR_STEP_OFDM;
975                 data->auto_corr_ofdm_x1 =
976                                 min((u32)AUTO_CORR_MAX_OFDM_X1, val);
977
978                 val = data->auto_corr_ofdm_mrc_x1 + AUTO_CORR_STEP_OFDM;
979                 data->auto_corr_ofdm_mrc_x1 =
980                                 min((u32)AUTO_CORR_MAX_OFDM_MRC_X1, val);
981         }
982
983         /* Else if we got fewer than desired, increase sensitivity */
984         else if (false_alarms < min_false_alarms) {
985
986                 IWL_DEBUG_CALIB("norm FA %u < min FA %u\n",
987                              false_alarms, min_false_alarms);
988
989                 val = data->auto_corr_ofdm - AUTO_CORR_STEP_OFDM;
990                 data->auto_corr_ofdm =
991                                 max((u32)AUTO_CORR_MIN_OFDM, val);
992
993                 val = data->auto_corr_ofdm_mrc - AUTO_CORR_STEP_OFDM;
994                 data->auto_corr_ofdm_mrc =
995                                 max((u32)AUTO_CORR_MIN_OFDM_MRC, val);
996
997                 val = data->auto_corr_ofdm_x1 - AUTO_CORR_STEP_OFDM;
998                 data->auto_corr_ofdm_x1 =
999                                 max((u32)AUTO_CORR_MIN_OFDM_X1, val);
1000
1001                 val = data->auto_corr_ofdm_mrc_x1 - AUTO_CORR_STEP_OFDM;
1002                 data->auto_corr_ofdm_mrc_x1 =
1003                                 max((u32)AUTO_CORR_MIN_OFDM_MRC_X1, val);
1004         }
1005
1006         else
1007                 IWL_DEBUG_CALIB("min FA %u < norm FA %u < max FA %u OK\n",
1008                          min_false_alarms, false_alarms, max_false_alarms);
1009
1010         return 0;
1011 }
1012
1013 static int iwl_sensitivity_callback(struct iwl_priv *priv,
1014                                     struct iwl_cmd *cmd, struct sk_buff *skb)
1015 {
1016         /* We didn't cache the SKB; let the caller free it */
1017         return 1;
1018 }
1019
1020 /* Prepare a SENSITIVITY_CMD, send to uCode if values have changed */
1021 static int iwl4965_sensitivity_write(struct iwl_priv *priv, u8 flags)
1022 {
1023         int rc = 0;
1024         struct iwl_sensitivity_cmd cmd ;
1025         struct iwl_sensitivity_data *data = NULL;
1026         struct iwl_host_cmd cmd_out = {
1027                 .id = SENSITIVITY_CMD,
1028                 .len = sizeof(struct iwl_sensitivity_cmd),
1029                 .meta.flags = flags,
1030                 .data = &cmd,
1031         };
1032
1033         data = &(priv->sensitivity_data);
1034
1035         memset(&cmd, 0, sizeof(cmd));
1036
1037         cmd.table[HD_AUTO_CORR32_X4_TH_ADD_MIN_INDEX] =
1038                                 cpu_to_le16((u16)data->auto_corr_ofdm);
1039         cmd.table[HD_AUTO_CORR32_X4_TH_ADD_MIN_MRC_INDEX] =
1040                                 cpu_to_le16((u16)data->auto_corr_ofdm_mrc);
1041         cmd.table[HD_AUTO_CORR32_X1_TH_ADD_MIN_INDEX] =
1042                                 cpu_to_le16((u16)data->auto_corr_ofdm_x1);
1043         cmd.table[HD_AUTO_CORR32_X1_TH_ADD_MIN_MRC_INDEX] =
1044                                 cpu_to_le16((u16)data->auto_corr_ofdm_mrc_x1);
1045
1046         cmd.table[HD_AUTO_CORR40_X4_TH_ADD_MIN_INDEX] =
1047                                 cpu_to_le16((u16)data->auto_corr_cck);
1048         cmd.table[HD_AUTO_CORR40_X4_TH_ADD_MIN_MRC_INDEX] =
1049                                 cpu_to_le16((u16)data->auto_corr_cck_mrc);
1050
1051         cmd.table[HD_MIN_ENERGY_CCK_DET_INDEX] =
1052                                 cpu_to_le16((u16)data->nrg_th_cck);
1053         cmd.table[HD_MIN_ENERGY_OFDM_DET_INDEX] =
1054                                 cpu_to_le16((u16)data->nrg_th_ofdm);
1055
1056         cmd.table[HD_BARKER_CORR_TH_ADD_MIN_INDEX] =
1057                                 __constant_cpu_to_le16(190);
1058         cmd.table[HD_BARKER_CORR_TH_ADD_MIN_MRC_INDEX] =
1059                                 __constant_cpu_to_le16(390);
1060         cmd.table[HD_OFDM_ENERGY_TH_IN_INDEX] =
1061                                 __constant_cpu_to_le16(62);
1062
1063         IWL_DEBUG_CALIB("ofdm: ac %u mrc %u x1 %u mrc_x1 %u thresh %u\n",
1064                         data->auto_corr_ofdm, data->auto_corr_ofdm_mrc,
1065                         data->auto_corr_ofdm_x1, data->auto_corr_ofdm_mrc_x1,
1066                         data->nrg_th_ofdm);
1067
1068         IWL_DEBUG_CALIB("cck: ac %u mrc %u thresh %u\n",
1069                         data->auto_corr_cck, data->auto_corr_cck_mrc,
1070                         data->nrg_th_cck);
1071
1072         cmd.control = SENSITIVITY_CMD_CONTROL_WORK_TABLE;
1073
1074         if (flags & CMD_ASYNC)
1075                 cmd_out.meta.u.callback = iwl_sensitivity_callback;
1076
1077         /* Don't send command to uCode if nothing has changed */
1078         if (!memcmp(&cmd.table[0], &(priv->sensitivity_tbl[0]),
1079                     sizeof(u16)*HD_TABLE_SIZE)) {
1080                 IWL_DEBUG_CALIB("No change in SENSITIVITY_CMD\n");
1081                 return 0;
1082         }
1083
1084         /* Copy table for comparison next time */
1085         memcpy(&(priv->sensitivity_tbl[0]), &(cmd.table[0]),
1086                sizeof(u16)*HD_TABLE_SIZE);
1087
1088         rc = iwl_send_cmd(priv, &cmd_out);
1089         if (!rc) {
1090                 IWL_DEBUG_CALIB("SENSITIVITY_CMD succeeded\n");
1091                 return rc;
1092         }
1093
1094         return 0;
1095 }
1096
1097 void iwl4965_init_sensitivity(struct iwl_priv *priv, u8 flags, u8 force)
1098 {
1099         int rc = 0;
1100         int i;
1101         struct iwl_sensitivity_data *data = NULL;
1102
1103         IWL_DEBUG_CALIB("Start iwl4965_init_sensitivity\n");
1104
1105         if (force)
1106                 memset(&(priv->sensitivity_tbl[0]), 0,
1107                         sizeof(u16)*HD_TABLE_SIZE);
1108
1109         /* Clear driver's sensitivity algo data */
1110         data = &(priv->sensitivity_data);
1111         memset(data, 0, sizeof(struct iwl_sensitivity_data));
1112
1113         data->num_in_cck_no_fa = 0;
1114         data->nrg_curr_state = IWL_FA_TOO_MANY;
1115         data->nrg_prev_state = IWL_FA_TOO_MANY;
1116         data->nrg_silence_ref = 0;
1117         data->nrg_silence_idx = 0;
1118         data->nrg_energy_idx = 0;
1119
1120         for (i = 0; i < 10; i++)
1121                 data->nrg_value[i] = 0;
1122
1123         for (i = 0; i < NRG_NUM_PREV_STAT_L; i++)
1124                 data->nrg_silence_rssi[i] = 0;
1125
1126         data->auto_corr_ofdm = 90;
1127         data->auto_corr_ofdm_mrc = 170;
1128         data->auto_corr_ofdm_x1  = 105;
1129         data->auto_corr_ofdm_mrc_x1 = 220;
1130         data->auto_corr_cck = AUTO_CORR_CCK_MIN_VAL_DEF;
1131         data->auto_corr_cck_mrc = 200;
1132         data->nrg_th_cck = 100;
1133         data->nrg_th_ofdm = 100;
1134
1135         data->last_bad_plcp_cnt_ofdm = 0;
1136         data->last_fa_cnt_ofdm = 0;
1137         data->last_bad_plcp_cnt_cck = 0;
1138         data->last_fa_cnt_cck = 0;
1139
1140         /* Clear prior Sensitivity command data to force send to uCode */
1141         if (force)
1142                 memset(&(priv->sensitivity_tbl[0]), 0,
1143                     sizeof(u16)*HD_TABLE_SIZE);
1144
1145         rc |= iwl4965_sensitivity_write(priv, flags);
1146         IWL_DEBUG_CALIB("<<return 0x%X\n", rc);
1147
1148         return;
1149 }
1150
1151
1152 /* Reset differential Rx gains in NIC to prepare for chain noise calibration.
1153  * Called after every association, but this runs only once!
1154  *  ... once chain noise is calibrated the first time, it's good forever.  */
1155 void iwl4965_chain_noise_reset(struct iwl_priv *priv)
1156 {
1157         struct iwl_chain_noise_data *data = NULL;
1158         int rc = 0;
1159
1160         data = &(priv->chain_noise_data);
1161         if ((data->state == IWL_CHAIN_NOISE_ALIVE) && iwl_is_associated(priv)) {
1162                 struct iwl_calibration_cmd cmd;
1163
1164                 memset(&cmd, 0, sizeof(cmd));
1165                 cmd.opCode = PHY_CALIBRATE_DIFF_GAIN_CMD;
1166                 cmd.diff_gain_a = 0;
1167                 cmd.diff_gain_b = 0;
1168                 cmd.diff_gain_c = 0;
1169                 rc = iwl_send_cmd_pdu(priv, REPLY_PHY_CALIBRATION_CMD,
1170                                  sizeof(cmd), &cmd);
1171                 msleep(4);
1172                 data->state = IWL_CHAIN_NOISE_ACCUMULATE;
1173                 IWL_DEBUG_CALIB("Run chain_noise_calibrate\n");
1174         }
1175         return;
1176 }
1177
1178 /*
1179  * Accumulate 20 beacons of signal and noise statistics for each of
1180  *   3 receivers/antennas/rx-chains, then figure out:
1181  * 1)  Which antennas are connected.
1182  * 2)  Differential rx gain settings to balance the 3 receivers.
1183  */
1184 static void iwl4965_noise_calibration(struct iwl_priv *priv,
1185                                       struct iwl_notif_statistics *stat_resp)
1186 {
1187         struct iwl_chain_noise_data *data = NULL;
1188         int rc = 0;
1189
1190         u32 chain_noise_a;
1191         u32 chain_noise_b;
1192         u32 chain_noise_c;
1193         u32 chain_sig_a;
1194         u32 chain_sig_b;
1195         u32 chain_sig_c;
1196         u32 average_sig[NUM_RX_CHAINS] = {INITIALIZATION_VALUE};
1197         u32 average_noise[NUM_RX_CHAINS] = {INITIALIZATION_VALUE};
1198         u32 max_average_sig;
1199         u16 max_average_sig_antenna_i;
1200         u32 min_average_noise = MIN_AVERAGE_NOISE_MAX_VALUE;
1201         u16 min_average_noise_antenna_i = INITIALIZATION_VALUE;
1202         u16 i = 0;
1203         u16 chan_num = INITIALIZATION_VALUE;
1204         u32 band = INITIALIZATION_VALUE;
1205         u32 active_chains = 0;
1206         unsigned long flags;
1207         struct statistics_rx_non_phy *rx_info = &(stat_resp->rx.general);
1208
1209         data = &(priv->chain_noise_data);
1210
1211         /* Accumulate just the first 20 beacons after the first association,
1212          *   then we're done forever. */
1213         if (data->state != IWL_CHAIN_NOISE_ACCUMULATE) {
1214                 if (data->state == IWL_CHAIN_NOISE_ALIVE)
1215                         IWL_DEBUG_CALIB("Wait for noise calib reset\n");
1216                 return;
1217         }
1218
1219         spin_lock_irqsave(&priv->lock, flags);
1220         if (rx_info->interference_data_flag != INTERFERENCE_DATA_AVAILABLE) {
1221                 IWL_DEBUG_CALIB(" << Interference data unavailable\n");
1222                 spin_unlock_irqrestore(&priv->lock, flags);
1223                 return;
1224         }
1225
1226         band = (priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK) ? 0 : 1;
1227         chan_num = le16_to_cpu(priv->staging_rxon.channel);
1228
1229         /* Make sure we accumulate data for just the associated channel
1230          *   (even if scanning). */
1231         if ((chan_num != (le32_to_cpu(stat_resp->flag) >> 16)) ||
1232             ((STATISTICS_REPLY_FLG_BAND_24G_MSK ==
1233              (stat_resp->flag & STATISTICS_REPLY_FLG_BAND_24G_MSK)) && band)) {
1234                 IWL_DEBUG_CALIB("Stats not from chan=%d, band=%d\n",
1235                                 chan_num, band);
1236                 spin_unlock_irqrestore(&priv->lock, flags);
1237                 return;
1238         }
1239
1240         /* Accumulate beacon statistics values across 20 beacons */
1241         chain_noise_a = le32_to_cpu(rx_info->beacon_silence_rssi_a) &
1242                                 IN_BAND_FILTER;
1243         chain_noise_b = le32_to_cpu(rx_info->beacon_silence_rssi_b) &
1244                                 IN_BAND_FILTER;
1245         chain_noise_c = le32_to_cpu(rx_info->beacon_silence_rssi_c) &
1246                                 IN_BAND_FILTER;
1247
1248         chain_sig_a = le32_to_cpu(rx_info->beacon_rssi_a) & IN_BAND_FILTER;
1249         chain_sig_b = le32_to_cpu(rx_info->beacon_rssi_b) & IN_BAND_FILTER;
1250         chain_sig_c = le32_to_cpu(rx_info->beacon_rssi_c) & IN_BAND_FILTER;
1251
1252         spin_unlock_irqrestore(&priv->lock, flags);
1253
1254         data->beacon_count++;
1255
1256         data->chain_noise_a = (chain_noise_a + data->chain_noise_a);
1257         data->chain_noise_b = (chain_noise_b + data->chain_noise_b);
1258         data->chain_noise_c = (chain_noise_c + data->chain_noise_c);
1259
1260         data->chain_signal_a = (chain_sig_a + data->chain_signal_a);
1261         data->chain_signal_b = (chain_sig_b + data->chain_signal_b);
1262         data->chain_signal_c = (chain_sig_c + data->chain_signal_c);
1263
1264         IWL_DEBUG_CALIB("chan=%d, band=%d, beacon=%d\n", chan_num, band,
1265                         data->beacon_count);
1266         IWL_DEBUG_CALIB("chain_sig: a %d b %d c %d\n",
1267                         chain_sig_a, chain_sig_b, chain_sig_c);
1268         IWL_DEBUG_CALIB("chain_noise: a %d b %d c %d\n",
1269                         chain_noise_a, chain_noise_b, chain_noise_c);
1270
1271         /* If this is the 20th beacon, determine:
1272          * 1)  Disconnected antennas (using signal strengths)
1273          * 2)  Differential gain (using silence noise) to balance receivers */
1274         if (data->beacon_count == CAL_NUM_OF_BEACONS) {
1275
1276                 /* Analyze signal for disconnected antenna */
1277                 average_sig[0] = (data->chain_signal_a) / CAL_NUM_OF_BEACONS;
1278                 average_sig[1] = (data->chain_signal_b) / CAL_NUM_OF_BEACONS;
1279                 average_sig[2] = (data->chain_signal_c) / CAL_NUM_OF_BEACONS;
1280
1281                 if (average_sig[0] >= average_sig[1]) {
1282                         max_average_sig = average_sig[0];
1283                         max_average_sig_antenna_i = 0;
1284                         active_chains = (1 << max_average_sig_antenna_i);
1285                 } else {
1286                         max_average_sig = average_sig[1];
1287                         max_average_sig_antenna_i = 1;
1288                         active_chains = (1 << max_average_sig_antenna_i);
1289                 }
1290
1291                 if (average_sig[2] >= max_average_sig) {
1292                         max_average_sig = average_sig[2];
1293                         max_average_sig_antenna_i = 2;
1294                         active_chains = (1 << max_average_sig_antenna_i);
1295                 }
1296
1297                 IWL_DEBUG_CALIB("average_sig: a %d b %d c %d\n",
1298                              average_sig[0], average_sig[1], average_sig[2]);
1299                 IWL_DEBUG_CALIB("max_average_sig = %d, antenna %d\n",
1300                              max_average_sig, max_average_sig_antenna_i);
1301
1302                 /* Compare signal strengths for all 3 receivers. */
1303                 for (i = 0; i < NUM_RX_CHAINS; i++) {
1304                         if (i != max_average_sig_antenna_i) {
1305                                 s32 rssi_delta = (max_average_sig -
1306                                                   average_sig[i]);
1307
1308                                 /* If signal is very weak, compared with
1309                                  * strongest, mark it as disconnected. */
1310                                 if (rssi_delta > MAXIMUM_ALLOWED_PATHLOSS)
1311                                         data->disconn_array[i] = 1;
1312                                 else
1313                                         active_chains |= (1 << i);
1314                         IWL_DEBUG_CALIB("i = %d  rssiDelta = %d  "
1315                                      "disconn_array[i] = %d\n",
1316                                      i, rssi_delta, data->disconn_array[i]);
1317                         }
1318                 }
1319
1320                 /*If both chains A & B are disconnected -
1321                  * connect B and leave A as is */
1322                 if (data->disconn_array[CHAIN_A] &&
1323                     data->disconn_array[CHAIN_B]) {
1324                         data->disconn_array[CHAIN_B] = 0;
1325                         active_chains |= (1 << CHAIN_B);
1326                         IWL_DEBUG_CALIB("both A & B chains are disconnected! "
1327                                      "W/A - declare B as connected\n");
1328                 }
1329
1330                 IWL_DEBUG_CALIB("active_chains (bitwise) = 0x%x\n",
1331                                 active_chains);
1332
1333                 /* Save for use within RXON, TX, SCAN commands, etc. */
1334                 priv->valid_antenna = active_chains;
1335
1336                 /* Analyze noise for rx balance */
1337                 average_noise[0] = ((data->chain_noise_a)/CAL_NUM_OF_BEACONS);
1338                 average_noise[1] = ((data->chain_noise_b)/CAL_NUM_OF_BEACONS);
1339                 average_noise[2] = ((data->chain_noise_c)/CAL_NUM_OF_BEACONS);
1340
1341                 for (i = 0; i < NUM_RX_CHAINS; i++) {
1342                         if (!(data->disconn_array[i]) &&
1343                            (average_noise[i] <= min_average_noise)) {
1344                                 /* This means that chain i is active and has
1345                                  * lower noise values so far: */
1346                                 min_average_noise = average_noise[i];
1347                                 min_average_noise_antenna_i = i;
1348                         }
1349                 }
1350
1351                 data->delta_gain_code[min_average_noise_antenna_i] = 0;
1352
1353                 IWL_DEBUG_CALIB("average_noise: a %d b %d c %d\n",
1354                                 average_noise[0], average_noise[1],
1355                                 average_noise[2]);
1356
1357                 IWL_DEBUG_CALIB("min_average_noise = %d, antenna %d\n",
1358                                 min_average_noise, min_average_noise_antenna_i);
1359
1360                 for (i = 0; i < NUM_RX_CHAINS; i++) {
1361                         s32 delta_g = 0;
1362
1363                         if (!(data->disconn_array[i]) &&
1364                             (data->delta_gain_code[i] ==
1365                              CHAIN_NOISE_DELTA_GAIN_INIT_VAL)) {
1366                                 delta_g = average_noise[i] - min_average_noise;
1367                                 data->delta_gain_code[i] = (u8)((delta_g *
1368                                                                     10) / 15);
1369                                 if (CHAIN_NOISE_MAX_DELTA_GAIN_CODE <
1370                                    data->delta_gain_code[i])
1371                                         data->delta_gain_code[i] =
1372                                           CHAIN_NOISE_MAX_DELTA_GAIN_CODE;
1373
1374                                 data->delta_gain_code[i] =
1375                                         (data->delta_gain_code[i] | (1 << 2));
1376                         } else
1377                                 data->delta_gain_code[i] = 0;
1378                 }
1379                 IWL_DEBUG_CALIB("delta_gain_codes: a %d b %d c %d\n",
1380                              data->delta_gain_code[0],
1381                              data->delta_gain_code[1],
1382                              data->delta_gain_code[2]);
1383
1384                 /* Differential gain gets sent to uCode only once */
1385                 if (!data->radio_write) {
1386                         struct iwl_calibration_cmd cmd;
1387                         data->radio_write = 1;
1388
1389                         memset(&cmd, 0, sizeof(cmd));
1390                         cmd.opCode = PHY_CALIBRATE_DIFF_GAIN_CMD;
1391                         cmd.diff_gain_a = data->delta_gain_code[0];
1392                         cmd.diff_gain_b = data->delta_gain_code[1];
1393                         cmd.diff_gain_c = data->delta_gain_code[2];
1394                         rc = iwl_send_cmd_pdu(priv, REPLY_PHY_CALIBRATION_CMD,
1395                                               sizeof(cmd), &cmd);
1396                         if (rc)
1397                                 IWL_DEBUG_CALIB("fail sending cmd "
1398                                              "REPLY_PHY_CALIBRATION_CMD \n");
1399
1400                         /* TODO we might want recalculate
1401                          * rx_chain in rxon cmd */
1402
1403                         /* Mark so we run this algo only once! */
1404                         data->state = IWL_CHAIN_NOISE_CALIBRATED;
1405                 }
1406                 data->chain_noise_a = 0;
1407                 data->chain_noise_b = 0;
1408                 data->chain_noise_c = 0;
1409                 data->chain_signal_a = 0;
1410                 data->chain_signal_b = 0;
1411                 data->chain_signal_c = 0;
1412                 data->beacon_count = 0;
1413         }
1414         return;
1415 }
1416
1417 static void iwl4965_sensitivity_calibration(struct iwl_priv *priv,
1418                                             struct iwl_notif_statistics *resp)
1419 {
1420         int rc = 0;
1421         u32 rx_enable_time;
1422         u32 fa_cck;
1423         u32 fa_ofdm;
1424         u32 bad_plcp_cck;
1425         u32 bad_plcp_ofdm;
1426         u32 norm_fa_ofdm;
1427         u32 norm_fa_cck;
1428         struct iwl_sensitivity_data *data = NULL;
1429         struct statistics_rx_non_phy *rx_info = &(resp->rx.general);
1430         struct statistics_rx *statistics = &(resp->rx);
1431         unsigned long flags;
1432         struct statistics_general_data statis;
1433
1434         data = &(priv->sensitivity_data);
1435
1436         if (!iwl_is_associated(priv)) {
1437                 IWL_DEBUG_CALIB("<< - not associated\n");
1438                 return;
1439         }
1440
1441         spin_lock_irqsave(&priv->lock, flags);
1442         if (rx_info->interference_data_flag != INTERFERENCE_DATA_AVAILABLE) {
1443                 IWL_DEBUG_CALIB("<< invalid data.\n");
1444                 spin_unlock_irqrestore(&priv->lock, flags);
1445                 return;
1446         }
1447
1448         /* Extract Statistics: */
1449         rx_enable_time = le32_to_cpu(rx_info->channel_load);
1450         fa_cck = le32_to_cpu(statistics->cck.false_alarm_cnt);
1451         fa_ofdm = le32_to_cpu(statistics->ofdm.false_alarm_cnt);
1452         bad_plcp_cck = le32_to_cpu(statistics->cck.plcp_err);
1453         bad_plcp_ofdm = le32_to_cpu(statistics->ofdm.plcp_err);
1454
1455         statis.beacon_silence_rssi_a =
1456                         le32_to_cpu(statistics->general.beacon_silence_rssi_a);
1457         statis.beacon_silence_rssi_b =
1458                         le32_to_cpu(statistics->general.beacon_silence_rssi_b);
1459         statis.beacon_silence_rssi_c =
1460                         le32_to_cpu(statistics->general.beacon_silence_rssi_c);
1461         statis.beacon_energy_a =
1462                         le32_to_cpu(statistics->general.beacon_energy_a);
1463         statis.beacon_energy_b =
1464                         le32_to_cpu(statistics->general.beacon_energy_b);
1465         statis.beacon_energy_c =
1466                         le32_to_cpu(statistics->general.beacon_energy_c);
1467
1468         spin_unlock_irqrestore(&priv->lock, flags);
1469
1470         IWL_DEBUG_CALIB("rx_enable_time = %u usecs\n", rx_enable_time);
1471
1472         if (!rx_enable_time) {
1473                 IWL_DEBUG_CALIB("<< RX Enable Time == 0! \n");
1474                 return;
1475         }
1476
1477         /* These statistics increase monotonically, and do not reset
1478          *   at each beacon.  Calculate difference from last value, or just
1479          *   use the new statistics value if it has reset or wrapped around. */
1480         if (data->last_bad_plcp_cnt_cck > bad_plcp_cck)
1481                 data->last_bad_plcp_cnt_cck = bad_plcp_cck;
1482         else {
1483                 bad_plcp_cck -= data->last_bad_plcp_cnt_cck;
1484                 data->last_bad_plcp_cnt_cck += bad_plcp_cck;
1485         }
1486
1487         if (data->last_bad_plcp_cnt_ofdm > bad_plcp_ofdm)
1488                 data->last_bad_plcp_cnt_ofdm = bad_plcp_ofdm;
1489         else {
1490                 bad_plcp_ofdm -= data->last_bad_plcp_cnt_ofdm;
1491                 data->last_bad_plcp_cnt_ofdm += bad_plcp_ofdm;
1492         }
1493
1494         if (data->last_fa_cnt_ofdm > fa_ofdm)
1495                 data->last_fa_cnt_ofdm = fa_ofdm;
1496         else {
1497                 fa_ofdm -= data->last_fa_cnt_ofdm;
1498                 data->last_fa_cnt_ofdm += fa_ofdm;
1499         }
1500
1501         if (data->last_fa_cnt_cck > fa_cck)
1502                 data->last_fa_cnt_cck = fa_cck;
1503         else {
1504                 fa_cck -= data->last_fa_cnt_cck;
1505                 data->last_fa_cnt_cck += fa_cck;
1506         }
1507
1508         /* Total aborted signal locks */
1509         norm_fa_ofdm = fa_ofdm + bad_plcp_ofdm;
1510         norm_fa_cck = fa_cck + bad_plcp_cck;
1511
1512         IWL_DEBUG_CALIB("cck: fa %u badp %u  ofdm: fa %u badp %u\n", fa_cck,
1513                         bad_plcp_cck, fa_ofdm, bad_plcp_ofdm);
1514
1515         iwl4965_sens_auto_corr_ofdm(priv, norm_fa_ofdm, rx_enable_time);
1516         iwl4965_sens_energy_cck(priv, norm_fa_cck, rx_enable_time, &statis);
1517         rc |= iwl4965_sensitivity_write(priv, CMD_ASYNC);
1518
1519         return;
1520 }
1521
1522 static void iwl4965_bg_sensitivity_work(struct work_struct *work)
1523 {
1524         struct iwl_priv *priv = container_of(work, struct iwl_priv,
1525                         sensitivity_work);
1526
1527         mutex_lock(&priv->mutex);
1528
1529         if (test_bit(STATUS_EXIT_PENDING, &priv->status) ||
1530             test_bit(STATUS_SCANNING, &priv->status)) {
1531                 mutex_unlock(&priv->mutex);
1532                 return;
1533         }
1534
1535         if (priv->start_calib) {
1536                 iwl4965_noise_calibration(priv, &priv->statistics);
1537
1538                 if (priv->sensitivity_data.state ==
1539                                         IWL_SENS_CALIB_NEED_REINIT) {
1540                         iwl4965_init_sensitivity(priv, CMD_ASYNC, 0);
1541                         priv->sensitivity_data.state = IWL_SENS_CALIB_ALLOWED;
1542                 } else
1543                         iwl4965_sensitivity_calibration(priv,
1544                                         &priv->statistics);
1545         }
1546
1547         mutex_unlock(&priv->mutex);
1548         return;
1549 }
1550 #endif /*CONFIG_IWLWIFI_SENSITIVITY*/
1551
1552 static void iwl4965_bg_txpower_work(struct work_struct *work)
1553 {
1554         struct iwl_priv *priv = container_of(work, struct iwl_priv,
1555                         txpower_work);
1556
1557         /* If a scan happened to start before we got here
1558          * then just return; the statistics notification will
1559          * kick off another scheduled work to compensate for
1560          * any temperature delta we missed here. */
1561         if (test_bit(STATUS_EXIT_PENDING, &priv->status) ||
1562             test_bit(STATUS_SCANNING, &priv->status))
1563                 return;
1564
1565         mutex_lock(&priv->mutex);
1566
1567         /* Regardless of if we are assocaited, we must reconfigure the
1568          * TX power since frames can be sent on non-radar channels while
1569          * not associated */
1570         iwl_hw_reg_send_txpower(priv);
1571
1572         /* Update last_temperature to keep is_calib_needed from running
1573          * when it isn't needed... */
1574         priv->last_temperature = priv->temperature;
1575
1576         mutex_unlock(&priv->mutex);
1577 }
1578
1579 /*
1580  * Acquire priv->lock before calling this function !
1581  */
1582 static void iwl4965_set_wr_ptrs(struct iwl_priv *priv, int txq_id, u32 index)
1583 {
1584         iwl_write_restricted(priv, HBUS_TARG_WRPTR,
1585                              (index & 0xff) | (txq_id << 8));
1586         iwl_write_prph(priv, SCD_QUEUE_RDPTR(txq_id), index);
1587 }
1588
1589 /*
1590  * Acquire priv->lock before calling this function !
1591  */
1592 static void iwl4965_tx_queue_set_status(struct iwl_priv *priv,
1593                                         struct iwl_tx_queue *txq,
1594                                         int tx_fifo_id, int scd_retry)
1595 {
1596         int txq_id = txq->q.id;
1597         int active = test_bit(txq_id, &priv->txq_ctx_active_msk)?1:0;
1598
1599         iwl_write_prph(priv, SCD_QUEUE_STATUS_BITS(txq_id),
1600                                  (active << SCD_QUEUE_STTS_REG_POS_ACTIVE) |
1601                                  (tx_fifo_id << SCD_QUEUE_STTS_REG_POS_TXF) |
1602                                  (scd_retry << SCD_QUEUE_STTS_REG_POS_WSL) |
1603                                  (scd_retry << SCD_QUEUE_STTS_REG_POS_SCD_ACK) |
1604                                  SCD_QUEUE_STTS_REG_MSK);
1605
1606         txq->sched_retry = scd_retry;
1607
1608         IWL_DEBUG_INFO("%s %s Queue %d on AC %d\n",
1609                        active ? "Activete" : "Deactivate",
1610                        scd_retry ? "BA" : "AC", txq_id, tx_fifo_id);
1611 }
1612
1613 static const u16 default_queue_to_tx_fifo[] = {
1614         IWL_TX_FIFO_AC3,
1615         IWL_TX_FIFO_AC2,
1616         IWL_TX_FIFO_AC1,
1617         IWL_TX_FIFO_AC0,
1618         IWL_CMD_FIFO_NUM,
1619         IWL_TX_FIFO_HCCA_1,
1620         IWL_TX_FIFO_HCCA_2
1621 };
1622
1623 static inline void iwl4965_txq_ctx_activate(struct iwl_priv *priv, int txq_id)
1624 {
1625         set_bit(txq_id, &priv->txq_ctx_active_msk);
1626 }
1627
1628 static inline void iwl4965_txq_ctx_deactivate(struct iwl_priv *priv, int txq_id)
1629 {
1630         clear_bit(txq_id, &priv->txq_ctx_active_msk);
1631 }
1632
1633 int iwl4965_alive_notify(struct iwl_priv *priv)
1634 {
1635         u32 a;
1636         int i = 0;
1637         unsigned long flags;
1638         int rc;
1639
1640         spin_lock_irqsave(&priv->lock, flags);
1641
1642 #ifdef CONFIG_IWLWIFI_SENSITIVITY
1643         memset(&(priv->sensitivity_data), 0,
1644                sizeof(struct iwl_sensitivity_data));
1645         memset(&(priv->chain_noise_data), 0,
1646                sizeof(struct iwl_chain_noise_data));
1647         for (i = 0; i < NUM_RX_CHAINS; i++)
1648                 priv->chain_noise_data.delta_gain_code[i] =
1649                                 CHAIN_NOISE_DELTA_GAIN_INIT_VAL;
1650 #endif /* CONFIG_IWLWIFI_SENSITIVITY*/
1651         rc = iwl_grab_restricted_access(priv);
1652         if (rc) {
1653                 spin_unlock_irqrestore(&priv->lock, flags);
1654                 return rc;
1655         }
1656
1657         priv->scd_base_addr = iwl_read_prph(priv, SCD_SRAM_BASE_ADDR);
1658         a = priv->scd_base_addr + SCD_CONTEXT_DATA_OFFSET;
1659         for (; a < priv->scd_base_addr + SCD_TX_STTS_BITMAP_OFFSET; a += 4)
1660                 iwl_write_restricted_mem(priv, a, 0);
1661         for (; a < priv->scd_base_addr + SCD_TRANSLATE_TBL_OFFSET; a += 4)
1662                 iwl_write_restricted_mem(priv, a, 0);
1663         for (; a < sizeof(u16) * priv->hw_setting.max_txq_num; a += 4)
1664                 iwl_write_restricted_mem(priv, a, 0);
1665
1666         iwl_write_prph(priv, SCD_DRAM_BASE_ADDR,
1667                 (priv->hw_setting.shared_phys +
1668                  offsetof(struct iwl_shared, queues_byte_cnt_tbls)) >> 10);
1669         iwl_write_prph(priv, SCD_QUEUECHAIN_SEL, 0);
1670
1671         /* initiate the queues */
1672         for (i = 0; i < priv->hw_setting.max_txq_num; i++) {
1673                 iwl_write_prph(priv, SCD_QUEUE_RDPTR(i), 0);
1674                 iwl_write_restricted(priv, HBUS_TARG_WRPTR, 0 | (i << 8));
1675                 iwl_write_restricted_mem(priv, priv->scd_base_addr +
1676                                         SCD_CONTEXT_QUEUE_OFFSET(i),
1677                                         (SCD_WIN_SIZE <<
1678                                         SCD_QUEUE_CTX_REG1_WIN_SIZE_POS) &
1679                                         SCD_QUEUE_CTX_REG1_WIN_SIZE_MSK);
1680                 iwl_write_restricted_mem(priv, priv->scd_base_addr +
1681                                         SCD_CONTEXT_QUEUE_OFFSET(i) +
1682                                         sizeof(u32),
1683                                         (SCD_FRAME_LIMIT <<
1684                                         SCD_QUEUE_CTX_REG2_FRAME_LIMIT_POS) &
1685                                         SCD_QUEUE_CTX_REG2_FRAME_LIMIT_MSK);
1686
1687         }
1688         iwl_write_prph(priv, SCD_INTERRUPT_MASK,
1689                                  (1 << priv->hw_setting.max_txq_num) - 1);
1690
1691         iwl_write_prph(priv, SCD_TXFACT,
1692                                  SCD_TXFACT_REG_TXFIFO_MASK(0, 7));
1693
1694         iwl4965_set_wr_ptrs(priv, IWL_CMD_QUEUE_NUM, 0);
1695         /* map qos queues to fifos one-to-one */
1696         for (i = 0; i < ARRAY_SIZE(default_queue_to_tx_fifo); i++) {
1697                 int ac = default_queue_to_tx_fifo[i];
1698                 iwl4965_txq_ctx_activate(priv, i);
1699                 iwl4965_tx_queue_set_status(priv, &priv->txq[i], ac, 0);
1700         }
1701
1702         iwl_release_restricted_access(priv);
1703         spin_unlock_irqrestore(&priv->lock, flags);
1704
1705         return 0;
1706 }
1707
1708 int iwl_hw_set_hw_setting(struct iwl_priv *priv)
1709 {
1710         priv->hw_setting.shared_virt =
1711             pci_alloc_consistent(priv->pci_dev,
1712                                  sizeof(struct iwl_shared),
1713                                  &priv->hw_setting.shared_phys);
1714
1715         if (!priv->hw_setting.shared_virt)
1716                 return -1;
1717
1718         memset(priv->hw_setting.shared_virt, 0, sizeof(struct iwl_shared));
1719
1720         priv->hw_setting.max_txq_num = iwl_param_queues_num;
1721         priv->hw_setting.ac_queue_count = AC_NUM;
1722         priv->hw_setting.tx_cmd_len = sizeof(struct iwl_tx_cmd);
1723         priv->hw_setting.max_rxq_size = RX_QUEUE_SIZE;
1724         priv->hw_setting.max_rxq_log = RX_QUEUE_SIZE_LOG;
1725
1726         priv->hw_setting.max_stations = IWL4965_STATION_COUNT;
1727         priv->hw_setting.bcast_sta_id = IWL4965_BROADCAST_ID;
1728         return 0;
1729 }
1730
1731 /**
1732  * iwl_hw_txq_ctx_free - Free TXQ Context
1733  *
1734  * Destroy all TX DMA queues and structures
1735  */
1736 void iwl_hw_txq_ctx_free(struct iwl_priv *priv)
1737 {
1738         int txq_id;
1739
1740         /* Tx queues */
1741         for (txq_id = 0; txq_id < priv->hw_setting.max_txq_num; txq_id++)
1742                 iwl_tx_queue_free(priv, &priv->txq[txq_id]);
1743
1744         iwl4965_kw_free(priv);
1745 }
1746
1747 /**
1748  * iwl_hw_txq_free_tfd -  Free one TFD, those at index [txq->q.read_ptr]
1749  *
1750  * Does NOT advance any indexes
1751  */
1752 int iwl_hw_txq_free_tfd(struct iwl_priv *priv, struct iwl_tx_queue *txq)
1753 {
1754         struct iwl_tfd_frame *bd_tmp = (struct iwl_tfd_frame *)&txq->bd[0];
1755         struct iwl_tfd_frame *bd = &bd_tmp[txq->q.read_ptr];
1756         struct pci_dev *dev = priv->pci_dev;
1757         int i;
1758         int counter = 0;
1759         int index, is_odd;
1760
1761         /* classify bd */
1762         if (txq->q.id == IWL_CMD_QUEUE_NUM)
1763                 /* nothing to cleanup after for host commands */
1764                 return 0;
1765
1766         /* sanity check */
1767         counter = IWL_GET_BITS(*bd, num_tbs);
1768         if (counter > MAX_NUM_OF_TBS) {
1769                 IWL_ERROR("Too many chunks: %i\n", counter);
1770                 /* @todo issue fatal error, it is quite serious situation */
1771                 return 0;
1772         }
1773
1774         /* unmap chunks if any */
1775
1776         for (i = 0; i < counter; i++) {
1777                 index = i / 2;
1778                 is_odd = i & 0x1;
1779
1780                 if (is_odd)
1781                         pci_unmap_single(
1782                                 dev,
1783                                 IWL_GET_BITS(bd->pa[index], tb2_addr_lo16) |
1784                                 (IWL_GET_BITS(bd->pa[index],
1785                                               tb2_addr_hi20) << 16),
1786                                 IWL_GET_BITS(bd->pa[index], tb2_len),
1787                                 PCI_DMA_TODEVICE);
1788
1789                 else if (i > 0)
1790                         pci_unmap_single(dev,
1791                                          le32_to_cpu(bd->pa[index].tb1_addr),
1792                                          IWL_GET_BITS(bd->pa[index], tb1_len),
1793                                          PCI_DMA_TODEVICE);
1794
1795                 if (txq->txb[txq->q.read_ptr].skb[i]) {
1796                         struct sk_buff *skb = txq->txb[txq->q.read_ptr].skb[i];
1797
1798                         dev_kfree_skb(skb);
1799                         txq->txb[txq->q.read_ptr].skb[i] = NULL;
1800                 }
1801         }
1802         return 0;
1803 }
1804
1805 int iwl_hw_reg_set_txpower(struct iwl_priv *priv, s8 power)
1806 {
1807         IWL_ERROR("TODO: Implement iwl_hw_reg_set_txpower!\n");
1808         return -EINVAL;
1809 }
1810
1811 static s32 iwl4965_math_div_round(s32 num, s32 denom, s32 *res)
1812 {
1813         s32 sign = 1;
1814
1815         if (num < 0) {
1816                 sign = -sign;
1817                 num = -num;
1818         }
1819         if (denom < 0) {
1820                 sign = -sign;
1821                 denom = -denom;
1822         }
1823         *res = 1;
1824         *res = ((num * 2 + denom) / (denom * 2)) * sign;
1825
1826         return 1;
1827 }
1828
1829 static s32 iwl4965_get_voltage_compensation(s32 eeprom_voltage,
1830                                             s32 current_voltage)
1831 {
1832         s32 comp = 0;
1833
1834         if ((TX_POWER_IWL_ILLEGAL_VOLTAGE == eeprom_voltage) ||
1835             (TX_POWER_IWL_ILLEGAL_VOLTAGE == current_voltage))
1836                 return 0;
1837
1838         iwl4965_math_div_round(current_voltage - eeprom_voltage,
1839                                TX_POWER_IWL_VOLTAGE_CODES_PER_03V, &comp);
1840
1841         if (current_voltage > eeprom_voltage)
1842                 comp *= 2;
1843         if ((comp < -2) || (comp > 2))
1844                 comp = 0;
1845
1846         return comp;
1847 }
1848
1849 static const struct iwl_channel_info *
1850 iwl4965_get_channel_txpower_info(struct iwl_priv *priv, u8 phymode, u16 channel)
1851 {
1852         const struct iwl_channel_info *ch_info;
1853
1854         ch_info = iwl_get_channel_info(priv, phymode, channel);
1855
1856         if (!is_channel_valid(ch_info))
1857                 return NULL;
1858
1859         return ch_info;
1860 }
1861
1862 static s32 iwl4965_get_tx_atten_grp(u16 channel)
1863 {
1864         if (channel >= CALIB_IWL_TX_ATTEN_GR5_FCH &&
1865             channel <= CALIB_IWL_TX_ATTEN_GR5_LCH)
1866                 return CALIB_CH_GROUP_5;
1867
1868         if (channel >= CALIB_IWL_TX_ATTEN_GR1_FCH &&
1869             channel <= CALIB_IWL_TX_ATTEN_GR1_LCH)
1870                 return CALIB_CH_GROUP_1;
1871
1872         if (channel >= CALIB_IWL_TX_ATTEN_GR2_FCH &&
1873             channel <= CALIB_IWL_TX_ATTEN_GR2_LCH)
1874                 return CALIB_CH_GROUP_2;
1875
1876         if (channel >= CALIB_IWL_TX_ATTEN_GR3_FCH &&
1877             channel <= CALIB_IWL_TX_ATTEN_GR3_LCH)
1878                 return CALIB_CH_GROUP_3;
1879
1880         if (channel >= CALIB_IWL_TX_ATTEN_GR4_FCH &&
1881             channel <= CALIB_IWL_TX_ATTEN_GR4_LCH)
1882                 return CALIB_CH_GROUP_4;
1883
1884         IWL_ERROR("Can't find txatten group for channel %d.\n", channel);
1885         return -1;
1886 }
1887
1888 static u32 iwl4965_get_sub_band(const struct iwl_priv *priv, u32 channel)
1889 {
1890         s32 b = -1;
1891
1892         for (b = 0; b < EEPROM_TX_POWER_BANDS; b++) {
1893                 if (priv->eeprom.calib_info.band_info[b].ch_from == 0)
1894                         continue;
1895
1896                 if ((channel >= priv->eeprom.calib_info.band_info[b].ch_from)
1897                     && (channel <= priv->eeprom.calib_info.band_info[b].ch_to))
1898                         break;
1899         }
1900
1901         return b;
1902 }
1903
1904 static s32 iwl4965_interpolate_value(s32 x, s32 x1, s32 y1, s32 x2, s32 y2)
1905 {
1906         s32 val;
1907
1908         if (x2 == x1)
1909                 return y1;
1910         else {
1911                 iwl4965_math_div_round((x2 - x) * (y1 - y2), (x2 - x1), &val);
1912                 return val + y2;
1913         }
1914 }
1915
1916 static int iwl4965_interpolate_chan(struct iwl_priv *priv, u32 channel,
1917                                     struct iwl_eeprom_calib_ch_info *chan_info)
1918 {
1919         s32 s = -1;
1920         u32 c;
1921         u32 m;
1922         const struct iwl_eeprom_calib_measure *m1;
1923         const struct iwl_eeprom_calib_measure *m2;
1924         struct iwl_eeprom_calib_measure *omeas;
1925         u32 ch_i1;
1926         u32 ch_i2;
1927
1928         s = iwl4965_get_sub_band(priv, channel);
1929         if (s >= EEPROM_TX_POWER_BANDS) {
1930                 IWL_ERROR("Tx Power can not find channel %d ", channel);
1931                 return -1;
1932         }
1933
1934         ch_i1 = priv->eeprom.calib_info.band_info[s].ch1.ch_num;
1935         ch_i2 = priv->eeprom.calib_info.band_info[s].ch2.ch_num;
1936         chan_info->ch_num = (u8) channel;
1937
1938         IWL_DEBUG_TXPOWER("channel %d subband %d factory cal ch %d & %d\n",
1939                           channel, s, ch_i1, ch_i2);
1940
1941         for (c = 0; c < EEPROM_TX_POWER_TX_CHAINS; c++) {
1942                 for (m = 0; m < EEPROM_TX_POWER_MEASUREMENTS; m++) {
1943                         m1 = &(priv->eeprom.calib_info.band_info[s].ch1.
1944                                measurements[c][m]);
1945                         m2 = &(priv->eeprom.calib_info.band_info[s].ch2.
1946                                measurements[c][m]);
1947                         omeas = &(chan_info->measurements[c][m]);
1948
1949                         omeas->actual_pow =
1950                             (u8) iwl4965_interpolate_value(channel, ch_i1,
1951                                                            m1->actual_pow,
1952                                                            ch_i2,
1953                                                            m2->actual_pow);
1954                         omeas->gain_idx =
1955                             (u8) iwl4965_interpolate_value(channel, ch_i1,
1956                                                            m1->gain_idx, ch_i2,
1957                                                            m2->gain_idx);
1958                         omeas->temperature =
1959                             (u8) iwl4965_interpolate_value(channel, ch_i1,
1960                                                            m1->temperature,
1961                                                            ch_i2,
1962                                                            m2->temperature);
1963                         omeas->pa_det =
1964                             (s8) iwl4965_interpolate_value(channel, ch_i1,
1965                                                            m1->pa_det, ch_i2,
1966                                                            m2->pa_det);
1967
1968                         IWL_DEBUG_TXPOWER
1969                             ("chain %d meas %d AP1=%d AP2=%d AP=%d\n", c, m,
1970                              m1->actual_pow, m2->actual_pow, omeas->actual_pow);
1971                         IWL_DEBUG_TXPOWER
1972                             ("chain %d meas %d NI1=%d NI2=%d NI=%d\n", c, m,
1973                              m1->gain_idx, m2->gain_idx, omeas->gain_idx);
1974                         IWL_DEBUG_TXPOWER
1975                             ("chain %d meas %d PA1=%d PA2=%d PA=%d\n", c, m,
1976                              m1->pa_det, m2->pa_det, omeas->pa_det);
1977                         IWL_DEBUG_TXPOWER
1978                             ("chain %d meas %d  T1=%d  T2=%d  T=%d\n", c, m,
1979                              m1->temperature, m2->temperature,
1980                              omeas->temperature);
1981                 }
1982         }
1983
1984         return 0;
1985 }
1986
1987 /* bit-rate-dependent table to prevent Tx distortion, in half-dB units,
1988  * for OFDM 6, 12, 18, 24, 36, 48, 54, 60 MBit, and CCK all rates. */
1989 static s32 back_off_table[] = {
1990         10, 10, 10, 10, 10, 15, 17, 20, /* OFDM SISO 20 MHz */
1991         10, 10, 10, 10, 10, 15, 17, 20, /* OFDM MIMO 20 MHz */
1992         10, 10, 10, 10, 10, 15, 17, 20, /* OFDM SISO 40 MHz */
1993         10, 10, 10, 10, 10, 15, 17, 20, /* OFDM MIMO 40 MHz */
1994         10                      /* CCK */
1995 };
1996
1997 /* Thermal compensation values for txpower for various frequency ranges ...
1998  *   ratios from 3:1 to 4.5:1 of degrees (Celsius) per half-dB gain adjust */
1999 static struct iwl_txpower_comp_entry {
2000         s32 degrees_per_05db_a;
2001         s32 degrees_per_05db_a_denom;
2002 } tx_power_cmp_tble[CALIB_CH_GROUP_MAX] = {
2003         {9, 2},                 /* group 0 5.2, ch  34-43 */
2004         {4, 1},                 /* group 1 5.2, ch  44-70 */
2005         {4, 1},                 /* group 2 5.2, ch  71-124 */
2006         {4, 1},                 /* group 3 5.2, ch 125-200 */
2007         {3, 1}                  /* group 4 2.4, ch   all */
2008 };
2009
2010 static s32 get_min_power_index(s32 rate_power_index, u32 band)
2011 {
2012         if (!band) {
2013                 if ((rate_power_index & 7) <= 4)
2014                         return MIN_TX_GAIN_INDEX_52GHZ_EXT;
2015         }
2016         return MIN_TX_GAIN_INDEX;
2017 }
2018
2019 struct gain_entry {
2020         u8 dsp;
2021         u8 radio;
2022 };
2023
2024 static const struct gain_entry gain_table[2][108] = {
2025         /* 5.2GHz power gain index table */
2026         {
2027          {123, 0x3F},           /* highest txpower */
2028          {117, 0x3F},
2029          {110, 0x3F},
2030          {104, 0x3F},
2031          {98, 0x3F},
2032          {110, 0x3E},
2033          {104, 0x3E},
2034          {98, 0x3E},
2035          {110, 0x3D},
2036          {104, 0x3D},
2037          {98, 0x3D},
2038          {110, 0x3C},
2039          {104, 0x3C},
2040          {98, 0x3C},
2041          {110, 0x3B},
2042          {104, 0x3B},
2043          {98, 0x3B},
2044          {110, 0x3A},
2045          {104, 0x3A},
2046          {98, 0x3A},
2047          {110, 0x39},
2048          {104, 0x39},
2049          {98, 0x39},
2050          {110, 0x38},
2051          {104, 0x38},
2052          {98, 0x38},
2053          {110, 0x37},
2054          {104, 0x37},
2055          {98, 0x37},
2056          {110, 0x36},
2057          {104, 0x36},
2058          {98, 0x36},
2059          {110, 0x35},
2060          {104, 0x35},
2061          {98, 0x35},
2062          {110, 0x34},
2063          {104, 0x34},
2064          {98, 0x34},
2065          {110, 0x33},
2066          {104, 0x33},
2067          {98, 0x33},
2068          {110, 0x32},
2069          {104, 0x32},
2070          {98, 0x32},
2071          {110, 0x31},
2072          {104, 0x31},
2073          {98, 0x31},
2074          {110, 0x30},
2075          {104, 0x30},
2076          {98, 0x30},
2077          {110, 0x25},
2078          {104, 0x25},
2079          {98, 0x25},
2080          {110, 0x24},
2081          {104, 0x24},
2082          {98, 0x24},
2083          {110, 0x23},
2084          {104, 0x23},
2085          {98, 0x23},
2086          {110, 0x22},
2087          {104, 0x18},
2088          {98, 0x18},
2089          {110, 0x17},
2090          {104, 0x17},
2091          {98, 0x17},
2092          {110, 0x16},
2093          {104, 0x16},
2094          {98, 0x16},
2095          {110, 0x15},
2096          {104, 0x15},
2097          {98, 0x15},
2098          {110, 0x14},
2099          {104, 0x14},
2100          {98, 0x14},
2101          {110, 0x13},
2102          {104, 0x13},
2103          {98, 0x13},
2104          {110, 0x12},
2105          {104, 0x08},
2106          {98, 0x08},
2107          {110, 0x07},
2108          {104, 0x07},
2109          {98, 0x07},
2110          {110, 0x06},
2111          {104, 0x06},
2112          {98, 0x06},
2113          {110, 0x05},
2114          {104, 0x05},
2115          {98, 0x05},
2116          {110, 0x04},
2117          {104, 0x04},
2118          {98, 0x04},
2119          {110, 0x03},
2120          {104, 0x03},
2121          {98, 0x03},
2122          {110, 0x02},
2123          {104, 0x02},
2124          {98, 0x02},
2125          {110, 0x01},
2126          {104, 0x01},
2127          {98, 0x01},
2128          {110, 0x00},
2129          {104, 0x00},
2130          {98, 0x00},
2131          {93, 0x00},
2132          {88, 0x00},
2133          {83, 0x00},
2134          {78, 0x00},
2135          },
2136         /* 2.4GHz power gain index table */
2137         {
2138          {110, 0x3f},           /* highest txpower */
2139          {104, 0x3f},
2140          {98, 0x3f},
2141          {110, 0x3e},
2142          {104, 0x3e},
2143          {98, 0x3e},
2144          {110, 0x3d},
2145          {104, 0x3d},
2146          {98, 0x3d},
2147          {110, 0x3c},
2148          {104, 0x3c},
2149          {98, 0x3c},
2150          {110, 0x3b},
2151          {104, 0x3b},
2152          {98, 0x3b},
2153          {110, 0x3a},
2154          {104, 0x3a},
2155          {98, 0x3a},
2156          {110, 0x39},
2157          {104, 0x39},
2158          {98, 0x39},
2159          {110, 0x38},
2160          {104, 0x38},
2161          {98, 0x38},
2162          {110, 0x37},
2163          {104, 0x37},
2164          {98, 0x37},
2165          {110, 0x36},
2166          {104, 0x36},
2167          {98, 0x36},
2168          {110, 0x35},
2169          {104, 0x35},
2170          {98, 0x35},
2171          {110, 0x34},
2172          {104, 0x34},
2173          {98, 0x34},
2174          {110, 0x33},
2175          {104, 0x33},
2176          {98, 0x33},
2177          {110, 0x32},
2178          {104, 0x32},
2179          {98, 0x32},
2180          {110, 0x31},
2181          {104, 0x31},
2182          {98, 0x31},
2183          {110, 0x30},
2184          {104, 0x30},
2185          {98, 0x30},
2186          {110, 0x6},
2187          {104, 0x6},
2188          {98, 0x6},
2189          {110, 0x5},
2190          {104, 0x5},
2191          {98, 0x5},
2192          {110, 0x4},
2193          {104, 0x4},
2194          {98, 0x4},
2195          {110, 0x3},
2196          {104, 0x3},
2197          {98, 0x3},
2198          {110, 0x2},
2199          {104, 0x2},
2200          {98, 0x2},
2201          {110, 0x1},
2202          {104, 0x1},
2203          {98, 0x1},
2204          {110, 0x0},
2205          {104, 0x0},
2206          {98, 0x0},
2207          {97, 0},
2208          {96, 0},
2209          {95, 0},
2210          {94, 0},
2211          {93, 0},
2212          {92, 0},
2213          {91, 0},
2214          {90, 0},
2215          {89, 0},
2216          {88, 0},
2217          {87, 0},
2218          {86, 0},
2219          {85, 0},
2220          {84, 0},
2221          {83, 0},
2222          {82, 0},
2223          {81, 0},
2224          {80, 0},
2225          {79, 0},
2226          {78, 0},
2227          {77, 0},
2228          {76, 0},
2229          {75, 0},
2230          {74, 0},
2231          {73, 0},
2232          {72, 0},
2233          {71, 0},
2234          {70, 0},
2235          {69, 0},
2236          {68, 0},
2237          {67, 0},
2238          {66, 0},
2239          {65, 0},
2240          {64, 0},
2241          {63, 0},
2242          {62, 0},
2243          {61, 0},
2244          {60, 0},
2245          {59, 0},
2246          }
2247 };
2248
2249 static int iwl4965_fill_txpower_tbl(struct iwl_priv *priv, u8 band, u16 channel,
2250                                     u8 is_fat, u8 ctrl_chan_high,
2251                                     struct iwl_tx_power_db *tx_power_tbl)
2252 {
2253         u8 saturation_power;
2254         s32 target_power;
2255         s32 user_target_power;
2256         s32 power_limit;
2257         s32 current_temp;
2258         s32 reg_limit;
2259         s32 current_regulatory;
2260         s32 txatten_grp = CALIB_CH_GROUP_MAX;
2261         int i;
2262         int c;
2263         const struct iwl_channel_info *ch_info = NULL;
2264         struct iwl_eeprom_calib_ch_info ch_eeprom_info;
2265         const struct iwl_eeprom_calib_measure *measurement;
2266         s16 voltage;
2267         s32 init_voltage;
2268         s32 voltage_compensation;
2269         s32 degrees_per_05db_num;
2270         s32 degrees_per_05db_denom;
2271         s32 factory_temp;
2272         s32 temperature_comp[2];
2273         s32 factory_gain_index[2];
2274         s32 factory_actual_pwr[2];
2275         s32 power_index;
2276
2277         /* Sanity check requested level (dBm) */
2278         if (priv->user_txpower_limit < IWL_TX_POWER_TARGET_POWER_MIN) {
2279                 IWL_WARNING("Requested user TXPOWER %d below limit.\n",
2280                             priv->user_txpower_limit);
2281                 return -EINVAL;
2282         }
2283         if (priv->user_txpower_limit > IWL_TX_POWER_TARGET_POWER_MAX) {
2284                 IWL_WARNING("Requested user TXPOWER %d above limit.\n",
2285                             priv->user_txpower_limit);
2286                 return -EINVAL;
2287         }
2288
2289         /* user_txpower_limit is in dBm, convert to half-dBm (half-dB units
2290          *   are used for indexing into txpower table) */
2291         user_target_power = 2 * priv->user_txpower_limit;
2292
2293         /* Get current (RXON) channel, band, width */
2294         ch_info =
2295                 iwl4965_get_channel_txpower_info(priv, priv->phymode, channel);
2296
2297         IWL_DEBUG_TXPOWER("chan %d band %d is_fat %d\n", channel, band,
2298                           is_fat);
2299
2300         if (!ch_info)
2301                 return -EINVAL;
2302
2303         /* get txatten group, used to select 1) thermal txpower adjustment
2304          *   and 2) mimo txpower balance between Tx chains. */
2305         txatten_grp = iwl4965_get_tx_atten_grp(channel);
2306         if (txatten_grp < 0)
2307                 return -EINVAL;
2308
2309         IWL_DEBUG_TXPOWER("channel %d belongs to txatten group %d\n",
2310                           channel, txatten_grp);
2311
2312         if (is_fat) {
2313                 if (ctrl_chan_high)
2314                         channel -= 2;
2315                 else
2316                         channel += 2;
2317         }
2318
2319         /* hardware txpower limits ...
2320          * saturation (clipping distortion) txpowers are in half-dBm */
2321         if (band)
2322                 saturation_power = priv->eeprom.calib_info.saturation_power24;
2323         else
2324                 saturation_power = priv->eeprom.calib_info.saturation_power52;
2325
2326         if (saturation_power < IWL_TX_POWER_SATURATION_MIN ||
2327             saturation_power > IWL_TX_POWER_SATURATION_MAX) {
2328                 if (band)
2329                         saturation_power = IWL_TX_POWER_DEFAULT_SATURATION_24;
2330                 else
2331                         saturation_power = IWL_TX_POWER_DEFAULT_SATURATION_52;
2332         }
2333
2334         /* regulatory txpower limits ... reg_limit values are in half-dBm,
2335          *   max_power_avg values are in dBm, convert * 2 */
2336         if (is_fat)
2337                 reg_limit = ch_info->fat_max_power_avg * 2;
2338         else
2339                 reg_limit = ch_info->max_power_avg * 2;
2340
2341         if ((reg_limit < IWL_TX_POWER_REGULATORY_MIN) ||
2342             (reg_limit > IWL_TX_POWER_REGULATORY_MAX)) {
2343                 if (band)
2344                         reg_limit = IWL_TX_POWER_DEFAULT_REGULATORY_24;
2345                 else
2346                         reg_limit = IWL_TX_POWER_DEFAULT_REGULATORY_52;
2347         }
2348
2349         /* Interpolate txpower calibration values for this channel,
2350          *   based on factory calibration tests on spaced channels. */
2351         iwl4965_interpolate_chan(priv, channel, &ch_eeprom_info);
2352
2353         /* calculate tx gain adjustment based on power supply voltage */
2354         voltage = priv->eeprom.calib_info.voltage;
2355         init_voltage = (s32)le32_to_cpu(priv->card_alive_init.voltage);
2356         voltage_compensation =
2357             iwl4965_get_voltage_compensation(voltage, init_voltage);
2358
2359         IWL_DEBUG_TXPOWER("curr volt %d eeprom volt %d volt comp %d\n",
2360                           init_voltage,
2361                           voltage, voltage_compensation);
2362
2363         /* get current temperature (Celsius) */
2364         current_temp = max(priv->temperature, IWL_TX_POWER_TEMPERATURE_MIN);
2365         current_temp = min(priv->temperature, IWL_TX_POWER_TEMPERATURE_MAX);
2366         current_temp = KELVIN_TO_CELSIUS(current_temp);
2367
2368         /* select thermal txpower adjustment params, based on channel group
2369          *   (same frequency group used for mimo txatten adjustment) */
2370         degrees_per_05db_num =
2371             tx_power_cmp_tble[txatten_grp].degrees_per_05db_a;
2372         degrees_per_05db_denom =
2373             tx_power_cmp_tble[txatten_grp].degrees_per_05db_a_denom;
2374
2375         /* get per-chain txpower values from factory measurements */
2376         for (c = 0; c < 2; c++) {
2377                 measurement = &ch_eeprom_info.measurements[c][1];
2378
2379                 /* txgain adjustment (in half-dB steps) based on difference
2380                  *   between factory and current temperature */
2381                 factory_temp = measurement->temperature;
2382                 iwl4965_math_div_round((current_temp - factory_temp) *
2383                                        degrees_per_05db_denom,
2384                                        degrees_per_05db_num,
2385                                        &temperature_comp[c]);
2386
2387                 factory_gain_index[c] = measurement->gain_idx;
2388                 factory_actual_pwr[c] = measurement->actual_pow;
2389
2390                 IWL_DEBUG_TXPOWER("chain = %d\n", c);
2391                 IWL_DEBUG_TXPOWER("fctry tmp %d, "
2392                                   "curr tmp %d, comp %d steps\n",
2393                                   factory_temp, current_temp,
2394                                   temperature_comp[c]);
2395
2396                 IWL_DEBUG_TXPOWER("fctry idx %d, fctry pwr %d\n",
2397                                   factory_gain_index[c],
2398                                   factory_actual_pwr[c]);
2399         }
2400
2401         /* for each of 33 bit-rates (including 1 for CCK) */
2402         for (i = 0; i < POWER_TABLE_NUM_ENTRIES; i++) {
2403                 u8 is_mimo_rate;
2404                 union iwl_tx_power_dual_stream tx_power;
2405
2406                 /* for mimo, reduce each chain's txpower by half
2407                  * (3dB, 6 steps), so total output power is regulatory
2408                  * compliant. */
2409                 if (i & 0x8) {
2410                         current_regulatory = reg_limit -
2411                             IWL_TX_POWER_MIMO_REGULATORY_COMPENSATION;
2412                         is_mimo_rate = 1;
2413                 } else {
2414                         current_regulatory = reg_limit;
2415                         is_mimo_rate = 0;
2416                 }
2417
2418                 /* find txpower limit, either hardware or regulatory */
2419                 power_limit = saturation_power - back_off_table[i];
2420                 if (power_limit > current_regulatory)
2421                         power_limit = current_regulatory;
2422
2423                 /* reduce user's txpower request if necessary
2424                  * for this rate on this channel */
2425                 target_power = user_target_power;
2426                 if (target_power > power_limit)
2427                         target_power = power_limit;
2428
2429                 IWL_DEBUG_TXPOWER("rate %d sat %d reg %d usr %d tgt %d\n",
2430                                   i, saturation_power - back_off_table[i],
2431                                   current_regulatory, user_target_power,
2432                                   target_power);
2433
2434                 /* for each of 2 Tx chains (radio transmitters) */
2435                 for (c = 0; c < 2; c++) {
2436                         s32 atten_value;
2437
2438                         if (is_mimo_rate)
2439                                 atten_value =
2440                                     (s32)le32_to_cpu(priv->card_alive_init.
2441                                     tx_atten[txatten_grp][c]);
2442                         else
2443                                 atten_value = 0;
2444
2445                         /* calculate index; higher index means lower txpower */
2446                         power_index = (u8) (factory_gain_index[c] -
2447                                             (target_power -
2448                                              factory_actual_pwr[c]) -
2449                                             temperature_comp[c] -
2450                                             voltage_compensation +
2451                                             atten_value);
2452
2453 /*                      IWL_DEBUG_TXPOWER("calculated txpower index %d\n",
2454                                                 power_index); */
2455
2456                         if (power_index < get_min_power_index(i, band))
2457                                 power_index = get_min_power_index(i, band);
2458
2459                         /* adjust 5 GHz index to support negative indexes */
2460                         if (!band)
2461                                 power_index += 9;
2462
2463                         /* CCK, rate 32, reduce txpower for CCK */
2464                         if (i == POWER_TABLE_CCK_ENTRY)
2465                                 power_index +=
2466                                     IWL_TX_POWER_CCK_COMPENSATION_C_STEP;
2467
2468                         /* stay within the table! */
2469                         if (power_index > 107) {
2470                                 IWL_WARNING("txpower index %d > 107\n",
2471                                             power_index);
2472                                 power_index = 107;
2473                         }
2474                         if (power_index < 0) {
2475                                 IWL_WARNING("txpower index %d < 0\n",
2476                                             power_index);
2477                                 power_index = 0;
2478                         }
2479
2480                         /* fill txpower command for this rate/chain */
2481                         tx_power.s.radio_tx_gain[c] =
2482                                 gain_table[band][power_index].radio;
2483                         tx_power.s.dsp_predis_atten[c] =
2484                                 gain_table[band][power_index].dsp;
2485
2486                         IWL_DEBUG_TXPOWER("chain %d mimo %d index %d "
2487                                           "gain 0x%02x dsp %d\n",
2488                                           c, atten_value, power_index,
2489                                         tx_power.s.radio_tx_gain[c],
2490                                         tx_power.s.dsp_predis_atten[c]);
2491                 }/* for each chain */
2492
2493                 tx_power_tbl->power_tbl[i].dw = cpu_to_le32(tx_power.dw);
2494
2495         }/* for each rate */
2496
2497         return 0;
2498 }
2499
2500 /**
2501  * iwl_hw_reg_send_txpower - Configure the TXPOWER level user limit
2502  *
2503  * Uses the active RXON for channel, band, and characteristics (fat, high)
2504  * The power limit is taken from priv->user_txpower_limit.
2505  */
2506 int iwl_hw_reg_send_txpower(struct iwl_priv *priv)
2507 {
2508         struct iwl_txpowertable_cmd cmd = { 0 };
2509         int rc = 0;
2510         u8 band = 0;
2511         u8 is_fat = 0;
2512         u8 ctrl_chan_high = 0;
2513
2514         if (test_bit(STATUS_SCANNING, &priv->status)) {
2515                 /* If this gets hit a lot, switch it to a BUG() and catch
2516                  * the stack trace to find out who is calling this during
2517                  * a scan. */
2518                 IWL_WARNING("TX Power requested while scanning!\n");
2519                 return -EAGAIN;
2520         }
2521
2522         band = ((priv->phymode == MODE_IEEE80211B) ||
2523                 (priv->phymode == MODE_IEEE80211G));
2524
2525         is_fat =  is_fat_channel(priv->active_rxon.flags);
2526
2527         if (is_fat &&
2528             (priv->active_rxon.flags & RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK))
2529                 ctrl_chan_high = 1;
2530
2531         cmd.band = band;
2532         cmd.channel = priv->active_rxon.channel;
2533
2534         rc = iwl4965_fill_txpower_tbl(priv, band,
2535                                 le16_to_cpu(priv->active_rxon.channel),
2536                                 is_fat, ctrl_chan_high, &cmd.tx_power);
2537         if (rc)
2538                 return rc;
2539
2540         rc = iwl_send_cmd_pdu(priv, REPLY_TX_PWR_TABLE_CMD, sizeof(cmd), &cmd);
2541         return rc;
2542 }
2543
2544 int iwl_hw_channel_switch(struct iwl_priv *priv, u16 channel)
2545 {
2546         int rc;
2547         u8 band = 0;
2548         u8 is_fat = 0;
2549         u8 ctrl_chan_high = 0;
2550         struct iwl_channel_switch_cmd cmd = { 0 };
2551         const struct iwl_channel_info *ch_info;
2552
2553         band = ((priv->phymode == MODE_IEEE80211B) ||
2554                 (priv->phymode == MODE_IEEE80211G));
2555
2556         ch_info = iwl_get_channel_info(priv, priv->phymode, channel);
2557
2558         is_fat = is_fat_channel(priv->staging_rxon.flags);
2559
2560         if (is_fat &&
2561             (priv->active_rxon.flags & RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK))
2562                 ctrl_chan_high = 1;
2563
2564         cmd.band = band;
2565         cmd.expect_beacon = 0;
2566         cmd.channel = cpu_to_le16(channel);
2567         cmd.rxon_flags = priv->active_rxon.flags;
2568         cmd.rxon_filter_flags = priv->active_rxon.filter_flags;
2569         cmd.switch_time = cpu_to_le32(priv->ucode_beacon_time);
2570         if (ch_info)
2571                 cmd.expect_beacon = is_channel_radar(ch_info);
2572         else
2573                 cmd.expect_beacon = 1;
2574
2575         rc = iwl4965_fill_txpower_tbl(priv, band, channel, is_fat,
2576                                       ctrl_chan_high, &cmd.tx_power);
2577         if (rc) {
2578                 IWL_DEBUG_11H("error:%d  fill txpower_tbl\n", rc);
2579                 return rc;
2580         }
2581
2582         rc = iwl_send_cmd_pdu(priv, REPLY_CHANNEL_SWITCH, sizeof(cmd), &cmd);
2583         return rc;
2584 }
2585
2586 #define RTS_HCCA_RETRY_LIMIT            3
2587 #define RTS_DFAULT_RETRY_LIMIT          60
2588
2589 void iwl_hw_build_tx_cmd_rate(struct iwl_priv *priv,
2590                               struct iwl_cmd *cmd,
2591                               struct ieee80211_tx_control *ctrl,
2592                               struct ieee80211_hdr *hdr, int sta_id,
2593                               int is_hcca)
2594 {
2595         u8 rate;
2596         u8 rts_retry_limit = 0;
2597         u8 data_retry_limit = 0;
2598         __le32 tx_flags;
2599         u16 fc = le16_to_cpu(hdr->frame_control);
2600
2601         tx_flags = cmd->cmd.tx.tx_flags;
2602
2603         rate = iwl_rates[ctrl->tx_rate].plcp;
2604
2605         rts_retry_limit = (is_hcca) ?
2606             RTS_HCCA_RETRY_LIMIT : RTS_DFAULT_RETRY_LIMIT;
2607
2608         if (ieee80211_is_probe_response(fc)) {
2609                 data_retry_limit = 3;
2610                 if (data_retry_limit < rts_retry_limit)
2611                         rts_retry_limit = data_retry_limit;
2612         } else
2613                 data_retry_limit = IWL_DEFAULT_TX_RETRY;
2614
2615         if (priv->data_retry_limit != -1)
2616                 data_retry_limit = priv->data_retry_limit;
2617
2618         if ((fc & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_MGMT) {
2619                 switch (fc & IEEE80211_FCTL_STYPE) {
2620                 case IEEE80211_STYPE_AUTH:
2621                 case IEEE80211_STYPE_DEAUTH:
2622                 case IEEE80211_STYPE_ASSOC_REQ:
2623                 case IEEE80211_STYPE_REASSOC_REQ:
2624                         if (tx_flags & TX_CMD_FLG_RTS_MSK) {
2625                                 tx_flags &= ~TX_CMD_FLG_RTS_MSK;
2626                                 tx_flags |= TX_CMD_FLG_CTS_MSK;
2627                         }
2628                         break;
2629                 default:
2630                         break;
2631                 }
2632         }
2633
2634         cmd->cmd.tx.rts_retry_limit = rts_retry_limit;
2635         cmd->cmd.tx.data_retry_limit = data_retry_limit;
2636         cmd->cmd.tx.rate_n_flags = iwl_hw_set_rate_n_flags(rate, 0);
2637         cmd->cmd.tx.tx_flags = tx_flags;
2638 }
2639
2640 int iwl_hw_get_rx_read(struct iwl_priv *priv)
2641 {
2642         struct iwl_shared *shared_data = priv->hw_setting.shared_virt;
2643
2644         return IWL_GET_BITS(*shared_data, rb_closed_stts_rb_num);
2645 }
2646
2647 int iwl_hw_get_temperature(struct iwl_priv *priv)
2648 {
2649         return priv->temperature;
2650 }
2651
2652 unsigned int iwl_hw_get_beacon_cmd(struct iwl_priv *priv,
2653                           struct iwl_frame *frame, u8 rate)
2654 {
2655         struct iwl_tx_beacon_cmd *tx_beacon_cmd;
2656         unsigned int frame_size;
2657
2658         tx_beacon_cmd = &frame->u.beacon;
2659         memset(tx_beacon_cmd, 0, sizeof(*tx_beacon_cmd));
2660
2661         tx_beacon_cmd->tx.sta_id = IWL4965_BROADCAST_ID;
2662         tx_beacon_cmd->tx.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
2663
2664         frame_size = iwl_fill_beacon_frame(priv,
2665                                 tx_beacon_cmd->frame,
2666                                 BROADCAST_ADDR,
2667                                 sizeof(frame->u) - sizeof(*tx_beacon_cmd));
2668
2669         BUG_ON(frame_size > MAX_MPDU_SIZE);
2670         tx_beacon_cmd->tx.len = cpu_to_le16((u16)frame_size);
2671
2672         if ((rate == IWL_RATE_1M_PLCP) || (rate >= IWL_RATE_2M_PLCP))
2673                 tx_beacon_cmd->tx.rate_n_flags =
2674                         iwl_hw_set_rate_n_flags(rate, RATE_MCS_CCK_MSK);
2675         else
2676                 tx_beacon_cmd->tx.rate_n_flags =
2677                         iwl_hw_set_rate_n_flags(rate, 0);
2678
2679         tx_beacon_cmd->tx.tx_flags = (TX_CMD_FLG_SEQ_CTL_MSK |
2680                                 TX_CMD_FLG_TSF_MSK | TX_CMD_FLG_STA_RATE_MSK);
2681         return (sizeof(*tx_beacon_cmd) + frame_size);
2682 }
2683
2684 int iwl_hw_tx_queue_init(struct iwl_priv *priv, struct iwl_tx_queue *txq)
2685 {
2686         int rc;
2687         unsigned long flags;
2688         int txq_id = txq->q.id;
2689
2690         spin_lock_irqsave(&priv->lock, flags);
2691         rc = iwl_grab_restricted_access(priv);
2692         if (rc) {
2693                 spin_unlock_irqrestore(&priv->lock, flags);
2694                 return rc;
2695         }
2696
2697         iwl_write_restricted(priv, FH_MEM_CBBC_QUEUE(txq_id),
2698                              txq->q.dma_addr >> 8);
2699         iwl_write_restricted(
2700                 priv, IWL_FH_TCSR_CHNL_TX_CONFIG_REG(txq_id),
2701                 IWL_FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE |
2702                 IWL_FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_ENABLE_VAL);
2703         iwl_release_restricted_access(priv);
2704         spin_unlock_irqrestore(&priv->lock, flags);
2705
2706         return 0;
2707 }
2708
2709 static inline u8 iwl4965_get_dma_hi_address(dma_addr_t addr)
2710 {
2711         return sizeof(addr) > sizeof(u32) ? (addr >> 16) >> 16 : 0;
2712 }
2713
2714 int iwl_hw_txq_attach_buf_to_tfd(struct iwl_priv *priv, void *ptr,
2715                                  dma_addr_t addr, u16 len)
2716 {
2717         int index, is_odd;
2718         struct iwl_tfd_frame *tfd = ptr;
2719         u32 num_tbs = IWL_GET_BITS(*tfd, num_tbs);
2720
2721         if ((num_tbs >= MAX_NUM_OF_TBS) || (num_tbs < 0)) {
2722                 IWL_ERROR("Error can not send more than %d chunks\n",
2723                           MAX_NUM_OF_TBS);
2724                 return -EINVAL;
2725         }
2726
2727         index = num_tbs / 2;
2728         is_odd = num_tbs & 0x1;
2729
2730         if (!is_odd) {
2731                 tfd->pa[index].tb1_addr = cpu_to_le32(addr);
2732                 IWL_SET_BITS(tfd->pa[index], tb1_addr_hi,
2733                              iwl4965_get_dma_hi_address(addr));
2734                 IWL_SET_BITS(tfd->pa[index], tb1_len, len);
2735         } else {
2736                 IWL_SET_BITS(tfd->pa[index], tb2_addr_lo16,
2737                              (u32) (addr & 0xffff));
2738                 IWL_SET_BITS(tfd->pa[index], tb2_addr_hi20, addr >> 16);
2739                 IWL_SET_BITS(tfd->pa[index], tb2_len, len);
2740         }
2741
2742         IWL_SET_BITS(*tfd, num_tbs, num_tbs + 1);
2743
2744         return 0;
2745 }
2746
2747 void iwl_hw_card_show_info(struct iwl_priv *priv)
2748 {
2749         u16 hw_version = priv->eeprom.board_revision_4965;
2750
2751         IWL_DEBUG_INFO("4965ABGN HW Version %u.%u.%u\n",
2752                        ((hw_version >> 8) & 0x0F),
2753                        ((hw_version >> 8) >> 4), (hw_version & 0x00FF));
2754
2755         IWL_DEBUG_INFO("4965ABGN PBA Number %.16s\n",
2756                        priv->eeprom.board_pba_number_4965);
2757 }
2758
2759 #define IWL_TX_CRC_SIZE         4
2760 #define IWL_TX_DELIMITER_SIZE   4
2761
2762 int iwl4965_tx_queue_update_wr_ptr(struct iwl_priv *priv,
2763                                    struct iwl_tx_queue *txq, u16 byte_cnt)
2764 {
2765         int len;
2766         int txq_id = txq->q.id;
2767         struct iwl_shared *shared_data = priv->hw_setting.shared_virt;
2768
2769         if (txq->need_update == 0)
2770                 return 0;
2771
2772         len = byte_cnt + IWL_TX_CRC_SIZE + IWL_TX_DELIMITER_SIZE;
2773
2774         IWL_SET_BITS16(shared_data->queues_byte_cnt_tbls[txq_id].
2775                        tfd_offset[txq->q.write_ptr], byte_cnt, len);
2776
2777         if (txq->q.write_ptr < IWL4965_MAX_WIN_SIZE)
2778                 IWL_SET_BITS16(shared_data->queues_byte_cnt_tbls[txq_id].
2779                         tfd_offset[IWL4965_QUEUE_SIZE + txq->q.write_ptr],
2780                         byte_cnt, len);
2781
2782         return 0;
2783 }
2784
2785 /* Set up Rx receiver/antenna/chain usage in "staging" RXON image.
2786  * This should not be used for scan command ... it puts data in wrong place.  */
2787 void iwl4965_set_rxon_chain(struct iwl_priv *priv)
2788 {
2789         u8 is_single = is_single_stream(priv);
2790         u8 idle_state, rx_state;
2791
2792         priv->staging_rxon.rx_chain = 0;
2793         rx_state = idle_state = 3;
2794
2795         /* Tell uCode which antennas are actually connected.
2796          * Before first association, we assume all antennas are connected.
2797          * Just after first association, iwl4965_noise_calibration()
2798          *    checks which antennas actually *are* connected. */
2799         priv->staging_rxon.rx_chain |=
2800             cpu_to_le16(priv->valid_antenna << RXON_RX_CHAIN_VALID_POS);
2801
2802         /* How many receivers should we use? */
2803         iwl4965_get_rx_chain_counter(priv, &idle_state, &rx_state);
2804         priv->staging_rxon.rx_chain |=
2805                 cpu_to_le16(rx_state << RXON_RX_CHAIN_MIMO_CNT_POS);
2806         priv->staging_rxon.rx_chain |=
2807                 cpu_to_le16(idle_state << RXON_RX_CHAIN_CNT_POS);
2808
2809         if (!is_single && (rx_state >= 2) &&
2810             !test_bit(STATUS_POWER_PMI, &priv->status))
2811                 priv->staging_rxon.rx_chain |= RXON_RX_CHAIN_MIMO_FORCE_MSK;
2812         else
2813                 priv->staging_rxon.rx_chain &= ~RXON_RX_CHAIN_MIMO_FORCE_MSK;
2814
2815         IWL_DEBUG_ASSOC("rx chain %X\n", priv->staging_rxon.rx_chain);
2816 }
2817
2818 #ifdef CONFIG_IWLWIFI_HT
2819 #ifdef CONFIG_IWLWIFI_HT_AGG
2820 /*
2821         get the traffic load value for tid
2822 */
2823 static u32 iwl4965_tl_get_load(struct iwl_priv *priv, u8 tid)
2824 {
2825         u32 load = 0;
2826         u32 current_time = jiffies_to_msecs(jiffies);
2827         u32 time_diff;
2828         s32 index;
2829         unsigned long flags;
2830         struct iwl_traffic_load *tid_ptr = NULL;
2831
2832         if (tid >= TID_MAX_LOAD_COUNT)
2833                 return 0;
2834
2835         tid_ptr = &(priv->lq_mngr.agg_ctrl.traffic_load[tid]);
2836
2837         current_time -= current_time % TID_ROUND_VALUE;
2838
2839         spin_lock_irqsave(&priv->lq_mngr.lock, flags);
2840         if (!(tid_ptr->queue_count))
2841                 goto out;
2842
2843         time_diff = TIME_WRAP_AROUND(tid_ptr->time_stamp, current_time);
2844         index = time_diff / TID_QUEUE_CELL_SPACING;
2845
2846         if (index >= TID_QUEUE_MAX_SIZE) {
2847                 u32 oldest_time = current_time - TID_MAX_TIME_DIFF;
2848
2849                 while (tid_ptr->queue_count &&
2850                        (tid_ptr->time_stamp < oldest_time)) {
2851                         tid_ptr->total -= tid_ptr->packet_count[tid_ptr->head];
2852                         tid_ptr->packet_count[tid_ptr->head] = 0;
2853                         tid_ptr->time_stamp += TID_QUEUE_CELL_SPACING;
2854                         tid_ptr->queue_count--;
2855                         tid_ptr->head++;
2856                         if (tid_ptr->head >= TID_QUEUE_MAX_SIZE)
2857                                 tid_ptr->head = 0;
2858                 }
2859         }
2860         load = tid_ptr->total;
2861
2862  out:
2863         spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
2864         return load;
2865 }
2866
2867 /*
2868         increment traffic load value for tid and also remove
2869         any old values if passed the certian time period
2870 */
2871 static void iwl4965_tl_add_packet(struct iwl_priv *priv, u8 tid)
2872 {
2873         u32 current_time = jiffies_to_msecs(jiffies);
2874         u32 time_diff;
2875         s32 index;
2876         unsigned long flags;
2877         struct iwl_traffic_load *tid_ptr = NULL;
2878
2879         if (tid >= TID_MAX_LOAD_COUNT)
2880                 return;
2881
2882         tid_ptr = &(priv->lq_mngr.agg_ctrl.traffic_load[tid]);
2883
2884         current_time -= current_time % TID_ROUND_VALUE;
2885
2886         spin_lock_irqsave(&priv->lq_mngr.lock, flags);
2887         if (!(tid_ptr->queue_count)) {
2888                 tid_ptr->total = 1;
2889                 tid_ptr->time_stamp = current_time;
2890                 tid_ptr->queue_count = 1;
2891                 tid_ptr->head = 0;
2892                 tid_ptr->packet_count[0] = 1;
2893                 goto out;
2894         }
2895
2896         time_diff = TIME_WRAP_AROUND(tid_ptr->time_stamp, current_time);
2897         index = time_diff / TID_QUEUE_CELL_SPACING;
2898
2899         if (index >= TID_QUEUE_MAX_SIZE) {
2900                 u32 oldest_time = current_time - TID_MAX_TIME_DIFF;
2901
2902                 while (tid_ptr->queue_count &&
2903                        (tid_ptr->time_stamp < oldest_time)) {
2904                         tid_ptr->total -= tid_ptr->packet_count[tid_ptr->head];
2905                         tid_ptr->packet_count[tid_ptr->head] = 0;
2906                         tid_ptr->time_stamp += TID_QUEUE_CELL_SPACING;
2907                         tid_ptr->queue_count--;
2908                         tid_ptr->head++;
2909                         if (tid_ptr->head >= TID_QUEUE_MAX_SIZE)
2910                                 tid_ptr->head = 0;
2911                 }
2912         }
2913
2914         index = (tid_ptr->head + index) % TID_QUEUE_MAX_SIZE;
2915         tid_ptr->packet_count[index] = tid_ptr->packet_count[index] + 1;
2916         tid_ptr->total = tid_ptr->total + 1;
2917
2918         if ((index + 1) > tid_ptr->queue_count)
2919                 tid_ptr->queue_count = index + 1;
2920  out:
2921         spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
2922
2923 }
2924
2925 #define MMAC_SCHED_MAX_NUMBER_OF_HT_BACK_FLOWS   7
2926 enum HT_STATUS {
2927         BA_STATUS_FAILURE = 0,
2928         BA_STATUS_INITIATOR_DELBA,
2929         BA_STATUS_RECIPIENT_DELBA,
2930         BA_STATUS_RENEW_ADDBA_REQUEST,
2931         BA_STATUS_ACTIVE,
2932 };
2933
2934 static u8 iwl4964_tl_ba_avail(struct iwl_priv *priv)
2935 {
2936         int i;
2937         struct iwl_lq_mngr *lq;
2938         u8 count = 0;
2939         u16 msk;
2940
2941         lq = (struct iwl_lq_mngr *)&(priv->lq_mngr);
2942         for (i = 0; i < TID_MAX_LOAD_COUNT ; i++) {
2943                 msk = 1 << i;
2944                 if ((lq->agg_ctrl.granted_ba & msk) ||
2945                     (lq->agg_ctrl.wait_for_agg_status & msk))
2946                         count++;
2947         }
2948
2949         if (count < MMAC_SCHED_MAX_NUMBER_OF_HT_BACK_FLOWS)
2950                 return 1;
2951
2952         return 0;
2953 }
2954
2955 static void iwl4965_ba_status(struct iwl_priv *priv,
2956                               u8 tid, enum HT_STATUS status);
2957
2958 static int iwl4965_perform_addba(struct iwl_priv *priv, u8 tid, u32 length,
2959                                  u32 ba_timeout)
2960 {
2961         int rc;
2962
2963         rc = ieee80211_start_BA_session(priv->hw, priv->bssid, tid);
2964         if (rc)
2965                 iwl4965_ba_status(priv, tid, BA_STATUS_FAILURE);
2966
2967         return rc;
2968 }
2969
2970 static int iwl4965_perform_delba(struct iwl_priv *priv, u8 tid)
2971 {
2972         int rc;
2973
2974         rc = ieee80211_stop_BA_session(priv->hw, priv->bssid, tid);
2975         if (rc)
2976                 iwl4965_ba_status(priv, tid, BA_STATUS_FAILURE);
2977
2978         return rc;
2979 }
2980
2981 static void iwl4965_turn_on_agg_for_tid(struct iwl_priv *priv,
2982                                         struct iwl_lq_mngr *lq,
2983                                         u8 auto_agg, u8 tid)
2984 {
2985         u32 tid_msk = (1 << tid);
2986         unsigned long flags;
2987
2988         spin_lock_irqsave(&priv->lq_mngr.lock, flags);
2989 /*
2990         if ((auto_agg) && (!lq->enable_counter)){
2991                 lq->agg_ctrl.next_retry = 0;
2992                 lq->agg_ctrl.tid_retry = 0;
2993                 spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
2994                 return;
2995         }
2996 */
2997         if (!(lq->agg_ctrl.granted_ba & tid_msk) &&
2998             (lq->agg_ctrl.requested_ba & tid_msk)) {
2999                 u8 available_queues;
3000                 u32 load;
3001
3002                 spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
3003                 available_queues = iwl4964_tl_ba_avail(priv);
3004                 load = iwl4965_tl_get_load(priv, tid);
3005
3006                 spin_lock_irqsave(&priv->lq_mngr.lock, flags);
3007                 if (!available_queues) {
3008                         if (auto_agg)
3009                                 lq->agg_ctrl.tid_retry |= tid_msk;
3010                         else {
3011                                 lq->agg_ctrl.requested_ba &= ~tid_msk;
3012                                 lq->agg_ctrl.wait_for_agg_status &= ~tid_msk;
3013                         }
3014                 } else if ((auto_agg) &&
3015                            ((load <= lq->agg_ctrl.tid_traffic_load_threshold) ||
3016                             ((lq->agg_ctrl.wait_for_agg_status & tid_msk))))
3017                         lq->agg_ctrl.tid_retry |= tid_msk;
3018                 else {
3019                         lq->agg_ctrl.wait_for_agg_status |= tid_msk;
3020                         spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
3021                         iwl4965_perform_addba(priv, tid, 0x40,
3022                                               lq->agg_ctrl.ba_timeout);
3023                         spin_lock_irqsave(&priv->lq_mngr.lock, flags);
3024                 }
3025         }
3026         spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
3027 }
3028
3029 static void iwl4965_turn_on_agg(struct iwl_priv *priv, u8 tid)
3030 {
3031         struct iwl_lq_mngr *lq;
3032         unsigned long flags;
3033
3034         lq = (struct iwl_lq_mngr *)&(priv->lq_mngr);
3035
3036         if ((tid < TID_MAX_LOAD_COUNT))
3037                 iwl4965_turn_on_agg_for_tid(priv, lq, lq->agg_ctrl.auto_agg,
3038                                             tid);
3039         else if (tid == TID_ALL_SPECIFIED) {
3040                 if (lq->agg_ctrl.requested_ba) {
3041                         for (tid = 0; tid < TID_MAX_LOAD_COUNT; tid++)
3042                                 iwl4965_turn_on_agg_for_tid(priv, lq,
3043                                         lq->agg_ctrl.auto_agg, tid);
3044                 } else {
3045                         spin_lock_irqsave(&priv->lq_mngr.lock, flags);
3046                         lq->agg_ctrl.tid_retry = 0;
3047                         lq->agg_ctrl.next_retry = 0;
3048                         spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
3049                 }
3050         }
3051
3052 }
3053
3054 void iwl4965_turn_off_agg(struct iwl_priv *priv, u8 tid)
3055 {
3056         u32 tid_msk;
3057         struct iwl_lq_mngr *lq;
3058         unsigned long flags;
3059
3060         lq = (struct iwl_lq_mngr *)&(priv->lq_mngr);
3061
3062         if ((tid < TID_MAX_LOAD_COUNT)) {
3063                 tid_msk = 1 << tid;
3064                 spin_lock_irqsave(&priv->lq_mngr.lock, flags);
3065                 lq->agg_ctrl.wait_for_agg_status |= tid_msk;
3066                 lq->agg_ctrl.requested_ba &= ~tid_msk;
3067                 spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
3068                 iwl4965_perform_delba(priv, tid);
3069         } else if (tid == TID_ALL_SPECIFIED) {
3070                 spin_lock_irqsave(&priv->lq_mngr.lock, flags);
3071                 for (tid = 0; tid < TID_MAX_LOAD_COUNT; tid++) {
3072                         tid_msk = 1 << tid;
3073                         lq->agg_ctrl.wait_for_agg_status |= tid_msk;
3074                         spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
3075                         iwl4965_perform_delba(priv, tid);
3076                         spin_lock_irqsave(&priv->lq_mngr.lock, flags);
3077                 }
3078                 lq->agg_ctrl.requested_ba = 0;
3079                 spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
3080         }
3081 }
3082
3083 static void iwl4965_ba_status(struct iwl_priv *priv,
3084                                 u8 tid, enum HT_STATUS status)
3085 {
3086         struct iwl_lq_mngr *lq;
3087         u32 tid_msk = (1 << tid);
3088         unsigned long flags;
3089
3090         lq = (struct iwl_lq_mngr *)&(priv->lq_mngr);
3091
3092         if ((tid >= TID_MAX_LOAD_COUNT))
3093                 goto out;
3094
3095         spin_lock_irqsave(&priv->lq_mngr.lock, flags);
3096         switch (status) {
3097         case BA_STATUS_ACTIVE:
3098                 if (!(lq->agg_ctrl.granted_ba & tid_msk))
3099                         lq->agg_ctrl.granted_ba |= tid_msk;
3100                 break;
3101         default:
3102                 if ((lq->agg_ctrl.granted_ba & tid_msk))
3103                         lq->agg_ctrl.granted_ba &= ~tid_msk;
3104                 break;
3105         }
3106
3107         lq->agg_ctrl.wait_for_agg_status &= ~tid_msk;
3108         if (status != BA_STATUS_ACTIVE) {
3109                 if (lq->agg_ctrl.auto_agg) {
3110                         lq->agg_ctrl.tid_retry |= tid_msk;
3111                         lq->agg_ctrl.next_retry =
3112                             jiffies + msecs_to_jiffies(500);
3113                 } else
3114                         lq->agg_ctrl.requested_ba &= ~tid_msk;
3115         }
3116         spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
3117  out:
3118         return;
3119 }
3120
3121 static void iwl4965_bg_agg_work(struct work_struct *work)
3122 {
3123         struct iwl_priv *priv = container_of(work, struct iwl_priv,
3124                                         agg_work);
3125
3126         u32 tid;
3127         u32 retry_tid;
3128         u32 tid_msk;
3129         unsigned long flags;
3130         struct iwl_lq_mngr *lq = (struct iwl_lq_mngr *)&(priv->lq_mngr);
3131
3132         spin_lock_irqsave(&priv->lq_mngr.lock, flags);
3133         retry_tid = lq->agg_ctrl.tid_retry;
3134         lq->agg_ctrl.tid_retry = 0;
3135         spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
3136
3137         if (retry_tid == TID_ALL_SPECIFIED)
3138                 iwl4965_turn_on_agg(priv, TID_ALL_SPECIFIED);
3139         else {
3140                 for (tid = 0; tid < TID_MAX_LOAD_COUNT; tid++) {
3141                         tid_msk = (1 << tid);
3142                         if (retry_tid & tid_msk)
3143                                 iwl4965_turn_on_agg(priv, tid);
3144                 }
3145         }
3146
3147         spin_lock_irqsave(&priv->lq_mngr.lock, flags);
3148         if (lq->agg_ctrl.tid_retry)
3149                 lq->agg_ctrl.next_retry = jiffies + msecs_to_jiffies(500);
3150         spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
3151         return;
3152 }
3153 #endif /*CONFIG_IWLWIFI_HT_AGG */
3154 #endif /* CONFIG_IWLWIFI_HT */
3155
3156 int iwl4965_tx_cmd(struct iwl_priv *priv, struct iwl_cmd *out_cmd,
3157                    u8 sta_id, dma_addr_t txcmd_phys,
3158                    struct ieee80211_hdr *hdr, u8 hdr_len,
3159                    struct ieee80211_tx_control *ctrl, void *sta_in)
3160 {
3161         struct iwl_tx_cmd cmd;
3162         struct iwl_tx_cmd *tx = (struct iwl_tx_cmd *)&out_cmd->cmd.payload[0];
3163         dma_addr_t scratch_phys;
3164         u8 unicast = 0;
3165         u8 is_data = 1;
3166         u16 fc;
3167         u16 rate_flags;
3168         int rate_index = min(ctrl->tx_rate & 0xffff, IWL_RATE_COUNT - 1);
3169 #ifdef CONFIG_IWLWIFI_HT
3170 #ifdef CONFIG_IWLWIFI_HT_AGG
3171         __le16 *qc;
3172 #endif /*CONFIG_IWLWIFI_HT_AGG */
3173 #endif /* CONFIG_IWLWIFI_HT */
3174
3175         unicast = !is_multicast_ether_addr(hdr->addr1);
3176
3177         fc = le16_to_cpu(hdr->frame_control);
3178         if ((fc & IEEE80211_FCTL_FTYPE) != IEEE80211_FTYPE_DATA)
3179                 is_data = 0;
3180
3181         memcpy(&cmd, &(out_cmd->cmd.tx), sizeof(struct iwl_tx_cmd));
3182         memset(tx, 0, sizeof(struct iwl_tx_cmd));
3183         memcpy(tx->hdr, hdr, hdr_len);
3184
3185         tx->len = cmd.len;
3186         tx->driver_txop = cmd.driver_txop;
3187         tx->stop_time.life_time = cmd.stop_time.life_time;
3188         tx->tx_flags = cmd.tx_flags;
3189         tx->sta_id = cmd.sta_id;
3190         tx->tid_tspec = cmd.tid_tspec;
3191         tx->timeout.pm_frame_timeout = cmd.timeout.pm_frame_timeout;
3192         tx->next_frame_len = cmd.next_frame_len;
3193
3194         tx->sec_ctl = cmd.sec_ctl;
3195         memcpy(&(tx->key[0]), &(cmd.key[0]), 16);
3196         tx->tx_flags = cmd.tx_flags;
3197
3198         tx->rts_retry_limit = cmd.rts_retry_limit;
3199         tx->data_retry_limit = cmd.data_retry_limit;
3200
3201         scratch_phys = txcmd_phys + sizeof(struct iwl_cmd_header) +
3202             offsetof(struct iwl_tx_cmd, scratch);
3203         tx->dram_lsb_ptr = cpu_to_le32(scratch_phys);
3204         tx->dram_msb_ptr = iwl4965_get_dma_hi_address(scratch_phys);
3205
3206         /* Hard coded to start at the highest retry fallback position
3207          * until the 4965 specific rate control algorithm is tied in */
3208         tx->initial_rate_index = LINK_QUAL_MAX_RETRY_NUM - 1;
3209
3210         /* Alternate between antenna A and B for successive frames */
3211         if (priv->use_ant_b_for_management_frame) {
3212                 priv->use_ant_b_for_management_frame = 0;
3213                 rate_flags = RATE_MCS_ANT_B_MSK;
3214         } else {
3215                 priv->use_ant_b_for_management_frame = 1;
3216                 rate_flags = RATE_MCS_ANT_A_MSK;
3217         }
3218
3219         if (!unicast || !is_data) {
3220                 if ((rate_index >= IWL_FIRST_CCK_RATE) &&
3221                     (rate_index <= IWL_LAST_CCK_RATE))
3222                         rate_flags |= RATE_MCS_CCK_MSK;
3223         } else {
3224                 tx->initial_rate_index = 0;
3225                 tx->tx_flags |= TX_CMD_FLG_STA_RATE_MSK;
3226         }
3227
3228         tx->rate_n_flags = iwl_hw_set_rate_n_flags(iwl_rates[rate_index].plcp,
3229                                                 rate_flags);
3230
3231         if (ieee80211_is_back_request(fc))
3232                 tx->tx_flags |= TX_CMD_FLG_ACK_MSK |
3233                         TX_CMD_FLG_IMM_BA_RSP_MASK;
3234 #ifdef CONFIG_IWLWIFI_HT
3235 #ifdef CONFIG_IWLWIFI_HT_AGG
3236         qc = ieee80211_get_qos_ctrl(hdr);
3237         if (qc &&
3238             (priv->iw_mode != IEEE80211_IF_TYPE_IBSS)) {
3239                 u8 tid = 0;
3240                 tid = (u8) (le16_to_cpu(*qc) & 0xF);
3241                 if (tid < TID_MAX_LOAD_COUNT)
3242                         iwl4965_tl_add_packet(priv, tid);
3243         }
3244
3245         if (priv->lq_mngr.agg_ctrl.next_retry &&
3246             (time_after(priv->lq_mngr.agg_ctrl.next_retry, jiffies))) {
3247                 unsigned long flags;
3248
3249                 spin_lock_irqsave(&priv->lq_mngr.lock, flags);
3250                 priv->lq_mngr.agg_ctrl.next_retry = 0;
3251                 spin_unlock_irqrestore(&priv->lq_mngr.lock, flags);
3252                 schedule_work(&priv->agg_work);
3253         }
3254 #endif
3255 #endif
3256         return 0;
3257 }
3258
3259 /**
3260  * sign_extend - Sign extend a value using specified bit as sign-bit
3261  *
3262  * Example: sign_extend(9, 3) would return -7 as bit3 of 1001b is 1
3263  * and bit0..2 is 001b which when sign extended to 1111111111111001b is -7.
3264  *
3265  * @param oper value to sign extend
3266  * @param index 0 based bit index (0<=index<32) to sign bit
3267  */
3268 static s32 sign_extend(u32 oper, int index)
3269 {
3270         u8 shift = 31 - index;
3271
3272         return (s32)(oper << shift) >> shift;
3273 }
3274
3275 /**
3276  * iwl4965_get_temperature - return the calibrated temperature (in Kelvin)
3277  * @statistics: Provides the temperature reading from the uCode
3278  *
3279  * A return of <0 indicates bogus data in the statistics
3280  */
3281 int iwl4965_get_temperature(const struct iwl_priv *priv)
3282 {
3283         s32 temperature;
3284         s32 vt;
3285         s32 R1, R2, R3;
3286         u32 R4;
3287
3288         if (test_bit(STATUS_TEMPERATURE, &priv->status) &&
3289                 (priv->statistics.flag & STATISTICS_REPLY_FLG_FAT_MODE_MSK)) {
3290                 IWL_DEBUG_TEMP("Running FAT temperature calibration\n");
3291                 R1 = (s32)le32_to_cpu(priv->card_alive_init.therm_r1[1]);
3292                 R2 = (s32)le32_to_cpu(priv->card_alive_init.therm_r2[1]);
3293                 R3 = (s32)le32_to_cpu(priv->card_alive_init.therm_r3[1]);
3294                 R4 = le32_to_cpu(priv->card_alive_init.therm_r4[1]);
3295         } else {
3296                 IWL_DEBUG_TEMP("Running temperature calibration\n");
3297                 R1 = (s32)le32_to_cpu(priv->card_alive_init.therm_r1[0]);
3298                 R2 = (s32)le32_to_cpu(priv->card_alive_init.therm_r2[0]);
3299                 R3 = (s32)le32_to_cpu(priv->card_alive_init.therm_r3[0]);
3300                 R4 = le32_to_cpu(priv->card_alive_init.therm_r4[0]);
3301         }
3302
3303         /*
3304          * Temperature is only 23 bits so sign extend out to 32
3305          *
3306          * NOTE If we haven't received a statistics notification yet
3307          * with an updated temperature, use R4 provided to us in the
3308          * ALIVE response. */
3309         if (!test_bit(STATUS_TEMPERATURE, &priv->status))
3310                 vt = sign_extend(R4, 23);
3311         else
3312                 vt = sign_extend(
3313                         le32_to_cpu(priv->statistics.general.temperature), 23);
3314
3315         IWL_DEBUG_TEMP("Calib values R[1-3]: %d %d %d R4: %d\n",
3316                        R1, R2, R3, vt);
3317
3318         if (R3 == R1) {
3319                 IWL_ERROR("Calibration conflict R1 == R3\n");
3320                 return -1;
3321         }
3322
3323         /* Calculate temperature in degrees Kelvin, adjust by 97%.
3324          * Add offset to center the adjustment around 0 degrees Centigrade. */
3325         temperature = TEMPERATURE_CALIB_A_VAL * (vt - R2);
3326         temperature /= (R3 - R1);
3327         temperature = (temperature * 97) / 100 +
3328             TEMPERATURE_CALIB_KELVIN_OFFSET;
3329
3330         IWL_DEBUG_TEMP("Calibrated temperature: %dK, %dC\n", temperature,
3331             KELVIN_TO_CELSIUS(temperature));
3332
3333         return temperature;
3334 }
3335
3336 /* Adjust Txpower only if temperature variance is greater than threshold. */
3337 #define IWL_TEMPERATURE_THRESHOLD   3
3338
3339 /**
3340  * iwl4965_is_temp_calib_needed - determines if new calibration is needed
3341  *
3342  * If the temperature changed has changed sufficiently, then a recalibration
3343  * is needed.
3344  *
3345  * Assumes caller will replace priv->last_temperature once calibration
3346  * executed.
3347  */
3348 static int iwl4965_is_temp_calib_needed(struct iwl_priv *priv)
3349 {
3350         int temp_diff;
3351
3352         if (!test_bit(STATUS_STATISTICS, &priv->status)) {
3353                 IWL_DEBUG_TEMP("Temperature not updated -- no statistics.\n");
3354                 return 0;
3355         }
3356
3357         temp_diff = priv->temperature - priv->last_temperature;
3358
3359         /* get absolute value */
3360         if (temp_diff < 0) {
3361                 IWL_DEBUG_POWER("Getting cooler, delta %d, \n", temp_diff);
3362                 temp_diff = -temp_diff;
3363         } else if (temp_diff == 0)
3364                 IWL_DEBUG_POWER("Same temp, \n");
3365         else
3366                 IWL_DEBUG_POWER("Getting warmer, delta %d, \n", temp_diff);
3367
3368         if (temp_diff < IWL_TEMPERATURE_THRESHOLD) {
3369                 IWL_DEBUG_POWER("Thermal txpower calib not needed\n");
3370                 return 0;
3371         }
3372
3373         IWL_DEBUG_POWER("Thermal txpower calib needed\n");
3374
3375         return 1;
3376 }
3377
3378 /* Calculate noise level, based on measurements during network silence just
3379  *   before arriving beacon.  This measurement can be done only if we know
3380  *   exactly when to expect beacons, therefore only when we're associated. */
3381 static void iwl4965_rx_calc_noise(struct iwl_priv *priv)
3382 {
3383         struct statistics_rx_non_phy *rx_info
3384                                 = &(priv->statistics.rx.general);
3385         int num_active_rx = 0;
3386         int total_silence = 0;
3387         int bcn_silence_a =
3388                 le32_to_cpu(rx_info->beacon_silence_rssi_a) & IN_BAND_FILTER;
3389         int bcn_silence_b =
3390                 le32_to_cpu(rx_info->beacon_silence_rssi_b) & IN_BAND_FILTER;
3391         int bcn_silence_c =
3392                 le32_to_cpu(rx_info->beacon_silence_rssi_c) & IN_BAND_FILTER;
3393
3394         if (bcn_silence_a) {
3395                 total_silence += bcn_silence_a;
3396                 num_active_rx++;
3397         }
3398         if (bcn_silence_b) {
3399                 total_silence += bcn_silence_b;
3400                 num_active_rx++;
3401         }
3402         if (bcn_silence_c) {
3403                 total_silence += bcn_silence_c;
3404                 num_active_rx++;
3405         }
3406
3407         /* Average among active antennas */
3408         if (num_active_rx)
3409                 priv->last_rx_noise = (total_silence / num_active_rx) - 107;
3410         else
3411                 priv->last_rx_noise = IWL_NOISE_MEAS_NOT_AVAILABLE;
3412
3413         IWL_DEBUG_CALIB("inband silence a %u, b %u, c %u, dBm %d\n",
3414                         bcn_silence_a, bcn_silence_b, bcn_silence_c,
3415                         priv->last_rx_noise);
3416 }
3417
3418 void iwl_hw_rx_statistics(struct iwl_priv *priv, struct iwl_rx_mem_buffer *rxb)
3419 {
3420         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
3421         int change;
3422         s32 temp;
3423
3424         IWL_DEBUG_RX("Statistics notification received (%d vs %d).\n",
3425                      (int)sizeof(priv->statistics), pkt->len);
3426
3427         change = ((priv->statistics.general.temperature !=
3428                    pkt->u.stats.general.temperature) ||
3429                   ((priv->statistics.flag &
3430                     STATISTICS_REPLY_FLG_FAT_MODE_MSK) !=
3431                    (pkt->u.stats.flag & STATISTICS_REPLY_FLG_FAT_MODE_MSK)));
3432
3433         memcpy(&priv->statistics, &pkt->u.stats, sizeof(priv->statistics));
3434
3435         set_bit(STATUS_STATISTICS, &priv->status);
3436
3437         /* Reschedule the statistics timer to occur in
3438          * REG_RECALIB_PERIOD seconds to ensure we get a
3439          * thermal update even if the uCode doesn't give
3440          * us one */
3441         mod_timer(&priv->statistics_periodic, jiffies +
3442                   msecs_to_jiffies(REG_RECALIB_PERIOD * 1000));
3443
3444         if (unlikely(!test_bit(STATUS_SCANNING, &priv->status)) &&
3445             (pkt->hdr.cmd == STATISTICS_NOTIFICATION)) {
3446                 iwl4965_rx_calc_noise(priv);
3447 #ifdef CONFIG_IWLWIFI_SENSITIVITY
3448                 queue_work(priv->workqueue, &priv->sensitivity_work);
3449 #endif
3450         }
3451
3452         /* If the hardware hasn't reported a change in
3453          * temperature then don't bother computing a
3454          * calibrated temperature value */
3455         if (!change)
3456                 return;
3457
3458         temp = iwl4965_get_temperature(priv);
3459         if (temp < 0)
3460                 return;
3461
3462         if (priv->temperature != temp) {
3463                 if (priv->temperature)
3464                         IWL_DEBUG_TEMP("Temperature changed "
3465                                        "from %dC to %dC\n",
3466                                        KELVIN_TO_CELSIUS(priv->temperature),
3467                                        KELVIN_TO_CELSIUS(temp));
3468                 else
3469                         IWL_DEBUG_TEMP("Temperature "
3470                                        "initialized to %dC\n",
3471                                        KELVIN_TO_CELSIUS(temp));
3472         }
3473
3474         priv->temperature = temp;
3475         set_bit(STATUS_TEMPERATURE, &priv->status);
3476
3477         if (unlikely(!test_bit(STATUS_SCANNING, &priv->status)) &&
3478                      iwl4965_is_temp_calib_needed(priv))
3479                 queue_work(priv->workqueue, &priv->txpower_work);
3480 }
3481
3482 static void iwl4965_handle_data_packet(struct iwl_priv *priv, int is_data,
3483                                        int include_phy,
3484                                        struct iwl_rx_mem_buffer *rxb,
3485                                        struct ieee80211_rx_status *stats)
3486 {
3487         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
3488         struct iwl4965_rx_phy_res *rx_start = (include_phy) ?
3489             (struct iwl4965_rx_phy_res *)&(pkt->u.raw[0]) : NULL;
3490         struct ieee80211_hdr *hdr;
3491         u16 len;
3492         __le32 *rx_end;
3493         unsigned int skblen;
3494         u32 ampdu_status;
3495
3496         if (!include_phy && priv->last_phy_res[0])
3497                 rx_start = (struct iwl4965_rx_phy_res *)&priv->last_phy_res[1];
3498
3499         if (!rx_start) {
3500                 IWL_ERROR("MPDU frame without a PHY data\n");
3501                 return;
3502         }
3503         if (include_phy) {
3504                 hdr = (struct ieee80211_hdr *)((u8 *) & rx_start[1] +
3505                                                rx_start->cfg_phy_cnt);
3506
3507                 len = le16_to_cpu(rx_start->byte_count);
3508
3509                 rx_end = (__le32 *) ((u8 *) & pkt->u.raw[0] +
3510                                   sizeof(struct iwl4965_rx_phy_res) +
3511                                   rx_start->cfg_phy_cnt + len);
3512
3513         } else {
3514                 struct iwl4965_rx_mpdu_res_start *amsdu =
3515                     (struct iwl4965_rx_mpdu_res_start *)pkt->u.raw;
3516
3517                 hdr = (struct ieee80211_hdr *)(pkt->u.raw +
3518                                sizeof(struct iwl4965_rx_mpdu_res_start));
3519                 len =  le16_to_cpu(amsdu->byte_count);
3520                 rx_start->byte_count = amsdu->byte_count;
3521                 rx_end = (__le32 *) (((u8 *) hdr) + len);
3522         }
3523         if (len > IWL_RX_BUF_SIZE || len < 16) {
3524                 IWL_WARNING("byte count out of range [16,4K]"
3525                                " : %d\n", len);
3526                 return;
3527         }
3528
3529         ampdu_status = le32_to_cpu(*rx_end);
3530         skblen = ((u8 *) rx_end - (u8 *) & pkt->u.raw[0]) + sizeof(u32);
3531
3532         /* start from MAC */
3533         skb_reserve(rxb->skb, (void *)hdr - (void *)pkt);
3534         skb_put(rxb->skb, len); /* end where data ends */
3535
3536         /* We only process data packets if the interface is open */
3537         if (unlikely(!priv->is_open)) {
3538                 IWL_DEBUG_DROP_LIMIT
3539                     ("Dropping packet while interface is not open.\n");
3540                 return;
3541         }
3542
3543         if (priv->iw_mode == IEEE80211_IF_TYPE_MNTR) {
3544                 if (iwl_param_hwcrypto)
3545                         iwl_set_decrypted_flag(priv, rxb->skb,
3546                                                ampdu_status, stats);
3547                 iwl_handle_data_packet_monitor(priv, rxb, hdr, len, stats, 0);
3548                 return;
3549         }
3550
3551         stats->flag = 0;
3552         hdr = (struct ieee80211_hdr *)rxb->skb->data;
3553
3554         if (iwl_param_hwcrypto)
3555                 iwl_set_decrypted_flag(priv, rxb->skb, ampdu_status, stats);
3556
3557         ieee80211_rx_irqsafe(priv->hw, rxb->skb, stats);
3558         priv->alloc_rxb_skb--;
3559         rxb->skb = NULL;
3560 #ifdef LED
3561         priv->led_packets += len;
3562         iwl_setup_activity_timer(priv);
3563 #endif
3564 }
3565
3566 /* Calc max signal level (dBm) among 3 possible receivers */
3567 static int iwl4965_calc_rssi(struct iwl4965_rx_phy_res *rx_resp)
3568 {
3569         /* data from PHY/DSP regarding signal strength, etc.,
3570          *   contents are always there, not configurable by host.  */
3571         struct iwl4965_rx_non_cfg_phy *ncphy =
3572             (struct iwl4965_rx_non_cfg_phy *)rx_resp->non_cfg_phy;
3573         u32 agc = (le16_to_cpu(ncphy->agc_info) & IWL_AGC_DB_MASK)
3574                         >> IWL_AGC_DB_POS;
3575
3576         u32 valid_antennae =
3577             (le16_to_cpu(rx_resp->phy_flags) & RX_PHY_FLAGS_ANTENNAE_MASK)
3578                         >> RX_PHY_FLAGS_ANTENNAE_OFFSET;
3579         u8 max_rssi = 0;
3580         u32 i;
3581
3582         /* Find max rssi among 3 possible receivers.
3583          * These values are measured by the digital signal processor (DSP).
3584          * They should stay fairly constant even as the signal strength varies,
3585          *   if the radio's automatic gain control (AGC) is working right.
3586          * AGC value (see below) will provide the "interesting" info. */
3587         for (i = 0; i < 3; i++)
3588                 if (valid_antennae & (1 << i))
3589                         max_rssi = max(ncphy->rssi_info[i << 1], max_rssi);
3590
3591         IWL_DEBUG_STATS("Rssi In A %d B %d C %d Max %d AGC dB %d\n",
3592                 ncphy->rssi_info[0], ncphy->rssi_info[2], ncphy->rssi_info[4],
3593                 max_rssi, agc);
3594
3595         /* dBm = max_rssi dB - agc dB - constant.
3596          * Higher AGC (higher radio gain) means lower signal. */
3597         return (max_rssi - agc - IWL_RSSI_OFFSET);
3598 }
3599
3600 #ifdef CONFIG_IWLWIFI_HT
3601
3602 /* Parsed Information Elements */
3603 struct ieee802_11_elems {
3604         u8 *ds_params;
3605         u8 ds_params_len;
3606         u8 *tim;
3607         u8 tim_len;
3608         u8 *ibss_params;
3609         u8 ibss_params_len;
3610         u8 *erp_info;
3611         u8 erp_info_len;
3612         u8 *ht_cap_param;
3613         u8 ht_cap_param_len;
3614         u8 *ht_extra_param;
3615         u8 ht_extra_param_len;
3616 };
3617
3618 static int parse_elems(u8 *start, size_t len, struct ieee802_11_elems *elems)
3619 {
3620         size_t left = len;
3621         u8 *pos = start;
3622         int unknown = 0;
3623
3624         memset(elems, 0, sizeof(*elems));
3625
3626         while (left >= 2) {
3627                 u8 id, elen;
3628
3629                 id = *pos++;
3630                 elen = *pos++;
3631                 left -= 2;
3632
3633                 if (elen > left)
3634                         return -1;
3635
3636                 switch (id) {
3637                 case WLAN_EID_DS_PARAMS:
3638                         elems->ds_params = pos;
3639                         elems->ds_params_len = elen;
3640                         break;
3641                 case WLAN_EID_TIM:
3642                         elems->tim = pos;
3643                         elems->tim_len = elen;
3644                         break;
3645                 case WLAN_EID_IBSS_PARAMS:
3646                         elems->ibss_params = pos;
3647                         elems->ibss_params_len = elen;
3648                         break;
3649                 case WLAN_EID_ERP_INFO:
3650                         elems->erp_info = pos;
3651                         elems->erp_info_len = elen;
3652                         break;
3653                 case WLAN_EID_HT_CAPABILITY:
3654                         elems->ht_cap_param = pos;
3655                         elems->ht_cap_param_len = elen;
3656                         break;
3657                 case WLAN_EID_HT_EXTRA_INFO:
3658                         elems->ht_extra_param = pos;
3659                         elems->ht_extra_param_len = elen;
3660                         break;
3661                 default:
3662                         unknown++;
3663                         break;
3664                 }
3665
3666                 left -= elen;
3667                 pos += elen;
3668         }
3669
3670         return 0;
3671 }
3672 #endif /* CONFIG_IWLWIFI_HT */
3673
3674 static void iwl4965_sta_modify_ps_wake(struct iwl_priv *priv, int sta_id)
3675 {
3676         unsigned long flags;
3677
3678         spin_lock_irqsave(&priv->sta_lock, flags);
3679         priv->stations[sta_id].sta.station_flags &= ~STA_FLG_PWR_SAVE_MSK;
3680         priv->stations[sta_id].sta.station_flags_msk = STA_FLG_PWR_SAVE_MSK;
3681         priv->stations[sta_id].sta.sta.modify_mask = 0;
3682         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
3683         spin_unlock_irqrestore(&priv->sta_lock, flags);
3684
3685         iwl_send_add_station(priv, &priv->stations[sta_id].sta, CMD_ASYNC);
3686 }
3687
3688 static void iwl4965_update_ps_mode(struct iwl_priv *priv, u16 ps_bit, u8 *addr)
3689 {
3690         /* FIXME: need locking over ps_status ??? */
3691         u8 sta_id = iwl_hw_find_station(priv, addr);
3692
3693         if (sta_id != IWL_INVALID_STATION) {
3694                 u8 sta_awake = priv->stations[sta_id].
3695                                 ps_status == STA_PS_STATUS_WAKE;
3696
3697                 if (sta_awake && ps_bit)
3698                         priv->stations[sta_id].ps_status = STA_PS_STATUS_SLEEP;
3699                 else if (!sta_awake && !ps_bit) {
3700                         iwl4965_sta_modify_ps_wake(priv, sta_id);
3701                         priv->stations[sta_id].ps_status = STA_PS_STATUS_WAKE;
3702                 }
3703         }
3704 }
3705
3706 /* Called for REPLY_4965_RX (legacy ABG frames), or
3707  * REPLY_RX_MPDU_CMD (HT high-throughput N frames). */
3708 static void iwl4965_rx_reply_rx(struct iwl_priv *priv,
3709                                 struct iwl_rx_mem_buffer *rxb)
3710 {
3711         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
3712         /* Use phy data (Rx signal strength, etc.) contained within
3713          *   this rx packet for legacy frames,
3714          *   or phy data cached from REPLY_RX_PHY_CMD for HT frames. */
3715         int include_phy = (pkt->hdr.cmd == REPLY_4965_RX);
3716         struct iwl4965_rx_phy_res *rx_start = (include_phy) ?
3717                 (struct iwl4965_rx_phy_res *)&(pkt->u.raw[0]) :
3718                 (struct iwl4965_rx_phy_res *)&priv->last_phy_res[1];
3719         __le32 *rx_end;
3720         unsigned int len = 0;
3721         struct ieee80211_hdr *header;
3722         u16 fc;
3723         struct ieee80211_rx_status stats = {
3724                 .mactime = le64_to_cpu(rx_start->timestamp),
3725                 .channel = le16_to_cpu(rx_start->channel),
3726                 .phymode =
3727                         (rx_start->phy_flags & RX_RES_PHY_FLAGS_BAND_24_MSK) ?
3728                         MODE_IEEE80211G : MODE_IEEE80211A,
3729                 .antenna = 0,
3730                 .rate = iwl_hw_get_rate(rx_start->rate_n_flags),
3731                 .flag = 0,
3732 #ifdef CONFIG_IWLWIFI_HT_AGG
3733                 .ordered = 0
3734 #endif /* CONFIG_IWLWIFI_HT_AGG */
3735         };
3736         u8 network_packet;
3737
3738         if ((unlikely(rx_start->cfg_phy_cnt > 20))) {
3739                 IWL_DEBUG_DROP
3740                         ("dsp size out of range [0,20]: "
3741                          "%d/n", rx_start->cfg_phy_cnt);
3742                 return;
3743         }
3744         if (!include_phy) {
3745                 if (priv->last_phy_res[0])
3746                         rx_start = (struct iwl4965_rx_phy_res *)
3747                                 &priv->last_phy_res[1];
3748                 else
3749                         rx_start = NULL;
3750         }
3751
3752         if (!rx_start) {
3753                 IWL_ERROR("MPDU frame without a PHY data\n");
3754                 return;
3755         }
3756
3757         if (include_phy) {
3758                 header = (struct ieee80211_hdr *)((u8 *) & rx_start[1]
3759                                                   + rx_start->cfg_phy_cnt);
3760
3761                 len = le16_to_cpu(rx_start->byte_count);
3762                 rx_end = (__le32 *) (pkt->u.raw + rx_start->cfg_phy_cnt +
3763                                   sizeof(struct iwl4965_rx_phy_res) + len);
3764         } else {
3765                 struct iwl4965_rx_mpdu_res_start *amsdu =
3766                         (struct iwl4965_rx_mpdu_res_start *)pkt->u.raw;
3767
3768                 header = (void *)(pkt->u.raw +
3769                         sizeof(struct iwl4965_rx_mpdu_res_start));
3770                 len = le16_to_cpu(amsdu->byte_count);
3771                 rx_end = (__le32 *) (pkt->u.raw +
3772                         sizeof(struct iwl4965_rx_mpdu_res_start) + len);
3773         }
3774
3775         if (!(*rx_end & RX_RES_STATUS_NO_CRC32_ERROR) ||
3776             !(*rx_end & RX_RES_STATUS_NO_RXE_OVERFLOW)) {
3777                 IWL_DEBUG_RX("Bad CRC or FIFO: 0x%08X.\n",
3778                                 le32_to_cpu(*rx_end));
3779                 return;
3780         }
3781
3782         priv->ucode_beacon_time = le32_to_cpu(rx_start->beacon_time_stamp);
3783
3784         stats.freq = ieee80211chan2mhz(stats.channel);
3785
3786         /* Find max signal strength (dBm) among 3 antenna/receiver chains */
3787         stats.ssi = iwl4965_calc_rssi(rx_start);
3788
3789         /* Meaningful noise values are available only from beacon statistics,
3790          *   which are gathered only when associated, and indicate noise
3791          *   only for the associated network channel ...
3792          * Ignore these noise values while scanning (other channels) */
3793         if (iwl_is_associated(priv) &&
3794             !test_bit(STATUS_SCANNING, &priv->status)) {
3795                 stats.noise = priv->last_rx_noise;
3796                 stats.signal = iwl_calc_sig_qual(stats.ssi, stats.noise);
3797         } else {
3798                 stats.noise = IWL_NOISE_MEAS_NOT_AVAILABLE;
3799                 stats.signal = iwl_calc_sig_qual(stats.ssi, 0);
3800         }
3801
3802         /* Reset beacon noise level if not associated. */
3803         if (!iwl_is_associated(priv))
3804                 priv->last_rx_noise = IWL_NOISE_MEAS_NOT_AVAILABLE;
3805
3806 #ifdef CONFIG_IWLWIFI_DEBUG
3807         /* TODO:  Parts of iwl_report_frame are broken for 4965 */
3808         if (iwl_debug_level & (IWL_DL_RX))
3809                 /* Set "1" to report good data frames in groups of 100 */
3810                 iwl_report_frame(priv, pkt, header, 1);
3811
3812         if (iwl_debug_level & (IWL_DL_RX | IWL_DL_STATS))
3813         IWL_DEBUG_RX("Rssi %d, noise %d, qual %d, TSF %lu\n",
3814                 stats.ssi, stats.noise, stats.signal,
3815                  (long unsigned int)le64_to_cpu(rx_start->timestamp));
3816 #endif
3817
3818         network_packet = iwl_is_network_packet(priv, header);
3819         if (network_packet) {
3820                 priv->last_rx_rssi = stats.ssi;
3821                 priv->last_beacon_time =  priv->ucode_beacon_time;
3822                 priv->last_tsf = le64_to_cpu(rx_start->timestamp);
3823         }
3824
3825         fc = le16_to_cpu(header->frame_control);
3826         switch (fc & IEEE80211_FCTL_FTYPE) {
3827         case IEEE80211_FTYPE_MGMT:
3828
3829                 if (priv->iw_mode == IEEE80211_IF_TYPE_AP)
3830                         iwl4965_update_ps_mode(priv, fc  & IEEE80211_FCTL_PM,
3831                                                 header->addr2);
3832                 switch (fc & IEEE80211_FCTL_STYPE) {
3833                 case IEEE80211_STYPE_PROBE_RESP:
3834                 case IEEE80211_STYPE_BEACON:
3835                         if ((priv->iw_mode == IEEE80211_IF_TYPE_STA &&
3836                              !compare_ether_addr(header->addr2, priv->bssid)) ||
3837                             (priv->iw_mode == IEEE80211_IF_TYPE_IBSS &&
3838                              !compare_ether_addr(header->addr3, priv->bssid))) {
3839                                 struct ieee80211_mgmt *mgmt =
3840                                         (struct ieee80211_mgmt *)header;
3841                                 u64 timestamp =
3842                                         le64_to_cpu(mgmt->u.beacon.timestamp);
3843
3844                                 priv->timestamp0 = timestamp & 0xFFFFFFFF;
3845                                 priv->timestamp1 =
3846                                         (timestamp >> 32) & 0xFFFFFFFF;
3847                                 priv->beacon_int = le16_to_cpu(
3848                                     mgmt->u.beacon.beacon_int);
3849                                 if (priv->call_post_assoc_from_beacon &&
3850                                     (priv->iw_mode == IEEE80211_IF_TYPE_STA)) {
3851                                         priv->call_post_assoc_from_beacon = 0;
3852                                         queue_work(priv->workqueue,
3853                                             &priv->post_associate.work);
3854                                 }
3855                         }
3856                         break;
3857
3858                 case IEEE80211_STYPE_ACTION:
3859                         break;
3860
3861                         /*
3862                          * TODO: There is no callback function from upper
3863                          * stack to inform us when associated status. this
3864                          * work around to sniff assoc_resp management frame
3865                          * and finish the association process.
3866                          */
3867                 case IEEE80211_STYPE_ASSOC_RESP:
3868                 case IEEE80211_STYPE_REASSOC_RESP:
3869                         if (network_packet) {
3870 #ifdef CONFIG_IWLWIFI_HT
3871                                 u8 *pos = NULL;
3872                                 struct ieee802_11_elems elems;
3873 #endif                          /*CONFIG_IWLWIFI_HT */
3874                                 struct ieee80211_mgmt *mgnt =
3875                                         (struct ieee80211_mgmt *)header;
3876
3877                                 priv->assoc_id = (~((1 << 15) | (1 << 14))
3878                                         & le16_to_cpu(mgnt->u.assoc_resp.aid));
3879                                 priv->assoc_capability =
3880                                         le16_to_cpu(
3881                                                 mgnt->u.assoc_resp.capab_info);
3882 #ifdef CONFIG_IWLWIFI_HT
3883                                 pos = mgnt->u.assoc_resp.variable;
3884                                 if (!parse_elems(pos,
3885                                                  len - (pos - (u8 *) mgnt),
3886                                                  &elems)) {
3887                                         if (elems.ht_extra_param &&
3888                                             elems.ht_cap_param)
3889                                                 break;
3890                                 }
3891 #endif                          /*CONFIG_IWLWIFI_HT */
3892                                 /* assoc_id is 0 no association */
3893                                 if (!priv->assoc_id)
3894                                         break;
3895                                 if (priv->beacon_int)
3896                                         queue_work(priv->workqueue,
3897                                             &priv->post_associate.work);
3898                                 else
3899                                         priv->call_post_assoc_from_beacon = 1;
3900                         }
3901
3902                         break;
3903
3904                 case IEEE80211_STYPE_PROBE_REQ:
3905                         if ((priv->iw_mode == IEEE80211_IF_TYPE_IBSS) &&
3906                             !iwl_is_associated(priv)) {
3907                                 DECLARE_MAC_BUF(mac1);
3908                                 DECLARE_MAC_BUF(mac2);
3909                                 DECLARE_MAC_BUF(mac3);
3910
3911                                 IWL_DEBUG_DROP("Dropping (non network): "
3912                                                "%s, %s, %s\n",
3913                                                print_mac(mac1, header->addr1),
3914                                                print_mac(mac2, header->addr2),
3915                                                print_mac(mac3, header->addr3));
3916                                 return;
3917                         }
3918                 }
3919                 iwl4965_handle_data_packet(priv, 0, include_phy, rxb, &stats);
3920                 break;
3921
3922         case IEEE80211_FTYPE_CTL:
3923 #ifdef CONFIG_IWLWIFI_HT_AGG
3924                 switch (fc & IEEE80211_FCTL_STYPE) {
3925                 case IEEE80211_STYPE_BACK_REQ:
3926                         IWL_DEBUG_HT("IEEE80211_STYPE_BACK_REQ arrived\n");
3927                         iwl4965_handle_data_packet(priv, 0, include_phy,
3928                                                 rxb, &stats);
3929                         break;
3930                 default:
3931                         break;
3932                 }
3933 #endif
3934
3935                 break;
3936
3937         case IEEE80211_FTYPE_DATA: {
3938                 DECLARE_MAC_BUF(mac1);
3939                 DECLARE_MAC_BUF(mac2);
3940                 DECLARE_MAC_BUF(mac3);
3941
3942                 if (priv->iw_mode == IEEE80211_IF_TYPE_AP)
3943                         iwl4965_update_ps_mode(priv, fc  & IEEE80211_FCTL_PM,
3944                                                 header->addr2);
3945
3946                 if (unlikely(!network_packet))
3947                         IWL_DEBUG_DROP("Dropping (non network): "
3948                                        "%s, %s, %s\n",
3949                                        print_mac(mac1, header->addr1),
3950                                        print_mac(mac2, header->addr2),
3951                                        print_mac(mac3, header->addr3));
3952                 else if (unlikely(is_duplicate_packet(priv, header)))
3953                         IWL_DEBUG_DROP("Dropping (dup): %s, %s, %s\n",
3954                                        print_mac(mac1, header->addr1),
3955                                        print_mac(mac2, header->addr2),
3956                                        print_mac(mac3, header->addr3));
3957                 else
3958                         iwl4965_handle_data_packet(priv, 1, include_phy, rxb,
3959                                                    &stats);
3960                 break;
3961         }
3962         default:
3963                 break;
3964
3965         }
3966 }
3967
3968 /* Cache phy data (Rx signal strength, etc) for HT frame (REPLY_RX_PHY_CMD).
3969  * This will be used later in iwl4965_rx_reply_rx() for REPLY_RX_MPDU_CMD. */
3970 static void iwl4965_rx_reply_rx_phy(struct iwl_priv *priv,
3971                                     struct iwl_rx_mem_buffer *rxb)
3972 {
3973         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
3974         priv->last_phy_res[0] = 1;
3975         memcpy(&priv->last_phy_res[1], &(pkt->u.raw[0]),
3976                sizeof(struct iwl4965_rx_phy_res));
3977 }
3978
3979 static void iwl4965_rx_missed_beacon_notif(struct iwl_priv *priv,
3980                                            struct iwl_rx_mem_buffer *rxb)
3981
3982 {
3983 #ifdef CONFIG_IWLWIFI_SENSITIVITY
3984         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
3985         struct iwl_missed_beacon_notif *missed_beacon;
3986
3987         missed_beacon = &pkt->u.missed_beacon;
3988         if (le32_to_cpu(missed_beacon->consequtive_missed_beacons) > 5) {
3989                 IWL_DEBUG_CALIB("missed bcn cnsq %d totl %d rcd %d expctd %d\n",
3990                     le32_to_cpu(missed_beacon->consequtive_missed_beacons),
3991                     le32_to_cpu(missed_beacon->total_missed_becons),
3992                     le32_to_cpu(missed_beacon->num_recvd_beacons),
3993                     le32_to_cpu(missed_beacon->num_expected_beacons));
3994                 priv->sensitivity_data.state = IWL_SENS_CALIB_NEED_REINIT;
3995                 if (unlikely(!test_bit(STATUS_SCANNING, &priv->status)))
3996                         queue_work(priv->workqueue, &priv->sensitivity_work);
3997         }
3998 #endif /*CONFIG_IWLWIFI_SENSITIVITY*/
3999 }
4000
4001 #ifdef CONFIG_IWLWIFI_HT
4002 #ifdef CONFIG_IWLWIFI_HT_AGG
4003
4004 static void iwl4965_set_tx_status(struct iwl_priv *priv, int txq_id, int idx,
4005                                   u32 status, u32 retry_count, u32 rate)
4006 {
4007         struct ieee80211_tx_status *tx_status =
4008                 &(priv->txq[txq_id].txb[idx].status);
4009
4010         tx_status->flags = status ? IEEE80211_TX_STATUS_ACK : 0;
4011         tx_status->retry_count += retry_count;
4012         tx_status->control.tx_rate = rate;
4013 }
4014
4015
4016 static void iwl_sta_modify_enable_tid_tx(struct iwl_priv *priv,
4017                                          int sta_id, int tid)
4018 {
4019         unsigned long flags;
4020
4021         spin_lock_irqsave(&priv->sta_lock, flags);
4022         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_TID_DISABLE_TX;
4023         priv->stations[sta_id].sta.tid_disable_tx &= cpu_to_le16(~(1 << tid));
4024         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
4025         spin_unlock_irqrestore(&priv->sta_lock, flags);
4026
4027         iwl_send_add_station(priv, &priv->stations[sta_id].sta, CMD_ASYNC);
4028 }
4029
4030
4031 static int iwl4965_tx_status_reply_compressed_ba(struct iwl_priv *priv,
4032                                                  struct iwl_ht_agg *agg,
4033                                                  struct iwl_compressed_ba_resp*
4034                                                  ba_resp)
4035
4036 {
4037         int i, sh, ack;
4038         u16 ba_seq_ctl = le16_to_cpu(ba_resp->ba_seq_ctl);
4039         u32 bitmap0, bitmap1;
4040         u32 resp_bitmap0 = le32_to_cpu(ba_resp->ba_bitmap0);
4041         u32 resp_bitmap1 = le32_to_cpu(ba_resp->ba_bitmap1);
4042
4043         if (unlikely(!agg->wait_for_ba))  {
4044                 IWL_ERROR("Received BA when not expected\n");
4045                 return -EINVAL;
4046         }
4047         agg->wait_for_ba = 0;
4048         IWL_DEBUG_TX_REPLY("BA %d %d\n", agg->start_idx, ba_resp->ba_seq_ctl);
4049         sh = agg->start_idx - SEQ_TO_INDEX(ba_seq_ctl>>4);
4050         if (sh < 0) /* tbw something is wrong with indices */
4051                 sh += 0x100;
4052
4053         /* don't use 64 bits for now */
4054         bitmap0 = resp_bitmap0 >> sh;
4055         bitmap1 = resp_bitmap1 >> sh;
4056         bitmap0 |= (resp_bitmap1 & ((1<<sh)|((1<<sh)-1))) << (32 - sh);
4057
4058         if (agg->frame_count > (64 - sh)) {
4059                 IWL_DEBUG_TX_REPLY("more frames than bitmap size");
4060                 return -1;
4061         }
4062
4063         /* check for success or failure according to the
4064          * transmitted bitmap and back bitmap */
4065         bitmap0 &= agg->bitmap0;
4066         bitmap1 &= agg->bitmap1;
4067
4068         for (i = 0; i < agg->frame_count ; i++) {
4069                 int idx = (agg->start_idx + i) & 0xff;
4070                 ack = bitmap0 & (1 << i);
4071                 IWL_DEBUG_TX_REPLY("%s ON i=%d idx=%d raw=%d\n",
4072                         ack? "ACK":"NACK", i, idx, agg->start_idx + i);
4073                 iwl4965_set_tx_status(priv, agg->txq_id, idx, ack, 0,
4074                         agg->rate_n_flags);
4075
4076         }
4077
4078         IWL_DEBUG_TX_REPLY("Bitmap %x%x\n", bitmap0, bitmap1);
4079
4080         return 0;
4081 }
4082
4083 static inline int iwl_queue_dec_wrap(int index, int n_bd)
4084 {
4085         return (index == 0) ? n_bd - 1 : index - 1;
4086 }
4087
4088 static void iwl4965_rx_reply_compressed_ba(struct iwl_priv *priv,
4089                                            struct iwl_rx_mem_buffer *rxb)
4090 {
4091         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
4092         struct iwl_compressed_ba_resp *ba_resp = &pkt->u.compressed_ba;
4093         int index;
4094         struct iwl_tx_queue *txq = NULL;
4095         struct iwl_ht_agg *agg;
4096         u16 ba_resp_scd_flow = le16_to_cpu(ba_resp->scd_flow);
4097         u16 ba_resp_scd_ssn = le16_to_cpu(ba_resp->scd_ssn);
4098
4099         if (ba_resp_scd_flow >= ARRAY_SIZE(priv->txq)) {
4100                 IWL_ERROR("BUG_ON scd_flow is bigger than number of queues");
4101                 return;
4102         }
4103
4104         txq = &priv->txq[ba_resp_scd_flow];
4105         agg = &priv->stations[ba_resp->sta_id].tid[ba_resp->tid].agg;
4106         index = iwl_queue_dec_wrap(ba_resp_scd_ssn & 0xff, txq->q.n_bd);
4107
4108         /* TODO: Need to get this copy more safely - now good for debug */
4109 /*
4110         {
4111         DECLARE_MAC_BUF(mac);
4112         IWL_DEBUG_TX_REPLY("REPLY_COMPRESSED_BA [%d]Received from %s, "
4113                            "sta_id = %d\n",
4114                            agg->wait_for_ba,
4115                            print_mac(mac, (u8*) &ba_resp->sta_addr_lo32),
4116                            ba_resp->sta_id);
4117         IWL_DEBUG_TX_REPLY("TID = %d, SeqCtl = %d, bitmap = 0x%X%X, scd_flow = "
4118                            "%d, scd_ssn = %d\n",
4119                            ba_resp->tid,
4120                            ba_resp->ba_seq_ctl,
4121                            ba_resp->ba_bitmap1,
4122                            ba_resp->ba_bitmap0,
4123                            ba_resp->scd_flow,
4124                            ba_resp->scd_ssn);
4125         IWL_DEBUG_TX_REPLY("DAT start_idx = %d, bitmap = 0x%X%X \n",
4126                            agg->start_idx,
4127                            agg->bitmap1,
4128                            agg->bitmap0);
4129         }
4130 */
4131         iwl4965_tx_status_reply_compressed_ba(priv, agg, ba_resp);
4132         /* releases all the TFDs until the SSN */
4133         if (txq->q.read_ptr != (ba_resp_scd_ssn & 0xff))
4134                 iwl_tx_queue_reclaim(priv, ba_resp_scd_flow, index);
4135
4136 }
4137
4138
4139 static void iwl4965_tx_queue_stop_scheduler(struct iwl_priv *priv, u16 txq_id)
4140 {
4141         iwl_write_prph(priv,
4142                 SCD_QUEUE_STATUS_BITS(txq_id),
4143                 (0 << SCD_QUEUE_STTS_REG_POS_ACTIVE)|
4144                 (1 << SCD_QUEUE_STTS_REG_POS_SCD_ACT_EN));
4145 }
4146
4147 static int iwl4965_tx_queue_set_q2ratid(struct iwl_priv *priv, u16 ra_tid,
4148                                         u16 txq_id)
4149 {
4150         u32 tbl_dw_addr;
4151         u32 tbl_dw;
4152         u16 scd_q2ratid;
4153
4154         scd_q2ratid = ra_tid & SCD_QUEUE_RA_TID_MAP_RATID_MSK;
4155
4156         tbl_dw_addr = priv->scd_base_addr +
4157                         SCD_TRANSLATE_TBL_OFFSET_QUEUE(txq_id);
4158
4159         tbl_dw = iwl_read_restricted_mem(priv, tbl_dw_addr);
4160
4161         if (txq_id & 0x1)
4162                 tbl_dw = (scd_q2ratid << 16) | (tbl_dw & 0x0000FFFF);
4163         else
4164                 tbl_dw = scd_q2ratid | (tbl_dw & 0xFFFF0000);
4165
4166         iwl_write_restricted_mem(priv, tbl_dw_addr, tbl_dw);
4167
4168         return 0;
4169 }
4170
4171 /**
4172  * txq_id must be greater than IWL_BACK_QUEUE_FIRST_ID
4173  */
4174 static int iwl4965_tx_queue_agg_enable(struct iwl_priv *priv, int txq_id,
4175                                        int tx_fifo, int sta_id, int tid,
4176                                        u16 ssn_idx)
4177 {
4178         unsigned long flags;
4179         int rc;
4180         u16 ra_tid;
4181
4182         if (IWL_BACK_QUEUE_FIRST_ID > txq_id)
4183                 IWL_WARNING("queue number too small: %d, must be > %d\n",
4184                         txq_id, IWL_BACK_QUEUE_FIRST_ID);
4185
4186         ra_tid = BUILD_RAxTID(sta_id, tid);
4187
4188         iwl_sta_modify_enable_tid_tx(priv, sta_id, tid);
4189
4190         spin_lock_irqsave(&priv->lock, flags);
4191         rc = iwl_grab_restricted_access(priv);
4192         if (rc) {
4193                 spin_unlock_irqrestore(&priv->lock, flags);
4194                 return rc;
4195         }
4196
4197         iwl4965_tx_queue_stop_scheduler(priv, txq_id);
4198
4199         iwl4965_tx_queue_set_q2ratid(priv, ra_tid, txq_id);
4200
4201
4202         iwl_set_bits_prph(priv, SCD_QUEUECHAIN_SEL, (1<<txq_id));
4203
4204         priv->txq[txq_id].q.read_ptr = (ssn_idx & 0xff);
4205         priv->txq[txq_id].q.write_ptr = (ssn_idx & 0xff);
4206
4207         /* supposes that ssn_idx is valid (!= 0xFFF) */
4208         iwl4965_set_wr_ptrs(priv, txq_id, ssn_idx);
4209
4210         iwl_write_restricted_mem(priv,
4211                         priv->scd_base_addr + SCD_CONTEXT_QUEUE_OFFSET(txq_id),
4212                         (SCD_WIN_SIZE << SCD_QUEUE_CTX_REG1_WIN_SIZE_POS) &
4213                         SCD_QUEUE_CTX_REG1_WIN_SIZE_MSK);
4214
4215         iwl_write_restricted_mem(priv, priv->scd_base_addr +
4216                         SCD_CONTEXT_QUEUE_OFFSET(txq_id) + sizeof(u32),
4217                         (SCD_FRAME_LIMIT << SCD_QUEUE_CTX_REG2_FRAME_LIMIT_POS)
4218                         & SCD_QUEUE_CTX_REG2_FRAME_LIMIT_MSK);
4219
4220         iwl_set_bits_prph(priv, SCD_INTERRUPT_MASK, (1 << txq_id));
4221
4222         iwl4965_tx_queue_set_status(priv, &priv->txq[txq_id], tx_fifo, 1);
4223
4224         iwl_release_restricted_access(priv);
4225         spin_unlock_irqrestore(&priv->lock, flags);
4226
4227         return 0;
4228 }
4229
4230 /**
4231  * txq_id must be greater than IWL_BACK_QUEUE_FIRST_ID
4232  */
4233 static int iwl4965_tx_queue_agg_disable(struct iwl_priv *priv, u16 txq_id,
4234                                         u16 ssn_idx, u8 tx_fifo)
4235 {
4236         unsigned long flags;
4237         int rc;
4238
4239         if (IWL_BACK_QUEUE_FIRST_ID > txq_id) {
4240                 IWL_WARNING("queue number too small: %d, must be > %d\n",
4241                                 txq_id, IWL_BACK_QUEUE_FIRST_ID);
4242                 return -EINVAL;
4243         }
4244
4245         spin_lock_irqsave(&priv->lock, flags);
4246         rc = iwl_grab_restricted_access(priv);
4247         if (rc) {
4248                 spin_unlock_irqrestore(&priv->lock, flags);
4249                 return rc;
4250         }
4251
4252         iwl4965_tx_queue_stop_scheduler(priv, txq_id);
4253
4254         iwl_clear_bits_prph(priv, SCD_QUEUECHAIN_SEL, (1 << txq_id));
4255
4256         priv->txq[txq_id].q.read_ptr = (ssn_idx & 0xff);
4257         priv->txq[txq_id].q.write_ptr = (ssn_idx & 0xff);
4258         /* supposes that ssn_idx is valid (!= 0xFFF) */
4259         iwl4965_set_wr_ptrs(priv, txq_id, ssn_idx);
4260
4261         iwl_clear_bits_prph(priv, SCD_INTERRUPT_MASK, (1 << txq_id));
4262         iwl4965_txq_ctx_deactivate(priv, txq_id);
4263         iwl4965_tx_queue_set_status(priv, &priv->txq[txq_id], tx_fifo, 0);
4264
4265         iwl_release_restricted_access(priv);
4266         spin_unlock_irqrestore(&priv->lock, flags);
4267
4268         return 0;
4269 }
4270
4271 #endif/* CONFIG_IWLWIFI_HT_AGG */
4272 #endif /* CONFIG_IWLWIFI_HT */
4273 /*
4274  * RATE SCALE CODE
4275  */
4276 int iwl4965_init_hw_rates(struct iwl_priv *priv, struct ieee80211_rate *rates)
4277 {
4278         return 0;
4279 }
4280
4281
4282 /**
4283  * iwl4965_add_station - Initialize a station's hardware rate table
4284  *
4285  * The uCode contains a table of fallback rates and retries per rate
4286  * for automatic fallback during transmission.
4287  *
4288  * NOTE: This initializes the table for a single retry per data rate
4289  * which is not optimal.  Setting up an intelligent retry per rate
4290  * requires feedback from transmission, which isn't exposed through
4291  * rc80211_simple which is what this driver is currently using.
4292  *
4293  */
4294 void iwl4965_add_station(struct iwl_priv *priv, const u8 *addr, int is_ap)
4295 {
4296         int i, r;
4297         struct iwl_link_quality_cmd link_cmd = {
4298                 .reserved1 = 0,
4299         };
4300         u16 rate_flags;
4301
4302         /* Set up the rate scaling to start at 54M and fallback
4303          * all the way to 1M in IEEE order and then spin on IEEE */
4304         if (is_ap)
4305                 r = IWL_RATE_54M_INDEX;
4306         else if (priv->phymode == MODE_IEEE80211A)
4307                 r = IWL_RATE_6M_INDEX;
4308         else
4309                 r = IWL_RATE_1M_INDEX;
4310
4311         for (i = 0; i < LINK_QUAL_MAX_RETRY_NUM; i++) {
4312                 rate_flags = 0;
4313                 if (r >= IWL_FIRST_CCK_RATE && r <= IWL_LAST_CCK_RATE)
4314                         rate_flags |= RATE_MCS_CCK_MSK;
4315
4316                 rate_flags |= RATE_MCS_ANT_B_MSK;
4317                 rate_flags &= ~RATE_MCS_ANT_A_MSK;
4318                 link_cmd.rs_table[i].rate_n_flags =
4319                         iwl_hw_set_rate_n_flags(iwl_rates[r].plcp, rate_flags);
4320                 r = iwl_get_prev_ieee_rate(r);
4321         }
4322
4323         link_cmd.general_params.single_stream_ant_msk = 2;
4324         link_cmd.general_params.dual_stream_ant_msk = 3;
4325         link_cmd.agg_params.agg_dis_start_th = 3;
4326         link_cmd.agg_params.agg_time_limit = cpu_to_le16(4000);
4327
4328         /* Update the rate scaling for control frame Tx to AP */
4329         link_cmd.sta_id = is_ap ? IWL_AP_ID : IWL4965_BROADCAST_ID;
4330
4331         iwl_send_cmd_pdu(priv, REPLY_TX_LINK_QUALITY_CMD, sizeof(link_cmd),
4332                          &link_cmd);
4333 }
4334
4335 #ifdef CONFIG_IWLWIFI_HT
4336
4337 static u8 iwl_is_channel_extension(struct iwl_priv *priv, int phymode,
4338                                    u16 channel, u8 extension_chan_offset)
4339 {
4340         const struct iwl_channel_info *ch_info;
4341
4342         ch_info = iwl_get_channel_info(priv, phymode, channel);
4343         if (!is_channel_valid(ch_info))
4344                 return 0;
4345
4346         if (extension_chan_offset == IWL_EXT_CHANNEL_OFFSET_AUTO)
4347                 return 0;
4348
4349         if ((ch_info->fat_extension_channel == extension_chan_offset) ||
4350             (ch_info->fat_extension_channel == HT_IE_EXT_CHANNEL_MAX))
4351                 return 1;
4352
4353         return 0;
4354 }
4355
4356 static u8 iwl_is_fat_tx_allowed(struct iwl_priv *priv,
4357                                 const struct sta_ht_info *ht_info)
4358 {
4359
4360         if (priv->channel_width != IWL_CHANNEL_WIDTH_40MHZ)
4361                 return 0;
4362
4363         if (ht_info->supported_chan_width != IWL_CHANNEL_WIDTH_40MHZ)
4364                 return 0;
4365
4366         if (ht_info->extension_chan_offset == IWL_EXT_CHANNEL_OFFSET_AUTO)
4367                 return 0;
4368
4369         /* no fat tx allowed on 2.4GHZ */
4370         if (priv->phymode != MODE_IEEE80211A)
4371                 return 0;
4372         return (iwl_is_channel_extension(priv, priv->phymode,
4373                                          ht_info->control_channel,
4374                                          ht_info->extension_chan_offset));
4375 }
4376
4377 void iwl4965_set_rxon_ht(struct iwl_priv *priv, struct sta_ht_info *ht_info)
4378 {
4379         struct iwl_rxon_cmd *rxon = &priv->staging_rxon;
4380         u32 val;
4381
4382         if (!ht_info->is_ht)
4383                 return;
4384
4385         if (iwl_is_fat_tx_allowed(priv, ht_info))
4386                 rxon->flags |= RXON_FLG_CHANNEL_MODE_MIXED_MSK;
4387         else
4388                 rxon->flags &= ~(RXON_FLG_CHANNEL_MODE_MIXED_MSK |
4389                                  RXON_FLG_CHANNEL_MODE_PURE_40_MSK);
4390
4391         if (le16_to_cpu(rxon->channel) != ht_info->control_channel) {
4392                 IWL_DEBUG_ASSOC("control diff than current %d %d\n",
4393                                 le16_to_cpu(rxon->channel),
4394                                 ht_info->control_channel);
4395                 rxon->channel = cpu_to_le16(ht_info->control_channel);
4396                 return;
4397         }
4398
4399         /* Note: control channel is oposit to extension channel */
4400         switch (ht_info->extension_chan_offset) {
4401         case IWL_EXT_CHANNEL_OFFSET_ABOVE:
4402                 rxon->flags &= ~(RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK);
4403                 break;
4404         case IWL_EXT_CHANNEL_OFFSET_BELOW:
4405                 rxon->flags |= RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
4406                 break;
4407         case IWL_EXT_CHANNEL_OFFSET_AUTO:
4408                 rxon->flags &= ~RXON_FLG_CHANNEL_MODE_MIXED_MSK;
4409                 break;
4410         default:
4411                 rxon->flags &= ~RXON_FLG_CHANNEL_MODE_MIXED_MSK;
4412                 break;
4413         }
4414
4415         val = ht_info->operating_mode;
4416
4417         rxon->flags |= cpu_to_le32(val << RXON_FLG_HT_OPERATING_MODE_POS);
4418
4419         priv->active_rate_ht[0] = ht_info->supp_rates[0];
4420         priv->active_rate_ht[1] = ht_info->supp_rates[1];
4421         iwl4965_set_rxon_chain(priv);
4422
4423         IWL_DEBUG_ASSOC("supported HT rate 0x%X %X "
4424                         "rxon flags 0x%X operation mode :0x%X "
4425                         "extension channel offset 0x%x "
4426                         "control chan %d\n",
4427                         priv->active_rate_ht[0], priv->active_rate_ht[1],
4428                         le32_to_cpu(rxon->flags), ht_info->operating_mode,
4429                         ht_info->extension_chan_offset,
4430                         ht_info->control_channel);
4431         return;
4432 }
4433
4434 void iwl4965_set_ht_add_station(struct iwl_priv *priv, u8 index)
4435 {
4436         __le32 sta_flags;
4437         struct sta_ht_info *ht_info = &priv->current_assoc_ht;
4438
4439         priv->current_channel_width = IWL_CHANNEL_WIDTH_20MHZ;
4440         if (!ht_info->is_ht)
4441                 goto done;
4442
4443         sta_flags = priv->stations[index].sta.station_flags;
4444
4445         if (ht_info->tx_mimo_ps_mode == IWL_MIMO_PS_DYNAMIC)
4446                 sta_flags |= STA_FLG_RTS_MIMO_PROT_MSK;
4447         else
4448                 sta_flags &= ~STA_FLG_RTS_MIMO_PROT_MSK;
4449
4450         sta_flags |= cpu_to_le32(
4451                 (u32)ht_info->ampdu_factor << STA_FLG_MAX_AGG_SIZE_POS);
4452
4453         sta_flags |= cpu_to_le32(
4454                 (u32)ht_info->mpdu_density << STA_FLG_AGG_MPDU_DENSITY_POS);
4455
4456         sta_flags &= (~STA_FLG_FAT_EN_MSK);
4457         ht_info->tx_chan_width = IWL_CHANNEL_WIDTH_20MHZ;
4458         ht_info->chan_width_cap = IWL_CHANNEL_WIDTH_20MHZ;
4459
4460         if (iwl_is_fat_tx_allowed(priv, ht_info)) {
4461                 sta_flags |= STA_FLG_FAT_EN_MSK;
4462                 ht_info->chan_width_cap = IWL_CHANNEL_WIDTH_40MHZ;
4463                 if (ht_info->supported_chan_width == IWL_CHANNEL_WIDTH_40MHZ)
4464                         ht_info->tx_chan_width = IWL_CHANNEL_WIDTH_40MHZ;
4465         }
4466         priv->current_channel_width = ht_info->tx_chan_width;
4467         priv->stations[index].sta.station_flags = sta_flags;
4468  done:
4469         return;
4470 }
4471
4472 #ifdef CONFIG_IWLWIFI_HT_AGG
4473
4474 static void iwl4965_sta_modify_add_ba_tid(struct iwl_priv *priv,
4475                                           int sta_id, int tid, u16 ssn)
4476 {
4477         unsigned long flags;
4478
4479         spin_lock_irqsave(&priv->sta_lock, flags);
4480         priv->stations[sta_id].sta.station_flags_msk = 0;
4481         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_ADDBA_TID_MSK;
4482         priv->stations[sta_id].sta.add_immediate_ba_tid = (u8)tid;
4483         priv->stations[sta_id].sta.add_immediate_ba_ssn = cpu_to_le16(ssn);
4484         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
4485         spin_unlock_irqrestore(&priv->sta_lock, flags);
4486
4487         iwl_send_add_station(priv, &priv->stations[sta_id].sta, CMD_ASYNC);
4488 }
4489
4490 static void iwl4965_sta_modify_del_ba_tid(struct iwl_priv *priv,
4491                                           int sta_id, int tid)
4492 {
4493         unsigned long flags;
4494
4495         spin_lock_irqsave(&priv->sta_lock, flags);
4496         priv->stations[sta_id].sta.station_flags_msk = 0;
4497         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_DELBA_TID_MSK;
4498         priv->stations[sta_id].sta.remove_immediate_ba_tid = (u8)tid;
4499         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
4500         spin_unlock_irqrestore(&priv->sta_lock, flags);
4501
4502         iwl_send_add_station(priv, &priv->stations[sta_id].sta, CMD_ASYNC);
4503 }
4504
4505 static const u16 default_tid_to_tx_fifo[] = {
4506         IWL_TX_FIFO_AC1,
4507         IWL_TX_FIFO_AC0,
4508         IWL_TX_FIFO_AC0,
4509         IWL_TX_FIFO_AC1,
4510         IWL_TX_FIFO_AC2,
4511         IWL_TX_FIFO_AC2,
4512         IWL_TX_FIFO_AC3,
4513         IWL_TX_FIFO_AC3,
4514         IWL_TX_FIFO_NONE,
4515         IWL_TX_FIFO_NONE,
4516         IWL_TX_FIFO_NONE,
4517         IWL_TX_FIFO_NONE,
4518         IWL_TX_FIFO_NONE,
4519         IWL_TX_FIFO_NONE,
4520         IWL_TX_FIFO_NONE,
4521         IWL_TX_FIFO_NONE,
4522         IWL_TX_FIFO_AC3
4523 };
4524
4525 static int iwl_txq_ctx_activate_free(struct iwl_priv *priv)
4526 {
4527         int txq_id;
4528
4529         for (txq_id = 0; txq_id < priv->hw_setting.max_txq_num; txq_id++)
4530                 if (!test_and_set_bit(txq_id, &priv->txq_ctx_active_msk))
4531                         return txq_id;
4532         return -1;
4533 }
4534
4535 int iwl_mac_ht_tx_agg_start(struct ieee80211_hw *hw, u8 *da, u16 tid,
4536                             u16 *start_seq_num)
4537 {
4538
4539         struct iwl_priv *priv = hw->priv;
4540         int sta_id;
4541         int tx_fifo;
4542         int txq_id;
4543         int ssn = -1;
4544         unsigned long flags;
4545         struct iwl_tid_data *tid_data;
4546         DECLARE_MAC_BUF(mac);
4547
4548         if (likely(tid < ARRAY_SIZE(default_tid_to_tx_fifo)))
4549                 tx_fifo = default_tid_to_tx_fifo[tid];
4550         else
4551                 return -EINVAL;
4552
4553         IWL_WARNING("iwl-AGG iwl_mac_ht_tx_agg_start on da=%s"
4554                     " tid=%d\n", print_mac(mac, da), tid);
4555
4556         sta_id = iwl_hw_find_station(priv, da);
4557         if (sta_id == IWL_INVALID_STATION)
4558                 return -ENXIO;
4559
4560         txq_id = iwl_txq_ctx_activate_free(priv);
4561         if (txq_id == -1)
4562                 return -ENXIO;
4563
4564         spin_lock_irqsave(&priv->sta_lock, flags);
4565         tid_data = &priv->stations[sta_id].tid[tid];
4566         ssn = SEQ_TO_SN(tid_data->seq_number);
4567         tid_data->agg.txq_id = txq_id;
4568         spin_unlock_irqrestore(&priv->sta_lock, flags);
4569
4570         *start_seq_num = ssn;
4571         iwl4965_ba_status(priv, tid, BA_STATUS_ACTIVE);
4572         return iwl4965_tx_queue_agg_enable(priv, txq_id, tx_fifo,
4573                                            sta_id, tid, ssn);
4574 }
4575
4576
4577 int iwl_mac_ht_tx_agg_stop(struct ieee80211_hw *hw, u8 *da, u16 tid,
4578                            int generator)
4579 {
4580
4581         struct iwl_priv *priv = hw->priv;
4582         int tx_fifo_id, txq_id, sta_id, ssn = -1;
4583         struct iwl_tid_data *tid_data;
4584         int rc;
4585         DECLARE_MAC_BUF(mac);
4586
4587         if (!da) {
4588                 IWL_ERROR("%s: da = NULL\n", __func__);
4589                 return -EINVAL;
4590         }
4591
4592         if (likely(tid < ARRAY_SIZE(default_tid_to_tx_fifo)))
4593                 tx_fifo_id = default_tid_to_tx_fifo[tid];
4594         else
4595                 return -EINVAL;
4596
4597         sta_id = iwl_hw_find_station(priv, da);
4598
4599         if (sta_id == IWL_INVALID_STATION)
4600                 return -ENXIO;
4601
4602         tid_data = &priv->stations[sta_id].tid[tid];
4603         ssn = (tid_data->seq_number & IEEE80211_SCTL_SEQ) >> 4;
4604         txq_id = tid_data->agg.txq_id;
4605
4606         rc = iwl4965_tx_queue_agg_disable(priv, txq_id, ssn, tx_fifo_id);
4607         /* FIXME: need more safe way to handle error condition */
4608         if (rc)
4609                 return rc;
4610
4611         iwl4965_ba_status(priv, tid, BA_STATUS_INITIATOR_DELBA);
4612         IWL_DEBUG_INFO("iwl_mac_ht_tx_agg_stop on da=%s tid=%d\n",
4613                        print_mac(mac, da), tid);
4614
4615         return 0;
4616 }
4617
4618 int iwl_mac_ht_rx_agg_start(struct ieee80211_hw *hw, u8 *da,
4619                             u16 tid, u16 start_seq_num)
4620 {
4621         struct iwl_priv *priv = hw->priv;
4622         int sta_id;
4623         DECLARE_MAC_BUF(mac);
4624
4625         IWL_WARNING("iwl-AGG iwl_mac_ht_rx_agg_start on da=%s"
4626                     " tid=%d\n", print_mac(mac, da), tid);
4627         sta_id = iwl_hw_find_station(priv, da);
4628         iwl4965_sta_modify_add_ba_tid(priv, sta_id, tid, start_seq_num);
4629         return 0;
4630 }
4631
4632 int iwl_mac_ht_rx_agg_stop(struct ieee80211_hw *hw, u8 *da,
4633                            u16 tid, int generator)
4634 {
4635         struct iwl_priv *priv = hw->priv;
4636         int sta_id;
4637         DECLARE_MAC_BUF(mac);
4638
4639         IWL_WARNING("iwl-AGG iwl_mac_ht_rx_agg_stop on da=%s tid=%d\n",
4640                     print_mac(mac, da), tid);
4641         sta_id = iwl_hw_find_station(priv, da);
4642         iwl4965_sta_modify_del_ba_tid(priv, sta_id, tid);
4643         return 0;
4644 }
4645
4646 #endif /* CONFIG_IWLWIFI_HT_AGG */
4647 #endif /* CONFIG_IWLWIFI_HT */
4648
4649 /* Set up 4965-specific Rx frame reply handlers */
4650 void iwl_hw_rx_handler_setup(struct iwl_priv *priv)
4651 {
4652         /* Legacy Rx frames */
4653         priv->rx_handlers[REPLY_4965_RX] = iwl4965_rx_reply_rx;
4654
4655         /* High-throughput (HT) Rx frames */
4656         priv->rx_handlers[REPLY_RX_PHY_CMD] = iwl4965_rx_reply_rx_phy;
4657         priv->rx_handlers[REPLY_RX_MPDU_CMD] = iwl4965_rx_reply_rx;
4658
4659         priv->rx_handlers[MISSED_BEACONS_NOTIFICATION] =
4660             iwl4965_rx_missed_beacon_notif;
4661
4662 #ifdef CONFIG_IWLWIFI_HT
4663 #ifdef CONFIG_IWLWIFI_HT_AGG
4664         priv->rx_handlers[REPLY_COMPRESSED_BA] = iwl4965_rx_reply_compressed_ba;
4665 #endif /* CONFIG_IWLWIFI_AGG */
4666 #endif /* CONFIG_IWLWIFI */
4667 }
4668
4669 void iwl_hw_setup_deferred_work(struct iwl_priv *priv)
4670 {
4671         INIT_WORK(&priv->txpower_work, iwl4965_bg_txpower_work);
4672         INIT_WORK(&priv->statistics_work, iwl4965_bg_statistics_work);
4673 #ifdef CONFIG_IWLWIFI_SENSITIVITY
4674         INIT_WORK(&priv->sensitivity_work, iwl4965_bg_sensitivity_work);
4675 #endif
4676 #ifdef CONFIG_IWLWIFI_HT
4677 #ifdef CONFIG_IWLWIFI_HT_AGG
4678         INIT_WORK(&priv->agg_work, iwl4965_bg_agg_work);
4679 #endif /* CONFIG_IWLWIFI_AGG */
4680 #endif /* CONFIG_IWLWIFI_HT */
4681         init_timer(&priv->statistics_periodic);
4682         priv->statistics_periodic.data = (unsigned long)priv;
4683         priv->statistics_periodic.function = iwl4965_bg_statistics_periodic;
4684 }
4685
4686 void iwl_hw_cancel_deferred_work(struct iwl_priv *priv)
4687 {
4688         del_timer_sync(&priv->statistics_periodic);
4689
4690         cancel_delayed_work(&priv->init_alive_start);
4691 }
4692
4693 struct pci_device_id iwl_hw_card_ids[] = {
4694         {PCI_DEVICE(0x8086, 0x4229)},
4695         {PCI_DEVICE(0x8086, 0x4230)},
4696         {0}
4697 };
4698
4699 int iwl_eeprom_acquire_semaphore(struct iwl_priv *priv)
4700 {
4701         u16 count;
4702         int rc;
4703
4704         for (count = 0; count < EEPROM_SEM_RETRY_LIMIT; count++) {
4705                 iwl_set_bit(priv, CSR_HW_IF_CONFIG_REG,
4706                         CSR_HW_IF_CONFIG_REG_BIT_EEPROM_OWN_SEM);
4707                 rc = iwl_poll_bit(priv, CSR_HW_IF_CONFIG_REG,
4708                                         CSR_HW_IF_CONFIG_REG_BIT_EEPROM_OWN_SEM,
4709                                         CSR_HW_IF_CONFIG_REG_BIT_EEPROM_OWN_SEM,
4710                                         EEPROM_SEM_TIMEOUT);
4711                 if (rc >= 0) {
4712                         IWL_DEBUG_IO("Acquired semaphore after %d tries.\n",
4713                                 count+1);
4714                         return rc;
4715                 }
4716         }
4717
4718         return rc;
4719 }
4720
4721 inline void iwl_eeprom_release_semaphore(struct iwl_priv *priv)
4722 {
4723         iwl_clear_bit(priv, CSR_HW_IF_CONFIG_REG,
4724                 CSR_HW_IF_CONFIG_REG_BIT_EEPROM_OWN_SEM);
4725 }
4726
4727
4728 MODULE_DEVICE_TABLE(pci, iwl_hw_card_ids);