xref: /freebsd/sys/dev/usb/wlan/if_uath.c (revision 780fb4a2)
1 /*-
2  * SPDX-License-Identifier: (BSD-2-Clause-FreeBSD AND BSD-1-Clause)
3  *
4  * Copyright (c) 2006 Sam Leffler, Errno Consulting
5  * Copyright (c) 2008-2009 Weongyo Jeong <weongyo@freebsd.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer,
13  *    without modification.
14  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
15  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
16  *    redistribution must be conditioned upon including a substantially
17  *    similar Disclaimer requirement for further binary redistribution.
18  *
19  * NO WARRANTY
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
23  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
24  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
25  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
28  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
30  * THE POSSIBILITY OF SUCH DAMAGES.
31  */
32 
33 /*
34  * This driver is distantly derived from a driver of the same name
35  * by Damien Bergamini.  The original copyright is included below:
36  *
37  * Copyright (c) 2006
38  *	Damien Bergamini <damien.bergamini@free.fr>
39  *
40  * Permission to use, copy, modify, and distribute this software for any
41  * purpose with or without fee is hereby granted, provided that the above
42  * copyright notice and this permission notice appear in all copies.
43  *
44  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
45  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
46  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
47  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
48  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
49  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
50  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
51  */
52 
53 #include <sys/cdefs.h>
54 __FBSDID("$FreeBSD$");
55 
56 /*-
57  * Driver for Atheros AR5523 USB parts.
58  *
59  * The driver requires firmware to be loaded into the device.  This
60  * is done on device discovery from a user application (uathload)
61  * that is launched by devd when a device with suitable product ID
62  * is recognized.  Once firmware has been loaded the device will
63  * reset the USB port and re-attach with the original product ID+1
64  * and this driver will be attached.  The firmware is licensed for
65  * general use (royalty free) and may be incorporated in products.
66  * Note that the firmware normally packaged with the NDIS drivers
67  * for these devices does not work in this way and so does not work
68  * with this driver.
69  */
70 
71 #include "opt_wlan.h"
72 
73 #include <sys/param.h>
74 #include <sys/sockio.h>
75 #include <sys/sysctl.h>
76 #include <sys/lock.h>
77 #include <sys/mutex.h>
78 #include <sys/mbuf.h>
79 #include <sys/kernel.h>
80 #include <sys/socket.h>
81 #include <sys/systm.h>
82 #include <sys/malloc.h>
83 #include <sys/module.h>
84 #include <sys/bus.h>
85 #include <sys/endian.h>
86 #include <sys/kdb.h>
87 
88 #include <machine/bus.h>
89 #include <machine/resource.h>
90 #include <sys/rman.h>
91 
92 #include <net/bpf.h>
93 #include <net/if.h>
94 #include <net/if_var.h>
95 #include <net/if_arp.h>
96 #include <net/ethernet.h>
97 #include <net/if_dl.h>
98 #include <net/if_media.h>
99 #include <net/if_types.h>
100 
101 #ifdef INET
102 #include <netinet/in.h>
103 #include <netinet/in_systm.h>
104 #include <netinet/in_var.h>
105 #include <netinet/if_ether.h>
106 #include <netinet/ip.h>
107 #endif
108 
109 #include <net80211/ieee80211_var.h>
110 #include <net80211/ieee80211_input.h>
111 #include <net80211/ieee80211_regdomain.h>
112 #include <net80211/ieee80211_radiotap.h>
113 
114 #include <dev/usb/usb.h>
115 #include <dev/usb/usbdi.h>
116 #include "usbdevs.h"
117 
118 #include <dev/usb/wlan/if_uathreg.h>
119 #include <dev/usb/wlan/if_uathvar.h>
120 
121 static SYSCTL_NODE(_hw_usb, OID_AUTO, uath, CTLFLAG_RW, 0, "USB Atheros");
122 
123 static	int uath_countrycode = CTRY_DEFAULT;	/* country code */
124 SYSCTL_INT(_hw_usb_uath, OID_AUTO, countrycode, CTLFLAG_RWTUN, &uath_countrycode,
125     0, "country code");
126 static	int uath_regdomain = 0;			/* regulatory domain */
127 SYSCTL_INT(_hw_usb_uath, OID_AUTO, regdomain, CTLFLAG_RD, &uath_regdomain,
128     0, "regulatory domain");
129 
130 #ifdef UATH_DEBUG
131 int uath_debug = 0;
132 SYSCTL_INT(_hw_usb_uath, OID_AUTO, debug, CTLFLAG_RWTUN, &uath_debug, 0,
133     "uath debug level");
134 enum {
135 	UATH_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
136 	UATH_DEBUG_XMIT_DUMP	= 0x00000002,	/* xmit dump */
137 	UATH_DEBUG_RECV		= 0x00000004,	/* basic recv operation */
138 	UATH_DEBUG_TX_PROC	= 0x00000008,	/* tx ISR proc */
139 	UATH_DEBUG_RX_PROC	= 0x00000010,	/* rx ISR proc */
140 	UATH_DEBUG_RECV_ALL	= 0x00000020,	/* trace all frames (beacons) */
141 	UATH_DEBUG_INIT		= 0x00000040,	/* initialization of dev */
142 	UATH_DEBUG_DEVCAP	= 0x00000080,	/* dev caps */
143 	UATH_DEBUG_CMDS		= 0x00000100,	/* commands */
144 	UATH_DEBUG_CMDS_DUMP	= 0x00000200,	/* command buffer dump */
145 	UATH_DEBUG_RESET	= 0x00000400,	/* reset processing */
146 	UATH_DEBUG_STATE	= 0x00000800,	/* 802.11 state transitions */
147 	UATH_DEBUG_MULTICAST	= 0x00001000,	/* multicast */
148 	UATH_DEBUG_WME		= 0x00002000,	/* WME */
149 	UATH_DEBUG_CHANNEL	= 0x00004000,	/* channel */
150 	UATH_DEBUG_RATES	= 0x00008000,	/* rates */
151 	UATH_DEBUG_CRYPTO	= 0x00010000,	/* crypto */
152 	UATH_DEBUG_LED		= 0x00020000,	/* LED */
153 	UATH_DEBUG_ANY		= 0xffffffff
154 };
155 #define	DPRINTF(sc, m, fmt, ...) do {				\
156 	if (sc->sc_debug & (m))					\
157 		printf(fmt, __VA_ARGS__);			\
158 } while (0)
159 #else
160 #define	DPRINTF(sc, m, fmt, ...) do {				\
161 	(void) sc;						\
162 } while (0)
163 #endif
164 
165 /* recognized device vendors/products */
166 static const STRUCT_USB_HOST_ID uath_devs[] = {
167 #define	UATH_DEV(v,p) { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) }
168 	UATH_DEV(ACCTON,		SMCWUSBTG2),
169 	UATH_DEV(ATHEROS,		AR5523),
170 	UATH_DEV(ATHEROS2,		AR5523_1),
171 	UATH_DEV(ATHEROS2,		AR5523_2),
172 	UATH_DEV(ATHEROS2,		AR5523_3),
173 	UATH_DEV(CONCEPTRONIC,		AR5523_1),
174 	UATH_DEV(CONCEPTRONIC,		AR5523_2),
175 	UATH_DEV(DLINK,			DWLAG122),
176 	UATH_DEV(DLINK,			DWLAG132),
177 	UATH_DEV(DLINK,			DWLG132),
178 	UATH_DEV(DLINK2,		DWA120),
179 	UATH_DEV(GIGASET,		AR5523),
180 	UATH_DEV(GIGASET,		SMCWUSBTG),
181 	UATH_DEV(GLOBALSUN,		AR5523_1),
182 	UATH_DEV(GLOBALSUN,		AR5523_2),
183 	UATH_DEV(NETGEAR,		WG111U),
184 	UATH_DEV(NETGEAR3,		WG111T),
185 	UATH_DEV(NETGEAR3,		WPN111),
186 	UATH_DEV(NETGEAR3,		WPN111_2),
187 	UATH_DEV(UMEDIA,		TEW444UBEU),
188 	UATH_DEV(UMEDIA,		AR5523_2),
189 	UATH_DEV(WISTRONNEWEB,		AR5523_1),
190 	UATH_DEV(WISTRONNEWEB,		AR5523_2),
191 	UATH_DEV(ZCOM,			AR5523)
192 #undef UATH_DEV
193 };
194 
195 static usb_callback_t uath_intr_rx_callback;
196 static usb_callback_t uath_intr_tx_callback;
197 static usb_callback_t uath_bulk_rx_callback;
198 static usb_callback_t uath_bulk_tx_callback;
199 
200 static const struct usb_config uath_usbconfig[UATH_N_XFERS] = {
201 	[UATH_INTR_RX] = {
202 		.type = UE_BULK,
203 		.endpoint = 0x1,
204 		.direction = UE_DIR_IN,
205 		.bufsize = UATH_MAX_CMDSZ,
206 		.flags = {
207 			.pipe_bof = 1,
208 			.short_xfer_ok = 1
209 		},
210 		.callback = uath_intr_rx_callback
211 	},
212 	[UATH_INTR_TX] = {
213 		.type = UE_BULK,
214 		.endpoint = 0x1,
215 		.direction = UE_DIR_OUT,
216 		.bufsize = UATH_MAX_CMDSZ * UATH_CMD_LIST_COUNT,
217 		.flags = {
218 			.force_short_xfer = 1,
219 			.pipe_bof = 1,
220 		},
221 		.callback = uath_intr_tx_callback,
222 		.timeout = UATH_CMD_TIMEOUT
223 	},
224 	[UATH_BULK_RX] = {
225 		.type = UE_BULK,
226 		.endpoint = 0x2,
227 		.direction = UE_DIR_IN,
228 		.bufsize = MCLBYTES,
229 		.flags = {
230 			.ext_buffer = 1,
231 			.pipe_bof = 1,
232 			.short_xfer_ok = 1
233 		},
234 		.callback = uath_bulk_rx_callback
235 	},
236 	[UATH_BULK_TX] = {
237 		.type = UE_BULK,
238 		.endpoint = 0x2,
239 		.direction = UE_DIR_OUT,
240 		.bufsize = UATH_MAX_TXBUFSZ * UATH_TX_DATA_LIST_COUNT,
241 		.flags = {
242 			.force_short_xfer = 1,
243 			.pipe_bof = 1
244 		},
245 		.callback = uath_bulk_tx_callback,
246 		.timeout = UATH_DATA_TIMEOUT
247 	}
248 };
249 
250 static struct ieee80211vap *uath_vap_create(struct ieee80211com *,
251 		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
252 		    const uint8_t [IEEE80211_ADDR_LEN],
253 		    const uint8_t [IEEE80211_ADDR_LEN]);
254 static void	uath_vap_delete(struct ieee80211vap *);
255 static int	uath_alloc_cmd_list(struct uath_softc *, struct uath_cmd []);
256 static void	uath_free_cmd_list(struct uath_softc *, struct uath_cmd []);
257 static int	uath_host_available(struct uath_softc *);
258 static int	uath_get_capability(struct uath_softc *, uint32_t, uint32_t *);
259 static int	uath_get_devcap(struct uath_softc *);
260 static struct uath_cmd *
261 		uath_get_cmdbuf(struct uath_softc *);
262 static int	uath_cmd_read(struct uath_softc *, uint32_t, const void *,
263 		    int, void *, int, int);
264 static int	uath_cmd_write(struct uath_softc *, uint32_t, const void *,
265 		    int, int);
266 static void	uath_stat(void *);
267 #ifdef UATH_DEBUG
268 static void	uath_dump_cmd(const uint8_t *, int, char);
269 static const char *
270 		uath_codename(int);
271 #endif
272 static int	uath_get_devstatus(struct uath_softc *,
273 		    uint8_t macaddr[IEEE80211_ADDR_LEN]);
274 static int	uath_get_status(struct uath_softc *, uint32_t, void *, int);
275 static int	uath_alloc_rx_data_list(struct uath_softc *);
276 static int	uath_alloc_tx_data_list(struct uath_softc *);
277 static void	uath_free_rx_data_list(struct uath_softc *);
278 static void	uath_free_tx_data_list(struct uath_softc *);
279 static int	uath_init(struct uath_softc *);
280 static void	uath_stop(struct uath_softc *);
281 static void	uath_parent(struct ieee80211com *);
282 static int	uath_transmit(struct ieee80211com *, struct mbuf *);
283 static void	uath_start(struct uath_softc *);
284 static int	uath_raw_xmit(struct ieee80211_node *, struct mbuf *,
285 		    const struct ieee80211_bpf_params *);
286 static void	uath_scan_start(struct ieee80211com *);
287 static void	uath_scan_end(struct ieee80211com *);
288 static void	uath_set_channel(struct ieee80211com *);
289 static void	uath_update_mcast(struct ieee80211com *);
290 static void	uath_update_promisc(struct ieee80211com *);
291 static int	uath_config(struct uath_softc *, uint32_t, uint32_t);
292 static int	uath_config_multi(struct uath_softc *, uint32_t, const void *,
293 		    int);
294 static int	uath_switch_channel(struct uath_softc *,
295 		    struct ieee80211_channel *);
296 static int	uath_set_rxfilter(struct uath_softc *, uint32_t, uint32_t);
297 static void	uath_watchdog(void *);
298 static void	uath_abort_xfers(struct uath_softc *);
299 static int	uath_dataflush(struct uath_softc *);
300 static int	uath_cmdflush(struct uath_softc *);
301 static int	uath_flush(struct uath_softc *);
302 static int	uath_set_ledstate(struct uath_softc *, int);
303 static int	uath_set_chan(struct uath_softc *, struct ieee80211_channel *);
304 static int	uath_reset_tx_queues(struct uath_softc *);
305 static int	uath_wme_init(struct uath_softc *);
306 static struct uath_data *
307 		uath_getbuf(struct uath_softc *);
308 static int	uath_newstate(struct ieee80211vap *, enum ieee80211_state,
309 		    int);
310 static int	uath_set_key(struct uath_softc *,
311 		    const struct ieee80211_key *, int);
312 static int	uath_set_keys(struct uath_softc *, struct ieee80211vap *);
313 static void	uath_sysctl_node(struct uath_softc *);
314 
315 static int
316 uath_match(device_t dev)
317 {
318 	struct usb_attach_arg *uaa = device_get_ivars(dev);
319 
320 	if (uaa->usb_mode != USB_MODE_HOST)
321 		return (ENXIO);
322 	if (uaa->info.bConfigIndex != UATH_CONFIG_INDEX)
323 		return (ENXIO);
324 	if (uaa->info.bIfaceIndex != UATH_IFACE_INDEX)
325 		return (ENXIO);
326 
327 	return (usbd_lookup_id_by_uaa(uath_devs, sizeof(uath_devs), uaa));
328 }
329 
330 static int
331 uath_attach(device_t dev)
332 {
333 	struct uath_softc *sc = device_get_softc(dev);
334 	struct usb_attach_arg *uaa = device_get_ivars(dev);
335 	struct ieee80211com *ic = &sc->sc_ic;
336 	uint8_t bands[IEEE80211_MODE_BYTES];
337 	uint8_t iface_index = UATH_IFACE_INDEX;		/* XXX */
338 	usb_error_t error;
339 
340 	sc->sc_dev = dev;
341 	sc->sc_udev = uaa->device;
342 #ifdef UATH_DEBUG
343 	sc->sc_debug = uath_debug;
344 #endif
345 	device_set_usb_desc(dev);
346 
347 	/*
348 	 * Only post-firmware devices here.
349 	 */
350 	mtx_init(&sc->sc_mtx, device_get_nameunit(sc->sc_dev), MTX_NETWORK_LOCK,
351 	    MTX_DEF);
352 	callout_init(&sc->stat_ch, 0);
353 	callout_init_mtx(&sc->watchdog_ch, &sc->sc_mtx, 0);
354 	mbufq_init(&sc->sc_snd, ifqmaxlen);
355 
356 	error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
357 	    uath_usbconfig, UATH_N_XFERS, sc, &sc->sc_mtx);
358 	if (error) {
359 		device_printf(dev, "could not allocate USB transfers, "
360 		    "err=%s\n", usbd_errstr(error));
361 		goto fail;
362 	}
363 
364 	sc->sc_cmd_dma_buf =
365 	    usbd_xfer_get_frame_buffer(sc->sc_xfer[UATH_INTR_TX], 0);
366 	sc->sc_tx_dma_buf =
367 	    usbd_xfer_get_frame_buffer(sc->sc_xfer[UATH_BULK_TX], 0);
368 
369 	/*
370 	 * Setup buffers for firmware commands.
371 	 */
372 	error = uath_alloc_cmd_list(sc, sc->sc_cmd);
373 	if (error != 0) {
374 		device_printf(sc->sc_dev,
375 		    "could not allocate Tx command list\n");
376 		goto fail1;
377 	}
378 
379 	/*
380 	 * We're now ready to send+receive firmware commands.
381 	 */
382 	UATH_LOCK(sc);
383 	error = uath_host_available(sc);
384 	if (error != 0) {
385 		device_printf(sc->sc_dev, "could not initialize adapter\n");
386 		goto fail2;
387 	}
388 	error = uath_get_devcap(sc);
389 	if (error != 0) {
390 		device_printf(sc->sc_dev,
391 		    "could not get device capabilities\n");
392 		goto fail2;
393 	}
394 	UATH_UNLOCK(sc);
395 
396 	/* Create device sysctl node. */
397 	uath_sysctl_node(sc);
398 
399 	UATH_LOCK(sc);
400 	error = uath_get_devstatus(sc, ic->ic_macaddr);
401 	if (error != 0) {
402 		device_printf(sc->sc_dev, "could not get device status\n");
403 		goto fail2;
404 	}
405 
406 	/*
407 	 * Allocate xfers for Rx/Tx data pipes.
408 	 */
409 	error = uath_alloc_rx_data_list(sc);
410 	if (error != 0) {
411 		device_printf(sc->sc_dev, "could not allocate Rx data list\n");
412 		goto fail2;
413 	}
414 	error = uath_alloc_tx_data_list(sc);
415 	if (error != 0) {
416 		device_printf(sc->sc_dev, "could not allocate Tx data list\n");
417 		goto fail2;
418 	}
419 	UATH_UNLOCK(sc);
420 
421 	ic->ic_softc = sc;
422 	ic->ic_name = device_get_nameunit(dev);
423 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
424 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
425 
426 	/* set device capabilities */
427 	ic->ic_caps =
428 	    IEEE80211_C_STA |		/* station mode */
429 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
430 	    IEEE80211_C_TXPMGT |	/* tx power management */
431 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
432 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
433 	    IEEE80211_C_WPA |		/* 802.11i */
434 	    IEEE80211_C_BGSCAN |	/* capable of bg scanning */
435 	    IEEE80211_C_TXFRAG;		/* handle tx frags */
436 
437 	/* put a regulatory domain to reveal informations.  */
438 	uath_regdomain = sc->sc_devcap.regDomain;
439 
440 	memset(bands, 0, sizeof(bands));
441 	setbit(bands, IEEE80211_MODE_11B);
442 	setbit(bands, IEEE80211_MODE_11G);
443 	if ((sc->sc_devcap.analog5GhzRevision & 0xf0) == 0x30)
444 		setbit(bands, IEEE80211_MODE_11A);
445 	/* XXX turbo */
446 	ieee80211_init_channels(ic, NULL, bands);
447 
448 	ieee80211_ifattach(ic);
449 	ic->ic_raw_xmit = uath_raw_xmit;
450 	ic->ic_scan_start = uath_scan_start;
451 	ic->ic_scan_end = uath_scan_end;
452 	ic->ic_set_channel = uath_set_channel;
453 	ic->ic_vap_create = uath_vap_create;
454 	ic->ic_vap_delete = uath_vap_delete;
455 	ic->ic_update_mcast = uath_update_mcast;
456 	ic->ic_update_promisc = uath_update_promisc;
457 	ic->ic_transmit = uath_transmit;
458 	ic->ic_parent = uath_parent;
459 
460 	ieee80211_radiotap_attach(ic,
461 	    &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
462 		UATH_TX_RADIOTAP_PRESENT,
463 	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
464 		UATH_RX_RADIOTAP_PRESENT);
465 
466 	if (bootverbose)
467 		ieee80211_announce(ic);
468 
469 	return (0);
470 
471 fail2:	UATH_UNLOCK(sc);
472 	uath_free_cmd_list(sc, sc->sc_cmd);
473 fail1:	usbd_transfer_unsetup(sc->sc_xfer, UATH_N_XFERS);
474 fail:
475 	return (error);
476 }
477 
478 static int
479 uath_detach(device_t dev)
480 {
481 	struct uath_softc *sc = device_get_softc(dev);
482 	struct ieee80211com *ic = &sc->sc_ic;
483 	unsigned int x;
484 
485 	/*
486 	 * Prevent further allocations from RX/TX/CMD
487 	 * data lists and ioctls
488 	 */
489 	UATH_LOCK(sc);
490 	sc->sc_flags |= UATH_FLAG_INVALID;
491 
492 	STAILQ_INIT(&sc->sc_rx_active);
493 	STAILQ_INIT(&sc->sc_rx_inactive);
494 
495 	STAILQ_INIT(&sc->sc_tx_active);
496 	STAILQ_INIT(&sc->sc_tx_inactive);
497 	STAILQ_INIT(&sc->sc_tx_pending);
498 
499 	STAILQ_INIT(&sc->sc_cmd_active);
500 	STAILQ_INIT(&sc->sc_cmd_pending);
501 	STAILQ_INIT(&sc->sc_cmd_waiting);
502 	STAILQ_INIT(&sc->sc_cmd_inactive);
503 
504 	uath_stop(sc);
505 	UATH_UNLOCK(sc);
506 
507 	callout_drain(&sc->stat_ch);
508 	callout_drain(&sc->watchdog_ch);
509 
510 	/* drain USB transfers */
511 	for (x = 0; x != UATH_N_XFERS; x++)
512 		usbd_transfer_drain(sc->sc_xfer[x]);
513 
514 	/* free data buffers */
515 	UATH_LOCK(sc);
516 	uath_free_rx_data_list(sc);
517 	uath_free_tx_data_list(sc);
518 	uath_free_cmd_list(sc, sc->sc_cmd);
519 	UATH_UNLOCK(sc);
520 
521 	/* free USB transfers and some data buffers */
522 	usbd_transfer_unsetup(sc->sc_xfer, UATH_N_XFERS);
523 
524 	ieee80211_ifdetach(ic);
525 	mbufq_drain(&sc->sc_snd);
526 	mtx_destroy(&sc->sc_mtx);
527 	return (0);
528 }
529 
530 static void
531 uath_free_cmd_list(struct uath_softc *sc, struct uath_cmd cmds[])
532 {
533 	int i;
534 
535 	for (i = 0; i != UATH_CMD_LIST_COUNT; i++)
536 		cmds[i].buf = NULL;
537 }
538 
539 static int
540 uath_alloc_cmd_list(struct uath_softc *sc, struct uath_cmd cmds[])
541 {
542 	int i;
543 
544 	STAILQ_INIT(&sc->sc_cmd_active);
545 	STAILQ_INIT(&sc->sc_cmd_pending);
546 	STAILQ_INIT(&sc->sc_cmd_waiting);
547 	STAILQ_INIT(&sc->sc_cmd_inactive);
548 
549 	for (i = 0; i != UATH_CMD_LIST_COUNT; i++) {
550 		struct uath_cmd *cmd = &cmds[i];
551 
552 		cmd->sc = sc;	/* backpointer for callbacks */
553 		cmd->msgid = i;
554 		cmd->buf = ((uint8_t *)sc->sc_cmd_dma_buf) +
555 		    (i * UATH_MAX_CMDSZ);
556 		STAILQ_INSERT_TAIL(&sc->sc_cmd_inactive, cmd, next);
557 		UATH_STAT_INC(sc, st_cmd_inactive);
558 	}
559 	return (0);
560 }
561 
562 static int
563 uath_host_available(struct uath_softc *sc)
564 {
565 	struct uath_cmd_host_available setup;
566 
567 	UATH_ASSERT_LOCKED(sc);
568 
569 	/* inform target the host is available */
570 	setup.sw_ver_major = htobe32(ATH_SW_VER_MAJOR);
571 	setup.sw_ver_minor = htobe32(ATH_SW_VER_MINOR);
572 	setup.sw_ver_patch = htobe32(ATH_SW_VER_PATCH);
573 	setup.sw_ver_build = htobe32(ATH_SW_VER_BUILD);
574 	return uath_cmd_read(sc, WDCMSG_HOST_AVAILABLE,
575 		&setup, sizeof setup, NULL, 0, 0);
576 }
577 
578 #ifdef UATH_DEBUG
579 static void
580 uath_dump_cmd(const uint8_t *buf, int len, char prefix)
581 {
582 	const char *sep = "";
583 	int i;
584 
585 	for (i = 0; i < len; i++) {
586 		if ((i % 16) == 0) {
587 			printf("%s%c ", sep, prefix);
588 			sep = "\n";
589 		}
590 		else if ((i % 4) == 0)
591 			printf(" ");
592 		printf("%02x", buf[i]);
593 	}
594 	printf("\n");
595 }
596 
597 static const char *
598 uath_codename(int code)
599 {
600 	static const char *names[] = {
601 	    "0x00",
602 	    "HOST_AVAILABLE",
603 	    "BIND",
604 	    "TARGET_RESET",
605 	    "TARGET_GET_CAPABILITY",
606 	    "TARGET_SET_CONFIG",
607 	    "TARGET_GET_STATUS",
608 	    "TARGET_GET_STATS",
609 	    "TARGET_START",
610 	    "TARGET_STOP",
611 	    "TARGET_ENABLE",
612 	    "TARGET_DISABLE",
613 	    "CREATE_CONNECTION",
614 	    "UPDATE_CONNECT_ATTR",
615 	    "DELETE_CONNECT",
616 	    "SEND",
617 	    "FLUSH",
618 	    "STATS_UPDATE",
619 	    "BMISS",
620 	    "DEVICE_AVAIL",
621 	    "SEND_COMPLETE",
622 	    "DATA_AVAIL",
623 	    "SET_PWR_MODE",
624 	    "BMISS_ACK",
625 	    "SET_LED_STEADY",
626 	    "SET_LED_BLINK",
627 	    "SETUP_BEACON_DESC",
628 	    "BEACON_INIT",
629 	    "RESET_KEY_CACHE",
630 	    "RESET_KEY_CACHE_ENTRY",
631 	    "SET_KEY_CACHE_ENTRY",
632 	    "SET_DECOMP_MASK",
633 	    "SET_REGULATORY_DOMAIN",
634 	    "SET_LED_STATE",
635 	    "WRITE_ASSOCID",
636 	    "SET_STA_BEACON_TIMERS",
637 	    "GET_TSF",
638 	    "RESET_TSF",
639 	    "SET_ADHOC_MODE",
640 	    "SET_BASIC_RATE",
641 	    "MIB_CONTROL",
642 	    "GET_CHANNEL_DATA",
643 	    "GET_CUR_RSSI",
644 	    "SET_ANTENNA_SWITCH",
645 	    "0x2c", "0x2d", "0x2e",
646 	    "USE_SHORT_SLOT_TIME",
647 	    "SET_POWER_MODE",
648 	    "SETUP_PSPOLL_DESC",
649 	    "SET_RX_MULTICAST_FILTER",
650 	    "RX_FILTER",
651 	    "PER_CALIBRATION",
652 	    "RESET",
653 	    "DISABLE",
654 	    "PHY_DISABLE",
655 	    "SET_TX_POWER_LIMIT",
656 	    "SET_TX_QUEUE_PARAMS",
657 	    "SETUP_TX_QUEUE",
658 	    "RELEASE_TX_QUEUE",
659 	};
660 	static char buf[8];
661 
662 	if (code < nitems(names))
663 		return names[code];
664 	if (code == WDCMSG_SET_DEFAULT_KEY)
665 		return "SET_DEFAULT_KEY";
666 	snprintf(buf, sizeof(buf), "0x%02x", code);
667 	return buf;
668 }
669 #endif
670 
671 /*
672  * Low-level function to send read or write commands to the firmware.
673  */
674 static int
675 uath_cmdsend(struct uath_softc *sc, uint32_t code, const void *idata, int ilen,
676     void *odata, int olen, int flags)
677 {
678 	struct uath_cmd_hdr *hdr;
679 	struct uath_cmd *cmd;
680 	int error;
681 
682 	UATH_ASSERT_LOCKED(sc);
683 
684 	/* grab a xfer */
685 	cmd = uath_get_cmdbuf(sc);
686 	if (cmd == NULL) {
687 		device_printf(sc->sc_dev, "%s: empty inactive queue\n",
688 		    __func__);
689 		return (ENOBUFS);
690 	}
691 	cmd->flags = flags;
692 	/* always bulk-out a multiple of 4 bytes */
693 	cmd->buflen = roundup2(sizeof(struct uath_cmd_hdr) + ilen, 4);
694 
695 	hdr = (struct uath_cmd_hdr *)cmd->buf;
696 	memset(hdr, 0, sizeof(struct uath_cmd_hdr));
697 	hdr->len   = htobe32(cmd->buflen);
698 	hdr->code  = htobe32(code);
699 	hdr->msgid = cmd->msgid;	/* don't care about endianness */
700 	hdr->magic = htobe32((cmd->flags & UATH_CMD_FLAG_MAGIC) ? 1 << 24 : 0);
701 	memcpy((uint8_t *)(hdr + 1), idata, ilen);
702 
703 #ifdef UATH_DEBUG
704 	if (sc->sc_debug & UATH_DEBUG_CMDS) {
705 		printf("%s: send  %s [flags 0x%x] olen %d\n",
706 		    __func__, uath_codename(code), cmd->flags, olen);
707 		if (sc->sc_debug & UATH_DEBUG_CMDS_DUMP)
708 			uath_dump_cmd(cmd->buf, cmd->buflen, '+');
709 	}
710 #endif
711 	cmd->odata = odata;
712 	KASSERT(odata == NULL ||
713 	    olen < UATH_MAX_CMDSZ - sizeof(*hdr) + sizeof(uint32_t),
714 	    ("odata %p olen %u", odata, olen));
715 	cmd->olen = olen;
716 
717 	STAILQ_INSERT_TAIL(&sc->sc_cmd_pending, cmd, next);
718 	UATH_STAT_INC(sc, st_cmd_pending);
719 	usbd_transfer_start(sc->sc_xfer[UATH_INTR_TX]);
720 
721 	if (cmd->flags & UATH_CMD_FLAG_READ) {
722 		usbd_transfer_start(sc->sc_xfer[UATH_INTR_RX]);
723 
724 		/* wait at most two seconds for command reply */
725 		error = mtx_sleep(cmd, &sc->sc_mtx, 0, "uathcmd", 2 * hz);
726 		cmd->odata = NULL;	/* in case reply comes too late */
727 		if (error != 0) {
728 			device_printf(sc->sc_dev, "timeout waiting for reply "
729 			    "to cmd 0x%x (%u)\n", code, code);
730 		} else if (cmd->olen != olen) {
731 			device_printf(sc->sc_dev, "unexpected reply data count "
732 			    "to cmd 0x%x (%u), got %u, expected %u\n",
733 			    code, code, cmd->olen, olen);
734 			error = EINVAL;
735 		}
736 		return (error);
737 	}
738 	return (0);
739 }
740 
741 static int
742 uath_cmd_read(struct uath_softc *sc, uint32_t code, const void *idata,
743     int ilen, void *odata, int olen, int flags)
744 {
745 
746 	flags |= UATH_CMD_FLAG_READ;
747 	return uath_cmdsend(sc, code, idata, ilen, odata, olen, flags);
748 }
749 
750 static int
751 uath_cmd_write(struct uath_softc *sc, uint32_t code, const void *data, int len,
752     int flags)
753 {
754 
755 	flags &= ~UATH_CMD_FLAG_READ;
756 	return uath_cmdsend(sc, code, data, len, NULL, 0, flags);
757 }
758 
759 static struct uath_cmd *
760 uath_get_cmdbuf(struct uath_softc *sc)
761 {
762 	struct uath_cmd *uc;
763 
764 	UATH_ASSERT_LOCKED(sc);
765 
766 	uc = STAILQ_FIRST(&sc->sc_cmd_inactive);
767 	if (uc != NULL) {
768 		STAILQ_REMOVE_HEAD(&sc->sc_cmd_inactive, next);
769 		UATH_STAT_DEC(sc, st_cmd_inactive);
770 	} else
771 		uc = NULL;
772 	if (uc == NULL)
773 		DPRINTF(sc, UATH_DEBUG_XMIT, "%s: %s\n", __func__,
774 		    "out of command xmit buffers");
775 	return (uc);
776 }
777 
778 /*
779  * This function is called periodically (every second) when associated to
780  * query device statistics.
781  */
782 static void
783 uath_stat(void *arg)
784 {
785 	struct uath_softc *sc = arg;
786 	int error;
787 
788 	UATH_LOCK(sc);
789 	/*
790 	 * Send request for statistics asynchronously. The timer will be
791 	 * restarted when we'll get the stats notification.
792 	 */
793 	error = uath_cmd_write(sc, WDCMSG_TARGET_GET_STATS, NULL, 0,
794 	    UATH_CMD_FLAG_ASYNC);
795 	if (error != 0) {
796 		device_printf(sc->sc_dev,
797 		    "could not query stats, error %d\n", error);
798 	}
799 	UATH_UNLOCK(sc);
800 }
801 
802 static int
803 uath_get_capability(struct uath_softc *sc, uint32_t cap, uint32_t *val)
804 {
805 	int error;
806 
807 	cap = htobe32(cap);
808 	error = uath_cmd_read(sc, WDCMSG_TARGET_GET_CAPABILITY,
809 	    &cap, sizeof cap, val, sizeof(uint32_t), UATH_CMD_FLAG_MAGIC);
810 	if (error != 0) {
811 		device_printf(sc->sc_dev, "could not read capability %u\n",
812 		    be32toh(cap));
813 		return (error);
814 	}
815 	*val = be32toh(*val);
816 	return (error);
817 }
818 
819 static int
820 uath_get_devcap(struct uath_softc *sc)
821 {
822 #define	GETCAP(x, v) do {				\
823 	error = uath_get_capability(sc, x, &v);		\
824 	if (error != 0)					\
825 		return (error);				\
826 	DPRINTF(sc, UATH_DEBUG_DEVCAP,			\
827 	    "%s: %s=0x%08x\n", __func__, #x, v);	\
828 } while (0)
829 	struct uath_devcap *cap = &sc->sc_devcap;
830 	int error;
831 
832 	/* collect device capabilities */
833 	GETCAP(CAP_TARGET_VERSION, cap->targetVersion);
834 	GETCAP(CAP_TARGET_REVISION, cap->targetRevision);
835 	GETCAP(CAP_MAC_VERSION, cap->macVersion);
836 	GETCAP(CAP_MAC_REVISION, cap->macRevision);
837 	GETCAP(CAP_PHY_REVISION, cap->phyRevision);
838 	GETCAP(CAP_ANALOG_5GHz_REVISION, cap->analog5GhzRevision);
839 	GETCAP(CAP_ANALOG_2GHz_REVISION, cap->analog2GhzRevision);
840 
841 	GETCAP(CAP_REG_DOMAIN, cap->regDomain);
842 	GETCAP(CAP_REG_CAP_BITS, cap->regCapBits);
843 #if 0
844 	/* NB: not supported in rev 1.5 */
845 	GETCAP(CAP_COUNTRY_CODE, cap->countryCode);
846 #endif
847 	GETCAP(CAP_WIRELESS_MODES, cap->wirelessModes);
848 	GETCAP(CAP_CHAN_SPREAD_SUPPORT, cap->chanSpreadSupport);
849 	GETCAP(CAP_COMPRESS_SUPPORT, cap->compressSupport);
850 	GETCAP(CAP_BURST_SUPPORT, cap->burstSupport);
851 	GETCAP(CAP_FAST_FRAMES_SUPPORT, cap->fastFramesSupport);
852 	GETCAP(CAP_CHAP_TUNING_SUPPORT, cap->chapTuningSupport);
853 	GETCAP(CAP_TURBOG_SUPPORT, cap->turboGSupport);
854 	GETCAP(CAP_TURBO_PRIME_SUPPORT, cap->turboPrimeSupport);
855 	GETCAP(CAP_DEVICE_TYPE, cap->deviceType);
856 	GETCAP(CAP_WME_SUPPORT, cap->wmeSupport);
857 	GETCAP(CAP_TOTAL_QUEUES, cap->numTxQueues);
858 	GETCAP(CAP_CONNECTION_ID_MAX, cap->connectionIdMax);
859 
860 	GETCAP(CAP_LOW_5GHZ_CHAN, cap->low5GhzChan);
861 	GETCAP(CAP_HIGH_5GHZ_CHAN, cap->high5GhzChan);
862 	GETCAP(CAP_LOW_2GHZ_CHAN, cap->low2GhzChan);
863 	GETCAP(CAP_HIGH_2GHZ_CHAN, cap->high2GhzChan);
864 	GETCAP(CAP_TWICE_ANTENNAGAIN_5G, cap->twiceAntennaGain5G);
865 	GETCAP(CAP_TWICE_ANTENNAGAIN_2G, cap->twiceAntennaGain2G);
866 
867 	GETCAP(CAP_CIPHER_AES_CCM, cap->supportCipherAES_CCM);
868 	GETCAP(CAP_CIPHER_TKIP, cap->supportCipherTKIP);
869 	GETCAP(CAP_MIC_TKIP, cap->supportMicTKIP);
870 
871 	cap->supportCipherWEP = 1;	/* NB: always available */
872 
873 	return (0);
874 }
875 
876 static int
877 uath_get_devstatus(struct uath_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
878 {
879 	int error;
880 
881 	/* retrieve MAC address */
882 	error = uath_get_status(sc, ST_MAC_ADDR, macaddr, IEEE80211_ADDR_LEN);
883 	if (error != 0) {
884 		device_printf(sc->sc_dev, "could not read MAC address\n");
885 		return (error);
886 	}
887 
888 	error = uath_get_status(sc, ST_SERIAL_NUMBER,
889 	    &sc->sc_serial[0], sizeof(sc->sc_serial));
890 	if (error != 0) {
891 		device_printf(sc->sc_dev,
892 		    "could not read device serial number\n");
893 		return (error);
894 	}
895 	return (0);
896 }
897 
898 static int
899 uath_get_status(struct uath_softc *sc, uint32_t which, void *odata, int olen)
900 {
901 	int error;
902 
903 	which = htobe32(which);
904 	error = uath_cmd_read(sc, WDCMSG_TARGET_GET_STATUS,
905 	    &which, sizeof(which), odata, olen, UATH_CMD_FLAG_MAGIC);
906 	if (error != 0)
907 		device_printf(sc->sc_dev,
908 		    "could not read EEPROM offset 0x%02x\n", be32toh(which));
909 	return (error);
910 }
911 
912 static void
913 uath_free_data_list(struct uath_softc *sc, struct uath_data data[], int ndata,
914     int fillmbuf)
915 {
916 	int i;
917 
918 	for (i = 0; i < ndata; i++) {
919 		struct uath_data *dp = &data[i];
920 
921 		if (fillmbuf == 1) {
922 			if (dp->m != NULL) {
923 				m_freem(dp->m);
924 				dp->m = NULL;
925 				dp->buf = NULL;
926 			}
927 		} else {
928 			dp->buf = NULL;
929 		}
930 		if (dp->ni != NULL) {
931 			ieee80211_free_node(dp->ni);
932 			dp->ni = NULL;
933 		}
934 	}
935 }
936 
937 static int
938 uath_alloc_data_list(struct uath_softc *sc, struct uath_data data[],
939     int ndata, int maxsz, void *dma_buf)
940 {
941 	int i, error;
942 
943 	for (i = 0; i < ndata; i++) {
944 		struct uath_data *dp = &data[i];
945 
946 		dp->sc = sc;
947 		if (dma_buf == NULL) {
948 			/* XXX check maxsz */
949 			dp->m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
950 			if (dp->m == NULL) {
951 				device_printf(sc->sc_dev,
952 				    "could not allocate rx mbuf\n");
953 				error = ENOMEM;
954 				goto fail;
955 			}
956 			dp->buf = mtod(dp->m, uint8_t *);
957 		} else {
958 			dp->m = NULL;
959 			dp->buf = ((uint8_t *)dma_buf) + (i * maxsz);
960 		}
961 		dp->ni = NULL;
962 	}
963 
964 	return (0);
965 
966 fail:	uath_free_data_list(sc, data, ndata, 1 /* free mbufs */);
967 	return (error);
968 }
969 
970 static int
971 uath_alloc_rx_data_list(struct uath_softc *sc)
972 {
973 	int error, i;
974 
975 	/* XXX is it enough to store the RX packet with MCLBYTES bytes?  */
976 	error = uath_alloc_data_list(sc,
977 	    sc->sc_rx, UATH_RX_DATA_LIST_COUNT, MCLBYTES,
978 	    NULL /* setup mbufs */);
979 	if (error != 0)
980 		return (error);
981 
982 	STAILQ_INIT(&sc->sc_rx_active);
983 	STAILQ_INIT(&sc->sc_rx_inactive);
984 
985 	for (i = 0; i < UATH_RX_DATA_LIST_COUNT; i++) {
986 		STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i],
987 		    next);
988 		UATH_STAT_INC(sc, st_rx_inactive);
989 	}
990 
991 	return (0);
992 }
993 
994 static int
995 uath_alloc_tx_data_list(struct uath_softc *sc)
996 {
997 	int error, i;
998 
999 	error = uath_alloc_data_list(sc,
1000 	    sc->sc_tx, UATH_TX_DATA_LIST_COUNT, UATH_MAX_TXBUFSZ,
1001 	    sc->sc_tx_dma_buf);
1002 	if (error != 0)
1003 		return (error);
1004 
1005 	STAILQ_INIT(&sc->sc_tx_active);
1006 	STAILQ_INIT(&sc->sc_tx_inactive);
1007 	STAILQ_INIT(&sc->sc_tx_pending);
1008 
1009 	for (i = 0; i < UATH_TX_DATA_LIST_COUNT; i++) {
1010 		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i],
1011 		    next);
1012 		UATH_STAT_INC(sc, st_tx_inactive);
1013 	}
1014 
1015 	return (0);
1016 }
1017 
1018 static void
1019 uath_free_rx_data_list(struct uath_softc *sc)
1020 {
1021 	uath_free_data_list(sc, sc->sc_rx, UATH_RX_DATA_LIST_COUNT,
1022 	    1 /* free mbufs */);
1023 }
1024 
1025 static void
1026 uath_free_tx_data_list(struct uath_softc *sc)
1027 {
1028 	uath_free_data_list(sc, sc->sc_tx, UATH_TX_DATA_LIST_COUNT,
1029 	    0 /* no mbufs */);
1030 }
1031 
1032 static struct ieee80211vap *
1033 uath_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
1034     enum ieee80211_opmode opmode, int flags,
1035     const uint8_t bssid[IEEE80211_ADDR_LEN],
1036     const uint8_t mac[IEEE80211_ADDR_LEN])
1037 {
1038 	struct uath_vap *uvp;
1039 	struct ieee80211vap *vap;
1040 
1041 	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
1042 		return (NULL);
1043 	uvp =  malloc(sizeof(struct uath_vap), M_80211_VAP, M_WAITOK | M_ZERO);
1044 	vap = &uvp->vap;
1045 	/* enable s/w bmiss handling for sta mode */
1046 
1047 	if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
1048 	    flags | IEEE80211_CLONE_NOBEACONS, bssid) != 0) {
1049 		/* out of memory */
1050 		free(uvp, M_80211_VAP);
1051 		return (NULL);
1052 	}
1053 
1054 	/* override state transition machine */
1055 	uvp->newstate = vap->iv_newstate;
1056 	vap->iv_newstate = uath_newstate;
1057 
1058 	/* complete setup */
1059 	ieee80211_vap_attach(vap, ieee80211_media_change,
1060 	    ieee80211_media_status, mac);
1061 	ic->ic_opmode = opmode;
1062 	return (vap);
1063 }
1064 
1065 static void
1066 uath_vap_delete(struct ieee80211vap *vap)
1067 {
1068 	struct uath_vap *uvp = UATH_VAP(vap);
1069 
1070 	ieee80211_vap_detach(vap);
1071 	free(uvp, M_80211_VAP);
1072 }
1073 
1074 static int
1075 uath_init(struct uath_softc *sc)
1076 {
1077 	struct ieee80211com *ic = &sc->sc_ic;
1078 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1079 	uint32_t val;
1080 	int error;
1081 
1082 	UATH_ASSERT_LOCKED(sc);
1083 
1084 	if (sc->sc_flags & UATH_FLAG_INITDONE)
1085 		uath_stop(sc);
1086 
1087 	/* reset variables */
1088 	sc->sc_intrx_nextnum = sc->sc_msgid = 0;
1089 
1090 	val = htobe32(0);
1091 	uath_cmd_write(sc, WDCMSG_BIND, &val, sizeof val, 0);
1092 
1093 	/* set MAC address */
1094 	uath_config_multi(sc, CFG_MAC_ADDR,
1095 	    vap ? vap->iv_myaddr : ic->ic_macaddr, IEEE80211_ADDR_LEN);
1096 
1097 	/* XXX honor net80211 state */
1098 	uath_config(sc, CFG_RATE_CONTROL_ENABLE, 0x00000001);
1099 	uath_config(sc, CFG_DIVERSITY_CTL, 0x00000001);
1100 	uath_config(sc, CFG_ABOLT, 0x0000003f);
1101 	uath_config(sc, CFG_WME_ENABLED, 0x00000001);
1102 
1103 	uath_config(sc, CFG_SERVICE_TYPE, 1);
1104 	uath_config(sc, CFG_TP_SCALE, 0x00000000);
1105 	uath_config(sc, CFG_TPC_HALF_DBM5, 0x0000003c);
1106 	uath_config(sc, CFG_TPC_HALF_DBM2, 0x0000003c);
1107 	uath_config(sc, CFG_OVERRD_TX_POWER, 0x00000000);
1108 	uath_config(sc, CFG_GMODE_PROTECTION, 0x00000000);
1109 	uath_config(sc, CFG_GMODE_PROTECT_RATE_INDEX, 0x00000003);
1110 	uath_config(sc, CFG_PROTECTION_TYPE, 0x00000000);
1111 	uath_config(sc, CFG_MODE_CTS, 0x00000002);
1112 
1113 	error = uath_cmd_read(sc, WDCMSG_TARGET_START, NULL, 0,
1114 	    &val, sizeof(val), UATH_CMD_FLAG_MAGIC);
1115 	if (error) {
1116 		device_printf(sc->sc_dev,
1117 		    "could not start target, error %d\n", error);
1118 		goto fail;
1119 	}
1120 	DPRINTF(sc, UATH_DEBUG_INIT, "%s returns handle: 0x%x\n",
1121 	    uath_codename(WDCMSG_TARGET_START), be32toh(val));
1122 
1123 	/* set default channel */
1124 	error = uath_switch_channel(sc, ic->ic_curchan);
1125 	if (error) {
1126 		device_printf(sc->sc_dev,
1127 		    "could not switch channel, error %d\n", error);
1128 		goto fail;
1129 	}
1130 
1131 	val = htobe32(TARGET_DEVICE_AWAKE);
1132 	uath_cmd_write(sc, WDCMSG_SET_PWR_MODE, &val, sizeof val, 0);
1133 	/* XXX? check */
1134 	uath_cmd_write(sc, WDCMSG_RESET_KEY_CACHE, NULL, 0, 0);
1135 
1136 	usbd_transfer_start(sc->sc_xfer[UATH_BULK_RX]);
1137 	/* enable Rx */
1138 	uath_set_rxfilter(sc, 0x0, UATH_FILTER_OP_INIT);
1139 	uath_set_rxfilter(sc,
1140 	    UATH_FILTER_RX_UCAST | UATH_FILTER_RX_MCAST |
1141 	    UATH_FILTER_RX_BCAST | UATH_FILTER_RX_BEACON,
1142 	    UATH_FILTER_OP_SET);
1143 
1144 	sc->sc_flags |= UATH_FLAG_INITDONE;
1145 
1146 	callout_reset(&sc->watchdog_ch, hz, uath_watchdog, sc);
1147 
1148 	return (0);
1149 
1150 fail:
1151 	uath_stop(sc);
1152 	return (error);
1153 }
1154 
1155 static void
1156 uath_stop(struct uath_softc *sc)
1157 {
1158 
1159 	UATH_ASSERT_LOCKED(sc);
1160 
1161 	sc->sc_flags &= ~UATH_FLAG_INITDONE;
1162 
1163 	callout_stop(&sc->stat_ch);
1164 	callout_stop(&sc->watchdog_ch);
1165 	sc->sc_tx_timer = 0;
1166 	/* abort pending transmits  */
1167 	uath_abort_xfers(sc);
1168 	/* flush data & control requests into the target  */
1169 	(void)uath_flush(sc);
1170 	/* set a LED status to the disconnected.  */
1171 	uath_set_ledstate(sc, 0);
1172 	/* stop the target  */
1173 	uath_cmd_write(sc, WDCMSG_TARGET_STOP, NULL, 0, 0);
1174 }
1175 
1176 static int
1177 uath_config(struct uath_softc *sc, uint32_t reg, uint32_t val)
1178 {
1179 	struct uath_write_mac write;
1180 	int error;
1181 
1182 	write.reg = htobe32(reg);
1183 	write.len = htobe32(0);	/* 0 = single write */
1184 	*(uint32_t *)write.data = htobe32(val);
1185 
1186 	error = uath_cmd_write(sc, WDCMSG_TARGET_SET_CONFIG, &write,
1187 	    3 * sizeof (uint32_t), 0);
1188 	if (error != 0) {
1189 		device_printf(sc->sc_dev, "could not write register 0x%02x\n",
1190 		    reg);
1191 	}
1192 	return (error);
1193 }
1194 
1195 static int
1196 uath_config_multi(struct uath_softc *sc, uint32_t reg, const void *data,
1197     int len)
1198 {
1199 	struct uath_write_mac write;
1200 	int error;
1201 
1202 	write.reg = htobe32(reg);
1203 	write.len = htobe32(len);
1204 	bcopy(data, write.data, len);
1205 
1206 	/* properly handle the case where len is zero (reset) */
1207 	error = uath_cmd_write(sc, WDCMSG_TARGET_SET_CONFIG, &write,
1208 	    (len == 0) ? sizeof (uint32_t) : 2 * sizeof (uint32_t) + len, 0);
1209 	if (error != 0) {
1210 		device_printf(sc->sc_dev,
1211 		    "could not write %d bytes to register 0x%02x\n", len, reg);
1212 	}
1213 	return (error);
1214 }
1215 
1216 static int
1217 uath_switch_channel(struct uath_softc *sc, struct ieee80211_channel *c)
1218 {
1219 	int error;
1220 
1221 	UATH_ASSERT_LOCKED(sc);
1222 
1223 	/* set radio frequency */
1224 	error = uath_set_chan(sc, c);
1225 	if (error) {
1226 		device_printf(sc->sc_dev,
1227 		    "could not set channel, error %d\n", error);
1228 		goto failed;
1229 	}
1230 	/* reset Tx rings */
1231 	error = uath_reset_tx_queues(sc);
1232 	if (error) {
1233 		device_printf(sc->sc_dev,
1234 		    "could not reset Tx queues, error %d\n", error);
1235 		goto failed;
1236 	}
1237 	/* set Tx rings WME properties */
1238 	error = uath_wme_init(sc);
1239 	if (error) {
1240 		device_printf(sc->sc_dev,
1241 		    "could not init Tx queues, error %d\n", error);
1242 		goto failed;
1243 	}
1244 	error = uath_set_ledstate(sc, 0);
1245 	if (error) {
1246 		device_printf(sc->sc_dev,
1247 		    "could not set led state, error %d\n", error);
1248 		goto failed;
1249 	}
1250 	error = uath_flush(sc);
1251 	if (error) {
1252 		device_printf(sc->sc_dev,
1253 		    "could not flush pipes, error %d\n", error);
1254 		goto failed;
1255 	}
1256 failed:
1257 	return (error);
1258 }
1259 
1260 static int
1261 uath_set_rxfilter(struct uath_softc *sc, uint32_t bits, uint32_t op)
1262 {
1263 	struct uath_cmd_rx_filter rxfilter;
1264 
1265 	rxfilter.bits = htobe32(bits);
1266 	rxfilter.op = htobe32(op);
1267 
1268 	DPRINTF(sc, UATH_DEBUG_RECV | UATH_DEBUG_RECV_ALL,
1269 	    "setting Rx filter=0x%x flags=0x%x\n", bits, op);
1270 	return uath_cmd_write(sc, WDCMSG_RX_FILTER, &rxfilter,
1271 	    sizeof rxfilter, 0);
1272 }
1273 
1274 static void
1275 uath_watchdog(void *arg)
1276 {
1277 	struct uath_softc *sc = arg;
1278 	struct ieee80211com *ic = &sc->sc_ic;
1279 
1280 	if (sc->sc_tx_timer > 0) {
1281 		if (--sc->sc_tx_timer == 0) {
1282 			device_printf(sc->sc_dev, "device timeout\n");
1283 			/*uath_init(sc); XXX needs a process context! */
1284 			counter_u64_add(ic->ic_oerrors, 1);
1285 			return;
1286 		}
1287 		callout_reset(&sc->watchdog_ch, hz, uath_watchdog, sc);
1288 	}
1289 }
1290 
1291 static void
1292 uath_abort_xfers(struct uath_softc *sc)
1293 {
1294 	int i;
1295 
1296 	UATH_ASSERT_LOCKED(sc);
1297 	/* abort any pending transfers */
1298 	for (i = 0; i < UATH_N_XFERS; i++)
1299 		usbd_transfer_stop(sc->sc_xfer[i]);
1300 }
1301 
1302 static int
1303 uath_flush(struct uath_softc *sc)
1304 {
1305 	int error;
1306 
1307 	error = uath_dataflush(sc);
1308 	if (error != 0)
1309 		goto failed;
1310 
1311 	error = uath_cmdflush(sc);
1312 	if (error != 0)
1313 		goto failed;
1314 
1315 failed:
1316 	return (error);
1317 }
1318 
1319 static int
1320 uath_cmdflush(struct uath_softc *sc)
1321 {
1322 
1323 	return uath_cmd_write(sc, WDCMSG_FLUSH, NULL, 0, 0);
1324 }
1325 
1326 static int
1327 uath_dataflush(struct uath_softc *sc)
1328 {
1329 	struct uath_data *data;
1330 	struct uath_chunk *chunk;
1331 	struct uath_tx_desc *desc;
1332 
1333 	UATH_ASSERT_LOCKED(sc);
1334 
1335 	data = uath_getbuf(sc);
1336 	if (data == NULL)
1337 		return (ENOBUFS);
1338 	data->buflen = sizeof(struct uath_chunk) + sizeof(struct uath_tx_desc);
1339 	data->m = NULL;
1340 	data->ni = NULL;
1341 	chunk = (struct uath_chunk *)data->buf;
1342 	desc = (struct uath_tx_desc *)(chunk + 1);
1343 
1344 	/* one chunk only */
1345 	chunk->seqnum = 0;
1346 	chunk->flags = UATH_CFLAGS_FINAL;
1347 	chunk->length = htobe16(sizeof (struct uath_tx_desc));
1348 
1349 	memset(desc, 0, sizeof(struct uath_tx_desc));
1350 	desc->msglen = htobe32(sizeof(struct uath_tx_desc));
1351 	desc->msgid  = (sc->sc_msgid++) + 1; /* don't care about endianness */
1352 	desc->type   = htobe32(WDCMSG_FLUSH);
1353 	desc->txqid  = htobe32(0);
1354 	desc->connid = htobe32(0);
1355 	desc->flags  = htobe32(0);
1356 
1357 #ifdef UATH_DEBUG
1358 	if (sc->sc_debug & UATH_DEBUG_CMDS) {
1359 		DPRINTF(sc, UATH_DEBUG_RESET, "send flush ix %d\n",
1360 		    desc->msgid);
1361 		if (sc->sc_debug & UATH_DEBUG_CMDS_DUMP)
1362 			uath_dump_cmd(data->buf, data->buflen, '+');
1363 	}
1364 #endif
1365 
1366 	STAILQ_INSERT_TAIL(&sc->sc_tx_pending, data, next);
1367 	UATH_STAT_INC(sc, st_tx_pending);
1368 	sc->sc_tx_timer = 5;
1369 	usbd_transfer_start(sc->sc_xfer[UATH_BULK_TX]);
1370 
1371 	return (0);
1372 }
1373 
1374 static struct uath_data *
1375 _uath_getbuf(struct uath_softc *sc)
1376 {
1377 	struct uath_data *bf;
1378 
1379 	bf = STAILQ_FIRST(&sc->sc_tx_inactive);
1380 	if (bf != NULL) {
1381 		STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next);
1382 		UATH_STAT_DEC(sc, st_tx_inactive);
1383 	} else
1384 		bf = NULL;
1385 	if (bf == NULL)
1386 		DPRINTF(sc, UATH_DEBUG_XMIT, "%s: %s\n", __func__,
1387 		    "out of xmit buffers");
1388 	return (bf);
1389 }
1390 
1391 static struct uath_data *
1392 uath_getbuf(struct uath_softc *sc)
1393 {
1394 	struct uath_data *bf;
1395 
1396 	UATH_ASSERT_LOCKED(sc);
1397 
1398 	bf = _uath_getbuf(sc);
1399 	if (bf == NULL)
1400 		DPRINTF(sc, UATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
1401 	return (bf);
1402 }
1403 
1404 static int
1405 uath_set_ledstate(struct uath_softc *sc, int connected)
1406 {
1407 
1408 	DPRINTF(sc, UATH_DEBUG_LED,
1409 	    "set led state %sconnected\n", connected ? "" : "!");
1410 	connected = htobe32(connected);
1411 	return uath_cmd_write(sc, WDCMSG_SET_LED_STATE,
1412 	     &connected, sizeof connected, 0);
1413 }
1414 
1415 static int
1416 uath_set_chan(struct uath_softc *sc, struct ieee80211_channel *c)
1417 {
1418 #ifdef UATH_DEBUG
1419 	struct ieee80211com *ic = &sc->sc_ic;
1420 #endif
1421 	struct uath_cmd_reset reset;
1422 
1423 	memset(&reset, 0, sizeof(reset));
1424 	if (IEEE80211_IS_CHAN_2GHZ(c))
1425 		reset.flags |= htobe32(UATH_CHAN_2GHZ);
1426 	if (IEEE80211_IS_CHAN_5GHZ(c))
1427 		reset.flags |= htobe32(UATH_CHAN_5GHZ);
1428 	/* NB: 11g =>'s 11b so don't specify both OFDM and CCK */
1429 	if (IEEE80211_IS_CHAN_OFDM(c))
1430 		reset.flags |= htobe32(UATH_CHAN_OFDM);
1431 	else if (IEEE80211_IS_CHAN_CCK(c))
1432 		reset.flags |= htobe32(UATH_CHAN_CCK);
1433 	/* turbo can be used in either 2GHz or 5GHz */
1434 	if (c->ic_flags & IEEE80211_CHAN_TURBO)
1435 		reset.flags |= htobe32(UATH_CHAN_TURBO);
1436 	reset.freq = htobe32(c->ic_freq);
1437 	reset.maxrdpower = htobe32(50);	/* XXX */
1438 	reset.channelchange = htobe32(1);
1439 	reset.keeprccontent = htobe32(0);
1440 
1441 	DPRINTF(sc, UATH_DEBUG_CHANNEL, "set channel %d, flags 0x%x freq %u\n",
1442 	    ieee80211_chan2ieee(ic, c),
1443 	    be32toh(reset.flags), be32toh(reset.freq));
1444 	return uath_cmd_write(sc, WDCMSG_RESET, &reset, sizeof reset, 0);
1445 }
1446 
1447 static int
1448 uath_reset_tx_queues(struct uath_softc *sc)
1449 {
1450 	int ac, error;
1451 
1452 	DPRINTF(sc, UATH_DEBUG_RESET, "%s: reset Tx queues\n", __func__);
1453 	for (ac = 0; ac < 4; ac++) {
1454 		const uint32_t qid = htobe32(ac);
1455 
1456 		error = uath_cmd_write(sc, WDCMSG_RELEASE_TX_QUEUE, &qid,
1457 		    sizeof qid, 0);
1458 		if (error != 0)
1459 			break;
1460 	}
1461 	return (error);
1462 }
1463 
1464 static int
1465 uath_wme_init(struct uath_softc *sc)
1466 {
1467 	/* XXX get from net80211 */
1468 	static const struct uath_wme_settings uath_wme_11g[4] = {
1469 		{ 7, 4, 10,  0, 0 },	/* Background */
1470 		{ 3, 4, 10,  0, 0 },	/* Best-Effort */
1471 		{ 3, 3,  4, 26, 0 },	/* Video */
1472 		{ 2, 2,  3, 47, 0 }	/* Voice */
1473 	};
1474 	struct uath_cmd_txq_setup qinfo;
1475 	int ac, error;
1476 
1477 	DPRINTF(sc, UATH_DEBUG_WME, "%s: setup Tx queues\n", __func__);
1478 	for (ac = 0; ac < 4; ac++) {
1479 		qinfo.qid		= htobe32(ac);
1480 		qinfo.len		= htobe32(sizeof(qinfo.attr));
1481 		qinfo.attr.priority	= htobe32(ac);	/* XXX */
1482 		qinfo.attr.aifs		= htobe32(uath_wme_11g[ac].aifsn);
1483 		qinfo.attr.logcwmin	= htobe32(uath_wme_11g[ac].logcwmin);
1484 		qinfo.attr.logcwmax	= htobe32(uath_wme_11g[ac].logcwmax);
1485 		qinfo.attr.bursttime	= htobe32(IEEE80211_TXOP_TO_US(
1486 					    uath_wme_11g[ac].txop));
1487 		qinfo.attr.mode		= htobe32(uath_wme_11g[ac].acm);/*XXX? */
1488 		qinfo.attr.qflags	= htobe32(1);	/* XXX? */
1489 
1490 		error = uath_cmd_write(sc, WDCMSG_SETUP_TX_QUEUE, &qinfo,
1491 		    sizeof qinfo, 0);
1492 		if (error != 0)
1493 			break;
1494 	}
1495 	return (error);
1496 }
1497 
1498 static void
1499 uath_parent(struct ieee80211com *ic)
1500 {
1501 	struct uath_softc *sc = ic->ic_softc;
1502 	int startall = 0;
1503 
1504 	UATH_LOCK(sc);
1505 	if (sc->sc_flags & UATH_FLAG_INVALID) {
1506 		UATH_UNLOCK(sc);
1507 		return;
1508 	}
1509 
1510 	if (ic->ic_nrunning > 0) {
1511 		if (!(sc->sc_flags & UATH_FLAG_INITDONE)) {
1512 			uath_init(sc);
1513 			startall = 1;
1514 		}
1515 	} else if (sc->sc_flags & UATH_FLAG_INITDONE)
1516 		uath_stop(sc);
1517 	UATH_UNLOCK(sc);
1518 	if (startall)
1519 		ieee80211_start_all(ic);
1520 }
1521 
1522 static int
1523 uath_tx_start(struct uath_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1524     struct uath_data *data)
1525 {
1526 	struct ieee80211vap *vap = ni->ni_vap;
1527 	struct uath_chunk *chunk;
1528 	struct uath_tx_desc *desc;
1529 	const struct ieee80211_frame *wh;
1530 	struct ieee80211_key *k;
1531 	int framelen, msglen;
1532 
1533 	UATH_ASSERT_LOCKED(sc);
1534 
1535 	data->ni = ni;
1536 	data->m = m0;
1537 	chunk = (struct uath_chunk *)data->buf;
1538 	desc = (struct uath_tx_desc *)(chunk + 1);
1539 
1540 	if (ieee80211_radiotap_active_vap(vap)) {
1541 		struct uath_tx_radiotap_header *tap = &sc->sc_txtap;
1542 
1543 		tap->wt_flags = 0;
1544 		if (m0->m_flags & M_FRAG)
1545 			tap->wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
1546 
1547 		ieee80211_radiotap_tx(vap, m0);
1548 	}
1549 
1550 	wh = mtod(m0, struct ieee80211_frame *);
1551 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1552 		k = ieee80211_crypto_encap(ni, m0);
1553 		if (k == NULL) {
1554 			m_freem(m0);
1555 			return (ENOBUFS);
1556 		}
1557 
1558 		/* packet header may have moved, reset our local pointer */
1559 		wh = mtod(m0, struct ieee80211_frame *);
1560 	}
1561 	m_copydata(m0, 0, m0->m_pkthdr.len, (uint8_t *)(desc + 1));
1562 
1563 	framelen = m0->m_pkthdr.len + IEEE80211_CRC_LEN;
1564 	msglen = framelen + sizeof (struct uath_tx_desc);
1565 	data->buflen = msglen + sizeof (struct uath_chunk);
1566 
1567 	/* one chunk only for now */
1568 	chunk->seqnum = sc->sc_seqnum++;
1569 	chunk->flags = (m0->m_flags & M_FRAG) ? 0 : UATH_CFLAGS_FINAL;
1570 	if (m0->m_flags & M_LASTFRAG)
1571 		chunk->flags |= UATH_CFLAGS_FINAL;
1572 	chunk->flags = UATH_CFLAGS_FINAL;
1573 	chunk->length = htobe16(msglen);
1574 
1575 	/* fill Tx descriptor */
1576 	desc->msglen = htobe32(msglen);
1577 	/* NB: to get UATH_TX_NOTIFY reply, `msgid' must be larger than 0  */
1578 	desc->msgid  = (sc->sc_msgid++) + 1; /* don't care about endianness */
1579 	desc->type   = htobe32(WDCMSG_SEND);
1580 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
1581 	case IEEE80211_FC0_TYPE_CTL:
1582 	case IEEE80211_FC0_TYPE_MGT:
1583 		/* NB: force all management frames to highest queue */
1584 		if (ni->ni_flags & IEEE80211_NODE_QOS) {
1585 			/* NB: force all management frames to highest queue */
1586 			desc->txqid = htobe32(WME_AC_VO | UATH_TXQID_MINRATE);
1587 		} else
1588 			desc->txqid = htobe32(WME_AC_BE | UATH_TXQID_MINRATE);
1589 		break;
1590 	case IEEE80211_FC0_TYPE_DATA:
1591 		/* XXX multicast frames should honor mcastrate */
1592 		desc->txqid = htobe32(M_WME_GETAC(m0));
1593 		break;
1594 	default:
1595 		device_printf(sc->sc_dev, "bogus frame type 0x%x (%s)\n",
1596 			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
1597 		m_freem(m0);
1598 		return (EIO);
1599 	}
1600 	if (vap->iv_state == IEEE80211_S_AUTH ||
1601 	    vap->iv_state == IEEE80211_S_ASSOC ||
1602 	    vap->iv_state == IEEE80211_S_RUN)
1603 		desc->connid = htobe32(UATH_ID_BSS);
1604 	else
1605 		desc->connid = htobe32(UATH_ID_INVALID);
1606 	desc->flags  = htobe32(0 /* no UATH_TX_NOTIFY */);
1607 	desc->buflen = htobe32(m0->m_pkthdr.len);
1608 
1609 #ifdef UATH_DEBUG
1610 	DPRINTF(sc, UATH_DEBUG_XMIT,
1611 	    "send frame ix %u framelen %d msglen %d connid 0x%x txqid 0x%x\n",
1612 	    desc->msgid, framelen, msglen, be32toh(desc->connid),
1613 	    be32toh(desc->txqid));
1614 	if (sc->sc_debug & UATH_DEBUG_XMIT_DUMP)
1615 		uath_dump_cmd(data->buf, data->buflen, '+');
1616 #endif
1617 
1618 	STAILQ_INSERT_TAIL(&sc->sc_tx_pending, data, next);
1619 	UATH_STAT_INC(sc, st_tx_pending);
1620 	usbd_transfer_start(sc->sc_xfer[UATH_BULK_TX]);
1621 
1622 	return (0);
1623 }
1624 
1625 /*
1626  * Cleanup driver resources when we run out of buffers while processing
1627  * fragments; return the tx buffers allocated and drop node references.
1628  */
1629 static void
1630 uath_txfrag_cleanup(struct uath_softc *sc,
1631     uath_datahead *frags, struct ieee80211_node *ni)
1632 {
1633 	struct uath_data *bf, *next;
1634 
1635 	UATH_ASSERT_LOCKED(sc);
1636 
1637 	STAILQ_FOREACH_SAFE(bf, frags, next, next) {
1638 		/* NB: bf assumed clean */
1639 		STAILQ_REMOVE_HEAD(frags, next);
1640 		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
1641 		UATH_STAT_INC(sc, st_tx_inactive);
1642 		ieee80211_node_decref(ni);
1643 	}
1644 }
1645 
1646 /*
1647  * Setup xmit of a fragmented frame.  Allocate a buffer for each frag and bump
1648  * the node reference count to reflect the held reference to be setup by
1649  * uath_tx_start.
1650  */
1651 static int
1652 uath_txfrag_setup(struct uath_softc *sc, uath_datahead *frags,
1653     struct mbuf *m0, struct ieee80211_node *ni)
1654 {
1655 	struct mbuf *m;
1656 	struct uath_data *bf;
1657 
1658 	UATH_ASSERT_LOCKED(sc);
1659 	for (m = m0->m_nextpkt; m != NULL; m = m->m_nextpkt) {
1660 		bf = uath_getbuf(sc);
1661 		if (bf == NULL) {       /* out of buffers, cleanup */
1662 			uath_txfrag_cleanup(sc, frags, ni);
1663 			break;
1664 		}
1665 		ieee80211_node_incref(ni);
1666 		STAILQ_INSERT_TAIL(frags, bf, next);
1667 	}
1668 
1669 	return !STAILQ_EMPTY(frags);
1670 }
1671 
1672 static int
1673 uath_transmit(struct ieee80211com *ic, struct mbuf *m)
1674 {
1675 	struct uath_softc *sc = ic->ic_softc;
1676 	int error;
1677 
1678 	UATH_LOCK(sc);
1679 	if ((sc->sc_flags & UATH_FLAG_INITDONE) == 0) {
1680 		UATH_UNLOCK(sc);
1681 		return (ENXIO);
1682 	}
1683 	error = mbufq_enqueue(&sc->sc_snd, m);
1684 	if (error) {
1685 		UATH_UNLOCK(sc);
1686 		return (error);
1687 	}
1688 	uath_start(sc);
1689 	UATH_UNLOCK(sc);
1690 
1691 	return (0);
1692 }
1693 
1694 static void
1695 uath_start(struct uath_softc *sc)
1696 {
1697 	struct uath_data *bf;
1698 	struct ieee80211_node *ni;
1699 	struct mbuf *m, *next;
1700 	uath_datahead frags;
1701 
1702 	UATH_ASSERT_LOCKED(sc);
1703 
1704 	if ((sc->sc_flags & UATH_FLAG_INITDONE) == 0 ||
1705 	    (sc->sc_flags & UATH_FLAG_INVALID))
1706 		return;
1707 
1708 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
1709 		bf = uath_getbuf(sc);
1710 		if (bf == NULL) {
1711 			mbufq_prepend(&sc->sc_snd, m);
1712 			break;
1713 		}
1714 
1715 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
1716 		m->m_pkthdr.rcvif = NULL;
1717 
1718 		/*
1719 		 * Check for fragmentation.  If this frame has been broken up
1720 		 * verify we have enough buffers to send all the fragments
1721 		 * so all go out or none...
1722 		 */
1723 		STAILQ_INIT(&frags);
1724 		if ((m->m_flags & M_FRAG) &&
1725 		    !uath_txfrag_setup(sc, &frags, m, ni)) {
1726 			DPRINTF(sc, UATH_DEBUG_XMIT,
1727 			    "%s: out of txfrag buffers\n", __func__);
1728 			ieee80211_free_mbuf(m);
1729 			goto bad;
1730 		}
1731 		sc->sc_seqnum = 0;
1732 	nextfrag:
1733 		/*
1734 		 * Pass the frame to the h/w for transmission.
1735 		 * Fragmented frames have each frag chained together
1736 		 * with m_nextpkt.  We know there are sufficient uath_data's
1737 		 * to send all the frags because of work done by
1738 		 * uath_txfrag_setup.
1739 		 */
1740 		next = m->m_nextpkt;
1741 		if (uath_tx_start(sc, m, ni, bf) != 0) {
1742 	bad:
1743 			if_inc_counter(ni->ni_vap->iv_ifp,
1744 			    IFCOUNTER_OERRORS, 1);
1745 	reclaim:
1746 			STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
1747 			UATH_STAT_INC(sc, st_tx_inactive);
1748 			uath_txfrag_cleanup(sc, &frags, ni);
1749 			ieee80211_free_node(ni);
1750 			continue;
1751 		}
1752 
1753 		if (next != NULL) {
1754 			/*
1755 			 * Beware of state changing between frags.
1756 			 XXX check sta power-save state?
1757 			*/
1758 			if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
1759 				DPRINTF(sc, UATH_DEBUG_XMIT,
1760 				    "%s: flush fragmented packet, state %s\n",
1761 				    __func__,
1762 				    ieee80211_state_name[ni->ni_vap->iv_state]);
1763 				ieee80211_free_mbuf(next);
1764 				goto reclaim;
1765 			}
1766 			m = next;
1767 			bf = STAILQ_FIRST(&frags);
1768 			KASSERT(bf != NULL, ("no buf for txfrag"));
1769 			STAILQ_REMOVE_HEAD(&frags, next);
1770 			goto nextfrag;
1771 		}
1772 
1773 		sc->sc_tx_timer = 5;
1774 	}
1775 }
1776 
1777 static int
1778 uath_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
1779     const struct ieee80211_bpf_params *params)
1780 {
1781 	struct ieee80211com *ic = ni->ni_ic;
1782 	struct uath_data *bf;
1783 	struct uath_softc *sc = ic->ic_softc;
1784 
1785 	UATH_LOCK(sc);
1786 	/* prevent management frames from being sent if we're not ready */
1787 	if ((sc->sc_flags & UATH_FLAG_INVALID) ||
1788 	    !(sc->sc_flags & UATH_FLAG_INITDONE)) {
1789 		m_freem(m);
1790 		UATH_UNLOCK(sc);
1791 		return (ENETDOWN);
1792 	}
1793 
1794 	/* grab a TX buffer  */
1795 	bf = uath_getbuf(sc);
1796 	if (bf == NULL) {
1797 		m_freem(m);
1798 		UATH_UNLOCK(sc);
1799 		return (ENOBUFS);
1800 	}
1801 
1802 	sc->sc_seqnum = 0;
1803 	if (uath_tx_start(sc, m, ni, bf) != 0) {
1804 		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
1805 		UATH_STAT_INC(sc, st_tx_inactive);
1806 		UATH_UNLOCK(sc);
1807 		return (EIO);
1808 	}
1809 	UATH_UNLOCK(sc);
1810 
1811 	sc->sc_tx_timer = 5;
1812 	return (0);
1813 }
1814 
1815 static void
1816 uath_scan_start(struct ieee80211com *ic)
1817 {
1818 	/* do nothing  */
1819 }
1820 
1821 static void
1822 uath_scan_end(struct ieee80211com *ic)
1823 {
1824 	/* do nothing  */
1825 }
1826 
1827 static void
1828 uath_set_channel(struct ieee80211com *ic)
1829 {
1830 	struct uath_softc *sc = ic->ic_softc;
1831 
1832 	UATH_LOCK(sc);
1833 	if ((sc->sc_flags & UATH_FLAG_INVALID) ||
1834 	    (sc->sc_flags & UATH_FLAG_INITDONE) == 0) {
1835 		UATH_UNLOCK(sc);
1836 		return;
1837 	}
1838 	(void)uath_switch_channel(sc, ic->ic_curchan);
1839 	UATH_UNLOCK(sc);
1840 }
1841 
1842 static int
1843 uath_set_rxmulti_filter(struct uath_softc *sc)
1844 {
1845 	/* XXX broken */
1846 	return (0);
1847 }
1848 static void
1849 uath_update_mcast(struct ieee80211com *ic)
1850 {
1851 	struct uath_softc *sc = ic->ic_softc;
1852 
1853 	UATH_LOCK(sc);
1854 	if ((sc->sc_flags & UATH_FLAG_INVALID) ||
1855 	    (sc->sc_flags & UATH_FLAG_INITDONE) == 0) {
1856 		UATH_UNLOCK(sc);
1857 		return;
1858 	}
1859 	/*
1860 	 * this is for avoiding the race condition when we're try to
1861 	 * connect to the AP with WPA.
1862 	 */
1863 	if (sc->sc_flags & UATH_FLAG_INITDONE)
1864 		(void)uath_set_rxmulti_filter(sc);
1865 	UATH_UNLOCK(sc);
1866 }
1867 
1868 static void
1869 uath_update_promisc(struct ieee80211com *ic)
1870 {
1871 	struct uath_softc *sc = ic->ic_softc;
1872 
1873 	UATH_LOCK(sc);
1874 	if ((sc->sc_flags & UATH_FLAG_INVALID) ||
1875 	    (sc->sc_flags & UATH_FLAG_INITDONE) == 0) {
1876 		UATH_UNLOCK(sc);
1877 		return;
1878 	}
1879 	if (sc->sc_flags & UATH_FLAG_INITDONE) {
1880 		uath_set_rxfilter(sc,
1881 		    UATH_FILTER_RX_UCAST | UATH_FILTER_RX_MCAST |
1882 		    UATH_FILTER_RX_BCAST | UATH_FILTER_RX_BEACON |
1883 		    UATH_FILTER_RX_PROM, UATH_FILTER_OP_SET);
1884 	}
1885 	UATH_UNLOCK(sc);
1886 }
1887 
1888 static int
1889 uath_create_connection(struct uath_softc *sc, uint32_t connid)
1890 {
1891 	const struct ieee80211_rateset *rs;
1892 	struct ieee80211com *ic = &sc->sc_ic;
1893 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1894 	struct ieee80211_node *ni;
1895 	struct uath_cmd_create_connection create;
1896 
1897 	ni = ieee80211_ref_node(vap->iv_bss);
1898 	memset(&create, 0, sizeof(create));
1899 	create.connid = htobe32(connid);
1900 	create.bssid = htobe32(0);
1901 	/* XXX packed or not?  */
1902 	create.size = htobe32(sizeof(struct uath_cmd_rateset));
1903 
1904 	rs = &ni->ni_rates;
1905 	create.connattr.rateset.length = rs->rs_nrates;
1906 	bcopy(rs->rs_rates, &create.connattr.rateset.set[0],
1907 	    rs->rs_nrates);
1908 
1909 	/* XXX turbo */
1910 	if (IEEE80211_IS_CHAN_A(ni->ni_chan))
1911 		create.connattr.wlanmode = htobe32(WLAN_MODE_11a);
1912 	else if (IEEE80211_IS_CHAN_ANYG(ni->ni_chan))
1913 		create.connattr.wlanmode = htobe32(WLAN_MODE_11g);
1914 	else
1915 		create.connattr.wlanmode = htobe32(WLAN_MODE_11b);
1916 	ieee80211_free_node(ni);
1917 
1918 	return uath_cmd_write(sc, WDCMSG_CREATE_CONNECTION, &create,
1919 	    sizeof create, 0);
1920 }
1921 
1922 static int
1923 uath_set_rates(struct uath_softc *sc, const struct ieee80211_rateset *rs)
1924 {
1925 	struct uath_cmd_rates rates;
1926 
1927 	memset(&rates, 0, sizeof(rates));
1928 	rates.connid = htobe32(UATH_ID_BSS);		/* XXX */
1929 	rates.size   = htobe32(sizeof(struct uath_cmd_rateset));
1930 	/* XXX bounds check rs->rs_nrates */
1931 	rates.rateset.length = rs->rs_nrates;
1932 	bcopy(rs->rs_rates, &rates.rateset.set[0], rs->rs_nrates);
1933 
1934 	DPRINTF(sc, UATH_DEBUG_RATES,
1935 	    "setting supported rates nrates=%d\n", rs->rs_nrates);
1936 	return uath_cmd_write(sc, WDCMSG_SET_BASIC_RATE,
1937 	    &rates, sizeof rates, 0);
1938 }
1939 
1940 static int
1941 uath_write_associd(struct uath_softc *sc)
1942 {
1943 	struct ieee80211com *ic = &sc->sc_ic;
1944 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1945 	struct ieee80211_node *ni;
1946 	struct uath_cmd_set_associd associd;
1947 
1948 	ni = ieee80211_ref_node(vap->iv_bss);
1949 	memset(&associd, 0, sizeof(associd));
1950 	associd.defaultrateix = htobe32(1);	/* XXX */
1951 	associd.associd = htobe32(ni->ni_associd);
1952 	associd.timoffset = htobe32(0x3b);	/* XXX */
1953 	IEEE80211_ADDR_COPY(associd.bssid, ni->ni_bssid);
1954 	ieee80211_free_node(ni);
1955 	return uath_cmd_write(sc, WDCMSG_WRITE_ASSOCID, &associd,
1956 	    sizeof associd, 0);
1957 }
1958 
1959 static int
1960 uath_set_ledsteady(struct uath_softc *sc, int lednum, int ledmode)
1961 {
1962 	struct uath_cmd_ledsteady led;
1963 
1964 	led.lednum = htobe32(lednum);
1965 	led.ledmode = htobe32(ledmode);
1966 
1967 	DPRINTF(sc, UATH_DEBUG_LED, "set %s led %s (steady)\n",
1968 	    (lednum == UATH_LED_LINK) ? "link" : "activity",
1969 	    ledmode ? "on" : "off");
1970 	return uath_cmd_write(sc, WDCMSG_SET_LED_STEADY, &led, sizeof led, 0);
1971 }
1972 
1973 static int
1974 uath_set_ledblink(struct uath_softc *sc, int lednum, int ledmode,
1975 	int blinkrate, int slowmode)
1976 {
1977 	struct uath_cmd_ledblink led;
1978 
1979 	led.lednum = htobe32(lednum);
1980 	led.ledmode = htobe32(ledmode);
1981 	led.blinkrate = htobe32(blinkrate);
1982 	led.slowmode = htobe32(slowmode);
1983 
1984 	DPRINTF(sc, UATH_DEBUG_LED, "set %s led %s (blink)\n",
1985 	    (lednum == UATH_LED_LINK) ? "link" : "activity",
1986 	    ledmode ? "on" : "off");
1987 	return uath_cmd_write(sc, WDCMSG_SET_LED_BLINK, &led, sizeof led, 0);
1988 }
1989 
1990 static int
1991 uath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1992 {
1993 	enum ieee80211_state ostate = vap->iv_state;
1994 	int error;
1995 	struct ieee80211_node *ni;
1996 	struct ieee80211com *ic = vap->iv_ic;
1997 	struct uath_softc *sc = ic->ic_softc;
1998 	struct uath_vap *uvp = UATH_VAP(vap);
1999 
2000 	DPRINTF(sc, UATH_DEBUG_STATE,
2001 	    "%s: %s -> %s\n", __func__, ieee80211_state_name[vap->iv_state],
2002 	    ieee80211_state_name[nstate]);
2003 
2004 	IEEE80211_UNLOCK(ic);
2005 	UATH_LOCK(sc);
2006 	callout_stop(&sc->stat_ch);
2007 	callout_stop(&sc->watchdog_ch);
2008 	ni = ieee80211_ref_node(vap->iv_bss);
2009 
2010 	switch (nstate) {
2011 	case IEEE80211_S_INIT:
2012 		if (ostate == IEEE80211_S_RUN) {
2013 			/* turn link and activity LEDs off */
2014 			uath_set_ledstate(sc, 0);
2015 		}
2016 		break;
2017 
2018 	case IEEE80211_S_SCAN:
2019 		break;
2020 
2021 	case IEEE80211_S_AUTH:
2022 		/* XXX good place?  set RTS threshold  */
2023 		uath_config(sc, CFG_USER_RTS_THRESHOLD, vap->iv_rtsthreshold);
2024 		/* XXX bad place  */
2025 		error = uath_set_keys(sc, vap);
2026 		if (error != 0) {
2027 			device_printf(sc->sc_dev,
2028 			    "could not set crypto keys, error %d\n", error);
2029 			break;
2030 		}
2031 		if (uath_switch_channel(sc, ni->ni_chan) != 0) {
2032 			device_printf(sc->sc_dev, "could not switch channel\n");
2033 			break;
2034 		}
2035 		if (uath_create_connection(sc, UATH_ID_BSS) != 0) {
2036 			device_printf(sc->sc_dev,
2037 			    "could not create connection\n");
2038 			break;
2039 		}
2040 		break;
2041 
2042 	case IEEE80211_S_ASSOC:
2043 		if (uath_set_rates(sc, &ni->ni_rates) != 0) {
2044 			device_printf(sc->sc_dev,
2045 			    "could not set negotiated rate set\n");
2046 			break;
2047 		}
2048 		break;
2049 
2050 	case IEEE80211_S_RUN:
2051 		/* XXX monitor mode doesn't be tested  */
2052 		if (ic->ic_opmode == IEEE80211_M_MONITOR) {
2053 			uath_set_ledstate(sc, 1);
2054 			break;
2055 		}
2056 
2057 		/*
2058 		 * Tx rate is controlled by firmware, report the maximum
2059 		 * negotiated rate in ifconfig output.
2060 		 */
2061 		ni->ni_txrate = ni->ni_rates.rs_rates[ni->ni_rates.rs_nrates-1];
2062 
2063 		if (uath_write_associd(sc) != 0) {
2064 			device_printf(sc->sc_dev,
2065 			    "could not write association id\n");
2066 			break;
2067 		}
2068 		/* turn link LED on */
2069 		uath_set_ledsteady(sc, UATH_LED_LINK, UATH_LED_ON);
2070 		/* make activity LED blink */
2071 		uath_set_ledblink(sc, UATH_LED_ACTIVITY, UATH_LED_ON, 1, 2);
2072 		/* set state to associated */
2073 		uath_set_ledstate(sc, 1);
2074 
2075 		/* start statistics timer */
2076 		callout_reset(&sc->stat_ch, hz, uath_stat, sc);
2077 		break;
2078 	default:
2079 		break;
2080 	}
2081 	ieee80211_free_node(ni);
2082 	UATH_UNLOCK(sc);
2083 	IEEE80211_LOCK(ic);
2084 	return (uvp->newstate(vap, nstate, arg));
2085 }
2086 
2087 static int
2088 uath_set_key(struct uath_softc *sc, const struct ieee80211_key *wk,
2089     int index)
2090 {
2091 #if 0
2092 	struct uath_cmd_crypto crypto;
2093 	int i;
2094 
2095 	memset(&crypto, 0, sizeof(crypto));
2096 	crypto.keyidx = htobe32(index);
2097 	crypto.magic1 = htobe32(1);
2098 	crypto.size   = htobe32(368);
2099 	crypto.mask   = htobe32(0xffff);
2100 	crypto.flags  = htobe32(0x80000068);
2101 	if (index != UATH_DEFAULT_KEY)
2102 		crypto.flags |= htobe32(index << 16);
2103 	memset(crypto.magic2, 0xff, sizeof(crypto.magic2));
2104 
2105 	/*
2106 	 * Each byte of the key must be XOR'ed with 10101010 before being
2107 	 * transmitted to the firmware.
2108 	 */
2109 	for (i = 0; i < wk->wk_keylen; i++)
2110 		crypto.key[i] = wk->wk_key[i] ^ 0xaa;
2111 
2112 	DPRINTF(sc, UATH_DEBUG_CRYPTO,
2113 	    "setting crypto key index=%d len=%d\n", index, wk->wk_keylen);
2114 	return uath_cmd_write(sc, WDCMSG_SET_KEY_CACHE_ENTRY, &crypto,
2115 	    sizeof crypto, 0);
2116 #else
2117 	/* XXX support H/W cryto  */
2118 	return (0);
2119 #endif
2120 }
2121 
2122 static int
2123 uath_set_keys(struct uath_softc *sc, struct ieee80211vap *vap)
2124 {
2125 	int i, error;
2126 
2127 	error = 0;
2128 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
2129 		const struct ieee80211_key *wk = &vap->iv_nw_keys[i];
2130 
2131 		if (wk->wk_flags & (IEEE80211_KEY_XMIT|IEEE80211_KEY_RECV)) {
2132 			error = uath_set_key(sc, wk, i);
2133 			if (error)
2134 				return (error);
2135 		}
2136 	}
2137 	if (vap->iv_def_txkey != IEEE80211_KEYIX_NONE) {
2138 		error = uath_set_key(sc, &vap->iv_nw_keys[vap->iv_def_txkey],
2139 			UATH_DEFAULT_KEY);
2140 	}
2141 	return (error);
2142 }
2143 
2144 #define	UATH_SYSCTL_STAT_ADD32(c, h, n, p, d)	\
2145 	    SYSCTL_ADD_UINT(c, h, OID_AUTO, n, CTLFLAG_RD, p, 0, d)
2146 
2147 static void
2148 uath_sysctl_node(struct uath_softc *sc)
2149 {
2150 	struct sysctl_ctx_list *ctx;
2151 	struct sysctl_oid_list *child;
2152 	struct sysctl_oid *tree;
2153 	struct uath_stat *stats;
2154 
2155 	stats = &sc->sc_stat;
2156 	ctx = device_get_sysctl_ctx(sc->sc_dev);
2157 	child = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->sc_dev));
2158 
2159 	tree = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, "stats", CTLFLAG_RD,
2160 	    NULL, "UATH statistics");
2161 	child = SYSCTL_CHILDREN(tree);
2162 	UATH_SYSCTL_STAT_ADD32(ctx, child, "badchunkseqnum",
2163 	    &stats->st_badchunkseqnum, "Bad chunk sequence numbers");
2164 	UATH_SYSCTL_STAT_ADD32(ctx, child, "invalidlen", &stats->st_invalidlen,
2165 	    "Invalid length");
2166 	UATH_SYSCTL_STAT_ADD32(ctx, child, "multichunk", &stats->st_multichunk,
2167 	    "Multi chunks");
2168 	UATH_SYSCTL_STAT_ADD32(ctx, child, "toobigrxpkt",
2169 	    &stats->st_toobigrxpkt, "Too big rx packets");
2170 	UATH_SYSCTL_STAT_ADD32(ctx, child, "stopinprogress",
2171 	    &stats->st_stopinprogress, "Stop in progress");
2172 	UATH_SYSCTL_STAT_ADD32(ctx, child, "crcerrs", &stats->st_crcerr,
2173 	    "CRC errors");
2174 	UATH_SYSCTL_STAT_ADD32(ctx, child, "phyerr", &stats->st_phyerr,
2175 	    "PHY errors");
2176 	UATH_SYSCTL_STAT_ADD32(ctx, child, "decrypt_crcerr",
2177 	    &stats->st_decrypt_crcerr, "Decryption CRC errors");
2178 	UATH_SYSCTL_STAT_ADD32(ctx, child, "decrypt_micerr",
2179 	    &stats->st_decrypt_micerr, "Decryption Misc errors");
2180 	UATH_SYSCTL_STAT_ADD32(ctx, child, "decomperr", &stats->st_decomperr,
2181 	    "Decomp errors");
2182 	UATH_SYSCTL_STAT_ADD32(ctx, child, "keyerr", &stats->st_keyerr,
2183 	    "Key errors");
2184 	UATH_SYSCTL_STAT_ADD32(ctx, child, "err", &stats->st_err,
2185 	    "Unknown errors");
2186 
2187 	UATH_SYSCTL_STAT_ADD32(ctx, child, "cmd_active",
2188 	    &stats->st_cmd_active, "Active numbers in Command queue");
2189 	UATH_SYSCTL_STAT_ADD32(ctx, child, "cmd_inactive",
2190 	    &stats->st_cmd_inactive, "Inactive numbers in Command queue");
2191 	UATH_SYSCTL_STAT_ADD32(ctx, child, "cmd_pending",
2192 	    &stats->st_cmd_pending, "Pending numbers in Command queue");
2193 	UATH_SYSCTL_STAT_ADD32(ctx, child, "cmd_waiting",
2194 	    &stats->st_cmd_waiting, "Waiting numbers in Command queue");
2195 	UATH_SYSCTL_STAT_ADD32(ctx, child, "rx_active",
2196 	    &stats->st_rx_active, "Active numbers in RX queue");
2197 	UATH_SYSCTL_STAT_ADD32(ctx, child, "rx_inactive",
2198 	    &stats->st_rx_inactive, "Inactive numbers in RX queue");
2199 	UATH_SYSCTL_STAT_ADD32(ctx, child, "tx_active",
2200 	    &stats->st_tx_active, "Active numbers in TX queue");
2201 	UATH_SYSCTL_STAT_ADD32(ctx, child, "tx_inactive",
2202 	    &stats->st_tx_inactive, "Inactive numbers in TX queue");
2203 	UATH_SYSCTL_STAT_ADD32(ctx, child, "tx_pending",
2204 	    &stats->st_tx_pending, "Pending numbers in TX queue");
2205 }
2206 
2207 #undef UATH_SYSCTL_STAT_ADD32
2208 
2209 CTASSERT(sizeof(u_int) >= sizeof(uint32_t));
2210 
2211 static void
2212 uath_cmdeof(struct uath_softc *sc, struct uath_cmd *cmd)
2213 {
2214 	struct uath_cmd_hdr *hdr;
2215 	uint32_t dlen;
2216 
2217 	hdr = (struct uath_cmd_hdr *)cmd->buf;
2218 	/* NB: msgid is passed thru w/o byte swapping */
2219 #ifdef UATH_DEBUG
2220 	if (sc->sc_debug & UATH_DEBUG_CMDS) {
2221 		uint32_t len = be32toh(hdr->len);
2222 		printf("%s: %s [ix %u] len %u status %u\n",
2223 		    __func__, uath_codename(be32toh(hdr->code)),
2224 		    hdr->msgid, len, be32toh(hdr->magic));
2225 		if (sc->sc_debug & UATH_DEBUG_CMDS_DUMP)
2226 			uath_dump_cmd(cmd->buf,
2227 			    len > UATH_MAX_CMDSZ ? sizeof(*hdr) : len, '-');
2228 	}
2229 #endif
2230 	hdr->code = be32toh(hdr->code);
2231 	hdr->len = be32toh(hdr->len);
2232 	hdr->magic = be32toh(hdr->magic);	/* target status on return */
2233 
2234 	switch (hdr->code & 0xff) {
2235 	/* reply to a read command */
2236 	default:
2237 		DPRINTF(sc, UATH_DEBUG_RX_PROC | UATH_DEBUG_RECV_ALL,
2238 		    "%s: code %d hdr len %u\n",
2239 		    __func__, hdr->code & 0xff, hdr->len);
2240 		/*
2241 		 * The first response from the target after the
2242 		 * HOST_AVAILABLE has an invalid msgid so we must
2243 		 * treat it specially.
2244 		 */
2245 		if (hdr->msgid < UATH_CMD_LIST_COUNT) {
2246 			uint32_t *rp = (uint32_t *)(hdr+1);
2247 			u_int olen;
2248 
2249 			if (sizeof(*hdr) > hdr->len ||
2250 			    hdr->len >= UATH_MAX_CMDSZ) {
2251 				device_printf(sc->sc_dev,
2252 				    "%s: invalid WDC msg length %u; "
2253 				    "msg ignored\n", __func__, hdr->len);
2254 				return;
2255 			}
2256 			/*
2257 			 * Calculate return/receive payload size; the
2258 			 * first word, if present, always gives the
2259 			 * number of bytes--unless it's 0 in which
2260 			 * case a single 32-bit word should be present.
2261 			 */
2262 			dlen = hdr->len - sizeof(*hdr);
2263 			if (dlen >= sizeof(uint32_t)) {
2264 				olen = be32toh(rp[0]);
2265 				dlen -= sizeof(uint32_t);
2266 				if (olen == 0) {
2267 					/* convention is 0 =>'s one word */
2268 					olen = sizeof(uint32_t);
2269 					/* XXX KASSERT(olen == dlen ) */
2270 				}
2271 			} else
2272 				olen = 0;
2273 			if (cmd->odata != NULL) {
2274 				/* NB: cmd->olen validated in uath_cmd */
2275 				if (olen > (u_int)cmd->olen) {
2276 					/* XXX complain? */
2277 					device_printf(sc->sc_dev,
2278 					    "%s: cmd 0x%x olen %u cmd olen %u\n",
2279 					    __func__, hdr->code, olen,
2280 					    cmd->olen);
2281 					olen = cmd->olen;
2282 				}
2283 				if (olen > dlen) {
2284 					/* XXX complain, shouldn't happen */
2285 					device_printf(sc->sc_dev,
2286 					    "%s: cmd 0x%x olen %u dlen %u\n",
2287 					    __func__, hdr->code, olen, dlen);
2288 					olen = dlen;
2289 				}
2290 				/* XXX have submitter do this */
2291 				/* copy answer into caller's supplied buffer */
2292 				bcopy(&rp[1], cmd->odata, olen);
2293 				cmd->olen = olen;
2294 			}
2295 		}
2296 		wakeup_one(cmd);		/* wake up caller */
2297 		break;
2298 
2299 	case WDCMSG_TARGET_START:
2300 		if (hdr->msgid >= UATH_CMD_LIST_COUNT) {
2301 			/* XXX */
2302 			return;
2303 		}
2304 		dlen = hdr->len - sizeof(*hdr);
2305 		if (dlen != sizeof(uint32_t)) {
2306 			device_printf(sc->sc_dev,
2307 			    "%s: dlen (%u) != %zu!\n",
2308 			    __func__, dlen, sizeof(uint32_t));
2309 			return;
2310 		}
2311 		/* XXX have submitter do this */
2312 		/* copy answer into caller's supplied buffer */
2313 		bcopy(hdr+1, cmd->odata, sizeof(uint32_t));
2314 		cmd->olen = sizeof(uint32_t);
2315 		wakeup_one(cmd);		/* wake up caller */
2316 		break;
2317 
2318 	case WDCMSG_SEND_COMPLETE:
2319 		/* this notification is sent when UATH_TX_NOTIFY is set */
2320 		DPRINTF(sc, UATH_DEBUG_RX_PROC | UATH_DEBUG_RECV_ALL,
2321 		    "%s: received Tx notification\n", __func__);
2322 		break;
2323 
2324 	case WDCMSG_TARGET_GET_STATS:
2325 		DPRINTF(sc, UATH_DEBUG_RX_PROC | UATH_DEBUG_RECV_ALL,
2326 		    "%s: received device statistics\n", __func__);
2327 		callout_reset(&sc->stat_ch, hz, uath_stat, sc);
2328 		break;
2329 	}
2330 }
2331 
2332 static void
2333 uath_intr_rx_callback(struct usb_xfer *xfer, usb_error_t error)
2334 {
2335 	struct uath_softc *sc = usbd_xfer_softc(xfer);
2336 	struct uath_cmd *cmd;
2337 	struct uath_cmd_hdr *hdr;
2338 	struct usb_page_cache *pc;
2339 	int actlen;
2340 
2341 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
2342 
2343 	UATH_ASSERT_LOCKED(sc);
2344 
2345 	switch (USB_GET_STATE(xfer)) {
2346 	case USB_ST_TRANSFERRED:
2347 		cmd = STAILQ_FIRST(&sc->sc_cmd_waiting);
2348 		if (cmd == NULL)
2349 			goto setup;
2350 		STAILQ_REMOVE_HEAD(&sc->sc_cmd_waiting, next);
2351 		UATH_STAT_DEC(sc, st_cmd_waiting);
2352 		STAILQ_INSERT_TAIL(&sc->sc_cmd_inactive, cmd, next);
2353 		UATH_STAT_INC(sc, st_cmd_inactive);
2354 
2355 		if (actlen < sizeof(struct uath_cmd_hdr)) {
2356 			device_printf(sc->sc_dev,
2357 			    "%s: short xfer error (actlen %d)\n",
2358 			    __func__, actlen);
2359 			goto setup;
2360 		}
2361 
2362 		pc = usbd_xfer_get_frame(xfer, 0);
2363 		usbd_copy_out(pc, 0, cmd->buf, actlen);
2364 
2365 		hdr = (struct uath_cmd_hdr *)cmd->buf;
2366 		hdr->len = be32toh(hdr->len);
2367 		if (hdr->len > (uint32_t)actlen) {
2368 			device_printf(sc->sc_dev,
2369 			    "%s: truncated xfer (len %u, actlen %d)\n",
2370 			    __func__, hdr->len, actlen);
2371 			goto setup;
2372 		}
2373 
2374 		uath_cmdeof(sc, cmd);
2375 	case USB_ST_SETUP:
2376 setup:
2377 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
2378 		usbd_transfer_submit(xfer);
2379 		break;
2380 	default:
2381 		if (error != USB_ERR_CANCELLED) {
2382 			usbd_xfer_set_stall(xfer);
2383 			goto setup;
2384 		}
2385 		break;
2386 	}
2387 }
2388 
2389 static void
2390 uath_intr_tx_callback(struct usb_xfer *xfer, usb_error_t error)
2391 {
2392 	struct uath_softc *sc = usbd_xfer_softc(xfer);
2393 	struct uath_cmd *cmd;
2394 
2395 	UATH_ASSERT_LOCKED(sc);
2396 
2397 	cmd = STAILQ_FIRST(&sc->sc_cmd_active);
2398 	if (cmd != NULL && USB_GET_STATE(xfer) != USB_ST_SETUP) {
2399 		STAILQ_REMOVE_HEAD(&sc->sc_cmd_active, next);
2400 		UATH_STAT_DEC(sc, st_cmd_active);
2401 		STAILQ_INSERT_TAIL((cmd->flags & UATH_CMD_FLAG_READ) ?
2402 		    &sc->sc_cmd_waiting : &sc->sc_cmd_inactive, cmd, next);
2403 		if (cmd->flags & UATH_CMD_FLAG_READ)
2404 			UATH_STAT_INC(sc, st_cmd_waiting);
2405 		else
2406 			UATH_STAT_INC(sc, st_cmd_inactive);
2407 	}
2408 
2409 	switch (USB_GET_STATE(xfer)) {
2410 	case USB_ST_TRANSFERRED:
2411 	case USB_ST_SETUP:
2412 setup:
2413 		cmd = STAILQ_FIRST(&sc->sc_cmd_pending);
2414 		if (cmd == NULL) {
2415 			DPRINTF(sc, UATH_DEBUG_XMIT, "%s: empty pending queue\n",
2416 			    __func__);
2417 			return;
2418 		}
2419 		STAILQ_REMOVE_HEAD(&sc->sc_cmd_pending, next);
2420 		UATH_STAT_DEC(sc, st_cmd_pending);
2421 		STAILQ_INSERT_TAIL((cmd->flags & UATH_CMD_FLAG_ASYNC) ?
2422 		    &sc->sc_cmd_inactive : &sc->sc_cmd_active, cmd, next);
2423 		if (cmd->flags & UATH_CMD_FLAG_ASYNC)
2424 			UATH_STAT_INC(sc, st_cmd_inactive);
2425 		else
2426 			UATH_STAT_INC(sc, st_cmd_active);
2427 
2428 		usbd_xfer_set_frame_data(xfer, 0, cmd->buf, cmd->buflen);
2429 		usbd_transfer_submit(xfer);
2430 		break;
2431 	default:
2432 		if (error != USB_ERR_CANCELLED) {
2433 			usbd_xfer_set_stall(xfer);
2434 			goto setup;
2435 		}
2436 		break;
2437 	}
2438 }
2439 
2440 static void
2441 uath_update_rxstat(struct uath_softc *sc, uint32_t status)
2442 {
2443 
2444 	switch (status) {
2445 	case UATH_STATUS_STOP_IN_PROGRESS:
2446 		UATH_STAT_INC(sc, st_stopinprogress);
2447 		break;
2448 	case UATH_STATUS_CRC_ERR:
2449 		UATH_STAT_INC(sc, st_crcerr);
2450 		break;
2451 	case UATH_STATUS_PHY_ERR:
2452 		UATH_STAT_INC(sc, st_phyerr);
2453 		break;
2454 	case UATH_STATUS_DECRYPT_CRC_ERR:
2455 		UATH_STAT_INC(sc, st_decrypt_crcerr);
2456 		break;
2457 	case UATH_STATUS_DECRYPT_MIC_ERR:
2458 		UATH_STAT_INC(sc, st_decrypt_micerr);
2459 		break;
2460 	case UATH_STATUS_DECOMP_ERR:
2461 		UATH_STAT_INC(sc, st_decomperr);
2462 		break;
2463 	case UATH_STATUS_KEY_ERR:
2464 		UATH_STAT_INC(sc, st_keyerr);
2465 		break;
2466 	case UATH_STATUS_ERR:
2467 		UATH_STAT_INC(sc, st_err);
2468 		break;
2469 	default:
2470 		break;
2471 	}
2472 }
2473 
2474 CTASSERT(UATH_MIN_RXBUFSZ >= sizeof(struct uath_chunk));
2475 
2476 static struct mbuf *
2477 uath_data_rxeof(struct usb_xfer *xfer, struct uath_data *data,
2478     struct uath_rx_desc **pdesc)
2479 {
2480 	struct uath_softc *sc = usbd_xfer_softc(xfer);
2481 	struct ieee80211com *ic = &sc->sc_ic;
2482 	struct uath_chunk *chunk;
2483 	struct uath_rx_desc *desc;
2484 	struct mbuf *m = data->m, *mnew, *mp;
2485 	uint16_t chunklen;
2486 	int actlen;
2487 
2488 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
2489 
2490 	if (actlen < (int)UATH_MIN_RXBUFSZ) {
2491 		DPRINTF(sc, UATH_DEBUG_RECV | UATH_DEBUG_RECV_ALL,
2492 		    "%s: wrong xfer size (len=%d)\n", __func__, actlen);
2493 		counter_u64_add(ic->ic_ierrors, 1);
2494 		return (NULL);
2495 	}
2496 
2497 	chunk = (struct uath_chunk *)data->buf;
2498 	chunklen = be16toh(chunk->length);
2499 	if (chunk->seqnum == 0 && chunk->flags == 0 && chunklen == 0) {
2500 		device_printf(sc->sc_dev, "%s: strange response\n", __func__);
2501 		counter_u64_add(ic->ic_ierrors, 1);
2502 		UATH_RESET_INTRX(sc);
2503 		return (NULL);
2504 	}
2505 
2506 	if (chunklen > actlen) {
2507 		device_printf(sc->sc_dev,
2508 		    "%s: invalid chunk length (len %u > actlen %d)\n",
2509 		    __func__, chunklen, actlen);
2510 		counter_u64_add(ic->ic_ierrors, 1);
2511 		/* XXX cleanup? */
2512 		UATH_RESET_INTRX(sc);
2513 		return (NULL);
2514 	}
2515 
2516 	if (chunk->seqnum != sc->sc_intrx_nextnum) {
2517 		DPRINTF(sc, UATH_DEBUG_XMIT, "invalid seqnum %d, expected %d\n",
2518 		    chunk->seqnum, sc->sc_intrx_nextnum);
2519 		UATH_STAT_INC(sc, st_badchunkseqnum);
2520 		if (sc->sc_intrx_head != NULL)
2521 			m_freem(sc->sc_intrx_head);
2522 		UATH_RESET_INTRX(sc);
2523 		return (NULL);
2524 	}
2525 
2526 	/* check multi-chunk frames  */
2527 	if ((chunk->seqnum == 0 && !(chunk->flags & UATH_CFLAGS_FINAL)) ||
2528 	    (chunk->seqnum != 0 && (chunk->flags & UATH_CFLAGS_FINAL)) ||
2529 	    chunk->flags & UATH_CFLAGS_RXMSG)
2530 		UATH_STAT_INC(sc, st_multichunk);
2531 
2532 	if (chunk->flags & UATH_CFLAGS_FINAL) {
2533 		if (chunklen < sizeof(struct uath_rx_desc)) {
2534 			device_printf(sc->sc_dev,
2535 			    "%s: invalid chunk length %d\n",
2536 			    __func__, chunklen);
2537 			counter_u64_add(ic->ic_ierrors, 1);
2538 			if (sc->sc_intrx_head != NULL)
2539 				m_freem(sc->sc_intrx_head);
2540 			UATH_RESET_INTRX(sc);
2541 			return (NULL);
2542 		}
2543 		chunklen -= sizeof(struct uath_rx_desc);
2544 	}
2545 
2546 	if (chunklen > 0 &&
2547 	    (!(chunk->flags & UATH_CFLAGS_FINAL) || !(chunk->seqnum == 0))) {
2548 		/* we should use intermediate RX buffer  */
2549 		if (chunk->seqnum == 0)
2550 			UATH_RESET_INTRX(sc);
2551 		if ((sc->sc_intrx_len + sizeof(struct uath_rx_desc) +
2552 		    chunklen) > UATH_MAX_INTRX_SIZE) {
2553 			UATH_STAT_INC(sc, st_invalidlen);
2554 			counter_u64_add(ic->ic_ierrors, 1);
2555 			if (sc->sc_intrx_head != NULL)
2556 				m_freem(sc->sc_intrx_head);
2557 			UATH_RESET_INTRX(sc);
2558 			return (NULL);
2559 		}
2560 
2561 		m->m_len = chunklen;
2562 		m->m_data += sizeof(struct uath_chunk);
2563 
2564 		if (sc->sc_intrx_head == NULL) {
2565 			sc->sc_intrx_head = m;
2566 			sc->sc_intrx_tail = m;
2567 		} else {
2568 			m->m_flags &= ~M_PKTHDR;
2569 			sc->sc_intrx_tail->m_next = m;
2570 			sc->sc_intrx_tail = m;
2571 		}
2572 	}
2573 	sc->sc_intrx_len += chunklen;
2574 
2575 	mnew = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2576 	if (mnew == NULL) {
2577 		DPRINTF(sc, UATH_DEBUG_RECV | UATH_DEBUG_RECV_ALL,
2578 		    "%s: can't get new mbuf, drop frame\n", __func__);
2579 		counter_u64_add(ic->ic_ierrors, 1);
2580 		if (sc->sc_intrx_head != NULL)
2581 			m_freem(sc->sc_intrx_head);
2582 		UATH_RESET_INTRX(sc);
2583 		return (NULL);
2584 	}
2585 
2586 	data->m = mnew;
2587 	data->buf = mtod(mnew, uint8_t *);
2588 
2589 	/* if the frame is not final continue the transfer  */
2590 	if (!(chunk->flags & UATH_CFLAGS_FINAL)) {
2591 		sc->sc_intrx_nextnum++;
2592 		UATH_RESET_INTRX(sc);
2593 		return (NULL);
2594 	}
2595 
2596 	/*
2597 	 * if the frame is not set UATH_CFLAGS_RXMSG, then rx descriptor is
2598 	 * located at the end, 32-bit aligned
2599 	 */
2600 	desc = (chunk->flags & UATH_CFLAGS_RXMSG) ?
2601 		(struct uath_rx_desc *)(chunk + 1) :
2602 		(struct uath_rx_desc *)(((uint8_t *)chunk) +
2603 		    sizeof(struct uath_chunk) + be16toh(chunk->length) -
2604 		    sizeof(struct uath_rx_desc));
2605 	if ((uint8_t *)chunk + actlen - sizeof(struct uath_rx_desc) <
2606 	    (uint8_t *)desc) {
2607 		device_printf(sc->sc_dev,
2608 		    "%s: wrong Rx descriptor pointer "
2609 		    "(desc %p chunk %p actlen %d)\n",
2610 		    __func__, desc, chunk, actlen);
2611 		counter_u64_add(ic->ic_ierrors, 1);
2612 		if (sc->sc_intrx_head != NULL)
2613 			m_freem(sc->sc_intrx_head);
2614 		UATH_RESET_INTRX(sc);
2615 		return (NULL);
2616 	}
2617 
2618 	*pdesc = desc;
2619 
2620 	DPRINTF(sc, UATH_DEBUG_RECV | UATH_DEBUG_RECV_ALL,
2621 	    "%s: frame len %u code %u status %u rate %u antenna %u "
2622 	    "rssi %d channel %u phyerror %u connix %u decrypterror %u "
2623 	    "keycachemiss %u\n", __func__, be32toh(desc->framelen)
2624 	    , be32toh(desc->code), be32toh(desc->status), be32toh(desc->rate)
2625 	    , be32toh(desc->antenna), be32toh(desc->rssi), be32toh(desc->channel)
2626 	    , be32toh(desc->phyerror), be32toh(desc->connix)
2627 	    , be32toh(desc->decrypterror), be32toh(desc->keycachemiss));
2628 
2629 	if (be32toh(desc->len) > MCLBYTES) {
2630 		DPRINTF(sc, UATH_DEBUG_RECV | UATH_DEBUG_RECV_ALL,
2631 		    "%s: bad descriptor (len=%d)\n", __func__,
2632 		    be32toh(desc->len));
2633 		counter_u64_add(ic->ic_ierrors, 1);
2634 		UATH_STAT_INC(sc, st_toobigrxpkt);
2635 		if (sc->sc_intrx_head != NULL)
2636 			m_freem(sc->sc_intrx_head);
2637 		UATH_RESET_INTRX(sc);
2638 		return (NULL);
2639 	}
2640 
2641 	uath_update_rxstat(sc, be32toh(desc->status));
2642 
2643 	/* finalize mbuf */
2644 	if (sc->sc_intrx_head == NULL) {
2645 		uint32_t framelen;
2646 
2647 		if (be32toh(desc->framelen) < UATH_RX_DUMMYSIZE) {
2648 			device_printf(sc->sc_dev,
2649 			    "%s: framelen too small (%u)\n",
2650 			    __func__, be32toh(desc->framelen));
2651 			counter_u64_add(ic->ic_ierrors, 1);
2652 			if (sc->sc_intrx_head != NULL)
2653 				m_freem(sc->sc_intrx_head);
2654 			UATH_RESET_INTRX(sc);
2655 			return (NULL);
2656 		}
2657 
2658 		framelen = be32toh(desc->framelen) - UATH_RX_DUMMYSIZE;
2659 		if (framelen > actlen - sizeof(struct uath_chunk) ||
2660 		    framelen < sizeof(struct ieee80211_frame_ack)) {
2661 			device_printf(sc->sc_dev,
2662 			    "%s: wrong frame length (%u, actlen %d)!\n",
2663 			    __func__, framelen, actlen);
2664 			counter_u64_add(ic->ic_ierrors, 1);
2665 			if (sc->sc_intrx_head != NULL)
2666 				m_freem(sc->sc_intrx_head);
2667 			UATH_RESET_INTRX(sc);
2668 			return (NULL);
2669 		}
2670 
2671 		m->m_pkthdr.len = m->m_len = framelen;
2672 		m->m_data += sizeof(struct uath_chunk);
2673 	} else {
2674 		mp = sc->sc_intrx_head;
2675 		mp->m_flags |= M_PKTHDR;
2676 		mp->m_pkthdr.len = sc->sc_intrx_len;
2677 		m = mp;
2678 	}
2679 
2680 	/* there are a lot more fields in the RX descriptor */
2681 	if ((sc->sc_flags & UATH_FLAG_INVALID) == 0 &&
2682 	    ieee80211_radiotap_active(ic)) {
2683 		struct uath_rx_radiotap_header *tap = &sc->sc_rxtap;
2684 		uint32_t tsf_hi = be32toh(desc->tstamp_high);
2685 		uint32_t tsf_lo = be32toh(desc->tstamp_low);
2686 
2687 		/* XXX only get low order 24bits of tsf from h/w */
2688 		tap->wr_tsf = htole64(((uint64_t)tsf_hi << 32) | tsf_lo);
2689 		tap->wr_flags = 0;
2690 		if (be32toh(desc->status) == UATH_STATUS_CRC_ERR)
2691 			tap->wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
2692 		/* XXX map other status to BADFCS? */
2693 		/* XXX ath h/w rate code, need to map */
2694 		tap->wr_rate = be32toh(desc->rate);
2695 		tap->wr_antenna = be32toh(desc->antenna);
2696 		tap->wr_antsignal = -95 + be32toh(desc->rssi);
2697 		tap->wr_antnoise = -95;
2698 	}
2699 
2700 	UATH_RESET_INTRX(sc);
2701 
2702 	return (m);
2703 }
2704 
2705 static void
2706 uath_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
2707 {
2708 	struct uath_softc *sc = usbd_xfer_softc(xfer);
2709 	struct ieee80211com *ic = &sc->sc_ic;
2710 	struct ieee80211_frame *wh;
2711 	struct ieee80211_node *ni;
2712 	struct mbuf *m = NULL;
2713 	struct uath_data *data;
2714 	struct uath_rx_desc *desc = NULL;
2715 	int8_t nf;
2716 
2717 	UATH_ASSERT_LOCKED(sc);
2718 
2719 	switch (USB_GET_STATE(xfer)) {
2720 	case USB_ST_TRANSFERRED:
2721 		data = STAILQ_FIRST(&sc->sc_rx_active);
2722 		if (data == NULL)
2723 			goto setup;
2724 		STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
2725 		UATH_STAT_DEC(sc, st_rx_active);
2726 		m = uath_data_rxeof(xfer, data, &desc);
2727 		STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
2728 		UATH_STAT_INC(sc, st_rx_inactive);
2729 		/* FALLTHROUGH */
2730 	case USB_ST_SETUP:
2731 setup:
2732 		data = STAILQ_FIRST(&sc->sc_rx_inactive);
2733 		if (data == NULL)
2734 			return;
2735 		STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next);
2736 		UATH_STAT_DEC(sc, st_rx_inactive);
2737 		STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next);
2738 		UATH_STAT_INC(sc, st_rx_active);
2739 		usbd_xfer_set_frame_data(xfer, 0, data->buf, MCLBYTES);
2740 		usbd_transfer_submit(xfer);
2741 
2742 		/*
2743 		 * To avoid LOR we should unlock our private mutex here to call
2744 		 * ieee80211_input() because here is at the end of a USB
2745 		 * callback and safe to unlock.
2746 		 */
2747 		if (sc->sc_flags & UATH_FLAG_INVALID) {
2748 			if (m != NULL)
2749 				m_freem(m);
2750 			return;
2751 		}
2752 		UATH_UNLOCK(sc);
2753 		if (m != NULL && desc != NULL) {
2754 			wh = mtod(m, struct ieee80211_frame *);
2755 			ni = ieee80211_find_rxnode(ic,
2756 			    (struct ieee80211_frame_min *)wh);
2757 			nf = -95;	/* XXX */
2758 			if (ni != NULL) {
2759 				(void) ieee80211_input(ni, m,
2760 				    (int)be32toh(desc->rssi), nf);
2761 				/* node is no longer needed */
2762 				ieee80211_free_node(ni);
2763 			} else
2764 				(void) ieee80211_input_all(ic, m,
2765 				    (int)be32toh(desc->rssi), nf);
2766 			m = NULL;
2767 			desc = NULL;
2768 		}
2769 		UATH_LOCK(sc);
2770 		uath_start(sc);
2771 		break;
2772 	default:
2773 		/* needs it to the inactive queue due to a error.  */
2774 		data = STAILQ_FIRST(&sc->sc_rx_active);
2775 		if (data != NULL) {
2776 			STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
2777 			UATH_STAT_DEC(sc, st_rx_active);
2778 			STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
2779 			UATH_STAT_INC(sc, st_rx_inactive);
2780 		}
2781 		if (error != USB_ERR_CANCELLED) {
2782 			usbd_xfer_set_stall(xfer);
2783 			counter_u64_add(ic->ic_ierrors, 1);
2784 			goto setup;
2785 		}
2786 		break;
2787 	}
2788 }
2789 
2790 static void
2791 uath_data_txeof(struct usb_xfer *xfer, struct uath_data *data)
2792 {
2793 	struct uath_softc *sc = usbd_xfer_softc(xfer);
2794 
2795 	UATH_ASSERT_LOCKED(sc);
2796 
2797 	if (data->m) {
2798 		/* XXX status? */
2799 		ieee80211_tx_complete(data->ni, data->m, 0);
2800 		data->m = NULL;
2801 		data->ni = NULL;
2802 	}
2803 	sc->sc_tx_timer = 0;
2804 }
2805 
2806 static void
2807 uath_bulk_tx_callback(struct usb_xfer *xfer, usb_error_t error)
2808 {
2809 	struct uath_softc *sc = usbd_xfer_softc(xfer);
2810 	struct uath_data *data;
2811 
2812 	UATH_ASSERT_LOCKED(sc);
2813 
2814 	switch (USB_GET_STATE(xfer)) {
2815 	case USB_ST_TRANSFERRED:
2816 		data = STAILQ_FIRST(&sc->sc_tx_active);
2817 		if (data == NULL)
2818 			goto setup;
2819 		STAILQ_REMOVE_HEAD(&sc->sc_tx_active, next);
2820 		UATH_STAT_DEC(sc, st_tx_active);
2821 		uath_data_txeof(xfer, data);
2822 		STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, data, next);
2823 		UATH_STAT_INC(sc, st_tx_inactive);
2824 		/* FALLTHROUGH */
2825 	case USB_ST_SETUP:
2826 setup:
2827 		data = STAILQ_FIRST(&sc->sc_tx_pending);
2828 		if (data == NULL) {
2829 			DPRINTF(sc, UATH_DEBUG_XMIT, "%s: empty pending queue\n",
2830 			    __func__);
2831 			return;
2832 		}
2833 		STAILQ_REMOVE_HEAD(&sc->sc_tx_pending, next);
2834 		UATH_STAT_DEC(sc, st_tx_pending);
2835 		STAILQ_INSERT_TAIL(&sc->sc_tx_active, data, next);
2836 		UATH_STAT_INC(sc, st_tx_active);
2837 
2838 		usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen);
2839 		usbd_transfer_submit(xfer);
2840 
2841 		uath_start(sc);
2842 		break;
2843 	default:
2844 		data = STAILQ_FIRST(&sc->sc_tx_active);
2845 		if (data == NULL)
2846 			goto setup;
2847 		if (data->ni != NULL) {
2848 			if_inc_counter(data->ni->ni_vap->iv_ifp,
2849 			    IFCOUNTER_OERRORS, 1);
2850 			if ((sc->sc_flags & UATH_FLAG_INVALID) == 0)
2851 				ieee80211_free_node(data->ni);
2852 			data->ni = NULL;
2853 		}
2854 		if (error != USB_ERR_CANCELLED) {
2855 			usbd_xfer_set_stall(xfer);
2856 			goto setup;
2857 		}
2858 		break;
2859 	}
2860 }
2861 
2862 static device_method_t uath_methods[] = {
2863 	DEVMETHOD(device_probe, uath_match),
2864 	DEVMETHOD(device_attach, uath_attach),
2865 	DEVMETHOD(device_detach, uath_detach),
2866 	DEVMETHOD_END
2867 };
2868 static driver_t uath_driver = {
2869 	.name = "uath",
2870 	.methods = uath_methods,
2871 	.size = sizeof(struct uath_softc)
2872 };
2873 static devclass_t uath_devclass;
2874 
2875 DRIVER_MODULE(uath, uhub, uath_driver, uath_devclass, NULL, 0);
2876 MODULE_DEPEND(uath, wlan, 1, 1, 1);
2877 MODULE_DEPEND(uath, usb, 1, 1, 1);
2878 MODULE_VERSION(uath, 1);
2879 USB_PNP_HOST_INFO(uath_devs);
2880