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