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