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