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