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