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