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