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