a8f2adfd799e790e009192a5bed1594ed602e87c
[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);
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
97                 /*
98                  * Start is the lowest frame sent. It may not be the first
99                  * frame in the batch; we figure this out dynamically during
100                  * the following loop.
101                  */
102                 int start = agg->start_idx;
103
104                 /* Construct bit-map of pending frames within Tx window */
105                 for (i = 0; i < agg->frame_count; i++) {
106                         u16 sc;
107                         status = le16_to_cpu(frame_status[i].status);
108                         seq  = le16_to_cpu(frame_status[i].sequence);
109                         idx = SEQ_TO_INDEX(seq);
110                         txq_id = SEQ_TO_QUEUE(seq);
111
112                         if (status & (AGG_TX_STATE_FEW_BYTES_MSK |
113                                       AGG_TX_STATE_ABORT_MSK))
114                                 continue;
115
116                         IWL_DEBUG_TX_REPLY(priv, "FrameCnt = %d, txq_id=%d idx=%d\n",
117                                            agg->frame_count, txq_id, idx);
118
119                         hdr = iwl_tx_queue_get_hdr(priv, txq_id, idx);
120                         if (!hdr) {
121                                 IWL_ERR(priv,
122                                         "BUG_ON idx doesn't point to valid skb"
123                                         " idx=%d, txq_id=%d\n", idx, txq_id);
124                                 return -1;
125                         }
126
127                         sc = le16_to_cpu(hdr->seq_ctrl);
128                         if (idx != (SEQ_TO_SN(sc) & 0xff)) {
129                                 IWL_ERR(priv,
130                                         "BUG_ON idx doesn't match seq control"
131                                         " idx=%d, seq_idx=%d, seq=%d\n",
132                                           idx, SEQ_TO_SN(sc),
133                                           hdr->seq_ctrl);
134                                 return -1;
135                         }
136
137                         IWL_DEBUG_TX_REPLY(priv, "AGG Frame i=%d idx %d seq=%d\n",
138                                            i, idx, SEQ_TO_SN(sc));
139
140                         /*
141                          * sh -> how many frames ahead of the starting frame is
142                          * the current one?
143                          *
144                          * Note that all frames sent in the batch must be in a
145                          * 64-frame window, so this number should be in [0,63].
146                          * If outside of this window, then we've found a new
147                          * "first" frame in the batch and need to change start.
148                          */
149                         sh = idx - start;
150
151                         /*
152                          * If >= 64, out of window. start must be at the front
153                          * of the circular buffer, idx must be near the end of
154                          * the buffer, and idx is the new "first" frame. Shift
155                          * the indices around.
156                          */
157                         if (sh >= 64) {
158                                 /* Shift bitmap by start - idx, wrapped */
159                                 sh = 0x100 - idx + start;
160                                 bitmap = bitmap << sh;
161                                 /* Now idx is the new start so sh = 0 */
162                                 sh = 0;
163                                 start = idx;
164                         /*
165                          * If <= -64 then wraps the 256-pkt circular buffer
166                          * (e.g., start = 255 and idx = 0, sh should be 1)
167                          */
168                         } else if (sh <= -64) {
169                                 sh  = 0x100 - start + idx;
170                         /*
171                          * If < 0 but > -64, out of window. idx is before start
172                          * but not wrapped. Shift the indices around.
173                          */
174                         } else if (sh < 0) {
175                                 /* Shift by how far start is ahead of idx */
176                                 sh = start - idx;
177                                 bitmap = bitmap << sh;
178                                 /* Now idx is the new start so sh = 0 */
179                                 start = idx;
180                                 sh = 0;
181                         }
182                         /* Sequence number start + sh was sent in this batch */
183                         bitmap |= 1ULL << sh;
184                         IWL_DEBUG_TX_REPLY(priv, "start=%d bitmap=0x%llx\n",
185                                            start, (unsigned long long)bitmap);
186                 }
187
188                 /*
189                  * Store the bitmap and possibly the new start, if we wrapped
190                  * the buffer above
191                  */
192                 agg->bitmap = bitmap;
193                 agg->start_idx = start;
194                 IWL_DEBUG_TX_REPLY(priv, "Frames %d start_idx=%d bitmap=0x%llx\n",
195                                    agg->frame_count, agg->start_idx,
196                                    (unsigned long long)agg->bitmap);
197
198                 if (bitmap)
199                         agg->wait_for_ba = 1;
200         }
201         return 0;
202 }
203
204 void iwl_check_abort_status(struct iwl_priv *priv,
205                             u8 frame_count, u32 status)
206 {
207         if (frame_count == 1 && status == TX_STATUS_FAIL_RFKILL_FLUSH) {
208                 IWL_ERR(priv, "Tx flush command to flush out all frames\n");
209                 if (!test_bit(STATUS_EXIT_PENDING, &priv->status))
210                         queue_work(priv->workqueue, &priv->tx_flush);
211         }
212 }
213
214 static void iwlagn_rx_reply_tx(struct iwl_priv *priv,
215                                 struct iwl_rx_mem_buffer *rxb)
216 {
217         struct iwl_rx_packet *pkt = rxb_addr(rxb);
218         u16 sequence = le16_to_cpu(pkt->hdr.sequence);
219         int txq_id = SEQ_TO_QUEUE(sequence);
220         int index = SEQ_TO_INDEX(sequence);
221         struct iwl_tx_queue *txq = &priv->txq[txq_id];
222         struct ieee80211_tx_info *info;
223         struct iwl5000_tx_resp *tx_resp = (void *)&pkt->u.raw[0];
224         u32  status = le16_to_cpu(tx_resp->status.status);
225         int tid;
226         int sta_id;
227         int freed;
228         unsigned long flags;
229
230         if ((index >= txq->q.n_bd) || (iwl_queue_used(&txq->q, index) == 0)) {
231                 IWL_ERR(priv, "Read index for DMA queue txq_id (%d) index %d "
232                           "is out of range [0-%d] %d %d\n", txq_id,
233                           index, txq->q.n_bd, txq->q.write_ptr,
234                           txq->q.read_ptr);
235                 return;
236         }
237
238         info = IEEE80211_SKB_CB(txq->txb[txq->q.read_ptr].skb);
239         memset(&info->status, 0, sizeof(info->status));
240
241         tid = (tx_resp->ra_tid & IWL50_TX_RES_TID_MSK) >> IWL50_TX_RES_TID_POS;
242         sta_id = (tx_resp->ra_tid & IWL50_TX_RES_RA_MSK) >> IWL50_TX_RES_RA_POS;
243
244         spin_lock_irqsave(&priv->sta_lock, flags);
245         if (txq->sched_retry) {
246                 const u32 scd_ssn = iwlagn_get_scd_ssn(tx_resp);
247                 struct iwl_ht_agg *agg;
248
249                 agg = &priv->stations[sta_id].tid[tid].agg;
250                 /*
251                  * If the BT kill count is non-zero, we'll get this
252                  * notification again.
253                  */
254                 if (tx_resp->bt_kill_count && tx_resp->frame_count == 1 &&
255                     priv->cfg->advanced_bt_coexist) {
256                         IWL_WARN(priv, "receive reply tx with bt_kill\n");
257                 }
258                 iwlagn_tx_status_reply_tx(priv, agg, tx_resp, txq_id, index);
259
260                 /* check if BAR is needed */
261                 if ((tx_resp->frame_count == 1) && !iwl_is_tx_success(status))
262                         info->flags |= IEEE80211_TX_STAT_AMPDU_NO_BACK;
263
264                 if (txq->q.read_ptr != (scd_ssn & 0xff)) {
265                         index = iwl_queue_dec_wrap(scd_ssn & 0xff, txq->q.n_bd);
266                         IWL_DEBUG_TX_REPLY(priv, "Retry scheduler reclaim "
267                                         "scd_ssn=%d idx=%d txq=%d swq=%d\n",
268                                         scd_ssn , index, txq_id, txq->swq_id);
269
270                         freed = iwlagn_tx_queue_reclaim(priv, txq_id, index);
271                         iwl_free_tfds_in_queue(priv, sta_id, tid, freed);
272
273                         if (priv->mac80211_registered &&
274                             (iwl_queue_space(&txq->q) > txq->q.low_mark) &&
275                             (agg->state != IWL_EMPTYING_HW_QUEUE_DELBA)) {
276                                 if (agg->state == IWL_AGG_OFF)
277                                         iwl_wake_queue(priv, txq_id);
278                                 else
279                                         iwl_wake_queue(priv, txq->swq_id);
280                         }
281                 }
282         } else {
283                 BUG_ON(txq_id != txq->swq_id);
284
285                 info->status.rates[0].count = tx_resp->failure_frame + 1;
286                 info->flags |= iwl_tx_status_to_mac80211(status);
287                 iwlagn_hwrate_to_tx_control(priv,
288                                         le32_to_cpu(tx_resp->rate_n_flags),
289                                         info);
290
291                 IWL_DEBUG_TX_REPLY(priv, "TXQ %d status %s (0x%08x) rate_n_flags "
292                                    "0x%x retries %d\n",
293                                    txq_id,
294                                    iwl_get_tx_fail_reason(status), status,
295                                    le32_to_cpu(tx_resp->rate_n_flags),
296                                    tx_resp->failure_frame);
297
298                 freed = iwlagn_tx_queue_reclaim(priv, txq_id, index);
299                 iwl_free_tfds_in_queue(priv, sta_id, tid, freed);
300
301                 if (priv->mac80211_registered &&
302                     (iwl_queue_space(&txq->q) > txq->q.low_mark))
303                         iwl_wake_queue(priv, txq_id);
304         }
305
306         iwlagn_txq_check_empty(priv, sta_id, tid, txq_id);
307
308         iwl_check_abort_status(priv, tx_resp->frame_count, status);
309         spin_unlock_irqrestore(&priv->sta_lock, flags);
310 }
311
312 void iwlagn_rx_handler_setup(struct iwl_priv *priv)
313 {
314         /* init calibration handlers */
315         priv->rx_handlers[CALIBRATION_RES_NOTIFICATION] =
316                                         iwlagn_rx_calib_result;
317         priv->rx_handlers[CALIBRATION_COMPLETE_NOTIFICATION] =
318                                         iwlagn_rx_calib_complete;
319         priv->rx_handlers[REPLY_TX] = iwlagn_rx_reply_tx;
320 }
321
322 void iwlagn_setup_deferred_work(struct iwl_priv *priv)
323 {
324         /* in agn, the tx power calibration is done in uCode */
325         priv->disable_tx_power_cal = 1;
326 }
327
328 int iwlagn_hw_valid_rtc_data_addr(u32 addr)
329 {
330         return (addr >= IWLAGN_RTC_DATA_LOWER_BOUND) &&
331                 (addr < IWLAGN_RTC_DATA_UPPER_BOUND);
332 }
333
334 int iwlagn_send_tx_power(struct iwl_priv *priv)
335 {
336         struct iwl5000_tx_power_dbm_cmd tx_power_cmd;
337         u8 tx_ant_cfg_cmd;
338
339         /* half dBm need to multiply */
340         tx_power_cmd.global_lmt = (s8)(2 * priv->tx_power_user_lmt);
341
342         if (priv->tx_power_lmt_in_half_dbm &&
343             priv->tx_power_lmt_in_half_dbm < tx_power_cmd.global_lmt) {
344                 /*
345                  * For the newer devices which using enhanced/extend tx power
346                  * table in EEPROM, the format is in half dBm. driver need to
347                  * convert to dBm format before report to mac80211.
348                  * By doing so, there is a possibility of 1/2 dBm resolution
349                  * lost. driver will perform "round-up" operation before
350                  * reporting, but it will cause 1/2 dBm tx power over the
351                  * regulatory limit. Perform the checking here, if the
352                  * "tx_power_user_lmt" is higher than EEPROM value (in
353                  * half-dBm format), lower the tx power based on EEPROM
354                  */
355                 tx_power_cmd.global_lmt = priv->tx_power_lmt_in_half_dbm;
356         }
357         tx_power_cmd.flags = IWL50_TX_POWER_NO_CLOSED;
358         tx_power_cmd.srv_chan_lmt = IWL50_TX_POWER_AUTO;
359
360         if (IWL_UCODE_API(priv->ucode_ver) == 1)
361                 tx_ant_cfg_cmd = REPLY_TX_POWER_DBM_CMD_V1;
362         else
363                 tx_ant_cfg_cmd = REPLY_TX_POWER_DBM_CMD;
364
365         return  iwl_send_cmd_pdu_async(priv, tx_ant_cfg_cmd,
366                                        sizeof(tx_power_cmd), &tx_power_cmd,
367                                        NULL);
368 }
369
370 void iwlagn_temperature(struct iwl_priv *priv)
371 {
372         /* store temperature from statistics (in Celsius) */
373         priv->temperature =
374                 le32_to_cpu(priv->_agn.statistics.general.common.temperature);
375         iwl_tt_handler(priv);
376 }
377
378 u16 iwlagn_eeprom_calib_version(struct iwl_priv *priv)
379 {
380         struct iwl_eeprom_calib_hdr {
381                 u8 version;
382                 u8 pa_type;
383                 u16 voltage;
384         } *hdr;
385
386         hdr = (struct iwl_eeprom_calib_hdr *)iwl_eeprom_query_addr(priv,
387                                                         EEPROM_CALIB_ALL);
388         return hdr->version;
389
390 }
391
392 /*
393  * EEPROM
394  */
395 static u32 eeprom_indirect_address(const struct iwl_priv *priv, u32 address)
396 {
397         u16 offset = 0;
398
399         if ((address & INDIRECT_ADDRESS) == 0)
400                 return address;
401
402         switch (address & INDIRECT_TYPE_MSK) {
403         case INDIRECT_HOST:
404                 offset = iwl_eeprom_query16(priv, EEPROM_LINK_HOST);
405                 break;
406         case INDIRECT_GENERAL:
407                 offset = iwl_eeprom_query16(priv, EEPROM_LINK_GENERAL);
408                 break;
409         case INDIRECT_REGULATORY:
410                 offset = iwl_eeprom_query16(priv, EEPROM_LINK_REGULATORY);
411                 break;
412         case INDIRECT_CALIBRATION:
413                 offset = iwl_eeprom_query16(priv, EEPROM_LINK_CALIBRATION);
414                 break;
415         case INDIRECT_PROCESS_ADJST:
416                 offset = iwl_eeprom_query16(priv, EEPROM_LINK_PROCESS_ADJST);
417                 break;
418         case INDIRECT_OTHERS:
419                 offset = iwl_eeprom_query16(priv, EEPROM_LINK_OTHERS);
420                 break;
421         default:
422                 IWL_ERR(priv, "illegal indirect type: 0x%X\n",
423                 address & INDIRECT_TYPE_MSK);
424                 break;
425         }
426
427         /* translate the offset from words to byte */
428         return (address & ADDRESS_MSK) + (offset << 1);
429 }
430
431 const u8 *iwlagn_eeprom_query_addr(const struct iwl_priv *priv,
432                                            size_t offset)
433 {
434         u32 address = eeprom_indirect_address(priv, offset);
435         BUG_ON(address >= priv->cfg->eeprom_size);
436         return &priv->eeprom[address];
437 }
438
439 struct iwl_mod_params iwlagn_mod_params = {
440         .amsdu_size_8K = 1,
441         .restart_fw = 1,
442         /* the rest are 0 by default */
443 };
444
445 void iwlagn_rx_queue_reset(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
446 {
447         unsigned long flags;
448         int i;
449         spin_lock_irqsave(&rxq->lock, flags);
450         INIT_LIST_HEAD(&rxq->rx_free);
451         INIT_LIST_HEAD(&rxq->rx_used);
452         /* Fill the rx_used queue with _all_ of the Rx buffers */
453         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) {
454                 /* In the reset function, these buffers may have been allocated
455                  * to an SKB, so we need to unmap and free potential storage */
456                 if (rxq->pool[i].page != NULL) {
457                         pci_unmap_page(priv->pci_dev, rxq->pool[i].page_dma,
458                                 PAGE_SIZE << priv->hw_params.rx_page_order,
459                                 PCI_DMA_FROMDEVICE);
460                         __iwl_free_pages(priv, rxq->pool[i].page);
461                         rxq->pool[i].page = NULL;
462                 }
463                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
464         }
465
466         for (i = 0; i < RX_QUEUE_SIZE; i++)
467                 rxq->queue[i] = NULL;
468
469         /* Set us so that we have processed and used all buffers, but have
470          * not restocked the Rx queue with fresh buffers */
471         rxq->read = rxq->write = 0;
472         rxq->write_actual = 0;
473         rxq->free_count = 0;
474         spin_unlock_irqrestore(&rxq->lock, flags);
475 }
476
477 int iwlagn_rx_init(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
478 {
479         u32 rb_size;
480         const u32 rfdnlog = RX_QUEUE_SIZE_LOG; /* 256 RBDs */
481         u32 rb_timeout = 0; /* FIXME: RX_RB_TIMEOUT for all devices? */
482
483         if (!priv->cfg->use_isr_legacy)
484                 rb_timeout = RX_RB_TIMEOUT;
485
486         if (priv->cfg->mod_params->amsdu_size_8K)
487                 rb_size = FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_8K;
488         else
489                 rb_size = FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_4K;
490
491         /* Stop Rx DMA */
492         iwl_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0);
493
494         /* Reset driver's Rx queue write index */
495         iwl_write_direct32(priv, FH_RSCSR_CHNL0_RBDCB_WPTR_REG, 0);
496
497         /* Tell device where to find RBD circular buffer in DRAM */
498         iwl_write_direct32(priv, FH_RSCSR_CHNL0_RBDCB_BASE_REG,
499                            (u32)(rxq->bd_dma >> 8));
500
501         /* Tell device where in DRAM to update its Rx status */
502         iwl_write_direct32(priv, FH_RSCSR_CHNL0_STTS_WPTR_REG,
503                            rxq->rb_stts_dma >> 4);
504
505         /* Enable Rx DMA
506          * FH_RCSR_CHNL0_RX_IGNORE_RXF_EMPTY is set because of HW bug in
507          *      the credit mechanism in 5000 HW RX FIFO
508          * Direct rx interrupts to hosts
509          * Rx buffer size 4 or 8k
510          * RB timeout 0x10
511          * 256 RBDs
512          */
513         iwl_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG,
514                            FH_RCSR_RX_CONFIG_CHNL_EN_ENABLE_VAL |
515                            FH_RCSR_CHNL0_RX_IGNORE_RXF_EMPTY |
516                            FH_RCSR_CHNL0_RX_CONFIG_IRQ_DEST_INT_HOST_VAL |
517                            FH_RCSR_CHNL0_RX_CONFIG_SINGLE_FRAME_MSK |
518                            rb_size|
519                            (rb_timeout << FH_RCSR_RX_CONFIG_REG_IRQ_RBTH_POS)|
520                            (rfdnlog << FH_RCSR_RX_CONFIG_RBDCB_SIZE_POS));
521
522         /* Set interrupt coalescing timer to default (2048 usecs) */
523         iwl_write8(priv, CSR_INT_COALESCING, IWL_HOST_INT_TIMEOUT_DEF);
524
525         return 0;
526 }
527
528 int iwlagn_hw_nic_init(struct iwl_priv *priv)
529 {
530         unsigned long flags;
531         struct iwl_rx_queue *rxq = &priv->rxq;
532         int ret;
533
534         /* nic_init */
535         spin_lock_irqsave(&priv->lock, flags);
536         priv->cfg->ops->lib->apm_ops.init(priv);
537
538         /* Set interrupt coalescing calibration timer to default (512 usecs) */
539         iwl_write8(priv, CSR_INT_COALESCING, IWL_HOST_INT_CALIB_TIMEOUT_DEF);
540
541         spin_unlock_irqrestore(&priv->lock, flags);
542
543         ret = priv->cfg->ops->lib->apm_ops.set_pwr_src(priv, IWL_PWR_SRC_VMAIN);
544
545         priv->cfg->ops->lib->apm_ops.config(priv);
546
547         /* Allocate the RX queue, or reset if it is already allocated */
548         if (!rxq->bd) {
549                 ret = iwl_rx_queue_alloc(priv);
550                 if (ret) {
551                         IWL_ERR(priv, "Unable to initialize Rx queue\n");
552                         return -ENOMEM;
553                 }
554         } else
555                 iwlagn_rx_queue_reset(priv, rxq);
556
557         iwlagn_rx_replenish(priv);
558
559         iwlagn_rx_init(priv, rxq);
560
561         spin_lock_irqsave(&priv->lock, flags);
562
563         rxq->need_update = 1;
564         iwl_rx_queue_update_write_ptr(priv, rxq);
565
566         spin_unlock_irqrestore(&priv->lock, flags);
567
568         /* Allocate or reset and init all Tx and Command queues */
569         if (!priv->txq) {
570                 ret = iwlagn_txq_ctx_alloc(priv);
571                 if (ret)
572                         return ret;
573         } else
574                 iwlagn_txq_ctx_reset(priv);
575
576         set_bit(STATUS_INIT, &priv->status);
577
578         return 0;
579 }
580
581 /**
582  * iwlagn_dma_addr2rbd_ptr - convert a DMA address to a uCode read buffer ptr
583  */
584 static inline __le32 iwlagn_dma_addr2rbd_ptr(struct iwl_priv *priv,
585                                           dma_addr_t dma_addr)
586 {
587         return cpu_to_le32((u32)(dma_addr >> 8));
588 }
589
590 /**
591  * iwlagn_rx_queue_restock - refill RX queue from pre-allocated pool
592  *
593  * If there are slots in the RX queue that need to be restocked,
594  * and we have free pre-allocated buffers, fill the ranks as much
595  * as we can, pulling from rx_free.
596  *
597  * This moves the 'write' index forward to catch up with 'processed', and
598  * also updates the memory address in the firmware to reference the new
599  * target buffer.
600  */
601 void iwlagn_rx_queue_restock(struct iwl_priv *priv)
602 {
603         struct iwl_rx_queue *rxq = &priv->rxq;
604         struct list_head *element;
605         struct iwl_rx_mem_buffer *rxb;
606         unsigned long flags;
607
608         spin_lock_irqsave(&rxq->lock, flags);
609         while ((iwl_rx_queue_space(rxq) > 0) && (rxq->free_count)) {
610                 /* The overwritten rxb must be a used one */
611                 rxb = rxq->queue[rxq->write];
612                 BUG_ON(rxb && rxb->page);
613
614                 /* Get next free Rx buffer, remove from free list */
615                 element = rxq->rx_free.next;
616                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
617                 list_del(element);
618
619                 /* Point to Rx buffer via next RBD in circular buffer */
620                 rxq->bd[rxq->write] = iwlagn_dma_addr2rbd_ptr(priv,
621                                                               rxb->page_dma);
622                 rxq->queue[rxq->write] = rxb;
623                 rxq->write = (rxq->write + 1) & RX_QUEUE_MASK;
624                 rxq->free_count--;
625         }
626         spin_unlock_irqrestore(&rxq->lock, flags);
627         /* If the pre-allocated buffer pool is dropping low, schedule to
628          * refill it */
629         if (rxq->free_count <= RX_LOW_WATERMARK)
630                 queue_work(priv->workqueue, &priv->rx_replenish);
631
632
633         /* If we've added more space for the firmware to place data, tell it.
634          * Increment device's write pointer in multiples of 8. */
635         if (rxq->write_actual != (rxq->write & ~0x7)) {
636                 spin_lock_irqsave(&rxq->lock, flags);
637                 rxq->need_update = 1;
638                 spin_unlock_irqrestore(&rxq->lock, flags);
639                 iwl_rx_queue_update_write_ptr(priv, rxq);
640         }
641 }
642
643 /**
644  * iwlagn_rx_replenish - Move all used packet from rx_used to rx_free
645  *
646  * When moving to rx_free an SKB is allocated for the slot.
647  *
648  * Also restock the Rx queue via iwl_rx_queue_restock.
649  * This is called as a scheduled work item (except for during initialization)
650  */
651 void iwlagn_rx_allocate(struct iwl_priv *priv, gfp_t priority)
652 {
653         struct iwl_rx_queue *rxq = &priv->rxq;
654         struct list_head *element;
655         struct iwl_rx_mem_buffer *rxb;
656         struct page *page;
657         unsigned long flags;
658         gfp_t gfp_mask = priority;
659
660         while (1) {
661                 spin_lock_irqsave(&rxq->lock, flags);
662                 if (list_empty(&rxq->rx_used)) {
663                         spin_unlock_irqrestore(&rxq->lock, flags);
664                         return;
665                 }
666                 spin_unlock_irqrestore(&rxq->lock, flags);
667
668                 if (rxq->free_count > RX_LOW_WATERMARK)
669                         gfp_mask |= __GFP_NOWARN;
670
671                 if (priv->hw_params.rx_page_order > 0)
672                         gfp_mask |= __GFP_COMP;
673
674                 /* Alloc a new receive buffer */
675                 page = alloc_pages(gfp_mask, priv->hw_params.rx_page_order);
676                 if (!page) {
677                         if (net_ratelimit())
678                                 IWL_DEBUG_INFO(priv, "alloc_pages failed, "
679                                                "order: %d\n",
680                                                priv->hw_params.rx_page_order);
681
682                         if ((rxq->free_count <= RX_LOW_WATERMARK) &&
683                             net_ratelimit())
684                                 IWL_CRIT(priv, "Failed to alloc_pages with %s. Only %u free buffers remaining.\n",
685                                          priority == GFP_ATOMIC ?  "GFP_ATOMIC" : "GFP_KERNEL",
686                                          rxq->free_count);
687                         /* We don't reschedule replenish work here -- we will
688                          * call the restock method and if it still needs
689                          * more buffers it will schedule replenish */
690                         return;
691                 }
692
693                 spin_lock_irqsave(&rxq->lock, flags);
694
695                 if (list_empty(&rxq->rx_used)) {
696                         spin_unlock_irqrestore(&rxq->lock, flags);
697                         __free_pages(page, priv->hw_params.rx_page_order);
698                         return;
699                 }
700                 element = rxq->rx_used.next;
701                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
702                 list_del(element);
703
704                 spin_unlock_irqrestore(&rxq->lock, flags);
705
706                 BUG_ON(rxb->page);
707                 rxb->page = page;
708                 /* Get physical address of the RB */
709                 rxb->page_dma = pci_map_page(priv->pci_dev, page, 0,
710                                 PAGE_SIZE << priv->hw_params.rx_page_order,
711                                 PCI_DMA_FROMDEVICE);
712                 /* dma address must be no more than 36 bits */
713                 BUG_ON(rxb->page_dma & ~DMA_BIT_MASK(36));
714                 /* and also 256 byte aligned! */
715                 BUG_ON(rxb->page_dma & DMA_BIT_MASK(8));
716
717                 spin_lock_irqsave(&rxq->lock, flags);
718
719                 list_add_tail(&rxb->list, &rxq->rx_free);
720                 rxq->free_count++;
721                 priv->alloc_rxb_page++;
722
723                 spin_unlock_irqrestore(&rxq->lock, flags);
724         }
725 }
726
727 void iwlagn_rx_replenish(struct iwl_priv *priv)
728 {
729         unsigned long flags;
730
731         iwlagn_rx_allocate(priv, GFP_KERNEL);
732
733         spin_lock_irqsave(&priv->lock, flags);
734         iwlagn_rx_queue_restock(priv);
735         spin_unlock_irqrestore(&priv->lock, flags);
736 }
737
738 void iwlagn_rx_replenish_now(struct iwl_priv *priv)
739 {
740         iwlagn_rx_allocate(priv, GFP_ATOMIC);
741
742         iwlagn_rx_queue_restock(priv);
743 }
744
745 /* Assumes that the skb field of the buffers in 'pool' is kept accurate.
746  * If an SKB has been detached, the POOL needs to have its SKB set to NULL
747  * This free routine walks the list of POOL entries and if SKB is set to
748  * non NULL it is unmapped and freed
749  */
750 void iwlagn_rx_queue_free(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
751 {
752         int i;
753         for (i = 0; i < RX_QUEUE_SIZE + RX_FREE_BUFFERS; i++) {
754                 if (rxq->pool[i].page != NULL) {
755                         pci_unmap_page(priv->pci_dev, rxq->pool[i].page_dma,
756                                 PAGE_SIZE << priv->hw_params.rx_page_order,
757                                 PCI_DMA_FROMDEVICE);
758                         __iwl_free_pages(priv, rxq->pool[i].page);
759                         rxq->pool[i].page = NULL;
760                 }
761         }
762
763         dma_free_coherent(&priv->pci_dev->dev, 4 * RX_QUEUE_SIZE, rxq->bd,
764                           rxq->bd_dma);
765         dma_free_coherent(&priv->pci_dev->dev, sizeof(struct iwl_rb_status),
766                           rxq->rb_stts, rxq->rb_stts_dma);
767         rxq->bd = NULL;
768         rxq->rb_stts  = NULL;
769 }
770
771 int iwlagn_rxq_stop(struct iwl_priv *priv)
772 {
773
774         /* stop Rx DMA */
775         iwl_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0);
776         iwl_poll_direct_bit(priv, FH_MEM_RSSR_RX_STATUS_REG,
777                             FH_RSSR_CHNL0_RX_STATUS_CHNL_IDLE, 1000);
778
779         return 0;
780 }
781
782 int iwlagn_hwrate_to_mac80211_idx(u32 rate_n_flags, enum ieee80211_band band)
783 {
784         int idx = 0;
785         int band_offset = 0;
786
787         /* HT rate format: mac80211 wants an MCS number, which is just LSB */
788         if (rate_n_flags & RATE_MCS_HT_MSK) {
789                 idx = (rate_n_flags & 0xff);
790                 return idx;
791         /* Legacy rate format, search for match in table */
792         } else {
793                 if (band == IEEE80211_BAND_5GHZ)
794                         band_offset = IWL_FIRST_OFDM_RATE;
795                 for (idx = band_offset; idx < IWL_RATE_COUNT_LEGACY; idx++)
796                         if (iwl_rates[idx].plcp == (rate_n_flags & 0xFF))
797                                 return idx - band_offset;
798         }
799
800         return -1;
801 }
802
803 /* Calc max signal level (dBm) among 3 possible receivers */
804 static inline int iwlagn_calc_rssi(struct iwl_priv *priv,
805                                 struct iwl_rx_phy_res *rx_resp)
806 {
807         return priv->cfg->ops->utils->calc_rssi(priv, rx_resp);
808 }
809
810 static u32 iwlagn_translate_rx_status(struct iwl_priv *priv, u32 decrypt_in)
811 {
812         u32 decrypt_out = 0;
813
814         if ((decrypt_in & RX_RES_STATUS_STATION_FOUND) ==
815                                         RX_RES_STATUS_STATION_FOUND)
816                 decrypt_out |= (RX_RES_STATUS_STATION_FOUND |
817                                 RX_RES_STATUS_NO_STATION_INFO_MISMATCH);
818
819         decrypt_out |= (decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK);
820
821         /* packet was not encrypted */
822         if ((decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) ==
823                                         RX_RES_STATUS_SEC_TYPE_NONE)
824                 return decrypt_out;
825
826         /* packet was encrypted with unknown alg */
827         if ((decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) ==
828                                         RX_RES_STATUS_SEC_TYPE_ERR)
829                 return decrypt_out;
830
831         /* decryption was not done in HW */
832         if ((decrypt_in & RX_MPDU_RES_STATUS_DEC_DONE_MSK) !=
833                                         RX_MPDU_RES_STATUS_DEC_DONE_MSK)
834                 return decrypt_out;
835
836         switch (decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) {
837
838         case RX_RES_STATUS_SEC_TYPE_CCMP:
839                 /* alg is CCM: check MIC only */
840                 if (!(decrypt_in & RX_MPDU_RES_STATUS_MIC_OK))
841                         /* Bad MIC */
842                         decrypt_out |= RX_RES_STATUS_BAD_ICV_MIC;
843                 else
844                         decrypt_out |= RX_RES_STATUS_DECRYPT_OK;
845
846                 break;
847
848         case RX_RES_STATUS_SEC_TYPE_TKIP:
849                 if (!(decrypt_in & RX_MPDU_RES_STATUS_TTAK_OK)) {
850                         /* Bad TTAK */
851                         decrypt_out |= RX_RES_STATUS_BAD_KEY_TTAK;
852                         break;
853                 }
854                 /* fall through if TTAK OK */
855         default:
856                 if (!(decrypt_in & RX_MPDU_RES_STATUS_ICV_OK))
857                         decrypt_out |= RX_RES_STATUS_BAD_ICV_MIC;
858                 else
859                         decrypt_out |= RX_RES_STATUS_DECRYPT_OK;
860                 break;
861         }
862
863         IWL_DEBUG_RX(priv, "decrypt_in:0x%x  decrypt_out = 0x%x\n",
864                                         decrypt_in, decrypt_out);
865
866         return decrypt_out;
867 }
868
869 static void iwlagn_pass_packet_to_mac80211(struct iwl_priv *priv,
870                                         struct ieee80211_hdr *hdr,
871                                         u16 len,
872                                         u32 ampdu_status,
873                                         struct iwl_rx_mem_buffer *rxb,
874                                         struct ieee80211_rx_status *stats)
875 {
876         struct sk_buff *skb;
877         __le16 fc = hdr->frame_control;
878
879         /* We only process data packets if the interface is open */
880         if (unlikely(!priv->is_open)) {
881                 IWL_DEBUG_DROP_LIMIT(priv,
882                     "Dropping packet while interface is not open.\n");
883                 return;
884         }
885
886         /* In case of HW accelerated crypto and bad decryption, drop */
887         if (!priv->cfg->mod_params->sw_crypto &&
888             iwl_set_decrypted_flag(priv, hdr, ampdu_status, stats))
889                 return;
890
891         skb = dev_alloc_skb(128);
892         if (!skb) {
893                 IWL_ERR(priv, "dev_alloc_skb failed\n");
894                 return;
895         }
896
897         skb_add_rx_frag(skb, 0, rxb->page, (void *)hdr - rxb_addr(rxb), len);
898
899         iwl_update_stats(priv, false, fc, len);
900         memcpy(IEEE80211_SKB_RXCB(skb), stats, sizeof(*stats));
901
902         ieee80211_rx(priv->hw, skb);
903         priv->alloc_rxb_page--;
904         rxb->page = NULL;
905 }
906
907 /* Called for REPLY_RX (legacy ABG frames), or
908  * REPLY_RX_MPDU_CMD (HT high-throughput N frames). */
909 void iwlagn_rx_reply_rx(struct iwl_priv *priv,
910                                 struct iwl_rx_mem_buffer *rxb)
911 {
912         struct ieee80211_hdr *header;
913         struct ieee80211_rx_status rx_status;
914         struct iwl_rx_packet *pkt = rxb_addr(rxb);
915         struct iwl_rx_phy_res *phy_res;
916         __le32 rx_pkt_status;
917         struct iwl_rx_mpdu_res_start *amsdu;
918         u32 len;
919         u32 ampdu_status;
920         u32 rate_n_flags;
921
922         /**
923          * REPLY_RX and REPLY_RX_MPDU_CMD are handled differently.
924          *      REPLY_RX: physical layer info is in this buffer
925          *      REPLY_RX_MPDU_CMD: physical layer info was sent in separate
926          *              command and cached in priv->last_phy_res
927          *
928          * Here we set up local variables depending on which command is
929          * received.
930          */
931         if (pkt->hdr.cmd == REPLY_RX) {
932                 phy_res = (struct iwl_rx_phy_res *)pkt->u.raw;
933                 header = (struct ieee80211_hdr *)(pkt->u.raw + sizeof(*phy_res)
934                                 + phy_res->cfg_phy_cnt);
935
936                 len = le16_to_cpu(phy_res->byte_count);
937                 rx_pkt_status = *(__le32 *)(pkt->u.raw + sizeof(*phy_res) +
938                                 phy_res->cfg_phy_cnt + len);
939                 ampdu_status = le32_to_cpu(rx_pkt_status);
940         } else {
941                 if (!priv->_agn.last_phy_res_valid) {
942                         IWL_ERR(priv, "MPDU frame without cached PHY data\n");
943                         return;
944                 }
945                 phy_res = &priv->_agn.last_phy_res;
946                 amsdu = (struct iwl_rx_mpdu_res_start *)pkt->u.raw;
947                 header = (struct ieee80211_hdr *)(pkt->u.raw + sizeof(*amsdu));
948                 len = le16_to_cpu(amsdu->byte_count);
949                 rx_pkt_status = *(__le32 *)(pkt->u.raw + sizeof(*amsdu) + len);
950                 ampdu_status = iwlagn_translate_rx_status(priv,
951                                 le32_to_cpu(rx_pkt_status));
952         }
953
954         if ((unlikely(phy_res->cfg_phy_cnt > 20))) {
955                 IWL_DEBUG_DROP(priv, "dsp size out of range [0,20]: %d/n",
956                                 phy_res->cfg_phy_cnt);
957                 return;
958         }
959
960         if (!(rx_pkt_status & RX_RES_STATUS_NO_CRC32_ERROR) ||
961             !(rx_pkt_status & RX_RES_STATUS_NO_RXE_OVERFLOW)) {
962                 IWL_DEBUG_RX(priv, "Bad CRC or FIFO: 0x%08X.\n",
963                                 le32_to_cpu(rx_pkt_status));
964                 return;
965         }
966
967         /* This will be used in several places later */
968         rate_n_flags = le32_to_cpu(phy_res->rate_n_flags);
969
970         /* rx_status carries information about the packet to mac80211 */
971         rx_status.mactime = le64_to_cpu(phy_res->timestamp);
972         rx_status.freq =
973                 ieee80211_channel_to_frequency(le16_to_cpu(phy_res->channel));
974         rx_status.band = (phy_res->phy_flags & RX_RES_PHY_FLAGS_BAND_24_MSK) ?
975                                 IEEE80211_BAND_2GHZ : IEEE80211_BAND_5GHZ;
976         rx_status.rate_idx =
977                 iwlagn_hwrate_to_mac80211_idx(rate_n_flags, rx_status.band);
978         rx_status.flag = 0;
979
980         /* TSF isn't reliable. In order to allow smooth user experience,
981          * this W/A doesn't propagate it to the mac80211 */
982         /*rx_status.flag |= RX_FLAG_TSFT;*/
983
984         priv->ucode_beacon_time = le32_to_cpu(phy_res->beacon_time_stamp);
985
986         /* Find max signal strength (dBm) among 3 antenna/receiver chains */
987         rx_status.signal = iwlagn_calc_rssi(priv, phy_res);
988
989         iwl_dbg_log_rx_data_frame(priv, len, header);
990         IWL_DEBUG_STATS_LIMIT(priv, "Rssi %d, TSF %llu\n",
991                 rx_status.signal, (unsigned long long)rx_status.mactime);
992
993         /*
994          * "antenna number"
995          *
996          * It seems that the antenna field in the phy flags value
997          * is actually a bit field. This is undefined by radiotap,
998          * it wants an actual antenna number but I always get "7"
999          * for most legacy frames I receive indicating that the
1000          * same frame was received on all three RX chains.
1001          *
1002          * I think this field should be removed in favor of a
1003          * new 802.11n radiotap field "RX chains" that is defined
1004          * as a bitmask.
1005          */
1006         rx_status.antenna =
1007                 (le16_to_cpu(phy_res->phy_flags) & RX_RES_PHY_FLAGS_ANTENNA_MSK)
1008                 >> RX_RES_PHY_FLAGS_ANTENNA_POS;
1009
1010         /* set the preamble flag if appropriate */
1011         if (phy_res->phy_flags & RX_RES_PHY_FLAGS_SHORT_PREAMBLE_MSK)
1012                 rx_status.flag |= RX_FLAG_SHORTPRE;
1013
1014         /* Set up the HT phy flags */
1015         if (rate_n_flags & RATE_MCS_HT_MSK)
1016                 rx_status.flag |= RX_FLAG_HT;
1017         if (rate_n_flags & RATE_MCS_HT40_MSK)
1018                 rx_status.flag |= RX_FLAG_40MHZ;
1019         if (rate_n_flags & RATE_MCS_SGI_MSK)
1020                 rx_status.flag |= RX_FLAG_SHORT_GI;
1021
1022         iwlagn_pass_packet_to_mac80211(priv, header, len, ampdu_status,
1023                                     rxb, &rx_status);
1024 }
1025
1026 /* Cache phy data (Rx signal strength, etc) for HT frame (REPLY_RX_PHY_CMD).
1027  * This will be used later in iwl_rx_reply_rx() for REPLY_RX_MPDU_CMD. */
1028 void iwlagn_rx_reply_rx_phy(struct iwl_priv *priv,
1029                             struct iwl_rx_mem_buffer *rxb)
1030 {
1031         struct iwl_rx_packet *pkt = rxb_addr(rxb);
1032         priv->_agn.last_phy_res_valid = true;
1033         memcpy(&priv->_agn.last_phy_res, pkt->u.raw,
1034                sizeof(struct iwl_rx_phy_res));
1035 }
1036
1037 static int iwl_get_single_channel_for_scan(struct iwl_priv *priv,
1038                                            struct ieee80211_vif *vif,
1039                                            enum ieee80211_band band,
1040                                            struct iwl_scan_channel *scan_ch)
1041 {
1042         const struct ieee80211_supported_band *sband;
1043         u16 passive_dwell = 0;
1044         u16 active_dwell = 0;
1045         int added = 0;
1046         u16 channel = 0;
1047
1048         sband = iwl_get_hw_mode(priv, band);
1049         if (!sband) {
1050                 IWL_ERR(priv, "invalid band\n");
1051                 return added;
1052         }
1053
1054         active_dwell = iwl_get_active_dwell_time(priv, band, 0);
1055         passive_dwell = iwl_get_passive_dwell_time(priv, band, vif);
1056
1057         if (passive_dwell <= active_dwell)
1058                 passive_dwell = active_dwell + 1;
1059
1060         channel = iwl_get_single_channel_number(priv, band);
1061         if (channel) {
1062                 scan_ch->channel = cpu_to_le16(channel);
1063                 scan_ch->type = SCAN_CHANNEL_TYPE_PASSIVE;
1064                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
1065                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
1066                 /* Set txpower levels to defaults */
1067                 scan_ch->dsp_atten = 110;
1068                 if (band == IEEE80211_BAND_5GHZ)
1069                         scan_ch->tx_gain = ((1 << 5) | (3 << 3)) | 3;
1070                 else
1071                         scan_ch->tx_gain = ((1 << 5) | (5 << 3));
1072                 added++;
1073         } else
1074                 IWL_ERR(priv, "no valid channel found\n");
1075         return added;
1076 }
1077
1078 static int iwl_get_channels_for_scan(struct iwl_priv *priv,
1079                                      struct ieee80211_vif *vif,
1080                                      enum ieee80211_band band,
1081                                      u8 is_active, u8 n_probes,
1082                                      struct iwl_scan_channel *scan_ch)
1083 {
1084         struct ieee80211_channel *chan;
1085         const struct ieee80211_supported_band *sband;
1086         const struct iwl_channel_info *ch_info;
1087         u16 passive_dwell = 0;
1088         u16 active_dwell = 0;
1089         int added, i;
1090         u16 channel;
1091
1092         sband = iwl_get_hw_mode(priv, band);
1093         if (!sband)
1094                 return 0;
1095
1096         active_dwell = iwl_get_active_dwell_time(priv, band, n_probes);
1097         passive_dwell = iwl_get_passive_dwell_time(priv, band, vif);
1098
1099         if (passive_dwell <= active_dwell)
1100                 passive_dwell = active_dwell + 1;
1101
1102         for (i = 0, added = 0; i < priv->scan_request->n_channels; i++) {
1103                 chan = priv->scan_request->channels[i];
1104
1105                 if (chan->band != band)
1106                         continue;
1107
1108                 channel = chan->hw_value;
1109                 scan_ch->channel = cpu_to_le16(channel);
1110
1111                 ch_info = iwl_get_channel_info(priv, band, channel);
1112                 if (!is_channel_valid(ch_info)) {
1113                         IWL_DEBUG_SCAN(priv, "Channel %d is INVALID for this band.\n",
1114                                         channel);
1115                         continue;
1116                 }
1117
1118                 if (!is_active || is_channel_passive(ch_info) ||
1119                     (chan->flags & IEEE80211_CHAN_PASSIVE_SCAN))
1120                         scan_ch->type = SCAN_CHANNEL_TYPE_PASSIVE;
1121                 else
1122                         scan_ch->type = SCAN_CHANNEL_TYPE_ACTIVE;
1123
1124                 if (n_probes)
1125                         scan_ch->type |= IWL_SCAN_PROBE_MASK(n_probes);
1126
1127                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
1128                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
1129
1130                 /* Set txpower levels to defaults */
1131                 scan_ch->dsp_atten = 110;
1132
1133                 /* NOTE: if we were doing 6Mb OFDM for scans we'd use
1134                  * power level:
1135                  * scan_ch->tx_gain = ((1 << 5) | (2 << 3)) | 3;
1136                  */
1137                 if (band == IEEE80211_BAND_5GHZ)
1138                         scan_ch->tx_gain = ((1 << 5) | (3 << 3)) | 3;
1139                 else
1140                         scan_ch->tx_gain = ((1 << 5) | (5 << 3));
1141
1142                 IWL_DEBUG_SCAN(priv, "Scanning ch=%d prob=0x%X [%s %d]\n",
1143                                channel, le32_to_cpu(scan_ch->type),
1144                                (scan_ch->type & SCAN_CHANNEL_TYPE_ACTIVE) ?
1145                                 "ACTIVE" : "PASSIVE",
1146                                (scan_ch->type & SCAN_CHANNEL_TYPE_ACTIVE) ?
1147                                active_dwell : passive_dwell);
1148
1149                 scan_ch++;
1150                 added++;
1151         }
1152
1153         IWL_DEBUG_SCAN(priv, "total channels to scan %d\n", added);
1154         return added;
1155 }
1156
1157 void iwlagn_request_scan(struct iwl_priv *priv, struct ieee80211_vif *vif)
1158 {
1159         struct iwl_host_cmd cmd = {
1160                 .id = REPLY_SCAN_CMD,
1161                 .len = sizeof(struct iwl_scan_cmd),
1162                 .flags = CMD_SIZE_HUGE,
1163         };
1164         struct iwl_scan_cmd *scan;
1165         struct ieee80211_conf *conf = NULL;
1166         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
1167         u32 rate_flags = 0;
1168         u16 cmd_len;
1169         u16 rx_chain = 0;
1170         enum ieee80211_band band;
1171         u8 n_probes = 0;
1172         u8 rx_ant = priv->hw_params.valid_rx_ant;
1173         u8 rate;
1174         bool is_active = false;
1175         int  chan_mod;
1176         u8 active_chains;
1177         u8 scan_tx_antennas = priv->hw_params.valid_tx_ant;
1178
1179         if (vif)
1180                 ctx = iwl_rxon_ctx_from_vif(vif);
1181
1182         conf = ieee80211_get_hw_conf(priv->hw);
1183
1184         cancel_delayed_work(&priv->scan_check);
1185
1186         if (!iwl_is_ready(priv)) {
1187                 IWL_WARN(priv, "request scan called when driver not ready.\n");
1188                 goto done;
1189         }
1190
1191         /* Make sure the scan wasn't canceled before this queued work
1192          * was given the chance to run... */
1193         if (!test_bit(STATUS_SCANNING, &priv->status))
1194                 goto done;
1195
1196         /* This should never be called or scheduled if there is currently
1197          * a scan active in the hardware. */
1198         if (test_bit(STATUS_SCAN_HW, &priv->status)) {
1199                 IWL_DEBUG_INFO(priv, "Multiple concurrent scan requests in parallel. "
1200                                "Ignoring second request.\n");
1201                 goto done;
1202         }
1203
1204         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
1205                 IWL_DEBUG_SCAN(priv, "Aborting scan due to device shutdown\n");
1206                 goto done;
1207         }
1208
1209         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
1210                 IWL_DEBUG_HC(priv, "Scan request while abort pending.  Queuing.\n");
1211                 goto done;
1212         }
1213
1214         if (iwl_is_rfkill(priv)) {
1215                 IWL_DEBUG_HC(priv, "Aborting scan due to RF Kill activation\n");
1216                 goto done;
1217         }
1218
1219         if (!test_bit(STATUS_READY, &priv->status)) {
1220                 IWL_DEBUG_HC(priv, "Scan request while uninitialized.  Queuing.\n");
1221                 goto done;
1222         }
1223
1224         if (!priv->scan_cmd) {
1225                 priv->scan_cmd = kmalloc(sizeof(struct iwl_scan_cmd) +
1226                                          IWL_MAX_SCAN_SIZE, GFP_KERNEL);
1227                 if (!priv->scan_cmd) {
1228                         IWL_DEBUG_SCAN(priv,
1229                                        "fail to allocate memory for scan\n");
1230                         goto done;
1231                 }
1232         }
1233         scan = priv->scan_cmd;
1234         memset(scan, 0, sizeof(struct iwl_scan_cmd) + IWL_MAX_SCAN_SIZE);
1235
1236         scan->quiet_plcp_th = IWL_PLCP_QUIET_THRESH;
1237         scan->quiet_time = IWL_ACTIVE_QUIET_TIME;
1238
1239         if (iwl_is_any_associated(priv)) {
1240                 u16 interval = 0;
1241                 u32 extra;
1242                 u32 suspend_time = 100;
1243                 u32 scan_suspend_time = 100;
1244                 unsigned long flags;
1245
1246                 IWL_DEBUG_INFO(priv, "Scanning while associated...\n");
1247                 spin_lock_irqsave(&priv->lock, flags);
1248                 if (priv->is_internal_short_scan)
1249                         interval = 0;
1250                 else
1251                         interval = vif->bss_conf.beacon_int;
1252                 spin_unlock_irqrestore(&priv->lock, flags);
1253
1254                 scan->suspend_time = 0;
1255                 scan->max_out_time = cpu_to_le32(200 * 1024);
1256                 if (!interval)
1257                         interval = suspend_time;
1258
1259                 extra = (suspend_time / interval) << 22;
1260                 scan_suspend_time = (extra |
1261                     ((suspend_time % interval) * 1024));
1262                 scan->suspend_time = cpu_to_le32(scan_suspend_time);
1263                 IWL_DEBUG_SCAN(priv, "suspend_time 0x%X beacon interval %d\n",
1264                                scan_suspend_time, interval);
1265         }
1266
1267         if (priv->is_internal_short_scan) {
1268                 IWL_DEBUG_SCAN(priv, "Start internal passive scan.\n");
1269         } else if (priv->scan_request->n_ssids) {
1270                 int i, p = 0;
1271                 IWL_DEBUG_SCAN(priv, "Kicking off active scan\n");
1272                 for (i = 0; i < priv->scan_request->n_ssids; i++) {
1273                         /* always does wildcard anyway */
1274                         if (!priv->scan_request->ssids[i].ssid_len)
1275                                 continue;
1276                         scan->direct_scan[p].id = WLAN_EID_SSID;
1277                         scan->direct_scan[p].len =
1278                                 priv->scan_request->ssids[i].ssid_len;
1279                         memcpy(scan->direct_scan[p].ssid,
1280                                priv->scan_request->ssids[i].ssid,
1281                                priv->scan_request->ssids[i].ssid_len);
1282                         n_probes++;
1283                         p++;
1284                 }
1285                 is_active = true;
1286         } else
1287                 IWL_DEBUG_SCAN(priv, "Start passive scan.\n");
1288
1289         scan->tx_cmd.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK;
1290         scan->tx_cmd.sta_id = ctx->bcast_sta_id;
1291         scan->tx_cmd.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
1292
1293         switch (priv->scan_band) {
1294         case IEEE80211_BAND_2GHZ:
1295                 scan->flags = RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK;
1296                 chan_mod = le32_to_cpu(
1297                         priv->contexts[IWL_RXON_CTX_BSS].active.flags &
1298                                                 RXON_FLG_CHANNEL_MODE_MSK)
1299                                        >> RXON_FLG_CHANNEL_MODE_POS;
1300                 if (chan_mod == CHANNEL_MODE_PURE_40) {
1301                         rate = IWL_RATE_6M_PLCP;
1302                 } else {
1303                         rate = IWL_RATE_1M_PLCP;
1304                         rate_flags = RATE_MCS_CCK_MSK;
1305                 }
1306                 /*
1307                  * Internal scans are passive, so we can indiscriminately set
1308                  * the BT ignore flag on 2.4 GHz since it applies to TX only.
1309                  */
1310                 if (priv->cfg->advanced_bt_coexist)
1311                         scan->tx_cmd.tx_flags |= TX_CMD_FLG_IGNORE_BT;
1312                 scan->good_CRC_th = IWL_GOOD_CRC_TH_DISABLED;
1313                 break;
1314         case IEEE80211_BAND_5GHZ:
1315                 rate = IWL_RATE_6M_PLCP;
1316                 /*
1317                  * If active scanning is requested but a certain channel is
1318                  * marked passive, we can do active scanning if we detect
1319                  * transmissions.
1320                  *
1321                  * There is an issue with some firmware versions that triggers
1322                  * a sysassert on a "good CRC threshold" of zero (== disabled),
1323                  * on a radar channel even though this means that we should NOT
1324                  * send probes.
1325                  *
1326                  * The "good CRC threshold" is the number of frames that we
1327                  * need to receive during our dwell time on a channel before
1328                  * sending out probes -- setting this to a huge value will
1329                  * mean we never reach it, but at the same time work around
1330                  * the aforementioned issue. Thus use IWL_GOOD_CRC_TH_NEVER
1331                  * here instead of IWL_GOOD_CRC_TH_DISABLED.
1332                  */
1333                 scan->good_CRC_th = is_active ? IWL_GOOD_CRC_TH_DEFAULT :
1334                                                 IWL_GOOD_CRC_TH_NEVER;
1335                 break;
1336         default:
1337                 IWL_WARN(priv, "Invalid scan band count\n");
1338                 goto done;
1339         }
1340
1341         band = priv->scan_band;
1342
1343         if (priv->cfg->scan_rx_antennas[band])
1344                 rx_ant = priv->cfg->scan_rx_antennas[band];
1345
1346         if (priv->cfg->scan_tx_antennas[band])
1347                 scan_tx_antennas = priv->cfg->scan_tx_antennas[band];
1348
1349         if (priv->cfg->advanced_bt_coexist && priv->bt_full_concurrent) {
1350                 /* operated as 1x1 in full concurrency mode */
1351                 scan_tx_antennas =
1352                         first_antenna(priv->cfg->scan_tx_antennas[band]);
1353         }
1354
1355         priv->scan_tx_ant[band] = iwl_toggle_tx_ant(priv, priv->scan_tx_ant[band],
1356                                                     scan_tx_antennas);
1357         rate_flags |= iwl_ant_idx_to_flags(priv->scan_tx_ant[band]);
1358         scan->tx_cmd.rate_n_flags = iwl_hw_set_rate_n_flags(rate, rate_flags);
1359
1360         /* In power save mode use one chain, otherwise use all chains */
1361         if (test_bit(STATUS_POWER_PMI, &priv->status)) {
1362                 /* rx_ant has been set to all valid chains previously */
1363                 active_chains = rx_ant &
1364                                 ((u8)(priv->chain_noise_data.active_chains));
1365                 if (!active_chains)
1366                         active_chains = rx_ant;
1367
1368                 IWL_DEBUG_SCAN(priv, "chain_noise_data.active_chains: %u\n",
1369                                 priv->chain_noise_data.active_chains);
1370
1371                 rx_ant = first_antenna(active_chains);
1372         }
1373         if (priv->cfg->advanced_bt_coexist && priv->bt_full_concurrent) {
1374                 /* operated as 1x1 in full concurrency mode */
1375                 rx_ant = first_antenna(rx_ant);
1376         }
1377
1378         /* MIMO is not used here, but value is required */
1379         rx_chain |= priv->hw_params.valid_rx_ant << RXON_RX_CHAIN_VALID_POS;
1380         rx_chain |= rx_ant << RXON_RX_CHAIN_FORCE_MIMO_SEL_POS;
1381         rx_chain |= rx_ant << RXON_RX_CHAIN_FORCE_SEL_POS;
1382         rx_chain |= 0x1 << RXON_RX_CHAIN_DRIVER_FORCE_POS;
1383         scan->rx_chain = cpu_to_le16(rx_chain);
1384         if (!priv->is_internal_short_scan) {
1385                 cmd_len = iwl_fill_probe_req(priv,
1386                                         (struct ieee80211_mgmt *)scan->data,
1387                                         vif->addr,
1388                                         priv->scan_request->ie,
1389                                         priv->scan_request->ie_len,
1390                                         IWL_MAX_SCAN_SIZE - sizeof(*scan));
1391         } else {
1392                 /* use bcast addr, will not be transmitted but must be valid */
1393                 cmd_len = iwl_fill_probe_req(priv,
1394                                         (struct ieee80211_mgmt *)scan->data,
1395                                         iwl_bcast_addr, NULL, 0,
1396                                         IWL_MAX_SCAN_SIZE - sizeof(*scan));
1397
1398         }
1399         scan->tx_cmd.len = cpu_to_le16(cmd_len);
1400
1401         scan->filter_flags |= (RXON_FILTER_ACCEPT_GRP_MSK |
1402                                RXON_FILTER_BCON_AWARE_MSK);
1403
1404         if (priv->is_internal_short_scan) {
1405                 scan->channel_count =
1406                         iwl_get_single_channel_for_scan(priv, vif, band,
1407                                 (void *)&scan->data[le16_to_cpu(
1408                                 scan->tx_cmd.len)]);
1409         } else {
1410                 scan->channel_count =
1411                         iwl_get_channels_for_scan(priv, vif, band,
1412                                 is_active, n_probes,
1413                                 (void *)&scan->data[le16_to_cpu(
1414                                 scan->tx_cmd.len)]);
1415         }
1416         if (scan->channel_count == 0) {
1417                 IWL_DEBUG_SCAN(priv, "channel count %d\n", scan->channel_count);
1418                 goto done;
1419         }
1420
1421         cmd.len += le16_to_cpu(scan->tx_cmd.len) +
1422             scan->channel_count * sizeof(struct iwl_scan_channel);
1423         cmd.data = scan;
1424         scan->len = cpu_to_le16(cmd.len);
1425
1426         set_bit(STATUS_SCAN_HW, &priv->status);
1427
1428         if (priv->cfg->ops->hcmd->set_pan_params &&
1429             priv->cfg->ops->hcmd->set_pan_params(priv))
1430                 goto done;
1431
1432         if (iwl_send_cmd_sync(priv, &cmd))
1433                 goto done;
1434
1435         queue_delayed_work(priv->workqueue, &priv->scan_check,
1436                            IWL_SCAN_CHECK_WATCHDOG);
1437
1438         return;
1439
1440  done:
1441         /* Cannot perform scan. Make sure we clear scanning
1442         * bits from status so next scan request can be performed.
1443         * If we don't clear scanning status bit here all next scan
1444         * will fail
1445         */
1446         clear_bit(STATUS_SCAN_HW, &priv->status);
1447         clear_bit(STATUS_SCANNING, &priv->status);
1448         /* inform mac80211 scan aborted */
1449         queue_work(priv->workqueue, &priv->scan_completed);
1450 }
1451
1452 int iwlagn_manage_ibss_station(struct iwl_priv *priv,
1453                                struct ieee80211_vif *vif, bool add)
1454 {
1455         struct iwl_vif_priv *vif_priv = (void *)vif->drv_priv;
1456
1457         if (add)
1458                 return iwl_add_bssid_station(priv, vif_priv->ctx,
1459                                              vif->bss_conf.bssid, true,
1460                                              &vif_priv->ibss_bssid_sta_id);
1461         return iwl_remove_station(priv, vif_priv->ibss_bssid_sta_id,
1462                                   vif->bss_conf.bssid);
1463 }
1464
1465 void iwl_free_tfds_in_queue(struct iwl_priv *priv,
1466                             int sta_id, int tid, int freed)
1467 {
1468         lockdep_assert_held(&priv->sta_lock);
1469
1470         if (priv->stations[sta_id].tid[tid].tfds_in_queue >= freed)
1471                 priv->stations[sta_id].tid[tid].tfds_in_queue -= freed;
1472         else {
1473                 IWL_DEBUG_TX(priv, "free more than tfds_in_queue (%u:%d)\n",
1474                         priv->stations[sta_id].tid[tid].tfds_in_queue,
1475                         freed);
1476                 priv->stations[sta_id].tid[tid].tfds_in_queue = 0;
1477         }
1478 }
1479
1480 #define IWL_FLUSH_WAIT_MS       2000
1481
1482 int iwlagn_wait_tx_queue_empty(struct iwl_priv *priv)
1483 {
1484         struct iwl_tx_queue *txq;
1485         struct iwl_queue *q;
1486         int cnt;
1487         unsigned long now = jiffies;
1488         int ret = 0;
1489
1490         /* waiting for all the tx frames complete might take a while */
1491         for (cnt = 0; cnt < priv->hw_params.max_txq_num; cnt++) {
1492                 if (cnt == priv->cmd_queue)
1493                         continue;
1494                 txq = &priv->txq[cnt];
1495                 q = &txq->q;
1496                 while (q->read_ptr != q->write_ptr && !time_after(jiffies,
1497                        now + msecs_to_jiffies(IWL_FLUSH_WAIT_MS)))
1498                                 msleep(1);
1499
1500                 if (q->read_ptr != q->write_ptr) {
1501                         IWL_ERR(priv, "fail to flush all tx fifo queues\n");
1502                         ret = -ETIMEDOUT;
1503                         break;
1504                 }
1505         }
1506         return ret;
1507 }
1508
1509 #define IWL_TX_QUEUE_MSK        0xfffff
1510
1511 /**
1512  * iwlagn_txfifo_flush: send REPLY_TXFIFO_FLUSH command to uCode
1513  *
1514  * pre-requirements:
1515  *  1. acquire mutex before calling
1516  *  2. make sure rf is on and not in exit state
1517  */
1518 int iwlagn_txfifo_flush(struct iwl_priv *priv, u16 flush_control)
1519 {
1520         struct iwl_txfifo_flush_cmd flush_cmd;
1521         struct iwl_host_cmd cmd = {
1522                 .id = REPLY_TXFIFO_FLUSH,
1523                 .len = sizeof(struct iwl_txfifo_flush_cmd),
1524                 .flags = CMD_SYNC,
1525                 .data = &flush_cmd,
1526         };
1527
1528         might_sleep();
1529
1530         memset(&flush_cmd, 0, sizeof(flush_cmd));
1531         flush_cmd.fifo_control = IWL_TX_FIFO_VO_MSK | IWL_TX_FIFO_VI_MSK |
1532                                  IWL_TX_FIFO_BE_MSK | IWL_TX_FIFO_BK_MSK;
1533         if (priv->cfg->sku & IWL_SKU_N)
1534                 flush_cmd.fifo_control |= IWL_AGG_TX_QUEUE_MSK;
1535
1536         IWL_DEBUG_INFO(priv, "fifo queue control: 0X%x\n",
1537                        flush_cmd.fifo_control);
1538         flush_cmd.flush_control = cpu_to_le16(flush_control);
1539
1540         return iwl_send_cmd(priv, &cmd);
1541 }
1542
1543 void iwlagn_dev_txfifo_flush(struct iwl_priv *priv, u16 flush_control)
1544 {
1545         mutex_lock(&priv->mutex);
1546         ieee80211_stop_queues(priv->hw);
1547         if (priv->cfg->ops->lib->txfifo_flush(priv, IWL_DROP_ALL)) {
1548                 IWL_ERR(priv, "flush request fail\n");
1549                 goto done;
1550         }
1551         IWL_DEBUG_INFO(priv, "wait transmit/flush all frames\n");
1552         iwlagn_wait_tx_queue_empty(priv);
1553 done:
1554         ieee80211_wake_queues(priv->hw);
1555         mutex_unlock(&priv->mutex);
1556 }
1557
1558 /*
1559  * BT coex
1560  */
1561 /*
1562  * Macros to access the lookup table.
1563  *
1564  * The lookup table has 7 inputs: bt3_prio, bt3_txrx, bt_rf_act, wifi_req,
1565 * wifi_prio, wifi_txrx and wifi_sh_ant_req.
1566  *
1567  * It has three outputs: WLAN_ACTIVE, WLAN_KILL and ANT_SWITCH
1568  *
1569  * The format is that "registers" 8 through 11 contain the WLAN_ACTIVE bits
1570  * one after another in 32-bit registers, and "registers" 0 through 7 contain
1571  * the WLAN_KILL and ANT_SWITCH bits interleaved (in that order).
1572  *
1573  * These macros encode that format.
1574  */
1575 #define LUT_VALUE(bt3_prio, bt3_txrx, bt_rf_act, wifi_req, wifi_prio, \
1576                   wifi_txrx, wifi_sh_ant_req) \
1577         (bt3_prio | (bt3_txrx << 1) | (bt_rf_act << 2) | (wifi_req << 3) | \
1578         (wifi_prio << 4) | (wifi_txrx << 5) | (wifi_sh_ant_req << 6))
1579
1580 #define LUT_PTA_WLAN_ACTIVE_OP(lut, op, val) \
1581         lut[8 + ((val) >> 5)] op (cpu_to_le32(BIT((val) & 0x1f)))
1582 #define LUT_TEST_PTA_WLAN_ACTIVE(lut, bt3_prio, bt3_txrx, bt_rf_act, wifi_req, \
1583                                  wifi_prio, wifi_txrx, wifi_sh_ant_req) \
1584         (!!(LUT_PTA_WLAN_ACTIVE_OP(lut, &, LUT_VALUE(bt3_prio, bt3_txrx, \
1585                                    bt_rf_act, wifi_req, wifi_prio, wifi_txrx, \
1586                                    wifi_sh_ant_req))))
1587 #define LUT_SET_PTA_WLAN_ACTIVE(lut, bt3_prio, bt3_txrx, bt_rf_act, wifi_req, \
1588                                 wifi_prio, wifi_txrx, wifi_sh_ant_req) \
1589         LUT_PTA_WLAN_ACTIVE_OP(lut, |=, LUT_VALUE(bt3_prio, bt3_txrx, \
1590                                bt_rf_act, wifi_req, wifi_prio, wifi_txrx, \
1591                                wifi_sh_ant_req))
1592 #define LUT_CLEAR_PTA_WLAN_ACTIVE(lut, bt3_prio, bt3_txrx, bt_rf_act, \
1593                                   wifi_req, wifi_prio, wifi_txrx, \
1594                                   wifi_sh_ant_req) \
1595         LUT_PTA_WLAN_ACTIVE_OP(lut, &= ~, LUT_VALUE(bt3_prio, bt3_txrx, \
1596                                bt_rf_act, wifi_req, wifi_prio, wifi_txrx, \
1597                                wifi_sh_ant_req))
1598
1599 #define LUT_WLAN_KILL_OP(lut, op, val) \
1600         lut[(val) >> 4] op (cpu_to_le32(BIT(((val) << 1) & 0x1e)))
1601 #define LUT_TEST_WLAN_KILL(lut, bt3_prio, bt3_txrx, bt_rf_act, wifi_req, \
1602                            wifi_prio, wifi_txrx, wifi_sh_ant_req) \
1603         (!!(LUT_WLAN_KILL_OP(lut, &, LUT_VALUE(bt3_prio, bt3_txrx, bt_rf_act, \
1604                              wifi_req, wifi_prio, wifi_txrx, wifi_sh_ant_req))))
1605 #define LUT_SET_WLAN_KILL(lut, bt3_prio, bt3_txrx, bt_rf_act, wifi_req, \
1606                           wifi_prio, wifi_txrx, wifi_sh_ant_req) \
1607         LUT_WLAN_KILL_OP(lut, |=, LUT_VALUE(bt3_prio, bt3_txrx, bt_rf_act, \
1608                          wifi_req, wifi_prio, wifi_txrx, wifi_sh_ant_req))
1609 #define LUT_CLEAR_WLAN_KILL(lut, bt3_prio, bt3_txrx, bt_rf_act, wifi_req, \
1610                             wifi_prio, wifi_txrx, wifi_sh_ant_req) \
1611         LUT_WLAN_KILL_OP(lut, &= ~, LUT_VALUE(bt3_prio, bt3_txrx, bt_rf_act, \
1612                          wifi_req, wifi_prio, wifi_txrx, wifi_sh_ant_req))
1613
1614 #define LUT_ANT_SWITCH_OP(lut, op, val) \
1615         lut[(val) >> 4] op (cpu_to_le32(BIT((((val) << 1) & 0x1e) + 1)))
1616 #define LUT_TEST_ANT_SWITCH(lut, bt3_prio, bt3_txrx, bt_rf_act, wifi_req, \
1617                             wifi_prio, wifi_txrx, wifi_sh_ant_req) \
1618         (!!(LUT_ANT_SWITCH_OP(lut, &, LUT_VALUE(bt3_prio, bt3_txrx, bt_rf_act, \
1619                               wifi_req, wifi_prio, wifi_txrx, \
1620                               wifi_sh_ant_req))))
1621 #define LUT_SET_ANT_SWITCH(lut, bt3_prio, bt3_txrx, bt_rf_act, wifi_req, \
1622                            wifi_prio, wifi_txrx, wifi_sh_ant_req) \
1623         LUT_ANT_SWITCH_OP(lut, |=, LUT_VALUE(bt3_prio, bt3_txrx, bt_rf_act, \
1624                           wifi_req, wifi_prio, wifi_txrx, wifi_sh_ant_req))
1625 #define LUT_CLEAR_ANT_SWITCH(lut, bt3_prio, bt3_txrx, bt_rf_act, wifi_req, \
1626                              wifi_prio, wifi_txrx, wifi_sh_ant_req) \
1627         LUT_ANT_SWITCH_OP(lut, &= ~, LUT_VALUE(bt3_prio, bt3_txrx, bt_rf_act, \
1628                           wifi_req, wifi_prio, wifi_txrx, wifi_sh_ant_req))
1629
1630 static const __le32 iwlagn_def_3w_lookup[12] = {
1631         cpu_to_le32(0xaaaaaaaa),
1632         cpu_to_le32(0xaaaaaaaa),
1633         cpu_to_le32(0xaeaaaaaa),
1634         cpu_to_le32(0xaaaaaaaa),
1635         cpu_to_le32(0xcc00ff28),
1636         cpu_to_le32(0x0000aaaa),
1637         cpu_to_le32(0xcc00aaaa),
1638         cpu_to_le32(0x0000aaaa),
1639         cpu_to_le32(0xc0004000),
1640         cpu_to_le32(0x00004000),
1641         cpu_to_le32(0xf0005000),
1642         cpu_to_le32(0xf0004000),
1643 };
1644
1645 static const __le32 iwlagn_concurrent_lookup[12] = {
1646         cpu_to_le32(0xaaaaaaaa),
1647         cpu_to_le32(0xaaaaaaaa),
1648         cpu_to_le32(0xaaaaaaaa),
1649         cpu_to_le32(0xaaaaaaaa),
1650         cpu_to_le32(0xaaaaaaaa),
1651         cpu_to_le32(0xaaaaaaaa),
1652         cpu_to_le32(0xaaaaaaaa),
1653         cpu_to_le32(0xaaaaaaaa),
1654         cpu_to_le32(0x00000000),
1655         cpu_to_le32(0x00000000),
1656         cpu_to_le32(0x00000000),
1657         cpu_to_le32(0x00000000),
1658 };
1659
1660 void iwlagn_send_advance_bt_config(struct iwl_priv *priv)
1661 {
1662         struct iwlagn_bt_cmd bt_cmd = {
1663                 .max_kill = IWLAGN_BT_MAX_KILL_DEFAULT,
1664                 .bt3_timer_t7_value = IWLAGN_BT3_T7_DEFAULT,
1665                 .bt3_prio_sample_time = IWLAGN_BT3_PRIO_SAMPLE_DEFAULT,
1666                 .bt3_timer_t2_value = IWLAGN_BT3_T2_DEFAULT,
1667         };
1668
1669         BUILD_BUG_ON(sizeof(iwlagn_def_3w_lookup) !=
1670                         sizeof(bt_cmd.bt3_lookup_table));
1671
1672         bt_cmd.prio_boost = priv->cfg->bt_prio_boost;
1673         bt_cmd.kill_ack_mask = priv->kill_ack_mask;
1674         bt_cmd.kill_cts_mask = priv->kill_cts_mask;
1675         bt_cmd.valid = priv->bt_valid;
1676
1677         /*
1678          * Configure BT coex mode to "no coexistence" when the
1679          * user disabled BT coexistence, we have no interface
1680          * (might be in monitor mode), or the interface is in
1681          * IBSS mode (no proper uCode support for coex then).
1682          */
1683         if (!bt_coex_active || priv->iw_mode == NL80211_IFTYPE_ADHOC) {
1684                 bt_cmd.flags = 0;
1685         } else {
1686                 bt_cmd.flags = IWLAGN_BT_FLAG_COEX_MODE_3W <<
1687                                         IWLAGN_BT_FLAG_COEX_MODE_SHIFT;
1688                 if (priv->bt_ch_announce)
1689                         bt_cmd.flags |= IWLAGN_BT_FLAG_CHANNEL_INHIBITION;
1690                 IWL_DEBUG_INFO(priv, "BT coex flag: 0X%x\n", bt_cmd.flags);
1691         }
1692         if (priv->bt_full_concurrent)
1693                 memcpy(bt_cmd.bt3_lookup_table, iwlagn_concurrent_lookup,
1694                         sizeof(iwlagn_concurrent_lookup));
1695         else
1696                 memcpy(bt_cmd.bt3_lookup_table, iwlagn_def_3w_lookup,
1697                         sizeof(iwlagn_def_3w_lookup));
1698
1699         IWL_DEBUG_INFO(priv, "BT coex %s in %s mode\n",
1700                        bt_cmd.flags ? "active" : "disabled",
1701                        priv->bt_full_concurrent ?
1702                        "full concurrency" : "3-wire");
1703
1704         if (iwl_send_cmd_pdu(priv, REPLY_BT_CONFIG, sizeof(bt_cmd), &bt_cmd))
1705                 IWL_ERR(priv, "failed to send BT Coex Config\n");
1706
1707         /*
1708          * When we are doing a restart, need to also reconfigure BT
1709          * SCO to the device. If not doing a restart, bt_sco_active
1710          * will always be false, so there's no need to have an extra
1711          * variable to check for it.
1712          */
1713         if (priv->bt_sco_active) {
1714                 struct iwlagn_bt_sco_cmd sco_cmd = { .flags = 0 };
1715
1716                 if (priv->bt_sco_active)
1717                         sco_cmd.flags |= IWLAGN_BT_SCO_ACTIVE;
1718                 if (iwl_send_cmd_pdu(priv, REPLY_BT_COEX_SCO,
1719                                      sizeof(sco_cmd), &sco_cmd))
1720                         IWL_ERR(priv, "failed to send BT SCO command\n");
1721         }
1722 }
1723
1724 static void iwlagn_bt_traffic_change_work(struct work_struct *work)
1725 {
1726         struct iwl_priv *priv =
1727                 container_of(work, struct iwl_priv, bt_traffic_change_work);
1728         struct iwl_rxon_context *ctx;
1729         int smps_request = -1;
1730
1731         IWL_DEBUG_INFO(priv, "BT traffic load changes: %d\n",
1732                        priv->bt_traffic_load);
1733
1734         switch (priv->bt_traffic_load) {
1735         case IWL_BT_COEX_TRAFFIC_LOAD_NONE:
1736                 smps_request = IEEE80211_SMPS_AUTOMATIC;
1737                 break;
1738         case IWL_BT_COEX_TRAFFIC_LOAD_LOW:
1739                 smps_request = IEEE80211_SMPS_DYNAMIC;
1740                 break;
1741         case IWL_BT_COEX_TRAFFIC_LOAD_HIGH:
1742         case IWL_BT_COEX_TRAFFIC_LOAD_CONTINUOUS:
1743                 smps_request = IEEE80211_SMPS_STATIC;
1744                 break;
1745         default:
1746                 IWL_ERR(priv, "Invalid BT traffic load: %d\n",
1747                         priv->bt_traffic_load);
1748                 break;
1749         }
1750
1751         mutex_lock(&priv->mutex);
1752
1753         if (priv->cfg->ops->lib->update_chain_flags)
1754                 priv->cfg->ops->lib->update_chain_flags(priv);
1755
1756         if (smps_request != -1) {
1757                 for_each_context(priv, ctx) {
1758                         if (ctx->vif && ctx->vif->type == NL80211_IFTYPE_STATION)
1759                                 ieee80211_request_smps(ctx->vif, smps_request);
1760                 }
1761         }
1762
1763         mutex_unlock(&priv->mutex);
1764 }
1765
1766 static void iwlagn_print_uartmsg(struct iwl_priv *priv,
1767                                 struct iwl_bt_uart_msg *uart_msg)
1768 {
1769         IWL_DEBUG_NOTIF(priv, "Message Type = 0x%X, SSN = 0x%X, "
1770                         "Update Req = 0x%X",
1771                 (BT_UART_MSG_FRAME1MSGTYPE_MSK & uart_msg->frame1) >>
1772                         BT_UART_MSG_FRAME1MSGTYPE_POS,
1773                 (BT_UART_MSG_FRAME1SSN_MSK & uart_msg->frame1) >>
1774                         BT_UART_MSG_FRAME1SSN_POS,
1775                 (BT_UART_MSG_FRAME1UPDATEREQ_MSK & uart_msg->frame1) >>
1776                         BT_UART_MSG_FRAME1UPDATEREQ_POS);
1777
1778         IWL_DEBUG_NOTIF(priv, "Open connections = 0x%X, Traffic load = 0x%X, "
1779                         "Chl_SeqN = 0x%X, In band = 0x%X",
1780                 (BT_UART_MSG_FRAME2OPENCONNECTIONS_MSK & uart_msg->frame2) >>
1781                         BT_UART_MSG_FRAME2OPENCONNECTIONS_POS,
1782                 (BT_UART_MSG_FRAME2TRAFFICLOAD_MSK & uart_msg->frame2) >>
1783                         BT_UART_MSG_FRAME2TRAFFICLOAD_POS,
1784                 (BT_UART_MSG_FRAME2CHLSEQN_MSK & uart_msg->frame2) >>
1785                         BT_UART_MSG_FRAME2CHLSEQN_POS,
1786                 (BT_UART_MSG_FRAME2INBAND_MSK & uart_msg->frame2) >>
1787                         BT_UART_MSG_FRAME2INBAND_POS);
1788
1789         IWL_DEBUG_NOTIF(priv, "SCO/eSCO = 0x%X, Sniff = 0x%X, A2DP = 0x%X, "
1790                         "ACL = 0x%X, Master = 0x%X, OBEX = 0x%X",
1791                 (BT_UART_MSG_FRAME3SCOESCO_MSK & uart_msg->frame3) >>
1792                         BT_UART_MSG_FRAME3SCOESCO_POS,
1793                 (BT_UART_MSG_FRAME3SNIFF_MSK & uart_msg->frame3) >>
1794                         BT_UART_MSG_FRAME3SNIFF_POS,
1795                 (BT_UART_MSG_FRAME3A2DP_MSK & uart_msg->frame3) >>
1796                         BT_UART_MSG_FRAME3A2DP_POS,
1797                 (BT_UART_MSG_FRAME3ACL_MSK & uart_msg->frame3) >>
1798                         BT_UART_MSG_FRAME3ACL_POS,
1799                 (BT_UART_MSG_FRAME3MASTER_MSK & uart_msg->frame3) >>
1800                         BT_UART_MSG_FRAME3MASTER_POS,
1801                 (BT_UART_MSG_FRAME3OBEX_MSK & uart_msg->frame3) >>
1802                         BT_UART_MSG_FRAME3OBEX_POS);
1803
1804         IWL_DEBUG_NOTIF(priv, "Idle duration = 0x%X",
1805                 (BT_UART_MSG_FRAME4IDLEDURATION_MSK & uart_msg->frame4) >>
1806                         BT_UART_MSG_FRAME4IDLEDURATION_POS);
1807
1808         IWL_DEBUG_NOTIF(priv, "Tx Activity = 0x%X, Rx Activity = 0x%X, "
1809                         "eSCO Retransmissions = 0x%X",
1810                 (BT_UART_MSG_FRAME5TXACTIVITY_MSK & uart_msg->frame5) >>
1811                         BT_UART_MSG_FRAME5TXACTIVITY_POS,
1812                 (BT_UART_MSG_FRAME5RXACTIVITY_MSK & uart_msg->frame5) >>
1813                         BT_UART_MSG_FRAME5RXACTIVITY_POS,
1814                 (BT_UART_MSG_FRAME5ESCORETRANSMIT_MSK & uart_msg->frame5) >>
1815                         BT_UART_MSG_FRAME5ESCORETRANSMIT_POS);
1816
1817         IWL_DEBUG_NOTIF(priv, "Sniff Interval = 0x%X, Discoverable = 0x%X",
1818                 (BT_UART_MSG_FRAME6SNIFFINTERVAL_MSK & uart_msg->frame6) >>
1819                         BT_UART_MSG_FRAME6SNIFFINTERVAL_POS,
1820                 (BT_UART_MSG_FRAME6DISCOVERABLE_MSK & uart_msg->frame6) >>
1821                         BT_UART_MSG_FRAME6DISCOVERABLE_POS);
1822
1823         IWL_DEBUG_NOTIF(priv, "Sniff Activity = 0x%X, Inquiry/Page SR Mode = "
1824                         "0x%X, Connectable = 0x%X",
1825                 (BT_UART_MSG_FRAME7SNIFFACTIVITY_MSK & uart_msg->frame7) >>
1826                         BT_UART_MSG_FRAME7SNIFFACTIVITY_POS,
1827                 (BT_UART_MSG_FRAME7INQUIRYPAGESRMODE_MSK & uart_msg->frame7) >>
1828                         BT_UART_MSG_FRAME7INQUIRYPAGESRMODE_POS,
1829                 (BT_UART_MSG_FRAME7CONNECTABLE_MSK & uart_msg->frame7) >>
1830                         BT_UART_MSG_FRAME7CONNECTABLE_POS);
1831 }
1832
1833 static void iwlagn_set_kill_ack_msk(struct iwl_priv *priv,
1834                                      struct iwl_bt_uart_msg *uart_msg)
1835 {
1836         u8 kill_ack_msk;
1837         __le32 bt_kill_ack_msg[2] = {
1838                         cpu_to_le32(0xFFFFFFF), cpu_to_le32(0xFFFFFC00) };
1839
1840         kill_ack_msk = (((BT_UART_MSG_FRAME3A2DP_MSK |
1841                         BT_UART_MSG_FRAME3SNIFF_MSK |
1842                         BT_UART_MSG_FRAME3SCOESCO_MSK) &
1843                         uart_msg->frame3) == 0) ? 1 : 0;
1844         if (priv->kill_ack_mask != bt_kill_ack_msg[kill_ack_msk]) {
1845                 priv->bt_valid |= IWLAGN_BT_VALID_KILL_ACK_MASK;
1846                 priv->kill_ack_mask = bt_kill_ack_msg[kill_ack_msk];
1847                 /* schedule to send runtime bt_config */
1848                 queue_work(priv->workqueue, &priv->bt_runtime_config);
1849         }
1850
1851 }
1852
1853 void iwlagn_bt_coex_profile_notif(struct iwl_priv *priv,
1854                                              struct iwl_rx_mem_buffer *rxb)
1855 {
1856         unsigned long flags;
1857         struct iwl_rx_packet *pkt = rxb_addr(rxb);
1858         struct iwl_bt_coex_profile_notif *coex = &pkt->u.bt_coex_profile_notif;
1859         struct iwlagn_bt_sco_cmd sco_cmd = { .flags = 0 };
1860         struct iwl_bt_uart_msg *uart_msg = &coex->last_bt_uart_msg;
1861         u8 last_traffic_load;
1862
1863         IWL_DEBUG_NOTIF(priv, "BT Coex notification:\n");
1864         IWL_DEBUG_NOTIF(priv, "    status: %d\n", coex->bt_status);
1865         IWL_DEBUG_NOTIF(priv, "    traffic load: %d\n", coex->bt_traffic_load);
1866         IWL_DEBUG_NOTIF(priv, "    CI compliance: %d\n",
1867                         coex->bt_ci_compliance);
1868         iwlagn_print_uartmsg(priv, uart_msg);
1869
1870         last_traffic_load = priv->notif_bt_traffic_load;
1871         priv->notif_bt_traffic_load = coex->bt_traffic_load;
1872         if (priv->iw_mode != NL80211_IFTYPE_ADHOC) {
1873                 if (priv->bt_status != coex->bt_status ||
1874                     last_traffic_load != coex->bt_traffic_load) {
1875                         if (coex->bt_status) {
1876                                 /* BT on */
1877                                 if (!priv->bt_ch_announce)
1878                                         priv->bt_traffic_load =
1879                                                 IWL_BT_COEX_TRAFFIC_LOAD_HIGH;
1880                                 else
1881                                         priv->bt_traffic_load =
1882                                                 coex->bt_traffic_load;
1883                         } else {
1884                                 /* BT off */
1885                                 priv->bt_traffic_load =
1886                                         IWL_BT_COEX_TRAFFIC_LOAD_NONE;
1887                         }
1888                         priv->bt_status = coex->bt_status;
1889                         queue_work(priv->workqueue,
1890                                    &priv->bt_traffic_change_work);
1891                 }
1892                 if (priv->bt_sco_active !=
1893                     (uart_msg->frame3 & BT_UART_MSG_FRAME3SCOESCO_MSK)) {
1894                         priv->bt_sco_active = uart_msg->frame3 &
1895                                 BT_UART_MSG_FRAME3SCOESCO_MSK;
1896                         if (priv->bt_sco_active)
1897                                 sco_cmd.flags |= IWLAGN_BT_SCO_ACTIVE;
1898                         iwl_send_cmd_pdu_async(priv, REPLY_BT_COEX_SCO,
1899                                        sizeof(sco_cmd), &sco_cmd, NULL);
1900                 }
1901         }
1902
1903         iwlagn_set_kill_ack_msk(priv, uart_msg);
1904
1905         /* FIXME: based on notification, adjust the prio_boost */
1906
1907         spin_lock_irqsave(&priv->lock, flags);
1908         priv->bt_ci_compliance = coex->bt_ci_compliance;
1909         spin_unlock_irqrestore(&priv->lock, flags);
1910 }
1911
1912 void iwlagn_bt_rx_handler_setup(struct iwl_priv *priv)
1913 {
1914         iwlagn_rx_handler_setup(priv);
1915         priv->rx_handlers[REPLY_BT_COEX_PROFILE_NOTIF] =
1916                 iwlagn_bt_coex_profile_notif;
1917 }
1918
1919 void iwlagn_bt_setup_deferred_work(struct iwl_priv *priv)
1920 {
1921         iwlagn_setup_deferred_work(priv);
1922
1923         INIT_WORK(&priv->bt_traffic_change_work,
1924                   iwlagn_bt_traffic_change_work);
1925 }
1926
1927 void iwlagn_bt_cancel_deferred_work(struct iwl_priv *priv)
1928 {
1929         cancel_work_sync(&priv->bt_traffic_change_work);
1930 }