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