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