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