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