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