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