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