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