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