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