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