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