]> err.no Git - linux-2.6/blob - drivers/net/wireless/iwlwifi/iwl-4965.c
iwlwifi: fix spinlock used before initialized
[linux-2.6] / drivers / net / wireless / iwlwifi / iwl-4965.c
1 /******************************************************************************
2  *
3  * Copyright(c) 2003 - 2008 Intel Corporation. All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of version 2 of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  *
14  * You should have received a copy of the GNU General Public License along with
15  * this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
17  *
18  * The full GNU General Public License is included in this distribution in the
19  * file called LICENSE.
20  *
21  * Contact Information:
22  * James P. Ketrenos <ipw2100-admin@linux.intel.com>
23  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
24  *
25  *****************************************************************************/
26
27 #include <linux/kernel.h>
28 #include <linux/module.h>
29 #include <linux/version.h>
30 #include <linux/init.h>
31 #include <linux/pci.h>
32 #include <linux/dma-mapping.h>
33 #include <linux/delay.h>
34 #include <linux/skbuff.h>
35 #include <linux/netdevice.h>
36 #include <linux/wireless.h>
37 #include <net/mac80211.h>
38 #include <linux/etherdevice.h>
39 #include <asm/unaligned.h>
40
41 #include "iwl-eeprom.h"
42 #include "iwl-dev.h"
43 #include "iwl-core.h"
44 #include "iwl-io.h"
45 #include "iwl-helpers.h"
46 #include "iwl-calib.h"
47
48 /* module parameters */
49 static struct iwl_mod_params iwl4965_mod_params = {
50         .num_of_queues = IWL49_NUM_QUEUES,
51         .enable_qos = 1,
52         .amsdu_size_8K = 1,
53         /* the rest are 0 by default */
54 };
55
56 #ifdef CONFIG_IWL4965_HT
57
58 static const u16 default_tid_to_tx_fifo[] = {
59         IWL_TX_FIFO_AC1,
60         IWL_TX_FIFO_AC0,
61         IWL_TX_FIFO_AC0,
62         IWL_TX_FIFO_AC1,
63         IWL_TX_FIFO_AC2,
64         IWL_TX_FIFO_AC2,
65         IWL_TX_FIFO_AC3,
66         IWL_TX_FIFO_AC3,
67         IWL_TX_FIFO_NONE,
68         IWL_TX_FIFO_NONE,
69         IWL_TX_FIFO_NONE,
70         IWL_TX_FIFO_NONE,
71         IWL_TX_FIFO_NONE,
72         IWL_TX_FIFO_NONE,
73         IWL_TX_FIFO_NONE,
74         IWL_TX_FIFO_NONE,
75         IWL_TX_FIFO_AC3
76 };
77
78 #endif  /*CONFIG_IWL4965_HT */
79
80 /* check contents of special bootstrap uCode SRAM */
81 static int iwl4965_verify_bsm(struct iwl_priv *priv)
82 {
83         __le32 *image = priv->ucode_boot.v_addr;
84         u32 len = priv->ucode_boot.len;
85         u32 reg;
86         u32 val;
87
88         IWL_DEBUG_INFO("Begin verify bsm\n");
89
90         /* verify BSM SRAM contents */
91         val = iwl_read_prph(priv, BSM_WR_DWCOUNT_REG);
92         for (reg = BSM_SRAM_LOWER_BOUND;
93              reg < BSM_SRAM_LOWER_BOUND + len;
94              reg += sizeof(u32), image++) {
95                 val = iwl_read_prph(priv, reg);
96                 if (val != le32_to_cpu(*image)) {
97                         IWL_ERROR("BSM uCode verification failed at "
98                                   "addr 0x%08X+%u (of %u), is 0x%x, s/b 0x%x\n",
99                                   BSM_SRAM_LOWER_BOUND,
100                                   reg - BSM_SRAM_LOWER_BOUND, len,
101                                   val, le32_to_cpu(*image));
102                         return -EIO;
103                 }
104         }
105
106         IWL_DEBUG_INFO("BSM bootstrap uCode image OK\n");
107
108         return 0;
109 }
110
111 /**
112  * iwl4965_load_bsm - Load bootstrap instructions
113  *
114  * BSM operation:
115  *
116  * The Bootstrap State Machine (BSM) stores a short bootstrap uCode program
117  * in special SRAM that does not power down during RFKILL.  When powering back
118  * up after power-saving sleeps (or during initial uCode load), the BSM loads
119  * the bootstrap program into the on-board processor, and starts it.
120  *
121  * The bootstrap program loads (via DMA) instructions and data for a new
122  * program from host DRAM locations indicated by the host driver in the
123  * BSM_DRAM_* registers.  Once the new program is loaded, it starts
124  * automatically.
125  *
126  * When initializing the NIC, the host driver points the BSM to the
127  * "initialize" uCode image.  This uCode sets up some internal data, then
128  * notifies host via "initialize alive" that it is complete.
129  *
130  * The host then replaces the BSM_DRAM_* pointer values to point to the
131  * normal runtime uCode instructions and a backup uCode data cache buffer
132  * (filled initially with starting data values for the on-board processor),
133  * then triggers the "initialize" uCode to load and launch the runtime uCode,
134  * which begins normal operation.
135  *
136  * When doing a power-save shutdown, runtime uCode saves data SRAM into
137  * the backup data cache in DRAM before SRAM is powered down.
138  *
139  * When powering back up, the BSM loads the bootstrap program.  This reloads
140  * the runtime uCode instructions and the backup data cache into SRAM,
141  * and re-launches the runtime uCode from where it left off.
142  */
143 static int iwl4965_load_bsm(struct iwl_priv *priv)
144 {
145         __le32 *image = priv->ucode_boot.v_addr;
146         u32 len = priv->ucode_boot.len;
147         dma_addr_t pinst;
148         dma_addr_t pdata;
149         u32 inst_len;
150         u32 data_len;
151         int i;
152         u32 done;
153         u32 reg_offset;
154         int ret;
155
156         IWL_DEBUG_INFO("Begin load bsm\n");
157
158         /* make sure bootstrap program is no larger than BSM's SRAM size */
159         if (len > IWL_MAX_BSM_SIZE)
160                 return -EINVAL;
161
162         /* Tell bootstrap uCode where to find the "Initialize" uCode
163          *   in host DRAM ... host DRAM physical address bits 35:4 for 4965.
164          * NOTE:  iwl4965_initialize_alive_start() will replace these values,
165          *        after the "initialize" uCode has run, to point to
166          *        runtime/protocol instructions and backup data cache. */
167         pinst = priv->ucode_init.p_addr >> 4;
168         pdata = priv->ucode_init_data.p_addr >> 4;
169         inst_len = priv->ucode_init.len;
170         data_len = priv->ucode_init_data.len;
171
172         ret = iwl_grab_nic_access(priv);
173         if (ret)
174                 return ret;
175
176         iwl_write_prph(priv, BSM_DRAM_INST_PTR_REG, pinst);
177         iwl_write_prph(priv, BSM_DRAM_DATA_PTR_REG, pdata);
178         iwl_write_prph(priv, BSM_DRAM_INST_BYTECOUNT_REG, inst_len);
179         iwl_write_prph(priv, BSM_DRAM_DATA_BYTECOUNT_REG, data_len);
180
181         /* Fill BSM memory with bootstrap instructions */
182         for (reg_offset = BSM_SRAM_LOWER_BOUND;
183              reg_offset < BSM_SRAM_LOWER_BOUND + len;
184              reg_offset += sizeof(u32), image++)
185                 _iwl_write_prph(priv, reg_offset, le32_to_cpu(*image));
186
187         ret = iwl4965_verify_bsm(priv);
188         if (ret) {
189                 iwl_release_nic_access(priv);
190                 return ret;
191         }
192
193         /* Tell BSM to copy from BSM SRAM into instruction SRAM, when asked */
194         iwl_write_prph(priv, BSM_WR_MEM_SRC_REG, 0x0);
195         iwl_write_prph(priv, BSM_WR_MEM_DST_REG, RTC_INST_LOWER_BOUND);
196         iwl_write_prph(priv, BSM_WR_DWCOUNT_REG, len / sizeof(u32));
197
198         /* Load bootstrap code into instruction SRAM now,
199          *   to prepare to load "initialize" uCode */
200         iwl_write_prph(priv, BSM_WR_CTRL_REG, BSM_WR_CTRL_REG_BIT_START);
201
202         /* Wait for load of bootstrap uCode to finish */
203         for (i = 0; i < 100; i++) {
204                 done = iwl_read_prph(priv, BSM_WR_CTRL_REG);
205                 if (!(done & BSM_WR_CTRL_REG_BIT_START))
206                         break;
207                 udelay(10);
208         }
209         if (i < 100)
210                 IWL_DEBUG_INFO("BSM write complete, poll %d iterations\n", i);
211         else {
212                 IWL_ERROR("BSM write did not complete!\n");
213                 return -EIO;
214         }
215
216         /* Enable future boot loads whenever power management unit triggers it
217          *   (e.g. when powering back up after power-save shutdown) */
218         iwl_write_prph(priv, BSM_WR_CTRL_REG, BSM_WR_CTRL_REG_BIT_START_EN);
219
220         iwl_release_nic_access(priv);
221
222         return 0;
223 }
224
225 /**
226  * iwl4965_set_ucode_ptrs - Set uCode address location
227  *
228  * Tell initialization uCode where to find runtime uCode.
229  *
230  * BSM registers initially contain pointers to initialization uCode.
231  * We need to replace them to load runtime uCode inst and data,
232  * and to save runtime data when powering down.
233  */
234 static int iwl4965_set_ucode_ptrs(struct iwl_priv *priv)
235 {
236         dma_addr_t pinst;
237         dma_addr_t pdata;
238         unsigned long flags;
239         int ret = 0;
240
241         /* bits 35:4 for 4965 */
242         pinst = priv->ucode_code.p_addr >> 4;
243         pdata = priv->ucode_data_backup.p_addr >> 4;
244
245         spin_lock_irqsave(&priv->lock, flags);
246         ret = iwl_grab_nic_access(priv);
247         if (ret) {
248                 spin_unlock_irqrestore(&priv->lock, flags);
249                 return ret;
250         }
251
252         /* Tell bootstrap uCode where to find image to load */
253         iwl_write_prph(priv, BSM_DRAM_INST_PTR_REG, pinst);
254         iwl_write_prph(priv, BSM_DRAM_DATA_PTR_REG, pdata);
255         iwl_write_prph(priv, BSM_DRAM_DATA_BYTECOUNT_REG,
256                                  priv->ucode_data.len);
257
258         /* Inst bytecount must be last to set up, bit 31 signals uCode
259          *   that all new ptr/size info is in place */
260         iwl_write_prph(priv, BSM_DRAM_INST_BYTECOUNT_REG,
261                                  priv->ucode_code.len | BSM_DRAM_INST_LOAD);
262         iwl_release_nic_access(priv);
263
264         spin_unlock_irqrestore(&priv->lock, flags);
265
266         IWL_DEBUG_INFO("Runtime uCode pointers are set.\n");
267
268         return ret;
269 }
270
271 /**
272  * iwl4965_init_alive_start - Called after REPLY_ALIVE notification received
273  *
274  * Called after REPLY_ALIVE notification received from "initialize" uCode.
275  *
276  * The 4965 "initialize" ALIVE reply contains calibration data for:
277  *   Voltage, temperature, and MIMO tx gain correction, now stored in priv
278  *   (3945 does not contain this data).
279  *
280  * Tell "initialize" uCode to go ahead and load the runtime uCode.
281 */
282 static void iwl4965_init_alive_start(struct iwl_priv *priv)
283 {
284         /* Check alive response for "valid" sign from uCode */
285         if (priv->card_alive_init.is_valid != UCODE_VALID_OK) {
286                 /* We had an error bringing up the hardware, so take it
287                  * all the way back down so we can try again */
288                 IWL_DEBUG_INFO("Initialize Alive failed.\n");
289                 goto restart;
290         }
291
292         /* Bootstrap uCode has loaded initialize uCode ... verify inst image.
293          * This is a paranoid check, because we would not have gotten the
294          * "initialize" alive if code weren't properly loaded.  */
295         if (iwl_verify_ucode(priv)) {
296                 /* Runtime instruction load was bad;
297                  * take it all the way back down so we can try again */
298                 IWL_DEBUG_INFO("Bad \"initialize\" uCode load.\n");
299                 goto restart;
300         }
301
302         /* Calculate temperature */
303         priv->temperature = iwl4965_get_temperature(priv);
304
305         /* Send pointers to protocol/runtime uCode image ... init code will
306          * load and launch runtime uCode, which will send us another "Alive"
307          * notification. */
308         IWL_DEBUG_INFO("Initialization Alive received.\n");
309         if (iwl4965_set_ucode_ptrs(priv)) {
310                 /* Runtime instruction load won't happen;
311                  * take it all the way back down so we can try again */
312                 IWL_DEBUG_INFO("Couldn't set up uCode pointers.\n");
313                 goto restart;
314         }
315         return;
316
317 restart:
318         queue_work(priv->workqueue, &priv->restart);
319 }
320
321 static int is_fat_channel(__le32 rxon_flags)
322 {
323         return (rxon_flags & RXON_FLG_CHANNEL_MODE_PURE_40_MSK) ||
324                 (rxon_flags & RXON_FLG_CHANNEL_MODE_MIXED_MSK);
325 }
326
327 int iwl4965_hwrate_to_plcp_idx(u32 rate_n_flags)
328 {
329         int idx = 0;
330
331         /* 4965 HT rate format */
332         if (rate_n_flags & RATE_MCS_HT_MSK) {
333                 idx = (rate_n_flags & 0xff);
334
335                 if (idx >= IWL_RATE_MIMO2_6M_PLCP)
336                         idx = idx - IWL_RATE_MIMO2_6M_PLCP;
337
338                 idx += IWL_FIRST_OFDM_RATE;
339                 /* skip 9M not supported in ht*/
340                 if (idx >= IWL_RATE_9M_INDEX)
341                         idx += 1;
342                 if ((idx >= IWL_FIRST_OFDM_RATE) && (idx <= IWL_LAST_OFDM_RATE))
343                         return idx;
344
345         /* 4965 legacy rate format, search for match in table */
346         } else {
347                 for (idx = 0; idx < ARRAY_SIZE(iwl4965_rates); idx++)
348                         if (iwl4965_rates[idx].plcp == (rate_n_flags & 0xFF))
349                                 return idx;
350         }
351
352         return -1;
353 }
354
355 /**
356  * translate ucode response to mac80211 tx status control values
357  */
358 void iwl4965_hwrate_to_tx_control(struct iwl_priv *priv, u32 rate_n_flags,
359                                   struct ieee80211_tx_control *control)
360 {
361         int rate_index;
362
363         control->antenna_sel_tx =
364                 ((rate_n_flags & RATE_MCS_ANT_ABC_MSK) >> RATE_MCS_ANT_POS);
365         if (rate_n_flags & RATE_MCS_HT_MSK)
366                 control->flags |= IEEE80211_TXCTL_OFDM_HT;
367         if (rate_n_flags & RATE_MCS_GF_MSK)
368                 control->flags |= IEEE80211_TXCTL_GREEN_FIELD;
369         if (rate_n_flags & RATE_MCS_FAT_MSK)
370                 control->flags |= IEEE80211_TXCTL_40_MHZ_WIDTH;
371         if (rate_n_flags & RATE_MCS_DUP_MSK)
372                 control->flags |= IEEE80211_TXCTL_DUP_DATA;
373         if (rate_n_flags & RATE_MCS_SGI_MSK)
374                 control->flags |= IEEE80211_TXCTL_SHORT_GI;
375         /* since iwl4965_hwrate_to_plcp_idx is band indifferent, we always use
376          * IEEE80211_BAND_2GHZ band as it contains all the rates */
377         rate_index = iwl4965_hwrate_to_plcp_idx(rate_n_flags);
378         if (rate_index == -1)
379                 control->tx_rate = NULL;
380         else
381                 control->tx_rate =
382                         &priv->bands[IEEE80211_BAND_2GHZ].bitrates[rate_index];
383 }
384
385 int iwl4965_hw_rxq_stop(struct iwl_priv *priv)
386 {
387         int rc;
388         unsigned long flags;
389
390         spin_lock_irqsave(&priv->lock, flags);
391         rc = iwl_grab_nic_access(priv);
392         if (rc) {
393                 spin_unlock_irqrestore(&priv->lock, flags);
394                 return rc;
395         }
396
397         /* stop Rx DMA */
398         iwl_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0);
399         rc = iwl_poll_direct_bit(priv, FH_MEM_RSSR_RX_STATUS_REG,
400                                      (1 << 24), 1000);
401         if (rc < 0)
402                 IWL_ERROR("Can't stop Rx DMA.\n");
403
404         iwl_release_nic_access(priv);
405         spin_unlock_irqrestore(&priv->lock, flags);
406
407         return 0;
408 }
409
410 /*
411  * EEPROM handlers
412  */
413
414 static int iwl4965_eeprom_check_version(struct iwl_priv *priv)
415 {
416         u16 eeprom_ver;
417         u16 calib_ver;
418
419         eeprom_ver = iwl_eeprom_query16(priv, EEPROM_VERSION);
420
421         calib_ver = iwl_eeprom_query16(priv, EEPROM_4965_CALIB_VERSION_OFFSET);
422
423         if (eeprom_ver < EEPROM_4965_EEPROM_VERSION ||
424             calib_ver < EEPROM_4965_TX_POWER_VERSION)
425                 goto err;
426
427         return 0;
428 err:
429         IWL_ERROR("Unsuported EEPROM VER=0x%x < 0x%x CALIB=0x%x < 0x%x\n",
430                   eeprom_ver, EEPROM_4965_EEPROM_VERSION,
431                   calib_ver, EEPROM_4965_TX_POWER_VERSION);
432         return -EINVAL;
433
434 }
435 int iwl4965_set_pwr_src(struct iwl_priv *priv, enum iwl_pwr_src src)
436 {
437         int ret;
438         unsigned long flags;
439
440         spin_lock_irqsave(&priv->lock, flags);
441         ret = iwl_grab_nic_access(priv);
442         if (ret) {
443                 spin_unlock_irqrestore(&priv->lock, flags);
444                 return ret;
445         }
446
447         if (src == IWL_PWR_SRC_VAUX) {
448                 u32 val;
449                 ret = pci_read_config_dword(priv->pci_dev, PCI_POWER_SOURCE,
450                                             &val);
451
452                 if (val & PCI_CFG_PMC_PME_FROM_D3COLD_SUPPORT) {
453                         iwl_set_bits_mask_prph(priv, APMG_PS_CTRL_REG,
454                                                APMG_PS_CTRL_VAL_PWR_SRC_VAUX,
455                                                ~APMG_PS_CTRL_MSK_PWR_SRC);
456                 }
457         } else {
458                 iwl_set_bits_mask_prph(priv, APMG_PS_CTRL_REG,
459                                        APMG_PS_CTRL_VAL_PWR_SRC_VMAIN,
460                                        ~APMG_PS_CTRL_MSK_PWR_SRC);
461         }
462
463         iwl_release_nic_access(priv);
464         spin_unlock_irqrestore(&priv->lock, flags);
465
466         return ret;
467 }
468
469 static int iwl4965_disable_tx_fifo(struct iwl_priv *priv)
470 {
471         unsigned long flags;
472         int ret;
473
474         spin_lock_irqsave(&priv->lock, flags);
475
476         ret = iwl_grab_nic_access(priv);
477         if (unlikely(ret)) {
478                 IWL_ERROR("Tx fifo reset failed");
479                 spin_unlock_irqrestore(&priv->lock, flags);
480                 return ret;
481         }
482
483         iwl_write_prph(priv, IWL49_SCD_TXFACT, 0);
484         iwl_release_nic_access(priv);
485         spin_unlock_irqrestore(&priv->lock, flags);
486
487         return 0;
488 }
489
490 static int iwl4965_apm_init(struct iwl_priv *priv)
491 {
492         int ret = 0;
493
494         iwl_set_bit(priv, CSR_GIO_CHICKEN_BITS,
495                           CSR_GIO_CHICKEN_BITS_REG_BIT_DIS_L0S_EXIT_TIMER);
496
497         /* set "initialization complete" bit to move adapter
498          * D0U* --> D0A* state */
499         iwl_set_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
500
501         /* wait for clock stabilization */
502         ret = iwl_poll_bit(priv, CSR_GP_CNTRL,
503                            CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY,
504                            CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY, 25000);
505         if (ret < 0) {
506                 IWL_DEBUG_INFO("Failed to init the card\n");
507                 goto out;
508         }
509
510         ret = iwl_grab_nic_access(priv);
511         if (ret)
512                 goto out;
513
514         /* enable DMA */
515         iwl_write_prph(priv, APMG_CLK_CTRL_REG,
516                         APMG_CLK_VAL_DMA_CLK_RQT | APMG_CLK_VAL_BSM_CLK_RQT);
517
518         udelay(20);
519
520         iwl_set_bits_prph(priv, APMG_PCIDEV_STT_REG,
521                           APMG_PCIDEV_STT_VAL_L1_ACT_DIS);
522
523         iwl_release_nic_access(priv);
524 out:
525         return ret;
526 }
527
528
529 static void iwl4965_nic_config(struct iwl_priv *priv)
530 {
531         unsigned long flags;
532         u32 val;
533         u16 radio_cfg;
534         u8 val_link;
535
536         spin_lock_irqsave(&priv->lock, flags);
537
538         if ((priv->rev_id & 0x80) == 0x80 && (priv->rev_id & 0x7f) < 8) {
539                 pci_read_config_dword(priv->pci_dev, PCI_REG_WUM8, &val);
540                 /* Enable No Snoop field */
541                 pci_write_config_dword(priv->pci_dev, PCI_REG_WUM8,
542                                        val & ~(1 << 11));
543         }
544
545         pci_read_config_byte(priv->pci_dev, PCI_LINK_CTRL, &val_link);
546
547         /* disable L1 entry -- workaround for pre-B1 */
548         pci_write_config_byte(priv->pci_dev, PCI_LINK_CTRL, val_link & ~0x02);
549
550         radio_cfg = iwl_eeprom_query16(priv, EEPROM_RADIO_CONFIG);
551
552         /* write radio config values to register */
553         if (EEPROM_RF_CFG_TYPE_MSK(radio_cfg) == EEPROM_4965_RF_CFG_TYPE_MAX)
554                 iwl_set_bit(priv, CSR_HW_IF_CONFIG_REG,
555                             EEPROM_RF_CFG_TYPE_MSK(radio_cfg) |
556                             EEPROM_RF_CFG_STEP_MSK(radio_cfg) |
557                             EEPROM_RF_CFG_DASH_MSK(radio_cfg));
558
559         /* set CSR_HW_CONFIG_REG for uCode use */
560         iwl_set_bit(priv, CSR_HW_IF_CONFIG_REG,
561                     CSR_HW_IF_CONFIG_REG_BIT_RADIO_SI |
562                     CSR_HW_IF_CONFIG_REG_BIT_MAC_SI);
563
564         priv->calib_info = (struct iwl_eeprom_calib_info *)
565                 iwl_eeprom_query_addr(priv, EEPROM_4965_CALIB_TXPOWER_OFFSET);
566
567         spin_unlock_irqrestore(&priv->lock, flags);
568 }
569
570 int iwl4965_hw_nic_stop_master(struct iwl_priv *priv)
571 {
572         int rc = 0;
573         u32 reg_val;
574         unsigned long flags;
575
576         spin_lock_irqsave(&priv->lock, flags);
577
578         /* set stop master bit */
579         iwl_set_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_STOP_MASTER);
580
581         reg_val = iwl_read32(priv, CSR_GP_CNTRL);
582
583         if (CSR_GP_CNTRL_REG_FLAG_MAC_POWER_SAVE ==
584             (reg_val & CSR_GP_CNTRL_REG_MSK_POWER_SAVE_TYPE))
585                 IWL_DEBUG_INFO("Card in power save, master is already "
586                                "stopped\n");
587         else {
588                 rc = iwl_poll_bit(priv, CSR_RESET,
589                                   CSR_RESET_REG_FLAG_MASTER_DISABLED,
590                                   CSR_RESET_REG_FLAG_MASTER_DISABLED, 100);
591                 if (rc < 0) {
592                         spin_unlock_irqrestore(&priv->lock, flags);
593                         return rc;
594                 }
595         }
596
597         spin_unlock_irqrestore(&priv->lock, flags);
598         IWL_DEBUG_INFO("stop master\n");
599
600         return rc;
601 }
602
603 /**
604  * iwl4965_hw_txq_ctx_stop - Stop all Tx DMA channels, free Tx queue memory
605  */
606 void iwl4965_hw_txq_ctx_stop(struct iwl_priv *priv)
607 {
608
609         int txq_id;
610         unsigned long flags;
611
612         /* Stop each Tx DMA channel, and wait for it to be idle */
613         for (txq_id = 0; txq_id < priv->hw_params.max_txq_num; txq_id++) {
614                 spin_lock_irqsave(&priv->lock, flags);
615                 if (iwl_grab_nic_access(priv)) {
616                         spin_unlock_irqrestore(&priv->lock, flags);
617                         continue;
618                 }
619
620                 iwl_write_direct32(priv,
621                                    FH_TCSR_CHNL_TX_CONFIG_REG(txq_id), 0x0);
622                 iwl_poll_direct_bit(priv, FH_TSSR_TX_STATUS_REG,
623                                     FH_TSSR_TX_STATUS_REG_MSK_CHNL_IDLE
624                                     (txq_id), 200);
625                 iwl_release_nic_access(priv);
626                 spin_unlock_irqrestore(&priv->lock, flags);
627         }
628
629         /* Deallocate memory for all Tx queues */
630         iwl_hw_txq_ctx_free(priv);
631 }
632
633 int iwl4965_hw_nic_reset(struct iwl_priv *priv)
634 {
635         int rc = 0;
636         unsigned long flags;
637
638         iwl4965_hw_nic_stop_master(priv);
639
640         spin_lock_irqsave(&priv->lock, flags);
641
642         iwl_set_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_SW_RESET);
643
644         udelay(10);
645
646         iwl_set_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
647         rc = iwl_poll_bit(priv, CSR_RESET,
648                           CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY,
649                           CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY, 25);
650
651         udelay(10);
652
653         rc = iwl_grab_nic_access(priv);
654         if (!rc) {
655                 iwl_write_prph(priv, APMG_CLK_EN_REG,
656                                 APMG_CLK_VAL_DMA_CLK_RQT |
657                                 APMG_CLK_VAL_BSM_CLK_RQT);
658
659                 udelay(10);
660
661                 iwl_set_bits_prph(priv, APMG_PCIDEV_STT_REG,
662                                         APMG_PCIDEV_STT_VAL_L1_ACT_DIS);
663
664                 iwl_release_nic_access(priv);
665         }
666
667         clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
668         wake_up_interruptible(&priv->wait_command_queue);
669
670         spin_unlock_irqrestore(&priv->lock, flags);
671
672         return rc;
673
674 }
675
676 #define REG_RECALIB_PERIOD (60)
677
678 /**
679  * iwl4965_bg_statistics_periodic - Timer callback to queue statistics
680  *
681  * This callback is provided in order to send a statistics request.
682  *
683  * This timer function is continually reset to execute within
684  * REG_RECALIB_PERIOD seconds since the last STATISTICS_NOTIFICATION
685  * was received.  We need to ensure we receive the statistics in order
686  * to update the temperature used for calibrating the TXPOWER.
687  */
688 static void iwl4965_bg_statistics_periodic(unsigned long data)
689 {
690         struct iwl_priv *priv = (struct iwl_priv *)data;
691
692         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
693                 return;
694
695         iwl_send_statistics_request(priv, CMD_ASYNC);
696 }
697
698 void iwl4965_rf_kill_ct_config(struct iwl_priv *priv)
699 {
700         struct iwl4965_ct_kill_config cmd;
701         unsigned long flags;
702         int ret = 0;
703
704         spin_lock_irqsave(&priv->lock, flags);
705         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR,
706                     CSR_UCODE_DRV_GP1_REG_BIT_CT_KILL_EXIT);
707         spin_unlock_irqrestore(&priv->lock, flags);
708
709         cmd.critical_temperature_R =
710                 cpu_to_le32(priv->hw_params.ct_kill_threshold);
711
712         ret = iwl_send_cmd_pdu(priv, REPLY_CT_KILL_CONFIG_CMD,
713                                sizeof(cmd), &cmd);
714         if (ret)
715                 IWL_ERROR("REPLY_CT_KILL_CONFIG_CMD failed\n");
716         else
717                 IWL_DEBUG_INFO("REPLY_CT_KILL_CONFIG_CMD succeeded, "
718                         "critical temperature is %d\n",
719                         cmd.critical_temperature_R);
720 }
721
722 #ifdef CONFIG_IWL4965_RUN_TIME_CALIB
723
724 /* Reset differential Rx gains in NIC to prepare for chain noise calibration.
725  * Called after every association, but this runs only once!
726  *  ... once chain noise is calibrated the first time, it's good forever.  */
727 static void iwl4965_chain_noise_reset(struct iwl_priv *priv)
728 {
729         struct iwl_chain_noise_data *data = &(priv->chain_noise_data);
730
731         if ((data->state == IWL_CHAIN_NOISE_ALIVE) && iwl_is_associated(priv)) {
732                 struct iwl4965_calibration_cmd cmd;
733
734                 memset(&cmd, 0, sizeof(cmd));
735                 cmd.opCode = PHY_CALIBRATE_DIFF_GAIN_CMD;
736                 cmd.diff_gain_a = 0;
737                 cmd.diff_gain_b = 0;
738                 cmd.diff_gain_c = 0;
739                 if (iwl_send_cmd_pdu(priv, REPLY_PHY_CALIBRATION_CMD,
740                                  sizeof(cmd), &cmd))
741                         IWL_ERROR("Could not send REPLY_PHY_CALIBRATION_CMD\n");
742                 data->state = IWL_CHAIN_NOISE_ACCUMULATE;
743                 IWL_DEBUG_CALIB("Run chain_noise_calibrate\n");
744         }
745 }
746
747 static void iwl4965_gain_computation(struct iwl_priv *priv,
748                 u32 *average_noise,
749                 u16 min_average_noise_antenna_i,
750                 u32 min_average_noise)
751 {
752         int i, ret;
753         struct iwl_chain_noise_data *data = &priv->chain_noise_data;
754
755         data->delta_gain_code[min_average_noise_antenna_i] = 0;
756
757         for (i = 0; i < NUM_RX_CHAINS; i++) {
758                 s32 delta_g = 0;
759
760                 if (!(data->disconn_array[i]) &&
761                     (data->delta_gain_code[i] ==
762                              CHAIN_NOISE_DELTA_GAIN_INIT_VAL)) {
763                         delta_g = average_noise[i] - min_average_noise;
764                         data->delta_gain_code[i] = (u8)((delta_g * 10) / 15);
765                         data->delta_gain_code[i] =
766                                 min(data->delta_gain_code[i],
767                                 (u8) CHAIN_NOISE_MAX_DELTA_GAIN_CODE);
768
769                         data->delta_gain_code[i] =
770                                 (data->delta_gain_code[i] | (1 << 2));
771                 } else {
772                         data->delta_gain_code[i] = 0;
773                 }
774         }
775         IWL_DEBUG_CALIB("delta_gain_codes: a %d b %d c %d\n",
776                      data->delta_gain_code[0],
777                      data->delta_gain_code[1],
778                      data->delta_gain_code[2]);
779
780         /* Differential gain gets sent to uCode only once */
781         if (!data->radio_write) {
782                 struct iwl4965_calibration_cmd cmd;
783                 data->radio_write = 1;
784
785                 memset(&cmd, 0, sizeof(cmd));
786                 cmd.opCode = PHY_CALIBRATE_DIFF_GAIN_CMD;
787                 cmd.diff_gain_a = data->delta_gain_code[0];
788                 cmd.diff_gain_b = data->delta_gain_code[1];
789                 cmd.diff_gain_c = data->delta_gain_code[2];
790                 ret = iwl_send_cmd_pdu(priv, REPLY_PHY_CALIBRATION_CMD,
791                                       sizeof(cmd), &cmd);
792                 if (ret)
793                         IWL_DEBUG_CALIB("fail sending cmd "
794                                      "REPLY_PHY_CALIBRATION_CMD \n");
795
796                 /* TODO we might want recalculate
797                  * rx_chain in rxon cmd */
798
799                 /* Mark so we run this algo only once! */
800                 data->state = IWL_CHAIN_NOISE_CALIBRATED;
801         }
802         data->chain_noise_a = 0;
803         data->chain_noise_b = 0;
804         data->chain_noise_c = 0;
805         data->chain_signal_a = 0;
806         data->chain_signal_b = 0;
807         data->chain_signal_c = 0;
808         data->beacon_count = 0;
809 }
810
811 static void iwl4965_bg_sensitivity_work(struct work_struct *work)
812 {
813         struct iwl_priv *priv = container_of(work, struct iwl_priv,
814                         sensitivity_work);
815
816         mutex_lock(&priv->mutex);
817
818         if (test_bit(STATUS_EXIT_PENDING, &priv->status) ||
819             test_bit(STATUS_SCANNING, &priv->status)) {
820                 mutex_unlock(&priv->mutex);
821                 return;
822         }
823
824         if (priv->start_calib) {
825                 iwl_chain_noise_calibration(priv, &priv->statistics);
826
827                 iwl_sensitivity_calibration(priv, &priv->statistics);
828         }
829
830         mutex_unlock(&priv->mutex);
831         return;
832 }
833 #endif /*CONFIG_IWL4965_RUN_TIME_CALIB*/
834
835 static void iwl4965_bg_txpower_work(struct work_struct *work)
836 {
837         struct iwl_priv *priv = container_of(work, struct iwl_priv,
838                         txpower_work);
839
840         /* If a scan happened to start before we got here
841          * then just return; the statistics notification will
842          * kick off another scheduled work to compensate for
843          * any temperature delta we missed here. */
844         if (test_bit(STATUS_EXIT_PENDING, &priv->status) ||
845             test_bit(STATUS_SCANNING, &priv->status))
846                 return;
847
848         mutex_lock(&priv->mutex);
849
850         /* Regardless of if we are assocaited, we must reconfigure the
851          * TX power since frames can be sent on non-radar channels while
852          * not associated */
853         iwl4965_hw_reg_send_txpower(priv);
854
855         /* Update last_temperature to keep is_calib_needed from running
856          * when it isn't needed... */
857         priv->last_temperature = priv->temperature;
858
859         mutex_unlock(&priv->mutex);
860 }
861
862 /*
863  * Acquire priv->lock before calling this function !
864  */
865 static void iwl4965_set_wr_ptrs(struct iwl_priv *priv, int txq_id, u32 index)
866 {
867         iwl_write_direct32(priv, HBUS_TARG_WRPTR,
868                              (index & 0xff) | (txq_id << 8));
869         iwl_write_prph(priv, IWL49_SCD_QUEUE_RDPTR(txq_id), index);
870 }
871
872 /**
873  * iwl4965_tx_queue_set_status - (optionally) start Tx/Cmd queue
874  * @tx_fifo_id: Tx DMA/FIFO channel (range 0-7) that the queue will feed
875  * @scd_retry: (1) Indicates queue will be used in aggregation mode
876  *
877  * NOTE:  Acquire priv->lock before calling this function !
878  */
879 static void iwl4965_tx_queue_set_status(struct iwl_priv *priv,
880                                         struct iwl_tx_queue *txq,
881                                         int tx_fifo_id, int scd_retry)
882 {
883         int txq_id = txq->q.id;
884
885         /* Find out whether to activate Tx queue */
886         int active = test_bit(txq_id, &priv->txq_ctx_active_msk)?1:0;
887
888         /* Set up and activate */
889         iwl_write_prph(priv, IWL49_SCD_QUEUE_STATUS_BITS(txq_id),
890                          (active << IWL49_SCD_QUEUE_STTS_REG_POS_ACTIVE) |
891                          (tx_fifo_id << IWL49_SCD_QUEUE_STTS_REG_POS_TXF) |
892                          (scd_retry << IWL49_SCD_QUEUE_STTS_REG_POS_WSL) |
893                          (scd_retry << IWL49_SCD_QUEUE_STTS_REG_POS_SCD_ACK) |
894                          IWL49_SCD_QUEUE_STTS_REG_MSK);
895
896         txq->sched_retry = scd_retry;
897
898         IWL_DEBUG_INFO("%s %s Queue %d on AC %d\n",
899                        active ? "Activate" : "Deactivate",
900                        scd_retry ? "BA" : "AC", txq_id, tx_fifo_id);
901 }
902
903 static const u16 default_queue_to_tx_fifo[] = {
904         IWL_TX_FIFO_AC3,
905         IWL_TX_FIFO_AC2,
906         IWL_TX_FIFO_AC1,
907         IWL_TX_FIFO_AC0,
908         IWL49_CMD_FIFO_NUM,
909         IWL_TX_FIFO_HCCA_1,
910         IWL_TX_FIFO_HCCA_2
911 };
912
913 static inline void iwl4965_txq_ctx_activate(struct iwl_priv *priv, int txq_id)
914 {
915         set_bit(txq_id, &priv->txq_ctx_active_msk);
916 }
917
918 static inline void iwl4965_txq_ctx_deactivate(struct iwl_priv *priv, int txq_id)
919 {
920         clear_bit(txq_id, &priv->txq_ctx_active_msk);
921 }
922
923 int iwl4965_alive_notify(struct iwl_priv *priv)
924 {
925         u32 a;
926         int i = 0;
927         unsigned long flags;
928         int ret;
929
930         spin_lock_irqsave(&priv->lock, flags);
931
932 #ifdef CONFIG_IWL4965_RUN_TIME_CALIB
933         memset(&(priv->sensitivity_data), 0,
934                sizeof(struct iwl_sensitivity_data));
935         memset(&(priv->chain_noise_data), 0,
936                sizeof(struct iwl_chain_noise_data));
937         for (i = 0; i < NUM_RX_CHAINS; i++)
938                 priv->chain_noise_data.delta_gain_code[i] =
939                                 CHAIN_NOISE_DELTA_GAIN_INIT_VAL;
940 #endif /* CONFIG_IWL4965_RUN_TIME_CALIB*/
941         ret = iwl_grab_nic_access(priv);
942         if (ret) {
943                 spin_unlock_irqrestore(&priv->lock, flags);
944                 return ret;
945         }
946
947         /* Clear 4965's internal Tx Scheduler data base */
948         priv->scd_base_addr = iwl_read_prph(priv, IWL49_SCD_SRAM_BASE_ADDR);
949         a = priv->scd_base_addr + IWL49_SCD_CONTEXT_DATA_OFFSET;
950         for (; a < priv->scd_base_addr + IWL49_SCD_TX_STTS_BITMAP_OFFSET; a += 4)
951                 iwl_write_targ_mem(priv, a, 0);
952         for (; a < priv->scd_base_addr + IWL49_SCD_TRANSLATE_TBL_OFFSET; a += 4)
953                 iwl_write_targ_mem(priv, a, 0);
954         for (; a < sizeof(u16) * priv->hw_params.max_txq_num; a += 4)
955                 iwl_write_targ_mem(priv, a, 0);
956
957         /* Tel 4965 where to find Tx byte count tables */
958         iwl_write_prph(priv, IWL49_SCD_DRAM_BASE_ADDR,
959                 (priv->shared_phys +
960                  offsetof(struct iwl4965_shared, queues_byte_cnt_tbls)) >> 10);
961
962         /* Disable chain mode for all queues */
963         iwl_write_prph(priv, IWL49_SCD_QUEUECHAIN_SEL, 0);
964
965         /* Initialize each Tx queue (including the command queue) */
966         for (i = 0; i < priv->hw_params.max_txq_num; i++) {
967
968                 /* TFD circular buffer read/write indexes */
969                 iwl_write_prph(priv, IWL49_SCD_QUEUE_RDPTR(i), 0);
970                 iwl_write_direct32(priv, HBUS_TARG_WRPTR, 0 | (i << 8));
971
972                 /* Max Tx Window size for Scheduler-ACK mode */
973                 iwl_write_targ_mem(priv, priv->scd_base_addr +
974                                 IWL49_SCD_CONTEXT_QUEUE_OFFSET(i),
975                                 (SCD_WIN_SIZE <<
976                                 IWL49_SCD_QUEUE_CTX_REG1_WIN_SIZE_POS) &
977                                 IWL49_SCD_QUEUE_CTX_REG1_WIN_SIZE_MSK);
978
979                 /* Frame limit */
980                 iwl_write_targ_mem(priv, priv->scd_base_addr +
981                                 IWL49_SCD_CONTEXT_QUEUE_OFFSET(i) +
982                                 sizeof(u32),
983                                 (SCD_FRAME_LIMIT <<
984                                 IWL49_SCD_QUEUE_CTX_REG2_FRAME_LIMIT_POS) &
985                                 IWL49_SCD_QUEUE_CTX_REG2_FRAME_LIMIT_MSK);
986
987         }
988         iwl_write_prph(priv, IWL49_SCD_INTERRUPT_MASK,
989                                  (1 << priv->hw_params.max_txq_num) - 1);
990
991         /* Activate all Tx DMA/FIFO channels */
992         iwl_write_prph(priv, IWL49_SCD_TXFACT,
993                                  SCD_TXFACT_REG_TXFIFO_MASK(0, 7));
994
995         iwl4965_set_wr_ptrs(priv, IWL_CMD_QUEUE_NUM, 0);
996
997         /* Map each Tx/cmd queue to its corresponding fifo */
998         for (i = 0; i < ARRAY_SIZE(default_queue_to_tx_fifo); i++) {
999                 int ac = default_queue_to_tx_fifo[i];
1000                 iwl4965_txq_ctx_activate(priv, i);
1001                 iwl4965_tx_queue_set_status(priv, &priv->txq[i], ac, 0);
1002         }
1003
1004         iwl_release_nic_access(priv);
1005         spin_unlock_irqrestore(&priv->lock, flags);
1006
1007         /* Ask for statistics now, the uCode will send statistics notification
1008          * periodically after association */
1009         iwl_send_statistics_request(priv, CMD_ASYNC);
1010         return ret;
1011 }
1012
1013 #ifdef CONFIG_IWL4965_RUN_TIME_CALIB
1014 static struct iwl_sensitivity_ranges iwl4965_sensitivity = {
1015         .min_nrg_cck = 97,
1016         .max_nrg_cck = 0,
1017
1018         .auto_corr_min_ofdm = 85,
1019         .auto_corr_min_ofdm_mrc = 170,
1020         .auto_corr_min_ofdm_x1 = 105,
1021         .auto_corr_min_ofdm_mrc_x1 = 220,
1022
1023         .auto_corr_max_ofdm = 120,
1024         .auto_corr_max_ofdm_mrc = 210,
1025         .auto_corr_max_ofdm_x1 = 140,
1026         .auto_corr_max_ofdm_mrc_x1 = 270,
1027
1028         .auto_corr_min_cck = 125,
1029         .auto_corr_max_cck = 200,
1030         .auto_corr_min_cck_mrc = 200,
1031         .auto_corr_max_cck_mrc = 400,
1032
1033         .nrg_th_cck = 100,
1034         .nrg_th_ofdm = 100,
1035 };
1036 #endif
1037
1038 /**
1039  * iwl4965_hw_set_hw_params
1040  *
1041  * Called when initializing driver
1042  */
1043 int iwl4965_hw_set_hw_params(struct iwl_priv *priv)
1044 {
1045
1046         if ((priv->cfg->mod_params->num_of_queues > IWL49_NUM_QUEUES) ||
1047             (priv->cfg->mod_params->num_of_queues < IWL_MIN_NUM_QUEUES)) {
1048                 IWL_ERROR("invalid queues_num, should be between %d and %d\n",
1049                           IWL_MIN_NUM_QUEUES, IWL49_NUM_QUEUES);
1050                 return -EINVAL;
1051         }
1052
1053         priv->hw_params.max_txq_num = priv->cfg->mod_params->num_of_queues;
1054         priv->hw_params.sw_crypto = priv->cfg->mod_params->sw_crypto;
1055         priv->hw_params.tx_cmd_len = sizeof(struct iwl4965_tx_cmd);
1056         priv->hw_params.max_rxq_size = RX_QUEUE_SIZE;
1057         priv->hw_params.max_rxq_log = RX_QUEUE_SIZE_LOG;
1058         if (priv->cfg->mod_params->amsdu_size_8K)
1059                 priv->hw_params.rx_buf_size = IWL_RX_BUF_SIZE_8K;
1060         else
1061                 priv->hw_params.rx_buf_size = IWL_RX_BUF_SIZE_4K;
1062         priv->hw_params.max_pkt_size = priv->hw_params.rx_buf_size - 256;
1063         priv->hw_params.max_stations = IWL4965_STATION_COUNT;
1064         priv->hw_params.bcast_sta_id = IWL4965_BROADCAST_ID;
1065
1066         priv->hw_params.max_data_size = IWL49_RTC_DATA_SIZE;
1067         priv->hw_params.max_inst_size = IWL49_RTC_INST_SIZE;
1068         priv->hw_params.max_bsm_size = BSM_SRAM_SIZE;
1069         priv->hw_params.fat_channel = BIT(IEEE80211_BAND_5GHZ);
1070
1071         priv->hw_params.tx_chains_num = 2;
1072         priv->hw_params.rx_chains_num = 2;
1073         priv->hw_params.valid_tx_ant = ANT_A | ANT_B;
1074         priv->hw_params.valid_rx_ant = ANT_A | ANT_B;
1075         priv->hw_params.ct_kill_threshold = CELSIUS_TO_KELVIN(CT_KILL_THRESHOLD);
1076
1077 #ifdef CONFIG_IWL4965_RUN_TIME_CALIB
1078         priv->hw_params.sens = &iwl4965_sensitivity;
1079 #endif
1080
1081         return 0;
1082 }
1083
1084 /* set card power command */
1085 static int iwl4965_set_power(struct iwl_priv *priv,
1086                       void *cmd)
1087 {
1088         int ret = 0;
1089
1090         ret = iwl_send_cmd_pdu_async(priv, POWER_TABLE_CMD,
1091                                     sizeof(struct iwl4965_powertable_cmd),
1092                                     cmd, NULL);
1093         return ret;
1094 }
1095 int iwl4965_hw_reg_set_txpower(struct iwl_priv *priv, s8 power)
1096 {
1097         IWL_ERROR("TODO: Implement iwl4965_hw_reg_set_txpower!\n");
1098         return -EINVAL;
1099 }
1100
1101 static s32 iwl4965_math_div_round(s32 num, s32 denom, s32 *res)
1102 {
1103         s32 sign = 1;
1104
1105         if (num < 0) {
1106                 sign = -sign;
1107                 num = -num;
1108         }
1109         if (denom < 0) {
1110                 sign = -sign;
1111                 denom = -denom;
1112         }
1113         *res = 1;
1114         *res = ((num * 2 + denom) / (denom * 2)) * sign;
1115
1116         return 1;
1117 }
1118
1119 /**
1120  * iwl4965_get_voltage_compensation - Power supply voltage comp for txpower
1121  *
1122  * Determines power supply voltage compensation for txpower calculations.
1123  * Returns number of 1/2-dB steps to subtract from gain table index,
1124  * to compensate for difference between power supply voltage during
1125  * factory measurements, vs. current power supply voltage.
1126  *
1127  * Voltage indication is higher for lower voltage.
1128  * Lower voltage requires more gain (lower gain table index).
1129  */
1130 static s32 iwl4965_get_voltage_compensation(s32 eeprom_voltage,
1131                                             s32 current_voltage)
1132 {
1133         s32 comp = 0;
1134
1135         if ((TX_POWER_IWL_ILLEGAL_VOLTAGE == eeprom_voltage) ||
1136             (TX_POWER_IWL_ILLEGAL_VOLTAGE == current_voltage))
1137                 return 0;
1138
1139         iwl4965_math_div_round(current_voltage - eeprom_voltage,
1140                                TX_POWER_IWL_VOLTAGE_CODES_PER_03V, &comp);
1141
1142         if (current_voltage > eeprom_voltage)
1143                 comp *= 2;
1144         if ((comp < -2) || (comp > 2))
1145                 comp = 0;
1146
1147         return comp;
1148 }
1149
1150 static const struct iwl_channel_info *
1151 iwl4965_get_channel_txpower_info(struct iwl_priv *priv,
1152                                  enum ieee80211_band band, u16 channel)
1153 {
1154         const struct iwl_channel_info *ch_info;
1155
1156         ch_info = iwl_get_channel_info(priv, band, channel);
1157
1158         if (!is_channel_valid(ch_info))
1159                 return NULL;
1160
1161         return ch_info;
1162 }
1163
1164 static s32 iwl4965_get_tx_atten_grp(u16 channel)
1165 {
1166         if (channel >= CALIB_IWL_TX_ATTEN_GR5_FCH &&
1167             channel <= CALIB_IWL_TX_ATTEN_GR5_LCH)
1168                 return CALIB_CH_GROUP_5;
1169
1170         if (channel >= CALIB_IWL_TX_ATTEN_GR1_FCH &&
1171             channel <= CALIB_IWL_TX_ATTEN_GR1_LCH)
1172                 return CALIB_CH_GROUP_1;
1173
1174         if (channel >= CALIB_IWL_TX_ATTEN_GR2_FCH &&
1175             channel <= CALIB_IWL_TX_ATTEN_GR2_LCH)
1176                 return CALIB_CH_GROUP_2;
1177
1178         if (channel >= CALIB_IWL_TX_ATTEN_GR3_FCH &&
1179             channel <= CALIB_IWL_TX_ATTEN_GR3_LCH)
1180                 return CALIB_CH_GROUP_3;
1181
1182         if (channel >= CALIB_IWL_TX_ATTEN_GR4_FCH &&
1183             channel <= CALIB_IWL_TX_ATTEN_GR4_LCH)
1184                 return CALIB_CH_GROUP_4;
1185
1186         IWL_ERROR("Can't find txatten group for channel %d.\n", channel);
1187         return -1;
1188 }
1189
1190 static u32 iwl4965_get_sub_band(const struct iwl_priv *priv, u32 channel)
1191 {
1192         s32 b = -1;
1193
1194         for (b = 0; b < EEPROM_TX_POWER_BANDS; b++) {
1195                 if (priv->calib_info->band_info[b].ch_from == 0)
1196                         continue;
1197
1198                 if ((channel >= priv->calib_info->band_info[b].ch_from)
1199                     && (channel <= priv->calib_info->band_info[b].ch_to))
1200                         break;
1201         }
1202
1203         return b;
1204 }
1205
1206 static s32 iwl4965_interpolate_value(s32 x, s32 x1, s32 y1, s32 x2, s32 y2)
1207 {
1208         s32 val;
1209
1210         if (x2 == x1)
1211                 return y1;
1212         else {
1213                 iwl4965_math_div_round((x2 - x) * (y1 - y2), (x2 - x1), &val);
1214                 return val + y2;
1215         }
1216 }
1217
1218 /**
1219  * iwl4965_interpolate_chan - Interpolate factory measurements for one channel
1220  *
1221  * Interpolates factory measurements from the two sample channels within a
1222  * sub-band, to apply to channel of interest.  Interpolation is proportional to
1223  * differences in channel frequencies, which is proportional to differences
1224  * in channel number.
1225  */
1226 static int iwl4965_interpolate_chan(struct iwl_priv *priv, u32 channel,
1227                                     struct iwl_eeprom_calib_ch_info *chan_info)
1228 {
1229         s32 s = -1;
1230         u32 c;
1231         u32 m;
1232         const struct iwl_eeprom_calib_measure *m1;
1233         const struct iwl_eeprom_calib_measure *m2;
1234         struct iwl_eeprom_calib_measure *omeas;
1235         u32 ch_i1;
1236         u32 ch_i2;
1237
1238         s = iwl4965_get_sub_band(priv, channel);
1239         if (s >= EEPROM_TX_POWER_BANDS) {
1240                 IWL_ERROR("Tx Power can not find channel %d ", channel);
1241                 return -1;
1242         }
1243
1244         ch_i1 = priv->calib_info->band_info[s].ch1.ch_num;
1245         ch_i2 = priv->calib_info->band_info[s].ch2.ch_num;
1246         chan_info->ch_num = (u8) channel;
1247
1248         IWL_DEBUG_TXPOWER("channel %d subband %d factory cal ch %d & %d\n",
1249                           channel, s, ch_i1, ch_i2);
1250
1251         for (c = 0; c < EEPROM_TX_POWER_TX_CHAINS; c++) {
1252                 for (m = 0; m < EEPROM_TX_POWER_MEASUREMENTS; m++) {
1253                         m1 = &(priv->calib_info->band_info[s].ch1.
1254                                measurements[c][m]);
1255                         m2 = &(priv->calib_info->band_info[s].ch2.
1256                                measurements[c][m]);
1257                         omeas = &(chan_info->measurements[c][m]);
1258
1259                         omeas->actual_pow =
1260                             (u8) iwl4965_interpolate_value(channel, ch_i1,
1261                                                            m1->actual_pow,
1262                                                            ch_i2,
1263                                                            m2->actual_pow);
1264                         omeas->gain_idx =
1265                             (u8) iwl4965_interpolate_value(channel, ch_i1,
1266                                                            m1->gain_idx, ch_i2,
1267                                                            m2->gain_idx);
1268                         omeas->temperature =
1269                             (u8) iwl4965_interpolate_value(channel, ch_i1,
1270                                                            m1->temperature,
1271                                                            ch_i2,
1272                                                            m2->temperature);
1273                         omeas->pa_det =
1274                             (s8) iwl4965_interpolate_value(channel, ch_i1,
1275                                                            m1->pa_det, ch_i2,
1276                                                            m2->pa_det);
1277
1278                         IWL_DEBUG_TXPOWER
1279                             ("chain %d meas %d AP1=%d AP2=%d AP=%d\n", c, m,
1280                              m1->actual_pow, m2->actual_pow, omeas->actual_pow);
1281                         IWL_DEBUG_TXPOWER
1282                             ("chain %d meas %d NI1=%d NI2=%d NI=%d\n", c, m,
1283                              m1->gain_idx, m2->gain_idx, omeas->gain_idx);
1284                         IWL_DEBUG_TXPOWER
1285                             ("chain %d meas %d PA1=%d PA2=%d PA=%d\n", c, m,
1286                              m1->pa_det, m2->pa_det, omeas->pa_det);
1287                         IWL_DEBUG_TXPOWER
1288                             ("chain %d meas %d  T1=%d  T2=%d  T=%d\n", c, m,
1289                              m1->temperature, m2->temperature,
1290                              omeas->temperature);
1291                 }
1292         }
1293
1294         return 0;
1295 }
1296
1297 /* bit-rate-dependent table to prevent Tx distortion, in half-dB units,
1298  * for OFDM 6, 12, 18, 24, 36, 48, 54, 60 MBit, and CCK all rates. */
1299 static s32 back_off_table[] = {
1300         10, 10, 10, 10, 10, 15, 17, 20, /* OFDM SISO 20 MHz */
1301         10, 10, 10, 10, 10, 15, 17, 20, /* OFDM MIMO 20 MHz */
1302         10, 10, 10, 10, 10, 15, 17, 20, /* OFDM SISO 40 MHz */
1303         10, 10, 10, 10, 10, 15, 17, 20, /* OFDM MIMO 40 MHz */
1304         10                      /* CCK */
1305 };
1306
1307 /* Thermal compensation values for txpower for various frequency ranges ...
1308  *   ratios from 3:1 to 4.5:1 of degrees (Celsius) per half-dB gain adjust */
1309 static struct iwl4965_txpower_comp_entry {
1310         s32 degrees_per_05db_a;
1311         s32 degrees_per_05db_a_denom;
1312 } tx_power_cmp_tble[CALIB_CH_GROUP_MAX] = {
1313         {9, 2},                 /* group 0 5.2, ch  34-43 */
1314         {4, 1},                 /* group 1 5.2, ch  44-70 */
1315         {4, 1},                 /* group 2 5.2, ch  71-124 */
1316         {4, 1},                 /* group 3 5.2, ch 125-200 */
1317         {3, 1}                  /* group 4 2.4, ch   all */
1318 };
1319
1320 static s32 get_min_power_index(s32 rate_power_index, u32 band)
1321 {
1322         if (!band) {
1323                 if ((rate_power_index & 7) <= 4)
1324                         return MIN_TX_GAIN_INDEX_52GHZ_EXT;
1325         }
1326         return MIN_TX_GAIN_INDEX;
1327 }
1328
1329 struct gain_entry {
1330         u8 dsp;
1331         u8 radio;
1332 };
1333
1334 static const struct gain_entry gain_table[2][108] = {
1335         /* 5.2GHz power gain index table */
1336         {
1337          {123, 0x3F},           /* highest txpower */
1338          {117, 0x3F},
1339          {110, 0x3F},
1340          {104, 0x3F},
1341          {98, 0x3F},
1342          {110, 0x3E},
1343          {104, 0x3E},
1344          {98, 0x3E},
1345          {110, 0x3D},
1346          {104, 0x3D},
1347          {98, 0x3D},
1348          {110, 0x3C},
1349          {104, 0x3C},
1350          {98, 0x3C},
1351          {110, 0x3B},
1352          {104, 0x3B},
1353          {98, 0x3B},
1354          {110, 0x3A},
1355          {104, 0x3A},
1356          {98, 0x3A},
1357          {110, 0x39},
1358          {104, 0x39},
1359          {98, 0x39},
1360          {110, 0x38},
1361          {104, 0x38},
1362          {98, 0x38},
1363          {110, 0x37},
1364          {104, 0x37},
1365          {98, 0x37},
1366          {110, 0x36},
1367          {104, 0x36},
1368          {98, 0x36},
1369          {110, 0x35},
1370          {104, 0x35},
1371          {98, 0x35},
1372          {110, 0x34},
1373          {104, 0x34},
1374          {98, 0x34},
1375          {110, 0x33},
1376          {104, 0x33},
1377          {98, 0x33},
1378          {110, 0x32},
1379          {104, 0x32},
1380          {98, 0x32},
1381          {110, 0x31},
1382          {104, 0x31},
1383          {98, 0x31},
1384          {110, 0x30},
1385          {104, 0x30},
1386          {98, 0x30},
1387          {110, 0x25},
1388          {104, 0x25},
1389          {98, 0x25},
1390          {110, 0x24},
1391          {104, 0x24},
1392          {98, 0x24},
1393          {110, 0x23},
1394          {104, 0x23},
1395          {98, 0x23},
1396          {110, 0x22},
1397          {104, 0x18},
1398          {98, 0x18},
1399          {110, 0x17},
1400          {104, 0x17},
1401          {98, 0x17},
1402          {110, 0x16},
1403          {104, 0x16},
1404          {98, 0x16},
1405          {110, 0x15},
1406          {104, 0x15},
1407          {98, 0x15},
1408          {110, 0x14},
1409          {104, 0x14},
1410          {98, 0x14},
1411          {110, 0x13},
1412          {104, 0x13},
1413          {98, 0x13},
1414          {110, 0x12},
1415          {104, 0x08},
1416          {98, 0x08},
1417          {110, 0x07},
1418          {104, 0x07},
1419          {98, 0x07},
1420          {110, 0x06},
1421          {104, 0x06},
1422          {98, 0x06},
1423          {110, 0x05},
1424          {104, 0x05},
1425          {98, 0x05},
1426          {110, 0x04},
1427          {104, 0x04},
1428          {98, 0x04},
1429          {110, 0x03},
1430          {104, 0x03},
1431          {98, 0x03},
1432          {110, 0x02},
1433          {104, 0x02},
1434          {98, 0x02},
1435          {110, 0x01},
1436          {104, 0x01},
1437          {98, 0x01},
1438          {110, 0x00},
1439          {104, 0x00},
1440          {98, 0x00},
1441          {93, 0x00},
1442          {88, 0x00},
1443          {83, 0x00},
1444          {78, 0x00},
1445          },
1446         /* 2.4GHz power gain index table */
1447         {
1448          {110, 0x3f},           /* highest txpower */
1449          {104, 0x3f},
1450          {98, 0x3f},
1451          {110, 0x3e},
1452          {104, 0x3e},
1453          {98, 0x3e},
1454          {110, 0x3d},
1455          {104, 0x3d},
1456          {98, 0x3d},
1457          {110, 0x3c},
1458          {104, 0x3c},
1459          {98, 0x3c},
1460          {110, 0x3b},
1461          {104, 0x3b},
1462          {98, 0x3b},
1463          {110, 0x3a},
1464          {104, 0x3a},
1465          {98, 0x3a},
1466          {110, 0x39},
1467          {104, 0x39},
1468          {98, 0x39},
1469          {110, 0x38},
1470          {104, 0x38},
1471          {98, 0x38},
1472          {110, 0x37},
1473          {104, 0x37},
1474          {98, 0x37},
1475          {110, 0x36},
1476          {104, 0x36},
1477          {98, 0x36},
1478          {110, 0x35},
1479          {104, 0x35},
1480          {98, 0x35},
1481          {110, 0x34},
1482          {104, 0x34},
1483          {98, 0x34},
1484          {110, 0x33},
1485          {104, 0x33},
1486          {98, 0x33},
1487          {110, 0x32},
1488          {104, 0x32},
1489          {98, 0x32},
1490          {110, 0x31},
1491          {104, 0x31},
1492          {98, 0x31},
1493          {110, 0x30},
1494          {104, 0x30},
1495          {98, 0x30},
1496          {110, 0x6},
1497          {104, 0x6},
1498          {98, 0x6},
1499          {110, 0x5},
1500          {104, 0x5},
1501          {98, 0x5},
1502          {110, 0x4},
1503          {104, 0x4},
1504          {98, 0x4},
1505          {110, 0x3},
1506          {104, 0x3},
1507          {98, 0x3},
1508          {110, 0x2},
1509          {104, 0x2},
1510          {98, 0x2},
1511          {110, 0x1},
1512          {104, 0x1},
1513          {98, 0x1},
1514          {110, 0x0},
1515          {104, 0x0},
1516          {98, 0x0},
1517          {97, 0},
1518          {96, 0},
1519          {95, 0},
1520          {94, 0},
1521          {93, 0},
1522          {92, 0},
1523          {91, 0},
1524          {90, 0},
1525          {89, 0},
1526          {88, 0},
1527          {87, 0},
1528          {86, 0},
1529          {85, 0},
1530          {84, 0},
1531          {83, 0},
1532          {82, 0},
1533          {81, 0},
1534          {80, 0},
1535          {79, 0},
1536          {78, 0},
1537          {77, 0},
1538          {76, 0},
1539          {75, 0},
1540          {74, 0},
1541          {73, 0},
1542          {72, 0},
1543          {71, 0},
1544          {70, 0},
1545          {69, 0},
1546          {68, 0},
1547          {67, 0},
1548          {66, 0},
1549          {65, 0},
1550          {64, 0},
1551          {63, 0},
1552          {62, 0},
1553          {61, 0},
1554          {60, 0},
1555          {59, 0},
1556          }
1557 };
1558
1559 static int iwl4965_fill_txpower_tbl(struct iwl_priv *priv, u8 band, u16 channel,
1560                                     u8 is_fat, u8 ctrl_chan_high,
1561                                     struct iwl4965_tx_power_db *tx_power_tbl)
1562 {
1563         u8 saturation_power;
1564         s32 target_power;
1565         s32 user_target_power;
1566         s32 power_limit;
1567         s32 current_temp;
1568         s32 reg_limit;
1569         s32 current_regulatory;
1570         s32 txatten_grp = CALIB_CH_GROUP_MAX;
1571         int i;
1572         int c;
1573         const struct iwl_channel_info *ch_info = NULL;
1574         struct iwl_eeprom_calib_ch_info ch_eeprom_info;
1575         const struct iwl_eeprom_calib_measure *measurement;
1576         s16 voltage;
1577         s32 init_voltage;
1578         s32 voltage_compensation;
1579         s32 degrees_per_05db_num;
1580         s32 degrees_per_05db_denom;
1581         s32 factory_temp;
1582         s32 temperature_comp[2];
1583         s32 factory_gain_index[2];
1584         s32 factory_actual_pwr[2];
1585         s32 power_index;
1586
1587         /* Sanity check requested level (dBm) */
1588         if (priv->user_txpower_limit < IWL_TX_POWER_TARGET_POWER_MIN) {
1589                 IWL_WARNING("Requested user TXPOWER %d below limit.\n",
1590                             priv->user_txpower_limit);
1591                 return -EINVAL;
1592         }
1593         if (priv->user_txpower_limit > IWL_TX_POWER_TARGET_POWER_MAX) {
1594                 IWL_WARNING("Requested user TXPOWER %d above limit.\n",
1595                             priv->user_txpower_limit);
1596                 return -EINVAL;
1597         }
1598
1599         /* user_txpower_limit is in dBm, convert to half-dBm (half-dB units
1600          *   are used for indexing into txpower table) */
1601         user_target_power = 2 * priv->user_txpower_limit;
1602
1603         /* Get current (RXON) channel, band, width */
1604         ch_info =
1605                 iwl4965_get_channel_txpower_info(priv, priv->band, channel);
1606
1607         IWL_DEBUG_TXPOWER("chan %d band %d is_fat %d\n", channel, band,
1608                           is_fat);
1609
1610         if (!ch_info)
1611                 return -EINVAL;
1612
1613         /* get txatten group, used to select 1) thermal txpower adjustment
1614          *   and 2) mimo txpower balance between Tx chains. */
1615         txatten_grp = iwl4965_get_tx_atten_grp(channel);
1616         if (txatten_grp < 0)
1617                 return -EINVAL;
1618
1619         IWL_DEBUG_TXPOWER("channel %d belongs to txatten group %d\n",
1620                           channel, txatten_grp);
1621
1622         if (is_fat) {
1623                 if (ctrl_chan_high)
1624                         channel -= 2;
1625                 else
1626                         channel += 2;
1627         }
1628
1629         /* hardware txpower limits ...
1630          * saturation (clipping distortion) txpowers are in half-dBm */
1631         if (band)
1632                 saturation_power = priv->calib_info->saturation_power24;
1633         else
1634                 saturation_power = priv->calib_info->saturation_power52;
1635
1636         if (saturation_power < IWL_TX_POWER_SATURATION_MIN ||
1637             saturation_power > IWL_TX_POWER_SATURATION_MAX) {
1638                 if (band)
1639                         saturation_power = IWL_TX_POWER_DEFAULT_SATURATION_24;
1640                 else
1641                         saturation_power = IWL_TX_POWER_DEFAULT_SATURATION_52;
1642         }
1643
1644         /* regulatory txpower limits ... reg_limit values are in half-dBm,
1645          *   max_power_avg values are in dBm, convert * 2 */
1646         if (is_fat)
1647                 reg_limit = ch_info->fat_max_power_avg * 2;
1648         else
1649                 reg_limit = ch_info->max_power_avg * 2;
1650
1651         if ((reg_limit < IWL_TX_POWER_REGULATORY_MIN) ||
1652             (reg_limit > IWL_TX_POWER_REGULATORY_MAX)) {
1653                 if (band)
1654                         reg_limit = IWL_TX_POWER_DEFAULT_REGULATORY_24;
1655                 else
1656                         reg_limit = IWL_TX_POWER_DEFAULT_REGULATORY_52;
1657         }
1658
1659         /* Interpolate txpower calibration values for this channel,
1660          *   based on factory calibration tests on spaced channels. */
1661         iwl4965_interpolate_chan(priv, channel, &ch_eeprom_info);
1662
1663         /* calculate tx gain adjustment based on power supply voltage */
1664         voltage = priv->calib_info->voltage;
1665         init_voltage = (s32)le32_to_cpu(priv->card_alive_init.voltage);
1666         voltage_compensation =
1667             iwl4965_get_voltage_compensation(voltage, init_voltage);
1668
1669         IWL_DEBUG_TXPOWER("curr volt %d eeprom volt %d volt comp %d\n",
1670                           init_voltage,
1671                           voltage, voltage_compensation);
1672
1673         /* get current temperature (Celsius) */
1674         current_temp = max(priv->temperature, IWL_TX_POWER_TEMPERATURE_MIN);
1675         current_temp = min(priv->temperature, IWL_TX_POWER_TEMPERATURE_MAX);
1676         current_temp = KELVIN_TO_CELSIUS(current_temp);
1677
1678         /* select thermal txpower adjustment params, based on channel group
1679          *   (same frequency group used for mimo txatten adjustment) */
1680         degrees_per_05db_num =
1681             tx_power_cmp_tble[txatten_grp].degrees_per_05db_a;
1682         degrees_per_05db_denom =
1683             tx_power_cmp_tble[txatten_grp].degrees_per_05db_a_denom;
1684
1685         /* get per-chain txpower values from factory measurements */
1686         for (c = 0; c < 2; c++) {
1687                 measurement = &ch_eeprom_info.measurements[c][1];
1688
1689                 /* txgain adjustment (in half-dB steps) based on difference
1690                  *   between factory and current temperature */
1691                 factory_temp = measurement->temperature;
1692                 iwl4965_math_div_round((current_temp - factory_temp) *
1693                                        degrees_per_05db_denom,
1694                                        degrees_per_05db_num,
1695                                        &temperature_comp[c]);
1696
1697                 factory_gain_index[c] = measurement->gain_idx;
1698                 factory_actual_pwr[c] = measurement->actual_pow;
1699
1700                 IWL_DEBUG_TXPOWER("chain = %d\n", c);
1701                 IWL_DEBUG_TXPOWER("fctry tmp %d, "
1702                                   "curr tmp %d, comp %d steps\n",
1703                                   factory_temp, current_temp,
1704                                   temperature_comp[c]);
1705
1706                 IWL_DEBUG_TXPOWER("fctry idx %d, fctry pwr %d\n",
1707                                   factory_gain_index[c],
1708                                   factory_actual_pwr[c]);
1709         }
1710
1711         /* for each of 33 bit-rates (including 1 for CCK) */
1712         for (i = 0; i < POWER_TABLE_NUM_ENTRIES; i++) {
1713                 u8 is_mimo_rate;
1714                 union iwl4965_tx_power_dual_stream tx_power;
1715
1716                 /* for mimo, reduce each chain's txpower by half
1717                  * (3dB, 6 steps), so total output power is regulatory
1718                  * compliant. */
1719                 if (i & 0x8) {
1720                         current_regulatory = reg_limit -
1721                             IWL_TX_POWER_MIMO_REGULATORY_COMPENSATION;
1722                         is_mimo_rate = 1;
1723                 } else {
1724                         current_regulatory = reg_limit;
1725                         is_mimo_rate = 0;
1726                 }
1727
1728                 /* find txpower limit, either hardware or regulatory */
1729                 power_limit = saturation_power - back_off_table[i];
1730                 if (power_limit > current_regulatory)
1731                         power_limit = current_regulatory;
1732
1733                 /* reduce user's txpower request if necessary
1734                  * for this rate on this channel */
1735                 target_power = user_target_power;
1736                 if (target_power > power_limit)
1737                         target_power = power_limit;
1738
1739                 IWL_DEBUG_TXPOWER("rate %d sat %d reg %d usr %d tgt %d\n",
1740                                   i, saturation_power - back_off_table[i],
1741                                   current_regulatory, user_target_power,
1742                                   target_power);
1743
1744                 /* for each of 2 Tx chains (radio transmitters) */
1745                 for (c = 0; c < 2; c++) {
1746                         s32 atten_value;
1747
1748                         if (is_mimo_rate)
1749                                 atten_value =
1750                                     (s32)le32_to_cpu(priv->card_alive_init.
1751                                     tx_atten[txatten_grp][c]);
1752                         else
1753                                 atten_value = 0;
1754
1755                         /* calculate index; higher index means lower txpower */
1756                         power_index = (u8) (factory_gain_index[c] -
1757                                             (target_power -
1758                                              factory_actual_pwr[c]) -
1759                                             temperature_comp[c] -
1760                                             voltage_compensation +
1761                                             atten_value);
1762
1763 /*                      IWL_DEBUG_TXPOWER("calculated txpower index %d\n",
1764                                                 power_index); */
1765
1766                         if (power_index < get_min_power_index(i, band))
1767                                 power_index = get_min_power_index(i, band);
1768
1769                         /* adjust 5 GHz index to support negative indexes */
1770                         if (!band)
1771                                 power_index += 9;
1772
1773                         /* CCK, rate 32, reduce txpower for CCK */
1774                         if (i == POWER_TABLE_CCK_ENTRY)
1775                                 power_index +=
1776                                     IWL_TX_POWER_CCK_COMPENSATION_C_STEP;
1777
1778                         /* stay within the table! */
1779                         if (power_index > 107) {
1780                                 IWL_WARNING("txpower index %d > 107\n",
1781                                             power_index);
1782                                 power_index = 107;
1783                         }
1784                         if (power_index < 0) {
1785                                 IWL_WARNING("txpower index %d < 0\n",
1786                                             power_index);
1787                                 power_index = 0;
1788                         }
1789
1790                         /* fill txpower command for this rate/chain */
1791                         tx_power.s.radio_tx_gain[c] =
1792                                 gain_table[band][power_index].radio;
1793                         tx_power.s.dsp_predis_atten[c] =
1794                                 gain_table[band][power_index].dsp;
1795
1796                         IWL_DEBUG_TXPOWER("chain %d mimo %d index %d "
1797                                           "gain 0x%02x dsp %d\n",
1798                                           c, atten_value, power_index,
1799                                         tx_power.s.radio_tx_gain[c],
1800                                         tx_power.s.dsp_predis_atten[c]);
1801                 }/* for each chain */
1802
1803                 tx_power_tbl->power_tbl[i].dw = cpu_to_le32(tx_power.dw);
1804
1805         }/* for each rate */
1806
1807         return 0;
1808 }
1809
1810 /**
1811  * iwl4965_hw_reg_send_txpower - Configure the TXPOWER level user limit
1812  *
1813  * Uses the active RXON for channel, band, and characteristics (fat, high)
1814  * The power limit is taken from priv->user_txpower_limit.
1815  */
1816 int iwl4965_hw_reg_send_txpower(struct iwl_priv *priv)
1817 {
1818         struct iwl4965_txpowertable_cmd cmd = { 0 };
1819         int ret;
1820         u8 band = 0;
1821         u8 is_fat = 0;
1822         u8 ctrl_chan_high = 0;
1823
1824         if (test_bit(STATUS_SCANNING, &priv->status)) {
1825                 /* If this gets hit a lot, switch it to a BUG() and catch
1826                  * the stack trace to find out who is calling this during
1827                  * a scan. */
1828                 IWL_WARNING("TX Power requested while scanning!\n");
1829                 return -EAGAIN;
1830         }
1831
1832         band = priv->band == IEEE80211_BAND_2GHZ;
1833
1834         is_fat =  is_fat_channel(priv->active_rxon.flags);
1835
1836         if (is_fat &&
1837             (priv->active_rxon.flags & RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK))
1838                 ctrl_chan_high = 1;
1839
1840         cmd.band = band;
1841         cmd.channel = priv->active_rxon.channel;
1842
1843         ret = iwl4965_fill_txpower_tbl(priv, band,
1844                                 le16_to_cpu(priv->active_rxon.channel),
1845                                 is_fat, ctrl_chan_high, &cmd.tx_power);
1846         if (ret)
1847                 goto out;
1848
1849         ret = iwl_send_cmd_pdu(priv, REPLY_TX_PWR_TABLE_CMD, sizeof(cmd), &cmd);
1850
1851 out:
1852         return ret;
1853 }
1854
1855 static int iwl4965_send_rxon_assoc(struct iwl_priv *priv)
1856 {
1857         int ret = 0;
1858         struct iwl4965_rxon_assoc_cmd rxon_assoc;
1859         const struct iwl4965_rxon_cmd *rxon1 = &priv->staging_rxon;
1860         const struct iwl4965_rxon_cmd *rxon2 = &priv->active_rxon;
1861
1862         if ((rxon1->flags == rxon2->flags) &&
1863             (rxon1->filter_flags == rxon2->filter_flags) &&
1864             (rxon1->cck_basic_rates == rxon2->cck_basic_rates) &&
1865             (rxon1->ofdm_ht_single_stream_basic_rates ==
1866              rxon2->ofdm_ht_single_stream_basic_rates) &&
1867             (rxon1->ofdm_ht_dual_stream_basic_rates ==
1868              rxon2->ofdm_ht_dual_stream_basic_rates) &&
1869             (rxon1->rx_chain == rxon2->rx_chain) &&
1870             (rxon1->ofdm_basic_rates == rxon2->ofdm_basic_rates)) {
1871                 IWL_DEBUG_INFO("Using current RXON_ASSOC.  Not resending.\n");
1872                 return 0;
1873         }
1874
1875         rxon_assoc.flags = priv->staging_rxon.flags;
1876         rxon_assoc.filter_flags = priv->staging_rxon.filter_flags;
1877         rxon_assoc.ofdm_basic_rates = priv->staging_rxon.ofdm_basic_rates;
1878         rxon_assoc.cck_basic_rates = priv->staging_rxon.cck_basic_rates;
1879         rxon_assoc.reserved = 0;
1880         rxon_assoc.ofdm_ht_single_stream_basic_rates =
1881             priv->staging_rxon.ofdm_ht_single_stream_basic_rates;
1882         rxon_assoc.ofdm_ht_dual_stream_basic_rates =
1883             priv->staging_rxon.ofdm_ht_dual_stream_basic_rates;
1884         rxon_assoc.rx_chain_select_flags = priv->staging_rxon.rx_chain;
1885
1886         ret = iwl_send_cmd_pdu_async(priv, REPLY_RXON_ASSOC,
1887                                      sizeof(rxon_assoc), &rxon_assoc, NULL);
1888         if (ret)
1889                 return ret;
1890
1891         return ret;
1892 }
1893
1894
1895 int iwl4965_hw_channel_switch(struct iwl_priv *priv, u16 channel)
1896 {
1897         int rc;
1898         u8 band = 0;
1899         u8 is_fat = 0;
1900         u8 ctrl_chan_high = 0;
1901         struct iwl4965_channel_switch_cmd cmd = { 0 };
1902         const struct iwl_channel_info *ch_info;
1903
1904         band = priv->band == IEEE80211_BAND_2GHZ;
1905
1906         ch_info = iwl_get_channel_info(priv, priv->band, channel);
1907
1908         is_fat = is_fat_channel(priv->staging_rxon.flags);
1909
1910         if (is_fat &&
1911             (priv->active_rxon.flags & RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK))
1912                 ctrl_chan_high = 1;
1913
1914         cmd.band = band;
1915         cmd.expect_beacon = 0;
1916         cmd.channel = cpu_to_le16(channel);
1917         cmd.rxon_flags = priv->active_rxon.flags;
1918         cmd.rxon_filter_flags = priv->active_rxon.filter_flags;
1919         cmd.switch_time = cpu_to_le32(priv->ucode_beacon_time);
1920         if (ch_info)
1921                 cmd.expect_beacon = is_channel_radar(ch_info);
1922         else
1923                 cmd.expect_beacon = 1;
1924
1925         rc = iwl4965_fill_txpower_tbl(priv, band, channel, is_fat,
1926                                       ctrl_chan_high, &cmd.tx_power);
1927         if (rc) {
1928                 IWL_DEBUG_11H("error:%d  fill txpower_tbl\n", rc);
1929                 return rc;
1930         }
1931
1932         rc = iwl_send_cmd_pdu(priv, REPLY_CHANNEL_SWITCH, sizeof(cmd), &cmd);
1933         return rc;
1934 }
1935
1936 #define RTS_HCCA_RETRY_LIMIT            3
1937 #define RTS_DFAULT_RETRY_LIMIT          60
1938
1939 void iwl4965_hw_build_tx_cmd_rate(struct iwl_priv *priv,
1940                               struct iwl_cmd *cmd,
1941                               struct ieee80211_tx_control *ctrl,
1942                               struct ieee80211_hdr *hdr, int sta_id,
1943                               int is_hcca)
1944 {
1945         struct iwl4965_tx_cmd *tx = &cmd->cmd.tx;
1946         u8 rts_retry_limit = 0;
1947         u8 data_retry_limit = 0;
1948         u16 fc = le16_to_cpu(hdr->frame_control);
1949         u8 rate_plcp;
1950         u16 rate_flags = 0;
1951         int rate_idx = min(ctrl->tx_rate->hw_value & 0xffff, IWL_RATE_COUNT - 1);
1952
1953         rate_plcp = iwl4965_rates[rate_idx].plcp;
1954
1955         rts_retry_limit = (is_hcca) ?
1956             RTS_HCCA_RETRY_LIMIT : RTS_DFAULT_RETRY_LIMIT;
1957
1958         if ((rate_idx >= IWL_FIRST_CCK_RATE) && (rate_idx <= IWL_LAST_CCK_RATE))
1959                 rate_flags |= RATE_MCS_CCK_MSK;
1960
1961
1962         if (ieee80211_is_probe_response(fc)) {
1963                 data_retry_limit = 3;
1964                 if (data_retry_limit < rts_retry_limit)
1965                         rts_retry_limit = data_retry_limit;
1966         } else
1967                 data_retry_limit = IWL_DEFAULT_TX_RETRY;
1968
1969         if (priv->data_retry_limit != -1)
1970                 data_retry_limit = priv->data_retry_limit;
1971
1972
1973         if (ieee80211_is_data(fc)) {
1974                 tx->initial_rate_index = 0;
1975                 tx->tx_flags |= TX_CMD_FLG_STA_RATE_MSK;
1976         } else {
1977                 switch (fc & IEEE80211_FCTL_STYPE) {
1978                 case IEEE80211_STYPE_AUTH:
1979                 case IEEE80211_STYPE_DEAUTH:
1980                 case IEEE80211_STYPE_ASSOC_REQ:
1981                 case IEEE80211_STYPE_REASSOC_REQ:
1982                         if (tx->tx_flags & TX_CMD_FLG_RTS_MSK) {
1983                                 tx->tx_flags &= ~TX_CMD_FLG_RTS_MSK;
1984                                 tx->tx_flags |= TX_CMD_FLG_CTS_MSK;
1985                         }
1986                         break;
1987                 default:
1988                         break;
1989                 }
1990
1991                 /* Alternate between antenna A and B for successive frames */
1992                 if (priv->use_ant_b_for_management_frame) {
1993                         priv->use_ant_b_for_management_frame = 0;
1994                         rate_flags |= RATE_MCS_ANT_B_MSK;
1995                 } else {
1996                         priv->use_ant_b_for_management_frame = 1;
1997                         rate_flags |= RATE_MCS_ANT_A_MSK;
1998                 }
1999         }
2000
2001         tx->rts_retry_limit = rts_retry_limit;
2002         tx->data_retry_limit = data_retry_limit;
2003         tx->rate_n_flags = iwl4965_hw_set_rate_n_flags(rate_plcp, rate_flags);
2004 }
2005
2006 static int iwl4965_shared_mem_rx_idx(struct iwl_priv *priv)
2007 {
2008         struct iwl4965_shared *s = priv->shared_virt;
2009         return le32_to_cpu(s->rb_closed) & 0xFFF;
2010 }
2011
2012 int iwl4965_hw_get_temperature(struct iwl_priv *priv)
2013 {
2014         return priv->temperature;
2015 }
2016
2017 unsigned int iwl4965_hw_get_beacon_cmd(struct iwl_priv *priv,
2018                           struct iwl4965_frame *frame, u8 rate)
2019 {
2020         struct iwl4965_tx_beacon_cmd *tx_beacon_cmd;
2021         unsigned int frame_size;
2022
2023         tx_beacon_cmd = &frame->u.beacon;
2024         memset(tx_beacon_cmd, 0, sizeof(*tx_beacon_cmd));
2025
2026         tx_beacon_cmd->tx.sta_id = priv->hw_params.bcast_sta_id;
2027         tx_beacon_cmd->tx.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
2028
2029         frame_size = iwl4965_fill_beacon_frame(priv,
2030                                 tx_beacon_cmd->frame,
2031                                 iwl4965_broadcast_addr,
2032                                 sizeof(frame->u) - sizeof(*tx_beacon_cmd));
2033
2034         BUG_ON(frame_size > MAX_MPDU_SIZE);
2035         tx_beacon_cmd->tx.len = cpu_to_le16((u16)frame_size);
2036
2037         if ((rate == IWL_RATE_1M_PLCP) || (rate >= IWL_RATE_2M_PLCP))
2038                 tx_beacon_cmd->tx.rate_n_flags =
2039                         iwl4965_hw_set_rate_n_flags(rate, RATE_MCS_CCK_MSK);
2040         else
2041                 tx_beacon_cmd->tx.rate_n_flags =
2042                         iwl4965_hw_set_rate_n_flags(rate, 0);
2043
2044         tx_beacon_cmd->tx.tx_flags = (TX_CMD_FLG_SEQ_CTL_MSK |
2045                                 TX_CMD_FLG_TSF_MSK | TX_CMD_FLG_STA_RATE_MSK);
2046         return (sizeof(*tx_beacon_cmd) + frame_size);
2047 }
2048
2049 int iwl4965_hw_txq_attach_buf_to_tfd(struct iwl_priv *priv, void *ptr,
2050                                  dma_addr_t addr, u16 len)
2051 {
2052         int index, is_odd;
2053         struct iwl_tfd_frame *tfd = ptr;
2054         u32 num_tbs = IWL_GET_BITS(*tfd, num_tbs);
2055
2056         /* Each TFD can point to a maximum 20 Tx buffers */
2057         if ((num_tbs >= MAX_NUM_OF_TBS) || (num_tbs < 0)) {
2058                 IWL_ERROR("Error can not send more than %d chunks\n",
2059                           MAX_NUM_OF_TBS);
2060                 return -EINVAL;
2061         }
2062
2063         index = num_tbs / 2;
2064         is_odd = num_tbs & 0x1;
2065
2066         if (!is_odd) {
2067                 tfd->pa[index].tb1_addr = cpu_to_le32(addr);
2068                 IWL_SET_BITS(tfd->pa[index], tb1_addr_hi,
2069                              iwl_get_dma_hi_address(addr));
2070                 IWL_SET_BITS(tfd->pa[index], tb1_len, len);
2071         } else {
2072                 IWL_SET_BITS(tfd->pa[index], tb2_addr_lo16,
2073                              (u32) (addr & 0xffff));
2074                 IWL_SET_BITS(tfd->pa[index], tb2_addr_hi20, addr >> 16);
2075                 IWL_SET_BITS(tfd->pa[index], tb2_len, len);
2076         }
2077
2078         IWL_SET_BITS(*tfd, num_tbs, num_tbs + 1);
2079
2080         return 0;
2081 }
2082
2083 static int iwl4965_alloc_shared_mem(struct iwl_priv *priv)
2084 {
2085         priv->shared_virt = pci_alloc_consistent(priv->pci_dev,
2086                                         sizeof(struct iwl4965_shared),
2087                                         &priv->shared_phys);
2088         if (!priv->shared_virt)
2089                 return -ENOMEM;
2090
2091         memset(priv->shared_virt, 0, sizeof(struct iwl4965_shared));
2092
2093         priv->rb_closed_offset = offsetof(struct iwl4965_shared, rb_closed);
2094
2095         return 0;
2096 }
2097
2098 static void iwl4965_free_shared_mem(struct iwl_priv *priv)
2099 {
2100         if (priv->shared_virt)
2101                 pci_free_consistent(priv->pci_dev,
2102                                     sizeof(struct iwl4965_shared),
2103                                     priv->shared_virt,
2104                                     priv->shared_phys);
2105 }
2106
2107 /**
2108  * iwl4965_txq_update_byte_cnt_tbl - Set up entry in Tx byte-count array
2109  */
2110 static void iwl4965_txq_update_byte_cnt_tbl(struct iwl_priv *priv,
2111                                             struct iwl_tx_queue *txq,
2112                                             u16 byte_cnt)
2113 {
2114         int len;
2115         int txq_id = txq->q.id;
2116         struct iwl4965_shared *shared_data = priv->shared_virt;
2117
2118         len = byte_cnt + IWL_TX_CRC_SIZE + IWL_TX_DELIMITER_SIZE;
2119
2120         /* Set up byte count within first 256 entries */
2121         IWL_SET_BITS16(shared_data->queues_byte_cnt_tbls[txq_id].
2122                        tfd_offset[txq->q.write_ptr], byte_cnt, len);
2123
2124         /* If within first 64 entries, duplicate at end */
2125         if (txq->q.write_ptr < IWL49_MAX_WIN_SIZE)
2126                 IWL_SET_BITS16(shared_data->queues_byte_cnt_tbls[txq_id].
2127                         tfd_offset[IWL49_QUEUE_SIZE + txq->q.write_ptr],
2128                         byte_cnt, len);
2129 }
2130
2131 /**
2132  * sign_extend - Sign extend a value using specified bit as sign-bit
2133  *
2134  * Example: sign_extend(9, 3) would return -7 as bit3 of 1001b is 1
2135  * and bit0..2 is 001b which when sign extended to 1111111111111001b is -7.
2136  *
2137  * @param oper value to sign extend
2138  * @param index 0 based bit index (0<=index<32) to sign bit
2139  */
2140 static s32 sign_extend(u32 oper, int index)
2141 {
2142         u8 shift = 31 - index;
2143
2144         return (s32)(oper << shift) >> shift;
2145 }
2146
2147 /**
2148  * iwl4965_get_temperature - return the calibrated temperature (in Kelvin)
2149  * @statistics: Provides the temperature reading from the uCode
2150  *
2151  * A return of <0 indicates bogus data in the statistics
2152  */
2153 int iwl4965_get_temperature(const struct iwl_priv *priv)
2154 {
2155         s32 temperature;
2156         s32 vt;
2157         s32 R1, R2, R3;
2158         u32 R4;
2159
2160         if (test_bit(STATUS_TEMPERATURE, &priv->status) &&
2161                 (priv->statistics.flag & STATISTICS_REPLY_FLG_FAT_MODE_MSK)) {
2162                 IWL_DEBUG_TEMP("Running FAT temperature calibration\n");
2163                 R1 = (s32)le32_to_cpu(priv->card_alive_init.therm_r1[1]);
2164                 R2 = (s32)le32_to_cpu(priv->card_alive_init.therm_r2[1]);
2165                 R3 = (s32)le32_to_cpu(priv->card_alive_init.therm_r3[1]);
2166                 R4 = le32_to_cpu(priv->card_alive_init.therm_r4[1]);
2167         } else {
2168                 IWL_DEBUG_TEMP("Running temperature calibration\n");
2169                 R1 = (s32)le32_to_cpu(priv->card_alive_init.therm_r1[0]);
2170                 R2 = (s32)le32_to_cpu(priv->card_alive_init.therm_r2[0]);
2171                 R3 = (s32)le32_to_cpu(priv->card_alive_init.therm_r3[0]);
2172                 R4 = le32_to_cpu(priv->card_alive_init.therm_r4[0]);
2173         }
2174
2175         /*
2176          * Temperature is only 23 bits, so sign extend out to 32.
2177          *
2178          * NOTE If we haven't received a statistics notification yet
2179          * with an updated temperature, use R4 provided to us in the
2180          * "initialize" ALIVE response.
2181          */
2182         if (!test_bit(STATUS_TEMPERATURE, &priv->status))
2183                 vt = sign_extend(R4, 23);
2184         else
2185                 vt = sign_extend(
2186                         le32_to_cpu(priv->statistics.general.temperature), 23);
2187
2188         IWL_DEBUG_TEMP("Calib values R[1-3]: %d %d %d R4: %d\n",
2189                        R1, R2, R3, vt);
2190
2191         if (R3 == R1) {
2192                 IWL_ERROR("Calibration conflict R1 == R3\n");
2193                 return -1;
2194         }
2195
2196         /* Calculate temperature in degrees Kelvin, adjust by 97%.
2197          * Add offset to center the adjustment around 0 degrees Centigrade. */
2198         temperature = TEMPERATURE_CALIB_A_VAL * (vt - R2);
2199         temperature /= (R3 - R1);
2200         temperature = (temperature * 97) / 100 +
2201             TEMPERATURE_CALIB_KELVIN_OFFSET;
2202
2203         IWL_DEBUG_TEMP("Calibrated temperature: %dK, %dC\n", temperature,
2204             KELVIN_TO_CELSIUS(temperature));
2205
2206         return temperature;
2207 }
2208
2209 /* Adjust Txpower only if temperature variance is greater than threshold. */
2210 #define IWL_TEMPERATURE_THRESHOLD   3
2211
2212 /**
2213  * iwl4965_is_temp_calib_needed - determines if new calibration is needed
2214  *
2215  * If the temperature changed has changed sufficiently, then a recalibration
2216  * is needed.
2217  *
2218  * Assumes caller will replace priv->last_temperature once calibration
2219  * executed.
2220  */
2221 static int iwl4965_is_temp_calib_needed(struct iwl_priv *priv)
2222 {
2223         int temp_diff;
2224
2225         if (!test_bit(STATUS_STATISTICS, &priv->status)) {
2226                 IWL_DEBUG_TEMP("Temperature not updated -- no statistics.\n");
2227                 return 0;
2228         }
2229
2230         temp_diff = priv->temperature - priv->last_temperature;
2231
2232         /* get absolute value */
2233         if (temp_diff < 0) {
2234                 IWL_DEBUG_POWER("Getting cooler, delta %d, \n", temp_diff);
2235                 temp_diff = -temp_diff;
2236         } else if (temp_diff == 0)
2237                 IWL_DEBUG_POWER("Same temp, \n");
2238         else
2239                 IWL_DEBUG_POWER("Getting warmer, delta %d, \n", temp_diff);
2240
2241         if (temp_diff < IWL_TEMPERATURE_THRESHOLD) {
2242                 IWL_DEBUG_POWER("Thermal txpower calib not needed\n");
2243                 return 0;
2244         }
2245
2246         IWL_DEBUG_POWER("Thermal txpower calib needed\n");
2247
2248         return 1;
2249 }
2250
2251 /* Calculate noise level, based on measurements during network silence just
2252  *   before arriving beacon.  This measurement can be done only if we know
2253  *   exactly when to expect beacons, therefore only when we're associated. */
2254 static void iwl4965_rx_calc_noise(struct iwl_priv *priv)
2255 {
2256         struct statistics_rx_non_phy *rx_info
2257                                 = &(priv->statistics.rx.general);
2258         int num_active_rx = 0;
2259         int total_silence = 0;
2260         int bcn_silence_a =
2261                 le32_to_cpu(rx_info->beacon_silence_rssi_a) & IN_BAND_FILTER;
2262         int bcn_silence_b =
2263                 le32_to_cpu(rx_info->beacon_silence_rssi_b) & IN_BAND_FILTER;
2264         int bcn_silence_c =
2265                 le32_to_cpu(rx_info->beacon_silence_rssi_c) & IN_BAND_FILTER;
2266
2267         if (bcn_silence_a) {
2268                 total_silence += bcn_silence_a;
2269                 num_active_rx++;
2270         }
2271         if (bcn_silence_b) {
2272                 total_silence += bcn_silence_b;
2273                 num_active_rx++;
2274         }
2275         if (bcn_silence_c) {
2276                 total_silence += bcn_silence_c;
2277                 num_active_rx++;
2278         }
2279
2280         /* Average among active antennas */
2281         if (num_active_rx)
2282                 priv->last_rx_noise = (total_silence / num_active_rx) - 107;
2283         else
2284                 priv->last_rx_noise = IWL_NOISE_MEAS_NOT_AVAILABLE;
2285
2286         IWL_DEBUG_CALIB("inband silence a %u, b %u, c %u, dBm %d\n",
2287                         bcn_silence_a, bcn_silence_b, bcn_silence_c,
2288                         priv->last_rx_noise);
2289 }
2290
2291 void iwl4965_hw_rx_statistics(struct iwl_priv *priv,
2292                               struct iwl_rx_mem_buffer *rxb)
2293 {
2294         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
2295         int change;
2296         s32 temp;
2297
2298         IWL_DEBUG_RX("Statistics notification received (%d vs %d).\n",
2299                      (int)sizeof(priv->statistics), pkt->len);
2300
2301         change = ((priv->statistics.general.temperature !=
2302                    pkt->u.stats.general.temperature) ||
2303                   ((priv->statistics.flag &
2304                     STATISTICS_REPLY_FLG_FAT_MODE_MSK) !=
2305                    (pkt->u.stats.flag & STATISTICS_REPLY_FLG_FAT_MODE_MSK)));
2306
2307         memcpy(&priv->statistics, &pkt->u.stats, sizeof(priv->statistics));
2308
2309         set_bit(STATUS_STATISTICS, &priv->status);
2310
2311         /* Reschedule the statistics timer to occur in
2312          * REG_RECALIB_PERIOD seconds to ensure we get a
2313          * thermal update even if the uCode doesn't give
2314          * us one */
2315         mod_timer(&priv->statistics_periodic, jiffies +
2316                   msecs_to_jiffies(REG_RECALIB_PERIOD * 1000));
2317
2318         if (unlikely(!test_bit(STATUS_SCANNING, &priv->status)) &&
2319             (pkt->hdr.cmd == STATISTICS_NOTIFICATION)) {
2320                 iwl4965_rx_calc_noise(priv);
2321 #ifdef CONFIG_IWL4965_RUN_TIME_CALIB
2322                 queue_work(priv->workqueue, &priv->sensitivity_work);
2323 #endif
2324         }
2325
2326         iwl_leds_background(priv);
2327
2328         /* If the hardware hasn't reported a change in
2329          * temperature then don't bother computing a
2330          * calibrated temperature value */
2331         if (!change)
2332                 return;
2333
2334         temp = iwl4965_get_temperature(priv);
2335         if (temp < 0)
2336                 return;
2337
2338         if (priv->temperature != temp) {
2339                 if (priv->temperature)
2340                         IWL_DEBUG_TEMP("Temperature changed "
2341                                        "from %dC to %dC\n",
2342                                        KELVIN_TO_CELSIUS(priv->temperature),
2343                                        KELVIN_TO_CELSIUS(temp));
2344                 else
2345                         IWL_DEBUG_TEMP("Temperature "
2346                                        "initialized to %dC\n",
2347                                        KELVIN_TO_CELSIUS(temp));
2348         }
2349
2350         priv->temperature = temp;
2351         set_bit(STATUS_TEMPERATURE, &priv->status);
2352
2353         if (unlikely(!test_bit(STATUS_SCANNING, &priv->status)) &&
2354                      iwl4965_is_temp_calib_needed(priv))
2355                 queue_work(priv->workqueue, &priv->txpower_work);
2356 }
2357
2358 static void iwl4965_add_radiotap(struct iwl_priv *priv,
2359                                  struct sk_buff *skb,
2360                                  struct iwl4965_rx_phy_res *rx_start,
2361                                  struct ieee80211_rx_status *stats,
2362                                  u32 ampdu_status)
2363 {
2364         s8 signal = stats->ssi;
2365         s8 noise = 0;
2366         int rate = stats->rate_idx;
2367         u64 tsf = stats->mactime;
2368         __le16 antenna;
2369         __le16 phy_flags_hw = rx_start->phy_flags;
2370         struct iwl4965_rt_rx_hdr {
2371                 struct ieee80211_radiotap_header rt_hdr;
2372                 __le64 rt_tsf;          /* TSF */
2373                 u8 rt_flags;            /* radiotap packet flags */
2374                 u8 rt_rate;             /* rate in 500kb/s */
2375                 __le16 rt_channelMHz;   /* channel in MHz */
2376                 __le16 rt_chbitmask;    /* channel bitfield */
2377                 s8 rt_dbmsignal;        /* signal in dBm, kluged to signed */
2378                 s8 rt_dbmnoise;
2379                 u8 rt_antenna;          /* antenna number */
2380         } __attribute__ ((packed)) *iwl4965_rt;
2381
2382         /* TODO: We won't have enough headroom for HT frames. Fix it later. */
2383         if (skb_headroom(skb) < sizeof(*iwl4965_rt)) {
2384                 if (net_ratelimit())
2385                         printk(KERN_ERR "not enough headroom [%d] for "
2386                                "radiotap head [%zd]\n",
2387                                skb_headroom(skb), sizeof(*iwl4965_rt));
2388                 return;
2389         }
2390
2391         /* put radiotap header in front of 802.11 header and data */
2392         iwl4965_rt = (void *)skb_push(skb, sizeof(*iwl4965_rt));
2393
2394         /* initialise radiotap header */
2395         iwl4965_rt->rt_hdr.it_version = PKTHDR_RADIOTAP_VERSION;
2396         iwl4965_rt->rt_hdr.it_pad = 0;
2397
2398         /* total header + data */
2399         put_unaligned(cpu_to_le16(sizeof(*iwl4965_rt)),
2400                       &iwl4965_rt->rt_hdr.it_len);
2401
2402         /* Indicate all the fields we add to the radiotap header */
2403         put_unaligned(cpu_to_le32((1 << IEEE80211_RADIOTAP_TSFT) |
2404                                   (1 << IEEE80211_RADIOTAP_FLAGS) |
2405                                   (1 << IEEE80211_RADIOTAP_RATE) |
2406                                   (1 << IEEE80211_RADIOTAP_CHANNEL) |
2407                                   (1 << IEEE80211_RADIOTAP_DBM_ANTSIGNAL) |
2408                                   (1 << IEEE80211_RADIOTAP_DBM_ANTNOISE) |
2409                                   (1 << IEEE80211_RADIOTAP_ANTENNA)),
2410                       &iwl4965_rt->rt_hdr.it_present);
2411
2412         /* Zero the flags, we'll add to them as we go */
2413         iwl4965_rt->rt_flags = 0;
2414
2415         put_unaligned(cpu_to_le64(tsf), &iwl4965_rt->rt_tsf);
2416
2417         iwl4965_rt->rt_dbmsignal = signal;
2418         iwl4965_rt->rt_dbmnoise = noise;
2419
2420         /* Convert the channel frequency and set the flags */
2421         put_unaligned(cpu_to_le16(stats->freq), &iwl4965_rt->rt_channelMHz);
2422         if (!(phy_flags_hw & RX_RES_PHY_FLAGS_BAND_24_MSK))
2423                 put_unaligned(cpu_to_le16(IEEE80211_CHAN_OFDM |
2424                                           IEEE80211_CHAN_5GHZ),
2425                               &iwl4965_rt->rt_chbitmask);
2426         else if (phy_flags_hw & RX_RES_PHY_FLAGS_MOD_CCK_MSK)
2427                 put_unaligned(cpu_to_le16(IEEE80211_CHAN_CCK |
2428                                           IEEE80211_CHAN_2GHZ),
2429                               &iwl4965_rt->rt_chbitmask);
2430         else    /* 802.11g */
2431                 put_unaligned(cpu_to_le16(IEEE80211_CHAN_OFDM |
2432                                           IEEE80211_CHAN_2GHZ),
2433                               &iwl4965_rt->rt_chbitmask);
2434
2435         if (rate == -1)
2436                 iwl4965_rt->rt_rate = 0;
2437         else
2438                 iwl4965_rt->rt_rate = iwl4965_rates[rate].ieee;
2439
2440         /*
2441          * "antenna number"
2442          *
2443          * It seems that the antenna field in the phy flags value
2444          * is actually a bitfield. This is undefined by radiotap,
2445          * it wants an actual antenna number but I always get "7"
2446          * for most legacy frames I receive indicating that the
2447          * same frame was received on all three RX chains.
2448          *
2449          * I think this field should be removed in favour of a
2450          * new 802.11n radiotap field "RX chains" that is defined
2451          * as a bitmask.
2452          */
2453         antenna = phy_flags_hw & RX_RES_PHY_FLAGS_ANTENNA_MSK;
2454         iwl4965_rt->rt_antenna = le16_to_cpu(antenna) >> 4;
2455
2456         /* set the preamble flag if appropriate */
2457         if (phy_flags_hw & RX_RES_PHY_FLAGS_SHORT_PREAMBLE_MSK)
2458                 iwl4965_rt->rt_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
2459
2460         stats->flag |= RX_FLAG_RADIOTAP;
2461 }
2462
2463 static void iwl_update_rx_stats(struct iwl_priv *priv, u16 fc, u16 len)
2464 {
2465         /* 0 - mgmt, 1 - cnt, 2 - data */
2466         int idx = (fc & IEEE80211_FCTL_FTYPE) >> 2;
2467         priv->rx_stats[idx].cnt++;
2468         priv->rx_stats[idx].bytes += len;
2469 }
2470
2471 /*
2472  * returns non-zero if packet should be dropped
2473  */
2474 static int iwl4965_set_decrypted_flag(struct iwl_priv *priv,
2475                                       struct ieee80211_hdr *hdr,
2476                                       u32 decrypt_res,
2477                                       struct ieee80211_rx_status *stats)
2478 {
2479         u16 fc = le16_to_cpu(hdr->frame_control);
2480
2481         if (priv->active_rxon.filter_flags & RXON_FILTER_DIS_DECRYPT_MSK)
2482                 return 0;
2483
2484         if (!(fc & IEEE80211_FCTL_PROTECTED))
2485                 return 0;
2486
2487         IWL_DEBUG_RX("decrypt_res:0x%x\n", decrypt_res);
2488         switch (decrypt_res & RX_RES_STATUS_SEC_TYPE_MSK) {
2489         case RX_RES_STATUS_SEC_TYPE_TKIP:
2490                 /* The uCode has got a bad phase 1 Key, pushes the packet.
2491                  * Decryption will be done in SW. */
2492                 if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) ==
2493                     RX_RES_STATUS_BAD_KEY_TTAK)
2494                         break;
2495
2496                 if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) ==
2497                     RX_RES_STATUS_BAD_ICV_MIC) {
2498                         /* bad ICV, the packet is destroyed since the
2499                          * decryption is inplace, drop it */
2500                         IWL_DEBUG_RX("Packet destroyed\n");
2501                         return -1;
2502                 }
2503         case RX_RES_STATUS_SEC_TYPE_WEP:
2504         case RX_RES_STATUS_SEC_TYPE_CCMP:
2505                 if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) ==
2506                     RX_RES_STATUS_DECRYPT_OK) {
2507                         IWL_DEBUG_RX("hw decrypt successfully!!!\n");
2508                         stats->flag |= RX_FLAG_DECRYPTED;
2509                 }
2510                 break;
2511
2512         default:
2513                 break;
2514         }
2515         return 0;
2516 }
2517
2518 static u32 iwl4965_translate_rx_status(struct iwl_priv *priv, u32 decrypt_in)
2519 {
2520         u32 decrypt_out = 0;
2521
2522         if ((decrypt_in & RX_RES_STATUS_STATION_FOUND) ==
2523                                         RX_RES_STATUS_STATION_FOUND)
2524                 decrypt_out |= (RX_RES_STATUS_STATION_FOUND |
2525                                 RX_RES_STATUS_NO_STATION_INFO_MISMATCH);
2526
2527         decrypt_out |= (decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK);
2528
2529         /* packet was not encrypted */
2530         if ((decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) ==
2531                                         RX_RES_STATUS_SEC_TYPE_NONE)
2532                 return decrypt_out;
2533
2534         /* packet was encrypted with unknown alg */
2535         if ((decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) ==
2536                                         RX_RES_STATUS_SEC_TYPE_ERR)
2537                 return decrypt_out;
2538
2539         /* decryption was not done in HW */
2540         if ((decrypt_in & RX_MPDU_RES_STATUS_DEC_DONE_MSK) !=
2541                                         RX_MPDU_RES_STATUS_DEC_DONE_MSK)
2542                 return decrypt_out;
2543
2544         switch (decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) {
2545
2546         case RX_RES_STATUS_SEC_TYPE_CCMP:
2547                 /* alg is CCM: check MIC only */
2548                 if (!(decrypt_in & RX_MPDU_RES_STATUS_MIC_OK))
2549                         /* Bad MIC */
2550                         decrypt_out |= RX_RES_STATUS_BAD_ICV_MIC;
2551                 else
2552                         decrypt_out |= RX_RES_STATUS_DECRYPT_OK;
2553
2554                 break;
2555
2556         case RX_RES_STATUS_SEC_TYPE_TKIP:
2557                 if (!(decrypt_in & RX_MPDU_RES_STATUS_TTAK_OK)) {
2558                         /* Bad TTAK */
2559                         decrypt_out |= RX_RES_STATUS_BAD_KEY_TTAK;
2560                         break;
2561                 }
2562                 /* fall through if TTAK OK */
2563         default:
2564                 if (!(decrypt_in & RX_MPDU_RES_STATUS_ICV_OK))
2565                         decrypt_out |= RX_RES_STATUS_BAD_ICV_MIC;
2566                 else
2567                         decrypt_out |= RX_RES_STATUS_DECRYPT_OK;
2568                 break;
2569         };
2570
2571         IWL_DEBUG_RX("decrypt_in:0x%x  decrypt_out = 0x%x\n",
2572                                         decrypt_in, decrypt_out);
2573
2574         return decrypt_out;
2575 }
2576
2577 static void iwl4965_handle_data_packet(struct iwl_priv *priv, int is_data,
2578                                        int include_phy,
2579                                        struct iwl_rx_mem_buffer *rxb,
2580                                        struct ieee80211_rx_status *stats)
2581 {
2582         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
2583         struct iwl4965_rx_phy_res *rx_start = (include_phy) ?
2584             (struct iwl4965_rx_phy_res *)&(pkt->u.raw[0]) : NULL;
2585         struct ieee80211_hdr *hdr;
2586         u16 len;
2587         __le32 *rx_end;
2588         unsigned int skblen;
2589         u32 ampdu_status;
2590         u32 ampdu_status_legacy;
2591
2592         if (!include_phy && priv->last_phy_res[0])
2593                 rx_start = (struct iwl4965_rx_phy_res *)&priv->last_phy_res[1];
2594
2595         if (!rx_start) {
2596                 IWL_ERROR("MPDU frame without a PHY data\n");
2597                 return;
2598         }
2599         if (include_phy) {
2600                 hdr = (struct ieee80211_hdr *)((u8 *) & rx_start[1] +
2601                                                rx_start->cfg_phy_cnt);
2602
2603                 len = le16_to_cpu(rx_start->byte_count);
2604
2605                 rx_end = (__le32 *) ((u8 *) & pkt->u.raw[0] +
2606                                   sizeof(struct iwl4965_rx_phy_res) +
2607                                   rx_start->cfg_phy_cnt + len);
2608
2609         } else {
2610                 struct iwl4965_rx_mpdu_res_start *amsdu =
2611                     (struct iwl4965_rx_mpdu_res_start *)pkt->u.raw;
2612
2613                 hdr = (struct ieee80211_hdr *)(pkt->u.raw +
2614                                sizeof(struct iwl4965_rx_mpdu_res_start));
2615                 len =  le16_to_cpu(amsdu->byte_count);
2616                 rx_start->byte_count = amsdu->byte_count;
2617                 rx_end = (__le32 *) (((u8 *) hdr) + len);
2618         }
2619         /* In monitor mode allow 802.11 ACk frames (10 bytes) */
2620         if (len > priv->hw_params.max_pkt_size ||
2621             len < ((priv->iw_mode == IEEE80211_IF_TYPE_MNTR) ? 10 : 16)) {
2622                 IWL_WARNING("byte count out of range [16,4K] : %d\n", len);
2623                 return;
2624         }
2625
2626         ampdu_status = le32_to_cpu(*rx_end);
2627         skblen = ((u8 *) rx_end - (u8 *) & pkt->u.raw[0]) + sizeof(u32);
2628
2629         if (!include_phy) {
2630                 /* New status scheme, need to translate */
2631                 ampdu_status_legacy = ampdu_status;
2632                 ampdu_status = iwl4965_translate_rx_status(priv, ampdu_status);
2633         }
2634
2635         /* start from MAC */
2636         skb_reserve(rxb->skb, (void *)hdr - (void *)pkt);
2637         skb_put(rxb->skb, len); /* end where data ends */
2638
2639         /* We only process data packets if the interface is open */
2640         if (unlikely(!priv->is_open)) {
2641                 IWL_DEBUG_DROP_LIMIT
2642                     ("Dropping packet while interface is not open.\n");
2643                 return;
2644         }
2645
2646         stats->flag = 0;
2647         hdr = (struct ieee80211_hdr *)rxb->skb->data;
2648
2649         /*  in case of HW accelerated crypto and bad decryption, drop */
2650         if (!priv->hw_params.sw_crypto &&
2651             iwl4965_set_decrypted_flag(priv, hdr, ampdu_status, stats))
2652                 return;
2653
2654         if (priv->add_radiotap)
2655                 iwl4965_add_radiotap(priv, rxb->skb, rx_start, stats, ampdu_status);
2656
2657         iwl_update_rx_stats(priv, le16_to_cpu(hdr->frame_control), len);
2658         ieee80211_rx_irqsafe(priv->hw, rxb->skb, stats);
2659         priv->alloc_rxb_skb--;
2660         rxb->skb = NULL;
2661 }
2662
2663 /* Calc max signal level (dBm) among 3 possible receivers */
2664 static int iwl4965_calc_rssi(struct iwl_priv *priv,
2665                              struct iwl4965_rx_phy_res *rx_resp)
2666 {
2667         /* data from PHY/DSP regarding signal strength, etc.,
2668          *   contents are always there, not configurable by host.  */
2669         struct iwl4965_rx_non_cfg_phy *ncphy =
2670             (struct iwl4965_rx_non_cfg_phy *)rx_resp->non_cfg_phy;
2671         u32 agc = (le16_to_cpu(ncphy->agc_info) & IWL_AGC_DB_MASK)
2672                         >> IWL_AGC_DB_POS;
2673
2674         u32 valid_antennae =
2675             (le16_to_cpu(rx_resp->phy_flags) & RX_PHY_FLAGS_ANTENNAE_MASK)
2676                         >> RX_PHY_FLAGS_ANTENNAE_OFFSET;
2677         u8 max_rssi = 0;
2678         u32 i;
2679
2680         /* Find max rssi among 3 possible receivers.
2681          * These values are measured by the digital signal processor (DSP).
2682          * They should stay fairly constant even as the signal strength varies,
2683          *   if the radio's automatic gain control (AGC) is working right.
2684          * AGC value (see below) will provide the "interesting" info. */
2685         for (i = 0; i < 3; i++)
2686                 if (valid_antennae & (1 << i))
2687                         max_rssi = max(ncphy->rssi_info[i << 1], max_rssi);
2688
2689         IWL_DEBUG_STATS("Rssi In A %d B %d C %d Max %d AGC dB %d\n",
2690                 ncphy->rssi_info[0], ncphy->rssi_info[2], ncphy->rssi_info[4],
2691                 max_rssi, agc);
2692
2693         /* dBm = max_rssi dB - agc dB - constant.
2694          * Higher AGC (higher radio gain) means lower signal. */
2695         return (max_rssi - agc - IWL_RSSI_OFFSET);
2696 }
2697
2698 static void iwl4965_sta_modify_ps_wake(struct iwl_priv *priv, int sta_id)
2699 {
2700         unsigned long flags;
2701
2702         spin_lock_irqsave(&priv->sta_lock, flags);
2703         priv->stations[sta_id].sta.station_flags &= ~STA_FLG_PWR_SAVE_MSK;
2704         priv->stations[sta_id].sta.station_flags_msk = STA_FLG_PWR_SAVE_MSK;
2705         priv->stations[sta_id].sta.sta.modify_mask = 0;
2706         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
2707         spin_unlock_irqrestore(&priv->sta_lock, flags);
2708
2709         iwl_send_add_sta(priv, &priv->stations[sta_id].sta, CMD_ASYNC);
2710 }
2711
2712 static void iwl4965_update_ps_mode(struct iwl_priv *priv, u16 ps_bit, u8 *addr)
2713 {
2714         /* FIXME: need locking over ps_status ??? */
2715         u8 sta_id = iwl_find_station(priv, addr);
2716
2717         if (sta_id != IWL_INVALID_STATION) {
2718                 u8 sta_awake = priv->stations[sta_id].
2719                                 ps_status == STA_PS_STATUS_WAKE;
2720
2721                 if (sta_awake && ps_bit)
2722                         priv->stations[sta_id].ps_status = STA_PS_STATUS_SLEEP;
2723                 else if (!sta_awake && !ps_bit) {
2724                         iwl4965_sta_modify_ps_wake(priv, sta_id);
2725                         priv->stations[sta_id].ps_status = STA_PS_STATUS_WAKE;
2726                 }
2727         }
2728 }
2729 #ifdef CONFIG_IWLWIFI_DEBUG
2730
2731 /**
2732  * iwl4965_dbg_report_frame - dump frame to syslog during debug sessions
2733  *
2734  * You may hack this function to show different aspects of received frames,
2735  * including selective frame dumps.
2736  * group100 parameter selects whether to show 1 out of 100 good frames.
2737  *
2738  * TODO:  This was originally written for 3945, need to audit for
2739  *        proper operation with 4965.
2740  */
2741 static void iwl4965_dbg_report_frame(struct iwl_priv *priv,
2742                       struct iwl_rx_packet *pkt,
2743                       struct ieee80211_hdr *header, int group100)
2744 {
2745         u32 to_us;
2746         u32 print_summary = 0;
2747         u32 print_dump = 0;     /* set to 1 to dump all frames' contents */
2748         u32 hundred = 0;
2749         u32 dataframe = 0;
2750         u16 fc;
2751         u16 seq_ctl;
2752         u16 channel;
2753         u16 phy_flags;
2754         int rate_sym;
2755         u16 length;
2756         u16 status;
2757         u16 bcn_tmr;
2758         u32 tsf_low;
2759         u64 tsf;
2760         u8 rssi;
2761         u8 agc;
2762         u16 sig_avg;
2763         u16 noise_diff;
2764         struct iwl4965_rx_frame_stats *rx_stats = IWL_RX_STATS(pkt);
2765         struct iwl4965_rx_frame_hdr *rx_hdr = IWL_RX_HDR(pkt);
2766         struct iwl4965_rx_frame_end *rx_end = IWL_RX_END(pkt);
2767         u8 *data = IWL_RX_DATA(pkt);
2768
2769         if (likely(!(priv->debug_level & IWL_DL_RX)))
2770                 return;
2771
2772         /* MAC header */
2773         fc = le16_to_cpu(header->frame_control);
2774         seq_ctl = le16_to_cpu(header->seq_ctrl);
2775
2776         /* metadata */
2777         channel = le16_to_cpu(rx_hdr->channel);
2778         phy_flags = le16_to_cpu(rx_hdr->phy_flags);
2779         rate_sym = rx_hdr->rate;
2780         length = le16_to_cpu(rx_hdr->len);
2781
2782         /* end-of-frame status and timestamp */
2783         status = le32_to_cpu(rx_end->status);
2784         bcn_tmr = le32_to_cpu(rx_end->beacon_timestamp);
2785         tsf_low = le64_to_cpu(rx_end->timestamp) & 0x0ffffffff;
2786         tsf = le64_to_cpu(rx_end->timestamp);
2787
2788         /* signal statistics */
2789         rssi = rx_stats->rssi;
2790         agc = rx_stats->agc;
2791         sig_avg = le16_to_cpu(rx_stats->sig_avg);
2792         noise_diff = le16_to_cpu(rx_stats->noise_diff);
2793
2794         to_us = !compare_ether_addr(header->addr1, priv->mac_addr);
2795
2796         /* if data frame is to us and all is good,
2797          *   (optionally) print summary for only 1 out of every 100 */
2798         if (to_us && (fc & ~IEEE80211_FCTL_PROTECTED) ==
2799             (IEEE80211_FCTL_FROMDS | IEEE80211_FTYPE_DATA)) {
2800                 dataframe = 1;
2801                 if (!group100)
2802                         print_summary = 1;      /* print each frame */
2803                 else if (priv->framecnt_to_us < 100) {
2804                         priv->framecnt_to_us++;
2805                         print_summary = 0;
2806                 } else {
2807                         priv->framecnt_to_us = 0;
2808                         print_summary = 1;
2809                         hundred = 1;
2810                 }
2811         } else {
2812                 /* print summary for all other frames */
2813                 print_summary = 1;
2814         }
2815
2816         if (print_summary) {
2817                 char *title;
2818                 int rate_idx;
2819                 u32 bitrate;
2820
2821                 if (hundred)
2822                         title = "100Frames";
2823                 else if (fc & IEEE80211_FCTL_RETRY)
2824                         title = "Retry";
2825                 else if (ieee80211_is_assoc_response(fc))
2826                         title = "AscRsp";
2827                 else if (ieee80211_is_reassoc_response(fc))
2828                         title = "RasRsp";
2829                 else if (ieee80211_is_probe_response(fc)) {
2830                         title = "PrbRsp";
2831                         print_dump = 1; /* dump frame contents */
2832                 } else if (ieee80211_is_beacon(fc)) {
2833                         title = "Beacon";
2834                         print_dump = 1; /* dump frame contents */
2835                 } else if (ieee80211_is_atim(fc))
2836                         title = "ATIM";
2837                 else if (ieee80211_is_auth(fc))
2838                         title = "Auth";
2839                 else if (ieee80211_is_deauth(fc))
2840                         title = "DeAuth";
2841                 else if (ieee80211_is_disassoc(fc))
2842                         title = "DisAssoc";
2843                 else
2844                         title = "Frame";
2845
2846                 rate_idx = iwl4965_hwrate_to_plcp_idx(rate_sym);
2847                 if (unlikely(rate_idx == -1))
2848                         bitrate = 0;
2849                 else
2850                         bitrate = iwl4965_rates[rate_idx].ieee / 2;
2851
2852                 /* print frame summary.
2853                  * MAC addresses show just the last byte (for brevity),
2854                  *    but you can hack it to show more, if you'd like to. */
2855                 if (dataframe)
2856                         IWL_DEBUG_RX("%s: mhd=0x%04x, dst=0x%02x, "
2857                                      "len=%u, rssi=%d, chnl=%d, rate=%u, \n",
2858                                      title, fc, header->addr1[5],
2859                                      length, rssi, channel, bitrate);
2860                 else {
2861                         /* src/dst addresses assume managed mode */
2862                         IWL_DEBUG_RX("%s: 0x%04x, dst=0x%02x, "
2863                                      "src=0x%02x, rssi=%u, tim=%lu usec, "
2864                                      "phy=0x%02x, chnl=%d\n",
2865                                      title, fc, header->addr1[5],
2866                                      header->addr3[5], rssi,
2867                                      tsf_low - priv->scan_start_tsf,
2868                                      phy_flags, channel);
2869                 }
2870         }
2871         if (print_dump)
2872                 iwl_print_hex_dump(priv, IWL_DL_RX, data, length);
2873 }
2874 #else
2875 static inline void iwl4965_dbg_report_frame(struct iwl_priv *priv,
2876                                             struct iwl_rx_packet *pkt,
2877                                             struct ieee80211_hdr *header,
2878                                             int group100)
2879 {
2880 }
2881 #endif
2882
2883
2884
2885 /* Called for REPLY_RX (legacy ABG frames), or
2886  * REPLY_RX_MPDU_CMD (HT high-throughput N frames). */
2887 static void iwl4965_rx_reply_rx(struct iwl_priv *priv,
2888                                 struct iwl_rx_mem_buffer *rxb)
2889 {
2890         struct ieee80211_hdr *header;
2891         struct ieee80211_rx_status rx_status;
2892         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
2893         /* Use phy data (Rx signal strength, etc.) contained within
2894          *   this rx packet for legacy frames,
2895          *   or phy data cached from REPLY_RX_PHY_CMD for HT frames. */
2896         int include_phy = (pkt->hdr.cmd == REPLY_RX);
2897         struct iwl4965_rx_phy_res *rx_start = (include_phy) ?
2898                 (struct iwl4965_rx_phy_res *)&(pkt->u.raw[0]) :
2899                 (struct iwl4965_rx_phy_res *)&priv->last_phy_res[1];
2900         __le32 *rx_end;
2901         unsigned int len = 0;
2902         u16 fc;
2903         u8 network_packet;
2904
2905         rx_status.mactime = le64_to_cpu(rx_start->timestamp);
2906         rx_status.freq =
2907                 ieee80211_frequency_to_channel(le16_to_cpu(rx_start->channel));
2908         rx_status.band = (rx_start->phy_flags & RX_RES_PHY_FLAGS_BAND_24_MSK) ?
2909                                 IEEE80211_BAND_2GHZ : IEEE80211_BAND_5GHZ;
2910         rx_status.rate_idx =
2911                 iwl4965_hwrate_to_plcp_idx(le32_to_cpu(rx_start->rate_n_flags));
2912         if (rx_status.band == IEEE80211_BAND_5GHZ)
2913                 rx_status.rate_idx -= IWL_FIRST_OFDM_RATE;
2914
2915         rx_status.antenna = 0;
2916         rx_status.flag = 0;
2917
2918         if ((unlikely(rx_start->cfg_phy_cnt > 20))) {
2919                 IWL_DEBUG_DROP("dsp size out of range [0,20]: %d/n",
2920                                 rx_start->cfg_phy_cnt);
2921                 return;
2922         }
2923
2924         if (!include_phy) {
2925                 if (priv->last_phy_res[0])
2926                         rx_start = (struct iwl4965_rx_phy_res *)
2927                                 &priv->last_phy_res[1];
2928                 else
2929                         rx_start = NULL;
2930         }
2931
2932         if (!rx_start) {
2933                 IWL_ERROR("MPDU frame without a PHY data\n");
2934                 return;
2935         }
2936
2937         if (include_phy) {
2938                 header = (struct ieee80211_hdr *)((u8 *) & rx_start[1]
2939                                                   + rx_start->cfg_phy_cnt);
2940
2941                 len = le16_to_cpu(rx_start->byte_count);
2942                 rx_end = (__le32 *)(pkt->u.raw + rx_start->cfg_phy_cnt +
2943                                   sizeof(struct iwl4965_rx_phy_res) + len);
2944         } else {
2945                 struct iwl4965_rx_mpdu_res_start *amsdu =
2946                         (struct iwl4965_rx_mpdu_res_start *)pkt->u.raw;
2947
2948                 header = (void *)(pkt->u.raw +
2949                         sizeof(struct iwl4965_rx_mpdu_res_start));
2950                 len = le16_to_cpu(amsdu->byte_count);
2951                 rx_end = (__le32 *) (pkt->u.raw +
2952                         sizeof(struct iwl4965_rx_mpdu_res_start) + len);
2953         }
2954
2955         if (!(*rx_end & RX_RES_STATUS_NO_CRC32_ERROR) ||
2956             !(*rx_end & RX_RES_STATUS_NO_RXE_OVERFLOW)) {
2957                 IWL_DEBUG_RX("Bad CRC or FIFO: 0x%08X.\n",
2958                                 le32_to_cpu(*rx_end));
2959                 return;
2960         }
2961
2962         priv->ucode_beacon_time = le32_to_cpu(rx_start->beacon_time_stamp);
2963
2964         /* Find max signal strength (dBm) among 3 antenna/receiver chains */
2965         rx_status.ssi = iwl4965_calc_rssi(priv, rx_start);
2966
2967         /* Meaningful noise values are available only from beacon statistics,
2968          *   which are gathered only when associated, and indicate noise
2969          *   only for the associated network channel ...
2970          * Ignore these noise values while scanning (other channels) */
2971         if (iwl_is_associated(priv) &&
2972             !test_bit(STATUS_SCANNING, &priv->status)) {
2973                 rx_status.noise = priv->last_rx_noise;
2974                 rx_status.signal = iwl4965_calc_sig_qual(rx_status.ssi,
2975                                                          rx_status.noise);
2976         } else {
2977                 rx_status.noise = IWL_NOISE_MEAS_NOT_AVAILABLE;
2978                 rx_status.signal = iwl4965_calc_sig_qual(rx_status.ssi, 0);
2979         }
2980
2981         /* Reset beacon noise level if not associated. */
2982         if (!iwl_is_associated(priv))
2983                 priv->last_rx_noise = IWL_NOISE_MEAS_NOT_AVAILABLE;
2984
2985         /* Set "1" to report good data frames in groups of 100 */
2986         /* FIXME: need to optimze the call: */
2987         iwl4965_dbg_report_frame(priv, pkt, header, 1);
2988
2989         IWL_DEBUG_STATS_LIMIT("Rssi %d, noise %d, qual %d, TSF %llu\n",
2990                               rx_status.ssi, rx_status.noise, rx_status.signal,
2991                               (unsigned long long)rx_status.mactime);
2992
2993
2994         if (priv->iw_mode == IEEE80211_IF_TYPE_MNTR) {
2995                 iwl4965_handle_data_packet(priv, 1, include_phy,
2996                                                  rxb, &rx_status);
2997                 return;
2998         }
2999
3000         network_packet = iwl4965_is_network_packet(priv, header);
3001         if (network_packet) {
3002                 priv->last_rx_rssi = rx_status.ssi;
3003                 priv->last_beacon_time =  priv->ucode_beacon_time;
3004                 priv->last_tsf = le64_to_cpu(rx_start->timestamp);
3005         }
3006
3007         fc = le16_to_cpu(header->frame_control);
3008         switch (fc & IEEE80211_FCTL_FTYPE) {
3009         case IEEE80211_FTYPE_MGMT:
3010                 if (priv->iw_mode == IEEE80211_IF_TYPE_AP)
3011                         iwl4965_update_ps_mode(priv, fc  & IEEE80211_FCTL_PM,
3012                                                 header->addr2);
3013                 iwl4965_handle_data_packet(priv, 0, include_phy, rxb, &rx_status);
3014                 break;
3015
3016         case IEEE80211_FTYPE_CTL:
3017 #ifdef CONFIG_IWL4965_HT
3018                 switch (fc & IEEE80211_FCTL_STYPE) {
3019                 case IEEE80211_STYPE_BACK_REQ:
3020                         IWL_DEBUG_HT("IEEE80211_STYPE_BACK_REQ arrived\n");
3021                         iwl4965_handle_data_packet(priv, 0, include_phy,
3022                                                 rxb, &rx_status);
3023                         break;
3024                 default:
3025                         break;
3026                 }
3027 #endif
3028                 break;
3029
3030         case IEEE80211_FTYPE_DATA: {
3031                 DECLARE_MAC_BUF(mac1);
3032                 DECLARE_MAC_BUF(mac2);
3033                 DECLARE_MAC_BUF(mac3);
3034
3035                 if (priv->iw_mode == IEEE80211_IF_TYPE_AP)
3036                         iwl4965_update_ps_mode(priv, fc  & IEEE80211_FCTL_PM,
3037                                                 header->addr2);
3038
3039                 if (unlikely(!network_packet))
3040                         IWL_DEBUG_DROP("Dropping (non network): "
3041                                        "%s, %s, %s\n",
3042                                        print_mac(mac1, header->addr1),
3043                                        print_mac(mac2, header->addr2),
3044                                        print_mac(mac3, header->addr3));
3045                 else if (unlikely(iwl4965_is_duplicate_packet(priv, header)))
3046                         IWL_DEBUG_DROP("Dropping (dup): %s, %s, %s\n",
3047                                        print_mac(mac1, header->addr1),
3048                                        print_mac(mac2, header->addr2),
3049                                        print_mac(mac3, header->addr3));
3050                 else
3051                         iwl4965_handle_data_packet(priv, 1, include_phy, rxb,
3052                                                    &rx_status);
3053                 break;
3054         }
3055         default:
3056                 break;
3057
3058         }
3059 }
3060
3061 /* Cache phy data (Rx signal strength, etc) for HT frame (REPLY_RX_PHY_CMD).
3062  * This will be used later in iwl4965_rx_reply_rx() for REPLY_RX_MPDU_CMD. */
3063 static void iwl4965_rx_reply_rx_phy(struct iwl_priv *priv,
3064                                     struct iwl_rx_mem_buffer *rxb)
3065 {
3066         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
3067         priv->last_phy_res[0] = 1;
3068         memcpy(&priv->last_phy_res[1], &(pkt->u.raw[0]),
3069                sizeof(struct iwl4965_rx_phy_res));
3070 }
3071 static void iwl4965_rx_missed_beacon_notif(struct iwl_priv *priv,
3072                                            struct iwl_rx_mem_buffer *rxb)
3073
3074 {
3075 #ifdef CONFIG_IWL4965_RUN_TIME_CALIB
3076         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
3077         struct iwl4965_missed_beacon_notif *missed_beacon;
3078
3079         missed_beacon = &pkt->u.missed_beacon;
3080         if (le32_to_cpu(missed_beacon->consequtive_missed_beacons) > 5) {
3081                 IWL_DEBUG_CALIB("missed bcn cnsq %d totl %d rcd %d expctd %d\n",
3082                     le32_to_cpu(missed_beacon->consequtive_missed_beacons),
3083                     le32_to_cpu(missed_beacon->total_missed_becons),
3084                     le32_to_cpu(missed_beacon->num_recvd_beacons),
3085                     le32_to_cpu(missed_beacon->num_expected_beacons));
3086                 if (!test_bit(STATUS_SCANNING, &priv->status))
3087                         iwl_init_sensitivity(priv);
3088         }
3089 #endif /*CONFIG_IWL4965_RUN_TIME_CALIB*/
3090 }
3091 #ifdef CONFIG_IWL4965_HT
3092
3093 /**
3094  * iwl4965_sta_modify_enable_tid_tx - Enable Tx for this TID in station table
3095  */
3096 static void iwl4965_sta_modify_enable_tid_tx(struct iwl_priv *priv,
3097                                          int sta_id, int tid)
3098 {
3099         unsigned long flags;
3100
3101         /* Remove "disable" flag, to enable Tx for this TID */
3102         spin_lock_irqsave(&priv->sta_lock, flags);
3103         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_TID_DISABLE_TX;
3104         priv->stations[sta_id].sta.tid_disable_tx &= cpu_to_le16(~(1 << tid));
3105         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
3106         spin_unlock_irqrestore(&priv->sta_lock, flags);
3107
3108         iwl_send_add_sta(priv, &priv->stations[sta_id].sta, CMD_ASYNC);
3109 }
3110
3111 /**
3112  * iwl4965_tx_status_reply_compressed_ba - Update tx status from block-ack
3113  *
3114  * Go through block-ack's bitmap of ACK'd frames, update driver's record of
3115  * ACK vs. not.  This gets sent to mac80211, then to rate scaling algo.
3116  */
3117 static int iwl4965_tx_status_reply_compressed_ba(struct iwl_priv *priv,
3118                                                  struct iwl_ht_agg *agg,
3119                                                  struct iwl4965_compressed_ba_resp*
3120                                                  ba_resp)
3121
3122 {
3123         int i, sh, ack;
3124         u16 seq_ctl = le16_to_cpu(ba_resp->seq_ctl);
3125         u16 scd_flow = le16_to_cpu(ba_resp->scd_flow);
3126         u64 bitmap;
3127         int successes = 0;
3128         struct ieee80211_tx_status *tx_status;
3129
3130         if (unlikely(!agg->wait_for_ba))  {
3131                 IWL_ERROR("Received BA when not expected\n");
3132                 return -EINVAL;
3133         }
3134
3135         /* Mark that the expected block-ack response arrived */
3136         agg->wait_for_ba = 0;
3137         IWL_DEBUG_TX_REPLY("BA %d %d\n", agg->start_idx, ba_resp->seq_ctl);
3138
3139         /* Calculate shift to align block-ack bits with our Tx window bits */
3140         sh = agg->start_idx - SEQ_TO_INDEX(seq_ctl>>4);
3141         if (sh < 0) /* tbw something is wrong with indices */
3142                 sh += 0x100;
3143
3144         /* don't use 64-bit values for now */
3145         bitmap = le64_to_cpu(ba_resp->bitmap) >> sh;
3146
3147         if (agg->frame_count > (64 - sh)) {
3148                 IWL_DEBUG_TX_REPLY("more frames than bitmap size");
3149                 return -1;
3150         }
3151
3152         /* check for success or failure according to the
3153          * transmitted bitmap and block-ack bitmap */
3154         bitmap &= agg->bitmap;
3155
3156         /* For each frame attempted in aggregation,
3157          * update driver's record of tx frame's status. */
3158         for (i = 0; i < agg->frame_count ; i++) {
3159                 ack = bitmap & (1 << i);
3160                 successes += !!ack;
3161                 IWL_DEBUG_TX_REPLY("%s ON i=%d idx=%d raw=%d\n",
3162                         ack? "ACK":"NACK", i, (agg->start_idx + i) & 0xff,
3163                         agg->start_idx + i);
3164         }
3165
3166         tx_status = &priv->txq[scd_flow].txb[agg->start_idx].status;
3167         tx_status->flags = IEEE80211_TX_STATUS_ACK;
3168         tx_status->flags |= IEEE80211_TX_STATUS_AMPDU;
3169         tx_status->ampdu_ack_map = successes;
3170         tx_status->ampdu_ack_len = agg->frame_count;
3171         iwl4965_hwrate_to_tx_control(priv, agg->rate_n_flags,
3172                                      &tx_status->control);
3173
3174         IWL_DEBUG_TX_REPLY("Bitmap %llx\n", (unsigned long long)bitmap);
3175
3176         return 0;
3177 }
3178
3179 /**
3180  * iwl4965_tx_queue_stop_scheduler - Stop queue, but keep configuration
3181  */
3182 static void iwl4965_tx_queue_stop_scheduler(struct iwl_priv *priv,
3183                                             u16 txq_id)
3184 {
3185         /* Simply stop the queue, but don't change any configuration;
3186          * the SCD_ACT_EN bit is the write-enable mask for the ACTIVE bit. */
3187         iwl_write_prph(priv,
3188                 IWL49_SCD_QUEUE_STATUS_BITS(txq_id),
3189                 (0 << IWL49_SCD_QUEUE_STTS_REG_POS_ACTIVE)|
3190                 (1 << IWL49_SCD_QUEUE_STTS_REG_POS_SCD_ACT_EN));
3191 }
3192
3193 /**
3194  * txq_id must be greater than IWL_BACK_QUEUE_FIRST_ID
3195  * priv->lock must be held by the caller
3196  */
3197 static int iwl4965_tx_queue_agg_disable(struct iwl_priv *priv, u16 txq_id,
3198                                         u16 ssn_idx, u8 tx_fifo)
3199 {
3200         int ret = 0;
3201
3202         if (IWL_BACK_QUEUE_FIRST_ID > txq_id) {
3203                 IWL_WARNING("queue number too small: %d, must be > %d\n",
3204                                 txq_id, IWL_BACK_QUEUE_FIRST_ID);
3205                 return -EINVAL;
3206         }
3207
3208         ret = iwl_grab_nic_access(priv);
3209         if (ret)
3210                 return ret;
3211
3212         iwl4965_tx_queue_stop_scheduler(priv, txq_id);
3213
3214         iwl_clear_bits_prph(priv, IWL49_SCD_QUEUECHAIN_SEL, (1 << txq_id));
3215
3216         priv->txq[txq_id].q.read_ptr = (ssn_idx & 0xff);
3217         priv->txq[txq_id].q.write_ptr = (ssn_idx & 0xff);
3218         /* supposes that ssn_idx is valid (!= 0xFFF) */
3219         iwl4965_set_wr_ptrs(priv, txq_id, ssn_idx);
3220
3221         iwl_clear_bits_prph(priv, IWL49_SCD_INTERRUPT_MASK, (1 << txq_id));
3222         iwl4965_txq_ctx_deactivate(priv, txq_id);
3223         iwl4965_tx_queue_set_status(priv, &priv->txq[txq_id], tx_fifo, 0);
3224
3225         iwl_release_nic_access(priv);
3226
3227         return 0;
3228 }
3229
3230 int iwl4965_check_empty_hw_queue(struct iwl_priv *priv, int sta_id,
3231                                          u8 tid, int txq_id)
3232 {
3233         struct iwl4965_queue *q = &priv->txq[txq_id].q;
3234         u8 *addr = priv->stations[sta_id].sta.sta.addr;
3235         struct iwl_tid_data *tid_data = &priv->stations[sta_id].tid[tid];
3236
3237         switch (priv->stations[sta_id].tid[tid].agg.state) {
3238         case IWL_EMPTYING_HW_QUEUE_DELBA:
3239                 /* We are reclaiming the last packet of the */
3240                 /* aggregated HW queue */
3241                 if (txq_id  == tid_data->agg.txq_id &&
3242                     q->read_ptr == q->write_ptr) {
3243                         u16 ssn = SEQ_TO_SN(tid_data->seq_number);
3244                         int tx_fifo = default_tid_to_tx_fifo[tid];
3245                         IWL_DEBUG_HT("HW queue empty: continue DELBA flow\n");
3246                         iwl4965_tx_queue_agg_disable(priv, txq_id,
3247                                                      ssn, tx_fifo);
3248                         tid_data->agg.state = IWL_AGG_OFF;
3249                         ieee80211_stop_tx_ba_cb_irqsafe(priv->hw, addr, tid);
3250                 }
3251                 break;
3252         case IWL_EMPTYING_HW_QUEUE_ADDBA:
3253                 /* We are reclaiming the last packet of the queue */
3254                 if (tid_data->tfds_in_queue == 0) {
3255                         IWL_DEBUG_HT("HW queue empty: continue ADDBA flow\n");
3256                         tid_data->agg.state = IWL_AGG_ON;
3257                         ieee80211_start_tx_ba_cb_irqsafe(priv->hw, addr, tid);
3258                 }
3259                 break;
3260         }
3261         return 0;
3262 }
3263
3264 /**
3265  * iwl4965_queue_dec_wrap - Decrement queue index, wrap back to end if needed
3266  * @index -- current index
3267  * @n_bd -- total number of entries in queue (s/b power of 2)
3268  */
3269 static inline int iwl4965_queue_dec_wrap(int index, int n_bd)
3270 {
3271         return (index == 0) ? n_bd - 1 : index - 1;
3272 }
3273
3274 /**
3275  * iwl4965_rx_reply_compressed_ba - Handler for REPLY_COMPRESSED_BA
3276  *
3277  * Handles block-acknowledge notification from device, which reports success
3278  * of frames sent via aggregation.
3279  */
3280 static void iwl4965_rx_reply_compressed_ba(struct iwl_priv *priv,
3281                                            struct iwl_rx_mem_buffer *rxb)
3282 {
3283         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
3284         struct iwl4965_compressed_ba_resp *ba_resp = &pkt->u.compressed_ba;
3285         int index;
3286         struct iwl_tx_queue *txq = NULL;
3287         struct iwl_ht_agg *agg;
3288         DECLARE_MAC_BUF(mac);
3289
3290         /* "flow" corresponds to Tx queue */
3291         u16 scd_flow = le16_to_cpu(ba_resp->scd_flow);
3292
3293         /* "ssn" is start of block-ack Tx window, corresponds to index
3294          * (in Tx queue's circular buffer) of first TFD/frame in window */
3295         u16 ba_resp_scd_ssn = le16_to_cpu(ba_resp->scd_ssn);
3296
3297         if (scd_flow >= priv->hw_params.max_txq_num) {
3298                 IWL_ERROR("BUG_ON scd_flow is bigger than number of queues");
3299                 return;
3300         }
3301
3302         txq = &priv->txq[scd_flow];
3303         agg = &priv->stations[ba_resp->sta_id].tid[ba_resp->tid].agg;
3304
3305         /* Find index just before block-ack window */
3306         index = iwl4965_queue_dec_wrap(ba_resp_scd_ssn & 0xff, txq->q.n_bd);
3307
3308         /* TODO: Need to get this copy more safely - now good for debug */
3309
3310         IWL_DEBUG_TX_REPLY("REPLY_COMPRESSED_BA [%d]Received from %s, "
3311                            "sta_id = %d\n",
3312                            agg->wait_for_ba,
3313                            print_mac(mac, (u8*) &ba_resp->sta_addr_lo32),
3314                            ba_resp->sta_id);
3315         IWL_DEBUG_TX_REPLY("TID = %d, SeqCtl = %d, bitmap = 0x%llx, scd_flow = "
3316                            "%d, scd_ssn = %d\n",
3317                            ba_resp->tid,
3318                            ba_resp->seq_ctl,
3319                            (unsigned long long)le64_to_cpu(ba_resp->bitmap),
3320                            ba_resp->scd_flow,
3321                            ba_resp->scd_ssn);
3322         IWL_DEBUG_TX_REPLY("DAT start_idx = %d, bitmap = 0x%llx \n",
3323                            agg->start_idx,
3324                            (unsigned long long)agg->bitmap);
3325
3326         /* Update driver's record of ACK vs. not for each frame in window */
3327         iwl4965_tx_status_reply_compressed_ba(priv, agg, ba_resp);
3328
3329         /* Release all TFDs before the SSN, i.e. all TFDs in front of
3330          * block-ack window (we assume that they've been successfully
3331          * transmitted ... if not, it's too late anyway). */
3332         if (txq->q.read_ptr != (ba_resp_scd_ssn & 0xff)) {
3333                 /* calculate mac80211 ampdu sw queue to wake */
3334                 int ampdu_q =
3335                    scd_flow - IWL_BACK_QUEUE_FIRST_ID + priv->hw->queues;
3336                 int freed = iwl4965_tx_queue_reclaim(priv, scd_flow, index);
3337                 priv->stations[ba_resp->sta_id].
3338                         tid[ba_resp->tid].tfds_in_queue -= freed;
3339                 if (iwl4965_queue_space(&txq->q) > txq->q.low_mark &&
3340                         priv->mac80211_registered &&
3341                         agg->state != IWL_EMPTYING_HW_QUEUE_DELBA)
3342                         ieee80211_wake_queue(priv->hw, ampdu_q);
3343                 iwl4965_check_empty_hw_queue(priv, ba_resp->sta_id,
3344                         ba_resp->tid, scd_flow);
3345         }
3346 }
3347
3348 /**
3349  * iwl4965_tx_queue_set_q2ratid - Map unique receiver/tid combination to a queue
3350  */
3351 static int iwl4965_tx_queue_set_q2ratid(struct iwl_priv *priv, u16 ra_tid,
3352                                         u16 txq_id)
3353 {
3354         u32 tbl_dw_addr;
3355         u32 tbl_dw;
3356         u16 scd_q2ratid;
3357
3358         scd_q2ratid = ra_tid & IWL49_SCD_QUEUE_RA_TID_MAP_RATID_MSK;
3359
3360         tbl_dw_addr = priv->scd_base_addr +
3361                         IWL49_SCD_TRANSLATE_TBL_OFFSET_QUEUE(txq_id);
3362
3363         tbl_dw = iwl_read_targ_mem(priv, tbl_dw_addr);
3364
3365         if (txq_id & 0x1)
3366                 tbl_dw = (scd_q2ratid << 16) | (tbl_dw & 0x0000FFFF);
3367         else
3368                 tbl_dw = scd_q2ratid | (tbl_dw & 0xFFFF0000);
3369
3370         iwl_write_targ_mem(priv, tbl_dw_addr, tbl_dw);
3371
3372         return 0;
3373 }
3374
3375
3376 /**
3377  * iwl4965_tx_queue_agg_enable - Set up & enable aggregation for selected queue
3378  *
3379  * NOTE:  txq_id must be greater than IWL_BACK_QUEUE_FIRST_ID,
3380  *        i.e. it must be one of the higher queues used for aggregation
3381  */
3382 static int iwl4965_tx_queue_agg_enable(struct iwl_priv *priv, int txq_id,
3383                                        int tx_fifo, int sta_id, int tid,
3384                                        u16 ssn_idx)
3385 {
3386         unsigned long flags;
3387         int rc;
3388         u16 ra_tid;
3389
3390         if (IWL_BACK_QUEUE_FIRST_ID > txq_id)
3391                 IWL_WARNING("queue number too small: %d, must be > %d\n",
3392                         txq_id, IWL_BACK_QUEUE_FIRST_ID);
3393
3394         ra_tid = BUILD_RAxTID(sta_id, tid);
3395
3396         /* Modify device's station table to Tx this TID */
3397         iwl4965_sta_modify_enable_tid_tx(priv, sta_id, tid);
3398
3399         spin_lock_irqsave(&priv->lock, flags);
3400         rc = iwl_grab_nic_access(priv);
3401         if (rc) {
3402                 spin_unlock_irqrestore(&priv->lock, flags);
3403                 return rc;
3404         }
3405
3406         /* Stop this Tx queue before configuring it */
3407         iwl4965_tx_queue_stop_scheduler(priv, txq_id);
3408
3409         /* Map receiver-address / traffic-ID to this queue */
3410         iwl4965_tx_queue_set_q2ratid(priv, ra_tid, txq_id);
3411
3412         /* Set this queue as a chain-building queue */
3413         iwl_set_bits_prph(priv, IWL49_SCD_QUEUECHAIN_SEL, (1 << txq_id));
3414
3415         /* Place first TFD at index corresponding to start sequence number.
3416          * Assumes that ssn_idx is valid (!= 0xFFF) */
3417         priv->txq[txq_id].q.read_ptr = (ssn_idx & 0xff);
3418         priv->txq[txq_id].q.write_ptr = (ssn_idx & 0xff);
3419         iwl4965_set_wr_ptrs(priv, txq_id, ssn_idx);
3420
3421         /* Set up Tx window size and frame limit for this queue */
3422         iwl_write_targ_mem(priv,
3423                 priv->scd_base_addr + IWL49_SCD_CONTEXT_QUEUE_OFFSET(txq_id),
3424                 (SCD_WIN_SIZE << IWL49_SCD_QUEUE_CTX_REG1_WIN_SIZE_POS) &
3425                 IWL49_SCD_QUEUE_CTX_REG1_WIN_SIZE_MSK);
3426
3427         iwl_write_targ_mem(priv, priv->scd_base_addr +
3428                 IWL49_SCD_CONTEXT_QUEUE_OFFSET(txq_id) + sizeof(u32),
3429                 (SCD_FRAME_LIMIT << IWL49_SCD_QUEUE_CTX_REG2_FRAME_LIMIT_POS)
3430                 & IWL49_SCD_QUEUE_CTX_REG2_FRAME_LIMIT_MSK);
3431
3432         iwl_set_bits_prph(priv, IWL49_SCD_INTERRUPT_MASK, (1 << txq_id));
3433
3434         /* Set up Status area in SRAM, map to Tx DMA/FIFO, activate the queue */
3435         iwl4965_tx_queue_set_status(priv, &priv->txq[txq_id], tx_fifo, 1);
3436
3437         iwl_release_nic_access(priv);
3438         spin_unlock_irqrestore(&priv->lock, flags);
3439
3440         return 0;
3441 }
3442
3443 #endif /* CONFIG_IWL4965_HT */
3444
3445 /**
3446  * iwl4965_add_station - Initialize a station's hardware rate table
3447  *
3448  * The uCode's station table contains a table of fallback rates
3449  * for automatic fallback during transmission.
3450  *
3451  * NOTE: This sets up a default set of values.  These will be replaced later
3452  *       if the driver's iwl-4965-rs rate scaling algorithm is used, instead of
3453  *       rc80211_simple.
3454  *
3455  * NOTE: Run REPLY_ADD_STA command to set up station table entry, before
3456  *       calling this function (which runs REPLY_TX_LINK_QUALITY_CMD,
3457  *       which requires station table entry to exist).
3458  */
3459 void iwl4965_add_station(struct iwl_priv *priv, const u8 *addr, int is_ap)
3460 {
3461         int i, r;
3462         struct iwl_link_quality_cmd link_cmd = {
3463                 .reserved1 = 0,
3464         };
3465         u16 rate_flags;
3466
3467         /* Set up the rate scaling to start at selected rate, fall back
3468          * all the way down to 1M in IEEE order, and then spin on 1M */
3469         if (is_ap)
3470                 r = IWL_RATE_54M_INDEX;
3471         else if (priv->band == IEEE80211_BAND_5GHZ)
3472                 r = IWL_RATE_6M_INDEX;
3473         else
3474                 r = IWL_RATE_1M_INDEX;
3475
3476         for (i = 0; i < LINK_QUAL_MAX_RETRY_NUM; i++) {
3477                 rate_flags = 0;
3478                 if (r >= IWL_FIRST_CCK_RATE && r <= IWL_LAST_CCK_RATE)
3479                         rate_flags |= RATE_MCS_CCK_MSK;
3480
3481                 /* Use Tx antenna B only */
3482                 rate_flags |= RATE_MCS_ANT_B_MSK; /*FIXME:RS*/
3483
3484                 link_cmd.rs_table[i].rate_n_flags =
3485                         iwl4965_hw_set_rate_n_flags(iwl4965_rates[r].plcp, rate_flags);
3486                 r = iwl4965_get_prev_ieee_rate(r);
3487         }
3488
3489         link_cmd.general_params.single_stream_ant_msk = 2;
3490         link_cmd.general_params.dual_stream_ant_msk = 3;
3491         link_cmd.agg_params.agg_dis_start_th = 3;
3492         link_cmd.agg_params.agg_time_limit = cpu_to_le16(4000);
3493
3494         /* Update the rate scaling for control frame Tx to AP */
3495         link_cmd.sta_id = is_ap ? IWL_AP_ID : priv->hw_params.bcast_sta_id;
3496
3497         iwl_send_cmd_pdu_async(priv, REPLY_TX_LINK_QUALITY_CMD,
3498                                sizeof(link_cmd), &link_cmd, NULL);
3499 }
3500
3501 #ifdef CONFIG_IWL4965_HT
3502
3503 void iwl4965_set_ht_add_station(struct iwl_priv *priv, u8 index,
3504                                 struct ieee80211_ht_info *sta_ht_inf)
3505 {
3506         __le32 sta_flags;
3507         u8 mimo_ps_mode;
3508
3509         if (!sta_ht_inf || !sta_ht_inf->ht_supported)
3510                 goto done;
3511
3512         mimo_ps_mode = (sta_ht_inf->cap & IEEE80211_HT_CAP_MIMO_PS) >> 2;
3513
3514         sta_flags = priv->stations[index].sta.station_flags;
3515
3516         sta_flags &= ~(STA_FLG_RTS_MIMO_PROT_MSK | STA_FLG_MIMO_DIS_MSK);
3517
3518         switch (mimo_ps_mode) {
3519         case WLAN_HT_CAP_MIMO_PS_STATIC:
3520                 sta_flags |= STA_FLG_MIMO_DIS_MSK;
3521                 break;
3522         case WLAN_HT_CAP_MIMO_PS_DYNAMIC:
3523                 sta_flags |= STA_FLG_RTS_MIMO_PROT_MSK;
3524                 break;
3525         case WLAN_HT_CAP_MIMO_PS_DISABLED:
3526                 break;
3527         default:
3528                 IWL_WARNING("Invalid MIMO PS mode %d", mimo_ps_mode);
3529                 break;
3530         }
3531
3532         sta_flags |= cpu_to_le32(
3533               (u32)sta_ht_inf->ampdu_factor << STA_FLG_MAX_AGG_SIZE_POS);
3534
3535         sta_flags |= cpu_to_le32(
3536               (u32)sta_ht_inf->ampdu_density << STA_FLG_AGG_MPDU_DENSITY_POS);
3537
3538         if (iwl_is_fat_tx_allowed(priv, sta_ht_inf))
3539                 sta_flags |= STA_FLG_FAT_EN_MSK;
3540         else
3541                 sta_flags &= ~STA_FLG_FAT_EN_MSK;
3542
3543         priv->stations[index].sta.station_flags = sta_flags;
3544  done:
3545         return;
3546 }
3547
3548 static int iwl4965_rx_agg_start(struct iwl_priv *priv,
3549                                 const u8 *addr, int tid, u16 ssn)
3550 {
3551         unsigned long flags;
3552         int sta_id;
3553
3554         sta_id = iwl_find_station(priv, addr);
3555         if (sta_id == IWL_INVALID_STATION)
3556                 return -ENXIO;
3557
3558         spin_lock_irqsave(&priv->sta_lock, flags);
3559         priv->stations[sta_id].sta.station_flags_msk = 0;
3560         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_ADDBA_TID_MSK;
3561         priv->stations[sta_id].sta.add_immediate_ba_tid = (u8)tid;
3562         priv->stations[sta_id].sta.add_immediate_ba_ssn = cpu_to_le16(ssn);
3563         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
3564         spin_unlock_irqrestore(&priv->sta_lock, flags);
3565
3566         return iwl_send_add_sta(priv, &priv->stations[sta_id].sta,
3567                                         CMD_ASYNC);
3568 }
3569
3570 static int iwl4965_rx_agg_stop(struct iwl_priv *priv,
3571                                const u8 *addr, int tid)
3572 {
3573         unsigned long flags;
3574         int sta_id;
3575
3576         sta_id = iwl_find_station(priv, addr);
3577         if (sta_id == IWL_INVALID_STATION)
3578                 return -ENXIO;
3579
3580         spin_lock_irqsave(&priv->sta_lock, flags);
3581         priv->stations[sta_id].sta.station_flags_msk = 0;
3582         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_DELBA_TID_MSK;
3583         priv->stations[sta_id].sta.remove_immediate_ba_tid = (u8)tid;
3584         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
3585         spin_unlock_irqrestore(&priv->sta_lock, flags);
3586
3587         return iwl_send_add_sta(priv, &priv->stations[sta_id].sta,
3588                                         CMD_ASYNC);
3589 }
3590
3591 /*
3592  * Find first available (lowest unused) Tx Queue, mark it "active".
3593  * Called only when finding queue for aggregation.
3594  * Should never return anything < 7, because they should already
3595  * be in use as EDCA AC (0-3), Command (4), HCCA (5, 6).
3596  */
3597 static int iwl4965_txq_ctx_activate_free(struct iwl_priv *priv)
3598 {
3599         int txq_id;
3600
3601         for (txq_id = 0; txq_id < priv->hw_params.max_txq_num; txq_id++)
3602                 if (!test_and_set_bit(txq_id, &priv->txq_ctx_active_msk))
3603                         return txq_id;
3604         return -1;
3605 }
3606
3607 static int iwl4965_tx_agg_start(struct ieee80211_hw *hw, const u8 *ra,
3608                                 u16 tid, u16 *start_seq_num)
3609 {
3610         struct iwl_priv *priv = hw->priv;
3611         int sta_id;
3612         int tx_fifo;
3613         int txq_id;
3614         int ssn = -1;
3615         int ret = 0;
3616         unsigned long flags;
3617         struct iwl_tid_data *tid_data;
3618         DECLARE_MAC_BUF(mac);
3619
3620         if (likely(tid < ARRAY_SIZE(default_tid_to_tx_fifo)))
3621                 tx_fifo = default_tid_to_tx_fifo[tid];
3622         else
3623                 return -EINVAL;
3624
3625         IWL_WARNING("%s on ra = %s tid = %d\n",
3626                         __func__, print_mac(mac, ra), tid);
3627
3628         sta_id = iwl_find_station(priv, ra);
3629         if (sta_id == IWL_INVALID_STATION)
3630                 return -ENXIO;
3631
3632         if (priv->stations[sta_id].tid[tid].agg.state != IWL_AGG_OFF) {
3633                 IWL_ERROR("Start AGG when state is not IWL_AGG_OFF !\n");
3634                 return -ENXIO;
3635         }
3636
3637         txq_id = iwl4965_txq_ctx_activate_free(priv);
3638         if (txq_id == -1)
3639                 return -ENXIO;
3640
3641         spin_lock_irqsave(&priv->sta_lock, flags);
3642         tid_data = &priv->stations[sta_id].tid[tid];
3643         ssn = SEQ_TO_SN(tid_data->seq_number);
3644         tid_data->agg.txq_id = txq_id;
3645         spin_unlock_irqrestore(&priv->sta_lock, flags);
3646
3647         *start_seq_num = ssn;
3648         ret = iwl4965_tx_queue_agg_enable(priv, txq_id, tx_fifo,
3649                                           sta_id, tid, ssn);
3650         if (ret)
3651                 return ret;
3652
3653         ret = 0;
3654         if (tid_data->tfds_in_queue == 0) {
3655                 printk(KERN_ERR "HW queue is empty\n");
3656                 tid_data->agg.state = IWL_AGG_ON;
3657                 ieee80211_start_tx_ba_cb_irqsafe(hw, ra, tid);
3658         } else {
3659                 IWL_DEBUG_HT("HW queue is NOT empty: %d packets in HW queue\n",
3660                                 tid_data->tfds_in_queue);
3661                 tid_data->agg.state = IWL_EMPTYING_HW_QUEUE_ADDBA;
3662         }
3663         return ret;
3664 }
3665
3666 static int iwl4965_tx_agg_stop(struct ieee80211_hw *hw, const u8 *ra, u16 tid)
3667 {
3668         struct iwl_priv *priv = hw->priv;
3669         int tx_fifo_id, txq_id, sta_id, ssn = -1;
3670         struct iwl_tid_data *tid_data;
3671         int ret, write_ptr, read_ptr;
3672         unsigned long flags;
3673         DECLARE_MAC_BUF(mac);
3674
3675         if (!ra) {
3676                 IWL_ERROR("ra = NULL\n");
3677                 return -EINVAL;
3678         }
3679
3680         if (likely(tid < ARRAY_SIZE(default_tid_to_tx_fifo)))
3681                 tx_fifo_id = default_tid_to_tx_fifo[tid];
3682         else
3683                 return -EINVAL;
3684
3685         sta_id = iwl_find_station(priv, ra);
3686
3687         if (sta_id == IWL_INVALID_STATION)
3688                 return -ENXIO;
3689
3690         if (priv->stations[sta_id].tid[tid].agg.state != IWL_AGG_ON)
3691                 IWL_WARNING("Stopping AGG while state not IWL_AGG_ON\n");
3692
3693         tid_data = &priv->stations[sta_id].tid[tid];
3694         ssn = (tid_data->seq_number & IEEE80211_SCTL_SEQ) >> 4;
3695         txq_id = tid_data->agg.txq_id;
3696         write_ptr = priv->txq[txq_id].q.write_ptr;
3697         read_ptr = priv->txq[txq_id].q.read_ptr;
3698
3699         /* The queue is not empty */
3700         if (write_ptr != read_ptr) {
3701                 IWL_DEBUG_HT("Stopping a non empty AGG HW QUEUE\n");
3702                 priv->stations[sta_id].tid[tid].agg.state =
3703                                 IWL_EMPTYING_HW_QUEUE_DELBA;
3704                 return 0;
3705         }
3706
3707         IWL_DEBUG_HT("HW queue is empty\n");
3708         priv->stations[sta_id].tid[tid].agg.state = IWL_AGG_OFF;
3709
3710         spin_lock_irqsave(&priv->lock, flags);
3711         ret = iwl4965_tx_queue_agg_disable(priv, txq_id, ssn, tx_fifo_id);
3712         spin_unlock_irqrestore(&priv->lock, flags);
3713
3714         if (ret)
3715                 return ret;
3716
3717         ieee80211_stop_tx_ba_cb_irqsafe(priv->hw, ra, tid);
3718
3719         return 0;
3720 }
3721
3722 int iwl4965_mac_ampdu_action(struct ieee80211_hw *hw,
3723                              enum ieee80211_ampdu_mlme_action action,
3724                              const u8 *addr, u16 tid, u16 *ssn)
3725 {
3726         struct iwl_priv *priv = hw->priv;
3727         DECLARE_MAC_BUF(mac);
3728
3729         IWL_DEBUG_HT("A-MPDU action on addr %s tid %d\n",
3730                      print_mac(mac, addr), tid);
3731
3732         switch (action) {
3733         case IEEE80211_AMPDU_RX_START:
3734                 IWL_DEBUG_HT("start Rx\n");
3735                 return iwl4965_rx_agg_start(priv, addr, tid, *ssn);
3736         case IEEE80211_AMPDU_RX_STOP:
3737                 IWL_DEBUG_HT("stop Rx\n");
3738                 return iwl4965_rx_agg_stop(priv, addr, tid);
3739         case IEEE80211_AMPDU_TX_START:
3740                 IWL_DEBUG_HT("start Tx\n");
3741                 return iwl4965_tx_agg_start(hw, addr, tid, ssn);
3742         case IEEE80211_AMPDU_TX_STOP:
3743                 IWL_DEBUG_HT("stop Tx\n");
3744                 return iwl4965_tx_agg_stop(hw, addr, tid);
3745         default:
3746                 IWL_DEBUG_HT("unknown\n");
3747                 return -EINVAL;
3748                 break;
3749         }
3750         return 0;
3751 }
3752 #endif /* CONFIG_IWL4965_HT */
3753
3754
3755 static u16 iwl4965_build_addsta_hcmd(const struct iwl_addsta_cmd *cmd, u8 *data)
3756 {
3757         struct iwl4965_addsta_cmd *addsta = (struct iwl4965_addsta_cmd *)data;
3758         addsta->mode = cmd->mode;
3759         memcpy(&addsta->sta, &cmd->sta, sizeof(struct sta_id_modify));
3760         memcpy(&addsta->key, &cmd->key, sizeof(struct iwl4965_keyinfo));
3761         addsta->station_flags = cmd->station_flags;
3762         addsta->station_flags_msk = cmd->station_flags_msk;
3763         addsta->tid_disable_tx = cmd->tid_disable_tx;
3764         addsta->add_immediate_ba_tid = cmd->add_immediate_ba_tid;
3765         addsta->remove_immediate_ba_tid = cmd->remove_immediate_ba_tid;
3766         addsta->add_immediate_ba_ssn = cmd->add_immediate_ba_ssn;
3767         addsta->reserved1 = __constant_cpu_to_le16(0);
3768         addsta->reserved2 = __constant_cpu_to_le32(0);
3769
3770         return (u16)sizeof(struct iwl4965_addsta_cmd);
3771 }
3772 /* Set up 4965-specific Rx frame reply handlers */
3773 static void iwl4965_rx_handler_setup(struct iwl_priv *priv)
3774 {
3775         /* Legacy Rx frames */
3776         priv->rx_handlers[REPLY_RX] = iwl4965_rx_reply_rx;
3777
3778         /* High-throughput (HT) Rx frames */
3779         priv->rx_handlers[REPLY_RX_PHY_CMD] = iwl4965_rx_reply_rx_phy;
3780         priv->rx_handlers[REPLY_RX_MPDU_CMD] = iwl4965_rx_reply_rx;
3781
3782         priv->rx_handlers[MISSED_BEACONS_NOTIFICATION] =
3783             iwl4965_rx_missed_beacon_notif;
3784
3785 #ifdef CONFIG_IWL4965_HT
3786         priv->rx_handlers[REPLY_COMPRESSED_BA] = iwl4965_rx_reply_compressed_ba;
3787 #endif /* CONFIG_IWL4965_HT */
3788 }
3789
3790 void iwl4965_hw_setup_deferred_work(struct iwl_priv *priv)
3791 {
3792         INIT_WORK(&priv->txpower_work, iwl4965_bg_txpower_work);
3793 #ifdef CONFIG_IWL4965_RUN_TIME_CALIB
3794         INIT_WORK(&priv->sensitivity_work, iwl4965_bg_sensitivity_work);
3795 #endif
3796         init_timer(&priv->statistics_periodic);
3797         priv->statistics_periodic.data = (unsigned long)priv;
3798         priv->statistics_periodic.function = iwl4965_bg_statistics_periodic;
3799 }
3800
3801 void iwl4965_hw_cancel_deferred_work(struct iwl_priv *priv)
3802 {
3803         del_timer_sync(&priv->statistics_periodic);
3804
3805         cancel_delayed_work(&priv->init_alive_start);
3806 }
3807
3808
3809 static struct iwl_hcmd_ops iwl4965_hcmd = {
3810         .rxon_assoc = iwl4965_send_rxon_assoc,
3811 };
3812
3813 static struct iwl_hcmd_utils_ops iwl4965_hcmd_utils = {
3814         .enqueue_hcmd = iwl4965_enqueue_hcmd,
3815         .build_addsta_hcmd = iwl4965_build_addsta_hcmd,
3816 #ifdef CONFIG_IWL4965_RUN_TIME_CALIB
3817         .chain_noise_reset = iwl4965_chain_noise_reset,
3818         .gain_computation = iwl4965_gain_computation,
3819 #endif
3820 };
3821
3822 static struct iwl_lib_ops iwl4965_lib = {
3823         .set_hw_params = iwl4965_hw_set_hw_params,
3824         .alloc_shared_mem = iwl4965_alloc_shared_mem,
3825         .free_shared_mem = iwl4965_free_shared_mem,
3826         .shared_mem_rx_idx = iwl4965_shared_mem_rx_idx,
3827         .txq_update_byte_cnt_tbl = iwl4965_txq_update_byte_cnt_tbl,
3828         .disable_tx_fifo = iwl4965_disable_tx_fifo,
3829         .rx_handler_setup = iwl4965_rx_handler_setup,
3830         .is_valid_rtc_data_addr = iwl4965_hw_valid_rtc_data_addr,
3831         .alive_notify = iwl4965_alive_notify,
3832         .init_alive_start = iwl4965_init_alive_start,
3833         .load_ucode = iwl4965_load_bsm,
3834         .apm_ops = {
3835                 .init = iwl4965_apm_init,
3836                 .config = iwl4965_nic_config,
3837                 .set_pwr_src = iwl4965_set_pwr_src,
3838         },
3839         .eeprom_ops = {
3840                 .regulatory_bands = {
3841                         EEPROM_REGULATORY_BAND_1_CHANNELS,
3842                         EEPROM_REGULATORY_BAND_2_CHANNELS,
3843                         EEPROM_REGULATORY_BAND_3_CHANNELS,
3844                         EEPROM_REGULATORY_BAND_4_CHANNELS,
3845                         EEPROM_REGULATORY_BAND_5_CHANNELS,
3846                         EEPROM_4965_REGULATORY_BAND_24_FAT_CHANNELS,
3847                         EEPROM_4965_REGULATORY_BAND_52_FAT_CHANNELS
3848                 },
3849                 .verify_signature  = iwlcore_eeprom_verify_signature,
3850                 .acquire_semaphore = iwlcore_eeprom_acquire_semaphore,
3851                 .release_semaphore = iwlcore_eeprom_release_semaphore,
3852                 .check_version = iwl4965_eeprom_check_version,
3853                 .query_addr = iwlcore_eeprom_query_addr,
3854         },
3855         .radio_kill_sw = iwl4965_radio_kill_sw,
3856         .set_power = iwl4965_set_power,
3857         .update_chain_flags = iwl4965_update_chain_flags,
3858 };
3859
3860 static struct iwl_ops iwl4965_ops = {
3861         .lib = &iwl4965_lib,
3862         .hcmd = &iwl4965_hcmd,
3863         .utils = &iwl4965_hcmd_utils,
3864 };
3865
3866 struct iwl_cfg iwl4965_agn_cfg = {
3867         .name = "4965AGN",
3868         .fw_name = "iwlwifi-4965" IWL4965_UCODE_API ".ucode",
3869         .sku = IWL_SKU_A|IWL_SKU_G|IWL_SKU_N,
3870         .eeprom_size = IWL4965_EEPROM_IMG_SIZE,
3871         .ops = &iwl4965_ops,
3872         .mod_params = &iwl4965_mod_params,
3873 };
3874
3875 module_param_named(antenna, iwl4965_mod_params.antenna, int, 0444);
3876 MODULE_PARM_DESC(antenna, "select antenna (1=Main, 2=Aux, default 0 [both])");
3877 module_param_named(disable, iwl4965_mod_params.disable, int, 0444);
3878 MODULE_PARM_DESC(disable, "manually disable the radio (default 0 [radio on])");
3879 module_param_named(swcrypto, iwl4965_mod_params.sw_crypto, int, 0444);
3880 MODULE_PARM_DESC(swcrypto, "using crypto in software (default 0 [hardware])\n");
3881 module_param_named(debug, iwl4965_mod_params.debug, int, 0444);
3882 MODULE_PARM_DESC(debug, "debug output mask");
3883 module_param_named(
3884         disable_hw_scan, iwl4965_mod_params.disable_hw_scan, int, 0444);
3885 MODULE_PARM_DESC(disable_hw_scan, "disable hardware scanning (default 0)");
3886
3887 module_param_named(queues_num, iwl4965_mod_params.num_of_queues, int, 0444);
3888 MODULE_PARM_DESC(queues_num, "number of hw queues.");
3889
3890 /* QoS */
3891 module_param_named(qos_enable, iwl4965_mod_params.enable_qos, int, 0444);
3892 MODULE_PARM_DESC(qos_enable, "enable all QoS functionality");
3893 module_param_named(amsdu_size_8K, iwl4965_mod_params.amsdu_size_8K, int, 0444);
3894 MODULE_PARM_DESC(amsdu_size_8K, "enable 8K amsdu size");
3895