iwlwifi: Packing all 4965 parameters
[pandora-kernel.git] / drivers / net / wireless / iwlwifi / iwl-4965.c
1 /******************************************************************************
2  *
3  * Copyright(c) 2003 - 2008 Intel Corporation. All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of version 2 of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  *
14  * You should have received a copy of the GNU General Public License along with
15  * this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
17  *
18  * The full GNU General Public License is included in this distribution in the
19  * file called LICENSE.
20  *
21  * Contact Information:
22  * James P. Ketrenos <ipw2100-admin@linux.intel.com>
23  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
24  *
25  *****************************************************************************/
26
27 #include <linux/kernel.h>
28 #include <linux/module.h>
29 #include <linux/version.h>
30 #include <linux/init.h>
31 #include <linux/pci.h>
32 #include <linux/dma-mapping.h>
33 #include <linux/delay.h>
34 #include <linux/skbuff.h>
35 #include <linux/netdevice.h>
36 #include <linux/wireless.h>
37 #include <net/mac80211.h>
38 #include <linux/etherdevice.h>
39 #include <asm/unaligned.h>
40
41 #include "iwl-eeprom.h"
42 #include "iwl-core.h"
43 #include "iwl-4965.h"
44 #include "iwl-helpers.h"
45
46 static void iwl4965_hw_card_show_info(struct iwl_priv *priv);
47
48 #define IWL_DECLARE_RATE_INFO(r, s, ip, in, rp, rn, pp, np)    \
49         [IWL_RATE_##r##M_INDEX] = { IWL_RATE_##r##M_PLCP,      \
50                                     IWL_RATE_SISO_##s##M_PLCP, \
51                                     IWL_RATE_MIMO_##s##M_PLCP, \
52                                     IWL_RATE_##r##M_IEEE,      \
53                                     IWL_RATE_##ip##M_INDEX,    \
54                                     IWL_RATE_##in##M_INDEX,    \
55                                     IWL_RATE_##rp##M_INDEX,    \
56                                     IWL_RATE_##rn##M_INDEX,    \
57                                     IWL_RATE_##pp##M_INDEX,    \
58                                     IWL_RATE_##np##M_INDEX }
59
60 /*
61  * Parameter order:
62  *   rate, ht rate, prev rate, next rate, prev tgg rate, next tgg rate
63  *
64  * If there isn't a valid next or previous rate then INV is used which
65  * maps to IWL_RATE_INVALID
66  *
67  */
68 const struct iwl4965_rate_info iwl4965_rates[IWL_RATE_COUNT] = {
69         IWL_DECLARE_RATE_INFO(1, INV, INV, 2, INV, 2, INV, 2),    /*  1mbps */
70         IWL_DECLARE_RATE_INFO(2, INV, 1, 5, 1, 5, 1, 5),          /*  2mbps */
71         IWL_DECLARE_RATE_INFO(5, INV, 2, 6, 2, 11, 2, 11),        /*5.5mbps */
72         IWL_DECLARE_RATE_INFO(11, INV, 9, 12, 9, 12, 5, 18),      /* 11mbps */
73         IWL_DECLARE_RATE_INFO(6, 6, 5, 9, 5, 11, 5, 11),        /*  6mbps */
74         IWL_DECLARE_RATE_INFO(9, 6, 6, 11, 6, 11, 5, 11),       /*  9mbps */
75         IWL_DECLARE_RATE_INFO(12, 12, 11, 18, 11, 18, 11, 18),   /* 12mbps */
76         IWL_DECLARE_RATE_INFO(18, 18, 12, 24, 12, 24, 11, 24),   /* 18mbps */
77         IWL_DECLARE_RATE_INFO(24, 24, 18, 36, 18, 36, 18, 36),   /* 24mbps */
78         IWL_DECLARE_RATE_INFO(36, 36, 24, 48, 24, 48, 24, 48),   /* 36mbps */
79         IWL_DECLARE_RATE_INFO(48, 48, 36, 54, 36, 54, 36, 54),   /* 48mbps */
80         IWL_DECLARE_RATE_INFO(54, 54, 48, INV, 48, INV, 48, INV),/* 54mbps */
81         IWL_DECLARE_RATE_INFO(60, 60, 48, INV, 48, INV, 48, INV),/* 60mbps */
82 };
83
84 #ifdef CONFIG_IWL4965_HT
85
86 static const u16 default_tid_to_tx_fifo[] = {
87         IWL_TX_FIFO_AC1,
88         IWL_TX_FIFO_AC0,
89         IWL_TX_FIFO_AC0,
90         IWL_TX_FIFO_AC1,
91         IWL_TX_FIFO_AC2,
92         IWL_TX_FIFO_AC2,
93         IWL_TX_FIFO_AC3,
94         IWL_TX_FIFO_AC3,
95         IWL_TX_FIFO_NONE,
96         IWL_TX_FIFO_NONE,
97         IWL_TX_FIFO_NONE,
98         IWL_TX_FIFO_NONE,
99         IWL_TX_FIFO_NONE,
100         IWL_TX_FIFO_NONE,
101         IWL_TX_FIFO_NONE,
102         IWL_TX_FIFO_NONE,
103         IWL_TX_FIFO_AC3
104 };
105
106 #endif  /*CONFIG_IWL4965_HT */
107
108 static int is_fat_channel(__le32 rxon_flags)
109 {
110         return (rxon_flags & RXON_FLG_CHANNEL_MODE_PURE_40_MSK) ||
111                 (rxon_flags & RXON_FLG_CHANNEL_MODE_MIXED_MSK);
112 }
113
114 static u8 is_single_stream(struct iwl_priv *priv)
115 {
116 #ifdef CONFIG_IWL4965_HT
117         if (!priv->current_ht_config.is_ht ||
118             (priv->current_ht_config.supp_mcs_set[1] == 0) ||
119             (priv->ps_mode == IWL_MIMO_PS_STATIC))
120                 return 1;
121 #else
122         return 1;
123 #endif  /*CONFIG_IWL4965_HT */
124         return 0;
125 }
126
127 int iwl4965_hwrate_to_plcp_idx(u32 rate_n_flags)
128 {
129         int idx = 0;
130
131         /* 4965 HT rate format */
132         if (rate_n_flags & RATE_MCS_HT_MSK) {
133                 idx = (rate_n_flags & 0xff);
134
135                 if (idx >= IWL_RATE_MIMO_6M_PLCP)
136                         idx = idx - IWL_RATE_MIMO_6M_PLCP;
137
138                 idx += IWL_FIRST_OFDM_RATE;
139                 /* skip 9M not supported in ht*/
140                 if (idx >= IWL_RATE_9M_INDEX)
141                         idx += 1;
142                 if ((idx >= IWL_FIRST_OFDM_RATE) && (idx <= IWL_LAST_OFDM_RATE))
143                         return idx;
144
145         /* 4965 legacy rate format, search for match in table */
146         } else {
147                 for (idx = 0; idx < ARRAY_SIZE(iwl4965_rates); idx++)
148                         if (iwl4965_rates[idx].plcp == (rate_n_flags & 0xFF))
149                                 return idx;
150         }
151
152         return -1;
153 }
154
155 /**
156  * translate ucode response to mac80211 tx status control values
157  */
158 void iwl4965_hwrate_to_tx_control(struct iwl_priv *priv, u32 rate_n_flags,
159                                   struct ieee80211_tx_control *control)
160 {
161         int rate_index;
162
163         control->antenna_sel_tx =
164                 ((rate_n_flags & RATE_MCS_ANT_AB_MSK) >> RATE_MCS_ANT_A_POS);
165         if (rate_n_flags & RATE_MCS_HT_MSK)
166                 control->flags |= IEEE80211_TXCTL_OFDM_HT;
167         if (rate_n_flags & RATE_MCS_GF_MSK)
168                 control->flags |= IEEE80211_TXCTL_GREEN_FIELD;
169         if (rate_n_flags & RATE_MCS_FAT_MSK)
170                 control->flags |= IEEE80211_TXCTL_40_MHZ_WIDTH;
171         if (rate_n_flags & RATE_MCS_DUP_MSK)
172                 control->flags |= IEEE80211_TXCTL_DUP_DATA;
173         if (rate_n_flags & RATE_MCS_SGI_MSK)
174                 control->flags |= IEEE80211_TXCTL_SHORT_GI;
175         /* since iwl4965_hwrate_to_plcp_idx is band indifferent, we always use
176          * IEEE80211_BAND_2GHZ band as it contains all the rates */
177         rate_index = iwl4965_hwrate_to_plcp_idx(rate_n_flags);
178         if (rate_index == -1)
179                 control->tx_rate = NULL;
180         else
181                 control->tx_rate =
182                         &priv->bands[IEEE80211_BAND_2GHZ].bitrates[rate_index];
183 }
184
185 /*
186  * Determine how many receiver/antenna chains to use.
187  * More provides better reception via diversity.  Fewer saves power.
188  * MIMO (dual stream) requires at least 2, but works better with 3.
189  * This does not determine *which* chains to use, just how many.
190  */
191 static int iwl4965_get_rx_chain_counter(struct iwl_priv *priv,
192                                         u8 *idle_state, u8 *rx_state)
193 {
194         u8 is_single = is_single_stream(priv);
195         u8 is_cam = test_bit(STATUS_POWER_PMI, &priv->status) ? 0 : 1;
196
197         /* # of Rx chains to use when expecting MIMO. */
198         if (is_single || (!is_cam && (priv->ps_mode == IWL_MIMO_PS_STATIC)))
199                 *rx_state = 2;
200         else
201                 *rx_state = 3;
202
203         /* # Rx chains when idling and maybe trying to save power */
204         switch (priv->ps_mode) {
205         case IWL_MIMO_PS_STATIC:
206         case IWL_MIMO_PS_DYNAMIC:
207                 *idle_state = (is_cam) ? 2 : 1;
208                 break;
209         case IWL_MIMO_PS_NONE:
210                 *idle_state = (is_cam) ? *rx_state : 1;
211                 break;
212         default:
213                 *idle_state = 1;
214                 break;
215         }
216
217         return 0;
218 }
219
220 int iwl4965_hw_rxq_stop(struct iwl_priv *priv)
221 {
222         int rc;
223         unsigned long flags;
224
225         spin_lock_irqsave(&priv->lock, flags);
226         rc = iwl4965_grab_nic_access(priv);
227         if (rc) {
228                 spin_unlock_irqrestore(&priv->lock, flags);
229                 return rc;
230         }
231
232         /* stop Rx DMA */
233         iwl4965_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0);
234         rc = iwl4965_poll_direct_bit(priv, FH_MEM_RSSR_RX_STATUS_REG,
235                                      (1 << 24), 1000);
236         if (rc < 0)
237                 IWL_ERROR("Can't stop Rx DMA.\n");
238
239         iwl4965_release_nic_access(priv);
240         spin_unlock_irqrestore(&priv->lock, flags);
241
242         return 0;
243 }
244
245 u8 iwl4965_hw_find_station(struct iwl_priv *priv, const u8 *addr)
246 {
247         int i;
248         int start = 0;
249         int ret = IWL_INVALID_STATION;
250         unsigned long flags;
251         DECLARE_MAC_BUF(mac);
252
253         if ((priv->iw_mode == IEEE80211_IF_TYPE_IBSS) ||
254             (priv->iw_mode == IEEE80211_IF_TYPE_AP))
255                 start = IWL_STA_ID;
256
257         if (is_broadcast_ether_addr(addr))
258                 return priv->hw_setting.bcast_sta_id;
259
260         spin_lock_irqsave(&priv->sta_lock, flags);
261         for (i = start; i < priv->hw_setting.max_stations; i++)
262                 if ((priv->stations[i].used) &&
263                     (!compare_ether_addr
264                      (priv->stations[i].sta.sta.addr, addr))) {
265                         ret = i;
266                         goto out;
267                 }
268
269         IWL_DEBUG_ASSOC_LIMIT("can not find STA %s total %d\n",
270                         print_mac(mac, addr), priv->num_stations);
271
272  out:
273         spin_unlock_irqrestore(&priv->sta_lock, flags);
274         return ret;
275 }
276
277 static int iwl4965_nic_set_pwr_src(struct iwl_priv *priv, int pwr_max)
278 {
279         int ret;
280         unsigned long flags;
281
282         spin_lock_irqsave(&priv->lock, flags);
283         ret = iwl4965_grab_nic_access(priv);
284         if (ret) {
285                 spin_unlock_irqrestore(&priv->lock, flags);
286                 return ret;
287         }
288
289         if (!pwr_max) {
290                 u32 val;
291
292                 ret = pci_read_config_dword(priv->pci_dev, PCI_POWER_SOURCE,
293                                            &val);
294
295                 if (val & PCI_CFG_PMC_PME_FROM_D3COLD_SUPPORT)
296                         iwl4965_set_bits_mask_prph(priv, APMG_PS_CTRL_REG,
297                                 APMG_PS_CTRL_VAL_PWR_SRC_VAUX,
298                                 ~APMG_PS_CTRL_MSK_PWR_SRC);
299         } else
300                 iwl4965_set_bits_mask_prph(priv, APMG_PS_CTRL_REG,
301                         APMG_PS_CTRL_VAL_PWR_SRC_VMAIN,
302                         ~APMG_PS_CTRL_MSK_PWR_SRC);
303
304         iwl4965_release_nic_access(priv);
305         spin_unlock_irqrestore(&priv->lock, flags);
306
307         return ret;
308 }
309
310 static int iwl4965_rx_init(struct iwl_priv *priv, struct iwl4965_rx_queue *rxq)
311 {
312         int rc;
313         unsigned long flags;
314         unsigned int rb_size;
315
316         spin_lock_irqsave(&priv->lock, flags);
317         rc = iwl4965_grab_nic_access(priv);
318         if (rc) {
319                 spin_unlock_irqrestore(&priv->lock, flags);
320                 return rc;
321         }
322
323         if (iwl4965_mod_params.amsdu_size_8K)
324                 rb_size = FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_8K;
325         else
326                 rb_size = FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_4K;
327
328         /* Stop Rx DMA */
329         iwl4965_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0);
330
331         /* Reset driver's Rx queue write index */
332         iwl4965_write_direct32(priv, FH_RSCSR_CHNL0_RBDCB_WPTR_REG, 0);
333
334         /* Tell device where to find RBD circular buffer in DRAM */
335         iwl4965_write_direct32(priv, FH_RSCSR_CHNL0_RBDCB_BASE_REG,
336                              rxq->dma_addr >> 8);
337
338         /* Tell device where in DRAM to update its Rx status */
339         iwl4965_write_direct32(priv, FH_RSCSR_CHNL0_STTS_WPTR_REG,
340                              (priv->hw_setting.shared_phys +
341                               offsetof(struct iwl4965_shared, val0)) >> 4);
342
343         /* Enable Rx DMA, enable host interrupt, Rx buffer size 4k, 256 RBDs */
344         iwl4965_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG,
345                              FH_RCSR_RX_CONFIG_CHNL_EN_ENABLE_VAL |
346                              FH_RCSR_CHNL0_RX_CONFIG_IRQ_DEST_INT_HOST_VAL |
347                              rb_size |
348                              /*0x10 << 4 | */
349                              (RX_QUEUE_SIZE_LOG <<
350                               FH_RCSR_RX_CONFIG_RBDCB_SIZE_BITSHIFT));
351
352         /*
353          * iwl4965_write32(priv,CSR_INT_COAL_REG,0);
354          */
355
356         iwl4965_release_nic_access(priv);
357         spin_unlock_irqrestore(&priv->lock, flags);
358
359         return 0;
360 }
361
362 /* Tell 4965 where to find the "keep warm" buffer */
363 static int iwl4965_kw_init(struct iwl_priv *priv)
364 {
365         unsigned long flags;
366         int rc;
367
368         spin_lock_irqsave(&priv->lock, flags);
369         rc = iwl4965_grab_nic_access(priv);
370         if (rc)
371                 goto out;
372
373         iwl4965_write_direct32(priv, IWL_FH_KW_MEM_ADDR_REG,
374                              priv->kw.dma_addr >> 4);
375         iwl4965_release_nic_access(priv);
376 out:
377         spin_unlock_irqrestore(&priv->lock, flags);
378         return rc;
379 }
380
381 static int iwl4965_kw_alloc(struct iwl_priv *priv)
382 {
383         struct pci_dev *dev = priv->pci_dev;
384         struct iwl4965_kw *kw = &priv->kw;
385
386         kw->size = IWL4965_KW_SIZE;     /* TBW need set somewhere else */
387         kw->v_addr = pci_alloc_consistent(dev, kw->size, &kw->dma_addr);
388         if (!kw->v_addr)
389                 return -ENOMEM;
390
391         return 0;
392 }
393
394 #define CHECK_AND_PRINT(x) ((eeprom_ch->flags & EEPROM_CHANNEL_##x) \
395                             ? # x " " : "")
396
397 /**
398  * iwl4965_set_fat_chan_info - Copy fat channel info into driver's priv.
399  *
400  * Does not set up a command, or touch hardware.
401  */
402 int iwl4965_set_fat_chan_info(struct iwl_priv *priv,
403                               enum ieee80211_band band, u16 channel,
404                               const struct iwl4965_eeprom_channel *eeprom_ch,
405                               u8 fat_extension_channel)
406 {
407         struct iwl4965_channel_info *ch_info;
408
409         ch_info = (struct iwl4965_channel_info *)
410                         iwl4965_get_channel_info(priv, band, channel);
411
412         if (!is_channel_valid(ch_info))
413                 return -1;
414
415         IWL_DEBUG_INFO("FAT Ch. %d [%sGHz] %s%s%s%s%s%s(0x%02x"
416                         " %ddBm): Ad-Hoc %ssupported\n",
417                         ch_info->channel,
418                         is_channel_a_band(ch_info) ?
419                         "5.2" : "2.4",
420                         CHECK_AND_PRINT(IBSS),
421                         CHECK_AND_PRINT(ACTIVE),
422                         CHECK_AND_PRINT(RADAR),
423                         CHECK_AND_PRINT(WIDE),
424                         CHECK_AND_PRINT(NARROW),
425                         CHECK_AND_PRINT(DFS),
426                         eeprom_ch->flags,
427                         eeprom_ch->max_power_avg,
428                         ((eeprom_ch->flags & EEPROM_CHANNEL_IBSS)
429                          && !(eeprom_ch->flags & EEPROM_CHANNEL_RADAR)) ?
430                         "" : "not ");
431
432         ch_info->fat_eeprom = *eeprom_ch;
433         ch_info->fat_max_power_avg = eeprom_ch->max_power_avg;
434         ch_info->fat_curr_txpow = eeprom_ch->max_power_avg;
435         ch_info->fat_min_power = 0;
436         ch_info->fat_scan_power = eeprom_ch->max_power_avg;
437         ch_info->fat_flags = eeprom_ch->flags;
438         ch_info->fat_extension_channel = fat_extension_channel;
439
440         return 0;
441 }
442
443 /**
444  * iwl4965_kw_free - Free the "keep warm" buffer
445  */
446 static void iwl4965_kw_free(struct iwl_priv *priv)
447 {
448         struct pci_dev *dev = priv->pci_dev;
449         struct iwl4965_kw *kw = &priv->kw;
450
451         if (kw->v_addr) {
452                 pci_free_consistent(dev, kw->size, kw->v_addr, kw->dma_addr);
453                 memset(kw, 0, sizeof(*kw));
454         }
455 }
456
457 /**
458  * iwl4965_txq_ctx_reset - Reset TX queue context
459  * Destroys all DMA structures and initialise them again
460  *
461  * @param priv
462  * @return error code
463  */
464 static int iwl4965_txq_ctx_reset(struct iwl_priv *priv)
465 {
466         int rc = 0;
467         int txq_id, slots_num;
468         unsigned long flags;
469
470         iwl4965_kw_free(priv);
471
472         /* Free all tx/cmd queues and keep-warm buffer */
473         iwl4965_hw_txq_ctx_free(priv);
474
475         /* Alloc keep-warm buffer */
476         rc = iwl4965_kw_alloc(priv);
477         if (rc) {
478                 IWL_ERROR("Keep Warm allocation failed");
479                 goto error_kw;
480         }
481
482         spin_lock_irqsave(&priv->lock, flags);
483
484         rc = iwl4965_grab_nic_access(priv);
485         if (unlikely(rc)) {
486                 IWL_ERROR("TX reset failed");
487                 spin_unlock_irqrestore(&priv->lock, flags);
488                 goto error_reset;
489         }
490
491         /* Turn off all Tx DMA channels */
492         iwl4965_write_prph(priv, KDR_SCD_TXFACT, 0);
493         iwl4965_release_nic_access(priv);
494         spin_unlock_irqrestore(&priv->lock, flags);
495
496         /* Tell 4965 where to find the keep-warm buffer */
497         rc = iwl4965_kw_init(priv);
498         if (rc) {
499                 IWL_ERROR("kw_init failed\n");
500                 goto error_reset;
501         }
502
503         /* Alloc and init all (default 16) Tx queues,
504          * including the command queue (#4) */
505         for (txq_id = 0; txq_id < priv->hw_setting.max_txq_num; txq_id++) {
506                 slots_num = (txq_id == IWL_CMD_QUEUE_NUM) ?
507                                         TFD_CMD_SLOTS : TFD_TX_CMD_SLOTS;
508                 rc = iwl4965_tx_queue_init(priv, &priv->txq[txq_id], slots_num,
509                                        txq_id);
510                 if (rc) {
511                         IWL_ERROR("Tx %d queue init failed\n", txq_id);
512                         goto error;
513                 }
514         }
515
516         return rc;
517
518  error:
519         iwl4965_hw_txq_ctx_free(priv);
520  error_reset:
521         iwl4965_kw_free(priv);
522  error_kw:
523         return rc;
524 }
525
526 int iwl4965_hw_nic_init(struct iwl_priv *priv)
527 {
528         int rc;
529         unsigned long flags;
530         struct iwl4965_rx_queue *rxq = &priv->rxq;
531         u8 rev_id;
532         u32 val;
533         u8 val_link;
534
535         iwl4965_power_init_handle(priv);
536
537         /* nic_init */
538         spin_lock_irqsave(&priv->lock, flags);
539
540         iwl4965_set_bit(priv, CSR_GIO_CHICKEN_BITS,
541                     CSR_GIO_CHICKEN_BITS_REG_BIT_DIS_L0S_EXIT_TIMER);
542
543         iwl4965_set_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
544         rc = iwl4965_poll_bit(priv, CSR_GP_CNTRL,
545                           CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY,
546                           CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY, 25000);
547         if (rc < 0) {
548                 spin_unlock_irqrestore(&priv->lock, flags);
549                 IWL_DEBUG_INFO("Failed to init the card\n");
550                 return rc;
551         }
552
553         rc = iwl4965_grab_nic_access(priv);
554         if (rc) {
555                 spin_unlock_irqrestore(&priv->lock, flags);
556                 return rc;
557         }
558
559         iwl4965_read_prph(priv, APMG_CLK_CTRL_REG);
560
561         iwl4965_write_prph(priv, APMG_CLK_CTRL_REG,
562                                  APMG_CLK_VAL_DMA_CLK_RQT |
563                                  APMG_CLK_VAL_BSM_CLK_RQT);
564         iwl4965_read_prph(priv, APMG_CLK_CTRL_REG);
565
566         udelay(20);
567
568         iwl4965_set_bits_prph(priv, APMG_PCIDEV_STT_REG,
569                                     APMG_PCIDEV_STT_VAL_L1_ACT_DIS);
570
571         iwl4965_release_nic_access(priv);
572         iwl4965_write32(priv, CSR_INT_COALESCING, 512 / 32);
573         spin_unlock_irqrestore(&priv->lock, flags);
574
575         /* Determine HW type */
576         rc = pci_read_config_byte(priv->pci_dev, PCI_REVISION_ID, &rev_id);
577         if (rc)
578                 return rc;
579
580         IWL_DEBUG_INFO("HW Revision ID = 0x%X\n", rev_id);
581
582         iwl4965_nic_set_pwr_src(priv, 1);
583         spin_lock_irqsave(&priv->lock, flags);
584
585         if ((rev_id & 0x80) == 0x80 && (rev_id & 0x7f) < 8) {
586                 pci_read_config_dword(priv->pci_dev, PCI_REG_WUM8, &val);
587                 /* Enable No Snoop field */
588                 pci_write_config_dword(priv->pci_dev, PCI_REG_WUM8,
589                                        val & ~(1 << 11));
590         }
591
592         spin_unlock_irqrestore(&priv->lock, flags);
593
594         if (priv->eeprom.calib_version < EEPROM_TX_POWER_VERSION_NEW) {
595                 IWL_ERROR("Older EEPROM detected!  Aborting.\n");
596                 return -EINVAL;
597         }
598
599         pci_read_config_byte(priv->pci_dev, PCI_LINK_CTRL, &val_link);
600
601         /* disable L1 entry -- workaround for pre-B1 */
602         pci_write_config_byte(priv->pci_dev, PCI_LINK_CTRL, val_link & ~0x02);
603
604         spin_lock_irqsave(&priv->lock, flags);
605
606         /* set CSR_HW_CONFIG_REG for uCode use */
607
608         iwl4965_set_bit(priv, CSR_HW_IF_CONFIG_REG,
609                         CSR49_HW_IF_CONFIG_REG_BIT_4965_R |
610                         CSR49_HW_IF_CONFIG_REG_BIT_RADIO_SI |
611                         CSR49_HW_IF_CONFIG_REG_BIT_MAC_SI);
612
613         rc = iwl4965_grab_nic_access(priv);
614         if (rc < 0) {
615                 spin_unlock_irqrestore(&priv->lock, flags);
616                 IWL_DEBUG_INFO("Failed to init the card\n");
617                 return rc;
618         }
619
620         iwl4965_read_prph(priv, APMG_PS_CTRL_REG);
621         iwl4965_set_bits_prph(priv, APMG_PS_CTRL_REG,
622                                     APMG_PS_CTRL_VAL_RESET_REQ);
623         udelay(5);
624         iwl4965_clear_bits_prph(priv, APMG_PS_CTRL_REG,
625                                       APMG_PS_CTRL_VAL_RESET_REQ);
626
627         iwl4965_release_nic_access(priv);
628         spin_unlock_irqrestore(&priv->lock, flags);
629
630         iwl4965_hw_card_show_info(priv);
631
632         /* end nic_init */
633
634         /* Allocate the RX queue, or reset if it is already allocated */
635         if (!rxq->bd) {
636                 rc = iwl4965_rx_queue_alloc(priv);
637                 if (rc) {
638                         IWL_ERROR("Unable to initialize Rx queue\n");
639                         return -ENOMEM;
640                 }
641         } else
642                 iwl4965_rx_queue_reset(priv, rxq);
643
644         iwl4965_rx_replenish(priv);
645
646         iwl4965_rx_init(priv, rxq);
647
648         spin_lock_irqsave(&priv->lock, flags);
649
650         rxq->need_update = 1;
651         iwl4965_rx_queue_update_write_ptr(priv, rxq);
652
653         spin_unlock_irqrestore(&priv->lock, flags);
654
655         /* Allocate and init all Tx and Command queues */
656         rc = iwl4965_txq_ctx_reset(priv);
657         if (rc)
658                 return rc;
659
660         if (priv->eeprom.sku_cap & EEPROM_SKU_CAP_SW_RF_KILL_ENABLE)
661                 IWL_DEBUG_RF_KILL("SW RF KILL supported in EEPROM.\n");
662
663         if (priv->eeprom.sku_cap & EEPROM_SKU_CAP_HW_RF_KILL_ENABLE)
664                 IWL_DEBUG_RF_KILL("HW RF KILL supported in EEPROM.\n");
665
666         set_bit(STATUS_INIT, &priv->status);
667
668         return 0;
669 }
670
671 int iwl4965_hw_nic_stop_master(struct iwl_priv *priv)
672 {
673         int rc = 0;
674         u32 reg_val;
675         unsigned long flags;
676
677         spin_lock_irqsave(&priv->lock, flags);
678
679         /* set stop master bit */
680         iwl4965_set_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_STOP_MASTER);
681
682         reg_val = iwl4965_read32(priv, CSR_GP_CNTRL);
683
684         if (CSR_GP_CNTRL_REG_FLAG_MAC_POWER_SAVE ==
685             (reg_val & CSR_GP_CNTRL_REG_MSK_POWER_SAVE_TYPE))
686                 IWL_DEBUG_INFO("Card in power save, master is already "
687                                "stopped\n");
688         else {
689                 rc = iwl4965_poll_bit(priv, CSR_RESET,
690                                   CSR_RESET_REG_FLAG_MASTER_DISABLED,
691                                   CSR_RESET_REG_FLAG_MASTER_DISABLED, 100);
692                 if (rc < 0) {
693                         spin_unlock_irqrestore(&priv->lock, flags);
694                         return rc;
695                 }
696         }
697
698         spin_unlock_irqrestore(&priv->lock, flags);
699         IWL_DEBUG_INFO("stop master\n");
700
701         return rc;
702 }
703
704 /**
705  * iwl4965_hw_txq_ctx_stop - Stop all Tx DMA channels, free Tx queue memory
706  */
707 void iwl4965_hw_txq_ctx_stop(struct iwl_priv *priv)
708 {
709
710         int txq_id;
711         unsigned long flags;
712
713         /* Stop each Tx DMA channel, and wait for it to be idle */
714         for (txq_id = 0; txq_id < priv->hw_setting.max_txq_num; txq_id++) {
715                 spin_lock_irqsave(&priv->lock, flags);
716                 if (iwl4965_grab_nic_access(priv)) {
717                         spin_unlock_irqrestore(&priv->lock, flags);
718                         continue;
719                 }
720
721                 iwl4965_write_direct32(priv,
722                                      IWL_FH_TCSR_CHNL_TX_CONFIG_REG(txq_id),
723                                      0x0);
724                 iwl4965_poll_direct_bit(priv, IWL_FH_TSSR_TX_STATUS_REG,
725                                         IWL_FH_TSSR_TX_STATUS_REG_MSK_CHNL_IDLE
726                                         (txq_id), 200);
727                 iwl4965_release_nic_access(priv);
728                 spin_unlock_irqrestore(&priv->lock, flags);
729         }
730
731         /* Deallocate memory for all Tx queues */
732         iwl4965_hw_txq_ctx_free(priv);
733 }
734
735 int iwl4965_hw_nic_reset(struct iwl_priv *priv)
736 {
737         int rc = 0;
738         unsigned long flags;
739
740         iwl4965_hw_nic_stop_master(priv);
741
742         spin_lock_irqsave(&priv->lock, flags);
743
744         iwl4965_set_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_SW_RESET);
745
746         udelay(10);
747
748         iwl4965_set_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
749         rc = iwl4965_poll_bit(priv, CSR_RESET,
750                           CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY,
751                           CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY, 25);
752
753         udelay(10);
754
755         rc = iwl4965_grab_nic_access(priv);
756         if (!rc) {
757                 iwl4965_write_prph(priv, APMG_CLK_EN_REG,
758                                          APMG_CLK_VAL_DMA_CLK_RQT |
759                                          APMG_CLK_VAL_BSM_CLK_RQT);
760
761                 udelay(10);
762
763                 iwl4965_set_bits_prph(priv, APMG_PCIDEV_STT_REG,
764                                 APMG_PCIDEV_STT_VAL_L1_ACT_DIS);
765
766                 iwl4965_release_nic_access(priv);
767         }
768
769         clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
770         wake_up_interruptible(&priv->wait_command_queue);
771
772         spin_unlock_irqrestore(&priv->lock, flags);
773
774         return rc;
775
776 }
777
778 #define REG_RECALIB_PERIOD (60)
779
780 /**
781  * iwl4965_bg_statistics_periodic - Timer callback to queue statistics
782  *
783  * This callback is provided in order to queue the statistics_work
784  * in work_queue context (v. softirq)
785  *
786  * This timer function is continually reset to execute within
787  * REG_RECALIB_PERIOD seconds since the last STATISTICS_NOTIFICATION
788  * was received.  We need to ensure we receive the statistics in order
789  * to update the temperature used for calibrating the TXPOWER.  However,
790  * we can't send the statistics command from softirq context (which
791  * is the context which timers run at) so we have to queue off the
792  * statistics_work to actually send the command to the hardware.
793  */
794 static void iwl4965_bg_statistics_periodic(unsigned long data)
795 {
796         struct iwl_priv *priv = (struct iwl_priv *)data;
797
798         queue_work(priv->workqueue, &priv->statistics_work);
799 }
800
801 /**
802  * iwl4965_bg_statistics_work - Send the statistics request to the hardware.
803  *
804  * This is queued by iwl4965_bg_statistics_periodic.
805  */
806 static void iwl4965_bg_statistics_work(struct work_struct *work)
807 {
808         struct iwl_priv *priv = container_of(work, struct iwl_priv,
809                                              statistics_work);
810
811         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
812                 return;
813
814         mutex_lock(&priv->mutex);
815         iwl4965_send_statistics_request(priv);
816         mutex_unlock(&priv->mutex);
817 }
818
819 #define CT_LIMIT_CONST          259
820 #define TM_CT_KILL_THRESHOLD    110
821
822 void iwl4965_rf_kill_ct_config(struct iwl_priv *priv)
823 {
824         struct iwl4965_ct_kill_config cmd;
825         u32 R1, R2, R3;
826         u32 temp_th;
827         u32 crit_temperature;
828         unsigned long flags;
829         int rc = 0;
830
831         spin_lock_irqsave(&priv->lock, flags);
832         iwl4965_write32(priv, CSR_UCODE_DRV_GP1_CLR,
833                     CSR_UCODE_DRV_GP1_REG_BIT_CT_KILL_EXIT);
834         spin_unlock_irqrestore(&priv->lock, flags);
835
836         if (priv->statistics.flag & STATISTICS_REPLY_FLG_FAT_MODE_MSK) {
837                 R1 = (s32)le32_to_cpu(priv->card_alive_init.therm_r1[1]);
838                 R2 = (s32)le32_to_cpu(priv->card_alive_init.therm_r2[1]);
839                 R3 = (s32)le32_to_cpu(priv->card_alive_init.therm_r3[1]);
840         } else {
841                 R1 = (s32)le32_to_cpu(priv->card_alive_init.therm_r1[0]);
842                 R2 = (s32)le32_to_cpu(priv->card_alive_init.therm_r2[0]);
843                 R3 = (s32)le32_to_cpu(priv->card_alive_init.therm_r3[0]);
844         }
845
846         temp_th = CELSIUS_TO_KELVIN(TM_CT_KILL_THRESHOLD);
847
848         crit_temperature = ((temp_th * (R3-R1))/CT_LIMIT_CONST) + R2;
849         cmd.critical_temperature_R =  cpu_to_le32(crit_temperature);
850         rc = iwl4965_send_cmd_pdu(priv,
851                               REPLY_CT_KILL_CONFIG_CMD, sizeof(cmd), &cmd);
852         if (rc)
853                 IWL_ERROR("REPLY_CT_KILL_CONFIG_CMD failed\n");
854         else
855                 IWL_DEBUG_INFO("REPLY_CT_KILL_CONFIG_CMD succeeded\n");
856 }
857
858 #ifdef CONFIG_IWL4965_SENSITIVITY
859
860 /* "false alarms" are signals that our DSP tries to lock onto,
861  *   but then determines that they are either noise, or transmissions
862  *   from a distant wireless network (also "noise", really) that get
863  *   "stepped on" by stronger transmissions within our own network.
864  * This algorithm attempts to set a sensitivity level that is high
865  *   enough to receive all of our own network traffic, but not so
866  *   high that our DSP gets too busy trying to lock onto non-network
867  *   activity/noise. */
868 static int iwl4965_sens_energy_cck(struct iwl_priv *priv,
869                                    u32 norm_fa,
870                                    u32 rx_enable_time,
871                                    struct statistics_general_data *rx_info)
872 {
873         u32 max_nrg_cck = 0;
874         int i = 0;
875         u8 max_silence_rssi = 0;
876         u32 silence_ref = 0;
877         u8 silence_rssi_a = 0;
878         u8 silence_rssi_b = 0;
879         u8 silence_rssi_c = 0;
880         u32 val;
881
882         /* "false_alarms" values below are cross-multiplications to assess the
883          *   numbers of false alarms within the measured period of actual Rx
884          *   (Rx is off when we're txing), vs the min/max expected false alarms
885          *   (some should be expected if rx is sensitive enough) in a
886          *   hypothetical listening period of 200 time units (TU), 204.8 msec:
887          *
888          * MIN_FA/fixed-time < false_alarms/actual-rx-time < MAX_FA/beacon-time
889          *
890          * */
891         u32 false_alarms = norm_fa * 200 * 1024;
892         u32 max_false_alarms = MAX_FA_CCK * rx_enable_time;
893         u32 min_false_alarms = MIN_FA_CCK * rx_enable_time;
894         struct iwl4965_sensitivity_data *data = NULL;
895
896         data = &(priv->sensitivity_data);
897
898         data->nrg_auto_corr_silence_diff = 0;
899
900         /* Find max silence rssi among all 3 receivers.
901          * This is background noise, which may include transmissions from other
902          *    networks, measured during silence before our network's beacon */
903         silence_rssi_a = (u8)((rx_info->beacon_silence_rssi_a &
904                             ALL_BAND_FILTER) >> 8);
905         silence_rssi_b = (u8)((rx_info->beacon_silence_rssi_b &
906                             ALL_BAND_FILTER) >> 8);
907         silence_rssi_c = (u8)((rx_info->beacon_silence_rssi_c &
908                             ALL_BAND_FILTER) >> 8);
909
910         val = max(silence_rssi_b, silence_rssi_c);
911         max_silence_rssi = max(silence_rssi_a, (u8) val);
912
913         /* Store silence rssi in 20-beacon history table */
914         data->nrg_silence_rssi[data->nrg_silence_idx] = max_silence_rssi;
915         data->nrg_silence_idx++;
916         if (data->nrg_silence_idx >= NRG_NUM_PREV_STAT_L)
917                 data->nrg_silence_idx = 0;
918
919         /* Find max silence rssi across 20 beacon history */
920         for (i = 0; i < NRG_NUM_PREV_STAT_L; i++) {
921                 val = data->nrg_silence_rssi[i];
922                 silence_ref = max(silence_ref, val);
923         }
924         IWL_DEBUG_CALIB("silence a %u, b %u, c %u, 20-bcn max %u\n",
925                         silence_rssi_a, silence_rssi_b, silence_rssi_c,
926                         silence_ref);
927
928         /* Find max rx energy (min value!) among all 3 receivers,
929          *   measured during beacon frame.
930          * Save it in 10-beacon history table. */
931         i = data->nrg_energy_idx;
932         val = min(rx_info->beacon_energy_b, rx_info->beacon_energy_c);
933         data->nrg_value[i] = min(rx_info->beacon_energy_a, val);
934
935         data->nrg_energy_idx++;
936         if (data->nrg_energy_idx >= 10)
937                 data->nrg_energy_idx = 0;
938
939         /* Find min rx energy (max value) across 10 beacon history.
940          * This is the minimum signal level that we want to receive well.
941          * Add backoff (margin so we don't miss slightly lower energy frames).
942          * This establishes an upper bound (min value) for energy threshold. */
943         max_nrg_cck = data->nrg_value[0];
944         for (i = 1; i < 10; i++)
945                 max_nrg_cck = (u32) max(max_nrg_cck, (data->nrg_value[i]));
946         max_nrg_cck += 6;
947
948         IWL_DEBUG_CALIB("rx energy a %u, b %u, c %u, 10-bcn max/min %u\n",
949                         rx_info->beacon_energy_a, rx_info->beacon_energy_b,
950                         rx_info->beacon_energy_c, max_nrg_cck - 6);
951
952         /* Count number of consecutive beacons with fewer-than-desired
953          *   false alarms. */
954         if (false_alarms < min_false_alarms)
955                 data->num_in_cck_no_fa++;
956         else
957                 data->num_in_cck_no_fa = 0;
958         IWL_DEBUG_CALIB("consecutive bcns with few false alarms = %u\n",
959                         data->num_in_cck_no_fa);
960
961         /* If we got too many false alarms this time, reduce sensitivity */
962         if (false_alarms > max_false_alarms) {
963                 IWL_DEBUG_CALIB("norm FA %u > max FA %u\n",
964                              false_alarms, max_false_alarms);
965                 IWL_DEBUG_CALIB("... reducing sensitivity\n");
966                 data->nrg_curr_state = IWL_FA_TOO_MANY;
967
968                 if (data->auto_corr_cck > AUTO_CORR_MAX_TH_CCK) {
969                         /* Store for "fewer than desired" on later beacon */
970                         data->nrg_silence_ref = silence_ref;
971
972                         /* increase energy threshold (reduce nrg value)
973                          *   to decrease sensitivity */
974                         if (data->nrg_th_cck > (NRG_MAX_CCK + NRG_STEP_CCK))
975                                 data->nrg_th_cck = data->nrg_th_cck
976                                                          - NRG_STEP_CCK;
977                 }
978
979                 /* increase auto_corr values to decrease sensitivity */
980                 if (data->auto_corr_cck < AUTO_CORR_MAX_TH_CCK)
981                         data->auto_corr_cck = AUTO_CORR_MAX_TH_CCK + 1;
982                 else {
983                         val = data->auto_corr_cck + AUTO_CORR_STEP_CCK;
984                         data->auto_corr_cck = min((u32)AUTO_CORR_MAX_CCK, val);
985                 }
986                 val = data->auto_corr_cck_mrc + AUTO_CORR_STEP_CCK;
987                 data->auto_corr_cck_mrc = min((u32)AUTO_CORR_MAX_CCK_MRC, val);
988
989         /* Else if we got fewer than desired, increase sensitivity */
990         } else if (false_alarms < min_false_alarms) {
991                 data->nrg_curr_state = IWL_FA_TOO_FEW;
992
993                 /* Compare silence level with silence level for most recent
994                  *   healthy number or too many false alarms */
995                 data->nrg_auto_corr_silence_diff = (s32)data->nrg_silence_ref -
996                                                    (s32)silence_ref;
997
998                 IWL_DEBUG_CALIB("norm FA %u < min FA %u, silence diff %d\n",
999                          false_alarms, min_false_alarms,
1000                          data->nrg_auto_corr_silence_diff);
1001
1002                 /* Increase value to increase sensitivity, but only if:
1003                  * 1a) previous beacon did *not* have *too many* false alarms
1004                  * 1b) AND there's a significant difference in Rx levels
1005                  *      from a previous beacon with too many, or healthy # FAs
1006                  * OR 2) We've seen a lot of beacons (100) with too few
1007                  *       false alarms */
1008                 if ((data->nrg_prev_state != IWL_FA_TOO_MANY) &&
1009                         ((data->nrg_auto_corr_silence_diff > NRG_DIFF) ||
1010                         (data->num_in_cck_no_fa > MAX_NUMBER_CCK_NO_FA))) {
1011
1012                         IWL_DEBUG_CALIB("... increasing sensitivity\n");
1013                         /* Increase nrg value to increase sensitivity */
1014                         val = data->nrg_th_cck + NRG_STEP_CCK;
1015                         data->nrg_th_cck = min((u32)NRG_MIN_CCK, val);
1016
1017                         /* Decrease auto_corr values to increase sensitivity */
1018                         val = data->auto_corr_cck - AUTO_CORR_STEP_CCK;
1019                         data->auto_corr_cck = max((u32)AUTO_CORR_MIN_CCK, val);
1020
1021                         val = data->auto_corr_cck_mrc - AUTO_CORR_STEP_CCK;
1022                         data->auto_corr_cck_mrc =
1023                                          max((u32)AUTO_CORR_MIN_CCK_MRC, val);
1024
1025                 } else
1026                         IWL_DEBUG_CALIB("... but not changing sensitivity\n");
1027
1028         /* Else we got a healthy number of false alarms, keep status quo */
1029         } else {
1030                 IWL_DEBUG_CALIB(" FA in safe zone\n");
1031                 data->nrg_curr_state = IWL_FA_GOOD_RANGE;
1032
1033                 /* Store for use in "fewer than desired" with later beacon */
1034                 data->nrg_silence_ref = silence_ref;
1035
1036                 /* If previous beacon had too many false alarms,
1037                  *   give it some extra margin by reducing sensitivity again
1038                  *   (but don't go below measured energy of desired Rx) */
1039                 if (IWL_FA_TOO_MANY == data->nrg_prev_state) {
1040                         IWL_DEBUG_CALIB("... increasing margin\n");
1041                         data->nrg_th_cck -= NRG_MARGIN;
1042                 }
1043         }
1044
1045         /* Make sure the energy threshold does not go above the measured
1046          * energy of the desired Rx signals (reduced by backoff margin),
1047          * or else we might start missing Rx frames.
1048          * Lower value is higher energy, so we use max()!
1049          */
1050         data->nrg_th_cck = max(max_nrg_cck, data->nrg_th_cck);
1051         IWL_DEBUG_CALIB("new nrg_th_cck %u\n", data->nrg_th_cck);
1052
1053         data->nrg_prev_state = data->nrg_curr_state;
1054
1055         return 0;
1056 }
1057
1058
1059 static int iwl4965_sens_auto_corr_ofdm(struct iwl_priv *priv,
1060                                        u32 norm_fa,
1061                                        u32 rx_enable_time)
1062 {
1063         u32 val;
1064         u32 false_alarms = norm_fa * 200 * 1024;
1065         u32 max_false_alarms = MAX_FA_OFDM * rx_enable_time;
1066         u32 min_false_alarms = MIN_FA_OFDM * rx_enable_time;
1067         struct iwl4965_sensitivity_data *data = NULL;
1068
1069         data = &(priv->sensitivity_data);
1070
1071         /* If we got too many false alarms this time, reduce sensitivity */
1072         if (false_alarms > max_false_alarms) {
1073
1074                 IWL_DEBUG_CALIB("norm FA %u > max FA %u)\n",
1075                              false_alarms, max_false_alarms);
1076
1077                 val = data->auto_corr_ofdm + AUTO_CORR_STEP_OFDM;
1078                 data->auto_corr_ofdm =
1079                                 min((u32)AUTO_CORR_MAX_OFDM, val);
1080
1081                 val = data->auto_corr_ofdm_mrc + AUTO_CORR_STEP_OFDM;
1082                 data->auto_corr_ofdm_mrc =
1083                                 min((u32)AUTO_CORR_MAX_OFDM_MRC, val);
1084
1085                 val = data->auto_corr_ofdm_x1 + AUTO_CORR_STEP_OFDM;
1086                 data->auto_corr_ofdm_x1 =
1087                                 min((u32)AUTO_CORR_MAX_OFDM_X1, val);
1088
1089                 val = data->auto_corr_ofdm_mrc_x1 + AUTO_CORR_STEP_OFDM;
1090                 data->auto_corr_ofdm_mrc_x1 =
1091                                 min((u32)AUTO_CORR_MAX_OFDM_MRC_X1, val);
1092         }
1093
1094         /* Else if we got fewer than desired, increase sensitivity */
1095         else if (false_alarms < min_false_alarms) {
1096
1097                 IWL_DEBUG_CALIB("norm FA %u < min FA %u\n",
1098                              false_alarms, min_false_alarms);
1099
1100                 val = data->auto_corr_ofdm - AUTO_CORR_STEP_OFDM;
1101                 data->auto_corr_ofdm =
1102                                 max((u32)AUTO_CORR_MIN_OFDM, val);
1103
1104                 val = data->auto_corr_ofdm_mrc - AUTO_CORR_STEP_OFDM;
1105                 data->auto_corr_ofdm_mrc =
1106                                 max((u32)AUTO_CORR_MIN_OFDM_MRC, val);
1107
1108                 val = data->auto_corr_ofdm_x1 - AUTO_CORR_STEP_OFDM;
1109                 data->auto_corr_ofdm_x1 =
1110                                 max((u32)AUTO_CORR_MIN_OFDM_X1, val);
1111
1112                 val = data->auto_corr_ofdm_mrc_x1 - AUTO_CORR_STEP_OFDM;
1113                 data->auto_corr_ofdm_mrc_x1 =
1114                                 max((u32)AUTO_CORR_MIN_OFDM_MRC_X1, val);
1115         }
1116
1117         else
1118                 IWL_DEBUG_CALIB("min FA %u < norm FA %u < max FA %u OK\n",
1119                          min_false_alarms, false_alarms, max_false_alarms);
1120
1121         return 0;
1122 }
1123
1124 static int iwl4965_sensitivity_callback(struct iwl_priv *priv,
1125                                     struct iwl4965_cmd *cmd, struct sk_buff *skb)
1126 {
1127         /* We didn't cache the SKB; let the caller free it */
1128         return 1;
1129 }
1130
1131 /* Prepare a SENSITIVITY_CMD, send to uCode if values have changed */
1132 static int iwl4965_sensitivity_write(struct iwl_priv *priv, u8 flags)
1133 {
1134         int rc = 0;
1135         struct iwl4965_sensitivity_cmd cmd ;
1136         struct iwl4965_sensitivity_data *data = NULL;
1137         struct iwl4965_host_cmd cmd_out = {
1138                 .id = SENSITIVITY_CMD,
1139                 .len = sizeof(struct iwl4965_sensitivity_cmd),
1140                 .meta.flags = flags,
1141                 .data = &cmd,
1142         };
1143
1144         data = &(priv->sensitivity_data);
1145
1146         memset(&cmd, 0, sizeof(cmd));
1147
1148         cmd.table[HD_AUTO_CORR32_X4_TH_ADD_MIN_INDEX] =
1149                                 cpu_to_le16((u16)data->auto_corr_ofdm);
1150         cmd.table[HD_AUTO_CORR32_X4_TH_ADD_MIN_MRC_INDEX] =
1151                                 cpu_to_le16((u16)data->auto_corr_ofdm_mrc);
1152         cmd.table[HD_AUTO_CORR32_X1_TH_ADD_MIN_INDEX] =
1153                                 cpu_to_le16((u16)data->auto_corr_ofdm_x1);
1154         cmd.table[HD_AUTO_CORR32_X1_TH_ADD_MIN_MRC_INDEX] =
1155                                 cpu_to_le16((u16)data->auto_corr_ofdm_mrc_x1);
1156
1157         cmd.table[HD_AUTO_CORR40_X4_TH_ADD_MIN_INDEX] =
1158                                 cpu_to_le16((u16)data->auto_corr_cck);
1159         cmd.table[HD_AUTO_CORR40_X4_TH_ADD_MIN_MRC_INDEX] =
1160                                 cpu_to_le16((u16)data->auto_corr_cck_mrc);
1161
1162         cmd.table[HD_MIN_ENERGY_CCK_DET_INDEX] =
1163                                 cpu_to_le16((u16)data->nrg_th_cck);
1164         cmd.table[HD_MIN_ENERGY_OFDM_DET_INDEX] =
1165                                 cpu_to_le16((u16)data->nrg_th_ofdm);
1166
1167         cmd.table[HD_BARKER_CORR_TH_ADD_MIN_INDEX] =
1168                                 __constant_cpu_to_le16(190);
1169         cmd.table[HD_BARKER_CORR_TH_ADD_MIN_MRC_INDEX] =
1170                                 __constant_cpu_to_le16(390);
1171         cmd.table[HD_OFDM_ENERGY_TH_IN_INDEX] =
1172                                 __constant_cpu_to_le16(62);
1173
1174         IWL_DEBUG_CALIB("ofdm: ac %u mrc %u x1 %u mrc_x1 %u thresh %u\n",
1175                         data->auto_corr_ofdm, data->auto_corr_ofdm_mrc,
1176                         data->auto_corr_ofdm_x1, data->auto_corr_ofdm_mrc_x1,
1177                         data->nrg_th_ofdm);
1178
1179         IWL_DEBUG_CALIB("cck: ac %u mrc %u thresh %u\n",
1180                         data->auto_corr_cck, data->auto_corr_cck_mrc,
1181                         data->nrg_th_cck);
1182
1183         /* Update uCode's "work" table, and copy it to DSP */
1184         cmd.control = SENSITIVITY_CMD_CONTROL_WORK_TABLE;
1185
1186         if (flags & CMD_ASYNC)
1187                 cmd_out.meta.u.callback = iwl4965_sensitivity_callback;
1188
1189         /* Don't send command to uCode if nothing has changed */
1190         if (!memcmp(&cmd.table[0], &(priv->sensitivity_tbl[0]),
1191                     sizeof(u16)*HD_TABLE_SIZE)) {
1192                 IWL_DEBUG_CALIB("No change in SENSITIVITY_CMD\n");
1193                 return 0;
1194         }
1195
1196         /* Copy table for comparison next time */
1197         memcpy(&(priv->sensitivity_tbl[0]), &(cmd.table[0]),
1198                sizeof(u16)*HD_TABLE_SIZE);
1199
1200         rc = iwl4965_send_cmd(priv, &cmd_out);
1201         if (!rc) {
1202                 IWL_DEBUG_CALIB("SENSITIVITY_CMD succeeded\n");
1203                 return rc;
1204         }
1205
1206         return 0;
1207 }
1208
1209 void iwl4965_init_sensitivity(struct iwl_priv *priv, u8 flags, u8 force)
1210 {
1211         int rc = 0;
1212         int i;
1213         struct iwl4965_sensitivity_data *data = NULL;
1214
1215         IWL_DEBUG_CALIB("Start iwl4965_init_sensitivity\n");
1216
1217         if (force)
1218                 memset(&(priv->sensitivity_tbl[0]), 0,
1219                         sizeof(u16)*HD_TABLE_SIZE);
1220
1221         /* Clear driver's sensitivity algo data */
1222         data = &(priv->sensitivity_data);
1223         memset(data, 0, sizeof(struct iwl4965_sensitivity_data));
1224
1225         data->num_in_cck_no_fa = 0;
1226         data->nrg_curr_state = IWL_FA_TOO_MANY;
1227         data->nrg_prev_state = IWL_FA_TOO_MANY;
1228         data->nrg_silence_ref = 0;
1229         data->nrg_silence_idx = 0;
1230         data->nrg_energy_idx = 0;
1231
1232         for (i = 0; i < 10; i++)
1233                 data->nrg_value[i] = 0;
1234
1235         for (i = 0; i < NRG_NUM_PREV_STAT_L; i++)
1236                 data->nrg_silence_rssi[i] = 0;
1237
1238         data->auto_corr_ofdm = 90;
1239         data->auto_corr_ofdm_mrc = 170;
1240         data->auto_corr_ofdm_x1  = 105;
1241         data->auto_corr_ofdm_mrc_x1 = 220;
1242         data->auto_corr_cck = AUTO_CORR_CCK_MIN_VAL_DEF;
1243         data->auto_corr_cck_mrc = 200;
1244         data->nrg_th_cck = 100;
1245         data->nrg_th_ofdm = 100;
1246
1247         data->last_bad_plcp_cnt_ofdm = 0;
1248         data->last_fa_cnt_ofdm = 0;
1249         data->last_bad_plcp_cnt_cck = 0;
1250         data->last_fa_cnt_cck = 0;
1251
1252         /* Clear prior Sensitivity command data to force send to uCode */
1253         if (force)
1254                 memset(&(priv->sensitivity_tbl[0]), 0,
1255                     sizeof(u16)*HD_TABLE_SIZE);
1256
1257         rc |= iwl4965_sensitivity_write(priv, flags);
1258         IWL_DEBUG_CALIB("<<return 0x%X\n", rc);
1259
1260         return;
1261 }
1262
1263
1264 /* Reset differential Rx gains in NIC to prepare for chain noise calibration.
1265  * Called after every association, but this runs only once!
1266  *  ... once chain noise is calibrated the first time, it's good forever.  */
1267 void iwl4965_chain_noise_reset(struct iwl_priv *priv)
1268 {
1269         struct iwl4965_chain_noise_data *data = NULL;
1270         int rc = 0;
1271
1272         data = &(priv->chain_noise_data);
1273         if ((data->state == IWL_CHAIN_NOISE_ALIVE) && iwl4965_is_associated(priv)) {
1274                 struct iwl4965_calibration_cmd cmd;
1275
1276                 memset(&cmd, 0, sizeof(cmd));
1277                 cmd.opCode = PHY_CALIBRATE_DIFF_GAIN_CMD;
1278                 cmd.diff_gain_a = 0;
1279                 cmd.diff_gain_b = 0;
1280                 cmd.diff_gain_c = 0;
1281                 rc = iwl4965_send_cmd_pdu(priv, REPLY_PHY_CALIBRATION_CMD,
1282                                  sizeof(cmd), &cmd);
1283                 msleep(4);
1284                 data->state = IWL_CHAIN_NOISE_ACCUMULATE;
1285                 IWL_DEBUG_CALIB("Run chain_noise_calibrate\n");
1286         }
1287         return;
1288 }
1289
1290 /*
1291  * Accumulate 20 beacons of signal and noise statistics for each of
1292  *   3 receivers/antennas/rx-chains, then figure out:
1293  * 1)  Which antennas are connected.
1294  * 2)  Differential rx gain settings to balance the 3 receivers.
1295  */
1296 static void iwl4965_noise_calibration(struct iwl_priv *priv,
1297                                       struct iwl4965_notif_statistics *stat_resp)
1298 {
1299         struct iwl4965_chain_noise_data *data = NULL;
1300         int rc = 0;
1301
1302         u32 chain_noise_a;
1303         u32 chain_noise_b;
1304         u32 chain_noise_c;
1305         u32 chain_sig_a;
1306         u32 chain_sig_b;
1307         u32 chain_sig_c;
1308         u32 average_sig[NUM_RX_CHAINS] = {INITIALIZATION_VALUE};
1309         u32 average_noise[NUM_RX_CHAINS] = {INITIALIZATION_VALUE};
1310         u32 max_average_sig;
1311         u16 max_average_sig_antenna_i;
1312         u32 min_average_noise = MIN_AVERAGE_NOISE_MAX_VALUE;
1313         u16 min_average_noise_antenna_i = INITIALIZATION_VALUE;
1314         u16 i = 0;
1315         u16 chan_num = INITIALIZATION_VALUE;
1316         u32 band = INITIALIZATION_VALUE;
1317         u32 active_chains = 0;
1318         unsigned long flags;
1319         struct statistics_rx_non_phy *rx_info = &(stat_resp->rx.general);
1320
1321         data = &(priv->chain_noise_data);
1322
1323         /* Accumulate just the first 20 beacons after the first association,
1324          *   then we're done forever. */
1325         if (data->state != IWL_CHAIN_NOISE_ACCUMULATE) {
1326                 if (data->state == IWL_CHAIN_NOISE_ALIVE)
1327                         IWL_DEBUG_CALIB("Wait for noise calib reset\n");
1328                 return;
1329         }
1330
1331         spin_lock_irqsave(&priv->lock, flags);
1332         if (rx_info->interference_data_flag != INTERFERENCE_DATA_AVAILABLE) {
1333                 IWL_DEBUG_CALIB(" << Interference data unavailable\n");
1334                 spin_unlock_irqrestore(&priv->lock, flags);
1335                 return;
1336         }
1337
1338         band = (priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK) ? 0 : 1;
1339         chan_num = le16_to_cpu(priv->staging_rxon.channel);
1340
1341         /* Make sure we accumulate data for just the associated channel
1342          *   (even if scanning). */
1343         if ((chan_num != (le32_to_cpu(stat_resp->flag) >> 16)) ||
1344             ((STATISTICS_REPLY_FLG_BAND_24G_MSK ==
1345              (stat_resp->flag & STATISTICS_REPLY_FLG_BAND_24G_MSK)) && band)) {
1346                 IWL_DEBUG_CALIB("Stats not from chan=%d, band=%d\n",
1347                                 chan_num, band);
1348                 spin_unlock_irqrestore(&priv->lock, flags);
1349                 return;
1350         }
1351
1352         /* Accumulate beacon statistics values across 20 beacons */
1353         chain_noise_a = le32_to_cpu(rx_info->beacon_silence_rssi_a) &
1354                                 IN_BAND_FILTER;
1355         chain_noise_b = le32_to_cpu(rx_info->beacon_silence_rssi_b) &
1356                                 IN_BAND_FILTER;
1357         chain_noise_c = le32_to_cpu(rx_info->beacon_silence_rssi_c) &
1358                                 IN_BAND_FILTER;
1359
1360         chain_sig_a = le32_to_cpu(rx_info->beacon_rssi_a) & IN_BAND_FILTER;
1361         chain_sig_b = le32_to_cpu(rx_info->beacon_rssi_b) & IN_BAND_FILTER;
1362         chain_sig_c = le32_to_cpu(rx_info->beacon_rssi_c) & IN_BAND_FILTER;
1363
1364         spin_unlock_irqrestore(&priv->lock, flags);
1365
1366         data->beacon_count++;
1367
1368         data->chain_noise_a = (chain_noise_a + data->chain_noise_a);
1369         data->chain_noise_b = (chain_noise_b + data->chain_noise_b);
1370         data->chain_noise_c = (chain_noise_c + data->chain_noise_c);
1371
1372         data->chain_signal_a = (chain_sig_a + data->chain_signal_a);
1373         data->chain_signal_b = (chain_sig_b + data->chain_signal_b);
1374         data->chain_signal_c = (chain_sig_c + data->chain_signal_c);
1375
1376         IWL_DEBUG_CALIB("chan=%d, band=%d, beacon=%d\n", chan_num, band,
1377                         data->beacon_count);
1378         IWL_DEBUG_CALIB("chain_sig: a %d b %d c %d\n",
1379                         chain_sig_a, chain_sig_b, chain_sig_c);
1380         IWL_DEBUG_CALIB("chain_noise: a %d b %d c %d\n",
1381                         chain_noise_a, chain_noise_b, chain_noise_c);
1382
1383         /* If this is the 20th beacon, determine:
1384          * 1)  Disconnected antennas (using signal strengths)
1385          * 2)  Differential gain (using silence noise) to balance receivers */
1386         if (data->beacon_count == CAL_NUM_OF_BEACONS) {
1387
1388                 /* Analyze signal for disconnected antenna */
1389                 average_sig[0] = (data->chain_signal_a) / CAL_NUM_OF_BEACONS;
1390                 average_sig[1] = (data->chain_signal_b) / CAL_NUM_OF_BEACONS;
1391                 average_sig[2] = (data->chain_signal_c) / CAL_NUM_OF_BEACONS;
1392
1393                 if (average_sig[0] >= average_sig[1]) {
1394                         max_average_sig = average_sig[0];
1395                         max_average_sig_antenna_i = 0;
1396                         active_chains = (1 << max_average_sig_antenna_i);
1397                 } else {
1398                         max_average_sig = average_sig[1];
1399                         max_average_sig_antenna_i = 1;
1400                         active_chains = (1 << max_average_sig_antenna_i);
1401                 }
1402
1403                 if (average_sig[2] >= max_average_sig) {
1404                         max_average_sig = average_sig[2];
1405                         max_average_sig_antenna_i = 2;
1406                         active_chains = (1 << max_average_sig_antenna_i);
1407                 }
1408
1409                 IWL_DEBUG_CALIB("average_sig: a %d b %d c %d\n",
1410                              average_sig[0], average_sig[1], average_sig[2]);
1411                 IWL_DEBUG_CALIB("max_average_sig = %d, antenna %d\n",
1412                              max_average_sig, max_average_sig_antenna_i);
1413
1414                 /* Compare signal strengths for all 3 receivers. */
1415                 for (i = 0; i < NUM_RX_CHAINS; i++) {
1416                         if (i != max_average_sig_antenna_i) {
1417                                 s32 rssi_delta = (max_average_sig -
1418                                                   average_sig[i]);
1419
1420                                 /* If signal is very weak, compared with
1421                                  * strongest, mark it as disconnected. */
1422                                 if (rssi_delta > MAXIMUM_ALLOWED_PATHLOSS)
1423                                         data->disconn_array[i] = 1;
1424                                 else
1425                                         active_chains |= (1 << i);
1426                         IWL_DEBUG_CALIB("i = %d  rssiDelta = %d  "
1427                                      "disconn_array[i] = %d\n",
1428                                      i, rssi_delta, data->disconn_array[i]);
1429                         }
1430                 }
1431
1432                 /*If both chains A & B are disconnected -
1433                  * connect B and leave A as is */
1434                 if (data->disconn_array[CHAIN_A] &&
1435                     data->disconn_array[CHAIN_B]) {
1436                         data->disconn_array[CHAIN_B] = 0;
1437                         active_chains |= (1 << CHAIN_B);
1438                         IWL_DEBUG_CALIB("both A & B chains are disconnected! "
1439                                      "W/A - declare B as connected\n");
1440                 }
1441
1442                 IWL_DEBUG_CALIB("active_chains (bitwise) = 0x%x\n",
1443                                 active_chains);
1444
1445                 /* Save for use within RXON, TX, SCAN commands, etc. */
1446                 priv->valid_antenna = active_chains;
1447
1448                 /* Analyze noise for rx balance */
1449                 average_noise[0] = ((data->chain_noise_a)/CAL_NUM_OF_BEACONS);
1450                 average_noise[1] = ((data->chain_noise_b)/CAL_NUM_OF_BEACONS);
1451                 average_noise[2] = ((data->chain_noise_c)/CAL_NUM_OF_BEACONS);
1452
1453                 for (i = 0; i < NUM_RX_CHAINS; i++) {
1454                         if (!(data->disconn_array[i]) &&
1455                            (average_noise[i] <= min_average_noise)) {
1456                                 /* This means that chain i is active and has
1457                                  * lower noise values so far: */
1458                                 min_average_noise = average_noise[i];
1459                                 min_average_noise_antenna_i = i;
1460                         }
1461                 }
1462
1463                 data->delta_gain_code[min_average_noise_antenna_i] = 0;
1464
1465                 IWL_DEBUG_CALIB("average_noise: a %d b %d c %d\n",
1466                                 average_noise[0], average_noise[1],
1467                                 average_noise[2]);
1468
1469                 IWL_DEBUG_CALIB("min_average_noise = %d, antenna %d\n",
1470                                 min_average_noise, min_average_noise_antenna_i);
1471
1472                 for (i = 0; i < NUM_RX_CHAINS; i++) {
1473                         s32 delta_g = 0;
1474
1475                         if (!(data->disconn_array[i]) &&
1476                             (data->delta_gain_code[i] ==
1477                              CHAIN_NOISE_DELTA_GAIN_INIT_VAL)) {
1478                                 delta_g = average_noise[i] - min_average_noise;
1479                                 data->delta_gain_code[i] = (u8)((delta_g *
1480                                                                     10) / 15);
1481                                 if (CHAIN_NOISE_MAX_DELTA_GAIN_CODE <
1482                                    data->delta_gain_code[i])
1483                                         data->delta_gain_code[i] =
1484                                           CHAIN_NOISE_MAX_DELTA_GAIN_CODE;
1485
1486                                 data->delta_gain_code[i] =
1487                                         (data->delta_gain_code[i] | (1 << 2));
1488                         } else
1489                                 data->delta_gain_code[i] = 0;
1490                 }
1491                 IWL_DEBUG_CALIB("delta_gain_codes: a %d b %d c %d\n",
1492                              data->delta_gain_code[0],
1493                              data->delta_gain_code[1],
1494                              data->delta_gain_code[2]);
1495
1496                 /* Differential gain gets sent to uCode only once */
1497                 if (!data->radio_write) {
1498                         struct iwl4965_calibration_cmd cmd;
1499                         data->radio_write = 1;
1500
1501                         memset(&cmd, 0, sizeof(cmd));
1502                         cmd.opCode = PHY_CALIBRATE_DIFF_GAIN_CMD;
1503                         cmd.diff_gain_a = data->delta_gain_code[0];
1504                         cmd.diff_gain_b = data->delta_gain_code[1];
1505                         cmd.diff_gain_c = data->delta_gain_code[2];
1506                         rc = iwl4965_send_cmd_pdu(priv, REPLY_PHY_CALIBRATION_CMD,
1507                                               sizeof(cmd), &cmd);
1508                         if (rc)
1509                                 IWL_DEBUG_CALIB("fail sending cmd "
1510                                              "REPLY_PHY_CALIBRATION_CMD \n");
1511
1512                         /* TODO we might want recalculate
1513                          * rx_chain in rxon cmd */
1514
1515                         /* Mark so we run this algo only once! */
1516                         data->state = IWL_CHAIN_NOISE_CALIBRATED;
1517                 }
1518                 data->chain_noise_a = 0;
1519                 data->chain_noise_b = 0;
1520                 data->chain_noise_c = 0;
1521                 data->chain_signal_a = 0;
1522                 data->chain_signal_b = 0;
1523                 data->chain_signal_c = 0;
1524                 data->beacon_count = 0;
1525         }
1526         return;
1527 }
1528
1529 static void iwl4965_sensitivity_calibration(struct iwl_priv *priv,
1530                                             struct iwl4965_notif_statistics *resp)
1531 {
1532         int rc = 0;
1533         u32 rx_enable_time;
1534         u32 fa_cck;
1535         u32 fa_ofdm;
1536         u32 bad_plcp_cck;
1537         u32 bad_plcp_ofdm;
1538         u32 norm_fa_ofdm;
1539         u32 norm_fa_cck;
1540         struct iwl4965_sensitivity_data *data = NULL;
1541         struct statistics_rx_non_phy *rx_info = &(resp->rx.general);
1542         struct statistics_rx *statistics = &(resp->rx);
1543         unsigned long flags;
1544         struct statistics_general_data statis;
1545
1546         data = &(priv->sensitivity_data);
1547
1548         if (!iwl4965_is_associated(priv)) {
1549                 IWL_DEBUG_CALIB("<< - not associated\n");
1550                 return;
1551         }
1552
1553         spin_lock_irqsave(&priv->lock, flags);
1554         if (rx_info->interference_data_flag != INTERFERENCE_DATA_AVAILABLE) {
1555                 IWL_DEBUG_CALIB("<< invalid data.\n");
1556                 spin_unlock_irqrestore(&priv->lock, flags);
1557                 return;
1558         }
1559
1560         /* Extract Statistics: */
1561         rx_enable_time = le32_to_cpu(rx_info->channel_load);
1562         fa_cck = le32_to_cpu(statistics->cck.false_alarm_cnt);
1563         fa_ofdm = le32_to_cpu(statistics->ofdm.false_alarm_cnt);
1564         bad_plcp_cck = le32_to_cpu(statistics->cck.plcp_err);
1565         bad_plcp_ofdm = le32_to_cpu(statistics->ofdm.plcp_err);
1566
1567         statis.beacon_silence_rssi_a =
1568                         le32_to_cpu(statistics->general.beacon_silence_rssi_a);
1569         statis.beacon_silence_rssi_b =
1570                         le32_to_cpu(statistics->general.beacon_silence_rssi_b);
1571         statis.beacon_silence_rssi_c =
1572                         le32_to_cpu(statistics->general.beacon_silence_rssi_c);
1573         statis.beacon_energy_a =
1574                         le32_to_cpu(statistics->general.beacon_energy_a);
1575         statis.beacon_energy_b =
1576                         le32_to_cpu(statistics->general.beacon_energy_b);
1577         statis.beacon_energy_c =
1578                         le32_to_cpu(statistics->general.beacon_energy_c);
1579
1580         spin_unlock_irqrestore(&priv->lock, flags);
1581
1582         IWL_DEBUG_CALIB("rx_enable_time = %u usecs\n", rx_enable_time);
1583
1584         if (!rx_enable_time) {
1585                 IWL_DEBUG_CALIB("<< RX Enable Time == 0! \n");
1586                 return;
1587         }
1588
1589         /* These statistics increase monotonically, and do not reset
1590          *   at each beacon.  Calculate difference from last value, or just
1591          *   use the new statistics value if it has reset or wrapped around. */
1592         if (data->last_bad_plcp_cnt_cck > bad_plcp_cck)
1593                 data->last_bad_plcp_cnt_cck = bad_plcp_cck;
1594         else {
1595                 bad_plcp_cck -= data->last_bad_plcp_cnt_cck;
1596                 data->last_bad_plcp_cnt_cck += bad_plcp_cck;
1597         }
1598
1599         if (data->last_bad_plcp_cnt_ofdm > bad_plcp_ofdm)
1600                 data->last_bad_plcp_cnt_ofdm = bad_plcp_ofdm;
1601         else {
1602                 bad_plcp_ofdm -= data->last_bad_plcp_cnt_ofdm;
1603                 data->last_bad_plcp_cnt_ofdm += bad_plcp_ofdm;
1604         }
1605
1606         if (data->last_fa_cnt_ofdm > fa_ofdm)
1607                 data->last_fa_cnt_ofdm = fa_ofdm;
1608         else {
1609                 fa_ofdm -= data->last_fa_cnt_ofdm;
1610                 data->last_fa_cnt_ofdm += fa_ofdm;
1611         }
1612
1613         if (data->last_fa_cnt_cck > fa_cck)
1614                 data->last_fa_cnt_cck = fa_cck;
1615         else {
1616                 fa_cck -= data->last_fa_cnt_cck;
1617                 data->last_fa_cnt_cck += fa_cck;
1618         }
1619
1620         /* Total aborted signal locks */
1621         norm_fa_ofdm = fa_ofdm + bad_plcp_ofdm;
1622         norm_fa_cck = fa_cck + bad_plcp_cck;
1623
1624         IWL_DEBUG_CALIB("cck: fa %u badp %u  ofdm: fa %u badp %u\n", fa_cck,
1625                         bad_plcp_cck, fa_ofdm, bad_plcp_ofdm);
1626
1627         iwl4965_sens_auto_corr_ofdm(priv, norm_fa_ofdm, rx_enable_time);
1628         iwl4965_sens_energy_cck(priv, norm_fa_cck, rx_enable_time, &statis);
1629         rc |= iwl4965_sensitivity_write(priv, CMD_ASYNC);
1630
1631         return;
1632 }
1633
1634 static void iwl4965_bg_sensitivity_work(struct work_struct *work)
1635 {
1636         struct iwl_priv *priv = container_of(work, struct iwl_priv,
1637                         sensitivity_work);
1638
1639         mutex_lock(&priv->mutex);
1640
1641         if (test_bit(STATUS_EXIT_PENDING, &priv->status) ||
1642             test_bit(STATUS_SCANNING, &priv->status)) {
1643                 mutex_unlock(&priv->mutex);
1644                 return;
1645         }
1646
1647         if (priv->start_calib) {
1648                 iwl4965_noise_calibration(priv, &priv->statistics);
1649
1650                 if (priv->sensitivity_data.state ==
1651                                         IWL_SENS_CALIB_NEED_REINIT) {
1652                         iwl4965_init_sensitivity(priv, CMD_ASYNC, 0);
1653                         priv->sensitivity_data.state = IWL_SENS_CALIB_ALLOWED;
1654                 } else
1655                         iwl4965_sensitivity_calibration(priv,
1656                                         &priv->statistics);
1657         }
1658
1659         mutex_unlock(&priv->mutex);
1660         return;
1661 }
1662 #endif /*CONFIG_IWL4965_SENSITIVITY*/
1663
1664 static void iwl4965_bg_txpower_work(struct work_struct *work)
1665 {
1666         struct iwl_priv *priv = container_of(work, struct iwl_priv,
1667                         txpower_work);
1668
1669         /* If a scan happened to start before we got here
1670          * then just return; the statistics notification will
1671          * kick off another scheduled work to compensate for
1672          * any temperature delta we missed here. */
1673         if (test_bit(STATUS_EXIT_PENDING, &priv->status) ||
1674             test_bit(STATUS_SCANNING, &priv->status))
1675                 return;
1676
1677         mutex_lock(&priv->mutex);
1678
1679         /* Regardless of if we are assocaited, we must reconfigure the
1680          * TX power since frames can be sent on non-radar channels while
1681          * not associated */
1682         iwl4965_hw_reg_send_txpower(priv);
1683
1684         /* Update last_temperature to keep is_calib_needed from running
1685          * when it isn't needed... */
1686         priv->last_temperature = priv->temperature;
1687
1688         mutex_unlock(&priv->mutex);
1689 }
1690
1691 /*
1692  * Acquire priv->lock before calling this function !
1693  */
1694 static void iwl4965_set_wr_ptrs(struct iwl_priv *priv, int txq_id, u32 index)
1695 {
1696         iwl4965_write_direct32(priv, HBUS_TARG_WRPTR,
1697                              (index & 0xff) | (txq_id << 8));
1698         iwl4965_write_prph(priv, KDR_SCD_QUEUE_RDPTR(txq_id), index);
1699 }
1700
1701 /**
1702  * iwl4965_tx_queue_set_status - (optionally) start Tx/Cmd queue
1703  * @tx_fifo_id: Tx DMA/FIFO channel (range 0-7) that the queue will feed
1704  * @scd_retry: (1) Indicates queue will be used in aggregation mode
1705  *
1706  * NOTE:  Acquire priv->lock before calling this function !
1707  */
1708 static void iwl4965_tx_queue_set_status(struct iwl_priv *priv,
1709                                         struct iwl4965_tx_queue *txq,
1710                                         int tx_fifo_id, int scd_retry)
1711 {
1712         int txq_id = txq->q.id;
1713
1714         /* Find out whether to activate Tx queue */
1715         int active = test_bit(txq_id, &priv->txq_ctx_active_msk)?1:0;
1716
1717         /* Set up and activate */
1718         iwl4965_write_prph(priv, KDR_SCD_QUEUE_STATUS_BITS(txq_id),
1719                                  (active << SCD_QUEUE_STTS_REG_POS_ACTIVE) |
1720                                  (tx_fifo_id << SCD_QUEUE_STTS_REG_POS_TXF) |
1721                                  (scd_retry << SCD_QUEUE_STTS_REG_POS_WSL) |
1722                                  (scd_retry << SCD_QUEUE_STTS_REG_POS_SCD_ACK) |
1723                                  SCD_QUEUE_STTS_REG_MSK);
1724
1725         txq->sched_retry = scd_retry;
1726
1727         IWL_DEBUG_INFO("%s %s Queue %d on AC %d\n",
1728                        active ? "Activate" : "Deactivate",
1729                        scd_retry ? "BA" : "AC", txq_id, tx_fifo_id);
1730 }
1731
1732 static const u16 default_queue_to_tx_fifo[] = {
1733         IWL_TX_FIFO_AC3,
1734         IWL_TX_FIFO_AC2,
1735         IWL_TX_FIFO_AC1,
1736         IWL_TX_FIFO_AC0,
1737         IWL_CMD_FIFO_NUM,
1738         IWL_TX_FIFO_HCCA_1,
1739         IWL_TX_FIFO_HCCA_2
1740 };
1741
1742 static inline void iwl4965_txq_ctx_activate(struct iwl_priv *priv, int txq_id)
1743 {
1744         set_bit(txq_id, &priv->txq_ctx_active_msk);
1745 }
1746
1747 static inline void iwl4965_txq_ctx_deactivate(struct iwl_priv *priv, int txq_id)
1748 {
1749         clear_bit(txq_id, &priv->txq_ctx_active_msk);
1750 }
1751
1752 int iwl4965_alive_notify(struct iwl_priv *priv)
1753 {
1754         u32 a;
1755         int i = 0;
1756         unsigned long flags;
1757         int rc;
1758
1759         spin_lock_irqsave(&priv->lock, flags);
1760
1761 #ifdef CONFIG_IWL4965_SENSITIVITY
1762         memset(&(priv->sensitivity_data), 0,
1763                sizeof(struct iwl4965_sensitivity_data));
1764         memset(&(priv->chain_noise_data), 0,
1765                sizeof(struct iwl4965_chain_noise_data));
1766         for (i = 0; i < NUM_RX_CHAINS; i++)
1767                 priv->chain_noise_data.delta_gain_code[i] =
1768                                 CHAIN_NOISE_DELTA_GAIN_INIT_VAL;
1769 #endif /* CONFIG_IWL4965_SENSITIVITY*/
1770         rc = iwl4965_grab_nic_access(priv);
1771         if (rc) {
1772                 spin_unlock_irqrestore(&priv->lock, flags);
1773                 return rc;
1774         }
1775
1776         /* Clear 4965's internal Tx Scheduler data base */
1777         priv->scd_base_addr = iwl4965_read_prph(priv, KDR_SCD_SRAM_BASE_ADDR);
1778         a = priv->scd_base_addr + SCD_CONTEXT_DATA_OFFSET;
1779         for (; a < priv->scd_base_addr + SCD_TX_STTS_BITMAP_OFFSET; a += 4)
1780                 iwl4965_write_targ_mem(priv, a, 0);
1781         for (; a < priv->scd_base_addr + SCD_TRANSLATE_TBL_OFFSET; a += 4)
1782                 iwl4965_write_targ_mem(priv, a, 0);
1783         for (; a < sizeof(u16) * priv->hw_setting.max_txq_num; a += 4)
1784                 iwl4965_write_targ_mem(priv, a, 0);
1785
1786         /* Tel 4965 where to find Tx byte count tables */
1787         iwl4965_write_prph(priv, KDR_SCD_DRAM_BASE_ADDR,
1788                 (priv->hw_setting.shared_phys +
1789                  offsetof(struct iwl4965_shared, queues_byte_cnt_tbls)) >> 10);
1790
1791         /* Disable chain mode for all queues */
1792         iwl4965_write_prph(priv, KDR_SCD_QUEUECHAIN_SEL, 0);
1793
1794         /* Initialize each Tx queue (including the command queue) */
1795         for (i = 0; i < priv->hw_setting.max_txq_num; i++) {
1796
1797                 /* TFD circular buffer read/write indexes */
1798                 iwl4965_write_prph(priv, KDR_SCD_QUEUE_RDPTR(i), 0);
1799                 iwl4965_write_direct32(priv, HBUS_TARG_WRPTR, 0 | (i << 8));
1800
1801                 /* Max Tx Window size for Scheduler-ACK mode */
1802                 iwl4965_write_targ_mem(priv, priv->scd_base_addr +
1803                                         SCD_CONTEXT_QUEUE_OFFSET(i),
1804                                         (SCD_WIN_SIZE <<
1805                                         SCD_QUEUE_CTX_REG1_WIN_SIZE_POS) &
1806                                         SCD_QUEUE_CTX_REG1_WIN_SIZE_MSK);
1807
1808                 /* Frame limit */
1809                 iwl4965_write_targ_mem(priv, priv->scd_base_addr +
1810                                         SCD_CONTEXT_QUEUE_OFFSET(i) +
1811                                         sizeof(u32),
1812                                         (SCD_FRAME_LIMIT <<
1813                                         SCD_QUEUE_CTX_REG2_FRAME_LIMIT_POS) &
1814                                         SCD_QUEUE_CTX_REG2_FRAME_LIMIT_MSK);
1815
1816         }
1817         iwl4965_write_prph(priv, KDR_SCD_INTERRUPT_MASK,
1818                                  (1 << priv->hw_setting.max_txq_num) - 1);
1819
1820         /* Activate all Tx DMA/FIFO channels */
1821         iwl4965_write_prph(priv, KDR_SCD_TXFACT,
1822                                  SCD_TXFACT_REG_TXFIFO_MASK(0, 7));
1823
1824         iwl4965_set_wr_ptrs(priv, IWL_CMD_QUEUE_NUM, 0);
1825
1826         /* Map each Tx/cmd queue to its corresponding fifo */
1827         for (i = 0; i < ARRAY_SIZE(default_queue_to_tx_fifo); i++) {
1828                 int ac = default_queue_to_tx_fifo[i];
1829                 iwl4965_txq_ctx_activate(priv, i);
1830                 iwl4965_tx_queue_set_status(priv, &priv->txq[i], ac, 0);
1831         }
1832
1833         iwl4965_release_nic_access(priv);
1834         spin_unlock_irqrestore(&priv->lock, flags);
1835
1836         return 0;
1837 }
1838
1839 /**
1840  * iwl4965_hw_set_hw_setting
1841  *
1842  * Called when initializing driver
1843  */
1844 int iwl4965_hw_set_hw_setting(struct iwl_priv *priv)
1845 {
1846         int ret = 0;
1847
1848         if ((iwl4965_mod_params.num_of_queues > IWL_MAX_NUM_QUEUES) ||
1849             (iwl4965_mod_params.num_of_queues < IWL_MIN_NUM_QUEUES)) {
1850                 IWL_ERROR("invalid queues_num, should be between %d and %d\n",
1851                           IWL_MIN_NUM_QUEUES, IWL_MAX_NUM_QUEUES);
1852                 ret = -EINVAL;
1853                 goto out;
1854         }
1855
1856         /* Allocate area for Tx byte count tables and Rx queue status */
1857         priv->hw_setting.shared_virt =
1858             pci_alloc_consistent(priv->pci_dev,
1859                                  sizeof(struct iwl4965_shared),
1860                                  &priv->hw_setting.shared_phys);
1861
1862         if (!priv->hw_setting.shared_virt) {
1863                 ret = -ENOMEM;
1864                 goto out;
1865         }
1866
1867         memset(priv->hw_setting.shared_virt, 0, sizeof(struct iwl4965_shared));
1868
1869         priv->hw_setting.max_txq_num = iwl4965_mod_params.num_of_queues;
1870         priv->hw_setting.tx_cmd_len = sizeof(struct iwl4965_tx_cmd);
1871         priv->hw_setting.max_rxq_size = RX_QUEUE_SIZE;
1872         priv->hw_setting.max_rxq_log = RX_QUEUE_SIZE_LOG;
1873         if (iwl4965_mod_params.amsdu_size_8K)
1874                 priv->hw_setting.rx_buf_size = IWL_RX_BUF_SIZE_8K;
1875         else
1876                 priv->hw_setting.rx_buf_size = IWL_RX_BUF_SIZE_4K;
1877         priv->hw_setting.max_pkt_size = priv->hw_setting.rx_buf_size - 256;
1878         priv->hw_setting.max_stations = IWL4965_STATION_COUNT;
1879         priv->hw_setting.bcast_sta_id = IWL4965_BROADCAST_ID;
1880
1881         priv->hw_setting.tx_ant_num = 2;
1882
1883 out:
1884         return ret;
1885 }
1886
1887 /**
1888  * iwl4965_hw_txq_ctx_free - Free TXQ Context
1889  *
1890  * Destroy all TX DMA queues and structures
1891  */
1892 void iwl4965_hw_txq_ctx_free(struct iwl_priv *priv)
1893 {
1894         int txq_id;
1895
1896         /* Tx queues */
1897         for (txq_id = 0; txq_id < priv->hw_setting.max_txq_num; txq_id++)
1898                 iwl4965_tx_queue_free(priv, &priv->txq[txq_id]);
1899
1900         /* Keep-warm buffer */
1901         iwl4965_kw_free(priv);
1902 }
1903
1904 /**
1905  * iwl4965_hw_txq_free_tfd - Free all chunks referenced by TFD [txq->q.read_ptr]
1906  *
1907  * Does NOT advance any TFD circular buffer read/write indexes
1908  * Does NOT free the TFD itself (which is within circular buffer)
1909  */
1910 int iwl4965_hw_txq_free_tfd(struct iwl_priv *priv, struct iwl4965_tx_queue *txq)
1911 {
1912         struct iwl4965_tfd_frame *bd_tmp = (struct iwl4965_tfd_frame *)&txq->bd[0];
1913         struct iwl4965_tfd_frame *bd = &bd_tmp[txq->q.read_ptr];
1914         struct pci_dev *dev = priv->pci_dev;
1915         int i;
1916         int counter = 0;
1917         int index, is_odd;
1918
1919         /* Host command buffers stay mapped in memory, nothing to clean */
1920         if (txq->q.id == IWL_CMD_QUEUE_NUM)
1921                 return 0;
1922
1923         /* Sanity check on number of chunks */
1924         counter = IWL_GET_BITS(*bd, num_tbs);
1925         if (counter > MAX_NUM_OF_TBS) {
1926                 IWL_ERROR("Too many chunks: %i\n", counter);
1927                 /* @todo issue fatal error, it is quite serious situation */
1928                 return 0;
1929         }
1930
1931         /* Unmap chunks, if any.
1932          * TFD info for odd chunks is different format than for even chunks. */
1933         for (i = 0; i < counter; i++) {
1934                 index = i / 2;
1935                 is_odd = i & 0x1;
1936
1937                 if (is_odd)
1938                         pci_unmap_single(
1939                                 dev,
1940                                 IWL_GET_BITS(bd->pa[index], tb2_addr_lo16) |
1941                                 (IWL_GET_BITS(bd->pa[index],
1942                                               tb2_addr_hi20) << 16),
1943                                 IWL_GET_BITS(bd->pa[index], tb2_len),
1944                                 PCI_DMA_TODEVICE);
1945
1946                 else if (i > 0)
1947                         pci_unmap_single(dev,
1948                                          le32_to_cpu(bd->pa[index].tb1_addr),
1949                                          IWL_GET_BITS(bd->pa[index], tb1_len),
1950                                          PCI_DMA_TODEVICE);
1951
1952                 /* Free SKB, if any, for this chunk */
1953                 if (txq->txb[txq->q.read_ptr].skb[i]) {
1954                         struct sk_buff *skb = txq->txb[txq->q.read_ptr].skb[i];
1955
1956                         dev_kfree_skb(skb);
1957                         txq->txb[txq->q.read_ptr].skb[i] = NULL;
1958                 }
1959         }
1960         return 0;
1961 }
1962
1963 int iwl4965_hw_reg_set_txpower(struct iwl_priv *priv, s8 power)
1964 {
1965         IWL_ERROR("TODO: Implement iwl4965_hw_reg_set_txpower!\n");
1966         return -EINVAL;
1967 }
1968
1969 static s32 iwl4965_math_div_round(s32 num, s32 denom, s32 *res)
1970 {
1971         s32 sign = 1;
1972
1973         if (num < 0) {
1974                 sign = -sign;
1975                 num = -num;
1976         }
1977         if (denom < 0) {
1978                 sign = -sign;
1979                 denom = -denom;
1980         }
1981         *res = 1;
1982         *res = ((num * 2 + denom) / (denom * 2)) * sign;
1983
1984         return 1;
1985 }
1986
1987 /**
1988  * iwl4965_get_voltage_compensation - Power supply voltage comp for txpower
1989  *
1990  * Determines power supply voltage compensation for txpower calculations.
1991  * Returns number of 1/2-dB steps to subtract from gain table index,
1992  * to compensate for difference between power supply voltage during
1993  * factory measurements, vs. current power supply voltage.
1994  *
1995  * Voltage indication is higher for lower voltage.
1996  * Lower voltage requires more gain (lower gain table index).
1997  */
1998 static s32 iwl4965_get_voltage_compensation(s32 eeprom_voltage,
1999                                             s32 current_voltage)
2000 {
2001         s32 comp = 0;
2002
2003         if ((TX_POWER_IWL_ILLEGAL_VOLTAGE == eeprom_voltage) ||
2004             (TX_POWER_IWL_ILLEGAL_VOLTAGE == current_voltage))
2005                 return 0;
2006
2007         iwl4965_math_div_round(current_voltage - eeprom_voltage,
2008                                TX_POWER_IWL_VOLTAGE_CODES_PER_03V, &comp);
2009
2010         if (current_voltage > eeprom_voltage)
2011                 comp *= 2;
2012         if ((comp < -2) || (comp > 2))
2013                 comp = 0;
2014
2015         return comp;
2016 }
2017
2018 static const struct iwl4965_channel_info *
2019 iwl4965_get_channel_txpower_info(struct iwl_priv *priv,
2020                                  enum ieee80211_band band, u16 channel)
2021 {
2022         const struct iwl4965_channel_info *ch_info;
2023
2024         ch_info = iwl4965_get_channel_info(priv, band, channel);
2025
2026         if (!is_channel_valid(ch_info))
2027                 return NULL;
2028
2029         return ch_info;
2030 }
2031
2032 static s32 iwl4965_get_tx_atten_grp(u16 channel)
2033 {
2034         if (channel >= CALIB_IWL_TX_ATTEN_GR5_FCH &&
2035             channel <= CALIB_IWL_TX_ATTEN_GR5_LCH)
2036                 return CALIB_CH_GROUP_5;
2037
2038         if (channel >= CALIB_IWL_TX_ATTEN_GR1_FCH &&
2039             channel <= CALIB_IWL_TX_ATTEN_GR1_LCH)
2040                 return CALIB_CH_GROUP_1;
2041
2042         if (channel >= CALIB_IWL_TX_ATTEN_GR2_FCH &&
2043             channel <= CALIB_IWL_TX_ATTEN_GR2_LCH)
2044                 return CALIB_CH_GROUP_2;
2045
2046         if (channel >= CALIB_IWL_TX_ATTEN_GR3_FCH &&
2047             channel <= CALIB_IWL_TX_ATTEN_GR3_LCH)
2048                 return CALIB_CH_GROUP_3;
2049
2050         if (channel >= CALIB_IWL_TX_ATTEN_GR4_FCH &&
2051             channel <= CALIB_IWL_TX_ATTEN_GR4_LCH)
2052                 return CALIB_CH_GROUP_4;
2053
2054         IWL_ERROR("Can't find txatten group for channel %d.\n", channel);
2055         return -1;
2056 }
2057
2058 static u32 iwl4965_get_sub_band(const struct iwl_priv *priv, u32 channel)
2059 {
2060         s32 b = -1;
2061
2062         for (b = 0; b < EEPROM_TX_POWER_BANDS; b++) {
2063                 if (priv->eeprom.calib_info.band_info[b].ch_from == 0)
2064                         continue;
2065
2066                 if ((channel >= priv->eeprom.calib_info.band_info[b].ch_from)
2067                     && (channel <= priv->eeprom.calib_info.band_info[b].ch_to))
2068                         break;
2069         }
2070
2071         return b;
2072 }
2073
2074 static s32 iwl4965_interpolate_value(s32 x, s32 x1, s32 y1, s32 x2, s32 y2)
2075 {
2076         s32 val;
2077
2078         if (x2 == x1)
2079                 return y1;
2080         else {
2081                 iwl4965_math_div_round((x2 - x) * (y1 - y2), (x2 - x1), &val);
2082                 return val + y2;
2083         }
2084 }
2085
2086 /**
2087  * iwl4965_interpolate_chan - Interpolate factory measurements for one channel
2088  *
2089  * Interpolates factory measurements from the two sample channels within a
2090  * sub-band, to apply to channel of interest.  Interpolation is proportional to
2091  * differences in channel frequencies, which is proportional to differences
2092  * in channel number.
2093  */
2094 static int iwl4965_interpolate_chan(struct iwl_priv *priv, u32 channel,
2095                                     struct iwl4965_eeprom_calib_ch_info *chan_info)
2096 {
2097         s32 s = -1;
2098         u32 c;
2099         u32 m;
2100         const struct iwl4965_eeprom_calib_measure *m1;
2101         const struct iwl4965_eeprom_calib_measure *m2;
2102         struct iwl4965_eeprom_calib_measure *omeas;
2103         u32 ch_i1;
2104         u32 ch_i2;
2105
2106         s = iwl4965_get_sub_band(priv, channel);
2107         if (s >= EEPROM_TX_POWER_BANDS) {
2108                 IWL_ERROR("Tx Power can not find channel %d ", channel);
2109                 return -1;
2110         }
2111
2112         ch_i1 = priv->eeprom.calib_info.band_info[s].ch1.ch_num;
2113         ch_i2 = priv->eeprom.calib_info.band_info[s].ch2.ch_num;
2114         chan_info->ch_num = (u8) channel;
2115
2116         IWL_DEBUG_TXPOWER("channel %d subband %d factory cal ch %d & %d\n",
2117                           channel, s, ch_i1, ch_i2);
2118
2119         for (c = 0; c < EEPROM_TX_POWER_TX_CHAINS; c++) {
2120                 for (m = 0; m < EEPROM_TX_POWER_MEASUREMENTS; m++) {
2121                         m1 = &(priv->eeprom.calib_info.band_info[s].ch1.
2122                                measurements[c][m]);
2123                         m2 = &(priv->eeprom.calib_info.band_info[s].ch2.
2124                                measurements[c][m]);
2125                         omeas = &(chan_info->measurements[c][m]);
2126
2127                         omeas->actual_pow =
2128                             (u8) iwl4965_interpolate_value(channel, ch_i1,
2129                                                            m1->actual_pow,
2130                                                            ch_i2,
2131                                                            m2->actual_pow);
2132                         omeas->gain_idx =
2133                             (u8) iwl4965_interpolate_value(channel, ch_i1,
2134                                                            m1->gain_idx, ch_i2,
2135                                                            m2->gain_idx);
2136                         omeas->temperature =
2137                             (u8) iwl4965_interpolate_value(channel, ch_i1,
2138                                                            m1->temperature,
2139                                                            ch_i2,
2140                                                            m2->temperature);
2141                         omeas->pa_det =
2142                             (s8) iwl4965_interpolate_value(channel, ch_i1,
2143                                                            m1->pa_det, ch_i2,
2144                                                            m2->pa_det);
2145
2146                         IWL_DEBUG_TXPOWER
2147                             ("chain %d meas %d AP1=%d AP2=%d AP=%d\n", c, m,
2148                              m1->actual_pow, m2->actual_pow, omeas->actual_pow);
2149                         IWL_DEBUG_TXPOWER
2150                             ("chain %d meas %d NI1=%d NI2=%d NI=%d\n", c, m,
2151                              m1->gain_idx, m2->gain_idx, omeas->gain_idx);
2152                         IWL_DEBUG_TXPOWER
2153                             ("chain %d meas %d PA1=%d PA2=%d PA=%d\n", c, m,
2154                              m1->pa_det, m2->pa_det, omeas->pa_det);
2155                         IWL_DEBUG_TXPOWER
2156                             ("chain %d meas %d  T1=%d  T2=%d  T=%d\n", c, m,
2157                              m1->temperature, m2->temperature,
2158                              omeas->temperature);
2159                 }
2160         }
2161
2162         return 0;
2163 }
2164
2165 /* bit-rate-dependent table to prevent Tx distortion, in half-dB units,
2166  * for OFDM 6, 12, 18, 24, 36, 48, 54, 60 MBit, and CCK all rates. */
2167 static s32 back_off_table[] = {
2168         10, 10, 10, 10, 10, 15, 17, 20, /* OFDM SISO 20 MHz */
2169         10, 10, 10, 10, 10, 15, 17, 20, /* OFDM MIMO 20 MHz */
2170         10, 10, 10, 10, 10, 15, 17, 20, /* OFDM SISO 40 MHz */
2171         10, 10, 10, 10, 10, 15, 17, 20, /* OFDM MIMO 40 MHz */
2172         10                      /* CCK */
2173 };
2174
2175 /* Thermal compensation values for txpower for various frequency ranges ...
2176  *   ratios from 3:1 to 4.5:1 of degrees (Celsius) per half-dB gain adjust */
2177 static struct iwl4965_txpower_comp_entry {
2178         s32 degrees_per_05db_a;
2179         s32 degrees_per_05db_a_denom;
2180 } tx_power_cmp_tble[CALIB_CH_GROUP_MAX] = {
2181         {9, 2},                 /* group 0 5.2, ch  34-43 */
2182         {4, 1},                 /* group 1 5.2, ch  44-70 */
2183         {4, 1},                 /* group 2 5.2, ch  71-124 */
2184         {4, 1},                 /* group 3 5.2, ch 125-200 */
2185         {3, 1}                  /* group 4 2.4, ch   all */
2186 };
2187
2188 static s32 get_min_power_index(s32 rate_power_index, u32 band)
2189 {
2190         if (!band) {
2191                 if ((rate_power_index & 7) <= 4)
2192                         return MIN_TX_GAIN_INDEX_52GHZ_EXT;
2193         }
2194         return MIN_TX_GAIN_INDEX;
2195 }
2196
2197 struct gain_entry {
2198         u8 dsp;
2199         u8 radio;
2200 };
2201
2202 static const struct gain_entry gain_table[2][108] = {
2203         /* 5.2GHz power gain index table */
2204         {
2205          {123, 0x3F},           /* highest txpower */
2206          {117, 0x3F},
2207          {110, 0x3F},
2208          {104, 0x3F},
2209          {98, 0x3F},
2210          {110, 0x3E},
2211          {104, 0x3E},
2212          {98, 0x3E},
2213          {110, 0x3D},
2214          {104, 0x3D},
2215          {98, 0x3D},
2216          {110, 0x3C},
2217          {104, 0x3C},
2218          {98, 0x3C},
2219          {110, 0x3B},
2220          {104, 0x3B},
2221          {98, 0x3B},
2222          {110, 0x3A},
2223          {104, 0x3A},
2224          {98, 0x3A},
2225          {110, 0x39},
2226          {104, 0x39},
2227          {98, 0x39},
2228          {110, 0x38},
2229          {104, 0x38},
2230          {98, 0x38},
2231          {110, 0x37},
2232          {104, 0x37},
2233          {98, 0x37},
2234          {110, 0x36},
2235          {104, 0x36},
2236          {98, 0x36},
2237          {110, 0x35},
2238          {104, 0x35},
2239          {98, 0x35},
2240          {110, 0x34},
2241          {104, 0x34},
2242          {98, 0x34},
2243          {110, 0x33},
2244          {104, 0x33},
2245          {98, 0x33},
2246          {110, 0x32},
2247          {104, 0x32},
2248          {98, 0x32},
2249          {110, 0x31},
2250          {104, 0x31},
2251          {98, 0x31},
2252          {110, 0x30},
2253          {104, 0x30},
2254          {98, 0x30},
2255          {110, 0x25},
2256          {104, 0x25},
2257          {98, 0x25},
2258          {110, 0x24},
2259          {104, 0x24},
2260          {98, 0x24},
2261          {110, 0x23},
2262          {104, 0x23},
2263          {98, 0x23},
2264          {110, 0x22},
2265          {104, 0x18},
2266          {98, 0x18},
2267          {110, 0x17},
2268          {104, 0x17},
2269          {98, 0x17},
2270          {110, 0x16},
2271          {104, 0x16},
2272          {98, 0x16},
2273          {110, 0x15},
2274          {104, 0x15},
2275          {98, 0x15},
2276          {110, 0x14},
2277          {104, 0x14},
2278          {98, 0x14},
2279          {110, 0x13},
2280          {104, 0x13},
2281          {98, 0x13},
2282          {110, 0x12},
2283          {104, 0x08},
2284          {98, 0x08},
2285          {110, 0x07},
2286          {104, 0x07},
2287          {98, 0x07},
2288          {110, 0x06},
2289          {104, 0x06},
2290          {98, 0x06},
2291          {110, 0x05},
2292          {104, 0x05},
2293          {98, 0x05},
2294          {110, 0x04},
2295          {104, 0x04},
2296          {98, 0x04},
2297          {110, 0x03},
2298          {104, 0x03},
2299          {98, 0x03},
2300          {110, 0x02},
2301          {104, 0x02},
2302          {98, 0x02},
2303          {110, 0x01},
2304          {104, 0x01},
2305          {98, 0x01},
2306          {110, 0x00},
2307          {104, 0x00},
2308          {98, 0x00},
2309          {93, 0x00},
2310          {88, 0x00},
2311          {83, 0x00},
2312          {78, 0x00},
2313          },
2314         /* 2.4GHz power gain index table */
2315         {
2316          {110, 0x3f},           /* highest txpower */
2317          {104, 0x3f},
2318          {98, 0x3f},
2319          {110, 0x3e},
2320          {104, 0x3e},
2321          {98, 0x3e},
2322          {110, 0x3d},
2323          {104, 0x3d},
2324          {98, 0x3d},
2325          {110, 0x3c},
2326          {104, 0x3c},
2327          {98, 0x3c},
2328          {110, 0x3b},
2329          {104, 0x3b},
2330          {98, 0x3b},
2331          {110, 0x3a},
2332          {104, 0x3a},
2333          {98, 0x3a},
2334          {110, 0x39},
2335          {104, 0x39},
2336          {98, 0x39},
2337          {110, 0x38},
2338          {104, 0x38},
2339          {98, 0x38},
2340          {110, 0x37},
2341          {104, 0x37},
2342          {98, 0x37},
2343          {110, 0x36},
2344          {104, 0x36},
2345          {98, 0x36},
2346          {110, 0x35},
2347          {104, 0x35},
2348          {98, 0x35},
2349          {110, 0x34},
2350          {104, 0x34},
2351          {98, 0x34},
2352          {110, 0x33},
2353          {104, 0x33},
2354          {98, 0x33},
2355          {110, 0x32},
2356          {104, 0x32},
2357          {98, 0x32},
2358          {110, 0x31},
2359          {104, 0x31},
2360          {98, 0x31},
2361          {110, 0x30},
2362          {104, 0x30},
2363          {98, 0x30},
2364          {110, 0x6},
2365          {104, 0x6},
2366          {98, 0x6},
2367          {110, 0x5},
2368          {104, 0x5},
2369          {98, 0x5},
2370          {110, 0x4},
2371          {104, 0x4},
2372          {98, 0x4},
2373          {110, 0x3},
2374          {104, 0x3},
2375          {98, 0x3},
2376          {110, 0x2},
2377          {104, 0x2},
2378          {98, 0x2},
2379          {110, 0x1},
2380          {104, 0x1},
2381          {98, 0x1},
2382          {110, 0x0},
2383          {104, 0x0},
2384          {98, 0x0},
2385          {97, 0},
2386          {96, 0},
2387          {95, 0},
2388          {94, 0},
2389          {93, 0},
2390          {92, 0},
2391          {91, 0},
2392          {90, 0},
2393          {89, 0},
2394          {88, 0},
2395          {87, 0},
2396          {86, 0},
2397          {85, 0},
2398          {84, 0},
2399          {83, 0},
2400          {82, 0},
2401          {81, 0},
2402          {80, 0},
2403          {79, 0},
2404          {78, 0},
2405          {77, 0},
2406          {76, 0},
2407          {75, 0},
2408          {74, 0},
2409          {73, 0},
2410          {72, 0},
2411          {71, 0},
2412          {70, 0},
2413          {69, 0},
2414          {68, 0},
2415          {67, 0},
2416          {66, 0},
2417          {65, 0},
2418          {64, 0},
2419          {63, 0},
2420          {62, 0},
2421          {61, 0},
2422          {60, 0},
2423          {59, 0},
2424          }
2425 };
2426
2427 static int iwl4965_fill_txpower_tbl(struct iwl_priv *priv, u8 band, u16 channel,
2428                                     u8 is_fat, u8 ctrl_chan_high,
2429                                     struct iwl4965_tx_power_db *tx_power_tbl)
2430 {
2431         u8 saturation_power;
2432         s32 target_power;
2433         s32 user_target_power;
2434         s32 power_limit;
2435         s32 current_temp;
2436         s32 reg_limit;
2437         s32 current_regulatory;
2438         s32 txatten_grp = CALIB_CH_GROUP_MAX;
2439         int i;
2440         int c;
2441         const struct iwl4965_channel_info *ch_info = NULL;
2442         struct iwl4965_eeprom_calib_ch_info ch_eeprom_info;
2443         const struct iwl4965_eeprom_calib_measure *measurement;
2444         s16 voltage;
2445         s32 init_voltage;
2446         s32 voltage_compensation;
2447         s32 degrees_per_05db_num;
2448         s32 degrees_per_05db_denom;
2449         s32 factory_temp;
2450         s32 temperature_comp[2];
2451         s32 factory_gain_index[2];
2452         s32 factory_actual_pwr[2];
2453         s32 power_index;
2454
2455         /* Sanity check requested level (dBm) */
2456         if (priv->user_txpower_limit < IWL_TX_POWER_TARGET_POWER_MIN) {
2457                 IWL_WARNING("Requested user TXPOWER %d below limit.\n",
2458                             priv->user_txpower_limit);
2459                 return -EINVAL;
2460         }
2461         if (priv->user_txpower_limit > IWL_TX_POWER_TARGET_POWER_MAX) {
2462                 IWL_WARNING("Requested user TXPOWER %d above limit.\n",
2463                             priv->user_txpower_limit);
2464                 return -EINVAL;
2465         }
2466
2467         /* user_txpower_limit is in dBm, convert to half-dBm (half-dB units
2468          *   are used for indexing into txpower table) */
2469         user_target_power = 2 * priv->user_txpower_limit;
2470
2471         /* Get current (RXON) channel, band, width */
2472         ch_info =
2473                 iwl4965_get_channel_txpower_info(priv, priv->band, channel);
2474
2475         IWL_DEBUG_TXPOWER("chan %d band %d is_fat %d\n", channel, band,
2476                           is_fat);
2477
2478         if (!ch_info)
2479                 return -EINVAL;
2480
2481         /* get txatten group, used to select 1) thermal txpower adjustment
2482          *   and 2) mimo txpower balance between Tx chains. */
2483         txatten_grp = iwl4965_get_tx_atten_grp(channel);
2484         if (txatten_grp < 0)
2485                 return -EINVAL;
2486
2487         IWL_DEBUG_TXPOWER("channel %d belongs to txatten group %d\n",
2488                           channel, txatten_grp);
2489
2490         if (is_fat) {
2491                 if (ctrl_chan_high)
2492                         channel -= 2;
2493                 else
2494                         channel += 2;
2495         }
2496
2497         /* hardware txpower limits ...
2498          * saturation (clipping distortion) txpowers are in half-dBm */
2499         if (band)
2500                 saturation_power = priv->eeprom.calib_info.saturation_power24;
2501         else
2502                 saturation_power = priv->eeprom.calib_info.saturation_power52;
2503
2504         if (saturation_power < IWL_TX_POWER_SATURATION_MIN ||
2505             saturation_power > IWL_TX_POWER_SATURATION_MAX) {
2506                 if (band)
2507                         saturation_power = IWL_TX_POWER_DEFAULT_SATURATION_24;
2508                 else
2509                         saturation_power = IWL_TX_POWER_DEFAULT_SATURATION_52;
2510         }
2511
2512         /* regulatory txpower limits ... reg_limit values are in half-dBm,
2513          *   max_power_avg values are in dBm, convert * 2 */
2514         if (is_fat)
2515                 reg_limit = ch_info->fat_max_power_avg * 2;
2516         else
2517                 reg_limit = ch_info->max_power_avg * 2;
2518
2519         if ((reg_limit < IWL_TX_POWER_REGULATORY_MIN) ||
2520             (reg_limit > IWL_TX_POWER_REGULATORY_MAX)) {
2521                 if (band)
2522                         reg_limit = IWL_TX_POWER_DEFAULT_REGULATORY_24;
2523                 else
2524                         reg_limit = IWL_TX_POWER_DEFAULT_REGULATORY_52;
2525         }
2526
2527         /* Interpolate txpower calibration values for this channel,
2528          *   based on factory calibration tests on spaced channels. */
2529         iwl4965_interpolate_chan(priv, channel, &ch_eeprom_info);
2530
2531         /* calculate tx gain adjustment based on power supply voltage */
2532         voltage = priv->eeprom.calib_info.voltage;
2533         init_voltage = (s32)le32_to_cpu(priv->card_alive_init.voltage);
2534         voltage_compensation =
2535             iwl4965_get_voltage_compensation(voltage, init_voltage);
2536
2537         IWL_DEBUG_TXPOWER("curr volt %d eeprom volt %d volt comp %d\n",
2538                           init_voltage,
2539                           voltage, voltage_compensation);
2540
2541         /* get current temperature (Celsius) */
2542         current_temp = max(priv->temperature, IWL_TX_POWER_TEMPERATURE_MIN);
2543         current_temp = min(priv->temperature, IWL_TX_POWER_TEMPERATURE_MAX);
2544         current_temp = KELVIN_TO_CELSIUS(current_temp);
2545
2546         /* select thermal txpower adjustment params, based on channel group
2547          *   (same frequency group used for mimo txatten adjustment) */
2548         degrees_per_05db_num =
2549             tx_power_cmp_tble[txatten_grp].degrees_per_05db_a;
2550         degrees_per_05db_denom =
2551             tx_power_cmp_tble[txatten_grp].degrees_per_05db_a_denom;
2552
2553         /* get per-chain txpower values from factory measurements */
2554         for (c = 0; c < 2; c++) {
2555                 measurement = &ch_eeprom_info.measurements[c][1];
2556
2557                 /* txgain adjustment (in half-dB steps) based on difference
2558                  *   between factory and current temperature */
2559                 factory_temp = measurement->temperature;
2560                 iwl4965_math_div_round((current_temp - factory_temp) *
2561                                        degrees_per_05db_denom,
2562                                        degrees_per_05db_num,
2563                                        &temperature_comp[c]);
2564
2565                 factory_gain_index[c] = measurement->gain_idx;
2566                 factory_actual_pwr[c] = measurement->actual_pow;
2567
2568                 IWL_DEBUG_TXPOWER("chain = %d\n", c);
2569                 IWL_DEBUG_TXPOWER("fctry tmp %d, "
2570                                   "curr tmp %d, comp %d steps\n",
2571                                   factory_temp, current_temp,
2572                                   temperature_comp[c]);
2573
2574                 IWL_DEBUG_TXPOWER("fctry idx %d, fctry pwr %d\n",
2575                                   factory_gain_index[c],
2576                                   factory_actual_pwr[c]);
2577         }
2578
2579         /* for each of 33 bit-rates (including 1 for CCK) */
2580         for (i = 0; i < POWER_TABLE_NUM_ENTRIES; i++) {
2581                 u8 is_mimo_rate;
2582                 union iwl4965_tx_power_dual_stream tx_power;
2583
2584                 /* for mimo, reduce each chain's txpower by half
2585                  * (3dB, 6 steps), so total output power is regulatory
2586                  * compliant. */
2587                 if (i & 0x8) {
2588                         current_regulatory = reg_limit -
2589                             IWL_TX_POWER_MIMO_REGULATORY_COMPENSATION;
2590                         is_mimo_rate = 1;
2591                 } else {
2592                         current_regulatory = reg_limit;
2593                         is_mimo_rate = 0;
2594                 }
2595
2596                 /* find txpower limit, either hardware or regulatory */
2597                 power_limit = saturation_power - back_off_table[i];
2598                 if (power_limit > current_regulatory)
2599                         power_limit = current_regulatory;
2600
2601                 /* reduce user's txpower request if necessary
2602                  * for this rate on this channel */
2603                 target_power = user_target_power;
2604                 if (target_power > power_limit)
2605                         target_power = power_limit;
2606
2607                 IWL_DEBUG_TXPOWER("rate %d sat %d reg %d usr %d tgt %d\n",
2608                                   i, saturation_power - back_off_table[i],
2609                                   current_regulatory, user_target_power,
2610                                   target_power);
2611
2612                 /* for each of 2 Tx chains (radio transmitters) */
2613                 for (c = 0; c < 2; c++) {
2614                         s32 atten_value;
2615
2616                         if (is_mimo_rate)
2617                                 atten_value =
2618                                     (s32)le32_to_cpu(priv->card_alive_init.
2619                                     tx_atten[txatten_grp][c]);
2620                         else
2621                                 atten_value = 0;
2622
2623                         /* calculate index; higher index means lower txpower */
2624                         power_index = (u8) (factory_gain_index[c] -
2625                                             (target_power -
2626                                              factory_actual_pwr[c]) -
2627                                             temperature_comp[c] -
2628                                             voltage_compensation +
2629                                             atten_value);
2630
2631 /*                      IWL_DEBUG_TXPOWER("calculated txpower index %d\n",
2632                                                 power_index); */
2633
2634                         if (power_index < get_min_power_index(i, band))
2635                                 power_index = get_min_power_index(i, band);
2636
2637                         /* adjust 5 GHz index to support negative indexes */
2638                         if (!band)
2639                                 power_index += 9;
2640
2641                         /* CCK, rate 32, reduce txpower for CCK */
2642                         if (i == POWER_TABLE_CCK_ENTRY)
2643                                 power_index +=
2644                                     IWL_TX_POWER_CCK_COMPENSATION_C_STEP;
2645
2646                         /* stay within the table! */
2647                         if (power_index > 107) {
2648                                 IWL_WARNING("txpower index %d > 107\n",
2649                                             power_index);
2650                                 power_index = 107;
2651                         }
2652                         if (power_index < 0) {
2653                                 IWL_WARNING("txpower index %d < 0\n",
2654                                             power_index);
2655                                 power_index = 0;
2656                         }
2657
2658                         /* fill txpower command for this rate/chain */
2659                         tx_power.s.radio_tx_gain[c] =
2660                                 gain_table[band][power_index].radio;
2661                         tx_power.s.dsp_predis_atten[c] =
2662                                 gain_table[band][power_index].dsp;
2663
2664                         IWL_DEBUG_TXPOWER("chain %d mimo %d index %d "
2665                                           "gain 0x%02x dsp %d\n",
2666                                           c, atten_value, power_index,
2667                                         tx_power.s.radio_tx_gain[c],
2668                                         tx_power.s.dsp_predis_atten[c]);
2669                 }/* for each chain */
2670
2671                 tx_power_tbl->power_tbl[i].dw = cpu_to_le32(tx_power.dw);
2672
2673         }/* for each rate */
2674
2675         return 0;
2676 }
2677
2678 /**
2679  * iwl4965_hw_reg_send_txpower - Configure the TXPOWER level user limit
2680  *
2681  * Uses the active RXON for channel, band, and characteristics (fat, high)
2682  * The power limit is taken from priv->user_txpower_limit.
2683  */
2684 int iwl4965_hw_reg_send_txpower(struct iwl_priv *priv)
2685 {
2686         struct iwl4965_txpowertable_cmd cmd = { 0 };
2687         int rc = 0;
2688         u8 band = 0;
2689         u8 is_fat = 0;
2690         u8 ctrl_chan_high = 0;
2691
2692         if (test_bit(STATUS_SCANNING, &priv->status)) {
2693                 /* If this gets hit a lot, switch it to a BUG() and catch
2694                  * the stack trace to find out who is calling this during
2695                  * a scan. */
2696                 IWL_WARNING("TX Power requested while scanning!\n");
2697                 return -EAGAIN;
2698         }
2699
2700         band = priv->band == IEEE80211_BAND_2GHZ;
2701
2702         is_fat =  is_fat_channel(priv->active_rxon.flags);
2703
2704         if (is_fat &&
2705             (priv->active_rxon.flags & RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK))
2706                 ctrl_chan_high = 1;
2707
2708         cmd.band = band;
2709         cmd.channel = priv->active_rxon.channel;
2710
2711         rc = iwl4965_fill_txpower_tbl(priv, band,
2712                                 le16_to_cpu(priv->active_rxon.channel),
2713                                 is_fat, ctrl_chan_high, &cmd.tx_power);
2714         if (rc)
2715                 return rc;
2716
2717         rc = iwl4965_send_cmd_pdu(priv, REPLY_TX_PWR_TABLE_CMD, sizeof(cmd), &cmd);
2718         return rc;
2719 }
2720
2721 int iwl4965_hw_channel_switch(struct iwl_priv *priv, u16 channel)
2722 {
2723         int rc;
2724         u8 band = 0;
2725         u8 is_fat = 0;
2726         u8 ctrl_chan_high = 0;
2727         struct iwl4965_channel_switch_cmd cmd = { 0 };
2728         const struct iwl4965_channel_info *ch_info;
2729
2730         band = priv->band == IEEE80211_BAND_2GHZ;
2731
2732         ch_info = iwl4965_get_channel_info(priv, priv->band, channel);
2733
2734         is_fat = is_fat_channel(priv->staging_rxon.flags);
2735
2736         if (is_fat &&
2737             (priv->active_rxon.flags & RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK))
2738                 ctrl_chan_high = 1;
2739
2740         cmd.band = band;
2741         cmd.expect_beacon = 0;
2742         cmd.channel = cpu_to_le16(channel);
2743         cmd.rxon_flags = priv->active_rxon.flags;
2744         cmd.rxon_filter_flags = priv->active_rxon.filter_flags;
2745         cmd.switch_time = cpu_to_le32(priv->ucode_beacon_time);
2746         if (ch_info)
2747                 cmd.expect_beacon = is_channel_radar(ch_info);
2748         else
2749                 cmd.expect_beacon = 1;
2750
2751         rc = iwl4965_fill_txpower_tbl(priv, band, channel, is_fat,
2752                                       ctrl_chan_high, &cmd.tx_power);
2753         if (rc) {
2754                 IWL_DEBUG_11H("error:%d  fill txpower_tbl\n", rc);
2755                 return rc;
2756         }
2757
2758         rc = iwl4965_send_cmd_pdu(priv, REPLY_CHANNEL_SWITCH, sizeof(cmd), &cmd);
2759         return rc;
2760 }
2761
2762 #define RTS_HCCA_RETRY_LIMIT            3
2763 #define RTS_DFAULT_RETRY_LIMIT          60
2764
2765 void iwl4965_hw_build_tx_cmd_rate(struct iwl_priv *priv,
2766                               struct iwl4965_cmd *cmd,
2767                               struct ieee80211_tx_control *ctrl,
2768                               struct ieee80211_hdr *hdr, int sta_id,
2769                               int is_hcca)
2770 {
2771         struct iwl4965_tx_cmd *tx = &cmd->cmd.tx;
2772         u8 rts_retry_limit = 0;
2773         u8 data_retry_limit = 0;
2774         u16 fc = le16_to_cpu(hdr->frame_control);
2775         u8 rate_plcp;
2776         u16 rate_flags = 0;
2777         int rate_idx = min(ctrl->tx_rate->hw_value & 0xffff, IWL_RATE_COUNT - 1);
2778
2779         rate_plcp = iwl4965_rates[rate_idx].plcp;
2780
2781         rts_retry_limit = (is_hcca) ?
2782             RTS_HCCA_RETRY_LIMIT : RTS_DFAULT_RETRY_LIMIT;
2783
2784         if ((rate_idx >= IWL_FIRST_CCK_RATE) && (rate_idx <= IWL_LAST_CCK_RATE))
2785                 rate_flags |= RATE_MCS_CCK_MSK;
2786
2787
2788         if (ieee80211_is_probe_response(fc)) {
2789                 data_retry_limit = 3;
2790                 if (data_retry_limit < rts_retry_limit)
2791                         rts_retry_limit = data_retry_limit;
2792         } else
2793                 data_retry_limit = IWL_DEFAULT_TX_RETRY;
2794
2795         if (priv->data_retry_limit != -1)
2796                 data_retry_limit = priv->data_retry_limit;
2797
2798
2799         if (ieee80211_is_data(fc)) {
2800                 tx->initial_rate_index = 0;
2801                 tx->tx_flags |= TX_CMD_FLG_STA_RATE_MSK;
2802         } else {
2803                 switch (fc & IEEE80211_FCTL_STYPE) {
2804                 case IEEE80211_STYPE_AUTH:
2805                 case IEEE80211_STYPE_DEAUTH:
2806                 case IEEE80211_STYPE_ASSOC_REQ:
2807                 case IEEE80211_STYPE_REASSOC_REQ:
2808                         if (tx->tx_flags & TX_CMD_FLG_RTS_MSK) {
2809                                 tx->tx_flags &= ~TX_CMD_FLG_RTS_MSK;
2810                                 tx->tx_flags |= TX_CMD_FLG_CTS_MSK;
2811                         }
2812                         break;
2813                 default:
2814                         break;
2815                 }
2816
2817                 /* Alternate between antenna A and B for successive frames */
2818                 if (priv->use_ant_b_for_management_frame) {
2819                         priv->use_ant_b_for_management_frame = 0;
2820                         rate_flags |= RATE_MCS_ANT_B_MSK;
2821                 } else {
2822                         priv->use_ant_b_for_management_frame = 1;
2823                         rate_flags |= RATE_MCS_ANT_A_MSK;
2824                 }
2825         }
2826
2827         tx->rts_retry_limit = rts_retry_limit;
2828         tx->data_retry_limit = data_retry_limit;
2829         tx->rate_n_flags = iwl4965_hw_set_rate_n_flags(rate_plcp, rate_flags);
2830 }
2831
2832 int iwl4965_hw_get_rx_read(struct iwl_priv *priv)
2833 {
2834         struct iwl4965_shared *shared_data = priv->hw_setting.shared_virt;
2835
2836         return IWL_GET_BITS(*shared_data, rb_closed_stts_rb_num);
2837 }
2838
2839 int iwl4965_hw_get_temperature(struct iwl_priv *priv)
2840 {
2841         return priv->temperature;
2842 }
2843
2844 unsigned int iwl4965_hw_get_beacon_cmd(struct iwl_priv *priv,
2845                           struct iwl4965_frame *frame, u8 rate)
2846 {
2847         struct iwl4965_tx_beacon_cmd *tx_beacon_cmd;
2848         unsigned int frame_size;
2849
2850         tx_beacon_cmd = &frame->u.beacon;
2851         memset(tx_beacon_cmd, 0, sizeof(*tx_beacon_cmd));
2852
2853         tx_beacon_cmd->tx.sta_id = priv->hw_setting.bcast_sta_id;
2854         tx_beacon_cmd->tx.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
2855
2856         frame_size = iwl4965_fill_beacon_frame(priv,
2857                                 tx_beacon_cmd->frame,
2858                                 iwl4965_broadcast_addr,
2859                                 sizeof(frame->u) - sizeof(*tx_beacon_cmd));
2860
2861         BUG_ON(frame_size > MAX_MPDU_SIZE);
2862         tx_beacon_cmd->tx.len = cpu_to_le16((u16)frame_size);
2863
2864         if ((rate == IWL_RATE_1M_PLCP) || (rate >= IWL_RATE_2M_PLCP))
2865                 tx_beacon_cmd->tx.rate_n_flags =
2866                         iwl4965_hw_set_rate_n_flags(rate, RATE_MCS_CCK_MSK);
2867         else
2868                 tx_beacon_cmd->tx.rate_n_flags =
2869                         iwl4965_hw_set_rate_n_flags(rate, 0);
2870
2871         tx_beacon_cmd->tx.tx_flags = (TX_CMD_FLG_SEQ_CTL_MSK |
2872                                 TX_CMD_FLG_TSF_MSK | TX_CMD_FLG_STA_RATE_MSK);
2873         return (sizeof(*tx_beacon_cmd) + frame_size);
2874 }
2875
2876 /*
2877  * Tell 4965 where to find circular buffer of Tx Frame Descriptors for
2878  * given Tx queue, and enable the DMA channel used for that queue.
2879  *
2880  * 4965 supports up to 16 Tx queues in DRAM, mapped to up to 8 Tx DMA
2881  * channels supported in hardware.
2882  */
2883 int iwl4965_hw_tx_queue_init(struct iwl_priv *priv, struct iwl4965_tx_queue *txq)
2884 {
2885         int rc;
2886         unsigned long flags;
2887         int txq_id = txq->q.id;
2888
2889         spin_lock_irqsave(&priv->lock, flags);
2890         rc = iwl4965_grab_nic_access(priv);
2891         if (rc) {
2892                 spin_unlock_irqrestore(&priv->lock, flags);
2893                 return rc;
2894         }
2895
2896         /* Circular buffer (TFD queue in DRAM) physical base address */
2897         iwl4965_write_direct32(priv, FH_MEM_CBBC_QUEUE(txq_id),
2898                              txq->q.dma_addr >> 8);
2899
2900         /* Enable DMA channel, using same id as for TFD queue */
2901         iwl4965_write_direct32(
2902                 priv, IWL_FH_TCSR_CHNL_TX_CONFIG_REG(txq_id),
2903                 IWL_FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE |
2904                 IWL_FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_ENABLE_VAL);
2905         iwl4965_release_nic_access(priv);
2906         spin_unlock_irqrestore(&priv->lock, flags);
2907
2908         return 0;
2909 }
2910
2911 int iwl4965_hw_txq_attach_buf_to_tfd(struct iwl_priv *priv, void *ptr,
2912                                  dma_addr_t addr, u16 len)
2913 {
2914         int index, is_odd;
2915         struct iwl4965_tfd_frame *tfd = ptr;
2916         u32 num_tbs = IWL_GET_BITS(*tfd, num_tbs);
2917
2918         /* Each TFD can point to a maximum 20 Tx buffers */
2919         if ((num_tbs >= MAX_NUM_OF_TBS) || (num_tbs < 0)) {
2920                 IWL_ERROR("Error can not send more than %d chunks\n",
2921                           MAX_NUM_OF_TBS);
2922                 return -EINVAL;
2923         }
2924
2925         index = num_tbs / 2;
2926         is_odd = num_tbs & 0x1;
2927
2928         if (!is_odd) {
2929                 tfd->pa[index].tb1_addr = cpu_to_le32(addr);
2930                 IWL_SET_BITS(tfd->pa[index], tb1_addr_hi,
2931                              iwl_get_dma_hi_address(addr));
2932                 IWL_SET_BITS(tfd->pa[index], tb1_len, len);
2933         } else {
2934                 IWL_SET_BITS(tfd->pa[index], tb2_addr_lo16,
2935                              (u32) (addr & 0xffff));
2936                 IWL_SET_BITS(tfd->pa[index], tb2_addr_hi20, addr >> 16);
2937                 IWL_SET_BITS(tfd->pa[index], tb2_len, len);
2938         }
2939
2940         IWL_SET_BITS(*tfd, num_tbs, num_tbs + 1);
2941
2942         return 0;
2943 }
2944
2945 static void iwl4965_hw_card_show_info(struct iwl_priv *priv)
2946 {
2947         u16 hw_version = priv->eeprom.board_revision_4965;
2948
2949         IWL_DEBUG_INFO("4965ABGN HW Version %u.%u.%u\n",
2950                        ((hw_version >> 8) & 0x0F),
2951                        ((hw_version >> 8) >> 4), (hw_version & 0x00FF));
2952
2953         IWL_DEBUG_INFO("4965ABGN PBA Number %.16s\n",
2954                        priv->eeprom.board_pba_number_4965);
2955 }
2956
2957 #define IWL_TX_CRC_SIZE         4
2958 #define IWL_TX_DELIMITER_SIZE   4
2959
2960 /**
2961  * iwl4965_tx_queue_update_wr_ptr - Set up entry in Tx byte-count array
2962  */
2963 int iwl4965_tx_queue_update_wr_ptr(struct iwl_priv *priv,
2964                                    struct iwl4965_tx_queue *txq, u16 byte_cnt)
2965 {
2966         int len;
2967         int txq_id = txq->q.id;
2968         struct iwl4965_shared *shared_data = priv->hw_setting.shared_virt;
2969
2970         if (txq->need_update == 0)
2971                 return 0;
2972
2973         len = byte_cnt + IWL_TX_CRC_SIZE + IWL_TX_DELIMITER_SIZE;
2974
2975         /* Set up byte count within first 256 entries */
2976         IWL_SET_BITS16(shared_data->queues_byte_cnt_tbls[txq_id].
2977                        tfd_offset[txq->q.write_ptr], byte_cnt, len);
2978
2979         /* If within first 64 entries, duplicate at end */
2980         if (txq->q.write_ptr < IWL4965_MAX_WIN_SIZE)
2981                 IWL_SET_BITS16(shared_data->queues_byte_cnt_tbls[txq_id].
2982                         tfd_offset[IWL4965_QUEUE_SIZE + txq->q.write_ptr],
2983                         byte_cnt, len);
2984
2985         return 0;
2986 }
2987
2988 /**
2989  * iwl4965_set_rxon_chain - Set up Rx chain usage in "staging" RXON image
2990  *
2991  * Selects how many and which Rx receivers/antennas/chains to use.
2992  * This should not be used for scan command ... it puts data in wrong place.
2993  */
2994 void iwl4965_set_rxon_chain(struct iwl_priv *priv)
2995 {
2996         u8 is_single = is_single_stream(priv);
2997         u8 idle_state, rx_state;
2998
2999         priv->staging_rxon.rx_chain = 0;
3000         rx_state = idle_state = 3;
3001
3002         /* Tell uCode which antennas are actually connected.
3003          * Before first association, we assume all antennas are connected.
3004          * Just after first association, iwl4965_noise_calibration()
3005          *    checks which antennas actually *are* connected. */
3006         priv->staging_rxon.rx_chain |=
3007             cpu_to_le16(priv->valid_antenna << RXON_RX_CHAIN_VALID_POS);
3008
3009         /* How many receivers should we use? */
3010         iwl4965_get_rx_chain_counter(priv, &idle_state, &rx_state);
3011         priv->staging_rxon.rx_chain |=
3012                 cpu_to_le16(rx_state << RXON_RX_CHAIN_MIMO_CNT_POS);
3013         priv->staging_rxon.rx_chain |=
3014                 cpu_to_le16(idle_state << RXON_RX_CHAIN_CNT_POS);
3015
3016         if (!is_single && (rx_state >= 2) &&
3017             !test_bit(STATUS_POWER_PMI, &priv->status))
3018                 priv->staging_rxon.rx_chain |= RXON_RX_CHAIN_MIMO_FORCE_MSK;
3019         else
3020                 priv->staging_rxon.rx_chain &= ~RXON_RX_CHAIN_MIMO_FORCE_MSK;
3021
3022         IWL_DEBUG_ASSOC("rx chain %X\n", priv->staging_rxon.rx_chain);
3023 }
3024
3025 /**
3026  * sign_extend - Sign extend a value using specified bit as sign-bit
3027  *
3028  * Example: sign_extend(9, 3) would return -7 as bit3 of 1001b is 1
3029  * and bit0..2 is 001b which when sign extended to 1111111111111001b is -7.
3030  *
3031  * @param oper value to sign extend
3032  * @param index 0 based bit index (0<=index<32) to sign bit
3033  */
3034 static s32 sign_extend(u32 oper, int index)
3035 {
3036         u8 shift = 31 - index;
3037
3038         return (s32)(oper << shift) >> shift;
3039 }
3040
3041 /**
3042  * iwl4965_get_temperature - return the calibrated temperature (in Kelvin)
3043  * @statistics: Provides the temperature reading from the uCode
3044  *
3045  * A return of <0 indicates bogus data in the statistics
3046  */
3047 int iwl4965_get_temperature(const struct iwl_priv *priv)
3048 {
3049         s32 temperature;
3050         s32 vt;
3051         s32 R1, R2, R3;
3052         u32 R4;
3053
3054         if (test_bit(STATUS_TEMPERATURE, &priv->status) &&
3055                 (priv->statistics.flag & STATISTICS_REPLY_FLG_FAT_MODE_MSK)) {
3056                 IWL_DEBUG_TEMP("Running FAT temperature calibration\n");
3057                 R1 = (s32)le32_to_cpu(priv->card_alive_init.therm_r1[1]);
3058                 R2 = (s32)le32_to_cpu(priv->card_alive_init.therm_r2[1]);
3059                 R3 = (s32)le32_to_cpu(priv->card_alive_init.therm_r3[1]);
3060                 R4 = le32_to_cpu(priv->card_alive_init.therm_r4[1]);
3061         } else {
3062                 IWL_DEBUG_TEMP("Running temperature calibration\n");
3063                 R1 = (s32)le32_to_cpu(priv->card_alive_init.therm_r1[0]);
3064                 R2 = (s32)le32_to_cpu(priv->card_alive_init.therm_r2[0]);
3065                 R3 = (s32)le32_to_cpu(priv->card_alive_init.therm_r3[0]);
3066                 R4 = le32_to_cpu(priv->card_alive_init.therm_r4[0]);
3067         }
3068
3069         /*
3070          * Temperature is only 23 bits, so sign extend out to 32.
3071          *
3072          * NOTE If we haven't received a statistics notification yet
3073          * with an updated temperature, use R4 provided to us in the
3074          * "initialize" ALIVE response.
3075          */
3076         if (!test_bit(STATUS_TEMPERATURE, &priv->status))
3077                 vt = sign_extend(R4, 23);
3078         else
3079                 vt = sign_extend(
3080                         le32_to_cpu(priv->statistics.general.temperature), 23);
3081
3082         IWL_DEBUG_TEMP("Calib values R[1-3]: %d %d %d R4: %d\n",
3083                        R1, R2, R3, vt);
3084
3085         if (R3 == R1) {
3086                 IWL_ERROR("Calibration conflict R1 == R3\n");
3087                 return -1;
3088         }
3089
3090         /* Calculate temperature in degrees Kelvin, adjust by 97%.
3091          * Add offset to center the adjustment around 0 degrees Centigrade. */
3092         temperature = TEMPERATURE_CALIB_A_VAL * (vt - R2);
3093         temperature /= (R3 - R1);
3094         temperature = (temperature * 97) / 100 +
3095             TEMPERATURE_CALIB_KELVIN_OFFSET;
3096
3097         IWL_DEBUG_TEMP("Calibrated temperature: %dK, %dC\n", temperature,
3098             KELVIN_TO_CELSIUS(temperature));
3099
3100         return temperature;
3101 }
3102
3103 /* Adjust Txpower only if temperature variance is greater than threshold. */
3104 #define IWL_TEMPERATURE_THRESHOLD   3
3105
3106 /**
3107  * iwl4965_is_temp_calib_needed - determines if new calibration is needed
3108  *
3109  * If the temperature changed has changed sufficiently, then a recalibration
3110  * is needed.
3111  *
3112  * Assumes caller will replace priv->last_temperature once calibration
3113  * executed.
3114  */
3115 static int iwl4965_is_temp_calib_needed(struct iwl_priv *priv)
3116 {
3117         int temp_diff;
3118
3119         if (!test_bit(STATUS_STATISTICS, &priv->status)) {
3120                 IWL_DEBUG_TEMP("Temperature not updated -- no statistics.\n");
3121                 return 0;
3122         }
3123
3124         temp_diff = priv->temperature - priv->last_temperature;
3125
3126         /* get absolute value */
3127         if (temp_diff < 0) {
3128                 IWL_DEBUG_POWER("Getting cooler, delta %d, \n", temp_diff);
3129                 temp_diff = -temp_diff;
3130         } else if (temp_diff == 0)
3131                 IWL_DEBUG_POWER("Same temp, \n");
3132         else
3133                 IWL_DEBUG_POWER("Getting warmer, delta %d, \n", temp_diff);
3134
3135         if (temp_diff < IWL_TEMPERATURE_THRESHOLD) {
3136                 IWL_DEBUG_POWER("Thermal txpower calib not needed\n");
3137                 return 0;
3138         }
3139
3140         IWL_DEBUG_POWER("Thermal txpower calib needed\n");
3141
3142         return 1;
3143 }
3144
3145 /* Calculate noise level, based on measurements during network silence just
3146  *   before arriving beacon.  This measurement can be done only if we know
3147  *   exactly when to expect beacons, therefore only when we're associated. */
3148 static void iwl4965_rx_calc_noise(struct iwl_priv *priv)
3149 {
3150         struct statistics_rx_non_phy *rx_info
3151                                 = &(priv->statistics.rx.general);
3152         int num_active_rx = 0;
3153         int total_silence = 0;
3154         int bcn_silence_a =
3155                 le32_to_cpu(rx_info->beacon_silence_rssi_a) & IN_BAND_FILTER;
3156         int bcn_silence_b =
3157                 le32_to_cpu(rx_info->beacon_silence_rssi_b) & IN_BAND_FILTER;
3158         int bcn_silence_c =
3159                 le32_to_cpu(rx_info->beacon_silence_rssi_c) & IN_BAND_FILTER;
3160
3161         if (bcn_silence_a) {
3162                 total_silence += bcn_silence_a;
3163                 num_active_rx++;
3164         }
3165         if (bcn_silence_b) {
3166                 total_silence += bcn_silence_b;
3167                 num_active_rx++;
3168         }
3169         if (bcn_silence_c) {
3170                 total_silence += bcn_silence_c;
3171                 num_active_rx++;
3172         }
3173
3174         /* Average among active antennas */
3175         if (num_active_rx)
3176                 priv->last_rx_noise = (total_silence / num_active_rx) - 107;
3177         else
3178                 priv->last_rx_noise = IWL_NOISE_MEAS_NOT_AVAILABLE;
3179
3180         IWL_DEBUG_CALIB("inband silence a %u, b %u, c %u, dBm %d\n",
3181                         bcn_silence_a, bcn_silence_b, bcn_silence_c,
3182                         priv->last_rx_noise);
3183 }
3184
3185 void iwl4965_hw_rx_statistics(struct iwl_priv *priv, struct iwl4965_rx_mem_buffer *rxb)
3186 {
3187         struct iwl4965_rx_packet *pkt = (void *)rxb->skb->data;
3188         int change;
3189         s32 temp;
3190
3191         IWL_DEBUG_RX("Statistics notification received (%d vs %d).\n",
3192                      (int)sizeof(priv->statistics), pkt->len);
3193
3194         change = ((priv->statistics.general.temperature !=
3195                    pkt->u.stats.general.temperature) ||
3196                   ((priv->statistics.flag &
3197                     STATISTICS_REPLY_FLG_FAT_MODE_MSK) !=
3198                    (pkt->u.stats.flag & STATISTICS_REPLY_FLG_FAT_MODE_MSK)));
3199
3200         memcpy(&priv->statistics, &pkt->u.stats, sizeof(priv->statistics));
3201
3202         set_bit(STATUS_STATISTICS, &priv->status);
3203
3204         /* Reschedule the statistics timer to occur in
3205          * REG_RECALIB_PERIOD seconds to ensure we get a
3206          * thermal update even if the uCode doesn't give
3207          * us one */
3208         mod_timer(&priv->statistics_periodic, jiffies +
3209                   msecs_to_jiffies(REG_RECALIB_PERIOD * 1000));
3210
3211         if (unlikely(!test_bit(STATUS_SCANNING, &priv->status)) &&
3212             (pkt->hdr.cmd == STATISTICS_NOTIFICATION)) {
3213                 iwl4965_rx_calc_noise(priv);
3214 #ifdef CONFIG_IWL4965_SENSITIVITY
3215                 queue_work(priv->workqueue, &priv->sensitivity_work);
3216 #endif
3217         }
3218
3219         /* If the hardware hasn't reported a change in
3220          * temperature then don't bother computing a
3221          * calibrated temperature value */
3222         if (!change)
3223                 return;
3224
3225         temp = iwl4965_get_temperature(priv);
3226         if (temp < 0)
3227                 return;
3228
3229         if (priv->temperature != temp) {
3230                 if (priv->temperature)
3231                         IWL_DEBUG_TEMP("Temperature changed "
3232                                        "from %dC to %dC\n",
3233                                        KELVIN_TO_CELSIUS(priv->temperature),
3234                                        KELVIN_TO_CELSIUS(temp));
3235                 else
3236                         IWL_DEBUG_TEMP("Temperature "
3237                                        "initialized to %dC\n",
3238                                        KELVIN_TO_CELSIUS(temp));
3239         }
3240
3241         priv->temperature = temp;
3242         set_bit(STATUS_TEMPERATURE, &priv->status);
3243
3244         if (unlikely(!test_bit(STATUS_SCANNING, &priv->status)) &&
3245                      iwl4965_is_temp_calib_needed(priv))
3246                 queue_work(priv->workqueue, &priv->txpower_work);
3247 }
3248
3249 static void iwl4965_add_radiotap(struct iwl_priv *priv,
3250                                  struct sk_buff *skb,
3251                                  struct iwl4965_rx_phy_res *rx_start,
3252                                  struct ieee80211_rx_status *stats,
3253                                  u32 ampdu_status)
3254 {
3255         s8 signal = stats->ssi;
3256         s8 noise = 0;
3257         int rate = stats->rate_idx;
3258         u64 tsf = stats->mactime;
3259         __le16 phy_flags_hw = rx_start->phy_flags;
3260         struct iwl4965_rt_rx_hdr {
3261                 struct ieee80211_radiotap_header rt_hdr;
3262                 __le64 rt_tsf;          /* TSF */
3263                 u8 rt_flags;            /* radiotap packet flags */
3264                 u8 rt_rate;             /* rate in 500kb/s */
3265                 __le16 rt_channelMHz;   /* channel in MHz */
3266                 __le16 rt_chbitmask;    /* channel bitfield */
3267                 s8 rt_dbmsignal;        /* signal in dBm, kluged to signed */
3268                 s8 rt_dbmnoise;
3269                 u8 rt_antenna;          /* antenna number */
3270         } __attribute__ ((packed)) *iwl4965_rt;
3271
3272         /* TODO: We won't have enough headroom for HT frames. Fix it later. */
3273         if (skb_headroom(skb) < sizeof(*iwl4965_rt)) {
3274                 if (net_ratelimit())
3275                         printk(KERN_ERR "not enough headroom [%d] for "
3276                                "radiotap head [%zd]\n",
3277                                skb_headroom(skb), sizeof(*iwl4965_rt));
3278                 return;
3279         }
3280
3281         /* put radiotap header in front of 802.11 header and data */
3282         iwl4965_rt = (void *)skb_push(skb, sizeof(*iwl4965_rt));
3283
3284         /* initialise radiotap header */
3285         iwl4965_rt->rt_hdr.it_version = PKTHDR_RADIOTAP_VERSION;
3286         iwl4965_rt->rt_hdr.it_pad = 0;
3287
3288         /* total header + data */
3289         put_unaligned(cpu_to_le16(sizeof(*iwl4965_rt)),
3290                       &iwl4965_rt->rt_hdr.it_len);
3291
3292         /* Indicate all the fields we add to the radiotap header */
3293         put_unaligned(cpu_to_le32((1 << IEEE80211_RADIOTAP_TSFT) |
3294                                   (1 << IEEE80211_RADIOTAP_FLAGS) |
3295                                   (1 << IEEE80211_RADIOTAP_RATE) |
3296                                   (1 << IEEE80211_RADIOTAP_CHANNEL) |
3297                                   (1 << IEEE80211_RADIOTAP_DBM_ANTSIGNAL) |
3298                                   (1 << IEEE80211_RADIOTAP_DBM_ANTNOISE) |
3299                                   (1 << IEEE80211_RADIOTAP_ANTENNA)),
3300                       &iwl4965_rt->rt_hdr.it_present);
3301
3302         /* Zero the flags, we'll add to them as we go */
3303         iwl4965_rt->rt_flags = 0;
3304
3305         put_unaligned(cpu_to_le64(tsf), &iwl4965_rt->rt_tsf);
3306
3307         iwl4965_rt->rt_dbmsignal = signal;
3308         iwl4965_rt->rt_dbmnoise = noise;
3309
3310         /* Convert the channel frequency and set the flags */
3311         put_unaligned(cpu_to_le16(stats->freq), &iwl4965_rt->rt_channelMHz);
3312         if (!(phy_flags_hw & RX_RES_PHY_FLAGS_BAND_24_MSK))
3313                 put_unaligned(cpu_to_le16(IEEE80211_CHAN_OFDM |
3314                                           IEEE80211_CHAN_5GHZ),
3315                               &iwl4965_rt->rt_chbitmask);
3316         else if (phy_flags_hw & RX_RES_PHY_FLAGS_MOD_CCK_MSK)
3317                 put_unaligned(cpu_to_le16(IEEE80211_CHAN_CCK |
3318                                           IEEE80211_CHAN_2GHZ),
3319                               &iwl4965_rt->rt_chbitmask);
3320         else    /* 802.11g */
3321                 put_unaligned(cpu_to_le16(IEEE80211_CHAN_OFDM |
3322                                           IEEE80211_CHAN_2GHZ),
3323                               &iwl4965_rt->rt_chbitmask);
3324
3325         if (rate == -1)
3326                 iwl4965_rt->rt_rate = 0;
3327         else
3328                 iwl4965_rt->rt_rate = iwl4965_rates[rate].ieee;
3329
3330         /*
3331          * "antenna number"
3332          *
3333          * It seems that the antenna field in the phy flags value
3334          * is actually a bitfield. This is undefined by radiotap,
3335          * it wants an actual antenna number but I always get "7"
3336          * for most legacy frames I receive indicating that the
3337          * same frame was received on all three RX chains.
3338          *
3339          * I think this field should be removed in favour of a
3340          * new 802.11n radiotap field "RX chains" that is defined
3341          * as a bitmask.
3342          */
3343         iwl4965_rt->rt_antenna =
3344                 le16_to_cpu(phy_flags_hw & RX_RES_PHY_FLAGS_ANTENNA_MSK) >> 4;
3345
3346         /* set the preamble flag if appropriate */
3347         if (phy_flags_hw & RX_RES_PHY_FLAGS_SHORT_PREAMBLE_MSK)
3348                 iwl4965_rt->rt_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
3349
3350         stats->flag |= RX_FLAG_RADIOTAP;
3351 }
3352
3353 static void iwl_update_rx_stats(struct iwl_priv *priv, u16 fc, u16 len)
3354 {
3355         /* 0 - mgmt, 1 - cnt, 2 - data */
3356         int idx = (fc & IEEE80211_FCTL_FTYPE) >> 2;
3357         priv->rx_stats[idx].cnt++;
3358         priv->rx_stats[idx].bytes += len;
3359 }
3360
3361 static void iwl4965_handle_data_packet(struct iwl_priv *priv, int is_data,
3362                                        int include_phy,
3363                                        struct iwl4965_rx_mem_buffer *rxb,
3364                                        struct ieee80211_rx_status *stats)
3365 {
3366         struct iwl4965_rx_packet *pkt = (struct iwl4965_rx_packet *)rxb->skb->data;
3367         struct iwl4965_rx_phy_res *rx_start = (include_phy) ?
3368             (struct iwl4965_rx_phy_res *)&(pkt->u.raw[0]) : NULL;
3369         struct ieee80211_hdr *hdr;
3370         u16 len;
3371         __le32 *rx_end;
3372         unsigned int skblen;
3373         u32 ampdu_status;
3374
3375         if (!include_phy && priv->last_phy_res[0])
3376                 rx_start = (struct iwl4965_rx_phy_res *)&priv->last_phy_res[1];
3377
3378         if (!rx_start) {
3379                 IWL_ERROR("MPDU frame without a PHY data\n");
3380                 return;
3381         }
3382         if (include_phy) {
3383                 hdr = (struct ieee80211_hdr *)((u8 *) & rx_start[1] +
3384                                                rx_start->cfg_phy_cnt);
3385
3386                 len = le16_to_cpu(rx_start->byte_count);
3387
3388                 rx_end = (__le32 *) ((u8 *) & pkt->u.raw[0] +
3389                                   sizeof(struct iwl4965_rx_phy_res) +
3390                                   rx_start->cfg_phy_cnt + len);
3391
3392         } else {
3393                 struct iwl4965_rx_mpdu_res_start *amsdu =
3394                     (struct iwl4965_rx_mpdu_res_start *)pkt->u.raw;
3395
3396                 hdr = (struct ieee80211_hdr *)(pkt->u.raw +
3397                                sizeof(struct iwl4965_rx_mpdu_res_start));
3398                 len =  le16_to_cpu(amsdu->byte_count);
3399                 rx_start->byte_count = amsdu->byte_count;
3400                 rx_end = (__le32 *) (((u8 *) hdr) + len);
3401         }
3402         if (len > priv->hw_setting.max_pkt_size || len < 16) {
3403                 IWL_WARNING("byte count out of range [16,4K] : %d\n", len);
3404                 return;
3405         }
3406
3407         ampdu_status = le32_to_cpu(*rx_end);
3408         skblen = ((u8 *) rx_end - (u8 *) & pkt->u.raw[0]) + sizeof(u32);
3409
3410         /* start from MAC */
3411         skb_reserve(rxb->skb, (void *)hdr - (void *)pkt);
3412         skb_put(rxb->skb, len); /* end where data ends */
3413
3414         /* We only process data packets if the interface is open */
3415         if (unlikely(!priv->is_open)) {
3416                 IWL_DEBUG_DROP_LIMIT
3417                     ("Dropping packet while interface is not open.\n");
3418                 return;
3419         }
3420
3421         stats->flag = 0;
3422         hdr = (struct ieee80211_hdr *)rxb->skb->data;
3423
3424         if (iwl4965_mod_params.hw_crypto)
3425                 iwl4965_set_decrypted_flag(priv, rxb->skb, ampdu_status, stats);
3426
3427         if (priv->add_radiotap)
3428                 iwl4965_add_radiotap(priv, rxb->skb, rx_start, stats, ampdu_status);
3429
3430         iwl_update_rx_stats(priv, le16_to_cpu(hdr->frame_control), len);
3431         ieee80211_rx_irqsafe(priv->hw, rxb->skb, stats);
3432         priv->alloc_rxb_skb--;
3433         rxb->skb = NULL;
3434 #ifdef LED
3435         priv->led_packets += len;
3436         iwl4965_setup_activity_timer(priv);
3437 #endif
3438 }
3439
3440 /* Calc max signal level (dBm) among 3 possible receivers */
3441 static int iwl4965_calc_rssi(struct iwl4965_rx_phy_res *rx_resp)
3442 {
3443         /* data from PHY/DSP regarding signal strength, etc.,
3444          *   contents are always there, not configurable by host.  */
3445         struct iwl4965_rx_non_cfg_phy *ncphy =
3446             (struct iwl4965_rx_non_cfg_phy *)rx_resp->non_cfg_phy;
3447         u32 agc = (le16_to_cpu(ncphy->agc_info) & IWL_AGC_DB_MASK)
3448                         >> IWL_AGC_DB_POS;
3449
3450         u32 valid_antennae =
3451             (le16_to_cpu(rx_resp->phy_flags) & RX_PHY_FLAGS_ANTENNAE_MASK)
3452                         >> RX_PHY_FLAGS_ANTENNAE_OFFSET;
3453         u8 max_rssi = 0;
3454         u32 i;
3455
3456         /* Find max rssi among 3 possible receivers.
3457          * These values are measured by the digital signal processor (DSP).
3458          * They should stay fairly constant even as the signal strength varies,
3459          *   if the radio's automatic gain control (AGC) is working right.
3460          * AGC value (see below) will provide the "interesting" info. */
3461         for (i = 0; i < 3; i++)
3462                 if (valid_antennae & (1 << i))
3463                         max_rssi = max(ncphy->rssi_info[i << 1], max_rssi);
3464
3465         IWL_DEBUG_STATS("Rssi In A %d B %d C %d Max %d AGC dB %d\n",
3466                 ncphy->rssi_info[0], ncphy->rssi_info[2], ncphy->rssi_info[4],
3467                 max_rssi, agc);
3468
3469         /* dBm = max_rssi dB - agc dB - constant.
3470          * Higher AGC (higher radio gain) means lower signal. */
3471         return (max_rssi - agc - IWL_RSSI_OFFSET);
3472 }
3473
3474 #ifdef CONFIG_IWL4965_HT
3475
3476 /* Parsed Information Elements */
3477 struct ieee802_11_elems {
3478         u8 *ds_params;
3479         u8 ds_params_len;
3480         u8 *tim;
3481         u8 tim_len;
3482         u8 *ibss_params;
3483         u8 ibss_params_len;
3484         u8 *erp_info;
3485         u8 erp_info_len;
3486         u8 *ht_cap_param;
3487         u8 ht_cap_param_len;
3488         u8 *ht_extra_param;
3489         u8 ht_extra_param_len;
3490 };
3491
3492 static int parse_elems(u8 *start, size_t len, struct ieee802_11_elems *elems)
3493 {
3494         size_t left = len;
3495         u8 *pos = start;
3496         int unknown = 0;
3497
3498         memset(elems, 0, sizeof(*elems));
3499
3500         while (left >= 2) {
3501                 u8 id, elen;
3502
3503                 id = *pos++;
3504                 elen = *pos++;
3505                 left -= 2;
3506
3507                 if (elen > left)
3508                         return -1;
3509
3510                 switch (id) {
3511                 case WLAN_EID_DS_PARAMS:
3512                         elems->ds_params = pos;
3513                         elems->ds_params_len = elen;
3514                         break;
3515                 case WLAN_EID_TIM:
3516                         elems->tim = pos;
3517                         elems->tim_len = elen;
3518                         break;
3519                 case WLAN_EID_IBSS_PARAMS:
3520                         elems->ibss_params = pos;
3521                         elems->ibss_params_len = elen;
3522                         break;
3523                 case WLAN_EID_ERP_INFO:
3524                         elems->erp_info = pos;
3525                         elems->erp_info_len = elen;
3526                         break;
3527                 case WLAN_EID_HT_CAPABILITY:
3528                         elems->ht_cap_param = pos;
3529                         elems->ht_cap_param_len = elen;
3530                         break;
3531                 case WLAN_EID_HT_EXTRA_INFO:
3532                         elems->ht_extra_param = pos;
3533                         elems->ht_extra_param_len = elen;
3534                         break;
3535                 default:
3536                         unknown++;
3537                         break;
3538                 }
3539
3540                 left -= elen;
3541                 pos += elen;
3542         }
3543
3544         return 0;
3545 }
3546
3547 void iwl4965_init_ht_hw_capab(struct ieee80211_ht_info *ht_info,
3548                               enum ieee80211_band band)
3549 {
3550         ht_info->cap = 0;
3551         memset(ht_info->supp_mcs_set, 0, 16);
3552
3553         ht_info->ht_supported = 1;
3554
3555         if (band == IEEE80211_BAND_5GHZ) {
3556                 ht_info->cap |= (u16)IEEE80211_HT_CAP_SUP_WIDTH;
3557                 ht_info->cap |= (u16)IEEE80211_HT_CAP_SGI_40;
3558                 ht_info->supp_mcs_set[4] = 0x01;
3559         }
3560         ht_info->cap |= (u16)IEEE80211_HT_CAP_GRN_FLD;
3561         ht_info->cap |= (u16)IEEE80211_HT_CAP_SGI_20;
3562         ht_info->cap |= (u16)(IEEE80211_HT_CAP_MIMO_PS &
3563                              (IWL_MIMO_PS_NONE << 2));
3564         if (iwl4965_mod_params.amsdu_size_8K) {
3565                 printk(KERN_DEBUG "iwl4965 in A-MSDU 8K support mode\n");
3566                 ht_info->cap |= (u16)IEEE80211_HT_CAP_MAX_AMSDU;
3567         }
3568
3569         ht_info->ampdu_factor = CFG_HT_RX_AMPDU_FACTOR_DEF;
3570         ht_info->ampdu_density = CFG_HT_MPDU_DENSITY_DEF;
3571
3572         ht_info->supp_mcs_set[0] = 0xFF;
3573         ht_info->supp_mcs_set[1] = 0xFF;
3574 }
3575 #endif /* CONFIG_IWL4965_HT */
3576
3577 static void iwl4965_sta_modify_ps_wake(struct iwl_priv *priv, int sta_id)
3578 {
3579         unsigned long flags;
3580
3581         spin_lock_irqsave(&priv->sta_lock, flags);
3582         priv->stations[sta_id].sta.station_flags &= ~STA_FLG_PWR_SAVE_MSK;
3583         priv->stations[sta_id].sta.station_flags_msk = STA_FLG_PWR_SAVE_MSK;
3584         priv->stations[sta_id].sta.sta.modify_mask = 0;
3585         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
3586         spin_unlock_irqrestore(&priv->sta_lock, flags);
3587
3588         iwl4965_send_add_station(priv, &priv->stations[sta_id].sta, CMD_ASYNC);
3589 }
3590
3591 static void iwl4965_update_ps_mode(struct iwl_priv *priv, u16 ps_bit, u8 *addr)
3592 {
3593         /* FIXME: need locking over ps_status ??? */
3594         u8 sta_id = iwl4965_hw_find_station(priv, addr);
3595
3596         if (sta_id != IWL_INVALID_STATION) {
3597                 u8 sta_awake = priv->stations[sta_id].
3598                                 ps_status == STA_PS_STATUS_WAKE;
3599
3600                 if (sta_awake && ps_bit)
3601                         priv->stations[sta_id].ps_status = STA_PS_STATUS_SLEEP;
3602                 else if (!sta_awake && !ps_bit) {
3603                         iwl4965_sta_modify_ps_wake(priv, sta_id);
3604                         priv->stations[sta_id].ps_status = STA_PS_STATUS_WAKE;
3605                 }
3606         }
3607 }
3608 #ifdef CONFIG_IWLWIFI_DEBUG
3609
3610 /**
3611  * iwl4965_dbg_report_frame - dump frame to syslog during debug sessions
3612  *
3613  * You may hack this function to show different aspects of received frames,
3614  * including selective frame dumps.
3615  * group100 parameter selects whether to show 1 out of 100 good frames.
3616  *
3617  * TODO:  This was originally written for 3945, need to audit for
3618  *        proper operation with 4965.
3619  */
3620 static void iwl4965_dbg_report_frame(struct iwl_priv *priv,
3621                       struct iwl4965_rx_packet *pkt,
3622                       struct ieee80211_hdr *header, int group100)
3623 {
3624         u32 to_us;
3625         u32 print_summary = 0;
3626         u32 print_dump = 0;     /* set to 1 to dump all frames' contents */
3627         u32 hundred = 0;
3628         u32 dataframe = 0;
3629         u16 fc;
3630         u16 seq_ctl;
3631         u16 channel;
3632         u16 phy_flags;
3633         int rate_sym;
3634         u16 length;
3635         u16 status;
3636         u16 bcn_tmr;
3637         u32 tsf_low;
3638         u64 tsf;
3639         u8 rssi;
3640         u8 agc;
3641         u16 sig_avg;
3642         u16 noise_diff;
3643         struct iwl4965_rx_frame_stats *rx_stats = IWL_RX_STATS(pkt);
3644         struct iwl4965_rx_frame_hdr *rx_hdr = IWL_RX_HDR(pkt);
3645         struct iwl4965_rx_frame_end *rx_end = IWL_RX_END(pkt);
3646         u8 *data = IWL_RX_DATA(pkt);
3647
3648         if (likely(!(iwl_debug_level & IWL_DL_RX)))
3649                 return;
3650
3651         /* MAC header */
3652         fc = le16_to_cpu(header->frame_control);
3653         seq_ctl = le16_to_cpu(header->seq_ctrl);
3654
3655         /* metadata */
3656         channel = le16_to_cpu(rx_hdr->channel);
3657         phy_flags = le16_to_cpu(rx_hdr->phy_flags);
3658         rate_sym = rx_hdr->rate;
3659         length = le16_to_cpu(rx_hdr->len);
3660
3661         /* end-of-frame status and timestamp */
3662         status = le32_to_cpu(rx_end->status);
3663         bcn_tmr = le32_to_cpu(rx_end->beacon_timestamp);
3664         tsf_low = le64_to_cpu(rx_end->timestamp) & 0x0ffffffff;
3665         tsf = le64_to_cpu(rx_end->timestamp);
3666
3667         /* signal statistics */
3668         rssi = rx_stats->rssi;
3669         agc = rx_stats->agc;
3670         sig_avg = le16_to_cpu(rx_stats->sig_avg);
3671         noise_diff = le16_to_cpu(rx_stats->noise_diff);
3672
3673         to_us = !compare_ether_addr(header->addr1, priv->mac_addr);
3674
3675         /* if data frame is to us and all is good,
3676          *   (optionally) print summary for only 1 out of every 100 */
3677         if (to_us && (fc & ~IEEE80211_FCTL_PROTECTED) ==
3678             (IEEE80211_FCTL_FROMDS | IEEE80211_FTYPE_DATA)) {
3679                 dataframe = 1;
3680                 if (!group100)
3681                         print_summary = 1;      /* print each frame */
3682                 else if (priv->framecnt_to_us < 100) {
3683                         priv->framecnt_to_us++;
3684                         print_summary = 0;
3685                 } else {
3686                         priv->framecnt_to_us = 0;
3687                         print_summary = 1;
3688                         hundred = 1;
3689                 }
3690         } else {
3691                 /* print summary for all other frames */
3692                 print_summary = 1;
3693         }
3694
3695         if (print_summary) {
3696                 char *title;
3697                 int rate_idx;
3698                 u32 bitrate;
3699
3700                 if (hundred)
3701                         title = "100Frames";
3702                 else if (fc & IEEE80211_FCTL_RETRY)
3703                         title = "Retry";
3704                 else if (ieee80211_is_assoc_response(fc))
3705                         title = "AscRsp";
3706                 else if (ieee80211_is_reassoc_response(fc))
3707                         title = "RasRsp";
3708                 else if (ieee80211_is_probe_response(fc)) {
3709                         title = "PrbRsp";
3710                         print_dump = 1; /* dump frame contents */
3711                 } else if (ieee80211_is_beacon(fc)) {
3712                         title = "Beacon";
3713                         print_dump = 1; /* dump frame contents */
3714                 } else if (ieee80211_is_atim(fc))
3715                         title = "ATIM";
3716                 else if (ieee80211_is_auth(fc))
3717                         title = "Auth";
3718                 else if (ieee80211_is_deauth(fc))
3719                         title = "DeAuth";
3720                 else if (ieee80211_is_disassoc(fc))
3721                         title = "DisAssoc";
3722                 else
3723                         title = "Frame";
3724
3725                 rate_idx = iwl4965_hwrate_to_plcp_idx(rate_sym);
3726                 if (unlikely(rate_idx == -1))
3727                         bitrate = 0;
3728                 else
3729                         bitrate = iwl4965_rates[rate_idx].ieee / 2;
3730
3731                 /* print frame summary.
3732                  * MAC addresses show just the last byte (for brevity),
3733                  *    but you can hack it to show more, if you'd like to. */
3734                 if (dataframe)
3735                         IWL_DEBUG_RX("%s: mhd=0x%04x, dst=0x%02x, "
3736                                      "len=%u, rssi=%d, chnl=%d, rate=%u, \n",
3737                                      title, fc, header->addr1[5],
3738                                      length, rssi, channel, bitrate);
3739                 else {
3740                         /* src/dst addresses assume managed mode */
3741                         IWL_DEBUG_RX("%s: 0x%04x, dst=0x%02x, "
3742                                      "src=0x%02x, rssi=%u, tim=%lu usec, "
3743                                      "phy=0x%02x, chnl=%d\n",
3744                                      title, fc, header->addr1[5],
3745                                      header->addr3[5], rssi,
3746                                      tsf_low - priv->scan_start_tsf,
3747                                      phy_flags, channel);
3748                 }
3749         }
3750         if (print_dump)
3751                 iwl_print_hex_dump(IWL_DL_RX, data, length);
3752 }
3753 #else
3754 static inline void iwl4965_dbg_report_frame(struct iwl_priv *priv,
3755                                             struct iwl4965_rx_packet *pkt,
3756                                             struct ieee80211_hdr *header,
3757                                             int group100)
3758 {
3759 }
3760 #endif
3761
3762
3763 #define IWL_DELAY_NEXT_SCAN_AFTER_ASSOC (HZ*6)
3764
3765 /* Called for REPLY_4965_RX (legacy ABG frames), or
3766  * REPLY_RX_MPDU_CMD (HT high-throughput N frames). */
3767 static void iwl4965_rx_reply_rx(struct iwl_priv *priv,
3768                                 struct iwl4965_rx_mem_buffer *rxb)
3769 {
3770         struct ieee80211_hdr *header;
3771         struct ieee80211_rx_status rx_status;
3772         struct iwl4965_rx_packet *pkt = (void *)rxb->skb->data;
3773         /* Use phy data (Rx signal strength, etc.) contained within
3774          *   this rx packet for legacy frames,
3775          *   or phy data cached from REPLY_RX_PHY_CMD for HT frames. */
3776         int include_phy = (pkt->hdr.cmd == REPLY_4965_RX);
3777         struct iwl4965_rx_phy_res *rx_start = (include_phy) ?
3778                 (struct iwl4965_rx_phy_res *)&(pkt->u.raw[0]) :
3779                 (struct iwl4965_rx_phy_res *)&priv->last_phy_res[1];
3780         __le32 *rx_end;
3781         unsigned int len = 0;
3782         u16 fc;
3783         u8 network_packet;
3784
3785         rx_status.mactime = le64_to_cpu(rx_start->timestamp);
3786         rx_status.freq = ieee80211chan2mhz(le16_to_cpu(rx_start->channel));
3787         rx_status.band = (rx_start->phy_flags & RX_RES_PHY_FLAGS_BAND_24_MSK) ?
3788                                 IEEE80211_BAND_2GHZ : IEEE80211_BAND_5GHZ;
3789         rx_status.rate_idx = iwl4965_hwrate_to_plcp_idx(
3790                                         le32_to_cpu(rx_start->rate_n_flags));
3791
3792         if (rx_status.band == IEEE80211_BAND_5GHZ)
3793                 rx_status.rate_idx -= IWL_FIRST_OFDM_RATE;
3794
3795         rx_status.antenna = 0;
3796         rx_status.flag = 0;
3797
3798         if ((unlikely(rx_start->cfg_phy_cnt > 20))) {
3799                 IWL_DEBUG_DROP
3800                         ("dsp size out of range [0,20]: "
3801                          "%d/n", rx_start->cfg_phy_cnt);
3802                 return;
3803         }
3804
3805         if (!include_phy) {
3806                 if (priv->last_phy_res[0])
3807                         rx_start = (struct iwl4965_rx_phy_res *)
3808                                 &priv->last_phy_res[1];
3809                 else
3810                         rx_start = NULL;
3811         }
3812
3813         if (!rx_start) {
3814                 IWL_ERROR("MPDU frame without a PHY data\n");
3815                 return;
3816         }
3817
3818         if (include_phy) {
3819                 header = (struct ieee80211_hdr *)((u8 *) & rx_start[1]
3820                                                   + rx_start->cfg_phy_cnt);
3821
3822                 len = le16_to_cpu(rx_start->byte_count);
3823                 rx_end = (__le32 *)(pkt->u.raw + rx_start->cfg_phy_cnt +
3824                                   sizeof(struct iwl4965_rx_phy_res) + len);
3825         } else {
3826                 struct iwl4965_rx_mpdu_res_start *amsdu =
3827                         (struct iwl4965_rx_mpdu_res_start *)pkt->u.raw;
3828
3829                 header = (void *)(pkt->u.raw +
3830                         sizeof(struct iwl4965_rx_mpdu_res_start));
3831                 len = le16_to_cpu(amsdu->byte_count);
3832                 rx_end = (__le32 *) (pkt->u.raw +
3833                         sizeof(struct iwl4965_rx_mpdu_res_start) + len);
3834         }
3835
3836         if (!(*rx_end & RX_RES_STATUS_NO_CRC32_ERROR) ||
3837             !(*rx_end & RX_RES_STATUS_NO_RXE_OVERFLOW)) {
3838                 IWL_DEBUG_RX("Bad CRC or FIFO: 0x%08X.\n",
3839                                 le32_to_cpu(*rx_end));
3840                 return;
3841         }
3842
3843         priv->ucode_beacon_time = le32_to_cpu(rx_start->beacon_time_stamp);
3844
3845         /* Find max signal strength (dBm) among 3 antenna/receiver chains */
3846         rx_status.ssi = iwl4965_calc_rssi(rx_start);
3847
3848         /* Meaningful noise values are available only from beacon statistics,
3849          *   which are gathered only when associated, and indicate noise
3850          *   only for the associated network channel ...
3851          * Ignore these noise values while scanning (other channels) */
3852         if (iwl4965_is_associated(priv) &&
3853             !test_bit(STATUS_SCANNING, &priv->status)) {
3854                 rx_status.noise = priv->last_rx_noise;
3855                 rx_status.signal = iwl4965_calc_sig_qual(rx_status.ssi,
3856                                                          rx_status.noise);
3857         } else {
3858                 rx_status.noise = IWL_NOISE_MEAS_NOT_AVAILABLE;
3859                 rx_status.signal = iwl4965_calc_sig_qual(rx_status.ssi, 0);
3860         }
3861
3862         /* Reset beacon noise level if not associated. */
3863         if (!iwl4965_is_associated(priv))
3864                 priv->last_rx_noise = IWL_NOISE_MEAS_NOT_AVAILABLE;
3865
3866         /* Set "1" to report good data frames in groups of 100 */
3867         /* FIXME: need to optimze the call: */
3868         iwl4965_dbg_report_frame(priv, pkt, header, 1);
3869
3870         IWL_DEBUG_STATS_LIMIT("Rssi %d, noise %d, qual %d, TSF %llu\n",
3871                               rx_status.ssi, rx_status.noise, rx_status.signal,
3872                               rx_status.mactime);
3873
3874         network_packet = iwl4965_is_network_packet(priv, header);
3875         if (network_packet) {
3876                 priv->last_rx_rssi = rx_status.ssi;
3877                 priv->last_beacon_time =  priv->ucode_beacon_time;
3878                 priv->last_tsf = le64_to_cpu(rx_start->timestamp);
3879         }
3880
3881         fc = le16_to_cpu(header->frame_control);
3882         switch (fc & IEEE80211_FCTL_FTYPE) {
3883         case IEEE80211_FTYPE_MGMT:
3884
3885                 if (priv->iw_mode == IEEE80211_IF_TYPE_AP)
3886                         iwl4965_update_ps_mode(priv, fc  & IEEE80211_FCTL_PM,
3887                                                 header->addr2);
3888                 switch (fc & IEEE80211_FCTL_STYPE) {
3889                 case IEEE80211_STYPE_PROBE_RESP:
3890                 case IEEE80211_STYPE_BEACON:
3891                         if ((priv->iw_mode == IEEE80211_IF_TYPE_STA &&
3892                              !compare_ether_addr(header->addr2, priv->bssid)) ||
3893                             (priv->iw_mode == IEEE80211_IF_TYPE_IBSS &&
3894                              !compare_ether_addr(header->addr3, priv->bssid))) {
3895                                 struct ieee80211_mgmt *mgmt =
3896                                         (struct ieee80211_mgmt *)header;
3897                                 u64 timestamp =
3898                                         le64_to_cpu(mgmt->u.beacon.timestamp);
3899
3900                                 priv->timestamp0 = timestamp & 0xFFFFFFFF;
3901                                 priv->timestamp1 =
3902                                         (timestamp >> 32) & 0xFFFFFFFF;
3903                                 priv->beacon_int = le16_to_cpu(
3904                                     mgmt->u.beacon.beacon_int);
3905                                 if (priv->call_post_assoc_from_beacon &&
3906                                     (priv->iw_mode == IEEE80211_IF_TYPE_STA)) {
3907                                         priv->call_post_assoc_from_beacon = 0;
3908                                         queue_work(priv->workqueue,
3909                                             &priv->post_associate.work);
3910                                 }
3911                         }
3912                         break;
3913
3914                 case IEEE80211_STYPE_ACTION:
3915                         break;
3916
3917                         /*
3918                          * TODO: Use the new callback function from
3919                          * mac80211 instead of sniffing these packets.
3920                          */
3921                 case IEEE80211_STYPE_ASSOC_RESP:
3922                 case IEEE80211_STYPE_REASSOC_RESP:
3923                         if (network_packet) {
3924 #ifdef CONFIG_IWL4965_HT
3925                                 u8 *pos = NULL;
3926                                 struct ieee802_11_elems elems;
3927 #endif                          /*CONFIG_IWL4965_HT */
3928                                 struct ieee80211_mgmt *mgnt =
3929                                         (struct ieee80211_mgmt *)header;
3930
3931                                 /* We have just associated, give some
3932                                  * time for the 4-way handshake if
3933                                  * any. Don't start scan too early. */
3934                                 priv->next_scan_jiffies = jiffies +
3935                                         IWL_DELAY_NEXT_SCAN_AFTER_ASSOC;
3936
3937                                 priv->assoc_id = (~((1 << 15) | (1 << 14))
3938                                         & le16_to_cpu(mgnt->u.assoc_resp.aid));
3939                                 priv->assoc_capability =
3940                                         le16_to_cpu(
3941                                                 mgnt->u.assoc_resp.capab_info);
3942 #ifdef CONFIG_IWL4965_HT
3943                                 pos = mgnt->u.assoc_resp.variable;
3944                                 if (!parse_elems(pos,
3945                                                  len - (pos - (u8 *) mgnt),
3946                                                  &elems)) {
3947                                         if (elems.ht_extra_param &&
3948                                             elems.ht_cap_param)
3949                                                 break;
3950                                 }
3951 #endif                          /*CONFIG_IWL4965_HT */
3952                                 /* assoc_id is 0 no association */
3953                                 if (!priv->assoc_id)
3954                                         break;
3955                                 if (priv->beacon_int)
3956                                         queue_work(priv->workqueue,
3957                                             &priv->post_associate.work);
3958                                 else
3959                                         priv->call_post_assoc_from_beacon = 1;
3960                         }
3961
3962                         break;
3963
3964                 case IEEE80211_STYPE_PROBE_REQ:
3965                         if ((priv->iw_mode == IEEE80211_IF_TYPE_IBSS) &&
3966                             !iwl4965_is_associated(priv)) {
3967                                 DECLARE_MAC_BUF(mac1);
3968                                 DECLARE_MAC_BUF(mac2);
3969                                 DECLARE_MAC_BUF(mac3);
3970
3971                                 IWL_DEBUG_DROP("Dropping (non network): "
3972                                                "%s, %s, %s\n",
3973                                                print_mac(mac1, header->addr1),
3974                                                print_mac(mac2, header->addr2),
3975                                                print_mac(mac3, header->addr3));
3976                                 return;
3977                         }
3978                 }
3979                 iwl4965_handle_data_packet(priv, 0, include_phy, rxb, &rx_status);
3980                 break;
3981
3982         case IEEE80211_FTYPE_CTL:
3983 #ifdef CONFIG_IWL4965_HT
3984                 switch (fc & IEEE80211_FCTL_STYPE) {
3985                 case IEEE80211_STYPE_BACK_REQ:
3986                         IWL_DEBUG_HT("IEEE80211_STYPE_BACK_REQ arrived\n");
3987                         iwl4965_handle_data_packet(priv, 0, include_phy,
3988                                                 rxb, &rx_status);
3989                         break;
3990                 default:
3991                         break;
3992                 }
3993 #endif
3994                 break;
3995
3996         case IEEE80211_FTYPE_DATA: {
3997                 DECLARE_MAC_BUF(mac1);
3998                 DECLARE_MAC_BUF(mac2);
3999                 DECLARE_MAC_BUF(mac3);
4000
4001                 if (priv->iw_mode == IEEE80211_IF_TYPE_AP)
4002                         iwl4965_update_ps_mode(priv, fc  & IEEE80211_FCTL_PM,
4003                                                 header->addr2);
4004
4005                 if (unlikely(!network_packet))
4006                         IWL_DEBUG_DROP("Dropping (non network): "
4007                                        "%s, %s, %s\n",
4008                                        print_mac(mac1, header->addr1),
4009                                        print_mac(mac2, header->addr2),
4010                                        print_mac(mac3, header->addr3));
4011                 else if (unlikely(iwl4965_is_duplicate_packet(priv, header)))
4012                         IWL_DEBUG_DROP("Dropping (dup): %s, %s, %s\n",
4013                                        print_mac(mac1, header->addr1),
4014                                        print_mac(mac2, header->addr2),
4015                                        print_mac(mac3, header->addr3));
4016                 else
4017                         iwl4965_handle_data_packet(priv, 1, include_phy, rxb,
4018                                                    &rx_status);
4019                 break;
4020         }
4021         default:
4022                 break;
4023
4024         }
4025 }
4026
4027 /* Cache phy data (Rx signal strength, etc) for HT frame (REPLY_RX_PHY_CMD).
4028  * This will be used later in iwl4965_rx_reply_rx() for REPLY_RX_MPDU_CMD. */
4029 static void iwl4965_rx_reply_rx_phy(struct iwl_priv *priv,
4030                                     struct iwl4965_rx_mem_buffer *rxb)
4031 {
4032         struct iwl4965_rx_packet *pkt = (void *)rxb->skb->data;
4033         priv->last_phy_res[0] = 1;
4034         memcpy(&priv->last_phy_res[1], &(pkt->u.raw[0]),
4035                sizeof(struct iwl4965_rx_phy_res));
4036 }
4037
4038 static void iwl4965_rx_missed_beacon_notif(struct iwl_priv *priv,
4039                                            struct iwl4965_rx_mem_buffer *rxb)
4040
4041 {
4042 #ifdef CONFIG_IWL4965_SENSITIVITY
4043         struct iwl4965_rx_packet *pkt = (void *)rxb->skb->data;
4044         struct iwl4965_missed_beacon_notif *missed_beacon;
4045
4046         missed_beacon = &pkt->u.missed_beacon;
4047         if (le32_to_cpu(missed_beacon->consequtive_missed_beacons) > 5) {
4048                 IWL_DEBUG_CALIB("missed bcn cnsq %d totl %d rcd %d expctd %d\n",
4049                     le32_to_cpu(missed_beacon->consequtive_missed_beacons),
4050                     le32_to_cpu(missed_beacon->total_missed_becons),
4051                     le32_to_cpu(missed_beacon->num_recvd_beacons),
4052                     le32_to_cpu(missed_beacon->num_expected_beacons));
4053                 priv->sensitivity_data.state = IWL_SENS_CALIB_NEED_REINIT;
4054                 if (unlikely(!test_bit(STATUS_SCANNING, &priv->status)))
4055                         queue_work(priv->workqueue, &priv->sensitivity_work);
4056         }
4057 #endif /*CONFIG_IWL4965_SENSITIVITY*/
4058 }
4059
4060 #ifdef CONFIG_IWL4965_HT
4061
4062 /**
4063  * iwl4965_sta_modify_enable_tid_tx - Enable Tx for this TID in station table
4064  */
4065 static void iwl4965_sta_modify_enable_tid_tx(struct iwl_priv *priv,
4066                                          int sta_id, int tid)
4067 {
4068         unsigned long flags;
4069
4070         /* Remove "disable" flag, to enable Tx for this TID */
4071         spin_lock_irqsave(&priv->sta_lock, flags);
4072         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_TID_DISABLE_TX;
4073         priv->stations[sta_id].sta.tid_disable_tx &= cpu_to_le16(~(1 << tid));
4074         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
4075         spin_unlock_irqrestore(&priv->sta_lock, flags);
4076
4077         iwl4965_send_add_station(priv, &priv->stations[sta_id].sta, CMD_ASYNC);
4078 }
4079
4080 /**
4081  * iwl4965_tx_status_reply_compressed_ba - Update tx status from block-ack
4082  *
4083  * Go through block-ack's bitmap of ACK'd frames, update driver's record of
4084  * ACK vs. not.  This gets sent to mac80211, then to rate scaling algo.
4085  */
4086 static int iwl4965_tx_status_reply_compressed_ba(struct iwl_priv *priv,
4087                                                  struct iwl4965_ht_agg *agg,
4088                                                  struct iwl4965_compressed_ba_resp*
4089                                                  ba_resp)
4090
4091 {
4092         int i, sh, ack;
4093         u16 seq_ctl = le16_to_cpu(ba_resp->seq_ctl);
4094         u16 scd_flow = le16_to_cpu(ba_resp->scd_flow);
4095         u64 bitmap;
4096         int successes = 0;
4097         struct ieee80211_tx_status *tx_status;
4098
4099         if (unlikely(!agg->wait_for_ba))  {
4100                 IWL_ERROR("Received BA when not expected\n");
4101                 return -EINVAL;
4102         }
4103
4104         /* Mark that the expected block-ack response arrived */
4105         agg->wait_for_ba = 0;
4106         IWL_DEBUG_TX_REPLY("BA %d %d\n", agg->start_idx, ba_resp->seq_ctl);
4107
4108         /* Calculate shift to align block-ack bits with our Tx window bits */
4109         sh = agg->start_idx - SEQ_TO_INDEX(seq_ctl>>4);
4110         if (sh < 0) /* tbw something is wrong with indices */
4111                 sh += 0x100;
4112
4113         /* don't use 64-bit values for now */
4114         bitmap = le64_to_cpu(ba_resp->bitmap) >> sh;
4115
4116         if (agg->frame_count > (64 - sh)) {
4117                 IWL_DEBUG_TX_REPLY("more frames than bitmap size");
4118                 return -1;
4119         }
4120
4121         /* check for success or failure according to the
4122          * transmitted bitmap and block-ack bitmap */
4123         bitmap &= agg->bitmap;
4124
4125         /* For each frame attempted in aggregation,
4126          * update driver's record of tx frame's status. */
4127         for (i = 0; i < agg->frame_count ; i++) {
4128                 ack = bitmap & (1 << i);
4129                 successes += !!ack;
4130                 IWL_DEBUG_TX_REPLY("%s ON i=%d idx=%d raw=%d\n",
4131                         ack? "ACK":"NACK", i, (agg->start_idx + i) & 0xff,
4132                         agg->start_idx + i);
4133         }
4134
4135         tx_status = &priv->txq[scd_flow].txb[agg->start_idx].status;
4136         tx_status->flags = IEEE80211_TX_STATUS_ACK;
4137         tx_status->flags |= IEEE80211_TX_STATUS_AMPDU;
4138         tx_status->ampdu_ack_map = successes;
4139         tx_status->ampdu_ack_len = agg->frame_count;
4140         iwl4965_hwrate_to_tx_control(priv, agg->rate_n_flags,
4141                                      &tx_status->control);
4142
4143         IWL_DEBUG_TX_REPLY("Bitmap %llx\n", (unsigned long long)bitmap);
4144
4145         return 0;
4146 }
4147
4148 /**
4149  * iwl4965_tx_queue_stop_scheduler - Stop queue, but keep configuration
4150  */
4151 static void iwl4965_tx_queue_stop_scheduler(struct iwl_priv *priv,
4152                                             u16 txq_id)
4153 {
4154         /* Simply stop the queue, but don't change any configuration;
4155          * the SCD_ACT_EN bit is the write-enable mask for the ACTIVE bit. */
4156         iwl4965_write_prph(priv,
4157                 KDR_SCD_QUEUE_STATUS_BITS(txq_id),
4158                 (0 << SCD_QUEUE_STTS_REG_POS_ACTIVE)|
4159                 (1 << SCD_QUEUE_STTS_REG_POS_SCD_ACT_EN));
4160 }
4161
4162 /**
4163  * txq_id must be greater than IWL_BACK_QUEUE_FIRST_ID
4164  * priv->lock must be held by the caller
4165  */
4166 static int iwl4965_tx_queue_agg_disable(struct iwl_priv *priv, u16 txq_id,
4167                                         u16 ssn_idx, u8 tx_fifo)
4168 {
4169         int ret = 0;
4170
4171         if (IWL_BACK_QUEUE_FIRST_ID > txq_id) {
4172                 IWL_WARNING("queue number too small: %d, must be > %d\n",
4173                                 txq_id, IWL_BACK_QUEUE_FIRST_ID);
4174                 return -EINVAL;
4175         }
4176
4177         ret = iwl4965_grab_nic_access(priv);
4178         if (ret)
4179                 return ret;
4180
4181         iwl4965_tx_queue_stop_scheduler(priv, txq_id);
4182
4183         iwl4965_clear_bits_prph(priv, KDR_SCD_QUEUECHAIN_SEL, (1 << txq_id));
4184
4185         priv->txq[txq_id].q.read_ptr = (ssn_idx & 0xff);
4186         priv->txq[txq_id].q.write_ptr = (ssn_idx & 0xff);
4187         /* supposes that ssn_idx is valid (!= 0xFFF) */
4188         iwl4965_set_wr_ptrs(priv, txq_id, ssn_idx);
4189
4190         iwl4965_clear_bits_prph(priv, KDR_SCD_INTERRUPT_MASK, (1 << txq_id));
4191         iwl4965_txq_ctx_deactivate(priv, txq_id);
4192         iwl4965_tx_queue_set_status(priv, &priv->txq[txq_id], tx_fifo, 0);
4193
4194         iwl4965_release_nic_access(priv);
4195
4196         return 0;
4197 }
4198
4199 int iwl4965_check_empty_hw_queue(struct iwl_priv *priv, int sta_id,
4200                                          u8 tid, int txq_id)
4201 {
4202         struct iwl4965_queue *q = &priv->txq[txq_id].q;
4203         u8 *addr = priv->stations[sta_id].sta.sta.addr;
4204         struct iwl4965_tid_data *tid_data = &priv->stations[sta_id].tid[tid];
4205
4206         switch (priv->stations[sta_id].tid[tid].agg.state) {
4207         case IWL_EMPTYING_HW_QUEUE_DELBA:
4208                 /* We are reclaiming the last packet of the */
4209                 /* aggregated HW queue */
4210                 if (txq_id  == tid_data->agg.txq_id &&
4211                     q->read_ptr == q->write_ptr) {
4212                         u16 ssn = SEQ_TO_SN(tid_data->seq_number);
4213                         int tx_fifo = default_tid_to_tx_fifo[tid];
4214                         IWL_DEBUG_HT("HW queue empty: continue DELBA flow\n");
4215                         iwl4965_tx_queue_agg_disable(priv, txq_id,
4216                                                      ssn, tx_fifo);
4217                         tid_data->agg.state = IWL_AGG_OFF;
4218                         ieee80211_stop_tx_ba_cb_irqsafe(priv->hw, addr, tid);
4219                 }
4220                 break;
4221         case IWL_EMPTYING_HW_QUEUE_ADDBA:
4222                 /* We are reclaiming the last packet of the queue */
4223                 if (tid_data->tfds_in_queue == 0) {
4224                         IWL_DEBUG_HT("HW queue empty: continue ADDBA flow\n");
4225                         tid_data->agg.state = IWL_AGG_ON;
4226                         ieee80211_start_tx_ba_cb_irqsafe(priv->hw, addr, tid);
4227                 }
4228                 break;
4229         }
4230         return 0;
4231 }
4232
4233 /**
4234  * iwl4965_queue_dec_wrap - Decrement queue index, wrap back to end if needed
4235  * @index -- current index
4236  * @n_bd -- total number of entries in queue (s/b power of 2)
4237  */
4238 static inline int iwl4965_queue_dec_wrap(int index, int n_bd)
4239 {
4240         return (index == 0) ? n_bd - 1 : index - 1;
4241 }
4242
4243 /**
4244  * iwl4965_rx_reply_compressed_ba - Handler for REPLY_COMPRESSED_BA
4245  *
4246  * Handles block-acknowledge notification from device, which reports success
4247  * of frames sent via aggregation.
4248  */
4249 static void iwl4965_rx_reply_compressed_ba(struct iwl_priv *priv,
4250                                            struct iwl4965_rx_mem_buffer *rxb)
4251 {
4252         struct iwl4965_rx_packet *pkt = (void *)rxb->skb->data;
4253         struct iwl4965_compressed_ba_resp *ba_resp = &pkt->u.compressed_ba;
4254         int index;
4255         struct iwl4965_tx_queue *txq = NULL;
4256         struct iwl4965_ht_agg *agg;
4257         DECLARE_MAC_BUF(mac);
4258
4259         /* "flow" corresponds to Tx queue */
4260         u16 scd_flow = le16_to_cpu(ba_resp->scd_flow);
4261
4262         /* "ssn" is start of block-ack Tx window, corresponds to index
4263          * (in Tx queue's circular buffer) of first TFD/frame in window */
4264         u16 ba_resp_scd_ssn = le16_to_cpu(ba_resp->scd_ssn);
4265
4266         if (scd_flow >= ARRAY_SIZE(priv->txq)) {
4267                 IWL_ERROR("BUG_ON scd_flow is bigger than number of queues");
4268                 return;
4269         }
4270
4271         txq = &priv->txq[scd_flow];
4272         agg = &priv->stations[ba_resp->sta_id].tid[ba_resp->tid].agg;
4273
4274         /* Find index just before block-ack window */
4275         index = iwl4965_queue_dec_wrap(ba_resp_scd_ssn & 0xff, txq->q.n_bd);
4276
4277         /* TODO: Need to get this copy more safely - now good for debug */
4278
4279         IWL_DEBUG_TX_REPLY("REPLY_COMPRESSED_BA [%d]Received from %s, "
4280                            "sta_id = %d\n",
4281                            agg->wait_for_ba,
4282                            print_mac(mac, (u8*) &ba_resp->sta_addr_lo32),
4283                            ba_resp->sta_id);
4284         IWL_DEBUG_TX_REPLY("TID = %d, SeqCtl = %d, bitmap = 0x%llx, scd_flow = "
4285                            "%d, scd_ssn = %d\n",
4286                            ba_resp->tid,
4287                            ba_resp->seq_ctl,
4288                            (unsigned long long)le64_to_cpu(ba_resp->bitmap),
4289                            ba_resp->scd_flow,
4290                            ba_resp->scd_ssn);
4291         IWL_DEBUG_TX_REPLY("DAT start_idx = %d, bitmap = 0x%llx \n",
4292                            agg->start_idx,
4293                            (unsigned long long)agg->bitmap);
4294
4295         /* Update driver's record of ACK vs. not for each frame in window */
4296         iwl4965_tx_status_reply_compressed_ba(priv, agg, ba_resp);
4297
4298         /* Release all TFDs before the SSN, i.e. all TFDs in front of
4299          * block-ack window (we assume that they've been successfully
4300          * transmitted ... if not, it's too late anyway). */
4301         if (txq->q.read_ptr != (ba_resp_scd_ssn & 0xff)) {
4302                 int freed = iwl4965_tx_queue_reclaim(priv, scd_flow, index);
4303                 priv->stations[ba_resp->sta_id].
4304                         tid[ba_resp->tid].tfds_in_queue -= freed;
4305                 if (iwl4965_queue_space(&txq->q) > txq->q.low_mark &&
4306                         priv->mac80211_registered &&
4307                         agg->state != IWL_EMPTYING_HW_QUEUE_DELBA)
4308                         ieee80211_wake_queue(priv->hw, scd_flow);
4309                 iwl4965_check_empty_hw_queue(priv, ba_resp->sta_id,
4310                         ba_resp->tid, scd_flow);
4311         }
4312 }
4313
4314 /**
4315  * iwl4965_tx_queue_set_q2ratid - Map unique receiver/tid combination to a queue
4316  */
4317 static int iwl4965_tx_queue_set_q2ratid(struct iwl_priv *priv, u16 ra_tid,
4318                                         u16 txq_id)
4319 {
4320         u32 tbl_dw_addr;
4321         u32 tbl_dw;
4322         u16 scd_q2ratid;
4323
4324         scd_q2ratid = ra_tid & SCD_QUEUE_RA_TID_MAP_RATID_MSK;
4325
4326         tbl_dw_addr = priv->scd_base_addr +
4327                         SCD_TRANSLATE_TBL_OFFSET_QUEUE(txq_id);
4328
4329         tbl_dw = iwl4965_read_targ_mem(priv, tbl_dw_addr);
4330
4331         if (txq_id & 0x1)
4332                 tbl_dw = (scd_q2ratid << 16) | (tbl_dw & 0x0000FFFF);
4333         else
4334                 tbl_dw = scd_q2ratid | (tbl_dw & 0xFFFF0000);
4335
4336         iwl4965_write_targ_mem(priv, tbl_dw_addr, tbl_dw);
4337
4338         return 0;
4339 }
4340
4341
4342 /**
4343  * iwl4965_tx_queue_agg_enable - Set up & enable aggregation for selected queue
4344  *
4345  * NOTE:  txq_id must be greater than IWL_BACK_QUEUE_FIRST_ID,
4346  *        i.e. it must be one of the higher queues used for aggregation
4347  */
4348 static int iwl4965_tx_queue_agg_enable(struct iwl_priv *priv, int txq_id,
4349                                        int tx_fifo, int sta_id, int tid,
4350                                        u16 ssn_idx)
4351 {
4352         unsigned long flags;
4353         int rc;
4354         u16 ra_tid;
4355
4356         if (IWL_BACK_QUEUE_FIRST_ID > txq_id)
4357                 IWL_WARNING("queue number too small: %d, must be > %d\n",
4358                         txq_id, IWL_BACK_QUEUE_FIRST_ID);
4359
4360         ra_tid = BUILD_RAxTID(sta_id, tid);
4361
4362         /* Modify device's station table to Tx this TID */
4363         iwl4965_sta_modify_enable_tid_tx(priv, sta_id, tid);
4364
4365         spin_lock_irqsave(&priv->lock, flags);
4366         rc = iwl4965_grab_nic_access(priv);
4367         if (rc) {
4368                 spin_unlock_irqrestore(&priv->lock, flags);
4369                 return rc;
4370         }
4371
4372         /* Stop this Tx queue before configuring it */
4373         iwl4965_tx_queue_stop_scheduler(priv, txq_id);
4374
4375         /* Map receiver-address / traffic-ID to this queue */
4376         iwl4965_tx_queue_set_q2ratid(priv, ra_tid, txq_id);
4377
4378         /* Set this queue as a chain-building queue */
4379         iwl4965_set_bits_prph(priv, KDR_SCD_QUEUECHAIN_SEL, (1 << txq_id));
4380
4381         /* Place first TFD at index corresponding to start sequence number.
4382          * Assumes that ssn_idx is valid (!= 0xFFF) */
4383         priv->txq[txq_id].q.read_ptr = (ssn_idx & 0xff);
4384         priv->txq[txq_id].q.write_ptr = (ssn_idx & 0xff);
4385         iwl4965_set_wr_ptrs(priv, txq_id, ssn_idx);
4386
4387         /* Set up Tx window size and frame limit for this queue */
4388         iwl4965_write_targ_mem(priv,
4389                         priv->scd_base_addr + SCD_CONTEXT_QUEUE_OFFSET(txq_id),
4390                         (SCD_WIN_SIZE << SCD_QUEUE_CTX_REG1_WIN_SIZE_POS) &
4391                         SCD_QUEUE_CTX_REG1_WIN_SIZE_MSK);
4392
4393         iwl4965_write_targ_mem(priv, priv->scd_base_addr +
4394                         SCD_CONTEXT_QUEUE_OFFSET(txq_id) + sizeof(u32),
4395                         (SCD_FRAME_LIMIT << SCD_QUEUE_CTX_REG2_FRAME_LIMIT_POS)
4396                         & SCD_QUEUE_CTX_REG2_FRAME_LIMIT_MSK);
4397
4398         iwl4965_set_bits_prph(priv, KDR_SCD_INTERRUPT_MASK, (1 << txq_id));
4399
4400         /* Set up Status area in SRAM, map to Tx DMA/FIFO, activate the queue */
4401         iwl4965_tx_queue_set_status(priv, &priv->txq[txq_id], tx_fifo, 1);
4402
4403         iwl4965_release_nic_access(priv);
4404         spin_unlock_irqrestore(&priv->lock, flags);
4405
4406         return 0;
4407 }
4408
4409 #endif /* CONFIG_IWL4965_HT */
4410
4411 /**
4412  * iwl4965_add_station - Initialize a station's hardware rate table
4413  *
4414  * The uCode's station table contains a table of fallback rates
4415  * for automatic fallback during transmission.
4416  *
4417  * NOTE: This sets up a default set of values.  These will be replaced later
4418  *       if the driver's iwl-4965-rs rate scaling algorithm is used, instead of
4419  *       rc80211_simple.
4420  *
4421  * NOTE: Run REPLY_ADD_STA command to set up station table entry, before
4422  *       calling this function (which runs REPLY_TX_LINK_QUALITY_CMD,
4423  *       which requires station table entry to exist).
4424  */
4425 void iwl4965_add_station(struct iwl_priv *priv, const u8 *addr, int is_ap)
4426 {
4427         int i, r;
4428         struct iwl4965_link_quality_cmd link_cmd = {
4429                 .reserved1 = 0,
4430         };
4431         u16 rate_flags;
4432
4433         /* Set up the rate scaling to start at selected rate, fall back
4434          * all the way down to 1M in IEEE order, and then spin on 1M */
4435         if (is_ap)
4436                 r = IWL_RATE_54M_INDEX;
4437         else if (priv->band == IEEE80211_BAND_5GHZ)
4438                 r = IWL_RATE_6M_INDEX;
4439         else
4440                 r = IWL_RATE_1M_INDEX;
4441
4442         for (i = 0; i < LINK_QUAL_MAX_RETRY_NUM; i++) {
4443                 rate_flags = 0;
4444                 if (r >= IWL_FIRST_CCK_RATE && r <= IWL_LAST_CCK_RATE)
4445                         rate_flags |= RATE_MCS_CCK_MSK;
4446
4447                 /* Use Tx antenna B only */
4448                 rate_flags |= RATE_MCS_ANT_B_MSK;
4449                 rate_flags &= ~RATE_MCS_ANT_A_MSK;
4450
4451                 link_cmd.rs_table[i].rate_n_flags =
4452                         iwl4965_hw_set_rate_n_flags(iwl4965_rates[r].plcp, rate_flags);
4453                 r = iwl4965_get_prev_ieee_rate(r);
4454         }
4455
4456         link_cmd.general_params.single_stream_ant_msk = 2;
4457         link_cmd.general_params.dual_stream_ant_msk = 3;
4458         link_cmd.agg_params.agg_dis_start_th = 3;
4459         link_cmd.agg_params.agg_time_limit = cpu_to_le16(4000);
4460
4461         /* Update the rate scaling for control frame Tx to AP */
4462         link_cmd.sta_id = is_ap ? IWL_AP_ID : priv->hw_setting.bcast_sta_id;
4463
4464         iwl4965_send_cmd_pdu(priv, REPLY_TX_LINK_QUALITY_CMD, sizeof(link_cmd),
4465                          &link_cmd);
4466 }
4467
4468 #ifdef CONFIG_IWL4965_HT
4469
4470 static u8 iwl4965_is_channel_extension(struct iwl_priv *priv,
4471                                        enum ieee80211_band band,
4472                                        u16 channel, u8 extension_chan_offset)
4473 {
4474         const struct iwl4965_channel_info *ch_info;
4475
4476         ch_info = iwl4965_get_channel_info(priv, band, channel);
4477         if (!is_channel_valid(ch_info))
4478                 return 0;
4479
4480         if (extension_chan_offset == IWL_EXT_CHANNEL_OFFSET_NONE)
4481                 return 0;
4482
4483         if ((ch_info->fat_extension_channel == extension_chan_offset) ||
4484             (ch_info->fat_extension_channel == HT_IE_EXT_CHANNEL_MAX))
4485                 return 1;
4486
4487         return 0;
4488 }
4489
4490 static u8 iwl4965_is_fat_tx_allowed(struct iwl_priv *priv,
4491                                 struct ieee80211_ht_info *sta_ht_inf)
4492 {
4493         struct iwl_ht_info *iwl_ht_conf = &priv->current_ht_config;
4494
4495         if ((!iwl_ht_conf->is_ht) ||
4496            (iwl_ht_conf->supported_chan_width != IWL_CHANNEL_WIDTH_40MHZ) ||
4497            (iwl_ht_conf->extension_chan_offset == IWL_EXT_CHANNEL_OFFSET_NONE))
4498                 return 0;
4499
4500         if (sta_ht_inf) {
4501                 if ((!sta_ht_inf->ht_supported) ||
4502                    (!(sta_ht_inf->cap & IEEE80211_HT_CAP_SUP_WIDTH)))
4503                         return 0;
4504         }
4505
4506         return (iwl4965_is_channel_extension(priv, priv->band,
4507                                          iwl_ht_conf->control_channel,
4508                                          iwl_ht_conf->extension_chan_offset));
4509 }
4510
4511 void iwl4965_set_rxon_ht(struct iwl_priv *priv, struct iwl_ht_info *ht_info)
4512 {
4513         struct iwl4965_rxon_cmd *rxon = &priv->staging_rxon;
4514         u32 val;
4515
4516         if (!ht_info->is_ht)
4517                 return;
4518
4519         /* Set up channel bandwidth:  20 MHz only, or 20/40 mixed if fat ok */
4520         if (iwl4965_is_fat_tx_allowed(priv, NULL))
4521                 rxon->flags |= RXON_FLG_CHANNEL_MODE_MIXED_MSK;
4522         else
4523                 rxon->flags &= ~(RXON_FLG_CHANNEL_MODE_MIXED_MSK |
4524                                  RXON_FLG_CHANNEL_MODE_PURE_40_MSK);
4525
4526         if (le16_to_cpu(rxon->channel) != ht_info->control_channel) {
4527                 IWL_DEBUG_ASSOC("control diff than current %d %d\n",
4528                                 le16_to_cpu(rxon->channel),
4529                                 ht_info->control_channel);
4530                 rxon->channel = cpu_to_le16(ht_info->control_channel);
4531                 return;
4532         }
4533
4534         /* Note: control channel is opposite of extension channel */
4535         switch (ht_info->extension_chan_offset) {
4536         case IWL_EXT_CHANNEL_OFFSET_ABOVE:
4537                 rxon->flags &= ~(RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK);
4538                 break;
4539         case IWL_EXT_CHANNEL_OFFSET_BELOW:
4540                 rxon->flags |= RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
4541                 break;
4542         case IWL_EXT_CHANNEL_OFFSET_NONE:
4543         default:
4544                 rxon->flags &= ~RXON_FLG_CHANNEL_MODE_MIXED_MSK;
4545                 break;
4546         }
4547
4548         val = ht_info->ht_protection;
4549
4550         rxon->flags |= cpu_to_le32(val << RXON_FLG_HT_OPERATING_MODE_POS);
4551
4552         iwl4965_set_rxon_chain(priv);
4553
4554         IWL_DEBUG_ASSOC("supported HT rate 0x%X %X "
4555                         "rxon flags 0x%X operation mode :0x%X "
4556                         "extension channel offset 0x%x "
4557                         "control chan %d\n",
4558                         ht_info->supp_mcs_set[0], ht_info->supp_mcs_set[1],
4559                         le32_to_cpu(rxon->flags), ht_info->ht_protection,
4560                         ht_info->extension_chan_offset,
4561                         ht_info->control_channel);
4562         return;
4563 }
4564
4565 void iwl4965_set_ht_add_station(struct iwl_priv *priv, u8 index,
4566                                 struct ieee80211_ht_info *sta_ht_inf)
4567 {
4568         __le32 sta_flags;
4569         u8 mimo_ps_mode;
4570
4571         if (!sta_ht_inf || !sta_ht_inf->ht_supported)
4572                 goto done;
4573
4574         mimo_ps_mode = (sta_ht_inf->cap & IEEE80211_HT_CAP_MIMO_PS) >> 2;
4575
4576         sta_flags = priv->stations[index].sta.station_flags;
4577
4578         sta_flags &= ~(STA_FLG_RTS_MIMO_PROT_MSK | STA_FLG_MIMO_DIS_MSK);
4579
4580         switch (mimo_ps_mode) {
4581         case WLAN_HT_CAP_MIMO_PS_STATIC:
4582                 sta_flags |= STA_FLG_MIMO_DIS_MSK;
4583                 break;
4584         case WLAN_HT_CAP_MIMO_PS_DYNAMIC:
4585                 sta_flags |= STA_FLG_RTS_MIMO_PROT_MSK;
4586                 break;
4587         case WLAN_HT_CAP_MIMO_PS_DISABLED:
4588                 break;
4589         default:
4590                 IWL_WARNING("Invalid MIMO PS mode %d", mimo_ps_mode);
4591                 break;
4592         }
4593
4594         sta_flags |= cpu_to_le32(
4595               (u32)sta_ht_inf->ampdu_factor << STA_FLG_MAX_AGG_SIZE_POS);
4596
4597         sta_flags |= cpu_to_le32(
4598               (u32)sta_ht_inf->ampdu_density << STA_FLG_AGG_MPDU_DENSITY_POS);
4599
4600         if (iwl4965_is_fat_tx_allowed(priv, sta_ht_inf))
4601                 sta_flags |= STA_FLG_FAT_EN_MSK;
4602         else
4603                 sta_flags &= ~STA_FLG_FAT_EN_MSK;
4604
4605         priv->stations[index].sta.station_flags = sta_flags;
4606  done:
4607         return;
4608 }
4609
4610 static void iwl4965_sta_modify_add_ba_tid(struct iwl_priv *priv,
4611                                           int sta_id, int tid, u16 ssn)
4612 {
4613         unsigned long flags;
4614
4615         spin_lock_irqsave(&priv->sta_lock, flags);
4616         priv->stations[sta_id].sta.station_flags_msk = 0;
4617         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_ADDBA_TID_MSK;
4618         priv->stations[sta_id].sta.add_immediate_ba_tid = (u8)tid;
4619         priv->stations[sta_id].sta.add_immediate_ba_ssn = cpu_to_le16(ssn);
4620         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
4621         spin_unlock_irqrestore(&priv->sta_lock, flags);
4622
4623         iwl4965_send_add_station(priv, &priv->stations[sta_id].sta, CMD_ASYNC);
4624 }
4625
4626 static void iwl4965_sta_modify_del_ba_tid(struct iwl_priv *priv,
4627                                           int sta_id, int tid)
4628 {
4629         unsigned long flags;
4630
4631         spin_lock_irqsave(&priv->sta_lock, flags);
4632         priv->stations[sta_id].sta.station_flags_msk = 0;
4633         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_DELBA_TID_MSK;
4634         priv->stations[sta_id].sta.remove_immediate_ba_tid = (u8)tid;
4635         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
4636         spin_unlock_irqrestore(&priv->sta_lock, flags);
4637
4638         iwl4965_send_add_station(priv, &priv->stations[sta_id].sta, CMD_ASYNC);
4639 }
4640
4641 /*
4642  * Find first available (lowest unused) Tx Queue, mark it "active".
4643  * Called only when finding queue for aggregation.
4644  * Should never return anything < 7, because they should already
4645  * be in use as EDCA AC (0-3), Command (4), HCCA (5, 6).
4646  */
4647 static int iwl4965_txq_ctx_activate_free(struct iwl_priv *priv)
4648 {
4649         int txq_id;
4650
4651         for (txq_id = 0; txq_id < priv->hw_setting.max_txq_num; txq_id++)
4652                 if (!test_and_set_bit(txq_id, &priv->txq_ctx_active_msk))
4653                         return txq_id;
4654         return -1;
4655 }
4656
4657 static int iwl4965_mac_ht_tx_agg_start(struct ieee80211_hw *hw, const u8 *da,
4658                                        u16 tid, u16 *start_seq_num)
4659 {
4660         struct iwl_priv *priv = hw->priv;
4661         int sta_id;
4662         int tx_fifo;
4663         int txq_id;
4664         int ssn = -1;
4665         int ret = 0;
4666         unsigned long flags;
4667         struct iwl4965_tid_data *tid_data;
4668         DECLARE_MAC_BUF(mac);
4669
4670         if (likely(tid < ARRAY_SIZE(default_tid_to_tx_fifo)))
4671                 tx_fifo = default_tid_to_tx_fifo[tid];
4672         else
4673                 return -EINVAL;
4674
4675         IWL_WARNING("%s on da = %s tid = %d\n",
4676                         __func__, print_mac(mac, da), tid);
4677
4678         sta_id = iwl4965_hw_find_station(priv, da);
4679         if (sta_id == IWL_INVALID_STATION)
4680                 return -ENXIO;
4681
4682         if (priv->stations[sta_id].tid[tid].agg.state != IWL_AGG_OFF) {
4683                 IWL_ERROR("Start AGG when state is not IWL_AGG_OFF !\n");
4684                 return -ENXIO;
4685         }
4686
4687         txq_id = iwl4965_txq_ctx_activate_free(priv);
4688         if (txq_id == -1)
4689                 return -ENXIO;
4690
4691         spin_lock_irqsave(&priv->sta_lock, flags);
4692         tid_data = &priv->stations[sta_id].tid[tid];
4693         ssn = SEQ_TO_SN(tid_data->seq_number);
4694         tid_data->agg.txq_id = txq_id;
4695         spin_unlock_irqrestore(&priv->sta_lock, flags);
4696
4697         *start_seq_num = ssn;
4698         ret = iwl4965_tx_queue_agg_enable(priv, txq_id, tx_fifo,
4699                                           sta_id, tid, ssn);
4700         if (ret)
4701                 return ret;
4702
4703         ret = 0;
4704         if (tid_data->tfds_in_queue == 0) {
4705                 printk(KERN_ERR "HW queue is empty\n");
4706                 tid_data->agg.state = IWL_AGG_ON;
4707                 ieee80211_start_tx_ba_cb_irqsafe(hw, da, tid);
4708         } else {
4709                 IWL_DEBUG_HT("HW queue is NOT empty: %d packets in HW queue\n",
4710                                 tid_data->tfds_in_queue);
4711                 tid_data->agg.state = IWL_EMPTYING_HW_QUEUE_ADDBA;
4712         }
4713         return ret;
4714 }
4715
4716 static int iwl4965_mac_ht_tx_agg_stop(struct ieee80211_hw *hw, const u8 *da,
4717                                       u16 tid)
4718 {
4719
4720         struct iwl_priv *priv = hw->priv;
4721         int tx_fifo_id, txq_id, sta_id, ssn = -1;
4722         struct iwl4965_tid_data *tid_data;
4723         int ret, write_ptr, read_ptr;
4724         unsigned long flags;
4725         DECLARE_MAC_BUF(mac);
4726
4727         if (!da) {
4728                 IWL_ERROR("da = NULL\n");
4729                 return -EINVAL;
4730         }
4731
4732         if (likely(tid < ARRAY_SIZE(default_tid_to_tx_fifo)))
4733                 tx_fifo_id = default_tid_to_tx_fifo[tid];
4734         else
4735                 return -EINVAL;
4736
4737         sta_id = iwl4965_hw_find_station(priv, da);
4738
4739         if (sta_id == IWL_INVALID_STATION)
4740                 return -ENXIO;
4741
4742         if (priv->stations[sta_id].tid[tid].agg.state != IWL_AGG_ON)
4743                 IWL_WARNING("Stopping AGG while state not IWL_AGG_ON\n");
4744
4745         tid_data = &priv->stations[sta_id].tid[tid];
4746         ssn = (tid_data->seq_number & IEEE80211_SCTL_SEQ) >> 4;
4747         txq_id = tid_data->agg.txq_id;
4748         write_ptr = priv->txq[txq_id].q.write_ptr;
4749         read_ptr = priv->txq[txq_id].q.read_ptr;
4750
4751         /* The queue is not empty */
4752         if (write_ptr != read_ptr) {
4753                 IWL_DEBUG_HT("Stopping a non empty AGG HW QUEUE\n");
4754                 priv->stations[sta_id].tid[tid].agg.state =
4755                                 IWL_EMPTYING_HW_QUEUE_DELBA;
4756                 return 0;
4757         }
4758
4759         IWL_DEBUG_HT("HW queue empty\n");;
4760         priv->stations[sta_id].tid[tid].agg.state = IWL_AGG_OFF;
4761
4762         spin_lock_irqsave(&priv->lock, flags);
4763         ret = iwl4965_tx_queue_agg_disable(priv, txq_id, ssn, tx_fifo_id);
4764         spin_unlock_irqrestore(&priv->lock, flags);
4765
4766         if (ret)
4767                 return ret;
4768
4769         ieee80211_stop_tx_ba_cb_irqsafe(priv->hw, da, tid);
4770
4771         IWL_DEBUG_INFO("iwl4965_mac_ht_tx_agg_stop on da=%s tid=%d\n",
4772                         print_mac(mac, da), tid);
4773
4774         return 0;
4775 }
4776
4777 int iwl4965_mac_ampdu_action(struct ieee80211_hw *hw,
4778                              enum ieee80211_ampdu_mlme_action action,
4779                              const u8 *addr, u16 tid, u16 *ssn)
4780 {
4781         struct iwl_priv *priv = hw->priv;
4782         int sta_id;
4783         DECLARE_MAC_BUF(mac);
4784
4785         IWL_DEBUG_HT("A-MPDU action on da=%s tid=%d ",
4786                         print_mac(mac, addr), tid);
4787         sta_id = iwl4965_hw_find_station(priv, addr);
4788         switch (action) {
4789         case IEEE80211_AMPDU_RX_START:
4790                 IWL_DEBUG_HT("start Rx\n");
4791                 iwl4965_sta_modify_add_ba_tid(priv, sta_id, tid, *ssn);
4792                 break;
4793         case IEEE80211_AMPDU_RX_STOP:
4794                 IWL_DEBUG_HT("stop Rx\n");
4795                 iwl4965_sta_modify_del_ba_tid(priv, sta_id, tid);
4796                 break;
4797         case IEEE80211_AMPDU_TX_START:
4798                 IWL_DEBUG_HT("start Tx\n");
4799                 return iwl4965_mac_ht_tx_agg_start(hw, addr, tid, ssn);
4800         case IEEE80211_AMPDU_TX_STOP:
4801                 IWL_DEBUG_HT("stop Tx\n");
4802                 return iwl4965_mac_ht_tx_agg_stop(hw, addr, tid);
4803         default:
4804                 IWL_DEBUG_HT("unknown\n");
4805                 return -EINVAL;
4806                 break;
4807         }
4808         return 0;
4809 }
4810
4811 #endif /* CONFIG_IWL4965_HT */
4812
4813 /* Set up 4965-specific Rx frame reply handlers */
4814 void iwl4965_hw_rx_handler_setup(struct iwl_priv *priv)
4815 {
4816         /* Legacy Rx frames */
4817         priv->rx_handlers[REPLY_4965_RX] = iwl4965_rx_reply_rx;
4818
4819         /* High-throughput (HT) Rx frames */
4820         priv->rx_handlers[REPLY_RX_PHY_CMD] = iwl4965_rx_reply_rx_phy;
4821         priv->rx_handlers[REPLY_RX_MPDU_CMD] = iwl4965_rx_reply_rx;
4822
4823         priv->rx_handlers[MISSED_BEACONS_NOTIFICATION] =
4824             iwl4965_rx_missed_beacon_notif;
4825
4826 #ifdef CONFIG_IWL4965_HT
4827         priv->rx_handlers[REPLY_COMPRESSED_BA] = iwl4965_rx_reply_compressed_ba;
4828 #endif /* CONFIG_IWL4965_HT */
4829 }
4830
4831 void iwl4965_hw_setup_deferred_work(struct iwl_priv *priv)
4832 {
4833         INIT_WORK(&priv->txpower_work, iwl4965_bg_txpower_work);
4834         INIT_WORK(&priv->statistics_work, iwl4965_bg_statistics_work);
4835 #ifdef CONFIG_IWL4965_SENSITIVITY
4836         INIT_WORK(&priv->sensitivity_work, iwl4965_bg_sensitivity_work);
4837 #endif
4838         init_timer(&priv->statistics_periodic);
4839         priv->statistics_periodic.data = (unsigned long)priv;
4840         priv->statistics_periodic.function = iwl4965_bg_statistics_periodic;
4841 }
4842
4843 void iwl4965_hw_cancel_deferred_work(struct iwl_priv *priv)
4844 {
4845         del_timer_sync(&priv->statistics_periodic);
4846
4847         cancel_delayed_work(&priv->init_alive_start);
4848 }
4849
4850 static struct iwl_lib_ops iwl4965_lib = {
4851         .eeprom_ops = {
4852                 .verify_signature  = iwlcore_eeprom_verify_signature,
4853                 .acquire_semaphore = iwlcore_eeprom_acquire_semaphore,
4854                 .release_semaphore = iwlcore_eeprom_release_semaphore,
4855         },
4856 };
4857
4858 static struct iwl_ops iwl4965_ops = {
4859         .lib = &iwl4965_lib,
4860 };
4861
4862 static struct iwl_cfg iwl4965_agn_cfg = {
4863         .name = "4965AGN",
4864         .fw_name = "iwlwifi-4965" IWL4965_UCODE_API ".ucode",
4865         .sku = IWL_SKU_A|IWL_SKU_G|IWL_SKU_N,
4866         .ops = &iwl4965_ops,
4867 };
4868
4869 struct pci_device_id iwl4965_hw_card_ids[] = {
4870         {IWL_PCI_DEVICE(0x4229, PCI_ANY_ID, iwl4965_agn_cfg)},
4871         {IWL_PCI_DEVICE(0x4230, PCI_ANY_ID, iwl4965_agn_cfg)},
4872         {0}
4873 };
4874
4875 MODULE_DEVICE_TABLE(pci, iwl4965_hw_card_ids);