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