1f4afa3b618d147a7a7b9b493f85a86b5ae60a4c
[carl9170fw.git] / carlfw / src / wlan.c
1 /*
2  * carl9170 firmware - used by the ar9170 wireless device
3  *
4  * Interface to the WLAN part of the chip
5  *
6  * Copyright (c) 2000-2005 ZyDAS Technology Corporation
7  * Copyright (c) 2007-2009 Atheros Communications, Inc.
8  * Copyright    2009    Johannes Berg <johannes@sipsolutions.net>
9  * Copyright 2009, 2010 Christian Lamparter <chunkeey@googlemail.com>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License along
22  * with this program; if not, write to the Free Software Foundation, Inc.,
23  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24  */
25
26 #include "carl9170.h"
27 #include "shared/phy.h"
28 #include "hostif.h"
29 #include "timer.h"
30 #include "wl.h"
31 #include "printf.h"
32 #include "rf.h"
33 #include "linux/ieee80211.h"
34
35 static void wlan_txunstuck(unsigned int queue)
36 {
37         set_wlan_txq_dma_addr(queue, ((uint32_t) fw.wlan.tx_queue[queue].head) | 1);
38         wlan_trigger(BIT(queue));
39 }
40
41 static void wlan_txupdate(unsigned int queue)
42 {
43         set_wlan_txq_dma_addr(queue, ((uint32_t) fw.wlan.tx_queue[queue].head));
44         wlan_trigger(BIT(queue));
45 }
46
47 static void wlan_dma_bump(unsigned int qidx)
48 {
49         unsigned int offset = qidx;
50         uint32_t status, trigger;
51
52         status = get(AR9170_MAC_REG_DMA_STATUS) >> 12;
53         trigger = get(AR9170_MAC_REG_DMA_TRIGGER) >> 12;
54
55         while (offset != 0) {
56                 status >>= 4;
57                 trigger >>= 4;
58                 offset--;
59         }
60
61         status &= 0xf;
62         trigger &= 0xf;
63
64         if ((trigger == 0xa) && (status == 0x8)) {
65                 DBG("UNSTUCK");
66                 wlan_txunstuck(qidx);
67         } else {
68                 DBG("UPDATE");
69                 wlan_txupdate(qidx);
70         }
71 }
72
73 #ifdef CONFIG_CARL9170FW_DEBUG
74 static void wlan_dump_queue(unsigned int qidx)
75 {
76
77         struct dma_desc *desc;
78         struct carl9170_tx_superframe *super;
79         int entries = 0;
80
81         __for_each_desc(desc, &fw.wlan.tx_queue[qidx]) {
82                 super = get_super(desc);
83                 DBG("%d: %p s:%x c:%x tl:%x ds:%x n:%p l:%p ", entries, desc,
84                     desc->status, desc->ctrl, desc->totalLen,
85                     desc->dataSize, desc->nextAddr, desc->lastAddr);
86
87                 DBG("c:%x tr:%d ri:%d l:%x m:%x p:%x fc:%x",
88                     super->s.cookie, super->s.cnt, super->s.rix,
89                     super->f.hdr.length, super->f.hdr.mac.set,
90                     (unsigned int) le32_to_cpu(super->f.hdr.phy.set),
91                     super->f.data.i3e.frame_control);
92
93                 entries++;
94         }
95
96         desc = get_wlan_txq_addr(qidx);
97
98         DBG("Queue: %d: te:%d td:%d h:%p c:%p t:%p",
99             qidx, entries, queue_len(&fw.wlan.tx_queue[qidx]),
100             fw.wlan.tx_queue[qidx].head,
101             desc, fw.wlan.tx_queue[qidx].terminator);
102
103         DBG("HW: t:%x s:%x ac:%x c:%x",
104             (unsigned int) get(AR9170_MAC_REG_DMA_TRIGGER),
105             (unsigned int) get(AR9170_MAC_REG_DMA_STATUS),
106             (unsigned int) get(AR9170_MAC_REG_AMPDU_COUNT),
107             (unsigned int) get(AR9170_MAC_REG_DMA_TXQX_ADDR_CURR));
108 }
109 #endif /* CONFIG_CARL9170FW_DEBUG */
110
111 static void wlan_send_buffered_tx_status(void)
112 {
113         unsigned int len;
114
115         while (fw.wlan.tx_status_pending) {
116                 len = min((unsigned int)fw.wlan.tx_status_pending,
117                           CARL9170_RSP_TX_STATUS_NUM);
118                 len = min(len, CARL9170_TX_STATUS_NUM - fw.wlan.tx_status_head_idx);
119
120                 /*
121                  * rather than memcpy each individual request into a large buffer,
122                  * we _splice_ them all together.
123                  *
124                  * The only downside is however that we have to be careful around
125                  * the edges of the tx_status_cache.
126                  *
127                  * Note:
128                  * Each tx_status is about 2 bytes. However every command package
129                  * must have a size which is a multiple of 4.
130                  */
131
132                 send_cmd_to_host((len * sizeof(struct carl9170_tx_status) + 3) & ~3,
133                                  CARL9170_RSP_TXCOMP, len, (void *)
134                                  &fw.wlan.tx_status_cache[fw.wlan.tx_status_head_idx]);
135
136                 fw.wlan.tx_status_pending -= len;
137                 fw.wlan.tx_status_head_idx += len;
138                 fw.wlan.tx_status_head_idx %= CARL9170_TX_STATUS_NUM;
139         }
140 }
141
142 static struct carl9170_tx_status *wlan_get_tx_status_buffer(void)
143 {
144         struct carl9170_tx_status *tmp;
145
146         tmp = &fw.wlan.tx_status_cache[fw.wlan.tx_status_tail_idx++];
147         fw.wlan.tx_status_tail_idx %= CARL9170_TX_STATUS_NUM;
148
149         if (fw.wlan.tx_status_pending == CARL9170_TX_STATUS_NUM)
150                 wlan_send_buffered_tx_status();
151
152         fw.wlan.tx_status_pending++;
153
154         return tmp;
155 }
156
157 /* generate _aggregated_ tx_status for the host */
158 static void wlan_tx_complete(struct carl9170_tx_superframe *super,
159                              bool txs)
160 {
161         struct carl9170_tx_status *status;
162
163         status = wlan_get_tx_status_buffer();
164
165         /*
166          * The *unique* cookie and AC_ID is used by the driver for
167          * frame lookup.
168          */
169         status->cookie = super->s.cookie;
170         status->queue = super->s.queue;
171
172         /*
173          * This field holds the number of tries of the rate in
174          * the rate index field (rix).
175          */
176         status->rix = super->s.rix;
177         status->tries = super->s.cnt;
178         status->success = (txs) ? 1 : 0;
179 }
180
181 static bool wlan_tx_consume_retry(struct carl9170_tx_superframe *super)
182 {
183         /* check if this was the last possible retry with this rate */
184         if (unlikely(super->s.cnt >= super->s.ri[super->s.rix].tries)) {
185                 /* end of the road - indicate tx failure */
186                 if (unlikely(super->s.rix == CARL9170_TX_MAX_RETRY_RATES))
187                         return false;
188
189                 /* check if there are alternative rates available */
190                 if (!super->s.rr[super->s.rix].set)
191                         return false;
192
193                 /* try next retry rate */
194                 super->f.hdr.phy.set = super->s.rr[super->s.rix].set;
195
196                 /* finally - mark the old rate as USED */
197                 super->s.rix++;
198
199                 /* update MAC flags */
200                 super->f.hdr.mac.erp_prot = super->s.ri[super->s.rix].erp_prot;
201
202                 /* reinitialize try counter */
203                 super->s.cnt = 1;
204         } else {
205                 /* just increase retry counter */
206                 super->s.cnt++;
207         }
208
209         return true;
210 }
211
212 /* for all tries */
213 static void __wlan_tx(struct dma_desc *desc)
214 {
215         struct carl9170_tx_superframe *super = get_super(desc);
216 #ifdef CONFIG_CARL9170FW_NORMAL_TX_RX
217         unsigned int queue = super->s.queue;
218 #endif /* CONFIG_CARL9170FW_LOOPBACK */
219
220         if (unlikely(super->s.fill_in_tsf)) {
221                 struct ieee80211_mgmt *mgmt = (void *) &super->f.data.i3e;
222                 uint32_t *tsf = (uint32_t *) &mgmt->u.probe_resp.timestamp;
223
224                 /*
225                  * Truth be told: this is a hack.
226                  *
227                  * The *real* TSF is definitely going to be higher/older.
228                  * But this hardware emulation code is head and shoulders
229                  * above anything a driver can possibly do.
230                  *
231                  * (even, if it's got an accurate atomic clock source).
232                  */
233
234                 read_tsf(tsf);
235         }
236
237 #if (defined CONFIG_CARL9170FW_LOOPBACK) || (defined CONFIG_CARL9170FW_DISCARD)
238         wlan_tx_complete(super, true);
239         unhide_super(desc);
240 # ifdef CONFIG_CARL9170FW_LOOPBACK
241         dma_put(&fw.pta.up_queue, desc);
242         up_trigger();
243 # elif CONFIG_CARL9170FW_DISCARD
244         dma_reclaim(&fw.pta.down_queue, desc);
245         down_trigger();
246 # endif
247 #else /* CONFIG_CARL9170FW_LOOPBACK */
248
249 # if ((defined CONFIG_CARL9170FW_DEBUG) && (defined CONFIG_CARL9170FW_PSM))
250         BUG_ON(fw.phy.psm.state != CARL9170_PSM_WAKE);
251 # endif /* CONFIG_CARL9170FW_DEBUG && CONFIG_CARL9170FW_PSM */
252
253         /* insert desc into the right queue */
254         dma_put(&fw.wlan.tx_queue[queue], desc);
255         wlan_trigger(BIT(queue));
256 #endif /* CONFIG_CARL9170FW_LOOPBACK */
257 }
258
259 /* prepares frame for the first transmission */
260 static void _wlan_tx(struct dma_desc *desc)
261 {
262         struct carl9170_tx_superframe *super = get_super(desc);
263
264         if (unlikely(super->s.ampdu_commit_density)) {
265                 set(AR9170_MAC_REG_AMPDU_DENSITY,
266                     MOD_VAL(AR9170_MAC_AMPDU_DENSITY,
267                             get(AR9170_MAC_REG_AMPDU_DENSITY),
268                             super->s.ampdu_density));
269         }
270
271         if (unlikely(super->s.ampdu_commit_factor)) {
272                 set(AR9170_MAC_REG_AMPDU_FACTOR,
273                     MOD_VAL(AR9170_MAC_AMPDU_FACTOR,
274                             get(AR9170_MAC_REG_AMPDU_FACTOR),
275                             8 << super->s.ampdu_factor));
276         }
277
278         __wlan_tx(desc);
279 }
280
281 /* propagate transmission status back to the driver */
282 static bool wlan_tx_status(struct dma_queue *queue,
283                            struct dma_desc *desc)
284 {
285         struct ar9170_tx_frame *frame = DESC_PAYLOAD(desc);
286         struct carl9170_tx_superframe *super = get_super(desc);
287         struct ieee80211_hdr *hdr = &super->f.data.i3e;
288         unsigned int qidx = super->s.queue;
289         bool txfail, success;
290
291         success = true;
292
293         if (!!(desc->ctrl & AR9170_CTRL_FAIL)) {
294                 txfail = !!(desc->ctrl & AR9170_CTRL_TXFAIL);
295
296                 /* reset retry indicator flags */
297                 desc->ctrl &= ~(AR9170_CTRL_TXFAIL | AR9170_CTRL_BAFAIL);
298
299                 if (wlan_tx_consume_retry(super)) {
300                         /*
301                          * retry for simple and aggregated 802.11 frames.
302                          *
303                          * Note: We must not mess up the original frame
304                          * order.
305                          */
306
307                         if (!frame->hdr.mac.ampdu) {
308                                 /*
309                                  * 802.11 - 7.1.3.1.5.
310                                  * set "Retry Field" for consecutive attempts
311                                  *
312                                  * Note: For AMPDU see:
313                                  * 802.11n 9.9.1.6 "Retransmit Procedures"
314                                  */
315
316                                 hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_RETRY);
317                         }
318
319                         if (txfail) {
320                                 /* Normal TX Failure */
321
322                                 /* demise descriptor ownership back to the hardware */
323                                 dma_rearm(desc);
324
325                                 /*
326                                  * And this will get the queue going again.
327                                  * To understand why: you have to get the HW
328                                  * specs... But sadly I never saw them.
329                                  */
330                                 wlan_txunstuck(qidx);
331
332                                 /* abort cycle - this is necessary due to HW design */
333                                 return false;
334                         } else {
335                                 /* (HT-) BlockACK failure */
336
337                                 /*
338                                  * Unlink the failed attempt and put it into
339                                  * the retry queue. The caller routine must
340                                  * be aware of this so the frames don't get lost.
341                                  */
342
343                                 dma_unlink_head(queue);
344 #ifdef CONFIG_CARL9170FW_DELAYED_TX
345                                 dma_put(&fw.wlan.tx_retry, desc);
346 #else
347                                 __wlan_tx(desc);
348 #endif /* CONFIG_CARL9170FW_DELAYED_TX */
349                                 return true;
350                         }
351                 } else {
352                         /* out of frame attempts - discard frame */
353                         success = false;
354                 }
355         }
356
357         dma_unlink_head(queue);
358         if (txfail) {
359                 /*
360                  * Issue the queue bump,
361                  * We need to do this in case this was the frame's last
362                  * possible retry attempt and it unfortunately: it failed.
363                  */
364
365                 wlan_txunstuck(qidx);
366         }
367
368         unhide_super(desc);
369
370         /* update hangcheck */
371         fw.wlan.last_tx_desc_num[qidx] = 0;
372
373 #ifdef CONFIG_CARL9170FW_HANDLE_BACK_REQ
374         if (unlikely(super == (void *) &dma_mem.reserved.ba)) {
375                 fw.wlan.ba_desc = desc;
376                 fw.wlan.ba_desc_available = 1;
377                 return true;
378         }
379 #endif /* CONFIG_CARL9170FW_HANDLE_BACK_REQ */
380
381         wlan_tx_complete(super, success);
382
383 #ifdef CONFIG_CARL9170FW_CAB_QUEUE
384         if (unlikely(super->s.cab))
385                 fw.wlan.cab_queue_len--;
386 #endif /* CONFIG_CARL9170FW_CAB_QUEUE */
387
388         /* recycle freed descriptors */
389         dma_reclaim(&fw.pta.down_queue, desc);
390         down_trigger();
391         return true;
392 }
393
394 static void handle_tx_completion(void)
395 {
396         struct dma_desc *desc;
397         unsigned int i;
398
399         for (i = 0; i < __AR9170_NUM_TX_QUEUES; i++) {
400                 __while_desc_bits(desc, &fw.wlan.tx_queue[i], AR9170_OWN_BITS_SW) {
401                         if (!wlan_tx_status(&fw.wlan.tx_queue[i], desc)) {
402                                 /* termination requested. */
403                                 break;
404                         }
405                 }
406
407 #ifdef CONFIG_CARL9170FW_DELAYED_TX
408                 for_each_desc(desc, &fw.wlan.tx_retry)
409                         __wlan_tx(desc);
410
411                 for_each_desc(desc, &fw.wlan.tx_delay[i])
412                         _wlan_tx(desc);
413 #endif /* CONFIG_CARL9170FW_DELAYED_TX */
414         }
415 }
416
417 void __hot wlan_tx(struct dma_desc *desc)
418 {
419         struct carl9170_tx_superframe *super = DESC_PAYLOAD(desc);
420
421         /* initialize rate control struct */
422         super->s.rix = 0;
423         super->s.cnt = 1;
424         hide_super(desc);
425
426 #ifdef CONFIG_CARL9170FW_DELAYED_TX
427         if (!queue_empty(&fw.wlan.tx_queue[super->s.queue])) {
428                 dma_put(&fw.wlan.tx_delay[super->s.queue], desc);
429                 return;
430         }
431 #endif /* CONFIG_CARL9170FW_DELAYED_TX */
432
433 #ifdef CONFIG_CARL9170FW_CAB_QUEUE
434         if (unlikely(super->s.cab)) {
435                 fw.wlan.cab_queue_len++;
436                 dma_put(&fw.wlan.cab_queue, desc);
437                 return;
438         }
439 #endif /* CONFIG_CARL9170FW_CAB_QUEUE */
440
441         _wlan_tx(desc);
442 }
443
444 #ifdef CONFIG_CARL9170FW_HANDLE_BACK_REQ
445 static void wlan_send_buffered_ba(void)
446 {
447         struct carl9170_tx_ba_superframe *baf = &dma_mem.reserved.ba.ba;
448         struct ieee80211_ba *ba = (struct ieee80211_ba *) &baf->f.ba;
449         struct carl9170_bar_ctx *ctx;
450
451         if (likely(fw.wlan.ba_head_idx == fw.wlan.ba_tail_idx))
452                 return;
453
454         /* there's no point to continue when the ba_desc is not available. */
455         if (!fw.wlan.ba_desc_available)
456                 return;
457
458         ctx = &fw.wlan.ba_cache[fw.wlan.ba_head_idx % CONFIG_CARL9170FW_BACK_REQS_NUM];
459         fw.wlan.ba_head_idx++;
460
461         /* Format BlockAck */
462         fw.wlan.ba_desc->status = 0;
463         fw.wlan.ba_desc->ctrl = AR9170_CTRL_FS_BIT | AR9170_CTRL_LS_BIT;
464         fw.wlan.ba_desc_available = 0;
465         fw.wlan.ba_desc->nextAddr = fw.wlan.ba_desc->lastAddr =
466                 fw.wlan.ba_desc;
467
468         baf->s.len = fw.wlan.ba_desc->totalLen = fw.wlan.ba_desc->dataSize =
469                 sizeof(struct carl9170_tx_superdesc) +
470                 sizeof(struct ar9170_tx_hwdesc) +
471                 sizeof(struct ieee80211_ba);
472
473         baf->s.ri[0].tries = 3;
474         baf->s.queue = 0;
475         baf->f.hdr.length = sizeof(struct ieee80211_ba) + FCS_LEN;
476
477         /* HW Duration / Backoff */
478         baf->f.hdr.mac.backoff = 1;
479         baf->f.hdr.mac.hw_duration = 1;
480
481         /* take the TX rate from the RX'd BAR */
482         baf->f.hdr.phy.set = ctx->phy;
483         baf->f.hdr.phy.tx_power = 29; /* 14.5 dBm */
484
485         /* format outgoing BA */
486         ba->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL | IEEE80211_STYPE_BACK);
487         ba->duration = cpu_to_le16(0);
488         memcpy(ba->ta, ctx->ta, 6);
489         memcpy(ba->ra, ctx->ra, 6);
490
491         /*
492          * Unfortunately, we cannot look into the hardware's scoreboard.
493          * Therefore we have to proceed as described in 802.11n 9.10.7.5
494          * and send a null BlockAck.
495          */
496         memset(ba->bitmap, 0x0, sizeof(ba->bitmap));
497
498         /*
499          * NB:
500          * not entirely sure if this is 100% correct?!
501          */
502         ba->control = ctx->control | cpu_to_le16(1);
503         ba->start_seq_num = ctx->start_seq_num;
504
505         wlan_tx(fw.wlan.ba_desc);
506 }
507
508 static struct carl9170_bar_ctx *wlan_get_bar_cache_buffer(void)
509 {
510         struct carl9170_bar_ctx *tmp;
511
512         /* expire oldest entry, if we ran out of ba_ctx' */
513         if (fw.wlan.ba_head_idx + CONFIG_CARL9170FW_BACK_REQS_NUM < fw.wlan.ba_tail_idx)
514                 fw.wlan.ba_head_idx++;
515
516         tmp = &fw.wlan.ba_cache[fw.wlan.ba_tail_idx % CONFIG_CARL9170FW_BACK_REQS_NUM];
517         fw.wlan.ba_tail_idx++;
518
519         return tmp;
520 }
521
522 static void handle_bar(struct dma_desc *desc)
523 {
524         struct ieee80211_hdr *hdr;
525         struct ieee80211_bar *bar;
526         struct carl9170_bar_ctx *ctx;
527
528         hdr = ar9170_get_rx_i3e(desc);
529
530         /* check if this is a BAR for us */
531         if (likely(!ieee80211_is_back_req(hdr->frame_control)))
532                 return ;
533
534         if (unlikely(ar9170_get_rx_macstatus_error(desc))) {
535                 /*
536                  * This check does a number of things:
537                  * 1. checks if the frame is in good nick
538                  * 2. checks if the RA (MAC) matches
539                  */
540                 return ;
541         }
542
543         if (unlikely(ar9170_get_rx_mpdu_len(desc) <
544             sizeof(struct ieee80211_bar))) {
545                 /*
546                  * Sneaky, corrupted BARs... but not with us!
547                  */
548
549                 return ;
550         }
551
552         bar = (void *) hdr;
553
554         if ((bar->control & cpu_to_le16(IEEE80211_BAR_CTRL_MULTI_TID)) ||
555             !(bar->control & cpu_to_le16(IEEE80211_BAR_CTRL_CBMTID_COMPRESSED_BA))) {
556                 /* not implemented yet */
557
558                 return ;
559         }
560
561         ctx = wlan_get_bar_cache_buffer();
562
563         /* Brilliant! The BAR provides all necessary MACs! */
564         memcpy(ctx->ra, bar->ta, 6);
565         memcpy(ctx->ta, bar->ra, 6);
566
567         /*
568          * NB:
569          * not entirely sure if this is 100% correct to force the
570          * imm ack bit or not...
571          */
572         ctx->control = bar->control | cpu_to_le16(1);
573         ctx->start_seq_num = bar->start_seq_num;
574         ctx->phy = ar9170_rx_to_phy(desc);
575         if (unlikely(!ctx->phy)) {
576                 /* provide a backup, in case ar9170_rx_to_phy fails */
577                 ctx->phy = cpu_to_le32(0x2cc301);
578         }
579 }
580 #endif /* CONFIG_CARL9170FW_HANDLE_BACK_REQ */
581
582 static void wlan_check_rx_overrun(void)
583 {
584         uint32_t overruns, total;
585
586         fw.wlan.rx_total += total = get(AR9170_MAC_REG_RX_TOTAL);
587         fw.wlan.rx_overruns += overruns = get(AR9170_MAC_REG_RX_OVERRUN);
588         if (unlikely(overruns)) {
589                 if (overruns == total) {
590                         DBG("RX Overrun");
591                         fw.wlan.mac_reset++;
592                 }
593         }
594 }
595
596 static void handle_rx(void)
597 {
598         struct dma_desc *desc;
599
600         wlan_check_rx_overrun();
601
602         for_each_desc_not_bits(desc, &fw.wlan.rx_queue, AR9170_OWN_BITS_HW) {
603                 if (unlikely(desc->totalLen < 26 ||
604                     desc->totalLen > CONFIG_CARL9170FW_RX_FRAME_LEN)) {
605                         /*
606                          * This frame is too damaged to do anything
607                          * useful with it.
608                          */
609                         dma_reclaim(&fw.wlan.rx_queue, desc);
610                         _wlan_trigger(AR9170_DMA_TRIGGER_RXQ);
611                 } else {
612 #ifdef CONFIG_CARL9170FW_HANDLE_BACK_REQ
613                         handle_bar(desc);
614 #endif /* CONFIG_CARL9170FW_HANDLE_BACK_REQ */
615
616                         dma_put(&fw.pta.up_queue, desc);
617                         up_trigger();
618                 }
619         }
620 }
621
622 #ifdef CONFIG_CARL9170FW_CAB_QUEUE
623 static uint8_t *beacon_find_ie(uint8_t ie)
624 {
625         struct ieee80211_mgmt *mgmt = getp(AR9170_MAC_REG_BCN_ADDR);
626         uint8_t *pos, *end;
627         unsigned int len;
628
629         len = get(AR9170_MAC_REG_BCN_LENGTH);
630
631         if (len < FCS_LEN + sizeof(mgmt))
632                 return NULL;
633
634         pos = mgmt->u.beacon.variable;
635         end = (uint8_t *) ((unsigned long)mgmt + (len - FCS_LEN));
636         while (pos < end) {
637                 if (pos + 2 + pos[1] > end)
638                         return NULL;
639
640                 if (pos[0] == ie)
641                         return pos;
642
643                 pos += pos[1] + 2;
644         }
645
646         return NULL;
647 }
648
649 static void wlan_cab_flush_queue(void)
650 {
651         struct dma_desc *desc;
652         uint8_t *_ie;
653         struct ieee80211_tim_ie *ie;
654
655         /*
656          * This prevents the code from sending new BC/MC frames
657          * which were queued after the previous buffered traffic
658          * has been sent out... They will have to wait until the
659          * next DTIM beacon comes along.
660          */
661         if (unlikely(fw.wlan.cab_flush_trigger == CARL9170_CAB_TRIGGER_DEFER))
662                 return ;
663
664         _ie = beacon_find_ie(WLAN_EID_TIM);
665         if (unlikely(!_ie))
666                 return ;
667
668         ie = (struct ieee80211_tim_ie *) &_ie[2];
669
670         /* Ideally, check here for == AR9170_CAB_TRIGGER_ARMED */
671         if (fw.wlan.cab_flush_trigger) {
672                 /* move queued frames into the main tx queues */
673                 for_each_desc(desc, &fw.wlan.cab_queue) {
674                         struct carl9170_tx_superframe *super = get_super(desc);
675
676                         if (!queue_empty(&fw.wlan.cab_queue)) {
677                                 /*
678                                  * Set MOREDATA flag for all,
679                                  * but the last queued frame.
680                                  * see: 802.11-2007 11.2.1.5 f)
681                                  *
682                                  * This is actually the reason to why
683                                  * we need to prevent the reentry.
684                                  */
685
686                                 super->f.data.i3e.frame_control |=
687                                         cpu_to_le16(IEEE80211_FCTL_MOREDATA);
688                         } else {
689                                 super->f.data.i3e.frame_control &=
690                                         cpu_to_le16(~IEEE80211_FCTL_MOREDATA);
691                         }
692
693                         /* ready to roll! */
694                         _wlan_tx(desc);
695                 }
696         }
697
698         /* Transfer finished - waiting for tx status */
699         fw.wlan.cab_flush_trigger = CARL9170_CAB_TRIGGER_DEFER;
700 }
701
702 static void wlan_cab_modify_dtim_beacon(void)
703 {
704         uint8_t *_ie;
705         struct ieee80211_tim_ie *ie;
706
707         _ie = beacon_find_ie(WLAN_EID_TIM);
708         if (likely(_ie)) {
709                 ie = (struct ieee80211_tim_ie *) &_ie[2];
710
711                 if (!queue_empty(&fw.wlan.cab_queue) && (ie->dtim_count == 0)) {
712                         /* schedule DTIM transfer */
713                         fw.wlan.cab_flush_trigger = CARL9170_CAB_TRIGGER_ARMED;
714                 } else if ((fw.wlan.cab_queue_len == 0) && (fw.wlan.cab_flush_trigger)) {
715                         /* undo all chances to the beacon structure */
716                         ie->bitmap_ctrl &= ~0x1;
717                         fw.wlan.cab_flush_trigger = CARL9170_CAB_TRIGGER_EMPTY;
718                 }
719
720                 if (fw.wlan.cab_flush_trigger) {
721                         /* Set the almighty Multicast Traffic Indication Bit. */
722                         ie->bitmap_ctrl |= 0x1;
723                 }
724         }
725 }
726 #endif /* CONFIG_CARL9170FW_CAB_QUEUE */
727
728 static void handle_beacon_config(void)
729 {
730         uint32_t bcn_count;
731
732 #ifdef CONFIG_CARL9170FW_CAB_QUEUE
733         /*
734          * The application has now updated the relevant beacon data.
735          * Now it should be the perfect time to apply the DTIM
736          * multicast information.
737          */
738
739         wlan_cab_modify_dtim_beacon();
740 #endif /* CONFIG_CARL9170FW_CAB_QUEUE */
741
742         bcn_count = get(AR9170_MAC_REG_BCN_COUNT);
743         send_cmd_to_host(4, CARL9170_RSP_BEACON_CONFIG, 0x00,
744                          (uint8_t *) &bcn_count);
745 }
746
747 static void handle_pretbtt(void)
748 {
749 #ifdef CONFIG_CARL9170FW_CAB_QUEUE
750         fw.wlan.cab_flush_time = get_clock_counter();
751 #endif /* CONFIG_CARL9170FW_CAB_QUEUE */
752
753 #ifdef CONFIG_CARL9170FW_PSM
754         rf_psm();
755
756         send_cmd_to_host(4, CARL9170_RSP_PRETBTT, 0x00,
757                          (uint8_t *) &fw.phy.psm.state);
758 #else
759         send_cmd_to_host(0, CARL9170_RSP_PRETBTT, 0x00, NULL);
760 #endif /* CONFIG_CARL9170FW_PSM */
761
762 }
763
764 static void handle_atim(void)
765 {
766         send_cmd_to_host(0, CARL9170_RSP_ATIM, 0x00, NULL);
767 }
768
769 #ifdef CONFIG_CARL9170FW_DEBUG
770 static void handle_qos(void)
771 {
772         /*
773          * What is the QoS Bit used for?
774          * Is it only an indicator for TXOP & Burst, or
775          * should we do something here?
776          */
777 }
778
779 static void handle_radar(void)
780 {
781         send_cmd_to_host(0, CARL9170_RSP_RADAR, 0x00, NULL);
782 }
783 #endif /* CONFIG_CARL9170FW_DEBUG */
784
785 static void wlan_janitor(void)
786 {
787 #ifdef CONFIG_CARL9170FW_CAB_QUEUE
788         if (unlikely(fw.wlan.cab_flush_trigger)) {
789                 /*
790                  * This is hardcoded into carl9170usb driver.
791                  *
792                  * The driver must set the PRETBTT event to beacon_interval -
793                  * CARL9170_PRETBTT_KUS (usually 6) Kus.
794                  *
795                  * But still, we can only do so much about 802.11-2007 9.3.2.1 &
796                  * 11.2.1.6. Let's hope the current solution is adequate enough.
797                  */
798
799                 if (is_after_msecs(fw.wlan.cab_flush_time,
800                     (CARL9170_TBTT_DELTA))) {
801                         wlan_cab_flush_queue();
802                 }
803         }
804 #endif /* CONFIG_CARL9170FW_CAB_QUEUE */
805
806 #ifdef CONFIG_CARL9170FW_DELAYED_TX
807         if (fw.wlan.tx_trigger) {
808                 _wlan_trigger(fw.wlan.tx_trigger);
809                 fw.wlan.tx_trigger = 0;
810         }
811 #endif /* CONFIG_CARL9170FW_DELAYED_TX */
812
813         wlan_send_buffered_tx_status();
814
815 #ifdef CONFIG_CARL9170FW_HANDLE_BACK_REQ
816         wlan_send_buffered_ba();
817 #endif /* CONFIG_CARL9170FW_HANDLE_BACK_REQ */
818 }
819
820 void handle_wlan(void)
821 {
822         uint32_t intr;
823
824         intr = get(AR9170_MAC_REG_INT_CTRL);
825         /* ACK Interrupt */
826         set(AR9170_MAC_REG_INT_CTRL, intr);
827
828 #define HANDLER(intr, flag, func)                       \
829         do {                                            \
830                 if ((intr & flag) != 0) {               \
831                         func();                         \
832                 }                                       \
833         } while (0)
834
835         HANDLER(intr, AR9170_MAC_INT_PRETBTT, handle_pretbtt);
836
837         HANDLER(intr, AR9170_MAC_INT_ATIM, handle_atim);
838
839         HANDLER(intr, AR9170_MAC_INT_RXC, handle_rx);
840
841         HANDLER(intr, (AR9170_MAC_INT_TXC | AR9170_MAC_INT_RETRY_FAIL),
842                 handle_tx_completion);
843
844 #ifdef CONFIG_CARL9170FW_DEBUG
845         HANDLER(intr, AR9170_MAC_INT_QOS, handle_qos);
846
847         HANDLER(intr, AR9170_MAC_INT_RADAR, handle_radar);
848 #endif /* CONFIG_CARL9170FW_DEBUG */
849
850         HANDLER(intr, AR9170_MAC_INT_CFG_BCN, handle_beacon_config);
851
852         if (unlikely(intr))
853                 DBG("Unhandled Interrupt %x\n", (unsigned int) intr);
854
855         wlan_janitor();
856
857 #undef HANDLER
858 }
859
860 static void wlan_check_hang(void)
861 {
862         struct dma_desc *desc;
863         unsigned int i;
864
865         for (i = 0; i < __AR9170_NUM_TX_QUEUES; i++) {
866                 if (queue_empty(&fw.wlan.tx_queue[i])) {
867                         /* Nothing to do here... move along */
868                         continue;
869                 }
870
871                 /* fetch the current DMA queue position */
872                 desc = get_wlan_txq_addr(i);
873
874                 /* Stuck frame detection */
875                 if (unlikely(desc == fw.wlan.last_tx_desc[i])) {
876                         fw.wlan.last_tx_desc_num[i]++;
877
878                         if (unlikely(fw.wlan.last_tx_desc_num[i] > 6)) {
879                                 /*
880                                  * schedule MAC reset (aka OFF/ON => dead)
881                                  *
882                                  * This will almost certainly kill
883                                  * the device for good, but it's the
884                                  * recommended thing to do...
885                                  */
886
887                                 fw.wlan.mac_reset++;
888                         }
889
890 #ifdef CONFIG_CARL9170FW_DEBUG
891                         if (unlikely(fw.wlan.last_tx_desc_num[i] > 5)) {
892                                 /*
893                                  * Sigh, the queue is almost certainly
894                                  * dead. Dump the queue content to the
895                                  * user, maybe we find out why it got
896                                  * so stuck.
897                                  */
898
899                                 wlan_dump_queue(i);
900                         }
901 #endif /* CONFIG_CARL9170FW_DEBUG */
902
903                         if (unlikely(fw.wlan.last_tx_desc_num[i] > 3)) {
904                                 /*
905                                  * Hrrm, bump the queue a bit.
906                                  * maybe this will get it going again.
907                                  */
908
909                                 wlan_dma_bump(i);
910                         }
911                 } else {
912                         /* Nothing stuck */
913                         fw.wlan.last_tx_desc[i] = desc;
914                         fw.wlan.last_tx_desc_num[i] = 0;
915                 }
916         }
917 }
918
919 /*
920  * NB: Resetting the MAC is a two-edged sword.
921  * On most occasions, it does what it is supposed to do.
922  * But there is a chance that this will make it
923  * even worse and the radio dies silently.
924  */
925 static void wlan_mac_reset(void)
926 {
927         uint32_t val;
928         uint32_t agg_wait_counter;
929         uint32_t agg_density;
930         uint32_t bcn_start_addr;
931         uint32_t rctl, rcth;
932         uint32_t cam_mode;
933         uint32_t ack_power;
934         uint32_t rts_cts_tpc;
935         unsigned int i;
936
937 #ifdef CONFIG_CARL9170FW_RADIO_FUNCTIONS
938         uint32_t rx_BB;
939 #endif /* CONFIG_CARL9170FW_RADIO_FUNCTIONS */
940
941         ERR("MAC RESET");
942
943         /* Save aggregation parameters */
944         agg_wait_counter = get(AR9170_MAC_REG_AMPDU_FACTOR);
945         agg_density = get(AR9170_MAC_REG_AMPDU_DENSITY);
946
947         bcn_start_addr = get(AR9170_MAC_REG_BCN_ADDR);
948
949         cam_mode = get(AR9170_MAC_REG_CAM_MODE);
950         rctl = get(AR9170_MAC_REG_CAM_ROLL_CALL_TBL_L);
951         rcth = get(AR9170_MAC_REG_CAM_ROLL_CALL_TBL_H);
952
953         ack_power = get(AR9170_MAC_REG_ACK_TPC);
954         rts_cts_tpc = get(AR9170_MAC_REG_RTS_CTS_TPC);
955
956 #ifdef CONFIG_CARL9170FW_RADIO_FUNCTIONS
957         /* 0x1c8960 write only */
958         rx_BB = get(AR9170_PHY_REG_SWITCH_CHAIN_0);
959 #endif /* CONFIG_CARL9170FW_RADIO_FUNCTIONS */
960
961         /* TX/RX must be stopped by now */
962         val = get(AR9170_MAC_REG_POWER_STATE_CTRL);
963
964         val |= AR9170_MAC_POWER_STATE_CTRL_RESET;
965
966         /*
967          * Manipulate CCA threshold to stop transmission
968          *
969          * set(AR9170_PHY_REG_CCA_THRESHOLD, 0x300);
970          */
971
972         /*
973          * check Rx state in 0(idle) 9(disable)
974          *
975          * chState = (get(AR9170_MAC_REG_MISC_684) >> 16) & 0xf;
976          * while( (chState != 0) && (chState != 9)) {
977          *      chState = (get(AR9170_MAC_REG_MISC_684) >> 16) & 0xf;
978          * }
979          */
980
981         set(AR9170_MAC_REG_POWER_STATE_CTRL, val);
982
983         delay(2);
984
985         /* Restore aggregation parameters */
986         set(AR9170_MAC_REG_AMPDU_FACTOR, agg_wait_counter);
987         set(AR9170_MAC_REG_AMPDU_DENSITY, agg_density);
988
989         set(AR9170_MAC_REG_BCN_ADDR, bcn_start_addr);
990         set(AR9170_MAC_REG_CAM_MODE, cam_mode);
991         set(AR9170_MAC_REG_CAM_ROLL_CALL_TBL_L, rctl);
992         set(AR9170_MAC_REG_CAM_ROLL_CALL_TBL_H, rcth);
993
994         set(AR9170_MAC_REG_RTS_CTS_TPC, rts_cts_tpc);
995         set(AR9170_MAC_REG_ACK_TPC, ack_power);
996
997 #ifdef CONFIG_CARL9170FW_RADIO_FUNCTIONS
998         set(AR9170_PHY_REG_SWITCH_CHAIN_2, rx_BB);
999 #endif /* CONFIG_CARL9170FW_RADIO_FUNCTIONS */
1000
1001         /*
1002          * Manipulate CCA threshold to resume transmission
1003          *
1004          * set(AR9170_PHY_REG_CCA_THRESHOLD, 0x0);
1005          */
1006
1007         for (i = 0; i < __AR9170_NUM_TX_QUEUES; i++) {
1008                 DBG("Q:%d l:%d h:%p t:%p\n", i, queue_len(&fw.wlan.tx_queue[i]),
1009                      fw.wlan.tx_queue[i].head, fw.wlan.tx_queue[i].terminator);
1010
1011                 set_wlan_txq_dma_addr(i, (uint32_t) fw.wlan.tx_queue[i].head);
1012
1013                 if (!queue_empty(&fw.wlan.tx_queue[i]))
1014                         wlan_trigger(BIT(i));
1015         }
1016
1017         handle_rx();
1018         set(AR9170_MAC_REG_DMA_RXQ_ADDR, (uint32_t) fw.wlan.rx_queue.head);
1019         wlan_trigger(AR9170_DMA_TRIGGER_RXQ);
1020 }
1021
1022 void __cold wlan_timer(void)
1023 {
1024         unsigned int cached_mac_reset;
1025
1026         cached_mac_reset = fw.wlan.mac_reset;
1027
1028         /* TX Queue Hang check */
1029         wlan_check_hang();
1030
1031         /* RX Overrun check */
1032         wlan_check_rx_overrun();
1033
1034         if (unlikely(fw.wlan.mac_reset >= CARL9170_MAC_RESET_RESET)) {
1035                 wlan_mac_reset();
1036                 fw.wlan.mac_reset = CARL9170_MAC_RESET_OFF;
1037         } else {
1038                 if (fw.wlan.mac_reset && cached_mac_reset == fw.wlan.mac_reset)
1039                         fw.wlan.mac_reset--;
1040         }
1041 }