]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - sys/dev/usb/wlan/if_rsu.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / sys / dev / usb / wlan / if_rsu.c
1 /*      $OpenBSD: if_rsu.c,v 1.17 2013/04/15 09:23:01 mglocker Exp $    */
2
3 /*-
4  * Copyright (c) 2010 Damien Bergamini <damien.bergamini@free.fr>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 #include <sys/cdefs.h>
19 __FBSDID("$FreeBSD$");
20
21 /*
22  * Driver for Realtek RTL8188SU/RTL8191SU/RTL8192SU.
23  *
24  * TODO:
25  *   o 11n support
26  *   o h/w crypto
27  *   o hostap / ibss / mesh
28  */
29 #include <sys/param.h>
30 #include <sys/endian.h>
31 #include <sys/sockio.h>
32 #include <sys/mbuf.h>
33 #include <sys/kernel.h>
34 #include <sys/socket.h>
35 #include <sys/systm.h>
36 #include <sys/conf.h>
37 #include <sys/bus.h>
38 #include <sys/rman.h>
39 #include <sys/firmware.h>
40 #include <sys/module.h>
41
42 #include <machine/bus.h>
43 #include <machine/resource.h>
44
45 #include <net/bpf.h>
46 #include <net/if.h>
47 #include <net/if_arp.h>
48 #include <net/if_dl.h>
49 #include <net/if_media.h>
50 #include <net/if_types.h>
51
52 #include <netinet/in.h>
53 #include <netinet/in_systm.h>
54 #include <netinet/in_var.h>
55 #include <netinet/if_ether.h>
56 #include <netinet/ip.h>
57
58 #include <net80211/ieee80211_var.h>
59 #include <net80211/ieee80211_regdomain.h>
60 #include <net80211/ieee80211_radiotap.h>
61
62 #include <dev/usb/usb.h>
63 #include <dev/usb/usbdi.h>
64 #include "usbdevs.h"
65
66 #define USB_DEBUG_VAR rsu_debug
67 #include <dev/usb/usb_debug.h>
68
69 #include <dev/usb/wlan/if_rsureg.h>
70
71 #ifdef USB_DEBUG
72 static int rsu_debug = 0;
73 SYSCTL_NODE(_hw_usb, OID_AUTO, rsu, CTLFLAG_RW, 0, "USB rsu");
74 SYSCTL_INT(_hw_usb_rsu, OID_AUTO, debug, CTLFLAG_RW, &rsu_debug, 0,
75     "Debug level");
76 #endif
77
78 static const STRUCT_USB_HOST_ID rsu_devs[] = {
79 #define RSU_HT_NOT_SUPPORTED 0
80 #define RSU_HT_SUPPORTED 1
81 #define RSU_DEV_HT(v,p)  { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \
82                                    RSU_HT_SUPPORTED) }
83 #define RSU_DEV(v,p)     { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \
84                                    RSU_HT_NOT_SUPPORTED) }
85         RSU_DEV(ASUS,                   RTL8192SU),
86         RSU_DEV(AZUREWAVE,              RTL8192SU_4),
87         RSU_DEV_HT(ACCTON,              RTL8192SU),
88         RSU_DEV_HT(ASUS,                USBN10),
89         RSU_DEV_HT(AZUREWAVE,           RTL8192SU_1),
90         RSU_DEV_HT(AZUREWAVE,           RTL8192SU_2),
91         RSU_DEV_HT(AZUREWAVE,           RTL8192SU_3),
92         RSU_DEV_HT(AZUREWAVE,           RTL8192SU_5),
93         RSU_DEV_HT(BELKIN,              RTL8192SU_1),
94         RSU_DEV_HT(BELKIN,              RTL8192SU_2),
95         RSU_DEV_HT(BELKIN,              RTL8192SU_3),
96         RSU_DEV_HT(CONCEPTRONIC2,       RTL8192SU_1),
97         RSU_DEV_HT(CONCEPTRONIC2,       RTL8192SU_2),
98         RSU_DEV_HT(CONCEPTRONIC2,       RTL8192SU_3),
99         RSU_DEV_HT(COREGA,              RTL8192SU),
100         RSU_DEV_HT(DLINK2,              DWA131A1),
101         RSU_DEV_HT(DLINK2,              RTL8192SU_1),
102         RSU_DEV_HT(DLINK2,              RTL8192SU_2),
103         RSU_DEV_HT(EDIMAX,              RTL8192SU_1),
104         RSU_DEV_HT(EDIMAX,              RTL8192SU_2),
105         RSU_DEV_HT(EDIMAX,              RTL8192SU_3),
106         RSU_DEV_HT(GUILLEMOT,           HWGUN54),
107         RSU_DEV_HT(GUILLEMOT,           HWNUM300),
108         RSU_DEV_HT(HAWKING,             RTL8192SU_1),
109         RSU_DEV_HT(HAWKING,             RTL8192SU_2),
110         RSU_DEV_HT(PLANEX2,             GWUSNANO),
111         RSU_DEV_HT(REALTEK,             RTL8171),
112         RSU_DEV_HT(REALTEK,             RTL8172),
113         RSU_DEV_HT(REALTEK,             RTL8173),
114         RSU_DEV_HT(REALTEK,             RTL8174),
115         RSU_DEV_HT(REALTEK,             RTL8192SU),
116         RSU_DEV_HT(REALTEK,             RTL8712),
117         RSU_DEV_HT(REALTEK,             RTL8713),
118         RSU_DEV_HT(SENAO,               RTL8192SU_1),
119         RSU_DEV_HT(SENAO,               RTL8192SU_2),
120         RSU_DEV_HT(SITECOMEU,           WL349V1),
121         RSU_DEV_HT(SITECOMEU,           WL353),
122         RSU_DEV_HT(SWEEX2,              LW154),
123 #undef RSU_DEV_HT
124 #undef RSU_DEV
125 };
126
127 static device_probe_t   rsu_match;
128 static device_attach_t  rsu_attach;
129 static device_detach_t  rsu_detach;
130 static usb_callback_t   rsu_bulk_tx_callback;
131 static usb_callback_t   rsu_bulk_rx_callback;
132 static usb_error_t      rsu_do_request(struct rsu_softc *,
133                             struct usb_device_request *, void *);
134 static struct ieee80211vap *
135                 rsu_vap_create(struct ieee80211com *, const char name[],
136                     int, enum ieee80211_opmode, int, const uint8_t bssid[],
137                     const uint8_t mac[]);
138 static void     rsu_vap_delete(struct ieee80211vap *);
139 static void     rsu_scan_start(struct ieee80211com *);
140 static void     rsu_scan_end(struct ieee80211com *);
141 static void     rsu_set_channel(struct ieee80211com *);
142 static void     rsu_update_mcast(struct ifnet *);
143 static int      rsu_alloc_rx_list(struct rsu_softc *);
144 static void     rsu_free_rx_list(struct rsu_softc *);
145 static int      rsu_alloc_tx_list(struct rsu_softc *);
146 static void     rsu_free_tx_list(struct rsu_softc *);
147 static void     rsu_free_list(struct rsu_softc *, struct rsu_data [], int);
148 static struct rsu_data *_rsu_getbuf(struct rsu_softc *);
149 static struct rsu_data *rsu_getbuf(struct rsu_softc *);
150 static int      rsu_write_region_1(struct rsu_softc *, uint16_t, uint8_t *,
151                     int);
152 static void     rsu_write_1(struct rsu_softc *, uint16_t, uint8_t);
153 static void     rsu_write_2(struct rsu_softc *, uint16_t, uint16_t);
154 static void     rsu_write_4(struct rsu_softc *, uint16_t, uint32_t);
155 static int      rsu_read_region_1(struct rsu_softc *, uint16_t, uint8_t *,
156                     int);
157 static uint8_t  rsu_read_1(struct rsu_softc *, uint16_t);
158 static uint16_t rsu_read_2(struct rsu_softc *, uint16_t);
159 static uint32_t rsu_read_4(struct rsu_softc *, uint16_t);
160 static int      rsu_fw_iocmd(struct rsu_softc *, uint32_t);
161 static uint8_t  rsu_efuse_read_1(struct rsu_softc *, uint16_t);
162 static int      rsu_read_rom(struct rsu_softc *);
163 static int      rsu_fw_cmd(struct rsu_softc *, uint8_t, void *, int);
164 static void     rsu_calib_task(void *, int);
165 static int      rsu_newstate(struct ieee80211vap *, enum ieee80211_state, int);
166 #ifdef notyet
167 static void     rsu_set_key(struct rsu_softc *, const struct ieee80211_key *);
168 static void     rsu_delete_key(struct rsu_softc *, const struct ieee80211_key *);
169 #endif
170 static int      rsu_site_survey(struct rsu_softc *, struct ieee80211vap *);
171 static int      rsu_join_bss(struct rsu_softc *, struct ieee80211_node *);
172 static int      rsu_disconnect(struct rsu_softc *);
173 static void     rsu_event_survey(struct rsu_softc *, uint8_t *, int);
174 static void     rsu_event_join_bss(struct rsu_softc *, uint8_t *, int);
175 static void     rsu_rx_event(struct rsu_softc *, uint8_t, uint8_t *, int);
176 static void     rsu_rx_multi_event(struct rsu_softc *, uint8_t *, int);
177 static int8_t   rsu_get_rssi(struct rsu_softc *, int, void *);
178 static struct mbuf *
179                 rsu_rx_frame(struct rsu_softc *, uint8_t *, int, int *);
180 static struct mbuf *
181                 rsu_rx_multi_frame(struct rsu_softc *, uint8_t *, int, int *);
182 static struct mbuf *
183                 rsu_rxeof(struct usb_xfer *, struct rsu_data *, int *);
184 static void     rsu_txeof(struct usb_xfer *, struct rsu_data *);
185 static int      rsu_raw_xmit(struct ieee80211_node *, struct mbuf *, 
186                     const struct ieee80211_bpf_params *);
187 static void     rsu_init(void *);
188 static void     rsu_init_locked(struct rsu_softc *);
189 static void     rsu_watchdog(void *);
190 static int      rsu_tx_start(struct rsu_softc *, struct ieee80211_node *, 
191                     struct mbuf *, struct rsu_data *);
192 static void     rsu_start(struct ifnet *);
193 static void     rsu_start_locked(struct ifnet *);
194 static int      rsu_ioctl(struct ifnet *, u_long, caddr_t);
195 static void     rsu_stop(struct ifnet *, int);
196 static void     rsu_stop_locked(struct ifnet *, int);
197
198 static device_method_t rsu_methods[] = {
199         DEVMETHOD(device_probe,         rsu_match),
200         DEVMETHOD(device_attach,        rsu_attach),
201         DEVMETHOD(device_detach,        rsu_detach),
202
203         DEVMETHOD_END
204 };
205
206 static driver_t rsu_driver = {
207         .name = "rsu",
208         .methods = rsu_methods,
209         .size = sizeof(struct rsu_softc)
210 };
211
212 static devclass_t rsu_devclass;
213
214 DRIVER_MODULE(rsu, uhub, rsu_driver, rsu_devclass, NULL, 0);
215 MODULE_DEPEND(rsu, wlan, 1, 1, 1);
216 MODULE_DEPEND(rsu, usb, 1, 1, 1);
217 MODULE_DEPEND(rsu, firmware, 1, 1, 1);
218 MODULE_VERSION(rsu, 1);
219
220 static const struct usb_config rsu_config[RSU_N_TRANSFER] = {
221         [RSU_BULK_RX] = {
222                 .type = UE_BULK,
223                 .endpoint = UE_ADDR_ANY,
224                 .direction = UE_DIR_IN,
225                 .bufsize = RSU_RXBUFSZ,
226                 .flags = {
227                         .pipe_bof = 1,
228                         .short_xfer_ok = 1
229                 },
230                 .callback = rsu_bulk_rx_callback
231         },
232         [RSU_BULK_TX_BE] = {
233                 .type = UE_BULK,
234                 .endpoint = 0x06,
235                 .direction = UE_DIR_OUT,
236                 .bufsize = RSU_TXBUFSZ,
237                 .flags = {
238                         .ext_buffer = 1,
239                         .pipe_bof = 1,
240                         .force_short_xfer = 1
241                 },
242                 .callback = rsu_bulk_tx_callback,
243                 .timeout = RSU_TX_TIMEOUT
244         },
245         [RSU_BULK_TX_BK] = {
246                 .type = UE_BULK,
247                 .endpoint = 0x06,
248                 .direction = UE_DIR_OUT,
249                 .bufsize = RSU_TXBUFSZ,
250                 .flags = {
251                         .ext_buffer = 1,
252                         .pipe_bof = 1,
253                         .force_short_xfer = 1
254                 },
255                 .callback = rsu_bulk_tx_callback,
256                 .timeout = RSU_TX_TIMEOUT
257         },
258         [RSU_BULK_TX_VI] = {
259                 .type = UE_BULK,
260                 .endpoint = 0x04,
261                 .direction = UE_DIR_OUT,
262                 .bufsize = RSU_TXBUFSZ,
263                 .flags = {
264                         .ext_buffer = 1,
265                         .pipe_bof = 1,
266                         .force_short_xfer = 1
267                 },
268                 .callback = rsu_bulk_tx_callback,
269                 .timeout = RSU_TX_TIMEOUT
270         },
271         [RSU_BULK_TX_VO] = {
272                 .type = UE_BULK,
273                 .endpoint = 0x04,
274                 .direction = UE_DIR_OUT,
275                 .bufsize = RSU_TXBUFSZ,
276                 .flags = {
277                         .ext_buffer = 1,
278                         .pipe_bof = 1,
279                         .force_short_xfer = 1
280                 },
281                 .callback = rsu_bulk_tx_callback,
282                 .timeout = RSU_TX_TIMEOUT
283         },
284 };
285
286 static int
287 rsu_match(device_t self)
288 {
289         struct usb_attach_arg *uaa = device_get_ivars(self);
290
291         if (uaa->usb_mode != USB_MODE_HOST ||
292             uaa->info.bIfaceIndex != 0 ||
293             uaa->info.bConfigIndex != 0)
294                 return (ENXIO);
295
296         return (usbd_lookup_id_by_uaa(rsu_devs, sizeof(rsu_devs), uaa));
297 }
298
299 static int
300 rsu_attach(device_t self)
301 {
302         struct usb_attach_arg *uaa = device_get_ivars(self);
303         struct rsu_softc *sc = device_get_softc(self);
304         struct ifnet *ifp;
305         struct ieee80211com *ic;
306         int error;
307         uint8_t iface_index, bands;
308
309         device_set_usb_desc(self);
310         sc->sc_udev = uaa->device;
311         sc->sc_dev = self;
312
313         mtx_init(&sc->sc_mtx, device_get_nameunit(self), MTX_NETWORK_LOCK,
314             MTX_DEF);
315         TIMEOUT_TASK_INIT(taskqueue_thread, &sc->calib_task, 0, 
316             rsu_calib_task, sc);
317         callout_init(&sc->sc_watchdog_ch, 0);
318
319         iface_index = 0;
320         error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
321             rsu_config, RSU_N_TRANSFER, sc, &sc->sc_mtx);
322         if (error) {
323                 device_printf(sc->sc_dev,
324                     "could not allocate USB transfers, err=%s\n", 
325                     usbd_errstr(error));
326                 goto fail_usb;
327         }
328         RSU_LOCK(sc);
329         /* Read chip revision. */
330         sc->cut = MS(rsu_read_4(sc, R92S_PMC_FSM), R92S_PMC_FSM_CUT);
331         if (sc->cut != 3)
332                 sc->cut = (sc->cut >> 1) + 1;
333         error = rsu_read_rom(sc);
334         if (error != 0) {
335                 device_printf(self, "could not read ROM\n");
336                 goto fail_rom;
337         }
338         RSU_UNLOCK(sc);
339         IEEE80211_ADDR_COPY(sc->sc_bssid, &sc->rom[0x12]);
340         device_printf(self, "MAC/BB RTL8712 cut %d\n", sc->cut);
341         ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
342         if (ifp == NULL) {
343                 device_printf(self, "cannot allocate interface\n");
344                 goto fail_ifalloc;
345         }
346         ic = ifp->if_l2com;
347         ifp->if_softc = sc;
348         if_initname(ifp, "rsu", device_get_unit(self));
349         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
350         ifp->if_init = rsu_init;
351         ifp->if_ioctl = rsu_ioctl;
352         ifp->if_start = rsu_start;
353         IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
354         ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
355         IFQ_SET_READY(&ifp->if_snd);
356         ifp->if_capabilities |= IFCAP_RXCSUM;
357         ifp->if_capenable |= IFCAP_RXCSUM;
358         ifp->if_hwassist = CSUM_TCP;
359
360         ic->ic_ifp = ifp;
361         ic->ic_phytype = IEEE80211_T_OFDM;      /* Not only, but not used. */
362         ic->ic_opmode = IEEE80211_M_STA;        /* Default to BSS mode. */
363
364         /* Set device capabilities. */
365         ic->ic_caps =
366             IEEE80211_C_STA |           /* station mode */
367             IEEE80211_C_BGSCAN |        /* Background scan. */
368             IEEE80211_C_SHPREAMBLE |    /* Short preamble supported. */
369             IEEE80211_C_SHSLOT |        /* Short slot time supported. */
370             IEEE80211_C_WPA;            /* WPA/RSN. */
371
372 #if 0
373         /* Check if HT support is present. */
374         if (usb_lookup(rsu_devs_noht, uaa->vendor, uaa->product) == NULL) {
375                 /* Set HT capabilities. */
376                 ic->ic_htcaps =
377                     IEEE80211_HTCAP_CBW20_40 |
378                     IEEE80211_HTCAP_DSSSCCK40;
379                 /* Set supported HT rates. */
380                 for (i = 0; i < 2; i++)
381                         ic->ic_sup_mcs[i] = 0xff;
382         }
383 #endif
384
385         /* Set supported .11b and .11g rates. */
386         bands = 0;
387         setbit(&bands, IEEE80211_MODE_11B);
388         setbit(&bands, IEEE80211_MODE_11G);
389         ieee80211_init_channels(ic, NULL, &bands);
390
391         ieee80211_ifattach(ic, sc->sc_bssid);
392         ic->ic_raw_xmit = rsu_raw_xmit;
393         ic->ic_scan_start = rsu_scan_start;
394         ic->ic_scan_end = rsu_scan_end;
395         ic->ic_set_channel = rsu_set_channel;
396         ic->ic_vap_create = rsu_vap_create;
397         ic->ic_vap_delete = rsu_vap_delete;
398         ic->ic_update_mcast = rsu_update_mcast;
399
400         ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr,
401             sizeof(sc->sc_txtap), RSU_TX_RADIOTAP_PRESENT, 
402             &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
403             RSU_RX_RADIOTAP_PRESENT);
404
405         if (bootverbose)
406                 ieee80211_announce(ic);
407
408         return (0);
409
410 fail_ifalloc:
411 fail_rom:
412         usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER);
413 fail_usb:
414         mtx_destroy(&sc->sc_mtx);
415         return (ENXIO);
416 }
417
418 static int
419 rsu_detach(device_t self)
420 {
421         struct rsu_softc *sc = device_get_softc(self);
422         struct ifnet *ifp = sc->sc_ifp;
423         struct ieee80211com *ic = ifp->if_l2com;
424
425         if (!device_is_attached(self))
426                 return (0);
427         rsu_stop(ifp, 1);
428         usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER);
429         ieee80211_ifdetach(ic);
430
431         callout_drain(&sc->sc_watchdog_ch);
432         taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task);
433
434         /* Free Tx/Rx buffers. */
435         rsu_free_tx_list(sc);
436         rsu_free_rx_list(sc);
437
438         if_free(ifp);
439         mtx_destroy(&sc->sc_mtx);
440
441         return (0);
442 }
443
444 static usb_error_t
445 rsu_do_request(struct rsu_softc *sc, struct usb_device_request *req,
446     void *data)
447 {
448         usb_error_t err;
449         int ntries = 10;
450         
451         RSU_ASSERT_LOCKED(sc);
452
453         while (ntries--) {
454                 err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
455                     req, data, 0, NULL, 250 /* ms */);
456                 if (err == 0 || !device_is_attached(sc->sc_dev))
457                         break;
458                 DPRINTFN(1, "Control request failed, %s (retrying)\n",
459                     usbd_errstr(err));
460                 usb_pause_mtx(&sc->sc_mtx, hz / 100);
461         }
462
463         return (err);
464 }
465
466 static struct ieee80211vap *
467 rsu_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
468     enum ieee80211_opmode opmode, int flags,
469     const uint8_t bssid[IEEE80211_ADDR_LEN],
470     const uint8_t mac[IEEE80211_ADDR_LEN])
471 {
472         struct rsu_vap *uvp;
473         struct ieee80211vap *vap;
474
475         if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
476                 return (NULL);
477
478         uvp = (struct rsu_vap *) malloc(sizeof(struct rsu_vap),
479             M_80211_VAP, M_NOWAIT | M_ZERO);
480         if (uvp == NULL)
481                 return (NULL);
482         vap = &uvp->vap;
483         ieee80211_vap_setup(ic, vap, name, unit, opmode,
484             flags, bssid, mac);
485
486         /* override state transition machine */
487         uvp->newstate = vap->iv_newstate;
488         vap->iv_newstate = rsu_newstate;
489
490         /* complete setup */
491         ieee80211_vap_attach(vap, ieee80211_media_change,
492             ieee80211_media_status);
493         ic->ic_opmode = opmode;
494
495         return (vap);
496 }
497
498 static void
499 rsu_vap_delete(struct ieee80211vap *vap)
500 {
501         struct rsu_vap *uvp = RSU_VAP(vap);
502
503         ieee80211_vap_detach(vap);
504         free(uvp, M_80211_VAP);
505 }
506
507 static void
508 rsu_scan_start(struct ieee80211com *ic)
509 {
510         int error;
511         struct ifnet *ifp = ic->ic_ifp;
512         struct rsu_softc *sc = ifp->if_softc;
513
514         /* Scanning is done by the firmware. */
515         RSU_LOCK(sc);
516         error = rsu_site_survey(sc, TAILQ_FIRST(&ic->ic_vaps));
517         RSU_UNLOCK(sc);
518         if (error != 0)
519                 device_printf(sc->sc_dev,
520                     "could not send site survey command\n");
521 }
522
523 static void
524 rsu_scan_end(struct ieee80211com *ic)
525 {
526         /* Nothing to do here. */
527 }
528
529 static void
530 rsu_set_channel(struct ieee80211com *ic __unused)
531 {
532         /* We are unable to switch channels, yet. */
533 }
534
535 static void
536 rsu_update_mcast(struct ifnet *ifp)
537 {
538         /* XXX do nothing?  */
539 }
540
541 static int
542 rsu_alloc_list(struct rsu_softc *sc, struct rsu_data data[],
543     int ndata, int maxsz)
544 {
545         int i, error;
546
547         for (i = 0; i < ndata; i++) {
548                 struct rsu_data *dp = &data[i];
549                 dp->sc = sc;
550                 dp->m = NULL;
551                 dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT);
552                 if (dp->buf == NULL) {
553                         device_printf(sc->sc_dev,
554                             "could not allocate buffer\n");
555                         error = ENOMEM;
556                         goto fail;
557                 }
558                 dp->ni = NULL;
559         }
560
561         return (0);
562 fail:
563         rsu_free_list(sc, data, ndata);
564         return (error);
565 }
566
567 static int
568 rsu_alloc_rx_list(struct rsu_softc *sc)
569 {
570         int error, i;
571
572         error = rsu_alloc_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT,
573             RSU_RXBUFSZ);
574         if (error != 0)
575                 return (error);
576
577         STAILQ_INIT(&sc->sc_rx_active);
578         STAILQ_INIT(&sc->sc_rx_inactive);
579
580         for (i = 0; i < RSU_RX_LIST_COUNT; i++)
581                 STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i], next);
582
583         return (0);
584 }
585
586 static int
587 rsu_alloc_tx_list(struct rsu_softc *sc)
588 {
589         int error, i;
590
591         error = rsu_alloc_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT,
592             RSU_TXBUFSZ);
593         if (error != 0)
594                 return (error);
595
596         STAILQ_INIT(&sc->sc_tx_active);
597         STAILQ_INIT(&sc->sc_tx_inactive);
598         STAILQ_INIT(&sc->sc_tx_pending);
599
600         for (i = 0; i < RSU_TX_LIST_COUNT; i++) {
601                 STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i], next);
602         }
603
604         return (0);
605 }
606
607 static void
608 rsu_free_tx_list(struct rsu_softc *sc)
609 {
610         rsu_free_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT);
611 }
612
613 static void
614 rsu_free_rx_list(struct rsu_softc *sc)
615 {
616         rsu_free_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT);
617 }
618
619 static void
620 rsu_free_list(struct rsu_softc *sc, struct rsu_data data[], int ndata)
621 {
622         int i;
623
624         for (i = 0; i < ndata; i++) {
625                 struct rsu_data *dp = &data[i];
626
627                 if (dp->buf != NULL) {
628                         free(dp->buf, M_USBDEV);
629                         dp->buf = NULL;
630                 }
631                 if (dp->ni != NULL) {
632                         ieee80211_free_node(dp->ni);
633                         dp->ni = NULL;
634                 }
635         }
636 }
637
638 static struct rsu_data *
639 _rsu_getbuf(struct rsu_softc *sc)
640 {
641         struct rsu_data *bf;
642
643         bf = STAILQ_FIRST(&sc->sc_tx_inactive);
644         if (bf != NULL)
645                 STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next);
646         else
647                 bf = NULL;
648         if (bf == NULL)
649                 DPRINTF("out of xmit buffers\n");
650         return (bf);
651 }
652
653 static struct rsu_data *
654 rsu_getbuf(struct rsu_softc *sc)
655 {
656         struct rsu_data *bf;
657
658         RSU_ASSERT_LOCKED(sc);
659
660         bf = _rsu_getbuf(sc);
661         if (bf == NULL) {
662                 struct ifnet *ifp = sc->sc_ifp;
663                 DPRINTF("stop queue\n");
664                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
665         }
666         return (bf);
667 }
668
669 static int
670 rsu_write_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
671     int len)
672 {
673         usb_device_request_t req;
674
675         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
676         req.bRequest = R92S_REQ_REGS;
677         USETW(req.wValue, addr);
678         USETW(req.wIndex, 0);
679         USETW(req.wLength, len);
680
681         return (rsu_do_request(sc, &req, buf));
682 }
683
684 static void
685 rsu_write_1(struct rsu_softc *sc, uint16_t addr, uint8_t val)
686 {
687         rsu_write_region_1(sc, addr, &val, 1);
688 }
689
690 static void
691 rsu_write_2(struct rsu_softc *sc, uint16_t addr, uint16_t val)
692 {
693         val = htole16(val);
694         rsu_write_region_1(sc, addr, (uint8_t *)&val, 2);
695 }
696
697 static void
698 rsu_write_4(struct rsu_softc *sc, uint16_t addr, uint32_t val)
699 {
700         val = htole32(val);
701         rsu_write_region_1(sc, addr, (uint8_t *)&val, 4);
702 }
703
704 static int
705 rsu_read_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
706     int len)
707 {
708         usb_device_request_t req;
709
710         req.bmRequestType = UT_READ_VENDOR_DEVICE;
711         req.bRequest = R92S_REQ_REGS;
712         USETW(req.wValue, addr);
713         USETW(req.wIndex, 0);
714         USETW(req.wLength, len);
715
716         return (rsu_do_request(sc, &req, buf));
717 }
718
719 static uint8_t
720 rsu_read_1(struct rsu_softc *sc, uint16_t addr)
721 {
722         uint8_t val;
723
724         if (rsu_read_region_1(sc, addr, &val, 1) != 0)
725                 return (0xff);
726         return (val);
727 }
728
729 static uint16_t
730 rsu_read_2(struct rsu_softc *sc, uint16_t addr)
731 {
732         uint16_t val;
733
734         if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0)
735                 return (0xffff);
736         return (le16toh(val));
737 }
738
739 static uint32_t
740 rsu_read_4(struct rsu_softc *sc, uint16_t addr)
741 {
742         uint32_t val;
743
744         if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0)
745                 return (0xffffffff);
746         return (le32toh(val));
747 }
748
749 static int
750 rsu_fw_iocmd(struct rsu_softc *sc, uint32_t iocmd)
751 {
752         int ntries;
753
754         rsu_write_4(sc, R92S_IOCMD_CTRL, iocmd);
755         DELAY(100);
756         for (ntries = 0; ntries < 50; ntries++) {
757                 if (rsu_read_4(sc, R92S_IOCMD_CTRL) == 0)
758                         return (0);
759                 DELAY(10);
760         }
761         return (ETIMEDOUT);
762 }
763
764 static uint8_t
765 rsu_efuse_read_1(struct rsu_softc *sc, uint16_t addr)
766 {
767         uint32_t reg;
768         int ntries;
769
770         reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
771         reg = RW(reg, R92S_EFUSE_CTRL_ADDR, addr);
772         reg &= ~R92S_EFUSE_CTRL_VALID;
773         rsu_write_4(sc, R92S_EFUSE_CTRL, reg);
774         /* Wait for read operation to complete. */
775         for (ntries = 0; ntries < 100; ntries++) {
776                 reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
777                 if (reg & R92S_EFUSE_CTRL_VALID)
778                         return (MS(reg, R92S_EFUSE_CTRL_DATA));
779                 DELAY(5);
780         }
781         device_printf(sc->sc_dev,
782             "could not read efuse byte at address 0x%x\n", addr);
783         return (0xff);
784 }
785
786 static int
787 rsu_read_rom(struct rsu_softc *sc)
788 {
789         uint8_t *rom = sc->rom;
790         uint16_t addr = 0;
791         uint32_t reg;
792         uint8_t off, msk;
793         int i;
794
795         /* Make sure that ROM type is eFuse and that autoload succeeded. */
796         reg = rsu_read_1(sc, R92S_EE_9346CR);
797         if ((reg & (R92S_9356SEL | R92S_EEPROM_EN)) != R92S_EEPROM_EN)
798                 return (EIO);
799
800         /* Turn on 2.5V to prevent eFuse leakage. */
801         reg = rsu_read_1(sc, R92S_EFUSE_TEST + 3);
802         rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg | 0x80);
803         DELAY(1000);
804         rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg & ~0x80);
805
806         /* Read full ROM image. */
807         memset(&sc->rom, 0xff, sizeof(sc->rom));
808         while (addr < 512) {
809                 reg = rsu_efuse_read_1(sc, addr);
810                 if (reg == 0xff)
811                         break;
812                 addr++;
813                 off = reg >> 4;
814                 msk = reg & 0xf;
815                 for (i = 0; i < 4; i++) {
816                         if (msk & (1 << i))
817                                 continue;
818                         rom[off * 8 + i * 2 + 0] =
819                             rsu_efuse_read_1(sc, addr);
820                         addr++;
821                         rom[off * 8 + i * 2 + 1] =
822                             rsu_efuse_read_1(sc, addr);
823                         addr++;
824                 }
825         }
826 #ifdef USB_DEBUG
827         if (rsu_debug >= 5) {
828                 /* Dump ROM content. */
829                 printf("\n");
830                 for (i = 0; i < sizeof(sc->rom); i++)
831                         printf("%02x:", rom[i]);
832                 printf("\n");
833         }
834 #endif
835         return (0);
836 }
837
838 static int
839 rsu_fw_cmd(struct rsu_softc *sc, uint8_t code, void *buf, int len)
840 {
841         struct rsu_data *data;
842         struct r92s_tx_desc *txd;
843         struct r92s_fw_cmd_hdr *cmd;
844         int cmdsz, xferlen;
845
846         data = rsu_getbuf(sc);
847         if (data == NULL)
848                 return (ENOMEM);
849
850         /* Round-up command length to a multiple of 8 bytes. */
851         cmdsz = (len + 7) & ~7;
852
853         xferlen = sizeof(*txd) + sizeof(*cmd) + cmdsz;
854         KASSERT(xferlen <= RSU_TXBUFSZ, ("%s: invalid length", __func__));
855         memset(data->buf, 0, xferlen);
856
857         /* Setup Tx descriptor. */
858         txd = (struct r92s_tx_desc *)data->buf;
859         txd->txdw0 = htole32(
860             SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
861             SM(R92S_TXDW0_PKTLEN, sizeof(*cmd) + cmdsz) |
862             R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
863         txd->txdw1 = htole32(SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_H2C));
864
865         /* Setup command header. */
866         cmd = (struct r92s_fw_cmd_hdr *)&txd[1];
867         cmd->len = htole16(cmdsz);
868         cmd->code = code;
869         cmd->seq = sc->cmd_seq;
870         sc->cmd_seq = (sc->cmd_seq + 1) & 0x7f;
871
872         /* Copy command payload. */
873         memcpy(&cmd[1], buf, len);
874
875         DPRINTFN(2, "Tx cmd code=0x%x len=0x%x\n", code, cmdsz);
876         data->buflen = xferlen;
877         STAILQ_INSERT_TAIL(&sc->sc_tx_pending, data, next);
878         usbd_transfer_start(sc->sc_xfer[RSU_BULK_TX_VO]);
879
880         return (0);
881 }
882
883 /* ARGSUSED */
884 static void
885 rsu_calib_task(void *arg, int pending __unused)
886 {
887         struct rsu_softc *sc = arg;
888         uint32_t reg;
889
890         DPRINTFN(6, "running calibration task\n");
891         RSU_LOCK(sc);
892 #ifdef notyet
893         /* Read WPS PBC status. */
894         rsu_write_1(sc, R92S_MAC_PINMUX_CTRL,
895             R92S_GPIOMUX_EN | SM(R92S_GPIOSEL_GPIO, R92S_GPIOSEL_GPIO_JTAG));
896         rsu_write_1(sc, R92S_GPIO_IO_SEL,
897             rsu_read_1(sc, R92S_GPIO_IO_SEL) & ~R92S_GPIO_WPS);
898         reg = rsu_read_1(sc, R92S_GPIO_CTRL);
899         if (reg != 0xff && (reg & R92S_GPIO_WPS))
900                 DPRINTF(("WPS PBC is pushed\n"));
901 #endif
902         /* Read current signal level. */
903         if (rsu_fw_iocmd(sc, 0xf4000001) == 0) {
904                 reg = rsu_read_4(sc, R92S_IOCMD_DATA);
905                 DPRINTFN(8, "RSSI=%d%%\n", reg >> 4);
906         }
907         if (sc->sc_calibrating) {
908                 RSU_UNLOCK(sc);
909                 taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, 
910                     hz * 2);
911         } else
912                 RSU_UNLOCK(sc);
913 }
914
915 static int
916 rsu_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
917 {
918         struct rsu_vap *uvp = RSU_VAP(vap);
919         struct ieee80211com *ic = vap->iv_ic;
920         struct rsu_softc *sc = ic->ic_ifp->if_softc;
921         struct ieee80211_node *ni;
922         struct ieee80211_rateset *rs;
923         enum ieee80211_state ostate;
924         int error, startcal = 0;
925
926         ostate = vap->iv_state;
927         DPRINTF("%s -> %s\n", ieee80211_state_name[ostate],
928             ieee80211_state_name[nstate]);
929
930         IEEE80211_UNLOCK(ic);
931         if (ostate == IEEE80211_S_RUN) {
932                 RSU_LOCK(sc);
933                 /* Stop calibration. */
934                 sc->sc_calibrating = 0;
935                 RSU_UNLOCK(sc);
936                 taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task);
937                 /* Disassociate from our current BSS. */
938                 RSU_LOCK(sc);
939                 rsu_disconnect(sc);
940         } else
941                 RSU_LOCK(sc);
942         switch (nstate) {
943         case IEEE80211_S_INIT:
944                 break;
945         case IEEE80211_S_AUTH:
946                 ni = ieee80211_ref_node(vap->iv_bss);
947                 error = rsu_join_bss(sc, ni);
948                 ieee80211_free_node(ni);
949                 if (error != 0) {
950                         device_printf(sc->sc_dev,
951                             "could not send join command\n");
952                 }
953                 break;
954         case IEEE80211_S_RUN:
955                 ni = ieee80211_ref_node(vap->iv_bss);
956                 rs = &ni->ni_rates;
957                 /* Indicate highest supported rate. */
958                 ni->ni_txrate = rs->rs_rates[rs->rs_nrates - 1];
959                 ieee80211_free_node(ni);
960                 startcal = 1;
961                 break;
962         default:
963                 break;
964         }
965         sc->sc_calibrating = 1;
966         RSU_UNLOCK(sc);
967         IEEE80211_LOCK(ic);
968         /* Start periodic calibration. */
969         taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, hz * 2);
970
971         return (uvp->newstate(vap, nstate, arg));
972 }
973
974 #ifdef notyet
975 static void
976 rsu_set_key(struct rsu_softc *sc, const struct ieee80211_key *k)
977 {
978         struct r92s_fw_cmd_set_key key;
979
980         memset(&key, 0, sizeof(key));
981         /* Map net80211 cipher to HW crypto algorithm. */
982         switch (k->wk_cipher->ic_cipher) {
983         case IEEE80211_CIPHER_WEP:
984                 if (k->wk_keylen < 8)
985                         key.algo = R92S_KEY_ALGO_WEP40;
986                 else
987                         key.algo = R92S_KEY_ALGO_WEP104;
988                 break;
989         case IEEE80211_CIPHER_TKIP:
990                 key.algo = R92S_KEY_ALGO_TKIP;
991                 break;
992         case IEEE80211_CIPHER_AES_CCM:
993                 key.algo = R92S_KEY_ALGO_AES;
994                 break;
995         default:
996                 return;
997         }
998         key.id = k->wk_keyix;
999         key.grpkey = (k->wk_flags & IEEE80211_KEY_GROUP) != 0;
1000         memcpy(key.key, k->wk_key, MIN(k->wk_keylen, sizeof(key.key)));
1001         (void)rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
1002 }
1003
1004 static void
1005 rsu_delete_key(struct rsu_softc *sc, const struct ieee80211_key *k)
1006 {
1007         struct r92s_fw_cmd_set_key key;
1008
1009         memset(&key, 0, sizeof(key));
1010         key.id = k->wk_keyix;
1011         (void)rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
1012 }
1013 #endif
1014
1015 static int
1016 rsu_site_survey(struct rsu_softc *sc, struct ieee80211vap *vap)
1017 {
1018         struct r92s_fw_cmd_sitesurvey cmd;
1019         struct ifnet *ifp = sc->sc_ifp;
1020         struct ieee80211com *ic = ifp->if_l2com;
1021
1022         memset(&cmd, 0, sizeof(cmd));
1023         if ((ic->ic_flags & IEEE80211_F_ASCAN) || sc->scan_pass == 1)
1024                 cmd.active = htole32(1);
1025         cmd.limit = htole32(48);
1026         if (sc->scan_pass == 1 && vap->iv_des_nssid > 0) {
1027                 /* Do a directed scan for second pass. */
1028                 cmd.ssidlen = htole32(vap->iv_des_ssid[0].len);
1029                 memcpy(cmd.ssid, vap->iv_des_ssid[0].ssid,
1030                     vap->iv_des_ssid[0].len);
1031
1032         }
1033         DPRINTF("sending site survey command, pass=%d\n", sc->scan_pass);
1034         return (rsu_fw_cmd(sc, R92S_CMD_SITE_SURVEY, &cmd, sizeof(cmd)));
1035 }
1036
1037 static int
1038 rsu_join_bss(struct rsu_softc *sc, struct ieee80211_node *ni)
1039 {
1040         struct ifnet *ifp = sc->sc_ifp;
1041         struct ieee80211com *ic = ifp->if_l2com;
1042         struct ieee80211vap *vap = ni->ni_vap;
1043         struct ndis_wlan_bssid_ex *bss;
1044         struct ndis_802_11_fixed_ies *fixed;
1045         struct r92s_fw_cmd_auth auth;
1046         uint8_t buf[sizeof(*bss) + 128], *frm;
1047         uint8_t opmode;
1048         int error;
1049
1050         /* Let the FW decide the opmode based on the capinfo field. */
1051         opmode = NDIS802_11AUTOUNKNOWN;
1052         DPRINTF("setting operating mode to %d\n", opmode);
1053         error = rsu_fw_cmd(sc, R92S_CMD_SET_OPMODE, &opmode, sizeof(opmode));
1054         if (error != 0)
1055                 return (error);
1056
1057         memset(&auth, 0, sizeof(auth));
1058         if (vap->iv_flags & IEEE80211_F_WPA) {
1059                 auth.mode = R92S_AUTHMODE_WPA;
1060                 auth.dot1x = ni->ni_authmode == IEEE80211_AUTH_8021X;
1061         } else
1062                 auth.mode = R92S_AUTHMODE_OPEN;
1063         DPRINTF("setting auth mode to %d\n", auth.mode);
1064         error = rsu_fw_cmd(sc, R92S_CMD_SET_AUTH, &auth, sizeof(auth));
1065         if (error != 0)
1066                 return (error);
1067
1068         memset(buf, 0, sizeof(buf));
1069         bss = (struct ndis_wlan_bssid_ex *)buf;
1070         IEEE80211_ADDR_COPY(bss->macaddr, ni->ni_bssid);
1071         bss->ssid.ssidlen = htole32(ni->ni_esslen);
1072         memcpy(bss->ssid.ssid, ni->ni_essid, ni->ni_esslen);
1073         if (vap->iv_flags & (IEEE80211_F_PRIVACY | IEEE80211_F_WPA))
1074                 bss->privacy = htole32(1);
1075         bss->rssi = htole32(ni->ni_avgrssi);
1076         if (ic->ic_curmode == IEEE80211_MODE_11B)
1077                 bss->networktype = htole32(NDIS802_11DS);
1078         else
1079                 bss->networktype = htole32(NDIS802_11OFDM24);
1080         bss->config.len = htole32(sizeof(bss->config));
1081         bss->config.bintval = htole32(ni->ni_intval);
1082         bss->config.dsconfig = htole32(ieee80211_chan2ieee(ic, ni->ni_chan));
1083         bss->inframode = htole32(NDIS802_11INFRASTRUCTURE);
1084         memcpy(bss->supprates, ni->ni_rates.rs_rates,
1085             ni->ni_rates.rs_nrates);
1086         /* Write the fixed fields of the beacon frame. */
1087         fixed = (struct ndis_802_11_fixed_ies *)&bss[1];
1088         memcpy(&fixed->tstamp, ni->ni_tstamp.data, 8);
1089         fixed->bintval = htole16(ni->ni_intval);
1090         fixed->capabilities = htole16(ni->ni_capinfo);
1091         /* Write IEs to be included in the association request. */
1092         frm = (uint8_t *)&fixed[1];
1093         frm = ieee80211_add_rsn(frm, vap);
1094         frm = ieee80211_add_wpa(frm, vap);
1095         frm = ieee80211_add_qos(frm, ni);
1096         if (ni->ni_flags & IEEE80211_NODE_HT)
1097                 frm = ieee80211_add_htcap(frm, ni);
1098         bss->ieslen = htole32(frm - (uint8_t *)fixed);
1099         bss->len = htole32(((frm - buf) + 3) & ~3);
1100         DPRINTF("sending join bss command to %s chan %d\n",
1101             ether_sprintf(bss->macaddr), le32toh(bss->config.dsconfig));
1102         return (rsu_fw_cmd(sc, R92S_CMD_JOIN_BSS, buf, sizeof(buf)));
1103 }
1104
1105 static int
1106 rsu_disconnect(struct rsu_softc *sc)
1107 {
1108         uint32_t zero = 0;      /* :-) */
1109
1110         /* Disassociate from our current BSS. */
1111         DPRINTF("sending disconnect command\n");
1112         return (rsu_fw_cmd(sc, R92S_CMD_DISCONNECT, &zero, sizeof(zero)));
1113 }
1114
1115 static void
1116 rsu_event_survey(struct rsu_softc *sc, uint8_t *buf, int len)
1117 {
1118         struct ifnet *ifp = sc->sc_ifp;
1119         struct ieee80211com *ic = ifp->if_l2com;
1120         struct ieee80211_frame *wh;
1121         struct ieee80211_channel *c;
1122         struct ndis_wlan_bssid_ex *bss;
1123         struct mbuf *m;
1124         int pktlen;
1125
1126         if (__predict_false(len < sizeof(*bss)))
1127                 return;
1128         bss = (struct ndis_wlan_bssid_ex *)buf;
1129         if (__predict_false(len < sizeof(*bss) + le32toh(bss->ieslen)))
1130                 return;
1131
1132         DPRINTFN(2, "found BSS %s: len=%d chan=%d inframode=%d "
1133             "networktype=%d privacy=%d\n",
1134             ether_sprintf(bss->macaddr), le32toh(bss->len),
1135             le32toh(bss->config.dsconfig), le32toh(bss->inframode),
1136             le32toh(bss->networktype), le32toh(bss->privacy));
1137
1138         /* Build a fake beacon frame to let net80211 do all the parsing. */
1139         pktlen = sizeof(*wh) + le32toh(bss->ieslen);
1140         if (__predict_false(pktlen > MCLBYTES))
1141                 return;
1142         MGETHDR(m, M_DONTWAIT, MT_DATA);
1143         if (__predict_false(m == NULL))
1144                 return;
1145         if (pktlen > MHLEN) {
1146                 MCLGET(m, M_DONTWAIT);
1147                 if (!(m->m_flags & M_EXT)) {
1148                         m_free(m);
1149                         return;
1150                 }
1151         }
1152         wh = mtod(m, struct ieee80211_frame *);
1153         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
1154             IEEE80211_FC0_SUBTYPE_BEACON;
1155         wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1156         *(uint16_t *)wh->i_dur = 0;
1157         IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
1158         IEEE80211_ADDR_COPY(wh->i_addr2, bss->macaddr);
1159         IEEE80211_ADDR_COPY(wh->i_addr3, bss->macaddr);
1160         *(uint16_t *)wh->i_seq = 0;
1161         memcpy(&wh[1], (uint8_t *)&bss[1], le32toh(bss->ieslen));
1162
1163         /* Finalize mbuf. */
1164         m->m_pkthdr.len = m->m_len = pktlen;
1165         m->m_pkthdr.rcvif = ifp;
1166         /* Fix the channel. */
1167         c = ieee80211_find_channel_byieee(ic, 
1168             le32toh(bss->config.dsconfig), 
1169             IEEE80211_CHAN_G);
1170         if (c) {
1171                 ic->ic_curchan = c;
1172                 ieee80211_radiotap_chan_change(ic);
1173         }
1174         /* XXX avoid a LOR */
1175         RSU_UNLOCK(sc);
1176         ieee80211_input_all(ic, m, le32toh(bss->rssi), 0);
1177         RSU_LOCK(sc);
1178 }
1179
1180 static void
1181 rsu_event_join_bss(struct rsu_softc *sc, uint8_t *buf, int len)
1182 {
1183         struct ifnet *ifp = sc->sc_ifp;
1184         struct ieee80211com *ic = ifp->if_l2com;
1185         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1186         struct ieee80211_node *ni = vap->iv_bss;
1187         struct r92s_event_join_bss *rsp;
1188         int res;
1189
1190         if (__predict_false(len < sizeof(*rsp)))
1191                 return;
1192         rsp = (struct r92s_event_join_bss *)buf;
1193         res = (int)le32toh(rsp->join_res);
1194
1195         DPRINTF("Rx join BSS event len=%d res=%d\n", len, res);
1196         if (res <= 0) {
1197                 RSU_UNLOCK(sc);
1198                 ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1199                 RSU_LOCK(sc);
1200                 return;
1201         }
1202         DPRINTF("associated with %s associd=%d\n",
1203             ether_sprintf(rsp->bss.macaddr), le32toh(rsp->associd));
1204         ni->ni_associd = le32toh(rsp->associd) | 0xc000;
1205         RSU_UNLOCK(sc);
1206         ieee80211_new_state(vap, IEEE80211_S_RUN,
1207             IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
1208         RSU_LOCK(sc);
1209 }
1210
1211 static void
1212 rsu_rx_event(struct rsu_softc *sc, uint8_t code, uint8_t *buf, int len)
1213 {
1214         struct ifnet *ifp = sc->sc_ifp;
1215         struct ieee80211com *ic = ifp->if_l2com;
1216         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1217
1218         DPRINTFN(4, "Rx event code=%d len=%d\n", code, len);
1219         switch (code) {
1220         case R92S_EVT_SURVEY:
1221                 if (vap->iv_state == IEEE80211_S_SCAN)
1222                         rsu_event_survey(sc, buf, len);
1223                 break;
1224         case R92S_EVT_SURVEY_DONE:
1225                 DPRINTF("site survey pass %d done, found %d BSS\n",
1226                     sc->scan_pass, le32toh(*(uint32_t *)buf));
1227                 if (vap->iv_state != IEEE80211_S_SCAN)
1228                         break;  /* Ignore if not scanning. */
1229                 if (sc->scan_pass == 0 && vap->iv_des_nssid != 0) {
1230                         /* Schedule a directed scan for hidden APs. */
1231                         sc->scan_pass = 1;
1232                         RSU_UNLOCK(sc);
1233                         ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1234                         RSU_LOCK(sc);
1235                         break;
1236                 }
1237                 sc->scan_pass = 0;
1238                 break;
1239         case R92S_EVT_JOIN_BSS:
1240                 if (vap->iv_state == IEEE80211_S_AUTH)
1241                         rsu_event_join_bss(sc, buf, len);
1242                 break;
1243         case R92S_EVT_DEL_STA:
1244                 DPRINTF("disassociated from %s\n", ether_sprintf(buf));
1245                 if (vap->iv_state == IEEE80211_S_RUN &&
1246                     IEEE80211_ADDR_EQ(vap->iv_bss->ni_bssid, buf)) {
1247                         RSU_UNLOCK(sc);
1248                         ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1249                         RSU_LOCK(sc);
1250                 }
1251                 break;
1252         case R92S_EVT_WPS_PBC:
1253                 DPRINTF("WPS PBC pushed.\n");
1254                 break;
1255         case R92S_EVT_FWDBG:
1256                 if (ifp->if_flags & IFF_DEBUG) {
1257                         buf[60] = '\0';
1258                         printf("FWDBG: %s\n", (char *)buf);
1259                 }
1260                 break;
1261         }
1262 }
1263
1264 static void
1265 rsu_rx_multi_event(struct rsu_softc *sc, uint8_t *buf, int len)
1266 {
1267         struct r92s_fw_cmd_hdr *cmd;
1268         int cmdsz;
1269
1270         DPRINTFN(6, "Rx events len=%d\n", len);
1271
1272         /* Skip Rx status. */
1273         buf += sizeof(struct r92s_rx_stat);
1274         len -= sizeof(struct r92s_rx_stat);
1275
1276         /* Process all events. */
1277         for (;;) {
1278                 /* Check that command header fits. */
1279                 if (__predict_false(len < sizeof(*cmd)))
1280                         break;
1281                 cmd = (struct r92s_fw_cmd_hdr *)buf;
1282                 /* Check that command payload fits. */
1283                 cmdsz = le16toh(cmd->len);
1284                 if (__predict_false(len < sizeof(*cmd) + cmdsz))
1285                         break;
1286
1287                 /* Process firmware event. */
1288                 rsu_rx_event(sc, cmd->code, (uint8_t *)&cmd[1], cmdsz);
1289
1290                 if (!(cmd->seq & R92S_FW_CMD_MORE))
1291                         break;
1292                 buf += sizeof(*cmd) + cmdsz;
1293                 len -= sizeof(*cmd) + cmdsz;
1294         }
1295 }
1296
1297 static int8_t
1298 rsu_get_rssi(struct rsu_softc *sc, int rate, void *physt)
1299 {
1300         static const int8_t cckoff[] = { 14, -2, -20, -40 };
1301         struct r92s_rx_phystat *phy;
1302         struct r92s_rx_cck *cck;
1303         uint8_t rpt;
1304         int8_t rssi;
1305
1306         if (rate <= 3) {
1307                 cck = (struct r92s_rx_cck *)physt;
1308                 rpt = (cck->agc_rpt >> 6) & 0x3;
1309                 rssi = cck->agc_rpt & 0x3e;
1310                 rssi = cckoff[rpt] - rssi;
1311         } else {        /* OFDM/HT. */
1312                 phy = (struct r92s_rx_phystat *)physt;
1313                 rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 106;
1314         }
1315         return (rssi);
1316 }
1317
1318 static struct mbuf *
1319 rsu_rx_frame(struct rsu_softc *sc, uint8_t *buf, int pktlen, int *rssi)
1320 {
1321         struct ifnet *ifp = sc->sc_ifp;
1322         struct ieee80211com *ic = ifp->if_l2com;
1323         struct ieee80211_frame *wh;
1324         struct r92s_rx_stat *stat;
1325         uint32_t rxdw0, rxdw3;
1326         struct mbuf *m;
1327         uint8_t rate;
1328         int infosz;
1329
1330         stat = (struct r92s_rx_stat *)buf;
1331         rxdw0 = le32toh(stat->rxdw0);
1332         rxdw3 = le32toh(stat->rxdw3);
1333
1334         if (__predict_false(rxdw0 & R92S_RXDW0_CRCERR)) {
1335                 ifp->if_ierrors++;
1336                 return NULL;
1337         }
1338         if (__predict_false(pktlen < sizeof(*wh) || pktlen > MCLBYTES)) {
1339                 ifp->if_ierrors++;
1340                 return NULL;
1341         }
1342
1343         rate = MS(rxdw3, R92S_RXDW3_RATE);
1344         infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
1345
1346         /* Get RSSI from PHY status descriptor if present. */
1347         if (infosz != 0)
1348                 *rssi = rsu_get_rssi(sc, rate, &stat[1]);
1349         else
1350                 *rssi = 0;
1351
1352         DPRINTFN(5, "Rx frame len=%d rate=%d infosz=%d rssi=%d\n",
1353             pktlen, rate, infosz, *rssi);
1354
1355         MGETHDR(m, M_DONTWAIT, MT_DATA);
1356         if (__predict_false(m == NULL)) {
1357                 ifp->if_ierrors++;
1358                 return NULL;
1359         }
1360         if (pktlen > MHLEN) {
1361                 MCLGET(m, M_DONTWAIT);
1362                 if (__predict_false(!(m->m_flags & M_EXT))) {
1363                         ifp->if_ierrors++;
1364                         m_freem(m);
1365                         return NULL;
1366                 }
1367         }
1368         /* Finalize mbuf. */
1369         m->m_pkthdr.rcvif = ifp;
1370         /* Hardware does Rx TCP checksum offload. */
1371         if (rxdw3 & R92S_RXDW3_TCPCHKVALID) {
1372                 if (__predict_true(rxdw3 & R92S_RXDW3_TCPCHKRPT))
1373                         m->m_pkthdr.csum_flags |= CSUM_DATA_VALID;
1374         }
1375         wh = (struct ieee80211_frame *)((uint8_t *)&stat[1] + infosz);
1376         memcpy(mtod(m, uint8_t *), wh, pktlen);
1377         m->m_pkthdr.len = m->m_len = pktlen;
1378
1379         if (ieee80211_radiotap_active(ic)) {
1380                 struct rsu_rx_radiotap_header *tap = &sc->sc_rxtap;
1381
1382                 /* Map HW rate index to 802.11 rate. */
1383                 tap->wr_flags = 2;
1384                 if (!(rxdw3 & R92S_RXDW3_HTC)) {
1385                         switch (rate) {
1386                         /* CCK. */
1387                         case  0: tap->wr_rate =   2; break;
1388                         case  1: tap->wr_rate =   4; break;
1389                         case  2: tap->wr_rate =  11; break;
1390                         case  3: tap->wr_rate =  22; break;
1391                         /* OFDM. */
1392                         case  4: tap->wr_rate =  12; break;
1393                         case  5: tap->wr_rate =  18; break;
1394                         case  6: tap->wr_rate =  24; break;
1395                         case  7: tap->wr_rate =  36; break;
1396                         case  8: tap->wr_rate =  48; break;
1397                         case  9: tap->wr_rate =  72; break;
1398                         case 10: tap->wr_rate =  96; break;
1399                         case 11: tap->wr_rate = 108; break;
1400                         }
1401                 } else if (rate >= 12) {        /* MCS0~15. */
1402                         /* Bit 7 set means HT MCS instead of rate. */
1403                         tap->wr_rate = 0x80 | (rate - 12);
1404                 }
1405                 tap->wr_dbm_antsignal = *rssi;
1406                 tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
1407                 tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
1408         }
1409
1410         return (m);
1411 }
1412
1413 static struct mbuf *
1414 rsu_rx_multi_frame(struct rsu_softc *sc, uint8_t *buf, int len, int *rssi)
1415 {
1416         struct r92s_rx_stat *stat;
1417         uint32_t rxdw0;
1418         int totlen, pktlen, infosz, npkts;
1419         struct mbuf *m, *m0 = NULL, *prevm = NULL;
1420
1421         /* Get the number of encapsulated frames. */
1422         stat = (struct r92s_rx_stat *)buf;
1423         npkts = MS(le32toh(stat->rxdw2), R92S_RXDW2_PKTCNT);
1424         DPRINTFN(6, "Rx %d frames in one chunk\n", npkts);
1425
1426         /* Process all of them. */
1427         while (npkts-- > 0) {
1428                 if (__predict_false(len < sizeof(*stat)))
1429                         break;
1430                 stat = (struct r92s_rx_stat *)buf;
1431                 rxdw0 = le32toh(stat->rxdw0);
1432
1433                 pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN);
1434                 if (__predict_false(pktlen == 0))
1435                         break;
1436
1437                 infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
1438
1439                 /* Make sure everything fits in xfer. */
1440                 totlen = sizeof(*stat) + infosz + pktlen;
1441                 if (__predict_false(totlen > len))
1442                         break;
1443
1444                 /* Process 802.11 frame. */
1445                 m = rsu_rx_frame(sc, buf, pktlen, rssi);
1446                 if (m0 == NULL)
1447                         m0 = m;
1448                 if (prevm == NULL)
1449                         prevm = m;
1450                 else {
1451                         prevm->m_next = m;
1452                         prevm = m;
1453                 }
1454                 /* Next chunk is 128-byte aligned. */
1455                 totlen = (totlen + 127) & ~127;
1456                 buf += totlen;
1457                 len -= totlen;
1458         }
1459
1460         return (m0);
1461 }
1462
1463 static struct mbuf *
1464 rsu_rxeof(struct usb_xfer *xfer, struct rsu_data *data, int *rssi)
1465 {
1466         struct rsu_softc *sc = data->sc;
1467         struct r92s_rx_stat *stat;
1468         int len;
1469
1470         usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
1471
1472         if (__predict_false(len < sizeof(*stat))) {
1473                 DPRINTF("xfer too short %d\n", len);
1474                 sc->sc_ifp->if_ierrors++;
1475                 return (NULL);
1476         }
1477         /* Determine if it is a firmware C2H event or an 802.11 frame. */
1478         stat = (struct r92s_rx_stat *)data->buf;
1479         if ((le32toh(stat->rxdw1) & 0x1ff) == 0x1ff) {
1480                 rsu_rx_multi_event(sc, data->buf, len);
1481                 /* No packets to process. */
1482                 return (NULL);
1483         } else
1484                 return (rsu_rx_multi_frame(sc, data->buf, len, rssi));
1485 }
1486
1487 static void
1488 rsu_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
1489 {
1490         struct rsu_softc *sc = usbd_xfer_softc(xfer);
1491         struct ifnet *ifp = sc->sc_ifp;
1492         struct ieee80211com *ic = ifp->if_l2com;
1493         struct ieee80211_frame *wh;
1494         struct ieee80211_node *ni;
1495         struct mbuf *m = NULL, *next;
1496         struct rsu_data *data;
1497         int rssi = 1;
1498
1499         RSU_ASSERT_LOCKED(sc);
1500
1501         switch (USB_GET_STATE(xfer)) {
1502         case USB_ST_TRANSFERRED:
1503                 data = STAILQ_FIRST(&sc->sc_rx_active);
1504                 if (data == NULL)
1505                         goto tr_setup;
1506                 STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
1507                 m = rsu_rxeof(xfer, data, &rssi);
1508                 STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
1509                 /* FALLTHROUGH */
1510         case USB_ST_SETUP:
1511 tr_setup:
1512                 data = STAILQ_FIRST(&sc->sc_rx_inactive);
1513                 if (data == NULL) {
1514                         KASSERT(m == NULL, ("mbuf isn't NULL"));
1515                         return;
1516                 }
1517                 STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next);
1518                 STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next);
1519                 usbd_xfer_set_frame_data(xfer, 0, data->buf,
1520                     usbd_xfer_max_len(xfer));
1521                 usbd_transfer_submit(xfer);
1522                 /*
1523                  * To avoid LOR we should unlock our private mutex here to call
1524                  * ieee80211_input() because here is at the end of a USB
1525                  * callback and safe to unlock.
1526                  */
1527                 RSU_UNLOCK(sc);
1528                 while (m != NULL) {
1529                         next = m->m_next;
1530                         m->m_next = NULL;
1531                         wh = mtod(m, struct ieee80211_frame *);
1532                         ni = ieee80211_find_rxnode(ic,
1533                             (struct ieee80211_frame_min *)wh);
1534                         if (ni != NULL) {
1535                                 (void)ieee80211_input(ni, m, rssi, 0);
1536                                 ieee80211_free_node(ni);
1537                         } else
1538                                 (void)ieee80211_input_all(ic, m, rssi, 0);
1539                         m = next;
1540                 }
1541                 RSU_LOCK(sc);
1542                 break;
1543         default:
1544                 /* needs it to the inactive queue due to a error. */
1545                 data = STAILQ_FIRST(&sc->sc_rx_active);
1546                 if (data != NULL) {
1547                         STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
1548                         STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
1549                 }
1550                 if (error != USB_ERR_CANCELLED) {
1551                         usbd_xfer_set_stall(xfer);
1552                         ifp->if_ierrors++;
1553                         goto tr_setup;
1554                 }
1555                 break;
1556         }
1557
1558 }
1559
1560
1561 static void
1562 rsu_txeof(struct usb_xfer *xfer, struct rsu_data *data)
1563 {
1564         struct rsu_softc *sc = usbd_xfer_softc(xfer);
1565         struct ifnet *ifp = sc->sc_ifp;
1566         struct mbuf *m;
1567
1568         RSU_ASSERT_LOCKED(sc);
1569
1570         /*
1571          * Do any tx complete callback.  Note this must be done before releasing
1572          * the node reference.
1573          */
1574         if (data->m) {
1575                 m = data->m;
1576                 if (m->m_flags & M_TXCB) {
1577                         /* XXX status? */
1578                         ieee80211_process_callback(data->ni, m, 0);
1579                 }
1580                 m_freem(m);
1581                 data->m = NULL;
1582         }
1583         if (data->ni) {
1584                 ieee80211_free_node(data->ni);
1585                 data->ni = NULL;
1586         }
1587         sc->sc_tx_timer = 0;
1588         ifp->if_opackets++;
1589         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1590 }
1591
1592 static void
1593 rsu_bulk_tx_callback(struct usb_xfer *xfer, usb_error_t error)
1594 {
1595         struct rsu_softc *sc = usbd_xfer_softc(xfer);
1596         struct ifnet *ifp = sc->sc_ifp;
1597         struct rsu_data *data;
1598
1599         RSU_ASSERT_LOCKED(sc);
1600
1601         switch (USB_GET_STATE(xfer)) {
1602         case USB_ST_TRANSFERRED:
1603                 data = STAILQ_FIRST(&sc->sc_tx_active);
1604                 if (data == NULL)
1605                         goto tr_setup;
1606                 DPRINTF("transfer done %p\n", data);
1607                 STAILQ_REMOVE_HEAD(&sc->sc_tx_active, next);
1608                 rsu_txeof(xfer, data);
1609                 STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, data, next);
1610                 /* FALLTHROUGH */
1611         case USB_ST_SETUP:
1612 tr_setup:
1613                 data = STAILQ_FIRST(&sc->sc_tx_pending);
1614                 if (data == NULL) {
1615                         DPRINTF("empty pending queue sc %p\n", sc);
1616                         return;
1617                 }
1618                 STAILQ_REMOVE_HEAD(&sc->sc_tx_pending, next);
1619                 STAILQ_INSERT_TAIL(&sc->sc_tx_active, data, next);
1620                 usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen);
1621                 DPRINTF("submitting transfer %p\n", data);
1622                 usbd_transfer_submit(xfer);
1623                 rsu_start_locked(ifp);
1624                 break;
1625         default:
1626                 data = STAILQ_FIRST(&sc->sc_tx_active);
1627                 if (data == NULL)
1628                         goto tr_setup;
1629                 if (data->ni != NULL) {
1630                         ieee80211_free_node(data->ni);
1631                         data->ni = NULL;
1632                         ifp->if_oerrors++;
1633                 }
1634                 if (error != USB_ERR_CANCELLED) {
1635                         usbd_xfer_set_stall(xfer);
1636                         goto tr_setup;
1637                 }
1638                 break;
1639         }
1640 }
1641
1642 static int
1643 rsu_tx_start(struct rsu_softc *sc, struct ieee80211_node *ni, 
1644     struct mbuf *m0, struct rsu_data *data)
1645 {
1646         struct ifnet *ifp = sc->sc_ifp;
1647         struct ieee80211com *ic = ifp->if_l2com;
1648         struct ieee80211vap *vap = ni->ni_vap;
1649         struct ieee80211_frame *wh;
1650         struct ieee80211_key *k = NULL;
1651         struct r92s_tx_desc *txd;
1652         struct usb_xfer *xfer;
1653         uint8_t type, tid = 0;
1654         int hasqos, xferlen;
1655         struct usb_xfer *rsu_pipes[4] = {
1656                 sc->sc_xfer[RSU_BULK_TX_BE],
1657                 sc->sc_xfer[RSU_BULK_TX_BK],
1658                 sc->sc_xfer[RSU_BULK_TX_VI],
1659                 sc->sc_xfer[RSU_BULK_TX_VO]
1660         };
1661
1662         RSU_ASSERT_LOCKED(sc);
1663
1664         wh = mtod(m0, struct ieee80211_frame *);
1665         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1666
1667         if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1668                 k = ieee80211_crypto_encap(ni, m0);
1669                 if (k == NULL) {
1670                         device_printf(sc->sc_dev,
1671                             "ieee80211_crypto_encap returns NULL.\n");
1672                         /* XXX we don't expect the fragmented frames */
1673                         m_freem(m0);
1674                         return (ENOBUFS);
1675                 }
1676                 wh = mtod(m0, struct ieee80211_frame *);
1677         }
1678         switch (type) {
1679         case IEEE80211_FC0_TYPE_CTL:
1680         case IEEE80211_FC0_TYPE_MGT:
1681                 xfer = sc->sc_xfer[RSU_BULK_TX_VO];
1682                 break;
1683         default:
1684                 KASSERT(M_WME_GETAC(m0) < 4,
1685                     ("unsupported WME pipe %d", M_WME_GETAC(m0)));
1686                 xfer = rsu_pipes[M_WME_GETAC(m0)];
1687                 break;
1688         }
1689         hasqos = 0;
1690
1691         /* Fill Tx descriptor. */
1692         txd = (struct r92s_tx_desc *)data->buf;
1693         memset(txd, 0, sizeof(*txd));
1694
1695         txd->txdw0 |= htole32(
1696             SM(R92S_TXDW0_PKTLEN, m0->m_pkthdr.len) |
1697             SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
1698             R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
1699
1700         txd->txdw1 |= htole32(
1701             SM(R92S_TXDW1_MACID, R92S_MACID_BSS) |
1702             SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_BE));
1703         if (!hasqos)
1704                 txd->txdw1 |= htole32(R92S_TXDW1_NONQOS);
1705 #ifdef notyet
1706         if (k != NULL) {
1707                 switch (k->wk_cipher->ic_cipher) {
1708                 case IEEE80211_CIPHER_WEP:
1709                         cipher = R92S_TXDW1_CIPHER_WEP;
1710                         break;
1711                 case IEEE80211_CIPHER_TKIP:
1712                         cipher = R92S_TXDW1_CIPHER_TKIP;
1713                         break;
1714                 case IEEE80211_CIPHER_AES_CCM:
1715                         cipher = R92S_TXDW1_CIPHER_AES;
1716                         break;
1717                 default:
1718                         cipher = R92S_TXDW1_CIPHER_NONE;
1719                 }
1720                 txd->txdw1 |= htole32(
1721                     SM(R92S_TXDW1_CIPHER, cipher) |
1722                     SM(R92S_TXDW1_KEYIDX, k->k_id));
1723         }
1724 #endif
1725         txd->txdw2 |= htole32(R92S_TXDW2_BK);
1726         if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1727                 txd->txdw2 |= htole32(R92S_TXDW2_BMCAST);
1728         /*
1729          * Firmware will use and increment the sequence number for the
1730          * specified TID.
1731          */
1732         txd->txdw3 |= htole32(SM(R92S_TXDW3_SEQ, tid));
1733
1734         if (ieee80211_radiotap_active_vap(vap)) {
1735                 struct rsu_tx_radiotap_header *tap = &sc->sc_txtap;
1736
1737                 tap->wt_flags = 0;
1738                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1739                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1740                 ieee80211_radiotap_tx(vap, m0);
1741         }
1742         xferlen = sizeof(*txd) + m0->m_pkthdr.len;
1743         m_copydata(m0, 0, m0->m_pkthdr.len, (caddr_t)&txd[1]);
1744
1745         data->buflen = xferlen;
1746         data->ni = ni;
1747         data->m = m0;
1748         STAILQ_INSERT_TAIL(&sc->sc_tx_pending, data, next);
1749         usbd_transfer_start(xfer);
1750
1751         return (0);
1752 }
1753
1754 static void
1755 rsu_start(struct ifnet *ifp)
1756 {
1757         struct rsu_softc *sc = ifp->if_softc;
1758
1759         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1760                 return;
1761
1762         RSU_LOCK(sc);
1763         rsu_start_locked(ifp);
1764         RSU_UNLOCK(sc);
1765 }
1766
1767 static void
1768 rsu_start_locked(struct ifnet *ifp)
1769 {
1770         struct rsu_softc *sc = ifp->if_softc;
1771         struct ieee80211_node *ni;
1772         struct mbuf *m;
1773         struct rsu_data *bf;
1774
1775         RSU_ASSERT_LOCKED(sc);
1776
1777         for (;;) {
1778                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1779                 if (m == NULL)
1780                         break;
1781                 bf = rsu_getbuf(sc);
1782                 if (bf == NULL) {
1783                         IFQ_DRV_PREPEND(&ifp->if_snd, m);
1784                         break;
1785                 }
1786                 ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
1787                 m->m_pkthdr.rcvif = NULL;
1788
1789                 if (rsu_tx_start(sc, ni, m, bf) != 0) {
1790                         ifp->if_oerrors++;
1791                         STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
1792                         ieee80211_free_node(ni);
1793                         break;
1794                 }
1795                 sc->sc_tx_timer = 5;
1796                 callout_reset(&sc->sc_watchdog_ch, hz, rsu_watchdog, sc);
1797         }
1798 }
1799
1800 static void
1801 rsu_watchdog(void *arg)
1802 {
1803         struct rsu_softc *sc = arg;
1804         struct ifnet *ifp = sc->sc_ifp;
1805
1806         if (sc->sc_tx_timer > 0) {
1807                 if (--sc->sc_tx_timer == 0) {
1808                         device_printf(sc->sc_dev, "device timeout\n");
1809                         /* rsu_init(ifp); XXX needs a process context! */
1810                         ifp->if_oerrors++;
1811                         return;
1812                 }
1813                 callout_reset(&sc->sc_watchdog_ch, hz, rsu_watchdog, sc);
1814         }
1815 }
1816
1817 static int
1818 rsu_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1819 {
1820         struct ieee80211com *ic = ifp->if_l2com;
1821         struct ifreq *ifr = (struct ifreq *) data;
1822         int error = 0, startall = 0;
1823
1824         switch (cmd) {
1825         case SIOCSIFFLAGS:
1826                 if (ifp->if_flags & IFF_UP) {
1827                         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1828                                 rsu_init(ifp->if_softc);
1829                                 startall = 1;
1830                         }
1831                 } else {
1832                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1833                                 rsu_stop(ifp, 1);
1834                 }
1835                 if (startall)
1836                         ieee80211_start_all(ic);
1837                 break;
1838         case SIOCGIFMEDIA:
1839                 error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
1840                 break;
1841         case SIOCGIFADDR:
1842                 error = ether_ioctl(ifp, cmd, data);
1843                 break;
1844         default:
1845                 error = EINVAL;
1846                 break;
1847         }
1848
1849         return (error);
1850 }
1851
1852 /*
1853  * Power on sequence for A-cut adapters.
1854  */
1855 static void
1856 rsu_power_on_acut(struct rsu_softc *sc)
1857 {
1858         uint32_t reg;
1859
1860         rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
1861         rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
1862
1863         /* Enable AFE macro block's bandgap and Mbias. */
1864         rsu_write_1(sc, R92S_AFE_MISC,
1865             rsu_read_1(sc, R92S_AFE_MISC) |
1866             R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN);
1867         /* Enable LDOA15 block. */
1868         rsu_write_1(sc, R92S_LDOA15_CTRL,
1869             rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
1870
1871         rsu_write_1(sc, R92S_SPS1_CTRL,
1872             rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_LDEN);
1873         usb_pause_mtx(&sc->sc_mtx, 2 * hz);
1874         /* Enable switch regulator block. */
1875         rsu_write_1(sc, R92S_SPS1_CTRL,
1876             rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_SWEN);
1877
1878         rsu_write_4(sc, R92S_SPS1_CTRL, 0x00a7b267);
1879
1880         rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1881             rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
1882
1883         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1884             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
1885
1886         rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1887             rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x90);
1888
1889         /* Enable AFE clock. */
1890         rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
1891             rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
1892         /* Enable AFE PLL macro block. */
1893         rsu_write_1(sc, R92S_AFE_PLL_CTRL,
1894             rsu_read_1(sc, R92S_AFE_PLL_CTRL) | 0x11);
1895         /* Attach AFE PLL to MACTOP/BB. */
1896         rsu_write_1(sc, R92S_SYS_ISO_CTRL,
1897             rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
1898
1899         /* Switch to 40MHz clock instead of 80MHz. */
1900         rsu_write_2(sc, R92S_SYS_CLKR,
1901             rsu_read_2(sc, R92S_SYS_CLKR) & ~R92S_SYS_CLKSEL);
1902
1903         /* Enable MAC clock. */
1904         rsu_write_2(sc, R92S_SYS_CLKR,
1905             rsu_read_2(sc, R92S_SYS_CLKR) |
1906             R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
1907
1908         rsu_write_1(sc, R92S_PMC_FSM, 0x02);
1909
1910         /* Enable digital core and IOREG R/W. */
1911         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1912             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
1913
1914         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1915             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
1916
1917         /* Switch the control path to firmware. */
1918         reg = rsu_read_2(sc, R92S_SYS_CLKR);
1919         reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
1920         rsu_write_2(sc, R92S_SYS_CLKR, reg);
1921
1922         rsu_write_2(sc, R92S_CR, 0x37fc);
1923
1924         /* Fix USB RX FIFO issue. */
1925         rsu_write_1(sc, 0xfe5c,
1926             rsu_read_1(sc, 0xfe5c) | 0x80);
1927         rsu_write_1(sc, 0x00ab,
1928             rsu_read_1(sc, 0x00ab) | 0xc0);
1929
1930         rsu_write_1(sc, R92S_SYS_CLKR,
1931             rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
1932 }
1933
1934 /*
1935  * Power on sequence for B-cut and C-cut adapters.
1936  */
1937 static void
1938 rsu_power_on_bcut(struct rsu_softc *sc)
1939 {
1940         uint32_t reg;
1941         int ntries;
1942
1943         /* Prevent eFuse leakage. */
1944         rsu_write_1(sc, 0x37, 0xb0);
1945         usb_pause_mtx(&sc->sc_mtx, 10);
1946         rsu_write_1(sc, 0x37, 0x30);
1947
1948         /* Switch the control path to hardware. */
1949         reg = rsu_read_2(sc, R92S_SYS_CLKR);
1950         if (reg & R92S_FWHW_SEL) {
1951                 rsu_write_2(sc, R92S_SYS_CLKR,
1952                     reg & ~(R92S_SWHW_SEL | R92S_FWHW_SEL));
1953         }
1954         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1955             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) & ~0x8c);
1956         DELAY(1000);
1957
1958         rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
1959         rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
1960
1961         reg = rsu_read_1(sc, R92S_AFE_MISC);
1962         rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN);
1963         rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN |
1964             R92S_AFE_MISC_MBEN | R92S_AFE_MISC_I32_EN);
1965
1966         /* Enable PLL. */
1967         rsu_write_1(sc, R92S_LDOA15_CTRL,
1968             rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
1969
1970         rsu_write_1(sc, R92S_LDOV12D_CTRL,
1971             rsu_read_1(sc, R92S_LDOV12D_CTRL) | R92S_LDV12_EN);
1972
1973         rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1974             rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
1975
1976         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1977             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
1978
1979         /* Support 64KB IMEM. */
1980         rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1981             rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x97);
1982
1983         /* Enable AFE clock. */
1984         rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
1985             rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
1986         /* Enable AFE PLL macro block. */
1987         reg = rsu_read_1(sc, R92S_AFE_PLL_CTRL);
1988         rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
1989         DELAY(500);
1990         rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x51);
1991         DELAY(500);
1992         rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
1993         DELAY(500);
1994
1995         /* Attach AFE PLL to MACTOP/BB. */
1996         rsu_write_1(sc, R92S_SYS_ISO_CTRL,
1997             rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
1998
1999         /* Switch to 40MHz clock. */
2000         rsu_write_1(sc, R92S_SYS_CLKR, 0x00);
2001         /* Disable CPU clock and 80MHz SSC. */
2002         rsu_write_1(sc, R92S_SYS_CLKR,
2003             rsu_read_1(sc, R92S_SYS_CLKR) | 0xa0);
2004         /* Enable MAC clock. */
2005         rsu_write_2(sc, R92S_SYS_CLKR,
2006             rsu_read_2(sc, R92S_SYS_CLKR) |
2007             R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
2008
2009         rsu_write_1(sc, R92S_PMC_FSM, 0x02);
2010
2011         /* Enable digital core and IOREG R/W. */
2012         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2013             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
2014
2015         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2016             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
2017
2018         /* Switch the control path to firmware. */
2019         reg = rsu_read_2(sc, R92S_SYS_CLKR);
2020         reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
2021         rsu_write_2(sc, R92S_SYS_CLKR, reg);
2022
2023         rsu_write_2(sc, R92S_CR, 0x37fc);
2024
2025         /* Fix USB RX FIFO issue. */
2026         rsu_write_1(sc, 0xfe5c,
2027             rsu_read_1(sc, 0xfe5c) | 0x80);
2028
2029         rsu_write_1(sc, R92S_SYS_CLKR,
2030             rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
2031
2032         rsu_write_1(sc, 0xfe1c, 0x80);
2033
2034         /* Make sure TxDMA is ready to download firmware. */
2035         for (ntries = 0; ntries < 20; ntries++) {
2036                 reg = rsu_read_1(sc, R92S_TCR);
2037                 if ((reg & (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) ==
2038                     (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT))
2039                         break;
2040                 DELAY(5);
2041         }
2042         if (ntries == 20) {
2043                 DPRINTF("TxDMA is not ready\n");
2044                 /* Reset TxDMA. */
2045                 reg = rsu_read_1(sc, R92S_CR);
2046                 rsu_write_1(sc, R92S_CR, reg & ~R92S_CR_TXDMA_EN);
2047                 DELAY(2);
2048                 rsu_write_1(sc, R92S_CR, reg | R92S_CR_TXDMA_EN);
2049         }
2050 }
2051
2052 static void
2053 rsu_power_off(struct rsu_softc *sc)
2054 {
2055         /* Turn RF off. */
2056         rsu_write_1(sc, R92S_RF_CTRL, 0x00);
2057         usb_pause_mtx(&sc->sc_mtx, 5);
2058
2059         /* Turn MAC off. */
2060         /* Switch control path. */
2061         rsu_write_1(sc, R92S_SYS_CLKR + 1, 0x38);
2062         /* Reset MACTOP. */
2063         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x70);
2064         rsu_write_1(sc, R92S_PMC_FSM, 0x06);
2065         rsu_write_1(sc, R92S_SYS_ISO_CTRL + 0, 0xf9);
2066         rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, 0xe8);
2067
2068         /* Disable AFE PLL. */
2069         rsu_write_1(sc, R92S_AFE_PLL_CTRL, 0x00);
2070         /* Disable A15V. */
2071         rsu_write_1(sc, R92S_LDOA15_CTRL, 0x54);
2072         /* Disable eFuse 1.2V. */
2073         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x50);
2074         rsu_write_1(sc, R92S_LDOV12D_CTRL, 0x24);
2075         /* Enable AFE macro block's bandgap and Mbias. */
2076         rsu_write_1(sc, R92S_AFE_MISC, 0x30);
2077         /* Disable 1.6V LDO. */
2078         rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x56);
2079         rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x43);
2080 }
2081
2082 static int
2083 rsu_fw_loadsection(struct rsu_softc *sc, const uint8_t *buf, int len)
2084 {
2085         struct rsu_data *data;
2086         struct r92s_tx_desc *txd;
2087         int mlen;
2088
2089         while (len > 0) {
2090                 data = rsu_getbuf(sc);
2091                 if (data == NULL)
2092                         return (ENOMEM);
2093                 txd = (struct r92s_tx_desc *)data->buf;
2094                 memset(txd, 0, sizeof(*txd));
2095                 if (len <= RSU_TXBUFSZ - sizeof(*txd)) {
2096                         /* Last chunk. */
2097                         txd->txdw0 |= htole32(R92S_TXDW0_LINIP);
2098                         mlen = len;
2099                 } else
2100                         mlen = RSU_TXBUFSZ - sizeof(*txd);
2101                 txd->txdw0 |= htole32(SM(R92S_TXDW0_PKTLEN, mlen));
2102                 memcpy(&txd[1], buf, mlen);
2103                 data->buflen = sizeof(*txd) + mlen;
2104                 DPRINTF("starting transfer %p\n", data);
2105                 STAILQ_INSERT_TAIL(&sc->sc_tx_pending, data, next);
2106                 buf += mlen;
2107                 len -= mlen;
2108         }
2109         usbd_transfer_start(sc->sc_xfer[RSU_BULK_TX_VO]);
2110
2111         return (0);
2112 }
2113
2114 static int
2115 rsu_load_firmware(struct rsu_softc *sc)
2116 {
2117         const struct r92s_fw_hdr *hdr;
2118         struct r92s_fw_priv *dmem;
2119         const uint8_t *imem, *emem;
2120         int imemsz, ememsz;
2121         const struct firmware *fw;
2122         size_t size;
2123         uint32_t reg;
2124         int ntries, error;
2125
2126         RSU_UNLOCK(sc);
2127         /* Read firmware image from the filesystem. */
2128         if ((fw = firmware_get("rsu-rtl8712fw")) == NULL) {
2129                 device_printf(sc->sc_dev, 
2130                     "%s: failed load firmware of file rsu-rtl8712fw\n",
2131                     __func__);
2132                 RSU_LOCK(sc);
2133                 return (ENXIO);
2134         }
2135         RSU_LOCK(sc);
2136         size = fw->datasize;
2137         if (size < sizeof(*hdr)) {
2138                 device_printf(sc->sc_dev, "firmware too short\n");
2139                 error = EINVAL;
2140                 goto fail;
2141         }
2142         hdr = (const struct r92s_fw_hdr *)fw->data;
2143         if (hdr->signature != htole16(0x8712) &&
2144             hdr->signature != htole16(0x8192)) {
2145                 device_printf(sc->sc_dev,
2146                     "invalid firmware signature 0x%x\n",
2147                     le16toh(hdr->signature));
2148                 error = EINVAL;
2149                 goto fail;
2150         }
2151         DPRINTF("FW V%d %02x-%02x %02x:%02x\n", le16toh(hdr->version),
2152             hdr->month, hdr->day, hdr->hour, hdr->minute);
2153
2154         /* Make sure that driver and firmware are in sync. */
2155         if (hdr->privsz != htole32(sizeof(*dmem))) {
2156                 device_printf(sc->sc_dev, "unsupported firmware image\n");
2157                 error = EINVAL;
2158                 goto fail;
2159         }
2160         /* Get FW sections sizes. */
2161         imemsz = le32toh(hdr->imemsz);
2162         ememsz = le32toh(hdr->sramsz);
2163         /* Check that all FW sections fit in image. */
2164         if (size < sizeof(*hdr) + imemsz + ememsz) {
2165                 device_printf(sc->sc_dev, "firmware too short\n");
2166                 error = EINVAL;
2167                 goto fail;
2168         }
2169         imem = (const uint8_t *)&hdr[1];
2170         emem = imem + imemsz;
2171
2172         /* Load IMEM section. */
2173         error = rsu_fw_loadsection(sc, imem, imemsz);
2174         if (error != 0) {
2175                 device_printf(sc->sc_dev,
2176                     "could not load firmware section %s\n", "IMEM");
2177                 goto fail;
2178         }
2179         /* Wait for load to complete. */
2180         for (ntries = 0; ntries < 10; ntries++) {
2181                 usb_pause_mtx(&sc->sc_mtx, 10);
2182                 reg = rsu_read_2(sc, R92S_TCR);
2183                 if (reg & R92S_TCR_IMEM_CODE_DONE)
2184                         break;
2185         }
2186         if (ntries == 10 || !(reg & R92S_TCR_IMEM_CHK_RPT)) {
2187                 device_printf(sc->sc_dev, "timeout waiting for %s transfer\n",
2188                     "IMEM");
2189                 error = ETIMEDOUT;
2190                 goto fail;
2191         }
2192
2193         /* Load EMEM section. */
2194         error = rsu_fw_loadsection(sc, emem, ememsz);
2195         if (error != 0) {
2196                 device_printf(sc->sc_dev,
2197                     "could not load firmware section %s\n", "EMEM");
2198                 goto fail;
2199         }
2200         /* Wait for load to complete. */
2201         for (ntries = 0; ntries < 10; ntries++) {
2202                 usb_pause_mtx(&sc->sc_mtx, 10);
2203                 reg = rsu_read_2(sc, R92S_TCR);
2204                 if (reg & R92S_TCR_EMEM_CODE_DONE)
2205                         break;
2206         }
2207         if (ntries == 10 || !(reg & R92S_TCR_EMEM_CHK_RPT)) {
2208                 device_printf(sc->sc_dev, "timeout waiting for %s transfer\n",
2209                     "EMEM");
2210                 error = ETIMEDOUT;
2211                 goto fail;
2212         }
2213
2214         /* Enable CPU. */
2215         rsu_write_1(sc, R92S_SYS_CLKR,
2216             rsu_read_1(sc, R92S_SYS_CLKR) | R92S_SYS_CPU_CLKSEL);
2217         if (!(rsu_read_1(sc, R92S_SYS_CLKR) & R92S_SYS_CPU_CLKSEL)) {
2218                 device_printf(sc->sc_dev, "could not enable system clock\n");
2219                 error = EIO;
2220                 goto fail;
2221         }
2222         rsu_write_2(sc, R92S_SYS_FUNC_EN,
2223             rsu_read_2(sc, R92S_SYS_FUNC_EN) | R92S_FEN_CPUEN);
2224         if (!(rsu_read_2(sc, R92S_SYS_FUNC_EN) & R92S_FEN_CPUEN)) {
2225                 device_printf(sc->sc_dev, 
2226                     "could not enable microcontroller\n");
2227                 error = EIO;
2228                 goto fail;
2229         }
2230         /* Wait for CPU to initialize. */
2231         for (ntries = 0; ntries < 100; ntries++) {
2232                 if (rsu_read_2(sc, R92S_TCR) & R92S_TCR_IMEM_RDY)
2233                         break;
2234                 DELAY(1000);
2235         }
2236         if (ntries == 100) {
2237                 device_printf(sc->sc_dev,
2238                     "timeout waiting for microcontroller\n");
2239                 error = ETIMEDOUT;
2240                 goto fail;
2241         }
2242
2243         /* Update DMEM section before loading. */
2244         dmem = __DECONST(struct r92s_fw_priv *, &hdr->priv);
2245         memset(dmem, 0, sizeof(*dmem));
2246         dmem->hci_sel = R92S_HCI_SEL_USB | R92S_HCI_SEL_8172;
2247         dmem->nendpoints = sc->npipes;
2248         dmem->rf_config = 0x12; /* 1T2R */
2249         dmem->vcs_type = R92S_VCS_TYPE_AUTO;
2250         dmem->vcs_mode = R92S_VCS_MODE_RTS_CTS;
2251 #ifdef notyet
2252         dmem->bw40_en = (ic->ic_htcaps & IEEE80211_HTCAP_CBW20_40) != 0;
2253 #endif
2254         dmem->turbo_mode = 1;
2255         /* Load DMEM section. */
2256         error = rsu_fw_loadsection(sc, (uint8_t *)dmem, sizeof(*dmem));
2257         if (error != 0) {
2258                 device_printf(sc->sc_dev,
2259                     "could not load firmware section %s\n", "DMEM");
2260                 goto fail;
2261         }
2262         /* Wait for load to complete. */
2263         for (ntries = 0; ntries < 100; ntries++) {
2264                 if (rsu_read_2(sc, R92S_TCR) & R92S_TCR_DMEM_CODE_DONE)
2265                         break;
2266                 DELAY(1000);
2267         }
2268         if (ntries == 100) {
2269                 device_printf(sc->sc_dev, "timeout waiting for %s transfer\n",
2270                     "DMEM");
2271                 error = ETIMEDOUT;
2272                 goto fail;
2273         }
2274         /* Wait for firmware readiness. */
2275         for (ntries = 0; ntries < 60; ntries++) {
2276                 if (!(rsu_read_2(sc, R92S_TCR) & R92S_TCR_FWRDY))
2277                         break;
2278                 DELAY(1000);
2279         }
2280         if (ntries == 60) {
2281                 device_printf(sc->sc_dev, 
2282                     "timeout waiting for firmware readiness\n");
2283                 error = ETIMEDOUT;
2284                 goto fail;
2285         }
2286  fail:
2287         firmware_put(fw, FIRMWARE_UNLOAD);
2288         return (error);
2289 }
2290
2291
2292 static int      
2293 rsu_raw_xmit(struct ieee80211_node *ni, struct mbuf *m, 
2294     const struct ieee80211_bpf_params *params)
2295 {
2296         struct ieee80211com *ic = ni->ni_ic;
2297         struct ifnet *ifp = ic->ic_ifp;
2298         struct rsu_softc *sc = ifp->if_softc;
2299         struct rsu_data *bf;
2300
2301         /* prevent management frames from being sent if we're not ready */
2302         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
2303                 m_freem(m);
2304                 ieee80211_free_node(ni);
2305                 return (ENETDOWN);
2306         }
2307         RSU_LOCK(sc);
2308         bf = rsu_getbuf(sc);
2309         if (bf == NULL) {
2310                 ieee80211_free_node(ni);
2311                 m_freem(m);
2312                 RSU_UNLOCK(sc);
2313                 return (ENOBUFS);
2314         }
2315         ifp->if_opackets++;
2316         if (rsu_tx_start(sc, ni, m, bf) != 0) {
2317                 ieee80211_free_node(ni);
2318                 ifp->if_oerrors++;
2319                 STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
2320                 RSU_UNLOCK(sc);
2321                 return (EIO);
2322         }
2323         RSU_UNLOCK(sc);
2324         sc->sc_tx_timer = 5;
2325
2326         return (0);
2327 }
2328
2329 static void
2330 rsu_init(void *arg)
2331 {
2332         struct rsu_softc *sc = arg;
2333
2334         RSU_LOCK(sc);
2335         rsu_init_locked(arg);
2336         RSU_UNLOCK(sc);
2337 }
2338
2339 static void
2340 rsu_init_locked(struct rsu_softc *sc)
2341 {
2342         struct ifnet *ifp = sc->sc_ifp;
2343         struct r92s_set_pwr_mode cmd;
2344         int error;
2345
2346         /* Init host async commands ring. */
2347         sc->cmdq.cur = sc->cmdq.next = sc->cmdq.queued = 0;
2348
2349         /* Allocate Tx/Rx buffers. */
2350         error = rsu_alloc_rx_list(sc);
2351         if (error != 0) {
2352                 device_printf(sc->sc_dev, "could not allocate Rx buffers\n");
2353                 return;
2354         }
2355         error = rsu_alloc_tx_list(sc);
2356         if (error != 0) {
2357                 device_printf(sc->sc_dev, "could not allocate Tx buffers\n");
2358                 rsu_free_rx_list(sc);
2359                 return;
2360         }
2361         /* Power on adapter. */
2362         if (sc->cut == 1)
2363                 rsu_power_on_acut(sc);
2364         else
2365                 rsu_power_on_bcut(sc);
2366         /* Load firmware. */
2367         error = rsu_load_firmware(sc);
2368         if (error != 0)
2369                 goto fail;
2370
2371         /* Enable Rx TCP checksum offload. */
2372         rsu_write_4(sc, R92S_RCR,
2373             rsu_read_4(sc, R92S_RCR) | 0x04000000);
2374         /* Append PHY status. */
2375         rsu_write_4(sc, R92S_RCR,
2376             rsu_read_4(sc, R92S_RCR) | 0x02000000);
2377
2378         rsu_write_4(sc, R92S_CR,
2379             rsu_read_4(sc, R92S_CR) & ~0xff000000);
2380
2381         /* Use 128 bytes pages. */
2382         rsu_write_1(sc, 0x00b5,
2383             rsu_read_1(sc, 0x00b5) | 0x01);
2384         /* Enable USB Rx aggregation. */
2385         rsu_write_1(sc, 0x00bd,
2386             rsu_read_1(sc, 0x00bd) | 0x80);
2387         /* Set USB Rx aggregation threshold. */
2388         rsu_write_1(sc, 0x00d9, 0x01);
2389         /* Set USB Rx aggregation timeout (1.7ms/4). */
2390         rsu_write_1(sc, 0xfe5b, 0x04);
2391         /* Fix USB Rx FIFO issue. */
2392         rsu_write_1(sc, 0xfe5c,
2393             rsu_read_1(sc, 0xfe5c) | 0x80);
2394
2395         /* Set MAC address. */
2396         rsu_write_region_1(sc, R92S_MACID, IF_LLADDR(ifp), 
2397             IEEE80211_ADDR_LEN);
2398
2399         /* NB: it really takes that long for firmware to boot. */
2400         usb_pause_mtx(&sc->sc_mtx, 1500);
2401
2402         DPRINTF("setting MAC address to %s\n", ether_sprintf(IF_LLADDR(ifp)));
2403         error = rsu_fw_cmd(sc, R92S_CMD_SET_MAC_ADDRESS, IF_LLADDR(ifp),
2404             IEEE80211_ADDR_LEN);
2405         if (error != 0) {
2406                 device_printf(sc->sc_dev, "could not set MAC address\n");
2407                 goto fail;
2408         }
2409
2410         rsu_write_1(sc, R92S_USB_HRPWM,
2411             R92S_USB_HRPWM_PS_ST_ACTIVE | R92S_USB_HRPWM_PS_ALL_ON);
2412
2413         memset(&cmd, 0, sizeof(cmd));
2414         cmd.mode = R92S_PS_MODE_ACTIVE;
2415         DPRINTF("setting ps mode to %d\n", cmd.mode);
2416         error = rsu_fw_cmd(sc, R92S_CMD_SET_PWR_MODE, &cmd, sizeof(cmd));
2417         if (error != 0) {
2418                 device_printf(sc->sc_dev, "could not set PS mode\n");
2419                 goto fail;
2420         }
2421
2422 #if 0
2423         if (ic->ic_htcaps & IEEE80211_HTCAP_CBW20_40) {
2424                 /* Enable 40MHz mode. */
2425                 error = rsu_fw_iocmd(sc,
2426                     SM(R92S_IOCMD_CLASS, 0xf4) |
2427                     SM(R92S_IOCMD_INDEX, 0x00) |
2428                     SM(R92S_IOCMD_VALUE, 0x0007));
2429                 if (error != 0) {
2430                         device_printf(sc->sc_dev,
2431                             "could not enable 40MHz mode\n");
2432                         goto fail;
2433                 }
2434         }
2435
2436         /* Set default channel. */
2437         ic->ic_bss->ni_chan = ic->ic_ibss_chan;
2438 #endif
2439         sc->scan_pass = 0;
2440         usbd_transfer_start(sc->sc_xfer[RSU_BULK_RX]);
2441
2442         /* We're ready to go. */
2443         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2444         ifp->if_drv_flags |= IFF_DRV_RUNNING;
2445
2446         callout_reset(&sc->sc_watchdog_ch, hz, rsu_watchdog, sc);
2447
2448         return;
2449 fail:
2450         rsu_free_rx_list(sc);
2451         rsu_free_tx_list(sc);
2452         return;
2453 }
2454
2455 static void
2456 rsu_stop(struct ifnet *ifp, int disable)
2457 {
2458         struct rsu_softc *sc = ifp->if_softc;
2459
2460         RSU_LOCK(sc);
2461         rsu_stop_locked(ifp, disable);
2462         RSU_UNLOCK(sc);
2463 }
2464
2465 static void
2466 rsu_stop_locked(struct ifnet *ifp, int disable __unused)
2467 {
2468         struct rsu_softc *sc = ifp->if_softc;
2469         int i;
2470
2471         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2472         callout_stop(&sc->sc_watchdog_ch);
2473         sc->sc_calibrating = 0;
2474         taskqueue_cancel_timeout(taskqueue_thread, &sc->calib_task, NULL);
2475
2476         /* Power off adapter. */
2477         rsu_power_off(sc);
2478
2479         for (i = 0; i < RSU_N_TRANSFER; i++)
2480                 usbd_transfer_stop(sc->sc_xfer[i]);
2481 }
2482