if_ath.c revision 217323
1/*-
2 * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer,
10 *    without modification.
11 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12 *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13 *    redistribution must be conditioned upon including a substantially
14 *    similar Disclaimer requirement for further binary redistribution.
15 *
16 * NO WARRANTY
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
20 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21 * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
22 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27 * THE POSSIBILITY OF SUCH DAMAGES.
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath.c 217323 2011-01-12 19:53:56Z mdf $");
32
33/*
34 * Driver for the Atheros Wireless LAN controller.
35 *
36 * This software is derived from work of Atsushi Onoe; his contribution
37 * is greatly appreciated.
38 */
39
40#include "opt_inet.h"
41#include "opt_ath.h"
42#include "opt_wlan.h"
43
44#include <sys/param.h>
45#include <sys/systm.h>
46#include <sys/sysctl.h>
47#include <sys/mbuf.h>
48#include <sys/malloc.h>
49#include <sys/lock.h>
50#include <sys/mutex.h>
51#include <sys/kernel.h>
52#include <sys/socket.h>
53#include <sys/sockio.h>
54#include <sys/errno.h>
55#include <sys/callout.h>
56#include <sys/bus.h>
57#include <sys/endian.h>
58#include <sys/kthread.h>
59#include <sys/taskqueue.h>
60#include <sys/priv.h>
61
62#include <machine/bus.h>
63
64#include <net/if.h>
65#include <net/if_dl.h>
66#include <net/if_media.h>
67#include <net/if_types.h>
68#include <net/if_arp.h>
69#include <net/ethernet.h>
70#include <net/if_llc.h>
71
72#include <net80211/ieee80211_var.h>
73#include <net80211/ieee80211_regdomain.h>
74#ifdef IEEE80211_SUPPORT_SUPERG
75#include <net80211/ieee80211_superg.h>
76#endif
77#ifdef IEEE80211_SUPPORT_TDMA
78#include <net80211/ieee80211_tdma.h>
79#endif
80
81#include <net/bpf.h>
82
83#ifdef INET
84#include <netinet/in.h>
85#include <netinet/if_ether.h>
86#endif
87
88#include <dev/ath/if_athvar.h>
89#include <dev/ath/ath_hal/ah_devid.h>		/* XXX for softled */
90
91#ifdef ATH_TX99_DIAG
92#include <dev/ath/ath_tx99/ath_tx99.h>
93#endif
94
95/*
96 * ATH_BCBUF determines the number of vap's that can transmit
97 * beacons and also (currently) the number of vap's that can
98 * have unique mac addresses/bssid.  When staggering beacons
99 * 4 is probably a good max as otherwise the beacons become
100 * very closely spaced and there is limited time for cab q traffic
101 * to go out.  You can burst beacons instead but that is not good
102 * for stations in power save and at some point you really want
103 * another radio (and channel).
104 *
105 * The limit on the number of mac addresses is tied to our use of
106 * the U/L bit and tracking addresses in a byte; it would be
107 * worthwhile to allow more for applications like proxy sta.
108 */
109CTASSERT(ATH_BCBUF <= 8);
110
111/* unaligned little endian access */
112#define LE_READ_2(p)							\
113	((u_int16_t)							\
114	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
115#define LE_READ_4(p)							\
116	((u_int32_t)							\
117	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) |	\
118	  (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
119
120static struct ieee80211vap *ath_vap_create(struct ieee80211com *,
121		    const char name[IFNAMSIZ], int unit, int opmode,
122		    int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
123		    const uint8_t mac[IEEE80211_ADDR_LEN]);
124static void	ath_vap_delete(struct ieee80211vap *);
125static void	ath_init(void *);
126static void	ath_stop_locked(struct ifnet *);
127static void	ath_stop(struct ifnet *);
128static void	ath_start(struct ifnet *);
129static int	ath_reset(struct ifnet *);
130static int	ath_reset_vap(struct ieee80211vap *, u_long);
131static int	ath_media_change(struct ifnet *);
132static void	ath_watchdog(void *);
133static int	ath_ioctl(struct ifnet *, u_long, caddr_t);
134static void	ath_fatal_proc(void *, int);
135static void	ath_bmiss_vap(struct ieee80211vap *);
136static void	ath_bmiss_proc(void *, int);
137static int	ath_keyset(struct ath_softc *, const struct ieee80211_key *,
138			struct ieee80211_node *);
139static int	ath_key_alloc(struct ieee80211vap *,
140			struct ieee80211_key *,
141			ieee80211_keyix *, ieee80211_keyix *);
142static int	ath_key_delete(struct ieee80211vap *,
143			const struct ieee80211_key *);
144static int	ath_key_set(struct ieee80211vap *, const struct ieee80211_key *,
145			const u_int8_t mac[IEEE80211_ADDR_LEN]);
146static void	ath_key_update_begin(struct ieee80211vap *);
147static void	ath_key_update_end(struct ieee80211vap *);
148static void	ath_update_mcast(struct ifnet *);
149static void	ath_update_promisc(struct ifnet *);
150static void	ath_mode_init(struct ath_softc *);
151static void	ath_setslottime(struct ath_softc *);
152static void	ath_updateslot(struct ifnet *);
153static int	ath_beaconq_setup(struct ath_hal *);
154static int	ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
155static void	ath_beacon_update(struct ieee80211vap *, int item);
156static void	ath_beacon_setup(struct ath_softc *, struct ath_buf *);
157static void	ath_beacon_proc(void *, int);
158static struct ath_buf *ath_beacon_generate(struct ath_softc *,
159			struct ieee80211vap *);
160static void	ath_bstuck_proc(void *, int);
161static void	ath_beacon_return(struct ath_softc *, struct ath_buf *);
162static void	ath_beacon_free(struct ath_softc *);
163static void	ath_beacon_config(struct ath_softc *, struct ieee80211vap *);
164static void	ath_descdma_cleanup(struct ath_softc *sc,
165			struct ath_descdma *, ath_bufhead *);
166static int	ath_desc_alloc(struct ath_softc *);
167static void	ath_desc_free(struct ath_softc *);
168static struct ieee80211_node *ath_node_alloc(struct ieee80211vap *,
169			const uint8_t [IEEE80211_ADDR_LEN]);
170static void	ath_node_free(struct ieee80211_node *);
171static void	ath_node_getsignal(const struct ieee80211_node *,
172			int8_t *, int8_t *);
173static int	ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
174static void	ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
175			int subtype, int rssi, int nf);
176static void	ath_setdefantenna(struct ath_softc *, u_int);
177static void	ath_rx_proc(void *, int);
178static void	ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
179static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
180static int	ath_tx_setup(struct ath_softc *, int, int);
181static int	ath_wme_update(struct ieee80211com *);
182static void	ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
183static void	ath_tx_cleanup(struct ath_softc *);
184static void	ath_freetx(struct mbuf *);
185static int	ath_tx_start(struct ath_softc *, struct ieee80211_node *,
186			     struct ath_buf *, struct mbuf *);
187static void	ath_tx_proc_q0(void *, int);
188static void	ath_tx_proc_q0123(void *, int);
189static void	ath_tx_proc(void *, int);
190static void	ath_tx_draintxq(struct ath_softc *, struct ath_txq *);
191static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
192static void	ath_draintxq(struct ath_softc *);
193static void	ath_stoprecv(struct ath_softc *);
194static int	ath_startrecv(struct ath_softc *);
195static void	ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
196static void	ath_scan_start(struct ieee80211com *);
197static void	ath_scan_end(struct ieee80211com *);
198static void	ath_set_channel(struct ieee80211com *);
199static void	ath_calibrate(void *);
200static int	ath_newstate(struct ieee80211vap *, enum ieee80211_state, int);
201static void	ath_setup_stationkey(struct ieee80211_node *);
202static void	ath_newassoc(struct ieee80211_node *, int);
203static int	ath_setregdomain(struct ieee80211com *,
204		    struct ieee80211_regdomain *, int,
205		    struct ieee80211_channel []);
206static void	ath_getradiocaps(struct ieee80211com *, int, int *,
207		    struct ieee80211_channel []);
208static int	ath_getchannels(struct ath_softc *);
209static void	ath_led_event(struct ath_softc *, int);
210
211static int	ath_rate_setup(struct ath_softc *, u_int mode);
212static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
213
214static void	ath_sysctlattach(struct ath_softc *);
215static int	ath_raw_xmit(struct ieee80211_node *,
216			struct mbuf *, const struct ieee80211_bpf_params *);
217static void	ath_announce(struct ath_softc *);
218static void	ath_sysctl_stats_attach(struct ath_softc *sc);
219
220#ifdef IEEE80211_SUPPORT_TDMA
221static void	ath_tdma_settimers(struct ath_softc *sc, u_int32_t nexttbtt,
222		    u_int32_t bintval);
223static void	ath_tdma_bintvalsetup(struct ath_softc *sc,
224		    const struct ieee80211_tdma_state *tdma);
225static void	ath_tdma_config(struct ath_softc *sc, struct ieee80211vap *vap);
226static void	ath_tdma_update(struct ieee80211_node *ni,
227		    const struct ieee80211_tdma_param *tdma, int);
228static void	ath_tdma_beacon_send(struct ath_softc *sc,
229		    struct ieee80211vap *vap);
230
231static __inline void
232ath_hal_setcca(struct ath_hal *ah, int ena)
233{
234	/*
235	 * NB: fill me in; this is not provided by default because disabling
236	 *     CCA in most locales violates regulatory.
237	 */
238}
239
240static __inline int
241ath_hal_getcca(struct ath_hal *ah)
242{
243	u_int32_t diag;
244	if (ath_hal_getcapability(ah, HAL_CAP_DIAG, 0, &diag) != HAL_OK)
245		return 1;
246	return ((diag & 0x500000) == 0);
247}
248
249#define	TDMA_EP_MULTIPLIER	(1<<10) /* pow2 to optimize out * and / */
250#define	TDMA_LPF_LEN		6
251#define	TDMA_DUMMY_MARKER	0x127
252#define	TDMA_EP_MUL(x, mul)	((x) * (mul))
253#define	TDMA_IN(x)		(TDMA_EP_MUL((x), TDMA_EP_MULTIPLIER))
254#define	TDMA_LPF(x, y, len) \
255    ((x != TDMA_DUMMY_MARKER) ? (((x) * ((len)-1) + (y)) / (len)) : (y))
256#define	TDMA_SAMPLE(x, y) do {					\
257	x = TDMA_LPF((x), TDMA_IN(y), TDMA_LPF_LEN);		\
258} while (0)
259#define	TDMA_EP_RND(x,mul) \
260	((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
261#define	TDMA_AVG(x)		TDMA_EP_RND(x, TDMA_EP_MULTIPLIER)
262#endif /* IEEE80211_SUPPORT_TDMA */
263
264SYSCTL_DECL(_hw_ath);
265
266/* XXX validate sysctl values */
267static	int ath_longcalinterval = 30;		/* long cals every 30 secs */
268SYSCTL_INT(_hw_ath, OID_AUTO, longcal, CTLFLAG_RW, &ath_longcalinterval,
269	    0, "long chip calibration interval (secs)");
270static	int ath_shortcalinterval = 100;		/* short cals every 100 ms */
271SYSCTL_INT(_hw_ath, OID_AUTO, shortcal, CTLFLAG_RW, &ath_shortcalinterval,
272	    0, "short chip calibration interval (msecs)");
273static	int ath_resetcalinterval = 20*60;	/* reset cal state 20 mins */
274SYSCTL_INT(_hw_ath, OID_AUTO, resetcal, CTLFLAG_RW, &ath_resetcalinterval,
275	    0, "reset chip calibration results (secs)");
276
277static	int ath_rxbuf = ATH_RXBUF;		/* # rx buffers to allocate */
278SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RW, &ath_rxbuf,
279	    0, "rx buffers allocated");
280TUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
281static	int ath_txbuf = ATH_TXBUF;		/* # tx buffers to allocate */
282SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RW, &ath_txbuf,
283	    0, "tx buffers allocated");
284TUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
285
286static	int ath_bstuck_threshold = 4;		/* max missed beacons */
287SYSCTL_INT(_hw_ath, OID_AUTO, bstuck, CTLFLAG_RW, &ath_bstuck_threshold,
288	    0, "max missed beacon xmits before chip reset");
289
290#ifdef ATH_DEBUG
291enum {
292	ATH_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
293	ATH_DEBUG_XMIT_DESC	= 0x00000002,	/* xmit descriptors */
294	ATH_DEBUG_RECV		= 0x00000004,	/* basic recv operation */
295	ATH_DEBUG_RECV_DESC	= 0x00000008,	/* recv descriptors */
296	ATH_DEBUG_RATE		= 0x00000010,	/* rate control */
297	ATH_DEBUG_RESET		= 0x00000020,	/* reset processing */
298	ATH_DEBUG_MODE		= 0x00000040,	/* mode init/setup */
299	ATH_DEBUG_BEACON 	= 0x00000080,	/* beacon handling */
300	ATH_DEBUG_WATCHDOG 	= 0x00000100,	/* watchdog timeout */
301	ATH_DEBUG_INTR		= 0x00001000,	/* ISR */
302	ATH_DEBUG_TX_PROC	= 0x00002000,	/* tx ISR proc */
303	ATH_DEBUG_RX_PROC	= 0x00004000,	/* rx ISR proc */
304	ATH_DEBUG_BEACON_PROC	= 0x00008000,	/* beacon ISR proc */
305	ATH_DEBUG_CALIBRATE	= 0x00010000,	/* periodic calibration */
306	ATH_DEBUG_KEYCACHE	= 0x00020000,	/* key cache management */
307	ATH_DEBUG_STATE		= 0x00040000,	/* 802.11 state transitions */
308	ATH_DEBUG_NODE		= 0x00080000,	/* node management */
309	ATH_DEBUG_LED		= 0x00100000,	/* led management */
310	ATH_DEBUG_FF		= 0x00200000,	/* fast frames */
311	ATH_DEBUG_DFS		= 0x00400000,	/* DFS processing */
312	ATH_DEBUG_TDMA		= 0x00800000,	/* TDMA processing */
313	ATH_DEBUG_TDMA_TIMER	= 0x01000000,	/* TDMA timer processing */
314	ATH_DEBUG_REGDOMAIN	= 0x02000000,	/* regulatory processing */
315	ATH_DEBUG_FATAL		= 0x80000000,	/* fatal errors */
316	ATH_DEBUG_ANY		= 0xffffffff
317};
318static	int ath_debug = 0;
319SYSCTL_INT(_hw_ath, OID_AUTO, debug, CTLFLAG_RW, &ath_debug,
320	    0, "control debugging printfs");
321TUNABLE_INT("hw.ath.debug", &ath_debug);
322
323#define	IFF_DUMPPKTS(sc, m) \
324	((sc->sc_debug & (m)) || \
325	    (sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
326#define	DPRINTF(sc, m, fmt, ...) do {				\
327	if (sc->sc_debug & (m))					\
328		device_printf(sc->sc_dev, fmt, __VA_ARGS__);		\
329} while (0)
330#define	KEYPRINTF(sc, ix, hk, mac) do {				\
331	if (sc->sc_debug & ATH_DEBUG_KEYCACHE)			\
332		ath_keyprint(sc, __func__, ix, hk, mac);	\
333} while (0)
334static	void ath_printrxbuf(struct ath_softc *, const struct ath_buf *bf,
335	u_int ix, int);
336static	void ath_printtxbuf(struct ath_softc *, const struct ath_buf *bf,
337	u_int qnum, u_int ix, int done);
338#else
339#define	IFF_DUMPPKTS(sc, m) \
340	((sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
341#define	DPRINTF(sc, m, fmt, ...) do {				\
342	(void) sc;						\
343} while (0)
344#define	KEYPRINTF(sc, k, ix, mac) do {				\
345	(void) sc;						\
346} while (0)
347#endif
348
349MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
350
351int
352ath_attach(u_int16_t devid, struct ath_softc *sc)
353{
354	struct ifnet *ifp;
355	struct ieee80211com *ic;
356	struct ath_hal *ah = NULL;
357	HAL_STATUS status;
358	int error = 0, i;
359	u_int wmodes;
360	uint8_t macaddr[IEEE80211_ADDR_LEN];
361
362	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
363
364	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
365	if (ifp == NULL) {
366		device_printf(sc->sc_dev, "can not if_alloc()\n");
367		error = ENOSPC;
368		goto bad;
369	}
370	ic = ifp->if_l2com;
371
372	/* set these up early for if_printf use */
373	if_initname(ifp, device_get_name(sc->sc_dev),
374		device_get_unit(sc->sc_dev));
375
376	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
377	if (ah == NULL) {
378		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
379			status);
380		error = ENXIO;
381		goto bad;
382	}
383	sc->sc_ah = ah;
384	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
385#ifdef	ATH_DEBUG
386	sc->sc_debug = ath_debug;
387#endif
388
389	/*
390	 * Check if the MAC has multi-rate retry support.
391	 * We do this by trying to setup a fake extended
392	 * descriptor.  MAC's that don't have support will
393	 * return false w/o doing anything.  MAC's that do
394	 * support it will return true w/o doing anything.
395	 */
396	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
397
398	/*
399	 * Check if the device has hardware counters for PHY
400	 * errors.  If so we need to enable the MIB interrupt
401	 * so we can act on stat triggers.
402	 */
403	if (ath_hal_hwphycounters(ah))
404		sc->sc_needmib = 1;
405
406	/*
407	 * Get the hardware key cache size.
408	 */
409	sc->sc_keymax = ath_hal_keycachesize(ah);
410	if (sc->sc_keymax > ATH_KEYMAX) {
411		if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
412			ATH_KEYMAX, sc->sc_keymax);
413		sc->sc_keymax = ATH_KEYMAX;
414	}
415	/*
416	 * Reset the key cache since some parts do not
417	 * reset the contents on initial power up.
418	 */
419	for (i = 0; i < sc->sc_keymax; i++)
420		ath_hal_keyreset(ah, i);
421
422	/*
423	 * Collect the default channel list.
424	 */
425	error = ath_getchannels(sc);
426	if (error != 0)
427		goto bad;
428
429	/*
430	 * Setup rate tables for all potential media types.
431	 */
432	ath_rate_setup(sc, IEEE80211_MODE_11A);
433	ath_rate_setup(sc, IEEE80211_MODE_11B);
434	ath_rate_setup(sc, IEEE80211_MODE_11G);
435	ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
436	ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
437	ath_rate_setup(sc, IEEE80211_MODE_STURBO_A);
438	ath_rate_setup(sc, IEEE80211_MODE_11NA);
439	ath_rate_setup(sc, IEEE80211_MODE_11NG);
440	ath_rate_setup(sc, IEEE80211_MODE_HALF);
441	ath_rate_setup(sc, IEEE80211_MODE_QUARTER);
442
443	/* NB: setup here so ath_rate_update is happy */
444	ath_setcurmode(sc, IEEE80211_MODE_11A);
445
446	/*
447	 * Allocate tx+rx descriptors and populate the lists.
448	 */
449	error = ath_desc_alloc(sc);
450	if (error != 0) {
451		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
452		goto bad;
453	}
454	callout_init_mtx(&sc->sc_cal_ch, &sc->sc_mtx, 0);
455	callout_init_mtx(&sc->sc_wd_ch, &sc->sc_mtx, 0);
456
457	ATH_TXBUF_LOCK_INIT(sc);
458
459	sc->sc_tq = taskqueue_create("ath_taskq", M_NOWAIT,
460		taskqueue_thread_enqueue, &sc->sc_tq);
461	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET,
462		"%s taskq", ifp->if_xname);
463
464	TASK_INIT(&sc->sc_rxtask, 0, ath_rx_proc, sc);
465	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
466	TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_proc, sc);
467
468	/*
469	 * Allocate hardware transmit queues: one queue for
470	 * beacon frames and one data queue for each QoS
471	 * priority.  Note that the hal handles resetting
472	 * these queues at the needed time.
473	 *
474	 * XXX PS-Poll
475	 */
476	sc->sc_bhalq = ath_beaconq_setup(ah);
477	if (sc->sc_bhalq == (u_int) -1) {
478		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
479		error = EIO;
480		goto bad2;
481	}
482	sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
483	if (sc->sc_cabq == NULL) {
484		if_printf(ifp, "unable to setup CAB xmit queue!\n");
485		error = EIO;
486		goto bad2;
487	}
488	/* NB: insure BK queue is the lowest priority h/w queue */
489	if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
490		if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
491			ieee80211_wme_acnames[WME_AC_BK]);
492		error = EIO;
493		goto bad2;
494	}
495	if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
496	    !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
497	    !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
498		/*
499		 * Not enough hardware tx queues to properly do WME;
500		 * just punt and assign them all to the same h/w queue.
501		 * We could do a better job of this if, for example,
502		 * we allocate queues when we switch from station to
503		 * AP mode.
504		 */
505		if (sc->sc_ac2q[WME_AC_VI] != NULL)
506			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
507		if (sc->sc_ac2q[WME_AC_BE] != NULL)
508			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
509		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
510		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
511		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
512	}
513
514	/*
515	 * Special case certain configurations.  Note the
516	 * CAB queue is handled by these specially so don't
517	 * include them when checking the txq setup mask.
518	 */
519	switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
520	case 0x01:
521		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
522		break;
523	case 0x0f:
524		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
525		break;
526	default:
527		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
528		break;
529	}
530
531	/*
532	 * Setup rate control.  Some rate control modules
533	 * call back to change the anntena state so expose
534	 * the necessary entry points.
535	 * XXX maybe belongs in struct ath_ratectrl?
536	 */
537	sc->sc_setdefantenna = ath_setdefantenna;
538	sc->sc_rc = ath_rate_attach(sc);
539	if (sc->sc_rc == NULL) {
540		error = EIO;
541		goto bad2;
542	}
543
544	sc->sc_blinking = 0;
545	sc->sc_ledstate = 1;
546	sc->sc_ledon = 0;			/* low true */
547	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
548	callout_init(&sc->sc_ledtimer, CALLOUT_MPSAFE);
549	/*
550	 * Auto-enable soft led processing for IBM cards and for
551	 * 5211 minipci cards.  Users can also manually enable/disable
552	 * support with a sysctl.
553	 */
554	sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
555	if (sc->sc_softled) {
556		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin,
557		    HAL_GPIO_MUX_MAC_NETWORK_LED);
558		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
559	}
560
561	ifp->if_softc = sc;
562	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
563	ifp->if_start = ath_start;
564	ifp->if_ioctl = ath_ioctl;
565	ifp->if_init = ath_init;
566	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
567	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
568	IFQ_SET_READY(&ifp->if_snd);
569
570	ic->ic_ifp = ifp;
571	/* XXX not right but it's not used anywhere important */
572	ic->ic_phytype = IEEE80211_T_OFDM;
573	ic->ic_opmode = IEEE80211_M_STA;
574	ic->ic_caps =
575		  IEEE80211_C_STA		/* station mode */
576		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
577		| IEEE80211_C_HOSTAP		/* hostap mode */
578		| IEEE80211_C_MONITOR		/* monitor mode */
579		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
580		| IEEE80211_C_WDS		/* 4-address traffic works */
581		| IEEE80211_C_MBSS		/* mesh point link mode */
582		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
583		| IEEE80211_C_SHSLOT		/* short slot time supported */
584		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
585		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
586		| IEEE80211_C_TXFRAG		/* handle tx frags */
587		;
588	/*
589	 * Query the hal to figure out h/w crypto support.
590	 */
591	if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
592		ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
593	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
594		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_OCB;
595	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
596		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_CCM;
597	if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
598		ic->ic_cryptocaps |= IEEE80211_CRYPTO_CKIP;
599	if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
600		ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIP;
601		/*
602		 * Check if h/w does the MIC and/or whether the
603		 * separate key cache entries are required to
604		 * handle both tx+rx MIC keys.
605		 */
606		if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
607			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
608		/*
609		 * If the h/w supports storing tx+rx MIC keys
610		 * in one cache slot automatically enable use.
611		 */
612		if (ath_hal_hastkipsplit(ah) ||
613		    !ath_hal_settkipsplit(ah, AH_FALSE))
614			sc->sc_splitmic = 1;
615		/*
616		 * If the h/w can do TKIP MIC together with WME then
617		 * we use it; otherwise we force the MIC to be done
618		 * in software by the net80211 layer.
619		 */
620		if (ath_hal_haswmetkipmic(ah))
621			sc->sc_wmetkipmic = 1;
622	}
623	sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
624	/*
625	 * Check for multicast key search support.
626	 */
627	if (ath_hal_hasmcastkeysearch(sc->sc_ah) &&
628	    !ath_hal_getmcastkeysearch(sc->sc_ah)) {
629		ath_hal_setmcastkeysearch(sc->sc_ah, 1);
630	}
631	sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
632	/*
633	 * Mark key cache slots associated with global keys
634	 * as in use.  If we knew TKIP was not to be used we
635	 * could leave the +32, +64, and +32+64 slots free.
636	 */
637	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
638		setbit(sc->sc_keymap, i);
639		setbit(sc->sc_keymap, i+64);
640		if (sc->sc_splitmic) {
641			setbit(sc->sc_keymap, i+32);
642			setbit(sc->sc_keymap, i+32+64);
643		}
644	}
645	/*
646	 * TPC support can be done either with a global cap or
647	 * per-packet support.  The latter is not available on
648	 * all parts.  We're a bit pedantic here as all parts
649	 * support a global cap.
650	 */
651	if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
652		ic->ic_caps |= IEEE80211_C_TXPMGT;
653
654	/*
655	 * Mark WME capability only if we have sufficient
656	 * hardware queues to do proper priority scheduling.
657	 */
658	if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
659		ic->ic_caps |= IEEE80211_C_WME;
660	/*
661	 * Check for misc other capabilities.
662	 */
663	if (ath_hal_hasbursting(ah))
664		ic->ic_caps |= IEEE80211_C_BURST;
665	sc->sc_hasbmask = ath_hal_hasbssidmask(ah);
666	sc->sc_hasbmatch = ath_hal_hasbssidmatch(ah);
667	sc->sc_hastsfadd = ath_hal_hastsfadjust(ah);
668	if (ath_hal_hasfastframes(ah))
669		ic->ic_caps |= IEEE80211_C_FF;
670	wmodes = ath_hal_getwirelessmodes(ah);
671	if (wmodes & (HAL_MODE_108G|HAL_MODE_TURBO))
672		ic->ic_caps |= IEEE80211_C_TURBOP;
673#ifdef IEEE80211_SUPPORT_TDMA
674	if (ath_hal_macversion(ah) > 0x78) {
675		ic->ic_caps |= IEEE80211_C_TDMA; /* capable of TDMA */
676		ic->ic_tdma_update = ath_tdma_update;
677	}
678#endif
679	/*
680	 * Indicate we need the 802.11 header padded to a
681	 * 32-bit boundary for 4-address and QoS frames.
682	 */
683	ic->ic_flags |= IEEE80211_F_DATAPAD;
684
685	/*
686	 * Query the hal about antenna support.
687	 */
688	sc->sc_defant = ath_hal_getdefantenna(ah);
689
690	/*
691	 * Not all chips have the VEOL support we want to
692	 * use with IBSS beacons; check here for it.
693	 */
694	sc->sc_hasveol = ath_hal_hasveol(ah);
695
696	/* get mac address from hardware */
697	ath_hal_getmac(ah, macaddr);
698	if (sc->sc_hasbmask)
699		ath_hal_getbssidmask(ah, sc->sc_hwbssidmask);
700
701	/* NB: used to size node table key mapping array */
702	ic->ic_max_keyix = sc->sc_keymax;
703	/* call MI attach routine. */
704	ieee80211_ifattach(ic, macaddr);
705	ic->ic_setregdomain = ath_setregdomain;
706	ic->ic_getradiocaps = ath_getradiocaps;
707	sc->sc_opmode = HAL_M_STA;
708
709	/* override default methods */
710	ic->ic_newassoc = ath_newassoc;
711	ic->ic_updateslot = ath_updateslot;
712	ic->ic_wme.wme_update = ath_wme_update;
713	ic->ic_vap_create = ath_vap_create;
714	ic->ic_vap_delete = ath_vap_delete;
715	ic->ic_raw_xmit = ath_raw_xmit;
716	ic->ic_update_mcast = ath_update_mcast;
717	ic->ic_update_promisc = ath_update_promisc;
718	ic->ic_node_alloc = ath_node_alloc;
719	sc->sc_node_free = ic->ic_node_free;
720	ic->ic_node_free = ath_node_free;
721	ic->ic_node_getsignal = ath_node_getsignal;
722	ic->ic_scan_start = ath_scan_start;
723	ic->ic_scan_end = ath_scan_end;
724	ic->ic_set_channel = ath_set_channel;
725
726	ieee80211_radiotap_attach(ic,
727	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
728		ATH_TX_RADIOTAP_PRESENT,
729	    &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
730		ATH_RX_RADIOTAP_PRESENT);
731
732	/*
733	 * Setup dynamic sysctl's now that country code and
734	 * regdomain are available from the hal.
735	 */
736	ath_sysctlattach(sc);
737	ath_sysctl_stats_attach(sc);
738
739	if (bootverbose)
740		ieee80211_announce(ic);
741	ath_announce(sc);
742	return 0;
743bad2:
744	ath_tx_cleanup(sc);
745	ath_desc_free(sc);
746bad:
747	if (ah)
748		ath_hal_detach(ah);
749	if (ifp != NULL)
750		if_free(ifp);
751	sc->sc_invalid = 1;
752	return error;
753}
754
755int
756ath_detach(struct ath_softc *sc)
757{
758	struct ifnet *ifp = sc->sc_ifp;
759
760	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
761		__func__, ifp->if_flags);
762
763	/*
764	 * NB: the order of these is important:
765	 * o stop the chip so no more interrupts will fire
766	 * o call the 802.11 layer before detaching the hal to
767	 *   insure callbacks into the driver to delete global
768	 *   key cache entries can be handled
769	 * o free the taskqueue which drains any pending tasks
770	 * o reclaim the tx queue data structures after calling
771	 *   the 802.11 layer as we'll get called back to reclaim
772	 *   node state and potentially want to use them
773	 * o to cleanup the tx queues the hal is called, so detach
774	 *   it last
775	 * Other than that, it's straightforward...
776	 */
777	ath_stop(ifp);
778	ieee80211_ifdetach(ifp->if_l2com);
779	taskqueue_free(sc->sc_tq);
780#ifdef ATH_TX99_DIAG
781	if (sc->sc_tx99 != NULL)
782		sc->sc_tx99->detach(sc->sc_tx99);
783#endif
784	ath_rate_detach(sc->sc_rc);
785	ath_desc_free(sc);
786	ath_tx_cleanup(sc);
787	ath_hal_detach(sc->sc_ah);	/* NB: sets chip in full sleep */
788	if_free(ifp);
789
790	return 0;
791}
792
793/*
794 * MAC address handling for multiple BSS on the same radio.
795 * The first vap uses the MAC address from the EEPROM.  For
796 * subsequent vap's we set the U/L bit (bit 1) in the MAC
797 * address and use the next six bits as an index.
798 */
799static void
800assign_address(struct ath_softc *sc, uint8_t mac[IEEE80211_ADDR_LEN], int clone)
801{
802	int i;
803
804	if (clone && sc->sc_hasbmask) {
805		/* NB: we only do this if h/w supports multiple bssid */
806		for (i = 0; i < 8; i++)
807			if ((sc->sc_bssidmask & (1<<i)) == 0)
808				break;
809		if (i != 0)
810			mac[0] |= (i << 2)|0x2;
811	} else
812		i = 0;
813	sc->sc_bssidmask |= 1<<i;
814	sc->sc_hwbssidmask[0] &= ~mac[0];
815	if (i == 0)
816		sc->sc_nbssid0++;
817}
818
819static void
820reclaim_address(struct ath_softc *sc, const uint8_t mac[IEEE80211_ADDR_LEN])
821{
822	int i = mac[0] >> 2;
823	uint8_t mask;
824
825	if (i != 0 || --sc->sc_nbssid0 == 0) {
826		sc->sc_bssidmask &= ~(1<<i);
827		/* recalculate bssid mask from remaining addresses */
828		mask = 0xff;
829		for (i = 1; i < 8; i++)
830			if (sc->sc_bssidmask & (1<<i))
831				mask &= ~((i<<2)|0x2);
832		sc->sc_hwbssidmask[0] |= mask;
833	}
834}
835
836/*
837 * Assign a beacon xmit slot.  We try to space out
838 * assignments so when beacons are staggered the
839 * traffic coming out of the cab q has maximal time
840 * to go out before the next beacon is scheduled.
841 */
842static int
843assign_bslot(struct ath_softc *sc)
844{
845	u_int slot, free;
846
847	free = 0;
848	for (slot = 0; slot < ATH_BCBUF; slot++)
849		if (sc->sc_bslot[slot] == NULL) {
850			if (sc->sc_bslot[(slot+1)%ATH_BCBUF] == NULL &&
851			    sc->sc_bslot[(slot-1)%ATH_BCBUF] == NULL)
852				return slot;
853			free = slot;
854			/* NB: keep looking for a double slot */
855		}
856	return free;
857}
858
859static struct ieee80211vap *
860ath_vap_create(struct ieee80211com *ic,
861	const char name[IFNAMSIZ], int unit, int opmode, int flags,
862	const uint8_t bssid[IEEE80211_ADDR_LEN],
863	const uint8_t mac0[IEEE80211_ADDR_LEN])
864{
865	struct ath_softc *sc = ic->ic_ifp->if_softc;
866	struct ath_vap *avp;
867	struct ieee80211vap *vap;
868	uint8_t mac[IEEE80211_ADDR_LEN];
869	int ic_opmode, needbeacon, error;
870
871	avp = (struct ath_vap *) malloc(sizeof(struct ath_vap),
872	    M_80211_VAP, M_WAITOK | M_ZERO);
873	needbeacon = 0;
874	IEEE80211_ADDR_COPY(mac, mac0);
875
876	ATH_LOCK(sc);
877	ic_opmode = opmode;		/* default to opmode of new vap */
878	switch (opmode) {
879	case IEEE80211_M_STA:
880		if (sc->sc_nstavaps != 0) {	/* XXX only 1 for now */
881			device_printf(sc->sc_dev, "only 1 sta vap supported\n");
882			goto bad;
883		}
884		if (sc->sc_nvaps) {
885			/*
886			 * With multiple vaps we must fall back
887			 * to s/w beacon miss handling.
888			 */
889			flags |= IEEE80211_CLONE_NOBEACONS;
890		}
891		if (flags & IEEE80211_CLONE_NOBEACONS) {
892			/*
893			 * Station mode w/o beacons are implemented w/ AP mode.
894			 */
895			ic_opmode = IEEE80211_M_HOSTAP;
896		}
897		break;
898	case IEEE80211_M_IBSS:
899		if (sc->sc_nvaps != 0) {	/* XXX only 1 for now */
900			device_printf(sc->sc_dev,
901			    "only 1 ibss vap supported\n");
902			goto bad;
903		}
904		needbeacon = 1;
905		break;
906	case IEEE80211_M_AHDEMO:
907#ifdef IEEE80211_SUPPORT_TDMA
908		if (flags & IEEE80211_CLONE_TDMA) {
909			if (sc->sc_nvaps != 0) {
910				device_printf(sc->sc_dev,
911				    "only 1 tdma vap supported\n");
912				goto bad;
913			}
914			needbeacon = 1;
915			flags |= IEEE80211_CLONE_NOBEACONS;
916		}
917		/* fall thru... */
918#endif
919	case IEEE80211_M_MONITOR:
920		if (sc->sc_nvaps != 0 && ic->ic_opmode != opmode) {
921			/*
922			 * Adopt existing mode.  Adding a monitor or ahdemo
923			 * vap to an existing configuration is of dubious
924			 * value but should be ok.
925			 */
926			/* XXX not right for monitor mode */
927			ic_opmode = ic->ic_opmode;
928		}
929		break;
930	case IEEE80211_M_HOSTAP:
931	case IEEE80211_M_MBSS:
932		needbeacon = 1;
933		break;
934	case IEEE80211_M_WDS:
935		if (sc->sc_nvaps != 0 && ic->ic_opmode == IEEE80211_M_STA) {
936			device_printf(sc->sc_dev,
937			    "wds not supported in sta mode\n");
938			goto bad;
939		}
940		/*
941		 * Silently remove any request for a unique
942		 * bssid; WDS vap's always share the local
943		 * mac address.
944		 */
945		flags &= ~IEEE80211_CLONE_BSSID;
946		if (sc->sc_nvaps == 0)
947			ic_opmode = IEEE80211_M_HOSTAP;
948		else
949			ic_opmode = ic->ic_opmode;
950		break;
951	default:
952		device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
953		goto bad;
954	}
955	/*
956	 * Check that a beacon buffer is available; the code below assumes it.
957	 */
958	if (needbeacon & STAILQ_EMPTY(&sc->sc_bbuf)) {
959		device_printf(sc->sc_dev, "no beacon buffer available\n");
960		goto bad;
961	}
962
963	/* STA, AHDEMO? */
964	if (opmode == IEEE80211_M_HOSTAP || opmode == IEEE80211_M_MBSS) {
965		assign_address(sc, mac, flags & IEEE80211_CLONE_BSSID);
966		ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
967	}
968
969	vap = &avp->av_vap;
970	/* XXX can't hold mutex across if_alloc */
971	ATH_UNLOCK(sc);
972	error = ieee80211_vap_setup(ic, vap, name, unit, opmode, flags,
973	    bssid, mac);
974	ATH_LOCK(sc);
975	if (error != 0) {
976		device_printf(sc->sc_dev, "%s: error %d creating vap\n",
977		    __func__, error);
978		goto bad2;
979	}
980
981	/* h/w crypto support */
982	vap->iv_key_alloc = ath_key_alloc;
983	vap->iv_key_delete = ath_key_delete;
984	vap->iv_key_set = ath_key_set;
985	vap->iv_key_update_begin = ath_key_update_begin;
986	vap->iv_key_update_end = ath_key_update_end;
987
988	/* override various methods */
989	avp->av_recv_mgmt = vap->iv_recv_mgmt;
990	vap->iv_recv_mgmt = ath_recv_mgmt;
991	vap->iv_reset = ath_reset_vap;
992	vap->iv_update_beacon = ath_beacon_update;
993	avp->av_newstate = vap->iv_newstate;
994	vap->iv_newstate = ath_newstate;
995	avp->av_bmiss = vap->iv_bmiss;
996	vap->iv_bmiss = ath_bmiss_vap;
997
998	avp->av_bslot = -1;
999	if (needbeacon) {
1000		/*
1001		 * Allocate beacon state and setup the q for buffered
1002		 * multicast frames.  We know a beacon buffer is
1003		 * available because we checked above.
1004		 */
1005		avp->av_bcbuf = STAILQ_FIRST(&sc->sc_bbuf);
1006		STAILQ_REMOVE_HEAD(&sc->sc_bbuf, bf_list);
1007		if (opmode != IEEE80211_M_IBSS || !sc->sc_hasveol) {
1008			/*
1009			 * Assign the vap to a beacon xmit slot.  As above
1010			 * this cannot fail to find a free one.
1011			 */
1012			avp->av_bslot = assign_bslot(sc);
1013			KASSERT(sc->sc_bslot[avp->av_bslot] == NULL,
1014			    ("beacon slot %u not empty", avp->av_bslot));
1015			sc->sc_bslot[avp->av_bslot] = vap;
1016			sc->sc_nbcnvaps++;
1017		}
1018		if (sc->sc_hastsfadd && sc->sc_nbcnvaps > 0) {
1019			/*
1020			 * Multple vaps are to transmit beacons and we
1021			 * have h/w support for TSF adjusting; enable
1022			 * use of staggered beacons.
1023			 */
1024			sc->sc_stagbeacons = 1;
1025		}
1026		ath_txq_init(sc, &avp->av_mcastq, ATH_TXQ_SWQ);
1027	}
1028
1029	ic->ic_opmode = ic_opmode;
1030	if (opmode != IEEE80211_M_WDS) {
1031		sc->sc_nvaps++;
1032		if (opmode == IEEE80211_M_STA)
1033			sc->sc_nstavaps++;
1034		if (opmode == IEEE80211_M_MBSS)
1035			sc->sc_nmeshvaps++;
1036	}
1037	switch (ic_opmode) {
1038	case IEEE80211_M_IBSS:
1039		sc->sc_opmode = HAL_M_IBSS;
1040		break;
1041	case IEEE80211_M_STA:
1042		sc->sc_opmode = HAL_M_STA;
1043		break;
1044	case IEEE80211_M_AHDEMO:
1045#ifdef IEEE80211_SUPPORT_TDMA
1046		if (vap->iv_caps & IEEE80211_C_TDMA) {
1047			sc->sc_tdma = 1;
1048			/* NB: disable tsf adjust */
1049			sc->sc_stagbeacons = 0;
1050		}
1051		/*
1052		 * NB: adhoc demo mode is a pseudo mode; to the hal it's
1053		 * just ap mode.
1054		 */
1055		/* fall thru... */
1056#endif
1057	case IEEE80211_M_HOSTAP:
1058	case IEEE80211_M_MBSS:
1059		sc->sc_opmode = HAL_M_HOSTAP;
1060		break;
1061	case IEEE80211_M_MONITOR:
1062		sc->sc_opmode = HAL_M_MONITOR;
1063		break;
1064	default:
1065		/* XXX should not happen */
1066		break;
1067	}
1068	if (sc->sc_hastsfadd) {
1069		/*
1070		 * Configure whether or not TSF adjust should be done.
1071		 */
1072		ath_hal_settsfadjust(sc->sc_ah, sc->sc_stagbeacons);
1073	}
1074	if (flags & IEEE80211_CLONE_NOBEACONS) {
1075		/*
1076		 * Enable s/w beacon miss handling.
1077		 */
1078		sc->sc_swbmiss = 1;
1079	}
1080	ATH_UNLOCK(sc);
1081
1082	/* complete setup */
1083	ieee80211_vap_attach(vap, ath_media_change, ieee80211_media_status);
1084	return vap;
1085bad2:
1086	reclaim_address(sc, mac);
1087	ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
1088bad:
1089	free(avp, M_80211_VAP);
1090	ATH_UNLOCK(sc);
1091	return NULL;
1092}
1093
1094static void
1095ath_vap_delete(struct ieee80211vap *vap)
1096{
1097	struct ieee80211com *ic = vap->iv_ic;
1098	struct ifnet *ifp = ic->ic_ifp;
1099	struct ath_softc *sc = ifp->if_softc;
1100	struct ath_hal *ah = sc->sc_ah;
1101	struct ath_vap *avp = ATH_VAP(vap);
1102
1103	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1104		/*
1105		 * Quiesce the hardware while we remove the vap.  In
1106		 * particular we need to reclaim all references to
1107		 * the vap state by any frames pending on the tx queues.
1108		 */
1109		ath_hal_intrset(ah, 0);		/* disable interrupts */
1110		ath_draintxq(sc);		/* stop xmit side */
1111		ath_stoprecv(sc);		/* stop recv side */
1112	}
1113
1114	ieee80211_vap_detach(vap);
1115	ATH_LOCK(sc);
1116	/*
1117	 * Reclaim beacon state.  Note this must be done before
1118	 * the vap instance is reclaimed as we may have a reference
1119	 * to it in the buffer for the beacon frame.
1120	 */
1121	if (avp->av_bcbuf != NULL) {
1122		if (avp->av_bslot != -1) {
1123			sc->sc_bslot[avp->av_bslot] = NULL;
1124			sc->sc_nbcnvaps--;
1125		}
1126		ath_beacon_return(sc, avp->av_bcbuf);
1127		avp->av_bcbuf = NULL;
1128		if (sc->sc_nbcnvaps == 0) {
1129			sc->sc_stagbeacons = 0;
1130			if (sc->sc_hastsfadd)
1131				ath_hal_settsfadjust(sc->sc_ah, 0);
1132		}
1133		/*
1134		 * Reclaim any pending mcast frames for the vap.
1135		 */
1136		ath_tx_draintxq(sc, &avp->av_mcastq);
1137		ATH_TXQ_LOCK_DESTROY(&avp->av_mcastq);
1138	}
1139	/*
1140	 * Update bookkeeping.
1141	 */
1142	if (vap->iv_opmode == IEEE80211_M_STA) {
1143		sc->sc_nstavaps--;
1144		if (sc->sc_nstavaps == 0 && sc->sc_swbmiss)
1145			sc->sc_swbmiss = 0;
1146	} else if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1147	    vap->iv_opmode == IEEE80211_M_MBSS) {
1148		reclaim_address(sc, vap->iv_myaddr);
1149		ath_hal_setbssidmask(ah, sc->sc_hwbssidmask);
1150		if (vap->iv_opmode == IEEE80211_M_MBSS)
1151			sc->sc_nmeshvaps--;
1152	}
1153	if (vap->iv_opmode != IEEE80211_M_WDS)
1154		sc->sc_nvaps--;
1155#ifdef IEEE80211_SUPPORT_TDMA
1156	/* TDMA operation ceases when the last vap is destroyed */
1157	if (sc->sc_tdma && sc->sc_nvaps == 0) {
1158		sc->sc_tdma = 0;
1159		sc->sc_swbmiss = 0;
1160	}
1161#endif
1162	ATH_UNLOCK(sc);
1163	free(avp, M_80211_VAP);
1164
1165	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1166		/*
1167		 * Restart rx+tx machines if still running (RUNNING will
1168		 * be reset if we just destroyed the last vap).
1169		 */
1170		if (ath_startrecv(sc) != 0)
1171			if_printf(ifp, "%s: unable to restart recv logic\n",
1172			    __func__);
1173		if (sc->sc_beacons) {		/* restart beacons */
1174#ifdef IEEE80211_SUPPORT_TDMA
1175			if (sc->sc_tdma)
1176				ath_tdma_config(sc, NULL);
1177			else
1178#endif
1179				ath_beacon_config(sc, NULL);
1180		}
1181		ath_hal_intrset(ah, sc->sc_imask);
1182	}
1183}
1184
1185void
1186ath_suspend(struct ath_softc *sc)
1187{
1188	struct ifnet *ifp = sc->sc_ifp;
1189	struct ieee80211com *ic = ifp->if_l2com;
1190
1191	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1192		__func__, ifp->if_flags);
1193
1194	sc->sc_resume_up = (ifp->if_flags & IFF_UP) != 0;
1195	if (ic->ic_opmode == IEEE80211_M_STA)
1196		ath_stop(ifp);
1197	else
1198		ieee80211_suspend_all(ic);
1199	/*
1200	 * NB: don't worry about putting the chip in low power
1201	 * mode; pci will power off our socket on suspend and
1202	 * CardBus detaches the device.
1203	 */
1204}
1205
1206/*
1207 * Reset the key cache since some parts do not reset the
1208 * contents on resume.  First we clear all entries, then
1209 * re-load keys that the 802.11 layer assumes are setup
1210 * in h/w.
1211 */
1212static void
1213ath_reset_keycache(struct ath_softc *sc)
1214{
1215	struct ifnet *ifp = sc->sc_ifp;
1216	struct ieee80211com *ic = ifp->if_l2com;
1217	struct ath_hal *ah = sc->sc_ah;
1218	int i;
1219
1220	for (i = 0; i < sc->sc_keymax; i++)
1221		ath_hal_keyreset(ah, i);
1222	ieee80211_crypto_reload_keys(ic);
1223}
1224
1225void
1226ath_resume(struct ath_softc *sc)
1227{
1228	struct ifnet *ifp = sc->sc_ifp;
1229	struct ieee80211com *ic = ifp->if_l2com;
1230	struct ath_hal *ah = sc->sc_ah;
1231	HAL_STATUS status;
1232
1233	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1234		__func__, ifp->if_flags);
1235
1236	/*
1237	 * Must reset the chip before we reload the
1238	 * keycache as we were powered down on suspend.
1239	 */
1240	ath_hal_reset(ah, sc->sc_opmode,
1241	    sc->sc_curchan != NULL ? sc->sc_curchan : ic->ic_curchan,
1242	    AH_FALSE, &status);
1243	ath_reset_keycache(sc);
1244	if (sc->sc_resume_up) {
1245		if (ic->ic_opmode == IEEE80211_M_STA) {
1246			ath_init(sc);
1247			/*
1248			 * Program the beacon registers using the last rx'd
1249			 * beacon frame and enable sync on the next beacon
1250			 * we see.  This should handle the case where we
1251			 * wakeup and find the same AP and also the case where
1252			 * we wakeup and need to roam.  For the latter we
1253			 * should get bmiss events that trigger a roam.
1254			 */
1255			ath_beacon_config(sc, NULL);
1256			sc->sc_syncbeacon = 1;
1257		} else
1258			ieee80211_resume_all(ic);
1259	}
1260	if (sc->sc_softled) {
1261		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin,
1262		    HAL_GPIO_MUX_MAC_NETWORK_LED);
1263		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
1264	}
1265}
1266
1267void
1268ath_shutdown(struct ath_softc *sc)
1269{
1270	struct ifnet *ifp = sc->sc_ifp;
1271
1272	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1273		__func__, ifp->if_flags);
1274
1275	ath_stop(ifp);
1276	/* NB: no point powering down chip as we're about to reboot */
1277}
1278
1279/*
1280 * Interrupt handler.  Most of the actual processing is deferred.
1281 */
1282void
1283ath_intr(void *arg)
1284{
1285	struct ath_softc *sc = arg;
1286	struct ifnet *ifp = sc->sc_ifp;
1287	struct ath_hal *ah = sc->sc_ah;
1288	HAL_INT status;
1289
1290	if (sc->sc_invalid) {
1291		/*
1292		 * The hardware is not ready/present, don't touch anything.
1293		 * Note this can happen early on if the IRQ is shared.
1294		 */
1295		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
1296		return;
1297	}
1298	if (!ath_hal_intrpend(ah))		/* shared irq, not for us */
1299		return;
1300	if ((ifp->if_flags & IFF_UP) == 0 ||
1301	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1302		HAL_INT status;
1303
1304		DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1305			__func__, ifp->if_flags);
1306		ath_hal_getisr(ah, &status);	/* clear ISR */
1307		ath_hal_intrset(ah, 0);		/* disable further intr's */
1308		return;
1309	}
1310	/*
1311	 * Figure out the reason(s) for the interrupt.  Note
1312	 * that the hal returns a pseudo-ISR that may include
1313	 * bits we haven't explicitly enabled so we mask the
1314	 * value to insure we only process bits we requested.
1315	 */
1316	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
1317	DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
1318	status &= sc->sc_imask;			/* discard unasked for bits */
1319	if (status & HAL_INT_FATAL) {
1320		sc->sc_stats.ast_hardware++;
1321		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
1322		ath_fatal_proc(sc, 0);
1323	} else {
1324		if (status & HAL_INT_SWBA) {
1325			/*
1326			 * Software beacon alert--time to send a beacon.
1327			 * Handle beacon transmission directly; deferring
1328			 * this is too slow to meet timing constraints
1329			 * under load.
1330			 */
1331#ifdef IEEE80211_SUPPORT_TDMA
1332			if (sc->sc_tdma) {
1333				if (sc->sc_tdmaswba == 0) {
1334					struct ieee80211com *ic = ifp->if_l2com;
1335					struct ieee80211vap *vap =
1336					    TAILQ_FIRST(&ic->ic_vaps);
1337					ath_tdma_beacon_send(sc, vap);
1338					sc->sc_tdmaswba =
1339					    vap->iv_tdma->tdma_bintval;
1340				} else
1341					sc->sc_tdmaswba--;
1342			} else
1343#endif
1344			{
1345				ath_beacon_proc(sc, 0);
1346#ifdef IEEE80211_SUPPORT_SUPERG
1347				/*
1348				 * Schedule the rx taskq in case there's no
1349				 * traffic so any frames held on the staging
1350				 * queue are aged and potentially flushed.
1351				 */
1352				taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1353#endif
1354			}
1355		}
1356		if (status & HAL_INT_RXEOL) {
1357			/*
1358			 * NB: the hardware should re-read the link when
1359			 *     RXE bit is written, but it doesn't work at
1360			 *     least on older hardware revs.
1361			 */
1362			sc->sc_stats.ast_rxeol++;
1363			sc->sc_rxlink = NULL;
1364		}
1365		if (status & HAL_INT_TXURN) {
1366			sc->sc_stats.ast_txurn++;
1367			/* bump tx trigger level */
1368			ath_hal_updatetxtriglevel(ah, AH_TRUE);
1369		}
1370		if (status & HAL_INT_RX)
1371			taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1372		if (status & HAL_INT_TX)
1373			taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
1374		if (status & HAL_INT_BMISS) {
1375			sc->sc_stats.ast_bmiss++;
1376			taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
1377		}
1378		if (status & HAL_INT_MIB) {
1379			sc->sc_stats.ast_mib++;
1380			/*
1381			 * Disable interrupts until we service the MIB
1382			 * interrupt; otherwise it will continue to fire.
1383			 */
1384			ath_hal_intrset(ah, 0);
1385			/*
1386			 * Let the hal handle the event.  We assume it will
1387			 * clear whatever condition caused the interrupt.
1388			 */
1389			ath_hal_mibevent(ah, &sc->sc_halstats);
1390			ath_hal_intrset(ah, sc->sc_imask);
1391		}
1392		if (status & HAL_INT_RXORN) {
1393			/* NB: hal marks HAL_INT_FATAL when RXORN is fatal */
1394			sc->sc_stats.ast_rxorn++;
1395		}
1396	}
1397}
1398
1399static void
1400ath_fatal_proc(void *arg, int pending)
1401{
1402	struct ath_softc *sc = arg;
1403	struct ifnet *ifp = sc->sc_ifp;
1404	u_int32_t *state;
1405	u_int32_t len;
1406	void *sp;
1407
1408	if_printf(ifp, "hardware error; resetting\n");
1409	/*
1410	 * Fatal errors are unrecoverable.  Typically these
1411	 * are caused by DMA errors.  Collect h/w state from
1412	 * the hal so we can diagnose what's going on.
1413	 */
1414	if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
1415		KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
1416		state = sp;
1417		if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
1418		    state[0], state[1] , state[2], state[3],
1419		    state[4], state[5]);
1420	}
1421	ath_reset(ifp);
1422}
1423
1424static void
1425ath_bmiss_vap(struct ieee80211vap *vap)
1426{
1427	/*
1428	 * Workaround phantom bmiss interrupts by sanity-checking
1429	 * the time of our last rx'd frame.  If it is within the
1430	 * beacon miss interval then ignore the interrupt.  If it's
1431	 * truly a bmiss we'll get another interrupt soon and that'll
1432	 * be dispatched up for processing.  Note this applies only
1433	 * for h/w beacon miss events.
1434	 */
1435	if ((vap->iv_flags_ext & IEEE80211_FEXT_SWBMISS) == 0) {
1436		struct ifnet *ifp = vap->iv_ic->ic_ifp;
1437		struct ath_softc *sc = ifp->if_softc;
1438		u_int64_t lastrx = sc->sc_lastrx;
1439		u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
1440		u_int bmisstimeout =
1441			vap->iv_bmissthreshold * vap->iv_bss->ni_intval * 1024;
1442
1443		DPRINTF(sc, ATH_DEBUG_BEACON,
1444		    "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
1445		    __func__, (unsigned long long) tsf,
1446		    (unsigned long long)(tsf - lastrx),
1447		    (unsigned long long) lastrx, bmisstimeout);
1448
1449		if (tsf - lastrx <= bmisstimeout) {
1450			sc->sc_stats.ast_bmiss_phantom++;
1451			return;
1452		}
1453	}
1454	ATH_VAP(vap)->av_bmiss(vap);
1455}
1456
1457static int
1458ath_hal_gethangstate(struct ath_hal *ah, uint32_t mask, uint32_t *hangs)
1459{
1460	uint32_t rsize;
1461	void *sp;
1462
1463	if (!ath_hal_getdiagstate(ah, 32, &mask, sizeof(mask), &sp, &rsize))
1464		return 0;
1465	KASSERT(rsize == sizeof(uint32_t), ("resultsize %u", rsize));
1466	*hangs = *(uint32_t *)sp;
1467	return 1;
1468}
1469
1470static void
1471ath_bmiss_proc(void *arg, int pending)
1472{
1473	struct ath_softc *sc = arg;
1474	struct ifnet *ifp = sc->sc_ifp;
1475	uint32_t hangs;
1476
1477	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
1478
1479	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0) {
1480		if_printf(ifp, "bb hang detected (0x%x), resetting\n", hangs);
1481		ath_reset(ifp);
1482	} else
1483		ieee80211_beacon_miss(ifp->if_l2com);
1484}
1485
1486/*
1487 * Handle TKIP MIC setup to deal hardware that doesn't do MIC
1488 * calcs together with WME.  If necessary disable the crypto
1489 * hardware and mark the 802.11 state so keys will be setup
1490 * with the MIC work done in software.
1491 */
1492static void
1493ath_settkipmic(struct ath_softc *sc)
1494{
1495	struct ifnet *ifp = sc->sc_ifp;
1496	struct ieee80211com *ic = ifp->if_l2com;
1497
1498	if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
1499		if (ic->ic_flags & IEEE80211_F_WME) {
1500			ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
1501			ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
1502		} else {
1503			ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
1504			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
1505		}
1506	}
1507}
1508
1509static void
1510ath_init(void *arg)
1511{
1512	struct ath_softc *sc = (struct ath_softc *) arg;
1513	struct ifnet *ifp = sc->sc_ifp;
1514	struct ieee80211com *ic = ifp->if_l2com;
1515	struct ath_hal *ah = sc->sc_ah;
1516	HAL_STATUS status;
1517
1518	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1519		__func__, ifp->if_flags);
1520
1521	ATH_LOCK(sc);
1522	/*
1523	 * Stop anything previously setup.  This is safe
1524	 * whether this is the first time through or not.
1525	 */
1526	ath_stop_locked(ifp);
1527
1528	/*
1529	 * The basic interface to setting the hardware in a good
1530	 * state is ``reset''.  On return the hardware is known to
1531	 * be powered up and with interrupts disabled.  This must
1532	 * be followed by initialization of the appropriate bits
1533	 * and then setup of the interrupt mask.
1534	 */
1535	ath_settkipmic(sc);
1536	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_FALSE, &status)) {
1537		if_printf(ifp, "unable to reset hardware; hal status %u\n",
1538			status);
1539		ATH_UNLOCK(sc);
1540		return;
1541	}
1542	ath_chan_change(sc, ic->ic_curchan);
1543
1544	/*
1545	 * Likewise this is set during reset so update
1546	 * state cached in the driver.
1547	 */
1548	sc->sc_diversity = ath_hal_getdiversity(ah);
1549	sc->sc_lastlongcal = 0;
1550	sc->sc_resetcal = 1;
1551	sc->sc_lastcalreset = 0;
1552
1553	/*
1554	 * Setup the hardware after reset: the key cache
1555	 * is filled as needed and the receive engine is
1556	 * set going.  Frame transmit is handled entirely
1557	 * in the frame output path; there's nothing to do
1558	 * here except setup the interrupt mask.
1559	 */
1560	if (ath_startrecv(sc) != 0) {
1561		if_printf(ifp, "unable to start recv logic\n");
1562		ATH_UNLOCK(sc);
1563		return;
1564	}
1565
1566	/*
1567	 * Enable interrupts.
1568	 */
1569	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
1570		  | HAL_INT_RXEOL | HAL_INT_RXORN
1571		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
1572	/*
1573	 * Enable MIB interrupts when there are hardware phy counters.
1574	 * Note we only do this (at the moment) for station mode.
1575	 */
1576	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
1577		sc->sc_imask |= HAL_INT_MIB;
1578
1579	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1580	callout_reset(&sc->sc_wd_ch, hz, ath_watchdog, sc);
1581	ath_hal_intrset(ah, sc->sc_imask);
1582
1583	ATH_UNLOCK(sc);
1584
1585#ifdef ATH_TX99_DIAG
1586	if (sc->sc_tx99 != NULL)
1587		sc->sc_tx99->start(sc->sc_tx99);
1588	else
1589#endif
1590	ieee80211_start_all(ic);		/* start all vap's */
1591}
1592
1593static void
1594ath_stop_locked(struct ifnet *ifp)
1595{
1596	struct ath_softc *sc = ifp->if_softc;
1597	struct ath_hal *ah = sc->sc_ah;
1598
1599	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1600		__func__, sc->sc_invalid, ifp->if_flags);
1601
1602	ATH_LOCK_ASSERT(sc);
1603	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1604		/*
1605		 * Shutdown the hardware and driver:
1606		 *    reset 802.11 state machine
1607		 *    turn off timers
1608		 *    disable interrupts
1609		 *    turn off the radio
1610		 *    clear transmit machinery
1611		 *    clear receive machinery
1612		 *    drain and release tx queues
1613		 *    reclaim beacon resources
1614		 *    power down hardware
1615		 *
1616		 * Note that some of this work is not possible if the
1617		 * hardware is gone (invalid).
1618		 */
1619#ifdef ATH_TX99_DIAG
1620		if (sc->sc_tx99 != NULL)
1621			sc->sc_tx99->stop(sc->sc_tx99);
1622#endif
1623		callout_stop(&sc->sc_wd_ch);
1624		sc->sc_wd_timer = 0;
1625		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1626		if (!sc->sc_invalid) {
1627			if (sc->sc_softled) {
1628				callout_stop(&sc->sc_ledtimer);
1629				ath_hal_gpioset(ah, sc->sc_ledpin,
1630					!sc->sc_ledon);
1631				sc->sc_blinking = 0;
1632			}
1633			ath_hal_intrset(ah, 0);
1634		}
1635		ath_draintxq(sc);
1636		if (!sc->sc_invalid) {
1637			ath_stoprecv(sc);
1638			ath_hal_phydisable(ah);
1639		} else
1640			sc->sc_rxlink = NULL;
1641		ath_beacon_free(sc);	/* XXX not needed */
1642	}
1643}
1644
1645static void
1646ath_stop(struct ifnet *ifp)
1647{
1648	struct ath_softc *sc = ifp->if_softc;
1649
1650	ATH_LOCK(sc);
1651	ath_stop_locked(ifp);
1652	ATH_UNLOCK(sc);
1653}
1654
1655/*
1656 * Reset the hardware w/o losing operational state.  This is
1657 * basically a more efficient way of doing ath_stop, ath_init,
1658 * followed by state transitions to the current 802.11
1659 * operational state.  Used to recover from various errors and
1660 * to reset or reload hardware state.
1661 */
1662static int
1663ath_reset(struct ifnet *ifp)
1664{
1665	struct ath_softc *sc = ifp->if_softc;
1666	struct ieee80211com *ic = ifp->if_l2com;
1667	struct ath_hal *ah = sc->sc_ah;
1668	HAL_STATUS status;
1669
1670	ath_hal_intrset(ah, 0);		/* disable interrupts */
1671	ath_draintxq(sc);		/* stop xmit side */
1672	ath_stoprecv(sc);		/* stop recv side */
1673	ath_settkipmic(sc);		/* configure TKIP MIC handling */
1674	/* NB: indicate channel change so we do a full reset */
1675	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_TRUE, &status))
1676		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
1677			__func__, status);
1678	sc->sc_diversity = ath_hal_getdiversity(ah);
1679	if (ath_startrecv(sc) != 0)	/* restart recv */
1680		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
1681	/*
1682	 * We may be doing a reset in response to an ioctl
1683	 * that changes the channel so update any state that
1684	 * might change as a result.
1685	 */
1686	ath_chan_change(sc, ic->ic_curchan);
1687	if (sc->sc_beacons) {		/* restart beacons */
1688#ifdef IEEE80211_SUPPORT_TDMA
1689		if (sc->sc_tdma)
1690			ath_tdma_config(sc, NULL);
1691		else
1692#endif
1693			ath_beacon_config(sc, NULL);
1694	}
1695	ath_hal_intrset(ah, sc->sc_imask);
1696
1697	ath_start(ifp);			/* restart xmit */
1698	return 0;
1699}
1700
1701static int
1702ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
1703{
1704	struct ieee80211com *ic = vap->iv_ic;
1705	struct ifnet *ifp = ic->ic_ifp;
1706	struct ath_softc *sc = ifp->if_softc;
1707	struct ath_hal *ah = sc->sc_ah;
1708
1709	switch (cmd) {
1710	case IEEE80211_IOC_TXPOWER:
1711		/*
1712		 * If per-packet TPC is enabled, then we have nothing
1713		 * to do; otherwise we need to force the global limit.
1714		 * All this can happen directly; no need to reset.
1715		 */
1716		if (!ath_hal_gettpc(ah))
1717			ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
1718		return 0;
1719	}
1720	return ath_reset(ifp);
1721}
1722
1723static struct ath_buf *
1724_ath_getbuf_locked(struct ath_softc *sc)
1725{
1726	struct ath_buf *bf;
1727
1728	ATH_TXBUF_LOCK_ASSERT(sc);
1729
1730	bf = STAILQ_FIRST(&sc->sc_txbuf);
1731	if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0)
1732		STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
1733	else
1734		bf = NULL;
1735	if (bf == NULL) {
1736		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
1737		    STAILQ_FIRST(&sc->sc_txbuf) == NULL ?
1738			"out of xmit buffers" : "xmit buffer busy");
1739	}
1740	return bf;
1741}
1742
1743static struct ath_buf *
1744ath_getbuf(struct ath_softc *sc)
1745{
1746	struct ath_buf *bf;
1747
1748	ATH_TXBUF_LOCK(sc);
1749	bf = _ath_getbuf_locked(sc);
1750	if (bf == NULL) {
1751		struct ifnet *ifp = sc->sc_ifp;
1752
1753		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
1754		sc->sc_stats.ast_tx_qstop++;
1755		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1756	}
1757	ATH_TXBUF_UNLOCK(sc);
1758	return bf;
1759}
1760
1761/*
1762 * Cleanup driver resources when we run out of buffers
1763 * while processing fragments; return the tx buffers
1764 * allocated and drop node references.
1765 */
1766static void
1767ath_txfrag_cleanup(struct ath_softc *sc,
1768	ath_bufhead *frags, struct ieee80211_node *ni)
1769{
1770	struct ath_buf *bf, *next;
1771
1772	ATH_TXBUF_LOCK_ASSERT(sc);
1773
1774	STAILQ_FOREACH_SAFE(bf, frags, bf_list, next) {
1775		/* NB: bf assumed clean */
1776		STAILQ_REMOVE_HEAD(frags, bf_list);
1777		STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1778		ieee80211_node_decref(ni);
1779	}
1780}
1781
1782/*
1783 * Setup xmit of a fragmented frame.  Allocate a buffer
1784 * for each frag and bump the node reference count to
1785 * reflect the held reference to be setup by ath_tx_start.
1786 */
1787static int
1788ath_txfrag_setup(struct ath_softc *sc, ath_bufhead *frags,
1789	struct mbuf *m0, struct ieee80211_node *ni)
1790{
1791	struct mbuf *m;
1792	struct ath_buf *bf;
1793
1794	ATH_TXBUF_LOCK(sc);
1795	for (m = m0->m_nextpkt; m != NULL; m = m->m_nextpkt) {
1796		bf = _ath_getbuf_locked(sc);
1797		if (bf == NULL) {	/* out of buffers, cleanup */
1798			ath_txfrag_cleanup(sc, frags, ni);
1799			break;
1800		}
1801		ieee80211_node_incref(ni);
1802		STAILQ_INSERT_TAIL(frags, bf, bf_list);
1803	}
1804	ATH_TXBUF_UNLOCK(sc);
1805
1806	return !STAILQ_EMPTY(frags);
1807}
1808
1809static void
1810ath_start(struct ifnet *ifp)
1811{
1812	struct ath_softc *sc = ifp->if_softc;
1813	struct ieee80211_node *ni;
1814	struct ath_buf *bf;
1815	struct mbuf *m, *next;
1816	ath_bufhead frags;
1817
1818	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
1819		return;
1820	for (;;) {
1821		/*
1822		 * Grab a TX buffer and associated resources.
1823		 */
1824		bf = ath_getbuf(sc);
1825		if (bf == NULL)
1826			break;
1827
1828		IFQ_DEQUEUE(&ifp->if_snd, m);
1829		if (m == NULL) {
1830			ATH_TXBUF_LOCK(sc);
1831			STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1832			ATH_TXBUF_UNLOCK(sc);
1833			break;
1834		}
1835		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1836		/*
1837		 * Check for fragmentation.  If this frame
1838		 * has been broken up verify we have enough
1839		 * buffers to send all the fragments so all
1840		 * go out or none...
1841		 */
1842		STAILQ_INIT(&frags);
1843		if ((m->m_flags & M_FRAG) &&
1844		    !ath_txfrag_setup(sc, &frags, m, ni)) {
1845			DPRINTF(sc, ATH_DEBUG_XMIT,
1846			    "%s: out of txfrag buffers\n", __func__);
1847			sc->sc_stats.ast_tx_nofrag++;
1848			ifp->if_oerrors++;
1849			ath_freetx(m);
1850			goto bad;
1851		}
1852		ifp->if_opackets++;
1853	nextfrag:
1854		/*
1855		 * Pass the frame to the h/w for transmission.
1856		 * Fragmented frames have each frag chained together
1857		 * with m_nextpkt.  We know there are sufficient ath_buf's
1858		 * to send all the frags because of work done by
1859		 * ath_txfrag_setup.  We leave m_nextpkt set while
1860		 * calling ath_tx_start so it can use it to extend the
1861		 * the tx duration to cover the subsequent frag and
1862		 * so it can reclaim all the mbufs in case of an error;
1863		 * ath_tx_start clears m_nextpkt once it commits to
1864		 * handing the frame to the hardware.
1865		 */
1866		next = m->m_nextpkt;
1867		if (ath_tx_start(sc, ni, bf, m)) {
1868	bad:
1869			ifp->if_oerrors++;
1870	reclaim:
1871			bf->bf_m = NULL;
1872			bf->bf_node = NULL;
1873			ATH_TXBUF_LOCK(sc);
1874			STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1875			ath_txfrag_cleanup(sc, &frags, ni);
1876			ATH_TXBUF_UNLOCK(sc);
1877			if (ni != NULL)
1878				ieee80211_free_node(ni);
1879			continue;
1880		}
1881		if (next != NULL) {
1882			/*
1883			 * Beware of state changing between frags.
1884			 * XXX check sta power-save state?
1885			 */
1886			if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
1887				DPRINTF(sc, ATH_DEBUG_XMIT,
1888				    "%s: flush fragmented packet, state %s\n",
1889				    __func__,
1890				    ieee80211_state_name[ni->ni_vap->iv_state]);
1891				ath_freetx(next);
1892				goto reclaim;
1893			}
1894			m = next;
1895			bf = STAILQ_FIRST(&frags);
1896			KASSERT(bf != NULL, ("no buf for txfrag"));
1897			STAILQ_REMOVE_HEAD(&frags, bf_list);
1898			goto nextfrag;
1899		}
1900
1901		sc->sc_wd_timer = 5;
1902	}
1903}
1904
1905static int
1906ath_media_change(struct ifnet *ifp)
1907{
1908	int error = ieee80211_media_change(ifp);
1909	/* NB: only the fixed rate can change and that doesn't need a reset */
1910	return (error == ENETRESET ? 0 : error);
1911}
1912
1913#ifdef ATH_DEBUG
1914static void
1915ath_keyprint(struct ath_softc *sc, const char *tag, u_int ix,
1916	const HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1917{
1918	static const char *ciphers[] = {
1919		"WEP",
1920		"AES-OCB",
1921		"AES-CCM",
1922		"CKIP",
1923		"TKIP",
1924		"CLR",
1925	};
1926	int i, n;
1927
1928	printf("%s: [%02u] %-7s ", tag, ix, ciphers[hk->kv_type]);
1929	for (i = 0, n = hk->kv_len; i < n; i++)
1930		printf("%02x", hk->kv_val[i]);
1931	printf(" mac %s", ether_sprintf(mac));
1932	if (hk->kv_type == HAL_CIPHER_TKIP) {
1933		printf(" %s ", sc->sc_splitmic ? "mic" : "rxmic");
1934		for (i = 0; i < sizeof(hk->kv_mic); i++)
1935			printf("%02x", hk->kv_mic[i]);
1936		if (!sc->sc_splitmic) {
1937			printf(" txmic ");
1938			for (i = 0; i < sizeof(hk->kv_txmic); i++)
1939				printf("%02x", hk->kv_txmic[i]);
1940		}
1941	}
1942	printf("\n");
1943}
1944#endif
1945
1946/*
1947 * Set a TKIP key into the hardware.  This handles the
1948 * potential distribution of key state to multiple key
1949 * cache slots for TKIP.
1950 */
1951static int
1952ath_keyset_tkip(struct ath_softc *sc, const struct ieee80211_key *k,
1953	HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1954{
1955#define	IEEE80211_KEY_XR	(IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV)
1956	static const u_int8_t zerobssid[IEEE80211_ADDR_LEN];
1957	struct ath_hal *ah = sc->sc_ah;
1958
1959	KASSERT(k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP,
1960		("got a non-TKIP key, cipher %u", k->wk_cipher->ic_cipher));
1961	if ((k->wk_flags & IEEE80211_KEY_XR) == IEEE80211_KEY_XR) {
1962		if (sc->sc_splitmic) {
1963			/*
1964			 * TX key goes at first index, RX key at the rx index.
1965			 * The hal handles the MIC keys at index+64.
1966			 */
1967			memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_mic));
1968			KEYPRINTF(sc, k->wk_keyix, hk, zerobssid);
1969			if (!ath_hal_keyset(ah, k->wk_keyix, hk, zerobssid))
1970				return 0;
1971
1972			memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1973			KEYPRINTF(sc, k->wk_keyix+32, hk, mac);
1974			/* XXX delete tx key on failure? */
1975			return ath_hal_keyset(ah, k->wk_keyix+32, hk, mac);
1976		} else {
1977			/*
1978			 * Room for both TX+RX MIC keys in one key cache
1979			 * slot, just set key at the first index; the hal
1980			 * will handle the rest.
1981			 */
1982			memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1983			memcpy(hk->kv_txmic, k->wk_txmic, sizeof(hk->kv_txmic));
1984			KEYPRINTF(sc, k->wk_keyix, hk, mac);
1985			return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1986		}
1987	} else if (k->wk_flags & IEEE80211_KEY_XMIT) {
1988		if (sc->sc_splitmic) {
1989			/*
1990			 * NB: must pass MIC key in expected location when
1991			 * the keycache only holds one MIC key per entry.
1992			 */
1993			memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_txmic));
1994		} else
1995			memcpy(hk->kv_txmic, k->wk_txmic, sizeof(hk->kv_txmic));
1996		KEYPRINTF(sc, k->wk_keyix, hk, mac);
1997		return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1998	} else if (k->wk_flags & IEEE80211_KEY_RECV) {
1999		memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
2000		KEYPRINTF(sc, k->wk_keyix, hk, mac);
2001		return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
2002	}
2003	return 0;
2004#undef IEEE80211_KEY_XR
2005}
2006
2007/*
2008 * Set a net80211 key into the hardware.  This handles the
2009 * potential distribution of key state to multiple key
2010 * cache slots for TKIP with hardware MIC support.
2011 */
2012static int
2013ath_keyset(struct ath_softc *sc, const struct ieee80211_key *k,
2014	struct ieee80211_node *bss)
2015{
2016#define	N(a)	(sizeof(a)/sizeof(a[0]))
2017	static const u_int8_t ciphermap[] = {
2018		HAL_CIPHER_WEP,		/* IEEE80211_CIPHER_WEP */
2019		HAL_CIPHER_TKIP,	/* IEEE80211_CIPHER_TKIP */
2020		HAL_CIPHER_AES_OCB,	/* IEEE80211_CIPHER_AES_OCB */
2021		HAL_CIPHER_AES_CCM,	/* IEEE80211_CIPHER_AES_CCM */
2022		(u_int8_t) -1,		/* 4 is not allocated */
2023		HAL_CIPHER_CKIP,	/* IEEE80211_CIPHER_CKIP */
2024		HAL_CIPHER_CLR,		/* IEEE80211_CIPHER_NONE */
2025	};
2026	struct ath_hal *ah = sc->sc_ah;
2027	const struct ieee80211_cipher *cip = k->wk_cipher;
2028	u_int8_t gmac[IEEE80211_ADDR_LEN];
2029	const u_int8_t *mac;
2030	HAL_KEYVAL hk;
2031
2032	memset(&hk, 0, sizeof(hk));
2033	/*
2034	 * Software crypto uses a "clear key" so non-crypto
2035	 * state kept in the key cache are maintained and
2036	 * so that rx frames have an entry to match.
2037	 */
2038	if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) == 0) {
2039		KASSERT(cip->ic_cipher < N(ciphermap),
2040			("invalid cipher type %u", cip->ic_cipher));
2041		hk.kv_type = ciphermap[cip->ic_cipher];
2042		hk.kv_len = k->wk_keylen;
2043		memcpy(hk.kv_val, k->wk_key, k->wk_keylen);
2044	} else
2045		hk.kv_type = HAL_CIPHER_CLR;
2046
2047	if ((k->wk_flags & IEEE80211_KEY_GROUP) && sc->sc_mcastkey) {
2048		/*
2049		 * Group keys on hardware that supports multicast frame
2050		 * key search use a MAC that is the sender's address with
2051		 * the high bit set instead of the app-specified address.
2052		 */
2053		IEEE80211_ADDR_COPY(gmac, bss->ni_macaddr);
2054		gmac[0] |= 0x80;
2055		mac = gmac;
2056	} else
2057		mac = k->wk_macaddr;
2058
2059	if (hk.kv_type == HAL_CIPHER_TKIP &&
2060	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2061		return ath_keyset_tkip(sc, k, &hk, mac);
2062	} else {
2063		KEYPRINTF(sc, k->wk_keyix, &hk, mac);
2064		return ath_hal_keyset(ah, k->wk_keyix, &hk, mac);
2065	}
2066#undef N
2067}
2068
2069/*
2070 * Allocate tx/rx key slots for TKIP.  We allocate two slots for
2071 * each key, one for decrypt/encrypt and the other for the MIC.
2072 */
2073static u_int16_t
2074key_alloc_2pair(struct ath_softc *sc,
2075	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2076{
2077#define	N(a)	(sizeof(a)/sizeof(a[0]))
2078	u_int i, keyix;
2079
2080	KASSERT(sc->sc_splitmic, ("key cache !split"));
2081	/* XXX could optimize */
2082	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
2083		u_int8_t b = sc->sc_keymap[i];
2084		if (b != 0xff) {
2085			/*
2086			 * One or more slots in this byte are free.
2087			 */
2088			keyix = i*NBBY;
2089			while (b & 1) {
2090		again:
2091				keyix++;
2092				b >>= 1;
2093			}
2094			/* XXX IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV */
2095			if (isset(sc->sc_keymap, keyix+32) ||
2096			    isset(sc->sc_keymap, keyix+64) ||
2097			    isset(sc->sc_keymap, keyix+32+64)) {
2098				/* full pair unavailable */
2099				/* XXX statistic */
2100				if (keyix == (i+1)*NBBY) {
2101					/* no slots were appropriate, advance */
2102					continue;
2103				}
2104				goto again;
2105			}
2106			setbit(sc->sc_keymap, keyix);
2107			setbit(sc->sc_keymap, keyix+64);
2108			setbit(sc->sc_keymap, keyix+32);
2109			setbit(sc->sc_keymap, keyix+32+64);
2110			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2111				"%s: key pair %u,%u %u,%u\n",
2112				__func__, keyix, keyix+64,
2113				keyix+32, keyix+32+64);
2114			*txkeyix = keyix;
2115			*rxkeyix = keyix+32;
2116			return 1;
2117		}
2118	}
2119	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
2120	return 0;
2121#undef N
2122}
2123
2124/*
2125 * Allocate tx/rx key slots for TKIP.  We allocate two slots for
2126 * each key, one for decrypt/encrypt and the other for the MIC.
2127 */
2128static u_int16_t
2129key_alloc_pair(struct ath_softc *sc,
2130	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2131{
2132#define	N(a)	(sizeof(a)/sizeof(a[0]))
2133	u_int i, keyix;
2134
2135	KASSERT(!sc->sc_splitmic, ("key cache split"));
2136	/* XXX could optimize */
2137	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
2138		u_int8_t b = sc->sc_keymap[i];
2139		if (b != 0xff) {
2140			/*
2141			 * One or more slots in this byte are free.
2142			 */
2143			keyix = i*NBBY;
2144			while (b & 1) {
2145		again:
2146				keyix++;
2147				b >>= 1;
2148			}
2149			if (isset(sc->sc_keymap, keyix+64)) {
2150				/* full pair unavailable */
2151				/* XXX statistic */
2152				if (keyix == (i+1)*NBBY) {
2153					/* no slots were appropriate, advance */
2154					continue;
2155				}
2156				goto again;
2157			}
2158			setbit(sc->sc_keymap, keyix);
2159			setbit(sc->sc_keymap, keyix+64);
2160			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2161				"%s: key pair %u,%u\n",
2162				__func__, keyix, keyix+64);
2163			*txkeyix = *rxkeyix = keyix;
2164			return 1;
2165		}
2166	}
2167	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
2168	return 0;
2169#undef N
2170}
2171
2172/*
2173 * Allocate a single key cache slot.
2174 */
2175static int
2176key_alloc_single(struct ath_softc *sc,
2177	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2178{
2179#define	N(a)	(sizeof(a)/sizeof(a[0]))
2180	u_int i, keyix;
2181
2182	/* XXX try i,i+32,i+64,i+32+64 to minimize key pair conflicts */
2183	for (i = 0; i < N(sc->sc_keymap); i++) {
2184		u_int8_t b = sc->sc_keymap[i];
2185		if (b != 0xff) {
2186			/*
2187			 * One or more slots are free.
2188			 */
2189			keyix = i*NBBY;
2190			while (b & 1)
2191				keyix++, b >>= 1;
2192			setbit(sc->sc_keymap, keyix);
2193			DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: key %u\n",
2194				__func__, keyix);
2195			*txkeyix = *rxkeyix = keyix;
2196			return 1;
2197		}
2198	}
2199	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of space\n", __func__);
2200	return 0;
2201#undef N
2202}
2203
2204/*
2205 * Allocate one or more key cache slots for a uniacst key.  The
2206 * key itself is needed only to identify the cipher.  For hardware
2207 * TKIP with split cipher+MIC keys we allocate two key cache slot
2208 * pairs so that we can setup separate TX and RX MIC keys.  Note
2209 * that the MIC key for a TKIP key at slot i is assumed by the
2210 * hardware to be at slot i+64.  This limits TKIP keys to the first
2211 * 64 entries.
2212 */
2213static int
2214ath_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,
2215	ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
2216{
2217	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2218
2219	/*
2220	 * Group key allocation must be handled specially for
2221	 * parts that do not support multicast key cache search
2222	 * functionality.  For those parts the key id must match
2223	 * the h/w key index so lookups find the right key.  On
2224	 * parts w/ the key search facility we install the sender's
2225	 * mac address (with the high bit set) and let the hardware
2226	 * find the key w/o using the key id.  This is preferred as
2227	 * it permits us to support multiple users for adhoc and/or
2228	 * multi-station operation.
2229	 */
2230	if (k->wk_keyix != IEEE80211_KEYIX_NONE) {
2231		/*
2232		 * Only global keys should have key index assigned.
2233		 */
2234		if (!(&vap->iv_nw_keys[0] <= k &&
2235		      k < &vap->iv_nw_keys[IEEE80211_WEP_NKID])) {
2236			/* should not happen */
2237			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2238				"%s: bogus group key\n", __func__);
2239			return 0;
2240		}
2241		if (vap->iv_opmode != IEEE80211_M_HOSTAP ||
2242		    !(k->wk_flags & IEEE80211_KEY_GROUP) ||
2243		    !sc->sc_mcastkey) {
2244			/*
2245			 * XXX we pre-allocate the global keys so
2246			 * have no way to check if they've already
2247			 * been allocated.
2248			 */
2249			*keyix = *rxkeyix = k - vap->iv_nw_keys;
2250			return 1;
2251		}
2252		/*
2253		 * Group key and device supports multicast key search.
2254		 */
2255		k->wk_keyix = IEEE80211_KEYIX_NONE;
2256	}
2257
2258	/*
2259	 * We allocate two pair for TKIP when using the h/w to do
2260	 * the MIC.  For everything else, including software crypto,
2261	 * we allocate a single entry.  Note that s/w crypto requires
2262	 * a pass-through slot on the 5211 and 5212.  The 5210 does
2263	 * not support pass-through cache entries and we map all
2264	 * those requests to slot 0.
2265	 */
2266	if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
2267		return key_alloc_single(sc, keyix, rxkeyix);
2268	} else if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP &&
2269	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2270		if (sc->sc_splitmic)
2271			return key_alloc_2pair(sc, keyix, rxkeyix);
2272		else
2273			return key_alloc_pair(sc, keyix, rxkeyix);
2274	} else {
2275		return key_alloc_single(sc, keyix, rxkeyix);
2276	}
2277}
2278
2279/*
2280 * Delete an entry in the key cache allocated by ath_key_alloc.
2281 */
2282static int
2283ath_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
2284{
2285	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2286	struct ath_hal *ah = sc->sc_ah;
2287	const struct ieee80211_cipher *cip = k->wk_cipher;
2288	u_int keyix = k->wk_keyix;
2289
2290	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: delete key %u\n", __func__, keyix);
2291
2292	ath_hal_keyreset(ah, keyix);
2293	/*
2294	 * Handle split tx/rx keying required for TKIP with h/w MIC.
2295	 */
2296	if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
2297	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic)
2298		ath_hal_keyreset(ah, keyix+32);		/* RX key */
2299	if (keyix >= IEEE80211_WEP_NKID) {
2300		/*
2301		 * Don't touch keymap entries for global keys so
2302		 * they are never considered for dynamic allocation.
2303		 */
2304		clrbit(sc->sc_keymap, keyix);
2305		if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
2306		    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2307			clrbit(sc->sc_keymap, keyix+64);	/* TX key MIC */
2308			if (sc->sc_splitmic) {
2309				/* +32 for RX key, +32+64 for RX key MIC */
2310				clrbit(sc->sc_keymap, keyix+32);
2311				clrbit(sc->sc_keymap, keyix+32+64);
2312			}
2313		}
2314	}
2315	return 1;
2316}
2317
2318/*
2319 * Set the key cache contents for the specified key.  Key cache
2320 * slot(s) must already have been allocated by ath_key_alloc.
2321 */
2322static int
2323ath_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k,
2324	const u_int8_t mac[IEEE80211_ADDR_LEN])
2325{
2326	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2327
2328	return ath_keyset(sc, k, vap->iv_bss);
2329}
2330
2331/*
2332 * Block/unblock tx+rx processing while a key change is done.
2333 * We assume the caller serializes key management operations
2334 * so we only need to worry about synchronization with other
2335 * uses that originate in the driver.
2336 */
2337static void
2338ath_key_update_begin(struct ieee80211vap *vap)
2339{
2340	struct ifnet *ifp = vap->iv_ic->ic_ifp;
2341	struct ath_softc *sc = ifp->if_softc;
2342
2343	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2344	taskqueue_block(sc->sc_tq);
2345	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
2346}
2347
2348static void
2349ath_key_update_end(struct ieee80211vap *vap)
2350{
2351	struct ifnet *ifp = vap->iv_ic->ic_ifp;
2352	struct ath_softc *sc = ifp->if_softc;
2353
2354	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2355	IF_UNLOCK(&ifp->if_snd);
2356	taskqueue_unblock(sc->sc_tq);
2357}
2358
2359/*
2360 * Calculate the receive filter according to the
2361 * operating mode and state:
2362 *
2363 * o always accept unicast, broadcast, and multicast traffic
2364 * o accept PHY error frames when hardware doesn't have MIB support
2365 *   to count and we need them for ANI (sta mode only until recently)
2366 *   and we are not scanning (ANI is disabled)
2367 *   NB: older hal's add rx filter bits out of sight and we need to
2368 *	 blindly preserve them
2369 * o probe request frames are accepted only when operating in
2370 *   hostap, adhoc, mesh, or monitor modes
2371 * o enable promiscuous mode
2372 *   - when in monitor mode
2373 *   - if interface marked PROMISC (assumes bridge setting is filtered)
2374 * o accept beacons:
2375 *   - when operating in station mode for collecting rssi data when
2376 *     the station is otherwise quiet, or
2377 *   - when operating in adhoc mode so the 802.11 layer creates
2378 *     node table entries for peers,
2379 *   - when scanning
2380 *   - when doing s/w beacon miss (e.g. for ap+sta)
2381 *   - when operating in ap mode in 11g to detect overlapping bss that
2382 *     require protection
2383 *   - when operating in mesh mode to detect neighbors
2384 * o accept control frames:
2385 *   - when in monitor mode
2386 * XXX BAR frames for 11n
2387 * XXX HT protection for 11n
2388 */
2389static u_int32_t
2390ath_calcrxfilter(struct ath_softc *sc)
2391{
2392	struct ifnet *ifp = sc->sc_ifp;
2393	struct ieee80211com *ic = ifp->if_l2com;
2394	u_int32_t rfilt;
2395
2396	rfilt = HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
2397	if (!sc->sc_needmib && !sc->sc_scanning)
2398		rfilt |= HAL_RX_FILTER_PHYERR;
2399	if (ic->ic_opmode != IEEE80211_M_STA)
2400		rfilt |= HAL_RX_FILTER_PROBEREQ;
2401	/* XXX ic->ic_monvaps != 0? */
2402	if (ic->ic_opmode == IEEE80211_M_MONITOR || (ifp->if_flags & IFF_PROMISC))
2403		rfilt |= HAL_RX_FILTER_PROM;
2404	if (ic->ic_opmode == IEEE80211_M_STA ||
2405	    ic->ic_opmode == IEEE80211_M_IBSS ||
2406	    sc->sc_swbmiss || sc->sc_scanning)
2407		rfilt |= HAL_RX_FILTER_BEACON;
2408	/*
2409	 * NB: We don't recalculate the rx filter when
2410	 * ic_protmode changes; otherwise we could do
2411	 * this only when ic_protmode != NONE.
2412	 */
2413	if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
2414	    IEEE80211_IS_CHAN_ANYG(ic->ic_curchan))
2415		rfilt |= HAL_RX_FILTER_BEACON;
2416	if (sc->sc_nmeshvaps) {
2417		rfilt |= HAL_RX_FILTER_BEACON;
2418		if (sc->sc_hasbmatch)
2419			rfilt |= HAL_RX_FILTER_BSSID;
2420		else
2421			rfilt |= HAL_RX_FILTER_PROM;
2422	}
2423	if (ic->ic_opmode == IEEE80211_M_MONITOR)
2424		rfilt |= HAL_RX_FILTER_CONTROL;
2425	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, %s if_flags 0x%x\n",
2426	    __func__, rfilt, ieee80211_opmode_name[ic->ic_opmode], ifp->if_flags);
2427	return rfilt;
2428}
2429
2430static void
2431ath_update_promisc(struct ifnet *ifp)
2432{
2433	struct ath_softc *sc = ifp->if_softc;
2434	u_int32_t rfilt;
2435
2436	/* configure rx filter */
2437	rfilt = ath_calcrxfilter(sc);
2438	ath_hal_setrxfilter(sc->sc_ah, rfilt);
2439
2440	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
2441}
2442
2443static void
2444ath_update_mcast(struct ifnet *ifp)
2445{
2446	struct ath_softc *sc = ifp->if_softc;
2447	u_int32_t mfilt[2];
2448
2449	/* calculate and install multicast filter */
2450	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
2451		struct ifmultiaddr *ifma;
2452		/*
2453		 * Merge multicast addresses to form the hardware filter.
2454		 */
2455		mfilt[0] = mfilt[1] = 0;
2456		if_maddr_rlock(ifp);	/* XXX need some fiddling to remove? */
2457		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2458			caddr_t dl;
2459			u_int32_t val;
2460			u_int8_t pos;
2461
2462			/* calculate XOR of eight 6bit values */
2463			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
2464			val = LE_READ_4(dl + 0);
2465			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2466			val = LE_READ_4(dl + 3);
2467			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2468			pos &= 0x3f;
2469			mfilt[pos / 32] |= (1 << (pos % 32));
2470		}
2471		if_maddr_runlock(ifp);
2472	} else
2473		mfilt[0] = mfilt[1] = ~0;
2474	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
2475	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
2476		__func__, mfilt[0], mfilt[1]);
2477}
2478
2479static void
2480ath_mode_init(struct ath_softc *sc)
2481{
2482	struct ifnet *ifp = sc->sc_ifp;
2483	struct ath_hal *ah = sc->sc_ah;
2484	u_int32_t rfilt;
2485
2486	/* configure rx filter */
2487	rfilt = ath_calcrxfilter(sc);
2488	ath_hal_setrxfilter(ah, rfilt);
2489
2490	/* configure operational mode */
2491	ath_hal_setopmode(ah);
2492
2493	/* handle any link-level address change */
2494	ath_hal_setmac(ah, IF_LLADDR(ifp));
2495
2496	/* calculate and install multicast filter */
2497	ath_update_mcast(ifp);
2498}
2499
2500/*
2501 * Set the slot time based on the current setting.
2502 */
2503static void
2504ath_setslottime(struct ath_softc *sc)
2505{
2506	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2507	struct ath_hal *ah = sc->sc_ah;
2508	u_int usec;
2509
2510	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
2511		usec = 13;
2512	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
2513		usec = 21;
2514	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
2515		/* honor short/long slot time only in 11g */
2516		/* XXX shouldn't honor on pure g or turbo g channel */
2517		if (ic->ic_flags & IEEE80211_F_SHSLOT)
2518			usec = HAL_SLOT_TIME_9;
2519		else
2520			usec = HAL_SLOT_TIME_20;
2521	} else
2522		usec = HAL_SLOT_TIME_9;
2523
2524	DPRINTF(sc, ATH_DEBUG_RESET,
2525	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
2526	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
2527	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
2528
2529	ath_hal_setslottime(ah, usec);
2530	sc->sc_updateslot = OK;
2531}
2532
2533/*
2534 * Callback from the 802.11 layer to update the
2535 * slot time based on the current setting.
2536 */
2537static void
2538ath_updateslot(struct ifnet *ifp)
2539{
2540	struct ath_softc *sc = ifp->if_softc;
2541	struct ieee80211com *ic = ifp->if_l2com;
2542
2543	/*
2544	 * When not coordinating the BSS, change the hardware
2545	 * immediately.  For other operation we defer the change
2546	 * until beacon updates have propagated to the stations.
2547	 */
2548	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2549	    ic->ic_opmode == IEEE80211_M_MBSS)
2550		sc->sc_updateslot = UPDATE;
2551	else
2552		ath_setslottime(sc);
2553}
2554
2555/*
2556 * Setup a h/w transmit queue for beacons.
2557 */
2558static int
2559ath_beaconq_setup(struct ath_hal *ah)
2560{
2561	HAL_TXQ_INFO qi;
2562
2563	memset(&qi, 0, sizeof(qi));
2564	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
2565	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
2566	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
2567	/* NB: for dynamic turbo, don't enable any other interrupts */
2568	qi.tqi_qflags = HAL_TXQ_TXDESCINT_ENABLE;
2569	return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
2570}
2571
2572/*
2573 * Setup the transmit queue parameters for the beacon queue.
2574 */
2575static int
2576ath_beaconq_config(struct ath_softc *sc)
2577{
2578#define	ATH_EXPONENT_TO_VALUE(v)	((1<<(v))-1)
2579	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2580	struct ath_hal *ah = sc->sc_ah;
2581	HAL_TXQ_INFO qi;
2582
2583	ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
2584	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2585	    ic->ic_opmode == IEEE80211_M_MBSS) {
2586		/*
2587		 * Always burst out beacon and CAB traffic.
2588		 */
2589		qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
2590		qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
2591		qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
2592	} else {
2593		struct wmeParams *wmep =
2594			&ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
2595		/*
2596		 * Adhoc mode; important thing is to use 2x cwmin.
2597		 */
2598		qi.tqi_aifs = wmep->wmep_aifsn;
2599		qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
2600		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
2601	}
2602
2603	if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
2604		device_printf(sc->sc_dev, "unable to update parameters for "
2605			"beacon hardware queue!\n");
2606		return 0;
2607	} else {
2608		ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
2609		return 1;
2610	}
2611#undef ATH_EXPONENT_TO_VALUE
2612}
2613
2614/*
2615 * Allocate and setup an initial beacon frame.
2616 */
2617static int
2618ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
2619{
2620	struct ieee80211vap *vap = ni->ni_vap;
2621	struct ath_vap *avp = ATH_VAP(vap);
2622	struct ath_buf *bf;
2623	struct mbuf *m;
2624	int error;
2625
2626	bf = avp->av_bcbuf;
2627	if (bf->bf_m != NULL) {
2628		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2629		m_freem(bf->bf_m);
2630		bf->bf_m = NULL;
2631	}
2632	if (bf->bf_node != NULL) {
2633		ieee80211_free_node(bf->bf_node);
2634		bf->bf_node = NULL;
2635	}
2636
2637	/*
2638	 * NB: the beacon data buffer must be 32-bit aligned;
2639	 * we assume the mbuf routines will return us something
2640	 * with this alignment (perhaps should assert).
2641	 */
2642	m = ieee80211_beacon_alloc(ni, &avp->av_boff);
2643	if (m == NULL) {
2644		device_printf(sc->sc_dev, "%s: cannot get mbuf\n", __func__);
2645		sc->sc_stats.ast_be_nombuf++;
2646		return ENOMEM;
2647	}
2648	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2649				     bf->bf_segs, &bf->bf_nseg,
2650				     BUS_DMA_NOWAIT);
2651	if (error != 0) {
2652		device_printf(sc->sc_dev,
2653		    "%s: cannot map mbuf, bus_dmamap_load_mbuf_sg returns %d\n",
2654		    __func__, error);
2655		m_freem(m);
2656		return error;
2657	}
2658
2659	/*
2660	 * Calculate a TSF adjustment factor required for staggered
2661	 * beacons.  Note that we assume the format of the beacon
2662	 * frame leaves the tstamp field immediately following the
2663	 * header.
2664	 */
2665	if (sc->sc_stagbeacons && avp->av_bslot > 0) {
2666		uint64_t tsfadjust;
2667		struct ieee80211_frame *wh;
2668
2669		/*
2670		 * The beacon interval is in TU's; the TSF is in usecs.
2671		 * We figure out how many TU's to add to align the timestamp
2672		 * then convert to TSF units and handle byte swapping before
2673		 * inserting it in the frame.  The hardware will then add this
2674		 * each time a beacon frame is sent.  Note that we align vap's
2675		 * 1..N and leave vap 0 untouched.  This means vap 0 has a
2676		 * timestamp in one beacon interval while the others get a
2677		 * timstamp aligned to the next interval.
2678		 */
2679		tsfadjust = ni->ni_intval *
2680		    (ATH_BCBUF - avp->av_bslot) / ATH_BCBUF;
2681		tsfadjust = htole64(tsfadjust << 10);	/* TU -> TSF */
2682
2683		DPRINTF(sc, ATH_DEBUG_BEACON,
2684		    "%s: %s beacons bslot %d intval %u tsfadjust %llu\n",
2685		    __func__, sc->sc_stagbeacons ? "stagger" : "burst",
2686		    avp->av_bslot, ni->ni_intval,
2687		    (long long unsigned) le64toh(tsfadjust));
2688
2689		wh = mtod(m, struct ieee80211_frame *);
2690		memcpy(&wh[1], &tsfadjust, sizeof(tsfadjust));
2691	}
2692	bf->bf_m = m;
2693	bf->bf_node = ieee80211_ref_node(ni);
2694
2695	return 0;
2696}
2697
2698/*
2699 * Setup the beacon frame for transmit.
2700 */
2701static void
2702ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
2703{
2704#define	USE_SHPREAMBLE(_ic) \
2705	(((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
2706		== IEEE80211_F_SHPREAMBLE)
2707	struct ieee80211_node *ni = bf->bf_node;
2708	struct ieee80211com *ic = ni->ni_ic;
2709	struct mbuf *m = bf->bf_m;
2710	struct ath_hal *ah = sc->sc_ah;
2711	struct ath_desc *ds;
2712	int flags, antenna;
2713	const HAL_RATE_TABLE *rt;
2714	u_int8_t rix, rate;
2715
2716	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: m %p len %u\n",
2717		__func__, m, m->m_len);
2718
2719	/* setup descriptors */
2720	ds = bf->bf_desc;
2721
2722	flags = HAL_TXDESC_NOACK;
2723	if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
2724		ds->ds_link = bf->bf_daddr;	/* self-linked */
2725		flags |= HAL_TXDESC_VEOL;
2726		/*
2727		 * Let hardware handle antenna switching.
2728		 */
2729		antenna = sc->sc_txantenna;
2730	} else {
2731		ds->ds_link = 0;
2732		/*
2733		 * Switch antenna every 4 beacons.
2734		 * XXX assumes two antenna
2735		 */
2736		if (sc->sc_txantenna != 0)
2737			antenna = sc->sc_txantenna;
2738		else if (sc->sc_stagbeacons && sc->sc_nbcnvaps != 0)
2739			antenna = ((sc->sc_stats.ast_be_xmit / sc->sc_nbcnvaps) & 4 ? 2 : 1);
2740		else
2741			antenna = (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
2742	}
2743
2744	KASSERT(bf->bf_nseg == 1,
2745		("multi-segment beacon frame; nseg %u", bf->bf_nseg));
2746	ds->ds_data = bf->bf_segs[0].ds_addr;
2747	/*
2748	 * Calculate rate code.
2749	 * XXX everything at min xmit rate
2750	 */
2751	rix = 0;
2752	rt = sc->sc_currates;
2753	rate = rt->info[rix].rateCode;
2754	if (USE_SHPREAMBLE(ic))
2755		rate |= rt->info[rix].shortPreamble;
2756	ath_hal_setuptxdesc(ah, ds
2757		, m->m_len + IEEE80211_CRC_LEN	/* frame length */
2758		, sizeof(struct ieee80211_frame)/* header length */
2759		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
2760		, ni->ni_txpower		/* txpower XXX */
2761		, rate, 1			/* series 0 rate/tries */
2762		, HAL_TXKEYIX_INVALID		/* no encryption */
2763		, antenna			/* antenna mode */
2764		, flags				/* no ack, veol for beacons */
2765		, 0				/* rts/cts rate */
2766		, 0				/* rts/cts duration */
2767	);
2768	/* NB: beacon's BufLen must be a multiple of 4 bytes */
2769	ath_hal_filltxdesc(ah, ds
2770		, roundup(m->m_len, 4)		/* buffer length */
2771		, AH_TRUE			/* first segment */
2772		, AH_TRUE			/* last segment */
2773		, ds				/* first descriptor */
2774	);
2775#if 0
2776	ath_desc_swap(ds);
2777#endif
2778#undef USE_SHPREAMBLE
2779}
2780
2781static void
2782ath_beacon_update(struct ieee80211vap *vap, int item)
2783{
2784	struct ieee80211_beacon_offsets *bo = &ATH_VAP(vap)->av_boff;
2785
2786	setbit(bo->bo_flags, item);
2787}
2788
2789/*
2790 * Append the contents of src to dst; both queues
2791 * are assumed to be locked.
2792 */
2793static void
2794ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
2795{
2796	STAILQ_CONCAT(&dst->axq_q, &src->axq_q);
2797	dst->axq_link = src->axq_link;
2798	src->axq_link = NULL;
2799	dst->axq_depth += src->axq_depth;
2800	src->axq_depth = 0;
2801}
2802
2803/*
2804 * Transmit a beacon frame at SWBA.  Dynamic updates to the
2805 * frame contents are done as needed and the slot time is
2806 * also adjusted based on current state.
2807 */
2808static void
2809ath_beacon_proc(void *arg, int pending)
2810{
2811	struct ath_softc *sc = arg;
2812	struct ath_hal *ah = sc->sc_ah;
2813	struct ieee80211vap *vap;
2814	struct ath_buf *bf;
2815	int slot, otherant;
2816	uint32_t bfaddr;
2817
2818	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
2819		__func__, pending);
2820	/*
2821	 * Check if the previous beacon has gone out.  If
2822	 * not don't try to post another, skip this period
2823	 * and wait for the next.  Missed beacons indicate
2824	 * a problem and should not occur.  If we miss too
2825	 * many consecutive beacons reset the device.
2826	 */
2827	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
2828		sc->sc_bmisscount++;
2829		sc->sc_stats.ast_be_missed++;
2830		DPRINTF(sc, ATH_DEBUG_BEACON,
2831			"%s: missed %u consecutive beacons\n",
2832			__func__, sc->sc_bmisscount);
2833		if (sc->sc_bmisscount >= ath_bstuck_threshold)
2834			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
2835		return;
2836	}
2837	if (sc->sc_bmisscount != 0) {
2838		DPRINTF(sc, ATH_DEBUG_BEACON,
2839			"%s: resume beacon xmit after %u misses\n",
2840			__func__, sc->sc_bmisscount);
2841		sc->sc_bmisscount = 0;
2842	}
2843
2844	if (sc->sc_stagbeacons) {			/* staggered beacons */
2845		struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2846		uint32_t tsftu;
2847
2848		tsftu = ath_hal_gettsf32(ah) >> 10;
2849		/* XXX lintval */
2850		slot = ((tsftu % ic->ic_lintval) * ATH_BCBUF) / ic->ic_lintval;
2851		vap = sc->sc_bslot[(slot+1) % ATH_BCBUF];
2852		bfaddr = 0;
2853		if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2854			bf = ath_beacon_generate(sc, vap);
2855			if (bf != NULL)
2856				bfaddr = bf->bf_daddr;
2857		}
2858	} else {					/* burst'd beacons */
2859		uint32_t *bflink = &bfaddr;
2860
2861		for (slot = 0; slot < ATH_BCBUF; slot++) {
2862			vap = sc->sc_bslot[slot];
2863			if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2864				bf = ath_beacon_generate(sc, vap);
2865				if (bf != NULL) {
2866					*bflink = bf->bf_daddr;
2867					bflink = &bf->bf_desc->ds_link;
2868				}
2869			}
2870		}
2871		*bflink = 0;				/* terminate list */
2872	}
2873
2874	/*
2875	 * Handle slot time change when a non-ERP station joins/leaves
2876	 * an 11g network.  The 802.11 layer notifies us via callback,
2877	 * we mark updateslot, then wait one beacon before effecting
2878	 * the change.  This gives associated stations at least one
2879	 * beacon interval to note the state change.
2880	 */
2881	/* XXX locking */
2882	if (sc->sc_updateslot == UPDATE) {
2883		sc->sc_updateslot = COMMIT;	/* commit next beacon */
2884		sc->sc_slotupdate = slot;
2885	} else if (sc->sc_updateslot == COMMIT && sc->sc_slotupdate == slot)
2886		ath_setslottime(sc);		/* commit change to h/w */
2887
2888	/*
2889	 * Check recent per-antenna transmit statistics and flip
2890	 * the default antenna if noticeably more frames went out
2891	 * on the non-default antenna.
2892	 * XXX assumes 2 anntenae
2893	 */
2894	if (!sc->sc_diversity && (!sc->sc_stagbeacons || slot == 0)) {
2895		otherant = sc->sc_defant & 1 ? 2 : 1;
2896		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
2897			ath_setdefantenna(sc, otherant);
2898		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
2899	}
2900
2901	if (bfaddr != 0) {
2902		/*
2903		 * Stop any current dma and put the new frame on the queue.
2904		 * This should never fail since we check above that no frames
2905		 * are still pending on the queue.
2906		 */
2907		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
2908			DPRINTF(sc, ATH_DEBUG_ANY,
2909				"%s: beacon queue %u did not stop?\n",
2910				__func__, sc->sc_bhalq);
2911		}
2912		/* NB: cabq traffic should already be queued and primed */
2913		ath_hal_puttxbuf(ah, sc->sc_bhalq, bfaddr);
2914		ath_hal_txstart(ah, sc->sc_bhalq);
2915
2916		sc->sc_stats.ast_be_xmit++;
2917	}
2918}
2919
2920static struct ath_buf *
2921ath_beacon_generate(struct ath_softc *sc, struct ieee80211vap *vap)
2922{
2923	struct ath_vap *avp = ATH_VAP(vap);
2924	struct ath_txq *cabq = sc->sc_cabq;
2925	struct ath_buf *bf;
2926	struct mbuf *m;
2927	int nmcastq, error;
2928
2929	KASSERT(vap->iv_state >= IEEE80211_S_RUN,
2930	    ("not running, state %d", vap->iv_state));
2931	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
2932
2933	/*
2934	 * Update dynamic beacon contents.  If this returns
2935	 * non-zero then we need to remap the memory because
2936	 * the beacon frame changed size (probably because
2937	 * of the TIM bitmap).
2938	 */
2939	bf = avp->av_bcbuf;
2940	m = bf->bf_m;
2941	nmcastq = avp->av_mcastq.axq_depth;
2942	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, nmcastq)) {
2943		/* XXX too conservative? */
2944		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2945		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2946					     bf->bf_segs, &bf->bf_nseg,
2947					     BUS_DMA_NOWAIT);
2948		if (error != 0) {
2949			if_printf(vap->iv_ifp,
2950			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
2951			    __func__, error);
2952			return NULL;
2953		}
2954	}
2955	if ((avp->av_boff.bo_tim[4] & 1) && cabq->axq_depth) {
2956		DPRINTF(sc, ATH_DEBUG_BEACON,
2957		    "%s: cabq did not drain, mcastq %u cabq %u\n",
2958		    __func__, nmcastq, cabq->axq_depth);
2959		sc->sc_stats.ast_cabq_busy++;
2960		if (sc->sc_nvaps > 1 && sc->sc_stagbeacons) {
2961			/*
2962			 * CABQ traffic from a previous vap is still pending.
2963			 * We must drain the q before this beacon frame goes
2964			 * out as otherwise this vap's stations will get cab
2965			 * frames from a different vap.
2966			 * XXX could be slow causing us to miss DBA
2967			 */
2968			ath_tx_draintxq(sc, cabq);
2969		}
2970	}
2971	ath_beacon_setup(sc, bf);
2972	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2973
2974	/*
2975	 * Enable the CAB queue before the beacon queue to
2976	 * insure cab frames are triggered by this beacon.
2977	 */
2978	if (avp->av_boff.bo_tim[4] & 1) {
2979		struct ath_hal *ah = sc->sc_ah;
2980
2981		/* NB: only at DTIM */
2982		ATH_TXQ_LOCK(cabq);
2983		ATH_TXQ_LOCK(&avp->av_mcastq);
2984		if (nmcastq) {
2985			struct ath_buf *bfm;
2986
2987			/*
2988			 * Move frames from the s/w mcast q to the h/w cab q.
2989			 * XXX MORE_DATA bit
2990			 */
2991			bfm = STAILQ_FIRST(&avp->av_mcastq.axq_q);
2992			if (cabq->axq_link != NULL) {
2993				*cabq->axq_link = bfm->bf_daddr;
2994			} else
2995				ath_hal_puttxbuf(ah, cabq->axq_qnum,
2996					bfm->bf_daddr);
2997			ath_txqmove(cabq, &avp->av_mcastq);
2998
2999			sc->sc_stats.ast_cabq_xmit += nmcastq;
3000		}
3001		/* NB: gated by beacon so safe to start here */
3002		ath_hal_txstart(ah, cabq->axq_qnum);
3003		ATH_TXQ_UNLOCK(cabq);
3004		ATH_TXQ_UNLOCK(&avp->av_mcastq);
3005	}
3006	return bf;
3007}
3008
3009static void
3010ath_beacon_start_adhoc(struct ath_softc *sc, struct ieee80211vap *vap)
3011{
3012	struct ath_vap *avp = ATH_VAP(vap);
3013	struct ath_hal *ah = sc->sc_ah;
3014	struct ath_buf *bf;
3015	struct mbuf *m;
3016	int error;
3017
3018	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
3019
3020	/*
3021	 * Update dynamic beacon contents.  If this returns
3022	 * non-zero then we need to remap the memory because
3023	 * the beacon frame changed size (probably because
3024	 * of the TIM bitmap).
3025	 */
3026	bf = avp->av_bcbuf;
3027	m = bf->bf_m;
3028	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, 0)) {
3029		/* XXX too conservative? */
3030		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3031		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
3032					     bf->bf_segs, &bf->bf_nseg,
3033					     BUS_DMA_NOWAIT);
3034		if (error != 0) {
3035			if_printf(vap->iv_ifp,
3036			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
3037			    __func__, error);
3038			return;
3039		}
3040	}
3041	ath_beacon_setup(sc, bf);
3042	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3043
3044	/* NB: caller is known to have already stopped tx dma */
3045	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
3046	ath_hal_txstart(ah, sc->sc_bhalq);
3047}
3048
3049/*
3050 * Reset the hardware after detecting beacons have stopped.
3051 */
3052static void
3053ath_bstuck_proc(void *arg, int pending)
3054{
3055	struct ath_softc *sc = arg;
3056	struct ifnet *ifp = sc->sc_ifp;
3057
3058	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
3059		sc->sc_bmisscount);
3060	sc->sc_stats.ast_bstuck++;
3061	ath_reset(ifp);
3062}
3063
3064/*
3065 * Reclaim beacon resources and return buffer to the pool.
3066 */
3067static void
3068ath_beacon_return(struct ath_softc *sc, struct ath_buf *bf)
3069{
3070
3071	if (bf->bf_m != NULL) {
3072		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3073		m_freem(bf->bf_m);
3074		bf->bf_m = NULL;
3075	}
3076	if (bf->bf_node != NULL) {
3077		ieee80211_free_node(bf->bf_node);
3078		bf->bf_node = NULL;
3079	}
3080	STAILQ_INSERT_TAIL(&sc->sc_bbuf, bf, bf_list);
3081}
3082
3083/*
3084 * Reclaim beacon resources.
3085 */
3086static void
3087ath_beacon_free(struct ath_softc *sc)
3088{
3089	struct ath_buf *bf;
3090
3091	STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
3092		if (bf->bf_m != NULL) {
3093			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3094			m_freem(bf->bf_m);
3095			bf->bf_m = NULL;
3096		}
3097		if (bf->bf_node != NULL) {
3098			ieee80211_free_node(bf->bf_node);
3099			bf->bf_node = NULL;
3100		}
3101	}
3102}
3103
3104/*
3105 * Configure the beacon and sleep timers.
3106 *
3107 * When operating as an AP this resets the TSF and sets
3108 * up the hardware to notify us when we need to issue beacons.
3109 *
3110 * When operating in station mode this sets up the beacon
3111 * timers according to the timestamp of the last received
3112 * beacon and the current TSF, configures PCF and DTIM
3113 * handling, programs the sleep registers so the hardware
3114 * will wakeup in time to receive beacons, and configures
3115 * the beacon miss handling so we'll receive a BMISS
3116 * interrupt when we stop seeing beacons from the AP
3117 * we've associated with.
3118 */
3119static void
3120ath_beacon_config(struct ath_softc *sc, struct ieee80211vap *vap)
3121{
3122#define	TSF_TO_TU(_h,_l) \
3123	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
3124#define	FUDGE	2
3125	struct ath_hal *ah = sc->sc_ah;
3126	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3127	struct ieee80211_node *ni;
3128	u_int32_t nexttbtt, intval, tsftu;
3129	u_int64_t tsf;
3130
3131	if (vap == NULL)
3132		vap = TAILQ_FIRST(&ic->ic_vaps);	/* XXX */
3133	ni = vap->iv_bss;
3134
3135	/* extract tstamp from last beacon and convert to TU */
3136	nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
3137			     LE_READ_4(ni->ni_tstamp.data));
3138	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3139	    ic->ic_opmode == IEEE80211_M_MBSS) {
3140		/*
3141		 * For multi-bss ap/mesh support beacons are either staggered
3142		 * evenly over N slots or burst together.  For the former
3143		 * arrange for the SWBA to be delivered for each slot.
3144		 * Slots that are not occupied will generate nothing.
3145		 */
3146		/* NB: the beacon interval is kept internally in TU's */
3147		intval = ni->ni_intval & HAL_BEACON_PERIOD;
3148		if (sc->sc_stagbeacons)
3149			intval /= ATH_BCBUF;
3150	} else {
3151		/* NB: the beacon interval is kept internally in TU's */
3152		intval = ni->ni_intval & HAL_BEACON_PERIOD;
3153	}
3154	if (nexttbtt == 0)		/* e.g. for ap mode */
3155		nexttbtt = intval;
3156	else if (intval)		/* NB: can be 0 for monitor mode */
3157		nexttbtt = roundup(nexttbtt, intval);
3158	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
3159		__func__, nexttbtt, intval, ni->ni_intval);
3160	if (ic->ic_opmode == IEEE80211_M_STA && !sc->sc_swbmiss) {
3161		HAL_BEACON_STATE bs;
3162		int dtimperiod, dtimcount;
3163		int cfpperiod, cfpcount;
3164
3165		/*
3166		 * Setup dtim and cfp parameters according to
3167		 * last beacon we received (which may be none).
3168		 */
3169		dtimperiod = ni->ni_dtim_period;
3170		if (dtimperiod <= 0)		/* NB: 0 if not known */
3171			dtimperiod = 1;
3172		dtimcount = ni->ni_dtim_count;
3173		if (dtimcount >= dtimperiod)	/* NB: sanity check */
3174			dtimcount = 0;		/* XXX? */
3175		cfpperiod = 1;			/* NB: no PCF support yet */
3176		cfpcount = 0;
3177		/*
3178		 * Pull nexttbtt forward to reflect the current
3179		 * TSF and calculate dtim+cfp state for the result.
3180		 */
3181		tsf = ath_hal_gettsf64(ah);
3182		tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3183		do {
3184			nexttbtt += intval;
3185			if (--dtimcount < 0) {
3186				dtimcount = dtimperiod - 1;
3187				if (--cfpcount < 0)
3188					cfpcount = cfpperiod - 1;
3189			}
3190		} while (nexttbtt < tsftu);
3191		memset(&bs, 0, sizeof(bs));
3192		bs.bs_intval = intval;
3193		bs.bs_nexttbtt = nexttbtt;
3194		bs.bs_dtimperiod = dtimperiod*intval;
3195		bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
3196		bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
3197		bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
3198		bs.bs_cfpmaxduration = 0;
3199#if 0
3200		/*
3201		 * The 802.11 layer records the offset to the DTIM
3202		 * bitmap while receiving beacons; use it here to
3203		 * enable h/w detection of our AID being marked in
3204		 * the bitmap vector (to indicate frames for us are
3205		 * pending at the AP).
3206		 * XXX do DTIM handling in s/w to WAR old h/w bugs
3207		 * XXX enable based on h/w rev for newer chips
3208		 */
3209		bs.bs_timoffset = ni->ni_timoff;
3210#endif
3211		/*
3212		 * Calculate the number of consecutive beacons to miss
3213		 * before taking a BMISS interrupt.
3214		 * Note that we clamp the result to at most 10 beacons.
3215		 */
3216		bs.bs_bmissthreshold = vap->iv_bmissthreshold;
3217		if (bs.bs_bmissthreshold > 10)
3218			bs.bs_bmissthreshold = 10;
3219		else if (bs.bs_bmissthreshold <= 0)
3220			bs.bs_bmissthreshold = 1;
3221
3222		/*
3223		 * Calculate sleep duration.  The configuration is
3224		 * given in ms.  We insure a multiple of the beacon
3225		 * period is used.  Also, if the sleep duration is
3226		 * greater than the DTIM period then it makes senses
3227		 * to make it a multiple of that.
3228		 *
3229		 * XXX fixed at 100ms
3230		 */
3231		bs.bs_sleepduration =
3232			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
3233		if (bs.bs_sleepduration > bs.bs_dtimperiod)
3234			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
3235
3236		DPRINTF(sc, ATH_DEBUG_BEACON,
3237			"%s: tsf %ju tsf:tu %u intval %u nexttbtt %u dtim %u nextdtim %u bmiss %u sleep %u cfp:period %u maxdur %u next %u timoffset %u\n"
3238			, __func__
3239			, tsf, tsftu
3240			, bs.bs_intval
3241			, bs.bs_nexttbtt
3242			, bs.bs_dtimperiod
3243			, bs.bs_nextdtim
3244			, bs.bs_bmissthreshold
3245			, bs.bs_sleepduration
3246			, bs.bs_cfpperiod
3247			, bs.bs_cfpmaxduration
3248			, bs.bs_cfpnext
3249			, bs.bs_timoffset
3250		);
3251		ath_hal_intrset(ah, 0);
3252		ath_hal_beacontimers(ah, &bs);
3253		sc->sc_imask |= HAL_INT_BMISS;
3254		ath_hal_intrset(ah, sc->sc_imask);
3255	} else {
3256		ath_hal_intrset(ah, 0);
3257		if (nexttbtt == intval)
3258			intval |= HAL_BEACON_RESET_TSF;
3259		if (ic->ic_opmode == IEEE80211_M_IBSS) {
3260			/*
3261			 * In IBSS mode enable the beacon timers but only
3262			 * enable SWBA interrupts if we need to manually
3263			 * prepare beacon frames.  Otherwise we use a
3264			 * self-linked tx descriptor and let the hardware
3265			 * deal with things.
3266			 */
3267			intval |= HAL_BEACON_ENA;
3268			if (!sc->sc_hasveol)
3269				sc->sc_imask |= HAL_INT_SWBA;
3270			if ((intval & HAL_BEACON_RESET_TSF) == 0) {
3271				/*
3272				 * Pull nexttbtt forward to reflect
3273				 * the current TSF.
3274				 */
3275				tsf = ath_hal_gettsf64(ah);
3276				tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3277				do {
3278					nexttbtt += intval;
3279				} while (nexttbtt < tsftu);
3280			}
3281			ath_beaconq_config(sc);
3282		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3283		    ic->ic_opmode == IEEE80211_M_MBSS) {
3284			/*
3285			 * In AP/mesh mode we enable the beacon timers
3286			 * and SWBA interrupts to prepare beacon frames.
3287			 */
3288			intval |= HAL_BEACON_ENA;
3289			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
3290			ath_beaconq_config(sc);
3291		}
3292		ath_hal_beaconinit(ah, nexttbtt, intval);
3293		sc->sc_bmisscount = 0;
3294		ath_hal_intrset(ah, sc->sc_imask);
3295		/*
3296		 * When using a self-linked beacon descriptor in
3297		 * ibss mode load it once here.
3298		 */
3299		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
3300			ath_beacon_start_adhoc(sc, vap);
3301	}
3302	sc->sc_syncbeacon = 0;
3303#undef FUDGE
3304#undef TSF_TO_TU
3305}
3306
3307static void
3308ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3309{
3310	bus_addr_t *paddr = (bus_addr_t*) arg;
3311	KASSERT(error == 0, ("error %u on bus_dma callback", error));
3312	*paddr = segs->ds_addr;
3313}
3314
3315static int
3316ath_descdma_setup(struct ath_softc *sc,
3317	struct ath_descdma *dd, ath_bufhead *head,
3318	const char *name, int nbuf, int ndesc)
3319{
3320#define	DS2PHYS(_dd, _ds) \
3321	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3322	struct ifnet *ifp = sc->sc_ifp;
3323	struct ath_desc *ds;
3324	struct ath_buf *bf;
3325	int i, bsize, error;
3326
3327	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
3328	    __func__, name, nbuf, ndesc);
3329
3330	dd->dd_name = name;
3331	dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
3332
3333	/*
3334	 * Setup DMA descriptor area.
3335	 */
3336	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
3337		       PAGE_SIZE, 0,		/* alignment, bounds */
3338		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
3339		       BUS_SPACE_MAXADDR,	/* highaddr */
3340		       NULL, NULL,		/* filter, filterarg */
3341		       dd->dd_desc_len,		/* maxsize */
3342		       1,			/* nsegments */
3343		       dd->dd_desc_len,		/* maxsegsize */
3344		       BUS_DMA_ALLOCNOW,	/* flags */
3345		       NULL,			/* lockfunc */
3346		       NULL,			/* lockarg */
3347		       &dd->dd_dmat);
3348	if (error != 0) {
3349		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
3350		return error;
3351	}
3352
3353	/* allocate descriptors */
3354	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
3355	if (error != 0) {
3356		if_printf(ifp, "unable to create dmamap for %s descriptors, "
3357			"error %u\n", dd->dd_name, error);
3358		goto fail0;
3359	}
3360
3361	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
3362				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
3363				 &dd->dd_dmamap);
3364	if (error != 0) {
3365		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
3366			"error %u\n", nbuf * ndesc, dd->dd_name, error);
3367		goto fail1;
3368	}
3369
3370	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
3371				dd->dd_desc, dd->dd_desc_len,
3372				ath_load_cb, &dd->dd_desc_paddr,
3373				BUS_DMA_NOWAIT);
3374	if (error != 0) {
3375		if_printf(ifp, "unable to map %s descriptors, error %u\n",
3376			dd->dd_name, error);
3377		goto fail2;
3378	}
3379
3380	ds = dd->dd_desc;
3381	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
3382	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
3383	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
3384
3385	/* allocate rx buffers */
3386	bsize = sizeof(struct ath_buf) * nbuf;
3387	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
3388	if (bf == NULL) {
3389		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3390			dd->dd_name, bsize);
3391		goto fail3;
3392	}
3393	dd->dd_bufptr = bf;
3394
3395	STAILQ_INIT(head);
3396	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
3397		bf->bf_desc = ds;
3398		bf->bf_daddr = DS2PHYS(dd, ds);
3399		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3400				&bf->bf_dmamap);
3401		if (error != 0) {
3402			if_printf(ifp, "unable to create dmamap for %s "
3403				"buffer %u, error %u\n", dd->dd_name, i, error);
3404			ath_descdma_cleanup(sc, dd, head);
3405			return error;
3406		}
3407		STAILQ_INSERT_TAIL(head, bf, bf_list);
3408	}
3409	return 0;
3410fail3:
3411	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3412fail2:
3413	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3414fail1:
3415	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3416fail0:
3417	bus_dma_tag_destroy(dd->dd_dmat);
3418	memset(dd, 0, sizeof(*dd));
3419	return error;
3420#undef DS2PHYS
3421}
3422
3423static void
3424ath_descdma_cleanup(struct ath_softc *sc,
3425	struct ath_descdma *dd, ath_bufhead *head)
3426{
3427	struct ath_buf *bf;
3428	struct ieee80211_node *ni;
3429
3430	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3431	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3432	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3433	bus_dma_tag_destroy(dd->dd_dmat);
3434
3435	STAILQ_FOREACH(bf, head, bf_list) {
3436		if (bf->bf_m) {
3437			m_freem(bf->bf_m);
3438			bf->bf_m = NULL;
3439		}
3440		if (bf->bf_dmamap != NULL) {
3441			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
3442			bf->bf_dmamap = NULL;
3443		}
3444		ni = bf->bf_node;
3445		bf->bf_node = NULL;
3446		if (ni != NULL) {
3447			/*
3448			 * Reclaim node reference.
3449			 */
3450			ieee80211_free_node(ni);
3451		}
3452	}
3453
3454	STAILQ_INIT(head);
3455	free(dd->dd_bufptr, M_ATHDEV);
3456	memset(dd, 0, sizeof(*dd));
3457}
3458
3459static int
3460ath_desc_alloc(struct ath_softc *sc)
3461{
3462	int error;
3463
3464	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
3465			"rx", ath_rxbuf, 1);
3466	if (error != 0)
3467		return error;
3468
3469	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
3470			"tx", ath_txbuf, ATH_TXDESC);
3471	if (error != 0) {
3472		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3473		return error;
3474	}
3475
3476	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3477			"beacon", ATH_BCBUF, 1);
3478	if (error != 0) {
3479		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3480		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3481		return error;
3482	}
3483	return 0;
3484}
3485
3486static void
3487ath_desc_free(struct ath_softc *sc)
3488{
3489
3490	if (sc->sc_bdma.dd_desc_len != 0)
3491		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3492	if (sc->sc_txdma.dd_desc_len != 0)
3493		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3494	if (sc->sc_rxdma.dd_desc_len != 0)
3495		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3496}
3497
3498static struct ieee80211_node *
3499ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3500{
3501	struct ieee80211com *ic = vap->iv_ic;
3502	struct ath_softc *sc = ic->ic_ifp->if_softc;
3503	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3504	struct ath_node *an;
3505
3506	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
3507	if (an == NULL) {
3508		/* XXX stat+msg */
3509		return NULL;
3510	}
3511	ath_rate_node_init(sc, an);
3512
3513	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
3514	return &an->an_node;
3515}
3516
3517static void
3518ath_node_free(struct ieee80211_node *ni)
3519{
3520	struct ieee80211com *ic = ni->ni_ic;
3521        struct ath_softc *sc = ic->ic_ifp->if_softc;
3522
3523	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3524
3525	ath_rate_node_cleanup(sc, ATH_NODE(ni));
3526	sc->sc_node_free(ni);
3527}
3528
3529static void
3530ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3531{
3532	struct ieee80211com *ic = ni->ni_ic;
3533	struct ath_softc *sc = ic->ic_ifp->if_softc;
3534	struct ath_hal *ah = sc->sc_ah;
3535
3536	*rssi = ic->ic_node_getrssi(ni);
3537	if (ni->ni_chan != IEEE80211_CHAN_ANYC)
3538		*noise = ath_hal_getchannoise(ah, ni->ni_chan);
3539	else
3540		*noise = -95;		/* nominally correct */
3541}
3542
3543static int
3544ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
3545{
3546	struct ath_hal *ah = sc->sc_ah;
3547	int error;
3548	struct mbuf *m;
3549	struct ath_desc *ds;
3550
3551	m = bf->bf_m;
3552	if (m == NULL) {
3553		/*
3554		 * NB: by assigning a page to the rx dma buffer we
3555		 * implicitly satisfy the Atheros requirement that
3556		 * this buffer be cache-line-aligned and sized to be
3557		 * multiple of the cache line size.  Not doing this
3558		 * causes weird stuff to happen (for the 5210 at least).
3559		 */
3560		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
3561		if (m == NULL) {
3562			DPRINTF(sc, ATH_DEBUG_ANY,
3563				"%s: no mbuf/cluster\n", __func__);
3564			sc->sc_stats.ast_rx_nombuf++;
3565			return ENOMEM;
3566		}
3567		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
3568
3569		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
3570					     bf->bf_dmamap, m,
3571					     bf->bf_segs, &bf->bf_nseg,
3572					     BUS_DMA_NOWAIT);
3573		if (error != 0) {
3574			DPRINTF(sc, ATH_DEBUG_ANY,
3575			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
3576			    __func__, error);
3577			sc->sc_stats.ast_rx_busdma++;
3578			m_freem(m);
3579			return error;
3580		}
3581		KASSERT(bf->bf_nseg == 1,
3582			("multi-segment packet; nseg %u", bf->bf_nseg));
3583		bf->bf_m = m;
3584	}
3585	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
3586
3587	/*
3588	 * Setup descriptors.  For receive we always terminate
3589	 * the descriptor list with a self-linked entry so we'll
3590	 * not get overrun under high load (as can happen with a
3591	 * 5212 when ANI processing enables PHY error frames).
3592	 *
3593	 * To insure the last descriptor is self-linked we create
3594	 * each descriptor as self-linked and add it to the end.  As
3595	 * each additional descriptor is added the previous self-linked
3596	 * entry is ``fixed'' naturally.  This should be safe even
3597	 * if DMA is happening.  When processing RX interrupts we
3598	 * never remove/process the last, self-linked, entry on the
3599	 * descriptor list.  This insures the hardware always has
3600	 * someplace to write a new frame.
3601	 */
3602	ds = bf->bf_desc;
3603	ds->ds_link = bf->bf_daddr;	/* link to self */
3604	ds->ds_data = bf->bf_segs[0].ds_addr;
3605	ath_hal_setuprxdesc(ah, ds
3606		, m->m_len		/* buffer size */
3607		, 0
3608	);
3609
3610	if (sc->sc_rxlink != NULL)
3611		*sc->sc_rxlink = bf->bf_daddr;
3612	sc->sc_rxlink = &ds->ds_link;
3613	return 0;
3614}
3615
3616/*
3617 * Extend 15-bit time stamp from rx descriptor to
3618 * a full 64-bit TSF using the specified TSF.
3619 */
3620static __inline u_int64_t
3621ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
3622{
3623	if ((tsf & 0x7fff) < rstamp)
3624		tsf -= 0x8000;
3625	return ((tsf &~ 0x7fff) | rstamp);
3626}
3627
3628/*
3629 * Intercept management frames to collect beacon rssi data
3630 * and to do ibss merges.
3631 */
3632static void
3633ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
3634	int subtype, int rssi, int nf)
3635{
3636	struct ieee80211vap *vap = ni->ni_vap;
3637	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
3638
3639	/*
3640	 * Call up first so subsequent work can use information
3641	 * potentially stored in the node (e.g. for ibss merge).
3642	 */
3643	ATH_VAP(vap)->av_recv_mgmt(ni, m, subtype, rssi, nf);
3644	switch (subtype) {
3645	case IEEE80211_FC0_SUBTYPE_BEACON:
3646		/* update rssi statistics for use by the hal */
3647		ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
3648		if (sc->sc_syncbeacon &&
3649		    ni == vap->iv_bss && vap->iv_state == IEEE80211_S_RUN) {
3650			/*
3651			 * Resync beacon timers using the tsf of the beacon
3652			 * frame we just received.
3653			 */
3654			ath_beacon_config(sc, vap);
3655		}
3656		/* fall thru... */
3657	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
3658		if (vap->iv_opmode == IEEE80211_M_IBSS &&
3659		    vap->iv_state == IEEE80211_S_RUN) {
3660			uint32_t rstamp = sc->sc_lastrs->rs_tstamp;
3661			uint64_t tsf = ath_extend_tsf(rstamp,
3662				ath_hal_gettsf64(sc->sc_ah));
3663			/*
3664			 * Handle ibss merge as needed; check the tsf on the
3665			 * frame before attempting the merge.  The 802.11 spec
3666			 * says the station should change it's bssid to match
3667			 * the oldest station with the same ssid, where oldest
3668			 * is determined by the tsf.  Note that hardware
3669			 * reconfiguration happens through callback to
3670			 * ath_newstate as the state machine will go from
3671			 * RUN -> RUN when this happens.
3672			 */
3673			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
3674				DPRINTF(sc, ATH_DEBUG_STATE,
3675				    "ibss merge, rstamp %u tsf %ju "
3676				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
3677				    (uintmax_t)ni->ni_tstamp.tsf);
3678				(void) ieee80211_ibss_merge(ni);
3679			}
3680		}
3681		break;
3682	}
3683}
3684
3685/*
3686 * Set the default antenna.
3687 */
3688static void
3689ath_setdefantenna(struct ath_softc *sc, u_int antenna)
3690{
3691	struct ath_hal *ah = sc->sc_ah;
3692
3693	/* XXX block beacon interrupts */
3694	ath_hal_setdefantenna(ah, antenna);
3695	if (sc->sc_defant != antenna)
3696		sc->sc_stats.ast_ant_defswitch++;
3697	sc->sc_defant = antenna;
3698	sc->sc_rxotherant = 0;
3699}
3700
3701static void
3702ath_rx_tap(struct ifnet *ifp, struct mbuf *m,
3703	const struct ath_rx_status *rs, u_int64_t tsf, int16_t nf)
3704{
3705#define	CHAN_HT20	htole32(IEEE80211_CHAN_HT20)
3706#define	CHAN_HT40U	htole32(IEEE80211_CHAN_HT40U)
3707#define	CHAN_HT40D	htole32(IEEE80211_CHAN_HT40D)
3708#define	CHAN_HT		(CHAN_HT20|CHAN_HT40U|CHAN_HT40D)
3709	struct ath_softc *sc = ifp->if_softc;
3710	const HAL_RATE_TABLE *rt;
3711	uint8_t rix;
3712
3713	rt = sc->sc_currates;
3714	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3715	rix = rt->rateCodeToIndex[rs->rs_rate];
3716	sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
3717	sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
3718#ifdef AH_SUPPORT_AR5416
3719	sc->sc_rx_th.wr_chan_flags &= ~CHAN_HT;
3720	if (sc->sc_rx_th.wr_rate & IEEE80211_RATE_MCS) {	/* HT rate */
3721		struct ieee80211com *ic = ifp->if_l2com;
3722
3723		if ((rs->rs_flags & HAL_RX_2040) == 0)
3724			sc->sc_rx_th.wr_chan_flags |= CHAN_HT20;
3725		else if (IEEE80211_IS_CHAN_HT40U(ic->ic_curchan))
3726			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40U;
3727		else
3728			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40D;
3729		if ((rs->rs_flags & HAL_RX_GI) == 0)
3730			sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_SHORTGI;
3731	}
3732#endif
3733	sc->sc_rx_th.wr_tsf = htole64(ath_extend_tsf(rs->rs_tstamp, tsf));
3734	if (rs->rs_status & HAL_RXERR_CRC)
3735		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
3736	/* XXX propagate other error flags from descriptor */
3737	sc->sc_rx_th.wr_antnoise = nf;
3738	sc->sc_rx_th.wr_antsignal = nf + rs->rs_rssi;
3739	sc->sc_rx_th.wr_antenna = rs->rs_antenna;
3740#undef CHAN_HT
3741#undef CHAN_HT20
3742#undef CHAN_HT40U
3743#undef CHAN_HT40D
3744}
3745
3746static void
3747ath_handle_micerror(struct ieee80211com *ic,
3748	struct ieee80211_frame *wh, int keyix)
3749{
3750	struct ieee80211_node *ni;
3751
3752	/* XXX recheck MIC to deal w/ chips that lie */
3753	/* XXX discard MIC errors on !data frames */
3754	ni = ieee80211_find_rxnode(ic, (const struct ieee80211_frame_min *) wh);
3755	if (ni != NULL) {
3756		ieee80211_notify_michael_failure(ni->ni_vap, wh, keyix);
3757		ieee80211_free_node(ni);
3758	}
3759}
3760
3761static void
3762ath_rx_proc(void *arg, int npending)
3763{
3764#define	PA2DESC(_sc, _pa) \
3765	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
3766		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
3767	struct ath_softc *sc = arg;
3768	struct ath_buf *bf;
3769	struct ifnet *ifp = sc->sc_ifp;
3770	struct ieee80211com *ic = ifp->if_l2com;
3771	struct ath_hal *ah = sc->sc_ah;
3772	struct ath_desc *ds;
3773	struct ath_rx_status *rs;
3774	struct mbuf *m;
3775	struct ieee80211_node *ni;
3776	int len, type, ngood;
3777	u_int phyerr;
3778	HAL_STATUS status;
3779	int16_t nf;
3780	u_int64_t tsf;
3781
3782	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
3783	ngood = 0;
3784	nf = ath_hal_getchannoise(ah, sc->sc_curchan);
3785	sc->sc_stats.ast_rx_noise = nf;
3786	tsf = ath_hal_gettsf64(ah);
3787	do {
3788		bf = STAILQ_FIRST(&sc->sc_rxbuf);
3789		if (bf == NULL) {		/* NB: shouldn't happen */
3790			if_printf(ifp, "%s: no buffer!\n", __func__);
3791			break;
3792		}
3793		m = bf->bf_m;
3794		if (m == NULL) {		/* NB: shouldn't happen */
3795			/*
3796			 * If mbuf allocation failed previously there
3797			 * will be no mbuf; try again to re-populate it.
3798			 */
3799			/* XXX make debug msg */
3800			if_printf(ifp, "%s: no mbuf!\n", __func__);
3801			STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3802			goto rx_next;
3803		}
3804		ds = bf->bf_desc;
3805		if (ds->ds_link == bf->bf_daddr) {
3806			/* NB: never process the self-linked entry at the end */
3807			break;
3808		}
3809		/* XXX sync descriptor memory */
3810		/*
3811		 * Must provide the virtual address of the current
3812		 * descriptor, the physical address, and the virtual
3813		 * address of the next descriptor in the h/w chain.
3814		 * This allows the HAL to look ahead to see if the
3815		 * hardware is done with a descriptor by checking the
3816		 * done bit in the following descriptor and the address
3817		 * of the current descriptor the DMA engine is working
3818		 * on.  All this is necessary because of our use of
3819		 * a self-linked list to avoid rx overruns.
3820		 */
3821		rs = &bf->bf_status.ds_rxstat;
3822		status = ath_hal_rxprocdesc(ah, ds,
3823				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
3824#ifdef ATH_DEBUG
3825		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
3826			ath_printrxbuf(sc, bf, 0, status == HAL_OK);
3827#endif
3828		if (status == HAL_EINPROGRESS)
3829			break;
3830		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3831		if (rs->rs_status != 0) {
3832			if (rs->rs_status & HAL_RXERR_CRC)
3833				sc->sc_stats.ast_rx_crcerr++;
3834			if (rs->rs_status & HAL_RXERR_FIFO)
3835				sc->sc_stats.ast_rx_fifoerr++;
3836			if (rs->rs_status & HAL_RXERR_PHY) {
3837				sc->sc_stats.ast_rx_phyerr++;
3838				phyerr = rs->rs_phyerr & 0x1f;
3839				sc->sc_stats.ast_rx_phy[phyerr]++;
3840				goto rx_error;	/* NB: don't count in ierrors */
3841			}
3842			if (rs->rs_status & HAL_RXERR_DECRYPT) {
3843				/*
3844				 * Decrypt error.  If the error occurred
3845				 * because there was no hardware key, then
3846				 * let the frame through so the upper layers
3847				 * can process it.  This is necessary for 5210
3848				 * parts which have no way to setup a ``clear''
3849				 * key cache entry.
3850				 *
3851				 * XXX do key cache faulting
3852				 */
3853				if (rs->rs_keyix == HAL_RXKEYIX_INVALID)
3854					goto rx_accept;
3855				sc->sc_stats.ast_rx_badcrypt++;
3856			}
3857			if (rs->rs_status & HAL_RXERR_MIC) {
3858				sc->sc_stats.ast_rx_badmic++;
3859				/*
3860				 * Do minimal work required to hand off
3861				 * the 802.11 header for notification.
3862				 */
3863				/* XXX frag's and qos frames */
3864				len = rs->rs_datalen;
3865				if (len >= sizeof (struct ieee80211_frame)) {
3866					bus_dmamap_sync(sc->sc_dmat,
3867					    bf->bf_dmamap,
3868					    BUS_DMASYNC_POSTREAD);
3869					ath_handle_micerror(ic,
3870					    mtod(m, struct ieee80211_frame *),
3871					    sc->sc_splitmic ?
3872						rs->rs_keyix-32 : rs->rs_keyix);
3873				}
3874			}
3875			ifp->if_ierrors++;
3876rx_error:
3877			/*
3878			 * Cleanup any pending partial frame.
3879			 */
3880			if (sc->sc_rxpending != NULL) {
3881				m_freem(sc->sc_rxpending);
3882				sc->sc_rxpending = NULL;
3883			}
3884			/*
3885			 * When a tap is present pass error frames
3886			 * that have been requested.  By default we
3887			 * pass decrypt+mic errors but others may be
3888			 * interesting (e.g. crc).
3889			 */
3890			if (ieee80211_radiotap_active(ic) &&
3891			    (rs->rs_status & sc->sc_monpass)) {
3892				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3893				    BUS_DMASYNC_POSTREAD);
3894				/* NB: bpf needs the mbuf length setup */
3895				len = rs->rs_datalen;
3896				m->m_pkthdr.len = m->m_len = len;
3897				ath_rx_tap(ifp, m, rs, tsf, nf);
3898				ieee80211_radiotap_rx_all(ic, m);
3899			}
3900			/* XXX pass MIC errors up for s/w reclaculation */
3901			goto rx_next;
3902		}
3903rx_accept:
3904		/*
3905		 * Sync and unmap the frame.  At this point we're
3906		 * committed to passing the mbuf somewhere so clear
3907		 * bf_m; this means a new mbuf must be allocated
3908		 * when the rx descriptor is setup again to receive
3909		 * another frame.
3910		 */
3911		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3912		    BUS_DMASYNC_POSTREAD);
3913		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3914		bf->bf_m = NULL;
3915
3916		len = rs->rs_datalen;
3917		m->m_len = len;
3918
3919		if (rs->rs_more) {
3920			/*
3921			 * Frame spans multiple descriptors; save
3922			 * it for the next completed descriptor, it
3923			 * will be used to construct a jumbogram.
3924			 */
3925			if (sc->sc_rxpending != NULL) {
3926				/* NB: max frame size is currently 2 clusters */
3927				sc->sc_stats.ast_rx_toobig++;
3928				m_freem(sc->sc_rxpending);
3929			}
3930			m->m_pkthdr.rcvif = ifp;
3931			m->m_pkthdr.len = len;
3932			sc->sc_rxpending = m;
3933			goto rx_next;
3934		} else if (sc->sc_rxpending != NULL) {
3935			/*
3936			 * This is the second part of a jumbogram,
3937			 * chain it to the first mbuf, adjust the
3938			 * frame length, and clear the rxpending state.
3939			 */
3940			sc->sc_rxpending->m_next = m;
3941			sc->sc_rxpending->m_pkthdr.len += len;
3942			m = sc->sc_rxpending;
3943			sc->sc_rxpending = NULL;
3944		} else {
3945			/*
3946			 * Normal single-descriptor receive; setup
3947			 * the rcvif and packet length.
3948			 */
3949			m->m_pkthdr.rcvif = ifp;
3950			m->m_pkthdr.len = len;
3951		}
3952
3953		ifp->if_ipackets++;
3954		sc->sc_stats.ast_ant_rx[rs->rs_antenna]++;
3955
3956		/*
3957		 * Populate the rx status block.  When there are bpf
3958		 * listeners we do the additional work to provide
3959		 * complete status.  Otherwise we fill in only the
3960		 * material required by ieee80211_input.  Note that
3961		 * noise setting is filled in above.
3962		 */
3963		if (ieee80211_radiotap_active(ic))
3964			ath_rx_tap(ifp, m, rs, tsf, nf);
3965
3966		/*
3967		 * From this point on we assume the frame is at least
3968		 * as large as ieee80211_frame_min; verify that.
3969		 */
3970		if (len < IEEE80211_MIN_LEN) {
3971			if (!ieee80211_radiotap_active(ic)) {
3972				DPRINTF(sc, ATH_DEBUG_RECV,
3973				    "%s: short packet %d\n", __func__, len);
3974				sc->sc_stats.ast_rx_tooshort++;
3975			} else {
3976				/* NB: in particular this captures ack's */
3977				ieee80211_radiotap_rx_all(ic, m);
3978			}
3979			m_freem(m);
3980			goto rx_next;
3981		}
3982
3983		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
3984			const HAL_RATE_TABLE *rt = sc->sc_currates;
3985			uint8_t rix = rt->rateCodeToIndex[rs->rs_rate];
3986
3987			ieee80211_dump_pkt(ic, mtod(m, caddr_t), len,
3988			    sc->sc_hwmap[rix].ieeerate, rs->rs_rssi);
3989		}
3990
3991		m_adj(m, -IEEE80211_CRC_LEN);
3992
3993		/*
3994		 * Locate the node for sender, track state, and then
3995		 * pass the (referenced) node up to the 802.11 layer
3996		 * for its use.
3997		 */
3998		ni = ieee80211_find_rxnode_withkey(ic,
3999			mtod(m, const struct ieee80211_frame_min *),
4000			rs->rs_keyix == HAL_RXKEYIX_INVALID ?
4001				IEEE80211_KEYIX_NONE : rs->rs_keyix);
4002		sc->sc_lastrs = rs;
4003		if (ni != NULL) {
4004			/*
4005			 * Sending station is known, dispatch directly.
4006			 */
4007			type = ieee80211_input(ni, m, rs->rs_rssi, nf);
4008			ieee80211_free_node(ni);
4009			/*
4010			 * Arrange to update the last rx timestamp only for
4011			 * frames from our ap when operating in station mode.
4012			 * This assumes the rx key is always setup when
4013			 * associated.
4014			 */
4015			if (ic->ic_opmode == IEEE80211_M_STA &&
4016			    rs->rs_keyix != HAL_RXKEYIX_INVALID)
4017				ngood++;
4018		} else {
4019			type = ieee80211_input_all(ic, m, rs->rs_rssi, nf);
4020		}
4021		/*
4022		 * Track rx rssi and do any rx antenna management.
4023		 */
4024		ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, rs->rs_rssi);
4025		if (sc->sc_diversity) {
4026			/*
4027			 * When using fast diversity, change the default rx
4028			 * antenna if diversity chooses the other antenna 3
4029			 * times in a row.
4030			 */
4031			if (sc->sc_defant != rs->rs_antenna) {
4032				if (++sc->sc_rxotherant >= 3)
4033					ath_setdefantenna(sc, rs->rs_antenna);
4034			} else
4035				sc->sc_rxotherant = 0;
4036		}
4037		if (sc->sc_softled) {
4038			/*
4039			 * Blink for any data frame.  Otherwise do a
4040			 * heartbeat-style blink when idle.  The latter
4041			 * is mainly for station mode where we depend on
4042			 * periodic beacon frames to trigger the poll event.
4043			 */
4044			if (type == IEEE80211_FC0_TYPE_DATA) {
4045				const HAL_RATE_TABLE *rt = sc->sc_currates;
4046				ath_led_event(sc,
4047				    rt->rateCodeToIndex[rs->rs_rate]);
4048			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
4049				ath_led_event(sc, 0);
4050		}
4051rx_next:
4052		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
4053	} while (ath_rxbuf_init(sc, bf) == 0);
4054
4055	/* rx signal state monitoring */
4056	ath_hal_rxmonitor(ah, &sc->sc_halstats, sc->sc_curchan);
4057	if (ngood)
4058		sc->sc_lastrx = tsf;
4059
4060	if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0) {
4061#ifdef IEEE80211_SUPPORT_SUPERG
4062		ieee80211_ff_age_all(ic, 100);
4063#endif
4064		if (!IFQ_IS_EMPTY(&ifp->if_snd))
4065			ath_start(ifp);
4066	}
4067#undef PA2DESC
4068}
4069
4070static void
4071ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
4072{
4073	txq->axq_qnum = qnum;
4074	txq->axq_ac = 0;
4075	txq->axq_depth = 0;
4076	txq->axq_intrcnt = 0;
4077	txq->axq_link = NULL;
4078	STAILQ_INIT(&txq->axq_q);
4079	ATH_TXQ_LOCK_INIT(sc, txq);
4080}
4081
4082/*
4083 * Setup a h/w transmit queue.
4084 */
4085static struct ath_txq *
4086ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
4087{
4088#define	N(a)	(sizeof(a)/sizeof(a[0]))
4089	struct ath_hal *ah = sc->sc_ah;
4090	HAL_TXQ_INFO qi;
4091	int qnum;
4092
4093	memset(&qi, 0, sizeof(qi));
4094	qi.tqi_subtype = subtype;
4095	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
4096	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
4097	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
4098	/*
4099	 * Enable interrupts only for EOL and DESC conditions.
4100	 * We mark tx descriptors to receive a DESC interrupt
4101	 * when a tx queue gets deep; otherwise waiting for the
4102	 * EOL to reap descriptors.  Note that this is done to
4103	 * reduce interrupt load and this only defers reaping
4104	 * descriptors, never transmitting frames.  Aside from
4105	 * reducing interrupts this also permits more concurrency.
4106	 * The only potential downside is if the tx queue backs
4107	 * up in which case the top half of the kernel may backup
4108	 * due to a lack of tx descriptors.
4109	 */
4110	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
4111	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
4112	if (qnum == -1) {
4113		/*
4114		 * NB: don't print a message, this happens
4115		 * normally on parts with too few tx queues
4116		 */
4117		return NULL;
4118	}
4119	if (qnum >= N(sc->sc_txq)) {
4120		device_printf(sc->sc_dev,
4121			"hal qnum %u out of range, max %zu!\n",
4122			qnum, N(sc->sc_txq));
4123		ath_hal_releasetxqueue(ah, qnum);
4124		return NULL;
4125	}
4126	if (!ATH_TXQ_SETUP(sc, qnum)) {
4127		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
4128		sc->sc_txqsetup |= 1<<qnum;
4129	}
4130	return &sc->sc_txq[qnum];
4131#undef N
4132}
4133
4134/*
4135 * Setup a hardware data transmit queue for the specified
4136 * access control.  The hal may not support all requested
4137 * queues in which case it will return a reference to a
4138 * previously setup queue.  We record the mapping from ac's
4139 * to h/w queues for use by ath_tx_start and also track
4140 * the set of h/w queues being used to optimize work in the
4141 * transmit interrupt handler and related routines.
4142 */
4143static int
4144ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
4145{
4146#define	N(a)	(sizeof(a)/sizeof(a[0]))
4147	struct ath_txq *txq;
4148
4149	if (ac >= N(sc->sc_ac2q)) {
4150		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
4151			ac, N(sc->sc_ac2q));
4152		return 0;
4153	}
4154	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
4155	if (txq != NULL) {
4156		txq->axq_ac = ac;
4157		sc->sc_ac2q[ac] = txq;
4158		return 1;
4159	} else
4160		return 0;
4161#undef N
4162}
4163
4164/*
4165 * Update WME parameters for a transmit queue.
4166 */
4167static int
4168ath_txq_update(struct ath_softc *sc, int ac)
4169{
4170#define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
4171#define	ATH_TXOP_TO_US(v)		(v<<5)
4172	struct ifnet *ifp = sc->sc_ifp;
4173	struct ieee80211com *ic = ifp->if_l2com;
4174	struct ath_txq *txq = sc->sc_ac2q[ac];
4175	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
4176	struct ath_hal *ah = sc->sc_ah;
4177	HAL_TXQ_INFO qi;
4178
4179	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
4180#ifdef IEEE80211_SUPPORT_TDMA
4181	if (sc->sc_tdma) {
4182		/*
4183		 * AIFS is zero so there's no pre-transmit wait.  The
4184		 * burst time defines the slot duration and is configured
4185		 * through net80211.  The QCU is setup to not do post-xmit
4186		 * back off, lockout all lower-priority QCU's, and fire
4187		 * off the DMA beacon alert timer which is setup based
4188		 * on the slot configuration.
4189		 */
4190		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4191			      | HAL_TXQ_TXERRINT_ENABLE
4192			      | HAL_TXQ_TXURNINT_ENABLE
4193			      | HAL_TXQ_TXEOLINT_ENABLE
4194			      | HAL_TXQ_DBA_GATED
4195			      | HAL_TXQ_BACKOFF_DISABLE
4196			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
4197			      ;
4198		qi.tqi_aifs = 0;
4199		/* XXX +dbaprep? */
4200		qi.tqi_readyTime = sc->sc_tdmaslotlen;
4201		qi.tqi_burstTime = qi.tqi_readyTime;
4202	} else {
4203#endif
4204		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4205			      | HAL_TXQ_TXERRINT_ENABLE
4206			      | HAL_TXQ_TXDESCINT_ENABLE
4207			      | HAL_TXQ_TXURNINT_ENABLE
4208			      ;
4209		qi.tqi_aifs = wmep->wmep_aifsn;
4210		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
4211		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
4212		qi.tqi_readyTime = 0;
4213		qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
4214#ifdef IEEE80211_SUPPORT_TDMA
4215	}
4216#endif
4217
4218	DPRINTF(sc, ATH_DEBUG_RESET,
4219	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
4220	    __func__, txq->axq_qnum, qi.tqi_qflags,
4221	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
4222
4223	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
4224		if_printf(ifp, "unable to update hardware queue "
4225			"parameters for %s traffic!\n",
4226			ieee80211_wme_acnames[ac]);
4227		return 0;
4228	} else {
4229		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
4230		return 1;
4231	}
4232#undef ATH_TXOP_TO_US
4233#undef ATH_EXPONENT_TO_VALUE
4234}
4235
4236/*
4237 * Callback from the 802.11 layer to update WME parameters.
4238 */
4239static int
4240ath_wme_update(struct ieee80211com *ic)
4241{
4242	struct ath_softc *sc = ic->ic_ifp->if_softc;
4243
4244	return !ath_txq_update(sc, WME_AC_BE) ||
4245	    !ath_txq_update(sc, WME_AC_BK) ||
4246	    !ath_txq_update(sc, WME_AC_VI) ||
4247	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
4248}
4249
4250/*
4251 * Reclaim resources for a setup queue.
4252 */
4253static void
4254ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
4255{
4256
4257	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
4258	ATH_TXQ_LOCK_DESTROY(txq);
4259	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
4260}
4261
4262/*
4263 * Reclaim all tx queue resources.
4264 */
4265static void
4266ath_tx_cleanup(struct ath_softc *sc)
4267{
4268	int i;
4269
4270	ATH_TXBUF_LOCK_DESTROY(sc);
4271	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4272		if (ATH_TXQ_SETUP(sc, i))
4273			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
4274}
4275
4276/*
4277 * Return h/w rate index for an IEEE rate (w/o basic rate bit)
4278 * using the current rates in sc_rixmap.
4279 */
4280static __inline int
4281ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
4282{
4283	int rix = sc->sc_rixmap[rate];
4284	/* NB: return lowest rix for invalid rate */
4285	return (rix == 0xff ? 0 : rix);
4286}
4287
4288/*
4289 * Reclaim mbuf resources.  For fragmented frames we
4290 * need to claim each frag chained with m_nextpkt.
4291 */
4292static void
4293ath_freetx(struct mbuf *m)
4294{
4295	struct mbuf *next;
4296
4297	do {
4298		next = m->m_nextpkt;
4299		m->m_nextpkt = NULL;
4300		m_freem(m);
4301	} while ((m = next) != NULL);
4302}
4303
4304static int
4305ath_tx_dmasetup(struct ath_softc *sc, struct ath_buf *bf, struct mbuf *m0)
4306{
4307	struct mbuf *m;
4308	int error;
4309
4310	/*
4311	 * Load the DMA map so any coalescing is done.  This
4312	 * also calculates the number of descriptors we need.
4313	 */
4314	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
4315				     bf->bf_segs, &bf->bf_nseg,
4316				     BUS_DMA_NOWAIT);
4317	if (error == EFBIG) {
4318		/* XXX packet requires too many descriptors */
4319		bf->bf_nseg = ATH_TXDESC+1;
4320	} else if (error != 0) {
4321		sc->sc_stats.ast_tx_busdma++;
4322		ath_freetx(m0);
4323		return error;
4324	}
4325	/*
4326	 * Discard null packets and check for packets that
4327	 * require too many TX descriptors.  We try to convert
4328	 * the latter to a cluster.
4329	 */
4330	if (bf->bf_nseg > ATH_TXDESC) {		/* too many desc's, linearize */
4331		sc->sc_stats.ast_tx_linear++;
4332		m = m_collapse(m0, M_DONTWAIT, ATH_TXDESC);
4333		if (m == NULL) {
4334			ath_freetx(m0);
4335			sc->sc_stats.ast_tx_nombuf++;
4336			return ENOMEM;
4337		}
4338		m0 = m;
4339		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
4340					     bf->bf_segs, &bf->bf_nseg,
4341					     BUS_DMA_NOWAIT);
4342		if (error != 0) {
4343			sc->sc_stats.ast_tx_busdma++;
4344			ath_freetx(m0);
4345			return error;
4346		}
4347		KASSERT(bf->bf_nseg <= ATH_TXDESC,
4348		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
4349	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
4350		sc->sc_stats.ast_tx_nodata++;
4351		ath_freetx(m0);
4352		return EIO;
4353	}
4354	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n",
4355		__func__, m0, m0->m_pkthdr.len);
4356	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
4357	bf->bf_m = m0;
4358
4359	return 0;
4360}
4361
4362static void
4363ath_tx_handoff(struct ath_softc *sc, struct ath_txq *txq, struct ath_buf *bf)
4364{
4365	struct ath_hal *ah = sc->sc_ah;
4366	struct ath_desc *ds, *ds0;
4367	int i;
4368
4369	/*
4370	 * Fillin the remainder of the descriptor info.
4371	 */
4372	ds0 = ds = bf->bf_desc;
4373	for (i = 0; i < bf->bf_nseg; i++, ds++) {
4374		ds->ds_data = bf->bf_segs[i].ds_addr;
4375		if (i == bf->bf_nseg - 1)
4376			ds->ds_link = 0;
4377		else
4378			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
4379		ath_hal_filltxdesc(ah, ds
4380			, bf->bf_segs[i].ds_len	/* segment length */
4381			, i == 0		/* first segment */
4382			, i == bf->bf_nseg - 1	/* last segment */
4383			, ds0			/* first descriptor */
4384		);
4385		DPRINTF(sc, ATH_DEBUG_XMIT,
4386			"%s: %d: %08x %08x %08x %08x %08x %08x\n",
4387			__func__, i, ds->ds_link, ds->ds_data,
4388			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
4389	}
4390	/*
4391	 * Insert the frame on the outbound list and pass it on
4392	 * to the hardware.  Multicast frames buffered for power
4393	 * save stations and transmit from the CAB queue are stored
4394	 * on a s/w only queue and loaded on to the CAB queue in
4395	 * the SWBA handler since frames only go out on DTIM and
4396	 * to avoid possible races.
4397	 */
4398	ATH_TXQ_LOCK(txq);
4399	KASSERT((bf->bf_flags & ATH_BUF_BUSY) == 0,
4400	     ("busy status 0x%x", bf->bf_flags));
4401	if (txq->axq_qnum != ATH_TXQ_SWQ) {
4402#ifdef IEEE80211_SUPPORT_TDMA
4403		int qbusy;
4404
4405		ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4406		qbusy = ath_hal_txqenabled(ah, txq->axq_qnum);
4407		if (txq->axq_link == NULL) {
4408			/*
4409			 * Be careful writing the address to TXDP.  If
4410			 * the tx q is enabled then this write will be
4411			 * ignored.  Normally this is not an issue but
4412			 * when tdma is in use and the q is beacon gated
4413			 * this race can occur.  If the q is busy then
4414			 * defer the work to later--either when another
4415			 * packet comes along or when we prepare a beacon
4416			 * frame at SWBA.
4417			 */
4418			if (!qbusy) {
4419				ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
4420				txq->axq_flags &= ~ATH_TXQ_PUTPENDING;
4421				DPRINTF(sc, ATH_DEBUG_XMIT,
4422				    "%s: TXDP[%u] = %p (%p) depth %d\n",
4423				    __func__, txq->axq_qnum,
4424				    (caddr_t)bf->bf_daddr, bf->bf_desc,
4425				    txq->axq_depth);
4426			} else {
4427				txq->axq_flags |= ATH_TXQ_PUTPENDING;
4428				DPRINTF(sc, ATH_DEBUG_TDMA | ATH_DEBUG_XMIT,
4429				    "%s: Q%u busy, defer enable\n", __func__,
4430				    txq->axq_qnum);
4431			}
4432		} else {
4433			*txq->axq_link = bf->bf_daddr;
4434			DPRINTF(sc, ATH_DEBUG_XMIT,
4435			    "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
4436			    txq->axq_qnum, txq->axq_link,
4437			    (caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
4438			if ((txq->axq_flags & ATH_TXQ_PUTPENDING) && !qbusy) {
4439				/*
4440				 * The q was busy when we previously tried
4441				 * to write the address of the first buffer
4442				 * in the chain.  Since it's not busy now
4443				 * handle this chore.  We are certain the
4444				 * buffer at the front is the right one since
4445				 * axq_link is NULL only when the buffer list
4446				 * is/was empty.
4447				 */
4448				ath_hal_puttxbuf(ah, txq->axq_qnum,
4449					STAILQ_FIRST(&txq->axq_q)->bf_daddr);
4450				txq->axq_flags &= ~ATH_TXQ_PUTPENDING;
4451				DPRINTF(sc, ATH_DEBUG_TDMA | ATH_DEBUG_XMIT,
4452				    "%s: Q%u restarted\n", __func__,
4453				    txq->axq_qnum);
4454			}
4455		}
4456#else
4457		ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4458		if (txq->axq_link == NULL) {
4459			ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
4460			DPRINTF(sc, ATH_DEBUG_XMIT,
4461			    "%s: TXDP[%u] = %p (%p) depth %d\n",
4462			    __func__, txq->axq_qnum,
4463			    (caddr_t)bf->bf_daddr, bf->bf_desc,
4464			    txq->axq_depth);
4465		} else {
4466			*txq->axq_link = bf->bf_daddr;
4467			DPRINTF(sc, ATH_DEBUG_XMIT,
4468			    "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
4469			    txq->axq_qnum, txq->axq_link,
4470			    (caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
4471		}
4472#endif /* IEEE80211_SUPPORT_TDMA */
4473		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
4474		ath_hal_txstart(ah, txq->axq_qnum);
4475	} else {
4476		if (txq->axq_link != NULL) {
4477			struct ath_buf *last = ATH_TXQ_LAST(txq);
4478			struct ieee80211_frame *wh;
4479
4480			/* mark previous frame */
4481			wh = mtod(last->bf_m, struct ieee80211_frame *);
4482			wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
4483			bus_dmamap_sync(sc->sc_dmat, last->bf_dmamap,
4484			    BUS_DMASYNC_PREWRITE);
4485
4486			/* link descriptor */
4487			*txq->axq_link = bf->bf_daddr;
4488		}
4489		ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4490		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
4491	}
4492	ATH_TXQ_UNLOCK(txq);
4493}
4494
4495static int
4496ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
4497    struct mbuf *m0)
4498{
4499	struct ieee80211vap *vap = ni->ni_vap;
4500	struct ath_vap *avp = ATH_VAP(vap);
4501	struct ath_hal *ah = sc->sc_ah;
4502	struct ifnet *ifp = sc->sc_ifp;
4503	struct ieee80211com *ic = ifp->if_l2com;
4504	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
4505	int error, iswep, ismcast, isfrag, ismrr;
4506	int keyix, hdrlen, pktlen, try0;
4507	u_int8_t rix, txrate, ctsrate;
4508	u_int8_t cix = 0xff;		/* NB: silence compiler */
4509	struct ath_desc *ds;
4510	struct ath_txq *txq;
4511	struct ieee80211_frame *wh;
4512	u_int subtype, flags, ctsduration;
4513	HAL_PKT_TYPE atype;
4514	const HAL_RATE_TABLE *rt;
4515	HAL_BOOL shortPreamble;
4516	struct ath_node *an;
4517	u_int pri;
4518
4519	wh = mtod(m0, struct ieee80211_frame *);
4520	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
4521	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
4522	isfrag = m0->m_flags & M_FRAG;
4523	hdrlen = ieee80211_anyhdrsize(wh);
4524	/*
4525	 * Packet length must not include any
4526	 * pad bytes; deduct them here.
4527	 */
4528	pktlen = m0->m_pkthdr.len - (hdrlen & 3);
4529
4530	if (iswep) {
4531		const struct ieee80211_cipher *cip;
4532		struct ieee80211_key *k;
4533
4534		/*
4535		 * Construct the 802.11 header+trailer for an encrypted
4536		 * frame. The only reason this can fail is because of an
4537		 * unknown or unsupported cipher/key type.
4538		 */
4539		k = ieee80211_crypto_encap(ni, m0);
4540		if (k == NULL) {
4541			/*
4542			 * This can happen when the key is yanked after the
4543			 * frame was queued.  Just discard the frame; the
4544			 * 802.11 layer counts failures and provides
4545			 * debugging/diagnostics.
4546			 */
4547			ath_freetx(m0);
4548			return EIO;
4549		}
4550		/*
4551		 * Adjust the packet + header lengths for the crypto
4552		 * additions and calculate the h/w key index.  When
4553		 * a s/w mic is done the frame will have had any mic
4554		 * added to it prior to entry so m0->m_pkthdr.len will
4555		 * account for it. Otherwise we need to add it to the
4556		 * packet length.
4557		 */
4558		cip = k->wk_cipher;
4559		hdrlen += cip->ic_header;
4560		pktlen += cip->ic_header + cip->ic_trailer;
4561		/* NB: frags always have any TKIP MIC done in s/w */
4562		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && !isfrag)
4563			pktlen += cip->ic_miclen;
4564		keyix = k->wk_keyix;
4565
4566		/* packet header may have moved, reset our local pointer */
4567		wh = mtod(m0, struct ieee80211_frame *);
4568	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
4569		/*
4570		 * Use station key cache slot, if assigned.
4571		 */
4572		keyix = ni->ni_ucastkey.wk_keyix;
4573		if (keyix == IEEE80211_KEYIX_NONE)
4574			keyix = HAL_TXKEYIX_INVALID;
4575	} else
4576		keyix = HAL_TXKEYIX_INVALID;
4577
4578	pktlen += IEEE80211_CRC_LEN;
4579
4580	/*
4581	 * Load the DMA map so any coalescing is done.  This
4582	 * also calculates the number of descriptors we need.
4583	 */
4584	error = ath_tx_dmasetup(sc, bf, m0);
4585	if (error != 0)
4586		return error;
4587	bf->bf_node = ni;			/* NB: held reference */
4588	m0 = bf->bf_m;				/* NB: may have changed */
4589	wh = mtod(m0, struct ieee80211_frame *);
4590
4591	/* setup descriptors */
4592	ds = bf->bf_desc;
4593	rt = sc->sc_currates;
4594	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
4595
4596	/*
4597	 * NB: the 802.11 layer marks whether or not we should
4598	 * use short preamble based on the current mode and
4599	 * negotiated parameters.
4600	 */
4601	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
4602	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
4603		shortPreamble = AH_TRUE;
4604		sc->sc_stats.ast_tx_shortpre++;
4605	} else {
4606		shortPreamble = AH_FALSE;
4607	}
4608
4609	an = ATH_NODE(ni);
4610	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
4611	ismrr = 0;				/* default no multi-rate retry*/
4612	pri = M_WME_GETAC(m0);			/* honor classification */
4613	/* XXX use txparams instead of fixed values */
4614	/*
4615	 * Calculate Atheros packet type from IEEE80211 packet header,
4616	 * setup for rate calculations, and select h/w transmit queue.
4617	 */
4618	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
4619	case IEEE80211_FC0_TYPE_MGT:
4620		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
4621		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
4622			atype = HAL_PKT_TYPE_BEACON;
4623		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
4624			atype = HAL_PKT_TYPE_PROBE_RESP;
4625		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
4626			atype = HAL_PKT_TYPE_ATIM;
4627		else
4628			atype = HAL_PKT_TYPE_NORMAL;	/* XXX */
4629		rix = an->an_mgmtrix;
4630		txrate = rt->info[rix].rateCode;
4631		if (shortPreamble)
4632			txrate |= rt->info[rix].shortPreamble;
4633		try0 = ATH_TXMGTTRY;
4634		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
4635		break;
4636	case IEEE80211_FC0_TYPE_CTL:
4637		atype = HAL_PKT_TYPE_PSPOLL;	/* stop setting of duration */
4638		rix = an->an_mgmtrix;
4639		txrate = rt->info[rix].rateCode;
4640		if (shortPreamble)
4641			txrate |= rt->info[rix].shortPreamble;
4642		try0 = ATH_TXMGTTRY;
4643		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
4644		break;
4645	case IEEE80211_FC0_TYPE_DATA:
4646		atype = HAL_PKT_TYPE_NORMAL;		/* default */
4647		/*
4648		 * Data frames: multicast frames go out at a fixed rate,
4649		 * EAPOL frames use the mgmt frame rate; otherwise consult
4650		 * the rate control module for the rate to use.
4651		 */
4652		if (ismcast) {
4653			rix = an->an_mcastrix;
4654			txrate = rt->info[rix].rateCode;
4655			if (shortPreamble)
4656				txrate |= rt->info[rix].shortPreamble;
4657			try0 = 1;
4658		} else if (m0->m_flags & M_EAPOL) {
4659			/* XXX? maybe always use long preamble? */
4660			rix = an->an_mgmtrix;
4661			txrate = rt->info[rix].rateCode;
4662			if (shortPreamble)
4663				txrate |= rt->info[rix].shortPreamble;
4664			try0 = ATH_TXMAXTRY;	/* XXX?too many? */
4665		} else {
4666			ath_rate_findrate(sc, an, shortPreamble, pktlen,
4667				&rix, &try0, &txrate);
4668			sc->sc_txrix = rix;		/* for LED blinking */
4669			sc->sc_lastdatarix = rix;	/* for fast frames */
4670			if (try0 != ATH_TXMAXTRY)
4671				ismrr = 1;
4672		}
4673		if (cap->cap_wmeParams[pri].wmep_noackPolicy)
4674			flags |= HAL_TXDESC_NOACK;
4675		break;
4676	default:
4677		if_printf(ifp, "bogus frame type 0x%x (%s)\n",
4678			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
4679		/* XXX statistic */
4680		ath_freetx(m0);
4681		return EIO;
4682	}
4683	txq = sc->sc_ac2q[pri];
4684
4685	/*
4686	 * When servicing one or more stations in power-save mode
4687	 * (or) if there is some mcast data waiting on the mcast
4688	 * queue (to prevent out of order delivery) multicast
4689	 * frames must be buffered until after the beacon.
4690	 */
4691	if (ismcast && (vap->iv_ps_sta || avp->av_mcastq.axq_depth))
4692		txq = &avp->av_mcastq;
4693
4694	/*
4695	 * Calculate miscellaneous flags.
4696	 */
4697	if (ismcast) {
4698		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
4699	} else if (pktlen > vap->iv_rtsthreshold &&
4700	    (ni->ni_ath_flags & IEEE80211_NODE_FF) == 0) {
4701		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
4702		cix = rt->info[rix].controlRate;
4703		sc->sc_stats.ast_tx_rts++;
4704	}
4705	if (flags & HAL_TXDESC_NOACK)		/* NB: avoid double counting */
4706		sc->sc_stats.ast_tx_noack++;
4707#ifdef IEEE80211_SUPPORT_TDMA
4708	if (sc->sc_tdma && (flags & HAL_TXDESC_NOACK) == 0) {
4709		DPRINTF(sc, ATH_DEBUG_TDMA,
4710		    "%s: discard frame, ACK required w/ TDMA\n", __func__);
4711		sc->sc_stats.ast_tdma_ack++;
4712		ath_freetx(m0);
4713		return EIO;
4714	}
4715#endif
4716
4717	/*
4718	 * If 802.11g protection is enabled, determine whether
4719	 * to use RTS/CTS or just CTS.  Note that this is only
4720	 * done for OFDM unicast frames.
4721	 */
4722	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
4723	    rt->info[rix].phy == IEEE80211_T_OFDM &&
4724	    (flags & HAL_TXDESC_NOACK) == 0) {
4725		/* XXX fragments must use CCK rates w/ protection */
4726		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
4727			flags |= HAL_TXDESC_RTSENA;
4728		else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
4729			flags |= HAL_TXDESC_CTSENA;
4730		if (isfrag) {
4731			/*
4732			 * For frags it would be desirable to use the
4733			 * highest CCK rate for RTS/CTS.  But stations
4734			 * farther away may detect it at a lower CCK rate
4735			 * so use the configured protection rate instead
4736			 * (for now).
4737			 */
4738			cix = rt->info[sc->sc_protrix].controlRate;
4739		} else
4740			cix = rt->info[sc->sc_protrix].controlRate;
4741		sc->sc_stats.ast_tx_protect++;
4742	}
4743
4744	/*
4745	 * Calculate duration.  This logically belongs in the 802.11
4746	 * layer but it lacks sufficient information to calculate it.
4747	 */
4748	if ((flags & HAL_TXDESC_NOACK) == 0 &&
4749	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
4750		u_int16_t dur;
4751		if (shortPreamble)
4752			dur = rt->info[rix].spAckDuration;
4753		else
4754			dur = rt->info[rix].lpAckDuration;
4755		if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) {
4756			dur += dur;		/* additional SIFS+ACK */
4757			KASSERT(m0->m_nextpkt != NULL, ("no fragment"));
4758			/*
4759			 * Include the size of next fragment so NAV is
4760			 * updated properly.  The last fragment uses only
4761			 * the ACK duration
4762			 */
4763			dur += ath_hal_computetxtime(ah, rt,
4764					m0->m_nextpkt->m_pkthdr.len,
4765					rix, shortPreamble);
4766		}
4767		if (isfrag) {
4768			/*
4769			 * Force hardware to use computed duration for next
4770			 * fragment by disabling multi-rate retry which updates
4771			 * duration based on the multi-rate duration table.
4772			 */
4773			ismrr = 0;
4774			try0 = ATH_TXMGTTRY;	/* XXX? */
4775		}
4776		*(u_int16_t *)wh->i_dur = htole16(dur);
4777	}
4778
4779	/*
4780	 * Calculate RTS/CTS rate and duration if needed.
4781	 */
4782	ctsduration = 0;
4783	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
4784		/*
4785		 * CTS transmit rate is derived from the transmit rate
4786		 * by looking in the h/w rate table.  We must also factor
4787		 * in whether or not a short preamble is to be used.
4788		 */
4789		/* NB: cix is set above where RTS/CTS is enabled */
4790		KASSERT(cix != 0xff, ("cix not setup"));
4791		ctsrate = rt->info[cix].rateCode;
4792		/*
4793		 * Compute the transmit duration based on the frame
4794		 * size and the size of an ACK frame.  We call into the
4795		 * HAL to do the computation since it depends on the
4796		 * characteristics of the actual PHY being used.
4797		 *
4798		 * NB: CTS is assumed the same size as an ACK so we can
4799		 *     use the precalculated ACK durations.
4800		 */
4801		if (shortPreamble) {
4802			ctsrate |= rt->info[cix].shortPreamble;
4803			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
4804				ctsduration += rt->info[cix].spAckDuration;
4805			ctsduration += ath_hal_computetxtime(ah,
4806				rt, pktlen, rix, AH_TRUE);
4807			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
4808				ctsduration += rt->info[rix].spAckDuration;
4809		} else {
4810			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
4811				ctsduration += rt->info[cix].lpAckDuration;
4812			ctsduration += ath_hal_computetxtime(ah,
4813				rt, pktlen, rix, AH_FALSE);
4814			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
4815				ctsduration += rt->info[rix].lpAckDuration;
4816		}
4817		/*
4818		 * Must disable multi-rate retry when using RTS/CTS.
4819		 */
4820		ismrr = 0;
4821		try0 = ATH_TXMGTTRY;		/* XXX */
4822	} else
4823		ctsrate = 0;
4824
4825	/*
4826	 * At this point we are committed to sending the frame
4827	 * and we don't need to look at m_nextpkt; clear it in
4828	 * case this frame is part of frag chain.
4829	 */
4830	m0->m_nextpkt = NULL;
4831
4832	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
4833		ieee80211_dump_pkt(ic, mtod(m0, const uint8_t *), m0->m_len,
4834		    sc->sc_hwmap[rix].ieeerate, -1);
4835
4836	if (ieee80211_radiotap_active_vap(vap)) {
4837		u_int64_t tsf = ath_hal_gettsf64(ah);
4838
4839		sc->sc_tx_th.wt_tsf = htole64(tsf);
4840		sc->sc_tx_th.wt_flags = sc->sc_hwmap[rix].txflags;
4841		if (iswep)
4842			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
4843		if (isfrag)
4844			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
4845		sc->sc_tx_th.wt_rate = sc->sc_hwmap[rix].ieeerate;
4846		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
4847		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
4848
4849		ieee80211_radiotap_tx(vap, m0);
4850	}
4851
4852	/*
4853	 * Determine if a tx interrupt should be generated for
4854	 * this descriptor.  We take a tx interrupt to reap
4855	 * descriptors when the h/w hits an EOL condition or
4856	 * when the descriptor is specifically marked to generate
4857	 * an interrupt.  We periodically mark descriptors in this
4858	 * way to insure timely replenishing of the supply needed
4859	 * for sending frames.  Defering interrupts reduces system
4860	 * load and potentially allows more concurrent work to be
4861	 * done but if done to aggressively can cause senders to
4862	 * backup.
4863	 *
4864	 * NB: use >= to deal with sc_txintrperiod changing
4865	 *     dynamically through sysctl.
4866	 */
4867	if (flags & HAL_TXDESC_INTREQ) {
4868		txq->axq_intrcnt = 0;
4869	} else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
4870		flags |= HAL_TXDESC_INTREQ;
4871		txq->axq_intrcnt = 0;
4872	}
4873
4874	/*
4875	 * Formulate first tx descriptor with tx controls.
4876	 */
4877	/* XXX check return value? */
4878	ath_hal_setuptxdesc(ah, ds
4879		, pktlen		/* packet length */
4880		, hdrlen		/* header length */
4881		, atype			/* Atheros packet type */
4882		, ni->ni_txpower	/* txpower */
4883		, txrate, try0		/* series 0 rate/tries */
4884		, keyix			/* key cache index */
4885		, sc->sc_txantenna	/* antenna mode */
4886		, flags			/* flags */
4887		, ctsrate		/* rts/cts rate */
4888		, ctsduration		/* rts/cts duration */
4889	);
4890	bf->bf_txflags = flags;
4891	/*
4892	 * Setup the multi-rate retry state only when we're
4893	 * going to use it.  This assumes ath_hal_setuptxdesc
4894	 * initializes the descriptors (so we don't have to)
4895	 * when the hardware supports multi-rate retry and
4896	 * we don't use it.
4897	 */
4898	if (ismrr)
4899		ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
4900
4901	ath_tx_handoff(sc, txq, bf);
4902	return 0;
4903}
4904
4905/*
4906 * Process completed xmit descriptors from the specified queue.
4907 */
4908static int
4909ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
4910{
4911	struct ath_hal *ah = sc->sc_ah;
4912	struct ifnet *ifp = sc->sc_ifp;
4913	struct ieee80211com *ic = ifp->if_l2com;
4914	struct ath_buf *bf, *last;
4915	struct ath_desc *ds, *ds0;
4916	struct ath_tx_status *ts;
4917	struct ieee80211_node *ni;
4918	struct ath_node *an;
4919	int sr, lr, pri, nacked;
4920	HAL_STATUS status;
4921
4922	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
4923		__func__, txq->axq_qnum,
4924		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4925		txq->axq_link);
4926	nacked = 0;
4927	for (;;) {
4928		ATH_TXQ_LOCK(txq);
4929		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
4930		bf = STAILQ_FIRST(&txq->axq_q);
4931		if (bf == NULL) {
4932			ATH_TXQ_UNLOCK(txq);
4933			break;
4934		}
4935		ds0 = &bf->bf_desc[0];
4936		ds = &bf->bf_desc[bf->bf_nseg - 1];
4937		ts = &bf->bf_status.ds_txstat;
4938		status = ath_hal_txprocdesc(ah, ds, ts);
4939#ifdef ATH_DEBUG
4940		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
4941			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4942			    status == HAL_OK);
4943#endif
4944		if (status == HAL_EINPROGRESS) {
4945			ATH_TXQ_UNLOCK(txq);
4946			break;
4947		}
4948		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
4949#ifdef IEEE80211_SUPPORT_TDMA
4950		if (txq->axq_depth > 0) {
4951			/*
4952			 * More frames follow.  Mark the buffer busy
4953			 * so it's not re-used while the hardware may
4954			 * still re-read the link field in the descriptor.
4955			 */
4956			bf->bf_flags |= ATH_BUF_BUSY;
4957		} else
4958#else
4959		if (txq->axq_depth == 0)
4960#endif
4961			txq->axq_link = NULL;
4962		ATH_TXQ_UNLOCK(txq);
4963
4964		ni = bf->bf_node;
4965		if (ni != NULL) {
4966			an = ATH_NODE(ni);
4967			if (ts->ts_status == 0) {
4968				u_int8_t txant = ts->ts_antenna;
4969				sc->sc_stats.ast_ant_tx[txant]++;
4970				sc->sc_ant_tx[txant]++;
4971				if (ts->ts_finaltsi != 0)
4972					sc->sc_stats.ast_tx_altrate++;
4973				pri = M_WME_GETAC(bf->bf_m);
4974				if (pri >= WME_AC_VO)
4975					ic->ic_wme.wme_hipri_traffic++;
4976				if ((bf->bf_txflags & HAL_TXDESC_NOACK) == 0)
4977					ni->ni_inact = ni->ni_inact_reload;
4978			} else {
4979				if (ts->ts_status & HAL_TXERR_XRETRY)
4980					sc->sc_stats.ast_tx_xretries++;
4981				if (ts->ts_status & HAL_TXERR_FIFO)
4982					sc->sc_stats.ast_tx_fifoerr++;
4983				if (ts->ts_status & HAL_TXERR_FILT)
4984					sc->sc_stats.ast_tx_filtered++;
4985				if (bf->bf_m->m_flags & M_FF)
4986					sc->sc_stats.ast_ff_txerr++;
4987			}
4988			sr = ts->ts_shortretry;
4989			lr = ts->ts_longretry;
4990			sc->sc_stats.ast_tx_shortretry += sr;
4991			sc->sc_stats.ast_tx_longretry += lr;
4992			/*
4993			 * Hand the descriptor to the rate control algorithm.
4994			 */
4995			if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
4996			    (bf->bf_txflags & HAL_TXDESC_NOACK) == 0) {
4997				/*
4998				 * If frame was ack'd update statistics,
4999				 * including the last rx time used to
5000				 * workaround phantom bmiss interrupts.
5001				 */
5002				if (ts->ts_status == 0) {
5003					nacked++;
5004					sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
5005					ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
5006						ts->ts_rssi);
5007				}
5008				ath_rate_tx_complete(sc, an, bf);
5009			}
5010			/*
5011			 * Do any tx complete callback.  Note this must
5012			 * be done before releasing the node reference.
5013			 */
5014			if (bf->bf_m->m_flags & M_TXCB)
5015				ieee80211_process_callback(ni, bf->bf_m,
5016				    (bf->bf_txflags & HAL_TXDESC_NOACK) == 0 ?
5017				        ts->ts_status : HAL_TXERR_XRETRY);
5018			ieee80211_free_node(ni);
5019		}
5020		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
5021		    BUS_DMASYNC_POSTWRITE);
5022		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5023
5024		m_freem(bf->bf_m);
5025		bf->bf_m = NULL;
5026		bf->bf_node = NULL;
5027
5028		ATH_TXBUF_LOCK(sc);
5029		last = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
5030		if (last != NULL)
5031			last->bf_flags &= ~ATH_BUF_BUSY;
5032		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5033		ATH_TXBUF_UNLOCK(sc);
5034	}
5035#ifdef IEEE80211_SUPPORT_SUPERG
5036	/*
5037	 * Flush fast-frame staging queue when traffic slows.
5038	 */
5039	if (txq->axq_depth <= 1)
5040		ieee80211_ff_flush(ic, txq->axq_ac);
5041#endif
5042	return nacked;
5043}
5044
5045static __inline int
5046txqactive(struct ath_hal *ah, int qnum)
5047{
5048	u_int32_t txqs = 1<<qnum;
5049	ath_hal_gettxintrtxqs(ah, &txqs);
5050	return (txqs & (1<<qnum));
5051}
5052
5053/*
5054 * Deferred processing of transmit interrupt; special-cased
5055 * for a single hardware transmit queue (e.g. 5210 and 5211).
5056 */
5057static void
5058ath_tx_proc_q0(void *arg, int npending)
5059{
5060	struct ath_softc *sc = arg;
5061	struct ifnet *ifp = sc->sc_ifp;
5062
5063	if (txqactive(sc->sc_ah, 0) && ath_tx_processq(sc, &sc->sc_txq[0]))
5064		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5065	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
5066		ath_tx_processq(sc, sc->sc_cabq);
5067	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5068	sc->sc_wd_timer = 0;
5069
5070	if (sc->sc_softled)
5071		ath_led_event(sc, sc->sc_txrix);
5072
5073	ath_start(ifp);
5074}
5075
5076/*
5077 * Deferred processing of transmit interrupt; special-cased
5078 * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
5079 */
5080static void
5081ath_tx_proc_q0123(void *arg, int npending)
5082{
5083	struct ath_softc *sc = arg;
5084	struct ifnet *ifp = sc->sc_ifp;
5085	int nacked;
5086
5087	/*
5088	 * Process each active queue.
5089	 */
5090	nacked = 0;
5091	if (txqactive(sc->sc_ah, 0))
5092		nacked += ath_tx_processq(sc, &sc->sc_txq[0]);
5093	if (txqactive(sc->sc_ah, 1))
5094		nacked += ath_tx_processq(sc, &sc->sc_txq[1]);
5095	if (txqactive(sc->sc_ah, 2))
5096		nacked += ath_tx_processq(sc, &sc->sc_txq[2]);
5097	if (txqactive(sc->sc_ah, 3))
5098		nacked += ath_tx_processq(sc, &sc->sc_txq[3]);
5099	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
5100		ath_tx_processq(sc, sc->sc_cabq);
5101	if (nacked)
5102		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5103
5104	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5105	sc->sc_wd_timer = 0;
5106
5107	if (sc->sc_softled)
5108		ath_led_event(sc, sc->sc_txrix);
5109
5110	ath_start(ifp);
5111}
5112
5113/*
5114 * Deferred processing of transmit interrupt.
5115 */
5116static void
5117ath_tx_proc(void *arg, int npending)
5118{
5119	struct ath_softc *sc = arg;
5120	struct ifnet *ifp = sc->sc_ifp;
5121	int i, nacked;
5122
5123	/*
5124	 * Process each active queue.
5125	 */
5126	nacked = 0;
5127	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5128		if (ATH_TXQ_SETUP(sc, i) && txqactive(sc->sc_ah, i))
5129			nacked += ath_tx_processq(sc, &sc->sc_txq[i]);
5130	if (nacked)
5131		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5132
5133	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5134	sc->sc_wd_timer = 0;
5135
5136	if (sc->sc_softled)
5137		ath_led_event(sc, sc->sc_txrix);
5138
5139	ath_start(ifp);
5140}
5141
5142static void
5143ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
5144{
5145#ifdef ATH_DEBUG
5146	struct ath_hal *ah = sc->sc_ah;
5147#endif
5148	struct ieee80211_node *ni;
5149	struct ath_buf *bf;
5150	u_int ix;
5151
5152	/*
5153	 * NB: this assumes output has been stopped and
5154	 *     we do not need to block ath_tx_proc
5155	 */
5156	ATH_TXBUF_LOCK(sc);
5157	bf = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
5158	if (bf != NULL)
5159		bf->bf_flags &= ~ATH_BUF_BUSY;
5160	ATH_TXBUF_UNLOCK(sc);
5161	for (ix = 0;; ix++) {
5162		ATH_TXQ_LOCK(txq);
5163		bf = STAILQ_FIRST(&txq->axq_q);
5164		if (bf == NULL) {
5165			txq->axq_link = NULL;
5166			ATH_TXQ_UNLOCK(txq);
5167			break;
5168		}
5169		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
5170		ATH_TXQ_UNLOCK(txq);
5171#ifdef ATH_DEBUG
5172		if (sc->sc_debug & ATH_DEBUG_RESET) {
5173			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
5174
5175			ath_printtxbuf(sc, bf, txq->axq_qnum, ix,
5176				ath_hal_txprocdesc(ah, bf->bf_desc,
5177				    &bf->bf_status.ds_txstat) == HAL_OK);
5178			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
5179			    bf->bf_m->m_len, 0, -1);
5180		}
5181#endif /* ATH_DEBUG */
5182		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5183		ni = bf->bf_node;
5184		bf->bf_node = NULL;
5185		if (ni != NULL) {
5186			/*
5187			 * Do any callback and reclaim the node reference.
5188			 */
5189			if (bf->bf_m->m_flags & M_TXCB)
5190				ieee80211_process_callback(ni, bf->bf_m, -1);
5191			ieee80211_free_node(ni);
5192		}
5193		m_freem(bf->bf_m);
5194		bf->bf_m = NULL;
5195		bf->bf_flags &= ~ATH_BUF_BUSY;
5196
5197		ATH_TXBUF_LOCK(sc);
5198		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5199		ATH_TXBUF_UNLOCK(sc);
5200	}
5201}
5202
5203static void
5204ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
5205{
5206	struct ath_hal *ah = sc->sc_ah;
5207
5208	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5209	    __func__, txq->axq_qnum,
5210	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
5211	    txq->axq_link);
5212	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
5213}
5214
5215/*
5216 * Drain the transmit queues and reclaim resources.
5217 */
5218static void
5219ath_draintxq(struct ath_softc *sc)
5220{
5221	struct ath_hal *ah = sc->sc_ah;
5222	struct ifnet *ifp = sc->sc_ifp;
5223	int i;
5224
5225	/* XXX return value */
5226	if (!sc->sc_invalid) {
5227		/* don't touch the hardware if marked invalid */
5228		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5229		    __func__, sc->sc_bhalq,
5230		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
5231		    NULL);
5232		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
5233		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5234			if (ATH_TXQ_SETUP(sc, i))
5235				ath_tx_stopdma(sc, &sc->sc_txq[i]);
5236	}
5237	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5238		if (ATH_TXQ_SETUP(sc, i))
5239			ath_tx_draintxq(sc, &sc->sc_txq[i]);
5240#ifdef ATH_DEBUG
5241	if (sc->sc_debug & ATH_DEBUG_RESET) {
5242		struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
5243		if (bf != NULL && bf->bf_m != NULL) {
5244			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
5245				ath_hal_txprocdesc(ah, bf->bf_desc,
5246				    &bf->bf_status.ds_txstat) == HAL_OK);
5247			ieee80211_dump_pkt(ifp->if_l2com,
5248			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
5249			    0, -1);
5250		}
5251	}
5252#endif /* ATH_DEBUG */
5253	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5254	sc->sc_wd_timer = 0;
5255}
5256
5257/*
5258 * Disable the receive h/w in preparation for a reset.
5259 */
5260static void
5261ath_stoprecv(struct ath_softc *sc)
5262{
5263#define	PA2DESC(_sc, _pa) \
5264	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
5265		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
5266	struct ath_hal *ah = sc->sc_ah;
5267
5268	ath_hal_stoppcurecv(ah);	/* disable PCU */
5269	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
5270	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
5271	DELAY(3000);			/* 3ms is long enough for 1 frame */
5272#ifdef ATH_DEBUG
5273	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
5274		struct ath_buf *bf;
5275		u_int ix;
5276
5277		printf("%s: rx queue %p, link %p\n", __func__,
5278			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
5279		ix = 0;
5280		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
5281			struct ath_desc *ds = bf->bf_desc;
5282			struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
5283			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
5284				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
5285			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
5286				ath_printrxbuf(sc, bf, ix, status == HAL_OK);
5287			ix++;
5288		}
5289	}
5290#endif
5291	if (sc->sc_rxpending != NULL) {
5292		m_freem(sc->sc_rxpending);
5293		sc->sc_rxpending = NULL;
5294	}
5295	sc->sc_rxlink = NULL;		/* just in case */
5296#undef PA2DESC
5297}
5298
5299/*
5300 * Enable the receive h/w following a reset.
5301 */
5302static int
5303ath_startrecv(struct ath_softc *sc)
5304{
5305	struct ath_hal *ah = sc->sc_ah;
5306	struct ath_buf *bf;
5307
5308	sc->sc_rxlink = NULL;
5309	sc->sc_rxpending = NULL;
5310	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
5311		int error = ath_rxbuf_init(sc, bf);
5312		if (error != 0) {
5313			DPRINTF(sc, ATH_DEBUG_RECV,
5314				"%s: ath_rxbuf_init failed %d\n",
5315				__func__, error);
5316			return error;
5317		}
5318	}
5319
5320	bf = STAILQ_FIRST(&sc->sc_rxbuf);
5321	ath_hal_putrxbuf(ah, bf->bf_daddr);
5322	ath_hal_rxena(ah);		/* enable recv descriptors */
5323	ath_mode_init(sc);		/* set filters, etc. */
5324	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
5325	return 0;
5326}
5327
5328/*
5329 * Update internal state after a channel change.
5330 */
5331static void
5332ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
5333{
5334	enum ieee80211_phymode mode;
5335
5336	/*
5337	 * Change channels and update the h/w rate map
5338	 * if we're switching; e.g. 11a to 11b/g.
5339	 */
5340	mode = ieee80211_chan2mode(chan);
5341	if (mode != sc->sc_curmode)
5342		ath_setcurmode(sc, mode);
5343	sc->sc_curchan = chan;
5344}
5345
5346/*
5347 * Set/change channels.  If the channel is really being changed,
5348 * it's done by resetting the chip.  To accomplish this we must
5349 * first cleanup any pending DMA, then restart stuff after a la
5350 * ath_init.
5351 */
5352static int
5353ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
5354{
5355	struct ifnet *ifp = sc->sc_ifp;
5356	struct ieee80211com *ic = ifp->if_l2com;
5357	struct ath_hal *ah = sc->sc_ah;
5358
5359	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
5360	    __func__, ieee80211_chan2ieee(ic, chan),
5361	    chan->ic_freq, chan->ic_flags);
5362	if (chan != sc->sc_curchan) {
5363		HAL_STATUS status;
5364		/*
5365		 * To switch channels clear any pending DMA operations;
5366		 * wait long enough for the RX fifo to drain, reset the
5367		 * hardware at the new frequency, and then re-enable
5368		 * the relevant bits of the h/w.
5369		 */
5370		ath_hal_intrset(ah, 0);		/* disable interrupts */
5371		ath_draintxq(sc);		/* clear pending tx frames */
5372		ath_stoprecv(sc);		/* turn off frame recv */
5373		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
5374			if_printf(ifp, "%s: unable to reset "
5375			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
5376			    __func__, ieee80211_chan2ieee(ic, chan),
5377			    chan->ic_freq, chan->ic_flags, status);
5378			return EIO;
5379		}
5380		sc->sc_diversity = ath_hal_getdiversity(ah);
5381
5382		/*
5383		 * Re-enable rx framework.
5384		 */
5385		if (ath_startrecv(sc) != 0) {
5386			if_printf(ifp, "%s: unable to restart recv logic\n",
5387			    __func__);
5388			return EIO;
5389		}
5390
5391		/*
5392		 * Change channels and update the h/w rate map
5393		 * if we're switching; e.g. 11a to 11b/g.
5394		 */
5395		ath_chan_change(sc, chan);
5396
5397		/*
5398		 * Re-enable interrupts.
5399		 */
5400		ath_hal_intrset(ah, sc->sc_imask);
5401	}
5402	return 0;
5403}
5404
5405/*
5406 * Periodically recalibrate the PHY to account
5407 * for temperature/environment changes.
5408 */
5409static void
5410ath_calibrate(void *arg)
5411{
5412	struct ath_softc *sc = arg;
5413	struct ath_hal *ah = sc->sc_ah;
5414	struct ifnet *ifp = sc->sc_ifp;
5415	struct ieee80211com *ic = ifp->if_l2com;
5416	HAL_BOOL longCal, isCalDone;
5417	int nextcal;
5418
5419	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
5420		goto restart;
5421	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
5422	if (longCal) {
5423		sc->sc_stats.ast_per_cal++;
5424		sc->sc_lastlongcal = ticks;
5425		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
5426			/*
5427			 * Rfgain is out of bounds, reset the chip
5428			 * to load new gain values.
5429			 */
5430			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5431				"%s: rfgain change\n", __func__);
5432			sc->sc_stats.ast_per_rfgain++;
5433			ath_reset(ifp);
5434		}
5435		/*
5436		 * If this long cal is after an idle period, then
5437		 * reset the data collection state so we start fresh.
5438		 */
5439		if (sc->sc_resetcal) {
5440			(void) ath_hal_calreset(ah, sc->sc_curchan);
5441			sc->sc_lastcalreset = ticks;
5442			sc->sc_resetcal = 0;
5443		}
5444	}
5445	if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
5446		if (longCal) {
5447			/*
5448			 * Calibrate noise floor data again in case of change.
5449			 */
5450			ath_hal_process_noisefloor(ah);
5451		}
5452	} else {
5453		DPRINTF(sc, ATH_DEBUG_ANY,
5454			"%s: calibration of channel %u failed\n",
5455			__func__, sc->sc_curchan->ic_freq);
5456		sc->sc_stats.ast_per_calfail++;
5457	}
5458	if (!isCalDone) {
5459restart:
5460		/*
5461		 * Use a shorter interval to potentially collect multiple
5462		 * data samples required to complete calibration.  Once
5463		 * we're told the work is done we drop back to a longer
5464		 * interval between requests.  We're more aggressive doing
5465		 * work when operating as an AP to improve operation right
5466		 * after startup.
5467		 */
5468		nextcal = (1000*ath_shortcalinterval)/hz;
5469		if (sc->sc_opmode != HAL_M_HOSTAP)
5470			nextcal *= 10;
5471	} else {
5472		nextcal = ath_longcalinterval*hz;
5473		if (sc->sc_lastcalreset == 0)
5474			sc->sc_lastcalreset = sc->sc_lastlongcal;
5475		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
5476			sc->sc_resetcal = 1;	/* setup reset next trip */
5477	}
5478
5479	if (nextcal != 0) {
5480		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
5481		    __func__, nextcal, isCalDone ? "" : "!");
5482		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
5483	} else {
5484		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
5485		    __func__);
5486		/* NB: don't rearm timer */
5487	}
5488}
5489
5490static void
5491ath_scan_start(struct ieee80211com *ic)
5492{
5493	struct ifnet *ifp = ic->ic_ifp;
5494	struct ath_softc *sc = ifp->if_softc;
5495	struct ath_hal *ah = sc->sc_ah;
5496	u_int32_t rfilt;
5497
5498	/* XXX calibration timer? */
5499
5500	sc->sc_scanning = 1;
5501	sc->sc_syncbeacon = 0;
5502	rfilt = ath_calcrxfilter(sc);
5503	ath_hal_setrxfilter(ah, rfilt);
5504	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
5505
5506	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
5507		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
5508}
5509
5510static void
5511ath_scan_end(struct ieee80211com *ic)
5512{
5513	struct ifnet *ifp = ic->ic_ifp;
5514	struct ath_softc *sc = ifp->if_softc;
5515	struct ath_hal *ah = sc->sc_ah;
5516	u_int32_t rfilt;
5517
5518	sc->sc_scanning = 0;
5519	rfilt = ath_calcrxfilter(sc);
5520	ath_hal_setrxfilter(ah, rfilt);
5521	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5522
5523	ath_hal_process_noisefloor(ah);
5524
5525	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5526		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
5527		 sc->sc_curaid);
5528}
5529
5530static void
5531ath_set_channel(struct ieee80211com *ic)
5532{
5533	struct ifnet *ifp = ic->ic_ifp;
5534	struct ath_softc *sc = ifp->if_softc;
5535
5536	(void) ath_chan_set(sc, ic->ic_curchan);
5537	/*
5538	 * If we are returning to our bss channel then mark state
5539	 * so the next recv'd beacon's tsf will be used to sync the
5540	 * beacon timers.  Note that since we only hear beacons in
5541	 * sta/ibss mode this has no effect in other operating modes.
5542	 */
5543	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
5544		sc->sc_syncbeacon = 1;
5545}
5546
5547/*
5548 * Walk the vap list and check if there any vap's in RUN state.
5549 */
5550static int
5551ath_isanyrunningvaps(struct ieee80211vap *this)
5552{
5553	struct ieee80211com *ic = this->iv_ic;
5554	struct ieee80211vap *vap;
5555
5556	IEEE80211_LOCK_ASSERT(ic);
5557
5558	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
5559		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
5560			return 1;
5561	}
5562	return 0;
5563}
5564
5565static int
5566ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
5567{
5568	struct ieee80211com *ic = vap->iv_ic;
5569	struct ath_softc *sc = ic->ic_ifp->if_softc;
5570	struct ath_vap *avp = ATH_VAP(vap);
5571	struct ath_hal *ah = sc->sc_ah;
5572	struct ieee80211_node *ni = NULL;
5573	int i, error, stamode;
5574	u_int32_t rfilt;
5575	static const HAL_LED_STATE leds[] = {
5576	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
5577	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
5578	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
5579	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
5580	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
5581	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
5582	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
5583	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
5584	};
5585
5586	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
5587		ieee80211_state_name[vap->iv_state],
5588		ieee80211_state_name[nstate]);
5589
5590	callout_drain(&sc->sc_cal_ch);
5591	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
5592
5593	if (nstate == IEEE80211_S_SCAN) {
5594		/*
5595		 * Scanning: turn off beacon miss and don't beacon.
5596		 * Mark beacon state so when we reach RUN state we'll
5597		 * [re]setup beacons.  Unblock the task q thread so
5598		 * deferred interrupt processing is done.
5599		 */
5600		ath_hal_intrset(ah,
5601		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
5602		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5603		sc->sc_beacons = 0;
5604		taskqueue_unblock(sc->sc_tq);
5605	}
5606
5607	ni = vap->iv_bss;
5608	rfilt = ath_calcrxfilter(sc);
5609	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
5610		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
5611		   vap->iv_opmode == IEEE80211_M_IBSS);
5612	if (stamode && nstate == IEEE80211_S_RUN) {
5613		sc->sc_curaid = ni->ni_associd;
5614		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
5615		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5616	}
5617	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5618	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
5619	ath_hal_setrxfilter(ah, rfilt);
5620
5621	/* XXX is this to restore keycache on resume? */
5622	if (vap->iv_opmode != IEEE80211_M_STA &&
5623	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
5624		for (i = 0; i < IEEE80211_WEP_NKID; i++)
5625			if (ath_hal_keyisvalid(ah, i))
5626				ath_hal_keysetmac(ah, i, ni->ni_bssid);
5627	}
5628
5629	/*
5630	 * Invoke the parent method to do net80211 work.
5631	 */
5632	error = avp->av_newstate(vap, nstate, arg);
5633	if (error != 0)
5634		goto bad;
5635
5636	if (nstate == IEEE80211_S_RUN) {
5637		/* NB: collect bss node again, it may have changed */
5638		ni = vap->iv_bss;
5639
5640		DPRINTF(sc, ATH_DEBUG_STATE,
5641		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
5642		    "capinfo 0x%04x chan %d\n", __func__,
5643		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
5644		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
5645
5646		switch (vap->iv_opmode) {
5647#ifdef IEEE80211_SUPPORT_TDMA
5648		case IEEE80211_M_AHDEMO:
5649			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
5650				break;
5651			/* fall thru... */
5652#endif
5653		case IEEE80211_M_HOSTAP:
5654		case IEEE80211_M_IBSS:
5655		case IEEE80211_M_MBSS:
5656			/*
5657			 * Allocate and setup the beacon frame.
5658			 *
5659			 * Stop any previous beacon DMA.  This may be
5660			 * necessary, for example, when an ibss merge
5661			 * causes reconfiguration; there will be a state
5662			 * transition from RUN->RUN that means we may
5663			 * be called with beacon transmission active.
5664			 */
5665			ath_hal_stoptxdma(ah, sc->sc_bhalq);
5666
5667			error = ath_beacon_alloc(sc, ni);
5668			if (error != 0)
5669				goto bad;
5670			/*
5671			 * If joining an adhoc network defer beacon timer
5672			 * configuration to the next beacon frame so we
5673			 * have a current TSF to use.  Otherwise we're
5674			 * starting an ibss/bss so there's no need to delay;
5675			 * if this is the first vap moving to RUN state, then
5676			 * beacon state needs to be [re]configured.
5677			 */
5678			if (vap->iv_opmode == IEEE80211_M_IBSS &&
5679			    ni->ni_tstamp.tsf != 0) {
5680				sc->sc_syncbeacon = 1;
5681			} else if (!sc->sc_beacons) {
5682#ifdef IEEE80211_SUPPORT_TDMA
5683				if (vap->iv_caps & IEEE80211_C_TDMA)
5684					ath_tdma_config(sc, vap);
5685				else
5686#endif
5687					ath_beacon_config(sc, vap);
5688				sc->sc_beacons = 1;
5689			}
5690			break;
5691		case IEEE80211_M_STA:
5692			/*
5693			 * Defer beacon timer configuration to the next
5694			 * beacon frame so we have a current TSF to use
5695			 * (any TSF collected when scanning is likely old).
5696			 */
5697			sc->sc_syncbeacon = 1;
5698			break;
5699		case IEEE80211_M_MONITOR:
5700			/*
5701			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
5702			 * transitions so we must re-enable interrupts here to
5703			 * handle the case of a single monitor mode vap.
5704			 */
5705			ath_hal_intrset(ah, sc->sc_imask);
5706			break;
5707		case IEEE80211_M_WDS:
5708			break;
5709		default:
5710			break;
5711		}
5712		/*
5713		 * Let the hal process statistics collected during a
5714		 * scan so it can provide calibrated noise floor data.
5715		 */
5716		ath_hal_process_noisefloor(ah);
5717		/*
5718		 * Reset rssi stats; maybe not the best place...
5719		 */
5720		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
5721		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
5722		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
5723		/*
5724		 * Finally, start any timers and the task q thread
5725		 * (in case we didn't go through SCAN state).
5726		 */
5727		if (ath_longcalinterval != 0) {
5728			/* start periodic recalibration timer */
5729			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
5730		} else {
5731			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5732			    "%s: calibration disabled\n", __func__);
5733		}
5734		taskqueue_unblock(sc->sc_tq);
5735	} else if (nstate == IEEE80211_S_INIT) {
5736		/*
5737		 * If there are no vaps left in RUN state then
5738		 * shutdown host/driver operation:
5739		 * o disable interrupts
5740		 * o disable the task queue thread
5741		 * o mark beacon processing as stopped
5742		 */
5743		if (!ath_isanyrunningvaps(vap)) {
5744			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5745			/* disable interrupts  */
5746			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
5747			taskqueue_block(sc->sc_tq);
5748			sc->sc_beacons = 0;
5749		}
5750#ifdef IEEE80211_SUPPORT_TDMA
5751		ath_hal_setcca(ah, AH_TRUE);
5752#endif
5753	}
5754bad:
5755	return error;
5756}
5757
5758/*
5759 * Allocate a key cache slot to the station so we can
5760 * setup a mapping from key index to node. The key cache
5761 * slot is needed for managing antenna state and for
5762 * compression when stations do not use crypto.  We do
5763 * it uniliaterally here; if crypto is employed this slot
5764 * will be reassigned.
5765 */
5766static void
5767ath_setup_stationkey(struct ieee80211_node *ni)
5768{
5769	struct ieee80211vap *vap = ni->ni_vap;
5770	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
5771	ieee80211_keyix keyix, rxkeyix;
5772
5773	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
5774		/*
5775		 * Key cache is full; we'll fall back to doing
5776		 * the more expensive lookup in software.  Note
5777		 * this also means no h/w compression.
5778		 */
5779		/* XXX msg+statistic */
5780	} else {
5781		/* XXX locking? */
5782		ni->ni_ucastkey.wk_keyix = keyix;
5783		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
5784		/* NB: must mark device key to get called back on delete */
5785		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
5786		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
5787		/* NB: this will create a pass-thru key entry */
5788		ath_keyset(sc, &ni->ni_ucastkey, vap->iv_bss);
5789	}
5790}
5791
5792/*
5793 * Setup driver-specific state for a newly associated node.
5794 * Note that we're called also on a re-associate, the isnew
5795 * param tells us if this is the first time or not.
5796 */
5797static void
5798ath_newassoc(struct ieee80211_node *ni, int isnew)
5799{
5800	struct ath_node *an = ATH_NODE(ni);
5801	struct ieee80211vap *vap = ni->ni_vap;
5802	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
5803	const struct ieee80211_txparam *tp = ni->ni_txparms;
5804
5805	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
5806	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
5807
5808	ath_rate_newassoc(sc, an, isnew);
5809	if (isnew &&
5810	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
5811	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
5812		ath_setup_stationkey(ni);
5813}
5814
5815static int
5816ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
5817	int nchans, struct ieee80211_channel chans[])
5818{
5819	struct ath_softc *sc = ic->ic_ifp->if_softc;
5820	struct ath_hal *ah = sc->sc_ah;
5821	HAL_STATUS status;
5822
5823	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
5824	    "%s: rd %u cc %u location %c%s\n",
5825	    __func__, reg->regdomain, reg->country, reg->location,
5826	    reg->ecm ? " ecm" : "");
5827
5828	status = ath_hal_set_channels(ah, chans, nchans,
5829	    reg->country, reg->regdomain);
5830	if (status != HAL_OK) {
5831		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
5832		    __func__, status);
5833		return EINVAL;		/* XXX */
5834	}
5835	return 0;
5836}
5837
5838static void
5839ath_getradiocaps(struct ieee80211com *ic,
5840	int maxchans, int *nchans, struct ieee80211_channel chans[])
5841{
5842	struct ath_softc *sc = ic->ic_ifp->if_softc;
5843	struct ath_hal *ah = sc->sc_ah;
5844
5845	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
5846	    __func__, SKU_DEBUG, CTRY_DEFAULT);
5847
5848	/* XXX check return */
5849	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
5850	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
5851
5852}
5853
5854static int
5855ath_getchannels(struct ath_softc *sc)
5856{
5857	struct ifnet *ifp = sc->sc_ifp;
5858	struct ieee80211com *ic = ifp->if_l2com;
5859	struct ath_hal *ah = sc->sc_ah;
5860	HAL_STATUS status;
5861
5862	/*
5863	 * Collect channel set based on EEPROM contents.
5864	 */
5865	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
5866	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
5867	if (status != HAL_OK) {
5868		if_printf(ifp, "%s: unable to collect channel list from hal, "
5869		    "status %d\n", __func__, status);
5870		return EINVAL;
5871	}
5872	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
5873	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
5874	/* XXX map Atheros sku's to net80211 SKU's */
5875	/* XXX net80211 types too small */
5876	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
5877	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
5878	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
5879	ic->ic_regdomain.isocc[1] = ' ';
5880
5881	ic->ic_regdomain.ecm = 1;
5882	ic->ic_regdomain.location = 'I';
5883
5884	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
5885	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
5886	    __func__, sc->sc_eerd, sc->sc_eecc,
5887	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
5888	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
5889	return 0;
5890}
5891
5892static void
5893ath_led_done(void *arg)
5894{
5895	struct ath_softc *sc = arg;
5896
5897	sc->sc_blinking = 0;
5898}
5899
5900/*
5901 * Turn the LED off: flip the pin and then set a timer so no
5902 * update will happen for the specified duration.
5903 */
5904static void
5905ath_led_off(void *arg)
5906{
5907	struct ath_softc *sc = arg;
5908
5909	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
5910	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
5911}
5912
5913/*
5914 * Blink the LED according to the specified on/off times.
5915 */
5916static void
5917ath_led_blink(struct ath_softc *sc, int on, int off)
5918{
5919	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
5920	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
5921	sc->sc_blinking = 1;
5922	sc->sc_ledoff = off;
5923	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
5924}
5925
5926static void
5927ath_led_event(struct ath_softc *sc, int rix)
5928{
5929	sc->sc_ledevent = ticks;	/* time of last event */
5930	if (sc->sc_blinking)		/* don't interrupt active blink */
5931		return;
5932	ath_led_blink(sc, sc->sc_hwmap[rix].ledon, sc->sc_hwmap[rix].ledoff);
5933}
5934
5935static int
5936ath_rate_setup(struct ath_softc *sc, u_int mode)
5937{
5938	struct ath_hal *ah = sc->sc_ah;
5939	const HAL_RATE_TABLE *rt;
5940
5941	switch (mode) {
5942	case IEEE80211_MODE_11A:
5943		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
5944		break;
5945	case IEEE80211_MODE_HALF:
5946		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
5947		break;
5948	case IEEE80211_MODE_QUARTER:
5949		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
5950		break;
5951	case IEEE80211_MODE_11B:
5952		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
5953		break;
5954	case IEEE80211_MODE_11G:
5955		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
5956		break;
5957	case IEEE80211_MODE_TURBO_A:
5958		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
5959		break;
5960	case IEEE80211_MODE_TURBO_G:
5961		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
5962		break;
5963	case IEEE80211_MODE_STURBO_A:
5964		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
5965		break;
5966	case IEEE80211_MODE_11NA:
5967		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
5968		break;
5969	case IEEE80211_MODE_11NG:
5970		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
5971		break;
5972	default:
5973		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
5974			__func__, mode);
5975		return 0;
5976	}
5977	sc->sc_rates[mode] = rt;
5978	return (rt != NULL);
5979}
5980
5981static void
5982ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
5983{
5984#define	N(a)	(sizeof(a)/sizeof(a[0]))
5985	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
5986	static const struct {
5987		u_int		rate;		/* tx/rx 802.11 rate */
5988		u_int16_t	timeOn;		/* LED on time (ms) */
5989		u_int16_t	timeOff;	/* LED off time (ms) */
5990	} blinkrates[] = {
5991		{ 108,  40,  10 },
5992		{  96,  44,  11 },
5993		{  72,  50,  13 },
5994		{  48,  57,  14 },
5995		{  36,  67,  16 },
5996		{  24,  80,  20 },
5997		{  22, 100,  25 },
5998		{  18, 133,  34 },
5999		{  12, 160,  40 },
6000		{  10, 200,  50 },
6001		{   6, 240,  58 },
6002		{   4, 267,  66 },
6003		{   2, 400, 100 },
6004		{   0, 500, 130 },
6005		/* XXX half/quarter rates */
6006	};
6007	const HAL_RATE_TABLE *rt;
6008	int i, j;
6009
6010	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
6011	rt = sc->sc_rates[mode];
6012	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
6013	for (i = 0; i < rt->rateCount; i++) {
6014		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6015		if (rt->info[i].phy != IEEE80211_T_HT)
6016			sc->sc_rixmap[ieeerate] = i;
6017		else
6018			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
6019	}
6020	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
6021	for (i = 0; i < N(sc->sc_hwmap); i++) {
6022		if (i >= rt->rateCount) {
6023			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
6024			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
6025			continue;
6026		}
6027		sc->sc_hwmap[i].ieeerate =
6028			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6029		if (rt->info[i].phy == IEEE80211_T_HT)
6030			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
6031		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
6032		if (rt->info[i].shortPreamble ||
6033		    rt->info[i].phy == IEEE80211_T_OFDM)
6034			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
6035		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
6036		for (j = 0; j < N(blinkrates)-1; j++)
6037			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
6038				break;
6039		/* NB: this uses the last entry if the rate isn't found */
6040		/* XXX beware of overlow */
6041		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
6042		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
6043	}
6044	sc->sc_currates = rt;
6045	sc->sc_curmode = mode;
6046	/*
6047	 * All protection frames are transmited at 2Mb/s for
6048	 * 11g, otherwise at 1Mb/s.
6049	 */
6050	if (mode == IEEE80211_MODE_11G)
6051		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
6052	else
6053		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
6054	/* NB: caller is responsible for resetting rate control state */
6055#undef N
6056}
6057
6058#ifdef ATH_DEBUG
6059static void
6060ath_printrxbuf(struct ath_softc *sc, const struct ath_buf *bf,
6061	u_int ix, int done)
6062{
6063	const struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
6064	struct ath_hal *ah = sc->sc_ah;
6065	const struct ath_desc *ds;
6066	int i;
6067
6068	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
6069		printf("R[%2u] (DS.V:%p DS.P:%p) L:%08x D:%08x%s\n"
6070		       "      %08x %08x %08x %08x\n",
6071		    ix, ds, (const struct ath_desc *)bf->bf_daddr + i,
6072		    ds->ds_link, ds->ds_data,
6073		    !done ? "" : (rs->rs_status == 0) ? " *" : " !",
6074		    ds->ds_ctl0, ds->ds_ctl1,
6075		    ds->ds_hw[0], ds->ds_hw[1]);
6076		if (ah->ah_magic == 0x20065416) {
6077			printf("        %08x %08x %08x %08x %08x %08x %08x\n",
6078			    ds->ds_hw[2], ds->ds_hw[3], ds->ds_hw[4],
6079			    ds->ds_hw[5], ds->ds_hw[6], ds->ds_hw[7],
6080			    ds->ds_hw[8]);
6081		}
6082	}
6083}
6084
6085static void
6086ath_printtxbuf(struct ath_softc *sc, const struct ath_buf *bf,
6087	u_int qnum, u_int ix, int done)
6088{
6089	const struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
6090	struct ath_hal *ah = sc->sc_ah;
6091	const struct ath_desc *ds;
6092	int i;
6093
6094	printf("Q%u[%3u]", qnum, ix);
6095	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
6096		printf(" (DS.V:%p DS.P:%p) L:%08x D:%08x F:04%x%s\n"
6097		       "        %08x %08x %08x %08x %08x %08x\n",
6098		    ds, (const struct ath_desc *)bf->bf_daddr + i,
6099		    ds->ds_link, ds->ds_data, bf->bf_txflags,
6100		    !done ? "" : (ts->ts_status == 0) ? " *" : " !",
6101		    ds->ds_ctl0, ds->ds_ctl1,
6102		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3]);
6103		if (ah->ah_magic == 0x20065416) {
6104			printf("        %08x %08x %08x %08x %08x %08x %08x %08x\n",
6105			    ds->ds_hw[4], ds->ds_hw[5], ds->ds_hw[6],
6106			    ds->ds_hw[7], ds->ds_hw[8], ds->ds_hw[9],
6107			    ds->ds_hw[10],ds->ds_hw[11]);
6108			printf("        %08x %08x %08x %08x %08x %08x %08x %08x\n",
6109			    ds->ds_hw[12],ds->ds_hw[13],ds->ds_hw[14],
6110			    ds->ds_hw[15],ds->ds_hw[16],ds->ds_hw[17],
6111			    ds->ds_hw[18], ds->ds_hw[19]);
6112		}
6113	}
6114}
6115#endif /* ATH_DEBUG */
6116
6117static void
6118ath_watchdog(void *arg)
6119{
6120	struct ath_softc *sc = arg;
6121
6122	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
6123		struct ifnet *ifp = sc->sc_ifp;
6124		uint32_t hangs;
6125
6126		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
6127		    hangs != 0) {
6128			if_printf(ifp, "%s hang detected (0x%x)\n",
6129			    hangs & 0xff ? "bb" : "mac", hangs);
6130		} else
6131			if_printf(ifp, "device timeout\n");
6132		ath_reset(ifp);
6133		ifp->if_oerrors++;
6134		sc->sc_stats.ast_watchdog++;
6135	}
6136	callout_schedule(&sc->sc_wd_ch, hz);
6137}
6138
6139#ifdef ATH_DIAGAPI
6140/*
6141 * Diagnostic interface to the HAL.  This is used by various
6142 * tools to do things like retrieve register contents for
6143 * debugging.  The mechanism is intentionally opaque so that
6144 * it can change frequently w/o concern for compatiblity.
6145 */
6146static int
6147ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
6148{
6149	struct ath_hal *ah = sc->sc_ah;
6150	u_int id = ad->ad_id & ATH_DIAG_ID;
6151	void *indata = NULL;
6152	void *outdata = NULL;
6153	u_int32_t insize = ad->ad_in_size;
6154	u_int32_t outsize = ad->ad_out_size;
6155	int error = 0;
6156
6157	if (ad->ad_id & ATH_DIAG_IN) {
6158		/*
6159		 * Copy in data.
6160		 */
6161		indata = malloc(insize, M_TEMP, M_NOWAIT);
6162		if (indata == NULL) {
6163			error = ENOMEM;
6164			goto bad;
6165		}
6166		error = copyin(ad->ad_in_data, indata, insize);
6167		if (error)
6168			goto bad;
6169	}
6170	if (ad->ad_id & ATH_DIAG_DYN) {
6171		/*
6172		 * Allocate a buffer for the results (otherwise the HAL
6173		 * returns a pointer to a buffer where we can read the
6174		 * results).  Note that we depend on the HAL leaving this
6175		 * pointer for us to use below in reclaiming the buffer;
6176		 * may want to be more defensive.
6177		 */
6178		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
6179		if (outdata == NULL) {
6180			error = ENOMEM;
6181			goto bad;
6182		}
6183	}
6184	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
6185		if (outsize < ad->ad_out_size)
6186			ad->ad_out_size = outsize;
6187		if (outdata != NULL)
6188			error = copyout(outdata, ad->ad_out_data,
6189					ad->ad_out_size);
6190	} else {
6191		error = EINVAL;
6192	}
6193bad:
6194	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
6195		free(indata, M_TEMP);
6196	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
6197		free(outdata, M_TEMP);
6198	return error;
6199}
6200#endif /* ATH_DIAGAPI */
6201
6202static int
6203ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
6204{
6205#define	IS_RUNNING(ifp) \
6206	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
6207	struct ath_softc *sc = ifp->if_softc;
6208	struct ieee80211com *ic = ifp->if_l2com;
6209	struct ifreq *ifr = (struct ifreq *)data;
6210	const HAL_RATE_TABLE *rt;
6211	int error = 0;
6212
6213	switch (cmd) {
6214	case SIOCSIFFLAGS:
6215		ATH_LOCK(sc);
6216		if (IS_RUNNING(ifp)) {
6217			/*
6218			 * To avoid rescanning another access point,
6219			 * do not call ath_init() here.  Instead,
6220			 * only reflect promisc mode settings.
6221			 */
6222			ath_mode_init(sc);
6223		} else if (ifp->if_flags & IFF_UP) {
6224			/*
6225			 * Beware of being called during attach/detach
6226			 * to reset promiscuous mode.  In that case we
6227			 * will still be marked UP but not RUNNING.
6228			 * However trying to re-init the interface
6229			 * is the wrong thing to do as we've already
6230			 * torn down much of our state.  There's
6231			 * probably a better way to deal with this.
6232			 */
6233			if (!sc->sc_invalid)
6234				ath_init(sc);	/* XXX lose error */
6235		} else {
6236			ath_stop_locked(ifp);
6237#ifdef notyet
6238			/* XXX must wakeup in places like ath_vap_delete */
6239			if (!sc->sc_invalid)
6240				ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
6241#endif
6242		}
6243		ATH_UNLOCK(sc);
6244		break;
6245	case SIOCGIFMEDIA:
6246	case SIOCSIFMEDIA:
6247		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
6248		break;
6249	case SIOCGATHSTATS:
6250		/* NB: embed these numbers to get a consistent view */
6251		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
6252		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
6253		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
6254		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
6255#ifdef IEEE80211_SUPPORT_TDMA
6256		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
6257		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
6258#endif
6259		rt = sc->sc_currates;
6260		/* XXX HT rates */
6261		sc->sc_stats.ast_tx_rate =
6262		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
6263		return copyout(&sc->sc_stats,
6264		    ifr->ifr_data, sizeof (sc->sc_stats));
6265	case SIOCZATHSTATS:
6266		error = priv_check(curthread, PRIV_DRIVER);
6267		if (error == 0)
6268			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
6269		break;
6270#ifdef ATH_DIAGAPI
6271	case SIOCGATHDIAG:
6272		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
6273		break;
6274#endif
6275	case SIOCGIFADDR:
6276		error = ether_ioctl(ifp, cmd, data);
6277		break;
6278	default:
6279		error = EINVAL;
6280		break;
6281	}
6282	return error;
6283#undef IS_RUNNING
6284}
6285
6286static int
6287ath_sysctl_slottime(SYSCTL_HANDLER_ARGS)
6288{
6289	struct ath_softc *sc = arg1;
6290	u_int slottime = ath_hal_getslottime(sc->sc_ah);
6291	int error;
6292
6293	error = sysctl_handle_int(oidp, &slottime, 0, req);
6294	if (error || !req->newptr)
6295		return error;
6296	return !ath_hal_setslottime(sc->sc_ah, slottime) ? EINVAL : 0;
6297}
6298
6299static int
6300ath_sysctl_acktimeout(SYSCTL_HANDLER_ARGS)
6301{
6302	struct ath_softc *sc = arg1;
6303	u_int acktimeout = ath_hal_getacktimeout(sc->sc_ah);
6304	int error;
6305
6306	error = sysctl_handle_int(oidp, &acktimeout, 0, req);
6307	if (error || !req->newptr)
6308		return error;
6309	return !ath_hal_setacktimeout(sc->sc_ah, acktimeout) ? EINVAL : 0;
6310}
6311
6312static int
6313ath_sysctl_ctstimeout(SYSCTL_HANDLER_ARGS)
6314{
6315	struct ath_softc *sc = arg1;
6316	u_int ctstimeout = ath_hal_getctstimeout(sc->sc_ah);
6317	int error;
6318
6319	error = sysctl_handle_int(oidp, &ctstimeout, 0, req);
6320	if (error || !req->newptr)
6321		return error;
6322	return !ath_hal_setctstimeout(sc->sc_ah, ctstimeout) ? EINVAL : 0;
6323}
6324
6325static int
6326ath_sysctl_softled(SYSCTL_HANDLER_ARGS)
6327{
6328	struct ath_softc *sc = arg1;
6329	int softled = sc->sc_softled;
6330	int error;
6331
6332	error = sysctl_handle_int(oidp, &softled, 0, req);
6333	if (error || !req->newptr)
6334		return error;
6335	softled = (softled != 0);
6336	if (softled != sc->sc_softled) {
6337		if (softled) {
6338			/* NB: handle any sc_ledpin change */
6339			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin,
6340			    HAL_GPIO_MUX_MAC_NETWORK_LED);
6341			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
6342				!sc->sc_ledon);
6343		}
6344		sc->sc_softled = softled;
6345	}
6346	return 0;
6347}
6348
6349static int
6350ath_sysctl_ledpin(SYSCTL_HANDLER_ARGS)
6351{
6352	struct ath_softc *sc = arg1;
6353	int ledpin = sc->sc_ledpin;
6354	int error;
6355
6356	error = sysctl_handle_int(oidp, &ledpin, 0, req);
6357	if (error || !req->newptr)
6358		return error;
6359	if (ledpin != sc->sc_ledpin) {
6360		sc->sc_ledpin = ledpin;
6361		if (sc->sc_softled) {
6362			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin,
6363			    HAL_GPIO_MUX_MAC_NETWORK_LED);
6364			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
6365				!sc->sc_ledon);
6366		}
6367	}
6368	return 0;
6369}
6370
6371static int
6372ath_sysctl_txantenna(SYSCTL_HANDLER_ARGS)
6373{
6374	struct ath_softc *sc = arg1;
6375	u_int txantenna = ath_hal_getantennaswitch(sc->sc_ah);
6376	int error;
6377
6378	error = sysctl_handle_int(oidp, &txantenna, 0, req);
6379	if (!error && req->newptr) {
6380		/* XXX assumes 2 antenna ports */
6381		if (txantenna < HAL_ANT_VARIABLE || txantenna > HAL_ANT_FIXED_B)
6382			return EINVAL;
6383		ath_hal_setantennaswitch(sc->sc_ah, txantenna);
6384		/*
6385		 * NB: with the switch locked this isn't meaningful,
6386		 *     but set it anyway so things like radiotap get
6387		 *     consistent info in their data.
6388		 */
6389		sc->sc_txantenna = txantenna;
6390	}
6391	return error;
6392}
6393
6394static int
6395ath_sysctl_rxantenna(SYSCTL_HANDLER_ARGS)
6396{
6397	struct ath_softc *sc = arg1;
6398	u_int defantenna = ath_hal_getdefantenna(sc->sc_ah);
6399	int error;
6400
6401	error = sysctl_handle_int(oidp, &defantenna, 0, req);
6402	if (!error && req->newptr)
6403		ath_hal_setdefantenna(sc->sc_ah, defantenna);
6404	return error;
6405}
6406
6407static int
6408ath_sysctl_diversity(SYSCTL_HANDLER_ARGS)
6409{
6410	struct ath_softc *sc = arg1;
6411	u_int diversity = ath_hal_getdiversity(sc->sc_ah);
6412	int error;
6413
6414	error = sysctl_handle_int(oidp, &diversity, 0, req);
6415	if (error || !req->newptr)
6416		return error;
6417	if (!ath_hal_setdiversity(sc->sc_ah, diversity))
6418		return EINVAL;
6419	sc->sc_diversity = diversity;
6420	return 0;
6421}
6422
6423static int
6424ath_sysctl_diag(SYSCTL_HANDLER_ARGS)
6425{
6426	struct ath_softc *sc = arg1;
6427	u_int32_t diag;
6428	int error;
6429
6430	if (!ath_hal_getdiag(sc->sc_ah, &diag))
6431		return EINVAL;
6432	error = sysctl_handle_int(oidp, &diag, 0, req);
6433	if (error || !req->newptr)
6434		return error;
6435	return !ath_hal_setdiag(sc->sc_ah, diag) ? EINVAL : 0;
6436}
6437
6438static int
6439ath_sysctl_tpscale(SYSCTL_HANDLER_ARGS)
6440{
6441	struct ath_softc *sc = arg1;
6442	struct ifnet *ifp = sc->sc_ifp;
6443	u_int32_t scale;
6444	int error;
6445
6446	(void) ath_hal_gettpscale(sc->sc_ah, &scale);
6447	error = sysctl_handle_int(oidp, &scale, 0, req);
6448	if (error || !req->newptr)
6449		return error;
6450	return !ath_hal_settpscale(sc->sc_ah, scale) ? EINVAL :
6451	    (ifp->if_drv_flags & IFF_DRV_RUNNING) ? ath_reset(ifp) : 0;
6452}
6453
6454static int
6455ath_sysctl_tpc(SYSCTL_HANDLER_ARGS)
6456{
6457	struct ath_softc *sc = arg1;
6458	u_int tpc = ath_hal_gettpc(sc->sc_ah);
6459	int error;
6460
6461	error = sysctl_handle_int(oidp, &tpc, 0, req);
6462	if (error || !req->newptr)
6463		return error;
6464	return !ath_hal_settpc(sc->sc_ah, tpc) ? EINVAL : 0;
6465}
6466
6467static int
6468ath_sysctl_rfkill(SYSCTL_HANDLER_ARGS)
6469{
6470	struct ath_softc *sc = arg1;
6471	struct ifnet *ifp = sc->sc_ifp;
6472	struct ath_hal *ah = sc->sc_ah;
6473	u_int rfkill = ath_hal_getrfkill(ah);
6474	int error;
6475
6476	error = sysctl_handle_int(oidp, &rfkill, 0, req);
6477	if (error || !req->newptr)
6478		return error;
6479	if (rfkill == ath_hal_getrfkill(ah))	/* unchanged */
6480		return 0;
6481	if (!ath_hal_setrfkill(ah, rfkill))
6482		return EINVAL;
6483	return (ifp->if_drv_flags & IFF_DRV_RUNNING) ? ath_reset(ifp) : 0;
6484}
6485
6486static int
6487ath_sysctl_rfsilent(SYSCTL_HANDLER_ARGS)
6488{
6489	struct ath_softc *sc = arg1;
6490	u_int rfsilent;
6491	int error;
6492
6493	(void) ath_hal_getrfsilent(sc->sc_ah, &rfsilent);
6494	error = sysctl_handle_int(oidp, &rfsilent, 0, req);
6495	if (error || !req->newptr)
6496		return error;
6497	if (!ath_hal_setrfsilent(sc->sc_ah, rfsilent))
6498		return EINVAL;
6499	sc->sc_rfsilentpin = rfsilent & 0x1c;
6500	sc->sc_rfsilentpol = (rfsilent & 0x2) != 0;
6501	return 0;
6502}
6503
6504static int
6505ath_sysctl_tpack(SYSCTL_HANDLER_ARGS)
6506{
6507	struct ath_softc *sc = arg1;
6508	u_int32_t tpack;
6509	int error;
6510
6511	(void) ath_hal_gettpack(sc->sc_ah, &tpack);
6512	error = sysctl_handle_int(oidp, &tpack, 0, req);
6513	if (error || !req->newptr)
6514		return error;
6515	return !ath_hal_settpack(sc->sc_ah, tpack) ? EINVAL : 0;
6516}
6517
6518static int
6519ath_sysctl_tpcts(SYSCTL_HANDLER_ARGS)
6520{
6521	struct ath_softc *sc = arg1;
6522	u_int32_t tpcts;
6523	int error;
6524
6525	(void) ath_hal_gettpcts(sc->sc_ah, &tpcts);
6526	error = sysctl_handle_int(oidp, &tpcts, 0, req);
6527	if (error || !req->newptr)
6528		return error;
6529	return !ath_hal_settpcts(sc->sc_ah, tpcts) ? EINVAL : 0;
6530}
6531
6532static int
6533ath_sysctl_intmit(SYSCTL_HANDLER_ARGS)
6534{
6535	struct ath_softc *sc = arg1;
6536	int intmit, error;
6537
6538	intmit = ath_hal_getintmit(sc->sc_ah);
6539	error = sysctl_handle_int(oidp, &intmit, 0, req);
6540	if (error || !req->newptr)
6541		return error;
6542	return !ath_hal_setintmit(sc->sc_ah, intmit) ? EINVAL : 0;
6543}
6544
6545#ifdef IEEE80211_SUPPORT_TDMA
6546static int
6547ath_sysctl_setcca(SYSCTL_HANDLER_ARGS)
6548{
6549	struct ath_softc *sc = arg1;
6550	int setcca, error;
6551
6552	setcca = sc->sc_setcca;
6553	error = sysctl_handle_int(oidp, &setcca, 0, req);
6554	if (error || !req->newptr)
6555		return error;
6556	sc->sc_setcca = (setcca != 0);
6557	return 0;
6558}
6559#endif /* IEEE80211_SUPPORT_TDMA */
6560
6561static void
6562ath_sysctlattach(struct ath_softc *sc)
6563{
6564	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
6565	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
6566	struct ath_hal *ah = sc->sc_ah;
6567
6568	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6569		"countrycode", CTLFLAG_RD, &sc->sc_eecc, 0,
6570		"EEPROM country code");
6571	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6572		"regdomain", CTLFLAG_RD, &sc->sc_eerd, 0,
6573		"EEPROM regdomain code");
6574#ifdef	ATH_DEBUG
6575	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6576		"debug", CTLFLAG_RW, &sc->sc_debug, 0,
6577		"control debugging printfs");
6578#endif
6579	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6580		"slottime", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6581		ath_sysctl_slottime, "I", "802.11 slot time (us)");
6582	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6583		"acktimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6584		ath_sysctl_acktimeout, "I", "802.11 ACK timeout (us)");
6585	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6586		"ctstimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6587		ath_sysctl_ctstimeout, "I", "802.11 CTS timeout (us)");
6588	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6589		"softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6590		ath_sysctl_softled, "I", "enable/disable software LED support");
6591	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6592		"ledpin", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6593		ath_sysctl_ledpin, "I", "GPIO pin connected to LED");
6594	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6595		"ledon", CTLFLAG_RW, &sc->sc_ledon, 0,
6596		"setting to turn LED on");
6597	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6598		"ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
6599		"idle time for inactivity LED (ticks)");
6600	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6601		"txantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6602		ath_sysctl_txantenna, "I", "antenna switch");
6603	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6604		"rxantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6605		ath_sysctl_rxantenna, "I", "default/rx antenna");
6606	if (ath_hal_hasdiversity(ah))
6607		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6608			"diversity", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6609			ath_sysctl_diversity, "I", "antenna diversity");
6610	sc->sc_txintrperiod = ATH_TXINTR_PERIOD;
6611	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6612		"txintrperiod", CTLFLAG_RW, &sc->sc_txintrperiod, 0,
6613		"tx descriptor batching");
6614	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6615		"diag", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6616		ath_sysctl_diag, "I", "h/w diagnostic control");
6617	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6618		"tpscale", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6619		ath_sysctl_tpscale, "I", "tx power scaling");
6620	if (ath_hal_hastpc(ah)) {
6621		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6622			"tpc", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6623			ath_sysctl_tpc, "I", "enable/disable per-packet TPC");
6624		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6625			"tpack", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6626			ath_sysctl_tpack, "I", "tx power for ack frames");
6627		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6628			"tpcts", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6629			ath_sysctl_tpcts, "I", "tx power for cts frames");
6630	}
6631	if (ath_hal_hasrfsilent(ah)) {
6632		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6633			"rfsilent", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6634			ath_sysctl_rfsilent, "I", "h/w RF silent config");
6635		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6636			"rfkill", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6637			ath_sysctl_rfkill, "I", "enable/disable RF kill switch");
6638	}
6639	if (ath_hal_hasintmit(ah)) {
6640		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6641			"intmit", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6642			ath_sysctl_intmit, "I", "interference mitigation");
6643	}
6644	sc->sc_monpass = HAL_RXERR_DECRYPT | HAL_RXERR_MIC;
6645	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6646		"monpass", CTLFLAG_RW, &sc->sc_monpass, 0,
6647		"mask of error frames to pass when monitoring");
6648#ifdef IEEE80211_SUPPORT_TDMA
6649	if (ath_hal_macversion(ah) > 0x78) {
6650		sc->sc_tdmadbaprep = 2;
6651		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6652			"dbaprep", CTLFLAG_RW, &sc->sc_tdmadbaprep, 0,
6653			"TDMA DBA preparation time");
6654		sc->sc_tdmaswbaprep = 10;
6655		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6656			"swbaprep", CTLFLAG_RW, &sc->sc_tdmaswbaprep, 0,
6657			"TDMA SWBA preparation time");
6658		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6659			"guardtime", CTLFLAG_RW, &sc->sc_tdmaguard, 0,
6660			"TDMA slot guard time");
6661		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6662			"superframe", CTLFLAG_RD, &sc->sc_tdmabintval, 0,
6663			"TDMA calculated super frame");
6664		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6665			"setcca", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6666			ath_sysctl_setcca, "I", "enable CCA control");
6667	}
6668#endif
6669}
6670
6671static int
6672ath_tx_raw_start(struct ath_softc *sc, struct ieee80211_node *ni,
6673	struct ath_buf *bf, struct mbuf *m0,
6674	const struct ieee80211_bpf_params *params)
6675{
6676	struct ifnet *ifp = sc->sc_ifp;
6677	struct ieee80211com *ic = ifp->if_l2com;
6678	struct ath_hal *ah = sc->sc_ah;
6679	struct ieee80211vap *vap = ni->ni_vap;
6680	int error, ismcast, ismrr;
6681	int keyix, hdrlen, pktlen, try0, txantenna;
6682	u_int8_t rix, cix, txrate, ctsrate, rate1, rate2, rate3;
6683	struct ieee80211_frame *wh;
6684	u_int flags, ctsduration;
6685	HAL_PKT_TYPE atype;
6686	const HAL_RATE_TABLE *rt;
6687	struct ath_desc *ds;
6688	u_int pri;
6689
6690	wh = mtod(m0, struct ieee80211_frame *);
6691	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
6692	hdrlen = ieee80211_anyhdrsize(wh);
6693	/*
6694	 * Packet length must not include any
6695	 * pad bytes; deduct them here.
6696	 */
6697	/* XXX honor IEEE80211_BPF_DATAPAD */
6698	pktlen = m0->m_pkthdr.len - (hdrlen & 3) + IEEE80211_CRC_LEN;
6699
6700	if (params->ibp_flags & IEEE80211_BPF_CRYPTO) {
6701		const struct ieee80211_cipher *cip;
6702		struct ieee80211_key *k;
6703
6704		/*
6705		 * Construct the 802.11 header+trailer for an encrypted
6706		 * frame. The only reason this can fail is because of an
6707		 * unknown or unsupported cipher/key type.
6708		 */
6709		k = ieee80211_crypto_encap(ni, m0);
6710		if (k == NULL) {
6711			/*
6712			 * This can happen when the key is yanked after the
6713			 * frame was queued.  Just discard the frame; the
6714			 * 802.11 layer counts failures and provides
6715			 * debugging/diagnostics.
6716			 */
6717			ath_freetx(m0);
6718			return EIO;
6719		}
6720		/*
6721		 * Adjust the packet + header lengths for the crypto
6722		 * additions and calculate the h/w key index.  When
6723		 * a s/w mic is done the frame will have had any mic
6724		 * added to it prior to entry so m0->m_pkthdr.len will
6725		 * account for it. Otherwise we need to add it to the
6726		 * packet length.
6727		 */
6728		cip = k->wk_cipher;
6729		hdrlen += cip->ic_header;
6730		pktlen += cip->ic_header + cip->ic_trailer;
6731		/* NB: frags always have any TKIP MIC done in s/w */
6732		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0)
6733			pktlen += cip->ic_miclen;
6734		keyix = k->wk_keyix;
6735
6736		/* packet header may have moved, reset our local pointer */
6737		wh = mtod(m0, struct ieee80211_frame *);
6738	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
6739		/*
6740		 * Use station key cache slot, if assigned.
6741		 */
6742		keyix = ni->ni_ucastkey.wk_keyix;
6743		if (keyix == IEEE80211_KEYIX_NONE)
6744			keyix = HAL_TXKEYIX_INVALID;
6745	} else
6746		keyix = HAL_TXKEYIX_INVALID;
6747
6748	error = ath_tx_dmasetup(sc, bf, m0);
6749	if (error != 0)
6750		return error;
6751	m0 = bf->bf_m;				/* NB: may have changed */
6752	wh = mtod(m0, struct ieee80211_frame *);
6753	bf->bf_node = ni;			/* NB: held reference */
6754
6755	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
6756	flags |= HAL_TXDESC_INTREQ;		/* force interrupt */
6757	if (params->ibp_flags & IEEE80211_BPF_RTS)
6758		flags |= HAL_TXDESC_RTSENA;
6759	else if (params->ibp_flags & IEEE80211_BPF_CTS)
6760		flags |= HAL_TXDESC_CTSENA;
6761	/* XXX leave ismcast to injector? */
6762	if ((params->ibp_flags & IEEE80211_BPF_NOACK) || ismcast)
6763		flags |= HAL_TXDESC_NOACK;
6764
6765	rt = sc->sc_currates;
6766	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
6767	rix = ath_tx_findrix(sc, params->ibp_rate0);
6768	txrate = rt->info[rix].rateCode;
6769	if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
6770		txrate |= rt->info[rix].shortPreamble;
6771	sc->sc_txrix = rix;
6772	try0 = params->ibp_try0;
6773	ismrr = (params->ibp_try1 != 0);
6774	txantenna = params->ibp_pri >> 2;
6775	if (txantenna == 0)			/* XXX? */
6776		txantenna = sc->sc_txantenna;
6777	ctsduration = 0;
6778	if (flags & (HAL_TXDESC_CTSENA | HAL_TXDESC_RTSENA)) {
6779		cix = ath_tx_findrix(sc, params->ibp_ctsrate);
6780		ctsrate = rt->info[cix].rateCode;
6781		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE) {
6782			ctsrate |= rt->info[cix].shortPreamble;
6783			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
6784				ctsduration += rt->info[cix].spAckDuration;
6785			ctsduration += ath_hal_computetxtime(ah,
6786				rt, pktlen, rix, AH_TRUE);
6787			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
6788				ctsduration += rt->info[rix].spAckDuration;
6789		} else {
6790			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
6791				ctsduration += rt->info[cix].lpAckDuration;
6792			ctsduration += ath_hal_computetxtime(ah,
6793				rt, pktlen, rix, AH_FALSE);
6794			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
6795				ctsduration += rt->info[rix].lpAckDuration;
6796		}
6797		ismrr = 0;			/* XXX */
6798	} else
6799		ctsrate = 0;
6800	pri = params->ibp_pri & 3;
6801	/*
6802	 * NB: we mark all packets as type PSPOLL so the h/w won't
6803	 * set the sequence number, duration, etc.
6804	 */
6805	atype = HAL_PKT_TYPE_PSPOLL;
6806
6807	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
6808		ieee80211_dump_pkt(ic, mtod(m0, caddr_t), m0->m_len,
6809		    sc->sc_hwmap[rix].ieeerate, -1);
6810
6811	if (ieee80211_radiotap_active_vap(vap)) {
6812		u_int64_t tsf = ath_hal_gettsf64(ah);
6813
6814		sc->sc_tx_th.wt_tsf = htole64(tsf);
6815		sc->sc_tx_th.wt_flags = sc->sc_hwmap[rix].txflags;
6816		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
6817			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
6818		if (m0->m_flags & M_FRAG)
6819			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
6820		sc->sc_tx_th.wt_rate = sc->sc_hwmap[rix].ieeerate;
6821		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
6822		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
6823
6824		ieee80211_radiotap_tx(vap, m0);
6825	}
6826
6827	/*
6828	 * Formulate first tx descriptor with tx controls.
6829	 */
6830	ds = bf->bf_desc;
6831	/* XXX check return value? */
6832	ath_hal_setuptxdesc(ah, ds
6833		, pktlen		/* packet length */
6834		, hdrlen		/* header length */
6835		, atype			/* Atheros packet type */
6836		, params->ibp_power	/* txpower */
6837		, txrate, try0		/* series 0 rate/tries */
6838		, keyix			/* key cache index */
6839		, txantenna		/* antenna mode */
6840		, flags			/* flags */
6841		, ctsrate		/* rts/cts rate */
6842		, ctsduration		/* rts/cts duration */
6843	);
6844	bf->bf_txflags = flags;
6845
6846	if (ismrr) {
6847		rix = ath_tx_findrix(sc, params->ibp_rate1);
6848		rate1 = rt->info[rix].rateCode;
6849		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
6850			rate1 |= rt->info[rix].shortPreamble;
6851		if (params->ibp_try2) {
6852			rix = ath_tx_findrix(sc, params->ibp_rate2);
6853			rate2 = rt->info[rix].rateCode;
6854			if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
6855				rate2 |= rt->info[rix].shortPreamble;
6856		} else
6857			rate2 = 0;
6858		if (params->ibp_try3) {
6859			rix = ath_tx_findrix(sc, params->ibp_rate3);
6860			rate3 = rt->info[rix].rateCode;
6861			if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
6862				rate3 |= rt->info[rix].shortPreamble;
6863		} else
6864			rate3 = 0;
6865		ath_hal_setupxtxdesc(ah, ds
6866			, rate1, params->ibp_try1	/* series 1 */
6867			, rate2, params->ibp_try2	/* series 2 */
6868			, rate3, params->ibp_try3	/* series 3 */
6869		);
6870	}
6871
6872	/* NB: no buffered multicast in power save support */
6873	ath_tx_handoff(sc, sc->sc_ac2q[pri], bf);
6874	return 0;
6875}
6876
6877static int
6878ath_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
6879	const struct ieee80211_bpf_params *params)
6880{
6881	struct ieee80211com *ic = ni->ni_ic;
6882	struct ifnet *ifp = ic->ic_ifp;
6883	struct ath_softc *sc = ifp->if_softc;
6884	struct ath_buf *bf;
6885	int error;
6886
6887	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid) {
6888		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: discard frame, %s", __func__,
6889		    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ?
6890			"!running" : "invalid");
6891		m_freem(m);
6892		error = ENETDOWN;
6893		goto bad;
6894	}
6895	/*
6896	 * Grab a TX buffer and associated resources.
6897	 */
6898	bf = ath_getbuf(sc);
6899	if (bf == NULL) {
6900		sc->sc_stats.ast_tx_nobuf++;
6901		m_freem(m);
6902		error = ENOBUFS;
6903		goto bad;
6904	}
6905
6906	if (params == NULL) {
6907		/*
6908		 * Legacy path; interpret frame contents to decide
6909		 * precisely how to send the frame.
6910		 */
6911		if (ath_tx_start(sc, ni, bf, m)) {
6912			error = EIO;		/* XXX */
6913			goto bad2;
6914		}
6915	} else {
6916		/*
6917		 * Caller supplied explicit parameters to use in
6918		 * sending the frame.
6919		 */
6920		if (ath_tx_raw_start(sc, ni, bf, m, params)) {
6921			error = EIO;		/* XXX */
6922			goto bad2;
6923		}
6924	}
6925	sc->sc_wd_timer = 5;
6926	ifp->if_opackets++;
6927	sc->sc_stats.ast_tx_raw++;
6928
6929	return 0;
6930bad2:
6931	ATH_TXBUF_LOCK(sc);
6932	STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
6933	ATH_TXBUF_UNLOCK(sc);
6934bad:
6935	ifp->if_oerrors++;
6936	sc->sc_stats.ast_tx_raw_fail++;
6937	ieee80211_free_node(ni);
6938	return error;
6939}
6940
6941/*
6942 * Announce various information on device/driver attach.
6943 */
6944static void
6945ath_announce(struct ath_softc *sc)
6946{
6947	struct ifnet *ifp = sc->sc_ifp;
6948	struct ath_hal *ah = sc->sc_ah;
6949
6950	if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
6951		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
6952		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
6953	if (bootverbose) {
6954		int i;
6955		for (i = 0; i <= WME_AC_VO; i++) {
6956			struct ath_txq *txq = sc->sc_ac2q[i];
6957			if_printf(ifp, "Use hw queue %u for %s traffic\n",
6958				txq->axq_qnum, ieee80211_wme_acnames[i]);
6959		}
6960		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
6961			sc->sc_cabq->axq_qnum);
6962		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
6963	}
6964	if (ath_rxbuf != ATH_RXBUF)
6965		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
6966	if (ath_txbuf != ATH_TXBUF)
6967		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
6968	if (sc->sc_mcastkey && bootverbose)
6969		if_printf(ifp, "using multicast key search\n");
6970}
6971
6972#ifdef IEEE80211_SUPPORT_TDMA
6973static __inline uint32_t
6974ath_hal_getnexttbtt(struct ath_hal *ah)
6975{
6976#define	AR_TIMER0	0x8028
6977	return OS_REG_READ(ah, AR_TIMER0);
6978}
6979
6980static __inline void
6981ath_hal_adjusttsf(struct ath_hal *ah, int32_t tsfdelta)
6982{
6983	/* XXX handle wrap/overflow */
6984	OS_REG_WRITE(ah, AR_TSF_L32, OS_REG_READ(ah, AR_TSF_L32) + tsfdelta);
6985}
6986
6987static void
6988ath_tdma_settimers(struct ath_softc *sc, u_int32_t nexttbtt, u_int32_t bintval)
6989{
6990	struct ath_hal *ah = sc->sc_ah;
6991	HAL_BEACON_TIMERS bt;
6992
6993	bt.bt_intval = bintval | HAL_BEACON_ENA;
6994	bt.bt_nexttbtt = nexttbtt;
6995	bt.bt_nextdba = (nexttbtt<<3) - sc->sc_tdmadbaprep;
6996	bt.bt_nextswba = (nexttbtt<<3) - sc->sc_tdmaswbaprep;
6997	bt.bt_nextatim = nexttbtt+1;
6998	ath_hal_beaconsettimers(ah, &bt);
6999}
7000
7001/*
7002 * Calculate the beacon interval.  This is periodic in the
7003 * superframe for the bss.  We assume each station is configured
7004 * identically wrt transmit rate so the guard time we calculate
7005 * above will be the same on all stations.  Note we need to
7006 * factor in the xmit time because the hardware will schedule
7007 * a frame for transmit if the start of the frame is within
7008 * the burst time.  When we get hardware that properly kills
7009 * frames in the PCU we can reduce/eliminate the guard time.
7010 *
7011 * Roundup to 1024 is so we have 1 TU buffer in the guard time
7012 * to deal with the granularity of the nexttbtt timer.  11n MAC's
7013 * with 1us timer granularity should allow us to reduce/eliminate
7014 * this.
7015 */
7016static void
7017ath_tdma_bintvalsetup(struct ath_softc *sc,
7018	const struct ieee80211_tdma_state *tdma)
7019{
7020	/* copy from vap state (XXX check all vaps have same value?) */
7021	sc->sc_tdmaslotlen = tdma->tdma_slotlen;
7022
7023	sc->sc_tdmabintval = roundup((sc->sc_tdmaslotlen+sc->sc_tdmaguard) *
7024		tdma->tdma_slotcnt, 1024);
7025	sc->sc_tdmabintval >>= 10;		/* TSF -> TU */
7026	if (sc->sc_tdmabintval & 1)
7027		sc->sc_tdmabintval++;
7028
7029	if (tdma->tdma_slot == 0) {
7030		/*
7031		 * Only slot 0 beacons; other slots respond.
7032		 */
7033		sc->sc_imask |= HAL_INT_SWBA;
7034		sc->sc_tdmaswba = 0;		/* beacon immediately */
7035	} else {
7036		/* XXX all vaps must be slot 0 or slot !0 */
7037		sc->sc_imask &= ~HAL_INT_SWBA;
7038	}
7039}
7040
7041/*
7042 * Max 802.11 overhead.  This assumes no 4-address frames and
7043 * the encapsulation done by ieee80211_encap (llc).  We also
7044 * include potential crypto overhead.
7045 */
7046#define	IEEE80211_MAXOVERHEAD \
7047	(sizeof(struct ieee80211_qosframe) \
7048	 + sizeof(struct llc) \
7049	 + IEEE80211_ADDR_LEN \
7050	 + IEEE80211_WEP_IVLEN \
7051	 + IEEE80211_WEP_KIDLEN \
7052	 + IEEE80211_WEP_CRCLEN \
7053	 + IEEE80211_WEP_MICLEN \
7054	 + IEEE80211_CRC_LEN)
7055
7056/*
7057 * Setup initially for tdma operation.  Start the beacon
7058 * timers and enable SWBA if we are slot 0.  Otherwise
7059 * we wait for slot 0 to arrive so we can sync up before
7060 * starting to transmit.
7061 */
7062static void
7063ath_tdma_config(struct ath_softc *sc, struct ieee80211vap *vap)
7064{
7065	struct ath_hal *ah = sc->sc_ah;
7066	struct ifnet *ifp = sc->sc_ifp;
7067	struct ieee80211com *ic = ifp->if_l2com;
7068	const struct ieee80211_txparam *tp;
7069	const struct ieee80211_tdma_state *tdma = NULL;
7070	int rix;
7071
7072	if (vap == NULL) {
7073		vap = TAILQ_FIRST(&ic->ic_vaps);   /* XXX */
7074		if (vap == NULL) {
7075			if_printf(ifp, "%s: no vaps?\n", __func__);
7076			return;
7077		}
7078	}
7079	tp = vap->iv_bss->ni_txparms;
7080	/*
7081	 * Calculate the guard time for each slot.  This is the
7082	 * time to send a maximal-size frame according to the
7083	 * fixed/lowest transmit rate.  Note that the interface
7084	 * mtu does not include the 802.11 overhead so we must
7085	 * tack that on (ath_hal_computetxtime includes the
7086	 * preamble and plcp in it's calculation).
7087	 */
7088	tdma = vap->iv_tdma;
7089	if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
7090		rix = ath_tx_findrix(sc, tp->ucastrate);
7091	else
7092		rix = ath_tx_findrix(sc, tp->mcastrate);
7093	/* XXX short preamble assumed */
7094	sc->sc_tdmaguard = ath_hal_computetxtime(ah, sc->sc_currates,
7095		ifp->if_mtu + IEEE80211_MAXOVERHEAD, rix, AH_TRUE);
7096
7097	ath_hal_intrset(ah, 0);
7098
7099	ath_beaconq_config(sc);			/* setup h/w beacon q */
7100	if (sc->sc_setcca)
7101		ath_hal_setcca(ah, AH_FALSE);	/* disable CCA */
7102	ath_tdma_bintvalsetup(sc, tdma);	/* calculate beacon interval */
7103	ath_tdma_settimers(sc, sc->sc_tdmabintval,
7104		sc->sc_tdmabintval | HAL_BEACON_RESET_TSF);
7105	sc->sc_syncbeacon = 0;
7106
7107	sc->sc_avgtsfdeltap = TDMA_DUMMY_MARKER;
7108	sc->sc_avgtsfdeltam = TDMA_DUMMY_MARKER;
7109
7110	ath_hal_intrset(ah, sc->sc_imask);
7111
7112	DPRINTF(sc, ATH_DEBUG_TDMA, "%s: slot %u len %uus cnt %u "
7113	    "bsched %u guard %uus bintval %u TU dba prep %u\n", __func__,
7114	    tdma->tdma_slot, tdma->tdma_slotlen, tdma->tdma_slotcnt,
7115	    tdma->tdma_bintval, sc->sc_tdmaguard, sc->sc_tdmabintval,
7116	    sc->sc_tdmadbaprep);
7117}
7118
7119/*
7120 * Update tdma operation.  Called from the 802.11 layer
7121 * when a beacon is received from the TDMA station operating
7122 * in the slot immediately preceding us in the bss.  Use
7123 * the rx timestamp for the beacon frame to update our
7124 * beacon timers so we follow their schedule.  Note that
7125 * by using the rx timestamp we implicitly include the
7126 * propagation delay in our schedule.
7127 */
7128static void
7129ath_tdma_update(struct ieee80211_node *ni,
7130	const struct ieee80211_tdma_param *tdma, int changed)
7131{
7132#define	TSF_TO_TU(_h,_l) \
7133	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
7134#define	TU_TO_TSF(_tu)	(((u_int64_t)(_tu)) << 10)
7135	struct ieee80211vap *vap = ni->ni_vap;
7136	struct ieee80211com *ic = ni->ni_ic;
7137	struct ath_softc *sc = ic->ic_ifp->if_softc;
7138	struct ath_hal *ah = sc->sc_ah;
7139	const HAL_RATE_TABLE *rt = sc->sc_currates;
7140	u_int64_t tsf, rstamp, nextslot;
7141	u_int32_t txtime, nextslottu, timer0;
7142	int32_t tudelta, tsfdelta;
7143	const struct ath_rx_status *rs;
7144	int rix;
7145
7146	sc->sc_stats.ast_tdma_update++;
7147
7148	/*
7149	 * Check for and adopt configuration changes.
7150	 */
7151	if (changed != 0) {
7152		const struct ieee80211_tdma_state *ts = vap->iv_tdma;
7153
7154		ath_tdma_bintvalsetup(sc, ts);
7155		if (changed & TDMA_UPDATE_SLOTLEN)
7156			ath_wme_update(ic);
7157
7158		DPRINTF(sc, ATH_DEBUG_TDMA,
7159		    "%s: adopt slot %u slotcnt %u slotlen %u us "
7160		    "bintval %u TU\n", __func__,
7161		    ts->tdma_slot, ts->tdma_slotcnt, ts->tdma_slotlen,
7162		    sc->sc_tdmabintval);
7163
7164		/* XXX right? */
7165		ath_hal_intrset(ah, sc->sc_imask);
7166		/* NB: beacon timers programmed below */
7167	}
7168
7169	/* extend rx timestamp to 64 bits */
7170	rs = sc->sc_lastrs;
7171	tsf = ath_hal_gettsf64(ah);
7172	rstamp = ath_extend_tsf(rs->rs_tstamp, tsf);
7173	/*
7174	 * The rx timestamp is set by the hardware on completing
7175	 * reception (at the point where the rx descriptor is DMA'd
7176	 * to the host).  To find the start of our next slot we
7177	 * must adjust this time by the time required to send
7178	 * the packet just received.
7179	 */
7180	rix = rt->rateCodeToIndex[rs->rs_rate];
7181	txtime = ath_hal_computetxtime(ah, rt, rs->rs_datalen, rix,
7182	    rt->info[rix].shortPreamble);
7183	/* NB: << 9 is to cvt to TU and /2 */
7184	nextslot = (rstamp - txtime) + (sc->sc_tdmabintval << 9);
7185	nextslottu = TSF_TO_TU(nextslot>>32, nextslot) & HAL_BEACON_PERIOD;
7186
7187	/*
7188	 * TIMER0 is the h/w's idea of NextTBTT (in TU's).  Convert
7189	 * to usecs and calculate the difference between what the
7190	 * other station thinks and what we have programmed.  This
7191	 * lets us figure how to adjust our timers to match.  The
7192	 * adjustments are done by pulling the TSF forward and possibly
7193	 * rewriting the beacon timers.
7194	 */
7195	timer0 = ath_hal_getnexttbtt(ah);
7196	tsfdelta = (int32_t)((nextslot % TU_TO_TSF(HAL_BEACON_PERIOD+1)) - TU_TO_TSF(timer0));
7197
7198	DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
7199	    "tsfdelta %d avg +%d/-%d\n", tsfdelta,
7200	    TDMA_AVG(sc->sc_avgtsfdeltap), TDMA_AVG(sc->sc_avgtsfdeltam));
7201
7202	if (tsfdelta < 0) {
7203		TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
7204		TDMA_SAMPLE(sc->sc_avgtsfdeltam, -tsfdelta);
7205		tsfdelta = -tsfdelta % 1024;
7206		nextslottu++;
7207	} else if (tsfdelta > 0) {
7208		TDMA_SAMPLE(sc->sc_avgtsfdeltap, tsfdelta);
7209		TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
7210		tsfdelta = 1024 - (tsfdelta % 1024);
7211		nextslottu++;
7212	} else {
7213		TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
7214		TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
7215	}
7216	tudelta = nextslottu - timer0;
7217
7218	/*
7219	 * Copy sender's timetstamp into tdma ie so they can
7220	 * calculate roundtrip time.  We submit a beacon frame
7221	 * below after any timer adjustment.  The frame goes out
7222	 * at the next TBTT so the sender can calculate the
7223	 * roundtrip by inspecting the tdma ie in our beacon frame.
7224	 *
7225	 * NB: This tstamp is subtlely preserved when
7226	 *     IEEE80211_BEACON_TDMA is marked (e.g. when the
7227	 *     slot position changes) because ieee80211_add_tdma
7228	 *     skips over the data.
7229	 */
7230	memcpy(ATH_VAP(vap)->av_boff.bo_tdma +
7231		__offsetof(struct ieee80211_tdma_param, tdma_tstamp),
7232		&ni->ni_tstamp.data, 8);
7233#if 0
7234	DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
7235	    "tsf %llu nextslot %llu (%d, %d) nextslottu %u timer0 %u (%d)\n",
7236	    (unsigned long long) tsf, (unsigned long long) nextslot,
7237	    (int)(nextslot - tsf), tsfdelta,
7238	    nextslottu, timer0, tudelta);
7239#endif
7240	/*
7241	 * Adjust the beacon timers only when pulling them forward
7242	 * or when going back by less than the beacon interval.
7243	 * Negative jumps larger than the beacon interval seem to
7244	 * cause the timers to stop and generally cause instability.
7245	 * This basically filters out jumps due to missed beacons.
7246	 */
7247	if (tudelta != 0 && (tudelta > 0 || -tudelta < sc->sc_tdmabintval)) {
7248		ath_tdma_settimers(sc, nextslottu, sc->sc_tdmabintval);
7249		sc->sc_stats.ast_tdma_timers++;
7250	}
7251	if (tsfdelta > 0) {
7252		ath_hal_adjusttsf(ah, tsfdelta);
7253		sc->sc_stats.ast_tdma_tsf++;
7254	}
7255	ath_tdma_beacon_send(sc, vap);		/* prepare response */
7256#undef TU_TO_TSF
7257#undef TSF_TO_TU
7258}
7259
7260/*
7261 * Transmit a beacon frame at SWBA.  Dynamic updates
7262 * to the frame contents are done as needed.
7263 */
7264static void
7265ath_tdma_beacon_send(struct ath_softc *sc, struct ieee80211vap *vap)
7266{
7267	struct ath_hal *ah = sc->sc_ah;
7268	struct ath_buf *bf;
7269	int otherant;
7270
7271	/*
7272	 * Check if the previous beacon has gone out.  If
7273	 * not don't try to post another, skip this period
7274	 * and wait for the next.  Missed beacons indicate
7275	 * a problem and should not occur.  If we miss too
7276	 * many consecutive beacons reset the device.
7277	 */
7278	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
7279		sc->sc_bmisscount++;
7280		DPRINTF(sc, ATH_DEBUG_BEACON,
7281			"%s: missed %u consecutive beacons\n",
7282			__func__, sc->sc_bmisscount);
7283		if (sc->sc_bmisscount >= ath_bstuck_threshold)
7284			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
7285		return;
7286	}
7287	if (sc->sc_bmisscount != 0) {
7288		DPRINTF(sc, ATH_DEBUG_BEACON,
7289			"%s: resume beacon xmit after %u misses\n",
7290			__func__, sc->sc_bmisscount);
7291		sc->sc_bmisscount = 0;
7292	}
7293
7294	/*
7295	 * Check recent per-antenna transmit statistics and flip
7296	 * the default antenna if noticeably more frames went out
7297	 * on the non-default antenna.
7298	 * XXX assumes 2 anntenae
7299	 */
7300	if (!sc->sc_diversity) {
7301		otherant = sc->sc_defant & 1 ? 2 : 1;
7302		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
7303			ath_setdefantenna(sc, otherant);
7304		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
7305	}
7306
7307	bf = ath_beacon_generate(sc, vap);
7308	if (bf != NULL) {
7309		/*
7310		 * Stop any current dma and put the new frame on the queue.
7311		 * This should never fail since we check above that no frames
7312		 * are still pending on the queue.
7313		 */
7314		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
7315			DPRINTF(sc, ATH_DEBUG_ANY,
7316				"%s: beacon queue %u did not stop?\n",
7317				__func__, sc->sc_bhalq);
7318			/* NB: the HAL still stops DMA, so proceed */
7319		}
7320		ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
7321		ath_hal_txstart(ah, sc->sc_bhalq);
7322
7323		sc->sc_stats.ast_be_xmit++;		/* XXX per-vap? */
7324
7325		/*
7326		 * Record local TSF for our last send for use
7327		 * in arbitrating slot collisions.
7328		 */
7329		vap->iv_bss->ni_tstamp.tsf = ath_hal_gettsf64(ah);
7330	}
7331}
7332#endif /* IEEE80211_SUPPORT_TDMA */
7333
7334static int
7335ath_sysctl_clearstats(SYSCTL_HANDLER_ARGS)
7336{
7337	struct ath_softc *sc = arg1;
7338	int val = 0;
7339	int error;
7340
7341	error = sysctl_handle_int(oidp, &val, 0, req);
7342	if (error || !req->newptr)
7343		return error;
7344	if (val == 0)
7345		return 0;       /* Not clearing the stats is still valid */
7346	memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
7347	val = 0;
7348	return 0;
7349}
7350
7351static void
7352ath_sysctl_stats_attach(struct ath_softc *sc)
7353{
7354	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
7355	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
7356	struct sysctl_oid_list *child = SYSCTL_CHILDREN(tree);
7357
7358	/* Create "clear" node */
7359	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7360	    "clear_stats", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7361	    ath_sysctl_clearstats, "I", "clear stats");
7362
7363	/* Create stats node */
7364	tree = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, "stats", CTLFLAG_RD,
7365	    NULL, "Statistics");
7366	child = SYSCTL_CHILDREN(tree);
7367
7368	/* This was generated from if_athioctl.h */
7369
7370	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_watchdog", CTLFLAG_RD,
7371	    &sc->sc_stats.ast_watchdog, 0, "device reset by watchdog");
7372	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_hardware", CTLFLAG_RD,
7373	    &sc->sc_stats.ast_hardware, 0, "fatal hardware error interrupts");
7374	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_bmiss", CTLFLAG_RD,
7375	    &sc->sc_stats.ast_bmiss, 0, "beacon miss interrupts");
7376	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_bmiss_phantom", CTLFLAG_RD,
7377	    &sc->sc_stats.ast_bmiss_phantom, 0, "beacon miss interrupts");
7378	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_bstuck", CTLFLAG_RD,
7379	    &sc->sc_stats.ast_bstuck, 0, "beacon stuck interrupts");
7380	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rxorn", CTLFLAG_RD,
7381	    &sc->sc_stats.ast_rxorn, 0, "rx overrun interrupts");
7382	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rxeol", CTLFLAG_RD,
7383	    &sc->sc_stats.ast_rxeol, 0, "rx eol interrupts");
7384	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_txurn", CTLFLAG_RD,
7385	    &sc->sc_stats.ast_txurn, 0, "tx underrun interrupts");
7386	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_mib", CTLFLAG_RD,
7387	    &sc->sc_stats.ast_mib, 0, "mib interrupts");
7388	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_intrcoal", CTLFLAG_RD,
7389	    &sc->sc_stats.ast_intrcoal, 0, "interrupts coalesced");
7390	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_packets", CTLFLAG_RD,
7391	    &sc->sc_stats.ast_tx_packets, 0, "packet sent on the interface");
7392	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_mgmt", CTLFLAG_RD,
7393	    &sc->sc_stats.ast_tx_mgmt, 0, "management frames transmitted");
7394	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_discard", CTLFLAG_RD,
7395	    &sc->sc_stats.ast_tx_discard, 0, "frames discarded prior to assoc");
7396	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_qstop", CTLFLAG_RD,
7397	    &sc->sc_stats.ast_tx_qstop, 0, "output stopped 'cuz no buffer");
7398	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_encap", CTLFLAG_RD,
7399	    &sc->sc_stats.ast_tx_encap, 0, "tx encapsulation failed");
7400	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nonode", CTLFLAG_RD,
7401	    &sc->sc_stats.ast_tx_nonode, 0, "tx failed 'cuz no node");
7402	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nombuf", CTLFLAG_RD,
7403	    &sc->sc_stats.ast_tx_nombuf, 0, "tx failed 'cuz no mbuf");
7404	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nomcl", CTLFLAG_RD,
7405	    &sc->sc_stats.ast_tx_nomcl, 0, "tx failed 'cuz no cluster");
7406	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_linear", CTLFLAG_RD,
7407	    &sc->sc_stats.ast_tx_linear, 0, "tx linearized to cluster");
7408	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nodata", CTLFLAG_RD,
7409	    &sc->sc_stats.ast_tx_nodata, 0, "tx discarded empty frame");
7410	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_busdma", CTLFLAG_RD,
7411	    &sc->sc_stats.ast_tx_busdma, 0, "tx failed for dma resrcs");
7412	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_xretries", CTLFLAG_RD,
7413	    &sc->sc_stats.ast_tx_xretries, 0, "tx failed 'cuz too many retries");
7414	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_fifoerr", CTLFLAG_RD,
7415	    &sc->sc_stats.ast_tx_fifoerr, 0, "tx failed 'cuz FIFO underrun");
7416	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_filtered", CTLFLAG_RD,
7417	    &sc->sc_stats.ast_tx_filtered, 0, "tx failed 'cuz xmit filtered");
7418	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_shortretry", CTLFLAG_RD,
7419	    &sc->sc_stats.ast_tx_shortretry, 0, "tx on-chip retries (short)");
7420	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_longretry", CTLFLAG_RD,
7421	    &sc->sc_stats.ast_tx_longretry, 0, "tx on-chip retries (long)");
7422	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_badrate", CTLFLAG_RD,
7423	    &sc->sc_stats.ast_tx_badrate, 0, "tx failed 'cuz bogus xmit rate");
7424	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_noack", CTLFLAG_RD,
7425	    &sc->sc_stats.ast_tx_noack, 0, "tx frames with no ack marked");
7426	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_rts", CTLFLAG_RD,
7427	    &sc->sc_stats.ast_tx_rts, 0, "tx frames with rts enabled");
7428	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_cts", CTLFLAG_RD,
7429	    &sc->sc_stats.ast_tx_cts, 0, "tx frames with cts enabled");
7430	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_shortpre", CTLFLAG_RD,
7431	    &sc->sc_stats.ast_tx_shortpre, 0, "tx frames with short preamble");
7432	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_altrate", CTLFLAG_RD,
7433	    &sc->sc_stats.ast_tx_altrate, 0, "tx frames with alternate rate");
7434	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_protect", CTLFLAG_RD,
7435	    &sc->sc_stats.ast_tx_protect, 0, "tx frames with protection");
7436	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_ctsburst", CTLFLAG_RD,
7437	    &sc->sc_stats.ast_tx_ctsburst, 0, "tx frames with cts and bursting");
7438	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_ctsext", CTLFLAG_RD,
7439	    &sc->sc_stats.ast_tx_ctsext, 0, "tx frames with cts extension");
7440	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_nombuf", CTLFLAG_RD,
7441	    &sc->sc_stats.ast_rx_nombuf, 0, "rx setup failed 'cuz no mbuf");
7442	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_busdma", CTLFLAG_RD,
7443	    &sc->sc_stats.ast_rx_busdma, 0, "rx setup failed for dma resrcs");
7444	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_orn", CTLFLAG_RD,
7445	    &sc->sc_stats.ast_rx_orn, 0, "rx failed 'cuz of desc overrun");
7446	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_crcerr", CTLFLAG_RD,
7447	    &sc->sc_stats.ast_rx_crcerr, 0, "rx failed 'cuz of bad CRC");
7448	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_fifoerr", CTLFLAG_RD,
7449	    &sc->sc_stats.ast_rx_fifoerr, 0, "rx failed 'cuz of FIFO overrun");
7450	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_badcrypt", CTLFLAG_RD,
7451	    &sc->sc_stats.ast_rx_badcrypt, 0, "rx failed 'cuz decryption");
7452	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_badmic", CTLFLAG_RD,
7453	    &sc->sc_stats.ast_rx_badmic, 0, "rx failed 'cuz MIC failure");
7454	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_phyerr", CTLFLAG_RD,
7455	    &sc->sc_stats.ast_rx_phyerr, 0, "rx failed 'cuz of PHY err");
7456	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_tooshort", CTLFLAG_RD,
7457	    &sc->sc_stats.ast_rx_tooshort, 0, "rx discarded 'cuz frame too short");
7458	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_toobig", CTLFLAG_RD,
7459	    &sc->sc_stats.ast_rx_toobig, 0, "rx discarded 'cuz frame too large");
7460	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_packets", CTLFLAG_RD,
7461	    &sc->sc_stats.ast_rx_packets, 0, "packet recv on the interface");
7462	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_mgt", CTLFLAG_RD,
7463	    &sc->sc_stats.ast_rx_mgt, 0, "management frames received");
7464	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_ctl", CTLFLAG_RD,
7465	    &sc->sc_stats.ast_rx_ctl, 0, "rx discarded 'cuz ctl frame");
7466	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_be_xmit", CTLFLAG_RD,
7467	    &sc->sc_stats.ast_be_xmit, 0, "beacons transmitted");
7468	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_be_nombuf", CTLFLAG_RD,
7469	    &sc->sc_stats.ast_be_nombuf, 0, "beacon setup failed 'cuz no mbuf");
7470	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_per_cal", CTLFLAG_RD,
7471	    &sc->sc_stats.ast_per_cal, 0, "periodic calibration calls");
7472	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_per_calfail", CTLFLAG_RD,
7473	    &sc->sc_stats.ast_per_calfail, 0, "periodic calibration failed");
7474	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_per_rfgain", CTLFLAG_RD,
7475	    &sc->sc_stats.ast_per_rfgain, 0, "periodic calibration rfgain reset");
7476	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rate_calls", CTLFLAG_RD,
7477	    &sc->sc_stats.ast_rate_calls, 0, "rate control checks");
7478	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rate_raise", CTLFLAG_RD,
7479	    &sc->sc_stats.ast_rate_raise, 0, "rate control raised xmit rate");
7480	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rate_drop", CTLFLAG_RD,
7481	    &sc->sc_stats.ast_rate_drop, 0, "rate control dropped xmit rate");
7482	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ant_defswitch", CTLFLAG_RD,
7483	    &sc->sc_stats.ast_ant_defswitch, 0, "rx/default antenna switches");
7484	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ant_txswitch", CTLFLAG_RD,
7485	    &sc->sc_stats.ast_ant_txswitch, 0, "tx antenna switches");
7486	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_cabq_xmit", CTLFLAG_RD,
7487	    &sc->sc_stats.ast_cabq_xmit, 0, "cabq frames transmitted");
7488	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_cabq_busy", CTLFLAG_RD,
7489	    &sc->sc_stats.ast_cabq_busy, 0, "cabq found busy");
7490	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_raw", CTLFLAG_RD,
7491	    &sc->sc_stats.ast_tx_raw, 0, "tx frames through raw api");
7492	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ff_txok", CTLFLAG_RD,
7493	    &sc->sc_stats.ast_ff_txok, 0, "fast frames tx'd successfully");
7494	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ff_txerr", CTLFLAG_RD,
7495	    &sc->sc_stats.ast_ff_txerr, 0, "fast frames tx'd w/ error");
7496	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ff_rx", CTLFLAG_RD,
7497	    &sc->sc_stats.ast_ff_rx, 0, "fast frames rx'd");
7498	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ff_flush", CTLFLAG_RD,
7499	    &sc->sc_stats.ast_ff_flush, 0, "fast frames flushed from staging q");
7500	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_qfull", CTLFLAG_RD,
7501	    &sc->sc_stats.ast_tx_qfull, 0, "tx dropped 'cuz of queue limit");
7502	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nobuf", CTLFLAG_RD,
7503	    &sc->sc_stats.ast_tx_nobuf, 0, "tx dropped 'cuz no ath buffer");
7504	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tdma_update", CTLFLAG_RD,
7505	    &sc->sc_stats.ast_tdma_update, 0, "TDMA slot timing updates");
7506	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tdma_timers", CTLFLAG_RD,
7507	    &sc->sc_stats.ast_tdma_timers, 0, "TDMA slot update set beacon timers");
7508	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tdma_tsf", CTLFLAG_RD,
7509	    &sc->sc_stats.ast_tdma_tsf, 0, "TDMA slot update set TSF");
7510	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tdma_ack", CTLFLAG_RD,
7511	    &sc->sc_stats.ast_tdma_ack, 0, "TDMA tx failed 'cuz ACK required");
7512	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_raw_fail", CTLFLAG_RD,
7513	    &sc->sc_stats.ast_tx_raw_fail, 0, "raw tx failed 'cuz h/w down");
7514	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nofrag", CTLFLAG_RD,
7515	    &sc->sc_stats.ast_tx_nofrag, 0, "tx dropped 'cuz no ath frag buffer");
7516	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_be_missed", CTLFLAG_RD,
7517	    &sc->sc_stats.ast_be_missed, 0, "number of -missed- beacons");
7518}
7519