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