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