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