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