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