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