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