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