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