if_ath.c revision 222432
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 222432 2011-05-29 00:17:13Z adrian $");
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#include <sys/module.h>
62
63#include <machine/bus.h>
64
65#include <net/if.h>
66#include <net/if_dl.h>
67#include <net/if_media.h>
68#include <net/if_types.h>
69#include <net/if_arp.h>
70#include <net/ethernet.h>
71#include <net/if_llc.h>
72
73#include <net80211/ieee80211_var.h>
74#include <net80211/ieee80211_regdomain.h>
75#ifdef IEEE80211_SUPPORT_SUPERG
76#include <net80211/ieee80211_superg.h>
77#endif
78#ifdef IEEE80211_SUPPORT_TDMA
79#include <net80211/ieee80211_tdma.h>
80#endif
81
82#include <net/bpf.h>
83
84#ifdef INET
85#include <netinet/in.h>
86#include <netinet/if_ether.h>
87#endif
88
89#include <dev/ath/if_athvar.h>
90#include <dev/ath/ath_hal/ah_devid.h>		/* XXX for softled */
91#include <dev/ath/ath_hal/ah_diagcodes.h>
92
93#include <dev/ath/if_ath_debug.h>
94#include <dev/ath/if_ath_misc.h>
95#include <dev/ath/if_ath_tx.h>
96#include <dev/ath/if_ath_sysctl.h>
97#include <dev/ath/if_ath_keycache.h>
98
99#ifdef ATH_TX99_DIAG
100#include <dev/ath/ath_tx99/ath_tx99.h>
101#endif
102
103/*
104 * ATH_BCBUF determines the number of vap's that can transmit
105 * beacons and also (currently) the number of vap's that can
106 * have unique mac addresses/bssid.  When staggering beacons
107 * 4 is probably a good max as otherwise the beacons become
108 * very closely spaced and there is limited time for cab q traffic
109 * to go out.  You can burst beacons instead but that is not good
110 * for stations in power save and at some point you really want
111 * another radio (and channel).
112 *
113 * The limit on the number of mac addresses is tied to our use of
114 * the U/L bit and tracking addresses in a byte; it would be
115 * worthwhile to allow more for applications like proxy sta.
116 */
117CTASSERT(ATH_BCBUF <= 8);
118
119static struct ieee80211vap *ath_vap_create(struct ieee80211com *,
120		    const char name[IFNAMSIZ], int unit, int opmode,
121		    int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
122		    const uint8_t mac[IEEE80211_ADDR_LEN]);
123static void	ath_vap_delete(struct ieee80211vap *);
124static void	ath_init(void *);
125static void	ath_stop_locked(struct ifnet *);
126static void	ath_stop(struct ifnet *);
127static void	ath_start(struct ifnet *);
128static int	ath_reset_vap(struct ieee80211vap *, u_long);
129static int	ath_media_change(struct ifnet *);
130static void	ath_watchdog(void *);
131static int	ath_ioctl(struct ifnet *, u_long, caddr_t);
132static void	ath_fatal_proc(void *, int);
133static void	ath_bmiss_vap(struct ieee80211vap *);
134static void	ath_bmiss_proc(void *, int);
135static void	ath_key_update_begin(struct ieee80211vap *);
136static void	ath_key_update_end(struct ieee80211vap *);
137static void	ath_update_mcast(struct ifnet *);
138static void	ath_update_promisc(struct ifnet *);
139static void	ath_mode_init(struct ath_softc *);
140static void	ath_setslottime(struct ath_softc *);
141static void	ath_updateslot(struct ifnet *);
142static int	ath_beaconq_setup(struct ath_hal *);
143static int	ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
144static void	ath_beacon_update(struct ieee80211vap *, int item);
145static void	ath_beacon_setup(struct ath_softc *, struct ath_buf *);
146static void	ath_beacon_proc(void *, int);
147static struct ath_buf *ath_beacon_generate(struct ath_softc *,
148			struct ieee80211vap *);
149static void	ath_bstuck_proc(void *, int);
150static void	ath_beacon_return(struct ath_softc *, struct ath_buf *);
151static void	ath_beacon_free(struct ath_softc *);
152static void	ath_beacon_config(struct ath_softc *, struct ieee80211vap *);
153static void	ath_descdma_cleanup(struct ath_softc *sc,
154			struct ath_descdma *, ath_bufhead *);
155static int	ath_desc_alloc(struct ath_softc *);
156static void	ath_desc_free(struct ath_softc *);
157static struct ieee80211_node *ath_node_alloc(struct ieee80211vap *,
158			const uint8_t [IEEE80211_ADDR_LEN]);
159static void	ath_node_free(struct ieee80211_node *);
160static void	ath_node_getsignal(const struct ieee80211_node *,
161			int8_t *, int8_t *);
162static int	ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
163static void	ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
164			int subtype, int rssi, int nf);
165static void	ath_setdefantenna(struct ath_softc *, u_int);
166static void	ath_rx_proc(void *, int);
167static void	ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
168static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
169static int	ath_tx_setup(struct ath_softc *, int, int);
170static int	ath_wme_update(struct ieee80211com *);
171static void	ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
172static void	ath_tx_cleanup(struct ath_softc *);
173static void	ath_tx_proc_q0(void *, int);
174static void	ath_tx_proc_q0123(void *, int);
175static void	ath_tx_proc(void *, int);
176static void	ath_tx_draintxq(struct ath_softc *, struct ath_txq *);
177static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
178static void	ath_draintxq(struct ath_softc *);
179static void	ath_stoprecv(struct ath_softc *);
180static int	ath_startrecv(struct ath_softc *);
181static void	ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
182static void	ath_scan_start(struct ieee80211com *);
183static void	ath_scan_end(struct ieee80211com *);
184static void	ath_set_channel(struct ieee80211com *);
185static void	ath_calibrate(void *);
186static int	ath_newstate(struct ieee80211vap *, enum ieee80211_state, int);
187static void	ath_setup_stationkey(struct ieee80211_node *);
188static void	ath_newassoc(struct ieee80211_node *, int);
189static int	ath_setregdomain(struct ieee80211com *,
190		    struct ieee80211_regdomain *, int,
191		    struct ieee80211_channel []);
192static void	ath_getradiocaps(struct ieee80211com *, int, int *,
193		    struct ieee80211_channel []);
194static int	ath_getchannels(struct ath_softc *);
195static void	ath_led_event(struct ath_softc *, int);
196
197static int	ath_rate_setup(struct ath_softc *, u_int mode);
198static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
199
200static void	ath_announce(struct ath_softc *);
201
202#ifdef IEEE80211_SUPPORT_TDMA
203static void	ath_tdma_settimers(struct ath_softc *sc, u_int32_t nexttbtt,
204		    u_int32_t bintval);
205static void	ath_tdma_bintvalsetup(struct ath_softc *sc,
206		    const struct ieee80211_tdma_state *tdma);
207static void	ath_tdma_config(struct ath_softc *sc, struct ieee80211vap *vap);
208static void	ath_tdma_update(struct ieee80211_node *ni,
209		    const struct ieee80211_tdma_param *tdma, int);
210static void	ath_tdma_beacon_send(struct ath_softc *sc,
211		    struct ieee80211vap *vap);
212
213static __inline void
214ath_hal_setcca(struct ath_hal *ah, int ena)
215{
216	/*
217	 * NB: fill me in; this is not provided by default because disabling
218	 *     CCA in most locales violates regulatory.
219	 */
220}
221
222static __inline int
223ath_hal_getcca(struct ath_hal *ah)
224{
225	u_int32_t diag;
226	if (ath_hal_getcapability(ah, HAL_CAP_DIAG, 0, &diag) != HAL_OK)
227		return 1;
228	return ((diag & 0x500000) == 0);
229}
230
231#define	TDMA_EP_MULTIPLIER	(1<<10) /* pow2 to optimize out * and / */
232#define	TDMA_LPF_LEN		6
233#define	TDMA_DUMMY_MARKER	0x127
234#define	TDMA_EP_MUL(x, mul)	((x) * (mul))
235#define	TDMA_IN(x)		(TDMA_EP_MUL((x), TDMA_EP_MULTIPLIER))
236#define	TDMA_LPF(x, y, len) \
237    ((x != TDMA_DUMMY_MARKER) ? (((x) * ((len)-1) + (y)) / (len)) : (y))
238#define	TDMA_SAMPLE(x, y) do {					\
239	x = TDMA_LPF((x), TDMA_IN(y), TDMA_LPF_LEN);		\
240} while (0)
241#define	TDMA_EP_RND(x,mul) \
242	((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
243#define	TDMA_AVG(x)		TDMA_EP_RND(x, TDMA_EP_MULTIPLIER)
244#endif /* IEEE80211_SUPPORT_TDMA */
245
246SYSCTL_DECL(_hw_ath);
247
248/* XXX validate sysctl values */
249static	int ath_longcalinterval = 30;		/* long cals every 30 secs */
250SYSCTL_INT(_hw_ath, OID_AUTO, longcal, CTLFLAG_RW, &ath_longcalinterval,
251	    0, "long chip calibration interval (secs)");
252static	int ath_shortcalinterval = 100;		/* short cals every 100 ms */
253SYSCTL_INT(_hw_ath, OID_AUTO, shortcal, CTLFLAG_RW, &ath_shortcalinterval,
254	    0, "short chip calibration interval (msecs)");
255static	int ath_resetcalinterval = 20*60;	/* reset cal state 20 mins */
256SYSCTL_INT(_hw_ath, OID_AUTO, resetcal, CTLFLAG_RW, &ath_resetcalinterval,
257	    0, "reset chip calibration results (secs)");
258static	int ath_anicalinterval = 100;		/* ANI calibration - 100 msec */
259SYSCTL_INT(_hw_ath, OID_AUTO, anical, CTLFLAG_RW, &ath_anicalinterval,
260	    0, "ANI calibration (msecs)");
261
262static	int ath_rxbuf = ATH_RXBUF;		/* # rx buffers to allocate */
263SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RW, &ath_rxbuf,
264	    0, "rx buffers allocated");
265TUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
266static	int ath_txbuf = ATH_TXBUF;		/* # tx buffers to allocate */
267SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RW, &ath_txbuf,
268	    0, "tx buffers allocated");
269TUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
270
271static	int ath_bstuck_threshold = 4;		/* max missed beacons */
272SYSCTL_INT(_hw_ath, OID_AUTO, bstuck, CTLFLAG_RW, &ath_bstuck_threshold,
273	    0, "max missed beacon xmits before chip reset");
274
275MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
276
277#define	HAL_MODE_HT20 (HAL_MODE_11NG_HT20 | HAL_MODE_11NA_HT20)
278#define	HAL_MODE_HT40 \
279	(HAL_MODE_11NG_HT40PLUS | HAL_MODE_11NG_HT40MINUS | \
280	HAL_MODE_11NA_HT40PLUS | HAL_MODE_11NA_HT40MINUS)
281int
282ath_attach(u_int16_t devid, struct ath_softc *sc)
283{
284	struct ifnet *ifp;
285	struct ieee80211com *ic;
286	struct ath_hal *ah = NULL;
287	HAL_STATUS status;
288	int error = 0, i;
289	u_int wmodes;
290	uint8_t macaddr[IEEE80211_ADDR_LEN];
291
292	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
293
294	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
295	if (ifp == NULL) {
296		device_printf(sc->sc_dev, "can not if_alloc()\n");
297		error = ENOSPC;
298		goto bad;
299	}
300	ic = ifp->if_l2com;
301
302	/* set these up early for if_printf use */
303	if_initname(ifp, device_get_name(sc->sc_dev),
304		device_get_unit(sc->sc_dev));
305
306	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, sc->sc_eepromdata, &status);
307	if (ah == NULL) {
308		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
309			status);
310		error = ENXIO;
311		goto bad;
312	}
313	sc->sc_ah = ah;
314	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
315#ifdef	ATH_DEBUG
316	sc->sc_debug = ath_debug;
317#endif
318
319	/*
320	 * Check if the MAC has multi-rate retry support.
321	 * We do this by trying to setup a fake extended
322	 * descriptor.  MAC's that don't have support will
323	 * return false w/o doing anything.  MAC's that do
324	 * support it will return true w/o doing anything.
325	 */
326	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
327
328	/*
329	 * Check if the device has hardware counters for PHY
330	 * errors.  If so we need to enable the MIB interrupt
331	 * so we can act on stat triggers.
332	 */
333	if (ath_hal_hwphycounters(ah))
334		sc->sc_needmib = 1;
335
336	/*
337	 * Get the hardware key cache size.
338	 */
339	sc->sc_keymax = ath_hal_keycachesize(ah);
340	if (sc->sc_keymax > ATH_KEYMAX) {
341		if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
342			ATH_KEYMAX, sc->sc_keymax);
343		sc->sc_keymax = ATH_KEYMAX;
344	}
345	/*
346	 * Reset the key cache since some parts do not
347	 * reset the contents on initial power up.
348	 */
349	for (i = 0; i < sc->sc_keymax; i++)
350		ath_hal_keyreset(ah, i);
351
352	/*
353	 * Collect the default channel list.
354	 */
355	error = ath_getchannels(sc);
356	if (error != 0)
357		goto bad;
358
359	/*
360	 * Setup rate tables for all potential media types.
361	 */
362	ath_rate_setup(sc, IEEE80211_MODE_11A);
363	ath_rate_setup(sc, IEEE80211_MODE_11B);
364	ath_rate_setup(sc, IEEE80211_MODE_11G);
365	ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
366	ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
367	ath_rate_setup(sc, IEEE80211_MODE_STURBO_A);
368	ath_rate_setup(sc, IEEE80211_MODE_11NA);
369	ath_rate_setup(sc, IEEE80211_MODE_11NG);
370	ath_rate_setup(sc, IEEE80211_MODE_HALF);
371	ath_rate_setup(sc, IEEE80211_MODE_QUARTER);
372
373	/* NB: setup here so ath_rate_update is happy */
374	ath_setcurmode(sc, IEEE80211_MODE_11A);
375
376	/*
377	 * Allocate tx+rx descriptors and populate the lists.
378	 */
379	error = ath_desc_alloc(sc);
380	if (error != 0) {
381		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
382		goto bad;
383	}
384	callout_init_mtx(&sc->sc_cal_ch, &sc->sc_mtx, 0);
385	callout_init_mtx(&sc->sc_wd_ch, &sc->sc_mtx, 0);
386
387	ATH_TXBUF_LOCK_INIT(sc);
388
389	sc->sc_tq = taskqueue_create("ath_taskq", M_NOWAIT,
390		taskqueue_thread_enqueue, &sc->sc_tq);
391	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET,
392		"%s taskq", ifp->if_xname);
393
394	TASK_INIT(&sc->sc_rxtask, 0, ath_rx_proc, sc);
395	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
396	TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_proc, sc);
397
398	/*
399	 * Allocate hardware transmit queues: one queue for
400	 * beacon frames and one data queue for each QoS
401	 * priority.  Note that the hal handles resetting
402	 * these queues at the needed time.
403	 *
404	 * XXX PS-Poll
405	 */
406	sc->sc_bhalq = ath_beaconq_setup(ah);
407	if (sc->sc_bhalq == (u_int) -1) {
408		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
409		error = EIO;
410		goto bad2;
411	}
412	sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
413	if (sc->sc_cabq == NULL) {
414		if_printf(ifp, "unable to setup CAB xmit queue!\n");
415		error = EIO;
416		goto bad2;
417	}
418	/* NB: insure BK queue is the lowest priority h/w queue */
419	if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
420		if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
421			ieee80211_wme_acnames[WME_AC_BK]);
422		error = EIO;
423		goto bad2;
424	}
425	if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
426	    !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
427	    !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
428		/*
429		 * Not enough hardware tx queues to properly do WME;
430		 * just punt and assign them all to the same h/w queue.
431		 * We could do a better job of this if, for example,
432		 * we allocate queues when we switch from station to
433		 * AP mode.
434		 */
435		if (sc->sc_ac2q[WME_AC_VI] != NULL)
436			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
437		if (sc->sc_ac2q[WME_AC_BE] != NULL)
438			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
439		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
440		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
441		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
442	}
443
444	/*
445	 * Special case certain configurations.  Note the
446	 * CAB queue is handled by these specially so don't
447	 * include them when checking the txq setup mask.
448	 */
449	switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
450	case 0x01:
451		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
452		break;
453	case 0x0f:
454		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
455		break;
456	default:
457		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
458		break;
459	}
460
461	/*
462	 * Setup rate control.  Some rate control modules
463	 * call back to change the anntena state so expose
464	 * the necessary entry points.
465	 * XXX maybe belongs in struct ath_ratectrl?
466	 */
467	sc->sc_setdefantenna = ath_setdefantenna;
468	sc->sc_rc = ath_rate_attach(sc);
469	if (sc->sc_rc == NULL) {
470		error = EIO;
471		goto bad2;
472	}
473
474	sc->sc_blinking = 0;
475	sc->sc_ledstate = 1;
476	sc->sc_ledon = 0;			/* low true */
477	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
478	callout_init(&sc->sc_ledtimer, CALLOUT_MPSAFE);
479	/*
480	 * Auto-enable soft led processing for IBM cards and for
481	 * 5211 minipci cards.  Users can also manually enable/disable
482	 * support with a sysctl.
483	 */
484	sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
485	if (sc->sc_softled) {
486		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin,
487		    HAL_GPIO_MUX_MAC_NETWORK_LED);
488		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
489	}
490
491	ifp->if_softc = sc;
492	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
493	ifp->if_start = ath_start;
494	ifp->if_ioctl = ath_ioctl;
495	ifp->if_init = ath_init;
496	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
497	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
498	IFQ_SET_READY(&ifp->if_snd);
499
500	ic->ic_ifp = ifp;
501	/* XXX not right but it's not used anywhere important */
502	ic->ic_phytype = IEEE80211_T_OFDM;
503	ic->ic_opmode = IEEE80211_M_STA;
504	ic->ic_caps =
505		  IEEE80211_C_STA		/* station mode */
506		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
507		| IEEE80211_C_HOSTAP		/* hostap mode */
508		| IEEE80211_C_MONITOR		/* monitor mode */
509		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
510		| IEEE80211_C_WDS		/* 4-address traffic works */
511		| IEEE80211_C_MBSS		/* mesh point link mode */
512		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
513		| IEEE80211_C_SHSLOT		/* short slot time supported */
514		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
515		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
516		| IEEE80211_C_TXFRAG		/* handle tx frags */
517		;
518	/*
519	 * Query the hal to figure out h/w crypto support.
520	 */
521	if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
522		ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
523	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
524		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_OCB;
525	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
526		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_CCM;
527	if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
528		ic->ic_cryptocaps |= IEEE80211_CRYPTO_CKIP;
529	if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
530		ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIP;
531		/*
532		 * Check if h/w does the MIC and/or whether the
533		 * separate key cache entries are required to
534		 * handle both tx+rx MIC keys.
535		 */
536		if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
537			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
538		/*
539		 * If the h/w supports storing tx+rx MIC keys
540		 * in one cache slot automatically enable use.
541		 */
542		if (ath_hal_hastkipsplit(ah) ||
543		    !ath_hal_settkipsplit(ah, AH_FALSE))
544			sc->sc_splitmic = 1;
545		/*
546		 * If the h/w can do TKIP MIC together with WME then
547		 * we use it; otherwise we force the MIC to be done
548		 * in software by the net80211 layer.
549		 */
550		if (ath_hal_haswmetkipmic(ah))
551			sc->sc_wmetkipmic = 1;
552	}
553	sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
554	/*
555	 * Check for multicast key search support.
556	 */
557	if (ath_hal_hasmcastkeysearch(sc->sc_ah) &&
558	    !ath_hal_getmcastkeysearch(sc->sc_ah)) {
559		ath_hal_setmcastkeysearch(sc->sc_ah, 1);
560	}
561	sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
562	/*
563	 * Mark key cache slots associated with global keys
564	 * as in use.  If we knew TKIP was not to be used we
565	 * could leave the +32, +64, and +32+64 slots free.
566	 */
567	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
568		setbit(sc->sc_keymap, i);
569		setbit(sc->sc_keymap, i+64);
570		if (sc->sc_splitmic) {
571			setbit(sc->sc_keymap, i+32);
572			setbit(sc->sc_keymap, i+32+64);
573		}
574	}
575	/*
576	 * TPC support can be done either with a global cap or
577	 * per-packet support.  The latter is not available on
578	 * all parts.  We're a bit pedantic here as all parts
579	 * support a global cap.
580	 */
581	if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
582		ic->ic_caps |= IEEE80211_C_TXPMGT;
583
584	/*
585	 * Mark WME capability only if we have sufficient
586	 * hardware queues to do proper priority scheduling.
587	 */
588	if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
589		ic->ic_caps |= IEEE80211_C_WME;
590	/*
591	 * Check for misc other capabilities.
592	 */
593	if (ath_hal_hasbursting(ah))
594		ic->ic_caps |= IEEE80211_C_BURST;
595	sc->sc_hasbmask = ath_hal_hasbssidmask(ah);
596	sc->sc_hasbmatch = ath_hal_hasbssidmatch(ah);
597	sc->sc_hastsfadd = ath_hal_hastsfadjust(ah);
598	sc->sc_rxslink = ath_hal_self_linked_final_rxdesc(ah);
599	if (ath_hal_hasfastframes(ah))
600		ic->ic_caps |= IEEE80211_C_FF;
601	wmodes = ath_hal_getwirelessmodes(ah);
602	if (wmodes & (HAL_MODE_108G|HAL_MODE_TURBO))
603		ic->ic_caps |= IEEE80211_C_TURBOP;
604#ifdef IEEE80211_SUPPORT_TDMA
605	if (ath_hal_macversion(ah) > 0x78) {
606		ic->ic_caps |= IEEE80211_C_TDMA; /* capable of TDMA */
607		ic->ic_tdma_update = ath_tdma_update;
608	}
609#endif
610
611	/*
612	 * The if_ath 11n support is completely not ready for normal use.
613	 * Enabling this option will likely break everything and everything.
614	 * Don't think of doing that unless you know what you're doing.
615	 */
616
617#ifdef	ATH_ENABLE_11N
618	/*
619	 * Query HT capabilities
620	 */
621	if (ath_hal_getcapability(ah, HAL_CAP_HT, 0, NULL) == HAL_OK &&
622	    (wmodes & (HAL_MODE_HT20 | HAL_MODE_HT40))) {
623		int rxs, txs;
624
625		device_printf(sc->sc_dev, "[HT] enabling HT modes\n");
626		ic->ic_htcaps = IEEE80211_HTC_HT		/* HT operation */
627			    | IEEE80211_HTC_AMPDU		/* A-MPDU tx/rx */
628			    | IEEE80211_HTC_AMSDU		/* A-MSDU tx/rx */
629			    | IEEE80211_HTCAP_MAXAMSDU_3839	/* max A-MSDU length */
630			    | IEEE80211_HTCAP_SMPS_OFF;		/* SM power save off */
631			;
632
633		/*
634		 * Enable short-GI for HT20 only if the hardware
635		 * advertises support.
636		 * Notably, anything earlier than the AR9287 doesn't.
637		 */
638		if ((ath_hal_getcapability(ah,
639		    HAL_CAP_HT20_SGI, 0, NULL) == HAL_OK) &&
640		    (wmodes & HAL_MODE_HT20)) {
641			device_printf(sc->sc_dev,
642			    "[HT] enabling short-GI in 20MHz mode\n");
643			ic->ic_htcaps |= IEEE80211_HTCAP_SHORTGI20;
644		}
645
646		if (wmodes & HAL_MODE_HT40)
647			ic->ic_htcaps |= IEEE80211_HTCAP_CHWIDTH40
648			    |  IEEE80211_HTCAP_SHORTGI40;
649
650		/*
651		 * rx/tx stream is not currently used anywhere; it needs to be taken
652		 * into account when negotiating which MCS rates it'll receive and
653		 * what MCS rates are available for TX.
654		 */
655		(void) ath_hal_getcapability(ah, HAL_CAP_STREAMS, 0, &rxs);
656		(void) ath_hal_getcapability(ah, HAL_CAP_STREAMS, 1, &txs);
657
658		ath_hal_getrxchainmask(ah, &sc->sc_rxchainmask);
659		ath_hal_gettxchainmask(ah, &sc->sc_txchainmask);
660
661		ic->ic_txstream = txs;
662		ic->ic_rxstream = rxs;
663
664		device_printf(sc->sc_dev, "[HT] %d RX streams; %d TX streams\n", rxs, txs);
665	}
666#endif
667
668	/*
669	 * Indicate we need the 802.11 header padded to a
670	 * 32-bit boundary for 4-address and QoS frames.
671	 */
672	ic->ic_flags |= IEEE80211_F_DATAPAD;
673
674	/*
675	 * Query the hal about antenna support.
676	 */
677	sc->sc_defant = ath_hal_getdefantenna(ah);
678
679	/*
680	 * Not all chips have the VEOL support we want to
681	 * use with IBSS beacons; check here for it.
682	 */
683	sc->sc_hasveol = ath_hal_hasveol(ah);
684
685	/* get mac address from hardware */
686	ath_hal_getmac(ah, macaddr);
687	if (sc->sc_hasbmask)
688		ath_hal_getbssidmask(ah, sc->sc_hwbssidmask);
689
690	/* NB: used to size node table key mapping array */
691	ic->ic_max_keyix = sc->sc_keymax;
692	/* call MI attach routine. */
693	ieee80211_ifattach(ic, macaddr);
694	ic->ic_setregdomain = ath_setregdomain;
695	ic->ic_getradiocaps = ath_getradiocaps;
696	sc->sc_opmode = HAL_M_STA;
697
698	/* override default methods */
699	ic->ic_newassoc = ath_newassoc;
700	ic->ic_updateslot = ath_updateslot;
701	ic->ic_wme.wme_update = ath_wme_update;
702	ic->ic_vap_create = ath_vap_create;
703	ic->ic_vap_delete = ath_vap_delete;
704	ic->ic_raw_xmit = ath_raw_xmit;
705	ic->ic_update_mcast = ath_update_mcast;
706	ic->ic_update_promisc = ath_update_promisc;
707	ic->ic_node_alloc = ath_node_alloc;
708	sc->sc_node_free = ic->ic_node_free;
709	ic->ic_node_free = ath_node_free;
710	ic->ic_node_getsignal = ath_node_getsignal;
711	ic->ic_scan_start = ath_scan_start;
712	ic->ic_scan_end = ath_scan_end;
713	ic->ic_set_channel = ath_set_channel;
714
715	ieee80211_radiotap_attach(ic,
716	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
717		ATH_TX_RADIOTAP_PRESENT,
718	    &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
719		ATH_RX_RADIOTAP_PRESENT);
720
721	/*
722	 * Setup dynamic sysctl's now that country code and
723	 * regdomain are available from the hal.
724	 */
725	ath_sysctlattach(sc);
726	ath_sysctl_stats_attach(sc);
727
728	if (bootverbose)
729		ieee80211_announce(ic);
730	ath_announce(sc);
731	return 0;
732bad2:
733	ath_tx_cleanup(sc);
734	ath_desc_free(sc);
735bad:
736	if (ah)
737		ath_hal_detach(ah);
738	if (ifp != NULL)
739		if_free(ifp);
740	sc->sc_invalid = 1;
741	return error;
742}
743
744int
745ath_detach(struct ath_softc *sc)
746{
747	struct ifnet *ifp = sc->sc_ifp;
748
749	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
750		__func__, ifp->if_flags);
751
752	/*
753	 * NB: the order of these is important:
754	 * o stop the chip so no more interrupts will fire
755	 * o call the 802.11 layer before detaching the hal to
756	 *   insure callbacks into the driver to delete global
757	 *   key cache entries can be handled
758	 * o free the taskqueue which drains any pending tasks
759	 * o reclaim the tx queue data structures after calling
760	 *   the 802.11 layer as we'll get called back to reclaim
761	 *   node state and potentially want to use them
762	 * o to cleanup the tx queues the hal is called, so detach
763	 *   it last
764	 * Other than that, it's straightforward...
765	 */
766	ath_stop(ifp);
767	ieee80211_ifdetach(ifp->if_l2com);
768	taskqueue_free(sc->sc_tq);
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	ic_opmode = opmode;		/* default to opmode of new vap */
867	switch (opmode) {
868	case IEEE80211_M_STA:
869		if (sc->sc_nstavaps != 0) {	/* XXX only 1 for now */
870			device_printf(sc->sc_dev, "only 1 sta vap supported\n");
871			goto bad;
872		}
873		if (sc->sc_nvaps) {
874			/*
875			 * With multiple vaps we must fall back
876			 * to s/w beacon miss handling.
877			 */
878			flags |= IEEE80211_CLONE_NOBEACONS;
879		}
880		if (flags & IEEE80211_CLONE_NOBEACONS) {
881			/*
882			 * Station mode w/o beacons are implemented w/ AP mode.
883			 */
884			ic_opmode = IEEE80211_M_HOSTAP;
885		}
886		break;
887	case IEEE80211_M_IBSS:
888		if (sc->sc_nvaps != 0) {	/* XXX only 1 for now */
889			device_printf(sc->sc_dev,
890			    "only 1 ibss vap supported\n");
891			goto bad;
892		}
893		needbeacon = 1;
894		break;
895	case IEEE80211_M_AHDEMO:
896#ifdef IEEE80211_SUPPORT_TDMA
897		if (flags & IEEE80211_CLONE_TDMA) {
898			if (sc->sc_nvaps != 0) {
899				device_printf(sc->sc_dev,
900				    "only 1 tdma vap supported\n");
901				goto bad;
902			}
903			needbeacon = 1;
904			flags |= IEEE80211_CLONE_NOBEACONS;
905		}
906		/* fall thru... */
907#endif
908	case IEEE80211_M_MONITOR:
909		if (sc->sc_nvaps != 0 && ic->ic_opmode != opmode) {
910			/*
911			 * Adopt existing mode.  Adding a monitor or ahdemo
912			 * vap to an existing configuration is of dubious
913			 * value but should be ok.
914			 */
915			/* XXX not right for monitor mode */
916			ic_opmode = ic->ic_opmode;
917		}
918		break;
919	case IEEE80211_M_HOSTAP:
920	case IEEE80211_M_MBSS:
921		needbeacon = 1;
922		break;
923	case IEEE80211_M_WDS:
924		if (sc->sc_nvaps != 0 && ic->ic_opmode == IEEE80211_M_STA) {
925			device_printf(sc->sc_dev,
926			    "wds not supported in sta mode\n");
927			goto bad;
928		}
929		/*
930		 * Silently remove any request for a unique
931		 * bssid; WDS vap's always share the local
932		 * mac address.
933		 */
934		flags &= ~IEEE80211_CLONE_BSSID;
935		if (sc->sc_nvaps == 0)
936			ic_opmode = IEEE80211_M_HOSTAP;
937		else
938			ic_opmode = ic->ic_opmode;
939		break;
940	default:
941		device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
942		goto bad;
943	}
944	/*
945	 * Check that a beacon buffer is available; the code below assumes it.
946	 */
947	if (needbeacon & STAILQ_EMPTY(&sc->sc_bbuf)) {
948		device_printf(sc->sc_dev, "no beacon buffer available\n");
949		goto bad;
950	}
951
952	/* STA, AHDEMO? */
953	if (opmode == IEEE80211_M_HOSTAP || opmode == IEEE80211_M_MBSS) {
954		assign_address(sc, mac, flags & IEEE80211_CLONE_BSSID);
955		ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
956	}
957
958	vap = &avp->av_vap;
959	/* XXX can't hold mutex across if_alloc */
960	ATH_UNLOCK(sc);
961	error = ieee80211_vap_setup(ic, vap, name, unit, opmode, flags,
962	    bssid, mac);
963	ATH_LOCK(sc);
964	if (error != 0) {
965		device_printf(sc->sc_dev, "%s: error %d creating vap\n",
966		    __func__, error);
967		goto bad2;
968	}
969
970	/* h/w crypto support */
971	vap->iv_key_alloc = ath_key_alloc;
972	vap->iv_key_delete = ath_key_delete;
973	vap->iv_key_set = ath_key_set;
974	vap->iv_key_update_begin = ath_key_update_begin;
975	vap->iv_key_update_end = ath_key_update_end;
976
977	/* override various methods */
978	avp->av_recv_mgmt = vap->iv_recv_mgmt;
979	vap->iv_recv_mgmt = ath_recv_mgmt;
980	vap->iv_reset = ath_reset_vap;
981	vap->iv_update_beacon = ath_beacon_update;
982	avp->av_newstate = vap->iv_newstate;
983	vap->iv_newstate = ath_newstate;
984	avp->av_bmiss = vap->iv_bmiss;
985	vap->iv_bmiss = ath_bmiss_vap;
986
987	avp->av_bslot = -1;
988	if (needbeacon) {
989		/*
990		 * Allocate beacon state and setup the q for buffered
991		 * multicast frames.  We know a beacon buffer is
992		 * available because we checked above.
993		 */
994		avp->av_bcbuf = STAILQ_FIRST(&sc->sc_bbuf);
995		STAILQ_REMOVE_HEAD(&sc->sc_bbuf, bf_list);
996		if (opmode != IEEE80211_M_IBSS || !sc->sc_hasveol) {
997			/*
998			 * Assign the vap to a beacon xmit slot.  As above
999			 * this cannot fail to find a free one.
1000			 */
1001			avp->av_bslot = assign_bslot(sc);
1002			KASSERT(sc->sc_bslot[avp->av_bslot] == NULL,
1003			    ("beacon slot %u not empty", avp->av_bslot));
1004			sc->sc_bslot[avp->av_bslot] = vap;
1005			sc->sc_nbcnvaps++;
1006		}
1007		if (sc->sc_hastsfadd && sc->sc_nbcnvaps > 0) {
1008			/*
1009			 * Multple vaps are to transmit beacons and we
1010			 * have h/w support for TSF adjusting; enable
1011			 * use of staggered beacons.
1012			 */
1013			sc->sc_stagbeacons = 1;
1014		}
1015		ath_txq_init(sc, &avp->av_mcastq, ATH_TXQ_SWQ);
1016	}
1017
1018	ic->ic_opmode = ic_opmode;
1019	if (opmode != IEEE80211_M_WDS) {
1020		sc->sc_nvaps++;
1021		if (opmode == IEEE80211_M_STA)
1022			sc->sc_nstavaps++;
1023		if (opmode == IEEE80211_M_MBSS)
1024			sc->sc_nmeshvaps++;
1025	}
1026	switch (ic_opmode) {
1027	case IEEE80211_M_IBSS:
1028		sc->sc_opmode = HAL_M_IBSS;
1029		break;
1030	case IEEE80211_M_STA:
1031		sc->sc_opmode = HAL_M_STA;
1032		break;
1033	case IEEE80211_M_AHDEMO:
1034#ifdef IEEE80211_SUPPORT_TDMA
1035		if (vap->iv_caps & IEEE80211_C_TDMA) {
1036			sc->sc_tdma = 1;
1037			/* NB: disable tsf adjust */
1038			sc->sc_stagbeacons = 0;
1039		}
1040		/*
1041		 * NB: adhoc demo mode is a pseudo mode; to the hal it's
1042		 * just ap mode.
1043		 */
1044		/* fall thru... */
1045#endif
1046	case IEEE80211_M_HOSTAP:
1047	case IEEE80211_M_MBSS:
1048		sc->sc_opmode = HAL_M_HOSTAP;
1049		break;
1050	case IEEE80211_M_MONITOR:
1051		sc->sc_opmode = HAL_M_MONITOR;
1052		break;
1053	default:
1054		/* XXX should not happen */
1055		break;
1056	}
1057	if (sc->sc_hastsfadd) {
1058		/*
1059		 * Configure whether or not TSF adjust should be done.
1060		 */
1061		ath_hal_settsfadjust(sc->sc_ah, sc->sc_stagbeacons);
1062	}
1063	if (flags & IEEE80211_CLONE_NOBEACONS) {
1064		/*
1065		 * Enable s/w beacon miss handling.
1066		 */
1067		sc->sc_swbmiss = 1;
1068	}
1069	ATH_UNLOCK(sc);
1070
1071	/* complete setup */
1072	ieee80211_vap_attach(vap, ath_media_change, ieee80211_media_status);
1073	return vap;
1074bad2:
1075	reclaim_address(sc, mac);
1076	ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
1077bad:
1078	free(avp, M_80211_VAP);
1079	ATH_UNLOCK(sc);
1080	return NULL;
1081}
1082
1083static void
1084ath_vap_delete(struct ieee80211vap *vap)
1085{
1086	struct ieee80211com *ic = vap->iv_ic;
1087	struct ifnet *ifp = ic->ic_ifp;
1088	struct ath_softc *sc = ifp->if_softc;
1089	struct ath_hal *ah = sc->sc_ah;
1090	struct ath_vap *avp = ATH_VAP(vap);
1091
1092	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1093		/*
1094		 * Quiesce the hardware while we remove the vap.  In
1095		 * particular we need to reclaim all references to
1096		 * the vap state by any frames pending on the tx queues.
1097		 */
1098		ath_hal_intrset(ah, 0);		/* disable interrupts */
1099		ath_draintxq(sc);		/* stop xmit side */
1100		ath_stoprecv(sc);		/* stop recv side */
1101	}
1102
1103	ieee80211_vap_detach(vap);
1104	ATH_LOCK(sc);
1105	/*
1106	 * Reclaim beacon state.  Note this must be done before
1107	 * the vap instance is reclaimed as we may have a reference
1108	 * to it in the buffer for the beacon frame.
1109	 */
1110	if (avp->av_bcbuf != NULL) {
1111		if (avp->av_bslot != -1) {
1112			sc->sc_bslot[avp->av_bslot] = NULL;
1113			sc->sc_nbcnvaps--;
1114		}
1115		ath_beacon_return(sc, avp->av_bcbuf);
1116		avp->av_bcbuf = NULL;
1117		if (sc->sc_nbcnvaps == 0) {
1118			sc->sc_stagbeacons = 0;
1119			if (sc->sc_hastsfadd)
1120				ath_hal_settsfadjust(sc->sc_ah, 0);
1121		}
1122		/*
1123		 * Reclaim any pending mcast frames for the vap.
1124		 */
1125		ath_tx_draintxq(sc, &avp->av_mcastq);
1126		ATH_TXQ_LOCK_DESTROY(&avp->av_mcastq);
1127	}
1128	/*
1129	 * Update bookkeeping.
1130	 */
1131	if (vap->iv_opmode == IEEE80211_M_STA) {
1132		sc->sc_nstavaps--;
1133		if (sc->sc_nstavaps == 0 && sc->sc_swbmiss)
1134			sc->sc_swbmiss = 0;
1135	} else if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1136	    vap->iv_opmode == IEEE80211_M_MBSS) {
1137		reclaim_address(sc, vap->iv_myaddr);
1138		ath_hal_setbssidmask(ah, sc->sc_hwbssidmask);
1139		if (vap->iv_opmode == IEEE80211_M_MBSS)
1140			sc->sc_nmeshvaps--;
1141	}
1142	if (vap->iv_opmode != IEEE80211_M_WDS)
1143		sc->sc_nvaps--;
1144#ifdef IEEE80211_SUPPORT_TDMA
1145	/* TDMA operation ceases when the last vap is destroyed */
1146	if (sc->sc_tdma && sc->sc_nvaps == 0) {
1147		sc->sc_tdma = 0;
1148		sc->sc_swbmiss = 0;
1149	}
1150#endif
1151	ATH_UNLOCK(sc);
1152	free(avp, M_80211_VAP);
1153
1154	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1155		/*
1156		 * Restart rx+tx machines if still running (RUNNING will
1157		 * be reset if we just destroyed the last vap).
1158		 */
1159		if (ath_startrecv(sc) != 0)
1160			if_printf(ifp, "%s: unable to restart recv logic\n",
1161			    __func__);
1162		if (sc->sc_beacons) {		/* restart beacons */
1163#ifdef IEEE80211_SUPPORT_TDMA
1164			if (sc->sc_tdma)
1165				ath_tdma_config(sc, NULL);
1166			else
1167#endif
1168				ath_beacon_config(sc, NULL);
1169		}
1170		ath_hal_intrset(ah, sc->sc_imask);
1171	}
1172}
1173
1174void
1175ath_suspend(struct ath_softc *sc)
1176{
1177	struct ifnet *ifp = sc->sc_ifp;
1178	struct ieee80211com *ic = ifp->if_l2com;
1179
1180	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1181		__func__, ifp->if_flags);
1182
1183	sc->sc_resume_up = (ifp->if_flags & IFF_UP) != 0;
1184	if (ic->ic_opmode == IEEE80211_M_STA)
1185		ath_stop(ifp);
1186	else
1187		ieee80211_suspend_all(ic);
1188	/*
1189	 * NB: don't worry about putting the chip in low power
1190	 * mode; pci will power off our socket on suspend and
1191	 * CardBus detaches the device.
1192	 */
1193}
1194
1195/*
1196 * Reset the key cache since some parts do not reset the
1197 * contents on resume.  First we clear all entries, then
1198 * re-load keys that the 802.11 layer assumes are setup
1199 * in h/w.
1200 */
1201static void
1202ath_reset_keycache(struct ath_softc *sc)
1203{
1204	struct ifnet *ifp = sc->sc_ifp;
1205	struct ieee80211com *ic = ifp->if_l2com;
1206	struct ath_hal *ah = sc->sc_ah;
1207	int i;
1208
1209	for (i = 0; i < sc->sc_keymax; i++)
1210		ath_hal_keyreset(ah, i);
1211	ieee80211_crypto_reload_keys(ic);
1212}
1213
1214void
1215ath_resume(struct ath_softc *sc)
1216{
1217	struct ifnet *ifp = sc->sc_ifp;
1218	struct ieee80211com *ic = ifp->if_l2com;
1219	struct ath_hal *ah = sc->sc_ah;
1220	HAL_STATUS status;
1221
1222	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1223		__func__, ifp->if_flags);
1224
1225	/*
1226	 * Must reset the chip before we reload the
1227	 * keycache as we were powered down on suspend.
1228	 */
1229	ath_hal_reset(ah, sc->sc_opmode,
1230	    sc->sc_curchan != NULL ? sc->sc_curchan : ic->ic_curchan,
1231	    AH_FALSE, &status);
1232	ath_reset_keycache(sc);
1233	if (sc->sc_resume_up) {
1234		if (ic->ic_opmode == IEEE80211_M_STA) {
1235			ath_init(sc);
1236			/*
1237			 * Program the beacon registers using the last rx'd
1238			 * beacon frame and enable sync on the next beacon
1239			 * we see.  This should handle the case where we
1240			 * wakeup and find the same AP and also the case where
1241			 * we wakeup and need to roam.  For the latter we
1242			 * should get bmiss events that trigger a roam.
1243			 */
1244			ath_beacon_config(sc, NULL);
1245			sc->sc_syncbeacon = 1;
1246		} else
1247			ieee80211_resume_all(ic);
1248	}
1249	if (sc->sc_softled) {
1250		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin,
1251		    HAL_GPIO_MUX_MAC_NETWORK_LED);
1252		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
1253	}
1254}
1255
1256void
1257ath_shutdown(struct ath_softc *sc)
1258{
1259	struct ifnet *ifp = sc->sc_ifp;
1260
1261	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1262		__func__, ifp->if_flags);
1263
1264	ath_stop(ifp);
1265	/* NB: no point powering down chip as we're about to reboot */
1266}
1267
1268/*
1269 * Interrupt handler.  Most of the actual processing is deferred.
1270 */
1271void
1272ath_intr(void *arg)
1273{
1274	struct ath_softc *sc = arg;
1275	struct ifnet *ifp = sc->sc_ifp;
1276	struct ath_hal *ah = sc->sc_ah;
1277	HAL_INT status = 0;
1278
1279	if (sc->sc_invalid) {
1280		/*
1281		 * The hardware is not ready/present, don't touch anything.
1282		 * Note this can happen early on if the IRQ is shared.
1283		 */
1284		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
1285		return;
1286	}
1287	if (!ath_hal_intrpend(ah))		/* shared irq, not for us */
1288		return;
1289	if ((ifp->if_flags & IFF_UP) == 0 ||
1290	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1291		HAL_INT status;
1292
1293		DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1294			__func__, ifp->if_flags);
1295		ath_hal_getisr(ah, &status);	/* clear ISR */
1296		ath_hal_intrset(ah, 0);		/* disable further intr's */
1297		return;
1298	}
1299	/*
1300	 * Figure out the reason(s) for the interrupt.  Note
1301	 * that the hal returns a pseudo-ISR that may include
1302	 * bits we haven't explicitly enabled so we mask the
1303	 * value to insure we only process bits we requested.
1304	 */
1305	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
1306	DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
1307	status &= sc->sc_imask;			/* discard unasked for bits */
1308
1309	/* Short-circuit un-handled interrupts */
1310	if (status == 0x0)
1311		return;
1312
1313	if (status & HAL_INT_FATAL) {
1314		sc->sc_stats.ast_hardware++;
1315		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
1316		ath_fatal_proc(sc, 0);
1317	} else {
1318		if (status & HAL_INT_SWBA) {
1319			/*
1320			 * Software beacon alert--time to send a beacon.
1321			 * Handle beacon transmission directly; deferring
1322			 * this is too slow to meet timing constraints
1323			 * under load.
1324			 */
1325#ifdef IEEE80211_SUPPORT_TDMA
1326			if (sc->sc_tdma) {
1327				if (sc->sc_tdmaswba == 0) {
1328					struct ieee80211com *ic = ifp->if_l2com;
1329					struct ieee80211vap *vap =
1330					    TAILQ_FIRST(&ic->ic_vaps);
1331					ath_tdma_beacon_send(sc, vap);
1332					sc->sc_tdmaswba =
1333					    vap->iv_tdma->tdma_bintval;
1334				} else
1335					sc->sc_tdmaswba--;
1336			} else
1337#endif
1338			{
1339				ath_beacon_proc(sc, 0);
1340#ifdef IEEE80211_SUPPORT_SUPERG
1341				/*
1342				 * Schedule the rx taskq in case there's no
1343				 * traffic so any frames held on the staging
1344				 * queue are aged and potentially flushed.
1345				 */
1346				taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1347#endif
1348			}
1349		}
1350		if (status & HAL_INT_RXEOL) {
1351			/*
1352			 * NB: the hardware should re-read the link when
1353			 *     RXE bit is written, but it doesn't work at
1354			 *     least on older hardware revs.
1355			 */
1356			sc->sc_stats.ast_rxeol++;
1357			sc->sc_rxlink = NULL;
1358		}
1359		if (status & HAL_INT_TXURN) {
1360			sc->sc_stats.ast_txurn++;
1361			/* bump tx trigger level */
1362			ath_hal_updatetxtriglevel(ah, AH_TRUE);
1363		}
1364		if (status & HAL_INT_RX)
1365			taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1366		if (status & HAL_INT_TX)
1367			taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
1368		if (status & HAL_INT_BMISS) {
1369			sc->sc_stats.ast_bmiss++;
1370			taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
1371		}
1372		if (status & HAL_INT_GTT)
1373			sc->sc_stats.ast_tx_timeout++;
1374		if (status & HAL_INT_CST)
1375			sc->sc_stats.ast_tx_cst++;
1376		if (status & HAL_INT_MIB) {
1377			sc->sc_stats.ast_mib++;
1378			/*
1379			 * Disable interrupts until we service the MIB
1380			 * interrupt; otherwise it will continue to fire.
1381			 */
1382			ath_hal_intrset(ah, 0);
1383			/*
1384			 * Let the hal handle the event.  We assume it will
1385			 * clear whatever condition caused the interrupt.
1386			 */
1387			ath_hal_mibevent(ah, &sc->sc_halstats);
1388			ath_hal_intrset(ah, sc->sc_imask);
1389		}
1390		if (status & HAL_INT_RXORN) {
1391			/* NB: hal marks HAL_INT_FATAL when RXORN is fatal */
1392			sc->sc_stats.ast_rxorn++;
1393		}
1394	}
1395}
1396
1397static void
1398ath_fatal_proc(void *arg, int pending)
1399{
1400	struct ath_softc *sc = arg;
1401	struct ifnet *ifp = sc->sc_ifp;
1402	u_int32_t *state;
1403	u_int32_t len;
1404	void *sp;
1405
1406	if_printf(ifp, "hardware error; resetting\n");
1407	/*
1408	 * Fatal errors are unrecoverable.  Typically these
1409	 * are caused by DMA errors.  Collect h/w state from
1410	 * the hal so we can diagnose what's going on.
1411	 */
1412	if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
1413		KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
1414		state = sp;
1415		if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
1416		    state[0], state[1] , state[2], state[3],
1417		    state[4], state[5]);
1418	}
1419	ath_reset(ifp);
1420}
1421
1422static void
1423ath_bmiss_vap(struct ieee80211vap *vap)
1424{
1425	/*
1426	 * Workaround phantom bmiss interrupts by sanity-checking
1427	 * the time of our last rx'd frame.  If it is within the
1428	 * beacon miss interval then ignore the interrupt.  If it's
1429	 * truly a bmiss we'll get another interrupt soon and that'll
1430	 * be dispatched up for processing.  Note this applies only
1431	 * for h/w beacon miss events.
1432	 */
1433	if ((vap->iv_flags_ext & IEEE80211_FEXT_SWBMISS) == 0) {
1434		struct ifnet *ifp = vap->iv_ic->ic_ifp;
1435		struct ath_softc *sc = ifp->if_softc;
1436		u_int64_t lastrx = sc->sc_lastrx;
1437		u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
1438		u_int bmisstimeout =
1439			vap->iv_bmissthreshold * vap->iv_bss->ni_intval * 1024;
1440
1441		DPRINTF(sc, ATH_DEBUG_BEACON,
1442		    "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
1443		    __func__, (unsigned long long) tsf,
1444		    (unsigned long long)(tsf - lastrx),
1445		    (unsigned long long) lastrx, bmisstimeout);
1446
1447		if (tsf - lastrx <= bmisstimeout) {
1448			sc->sc_stats.ast_bmiss_phantom++;
1449			return;
1450		}
1451	}
1452	ATH_VAP(vap)->av_bmiss(vap);
1453}
1454
1455static int
1456ath_hal_gethangstate(struct ath_hal *ah, uint32_t mask, uint32_t *hangs)
1457{
1458	uint32_t rsize;
1459	void *sp;
1460
1461	if (!ath_hal_getdiagstate(ah, HAL_DIAG_CHECK_HANGS, &mask, sizeof(mask), &sp, &rsize))
1462		return 0;
1463	KASSERT(rsize == sizeof(uint32_t), ("resultsize %u", rsize));
1464	*hangs = *(uint32_t *)sp;
1465	return 1;
1466}
1467
1468static void
1469ath_bmiss_proc(void *arg, int pending)
1470{
1471	struct ath_softc *sc = arg;
1472	struct ifnet *ifp = sc->sc_ifp;
1473	uint32_t hangs;
1474
1475	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
1476
1477	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0) {
1478		if_printf(ifp, "bb hang detected (0x%x), resetting\n", hangs);
1479		ath_reset(ifp);
1480	} else
1481		ieee80211_beacon_miss(ifp->if_l2com);
1482}
1483
1484/*
1485 * Handle TKIP MIC setup to deal hardware that doesn't do MIC
1486 * calcs together with WME.  If necessary disable the crypto
1487 * hardware and mark the 802.11 state so keys will be setup
1488 * with the MIC work done in software.
1489 */
1490static void
1491ath_settkipmic(struct ath_softc *sc)
1492{
1493	struct ifnet *ifp = sc->sc_ifp;
1494	struct ieee80211com *ic = ifp->if_l2com;
1495
1496	if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
1497		if (ic->ic_flags & IEEE80211_F_WME) {
1498			ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
1499			ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
1500		} else {
1501			ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
1502			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
1503		}
1504	}
1505}
1506
1507static void
1508ath_init(void *arg)
1509{
1510	struct ath_softc *sc = (struct ath_softc *) arg;
1511	struct ifnet *ifp = sc->sc_ifp;
1512	struct ieee80211com *ic = ifp->if_l2com;
1513	struct ath_hal *ah = sc->sc_ah;
1514	HAL_STATUS status;
1515
1516	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1517		__func__, ifp->if_flags);
1518
1519	ATH_LOCK(sc);
1520	/*
1521	 * Stop anything previously setup.  This is safe
1522	 * whether this is the first time through or not.
1523	 */
1524	ath_stop_locked(ifp);
1525
1526	/*
1527	 * The basic interface to setting the hardware in a good
1528	 * state is ``reset''.  On return the hardware is known to
1529	 * be powered up and with interrupts disabled.  This must
1530	 * be followed by initialization of the appropriate bits
1531	 * and then setup of the interrupt mask.
1532	 */
1533	ath_settkipmic(sc);
1534	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_FALSE, &status)) {
1535		if_printf(ifp, "unable to reset hardware; hal status %u\n",
1536			status);
1537		ATH_UNLOCK(sc);
1538		return;
1539	}
1540	ath_chan_change(sc, ic->ic_curchan);
1541
1542	/*
1543	 * Likewise this is set during reset so update
1544	 * state cached in the driver.
1545	 */
1546	sc->sc_diversity = ath_hal_getdiversity(ah);
1547	sc->sc_lastlongcal = 0;
1548	sc->sc_resetcal = 1;
1549	sc->sc_lastcalreset = 0;
1550	sc->sc_lastani = 0;
1551	sc->sc_lastshortcal = 0;
1552	sc->sc_doresetcal = AH_FALSE;
1553
1554	/*
1555	 * Setup the hardware after reset: the key cache
1556	 * is filled as needed and the receive engine is
1557	 * set going.  Frame transmit is handled entirely
1558	 * in the frame output path; there's nothing to do
1559	 * here except setup the interrupt mask.
1560	 */
1561	if (ath_startrecv(sc) != 0) {
1562		if_printf(ifp, "unable to start recv logic\n");
1563		ATH_UNLOCK(sc);
1564		return;
1565	}
1566
1567	/*
1568	 * Enable interrupts.
1569	 */
1570	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
1571		  | HAL_INT_RXEOL | HAL_INT_RXORN
1572		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
1573	/*
1574	 * Enable MIB interrupts when there are hardware phy counters.
1575	 * Note we only do this (at the moment) for station mode.
1576	 */
1577	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
1578		sc->sc_imask |= HAL_INT_MIB;
1579
1580	/* Enable global TX timeout and carrier sense timeout if available */
1581	if (ath_hal_gtxto_supported(ah))
1582		sc->sc_imask |= HAL_INT_GTT;
1583
1584	DPRINTF(sc, ATH_DEBUG_RESET, "%s: imask=0x%x\n",
1585		__func__, sc->sc_imask);
1586
1587	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1588	callout_reset(&sc->sc_wd_ch, hz, ath_watchdog, sc);
1589	ath_hal_intrset(ah, sc->sc_imask);
1590
1591	ATH_UNLOCK(sc);
1592
1593#ifdef ATH_TX99_DIAG
1594	if (sc->sc_tx99 != NULL)
1595		sc->sc_tx99->start(sc->sc_tx99);
1596	else
1597#endif
1598	ieee80211_start_all(ic);		/* start all vap's */
1599}
1600
1601static void
1602ath_stop_locked(struct ifnet *ifp)
1603{
1604	struct ath_softc *sc = ifp->if_softc;
1605	struct ath_hal *ah = sc->sc_ah;
1606
1607	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1608		__func__, sc->sc_invalid, ifp->if_flags);
1609
1610	ATH_LOCK_ASSERT(sc);
1611	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1612		/*
1613		 * Shutdown the hardware and driver:
1614		 *    reset 802.11 state machine
1615		 *    turn off timers
1616		 *    disable interrupts
1617		 *    turn off the radio
1618		 *    clear transmit machinery
1619		 *    clear receive machinery
1620		 *    drain and release tx queues
1621		 *    reclaim beacon resources
1622		 *    power down hardware
1623		 *
1624		 * Note that some of this work is not possible if the
1625		 * hardware is gone (invalid).
1626		 */
1627#ifdef ATH_TX99_DIAG
1628		if (sc->sc_tx99 != NULL)
1629			sc->sc_tx99->stop(sc->sc_tx99);
1630#endif
1631		callout_stop(&sc->sc_wd_ch);
1632		sc->sc_wd_timer = 0;
1633		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1634		if (!sc->sc_invalid) {
1635			if (sc->sc_softled) {
1636				callout_stop(&sc->sc_ledtimer);
1637				ath_hal_gpioset(ah, sc->sc_ledpin,
1638					!sc->sc_ledon);
1639				sc->sc_blinking = 0;
1640			}
1641			ath_hal_intrset(ah, 0);
1642		}
1643		ath_draintxq(sc);
1644		if (!sc->sc_invalid) {
1645			ath_stoprecv(sc);
1646			ath_hal_phydisable(ah);
1647		} else
1648			sc->sc_rxlink = NULL;
1649		ath_beacon_free(sc);	/* XXX not needed */
1650	}
1651}
1652
1653static void
1654ath_stop(struct ifnet *ifp)
1655{
1656	struct ath_softc *sc = ifp->if_softc;
1657
1658	ATH_LOCK(sc);
1659	ath_stop_locked(ifp);
1660	ATH_UNLOCK(sc);
1661}
1662
1663/*
1664 * Reset the hardware w/o losing operational state.  This is
1665 * basically a more efficient way of doing ath_stop, ath_init,
1666 * followed by state transitions to the current 802.11
1667 * operational state.  Used to recover from various errors and
1668 * to reset or reload hardware state.
1669 */
1670int
1671ath_reset(struct ifnet *ifp)
1672{
1673	struct ath_softc *sc = ifp->if_softc;
1674	struct ieee80211com *ic = ifp->if_l2com;
1675	struct ath_hal *ah = sc->sc_ah;
1676	HAL_STATUS status;
1677
1678	ath_hal_intrset(ah, 0);		/* disable interrupts */
1679	ath_draintxq(sc);		/* stop xmit side */
1680	ath_stoprecv(sc);		/* stop recv side */
1681	ath_settkipmic(sc);		/* configure TKIP MIC handling */
1682	/* NB: indicate channel change so we do a full reset */
1683	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_TRUE, &status))
1684		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
1685			__func__, status);
1686	sc->sc_diversity = ath_hal_getdiversity(ah);
1687	if (ath_startrecv(sc) != 0)	/* restart recv */
1688		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
1689	/*
1690	 * We may be doing a reset in response to an ioctl
1691	 * that changes the channel so update any state that
1692	 * might change as a result.
1693	 */
1694	ath_chan_change(sc, ic->ic_curchan);
1695	if (sc->sc_beacons) {		/* restart beacons */
1696#ifdef IEEE80211_SUPPORT_TDMA
1697		if (sc->sc_tdma)
1698			ath_tdma_config(sc, NULL);
1699		else
1700#endif
1701			ath_beacon_config(sc, NULL);
1702	}
1703	ath_hal_intrset(ah, sc->sc_imask);
1704
1705	ath_start(ifp);			/* restart xmit */
1706	return 0;
1707}
1708
1709static int
1710ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
1711{
1712	struct ieee80211com *ic = vap->iv_ic;
1713	struct ifnet *ifp = ic->ic_ifp;
1714	struct ath_softc *sc = ifp->if_softc;
1715	struct ath_hal *ah = sc->sc_ah;
1716
1717	switch (cmd) {
1718	case IEEE80211_IOC_TXPOWER:
1719		/*
1720		 * If per-packet TPC is enabled, then we have nothing
1721		 * to do; otherwise we need to force the global limit.
1722		 * All this can happen directly; no need to reset.
1723		 */
1724		if (!ath_hal_gettpc(ah))
1725			ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
1726		return 0;
1727	}
1728	return ath_reset(ifp);
1729}
1730
1731struct ath_buf *
1732_ath_getbuf_locked(struct ath_softc *sc)
1733{
1734	struct ath_buf *bf;
1735
1736	ATH_TXBUF_LOCK_ASSERT(sc);
1737
1738	bf = STAILQ_FIRST(&sc->sc_txbuf);
1739	if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0)
1740		STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
1741	else
1742		bf = NULL;
1743	if (bf == NULL) {
1744		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
1745		    STAILQ_FIRST(&sc->sc_txbuf) == NULL ?
1746			"out of xmit buffers" : "xmit buffer busy");
1747	}
1748	return bf;
1749}
1750
1751struct ath_buf *
1752ath_getbuf(struct ath_softc *sc)
1753{
1754	struct ath_buf *bf;
1755
1756	ATH_TXBUF_LOCK(sc);
1757	bf = _ath_getbuf_locked(sc);
1758	if (bf == NULL) {
1759		struct ifnet *ifp = sc->sc_ifp;
1760
1761		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
1762		sc->sc_stats.ast_tx_qstop++;
1763		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1764	}
1765	ATH_TXBUF_UNLOCK(sc);
1766	return bf;
1767}
1768
1769static void
1770ath_start(struct ifnet *ifp)
1771{
1772	struct ath_softc *sc = ifp->if_softc;
1773	struct ieee80211_node *ni;
1774	struct ath_buf *bf;
1775	struct mbuf *m, *next;
1776	ath_bufhead frags;
1777
1778	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
1779		return;
1780	for (;;) {
1781		/*
1782		 * Grab a TX buffer and associated resources.
1783		 */
1784		bf = ath_getbuf(sc);
1785		if (bf == NULL)
1786			break;
1787
1788		IFQ_DEQUEUE(&ifp->if_snd, m);
1789		if (m == NULL) {
1790			ATH_TXBUF_LOCK(sc);
1791			STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1792			ATH_TXBUF_UNLOCK(sc);
1793			break;
1794		}
1795		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1796		/*
1797		 * Check for fragmentation.  If this frame
1798		 * has been broken up verify we have enough
1799		 * buffers to send all the fragments so all
1800		 * go out or none...
1801		 */
1802		STAILQ_INIT(&frags);
1803		if ((m->m_flags & M_FRAG) &&
1804		    !ath_txfrag_setup(sc, &frags, m, ni)) {
1805			DPRINTF(sc, ATH_DEBUG_XMIT,
1806			    "%s: out of txfrag buffers\n", __func__);
1807			sc->sc_stats.ast_tx_nofrag++;
1808			ifp->if_oerrors++;
1809			ath_freetx(m);
1810			goto bad;
1811		}
1812		ifp->if_opackets++;
1813	nextfrag:
1814		/*
1815		 * Pass the frame to the h/w for transmission.
1816		 * Fragmented frames have each frag chained together
1817		 * with m_nextpkt.  We know there are sufficient ath_buf's
1818		 * to send all the frags because of work done by
1819		 * ath_txfrag_setup.  We leave m_nextpkt set while
1820		 * calling ath_tx_start so it can use it to extend the
1821		 * the tx duration to cover the subsequent frag and
1822		 * so it can reclaim all the mbufs in case of an error;
1823		 * ath_tx_start clears m_nextpkt once it commits to
1824		 * handing the frame to the hardware.
1825		 */
1826		next = m->m_nextpkt;
1827		if (ath_tx_start(sc, ni, bf, m)) {
1828	bad:
1829			ifp->if_oerrors++;
1830	reclaim:
1831			bf->bf_m = NULL;
1832			bf->bf_node = NULL;
1833			ATH_TXBUF_LOCK(sc);
1834			STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1835			ath_txfrag_cleanup(sc, &frags, ni);
1836			ATH_TXBUF_UNLOCK(sc);
1837			if (ni != NULL)
1838				ieee80211_free_node(ni);
1839			continue;
1840		}
1841		if (next != NULL) {
1842			/*
1843			 * Beware of state changing between frags.
1844			 * XXX check sta power-save state?
1845			 */
1846			if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
1847				DPRINTF(sc, ATH_DEBUG_XMIT,
1848				    "%s: flush fragmented packet, state %s\n",
1849				    __func__,
1850				    ieee80211_state_name[ni->ni_vap->iv_state]);
1851				ath_freetx(next);
1852				goto reclaim;
1853			}
1854			m = next;
1855			bf = STAILQ_FIRST(&frags);
1856			KASSERT(bf != NULL, ("no buf for txfrag"));
1857			STAILQ_REMOVE_HEAD(&frags, bf_list);
1858			goto nextfrag;
1859		}
1860
1861		sc->sc_wd_timer = 5;
1862	}
1863}
1864
1865static int
1866ath_media_change(struct ifnet *ifp)
1867{
1868	int error = ieee80211_media_change(ifp);
1869	/* NB: only the fixed rate can change and that doesn't need a reset */
1870	return (error == ENETRESET ? 0 : error);
1871}
1872
1873/*
1874 * Block/unblock tx+rx processing while a key change is done.
1875 * We assume the caller serializes key management operations
1876 * so we only need to worry about synchronization with other
1877 * uses that originate in the driver.
1878 */
1879static void
1880ath_key_update_begin(struct ieee80211vap *vap)
1881{
1882	struct ifnet *ifp = vap->iv_ic->ic_ifp;
1883	struct ath_softc *sc = ifp->if_softc;
1884
1885	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
1886	taskqueue_block(sc->sc_tq);
1887	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
1888}
1889
1890static void
1891ath_key_update_end(struct ieee80211vap *vap)
1892{
1893	struct ifnet *ifp = vap->iv_ic->ic_ifp;
1894	struct ath_softc *sc = ifp->if_softc;
1895
1896	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
1897	IF_UNLOCK(&ifp->if_snd);
1898	taskqueue_unblock(sc->sc_tq);
1899}
1900
1901/*
1902 * Calculate the receive filter according to the
1903 * operating mode and state:
1904 *
1905 * o always accept unicast, broadcast, and multicast traffic
1906 * o accept PHY error frames when hardware doesn't have MIB support
1907 *   to count and we need them for ANI (sta mode only until recently)
1908 *   and we are not scanning (ANI is disabled)
1909 *   NB: older hal's add rx filter bits out of sight and we need to
1910 *	 blindly preserve them
1911 * o probe request frames are accepted only when operating in
1912 *   hostap, adhoc, mesh, or monitor modes
1913 * o enable promiscuous mode
1914 *   - when in monitor mode
1915 *   - if interface marked PROMISC (assumes bridge setting is filtered)
1916 * o accept beacons:
1917 *   - when operating in station mode for collecting rssi data when
1918 *     the station is otherwise quiet, or
1919 *   - when operating in adhoc mode so the 802.11 layer creates
1920 *     node table entries for peers,
1921 *   - when scanning
1922 *   - when doing s/w beacon miss (e.g. for ap+sta)
1923 *   - when operating in ap mode in 11g to detect overlapping bss that
1924 *     require protection
1925 *   - when operating in mesh mode to detect neighbors
1926 * o accept control frames:
1927 *   - when in monitor mode
1928 * XXX HT protection for 11n
1929 */
1930static u_int32_t
1931ath_calcrxfilter(struct ath_softc *sc)
1932{
1933	struct ifnet *ifp = sc->sc_ifp;
1934	struct ieee80211com *ic = ifp->if_l2com;
1935	u_int32_t rfilt;
1936
1937	rfilt = HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
1938	if (!sc->sc_needmib && !sc->sc_scanning)
1939		rfilt |= HAL_RX_FILTER_PHYERR;
1940	if (ic->ic_opmode != IEEE80211_M_STA)
1941		rfilt |= HAL_RX_FILTER_PROBEREQ;
1942	/* XXX ic->ic_monvaps != 0? */
1943	if (ic->ic_opmode == IEEE80211_M_MONITOR || (ifp->if_flags & IFF_PROMISC))
1944		rfilt |= HAL_RX_FILTER_PROM;
1945	if (ic->ic_opmode == IEEE80211_M_STA ||
1946	    ic->ic_opmode == IEEE80211_M_IBSS ||
1947	    sc->sc_swbmiss || sc->sc_scanning)
1948		rfilt |= HAL_RX_FILTER_BEACON;
1949	/*
1950	 * NB: We don't recalculate the rx filter when
1951	 * ic_protmode changes; otherwise we could do
1952	 * this only when ic_protmode != NONE.
1953	 */
1954	if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1955	    IEEE80211_IS_CHAN_ANYG(ic->ic_curchan))
1956		rfilt |= HAL_RX_FILTER_BEACON;
1957
1958	/*
1959	 * Enable hardware PS-POLL RX only for hostap mode;
1960	 * STA mode sends PS-POLL frames but never
1961	 * receives them.
1962	 */
1963	if (ath_hal_getcapability(sc->sc_ah, HAL_CAP_PSPOLL,
1964	    0, NULL) == HAL_OK &&
1965	    ic->ic_opmode == IEEE80211_M_HOSTAP)
1966		rfilt |= HAL_RX_FILTER_PSPOLL;
1967
1968	if (sc->sc_nmeshvaps) {
1969		rfilt |= HAL_RX_FILTER_BEACON;
1970		if (sc->sc_hasbmatch)
1971			rfilt |= HAL_RX_FILTER_BSSID;
1972		else
1973			rfilt |= HAL_RX_FILTER_PROM;
1974	}
1975	if (ic->ic_opmode == IEEE80211_M_MONITOR)
1976		rfilt |= HAL_RX_FILTER_CONTROL;
1977
1978	/*
1979	 * Enable RX of compressed BAR frames only when doing
1980	 * 802.11n. Required for A-MPDU.
1981	 */
1982	if (IEEE80211_IS_CHAN_HT(ic->ic_curchan))
1983		rfilt |= HAL_RX_FILTER_COMPBAR;
1984
1985	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, %s if_flags 0x%x\n",
1986	    __func__, rfilt, ieee80211_opmode_name[ic->ic_opmode], ifp->if_flags);
1987	return rfilt;
1988}
1989
1990static void
1991ath_update_promisc(struct ifnet *ifp)
1992{
1993	struct ath_softc *sc = ifp->if_softc;
1994	u_int32_t rfilt;
1995
1996	/* configure rx filter */
1997	rfilt = ath_calcrxfilter(sc);
1998	ath_hal_setrxfilter(sc->sc_ah, rfilt);
1999
2000	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
2001}
2002
2003static void
2004ath_update_mcast(struct ifnet *ifp)
2005{
2006	struct ath_softc *sc = ifp->if_softc;
2007	u_int32_t mfilt[2];
2008
2009	/* calculate and install multicast filter */
2010	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
2011		struct ifmultiaddr *ifma;
2012		/*
2013		 * Merge multicast addresses to form the hardware filter.
2014		 */
2015		mfilt[0] = mfilt[1] = 0;
2016		if_maddr_rlock(ifp);	/* XXX need some fiddling to remove? */
2017		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2018			caddr_t dl;
2019			u_int32_t val;
2020			u_int8_t pos;
2021
2022			/* calculate XOR of eight 6bit values */
2023			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
2024			val = LE_READ_4(dl + 0);
2025			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2026			val = LE_READ_4(dl + 3);
2027			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2028			pos &= 0x3f;
2029			mfilt[pos / 32] |= (1 << (pos % 32));
2030		}
2031		if_maddr_runlock(ifp);
2032	} else
2033		mfilt[0] = mfilt[1] = ~0;
2034	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
2035	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
2036		__func__, mfilt[0], mfilt[1]);
2037}
2038
2039static void
2040ath_mode_init(struct ath_softc *sc)
2041{
2042	struct ifnet *ifp = sc->sc_ifp;
2043	struct ath_hal *ah = sc->sc_ah;
2044	u_int32_t rfilt;
2045
2046	/* configure rx filter */
2047	rfilt = ath_calcrxfilter(sc);
2048	ath_hal_setrxfilter(ah, rfilt);
2049
2050	/* configure operational mode */
2051	ath_hal_setopmode(ah);
2052
2053	/* handle any link-level address change */
2054	ath_hal_setmac(ah, IF_LLADDR(ifp));
2055
2056	/* calculate and install multicast filter */
2057	ath_update_mcast(ifp);
2058}
2059
2060/*
2061 * Set the slot time based on the current setting.
2062 */
2063static void
2064ath_setslottime(struct ath_softc *sc)
2065{
2066	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2067	struct ath_hal *ah = sc->sc_ah;
2068	u_int usec;
2069
2070	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
2071		usec = 13;
2072	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
2073		usec = 21;
2074	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
2075		/* honor short/long slot time only in 11g */
2076		/* XXX shouldn't honor on pure g or turbo g channel */
2077		if (ic->ic_flags & IEEE80211_F_SHSLOT)
2078			usec = HAL_SLOT_TIME_9;
2079		else
2080			usec = HAL_SLOT_TIME_20;
2081	} else
2082		usec = HAL_SLOT_TIME_9;
2083
2084	DPRINTF(sc, ATH_DEBUG_RESET,
2085	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
2086	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
2087	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
2088
2089	ath_hal_setslottime(ah, usec);
2090	sc->sc_updateslot = OK;
2091}
2092
2093/*
2094 * Callback from the 802.11 layer to update the
2095 * slot time based on the current setting.
2096 */
2097static void
2098ath_updateslot(struct ifnet *ifp)
2099{
2100	struct ath_softc *sc = ifp->if_softc;
2101	struct ieee80211com *ic = ifp->if_l2com;
2102
2103	/*
2104	 * When not coordinating the BSS, change the hardware
2105	 * immediately.  For other operation we defer the change
2106	 * until beacon updates have propagated to the stations.
2107	 */
2108	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2109	    ic->ic_opmode == IEEE80211_M_MBSS)
2110		sc->sc_updateslot = UPDATE;
2111	else
2112		ath_setslottime(sc);
2113}
2114
2115/*
2116 * Setup a h/w transmit queue for beacons.
2117 */
2118static int
2119ath_beaconq_setup(struct ath_hal *ah)
2120{
2121	HAL_TXQ_INFO qi;
2122
2123	memset(&qi, 0, sizeof(qi));
2124	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
2125	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
2126	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
2127	/* NB: for dynamic turbo, don't enable any other interrupts */
2128	qi.tqi_qflags = HAL_TXQ_TXDESCINT_ENABLE;
2129	return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
2130}
2131
2132/*
2133 * Setup the transmit queue parameters for the beacon queue.
2134 */
2135static int
2136ath_beaconq_config(struct ath_softc *sc)
2137{
2138#define	ATH_EXPONENT_TO_VALUE(v)	((1<<(v))-1)
2139	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2140	struct ath_hal *ah = sc->sc_ah;
2141	HAL_TXQ_INFO qi;
2142
2143	ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
2144	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2145	    ic->ic_opmode == IEEE80211_M_MBSS) {
2146		/*
2147		 * Always burst out beacon and CAB traffic.
2148		 */
2149		qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
2150		qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
2151		qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
2152	} else {
2153		struct wmeParams *wmep =
2154			&ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
2155		/*
2156		 * Adhoc mode; important thing is to use 2x cwmin.
2157		 */
2158		qi.tqi_aifs = wmep->wmep_aifsn;
2159		qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
2160		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
2161	}
2162
2163	if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
2164		device_printf(sc->sc_dev, "unable to update parameters for "
2165			"beacon hardware queue!\n");
2166		return 0;
2167	} else {
2168		ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
2169		return 1;
2170	}
2171#undef ATH_EXPONENT_TO_VALUE
2172}
2173
2174/*
2175 * Allocate and setup an initial beacon frame.
2176 */
2177static int
2178ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
2179{
2180	struct ieee80211vap *vap = ni->ni_vap;
2181	struct ath_vap *avp = ATH_VAP(vap);
2182	struct ath_buf *bf;
2183	struct mbuf *m;
2184	int error;
2185
2186	bf = avp->av_bcbuf;
2187	if (bf->bf_m != NULL) {
2188		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2189		m_freem(bf->bf_m);
2190		bf->bf_m = NULL;
2191	}
2192	if (bf->bf_node != NULL) {
2193		ieee80211_free_node(bf->bf_node);
2194		bf->bf_node = NULL;
2195	}
2196
2197	/*
2198	 * NB: the beacon data buffer must be 32-bit aligned;
2199	 * we assume the mbuf routines will return us something
2200	 * with this alignment (perhaps should assert).
2201	 */
2202	m = ieee80211_beacon_alloc(ni, &avp->av_boff);
2203	if (m == NULL) {
2204		device_printf(sc->sc_dev, "%s: cannot get mbuf\n", __func__);
2205		sc->sc_stats.ast_be_nombuf++;
2206		return ENOMEM;
2207	}
2208	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2209				     bf->bf_segs, &bf->bf_nseg,
2210				     BUS_DMA_NOWAIT);
2211	if (error != 0) {
2212		device_printf(sc->sc_dev,
2213		    "%s: cannot map mbuf, bus_dmamap_load_mbuf_sg returns %d\n",
2214		    __func__, error);
2215		m_freem(m);
2216		return error;
2217	}
2218
2219	/*
2220	 * Calculate a TSF adjustment factor required for staggered
2221	 * beacons.  Note that we assume the format of the beacon
2222	 * frame leaves the tstamp field immediately following the
2223	 * header.
2224	 */
2225	if (sc->sc_stagbeacons && avp->av_bslot > 0) {
2226		uint64_t tsfadjust;
2227		struct ieee80211_frame *wh;
2228
2229		/*
2230		 * The beacon interval is in TU's; the TSF is in usecs.
2231		 * We figure out how many TU's to add to align the timestamp
2232		 * then convert to TSF units and handle byte swapping before
2233		 * inserting it in the frame.  The hardware will then add this
2234		 * each time a beacon frame is sent.  Note that we align vap's
2235		 * 1..N and leave vap 0 untouched.  This means vap 0 has a
2236		 * timestamp in one beacon interval while the others get a
2237		 * timstamp aligned to the next interval.
2238		 */
2239		tsfadjust = ni->ni_intval *
2240		    (ATH_BCBUF - avp->av_bslot) / ATH_BCBUF;
2241		tsfadjust = htole64(tsfadjust << 10);	/* TU -> TSF */
2242
2243		DPRINTF(sc, ATH_DEBUG_BEACON,
2244		    "%s: %s beacons bslot %d intval %u tsfadjust %llu\n",
2245		    __func__, sc->sc_stagbeacons ? "stagger" : "burst",
2246		    avp->av_bslot, ni->ni_intval,
2247		    (long long unsigned) le64toh(tsfadjust));
2248
2249		wh = mtod(m, struct ieee80211_frame *);
2250		memcpy(&wh[1], &tsfadjust, sizeof(tsfadjust));
2251	}
2252	bf->bf_m = m;
2253	bf->bf_node = ieee80211_ref_node(ni);
2254
2255	return 0;
2256}
2257
2258/*
2259 * Setup the beacon frame for transmit.
2260 */
2261static void
2262ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
2263{
2264#define	USE_SHPREAMBLE(_ic) \
2265	(((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
2266		== IEEE80211_F_SHPREAMBLE)
2267	struct ieee80211_node *ni = bf->bf_node;
2268	struct ieee80211com *ic = ni->ni_ic;
2269	struct mbuf *m = bf->bf_m;
2270	struct ath_hal *ah = sc->sc_ah;
2271	struct ath_desc *ds;
2272	int flags, antenna;
2273	const HAL_RATE_TABLE *rt;
2274	u_int8_t rix, rate;
2275
2276	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: m %p len %u\n",
2277		__func__, m, m->m_len);
2278
2279	/* setup descriptors */
2280	ds = bf->bf_desc;
2281
2282	flags = HAL_TXDESC_NOACK;
2283	if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
2284		ds->ds_link = bf->bf_daddr;	/* self-linked */
2285		flags |= HAL_TXDESC_VEOL;
2286		/*
2287		 * Let hardware handle antenna switching.
2288		 */
2289		antenna = sc->sc_txantenna;
2290	} else {
2291		ds->ds_link = 0;
2292		/*
2293		 * Switch antenna every 4 beacons.
2294		 * XXX assumes two antenna
2295		 */
2296		if (sc->sc_txantenna != 0)
2297			antenna = sc->sc_txantenna;
2298		else if (sc->sc_stagbeacons && sc->sc_nbcnvaps != 0)
2299			antenna = ((sc->sc_stats.ast_be_xmit / sc->sc_nbcnvaps) & 4 ? 2 : 1);
2300		else
2301			antenna = (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
2302	}
2303
2304	KASSERT(bf->bf_nseg == 1,
2305		("multi-segment beacon frame; nseg %u", bf->bf_nseg));
2306	ds->ds_data = bf->bf_segs[0].ds_addr;
2307	/*
2308	 * Calculate rate code.
2309	 * XXX everything at min xmit rate
2310	 */
2311	rix = 0;
2312	rt = sc->sc_currates;
2313	rate = rt->info[rix].rateCode;
2314	if (USE_SHPREAMBLE(ic))
2315		rate |= rt->info[rix].shortPreamble;
2316	ath_hal_setuptxdesc(ah, ds
2317		, m->m_len + IEEE80211_CRC_LEN	/* frame length */
2318		, sizeof(struct ieee80211_frame)/* header length */
2319		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
2320		, ni->ni_txpower		/* txpower XXX */
2321		, rate, 1			/* series 0 rate/tries */
2322		, HAL_TXKEYIX_INVALID		/* no encryption */
2323		, antenna			/* antenna mode */
2324		, flags				/* no ack, veol for beacons */
2325		, 0				/* rts/cts rate */
2326		, 0				/* rts/cts duration */
2327	);
2328	/* NB: beacon's BufLen must be a multiple of 4 bytes */
2329	ath_hal_filltxdesc(ah, ds
2330		, roundup(m->m_len, 4)		/* buffer length */
2331		, AH_TRUE			/* first segment */
2332		, AH_TRUE			/* last segment */
2333		, ds				/* first descriptor */
2334	);
2335#if 0
2336	ath_desc_swap(ds);
2337#endif
2338#undef USE_SHPREAMBLE
2339}
2340
2341static void
2342ath_beacon_update(struct ieee80211vap *vap, int item)
2343{
2344	struct ieee80211_beacon_offsets *bo = &ATH_VAP(vap)->av_boff;
2345
2346	setbit(bo->bo_flags, item);
2347}
2348
2349/*
2350 * Append the contents of src to dst; both queues
2351 * are assumed to be locked.
2352 */
2353static void
2354ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
2355{
2356	STAILQ_CONCAT(&dst->axq_q, &src->axq_q);
2357	dst->axq_link = src->axq_link;
2358	src->axq_link = NULL;
2359	dst->axq_depth += src->axq_depth;
2360	src->axq_depth = 0;
2361}
2362
2363/*
2364 * Transmit a beacon frame at SWBA.  Dynamic updates to the
2365 * frame contents are done as needed and the slot time is
2366 * also adjusted based on current state.
2367 */
2368static void
2369ath_beacon_proc(void *arg, int pending)
2370{
2371	struct ath_softc *sc = arg;
2372	struct ath_hal *ah = sc->sc_ah;
2373	struct ieee80211vap *vap;
2374	struct ath_buf *bf;
2375	int slot, otherant;
2376	uint32_t bfaddr;
2377
2378	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
2379		__func__, pending);
2380	/*
2381	 * Check if the previous beacon has gone out.  If
2382	 * not don't try to post another, skip this period
2383	 * and wait for the next.  Missed beacons indicate
2384	 * a problem and should not occur.  If we miss too
2385	 * many consecutive beacons reset the device.
2386	 */
2387	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
2388		sc->sc_bmisscount++;
2389		sc->sc_stats.ast_be_missed++;
2390		DPRINTF(sc, ATH_DEBUG_BEACON,
2391			"%s: missed %u consecutive beacons\n",
2392			__func__, sc->sc_bmisscount);
2393		if (sc->sc_bmisscount >= ath_bstuck_threshold)
2394			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
2395		return;
2396	}
2397	if (sc->sc_bmisscount != 0) {
2398		DPRINTF(sc, ATH_DEBUG_BEACON,
2399			"%s: resume beacon xmit after %u misses\n",
2400			__func__, sc->sc_bmisscount);
2401		sc->sc_bmisscount = 0;
2402	}
2403
2404	if (sc->sc_stagbeacons) {			/* staggered beacons */
2405		struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2406		uint32_t tsftu;
2407
2408		tsftu = ath_hal_gettsf32(ah) >> 10;
2409		/* XXX lintval */
2410		slot = ((tsftu % ic->ic_lintval) * ATH_BCBUF) / ic->ic_lintval;
2411		vap = sc->sc_bslot[(slot+1) % ATH_BCBUF];
2412		bfaddr = 0;
2413		if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2414			bf = ath_beacon_generate(sc, vap);
2415			if (bf != NULL)
2416				bfaddr = bf->bf_daddr;
2417		}
2418	} else {					/* burst'd beacons */
2419		uint32_t *bflink = &bfaddr;
2420
2421		for (slot = 0; slot < ATH_BCBUF; slot++) {
2422			vap = sc->sc_bslot[slot];
2423			if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2424				bf = ath_beacon_generate(sc, vap);
2425				if (bf != NULL) {
2426					*bflink = bf->bf_daddr;
2427					bflink = &bf->bf_desc->ds_link;
2428				}
2429			}
2430		}
2431		*bflink = 0;				/* terminate list */
2432	}
2433
2434	/*
2435	 * Handle slot time change when a non-ERP station joins/leaves
2436	 * an 11g network.  The 802.11 layer notifies us via callback,
2437	 * we mark updateslot, then wait one beacon before effecting
2438	 * the change.  This gives associated stations at least one
2439	 * beacon interval to note the state change.
2440	 */
2441	/* XXX locking */
2442	if (sc->sc_updateslot == UPDATE) {
2443		sc->sc_updateslot = COMMIT;	/* commit next beacon */
2444		sc->sc_slotupdate = slot;
2445	} else if (sc->sc_updateslot == COMMIT && sc->sc_slotupdate == slot)
2446		ath_setslottime(sc);		/* commit change to h/w */
2447
2448	/*
2449	 * Check recent per-antenna transmit statistics and flip
2450	 * the default antenna if noticeably more frames went out
2451	 * on the non-default antenna.
2452	 * XXX assumes 2 anntenae
2453	 */
2454	if (!sc->sc_diversity && (!sc->sc_stagbeacons || slot == 0)) {
2455		otherant = sc->sc_defant & 1 ? 2 : 1;
2456		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
2457			ath_setdefantenna(sc, otherant);
2458		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
2459	}
2460
2461	if (bfaddr != 0) {
2462		/*
2463		 * Stop any current dma and put the new frame on the queue.
2464		 * This should never fail since we check above that no frames
2465		 * are still pending on the queue.
2466		 */
2467		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
2468			DPRINTF(sc, ATH_DEBUG_ANY,
2469				"%s: beacon queue %u did not stop?\n",
2470				__func__, sc->sc_bhalq);
2471		}
2472		/* NB: cabq traffic should already be queued and primed */
2473		ath_hal_puttxbuf(ah, sc->sc_bhalq, bfaddr);
2474		ath_hal_txstart(ah, sc->sc_bhalq);
2475
2476		sc->sc_stats.ast_be_xmit++;
2477	}
2478}
2479
2480static struct ath_buf *
2481ath_beacon_generate(struct ath_softc *sc, struct ieee80211vap *vap)
2482{
2483	struct ath_vap *avp = ATH_VAP(vap);
2484	struct ath_txq *cabq = sc->sc_cabq;
2485	struct ath_buf *bf;
2486	struct mbuf *m;
2487	int nmcastq, error;
2488
2489	KASSERT(vap->iv_state >= IEEE80211_S_RUN,
2490	    ("not running, state %d", vap->iv_state));
2491	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
2492
2493	/*
2494	 * Update dynamic beacon contents.  If this returns
2495	 * non-zero then we need to remap the memory because
2496	 * the beacon frame changed size (probably because
2497	 * of the TIM bitmap).
2498	 */
2499	bf = avp->av_bcbuf;
2500	m = bf->bf_m;
2501	nmcastq = avp->av_mcastq.axq_depth;
2502	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, nmcastq)) {
2503		/* XXX too conservative? */
2504		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2505		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2506					     bf->bf_segs, &bf->bf_nseg,
2507					     BUS_DMA_NOWAIT);
2508		if (error != 0) {
2509			if_printf(vap->iv_ifp,
2510			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
2511			    __func__, error);
2512			return NULL;
2513		}
2514	}
2515	if ((avp->av_boff.bo_tim[4] & 1) && cabq->axq_depth) {
2516		DPRINTF(sc, ATH_DEBUG_BEACON,
2517		    "%s: cabq did not drain, mcastq %u cabq %u\n",
2518		    __func__, nmcastq, cabq->axq_depth);
2519		sc->sc_stats.ast_cabq_busy++;
2520		if (sc->sc_nvaps > 1 && sc->sc_stagbeacons) {
2521			/*
2522			 * CABQ traffic from a previous vap is still pending.
2523			 * We must drain the q before this beacon frame goes
2524			 * out as otherwise this vap's stations will get cab
2525			 * frames from a different vap.
2526			 * XXX could be slow causing us to miss DBA
2527			 */
2528			ath_tx_draintxq(sc, cabq);
2529		}
2530	}
2531	ath_beacon_setup(sc, bf);
2532	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2533
2534	/*
2535	 * Enable the CAB queue before the beacon queue to
2536	 * insure cab frames are triggered by this beacon.
2537	 */
2538	if (avp->av_boff.bo_tim[4] & 1) {
2539		struct ath_hal *ah = sc->sc_ah;
2540
2541		/* NB: only at DTIM */
2542		ATH_TXQ_LOCK(cabq);
2543		ATH_TXQ_LOCK(&avp->av_mcastq);
2544		if (nmcastq) {
2545			struct ath_buf *bfm;
2546
2547			/*
2548			 * Move frames from the s/w mcast q to the h/w cab q.
2549			 * XXX MORE_DATA bit
2550			 */
2551			bfm = STAILQ_FIRST(&avp->av_mcastq.axq_q);
2552			if (cabq->axq_link != NULL) {
2553				*cabq->axq_link = bfm->bf_daddr;
2554			} else
2555				ath_hal_puttxbuf(ah, cabq->axq_qnum,
2556					bfm->bf_daddr);
2557			ath_txqmove(cabq, &avp->av_mcastq);
2558
2559			sc->sc_stats.ast_cabq_xmit += nmcastq;
2560		}
2561		/* NB: gated by beacon so safe to start here */
2562		ath_hal_txstart(ah, cabq->axq_qnum);
2563		ATH_TXQ_UNLOCK(cabq);
2564		ATH_TXQ_UNLOCK(&avp->av_mcastq);
2565	}
2566	return bf;
2567}
2568
2569static void
2570ath_beacon_start_adhoc(struct ath_softc *sc, struct ieee80211vap *vap)
2571{
2572	struct ath_vap *avp = ATH_VAP(vap);
2573	struct ath_hal *ah = sc->sc_ah;
2574	struct ath_buf *bf;
2575	struct mbuf *m;
2576	int error;
2577
2578	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
2579
2580	/*
2581	 * Update dynamic beacon contents.  If this returns
2582	 * non-zero then we need to remap the memory because
2583	 * the beacon frame changed size (probably because
2584	 * of the TIM bitmap).
2585	 */
2586	bf = avp->av_bcbuf;
2587	m = bf->bf_m;
2588	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, 0)) {
2589		/* XXX too conservative? */
2590		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2591		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2592					     bf->bf_segs, &bf->bf_nseg,
2593					     BUS_DMA_NOWAIT);
2594		if (error != 0) {
2595			if_printf(vap->iv_ifp,
2596			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
2597			    __func__, error);
2598			return;
2599		}
2600	}
2601	ath_beacon_setup(sc, bf);
2602	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2603
2604	/* NB: caller is known to have already stopped tx dma */
2605	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
2606	ath_hal_txstart(ah, sc->sc_bhalq);
2607}
2608
2609/*
2610 * Reset the hardware after detecting beacons have stopped.
2611 */
2612static void
2613ath_bstuck_proc(void *arg, int pending)
2614{
2615	struct ath_softc *sc = arg;
2616	struct ifnet *ifp = sc->sc_ifp;
2617
2618	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
2619		sc->sc_bmisscount);
2620	sc->sc_stats.ast_bstuck++;
2621	ath_reset(ifp);
2622}
2623
2624/*
2625 * Reclaim beacon resources and return buffer to the pool.
2626 */
2627static void
2628ath_beacon_return(struct ath_softc *sc, struct ath_buf *bf)
2629{
2630
2631	if (bf->bf_m != NULL) {
2632		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2633		m_freem(bf->bf_m);
2634		bf->bf_m = NULL;
2635	}
2636	if (bf->bf_node != NULL) {
2637		ieee80211_free_node(bf->bf_node);
2638		bf->bf_node = NULL;
2639	}
2640	STAILQ_INSERT_TAIL(&sc->sc_bbuf, bf, bf_list);
2641}
2642
2643/*
2644 * Reclaim beacon resources.
2645 */
2646static void
2647ath_beacon_free(struct ath_softc *sc)
2648{
2649	struct ath_buf *bf;
2650
2651	STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
2652		if (bf->bf_m != NULL) {
2653			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2654			m_freem(bf->bf_m);
2655			bf->bf_m = NULL;
2656		}
2657		if (bf->bf_node != NULL) {
2658			ieee80211_free_node(bf->bf_node);
2659			bf->bf_node = NULL;
2660		}
2661	}
2662}
2663
2664/*
2665 * Configure the beacon and sleep timers.
2666 *
2667 * When operating as an AP this resets the TSF and sets
2668 * up the hardware to notify us when we need to issue beacons.
2669 *
2670 * When operating in station mode this sets up the beacon
2671 * timers according to the timestamp of the last received
2672 * beacon and the current TSF, configures PCF and DTIM
2673 * handling, programs the sleep registers so the hardware
2674 * will wakeup in time to receive beacons, and configures
2675 * the beacon miss handling so we'll receive a BMISS
2676 * interrupt when we stop seeing beacons from the AP
2677 * we've associated with.
2678 */
2679static void
2680ath_beacon_config(struct ath_softc *sc, struct ieee80211vap *vap)
2681{
2682#define	TSF_TO_TU(_h,_l) \
2683	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
2684#define	FUDGE	2
2685	struct ath_hal *ah = sc->sc_ah;
2686	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2687	struct ieee80211_node *ni;
2688	u_int32_t nexttbtt, intval, tsftu;
2689	u_int64_t tsf;
2690
2691	if (vap == NULL)
2692		vap = TAILQ_FIRST(&ic->ic_vaps);	/* XXX */
2693	ni = vap->iv_bss;
2694
2695	/* extract tstamp from last beacon and convert to TU */
2696	nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
2697			     LE_READ_4(ni->ni_tstamp.data));
2698	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2699	    ic->ic_opmode == IEEE80211_M_MBSS) {
2700		/*
2701		 * For multi-bss ap/mesh support beacons are either staggered
2702		 * evenly over N slots or burst together.  For the former
2703		 * arrange for the SWBA to be delivered for each slot.
2704		 * Slots that are not occupied will generate nothing.
2705		 */
2706		/* NB: the beacon interval is kept internally in TU's */
2707		intval = ni->ni_intval & HAL_BEACON_PERIOD;
2708		if (sc->sc_stagbeacons)
2709			intval /= ATH_BCBUF;
2710	} else {
2711		/* NB: the beacon interval is kept internally in TU's */
2712		intval = ni->ni_intval & HAL_BEACON_PERIOD;
2713	}
2714	if (nexttbtt == 0)		/* e.g. for ap mode */
2715		nexttbtt = intval;
2716	else if (intval)		/* NB: can be 0 for monitor mode */
2717		nexttbtt = roundup(nexttbtt, intval);
2718	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
2719		__func__, nexttbtt, intval, ni->ni_intval);
2720	if (ic->ic_opmode == IEEE80211_M_STA && !sc->sc_swbmiss) {
2721		HAL_BEACON_STATE bs;
2722		int dtimperiod, dtimcount;
2723		int cfpperiod, cfpcount;
2724
2725		/*
2726		 * Setup dtim and cfp parameters according to
2727		 * last beacon we received (which may be none).
2728		 */
2729		dtimperiod = ni->ni_dtim_period;
2730		if (dtimperiod <= 0)		/* NB: 0 if not known */
2731			dtimperiod = 1;
2732		dtimcount = ni->ni_dtim_count;
2733		if (dtimcount >= dtimperiod)	/* NB: sanity check */
2734			dtimcount = 0;		/* XXX? */
2735		cfpperiod = 1;			/* NB: no PCF support yet */
2736		cfpcount = 0;
2737		/*
2738		 * Pull nexttbtt forward to reflect the current
2739		 * TSF and calculate dtim+cfp state for the result.
2740		 */
2741		tsf = ath_hal_gettsf64(ah);
2742		tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
2743		do {
2744			nexttbtt += intval;
2745			if (--dtimcount < 0) {
2746				dtimcount = dtimperiod - 1;
2747				if (--cfpcount < 0)
2748					cfpcount = cfpperiod - 1;
2749			}
2750		} while (nexttbtt < tsftu);
2751		memset(&bs, 0, sizeof(bs));
2752		bs.bs_intval = intval;
2753		bs.bs_nexttbtt = nexttbtt;
2754		bs.bs_dtimperiod = dtimperiod*intval;
2755		bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
2756		bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
2757		bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
2758		bs.bs_cfpmaxduration = 0;
2759#if 0
2760		/*
2761		 * The 802.11 layer records the offset to the DTIM
2762		 * bitmap while receiving beacons; use it here to
2763		 * enable h/w detection of our AID being marked in
2764		 * the bitmap vector (to indicate frames for us are
2765		 * pending at the AP).
2766		 * XXX do DTIM handling in s/w to WAR old h/w bugs
2767		 * XXX enable based on h/w rev for newer chips
2768		 */
2769		bs.bs_timoffset = ni->ni_timoff;
2770#endif
2771		/*
2772		 * Calculate the number of consecutive beacons to miss
2773		 * before taking a BMISS interrupt.
2774		 * Note that we clamp the result to at most 10 beacons.
2775		 */
2776		bs.bs_bmissthreshold = vap->iv_bmissthreshold;
2777		if (bs.bs_bmissthreshold > 10)
2778			bs.bs_bmissthreshold = 10;
2779		else if (bs.bs_bmissthreshold <= 0)
2780			bs.bs_bmissthreshold = 1;
2781
2782		/*
2783		 * Calculate sleep duration.  The configuration is
2784		 * given in ms.  We insure a multiple of the beacon
2785		 * period is used.  Also, if the sleep duration is
2786		 * greater than the DTIM period then it makes senses
2787		 * to make it a multiple of that.
2788		 *
2789		 * XXX fixed at 100ms
2790		 */
2791		bs.bs_sleepduration =
2792			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
2793		if (bs.bs_sleepduration > bs.bs_dtimperiod)
2794			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
2795
2796		DPRINTF(sc, ATH_DEBUG_BEACON,
2797			"%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"
2798			, __func__
2799			, tsf, tsftu
2800			, bs.bs_intval
2801			, bs.bs_nexttbtt
2802			, bs.bs_dtimperiod
2803			, bs.bs_nextdtim
2804			, bs.bs_bmissthreshold
2805			, bs.bs_sleepduration
2806			, bs.bs_cfpperiod
2807			, bs.bs_cfpmaxduration
2808			, bs.bs_cfpnext
2809			, bs.bs_timoffset
2810		);
2811		ath_hal_intrset(ah, 0);
2812		ath_hal_beacontimers(ah, &bs);
2813		sc->sc_imask |= HAL_INT_BMISS;
2814		ath_hal_intrset(ah, sc->sc_imask);
2815	} else {
2816		ath_hal_intrset(ah, 0);
2817		if (nexttbtt == intval)
2818			intval |= HAL_BEACON_RESET_TSF;
2819		if (ic->ic_opmode == IEEE80211_M_IBSS) {
2820			/*
2821			 * In IBSS mode enable the beacon timers but only
2822			 * enable SWBA interrupts if we need to manually
2823			 * prepare beacon frames.  Otherwise we use a
2824			 * self-linked tx descriptor and let the hardware
2825			 * deal with things.
2826			 */
2827			intval |= HAL_BEACON_ENA;
2828			if (!sc->sc_hasveol)
2829				sc->sc_imask |= HAL_INT_SWBA;
2830			if ((intval & HAL_BEACON_RESET_TSF) == 0) {
2831				/*
2832				 * Pull nexttbtt forward to reflect
2833				 * the current TSF.
2834				 */
2835				tsf = ath_hal_gettsf64(ah);
2836				tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
2837				do {
2838					nexttbtt += intval;
2839				} while (nexttbtt < tsftu);
2840			}
2841			ath_beaconq_config(sc);
2842		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2843		    ic->ic_opmode == IEEE80211_M_MBSS) {
2844			/*
2845			 * In AP/mesh mode we enable the beacon timers
2846			 * and SWBA interrupts to prepare beacon frames.
2847			 */
2848			intval |= HAL_BEACON_ENA;
2849			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
2850			ath_beaconq_config(sc);
2851		}
2852		ath_hal_beaconinit(ah, nexttbtt, intval);
2853		sc->sc_bmisscount = 0;
2854		ath_hal_intrset(ah, sc->sc_imask);
2855		/*
2856		 * When using a self-linked beacon descriptor in
2857		 * ibss mode load it once here.
2858		 */
2859		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
2860			ath_beacon_start_adhoc(sc, vap);
2861	}
2862	sc->sc_syncbeacon = 0;
2863#undef FUDGE
2864#undef TSF_TO_TU
2865}
2866
2867static void
2868ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2869{
2870	bus_addr_t *paddr = (bus_addr_t*) arg;
2871	KASSERT(error == 0, ("error %u on bus_dma callback", error));
2872	*paddr = segs->ds_addr;
2873}
2874
2875static int
2876ath_descdma_setup(struct ath_softc *sc,
2877	struct ath_descdma *dd, ath_bufhead *head,
2878	const char *name, int nbuf, int ndesc)
2879{
2880#define	DS2PHYS(_dd, _ds) \
2881	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
2882	struct ifnet *ifp = sc->sc_ifp;
2883	struct ath_desc *ds;
2884	struct ath_buf *bf;
2885	int i, bsize, error;
2886
2887	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
2888	    __func__, name, nbuf, ndesc);
2889
2890	dd->dd_name = name;
2891	dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
2892
2893	/*
2894	 * Setup DMA descriptor area.
2895	 */
2896	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
2897		       PAGE_SIZE, 0,		/* alignment, bounds */
2898		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
2899		       BUS_SPACE_MAXADDR,	/* highaddr */
2900		       NULL, NULL,		/* filter, filterarg */
2901		       dd->dd_desc_len,		/* maxsize */
2902		       1,			/* nsegments */
2903		       dd->dd_desc_len,		/* maxsegsize */
2904		       BUS_DMA_ALLOCNOW,	/* flags */
2905		       NULL,			/* lockfunc */
2906		       NULL,			/* lockarg */
2907		       &dd->dd_dmat);
2908	if (error != 0) {
2909		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
2910		return error;
2911	}
2912
2913	/* allocate descriptors */
2914	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
2915	if (error != 0) {
2916		if_printf(ifp, "unable to create dmamap for %s descriptors, "
2917			"error %u\n", dd->dd_name, error);
2918		goto fail0;
2919	}
2920
2921	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
2922				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
2923				 &dd->dd_dmamap);
2924	if (error != 0) {
2925		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
2926			"error %u\n", nbuf * ndesc, dd->dd_name, error);
2927		goto fail1;
2928	}
2929
2930	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
2931				dd->dd_desc, dd->dd_desc_len,
2932				ath_load_cb, &dd->dd_desc_paddr,
2933				BUS_DMA_NOWAIT);
2934	if (error != 0) {
2935		if_printf(ifp, "unable to map %s descriptors, error %u\n",
2936			dd->dd_name, error);
2937		goto fail2;
2938	}
2939
2940	ds = dd->dd_desc;
2941	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
2942	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
2943	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
2944
2945	/* allocate rx buffers */
2946	bsize = sizeof(struct ath_buf) * nbuf;
2947	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
2948	if (bf == NULL) {
2949		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
2950			dd->dd_name, bsize);
2951		goto fail3;
2952	}
2953	dd->dd_bufptr = bf;
2954
2955	STAILQ_INIT(head);
2956	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
2957		bf->bf_desc = ds;
2958		bf->bf_daddr = DS2PHYS(dd, ds);
2959		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
2960				&bf->bf_dmamap);
2961		if (error != 0) {
2962			if_printf(ifp, "unable to create dmamap for %s "
2963				"buffer %u, error %u\n", dd->dd_name, i, error);
2964			ath_descdma_cleanup(sc, dd, head);
2965			return error;
2966		}
2967		STAILQ_INSERT_TAIL(head, bf, bf_list);
2968	}
2969	return 0;
2970fail3:
2971	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2972fail2:
2973	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2974fail1:
2975	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2976fail0:
2977	bus_dma_tag_destroy(dd->dd_dmat);
2978	memset(dd, 0, sizeof(*dd));
2979	return error;
2980#undef DS2PHYS
2981}
2982
2983static void
2984ath_descdma_cleanup(struct ath_softc *sc,
2985	struct ath_descdma *dd, ath_bufhead *head)
2986{
2987	struct ath_buf *bf;
2988	struct ieee80211_node *ni;
2989
2990	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2991	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2992	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2993	bus_dma_tag_destroy(dd->dd_dmat);
2994
2995	STAILQ_FOREACH(bf, head, bf_list) {
2996		if (bf->bf_m) {
2997			m_freem(bf->bf_m);
2998			bf->bf_m = NULL;
2999		}
3000		if (bf->bf_dmamap != NULL) {
3001			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
3002			bf->bf_dmamap = NULL;
3003		}
3004		ni = bf->bf_node;
3005		bf->bf_node = NULL;
3006		if (ni != NULL) {
3007			/*
3008			 * Reclaim node reference.
3009			 */
3010			ieee80211_free_node(ni);
3011		}
3012	}
3013
3014	STAILQ_INIT(head);
3015	free(dd->dd_bufptr, M_ATHDEV);
3016	memset(dd, 0, sizeof(*dd));
3017}
3018
3019static int
3020ath_desc_alloc(struct ath_softc *sc)
3021{
3022	int error;
3023
3024	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
3025			"rx", ath_rxbuf, 1);
3026	if (error != 0)
3027		return error;
3028
3029	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
3030			"tx", ath_txbuf, ATH_TXDESC);
3031	if (error != 0) {
3032		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3033		return error;
3034	}
3035
3036	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3037			"beacon", ATH_BCBUF, 1);
3038	if (error != 0) {
3039		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3040		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3041		return error;
3042	}
3043	return 0;
3044}
3045
3046static void
3047ath_desc_free(struct ath_softc *sc)
3048{
3049
3050	if (sc->sc_bdma.dd_desc_len != 0)
3051		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3052	if (sc->sc_txdma.dd_desc_len != 0)
3053		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3054	if (sc->sc_rxdma.dd_desc_len != 0)
3055		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3056}
3057
3058static struct ieee80211_node *
3059ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3060{
3061	struct ieee80211com *ic = vap->iv_ic;
3062	struct ath_softc *sc = ic->ic_ifp->if_softc;
3063	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3064	struct ath_node *an;
3065
3066	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
3067	if (an == NULL) {
3068		/* XXX stat+msg */
3069		return NULL;
3070	}
3071	ath_rate_node_init(sc, an);
3072
3073	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
3074	return &an->an_node;
3075}
3076
3077static void
3078ath_node_free(struct ieee80211_node *ni)
3079{
3080	struct ieee80211com *ic = ni->ni_ic;
3081        struct ath_softc *sc = ic->ic_ifp->if_softc;
3082
3083	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3084
3085	ath_rate_node_cleanup(sc, ATH_NODE(ni));
3086	sc->sc_node_free(ni);
3087}
3088
3089static void
3090ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3091{
3092	struct ieee80211com *ic = ni->ni_ic;
3093	struct ath_softc *sc = ic->ic_ifp->if_softc;
3094	struct ath_hal *ah = sc->sc_ah;
3095
3096	*rssi = ic->ic_node_getrssi(ni);
3097	if (ni->ni_chan != IEEE80211_CHAN_ANYC)
3098		*noise = ath_hal_getchannoise(ah, ni->ni_chan);
3099	else
3100		*noise = -95;		/* nominally correct */
3101}
3102
3103static int
3104ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
3105{
3106	struct ath_hal *ah = sc->sc_ah;
3107	int error;
3108	struct mbuf *m;
3109	struct ath_desc *ds;
3110
3111	m = bf->bf_m;
3112	if (m == NULL) {
3113		/*
3114		 * NB: by assigning a page to the rx dma buffer we
3115		 * implicitly satisfy the Atheros requirement that
3116		 * this buffer be cache-line-aligned and sized to be
3117		 * multiple of the cache line size.  Not doing this
3118		 * causes weird stuff to happen (for the 5210 at least).
3119		 */
3120		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
3121		if (m == NULL) {
3122			DPRINTF(sc, ATH_DEBUG_ANY,
3123				"%s: no mbuf/cluster\n", __func__);
3124			sc->sc_stats.ast_rx_nombuf++;
3125			return ENOMEM;
3126		}
3127		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
3128
3129		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
3130					     bf->bf_dmamap, m,
3131					     bf->bf_segs, &bf->bf_nseg,
3132					     BUS_DMA_NOWAIT);
3133		if (error != 0) {
3134			DPRINTF(sc, ATH_DEBUG_ANY,
3135			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
3136			    __func__, error);
3137			sc->sc_stats.ast_rx_busdma++;
3138			m_freem(m);
3139			return error;
3140		}
3141		KASSERT(bf->bf_nseg == 1,
3142			("multi-segment packet; nseg %u", bf->bf_nseg));
3143		bf->bf_m = m;
3144	}
3145	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
3146
3147	/*
3148	 * Setup descriptors.  For receive we always terminate
3149	 * the descriptor list with a self-linked entry so we'll
3150	 * not get overrun under high load (as can happen with a
3151	 * 5212 when ANI processing enables PHY error frames).
3152	 *
3153	 * To insure the last descriptor is self-linked we create
3154	 * each descriptor as self-linked and add it to the end.  As
3155	 * each additional descriptor is added the previous self-linked
3156	 * entry is ``fixed'' naturally.  This should be safe even
3157	 * if DMA is happening.  When processing RX interrupts we
3158	 * never remove/process the last, self-linked, entry on the
3159	 * descriptor list.  This insures the hardware always has
3160	 * someplace to write a new frame.
3161	 */
3162	/*
3163	 * 11N: we can no longer afford to self link the last descriptor.
3164	 * MAC acknowledges BA status as long as it copies frames to host
3165	 * buffer (or rx fifo). This can incorrectly acknowledge packets
3166	 * to a sender if last desc is self-linked.
3167	 */
3168	ds = bf->bf_desc;
3169	if (sc->sc_rxslink)
3170		ds->ds_link = bf->bf_daddr;	/* link to self */
3171	else
3172		ds->ds_link = 0;		/* terminate the list */
3173	ds->ds_data = bf->bf_segs[0].ds_addr;
3174	ath_hal_setuprxdesc(ah, ds
3175		, m->m_len		/* buffer size */
3176		, 0
3177	);
3178
3179	if (sc->sc_rxlink != NULL)
3180		*sc->sc_rxlink = bf->bf_daddr;
3181	sc->sc_rxlink = &ds->ds_link;
3182	return 0;
3183}
3184
3185/*
3186 * Extend 15-bit time stamp from rx descriptor to
3187 * a full 64-bit TSF using the specified TSF.
3188 */
3189static __inline u_int64_t
3190ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
3191{
3192	if ((tsf & 0x7fff) < rstamp)
3193		tsf -= 0x8000;
3194	return ((tsf &~ 0x7fff) | rstamp);
3195}
3196
3197/*
3198 * Intercept management frames to collect beacon rssi data
3199 * and to do ibss merges.
3200 */
3201static void
3202ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
3203	int subtype, int rssi, int nf)
3204{
3205	struct ieee80211vap *vap = ni->ni_vap;
3206	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
3207
3208	/*
3209	 * Call up first so subsequent work can use information
3210	 * potentially stored in the node (e.g. for ibss merge).
3211	 */
3212	ATH_VAP(vap)->av_recv_mgmt(ni, m, subtype, rssi, nf);
3213	switch (subtype) {
3214	case IEEE80211_FC0_SUBTYPE_BEACON:
3215		/* update rssi statistics for use by the hal */
3216		ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
3217		if (sc->sc_syncbeacon &&
3218		    ni == vap->iv_bss && vap->iv_state == IEEE80211_S_RUN) {
3219			/*
3220			 * Resync beacon timers using the tsf of the beacon
3221			 * frame we just received.
3222			 */
3223			ath_beacon_config(sc, vap);
3224		}
3225		/* fall thru... */
3226	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
3227		if (vap->iv_opmode == IEEE80211_M_IBSS &&
3228		    vap->iv_state == IEEE80211_S_RUN) {
3229			uint32_t rstamp = sc->sc_lastrs->rs_tstamp;
3230			uint64_t tsf = ath_extend_tsf(rstamp,
3231				ath_hal_gettsf64(sc->sc_ah));
3232			/*
3233			 * Handle ibss merge as needed; check the tsf on the
3234			 * frame before attempting the merge.  The 802.11 spec
3235			 * says the station should change it's bssid to match
3236			 * the oldest station with the same ssid, where oldest
3237			 * is determined by the tsf.  Note that hardware
3238			 * reconfiguration happens through callback to
3239			 * ath_newstate as the state machine will go from
3240			 * RUN -> RUN when this happens.
3241			 */
3242			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
3243				DPRINTF(sc, ATH_DEBUG_STATE,
3244				    "ibss merge, rstamp %u tsf %ju "
3245				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
3246				    (uintmax_t)ni->ni_tstamp.tsf);
3247				(void) ieee80211_ibss_merge(ni);
3248			}
3249		}
3250		break;
3251	}
3252}
3253
3254/*
3255 * Set the default antenna.
3256 */
3257static void
3258ath_setdefantenna(struct ath_softc *sc, u_int antenna)
3259{
3260	struct ath_hal *ah = sc->sc_ah;
3261
3262	/* XXX block beacon interrupts */
3263	ath_hal_setdefantenna(ah, antenna);
3264	if (sc->sc_defant != antenna)
3265		sc->sc_stats.ast_ant_defswitch++;
3266	sc->sc_defant = antenna;
3267	sc->sc_rxotherant = 0;
3268}
3269
3270static void
3271ath_rx_tap(struct ifnet *ifp, struct mbuf *m,
3272	const struct ath_rx_status *rs, u_int64_t tsf, int16_t nf)
3273{
3274#define	CHAN_HT20	htole32(IEEE80211_CHAN_HT20)
3275#define	CHAN_HT40U	htole32(IEEE80211_CHAN_HT40U)
3276#define	CHAN_HT40D	htole32(IEEE80211_CHAN_HT40D)
3277#define	CHAN_HT		(CHAN_HT20|CHAN_HT40U|CHAN_HT40D)
3278	struct ath_softc *sc = ifp->if_softc;
3279	const HAL_RATE_TABLE *rt;
3280	uint8_t rix;
3281
3282	rt = sc->sc_currates;
3283	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3284	rix = rt->rateCodeToIndex[rs->rs_rate];
3285	sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
3286	sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
3287#ifdef AH_SUPPORT_AR5416
3288	sc->sc_rx_th.wr_chan_flags &= ~CHAN_HT;
3289	if (sc->sc_rx_th.wr_rate & IEEE80211_RATE_MCS) {	/* HT rate */
3290		struct ieee80211com *ic = ifp->if_l2com;
3291
3292		if ((rs->rs_flags & HAL_RX_2040) == 0)
3293			sc->sc_rx_th.wr_chan_flags |= CHAN_HT20;
3294		else if (IEEE80211_IS_CHAN_HT40U(ic->ic_curchan))
3295			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40U;
3296		else
3297			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40D;
3298		if ((rs->rs_flags & HAL_RX_GI) == 0)
3299			sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_SHORTGI;
3300	}
3301#endif
3302	sc->sc_rx_th.wr_tsf = htole64(ath_extend_tsf(rs->rs_tstamp, tsf));
3303	if (rs->rs_status & HAL_RXERR_CRC)
3304		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
3305	/* XXX propagate other error flags from descriptor */
3306	sc->sc_rx_th.wr_antnoise = nf;
3307	sc->sc_rx_th.wr_antsignal = nf + rs->rs_rssi;
3308	sc->sc_rx_th.wr_antenna = rs->rs_antenna;
3309#undef CHAN_HT
3310#undef CHAN_HT20
3311#undef CHAN_HT40U
3312#undef CHAN_HT40D
3313}
3314
3315static void
3316ath_handle_micerror(struct ieee80211com *ic,
3317	struct ieee80211_frame *wh, int keyix)
3318{
3319	struct ieee80211_node *ni;
3320
3321	/* XXX recheck MIC to deal w/ chips that lie */
3322	/* XXX discard MIC errors on !data frames */
3323	ni = ieee80211_find_rxnode(ic, (const struct ieee80211_frame_min *) wh);
3324	if (ni != NULL) {
3325		ieee80211_notify_michael_failure(ni->ni_vap, wh, keyix);
3326		ieee80211_free_node(ni);
3327	}
3328}
3329
3330static void
3331ath_rx_proc(void *arg, int npending)
3332{
3333#define	PA2DESC(_sc, _pa) \
3334	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
3335		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
3336	struct ath_softc *sc = arg;
3337	struct ath_buf *bf;
3338	struct ifnet *ifp = sc->sc_ifp;
3339	struct ieee80211com *ic = ifp->if_l2com;
3340	struct ath_hal *ah = sc->sc_ah;
3341	struct ath_desc *ds;
3342	struct ath_rx_status *rs;
3343	struct mbuf *m;
3344	struct ieee80211_node *ni;
3345	int len, type, ngood;
3346	HAL_STATUS status;
3347	int16_t nf;
3348	u_int64_t tsf;
3349
3350	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
3351	ngood = 0;
3352	nf = ath_hal_getchannoise(ah, sc->sc_curchan);
3353	sc->sc_stats.ast_rx_noise = nf;
3354	tsf = ath_hal_gettsf64(ah);
3355	do {
3356		bf = STAILQ_FIRST(&sc->sc_rxbuf);
3357		if (sc->sc_rxslink && bf == NULL) {	/* NB: shouldn't happen */
3358			if_printf(ifp, "%s: no buffer!\n", __func__);
3359			break;
3360		} else if (bf == NULL) {
3361			/*
3362			 * End of List:
3363			 * this can happen for non-self-linked RX chains
3364			 */
3365			sc->sc_stats.ast_rx_hitqueueend++;
3366			break;
3367		}
3368		m = bf->bf_m;
3369		if (m == NULL) {		/* NB: shouldn't happen */
3370			/*
3371			 * If mbuf allocation failed previously there
3372			 * will be no mbuf; try again to re-populate it.
3373			 */
3374			/* XXX make debug msg */
3375			if_printf(ifp, "%s: no mbuf!\n", __func__);
3376			STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3377			goto rx_next;
3378		}
3379		ds = bf->bf_desc;
3380		if (ds->ds_link == bf->bf_daddr) {
3381			/* NB: never process the self-linked entry at the end */
3382			sc->sc_stats.ast_rx_hitqueueend++;
3383			break;
3384		}
3385		/* XXX sync descriptor memory */
3386		/*
3387		 * Must provide the virtual address of the current
3388		 * descriptor, the physical address, and the virtual
3389		 * address of the next descriptor in the h/w chain.
3390		 * This allows the HAL to look ahead to see if the
3391		 * hardware is done with a descriptor by checking the
3392		 * done bit in the following descriptor and the address
3393		 * of the current descriptor the DMA engine is working
3394		 * on.  All this is necessary because of our use of
3395		 * a self-linked list to avoid rx overruns.
3396		 */
3397		rs = &bf->bf_status.ds_rxstat;
3398		status = ath_hal_rxprocdesc(ah, ds,
3399				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
3400#ifdef ATH_DEBUG
3401		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
3402			ath_printrxbuf(sc, bf, 0, status == HAL_OK);
3403#endif
3404		if (status == HAL_EINPROGRESS)
3405			break;
3406		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3407
3408		/* These aren't specifically errors */
3409		if (rs->rs_flags & HAL_RX_GI)
3410			sc->sc_stats.ast_rx_halfgi++;
3411		if (rs->rs_flags & HAL_RX_2040)
3412			sc->sc_stats.ast_rx_2040++;
3413		if (rs->rs_flags & HAL_RX_DELIM_CRC_PRE)
3414			sc->sc_stats.ast_rx_pre_crc_err++;
3415		if (rs->rs_flags & HAL_RX_DELIM_CRC_POST)
3416			sc->sc_stats.ast_rx_post_crc_err++;
3417		if (rs->rs_flags & HAL_RX_DECRYPT_BUSY)
3418			sc->sc_stats.ast_rx_decrypt_busy_err++;
3419		if (rs->rs_flags & HAL_RX_HI_RX_CHAIN)
3420			sc->sc_stats.ast_rx_hi_rx_chain++;
3421
3422		if (rs->rs_status != 0) {
3423			if (rs->rs_status & HAL_RXERR_CRC)
3424				sc->sc_stats.ast_rx_crcerr++;
3425			if (rs->rs_status & HAL_RXERR_FIFO)
3426				sc->sc_stats.ast_rx_fifoerr++;
3427			if (rs->rs_status & HAL_RXERR_PHY) {
3428				sc->sc_stats.ast_rx_phyerr++;
3429				/* Be suitably paranoid about receiving phy errors out of the stats array bounds */
3430				if (rs->rs_phyerr < 64)
3431					sc->sc_stats.ast_rx_phy[rs->rs_phyerr]++;
3432				goto rx_error;	/* NB: don't count in ierrors */
3433			}
3434			if (rs->rs_status & HAL_RXERR_DECRYPT) {
3435				/*
3436				 * Decrypt error.  If the error occurred
3437				 * because there was no hardware key, then
3438				 * let the frame through so the upper layers
3439				 * can process it.  This is necessary for 5210
3440				 * parts which have no way to setup a ``clear''
3441				 * key cache entry.
3442				 *
3443				 * XXX do key cache faulting
3444				 */
3445				if (rs->rs_keyix == HAL_RXKEYIX_INVALID)
3446					goto rx_accept;
3447				sc->sc_stats.ast_rx_badcrypt++;
3448			}
3449			if (rs->rs_status & HAL_RXERR_MIC) {
3450				sc->sc_stats.ast_rx_badmic++;
3451				/*
3452				 * Do minimal work required to hand off
3453				 * the 802.11 header for notification.
3454				 */
3455				/* XXX frag's and qos frames */
3456				len = rs->rs_datalen;
3457				if (len >= sizeof (struct ieee80211_frame)) {
3458					bus_dmamap_sync(sc->sc_dmat,
3459					    bf->bf_dmamap,
3460					    BUS_DMASYNC_POSTREAD);
3461					ath_handle_micerror(ic,
3462					    mtod(m, struct ieee80211_frame *),
3463					    sc->sc_splitmic ?
3464						rs->rs_keyix-32 : rs->rs_keyix);
3465				}
3466			}
3467			ifp->if_ierrors++;
3468rx_error:
3469			/*
3470			 * Cleanup any pending partial frame.
3471			 */
3472			if (sc->sc_rxpending != NULL) {
3473				m_freem(sc->sc_rxpending);
3474				sc->sc_rxpending = NULL;
3475			}
3476			/*
3477			 * When a tap is present pass error frames
3478			 * that have been requested.  By default we
3479			 * pass decrypt+mic errors but others may be
3480			 * interesting (e.g. crc).
3481			 */
3482			if (ieee80211_radiotap_active(ic) &&
3483			    (rs->rs_status & sc->sc_monpass)) {
3484				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3485				    BUS_DMASYNC_POSTREAD);
3486				/* NB: bpf needs the mbuf length setup */
3487				len = rs->rs_datalen;
3488				m->m_pkthdr.len = m->m_len = len;
3489				ath_rx_tap(ifp, m, rs, tsf, nf);
3490				ieee80211_radiotap_rx_all(ic, m);
3491			}
3492			/* XXX pass MIC errors up for s/w reclaculation */
3493			goto rx_next;
3494		}
3495rx_accept:
3496		/*
3497		 * Sync and unmap the frame.  At this point we're
3498		 * committed to passing the mbuf somewhere so clear
3499		 * bf_m; this means a new mbuf must be allocated
3500		 * when the rx descriptor is setup again to receive
3501		 * another frame.
3502		 */
3503		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3504		    BUS_DMASYNC_POSTREAD);
3505		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3506		bf->bf_m = NULL;
3507
3508		len = rs->rs_datalen;
3509		m->m_len = len;
3510
3511		if (rs->rs_more) {
3512			/*
3513			 * Frame spans multiple descriptors; save
3514			 * it for the next completed descriptor, it
3515			 * will be used to construct a jumbogram.
3516			 */
3517			if (sc->sc_rxpending != NULL) {
3518				/* NB: max frame size is currently 2 clusters */
3519				sc->sc_stats.ast_rx_toobig++;
3520				m_freem(sc->sc_rxpending);
3521			}
3522			m->m_pkthdr.rcvif = ifp;
3523			m->m_pkthdr.len = len;
3524			sc->sc_rxpending = m;
3525			goto rx_next;
3526		} else if (sc->sc_rxpending != NULL) {
3527			/*
3528			 * This is the second part of a jumbogram,
3529			 * chain it to the first mbuf, adjust the
3530			 * frame length, and clear the rxpending state.
3531			 */
3532			sc->sc_rxpending->m_next = m;
3533			sc->sc_rxpending->m_pkthdr.len += len;
3534			m = sc->sc_rxpending;
3535			sc->sc_rxpending = NULL;
3536		} else {
3537			/*
3538			 * Normal single-descriptor receive; setup
3539			 * the rcvif and packet length.
3540			 */
3541			m->m_pkthdr.rcvif = ifp;
3542			m->m_pkthdr.len = len;
3543		}
3544
3545		ifp->if_ipackets++;
3546		sc->sc_stats.ast_ant_rx[rs->rs_antenna]++;
3547
3548		/*
3549		 * Populate the rx status block.  When there are bpf
3550		 * listeners we do the additional work to provide
3551		 * complete status.  Otherwise we fill in only the
3552		 * material required by ieee80211_input.  Note that
3553		 * noise setting is filled in above.
3554		 */
3555		if (ieee80211_radiotap_active(ic))
3556			ath_rx_tap(ifp, m, rs, tsf, nf);
3557
3558		/*
3559		 * From this point on we assume the frame is at least
3560		 * as large as ieee80211_frame_min; verify that.
3561		 */
3562		if (len < IEEE80211_MIN_LEN) {
3563			if (!ieee80211_radiotap_active(ic)) {
3564				DPRINTF(sc, ATH_DEBUG_RECV,
3565				    "%s: short packet %d\n", __func__, len);
3566				sc->sc_stats.ast_rx_tooshort++;
3567			} else {
3568				/* NB: in particular this captures ack's */
3569				ieee80211_radiotap_rx_all(ic, m);
3570			}
3571			m_freem(m);
3572			goto rx_next;
3573		}
3574
3575		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
3576			const HAL_RATE_TABLE *rt = sc->sc_currates;
3577			uint8_t rix = rt->rateCodeToIndex[rs->rs_rate];
3578
3579			ieee80211_dump_pkt(ic, mtod(m, caddr_t), len,
3580			    sc->sc_hwmap[rix].ieeerate, rs->rs_rssi);
3581		}
3582
3583		m_adj(m, -IEEE80211_CRC_LEN);
3584
3585		/*
3586		 * Locate the node for sender, track state, and then
3587		 * pass the (referenced) node up to the 802.11 layer
3588		 * for its use.
3589		 */
3590		ni = ieee80211_find_rxnode_withkey(ic,
3591			mtod(m, const struct ieee80211_frame_min *),
3592			rs->rs_keyix == HAL_RXKEYIX_INVALID ?
3593				IEEE80211_KEYIX_NONE : rs->rs_keyix);
3594		sc->sc_lastrs = rs;
3595
3596		if (rs->rs_isaggr)
3597			sc->sc_stats.ast_rx_agg++;
3598
3599		if (ni != NULL) {
3600			/*
3601 			 * Only punt packets for ampdu reorder processing for
3602			 * 11n nodes; net80211 enforces that M_AMPDU is only
3603			 * set for 11n nodes.
3604 			 */
3605			if (ni->ni_flags & IEEE80211_NODE_HT)
3606				m->m_flags |= M_AMPDU;
3607
3608			/*
3609			 * Sending station is known, dispatch directly.
3610			 */
3611			type = ieee80211_input(ni, m, rs->rs_rssi, nf);
3612			ieee80211_free_node(ni);
3613			/*
3614			 * Arrange to update the last rx timestamp only for
3615			 * frames from our ap when operating in station mode.
3616			 * This assumes the rx key is always setup when
3617			 * associated.
3618			 */
3619			if (ic->ic_opmode == IEEE80211_M_STA &&
3620			    rs->rs_keyix != HAL_RXKEYIX_INVALID)
3621				ngood++;
3622		} else {
3623			type = ieee80211_input_all(ic, m, rs->rs_rssi, nf);
3624		}
3625		/*
3626		 * Track rx rssi and do any rx antenna management.
3627		 */
3628		ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, rs->rs_rssi);
3629		if (sc->sc_diversity) {
3630			/*
3631			 * When using fast diversity, change the default rx
3632			 * antenna if diversity chooses the other antenna 3
3633			 * times in a row.
3634			 */
3635			if (sc->sc_defant != rs->rs_antenna) {
3636				if (++sc->sc_rxotherant >= 3)
3637					ath_setdefantenna(sc, rs->rs_antenna);
3638			} else
3639				sc->sc_rxotherant = 0;
3640		}
3641
3642		/* Newer school diversity - kite specific for now */
3643		/* XXX perhaps migrate the normal diversity code to this? */
3644		if ((ah)->ah_rxAntCombDiversity)
3645			(*(ah)->ah_rxAntCombDiversity)(ah, rs, ticks, hz);
3646
3647		if (sc->sc_softled) {
3648			/*
3649			 * Blink for any data frame.  Otherwise do a
3650			 * heartbeat-style blink when idle.  The latter
3651			 * is mainly for station mode where we depend on
3652			 * periodic beacon frames to trigger the poll event.
3653			 */
3654			if (type == IEEE80211_FC0_TYPE_DATA) {
3655				const HAL_RATE_TABLE *rt = sc->sc_currates;
3656				ath_led_event(sc,
3657				    rt->rateCodeToIndex[rs->rs_rate]);
3658			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
3659				ath_led_event(sc, 0);
3660		}
3661rx_next:
3662		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
3663	} while (ath_rxbuf_init(sc, bf) == 0);
3664
3665	/* rx signal state monitoring */
3666	ath_hal_rxmonitor(ah, &sc->sc_halstats, sc->sc_curchan);
3667	if (ngood)
3668		sc->sc_lastrx = tsf;
3669
3670	if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0) {
3671#ifdef IEEE80211_SUPPORT_SUPERG
3672		ieee80211_ff_age_all(ic, 100);
3673#endif
3674		if (!IFQ_IS_EMPTY(&ifp->if_snd))
3675			ath_start(ifp);
3676	}
3677#undef PA2DESC
3678}
3679
3680static void
3681ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
3682{
3683	txq->axq_qnum = qnum;
3684	txq->axq_ac = 0;
3685	txq->axq_depth = 0;
3686	txq->axq_intrcnt = 0;
3687	txq->axq_link = NULL;
3688	STAILQ_INIT(&txq->axq_q);
3689	ATH_TXQ_LOCK_INIT(sc, txq);
3690}
3691
3692/*
3693 * Setup a h/w transmit queue.
3694 */
3695static struct ath_txq *
3696ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
3697{
3698#define	N(a)	(sizeof(a)/sizeof(a[0]))
3699	struct ath_hal *ah = sc->sc_ah;
3700	HAL_TXQ_INFO qi;
3701	int qnum;
3702
3703	memset(&qi, 0, sizeof(qi));
3704	qi.tqi_subtype = subtype;
3705	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
3706	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
3707	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
3708	/*
3709	 * Enable interrupts only for EOL and DESC conditions.
3710	 * We mark tx descriptors to receive a DESC interrupt
3711	 * when a tx queue gets deep; otherwise waiting for the
3712	 * EOL to reap descriptors.  Note that this is done to
3713	 * reduce interrupt load and this only defers reaping
3714	 * descriptors, never transmitting frames.  Aside from
3715	 * reducing interrupts this also permits more concurrency.
3716	 * The only potential downside is if the tx queue backs
3717	 * up in which case the top half of the kernel may backup
3718	 * due to a lack of tx descriptors.
3719	 */
3720	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
3721	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
3722	if (qnum == -1) {
3723		/*
3724		 * NB: don't print a message, this happens
3725		 * normally on parts with too few tx queues
3726		 */
3727		return NULL;
3728	}
3729	if (qnum >= N(sc->sc_txq)) {
3730		device_printf(sc->sc_dev,
3731			"hal qnum %u out of range, max %zu!\n",
3732			qnum, N(sc->sc_txq));
3733		ath_hal_releasetxqueue(ah, qnum);
3734		return NULL;
3735	}
3736	if (!ATH_TXQ_SETUP(sc, qnum)) {
3737		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
3738		sc->sc_txqsetup |= 1<<qnum;
3739	}
3740	return &sc->sc_txq[qnum];
3741#undef N
3742}
3743
3744/*
3745 * Setup a hardware data transmit queue for the specified
3746 * access control.  The hal may not support all requested
3747 * queues in which case it will return a reference to a
3748 * previously setup queue.  We record the mapping from ac's
3749 * to h/w queues for use by ath_tx_start and also track
3750 * the set of h/w queues being used to optimize work in the
3751 * transmit interrupt handler and related routines.
3752 */
3753static int
3754ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
3755{
3756#define	N(a)	(sizeof(a)/sizeof(a[0]))
3757	struct ath_txq *txq;
3758
3759	if (ac >= N(sc->sc_ac2q)) {
3760		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
3761			ac, N(sc->sc_ac2q));
3762		return 0;
3763	}
3764	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
3765	if (txq != NULL) {
3766		txq->axq_ac = ac;
3767		sc->sc_ac2q[ac] = txq;
3768		return 1;
3769	} else
3770		return 0;
3771#undef N
3772}
3773
3774/*
3775 * Update WME parameters for a transmit queue.
3776 */
3777static int
3778ath_txq_update(struct ath_softc *sc, int ac)
3779{
3780#define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
3781#define	ATH_TXOP_TO_US(v)		(v<<5)
3782	struct ifnet *ifp = sc->sc_ifp;
3783	struct ieee80211com *ic = ifp->if_l2com;
3784	struct ath_txq *txq = sc->sc_ac2q[ac];
3785	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3786	struct ath_hal *ah = sc->sc_ah;
3787	HAL_TXQ_INFO qi;
3788
3789	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
3790#ifdef IEEE80211_SUPPORT_TDMA
3791	if (sc->sc_tdma) {
3792		/*
3793		 * AIFS is zero so there's no pre-transmit wait.  The
3794		 * burst time defines the slot duration and is configured
3795		 * through net80211.  The QCU is setup to not do post-xmit
3796		 * back off, lockout all lower-priority QCU's, and fire
3797		 * off the DMA beacon alert timer which is setup based
3798		 * on the slot configuration.
3799		 */
3800		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
3801			      | HAL_TXQ_TXERRINT_ENABLE
3802			      | HAL_TXQ_TXURNINT_ENABLE
3803			      | HAL_TXQ_TXEOLINT_ENABLE
3804			      | HAL_TXQ_DBA_GATED
3805			      | HAL_TXQ_BACKOFF_DISABLE
3806			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
3807			      ;
3808		qi.tqi_aifs = 0;
3809		/* XXX +dbaprep? */
3810		qi.tqi_readyTime = sc->sc_tdmaslotlen;
3811		qi.tqi_burstTime = qi.tqi_readyTime;
3812	} else {
3813#endif
3814		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
3815			      | HAL_TXQ_TXERRINT_ENABLE
3816			      | HAL_TXQ_TXDESCINT_ENABLE
3817			      | HAL_TXQ_TXURNINT_ENABLE
3818			      ;
3819		qi.tqi_aifs = wmep->wmep_aifsn;
3820		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3821		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
3822		qi.tqi_readyTime = 0;
3823		qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
3824#ifdef IEEE80211_SUPPORT_TDMA
3825	}
3826#endif
3827
3828	DPRINTF(sc, ATH_DEBUG_RESET,
3829	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
3830	    __func__, txq->axq_qnum, qi.tqi_qflags,
3831	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
3832
3833	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
3834		if_printf(ifp, "unable to update hardware queue "
3835			"parameters for %s traffic!\n",
3836			ieee80211_wme_acnames[ac]);
3837		return 0;
3838	} else {
3839		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
3840		return 1;
3841	}
3842#undef ATH_TXOP_TO_US
3843#undef ATH_EXPONENT_TO_VALUE
3844}
3845
3846/*
3847 * Callback from the 802.11 layer to update WME parameters.
3848 */
3849static int
3850ath_wme_update(struct ieee80211com *ic)
3851{
3852	struct ath_softc *sc = ic->ic_ifp->if_softc;
3853
3854	return !ath_txq_update(sc, WME_AC_BE) ||
3855	    !ath_txq_update(sc, WME_AC_BK) ||
3856	    !ath_txq_update(sc, WME_AC_VI) ||
3857	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
3858}
3859
3860/*
3861 * Reclaim resources for a setup queue.
3862 */
3863static void
3864ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
3865{
3866
3867	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
3868	ATH_TXQ_LOCK_DESTROY(txq);
3869	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
3870}
3871
3872/*
3873 * Reclaim all tx queue resources.
3874 */
3875static void
3876ath_tx_cleanup(struct ath_softc *sc)
3877{
3878	int i;
3879
3880	ATH_TXBUF_LOCK_DESTROY(sc);
3881	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3882		if (ATH_TXQ_SETUP(sc, i))
3883			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
3884}
3885
3886/*
3887 * Return h/w rate index for an IEEE rate (w/o basic rate bit)
3888 * using the current rates in sc_rixmap.
3889 */
3890int
3891ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
3892{
3893	int rix = sc->sc_rixmap[rate];
3894	/* NB: return lowest rix for invalid rate */
3895	return (rix == 0xff ? 0 : rix);
3896}
3897
3898/*
3899 * Process completed xmit descriptors from the specified queue.
3900 */
3901static int
3902ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
3903{
3904	struct ath_hal *ah = sc->sc_ah;
3905	struct ifnet *ifp = sc->sc_ifp;
3906	struct ieee80211com *ic = ifp->if_l2com;
3907	struct ath_buf *bf, *last;
3908	struct ath_desc *ds, *ds0;
3909	struct ath_tx_status *ts;
3910	struct ieee80211_node *ni;
3911	struct ath_node *an;
3912	int sr, lr, pri, nacked;
3913	HAL_STATUS status;
3914
3915	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
3916		__func__, txq->axq_qnum,
3917		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
3918		txq->axq_link);
3919	nacked = 0;
3920	for (;;) {
3921		ATH_TXQ_LOCK(txq);
3922		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
3923		bf = STAILQ_FIRST(&txq->axq_q);
3924		if (bf == NULL) {
3925			ATH_TXQ_UNLOCK(txq);
3926			break;
3927		}
3928		ds0 = &bf->bf_desc[0];
3929		ds = &bf->bf_desc[bf->bf_nseg - 1];
3930		ts = &bf->bf_status.ds_txstat;
3931		status = ath_hal_txprocdesc(ah, ds, ts);
3932#ifdef ATH_DEBUG
3933		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
3934			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
3935			    status == HAL_OK);
3936#endif
3937		if (status == HAL_EINPROGRESS) {
3938			ATH_TXQ_UNLOCK(txq);
3939			break;
3940		}
3941		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
3942#ifdef IEEE80211_SUPPORT_TDMA
3943		if (txq->axq_depth > 0) {
3944			/*
3945			 * More frames follow.  Mark the buffer busy
3946			 * so it's not re-used while the hardware may
3947			 * still re-read the link field in the descriptor.
3948			 */
3949			bf->bf_flags |= ATH_BUF_BUSY;
3950		} else
3951#else
3952		if (txq->axq_depth == 0)
3953#endif
3954			txq->axq_link = NULL;
3955		ATH_TXQ_UNLOCK(txq);
3956
3957		ni = bf->bf_node;
3958		if (ni != NULL) {
3959			an = ATH_NODE(ni);
3960			if (ts->ts_status == 0) {
3961				u_int8_t txant = ts->ts_antenna;
3962				sc->sc_stats.ast_ant_tx[txant]++;
3963				sc->sc_ant_tx[txant]++;
3964				if (ts->ts_finaltsi != 0)
3965					sc->sc_stats.ast_tx_altrate++;
3966				pri = M_WME_GETAC(bf->bf_m);
3967				if (pri >= WME_AC_VO)
3968					ic->ic_wme.wme_hipri_traffic++;
3969				if ((bf->bf_txflags & HAL_TXDESC_NOACK) == 0)
3970					ni->ni_inact = ni->ni_inact_reload;
3971			} else {
3972				if (ts->ts_status & HAL_TXERR_XRETRY)
3973					sc->sc_stats.ast_tx_xretries++;
3974				if (ts->ts_status & HAL_TXERR_FIFO)
3975					sc->sc_stats.ast_tx_fifoerr++;
3976				if (ts->ts_status & HAL_TXERR_FILT)
3977					sc->sc_stats.ast_tx_filtered++;
3978				if (ts->ts_status & HAL_TXERR_XTXOP)
3979					sc->sc_stats.ast_tx_xtxop++;
3980				if (ts->ts_status & HAL_TXERR_TIMER_EXPIRED)
3981					sc->sc_stats.ast_tx_timerexpired++;
3982
3983				/* XXX HAL_TX_DATA_UNDERRUN */
3984				/* XXX HAL_TX_DELIM_UNDERRUN */
3985
3986				if (bf->bf_m->m_flags & M_FF)
3987					sc->sc_stats.ast_ff_txerr++;
3988			}
3989			/* XXX when is this valid? */
3990			if (ts->ts_status & HAL_TX_DESC_CFG_ERR)
3991				sc->sc_stats.ast_tx_desccfgerr++;
3992
3993			sr = ts->ts_shortretry;
3994			lr = ts->ts_longretry;
3995			sc->sc_stats.ast_tx_shortretry += sr;
3996			sc->sc_stats.ast_tx_longretry += lr;
3997			/*
3998			 * Hand the descriptor to the rate control algorithm.
3999			 */
4000			if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
4001			    (bf->bf_txflags & HAL_TXDESC_NOACK) == 0) {
4002				/*
4003				 * If frame was ack'd update statistics,
4004				 * including the last rx time used to
4005				 * workaround phantom bmiss interrupts.
4006				 */
4007				if (ts->ts_status == 0) {
4008					nacked++;
4009					sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
4010					ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
4011						ts->ts_rssi);
4012				}
4013				ath_rate_tx_complete(sc, an, bf);
4014			}
4015			/*
4016			 * Do any tx complete callback.  Note this must
4017			 * be done before releasing the node reference.
4018			 */
4019			if (bf->bf_m->m_flags & M_TXCB)
4020				ieee80211_process_callback(ni, bf->bf_m,
4021				    (bf->bf_txflags & HAL_TXDESC_NOACK) == 0 ?
4022				        ts->ts_status : HAL_TXERR_XRETRY);
4023			ieee80211_free_node(ni);
4024		}
4025		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4026		    BUS_DMASYNC_POSTWRITE);
4027		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4028
4029		m_freem(bf->bf_m);
4030		bf->bf_m = NULL;
4031		bf->bf_node = NULL;
4032
4033		ATH_TXBUF_LOCK(sc);
4034		last = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
4035		if (last != NULL)
4036			last->bf_flags &= ~ATH_BUF_BUSY;
4037		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4038		ATH_TXBUF_UNLOCK(sc);
4039	}
4040#ifdef IEEE80211_SUPPORT_SUPERG
4041	/*
4042	 * Flush fast-frame staging queue when traffic slows.
4043	 */
4044	if (txq->axq_depth <= 1)
4045		ieee80211_ff_flush(ic, txq->axq_ac);
4046#endif
4047	return nacked;
4048}
4049
4050static __inline int
4051txqactive(struct ath_hal *ah, int qnum)
4052{
4053	u_int32_t txqs = 1<<qnum;
4054	ath_hal_gettxintrtxqs(ah, &txqs);
4055	return (txqs & (1<<qnum));
4056}
4057
4058/*
4059 * Deferred processing of transmit interrupt; special-cased
4060 * for a single hardware transmit queue (e.g. 5210 and 5211).
4061 */
4062static void
4063ath_tx_proc_q0(void *arg, int npending)
4064{
4065	struct ath_softc *sc = arg;
4066	struct ifnet *ifp = sc->sc_ifp;
4067
4068	if (txqactive(sc->sc_ah, 0) && ath_tx_processq(sc, &sc->sc_txq[0]))
4069		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4070	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
4071		ath_tx_processq(sc, sc->sc_cabq);
4072	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4073	sc->sc_wd_timer = 0;
4074
4075	if (sc->sc_softled)
4076		ath_led_event(sc, sc->sc_txrix);
4077
4078	ath_start(ifp);
4079}
4080
4081/*
4082 * Deferred processing of transmit interrupt; special-cased
4083 * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
4084 */
4085static void
4086ath_tx_proc_q0123(void *arg, int npending)
4087{
4088	struct ath_softc *sc = arg;
4089	struct ifnet *ifp = sc->sc_ifp;
4090	int nacked;
4091
4092	/*
4093	 * Process each active queue.
4094	 */
4095	nacked = 0;
4096	if (txqactive(sc->sc_ah, 0))
4097		nacked += ath_tx_processq(sc, &sc->sc_txq[0]);
4098	if (txqactive(sc->sc_ah, 1))
4099		nacked += ath_tx_processq(sc, &sc->sc_txq[1]);
4100	if (txqactive(sc->sc_ah, 2))
4101		nacked += ath_tx_processq(sc, &sc->sc_txq[2]);
4102	if (txqactive(sc->sc_ah, 3))
4103		nacked += ath_tx_processq(sc, &sc->sc_txq[3]);
4104	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
4105		ath_tx_processq(sc, sc->sc_cabq);
4106	if (nacked)
4107		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4108
4109	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4110	sc->sc_wd_timer = 0;
4111
4112	if (sc->sc_softled)
4113		ath_led_event(sc, sc->sc_txrix);
4114
4115	ath_start(ifp);
4116}
4117
4118/*
4119 * Deferred processing of transmit interrupt.
4120 */
4121static void
4122ath_tx_proc(void *arg, int npending)
4123{
4124	struct ath_softc *sc = arg;
4125	struct ifnet *ifp = sc->sc_ifp;
4126	int i, nacked;
4127
4128	/*
4129	 * Process each active queue.
4130	 */
4131	nacked = 0;
4132	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4133		if (ATH_TXQ_SETUP(sc, i) && txqactive(sc->sc_ah, i))
4134			nacked += ath_tx_processq(sc, &sc->sc_txq[i]);
4135	if (nacked)
4136		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4137
4138	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4139	sc->sc_wd_timer = 0;
4140
4141	if (sc->sc_softled)
4142		ath_led_event(sc, sc->sc_txrix);
4143
4144	ath_start(ifp);
4145}
4146
4147static void
4148ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
4149{
4150#ifdef ATH_DEBUG
4151	struct ath_hal *ah = sc->sc_ah;
4152#endif
4153	struct ieee80211_node *ni;
4154	struct ath_buf *bf;
4155	u_int ix;
4156
4157	/*
4158	 * NB: this assumes output has been stopped and
4159	 *     we do not need to block ath_tx_proc
4160	 */
4161	ATH_TXBUF_LOCK(sc);
4162	bf = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
4163	if (bf != NULL)
4164		bf->bf_flags &= ~ATH_BUF_BUSY;
4165	ATH_TXBUF_UNLOCK(sc);
4166	for (ix = 0;; ix++) {
4167		ATH_TXQ_LOCK(txq);
4168		bf = STAILQ_FIRST(&txq->axq_q);
4169		if (bf == NULL) {
4170			txq->axq_link = NULL;
4171			ATH_TXQ_UNLOCK(txq);
4172			break;
4173		}
4174		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
4175		ATH_TXQ_UNLOCK(txq);
4176#ifdef ATH_DEBUG
4177		if (sc->sc_debug & ATH_DEBUG_RESET) {
4178			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4179
4180			ath_printtxbuf(sc, bf, txq->axq_qnum, ix,
4181				ath_hal_txprocdesc(ah, bf->bf_desc,
4182				    &bf->bf_status.ds_txstat) == HAL_OK);
4183			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
4184			    bf->bf_m->m_len, 0, -1);
4185		}
4186#endif /* ATH_DEBUG */
4187		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4188		ni = bf->bf_node;
4189		bf->bf_node = NULL;
4190		if (ni != NULL) {
4191			/*
4192			 * Do any callback and reclaim the node reference.
4193			 */
4194			if (bf->bf_m->m_flags & M_TXCB)
4195				ieee80211_process_callback(ni, bf->bf_m, -1);
4196			ieee80211_free_node(ni);
4197		}
4198		m_freem(bf->bf_m);
4199		bf->bf_m = NULL;
4200		bf->bf_flags &= ~ATH_BUF_BUSY;
4201
4202		ATH_TXBUF_LOCK(sc);
4203		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4204		ATH_TXBUF_UNLOCK(sc);
4205	}
4206}
4207
4208static void
4209ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
4210{
4211	struct ath_hal *ah = sc->sc_ah;
4212
4213	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4214	    __func__, txq->axq_qnum,
4215	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
4216	    txq->axq_link);
4217	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
4218}
4219
4220/*
4221 * Drain the transmit queues and reclaim resources.
4222 */
4223static void
4224ath_draintxq(struct ath_softc *sc)
4225{
4226	struct ath_hal *ah = sc->sc_ah;
4227	struct ifnet *ifp = sc->sc_ifp;
4228	int i;
4229
4230	/* XXX return value */
4231	if (!sc->sc_invalid) {
4232		/* don't touch the hardware if marked invalid */
4233		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4234		    __func__, sc->sc_bhalq,
4235		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
4236		    NULL);
4237		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
4238		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4239			if (ATH_TXQ_SETUP(sc, i))
4240				ath_tx_stopdma(sc, &sc->sc_txq[i]);
4241	}
4242	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4243		if (ATH_TXQ_SETUP(sc, i))
4244			ath_tx_draintxq(sc, &sc->sc_txq[i]);
4245#ifdef ATH_DEBUG
4246	if (sc->sc_debug & ATH_DEBUG_RESET) {
4247		struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
4248		if (bf != NULL && bf->bf_m != NULL) {
4249			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
4250				ath_hal_txprocdesc(ah, bf->bf_desc,
4251				    &bf->bf_status.ds_txstat) == HAL_OK);
4252			ieee80211_dump_pkt(ifp->if_l2com,
4253			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
4254			    0, -1);
4255		}
4256	}
4257#endif /* ATH_DEBUG */
4258	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4259	sc->sc_wd_timer = 0;
4260}
4261
4262/*
4263 * Disable the receive h/w in preparation for a reset.
4264 */
4265static void
4266ath_stoprecv(struct ath_softc *sc)
4267{
4268#define	PA2DESC(_sc, _pa) \
4269	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
4270		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
4271	struct ath_hal *ah = sc->sc_ah;
4272
4273	ath_hal_stoppcurecv(ah);	/* disable PCU */
4274	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
4275	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
4276	DELAY(3000);			/* 3ms is long enough for 1 frame */
4277#ifdef ATH_DEBUG
4278	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
4279		struct ath_buf *bf;
4280		u_int ix;
4281
4282		printf("%s: rx queue %p, link %p\n", __func__,
4283			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
4284		ix = 0;
4285		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4286			struct ath_desc *ds = bf->bf_desc;
4287			struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
4288			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
4289				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
4290			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
4291				ath_printrxbuf(sc, bf, ix, status == HAL_OK);
4292			ix++;
4293		}
4294	}
4295#endif
4296	if (sc->sc_rxpending != NULL) {
4297		m_freem(sc->sc_rxpending);
4298		sc->sc_rxpending = NULL;
4299	}
4300	sc->sc_rxlink = NULL;		/* just in case */
4301#undef PA2DESC
4302}
4303
4304/*
4305 * Enable the receive h/w following a reset.
4306 */
4307static int
4308ath_startrecv(struct ath_softc *sc)
4309{
4310	struct ath_hal *ah = sc->sc_ah;
4311	struct ath_buf *bf;
4312
4313	sc->sc_rxlink = NULL;
4314	sc->sc_rxpending = NULL;
4315	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4316		int error = ath_rxbuf_init(sc, bf);
4317		if (error != 0) {
4318			DPRINTF(sc, ATH_DEBUG_RECV,
4319				"%s: ath_rxbuf_init failed %d\n",
4320				__func__, error);
4321			return error;
4322		}
4323	}
4324
4325	bf = STAILQ_FIRST(&sc->sc_rxbuf);
4326	ath_hal_putrxbuf(ah, bf->bf_daddr);
4327	ath_hal_rxena(ah);		/* enable recv descriptors */
4328	ath_mode_init(sc);		/* set filters, etc. */
4329	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
4330	return 0;
4331}
4332
4333/*
4334 * Update internal state after a channel change.
4335 */
4336static void
4337ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
4338{
4339	enum ieee80211_phymode mode;
4340
4341	/*
4342	 * Change channels and update the h/w rate map
4343	 * if we're switching; e.g. 11a to 11b/g.
4344	 */
4345	mode = ieee80211_chan2mode(chan);
4346	if (mode != sc->sc_curmode)
4347		ath_setcurmode(sc, mode);
4348	sc->sc_curchan = chan;
4349}
4350
4351/*
4352 * Set/change channels.  If the channel is really being changed,
4353 * it's done by resetting the chip.  To accomplish this we must
4354 * first cleanup any pending DMA, then restart stuff after a la
4355 * ath_init.
4356 */
4357static int
4358ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
4359{
4360	struct ifnet *ifp = sc->sc_ifp;
4361	struct ieee80211com *ic = ifp->if_l2com;
4362	struct ath_hal *ah = sc->sc_ah;
4363
4364	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
4365	    __func__, ieee80211_chan2ieee(ic, chan),
4366	    chan->ic_freq, chan->ic_flags);
4367	if (chan != sc->sc_curchan) {
4368		HAL_STATUS status;
4369		/*
4370		 * To switch channels clear any pending DMA operations;
4371		 * wait long enough for the RX fifo to drain, reset the
4372		 * hardware at the new frequency, and then re-enable
4373		 * the relevant bits of the h/w.
4374		 */
4375		ath_hal_intrset(ah, 0);		/* disable interrupts */
4376		ath_draintxq(sc);		/* clear pending tx frames */
4377		ath_stoprecv(sc);		/* turn off frame recv */
4378		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
4379			if_printf(ifp, "%s: unable to reset "
4380			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
4381			    __func__, ieee80211_chan2ieee(ic, chan),
4382			    chan->ic_freq, chan->ic_flags, status);
4383			return EIO;
4384		}
4385		sc->sc_diversity = ath_hal_getdiversity(ah);
4386
4387		/*
4388		 * Re-enable rx framework.
4389		 */
4390		if (ath_startrecv(sc) != 0) {
4391			if_printf(ifp, "%s: unable to restart recv logic\n",
4392			    __func__);
4393			return EIO;
4394		}
4395
4396		/*
4397		 * Change channels and update the h/w rate map
4398		 * if we're switching; e.g. 11a to 11b/g.
4399		 */
4400		ath_chan_change(sc, chan);
4401
4402		/*
4403		 * Re-enable interrupts.
4404		 */
4405		ath_hal_intrset(ah, sc->sc_imask);
4406	}
4407	return 0;
4408}
4409
4410/*
4411 * Periodically recalibrate the PHY to account
4412 * for temperature/environment changes.
4413 */
4414static void
4415ath_calibrate(void *arg)
4416{
4417	struct ath_softc *sc = arg;
4418	struct ath_hal *ah = sc->sc_ah;
4419	struct ifnet *ifp = sc->sc_ifp;
4420	struct ieee80211com *ic = ifp->if_l2com;
4421	HAL_BOOL longCal, isCalDone;
4422	HAL_BOOL aniCal, shortCal = AH_FALSE;
4423	int nextcal;
4424
4425	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
4426		goto restart;
4427	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
4428	aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
4429	if (sc->sc_doresetcal)
4430		shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);
4431
4432	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
4433	if (aniCal) {
4434		sc->sc_stats.ast_ani_cal++;
4435		sc->sc_lastani = ticks;
4436		ath_hal_ani_poll(ah, sc->sc_curchan);
4437	}
4438
4439	if (longCal) {
4440		sc->sc_stats.ast_per_cal++;
4441		sc->sc_lastlongcal = ticks;
4442		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4443			/*
4444			 * Rfgain is out of bounds, reset the chip
4445			 * to load new gain values.
4446			 */
4447			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4448				"%s: rfgain change\n", __func__);
4449			sc->sc_stats.ast_per_rfgain++;
4450			ath_reset(ifp);
4451		}
4452		/*
4453		 * If this long cal is after an idle period, then
4454		 * reset the data collection state so we start fresh.
4455		 */
4456		if (sc->sc_resetcal) {
4457			(void) ath_hal_calreset(ah, sc->sc_curchan);
4458			sc->sc_lastcalreset = ticks;
4459			sc->sc_lastshortcal = ticks;
4460			sc->sc_resetcal = 0;
4461			sc->sc_doresetcal = AH_TRUE;
4462		}
4463	}
4464
4465	/* Only call if we're doing a short/long cal, not for ANI calibration */
4466	if (shortCal || longCal) {
4467		if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
4468			if (longCal) {
4469				/*
4470				 * Calibrate noise floor data again in case of change.
4471				 */
4472				ath_hal_process_noisefloor(ah);
4473			}
4474		} else {
4475			DPRINTF(sc, ATH_DEBUG_ANY,
4476				"%s: calibration of channel %u failed\n",
4477				__func__, sc->sc_curchan->ic_freq);
4478			sc->sc_stats.ast_per_calfail++;
4479		}
4480		if (shortCal)
4481			sc->sc_lastshortcal = ticks;
4482	}
4483	if (!isCalDone) {
4484restart:
4485		/*
4486		 * Use a shorter interval to potentially collect multiple
4487		 * data samples required to complete calibration.  Once
4488		 * we're told the work is done we drop back to a longer
4489		 * interval between requests.  We're more aggressive doing
4490		 * work when operating as an AP to improve operation right
4491		 * after startup.
4492		 */
4493		sc->sc_lastshortcal = ticks;
4494		nextcal = ath_shortcalinterval*hz/1000;
4495		if (sc->sc_opmode != HAL_M_HOSTAP)
4496			nextcal *= 10;
4497		sc->sc_doresetcal = AH_TRUE;
4498	} else {
4499		/* nextcal should be the shortest time for next event */
4500		nextcal = ath_longcalinterval*hz;
4501		if (sc->sc_lastcalreset == 0)
4502			sc->sc_lastcalreset = sc->sc_lastlongcal;
4503		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
4504			sc->sc_resetcal = 1;	/* setup reset next trip */
4505		sc->sc_doresetcal = AH_FALSE;
4506	}
4507	/* ANI calibration may occur more often than short/long/resetcal */
4508	if (ath_anicalinterval > 0)
4509		nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);
4510
4511	if (nextcal != 0) {
4512		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
4513		    __func__, nextcal, isCalDone ? "" : "!");
4514		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
4515	} else {
4516		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
4517		    __func__);
4518		/* NB: don't rearm timer */
4519	}
4520}
4521
4522static void
4523ath_scan_start(struct ieee80211com *ic)
4524{
4525	struct ifnet *ifp = ic->ic_ifp;
4526	struct ath_softc *sc = ifp->if_softc;
4527	struct ath_hal *ah = sc->sc_ah;
4528	u_int32_t rfilt;
4529
4530	/* XXX calibration timer? */
4531
4532	sc->sc_scanning = 1;
4533	sc->sc_syncbeacon = 0;
4534	rfilt = ath_calcrxfilter(sc);
4535	ath_hal_setrxfilter(ah, rfilt);
4536	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
4537
4538	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
4539		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
4540}
4541
4542static void
4543ath_scan_end(struct ieee80211com *ic)
4544{
4545	struct ifnet *ifp = ic->ic_ifp;
4546	struct ath_softc *sc = ifp->if_softc;
4547	struct ath_hal *ah = sc->sc_ah;
4548	u_int32_t rfilt;
4549
4550	sc->sc_scanning = 0;
4551	rfilt = ath_calcrxfilter(sc);
4552	ath_hal_setrxfilter(ah, rfilt);
4553	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4554
4555	ath_hal_process_noisefloor(ah);
4556
4557	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4558		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
4559		 sc->sc_curaid);
4560}
4561
4562static void
4563ath_set_channel(struct ieee80211com *ic)
4564{
4565	struct ifnet *ifp = ic->ic_ifp;
4566	struct ath_softc *sc = ifp->if_softc;
4567
4568	(void) ath_chan_set(sc, ic->ic_curchan);
4569	/*
4570	 * If we are returning to our bss channel then mark state
4571	 * so the next recv'd beacon's tsf will be used to sync the
4572	 * beacon timers.  Note that since we only hear beacons in
4573	 * sta/ibss mode this has no effect in other operating modes.
4574	 */
4575	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
4576		sc->sc_syncbeacon = 1;
4577}
4578
4579/*
4580 * Walk the vap list and check if there any vap's in RUN state.
4581 */
4582static int
4583ath_isanyrunningvaps(struct ieee80211vap *this)
4584{
4585	struct ieee80211com *ic = this->iv_ic;
4586	struct ieee80211vap *vap;
4587
4588	IEEE80211_LOCK_ASSERT(ic);
4589
4590	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
4591		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
4592			return 1;
4593	}
4594	return 0;
4595}
4596
4597static int
4598ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
4599{
4600	struct ieee80211com *ic = vap->iv_ic;
4601	struct ath_softc *sc = ic->ic_ifp->if_softc;
4602	struct ath_vap *avp = ATH_VAP(vap);
4603	struct ath_hal *ah = sc->sc_ah;
4604	struct ieee80211_node *ni = NULL;
4605	int i, error, stamode;
4606	u_int32_t rfilt;
4607	static const HAL_LED_STATE leds[] = {
4608	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
4609	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
4610	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
4611	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
4612	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
4613	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
4614	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
4615	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
4616	};
4617
4618	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
4619		ieee80211_state_name[vap->iv_state],
4620		ieee80211_state_name[nstate]);
4621
4622	callout_drain(&sc->sc_cal_ch);
4623	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
4624
4625	if (nstate == IEEE80211_S_SCAN) {
4626		/*
4627		 * Scanning: turn off beacon miss and don't beacon.
4628		 * Mark beacon state so when we reach RUN state we'll
4629		 * [re]setup beacons.  Unblock the task q thread so
4630		 * deferred interrupt processing is done.
4631		 */
4632		ath_hal_intrset(ah,
4633		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
4634		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4635		sc->sc_beacons = 0;
4636		taskqueue_unblock(sc->sc_tq);
4637	}
4638
4639	ni = vap->iv_bss;
4640	rfilt = ath_calcrxfilter(sc);
4641	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
4642		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
4643		   vap->iv_opmode == IEEE80211_M_IBSS);
4644	if (stamode && nstate == IEEE80211_S_RUN) {
4645		sc->sc_curaid = ni->ni_associd;
4646		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
4647		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4648	}
4649	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4650	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
4651	ath_hal_setrxfilter(ah, rfilt);
4652
4653	/* XXX is this to restore keycache on resume? */
4654	if (vap->iv_opmode != IEEE80211_M_STA &&
4655	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
4656		for (i = 0; i < IEEE80211_WEP_NKID; i++)
4657			if (ath_hal_keyisvalid(ah, i))
4658				ath_hal_keysetmac(ah, i, ni->ni_bssid);
4659	}
4660
4661	/*
4662	 * Invoke the parent method to do net80211 work.
4663	 */
4664	error = avp->av_newstate(vap, nstate, arg);
4665	if (error != 0)
4666		goto bad;
4667
4668	if (nstate == IEEE80211_S_RUN) {
4669		/* NB: collect bss node again, it may have changed */
4670		ni = vap->iv_bss;
4671
4672		DPRINTF(sc, ATH_DEBUG_STATE,
4673		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
4674		    "capinfo 0x%04x chan %d\n", __func__,
4675		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
4676		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
4677
4678		switch (vap->iv_opmode) {
4679#ifdef IEEE80211_SUPPORT_TDMA
4680		case IEEE80211_M_AHDEMO:
4681			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
4682				break;
4683			/* fall thru... */
4684#endif
4685		case IEEE80211_M_HOSTAP:
4686		case IEEE80211_M_IBSS:
4687		case IEEE80211_M_MBSS:
4688			/*
4689			 * Allocate and setup the beacon frame.
4690			 *
4691			 * Stop any previous beacon DMA.  This may be
4692			 * necessary, for example, when an ibss merge
4693			 * causes reconfiguration; there will be a state
4694			 * transition from RUN->RUN that means we may
4695			 * be called with beacon transmission active.
4696			 */
4697			ath_hal_stoptxdma(ah, sc->sc_bhalq);
4698
4699			error = ath_beacon_alloc(sc, ni);
4700			if (error != 0)
4701				goto bad;
4702			/*
4703			 * If joining an adhoc network defer beacon timer
4704			 * configuration to the next beacon frame so we
4705			 * have a current TSF to use.  Otherwise we're
4706			 * starting an ibss/bss so there's no need to delay;
4707			 * if this is the first vap moving to RUN state, then
4708			 * beacon state needs to be [re]configured.
4709			 */
4710			if (vap->iv_opmode == IEEE80211_M_IBSS &&
4711			    ni->ni_tstamp.tsf != 0) {
4712				sc->sc_syncbeacon = 1;
4713			} else if (!sc->sc_beacons) {
4714#ifdef IEEE80211_SUPPORT_TDMA
4715				if (vap->iv_caps & IEEE80211_C_TDMA)
4716					ath_tdma_config(sc, vap);
4717				else
4718#endif
4719					ath_beacon_config(sc, vap);
4720				sc->sc_beacons = 1;
4721			}
4722			break;
4723		case IEEE80211_M_STA:
4724			/*
4725			 * Defer beacon timer configuration to the next
4726			 * beacon frame so we have a current TSF to use
4727			 * (any TSF collected when scanning is likely old).
4728			 */
4729			sc->sc_syncbeacon = 1;
4730			break;
4731		case IEEE80211_M_MONITOR:
4732			/*
4733			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
4734			 * transitions so we must re-enable interrupts here to
4735			 * handle the case of a single monitor mode vap.
4736			 */
4737			ath_hal_intrset(ah, sc->sc_imask);
4738			break;
4739		case IEEE80211_M_WDS:
4740			break;
4741		default:
4742			break;
4743		}
4744		/*
4745		 * Let the hal process statistics collected during a
4746		 * scan so it can provide calibrated noise floor data.
4747		 */
4748		ath_hal_process_noisefloor(ah);
4749		/*
4750		 * Reset rssi stats; maybe not the best place...
4751		 */
4752		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
4753		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
4754		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
4755		/*
4756		 * Finally, start any timers and the task q thread
4757		 * (in case we didn't go through SCAN state).
4758		 */
4759		if (ath_longcalinterval != 0) {
4760			/* start periodic recalibration timer */
4761			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
4762		} else {
4763			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4764			    "%s: calibration disabled\n", __func__);
4765		}
4766		taskqueue_unblock(sc->sc_tq);
4767	} else if (nstate == IEEE80211_S_INIT) {
4768		/*
4769		 * If there are no vaps left in RUN state then
4770		 * shutdown host/driver operation:
4771		 * o disable interrupts
4772		 * o disable the task queue thread
4773		 * o mark beacon processing as stopped
4774		 */
4775		if (!ath_isanyrunningvaps(vap)) {
4776			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4777			/* disable interrupts  */
4778			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
4779			taskqueue_block(sc->sc_tq);
4780			sc->sc_beacons = 0;
4781		}
4782#ifdef IEEE80211_SUPPORT_TDMA
4783		ath_hal_setcca(ah, AH_TRUE);
4784#endif
4785	}
4786bad:
4787	return error;
4788}
4789
4790/*
4791 * Allocate a key cache slot to the station so we can
4792 * setup a mapping from key index to node. The key cache
4793 * slot is needed for managing antenna state and for
4794 * compression when stations do not use crypto.  We do
4795 * it uniliaterally here; if crypto is employed this slot
4796 * will be reassigned.
4797 */
4798static void
4799ath_setup_stationkey(struct ieee80211_node *ni)
4800{
4801	struct ieee80211vap *vap = ni->ni_vap;
4802	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4803	ieee80211_keyix keyix, rxkeyix;
4804
4805	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
4806		/*
4807		 * Key cache is full; we'll fall back to doing
4808		 * the more expensive lookup in software.  Note
4809		 * this also means no h/w compression.
4810		 */
4811		/* XXX msg+statistic */
4812	} else {
4813		/* XXX locking? */
4814		ni->ni_ucastkey.wk_keyix = keyix;
4815		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
4816		/* NB: must mark device key to get called back on delete */
4817		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
4818		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
4819		/* NB: this will create a pass-thru key entry */
4820		ath_keyset(sc, &ni->ni_ucastkey, vap->iv_bss);
4821	}
4822}
4823
4824/*
4825 * Setup driver-specific state for a newly associated node.
4826 * Note that we're called also on a re-associate, the isnew
4827 * param tells us if this is the first time or not.
4828 */
4829static void
4830ath_newassoc(struct ieee80211_node *ni, int isnew)
4831{
4832	struct ath_node *an = ATH_NODE(ni);
4833	struct ieee80211vap *vap = ni->ni_vap;
4834	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4835	const struct ieee80211_txparam *tp = ni->ni_txparms;
4836
4837	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
4838	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
4839
4840	ath_rate_newassoc(sc, an, isnew);
4841	if (isnew &&
4842	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
4843	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
4844		ath_setup_stationkey(ni);
4845}
4846
4847static int
4848ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
4849	int nchans, struct ieee80211_channel chans[])
4850{
4851	struct ath_softc *sc = ic->ic_ifp->if_softc;
4852	struct ath_hal *ah = sc->sc_ah;
4853	HAL_STATUS status;
4854
4855	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
4856	    "%s: rd %u cc %u location %c%s\n",
4857	    __func__, reg->regdomain, reg->country, reg->location,
4858	    reg->ecm ? " ecm" : "");
4859
4860	status = ath_hal_set_channels(ah, chans, nchans,
4861	    reg->country, reg->regdomain);
4862	if (status != HAL_OK) {
4863		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
4864		    __func__, status);
4865		return EINVAL;		/* XXX */
4866	}
4867	return 0;
4868}
4869
4870static void
4871ath_getradiocaps(struct ieee80211com *ic,
4872	int maxchans, int *nchans, struct ieee80211_channel chans[])
4873{
4874	struct ath_softc *sc = ic->ic_ifp->if_softc;
4875	struct ath_hal *ah = sc->sc_ah;
4876
4877	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
4878	    __func__, SKU_DEBUG, CTRY_DEFAULT);
4879
4880	/* XXX check return */
4881	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
4882	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
4883
4884}
4885
4886static int
4887ath_getchannels(struct ath_softc *sc)
4888{
4889	struct ifnet *ifp = sc->sc_ifp;
4890	struct ieee80211com *ic = ifp->if_l2com;
4891	struct ath_hal *ah = sc->sc_ah;
4892	HAL_STATUS status;
4893
4894	/*
4895	 * Collect channel set based on EEPROM contents.
4896	 */
4897	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
4898	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
4899	if (status != HAL_OK) {
4900		if_printf(ifp, "%s: unable to collect channel list from hal, "
4901		    "status %d\n", __func__, status);
4902		return EINVAL;
4903	}
4904	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
4905	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
4906	/* XXX map Atheros sku's to net80211 SKU's */
4907	/* XXX net80211 types too small */
4908	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
4909	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
4910	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
4911	ic->ic_regdomain.isocc[1] = ' ';
4912
4913	ic->ic_regdomain.ecm = 1;
4914	ic->ic_regdomain.location = 'I';
4915
4916	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
4917	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
4918	    __func__, sc->sc_eerd, sc->sc_eecc,
4919	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
4920	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
4921	return 0;
4922}
4923
4924static void
4925ath_led_done(void *arg)
4926{
4927	struct ath_softc *sc = arg;
4928
4929	sc->sc_blinking = 0;
4930}
4931
4932/*
4933 * Turn the LED off: flip the pin and then set a timer so no
4934 * update will happen for the specified duration.
4935 */
4936static void
4937ath_led_off(void *arg)
4938{
4939	struct ath_softc *sc = arg;
4940
4941	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
4942	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
4943}
4944
4945/*
4946 * Blink the LED according to the specified on/off times.
4947 */
4948static void
4949ath_led_blink(struct ath_softc *sc, int on, int off)
4950{
4951	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
4952	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
4953	sc->sc_blinking = 1;
4954	sc->sc_ledoff = off;
4955	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
4956}
4957
4958static void
4959ath_led_event(struct ath_softc *sc, int rix)
4960{
4961	sc->sc_ledevent = ticks;	/* time of last event */
4962	if (sc->sc_blinking)		/* don't interrupt active blink */
4963		return;
4964	ath_led_blink(sc, sc->sc_hwmap[rix].ledon, sc->sc_hwmap[rix].ledoff);
4965}
4966
4967static int
4968ath_rate_setup(struct ath_softc *sc, u_int mode)
4969{
4970	struct ath_hal *ah = sc->sc_ah;
4971	const HAL_RATE_TABLE *rt;
4972
4973	switch (mode) {
4974	case IEEE80211_MODE_11A:
4975		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
4976		break;
4977	case IEEE80211_MODE_HALF:
4978		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
4979		break;
4980	case IEEE80211_MODE_QUARTER:
4981		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
4982		break;
4983	case IEEE80211_MODE_11B:
4984		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
4985		break;
4986	case IEEE80211_MODE_11G:
4987		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
4988		break;
4989	case IEEE80211_MODE_TURBO_A:
4990		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
4991		break;
4992	case IEEE80211_MODE_TURBO_G:
4993		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
4994		break;
4995	case IEEE80211_MODE_STURBO_A:
4996		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
4997		break;
4998	case IEEE80211_MODE_11NA:
4999		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
5000		break;
5001	case IEEE80211_MODE_11NG:
5002		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
5003		break;
5004	default:
5005		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
5006			__func__, mode);
5007		return 0;
5008	}
5009	sc->sc_rates[mode] = rt;
5010	return (rt != NULL);
5011}
5012
5013static void
5014ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
5015{
5016#define	N(a)	(sizeof(a)/sizeof(a[0]))
5017	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
5018	static const struct {
5019		u_int		rate;		/* tx/rx 802.11 rate */
5020		u_int16_t	timeOn;		/* LED on time (ms) */
5021		u_int16_t	timeOff;	/* LED off time (ms) */
5022	} blinkrates[] = {
5023		{ 108,  40,  10 },
5024		{  96,  44,  11 },
5025		{  72,  50,  13 },
5026		{  48,  57,  14 },
5027		{  36,  67,  16 },
5028		{  24,  80,  20 },
5029		{  22, 100,  25 },
5030		{  18, 133,  34 },
5031		{  12, 160,  40 },
5032		{  10, 200,  50 },
5033		{   6, 240,  58 },
5034		{   4, 267,  66 },
5035		{   2, 400, 100 },
5036		{   0, 500, 130 },
5037		/* XXX half/quarter rates */
5038	};
5039	const HAL_RATE_TABLE *rt;
5040	int i, j;
5041
5042	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
5043	rt = sc->sc_rates[mode];
5044	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
5045	for (i = 0; i < rt->rateCount; i++) {
5046		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
5047		if (rt->info[i].phy != IEEE80211_T_HT)
5048			sc->sc_rixmap[ieeerate] = i;
5049		else
5050			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
5051	}
5052	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
5053	for (i = 0; i < N(sc->sc_hwmap); i++) {
5054		if (i >= rt->rateCount) {
5055			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
5056			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
5057			continue;
5058		}
5059		sc->sc_hwmap[i].ieeerate =
5060			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
5061		if (rt->info[i].phy == IEEE80211_T_HT)
5062			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
5063		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
5064		if (rt->info[i].shortPreamble ||
5065		    rt->info[i].phy == IEEE80211_T_OFDM)
5066			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
5067		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
5068		for (j = 0; j < N(blinkrates)-1; j++)
5069			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
5070				break;
5071		/* NB: this uses the last entry if the rate isn't found */
5072		/* XXX beware of overlow */
5073		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
5074		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
5075	}
5076	sc->sc_currates = rt;
5077	sc->sc_curmode = mode;
5078	/*
5079	 * All protection frames are transmited at 2Mb/s for
5080	 * 11g, otherwise at 1Mb/s.
5081	 */
5082	if (mode == IEEE80211_MODE_11G)
5083		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
5084	else
5085		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
5086	/* NB: caller is responsible for resetting rate control state */
5087#undef N
5088}
5089
5090static void
5091ath_watchdog(void *arg)
5092{
5093	struct ath_softc *sc = arg;
5094
5095	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
5096		struct ifnet *ifp = sc->sc_ifp;
5097		uint32_t hangs;
5098
5099		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
5100		    hangs != 0) {
5101			if_printf(ifp, "%s hang detected (0x%x)\n",
5102			    hangs & 0xff ? "bb" : "mac", hangs);
5103		} else
5104			if_printf(ifp, "device timeout\n");
5105		ath_reset(ifp);
5106		ifp->if_oerrors++;
5107		sc->sc_stats.ast_watchdog++;
5108	}
5109	callout_schedule(&sc->sc_wd_ch, hz);
5110}
5111
5112#ifdef ATH_DIAGAPI
5113/*
5114 * Diagnostic interface to the HAL.  This is used by various
5115 * tools to do things like retrieve register contents for
5116 * debugging.  The mechanism is intentionally opaque so that
5117 * it can change frequently w/o concern for compatiblity.
5118 */
5119static int
5120ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
5121{
5122	struct ath_hal *ah = sc->sc_ah;
5123	u_int id = ad->ad_id & ATH_DIAG_ID;
5124	void *indata = NULL;
5125	void *outdata = NULL;
5126	u_int32_t insize = ad->ad_in_size;
5127	u_int32_t outsize = ad->ad_out_size;
5128	int error = 0;
5129
5130	if (ad->ad_id & ATH_DIAG_IN) {
5131		/*
5132		 * Copy in data.
5133		 */
5134		indata = malloc(insize, M_TEMP, M_NOWAIT);
5135		if (indata == NULL) {
5136			error = ENOMEM;
5137			goto bad;
5138		}
5139		error = copyin(ad->ad_in_data, indata, insize);
5140		if (error)
5141			goto bad;
5142	}
5143	if (ad->ad_id & ATH_DIAG_DYN) {
5144		/*
5145		 * Allocate a buffer for the results (otherwise the HAL
5146		 * returns a pointer to a buffer where we can read the
5147		 * results).  Note that we depend on the HAL leaving this
5148		 * pointer for us to use below in reclaiming the buffer;
5149		 * may want to be more defensive.
5150		 */
5151		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
5152		if (outdata == NULL) {
5153			error = ENOMEM;
5154			goto bad;
5155		}
5156	}
5157	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
5158		if (outsize < ad->ad_out_size)
5159			ad->ad_out_size = outsize;
5160		if (outdata != NULL)
5161			error = copyout(outdata, ad->ad_out_data,
5162					ad->ad_out_size);
5163	} else {
5164		error = EINVAL;
5165	}
5166bad:
5167	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
5168		free(indata, M_TEMP);
5169	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
5170		free(outdata, M_TEMP);
5171	return error;
5172}
5173#endif /* ATH_DIAGAPI */
5174
5175static int
5176ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
5177{
5178#define	IS_RUNNING(ifp) \
5179	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
5180	struct ath_softc *sc = ifp->if_softc;
5181	struct ieee80211com *ic = ifp->if_l2com;
5182	struct ifreq *ifr = (struct ifreq *)data;
5183	const HAL_RATE_TABLE *rt;
5184	int error = 0;
5185
5186	switch (cmd) {
5187	case SIOCSIFFLAGS:
5188		ATH_LOCK(sc);
5189		if (IS_RUNNING(ifp)) {
5190			/*
5191			 * To avoid rescanning another access point,
5192			 * do not call ath_init() here.  Instead,
5193			 * only reflect promisc mode settings.
5194			 */
5195			ath_mode_init(sc);
5196		} else if (ifp->if_flags & IFF_UP) {
5197			/*
5198			 * Beware of being called during attach/detach
5199			 * to reset promiscuous mode.  In that case we
5200			 * will still be marked UP but not RUNNING.
5201			 * However trying to re-init the interface
5202			 * is the wrong thing to do as we've already
5203			 * torn down much of our state.  There's
5204			 * probably a better way to deal with this.
5205			 */
5206			if (!sc->sc_invalid)
5207				ath_init(sc);	/* XXX lose error */
5208		} else {
5209			ath_stop_locked(ifp);
5210#ifdef notyet
5211			/* XXX must wakeup in places like ath_vap_delete */
5212			if (!sc->sc_invalid)
5213				ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
5214#endif
5215		}
5216		ATH_UNLOCK(sc);
5217		break;
5218	case SIOCGIFMEDIA:
5219	case SIOCSIFMEDIA:
5220		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
5221		break;
5222	case SIOCGATHSTATS:
5223		/* NB: embed these numbers to get a consistent view */
5224		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
5225		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
5226		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
5227		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
5228#ifdef IEEE80211_SUPPORT_TDMA
5229		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
5230		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
5231#endif
5232		rt = sc->sc_currates;
5233		sc->sc_stats.ast_tx_rate =
5234		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
5235		if (rt->info[sc->sc_txrix].phy & IEEE80211_T_HT)
5236			sc->sc_stats.ast_tx_rate |= IEEE80211_RATE_MCS;
5237		return copyout(&sc->sc_stats,
5238		    ifr->ifr_data, sizeof (sc->sc_stats));
5239	case SIOCZATHSTATS:
5240		error = priv_check(curthread, PRIV_DRIVER);
5241		if (error == 0)
5242			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
5243		break;
5244#ifdef ATH_DIAGAPI
5245	case SIOCGATHDIAG:
5246		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
5247		break;
5248#endif
5249	case SIOCGIFADDR:
5250		error = ether_ioctl(ifp, cmd, data);
5251		break;
5252	default:
5253		error = EINVAL;
5254		break;
5255	}
5256	return error;
5257#undef IS_RUNNING
5258}
5259
5260/*
5261 * Announce various information on device/driver attach.
5262 */
5263static void
5264ath_announce(struct ath_softc *sc)
5265{
5266	struct ifnet *ifp = sc->sc_ifp;
5267	struct ath_hal *ah = sc->sc_ah;
5268
5269	if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
5270		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
5271		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5272	if (bootverbose) {
5273		int i;
5274		for (i = 0; i <= WME_AC_VO; i++) {
5275			struct ath_txq *txq = sc->sc_ac2q[i];
5276			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5277				txq->axq_qnum, ieee80211_wme_acnames[i]);
5278		}
5279		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5280			sc->sc_cabq->axq_qnum);
5281		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5282	}
5283	if (ath_rxbuf != ATH_RXBUF)
5284		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5285	if (ath_txbuf != ATH_TXBUF)
5286		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5287	if (sc->sc_mcastkey && bootverbose)
5288		if_printf(ifp, "using multicast key search\n");
5289}
5290
5291#ifdef IEEE80211_SUPPORT_TDMA
5292static __inline uint32_t
5293ath_hal_getnexttbtt(struct ath_hal *ah)
5294{
5295#define	AR_TIMER0	0x8028
5296	return OS_REG_READ(ah, AR_TIMER0);
5297}
5298
5299static __inline void
5300ath_hal_adjusttsf(struct ath_hal *ah, int32_t tsfdelta)
5301{
5302	/* XXX handle wrap/overflow */
5303	OS_REG_WRITE(ah, AR_TSF_L32, OS_REG_READ(ah, AR_TSF_L32) + tsfdelta);
5304}
5305
5306static void
5307ath_tdma_settimers(struct ath_softc *sc, u_int32_t nexttbtt, u_int32_t bintval)
5308{
5309	struct ath_hal *ah = sc->sc_ah;
5310	HAL_BEACON_TIMERS bt;
5311
5312	bt.bt_intval = bintval | HAL_BEACON_ENA;
5313	bt.bt_nexttbtt = nexttbtt;
5314	bt.bt_nextdba = (nexttbtt<<3) - sc->sc_tdmadbaprep;
5315	bt.bt_nextswba = (nexttbtt<<3) - sc->sc_tdmaswbaprep;
5316	bt.bt_nextatim = nexttbtt+1;
5317	ath_hal_beaconsettimers(ah, &bt);
5318}
5319
5320/*
5321 * Calculate the beacon interval.  This is periodic in the
5322 * superframe for the bss.  We assume each station is configured
5323 * identically wrt transmit rate so the guard time we calculate
5324 * above will be the same on all stations.  Note we need to
5325 * factor in the xmit time because the hardware will schedule
5326 * a frame for transmit if the start of the frame is within
5327 * the burst time.  When we get hardware that properly kills
5328 * frames in the PCU we can reduce/eliminate the guard time.
5329 *
5330 * Roundup to 1024 is so we have 1 TU buffer in the guard time
5331 * to deal with the granularity of the nexttbtt timer.  11n MAC's
5332 * with 1us timer granularity should allow us to reduce/eliminate
5333 * this.
5334 */
5335static void
5336ath_tdma_bintvalsetup(struct ath_softc *sc,
5337	const struct ieee80211_tdma_state *tdma)
5338{
5339	/* copy from vap state (XXX check all vaps have same value?) */
5340	sc->sc_tdmaslotlen = tdma->tdma_slotlen;
5341
5342	sc->sc_tdmabintval = roundup((sc->sc_tdmaslotlen+sc->sc_tdmaguard) *
5343		tdma->tdma_slotcnt, 1024);
5344	sc->sc_tdmabintval >>= 10;		/* TSF -> TU */
5345	if (sc->sc_tdmabintval & 1)
5346		sc->sc_tdmabintval++;
5347
5348	if (tdma->tdma_slot == 0) {
5349		/*
5350		 * Only slot 0 beacons; other slots respond.
5351		 */
5352		sc->sc_imask |= HAL_INT_SWBA;
5353		sc->sc_tdmaswba = 0;		/* beacon immediately */
5354	} else {
5355		/* XXX all vaps must be slot 0 or slot !0 */
5356		sc->sc_imask &= ~HAL_INT_SWBA;
5357	}
5358}
5359
5360/*
5361 * Max 802.11 overhead.  This assumes no 4-address frames and
5362 * the encapsulation done by ieee80211_encap (llc).  We also
5363 * include potential crypto overhead.
5364 */
5365#define	IEEE80211_MAXOVERHEAD \
5366	(sizeof(struct ieee80211_qosframe) \
5367	 + sizeof(struct llc) \
5368	 + IEEE80211_ADDR_LEN \
5369	 + IEEE80211_WEP_IVLEN \
5370	 + IEEE80211_WEP_KIDLEN \
5371	 + IEEE80211_WEP_CRCLEN \
5372	 + IEEE80211_WEP_MICLEN \
5373	 + IEEE80211_CRC_LEN)
5374
5375/*
5376 * Setup initially for tdma operation.  Start the beacon
5377 * timers and enable SWBA if we are slot 0.  Otherwise
5378 * we wait for slot 0 to arrive so we can sync up before
5379 * starting to transmit.
5380 */
5381static void
5382ath_tdma_config(struct ath_softc *sc, struct ieee80211vap *vap)
5383{
5384	struct ath_hal *ah = sc->sc_ah;
5385	struct ifnet *ifp = sc->sc_ifp;
5386	struct ieee80211com *ic = ifp->if_l2com;
5387	const struct ieee80211_txparam *tp;
5388	const struct ieee80211_tdma_state *tdma = NULL;
5389	int rix;
5390
5391	if (vap == NULL) {
5392		vap = TAILQ_FIRST(&ic->ic_vaps);   /* XXX */
5393		if (vap == NULL) {
5394			if_printf(ifp, "%s: no vaps?\n", __func__);
5395			return;
5396		}
5397	}
5398	tp = vap->iv_bss->ni_txparms;
5399	/*
5400	 * Calculate the guard time for each slot.  This is the
5401	 * time to send a maximal-size frame according to the
5402	 * fixed/lowest transmit rate.  Note that the interface
5403	 * mtu does not include the 802.11 overhead so we must
5404	 * tack that on (ath_hal_computetxtime includes the
5405	 * preamble and plcp in it's calculation).
5406	 */
5407	tdma = vap->iv_tdma;
5408	if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
5409		rix = ath_tx_findrix(sc, tp->ucastrate);
5410	else
5411		rix = ath_tx_findrix(sc, tp->mcastrate);
5412	/* XXX short preamble assumed */
5413	sc->sc_tdmaguard = ath_hal_computetxtime(ah, sc->sc_currates,
5414		ifp->if_mtu + IEEE80211_MAXOVERHEAD, rix, AH_TRUE);
5415
5416	ath_hal_intrset(ah, 0);
5417
5418	ath_beaconq_config(sc);			/* setup h/w beacon q */
5419	if (sc->sc_setcca)
5420		ath_hal_setcca(ah, AH_FALSE);	/* disable CCA */
5421	ath_tdma_bintvalsetup(sc, tdma);	/* calculate beacon interval */
5422	ath_tdma_settimers(sc, sc->sc_tdmabintval,
5423		sc->sc_tdmabintval | HAL_BEACON_RESET_TSF);
5424	sc->sc_syncbeacon = 0;
5425
5426	sc->sc_avgtsfdeltap = TDMA_DUMMY_MARKER;
5427	sc->sc_avgtsfdeltam = TDMA_DUMMY_MARKER;
5428
5429	ath_hal_intrset(ah, sc->sc_imask);
5430
5431	DPRINTF(sc, ATH_DEBUG_TDMA, "%s: slot %u len %uus cnt %u "
5432	    "bsched %u guard %uus bintval %u TU dba prep %u\n", __func__,
5433	    tdma->tdma_slot, tdma->tdma_slotlen, tdma->tdma_slotcnt,
5434	    tdma->tdma_bintval, sc->sc_tdmaguard, sc->sc_tdmabintval,
5435	    sc->sc_tdmadbaprep);
5436}
5437
5438/*
5439 * Update tdma operation.  Called from the 802.11 layer
5440 * when a beacon is received from the TDMA station operating
5441 * in the slot immediately preceding us in the bss.  Use
5442 * the rx timestamp for the beacon frame to update our
5443 * beacon timers so we follow their schedule.  Note that
5444 * by using the rx timestamp we implicitly include the
5445 * propagation delay in our schedule.
5446 */
5447static void
5448ath_tdma_update(struct ieee80211_node *ni,
5449	const struct ieee80211_tdma_param *tdma, int changed)
5450{
5451#define	TSF_TO_TU(_h,_l) \
5452	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
5453#define	TU_TO_TSF(_tu)	(((u_int64_t)(_tu)) << 10)
5454	struct ieee80211vap *vap = ni->ni_vap;
5455	struct ieee80211com *ic = ni->ni_ic;
5456	struct ath_softc *sc = ic->ic_ifp->if_softc;
5457	struct ath_hal *ah = sc->sc_ah;
5458	const HAL_RATE_TABLE *rt = sc->sc_currates;
5459	u_int64_t tsf, rstamp, nextslot;
5460	u_int32_t txtime, nextslottu, timer0;
5461	int32_t tudelta, tsfdelta;
5462	const struct ath_rx_status *rs;
5463	int rix;
5464
5465	sc->sc_stats.ast_tdma_update++;
5466
5467	/*
5468	 * Check for and adopt configuration changes.
5469	 */
5470	if (changed != 0) {
5471		const struct ieee80211_tdma_state *ts = vap->iv_tdma;
5472
5473		ath_tdma_bintvalsetup(sc, ts);
5474		if (changed & TDMA_UPDATE_SLOTLEN)
5475			ath_wme_update(ic);
5476
5477		DPRINTF(sc, ATH_DEBUG_TDMA,
5478		    "%s: adopt slot %u slotcnt %u slotlen %u us "
5479		    "bintval %u TU\n", __func__,
5480		    ts->tdma_slot, ts->tdma_slotcnt, ts->tdma_slotlen,
5481		    sc->sc_tdmabintval);
5482
5483		/* XXX right? */
5484		ath_hal_intrset(ah, sc->sc_imask);
5485		/* NB: beacon timers programmed below */
5486	}
5487
5488	/* extend rx timestamp to 64 bits */
5489	rs = sc->sc_lastrs;
5490	tsf = ath_hal_gettsf64(ah);
5491	rstamp = ath_extend_tsf(rs->rs_tstamp, tsf);
5492	/*
5493	 * The rx timestamp is set by the hardware on completing
5494	 * reception (at the point where the rx descriptor is DMA'd
5495	 * to the host).  To find the start of our next slot we
5496	 * must adjust this time by the time required to send
5497	 * the packet just received.
5498	 */
5499	rix = rt->rateCodeToIndex[rs->rs_rate];
5500	txtime = ath_hal_computetxtime(ah, rt, rs->rs_datalen, rix,
5501	    rt->info[rix].shortPreamble);
5502	/* NB: << 9 is to cvt to TU and /2 */
5503	nextslot = (rstamp - txtime) + (sc->sc_tdmabintval << 9);
5504	nextslottu = TSF_TO_TU(nextslot>>32, nextslot) & HAL_BEACON_PERIOD;
5505
5506	/*
5507	 * TIMER0 is the h/w's idea of NextTBTT (in TU's).  Convert
5508	 * to usecs and calculate the difference between what the
5509	 * other station thinks and what we have programmed.  This
5510	 * lets us figure how to adjust our timers to match.  The
5511	 * adjustments are done by pulling the TSF forward and possibly
5512	 * rewriting the beacon timers.
5513	 */
5514	timer0 = ath_hal_getnexttbtt(ah);
5515	tsfdelta = (int32_t)((nextslot % TU_TO_TSF(HAL_BEACON_PERIOD+1)) - TU_TO_TSF(timer0));
5516
5517	DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
5518	    "tsfdelta %d avg +%d/-%d\n", tsfdelta,
5519	    TDMA_AVG(sc->sc_avgtsfdeltap), TDMA_AVG(sc->sc_avgtsfdeltam));
5520
5521	if (tsfdelta < 0) {
5522		TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
5523		TDMA_SAMPLE(sc->sc_avgtsfdeltam, -tsfdelta);
5524		tsfdelta = -tsfdelta % 1024;
5525		nextslottu++;
5526	} else if (tsfdelta > 0) {
5527		TDMA_SAMPLE(sc->sc_avgtsfdeltap, tsfdelta);
5528		TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
5529		tsfdelta = 1024 - (tsfdelta % 1024);
5530		nextslottu++;
5531	} else {
5532		TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
5533		TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
5534	}
5535	tudelta = nextslottu - timer0;
5536
5537	/*
5538	 * Copy sender's timetstamp into tdma ie so they can
5539	 * calculate roundtrip time.  We submit a beacon frame
5540	 * below after any timer adjustment.  The frame goes out
5541	 * at the next TBTT so the sender can calculate the
5542	 * roundtrip by inspecting the tdma ie in our beacon frame.
5543	 *
5544	 * NB: This tstamp is subtlely preserved when
5545	 *     IEEE80211_BEACON_TDMA is marked (e.g. when the
5546	 *     slot position changes) because ieee80211_add_tdma
5547	 *     skips over the data.
5548	 */
5549	memcpy(ATH_VAP(vap)->av_boff.bo_tdma +
5550		__offsetof(struct ieee80211_tdma_param, tdma_tstamp),
5551		&ni->ni_tstamp.data, 8);
5552#if 0
5553	DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
5554	    "tsf %llu nextslot %llu (%d, %d) nextslottu %u timer0 %u (%d)\n",
5555	    (unsigned long long) tsf, (unsigned long long) nextslot,
5556	    (int)(nextslot - tsf), tsfdelta,
5557	    nextslottu, timer0, tudelta);
5558#endif
5559	/*
5560	 * Adjust the beacon timers only when pulling them forward
5561	 * or when going back by less than the beacon interval.
5562	 * Negative jumps larger than the beacon interval seem to
5563	 * cause the timers to stop and generally cause instability.
5564	 * This basically filters out jumps due to missed beacons.
5565	 */
5566	if (tudelta != 0 && (tudelta > 0 || -tudelta < sc->sc_tdmabintval)) {
5567		ath_tdma_settimers(sc, nextslottu, sc->sc_tdmabintval);
5568		sc->sc_stats.ast_tdma_timers++;
5569	}
5570	if (tsfdelta > 0) {
5571		ath_hal_adjusttsf(ah, tsfdelta);
5572		sc->sc_stats.ast_tdma_tsf++;
5573	}
5574	ath_tdma_beacon_send(sc, vap);		/* prepare response */
5575#undef TU_TO_TSF
5576#undef TSF_TO_TU
5577}
5578
5579/*
5580 * Transmit a beacon frame at SWBA.  Dynamic updates
5581 * to the frame contents are done as needed.
5582 */
5583static void
5584ath_tdma_beacon_send(struct ath_softc *sc, struct ieee80211vap *vap)
5585{
5586	struct ath_hal *ah = sc->sc_ah;
5587	struct ath_buf *bf;
5588	int otherant;
5589
5590	/*
5591	 * Check if the previous beacon has gone out.  If
5592	 * not don't try to post another, skip this period
5593	 * and wait for the next.  Missed beacons indicate
5594	 * a problem and should not occur.  If we miss too
5595	 * many consecutive beacons reset the device.
5596	 */
5597	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
5598		sc->sc_bmisscount++;
5599		DPRINTF(sc, ATH_DEBUG_BEACON,
5600			"%s: missed %u consecutive beacons\n",
5601			__func__, sc->sc_bmisscount);
5602		if (sc->sc_bmisscount >= ath_bstuck_threshold)
5603			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
5604		return;
5605	}
5606	if (sc->sc_bmisscount != 0) {
5607		DPRINTF(sc, ATH_DEBUG_BEACON,
5608			"%s: resume beacon xmit after %u misses\n",
5609			__func__, sc->sc_bmisscount);
5610		sc->sc_bmisscount = 0;
5611	}
5612
5613	/*
5614	 * Check recent per-antenna transmit statistics and flip
5615	 * the default antenna if noticeably more frames went out
5616	 * on the non-default antenna.
5617	 * XXX assumes 2 anntenae
5618	 */
5619	if (!sc->sc_diversity) {
5620		otherant = sc->sc_defant & 1 ? 2 : 1;
5621		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
5622			ath_setdefantenna(sc, otherant);
5623		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
5624	}
5625
5626	bf = ath_beacon_generate(sc, vap);
5627	if (bf != NULL) {
5628		/*
5629		 * Stop any current dma and put the new frame on the queue.
5630		 * This should never fail since we check above that no frames
5631		 * are still pending on the queue.
5632		 */
5633		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
5634			DPRINTF(sc, ATH_DEBUG_ANY,
5635				"%s: beacon queue %u did not stop?\n",
5636				__func__, sc->sc_bhalq);
5637			/* NB: the HAL still stops DMA, so proceed */
5638		}
5639		ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
5640		ath_hal_txstart(ah, sc->sc_bhalq);
5641
5642		sc->sc_stats.ast_be_xmit++;		/* XXX per-vap? */
5643
5644		/*
5645		 * Record local TSF for our last send for use
5646		 * in arbitrating slot collisions.
5647		 */
5648		vap->iv_bss->ni_tstamp.tsf = ath_hal_gettsf64(ah);
5649	}
5650}
5651#endif /* IEEE80211_SUPPORT_TDMA */
5652
5653MODULE_VERSION(if_ath, 1);
5654MODULE_DEPEND(if_ath, wlan, 1, 1, 1);          /* 802.11 media layer */
5655