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