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