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