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