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