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