if_ath.c revision 155490
1/*-
2 * Copyright (c) 2002-2005 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 * 3. Neither the names of the above-listed copyright holders nor the names
16 *    of any contributors may be used to endorse or promote products derived
17 *    from this software without specific prior written permission.
18 *
19 * Alternatively, this software may be distributed under the terms of the
20 * GNU General Public License ("GPL") version 2 as published by the Free
21 * Software Foundation.
22 *
23 * NO WARRANTY
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
27 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
28 * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
29 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
32 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
34 * THE POSSIBILITY OF SUCH DAMAGES.
35 */
36
37#include <sys/cdefs.h>
38__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath.c 155490 2006-02-09 21:42:53Z sam $");
39
40/*
41 * Driver for the Atheros Wireless LAN controller.
42 *
43 * This software is derived from work of Atsushi Onoe; his contribution
44 * is greatly appreciated.
45 */
46
47#include "opt_inet.h"
48
49#include <sys/param.h>
50#include <sys/systm.h>
51#include <sys/sysctl.h>
52#include <sys/mbuf.h>
53#include <sys/malloc.h>
54#include <sys/lock.h>
55#include <sys/mutex.h>
56#include <sys/kernel.h>
57#include <sys/socket.h>
58#include <sys/sockio.h>
59#include <sys/errno.h>
60#include <sys/callout.h>
61#include <sys/bus.h>
62#include <sys/endian.h>
63
64#include <machine/bus.h>
65
66#include <net/if.h>
67#include <net/if_dl.h>
68#include <net/if_media.h>
69#include <net/if_types.h>
70#include <net/if_arp.h>
71#include <net/ethernet.h>
72#include <net/if_llc.h>
73
74#include <net80211/ieee80211_var.h>
75
76#include <net/bpf.h>
77
78#ifdef INET
79#include <netinet/in.h>
80#include <netinet/if_ether.h>
81#endif
82
83#define	AR_DEBUG
84#include <dev/ath/if_athvar.h>
85#include <contrib/dev/ath/ah_desc.h>
86#include <contrib/dev/ath/ah_devid.h>		/* XXX for softled */
87
88#ifdef ATH_TX99_DIAG
89#include <dev/ath/ath_tx99/ath_tx99.h>
90#endif
91
92/* unaligned little endian access */
93#define LE_READ_2(p)							\
94	((u_int16_t)							\
95	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
96#define LE_READ_4(p)							\
97	((u_int32_t)							\
98	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) |	\
99	  (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
100
101enum {
102	ATH_LED_TX,
103	ATH_LED_RX,
104	ATH_LED_POLL,
105};
106
107static void	ath_init(void *);
108static void	ath_stop_locked(struct ifnet *);
109static void	ath_stop(struct ifnet *);
110static void	ath_start(struct ifnet *);
111static int	ath_reset(struct ifnet *);
112static int	ath_media_change(struct ifnet *);
113static void	ath_watchdog(struct ifnet *);
114static int	ath_ioctl(struct ifnet *, u_long, caddr_t);
115static void	ath_fatal_proc(void *, int);
116static void	ath_rxorn_proc(void *, int);
117static void	ath_bmiss_proc(void *, int);
118static int	ath_key_alloc(struct ieee80211com *,
119			const struct ieee80211_key *,
120			ieee80211_keyix *, ieee80211_keyix *);
121static int	ath_key_delete(struct ieee80211com *,
122			const struct ieee80211_key *);
123static int	ath_key_set(struct ieee80211com *, const struct ieee80211_key *,
124			const u_int8_t mac[IEEE80211_ADDR_LEN]);
125static void	ath_key_update_begin(struct ieee80211com *);
126static void	ath_key_update_end(struct ieee80211com *);
127static void	ath_mode_init(struct ath_softc *);
128static void	ath_setslottime(struct ath_softc *);
129static void	ath_updateslot(struct ifnet *);
130static int	ath_beaconq_setup(struct ath_hal *);
131static int	ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
132static void	ath_beacon_setup(struct ath_softc *, struct ath_buf *);
133static void	ath_beacon_proc(void *, int);
134static void	ath_bstuck_proc(void *, int);
135static void	ath_beacon_free(struct ath_softc *);
136static void	ath_beacon_config(struct ath_softc *);
137static void	ath_descdma_cleanup(struct ath_softc *sc,
138			struct ath_descdma *, ath_bufhead *);
139static int	ath_desc_alloc(struct ath_softc *);
140static void	ath_desc_free(struct ath_softc *);
141static struct ieee80211_node *ath_node_alloc(struct ieee80211_node_table *);
142static void	ath_node_free(struct ieee80211_node *);
143static u_int8_t	ath_node_getrssi(const struct ieee80211_node *);
144static int	ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
145static void	ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
146			struct ieee80211_node *ni,
147			int subtype, int rssi, u_int32_t rstamp);
148static void	ath_setdefantenna(struct ath_softc *, u_int);
149static void	ath_rx_proc(void *, int);
150static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
151static int	ath_tx_setup(struct ath_softc *, int, int);
152static int	ath_wme_update(struct ieee80211com *);
153static void	ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
154static void	ath_tx_cleanup(struct ath_softc *);
155static int	ath_tx_start(struct ath_softc *, struct ieee80211_node *,
156			     struct ath_buf *, struct mbuf *);
157static void	ath_tx_proc_q0(void *, int);
158static void	ath_tx_proc_q0123(void *, int);
159static void	ath_tx_proc(void *, int);
160static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
161static void	ath_draintxq(struct ath_softc *);
162static void	ath_stoprecv(struct ath_softc *);
163static int	ath_startrecv(struct ath_softc *);
164static void	ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
165static void	ath_next_scan(void *);
166static void	ath_calibrate(void *);
167static int	ath_newstate(struct ieee80211com *, enum ieee80211_state, int);
168static void	ath_setup_stationkey(struct ieee80211_node *);
169static void	ath_newassoc(struct ieee80211_node *, int);
170static int	ath_getchannels(struct ath_softc *, u_int cc,
171			HAL_BOOL outdoor, HAL_BOOL xchanmode);
172static void	ath_led_event(struct ath_softc *, int);
173static void	ath_update_txpow(struct ath_softc *);
174
175static int	ath_rate_setup(struct ath_softc *, u_int mode);
176static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
177
178static void	ath_sysctlattach(struct ath_softc *);
179static void	ath_bpfattach(struct ath_softc *);
180static void	ath_announce(struct ath_softc *);
181
182SYSCTL_DECL(_hw_ath);
183
184/* XXX validate sysctl values */
185static	int ath_dwelltime = 200;		/* 5 channels/second */
186SYSCTL_INT(_hw_ath, OID_AUTO, dwell, CTLFLAG_RW, &ath_dwelltime,
187	    0, "channel dwell time (ms) for AP/station scanning");
188static	int ath_calinterval = 30;		/* calibrate every 30 secs */
189SYSCTL_INT(_hw_ath, OID_AUTO, calibrate, CTLFLAG_RW, &ath_calinterval,
190	    0, "chip calibration interval (secs)");
191static	int ath_outdoor = AH_TRUE;		/* outdoor operation */
192SYSCTL_INT(_hw_ath, OID_AUTO, outdoor, CTLFLAG_RD, &ath_outdoor,
193	    0, "outdoor operation");
194TUNABLE_INT("hw.ath.outdoor", &ath_outdoor);
195static	int ath_xchanmode = AH_TRUE;		/* extended channel use */
196SYSCTL_INT(_hw_ath, OID_AUTO, xchanmode, CTLFLAG_RD, &ath_xchanmode,
197	    0, "extended channel mode");
198TUNABLE_INT("hw.ath.xchanmode", &ath_xchanmode);
199static	int ath_countrycode = CTRY_DEFAULT;	/* country code */
200SYSCTL_INT(_hw_ath, OID_AUTO, countrycode, CTLFLAG_RD, &ath_countrycode,
201	    0, "country code");
202TUNABLE_INT("hw.ath.countrycode", &ath_countrycode);
203static	int ath_regdomain = 0;			/* regulatory domain */
204SYSCTL_INT(_hw_ath, OID_AUTO, regdomain, CTLFLAG_RD, &ath_regdomain,
205	    0, "regulatory domain");
206
207static	int ath_rxbuf = ATH_RXBUF;		/* # rx buffers to allocate */
208SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RD, &ath_rxbuf,
209	    0, "rx buffers allocated");
210TUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
211static	int ath_txbuf = ATH_TXBUF;		/* # tx buffers to allocate */
212SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RD, &ath_txbuf,
213	    0, "tx buffers allocated");
214TUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
215
216#ifdef AR_DEBUG
217static	int ath_debug = 0;
218SYSCTL_INT(_hw_ath, OID_AUTO, debug, CTLFLAG_RW, &ath_debug,
219	    0, "control debugging printfs");
220TUNABLE_INT("hw.ath.debug", &ath_debug);
221enum {
222	ATH_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
223	ATH_DEBUG_XMIT_DESC	= 0x00000002,	/* xmit descriptors */
224	ATH_DEBUG_RECV		= 0x00000004,	/* basic recv operation */
225	ATH_DEBUG_RECV_DESC	= 0x00000008,	/* recv descriptors */
226	ATH_DEBUG_RATE		= 0x00000010,	/* rate control */
227	ATH_DEBUG_RESET		= 0x00000020,	/* reset processing */
228	ATH_DEBUG_MODE		= 0x00000040,	/* mode init/setup */
229	ATH_DEBUG_BEACON 	= 0x00000080,	/* beacon handling */
230	ATH_DEBUG_WATCHDOG 	= 0x00000100,	/* watchdog timeout */
231	ATH_DEBUG_INTR		= 0x00001000,	/* ISR */
232	ATH_DEBUG_TX_PROC	= 0x00002000,	/* tx ISR proc */
233	ATH_DEBUG_RX_PROC	= 0x00004000,	/* rx ISR proc */
234	ATH_DEBUG_BEACON_PROC	= 0x00008000,	/* beacon ISR proc */
235	ATH_DEBUG_CALIBRATE	= 0x00010000,	/* periodic calibration */
236	ATH_DEBUG_KEYCACHE	= 0x00020000,	/* key cache management */
237	ATH_DEBUG_STATE		= 0x00040000,	/* 802.11 state transitions */
238	ATH_DEBUG_NODE		= 0x00080000,	/* node management */
239	ATH_DEBUG_LED		= 0x00100000,	/* led management */
240	ATH_DEBUG_FATAL		= 0x80000000,	/* fatal errors */
241	ATH_DEBUG_ANY		= 0xffffffff
242};
243#define	IFF_DUMPPKTS(sc, m) \
244	((sc->sc_debug & (m)) || \
245	    (sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
246#define	DPRINTF(sc, m, fmt, ...) do {				\
247	if (sc->sc_debug & (m))					\
248		printf(fmt, __VA_ARGS__);			\
249} while (0)
250#define	KEYPRINTF(sc, ix, hk, mac) do {				\
251	if (sc->sc_debug & ATH_DEBUG_KEYCACHE)			\
252		ath_keyprint(__func__, ix, hk, mac);		\
253} while (0)
254static	void ath_printrxbuf(struct ath_buf *bf, int);
255static	void ath_printtxbuf(struct ath_buf *bf, int);
256#else
257#define	IFF_DUMPPKTS(sc, m) \
258	((sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
259#define	DPRINTF(m, fmt, ...)
260#define	KEYPRINTF(sc, k, ix, mac)
261#endif
262
263MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
264
265int
266ath_attach(u_int16_t devid, struct ath_softc *sc)
267{
268	struct ifnet *ifp;
269	struct ieee80211com *ic = &sc->sc_ic;
270	struct ath_hal *ah = NULL;
271	HAL_STATUS status;
272	int error = 0, i;
273
274	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
275
276	ifp = sc->sc_ifp = if_alloc(IFT_ETHER);
277	if (ifp == NULL) {
278		device_printf(sc->sc_dev, "can not if_alloc()\n");
279		error = ENOSPC;
280		goto bad;
281	}
282
283	/* set these up early for if_printf use */
284	if_initname(ifp, device_get_name(sc->sc_dev),
285		device_get_unit(sc->sc_dev));
286
287	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
288	if (ah == NULL) {
289		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
290			status);
291		error = ENXIO;
292		goto bad;
293	}
294	if (ah->ah_abi != HAL_ABI_VERSION) {
295		if_printf(ifp, "HAL ABI mismatch detected "
296			"(HAL:0x%x != driver:0x%x)\n",
297			ah->ah_abi, HAL_ABI_VERSION);
298		error = ENXIO;
299		goto bad;
300	}
301	sc->sc_ah = ah;
302	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
303
304	/*
305	 * Check if the MAC has multi-rate retry support.
306	 * We do this by trying to setup a fake extended
307	 * descriptor.  MAC's that don't have support will
308	 * return false w/o doing anything.  MAC's that do
309	 * support it will return true w/o doing anything.
310	 */
311	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
312
313	/*
314	 * Check if the device has hardware counters for PHY
315	 * errors.  If so we need to enable the MIB interrupt
316	 * so we can act on stat triggers.
317	 */
318	if (ath_hal_hwphycounters(ah))
319		sc->sc_needmib = 1;
320
321	/*
322	 * Get the hardware key cache size.
323	 */
324	sc->sc_keymax = ath_hal_keycachesize(ah);
325	if (sc->sc_keymax > ATH_KEYMAX) {
326		if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
327			ATH_KEYMAX, sc->sc_keymax);
328		sc->sc_keymax = ATH_KEYMAX;
329	}
330	/*
331	 * Reset the key cache since some parts do not
332	 * reset the contents on initial power up.
333	 */
334	for (i = 0; i < sc->sc_keymax; i++)
335		ath_hal_keyreset(ah, i);
336	/*
337	 * Mark key cache slots associated with global keys
338	 * as in use.  If we knew TKIP was not to be used we
339	 * could leave the +32, +64, and +32+64 slots free.
340	 * XXX only for splitmic.
341	 */
342	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
343		setbit(sc->sc_keymap, i);
344		setbit(sc->sc_keymap, i+32);
345		setbit(sc->sc_keymap, i+64);
346		setbit(sc->sc_keymap, i+32+64);
347	}
348
349	/*
350	 * Collect the channel list using the default country
351	 * code and including outdoor channels.  The 802.11 layer
352	 * is resposible for filtering this list based on settings
353	 * like the phy mode.
354	 */
355	error = ath_getchannels(sc, ath_countrycode,
356			ath_outdoor, ath_xchanmode);
357	if (error != 0)
358		goto bad;
359
360	/*
361	 * Setup rate tables for all potential media types.
362	 */
363	ath_rate_setup(sc, IEEE80211_MODE_11A);
364	ath_rate_setup(sc, IEEE80211_MODE_11B);
365	ath_rate_setup(sc, IEEE80211_MODE_11G);
366	ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
367	ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
368	/* NB: setup here so ath_rate_update is happy */
369	ath_setcurmode(sc, IEEE80211_MODE_11A);
370
371	/*
372	 * Allocate tx+rx descriptors and populate the lists.
373	 */
374	error = ath_desc_alloc(sc);
375	if (error != 0) {
376		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
377		goto bad;
378	}
379	callout_init(&sc->sc_scan_ch, debug_mpsafenet ? CALLOUT_MPSAFE : 0);
380	callout_init(&sc->sc_cal_ch, CALLOUT_MPSAFE);
381
382	ATH_TXBUF_LOCK_INIT(sc);
383
384	TASK_INIT(&sc->sc_rxtask, 0, ath_rx_proc, sc);
385	TASK_INIT(&sc->sc_rxorntask, 0, ath_rxorn_proc, sc);
386	TASK_INIT(&sc->sc_fataltask, 0, ath_fatal_proc, sc);
387	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
388	TASK_INIT(&sc->sc_bstucktask, 0, ath_bstuck_proc, sc);
389
390	/*
391	 * Allocate hardware transmit queues: one queue for
392	 * beacon frames and one data queue for each QoS
393	 * priority.  Note that the hal handles reseting
394	 * these queues at the needed time.
395	 *
396	 * XXX PS-Poll
397	 */
398	sc->sc_bhalq = ath_beaconq_setup(ah);
399	if (sc->sc_bhalq == (u_int) -1) {
400		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
401		error = EIO;
402		goto bad2;
403	}
404	sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
405	if (sc->sc_cabq == NULL) {
406		if_printf(ifp, "unable to setup CAB xmit queue!\n");
407		error = EIO;
408		goto bad2;
409	}
410	/* NB: insure BK queue is the lowest priority h/w queue */
411	if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
412		if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
413			ieee80211_wme_acnames[WME_AC_BK]);
414		error = EIO;
415		goto bad2;
416	}
417	if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
418	    !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
419	    !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
420		/*
421		 * Not enough hardware tx queues to properly do WME;
422		 * just punt and assign them all to the same h/w queue.
423		 * We could do a better job of this if, for example,
424		 * we allocate queues when we switch from station to
425		 * AP mode.
426		 */
427		if (sc->sc_ac2q[WME_AC_VI] != NULL)
428			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
429		if (sc->sc_ac2q[WME_AC_BE] != NULL)
430			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
431		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
432		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
433		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
434	}
435
436	/*
437	 * Special case certain configurations.  Note the
438	 * CAB queue is handled by these specially so don't
439	 * include them when checking the txq setup mask.
440	 */
441	switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
442	case 0x01:
443		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
444		break;
445	case 0x0f:
446		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
447		break;
448	default:
449		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
450		break;
451	}
452
453	/*
454	 * Setup rate control.  Some rate control modules
455	 * call back to change the anntena state so expose
456	 * the necessary entry points.
457	 * XXX maybe belongs in struct ath_ratectrl?
458	 */
459	sc->sc_setdefantenna = ath_setdefantenna;
460	sc->sc_rc = ath_rate_attach(sc);
461	if (sc->sc_rc == NULL) {
462		error = EIO;
463		goto bad2;
464	}
465
466	sc->sc_blinking = 0;
467	sc->sc_ledstate = 1;
468	sc->sc_ledon = 0;			/* low true */
469	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
470	callout_init(&sc->sc_ledtimer, CALLOUT_MPSAFE);
471	/*
472	 * Auto-enable soft led processing for IBM cards and for
473	 * 5211 minipci cards.  Users can also manually enable/disable
474	 * support with a sysctl.
475	 */
476	sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
477	if (sc->sc_softled) {
478		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin);
479		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
480	}
481
482	ifp->if_softc = sc;
483	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
484	ifp->if_start = ath_start;
485	ifp->if_watchdog = ath_watchdog;
486	ifp->if_ioctl = ath_ioctl;
487	ifp->if_init = ath_init;
488	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
489	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
490	IFQ_SET_READY(&ifp->if_snd);
491
492	ic->ic_ifp = ifp;
493	ic->ic_reset = ath_reset;
494	ic->ic_newassoc = ath_newassoc;
495	ic->ic_updateslot = ath_updateslot;
496	ic->ic_wme.wme_update = ath_wme_update;
497	/* XXX not right but it's not used anywhere important */
498	ic->ic_phytype = IEEE80211_T_OFDM;
499	ic->ic_opmode = IEEE80211_M_STA;
500	ic->ic_caps =
501		  IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
502		| IEEE80211_C_HOSTAP		/* hostap mode */
503		| IEEE80211_C_MONITOR		/* monitor mode */
504		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
505		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
506		| IEEE80211_C_SHSLOT		/* short slot time supported */
507		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
508		;
509	/*
510	 * Query the hal to figure out h/w crypto support.
511	 */
512	if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
513		ic->ic_caps |= IEEE80211_C_WEP;
514	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
515		ic->ic_caps |= IEEE80211_C_AES;
516	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
517		ic->ic_caps |= IEEE80211_C_AES_CCM;
518	if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
519		ic->ic_caps |= IEEE80211_C_CKIP;
520	if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
521		ic->ic_caps |= IEEE80211_C_TKIP;
522		/*
523		 * Check if h/w does the MIC and/or whether the
524		 * separate key cache entries are required to
525		 * handle both tx+rx MIC keys.
526		 */
527		if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
528			ic->ic_caps |= IEEE80211_C_TKIPMIC;
529		if (ath_hal_tkipsplit(ah))
530			sc->sc_splitmic = 1;
531	}
532	sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
533	sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
534	/*
535	 * TPC support can be done either with a global cap or
536	 * per-packet support.  The latter is not available on
537	 * all parts.  We're a bit pedantic here as all parts
538	 * support a global cap.
539	 */
540	if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
541		ic->ic_caps |= IEEE80211_C_TXPMGT;
542
543	/*
544	 * Mark WME capability only if we have sufficient
545	 * hardware queues to do proper priority scheduling.
546	 */
547	if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
548		ic->ic_caps |= IEEE80211_C_WME;
549	/*
550	 * Check for misc other capabilities.
551	 */
552	if (ath_hal_hasbursting(ah))
553		ic->ic_caps |= IEEE80211_C_BURST;
554
555	/*
556	 * Indicate we need the 802.11 header padded to a
557	 * 32-bit boundary for 4-address and QoS frames.
558	 */
559	ic->ic_flags |= IEEE80211_F_DATAPAD;
560
561	/*
562	 * Query the hal about antenna support.
563	 */
564	sc->sc_defant = ath_hal_getdefantenna(ah);
565
566	/*
567	 * Not all chips have the VEOL support we want to
568	 * use with IBSS beacons; check here for it.
569	 */
570	sc->sc_hasveol = ath_hal_hasveol(ah);
571
572	/* get mac address from hardware */
573	ath_hal_getmac(ah, ic->ic_myaddr);
574
575	/* call MI attach routine. */
576	ieee80211_ifattach(ic);
577	sc->sc_opmode = ic->ic_opmode;
578	/* override default methods */
579	ic->ic_node_alloc = ath_node_alloc;
580	sc->sc_node_free = ic->ic_node_free;
581	ic->ic_node_free = ath_node_free;
582	ic->ic_node_getrssi = ath_node_getrssi;
583	sc->sc_recv_mgmt = ic->ic_recv_mgmt;
584	ic->ic_recv_mgmt = ath_recv_mgmt;
585	sc->sc_newstate = ic->ic_newstate;
586	ic->ic_newstate = ath_newstate;
587	ic->ic_crypto.cs_max_keyix = sc->sc_keymax;
588	ic->ic_crypto.cs_key_alloc = ath_key_alloc;
589	ic->ic_crypto.cs_key_delete = ath_key_delete;
590	ic->ic_crypto.cs_key_set = ath_key_set;
591	ic->ic_crypto.cs_key_update_begin = ath_key_update_begin;
592	ic->ic_crypto.cs_key_update_end = ath_key_update_end;
593	/* complete initialization */
594	ieee80211_media_init(ic, ath_media_change, ieee80211_media_status);
595
596	ath_bpfattach(sc);
597	/*
598	 * Setup dynamic sysctl's now that country code and
599	 * regdomain are available from the hal.
600	 */
601	ath_sysctlattach(sc);
602
603	if (bootverbose)
604		ieee80211_announce(ic);
605	ath_announce(sc);
606	return 0;
607bad2:
608	ath_tx_cleanup(sc);
609	ath_desc_free(sc);
610bad:
611	if (ah)
612		ath_hal_detach(ah);
613	if (ifp != NULL)
614		if_free(ifp);
615	sc->sc_invalid = 1;
616	return error;
617}
618
619int
620ath_detach(struct ath_softc *sc)
621{
622	struct ifnet *ifp = sc->sc_ifp;
623
624	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
625		__func__, ifp->if_flags);
626
627	ath_stop(ifp);
628	bpfdetach(ifp);
629	/*
630	 * NB: the order of these is important:
631	 * o call the 802.11 layer before detaching the hal to
632	 *   insure callbacks into the driver to delete global
633	 *   key cache entries can be handled
634	 * o reclaim the tx queue data structures after calling
635	 *   the 802.11 layer as we'll get called back to reclaim
636	 *   node state and potentially want to use them
637	 * o to cleanup the tx queues the hal is called, so detach
638	 *   it last
639	 * Other than that, it's straightforward...
640	 */
641	ieee80211_ifdetach(&sc->sc_ic);
642#ifdef ATH_TX99_DIAG
643	if (sc->sc_tx99 != NULL)
644		sc->sc_tx99->detach(sc->sc_tx99);
645#endif
646	ath_rate_detach(sc->sc_rc);
647	ath_desc_free(sc);
648	ath_tx_cleanup(sc);
649	ath_hal_detach(sc->sc_ah);
650	if_free(ifp);
651
652	return 0;
653}
654
655void
656ath_suspend(struct ath_softc *sc)
657{
658	struct ifnet *ifp = sc->sc_ifp;
659
660	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
661		__func__, ifp->if_flags);
662
663	ath_stop(ifp);
664}
665
666void
667ath_resume(struct ath_softc *sc)
668{
669	struct ifnet *ifp = sc->sc_ifp;
670
671	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
672		__func__, ifp->if_flags);
673
674	if (ifp->if_flags & IFF_UP) {
675		ath_init(sc);
676		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
677			ath_start(ifp);
678	}
679	if (sc->sc_softled) {
680		ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
681		ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
682	}
683}
684
685void
686ath_shutdown(struct ath_softc *sc)
687{
688	struct ifnet *ifp = sc->sc_ifp;
689
690	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
691		__func__, ifp->if_flags);
692
693	ath_stop(ifp);
694}
695
696/*
697 * Interrupt handler.  Most of the actual processing is deferred.
698 */
699void
700ath_intr(void *arg)
701{
702	struct ath_softc *sc = arg;
703	struct ifnet *ifp = sc->sc_ifp;
704	struct ath_hal *ah = sc->sc_ah;
705	HAL_INT status;
706
707	if (sc->sc_invalid) {
708		/*
709		 * The hardware is not ready/present, don't touch anything.
710		 * Note this can happen early on if the IRQ is shared.
711		 */
712		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
713		return;
714	}
715	if (!ath_hal_intrpend(ah))		/* shared irq, not for us */
716		return;
717	if (!((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags &
718	    IFF_DRV_RUNNING))) {
719		DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
720			__func__, ifp->if_flags);
721		ath_hal_getisr(ah, &status);	/* clear ISR */
722		ath_hal_intrset(ah, 0);		/* disable further intr's */
723		return;
724	}
725	/*
726	 * Figure out the reason(s) for the interrupt.  Note
727	 * that the hal returns a pseudo-ISR that may include
728	 * bits we haven't explicitly enabled so we mask the
729	 * value to insure we only process bits we requested.
730	 */
731	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
732	DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
733	status &= sc->sc_imask;			/* discard unasked for bits */
734	if (status & HAL_INT_FATAL) {
735		/*
736		 * Fatal errors are unrecoverable.  Typically
737		 * these are caused by DMA errors.  Unfortunately
738		 * the exact reason is not (presently) returned
739		 * by the hal.
740		 */
741		sc->sc_stats.ast_hardware++;
742		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
743		taskqueue_enqueue(taskqueue_swi, &sc->sc_fataltask);
744	} else if (status & HAL_INT_RXORN) {
745		sc->sc_stats.ast_rxorn++;
746		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
747		taskqueue_enqueue(taskqueue_swi, &sc->sc_rxorntask);
748	} else {
749		if (status & HAL_INT_SWBA) {
750			/*
751			 * Software beacon alert--time to send a beacon.
752			 * Handle beacon transmission directly; deferring
753			 * this is too slow to meet timing constraints
754			 * under load.
755			 */
756			ath_beacon_proc(sc, 0);
757		}
758		if (status & HAL_INT_RXEOL) {
759			/*
760			 * NB: the hardware should re-read the link when
761			 *     RXE bit is written, but it doesn't work at
762			 *     least on older hardware revs.
763			 */
764			sc->sc_stats.ast_rxeol++;
765			sc->sc_rxlink = NULL;
766		}
767		if (status & HAL_INT_TXURN) {
768			sc->sc_stats.ast_txurn++;
769			/* bump tx trigger level */
770			ath_hal_updatetxtriglevel(ah, AH_TRUE);
771		}
772		if (status & HAL_INT_RX)
773			taskqueue_enqueue(taskqueue_swi, &sc->sc_rxtask);
774		if (status & HAL_INT_TX)
775			taskqueue_enqueue(taskqueue_swi, &sc->sc_txtask);
776		if (status & HAL_INT_BMISS) {
777			sc->sc_stats.ast_bmiss++;
778			taskqueue_enqueue(taskqueue_swi, &sc->sc_bmisstask);
779		}
780		if (status & HAL_INT_MIB) {
781			sc->sc_stats.ast_mib++;
782			/*
783			 * Disable interrupts until we service the MIB
784			 * interrupt; otherwise it will continue to fire.
785			 */
786			ath_hal_intrset(ah, 0);
787			/*
788			 * Let the hal handle the event.  We assume it will
789			 * clear whatever condition caused the interrupt.
790			 */
791			ath_hal_mibevent(ah, &sc->sc_halstats);
792			ath_hal_intrset(ah, sc->sc_imask);
793		}
794	}
795}
796
797static void
798ath_fatal_proc(void *arg, int pending)
799{
800	struct ath_softc *sc = arg;
801	struct ifnet *ifp = sc->sc_ifp;
802
803	if_printf(ifp, "hardware error; resetting\n");
804	ath_reset(ifp);
805}
806
807static void
808ath_rxorn_proc(void *arg, int pending)
809{
810	struct ath_softc *sc = arg;
811	struct ifnet *ifp = sc->sc_ifp;
812
813	if_printf(ifp, "rx FIFO overrun; resetting\n");
814	ath_reset(ifp);
815}
816
817static void
818ath_bmiss_proc(void *arg, int pending)
819{
820	struct ath_softc *sc = arg;
821	struct ieee80211com *ic = &sc->sc_ic;
822
823	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
824	KASSERT(ic->ic_opmode == IEEE80211_M_STA,
825		("unexpect operating mode %u", ic->ic_opmode));
826	if (ic->ic_state == IEEE80211_S_RUN) {
827		/*
828		 * Rather than go directly to scan state, try to
829		 * reassociate first.  If that fails then the state
830		 * machine will drop us into scanning after timing
831		 * out waiting for a probe response.
832		 */
833		NET_LOCK_GIANT();
834		ieee80211_new_state(ic, IEEE80211_S_ASSOC, -1);
835		NET_UNLOCK_GIANT();
836	}
837}
838
839static u_int
840ath_chan2flags(struct ieee80211com *ic, struct ieee80211_channel *chan)
841{
842#define	N(a)	(sizeof(a) / sizeof(a[0]))
843	static const u_int modeflags[] = {
844		0,			/* IEEE80211_MODE_AUTO */
845		CHANNEL_A,		/* IEEE80211_MODE_11A */
846		CHANNEL_B,		/* IEEE80211_MODE_11B */
847		CHANNEL_PUREG,		/* IEEE80211_MODE_11G */
848		0,			/* IEEE80211_MODE_FH */
849		CHANNEL_T,		/* IEEE80211_MODE_TURBO_A */
850		CHANNEL_108G		/* IEEE80211_MODE_TURBO_G */
851	};
852	enum ieee80211_phymode mode = ieee80211_chan2mode(ic, chan);
853
854	KASSERT(mode < N(modeflags), ("unexpected phy mode %u", mode));
855	KASSERT(modeflags[mode] != 0, ("mode %u undefined", mode));
856	return modeflags[mode];
857#undef N
858}
859
860static void
861ath_init(void *arg)
862{
863	struct ath_softc *sc = (struct ath_softc *) arg;
864	struct ieee80211com *ic = &sc->sc_ic;
865	struct ifnet *ifp = sc->sc_ifp;
866	struct ath_hal *ah = sc->sc_ah;
867	HAL_STATUS status;
868
869	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
870		__func__, ifp->if_flags);
871
872	ATH_LOCK(sc);
873	/*
874	 * Stop anything previously setup.  This is safe
875	 * whether this is the first time through or not.
876	 */
877	ath_stop_locked(ifp);
878
879	/*
880	 * The basic interface to setting the hardware in a good
881	 * state is ``reset''.  On return the hardware is known to
882	 * be powered up and with interrupts disabled.  This must
883	 * be followed by initialization of the appropriate bits
884	 * and then setup of the interrupt mask.
885	 */
886	sc->sc_curchan.channel = ic->ic_curchan->ic_freq;
887	sc->sc_curchan.channelFlags = ath_chan2flags(ic, ic->ic_curchan);
888	if (!ath_hal_reset(ah, sc->sc_opmode, &sc->sc_curchan, AH_FALSE, &status)) {
889		if_printf(ifp, "unable to reset hardware; hal status %u\n",
890			status);
891		goto done;
892	}
893
894	/*
895	 * This is needed only to setup initial state
896	 * but it's best done after a reset.
897	 */
898	ath_update_txpow(sc);
899	/*
900	 * Likewise this is set during reset so update
901	 * state cached in the driver.
902	 */
903	sc->sc_diversity = ath_hal_getdiversity(ah);
904
905	/*
906	 * Setup the hardware after reset: the key cache
907	 * is filled as needed and the receive engine is
908	 * set going.  Frame transmit is handled entirely
909	 * in the frame output path; there's nothing to do
910	 * here except setup the interrupt mask.
911	 */
912	if (ath_startrecv(sc) != 0) {
913		if_printf(ifp, "unable to start recv logic\n");
914		goto done;
915	}
916
917	/*
918	 * Enable interrupts.
919	 */
920	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
921		  | HAL_INT_RXEOL | HAL_INT_RXORN
922		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
923	/*
924	 * Enable MIB interrupts when there are hardware phy counters.
925	 * Note we only do this (at the moment) for station mode.
926	 */
927	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
928		sc->sc_imask |= HAL_INT_MIB;
929	ath_hal_intrset(ah, sc->sc_imask);
930
931	ifp->if_drv_flags |= IFF_DRV_RUNNING;
932	ic->ic_state = IEEE80211_S_INIT;
933
934	/*
935	 * The hardware should be ready to go now so it's safe
936	 * to kick the 802.11 state machine as it's likely to
937	 * immediately call back to us to send mgmt frames.
938	 */
939	ath_chan_change(sc, ic->ic_curchan);
940#ifdef ATH_TX99_DIAG
941	if (sc->sc_tx99 != NULL)
942		sc->sc_tx99->start(sc->sc_tx99);
943	else
944#endif
945	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
946		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
947			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
948	} else
949		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
950done:
951	ATH_UNLOCK(sc);
952}
953
954static void
955ath_stop_locked(struct ifnet *ifp)
956{
957	struct ath_softc *sc = ifp->if_softc;
958	struct ieee80211com *ic = &sc->sc_ic;
959	struct ath_hal *ah = sc->sc_ah;
960
961	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
962		__func__, sc->sc_invalid, ifp->if_flags);
963
964	ATH_LOCK_ASSERT(sc);
965	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
966		/*
967		 * Shutdown the hardware and driver:
968		 *    reset 802.11 state machine
969		 *    turn off timers
970		 *    disable interrupts
971		 *    turn off the radio
972		 *    clear transmit machinery
973		 *    clear receive machinery
974		 *    drain and release tx queues
975		 *    reclaim beacon resources
976		 *    power down hardware
977		 *
978		 * Note that some of this work is not possible if the
979		 * hardware is gone (invalid).
980		 */
981#ifdef ATH_TX99_DIAG
982		if (sc->sc_tx99 != NULL)
983			sc->sc_tx99->stop(sc->sc_tx99);
984#endif
985		ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
986		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
987		ifp->if_timer = 0;
988		if (!sc->sc_invalid) {
989			if (sc->sc_softled) {
990				callout_stop(&sc->sc_ledtimer);
991				ath_hal_gpioset(ah, sc->sc_ledpin,
992					!sc->sc_ledon);
993				sc->sc_blinking = 0;
994			}
995			ath_hal_intrset(ah, 0);
996		}
997		ath_draintxq(sc);
998		if (!sc->sc_invalid) {
999			ath_stoprecv(sc);
1000			ath_hal_phydisable(ah);
1001		} else
1002			sc->sc_rxlink = NULL;
1003		IFQ_DRV_PURGE(&ifp->if_snd);
1004		ath_beacon_free(sc);
1005	}
1006}
1007
1008static void
1009ath_stop(struct ifnet *ifp)
1010{
1011	struct ath_softc *sc = ifp->if_softc;
1012
1013	ATH_LOCK(sc);
1014	ath_stop_locked(ifp);
1015	if (!sc->sc_invalid) {
1016		/*
1017		 * Set the chip in full sleep mode.  Note that we are
1018		 * careful to do this only when bringing the interface
1019		 * completely to a stop.  When the chip is in this state
1020		 * it must be carefully woken up or references to
1021		 * registers in the PCI clock domain may freeze the bus
1022		 * (and system).  This varies by chip and is mostly an
1023		 * issue with newer parts that go to sleep more quickly.
1024		 */
1025		ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP, 0);
1026	}
1027	ATH_UNLOCK(sc);
1028}
1029
1030/*
1031 * Reset the hardware w/o losing operational state.  This is
1032 * basically a more efficient way of doing ath_stop, ath_init,
1033 * followed by state transitions to the current 802.11
1034 * operational state.  Used to recover from various errors and
1035 * to reset or reload hardware state.
1036 */
1037static int
1038ath_reset(struct ifnet *ifp)
1039{
1040	struct ath_softc *sc = ifp->if_softc;
1041	struct ieee80211com *ic = &sc->sc_ic;
1042	struct ath_hal *ah = sc->sc_ah;
1043	struct ieee80211_channel *c;
1044	HAL_STATUS status;
1045
1046	/*
1047	 * Convert to a HAL channel description with the flags
1048	 * constrained to reflect the current operating mode.
1049	 */
1050	c = ic->ic_curchan;
1051	sc->sc_curchan.channel = c->ic_freq;
1052	sc->sc_curchan.channelFlags = ath_chan2flags(ic, c);
1053
1054	ath_hal_intrset(ah, 0);		/* disable interrupts */
1055	ath_draintxq(sc);		/* stop xmit side */
1056	ath_stoprecv(sc);		/* stop recv side */
1057	/* NB: indicate channel change so we do a full reset */
1058	if (!ath_hal_reset(ah, sc->sc_opmode, &sc->sc_curchan, AH_TRUE, &status))
1059		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
1060			__func__, status);
1061	ath_update_txpow(sc);		/* update tx power state */
1062	sc->sc_diversity = ath_hal_getdiversity(ah);
1063	if (ath_startrecv(sc) != 0)	/* restart recv */
1064		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
1065	/*
1066	 * We may be doing a reset in response to an ioctl
1067	 * that changes the channel so update any state that
1068	 * might change as a result.
1069	 */
1070	ath_chan_change(sc, c);
1071	if (ic->ic_state == IEEE80211_S_RUN)
1072		ath_beacon_config(sc);	/* restart beacons */
1073	ath_hal_intrset(ah, sc->sc_imask);
1074
1075	ath_start(ifp);			/* restart xmit */
1076	return 0;
1077}
1078
1079static void
1080ath_start(struct ifnet *ifp)
1081{
1082	struct ath_softc *sc = ifp->if_softc;
1083	struct ath_hal *ah = sc->sc_ah;
1084	struct ieee80211com *ic = &sc->sc_ic;
1085	struct ieee80211_node *ni;
1086	struct ath_buf *bf;
1087	struct mbuf *m;
1088	struct ieee80211_frame *wh;
1089	struct ether_header *eh;
1090
1091	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
1092		return;
1093	for (;;) {
1094		/*
1095		 * Grab a TX buffer and associated resources.
1096		 */
1097		ATH_TXBUF_LOCK(sc);
1098		bf = STAILQ_FIRST(&sc->sc_txbuf);
1099		if (bf != NULL)
1100			STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
1101		ATH_TXBUF_UNLOCK(sc);
1102		if (bf == NULL) {
1103			DPRINTF(sc, ATH_DEBUG_ANY, "%s: out of xmit buffers\n",
1104				__func__);
1105			sc->sc_stats.ast_tx_qstop++;
1106			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1107			break;
1108		}
1109		/*
1110		 * Poll the management queue for frames; they
1111		 * have priority over normal data frames.
1112		 */
1113		IF_DEQUEUE(&ic->ic_mgtq, m);
1114		if (m == NULL) {
1115			/*
1116			 * No data frames go out unless we're associated.
1117			 */
1118			if (ic->ic_state != IEEE80211_S_RUN) {
1119				DPRINTF(sc, ATH_DEBUG_ANY,
1120					"%s: ignore data packet, state %u\n",
1121					__func__, ic->ic_state);
1122				sc->sc_stats.ast_tx_discard++;
1123				ATH_TXBUF_LOCK(sc);
1124				STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1125				ATH_TXBUF_UNLOCK(sc);
1126				break;
1127			}
1128			IFQ_DRV_DEQUEUE(&ifp->if_snd, m);	/* XXX: LOCK */
1129			if (m == NULL) {
1130				ATH_TXBUF_LOCK(sc);
1131				STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1132				ATH_TXBUF_UNLOCK(sc);
1133				break;
1134			}
1135			/*
1136			 * Find the node for the destination so we can do
1137			 * things like power save and fast frames aggregation.
1138			 */
1139			if (m->m_len < sizeof(struct ether_header) &&
1140			   (m = m_pullup(m, sizeof(struct ether_header))) == NULL) {
1141				ic->ic_stats.is_tx_nobuf++;	/* XXX */
1142				ni = NULL;
1143				goto bad;
1144			}
1145			eh = mtod(m, struct ether_header *);
1146			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1147			if (ni == NULL) {
1148				/* NB: ieee80211_find_txnode does stat+msg */
1149				m_freem(m);
1150				goto bad;
1151			}
1152			if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
1153			    (m->m_flags & M_PWR_SAV) == 0) {
1154				/*
1155				 * Station in power save mode; pass the frame
1156				 * to the 802.11 layer and continue.  We'll get
1157				 * the frame back when the time is right.
1158				 */
1159				ieee80211_pwrsave(ic, ni, m);
1160				goto reclaim;
1161			}
1162			/* calculate priority so we can find the tx queue */
1163			if (ieee80211_classify(ic, m, ni)) {
1164				DPRINTF(sc, ATH_DEBUG_XMIT,
1165					"%s: discard, classification failure\n",
1166					__func__);
1167				m_freem(m);
1168				goto bad;
1169			}
1170			ifp->if_opackets++;
1171			BPF_MTAP(ifp, m);
1172			/*
1173			 * Encapsulate the packet in prep for transmission.
1174			 */
1175			m = ieee80211_encap(ic, m, ni);
1176			if (m == NULL) {
1177				DPRINTF(sc, ATH_DEBUG_ANY,
1178					"%s: encapsulation failure\n",
1179					__func__);
1180				sc->sc_stats.ast_tx_encap++;
1181				goto bad;
1182			}
1183		} else {
1184			/*
1185			 * Hack!  The referenced node pointer is in the
1186			 * rcvif field of the packet header.  This is
1187			 * placed there by ieee80211_mgmt_output because
1188			 * we need to hold the reference with the frame
1189			 * and there's no other way (other than packet
1190			 * tags which we consider too expensive to use)
1191			 * to pass it along.
1192			 */
1193			ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1194			m->m_pkthdr.rcvif = NULL;
1195
1196			wh = mtod(m, struct ieee80211_frame *);
1197			if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1198			    IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
1199				/* fill time stamp */
1200				u_int64_t tsf;
1201				u_int32_t *tstamp;
1202
1203				tsf = ath_hal_gettsf64(ah);
1204				/* XXX: adjust 100us delay to xmit */
1205				tsf += 100;
1206				tstamp = (u_int32_t *)&wh[1];
1207				tstamp[0] = htole32(tsf & 0xffffffff);
1208				tstamp[1] = htole32(tsf >> 32);
1209			}
1210			sc->sc_stats.ast_tx_mgmt++;
1211		}
1212
1213		if (ath_tx_start(sc, ni, bf, m)) {
1214	bad:
1215			ifp->if_oerrors++;
1216	reclaim:
1217			ATH_TXBUF_LOCK(sc);
1218			STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1219			ATH_TXBUF_UNLOCK(sc);
1220			if (ni != NULL)
1221				ieee80211_free_node(ni);
1222			continue;
1223		}
1224
1225		sc->sc_tx_timer = 5;
1226		ifp->if_timer = 1;
1227	}
1228}
1229
1230static int
1231ath_media_change(struct ifnet *ifp)
1232{
1233#define	IS_UP(ifp) \
1234	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
1235	int error;
1236
1237	error = ieee80211_media_change(ifp);
1238	if (error == ENETRESET) {
1239		struct ath_softc *sc = ifp->if_softc;
1240		struct ieee80211com *ic = &sc->sc_ic;
1241
1242		if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
1243			/*
1244			 * Adhoc demo mode is just ibss mode w/o beacons
1245			 * (mostly).  The hal knows nothing about it;
1246			 * tell it we're operating in ibss mode.
1247			 */
1248			sc->sc_opmode = HAL_M_IBSS;
1249		} else
1250			sc->sc_opmode = ic->ic_opmode;
1251		if (IS_UP(ifp))
1252			ath_init(ifp->if_softc);	/* XXX lose error */
1253		error = 0;
1254	}
1255	return error;
1256#undef IS_UP
1257}
1258
1259#ifdef AR_DEBUG
1260static void
1261ath_keyprint(const char *tag, u_int ix,
1262	const HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1263{
1264	static const char *ciphers[] = {
1265		"WEP",
1266		"AES-OCB",
1267		"AES-CCM",
1268		"CKIP",
1269		"TKIP",
1270		"CLR",
1271	};
1272	int i, n;
1273
1274	printf("%s: [%02u] %-7s ", tag, ix, ciphers[hk->kv_type]);
1275	for (i = 0, n = hk->kv_len; i < n; i++)
1276		printf("%02x", hk->kv_val[i]);
1277	printf(" mac %s", ether_sprintf(mac));
1278	if (hk->kv_type == HAL_CIPHER_TKIP) {
1279		printf(" mic ");
1280		for (i = 0; i < sizeof(hk->kv_mic); i++)
1281			printf("%02x", hk->kv_mic[i]);
1282	}
1283	printf("\n");
1284}
1285#endif
1286
1287/*
1288 * Set a TKIP key into the hardware.  This handles the
1289 * potential distribution of key state to multiple key
1290 * cache slots for TKIP.
1291 */
1292static int
1293ath_keyset_tkip(struct ath_softc *sc, const struct ieee80211_key *k,
1294	HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1295{
1296#define	IEEE80211_KEY_XR	(IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV)
1297	static const u_int8_t zerobssid[IEEE80211_ADDR_LEN];
1298	struct ath_hal *ah = sc->sc_ah;
1299
1300	KASSERT(k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP,
1301		("got a non-TKIP key, cipher %u", k->wk_cipher->ic_cipher));
1302	KASSERT(sc->sc_splitmic, ("key cache !split"));
1303	if ((k->wk_flags & IEEE80211_KEY_XR) == IEEE80211_KEY_XR) {
1304		/*
1305		 * TX key goes at first index, RX key at the rx index.
1306		 * The hal handles the MIC keys at index+64.
1307		 */
1308		memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_mic));
1309		KEYPRINTF(sc, k->wk_keyix, hk, zerobssid);
1310		if (!ath_hal_keyset(ah, k->wk_keyix, hk, zerobssid))
1311			return 0;
1312
1313		memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1314		KEYPRINTF(sc, k->wk_keyix+32, hk, mac);
1315		/* XXX delete tx key on failure? */
1316		return ath_hal_keyset(ah, k->wk_keyix+32, hk, mac);
1317	} else if (k->wk_flags & IEEE80211_KEY_XR) {
1318		/*
1319		 * TX/RX key goes at first index.
1320		 * The hal handles the MIC keys are index+64.
1321		 */
1322		memcpy(hk->kv_mic, k->wk_flags & IEEE80211_KEY_XMIT ?
1323			k->wk_txmic : k->wk_rxmic, sizeof(hk->kv_mic));
1324		KEYPRINTF(sc, k->wk_keyix, hk, mac);
1325		return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1326	}
1327	return 0;
1328#undef IEEE80211_KEY_XR
1329}
1330
1331/*
1332 * Set a net80211 key into the hardware.  This handles the
1333 * potential distribution of key state to multiple key
1334 * cache slots for TKIP with hardware MIC support.
1335 */
1336static int
1337ath_keyset(struct ath_softc *sc, const struct ieee80211_key *k,
1338	const u_int8_t mac0[IEEE80211_ADDR_LEN],
1339	struct ieee80211_node *bss)
1340{
1341#define	N(a)	(sizeof(a)/sizeof(a[0]))
1342	static const u_int8_t ciphermap[] = {
1343		HAL_CIPHER_WEP,		/* IEEE80211_CIPHER_WEP */
1344		HAL_CIPHER_TKIP,	/* IEEE80211_CIPHER_TKIP */
1345		HAL_CIPHER_AES_OCB,	/* IEEE80211_CIPHER_AES_OCB */
1346		HAL_CIPHER_AES_CCM,	/* IEEE80211_CIPHER_AES_CCM */
1347		(u_int8_t) -1,		/* 4 is not allocated */
1348		HAL_CIPHER_CKIP,	/* IEEE80211_CIPHER_CKIP */
1349		HAL_CIPHER_CLR,		/* IEEE80211_CIPHER_NONE */
1350	};
1351	struct ath_hal *ah = sc->sc_ah;
1352	const struct ieee80211_cipher *cip = k->wk_cipher;
1353	u_int8_t gmac[IEEE80211_ADDR_LEN];
1354	const u_int8_t *mac;
1355	HAL_KEYVAL hk;
1356
1357	memset(&hk, 0, sizeof(hk));
1358	/*
1359	 * Software crypto uses a "clear key" so non-crypto
1360	 * state kept in the key cache are maintained and
1361	 * so that rx frames have an entry to match.
1362	 */
1363	if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) == 0) {
1364		KASSERT(cip->ic_cipher < N(ciphermap),
1365			("invalid cipher type %u", cip->ic_cipher));
1366		hk.kv_type = ciphermap[cip->ic_cipher];
1367		hk.kv_len = k->wk_keylen;
1368		memcpy(hk.kv_val, k->wk_key, k->wk_keylen);
1369	} else
1370		hk.kv_type = HAL_CIPHER_CLR;
1371
1372	if ((k->wk_flags & IEEE80211_KEY_GROUP) && sc->sc_mcastkey) {
1373		/*
1374		 * Group keys on hardware that supports multicast frame
1375		 * key search use a mac that is the sender's address with
1376		 * the high bit set instead of the app-specified address.
1377		 */
1378		IEEE80211_ADDR_COPY(gmac, bss->ni_macaddr);
1379		gmac[0] |= 0x80;
1380		mac = gmac;
1381	} else
1382		mac = mac0;
1383
1384	if (hk.kv_type == HAL_CIPHER_TKIP &&
1385	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 &&
1386	    sc->sc_splitmic) {
1387		return ath_keyset_tkip(sc, k, &hk, mac);
1388	} else {
1389		KEYPRINTF(sc, k->wk_keyix, &hk, mac);
1390		return ath_hal_keyset(ah, k->wk_keyix, &hk, mac);
1391	}
1392#undef N
1393}
1394
1395/*
1396 * Allocate tx/rx key slots for TKIP.  We allocate two slots for
1397 * each key, one for decrypt/encrypt and the other for the MIC.
1398 */
1399static u_int16_t
1400key_alloc_2pair(struct ath_softc *sc,
1401	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
1402{
1403#define	N(a)	(sizeof(a)/sizeof(a[0]))
1404	u_int i, keyix;
1405
1406	KASSERT(sc->sc_splitmic, ("key cache !split"));
1407	/* XXX could optimize */
1408	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
1409		u_int8_t b = sc->sc_keymap[i];
1410		if (b != 0xff) {
1411			/*
1412			 * One or more slots in this byte are free.
1413			 */
1414			keyix = i*NBBY;
1415			while (b & 1) {
1416		again:
1417				keyix++;
1418				b >>= 1;
1419			}
1420			/* XXX IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV */
1421			if (isset(sc->sc_keymap, keyix+32) ||
1422			    isset(sc->sc_keymap, keyix+64) ||
1423			    isset(sc->sc_keymap, keyix+32+64)) {
1424				/* full pair unavailable */
1425				/* XXX statistic */
1426				if (keyix == (i+1)*NBBY) {
1427					/* no slots were appropriate, advance */
1428					continue;
1429				}
1430				goto again;
1431			}
1432			setbit(sc->sc_keymap, keyix);
1433			setbit(sc->sc_keymap, keyix+64);
1434			setbit(sc->sc_keymap, keyix+32);
1435			setbit(sc->sc_keymap, keyix+32+64);
1436			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
1437				"%s: key pair %u,%u %u,%u\n",
1438				__func__, keyix, keyix+64,
1439				keyix+32, keyix+32+64);
1440			*txkeyix = keyix;
1441			*rxkeyix = keyix+32;
1442			return 1;
1443		}
1444	}
1445	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
1446	return 0;
1447#undef N
1448}
1449
1450/*
1451 * Allocate a single key cache slot.
1452 */
1453static int
1454key_alloc_single(struct ath_softc *sc,
1455	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
1456{
1457#define	N(a)	(sizeof(a)/sizeof(a[0]))
1458	u_int i, keyix;
1459
1460	/* XXX try i,i+32,i+64,i+32+64 to minimize key pair conflicts */
1461	for (i = 0; i < N(sc->sc_keymap); i++) {
1462		u_int8_t b = sc->sc_keymap[i];
1463		if (b != 0xff) {
1464			/*
1465			 * One or more slots are free.
1466			 */
1467			keyix = i*NBBY;
1468			while (b & 1)
1469				keyix++, b >>= 1;
1470			setbit(sc->sc_keymap, keyix);
1471			DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: key %u\n",
1472				__func__, keyix);
1473			*txkeyix = *rxkeyix = keyix;
1474			return 1;
1475		}
1476	}
1477	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of space\n", __func__);
1478	return 0;
1479#undef N
1480}
1481
1482/*
1483 * Allocate one or more key cache slots for a uniacst key.  The
1484 * key itself is needed only to identify the cipher.  For hardware
1485 * TKIP with split cipher+MIC keys we allocate two key cache slot
1486 * pairs so that we can setup separate TX and RX MIC keys.  Note
1487 * that the MIC key for a TKIP key at slot i is assumed by the
1488 * hardware to be at slot i+64.  This limits TKIP keys to the first
1489 * 64 entries.
1490 */
1491static int
1492ath_key_alloc(struct ieee80211com *ic, const struct ieee80211_key *k,
1493	ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
1494{
1495	struct ath_softc *sc = ic->ic_ifp->if_softc;
1496
1497	/*
1498	 * Group key allocation must be handled specially for
1499	 * parts that do not support multicast key cache search
1500	 * functionality.  For those parts the key id must match
1501	 * the h/w key index so lookups find the right key.  On
1502	 * parts w/ the key search facility we install the sender's
1503	 * mac address (with the high bit set) and let the hardware
1504	 * find the key w/o using the key id.  This is preferred as
1505	 * it permits us to support multiple users for adhoc and/or
1506	 * multi-station operation.
1507	 */
1508	if ((k->wk_flags & IEEE80211_KEY_GROUP) && !sc->sc_mcastkey) {
1509		if (!(&ic->ic_nw_keys[0] <= k &&
1510		      k < &ic->ic_nw_keys[IEEE80211_WEP_NKID])) {
1511			/* should not happen */
1512			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
1513				"%s: bogus group key\n", __func__);
1514			return 0;
1515		}
1516		/*
1517		 * XXX we pre-allocate the global keys so
1518		 * have no way to check if they've already been allocated.
1519		 */
1520		*keyix = *rxkeyix = k - ic->ic_nw_keys;
1521		return 1;
1522	}
1523
1524	/*
1525	 * We allocate two pair for TKIP when using the h/w to do
1526	 * the MIC.  For everything else, including software crypto,
1527	 * we allocate a single entry.  Note that s/w crypto requires
1528	 * a pass-through slot on the 5211 and 5212.  The 5210 does
1529	 * not support pass-through cache entries and we map all
1530	 * those requests to slot 0.
1531	 */
1532	if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
1533		return key_alloc_single(sc, keyix, rxkeyix);
1534	} else if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP &&
1535	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic) {
1536		return key_alloc_2pair(sc, keyix, rxkeyix);
1537	} else {
1538		return key_alloc_single(sc, keyix, rxkeyix);
1539	}
1540}
1541
1542/*
1543 * Delete an entry in the key cache allocated by ath_key_alloc.
1544 */
1545static int
1546ath_key_delete(struct ieee80211com *ic, const struct ieee80211_key *k)
1547{
1548	struct ath_softc *sc = ic->ic_ifp->if_softc;
1549	struct ath_hal *ah = sc->sc_ah;
1550	const struct ieee80211_cipher *cip = k->wk_cipher;
1551	u_int keyix = k->wk_keyix;
1552
1553	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: delete key %u\n", __func__, keyix);
1554
1555	ath_hal_keyreset(ah, keyix);
1556	/*
1557	 * Handle split tx/rx keying required for TKIP with h/w MIC.
1558	 */
1559	if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
1560	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic)
1561		ath_hal_keyreset(ah, keyix+32);		/* RX key */
1562	if (keyix >= IEEE80211_WEP_NKID) {
1563		/*
1564		 * Don't touch keymap entries for global keys so
1565		 * they are never considered for dynamic allocation.
1566		 */
1567		clrbit(sc->sc_keymap, keyix);
1568		if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
1569		    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 &&
1570		    sc->sc_splitmic) {
1571			clrbit(sc->sc_keymap, keyix+64);	/* TX key MIC */
1572			clrbit(sc->sc_keymap, keyix+32);	/* RX key */
1573			clrbit(sc->sc_keymap, keyix+32+64);	/* RX key MIC */
1574		}
1575	}
1576	return 1;
1577}
1578
1579/*
1580 * Set the key cache contents for the specified key.  Key cache
1581 * slot(s) must already have been allocated by ath_key_alloc.
1582 */
1583static int
1584ath_key_set(struct ieee80211com *ic, const struct ieee80211_key *k,
1585	const u_int8_t mac[IEEE80211_ADDR_LEN])
1586{
1587	struct ath_softc *sc = ic->ic_ifp->if_softc;
1588
1589	return ath_keyset(sc, k, mac, ic->ic_bss);
1590}
1591
1592/*
1593 * Block/unblock tx+rx processing while a key change is done.
1594 * We assume the caller serializes key management operations
1595 * so we only need to worry about synchronization with other
1596 * uses that originate in the driver.
1597 */
1598static void
1599ath_key_update_begin(struct ieee80211com *ic)
1600{
1601	struct ifnet *ifp = ic->ic_ifp;
1602	struct ath_softc *sc = ifp->if_softc;
1603
1604	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
1605#if 0
1606	tasklet_disable(&sc->sc_rxtq);
1607#endif
1608	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
1609}
1610
1611static void
1612ath_key_update_end(struct ieee80211com *ic)
1613{
1614	struct ifnet *ifp = ic->ic_ifp;
1615	struct ath_softc *sc = ifp->if_softc;
1616
1617	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
1618	IF_UNLOCK(&ifp->if_snd);
1619#if 0
1620	tasklet_enable(&sc->sc_rxtq);
1621#endif
1622}
1623
1624/*
1625 * Calculate the receive filter according to the
1626 * operating mode and state:
1627 *
1628 * o always accept unicast, broadcast, and multicast traffic
1629 * o maintain current state of phy error reception (the hal
1630 *   may enable phy error frames for noise immunity work)
1631 * o probe request frames are accepted only when operating in
1632 *   hostap, adhoc, or monitor modes
1633 * o enable promiscuous mode according to the interface state
1634 * o accept beacons:
1635 *   - when operating in adhoc mode so the 802.11 layer creates
1636 *     node table entries for peers,
1637 *   - when operating in station mode for collecting rssi data when
1638 *     the station is otherwise quiet, or
1639 *   - when scanning
1640 */
1641static u_int32_t
1642ath_calcrxfilter(struct ath_softc *sc, enum ieee80211_state state)
1643{
1644	struct ieee80211com *ic = &sc->sc_ic;
1645	struct ath_hal *ah = sc->sc_ah;
1646	struct ifnet *ifp = sc->sc_ifp;
1647	u_int32_t rfilt;
1648
1649	rfilt = (ath_hal_getrxfilter(ah) & HAL_RX_FILTER_PHYERR)
1650	      | HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
1651	if (ic->ic_opmode != IEEE80211_M_STA)
1652		rfilt |= HAL_RX_FILTER_PROBEREQ;
1653	if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
1654	    (ifp->if_flags & IFF_PROMISC))
1655		rfilt |= HAL_RX_FILTER_PROM;
1656	if (ic->ic_opmode == IEEE80211_M_STA ||
1657	    ic->ic_opmode == IEEE80211_M_IBSS ||
1658	    state == IEEE80211_S_SCAN)
1659		rfilt |= HAL_RX_FILTER_BEACON;
1660	return rfilt;
1661}
1662
1663static void
1664ath_mode_init(struct ath_softc *sc)
1665{
1666	struct ieee80211com *ic = &sc->sc_ic;
1667	struct ath_hal *ah = sc->sc_ah;
1668	struct ifnet *ifp = sc->sc_ifp;
1669	u_int32_t rfilt, mfilt[2], val;
1670	u_int8_t pos;
1671	struct ifmultiaddr *ifma;
1672
1673	/* configure rx filter */
1674	rfilt = ath_calcrxfilter(sc, ic->ic_state);
1675	ath_hal_setrxfilter(ah, rfilt);
1676
1677	/* configure operational mode */
1678	ath_hal_setopmode(ah);
1679
1680	/*
1681	 * Handle any link-level address change.  Note that we only
1682	 * need to force ic_myaddr; any other addresses are handled
1683	 * as a byproduct of the ifnet code marking the interface
1684	 * down then up.
1685	 *
1686	 * XXX should get from lladdr instead of arpcom but that's more work
1687	 */
1688	IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
1689	ath_hal_setmac(ah, ic->ic_myaddr);
1690
1691	/* calculate and install multicast filter */
1692	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
1693		mfilt[0] = mfilt[1] = 0;
1694		IF_ADDR_LOCK(ifp);
1695		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1696			caddr_t dl;
1697
1698			/* calculate XOR of eight 6bit values */
1699			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
1700			val = LE_READ_4(dl + 0);
1701			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
1702			val = LE_READ_4(dl + 3);
1703			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
1704			pos &= 0x3f;
1705			mfilt[pos / 32] |= (1 << (pos % 32));
1706		}
1707		IF_ADDR_UNLOCK(ifp);
1708	} else {
1709		mfilt[0] = mfilt[1] = ~0;
1710	}
1711	ath_hal_setmcastfilter(ah, mfilt[0], mfilt[1]);
1712	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, MC filter %08x:%08x\n",
1713		__func__, rfilt, mfilt[0], mfilt[1]);
1714}
1715
1716/*
1717 * Set the slot time based on the current setting.
1718 */
1719static void
1720ath_setslottime(struct ath_softc *sc)
1721{
1722	struct ieee80211com *ic = &sc->sc_ic;
1723	struct ath_hal *ah = sc->sc_ah;
1724
1725	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1726		ath_hal_setslottime(ah, HAL_SLOT_TIME_9);
1727	else
1728		ath_hal_setslottime(ah, HAL_SLOT_TIME_20);
1729	sc->sc_updateslot = OK;
1730}
1731
1732/*
1733 * Callback from the 802.11 layer to update the
1734 * slot time based on the current setting.
1735 */
1736static void
1737ath_updateslot(struct ifnet *ifp)
1738{
1739	struct ath_softc *sc = ifp->if_softc;
1740	struct ieee80211com *ic = &sc->sc_ic;
1741
1742	/*
1743	 * When not coordinating the BSS, change the hardware
1744	 * immediately.  For other operation we defer the change
1745	 * until beacon updates have propagated to the stations.
1746	 */
1747	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1748		sc->sc_updateslot = UPDATE;
1749	else
1750		ath_setslottime(sc);
1751}
1752
1753/*
1754 * Setup a h/w transmit queue for beacons.
1755 */
1756static int
1757ath_beaconq_setup(struct ath_hal *ah)
1758{
1759	HAL_TXQ_INFO qi;
1760
1761	memset(&qi, 0, sizeof(qi));
1762	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
1763	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
1764	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
1765	/* NB: for dynamic turbo, don't enable any other interrupts */
1766	qi.tqi_qflags = TXQ_FLAG_TXDESCINT_ENABLE;
1767	return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
1768}
1769
1770/*
1771 * Setup the transmit queue parameters for the beacon queue.
1772 */
1773static int
1774ath_beaconq_config(struct ath_softc *sc)
1775{
1776#define	ATH_EXPONENT_TO_VALUE(v)	((1<<(v))-1)
1777	struct ieee80211com *ic = &sc->sc_ic;
1778	struct ath_hal *ah = sc->sc_ah;
1779	HAL_TXQ_INFO qi;
1780
1781	ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
1782	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1783		/*
1784		 * Always burst out beacon and CAB traffic.
1785		 */
1786		qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
1787		qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
1788		qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
1789	} else {
1790		struct wmeParams *wmep =
1791			&ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
1792		/*
1793		 * Adhoc mode; important thing is to use 2x cwmin.
1794		 */
1795		qi.tqi_aifs = wmep->wmep_aifsn;
1796		qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
1797		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
1798	}
1799
1800	if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
1801		device_printf(sc->sc_dev, "unable to update parameters for "
1802			"beacon hardware queue!\n");
1803		return 0;
1804	} else {
1805		ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
1806		return 1;
1807	}
1808#undef ATH_EXPONENT_TO_VALUE
1809}
1810
1811/*
1812 * Allocate and setup an initial beacon frame.
1813 */
1814static int
1815ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
1816{
1817	struct ieee80211com *ic = ni->ni_ic;
1818	struct ath_buf *bf;
1819	struct mbuf *m;
1820	int error;
1821
1822	bf = STAILQ_FIRST(&sc->sc_bbuf);
1823	if (bf == NULL) {
1824		DPRINTF(sc, ATH_DEBUG_BEACON, "%s: no dma buffers\n", __func__);
1825		sc->sc_stats.ast_be_nombuf++;	/* XXX */
1826		return ENOMEM;			/* XXX */
1827	}
1828	/*
1829	 * NB: the beacon data buffer must be 32-bit aligned;
1830	 * we assume the mbuf routines will return us something
1831	 * with this alignment (perhaps should assert).
1832	 */
1833	m = ieee80211_beacon_alloc(ic, ni, &sc->sc_boff);
1834	if (m == NULL) {
1835		DPRINTF(sc, ATH_DEBUG_BEACON, "%s: cannot get mbuf\n",
1836			__func__);
1837		sc->sc_stats.ast_be_nombuf++;
1838		return ENOMEM;
1839	}
1840	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
1841				     bf->bf_segs, &bf->bf_nseg,
1842				     BUS_DMA_NOWAIT);
1843	if (error == 0) {
1844		bf->bf_m = m;
1845		bf->bf_node = ieee80211_ref_node(ni);
1846	} else {
1847		m_freem(m);
1848	}
1849	return error;
1850}
1851
1852/*
1853 * Setup the beacon frame for transmit.
1854 */
1855static void
1856ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
1857{
1858#define	USE_SHPREAMBLE(_ic) \
1859	(((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
1860		== IEEE80211_F_SHPREAMBLE)
1861	struct ieee80211_node *ni = bf->bf_node;
1862	struct ieee80211com *ic = ni->ni_ic;
1863	struct mbuf *m = bf->bf_m;
1864	struct ath_hal *ah = sc->sc_ah;
1865	struct ath_desc *ds;
1866	int flags, antenna;
1867	const HAL_RATE_TABLE *rt;
1868	u_int8_t rix, rate;
1869
1870	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: m %p len %u\n",
1871		__func__, m, m->m_len);
1872
1873	/* setup descriptors */
1874	ds = bf->bf_desc;
1875
1876	flags = HAL_TXDESC_NOACK;
1877	if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
1878		ds->ds_link = bf->bf_daddr;	/* self-linked */
1879		flags |= HAL_TXDESC_VEOL;
1880		/*
1881		 * Let hardware handle antenna switching.
1882		 */
1883		antenna = sc->sc_txantenna;
1884	} else {
1885		ds->ds_link = 0;
1886		/*
1887		 * Switch antenna every 4 beacons.
1888		 * XXX assumes two antenna
1889		 */
1890		antenna = (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
1891	}
1892
1893	KASSERT(bf->bf_nseg == 1,
1894		("multi-segment beacon frame; nseg %u", bf->bf_nseg));
1895	ds->ds_data = bf->bf_segs[0].ds_addr;
1896	/*
1897	 * Calculate rate code.
1898	 * XXX everything at min xmit rate
1899	 */
1900	rix = sc->sc_minrateix;
1901	rt = sc->sc_currates;
1902	rate = rt->info[rix].rateCode;
1903	if (USE_SHPREAMBLE(ic))
1904		rate |= rt->info[rix].shortPreamble;
1905	ath_hal_setuptxdesc(ah, ds
1906		, m->m_len + IEEE80211_CRC_LEN	/* frame length */
1907		, sizeof(struct ieee80211_frame)/* header length */
1908		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
1909		, ni->ni_txpower		/* txpower XXX */
1910		, rate, 1			/* series 0 rate/tries */
1911		, HAL_TXKEYIX_INVALID		/* no encryption */
1912		, antenna			/* antenna mode */
1913		, flags				/* no ack, veol for beacons */
1914		, 0				/* rts/cts rate */
1915		, 0				/* rts/cts duration */
1916	);
1917	/* NB: beacon's BufLen must be a multiple of 4 bytes */
1918	ath_hal_filltxdesc(ah, ds
1919		, roundup(m->m_len, 4)		/* buffer length */
1920		, AH_TRUE			/* first segment */
1921		, AH_TRUE			/* last segment */
1922		, ds				/* first descriptor */
1923	);
1924#undef USE_SHPREAMBLE
1925}
1926
1927/*
1928 * Transmit a beacon frame at SWBA.  Dynamic updates to the
1929 * frame contents are done as needed and the slot time is
1930 * also adjusted based on current state.
1931 */
1932static void
1933ath_beacon_proc(void *arg, int pending)
1934{
1935	struct ath_softc *sc = arg;
1936	struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
1937	struct ieee80211_node *ni = bf->bf_node;
1938	struct ieee80211com *ic = ni->ni_ic;
1939	struct ath_hal *ah = sc->sc_ah;
1940	struct mbuf *m;
1941	int ncabq, error, otherant;
1942
1943	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
1944		__func__, pending);
1945
1946	if (ic->ic_opmode == IEEE80211_M_STA ||
1947	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1948	    bf == NULL || bf->bf_m == NULL) {
1949		DPRINTF(sc, ATH_DEBUG_ANY, "%s: ic_flags=%x bf=%p bf_m=%p\n",
1950			__func__, ic->ic_flags, bf, bf ? bf->bf_m : NULL);
1951		return;
1952	}
1953	/*
1954	 * Check if the previous beacon has gone out.  If
1955	 * not don't don't try to post another, skip this
1956	 * period and wait for the next.  Missed beacons
1957	 * indicate a problem and should not occur.  If we
1958	 * miss too many consecutive beacons reset the device.
1959	 */
1960	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
1961		sc->sc_bmisscount++;
1962		DPRINTF(sc, ATH_DEBUG_BEACON_PROC,
1963			"%s: missed %u consecutive beacons\n",
1964			__func__, sc->sc_bmisscount);
1965		if (sc->sc_bmisscount > 3)		/* NB: 3 is a guess */
1966			taskqueue_enqueue(taskqueue_swi, &sc->sc_bstucktask);
1967		return;
1968	}
1969	if (sc->sc_bmisscount != 0) {
1970		DPRINTF(sc, ATH_DEBUG_BEACON,
1971			"%s: resume beacon xmit after %u misses\n",
1972			__func__, sc->sc_bmisscount);
1973		sc->sc_bmisscount = 0;
1974	}
1975
1976	/*
1977	 * Update dynamic beacon contents.  If this returns
1978	 * non-zero then we need to remap the memory because
1979	 * the beacon frame changed size (probably because
1980	 * of the TIM bitmap).
1981	 */
1982	m = bf->bf_m;
1983	ncabq = ath_hal_numtxpending(ah, sc->sc_cabq->axq_qnum);
1984	if (ieee80211_beacon_update(ic, bf->bf_node, &sc->sc_boff, m, ncabq)) {
1985		/* XXX too conservative? */
1986		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
1987		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
1988					     bf->bf_segs, &bf->bf_nseg,
1989					     BUS_DMA_NOWAIT);
1990		if (error != 0) {
1991			if_printf(ic->ic_ifp,
1992			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
1993			    __func__, error);
1994			return;
1995		}
1996	}
1997
1998	/*
1999	 * Handle slot time change when a non-ERP station joins/leaves
2000	 * an 11g network.  The 802.11 layer notifies us via callback,
2001	 * we mark updateslot, then wait one beacon before effecting
2002	 * the change.  This gives associated stations at least one
2003	 * beacon interval to note the state change.
2004	 */
2005	/* XXX locking */
2006	if (sc->sc_updateslot == UPDATE)
2007		sc->sc_updateslot = COMMIT;	/* commit next beacon */
2008	else if (sc->sc_updateslot == COMMIT)
2009		ath_setslottime(sc);		/* commit change to h/w */
2010
2011	/*
2012	 * Check recent per-antenna transmit statistics and flip
2013	 * the default antenna if noticeably more frames went out
2014	 * on the non-default antenna.
2015	 * XXX assumes 2 anntenae
2016	 */
2017	otherant = sc->sc_defant & 1 ? 2 : 1;
2018	if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
2019		ath_setdefantenna(sc, otherant);
2020	sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
2021
2022	/*
2023	 * Construct tx descriptor.
2024	 */
2025	ath_beacon_setup(sc, bf);
2026
2027	/*
2028	 * Stop any current dma and put the new frame on the queue.
2029	 * This should never fail since we check above that no frames
2030	 * are still pending on the queue.
2031	 */
2032	if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
2033		DPRINTF(sc, ATH_DEBUG_ANY,
2034			"%s: beacon queue %u did not stop?\n",
2035			__func__, sc->sc_bhalq);
2036	}
2037	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2038
2039	/*
2040	 * Enable the CAB queue before the beacon queue to
2041	 * insure cab frames are triggered by this beacon.
2042	 */
2043	if (sc->sc_boff.bo_tim[4] & 1)		/* NB: only at DTIM */
2044		ath_hal_txstart(ah, sc->sc_cabq->axq_qnum);
2045	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
2046	ath_hal_txstart(ah, sc->sc_bhalq);
2047	DPRINTF(sc, ATH_DEBUG_BEACON_PROC,
2048		"%s: TXDP[%u] = %p (%p)\n", __func__,
2049		sc->sc_bhalq, (caddr_t)bf->bf_daddr, bf->bf_desc);
2050
2051	sc->sc_stats.ast_be_xmit++;
2052}
2053
2054/*
2055 * Reset the hardware after detecting beacons have stopped.
2056 */
2057static void
2058ath_bstuck_proc(void *arg, int pending)
2059{
2060	struct ath_softc *sc = arg;
2061	struct ifnet *ifp = sc->sc_ifp;
2062
2063	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
2064		sc->sc_bmisscount);
2065	ath_reset(ifp);
2066}
2067
2068/*
2069 * Reclaim beacon resources.
2070 */
2071static void
2072ath_beacon_free(struct ath_softc *sc)
2073{
2074	struct ath_buf *bf;
2075
2076	STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
2077		if (bf->bf_m != NULL) {
2078			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2079			m_freem(bf->bf_m);
2080			bf->bf_m = NULL;
2081		}
2082		if (bf->bf_node != NULL) {
2083			ieee80211_free_node(bf->bf_node);
2084			bf->bf_node = NULL;
2085		}
2086	}
2087}
2088
2089/*
2090 * Configure the beacon and sleep timers.
2091 *
2092 * When operating as an AP this resets the TSF and sets
2093 * up the hardware to notify us when we need to issue beacons.
2094 *
2095 * When operating in station mode this sets up the beacon
2096 * timers according to the timestamp of the last received
2097 * beacon and the current TSF, configures PCF and DTIM
2098 * handling, programs the sleep registers so the hardware
2099 * will wakeup in time to receive beacons, and configures
2100 * the beacon miss handling so we'll receive a BMISS
2101 * interrupt when we stop seeing beacons from the AP
2102 * we've associated with.
2103 */
2104static void
2105ath_beacon_config(struct ath_softc *sc)
2106{
2107#define	TSF_TO_TU(_h,_l)	(((_h) << 22) | ((_l) >> 10))
2108	struct ath_hal *ah = sc->sc_ah;
2109	struct ieee80211com *ic = &sc->sc_ic;
2110	struct ieee80211_node *ni = ic->ic_bss;
2111	u_int32_t nexttbtt, intval;
2112
2113	/* extract tstamp from last beacon and convert to TU */
2114	nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
2115			     LE_READ_4(ni->ni_tstamp.data));
2116	/* NB: the beacon interval is kept internally in TU's */
2117	intval = ni->ni_intval & HAL_BEACON_PERIOD;
2118	if (nexttbtt == 0)		/* e.g. for ap mode */
2119		nexttbtt = intval;
2120	else if (intval)		/* NB: can be 0 for monitor mode */
2121		nexttbtt = roundup(nexttbtt, intval);
2122	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
2123		__func__, nexttbtt, intval, ni->ni_intval);
2124	if (ic->ic_opmode == IEEE80211_M_STA) {
2125		HAL_BEACON_STATE bs;
2126		u_int64_t tsf;
2127		u_int32_t tsftu;
2128		int dtimperiod, dtimcount;
2129		int cfpperiod, cfpcount;
2130
2131		/*
2132		 * Setup dtim and cfp parameters according to
2133		 * last beacon we received (which may be none).
2134		 */
2135		dtimperiod = ni->ni_dtim_period;
2136		if (dtimperiod <= 0)		/* NB: 0 if not known */
2137			dtimperiod = 1;
2138		dtimcount = ni->ni_dtim_count;
2139		if (dtimcount >= dtimperiod)	/* NB: sanity check */
2140			dtimcount = 0;		/* XXX? */
2141		cfpperiod = 1;			/* NB: no PCF support yet */
2142		cfpcount = 0;
2143#define	FUDGE	2
2144		/*
2145		 * Pull nexttbtt forward to reflect the current
2146		 * TSF and calculate dtim+cfp state for the result.
2147		 */
2148		tsf = ath_hal_gettsf64(ah);
2149		tsftu = TSF_TO_TU((u_int32_t)(tsf>>32), (u_int32_t)tsf) + FUDGE;
2150		do {
2151			nexttbtt += intval;
2152			if (--dtimcount < 0) {
2153				dtimcount = dtimperiod - 1;
2154				if (--cfpcount < 0)
2155					cfpcount = cfpperiod - 1;
2156			}
2157		} while (nexttbtt < tsftu);
2158#undef FUDGE
2159		memset(&bs, 0, sizeof(bs));
2160		bs.bs_intval = intval;
2161		bs.bs_nexttbtt = nexttbtt;
2162		bs.bs_dtimperiod = dtimperiod*intval;
2163		bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
2164		bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
2165		bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
2166		bs.bs_cfpmaxduration = 0;
2167#if 0
2168		/*
2169		 * The 802.11 layer records the offset to the DTIM
2170		 * bitmap while receiving beacons; use it here to
2171		 * enable h/w detection of our AID being marked in
2172		 * the bitmap vector (to indicate frames for us are
2173		 * pending at the AP).
2174		 * XXX do DTIM handling in s/w to WAR old h/w bugs
2175		 * XXX enable based on h/w rev for newer chips
2176		 */
2177		bs.bs_timoffset = ni->ni_timoff;
2178#endif
2179		/*
2180		 * Calculate the number of consecutive beacons to miss
2181		 * before taking a BMISS interrupt.  The configuration
2182		 * is specified in ms, so we need to convert that to
2183		 * TU's and then calculate based on the beacon interval.
2184		 * Note that we clamp the result to at most 10 beacons.
2185		 */
2186		bs.bs_bmissthreshold = ic->ic_bmissthreshold;
2187		if (bs.bs_bmissthreshold > 10)
2188			bs.bs_bmissthreshold = 10;
2189		else if (bs.bs_bmissthreshold <= 0)
2190			bs.bs_bmissthreshold = 1;
2191
2192		/*
2193		 * Calculate sleep duration.  The configuration is
2194		 * given in ms.  We insure a multiple of the beacon
2195		 * period is used.  Also, if the sleep duration is
2196		 * greater than the DTIM period then it makes senses
2197		 * to make it a multiple of that.
2198		 *
2199		 * XXX fixed at 100ms
2200		 */
2201		bs.bs_sleepduration =
2202			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
2203		if (bs.bs_sleepduration > bs.bs_dtimperiod)
2204			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
2205
2206		DPRINTF(sc, ATH_DEBUG_BEACON,
2207			"%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"
2208			, __func__
2209			, tsf, tsftu
2210			, bs.bs_intval
2211			, bs.bs_nexttbtt
2212			, bs.bs_dtimperiod
2213			, bs.bs_nextdtim
2214			, bs.bs_bmissthreshold
2215			, bs.bs_sleepduration
2216			, bs.bs_cfpperiod
2217			, bs.bs_cfpmaxduration
2218			, bs.bs_cfpnext
2219			, bs.bs_timoffset
2220		);
2221		ath_hal_intrset(ah, 0);
2222		ath_hal_beacontimers(ah, &bs);
2223		sc->sc_imask |= HAL_INT_BMISS;
2224		ath_hal_intrset(ah, sc->sc_imask);
2225	} else {
2226		ath_hal_intrset(ah, 0);
2227		if (nexttbtt == intval)
2228			intval |= HAL_BEACON_RESET_TSF;
2229		if (ic->ic_opmode == IEEE80211_M_IBSS) {
2230			/*
2231			 * In IBSS mode enable the beacon timers but only
2232			 * enable SWBA interrupts if we need to manually
2233			 * prepare beacon frames.  Otherwise we use a
2234			 * self-linked tx descriptor and let the hardware
2235			 * deal with things.
2236			 */
2237			intval |= HAL_BEACON_ENA;
2238			if (!sc->sc_hasveol)
2239				sc->sc_imask |= HAL_INT_SWBA;
2240			ath_beaconq_config(sc);
2241		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2242			/*
2243			 * In AP mode we enable the beacon timers and
2244			 * SWBA interrupts to prepare beacon frames.
2245			 */
2246			intval |= HAL_BEACON_ENA;
2247			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
2248			ath_beaconq_config(sc);
2249		}
2250		ath_hal_beaconinit(ah, nexttbtt, intval);
2251		sc->sc_bmisscount = 0;
2252		ath_hal_intrset(ah, sc->sc_imask);
2253		/*
2254		 * When using a self-linked beacon descriptor in
2255		 * ibss mode load it once here.
2256		 */
2257		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
2258			ath_beacon_proc(sc, 0);
2259	}
2260#undef TSF_TO_TU
2261}
2262
2263static void
2264ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2265{
2266	bus_addr_t *paddr = (bus_addr_t*) arg;
2267	KASSERT(error == 0, ("error %u on bus_dma callback", error));
2268	*paddr = segs->ds_addr;
2269}
2270
2271static int
2272ath_descdma_setup(struct ath_softc *sc,
2273	struct ath_descdma *dd, ath_bufhead *head,
2274	const char *name, int nbuf, int ndesc)
2275{
2276#define	DS2PHYS(_dd, _ds) \
2277	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
2278	struct ifnet *ifp = sc->sc_ifp;
2279	struct ath_desc *ds;
2280	struct ath_buf *bf;
2281	int i, bsize, error;
2282
2283	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
2284	    __func__, name, nbuf, ndesc);
2285
2286	dd->dd_name = name;
2287	dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
2288
2289	/*
2290	 * Setup DMA descriptor area.
2291	 */
2292	error = bus_dma_tag_create(NULL,	/* parent */
2293		       PAGE_SIZE, 0,		/* alignment, bounds */
2294		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
2295		       BUS_SPACE_MAXADDR,	/* highaddr */
2296		       NULL, NULL,		/* filter, filterarg */
2297		       dd->dd_desc_len,		/* maxsize */
2298		       1,			/* nsegments */
2299		       BUS_SPACE_MAXADDR,	/* maxsegsize */
2300		       BUS_DMA_ALLOCNOW,	/* flags */
2301		       NULL,			/* lockfunc */
2302		       NULL,			/* lockarg */
2303		       &dd->dd_dmat);
2304	if (error != 0) {
2305		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
2306		return error;
2307	}
2308
2309	/* allocate descriptors */
2310	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
2311	if (error != 0) {
2312		if_printf(ifp, "unable to create dmamap for %s descriptors, "
2313			"error %u\n", dd->dd_name, error);
2314		goto fail0;
2315	}
2316
2317	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
2318				 BUS_DMA_NOWAIT, &dd->dd_dmamap);
2319	if (error != 0) {
2320		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
2321			"error %u\n", nbuf * ndesc, dd->dd_name, error);
2322		goto fail1;
2323	}
2324
2325	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
2326				dd->dd_desc, dd->dd_desc_len,
2327				ath_load_cb, &dd->dd_desc_paddr,
2328				BUS_DMA_NOWAIT);
2329	if (error != 0) {
2330		if_printf(ifp, "unable to map %s descriptors, error %u\n",
2331			dd->dd_name, error);
2332		goto fail2;
2333	}
2334
2335	ds = dd->dd_desc;
2336	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
2337	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
2338	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
2339
2340	/* allocate rx buffers */
2341	bsize = sizeof(struct ath_buf) * nbuf;
2342	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
2343	if (bf == NULL) {
2344		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
2345			dd->dd_name, bsize);
2346		goto fail3;
2347	}
2348	dd->dd_bufptr = bf;
2349
2350	STAILQ_INIT(head);
2351	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
2352		bf->bf_desc = ds;
2353		bf->bf_daddr = DS2PHYS(dd, ds);
2354		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
2355				&bf->bf_dmamap);
2356		if (error != 0) {
2357			if_printf(ifp, "unable to create dmamap for %s "
2358				"buffer %u, error %u\n", dd->dd_name, i, error);
2359			ath_descdma_cleanup(sc, dd, head);
2360			return error;
2361		}
2362		STAILQ_INSERT_TAIL(head, bf, bf_list);
2363	}
2364	return 0;
2365fail3:
2366	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2367fail2:
2368	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2369fail1:
2370	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2371fail0:
2372	bus_dma_tag_destroy(dd->dd_dmat);
2373	memset(dd, 0, sizeof(*dd));
2374	return error;
2375#undef DS2PHYS
2376}
2377
2378static void
2379ath_descdma_cleanup(struct ath_softc *sc,
2380	struct ath_descdma *dd, ath_bufhead *head)
2381{
2382	struct ath_buf *bf;
2383	struct ieee80211_node *ni;
2384
2385	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2386	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2387	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2388	bus_dma_tag_destroy(dd->dd_dmat);
2389
2390	STAILQ_FOREACH(bf, head, bf_list) {
2391		if (bf->bf_m) {
2392			m_freem(bf->bf_m);
2393			bf->bf_m = NULL;
2394		}
2395		if (bf->bf_dmamap != NULL) {
2396			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
2397			bf->bf_dmamap = NULL;
2398		}
2399		ni = bf->bf_node;
2400		bf->bf_node = NULL;
2401		if (ni != NULL) {
2402			/*
2403			 * Reclaim node reference.
2404			 */
2405			ieee80211_free_node(ni);
2406		}
2407	}
2408
2409	STAILQ_INIT(head);
2410	free(dd->dd_bufptr, M_ATHDEV);
2411	memset(dd, 0, sizeof(*dd));
2412}
2413
2414static int
2415ath_desc_alloc(struct ath_softc *sc)
2416{
2417	int error;
2418
2419	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
2420			"rx", ath_rxbuf, 1);
2421	if (error != 0)
2422		return error;
2423
2424	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
2425			"tx", ath_txbuf, ATH_TXDESC);
2426	if (error != 0) {
2427		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2428		return error;
2429	}
2430
2431	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
2432			"beacon", 1, 1);
2433	if (error != 0) {
2434		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2435		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2436		return error;
2437	}
2438	return 0;
2439}
2440
2441static void
2442ath_desc_free(struct ath_softc *sc)
2443{
2444
2445	if (sc->sc_bdma.dd_desc_len != 0)
2446		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
2447	if (sc->sc_txdma.dd_desc_len != 0)
2448		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2449	if (sc->sc_rxdma.dd_desc_len != 0)
2450		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2451}
2452
2453static struct ieee80211_node *
2454ath_node_alloc(struct ieee80211_node_table *nt)
2455{
2456	struct ieee80211com *ic = nt->nt_ic;
2457	struct ath_softc *sc = ic->ic_ifp->if_softc;
2458	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
2459	struct ath_node *an;
2460
2461	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
2462	if (an == NULL) {
2463		/* XXX stat+msg */
2464		return NULL;
2465	}
2466	an->an_avgrssi = ATH_RSSI_DUMMY_MARKER;
2467	ath_rate_node_init(sc, an);
2468
2469	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
2470	return &an->an_node;
2471}
2472
2473static void
2474ath_node_free(struct ieee80211_node *ni)
2475{
2476	struct ieee80211com *ic = ni->ni_ic;
2477        struct ath_softc *sc = ic->ic_ifp->if_softc;
2478
2479	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
2480
2481	ath_rate_node_cleanup(sc, ATH_NODE(ni));
2482	sc->sc_node_free(ni);
2483}
2484
2485static u_int8_t
2486ath_node_getrssi(const struct ieee80211_node *ni)
2487{
2488#define	HAL_EP_RND(x, mul) \
2489	((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
2490	u_int32_t avgrssi = ATH_NODE_CONST(ni)->an_avgrssi;
2491	int32_t rssi;
2492
2493	/*
2494	 * When only one frame is received there will be no state in
2495	 * avgrssi so fallback on the value recorded by the 802.11 layer.
2496	 */
2497	if (avgrssi != ATH_RSSI_DUMMY_MARKER)
2498		rssi = HAL_EP_RND(avgrssi, HAL_RSSI_EP_MULTIPLIER);
2499	else
2500		rssi = ni->ni_rssi;
2501	/* NB: theoretically we shouldn't need this, but be paranoid */
2502	return rssi < 0 ? 0 : rssi > 127 ? 127 : rssi;
2503#undef HAL_EP_RND
2504}
2505
2506static int
2507ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
2508{
2509	struct ath_hal *ah = sc->sc_ah;
2510	int error;
2511	struct mbuf *m;
2512	struct ath_desc *ds;
2513
2514	m = bf->bf_m;
2515	if (m == NULL) {
2516		/*
2517		 * NB: by assigning a page to the rx dma buffer we
2518		 * implicitly satisfy the Atheros requirement that
2519		 * this buffer be cache-line-aligned and sized to be
2520		 * multiple of the cache line size.  Not doing this
2521		 * causes weird stuff to happen (for the 5210 at least).
2522		 */
2523		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
2524		if (m == NULL) {
2525			DPRINTF(sc, ATH_DEBUG_ANY,
2526				"%s: no mbuf/cluster\n", __func__);
2527			sc->sc_stats.ast_rx_nombuf++;
2528			return ENOMEM;
2529		}
2530		bf->bf_m = m;
2531		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
2532
2533		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
2534					     bf->bf_dmamap, m,
2535					     bf->bf_segs, &bf->bf_nseg,
2536					     BUS_DMA_NOWAIT);
2537		if (error != 0) {
2538			DPRINTF(sc, ATH_DEBUG_ANY,
2539			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
2540			    __func__, error);
2541			sc->sc_stats.ast_rx_busdma++;
2542			return error;
2543		}
2544		KASSERT(bf->bf_nseg == 1,
2545			("multi-segment packet; nseg %u", bf->bf_nseg));
2546	}
2547	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
2548
2549	/*
2550	 * Setup descriptors.  For receive we always terminate
2551	 * the descriptor list with a self-linked entry so we'll
2552	 * not get overrun under high load (as can happen with a
2553	 * 5212 when ANI processing enables PHY error frames).
2554	 *
2555	 * To insure the last descriptor is self-linked we create
2556	 * each descriptor as self-linked and add it to the end.  As
2557	 * each additional descriptor is added the previous self-linked
2558	 * entry is ``fixed'' naturally.  This should be safe even
2559	 * if DMA is happening.  When processing RX interrupts we
2560	 * never remove/process the last, self-linked, entry on the
2561	 * descriptor list.  This insures the hardware always has
2562	 * someplace to write a new frame.
2563	 */
2564	ds = bf->bf_desc;
2565	ds->ds_link = bf->bf_daddr;	/* link to self */
2566	ds->ds_data = bf->bf_segs[0].ds_addr;
2567	ath_hal_setuprxdesc(ah, ds
2568		, m->m_len		/* buffer size */
2569		, 0
2570	);
2571
2572	if (sc->sc_rxlink != NULL)
2573		*sc->sc_rxlink = bf->bf_daddr;
2574	sc->sc_rxlink = &ds->ds_link;
2575	return 0;
2576}
2577
2578/*
2579 * Extend 15-bit time stamp from rx descriptor to
2580 * a full 64-bit TSF using the specified TSF.
2581 */
2582static __inline u_int64_t
2583ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
2584{
2585	if ((tsf & 0x7fff) < rstamp)
2586		tsf -= 0x8000;
2587	return ((tsf &~ 0x7fff) | rstamp);
2588}
2589
2590/*
2591 * Intercept management frames to collect beacon rssi data
2592 * and to do ibss merges.
2593 */
2594static void
2595ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
2596	struct ieee80211_node *ni,
2597	int subtype, int rssi, u_int32_t rstamp)
2598{
2599	struct ath_softc *sc = ic->ic_ifp->if_softc;
2600
2601	/*
2602	 * Call up first so subsequent work can use information
2603	 * potentially stored in the node (e.g. for ibss merge).
2604	 */
2605	sc->sc_recv_mgmt(ic, m, ni, subtype, rssi, rstamp);
2606	switch (subtype) {
2607	case IEEE80211_FC0_SUBTYPE_BEACON:
2608		/* update rssi statistics for use by the hal */
2609		ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
2610		/* fall thru... */
2611	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
2612		if (ic->ic_opmode == IEEE80211_M_IBSS &&
2613		    ic->ic_state == IEEE80211_S_RUN) {
2614			u_int64_t tsf = ath_extend_tsf(rstamp,
2615				ath_hal_gettsf64(sc->sc_ah));
2616			/*
2617			 * Handle ibss merge as needed; check the tsf on the
2618			 * frame before attempting the merge.  The 802.11 spec
2619			 * says the station should change it's bssid to match
2620			 * the oldest station with the same ssid, where oldest
2621			 * is determined by the tsf.  Note that hardware
2622			 * reconfiguration happens through callback to
2623			 * ath_newstate as the state machine will go from
2624			 * RUN -> RUN when this happens.
2625			 */
2626			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
2627				DPRINTF(sc, ATH_DEBUG_STATE,
2628				    "ibss merge, rstamp %u tsf %ju "
2629				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
2630				    (uintmax_t)ni->ni_tstamp.tsf);
2631				(void) ieee80211_ibss_merge(ni);
2632			}
2633		}
2634		break;
2635	}
2636}
2637
2638/*
2639 * Set the default antenna.
2640 */
2641static void
2642ath_setdefantenna(struct ath_softc *sc, u_int antenna)
2643{
2644	struct ath_hal *ah = sc->sc_ah;
2645
2646	/* XXX block beacon interrupts */
2647	ath_hal_setdefantenna(ah, antenna);
2648	if (sc->sc_defant != antenna)
2649		sc->sc_stats.ast_ant_defswitch++;
2650	sc->sc_defant = antenna;
2651	sc->sc_rxotherant = 0;
2652}
2653
2654static int
2655ath_rx_tap(struct ath_softc *sc, struct mbuf *m,
2656	const struct ath_desc *ds, u_int64_t tsf, int16_t nf)
2657{
2658	u_int8_t rix;
2659
2660	KASSERT(sc->sc_drvbpf != NULL, ("no tap"));
2661
2662	/*
2663	 * Discard anything shorter than an ack or cts.
2664	 */
2665	if (m->m_pkthdr.len < IEEE80211_ACK_LEN) {
2666		DPRINTF(sc, ATH_DEBUG_RECV, "%s: runt packet %d\n",
2667			__func__, m->m_pkthdr.len);
2668		sc->sc_stats.ast_rx_tooshort++;
2669		return 0;
2670	}
2671	sc->sc_rx_th.wr_tsf = htole64(
2672		ath_extend_tsf(ds->ds_rxstat.rs_tstamp, tsf));
2673	rix = ds->ds_rxstat.rs_rate;
2674	sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
2675	if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
2676		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
2677	/* XXX propagate other error flags from descriptor */
2678	sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
2679	sc->sc_rx_th.wr_antsignal = ds->ds_rxstat.rs_rssi + nf;
2680	sc->sc_rx_th.wr_antnoise = nf;
2681	sc->sc_rx_th.wr_antenna = ds->ds_rxstat.rs_antenna;
2682
2683	bpf_mtap2(sc->sc_drvbpf, &sc->sc_rx_th, sc->sc_rx_th_len, m);
2684
2685	return 1;
2686}
2687
2688static void
2689ath_rx_proc(void *arg, int npending)
2690{
2691#define	PA2DESC(_sc, _pa) \
2692	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
2693		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
2694	struct ath_softc *sc = arg;
2695	struct ath_buf *bf;
2696	struct ieee80211com *ic = &sc->sc_ic;
2697	struct ifnet *ifp = sc->sc_ifp;
2698	struct ath_hal *ah = sc->sc_ah;
2699	struct ath_desc *ds;
2700	struct mbuf *m;
2701	struct ieee80211_node *ni;
2702	struct ath_node *an;
2703	int len, type;
2704	u_int phyerr;
2705	HAL_STATUS status;
2706	int16_t nf;
2707	u_int64_t tsf;
2708
2709	NET_LOCK_GIANT();		/* XXX */
2710
2711	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
2712	nf = ath_hal_getchannoise(ah, &sc->sc_curchan);
2713	tsf = ath_hal_gettsf64(ah);
2714	do {
2715		bf = STAILQ_FIRST(&sc->sc_rxbuf);
2716		if (bf == NULL) {		/* NB: shouldn't happen */
2717			if_printf(ifp, "%s: no buffer!\n", __func__);
2718			break;
2719		}
2720		ds = bf->bf_desc;
2721		if (ds->ds_link == bf->bf_daddr) {
2722			/* NB: never process the self-linked entry at the end */
2723			break;
2724		}
2725		m = bf->bf_m;
2726		if (m == NULL) {		/* NB: shouldn't happen */
2727			if_printf(ifp, "%s: no mbuf!\n", __func__);
2728			continue;
2729		}
2730		/* XXX sync descriptor memory */
2731		/*
2732		 * Must provide the virtual address of the current
2733		 * descriptor, the physical address, and the virtual
2734		 * address of the next descriptor in the h/w chain.
2735		 * This allows the HAL to look ahead to see if the
2736		 * hardware is done with a descriptor by checking the
2737		 * done bit in the following descriptor and the address
2738		 * of the current descriptor the DMA engine is working
2739		 * on.  All this is necessary because of our use of
2740		 * a self-linked list to avoid rx overruns.
2741		 */
2742		status = ath_hal_rxprocdesc(ah, ds,
2743				bf->bf_daddr, PA2DESC(sc, ds->ds_link));
2744#ifdef AR_DEBUG
2745		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
2746			ath_printrxbuf(bf, status == HAL_OK);
2747#endif
2748		if (status == HAL_EINPROGRESS)
2749			break;
2750		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
2751		if (ds->ds_rxstat.rs_more) {
2752			/*
2753			 * Frame spans multiple descriptors; this
2754			 * cannot happen yet as we don't support
2755			 * jumbograms.  If not in monitor mode,
2756			 * discard the frame.
2757			 */
2758			if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2759				sc->sc_stats.ast_rx_toobig++;
2760				goto rx_next;
2761			}
2762			/* fall thru for monitor mode handling... */
2763		} else if (ds->ds_rxstat.rs_status != 0) {
2764			if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
2765				sc->sc_stats.ast_rx_crcerr++;
2766			if (ds->ds_rxstat.rs_status & HAL_RXERR_FIFO)
2767				sc->sc_stats.ast_rx_fifoerr++;
2768			if (ds->ds_rxstat.rs_status & HAL_RXERR_PHY) {
2769				sc->sc_stats.ast_rx_phyerr++;
2770				phyerr = ds->ds_rxstat.rs_phyerr & 0x1f;
2771				sc->sc_stats.ast_rx_phy[phyerr]++;
2772				goto rx_next;
2773			}
2774			if (ds->ds_rxstat.rs_status & HAL_RXERR_DECRYPT) {
2775				/*
2776				 * Decrypt error.  If the error occurred
2777				 * because there was no hardware key, then
2778				 * let the frame through so the upper layers
2779				 * can process it.  This is necessary for 5210
2780				 * parts which have no way to setup a ``clear''
2781				 * key cache entry.
2782				 *
2783				 * XXX do key cache faulting
2784				 */
2785				if (ds->ds_rxstat.rs_keyix == HAL_RXKEYIX_INVALID)
2786					goto rx_accept;
2787				sc->sc_stats.ast_rx_badcrypt++;
2788			}
2789			if (ds->ds_rxstat.rs_status & HAL_RXERR_MIC) {
2790				sc->sc_stats.ast_rx_badmic++;
2791				/*
2792				 * Do minimal work required to hand off
2793				 * the 802.11 header for notifcation.
2794				 */
2795				/* XXX frag's and qos frames */
2796				len = ds->ds_rxstat.rs_datalen;
2797				if (len >= sizeof (struct ieee80211_frame)) {
2798					bus_dmamap_sync(sc->sc_dmat,
2799					    bf->bf_dmamap,
2800					    BUS_DMASYNC_POSTREAD);
2801					ieee80211_notify_michael_failure(ic,
2802					    mtod(m, struct ieee80211_frame *),
2803					    sc->sc_splitmic ?
2804					        ds->ds_rxstat.rs_keyix-32 :
2805					        ds->ds_rxstat.rs_keyix
2806					);
2807				}
2808			}
2809			ifp->if_ierrors++;
2810			/*
2811			 * When a tap is present pass error frames
2812			 * that have been requested.  By default we
2813			 * pass decrypt+mic errors but others may be
2814			 * interesting (e.g. crc).
2815			 */
2816			if (sc->sc_drvbpf != NULL &&
2817			    (ds->ds_rxstat.rs_status & sc->sc_monpass)) {
2818				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
2819				    BUS_DMASYNC_POSTREAD);
2820				/* NB: bpf needs the mbuf length setup */
2821				len = ds->ds_rxstat.rs_datalen;
2822				m->m_pkthdr.len = m->m_len = len;
2823				(void) ath_rx_tap(sc, m, ds, tsf, nf);
2824			}
2825			/* XXX pass MIC errors up for s/w reclaculation */
2826			goto rx_next;
2827		}
2828rx_accept:
2829		/*
2830		 * Sync and unmap the frame.  At this point we're
2831		 * committed to passing the mbuf somewhere so clear
2832		 * bf_m; this means a new sk_buff must be allocated
2833		 * when the rx descriptor is setup again to receive
2834		 * another frame.
2835		 */
2836		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
2837		    BUS_DMASYNC_POSTREAD);
2838		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2839		bf->bf_m = NULL;
2840
2841		m->m_pkthdr.rcvif = ifp;
2842		len = ds->ds_rxstat.rs_datalen;
2843		m->m_pkthdr.len = m->m_len = len;
2844
2845		sc->sc_stats.ast_ant_rx[ds->ds_rxstat.rs_antenna]++;
2846
2847		if (sc->sc_drvbpf != NULL && !ath_rx_tap(sc, m, ds, tsf, nf)) {
2848			m_freem(m);		/* XXX reclaim */
2849			goto rx_next;
2850		}
2851
2852		/*
2853		 * From this point on we assume the frame is at least
2854		 * as large as ieee80211_frame_min; verify that.
2855		 */
2856		if (len < IEEE80211_MIN_LEN) {
2857			DPRINTF(sc, ATH_DEBUG_RECV, "%s: short packet %d\n",
2858				__func__, len);
2859			sc->sc_stats.ast_rx_tooshort++;
2860			m_freem(m);
2861			goto rx_next;
2862		}
2863
2864		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
2865			ieee80211_dump_pkt(mtod(m, caddr_t), len,
2866				   sc->sc_hwmap[ds->ds_rxstat.rs_rate].ieeerate,
2867				   ds->ds_rxstat.rs_rssi);
2868		}
2869
2870		m_adj(m, -IEEE80211_CRC_LEN);
2871
2872		/*
2873		 * Locate the node for sender, track state, and then
2874		 * pass the (referenced) node up to the 802.11 layer
2875		 * for its use.
2876		 */
2877		ni = ieee80211_find_rxnode_withkey(ic,
2878			mtod(m, const struct ieee80211_frame_min *),
2879			ds->ds_rxstat.rs_keyix == HAL_RXKEYIX_INVALID ?
2880				IEEE80211_KEYIX_NONE : ds->ds_rxstat.rs_keyix);
2881		/*
2882		 * Track rx rssi and do any rx antenna management.
2883		 */
2884		an = ATH_NODE(ni);
2885		ATH_RSSI_LPF(an->an_avgrssi, ds->ds_rxstat.rs_rssi);
2886		ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, ds->ds_rxstat.rs_rssi);
2887		/*
2888		 * Send frame up for processing.
2889		 */
2890		type = ieee80211_input(ic, m, ni,
2891			ds->ds_rxstat.rs_rssi, ds->ds_rxstat.rs_tstamp);
2892		ieee80211_free_node(ni);
2893		if (sc->sc_diversity) {
2894			/*
2895			 * When using fast diversity, change the default rx
2896			 * antenna if diversity chooses the other antenna 3
2897			 * times in a row.
2898			 */
2899			if (sc->sc_defant != ds->ds_rxstat.rs_antenna) {
2900				if (++sc->sc_rxotherant >= 3)
2901					ath_setdefantenna(sc,
2902						ds->ds_rxstat.rs_antenna);
2903			} else
2904				sc->sc_rxotherant = 0;
2905		}
2906		if (sc->sc_softled) {
2907			/*
2908			 * Blink for any data frame.  Otherwise do a
2909			 * heartbeat-style blink when idle.  The latter
2910			 * is mainly for station mode where we depend on
2911			 * periodic beacon frames to trigger the poll event.
2912			 */
2913			if (type == IEEE80211_FC0_TYPE_DATA) {
2914				sc->sc_rxrate = ds->ds_rxstat.rs_rate;
2915				ath_led_event(sc, ATH_LED_RX);
2916			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
2917				ath_led_event(sc, ATH_LED_POLL);
2918		}
2919rx_next:
2920		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
2921	} while (ath_rxbuf_init(sc, bf) == 0);
2922
2923	/* rx signal state monitoring */
2924	ath_hal_rxmonitor(ah, &sc->sc_halstats);
2925
2926	NET_UNLOCK_GIANT();		/* XXX */
2927#undef PA2DESC
2928}
2929
2930/*
2931 * Setup a h/w transmit queue.
2932 */
2933static struct ath_txq *
2934ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
2935{
2936#define	N(a)	(sizeof(a)/sizeof(a[0]))
2937	struct ath_hal *ah = sc->sc_ah;
2938	HAL_TXQ_INFO qi;
2939	int qnum;
2940
2941	memset(&qi, 0, sizeof(qi));
2942	qi.tqi_subtype = subtype;
2943	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
2944	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
2945	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
2946	/*
2947	 * Enable interrupts only for EOL and DESC conditions.
2948	 * We mark tx descriptors to receive a DESC interrupt
2949	 * when a tx queue gets deep; otherwise waiting for the
2950	 * EOL to reap descriptors.  Note that this is done to
2951	 * reduce interrupt load and this only defers reaping
2952	 * descriptors, never transmitting frames.  Aside from
2953	 * reducing interrupts this also permits more concurrency.
2954	 * The only potential downside is if the tx queue backs
2955	 * up in which case the top half of the kernel may backup
2956	 * due to a lack of tx descriptors.
2957	 */
2958	qi.tqi_qflags = TXQ_FLAG_TXEOLINT_ENABLE | TXQ_FLAG_TXDESCINT_ENABLE;
2959	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
2960	if (qnum == -1) {
2961		/*
2962		 * NB: don't print a message, this happens
2963		 * normally on parts with too few tx queues
2964		 */
2965		return NULL;
2966	}
2967	if (qnum >= N(sc->sc_txq)) {
2968		device_printf(sc->sc_dev,
2969			"hal qnum %u out of range, max %zu!\n",
2970			qnum, N(sc->sc_txq));
2971		ath_hal_releasetxqueue(ah, qnum);
2972		return NULL;
2973	}
2974	if (!ATH_TXQ_SETUP(sc, qnum)) {
2975		struct ath_txq *txq = &sc->sc_txq[qnum];
2976
2977		txq->axq_qnum = qnum;
2978		txq->axq_depth = 0;
2979		txq->axq_intrcnt = 0;
2980		txq->axq_link = NULL;
2981		STAILQ_INIT(&txq->axq_q);
2982		ATH_TXQ_LOCK_INIT(sc, txq);
2983		sc->sc_txqsetup |= 1<<qnum;
2984	}
2985	return &sc->sc_txq[qnum];
2986#undef N
2987}
2988
2989/*
2990 * Setup a hardware data transmit queue for the specified
2991 * access control.  The hal may not support all requested
2992 * queues in which case it will return a reference to a
2993 * previously setup queue.  We record the mapping from ac's
2994 * to h/w queues for use by ath_tx_start and also track
2995 * the set of h/w queues being used to optimize work in the
2996 * transmit interrupt handler and related routines.
2997 */
2998static int
2999ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
3000{
3001#define	N(a)	(sizeof(a)/sizeof(a[0]))
3002	struct ath_txq *txq;
3003
3004	if (ac >= N(sc->sc_ac2q)) {
3005		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
3006			ac, N(sc->sc_ac2q));
3007		return 0;
3008	}
3009	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
3010	if (txq != NULL) {
3011		sc->sc_ac2q[ac] = txq;
3012		return 1;
3013	} else
3014		return 0;
3015#undef N
3016}
3017
3018/*
3019 * Update WME parameters for a transmit queue.
3020 */
3021static int
3022ath_txq_update(struct ath_softc *sc, int ac)
3023{
3024#define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
3025#define	ATH_TXOP_TO_US(v)		(v<<5)
3026	struct ieee80211com *ic = &sc->sc_ic;
3027	struct ath_txq *txq = sc->sc_ac2q[ac];
3028	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3029	struct ath_hal *ah = sc->sc_ah;
3030	HAL_TXQ_INFO qi;
3031
3032	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
3033	qi.tqi_aifs = wmep->wmep_aifsn;
3034	qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3035	qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
3036	qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
3037
3038	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
3039		device_printf(sc->sc_dev, "unable to update hardware queue "
3040			"parameters for %s traffic!\n",
3041			ieee80211_wme_acnames[ac]);
3042		return 0;
3043	} else {
3044		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
3045		return 1;
3046	}
3047#undef ATH_TXOP_TO_US
3048#undef ATH_EXPONENT_TO_VALUE
3049}
3050
3051/*
3052 * Callback from the 802.11 layer to update WME parameters.
3053 */
3054static int
3055ath_wme_update(struct ieee80211com *ic)
3056{
3057	struct ath_softc *sc = ic->ic_ifp->if_softc;
3058
3059	return !ath_txq_update(sc, WME_AC_BE) ||
3060	    !ath_txq_update(sc, WME_AC_BK) ||
3061	    !ath_txq_update(sc, WME_AC_VI) ||
3062	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
3063}
3064
3065/*
3066 * Reclaim resources for a setup queue.
3067 */
3068static void
3069ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
3070{
3071
3072	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
3073	ATH_TXQ_LOCK_DESTROY(txq);
3074	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
3075}
3076
3077/*
3078 * Reclaim all tx queue resources.
3079 */
3080static void
3081ath_tx_cleanup(struct ath_softc *sc)
3082{
3083	int i;
3084
3085	ATH_TXBUF_LOCK_DESTROY(sc);
3086	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3087		if (ATH_TXQ_SETUP(sc, i))
3088			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
3089}
3090
3091/*
3092 * Defragment an mbuf chain, returning at most maxfrags separate
3093 * mbufs+clusters.  If this is not possible NULL is returned and
3094 * the original mbuf chain is left in it's present (potentially
3095 * modified) state.  We use two techniques: collapsing consecutive
3096 * mbufs and replacing consecutive mbufs by a cluster.
3097 */
3098static struct mbuf *
3099ath_defrag(struct mbuf *m0, int how, int maxfrags)
3100{
3101	struct mbuf *m, *n, *n2, **prev;
3102	u_int curfrags;
3103
3104	/*
3105	 * Calculate the current number of frags.
3106	 */
3107	curfrags = 0;
3108	for (m = m0; m != NULL; m = m->m_next)
3109		curfrags++;
3110	/*
3111	 * First, try to collapse mbufs.  Note that we always collapse
3112	 * towards the front so we don't need to deal with moving the
3113	 * pkthdr.  This may be suboptimal if the first mbuf has much
3114	 * less data than the following.
3115	 */
3116	m = m0;
3117again:
3118	for (;;) {
3119		n = m->m_next;
3120		if (n == NULL)
3121			break;
3122		if ((m->m_flags & M_RDONLY) == 0 &&
3123		    n->m_len < M_TRAILINGSPACE(m)) {
3124			bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
3125				n->m_len);
3126			m->m_len += n->m_len;
3127			m->m_next = n->m_next;
3128			m_free(n);
3129			if (--curfrags <= maxfrags)
3130				return m0;
3131		} else
3132			m = n;
3133	}
3134	KASSERT(maxfrags > 1,
3135		("maxfrags %u, but normal collapse failed", maxfrags));
3136	/*
3137	 * Collapse consecutive mbufs to a cluster.
3138	 */
3139	prev = &m0->m_next;		/* NB: not the first mbuf */
3140	while ((n = *prev) != NULL) {
3141		if ((n2 = n->m_next) != NULL &&
3142		    n->m_len + n2->m_len < MCLBYTES) {
3143			m = m_getcl(how, MT_DATA, 0);
3144			if (m == NULL)
3145				goto bad;
3146			bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
3147			bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
3148				n2->m_len);
3149			m->m_len = n->m_len + n2->m_len;
3150			m->m_next = n2->m_next;
3151			*prev = m;
3152			m_free(n);
3153			m_free(n2);
3154			if (--curfrags <= maxfrags)	/* +1 cl -2 mbufs */
3155				return m0;
3156			/*
3157			 * Still not there, try the normal collapse
3158			 * again before we allocate another cluster.
3159			 */
3160			goto again;
3161		}
3162		prev = &n->m_next;
3163	}
3164	/*
3165	 * No place where we can collapse to a cluster; punt.
3166	 * This can occur if, for example, you request 2 frags
3167	 * but the packet requires that both be clusters (we
3168	 * never reallocate the first mbuf to avoid moving the
3169	 * packet header).
3170	 */
3171bad:
3172	return NULL;
3173}
3174
3175/*
3176 * Return h/w rate index for an IEEE rate (w/o basic rate bit).
3177 */
3178static int
3179ath_tx_findrix(const HAL_RATE_TABLE *rt, int rate)
3180{
3181	int i;
3182
3183	for (i = 0; i < rt->rateCount; i++)
3184		if ((rt->info[i].dot11Rate & IEEE80211_RATE_VAL) == rate)
3185			return i;
3186	return 0;		/* NB: lowest rate */
3187}
3188
3189static int
3190ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
3191    struct mbuf *m0)
3192{
3193	struct ieee80211com *ic = &sc->sc_ic;
3194	struct ath_hal *ah = sc->sc_ah;
3195	struct ifnet *ifp = sc->sc_ifp;
3196	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
3197	int i, error, iswep, ismcast, ismrr;
3198	int keyix, hdrlen, pktlen, try0;
3199	u_int8_t rix, txrate, ctsrate;
3200	u_int8_t cix = 0xff;		/* NB: silence compiler */
3201	struct ath_desc *ds, *ds0;
3202	struct ath_txq *txq;
3203	struct ieee80211_frame *wh;
3204	u_int subtype, flags, ctsduration;
3205	HAL_PKT_TYPE atype;
3206	const HAL_RATE_TABLE *rt;
3207	HAL_BOOL shortPreamble;
3208	struct ath_node *an;
3209	struct mbuf *m;
3210	u_int pri;
3211
3212	wh = mtod(m0, struct ieee80211_frame *);
3213	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
3214	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
3215	hdrlen = ieee80211_anyhdrsize(wh);
3216	/*
3217	 * Packet length must not include any
3218	 * pad bytes; deduct them here.
3219	 */
3220	pktlen = m0->m_pkthdr.len - (hdrlen & 3);
3221
3222	if (iswep) {
3223		const struct ieee80211_cipher *cip;
3224		struct ieee80211_key *k;
3225
3226		/*
3227		 * Construct the 802.11 header+trailer for an encrypted
3228		 * frame. The only reason this can fail is because of an
3229		 * unknown or unsupported cipher/key type.
3230		 */
3231		k = ieee80211_crypto_encap(ic, ni, m0);
3232		if (k == NULL) {
3233			/*
3234			 * This can happen when the key is yanked after the
3235			 * frame was queued.  Just discard the frame; the
3236			 * 802.11 layer counts failures and provides
3237			 * debugging/diagnostics.
3238			 */
3239			m_freem(m0);
3240			return EIO;
3241		}
3242		/*
3243		 * Adjust the packet + header lengths for the crypto
3244		 * additions and calculate the h/w key index.  When
3245		 * a s/w mic is done the frame will have had any mic
3246		 * added to it prior to entry so skb->len above will
3247		 * account for it. Otherwise we need to add it to the
3248		 * packet length.
3249		 */
3250		cip = k->wk_cipher;
3251		hdrlen += cip->ic_header;
3252		pktlen += cip->ic_header + cip->ic_trailer;
3253		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0)
3254			pktlen += cip->ic_miclen;
3255		keyix = k->wk_keyix;
3256
3257		/* packet header may have moved, reset our local pointer */
3258		wh = mtod(m0, struct ieee80211_frame *);
3259	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
3260		/*
3261		 * Use station key cache slot, if assigned.
3262		 */
3263		keyix = ni->ni_ucastkey.wk_keyix;
3264		if (keyix == IEEE80211_KEYIX_NONE)
3265			keyix = HAL_TXKEYIX_INVALID;
3266	} else
3267		keyix = HAL_TXKEYIX_INVALID;
3268
3269	pktlen += IEEE80211_CRC_LEN;
3270
3271	/*
3272	 * Load the DMA map so any coalescing is done.  This
3273	 * also calculates the number of descriptors we need.
3274	 */
3275	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3276				     bf->bf_segs, &bf->bf_nseg,
3277				     BUS_DMA_NOWAIT);
3278	if (error == EFBIG) {
3279		/* XXX packet requires too many descriptors */
3280		bf->bf_nseg = ATH_TXDESC+1;
3281	} else if (error != 0) {
3282		sc->sc_stats.ast_tx_busdma++;
3283		m_freem(m0);
3284		return error;
3285	}
3286	/*
3287	 * Discard null packets and check for packets that
3288	 * require too many TX descriptors.  We try to convert
3289	 * the latter to a cluster.
3290	 */
3291	if (bf->bf_nseg > ATH_TXDESC) {		/* too many desc's, linearize */
3292		sc->sc_stats.ast_tx_linear++;
3293		m = ath_defrag(m0, M_DONTWAIT, ATH_TXDESC);
3294		if (m == NULL) {
3295			m_freem(m0);
3296			sc->sc_stats.ast_tx_nombuf++;
3297			return ENOMEM;
3298		}
3299		m0 = m;
3300		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3301					     bf->bf_segs, &bf->bf_nseg,
3302					     BUS_DMA_NOWAIT);
3303		if (error != 0) {
3304			sc->sc_stats.ast_tx_busdma++;
3305			m_freem(m0);
3306			return error;
3307		}
3308		KASSERT(bf->bf_nseg <= ATH_TXDESC,
3309		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
3310	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
3311		sc->sc_stats.ast_tx_nodata++;
3312		m_freem(m0);
3313		return EIO;
3314	}
3315	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n", __func__, m0, pktlen);
3316	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3317	bf->bf_m = m0;
3318	bf->bf_node = ni;			/* NB: held reference */
3319
3320	/* setup descriptors */
3321	ds = bf->bf_desc;
3322	rt = sc->sc_currates;
3323	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3324
3325	/*
3326	 * NB: the 802.11 layer marks whether or not we should
3327	 * use short preamble based on the current mode and
3328	 * negotiated parameters.
3329	 */
3330	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
3331	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
3332		shortPreamble = AH_TRUE;
3333		sc->sc_stats.ast_tx_shortpre++;
3334	} else {
3335		shortPreamble = AH_FALSE;
3336	}
3337
3338	an = ATH_NODE(ni);
3339	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
3340	ismrr = 0;				/* default no multi-rate retry*/
3341	/*
3342	 * Calculate Atheros packet type from IEEE80211 packet header,
3343	 * setup for rate calculations, and select h/w transmit queue.
3344	 */
3345	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
3346	case IEEE80211_FC0_TYPE_MGT:
3347		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3348		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
3349			atype = HAL_PKT_TYPE_BEACON;
3350		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
3351			atype = HAL_PKT_TYPE_PROBE_RESP;
3352		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
3353			atype = HAL_PKT_TYPE_ATIM;
3354		else
3355			atype = HAL_PKT_TYPE_NORMAL;	/* XXX */
3356		rix = sc->sc_minrateix;
3357		txrate = rt->info[rix].rateCode;
3358		if (shortPreamble)
3359			txrate |= rt->info[rix].shortPreamble;
3360		try0 = ATH_TXMGTTRY;
3361		/* NB: force all management frames to highest queue */
3362		if (ni->ni_flags & IEEE80211_NODE_QOS) {
3363			/* NB: force all management frames to highest queue */
3364			pri = WME_AC_VO;
3365		} else
3366			pri = WME_AC_BE;
3367		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
3368		break;
3369	case IEEE80211_FC0_TYPE_CTL:
3370		atype = HAL_PKT_TYPE_PSPOLL;	/* stop setting of duration */
3371		rix = sc->sc_minrateix;
3372		txrate = rt->info[rix].rateCode;
3373		if (shortPreamble)
3374			txrate |= rt->info[rix].shortPreamble;
3375		try0 = ATH_TXMGTTRY;
3376		/* NB: force all ctl frames to highest queue */
3377		if (ni->ni_flags & IEEE80211_NODE_QOS) {
3378			/* NB: force all ctl frames to highest queue */
3379			pri = WME_AC_VO;
3380		} else
3381			pri = WME_AC_BE;
3382		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
3383		break;
3384	case IEEE80211_FC0_TYPE_DATA:
3385		atype = HAL_PKT_TYPE_NORMAL;		/* default */
3386		/*
3387		 * Data frames: multicast frames go out at a fixed rate,
3388		 * otherwise consult the rate control module for the
3389		 * rate to use.
3390		 */
3391		if (ismcast) {
3392			/*
3393			 * Check mcast rate setting in case it's changed.
3394			 * XXX move out of fastpath
3395			 */
3396			if (ic->ic_mcast_rate != sc->sc_mcastrate) {
3397				sc->sc_mcastrix =
3398					ath_tx_findrix(rt, ic->ic_mcast_rate);
3399				sc->sc_mcastrate = ic->ic_mcast_rate;
3400			}
3401			rix = sc->sc_mcastrix;
3402			txrate = rt->info[rix].rateCode;
3403			if (shortPreamble)
3404				txrate |= rt->info[rix].shortPreamble;
3405			try0 = 1;
3406		} else {
3407			ath_rate_findrate(sc, an, shortPreamble, pktlen,
3408				&rix, &try0, &txrate);
3409			sc->sc_txrate = txrate;		/* for LED blinking */
3410			if (try0 != ATH_TXMAXTRY)
3411				ismrr = 1;
3412		}
3413		/*
3414		 * Default all non-QoS traffic to the background queue.
3415		 */
3416		if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
3417			pri = M_WME_GETAC(m0);
3418			if (cap->cap_wmeParams[pri].wmep_noackPolicy) {
3419				flags |= HAL_TXDESC_NOACK;
3420				sc->sc_stats.ast_tx_noack++;
3421			}
3422		} else
3423			pri = WME_AC_BE;
3424		break;
3425	default:
3426		if_printf(ifp, "bogus frame type 0x%x (%s)\n",
3427			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
3428		/* XXX statistic */
3429		m_freem(m0);
3430		return EIO;
3431	}
3432	txq = sc->sc_ac2q[pri];
3433
3434	/*
3435	 * When servicing one or more stations in power-save mode
3436	 * multicast frames must be buffered until after the beacon.
3437	 * We use the CAB queue for that.
3438	 */
3439	if (ismcast && ic->ic_ps_sta) {
3440		txq = sc->sc_cabq;
3441		/* XXX? more bit in 802.11 frame header */
3442	}
3443
3444	/*
3445	 * Calculate miscellaneous flags.
3446	 */
3447	if (ismcast) {
3448		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
3449		sc->sc_stats.ast_tx_noack++;
3450	} else if (pktlen > ic->ic_rtsthreshold) {
3451		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
3452		cix = rt->info[rix].controlRate;
3453		sc->sc_stats.ast_tx_rts++;
3454	}
3455
3456	/*
3457	 * If 802.11g protection is enabled, determine whether
3458	 * to use RTS/CTS or just CTS.  Note that this is only
3459	 * done for OFDM unicast frames.
3460	 */
3461	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
3462	    rt->info[rix].phy == IEEE80211_T_OFDM &&
3463	    (flags & HAL_TXDESC_NOACK) == 0) {
3464		/* XXX fragments must use CCK rates w/ protection */
3465		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
3466			flags |= HAL_TXDESC_RTSENA;
3467		else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
3468			flags |= HAL_TXDESC_CTSENA;
3469		cix = rt->info[sc->sc_protrix].controlRate;
3470		sc->sc_stats.ast_tx_protect++;
3471	}
3472
3473	/*
3474	 * Calculate duration.  This logically belongs in the 802.11
3475	 * layer but it lacks sufficient information to calculate it.
3476	 */
3477	if ((flags & HAL_TXDESC_NOACK) == 0 &&
3478	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
3479		u_int16_t dur;
3480		/*
3481		 * XXX not right with fragmentation.
3482		 */
3483		if (shortPreamble)
3484			dur = rt->info[rix].spAckDuration;
3485		else
3486			dur = rt->info[rix].lpAckDuration;
3487		*(u_int16_t *)wh->i_dur = htole16(dur);
3488	}
3489
3490	/*
3491	 * Calculate RTS/CTS rate and duration if needed.
3492	 */
3493	ctsduration = 0;
3494	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
3495		/*
3496		 * CTS transmit rate is derived from the transmit rate
3497		 * by looking in the h/w rate table.  We must also factor
3498		 * in whether or not a short preamble is to be used.
3499		 */
3500		/* NB: cix is set above where RTS/CTS is enabled */
3501		KASSERT(cix != 0xff, ("cix not setup"));
3502		ctsrate = rt->info[cix].rateCode;
3503		/*
3504		 * Compute the transmit duration based on the frame
3505		 * size and the size of an ACK frame.  We call into the
3506		 * HAL to do the computation since it depends on the
3507		 * characteristics of the actual PHY being used.
3508		 *
3509		 * NB: CTS is assumed the same size as an ACK so we can
3510		 *     use the precalculated ACK durations.
3511		 */
3512		if (shortPreamble) {
3513			ctsrate |= rt->info[cix].shortPreamble;
3514			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
3515				ctsduration += rt->info[cix].spAckDuration;
3516			ctsduration += ath_hal_computetxtime(ah,
3517				rt, pktlen, rix, AH_TRUE);
3518			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
3519				ctsduration += rt->info[rix].spAckDuration;
3520		} else {
3521			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
3522				ctsduration += rt->info[cix].lpAckDuration;
3523			ctsduration += ath_hal_computetxtime(ah,
3524				rt, pktlen, rix, AH_FALSE);
3525			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
3526				ctsduration += rt->info[rix].lpAckDuration;
3527		}
3528		/*
3529		 * Must disable multi-rate retry when using RTS/CTS.
3530		 */
3531		ismrr = 0;
3532		try0 = ATH_TXMGTTRY;		/* XXX */
3533	} else
3534		ctsrate = 0;
3535
3536	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
3537		ieee80211_dump_pkt(mtod(m0, caddr_t), m0->m_len,
3538			sc->sc_hwmap[txrate].ieeerate, -1);
3539
3540	if (ic->ic_rawbpf)
3541		bpf_mtap(ic->ic_rawbpf, m0);
3542	if (sc->sc_drvbpf) {
3543		u_int64_t tsf = ath_hal_gettsf64(ah);
3544
3545		sc->sc_tx_th.wt_tsf = htole64(tsf);
3546		sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
3547		if (iswep)
3548			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3549		sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
3550		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
3551		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
3552
3553		bpf_mtap2(sc->sc_drvbpf,
3554			&sc->sc_tx_th, sc->sc_tx_th_len, m0);
3555	}
3556
3557	/*
3558	 * Determine if a tx interrupt should be generated for
3559	 * this descriptor.  We take a tx interrupt to reap
3560	 * descriptors when the h/w hits an EOL condition or
3561	 * when the descriptor is specifically marked to generate
3562	 * an interrupt.  We periodically mark descriptors in this
3563	 * way to insure timely replenishing of the supply needed
3564	 * for sending frames.  Defering interrupts reduces system
3565	 * load and potentially allows more concurrent work to be
3566	 * done but if done to aggressively can cause senders to
3567	 * backup.
3568	 *
3569	 * NB: use >= to deal with sc_txintrperiod changing
3570	 *     dynamically through sysctl.
3571	 */
3572	if (flags & HAL_TXDESC_INTREQ) {
3573		txq->axq_intrcnt = 0;
3574	} else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
3575		flags |= HAL_TXDESC_INTREQ;
3576		txq->axq_intrcnt = 0;
3577	}
3578
3579	/*
3580	 * Formulate first tx descriptor with tx controls.
3581	 */
3582	/* XXX check return value? */
3583	ath_hal_setuptxdesc(ah, ds
3584		, pktlen		/* packet length */
3585		, hdrlen		/* header length */
3586		, atype			/* Atheros packet type */
3587		, ni->ni_txpower	/* txpower */
3588		, txrate, try0		/* series 0 rate/tries */
3589		, keyix			/* key cache index */
3590		, sc->sc_txantenna	/* antenna mode */
3591		, flags			/* flags */
3592		, ctsrate		/* rts/cts rate */
3593		, ctsduration		/* rts/cts duration */
3594	);
3595	bf->bf_flags = flags;
3596	/*
3597	 * Setup the multi-rate retry state only when we're
3598	 * going to use it.  This assumes ath_hal_setuptxdesc
3599	 * initializes the descriptors (so we don't have to)
3600	 * when the hardware supports multi-rate retry and
3601	 * we don't use it.
3602	 */
3603	if (ismrr)
3604		ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
3605
3606	/*
3607	 * Fillin the remainder of the descriptor info.
3608	 */
3609	ds0 = ds;
3610	for (i = 0; i < bf->bf_nseg; i++, ds++) {
3611		ds->ds_data = bf->bf_segs[i].ds_addr;
3612		if (i == bf->bf_nseg - 1)
3613			ds->ds_link = 0;
3614		else
3615			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
3616		ath_hal_filltxdesc(ah, ds
3617			, bf->bf_segs[i].ds_len	/* segment length */
3618			, i == 0		/* first segment */
3619			, i == bf->bf_nseg - 1	/* last segment */
3620			, ds0			/* first descriptor */
3621		);
3622		DPRINTF(sc, ATH_DEBUG_XMIT,
3623			"%s: %d: %08x %08x %08x %08x %08x %08x\n",
3624			__func__, i, ds->ds_link, ds->ds_data,
3625			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
3626	}
3627	/*
3628	 * Insert the frame on the outbound list and
3629	 * pass it on to the hardware.
3630	 */
3631	ATH_TXQ_LOCK(txq);
3632	ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
3633	if (txq->axq_link == NULL) {
3634		ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
3635		DPRINTF(sc, ATH_DEBUG_XMIT,
3636			"%s: TXDP[%u] = %p (%p) depth %d\n", __func__,
3637			txq->axq_qnum, (caddr_t)bf->bf_daddr, bf->bf_desc,
3638			txq->axq_depth);
3639	} else {
3640		*txq->axq_link = bf->bf_daddr;
3641		DPRINTF(sc, ATH_DEBUG_XMIT,
3642			"%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
3643			txq->axq_qnum, txq->axq_link,
3644			(caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
3645	}
3646	txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
3647	/*
3648	 * The CAB queue is started from the SWBA handler since
3649	 * frames only go out on DTIM and to avoid possible races.
3650	 */
3651	if (txq != sc->sc_cabq)
3652		ath_hal_txstart(ah, txq->axq_qnum);
3653	ATH_TXQ_UNLOCK(txq);
3654
3655	return 0;
3656}
3657
3658/*
3659 * Process completed xmit descriptors from the specified queue.
3660 */
3661static void
3662ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
3663{
3664	struct ath_hal *ah = sc->sc_ah;
3665	struct ieee80211com *ic = &sc->sc_ic;
3666	struct ath_buf *bf;
3667	struct ath_desc *ds, *ds0;
3668	struct ieee80211_node *ni;
3669	struct ath_node *an;
3670	int sr, lr, pri;
3671	HAL_STATUS status;
3672
3673	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
3674		__func__, txq->axq_qnum,
3675		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
3676		txq->axq_link);
3677	for (;;) {
3678		ATH_TXQ_LOCK(txq);
3679		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
3680		bf = STAILQ_FIRST(&txq->axq_q);
3681		if (bf == NULL) {
3682			txq->axq_link = NULL;
3683			ATH_TXQ_UNLOCK(txq);
3684			break;
3685		}
3686		ds0 = &bf->bf_desc[0];
3687		ds = &bf->bf_desc[bf->bf_nseg - 1];
3688		status = ath_hal_txprocdesc(ah, ds);
3689#ifdef AR_DEBUG
3690		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
3691			ath_printtxbuf(bf, status == HAL_OK);
3692#endif
3693		if (status == HAL_EINPROGRESS) {
3694			ATH_TXQ_UNLOCK(txq);
3695			break;
3696		}
3697		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
3698		ATH_TXQ_UNLOCK(txq);
3699
3700		ni = bf->bf_node;
3701		if (ni != NULL) {
3702			an = ATH_NODE(ni);
3703			if (ds->ds_txstat.ts_status == 0) {
3704				u_int8_t txant = ds->ds_txstat.ts_antenna;
3705				sc->sc_stats.ast_ant_tx[txant]++;
3706				sc->sc_ant_tx[txant]++;
3707				if (ds->ds_txstat.ts_rate & HAL_TXSTAT_ALTRATE)
3708					sc->sc_stats.ast_tx_altrate++;
3709				sc->sc_stats.ast_tx_rssi =
3710					ds->ds_txstat.ts_rssi;
3711				ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
3712					ds->ds_txstat.ts_rssi);
3713				pri = M_WME_GETAC(bf->bf_m);
3714				if (pri >= WME_AC_VO)
3715					ic->ic_wme.wme_hipri_traffic++;
3716				ni->ni_inact = ni->ni_inact_reload;
3717			} else {
3718				if (ds->ds_txstat.ts_status & HAL_TXERR_XRETRY)
3719					sc->sc_stats.ast_tx_xretries++;
3720				if (ds->ds_txstat.ts_status & HAL_TXERR_FIFO)
3721					sc->sc_stats.ast_tx_fifoerr++;
3722				if (ds->ds_txstat.ts_status & HAL_TXERR_FILT)
3723					sc->sc_stats.ast_tx_filtered++;
3724			}
3725			sr = ds->ds_txstat.ts_shortretry;
3726			lr = ds->ds_txstat.ts_longretry;
3727			sc->sc_stats.ast_tx_shortretry += sr;
3728			sc->sc_stats.ast_tx_longretry += lr;
3729			/*
3730			 * Hand the descriptor to the rate control algorithm.
3731			 */
3732			if ((ds->ds_txstat.ts_status & HAL_TXERR_FILT) == 0 &&
3733			    (bf->bf_flags & HAL_TXDESC_NOACK) == 0)
3734				ath_rate_tx_complete(sc, an, ds, ds0);
3735			/*
3736			 * Reclaim reference to node.
3737			 *
3738			 * NB: the node may be reclaimed here if, for example
3739			 *     this is a DEAUTH message that was sent and the
3740			 *     node was timed out due to inactivity.
3741			 */
3742			ieee80211_free_node(ni);
3743		}
3744		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3745		    BUS_DMASYNC_POSTWRITE);
3746		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3747		m_freem(bf->bf_m);
3748		bf->bf_m = NULL;
3749		bf->bf_node = NULL;
3750
3751		ATH_TXBUF_LOCK(sc);
3752		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
3753		ATH_TXBUF_UNLOCK(sc);
3754	}
3755}
3756
3757/*
3758 * Deferred processing of transmit interrupt; special-cased
3759 * for a single hardware transmit queue (e.g. 5210 and 5211).
3760 */
3761static void
3762ath_tx_proc_q0(void *arg, int npending)
3763{
3764	struct ath_softc *sc = arg;
3765	struct ifnet *ifp = sc->sc_ifp;
3766
3767	ath_tx_processq(sc, &sc->sc_txq[0]);
3768	ath_tx_processq(sc, sc->sc_cabq);
3769	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3770	sc->sc_tx_timer = 0;
3771
3772	if (sc->sc_softled)
3773		ath_led_event(sc, ATH_LED_TX);
3774
3775	ath_start(ifp);
3776}
3777
3778/*
3779 * Deferred processing of transmit interrupt; special-cased
3780 * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
3781 */
3782static void
3783ath_tx_proc_q0123(void *arg, int npending)
3784{
3785	struct ath_softc *sc = arg;
3786	struct ifnet *ifp = sc->sc_ifp;
3787
3788	/*
3789	 * Process each active queue.
3790	 */
3791	ath_tx_processq(sc, &sc->sc_txq[0]);
3792	ath_tx_processq(sc, &sc->sc_txq[1]);
3793	ath_tx_processq(sc, &sc->sc_txq[2]);
3794	ath_tx_processq(sc, &sc->sc_txq[3]);
3795	ath_tx_processq(sc, sc->sc_cabq);
3796
3797	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3798	sc->sc_tx_timer = 0;
3799
3800	if (sc->sc_softled)
3801		ath_led_event(sc, ATH_LED_TX);
3802
3803	ath_start(ifp);
3804}
3805
3806/*
3807 * Deferred processing of transmit interrupt.
3808 */
3809static void
3810ath_tx_proc(void *arg, int npending)
3811{
3812	struct ath_softc *sc = arg;
3813	struct ifnet *ifp = sc->sc_ifp;
3814	int i;
3815
3816	/*
3817	 * Process each active queue.
3818	 */
3819	/* XXX faster to read ISR_S0_S and ISR_S1_S to determine q's? */
3820	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3821		if (ATH_TXQ_SETUP(sc, i))
3822			ath_tx_processq(sc, &sc->sc_txq[i]);
3823
3824	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3825	sc->sc_tx_timer = 0;
3826
3827	if (sc->sc_softled)
3828		ath_led_event(sc, ATH_LED_TX);
3829
3830	ath_start(ifp);
3831}
3832
3833static void
3834ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
3835{
3836	struct ath_hal *ah = sc->sc_ah;
3837	struct ieee80211_node *ni;
3838	struct ath_buf *bf;
3839
3840	/*
3841	 * NB: this assumes output has been stopped and
3842	 *     we do not need to block ath_tx_tasklet
3843	 */
3844	for (;;) {
3845		ATH_TXQ_LOCK(txq);
3846		bf = STAILQ_FIRST(&txq->axq_q);
3847		if (bf == NULL) {
3848			txq->axq_link = NULL;
3849			ATH_TXQ_UNLOCK(txq);
3850			break;
3851		}
3852		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
3853		ATH_TXQ_UNLOCK(txq);
3854#ifdef AR_DEBUG
3855		if (sc->sc_debug & ATH_DEBUG_RESET)
3856			ath_printtxbuf(bf,
3857				ath_hal_txprocdesc(ah, bf->bf_desc) == HAL_OK);
3858#endif /* AR_DEBUG */
3859		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3860		m_freem(bf->bf_m);
3861		bf->bf_m = NULL;
3862		ni = bf->bf_node;
3863		bf->bf_node = NULL;
3864		if (ni != NULL) {
3865			/*
3866			 * Reclaim node reference.
3867			 */
3868			ieee80211_free_node(ni);
3869		}
3870		ATH_TXBUF_LOCK(sc);
3871		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
3872		ATH_TXBUF_UNLOCK(sc);
3873	}
3874}
3875
3876static void
3877ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
3878{
3879	struct ath_hal *ah = sc->sc_ah;
3880
3881	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
3882	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
3883	    __func__, txq->axq_qnum,
3884	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
3885	    txq->axq_link);
3886}
3887
3888/*
3889 * Drain the transmit queues and reclaim resources.
3890 */
3891static void
3892ath_draintxq(struct ath_softc *sc)
3893{
3894	struct ath_hal *ah = sc->sc_ah;
3895	struct ifnet *ifp = sc->sc_ifp;
3896	int i;
3897
3898	/* XXX return value */
3899	if (!sc->sc_invalid) {
3900		/* don't touch the hardware if marked invalid */
3901		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
3902		DPRINTF(sc, ATH_DEBUG_RESET,
3903		    "%s: beacon queue %p\n", __func__,
3904		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq));
3905		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3906			if (ATH_TXQ_SETUP(sc, i))
3907				ath_tx_stopdma(sc, &sc->sc_txq[i]);
3908	}
3909	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3910		if (ATH_TXQ_SETUP(sc, i))
3911			ath_tx_draintxq(sc, &sc->sc_txq[i]);
3912	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3913	sc->sc_tx_timer = 0;
3914}
3915
3916/*
3917 * Disable the receive h/w in preparation for a reset.
3918 */
3919static void
3920ath_stoprecv(struct ath_softc *sc)
3921{
3922#define	PA2DESC(_sc, _pa) \
3923	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
3924		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
3925	struct ath_hal *ah = sc->sc_ah;
3926
3927	ath_hal_stoppcurecv(ah);	/* disable PCU */
3928	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
3929	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
3930	DELAY(3000);			/* 3ms is long enough for 1 frame */
3931#ifdef AR_DEBUG
3932	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
3933		struct ath_buf *bf;
3934
3935		printf("%s: rx queue %p, link %p\n", __func__,
3936			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
3937		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
3938			struct ath_desc *ds = bf->bf_desc;
3939			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
3940				bf->bf_daddr, PA2DESC(sc, ds->ds_link));
3941			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
3942				ath_printrxbuf(bf, status == HAL_OK);
3943		}
3944	}
3945#endif
3946	sc->sc_rxlink = NULL;		/* just in case */
3947#undef PA2DESC
3948}
3949
3950/*
3951 * Enable the receive h/w following a reset.
3952 */
3953static int
3954ath_startrecv(struct ath_softc *sc)
3955{
3956	struct ath_hal *ah = sc->sc_ah;
3957	struct ath_buf *bf;
3958
3959	sc->sc_rxlink = NULL;
3960	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
3961		int error = ath_rxbuf_init(sc, bf);
3962		if (error != 0) {
3963			DPRINTF(sc, ATH_DEBUG_RECV,
3964				"%s: ath_rxbuf_init failed %d\n",
3965				__func__, error);
3966			return error;
3967		}
3968	}
3969
3970	bf = STAILQ_FIRST(&sc->sc_rxbuf);
3971	ath_hal_putrxbuf(ah, bf->bf_daddr);
3972	ath_hal_rxena(ah);		/* enable recv descriptors */
3973	ath_mode_init(sc);		/* set filters, etc. */
3974	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
3975	return 0;
3976}
3977
3978/*
3979 * Update internal state after a channel change.
3980 */
3981static void
3982ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
3983{
3984	struct ieee80211com *ic = &sc->sc_ic;
3985	enum ieee80211_phymode mode;
3986	u_int16_t flags;
3987
3988	/*
3989	 * Change channels and update the h/w rate map
3990	 * if we're switching; e.g. 11a to 11b/g.
3991	 */
3992	mode = ieee80211_chan2mode(ic, chan);
3993	if (mode != sc->sc_curmode)
3994		ath_setcurmode(sc, mode);
3995	/*
3996	 * Update BPF state.  NB: ethereal et. al. don't handle
3997	 * merged flags well so pick a unique mode for their use.
3998	 */
3999	if (IEEE80211_IS_CHAN_A(chan))
4000		flags = IEEE80211_CHAN_A;
4001	/* XXX 11g schizophrenia */
4002	else if (IEEE80211_IS_CHAN_G(chan) ||
4003	    IEEE80211_IS_CHAN_PUREG(chan))
4004		flags = IEEE80211_CHAN_G;
4005	else
4006		flags = IEEE80211_CHAN_B;
4007	if (IEEE80211_IS_CHAN_T(chan))
4008		flags |= IEEE80211_CHAN_TURBO;
4009	sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
4010		htole16(chan->ic_freq);
4011	sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
4012		htole16(flags);
4013}
4014
4015/*
4016 * Set/change channels.  If the channel is really being changed,
4017 * it's done by reseting the chip.  To accomplish this we must
4018 * first cleanup any pending DMA, then restart stuff after a la
4019 * ath_init.
4020 */
4021static int
4022ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
4023{
4024	struct ath_hal *ah = sc->sc_ah;
4025	struct ieee80211com *ic = &sc->sc_ic;
4026	HAL_CHANNEL hchan;
4027
4028	/*
4029	 * Convert to a HAL channel description with
4030	 * the flags constrained to reflect the current
4031	 * operating mode.
4032	 */
4033	hchan.channel = chan->ic_freq;
4034	hchan.channelFlags = ath_chan2flags(ic, chan);
4035
4036	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz) -> %u (%u MHz)\n",
4037	    __func__,
4038	    ath_hal_mhz2ieee(sc->sc_curchan.channel,
4039		sc->sc_curchan.channelFlags),
4040	    	sc->sc_curchan.channel,
4041	    ath_hal_mhz2ieee(hchan.channel, hchan.channelFlags), hchan.channel);
4042	if (hchan.channel != sc->sc_curchan.channel ||
4043	    hchan.channelFlags != sc->sc_curchan.channelFlags) {
4044		HAL_STATUS status;
4045
4046		/*
4047		 * To switch channels clear any pending DMA operations;
4048		 * wait long enough for the RX fifo to drain, reset the
4049		 * hardware at the new frequency, and then re-enable
4050		 * the relevant bits of the h/w.
4051		 */
4052		ath_hal_intrset(ah, 0);		/* disable interrupts */
4053		ath_draintxq(sc);		/* clear pending tx frames */
4054		ath_stoprecv(sc);		/* turn off frame recv */
4055		if (!ath_hal_reset(ah, sc->sc_opmode, &hchan, AH_TRUE, &status)) {
4056			if_printf(ic->ic_ifp, "ath_chan_set: unable to reset "
4057				"channel %u (%u Mhz)\n",
4058				ieee80211_chan2ieee(ic, chan), chan->ic_freq);
4059			return EIO;
4060		}
4061		sc->sc_curchan = hchan;
4062		ath_update_txpow(sc);		/* update tx power state */
4063		sc->sc_diversity = ath_hal_getdiversity(ah);
4064
4065		/*
4066		 * Re-enable rx framework.
4067		 */
4068		if (ath_startrecv(sc) != 0) {
4069			if_printf(ic->ic_ifp,
4070				"ath_chan_set: unable to restart recv logic\n");
4071			return EIO;
4072		}
4073
4074		/*
4075		 * Change channels and update the h/w rate map
4076		 * if we're switching; e.g. 11a to 11b/g.
4077		 */
4078		ic->ic_ibss_chan = chan;
4079		ath_chan_change(sc, chan);
4080
4081		/*
4082		 * Re-enable interrupts.
4083		 */
4084		ath_hal_intrset(ah, sc->sc_imask);
4085	}
4086	return 0;
4087}
4088
4089static void
4090ath_next_scan(void *arg)
4091{
4092	struct ath_softc *sc = arg;
4093	struct ieee80211com *ic = &sc->sc_ic;
4094
4095	if (ic->ic_state == IEEE80211_S_SCAN)
4096		ieee80211_next_scan(ic);
4097}
4098
4099/*
4100 * Periodically recalibrate the PHY to account
4101 * for temperature/environment changes.
4102 */
4103static void
4104ath_calibrate(void *arg)
4105{
4106	struct ath_softc *sc = arg;
4107	struct ath_hal *ah = sc->sc_ah;
4108
4109	sc->sc_stats.ast_per_cal++;
4110
4111	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: channel %u/%x\n",
4112		__func__, sc->sc_curchan.channel, sc->sc_curchan.channelFlags);
4113
4114	if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4115		/*
4116		 * Rfgain is out of bounds, reset the chip
4117		 * to load new gain values.
4118		 */
4119		sc->sc_stats.ast_per_rfgain++;
4120		ath_reset(sc->sc_ifp);
4121	}
4122	if (!ath_hal_calibrate(ah, &sc->sc_curchan)) {
4123		DPRINTF(sc, ATH_DEBUG_ANY,
4124			"%s: calibration of channel %u failed\n",
4125			__func__, sc->sc_curchan.channel);
4126		sc->sc_stats.ast_per_calfail++;
4127	}
4128	/*
4129	 * Calibrate noise floor data again in case of change.
4130	 */
4131	ath_hal_process_noisefloor(ah);
4132	callout_reset(&sc->sc_cal_ch, ath_calinterval * hz, ath_calibrate, sc);
4133}
4134
4135static int
4136ath_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
4137{
4138	struct ifnet *ifp = ic->ic_ifp;
4139	struct ath_softc *sc = ifp->if_softc;
4140	struct ath_hal *ah = sc->sc_ah;
4141	struct ieee80211_node *ni;
4142	int i, error;
4143	const u_int8_t *bssid;
4144	u_int32_t rfilt;
4145	static const HAL_LED_STATE leds[] = {
4146	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
4147	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
4148	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
4149	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
4150	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
4151	};
4152
4153	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
4154		ieee80211_state_name[ic->ic_state],
4155		ieee80211_state_name[nstate]);
4156
4157	callout_stop(&sc->sc_scan_ch);
4158	callout_stop(&sc->sc_cal_ch);
4159	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
4160
4161	if (nstate == IEEE80211_S_INIT) {
4162		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4163		/*
4164		 * NB: disable interrupts so we don't rx frames.
4165		 */
4166		ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
4167		/*
4168		 * Notify the rate control algorithm.
4169		 */
4170		ath_rate_newstate(sc, nstate);
4171		goto done;
4172	}
4173	ni = ic->ic_bss;
4174	error = ath_chan_set(sc, ic->ic_curchan);
4175	if (error != 0)
4176		goto bad;
4177	rfilt = ath_calcrxfilter(sc, nstate);
4178	if (nstate == IEEE80211_S_SCAN)
4179		bssid = ifp->if_broadcastaddr;
4180	else
4181		bssid = ni->ni_bssid;
4182	ath_hal_setrxfilter(ah, rfilt);
4183	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s\n",
4184		 __func__, rfilt, ether_sprintf(bssid));
4185
4186	if (nstate == IEEE80211_S_RUN && ic->ic_opmode == IEEE80211_M_STA)
4187		ath_hal_setassocid(ah, bssid, ni->ni_associd);
4188	else
4189		ath_hal_setassocid(ah, bssid, 0);
4190	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
4191		for (i = 0; i < IEEE80211_WEP_NKID; i++)
4192			if (ath_hal_keyisvalid(ah, i))
4193				ath_hal_keysetmac(ah, i, bssid);
4194	}
4195
4196	/*
4197	 * Notify the rate control algorithm so rates
4198	 * are setup should ath_beacon_alloc be called.
4199	 */
4200	ath_rate_newstate(sc, nstate);
4201
4202	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
4203		/* nothing to do */;
4204	} else if (nstate == IEEE80211_S_RUN) {
4205		DPRINTF(sc, ATH_DEBUG_STATE,
4206			"%s(RUN): ic_flags=0x%08x iv=%d bssid=%s "
4207			"capinfo=0x%04x chan=%d\n"
4208			 , __func__
4209			 , ic->ic_flags
4210			 , ni->ni_intval
4211			 , ether_sprintf(ni->ni_bssid)
4212			 , ni->ni_capinfo
4213			 , ieee80211_chan2ieee(ic, ic->ic_curchan));
4214
4215		switch (ic->ic_opmode) {
4216		case IEEE80211_M_HOSTAP:
4217		case IEEE80211_M_IBSS:
4218			/*
4219			 * Allocate and setup the beacon frame.
4220			 *
4221			 * Stop any previous beacon DMA.  This may be
4222			 * necessary, for example, when an ibss merge
4223			 * causes reconfiguration; there will be a state
4224			 * transition from RUN->RUN that means we may
4225			 * be called with beacon transmission active.
4226			 */
4227			ath_hal_stoptxdma(ah, sc->sc_bhalq);
4228			ath_beacon_free(sc);
4229			error = ath_beacon_alloc(sc, ni);
4230			if (error != 0)
4231				goto bad;
4232			/*
4233			 * Configure the beacon and sleep timers.
4234			 */
4235			ath_beacon_config(sc);
4236			break;
4237		case IEEE80211_M_STA:
4238			/*
4239			 * Allocate a key cache slot to the station.
4240			 */
4241			if ((ic->ic_flags & IEEE80211_F_PRIVACY) == 0 &&
4242			    sc->sc_hasclrkey &&
4243			    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
4244				ath_setup_stationkey(ni);
4245			/*
4246			 * Configure the beacon and sleep timers.
4247			 */
4248			ath_beacon_config(sc);
4249			break;
4250		default:
4251			break;
4252		}
4253
4254		/*
4255		 * Let the hal process statistics collected during a
4256		 * scan so it can provide calibrated noise floor data.
4257		 */
4258		ath_hal_process_noisefloor(ah);
4259		/*
4260		 * Reset rssi stats; maybe not the best place...
4261		 */
4262		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
4263		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
4264		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
4265	} else {
4266		ath_hal_intrset(ah,
4267			sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
4268		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4269	}
4270done:
4271	/*
4272	 * Invoke the parent method to complete the work.
4273	 */
4274	error = sc->sc_newstate(ic, nstate, arg);
4275	/*
4276	 * Finally, start any timers.
4277	 */
4278	if (nstate == IEEE80211_S_RUN) {
4279		/* start periodic recalibration timer */
4280		callout_reset(&sc->sc_cal_ch, ath_calinterval * hz,
4281			ath_calibrate, sc);
4282	} else if (nstate == IEEE80211_S_SCAN) {
4283		/* start ap/neighbor scan timer */
4284		callout_reset(&sc->sc_scan_ch, (ath_dwelltime * hz) / 1000,
4285			ath_next_scan, sc);
4286	}
4287bad:
4288	return error;
4289}
4290
4291/*
4292 * Allocate a key cache slot to the station so we can
4293 * setup a mapping from key index to node. The key cache
4294 * slot is needed for managing antenna state and for
4295 * compression when stations do not use crypto.  We do
4296 * it uniliaterally here; if crypto is employed this slot
4297 * will be reassigned.
4298 */
4299static void
4300ath_setup_stationkey(struct ieee80211_node *ni)
4301{
4302	struct ieee80211com *ic = ni->ni_ic;
4303	struct ath_softc *sc = ic->ic_ifp->if_softc;
4304	ieee80211_keyix keyix, rxkeyix;
4305
4306	if (!ath_key_alloc(ic, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
4307		/*
4308		 * Key cache is full; we'll fall back to doing
4309		 * the more expensive lookup in software.  Note
4310		 * this also means no h/w compression.
4311		 */
4312		/* XXX msg+statistic */
4313	} else {
4314		/* XXX locking? */
4315		ni->ni_ucastkey.wk_keyix = keyix;
4316		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
4317		/* NB: this will create a pass-thru key entry */
4318		ath_keyset(sc, &ni->ni_ucastkey, ni->ni_macaddr, ic->ic_bss);
4319	}
4320}
4321
4322/*
4323 * Setup driver-specific state for a newly associated node.
4324 * Note that we're called also on a re-associate, the isnew
4325 * param tells us if this is the first time or not.
4326 */
4327static void
4328ath_newassoc(struct ieee80211_node *ni, int isnew)
4329{
4330	struct ieee80211com *ic = ni->ni_ic;
4331	struct ath_softc *sc = ic->ic_ifp->if_softc;
4332
4333	ath_rate_newassoc(sc, ATH_NODE(ni), isnew);
4334	if (isnew &&
4335	    (ic->ic_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey) {
4336		KASSERT(ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE,
4337		    ("new assoc with a unicast key already setup (keyix %u)",
4338		    ni->ni_ucastkey.wk_keyix));
4339		ath_setup_stationkey(ni);
4340	}
4341}
4342
4343static int
4344ath_getchannels(struct ath_softc *sc, u_int cc,
4345	HAL_BOOL outdoor, HAL_BOOL xchanmode)
4346{
4347	struct ieee80211com *ic = &sc->sc_ic;
4348	struct ifnet *ifp = sc->sc_ifp;
4349	struct ath_hal *ah = sc->sc_ah;
4350	HAL_CHANNEL *chans;
4351	int i, ix, nchan;
4352
4353	chans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
4354			M_TEMP, M_NOWAIT);
4355	if (chans == NULL) {
4356		if_printf(ifp, "unable to allocate channel table\n");
4357		return ENOMEM;
4358	}
4359	if (!ath_hal_init_channels(ah, chans, IEEE80211_CHAN_MAX, &nchan,
4360	    cc, HAL_MODE_ALL, outdoor, xchanmode)) {
4361		u_int32_t rd;
4362
4363		ath_hal_getregdomain(ah, &rd);
4364		if_printf(ifp, "unable to collect channel list from hal; "
4365			"regdomain likely %u country code %u\n", rd, cc);
4366		free(chans, M_TEMP);
4367		return EINVAL;
4368	}
4369
4370	/*
4371	 * Convert HAL channels to ieee80211 ones and insert
4372	 * them in the table according to their channel number.
4373	 */
4374	for (i = 0; i < nchan; i++) {
4375		HAL_CHANNEL *c = &chans[i];
4376		ix = ath_hal_mhz2ieee(c->channel, c->channelFlags);
4377		if (ix > IEEE80211_CHAN_MAX) {
4378			if_printf(ifp, "bad hal channel %u (%u/%x) ignored\n",
4379				ix, c->channel, c->channelFlags);
4380			continue;
4381		}
4382		/* NB: flags are known to be compatible */
4383		if (ic->ic_channels[ix].ic_freq == 0) {
4384			ic->ic_channels[ix].ic_freq = c->channel;
4385			ic->ic_channels[ix].ic_flags = c->channelFlags;
4386		} else {
4387			/* channels overlap; e.g. 11g and 11b */
4388			ic->ic_channels[ix].ic_flags |= c->channelFlags;
4389		}
4390	}
4391	free(chans, M_TEMP);
4392	return 0;
4393}
4394
4395static void
4396ath_led_done(void *arg)
4397{
4398	struct ath_softc *sc = arg;
4399
4400	sc->sc_blinking = 0;
4401}
4402
4403/*
4404 * Turn the LED off: flip the pin and then set a timer so no
4405 * update will happen for the specified duration.
4406 */
4407static void
4408ath_led_off(void *arg)
4409{
4410	struct ath_softc *sc = arg;
4411
4412	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
4413	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
4414}
4415
4416/*
4417 * Blink the LED according to the specified on/off times.
4418 */
4419static void
4420ath_led_blink(struct ath_softc *sc, int on, int off)
4421{
4422	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
4423	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
4424	sc->sc_blinking = 1;
4425	sc->sc_ledoff = off;
4426	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
4427}
4428
4429static void
4430ath_led_event(struct ath_softc *sc, int event)
4431{
4432
4433	sc->sc_ledevent = ticks;	/* time of last event */
4434	if (sc->sc_blinking)		/* don't interrupt active blink */
4435		return;
4436	switch (event) {
4437	case ATH_LED_POLL:
4438		ath_led_blink(sc, sc->sc_hwmap[0].ledon,
4439			sc->sc_hwmap[0].ledoff);
4440		break;
4441	case ATH_LED_TX:
4442		ath_led_blink(sc, sc->sc_hwmap[sc->sc_txrate].ledon,
4443			sc->sc_hwmap[sc->sc_txrate].ledoff);
4444		break;
4445	case ATH_LED_RX:
4446		ath_led_blink(sc, sc->sc_hwmap[sc->sc_rxrate].ledon,
4447			sc->sc_hwmap[sc->sc_rxrate].ledoff);
4448		break;
4449	}
4450}
4451
4452static void
4453ath_update_txpow(struct ath_softc *sc)
4454{
4455	struct ieee80211com *ic = &sc->sc_ic;
4456	struct ath_hal *ah = sc->sc_ah;
4457	u_int32_t txpow;
4458
4459	if (sc->sc_curtxpow != ic->ic_txpowlimit) {
4460		ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
4461		/* read back in case value is clamped */
4462		ath_hal_gettxpowlimit(ah, &txpow);
4463		ic->ic_txpowlimit = sc->sc_curtxpow = txpow;
4464	}
4465	/*
4466	 * Fetch max tx power level for status requests.
4467	 */
4468	ath_hal_getmaxtxpow(sc->sc_ah, &txpow);
4469	ic->ic_bss->ni_txpower = txpow;
4470}
4471
4472static void
4473rate_setup(struct ath_softc *sc,
4474	const HAL_RATE_TABLE *rt, struct ieee80211_rateset *rs)
4475{
4476	int i, maxrates;
4477
4478	if (rt->rateCount > IEEE80211_RATE_MAXSIZE) {
4479		DPRINTF(sc, ATH_DEBUG_ANY,
4480			"%s: rate table too small (%u > %u)\n",
4481		       __func__, rt->rateCount, IEEE80211_RATE_MAXSIZE);
4482		maxrates = IEEE80211_RATE_MAXSIZE;
4483	} else
4484		maxrates = rt->rateCount;
4485	for (i = 0; i < maxrates; i++)
4486		rs->rs_rates[i] = rt->info[i].dot11Rate;
4487	rs->rs_nrates = maxrates;
4488}
4489
4490static int
4491ath_rate_setup(struct ath_softc *sc, u_int mode)
4492{
4493	struct ath_hal *ah = sc->sc_ah;
4494	struct ieee80211com *ic = &sc->sc_ic;
4495	const HAL_RATE_TABLE *rt;
4496
4497	switch (mode) {
4498	case IEEE80211_MODE_11A:
4499		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
4500		break;
4501	case IEEE80211_MODE_11B:
4502		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
4503		break;
4504	case IEEE80211_MODE_11G:
4505		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
4506		break;
4507	case IEEE80211_MODE_TURBO_A:
4508		/* XXX until static/dynamic turbo is fixed */
4509		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
4510		break;
4511	case IEEE80211_MODE_TURBO_G:
4512		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
4513		break;
4514	default:
4515		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
4516			__func__, mode);
4517		return 0;
4518	}
4519	sc->sc_rates[mode] = rt;
4520	if (rt != NULL) {
4521		rate_setup(sc, rt, &ic->ic_sup_rates[mode]);
4522		return 1;
4523	} else
4524		return 0;
4525}
4526
4527static void
4528ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
4529{
4530#define	N(a)	(sizeof(a)/sizeof(a[0]))
4531	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
4532	static const struct {
4533		u_int		rate;		/* tx/rx 802.11 rate */
4534		u_int16_t	timeOn;		/* LED on time (ms) */
4535		u_int16_t	timeOff;	/* LED off time (ms) */
4536	} blinkrates[] = {
4537		{ 108,  40,  10 },
4538		{  96,  44,  11 },
4539		{  72,  50,  13 },
4540		{  48,  57,  14 },
4541		{  36,  67,  16 },
4542		{  24,  80,  20 },
4543		{  22, 100,  25 },
4544		{  18, 133,  34 },
4545		{  12, 160,  40 },
4546		{  10, 200,  50 },
4547		{   6, 240,  58 },
4548		{   4, 267,  66 },
4549		{   2, 400, 100 },
4550		{   0, 500, 130 },
4551	};
4552	const HAL_RATE_TABLE *rt;
4553	int i, j;
4554
4555	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
4556	rt = sc->sc_rates[mode];
4557	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
4558	for (i = 0; i < rt->rateCount; i++)
4559		sc->sc_rixmap[rt->info[i].dot11Rate & IEEE80211_RATE_VAL] = i;
4560	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
4561	for (i = 0; i < 32; i++) {
4562		u_int8_t ix = rt->rateCodeToIndex[i];
4563		if (ix == 0xff) {
4564			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
4565			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
4566			continue;
4567		}
4568		sc->sc_hwmap[i].ieeerate =
4569			rt->info[ix].dot11Rate & IEEE80211_RATE_VAL;
4570		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
4571		if (rt->info[ix].shortPreamble ||
4572		    rt->info[ix].phy == IEEE80211_T_OFDM)
4573			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
4574		/* NB: receive frames include FCS */
4575		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags |
4576			IEEE80211_RADIOTAP_F_FCS;
4577		/* setup blink rate table to avoid per-packet lookup */
4578		for (j = 0; j < N(blinkrates)-1; j++)
4579			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
4580				break;
4581		/* NB: this uses the last entry if the rate isn't found */
4582		/* XXX beware of overlow */
4583		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
4584		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
4585	}
4586	sc->sc_currates = rt;
4587	sc->sc_curmode = mode;
4588	/*
4589	 * All protection frames are transmited at 2Mb/s for
4590	 * 11g, otherwise at 1Mb/s.
4591	 */
4592	if (mode == IEEE80211_MODE_11G)
4593		sc->sc_protrix = ath_tx_findrix(rt, 2*2);
4594	else
4595		sc->sc_protrix = ath_tx_findrix(rt, 2*1);
4596	/* rate index used to send management frames */
4597	sc->sc_minrateix = 0;
4598	/*
4599	 * Setup multicast rate state.
4600	 */
4601	/* XXX layering violation */
4602	sc->sc_mcastrix = ath_tx_findrix(rt, sc->sc_ic.ic_mcast_rate);
4603	sc->sc_mcastrate = sc->sc_ic.ic_mcast_rate;
4604	/* NB: caller is responsible for reseting rate control state */
4605#undef N
4606}
4607
4608#ifdef AR_DEBUG
4609static void
4610ath_printrxbuf(struct ath_buf *bf, int done)
4611{
4612	struct ath_desc *ds;
4613	int i;
4614
4615	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
4616		printf("R%d (%p %p) %08x %08x %08x %08x %08x %08x %c\n",
4617		    i, ds, (struct ath_desc *)bf->bf_daddr + i,
4618		    ds->ds_link, ds->ds_data,
4619		    ds->ds_ctl0, ds->ds_ctl1,
4620		    ds->ds_hw[0], ds->ds_hw[1],
4621		    !done ? ' ' : (ds->ds_rxstat.rs_status == 0) ? '*' : '!');
4622	}
4623}
4624
4625static void
4626ath_printtxbuf(struct ath_buf *bf, int done)
4627{
4628	struct ath_desc *ds;
4629	int i;
4630
4631	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
4632		printf("T%d (%p %p) %08x %08x %08x %08x %08x %08x %08x %08x %c\n",
4633		    i, ds, (struct ath_desc *)bf->bf_daddr + i,
4634		    ds->ds_link, ds->ds_data,
4635		    ds->ds_ctl0, ds->ds_ctl1,
4636		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3],
4637		    !done ? ' ' : (ds->ds_txstat.ts_status == 0) ? '*' : '!');
4638	}
4639}
4640#endif /* AR_DEBUG */
4641
4642static void
4643ath_watchdog(struct ifnet *ifp)
4644{
4645	struct ath_softc *sc = ifp->if_softc;
4646	struct ieee80211com *ic = &sc->sc_ic;
4647
4648	ifp->if_timer = 0;
4649	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
4650		return;
4651	if (sc->sc_tx_timer) {
4652		if (--sc->sc_tx_timer == 0) {
4653			if_printf(ifp, "device timeout\n");
4654			ath_reset(ifp);
4655			ifp->if_oerrors++;
4656			sc->sc_stats.ast_watchdog++;
4657		} else
4658			ifp->if_timer = 1;
4659	}
4660	ieee80211_watchdog(ic);
4661}
4662
4663/*
4664 * Diagnostic interface to the HAL.  This is used by various
4665 * tools to do things like retrieve register contents for
4666 * debugging.  The mechanism is intentionally opaque so that
4667 * it can change frequently w/o concern for compatiblity.
4668 */
4669static int
4670ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
4671{
4672	struct ath_hal *ah = sc->sc_ah;
4673	u_int id = ad->ad_id & ATH_DIAG_ID;
4674	void *indata = NULL;
4675	void *outdata = NULL;
4676	u_int32_t insize = ad->ad_in_size;
4677	u_int32_t outsize = ad->ad_out_size;
4678	int error = 0;
4679
4680	if (ad->ad_id & ATH_DIAG_IN) {
4681		/*
4682		 * Copy in data.
4683		 */
4684		indata = malloc(insize, M_TEMP, M_NOWAIT);
4685		if (indata == NULL) {
4686			error = ENOMEM;
4687			goto bad;
4688		}
4689		error = copyin(ad->ad_in_data, indata, insize);
4690		if (error)
4691			goto bad;
4692	}
4693	if (ad->ad_id & ATH_DIAG_DYN) {
4694		/*
4695		 * Allocate a buffer for the results (otherwise the HAL
4696		 * returns a pointer to a buffer where we can read the
4697		 * results).  Note that we depend on the HAL leaving this
4698		 * pointer for us to use below in reclaiming the buffer;
4699		 * may want to be more defensive.
4700		 */
4701		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
4702		if (outdata == NULL) {
4703			error = ENOMEM;
4704			goto bad;
4705		}
4706	}
4707	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
4708		if (outsize < ad->ad_out_size)
4709			ad->ad_out_size = outsize;
4710		if (outdata != NULL)
4711			error = copyout(outdata, ad->ad_out_data,
4712					ad->ad_out_size);
4713	} else {
4714		error = EINVAL;
4715	}
4716bad:
4717	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
4718		free(indata, M_TEMP);
4719	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
4720		free(outdata, M_TEMP);
4721	return error;
4722}
4723
4724static int
4725ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
4726{
4727#define	IS_RUNNING(ifp) \
4728	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
4729	struct ath_softc *sc = ifp->if_softc;
4730	struct ieee80211com *ic = &sc->sc_ic;
4731	struct ifreq *ifr = (struct ifreq *)data;
4732	int error = 0;
4733
4734	ATH_LOCK(sc);
4735	switch (cmd) {
4736	case SIOCSIFFLAGS:
4737		if (IS_RUNNING(ifp)) {
4738			/*
4739			 * To avoid rescanning another access point,
4740			 * do not call ath_init() here.  Instead,
4741			 * only reflect promisc mode settings.
4742			 */
4743			ath_mode_init(sc);
4744		} else if (ifp->if_flags & IFF_UP) {
4745			/*
4746			 * Beware of being called during attach/detach
4747			 * to reset promiscuous mode.  In that case we
4748			 * will still be marked UP but not RUNNING.
4749			 * However trying to re-init the interface
4750			 * is the wrong thing to do as we've already
4751			 * torn down much of our state.  There's
4752			 * probably a better way to deal with this.
4753			 */
4754			if (!sc->sc_invalid && ic->ic_bss != NULL)
4755				ath_init(sc);	/* XXX lose error */
4756		} else
4757			ath_stop_locked(ifp);
4758		break;
4759	case SIOCADDMULTI:
4760	case SIOCDELMULTI:
4761		/*
4762		 * The upper layer has already installed/removed
4763		 * the multicast address(es), just recalculate the
4764		 * multicast filter for the card.
4765		 */
4766		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4767			ath_mode_init(sc);
4768		break;
4769	case SIOCGATHSTATS:
4770		/* NB: embed these numbers to get a consistent view */
4771		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
4772		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
4773		sc->sc_stats.ast_rx_rssi = ieee80211_getrssi(ic);
4774		ATH_UNLOCK(sc);
4775		/*
4776		 * NB: Drop the softc lock in case of a page fault;
4777		 * we'll accept any potential inconsisentcy in the
4778		 * statistics.  The alternative is to copy the data
4779		 * to a local structure.
4780		 */
4781		return copyout(&sc->sc_stats,
4782				ifr->ifr_data, sizeof (sc->sc_stats));
4783	case SIOCGATHDIAG:
4784		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
4785		break;
4786	default:
4787		error = ieee80211_ioctl(ic, cmd, data);
4788		if (error == ENETRESET) {
4789			if (IS_RUNNING(ifp) &&
4790			    ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
4791				ath_init(sc);	/* XXX lose error */
4792			error = 0;
4793		}
4794		if (error == ERESTART)
4795			error = IS_RUNNING(ifp) ? ath_reset(ifp) : 0;
4796		break;
4797	}
4798	ATH_UNLOCK(sc);
4799	return error;
4800#undef IS_RUNNING
4801}
4802
4803static int
4804ath_sysctl_slottime(SYSCTL_HANDLER_ARGS)
4805{
4806	struct ath_softc *sc = arg1;
4807	u_int slottime = ath_hal_getslottime(sc->sc_ah);
4808	int error;
4809
4810	error = sysctl_handle_int(oidp, &slottime, 0, req);
4811	if (error || !req->newptr)
4812		return error;
4813	return !ath_hal_setslottime(sc->sc_ah, slottime) ? EINVAL : 0;
4814}
4815
4816static int
4817ath_sysctl_acktimeout(SYSCTL_HANDLER_ARGS)
4818{
4819	struct ath_softc *sc = arg1;
4820	u_int acktimeout = ath_hal_getacktimeout(sc->sc_ah);
4821	int error;
4822
4823	error = sysctl_handle_int(oidp, &acktimeout, 0, req);
4824	if (error || !req->newptr)
4825		return error;
4826	return !ath_hal_setacktimeout(sc->sc_ah, acktimeout) ? EINVAL : 0;
4827}
4828
4829static int
4830ath_sysctl_ctstimeout(SYSCTL_HANDLER_ARGS)
4831{
4832	struct ath_softc *sc = arg1;
4833	u_int ctstimeout = ath_hal_getctstimeout(sc->sc_ah);
4834	int error;
4835
4836	error = sysctl_handle_int(oidp, &ctstimeout, 0, req);
4837	if (error || !req->newptr)
4838		return error;
4839	return !ath_hal_setctstimeout(sc->sc_ah, ctstimeout) ? EINVAL : 0;
4840}
4841
4842static int
4843ath_sysctl_softled(SYSCTL_HANDLER_ARGS)
4844{
4845	struct ath_softc *sc = arg1;
4846	int softled = sc->sc_softled;
4847	int error;
4848
4849	error = sysctl_handle_int(oidp, &softled, 0, req);
4850	if (error || !req->newptr)
4851		return error;
4852	softled = (softled != 0);
4853	if (softled != sc->sc_softled) {
4854		if (softled) {
4855			/* NB: handle any sc_ledpin change */
4856			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
4857			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
4858				!sc->sc_ledon);
4859		}
4860		sc->sc_softled = softled;
4861	}
4862	return 0;
4863}
4864
4865static int
4866ath_sysctl_rxantenna(SYSCTL_HANDLER_ARGS)
4867{
4868	struct ath_softc *sc = arg1;
4869	u_int defantenna = ath_hal_getdefantenna(sc->sc_ah);
4870	int error;
4871
4872	error = sysctl_handle_int(oidp, &defantenna, 0, req);
4873	if (!error && req->newptr)
4874		ath_hal_setdefantenna(sc->sc_ah, defantenna);
4875	return error;
4876}
4877
4878static int
4879ath_sysctl_diversity(SYSCTL_HANDLER_ARGS)
4880{
4881	struct ath_softc *sc = arg1;
4882	u_int diversity = ath_hal_getdiversity(sc->sc_ah);
4883	int error;
4884
4885	error = sysctl_handle_int(oidp, &diversity, 0, req);
4886	if (error || !req->newptr)
4887		return error;
4888	if (!ath_hal_setdiversity(sc->sc_ah, diversity))
4889		return EINVAL;
4890	sc->sc_diversity = diversity;
4891	return 0;
4892}
4893
4894static int
4895ath_sysctl_diag(SYSCTL_HANDLER_ARGS)
4896{
4897	struct ath_softc *sc = arg1;
4898	u_int32_t diag;
4899	int error;
4900
4901	if (!ath_hal_getdiag(sc->sc_ah, &diag))
4902		return EINVAL;
4903	error = sysctl_handle_int(oidp, &diag, 0, req);
4904	if (error || !req->newptr)
4905		return error;
4906	return !ath_hal_setdiag(sc->sc_ah, diag) ? EINVAL : 0;
4907}
4908
4909static int
4910ath_sysctl_tpscale(SYSCTL_HANDLER_ARGS)
4911{
4912	struct ath_softc *sc = arg1;
4913	struct ifnet *ifp = sc->sc_ifp;
4914	u_int32_t scale;
4915	int error;
4916
4917	ath_hal_gettpscale(sc->sc_ah, &scale);
4918	error = sysctl_handle_int(oidp, &scale, 0, req);
4919	if (error || !req->newptr)
4920		return error;
4921	return !ath_hal_settpscale(sc->sc_ah, scale) ? EINVAL : ath_reset(ifp);
4922}
4923
4924static int
4925ath_sysctl_tpc(SYSCTL_HANDLER_ARGS)
4926{
4927	struct ath_softc *sc = arg1;
4928	u_int tpc = ath_hal_gettpc(sc->sc_ah);
4929	int error;
4930
4931	error = sysctl_handle_int(oidp, &tpc, 0, req);
4932	if (error || !req->newptr)
4933		return error;
4934	return !ath_hal_settpc(sc->sc_ah, tpc) ? EINVAL : 0;
4935}
4936
4937static int
4938ath_sysctl_regdomain(SYSCTL_HANDLER_ARGS)
4939{
4940	struct ath_softc *sc = arg1;
4941	u_int32_t rd;
4942	int error;
4943
4944	if (!ath_hal_getregdomain(sc->sc_ah, &rd))
4945		return EINVAL;
4946	error = sysctl_handle_int(oidp, &rd, 0, req);
4947	if (error || !req->newptr)
4948		return error;
4949	return !ath_hal_setregdomain(sc->sc_ah, rd) ? EINVAL : 0;
4950}
4951
4952static void
4953ath_sysctlattach(struct ath_softc *sc)
4954{
4955	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
4956	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
4957	struct ath_hal *ah = sc->sc_ah;
4958
4959	ath_hal_getcountrycode(sc->sc_ah, &sc->sc_countrycode);
4960	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4961		"countrycode", CTLFLAG_RD, &sc->sc_countrycode, 0,
4962		"EEPROM country code");
4963	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4964		"regdomain", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4965		ath_sysctl_regdomain, "I", "EEPROM regdomain code");
4966	sc->sc_debug = ath_debug;
4967	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4968		"debug", CTLFLAG_RW, &sc->sc_debug, 0,
4969		"control debugging printfs");
4970
4971	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4972		"slottime", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4973		ath_sysctl_slottime, "I", "802.11 slot time (us)");
4974	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4975		"acktimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4976		ath_sysctl_acktimeout, "I", "802.11 ACK timeout (us)");
4977	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4978		"ctstimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4979		ath_sysctl_ctstimeout, "I", "802.11 CTS timeout (us)");
4980	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4981		"softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4982		ath_sysctl_softled, "I", "enable/disable software LED support");
4983	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4984		"ledpin", CTLFLAG_RW, &sc->sc_ledpin, 0,
4985		"GPIO pin connected to LED");
4986	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4987		"ledon", CTLFLAG_RW, &sc->sc_ledon, 0,
4988		"setting to turn LED on");
4989	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4990		"ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
4991		"idle time for inactivity LED (ticks)");
4992	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4993		"txantenna", CTLFLAG_RW, &sc->sc_txantenna, 0,
4994		"tx antenna (0=auto)");
4995	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4996		"rxantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4997		ath_sysctl_rxantenna, "I", "default/rx antenna");
4998	if (ath_hal_hasdiversity(ah))
4999		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5000			"diversity", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5001			ath_sysctl_diversity, "I", "antenna diversity");
5002	sc->sc_txintrperiod = ATH_TXINTR_PERIOD;
5003	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5004		"txintrperiod", CTLFLAG_RW, &sc->sc_txintrperiod, 0,
5005		"tx descriptor batching");
5006	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5007		"diag", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5008		ath_sysctl_diag, "I", "h/w diagnostic control");
5009	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5010		"tpscale", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5011		ath_sysctl_tpscale, "I", "tx power scaling");
5012	if (ath_hal_hastpc(ah))
5013		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5014			"tpc", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5015			ath_sysctl_tpc, "I", "enable/disable per-packet TPC");
5016	sc->sc_monpass = HAL_RXERR_DECRYPT | HAL_RXERR_MIC;
5017	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5018		"monpass", CTLFLAG_RW, &sc->sc_monpass, 0,
5019		"mask of error frames to pass when monitoring");
5020}
5021
5022static void
5023ath_bpfattach(struct ath_softc *sc)
5024{
5025	struct ifnet *ifp = sc->sc_ifp;
5026
5027	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
5028		sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th),
5029		&sc->sc_drvbpf);
5030	/*
5031	 * Initialize constant fields.
5032	 * XXX make header lengths a multiple of 32-bits so subsequent
5033	 *     headers are properly aligned; this is a kludge to keep
5034	 *     certain applications happy.
5035	 *
5036	 * NB: the channel is setup each time we transition to the
5037	 *     RUN state to avoid filling it in for each frame.
5038	 */
5039	sc->sc_tx_th_len = roundup(sizeof(sc->sc_tx_th), sizeof(u_int32_t));
5040	sc->sc_tx_th.wt_ihdr.it_len = htole16(sc->sc_tx_th_len);
5041	sc->sc_tx_th.wt_ihdr.it_present = htole32(ATH_TX_RADIOTAP_PRESENT);
5042
5043	sc->sc_rx_th_len = roundup(sizeof(sc->sc_rx_th), sizeof(u_int32_t));
5044	sc->sc_rx_th.wr_ihdr.it_len = htole16(sc->sc_rx_th_len);
5045	sc->sc_rx_th.wr_ihdr.it_present = htole32(ATH_RX_RADIOTAP_PRESENT);
5046}
5047
5048/*
5049 * Announce various information on device/driver attach.
5050 */
5051static void
5052ath_announce(struct ath_softc *sc)
5053{
5054#define	HAL_MODE_DUALBAND	(HAL_MODE_11A|HAL_MODE_11B)
5055	struct ifnet *ifp = sc->sc_ifp;
5056	struct ath_hal *ah = sc->sc_ah;
5057	u_int modes, cc;
5058
5059	if_printf(ifp, "mac %d.%d phy %d.%d",
5060		ah->ah_macVersion, ah->ah_macRev,
5061		ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5062	/*
5063	 * Print radio revision(s).  We check the wireless modes
5064	 * to avoid falsely printing revs for inoperable parts.
5065	 * Dual-band radio revs are returned in the 5Ghz rev number.
5066	 */
5067	ath_hal_getcountrycode(ah, &cc);
5068	modes = ath_hal_getwirelessmodes(ah, cc);
5069	if ((modes & HAL_MODE_DUALBAND) == HAL_MODE_DUALBAND) {
5070		if (ah->ah_analog5GhzRev && ah->ah_analog2GhzRev)
5071			printf(" 5ghz radio %d.%d 2ghz radio %d.%d",
5072				ah->ah_analog5GhzRev >> 4,
5073				ah->ah_analog5GhzRev & 0xf,
5074				ah->ah_analog2GhzRev >> 4,
5075				ah->ah_analog2GhzRev & 0xf);
5076		else
5077			printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
5078				ah->ah_analog5GhzRev & 0xf);
5079	} else
5080		printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
5081			ah->ah_analog5GhzRev & 0xf);
5082	printf("\n");
5083	if (bootverbose) {
5084		int i;
5085		for (i = 0; i <= WME_AC_VO; i++) {
5086			struct ath_txq *txq = sc->sc_ac2q[i];
5087			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5088				txq->axq_qnum, ieee80211_wme_acnames[i]);
5089		}
5090		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5091			sc->sc_cabq->axq_qnum);
5092		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5093	}
5094	if (ath_rxbuf != ATH_RXBUF)
5095		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5096	if (ath_txbuf != ATH_TXBUF)
5097		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5098#undef HAL_MODE_DUALBAND
5099}
5100