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