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