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