xref: /freebsd/sys/dev/ath/if_ath_tx.c (revision 09a53ad8f1318c5daae6cfb19d97f4f6459f0013)
1 /*-
2  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3  * Copyright (c) 2010-2012 Adrian Chadd, Xenion Pty Ltd
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer,
11  *    without modification.
12  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
13  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
14  *    redistribution must be conditioned upon including a substantially
15  *    similar Disclaimer requirement for further binary redistribution.
16  *
17  * NO WARRANTY
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
21  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
23  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
26  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
28  * THE POSSIBILITY OF SUCH DAMAGES.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 /*
35  * Driver for the Atheros Wireless LAN controller.
36  *
37  * This software is derived from work of Atsushi Onoe; his contribution
38  * is greatly appreciated.
39  */
40 
41 #include "opt_inet.h"
42 #include "opt_ath.h"
43 #include "opt_wlan.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/sysctl.h>
48 #include <sys/mbuf.h>
49 #include <sys/malloc.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/kernel.h>
53 #include <sys/socket.h>
54 #include <sys/sockio.h>
55 #include <sys/errno.h>
56 #include <sys/callout.h>
57 #include <sys/bus.h>
58 #include <sys/endian.h>
59 #include <sys/kthread.h>
60 #include <sys/taskqueue.h>
61 #include <sys/priv.h>
62 #include <sys/ktr.h>
63 
64 #include <machine/bus.h>
65 
66 #include <net/if.h>
67 #include <net/if_var.h>
68 #include <net/if_dl.h>
69 #include <net/if_media.h>
70 #include <net/if_types.h>
71 #include <net/if_arp.h>
72 #include <net/ethernet.h>
73 #include <net/if_llc.h>
74 
75 #include <net80211/ieee80211_var.h>
76 #include <net80211/ieee80211_regdomain.h>
77 #ifdef IEEE80211_SUPPORT_SUPERG
78 #include <net80211/ieee80211_superg.h>
79 #endif
80 #ifdef IEEE80211_SUPPORT_TDMA
81 #include <net80211/ieee80211_tdma.h>
82 #endif
83 #include <net80211/ieee80211_ht.h>
84 
85 #include <net/bpf.h>
86 
87 #ifdef INET
88 #include <netinet/in.h>
89 #include <netinet/if_ether.h>
90 #endif
91 
92 #include <dev/ath/if_athvar.h>
93 #include <dev/ath/ath_hal/ah_devid.h>		/* XXX for softled */
94 #include <dev/ath/ath_hal/ah_diagcodes.h>
95 
96 #include <dev/ath/if_ath_debug.h>
97 
98 #ifdef ATH_TX99_DIAG
99 #include <dev/ath/ath_tx99/ath_tx99.h>
100 #endif
101 
102 #include <dev/ath/if_ath_misc.h>
103 #include <dev/ath/if_ath_tx.h>
104 #include <dev/ath/if_ath_tx_ht.h>
105 
106 #ifdef	ATH_DEBUG_ALQ
107 #include <dev/ath/if_ath_alq.h>
108 #endif
109 
110 /*
111  * How many retries to perform in software
112  */
113 #define	SWMAX_RETRIES		10
114 
115 /*
116  * What queue to throw the non-QoS TID traffic into
117  */
118 #define	ATH_NONQOS_TID_AC	WME_AC_VO
119 
120 #if 0
121 static int ath_tx_node_is_asleep(struct ath_softc *sc, struct ath_node *an);
122 #endif
123 static int ath_tx_ampdu_pending(struct ath_softc *sc, struct ath_node *an,
124     int tid);
125 static int ath_tx_ampdu_running(struct ath_softc *sc, struct ath_node *an,
126     int tid);
127 static ieee80211_seq ath_tx_tid_seqno_assign(struct ath_softc *sc,
128     struct ieee80211_node *ni, struct ath_buf *bf, struct mbuf *m0);
129 static int ath_tx_action_frame_override_queue(struct ath_softc *sc,
130     struct ieee80211_node *ni, struct mbuf *m0, int *tid);
131 static struct ath_buf *
132 ath_tx_retry_clone(struct ath_softc *sc, struct ath_node *an,
133     struct ath_tid *tid, struct ath_buf *bf);
134 
135 #ifdef	ATH_DEBUG_ALQ
136 void
137 ath_tx_alq_post(struct ath_softc *sc, struct ath_buf *bf_first)
138 {
139 	struct ath_buf *bf;
140 	int i, n;
141 	const char *ds;
142 
143 	/* XXX we should skip out early if debugging isn't enabled! */
144 	bf = bf_first;
145 
146 	while (bf != NULL) {
147 		/* XXX should ensure bf_nseg > 0! */
148 		if (bf->bf_nseg == 0)
149 			break;
150 		n = ((bf->bf_nseg - 1) / sc->sc_tx_nmaps) + 1;
151 		for (i = 0, ds = (const char *) bf->bf_desc;
152 		    i < n;
153 		    i++, ds += sc->sc_tx_desclen) {
154 			if_ath_alq_post(&sc->sc_alq,
155 			    ATH_ALQ_EDMA_TXDESC,
156 			    sc->sc_tx_desclen,
157 			    ds);
158 		}
159 		bf = bf->bf_next;
160 	}
161 }
162 #endif /* ATH_DEBUG_ALQ */
163 
164 /*
165  * Whether to use the 11n rate scenario functions or not
166  */
167 static inline int
168 ath_tx_is_11n(struct ath_softc *sc)
169 {
170 	return ((sc->sc_ah->ah_magic == 0x20065416) ||
171 		    (sc->sc_ah->ah_magic == 0x19741014));
172 }
173 
174 /*
175  * Obtain the current TID from the given frame.
176  *
177  * Non-QoS frames need to go into TID 16 (IEEE80211_NONQOS_TID.)
178  * This has implications for which AC/priority the packet is placed
179  * in.
180  */
181 static int
182 ath_tx_gettid(struct ath_softc *sc, const struct mbuf *m0)
183 {
184 	const struct ieee80211_frame *wh;
185 	int pri = M_WME_GETAC(m0);
186 
187 	wh = mtod(m0, const struct ieee80211_frame *);
188 	if (! IEEE80211_QOS_HAS_SEQ(wh))
189 		return IEEE80211_NONQOS_TID;
190 	else
191 		return WME_AC_TO_TID(pri);
192 }
193 
194 static void
195 ath_tx_set_retry(struct ath_softc *sc, struct ath_buf *bf)
196 {
197 	struct ieee80211_frame *wh;
198 
199 	wh = mtod(bf->bf_m, struct ieee80211_frame *);
200 	/* Only update/resync if needed */
201 	if (bf->bf_state.bfs_isretried == 0) {
202 		wh->i_fc[1] |= IEEE80211_FC1_RETRY;
203 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
204 		    BUS_DMASYNC_PREWRITE);
205 	}
206 	bf->bf_state.bfs_isretried = 1;
207 	bf->bf_state.bfs_retries ++;
208 }
209 
210 /*
211  * Determine what the correct AC queue for the given frame
212  * should be.
213  *
214  * This code assumes that the TIDs map consistently to
215  * the underlying hardware (or software) ath_txq.
216  * Since the sender may try to set an AC which is
217  * arbitrary, non-QoS TIDs may end up being put on
218  * completely different ACs. There's no way to put a
219  * TID into multiple ath_txq's for scheduling, so
220  * for now we override the AC/TXQ selection and set
221  * non-QOS TID frames into the BE queue.
222  *
223  * This may be completely incorrect - specifically,
224  * some management frames may end up out of order
225  * compared to the QoS traffic they're controlling.
226  * I'll look into this later.
227  */
228 static int
229 ath_tx_getac(struct ath_softc *sc, const struct mbuf *m0)
230 {
231 	const struct ieee80211_frame *wh;
232 	int pri = M_WME_GETAC(m0);
233 	wh = mtod(m0, const struct ieee80211_frame *);
234 	if (IEEE80211_QOS_HAS_SEQ(wh))
235 		return pri;
236 
237 	return ATH_NONQOS_TID_AC;
238 }
239 
240 void
241 ath_txfrag_cleanup(struct ath_softc *sc,
242 	ath_bufhead *frags, struct ieee80211_node *ni)
243 {
244 	struct ath_buf *bf, *next;
245 
246 	ATH_TXBUF_LOCK_ASSERT(sc);
247 
248 	TAILQ_FOREACH_SAFE(bf, frags, bf_list, next) {
249 		/* NB: bf assumed clean */
250 		TAILQ_REMOVE(frags, bf, bf_list);
251 		ath_returnbuf_head(sc, bf);
252 		ieee80211_node_decref(ni);
253 	}
254 }
255 
256 /*
257  * Setup xmit of a fragmented frame.  Allocate a buffer
258  * for each frag and bump the node reference count to
259  * reflect the held reference to be setup by ath_tx_start.
260  */
261 int
262 ath_txfrag_setup(struct ath_softc *sc, ath_bufhead *frags,
263 	struct mbuf *m0, struct ieee80211_node *ni)
264 {
265 	struct mbuf *m;
266 	struct ath_buf *bf;
267 
268 	ATH_TXBUF_LOCK(sc);
269 	for (m = m0->m_nextpkt; m != NULL; m = m->m_nextpkt) {
270 		/* XXX non-management? */
271 		bf = _ath_getbuf_locked(sc, ATH_BUFTYPE_NORMAL);
272 		if (bf == NULL) {	/* out of buffers, cleanup */
273 			DPRINTF(sc, ATH_DEBUG_XMIT, "%s: no buffer?\n",
274 			    __func__);
275 			ath_txfrag_cleanup(sc, frags, ni);
276 			break;
277 		}
278 		ieee80211_node_incref(ni);
279 		TAILQ_INSERT_TAIL(frags, bf, bf_list);
280 	}
281 	ATH_TXBUF_UNLOCK(sc);
282 
283 	return !TAILQ_EMPTY(frags);
284 }
285 
286 static int
287 ath_tx_dmasetup(struct ath_softc *sc, struct ath_buf *bf, struct mbuf *m0)
288 {
289 	struct mbuf *m;
290 	int error;
291 
292 	/*
293 	 * Load the DMA map so any coalescing is done.  This
294 	 * also calculates the number of descriptors we need.
295 	 */
296 	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
297 				     bf->bf_segs, &bf->bf_nseg,
298 				     BUS_DMA_NOWAIT);
299 	if (error == EFBIG) {
300 		/* XXX packet requires too many descriptors */
301 		bf->bf_nseg = ATH_MAX_SCATTER + 1;
302 	} else if (error != 0) {
303 		sc->sc_stats.ast_tx_busdma++;
304 		ieee80211_free_mbuf(m0);
305 		return error;
306 	}
307 	/*
308 	 * Discard null packets and check for packets that
309 	 * require too many TX descriptors.  We try to convert
310 	 * the latter to a cluster.
311 	 */
312 	if (bf->bf_nseg > ATH_MAX_SCATTER) {		/* too many desc's, linearize */
313 		sc->sc_stats.ast_tx_linear++;
314 		m = m_collapse(m0, M_NOWAIT, ATH_MAX_SCATTER);
315 		if (m == NULL) {
316 			ieee80211_free_mbuf(m0);
317 			sc->sc_stats.ast_tx_nombuf++;
318 			return ENOMEM;
319 		}
320 		m0 = m;
321 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
322 					     bf->bf_segs, &bf->bf_nseg,
323 					     BUS_DMA_NOWAIT);
324 		if (error != 0) {
325 			sc->sc_stats.ast_tx_busdma++;
326 			ieee80211_free_mbuf(m0);
327 			return error;
328 		}
329 		KASSERT(bf->bf_nseg <= ATH_MAX_SCATTER,
330 		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
331 	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
332 		sc->sc_stats.ast_tx_nodata++;
333 		ieee80211_free_mbuf(m0);
334 		return EIO;
335 	}
336 	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n",
337 		__func__, m0, m0->m_pkthdr.len);
338 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
339 	bf->bf_m = m0;
340 
341 	return 0;
342 }
343 
344 /*
345  * Chain together segments+descriptors for a frame - 11n or otherwise.
346  *
347  * For aggregates, this is called on each frame in the aggregate.
348  */
349 static void
350 ath_tx_chaindesclist(struct ath_softc *sc, struct ath_desc *ds0,
351     struct ath_buf *bf, int is_aggr, int is_first_subframe,
352     int is_last_subframe)
353 {
354 	struct ath_hal *ah = sc->sc_ah;
355 	char *ds;
356 	int i, bp, dsp;
357 	HAL_DMA_ADDR bufAddrList[4];
358 	uint32_t segLenList[4];
359 	int numTxMaps = 1;
360 	int isFirstDesc = 1;
361 
362 	/*
363 	 * XXX There's txdma and txdma_mgmt; the descriptor
364 	 * sizes must match.
365 	 */
366 	struct ath_descdma *dd = &sc->sc_txdma;
367 
368 	/*
369 	 * Fillin the remainder of the descriptor info.
370 	 */
371 
372 	/*
373 	 * We need the number of TX data pointers in each descriptor.
374 	 * EDMA and later chips support 4 TX buffers per descriptor;
375 	 * previous chips just support one.
376 	 */
377 	numTxMaps = sc->sc_tx_nmaps;
378 
379 	/*
380 	 * For EDMA and later chips ensure the TX map is fully populated
381 	 * before advancing to the next descriptor.
382 	 */
383 	ds = (char *) bf->bf_desc;
384 	bp = dsp = 0;
385 	bzero(bufAddrList, sizeof(bufAddrList));
386 	bzero(segLenList, sizeof(segLenList));
387 	for (i = 0; i < bf->bf_nseg; i++) {
388 		bufAddrList[bp] = bf->bf_segs[i].ds_addr;
389 		segLenList[bp] = bf->bf_segs[i].ds_len;
390 		bp++;
391 
392 		/*
393 		 * Go to the next segment if this isn't the last segment
394 		 * and there's space in the current TX map.
395 		 */
396 		if ((i != bf->bf_nseg - 1) && (bp < numTxMaps))
397 			continue;
398 
399 		/*
400 		 * Last segment or we're out of buffer pointers.
401 		 */
402 		bp = 0;
403 
404 		if (i == bf->bf_nseg - 1)
405 			ath_hal_settxdesclink(ah, (struct ath_desc *) ds, 0);
406 		else
407 			ath_hal_settxdesclink(ah, (struct ath_desc *) ds,
408 			    bf->bf_daddr + dd->dd_descsize * (dsp + 1));
409 
410 		/*
411 		 * XXX This assumes that bfs_txq is the actual destination
412 		 * hardware queue at this point.  It may not have been
413 		 * assigned, it may actually be pointing to the multicast
414 		 * software TXQ id.  These must be fixed!
415 		 */
416 		ath_hal_filltxdesc(ah, (struct ath_desc *) ds
417 			, bufAddrList
418 			, segLenList
419 			, bf->bf_descid		/* XXX desc id */
420 			, bf->bf_state.bfs_tx_queue
421 			, isFirstDesc		/* first segment */
422 			, i == bf->bf_nseg - 1	/* last segment */
423 			, (struct ath_desc *) ds0	/* first descriptor */
424 		);
425 
426 		/*
427 		 * Make sure the 11n aggregate fields are cleared.
428 		 *
429 		 * XXX TODO: this doesn't need to be called for
430 		 * aggregate frames; as it'll be called on all
431 		 * sub-frames.  Since the descriptors are in
432 		 * non-cacheable memory, this leads to some
433 		 * rather slow writes on MIPS/ARM platforms.
434 		 */
435 		if (ath_tx_is_11n(sc))
436 			ath_hal_clr11n_aggr(sc->sc_ah, (struct ath_desc *) ds);
437 
438 		/*
439 		 * If 11n is enabled, set it up as if it's an aggregate
440 		 * frame.
441 		 */
442 		if (is_last_subframe) {
443 			ath_hal_set11n_aggr_last(sc->sc_ah,
444 			    (struct ath_desc *) ds);
445 		} else if (is_aggr) {
446 			/*
447 			 * This clears the aggrlen field; so
448 			 * the caller needs to call set_aggr_first()!
449 			 *
450 			 * XXX TODO: don't call this for the first
451 			 * descriptor in the first frame in an
452 			 * aggregate!
453 			 */
454 			ath_hal_set11n_aggr_middle(sc->sc_ah,
455 			    (struct ath_desc *) ds,
456 			    bf->bf_state.bfs_ndelim);
457 		}
458 		isFirstDesc = 0;
459 		bf->bf_lastds = (struct ath_desc *) ds;
460 
461 		/*
462 		 * Don't forget to skip to the next descriptor.
463 		 */
464 		ds += sc->sc_tx_desclen;
465 		dsp++;
466 
467 		/*
468 		 * .. and don't forget to blank these out!
469 		 */
470 		bzero(bufAddrList, sizeof(bufAddrList));
471 		bzero(segLenList, sizeof(segLenList));
472 	}
473 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
474 }
475 
476 /*
477  * Set the rate control fields in the given descriptor based on
478  * the bf_state fields and node state.
479  *
480  * The bfs fields should already be set with the relevant rate
481  * control information, including whether MRR is to be enabled.
482  *
483  * Since the FreeBSD HAL currently sets up the first TX rate
484  * in ath_hal_setuptxdesc(), this will setup the MRR
485  * conditionally for the pre-11n chips, and call ath_buf_set_rate
486  * unconditionally for 11n chips. These require the 11n rate
487  * scenario to be set if MCS rates are enabled, so it's easier
488  * to just always call it. The caller can then only set rates 2, 3
489  * and 4 if multi-rate retry is needed.
490  */
491 static void
492 ath_tx_set_ratectrl(struct ath_softc *sc, struct ieee80211_node *ni,
493     struct ath_buf *bf)
494 {
495 	struct ath_rc_series *rc = bf->bf_state.bfs_rc;
496 
497 	/* If mrr is disabled, blank tries 1, 2, 3 */
498 	if (! bf->bf_state.bfs_ismrr)
499 		rc[1].tries = rc[2].tries = rc[3].tries = 0;
500 
501 #if 0
502 	/*
503 	 * If NOACK is set, just set ntries=1.
504 	 */
505 	else if (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) {
506 		rc[1].tries = rc[2].tries = rc[3].tries = 0;
507 		rc[0].tries = 1;
508 	}
509 #endif
510 
511 	/*
512 	 * Always call - that way a retried descriptor will
513 	 * have the MRR fields overwritten.
514 	 *
515 	 * XXX TODO: see if this is really needed - setting up
516 	 * the first descriptor should set the MRR fields to 0
517 	 * for us anyway.
518 	 */
519 	if (ath_tx_is_11n(sc)) {
520 		ath_buf_set_rate(sc, ni, bf);
521 	} else {
522 		ath_hal_setupxtxdesc(sc->sc_ah, bf->bf_desc
523 			, rc[1].ratecode, rc[1].tries
524 			, rc[2].ratecode, rc[2].tries
525 			, rc[3].ratecode, rc[3].tries
526 		);
527 	}
528 }
529 
530 /*
531  * Setup segments+descriptors for an 11n aggregate.
532  * bf_first is the first buffer in the aggregate.
533  * The descriptor list must already been linked together using
534  * bf->bf_next.
535  */
536 static void
537 ath_tx_setds_11n(struct ath_softc *sc, struct ath_buf *bf_first)
538 {
539 	struct ath_buf *bf, *bf_prev = NULL;
540 	struct ath_desc *ds0 = bf_first->bf_desc;
541 
542 	DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: nframes=%d, al=%d\n",
543 	    __func__, bf_first->bf_state.bfs_nframes,
544 	    bf_first->bf_state.bfs_al);
545 
546 	bf = bf_first;
547 
548 	if (bf->bf_state.bfs_txrate0 == 0)
549 		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: bf=%p, txrate0=%d\n",
550 		    __func__, bf, 0);
551 	if (bf->bf_state.bfs_rc[0].ratecode == 0)
552 		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: bf=%p, rix0=%d\n",
553 		    __func__, bf, 0);
554 
555 	/*
556 	 * Setup all descriptors of all subframes - this will
557 	 * call ath_hal_set11naggrmiddle() on every frame.
558 	 */
559 	while (bf != NULL) {
560 		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
561 		    "%s: bf=%p, nseg=%d, pktlen=%d, seqno=%d\n",
562 		    __func__, bf, bf->bf_nseg, bf->bf_state.bfs_pktlen,
563 		    SEQNO(bf->bf_state.bfs_seqno));
564 
565 		/*
566 		 * Setup the initial fields for the first descriptor - all
567 		 * the non-11n specific stuff.
568 		 */
569 		ath_hal_setuptxdesc(sc->sc_ah, bf->bf_desc
570 			, bf->bf_state.bfs_pktlen	/* packet length */
571 			, bf->bf_state.bfs_hdrlen	/* header length */
572 			, bf->bf_state.bfs_atype	/* Atheros packet type */
573 			, bf->bf_state.bfs_txpower	/* txpower */
574 			, bf->bf_state.bfs_txrate0
575 			, bf->bf_state.bfs_try0		/* series 0 rate/tries */
576 			, bf->bf_state.bfs_keyix	/* key cache index */
577 			, bf->bf_state.bfs_txantenna	/* antenna mode */
578 			, bf->bf_state.bfs_txflags | HAL_TXDESC_INTREQ	/* flags */
579 			, bf->bf_state.bfs_ctsrate	/* rts/cts rate */
580 			, bf->bf_state.bfs_ctsduration	/* rts/cts duration */
581 		);
582 
583 		/*
584 		 * First descriptor? Setup the rate control and initial
585 		 * aggregate header information.
586 		 */
587 		if (bf == bf_first) {
588 			/*
589 			 * setup first desc with rate and aggr info
590 			 */
591 			ath_tx_set_ratectrl(sc, bf->bf_node, bf);
592 		}
593 
594 		/*
595 		 * Setup the descriptors for a multi-descriptor frame.
596 		 * This is both aggregate and non-aggregate aware.
597 		 */
598 		ath_tx_chaindesclist(sc, ds0, bf,
599 		    1, /* is_aggr */
600 		    !! (bf == bf_first), /* is_first_subframe */
601 		    !! (bf->bf_next == NULL) /* is_last_subframe */
602 		    );
603 
604 		if (bf == bf_first) {
605 			/*
606 			 * Initialise the first 11n aggregate with the
607 			 * aggregate length and aggregate enable bits.
608 			 */
609 			ath_hal_set11n_aggr_first(sc->sc_ah,
610 			    ds0,
611 			    bf->bf_state.bfs_al,
612 			    bf->bf_state.bfs_ndelim);
613 		}
614 
615 		/*
616 		 * Link the last descriptor of the previous frame
617 		 * to the beginning descriptor of this frame.
618 		 */
619 		if (bf_prev != NULL)
620 			ath_hal_settxdesclink(sc->sc_ah, bf_prev->bf_lastds,
621 			    bf->bf_daddr);
622 
623 		/* Save a copy so we can link the next descriptor in */
624 		bf_prev = bf;
625 		bf = bf->bf_next;
626 	}
627 
628 	/*
629 	 * Set the first descriptor bf_lastds field to point to
630 	 * the last descriptor in the last subframe, that's where
631 	 * the status update will occur.
632 	 */
633 	bf_first->bf_lastds = bf_prev->bf_lastds;
634 
635 	/*
636 	 * And bf_last in the first descriptor points to the end of
637 	 * the aggregate list.
638 	 */
639 	bf_first->bf_last = bf_prev;
640 
641 	/*
642 	 * For non-AR9300 NICs, which require the rate control
643 	 * in the final descriptor - let's set that up now.
644 	 *
645 	 * This is because the filltxdesc() HAL call doesn't
646 	 * populate the last segment with rate control information
647 	 * if firstSeg is also true.  For non-aggregate frames
648 	 * that is fine, as the first frame already has rate control
649 	 * info.  But if the last frame in an aggregate has one
650 	 * descriptor, both firstseg and lastseg will be true and
651 	 * the rate info isn't copied.
652 	 *
653 	 * This is inefficient on MIPS/ARM platforms that have
654 	 * non-cachable memory for TX descriptors, but we'll just
655 	 * make do for now.
656 	 *
657 	 * As to why the rate table is stashed in the last descriptor
658 	 * rather than the first descriptor?  Because proctxdesc()
659 	 * is called on the final descriptor in an MPDU or A-MPDU -
660 	 * ie, the one that gets updated by the hardware upon
661 	 * completion.  That way proctxdesc() doesn't need to know
662 	 * about the first _and_ last TX descriptor.
663 	 */
664 	ath_hal_setuplasttxdesc(sc->sc_ah, bf_prev->bf_lastds, ds0);
665 
666 	DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: end\n", __func__);
667 }
668 
669 /*
670  * Hand-off a frame to the multicast TX queue.
671  *
672  * This is a software TXQ which will be appended to the CAB queue
673  * during the beacon setup code.
674  *
675  * XXX TODO: since the AR9300 EDMA TX queue support wants the QCU ID
676  * as part of the TX descriptor, bf_state.bfs_tx_queue must be updated
677  * with the actual hardware txq, or all of this will fall apart.
678  *
679  * XXX It may not be a bad idea to just stuff the QCU ID into bf_state
680  * and retire bfs_tx_queue; then make sure the CABQ QCU ID is populated
681  * correctly.
682  */
683 static void
684 ath_tx_handoff_mcast(struct ath_softc *sc, struct ath_txq *txq,
685     struct ath_buf *bf)
686 {
687 	ATH_TX_LOCK_ASSERT(sc);
688 
689 	KASSERT((bf->bf_flags & ATH_BUF_BUSY) == 0,
690 	     ("%s: busy status 0x%x", __func__, bf->bf_flags));
691 
692 	/*
693 	 * Ensure that the tx queue is the cabq, so things get
694 	 * mapped correctly.
695 	 */
696 	if (bf->bf_state.bfs_tx_queue != sc->sc_cabq->axq_qnum) {
697 		DPRINTF(sc, ATH_DEBUG_XMIT,
698 		    "%s: bf=%p, bfs_tx_queue=%d, axq_qnum=%d\n",
699 		    __func__, bf, bf->bf_state.bfs_tx_queue,
700 		    txq->axq_qnum);
701 	}
702 
703 	ATH_TXQ_LOCK(txq);
704 	if (ATH_TXQ_LAST(txq, axq_q_s) != NULL) {
705 		struct ath_buf *bf_last = ATH_TXQ_LAST(txq, axq_q_s);
706 		struct ieee80211_frame *wh;
707 
708 		/* mark previous frame */
709 		wh = mtod(bf_last->bf_m, struct ieee80211_frame *);
710 		wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
711 		bus_dmamap_sync(sc->sc_dmat, bf_last->bf_dmamap,
712 		    BUS_DMASYNC_PREWRITE);
713 
714 		/* link descriptor */
715 		ath_hal_settxdesclink(sc->sc_ah,
716 		    bf_last->bf_lastds,
717 		    bf->bf_daddr);
718 	}
719 	ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
720 	ATH_TXQ_UNLOCK(txq);
721 }
722 
723 /*
724  * Hand-off packet to a hardware queue.
725  */
726 static void
727 ath_tx_handoff_hw(struct ath_softc *sc, struct ath_txq *txq,
728     struct ath_buf *bf)
729 {
730 	struct ath_hal *ah = sc->sc_ah;
731 	struct ath_buf *bf_first;
732 
733 	/*
734 	 * Insert the frame on the outbound list and pass it on
735 	 * to the hardware.  Multicast frames buffered for power
736 	 * save stations and transmit from the CAB queue are stored
737 	 * on a s/w only queue and loaded on to the CAB queue in
738 	 * the SWBA handler since frames only go out on DTIM and
739 	 * to avoid possible races.
740 	 */
741 	ATH_TX_LOCK_ASSERT(sc);
742 	KASSERT((bf->bf_flags & ATH_BUF_BUSY) == 0,
743 	     ("%s: busy status 0x%x", __func__, bf->bf_flags));
744 	KASSERT(txq->axq_qnum != ATH_TXQ_SWQ,
745 	     ("ath_tx_handoff_hw called for mcast queue"));
746 
747 	/*
748 	 * XXX We should instead just verify that sc_txstart_cnt
749 	 * or ath_txproc_cnt > 0.  That would mean that
750 	 * the reset is going to be waiting for us to complete.
751 	 */
752 	if (sc->sc_txproc_cnt == 0 && sc->sc_txstart_cnt == 0) {
753 		device_printf(sc->sc_dev,
754 		    "%s: TX dispatch without holding txcount/txstart refcnt!\n",
755 		    __func__);
756 	}
757 
758 	/*
759 	 * XXX .. this is going to cause the hardware to get upset;
760 	 * so we really should find some way to drop or queue
761 	 * things.
762 	 */
763 
764 	ATH_TXQ_LOCK(txq);
765 
766 	/*
767 	 * XXX TODO: if there's a holdingbf, then
768 	 * ATH_TXQ_PUTRUNNING should be clear.
769 	 *
770 	 * If there is a holdingbf and the list is empty,
771 	 * then axq_link should be pointing to the holdingbf.
772 	 *
773 	 * Otherwise it should point to the last descriptor
774 	 * in the last ath_buf.
775 	 *
776 	 * In any case, we should really ensure that we
777 	 * update the previous descriptor link pointer to
778 	 * this descriptor, regardless of all of the above state.
779 	 *
780 	 * For now this is captured by having axq_link point
781 	 * to either the holdingbf (if the TXQ list is empty)
782 	 * or the end of the list (if the TXQ list isn't empty.)
783 	 * I'd rather just kill axq_link here and do it as above.
784 	 */
785 
786 	/*
787 	 * Append the frame to the TX queue.
788 	 */
789 	ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
790 	ATH_KTR(sc, ATH_KTR_TX, 3,
791 	    "ath_tx_handoff: non-tdma: txq=%u, add bf=%p "
792 	    "depth=%d",
793 	    txq->axq_qnum,
794 	    bf,
795 	    txq->axq_depth);
796 
797 	/*
798 	 * If there's a link pointer, update it.
799 	 *
800 	 * XXX we should replace this with the above logic, just
801 	 * to kill axq_link with fire.
802 	 */
803 	if (txq->axq_link != NULL) {
804 		*txq->axq_link = bf->bf_daddr;
805 		DPRINTF(sc, ATH_DEBUG_XMIT,
806 		    "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
807 		    txq->axq_qnum, txq->axq_link,
808 		    (caddr_t)bf->bf_daddr, bf->bf_desc,
809 		    txq->axq_depth);
810 		ATH_KTR(sc, ATH_KTR_TX, 5,
811 		    "ath_tx_handoff: non-tdma: link[%u](%p)=%p (%p) "
812 		    "lastds=%d",
813 		    txq->axq_qnum, txq->axq_link,
814 		    (caddr_t)bf->bf_daddr, bf->bf_desc,
815 		    bf->bf_lastds);
816 	}
817 
818 	/*
819 	 * If we've not pushed anything into the hardware yet,
820 	 * push the head of the queue into the TxDP.
821 	 *
822 	 * Once we've started DMA, there's no guarantee that
823 	 * updating the TxDP with a new value will actually work.
824 	 * So we just don't do that - if we hit the end of the list,
825 	 * we keep that buffer around (the "holding buffer") and
826 	 * re-start DMA by updating the link pointer of _that_
827 	 * descriptor and then restart DMA.
828 	 */
829 	if (! (txq->axq_flags & ATH_TXQ_PUTRUNNING)) {
830 		bf_first = TAILQ_FIRST(&txq->axq_q);
831 		txq->axq_flags |= ATH_TXQ_PUTRUNNING;
832 		ath_hal_puttxbuf(ah, txq->axq_qnum, bf_first->bf_daddr);
833 		DPRINTF(sc, ATH_DEBUG_XMIT,
834 		    "%s: TXDP[%u] = %p (%p) depth %d\n",
835 		    __func__, txq->axq_qnum,
836 		    (caddr_t)bf_first->bf_daddr, bf_first->bf_desc,
837 		    txq->axq_depth);
838 		ATH_KTR(sc, ATH_KTR_TX, 5,
839 		    "ath_tx_handoff: TXDP[%u] = %p (%p) "
840 		    "lastds=%p depth %d",
841 		    txq->axq_qnum,
842 		    (caddr_t)bf_first->bf_daddr, bf_first->bf_desc,
843 		    bf_first->bf_lastds,
844 		    txq->axq_depth);
845 	}
846 
847 	/*
848 	 * Ensure that the bf TXQ matches this TXQ, so later
849 	 * checking and holding buffer manipulation is sane.
850 	 */
851 	if (bf->bf_state.bfs_tx_queue != txq->axq_qnum) {
852 		DPRINTF(sc, ATH_DEBUG_XMIT,
853 		    "%s: bf=%p, bfs_tx_queue=%d, axq_qnum=%d\n",
854 		    __func__, bf, bf->bf_state.bfs_tx_queue,
855 		    txq->axq_qnum);
856 	}
857 
858 	/*
859 	 * Track aggregate queue depth.
860 	 */
861 	if (bf->bf_state.bfs_aggr)
862 		txq->axq_aggr_depth++;
863 
864 	/*
865 	 * Update the link pointer.
866 	 */
867 	ath_hal_gettxdesclinkptr(ah, bf->bf_lastds, &txq->axq_link);
868 
869 	/*
870 	 * Start DMA.
871 	 *
872 	 * If we wrote a TxDP above, DMA will start from here.
873 	 *
874 	 * If DMA is running, it'll do nothing.
875 	 *
876 	 * If the DMA engine hit the end of the QCU list (ie LINK=NULL,
877 	 * or VEOL) then it stops at the last transmitted write.
878 	 * We then append a new frame by updating the link pointer
879 	 * in that descriptor and then kick TxE here; it will re-read
880 	 * that last descriptor and find the new descriptor to transmit.
881 	 *
882 	 * This is why we keep the holding descriptor around.
883 	 */
884 	ath_hal_txstart(ah, txq->axq_qnum);
885 	ATH_TXQ_UNLOCK(txq);
886 	ATH_KTR(sc, ATH_KTR_TX, 1,
887 	    "ath_tx_handoff: txq=%u, txstart", txq->axq_qnum);
888 }
889 
890 /*
891  * Restart TX DMA for the given TXQ.
892  *
893  * This must be called whether the queue is empty or not.
894  */
895 static void
896 ath_legacy_tx_dma_restart(struct ath_softc *sc, struct ath_txq *txq)
897 {
898 	struct ath_buf *bf, *bf_last;
899 
900 	ATH_TXQ_LOCK_ASSERT(txq);
901 
902 	/* XXX make this ATH_TXQ_FIRST */
903 	bf = TAILQ_FIRST(&txq->axq_q);
904 	bf_last = ATH_TXQ_LAST(txq, axq_q_s);
905 
906 	if (bf == NULL)
907 		return;
908 
909 	DPRINTF(sc, ATH_DEBUG_RESET,
910 	    "%s: Q%d: bf=%p, bf_last=%p, daddr=0x%08x\n",
911 	    __func__,
912 	    txq->axq_qnum,
913 	    bf,
914 	    bf_last,
915 	    (uint32_t) bf->bf_daddr);
916 
917 #ifdef	ATH_DEBUG
918 	if (sc->sc_debug & ATH_DEBUG_RESET)
919 		ath_tx_dump(sc, txq);
920 #endif
921 
922 	/*
923 	 * This is called from a restart, so DMA is known to be
924 	 * completely stopped.
925 	 */
926 	KASSERT((!(txq->axq_flags & ATH_TXQ_PUTRUNNING)),
927 	    ("%s: Q%d: called with PUTRUNNING=1\n",
928 	    __func__,
929 	    txq->axq_qnum));
930 
931 	ath_hal_puttxbuf(sc->sc_ah, txq->axq_qnum, bf->bf_daddr);
932 	txq->axq_flags |= ATH_TXQ_PUTRUNNING;
933 
934 	ath_hal_gettxdesclinkptr(sc->sc_ah, bf_last->bf_lastds,
935 	    &txq->axq_link);
936 	ath_hal_txstart(sc->sc_ah, txq->axq_qnum);
937 }
938 
939 /*
940  * Hand off a packet to the hardware (or mcast queue.)
941  *
942  * The relevant hardware txq should be locked.
943  */
944 static void
945 ath_legacy_xmit_handoff(struct ath_softc *sc, struct ath_txq *txq,
946     struct ath_buf *bf)
947 {
948 	ATH_TX_LOCK_ASSERT(sc);
949 
950 #ifdef	ATH_DEBUG_ALQ
951 	if (if_ath_alq_checkdebug(&sc->sc_alq, ATH_ALQ_EDMA_TXDESC))
952 		ath_tx_alq_post(sc, bf);
953 #endif
954 
955 	if (txq->axq_qnum == ATH_TXQ_SWQ)
956 		ath_tx_handoff_mcast(sc, txq, bf);
957 	else
958 		ath_tx_handoff_hw(sc, txq, bf);
959 }
960 
961 static int
962 ath_tx_tag_crypto(struct ath_softc *sc, struct ieee80211_node *ni,
963     struct mbuf *m0, int iswep, int isfrag, int *hdrlen, int *pktlen,
964     int *keyix)
965 {
966 	DPRINTF(sc, ATH_DEBUG_XMIT,
967 	    "%s: hdrlen=%d, pktlen=%d, isfrag=%d, iswep=%d, m0=%p\n",
968 	    __func__,
969 	    *hdrlen,
970 	    *pktlen,
971 	    isfrag,
972 	    iswep,
973 	    m0);
974 
975 	if (iswep) {
976 		const struct ieee80211_cipher *cip;
977 		struct ieee80211_key *k;
978 
979 		/*
980 		 * Construct the 802.11 header+trailer for an encrypted
981 		 * frame. The only reason this can fail is because of an
982 		 * unknown or unsupported cipher/key type.
983 		 */
984 		k = ieee80211_crypto_encap(ni, m0);
985 		if (k == NULL) {
986 			/*
987 			 * This can happen when the key is yanked after the
988 			 * frame was queued.  Just discard the frame; the
989 			 * 802.11 layer counts failures and provides
990 			 * debugging/diagnostics.
991 			 */
992 			return (0);
993 		}
994 		/*
995 		 * Adjust the packet + header lengths for the crypto
996 		 * additions and calculate the h/w key index.  When
997 		 * a s/w mic is done the frame will have had any mic
998 		 * added to it prior to entry so m0->m_pkthdr.len will
999 		 * account for it. Otherwise we need to add it to the
1000 		 * packet length.
1001 		 */
1002 		cip = k->wk_cipher;
1003 		(*hdrlen) += cip->ic_header;
1004 		(*pktlen) += cip->ic_header + cip->ic_trailer;
1005 		/* NB: frags always have any TKIP MIC done in s/w */
1006 		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && !isfrag)
1007 			(*pktlen) += cip->ic_miclen;
1008 		(*keyix) = k->wk_keyix;
1009 	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
1010 		/*
1011 		 * Use station key cache slot, if assigned.
1012 		 */
1013 		(*keyix) = ni->ni_ucastkey.wk_keyix;
1014 		if ((*keyix) == IEEE80211_KEYIX_NONE)
1015 			(*keyix) = HAL_TXKEYIX_INVALID;
1016 	} else
1017 		(*keyix) = HAL_TXKEYIX_INVALID;
1018 
1019 	return (1);
1020 }
1021 
1022 /*
1023  * Calculate whether interoperability protection is required for
1024  * this frame.
1025  *
1026  * This requires the rate control information be filled in,
1027  * as the protection requirement depends upon the current
1028  * operating mode / PHY.
1029  */
1030 static void
1031 ath_tx_calc_protection(struct ath_softc *sc, struct ath_buf *bf)
1032 {
1033 	struct ieee80211_frame *wh;
1034 	uint8_t rix;
1035 	uint16_t flags;
1036 	int shortPreamble;
1037 	const HAL_RATE_TABLE *rt = sc->sc_currates;
1038 	struct ieee80211com *ic = &sc->sc_ic;
1039 
1040 	flags = bf->bf_state.bfs_txflags;
1041 	rix = bf->bf_state.bfs_rc[0].rix;
1042 	shortPreamble = bf->bf_state.bfs_shpream;
1043 	wh = mtod(bf->bf_m, struct ieee80211_frame *);
1044 
1045 	/* Disable frame protection for TOA probe frames */
1046 	if (bf->bf_flags & ATH_BUF_TOA_PROBE) {
1047 		/* XXX count */
1048 		flags &= ~(HAL_TXDESC_CTSENA | HAL_TXDESC_RTSENA);
1049 		bf->bf_state.bfs_doprot = 0;
1050 		goto finish;
1051 	}
1052 
1053 	/*
1054 	 * If 802.11g protection is enabled, determine whether
1055 	 * to use RTS/CTS or just CTS.  Note that this is only
1056 	 * done for OFDM unicast frames.
1057 	 */
1058 	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1059 	    rt->info[rix].phy == IEEE80211_T_OFDM &&
1060 	    (flags & HAL_TXDESC_NOACK) == 0) {
1061 		bf->bf_state.bfs_doprot = 1;
1062 		/* XXX fragments must use CCK rates w/ protection */
1063 		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS) {
1064 			flags |= HAL_TXDESC_RTSENA;
1065 		} else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY) {
1066 			flags |= HAL_TXDESC_CTSENA;
1067 		}
1068 		/*
1069 		 * For frags it would be desirable to use the
1070 		 * highest CCK rate for RTS/CTS.  But stations
1071 		 * farther away may detect it at a lower CCK rate
1072 		 * so use the configured protection rate instead
1073 		 * (for now).
1074 		 */
1075 		sc->sc_stats.ast_tx_protect++;
1076 	}
1077 
1078 	/*
1079 	 * If 11n protection is enabled and it's a HT frame,
1080 	 * enable RTS.
1081 	 *
1082 	 * XXX ic_htprotmode or ic_curhtprotmode?
1083 	 * XXX should it_htprotmode only matter if ic_curhtprotmode
1084 	 * XXX indicates it's not a HT pure environment?
1085 	 */
1086 	if ((ic->ic_htprotmode == IEEE80211_PROT_RTSCTS) &&
1087 	    rt->info[rix].phy == IEEE80211_T_HT &&
1088 	    (flags & HAL_TXDESC_NOACK) == 0) {
1089 		flags |= HAL_TXDESC_RTSENA;
1090 		sc->sc_stats.ast_tx_htprotect++;
1091 	}
1092 
1093 finish:
1094 	bf->bf_state.bfs_txflags = flags;
1095 }
1096 
1097 /*
1098  * Update the frame duration given the currently selected rate.
1099  *
1100  * This also updates the frame duration value, so it will require
1101  * a DMA flush.
1102  */
1103 static void
1104 ath_tx_calc_duration(struct ath_softc *sc, struct ath_buf *bf)
1105 {
1106 	struct ieee80211_frame *wh;
1107 	uint8_t rix;
1108 	uint16_t flags;
1109 	int shortPreamble;
1110 	struct ath_hal *ah = sc->sc_ah;
1111 	const HAL_RATE_TABLE *rt = sc->sc_currates;
1112 	int isfrag = bf->bf_m->m_flags & M_FRAG;
1113 
1114 	flags = bf->bf_state.bfs_txflags;
1115 	rix = bf->bf_state.bfs_rc[0].rix;
1116 	shortPreamble = bf->bf_state.bfs_shpream;
1117 	wh = mtod(bf->bf_m, struct ieee80211_frame *);
1118 
1119 	/*
1120 	 * Calculate duration.  This logically belongs in the 802.11
1121 	 * layer but it lacks sufficient information to calculate it.
1122 	 */
1123 	if ((flags & HAL_TXDESC_NOACK) == 0 &&
1124 	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
1125 		u_int16_t dur;
1126 		if (shortPreamble)
1127 			dur = rt->info[rix].spAckDuration;
1128 		else
1129 			dur = rt->info[rix].lpAckDuration;
1130 		if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) {
1131 			dur += dur;		/* additional SIFS+ACK */
1132 			/*
1133 			 * Include the size of next fragment so NAV is
1134 			 * updated properly.  The last fragment uses only
1135 			 * the ACK duration
1136 			 *
1137 			 * XXX TODO: ensure that the rate lookup for each
1138 			 * fragment is the same as the rate used by the
1139 			 * first fragment!
1140 			 */
1141 			dur += ath_hal_computetxtime(ah,
1142 			    rt,
1143 			    bf->bf_nextfraglen,
1144 			    rix, shortPreamble,
1145 			    AH_TRUE);
1146 		}
1147 		if (isfrag) {
1148 			/*
1149 			 * Force hardware to use computed duration for next
1150 			 * fragment by disabling multi-rate retry which updates
1151 			 * duration based on the multi-rate duration table.
1152 			 */
1153 			bf->bf_state.bfs_ismrr = 0;
1154 			bf->bf_state.bfs_try0 = ATH_TXMGTTRY;
1155 			/* XXX update bfs_rc[0].try? */
1156 		}
1157 
1158 		/* Update the duration field itself */
1159 		*(u_int16_t *)wh->i_dur = htole16(dur);
1160 	}
1161 }
1162 
1163 static uint8_t
1164 ath_tx_get_rtscts_rate(struct ath_hal *ah, const HAL_RATE_TABLE *rt,
1165     int cix, int shortPreamble)
1166 {
1167 	uint8_t ctsrate;
1168 
1169 	/*
1170 	 * CTS transmit rate is derived from the transmit rate
1171 	 * by looking in the h/w rate table.  We must also factor
1172 	 * in whether or not a short preamble is to be used.
1173 	 */
1174 	/* NB: cix is set above where RTS/CTS is enabled */
1175 	KASSERT(cix != 0xff, ("cix not setup"));
1176 	ctsrate = rt->info[cix].rateCode;
1177 
1178 	/* XXX this should only matter for legacy rates */
1179 	if (shortPreamble)
1180 		ctsrate |= rt->info[cix].shortPreamble;
1181 
1182 	return (ctsrate);
1183 }
1184 
1185 /*
1186  * Calculate the RTS/CTS duration for legacy frames.
1187  */
1188 static int
1189 ath_tx_calc_ctsduration(struct ath_hal *ah, int rix, int cix,
1190     int shortPreamble, int pktlen, const HAL_RATE_TABLE *rt,
1191     int flags)
1192 {
1193 	int ctsduration = 0;
1194 
1195 	/* This mustn't be called for HT modes */
1196 	if (rt->info[cix].phy == IEEE80211_T_HT) {
1197 		printf("%s: HT rate where it shouldn't be (0x%x)\n",
1198 		    __func__, rt->info[cix].rateCode);
1199 		return (-1);
1200 	}
1201 
1202 	/*
1203 	 * Compute the transmit duration based on the frame
1204 	 * size and the size of an ACK frame.  We call into the
1205 	 * HAL to do the computation since it depends on the
1206 	 * characteristics of the actual PHY being used.
1207 	 *
1208 	 * NB: CTS is assumed the same size as an ACK so we can
1209 	 *     use the precalculated ACK durations.
1210 	 */
1211 	if (shortPreamble) {
1212 		if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
1213 			ctsduration += rt->info[cix].spAckDuration;
1214 		ctsduration += ath_hal_computetxtime(ah,
1215 			rt, pktlen, rix, AH_TRUE, AH_TRUE);
1216 		if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
1217 			ctsduration += rt->info[rix].spAckDuration;
1218 	} else {
1219 		if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
1220 			ctsduration += rt->info[cix].lpAckDuration;
1221 		ctsduration += ath_hal_computetxtime(ah,
1222 			rt, pktlen, rix, AH_FALSE, AH_TRUE);
1223 		if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
1224 			ctsduration += rt->info[rix].lpAckDuration;
1225 	}
1226 
1227 	return (ctsduration);
1228 }
1229 
1230 /*
1231  * Update the given ath_buf with updated rts/cts setup and duration
1232  * values.
1233  *
1234  * To support rate lookups for each software retry, the rts/cts rate
1235  * and cts duration must be re-calculated.
1236  *
1237  * This function assumes the RTS/CTS flags have been set as needed;
1238  * mrr has been disabled; and the rate control lookup has been done.
1239  *
1240  * XXX TODO: MRR need only be disabled for the pre-11n NICs.
1241  * XXX The 11n NICs support per-rate RTS/CTS configuration.
1242  */
1243 static void
1244 ath_tx_set_rtscts(struct ath_softc *sc, struct ath_buf *bf)
1245 {
1246 	uint16_t ctsduration = 0;
1247 	uint8_t ctsrate = 0;
1248 	uint8_t rix = bf->bf_state.bfs_rc[0].rix;
1249 	uint8_t cix = 0;
1250 	const HAL_RATE_TABLE *rt = sc->sc_currates;
1251 
1252 	/*
1253 	 * No RTS/CTS enabled? Don't bother.
1254 	 */
1255 	if ((bf->bf_state.bfs_txflags &
1256 	    (HAL_TXDESC_RTSENA | HAL_TXDESC_CTSENA)) == 0) {
1257 		/* XXX is this really needed? */
1258 		bf->bf_state.bfs_ctsrate = 0;
1259 		bf->bf_state.bfs_ctsduration = 0;
1260 		return;
1261 	}
1262 
1263 	/*
1264 	 * If protection is enabled, use the protection rix control
1265 	 * rate. Otherwise use the rate0 control rate.
1266 	 */
1267 	if (bf->bf_state.bfs_doprot)
1268 		rix = sc->sc_protrix;
1269 	else
1270 		rix = bf->bf_state.bfs_rc[0].rix;
1271 
1272 	/*
1273 	 * If the raw path has hard-coded ctsrate0 to something,
1274 	 * use it.
1275 	 */
1276 	if (bf->bf_state.bfs_ctsrate0 != 0)
1277 		cix = ath_tx_findrix(sc, bf->bf_state.bfs_ctsrate0);
1278 	else
1279 		/* Control rate from above */
1280 		cix = rt->info[rix].controlRate;
1281 
1282 	/* Calculate the rtscts rate for the given cix */
1283 	ctsrate = ath_tx_get_rtscts_rate(sc->sc_ah, rt, cix,
1284 	    bf->bf_state.bfs_shpream);
1285 
1286 	/* The 11n chipsets do ctsduration calculations for you */
1287 	if (! ath_tx_is_11n(sc))
1288 		ctsduration = ath_tx_calc_ctsduration(sc->sc_ah, rix, cix,
1289 		    bf->bf_state.bfs_shpream, bf->bf_state.bfs_pktlen,
1290 		    rt, bf->bf_state.bfs_txflags);
1291 
1292 	/* Squirrel away in ath_buf */
1293 	bf->bf_state.bfs_ctsrate = ctsrate;
1294 	bf->bf_state.bfs_ctsduration = ctsduration;
1295 
1296 	/*
1297 	 * Must disable multi-rate retry when using RTS/CTS.
1298 	 */
1299 	if (!sc->sc_mrrprot) {
1300 		bf->bf_state.bfs_ismrr = 0;
1301 		bf->bf_state.bfs_try0 =
1302 		    bf->bf_state.bfs_rc[0].tries = ATH_TXMGTTRY; /* XXX ew */
1303 	}
1304 }
1305 
1306 /*
1307  * Setup the descriptor chain for a normal or fast-frame
1308  * frame.
1309  *
1310  * XXX TODO: extend to include the destination hardware QCU ID.
1311  * Make sure that is correct.  Make sure that when being added
1312  * to the mcastq, the CABQ QCUID is set or things will get a bit
1313  * odd.
1314  */
1315 static void
1316 ath_tx_setds(struct ath_softc *sc, struct ath_buf *bf)
1317 {
1318 	struct ath_desc *ds = bf->bf_desc;
1319 	struct ath_hal *ah = sc->sc_ah;
1320 
1321 	if (bf->bf_state.bfs_txrate0 == 0)
1322 		DPRINTF(sc, ATH_DEBUG_XMIT,
1323 		    "%s: bf=%p, txrate0=%d\n", __func__, bf, 0);
1324 
1325 	ath_hal_setuptxdesc(ah, ds
1326 		, bf->bf_state.bfs_pktlen	/* packet length */
1327 		, bf->bf_state.bfs_hdrlen	/* header length */
1328 		, bf->bf_state.bfs_atype	/* Atheros packet type */
1329 		, bf->bf_state.bfs_txpower	/* txpower */
1330 		, bf->bf_state.bfs_txrate0
1331 		, bf->bf_state.bfs_try0		/* series 0 rate/tries */
1332 		, bf->bf_state.bfs_keyix	/* key cache index */
1333 		, bf->bf_state.bfs_txantenna	/* antenna mode */
1334 		, bf->bf_state.bfs_txflags	/* flags */
1335 		, bf->bf_state.bfs_ctsrate	/* rts/cts rate */
1336 		, bf->bf_state.bfs_ctsduration	/* rts/cts duration */
1337 	);
1338 
1339 	/*
1340 	 * This will be overriden when the descriptor chain is written.
1341 	 */
1342 	bf->bf_lastds = ds;
1343 	bf->bf_last = bf;
1344 
1345 	/* Set rate control and descriptor chain for this frame */
1346 	ath_tx_set_ratectrl(sc, bf->bf_node, bf);
1347 	ath_tx_chaindesclist(sc, ds, bf, 0, 0, 0);
1348 }
1349 
1350 /*
1351  * Do a rate lookup.
1352  *
1353  * This performs a rate lookup for the given ath_buf only if it's required.
1354  * Non-data frames and raw frames don't require it.
1355  *
1356  * This populates the primary and MRR entries; MRR values are
1357  * then disabled later on if something requires it (eg RTS/CTS on
1358  * pre-11n chipsets.
1359  *
1360  * This needs to be done before the RTS/CTS fields are calculated
1361  * as they may depend upon the rate chosen.
1362  */
1363 static void
1364 ath_tx_do_ratelookup(struct ath_softc *sc, struct ath_buf *bf)
1365 {
1366 	uint8_t rate, rix;
1367 	int try0;
1368 
1369 	if (! bf->bf_state.bfs_doratelookup)
1370 		return;
1371 
1372 	/* Get rid of any previous state */
1373 	bzero(bf->bf_state.bfs_rc, sizeof(bf->bf_state.bfs_rc));
1374 
1375 	ATH_NODE_LOCK(ATH_NODE(bf->bf_node));
1376 	ath_rate_findrate(sc, ATH_NODE(bf->bf_node), bf->bf_state.bfs_shpream,
1377 	    bf->bf_state.bfs_pktlen, &rix, &try0, &rate);
1378 
1379 	/* In case MRR is disabled, make sure rc[0] is setup correctly */
1380 	bf->bf_state.bfs_rc[0].rix = rix;
1381 	bf->bf_state.bfs_rc[0].ratecode = rate;
1382 	bf->bf_state.bfs_rc[0].tries = try0;
1383 
1384 	if (bf->bf_state.bfs_ismrr && try0 != ATH_TXMAXTRY)
1385 		ath_rate_getxtxrates(sc, ATH_NODE(bf->bf_node), rix,
1386 		    bf->bf_state.bfs_rc);
1387 	ATH_NODE_UNLOCK(ATH_NODE(bf->bf_node));
1388 
1389 	sc->sc_txrix = rix;	/* for LED blinking */
1390 	sc->sc_lastdatarix = rix;	/* for fast frames */
1391 	bf->bf_state.bfs_try0 = try0;
1392 	bf->bf_state.bfs_txrate0 = rate;
1393 }
1394 
1395 /*
1396  * Update the CLRDMASK bit in the ath_buf if it needs to be set.
1397  */
1398 static void
1399 ath_tx_update_clrdmask(struct ath_softc *sc, struct ath_tid *tid,
1400     struct ath_buf *bf)
1401 {
1402 	struct ath_node *an = ATH_NODE(bf->bf_node);
1403 
1404 	ATH_TX_LOCK_ASSERT(sc);
1405 
1406 	if (an->clrdmask == 1) {
1407 		bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
1408 		an->clrdmask = 0;
1409 	}
1410 }
1411 
1412 /*
1413  * Return whether this frame should be software queued or
1414  * direct dispatched.
1415  *
1416  * When doing powersave, BAR frames should be queued but other management
1417  * frames should be directly sent.
1418  *
1419  * When not doing powersave, stick BAR frames into the hardware queue
1420  * so it goes out even though the queue is paused.
1421  *
1422  * For now, management frames are also software queued by default.
1423  */
1424 static int
1425 ath_tx_should_swq_frame(struct ath_softc *sc, struct ath_node *an,
1426     struct mbuf *m0, int *queue_to_head)
1427 {
1428 	struct ieee80211_node *ni = &an->an_node;
1429 	struct ieee80211_frame *wh;
1430 	uint8_t type, subtype;
1431 
1432 	wh = mtod(m0, struct ieee80211_frame *);
1433 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1434 	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1435 
1436 	(*queue_to_head) = 0;
1437 
1438 	/* If it's not in powersave - direct-dispatch BAR */
1439 	if ((ATH_NODE(ni)->an_is_powersave == 0)
1440 	    && type == IEEE80211_FC0_TYPE_CTL &&
1441 	    subtype == IEEE80211_FC0_SUBTYPE_BAR) {
1442 		DPRINTF(sc, ATH_DEBUG_SW_TX,
1443 		    "%s: BAR: TX'ing direct\n", __func__);
1444 		return (0);
1445 	} else if ((ATH_NODE(ni)->an_is_powersave == 1)
1446 	    && type == IEEE80211_FC0_TYPE_CTL &&
1447 	    subtype == IEEE80211_FC0_SUBTYPE_BAR) {
1448 		/* BAR TX whilst asleep; queue */
1449 		DPRINTF(sc, ATH_DEBUG_SW_TX,
1450 		    "%s: swq: TX'ing\n", __func__);
1451 		(*queue_to_head) = 1;
1452 		return (1);
1453 	} else if ((ATH_NODE(ni)->an_is_powersave == 1)
1454 	    && (type == IEEE80211_FC0_TYPE_MGT ||
1455 	        type == IEEE80211_FC0_TYPE_CTL)) {
1456 		/*
1457 		 * Other control/mgmt frame; bypass software queuing
1458 		 * for now!
1459 		 */
1460 		DPRINTF(sc, ATH_DEBUG_XMIT,
1461 		    "%s: %6D: Node is asleep; sending mgmt "
1462 		    "(type=%d, subtype=%d)\n",
1463 		    __func__, ni->ni_macaddr, ":", type, subtype);
1464 		return (0);
1465 	} else {
1466 		return (1);
1467 	}
1468 }
1469 
1470 
1471 /*
1472  * Transmit the given frame to the hardware.
1473  *
1474  * The frame must already be setup; rate control must already have
1475  * been done.
1476  *
1477  * XXX since the TXQ lock is being held here (and I dislike holding
1478  * it for this long when not doing software aggregation), later on
1479  * break this function into "setup_normal" and "xmit_normal". The
1480  * lock only needs to be held for the ath_tx_handoff call.
1481  *
1482  * XXX we don't update the leak count here - if we're doing
1483  * direct frame dispatch, we need to be able to do it without
1484  * decrementing the leak count (eg multicast queue frames.)
1485  */
1486 static void
1487 ath_tx_xmit_normal(struct ath_softc *sc, struct ath_txq *txq,
1488     struct ath_buf *bf)
1489 {
1490 	struct ath_node *an = ATH_NODE(bf->bf_node);
1491 	struct ath_tid *tid = &an->an_tid[bf->bf_state.bfs_tid];
1492 
1493 	ATH_TX_LOCK_ASSERT(sc);
1494 
1495 	/*
1496 	 * For now, just enable CLRDMASK. ath_tx_xmit_normal() does
1497 	 * set a completion handler however it doesn't (yet) properly
1498 	 * handle the strict ordering requirements needed for normal,
1499 	 * non-aggregate session frames.
1500 	 *
1501 	 * Once this is implemented, only set CLRDMASK like this for
1502 	 * frames that must go out - eg management/raw frames.
1503 	 */
1504 	bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
1505 
1506 	/* Setup the descriptor before handoff */
1507 	ath_tx_do_ratelookup(sc, bf);
1508 	ath_tx_calc_duration(sc, bf);
1509 	ath_tx_calc_protection(sc, bf);
1510 	ath_tx_set_rtscts(sc, bf);
1511 	ath_tx_rate_fill_rcflags(sc, bf);
1512 	ath_tx_setds(sc, bf);
1513 
1514 	/* Track per-TID hardware queue depth correctly */
1515 	tid->hwq_depth++;
1516 
1517 	/* Assign the completion handler */
1518 	bf->bf_comp = ath_tx_normal_comp;
1519 
1520 	/* Hand off to hardware */
1521 	ath_tx_handoff(sc, txq, bf);
1522 }
1523 
1524 /*
1525  * Do the basic frame setup stuff that's required before the frame
1526  * is added to a software queue.
1527  *
1528  * All frames get mostly the same treatment and it's done once.
1529  * Retransmits fiddle with things like the rate control setup,
1530  * setting the retransmit bit in the packet; doing relevant DMA/bus
1531  * syncing and relinking it (back) into the hardware TX queue.
1532  *
1533  * Note that this may cause the mbuf to be reallocated, so
1534  * m0 may not be valid.
1535  */
1536 static int
1537 ath_tx_normal_setup(struct ath_softc *sc, struct ieee80211_node *ni,
1538     struct ath_buf *bf, struct mbuf *m0, struct ath_txq *txq)
1539 {
1540 	struct ieee80211vap *vap = ni->ni_vap;
1541 	struct ath_hal *ah = sc->sc_ah;
1542 	struct ieee80211com *ic = &sc->sc_ic;
1543 	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
1544 	int error, iswep, ismcast, isfrag, ismrr;
1545 	int keyix, hdrlen, pktlen, try0 = 0;
1546 	u_int8_t rix = 0, txrate = 0;
1547 	struct ath_desc *ds;
1548 	struct ieee80211_frame *wh;
1549 	u_int subtype, flags;
1550 	HAL_PKT_TYPE atype;
1551 	const HAL_RATE_TABLE *rt;
1552 	HAL_BOOL shortPreamble;
1553 	struct ath_node *an;
1554 	u_int pri;
1555 
1556 	/*
1557 	 * To ensure that both sequence numbers and the CCMP PN handling
1558 	 * is "correct", make sure that the relevant TID queue is locked.
1559 	 * Otherwise the CCMP PN and seqno may appear out of order, causing
1560 	 * re-ordered frames to have out of order CCMP PN's, resulting
1561 	 * in many, many frame drops.
1562 	 */
1563 	ATH_TX_LOCK_ASSERT(sc);
1564 
1565 	wh = mtod(m0, struct ieee80211_frame *);
1566 	iswep = wh->i_fc[1] & IEEE80211_FC1_PROTECTED;
1567 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
1568 	isfrag = m0->m_flags & M_FRAG;
1569 	hdrlen = ieee80211_anyhdrsize(wh);
1570 	/*
1571 	 * Packet length must not include any
1572 	 * pad bytes; deduct them here.
1573 	 */
1574 	pktlen = m0->m_pkthdr.len - (hdrlen & 3);
1575 
1576 	/* Handle encryption twiddling if needed */
1577 	if (! ath_tx_tag_crypto(sc, ni, m0, iswep, isfrag, &hdrlen,
1578 	    &pktlen, &keyix)) {
1579 		ieee80211_free_mbuf(m0);
1580 		return EIO;
1581 	}
1582 
1583 	/* packet header may have moved, reset our local pointer */
1584 	wh = mtod(m0, struct ieee80211_frame *);
1585 
1586 	pktlen += IEEE80211_CRC_LEN;
1587 
1588 	/*
1589 	 * Load the DMA map so any coalescing is done.  This
1590 	 * also calculates the number of descriptors we need.
1591 	 */
1592 	error = ath_tx_dmasetup(sc, bf, m0);
1593 	if (error != 0)
1594 		return error;
1595 	KASSERT((ni != NULL), ("%s: ni=NULL!", __func__));
1596 	bf->bf_node = ni;			/* NB: held reference */
1597 	m0 = bf->bf_m;				/* NB: may have changed */
1598 	wh = mtod(m0, struct ieee80211_frame *);
1599 
1600 	/* setup descriptors */
1601 	ds = bf->bf_desc;
1602 	rt = sc->sc_currates;
1603 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
1604 
1605 	/*
1606 	 * NB: the 802.11 layer marks whether or not we should
1607 	 * use short preamble based on the current mode and
1608 	 * negotiated parameters.
1609 	 */
1610 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1611 	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
1612 		shortPreamble = AH_TRUE;
1613 		sc->sc_stats.ast_tx_shortpre++;
1614 	} else {
1615 		shortPreamble = AH_FALSE;
1616 	}
1617 
1618 	an = ATH_NODE(ni);
1619 	//flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
1620 	flags = 0;
1621 	ismrr = 0;				/* default no multi-rate retry*/
1622 	pri = M_WME_GETAC(m0);			/* honor classification */
1623 	/* XXX use txparams instead of fixed values */
1624 	/*
1625 	 * Calculate Atheros packet type from IEEE80211 packet header,
1626 	 * setup for rate calculations, and select h/w transmit queue.
1627 	 */
1628 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
1629 	case IEEE80211_FC0_TYPE_MGT:
1630 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1631 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
1632 			atype = HAL_PKT_TYPE_BEACON;
1633 		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1634 			atype = HAL_PKT_TYPE_PROBE_RESP;
1635 		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
1636 			atype = HAL_PKT_TYPE_ATIM;
1637 		else
1638 			atype = HAL_PKT_TYPE_NORMAL;	/* XXX */
1639 		rix = an->an_mgmtrix;
1640 		txrate = rt->info[rix].rateCode;
1641 		if (shortPreamble)
1642 			txrate |= rt->info[rix].shortPreamble;
1643 		try0 = ATH_TXMGTTRY;
1644 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
1645 		break;
1646 	case IEEE80211_FC0_TYPE_CTL:
1647 		atype = HAL_PKT_TYPE_PSPOLL;	/* stop setting of duration */
1648 		rix = an->an_mgmtrix;
1649 		txrate = rt->info[rix].rateCode;
1650 		if (shortPreamble)
1651 			txrate |= rt->info[rix].shortPreamble;
1652 		try0 = ATH_TXMGTTRY;
1653 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
1654 		break;
1655 	case IEEE80211_FC0_TYPE_DATA:
1656 		atype = HAL_PKT_TYPE_NORMAL;		/* default */
1657 		/*
1658 		 * Data frames: multicast frames go out at a fixed rate,
1659 		 * EAPOL frames use the mgmt frame rate; otherwise consult
1660 		 * the rate control module for the rate to use.
1661 		 */
1662 		if (ismcast) {
1663 			rix = an->an_mcastrix;
1664 			txrate = rt->info[rix].rateCode;
1665 			if (shortPreamble)
1666 				txrate |= rt->info[rix].shortPreamble;
1667 			try0 = 1;
1668 		} else if (m0->m_flags & M_EAPOL) {
1669 			/* XXX? maybe always use long preamble? */
1670 			rix = an->an_mgmtrix;
1671 			txrate = rt->info[rix].rateCode;
1672 			if (shortPreamble)
1673 				txrate |= rt->info[rix].shortPreamble;
1674 			try0 = ATH_TXMAXTRY;	/* XXX?too many? */
1675 		} else {
1676 			/*
1677 			 * Do rate lookup on each TX, rather than using
1678 			 * the hard-coded TX information decided here.
1679 			 */
1680 			ismrr = 1;
1681 			bf->bf_state.bfs_doratelookup = 1;
1682 		}
1683 		if (cap->cap_wmeParams[pri].wmep_noackPolicy)
1684 			flags |= HAL_TXDESC_NOACK;
1685 		break;
1686 	default:
1687 		device_printf(sc->sc_dev, "bogus frame type 0x%x (%s)\n",
1688 		    wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
1689 		/* XXX statistic */
1690 		/* XXX free tx dmamap */
1691 		ieee80211_free_mbuf(m0);
1692 		return EIO;
1693 	}
1694 
1695 	/*
1696 	 * There are two known scenarios where the frame AC doesn't match
1697 	 * what the destination TXQ is.
1698 	 *
1699 	 * + non-QoS frames (eg management?) that the net80211 stack has
1700 	 *   assigned a higher AC to, but since it's a non-QoS TID, it's
1701 	 *   being thrown into TID 16.  TID 16 gets the AC_BE queue.
1702 	 *   It's quite possible that management frames should just be
1703 	 *   direct dispatched to hardware rather than go via the software
1704 	 *   queue; that should be investigated in the future.  There are
1705 	 *   some specific scenarios where this doesn't make sense, mostly
1706 	 *   surrounding ADDBA request/response - hence why that is special
1707 	 *   cased.
1708 	 *
1709 	 * + Multicast frames going into the VAP mcast queue.  That shows up
1710 	 *   as "TXQ 11".
1711 	 *
1712 	 * This driver should eventually support separate TID and TXQ locking,
1713 	 * allowing for arbitrary AC frames to appear on arbitrary software
1714 	 * queues, being queued to the "correct" hardware queue when needed.
1715 	 */
1716 #if 0
1717 	if (txq != sc->sc_ac2q[pri]) {
1718 		DPRINTF(sc, ATH_DEBUG_XMIT,
1719 		    "%s: txq=%p (%d), pri=%d, pri txq=%p (%d)\n",
1720 		    __func__,
1721 		    txq,
1722 		    txq->axq_qnum,
1723 		    pri,
1724 		    sc->sc_ac2q[pri],
1725 		    sc->sc_ac2q[pri]->axq_qnum);
1726 	}
1727 #endif
1728 
1729 	/*
1730 	 * Calculate miscellaneous flags.
1731 	 */
1732 	if (ismcast) {
1733 		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
1734 	} else if (pktlen > vap->iv_rtsthreshold &&
1735 	    (ni->ni_ath_flags & IEEE80211_NODE_FF) == 0) {
1736 		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
1737 		sc->sc_stats.ast_tx_rts++;
1738 	}
1739 	if (flags & HAL_TXDESC_NOACK)		/* NB: avoid double counting */
1740 		sc->sc_stats.ast_tx_noack++;
1741 #ifdef IEEE80211_SUPPORT_TDMA
1742 	if (sc->sc_tdma && (flags & HAL_TXDESC_NOACK) == 0) {
1743 		DPRINTF(sc, ATH_DEBUG_TDMA,
1744 		    "%s: discard frame, ACK required w/ TDMA\n", __func__);
1745 		sc->sc_stats.ast_tdma_ack++;
1746 		/* XXX free tx dmamap */
1747 		ieee80211_free_mbuf(m0);
1748 		return EIO;
1749 	}
1750 #endif
1751 
1752 	/*
1753 	 * If it's a frame to do location reporting on,
1754 	 * communicate it to the HAL.
1755 	 */
1756 	if (ieee80211_get_toa_params(m0, NULL)) {
1757 		device_printf(sc->sc_dev,
1758 		    "%s: setting TX positioning bit\n", __func__);
1759 		flags |= HAL_TXDESC_POS;
1760 
1761 		/*
1762 		 * Note: The hardware reports timestamps for
1763 		 * each of the RX'ed packets as part of the packet
1764 		 * exchange.  So this means things like RTS/CTS
1765 		 * exchanges, as well as the final ACK.
1766 		 *
1767 		 * So, if you send a RTS-protected NULL data frame,
1768 		 * you'll get an RX report for the RTS response, then
1769 		 * an RX report for the NULL frame, and then the TX
1770 		 * completion at the end.
1771 		 *
1772 		 * NOTE: it doesn't work right for CCK frames;
1773 		 * there's no channel info data provided unless
1774 		 * it's OFDM or HT.  Will have to dig into it.
1775 		 */
1776 		flags &= ~(HAL_TXDESC_RTSENA | HAL_TXDESC_CTSENA);
1777 		bf->bf_flags |= ATH_BUF_TOA_PROBE;
1778 	}
1779 
1780 #if 0
1781 	/*
1782 	 * Placeholder: if you want to transmit with the azimuth
1783 	 * timestamp in the end of the payload, here's where you
1784 	 * should set the TXDESC field.
1785 	 */
1786 	flags |= HAL_TXDESC_HWTS;
1787 #endif
1788 
1789 	/*
1790 	 * Determine if a tx interrupt should be generated for
1791 	 * this descriptor.  We take a tx interrupt to reap
1792 	 * descriptors when the h/w hits an EOL condition or
1793 	 * when the descriptor is specifically marked to generate
1794 	 * an interrupt.  We periodically mark descriptors in this
1795 	 * way to insure timely replenishing of the supply needed
1796 	 * for sending frames.  Defering interrupts reduces system
1797 	 * load and potentially allows more concurrent work to be
1798 	 * done but if done to aggressively can cause senders to
1799 	 * backup.
1800 	 *
1801 	 * NB: use >= to deal with sc_txintrperiod changing
1802 	 *     dynamically through sysctl.
1803 	 */
1804 	if (flags & HAL_TXDESC_INTREQ) {
1805 		txq->axq_intrcnt = 0;
1806 	} else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
1807 		flags |= HAL_TXDESC_INTREQ;
1808 		txq->axq_intrcnt = 0;
1809 	}
1810 
1811 	/* This point forward is actual TX bits */
1812 
1813 	/*
1814 	 * At this point we are committed to sending the frame
1815 	 * and we don't need to look at m_nextpkt; clear it in
1816 	 * case this frame is part of frag chain.
1817 	 */
1818 	m0->m_nextpkt = NULL;
1819 
1820 	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
1821 		ieee80211_dump_pkt(ic, mtod(m0, const uint8_t *), m0->m_len,
1822 		    sc->sc_hwmap[rix].ieeerate, -1);
1823 
1824 	if (ieee80211_radiotap_active_vap(vap)) {
1825 		u_int64_t tsf = ath_hal_gettsf64(ah);
1826 
1827 		sc->sc_tx_th.wt_tsf = htole64(tsf);
1828 		sc->sc_tx_th.wt_flags = sc->sc_hwmap[rix].txflags;
1829 		if (iswep)
1830 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
1831 		if (isfrag)
1832 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
1833 		sc->sc_tx_th.wt_rate = sc->sc_hwmap[rix].ieeerate;
1834 		sc->sc_tx_th.wt_txpower = ieee80211_get_node_txpower(ni);
1835 		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
1836 
1837 		ieee80211_radiotap_tx(vap, m0);
1838 	}
1839 
1840 	/* Blank the legacy rate array */
1841 	bzero(&bf->bf_state.bfs_rc, sizeof(bf->bf_state.bfs_rc));
1842 
1843 	/*
1844 	 * ath_buf_set_rate needs at least one rate/try to setup
1845 	 * the rate scenario.
1846 	 */
1847 	bf->bf_state.bfs_rc[0].rix = rix;
1848 	bf->bf_state.bfs_rc[0].tries = try0;
1849 	bf->bf_state.bfs_rc[0].ratecode = txrate;
1850 
1851 	/* Store the decided rate index values away */
1852 	bf->bf_state.bfs_pktlen = pktlen;
1853 	bf->bf_state.bfs_hdrlen = hdrlen;
1854 	bf->bf_state.bfs_atype = atype;
1855 	bf->bf_state.bfs_txpower = ieee80211_get_node_txpower(ni);
1856 	bf->bf_state.bfs_txrate0 = txrate;
1857 	bf->bf_state.bfs_try0 = try0;
1858 	bf->bf_state.bfs_keyix = keyix;
1859 	bf->bf_state.bfs_txantenna = sc->sc_txantenna;
1860 	bf->bf_state.bfs_txflags = flags;
1861 	bf->bf_state.bfs_shpream = shortPreamble;
1862 
1863 	/* XXX this should be done in ath_tx_setrate() */
1864 	bf->bf_state.bfs_ctsrate0 = 0;	/* ie, no hard-coded ctsrate */
1865 	bf->bf_state.bfs_ctsrate = 0;	/* calculated later */
1866 	bf->bf_state.bfs_ctsduration = 0;
1867 	bf->bf_state.bfs_ismrr = ismrr;
1868 
1869 	return 0;
1870 }
1871 
1872 /*
1873  * Queue a frame to the hardware or software queue.
1874  *
1875  * This can be called by the net80211 code.
1876  *
1877  * XXX what about locking? Or, push the seqno assign into the
1878  * XXX aggregate scheduler so its serialised?
1879  *
1880  * XXX When sending management frames via ath_raw_xmit(),
1881  *     should CLRDMASK be set unconditionally?
1882  */
1883 int
1884 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni,
1885     struct ath_buf *bf, struct mbuf *m0)
1886 {
1887 	struct ieee80211vap *vap = ni->ni_vap;
1888 	struct ath_vap *avp = ATH_VAP(vap);
1889 	int r = 0;
1890 	u_int pri;
1891 	int tid;
1892 	struct ath_txq *txq;
1893 	int ismcast;
1894 	const struct ieee80211_frame *wh;
1895 	int is_ampdu, is_ampdu_tx, is_ampdu_pending;
1896 	ieee80211_seq seqno;
1897 	uint8_t type, subtype;
1898 	int queue_to_head;
1899 
1900 	ATH_TX_LOCK_ASSERT(sc);
1901 
1902 	/*
1903 	 * Determine the target hardware queue.
1904 	 *
1905 	 * For multicast frames, the txq gets overridden appropriately
1906 	 * depending upon the state of PS.
1907 	 *
1908 	 * For any other frame, we do a TID/QoS lookup inside the frame
1909 	 * to see what the TID should be. If it's a non-QoS frame, the
1910 	 * AC and TID are overridden. The TID/TXQ code assumes the
1911 	 * TID is on a predictable hardware TXQ, so we don't support
1912 	 * having a node TID queued to multiple hardware TXQs.
1913 	 * This may change in the future but would require some locking
1914 	 * fudgery.
1915 	 */
1916 	pri = ath_tx_getac(sc, m0);
1917 	tid = ath_tx_gettid(sc, m0);
1918 
1919 	txq = sc->sc_ac2q[pri];
1920 	wh = mtod(m0, struct ieee80211_frame *);
1921 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
1922 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1923 	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1924 
1925 	/*
1926 	 * Enforce how deep the multicast queue can grow.
1927 	 *
1928 	 * XXX duplicated in ath_raw_xmit().
1929 	 */
1930 	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1931 		if (sc->sc_cabq->axq_depth + sc->sc_cabq->fifo.axq_depth
1932 		    > sc->sc_txq_mcastq_maxdepth) {
1933 			sc->sc_stats.ast_tx_mcastq_overflow++;
1934 			m_freem(m0);
1935 			return (ENOBUFS);
1936 		}
1937 	}
1938 
1939 	/*
1940 	 * Enforce how deep the unicast queue can grow.
1941 	 *
1942 	 * If the node is in power save then we don't want
1943 	 * the software queue to grow too deep, or a node may
1944 	 * end up consuming all of the ath_buf entries.
1945 	 *
1946 	 * For now, only do this for DATA frames.
1947 	 *
1948 	 * We will want to cap how many management/control
1949 	 * frames get punted to the software queue so it doesn't
1950 	 * fill up.  But the correct solution isn't yet obvious.
1951 	 * In any case, this check should at least let frames pass
1952 	 * that we are direct-dispatching.
1953 	 *
1954 	 * XXX TODO: duplicate this to the raw xmit path!
1955 	 */
1956 	if (type == IEEE80211_FC0_TYPE_DATA &&
1957 	    ATH_NODE(ni)->an_is_powersave &&
1958 	    ATH_NODE(ni)->an_swq_depth >
1959 	     sc->sc_txq_node_psq_maxdepth) {
1960 		sc->sc_stats.ast_tx_node_psq_overflow++;
1961 		m_freem(m0);
1962 		return (ENOBUFS);
1963 	}
1964 
1965 	/* A-MPDU TX */
1966 	is_ampdu_tx = ath_tx_ampdu_running(sc, ATH_NODE(ni), tid);
1967 	is_ampdu_pending = ath_tx_ampdu_pending(sc, ATH_NODE(ni), tid);
1968 	is_ampdu = is_ampdu_tx | is_ampdu_pending;
1969 
1970 	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: tid=%d, ac=%d, is_ampdu=%d\n",
1971 	    __func__, tid, pri, is_ampdu);
1972 
1973 	/* Set local packet state, used to queue packets to hardware */
1974 	bf->bf_state.bfs_tid = tid;
1975 	bf->bf_state.bfs_tx_queue = txq->axq_qnum;
1976 	bf->bf_state.bfs_pri = pri;
1977 
1978 #if 1
1979 	/*
1980 	 * When servicing one or more stations in power-save mode
1981 	 * (or) if there is some mcast data waiting on the mcast
1982 	 * queue (to prevent out of order delivery) multicast frames
1983 	 * must be bufferd until after the beacon.
1984 	 *
1985 	 * TODO: we should lock the mcastq before we check the length.
1986 	 */
1987 	if (sc->sc_cabq_enable && ismcast && (vap->iv_ps_sta || avp->av_mcastq.axq_depth)) {
1988 		txq = &avp->av_mcastq;
1989 		/*
1990 		 * Mark the frame as eventually belonging on the CAB
1991 		 * queue, so the descriptor setup functions will
1992 		 * correctly initialise the descriptor 'qcuId' field.
1993 		 */
1994 		bf->bf_state.bfs_tx_queue = sc->sc_cabq->axq_qnum;
1995 	}
1996 #endif
1997 
1998 	/* Do the generic frame setup */
1999 	/* XXX should just bzero the bf_state? */
2000 	bf->bf_state.bfs_dobaw = 0;
2001 
2002 	/* A-MPDU TX? Manually set sequence number */
2003 	/*
2004 	 * Don't do it whilst pending; the net80211 layer still
2005 	 * assigns them.
2006 	 */
2007 	if (is_ampdu_tx) {
2008 		/*
2009 		 * Always call; this function will
2010 		 * handle making sure that null data frames
2011 		 * don't get a sequence number from the current
2012 		 * TID and thus mess with the BAW.
2013 		 */
2014 		seqno = ath_tx_tid_seqno_assign(sc, ni, bf, m0);
2015 
2016 		/*
2017 		 * Don't add QoS NULL frames to the BAW.
2018 		 */
2019 		if (IEEE80211_QOS_HAS_SEQ(wh) &&
2020 		    subtype != IEEE80211_FC0_SUBTYPE_QOS_NULL) {
2021 			bf->bf_state.bfs_dobaw = 1;
2022 		}
2023 	}
2024 
2025 	/*
2026 	 * If needed, the sequence number has been assigned.
2027 	 * Squirrel it away somewhere easy to get to.
2028 	 */
2029 	bf->bf_state.bfs_seqno = M_SEQNO_GET(m0) << IEEE80211_SEQ_SEQ_SHIFT;
2030 
2031 	/* Is ampdu pending? fetch the seqno and print it out */
2032 	if (is_ampdu_pending)
2033 		DPRINTF(sc, ATH_DEBUG_SW_TX,
2034 		    "%s: tid %d: ampdu pending, seqno %d\n",
2035 		    __func__, tid, M_SEQNO_GET(m0));
2036 
2037 	/* This also sets up the DMA map */
2038 	r = ath_tx_normal_setup(sc, ni, bf, m0, txq);
2039 
2040 	if (r != 0)
2041 		goto done;
2042 
2043 	/* At this point m0 could have changed! */
2044 	m0 = bf->bf_m;
2045 
2046 #if 1
2047 	/*
2048 	 * If it's a multicast frame, do a direct-dispatch to the
2049 	 * destination hardware queue. Don't bother software
2050 	 * queuing it.
2051 	 */
2052 	/*
2053 	 * If it's a BAR frame, do a direct dispatch to the
2054 	 * destination hardware queue. Don't bother software
2055 	 * queuing it, as the TID will now be paused.
2056 	 * Sending a BAR frame can occur from the net80211 txa timer
2057 	 * (ie, retries) or from the ath txtask (completion call.)
2058 	 * It queues directly to hardware because the TID is paused
2059 	 * at this point (and won't be unpaused until the BAR has
2060 	 * either been TXed successfully or max retries has been
2061 	 * reached.)
2062 	 */
2063 	/*
2064 	 * Until things are better debugged - if this node is asleep
2065 	 * and we're sending it a non-BAR frame, direct dispatch it.
2066 	 * Why? Because we need to figure out what's actually being
2067 	 * sent - eg, during reassociation/reauthentication after
2068 	 * the node (last) disappeared whilst asleep, the driver should
2069 	 * have unpaused/unsleep'ed the node.  So until that is
2070 	 * sorted out, use this workaround.
2071 	 */
2072 	if (txq == &avp->av_mcastq) {
2073 		DPRINTF(sc, ATH_DEBUG_SW_TX,
2074 		    "%s: bf=%p: mcastq: TX'ing\n", __func__, bf);
2075 		bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
2076 		ath_tx_xmit_normal(sc, txq, bf);
2077 	} else if (ath_tx_should_swq_frame(sc, ATH_NODE(ni), m0,
2078 	    &queue_to_head)) {
2079 		ath_tx_swq(sc, ni, txq, queue_to_head, bf);
2080 	} else {
2081 		bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
2082 		ath_tx_xmit_normal(sc, txq, bf);
2083 	}
2084 #else
2085 	/*
2086 	 * For now, since there's no software queue,
2087 	 * direct-dispatch to the hardware.
2088 	 */
2089 	bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
2090 	/*
2091 	 * Update the current leak count if
2092 	 * we're leaking frames; and set the
2093 	 * MORE flag as appropriate.
2094 	 */
2095 	ath_tx_leak_count_update(sc, tid, bf);
2096 	ath_tx_xmit_normal(sc, txq, bf);
2097 #endif
2098 done:
2099 	return 0;
2100 }
2101 
2102 static int
2103 ath_tx_raw_start(struct ath_softc *sc, struct ieee80211_node *ni,
2104 	struct ath_buf *bf, struct mbuf *m0,
2105 	const struct ieee80211_bpf_params *params)
2106 {
2107 	struct ieee80211com *ic = &sc->sc_ic;
2108 	struct ath_hal *ah = sc->sc_ah;
2109 	struct ieee80211vap *vap = ni->ni_vap;
2110 	int error, ismcast, ismrr;
2111 	int keyix, hdrlen, pktlen, try0, txantenna;
2112 	u_int8_t rix, txrate;
2113 	struct ieee80211_frame *wh;
2114 	u_int flags;
2115 	HAL_PKT_TYPE atype;
2116 	const HAL_RATE_TABLE *rt;
2117 	struct ath_desc *ds;
2118 	u_int pri;
2119 	int o_tid = -1;
2120 	int do_override;
2121 	uint8_t type, subtype;
2122 	int queue_to_head;
2123 	struct ath_node *an = ATH_NODE(ni);
2124 
2125 	ATH_TX_LOCK_ASSERT(sc);
2126 
2127 	wh = mtod(m0, struct ieee80211_frame *);
2128 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
2129 	hdrlen = ieee80211_anyhdrsize(wh);
2130 	/*
2131 	 * Packet length must not include any
2132 	 * pad bytes; deduct them here.
2133 	 */
2134 	/* XXX honor IEEE80211_BPF_DATAPAD */
2135 	pktlen = m0->m_pkthdr.len - (hdrlen & 3) + IEEE80211_CRC_LEN;
2136 
2137 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2138 	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
2139 
2140 	ATH_KTR(sc, ATH_KTR_TX, 2,
2141 	     "ath_tx_raw_start: ni=%p, bf=%p, raw", ni, bf);
2142 
2143 	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: ismcast=%d\n",
2144 	    __func__, ismcast);
2145 
2146 	pri = params->ibp_pri & 3;
2147 	/* Override pri if the frame isn't a QoS one */
2148 	if (! IEEE80211_QOS_HAS_SEQ(wh))
2149 		pri = ath_tx_getac(sc, m0);
2150 
2151 	/* XXX If it's an ADDBA, override the correct queue */
2152 	do_override = ath_tx_action_frame_override_queue(sc, ni, m0, &o_tid);
2153 
2154 	/* Map ADDBA to the correct priority */
2155 	if (do_override) {
2156 #if 0
2157 		DPRINTF(sc, ATH_DEBUG_XMIT,
2158 		    "%s: overriding tid %d pri %d -> %d\n",
2159 		    __func__, o_tid, pri, TID_TO_WME_AC(o_tid));
2160 #endif
2161 		pri = TID_TO_WME_AC(o_tid);
2162 	}
2163 
2164 	/* Handle encryption twiddling if needed */
2165 	if (! ath_tx_tag_crypto(sc, ni,
2166 	    m0, params->ibp_flags & IEEE80211_BPF_CRYPTO, 0,
2167 	    &hdrlen, &pktlen, &keyix)) {
2168 		ieee80211_free_mbuf(m0);
2169 		return EIO;
2170 	}
2171 	/* packet header may have moved, reset our local pointer */
2172 	wh = mtod(m0, struct ieee80211_frame *);
2173 
2174 	/* Do the generic frame setup */
2175 	/* XXX should just bzero the bf_state? */
2176 	bf->bf_state.bfs_dobaw = 0;
2177 
2178 	error = ath_tx_dmasetup(sc, bf, m0);
2179 	if (error != 0)
2180 		return error;
2181 	m0 = bf->bf_m;				/* NB: may have changed */
2182 	wh = mtod(m0, struct ieee80211_frame *);
2183 	KASSERT((ni != NULL), ("%s: ni=NULL!", __func__));
2184 	bf->bf_node = ni;			/* NB: held reference */
2185 
2186 	/* Always enable CLRDMASK for raw frames for now.. */
2187 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
2188 	flags |= HAL_TXDESC_INTREQ;		/* force interrupt */
2189 	if (params->ibp_flags & IEEE80211_BPF_RTS)
2190 		flags |= HAL_TXDESC_RTSENA;
2191 	else if (params->ibp_flags & IEEE80211_BPF_CTS) {
2192 		/* XXX assume 11g/11n protection? */
2193 		bf->bf_state.bfs_doprot = 1;
2194 		flags |= HAL_TXDESC_CTSENA;
2195 	}
2196 	/* XXX leave ismcast to injector? */
2197 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) || ismcast)
2198 		flags |= HAL_TXDESC_NOACK;
2199 
2200 	rt = sc->sc_currates;
2201 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
2202 
2203 	/* Fetch first rate information */
2204 	rix = ath_tx_findrix(sc, params->ibp_rate0);
2205 	try0 = params->ibp_try0;
2206 
2207 	/*
2208 	 * Override EAPOL rate as appropriate.
2209 	 */
2210 	if (m0->m_flags & M_EAPOL) {
2211 		/* XXX? maybe always use long preamble? */
2212 		rix = an->an_mgmtrix;
2213 		try0 = ATH_TXMAXTRY;	/* XXX?too many? */
2214 	}
2215 
2216 	/*
2217 	 * If it's a frame to do location reporting on,
2218 	 * communicate it to the HAL.
2219 	 */
2220 	if (ieee80211_get_toa_params(m0, NULL)) {
2221 		device_printf(sc->sc_dev,
2222 		    "%s: setting TX positioning bit\n", __func__);
2223 		flags |= HAL_TXDESC_POS;
2224 		flags &= ~(HAL_TXDESC_RTSENA | HAL_TXDESC_CTSENA);
2225 		bf->bf_flags |= ATH_BUF_TOA_PROBE;
2226 	}
2227 
2228 	txrate = rt->info[rix].rateCode;
2229 	if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
2230 		txrate |= rt->info[rix].shortPreamble;
2231 	sc->sc_txrix = rix;
2232 	ismrr = (params->ibp_try1 != 0);
2233 	txantenna = params->ibp_pri >> 2;
2234 	if (txantenna == 0)			/* XXX? */
2235 		txantenna = sc->sc_txantenna;
2236 
2237 	/*
2238 	 * Since ctsrate is fixed, store it away for later
2239 	 * use when the descriptor fields are being set.
2240 	 */
2241 	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA))
2242 		bf->bf_state.bfs_ctsrate0 = params->ibp_ctsrate;
2243 
2244 	/*
2245 	 * NB: we mark all packets as type PSPOLL so the h/w won't
2246 	 * set the sequence number, duration, etc.
2247 	 */
2248 	atype = HAL_PKT_TYPE_PSPOLL;
2249 
2250 	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
2251 		ieee80211_dump_pkt(ic, mtod(m0, caddr_t), m0->m_len,
2252 		    sc->sc_hwmap[rix].ieeerate, -1);
2253 
2254 	if (ieee80211_radiotap_active_vap(vap)) {
2255 		u_int64_t tsf = ath_hal_gettsf64(ah);
2256 
2257 		sc->sc_tx_th.wt_tsf = htole64(tsf);
2258 		sc->sc_tx_th.wt_flags = sc->sc_hwmap[rix].txflags;
2259 		if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED)
2260 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
2261 		if (m0->m_flags & M_FRAG)
2262 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
2263 		sc->sc_tx_th.wt_rate = sc->sc_hwmap[rix].ieeerate;
2264 		sc->sc_tx_th.wt_txpower = MIN(params->ibp_power,
2265 		    ieee80211_get_node_txpower(ni));
2266 		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
2267 
2268 		ieee80211_radiotap_tx(vap, m0);
2269 	}
2270 
2271 	/*
2272 	 * Formulate first tx descriptor with tx controls.
2273 	 */
2274 	ds = bf->bf_desc;
2275 	/* XXX check return value? */
2276 
2277 	/* Store the decided rate index values away */
2278 	bf->bf_state.bfs_pktlen = pktlen;
2279 	bf->bf_state.bfs_hdrlen = hdrlen;
2280 	bf->bf_state.bfs_atype = atype;
2281 	bf->bf_state.bfs_txpower = MIN(params->ibp_power,
2282 	    ieee80211_get_node_txpower(ni));
2283 	bf->bf_state.bfs_txrate0 = txrate;
2284 	bf->bf_state.bfs_try0 = try0;
2285 	bf->bf_state.bfs_keyix = keyix;
2286 	bf->bf_state.bfs_txantenna = txantenna;
2287 	bf->bf_state.bfs_txflags = flags;
2288 	bf->bf_state.bfs_shpream =
2289 	    !! (params->ibp_flags & IEEE80211_BPF_SHORTPRE);
2290 
2291 	/* Set local packet state, used to queue packets to hardware */
2292 	bf->bf_state.bfs_tid = WME_AC_TO_TID(pri);
2293 	bf->bf_state.bfs_tx_queue = sc->sc_ac2q[pri]->axq_qnum;
2294 	bf->bf_state.bfs_pri = pri;
2295 
2296 	/* XXX this should be done in ath_tx_setrate() */
2297 	bf->bf_state.bfs_ctsrate = 0;
2298 	bf->bf_state.bfs_ctsduration = 0;
2299 	bf->bf_state.bfs_ismrr = ismrr;
2300 
2301 	/* Blank the legacy rate array */
2302 	bzero(&bf->bf_state.bfs_rc, sizeof(bf->bf_state.bfs_rc));
2303 
2304 	bf->bf_state.bfs_rc[0].rix = rix;
2305 	bf->bf_state.bfs_rc[0].tries = try0;
2306 	bf->bf_state.bfs_rc[0].ratecode = txrate;
2307 
2308 	if (ismrr) {
2309 		int rix;
2310 
2311 		rix = ath_tx_findrix(sc, params->ibp_rate1);
2312 		bf->bf_state.bfs_rc[1].rix = rix;
2313 		bf->bf_state.bfs_rc[1].tries = params->ibp_try1;
2314 
2315 		rix = ath_tx_findrix(sc, params->ibp_rate2);
2316 		bf->bf_state.bfs_rc[2].rix = rix;
2317 		bf->bf_state.bfs_rc[2].tries = params->ibp_try2;
2318 
2319 		rix = ath_tx_findrix(sc, params->ibp_rate3);
2320 		bf->bf_state.bfs_rc[3].rix = rix;
2321 		bf->bf_state.bfs_rc[3].tries = params->ibp_try3;
2322 	}
2323 	/*
2324 	 * All the required rate control decisions have been made;
2325 	 * fill in the rc flags.
2326 	 */
2327 	ath_tx_rate_fill_rcflags(sc, bf);
2328 
2329 	/* NB: no buffered multicast in power save support */
2330 
2331 	/*
2332 	 * If we're overiding the ADDBA destination, dump directly
2333 	 * into the hardware queue, right after any pending
2334 	 * frames to that node are.
2335 	 */
2336 	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: dooverride=%d\n",
2337 	    __func__, do_override);
2338 
2339 #if 1
2340 	/*
2341 	 * Put addba frames in the right place in the right TID/HWQ.
2342 	 */
2343 	if (do_override) {
2344 		bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
2345 		/*
2346 		 * XXX if it's addba frames, should we be leaking
2347 		 * them out via the frame leak method?
2348 		 * XXX for now let's not risk it; but we may wish
2349 		 * to investigate this later.
2350 		 */
2351 		ath_tx_xmit_normal(sc, sc->sc_ac2q[pri], bf);
2352 	} else if (ath_tx_should_swq_frame(sc, ATH_NODE(ni), m0,
2353 	    &queue_to_head)) {
2354 		/* Queue to software queue */
2355 		ath_tx_swq(sc, ni, sc->sc_ac2q[pri], queue_to_head, bf);
2356 	} else {
2357 		bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
2358 		ath_tx_xmit_normal(sc, sc->sc_ac2q[pri], bf);
2359 	}
2360 #else
2361 	/* Direct-dispatch to the hardware */
2362 	bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
2363 	/*
2364 	 * Update the current leak count if
2365 	 * we're leaking frames; and set the
2366 	 * MORE flag as appropriate.
2367 	 */
2368 	ath_tx_leak_count_update(sc, tid, bf);
2369 	ath_tx_xmit_normal(sc, sc->sc_ac2q[pri], bf);
2370 #endif
2371 	return 0;
2372 }
2373 
2374 /*
2375  * Send a raw frame.
2376  *
2377  * This can be called by net80211.
2378  */
2379 int
2380 ath_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2381 	const struct ieee80211_bpf_params *params)
2382 {
2383 	struct ieee80211com *ic = ni->ni_ic;
2384 	struct ath_softc *sc = ic->ic_softc;
2385 	struct ath_buf *bf;
2386 	struct ieee80211_frame *wh = mtod(m, struct ieee80211_frame *);
2387 	int error = 0;
2388 
2389 	ATH_PCU_LOCK(sc);
2390 	if (sc->sc_inreset_cnt > 0) {
2391 		DPRINTF(sc, ATH_DEBUG_XMIT,
2392 		    "%s: sc_inreset_cnt > 0; bailing\n", __func__);
2393 		error = EIO;
2394 		ATH_PCU_UNLOCK(sc);
2395 		goto badbad;
2396 	}
2397 	sc->sc_txstart_cnt++;
2398 	ATH_PCU_UNLOCK(sc);
2399 
2400 	/* Wake the hardware up already */
2401 	ATH_LOCK(sc);
2402 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
2403 	ATH_UNLOCK(sc);
2404 
2405 	ATH_TX_LOCK(sc);
2406 
2407 	if (!sc->sc_running || sc->sc_invalid) {
2408 		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: discard frame, r/i: %d/%d",
2409 		    __func__, sc->sc_running, sc->sc_invalid);
2410 		m_freem(m);
2411 		error = ENETDOWN;
2412 		goto bad;
2413 	}
2414 
2415 	/*
2416 	 * Enforce how deep the multicast queue can grow.
2417 	 *
2418 	 * XXX duplicated in ath_tx_start().
2419 	 */
2420 	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
2421 		if (sc->sc_cabq->axq_depth + sc->sc_cabq->fifo.axq_depth
2422 		    > sc->sc_txq_mcastq_maxdepth) {
2423 			sc->sc_stats.ast_tx_mcastq_overflow++;
2424 			error = ENOBUFS;
2425 		}
2426 
2427 		if (error != 0) {
2428 			m_freem(m);
2429 			goto bad;
2430 		}
2431 	}
2432 
2433 	/*
2434 	 * Grab a TX buffer and associated resources.
2435 	 */
2436 	bf = ath_getbuf(sc, ATH_BUFTYPE_MGMT);
2437 	if (bf == NULL) {
2438 		sc->sc_stats.ast_tx_nobuf++;
2439 		m_freem(m);
2440 		error = ENOBUFS;
2441 		goto bad;
2442 	}
2443 	ATH_KTR(sc, ATH_KTR_TX, 3, "ath_raw_xmit: m=%p, params=%p, bf=%p\n",
2444 	    m, params,  bf);
2445 
2446 	if (params == NULL) {
2447 		/*
2448 		 * Legacy path; interpret frame contents to decide
2449 		 * precisely how to send the frame.
2450 		 */
2451 		if (ath_tx_start(sc, ni, bf, m)) {
2452 			error = EIO;		/* XXX */
2453 			goto bad2;
2454 		}
2455 	} else {
2456 		/*
2457 		 * Caller supplied explicit parameters to use in
2458 		 * sending the frame.
2459 		 */
2460 		if (ath_tx_raw_start(sc, ni, bf, m, params)) {
2461 			error = EIO;		/* XXX */
2462 			goto bad2;
2463 		}
2464 	}
2465 	sc->sc_wd_timer = 5;
2466 	sc->sc_stats.ast_tx_raw++;
2467 
2468 	/*
2469 	 * Update the TIM - if there's anything queued to the
2470 	 * software queue and power save is enabled, we should
2471 	 * set the TIM.
2472 	 */
2473 	ath_tx_update_tim(sc, ni, 1);
2474 
2475 	ATH_TX_UNLOCK(sc);
2476 
2477 	ATH_PCU_LOCK(sc);
2478 	sc->sc_txstart_cnt--;
2479 	ATH_PCU_UNLOCK(sc);
2480 
2481 
2482 	/* Put the hardware back to sleep if required */
2483 	ATH_LOCK(sc);
2484 	ath_power_restore_power_state(sc);
2485 	ATH_UNLOCK(sc);
2486 
2487 	return 0;
2488 
2489 bad2:
2490 	ATH_KTR(sc, ATH_KTR_TX, 3, "ath_raw_xmit: bad2: m=%p, params=%p, "
2491 	    "bf=%p",
2492 	    m,
2493 	    params,
2494 	    bf);
2495 	ATH_TXBUF_LOCK(sc);
2496 	ath_returnbuf_head(sc, bf);
2497 	ATH_TXBUF_UNLOCK(sc);
2498 
2499 bad:
2500 	ATH_TX_UNLOCK(sc);
2501 
2502 	ATH_PCU_LOCK(sc);
2503 	sc->sc_txstart_cnt--;
2504 	ATH_PCU_UNLOCK(sc);
2505 
2506 	/* Put the hardware back to sleep if required */
2507 	ATH_LOCK(sc);
2508 	ath_power_restore_power_state(sc);
2509 	ATH_UNLOCK(sc);
2510 
2511 badbad:
2512 	ATH_KTR(sc, ATH_KTR_TX, 2, "ath_raw_xmit: bad0: m=%p, params=%p",
2513 	    m, params);
2514 	sc->sc_stats.ast_tx_raw_fail++;
2515 
2516 	return error;
2517 }
2518 
2519 /* Some helper functions */
2520 
2521 /*
2522  * ADDBA (and potentially others) need to be placed in the same
2523  * hardware queue as the TID/node it's relating to. This is so
2524  * it goes out after any pending non-aggregate frames to the
2525  * same node/TID.
2526  *
2527  * If this isn't done, the ADDBA can go out before the frames
2528  * queued in hardware. Even though these frames have a sequence
2529  * number -earlier- than the ADDBA can be transmitted (but
2530  * no frames whose sequence numbers are after the ADDBA should
2531  * be!) they'll arrive after the ADDBA - and the receiving end
2532  * will simply drop them as being out of the BAW.
2533  *
2534  * The frames can't be appended to the TID software queue - it'll
2535  * never be sent out. So these frames have to be directly
2536  * dispatched to the hardware, rather than queued in software.
2537  * So if this function returns true, the TXQ has to be
2538  * overridden and it has to be directly dispatched.
2539  *
2540  * It's a dirty hack, but someone's gotta do it.
2541  */
2542 
2543 /*
2544  * XXX doesn't belong here!
2545  */
2546 static int
2547 ieee80211_is_action(struct ieee80211_frame *wh)
2548 {
2549 	/* Type: Management frame? */
2550 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) !=
2551 	    IEEE80211_FC0_TYPE_MGT)
2552 		return 0;
2553 
2554 	/* Subtype: Action frame? */
2555 	if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) !=
2556 	    IEEE80211_FC0_SUBTYPE_ACTION)
2557 		return 0;
2558 
2559 	return 1;
2560 }
2561 
2562 #define	MS(_v, _f)	(((_v) & _f) >> _f##_S)
2563 /*
2564  * Return an alternate TID for ADDBA request frames.
2565  *
2566  * Yes, this likely should be done in the net80211 layer.
2567  */
2568 static int
2569 ath_tx_action_frame_override_queue(struct ath_softc *sc,
2570     struct ieee80211_node *ni,
2571     struct mbuf *m0, int *tid)
2572 {
2573 	struct ieee80211_frame *wh = mtod(m0, struct ieee80211_frame *);
2574 	struct ieee80211_action_ba_addbarequest *ia;
2575 	uint8_t *frm;
2576 	uint16_t baparamset;
2577 
2578 	/* Not action frame? Bail */
2579 	if (! ieee80211_is_action(wh))
2580 		return 0;
2581 
2582 	/* XXX Not needed for frames we send? */
2583 #if 0
2584 	/* Correct length? */
2585 	if (! ieee80211_parse_action(ni, m))
2586 		return 0;
2587 #endif
2588 
2589 	/* Extract out action frame */
2590 	frm = (u_int8_t *)&wh[1];
2591 	ia = (struct ieee80211_action_ba_addbarequest *) frm;
2592 
2593 	/* Not ADDBA? Bail */
2594 	if (ia->rq_header.ia_category != IEEE80211_ACTION_CAT_BA)
2595 		return 0;
2596 	if (ia->rq_header.ia_action != IEEE80211_ACTION_BA_ADDBA_REQUEST)
2597 		return 0;
2598 
2599 	/* Extract TID, return it */
2600 	baparamset = le16toh(ia->rq_baparamset);
2601 	*tid = (int) MS(baparamset, IEEE80211_BAPS_TID);
2602 
2603 	return 1;
2604 }
2605 #undef	MS
2606 
2607 /* Per-node software queue operations */
2608 
2609 /*
2610  * Add the current packet to the given BAW.
2611  * It is assumed that the current packet
2612  *
2613  * + fits inside the BAW;
2614  * + already has had a sequence number allocated.
2615  *
2616  * Since the BAW status may be modified by both the ath task and
2617  * the net80211/ifnet contexts, the TID must be locked.
2618  */
2619 void
2620 ath_tx_addto_baw(struct ath_softc *sc, struct ath_node *an,
2621     struct ath_tid *tid, struct ath_buf *bf)
2622 {
2623 	int index, cindex;
2624 	struct ieee80211_tx_ampdu *tap;
2625 
2626 	ATH_TX_LOCK_ASSERT(sc);
2627 
2628 	if (bf->bf_state.bfs_isretried)
2629 		return;
2630 
2631 	tap = ath_tx_get_tx_tid(an, tid->tid);
2632 
2633 	if (! bf->bf_state.bfs_dobaw) {
2634 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2635 		    "%s: dobaw=0, seqno=%d, window %d:%d\n",
2636 		    __func__, SEQNO(bf->bf_state.bfs_seqno),
2637 		    tap->txa_start, tap->txa_wnd);
2638 	}
2639 
2640 	if (bf->bf_state.bfs_addedbaw)
2641 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2642 		    "%s: re-added? tid=%d, seqno %d; window %d:%d; "
2643 		    "baw head=%d tail=%d\n",
2644 		    __func__, tid->tid, SEQNO(bf->bf_state.bfs_seqno),
2645 		    tap->txa_start, tap->txa_wnd, tid->baw_head,
2646 		    tid->baw_tail);
2647 
2648 	/*
2649 	 * Verify that the given sequence number is not outside of the
2650 	 * BAW.  Complain loudly if that's the case.
2651 	 */
2652 	if (! BAW_WITHIN(tap->txa_start, tap->txa_wnd,
2653 	    SEQNO(bf->bf_state.bfs_seqno))) {
2654 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2655 		    "%s: bf=%p: outside of BAW?? tid=%d, seqno %d; window %d:%d; "
2656 		    "baw head=%d tail=%d\n",
2657 		    __func__, bf, tid->tid, SEQNO(bf->bf_state.bfs_seqno),
2658 		    tap->txa_start, tap->txa_wnd, tid->baw_head,
2659 		    tid->baw_tail);
2660 	}
2661 
2662 	/*
2663 	 * ni->ni_txseqs[] is the currently allocated seqno.
2664 	 * the txa state contains the current baw start.
2665 	 */
2666 	index  = ATH_BA_INDEX(tap->txa_start, SEQNO(bf->bf_state.bfs_seqno));
2667 	cindex = (tid->baw_head + index) & (ATH_TID_MAX_BUFS - 1);
2668 	DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2669 	    "%s: tid=%d, seqno %d; window %d:%d; index=%d cindex=%d "
2670 	    "baw head=%d tail=%d\n",
2671 	    __func__, tid->tid, SEQNO(bf->bf_state.bfs_seqno),
2672 	    tap->txa_start, tap->txa_wnd, index, cindex, tid->baw_head,
2673 	    tid->baw_tail);
2674 
2675 
2676 #if 0
2677 	assert(tid->tx_buf[cindex] == NULL);
2678 #endif
2679 	if (tid->tx_buf[cindex] != NULL) {
2680 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2681 		    "%s: ba packet dup (index=%d, cindex=%d, "
2682 		    "head=%d, tail=%d)\n",
2683 		    __func__, index, cindex, tid->baw_head, tid->baw_tail);
2684 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2685 		    "%s: BA bf: %p; seqno=%d ; new bf: %p; seqno=%d\n",
2686 		    __func__,
2687 		    tid->tx_buf[cindex],
2688 		    SEQNO(tid->tx_buf[cindex]->bf_state.bfs_seqno),
2689 		    bf,
2690 		    SEQNO(bf->bf_state.bfs_seqno)
2691 		);
2692 	}
2693 	tid->tx_buf[cindex] = bf;
2694 
2695 	if (index >= ((tid->baw_tail - tid->baw_head) &
2696 	    (ATH_TID_MAX_BUFS - 1))) {
2697 		tid->baw_tail = cindex;
2698 		INCR(tid->baw_tail, ATH_TID_MAX_BUFS);
2699 	}
2700 }
2701 
2702 /*
2703  * Flip the BAW buffer entry over from the existing one to the new one.
2704  *
2705  * When software retransmitting a (sub-)frame, it is entirely possible that
2706  * the frame ath_buf is marked as BUSY and can't be immediately reused.
2707  * In that instance the buffer is cloned and the new buffer is used for
2708  * retransmit. We thus need to update the ath_buf slot in the BAW buf
2709  * tracking array to maintain consistency.
2710  */
2711 static void
2712 ath_tx_switch_baw_buf(struct ath_softc *sc, struct ath_node *an,
2713     struct ath_tid *tid, struct ath_buf *old_bf, struct ath_buf *new_bf)
2714 {
2715 	int index, cindex;
2716 	struct ieee80211_tx_ampdu *tap;
2717 	int seqno = SEQNO(old_bf->bf_state.bfs_seqno);
2718 
2719 	ATH_TX_LOCK_ASSERT(sc);
2720 
2721 	tap = ath_tx_get_tx_tid(an, tid->tid);
2722 	index  = ATH_BA_INDEX(tap->txa_start, seqno);
2723 	cindex = (tid->baw_head + index) & (ATH_TID_MAX_BUFS - 1);
2724 
2725 	/*
2726 	 * Just warn for now; if it happens then we should find out
2727 	 * about it. It's highly likely the aggregation session will
2728 	 * soon hang.
2729 	 */
2730 	if (old_bf->bf_state.bfs_seqno != new_bf->bf_state.bfs_seqno) {
2731 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2732 		    "%s: retransmitted buffer"
2733 		    " has mismatching seqno's, BA session may hang.\n",
2734 		    __func__);
2735 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2736 		    "%s: old seqno=%d, new_seqno=%d\n", __func__,
2737 		    old_bf->bf_state.bfs_seqno, new_bf->bf_state.bfs_seqno);
2738 	}
2739 
2740 	if (tid->tx_buf[cindex] != old_bf) {
2741 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2742 		    "%s: ath_buf pointer incorrect; "
2743 		    " has m BA session may hang.\n", __func__);
2744 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2745 		    "%s: old bf=%p, new bf=%p\n", __func__, old_bf, new_bf);
2746 	}
2747 
2748 	tid->tx_buf[cindex] = new_bf;
2749 }
2750 
2751 /*
2752  * seq_start - left edge of BAW
2753  * seq_next - current/next sequence number to allocate
2754  *
2755  * Since the BAW status may be modified by both the ath task and
2756  * the net80211/ifnet contexts, the TID must be locked.
2757  */
2758 static void
2759 ath_tx_update_baw(struct ath_softc *sc, struct ath_node *an,
2760     struct ath_tid *tid, const struct ath_buf *bf)
2761 {
2762 	int index, cindex;
2763 	struct ieee80211_tx_ampdu *tap;
2764 	int seqno = SEQNO(bf->bf_state.bfs_seqno);
2765 
2766 	ATH_TX_LOCK_ASSERT(sc);
2767 
2768 	tap = ath_tx_get_tx_tid(an, tid->tid);
2769 	index  = ATH_BA_INDEX(tap->txa_start, seqno);
2770 	cindex = (tid->baw_head + index) & (ATH_TID_MAX_BUFS - 1);
2771 
2772 	DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2773 	    "%s: tid=%d, baw=%d:%d, seqno=%d, index=%d, cindex=%d, "
2774 	    "baw head=%d, tail=%d\n",
2775 	    __func__, tid->tid, tap->txa_start, tap->txa_wnd, seqno, index,
2776 	    cindex, tid->baw_head, tid->baw_tail);
2777 
2778 	/*
2779 	 * If this occurs then we have a big problem - something else
2780 	 * has slid tap->txa_start along without updating the BAW
2781 	 * tracking start/end pointers. Thus the TX BAW state is now
2782 	 * completely busted.
2783 	 *
2784 	 * But for now, since I haven't yet fixed TDMA and buffer cloning,
2785 	 * it's quite possible that a cloned buffer is making its way
2786 	 * here and causing it to fire off. Disable TDMA for now.
2787 	 */
2788 	if (tid->tx_buf[cindex] != bf) {
2789 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2790 		    "%s: comp bf=%p, seq=%d; slot bf=%p, seqno=%d\n",
2791 		    __func__, bf, SEQNO(bf->bf_state.bfs_seqno),
2792 		    tid->tx_buf[cindex],
2793 		    (tid->tx_buf[cindex] != NULL) ?
2794 		      SEQNO(tid->tx_buf[cindex]->bf_state.bfs_seqno) : -1);
2795 	}
2796 
2797 	tid->tx_buf[cindex] = NULL;
2798 
2799 	while (tid->baw_head != tid->baw_tail &&
2800 	    !tid->tx_buf[tid->baw_head]) {
2801 		INCR(tap->txa_start, IEEE80211_SEQ_RANGE);
2802 		INCR(tid->baw_head, ATH_TID_MAX_BUFS);
2803 	}
2804 	DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
2805 	    "%s: tid=%d: baw is now %d:%d, baw head=%d\n",
2806 	    __func__, tid->tid, tap->txa_start, tap->txa_wnd, tid->baw_head);
2807 }
2808 
2809 static void
2810 ath_tx_leak_count_update(struct ath_softc *sc, struct ath_tid *tid,
2811     struct ath_buf *bf)
2812 {
2813 	struct ieee80211_frame *wh;
2814 
2815 	ATH_TX_LOCK_ASSERT(sc);
2816 
2817 	if (tid->an->an_leak_count > 0) {
2818 		wh = mtod(bf->bf_m, struct ieee80211_frame *);
2819 
2820 		/*
2821 		 * Update MORE based on the software/net80211 queue states.
2822 		 */
2823 		if ((tid->an->an_stack_psq > 0)
2824 		    || (tid->an->an_swq_depth > 0))
2825 			wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
2826 		else
2827 			wh->i_fc[1] &= ~IEEE80211_FC1_MORE_DATA;
2828 
2829 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
2830 		    "%s: %6D: leak count = %d, psq=%d, swq=%d, MORE=%d\n",
2831 		    __func__,
2832 		    tid->an->an_node.ni_macaddr,
2833 		    ":",
2834 		    tid->an->an_leak_count,
2835 		    tid->an->an_stack_psq,
2836 		    tid->an->an_swq_depth,
2837 		    !! (wh->i_fc[1] & IEEE80211_FC1_MORE_DATA));
2838 
2839 		/*
2840 		 * Re-sync the underlying buffer.
2841 		 */
2842 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
2843 		    BUS_DMASYNC_PREWRITE);
2844 
2845 		tid->an->an_leak_count --;
2846 	}
2847 }
2848 
2849 static int
2850 ath_tx_tid_can_tx_or_sched(struct ath_softc *sc, struct ath_tid *tid)
2851 {
2852 
2853 	ATH_TX_LOCK_ASSERT(sc);
2854 
2855 	if (tid->an->an_leak_count > 0) {
2856 		return (1);
2857 	}
2858 	if (tid->paused)
2859 		return (0);
2860 	return (1);
2861 }
2862 
2863 /*
2864  * Mark the current node/TID as ready to TX.
2865  *
2866  * This is done to make it easy for the software scheduler to
2867  * find which nodes have data to send.
2868  *
2869  * The TXQ lock must be held.
2870  */
2871 void
2872 ath_tx_tid_sched(struct ath_softc *sc, struct ath_tid *tid)
2873 {
2874 	struct ath_txq *txq = sc->sc_ac2q[tid->ac];
2875 
2876 	ATH_TX_LOCK_ASSERT(sc);
2877 
2878 	/*
2879 	 * If we are leaking out a frame to this destination
2880 	 * for PS-POLL, ensure that we allow scheduling to
2881 	 * occur.
2882 	 */
2883 	if (! ath_tx_tid_can_tx_or_sched(sc, tid))
2884 		return;		/* paused, can't schedule yet */
2885 
2886 	if (tid->sched)
2887 		return;		/* already scheduled */
2888 
2889 	tid->sched = 1;
2890 
2891 #if 0
2892 	/*
2893 	 * If this is a sleeping node we're leaking to, given
2894 	 * it a higher priority.  This is so bad for QoS it hurts.
2895 	 */
2896 	if (tid->an->an_leak_count) {
2897 		TAILQ_INSERT_HEAD(&txq->axq_tidq, tid, axq_qelem);
2898 	} else {
2899 		TAILQ_INSERT_TAIL(&txq->axq_tidq, tid, axq_qelem);
2900 	}
2901 #endif
2902 
2903 	/*
2904 	 * We can't do the above - it'll confuse the TXQ software
2905 	 * scheduler which will keep checking the _head_ TID
2906 	 * in the list to see if it has traffic.  If we queue
2907 	 * a TID to the head of the list and it doesn't transmit,
2908 	 * we'll check it again.
2909 	 *
2910 	 * So, get the rest of this leaking frames support working
2911 	 * and reliable first and _then_ optimise it so they're
2912 	 * pushed out in front of any other pending software
2913 	 * queued nodes.
2914 	 */
2915 	TAILQ_INSERT_TAIL(&txq->axq_tidq, tid, axq_qelem);
2916 }
2917 
2918 /*
2919  * Mark the current node as no longer needing to be polled for
2920  * TX packets.
2921  *
2922  * The TXQ lock must be held.
2923  */
2924 static void
2925 ath_tx_tid_unsched(struct ath_softc *sc, struct ath_tid *tid)
2926 {
2927 	struct ath_txq *txq = sc->sc_ac2q[tid->ac];
2928 
2929 	ATH_TX_LOCK_ASSERT(sc);
2930 
2931 	if (tid->sched == 0)
2932 		return;
2933 
2934 	tid->sched = 0;
2935 	TAILQ_REMOVE(&txq->axq_tidq, tid, axq_qelem);
2936 }
2937 
2938 /*
2939  * Assign a sequence number manually to the given frame.
2940  *
2941  * This should only be called for A-MPDU TX frames.
2942  */
2943 static ieee80211_seq
2944 ath_tx_tid_seqno_assign(struct ath_softc *sc, struct ieee80211_node *ni,
2945     struct ath_buf *bf, struct mbuf *m0)
2946 {
2947 	struct ieee80211_frame *wh;
2948 	int tid, pri;
2949 	ieee80211_seq seqno;
2950 	uint8_t subtype;
2951 
2952 	/* TID lookup */
2953 	wh = mtod(m0, struct ieee80211_frame *);
2954 	pri = M_WME_GETAC(m0);			/* honor classification */
2955 	tid = WME_AC_TO_TID(pri);
2956 	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: pri=%d, tid=%d, qos has seq=%d\n",
2957 	    __func__, pri, tid, IEEE80211_QOS_HAS_SEQ(wh));
2958 
2959 	/* XXX Is it a control frame? Ignore */
2960 
2961 	/* Does the packet require a sequence number? */
2962 	if (! IEEE80211_QOS_HAS_SEQ(wh))
2963 		return -1;
2964 
2965 	ATH_TX_LOCK_ASSERT(sc);
2966 
2967 	/*
2968 	 * Is it a QOS NULL Data frame? Give it a sequence number from
2969 	 * the default TID (IEEE80211_NONQOS_TID.)
2970 	 *
2971 	 * The RX path of everything I've looked at doesn't include the NULL
2972 	 * data frame sequence number in the aggregation state updates, so
2973 	 * assigning it a sequence number there will cause a BAW hole on the
2974 	 * RX side.
2975 	 */
2976 	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
2977 	if (subtype == IEEE80211_FC0_SUBTYPE_QOS_NULL) {
2978 		/* XXX no locking for this TID? This is a bit of a problem. */
2979 		seqno = ni->ni_txseqs[IEEE80211_NONQOS_TID];
2980 		INCR(ni->ni_txseqs[IEEE80211_NONQOS_TID], IEEE80211_SEQ_RANGE);
2981 	} else {
2982 		/* Manually assign sequence number */
2983 		seqno = ni->ni_txseqs[tid];
2984 		INCR(ni->ni_txseqs[tid], IEEE80211_SEQ_RANGE);
2985 	}
2986 	*(uint16_t *)&wh->i_seq[0] = htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
2987 	M_SEQNO_SET(m0, seqno);
2988 
2989 	/* Return so caller can do something with it if needed */
2990 	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s:  -> seqno=%d\n", __func__, seqno);
2991 	return seqno;
2992 }
2993 
2994 /*
2995  * Attempt to direct dispatch an aggregate frame to hardware.
2996  * If the frame is out of BAW, queue.
2997  * Otherwise, schedule it as a single frame.
2998  */
2999 static void
3000 ath_tx_xmit_aggr(struct ath_softc *sc, struct ath_node *an,
3001     struct ath_txq *txq, struct ath_buf *bf)
3002 {
3003 	struct ath_tid *tid = &an->an_tid[bf->bf_state.bfs_tid];
3004 	struct ieee80211_tx_ampdu *tap;
3005 
3006 	ATH_TX_LOCK_ASSERT(sc);
3007 
3008 	tap = ath_tx_get_tx_tid(an, tid->tid);
3009 
3010 	/* paused? queue */
3011 	if (! ath_tx_tid_can_tx_or_sched(sc, tid)) {
3012 		ATH_TID_INSERT_HEAD(tid, bf, bf_list);
3013 		/* XXX don't sched - we're paused! */
3014 		return;
3015 	}
3016 
3017 	/* outside baw? queue */
3018 	if (bf->bf_state.bfs_dobaw &&
3019 	    (! BAW_WITHIN(tap->txa_start, tap->txa_wnd,
3020 	    SEQNO(bf->bf_state.bfs_seqno)))) {
3021 		ATH_TID_INSERT_HEAD(tid, bf, bf_list);
3022 		ath_tx_tid_sched(sc, tid);
3023 		return;
3024 	}
3025 
3026 	/*
3027 	 * This is a temporary check and should be removed once
3028 	 * all the relevant code paths have been fixed.
3029 	 *
3030 	 * During aggregate retries, it's possible that the head
3031 	 * frame will fail (which has the bfs_aggr and bfs_nframes
3032 	 * fields set for said aggregate) and will be retried as
3033 	 * a single frame.  In this instance, the values should
3034 	 * be reset or the completion code will get upset with you.
3035 	 */
3036 	if (bf->bf_state.bfs_aggr != 0 || bf->bf_state.bfs_nframes > 1) {
3037 		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
3038 		    "%s: bfs_aggr=%d, bfs_nframes=%d\n", __func__,
3039 		    bf->bf_state.bfs_aggr, bf->bf_state.bfs_nframes);
3040 		bf->bf_state.bfs_aggr = 0;
3041 		bf->bf_state.bfs_nframes = 1;
3042 	}
3043 
3044 	/* Update CLRDMASK just before this frame is queued */
3045 	ath_tx_update_clrdmask(sc, tid, bf);
3046 
3047 	/* Direct dispatch to hardware */
3048 	ath_tx_do_ratelookup(sc, bf);
3049 	ath_tx_calc_duration(sc, bf);
3050 	ath_tx_calc_protection(sc, bf);
3051 	ath_tx_set_rtscts(sc, bf);
3052 	ath_tx_rate_fill_rcflags(sc, bf);
3053 	ath_tx_setds(sc, bf);
3054 
3055 	/* Statistics */
3056 	sc->sc_aggr_stats.aggr_low_hwq_single_pkt++;
3057 
3058 	/* Track per-TID hardware queue depth correctly */
3059 	tid->hwq_depth++;
3060 
3061 	/* Add to BAW */
3062 	if (bf->bf_state.bfs_dobaw) {
3063 		ath_tx_addto_baw(sc, an, tid, bf);
3064 		bf->bf_state.bfs_addedbaw = 1;
3065 	}
3066 
3067 	/* Set completion handler, multi-frame aggregate or not */
3068 	bf->bf_comp = ath_tx_aggr_comp;
3069 
3070 	/*
3071 	 * Update the current leak count if
3072 	 * we're leaking frames; and set the
3073 	 * MORE flag as appropriate.
3074 	 */
3075 	ath_tx_leak_count_update(sc, tid, bf);
3076 
3077 	/* Hand off to hardware */
3078 	ath_tx_handoff(sc, txq, bf);
3079 }
3080 
3081 /*
3082  * Attempt to send the packet.
3083  * If the queue isn't busy, direct-dispatch.
3084  * If the queue is busy enough, queue the given packet on the
3085  *  relevant software queue.
3086  */
3087 void
3088 ath_tx_swq(struct ath_softc *sc, struct ieee80211_node *ni,
3089     struct ath_txq *txq, int queue_to_head, struct ath_buf *bf)
3090 {
3091 	struct ath_node *an = ATH_NODE(ni);
3092 	struct ieee80211_frame *wh;
3093 	struct ath_tid *atid;
3094 	int pri, tid;
3095 	struct mbuf *m0 = bf->bf_m;
3096 
3097 	ATH_TX_LOCK_ASSERT(sc);
3098 
3099 	/* Fetch the TID - non-QoS frames get assigned to TID 16 */
3100 	wh = mtod(m0, struct ieee80211_frame *);
3101 	pri = ath_tx_getac(sc, m0);
3102 	tid = ath_tx_gettid(sc, m0);
3103 	atid = &an->an_tid[tid];
3104 
3105 	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: bf=%p, pri=%d, tid=%d, qos=%d\n",
3106 	    __func__, bf, pri, tid, IEEE80211_QOS_HAS_SEQ(wh));
3107 
3108 	/* Set local packet state, used to queue packets to hardware */
3109 	/* XXX potentially duplicate info, re-check */
3110 	bf->bf_state.bfs_tid = tid;
3111 	bf->bf_state.bfs_tx_queue = txq->axq_qnum;
3112 	bf->bf_state.bfs_pri = pri;
3113 
3114 	/*
3115 	 * If the hardware queue isn't busy, queue it directly.
3116 	 * If the hardware queue is busy, queue it.
3117 	 * If the TID is paused or the traffic it outside BAW, software
3118 	 * queue it.
3119 	 *
3120 	 * If the node is in power-save and we're leaking a frame,
3121 	 * leak a single frame.
3122 	 */
3123 	if (! ath_tx_tid_can_tx_or_sched(sc, atid)) {
3124 		/* TID is paused, queue */
3125 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: paused\n", __func__);
3126 		/*
3127 		 * If the caller requested that it be sent at a high
3128 		 * priority, queue it at the head of the list.
3129 		 */
3130 		if (queue_to_head)
3131 			ATH_TID_INSERT_HEAD(atid, bf, bf_list);
3132 		else
3133 			ATH_TID_INSERT_TAIL(atid, bf, bf_list);
3134 	} else if (ath_tx_ampdu_pending(sc, an, tid)) {
3135 		/* AMPDU pending; queue */
3136 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: pending\n", __func__);
3137 		ATH_TID_INSERT_TAIL(atid, bf, bf_list);
3138 		/* XXX sched? */
3139 	} else if (ath_tx_ampdu_running(sc, an, tid)) {
3140 		/* AMPDU running, attempt direct dispatch if possible */
3141 
3142 		/*
3143 		 * Always queue the frame to the tail of the list.
3144 		 */
3145 		ATH_TID_INSERT_TAIL(atid, bf, bf_list);
3146 
3147 		/*
3148 		 * If the hardware queue isn't busy, direct dispatch
3149 		 * the head frame in the list.  Don't schedule the
3150 		 * TID - let it build some more frames first?
3151 		 *
3152 		 * When running A-MPDU, always just check the hardware
3153 		 * queue depth against the aggregate frame limit.
3154 		 * We don't want to burst a large number of single frames
3155 		 * out to the hardware; we want to aggressively hold back.
3156 		 *
3157 		 * Otherwise, schedule the TID.
3158 		 */
3159 		/* XXX TXQ locking */
3160 		if (txq->axq_depth + txq->fifo.axq_depth < sc->sc_hwq_limit_aggr) {
3161 			bf = ATH_TID_FIRST(atid);
3162 			ATH_TID_REMOVE(atid, bf, bf_list);
3163 
3164 			/*
3165 			 * Ensure it's definitely treated as a non-AMPDU
3166 			 * frame - this information may have been left
3167 			 * over from a previous attempt.
3168 			 */
3169 			bf->bf_state.bfs_aggr = 0;
3170 			bf->bf_state.bfs_nframes = 1;
3171 
3172 			/* Queue to the hardware */
3173 			ath_tx_xmit_aggr(sc, an, txq, bf);
3174 			DPRINTF(sc, ATH_DEBUG_SW_TX,
3175 			    "%s: xmit_aggr\n",
3176 			    __func__);
3177 		} else {
3178 			DPRINTF(sc, ATH_DEBUG_SW_TX,
3179 			    "%s: ampdu; swq'ing\n",
3180 			    __func__);
3181 
3182 			ath_tx_tid_sched(sc, atid);
3183 		}
3184 	/*
3185 	 * If we're not doing A-MPDU, be prepared to direct dispatch
3186 	 * up to both limits if possible.  This particular corner
3187 	 * case may end up with packet starvation between aggregate
3188 	 * traffic and non-aggregate traffic: we want to ensure
3189 	 * that non-aggregate stations get a few frames queued to the
3190 	 * hardware before the aggregate station(s) get their chance.
3191 	 *
3192 	 * So if you only ever see a couple of frames direct dispatched
3193 	 * to the hardware from a non-AMPDU client, check both here
3194 	 * and in the software queue dispatcher to ensure that those
3195 	 * non-AMPDU stations get a fair chance to transmit.
3196 	 */
3197 	/* XXX TXQ locking */
3198 	} else if ((txq->axq_depth + txq->fifo.axq_depth < sc->sc_hwq_limit_nonaggr) &&
3199 		    (txq->axq_aggr_depth < sc->sc_hwq_limit_aggr)) {
3200 		/* AMPDU not running, attempt direct dispatch */
3201 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: xmit_normal\n", __func__);
3202 		/* See if clrdmask needs to be set */
3203 		ath_tx_update_clrdmask(sc, atid, bf);
3204 
3205 		/*
3206 		 * Update the current leak count if
3207 		 * we're leaking frames; and set the
3208 		 * MORE flag as appropriate.
3209 		 */
3210 		ath_tx_leak_count_update(sc, atid, bf);
3211 
3212 		/*
3213 		 * Dispatch the frame.
3214 		 */
3215 		ath_tx_xmit_normal(sc, txq, bf);
3216 	} else {
3217 		/* Busy; queue */
3218 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: swq'ing\n", __func__);
3219 		ATH_TID_INSERT_TAIL(atid, bf, bf_list);
3220 		ath_tx_tid_sched(sc, atid);
3221 	}
3222 }
3223 
3224 /*
3225  * Only set the clrdmask bit if none of the nodes are currently
3226  * filtered.
3227  *
3228  * XXX TODO: go through all the callers and check to see
3229  * which are being called in the context of looping over all
3230  * TIDs (eg, if all tids are being paused, resumed, etc.)
3231  * That'll avoid O(n^2) complexity here.
3232  */
3233 static void
3234 ath_tx_set_clrdmask(struct ath_softc *sc, struct ath_node *an)
3235 {
3236 	int i;
3237 
3238 	ATH_TX_LOCK_ASSERT(sc);
3239 
3240 	for (i = 0; i < IEEE80211_TID_SIZE; i++) {
3241 		if (an->an_tid[i].isfiltered == 1)
3242 			return;
3243 	}
3244 	an->clrdmask = 1;
3245 }
3246 
3247 /*
3248  * Configure the per-TID node state.
3249  *
3250  * This likely belongs in if_ath_node.c but I can't think of anywhere
3251  * else to put it just yet.
3252  *
3253  * This sets up the SLISTs and the mutex as appropriate.
3254  */
3255 void
3256 ath_tx_tid_init(struct ath_softc *sc, struct ath_node *an)
3257 {
3258 	int i, j;
3259 	struct ath_tid *atid;
3260 
3261 	for (i = 0; i < IEEE80211_TID_SIZE; i++) {
3262 		atid = &an->an_tid[i];
3263 
3264 		/* XXX now with this bzer(), is the field 0'ing needed? */
3265 		bzero(atid, sizeof(*atid));
3266 
3267 		TAILQ_INIT(&atid->tid_q);
3268 		TAILQ_INIT(&atid->filtq.tid_q);
3269 		atid->tid = i;
3270 		atid->an = an;
3271 		for (j = 0; j < ATH_TID_MAX_BUFS; j++)
3272 			atid->tx_buf[j] = NULL;
3273 		atid->baw_head = atid->baw_tail = 0;
3274 		atid->paused = 0;
3275 		atid->sched = 0;
3276 		atid->hwq_depth = 0;
3277 		atid->cleanup_inprogress = 0;
3278 		if (i == IEEE80211_NONQOS_TID)
3279 			atid->ac = ATH_NONQOS_TID_AC;
3280 		else
3281 			atid->ac = TID_TO_WME_AC(i);
3282 	}
3283 	an->clrdmask = 1;	/* Always start by setting this bit */
3284 }
3285 
3286 /*
3287  * Pause the current TID. This stops packets from being transmitted
3288  * on it.
3289  *
3290  * Since this is also called from upper layers as well as the driver,
3291  * it will get the TID lock.
3292  */
3293 static void
3294 ath_tx_tid_pause(struct ath_softc *sc, struct ath_tid *tid)
3295 {
3296 
3297 	ATH_TX_LOCK_ASSERT(sc);
3298 	tid->paused++;
3299 	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL, "%s: [%6D]: tid=%d, paused = %d\n",
3300 	    __func__,
3301 	    tid->an->an_node.ni_macaddr, ":",
3302 	    tid->tid,
3303 	    tid->paused);
3304 }
3305 
3306 /*
3307  * Unpause the current TID, and schedule it if needed.
3308  */
3309 static void
3310 ath_tx_tid_resume(struct ath_softc *sc, struct ath_tid *tid)
3311 {
3312 	ATH_TX_LOCK_ASSERT(sc);
3313 
3314 	/*
3315 	 * There's some odd places where ath_tx_tid_resume() is called
3316 	 * when it shouldn't be; this works around that particular issue
3317 	 * until it's actually resolved.
3318 	 */
3319 	if (tid->paused == 0) {
3320 		device_printf(sc->sc_dev,
3321 		    "%s: [%6D]: tid=%d, paused=0?\n",
3322 		    __func__,
3323 		    tid->an->an_node.ni_macaddr, ":",
3324 		    tid->tid);
3325 	} else {
3326 		tid->paused--;
3327 	}
3328 
3329 	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
3330 	    "%s: [%6D]: tid=%d, unpaused = %d\n",
3331 	    __func__,
3332 	    tid->an->an_node.ni_macaddr, ":",
3333 	    tid->tid,
3334 	    tid->paused);
3335 
3336 	if (tid->paused)
3337 		return;
3338 
3339 	/*
3340 	 * Override the clrdmask configuration for the next frame
3341 	 * from this TID, just to get the ball rolling.
3342 	 */
3343 	ath_tx_set_clrdmask(sc, tid->an);
3344 
3345 	if (tid->axq_depth == 0)
3346 		return;
3347 
3348 	/* XXX isfiltered shouldn't ever be 0 at this point */
3349 	if (tid->isfiltered == 1) {
3350 		DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL, "%s: filtered?!\n",
3351 		    __func__);
3352 		return;
3353 	}
3354 
3355 	ath_tx_tid_sched(sc, tid);
3356 
3357 	/*
3358 	 * Queue the software TX scheduler.
3359 	 */
3360 	ath_tx_swq_kick(sc);
3361 }
3362 
3363 /*
3364  * Add the given ath_buf to the TID filtered frame list.
3365  * This requires the TID be filtered.
3366  */
3367 static void
3368 ath_tx_tid_filt_addbuf(struct ath_softc *sc, struct ath_tid *tid,
3369     struct ath_buf *bf)
3370 {
3371 
3372 	ATH_TX_LOCK_ASSERT(sc);
3373 
3374 	if (!tid->isfiltered)
3375 		DPRINTF(sc, ATH_DEBUG_SW_TX_FILT, "%s: not filtered?!\n",
3376 		    __func__);
3377 
3378 	DPRINTF(sc, ATH_DEBUG_SW_TX_FILT, "%s: bf=%p\n", __func__, bf);
3379 
3380 	/* Set the retry bit and bump the retry counter */
3381 	ath_tx_set_retry(sc, bf);
3382 	sc->sc_stats.ast_tx_swfiltered++;
3383 
3384 	ATH_TID_FILT_INSERT_TAIL(tid, bf, bf_list);
3385 }
3386 
3387 /*
3388  * Handle a completed filtered frame from the given TID.
3389  * This just enables/pauses the filtered frame state if required
3390  * and appends the filtered frame to the filtered queue.
3391  */
3392 static void
3393 ath_tx_tid_filt_comp_buf(struct ath_softc *sc, struct ath_tid *tid,
3394     struct ath_buf *bf)
3395 {
3396 
3397 	ATH_TX_LOCK_ASSERT(sc);
3398 
3399 	if (! tid->isfiltered) {
3400 		DPRINTF(sc, ATH_DEBUG_SW_TX_FILT, "%s: tid=%d; filter transition\n",
3401 		    __func__, tid->tid);
3402 		tid->isfiltered = 1;
3403 		ath_tx_tid_pause(sc, tid);
3404 	}
3405 
3406 	/* Add the frame to the filter queue */
3407 	ath_tx_tid_filt_addbuf(sc, tid, bf);
3408 }
3409 
3410 /*
3411  * Complete the filtered frame TX completion.
3412  *
3413  * If there are no more frames in the hardware queue, unpause/unfilter
3414  * the TID if applicable.  Otherwise we will wait for a node PS transition
3415  * to unfilter.
3416  */
3417 static void
3418 ath_tx_tid_filt_comp_complete(struct ath_softc *sc, struct ath_tid *tid)
3419 {
3420 	struct ath_buf *bf;
3421 	int do_resume = 0;
3422 
3423 	ATH_TX_LOCK_ASSERT(sc);
3424 
3425 	if (tid->hwq_depth != 0)
3426 		return;
3427 
3428 	DPRINTF(sc, ATH_DEBUG_SW_TX_FILT, "%s: tid=%d, hwq=0, transition back\n",
3429 	    __func__, tid->tid);
3430 	if (tid->isfiltered == 1) {
3431 		tid->isfiltered = 0;
3432 		do_resume = 1;
3433 	}
3434 
3435 	/* XXX ath_tx_tid_resume() also calls ath_tx_set_clrdmask()! */
3436 	ath_tx_set_clrdmask(sc, tid->an);
3437 
3438 	/* XXX this is really quite inefficient */
3439 	while ((bf = ATH_TID_FILT_LAST(tid, ath_bufhead_s)) != NULL) {
3440 		ATH_TID_FILT_REMOVE(tid, bf, bf_list);
3441 		ATH_TID_INSERT_HEAD(tid, bf, bf_list);
3442 	}
3443 
3444 	/* And only resume if we had paused before */
3445 	if (do_resume)
3446 		ath_tx_tid_resume(sc, tid);
3447 }
3448 
3449 /*
3450  * Called when a single (aggregate or otherwise) frame is completed.
3451  *
3452  * Returns 0 if the buffer could be added to the filtered list
3453  * (cloned or otherwise), 1 if the buffer couldn't be added to the
3454  * filtered list (failed clone; expired retry) and the caller should
3455  * free it and handle it like a failure (eg by sending a BAR.)
3456  *
3457  * since the buffer may be cloned, bf must be not touched after this
3458  * if the return value is 0.
3459  */
3460 static int
3461 ath_tx_tid_filt_comp_single(struct ath_softc *sc, struct ath_tid *tid,
3462     struct ath_buf *bf)
3463 {
3464 	struct ath_buf *nbf;
3465 	int retval;
3466 
3467 	ATH_TX_LOCK_ASSERT(sc);
3468 
3469 	/*
3470 	 * Don't allow a filtered frame to live forever.
3471 	 */
3472 	if (bf->bf_state.bfs_retries > SWMAX_RETRIES) {
3473 		sc->sc_stats.ast_tx_swretrymax++;
3474 		DPRINTF(sc, ATH_DEBUG_SW_TX_FILT,
3475 		    "%s: bf=%p, seqno=%d, exceeded retries\n",
3476 		    __func__,
3477 		    bf,
3478 		    SEQNO(bf->bf_state.bfs_seqno));
3479 		retval = 1; /* error */
3480 		goto finish;
3481 	}
3482 
3483 	/*
3484 	 * A busy buffer can't be added to the retry list.
3485 	 * It needs to be cloned.
3486 	 */
3487 	if (bf->bf_flags & ATH_BUF_BUSY) {
3488 		nbf = ath_tx_retry_clone(sc, tid->an, tid, bf);
3489 		DPRINTF(sc, ATH_DEBUG_SW_TX_FILT,
3490 		    "%s: busy buffer clone: %p -> %p\n",
3491 		    __func__, bf, nbf);
3492 	} else {
3493 		nbf = bf;
3494 	}
3495 
3496 	if (nbf == NULL) {
3497 		DPRINTF(sc, ATH_DEBUG_SW_TX_FILT,
3498 		    "%s: busy buffer couldn't be cloned (%p)!\n",
3499 		    __func__, bf);
3500 		retval = 1; /* error */
3501 	} else {
3502 		ath_tx_tid_filt_comp_buf(sc, tid, nbf);
3503 		retval = 0; /* ok */
3504 	}
3505 finish:
3506 	ath_tx_tid_filt_comp_complete(sc, tid);
3507 
3508 	return (retval);
3509 }
3510 
3511 static void
3512 ath_tx_tid_filt_comp_aggr(struct ath_softc *sc, struct ath_tid *tid,
3513     struct ath_buf *bf_first, ath_bufhead *bf_q)
3514 {
3515 	struct ath_buf *bf, *bf_next, *nbf;
3516 
3517 	ATH_TX_LOCK_ASSERT(sc);
3518 
3519 	bf = bf_first;
3520 	while (bf) {
3521 		bf_next = bf->bf_next;
3522 		bf->bf_next = NULL;	/* Remove it from the aggr list */
3523 
3524 		/*
3525 		 * Don't allow a filtered frame to live forever.
3526 		 */
3527 		if (bf->bf_state.bfs_retries > SWMAX_RETRIES) {
3528 			sc->sc_stats.ast_tx_swretrymax++;
3529 			DPRINTF(sc, ATH_DEBUG_SW_TX_FILT,
3530 			    "%s: tid=%d, bf=%p, seqno=%d, exceeded retries\n",
3531 			    __func__,
3532 			    tid->tid,
3533 			    bf,
3534 			    SEQNO(bf->bf_state.bfs_seqno));
3535 			TAILQ_INSERT_TAIL(bf_q, bf, bf_list);
3536 			goto next;
3537 		}
3538 
3539 		if (bf->bf_flags & ATH_BUF_BUSY) {
3540 			nbf = ath_tx_retry_clone(sc, tid->an, tid, bf);
3541 			DPRINTF(sc, ATH_DEBUG_SW_TX_FILT,
3542 			    "%s: tid=%d, busy buffer cloned: %p -> %p, seqno=%d\n",
3543 			    __func__, tid->tid, bf, nbf, SEQNO(bf->bf_state.bfs_seqno));
3544 		} else {
3545 			nbf = bf;
3546 		}
3547 
3548 		/*
3549 		 * If the buffer couldn't be cloned, add it to bf_q;
3550 		 * the caller will free the buffer(s) as required.
3551 		 */
3552 		if (nbf == NULL) {
3553 			DPRINTF(sc, ATH_DEBUG_SW_TX_FILT,
3554 			    "%s: tid=%d, buffer couldn't be cloned! (%p) seqno=%d\n",
3555 			    __func__, tid->tid, bf, SEQNO(bf->bf_state.bfs_seqno));
3556 			TAILQ_INSERT_TAIL(bf_q, bf, bf_list);
3557 		} else {
3558 			ath_tx_tid_filt_comp_buf(sc, tid, nbf);
3559 		}
3560 next:
3561 		bf = bf_next;
3562 	}
3563 
3564 	ath_tx_tid_filt_comp_complete(sc, tid);
3565 }
3566 
3567 /*
3568  * Suspend the queue because we need to TX a BAR.
3569  */
3570 static void
3571 ath_tx_tid_bar_suspend(struct ath_softc *sc, struct ath_tid *tid)
3572 {
3573 
3574 	ATH_TX_LOCK_ASSERT(sc);
3575 
3576 	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
3577 	    "%s: tid=%d, bar_wait=%d, bar_tx=%d, called\n",
3578 	    __func__,
3579 	    tid->tid,
3580 	    tid->bar_wait,
3581 	    tid->bar_tx);
3582 
3583 	/* We shouldn't be called when bar_tx is 1 */
3584 	if (tid->bar_tx) {
3585 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
3586 		    "%s: bar_tx is 1?!\n", __func__);
3587 	}
3588 
3589 	/* If we've already been called, just be patient. */
3590 	if (tid->bar_wait)
3591 		return;
3592 
3593 	/* Wait! */
3594 	tid->bar_wait = 1;
3595 
3596 	/* Only one pause, no matter how many frames fail */
3597 	ath_tx_tid_pause(sc, tid);
3598 }
3599 
3600 /*
3601  * We've finished with BAR handling - either we succeeded or
3602  * failed. Either way, unsuspend TX.
3603  */
3604 static void
3605 ath_tx_tid_bar_unsuspend(struct ath_softc *sc, struct ath_tid *tid)
3606 {
3607 
3608 	ATH_TX_LOCK_ASSERT(sc);
3609 
3610 	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
3611 	    "%s: %6D: TID=%d, called\n",
3612 	    __func__,
3613 	    tid->an->an_node.ni_macaddr,
3614 	    ":",
3615 	    tid->tid);
3616 
3617 	if (tid->bar_tx == 0 || tid->bar_wait == 0) {
3618 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
3619 		    "%s: %6D: TID=%d, bar_tx=%d, bar_wait=%d: ?\n",
3620 		    __func__, tid->an->an_node.ni_macaddr, ":",
3621 		    tid->tid, tid->bar_tx, tid->bar_wait);
3622 	}
3623 
3624 	tid->bar_tx = tid->bar_wait = 0;
3625 	ath_tx_tid_resume(sc, tid);
3626 }
3627 
3628 /*
3629  * Return whether we're ready to TX a BAR frame.
3630  *
3631  * Requires the TID lock be held.
3632  */
3633 static int
3634 ath_tx_tid_bar_tx_ready(struct ath_softc *sc, struct ath_tid *tid)
3635 {
3636 
3637 	ATH_TX_LOCK_ASSERT(sc);
3638 
3639 	if (tid->bar_wait == 0 || tid->hwq_depth > 0)
3640 		return (0);
3641 
3642 	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
3643 	    "%s: %6D: TID=%d, bar ready\n",
3644 	    __func__,
3645 	    tid->an->an_node.ni_macaddr,
3646 	    ":",
3647 	    tid->tid);
3648 
3649 	return (1);
3650 }
3651 
3652 /*
3653  * Check whether the current TID is ready to have a BAR
3654  * TXed and if so, do the TX.
3655  *
3656  * Since the TID/TXQ lock can't be held during a call to
3657  * ieee80211_send_bar(), we have to do the dirty thing of unlocking it,
3658  * sending the BAR and locking it again.
3659  *
3660  * Eventually, the code to send the BAR should be broken out
3661  * from this routine so the lock doesn't have to be reacquired
3662  * just to be immediately dropped by the caller.
3663  */
3664 static void
3665 ath_tx_tid_bar_tx(struct ath_softc *sc, struct ath_tid *tid)
3666 {
3667 	struct ieee80211_tx_ampdu *tap;
3668 
3669 	ATH_TX_LOCK_ASSERT(sc);
3670 
3671 	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
3672 	    "%s: %6D: TID=%d, called\n",
3673 	    __func__,
3674 	    tid->an->an_node.ni_macaddr,
3675 	    ":",
3676 	    tid->tid);
3677 
3678 	tap = ath_tx_get_tx_tid(tid->an, tid->tid);
3679 
3680 	/*
3681 	 * This is an error condition!
3682 	 */
3683 	if (tid->bar_wait == 0 || tid->bar_tx == 1) {
3684 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
3685 		    "%s: %6D: TID=%d, bar_tx=%d, bar_wait=%d: ?\n",
3686 		    __func__, tid->an->an_node.ni_macaddr, ":",
3687 		    tid->tid, tid->bar_tx, tid->bar_wait);
3688 		return;
3689 	}
3690 
3691 	/* Don't do anything if we still have pending frames */
3692 	if (tid->hwq_depth > 0) {
3693 		DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
3694 		    "%s: %6D: TID=%d, hwq_depth=%d, waiting\n",
3695 		    __func__,
3696 		    tid->an->an_node.ni_macaddr,
3697 		    ":",
3698 		    tid->tid,
3699 		    tid->hwq_depth);
3700 		return;
3701 	}
3702 
3703 	/* We're now about to TX */
3704 	tid->bar_tx = 1;
3705 
3706 	/*
3707 	 * Override the clrdmask configuration for the next frame,
3708 	 * just to get the ball rolling.
3709 	 */
3710 	ath_tx_set_clrdmask(sc, tid->an);
3711 
3712 	/*
3713 	 * Calculate new BAW left edge, now that all frames have either
3714 	 * succeeded or failed.
3715 	 *
3716 	 * XXX verify this is _actually_ the valid value to begin at!
3717 	 */
3718 	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
3719 	    "%s: %6D: TID=%d, new BAW left edge=%d\n",
3720 	    __func__,
3721 	    tid->an->an_node.ni_macaddr,
3722 	    ":",
3723 	    tid->tid,
3724 	    tap->txa_start);
3725 
3726 	/* Try sending the BAR frame */
3727 	/* We can't hold the lock here! */
3728 
3729 	ATH_TX_UNLOCK(sc);
3730 	if (ieee80211_send_bar(&tid->an->an_node, tap, tap->txa_start) == 0) {
3731 		/* Success? Now we wait for notification that it's done */
3732 		ATH_TX_LOCK(sc);
3733 		return;
3734 	}
3735 
3736 	/* Failure? For now, warn loudly and continue */
3737 	ATH_TX_LOCK(sc);
3738 	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
3739 	    "%s: %6D: TID=%d, failed to TX BAR, continue!\n",
3740 	    __func__, tid->an->an_node.ni_macaddr, ":",
3741 	    tid->tid);
3742 	ath_tx_tid_bar_unsuspend(sc, tid);
3743 }
3744 
3745 static void
3746 ath_tx_tid_drain_pkt(struct ath_softc *sc, struct ath_node *an,
3747     struct ath_tid *tid, ath_bufhead *bf_cq, struct ath_buf *bf)
3748 {
3749 
3750 	ATH_TX_LOCK_ASSERT(sc);
3751 
3752 	/*
3753 	 * If the current TID is running AMPDU, update
3754 	 * the BAW.
3755 	 */
3756 	if (ath_tx_ampdu_running(sc, an, tid->tid) &&
3757 	    bf->bf_state.bfs_dobaw) {
3758 		/*
3759 		 * Only remove the frame from the BAW if it's
3760 		 * been transmitted at least once; this means
3761 		 * the frame was in the BAW to begin with.
3762 		 */
3763 		if (bf->bf_state.bfs_retries > 0) {
3764 			ath_tx_update_baw(sc, an, tid, bf);
3765 			bf->bf_state.bfs_dobaw = 0;
3766 		}
3767 #if 0
3768 		/*
3769 		 * This has become a non-fatal error now
3770 		 */
3771 		if (! bf->bf_state.bfs_addedbaw)
3772 			DPRINTF(sc, ATH_DEBUG_SW_TX_BAW
3773 			    "%s: wasn't added: seqno %d\n",
3774 			    __func__, SEQNO(bf->bf_state.bfs_seqno));
3775 #endif
3776 	}
3777 
3778 	/* Strip it out of an aggregate list if it was in one */
3779 	bf->bf_next = NULL;
3780 
3781 	/* Insert on the free queue to be freed by the caller */
3782 	TAILQ_INSERT_TAIL(bf_cq, bf, bf_list);
3783 }
3784 
3785 static void
3786 ath_tx_tid_drain_print(struct ath_softc *sc, struct ath_node *an,
3787     const char *pfx, struct ath_tid *tid, struct ath_buf *bf)
3788 {
3789 	struct ieee80211_node *ni = &an->an_node;
3790 	struct ath_txq *txq;
3791 	struct ieee80211_tx_ampdu *tap;
3792 
3793 	txq = sc->sc_ac2q[tid->ac];
3794 	tap = ath_tx_get_tx_tid(an, tid->tid);
3795 
3796 	DPRINTF(sc, ATH_DEBUG_SW_TX | ATH_DEBUG_RESET,
3797 	    "%s: %s: %6D: bf=%p: addbaw=%d, dobaw=%d, "
3798 	    "seqno=%d, retry=%d\n",
3799 	    __func__,
3800 	    pfx,
3801 	    ni->ni_macaddr,
3802 	    ":",
3803 	    bf,
3804 	    bf->bf_state.bfs_addedbaw,
3805 	    bf->bf_state.bfs_dobaw,
3806 	    SEQNO(bf->bf_state.bfs_seqno),
3807 	    bf->bf_state.bfs_retries);
3808 	DPRINTF(sc, ATH_DEBUG_SW_TX | ATH_DEBUG_RESET,
3809 	    "%s: %s: %6D: bf=%p: txq[%d] axq_depth=%d, axq_aggr_depth=%d\n",
3810 	    __func__,
3811 	    pfx,
3812 	    ni->ni_macaddr,
3813 	    ":",
3814 	    bf,
3815 	    txq->axq_qnum,
3816 	    txq->axq_depth,
3817 	    txq->axq_aggr_depth);
3818 	DPRINTF(sc, ATH_DEBUG_SW_TX | ATH_DEBUG_RESET,
3819 	    "%s: %s: %6D: bf=%p: tid txq_depth=%d hwq_depth=%d, bar_wait=%d, "
3820 	      "isfiltered=%d\n",
3821 	    __func__,
3822 	    pfx,
3823 	    ni->ni_macaddr,
3824 	    ":",
3825 	    bf,
3826 	    tid->axq_depth,
3827 	    tid->hwq_depth,
3828 	    tid->bar_wait,
3829 	    tid->isfiltered);
3830 	DPRINTF(sc, ATH_DEBUG_SW_TX | ATH_DEBUG_RESET,
3831 	    "%s: %s: %6D: tid %d: "
3832 	    "sched=%d, paused=%d, "
3833 	    "incomp=%d, baw_head=%d, "
3834 	    "baw_tail=%d txa_start=%d, ni_txseqs=%d\n",
3835 	     __func__,
3836 	     pfx,
3837 	     ni->ni_macaddr,
3838 	     ":",
3839 	     tid->tid,
3840 	     tid->sched, tid->paused,
3841 	     tid->incomp, tid->baw_head,
3842 	     tid->baw_tail, tap == NULL ? -1 : tap->txa_start,
3843 	     ni->ni_txseqs[tid->tid]);
3844 
3845 	/* XXX Dump the frame, see what it is? */
3846 	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
3847 		ieee80211_dump_pkt(ni->ni_ic,
3848 		    mtod(bf->bf_m, const uint8_t *),
3849 		    bf->bf_m->m_len, 0, -1);
3850 }
3851 
3852 /*
3853  * Free any packets currently pending in the software TX queue.
3854  *
3855  * This will be called when a node is being deleted.
3856  *
3857  * It can also be called on an active node during an interface
3858  * reset or state transition.
3859  *
3860  * (From Linux/reference):
3861  *
3862  * TODO: For frame(s) that are in the retry state, we will reuse the
3863  * sequence number(s) without setting the retry bit. The
3864  * alternative is to give up on these and BAR the receiver's window
3865  * forward.
3866  */
3867 static void
3868 ath_tx_tid_drain(struct ath_softc *sc, struct ath_node *an,
3869     struct ath_tid *tid, ath_bufhead *bf_cq)
3870 {
3871 	struct ath_buf *bf;
3872 	struct ieee80211_tx_ampdu *tap;
3873 	struct ieee80211_node *ni = &an->an_node;
3874 	int t;
3875 
3876 	tap = ath_tx_get_tx_tid(an, tid->tid);
3877 
3878 	ATH_TX_LOCK_ASSERT(sc);
3879 
3880 	/* Walk the queue, free frames */
3881 	t = 0;
3882 	for (;;) {
3883 		bf = ATH_TID_FIRST(tid);
3884 		if (bf == NULL) {
3885 			break;
3886 		}
3887 
3888 		if (t == 0) {
3889 			ath_tx_tid_drain_print(sc, an, "norm", tid, bf);
3890 //			t = 1;
3891 		}
3892 
3893 		ATH_TID_REMOVE(tid, bf, bf_list);
3894 		ath_tx_tid_drain_pkt(sc, an, tid, bf_cq, bf);
3895 	}
3896 
3897 	/* And now, drain the filtered frame queue */
3898 	t = 0;
3899 	for (;;) {
3900 		bf = ATH_TID_FILT_FIRST(tid);
3901 		if (bf == NULL)
3902 			break;
3903 
3904 		if (t == 0) {
3905 			ath_tx_tid_drain_print(sc, an, "filt", tid, bf);
3906 //			t = 1;
3907 		}
3908 
3909 		ATH_TID_FILT_REMOVE(tid, bf, bf_list);
3910 		ath_tx_tid_drain_pkt(sc, an, tid, bf_cq, bf);
3911 	}
3912 
3913 	/*
3914 	 * Override the clrdmask configuration for the next frame
3915 	 * in case there is some future transmission, just to get
3916 	 * the ball rolling.
3917 	 *
3918 	 * This won't hurt things if the TID is about to be freed.
3919 	 */
3920 	ath_tx_set_clrdmask(sc, tid->an);
3921 
3922 	/*
3923 	 * Now that it's completed, grab the TID lock and update
3924 	 * the sequence number and BAW window.
3925 	 * Because sequence numbers have been assigned to frames
3926 	 * that haven't been sent yet, it's entirely possible
3927 	 * we'll be called with some pending frames that have not
3928 	 * been transmitted.
3929 	 *
3930 	 * The cleaner solution is to do the sequence number allocation
3931 	 * when the packet is first transmitted - and thus the "retries"
3932 	 * check above would be enough to update the BAW/seqno.
3933 	 */
3934 
3935 	/* But don't do it for non-QoS TIDs */
3936 	if (tap) {
3937 #if 1
3938 		DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
3939 		    "%s: %6D: node %p: TID %d: sliding BAW left edge to %d\n",
3940 		    __func__,
3941 		    ni->ni_macaddr,
3942 		    ":",
3943 		    an,
3944 		    tid->tid,
3945 		    tap->txa_start);
3946 #endif
3947 		ni->ni_txseqs[tid->tid] = tap->txa_start;
3948 		tid->baw_tail = tid->baw_head;
3949 	}
3950 }
3951 
3952 /*
3953  * Reset the TID state.  This must be only called once the node has
3954  * had its frames flushed from this TID, to ensure that no other
3955  * pause / unpause logic can kick in.
3956  */
3957 static void
3958 ath_tx_tid_reset(struct ath_softc *sc, struct ath_tid *tid)
3959 {
3960 
3961 #if 0
3962 	tid->bar_wait = tid->bar_tx = tid->isfiltered = 0;
3963 	tid->paused = tid->sched = tid->addba_tx_pending = 0;
3964 	tid->incomp = tid->cleanup_inprogress = 0;
3965 #endif
3966 
3967 	/*
3968 	 * If we have a bar_wait set, we need to unpause the TID
3969 	 * here.  Otherwise once cleanup has finished, the TID won't
3970 	 * have the right paused counter.
3971 	 *
3972 	 * XXX I'm not going through resume here - I don't want the
3973 	 * node to be rescheuled just yet.  This however should be
3974 	 * methodized!
3975 	 */
3976 	if (tid->bar_wait) {
3977 		if (tid->paused > 0) {
3978 			tid->paused --;
3979 		}
3980 	}
3981 
3982 	/*
3983 	 * XXX same with a currently filtered TID.
3984 	 *
3985 	 * Since this is being called during a flush, we assume that
3986 	 * the filtered frame list is actually empty.
3987 	 *
3988 	 * XXX TODO: add in a check to ensure that the filtered queue
3989 	 * depth is actually 0!
3990 	 */
3991 	if (tid->isfiltered) {
3992 		if (tid->paused > 0) {
3993 			tid->paused --;
3994 		}
3995 	}
3996 
3997 	/*
3998 	 * Clear BAR, filtered frames, scheduled and ADDBA pending.
3999 	 * The TID may be going through cleanup from the last association
4000 	 * where things in the BAW are still in the hardware queue.
4001 	 */
4002 	tid->bar_wait = 0;
4003 	tid->bar_tx = 0;
4004 	tid->isfiltered = 0;
4005 	tid->sched = 0;
4006 	tid->addba_tx_pending = 0;
4007 
4008 	/*
4009 	 * XXX TODO: it may just be enough to walk the HWQs and mark
4010 	 * frames for that node as non-aggregate; or mark the ath_node
4011 	 * with something that indicates that aggregation is no longer
4012 	 * occurring.  Then we can just toss the BAW complaints and
4013 	 * do a complete hard reset of state here - no pause, no
4014 	 * complete counter, etc.
4015 	 */
4016 
4017 }
4018 
4019 /*
4020  * Flush all software queued packets for the given node.
4021  *
4022  * This occurs when a completion handler frees the last buffer
4023  * for a node, and the node is thus freed. This causes the node
4024  * to be cleaned up, which ends up calling ath_tx_node_flush.
4025  */
4026 void
4027 ath_tx_node_flush(struct ath_softc *sc, struct ath_node *an)
4028 {
4029 	int tid;
4030 	ath_bufhead bf_cq;
4031 	struct ath_buf *bf;
4032 
4033 	TAILQ_INIT(&bf_cq);
4034 
4035 	ATH_KTR(sc, ATH_KTR_NODE, 1, "ath_tx_node_flush: flush node; ni=%p",
4036 	    &an->an_node);
4037 
4038 	ATH_TX_LOCK(sc);
4039 	DPRINTF(sc, ATH_DEBUG_NODE,
4040 	    "%s: %6D: flush; is_powersave=%d, stack_psq=%d, tim=%d, "
4041 	    "swq_depth=%d, clrdmask=%d, leak_count=%d\n",
4042 	    __func__,
4043 	    an->an_node.ni_macaddr,
4044 	    ":",
4045 	    an->an_is_powersave,
4046 	    an->an_stack_psq,
4047 	    an->an_tim_set,
4048 	    an->an_swq_depth,
4049 	    an->clrdmask,
4050 	    an->an_leak_count);
4051 
4052 	for (tid = 0; tid < IEEE80211_TID_SIZE; tid++) {
4053 		struct ath_tid *atid = &an->an_tid[tid];
4054 
4055 		/* Free packets */
4056 		ath_tx_tid_drain(sc, an, atid, &bf_cq);
4057 
4058 		/* Remove this tid from the list of active tids */
4059 		ath_tx_tid_unsched(sc, atid);
4060 
4061 		/* Reset the per-TID pause, BAR, etc state */
4062 		ath_tx_tid_reset(sc, atid);
4063 	}
4064 
4065 	/*
4066 	 * Clear global leak count
4067 	 */
4068 	an->an_leak_count = 0;
4069 	ATH_TX_UNLOCK(sc);
4070 
4071 	/* Handle completed frames */
4072 	while ((bf = TAILQ_FIRST(&bf_cq)) != NULL) {
4073 		TAILQ_REMOVE(&bf_cq, bf, bf_list);
4074 		ath_tx_default_comp(sc, bf, 0);
4075 	}
4076 }
4077 
4078 /*
4079  * Drain all the software TXQs currently with traffic queued.
4080  */
4081 void
4082 ath_tx_txq_drain(struct ath_softc *sc, struct ath_txq *txq)
4083 {
4084 	struct ath_tid *tid;
4085 	ath_bufhead bf_cq;
4086 	struct ath_buf *bf;
4087 
4088 	TAILQ_INIT(&bf_cq);
4089 	ATH_TX_LOCK(sc);
4090 
4091 	/*
4092 	 * Iterate over all active tids for the given txq,
4093 	 * flushing and unsched'ing them
4094 	 */
4095 	while (! TAILQ_EMPTY(&txq->axq_tidq)) {
4096 		tid = TAILQ_FIRST(&txq->axq_tidq);
4097 		ath_tx_tid_drain(sc, tid->an, tid, &bf_cq);
4098 		ath_tx_tid_unsched(sc, tid);
4099 	}
4100 
4101 	ATH_TX_UNLOCK(sc);
4102 
4103 	while ((bf = TAILQ_FIRST(&bf_cq)) != NULL) {
4104 		TAILQ_REMOVE(&bf_cq, bf, bf_list);
4105 		ath_tx_default_comp(sc, bf, 0);
4106 	}
4107 }
4108 
4109 /*
4110  * Handle completion of non-aggregate session frames.
4111  *
4112  * This (currently) doesn't implement software retransmission of
4113  * non-aggregate frames!
4114  *
4115  * Software retransmission of non-aggregate frames needs to obey
4116  * the strict sequence number ordering, and drop any frames that
4117  * will fail this.
4118  *
4119  * For now, filtered frames and frame transmission will cause
4120  * all kinds of issues.  So we don't support them.
4121  *
4122  * So anyone queuing frames via ath_tx_normal_xmit() or
4123  * ath_tx_hw_queue_norm() must override and set CLRDMASK.
4124  */
4125 void
4126 ath_tx_normal_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
4127 {
4128 	struct ieee80211_node *ni = bf->bf_node;
4129 	struct ath_node *an = ATH_NODE(ni);
4130 	int tid = bf->bf_state.bfs_tid;
4131 	struct ath_tid *atid = &an->an_tid[tid];
4132 	struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
4133 
4134 	/* The TID state is protected behind the TXQ lock */
4135 	ATH_TX_LOCK(sc);
4136 
4137 	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: bf=%p: fail=%d, hwq_depth now %d\n",
4138 	    __func__, bf, fail, atid->hwq_depth - 1);
4139 
4140 	atid->hwq_depth--;
4141 
4142 #if 0
4143 	/*
4144 	 * If the frame was filtered, stick it on the filter frame
4145 	 * queue and complain about it.  It shouldn't happen!
4146 	 */
4147 	if ((ts->ts_status & HAL_TXERR_FILT) ||
4148 	    (ts->ts_status != 0 && atid->isfiltered)) {
4149 		DPRINTF(sc, ATH_DEBUG_SW_TX,
4150 		    "%s: isfiltered=%d, ts_status=%d: huh?\n",
4151 		    __func__,
4152 		    atid->isfiltered,
4153 		    ts->ts_status);
4154 		ath_tx_tid_filt_comp_buf(sc, atid, bf);
4155 	}
4156 #endif
4157 	if (atid->isfiltered)
4158 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: filtered?!\n", __func__);
4159 	if (atid->hwq_depth < 0)
4160 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: hwq_depth < 0: %d\n",
4161 		    __func__, atid->hwq_depth);
4162 
4163 	/* If the TID is being cleaned up, track things */
4164 	/* XXX refactor! */
4165 	if (atid->cleanup_inprogress) {
4166 		atid->incomp--;
4167 		if (atid->incomp == 0) {
4168 			DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
4169 			    "%s: TID %d: cleaned up! resume!\n",
4170 			    __func__, tid);
4171 			atid->cleanup_inprogress = 0;
4172 			ath_tx_tid_resume(sc, atid);
4173 		}
4174 	}
4175 
4176 	/*
4177 	 * If the queue is filtered, potentially mark it as complete
4178 	 * and reschedule it as needed.
4179 	 *
4180 	 * This is required as there may be a subsequent TX descriptor
4181 	 * for this end-node that has CLRDMASK set, so it's quite possible
4182 	 * that a filtered frame will be followed by a non-filtered
4183 	 * (complete or otherwise) frame.
4184 	 *
4185 	 * XXX should we do this before we complete the frame?
4186 	 */
4187 	if (atid->isfiltered)
4188 		ath_tx_tid_filt_comp_complete(sc, atid);
4189 	ATH_TX_UNLOCK(sc);
4190 
4191 	/*
4192 	 * punt to rate control if we're not being cleaned up
4193 	 * during a hw queue drain and the frame wanted an ACK.
4194 	 */
4195 	if (fail == 0 && ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0))
4196 		ath_tx_update_ratectrl(sc, ni, bf->bf_state.bfs_rc,
4197 		    ts, bf->bf_state.bfs_pktlen,
4198 		    1, (ts->ts_status == 0) ? 0 : 1);
4199 
4200 	ath_tx_default_comp(sc, bf, fail);
4201 }
4202 
4203 /*
4204  * Handle cleanup of aggregate session packets that aren't
4205  * an A-MPDU.
4206  *
4207  * There's no need to update the BAW here - the session is being
4208  * torn down.
4209  */
4210 static void
4211 ath_tx_comp_cleanup_unaggr(struct ath_softc *sc, struct ath_buf *bf)
4212 {
4213 	struct ieee80211_node *ni = bf->bf_node;
4214 	struct ath_node *an = ATH_NODE(ni);
4215 	int tid = bf->bf_state.bfs_tid;
4216 	struct ath_tid *atid = &an->an_tid[tid];
4217 
4218 	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL, "%s: TID %d: incomp=%d\n",
4219 	    __func__, tid, atid->incomp);
4220 
4221 	ATH_TX_LOCK(sc);
4222 	atid->incomp--;
4223 
4224 	/* XXX refactor! */
4225 	if (bf->bf_state.bfs_dobaw) {
4226 		ath_tx_update_baw(sc, an, atid, bf);
4227 		if (!bf->bf_state.bfs_addedbaw)
4228 			DPRINTF(sc, ATH_DEBUG_SW_TX,
4229 			    "%s: wasn't added: seqno %d\n",
4230 			    __func__, SEQNO(bf->bf_state.bfs_seqno));
4231 	}
4232 
4233 	if (atid->incomp == 0) {
4234 		DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
4235 		    "%s: TID %d: cleaned up! resume!\n",
4236 		    __func__, tid);
4237 		atid->cleanup_inprogress = 0;
4238 		ath_tx_tid_resume(sc, atid);
4239 	}
4240 	ATH_TX_UNLOCK(sc);
4241 
4242 	ath_tx_default_comp(sc, bf, 0);
4243 }
4244 
4245 
4246 /*
4247  * This as it currently stands is a bit dumb.  Ideally we'd just
4248  * fail the frame the normal way and have it permanently fail
4249  * via the normal aggregate completion path.
4250  */
4251 static void
4252 ath_tx_tid_cleanup_frame(struct ath_softc *sc, struct ath_node *an,
4253     int tid, struct ath_buf *bf_head, ath_bufhead *bf_cq)
4254 {
4255 	struct ath_tid *atid = &an->an_tid[tid];
4256 	struct ath_buf *bf, *bf_next;
4257 
4258 	ATH_TX_LOCK_ASSERT(sc);
4259 
4260 	/*
4261 	 * Remove this frame from the queue.
4262 	 */
4263 	ATH_TID_REMOVE(atid, bf_head, bf_list);
4264 
4265 	/*
4266 	 * Loop over all the frames in the aggregate.
4267 	 */
4268 	bf = bf_head;
4269 	while (bf != NULL) {
4270 		bf_next = bf->bf_next;	/* next aggregate frame, or NULL */
4271 
4272 		/*
4273 		 * If it's been added to the BAW we need to kick
4274 		 * it out of the BAW before we continue.
4275 		 *
4276 		 * XXX if it's an aggregate, assert that it's in the
4277 		 * BAW - we shouldn't have it be in an aggregate
4278 		 * otherwise!
4279 		 */
4280 		if (bf->bf_state.bfs_addedbaw) {
4281 			ath_tx_update_baw(sc, an, atid, bf);
4282 			bf->bf_state.bfs_dobaw = 0;
4283 		}
4284 
4285 		/*
4286 		 * Give it the default completion handler.
4287 		 */
4288 		bf->bf_comp = ath_tx_normal_comp;
4289 		bf->bf_next = NULL;
4290 
4291 		/*
4292 		 * Add it to the list to free.
4293 		 */
4294 		TAILQ_INSERT_TAIL(bf_cq, bf, bf_list);
4295 
4296 		/*
4297 		 * Now advance to the next frame in the aggregate.
4298 		 */
4299 		bf = bf_next;
4300 	}
4301 }
4302 
4303 /*
4304  * Performs transmit side cleanup when TID changes from aggregated to
4305  * unaggregated and during reassociation.
4306  *
4307  * For now, this just tosses everything from the TID software queue
4308  * whether or not it has been retried and marks the TID as
4309  * pending completion if there's anything for this TID queued to
4310  * the hardware.
4311  *
4312  * The caller is responsible for pausing the TID and unpausing the
4313  * TID if no cleanup was required. Otherwise the cleanup path will
4314  * unpause the TID once the last hardware queued frame is completed.
4315  */
4316 static void
4317 ath_tx_tid_cleanup(struct ath_softc *sc, struct ath_node *an, int tid,
4318     ath_bufhead *bf_cq)
4319 {
4320 	struct ath_tid *atid = &an->an_tid[tid];
4321 	struct ath_buf *bf, *bf_next;
4322 
4323 	ATH_TX_LOCK_ASSERT(sc);
4324 
4325 	DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
4326 	    "%s: TID %d: called; inprogress=%d\n", __func__, tid,
4327 	    atid->cleanup_inprogress);
4328 
4329 	/*
4330 	 * Move the filtered frames to the TX queue, before
4331 	 * we run off and discard/process things.
4332 	 */
4333 
4334 	/* XXX this is really quite inefficient */
4335 	while ((bf = ATH_TID_FILT_LAST(atid, ath_bufhead_s)) != NULL) {
4336 		ATH_TID_FILT_REMOVE(atid, bf, bf_list);
4337 		ATH_TID_INSERT_HEAD(atid, bf, bf_list);
4338 	}
4339 
4340 	/*
4341 	 * Update the frames in the software TX queue:
4342 	 *
4343 	 * + Discard retry frames in the queue
4344 	 * + Fix the completion function to be non-aggregate
4345 	 */
4346 	bf = ATH_TID_FIRST(atid);
4347 	while (bf) {
4348 		/*
4349 		 * Grab the next frame in the list, we may
4350 		 * be fiddling with the list.
4351 		 */
4352 		bf_next = TAILQ_NEXT(bf, bf_list);
4353 
4354 		/*
4355 		 * Free the frame and all subframes.
4356 		 */
4357 		ath_tx_tid_cleanup_frame(sc, an, tid, bf, bf_cq);
4358 
4359 		/*
4360 		 * Next frame!
4361 		 */
4362 		bf = bf_next;
4363 	}
4364 
4365 	/*
4366 	 * If there's anything in the hardware queue we wait
4367 	 * for the TID HWQ to empty.
4368 	 */
4369 	if (atid->hwq_depth > 0) {
4370 		/*
4371 		 * XXX how about we kill atid->incomp, and instead
4372 		 * replace it with a macro that checks that atid->hwq_depth
4373 		 * is 0?
4374 		 */
4375 		atid->incomp = atid->hwq_depth;
4376 		atid->cleanup_inprogress = 1;
4377 	}
4378 
4379 	if (atid->cleanup_inprogress)
4380 		DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
4381 		    "%s: TID %d: cleanup needed: %d packets\n",
4382 		    __func__, tid, atid->incomp);
4383 
4384 	/* Owner now must free completed frames */
4385 }
4386 
4387 static struct ath_buf *
4388 ath_tx_retry_clone(struct ath_softc *sc, struct ath_node *an,
4389     struct ath_tid *tid, struct ath_buf *bf)
4390 {
4391 	struct ath_buf *nbf;
4392 	int error;
4393 
4394 	/*
4395 	 * Clone the buffer.  This will handle the dma unmap and
4396 	 * copy the node reference to the new buffer.  If this
4397 	 * works out, 'bf' will have no DMA mapping, no mbuf
4398 	 * pointer and no node reference.
4399 	 */
4400 	nbf = ath_buf_clone(sc, bf);
4401 
4402 #if 0
4403 	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: ATH_BUF_BUSY; cloning\n",
4404 	    __func__);
4405 #endif
4406 
4407 	if (nbf == NULL) {
4408 		/* Failed to clone */
4409 		DPRINTF(sc, ATH_DEBUG_XMIT,
4410 		    "%s: failed to clone a busy buffer\n",
4411 		    __func__);
4412 		return NULL;
4413 	}
4414 
4415 	/* Setup the dma for the new buffer */
4416 	error = ath_tx_dmasetup(sc, nbf, nbf->bf_m);
4417 	if (error != 0) {
4418 		DPRINTF(sc, ATH_DEBUG_XMIT,
4419 		    "%s: failed to setup dma for clone\n",
4420 		    __func__);
4421 		/*
4422 		 * Put this at the head of the list, not tail;
4423 		 * that way it doesn't interfere with the
4424 		 * busy buffer logic (which uses the tail of
4425 		 * the list.)
4426 		 */
4427 		ATH_TXBUF_LOCK(sc);
4428 		ath_returnbuf_head(sc, nbf);
4429 		ATH_TXBUF_UNLOCK(sc);
4430 		return NULL;
4431 	}
4432 
4433 	/* Update BAW if required, before we free the original buf */
4434 	if (bf->bf_state.bfs_dobaw)
4435 		ath_tx_switch_baw_buf(sc, an, tid, bf, nbf);
4436 
4437 	/* Free original buffer; return new buffer */
4438 	ath_freebuf(sc, bf);
4439 
4440 	return nbf;
4441 }
4442 
4443 /*
4444  * Handle retrying an unaggregate frame in an aggregate
4445  * session.
4446  *
4447  * If too many retries occur, pause the TID, wait for
4448  * any further retransmits (as there's no reason why
4449  * non-aggregate frames in an aggregate session are
4450  * transmitted in-order; they just have to be in-BAW)
4451  * and then queue a BAR.
4452  */
4453 static void
4454 ath_tx_aggr_retry_unaggr(struct ath_softc *sc, struct ath_buf *bf)
4455 {
4456 	struct ieee80211_node *ni = bf->bf_node;
4457 	struct ath_node *an = ATH_NODE(ni);
4458 	int tid = bf->bf_state.bfs_tid;
4459 	struct ath_tid *atid = &an->an_tid[tid];
4460 	struct ieee80211_tx_ampdu *tap;
4461 
4462 	ATH_TX_LOCK(sc);
4463 
4464 	tap = ath_tx_get_tx_tid(an, tid);
4465 
4466 	/*
4467 	 * If the buffer is marked as busy, we can't directly
4468 	 * reuse it. Instead, try to clone the buffer.
4469 	 * If the clone is successful, recycle the old buffer.
4470 	 * If the clone is unsuccessful, set bfs_retries to max
4471 	 * to force the next bit of code to free the buffer
4472 	 * for us.
4473 	 */
4474 	if ((bf->bf_state.bfs_retries < SWMAX_RETRIES) &&
4475 	    (bf->bf_flags & ATH_BUF_BUSY)) {
4476 		struct ath_buf *nbf;
4477 		nbf = ath_tx_retry_clone(sc, an, atid, bf);
4478 		if (nbf)
4479 			/* bf has been freed at this point */
4480 			bf = nbf;
4481 		else
4482 			bf->bf_state.bfs_retries = SWMAX_RETRIES + 1;
4483 	}
4484 
4485 	if (bf->bf_state.bfs_retries >= SWMAX_RETRIES) {
4486 		DPRINTF(sc, ATH_DEBUG_SW_TX_RETRIES,
4487 		    "%s: exceeded retries; seqno %d\n",
4488 		    __func__, SEQNO(bf->bf_state.bfs_seqno));
4489 		sc->sc_stats.ast_tx_swretrymax++;
4490 
4491 		/* Update BAW anyway */
4492 		if (bf->bf_state.bfs_dobaw) {
4493 			ath_tx_update_baw(sc, an, atid, bf);
4494 			if (! bf->bf_state.bfs_addedbaw)
4495 				DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
4496 				    "%s: wasn't added: seqno %d\n",
4497 				    __func__, SEQNO(bf->bf_state.bfs_seqno));
4498 		}
4499 		bf->bf_state.bfs_dobaw = 0;
4500 
4501 		/* Suspend the TX queue and get ready to send the BAR */
4502 		ath_tx_tid_bar_suspend(sc, atid);
4503 
4504 		/* Send the BAR if there are no other frames waiting */
4505 		if (ath_tx_tid_bar_tx_ready(sc, atid))
4506 			ath_tx_tid_bar_tx(sc, atid);
4507 
4508 		ATH_TX_UNLOCK(sc);
4509 
4510 		/* Free buffer, bf is free after this call */
4511 		ath_tx_default_comp(sc, bf, 0);
4512 		return;
4513 	}
4514 
4515 	/*
4516 	 * This increments the retry counter as well as
4517 	 * sets the retry flag in the ath_buf and packet
4518 	 * body.
4519 	 */
4520 	ath_tx_set_retry(sc, bf);
4521 	sc->sc_stats.ast_tx_swretries++;
4522 
4523 	/*
4524 	 * Insert this at the head of the queue, so it's
4525 	 * retried before any current/subsequent frames.
4526 	 */
4527 	ATH_TID_INSERT_HEAD(atid, bf, bf_list);
4528 	ath_tx_tid_sched(sc, atid);
4529 	/* Send the BAR if there are no other frames waiting */
4530 	if (ath_tx_tid_bar_tx_ready(sc, atid))
4531 		ath_tx_tid_bar_tx(sc, atid);
4532 
4533 	ATH_TX_UNLOCK(sc);
4534 }
4535 
4536 /*
4537  * Common code for aggregate excessive retry/subframe retry.
4538  * If retrying, queues buffers to bf_q. If not, frees the
4539  * buffers.
4540  *
4541  * XXX should unify this with ath_tx_aggr_retry_unaggr()
4542  */
4543 static int
4544 ath_tx_retry_subframe(struct ath_softc *sc, struct ath_buf *bf,
4545     ath_bufhead *bf_q)
4546 {
4547 	struct ieee80211_node *ni = bf->bf_node;
4548 	struct ath_node *an = ATH_NODE(ni);
4549 	int tid = bf->bf_state.bfs_tid;
4550 	struct ath_tid *atid = &an->an_tid[tid];
4551 
4552 	ATH_TX_LOCK_ASSERT(sc);
4553 
4554 	/* XXX clr11naggr should be done for all subframes */
4555 	ath_hal_clr11n_aggr(sc->sc_ah, bf->bf_desc);
4556 	ath_hal_set11nburstduration(sc->sc_ah, bf->bf_desc, 0);
4557 
4558 	/* ath_hal_set11n_virtualmorefrag(sc->sc_ah, bf->bf_desc, 0); */
4559 
4560 	/*
4561 	 * If the buffer is marked as busy, we can't directly
4562 	 * reuse it. Instead, try to clone the buffer.
4563 	 * If the clone is successful, recycle the old buffer.
4564 	 * If the clone is unsuccessful, set bfs_retries to max
4565 	 * to force the next bit of code to free the buffer
4566 	 * for us.
4567 	 */
4568 	if ((bf->bf_state.bfs_retries < SWMAX_RETRIES) &&
4569 	    (bf->bf_flags & ATH_BUF_BUSY)) {
4570 		struct ath_buf *nbf;
4571 		nbf = ath_tx_retry_clone(sc, an, atid, bf);
4572 		if (nbf)
4573 			/* bf has been freed at this point */
4574 			bf = nbf;
4575 		else
4576 			bf->bf_state.bfs_retries = SWMAX_RETRIES + 1;
4577 	}
4578 
4579 	if (bf->bf_state.bfs_retries >= SWMAX_RETRIES) {
4580 		sc->sc_stats.ast_tx_swretrymax++;
4581 		DPRINTF(sc, ATH_DEBUG_SW_TX_RETRIES,
4582 		    "%s: max retries: seqno %d\n",
4583 		    __func__, SEQNO(bf->bf_state.bfs_seqno));
4584 		ath_tx_update_baw(sc, an, atid, bf);
4585 		if (!bf->bf_state.bfs_addedbaw)
4586 			DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
4587 			    "%s: wasn't added: seqno %d\n",
4588 			    __func__, SEQNO(bf->bf_state.bfs_seqno));
4589 		bf->bf_state.bfs_dobaw = 0;
4590 		return 1;
4591 	}
4592 
4593 	ath_tx_set_retry(sc, bf);
4594 	sc->sc_stats.ast_tx_swretries++;
4595 	bf->bf_next = NULL;		/* Just to make sure */
4596 
4597 	/* Clear the aggregate state */
4598 	bf->bf_state.bfs_aggr = 0;
4599 	bf->bf_state.bfs_ndelim = 0;	/* ??? needed? */
4600 	bf->bf_state.bfs_nframes = 1;
4601 
4602 	TAILQ_INSERT_TAIL(bf_q, bf, bf_list);
4603 	return 0;
4604 }
4605 
4606 /*
4607  * error pkt completion for an aggregate destination
4608  */
4609 static void
4610 ath_tx_comp_aggr_error(struct ath_softc *sc, struct ath_buf *bf_first,
4611     struct ath_tid *tid)
4612 {
4613 	struct ieee80211_node *ni = bf_first->bf_node;
4614 	struct ath_node *an = ATH_NODE(ni);
4615 	struct ath_buf *bf_next, *bf;
4616 	ath_bufhead bf_q;
4617 	int drops = 0;
4618 	struct ieee80211_tx_ampdu *tap;
4619 	ath_bufhead bf_cq;
4620 
4621 	TAILQ_INIT(&bf_q);
4622 	TAILQ_INIT(&bf_cq);
4623 
4624 	/*
4625 	 * Update rate control - all frames have failed.
4626 	 *
4627 	 * XXX use the length in the first frame in the series;
4628 	 * XXX just so things are consistent for now.
4629 	 */
4630 	ath_tx_update_ratectrl(sc, ni, bf_first->bf_state.bfs_rc,
4631 	    &bf_first->bf_status.ds_txstat,
4632 	    bf_first->bf_state.bfs_pktlen,
4633 	    bf_first->bf_state.bfs_nframes, bf_first->bf_state.bfs_nframes);
4634 
4635 	ATH_TX_LOCK(sc);
4636 	tap = ath_tx_get_tx_tid(an, tid->tid);
4637 	sc->sc_stats.ast_tx_aggr_failall++;
4638 
4639 	/* Retry all subframes */
4640 	bf = bf_first;
4641 	while (bf) {
4642 		bf_next = bf->bf_next;
4643 		bf->bf_next = NULL;	/* Remove it from the aggr list */
4644 		sc->sc_stats.ast_tx_aggr_fail++;
4645 		if (ath_tx_retry_subframe(sc, bf, &bf_q)) {
4646 			drops++;
4647 			bf->bf_next = NULL;
4648 			TAILQ_INSERT_TAIL(&bf_cq, bf, bf_list);
4649 		}
4650 		bf = bf_next;
4651 	}
4652 
4653 	/* Prepend all frames to the beginning of the queue */
4654 	while ((bf = TAILQ_LAST(&bf_q, ath_bufhead_s)) != NULL) {
4655 		TAILQ_REMOVE(&bf_q, bf, bf_list);
4656 		ATH_TID_INSERT_HEAD(tid, bf, bf_list);
4657 	}
4658 
4659 	/*
4660 	 * Schedule the TID to be re-tried.
4661 	 */
4662 	ath_tx_tid_sched(sc, tid);
4663 
4664 	/*
4665 	 * send bar if we dropped any frames
4666 	 *
4667 	 * Keep the txq lock held for now, as we need to ensure
4668 	 * that ni_txseqs[] is consistent (as it's being updated
4669 	 * in the ifnet TX context or raw TX context.)
4670 	 */
4671 	if (drops) {
4672 		/* Suspend the TX queue and get ready to send the BAR */
4673 		ath_tx_tid_bar_suspend(sc, tid);
4674 	}
4675 
4676 	/*
4677 	 * Send BAR if required
4678 	 */
4679 	if (ath_tx_tid_bar_tx_ready(sc, tid))
4680 		ath_tx_tid_bar_tx(sc, tid);
4681 
4682 	ATH_TX_UNLOCK(sc);
4683 
4684 	/* Complete frames which errored out */
4685 	while ((bf = TAILQ_FIRST(&bf_cq)) != NULL) {
4686 		TAILQ_REMOVE(&bf_cq, bf, bf_list);
4687 		ath_tx_default_comp(sc, bf, 0);
4688 	}
4689 }
4690 
4691 /*
4692  * Handle clean-up of packets from an aggregate list.
4693  *
4694  * There's no need to update the BAW here - the session is being
4695  * torn down.
4696  */
4697 static void
4698 ath_tx_comp_cleanup_aggr(struct ath_softc *sc, struct ath_buf *bf_first)
4699 {
4700 	struct ath_buf *bf, *bf_next;
4701 	struct ieee80211_node *ni = bf_first->bf_node;
4702 	struct ath_node *an = ATH_NODE(ni);
4703 	int tid = bf_first->bf_state.bfs_tid;
4704 	struct ath_tid *atid = &an->an_tid[tid];
4705 
4706 	ATH_TX_LOCK(sc);
4707 
4708 	/* update incomp */
4709 	atid->incomp--;
4710 
4711 	/* Update the BAW */
4712 	bf = bf_first;
4713 	while (bf) {
4714 		/* XXX refactor! */
4715 		if (bf->bf_state.bfs_dobaw) {
4716 			ath_tx_update_baw(sc, an, atid, bf);
4717 			if (!bf->bf_state.bfs_addedbaw)
4718 				DPRINTF(sc, ATH_DEBUG_SW_TX,
4719 				    "%s: wasn't added: seqno %d\n",
4720 				    __func__, SEQNO(bf->bf_state.bfs_seqno));
4721 		}
4722 		bf = bf->bf_next;
4723 	}
4724 
4725 	if (atid->incomp == 0) {
4726 		DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
4727 		    "%s: TID %d: cleaned up! resume!\n",
4728 		    __func__, tid);
4729 		atid->cleanup_inprogress = 0;
4730 		ath_tx_tid_resume(sc, atid);
4731 	}
4732 
4733 	/* Send BAR if required */
4734 	/* XXX why would we send a BAR when transitioning to non-aggregation? */
4735 	/*
4736 	 * XXX TODO: we should likely just tear down the BAR state here,
4737 	 * rather than sending a BAR.
4738 	 */
4739 	if (ath_tx_tid_bar_tx_ready(sc, atid))
4740 		ath_tx_tid_bar_tx(sc, atid);
4741 
4742 	ATH_TX_UNLOCK(sc);
4743 
4744 	/* Handle frame completion as individual frames */
4745 	bf = bf_first;
4746 	while (bf) {
4747 		bf_next = bf->bf_next;
4748 		bf->bf_next = NULL;
4749 		ath_tx_default_comp(sc, bf, 1);
4750 		bf = bf_next;
4751 	}
4752 }
4753 
4754 /*
4755  * Handle completion of an set of aggregate frames.
4756  *
4757  * Note: the completion handler is the last descriptor in the aggregate,
4758  * not the last descriptor in the first frame.
4759  */
4760 static void
4761 ath_tx_aggr_comp_aggr(struct ath_softc *sc, struct ath_buf *bf_first,
4762     int fail)
4763 {
4764 	//struct ath_desc *ds = bf->bf_lastds;
4765 	struct ieee80211_node *ni = bf_first->bf_node;
4766 	struct ath_node *an = ATH_NODE(ni);
4767 	int tid = bf_first->bf_state.bfs_tid;
4768 	struct ath_tid *atid = &an->an_tid[tid];
4769 	struct ath_tx_status ts;
4770 	struct ieee80211_tx_ampdu *tap;
4771 	ath_bufhead bf_q;
4772 	ath_bufhead bf_cq;
4773 	int seq_st, tx_ok;
4774 	int hasba, isaggr;
4775 	uint32_t ba[2];
4776 	struct ath_buf *bf, *bf_next;
4777 	int ba_index;
4778 	int drops = 0;
4779 	int nframes = 0, nbad = 0, nf;
4780 	int pktlen;
4781 	/* XXX there's too much on the stack? */
4782 	struct ath_rc_series rc[ATH_RC_NUM];
4783 	int txseq;
4784 
4785 	DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: called; hwq_depth=%d\n",
4786 	    __func__, atid->hwq_depth);
4787 
4788 	/*
4789 	 * Take a copy; this may be needed -after- bf_first
4790 	 * has been completed and freed.
4791 	 */
4792 	ts = bf_first->bf_status.ds_txstat;
4793 
4794 	TAILQ_INIT(&bf_q);
4795 	TAILQ_INIT(&bf_cq);
4796 
4797 	/* The TID state is kept behind the TXQ lock */
4798 	ATH_TX_LOCK(sc);
4799 
4800 	atid->hwq_depth--;
4801 	if (atid->hwq_depth < 0)
4802 		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: hwq_depth < 0: %d\n",
4803 		    __func__, atid->hwq_depth);
4804 
4805 	/*
4806 	 * If the TID is filtered, handle completing the filter
4807 	 * transition before potentially kicking it to the cleanup
4808 	 * function.
4809 	 *
4810 	 * XXX this is duplicate work, ew.
4811 	 */
4812 	if (atid->isfiltered)
4813 		ath_tx_tid_filt_comp_complete(sc, atid);
4814 
4815 	/*
4816 	 * Punt cleanup to the relevant function, not our problem now
4817 	 */
4818 	if (atid->cleanup_inprogress) {
4819 		if (atid->isfiltered)
4820 			DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
4821 			    "%s: isfiltered=1, normal_comp?\n",
4822 			    __func__);
4823 		ATH_TX_UNLOCK(sc);
4824 		ath_tx_comp_cleanup_aggr(sc, bf_first);
4825 		return;
4826 	}
4827 
4828 	/*
4829 	 * If the frame is filtered, transition to filtered frame
4830 	 * mode and add this to the filtered frame list.
4831 	 *
4832 	 * XXX TODO: figure out how this interoperates with
4833 	 * BAR, pause and cleanup states.
4834 	 */
4835 	if ((ts.ts_status & HAL_TXERR_FILT) ||
4836 	    (ts.ts_status != 0 && atid->isfiltered)) {
4837 		if (fail != 0)
4838 			DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
4839 			    "%s: isfiltered=1, fail=%d\n", __func__, fail);
4840 		ath_tx_tid_filt_comp_aggr(sc, atid, bf_first, &bf_cq);
4841 
4842 		/* Remove from BAW */
4843 		TAILQ_FOREACH_SAFE(bf, &bf_cq, bf_list, bf_next) {
4844 			if (bf->bf_state.bfs_addedbaw)
4845 				drops++;
4846 			if (bf->bf_state.bfs_dobaw) {
4847 				ath_tx_update_baw(sc, an, atid, bf);
4848 				if (!bf->bf_state.bfs_addedbaw)
4849 					DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
4850 					    "%s: wasn't added: seqno %d\n",
4851 					    __func__,
4852 					    SEQNO(bf->bf_state.bfs_seqno));
4853 			}
4854 			bf->bf_state.bfs_dobaw = 0;
4855 		}
4856 		/*
4857 		 * If any intermediate frames in the BAW were dropped when
4858 		 * handling filtering things, send a BAR.
4859 		 */
4860 		if (drops)
4861 			ath_tx_tid_bar_suspend(sc, atid);
4862 
4863 		/*
4864 		 * Finish up by sending a BAR if required and freeing
4865 		 * the frames outside of the TX lock.
4866 		 */
4867 		goto finish_send_bar;
4868 	}
4869 
4870 	/*
4871 	 * XXX for now, use the first frame in the aggregate for
4872 	 * XXX rate control completion; it's at least consistent.
4873 	 */
4874 	pktlen = bf_first->bf_state.bfs_pktlen;
4875 
4876 	/*
4877 	 * Handle errors first!
4878 	 *
4879 	 * Here, handle _any_ error as a "exceeded retries" error.
4880 	 * Later on (when filtered frames are to be specially handled)
4881 	 * it'll have to be expanded.
4882 	 */
4883 #if 0
4884 	if (ts.ts_status & HAL_TXERR_XRETRY) {
4885 #endif
4886 	if (ts.ts_status != 0) {
4887 		ATH_TX_UNLOCK(sc);
4888 		ath_tx_comp_aggr_error(sc, bf_first, atid);
4889 		return;
4890 	}
4891 
4892 	tap = ath_tx_get_tx_tid(an, tid);
4893 
4894 	/*
4895 	 * extract starting sequence and block-ack bitmap
4896 	 */
4897 	/* XXX endian-ness of seq_st, ba? */
4898 	seq_st = ts.ts_seqnum;
4899 	hasba = !! (ts.ts_flags & HAL_TX_BA);
4900 	tx_ok = (ts.ts_status == 0);
4901 	isaggr = bf_first->bf_state.bfs_aggr;
4902 	ba[0] = ts.ts_ba_low;
4903 	ba[1] = ts.ts_ba_high;
4904 
4905 	/*
4906 	 * Copy the TX completion status and the rate control
4907 	 * series from the first descriptor, as it may be freed
4908 	 * before the rate control code can get its grubby fingers
4909 	 * into things.
4910 	 */
4911 	memcpy(rc, bf_first->bf_state.bfs_rc, sizeof(rc));
4912 
4913 	DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
4914 	    "%s: txa_start=%d, tx_ok=%d, status=%.8x, flags=%.8x, "
4915 	    "isaggr=%d, seq_st=%d, hasba=%d, ba=%.8x, %.8x\n",
4916 	    __func__, tap->txa_start, tx_ok, ts.ts_status, ts.ts_flags,
4917 	    isaggr, seq_st, hasba, ba[0], ba[1]);
4918 
4919 	/*
4920 	 * The reference driver doesn't do this; it simply ignores
4921 	 * this check in its entirety.
4922 	 *
4923 	 * I've seen this occur when using iperf to send traffic
4924 	 * out tid 1 - the aggregate frames are all marked as TID 1,
4925 	 * but the TXSTATUS has TID=0.  So, let's just ignore this
4926 	 * check.
4927 	 */
4928 #if 0
4929 	/* Occasionally, the MAC sends a tx status for the wrong TID. */
4930 	if (tid != ts.ts_tid) {
4931 		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: tid %d != hw tid %d\n",
4932 		    __func__, tid, ts.ts_tid);
4933 		tx_ok = 0;
4934 	}
4935 #endif
4936 
4937 	/* AR5416 BA bug; this requires an interface reset */
4938 	if (isaggr && tx_ok && (! hasba)) {
4939 		device_printf(sc->sc_dev,
4940 		    "%s: AR5416 bug: hasba=%d; txok=%d, isaggr=%d, "
4941 		    "seq_st=%d\n",
4942 		    __func__, hasba, tx_ok, isaggr, seq_st);
4943 		/* XXX TODO: schedule an interface reset */
4944 #ifdef ATH_DEBUG
4945 		ath_printtxbuf(sc, bf_first,
4946 		    sc->sc_ac2q[atid->ac]->axq_qnum, 0, 0);
4947 #endif
4948 	}
4949 
4950 	/*
4951 	 * Walk the list of frames, figure out which ones were correctly
4952 	 * sent and which weren't.
4953 	 */
4954 	bf = bf_first;
4955 	nf = bf_first->bf_state.bfs_nframes;
4956 
4957 	/* bf_first is going to be invalid once this list is walked */
4958 	bf_first = NULL;
4959 
4960 	/*
4961 	 * Walk the list of completed frames and determine
4962 	 * which need to be completed and which need to be
4963 	 * retransmitted.
4964 	 *
4965 	 * For completed frames, the completion functions need
4966 	 * to be called at the end of this function as the last
4967 	 * node reference may free the node.
4968 	 *
4969 	 * Finally, since the TXQ lock can't be held during the
4970 	 * completion callback (to avoid lock recursion),
4971 	 * the completion calls have to be done outside of the
4972 	 * lock.
4973 	 */
4974 	while (bf) {
4975 		nframes++;
4976 		ba_index = ATH_BA_INDEX(seq_st,
4977 		    SEQNO(bf->bf_state.bfs_seqno));
4978 		bf_next = bf->bf_next;
4979 		bf->bf_next = NULL;	/* Remove it from the aggr list */
4980 
4981 		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
4982 		    "%s: checking bf=%p seqno=%d; ack=%d\n",
4983 		    __func__, bf, SEQNO(bf->bf_state.bfs_seqno),
4984 		    ATH_BA_ISSET(ba, ba_index));
4985 
4986 		if (tx_ok && ATH_BA_ISSET(ba, ba_index)) {
4987 			sc->sc_stats.ast_tx_aggr_ok++;
4988 			ath_tx_update_baw(sc, an, atid, bf);
4989 			bf->bf_state.bfs_dobaw = 0;
4990 			if (!bf->bf_state.bfs_addedbaw)
4991 				DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
4992 				    "%s: wasn't added: seqno %d\n",
4993 				    __func__, SEQNO(bf->bf_state.bfs_seqno));
4994 			bf->bf_next = NULL;
4995 			TAILQ_INSERT_TAIL(&bf_cq, bf, bf_list);
4996 		} else {
4997 			sc->sc_stats.ast_tx_aggr_fail++;
4998 			if (ath_tx_retry_subframe(sc, bf, &bf_q)) {
4999 				drops++;
5000 				bf->bf_next = NULL;
5001 				TAILQ_INSERT_TAIL(&bf_cq, bf, bf_list);
5002 			}
5003 			nbad++;
5004 		}
5005 		bf = bf_next;
5006 	}
5007 
5008 	/*
5009 	 * Now that the BAW updates have been done, unlock
5010 	 *
5011 	 * txseq is grabbed before the lock is released so we
5012 	 * have a consistent view of what -was- in the BAW.
5013 	 * Anything after this point will not yet have been
5014 	 * TXed.
5015 	 */
5016 	txseq = tap->txa_start;
5017 	ATH_TX_UNLOCK(sc);
5018 
5019 	if (nframes != nf)
5020 		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
5021 		    "%s: num frames seen=%d; bf nframes=%d\n",
5022 		    __func__, nframes, nf);
5023 
5024 	/*
5025 	 * Now we know how many frames were bad, call the rate
5026 	 * control code.
5027 	 */
5028 	if (fail == 0)
5029 		ath_tx_update_ratectrl(sc, ni, rc, &ts, pktlen, nframes,
5030 		    nbad);
5031 
5032 	/*
5033 	 * send bar if we dropped any frames
5034 	 */
5035 	if (drops) {
5036 		/* Suspend the TX queue and get ready to send the BAR */
5037 		ATH_TX_LOCK(sc);
5038 		ath_tx_tid_bar_suspend(sc, atid);
5039 		ATH_TX_UNLOCK(sc);
5040 	}
5041 
5042 	DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
5043 	    "%s: txa_start now %d\n", __func__, tap->txa_start);
5044 
5045 	ATH_TX_LOCK(sc);
5046 
5047 	/* Prepend all frames to the beginning of the queue */
5048 	while ((bf = TAILQ_LAST(&bf_q, ath_bufhead_s)) != NULL) {
5049 		TAILQ_REMOVE(&bf_q, bf, bf_list);
5050 		ATH_TID_INSERT_HEAD(atid, bf, bf_list);
5051 	}
5052 
5053 	/*
5054 	 * Reschedule to grab some further frames.
5055 	 */
5056 	ath_tx_tid_sched(sc, atid);
5057 
5058 	/*
5059 	 * If the queue is filtered, re-schedule as required.
5060 	 *
5061 	 * This is required as there may be a subsequent TX descriptor
5062 	 * for this end-node that has CLRDMASK set, so it's quite possible
5063 	 * that a filtered frame will be followed by a non-filtered
5064 	 * (complete or otherwise) frame.
5065 	 *
5066 	 * XXX should we do this before we complete the frame?
5067 	 */
5068 	if (atid->isfiltered)
5069 		ath_tx_tid_filt_comp_complete(sc, atid);
5070 
5071 finish_send_bar:
5072 
5073 	/*
5074 	 * Send BAR if required
5075 	 */
5076 	if (ath_tx_tid_bar_tx_ready(sc, atid))
5077 		ath_tx_tid_bar_tx(sc, atid);
5078 
5079 	ATH_TX_UNLOCK(sc);
5080 
5081 	/* Do deferred completion */
5082 	while ((bf = TAILQ_FIRST(&bf_cq)) != NULL) {
5083 		TAILQ_REMOVE(&bf_cq, bf, bf_list);
5084 		ath_tx_default_comp(sc, bf, 0);
5085 	}
5086 }
5087 
5088 /*
5089  * Handle completion of unaggregated frames in an ADDBA
5090  * session.
5091  *
5092  * Fail is set to 1 if the entry is being freed via a call to
5093  * ath_tx_draintxq().
5094  */
5095 static void
5096 ath_tx_aggr_comp_unaggr(struct ath_softc *sc, struct ath_buf *bf, int fail)
5097 {
5098 	struct ieee80211_node *ni = bf->bf_node;
5099 	struct ath_node *an = ATH_NODE(ni);
5100 	int tid = bf->bf_state.bfs_tid;
5101 	struct ath_tid *atid = &an->an_tid[tid];
5102 	struct ath_tx_status ts;
5103 	int drops = 0;
5104 
5105 	/*
5106 	 * Take a copy of this; filtering/cloning the frame may free the
5107 	 * bf pointer.
5108 	 */
5109 	ts = bf->bf_status.ds_txstat;
5110 
5111 	/*
5112 	 * Update rate control status here, before we possibly
5113 	 * punt to retry or cleanup.
5114 	 *
5115 	 * Do it outside of the TXQ lock.
5116 	 */
5117 	if (fail == 0 && ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0))
5118 		ath_tx_update_ratectrl(sc, ni, bf->bf_state.bfs_rc,
5119 		    &bf->bf_status.ds_txstat,
5120 		    bf->bf_state.bfs_pktlen,
5121 		    1, (ts.ts_status == 0) ? 0 : 1);
5122 
5123 	/*
5124 	 * This is called early so atid->hwq_depth can be tracked.
5125 	 * This unfortunately means that it's released and regrabbed
5126 	 * during retry and cleanup. That's rather inefficient.
5127 	 */
5128 	ATH_TX_LOCK(sc);
5129 
5130 	if (tid == IEEE80211_NONQOS_TID)
5131 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: TID=16!\n", __func__);
5132 
5133 	DPRINTF(sc, ATH_DEBUG_SW_TX,
5134 	    "%s: bf=%p: tid=%d, hwq_depth=%d, seqno=%d\n",
5135 	    __func__, bf, bf->bf_state.bfs_tid, atid->hwq_depth,
5136 	    SEQNO(bf->bf_state.bfs_seqno));
5137 
5138 	atid->hwq_depth--;
5139 	if (atid->hwq_depth < 0)
5140 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: hwq_depth < 0: %d\n",
5141 		    __func__, atid->hwq_depth);
5142 
5143 	/*
5144 	 * If the TID is filtered, handle completing the filter
5145 	 * transition before potentially kicking it to the cleanup
5146 	 * function.
5147 	 */
5148 	if (atid->isfiltered)
5149 		ath_tx_tid_filt_comp_complete(sc, atid);
5150 
5151 	/*
5152 	 * If a cleanup is in progress, punt to comp_cleanup;
5153 	 * rather than handling it here. It's thus their
5154 	 * responsibility to clean up, call the completion
5155 	 * function in net80211, etc.
5156 	 */
5157 	if (atid->cleanup_inprogress) {
5158 		if (atid->isfiltered)
5159 			DPRINTF(sc, ATH_DEBUG_SW_TX,
5160 			    "%s: isfiltered=1, normal_comp?\n",
5161 			    __func__);
5162 		ATH_TX_UNLOCK(sc);
5163 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: cleanup_unaggr\n",
5164 		    __func__);
5165 		ath_tx_comp_cleanup_unaggr(sc, bf);
5166 		return;
5167 	}
5168 
5169 	/*
5170 	 * XXX TODO: how does cleanup, BAR and filtered frame handling
5171 	 * overlap?
5172 	 *
5173 	 * If the frame is filtered OR if it's any failure but
5174 	 * the TID is filtered, the frame must be added to the
5175 	 * filtered frame list.
5176 	 *
5177 	 * However - a busy buffer can't be added to the filtered
5178 	 * list as it will end up being recycled without having
5179 	 * been made available for the hardware.
5180 	 */
5181 	if ((ts.ts_status & HAL_TXERR_FILT) ||
5182 	    (ts.ts_status != 0 && atid->isfiltered)) {
5183 		int freeframe;
5184 
5185 		if (fail != 0)
5186 			DPRINTF(sc, ATH_DEBUG_SW_TX,
5187 			    "%s: isfiltered=1, fail=%d\n",
5188 			    __func__, fail);
5189 		freeframe = ath_tx_tid_filt_comp_single(sc, atid, bf);
5190 		/*
5191 		 * If freeframe=0 then bf is no longer ours; don't
5192 		 * touch it.
5193 		 */
5194 		if (freeframe) {
5195 			/* Remove from BAW */
5196 			if (bf->bf_state.bfs_addedbaw)
5197 				drops++;
5198 			if (bf->bf_state.bfs_dobaw) {
5199 				ath_tx_update_baw(sc, an, atid, bf);
5200 				if (!bf->bf_state.bfs_addedbaw)
5201 					DPRINTF(sc, ATH_DEBUG_SW_TX,
5202 					    "%s: wasn't added: seqno %d\n",
5203 					    __func__, SEQNO(bf->bf_state.bfs_seqno));
5204 			}
5205 			bf->bf_state.bfs_dobaw = 0;
5206 		}
5207 
5208 		/*
5209 		 * If the frame couldn't be filtered, treat it as a drop and
5210 		 * prepare to send a BAR.
5211 		 */
5212 		if (freeframe && drops)
5213 			ath_tx_tid_bar_suspend(sc, atid);
5214 
5215 		/*
5216 		 * Send BAR if required
5217 		 */
5218 		if (ath_tx_tid_bar_tx_ready(sc, atid))
5219 			ath_tx_tid_bar_tx(sc, atid);
5220 
5221 		ATH_TX_UNLOCK(sc);
5222 		/*
5223 		 * If freeframe is set, then the frame couldn't be
5224 		 * cloned and bf is still valid.  Just complete/free it.
5225 		 */
5226 		if (freeframe)
5227 			ath_tx_default_comp(sc, bf, fail);
5228 
5229 		return;
5230 	}
5231 	/*
5232 	 * Don't bother with the retry check if all frames
5233 	 * are being failed (eg during queue deletion.)
5234 	 */
5235 #if 0
5236 	if (fail == 0 && ts->ts_status & HAL_TXERR_XRETRY) {
5237 #endif
5238 	if (fail == 0 && ts.ts_status != 0) {
5239 		ATH_TX_UNLOCK(sc);
5240 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: retry_unaggr\n",
5241 		    __func__);
5242 		ath_tx_aggr_retry_unaggr(sc, bf);
5243 		return;
5244 	}
5245 
5246 	/* Success? Complete */
5247 	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: TID=%d, seqno %d\n",
5248 	    __func__, tid, SEQNO(bf->bf_state.bfs_seqno));
5249 	if (bf->bf_state.bfs_dobaw) {
5250 		ath_tx_update_baw(sc, an, atid, bf);
5251 		bf->bf_state.bfs_dobaw = 0;
5252 		if (!bf->bf_state.bfs_addedbaw)
5253 			DPRINTF(sc, ATH_DEBUG_SW_TX,
5254 			    "%s: wasn't added: seqno %d\n",
5255 			    __func__, SEQNO(bf->bf_state.bfs_seqno));
5256 	}
5257 
5258 	/*
5259 	 * If the queue is filtered, re-schedule as required.
5260 	 *
5261 	 * This is required as there may be a subsequent TX descriptor
5262 	 * for this end-node that has CLRDMASK set, so it's quite possible
5263 	 * that a filtered frame will be followed by a non-filtered
5264 	 * (complete or otherwise) frame.
5265 	 *
5266 	 * XXX should we do this before we complete the frame?
5267 	 */
5268 	if (atid->isfiltered)
5269 		ath_tx_tid_filt_comp_complete(sc, atid);
5270 
5271 	/*
5272 	 * Send BAR if required
5273 	 */
5274 	if (ath_tx_tid_bar_tx_ready(sc, atid))
5275 		ath_tx_tid_bar_tx(sc, atid);
5276 
5277 	ATH_TX_UNLOCK(sc);
5278 
5279 	ath_tx_default_comp(sc, bf, fail);
5280 	/* bf is freed at this point */
5281 }
5282 
5283 void
5284 ath_tx_aggr_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
5285 {
5286 	if (bf->bf_state.bfs_aggr)
5287 		ath_tx_aggr_comp_aggr(sc, bf, fail);
5288 	else
5289 		ath_tx_aggr_comp_unaggr(sc, bf, fail);
5290 }
5291 
5292 /*
5293  * Schedule some packets from the given node/TID to the hardware.
5294  *
5295  * This is the aggregate version.
5296  */
5297 void
5298 ath_tx_tid_hw_queue_aggr(struct ath_softc *sc, struct ath_node *an,
5299     struct ath_tid *tid)
5300 {
5301 	struct ath_buf *bf;
5302 	struct ath_txq *txq = sc->sc_ac2q[tid->ac];
5303 	struct ieee80211_tx_ampdu *tap;
5304 	ATH_AGGR_STATUS status;
5305 	ath_bufhead bf_q;
5306 
5307 	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: tid=%d\n", __func__, tid->tid);
5308 	ATH_TX_LOCK_ASSERT(sc);
5309 
5310 	/*
5311 	 * XXX TODO: If we're called for a queue that we're leaking frames to,
5312 	 * ensure we only leak one.
5313 	 */
5314 
5315 	tap = ath_tx_get_tx_tid(an, tid->tid);
5316 
5317 	if (tid->tid == IEEE80211_NONQOS_TID)
5318 		DPRINTF(sc, ATH_DEBUG_SW_TX,
5319 		    "%s: called for TID=NONQOS_TID?\n", __func__);
5320 
5321 	for (;;) {
5322 		status = ATH_AGGR_DONE;
5323 
5324 		/*
5325 		 * If the upper layer has paused the TID, don't
5326 		 * queue any further packets.
5327 		 *
5328 		 * This can also occur from the completion task because
5329 		 * of packet loss; but as its serialised with this code,
5330 		 * it won't "appear" half way through queuing packets.
5331 		 */
5332 		if (! ath_tx_tid_can_tx_or_sched(sc, tid))
5333 			break;
5334 
5335 		bf = ATH_TID_FIRST(tid);
5336 		if (bf == NULL) {
5337 			break;
5338 		}
5339 
5340 		/*
5341 		 * If the packet doesn't fall within the BAW (eg a NULL
5342 		 * data frame), schedule it directly; continue.
5343 		 */
5344 		if (! bf->bf_state.bfs_dobaw) {
5345 			DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
5346 			    "%s: non-baw packet\n",
5347 			    __func__);
5348 			ATH_TID_REMOVE(tid, bf, bf_list);
5349 
5350 			if (bf->bf_state.bfs_nframes > 1)
5351 				DPRINTF(sc, ATH_DEBUG_SW_TX,
5352 				    "%s: aggr=%d, nframes=%d\n",
5353 				    __func__,
5354 				    bf->bf_state.bfs_aggr,
5355 				    bf->bf_state.bfs_nframes);
5356 
5357 			/*
5358 			 * This shouldn't happen - such frames shouldn't
5359 			 * ever have been queued as an aggregate in the
5360 			 * first place.  However, make sure the fields
5361 			 * are correctly setup just to be totally sure.
5362 			 */
5363 			bf->bf_state.bfs_aggr = 0;
5364 			bf->bf_state.bfs_nframes = 1;
5365 
5366 			/* Update CLRDMASK just before this frame is queued */
5367 			ath_tx_update_clrdmask(sc, tid, bf);
5368 
5369 			ath_tx_do_ratelookup(sc, bf);
5370 			ath_tx_calc_duration(sc, bf);
5371 			ath_tx_calc_protection(sc, bf);
5372 			ath_tx_set_rtscts(sc, bf);
5373 			ath_tx_rate_fill_rcflags(sc, bf);
5374 			ath_tx_setds(sc, bf);
5375 			ath_hal_clr11n_aggr(sc->sc_ah, bf->bf_desc);
5376 
5377 			sc->sc_aggr_stats.aggr_nonbaw_pkt++;
5378 
5379 			/* Queue the packet; continue */
5380 			goto queuepkt;
5381 		}
5382 
5383 		TAILQ_INIT(&bf_q);
5384 
5385 		/*
5386 		 * Do a rate control lookup on the first frame in the
5387 		 * list. The rate control code needs that to occur
5388 		 * before it can determine whether to TX.
5389 		 * It's inaccurate because the rate control code doesn't
5390 		 * really "do" aggregate lookups, so it only considers
5391 		 * the size of the first frame.
5392 		 */
5393 		ath_tx_do_ratelookup(sc, bf);
5394 		bf->bf_state.bfs_rc[3].rix = 0;
5395 		bf->bf_state.bfs_rc[3].tries = 0;
5396 
5397 		ath_tx_calc_duration(sc, bf);
5398 		ath_tx_calc_protection(sc, bf);
5399 
5400 		ath_tx_set_rtscts(sc, bf);
5401 		ath_tx_rate_fill_rcflags(sc, bf);
5402 
5403 		status = ath_tx_form_aggr(sc, an, tid, &bf_q);
5404 
5405 		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
5406 		    "%s: ath_tx_form_aggr() status=%d\n", __func__, status);
5407 
5408 		/*
5409 		 * No frames to be picked up - out of BAW
5410 		 */
5411 		if (TAILQ_EMPTY(&bf_q))
5412 			break;
5413 
5414 		/*
5415 		 * This assumes that the descriptor list in the ath_bufhead
5416 		 * are already linked together via bf_next pointers.
5417 		 */
5418 		bf = TAILQ_FIRST(&bf_q);
5419 
5420 		if (status == ATH_AGGR_8K_LIMITED)
5421 			sc->sc_aggr_stats.aggr_rts_aggr_limited++;
5422 
5423 		/*
5424 		 * If it's the only frame send as non-aggregate
5425 		 * assume that ath_tx_form_aggr() has checked
5426 		 * whether it's in the BAW and added it appropriately.
5427 		 */
5428 		if (bf->bf_state.bfs_nframes == 1) {
5429 			DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
5430 			    "%s: single-frame aggregate\n", __func__);
5431 
5432 			/* Update CLRDMASK just before this frame is queued */
5433 			ath_tx_update_clrdmask(sc, tid, bf);
5434 
5435 			bf->bf_state.bfs_aggr = 0;
5436 			bf->bf_state.bfs_ndelim = 0;
5437 			ath_tx_setds(sc, bf);
5438 			ath_hal_clr11n_aggr(sc->sc_ah, bf->bf_desc);
5439 			if (status == ATH_AGGR_BAW_CLOSED)
5440 				sc->sc_aggr_stats.aggr_baw_closed_single_pkt++;
5441 			else
5442 				sc->sc_aggr_stats.aggr_single_pkt++;
5443 		} else {
5444 			DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
5445 			    "%s: multi-frame aggregate: %d frames, "
5446 			    "length %d\n",
5447 			     __func__, bf->bf_state.bfs_nframes,
5448 			    bf->bf_state.bfs_al);
5449 			bf->bf_state.bfs_aggr = 1;
5450 			sc->sc_aggr_stats.aggr_pkts[bf->bf_state.bfs_nframes]++;
5451 			sc->sc_aggr_stats.aggr_aggr_pkt++;
5452 
5453 			/* Update CLRDMASK just before this frame is queued */
5454 			ath_tx_update_clrdmask(sc, tid, bf);
5455 
5456 			/*
5457 			 * Calculate the duration/protection as required.
5458 			 */
5459 			ath_tx_calc_duration(sc, bf);
5460 			ath_tx_calc_protection(sc, bf);
5461 
5462 			/*
5463 			 * Update the rate and rtscts information based on the
5464 			 * rate decision made by the rate control code;
5465 			 * the first frame in the aggregate needs it.
5466 			 */
5467 			ath_tx_set_rtscts(sc, bf);
5468 
5469 			/*
5470 			 * Setup the relevant descriptor fields
5471 			 * for aggregation. The first descriptor
5472 			 * already points to the rest in the chain.
5473 			 */
5474 			ath_tx_setds_11n(sc, bf);
5475 
5476 		}
5477 	queuepkt:
5478 		/* Set completion handler, multi-frame aggregate or not */
5479 		bf->bf_comp = ath_tx_aggr_comp;
5480 
5481 		if (bf->bf_state.bfs_tid == IEEE80211_NONQOS_TID)
5482 			DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: TID=16?\n", __func__);
5483 
5484 		/*
5485 		 * Update leak count and frame config if were leaking frames.
5486 		 *
5487 		 * XXX TODO: it should update all frames in an aggregate
5488 		 * correctly!
5489 		 */
5490 		ath_tx_leak_count_update(sc, tid, bf);
5491 
5492 		/* Punt to txq */
5493 		ath_tx_handoff(sc, txq, bf);
5494 
5495 		/* Track outstanding buffer count to hardware */
5496 		/* aggregates are "one" buffer */
5497 		tid->hwq_depth++;
5498 
5499 		/*
5500 		 * Break out if ath_tx_form_aggr() indicated
5501 		 * there can't be any further progress (eg BAW is full.)
5502 		 * Checking for an empty txq is done above.
5503 		 *
5504 		 * XXX locking on txq here?
5505 		 */
5506 		/* XXX TXQ locking */
5507 		if (txq->axq_aggr_depth >= sc->sc_hwq_limit_aggr ||
5508 		    (status == ATH_AGGR_BAW_CLOSED ||
5509 		     status == ATH_AGGR_LEAK_CLOSED))
5510 			break;
5511 	}
5512 }
5513 
5514 /*
5515  * Schedule some packets from the given node/TID to the hardware.
5516  *
5517  * XXX TODO: this routine doesn't enforce the maximum TXQ depth.
5518  * It just dumps frames into the TXQ.  We should limit how deep
5519  * the transmit queue can grow for frames dispatched to the given
5520  * TXQ.
5521  *
5522  * To avoid locking issues, either we need to own the TXQ lock
5523  * at this point, or we need to pass in the maximum frame count
5524  * from the caller.
5525  */
5526 void
5527 ath_tx_tid_hw_queue_norm(struct ath_softc *sc, struct ath_node *an,
5528     struct ath_tid *tid)
5529 {
5530 	struct ath_buf *bf;
5531 	struct ath_txq *txq = sc->sc_ac2q[tid->ac];
5532 
5533 	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: node %p: TID %d: called\n",
5534 	    __func__, an, tid->tid);
5535 
5536 	ATH_TX_LOCK_ASSERT(sc);
5537 
5538 	/* Check - is AMPDU pending or running? then print out something */
5539 	if (ath_tx_ampdu_pending(sc, an, tid->tid))
5540 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: tid=%d, ampdu pending?\n",
5541 		    __func__, tid->tid);
5542 	if (ath_tx_ampdu_running(sc, an, tid->tid))
5543 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: tid=%d, ampdu running?\n",
5544 		    __func__, tid->tid);
5545 
5546 	for (;;) {
5547 
5548 		/*
5549 		 * If the upper layers have paused the TID, don't
5550 		 * queue any further packets.
5551 		 *
5552 		 * XXX if we are leaking frames, make sure we decrement
5553 		 * that counter _and_ we continue here.
5554 		 */
5555 		if (! ath_tx_tid_can_tx_or_sched(sc, tid))
5556 			break;
5557 
5558 		bf = ATH_TID_FIRST(tid);
5559 		if (bf == NULL) {
5560 			break;
5561 		}
5562 
5563 		ATH_TID_REMOVE(tid, bf, bf_list);
5564 
5565 		/* Sanity check! */
5566 		if (tid->tid != bf->bf_state.bfs_tid) {
5567 			DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: bfs_tid %d !="
5568 			    " tid %d\n", __func__, bf->bf_state.bfs_tid,
5569 			    tid->tid);
5570 		}
5571 		/* Normal completion handler */
5572 		bf->bf_comp = ath_tx_normal_comp;
5573 
5574 		/*
5575 		 * Override this for now, until the non-aggregate
5576 		 * completion handler correctly handles software retransmits.
5577 		 */
5578 		bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
5579 
5580 		/* Update CLRDMASK just before this frame is queued */
5581 		ath_tx_update_clrdmask(sc, tid, bf);
5582 
5583 		/* Program descriptors + rate control */
5584 		ath_tx_do_ratelookup(sc, bf);
5585 		ath_tx_calc_duration(sc, bf);
5586 		ath_tx_calc_protection(sc, bf);
5587 		ath_tx_set_rtscts(sc, bf);
5588 		ath_tx_rate_fill_rcflags(sc, bf);
5589 		ath_tx_setds(sc, bf);
5590 
5591 		/*
5592 		 * Update the current leak count if
5593 		 * we're leaking frames; and set the
5594 		 * MORE flag as appropriate.
5595 		 */
5596 		ath_tx_leak_count_update(sc, tid, bf);
5597 
5598 		/* Track outstanding buffer count to hardware */
5599 		/* aggregates are "one" buffer */
5600 		tid->hwq_depth++;
5601 
5602 		/* Punt to hardware or software txq */
5603 		ath_tx_handoff(sc, txq, bf);
5604 	}
5605 }
5606 
5607 /*
5608  * Schedule some packets to the given hardware queue.
5609  *
5610  * This function walks the list of TIDs (ie, ath_node TIDs
5611  * with queued traffic) and attempts to schedule traffic
5612  * from them.
5613  *
5614  * TID scheduling is implemented as a FIFO, with TIDs being
5615  * added to the end of the queue after some frames have been
5616  * scheduled.
5617  */
5618 void
5619 ath_txq_sched(struct ath_softc *sc, struct ath_txq *txq)
5620 {
5621 	struct ath_tid *tid, *next, *last;
5622 
5623 	ATH_TX_LOCK_ASSERT(sc);
5624 
5625 	/*
5626 	 * Don't schedule if the hardware queue is busy.
5627 	 * This (hopefully) gives some more time to aggregate
5628 	 * some packets in the aggregation queue.
5629 	 *
5630 	 * XXX It doesn't stop a parallel sender from sneaking
5631 	 * in transmitting a frame!
5632 	 */
5633 	/* XXX TXQ locking */
5634 	if (txq->axq_aggr_depth + txq->fifo.axq_depth >= sc->sc_hwq_limit_aggr) {
5635 		sc->sc_aggr_stats.aggr_sched_nopkt++;
5636 		return;
5637 	}
5638 	if (txq->axq_depth >= sc->sc_hwq_limit_nonaggr) {
5639 		sc->sc_aggr_stats.aggr_sched_nopkt++;
5640 		return;
5641 	}
5642 
5643 	last = TAILQ_LAST(&txq->axq_tidq, axq_t_s);
5644 
5645 	TAILQ_FOREACH_SAFE(tid, &txq->axq_tidq, axq_qelem, next) {
5646 		/*
5647 		 * Suspend paused queues here; they'll be resumed
5648 		 * once the addba completes or times out.
5649 		 */
5650 		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: tid=%d, paused=%d\n",
5651 		    __func__, tid->tid, tid->paused);
5652 		ath_tx_tid_unsched(sc, tid);
5653 		/*
5654 		 * This node may be in power-save and we're leaking
5655 		 * a frame; be careful.
5656 		 */
5657 		if (! ath_tx_tid_can_tx_or_sched(sc, tid)) {
5658 			goto loop_done;
5659 		}
5660 		if (ath_tx_ampdu_running(sc, tid->an, tid->tid))
5661 			ath_tx_tid_hw_queue_aggr(sc, tid->an, tid);
5662 		else
5663 			ath_tx_tid_hw_queue_norm(sc, tid->an, tid);
5664 
5665 		/* Not empty? Re-schedule */
5666 		if (tid->axq_depth != 0)
5667 			ath_tx_tid_sched(sc, tid);
5668 
5669 		/*
5670 		 * Give the software queue time to aggregate more
5671 		 * packets.  If we aren't running aggregation then
5672 		 * we should still limit the hardware queue depth.
5673 		 */
5674 		/* XXX TXQ locking */
5675 		if (txq->axq_aggr_depth + txq->fifo.axq_depth >= sc->sc_hwq_limit_aggr) {
5676 			break;
5677 		}
5678 		if (txq->axq_depth >= sc->sc_hwq_limit_nonaggr) {
5679 			break;
5680 		}
5681 loop_done:
5682 		/*
5683 		 * If this was the last entry on the original list, stop.
5684 		 * Otherwise nodes that have been rescheduled onto the end
5685 		 * of the TID FIFO list will just keep being rescheduled.
5686 		 *
5687 		 * XXX What should we do about nodes that were paused
5688 		 * but are pending a leaking frame in response to a ps-poll?
5689 		 * They'll be put at the front of the list; so they'll
5690 		 * prematurely trigger this condition! Ew.
5691 		 */
5692 		if (tid == last)
5693 			break;
5694 	}
5695 }
5696 
5697 /*
5698  * TX addba handling
5699  */
5700 
5701 /*
5702  * Return net80211 TID struct pointer, or NULL for none
5703  */
5704 struct ieee80211_tx_ampdu *
5705 ath_tx_get_tx_tid(struct ath_node *an, int tid)
5706 {
5707 	struct ieee80211_node *ni = &an->an_node;
5708 	struct ieee80211_tx_ampdu *tap;
5709 
5710 	if (tid == IEEE80211_NONQOS_TID)
5711 		return NULL;
5712 
5713 	tap = &ni->ni_tx_ampdu[tid];
5714 	return tap;
5715 }
5716 
5717 /*
5718  * Is AMPDU-TX running?
5719  */
5720 static int
5721 ath_tx_ampdu_running(struct ath_softc *sc, struct ath_node *an, int tid)
5722 {
5723 	struct ieee80211_tx_ampdu *tap;
5724 
5725 	if (tid == IEEE80211_NONQOS_TID)
5726 		return 0;
5727 
5728 	tap = ath_tx_get_tx_tid(an, tid);
5729 	if (tap == NULL)
5730 		return 0;	/* Not valid; default to not running */
5731 
5732 	return !! (tap->txa_flags & IEEE80211_AGGR_RUNNING);
5733 }
5734 
5735 /*
5736  * Is AMPDU-TX negotiation pending?
5737  */
5738 static int
5739 ath_tx_ampdu_pending(struct ath_softc *sc, struct ath_node *an, int tid)
5740 {
5741 	struct ieee80211_tx_ampdu *tap;
5742 
5743 	if (tid == IEEE80211_NONQOS_TID)
5744 		return 0;
5745 
5746 	tap = ath_tx_get_tx_tid(an, tid);
5747 	if (tap == NULL)
5748 		return 0;	/* Not valid; default to not pending */
5749 
5750 	return !! (tap->txa_flags & IEEE80211_AGGR_XCHGPEND);
5751 }
5752 
5753 /*
5754  * Is AMPDU-TX pending for the given TID?
5755  */
5756 
5757 
5758 /*
5759  * Method to handle sending an ADDBA request.
5760  *
5761  * We tap this so the relevant flags can be set to pause the TID
5762  * whilst waiting for the response.
5763  *
5764  * XXX there's no timeout handler we can override?
5765  */
5766 int
5767 ath_addba_request(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
5768     int dialogtoken, int baparamset, int batimeout)
5769 {
5770 	struct ath_softc *sc = ni->ni_ic->ic_softc;
5771 	int tid = tap->txa_tid;
5772 	struct ath_node *an = ATH_NODE(ni);
5773 	struct ath_tid *atid = &an->an_tid[tid];
5774 
5775 	/*
5776 	 * XXX danger Will Robinson!
5777 	 *
5778 	 * Although the taskqueue may be running and scheduling some more
5779 	 * packets, these should all be _before_ the addba sequence number.
5780 	 * However, net80211 will keep self-assigning sequence numbers
5781 	 * until addba has been negotiated.
5782 	 *
5783 	 * In the past, these packets would be "paused" (which still works
5784 	 * fine, as they're being scheduled to the driver in the same
5785 	 * serialised method which is calling the addba request routine)
5786 	 * and when the aggregation session begins, they'll be dequeued
5787 	 * as aggregate packets and added to the BAW. However, now there's
5788 	 * a "bf->bf_state.bfs_dobaw" flag, and this isn't set for these
5789 	 * packets. Thus they never get included in the BAW tracking and
5790 	 * this can cause the initial burst of packets after the addba
5791 	 * negotiation to "hang", as they quickly fall outside the BAW.
5792 	 *
5793 	 * The "eventual" solution should be to tag these packets with
5794 	 * dobaw. Although net80211 has given us a sequence number,
5795 	 * it'll be "after" the left edge of the BAW and thus it'll
5796 	 * fall within it.
5797 	 */
5798 	ATH_TX_LOCK(sc);
5799 	/*
5800 	 * This is a bit annoying.  Until net80211 HT code inherits some
5801 	 * (any) locking, we may have this called in parallel BUT only
5802 	 * one response/timeout will be called.  Grr.
5803 	 */
5804 	if (atid->addba_tx_pending == 0) {
5805 		ath_tx_tid_pause(sc, atid);
5806 		atid->addba_tx_pending = 1;
5807 	}
5808 	ATH_TX_UNLOCK(sc);
5809 
5810 	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
5811 	    "%s: %6D: called; dialogtoken=%d, baparamset=%d, batimeout=%d\n",
5812 	    __func__,
5813 	    ni->ni_macaddr,
5814 	    ":",
5815 	    dialogtoken, baparamset, batimeout);
5816 	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
5817 	    "%s: txa_start=%d, ni_txseqs=%d\n",
5818 	    __func__, tap->txa_start, ni->ni_txseqs[tid]);
5819 
5820 	return sc->sc_addba_request(ni, tap, dialogtoken, baparamset,
5821 	    batimeout);
5822 }
5823 
5824 /*
5825  * Handle an ADDBA response.
5826  *
5827  * We unpause the queue so TX'ing can resume.
5828  *
5829  * Any packets TX'ed from this point should be "aggregate" (whether
5830  * aggregate or not) so the BAW is updated.
5831  *
5832  * Note! net80211 keeps self-assigning sequence numbers until
5833  * ampdu is negotiated. This means the initially-negotiated BAW left
5834  * edge won't match the ni->ni_txseq.
5835  *
5836  * So, being very dirty, the BAW left edge is "slid" here to match
5837  * ni->ni_txseq.
5838  *
5839  * What likely SHOULD happen is that all packets subsequent to the
5840  * addba request should be tagged as aggregate and queued as non-aggregate
5841  * frames; thus updating the BAW. For now though, I'll just slide the
5842  * window.
5843  */
5844 int
5845 ath_addba_response(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
5846     int status, int code, int batimeout)
5847 {
5848 	struct ath_softc *sc = ni->ni_ic->ic_softc;
5849 	int tid = tap->txa_tid;
5850 	struct ath_node *an = ATH_NODE(ni);
5851 	struct ath_tid *atid = &an->an_tid[tid];
5852 	int r;
5853 
5854 	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
5855 	    "%s: %6D: called; status=%d, code=%d, batimeout=%d\n", __func__,
5856 	    ni->ni_macaddr,
5857 	    ":",
5858 	    status, code, batimeout);
5859 
5860 	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
5861 	    "%s: txa_start=%d, ni_txseqs=%d\n",
5862 	    __func__, tap->txa_start, ni->ni_txseqs[tid]);
5863 
5864 	/*
5865 	 * Call this first, so the interface flags get updated
5866 	 * before the TID is unpaused. Otherwise a race condition
5867 	 * exists where the unpaused TID still doesn't yet have
5868 	 * IEEE80211_AGGR_RUNNING set.
5869 	 */
5870 	r = sc->sc_addba_response(ni, tap, status, code, batimeout);
5871 
5872 	ATH_TX_LOCK(sc);
5873 	atid->addba_tx_pending = 0;
5874 	/*
5875 	 * XXX dirty!
5876 	 * Slide the BAW left edge to wherever net80211 left it for us.
5877 	 * Read above for more information.
5878 	 */
5879 	tap->txa_start = ni->ni_txseqs[tid];
5880 	ath_tx_tid_resume(sc, atid);
5881 	ATH_TX_UNLOCK(sc);
5882 	return r;
5883 }
5884 
5885 
5886 /*
5887  * Stop ADDBA on a queue.
5888  *
5889  * This can be called whilst BAR TX is currently active on the queue,
5890  * so make sure this is unblocked before continuing.
5891  */
5892 void
5893 ath_addba_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
5894 {
5895 	struct ath_softc *sc = ni->ni_ic->ic_softc;
5896 	int tid = tap->txa_tid;
5897 	struct ath_node *an = ATH_NODE(ni);
5898 	struct ath_tid *atid = &an->an_tid[tid];
5899 	ath_bufhead bf_cq;
5900 	struct ath_buf *bf;
5901 
5902 	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL, "%s: %6D: called\n",
5903 	    __func__,
5904 	    ni->ni_macaddr,
5905 	    ":");
5906 
5907 	/*
5908 	 * Pause TID traffic early, so there aren't any races
5909 	 * Unblock the pending BAR held traffic, if it's currently paused.
5910 	 */
5911 	ATH_TX_LOCK(sc);
5912 	ath_tx_tid_pause(sc, atid);
5913 	if (atid->bar_wait) {
5914 		/*
5915 		 * bar_unsuspend() expects bar_tx == 1, as it should be
5916 		 * called from the TX completion path.  This quietens
5917 		 * the warning.  It's cleared for us anyway.
5918 		 */
5919 		atid->bar_tx = 1;
5920 		ath_tx_tid_bar_unsuspend(sc, atid);
5921 	}
5922 	ATH_TX_UNLOCK(sc);
5923 
5924 	/* There's no need to hold the TXQ lock here */
5925 	sc->sc_addba_stop(ni, tap);
5926 
5927 	/*
5928 	 * ath_tx_tid_cleanup will resume the TID if possible, otherwise
5929 	 * it'll set the cleanup flag, and it'll be unpaused once
5930 	 * things have been cleaned up.
5931 	 */
5932 	TAILQ_INIT(&bf_cq);
5933 	ATH_TX_LOCK(sc);
5934 
5935 	/*
5936 	 * In case there's a followup call to this, only call it
5937 	 * if we don't have a cleanup in progress.
5938 	 *
5939 	 * Since we've paused the queue above, we need to make
5940 	 * sure we unpause if there's already a cleanup in
5941 	 * progress - it means something else is also doing
5942 	 * this stuff, so we don't need to also keep it paused.
5943 	 */
5944 	if (atid->cleanup_inprogress) {
5945 		ath_tx_tid_resume(sc, atid);
5946 	} else {
5947 		ath_tx_tid_cleanup(sc, an, tid, &bf_cq);
5948 		/*
5949 		 * Unpause the TID if no cleanup is required.
5950 		 */
5951 		if (! atid->cleanup_inprogress)
5952 			ath_tx_tid_resume(sc, atid);
5953 	}
5954 	ATH_TX_UNLOCK(sc);
5955 
5956 	/* Handle completing frames and fail them */
5957 	while ((bf = TAILQ_FIRST(&bf_cq)) != NULL) {
5958 		TAILQ_REMOVE(&bf_cq, bf, bf_list);
5959 		ath_tx_default_comp(sc, bf, 1);
5960 	}
5961 
5962 }
5963 
5964 /*
5965  * Handle a node reassociation.
5966  *
5967  * We may have a bunch of frames queued to the hardware; those need
5968  * to be marked as cleanup.
5969  */
5970 void
5971 ath_tx_node_reassoc(struct ath_softc *sc, struct ath_node *an)
5972 {
5973 	struct ath_tid *tid;
5974 	int i;
5975 	ath_bufhead bf_cq;
5976 	struct ath_buf *bf;
5977 
5978 	TAILQ_INIT(&bf_cq);
5979 
5980 	ATH_TX_UNLOCK_ASSERT(sc);
5981 
5982 	ATH_TX_LOCK(sc);
5983 	for (i = 0; i < IEEE80211_TID_SIZE; i++) {
5984 		tid = &an->an_tid[i];
5985 		if (tid->hwq_depth == 0)
5986 			continue;
5987 		DPRINTF(sc, ATH_DEBUG_NODE,
5988 		    "%s: %6D: TID %d: cleaning up TID\n",
5989 		    __func__,
5990 		    an->an_node.ni_macaddr,
5991 		    ":",
5992 		    i);
5993 		/*
5994 		 * In case there's a followup call to this, only call it
5995 		 * if we don't have a cleanup in progress.
5996 		 */
5997 		if (! tid->cleanup_inprogress) {
5998 			ath_tx_tid_pause(sc, tid);
5999 			ath_tx_tid_cleanup(sc, an, i, &bf_cq);
6000 			/*
6001 			 * Unpause the TID if no cleanup is required.
6002 			 */
6003 			if (! tid->cleanup_inprogress)
6004 				ath_tx_tid_resume(sc, tid);
6005 		}
6006 	}
6007 	ATH_TX_UNLOCK(sc);
6008 
6009 	/* Handle completing frames and fail them */
6010 	while ((bf = TAILQ_FIRST(&bf_cq)) != NULL) {
6011 		TAILQ_REMOVE(&bf_cq, bf, bf_list);
6012 		ath_tx_default_comp(sc, bf, 1);
6013 	}
6014 }
6015 
6016 /*
6017  * Note: net80211 bar_timeout() doesn't call this function on BAR failure;
6018  * it simply tears down the aggregation session. Ew.
6019  *
6020  * It however will call ieee80211_ampdu_stop() which will call
6021  * ic->ic_addba_stop().
6022  *
6023  * XXX This uses a hard-coded max BAR count value; the whole
6024  * XXX BAR TX success or failure should be better handled!
6025  */
6026 void
6027 ath_bar_response(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
6028     int status)
6029 {
6030 	struct ath_softc *sc = ni->ni_ic->ic_softc;
6031 	int tid = tap->txa_tid;
6032 	struct ath_node *an = ATH_NODE(ni);
6033 	struct ath_tid *atid = &an->an_tid[tid];
6034 	int attempts = tap->txa_attempts;
6035 	int old_txa_start;
6036 
6037 	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
6038 	    "%s: %6D: called; txa_tid=%d, atid->tid=%d, status=%d, attempts=%d, txa_start=%d, txa_seqpending=%d\n",
6039 	    __func__,
6040 	    ni->ni_macaddr,
6041 	    ":",
6042 	    tap->txa_tid,
6043 	    atid->tid,
6044 	    status,
6045 	    attempts,
6046 	    tap->txa_start,
6047 	    tap->txa_seqpending);
6048 
6049 	/* Note: This may update the BAW details */
6050 	/*
6051 	 * XXX What if this does slide the BAW along? We need to somehow
6052 	 * XXX either fix things when it does happen, or prevent the
6053 	 * XXX seqpending value to be anything other than exactly what
6054 	 * XXX the hell we want!
6055 	 *
6056 	 * XXX So for now, how I do this inside the TX lock for now
6057 	 * XXX and just correct it afterwards? The below condition should
6058 	 * XXX never happen and if it does I need to fix all kinds of things.
6059 	 */
6060 	ATH_TX_LOCK(sc);
6061 	old_txa_start = tap->txa_start;
6062 	sc->sc_bar_response(ni, tap, status);
6063 	if (tap->txa_start != old_txa_start) {
6064 		device_printf(sc->sc_dev, "%s: tid=%d; txa_start=%d, old=%d, adjusting\n",
6065 		    __func__,
6066 		    tid,
6067 		    tap->txa_start,
6068 		    old_txa_start);
6069 	}
6070 	tap->txa_start = old_txa_start;
6071 	ATH_TX_UNLOCK(sc);
6072 
6073 	/* Unpause the TID */
6074 	/*
6075 	 * XXX if this is attempt=50, the TID will be downgraded
6076 	 * XXX to a non-aggregate session. So we must unpause the
6077 	 * XXX TID here or it'll never be done.
6078 	 *
6079 	 * Also, don't call it if bar_tx/bar_wait are 0; something
6080 	 * has beaten us to the punch? (XXX figure out what?)
6081 	 */
6082 	if (status == 0 || attempts == 50) {
6083 		ATH_TX_LOCK(sc);
6084 		if (atid->bar_tx == 0 || atid->bar_wait == 0)
6085 			DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
6086 			    "%s: huh? bar_tx=%d, bar_wait=%d\n",
6087 			    __func__,
6088 			    atid->bar_tx, atid->bar_wait);
6089 		else
6090 			ath_tx_tid_bar_unsuspend(sc, atid);
6091 		ATH_TX_UNLOCK(sc);
6092 	}
6093 }
6094 
6095 /*
6096  * This is called whenever the pending ADDBA request times out.
6097  * Unpause and reschedule the TID.
6098  */
6099 void
6100 ath_addba_response_timeout(struct ieee80211_node *ni,
6101     struct ieee80211_tx_ampdu *tap)
6102 {
6103 	struct ath_softc *sc = ni->ni_ic->ic_softc;
6104 	int tid = tap->txa_tid;
6105 	struct ath_node *an = ATH_NODE(ni);
6106 	struct ath_tid *atid = &an->an_tid[tid];
6107 
6108 	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
6109 	    "%s: %6D: TID=%d, called; resuming\n",
6110 	    __func__,
6111 	    ni->ni_macaddr,
6112 	    ":",
6113 	    tid);
6114 
6115 	ATH_TX_LOCK(sc);
6116 	atid->addba_tx_pending = 0;
6117 	ATH_TX_UNLOCK(sc);
6118 
6119 	/* Note: This updates the aggregate state to (again) pending */
6120 	sc->sc_addba_response_timeout(ni, tap);
6121 
6122 	/* Unpause the TID; which reschedules it */
6123 	ATH_TX_LOCK(sc);
6124 	ath_tx_tid_resume(sc, atid);
6125 	ATH_TX_UNLOCK(sc);
6126 }
6127 
6128 /*
6129  * Check if a node is asleep or not.
6130  */
6131 int
6132 ath_tx_node_is_asleep(struct ath_softc *sc, struct ath_node *an)
6133 {
6134 
6135 	ATH_TX_LOCK_ASSERT(sc);
6136 
6137 	return (an->an_is_powersave);
6138 }
6139 
6140 /*
6141  * Mark a node as currently "in powersaving."
6142  * This suspends all traffic on the node.
6143  *
6144  * This must be called with the node/tx locks free.
6145  *
6146  * XXX TODO: the locking silliness below is due to how the node
6147  * locking currently works.  Right now, the node lock is grabbed
6148  * to do rate control lookups and these are done with the TX
6149  * queue lock held.  This means the node lock can't be grabbed
6150  * first here or a LOR will occur.
6151  *
6152  * Eventually (hopefully!) the TX path code will only grab
6153  * the TXQ lock when transmitting and the ath_node lock when
6154  * doing node/TID operations.  There are other complications -
6155  * the sched/unsched operations involve walking the per-txq
6156  * 'active tid' list and this requires both locks to be held.
6157  */
6158 void
6159 ath_tx_node_sleep(struct ath_softc *sc, struct ath_node *an)
6160 {
6161 	struct ath_tid *atid;
6162 	struct ath_txq *txq;
6163 	int tid;
6164 
6165 	ATH_TX_UNLOCK_ASSERT(sc);
6166 
6167 	/* Suspend all traffic on the node */
6168 	ATH_TX_LOCK(sc);
6169 
6170 	if (an->an_is_powersave) {
6171 		DPRINTF(sc, ATH_DEBUG_XMIT,
6172 		    "%s: %6D: node was already asleep!\n",
6173 		    __func__, an->an_node.ni_macaddr, ":");
6174 		ATH_TX_UNLOCK(sc);
6175 		return;
6176 	}
6177 
6178 	for (tid = 0; tid < IEEE80211_TID_SIZE; tid++) {
6179 		atid = &an->an_tid[tid];
6180 		txq = sc->sc_ac2q[atid->ac];
6181 
6182 		ath_tx_tid_pause(sc, atid);
6183 	}
6184 
6185 	/* Mark node as in powersaving */
6186 	an->an_is_powersave = 1;
6187 
6188 	ATH_TX_UNLOCK(sc);
6189 }
6190 
6191 /*
6192  * Mark a node as currently "awake."
6193  * This resumes all traffic to the node.
6194  */
6195 void
6196 ath_tx_node_wakeup(struct ath_softc *sc, struct ath_node *an)
6197 {
6198 	struct ath_tid *atid;
6199 	struct ath_txq *txq;
6200 	int tid;
6201 
6202 	ATH_TX_UNLOCK_ASSERT(sc);
6203 
6204 	ATH_TX_LOCK(sc);
6205 
6206 	/* !? */
6207 	if (an->an_is_powersave == 0) {
6208 		ATH_TX_UNLOCK(sc);
6209 		DPRINTF(sc, ATH_DEBUG_XMIT,
6210 		    "%s: an=%p: node was already awake\n",
6211 		    __func__, an);
6212 		return;
6213 	}
6214 
6215 	/* Mark node as awake */
6216 	an->an_is_powersave = 0;
6217 	/*
6218 	 * Clear any pending leaked frame requests
6219 	 */
6220 	an->an_leak_count = 0;
6221 
6222 	for (tid = 0; tid < IEEE80211_TID_SIZE; tid++) {
6223 		atid = &an->an_tid[tid];
6224 		txq = sc->sc_ac2q[atid->ac];
6225 
6226 		ath_tx_tid_resume(sc, atid);
6227 	}
6228 	ATH_TX_UNLOCK(sc);
6229 }
6230 
6231 static int
6232 ath_legacy_dma_txsetup(struct ath_softc *sc)
6233 {
6234 
6235 	/* nothing new needed */
6236 	return (0);
6237 }
6238 
6239 static int
6240 ath_legacy_dma_txteardown(struct ath_softc *sc)
6241 {
6242 
6243 	/* nothing new needed */
6244 	return (0);
6245 }
6246 
6247 void
6248 ath_xmit_setup_legacy(struct ath_softc *sc)
6249 {
6250 	/*
6251 	 * For now, just set the descriptor length to sizeof(ath_desc);
6252 	 * worry about extracting the real length out of the HAL later.
6253 	 */
6254 	sc->sc_tx_desclen = sizeof(struct ath_desc);
6255 	sc->sc_tx_statuslen = sizeof(struct ath_desc);
6256 	sc->sc_tx_nmaps = 1;	/* only one buffer per TX desc */
6257 
6258 	sc->sc_tx.xmit_setup = ath_legacy_dma_txsetup;
6259 	sc->sc_tx.xmit_teardown = ath_legacy_dma_txteardown;
6260 	sc->sc_tx.xmit_attach_comp_func = ath_legacy_attach_comp_func;
6261 
6262 	sc->sc_tx.xmit_dma_restart = ath_legacy_tx_dma_restart;
6263 	sc->sc_tx.xmit_handoff = ath_legacy_xmit_handoff;
6264 
6265 	sc->sc_tx.xmit_drain = ath_legacy_tx_drain;
6266 }
6267