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