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