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