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