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