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