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