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