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