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