PM / x86: Save/restore MISC_ENABLE register
[pandora-kernel.git] / drivers / net / wireless / iwlwifi / iwl-agn-lib.c
1 /******************************************************************************
2  *
3  * GPL LICENSE SUMMARY
4  *
5  * Copyright(c) 2008 - 2010 Intel Corporation. All rights reserved.
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of version 2 of the GNU General Public License as
9  * published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
19  * USA
20  *
21  * The full GNU General Public License is included in this distribution
22  * in the file called LICENSE.GPL.
23  *
24  * Contact Information:
25  *  Intel Linux Wireless <ilw@linux.intel.com>
26  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
27  *
28  *****************************************************************************/
29 #include <linux/etherdevice.h>
30 #include <linux/kernel.h>
31 #include <linux/module.h>
32 #include <linux/init.h>
33 #include <linux/sched.h>
34
35 #include "iwl-dev.h"
36 #include "iwl-core.h"
37 #include "iwl-io.h"
38 #include "iwl-helpers.h"
39 #include "iwl-agn-hw.h"
40 #include "iwl-agn.h"
41 #include "iwl-sta.h"
42
43 static inline u32 iwlagn_get_scd_ssn(struct iwl5000_tx_resp *tx_resp)
44 {
45         return le32_to_cpup((__le32 *)&tx_resp->status +
46                             tx_resp->frame_count) & MAX_SN;
47 }
48
49 static int iwlagn_tx_status_reply_tx(struct iwl_priv *priv,
50                                       struct iwl_ht_agg *agg,
51                                       struct iwl5000_tx_resp *tx_resp,
52                                       int txq_id, u16 start_idx)
53 {
54         u16 status;
55         struct agg_tx_status *frame_status = &tx_resp->status;
56         struct ieee80211_tx_info *info = NULL;
57         struct ieee80211_hdr *hdr = NULL;
58         u32 rate_n_flags = le32_to_cpu(tx_resp->rate_n_flags);
59         int i, sh, idx;
60         u16 seq;
61
62         if (agg->wait_for_ba)
63                 IWL_DEBUG_TX_REPLY(priv, "got tx response w/o block-ack\n");
64
65         agg->frame_count = tx_resp->frame_count;
66         agg->start_idx = start_idx;
67         agg->rate_n_flags = rate_n_flags;
68         agg->bitmap = 0;
69
70         /* # frames attempted by Tx command */
71         if (agg->frame_count == 1) {
72                 /* Only one frame was attempted; no block-ack will arrive */
73                 status = le16_to_cpu(frame_status[0].status);
74                 idx = start_idx;
75
76                 /* FIXME: code repetition */
77                 IWL_DEBUG_TX_REPLY(priv, "FrameCnt = %d, StartIdx=%d idx=%d\n",
78                                    agg->frame_count, agg->start_idx, idx);
79
80                 info = IEEE80211_SKB_CB(priv->txq[txq_id].txb[idx].skb[0]);
81                 info->status.rates[0].count = tx_resp->failure_frame + 1;
82                 info->flags &= ~IEEE80211_TX_CTL_AMPDU;
83                 info->flags |= iwl_tx_status_to_mac80211(status);
84                 iwlagn_hwrate_to_tx_control(priv, rate_n_flags, info);
85
86                 /* FIXME: code repetition end */
87
88                 IWL_DEBUG_TX_REPLY(priv, "1 Frame 0x%x failure :%d\n",
89                                     status & 0xff, tx_resp->failure_frame);
90                 IWL_DEBUG_TX_REPLY(priv, "Rate Info rate_n_flags=%x\n", rate_n_flags);
91
92                 agg->wait_for_ba = 0;
93         } else {
94                 /* Two or more frames were attempted; expect block-ack */
95                 u64 bitmap = 0;
96                 int start = agg->start_idx;
97
98                 /* Construct bit-map of pending frames within Tx window */
99                 for (i = 0; i < agg->frame_count; i++) {
100                         u16 sc;
101                         status = le16_to_cpu(frame_status[i].status);
102                         seq  = le16_to_cpu(frame_status[i].sequence);
103                         idx = SEQ_TO_INDEX(seq);
104                         txq_id = SEQ_TO_QUEUE(seq);
105
106                         if (status & (AGG_TX_STATE_FEW_BYTES_MSK |
107                                       AGG_TX_STATE_ABORT_MSK))
108                                 continue;
109
110                         IWL_DEBUG_TX_REPLY(priv, "FrameCnt = %d, txq_id=%d idx=%d\n",
111                                            agg->frame_count, txq_id, idx);
112
113                         hdr = iwl_tx_queue_get_hdr(priv, txq_id, idx);
114                         if (!hdr) {
115                                 IWL_ERR(priv,
116                                         "BUG_ON idx doesn't point to valid skb"
117                                         " idx=%d, txq_id=%d\n", idx, txq_id);
118                                 return -1;
119                         }
120
121                         sc = le16_to_cpu(hdr->seq_ctrl);
122                         if (idx != (SEQ_TO_SN(sc) & 0xff)) {
123                                 IWL_ERR(priv,
124                                         "BUG_ON idx doesn't match seq control"
125                                         " idx=%d, seq_idx=%d, seq=%d\n",
126                                           idx, SEQ_TO_SN(sc),
127                                           hdr->seq_ctrl);
128                                 return -1;
129                         }
130
131                         IWL_DEBUG_TX_REPLY(priv, "AGG Frame i=%d idx %d seq=%d\n",
132                                            i, idx, SEQ_TO_SN(sc));
133
134                         sh = idx - start;
135                         if (sh > 64) {
136                                 sh = (start - idx) + 0xff;
137                                 bitmap = bitmap << sh;
138                                 sh = 0;
139                                 start = idx;
140                         } else if (sh < -64)
141                                 sh  = 0xff - (start - idx);
142                         else if (sh < 0) {
143                                 sh = start - idx;
144                                 start = idx;
145                                 bitmap = bitmap << sh;
146                                 sh = 0;
147                         }
148                         bitmap |= 1ULL << sh;
149                         IWL_DEBUG_TX_REPLY(priv, "start=%d bitmap=0x%llx\n",
150                                            start, (unsigned long long)bitmap);
151                 }
152
153                 agg->bitmap = bitmap;
154                 agg->start_idx = start;
155                 IWL_DEBUG_TX_REPLY(priv, "Frames %d start_idx=%d bitmap=0x%llx\n",
156                                    agg->frame_count, agg->start_idx,
157                                    (unsigned long long)agg->bitmap);
158
159                 if (bitmap)
160                         agg->wait_for_ba = 1;
161         }
162         return 0;
163 }
164
165 void iwl_check_abort_status(struct iwl_priv *priv,
166                             u8 frame_count, u32 status)
167 {
168         if (frame_count == 1 && status == TX_STATUS_FAIL_RFKILL_FLUSH) {
169                 IWL_ERR(priv, "TODO: Implement Tx flush command!!!\n");
170         }
171 }
172
173 static void iwlagn_rx_reply_tx(struct iwl_priv *priv,
174                                 struct iwl_rx_mem_buffer *rxb)
175 {
176         struct iwl_rx_packet *pkt = rxb_addr(rxb);
177         u16 sequence = le16_to_cpu(pkt->hdr.sequence);
178         int txq_id = SEQ_TO_QUEUE(sequence);
179         int index = SEQ_TO_INDEX(sequence);
180         struct iwl_tx_queue *txq = &priv->txq[txq_id];
181         struct ieee80211_tx_info *info;
182         struct iwl5000_tx_resp *tx_resp = (void *)&pkt->u.raw[0];
183         u32  status = le16_to_cpu(tx_resp->status.status);
184         int tid;
185         int sta_id;
186         int freed;
187
188         if ((index >= txq->q.n_bd) || (iwl_queue_used(&txq->q, index) == 0)) {
189                 IWL_ERR(priv, "Read index for DMA queue txq_id (%d) index %d "
190                           "is out of range [0-%d] %d %d\n", txq_id,
191                           index, txq->q.n_bd, txq->q.write_ptr,
192                           txq->q.read_ptr);
193                 return;
194         }
195
196         info = IEEE80211_SKB_CB(txq->txb[txq->q.read_ptr].skb[0]);
197         memset(&info->status, 0, sizeof(info->status));
198
199         tid = (tx_resp->ra_tid & IWL50_TX_RES_TID_MSK) >> IWL50_TX_RES_TID_POS;
200         sta_id = (tx_resp->ra_tid & IWL50_TX_RES_RA_MSK) >> IWL50_TX_RES_RA_POS;
201
202         if (txq->sched_retry) {
203                 const u32 scd_ssn = iwlagn_get_scd_ssn(tx_resp);
204                 struct iwl_ht_agg *agg = NULL;
205
206                 agg = &priv->stations[sta_id].tid[tid].agg;
207
208                 iwlagn_tx_status_reply_tx(priv, agg, tx_resp, txq_id, index);
209
210                 /* check if BAR is needed */
211                 if ((tx_resp->frame_count == 1) && !iwl_is_tx_success(status))
212                         info->flags |= IEEE80211_TX_STAT_AMPDU_NO_BACK;
213
214                 if (txq->q.read_ptr != (scd_ssn & 0xff)) {
215                         index = iwl_queue_dec_wrap(scd_ssn & 0xff, txq->q.n_bd);
216                         IWL_DEBUG_TX_REPLY(priv, "Retry scheduler reclaim "
217                                         "scd_ssn=%d idx=%d txq=%d swq=%d\n",
218                                         scd_ssn , index, txq_id, txq->swq_id);
219
220                         freed = iwlagn_tx_queue_reclaim(priv, txq_id, index);
221                         iwl_free_tfds_in_queue(priv, sta_id, tid, freed);
222
223                         if (priv->mac80211_registered &&
224                             (iwl_queue_space(&txq->q) > txq->q.low_mark) &&
225                             (agg->state != IWL_EMPTYING_HW_QUEUE_DELBA)) {
226                                 if (agg->state == IWL_AGG_OFF)
227                                         iwl_wake_queue(priv, txq_id);
228                                 else
229                                         iwl_wake_queue(priv, txq->swq_id);
230                         }
231                 }
232         } else {
233                 BUG_ON(txq_id != txq->swq_id);
234
235                 info->status.rates[0].count = tx_resp->failure_frame + 1;
236                 info->flags |= iwl_tx_status_to_mac80211(status);
237                 iwlagn_hwrate_to_tx_control(priv,
238                                         le32_to_cpu(tx_resp->rate_n_flags),
239                                         info);
240
241                 IWL_DEBUG_TX_REPLY(priv, "TXQ %d status %s (0x%08x) rate_n_flags "
242                                    "0x%x retries %d\n",
243                                    txq_id,
244                                    iwl_get_tx_fail_reason(status), status,
245                                    le32_to_cpu(tx_resp->rate_n_flags),
246                                    tx_resp->failure_frame);
247
248                 freed = iwlagn_tx_queue_reclaim(priv, txq_id, index);
249                 iwl_free_tfds_in_queue(priv, sta_id, tid, freed);
250
251                 if (priv->mac80211_registered &&
252                     (iwl_queue_space(&txq->q) > txq->q.low_mark))
253                         iwl_wake_queue(priv, txq_id);
254         }
255
256         iwlagn_txq_check_empty(priv, sta_id, tid, txq_id);
257
258         iwl_check_abort_status(priv, tx_resp->frame_count, status);
259 }
260
261 void iwlagn_rx_handler_setup(struct iwl_priv *priv)
262 {
263         /* init calibration handlers */
264         priv->rx_handlers[CALIBRATION_RES_NOTIFICATION] =
265                                         iwlagn_rx_calib_result;
266         priv->rx_handlers[CALIBRATION_COMPLETE_NOTIFICATION] =
267                                         iwlagn_rx_calib_complete;
268         priv->rx_handlers[REPLY_TX] = iwlagn_rx_reply_tx;
269 }
270
271 void iwlagn_setup_deferred_work(struct iwl_priv *priv)
272 {
273         /* in agn, the tx power calibration is done in uCode */
274         priv->disable_tx_power_cal = 1;
275 }
276
277 int iwlagn_hw_valid_rtc_data_addr(u32 addr)
278 {
279         return (addr >= IWLAGN_RTC_DATA_LOWER_BOUND) &&
280                 (addr < IWLAGN_RTC_DATA_UPPER_BOUND);
281 }
282
283 int iwlagn_send_tx_power(struct iwl_priv *priv)
284 {
285         struct iwl5000_tx_power_dbm_cmd tx_power_cmd;
286         u8 tx_ant_cfg_cmd;
287
288         /* half dBm need to multiply */
289         tx_power_cmd.global_lmt = (s8)(2 * priv->tx_power_user_lmt);
290
291         if (priv->tx_power_lmt_in_half_dbm &&
292             priv->tx_power_lmt_in_half_dbm < tx_power_cmd.global_lmt) {
293                 /*
294                  * For the newer devices which using enhanced/extend tx power
295                  * table in EEPROM, the format is in half dBm. driver need to
296                  * convert to dBm format before report to mac80211.
297                  * By doing so, there is a possibility of 1/2 dBm resolution
298                  * lost. driver will perform "round-up" operation before
299                  * reporting, but it will cause 1/2 dBm tx power over the
300                  * regulatory limit. Perform the checking here, if the
301                  * "tx_power_user_lmt" is higher than EEPROM value (in
302                  * half-dBm format), lower the tx power based on EEPROM
303                  */
304                 tx_power_cmd.global_lmt = priv->tx_power_lmt_in_half_dbm;
305         }
306         tx_power_cmd.flags = IWL50_TX_POWER_NO_CLOSED;
307         tx_power_cmd.srv_chan_lmt = IWL50_TX_POWER_AUTO;
308
309         if (IWL_UCODE_API(priv->ucode_ver) == 1)
310                 tx_ant_cfg_cmd = REPLY_TX_POWER_DBM_CMD_V1;
311         else
312                 tx_ant_cfg_cmd = REPLY_TX_POWER_DBM_CMD;
313
314         return  iwl_send_cmd_pdu_async(priv, tx_ant_cfg_cmd,
315                                        sizeof(tx_power_cmd), &tx_power_cmd,
316                                        NULL);
317 }
318
319 void iwlagn_temperature(struct iwl_priv *priv)
320 {
321         /* store temperature from statistics (in Celsius) */
322         priv->temperature = le32_to_cpu(priv->statistics.general.temperature);
323         iwl_tt_handler(priv);
324 }
325
326 u16 iwlagn_eeprom_calib_version(struct iwl_priv *priv)
327 {
328         struct iwl_eeprom_calib_hdr {
329                 u8 version;
330                 u8 pa_type;
331                 u16 voltage;
332         } *hdr;
333
334         hdr = (struct iwl_eeprom_calib_hdr *)iwl_eeprom_query_addr(priv,
335                                                         EEPROM_CALIB_ALL);
336         return hdr->version;
337
338 }
339
340 /*
341  * EEPROM
342  */
343 static u32 eeprom_indirect_address(const struct iwl_priv *priv, u32 address)
344 {
345         u16 offset = 0;
346
347         if ((address & INDIRECT_ADDRESS) == 0)
348                 return address;
349
350         switch (address & INDIRECT_TYPE_MSK) {
351         case INDIRECT_HOST:
352                 offset = iwl_eeprom_query16(priv, EEPROM_LINK_HOST);
353                 break;
354         case INDIRECT_GENERAL:
355                 offset = iwl_eeprom_query16(priv, EEPROM_LINK_GENERAL);
356                 break;
357         case INDIRECT_REGULATORY:
358                 offset = iwl_eeprom_query16(priv, EEPROM_LINK_REGULATORY);
359                 break;
360         case INDIRECT_CALIBRATION:
361                 offset = iwl_eeprom_query16(priv, EEPROM_LINK_CALIBRATION);
362                 break;
363         case INDIRECT_PROCESS_ADJST:
364                 offset = iwl_eeprom_query16(priv, EEPROM_LINK_PROCESS_ADJST);
365                 break;
366         case INDIRECT_OTHERS:
367                 offset = iwl_eeprom_query16(priv, EEPROM_LINK_OTHERS);
368                 break;
369         default:
370                 IWL_ERR(priv, "illegal indirect type: 0x%X\n",
371                 address & INDIRECT_TYPE_MSK);
372                 break;
373         }
374
375         /* translate the offset from words to byte */
376         return (address & ADDRESS_MSK) + (offset << 1);
377 }
378
379 const u8 *iwlagn_eeprom_query_addr(const struct iwl_priv *priv,
380                                            size_t offset)
381 {
382         u32 address = eeprom_indirect_address(priv, offset);
383         BUG_ON(address >= priv->cfg->eeprom_size);
384         return &priv->eeprom[address];
385 }
386
387 struct iwl_mod_params iwlagn_mod_params = {
388         .amsdu_size_8K = 1,
389         .restart_fw = 1,
390         /* the rest are 0 by default */
391 };
392
393 void iwlagn_rx_queue_reset(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
394 {
395         unsigned long flags;
396         int i;
397         spin_lock_irqsave(&rxq->lock, flags);
398         INIT_LIST_HEAD(&rxq->rx_free);
399         INIT_LIST_HEAD(&rxq->rx_used);
400         /* Fill the rx_used queue with _all_ of the Rx buffers */
401         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) {
402                 /* In the reset function, these buffers may have been allocated
403                  * to an SKB, so we need to unmap and free potential storage */
404                 if (rxq->pool[i].page != NULL) {
405                         pci_unmap_page(priv->pci_dev, rxq->pool[i].page_dma,
406                                 PAGE_SIZE << priv->hw_params.rx_page_order,
407                                 PCI_DMA_FROMDEVICE);
408                         __iwl_free_pages(priv, rxq->pool[i].page);
409                         rxq->pool[i].page = NULL;
410                 }
411                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
412         }
413
414         for (i = 0; i < RX_QUEUE_SIZE; i++)
415                 rxq->queue[i] = NULL;
416
417         /* Set us so that we have processed and used all buffers, but have
418          * not restocked the Rx queue with fresh buffers */
419         rxq->read = rxq->write = 0;
420         rxq->write_actual = 0;
421         rxq->free_count = 0;
422         spin_unlock_irqrestore(&rxq->lock, flags);
423 }
424
425 int iwlagn_rx_init(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
426 {
427         u32 rb_size;
428         const u32 rfdnlog = RX_QUEUE_SIZE_LOG; /* 256 RBDs */
429         u32 rb_timeout = 0; /* FIXME: RX_RB_TIMEOUT for all devices? */
430
431         if (!priv->cfg->use_isr_legacy)
432                 rb_timeout = RX_RB_TIMEOUT;
433
434         if (priv->cfg->mod_params->amsdu_size_8K)
435                 rb_size = FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_8K;
436         else
437                 rb_size = FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_4K;
438
439         /* Stop Rx DMA */
440         iwl_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0);
441
442         /* Reset driver's Rx queue write index */
443         iwl_write_direct32(priv, FH_RSCSR_CHNL0_RBDCB_WPTR_REG, 0);
444
445         /* Tell device where to find RBD circular buffer in DRAM */
446         iwl_write_direct32(priv, FH_RSCSR_CHNL0_RBDCB_BASE_REG,
447                            (u32)(rxq->dma_addr >> 8));
448
449         /* Tell device where in DRAM to update its Rx status */
450         iwl_write_direct32(priv, FH_RSCSR_CHNL0_STTS_WPTR_REG,
451                            rxq->rb_stts_dma >> 4);
452
453         /* Enable Rx DMA
454          * FH_RCSR_CHNL0_RX_IGNORE_RXF_EMPTY is set because of HW bug in
455          *      the credit mechanism in 5000 HW RX FIFO
456          * Direct rx interrupts to hosts
457          * Rx buffer size 4 or 8k
458          * RB timeout 0x10
459          * 256 RBDs
460          */
461         iwl_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG,
462                            FH_RCSR_RX_CONFIG_CHNL_EN_ENABLE_VAL |
463                            FH_RCSR_CHNL0_RX_IGNORE_RXF_EMPTY |
464                            FH_RCSR_CHNL0_RX_CONFIG_IRQ_DEST_INT_HOST_VAL |
465                            FH_RCSR_CHNL0_RX_CONFIG_SINGLE_FRAME_MSK |
466                            rb_size|
467                            (rb_timeout << FH_RCSR_RX_CONFIG_REG_IRQ_RBTH_POS)|
468                            (rfdnlog << FH_RCSR_RX_CONFIG_RBDCB_SIZE_POS));
469
470         /* Set interrupt coalescing timer to default (2048 usecs) */
471         iwl_write8(priv, CSR_INT_COALESCING, IWL_HOST_INT_TIMEOUT_DEF);
472
473         return 0;
474 }
475
476 int iwlagn_hw_nic_init(struct iwl_priv *priv)
477 {
478         unsigned long flags;
479         struct iwl_rx_queue *rxq = &priv->rxq;
480         int ret;
481
482         /* nic_init */
483         spin_lock_irqsave(&priv->lock, flags);
484         priv->cfg->ops->lib->apm_ops.init(priv);
485
486         /* Set interrupt coalescing calibration timer to default (512 usecs) */
487         iwl_write8(priv, CSR_INT_COALESCING, IWL_HOST_INT_CALIB_TIMEOUT_DEF);
488
489         spin_unlock_irqrestore(&priv->lock, flags);
490
491         ret = priv->cfg->ops->lib->apm_ops.set_pwr_src(priv, IWL_PWR_SRC_VMAIN);
492
493         priv->cfg->ops->lib->apm_ops.config(priv);
494
495         /* Allocate the RX queue, or reset if it is already allocated */
496         if (!rxq->bd) {
497                 ret = iwl_rx_queue_alloc(priv);
498                 if (ret) {
499                         IWL_ERR(priv, "Unable to initialize Rx queue\n");
500                         return -ENOMEM;
501                 }
502         } else
503                 iwlagn_rx_queue_reset(priv, rxq);
504
505         iwlagn_rx_replenish(priv);
506
507         iwlagn_rx_init(priv, rxq);
508
509         spin_lock_irqsave(&priv->lock, flags);
510
511         rxq->need_update = 1;
512         iwl_rx_queue_update_write_ptr(priv, rxq);
513
514         spin_unlock_irqrestore(&priv->lock, flags);
515
516         /* Allocate or reset and init all Tx and Command queues */
517         if (!priv->txq) {
518                 ret = iwlagn_txq_ctx_alloc(priv);
519                 if (ret)
520                         return ret;
521         } else
522                 iwlagn_txq_ctx_reset(priv);
523
524         set_bit(STATUS_INIT, &priv->status);
525
526         return 0;
527 }
528
529 /**
530  * iwlagn_dma_addr2rbd_ptr - convert a DMA address to a uCode read buffer ptr
531  */
532 static inline __le32 iwlagn_dma_addr2rbd_ptr(struct iwl_priv *priv,
533                                           dma_addr_t dma_addr)
534 {
535         return cpu_to_le32((u32)(dma_addr >> 8));
536 }
537
538 /**
539  * iwlagn_rx_queue_restock - refill RX queue from pre-allocated pool
540  *
541  * If there are slots in the RX queue that need to be restocked,
542  * and we have free pre-allocated buffers, fill the ranks as much
543  * as we can, pulling from rx_free.
544  *
545  * This moves the 'write' index forward to catch up with 'processed', and
546  * also updates the memory address in the firmware to reference the new
547  * target buffer.
548  */
549 void iwlagn_rx_queue_restock(struct iwl_priv *priv)
550 {
551         struct iwl_rx_queue *rxq = &priv->rxq;
552         struct list_head *element;
553         struct iwl_rx_mem_buffer *rxb;
554         unsigned long flags;
555
556         spin_lock_irqsave(&rxq->lock, flags);
557         while ((iwl_rx_queue_space(rxq) > 0) && (rxq->free_count)) {
558                 /* The overwritten rxb must be a used one */
559                 rxb = rxq->queue[rxq->write];
560                 BUG_ON(rxb && rxb->page);
561
562                 /* Get next free Rx buffer, remove from free list */
563                 element = rxq->rx_free.next;
564                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
565                 list_del(element);
566
567                 /* Point to Rx buffer via next RBD in circular buffer */
568                 rxq->bd[rxq->write] = iwlagn_dma_addr2rbd_ptr(priv,
569                                                               rxb->page_dma);
570                 rxq->queue[rxq->write] = rxb;
571                 rxq->write = (rxq->write + 1) & RX_QUEUE_MASK;
572                 rxq->free_count--;
573         }
574         spin_unlock_irqrestore(&rxq->lock, flags);
575         /* If the pre-allocated buffer pool is dropping low, schedule to
576          * refill it */
577         if (rxq->free_count <= RX_LOW_WATERMARK)
578                 queue_work(priv->workqueue, &priv->rx_replenish);
579
580
581         /* If we've added more space for the firmware to place data, tell it.
582          * Increment device's write pointer in multiples of 8. */
583         if (rxq->write_actual != (rxq->write & ~0x7)) {
584                 spin_lock_irqsave(&rxq->lock, flags);
585                 rxq->need_update = 1;
586                 spin_unlock_irqrestore(&rxq->lock, flags);
587                 iwl_rx_queue_update_write_ptr(priv, rxq);
588         }
589 }
590
591 /**
592  * iwlagn_rx_replenish - Move all used packet from rx_used to rx_free
593  *
594  * When moving to rx_free an SKB is allocated for the slot.
595  *
596  * Also restock the Rx queue via iwl_rx_queue_restock.
597  * This is called as a scheduled work item (except for during initialization)
598  */
599 void iwlagn_rx_allocate(struct iwl_priv *priv, gfp_t priority)
600 {
601         struct iwl_rx_queue *rxq = &priv->rxq;
602         struct list_head *element;
603         struct iwl_rx_mem_buffer *rxb;
604         struct page *page;
605         unsigned long flags;
606         gfp_t gfp_mask = priority;
607
608         while (1) {
609                 spin_lock_irqsave(&rxq->lock, flags);
610                 if (list_empty(&rxq->rx_used)) {
611                         spin_unlock_irqrestore(&rxq->lock, flags);
612                         return;
613                 }
614                 spin_unlock_irqrestore(&rxq->lock, flags);
615
616                 if (rxq->free_count > RX_LOW_WATERMARK)
617                         gfp_mask |= __GFP_NOWARN;
618
619                 if (priv->hw_params.rx_page_order > 0)
620                         gfp_mask |= __GFP_COMP;
621
622                 /* Alloc a new receive buffer */
623                 page = alloc_pages(gfp_mask, priv->hw_params.rx_page_order);
624                 if (!page) {
625                         if (net_ratelimit())
626                                 IWL_DEBUG_INFO(priv, "alloc_pages failed, "
627                                                "order: %d\n",
628                                                priv->hw_params.rx_page_order);
629
630                         if ((rxq->free_count <= RX_LOW_WATERMARK) &&
631                             net_ratelimit())
632                                 IWL_CRIT(priv, "Failed to alloc_pages with %s. Only %u free buffers remaining.\n",
633                                          priority == GFP_ATOMIC ?  "GFP_ATOMIC" : "GFP_KERNEL",
634                                          rxq->free_count);
635                         /* We don't reschedule replenish work here -- we will
636                          * call the restock method and if it still needs
637                          * more buffers it will schedule replenish */
638                         return;
639                 }
640
641                 spin_lock_irqsave(&rxq->lock, flags);
642
643                 if (list_empty(&rxq->rx_used)) {
644                         spin_unlock_irqrestore(&rxq->lock, flags);
645                         __free_pages(page, priv->hw_params.rx_page_order);
646                         return;
647                 }
648                 element = rxq->rx_used.next;
649                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
650                 list_del(element);
651
652                 spin_unlock_irqrestore(&rxq->lock, flags);
653
654                 BUG_ON(rxb->page);
655                 rxb->page = page;
656                 /* Get physical address of the RB */
657                 rxb->page_dma = pci_map_page(priv->pci_dev, page, 0,
658                                 PAGE_SIZE << priv->hw_params.rx_page_order,
659                                 PCI_DMA_FROMDEVICE);
660                 /* dma address must be no more than 36 bits */
661                 BUG_ON(rxb->page_dma & ~DMA_BIT_MASK(36));
662                 /* and also 256 byte aligned! */
663                 BUG_ON(rxb->page_dma & DMA_BIT_MASK(8));
664
665                 spin_lock_irqsave(&rxq->lock, flags);
666
667                 list_add_tail(&rxb->list, &rxq->rx_free);
668                 rxq->free_count++;
669                 priv->alloc_rxb_page++;
670
671                 spin_unlock_irqrestore(&rxq->lock, flags);
672         }
673 }
674
675 void iwlagn_rx_replenish(struct iwl_priv *priv)
676 {
677         unsigned long flags;
678
679         iwlagn_rx_allocate(priv, GFP_KERNEL);
680
681         spin_lock_irqsave(&priv->lock, flags);
682         iwlagn_rx_queue_restock(priv);
683         spin_unlock_irqrestore(&priv->lock, flags);
684 }
685
686 void iwlagn_rx_replenish_now(struct iwl_priv *priv)
687 {
688         iwlagn_rx_allocate(priv, GFP_ATOMIC);
689
690         iwlagn_rx_queue_restock(priv);
691 }
692
693 /* Assumes that the skb field of the buffers in 'pool' is kept accurate.
694  * If an SKB has been detached, the POOL needs to have its SKB set to NULL
695  * This free routine walks the list of POOL entries and if SKB is set to
696  * non NULL it is unmapped and freed
697  */
698 void iwlagn_rx_queue_free(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
699 {
700         int i;
701         for (i = 0; i < RX_QUEUE_SIZE + RX_FREE_BUFFERS; i++) {
702                 if (rxq->pool[i].page != NULL) {
703                         pci_unmap_page(priv->pci_dev, rxq->pool[i].page_dma,
704                                 PAGE_SIZE << priv->hw_params.rx_page_order,
705                                 PCI_DMA_FROMDEVICE);
706                         __iwl_free_pages(priv, rxq->pool[i].page);
707                         rxq->pool[i].page = NULL;
708                 }
709         }
710
711         dma_free_coherent(&priv->pci_dev->dev, 4 * RX_QUEUE_SIZE, rxq->bd,
712                           rxq->dma_addr);
713         dma_free_coherent(&priv->pci_dev->dev, sizeof(struct iwl_rb_status),
714                           rxq->rb_stts, rxq->rb_stts_dma);
715         rxq->bd = NULL;
716         rxq->rb_stts  = NULL;
717 }
718
719 int iwlagn_rxq_stop(struct iwl_priv *priv)
720 {
721
722         /* stop Rx DMA */
723         iwl_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0);
724         iwl_poll_direct_bit(priv, FH_MEM_RSSR_RX_STATUS_REG,
725                             FH_RSSR_CHNL0_RX_STATUS_CHNL_IDLE, 1000);
726
727         return 0;
728 }
729
730 int iwlagn_hwrate_to_mac80211_idx(u32 rate_n_flags, enum ieee80211_band band)
731 {
732         int idx = 0;
733         int band_offset = 0;
734
735         /* HT rate format: mac80211 wants an MCS number, which is just LSB */
736         if (rate_n_flags & RATE_MCS_HT_MSK) {
737                 idx = (rate_n_flags & 0xff);
738                 return idx;
739         /* Legacy rate format, search for match in table */
740         } else {
741                 if (band == IEEE80211_BAND_5GHZ)
742                         band_offset = IWL_FIRST_OFDM_RATE;
743                 for (idx = band_offset; idx < IWL_RATE_COUNT_LEGACY; idx++)
744                         if (iwl_rates[idx].plcp == (rate_n_flags & 0xFF))
745                                 return idx - band_offset;
746         }
747
748         return -1;
749 }
750
751 /* Calc max signal level (dBm) among 3 possible receivers */
752 static inline int iwlagn_calc_rssi(struct iwl_priv *priv,
753                                 struct iwl_rx_phy_res *rx_resp)
754 {
755         return priv->cfg->ops->utils->calc_rssi(priv, rx_resp);
756 }
757
758 #ifdef CONFIG_IWLWIFI_DEBUG
759 /**
760  * iwlagn_dbg_report_frame - dump frame to syslog during debug sessions
761  *
762  * You may hack this function to show different aspects of received frames,
763  * including selective frame dumps.
764  * group100 parameter selects whether to show 1 out of 100 good data frames.
765  *    All beacon and probe response frames are printed.
766  */
767 static void iwlagn_dbg_report_frame(struct iwl_priv *priv,
768                       struct iwl_rx_phy_res *phy_res, u16 length,
769                       struct ieee80211_hdr *header, int group100)
770 {
771         u32 to_us;
772         u32 print_summary = 0;
773         u32 print_dump = 0;     /* set to 1 to dump all frames' contents */
774         u32 hundred = 0;
775         u32 dataframe = 0;
776         __le16 fc;
777         u16 seq_ctl;
778         u16 channel;
779         u16 phy_flags;
780         u32 rate_n_flags;
781         u32 tsf_low;
782         int rssi;
783
784         if (likely(!(iwl_get_debug_level(priv) & IWL_DL_RX)))
785                 return;
786
787         /* MAC header */
788         fc = header->frame_control;
789         seq_ctl = le16_to_cpu(header->seq_ctrl);
790
791         /* metadata */
792         channel = le16_to_cpu(phy_res->channel);
793         phy_flags = le16_to_cpu(phy_res->phy_flags);
794         rate_n_flags = le32_to_cpu(phy_res->rate_n_flags);
795
796         /* signal statistics */
797         rssi = iwlagn_calc_rssi(priv, phy_res);
798         tsf_low = le64_to_cpu(phy_res->timestamp) & 0x0ffffffff;
799
800         to_us = !compare_ether_addr(header->addr1, priv->mac_addr);
801
802         /* if data frame is to us and all is good,
803          *   (optionally) print summary for only 1 out of every 100 */
804         if (to_us && (fc & ~cpu_to_le16(IEEE80211_FCTL_PROTECTED)) ==
805             cpu_to_le16(IEEE80211_FCTL_FROMDS | IEEE80211_FTYPE_DATA)) {
806                 dataframe = 1;
807                 if (!group100)
808                         print_summary = 1;      /* print each frame */
809                 else if (priv->framecnt_to_us < 100) {
810                         priv->framecnt_to_us++;
811                         print_summary = 0;
812                 } else {
813                         priv->framecnt_to_us = 0;
814                         print_summary = 1;
815                         hundred = 1;
816                 }
817         } else {
818                 /* print summary for all other frames */
819                 print_summary = 1;
820         }
821
822         if (print_summary) {
823                 char *title;
824                 int rate_idx;
825                 u32 bitrate;
826
827                 if (hundred)
828                         title = "100Frames";
829                 else if (ieee80211_has_retry(fc))
830                         title = "Retry";
831                 else if (ieee80211_is_assoc_resp(fc))
832                         title = "AscRsp";
833                 else if (ieee80211_is_reassoc_resp(fc))
834                         title = "RasRsp";
835                 else if (ieee80211_is_probe_resp(fc)) {
836                         title = "PrbRsp";
837                         print_dump = 1; /* dump frame contents */
838                 } else if (ieee80211_is_beacon(fc)) {
839                         title = "Beacon";
840                         print_dump = 1; /* dump frame contents */
841                 } else if (ieee80211_is_atim(fc))
842                         title = "ATIM";
843                 else if (ieee80211_is_auth(fc))
844                         title = "Auth";
845                 else if (ieee80211_is_deauth(fc))
846                         title = "DeAuth";
847                 else if (ieee80211_is_disassoc(fc))
848                         title = "DisAssoc";
849                 else
850                         title = "Frame";
851
852                 rate_idx = iwl_hwrate_to_plcp_idx(rate_n_flags);
853                 if (unlikely((rate_idx < 0) || (rate_idx >= IWL_RATE_COUNT))) {
854                         bitrate = 0;
855                         WARN_ON_ONCE(1);
856                 } else {
857                         bitrate = iwl_rates[rate_idx].ieee / 2;
858                 }
859
860                 /* print frame summary.
861                  * MAC addresses show just the last byte (for brevity),
862                  *    but you can hack it to show more, if you'd like to. */
863                 if (dataframe)
864                         IWL_DEBUG_RX(priv, "%s: mhd=0x%04x, dst=0x%02x, "
865                                      "len=%u, rssi=%d, chnl=%d, rate=%u,\n",
866                                      title, le16_to_cpu(fc), header->addr1[5],
867                                      length, rssi, channel, bitrate);
868                 else {
869                         /* src/dst addresses assume managed mode */
870                         IWL_DEBUG_RX(priv, "%s: 0x%04x, dst=0x%02x, src=0x%02x, "
871                                      "len=%u, rssi=%d, tim=%lu usec, "
872                                      "phy=0x%02x, chnl=%d\n",
873                                      title, le16_to_cpu(fc), header->addr1[5],
874                                      header->addr3[5], length, rssi,
875                                      tsf_low - priv->scan_start_tsf,
876                                      phy_flags, channel);
877                 }
878         }
879         if (print_dump)
880                 iwl_print_hex_dump(priv, IWL_DL_RX, header, length);
881 }
882 #endif
883
884 static u32 iwlagn_translate_rx_status(struct iwl_priv *priv, u32 decrypt_in)
885 {
886         u32 decrypt_out = 0;
887
888         if ((decrypt_in & RX_RES_STATUS_STATION_FOUND) ==
889                                         RX_RES_STATUS_STATION_FOUND)
890                 decrypt_out |= (RX_RES_STATUS_STATION_FOUND |
891                                 RX_RES_STATUS_NO_STATION_INFO_MISMATCH);
892
893         decrypt_out |= (decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK);
894
895         /* packet was not encrypted */
896         if ((decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) ==
897                                         RX_RES_STATUS_SEC_TYPE_NONE)
898                 return decrypt_out;
899
900         /* packet was encrypted with unknown alg */
901         if ((decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) ==
902                                         RX_RES_STATUS_SEC_TYPE_ERR)
903                 return decrypt_out;
904
905         /* decryption was not done in HW */
906         if ((decrypt_in & RX_MPDU_RES_STATUS_DEC_DONE_MSK) !=
907                                         RX_MPDU_RES_STATUS_DEC_DONE_MSK)
908                 return decrypt_out;
909
910         switch (decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) {
911
912         case RX_RES_STATUS_SEC_TYPE_CCMP:
913                 /* alg is CCM: check MIC only */
914                 if (!(decrypt_in & RX_MPDU_RES_STATUS_MIC_OK))
915                         /* Bad MIC */
916                         decrypt_out |= RX_RES_STATUS_BAD_ICV_MIC;
917                 else
918                         decrypt_out |= RX_RES_STATUS_DECRYPT_OK;
919
920                 break;
921
922         case RX_RES_STATUS_SEC_TYPE_TKIP:
923                 if (!(decrypt_in & RX_MPDU_RES_STATUS_TTAK_OK)) {
924                         /* Bad TTAK */
925                         decrypt_out |= RX_RES_STATUS_BAD_KEY_TTAK;
926                         break;
927                 }
928                 /* fall through if TTAK OK */
929         default:
930                 if (!(decrypt_in & RX_MPDU_RES_STATUS_ICV_OK))
931                         decrypt_out |= RX_RES_STATUS_BAD_ICV_MIC;
932                 else
933                         decrypt_out |= RX_RES_STATUS_DECRYPT_OK;
934                 break;
935         }
936
937         IWL_DEBUG_RX(priv, "decrypt_in:0x%x  decrypt_out = 0x%x\n",
938                                         decrypt_in, decrypt_out);
939
940         return decrypt_out;
941 }
942
943 static void iwlagn_pass_packet_to_mac80211(struct iwl_priv *priv,
944                                         struct ieee80211_hdr *hdr,
945                                         u16 len,
946                                         u32 ampdu_status,
947                                         struct iwl_rx_mem_buffer *rxb,
948                                         struct ieee80211_rx_status *stats)
949 {
950         struct sk_buff *skb;
951         __le16 fc = hdr->frame_control;
952
953         /* We only process data packets if the interface is open */
954         if (unlikely(!priv->is_open)) {
955                 IWL_DEBUG_DROP_LIMIT(priv,
956                     "Dropping packet while interface is not open.\n");
957                 return;
958         }
959
960         /* In case of HW accelerated crypto and bad decryption, drop */
961         if (!priv->cfg->mod_params->sw_crypto &&
962             iwl_set_decrypted_flag(priv, hdr, ampdu_status, stats))
963                 return;
964
965         skb = dev_alloc_skb(128);
966         if (!skb) {
967                 IWL_ERR(priv, "dev_alloc_skb failed\n");
968                 return;
969         }
970
971         skb_add_rx_frag(skb, 0, rxb->page, (void *)hdr - rxb_addr(rxb), len);
972
973         iwl_update_stats(priv, false, fc, len);
974         memcpy(IEEE80211_SKB_RXCB(skb), stats, sizeof(*stats));
975
976         ieee80211_rx(priv->hw, skb);
977         priv->alloc_rxb_page--;
978         rxb->page = NULL;
979 }
980
981 /* Called for REPLY_RX (legacy ABG frames), or
982  * REPLY_RX_MPDU_CMD (HT high-throughput N frames). */
983 void iwlagn_rx_reply_rx(struct iwl_priv *priv,
984                                 struct iwl_rx_mem_buffer *rxb)
985 {
986         struct ieee80211_hdr *header;
987         struct ieee80211_rx_status rx_status;
988         struct iwl_rx_packet *pkt = rxb_addr(rxb);
989         struct iwl_rx_phy_res *phy_res;
990         __le32 rx_pkt_status;
991         struct iwl4965_rx_mpdu_res_start *amsdu;
992         u32 len;
993         u32 ampdu_status;
994         u32 rate_n_flags;
995
996         /**
997          * REPLY_RX and REPLY_RX_MPDU_CMD are handled differently.
998          *      REPLY_RX: physical layer info is in this buffer
999          *      REPLY_RX_MPDU_CMD: physical layer info was sent in separate
1000          *              command and cached in priv->last_phy_res
1001          *
1002          * Here we set up local variables depending on which command is
1003          * received.
1004          */
1005         if (pkt->hdr.cmd == REPLY_RX) {
1006                 phy_res = (struct iwl_rx_phy_res *)pkt->u.raw;
1007                 header = (struct ieee80211_hdr *)(pkt->u.raw + sizeof(*phy_res)
1008                                 + phy_res->cfg_phy_cnt);
1009
1010                 len = le16_to_cpu(phy_res->byte_count);
1011                 rx_pkt_status = *(__le32 *)(pkt->u.raw + sizeof(*phy_res) +
1012                                 phy_res->cfg_phy_cnt + len);
1013                 ampdu_status = le32_to_cpu(rx_pkt_status);
1014         } else {
1015                 if (!priv->_agn.last_phy_res_valid) {
1016                         IWL_ERR(priv, "MPDU frame without cached PHY data\n");
1017                         return;
1018                 }
1019                 phy_res = &priv->_agn.last_phy_res;
1020                 amsdu = (struct iwl4965_rx_mpdu_res_start *)pkt->u.raw;
1021                 header = (struct ieee80211_hdr *)(pkt->u.raw + sizeof(*amsdu));
1022                 len = le16_to_cpu(amsdu->byte_count);
1023                 rx_pkt_status = *(__le32 *)(pkt->u.raw + sizeof(*amsdu) + len);
1024                 ampdu_status = iwlagn_translate_rx_status(priv,
1025                                 le32_to_cpu(rx_pkt_status));
1026         }
1027
1028         if ((unlikely(phy_res->cfg_phy_cnt > 20))) {
1029                 IWL_DEBUG_DROP(priv, "dsp size out of range [0,20]: %d/n",
1030                                 phy_res->cfg_phy_cnt);
1031                 return;
1032         }
1033
1034         if (!(rx_pkt_status & RX_RES_STATUS_NO_CRC32_ERROR) ||
1035             !(rx_pkt_status & RX_RES_STATUS_NO_RXE_OVERFLOW)) {
1036                 IWL_DEBUG_RX(priv, "Bad CRC or FIFO: 0x%08X.\n",
1037                                 le32_to_cpu(rx_pkt_status));
1038                 return;
1039         }
1040
1041         /* This will be used in several places later */
1042         rate_n_flags = le32_to_cpu(phy_res->rate_n_flags);
1043
1044         /* rx_status carries information about the packet to mac80211 */
1045         rx_status.mactime = le64_to_cpu(phy_res->timestamp);
1046         rx_status.freq =
1047                 ieee80211_channel_to_frequency(le16_to_cpu(phy_res->channel));
1048         rx_status.band = (phy_res->phy_flags & RX_RES_PHY_FLAGS_BAND_24_MSK) ?
1049                                 IEEE80211_BAND_2GHZ : IEEE80211_BAND_5GHZ;
1050         rx_status.rate_idx =
1051                 iwlagn_hwrate_to_mac80211_idx(rate_n_flags, rx_status.band);
1052         rx_status.flag = 0;
1053
1054         /* TSF isn't reliable. In order to allow smooth user experience,
1055          * this W/A doesn't propagate it to the mac80211 */
1056         /*rx_status.flag |= RX_FLAG_TSFT;*/
1057
1058         priv->ucode_beacon_time = le32_to_cpu(phy_res->beacon_time_stamp);
1059
1060         /* Find max signal strength (dBm) among 3 antenna/receiver chains */
1061         rx_status.signal = iwlagn_calc_rssi(priv, phy_res);
1062
1063 #ifdef CONFIG_IWLWIFI_DEBUG
1064         /* Set "1" to report good data frames in groups of 100 */
1065         if (unlikely(iwl_get_debug_level(priv) & IWL_DL_RX))
1066                 iwlagn_dbg_report_frame(priv, phy_res, len, header, 1);
1067 #endif
1068         iwl_dbg_log_rx_data_frame(priv, len, header);
1069         IWL_DEBUG_STATS_LIMIT(priv, "Rssi %d, TSF %llu\n",
1070                 rx_status.signal, (unsigned long long)rx_status.mactime);
1071
1072         /*
1073          * "antenna number"
1074          *
1075          * It seems that the antenna field in the phy flags value
1076          * is actually a bit field. This is undefined by radiotap,
1077          * it wants an actual antenna number but I always get "7"
1078          * for most legacy frames I receive indicating that the
1079          * same frame was received on all three RX chains.
1080          *
1081          * I think this field should be removed in favor of a
1082          * new 802.11n radiotap field "RX chains" that is defined
1083          * as a bitmask.
1084          */
1085         rx_status.antenna =
1086                 (le16_to_cpu(phy_res->phy_flags) & RX_RES_PHY_FLAGS_ANTENNA_MSK)
1087                 >> RX_RES_PHY_FLAGS_ANTENNA_POS;
1088
1089         /* set the preamble flag if appropriate */
1090         if (phy_res->phy_flags & RX_RES_PHY_FLAGS_SHORT_PREAMBLE_MSK)
1091                 rx_status.flag |= RX_FLAG_SHORTPRE;
1092
1093         /* Set up the HT phy flags */
1094         if (rate_n_flags & RATE_MCS_HT_MSK)
1095                 rx_status.flag |= RX_FLAG_HT;
1096         if (rate_n_flags & RATE_MCS_HT40_MSK)
1097                 rx_status.flag |= RX_FLAG_40MHZ;
1098         if (rate_n_flags & RATE_MCS_SGI_MSK)
1099                 rx_status.flag |= RX_FLAG_SHORT_GI;
1100
1101         iwlagn_pass_packet_to_mac80211(priv, header, len, ampdu_status,
1102                                     rxb, &rx_status);
1103 }
1104
1105 /* Cache phy data (Rx signal strength, etc) for HT frame (REPLY_RX_PHY_CMD).
1106  * This will be used later in iwl_rx_reply_rx() for REPLY_RX_MPDU_CMD. */
1107 void iwlagn_rx_reply_rx_phy(struct iwl_priv *priv,
1108                             struct iwl_rx_mem_buffer *rxb)
1109 {
1110         struct iwl_rx_packet *pkt = rxb_addr(rxb);
1111         priv->_agn.last_phy_res_valid = true;
1112         memcpy(&priv->_agn.last_phy_res, pkt->u.raw,
1113                sizeof(struct iwl_rx_phy_res));
1114 }
1115
1116 static int iwl_get_single_channel_for_scan(struct iwl_priv *priv,
1117                                            struct ieee80211_vif *vif,
1118                                            enum ieee80211_band band,
1119                                            struct iwl_scan_channel *scan_ch)
1120 {
1121         const struct ieee80211_supported_band *sband;
1122         const struct iwl_channel_info *ch_info;
1123         u16 passive_dwell = 0;
1124         u16 active_dwell = 0;
1125         int i, added = 0;
1126         u16 channel = 0;
1127
1128         sband = iwl_get_hw_mode(priv, band);
1129         if (!sband) {
1130                 IWL_ERR(priv, "invalid band\n");
1131                 return added;
1132         }
1133
1134         active_dwell = iwl_get_active_dwell_time(priv, band, 0);
1135         passive_dwell = iwl_get_passive_dwell_time(priv, band, vif);
1136
1137         if (passive_dwell <= active_dwell)
1138                 passive_dwell = active_dwell + 1;
1139
1140         /* only scan single channel, good enough to reset the RF */
1141         /* pick the first valid not in-use channel */
1142         if (band == IEEE80211_BAND_5GHZ) {
1143                 for (i = 14; i < priv->channel_count; i++) {
1144                         if (priv->channel_info[i].channel !=
1145                             le16_to_cpu(priv->staging_rxon.channel)) {
1146                                 channel = priv->channel_info[i].channel;
1147                                 ch_info = iwl_get_channel_info(priv,
1148                                         band, channel);
1149                                 if (is_channel_valid(ch_info))
1150                                         break;
1151                         }
1152                 }
1153         } else {
1154                 for (i = 0; i < 14; i++) {
1155                         if (priv->channel_info[i].channel !=
1156                             le16_to_cpu(priv->staging_rxon.channel)) {
1157                                         channel =
1158                                                 priv->channel_info[i].channel;
1159                                         ch_info = iwl_get_channel_info(priv,
1160                                                 band, channel);
1161                                         if (is_channel_valid(ch_info))
1162                                                 break;
1163                         }
1164                 }
1165         }
1166         if (channel) {
1167                 scan_ch->channel = cpu_to_le16(channel);
1168                 scan_ch->type = SCAN_CHANNEL_TYPE_PASSIVE;
1169                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
1170                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
1171                 /* Set txpower levels to defaults */
1172                 scan_ch->dsp_atten = 110;
1173                 if (band == IEEE80211_BAND_5GHZ)
1174                         scan_ch->tx_gain = ((1 << 5) | (3 << 3)) | 3;
1175                 else
1176                         scan_ch->tx_gain = ((1 << 5) | (5 << 3));
1177                 added++;
1178         } else
1179                 IWL_ERR(priv, "no valid channel found\n");
1180         return added;
1181 }
1182
1183 static int iwl_get_channels_for_scan(struct iwl_priv *priv,
1184                                      struct ieee80211_vif *vif,
1185                                      enum ieee80211_band band,
1186                                      u8 is_active, u8 n_probes,
1187                                      struct iwl_scan_channel *scan_ch)
1188 {
1189         struct ieee80211_channel *chan;
1190         const struct ieee80211_supported_band *sband;
1191         const struct iwl_channel_info *ch_info;
1192         u16 passive_dwell = 0;
1193         u16 active_dwell = 0;
1194         int added, i;
1195         u16 channel;
1196
1197         sband = iwl_get_hw_mode(priv, band);
1198         if (!sband)
1199                 return 0;
1200
1201         active_dwell = iwl_get_active_dwell_time(priv, band, n_probes);
1202         passive_dwell = iwl_get_passive_dwell_time(priv, band, vif);
1203
1204         if (passive_dwell <= active_dwell)
1205                 passive_dwell = active_dwell + 1;
1206
1207         for (i = 0, added = 0; i < priv->scan_request->n_channels; i++) {
1208                 chan = priv->scan_request->channels[i];
1209
1210                 if (chan->band != band)
1211                         continue;
1212
1213                 channel = ieee80211_frequency_to_channel(chan->center_freq);
1214                 scan_ch->channel = cpu_to_le16(channel);
1215
1216                 ch_info = iwl_get_channel_info(priv, band, channel);
1217                 if (!is_channel_valid(ch_info)) {
1218                         IWL_DEBUG_SCAN(priv, "Channel %d is INVALID for this band.\n",
1219                                         channel);
1220                         continue;
1221                 }
1222
1223                 if (!is_active || is_channel_passive(ch_info) ||
1224                     (chan->flags & IEEE80211_CHAN_PASSIVE_SCAN))
1225                         scan_ch->type = SCAN_CHANNEL_TYPE_PASSIVE;
1226                 else
1227                         scan_ch->type = SCAN_CHANNEL_TYPE_ACTIVE;
1228
1229                 if (n_probes)
1230                         scan_ch->type |= IWL_SCAN_PROBE_MASK(n_probes);
1231
1232                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
1233                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
1234
1235                 /* Set txpower levels to defaults */
1236                 scan_ch->dsp_atten = 110;
1237
1238                 /* NOTE: if we were doing 6Mb OFDM for scans we'd use
1239                  * power level:
1240                  * scan_ch->tx_gain = ((1 << 5) | (2 << 3)) | 3;
1241                  */
1242                 if (band == IEEE80211_BAND_5GHZ)
1243                         scan_ch->tx_gain = ((1 << 5) | (3 << 3)) | 3;
1244                 else
1245                         scan_ch->tx_gain = ((1 << 5) | (5 << 3));
1246
1247                 IWL_DEBUG_SCAN(priv, "Scanning ch=%d prob=0x%X [%s %d]\n",
1248                                channel, le32_to_cpu(scan_ch->type),
1249                                (scan_ch->type & SCAN_CHANNEL_TYPE_ACTIVE) ?
1250                                 "ACTIVE" : "PASSIVE",
1251                                (scan_ch->type & SCAN_CHANNEL_TYPE_ACTIVE) ?
1252                                active_dwell : passive_dwell);
1253
1254                 scan_ch++;
1255                 added++;
1256         }
1257
1258         IWL_DEBUG_SCAN(priv, "total channels to scan %d\n", added);
1259         return added;
1260 }
1261
1262 void iwlagn_request_scan(struct iwl_priv *priv, struct ieee80211_vif *vif)
1263 {
1264         struct iwl_host_cmd cmd = {
1265                 .id = REPLY_SCAN_CMD,
1266                 .len = sizeof(struct iwl_scan_cmd),
1267                 .flags = CMD_SIZE_HUGE,
1268         };
1269         struct iwl_scan_cmd *scan;
1270         struct ieee80211_conf *conf = NULL;
1271         u32 rate_flags = 0;
1272         u16 cmd_len;
1273         u16 rx_chain = 0;
1274         enum ieee80211_band band;
1275         u8 n_probes = 0;
1276         u8 rx_ant = priv->hw_params.valid_rx_ant;
1277         u8 rate;
1278         bool is_active = false;
1279         int  chan_mod;
1280         u8 active_chains;
1281
1282         conf = ieee80211_get_hw_conf(priv->hw);
1283
1284         cancel_delayed_work(&priv->scan_check);
1285
1286         if (!iwl_is_ready(priv)) {
1287                 IWL_WARN(priv, "request scan called when driver not ready.\n");
1288                 goto done;
1289         }
1290
1291         /* Make sure the scan wasn't canceled before this queued work
1292          * was given the chance to run... */
1293         if (!test_bit(STATUS_SCANNING, &priv->status))
1294                 goto done;
1295
1296         /* This should never be called or scheduled if there is currently
1297          * a scan active in the hardware. */
1298         if (test_bit(STATUS_SCAN_HW, &priv->status)) {
1299                 IWL_DEBUG_INFO(priv, "Multiple concurrent scan requests in parallel. "
1300                                "Ignoring second request.\n");
1301                 goto done;
1302         }
1303
1304         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
1305                 IWL_DEBUG_SCAN(priv, "Aborting scan due to device shutdown\n");
1306                 goto done;
1307         }
1308
1309         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
1310                 IWL_DEBUG_HC(priv, "Scan request while abort pending.  Queuing.\n");
1311                 goto done;
1312         }
1313
1314         if (iwl_is_rfkill(priv)) {
1315                 IWL_DEBUG_HC(priv, "Aborting scan due to RF Kill activation\n");
1316                 goto done;
1317         }
1318
1319         if (!test_bit(STATUS_READY, &priv->status)) {
1320                 IWL_DEBUG_HC(priv, "Scan request while uninitialized.  Queuing.\n");
1321                 goto done;
1322         }
1323
1324         if (!priv->scan_cmd) {
1325                 priv->scan_cmd = kmalloc(sizeof(struct iwl_scan_cmd) +
1326                                          IWL_MAX_SCAN_SIZE, GFP_KERNEL);
1327                 if (!priv->scan_cmd) {
1328                         IWL_DEBUG_SCAN(priv,
1329                                        "fail to allocate memory for scan\n");
1330                         goto done;
1331                 }
1332         }
1333         scan = priv->scan_cmd;
1334         memset(scan, 0, sizeof(struct iwl_scan_cmd) + IWL_MAX_SCAN_SIZE);
1335
1336         scan->quiet_plcp_th = IWL_PLCP_QUIET_THRESH;
1337         scan->quiet_time = IWL_ACTIVE_QUIET_TIME;
1338
1339         if (iwl_is_associated(priv)) {
1340                 u16 interval = 0;
1341                 u32 extra;
1342                 u32 suspend_time = 100;
1343                 u32 scan_suspend_time = 100;
1344                 unsigned long flags;
1345
1346                 IWL_DEBUG_INFO(priv, "Scanning while associated...\n");
1347                 spin_lock_irqsave(&priv->lock, flags);
1348                 interval = vif ? vif->bss_conf.beacon_int : 0;
1349                 spin_unlock_irqrestore(&priv->lock, flags);
1350
1351                 scan->suspend_time = 0;
1352                 scan->max_out_time = cpu_to_le32(200 * 1024);
1353                 if (!interval)
1354                         interval = suspend_time;
1355
1356                 extra = (suspend_time / interval) << 22;
1357                 scan_suspend_time = (extra |
1358                     ((suspend_time % interval) * 1024));
1359                 scan->suspend_time = cpu_to_le32(scan_suspend_time);
1360                 IWL_DEBUG_SCAN(priv, "suspend_time 0x%X beacon interval %d\n",
1361                                scan_suspend_time, interval);
1362         }
1363
1364         if (priv->is_internal_short_scan) {
1365                 IWL_DEBUG_SCAN(priv, "Start internal passive scan.\n");
1366         } else if (priv->scan_request->n_ssids) {
1367                 int i, p = 0;
1368                 IWL_DEBUG_SCAN(priv, "Kicking off active scan\n");
1369                 for (i = 0; i < priv->scan_request->n_ssids; i++) {
1370                         /* always does wildcard anyway */
1371                         if (!priv->scan_request->ssids[i].ssid_len)
1372                                 continue;
1373                         scan->direct_scan[p].id = WLAN_EID_SSID;
1374                         scan->direct_scan[p].len =
1375                                 priv->scan_request->ssids[i].ssid_len;
1376                         memcpy(scan->direct_scan[p].ssid,
1377                                priv->scan_request->ssids[i].ssid,
1378                                priv->scan_request->ssids[i].ssid_len);
1379                         n_probes++;
1380                         p++;
1381                 }
1382                 is_active = true;
1383         } else
1384                 IWL_DEBUG_SCAN(priv, "Start passive scan.\n");
1385
1386         scan->tx_cmd.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK;
1387         scan->tx_cmd.sta_id = priv->hw_params.bcast_sta_id;
1388         scan->tx_cmd.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
1389
1390         switch (priv->scan_band) {
1391         case IEEE80211_BAND_2GHZ:
1392                 scan->flags = RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK;
1393                 chan_mod = le32_to_cpu(priv->active_rxon.flags & RXON_FLG_CHANNEL_MODE_MSK)
1394                                        >> RXON_FLG_CHANNEL_MODE_POS;
1395                 if (chan_mod == CHANNEL_MODE_PURE_40) {
1396                         rate = IWL_RATE_6M_PLCP;
1397                 } else {
1398                         rate = IWL_RATE_1M_PLCP;
1399                         rate_flags = RATE_MCS_CCK_MSK;
1400                 }
1401                 scan->good_CRC_th = IWL_GOOD_CRC_TH_DISABLED;
1402                 break;
1403         case IEEE80211_BAND_5GHZ:
1404                 rate = IWL_RATE_6M_PLCP;
1405                 /*
1406                  * If active scanning is requested but a certain channel is
1407                  * marked passive, we can do active scanning if we detect
1408                  * transmissions.
1409                  *
1410                  * There is an issue with some firmware versions that triggers
1411                  * a sysassert on a "good CRC threshold" of zero (== disabled),
1412                  * on a radar channel even though this means that we should NOT
1413                  * send probes.
1414                  *
1415                  * The "good CRC threshold" is the number of frames that we
1416                  * need to receive during our dwell time on a channel before
1417                  * sending out probes -- setting this to a huge value will
1418                  * mean we never reach it, but at the same time work around
1419                  * the aforementioned issue. Thus use IWL_GOOD_CRC_TH_NEVER
1420                  * here instead of IWL_GOOD_CRC_TH_DISABLED.
1421                  */
1422                 scan->good_CRC_th = is_active ? IWL_GOOD_CRC_TH_DEFAULT :
1423                                                 IWL_GOOD_CRC_TH_NEVER;
1424                 break;
1425         default:
1426                 IWL_WARN(priv, "Invalid scan band count\n");
1427                 goto done;
1428         }
1429
1430         band = priv->scan_band;
1431
1432         if (priv->cfg->scan_antennas[band])
1433                 rx_ant = priv->cfg->scan_antennas[band];
1434
1435         priv->scan_tx_ant[band] =
1436                         iwl_toggle_tx_ant(priv, priv->scan_tx_ant[band]);
1437         rate_flags |= iwl_ant_idx_to_flags(priv->scan_tx_ant[band]);
1438         scan->tx_cmd.rate_n_flags = iwl_hw_set_rate_n_flags(rate, rate_flags);
1439
1440         /* In power save mode use one chain, otherwise use all chains */
1441         if (test_bit(STATUS_POWER_PMI, &priv->status)) {
1442                 /* rx_ant has been set to all valid chains previously */
1443                 active_chains = rx_ant &
1444                                 ((u8)(priv->chain_noise_data.active_chains));
1445                 if (!active_chains)
1446                         active_chains = rx_ant;
1447
1448                 IWL_DEBUG_SCAN(priv, "chain_noise_data.active_chains: %u\n",
1449                                 priv->chain_noise_data.active_chains);
1450
1451                 rx_ant = first_antenna(active_chains);
1452         }
1453         /* MIMO is not used here, but value is required */
1454         rx_chain |= priv->hw_params.valid_rx_ant << RXON_RX_CHAIN_VALID_POS;
1455         rx_chain |= rx_ant << RXON_RX_CHAIN_FORCE_MIMO_SEL_POS;
1456         rx_chain |= rx_ant << RXON_RX_CHAIN_FORCE_SEL_POS;
1457         rx_chain |= 0x1 << RXON_RX_CHAIN_DRIVER_FORCE_POS;
1458         scan->rx_chain = cpu_to_le16(rx_chain);
1459         if (!priv->is_internal_short_scan) {
1460                 cmd_len = iwl_fill_probe_req(priv,
1461                                         (struct ieee80211_mgmt *)scan->data,
1462                                         priv->scan_request->ie,
1463                                         priv->scan_request->ie_len,
1464                                         IWL_MAX_SCAN_SIZE - sizeof(*scan));
1465         } else {
1466                 cmd_len = iwl_fill_probe_req(priv,
1467                                         (struct ieee80211_mgmt *)scan->data,
1468                                         NULL, 0,
1469                                         IWL_MAX_SCAN_SIZE - sizeof(*scan));
1470
1471         }
1472         scan->tx_cmd.len = cpu_to_le16(cmd_len);
1473
1474         scan->filter_flags |= (RXON_FILTER_ACCEPT_GRP_MSK |
1475                                RXON_FILTER_BCON_AWARE_MSK);
1476
1477         if (priv->is_internal_short_scan) {
1478                 scan->channel_count =
1479                         iwl_get_single_channel_for_scan(priv, vif, band,
1480                                 (void *)&scan->data[le16_to_cpu(
1481                                 scan->tx_cmd.len)]);
1482         } else {
1483                 scan->channel_count =
1484                         iwl_get_channels_for_scan(priv, vif, band,
1485                                 is_active, n_probes,
1486                                 (void *)&scan->data[le16_to_cpu(
1487                                 scan->tx_cmd.len)]);
1488         }
1489         if (scan->channel_count == 0) {
1490                 IWL_DEBUG_SCAN(priv, "channel count %d\n", scan->channel_count);
1491                 goto done;
1492         }
1493
1494         cmd.len += le16_to_cpu(scan->tx_cmd.len) +
1495             scan->channel_count * sizeof(struct iwl_scan_channel);
1496         cmd.data = scan;
1497         scan->len = cpu_to_le16(cmd.len);
1498
1499         set_bit(STATUS_SCAN_HW, &priv->status);
1500         if (iwl_send_cmd_sync(priv, &cmd))
1501                 goto done;
1502
1503         queue_delayed_work(priv->workqueue, &priv->scan_check,
1504                            IWL_SCAN_CHECK_WATCHDOG);
1505
1506         return;
1507
1508  done:
1509         /* Cannot perform scan. Make sure we clear scanning
1510         * bits from status so next scan request can be performed.
1511         * If we don't clear scanning status bit here all next scan
1512         * will fail
1513         */
1514         clear_bit(STATUS_SCAN_HW, &priv->status);
1515         clear_bit(STATUS_SCANNING, &priv->status);
1516         /* inform mac80211 scan aborted */
1517         queue_work(priv->workqueue, &priv->scan_completed);
1518 }
1519
1520 int iwlagn_manage_ibss_station(struct iwl_priv *priv,
1521                                struct ieee80211_vif *vif, bool add)
1522 {
1523         struct iwl_vif_priv *vif_priv = (void *)vif->drv_priv;
1524
1525         if (add)
1526                 return iwl_add_bssid_station(priv, vif->bss_conf.bssid, true,
1527                                              &vif_priv->ibss_bssid_sta_id);
1528         return iwl_remove_station(priv, vif_priv->ibss_bssid_sta_id,
1529                                   vif->bss_conf.bssid);
1530 }