iwlwifi: fix erroneous use of iwl_rx_packet.len as a length
[pandora-kernel.git] / drivers / net / wireless / iwlwifi / iwl-rx.c
1 /******************************************************************************
2  *
3  * Copyright(c) 2003 - 2009 Intel Corporation. All rights reserved.
4  *
5  * Portions of this file are derived from the ipw3945 project, as well
6  * as portions of the ieee80211 subsystem header files.
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of version 2 of the GNU General Public License as
10  * published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15  * more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
20  *
21  * The full GNU General Public License is included in this distribution in the
22  * file called LICENSE.
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
30 #include <linux/etherdevice.h>
31 #include <net/mac80211.h>
32 #include <asm/unaligned.h>
33 #include "iwl-eeprom.h"
34 #include "iwl-dev.h"
35 #include "iwl-core.h"
36 #include "iwl-sta.h"
37 #include "iwl-io.h"
38 #include "iwl-calib.h"
39 #include "iwl-helpers.h"
40 /************************** RX-FUNCTIONS ****************************/
41 /*
42  * Rx theory of operation
43  *
44  * Driver allocates a circular buffer of Receive Buffer Descriptors (RBDs),
45  * each of which point to Receive Buffers to be filled by the NIC.  These get
46  * used not only for Rx frames, but for any command response or notification
47  * from the NIC.  The driver and NIC manage the Rx buffers by means
48  * of indexes into the circular buffer.
49  *
50  * Rx Queue Indexes
51  * The host/firmware share two index registers for managing the Rx buffers.
52  *
53  * The READ index maps to the first position that the firmware may be writing
54  * to -- the driver can read up to (but not including) this position and get
55  * good data.
56  * The READ index is managed by the firmware once the card is enabled.
57  *
58  * The WRITE index maps to the last position the driver has read from -- the
59  * position preceding WRITE is the last slot the firmware can place a packet.
60  *
61  * The queue is empty (no good data) if WRITE = READ - 1, and is full if
62  * WRITE = READ.
63  *
64  * During initialization, the host sets up the READ queue position to the first
65  * INDEX position, and WRITE to the last (READ - 1 wrapped)
66  *
67  * When the firmware places a packet in a buffer, it will advance the READ index
68  * and fire the RX interrupt.  The driver can then query the READ index and
69  * process as many packets as possible, moving the WRITE index forward as it
70  * resets the Rx queue buffers with new memory.
71  *
72  * The management in the driver is as follows:
73  * + A list of pre-allocated SKBs is stored in iwl->rxq->rx_free.  When
74  *   iwl->rxq->free_count drops to or below RX_LOW_WATERMARK, work is scheduled
75  *   to replenish the iwl->rxq->rx_free.
76  * + In iwl_rx_replenish (scheduled) if 'processed' != 'read' then the
77  *   iwl->rxq is replenished and the READ INDEX is updated (updating the
78  *   'processed' and 'read' driver indexes as well)
79  * + A received packet is processed and handed to the kernel network stack,
80  *   detached from the iwl->rxq.  The driver 'processed' index is updated.
81  * + The Host/Firmware iwl->rxq is replenished at tasklet time from the rx_free
82  *   list. If there are no allocated buffers in iwl->rxq->rx_free, the READ
83  *   INDEX is not incremented and iwl->status(RX_STALLED) is set.  If there
84  *   were enough free buffers and RX_STALLED is set it is cleared.
85  *
86  *
87  * Driver sequence:
88  *
89  * iwl_rx_queue_alloc()   Allocates rx_free
90  * iwl_rx_replenish()     Replenishes rx_free list from rx_used, and calls
91  *                            iwl_rx_queue_restock
92  * iwl_rx_queue_restock() Moves available buffers from rx_free into Rx
93  *                            queue, updates firmware pointers, and updates
94  *                            the WRITE index.  If insufficient rx_free buffers
95  *                            are available, schedules iwl_rx_replenish
96  *
97  * -- enable interrupts --
98  * ISR - iwl_rx()         Detach iwl_rx_mem_buffers from pool up to the
99  *                            READ INDEX, detaching the SKB from the pool.
100  *                            Moves the packet buffer from queue to rx_used.
101  *                            Calls iwl_rx_queue_restock to refill any empty
102  *                            slots.
103  * ...
104  *
105  */
106
107 /**
108  * iwl_rx_queue_space - Return number of free slots available in queue.
109  */
110 int iwl_rx_queue_space(const struct iwl_rx_queue *q)
111 {
112         int s = q->read - q->write;
113         if (s <= 0)
114                 s += RX_QUEUE_SIZE;
115         /* keep some buffer to not confuse full and empty queue */
116         s -= 2;
117         if (s < 0)
118                 s = 0;
119         return s;
120 }
121 EXPORT_SYMBOL(iwl_rx_queue_space);
122
123 /**
124  * iwl_rx_queue_update_write_ptr - Update the write pointer for the RX queue
125  */
126 int iwl_rx_queue_update_write_ptr(struct iwl_priv *priv, struct iwl_rx_queue *q)
127 {
128         unsigned long flags;
129         u32 rx_wrt_ptr_reg = priv->hw_params.rx_wrt_ptr_reg;
130         u32 reg;
131         int ret = 0;
132
133         spin_lock_irqsave(&q->lock, flags);
134
135         if (q->need_update == 0)
136                 goto exit_unlock;
137
138         /* If power-saving is in use, make sure device is awake */
139         if (test_bit(STATUS_POWER_PMI, &priv->status)) {
140                 reg = iwl_read32(priv, CSR_UCODE_DRV_GP1);
141
142                 if (reg & CSR_UCODE_DRV_GP1_BIT_MAC_SLEEP) {
143                         iwl_set_bit(priv, CSR_GP_CNTRL,
144                                     CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
145                         goto exit_unlock;
146                 }
147
148                 q->write_actual = (q->write & ~0x7);
149                 iwl_write_direct32(priv, rx_wrt_ptr_reg, q->write_actual);
150
151         /* Else device is assumed to be awake */
152         } else {
153                 /* Device expects a multiple of 8 */
154                 q->write_actual = (q->write & ~0x7);
155                 iwl_write_direct32(priv, rx_wrt_ptr_reg, q->write_actual);
156         }
157
158         q->need_update = 0;
159
160  exit_unlock:
161         spin_unlock_irqrestore(&q->lock, flags);
162         return ret;
163 }
164 EXPORT_SYMBOL(iwl_rx_queue_update_write_ptr);
165 /**
166  * iwl_dma_addr2rbd_ptr - convert a DMA address to a uCode read buffer ptr
167  */
168 static inline __le32 iwl_dma_addr2rbd_ptr(struct iwl_priv *priv,
169                                           dma_addr_t dma_addr)
170 {
171         return cpu_to_le32((u32)(dma_addr >> 8));
172 }
173
174 /**
175  * iwl_rx_queue_restock - refill RX queue from pre-allocated pool
176  *
177  * If there are slots in the RX queue that need to be restocked,
178  * and we have free pre-allocated buffers, fill the ranks as much
179  * as we can, pulling from rx_free.
180  *
181  * This moves the 'write' index forward to catch up with 'processed', and
182  * also updates the memory address in the firmware to reference the new
183  * target buffer.
184  */
185 int iwl_rx_queue_restock(struct iwl_priv *priv)
186 {
187         struct iwl_rx_queue *rxq = &priv->rxq;
188         struct list_head *element;
189         struct iwl_rx_mem_buffer *rxb;
190         unsigned long flags;
191         int write;
192         int ret = 0;
193
194         spin_lock_irqsave(&rxq->lock, flags);
195         write = rxq->write & ~0x7;
196         while ((iwl_rx_queue_space(rxq) > 0) && (rxq->free_count)) {
197                 /* Get next free Rx buffer, remove from free list */
198                 element = rxq->rx_free.next;
199                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
200                 list_del(element);
201
202                 /* Point to Rx buffer via next RBD in circular buffer */
203                 rxq->bd[rxq->write] = iwl_dma_addr2rbd_ptr(priv, rxb->aligned_dma_addr);
204                 rxq->queue[rxq->write] = rxb;
205                 rxq->write = (rxq->write + 1) & RX_QUEUE_MASK;
206                 rxq->free_count--;
207         }
208         spin_unlock_irqrestore(&rxq->lock, flags);
209         /* If the pre-allocated buffer pool is dropping low, schedule to
210          * refill it */
211         if (rxq->free_count <= RX_LOW_WATERMARK)
212                 queue_work(priv->workqueue, &priv->rx_replenish);
213
214
215         /* If we've added more space for the firmware to place data, tell it.
216          * Increment device's write pointer in multiples of 8. */
217         if (rxq->write_actual != (rxq->write & ~0x7)) {
218                 spin_lock_irqsave(&rxq->lock, flags);
219                 rxq->need_update = 1;
220                 spin_unlock_irqrestore(&rxq->lock, flags);
221                 ret = iwl_rx_queue_update_write_ptr(priv, rxq);
222         }
223
224         return ret;
225 }
226 EXPORT_SYMBOL(iwl_rx_queue_restock);
227
228
229 /**
230  * iwl_rx_replenish - Move all used packet from rx_used to rx_free
231  *
232  * When moving to rx_free an SKB is allocated for the slot.
233  *
234  * Also restock the Rx queue via iwl_rx_queue_restock.
235  * This is called as a scheduled work item (except for during initialization)
236  */
237 void iwl_rx_allocate(struct iwl_priv *priv, gfp_t priority)
238 {
239         struct iwl_rx_queue *rxq = &priv->rxq;
240         struct list_head *element;
241         struct iwl_rx_mem_buffer *rxb;
242         unsigned long flags;
243
244         while (1) {
245                 spin_lock_irqsave(&rxq->lock, flags);
246
247                 if (list_empty(&rxq->rx_used)) {
248                         spin_unlock_irqrestore(&rxq->lock, flags);
249                         return;
250                 }
251                 element = rxq->rx_used.next;
252                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
253                 list_del(element);
254
255                 spin_unlock_irqrestore(&rxq->lock, flags);
256
257                 /* Alloc a new receive buffer */
258                 rxb->skb = alloc_skb(priv->hw_params.rx_buf_size + 256,
259                                                 priority);
260
261                 if (!rxb->skb) {
262                         IWL_CRIT(priv, "Can not allocate SKB buffers\n");
263                         /* We don't reschedule replenish work here -- we will
264                          * call the restock method and if it still needs
265                          * more buffers it will schedule replenish */
266                         break;
267                 }
268
269                 /* Get physical address of RB/SKB */
270                 rxb->real_dma_addr = pci_map_single(
271                                         priv->pci_dev,
272                                         rxb->skb->data,
273                                         priv->hw_params.rx_buf_size + 256,
274                                         PCI_DMA_FROMDEVICE);
275                 /* dma address must be no more than 36 bits */
276                 BUG_ON(rxb->real_dma_addr & ~DMA_BIT_MASK(36));
277                 /* and also 256 byte aligned! */
278                 rxb->aligned_dma_addr = ALIGN(rxb->real_dma_addr, 256);
279                 skb_reserve(rxb->skb, rxb->aligned_dma_addr - rxb->real_dma_addr);
280
281                 spin_lock_irqsave(&rxq->lock, flags);
282
283                 list_add_tail(&rxb->list, &rxq->rx_free);
284                 rxq->free_count++;
285                 priv->alloc_rxb_skb++;
286
287                 spin_unlock_irqrestore(&rxq->lock, flags);
288         }
289 }
290
291 void iwl_rx_replenish(struct iwl_priv *priv)
292 {
293         unsigned long flags;
294
295         iwl_rx_allocate(priv, GFP_KERNEL);
296
297         spin_lock_irqsave(&priv->lock, flags);
298         iwl_rx_queue_restock(priv);
299         spin_unlock_irqrestore(&priv->lock, flags);
300 }
301 EXPORT_SYMBOL(iwl_rx_replenish);
302
303 void iwl_rx_replenish_now(struct iwl_priv *priv)
304 {
305         iwl_rx_allocate(priv, GFP_ATOMIC);
306
307         iwl_rx_queue_restock(priv);
308 }
309 EXPORT_SYMBOL(iwl_rx_replenish_now);
310
311
312 /* Assumes that the skb field of the buffers in 'pool' is kept accurate.
313  * If an SKB has been detached, the POOL needs to have its SKB set to NULL
314  * This free routine walks the list of POOL entries and if SKB is set to
315  * non NULL it is unmapped and freed
316  */
317 void iwl_rx_queue_free(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
318 {
319         int i;
320         for (i = 0; i < RX_QUEUE_SIZE + RX_FREE_BUFFERS; i++) {
321                 if (rxq->pool[i].skb != NULL) {
322                         pci_unmap_single(priv->pci_dev,
323                                          rxq->pool[i].real_dma_addr,
324                                          priv->hw_params.rx_buf_size + 256,
325                                          PCI_DMA_FROMDEVICE);
326                         dev_kfree_skb(rxq->pool[i].skb);
327                 }
328         }
329
330         pci_free_consistent(priv->pci_dev, 4 * RX_QUEUE_SIZE, rxq->bd,
331                             rxq->dma_addr);
332         pci_free_consistent(priv->pci_dev, sizeof(struct iwl_rb_status),
333                             rxq->rb_stts, rxq->rb_stts_dma);
334         rxq->bd = NULL;
335         rxq->rb_stts  = NULL;
336 }
337 EXPORT_SYMBOL(iwl_rx_queue_free);
338
339 int iwl_rx_queue_alloc(struct iwl_priv *priv)
340 {
341         struct iwl_rx_queue *rxq = &priv->rxq;
342         struct pci_dev *dev = priv->pci_dev;
343         int i;
344
345         spin_lock_init(&rxq->lock);
346         INIT_LIST_HEAD(&rxq->rx_free);
347         INIT_LIST_HEAD(&rxq->rx_used);
348
349         /* Alloc the circular buffer of Read Buffer Descriptors (RBDs) */
350         rxq->bd = pci_alloc_consistent(dev, 4 * RX_QUEUE_SIZE, &rxq->dma_addr);
351         if (!rxq->bd)
352                 goto err_bd;
353
354         rxq->rb_stts = pci_alloc_consistent(dev, sizeof(struct iwl_rb_status),
355                                         &rxq->rb_stts_dma);
356         if (!rxq->rb_stts)
357                 goto err_rb;
358
359         /* Fill the rx_used queue with _all_ of the Rx buffers */
360         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++)
361                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
362
363         /* Set us so that we have processed and used all buffers, but have
364          * not restocked the Rx queue with fresh buffers */
365         rxq->read = rxq->write = 0;
366         rxq->write_actual = 0;
367         rxq->free_count = 0;
368         rxq->need_update = 0;
369         return 0;
370
371 err_rb:
372         pci_free_consistent(priv->pci_dev, 4 * RX_QUEUE_SIZE, rxq->bd,
373                             rxq->dma_addr);
374 err_bd:
375         return -ENOMEM;
376 }
377 EXPORT_SYMBOL(iwl_rx_queue_alloc);
378
379 void iwl_rx_queue_reset(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
380 {
381         unsigned long flags;
382         int i;
383         spin_lock_irqsave(&rxq->lock, flags);
384         INIT_LIST_HEAD(&rxq->rx_free);
385         INIT_LIST_HEAD(&rxq->rx_used);
386         /* Fill the rx_used queue with _all_ of the Rx buffers */
387         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) {
388                 /* In the reset function, these buffers may have been allocated
389                  * to an SKB, so we need to unmap and free potential storage */
390                 if (rxq->pool[i].skb != NULL) {
391                         pci_unmap_single(priv->pci_dev,
392                                          rxq->pool[i].real_dma_addr,
393                                          priv->hw_params.rx_buf_size + 256,
394                                          PCI_DMA_FROMDEVICE);
395                         priv->alloc_rxb_skb--;
396                         dev_kfree_skb(rxq->pool[i].skb);
397                         rxq->pool[i].skb = NULL;
398                 }
399                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
400         }
401
402         /* Set us so that we have processed and used all buffers, but have
403          * not restocked the Rx queue with fresh buffers */
404         rxq->read = rxq->write = 0;
405         rxq->write_actual = 0;
406         rxq->free_count = 0;
407         spin_unlock_irqrestore(&rxq->lock, flags);
408 }
409
410 int iwl_rx_init(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
411 {
412         u32 rb_size;
413         const u32 rfdnlog = RX_QUEUE_SIZE_LOG; /* 256 RBDs */
414         u32 rb_timeout = 0; /* FIXME: RX_RB_TIMEOUT for all devices? */
415
416         if (!priv->cfg->use_isr_legacy)
417                 rb_timeout = RX_RB_TIMEOUT;
418
419         if (priv->cfg->mod_params->amsdu_size_8K)
420                 rb_size = FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_8K;
421         else
422                 rb_size = FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_4K;
423
424         /* Stop Rx DMA */
425         iwl_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0);
426
427         /* Reset driver's Rx queue write index */
428         iwl_write_direct32(priv, FH_RSCSR_CHNL0_RBDCB_WPTR_REG, 0);
429
430         /* Tell device where to find RBD circular buffer in DRAM */
431         iwl_write_direct32(priv, FH_RSCSR_CHNL0_RBDCB_BASE_REG,
432                            (u32)(rxq->dma_addr >> 8));
433
434         /* Tell device where in DRAM to update its Rx status */
435         iwl_write_direct32(priv, FH_RSCSR_CHNL0_STTS_WPTR_REG,
436                            rxq->rb_stts_dma >> 4);
437
438         /* Enable Rx DMA
439          * FH_RCSR_CHNL0_RX_IGNORE_RXF_EMPTY is set because of HW bug in
440          *      the credit mechanism in 5000 HW RX FIFO
441          * Direct rx interrupts to hosts
442          * Rx buffer size 4 or 8k
443          * RB timeout 0x10
444          * 256 RBDs
445          */
446         iwl_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG,
447                            FH_RCSR_RX_CONFIG_CHNL_EN_ENABLE_VAL |
448                            FH_RCSR_CHNL0_RX_IGNORE_RXF_EMPTY |
449                            FH_RCSR_CHNL0_RX_CONFIG_IRQ_DEST_INT_HOST_VAL |
450                            FH_RCSR_CHNL0_RX_CONFIG_SINGLE_FRAME_MSK |
451                            rb_size|
452                            (rb_timeout << FH_RCSR_RX_CONFIG_REG_IRQ_RBTH_POS)|
453                            (rfdnlog << FH_RCSR_RX_CONFIG_RBDCB_SIZE_POS));
454
455         iwl_write32(priv, CSR_INT_COALESCING, 0x40);
456
457         return 0;
458 }
459
460 int iwl_rxq_stop(struct iwl_priv *priv)
461 {
462
463         /* stop Rx DMA */
464         iwl_write_direct32(priv, FH_MEM_RCSR_CHNL0_CONFIG_REG, 0);
465         iwl_poll_direct_bit(priv, FH_MEM_RSSR_RX_STATUS_REG,
466                             FH_RSSR_CHNL0_RX_STATUS_CHNL_IDLE, 1000);
467
468         return 0;
469 }
470 EXPORT_SYMBOL(iwl_rxq_stop);
471
472 void iwl_rx_missed_beacon_notif(struct iwl_priv *priv,
473                                 struct iwl_rx_mem_buffer *rxb)
474
475 {
476         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
477         struct iwl_missed_beacon_notif *missed_beacon;
478
479         missed_beacon = &pkt->u.missed_beacon;
480         if (le32_to_cpu(missed_beacon->consequtive_missed_beacons) > 5) {
481                 IWL_DEBUG_CALIB(priv, "missed bcn cnsq %d totl %d rcd %d expctd %d\n",
482                     le32_to_cpu(missed_beacon->consequtive_missed_beacons),
483                     le32_to_cpu(missed_beacon->total_missed_becons),
484                     le32_to_cpu(missed_beacon->num_recvd_beacons),
485                     le32_to_cpu(missed_beacon->num_expected_beacons));
486                 if (!test_bit(STATUS_SCANNING, &priv->status))
487                         iwl_init_sensitivity(priv);
488         }
489 }
490 EXPORT_SYMBOL(iwl_rx_missed_beacon_notif);
491
492
493 /* Calculate noise level, based on measurements during network silence just
494  *   before arriving beacon.  This measurement can be done only if we know
495  *   exactly when to expect beacons, therefore only when we're associated. */
496 static void iwl_rx_calc_noise(struct iwl_priv *priv)
497 {
498         struct statistics_rx_non_phy *rx_info
499                                 = &(priv->statistics.rx.general);
500         int num_active_rx = 0;
501         int total_silence = 0;
502         int bcn_silence_a =
503                 le32_to_cpu(rx_info->beacon_silence_rssi_a) & IN_BAND_FILTER;
504         int bcn_silence_b =
505                 le32_to_cpu(rx_info->beacon_silence_rssi_b) & IN_BAND_FILTER;
506         int bcn_silence_c =
507                 le32_to_cpu(rx_info->beacon_silence_rssi_c) & IN_BAND_FILTER;
508
509         if (bcn_silence_a) {
510                 total_silence += bcn_silence_a;
511                 num_active_rx++;
512         }
513         if (bcn_silence_b) {
514                 total_silence += bcn_silence_b;
515                 num_active_rx++;
516         }
517         if (bcn_silence_c) {
518                 total_silence += bcn_silence_c;
519                 num_active_rx++;
520         }
521
522         /* Average among active antennas */
523         if (num_active_rx)
524                 priv->last_rx_noise = (total_silence / num_active_rx) - 107;
525         else
526                 priv->last_rx_noise = IWL_NOISE_MEAS_NOT_AVAILABLE;
527
528         IWL_DEBUG_CALIB(priv, "inband silence a %u, b %u, c %u, dBm %d\n",
529                         bcn_silence_a, bcn_silence_b, bcn_silence_c,
530                         priv->last_rx_noise);
531 }
532
533 #define REG_RECALIB_PERIOD (60)
534
535 void iwl_rx_statistics(struct iwl_priv *priv,
536                               struct iwl_rx_mem_buffer *rxb)
537 {
538         int change;
539         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
540
541         IWL_DEBUG_RX(priv, "Statistics notification received (%d vs %d).\n",
542                      (int)sizeof(priv->statistics),
543                      le32_to_cpu(pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK);
544
545         change = ((priv->statistics.general.temperature !=
546                    pkt->u.stats.general.temperature) ||
547                   ((priv->statistics.flag &
548                     STATISTICS_REPLY_FLG_HT40_MODE_MSK) !=
549                    (pkt->u.stats.flag & STATISTICS_REPLY_FLG_HT40_MODE_MSK)));
550
551         memcpy(&priv->statistics, &pkt->u.stats, sizeof(priv->statistics));
552
553         set_bit(STATUS_STATISTICS, &priv->status);
554
555         /* Reschedule the statistics timer to occur in
556          * REG_RECALIB_PERIOD seconds to ensure we get a
557          * thermal update even if the uCode doesn't give
558          * us one */
559         mod_timer(&priv->statistics_periodic, jiffies +
560                   msecs_to_jiffies(REG_RECALIB_PERIOD * 1000));
561
562         if (unlikely(!test_bit(STATUS_SCANNING, &priv->status)) &&
563             (pkt->hdr.cmd == STATISTICS_NOTIFICATION)) {
564                 iwl_rx_calc_noise(priv);
565                 queue_work(priv->workqueue, &priv->run_time_calib_work);
566         }
567
568         iwl_leds_background(priv);
569
570         if (priv->cfg->ops->lib->temp_ops.temperature && change)
571                 priv->cfg->ops->lib->temp_ops.temperature(priv);
572 }
573 EXPORT_SYMBOL(iwl_rx_statistics);
574
575 #define PERFECT_RSSI (-20) /* dBm */
576 #define WORST_RSSI (-95)   /* dBm */
577 #define RSSI_RANGE (PERFECT_RSSI - WORST_RSSI)
578
579 /* Calculate an indication of rx signal quality (a percentage, not dBm!).
580  * See http://www.ces.clemson.edu/linux/signal_quality.shtml for info
581  *   about formulas used below. */
582 static int iwl_calc_sig_qual(int rssi_dbm, int noise_dbm)
583 {
584         int sig_qual;
585         int degradation = PERFECT_RSSI - rssi_dbm;
586
587         /* If we get a noise measurement, use signal-to-noise ratio (SNR)
588          * as indicator; formula is (signal dbm - noise dbm).
589          * SNR at or above 40 is a great signal (100%).
590          * Below that, scale to fit SNR of 0 - 40 dB within 0 - 100% indicator.
591          * Weakest usable signal is usually 10 - 15 dB SNR. */
592         if (noise_dbm) {
593                 if (rssi_dbm - noise_dbm >= 40)
594                         return 100;
595                 else if (rssi_dbm < noise_dbm)
596                         return 0;
597                 sig_qual = ((rssi_dbm - noise_dbm) * 5) / 2;
598
599         /* Else use just the signal level.
600          * This formula is a least squares fit of data points collected and
601          *   compared with a reference system that had a percentage (%) display
602          *   for signal quality. */
603         } else
604                 sig_qual = (100 * (RSSI_RANGE * RSSI_RANGE) - degradation *
605                             (15 * RSSI_RANGE + 62 * degradation)) /
606                            (RSSI_RANGE * RSSI_RANGE);
607
608         if (sig_qual > 100)
609                 sig_qual = 100;
610         else if (sig_qual < 1)
611                 sig_qual = 0;
612
613         return sig_qual;
614 }
615
616 /* Calc max signal level (dBm) among 3 possible receivers */
617 static inline int iwl_calc_rssi(struct iwl_priv *priv,
618                                 struct iwl_rx_phy_res *rx_resp)
619 {
620         return priv->cfg->ops->utils->calc_rssi(priv, rx_resp);
621 }
622
623 #ifdef CONFIG_IWLWIFI_DEBUG
624 /**
625  * iwl_dbg_report_frame - dump frame to syslog during debug sessions
626  *
627  * You may hack this function to show different aspects of received frames,
628  * including selective frame dumps.
629  * group100 parameter selects whether to show 1 out of 100 good data frames.
630  *    All beacon and probe response frames are printed.
631  */
632 static void iwl_dbg_report_frame(struct iwl_priv *priv,
633                       struct iwl_rx_phy_res *phy_res, u16 length,
634                       struct ieee80211_hdr *header, int group100)
635 {
636         u32 to_us;
637         u32 print_summary = 0;
638         u32 print_dump = 0;     /* set to 1 to dump all frames' contents */
639         u32 hundred = 0;
640         u32 dataframe = 0;
641         __le16 fc;
642         u16 seq_ctl;
643         u16 channel;
644         u16 phy_flags;
645         u32 rate_n_flags;
646         u32 tsf_low;
647         int rssi;
648
649         if (likely(!(iwl_get_debug_level(priv) & IWL_DL_RX)))
650                 return;
651
652         /* MAC header */
653         fc = header->frame_control;
654         seq_ctl = le16_to_cpu(header->seq_ctrl);
655
656         /* metadata */
657         channel = le16_to_cpu(phy_res->channel);
658         phy_flags = le16_to_cpu(phy_res->phy_flags);
659         rate_n_flags = le32_to_cpu(phy_res->rate_n_flags);
660
661         /* signal statistics */
662         rssi = iwl_calc_rssi(priv, phy_res);
663         tsf_low = le64_to_cpu(phy_res->timestamp) & 0x0ffffffff;
664
665         to_us = !compare_ether_addr(header->addr1, priv->mac_addr);
666
667         /* if data frame is to us and all is good,
668          *   (optionally) print summary for only 1 out of every 100 */
669         if (to_us && (fc & ~cpu_to_le16(IEEE80211_FCTL_PROTECTED)) ==
670             cpu_to_le16(IEEE80211_FCTL_FROMDS | IEEE80211_FTYPE_DATA)) {
671                 dataframe = 1;
672                 if (!group100)
673                         print_summary = 1;      /* print each frame */
674                 else if (priv->framecnt_to_us < 100) {
675                         priv->framecnt_to_us++;
676                         print_summary = 0;
677                 } else {
678                         priv->framecnt_to_us = 0;
679                         print_summary = 1;
680                         hundred = 1;
681                 }
682         } else {
683                 /* print summary for all other frames */
684                 print_summary = 1;
685         }
686
687         if (print_summary) {
688                 char *title;
689                 int rate_idx;
690                 u32 bitrate;
691
692                 if (hundred)
693                         title = "100Frames";
694                 else if (ieee80211_has_retry(fc))
695                         title = "Retry";
696                 else if (ieee80211_is_assoc_resp(fc))
697                         title = "AscRsp";
698                 else if (ieee80211_is_reassoc_resp(fc))
699                         title = "RasRsp";
700                 else if (ieee80211_is_probe_resp(fc)) {
701                         title = "PrbRsp";
702                         print_dump = 1; /* dump frame contents */
703                 } else if (ieee80211_is_beacon(fc)) {
704                         title = "Beacon";
705                         print_dump = 1; /* dump frame contents */
706                 } else if (ieee80211_is_atim(fc))
707                         title = "ATIM";
708                 else if (ieee80211_is_auth(fc))
709                         title = "Auth";
710                 else if (ieee80211_is_deauth(fc))
711                         title = "DeAuth";
712                 else if (ieee80211_is_disassoc(fc))
713                         title = "DisAssoc";
714                 else
715                         title = "Frame";
716
717                 rate_idx = iwl_hwrate_to_plcp_idx(rate_n_flags);
718                 if (unlikely((rate_idx < 0) || (rate_idx >= IWL_RATE_COUNT))) {
719                         bitrate = 0;
720                         WARN_ON_ONCE(1);
721                 } else {
722                         bitrate = iwl_rates[rate_idx].ieee / 2;
723                 }
724
725                 /* print frame summary.
726                  * MAC addresses show just the last byte (for brevity),
727                  *    but you can hack it to show more, if you'd like to. */
728                 if (dataframe)
729                         IWL_DEBUG_RX(priv, "%s: mhd=0x%04x, dst=0x%02x, "
730                                      "len=%u, rssi=%d, chnl=%d, rate=%u, \n",
731                                      title, le16_to_cpu(fc), header->addr1[5],
732                                      length, rssi, channel, bitrate);
733                 else {
734                         /* src/dst addresses assume managed mode */
735                         IWL_DEBUG_RX(priv, "%s: 0x%04x, dst=0x%02x, src=0x%02x, "
736                                      "len=%u, rssi=%d, tim=%lu usec, "
737                                      "phy=0x%02x, chnl=%d\n",
738                                      title, le16_to_cpu(fc), header->addr1[5],
739                                      header->addr3[5], length, rssi,
740                                      tsf_low - priv->scan_start_tsf,
741                                      phy_flags, channel);
742                 }
743         }
744         if (print_dump)
745                 iwl_print_hex_dump(priv, IWL_DL_RX, header, length);
746 }
747 #endif
748
749 /*
750  * returns non-zero if packet should be dropped
751  */
752 int iwl_set_decrypted_flag(struct iwl_priv *priv,
753                            struct ieee80211_hdr *hdr,
754                            u32 decrypt_res,
755                            struct ieee80211_rx_status *stats)
756 {
757         u16 fc = le16_to_cpu(hdr->frame_control);
758
759         if (priv->active_rxon.filter_flags & RXON_FILTER_DIS_DECRYPT_MSK)
760                 return 0;
761
762         if (!(fc & IEEE80211_FCTL_PROTECTED))
763                 return 0;
764
765         IWL_DEBUG_RX(priv, "decrypt_res:0x%x\n", decrypt_res);
766         switch (decrypt_res & RX_RES_STATUS_SEC_TYPE_MSK) {
767         case RX_RES_STATUS_SEC_TYPE_TKIP:
768                 /* The uCode has got a bad phase 1 Key, pushes the packet.
769                  * Decryption will be done in SW. */
770                 if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) ==
771                     RX_RES_STATUS_BAD_KEY_TTAK)
772                         break;
773
774         case RX_RES_STATUS_SEC_TYPE_WEP:
775                 if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) ==
776                     RX_RES_STATUS_BAD_ICV_MIC) {
777                         /* bad ICV, the packet is destroyed since the
778                          * decryption is inplace, drop it */
779                         IWL_DEBUG_RX(priv, "Packet destroyed\n");
780                         return -1;
781                 }
782         case RX_RES_STATUS_SEC_TYPE_CCMP:
783                 if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) ==
784                     RX_RES_STATUS_DECRYPT_OK) {
785                         IWL_DEBUG_RX(priv, "hw decrypt successfully!!!\n");
786                         stats->flag |= RX_FLAG_DECRYPTED;
787                 }
788                 break;
789
790         default:
791                 break;
792         }
793         return 0;
794 }
795 EXPORT_SYMBOL(iwl_set_decrypted_flag);
796
797 static u32 iwl_translate_rx_status(struct iwl_priv *priv, u32 decrypt_in)
798 {
799         u32 decrypt_out = 0;
800
801         if ((decrypt_in & RX_RES_STATUS_STATION_FOUND) ==
802                                         RX_RES_STATUS_STATION_FOUND)
803                 decrypt_out |= (RX_RES_STATUS_STATION_FOUND |
804                                 RX_RES_STATUS_NO_STATION_INFO_MISMATCH);
805
806         decrypt_out |= (decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK);
807
808         /* packet was not encrypted */
809         if ((decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) ==
810                                         RX_RES_STATUS_SEC_TYPE_NONE)
811                 return decrypt_out;
812
813         /* packet was encrypted with unknown alg */
814         if ((decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) ==
815                                         RX_RES_STATUS_SEC_TYPE_ERR)
816                 return decrypt_out;
817
818         /* decryption was not done in HW */
819         if ((decrypt_in & RX_MPDU_RES_STATUS_DEC_DONE_MSK) !=
820                                         RX_MPDU_RES_STATUS_DEC_DONE_MSK)
821                 return decrypt_out;
822
823         switch (decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) {
824
825         case RX_RES_STATUS_SEC_TYPE_CCMP:
826                 /* alg is CCM: check MIC only */
827                 if (!(decrypt_in & RX_MPDU_RES_STATUS_MIC_OK))
828                         /* Bad MIC */
829                         decrypt_out |= RX_RES_STATUS_BAD_ICV_MIC;
830                 else
831                         decrypt_out |= RX_RES_STATUS_DECRYPT_OK;
832
833                 break;
834
835         case RX_RES_STATUS_SEC_TYPE_TKIP:
836                 if (!(decrypt_in & RX_MPDU_RES_STATUS_TTAK_OK)) {
837                         /* Bad TTAK */
838                         decrypt_out |= RX_RES_STATUS_BAD_KEY_TTAK;
839                         break;
840                 }
841                 /* fall through if TTAK OK */
842         default:
843                 if (!(decrypt_in & RX_MPDU_RES_STATUS_ICV_OK))
844                         decrypt_out |= RX_RES_STATUS_BAD_ICV_MIC;
845                 else
846                         decrypt_out |= RX_RES_STATUS_DECRYPT_OK;
847                 break;
848         };
849
850         IWL_DEBUG_RX(priv, "decrypt_in:0x%x  decrypt_out = 0x%x\n",
851                                         decrypt_in, decrypt_out);
852
853         return decrypt_out;
854 }
855
856 static void iwl_pass_packet_to_mac80211(struct iwl_priv *priv,
857                                         struct ieee80211_hdr *hdr,
858                                         u16 len,
859                                         u32 ampdu_status,
860                                         struct iwl_rx_mem_buffer *rxb,
861                                         struct ieee80211_rx_status *stats)
862 {
863         /* We only process data packets if the interface is open */
864         if (unlikely(!priv->is_open)) {
865                 IWL_DEBUG_DROP_LIMIT(priv,
866                     "Dropping packet while interface is not open.\n");
867                 return;
868         }
869
870         /* In case of HW accelerated crypto and bad decryption, drop */
871         if (!priv->cfg->mod_params->sw_crypto &&
872             iwl_set_decrypted_flag(priv, hdr, ampdu_status, stats))
873                 return;
874
875         /* Resize SKB from mac header to end of packet */
876         skb_reserve(rxb->skb, (void *)hdr - (void *)rxb->skb->data);
877         skb_put(rxb->skb, len);
878
879         iwl_update_stats(priv, false, hdr->frame_control, len);
880         memcpy(IEEE80211_SKB_RXCB(rxb->skb), stats, sizeof(*stats));
881         ieee80211_rx_irqsafe(priv->hw, rxb->skb);
882         priv->alloc_rxb_skb--;
883         rxb->skb = NULL;
884 }
885
886 /* This is necessary only for a number of statistics, see the caller. */
887 static int iwl_is_network_packet(struct iwl_priv *priv,
888                 struct ieee80211_hdr *header)
889 {
890         /* Filter incoming packets to determine if they are targeted toward
891          * this network, discarding packets coming from ourselves */
892         switch (priv->iw_mode) {
893         case NL80211_IFTYPE_ADHOC: /* Header: Dest. | Source    | BSSID */
894                 /* packets to our IBSS update information */
895                 return !compare_ether_addr(header->addr3, priv->bssid);
896         case NL80211_IFTYPE_STATION: /* Header: Dest. | AP{BSSID} | Source */
897                 /* packets to our IBSS update information */
898                 return !compare_ether_addr(header->addr2, priv->bssid);
899         default:
900                 return 1;
901         }
902 }
903
904 /* Called for REPLY_RX (legacy ABG frames), or
905  * REPLY_RX_MPDU_CMD (HT high-throughput N frames). */
906 void iwl_rx_reply_rx(struct iwl_priv *priv,
907                                 struct iwl_rx_mem_buffer *rxb)
908 {
909         struct ieee80211_hdr *header;
910         struct ieee80211_rx_status rx_status;
911         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
912         struct iwl_rx_phy_res *phy_res;
913         __le32 rx_pkt_status;
914         struct iwl4965_rx_mpdu_res_start *amsdu;
915         u32 len;
916         u32 ampdu_status;
917         u16 fc;
918
919         /**
920          * REPLY_RX and REPLY_RX_MPDU_CMD are handled differently.
921          *      REPLY_RX: physical layer info is in this buffer
922          *      REPLY_RX_MPDU_CMD: physical layer info was sent in separate
923          *              command and cached in priv->last_phy_res
924          *
925          * Here we set up local variables depending on which command is
926          * received.
927          */
928         if (pkt->hdr.cmd == REPLY_RX) {
929                 phy_res = (struct iwl_rx_phy_res *)pkt->u.raw;
930                 header = (struct ieee80211_hdr *)(pkt->u.raw + sizeof(*phy_res)
931                                 + phy_res->cfg_phy_cnt);
932
933                 len = le16_to_cpu(phy_res->byte_count);
934                 rx_pkt_status = *(__le32 *)(pkt->u.raw + sizeof(*phy_res) +
935                                 phy_res->cfg_phy_cnt + len);
936                 ampdu_status = le32_to_cpu(rx_pkt_status);
937         } else {
938                 if (!priv->last_phy_res[0]) {
939                         IWL_ERR(priv, "MPDU frame without cached PHY data\n");
940                         return;
941                 }
942                 phy_res = (struct iwl_rx_phy_res *)&priv->last_phy_res[1];
943                 amsdu = (struct iwl4965_rx_mpdu_res_start *)pkt->u.raw;
944                 header = (struct ieee80211_hdr *)(pkt->u.raw + sizeof(*amsdu));
945                 len = le16_to_cpu(amsdu->byte_count);
946                 rx_pkt_status = *(__le32 *)(pkt->u.raw + sizeof(*amsdu) + len);
947                 ampdu_status = iwl_translate_rx_status(priv,
948                                 le32_to_cpu(rx_pkt_status));
949         }
950
951         if ((unlikely(phy_res->cfg_phy_cnt > 20))) {
952                 IWL_DEBUG_DROP(priv, "dsp size out of range [0,20]: %d/n",
953                                 phy_res->cfg_phy_cnt);
954                 return;
955         }
956
957         if (!(rx_pkt_status & RX_RES_STATUS_NO_CRC32_ERROR) ||
958             !(rx_pkt_status & RX_RES_STATUS_NO_RXE_OVERFLOW)) {
959                 IWL_DEBUG_RX(priv, "Bad CRC or FIFO: 0x%08X.\n",
960                                 le32_to_cpu(rx_pkt_status));
961                 return;
962         }
963
964         /* rx_status carries information about the packet to mac80211 */
965         rx_status.mactime = le64_to_cpu(phy_res->timestamp);
966         rx_status.freq =
967                 ieee80211_channel_to_frequency(le16_to_cpu(phy_res->channel));
968         rx_status.band = (phy_res->phy_flags & RX_RES_PHY_FLAGS_BAND_24_MSK) ?
969                                 IEEE80211_BAND_2GHZ : IEEE80211_BAND_5GHZ;
970         rx_status.rate_idx =
971                 iwl_hwrate_to_plcp_idx(le32_to_cpu(phy_res->rate_n_flags));
972         if (rx_status.band == IEEE80211_BAND_5GHZ)
973                 rx_status.rate_idx -= IWL_FIRST_OFDM_RATE;
974
975         rx_status.flag = 0;
976
977         /* TSF isn't reliable. In order to allow smooth user experience,
978          * this W/A doesn't propagate it to the mac80211 */
979         /*rx_status.flag |= RX_FLAG_TSFT;*/
980
981         priv->ucode_beacon_time = le32_to_cpu(phy_res->beacon_time_stamp);
982
983         /* Find max signal strength (dBm) among 3 antenna/receiver chains */
984         rx_status.signal = iwl_calc_rssi(priv, phy_res);
985
986         /* Meaningful noise values are available only from beacon statistics,
987          *   which are gathered only when associated, and indicate noise
988          *   only for the associated network channel ...
989          * Ignore these noise values while scanning (other channels) */
990         if (iwl_is_associated(priv) &&
991             !test_bit(STATUS_SCANNING, &priv->status)) {
992                 rx_status.noise = priv->last_rx_noise;
993                 rx_status.qual = iwl_calc_sig_qual(rx_status.signal,
994                                                          rx_status.noise);
995         } else {
996                 rx_status.noise = IWL_NOISE_MEAS_NOT_AVAILABLE;
997                 rx_status.qual = iwl_calc_sig_qual(rx_status.signal, 0);
998         }
999
1000         /* Reset beacon noise level if not associated. */
1001         if (!iwl_is_associated(priv))
1002                 priv->last_rx_noise = IWL_NOISE_MEAS_NOT_AVAILABLE;
1003
1004 #ifdef CONFIG_IWLWIFI_DEBUG
1005         /* Set "1" to report good data frames in groups of 100 */
1006         if (unlikely(iwl_get_debug_level(priv) & IWL_DL_RX))
1007                 iwl_dbg_report_frame(priv, phy_res, len, header, 1);
1008 #endif
1009         iwl_dbg_log_rx_data_frame(priv, len, header);
1010         IWL_DEBUG_STATS_LIMIT(priv, "Rssi %d, noise %d, qual %d, TSF %llu\n",
1011                 rx_status.signal, rx_status.noise, rx_status.qual,
1012                 (unsigned long long)rx_status.mactime);
1013
1014         /*
1015          * "antenna number"
1016          *
1017          * It seems that the antenna field in the phy flags value
1018          * is actually a bit field. This is undefined by radiotap,
1019          * it wants an actual antenna number but I always get "7"
1020          * for most legacy frames I receive indicating that the
1021          * same frame was received on all three RX chains.
1022          *
1023          * I think this field should be removed in favor of a
1024          * new 802.11n radiotap field "RX chains" that is defined
1025          * as a bitmask.
1026          */
1027         rx_status.antenna =
1028                 le16_to_cpu(phy_res->phy_flags & RX_RES_PHY_FLAGS_ANTENNA_MSK)
1029                 >> RX_RES_PHY_FLAGS_ANTENNA_POS;
1030
1031         /* set the preamble flag if appropriate */
1032         if (phy_res->phy_flags & RX_RES_PHY_FLAGS_SHORT_PREAMBLE_MSK)
1033                 rx_status.flag |= RX_FLAG_SHORTPRE;
1034
1035         if (iwl_is_network_packet(priv, header)) {
1036                 priv->last_rx_rssi = rx_status.signal;
1037                 priv->last_beacon_time =  priv->ucode_beacon_time;
1038                 priv->last_tsf = le64_to_cpu(phy_res->timestamp);
1039         }
1040
1041         fc = le16_to_cpu(header->frame_control);
1042         switch (fc & IEEE80211_FCTL_FTYPE) {
1043         case IEEE80211_FTYPE_MGMT:
1044         case IEEE80211_FTYPE_DATA:
1045                 if (priv->iw_mode == NL80211_IFTYPE_AP)
1046                         iwl_update_ps_mode(priv, fc  & IEEE80211_FCTL_PM,
1047                                                 header->addr2);
1048                 /* fall through */
1049         default:
1050                 iwl_pass_packet_to_mac80211(priv, header, len, ampdu_status,
1051                                 rxb, &rx_status);
1052                 break;
1053
1054         }
1055 }
1056 EXPORT_SYMBOL(iwl_rx_reply_rx);
1057
1058 /* Cache phy data (Rx signal strength, etc) for HT frame (REPLY_RX_PHY_CMD).
1059  * This will be used later in iwl_rx_reply_rx() for REPLY_RX_MPDU_CMD. */
1060 void iwl_rx_reply_rx_phy(struct iwl_priv *priv,
1061                                     struct iwl_rx_mem_buffer *rxb)
1062 {
1063         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
1064         priv->last_phy_res[0] = 1;
1065         memcpy(&priv->last_phy_res[1], &(pkt->u.raw[0]),
1066                sizeof(struct iwl_rx_phy_res));
1067 }
1068 EXPORT_SYMBOL(iwl_rx_reply_rx_phy);