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