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