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