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