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