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