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