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