]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/usb/wlan/if_rsu.c
MFV: file 5.33
[FreeBSD/FreeBSD.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 tx a-mpdu
26  *   o hostap / ibss / mesh
27  *   o power-save operation
28  */
29
30 #include "opt_wlan.h"
31
32 #include <sys/param.h>
33 #include <sys/endian.h>
34 #include <sys/sockio.h>
35 #include <sys/malloc.h>
36 #include <sys/mbuf.h>
37 #include <sys/kernel.h>
38 #include <sys/socket.h>
39 #include <sys/systm.h>
40 #include <sys/conf.h>
41 #include <sys/bus.h>
42 #include <sys/rman.h>
43 #include <sys/firmware.h>
44 #include <sys/module.h>
45
46 #include <machine/bus.h>
47 #include <machine/resource.h>
48
49 #include <net/bpf.h>
50 #include <net/if.h>
51 #include <net/if_var.h>
52 #include <net/if_arp.h>
53 #include <net/if_dl.h>
54 #include <net/if_media.h>
55 #include <net/if_types.h>
56
57 #include <netinet/in.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/in_var.h>
60 #include <netinet/if_ether.h>
61 #include <netinet/ip.h>
62
63 #include <net80211/ieee80211_var.h>
64 #include <net80211/ieee80211_regdomain.h>
65 #include <net80211/ieee80211_radiotap.h>
66
67 #include <dev/usb/usb.h>
68 #include <dev/usb/usbdi.h>
69 #include "usbdevs.h"
70
71 #include <dev/rtwn/if_rtwn_ridx.h>      /* XXX */
72 #include <dev/usb/wlan/if_rsureg.h>
73
74 #define RSU_RATE_IS_CCK RTWN_RATE_IS_CCK
75
76 #ifdef USB_DEBUG
77 static int rsu_debug = 0;
78 SYSCTL_NODE(_hw_usb, OID_AUTO, rsu, CTLFLAG_RW, 0, "USB rsu");
79 SYSCTL_INT(_hw_usb_rsu, OID_AUTO, debug, CTLFLAG_RWTUN, &rsu_debug, 0,
80     "Debug level");
81 #define RSU_DPRINTF(_sc, _flg, ...)                                     \
82         do                                                              \
83                 if (((_flg) == (RSU_DEBUG_ANY)) || (rsu_debug & (_flg))) \
84                         device_printf((_sc)->sc_dev, __VA_ARGS__);      \
85         while (0)
86 #else
87 #define RSU_DPRINTF(_sc, _flg, ...)
88 #endif
89
90 static int rsu_enable_11n = 1;
91 TUNABLE_INT("hw.usb.rsu.enable_11n", &rsu_enable_11n);
92
93 #define RSU_DEBUG_ANY           0xffffffff
94 #define RSU_DEBUG_TX            0x00000001
95 #define RSU_DEBUG_RX            0x00000002
96 #define RSU_DEBUG_RESET         0x00000004
97 #define RSU_DEBUG_CALIB         0x00000008
98 #define RSU_DEBUG_STATE         0x00000010
99 #define RSU_DEBUG_SCAN          0x00000020
100 #define RSU_DEBUG_FWCMD         0x00000040
101 #define RSU_DEBUG_TXDONE        0x00000080
102 #define RSU_DEBUG_FW            0x00000100
103 #define RSU_DEBUG_FWDBG         0x00000200
104 #define RSU_DEBUG_AMPDU         0x00000400
105 #define RSU_DEBUG_KEY           0x00000800
106 #define RSU_DEBUG_USB           0x00001000
107
108 static const STRUCT_USB_HOST_ID rsu_devs[] = {
109 #define RSU_HT_NOT_SUPPORTED 0
110 #define RSU_HT_SUPPORTED 1
111 #define RSU_DEV_HT(v,p)  { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \
112                                    RSU_HT_SUPPORTED) }
113 #define RSU_DEV(v,p)     { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \
114                                    RSU_HT_NOT_SUPPORTED) }
115         RSU_DEV(ASUS,                   RTL8192SU),
116         RSU_DEV(AZUREWAVE,              RTL8192SU_4),
117         RSU_DEV_HT(ACCTON,              RTL8192SU),
118         RSU_DEV_HT(ASUS,                USBN10),
119         RSU_DEV_HT(AZUREWAVE,           RTL8192SU_1),
120         RSU_DEV_HT(AZUREWAVE,           RTL8192SU_2),
121         RSU_DEV_HT(AZUREWAVE,           RTL8192SU_3),
122         RSU_DEV_HT(AZUREWAVE,           RTL8192SU_5),
123         RSU_DEV_HT(BELKIN,              RTL8192SU_1),
124         RSU_DEV_HT(BELKIN,              RTL8192SU_2),
125         RSU_DEV_HT(BELKIN,              RTL8192SU_3),
126         RSU_DEV_HT(CONCEPTRONIC2,       RTL8192SU_1),
127         RSU_DEV_HT(CONCEPTRONIC2,       RTL8192SU_2),
128         RSU_DEV_HT(CONCEPTRONIC2,       RTL8192SU_3),
129         RSU_DEV_HT(COREGA,              RTL8192SU),
130         RSU_DEV_HT(DLINK2,              DWA131A1),
131         RSU_DEV_HT(DLINK2,              RTL8192SU_1),
132         RSU_DEV_HT(DLINK2,              RTL8192SU_2),
133         RSU_DEV_HT(EDIMAX,              RTL8192SU_1),
134         RSU_DEV_HT(EDIMAX,              RTL8192SU_2),
135         RSU_DEV_HT(EDIMAX,              EW7622UMN),
136         RSU_DEV_HT(GUILLEMOT,           HWGUN54),
137         RSU_DEV_HT(GUILLEMOT,           HWNUM300),
138         RSU_DEV_HT(HAWKING,             RTL8192SU_1),
139         RSU_DEV_HT(HAWKING,             RTL8192SU_2),
140         RSU_DEV_HT(PLANEX2,             GWUSNANO),
141         RSU_DEV_HT(REALTEK,             RTL8171),
142         RSU_DEV_HT(REALTEK,             RTL8172),
143         RSU_DEV_HT(REALTEK,             RTL8173),
144         RSU_DEV_HT(REALTEK,             RTL8174),
145         RSU_DEV_HT(REALTEK,             RTL8192SU),
146         RSU_DEV_HT(REALTEK,             RTL8712),
147         RSU_DEV_HT(REALTEK,             RTL8713),
148         RSU_DEV_HT(SENAO,               RTL8192SU_1),
149         RSU_DEV_HT(SENAO,               RTL8192SU_2),
150         RSU_DEV_HT(SITECOMEU,           WL349V1),
151         RSU_DEV_HT(SITECOMEU,           WL353),
152         RSU_DEV_HT(SWEEX2,              LW154),
153         RSU_DEV_HT(TRENDNET,            TEW646UBH),
154 #undef RSU_DEV_HT
155 #undef RSU_DEV
156 };
157
158 static device_probe_t   rsu_match;
159 static device_attach_t  rsu_attach;
160 static device_detach_t  rsu_detach;
161 static usb_callback_t   rsu_bulk_tx_callback_be_bk;
162 static usb_callback_t   rsu_bulk_tx_callback_vi_vo;
163 static usb_callback_t   rsu_bulk_tx_callback_h2c;
164 static usb_callback_t   rsu_bulk_rx_callback;
165 static usb_error_t      rsu_do_request(struct rsu_softc *,
166                             struct usb_device_request *, void *);
167 static struct ieee80211vap *
168                 rsu_vap_create(struct ieee80211com *, const char name[],
169                     int, enum ieee80211_opmode, int, const uint8_t bssid[],
170                     const uint8_t mac[]);
171 static void     rsu_vap_delete(struct ieee80211vap *);
172 static void     rsu_scan_start(struct ieee80211com *);
173 static void     rsu_scan_end(struct ieee80211com *);
174 static void     rsu_getradiocaps(struct ieee80211com *, int, int *,
175                     struct ieee80211_channel[]);
176 static void     rsu_set_channel(struct ieee80211com *);
177 static void     rsu_scan_curchan(struct ieee80211_scan_state *, unsigned long);
178 static void     rsu_scan_mindwell(struct ieee80211_scan_state *);
179 static void     rsu_update_promisc(struct ieee80211com *);
180 static uint8_t  rsu_get_multi_pos(const uint8_t[]);
181 static void     rsu_set_multi(struct rsu_softc *);
182 static void     rsu_update_mcast(struct ieee80211com *);
183 static int      rsu_alloc_rx_list(struct rsu_softc *);
184 static void     rsu_free_rx_list(struct rsu_softc *);
185 static int      rsu_alloc_tx_list(struct rsu_softc *);
186 static void     rsu_free_tx_list(struct rsu_softc *);
187 static void     rsu_free_list(struct rsu_softc *, struct rsu_data [], int);
188 static struct rsu_data *_rsu_getbuf(struct rsu_softc *);
189 static struct rsu_data *rsu_getbuf(struct rsu_softc *);
190 static void     rsu_freebuf(struct rsu_softc *, struct rsu_data *);
191 static int      rsu_write_region_1(struct rsu_softc *, uint16_t, uint8_t *,
192                     int);
193 static void     rsu_write_1(struct rsu_softc *, uint16_t, uint8_t);
194 static void     rsu_write_2(struct rsu_softc *, uint16_t, uint16_t);
195 static void     rsu_write_4(struct rsu_softc *, uint16_t, uint32_t);
196 static int      rsu_read_region_1(struct rsu_softc *, uint16_t, uint8_t *,
197                     int);
198 static uint8_t  rsu_read_1(struct rsu_softc *, uint16_t);
199 static uint16_t rsu_read_2(struct rsu_softc *, uint16_t);
200 static uint32_t rsu_read_4(struct rsu_softc *, uint16_t);
201 static int      rsu_fw_iocmd(struct rsu_softc *, uint32_t);
202 static uint8_t  rsu_efuse_read_1(struct rsu_softc *, uint16_t);
203 static int      rsu_read_rom(struct rsu_softc *);
204 static int      rsu_fw_cmd(struct rsu_softc *, uint8_t, void *, int);
205 static void     rsu_calib_task(void *, int);
206 static void     rsu_tx_task(void *, int);
207 static void     rsu_set_led(struct rsu_softc *, int);
208 static int      rsu_monitor_newstate(struct ieee80211vap *,
209                     enum ieee80211_state, int);
210 static int      rsu_newstate(struct ieee80211vap *, enum ieee80211_state, int);
211 static int      rsu_key_alloc(struct ieee80211vap *, struct ieee80211_key *,
212                     ieee80211_keyix *, ieee80211_keyix *);
213 static int      rsu_process_key(struct ieee80211vap *,
214                     const struct ieee80211_key *, int);
215 static int      rsu_key_set(struct ieee80211vap *,
216                     const struct ieee80211_key *);
217 static int      rsu_key_delete(struct ieee80211vap *,
218                     const struct ieee80211_key *);
219 static int      rsu_cam_read(struct rsu_softc *, uint8_t, uint32_t *);
220 static void     rsu_cam_write(struct rsu_softc *, uint8_t, uint32_t);
221 static int      rsu_key_check(struct rsu_softc *, ieee80211_keyix, int);
222 static uint8_t  rsu_crypto_mode(struct rsu_softc *, u_int, int);
223 static int      rsu_set_key_group(struct rsu_softc *,
224                     const struct ieee80211_key *);
225 static int      rsu_set_key_pair(struct rsu_softc *,
226                     const struct ieee80211_key *);
227 static int      rsu_reinit_static_keys(struct rsu_softc *);
228 static int      rsu_delete_key(struct rsu_softc *sc, ieee80211_keyix);
229 static void     rsu_delete_key_pair_cb(void *, int);
230 static int      rsu_site_survey(struct rsu_softc *,
231                     struct ieee80211_scan_ssid *);
232 static int      rsu_join_bss(struct rsu_softc *, struct ieee80211_node *);
233 static int      rsu_disconnect(struct rsu_softc *);
234 static int      rsu_hwrssi_to_rssi(struct rsu_softc *, int hw_rssi);
235 static void     rsu_event_survey(struct rsu_softc *, uint8_t *, int);
236 static void     rsu_event_join_bss(struct rsu_softc *, uint8_t *, int);
237 static void     rsu_rx_event(struct rsu_softc *, uint8_t, uint8_t *, int);
238 static void     rsu_rx_multi_event(struct rsu_softc *, uint8_t *, int);
239 static int8_t   rsu_get_rssi(struct rsu_softc *, int, void *);
240 static struct mbuf * rsu_rx_copy_to_mbuf(struct rsu_softc *,
241                     struct r92s_rx_stat *, int);
242 static uint32_t rsu_get_tsf_low(struct rsu_softc *);
243 static uint32_t rsu_get_tsf_high(struct rsu_softc *);
244 static struct ieee80211_node * rsu_rx_frame(struct rsu_softc *, struct mbuf *);
245 static struct mbuf * rsu_rx_multi_frame(struct rsu_softc *, uint8_t *, int);
246 static struct mbuf *
247                 rsu_rxeof(struct usb_xfer *, struct rsu_data *);
248 static void     rsu_txeof(struct usb_xfer *, struct rsu_data *);
249 static int      rsu_raw_xmit(struct ieee80211_node *, struct mbuf *, 
250                     const struct ieee80211_bpf_params *);
251 static void     rsu_rxfilter_init(struct rsu_softc *);
252 static void     rsu_rxfilter_set(struct rsu_softc *, uint32_t, uint32_t);
253 static void     rsu_rxfilter_refresh(struct rsu_softc *);
254 static int      rsu_init(struct rsu_softc *);
255 static int      rsu_tx_start(struct rsu_softc *, struct ieee80211_node *, 
256                     struct mbuf *, struct rsu_data *);
257 static int      rsu_transmit(struct ieee80211com *, struct mbuf *);
258 static void     rsu_start(struct rsu_softc *);
259 static void     _rsu_start(struct rsu_softc *);
260 static int      rsu_ioctl_net(struct ieee80211com *, u_long, void *);
261 static void     rsu_parent(struct ieee80211com *);
262 static void     rsu_stop(struct rsu_softc *);
263 static void     rsu_ms_delay(struct rsu_softc *, int);
264
265 static device_method_t rsu_methods[] = {
266         DEVMETHOD(device_probe,         rsu_match),
267         DEVMETHOD(device_attach,        rsu_attach),
268         DEVMETHOD(device_detach,        rsu_detach),
269
270         DEVMETHOD_END
271 };
272
273 static driver_t rsu_driver = {
274         .name = "rsu",
275         .methods = rsu_methods,
276         .size = sizeof(struct rsu_softc)
277 };
278
279 static devclass_t rsu_devclass;
280
281 DRIVER_MODULE(rsu, uhub, rsu_driver, rsu_devclass, NULL, 0);
282 MODULE_DEPEND(rsu, wlan, 1, 1, 1);
283 MODULE_DEPEND(rsu, usb, 1, 1, 1);
284 MODULE_DEPEND(rsu, firmware, 1, 1, 1);
285 MODULE_VERSION(rsu, 1);
286 USB_PNP_HOST_INFO(rsu_devs);
287
288 static const uint8_t rsu_chan_2ghz[] =
289         { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
290
291 static uint8_t rsu_wme_ac_xfer_map[4] = {
292         [WME_AC_BE] = RSU_BULK_TX_BE_BK,
293         [WME_AC_BK] = RSU_BULK_TX_BE_BK,
294         [WME_AC_VI] = RSU_BULK_TX_VI_VO,
295         [WME_AC_VO] = RSU_BULK_TX_VI_VO,
296 };
297
298 /* XXX hard-coded */
299 #define RSU_H2C_ENDPOINT        3
300
301 static const struct usb_config rsu_config[RSU_N_TRANSFER] = {
302         [RSU_BULK_RX] = {
303                 .type = UE_BULK,
304                 .endpoint = UE_ADDR_ANY,
305                 .direction = UE_DIR_IN,
306                 .bufsize = RSU_RXBUFSZ,
307                 .flags = {
308                         .pipe_bof = 1,
309                         .short_xfer_ok = 1
310                 },
311                 .callback = rsu_bulk_rx_callback
312         },
313         [RSU_BULK_TX_BE_BK] = {
314                 .type = UE_BULK,
315                 .endpoint = 0x06,
316                 .direction = UE_DIR_OUT,
317                 .bufsize = RSU_TXBUFSZ,
318                 .flags = {
319                         .ext_buffer = 1,
320                         .pipe_bof = 1,
321                         .force_short_xfer = 1
322                 },
323                 .callback = rsu_bulk_tx_callback_be_bk,
324                 .timeout = RSU_TX_TIMEOUT
325         },
326         [RSU_BULK_TX_VI_VO] = {
327                 .type = UE_BULK,
328                 .endpoint = 0x04,
329                 .direction = UE_DIR_OUT,
330                 .bufsize = RSU_TXBUFSZ,
331                 .flags = {
332                         .ext_buffer = 1,
333                         .pipe_bof = 1,
334                         .force_short_xfer = 1
335                 },
336                 .callback = rsu_bulk_tx_callback_vi_vo,
337                 .timeout = RSU_TX_TIMEOUT
338         },
339         [RSU_BULK_TX_H2C] = {
340                 .type = UE_BULK,
341                 .endpoint = 0x0d,
342                 .direction = UE_DIR_OUT,
343                 .bufsize = RSU_TXBUFSZ,
344                 .flags = {
345                         .ext_buffer = 1,
346                         .pipe_bof = 1,
347                         .short_xfer_ok = 1
348                 },
349                 .callback = rsu_bulk_tx_callback_h2c,
350                 .timeout = RSU_TX_TIMEOUT
351         },
352 };
353
354 static int
355 rsu_match(device_t self)
356 {
357         struct usb_attach_arg *uaa = device_get_ivars(self);
358
359         if (uaa->usb_mode != USB_MODE_HOST ||
360             uaa->info.bIfaceIndex != 0 ||
361             uaa->info.bConfigIndex != 0)
362                 return (ENXIO);
363
364         return (usbd_lookup_id_by_uaa(rsu_devs, sizeof(rsu_devs), uaa));
365 }
366
367 static int
368 rsu_send_mgmt(struct ieee80211_node *ni, int type, int arg)
369 {
370
371         return (ENOTSUP);
372 }
373
374 static void
375 rsu_update_chw(struct ieee80211com *ic)
376 {
377
378 }
379
380 /*
381  * notification from net80211 that it'd like to do A-MPDU on the given TID.
382  *
383  * Note: this actually hangs traffic at the present moment, so don't use it.
384  * The firmware debug does indiciate it's sending and establishing a TX AMPDU
385  * session, but then no traffic flows.
386  */
387 static int
388 rsu_ampdu_enable(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
389 {
390 #if 0
391         struct rsu_softc *sc = ni->ni_ic->ic_softc;
392         struct r92s_add_ba_req req;
393
394         /* Don't enable if it's requested or running */
395         if (IEEE80211_AMPDU_REQUESTED(tap))
396                 return (0);
397         if (IEEE80211_AMPDU_RUNNING(tap))
398                 return (0);
399
400         /* We've decided to send addba; so send it */
401         req.tid = htole32(tap->txa_tid);
402
403         /* Attempt net80211 state */
404         if (ieee80211_ampdu_tx_request_ext(ni, tap->txa_tid) != 1)
405                 return (0);
406
407         /* Send the firmware command */
408         RSU_DPRINTF(sc, RSU_DEBUG_AMPDU, "%s: establishing AMPDU TX for TID %d\n",
409             __func__,
410             tap->txa_tid);
411
412         RSU_LOCK(sc);
413         if (rsu_fw_cmd(sc, R92S_CMD_ADDBA_REQ, &req, sizeof(req)) != 1) {
414                 RSU_UNLOCK(sc);
415                 /* Mark failure */
416                 (void) ieee80211_ampdu_tx_request_active_ext(ni, tap->txa_tid, 0);
417                 return (0);
418         }
419         RSU_UNLOCK(sc);
420
421         /* Mark success; we don't get any further notifications */
422         (void) ieee80211_ampdu_tx_request_active_ext(ni, tap->txa_tid, 1);
423 #endif
424         /* Return 0, we're driving this ourselves */
425         return (0);
426 }
427
428 static int
429 rsu_wme_update(struct ieee80211com *ic)
430 {
431
432         /* Firmware handles this; not our problem */
433         return (0);
434 }
435
436 static int
437 rsu_attach(device_t self)
438 {
439         struct usb_attach_arg *uaa = device_get_ivars(self);
440         struct rsu_softc *sc = device_get_softc(self);
441         struct ieee80211com *ic = &sc->sc_ic;
442         int error;
443         uint8_t iface_index;
444         struct usb_interface *iface;
445         const char *rft;
446
447         device_set_usb_desc(self);
448         sc->sc_udev = uaa->device;
449         sc->sc_dev = self;
450         sc->sc_rx_checksum_enable = 1;
451         if (rsu_enable_11n)
452                 sc->sc_ht = !! (USB_GET_DRIVER_INFO(uaa) & RSU_HT_SUPPORTED);
453
454         /* Get number of endpoints */
455         iface = usbd_get_iface(sc->sc_udev, 0);
456         sc->sc_nendpoints = iface->idesc->bNumEndpoints;
457
458         /* Endpoints are hard-coded for now, so enforce 4-endpoint only */
459         if (sc->sc_nendpoints != 4) {
460                 device_printf(sc->sc_dev,
461                     "the driver currently only supports 4-endpoint devices\n");
462                 return (ENXIO);
463         }
464
465         mtx_init(&sc->sc_mtx, device_get_nameunit(self), MTX_NETWORK_LOCK,
466             MTX_DEF);
467         RSU_DELKEY_BMAP_LOCK_INIT(sc);
468         TIMEOUT_TASK_INIT(taskqueue_thread, &sc->calib_task, 0, 
469             rsu_calib_task, sc);
470         TASK_INIT(&sc->del_key_task, 0, rsu_delete_key_pair_cb, sc);
471         TASK_INIT(&sc->tx_task, 0, rsu_tx_task, sc);
472         mbufq_init(&sc->sc_snd, ifqmaxlen);
473
474         /* Allocate Tx/Rx buffers. */
475         error = rsu_alloc_rx_list(sc);
476         if (error != 0) {
477                 device_printf(sc->sc_dev, "could not allocate Rx buffers\n");
478                 goto fail_usb;
479         }
480
481         error = rsu_alloc_tx_list(sc);
482         if (error != 0) {
483                 device_printf(sc->sc_dev, "could not allocate Tx buffers\n");
484                 rsu_free_rx_list(sc);
485                 goto fail_usb;
486         }
487
488         iface_index = 0;
489         error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
490             rsu_config, RSU_N_TRANSFER, sc, &sc->sc_mtx);
491         if (error) {
492                 device_printf(sc->sc_dev,
493                     "could not allocate USB transfers, err=%s\n", 
494                     usbd_errstr(error));
495                 goto fail_usb;
496         }
497         RSU_LOCK(sc);
498         /* Read chip revision. */
499         sc->cut = MS(rsu_read_4(sc, R92S_PMC_FSM), R92S_PMC_FSM_CUT);
500         if (sc->cut != 3)
501                 sc->cut = (sc->cut >> 1) + 1;
502         error = rsu_read_rom(sc);
503         RSU_UNLOCK(sc);
504         if (error != 0) {
505                 device_printf(self, "could not read ROM\n");
506                 goto fail_rom;
507         }
508
509         /* Figure out TX/RX streams */
510         switch (sc->rom[84]) {
511         case 0x0:
512                 sc->sc_rftype = RTL8712_RFCONFIG_1T1R;
513                 sc->sc_nrxstream = 1;
514                 sc->sc_ntxstream = 1;
515                 rft = "1T1R";
516                 break;
517         case 0x1:
518                 sc->sc_rftype = RTL8712_RFCONFIG_1T2R;
519                 sc->sc_nrxstream = 2;
520                 sc->sc_ntxstream = 1;
521                 rft = "1T2R";
522                 break;
523         case 0x2:
524                 sc->sc_rftype = RTL8712_RFCONFIG_2T2R;
525                 sc->sc_nrxstream = 2;
526                 sc->sc_ntxstream = 2;
527                 rft = "2T2R";
528                 break;
529         case 0x3:       /* "green" NIC */
530                 sc->sc_rftype = RTL8712_RFCONFIG_1T2R;
531                 sc->sc_nrxstream = 2;
532                 sc->sc_ntxstream = 1;
533                 rft = "1T2R ('green')";
534                 break;
535         default:
536                 device_printf(sc->sc_dev,
537                     "%s: unknown board type (rfconfig=0x%02x)\n",
538                     __func__,
539                     sc->rom[84]);
540                 goto fail_rom;
541         }
542
543         IEEE80211_ADDR_COPY(ic->ic_macaddr, &sc->rom[0x12]);
544         device_printf(self, "MAC/BB RTL8712 cut %d %s\n", sc->cut, rft);
545
546         ic->ic_softc = sc;
547         ic->ic_name = device_get_nameunit(self);
548         ic->ic_phytype = IEEE80211_T_OFDM;      /* Not only, but not used. */
549         ic->ic_opmode = IEEE80211_M_STA;        /* Default to BSS mode. */
550
551         /* Set device capabilities. */
552         ic->ic_caps =
553             IEEE80211_C_STA |           /* station mode */
554             IEEE80211_C_MONITOR |       /* monitor mode supported */
555 #if 0
556             IEEE80211_C_BGSCAN |        /* Background scan. */
557 #endif
558             IEEE80211_C_SHPREAMBLE |    /* Short preamble supported. */
559             IEEE80211_C_WME |           /* WME/QoS */
560             IEEE80211_C_SHSLOT |        /* Short slot time supported. */
561             IEEE80211_C_WPA;            /* WPA/RSN. */
562
563         ic->ic_cryptocaps =
564             IEEE80211_CRYPTO_WEP |
565             IEEE80211_CRYPTO_TKIP |
566             IEEE80211_CRYPTO_AES_CCM;
567
568         /* Check if HT support is present. */
569         if (sc->sc_ht) {
570                 device_printf(sc->sc_dev, "%s: enabling 11n\n", __func__);
571
572                 /* Enable basic HT */
573                 ic->ic_htcaps = IEEE80211_HTC_HT |
574 #if 0
575                     IEEE80211_HTC_AMPDU |
576 #endif
577                     IEEE80211_HTC_AMSDU |
578                     IEEE80211_HTCAP_MAXAMSDU_3839 |
579                     IEEE80211_HTCAP_SMPS_OFF;
580                 ic->ic_htcaps |= IEEE80211_HTCAP_CHWIDTH40;
581
582                 /* set number of spatial streams */
583                 ic->ic_txstream = sc->sc_ntxstream;
584                 ic->ic_rxstream = sc->sc_nrxstream;
585         }
586         ic->ic_flags_ext |= IEEE80211_FEXT_SCAN_OFFLOAD;
587
588         rsu_getradiocaps(ic, IEEE80211_CHAN_MAX, &ic->ic_nchans,
589             ic->ic_channels);
590
591         ieee80211_ifattach(ic);
592         ic->ic_raw_xmit = rsu_raw_xmit;
593         ic->ic_scan_start = rsu_scan_start;
594         ic->ic_scan_end = rsu_scan_end;
595         ic->ic_getradiocaps = rsu_getradiocaps;
596         ic->ic_set_channel = rsu_set_channel;
597         ic->ic_scan_curchan = rsu_scan_curchan;
598         ic->ic_scan_mindwell = rsu_scan_mindwell;
599         ic->ic_vap_create = rsu_vap_create;
600         ic->ic_vap_delete = rsu_vap_delete;
601         ic->ic_update_promisc = rsu_update_promisc;
602         ic->ic_update_mcast = rsu_update_mcast;
603         ic->ic_ioctl = rsu_ioctl_net;
604         ic->ic_parent = rsu_parent;
605         ic->ic_transmit = rsu_transmit;
606         ic->ic_send_mgmt = rsu_send_mgmt;
607         ic->ic_update_chw = rsu_update_chw;
608         ic->ic_ampdu_enable = rsu_ampdu_enable;
609         ic->ic_wme.wme_update = rsu_wme_update;
610
611         ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr,
612             sizeof(sc->sc_txtap), RSU_TX_RADIOTAP_PRESENT, 
613             &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
614             RSU_RX_RADIOTAP_PRESENT);
615
616         if (bootverbose)
617                 ieee80211_announce(ic);
618
619         return (0);
620
621 fail_rom:
622         usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER);
623 fail_usb:
624         mtx_destroy(&sc->sc_mtx);
625         return (ENXIO);
626 }
627
628 static int
629 rsu_detach(device_t self)
630 {
631         struct rsu_softc *sc = device_get_softc(self);
632         struct ieee80211com *ic = &sc->sc_ic;
633
634         rsu_stop(sc);
635
636         usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER);
637
638         /*
639          * Free buffers /before/ we detach from net80211, else node
640          * references to destroyed vaps will lead to a panic.
641          */
642         /* Free Tx/Rx buffers. */
643         RSU_LOCK(sc);
644         rsu_free_tx_list(sc);
645         rsu_free_rx_list(sc);
646         RSU_UNLOCK(sc);
647
648         /* Frames are freed; detach from net80211 */
649         ieee80211_ifdetach(ic);
650
651         taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task);
652         taskqueue_drain(taskqueue_thread, &sc->del_key_task);
653         taskqueue_drain(taskqueue_thread, &sc->tx_task);
654
655         RSU_DELKEY_BMAP_LOCK_DESTROY(sc);
656         mtx_destroy(&sc->sc_mtx);
657
658         return (0);
659 }
660
661 static usb_error_t
662 rsu_do_request(struct rsu_softc *sc, struct usb_device_request *req,
663     void *data)
664 {
665         usb_error_t err;
666         int ntries = 10;
667         
668         RSU_ASSERT_LOCKED(sc);
669
670         while (ntries--) {
671                 err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
672                     req, data, 0, NULL, 250 /* ms */);
673                 if (err == 0 || err == USB_ERR_NOT_CONFIGURED)
674                         break;
675                 RSU_DPRINTF(sc, RSU_DEBUG_USB,
676                     "Control request failed, %s (retries left: %d)\n",
677                     usbd_errstr(err), ntries);
678                 rsu_ms_delay(sc, 10);
679         }
680
681         return (err);
682 }
683
684 static struct ieee80211vap *
685 rsu_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
686     enum ieee80211_opmode opmode, int flags,
687     const uint8_t bssid[IEEE80211_ADDR_LEN],
688     const uint8_t mac[IEEE80211_ADDR_LEN])
689 {
690         struct rsu_softc *sc = ic->ic_softc;
691         struct rsu_vap *uvp;
692         struct ieee80211vap *vap;
693         struct ifnet *ifp;
694
695         if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
696                 return (NULL);
697
698         uvp =  malloc(sizeof(struct rsu_vap), M_80211_VAP, M_WAITOK | M_ZERO);
699         vap = &uvp->vap;
700
701         if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
702             flags, bssid) != 0) {
703                 /* out of memory */
704                 free(uvp, M_80211_VAP);
705                 return (NULL);
706         }
707
708         ifp = vap->iv_ifp;
709         ifp->if_capabilities = IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6;
710         RSU_LOCK(sc);
711         if (sc->sc_rx_checksum_enable)
712                 ifp->if_capenable |= IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6;
713         RSU_UNLOCK(sc);
714
715         /* override state transition machine */
716         uvp->newstate = vap->iv_newstate;
717         if (opmode == IEEE80211_M_MONITOR)
718                 vap->iv_newstate = rsu_monitor_newstate;
719         else
720                 vap->iv_newstate = rsu_newstate;
721         vap->iv_key_alloc = rsu_key_alloc;
722         vap->iv_key_set = rsu_key_set;
723         vap->iv_key_delete = rsu_key_delete;
724
725         /* Limits from the r92su driver */
726         vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_16;
727         vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_32K;
728
729         /* complete setup */
730         ieee80211_vap_attach(vap, ieee80211_media_change,
731             ieee80211_media_status, mac);
732         ic->ic_opmode = opmode;
733
734         return (vap);
735 }
736
737 static void
738 rsu_vap_delete(struct ieee80211vap *vap)
739 {
740         struct rsu_vap *uvp = RSU_VAP(vap);
741
742         ieee80211_vap_detach(vap);
743         free(uvp, M_80211_VAP);
744 }
745
746 static void
747 rsu_scan_start(struct ieee80211com *ic)
748 {
749         struct rsu_softc *sc = ic->ic_softc;
750         struct ieee80211_scan_state *ss = ic->ic_scan;
751         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
752         int error;
753
754         /* Scanning is done by the firmware. */
755         RSU_LOCK(sc);
756         sc->sc_active_scan = !!(ss->ss_flags & IEEE80211_SCAN_ACTIVE);
757         /* XXX TODO: force awake if in network-sleep? */
758         error = rsu_site_survey(sc, ss->ss_nssid > 0 ? &ss->ss_ssid[0] : NULL);
759         RSU_UNLOCK(sc);
760         if (error != 0) {
761                 device_printf(sc->sc_dev,
762                     "could not send site survey command\n");
763                 ieee80211_cancel_scan(vap);
764         }
765 }
766
767 static void
768 rsu_scan_end(struct ieee80211com *ic)
769 {
770         /* Nothing to do here. */
771 }
772
773 static void
774 rsu_getradiocaps(struct ieee80211com *ic,
775     int maxchans, int *nchans, struct ieee80211_channel chans[])
776 {
777         struct rsu_softc *sc = ic->ic_softc;
778         uint8_t bands[IEEE80211_MODE_BYTES];
779
780         /* Set supported .11b and .11g rates. */
781         memset(bands, 0, sizeof(bands));
782         setbit(bands, IEEE80211_MODE_11B);
783         setbit(bands, IEEE80211_MODE_11G);
784         if (sc->sc_ht)
785                 setbit(bands, IEEE80211_MODE_11NG);
786         ieee80211_add_channel_list_2ghz(chans, maxchans, nchans,
787             rsu_chan_2ghz, nitems(rsu_chan_2ghz), bands,
788             (ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) != 0);
789 }
790
791 static void
792 rsu_set_channel(struct ieee80211com *ic)
793 {
794         struct rsu_softc *sc = ic->ic_softc;
795
796         /*
797          * Only need to set the channel in Monitor mode. AP scanning and auth
798          * are already taken care of by their respective firmware commands.
799          */     
800         if (ic->ic_opmode == IEEE80211_M_MONITOR) {
801                 struct r92s_set_channel cmd;
802                 int error;
803
804                 cmd.channel = IEEE80211_CHAN2IEEE(ic->ic_curchan);
805
806                 RSU_LOCK(sc);
807                 error = rsu_fw_cmd(sc, R92S_CMD_SET_CHANNEL, &cmd,
808                     sizeof(cmd));
809                 if (error != 0) {
810                         device_printf(sc->sc_dev,
811                             "%s: error %d setting channel\n", __func__,
812                             error);
813                 }
814                 RSU_UNLOCK(sc);
815         }
816 }
817
818 static void
819 rsu_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
820 {
821         /* Scan is done in rsu_scan_start(). */
822 }
823
824 /**
825  * Called by the net80211 framework to indicate
826  * the minimum dwell time has been met, terminate the scan.
827  * We don't actually terminate the scan as the firmware will notify
828  * us when it's finished and we have no way to interrupt it.
829  */
830 static void
831 rsu_scan_mindwell(struct ieee80211_scan_state *ss)
832 {
833         /* NB: don't try to abort scan; wait for firmware to finish */
834 }
835
836 static void
837 rsu_update_promisc(struct ieee80211com *ic)
838 {
839         struct rsu_softc *sc = ic->ic_softc;
840
841         RSU_LOCK(sc);
842         if (sc->sc_running)
843                 rsu_rxfilter_refresh(sc);
844         RSU_UNLOCK(sc);
845 }
846
847 /*
848  * The same as rtwn_get_multi_pos() / rtwn_set_multi().
849  */
850 static uint8_t
851 rsu_get_multi_pos(const uint8_t maddr[])
852 {
853         uint64_t mask = 0x00004d101df481b4;
854         uint8_t pos = 0x27;     /* initial value */
855         int i, j;
856
857         for (i = 0; i < IEEE80211_ADDR_LEN; i++)
858                 for (j = (i == 0) ? 1 : 0; j < 8; j++)
859                         if ((maddr[i] >> j) & 1)
860                                 pos ^= (mask >> (i * 8 + j - 1));
861
862         pos &= 0x3f;
863
864         return (pos);
865 }
866
867 static void
868 rsu_set_multi(struct rsu_softc *sc)
869 {
870         struct ieee80211com *ic = &sc->sc_ic;
871         uint32_t mfilt[2];
872
873         RSU_ASSERT_LOCKED(sc);
874
875         /* general structure was copied from ath(4). */
876         if (ic->ic_allmulti == 0) {
877                 struct ieee80211vap *vap;
878                 struct ifnet *ifp;
879                 struct ifmultiaddr *ifma;
880
881                 /*
882                  * Merge multicast addresses to form the hardware filter.
883                  */
884                 mfilt[0] = mfilt[1] = 0;
885                 TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
886                         ifp = vap->iv_ifp;
887                         if_maddr_rlock(ifp);
888                         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
889                                 caddr_t dl;
890                                 uint8_t pos;
891
892                                 dl = LLADDR((struct sockaddr_dl *)
893                                     ifma->ifma_addr);
894                                 pos = rsu_get_multi_pos(dl);
895
896                                 mfilt[pos / 32] |= (1 << (pos % 32));
897                         }
898                         if_maddr_runlock(ifp);
899                 }
900         } else
901                 mfilt[0] = mfilt[1] = ~0;
902
903         rsu_write_4(sc, R92S_MAR + 0, mfilt[0]);
904         rsu_write_4(sc, R92S_MAR + 4, mfilt[1]);
905
906         RSU_DPRINTF(sc, RSU_DEBUG_STATE, "%s: MC filter %08x:%08x\n",
907             __func__, mfilt[0], mfilt[1]);
908 }
909
910 static void
911 rsu_update_mcast(struct ieee80211com *ic)
912 {
913         struct rsu_softc *sc = ic->ic_softc;
914
915         RSU_LOCK(sc);
916         if (sc->sc_running)
917                 rsu_set_multi(sc);
918         RSU_UNLOCK(sc);
919 }
920
921 static int
922 rsu_alloc_list(struct rsu_softc *sc, struct rsu_data data[],
923     int ndata, int maxsz)
924 {
925         int i, error;
926
927         for (i = 0; i < ndata; i++) {
928                 struct rsu_data *dp = &data[i];
929                 dp->sc = sc;
930                 dp->m = NULL;
931                 dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT);
932                 if (dp->buf == NULL) {
933                         device_printf(sc->sc_dev,
934                             "could not allocate buffer\n");
935                         error = ENOMEM;
936                         goto fail;
937                 }
938                 dp->ni = NULL;
939         }
940
941         return (0);
942 fail:
943         rsu_free_list(sc, data, ndata);
944         return (error);
945 }
946
947 static int
948 rsu_alloc_rx_list(struct rsu_softc *sc)
949 {
950         int error, i;
951
952         error = rsu_alloc_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT,
953             RSU_RXBUFSZ);
954         if (error != 0)
955                 return (error);
956
957         STAILQ_INIT(&sc->sc_rx_active);
958         STAILQ_INIT(&sc->sc_rx_inactive);
959
960         for (i = 0; i < RSU_RX_LIST_COUNT; i++)
961                 STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i], next);
962
963         return (0);
964 }
965
966 static int
967 rsu_alloc_tx_list(struct rsu_softc *sc)
968 {
969         int error, i;
970
971         error = rsu_alloc_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT,
972             RSU_TXBUFSZ);
973         if (error != 0)
974                 return (error);
975
976         STAILQ_INIT(&sc->sc_tx_inactive);
977
978         for (i = 0; i != RSU_N_TRANSFER; i++) {
979                 STAILQ_INIT(&sc->sc_tx_active[i]);
980                 STAILQ_INIT(&sc->sc_tx_pending[i]);
981         }
982
983         for (i = 0; i < RSU_TX_LIST_COUNT; i++) {
984                 STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i], next);
985         }
986
987         return (0);
988 }
989
990 static void
991 rsu_free_tx_list(struct rsu_softc *sc)
992 {
993         int i;
994
995         /* prevent further allocations from TX list(s) */
996         STAILQ_INIT(&sc->sc_tx_inactive);
997
998         for (i = 0; i != RSU_N_TRANSFER; i++) {
999                 STAILQ_INIT(&sc->sc_tx_active[i]);
1000                 STAILQ_INIT(&sc->sc_tx_pending[i]);
1001         }
1002
1003         rsu_free_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT);
1004 }
1005
1006 static void
1007 rsu_free_rx_list(struct rsu_softc *sc)
1008 {
1009         /* prevent further allocations from RX list(s) */
1010         STAILQ_INIT(&sc->sc_rx_inactive);
1011         STAILQ_INIT(&sc->sc_rx_active);
1012
1013         rsu_free_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT);
1014 }
1015
1016 static void
1017 rsu_free_list(struct rsu_softc *sc, struct rsu_data data[], int ndata)
1018 {
1019         int i;
1020
1021         for (i = 0; i < ndata; i++) {
1022                 struct rsu_data *dp = &data[i];
1023
1024                 if (dp->buf != NULL) {
1025                         free(dp->buf, M_USBDEV);
1026                         dp->buf = NULL;
1027                 }
1028                 if (dp->ni != NULL) {
1029                         ieee80211_free_node(dp->ni);
1030                         dp->ni = NULL;
1031                 }
1032         }
1033 }
1034
1035 static struct rsu_data *
1036 _rsu_getbuf(struct rsu_softc *sc)
1037 {
1038         struct rsu_data *bf;
1039
1040         bf = STAILQ_FIRST(&sc->sc_tx_inactive);
1041         if (bf != NULL)
1042                 STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next);
1043         else
1044                 bf = NULL;
1045         return (bf);
1046 }
1047
1048 static struct rsu_data *
1049 rsu_getbuf(struct rsu_softc *sc)
1050 {
1051         struct rsu_data *bf;
1052
1053         RSU_ASSERT_LOCKED(sc);
1054
1055         bf = _rsu_getbuf(sc);
1056         if (bf == NULL) {
1057                 RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: no buffers\n", __func__);
1058         }
1059         return (bf);
1060 }
1061
1062 static void
1063 rsu_freebuf(struct rsu_softc *sc, struct rsu_data *bf)
1064 {
1065
1066         RSU_ASSERT_LOCKED(sc);
1067         STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, bf, next);
1068 }
1069
1070 static int
1071 rsu_write_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
1072     int len)
1073 {
1074         usb_device_request_t req;
1075
1076         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1077         req.bRequest = R92S_REQ_REGS;
1078         USETW(req.wValue, addr);
1079         USETW(req.wIndex, 0);
1080         USETW(req.wLength, len);
1081
1082         return (rsu_do_request(sc, &req, buf));
1083 }
1084
1085 static void
1086 rsu_write_1(struct rsu_softc *sc, uint16_t addr, uint8_t val)
1087 {
1088         rsu_write_region_1(sc, addr, &val, 1);
1089 }
1090
1091 static void
1092 rsu_write_2(struct rsu_softc *sc, uint16_t addr, uint16_t val)
1093 {
1094         val = htole16(val);
1095         rsu_write_region_1(sc, addr, (uint8_t *)&val, 2);
1096 }
1097
1098 static void
1099 rsu_write_4(struct rsu_softc *sc, uint16_t addr, uint32_t val)
1100 {
1101         val = htole32(val);
1102         rsu_write_region_1(sc, addr, (uint8_t *)&val, 4);
1103 }
1104
1105 static int
1106 rsu_read_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
1107     int len)
1108 {
1109         usb_device_request_t req;
1110
1111         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1112         req.bRequest = R92S_REQ_REGS;
1113         USETW(req.wValue, addr);
1114         USETW(req.wIndex, 0);
1115         USETW(req.wLength, len);
1116
1117         return (rsu_do_request(sc, &req, buf));
1118 }
1119
1120 static uint8_t
1121 rsu_read_1(struct rsu_softc *sc, uint16_t addr)
1122 {
1123         uint8_t val;
1124
1125         if (rsu_read_region_1(sc, addr, &val, 1) != 0)
1126                 return (0xff);
1127         return (val);
1128 }
1129
1130 static uint16_t
1131 rsu_read_2(struct rsu_softc *sc, uint16_t addr)
1132 {
1133         uint16_t val;
1134
1135         if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0)
1136                 return (0xffff);
1137         return (le16toh(val));
1138 }
1139
1140 static uint32_t
1141 rsu_read_4(struct rsu_softc *sc, uint16_t addr)
1142 {
1143         uint32_t val;
1144
1145         if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0)
1146                 return (0xffffffff);
1147         return (le32toh(val));
1148 }
1149
1150 static int
1151 rsu_fw_iocmd(struct rsu_softc *sc, uint32_t iocmd)
1152 {
1153         int ntries;
1154
1155         rsu_write_4(sc, R92S_IOCMD_CTRL, iocmd);
1156         rsu_ms_delay(sc, 1);
1157         for (ntries = 0; ntries < 50; ntries++) {
1158                 if (rsu_read_4(sc, R92S_IOCMD_CTRL) == 0)
1159                         return (0);
1160                 rsu_ms_delay(sc, 1);
1161         }
1162         return (ETIMEDOUT);
1163 }
1164
1165 static uint8_t
1166 rsu_efuse_read_1(struct rsu_softc *sc, uint16_t addr)
1167 {
1168         uint32_t reg;
1169         int ntries;
1170
1171         reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
1172         reg = RW(reg, R92S_EFUSE_CTRL_ADDR, addr);
1173         reg &= ~R92S_EFUSE_CTRL_VALID;
1174         rsu_write_4(sc, R92S_EFUSE_CTRL, reg);
1175         /* Wait for read operation to complete. */
1176         for (ntries = 0; ntries < 100; ntries++) {
1177                 reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
1178                 if (reg & R92S_EFUSE_CTRL_VALID)
1179                         return (MS(reg, R92S_EFUSE_CTRL_DATA));
1180                 rsu_ms_delay(sc, 1);
1181         }
1182         device_printf(sc->sc_dev,
1183             "could not read efuse byte at address 0x%x\n", addr);
1184         return (0xff);
1185 }
1186
1187 static int
1188 rsu_read_rom(struct rsu_softc *sc)
1189 {
1190         uint8_t *rom = sc->rom;
1191         uint16_t addr = 0;
1192         uint32_t reg;
1193         uint8_t off, msk;
1194         int i;
1195
1196         /* Make sure that ROM type is eFuse and that autoload succeeded. */
1197         reg = rsu_read_1(sc, R92S_EE_9346CR);
1198         if ((reg & (R92S_9356SEL | R92S_EEPROM_EN)) != R92S_EEPROM_EN)
1199                 return (EIO);
1200
1201         /* Turn on 2.5V to prevent eFuse leakage. */
1202         reg = rsu_read_1(sc, R92S_EFUSE_TEST + 3);
1203         rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg | 0x80);
1204         rsu_ms_delay(sc, 1);
1205         rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg & ~0x80);
1206
1207         /* Read full ROM image. */
1208         memset(&sc->rom, 0xff, sizeof(sc->rom));
1209         while (addr < 512) {
1210                 reg = rsu_efuse_read_1(sc, addr);
1211                 if (reg == 0xff)
1212                         break;
1213                 addr++;
1214                 off = reg >> 4;
1215                 msk = reg & 0xf;
1216                 for (i = 0; i < 4; i++) {
1217                         if (msk & (1 << i))
1218                                 continue;
1219                         rom[off * 8 + i * 2 + 0] =
1220                             rsu_efuse_read_1(sc, addr);
1221                         addr++;
1222                         rom[off * 8 + i * 2 + 1] =
1223                             rsu_efuse_read_1(sc, addr);
1224                         addr++;
1225                 }
1226         }
1227 #ifdef USB_DEBUG
1228         if (rsu_debug & RSU_DEBUG_RESET) {
1229                 /* Dump ROM content. */
1230                 printf("\n");
1231                 for (i = 0; i < sizeof(sc->rom); i++)
1232                         printf("%02x:", rom[i]);
1233                 printf("\n");
1234         }
1235 #endif
1236         return (0);
1237 }
1238
1239 static int
1240 rsu_fw_cmd(struct rsu_softc *sc, uint8_t code, void *buf, int len)
1241 {
1242         const uint8_t which = RSU_H2C_ENDPOINT;
1243         struct rsu_data *data;
1244         struct r92s_tx_desc *txd;
1245         struct r92s_fw_cmd_hdr *cmd;
1246         int cmdsz;
1247         int xferlen;
1248
1249         RSU_ASSERT_LOCKED(sc);
1250
1251         data = rsu_getbuf(sc);
1252         if (data == NULL)
1253                 return (ENOMEM);
1254
1255         /* Blank the entire payload, just to be safe */
1256         memset(data->buf, '\0', RSU_TXBUFSZ);
1257
1258         /* Round-up command length to a multiple of 8 bytes. */
1259         /* XXX TODO: is this required? */
1260         cmdsz = (len + 7) & ~7;
1261
1262         xferlen = sizeof(*txd) + sizeof(*cmd) + cmdsz;
1263         KASSERT(xferlen <= RSU_TXBUFSZ, ("%s: invalid length", __func__));
1264         memset(data->buf, 0, xferlen);
1265
1266         /* Setup Tx descriptor. */
1267         txd = (struct r92s_tx_desc *)data->buf;
1268         txd->txdw0 = htole32(
1269             SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
1270             SM(R92S_TXDW0_PKTLEN, sizeof(*cmd) + cmdsz) |
1271             R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
1272         txd->txdw1 = htole32(SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_H2C));
1273
1274         /* Setup command header. */
1275         cmd = (struct r92s_fw_cmd_hdr *)&txd[1];
1276         cmd->len = htole16(cmdsz);
1277         cmd->code = code;
1278         cmd->seq = sc->cmd_seq;
1279         sc->cmd_seq = (sc->cmd_seq + 1) & 0x7f;
1280
1281         /* Copy command payload. */
1282         memcpy(&cmd[1], buf, len);
1283
1284         RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FWCMD,
1285             "%s: Tx cmd code=0x%x len=0x%x\n",
1286             __func__, code, cmdsz);
1287         data->buflen = xferlen;
1288         STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
1289         usbd_transfer_start(sc->sc_xfer[which]);
1290
1291         return (0);
1292 }
1293
1294 /* ARGSUSED */
1295 static void
1296 rsu_calib_task(void *arg, int pending __unused)
1297 {
1298         struct rsu_softc *sc = arg;
1299 #ifdef notyet
1300         uint32_t reg;
1301 #endif
1302
1303         RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "%s: running calibration task\n",
1304             __func__);
1305
1306         RSU_LOCK(sc);
1307 #ifdef notyet
1308         /* Read WPS PBC status. */
1309         rsu_write_1(sc, R92S_MAC_PINMUX_CTRL,
1310             R92S_GPIOMUX_EN | SM(R92S_GPIOSEL_GPIO, R92S_GPIOSEL_GPIO_JTAG));
1311         rsu_write_1(sc, R92S_GPIO_IO_SEL,
1312             rsu_read_1(sc, R92S_GPIO_IO_SEL) & ~R92S_GPIO_WPS);
1313         reg = rsu_read_1(sc, R92S_GPIO_CTRL);
1314         if (reg != 0xff && (reg & R92S_GPIO_WPS))
1315                 RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "WPS PBC is pushed\n");
1316 #endif
1317         /* Read current signal level. */
1318         if (rsu_fw_iocmd(sc, 0xf4000001) == 0) {
1319                 sc->sc_currssi = rsu_read_4(sc, R92S_IOCMD_DATA);
1320                 RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "%s: RSSI=%d (%d)\n",
1321                     __func__, sc->sc_currssi,
1322                     rsu_hwrssi_to_rssi(sc, sc->sc_currssi));
1323         }
1324         if (sc->sc_calibrating)
1325                 taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, hz);
1326         RSU_UNLOCK(sc);
1327 }
1328
1329 static void
1330 rsu_tx_task(void *arg, int pending __unused)
1331 {
1332         struct rsu_softc *sc = arg;
1333
1334         RSU_LOCK(sc);
1335         _rsu_start(sc);
1336         RSU_UNLOCK(sc);
1337 }
1338
1339 #define RSU_PWR_UNKNOWN         0x0
1340 #define RSU_PWR_ACTIVE          0x1
1341 #define RSU_PWR_OFF             0x2
1342 #define RSU_PWR_SLEEP           0x3
1343
1344 /*
1345  * Set the current power state.
1346  *
1347  * The rtlwifi code doesn't do this so aggressively; it
1348  * waits for an idle period after association with
1349  * no traffic before doing this.
1350  *
1351  * For now - it's on in all states except RUN, and
1352  * in RUN it'll transition to allow sleep.
1353  */
1354
1355 struct r92s_pwr_cmd {
1356         uint8_t mode;
1357         uint8_t smart_ps;
1358         uint8_t bcn_pass_time;
1359 };
1360
1361 static int
1362 rsu_set_fw_power_state(struct rsu_softc *sc, int state)
1363 {
1364         struct r92s_set_pwr_mode cmd;
1365         //struct r92s_pwr_cmd cmd;
1366         int error;
1367
1368         RSU_ASSERT_LOCKED(sc);
1369
1370         /* only change state if required */
1371         if (sc->sc_curpwrstate == state)
1372                 return (0);
1373
1374         memset(&cmd, 0, sizeof(cmd));
1375
1376         switch (state) {
1377         case RSU_PWR_ACTIVE:
1378                 /* Force the hardware awake */
1379                 rsu_write_1(sc, R92S_USB_HRPWM,
1380                     R92S_USB_HRPWM_PS_ST_ACTIVE | R92S_USB_HRPWM_PS_ALL_ON);
1381                 cmd.mode = R92S_PS_MODE_ACTIVE;
1382                 break;
1383         case RSU_PWR_SLEEP:
1384                 cmd.mode = R92S_PS_MODE_DTIM;   /* XXX configurable? */
1385                 cmd.smart_ps = 1; /* XXX 2 if doing p2p */
1386                 cmd.bcn_pass_time = 5; /* in 100mS usb.c, linux/rtlwifi */
1387                 break;
1388         case RSU_PWR_OFF:
1389                 cmd.mode = R92S_PS_MODE_RADIOOFF;
1390                 break;
1391         default:
1392                 device_printf(sc->sc_dev, "%s: unknown ps mode (%d)\n",
1393                     __func__,
1394                     state);
1395                 return (ENXIO);
1396         }
1397
1398         RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1399             "%s: setting ps mode to %d (mode %d)\n",
1400             __func__, state, cmd.mode);
1401         error = rsu_fw_cmd(sc, R92S_CMD_SET_PWR_MODE, &cmd, sizeof(cmd));
1402         if (error == 0)
1403                 sc->sc_curpwrstate = state;
1404
1405         return (error);
1406 }
1407
1408 static void
1409 rsu_set_led(struct rsu_softc *sc, int on)
1410 {
1411         rsu_write_1(sc, R92S_LEDCFG,
1412             (rsu_read_1(sc, R92S_LEDCFG) & 0xf0) | (!on << 3));
1413 }
1414
1415 static int
1416 rsu_monitor_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate,
1417     int arg)
1418 {
1419         struct ieee80211com *ic = vap->iv_ic;
1420         struct rsu_softc *sc = ic->ic_softc;
1421         struct rsu_vap *uvp = RSU_VAP(vap);
1422
1423         if (vap->iv_state != nstate) {
1424                 IEEE80211_UNLOCK(ic);
1425                 RSU_LOCK(sc);
1426
1427                 switch (nstate) {
1428                 case IEEE80211_S_INIT:
1429                         sc->sc_vap_is_running = 0;
1430                         rsu_set_led(sc, 0);
1431                         break;
1432                 case IEEE80211_S_RUN:
1433                         sc->sc_vap_is_running = 1;
1434                         rsu_set_led(sc, 1);
1435                         break;
1436                 default:
1437                         /* NOTREACHED */
1438                         break;
1439                 }
1440                 rsu_rxfilter_refresh(sc);
1441
1442                 RSU_UNLOCK(sc);
1443                 IEEE80211_LOCK(ic);
1444         }
1445
1446         return (uvp->newstate(vap, nstate, arg));
1447 }
1448
1449 static int
1450 rsu_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1451 {
1452         struct rsu_vap *uvp = RSU_VAP(vap);
1453         struct ieee80211com *ic = vap->iv_ic;
1454         struct rsu_softc *sc = ic->ic_softc;
1455         struct ieee80211_node *ni;
1456         struct ieee80211_rateset *rs;
1457         enum ieee80211_state ostate;
1458         int error, startcal = 0;
1459
1460         ostate = vap->iv_state;
1461         RSU_DPRINTF(sc, RSU_DEBUG_STATE, "%s: %s -> %s\n",
1462             __func__,
1463             ieee80211_state_name[ostate],
1464             ieee80211_state_name[nstate]);
1465
1466         IEEE80211_UNLOCK(ic);
1467         if (ostate == IEEE80211_S_RUN) {
1468                 RSU_LOCK(sc);
1469                 /* Stop calibration. */
1470                 sc->sc_calibrating = 0;
1471
1472                 /* Pause Tx for AC queues. */
1473                 rsu_write_1(sc, R92S_TXPAUSE, R92S_TXPAUSE_AC);
1474                 usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(10));
1475
1476                 RSU_UNLOCK(sc);
1477                 taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task);
1478                 taskqueue_drain(taskqueue_thread, &sc->tx_task);
1479                 RSU_LOCK(sc);
1480                 /* Disassociate from our current BSS. */
1481                 rsu_disconnect(sc);
1482                 usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(10));
1483
1484                 /* Refresh Rx filter (may be modified by firmware). */
1485                 sc->sc_vap_is_running = 0;
1486                 rsu_rxfilter_refresh(sc);
1487
1488                 /* Reinstall static keys. */
1489                 if (sc->sc_running)
1490                         rsu_reinit_static_keys(sc);
1491         } else
1492                 RSU_LOCK(sc);
1493         switch (nstate) {
1494         case IEEE80211_S_INIT:
1495                 (void) rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
1496                 break;
1497         case IEEE80211_S_AUTH:
1498                 ni = ieee80211_ref_node(vap->iv_bss);
1499                 (void) rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
1500                 error = rsu_join_bss(sc, ni);
1501                 ieee80211_free_node(ni);
1502                 if (error != 0) {
1503                         device_printf(sc->sc_dev,
1504                             "could not send join command\n");
1505                 }
1506                 break;
1507         case IEEE80211_S_RUN:
1508                 /* Flush all AC queues. */
1509                 rsu_write_1(sc, R92S_TXPAUSE, 0);
1510
1511                 ni = ieee80211_ref_node(vap->iv_bss);
1512                 rs = &ni->ni_rates;
1513                 /* Indicate highest supported rate. */
1514                 ni->ni_txrate = rs->rs_rates[rs->rs_nrates - 1];
1515                 (void) rsu_set_fw_power_state(sc, RSU_PWR_SLEEP);
1516                 ieee80211_free_node(ni);
1517                 startcal = 1;
1518                 break;
1519         default:
1520                 break;
1521         }
1522         if (startcal != 0) {
1523                 sc->sc_calibrating = 1;
1524                 /* Start periodic calibration. */
1525                 taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task,
1526                     hz);
1527         }
1528         RSU_UNLOCK(sc);
1529         IEEE80211_LOCK(ic);
1530         return (uvp->newstate(vap, nstate, arg));
1531 }
1532
1533 static int
1534 rsu_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,
1535     ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
1536 {
1537         struct rsu_softc *sc = vap->iv_ic->ic_softc;
1538         int is_checked = 0;
1539
1540         if (&vap->iv_nw_keys[0] <= k &&
1541             k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
1542                 *keyix = ieee80211_crypto_get_key_wepidx(vap, k);
1543         } else {
1544                 if (vap->iv_opmode != IEEE80211_M_STA) {
1545                         *keyix = 0;
1546                         /* TODO: obtain keyix from node id */
1547                         is_checked = 1;
1548                         k->wk_flags |= IEEE80211_KEY_SWCRYPT;
1549                 } else
1550                         *keyix = R92S_MACID_BSS;
1551         }
1552
1553         if (!is_checked) {
1554                 RSU_LOCK(sc);
1555                 if (isset(sc->keys_bmap, *keyix)) {
1556                         device_printf(sc->sc_dev,
1557                             "%s: key slot %d is already used!\n",
1558                             __func__, *keyix);
1559                         RSU_UNLOCK(sc);
1560                         return (0);
1561                 }
1562                 setbit(sc->keys_bmap, *keyix);
1563                 RSU_UNLOCK(sc);
1564         }
1565
1566         *rxkeyix = *keyix;
1567
1568         return (1);
1569 }
1570
1571 static int
1572 rsu_process_key(struct ieee80211vap *vap, const struct ieee80211_key *k,
1573     int set)
1574 {
1575         struct rsu_softc *sc = vap->iv_ic->ic_softc;
1576         int ret;
1577
1578         if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
1579                 /* Not for us. */
1580                 return (1);
1581         }
1582
1583         /* Handle group keys. */
1584         if (&vap->iv_nw_keys[0] <= k &&
1585             k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
1586                 KASSERT(k->wk_keyix < nitems(sc->group_keys),
1587                     ("keyix %u > %zu\n", k->wk_keyix, nitems(sc->group_keys)));
1588
1589                 RSU_LOCK(sc);
1590                 sc->group_keys[k->wk_keyix] = (set ? k : NULL);
1591                 if (!sc->sc_running) {
1592                         /* Static keys will be set during device startup. */
1593                         RSU_UNLOCK(sc);
1594                         return (1);
1595                 }
1596
1597                 if (set)
1598                         ret = rsu_set_key_group(sc, k);
1599                 else
1600                         ret = rsu_delete_key(sc, k->wk_keyix);
1601                 RSU_UNLOCK(sc);
1602
1603                 return (!ret);
1604         }
1605
1606         if (set) {
1607                 /* wait for pending key removal */
1608                 taskqueue_drain(taskqueue_thread, &sc->del_key_task);
1609
1610                 RSU_LOCK(sc);
1611                 ret = rsu_set_key_pair(sc, k);
1612                 RSU_UNLOCK(sc);
1613         } else {
1614                 RSU_DELKEY_BMAP_LOCK(sc);
1615                 setbit(sc->free_keys_bmap, k->wk_keyix);
1616                 RSU_DELKEY_BMAP_UNLOCK(sc);
1617
1618                 /* workaround ieee80211_node_delucastkey() locking */
1619                 taskqueue_enqueue(taskqueue_thread, &sc->del_key_task);
1620                 ret = 0;        /* fake success */
1621         }
1622
1623         return (!ret);
1624 }
1625
1626 static int
1627 rsu_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k)
1628 {
1629         return (rsu_process_key(vap, k, 1));
1630 }
1631
1632 static int
1633 rsu_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
1634 {
1635         return (rsu_process_key(vap, k, 0));
1636 }
1637
1638 static int
1639 rsu_cam_read(struct rsu_softc *sc, uint8_t addr, uint32_t *val)
1640 {
1641         int ntries;
1642
1643         rsu_write_4(sc, R92S_CAMCMD,
1644             R92S_CAMCMD_POLLING | SM(R92S_CAMCMD_ADDR, addr));
1645         for (ntries = 0; ntries < 10; ntries++) {
1646                 if (!(rsu_read_4(sc, R92S_CAMCMD) & R92S_CAMCMD_POLLING))
1647                         break;
1648
1649                 usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(1));
1650         }
1651         if (ntries == 10) {
1652                 device_printf(sc->sc_dev,
1653                     "%s: cannot read CAM entry at address %02X\n",
1654                     __func__, addr);
1655                 return (ETIMEDOUT);
1656         }
1657
1658         *val = rsu_read_4(sc, R92S_CAMREAD);
1659
1660         return (0);
1661 }
1662
1663 static void
1664 rsu_cam_write(struct rsu_softc *sc, uint8_t addr, uint32_t data)
1665 {
1666
1667         rsu_write_4(sc, R92S_CAMWRITE, data);
1668         rsu_write_4(sc, R92S_CAMCMD,
1669             R92S_CAMCMD_POLLING | R92S_CAMCMD_WRITE |
1670             SM(R92S_CAMCMD_ADDR, addr));
1671 }
1672
1673 static int
1674 rsu_key_check(struct rsu_softc *sc, ieee80211_keyix keyix, int is_valid)
1675 {
1676         uint32_t val;
1677         int error, ntries;
1678
1679         for (ntries = 0; ntries < 20; ntries++) {
1680                 usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(1));
1681
1682                 error = rsu_cam_read(sc, R92S_CAM_CTL0(keyix), &val);
1683                 if (error != 0) {
1684                         device_printf(sc->sc_dev,
1685                             "%s: cannot check key status!\n", __func__);
1686                         return (error);
1687                 }
1688                 if (((val & R92S_CAM_VALID) == 0) ^ is_valid)
1689                         break;
1690         }
1691         if (ntries == 20) {
1692                 device_printf(sc->sc_dev,
1693                     "%s: key %d is %s marked as valid, rejecting request\n",
1694                     __func__, keyix, is_valid ? "not" : "still");
1695                 return (EIO);
1696         }
1697
1698         return (0);
1699 }
1700
1701 /*
1702  * Map net80211 cipher to RTL8712 security mode.
1703  */
1704 static uint8_t
1705 rsu_crypto_mode(struct rsu_softc *sc, u_int cipher, int keylen)
1706 {
1707         switch (cipher) {
1708         case IEEE80211_CIPHER_WEP:
1709                 return keylen < 8 ? R92S_KEY_ALGO_WEP40 : R92S_KEY_ALGO_WEP104;
1710         case IEEE80211_CIPHER_TKIP:
1711                 return R92S_KEY_ALGO_TKIP;
1712         case IEEE80211_CIPHER_AES_CCM:
1713                 return R92S_KEY_ALGO_AES;
1714         default:
1715                 device_printf(sc->sc_dev, "unknown cipher %d\n", cipher);
1716                 return R92S_KEY_ALGO_INVALID;
1717         }
1718 }
1719
1720 static int
1721 rsu_set_key_group(struct rsu_softc *sc, const struct ieee80211_key *k)
1722 {
1723         struct r92s_fw_cmd_set_key key;
1724         uint8_t algo;
1725         int error;
1726
1727         RSU_ASSERT_LOCKED(sc);
1728
1729         /* Map net80211 cipher to HW crypto algorithm. */
1730         algo = rsu_crypto_mode(sc, k->wk_cipher->ic_cipher, k->wk_keylen);
1731         if (algo == R92S_KEY_ALGO_INVALID)
1732                 return (EINVAL);
1733
1734         memset(&key, 0, sizeof(key));
1735         key.algo = algo;
1736         key.cam_id = k->wk_keyix;
1737         key.grpkey = (k->wk_flags & IEEE80211_KEY_GROUP) != 0;
1738         memcpy(key.key, k->wk_key, MIN(k->wk_keylen, sizeof(key.key)));
1739
1740         RSU_DPRINTF(sc, RSU_DEBUG_KEY | RSU_DEBUG_FWCMD,
1741             "%s: keyix %u, group %u, algo %u/%u, flags %04X, len %u, "
1742             "macaddr %s\n", __func__, key.cam_id, key.grpkey,
1743             k->wk_cipher->ic_cipher, key.algo, k->wk_flags, k->wk_keylen,
1744             ether_sprintf(k->wk_macaddr));
1745
1746         error = rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
1747         if (error != 0) {
1748                 device_printf(sc->sc_dev,
1749                     "%s: cannot send firmware command, error %d\n",
1750                     __func__, error);
1751                 return (error);
1752         }
1753
1754         return (rsu_key_check(sc, k->wk_keyix, 1));
1755 }
1756
1757 static int
1758 rsu_set_key_pair(struct rsu_softc *sc, const struct ieee80211_key *k)
1759 {
1760         struct r92s_fw_cmd_set_key_mac key;
1761         uint8_t algo;
1762         int error;
1763
1764         RSU_ASSERT_LOCKED(sc);
1765
1766         if (!sc->sc_running)
1767                 return (ESHUTDOWN);
1768
1769         /* Map net80211 cipher to HW crypto algorithm. */
1770         algo = rsu_crypto_mode(sc, k->wk_cipher->ic_cipher, k->wk_keylen);
1771         if (algo == R92S_KEY_ALGO_INVALID)
1772                 return (EINVAL);
1773
1774         memset(&key, 0, sizeof(key));
1775         key.algo = algo;
1776         memcpy(key.macaddr, k->wk_macaddr, sizeof(key.macaddr));
1777         memcpy(key.key, k->wk_key, MIN(k->wk_keylen, sizeof(key.key)));
1778
1779         RSU_DPRINTF(sc, RSU_DEBUG_KEY | RSU_DEBUG_FWCMD,
1780             "%s: keyix %u, algo %u/%u, flags %04X, len %u, macaddr %s\n",
1781             __func__, k->wk_keyix, k->wk_cipher->ic_cipher, key.algo,
1782             k->wk_flags, k->wk_keylen, ether_sprintf(key.macaddr));
1783
1784         error = rsu_fw_cmd(sc, R92S_CMD_SET_STA_KEY, &key, sizeof(key));
1785         if (error != 0) {
1786                 device_printf(sc->sc_dev,
1787                     "%s: cannot send firmware command, error %d\n",
1788                     __func__, error);
1789                 return (error);
1790         }
1791
1792         return (rsu_key_check(sc, k->wk_keyix, 1));
1793 }
1794
1795 static int
1796 rsu_reinit_static_keys(struct rsu_softc *sc)
1797 {
1798         int i, error;
1799
1800         for (i = 0; i < nitems(sc->group_keys); i++) {
1801                 if (sc->group_keys[i] != NULL) {
1802                         error = rsu_set_key_group(sc, sc->group_keys[i]);
1803                         if (error != 0) {
1804                                 device_printf(sc->sc_dev,
1805                                     "%s: failed to set static key %d, "
1806                                     "error %d\n", __func__, i, error);
1807                                 return (error);
1808                         }
1809                 }
1810         }
1811
1812         return (0);
1813 }
1814
1815 static int
1816 rsu_delete_key(struct rsu_softc *sc, ieee80211_keyix keyix)
1817 {
1818         struct r92s_fw_cmd_set_key key;
1819         uint32_t val;
1820         int error;
1821
1822         RSU_ASSERT_LOCKED(sc);
1823
1824         if (!sc->sc_running)
1825                 return (0);
1826
1827         /* check if it was automatically removed by firmware */
1828         error = rsu_cam_read(sc, R92S_CAM_CTL0(keyix), &val);
1829         if (error == 0 && (val & R92S_CAM_VALID) == 0) {
1830                 RSU_DPRINTF(sc, RSU_DEBUG_KEY,
1831                     "%s: key %u does not exist\n", __func__, keyix);
1832                 clrbit(sc->keys_bmap, keyix);
1833                 return (0);
1834         }
1835
1836         memset(&key, 0, sizeof(key));
1837         key.cam_id = keyix;
1838
1839         RSU_DPRINTF(sc, RSU_DEBUG_KEY | RSU_DEBUG_FWCMD,
1840             "%s: removing key %u\n", __func__, key.cam_id);
1841
1842         error = rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
1843         if (error != 0) {
1844                 device_printf(sc->sc_dev,
1845                     "%s: cannot send firmware command, error %d\n",
1846                     __func__, error);
1847                 goto finish;
1848         }
1849
1850         usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(5));
1851
1852         /*
1853          * Clear 'valid' bit manually (cannot be done via firmware command).
1854          * Used for key check + when firmware command cannot be sent.
1855          */
1856 finish:
1857         rsu_cam_write(sc, R92S_CAM_CTL0(keyix), 0);
1858
1859         clrbit(sc->keys_bmap, keyix);
1860
1861         return (rsu_key_check(sc, keyix, 0));
1862 }
1863
1864 static void
1865 rsu_delete_key_pair_cb(void *arg, int pending __unused)
1866 {
1867         struct rsu_softc *sc = arg;
1868         int i;
1869
1870         RSU_DELKEY_BMAP_LOCK(sc);
1871         for (i = IEEE80211_WEP_NKID; i < R92S_CAM_ENTRY_LIMIT; i++) {
1872                 if (isset(sc->free_keys_bmap, i)) {
1873                         RSU_DELKEY_BMAP_UNLOCK(sc);
1874
1875                         RSU_LOCK(sc);
1876                         RSU_DPRINTF(sc, RSU_DEBUG_KEY,
1877                             "%s: calling rsu_delete_key() with keyix = %d\n",
1878                             __func__, i);
1879                         (void) rsu_delete_key(sc, i);
1880                         RSU_UNLOCK(sc);
1881
1882                         RSU_DELKEY_BMAP_LOCK(sc);
1883                         clrbit(sc->free_keys_bmap, i);
1884
1885                         /* bmap can be changed */
1886                         i = IEEE80211_WEP_NKID - 1;
1887                         continue;
1888                 }
1889         }
1890         RSU_DELKEY_BMAP_UNLOCK(sc);
1891 }
1892
1893 static int
1894 rsu_site_survey(struct rsu_softc *sc, struct ieee80211_scan_ssid *ssid)
1895 {
1896         struct r92s_fw_cmd_sitesurvey cmd;
1897
1898         RSU_ASSERT_LOCKED(sc);
1899
1900         memset(&cmd, 0, sizeof(cmd));
1901         /* TODO: passive channels? */
1902         if (sc->sc_active_scan)
1903                 cmd.active = htole32(1);
1904         cmd.limit = htole32(48);
1905         
1906         if (ssid != NULL) {
1907                 sc->sc_extra_scan = 1;
1908                 cmd.ssidlen = htole32(ssid->len);
1909                 memcpy(cmd.ssid, ssid->ssid, ssid->len);
1910         }
1911 #ifdef USB_DEBUG
1912         if (rsu_debug & (RSU_DEBUG_SCAN | RSU_DEBUG_FWCMD)) {
1913                 device_printf(sc->sc_dev,
1914                     "sending site survey command, active %d",
1915                     le32toh(cmd.active));
1916                 if (ssid != NULL) {
1917                         printf(", ssid: ");
1918                         ieee80211_print_essid(cmd.ssid, le32toh(cmd.ssidlen));
1919                 }
1920                 printf("\n");
1921         }
1922 #endif
1923         return (rsu_fw_cmd(sc, R92S_CMD_SITE_SURVEY, &cmd, sizeof(cmd)));
1924 }
1925
1926 static int
1927 rsu_join_bss(struct rsu_softc *sc, struct ieee80211_node *ni)
1928 {
1929         struct ieee80211com *ic = &sc->sc_ic;
1930         struct ieee80211vap *vap = ni->ni_vap;
1931         struct ndis_wlan_bssid_ex *bss;
1932         struct ndis_802_11_fixed_ies *fixed;
1933         struct r92s_fw_cmd_auth auth;
1934         uint8_t buf[sizeof(*bss) + 128] __aligned(4);
1935         uint8_t *frm;
1936         uint8_t opmode;
1937         int error;
1938
1939         RSU_ASSERT_LOCKED(sc);
1940
1941         /* Let the FW decide the opmode based on the capinfo field. */
1942         opmode = NDIS802_11AUTOUNKNOWN;
1943         RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1944             "%s: setting operating mode to %d\n",
1945             __func__, opmode);
1946         error = rsu_fw_cmd(sc, R92S_CMD_SET_OPMODE, &opmode, sizeof(opmode));
1947         if (error != 0)
1948                 return (error);
1949
1950         memset(&auth, 0, sizeof(auth));
1951         if (vap->iv_flags & IEEE80211_F_WPA) {
1952                 auth.mode = R92S_AUTHMODE_WPA;
1953                 auth.dot1x = (ni->ni_authmode == IEEE80211_AUTH_8021X);
1954         } else
1955                 auth.mode = R92S_AUTHMODE_OPEN;
1956         RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1957             "%s: setting auth mode to %d\n",
1958             __func__, auth.mode);
1959         error = rsu_fw_cmd(sc, R92S_CMD_SET_AUTH, &auth, sizeof(auth));
1960         if (error != 0)
1961                 return (error);
1962
1963         memset(buf, 0, sizeof(buf));
1964         bss = (struct ndis_wlan_bssid_ex *)buf;
1965         IEEE80211_ADDR_COPY(bss->macaddr, ni->ni_bssid);
1966         bss->ssid.ssidlen = htole32(ni->ni_esslen);
1967         memcpy(bss->ssid.ssid, ni->ni_essid, ni->ni_esslen);
1968         if (vap->iv_flags & (IEEE80211_F_PRIVACY | IEEE80211_F_WPA))
1969                 bss->privacy = htole32(1);
1970         bss->rssi = htole32(ni->ni_avgrssi);
1971         if (ic->ic_curmode == IEEE80211_MODE_11B)
1972                 bss->networktype = htole32(NDIS802_11DS);
1973         else
1974                 bss->networktype = htole32(NDIS802_11OFDM24);
1975         bss->config.len = htole32(sizeof(bss->config));
1976         bss->config.bintval = htole32(ni->ni_intval);
1977         bss->config.dsconfig = htole32(ieee80211_chan2ieee(ic, ni->ni_chan));
1978         bss->inframode = htole32(NDIS802_11INFRASTRUCTURE);
1979         /* XXX verify how this is supposed to look! */
1980         memcpy(bss->supprates, ni->ni_rates.rs_rates,
1981             ni->ni_rates.rs_nrates);
1982         /* Write the fixed fields of the beacon frame. */
1983         fixed = (struct ndis_802_11_fixed_ies *)&bss[1];
1984         memcpy(&fixed->tstamp, ni->ni_tstamp.data, 8);
1985         fixed->bintval = htole16(ni->ni_intval);
1986         fixed->capabilities = htole16(ni->ni_capinfo);
1987         /* Write IEs to be included in the association request. */
1988         frm = (uint8_t *)&fixed[1];
1989         frm = ieee80211_add_rsn(frm, vap);
1990         frm = ieee80211_add_wpa(frm, vap);
1991         frm = ieee80211_add_qos(frm, ni);
1992         if ((ic->ic_flags & IEEE80211_F_WME) &&
1993             (ni->ni_ies.wme_ie != NULL))
1994                 frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1995         if (ni->ni_flags & IEEE80211_NODE_HT) {
1996                 frm = ieee80211_add_htcap(frm, ni);
1997                 frm = ieee80211_add_htinfo(frm, ni);
1998         }
1999         bss->ieslen = htole32(frm - (uint8_t *)fixed);
2000         bss->len = htole32(((frm - buf) + 3) & ~3);
2001         RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_FWCMD,
2002             "%s: sending join bss command to %s chan %d\n",
2003             __func__,
2004             ether_sprintf(bss->macaddr), le32toh(bss->config.dsconfig));
2005         return (rsu_fw_cmd(sc, R92S_CMD_JOIN_BSS, buf, sizeof(buf)));
2006 }
2007
2008 static int
2009 rsu_disconnect(struct rsu_softc *sc)
2010 {
2011         uint32_t zero = 0;      /* :-) */
2012
2013         /* Disassociate from our current BSS. */
2014         RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
2015             "%s: sending disconnect command\n", __func__);
2016         return (rsu_fw_cmd(sc, R92S_CMD_DISCONNECT, &zero, sizeof(zero)));
2017 }
2018
2019 /*
2020  * Map the hardware provided RSSI value to a signal level.
2021  * For the most part it's just something we divide by and cap
2022  * so it doesn't overflow the representation by net80211.
2023  */
2024 static int
2025 rsu_hwrssi_to_rssi(struct rsu_softc *sc, int hw_rssi)
2026 {
2027         int v;
2028
2029         if (hw_rssi == 0)
2030                 return (0);
2031         v = hw_rssi >> 4;
2032         if (v > 80)
2033                 v = 80;
2034         return (v);
2035 }
2036
2037 CTASSERT(MCLBYTES > sizeof(struct ieee80211_frame));
2038
2039 static void
2040 rsu_event_survey(struct rsu_softc *sc, uint8_t *buf, int len)
2041 {
2042         struct ieee80211com *ic = &sc->sc_ic;
2043         struct ieee80211_frame *wh;
2044         struct ndis_wlan_bssid_ex *bss;
2045         struct ieee80211_rx_stats rxs;
2046         struct mbuf *m;
2047         uint32_t ieslen;
2048         uint32_t pktlen;
2049
2050         if (__predict_false(len < sizeof(*bss)))
2051                 return;
2052         bss = (struct ndis_wlan_bssid_ex *)buf;
2053         ieslen = le32toh(bss->ieslen);
2054         /* range check length of information element */
2055         if (__predict_false(ieslen > (uint32_t)(len - sizeof(*bss))))
2056                 return;
2057
2058         RSU_DPRINTF(sc, RSU_DEBUG_SCAN,
2059             "%s: found BSS %s: len=%d chan=%d inframode=%d "
2060             "networktype=%d privacy=%d, RSSI=%d\n",
2061             __func__,
2062             ether_sprintf(bss->macaddr), ieslen,
2063             le32toh(bss->config.dsconfig), le32toh(bss->inframode),
2064             le32toh(bss->networktype), le32toh(bss->privacy),
2065             le32toh(bss->rssi));
2066
2067         /* Build a fake beacon frame to let net80211 do all the parsing. */
2068         /* XXX TODO: just call the new scan API methods! */
2069         if (__predict_false(ieslen > (size_t)(MCLBYTES - sizeof(*wh))))
2070                 return;
2071         pktlen = sizeof(*wh) + ieslen;
2072         m = m_get2(pktlen, M_NOWAIT, MT_DATA, M_PKTHDR);
2073         if (__predict_false(m == NULL))
2074                 return;
2075         wh = mtod(m, struct ieee80211_frame *);
2076         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2077             IEEE80211_FC0_SUBTYPE_BEACON;
2078         wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2079         USETW(wh->i_dur, 0);
2080         IEEE80211_ADDR_COPY(wh->i_addr1, ieee80211broadcastaddr);
2081         IEEE80211_ADDR_COPY(wh->i_addr2, bss->macaddr);
2082         IEEE80211_ADDR_COPY(wh->i_addr3, bss->macaddr);
2083         *(uint16_t *)wh->i_seq = 0;
2084         memcpy(&wh[1], (uint8_t *)&bss[1], ieslen);
2085
2086         /* Finalize mbuf. */
2087         m->m_pkthdr.len = m->m_len = pktlen;
2088
2089         /* Set channel flags for input path */
2090         bzero(&rxs, sizeof(rxs));
2091         rxs.r_flags |= IEEE80211_R_IEEE | IEEE80211_R_FREQ;
2092         rxs.r_flags |= IEEE80211_R_NF | IEEE80211_R_RSSI;
2093         rxs.c_ieee = le32toh(bss->config.dsconfig);
2094         rxs.c_freq = ieee80211_ieee2mhz(rxs.c_ieee, IEEE80211_CHAN_2GHZ);
2095         /* This is a number from 0..100; so let's just divide it down a bit */
2096         rxs.c_rssi = le32toh(bss->rssi) / 2;
2097         rxs.c_nf = -96;
2098         if (ieee80211_add_rx_params(m, &rxs) == 0)
2099                 return;
2100
2101         /* XXX avoid a LOR */
2102         RSU_UNLOCK(sc);
2103         ieee80211_input_mimo_all(ic, m);
2104         RSU_LOCK(sc);
2105 }
2106
2107 static void
2108 rsu_event_join_bss(struct rsu_softc *sc, uint8_t *buf, int len)
2109 {
2110         struct ieee80211com *ic = &sc->sc_ic;
2111         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2112         struct ieee80211_node *ni = vap->iv_bss;
2113         struct r92s_event_join_bss *rsp;
2114         uint32_t tmp;
2115         int res;
2116
2117         if (__predict_false(len < sizeof(*rsp)))
2118                 return;
2119         rsp = (struct r92s_event_join_bss *)buf;
2120         res = (int)le32toh(rsp->join_res);
2121
2122         RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
2123             "%s: Rx join BSS event len=%d res=%d\n",
2124             __func__, len, res);
2125
2126         /*
2127          * XXX Don't do this; there's likely a better way to tell
2128          * the caller we failed.
2129          */
2130         if (res <= 0) {
2131                 RSU_UNLOCK(sc);
2132                 ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
2133                 RSU_LOCK(sc);
2134                 return;
2135         }
2136
2137         tmp = le32toh(rsp->associd);
2138         if (tmp >= vap->iv_max_aid) {
2139                 RSU_DPRINTF(sc, RSU_DEBUG_ANY, "Assoc ID overflow\n");
2140                 tmp = 1;
2141         }
2142         RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
2143             "%s: associated with %s associd=%d\n",
2144             __func__, ether_sprintf(rsp->bss.macaddr), tmp);
2145         /* XXX is this required? What's the top two bits for again? */
2146         ni->ni_associd = tmp | 0xc000;
2147
2148         /* Refresh Rx filter (was changed by firmware). */
2149         sc->sc_vap_is_running = 1;
2150         rsu_rxfilter_refresh(sc);
2151
2152         RSU_UNLOCK(sc);
2153         ieee80211_new_state(vap, IEEE80211_S_RUN,
2154             IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
2155         RSU_LOCK(sc);
2156 }
2157
2158 static void
2159 rsu_event_addba_req_report(struct rsu_softc *sc, uint8_t *buf, int len)
2160 {
2161         struct ieee80211com *ic = &sc->sc_ic;
2162         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2163         struct r92s_add_ba_event *ba = (void *) buf;
2164         struct ieee80211_node *ni;
2165
2166         if (len < sizeof(*ba)) {
2167                 device_printf(sc->sc_dev, "%s: short read (%d)\n", __func__, len);
2168                 return;
2169         }
2170
2171         if (vap == NULL)
2172                 return;
2173
2174         RSU_DPRINTF(sc, RSU_DEBUG_AMPDU, "%s: mac=%s, tid=%d, ssn=%d\n",
2175             __func__,
2176             ether_sprintf(ba->mac_addr),
2177             (int) ba->tid,
2178             (int) le16toh(ba->ssn));
2179
2180         /* XXX do node lookup; this is STA specific */
2181
2182         ni = ieee80211_ref_node(vap->iv_bss);
2183         ieee80211_ampdu_rx_start_ext(ni, ba->tid, le16toh(ba->ssn) >> 4, 32);
2184         ieee80211_free_node(ni);
2185 }
2186
2187 static void
2188 rsu_rx_event(struct rsu_softc *sc, uint8_t code, uint8_t *buf, int len)
2189 {
2190         struct ieee80211com *ic = &sc->sc_ic;
2191         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2192
2193         RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD,
2194             "%s: Rx event code=%d len=%d\n", __func__, code, len);
2195         switch (code) {
2196         case R92S_EVT_SURVEY:
2197                 rsu_event_survey(sc, buf, len);
2198                 break;
2199         case R92S_EVT_SURVEY_DONE:
2200                 RSU_DPRINTF(sc, RSU_DEBUG_SCAN,
2201                     "%s: %s scan done, found %d BSS\n",
2202                     __func__, sc->sc_extra_scan ? "direct" : "broadcast",
2203                     le32toh(*(uint32_t *)buf));
2204                 if (sc->sc_extra_scan == 1) {
2205                         /* Send broadcast probe request. */
2206                         sc->sc_extra_scan = 0;
2207                         if (vap != NULL && rsu_site_survey(sc, NULL) != 0) {
2208                                 RSU_UNLOCK(sc);
2209                                 ieee80211_cancel_scan(vap);
2210                                 RSU_LOCK(sc);
2211                         }
2212                         break;
2213                 }
2214                 if (vap != NULL) {
2215                         RSU_UNLOCK(sc);
2216                         ieee80211_scan_done(vap);
2217                         RSU_LOCK(sc);
2218                 }
2219                 break;
2220         case R92S_EVT_JOIN_BSS:
2221                 if (vap->iv_state == IEEE80211_S_AUTH)
2222                         rsu_event_join_bss(sc, buf, len);
2223                 break;
2224         case R92S_EVT_DEL_STA:
2225                 RSU_DPRINTF(sc, RSU_DEBUG_FWCMD | RSU_DEBUG_STATE,
2226                     "%s: disassociated from %s\n", __func__,
2227                     ether_sprintf(buf));
2228                 if (vap->iv_state == IEEE80211_S_RUN &&
2229                     IEEE80211_ADDR_EQ(vap->iv_bss->ni_bssid, buf)) {
2230                         RSU_UNLOCK(sc);
2231                         ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
2232                         RSU_LOCK(sc);
2233                 }
2234                 break;
2235         case R92S_EVT_WPS_PBC:
2236                 RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD,
2237                     "%s: WPS PBC pushed.\n", __func__);
2238                 break;
2239         case R92S_EVT_FWDBG:
2240                 buf[60] = '\0';
2241                 RSU_DPRINTF(sc, RSU_DEBUG_FWDBG, "FWDBG: %s\n", (char *)buf);
2242                 break;
2243         case R92S_EVT_ADDBA_REQ_REPORT:
2244                 rsu_event_addba_req_report(sc, buf, len);
2245                 break;
2246         default:
2247                 device_printf(sc->sc_dev, "%s: unhandled code (%d)\n", __func__, code);
2248                 break;
2249         }
2250 }
2251
2252 static void
2253 rsu_rx_multi_event(struct rsu_softc *sc, uint8_t *buf, int len)
2254 {
2255         struct r92s_fw_cmd_hdr *cmd;
2256         int cmdsz;
2257
2258         RSU_DPRINTF(sc, RSU_DEBUG_RX, "%s: Rx events len=%d\n", __func__, len);
2259
2260         /* Skip Rx status. */
2261         buf += sizeof(struct r92s_rx_stat);
2262         len -= sizeof(struct r92s_rx_stat);
2263
2264         /* Process all events. */
2265         for (;;) {
2266                 /* Check that command header fits. */
2267                 if (__predict_false(len < sizeof(*cmd)))
2268                         break;
2269                 cmd = (struct r92s_fw_cmd_hdr *)buf;
2270                 /* Check that command payload fits. */
2271                 cmdsz = le16toh(cmd->len);
2272                 if (__predict_false(len < sizeof(*cmd) + cmdsz))
2273                         break;
2274
2275                 /* Process firmware event. */
2276                 rsu_rx_event(sc, cmd->code, (uint8_t *)&cmd[1], cmdsz);
2277
2278                 if (!(cmd->seq & R92S_FW_CMD_MORE))
2279                         break;
2280                 buf += sizeof(*cmd) + cmdsz;
2281                 len -= sizeof(*cmd) + cmdsz;
2282         }
2283 }
2284
2285 static int8_t
2286 rsu_get_rssi(struct rsu_softc *sc, int rate, void *physt)
2287 {
2288         static const int8_t cckoff[] = { 14, -2, -20, -40 };
2289         struct r92s_rx_phystat *phy;
2290         struct r92s_rx_cck *cck;
2291         uint8_t rpt;
2292         int8_t rssi;
2293
2294         if (rate <= 3) {
2295                 cck = (struct r92s_rx_cck *)physt;
2296                 rpt = (cck->agc_rpt >> 6) & 0x3;
2297                 rssi = cck->agc_rpt & 0x3e;
2298                 rssi = cckoff[rpt] - rssi;
2299         } else {        /* OFDM/HT. */
2300                 phy = (struct r92s_rx_phystat *)physt;
2301                 rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 106;
2302         }
2303         return (rssi);
2304 }
2305
2306 static struct mbuf *
2307 rsu_rx_copy_to_mbuf(struct rsu_softc *sc, struct r92s_rx_stat *stat,
2308     int totlen)
2309 {
2310         struct ieee80211com *ic = &sc->sc_ic;
2311         struct mbuf *m;
2312         uint32_t rxdw0;
2313         int pktlen;
2314
2315         rxdw0 = le32toh(stat->rxdw0);
2316         if (__predict_false(rxdw0 & (R92S_RXDW0_CRCERR | R92S_RXDW0_ICVERR))) {
2317                 RSU_DPRINTF(sc, RSU_DEBUG_RX,
2318                     "%s: RX flags error (%s)\n", __func__,
2319                     rxdw0 & R92S_RXDW0_CRCERR ? "CRC" : "ICV");
2320                 goto fail;
2321         }
2322
2323         pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN);
2324         if (__predict_false(pktlen < sizeof (struct ieee80211_frame_ack))) {
2325                 RSU_DPRINTF(sc, RSU_DEBUG_RX,
2326                     "%s: frame is too short: %d\n", __func__, pktlen);
2327                 goto fail;
2328         }
2329
2330         m = m_get2(totlen, M_NOWAIT, MT_DATA, M_PKTHDR);
2331         if (__predict_false(m == NULL)) {
2332                 device_printf(sc->sc_dev,
2333                     "%s: could not allocate RX mbuf, totlen %d\n",
2334                     __func__, totlen);
2335                 goto fail;
2336         }
2337
2338         /* Finalize mbuf. */
2339         memcpy(mtod(m, uint8_t *), (uint8_t *)stat, totlen);
2340         m->m_pkthdr.len = m->m_len = totlen;
2341  
2342         return (m);
2343 fail:
2344         counter_u64_add(ic->ic_ierrors, 1);
2345         return (NULL);
2346 }
2347
2348 static uint32_t
2349 rsu_get_tsf_low(struct rsu_softc *sc)
2350 {
2351         return (rsu_read_4(sc, R92S_TSFTR));
2352 }
2353
2354 static uint32_t
2355 rsu_get_tsf_high(struct rsu_softc *sc)
2356 {
2357         return (rsu_read_4(sc, R92S_TSFTR + 4));
2358 }
2359
2360 static struct ieee80211_node *
2361 rsu_rx_frame(struct rsu_softc *sc, struct mbuf *m)
2362 {
2363         struct ieee80211com *ic = &sc->sc_ic;
2364         struct ieee80211_frame_min *wh;
2365         struct ieee80211_rx_stats rxs;
2366         struct r92s_rx_stat *stat;
2367         uint32_t rxdw0, rxdw3;
2368         uint8_t cipher, rate;
2369         int infosz;
2370         int rssi;
2371
2372         stat = mtod(m, struct r92s_rx_stat *);
2373         rxdw0 = le32toh(stat->rxdw0);
2374         rxdw3 = le32toh(stat->rxdw3);
2375
2376         rate = MS(rxdw3, R92S_RXDW3_RATE);
2377         cipher = MS(rxdw0, R92S_RXDW0_CIPHER);
2378         infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
2379
2380         /* Get RSSI from PHY status descriptor if present. */
2381         if (infosz != 0 && (rxdw0 & R92S_RXDW0_PHYST))
2382                 rssi = rsu_get_rssi(sc, rate, &stat[1]);
2383         else {
2384                 /* Cheat and get the last calibrated RSSI */
2385                 rssi = rsu_hwrssi_to_rssi(sc, sc->sc_currssi);
2386         }
2387
2388         /* Hardware does Rx TCP checksum offload. */
2389         /*
2390          * This flag can be set for some other
2391          * (e.g., EAPOL) frame types, so don't rely on it.
2392          */
2393         if (rxdw3 & R92S_RXDW3_TCPCHKVALID) {
2394                 RSU_DPRINTF(sc, RSU_DEBUG_RX,
2395                     "%s: TCP/IP checksums: %schecked / %schecked\n",
2396                     __func__,
2397                     (rxdw3 & R92S_RXDW3_TCPCHKRPT) ? "" : "not ",
2398                     (rxdw3 & R92S_RXDW3_IPCHKRPT) ? "" : "not ");
2399
2400                 /*
2401                  * 'IP header checksum valid' bit will not be set if
2402                  * the frame was not checked / has incorrect checksum /
2403                  * does not have checksum (IPv6).
2404                  *
2405                  * NB: if DF bit is not set then frame will not be checked.
2406                  */
2407                 if (rxdw3 & R92S_RXDW3_IPCHKRPT) {
2408                         m->m_pkthdr.csum_flags = CSUM_IP_CHECKED;
2409                         m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
2410                 }
2411
2412                 /*
2413                  * This is independent of the above check.
2414                  */
2415                 if (rxdw3 & R92S_RXDW3_TCPCHKRPT) {
2416                         m->m_pkthdr.csum_flags |= CSUM_DATA_VALID;
2417                         m->m_pkthdr.csum_flags |= CSUM_PSEUDO_HDR;
2418                         m->m_pkthdr.csum_data = 0xffff;
2419                 }
2420         }
2421
2422         /* RX flags */
2423
2424         /* Set channel flags for input path */
2425         bzero(&rxs, sizeof(rxs));
2426
2427         /* normal RSSI */
2428         rxs.r_flags |= IEEE80211_R_NF | IEEE80211_R_RSSI;
2429         rxs.c_rssi = rssi;
2430         rxs.c_nf = -96;
2431
2432         /* Rate */
2433         if (rate < 12) {
2434                 rxs.c_rate = ridx2rate[rate];
2435                 if (RSU_RATE_IS_CCK(rate))
2436                         rxs.c_pktflags |= IEEE80211_RX_F_CCK;
2437                 else
2438                         rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2439         } else {
2440                 rxs.c_rate = IEEE80211_RATE_MCS | (rate - 12);
2441                 rxs.c_pktflags |= IEEE80211_RX_F_HT;
2442         }
2443
2444         if (ieee80211_radiotap_active(ic)) {
2445                 struct rsu_rx_radiotap_header *tap = &sc->sc_rxtap;
2446
2447                 /* Map HW rate index to 802.11 rate. */
2448                 tap->wr_flags = 0;              /* TODO */
2449                 tap->wr_tsft = rsu_get_tsf_high(sc);
2450                 if (le32toh(stat->tsf_low) > rsu_get_tsf_low(sc))
2451                         tap->wr_tsft--;
2452                 tap->wr_tsft = (uint64_t)htole32(tap->wr_tsft) << 32;
2453                 tap->wr_tsft += stat->tsf_low;
2454
2455                 tap->wr_rate = rxs.c_rate;
2456                 tap->wr_dbm_antsignal = rssi;
2457                 tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
2458                 tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
2459         };
2460
2461         (void) ieee80211_add_rx_params(m, &rxs);
2462
2463         /* Drop descriptor. */
2464         m_adj(m, sizeof(*stat) + infosz);
2465         wh = mtod(m, struct ieee80211_frame_min *);
2466         if ((wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
2467             cipher != R92S_KEY_ALGO_NONE) {
2468                 m->m_flags |= M_WEP;
2469         }
2470
2471         RSU_DPRINTF(sc, RSU_DEBUG_RX,
2472             "%s: Rx frame len %d, rate %d, infosz %d\n",
2473             __func__, m->m_len, rate, infosz);
2474
2475         if (m->m_len >= sizeof(*wh))
2476                 return (ieee80211_find_rxnode(ic, wh));
2477
2478         return (NULL);
2479 }
2480
2481 static struct mbuf *
2482 rsu_rx_multi_frame(struct rsu_softc *sc, uint8_t *buf, int len)
2483 {
2484         struct r92s_rx_stat *stat;
2485         uint32_t rxdw0;
2486         int totlen, pktlen, infosz, npkts;
2487         struct mbuf *m, *m0 = NULL, *prevm = NULL;
2488
2489         /*
2490          * don't pass packets to the ieee80211 framework if the driver isn't
2491          * RUNNING.
2492          */
2493         if (!sc->sc_running)
2494                 return (NULL);
2495
2496         /* Get the number of encapsulated frames. */
2497         stat = (struct r92s_rx_stat *)buf;
2498         npkts = MS(le32toh(stat->rxdw2), R92S_RXDW2_PKTCNT);
2499         RSU_DPRINTF(sc, RSU_DEBUG_RX,
2500             "%s: Rx %d frames in one chunk\n", __func__, npkts);
2501
2502         /* Process all of them. */
2503         while (npkts-- > 0) {
2504                 if (__predict_false(len < sizeof(*stat)))
2505                         break;
2506                 stat = (struct r92s_rx_stat *)buf;
2507                 rxdw0 = le32toh(stat->rxdw0);
2508
2509                 pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN);
2510                 if (__predict_false(pktlen == 0))
2511                         break;
2512
2513                 infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
2514
2515                 /* Make sure everything fits in xfer. */
2516                 totlen = sizeof(*stat) + infosz + pktlen;
2517                 if (__predict_false(totlen > len))
2518                         break;
2519
2520                 /* Process 802.11 frame. */
2521                 m = rsu_rx_copy_to_mbuf(sc, stat, totlen);
2522                 if (m0 == NULL)
2523                         m0 = m;
2524                 if (prevm == NULL)
2525                         prevm = m;
2526                 else {
2527                         prevm->m_next = m;
2528                         prevm = m;
2529                 }
2530                 /* Next chunk is 128-byte aligned. */
2531                 totlen = (totlen + 127) & ~127;
2532                 buf += totlen;
2533                 len -= totlen;
2534         }
2535
2536         return (m0);
2537 }
2538
2539 static struct mbuf *
2540 rsu_rxeof(struct usb_xfer *xfer, struct rsu_data *data)
2541 {
2542         struct rsu_softc *sc = data->sc;
2543         struct ieee80211com *ic = &sc->sc_ic;
2544         struct r92s_rx_stat *stat;
2545         int len;
2546
2547         usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
2548
2549         if (__predict_false(len < sizeof(*stat))) {
2550                 RSU_DPRINTF(sc, RSU_DEBUG_RX, "xfer too short %d\n", len);
2551                 counter_u64_add(ic->ic_ierrors, 1);
2552                 return (NULL);
2553         }
2554         /* Determine if it is a firmware C2H event or an 802.11 frame. */
2555         stat = (struct r92s_rx_stat *)data->buf;
2556         if ((le32toh(stat->rxdw1) & 0x1ff) == 0x1ff) {
2557                 rsu_rx_multi_event(sc, data->buf, len);
2558                 /* No packets to process. */
2559                 return (NULL);
2560         } else
2561                 return (rsu_rx_multi_frame(sc, data->buf, len));
2562 }
2563
2564 static void
2565 rsu_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
2566 {
2567         struct rsu_softc *sc = usbd_xfer_softc(xfer);
2568         struct ieee80211com *ic = &sc->sc_ic;
2569         struct ieee80211_node *ni;
2570         struct mbuf *m = NULL, *next;
2571         struct rsu_data *data;
2572
2573         RSU_ASSERT_LOCKED(sc);
2574
2575         switch (USB_GET_STATE(xfer)) {
2576         case USB_ST_TRANSFERRED:
2577                 data = STAILQ_FIRST(&sc->sc_rx_active);
2578                 if (data == NULL)
2579                         goto tr_setup;
2580                 STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
2581                 m = rsu_rxeof(xfer, data);
2582                 STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
2583                 /* FALLTHROUGH */
2584         case USB_ST_SETUP:
2585 tr_setup:
2586                 data = STAILQ_FIRST(&sc->sc_rx_inactive);
2587                 if (data == NULL) {
2588                         KASSERT(m == NULL, ("mbuf isn't NULL"));
2589                         return;
2590                 }
2591                 STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next);
2592                 STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next);
2593                 usbd_xfer_set_frame_data(xfer, 0, data->buf,
2594                     usbd_xfer_max_len(xfer));
2595                 usbd_transfer_submit(xfer);
2596                 /*
2597                  * To avoid LOR we should unlock our private mutex here to call
2598                  * ieee80211_input() because here is at the end of a USB
2599                  * callback and safe to unlock.
2600                  */
2601                 while (m != NULL) {
2602                         next = m->m_next;
2603                         m->m_next = NULL;
2604
2605                         ni = rsu_rx_frame(sc, m);
2606                         RSU_UNLOCK(sc);
2607
2608                         if (ni != NULL) {
2609                                 if (ni->ni_flags & IEEE80211_NODE_HT)
2610                                         m->m_flags |= M_AMPDU;
2611                                 (void)ieee80211_input_mimo(ni, m);
2612                                 ieee80211_free_node(ni);
2613                         } else
2614                                 (void)ieee80211_input_mimo_all(ic, m);
2615
2616                         RSU_LOCK(sc);
2617                         m = next;
2618                 }
2619                 break;
2620         default:
2621                 /* needs it to the inactive queue due to a error. */
2622                 data = STAILQ_FIRST(&sc->sc_rx_active);
2623                 if (data != NULL) {
2624                         STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
2625                         STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
2626                 }
2627                 if (error != USB_ERR_CANCELLED) {
2628                         usbd_xfer_set_stall(xfer);
2629                         counter_u64_add(ic->ic_ierrors, 1);
2630                         goto tr_setup;
2631                 }
2632                 break;
2633         }
2634
2635 }
2636
2637 static void
2638 rsu_txeof(struct usb_xfer *xfer, struct rsu_data *data)
2639 {
2640 #ifdef  USB_DEBUG
2641         struct rsu_softc *sc = usbd_xfer_softc(xfer);
2642 #endif
2643
2644         RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: called; data=%p\n",
2645             __func__,
2646             data);
2647
2648         if (data->m) {
2649                 /* XXX status? */
2650                 ieee80211_tx_complete(data->ni, data->m, 0);
2651                 data->m = NULL;
2652                 data->ni = NULL;
2653         }
2654 }
2655
2656 static void
2657 rsu_bulk_tx_callback_sub(struct usb_xfer *xfer, usb_error_t error,
2658     uint8_t which)
2659 {
2660         struct rsu_softc *sc = usbd_xfer_softc(xfer);
2661         struct ieee80211com *ic = &sc->sc_ic;
2662         struct rsu_data *data;
2663
2664         RSU_ASSERT_LOCKED(sc);
2665
2666         switch (USB_GET_STATE(xfer)) {
2667         case USB_ST_TRANSFERRED:
2668                 data = STAILQ_FIRST(&sc->sc_tx_active[which]);
2669                 if (data == NULL)
2670                         goto tr_setup;
2671                 RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: transfer done %p\n",
2672                     __func__, data);
2673                 STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
2674                 rsu_txeof(xfer, data);
2675                 rsu_freebuf(sc, data);
2676                 /* FALLTHROUGH */
2677         case USB_ST_SETUP:
2678 tr_setup:
2679                 data = STAILQ_FIRST(&sc->sc_tx_pending[which]);
2680                 if (data == NULL) {
2681                         RSU_DPRINTF(sc, RSU_DEBUG_TXDONE,
2682                             "%s: empty pending queue sc %p\n", __func__, sc);
2683                         return;
2684                 }
2685                 STAILQ_REMOVE_HEAD(&sc->sc_tx_pending[which], next);
2686                 STAILQ_INSERT_TAIL(&sc->sc_tx_active[which], data, next);
2687                 usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen);
2688                 RSU_DPRINTF(sc, RSU_DEBUG_TXDONE,
2689                     "%s: submitting transfer %p\n",
2690                     __func__,
2691                     data);
2692                 usbd_transfer_submit(xfer);
2693                 break;
2694         default:
2695                 data = STAILQ_FIRST(&sc->sc_tx_active[which]);
2696                 if (data != NULL) {
2697                         STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
2698                         rsu_txeof(xfer, data);
2699                         rsu_freebuf(sc, data);
2700                 }
2701                 counter_u64_add(ic->ic_oerrors, 1);
2702
2703                 if (error != USB_ERR_CANCELLED) {
2704                         usbd_xfer_set_stall(xfer);
2705                         goto tr_setup;
2706                 }
2707                 break;
2708         }
2709
2710         /*
2711          * XXX TODO: if the queue is low, flush out FF TX frames.
2712          * Remember to unlock the driver for now; net80211 doesn't
2713          * defer it for us.
2714          */
2715 }
2716
2717 static void
2718 rsu_bulk_tx_callback_be_bk(struct usb_xfer *xfer, usb_error_t error)
2719 {
2720         struct rsu_softc *sc = usbd_xfer_softc(xfer);
2721
2722         rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_BE_BK);
2723
2724         /* This kicks the TX taskqueue */
2725         rsu_start(sc);
2726 }
2727
2728 static void
2729 rsu_bulk_tx_callback_vi_vo(struct usb_xfer *xfer, usb_error_t error)
2730 {
2731         struct rsu_softc *sc = usbd_xfer_softc(xfer);
2732
2733         rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_VI_VO);
2734
2735         /* This kicks the TX taskqueue */
2736         rsu_start(sc);
2737 }
2738
2739 static void
2740 rsu_bulk_tx_callback_h2c(struct usb_xfer *xfer, usb_error_t error)
2741 {
2742         struct rsu_softc *sc = usbd_xfer_softc(xfer);
2743
2744         rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_H2C);
2745
2746         /* This kicks the TX taskqueue */
2747         rsu_start(sc);
2748 }
2749
2750 /*
2751  * Transmit the given frame.
2752  *
2753  * This doesn't free the node or mbuf upon failure.
2754  */
2755 static int
2756 rsu_tx_start(struct rsu_softc *sc, struct ieee80211_node *ni, 
2757     struct mbuf *m0, struct rsu_data *data)
2758 {
2759         struct ieee80211com *ic = &sc->sc_ic;
2760         struct ieee80211vap *vap = ni->ni_vap;
2761         struct ieee80211_frame *wh;
2762         struct ieee80211_key *k = NULL;
2763         struct r92s_tx_desc *txd;
2764         uint8_t type, cipher;
2765         int prio = 0;
2766         uint8_t which;
2767         int hasqos;
2768         int xferlen;
2769         int qid;
2770
2771         RSU_ASSERT_LOCKED(sc);
2772
2773         wh = mtod(m0, struct ieee80211_frame *);
2774         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2775
2776         RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: data=%p, m=%p\n",
2777             __func__, data, m0);
2778
2779         if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
2780                 k = ieee80211_crypto_encap(ni, m0);
2781                 if (k == NULL) {
2782                         device_printf(sc->sc_dev,
2783                             "ieee80211_crypto_encap returns NULL.\n");
2784                         /* XXX we don't expect the fragmented frames */
2785                         return (ENOBUFS);
2786                 }
2787                 wh = mtod(m0, struct ieee80211_frame *);
2788         }
2789         /* If we have QoS then use it */
2790         /* XXX TODO: mbuf WME/PRI versus TID? */
2791         if (IEEE80211_QOS_HAS_SEQ(wh)) {
2792                 /* Has QoS */
2793                 prio = M_WME_GETAC(m0);
2794                 which = rsu_wme_ac_xfer_map[prio];
2795                 hasqos = 1;
2796         } else {
2797                 /* Non-QoS TID */
2798                 /* XXX TODO: tid=0 for non-qos TID? */
2799                 which = rsu_wme_ac_xfer_map[WME_AC_BE];
2800                 hasqos = 0;
2801                 prio = 0;
2802         }
2803
2804         qid = rsu_ac2qid[prio];
2805 #if 0
2806         switch (type) {
2807         case IEEE80211_FC0_TYPE_CTL:
2808         case IEEE80211_FC0_TYPE_MGT:
2809                 which = rsu_wme_ac_xfer_map[WME_AC_VO];
2810                 break;
2811         default:
2812                 which = rsu_wme_ac_xfer_map[M_WME_GETAC(m0)];
2813                 break;
2814         }
2815         hasqos = 0;
2816 #endif
2817
2818         RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: pri=%d, which=%d, hasqos=%d\n",
2819             __func__,
2820             prio,
2821             which,
2822             hasqos);
2823
2824         /* Fill Tx descriptor. */
2825         txd = (struct r92s_tx_desc *)data->buf;
2826         memset(txd, 0, sizeof(*txd));
2827
2828         txd->txdw0 |= htole32(
2829             SM(R92S_TXDW0_PKTLEN, m0->m_pkthdr.len) |
2830             SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
2831             R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
2832
2833         txd->txdw1 |= htole32(
2834             SM(R92S_TXDW1_MACID, R92S_MACID_BSS) | SM(R92S_TXDW1_QSEL, qid));
2835         if (!hasqos)
2836                 txd->txdw1 |= htole32(R92S_TXDW1_NONQOS);
2837         if (k != NULL && !(k->wk_flags & IEEE80211_KEY_SWENCRYPT)) {
2838                 switch (k->wk_cipher->ic_cipher) {
2839                 case IEEE80211_CIPHER_WEP:
2840                         cipher = R92S_TXDW1_CIPHER_WEP;
2841                         break;
2842                 case IEEE80211_CIPHER_TKIP:
2843                         cipher = R92S_TXDW1_CIPHER_TKIP;
2844                         break;
2845                 case IEEE80211_CIPHER_AES_CCM:
2846                         cipher = R92S_TXDW1_CIPHER_AES;
2847                         break;
2848                 default:
2849                         cipher = R92S_TXDW1_CIPHER_NONE;
2850                 }
2851                 txd->txdw1 |= htole32(
2852                     SM(R92S_TXDW1_CIPHER, cipher) |
2853                     SM(R92S_TXDW1_KEYIDX, k->wk_keyix));
2854         }
2855         /* XXX todo: set AGGEN bit if appropriate? */
2856         txd->txdw2 |= htole32(R92S_TXDW2_BK);
2857         if (IEEE80211_IS_MULTICAST(wh->i_addr1))
2858                 txd->txdw2 |= htole32(R92S_TXDW2_BMCAST);
2859         /*
2860          * Firmware will use and increment the sequence number for the
2861          * specified priority.
2862          */
2863         txd->txdw3 |= htole32(SM(R92S_TXDW3_SEQ, prio));
2864
2865         if (ieee80211_radiotap_active_vap(vap)) {
2866                 struct rsu_tx_radiotap_header *tap = &sc->sc_txtap;
2867
2868                 tap->wt_flags = 0;
2869                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
2870                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
2871                 ieee80211_radiotap_tx(vap, m0);
2872         }
2873
2874         xferlen = sizeof(*txd) + m0->m_pkthdr.len;
2875         m_copydata(m0, 0, m0->m_pkthdr.len, (caddr_t)&txd[1]);
2876
2877         data->buflen = xferlen;
2878         data->ni = ni;
2879         data->m = m0;
2880         STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
2881
2882         /* start transfer, if any */
2883         usbd_transfer_start(sc->sc_xfer[which]);
2884         return (0);
2885 }
2886
2887 static int
2888 rsu_transmit(struct ieee80211com *ic, struct mbuf *m)   
2889 {
2890         struct rsu_softc *sc = ic->ic_softc;
2891         int error;
2892
2893         RSU_LOCK(sc);
2894         if (!sc->sc_running) {
2895                 RSU_UNLOCK(sc);
2896                 return (ENXIO);
2897         }
2898
2899         /*
2900          * XXX TODO: ensure that we treat 'm' as a list of frames
2901          * to transmit!
2902          */
2903         error = mbufq_enqueue(&sc->sc_snd, m);
2904         if (error) {
2905                 RSU_DPRINTF(sc, RSU_DEBUG_TX,
2906                     "%s: mbufq_enable: failed (%d)\n",
2907                     __func__,
2908                     error);
2909                 RSU_UNLOCK(sc);
2910                 return (error);
2911         }
2912         RSU_UNLOCK(sc);
2913
2914         /* This kicks the TX taskqueue */
2915         rsu_start(sc);
2916
2917         return (0);
2918 }
2919
2920 static void
2921 rsu_drain_mbufq(struct rsu_softc *sc)
2922 {
2923         struct mbuf *m;
2924         struct ieee80211_node *ni;
2925
2926         RSU_ASSERT_LOCKED(sc);
2927         while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
2928                 ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
2929                 m->m_pkthdr.rcvif = NULL;
2930                 ieee80211_free_node(ni);
2931                 m_freem(m);
2932         }
2933 }
2934
2935 static void
2936 _rsu_start(struct rsu_softc *sc)
2937 {
2938         struct ieee80211_node *ni;
2939         struct rsu_data *bf;
2940         struct mbuf *m;
2941
2942         RSU_ASSERT_LOCKED(sc);
2943
2944         while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
2945                 bf = rsu_getbuf(sc);
2946                 if (bf == NULL) {
2947                         RSU_DPRINTF(sc, RSU_DEBUG_TX,
2948                             "%s: failed to get buffer\n", __func__);
2949                         mbufq_prepend(&sc->sc_snd, m);
2950                         break;
2951                 }
2952
2953                 ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
2954                 m->m_pkthdr.rcvif = NULL;
2955
2956                 if (rsu_tx_start(sc, ni, m, bf) != 0) {
2957                         RSU_DPRINTF(sc, RSU_DEBUG_TX,
2958                             "%s: failed to transmit\n", __func__);
2959                         if_inc_counter(ni->ni_vap->iv_ifp,
2960                             IFCOUNTER_OERRORS, 1);
2961                         rsu_freebuf(sc, bf);
2962                         ieee80211_free_node(ni);
2963                         m_freem(m);
2964                         break;
2965                 }
2966         }
2967 }
2968
2969 static void
2970 rsu_start(struct rsu_softc *sc)
2971 {
2972
2973         taskqueue_enqueue(taskqueue_thread, &sc->tx_task);
2974 }
2975
2976 static int
2977 rsu_ioctl_net(struct ieee80211com *ic, u_long cmd, void *data)
2978 {
2979         struct rsu_softc *sc = ic->ic_softc;
2980         struct ifreq *ifr = (struct ifreq *)data;
2981         int error;
2982
2983         error = 0;
2984         switch (cmd) {
2985         case SIOCSIFCAP:
2986         {
2987                 struct ieee80211vap *vap;
2988                 int rxmask;
2989
2990                 rxmask = ifr->ifr_reqcap & (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6);
2991
2992                 RSU_LOCK(sc);
2993                 /* Both RXCSUM bits must be set (or unset). */
2994                 if (sc->sc_rx_checksum_enable &&
2995                     rxmask != (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6)) {
2996                         rxmask = 0;
2997                         sc->sc_rx_checksum_enable = 0;
2998                         rsu_rxfilter_set(sc, R92S_RCR_TCP_OFFLD_EN, 0);
2999                 } else if (!sc->sc_rx_checksum_enable && rxmask != 0) {
3000                         rxmask = IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6;
3001                         sc->sc_rx_checksum_enable = 1;
3002                         rsu_rxfilter_set(sc, 0, R92S_RCR_TCP_OFFLD_EN);
3003                 } else {
3004                         /* Nothing to do. */
3005                         RSU_UNLOCK(sc);
3006                         break;
3007                 }
3008                 RSU_UNLOCK(sc);
3009
3010                 IEEE80211_LOCK(ic);     /* XXX */
3011                 TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
3012                         struct ifnet *ifp = vap->iv_ifp;
3013
3014                         ifp->if_capenable &=
3015                             ~(IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6);
3016                         ifp->if_capenable |= rxmask;
3017                 }
3018                 IEEE80211_UNLOCK(ic);
3019                 break;
3020         }
3021         default:
3022                 error = ENOTTY;         /* for net80211 */
3023                 break;
3024         }
3025
3026         return (error);
3027 }
3028
3029 static void
3030 rsu_parent(struct ieee80211com *ic)
3031 {
3032         struct rsu_softc *sc = ic->ic_softc;
3033
3034         if (ic->ic_nrunning > 0) {
3035                 if (rsu_init(sc) == 0)
3036                         ieee80211_start_all(ic);
3037                 else {
3038                         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3039                         if (vap != NULL)
3040                                 ieee80211_stop(vap);
3041                 }
3042         } else
3043                 rsu_stop(sc);
3044 }
3045
3046 /*
3047  * Power on sequence for A-cut adapters.
3048  */
3049 static void
3050 rsu_power_on_acut(struct rsu_softc *sc)
3051 {
3052         uint32_t reg;
3053
3054         rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
3055         rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
3056
3057         /* Enable AFE macro block's bandgap and Mbias. */
3058         rsu_write_1(sc, R92S_AFE_MISC,
3059             rsu_read_1(sc, R92S_AFE_MISC) |
3060             R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN);
3061         /* Enable LDOA15 block. */
3062         rsu_write_1(sc, R92S_LDOA15_CTRL,
3063             rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
3064
3065         rsu_write_1(sc, R92S_SPS1_CTRL,
3066             rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_LDEN);
3067         rsu_ms_delay(sc, 2000);
3068         /* Enable switch regulator block. */
3069         rsu_write_1(sc, R92S_SPS1_CTRL,
3070             rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_SWEN);
3071
3072         rsu_write_4(sc, R92S_SPS1_CTRL, 0x00a7b267);
3073
3074         rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3075             rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
3076
3077         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3078             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
3079
3080         rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3081             rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x90);
3082
3083         /* Enable AFE clock. */
3084         rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
3085             rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
3086         /* Enable AFE PLL macro block. */
3087         rsu_write_1(sc, R92S_AFE_PLL_CTRL,
3088             rsu_read_1(sc, R92S_AFE_PLL_CTRL) | 0x11);
3089         /* Attach AFE PLL to MACTOP/BB. */
3090         rsu_write_1(sc, R92S_SYS_ISO_CTRL,
3091             rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
3092
3093         /* Switch to 40MHz clock instead of 80MHz. */
3094         rsu_write_2(sc, R92S_SYS_CLKR,
3095             rsu_read_2(sc, R92S_SYS_CLKR) & ~R92S_SYS_CLKSEL);
3096
3097         /* Enable MAC clock. */
3098         rsu_write_2(sc, R92S_SYS_CLKR,
3099             rsu_read_2(sc, R92S_SYS_CLKR) |
3100             R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
3101
3102         rsu_write_1(sc, R92S_PMC_FSM, 0x02);
3103
3104         /* Enable digital core and IOREG R/W. */
3105         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3106             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
3107
3108         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3109             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
3110
3111         /* Switch the control path to firmware. */
3112         reg = rsu_read_2(sc, R92S_SYS_CLKR);
3113         reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
3114         rsu_write_2(sc, R92S_SYS_CLKR, reg);
3115
3116         rsu_write_2(sc, R92S_CR, 0x37fc);
3117
3118         /* Fix USB RX FIFO issue. */
3119         rsu_write_1(sc, 0xfe5c,
3120             rsu_read_1(sc, 0xfe5c) | 0x80);
3121         rsu_write_1(sc, 0x00ab,
3122             rsu_read_1(sc, 0x00ab) | 0xc0);
3123
3124         rsu_write_1(sc, R92S_SYS_CLKR,
3125             rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
3126 }
3127
3128 /*
3129  * Power on sequence for B-cut and C-cut adapters.
3130  */
3131 static void
3132 rsu_power_on_bcut(struct rsu_softc *sc)
3133 {
3134         uint32_t reg;
3135         int ntries;
3136
3137         /* Prevent eFuse leakage. */
3138         rsu_write_1(sc, 0x37, 0xb0);
3139         rsu_ms_delay(sc, 10);
3140         rsu_write_1(sc, 0x37, 0x30);
3141
3142         /* Switch the control path to hardware. */
3143         reg = rsu_read_2(sc, R92S_SYS_CLKR);
3144         if (reg & R92S_FWHW_SEL) {
3145                 rsu_write_2(sc, R92S_SYS_CLKR,
3146                     reg & ~(R92S_SWHW_SEL | R92S_FWHW_SEL));
3147         }
3148         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3149             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) & ~0x8c);
3150         rsu_ms_delay(sc, 1);
3151
3152         rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
3153         rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
3154
3155         reg = rsu_read_1(sc, R92S_AFE_MISC);
3156         rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN);
3157         rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN |
3158             R92S_AFE_MISC_MBEN | R92S_AFE_MISC_I32_EN);
3159
3160         /* Enable PLL. */
3161         rsu_write_1(sc, R92S_LDOA15_CTRL,
3162             rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
3163
3164         rsu_write_1(sc, R92S_LDOV12D_CTRL,
3165             rsu_read_1(sc, R92S_LDOV12D_CTRL) | R92S_LDV12_EN);
3166
3167         rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3168             rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
3169
3170         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3171             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
3172
3173         /* Support 64KB IMEM. */
3174         rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3175             rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x97);
3176
3177         /* Enable AFE clock. */
3178         rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
3179             rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
3180         /* Enable AFE PLL macro block. */
3181         reg = rsu_read_1(sc, R92S_AFE_PLL_CTRL);
3182         rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
3183         rsu_ms_delay(sc, 1);
3184         rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x51);
3185         rsu_ms_delay(sc, 1);
3186         rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
3187         rsu_ms_delay(sc, 1);
3188
3189         /* Attach AFE PLL to MACTOP/BB. */
3190         rsu_write_1(sc, R92S_SYS_ISO_CTRL,
3191             rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
3192
3193         /* Switch to 40MHz clock. */
3194         rsu_write_1(sc, R92S_SYS_CLKR, 0x00);
3195         /* Disable CPU clock and 80MHz SSC. */
3196         rsu_write_1(sc, R92S_SYS_CLKR,
3197             rsu_read_1(sc, R92S_SYS_CLKR) | 0xa0);
3198         /* Enable MAC clock. */
3199         rsu_write_2(sc, R92S_SYS_CLKR,
3200             rsu_read_2(sc, R92S_SYS_CLKR) |
3201             R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
3202
3203         rsu_write_1(sc, R92S_PMC_FSM, 0x02);
3204
3205         /* Enable digital core and IOREG R/W. */
3206         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3207             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
3208
3209         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3210             rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
3211
3212         /* Switch the control path to firmware. */
3213         reg = rsu_read_2(sc, R92S_SYS_CLKR);
3214         reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
3215         rsu_write_2(sc, R92S_SYS_CLKR, reg);
3216
3217         rsu_write_2(sc, R92S_CR, 0x37fc);
3218
3219         /* Fix USB RX FIFO issue. */
3220         rsu_write_1(sc, 0xfe5c,
3221             rsu_read_1(sc, 0xfe5c) | 0x80);
3222
3223         rsu_write_1(sc, R92S_SYS_CLKR,
3224             rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
3225
3226         rsu_write_1(sc, 0xfe1c, 0x80);
3227
3228         /* Make sure TxDMA is ready to download firmware. */
3229         for (ntries = 0; ntries < 20; ntries++) {
3230                 reg = rsu_read_1(sc, R92S_TCR);
3231                 if ((reg & (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) ==
3232                     (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT))
3233                         break;
3234                 rsu_ms_delay(sc, 1);
3235         }
3236         if (ntries == 20) {
3237                 RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_TX,
3238                     "%s: TxDMA is not ready\n",
3239                     __func__);
3240                 /* Reset TxDMA. */
3241                 reg = rsu_read_1(sc, R92S_CR);
3242                 rsu_write_1(sc, R92S_CR, reg & ~R92S_CR_TXDMA_EN);
3243                 rsu_ms_delay(sc, 1);
3244                 rsu_write_1(sc, R92S_CR, reg | R92S_CR_TXDMA_EN);
3245         }
3246 }
3247
3248 static void
3249 rsu_power_off(struct rsu_softc *sc)
3250 {
3251         /* Turn RF off. */
3252         rsu_write_1(sc, R92S_RF_CTRL, 0x00);
3253         rsu_ms_delay(sc, 5);
3254
3255         /* Turn MAC off. */
3256         /* Switch control path. */
3257         rsu_write_1(sc, R92S_SYS_CLKR + 1, 0x38);
3258         /* Reset MACTOP. */
3259         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x70);
3260         rsu_write_1(sc, R92S_PMC_FSM, 0x06);
3261         rsu_write_1(sc, R92S_SYS_ISO_CTRL + 0, 0xf9);
3262         rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, 0xe8);
3263
3264         /* Disable AFE PLL. */
3265         rsu_write_1(sc, R92S_AFE_PLL_CTRL, 0x00);
3266         /* Disable A15V. */
3267         rsu_write_1(sc, R92S_LDOA15_CTRL, 0x54);
3268         /* Disable eFuse 1.2V. */
3269         rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x50);
3270         rsu_write_1(sc, R92S_LDOV12D_CTRL, 0x24);
3271         /* Enable AFE macro block's bandgap and Mbias. */
3272         rsu_write_1(sc, R92S_AFE_MISC, 0x30);
3273         /* Disable 1.6V LDO. */
3274         rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x56);
3275         rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x43);
3276
3277         /* Firmware - tell it to switch things off */
3278         (void) rsu_set_fw_power_state(sc, RSU_PWR_OFF);
3279 }
3280
3281 static int
3282 rsu_fw_loadsection(struct rsu_softc *sc, const uint8_t *buf, int len)
3283 {
3284         const uint8_t which = rsu_wme_ac_xfer_map[WME_AC_VO];
3285         struct rsu_data *data;
3286         struct r92s_tx_desc *txd;
3287         int mlen;
3288
3289         while (len > 0) {
3290                 data = rsu_getbuf(sc);
3291                 if (data == NULL)
3292                         return (ENOMEM);
3293                 txd = (struct r92s_tx_desc *)data->buf;
3294                 memset(txd, 0, sizeof(*txd));
3295                 if (len <= RSU_TXBUFSZ - sizeof(*txd)) {
3296                         /* Last chunk. */
3297                         txd->txdw0 |= htole32(R92S_TXDW0_LINIP);
3298                         mlen = len;
3299                 } else
3300                         mlen = RSU_TXBUFSZ - sizeof(*txd);
3301                 txd->txdw0 |= htole32(SM(R92S_TXDW0_PKTLEN, mlen));
3302                 memcpy(&txd[1], buf, mlen);
3303                 data->buflen = sizeof(*txd) + mlen;
3304                 RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FW | RSU_DEBUG_RESET,
3305                     "%s: starting transfer %p\n",
3306                     __func__, data);
3307                 STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
3308                 buf += mlen;
3309                 len -= mlen;
3310         }
3311         usbd_transfer_start(sc->sc_xfer[which]);
3312         return (0);
3313 }
3314
3315 CTASSERT(sizeof(size_t) >= sizeof(uint32_t));
3316
3317 static int
3318 rsu_load_firmware(struct rsu_softc *sc)
3319 {
3320         const struct r92s_fw_hdr *hdr;
3321         struct r92s_fw_priv *dmem;
3322         struct ieee80211com *ic = &sc->sc_ic;
3323         const uint8_t *imem, *emem;
3324         uint32_t imemsz, ememsz;
3325         const struct firmware *fw;
3326         size_t size;
3327         uint32_t reg;
3328         int ntries, error;
3329
3330         if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY) {
3331                 RSU_DPRINTF(sc, RSU_DEBUG_ANY,
3332                     "%s: Firmware already loaded\n",
3333                     __func__);
3334                 return (0);
3335         }
3336
3337         RSU_UNLOCK(sc);
3338         /* Read firmware image from the filesystem. */
3339         if ((fw = firmware_get("rsu-rtl8712fw")) == NULL) {
3340                 device_printf(sc->sc_dev, 
3341                     "%s: failed load firmware of file rsu-rtl8712fw\n",
3342                     __func__);
3343                 RSU_LOCK(sc);
3344                 return (ENXIO);
3345         }
3346         RSU_LOCK(sc);
3347         size = fw->datasize;
3348         if (size < sizeof(*hdr)) {
3349                 device_printf(sc->sc_dev, "firmware too short\n");
3350                 error = EINVAL;
3351                 goto fail;
3352         }
3353         hdr = (const struct r92s_fw_hdr *)fw->data;
3354         if (hdr->signature != htole16(0x8712) &&
3355             hdr->signature != htole16(0x8192)) {
3356                 device_printf(sc->sc_dev,
3357                     "invalid firmware signature 0x%x\n",
3358                     le16toh(hdr->signature));
3359                 error = EINVAL;
3360                 goto fail;
3361         }
3362         RSU_DPRINTF(sc, RSU_DEBUG_FW, "FW V%d %02x-%02x %02x:%02x\n",
3363             le16toh(hdr->version), hdr->month, hdr->day, hdr->hour,
3364             hdr->minute);
3365
3366         /* Make sure that driver and firmware are in sync. */
3367         if (hdr->privsz != htole32(sizeof(*dmem))) {
3368                 device_printf(sc->sc_dev, "unsupported firmware image\n");
3369                 error = EINVAL;
3370                 goto fail;
3371         }
3372         /* Get FW sections sizes. */
3373         imemsz = le32toh(hdr->imemsz);
3374         ememsz = le32toh(hdr->sramsz);
3375         /* Check that all FW sections fit in image. */
3376         if (imemsz > (size_t)(size - sizeof(*hdr)) ||
3377             ememsz > (size_t)(size - sizeof(*hdr) - imemsz)) {
3378                 device_printf(sc->sc_dev, "firmware too short\n");
3379                 error = EINVAL;
3380                 goto fail;
3381         }
3382         imem = (const uint8_t *)&hdr[1];
3383         emem = imem + imemsz;
3384
3385         /* Load IMEM section. */
3386         error = rsu_fw_loadsection(sc, imem, imemsz);
3387         if (error != 0) {
3388                 device_printf(sc->sc_dev,
3389                     "could not load firmware section %s\n", "IMEM");
3390                 goto fail;
3391         }
3392         /* Wait for load to complete. */
3393         for (ntries = 0; ntries != 50; ntries++) {
3394                 rsu_ms_delay(sc, 10);
3395                 reg = rsu_read_1(sc, R92S_TCR);
3396                 if (reg & R92S_TCR_IMEM_CODE_DONE)
3397                         break;
3398         }
3399         if (ntries == 50) {
3400                 device_printf(sc->sc_dev, "timeout waiting for IMEM transfer\n");
3401                 error = ETIMEDOUT;
3402                 goto fail;
3403         }
3404         /* Load EMEM section. */
3405         error = rsu_fw_loadsection(sc, emem, ememsz);
3406         if (error != 0) {
3407                 device_printf(sc->sc_dev,
3408                     "could not load firmware section %s\n", "EMEM");
3409                 goto fail;
3410         }
3411         /* Wait for load to complete. */
3412         for (ntries = 0; ntries != 50; ntries++) {
3413                 rsu_ms_delay(sc, 10);
3414                 reg = rsu_read_2(sc, R92S_TCR);
3415                 if (reg & R92S_TCR_EMEM_CODE_DONE)
3416                         break;
3417         }
3418         if (ntries == 50) {
3419                 device_printf(sc->sc_dev, "timeout waiting for EMEM transfer\n");
3420                 error = ETIMEDOUT;
3421                 goto fail;
3422         }
3423         /* Enable CPU. */
3424         rsu_write_1(sc, R92S_SYS_CLKR,
3425             rsu_read_1(sc, R92S_SYS_CLKR) | R92S_SYS_CPU_CLKSEL);
3426         if (!(rsu_read_1(sc, R92S_SYS_CLKR) & R92S_SYS_CPU_CLKSEL)) {
3427                 device_printf(sc->sc_dev, "could not enable system clock\n");
3428                 error = EIO;
3429                 goto fail;
3430         }
3431         rsu_write_2(sc, R92S_SYS_FUNC_EN,
3432             rsu_read_2(sc, R92S_SYS_FUNC_EN) | R92S_FEN_CPUEN);
3433         if (!(rsu_read_2(sc, R92S_SYS_FUNC_EN) & R92S_FEN_CPUEN)) {
3434                 device_printf(sc->sc_dev, 
3435                     "could not enable microcontroller\n");
3436                 error = EIO;
3437                 goto fail;
3438         }
3439         /* Wait for CPU to initialize. */
3440         for (ntries = 0; ntries < 100; ntries++) {
3441                 if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_IMEM_RDY)
3442                         break;
3443                 rsu_ms_delay(sc, 1);
3444         }
3445         if (ntries == 100) {
3446                 device_printf(sc->sc_dev,
3447                     "timeout waiting for microcontroller\n");
3448                 error = ETIMEDOUT;
3449                 goto fail;
3450         }
3451
3452         /* Update DMEM section before loading. */
3453         dmem = __DECONST(struct r92s_fw_priv *, &hdr->priv);
3454         memset(dmem, 0, sizeof(*dmem));
3455         dmem->hci_sel = R92S_HCI_SEL_USB | R92S_HCI_SEL_8172;
3456         dmem->nendpoints = sc->sc_nendpoints;
3457         dmem->chip_version = sc->cut;
3458         dmem->rf_config = sc->sc_rftype;
3459         dmem->vcs_type = R92S_VCS_TYPE_AUTO;
3460         dmem->vcs_mode = R92S_VCS_MODE_RTS_CTS;
3461         dmem->turbo_mode = 0;
3462         dmem->bw40_en = !! (ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40);
3463         dmem->amsdu2ampdu_en = !! (sc->sc_ht);
3464         dmem->ampdu_en = !! (sc->sc_ht);
3465         dmem->agg_offload = !! (sc->sc_ht);
3466         dmem->qos_en = 1;
3467         dmem->ps_offload = 1;
3468         dmem->lowpower_mode = 1;        /* XXX TODO: configurable? */
3469         /* Load DMEM section. */
3470         error = rsu_fw_loadsection(sc, (uint8_t *)dmem, sizeof(*dmem));
3471         if (error != 0) {
3472                 device_printf(sc->sc_dev,
3473                     "could not load firmware section %s\n", "DMEM");
3474                 goto fail;
3475         }
3476         /* Wait for load to complete. */
3477         for (ntries = 0; ntries < 100; ntries++) {
3478                 if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_DMEM_CODE_DONE)
3479                         break;
3480                 rsu_ms_delay(sc, 1);
3481         }
3482         if (ntries == 100) {
3483                 device_printf(sc->sc_dev, "timeout waiting for %s transfer\n",
3484                     "DMEM");
3485                 error = ETIMEDOUT;
3486                 goto fail;
3487         }
3488         /* Wait for firmware readiness. */
3489         for (ntries = 0; ntries < 60; ntries++) {
3490                 if (!(rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY))
3491                         break;
3492                 rsu_ms_delay(sc, 1);
3493         }
3494         if (ntries == 60) {
3495                 device_printf(sc->sc_dev, 
3496                     "timeout waiting for firmware readiness\n");
3497                 error = ETIMEDOUT;
3498                 goto fail;
3499         }
3500  fail:
3501         firmware_put(fw, FIRMWARE_UNLOAD);
3502         return (error);
3503 }
3504
3505
3506 static int      
3507 rsu_raw_xmit(struct ieee80211_node *ni, struct mbuf *m, 
3508     const struct ieee80211_bpf_params *params)
3509 {
3510         struct ieee80211com *ic = ni->ni_ic;
3511         struct rsu_softc *sc = ic->ic_softc;
3512         struct rsu_data *bf;
3513
3514         /* prevent management frames from being sent if we're not ready */
3515         if (!sc->sc_running) {
3516                 m_freem(m);
3517                 return (ENETDOWN);
3518         }
3519         RSU_LOCK(sc);
3520         bf = rsu_getbuf(sc);
3521         if (bf == NULL) {
3522                 m_freem(m);
3523                 RSU_UNLOCK(sc);
3524                 return (ENOBUFS);
3525         }
3526         if (rsu_tx_start(sc, ni, m, bf) != 0) {
3527                 m_freem(m);
3528                 rsu_freebuf(sc, bf);
3529                 RSU_UNLOCK(sc);
3530                 return (EIO);
3531         }
3532         RSU_UNLOCK(sc);
3533
3534         return (0);
3535 }
3536
3537 static void
3538 rsu_rxfilter_init(struct rsu_softc *sc)
3539 {
3540         uint32_t reg;
3541
3542         RSU_ASSERT_LOCKED(sc);
3543
3544         /* Setup multicast filter. */
3545         rsu_set_multi(sc);
3546
3547         /* Adjust Rx filter. */
3548         reg = rsu_read_4(sc, R92S_RCR);
3549         reg &= ~R92S_RCR_AICV;
3550         reg |= R92S_RCR_APP_PHYSTS;
3551         if (sc->sc_rx_checksum_enable)
3552                 reg |= R92S_RCR_TCP_OFFLD_EN;
3553         rsu_write_4(sc, R92S_RCR, reg);
3554
3555         /* Update dynamic Rx filter parts. */
3556         rsu_rxfilter_refresh(sc);
3557 }
3558
3559 static void
3560 rsu_rxfilter_set(struct rsu_softc *sc, uint32_t clear, uint32_t set)
3561 {
3562         /* NB: firmware can touch this register too. */
3563         rsu_write_4(sc, R92S_RCR,
3564            (rsu_read_4(sc, R92S_RCR) & ~clear) | set);
3565 }
3566
3567 static void
3568 rsu_rxfilter_refresh(struct rsu_softc *sc)
3569 {
3570         struct ieee80211com *ic = &sc->sc_ic;
3571         uint32_t mask_all, mask_min;
3572
3573         RSU_ASSERT_LOCKED(sc);
3574
3575         /* NB: RCR_AMF / RXFLTMAP_MGT are used by firmware. */
3576         mask_all = R92S_RCR_ACF | R92S_RCR_AAP;
3577         mask_min = R92S_RCR_APM;
3578         if (sc->sc_vap_is_running)
3579                 mask_min |= R92S_RCR_CBSSID;
3580         else
3581                 mask_all |= R92S_RCR_ADF;
3582
3583         if (ic->ic_opmode == IEEE80211_M_MONITOR) {
3584                 uint16_t rxfltmap;
3585                 if (sc->sc_vap_is_running)
3586                         rxfltmap = 0;
3587                 else
3588                         rxfltmap = R92S_RXFLTMAP_MGT_DEF;
3589                 rsu_write_2(sc, R92S_RXFLTMAP_MGT, rxfltmap);
3590         }
3591
3592         if (ic->ic_promisc == 0 && ic->ic_opmode != IEEE80211_M_MONITOR)
3593                 rsu_rxfilter_set(sc, mask_all, mask_min);
3594         else
3595                 rsu_rxfilter_set(sc, mask_min, mask_all);
3596 }
3597
3598 static int
3599 rsu_init(struct rsu_softc *sc)
3600 {
3601         struct ieee80211com *ic = &sc->sc_ic;
3602         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3603         uint8_t macaddr[IEEE80211_ADDR_LEN];
3604         int error;
3605         int i;
3606
3607         RSU_LOCK(sc);
3608
3609         if (sc->sc_running) {
3610                 RSU_UNLOCK(sc);
3611                 return (0);
3612         }
3613
3614         /* Ensure the mbuf queue is drained */
3615         rsu_drain_mbufq(sc);
3616
3617         /* Reset power management state. */
3618         rsu_write_1(sc, R92S_USB_HRPWM, 0);
3619
3620         /* Power on adapter. */
3621         if (sc->cut == 1)
3622                 rsu_power_on_acut(sc);
3623         else
3624                 rsu_power_on_bcut(sc);
3625
3626         /* Load firmware. */
3627         error = rsu_load_firmware(sc);
3628         if (error != 0)
3629                 goto fail;
3630
3631         rsu_write_4(sc, R92S_CR,
3632             rsu_read_4(sc, R92S_CR) & ~0xff000000);
3633
3634         /* Use 128 bytes pages. */
3635         rsu_write_1(sc, 0x00b5,
3636             rsu_read_1(sc, 0x00b5) | 0x01);
3637         /* Enable USB Rx aggregation. */
3638         rsu_write_1(sc, 0x00bd,
3639             rsu_read_1(sc, 0x00bd) | 0x80);
3640         /* Set USB Rx aggregation threshold. */
3641         rsu_write_1(sc, 0x00d9, 0x01);
3642         /* Set USB Rx aggregation timeout (1.7ms/4). */
3643         rsu_write_1(sc, 0xfe5b, 0x04);
3644         /* Fix USB Rx FIFO issue. */
3645         rsu_write_1(sc, 0xfe5c,
3646             rsu_read_1(sc, 0xfe5c) | 0x80);
3647
3648         /* Set MAC address. */
3649         IEEE80211_ADDR_COPY(macaddr, vap ? vap->iv_myaddr : ic->ic_macaddr);
3650         rsu_write_region_1(sc, R92S_MACID, macaddr, IEEE80211_ADDR_LEN);
3651
3652         /* It really takes 1.5 seconds for the firmware to boot: */
3653         usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(2000));
3654
3655         RSU_DPRINTF(sc, RSU_DEBUG_RESET, "%s: setting MAC address to %s\n",
3656             __func__,
3657             ether_sprintf(macaddr));
3658         error = rsu_fw_cmd(sc, R92S_CMD_SET_MAC_ADDRESS, macaddr,
3659             IEEE80211_ADDR_LEN);
3660         if (error != 0) {
3661                 device_printf(sc->sc_dev, "could not set MAC address\n");
3662                 goto fail;
3663         }
3664
3665         /* Initialize Rx filter. */
3666         rsu_rxfilter_init(sc);
3667
3668         /* Set PS mode fully active */
3669         error = rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
3670         if (error != 0) {
3671                 device_printf(sc->sc_dev, "could not set PS mode\n");
3672                 goto fail;
3673         }
3674
3675         /* Install static keys (if any). */
3676         error = rsu_reinit_static_keys(sc);
3677         if (error != 0)
3678                 goto fail;
3679
3680         sc->sc_extra_scan = 0;
3681         usbd_transfer_start(sc->sc_xfer[RSU_BULK_RX]);
3682
3683         /* We're ready to go. */
3684         sc->sc_running = 1;
3685         RSU_UNLOCK(sc);
3686
3687         return (0);
3688 fail:
3689         /* Need to stop all failed transfers, if any */
3690         for (i = 0; i != RSU_N_TRANSFER; i++)
3691                 usbd_transfer_stop(sc->sc_xfer[i]);
3692         RSU_UNLOCK(sc);
3693
3694         return (error);
3695 }
3696
3697 static void
3698 rsu_stop(struct rsu_softc *sc)
3699 {
3700         int i;
3701
3702         RSU_LOCK(sc);
3703         if (!sc->sc_running) {
3704                 RSU_UNLOCK(sc);
3705                 return;
3706         }
3707
3708         sc->sc_running = 0;
3709         sc->sc_vap_is_running = 0;
3710         sc->sc_calibrating = 0;
3711         taskqueue_cancel_timeout(taskqueue_thread, &sc->calib_task, NULL);
3712         taskqueue_cancel(taskqueue_thread, &sc->tx_task, NULL);
3713
3714         /* Power off adapter. */
3715         rsu_power_off(sc);
3716
3717         /*
3718          * CAM is not accessible after shutdown;
3719          * all entries are marked (by firmware?) as invalid.
3720          */
3721         memset(sc->free_keys_bmap, 0, sizeof(sc->free_keys_bmap));
3722         memset(sc->keys_bmap, 0, sizeof(sc->keys_bmap));
3723
3724         for (i = 0; i < RSU_N_TRANSFER; i++)
3725                 usbd_transfer_stop(sc->sc_xfer[i]);
3726
3727         /* Ensure the mbuf queue is drained */
3728         rsu_drain_mbufq(sc);
3729         RSU_UNLOCK(sc);
3730 }
3731
3732 /*
3733  * Note: usb_pause_mtx() actually releases the mutex before calling pause(),
3734  * which breaks any kind of driver serialisation.
3735  */
3736 static void
3737 rsu_ms_delay(struct rsu_softc *sc, int ms)
3738 {
3739
3740         //usb_pause_mtx(&sc->sc_mtx, hz / 1000);
3741         DELAY(ms * 1000);
3742 }