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