iwlwifi: tx command must run on same tfd as packet
[safe/jmp/linux-2.6] / drivers / net / wireless / iwlwifi / iwl-tx.c
1 /******************************************************************************
2  *
3  * Copyright(c) 2003 - 2008 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  * James P. Ketrenos <ipw2100-admin@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 "iwl-eeprom.h"
33 #include "iwl-dev.h"
34 #include "iwl-core.h"
35 #include "iwl-sta.h"
36 #include "iwl-io.h"
37 #include "iwl-helpers.h"
38
39 static const u16 default_tid_to_tx_fifo[] = {
40         IWL_TX_FIFO_AC1,
41         IWL_TX_FIFO_AC0,
42         IWL_TX_FIFO_AC0,
43         IWL_TX_FIFO_AC1,
44         IWL_TX_FIFO_AC2,
45         IWL_TX_FIFO_AC2,
46         IWL_TX_FIFO_AC3,
47         IWL_TX_FIFO_AC3,
48         IWL_TX_FIFO_NONE,
49         IWL_TX_FIFO_NONE,
50         IWL_TX_FIFO_NONE,
51         IWL_TX_FIFO_NONE,
52         IWL_TX_FIFO_NONE,
53         IWL_TX_FIFO_NONE,
54         IWL_TX_FIFO_NONE,
55         IWL_TX_FIFO_NONE,
56         IWL_TX_FIFO_AC3
57 };
58
59 static inline dma_addr_t iwl_tfd_tb_get_addr(struct iwl_tfd *tfd, u8 idx)
60 {
61         struct iwl_tfd_tb *tb = &tfd->tbs[idx];
62
63         dma_addr_t addr = get_unaligned_le32(&tb->lo);
64         if (sizeof(dma_addr_t) > sizeof(u32))
65                 addr |=
66                 ((dma_addr_t)(le16_to_cpu(tb->hi_n_len) & 0xF) << 16) << 16;
67
68         return addr;
69 }
70
71 static inline u16 iwl_tfd_tb_get_len(struct iwl_tfd *tfd, u8 idx)
72 {
73         struct iwl_tfd_tb *tb = &tfd->tbs[idx];
74
75         return le16_to_cpu(tb->hi_n_len) >> 4;
76 }
77
78 static inline void iwl_tfd_set_tb(struct iwl_tfd *tfd, u8 idx,
79                                   dma_addr_t addr, u16 len)
80 {
81         struct iwl_tfd_tb *tb = &tfd->tbs[idx];
82         u16 hi_n_len = len << 4;
83
84         put_unaligned_le32(addr, &tb->lo);
85         if (sizeof(dma_addr_t) > sizeof(u32))
86                 hi_n_len |= ((addr >> 16) >> 16) & 0xF;
87
88         tb->hi_n_len = cpu_to_le16(hi_n_len);
89
90         tfd->num_tbs = idx + 1;
91 }
92
93 static inline u8 iwl_tfd_get_num_tbs(struct iwl_tfd *tfd)
94 {
95         return tfd->num_tbs & 0x1f;
96 }
97
98 /**
99  * iwl_hw_txq_free_tfd - Free all chunks referenced by TFD [txq->q.read_ptr]
100  * @priv - driver private data
101  * @txq - tx queue
102  *
103  * Does NOT advance any TFD circular buffer read/write indexes
104  * Does NOT free the TFD itself (which is within circular buffer)
105  */
106 static void iwl_hw_txq_free_tfd(struct iwl_priv *priv, struct iwl_tx_queue *txq)
107 {
108         struct iwl_tfd *tfd_tmp = (struct iwl_tfd *)&txq->tfds[0];
109         struct iwl_tfd *tfd;
110         struct pci_dev *dev = priv->pci_dev;
111         int index = txq->q.read_ptr;
112         int i;
113         int num_tbs;
114
115         tfd = &tfd_tmp[index];
116
117         /* Sanity check on number of chunks */
118         num_tbs = iwl_tfd_get_num_tbs(tfd);
119
120         if (num_tbs >= IWL_NUM_OF_TBS) {
121                 IWL_ERROR("Too many chunks: %i\n", num_tbs);
122                 /* @todo issue fatal error, it is quite serious situation */
123                 return;
124         }
125
126         /* Unmap tx_cmd */
127         if (num_tbs)
128                 pci_unmap_single(dev,
129                                 pci_unmap_addr(&txq->cmd[index]->meta, mapping),
130                                 pci_unmap_len(&txq->cmd[index]->meta, len),
131                                 PCI_DMA_TODEVICE);
132
133         /* Unmap chunks, if any. */
134         for (i = 1; i < num_tbs; i++) {
135                 pci_unmap_single(dev, iwl_tfd_tb_get_addr(tfd, i),
136                                 iwl_tfd_tb_get_len(tfd, i), PCI_DMA_TODEVICE);
137
138                 if (txq->txb) {
139                         dev_kfree_skb(txq->txb[txq->q.read_ptr].skb[i - 1]);
140                         txq->txb[txq->q.read_ptr].skb[i - 1] = NULL;
141                 }
142         }
143 }
144
145 static int iwl_hw_txq_attach_buf_to_tfd(struct iwl_priv *priv,
146                                         struct iwl_tfd *tfd,
147                                         dma_addr_t addr, u16 len)
148 {
149
150         u32 num_tbs = iwl_tfd_get_num_tbs(tfd);
151
152         /* Each TFD can point to a maximum 20 Tx buffers */
153         if (num_tbs >= IWL_NUM_OF_TBS) {
154                 IWL_ERROR("Error can not send more than %d chunks\n",
155                           IWL_NUM_OF_TBS);
156                 return -EINVAL;
157         }
158
159         BUG_ON(addr & ~DMA_BIT_MASK(36));
160         if (unlikely(addr & ~IWL_TX_DMA_MASK))
161                 IWL_ERROR("Unaligned address = %llx\n",
162                           (unsigned long long)addr);
163
164         iwl_tfd_set_tb(tfd, num_tbs, addr, len);
165
166         return 0;
167 }
168
169 /**
170  * iwl_txq_update_write_ptr - Send new write index to hardware
171  */
172 int iwl_txq_update_write_ptr(struct iwl_priv *priv, struct iwl_tx_queue *txq)
173 {
174         u32 reg = 0;
175         int ret = 0;
176         int txq_id = txq->q.id;
177
178         if (txq->need_update == 0)
179                 return ret;
180
181         /* if we're trying to save power */
182         if (test_bit(STATUS_POWER_PMI, &priv->status)) {
183                 /* wake up nic if it's powered down ...
184                  * uCode will wake up, and interrupt us again, so next
185                  * time we'll skip this part. */
186                 reg = iwl_read32(priv, CSR_UCODE_DRV_GP1);
187
188                 if (reg & CSR_UCODE_DRV_GP1_BIT_MAC_SLEEP) {
189                         IWL_DEBUG_INFO("Requesting wakeup, GP1 = 0x%x\n", reg);
190                         iwl_set_bit(priv, CSR_GP_CNTRL,
191                                     CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
192                         return ret;
193                 }
194
195                 /* restore this queue's parameters in nic hardware. */
196                 ret = iwl_grab_nic_access(priv);
197                 if (ret)
198                         return ret;
199                 iwl_write_direct32(priv, HBUS_TARG_WRPTR,
200                                      txq->q.write_ptr | (txq_id << 8));
201                 iwl_release_nic_access(priv);
202
203         /* else not in power-save mode, uCode will never sleep when we're
204          * trying to tx (during RFKILL, we're not trying to tx). */
205         } else
206                 iwl_write32(priv, HBUS_TARG_WRPTR,
207                             txq->q.write_ptr | (txq_id << 8));
208
209         txq->need_update = 0;
210
211         return ret;
212 }
213 EXPORT_SYMBOL(iwl_txq_update_write_ptr);
214
215
216 /**
217  * iwl_tx_queue_free - Deallocate DMA queue.
218  * @txq: Transmit queue to deallocate.
219  *
220  * Empty queue by removing and destroying all BD's.
221  * Free all buffers.
222  * 0-fill, but do not free "txq" descriptor structure.
223  */
224 static void iwl_tx_queue_free(struct iwl_priv *priv, int txq_id)
225 {
226         struct iwl_tx_queue *txq = &priv->txq[txq_id];
227         struct iwl_queue *q = &txq->q;
228         struct pci_dev *dev = priv->pci_dev;
229         int i, len;
230
231         if (q->n_bd == 0)
232                 return;
233
234         /* first, empty all BD's */
235         for (; q->write_ptr != q->read_ptr;
236              q->read_ptr = iwl_queue_inc_wrap(q->read_ptr, q->n_bd))
237                 iwl_hw_txq_free_tfd(priv, txq);
238
239         len = sizeof(struct iwl_cmd) * q->n_window;
240
241         /* De-alloc array of command/tx buffers */
242         for (i = 0; i < TFD_TX_CMD_SLOTS; i++)
243                 kfree(txq->cmd[i]);
244
245         /* De-alloc circular buffer of TFDs */
246         if (txq->q.n_bd)
247                 pci_free_consistent(dev, sizeof(struct iwl_tfd) *
248                                     txq->q.n_bd, txq->tfds, txq->q.dma_addr);
249
250         /* De-alloc array of per-TFD driver data */
251         kfree(txq->txb);
252         txq->txb = NULL;
253
254         /* 0-fill queue descriptor structure */
255         memset(txq, 0, sizeof(*txq));
256 }
257
258
259 /**
260  * iwl_cmd_queue_free - Deallocate DMA queue.
261  * @txq: Transmit queue to deallocate.
262  *
263  * Empty queue by removing and destroying all BD's.
264  * Free all buffers.
265  * 0-fill, but do not free "txq" descriptor structure.
266  */
267 static void iwl_cmd_queue_free(struct iwl_priv *priv)
268 {
269         struct iwl_tx_queue *txq = &priv->txq[IWL_CMD_QUEUE_NUM];
270         struct iwl_queue *q = &txq->q;
271         struct pci_dev *dev = priv->pci_dev;
272         int i, len;
273
274         if (q->n_bd == 0)
275                 return;
276
277         len = sizeof(struct iwl_cmd) * q->n_window;
278         len += IWL_MAX_SCAN_SIZE;
279
280         /* De-alloc array of command/tx buffers */
281         for (i = 0; i <= TFD_CMD_SLOTS; i++)
282                 kfree(txq->cmd[i]);
283
284         /* De-alloc circular buffer of TFDs */
285         if (txq->q.n_bd)
286                 pci_free_consistent(dev, sizeof(struct iwl_tfd) *
287                                     txq->q.n_bd, txq->tfds, txq->q.dma_addr);
288
289         /* 0-fill queue descriptor structure */
290         memset(txq, 0, sizeof(*txq));
291 }
292 /*************** DMA-QUEUE-GENERAL-FUNCTIONS  *****
293  * DMA services
294  *
295  * Theory of operation
296  *
297  * A Tx or Rx queue resides in host DRAM, and is comprised of a circular buffer
298  * of buffer descriptors, each of which points to one or more data buffers for
299  * the device to read from or fill.  Driver and device exchange status of each
300  * queue via "read" and "write" pointers.  Driver keeps minimum of 2 empty
301  * entries in each circular buffer, to protect against confusing empty and full
302  * queue states.
303  *
304  * The device reads or writes the data in the queues via the device's several
305  * DMA/FIFO channels.  Each queue is mapped to a single DMA channel.
306  *
307  * For Tx queue, there are low mark and high mark limits. If, after queuing
308  * the packet for Tx, free space become < low mark, Tx queue stopped. When
309  * reclaiming packets (on 'tx done IRQ), if free space become > high mark,
310  * Tx queue resumed.
311  *
312  * See more detailed info in iwl-4965-hw.h.
313  ***************************************************/
314
315 int iwl_queue_space(const struct iwl_queue *q)
316 {
317         int s = q->read_ptr - q->write_ptr;
318
319         if (q->read_ptr > q->write_ptr)
320                 s -= q->n_bd;
321
322         if (s <= 0)
323                 s += q->n_window;
324         /* keep some reserve to not confuse empty and full situations */
325         s -= 2;
326         if (s < 0)
327                 s = 0;
328         return s;
329 }
330 EXPORT_SYMBOL(iwl_queue_space);
331
332
333 /**
334  * iwl_queue_init - Initialize queue's high/low-water and read/write indexes
335  */
336 static int iwl_queue_init(struct iwl_priv *priv, struct iwl_queue *q,
337                           int count, int slots_num, u32 id)
338 {
339         q->n_bd = count;
340         q->n_window = slots_num;
341         q->id = id;
342
343         /* count must be power-of-two size, otherwise iwl_queue_inc_wrap
344          * and iwl_queue_dec_wrap are broken. */
345         BUG_ON(!is_power_of_2(count));
346
347         /* slots_num must be power-of-two size, otherwise
348          * get_cmd_index is broken. */
349         BUG_ON(!is_power_of_2(slots_num));
350
351         q->low_mark = q->n_window / 4;
352         if (q->low_mark < 4)
353                 q->low_mark = 4;
354
355         q->high_mark = q->n_window / 8;
356         if (q->high_mark < 2)
357                 q->high_mark = 2;
358
359         q->write_ptr = q->read_ptr = 0;
360
361         return 0;
362 }
363
364 /**
365  * iwl_tx_queue_alloc - Alloc driver data and TFD CB for one Tx/cmd queue
366  */
367 static int iwl_tx_queue_alloc(struct iwl_priv *priv,
368                               struct iwl_tx_queue *txq, u32 id)
369 {
370         struct pci_dev *dev = priv->pci_dev;
371
372         /* Driver private data, only for Tx (not command) queues,
373          * not shared with device. */
374         if (id != IWL_CMD_QUEUE_NUM) {
375                 txq->txb = kmalloc(sizeof(txq->txb[0]) *
376                                    TFD_QUEUE_SIZE_MAX, GFP_KERNEL);
377                 if (!txq->txb) {
378                         IWL_ERROR("kmalloc for auxiliary BD "
379                                   "structures failed\n");
380                         goto error;
381                 }
382         } else
383                 txq->txb = NULL;
384
385         /* Circular buffer of transmit frame descriptors (TFDs),
386          * shared with device */
387         txq->tfds = pci_alloc_consistent(dev,
388                         sizeof(txq->tfds[0]) * TFD_QUEUE_SIZE_MAX,
389                         &txq->q.dma_addr);
390
391         if (!txq->tfds) {
392                 IWL_ERROR("pci_alloc_consistent(%zd) failed\n",
393                           sizeof(txq->tfds[0]) * TFD_QUEUE_SIZE_MAX);
394                 goto error;
395         }
396         txq->q.id = id;
397
398         return 0;
399
400  error:
401         kfree(txq->txb);
402         txq->txb = NULL;
403
404         return -ENOMEM;
405 }
406
407 /*
408  * Tell nic where to find circular buffer of Tx Frame Descriptors for
409  * given Tx queue, and enable the DMA channel used for that queue.
410  *
411  * 4965 supports up to 16 Tx queues in DRAM, mapped to up to 8 Tx DMA
412  * channels supported in hardware.
413  */
414 static int iwl_hw_tx_queue_init(struct iwl_priv *priv,
415                                 struct iwl_tx_queue *txq)
416 {
417         int ret;
418         unsigned long flags;
419         int txq_id = txq->q.id;
420
421         spin_lock_irqsave(&priv->lock, flags);
422         ret = iwl_grab_nic_access(priv);
423         if (ret) {
424                 spin_unlock_irqrestore(&priv->lock, flags);
425                 return ret;
426         }
427
428         /* Circular buffer (TFD queue in DRAM) physical base address */
429         iwl_write_direct32(priv, FH_MEM_CBBC_QUEUE(txq_id),
430                              txq->q.dma_addr >> 8);
431
432         /* Enable DMA channel, using same id as for TFD queue */
433         iwl_write_direct32(priv, FH_TCSR_CHNL_TX_CONFIG_REG(txq_id),
434                 FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE |
435                 FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_ENABLE_VAL);
436
437         iwl_release_nic_access(priv);
438         spin_unlock_irqrestore(&priv->lock, flags);
439
440         return 0;
441 }
442
443 /**
444  * iwl_tx_queue_init - Allocate and initialize one tx/cmd queue
445  */
446 static int iwl_tx_queue_init(struct iwl_priv *priv, struct iwl_tx_queue *txq,
447                              int slots_num, u32 txq_id)
448 {
449         int i, len;
450         int ret;
451
452         /*
453          * Alloc buffer array for commands (Tx or other types of commands).
454          * For the command queue (#4), allocate command space + one big
455          * command for scan, since scan command is very huge; the system will
456          * not have two scans at the same time, so only one is needed.
457          * For normal Tx queues (all other queues), no super-size command
458          * space is needed.
459          */
460         len = sizeof(struct iwl_cmd);
461         for (i = 0; i <= slots_num; i++) {
462                 if (i == slots_num) {
463                         if (txq_id == IWL_CMD_QUEUE_NUM)
464                                 len += IWL_MAX_SCAN_SIZE;
465                         else
466                                 continue;
467                 }
468
469                 txq->cmd[i] = kmalloc(len, GFP_KERNEL);
470                 if (!txq->cmd[i])
471                         goto err;
472         }
473
474         /* Alloc driver data array and TFD circular buffer */
475         ret = iwl_tx_queue_alloc(priv, txq, txq_id);
476         if (ret)
477                 goto err;
478
479         txq->need_update = 0;
480
481         /* TFD_QUEUE_SIZE_MAX must be power-of-two size, otherwise
482          * iwl_queue_inc_wrap and iwl_queue_dec_wrap are broken. */
483         BUILD_BUG_ON(TFD_QUEUE_SIZE_MAX & (TFD_QUEUE_SIZE_MAX - 1));
484
485         /* Initialize queue's high/low-water marks, and head/tail indexes */
486         iwl_queue_init(priv, &txq->q, TFD_QUEUE_SIZE_MAX, slots_num, txq_id);
487
488         /* Tell device where to find queue */
489         iwl_hw_tx_queue_init(priv, txq);
490
491         return 0;
492 err:
493         for (i = 0; i < slots_num; i++) {
494                 kfree(txq->cmd[i]);
495                 txq->cmd[i] = NULL;
496         }
497
498         if (txq_id == IWL_CMD_QUEUE_NUM) {
499                 kfree(txq->cmd[slots_num]);
500                 txq->cmd[slots_num] = NULL;
501         }
502         return -ENOMEM;
503 }
504 /**
505  * iwl_hw_txq_ctx_free - Free TXQ Context
506  *
507  * Destroy all TX DMA queues and structures
508  */
509 void iwl_hw_txq_ctx_free(struct iwl_priv *priv)
510 {
511         int txq_id;
512
513         /* Tx queues */
514         for (txq_id = 0; txq_id < priv->hw_params.max_txq_num; txq_id++)
515                 if (txq_id == IWL_CMD_QUEUE_NUM)
516                         iwl_cmd_queue_free(priv);
517                 else
518                         iwl_tx_queue_free(priv, txq_id);
519
520         /* Keep-warm buffer */
521         iwl_kw_free(priv);
522 }
523 EXPORT_SYMBOL(iwl_hw_txq_ctx_free);
524
525 /**
526  * iwl_txq_ctx_reset - Reset TX queue context
527  * Destroys all DMA structures and initialise them again
528  *
529  * @param priv
530  * @return error code
531  */
532 int iwl_txq_ctx_reset(struct iwl_priv *priv)
533 {
534         int ret = 0;
535         int txq_id, slots_num;
536         unsigned long flags;
537
538         iwl_kw_free(priv);
539
540         /* Free all tx/cmd queues and keep-warm buffer */
541         iwl_hw_txq_ctx_free(priv);
542
543         /* Alloc keep-warm buffer */
544         ret = iwl_kw_alloc(priv);
545         if (ret) {
546                 IWL_ERROR("Keep Warm allocation failed\n");
547                 goto error_kw;
548         }
549         spin_lock_irqsave(&priv->lock, flags);
550         ret = iwl_grab_nic_access(priv);
551         if (unlikely(ret)) {
552                 spin_unlock_irqrestore(&priv->lock, flags);
553                 goto error_reset;
554         }
555
556         /* Turn off all Tx DMA fifos */
557         priv->cfg->ops->lib->txq_set_sched(priv, 0);
558
559         iwl_release_nic_access(priv);
560         spin_unlock_irqrestore(&priv->lock, flags);
561
562
563         /* Tell nic where to find the keep-warm buffer */
564         ret = iwl_kw_init(priv);
565         if (ret) {
566                 IWL_ERROR("kw_init failed\n");
567                 goto error_reset;
568         }
569
570         /* Alloc and init all Tx queues, including the command queue (#4) */
571         for (txq_id = 0; txq_id < priv->hw_params.max_txq_num; txq_id++) {
572                 slots_num = (txq_id == IWL_CMD_QUEUE_NUM) ?
573                                         TFD_CMD_SLOTS : TFD_TX_CMD_SLOTS;
574                 ret = iwl_tx_queue_init(priv, &priv->txq[txq_id], slots_num,
575                                        txq_id);
576                 if (ret) {
577                         IWL_ERROR("Tx %d queue init failed\n", txq_id);
578                         goto error;
579                 }
580         }
581
582         return ret;
583
584  error:
585         iwl_hw_txq_ctx_free(priv);
586  error_reset:
587         iwl_kw_free(priv);
588  error_kw:
589         return ret;
590 }
591
592 /**
593  * iwl_txq_ctx_stop - Stop all Tx DMA channels, free Tx queue memory
594  */
595 void iwl_txq_ctx_stop(struct iwl_priv *priv)
596 {
597
598         int txq_id;
599         unsigned long flags;
600
601
602         /* Turn off all Tx DMA fifos */
603         spin_lock_irqsave(&priv->lock, flags);
604         if (iwl_grab_nic_access(priv)) {
605                 spin_unlock_irqrestore(&priv->lock, flags);
606                 return;
607         }
608
609         priv->cfg->ops->lib->txq_set_sched(priv, 0);
610
611         /* Stop each Tx DMA channel, and wait for it to be idle */
612         for (txq_id = 0; txq_id < priv->hw_params.max_txq_num; txq_id++) {
613                 iwl_write_direct32(priv,
614                                    FH_TCSR_CHNL_TX_CONFIG_REG(txq_id), 0x0);
615                 iwl_poll_direct_bit(priv, FH_TSSR_TX_STATUS_REG,
616                                     FH_TSSR_TX_STATUS_REG_MSK_CHNL_IDLE
617                                     (txq_id), 200);
618         }
619         iwl_release_nic_access(priv);
620         spin_unlock_irqrestore(&priv->lock, flags);
621
622         /* Deallocate memory for all Tx queues */
623         iwl_hw_txq_ctx_free(priv);
624 }
625 EXPORT_SYMBOL(iwl_txq_ctx_stop);
626
627 /*
628  * handle build REPLY_TX command notification.
629  */
630 static void iwl_tx_cmd_build_basic(struct iwl_priv *priv,
631                                   struct iwl_tx_cmd *tx_cmd,
632                                   struct ieee80211_tx_info *info,
633                                   struct ieee80211_hdr *hdr,
634                                   int is_unicast, u8 std_id)
635 {
636         __le16 fc = hdr->frame_control;
637         __le32 tx_flags = tx_cmd->tx_flags;
638
639         tx_cmd->stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
640         if (!(info->flags & IEEE80211_TX_CTL_NO_ACK)) {
641                 tx_flags |= TX_CMD_FLG_ACK_MSK;
642                 if (ieee80211_is_mgmt(fc))
643                         tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
644                 if (ieee80211_is_probe_resp(fc) &&
645                     !(le16_to_cpu(hdr->seq_ctrl) & 0xf))
646                         tx_flags |= TX_CMD_FLG_TSF_MSK;
647         } else {
648                 tx_flags &= (~TX_CMD_FLG_ACK_MSK);
649                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
650         }
651
652         if (ieee80211_is_back_req(fc))
653                 tx_flags |= TX_CMD_FLG_ACK_MSK | TX_CMD_FLG_IMM_BA_RSP_MASK;
654
655
656         tx_cmd->sta_id = std_id;
657         if (ieee80211_has_morefrags(fc))
658                 tx_flags |= TX_CMD_FLG_MORE_FRAG_MSK;
659
660         if (ieee80211_is_data_qos(fc)) {
661                 u8 *qc = ieee80211_get_qos_ctl(hdr);
662                 tx_cmd->tid_tspec = qc[0] & 0xf;
663                 tx_flags &= ~TX_CMD_FLG_SEQ_CTL_MSK;
664         } else {
665                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
666         }
667
668         priv->cfg->ops->utils->rts_tx_cmd_flag(info, &tx_flags);
669
670         if ((tx_flags & TX_CMD_FLG_RTS_MSK) || (tx_flags & TX_CMD_FLG_CTS_MSK))
671                 tx_flags |= TX_CMD_FLG_FULL_TXOP_PROT_MSK;
672
673         tx_flags &= ~(TX_CMD_FLG_ANT_SEL_MSK);
674         if (ieee80211_is_mgmt(fc)) {
675                 if (ieee80211_is_assoc_req(fc) || ieee80211_is_reassoc_req(fc))
676                         tx_cmd->timeout.pm_frame_timeout = cpu_to_le16(3);
677                 else
678                         tx_cmd->timeout.pm_frame_timeout = cpu_to_le16(2);
679         } else {
680                 tx_cmd->timeout.pm_frame_timeout = 0;
681         }
682
683         tx_cmd->driver_txop = 0;
684         tx_cmd->tx_flags = tx_flags;
685         tx_cmd->next_frame_len = 0;
686 }
687
688 #define RTS_HCCA_RETRY_LIMIT            3
689 #define RTS_DFAULT_RETRY_LIMIT          60
690
691 static void iwl_tx_cmd_build_rate(struct iwl_priv *priv,
692                               struct iwl_tx_cmd *tx_cmd,
693                               struct ieee80211_tx_info *info,
694                               __le16 fc, int sta_id,
695                               int is_hcca)
696 {
697         u32 rate_flags = 0;
698         int rate_idx;
699         u8 rts_retry_limit = 0;
700         u8 data_retry_limit = 0;
701         u8 rate_plcp;
702
703         rate_idx = min(ieee80211_get_tx_rate(priv->hw, info)->hw_value & 0xffff,
704                         IWL_RATE_COUNT - 1);
705
706         rate_plcp = iwl_rates[rate_idx].plcp;
707
708         rts_retry_limit = (is_hcca) ?
709             RTS_HCCA_RETRY_LIMIT : RTS_DFAULT_RETRY_LIMIT;
710
711         if ((rate_idx >= IWL_FIRST_CCK_RATE) && (rate_idx <= IWL_LAST_CCK_RATE))
712                 rate_flags |= RATE_MCS_CCK_MSK;
713
714
715         if (ieee80211_is_probe_resp(fc)) {
716                 data_retry_limit = 3;
717                 if (data_retry_limit < rts_retry_limit)
718                         rts_retry_limit = data_retry_limit;
719         } else
720                 data_retry_limit = IWL_DEFAULT_TX_RETRY;
721
722         if (priv->data_retry_limit != -1)
723                 data_retry_limit = priv->data_retry_limit;
724
725
726         if (ieee80211_is_data(fc)) {
727                 tx_cmd->initial_rate_index = 0;
728                 tx_cmd->tx_flags |= TX_CMD_FLG_STA_RATE_MSK;
729         } else {
730                 switch (fc & cpu_to_le16(IEEE80211_FCTL_STYPE)) {
731                 case cpu_to_le16(IEEE80211_STYPE_AUTH):
732                 case cpu_to_le16(IEEE80211_STYPE_DEAUTH):
733                 case cpu_to_le16(IEEE80211_STYPE_ASSOC_REQ):
734                 case cpu_to_le16(IEEE80211_STYPE_REASSOC_REQ):
735                         if (tx_cmd->tx_flags & TX_CMD_FLG_RTS_MSK) {
736                                 tx_cmd->tx_flags &= ~TX_CMD_FLG_RTS_MSK;
737                                 tx_cmd->tx_flags |= TX_CMD_FLG_CTS_MSK;
738                         }
739                         break;
740                 default:
741                         break;
742                 }
743
744                 priv->mgmt_tx_ant = iwl_toggle_tx_ant(priv, priv->mgmt_tx_ant);
745                 rate_flags |= iwl_ant_idx_to_flags(priv->mgmt_tx_ant);
746         }
747
748         tx_cmd->rts_retry_limit = rts_retry_limit;
749         tx_cmd->data_retry_limit = data_retry_limit;
750         tx_cmd->rate_n_flags = iwl_hw_set_rate_n_flags(rate_plcp, rate_flags);
751 }
752
753 static void iwl_tx_cmd_build_hwcrypto(struct iwl_priv *priv,
754                                       struct ieee80211_tx_info *info,
755                                       struct iwl_tx_cmd *tx_cmd,
756                                       struct sk_buff *skb_frag,
757                                       int sta_id)
758 {
759         struct ieee80211_key_conf *keyconf = info->control.hw_key;
760
761         switch (keyconf->alg) {
762         case ALG_CCMP:
763                 tx_cmd->sec_ctl = TX_CMD_SEC_CCM;
764                 memcpy(tx_cmd->key, keyconf->key, keyconf->keylen);
765                 if (info->flags & IEEE80211_TX_CTL_AMPDU)
766                         tx_cmd->tx_flags |= TX_CMD_FLG_AGG_CCMP_MSK;
767                 IWL_DEBUG_TX("tx_cmd with aes hwcrypto\n");
768                 break;
769
770         case ALG_TKIP:
771                 tx_cmd->sec_ctl = TX_CMD_SEC_TKIP;
772                 ieee80211_get_tkip_key(keyconf, skb_frag,
773                         IEEE80211_TKIP_P2_KEY, tx_cmd->key);
774                 IWL_DEBUG_TX("tx_cmd with tkip hwcrypto\n");
775                 break;
776
777         case ALG_WEP:
778                 tx_cmd->sec_ctl |= (TX_CMD_SEC_WEP |
779                         (keyconf->keyidx & TX_CMD_SEC_MSK) << TX_CMD_SEC_SHIFT);
780
781                 if (keyconf->keylen == WEP_KEY_LEN_128)
782                         tx_cmd->sec_ctl |= TX_CMD_SEC_KEY128;
783
784                 memcpy(&tx_cmd->key[3], keyconf->key, keyconf->keylen);
785
786                 IWL_DEBUG_TX("Configuring packet for WEP encryption "
787                              "with key %d\n", keyconf->keyidx);
788                 break;
789
790         default:
791                 printk(KERN_ERR "Unknown encode alg %d\n", keyconf->alg);
792                 break;
793         }
794 }
795
796 static void iwl_update_tx_stats(struct iwl_priv *priv, u16 fc, u16 len)
797 {
798         /* 0 - mgmt, 1 - cnt, 2 - data */
799         int idx = (fc & IEEE80211_FCTL_FTYPE) >> 2;
800         priv->tx_stats[idx].cnt++;
801         priv->tx_stats[idx].bytes += len;
802 }
803
804 /*
805  * start REPLY_TX command process
806  */
807 int iwl_tx_skb(struct iwl_priv *priv, struct sk_buff *skb)
808 {
809         struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
810         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
811         struct iwl_tfd *tfd;
812         struct iwl_tx_queue *txq;
813         struct iwl_queue *q;
814         struct iwl_cmd *out_cmd;
815         struct iwl_tx_cmd *tx_cmd;
816         int swq_id, txq_id;
817         dma_addr_t phys_addr;
818         dma_addr_t txcmd_phys;
819         dma_addr_t scratch_phys;
820         u16 len, len_org;
821         u16 seq_number = 0;
822         __le16 fc;
823         u8 hdr_len, unicast;
824         u8 sta_id;
825         u8 wait_write_ptr = 0;
826         u8 tid = 0;
827         u8 *qc = NULL;
828         unsigned long flags;
829         int ret;
830
831         spin_lock_irqsave(&priv->lock, flags);
832         if (iwl_is_rfkill(priv)) {
833                 IWL_DEBUG_DROP("Dropping - RF KILL\n");
834                 goto drop_unlock;
835         }
836
837         if ((ieee80211_get_tx_rate(priv->hw, info)->hw_value & 0xFF) ==
838              IWL_INVALID_RATE) {
839                 IWL_ERROR("ERROR: No TX rate available.\n");
840                 goto drop_unlock;
841         }
842
843         unicast = !is_multicast_ether_addr(hdr->addr1);
844
845         fc = hdr->frame_control;
846
847 #ifdef CONFIG_IWLWIFI_DEBUG
848         if (ieee80211_is_auth(fc))
849                 IWL_DEBUG_TX("Sending AUTH frame\n");
850         else if (ieee80211_is_assoc_req(fc))
851                 IWL_DEBUG_TX("Sending ASSOC frame\n");
852         else if (ieee80211_is_reassoc_req(fc))
853                 IWL_DEBUG_TX("Sending REASSOC frame\n");
854 #endif
855
856         /* drop all data frame if we are not associated */
857         if (ieee80211_is_data(fc) &&
858             (priv->iw_mode != NL80211_IFTYPE_MONITOR ||
859             !(info->flags & IEEE80211_TX_CTL_INJECTED)) && /* packet injection */
860             (!iwl_is_associated(priv) ||
861              ((priv->iw_mode == NL80211_IFTYPE_STATION) && !priv->assoc_id) ||
862              !priv->assoc_station_added)) {
863                 IWL_DEBUG_DROP("Dropping - !iwl_is_associated\n");
864                 goto drop_unlock;
865         }
866
867         spin_unlock_irqrestore(&priv->lock, flags);
868
869         hdr_len = ieee80211_hdrlen(fc);
870
871         /* Find (or create) index into station table for destination station */
872         sta_id = iwl_get_sta_id(priv, hdr);
873         if (sta_id == IWL_INVALID_STATION) {
874                 IWL_DEBUG_DROP("Dropping - INVALID STATION: %pM\n",
875                                hdr->addr1);
876                 goto drop;
877         }
878
879         IWL_DEBUG_TX("station Id %d\n", sta_id);
880
881         swq_id = skb_get_queue_mapping(skb);
882         txq_id = swq_id;
883         if (ieee80211_is_data_qos(fc)) {
884                 qc = ieee80211_get_qos_ctl(hdr);
885                 tid = qc[0] & IEEE80211_QOS_CTL_TID_MASK;
886                 seq_number = priv->stations[sta_id].tid[tid].seq_number;
887                 seq_number &= IEEE80211_SCTL_SEQ;
888                 hdr->seq_ctrl = hdr->seq_ctrl &
889                                 __constant_cpu_to_le16(IEEE80211_SCTL_FRAG);
890                 hdr->seq_ctrl |= cpu_to_le16(seq_number);
891                 seq_number += 0x10;
892                 /* aggregation is on for this <sta,tid> */
893                 if (info->flags & IEEE80211_TX_CTL_AMPDU)
894                         txq_id = priv->stations[sta_id].tid[tid].agg.txq_id;
895                 priv->stations[sta_id].tid[tid].tfds_in_queue++;
896         }
897
898         /* Descriptor for chosen Tx queue */
899         txq = &priv->txq[txq_id];
900         q = &txq->q;
901
902         spin_lock_irqsave(&priv->lock, flags);
903
904         /* Set up first empty TFD within this queue's circular TFD buffer */
905         tfd = &txq->tfds[q->write_ptr];
906         memset(tfd, 0, sizeof(*tfd));
907
908         /* Set up driver data for this TFD */
909         memset(&(txq->txb[q->write_ptr]), 0, sizeof(struct iwl_tx_info));
910         txq->txb[q->write_ptr].skb[0] = skb;
911
912         /* Set up first empty entry in queue's array of Tx/cmd buffers */
913         out_cmd = txq->cmd[q->write_ptr];
914         tx_cmd = &out_cmd->cmd.tx;
915         memset(&out_cmd->hdr, 0, sizeof(out_cmd->hdr));
916         memset(tx_cmd, 0, sizeof(struct iwl_tx_cmd));
917
918         /*
919          * Set up the Tx-command (not MAC!) header.
920          * Store the chosen Tx queue and TFD index within the sequence field;
921          * after Tx, uCode's Tx response will return this value so driver can
922          * locate the frame within the tx queue and do post-tx processing.
923          */
924         out_cmd->hdr.cmd = REPLY_TX;
925         out_cmd->hdr.sequence = cpu_to_le16((u16)(QUEUE_TO_SEQ(txq_id) |
926                                 INDEX_TO_SEQ(q->write_ptr)));
927
928         /* Copy MAC header from skb into command buffer */
929         memcpy(tx_cmd->hdr, hdr, hdr_len);
930
931         /*
932          * Use the first empty entry in this queue's command buffer array
933          * to contain the Tx command and MAC header concatenated together
934          * (payload data will be in another buffer).
935          * Size of this varies, due to varying MAC header length.
936          * If end is not dword aligned, we'll have 2 extra bytes at the end
937          * of the MAC header (device reads on dword boundaries).
938          * We'll tell device about this padding later.
939          */
940         len = sizeof(struct iwl_tx_cmd) +
941                 sizeof(struct iwl_cmd_header) + hdr_len;
942
943         len_org = len;
944         len = (len + 3) & ~3;
945
946         if (len_org != len)
947                 len_org = 1;
948         else
949                 len_org = 0;
950
951         /* Physical address of this Tx command's header (not MAC header!),
952          * within command buffer array. */
953         txcmd_phys = pci_map_single(priv->pci_dev,
954                                     out_cmd, sizeof(struct iwl_cmd),
955                                     PCI_DMA_TODEVICE);
956         pci_unmap_addr_set(&out_cmd->meta, mapping, txcmd_phys);
957         pci_unmap_len_set(&out_cmd->meta, len, sizeof(struct iwl_cmd));
958         /* Add buffer containing Tx command and MAC(!) header to TFD's
959          * first entry */
960         txcmd_phys += offsetof(struct iwl_cmd, hdr);
961         iwl_hw_txq_attach_buf_to_tfd(priv, tfd, txcmd_phys, len);
962
963         if (info->control.hw_key)
964                 iwl_tx_cmd_build_hwcrypto(priv, info, tx_cmd, skb, sta_id);
965
966         /* Set up TFD's 2nd entry to point directly to remainder of skb,
967          * if any (802.11 null frames have no payload). */
968         len = skb->len - hdr_len;
969         if (len) {
970                 phys_addr = pci_map_single(priv->pci_dev, skb->data + hdr_len,
971                                            len, PCI_DMA_TODEVICE);
972                 iwl_hw_txq_attach_buf_to_tfd(priv, tfd, phys_addr, len);
973         }
974
975         /* Tell NIC about any 2-byte padding after MAC header */
976         if (len_org)
977                 tx_cmd->tx_flags |= TX_CMD_FLG_MH_PAD_MSK;
978
979         /* Total # bytes to be transmitted */
980         len = (u16)skb->len;
981         tx_cmd->len = cpu_to_le16(len);
982         /* TODO need this for burst mode later on */
983         iwl_tx_cmd_build_basic(priv, tx_cmd, info, hdr, unicast, sta_id);
984
985         /* set is_hcca to 0; it probably will never be implemented */
986         iwl_tx_cmd_build_rate(priv, tx_cmd, info, fc, sta_id, 0);
987
988         iwl_update_tx_stats(priv, le16_to_cpu(fc), len);
989
990         scratch_phys = txcmd_phys + sizeof(struct iwl_cmd_header) +
991                 offsetof(struct iwl_tx_cmd, scratch);
992         tx_cmd->dram_lsb_ptr = cpu_to_le32(scratch_phys);
993         tx_cmd->dram_msb_ptr = iwl_get_dma_hi_addr(scratch_phys);
994
995         if (!ieee80211_has_morefrags(hdr->frame_control)) {
996                 txq->need_update = 1;
997                 if (qc)
998                         priv->stations[sta_id].tid[tid].seq_number = seq_number;
999         } else {
1000                 wait_write_ptr = 1;
1001                 txq->need_update = 0;
1002         }
1003
1004         iwl_print_hex_dump(priv, IWL_DL_TX, (u8 *)tx_cmd, sizeof(*tx_cmd));
1005
1006         iwl_print_hex_dump(priv, IWL_DL_TX, (u8 *)tx_cmd->hdr, hdr_len);
1007
1008         /* Set up entry for this TFD in Tx byte-count array */
1009         priv->cfg->ops->lib->txq_update_byte_cnt_tbl(priv, txq, len);
1010
1011         /* Tell device the write index *just past* this latest filled TFD */
1012         q->write_ptr = iwl_queue_inc_wrap(q->write_ptr, q->n_bd);
1013         ret = iwl_txq_update_write_ptr(priv, txq);
1014         spin_unlock_irqrestore(&priv->lock, flags);
1015
1016         if (ret)
1017                 return ret;
1018
1019         if ((iwl_queue_space(q) < q->high_mark) && priv->mac80211_registered) {
1020                 if (wait_write_ptr) {
1021                         spin_lock_irqsave(&priv->lock, flags);
1022                         txq->need_update = 1;
1023                         iwl_txq_update_write_ptr(priv, txq);
1024                         spin_unlock_irqrestore(&priv->lock, flags);
1025                 } else {
1026                         ieee80211_stop_queue(priv->hw, swq_id);
1027                 }
1028         }
1029
1030         return 0;
1031
1032 drop_unlock:
1033         spin_unlock_irqrestore(&priv->lock, flags);
1034 drop:
1035         return -1;
1036 }
1037 EXPORT_SYMBOL(iwl_tx_skb);
1038
1039 /*************** HOST COMMAND QUEUE FUNCTIONS   *****/
1040
1041 /**
1042  * iwl_enqueue_hcmd - enqueue a uCode command
1043  * @priv: device private data point
1044  * @cmd: a point to the ucode command structure
1045  *
1046  * The function returns < 0 values to indicate the operation is
1047  * failed. On success, it turns the index (> 0) of command in the
1048  * command queue.
1049  */
1050 int iwl_enqueue_hcmd(struct iwl_priv *priv, struct iwl_host_cmd *cmd)
1051 {
1052         struct iwl_tx_queue *txq = &priv->txq[IWL_CMD_QUEUE_NUM];
1053         struct iwl_queue *q = &txq->q;
1054         struct iwl_tfd *tfd;
1055         struct iwl_cmd *out_cmd;
1056         dma_addr_t phys_addr;
1057         unsigned long flags;
1058         int len, ret;
1059         u32 idx;
1060         u16 fix_size;
1061
1062         cmd->len = priv->cfg->ops->utils->get_hcmd_size(cmd->id, cmd->len);
1063         fix_size = (u16)(cmd->len + sizeof(out_cmd->hdr));
1064
1065         /* If any of the command structures end up being larger than
1066          * the TFD_MAX_PAYLOAD_SIZE, and it sent as a 'small' command then
1067          * we will need to increase the size of the TFD entries */
1068         BUG_ON((fix_size > TFD_MAX_PAYLOAD_SIZE) &&
1069                !(cmd->meta.flags & CMD_SIZE_HUGE));
1070
1071         if (iwl_is_rfkill(priv)) {
1072                 IWL_DEBUG_INFO("Not sending command - RF KILL");
1073                 return -EIO;
1074         }
1075
1076         if (iwl_queue_space(q) < ((cmd->meta.flags & CMD_ASYNC) ? 2 : 1)) {
1077                 IWL_ERROR("No space for Tx\n");
1078                 return -ENOSPC;
1079         }
1080
1081         spin_lock_irqsave(&priv->hcmd_lock, flags);
1082
1083         tfd = &txq->tfds[q->write_ptr];
1084         memset(tfd, 0, sizeof(*tfd));
1085
1086
1087         idx = get_cmd_index(q, q->write_ptr, cmd->meta.flags & CMD_SIZE_HUGE);
1088         out_cmd = txq->cmd[idx];
1089
1090         out_cmd->hdr.cmd = cmd->id;
1091         memcpy(&out_cmd->meta, &cmd->meta, sizeof(cmd->meta));
1092         memcpy(&out_cmd->cmd.payload, cmd->data, cmd->len);
1093
1094         /* At this point, the out_cmd now has all of the incoming cmd
1095          * information */
1096
1097         out_cmd->hdr.flags = 0;
1098         out_cmd->hdr.sequence = cpu_to_le16(QUEUE_TO_SEQ(IWL_CMD_QUEUE_NUM) |
1099                         INDEX_TO_SEQ(q->write_ptr));
1100         if (out_cmd->meta.flags & CMD_SIZE_HUGE)
1101                 out_cmd->hdr.sequence |= SEQ_HUGE_FRAME;
1102         len = (idx == TFD_CMD_SLOTS) ?
1103                         IWL_MAX_SCAN_SIZE : sizeof(struct iwl_cmd);
1104
1105         phys_addr = pci_map_single(priv->pci_dev, out_cmd,
1106                                    len, PCI_DMA_TODEVICE);
1107         pci_unmap_addr_set(&out_cmd->meta, mapping, phys_addr);
1108         pci_unmap_len_set(&out_cmd->meta, len, len);
1109         phys_addr += offsetof(struct iwl_cmd, hdr);
1110
1111         iwl_hw_txq_attach_buf_to_tfd(priv, tfd, phys_addr, fix_size);
1112
1113 #ifdef CONFIG_IWLWIFI_DEBUG
1114         switch (out_cmd->hdr.cmd) {
1115         case REPLY_TX_LINK_QUALITY_CMD:
1116         case SENSITIVITY_CMD:
1117                 IWL_DEBUG_HC_DUMP("Sending command %s (#%x), seq: 0x%04X, "
1118                                 "%d bytes at %d[%d]:%d\n",
1119                                 get_cmd_string(out_cmd->hdr.cmd),
1120                                 out_cmd->hdr.cmd,
1121                                 le16_to_cpu(out_cmd->hdr.sequence), fix_size,
1122                                 q->write_ptr, idx, IWL_CMD_QUEUE_NUM);
1123                                 break;
1124         default:
1125                 IWL_DEBUG_HC("Sending command %s (#%x), seq: 0x%04X, "
1126                                 "%d bytes at %d[%d]:%d\n",
1127                                 get_cmd_string(out_cmd->hdr.cmd),
1128                                 out_cmd->hdr.cmd,
1129                                 le16_to_cpu(out_cmd->hdr.sequence), fix_size,
1130                                 q->write_ptr, idx, IWL_CMD_QUEUE_NUM);
1131         }
1132 #endif
1133         txq->need_update = 1;
1134
1135         /* Set up entry in queue's byte count circular buffer */
1136         priv->cfg->ops->lib->txq_update_byte_cnt_tbl(priv, txq, 0);
1137
1138         /* Increment and update queue's write index */
1139         q->write_ptr = iwl_queue_inc_wrap(q->write_ptr, q->n_bd);
1140         ret = iwl_txq_update_write_ptr(priv, txq);
1141
1142         spin_unlock_irqrestore(&priv->hcmd_lock, flags);
1143         return ret ? ret : idx;
1144 }
1145
1146 int iwl_tx_queue_reclaim(struct iwl_priv *priv, int txq_id, int index)
1147 {
1148         struct iwl_tx_queue *txq = &priv->txq[txq_id];
1149         struct iwl_queue *q = &txq->q;
1150         struct iwl_tx_info *tx_info;
1151         int nfreed = 0;
1152
1153         if ((index >= q->n_bd) || (iwl_queue_used(q, index) == 0)) {
1154                 IWL_ERROR("Read index for DMA queue txq id (%d), index %d, "
1155                           "is out of range [0-%d] %d %d.\n", txq_id,
1156                           index, q->n_bd, q->write_ptr, q->read_ptr);
1157                 return 0;
1158         }
1159
1160         for (index = iwl_queue_inc_wrap(index, q->n_bd);
1161              q->read_ptr != index;
1162              q->read_ptr = iwl_queue_inc_wrap(q->read_ptr, q->n_bd)) {
1163
1164                 tx_info = &txq->txb[txq->q.read_ptr];
1165                 ieee80211_tx_status_irqsafe(priv->hw, tx_info->skb[0]);
1166                 tx_info->skb[0] = NULL;
1167
1168                 if (priv->cfg->ops->lib->txq_inval_byte_cnt_tbl)
1169                         priv->cfg->ops->lib->txq_inval_byte_cnt_tbl(priv, txq);
1170
1171                 iwl_hw_txq_free_tfd(priv, txq);
1172                 nfreed++;
1173         }
1174         return nfreed;
1175 }
1176 EXPORT_SYMBOL(iwl_tx_queue_reclaim);
1177
1178
1179 /**
1180  * iwl_hcmd_queue_reclaim - Reclaim TX command queue entries already Tx'd
1181  *
1182  * When FW advances 'R' index, all entries between old and new 'R' index
1183  * need to be reclaimed. As result, some free space forms.  If there is
1184  * enough free space (> low mark), wake the stack that feeds us.
1185  */
1186 static void iwl_hcmd_queue_reclaim(struct iwl_priv *priv, int txq_id,
1187                                    int idx, int cmd_idx)
1188 {
1189         struct iwl_tx_queue *txq = &priv->txq[txq_id];
1190         struct iwl_queue *q = &txq->q;
1191         int nfreed = 0;
1192
1193         if ((idx >= q->n_bd) || (iwl_queue_used(q, idx) == 0)) {
1194                 IWL_ERROR("Read index for DMA queue txq id (%d), index %d, "
1195                           "is out of range [0-%d] %d %d.\n", txq_id,
1196                           idx, q->n_bd, q->write_ptr, q->read_ptr);
1197                 return;
1198         }
1199
1200         pci_unmap_single(priv->pci_dev,
1201                 pci_unmap_addr(&txq->cmd[cmd_idx]->meta, mapping),
1202                 pci_unmap_len(&txq->cmd[cmd_idx]->meta, len),
1203                 PCI_DMA_TODEVICE);
1204
1205         for (idx = iwl_queue_inc_wrap(idx, q->n_bd); q->read_ptr != idx;
1206              q->read_ptr = iwl_queue_inc_wrap(q->read_ptr, q->n_bd)) {
1207
1208                 if (nfreed++ > 0) {
1209                         IWL_ERROR("HCMD skipped: index (%d) %d %d\n", idx,
1210                                         q->write_ptr, q->read_ptr);
1211                         queue_work(priv->workqueue, &priv->restart);
1212                 }
1213
1214         }
1215 }
1216
1217 /**
1218  * iwl_tx_cmd_complete - Pull unused buffers off the queue and reclaim them
1219  * @rxb: Rx buffer to reclaim
1220  *
1221  * If an Rx buffer has an async callback associated with it the callback
1222  * will be executed.  The attached skb (if present) will only be freed
1223  * if the callback returns 1
1224  */
1225 void iwl_tx_cmd_complete(struct iwl_priv *priv, struct iwl_rx_mem_buffer *rxb)
1226 {
1227         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
1228         u16 sequence = le16_to_cpu(pkt->hdr.sequence);
1229         int txq_id = SEQ_TO_QUEUE(sequence);
1230         int index = SEQ_TO_INDEX(sequence);
1231         int cmd_index;
1232         bool huge = !!(pkt->hdr.sequence & SEQ_HUGE_FRAME);
1233         struct iwl_cmd *cmd;
1234
1235         /* If a Tx command is being handled and it isn't in the actual
1236          * command queue then there a command routing bug has been introduced
1237          * in the queue management code. */
1238         if (WARN(txq_id != IWL_CMD_QUEUE_NUM,
1239                  "wrong command queue %d, command id 0x%X\n", txq_id, pkt->hdr.cmd))
1240                 return;
1241
1242         cmd_index = get_cmd_index(&priv->txq[IWL_CMD_QUEUE_NUM].q, index, huge);
1243         cmd = priv->txq[IWL_CMD_QUEUE_NUM].cmd[cmd_index];
1244
1245         /* Input error checking is done when commands are added to queue. */
1246         if (cmd->meta.flags & CMD_WANT_SKB) {
1247                 cmd->meta.source->u.skb = rxb->skb;
1248                 rxb->skb = NULL;
1249         } else if (cmd->meta.u.callback &&
1250                    !cmd->meta.u.callback(priv, cmd, rxb->skb))
1251                 rxb->skb = NULL;
1252
1253         iwl_hcmd_queue_reclaim(priv, txq_id, index, cmd_index);
1254
1255         if (!(cmd->meta.flags & CMD_ASYNC)) {
1256                 clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
1257                 wake_up_interruptible(&priv->wait_command_queue);
1258         }
1259 }
1260 EXPORT_SYMBOL(iwl_tx_cmd_complete);
1261
1262 /*
1263  * Find first available (lowest unused) Tx Queue, mark it "active".
1264  * Called only when finding queue for aggregation.
1265  * Should never return anything < 7, because they should already
1266  * be in use as EDCA AC (0-3), Command (4), HCCA (5, 6).
1267  */
1268 static int iwl_txq_ctx_activate_free(struct iwl_priv *priv)
1269 {
1270         int txq_id;
1271
1272         for (txq_id = 0; txq_id < priv->hw_params.max_txq_num; txq_id++)
1273                 if (!test_and_set_bit(txq_id, &priv->txq_ctx_active_msk))
1274                         return txq_id;
1275         return -1;
1276 }
1277
1278 int iwl_tx_agg_start(struct iwl_priv *priv, const u8 *ra, u16 tid, u16 *ssn)
1279 {
1280         int sta_id;
1281         int tx_fifo;
1282         int txq_id;
1283         int ret;
1284         unsigned long flags;
1285         struct iwl_tid_data *tid_data;
1286
1287         if (likely(tid < ARRAY_SIZE(default_tid_to_tx_fifo)))
1288                 tx_fifo = default_tid_to_tx_fifo[tid];
1289         else
1290                 return -EINVAL;
1291
1292         IWL_WARNING("%s on ra = %pM tid = %d\n",
1293                         __func__, ra, tid);
1294
1295         sta_id = iwl_find_station(priv, ra);
1296         if (sta_id == IWL_INVALID_STATION)
1297                 return -ENXIO;
1298
1299         if (priv->stations[sta_id].tid[tid].agg.state != IWL_AGG_OFF) {
1300                 IWL_ERROR("Start AGG when state is not IWL_AGG_OFF !\n");
1301                 return -ENXIO;
1302         }
1303
1304         txq_id = iwl_txq_ctx_activate_free(priv);
1305         if (txq_id == -1)
1306                 return -ENXIO;
1307
1308         spin_lock_irqsave(&priv->sta_lock, flags);
1309         tid_data = &priv->stations[sta_id].tid[tid];
1310         *ssn = SEQ_TO_SN(tid_data->seq_number);
1311         tid_data->agg.txq_id = txq_id;
1312         spin_unlock_irqrestore(&priv->sta_lock, flags);
1313
1314         ret = priv->cfg->ops->lib->txq_agg_enable(priv, txq_id, tx_fifo,
1315                                                   sta_id, tid, *ssn);
1316         if (ret)
1317                 return ret;
1318
1319         if (tid_data->tfds_in_queue == 0) {
1320                 printk(KERN_ERR "HW queue is empty\n");
1321                 tid_data->agg.state = IWL_AGG_ON;
1322                 ieee80211_start_tx_ba_cb_irqsafe(priv->hw, ra, tid);
1323         } else {
1324                 IWL_DEBUG_HT("HW queue is NOT empty: %d packets in HW queue\n",
1325                              tid_data->tfds_in_queue);
1326                 tid_data->agg.state = IWL_EMPTYING_HW_QUEUE_ADDBA;
1327         }
1328         return ret;
1329 }
1330 EXPORT_SYMBOL(iwl_tx_agg_start);
1331
1332 int iwl_tx_agg_stop(struct iwl_priv *priv , const u8 *ra, u16 tid)
1333 {
1334         int tx_fifo_id, txq_id, sta_id, ssn = -1;
1335         struct iwl_tid_data *tid_data;
1336         int ret, write_ptr, read_ptr;
1337         unsigned long flags;
1338
1339         if (!ra) {
1340                 IWL_ERROR("ra = NULL\n");
1341                 return -EINVAL;
1342         }
1343
1344         if (likely(tid < ARRAY_SIZE(default_tid_to_tx_fifo)))
1345                 tx_fifo_id = default_tid_to_tx_fifo[tid];
1346         else
1347                 return -EINVAL;
1348
1349         sta_id = iwl_find_station(priv, ra);
1350
1351         if (sta_id == IWL_INVALID_STATION)
1352                 return -ENXIO;
1353
1354         if (priv->stations[sta_id].tid[tid].agg.state != IWL_AGG_ON)
1355                 IWL_WARNING("Stopping AGG while state not IWL_AGG_ON\n");
1356
1357         tid_data = &priv->stations[sta_id].tid[tid];
1358         ssn = (tid_data->seq_number & IEEE80211_SCTL_SEQ) >> 4;
1359         txq_id = tid_data->agg.txq_id;
1360         write_ptr = priv->txq[txq_id].q.write_ptr;
1361         read_ptr = priv->txq[txq_id].q.read_ptr;
1362
1363         /* The queue is not empty */
1364         if (write_ptr != read_ptr) {
1365                 IWL_DEBUG_HT("Stopping a non empty AGG HW QUEUE\n");
1366                 priv->stations[sta_id].tid[tid].agg.state =
1367                                 IWL_EMPTYING_HW_QUEUE_DELBA;
1368                 return 0;
1369         }
1370
1371         IWL_DEBUG_HT("HW queue is empty\n");
1372         priv->stations[sta_id].tid[tid].agg.state = IWL_AGG_OFF;
1373
1374         spin_lock_irqsave(&priv->lock, flags);
1375         ret = priv->cfg->ops->lib->txq_agg_disable(priv, txq_id, ssn,
1376                                                    tx_fifo_id);
1377         spin_unlock_irqrestore(&priv->lock, flags);
1378
1379         if (ret)
1380                 return ret;
1381
1382         ieee80211_stop_tx_ba_cb_irqsafe(priv->hw, ra, tid);
1383
1384         return 0;
1385 }
1386 EXPORT_SYMBOL(iwl_tx_agg_stop);
1387
1388 int iwl_txq_check_empty(struct iwl_priv *priv, int sta_id, u8 tid, int txq_id)
1389 {
1390         struct iwl_queue *q = &priv->txq[txq_id].q;
1391         u8 *addr = priv->stations[sta_id].sta.sta.addr;
1392         struct iwl_tid_data *tid_data = &priv->stations[sta_id].tid[tid];
1393
1394         switch (priv->stations[sta_id].tid[tid].agg.state) {
1395         case IWL_EMPTYING_HW_QUEUE_DELBA:
1396                 /* We are reclaiming the last packet of the */
1397                 /* aggregated HW queue */
1398                 if (txq_id  == tid_data->agg.txq_id &&
1399                     q->read_ptr == q->write_ptr) {
1400                         u16 ssn = SEQ_TO_SN(tid_data->seq_number);
1401                         int tx_fifo = default_tid_to_tx_fifo[tid];
1402                         IWL_DEBUG_HT("HW queue empty: continue DELBA flow\n");
1403                         priv->cfg->ops->lib->txq_agg_disable(priv, txq_id,
1404                                                              ssn, tx_fifo);
1405                         tid_data->agg.state = IWL_AGG_OFF;
1406                         ieee80211_stop_tx_ba_cb_irqsafe(priv->hw, addr, tid);
1407                 }
1408                 break;
1409         case IWL_EMPTYING_HW_QUEUE_ADDBA:
1410                 /* We are reclaiming the last packet of the queue */
1411                 if (tid_data->tfds_in_queue == 0) {
1412                         IWL_DEBUG_HT("HW queue empty: continue ADDBA flow\n");
1413                         tid_data->agg.state = IWL_AGG_ON;
1414                         ieee80211_start_tx_ba_cb_irqsafe(priv->hw, addr, tid);
1415                 }
1416                 break;
1417         }
1418         return 0;
1419 }
1420 EXPORT_SYMBOL(iwl_txq_check_empty);
1421
1422 /**
1423  * iwl_tx_status_reply_compressed_ba - Update tx status from block-ack
1424  *
1425  * Go through block-ack's bitmap of ACK'd frames, update driver's record of
1426  * ACK vs. not.  This gets sent to mac80211, then to rate scaling algo.
1427  */
1428 static int iwl_tx_status_reply_compressed_ba(struct iwl_priv *priv,
1429                                  struct iwl_ht_agg *agg,
1430                                  struct iwl_compressed_ba_resp *ba_resp)
1431
1432 {
1433         int i, sh, ack;
1434         u16 seq_ctl = le16_to_cpu(ba_resp->seq_ctl);
1435         u16 scd_flow = le16_to_cpu(ba_resp->scd_flow);
1436         u64 bitmap;
1437         int successes = 0;
1438         struct ieee80211_tx_info *info;
1439
1440         if (unlikely(!agg->wait_for_ba))  {
1441                 IWL_ERROR("Received BA when not expected\n");
1442                 return -EINVAL;
1443         }
1444
1445         /* Mark that the expected block-ack response arrived */
1446         agg->wait_for_ba = 0;
1447         IWL_DEBUG_TX_REPLY("BA %d %d\n", agg->start_idx, ba_resp->seq_ctl);
1448
1449         /* Calculate shift to align block-ack bits with our Tx window bits */
1450         sh = agg->start_idx - SEQ_TO_INDEX(seq_ctl>>4);
1451         if (sh < 0) /* tbw something is wrong with indices */
1452                 sh += 0x100;
1453
1454         /* don't use 64-bit values for now */
1455         bitmap = le64_to_cpu(ba_resp->bitmap) >> sh;
1456
1457         if (agg->frame_count > (64 - sh)) {
1458                 IWL_DEBUG_TX_REPLY("more frames than bitmap size");
1459                 return -1;
1460         }
1461
1462         /* check for success or failure according to the
1463          * transmitted bitmap and block-ack bitmap */
1464         bitmap &= agg->bitmap;
1465
1466         /* For each frame attempted in aggregation,
1467          * update driver's record of tx frame's status. */
1468         for (i = 0; i < agg->frame_count ; i++) {
1469                 ack = bitmap & (1ULL << i);
1470                 successes += !!ack;
1471                 IWL_DEBUG_TX_REPLY("%s ON i=%d idx=%d raw=%d\n",
1472                         ack? "ACK":"NACK", i, (agg->start_idx + i) & 0xff,
1473                         agg->start_idx + i);
1474         }
1475
1476         info = IEEE80211_SKB_CB(priv->txq[scd_flow].txb[agg->start_idx].skb[0]);
1477         memset(&info->status, 0, sizeof(info->status));
1478         info->flags = IEEE80211_TX_STAT_ACK;
1479         info->flags |= IEEE80211_TX_STAT_AMPDU;
1480         info->status.ampdu_ack_map = successes;
1481         info->status.ampdu_ack_len = agg->frame_count;
1482         iwl_hwrate_to_tx_control(priv, agg->rate_n_flags, info);
1483
1484         IWL_DEBUG_TX_REPLY("Bitmap %llx\n", (unsigned long long)bitmap);
1485
1486         return 0;
1487 }
1488
1489 /**
1490  * iwl_rx_reply_compressed_ba - Handler for REPLY_COMPRESSED_BA
1491  *
1492  * Handles block-acknowledge notification from device, which reports success
1493  * of frames sent via aggregation.
1494  */
1495 void iwl_rx_reply_compressed_ba(struct iwl_priv *priv,
1496                                            struct iwl_rx_mem_buffer *rxb)
1497 {
1498         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
1499         struct iwl_compressed_ba_resp *ba_resp = &pkt->u.compressed_ba;
1500         int index;
1501         struct iwl_tx_queue *txq = NULL;
1502         struct iwl_ht_agg *agg;
1503
1504         /* "flow" corresponds to Tx queue */
1505         u16 scd_flow = le16_to_cpu(ba_resp->scd_flow);
1506
1507         /* "ssn" is start of block-ack Tx window, corresponds to index
1508          * (in Tx queue's circular buffer) of first TFD/frame in window */
1509         u16 ba_resp_scd_ssn = le16_to_cpu(ba_resp->scd_ssn);
1510
1511         if (scd_flow >= priv->hw_params.max_txq_num) {
1512                 IWL_ERROR("BUG_ON scd_flow is bigger than number of queues\n");
1513                 return;
1514         }
1515
1516         txq = &priv->txq[scd_flow];
1517         agg = &priv->stations[ba_resp->sta_id].tid[ba_resp->tid].agg;
1518
1519         /* Find index just before block-ack window */
1520         index = iwl_queue_dec_wrap(ba_resp_scd_ssn & 0xff, txq->q.n_bd);
1521
1522         /* TODO: Need to get this copy more safely - now good for debug */
1523
1524         IWL_DEBUG_TX_REPLY("REPLY_COMPRESSED_BA [%d]Received from %pM, "
1525                            "sta_id = %d\n",
1526                            agg->wait_for_ba,
1527                            (u8 *) &ba_resp->sta_addr_lo32,
1528                            ba_resp->sta_id);
1529         IWL_DEBUG_TX_REPLY("TID = %d, SeqCtl = %d, bitmap = 0x%llx, scd_flow = "
1530                            "%d, scd_ssn = %d\n",
1531                            ba_resp->tid,
1532                            ba_resp->seq_ctl,
1533                            (unsigned long long)le64_to_cpu(ba_resp->bitmap),
1534                            ba_resp->scd_flow,
1535                            ba_resp->scd_ssn);
1536         IWL_DEBUG_TX_REPLY("DAT start_idx = %d, bitmap = 0x%llx \n",
1537                            agg->start_idx,
1538                            (unsigned long long)agg->bitmap);
1539
1540         /* Update driver's record of ACK vs. not for each frame in window */
1541         iwl_tx_status_reply_compressed_ba(priv, agg, ba_resp);
1542
1543         /* Release all TFDs before the SSN, i.e. all TFDs in front of
1544          * block-ack window (we assume that they've been successfully
1545          * transmitted ... if not, it's too late anyway). */
1546         if (txq->q.read_ptr != (ba_resp_scd_ssn & 0xff)) {
1547                 /* calculate mac80211 ampdu sw queue to wake */
1548                 int ampdu_q =
1549                    scd_flow - priv->hw_params.first_ampdu_q + priv->hw->queues;
1550                 int freed = iwl_tx_queue_reclaim(priv, scd_flow, index);
1551                 priv->stations[ba_resp->sta_id].
1552                         tid[ba_resp->tid].tfds_in_queue -= freed;
1553                 if (iwl_queue_space(&txq->q) > txq->q.low_mark &&
1554                         priv->mac80211_registered &&
1555                         agg->state != IWL_EMPTYING_HW_QUEUE_DELBA)
1556                         ieee80211_wake_queue(priv->hw, ampdu_q);
1557
1558                 iwl_txq_check_empty(priv, ba_resp->sta_id,
1559                                     ba_resp->tid, scd_flow);
1560         }
1561 }
1562 EXPORT_SYMBOL(iwl_rx_reply_compressed_ba);
1563
1564 #ifdef CONFIG_IWLWIFI_DEBUG
1565 #define TX_STATUS_ENTRY(x) case TX_STATUS_FAIL_ ## x: return #x
1566
1567 const char *iwl_get_tx_fail_reason(u32 status)
1568 {
1569         switch (status & TX_STATUS_MSK) {
1570         case TX_STATUS_SUCCESS:
1571                 return "SUCCESS";
1572                 TX_STATUS_ENTRY(SHORT_LIMIT);
1573                 TX_STATUS_ENTRY(LONG_LIMIT);
1574                 TX_STATUS_ENTRY(FIFO_UNDERRUN);
1575                 TX_STATUS_ENTRY(MGMNT_ABORT);
1576                 TX_STATUS_ENTRY(NEXT_FRAG);
1577                 TX_STATUS_ENTRY(LIFE_EXPIRE);
1578                 TX_STATUS_ENTRY(DEST_PS);
1579                 TX_STATUS_ENTRY(ABORTED);
1580                 TX_STATUS_ENTRY(BT_RETRY);
1581                 TX_STATUS_ENTRY(STA_INVALID);
1582                 TX_STATUS_ENTRY(FRAG_DROPPED);
1583                 TX_STATUS_ENTRY(TID_DISABLE);
1584                 TX_STATUS_ENTRY(FRAME_FLUSHED);
1585                 TX_STATUS_ENTRY(INSUFFICIENT_CF_POLL);
1586                 TX_STATUS_ENTRY(TX_LOCKED);
1587                 TX_STATUS_ENTRY(NO_BEACON_ON_RADAR);
1588         }
1589
1590         return "UNKNOWN";
1591 }
1592 EXPORT_SYMBOL(iwl_get_tx_fail_reason);
1593 #endif /* CONFIG_IWLWIFI_DEBUG */