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