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