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