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