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