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