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