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