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