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