xref: /freebsd/sys/dev/usb/wlan/if_rsu.c (revision 123af6ec70016f5556da5972d4d63c7d175c06d3)
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 void
861 rsu_set_multi(struct rsu_softc *sc)
862 {
863 	struct ieee80211com *ic = &sc->sc_ic;
864 	uint32_t mfilt[2];
865 
866 	RSU_ASSERT_LOCKED(sc);
867 
868 	/* general structure was copied from ath(4). */
869 	if (ic->ic_allmulti == 0) {
870 		struct ieee80211vap *vap;
871 		struct ifnet *ifp;
872 		struct ifmultiaddr *ifma;
873 
874 		/*
875 		 * Merge multicast addresses to form the hardware filter.
876 		 */
877 		mfilt[0] = mfilt[1] = 0;
878 		TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
879 			ifp = vap->iv_ifp;
880 			if_maddr_rlock(ifp);
881 			CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
882 				caddr_t dl;
883 				uint8_t pos;
884 
885 				dl = LLADDR((struct sockaddr_dl *)
886 				    ifma->ifma_addr);
887 				pos = rsu_get_multi_pos(dl);
888 
889 				mfilt[pos / 32] |= (1 << (pos % 32));
890 			}
891 			if_maddr_runlock(ifp);
892 		}
893 	} else
894 		mfilt[0] = mfilt[1] = ~0;
895 
896 	rsu_write_4(sc, R92S_MAR + 0, mfilt[0]);
897 	rsu_write_4(sc, R92S_MAR + 4, mfilt[1]);
898 
899 	RSU_DPRINTF(sc, RSU_DEBUG_STATE, "%s: MC filter %08x:%08x\n",
900 	    __func__, mfilt[0], mfilt[1]);
901 }
902 
903 static void
904 rsu_update_mcast(struct ieee80211com *ic)
905 {
906 	struct rsu_softc *sc = ic->ic_softc;
907 
908 	RSU_LOCK(sc);
909 	if (sc->sc_running)
910 		rsu_set_multi(sc);
911 	RSU_UNLOCK(sc);
912 }
913 
914 static int
915 rsu_alloc_list(struct rsu_softc *sc, struct rsu_data data[],
916     int ndata, int maxsz)
917 {
918 	int i, error;
919 
920 	for (i = 0; i < ndata; i++) {
921 		struct rsu_data *dp = &data[i];
922 		dp->sc = sc;
923 		dp->m = NULL;
924 		dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT);
925 		if (dp->buf == NULL) {
926 			device_printf(sc->sc_dev,
927 			    "could not allocate buffer\n");
928 			error = ENOMEM;
929 			goto fail;
930 		}
931 		dp->ni = NULL;
932 	}
933 
934 	return (0);
935 fail:
936 	rsu_free_list(sc, data, ndata);
937 	return (error);
938 }
939 
940 static int
941 rsu_alloc_rx_list(struct rsu_softc *sc)
942 {
943         int error, i;
944 
945 	error = rsu_alloc_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT,
946 	    RSU_RXBUFSZ);
947 	if (error != 0)
948 		return (error);
949 
950 	STAILQ_INIT(&sc->sc_rx_active);
951 	STAILQ_INIT(&sc->sc_rx_inactive);
952 
953 	for (i = 0; i < RSU_RX_LIST_COUNT; i++)
954 		STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i], next);
955 
956 	return (0);
957 }
958 
959 static int
960 rsu_alloc_tx_list(struct rsu_softc *sc)
961 {
962 	int error, i;
963 
964 	error = rsu_alloc_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT,
965 	    RSU_TXBUFSZ);
966 	if (error != 0)
967 		return (error);
968 
969 	STAILQ_INIT(&sc->sc_tx_inactive);
970 
971 	for (i = 0; i != RSU_N_TRANSFER; i++) {
972 		STAILQ_INIT(&sc->sc_tx_active[i]);
973 		STAILQ_INIT(&sc->sc_tx_pending[i]);
974 	}
975 
976 	for (i = 0; i < RSU_TX_LIST_COUNT; i++) {
977 		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i], next);
978 	}
979 
980 	return (0);
981 }
982 
983 static void
984 rsu_free_tx_list(struct rsu_softc *sc)
985 {
986 	int i;
987 
988 	/* prevent further allocations from TX list(s) */
989 	STAILQ_INIT(&sc->sc_tx_inactive);
990 
991 	for (i = 0; i != RSU_N_TRANSFER; i++) {
992 		STAILQ_INIT(&sc->sc_tx_active[i]);
993 		STAILQ_INIT(&sc->sc_tx_pending[i]);
994 	}
995 
996 	rsu_free_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT);
997 }
998 
999 static void
1000 rsu_free_rx_list(struct rsu_softc *sc)
1001 {
1002 	/* prevent further allocations from RX list(s) */
1003 	STAILQ_INIT(&sc->sc_rx_inactive);
1004 	STAILQ_INIT(&sc->sc_rx_active);
1005 
1006 	rsu_free_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT);
1007 }
1008 
1009 static void
1010 rsu_free_list(struct rsu_softc *sc, struct rsu_data data[], int ndata)
1011 {
1012 	int i;
1013 
1014 	for (i = 0; i < ndata; i++) {
1015 		struct rsu_data *dp = &data[i];
1016 
1017 		if (dp->buf != NULL) {
1018 			free(dp->buf, M_USBDEV);
1019 			dp->buf = NULL;
1020 		}
1021 		if (dp->ni != NULL) {
1022 			ieee80211_free_node(dp->ni);
1023 			dp->ni = NULL;
1024 		}
1025 	}
1026 }
1027 
1028 static struct rsu_data *
1029 _rsu_getbuf(struct rsu_softc *sc)
1030 {
1031 	struct rsu_data *bf;
1032 
1033 	bf = STAILQ_FIRST(&sc->sc_tx_inactive);
1034 	if (bf != NULL)
1035 		STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next);
1036 	else
1037 		bf = NULL;
1038 	return (bf);
1039 }
1040 
1041 static struct rsu_data *
1042 rsu_getbuf(struct rsu_softc *sc)
1043 {
1044 	struct rsu_data *bf;
1045 
1046 	RSU_ASSERT_LOCKED(sc);
1047 
1048 	bf = _rsu_getbuf(sc);
1049 	if (bf == NULL) {
1050 		RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: no buffers\n", __func__);
1051 	}
1052 	return (bf);
1053 }
1054 
1055 static void
1056 rsu_freebuf(struct rsu_softc *sc, struct rsu_data *bf)
1057 {
1058 
1059 	RSU_ASSERT_LOCKED(sc);
1060 	STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, bf, next);
1061 }
1062 
1063 static int
1064 rsu_write_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
1065     int len)
1066 {
1067 	usb_device_request_t req;
1068 
1069 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1070 	req.bRequest = R92S_REQ_REGS;
1071 	USETW(req.wValue, addr);
1072 	USETW(req.wIndex, 0);
1073 	USETW(req.wLength, len);
1074 
1075 	return (rsu_do_request(sc, &req, buf));
1076 }
1077 
1078 static void
1079 rsu_write_1(struct rsu_softc *sc, uint16_t addr, uint8_t val)
1080 {
1081 	rsu_write_region_1(sc, addr, &val, 1);
1082 }
1083 
1084 static void
1085 rsu_write_2(struct rsu_softc *sc, uint16_t addr, uint16_t val)
1086 {
1087 	val = htole16(val);
1088 	rsu_write_region_1(sc, addr, (uint8_t *)&val, 2);
1089 }
1090 
1091 static void
1092 rsu_write_4(struct rsu_softc *sc, uint16_t addr, uint32_t val)
1093 {
1094 	val = htole32(val);
1095 	rsu_write_region_1(sc, addr, (uint8_t *)&val, 4);
1096 }
1097 
1098 static int
1099 rsu_read_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
1100     int len)
1101 {
1102 	usb_device_request_t req;
1103 
1104 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1105 	req.bRequest = R92S_REQ_REGS;
1106 	USETW(req.wValue, addr);
1107 	USETW(req.wIndex, 0);
1108 	USETW(req.wLength, len);
1109 
1110 	return (rsu_do_request(sc, &req, buf));
1111 }
1112 
1113 static uint8_t
1114 rsu_read_1(struct rsu_softc *sc, uint16_t addr)
1115 {
1116 	uint8_t val;
1117 
1118 	if (rsu_read_region_1(sc, addr, &val, 1) != 0)
1119 		return (0xff);
1120 	return (val);
1121 }
1122 
1123 static uint16_t
1124 rsu_read_2(struct rsu_softc *sc, uint16_t addr)
1125 {
1126 	uint16_t val;
1127 
1128 	if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0)
1129 		return (0xffff);
1130 	return (le16toh(val));
1131 }
1132 
1133 static uint32_t
1134 rsu_read_4(struct rsu_softc *sc, uint16_t addr)
1135 {
1136 	uint32_t val;
1137 
1138 	if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0)
1139 		return (0xffffffff);
1140 	return (le32toh(val));
1141 }
1142 
1143 static int
1144 rsu_fw_iocmd(struct rsu_softc *sc, uint32_t iocmd)
1145 {
1146 	int ntries;
1147 
1148 	rsu_write_4(sc, R92S_IOCMD_CTRL, iocmd);
1149 	rsu_ms_delay(sc, 1);
1150 	for (ntries = 0; ntries < 50; ntries++) {
1151 		if (rsu_read_4(sc, R92S_IOCMD_CTRL) == 0)
1152 			return (0);
1153 		rsu_ms_delay(sc, 1);
1154 	}
1155 	return (ETIMEDOUT);
1156 }
1157 
1158 static uint8_t
1159 rsu_efuse_read_1(struct rsu_softc *sc, uint16_t addr)
1160 {
1161 	uint32_t reg;
1162 	int ntries;
1163 
1164 	reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
1165 	reg = RW(reg, R92S_EFUSE_CTRL_ADDR, addr);
1166 	reg &= ~R92S_EFUSE_CTRL_VALID;
1167 	rsu_write_4(sc, R92S_EFUSE_CTRL, reg);
1168 	/* Wait for read operation to complete. */
1169 	for (ntries = 0; ntries < 100; ntries++) {
1170 		reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
1171 		if (reg & R92S_EFUSE_CTRL_VALID)
1172 			return (MS(reg, R92S_EFUSE_CTRL_DATA));
1173 		rsu_ms_delay(sc, 1);
1174 	}
1175 	device_printf(sc->sc_dev,
1176 	    "could not read efuse byte at address 0x%x\n", addr);
1177 	return (0xff);
1178 }
1179 
1180 static int
1181 rsu_read_rom(struct rsu_softc *sc)
1182 {
1183 	uint8_t *rom = sc->rom;
1184 	uint16_t addr = 0;
1185 	uint32_t reg;
1186 	uint8_t off, msk;
1187 	int i;
1188 
1189 	/* Make sure that ROM type is eFuse and that autoload succeeded. */
1190 	reg = rsu_read_1(sc, R92S_EE_9346CR);
1191 	if ((reg & (R92S_9356SEL | R92S_EEPROM_EN)) != R92S_EEPROM_EN)
1192 		return (EIO);
1193 
1194 	/* Turn on 2.5V to prevent eFuse leakage. */
1195 	reg = rsu_read_1(sc, R92S_EFUSE_TEST + 3);
1196 	rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg | 0x80);
1197 	rsu_ms_delay(sc, 1);
1198 	rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg & ~0x80);
1199 
1200 	/* Read full ROM image. */
1201 	memset(&sc->rom, 0xff, sizeof(sc->rom));
1202 	while (addr < 512) {
1203 		reg = rsu_efuse_read_1(sc, addr);
1204 		if (reg == 0xff)
1205 			break;
1206 		addr++;
1207 		off = reg >> 4;
1208 		msk = reg & 0xf;
1209 		for (i = 0; i < 4; i++) {
1210 			if (msk & (1 << i))
1211 				continue;
1212 			rom[off * 8 + i * 2 + 0] =
1213 			    rsu_efuse_read_1(sc, addr);
1214 			addr++;
1215 			rom[off * 8 + i * 2 + 1] =
1216 			    rsu_efuse_read_1(sc, addr);
1217 			addr++;
1218 		}
1219 	}
1220 #ifdef USB_DEBUG
1221 	if (rsu_debug & RSU_DEBUG_RESET) {
1222 		/* Dump ROM content. */
1223 		printf("\n");
1224 		for (i = 0; i < sizeof(sc->rom); i++)
1225 			printf("%02x:", rom[i]);
1226 		printf("\n");
1227 	}
1228 #endif
1229 	return (0);
1230 }
1231 
1232 static int
1233 rsu_fw_cmd(struct rsu_softc *sc, uint8_t code, void *buf, int len)
1234 {
1235 	const uint8_t which = RSU_H2C_ENDPOINT;
1236 	struct rsu_data *data;
1237 	struct r92s_tx_desc *txd;
1238 	struct r92s_fw_cmd_hdr *cmd;
1239 	int cmdsz;
1240 	int xferlen;
1241 
1242 	RSU_ASSERT_LOCKED(sc);
1243 
1244 	data = rsu_getbuf(sc);
1245 	if (data == NULL)
1246 		return (ENOMEM);
1247 
1248 	/* Blank the entire payload, just to be safe */
1249 	memset(data->buf, '\0', RSU_TXBUFSZ);
1250 
1251 	/* Round-up command length to a multiple of 8 bytes. */
1252 	/* XXX TODO: is this required? */
1253 	cmdsz = (len + 7) & ~7;
1254 
1255 	xferlen = sizeof(*txd) + sizeof(*cmd) + cmdsz;
1256 	KASSERT(xferlen <= RSU_TXBUFSZ, ("%s: invalid length", __func__));
1257 	memset(data->buf, 0, xferlen);
1258 
1259 	/* Setup Tx descriptor. */
1260 	txd = (struct r92s_tx_desc *)data->buf;
1261 	txd->txdw0 = htole32(
1262 	    SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
1263 	    SM(R92S_TXDW0_PKTLEN, sizeof(*cmd) + cmdsz) |
1264 	    R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
1265 	txd->txdw1 = htole32(SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_H2C));
1266 
1267 	/* Setup command header. */
1268 	cmd = (struct r92s_fw_cmd_hdr *)&txd[1];
1269 	cmd->len = htole16(cmdsz);
1270 	cmd->code = code;
1271 	cmd->seq = sc->cmd_seq;
1272 	sc->cmd_seq = (sc->cmd_seq + 1) & 0x7f;
1273 
1274 	/* Copy command payload. */
1275 	memcpy(&cmd[1], buf, len);
1276 
1277 	RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FWCMD,
1278 	    "%s: Tx cmd code=0x%x len=0x%x\n",
1279 	    __func__, code, cmdsz);
1280 	data->buflen = xferlen;
1281 	STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
1282 	usbd_transfer_start(sc->sc_xfer[which]);
1283 
1284 	return (0);
1285 }
1286 
1287 /* ARGSUSED */
1288 static void
1289 rsu_calib_task(void *arg, int pending __unused)
1290 {
1291 	struct rsu_softc *sc = arg;
1292 #ifdef notyet
1293 	uint32_t reg;
1294 #endif
1295 
1296 	RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "%s: running calibration task\n",
1297 	    __func__);
1298 
1299 	RSU_LOCK(sc);
1300 #ifdef notyet
1301 	/* Read WPS PBC status. */
1302 	rsu_write_1(sc, R92S_MAC_PINMUX_CTRL,
1303 	    R92S_GPIOMUX_EN | SM(R92S_GPIOSEL_GPIO, R92S_GPIOSEL_GPIO_JTAG));
1304 	rsu_write_1(sc, R92S_GPIO_IO_SEL,
1305 	    rsu_read_1(sc, R92S_GPIO_IO_SEL) & ~R92S_GPIO_WPS);
1306 	reg = rsu_read_1(sc, R92S_GPIO_CTRL);
1307 	if (reg != 0xff && (reg & R92S_GPIO_WPS))
1308 		RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "WPS PBC is pushed\n");
1309 #endif
1310 	/* Read current signal level. */
1311 	if (rsu_fw_iocmd(sc, 0xf4000001) == 0) {
1312 		sc->sc_currssi = rsu_read_4(sc, R92S_IOCMD_DATA);
1313 		RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "%s: RSSI=%d (%d)\n",
1314 		    __func__, sc->sc_currssi,
1315 		    rsu_hwrssi_to_rssi(sc, sc->sc_currssi));
1316 	}
1317 	if (sc->sc_calibrating)
1318 		taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, hz);
1319 	RSU_UNLOCK(sc);
1320 }
1321 
1322 static void
1323 rsu_tx_task(void *arg, int pending __unused)
1324 {
1325 	struct rsu_softc *sc = arg;
1326 
1327 	RSU_LOCK(sc);
1328 	_rsu_start(sc);
1329 	RSU_UNLOCK(sc);
1330 }
1331 
1332 #define	RSU_PWR_UNKNOWN		0x0
1333 #define	RSU_PWR_ACTIVE		0x1
1334 #define	RSU_PWR_OFF		0x2
1335 #define	RSU_PWR_SLEEP		0x3
1336 
1337 /*
1338  * Set the current power state.
1339  *
1340  * The rtlwifi code doesn't do this so aggressively; it
1341  * waits for an idle period after association with
1342  * no traffic before doing this.
1343  *
1344  * For now - it's on in all states except RUN, and
1345  * in RUN it'll transition to allow sleep.
1346  */
1347 
1348 struct r92s_pwr_cmd {
1349 	uint8_t mode;
1350 	uint8_t smart_ps;
1351 	uint8_t bcn_pass_time;
1352 };
1353 
1354 static int
1355 rsu_set_fw_power_state(struct rsu_softc *sc, int state)
1356 {
1357 	struct r92s_set_pwr_mode cmd;
1358 	//struct r92s_pwr_cmd cmd;
1359 	int error;
1360 
1361 	RSU_ASSERT_LOCKED(sc);
1362 
1363 	/* only change state if required */
1364 	if (sc->sc_curpwrstate == state)
1365 		return (0);
1366 
1367 	memset(&cmd, 0, sizeof(cmd));
1368 
1369 	switch (state) {
1370 	case RSU_PWR_ACTIVE:
1371 		/* Force the hardware awake */
1372 		rsu_write_1(sc, R92S_USB_HRPWM,
1373 		    R92S_USB_HRPWM_PS_ST_ACTIVE | R92S_USB_HRPWM_PS_ALL_ON);
1374 		cmd.mode = R92S_PS_MODE_ACTIVE;
1375 		break;
1376 	case RSU_PWR_SLEEP:
1377 		cmd.mode = R92S_PS_MODE_DTIM;	/* XXX configurable? */
1378 		cmd.smart_ps = 1; /* XXX 2 if doing p2p */
1379 		cmd.bcn_pass_time = 5; /* in 100mS usb.c, linux/rtlwifi */
1380 		break;
1381 	case RSU_PWR_OFF:
1382 		cmd.mode = R92S_PS_MODE_RADIOOFF;
1383 		break;
1384 	default:
1385 		device_printf(sc->sc_dev, "%s: unknown ps mode (%d)\n",
1386 		    __func__,
1387 		    state);
1388 		return (ENXIO);
1389 	}
1390 
1391 	RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1392 	    "%s: setting ps mode to %d (mode %d)\n",
1393 	    __func__, state, cmd.mode);
1394 	error = rsu_fw_cmd(sc, R92S_CMD_SET_PWR_MODE, &cmd, sizeof(cmd));
1395 	if (error == 0)
1396 		sc->sc_curpwrstate = state;
1397 
1398 	return (error);
1399 }
1400 
1401 static void
1402 rsu_set_led(struct rsu_softc *sc, int on)
1403 {
1404 	rsu_write_1(sc, R92S_LEDCFG,
1405 	    (rsu_read_1(sc, R92S_LEDCFG) & 0xf0) | (!on << 3));
1406 }
1407 
1408 static int
1409 rsu_monitor_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate,
1410     int arg)
1411 {
1412 	struct ieee80211com *ic = vap->iv_ic;
1413 	struct rsu_softc *sc = ic->ic_softc;
1414 	struct rsu_vap *uvp = RSU_VAP(vap);
1415 
1416 	if (vap->iv_state != nstate) {
1417 		IEEE80211_UNLOCK(ic);
1418 		RSU_LOCK(sc);
1419 
1420 		switch (nstate) {
1421 		case IEEE80211_S_INIT:
1422 			sc->sc_vap_is_running = 0;
1423 			rsu_set_led(sc, 0);
1424 			break;
1425 		case IEEE80211_S_RUN:
1426 			sc->sc_vap_is_running = 1;
1427 			rsu_set_led(sc, 1);
1428 			break;
1429 		default:
1430 			/* NOTREACHED */
1431 			break;
1432 		}
1433 		rsu_rxfilter_refresh(sc);
1434 
1435 		RSU_UNLOCK(sc);
1436 		IEEE80211_LOCK(ic);
1437 	}
1438 
1439 	return (uvp->newstate(vap, nstate, arg));
1440 }
1441 
1442 static int
1443 rsu_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1444 {
1445 	struct rsu_vap *uvp = RSU_VAP(vap);
1446 	struct ieee80211com *ic = vap->iv_ic;
1447 	struct rsu_softc *sc = ic->ic_softc;
1448 	struct ieee80211_node *ni;
1449 	struct ieee80211_rateset *rs;
1450 	enum ieee80211_state ostate;
1451 	int error, startcal = 0;
1452 
1453 	ostate = vap->iv_state;
1454 	RSU_DPRINTF(sc, RSU_DEBUG_STATE, "%s: %s -> %s\n",
1455 	    __func__,
1456 	    ieee80211_state_name[ostate],
1457 	    ieee80211_state_name[nstate]);
1458 
1459 	IEEE80211_UNLOCK(ic);
1460 	if (ostate == IEEE80211_S_RUN) {
1461 		RSU_LOCK(sc);
1462 		/* Stop calibration. */
1463 		sc->sc_calibrating = 0;
1464 
1465 		/* Pause Tx for AC queues. */
1466 		rsu_write_1(sc, R92S_TXPAUSE, R92S_TXPAUSE_AC);
1467 		usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(10));
1468 
1469 		RSU_UNLOCK(sc);
1470 		taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task);
1471 		taskqueue_drain(taskqueue_thread, &sc->tx_task);
1472 		RSU_LOCK(sc);
1473 		/* Disassociate from our current BSS. */
1474 		rsu_disconnect(sc);
1475 		usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(10));
1476 
1477 		/* Refresh Rx filter (may be modified by firmware). */
1478 		sc->sc_vap_is_running = 0;
1479 		rsu_rxfilter_refresh(sc);
1480 
1481 		/* Reinstall static keys. */
1482 		if (sc->sc_running)
1483 			rsu_reinit_static_keys(sc);
1484 	} else
1485 		RSU_LOCK(sc);
1486 	switch (nstate) {
1487 	case IEEE80211_S_INIT:
1488 		(void) rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
1489 		break;
1490 	case IEEE80211_S_AUTH:
1491 		ni = ieee80211_ref_node(vap->iv_bss);
1492 		(void) rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
1493 		error = rsu_join_bss(sc, ni);
1494 		ieee80211_free_node(ni);
1495 		if (error != 0) {
1496 			device_printf(sc->sc_dev,
1497 			    "could not send join command\n");
1498 		}
1499 		break;
1500 	case IEEE80211_S_RUN:
1501 		/* Flush all AC queues. */
1502 		rsu_write_1(sc, R92S_TXPAUSE, 0);
1503 
1504 		ni = ieee80211_ref_node(vap->iv_bss);
1505 		rs = &ni->ni_rates;
1506 		/* Indicate highest supported rate. */
1507 		ni->ni_txrate = rs->rs_rates[rs->rs_nrates - 1];
1508 		(void) rsu_set_fw_power_state(sc, RSU_PWR_SLEEP);
1509 		ieee80211_free_node(ni);
1510 		startcal = 1;
1511 		break;
1512 	default:
1513 		break;
1514 	}
1515 	if (startcal != 0) {
1516 		sc->sc_calibrating = 1;
1517 		/* Start periodic calibration. */
1518 		taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task,
1519 		    hz);
1520 	}
1521 	RSU_UNLOCK(sc);
1522 	IEEE80211_LOCK(ic);
1523 	return (uvp->newstate(vap, nstate, arg));
1524 }
1525 
1526 static int
1527 rsu_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,
1528     ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
1529 {
1530 	struct rsu_softc *sc = vap->iv_ic->ic_softc;
1531 	int is_checked = 0;
1532 
1533 	if (&vap->iv_nw_keys[0] <= k &&
1534 	    k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
1535 		*keyix = ieee80211_crypto_get_key_wepidx(vap, k);
1536 	} else {
1537 		if (vap->iv_opmode != IEEE80211_M_STA) {
1538 			*keyix = 0;
1539 			/* TODO: obtain keyix from node id */
1540 			is_checked = 1;
1541 			k->wk_flags |= IEEE80211_KEY_SWCRYPT;
1542 		} else
1543 			*keyix = R92S_MACID_BSS;
1544 	}
1545 
1546 	if (!is_checked) {
1547 		RSU_LOCK(sc);
1548 		if (isset(sc->keys_bmap, *keyix)) {
1549 			device_printf(sc->sc_dev,
1550 			    "%s: key slot %d is already used!\n",
1551 			    __func__, *keyix);
1552 			RSU_UNLOCK(sc);
1553 			return (0);
1554 		}
1555 		setbit(sc->keys_bmap, *keyix);
1556 		RSU_UNLOCK(sc);
1557 	}
1558 
1559 	*rxkeyix = *keyix;
1560 
1561 	return (1);
1562 }
1563 
1564 static int
1565 rsu_process_key(struct ieee80211vap *vap, const struct ieee80211_key *k,
1566     int set)
1567 {
1568 	struct rsu_softc *sc = vap->iv_ic->ic_softc;
1569 	int ret;
1570 
1571 	if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
1572 		/* Not for us. */
1573 		return (1);
1574 	}
1575 
1576 	/* Handle group keys. */
1577 	if (&vap->iv_nw_keys[0] <= k &&
1578 	    k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
1579 		KASSERT(k->wk_keyix < nitems(sc->group_keys),
1580 		    ("keyix %u > %zu\n", k->wk_keyix, nitems(sc->group_keys)));
1581 
1582 		RSU_LOCK(sc);
1583 		sc->group_keys[k->wk_keyix] = (set ? k : NULL);
1584 		if (!sc->sc_running) {
1585 			/* Static keys will be set during device startup. */
1586 			RSU_UNLOCK(sc);
1587 			return (1);
1588 		}
1589 
1590 		if (set)
1591 			ret = rsu_set_key_group(sc, k);
1592 		else
1593 			ret = rsu_delete_key(sc, k->wk_keyix);
1594 		RSU_UNLOCK(sc);
1595 
1596 		return (!ret);
1597 	}
1598 
1599 	if (set) {
1600 		/* wait for pending key removal */
1601 		taskqueue_drain(taskqueue_thread, &sc->del_key_task);
1602 
1603 		RSU_LOCK(sc);
1604 		ret = rsu_set_key_pair(sc, k);
1605 		RSU_UNLOCK(sc);
1606 	} else {
1607 		RSU_DELKEY_BMAP_LOCK(sc);
1608 		setbit(sc->free_keys_bmap, k->wk_keyix);
1609 		RSU_DELKEY_BMAP_UNLOCK(sc);
1610 
1611 		/* workaround ieee80211_node_delucastkey() locking */
1612 		taskqueue_enqueue(taskqueue_thread, &sc->del_key_task);
1613 		ret = 0;	/* fake success */
1614 	}
1615 
1616 	return (!ret);
1617 }
1618 
1619 static int
1620 rsu_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k)
1621 {
1622 	return (rsu_process_key(vap, k, 1));
1623 }
1624 
1625 static int
1626 rsu_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
1627 {
1628 	return (rsu_process_key(vap, k, 0));
1629 }
1630 
1631 static int
1632 rsu_cam_read(struct rsu_softc *sc, uint8_t addr, uint32_t *val)
1633 {
1634 	int ntries;
1635 
1636 	rsu_write_4(sc, R92S_CAMCMD,
1637 	    R92S_CAMCMD_POLLING | SM(R92S_CAMCMD_ADDR, addr));
1638 	for (ntries = 0; ntries < 10; ntries++) {
1639 		if (!(rsu_read_4(sc, R92S_CAMCMD) & R92S_CAMCMD_POLLING))
1640 			break;
1641 
1642 		usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(1));
1643 	}
1644 	if (ntries == 10) {
1645 		device_printf(sc->sc_dev,
1646 		    "%s: cannot read CAM entry at address %02X\n",
1647 		    __func__, addr);
1648 		return (ETIMEDOUT);
1649 	}
1650 
1651 	*val = rsu_read_4(sc, R92S_CAMREAD);
1652 
1653 	return (0);
1654 }
1655 
1656 static void
1657 rsu_cam_write(struct rsu_softc *sc, uint8_t addr, uint32_t data)
1658 {
1659 
1660 	rsu_write_4(sc, R92S_CAMWRITE, data);
1661 	rsu_write_4(sc, R92S_CAMCMD,
1662 	    R92S_CAMCMD_POLLING | R92S_CAMCMD_WRITE |
1663 	    SM(R92S_CAMCMD_ADDR, addr));
1664 }
1665 
1666 static int
1667 rsu_key_check(struct rsu_softc *sc, ieee80211_keyix keyix, int is_valid)
1668 {
1669 	uint32_t val;
1670 	int error, ntries;
1671 
1672 	for (ntries = 0; ntries < 20; ntries++) {
1673 		usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(1));
1674 
1675 		error = rsu_cam_read(sc, R92S_CAM_CTL0(keyix), &val);
1676 		if (error != 0) {
1677 			device_printf(sc->sc_dev,
1678 			    "%s: cannot check key status!\n", __func__);
1679 			return (error);
1680 		}
1681 		if (((val & R92S_CAM_VALID) == 0) ^ is_valid)
1682 			break;
1683 	}
1684 	if (ntries == 20) {
1685 		device_printf(sc->sc_dev,
1686 		    "%s: key %d is %s marked as valid, rejecting request\n",
1687 		    __func__, keyix, is_valid ? "not" : "still");
1688 		return (EIO);
1689 	}
1690 
1691 	return (0);
1692 }
1693 
1694 /*
1695  * Map net80211 cipher to RTL8712 security mode.
1696  */
1697 static uint8_t
1698 rsu_crypto_mode(struct rsu_softc *sc, u_int cipher, int keylen)
1699 {
1700 	switch (cipher) {
1701 	case IEEE80211_CIPHER_WEP:
1702 		return keylen < 8 ? R92S_KEY_ALGO_WEP40 : R92S_KEY_ALGO_WEP104;
1703 	case IEEE80211_CIPHER_TKIP:
1704 		return R92S_KEY_ALGO_TKIP;
1705 	case IEEE80211_CIPHER_AES_CCM:
1706 		return R92S_KEY_ALGO_AES;
1707 	default:
1708 		device_printf(sc->sc_dev, "unknown cipher %d\n", cipher);
1709 		return R92S_KEY_ALGO_INVALID;
1710 	}
1711 }
1712 
1713 static int
1714 rsu_set_key_group(struct rsu_softc *sc, const struct ieee80211_key *k)
1715 {
1716 	struct r92s_fw_cmd_set_key key;
1717 	uint8_t algo;
1718 	int error;
1719 
1720 	RSU_ASSERT_LOCKED(sc);
1721 
1722 	/* Map net80211 cipher to HW crypto algorithm. */
1723 	algo = rsu_crypto_mode(sc, k->wk_cipher->ic_cipher, k->wk_keylen);
1724 	if (algo == R92S_KEY_ALGO_INVALID)
1725 		return (EINVAL);
1726 
1727 	memset(&key, 0, sizeof(key));
1728 	key.algo = algo;
1729 	key.cam_id = k->wk_keyix;
1730 	key.grpkey = (k->wk_flags & IEEE80211_KEY_GROUP) != 0;
1731 	memcpy(key.key, k->wk_key, MIN(k->wk_keylen, sizeof(key.key)));
1732 
1733 	RSU_DPRINTF(sc, RSU_DEBUG_KEY | RSU_DEBUG_FWCMD,
1734 	    "%s: keyix %u, group %u, algo %u/%u, flags %04X, len %u, "
1735 	    "macaddr %s\n", __func__, key.cam_id, key.grpkey,
1736 	    k->wk_cipher->ic_cipher, key.algo, k->wk_flags, k->wk_keylen,
1737 	    ether_sprintf(k->wk_macaddr));
1738 
1739 	error = rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
1740 	if (error != 0) {
1741 		device_printf(sc->sc_dev,
1742 		    "%s: cannot send firmware command, error %d\n",
1743 		    __func__, error);
1744 		return (error);
1745 	}
1746 
1747 	return (rsu_key_check(sc, k->wk_keyix, 1));
1748 }
1749 
1750 static int
1751 rsu_set_key_pair(struct rsu_softc *sc, const struct ieee80211_key *k)
1752 {
1753 	struct r92s_fw_cmd_set_key_mac key;
1754 	uint8_t algo;
1755 	int error;
1756 
1757 	RSU_ASSERT_LOCKED(sc);
1758 
1759 	if (!sc->sc_running)
1760 		return (ESHUTDOWN);
1761 
1762 	/* Map net80211 cipher to HW crypto algorithm. */
1763 	algo = rsu_crypto_mode(sc, k->wk_cipher->ic_cipher, k->wk_keylen);
1764 	if (algo == R92S_KEY_ALGO_INVALID)
1765 		return (EINVAL);
1766 
1767 	memset(&key, 0, sizeof(key));
1768 	key.algo = algo;
1769 	memcpy(key.macaddr, k->wk_macaddr, sizeof(key.macaddr));
1770 	memcpy(key.key, k->wk_key, MIN(k->wk_keylen, sizeof(key.key)));
1771 
1772 	RSU_DPRINTF(sc, RSU_DEBUG_KEY | RSU_DEBUG_FWCMD,
1773 	    "%s: keyix %u, algo %u/%u, flags %04X, len %u, macaddr %s\n",
1774 	    __func__, k->wk_keyix, k->wk_cipher->ic_cipher, key.algo,
1775 	    k->wk_flags, k->wk_keylen, ether_sprintf(key.macaddr));
1776 
1777 	error = rsu_fw_cmd(sc, R92S_CMD_SET_STA_KEY, &key, sizeof(key));
1778 	if (error != 0) {
1779 		device_printf(sc->sc_dev,
1780 		    "%s: cannot send firmware command, error %d\n",
1781 		    __func__, error);
1782 		return (error);
1783 	}
1784 
1785 	return (rsu_key_check(sc, k->wk_keyix, 1));
1786 }
1787 
1788 static int
1789 rsu_reinit_static_keys(struct rsu_softc *sc)
1790 {
1791 	int i, error;
1792 
1793 	for (i = 0; i < nitems(sc->group_keys); i++) {
1794 		if (sc->group_keys[i] != NULL) {
1795 			error = rsu_set_key_group(sc, sc->group_keys[i]);
1796 			if (error != 0) {
1797 				device_printf(sc->sc_dev,
1798 				    "%s: failed to set static key %d, "
1799 				    "error %d\n", __func__, i, error);
1800 				return (error);
1801 			}
1802 		}
1803 	}
1804 
1805 	return (0);
1806 }
1807 
1808 static int
1809 rsu_delete_key(struct rsu_softc *sc, ieee80211_keyix keyix)
1810 {
1811 	struct r92s_fw_cmd_set_key key;
1812 	uint32_t val;
1813 	int error;
1814 
1815 	RSU_ASSERT_LOCKED(sc);
1816 
1817 	if (!sc->sc_running)
1818 		return (0);
1819 
1820 	/* check if it was automatically removed by firmware */
1821 	error = rsu_cam_read(sc, R92S_CAM_CTL0(keyix), &val);
1822 	if (error == 0 && (val & R92S_CAM_VALID) == 0) {
1823 		RSU_DPRINTF(sc, RSU_DEBUG_KEY,
1824 		    "%s: key %u does not exist\n", __func__, keyix);
1825 		clrbit(sc->keys_bmap, keyix);
1826 		return (0);
1827 	}
1828 
1829 	memset(&key, 0, sizeof(key));
1830 	key.cam_id = keyix;
1831 
1832 	RSU_DPRINTF(sc, RSU_DEBUG_KEY | RSU_DEBUG_FWCMD,
1833 	    "%s: removing key %u\n", __func__, key.cam_id);
1834 
1835 	error = rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
1836 	if (error != 0) {
1837 		device_printf(sc->sc_dev,
1838 		    "%s: cannot send firmware command, error %d\n",
1839 		    __func__, error);
1840 		goto finish;
1841 	}
1842 
1843 	usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(5));
1844 
1845 	/*
1846 	 * Clear 'valid' bit manually (cannot be done via firmware command).
1847 	 * Used for key check + when firmware command cannot be sent.
1848 	 */
1849 finish:
1850 	rsu_cam_write(sc, R92S_CAM_CTL0(keyix), 0);
1851 
1852 	clrbit(sc->keys_bmap, keyix);
1853 
1854 	return (rsu_key_check(sc, keyix, 0));
1855 }
1856 
1857 static void
1858 rsu_delete_key_pair_cb(void *arg, int pending __unused)
1859 {
1860 	struct rsu_softc *sc = arg;
1861 	int i;
1862 
1863 	RSU_DELKEY_BMAP_LOCK(sc);
1864 	for (i = IEEE80211_WEP_NKID; i < R92S_CAM_ENTRY_LIMIT; i++) {
1865 		if (isset(sc->free_keys_bmap, i)) {
1866 			RSU_DELKEY_BMAP_UNLOCK(sc);
1867 
1868 			RSU_LOCK(sc);
1869 			RSU_DPRINTF(sc, RSU_DEBUG_KEY,
1870 			    "%s: calling rsu_delete_key() with keyix = %d\n",
1871 			    __func__, i);
1872 			(void) rsu_delete_key(sc, i);
1873 			RSU_UNLOCK(sc);
1874 
1875 			RSU_DELKEY_BMAP_LOCK(sc);
1876 			clrbit(sc->free_keys_bmap, i);
1877 
1878 			/* bmap can be changed */
1879 			i = IEEE80211_WEP_NKID - 1;
1880 			continue;
1881 		}
1882 	}
1883 	RSU_DELKEY_BMAP_UNLOCK(sc);
1884 }
1885 
1886 static int
1887 rsu_site_survey(struct rsu_softc *sc, struct ieee80211_scan_ssid *ssid)
1888 {
1889 	struct r92s_fw_cmd_sitesurvey cmd;
1890 
1891 	RSU_ASSERT_LOCKED(sc);
1892 
1893 	memset(&cmd, 0, sizeof(cmd));
1894 	/* TODO: passive channels? */
1895 	if (sc->sc_active_scan)
1896 		cmd.active = htole32(1);
1897 	cmd.limit = htole32(48);
1898 
1899 	if (ssid != NULL) {
1900 		sc->sc_extra_scan = 1;
1901 		cmd.ssidlen = htole32(ssid->len);
1902 		memcpy(cmd.ssid, ssid->ssid, ssid->len);
1903 	}
1904 #ifdef USB_DEBUG
1905 	if (rsu_debug & (RSU_DEBUG_SCAN | RSU_DEBUG_FWCMD)) {
1906 		device_printf(sc->sc_dev,
1907 		    "sending site survey command, active %d",
1908 		    le32toh(cmd.active));
1909 		if (ssid != NULL) {
1910 			printf(", ssid: ");
1911 			ieee80211_print_essid(cmd.ssid, le32toh(cmd.ssidlen));
1912 		}
1913 		printf("\n");
1914 	}
1915 #endif
1916 	return (rsu_fw_cmd(sc, R92S_CMD_SITE_SURVEY, &cmd, sizeof(cmd)));
1917 }
1918 
1919 static int
1920 rsu_join_bss(struct rsu_softc *sc, struct ieee80211_node *ni)
1921 {
1922 	struct ieee80211com *ic = &sc->sc_ic;
1923 	struct ieee80211vap *vap = ni->ni_vap;
1924 	struct ndis_wlan_bssid_ex *bss;
1925 	struct ndis_802_11_fixed_ies *fixed;
1926 	struct r92s_fw_cmd_auth auth;
1927 	uint8_t buf[sizeof(*bss) + 128] __aligned(4);
1928 	uint8_t *frm;
1929 	uint8_t opmode;
1930 	int error;
1931 
1932 	RSU_ASSERT_LOCKED(sc);
1933 
1934 	/* Let the FW decide the opmode based on the capinfo field. */
1935 	opmode = NDIS802_11AUTOUNKNOWN;
1936 	RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1937 	    "%s: setting operating mode to %d\n",
1938 	    __func__, opmode);
1939 	error = rsu_fw_cmd(sc, R92S_CMD_SET_OPMODE, &opmode, sizeof(opmode));
1940 	if (error != 0)
1941 		return (error);
1942 
1943 	memset(&auth, 0, sizeof(auth));
1944 	if (vap->iv_flags & IEEE80211_F_WPA) {
1945 		auth.mode = R92S_AUTHMODE_WPA;
1946 		auth.dot1x = (ni->ni_authmode == IEEE80211_AUTH_8021X);
1947 	} else
1948 		auth.mode = R92S_AUTHMODE_OPEN;
1949 	RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1950 	    "%s: setting auth mode to %d\n",
1951 	    __func__, auth.mode);
1952 	error = rsu_fw_cmd(sc, R92S_CMD_SET_AUTH, &auth, sizeof(auth));
1953 	if (error != 0)
1954 		return (error);
1955 
1956 	memset(buf, 0, sizeof(buf));
1957 	bss = (struct ndis_wlan_bssid_ex *)buf;
1958 	IEEE80211_ADDR_COPY(bss->macaddr, ni->ni_bssid);
1959 	bss->ssid.ssidlen = htole32(ni->ni_esslen);
1960 	memcpy(bss->ssid.ssid, ni->ni_essid, ni->ni_esslen);
1961 	if (vap->iv_flags & (IEEE80211_F_PRIVACY | IEEE80211_F_WPA))
1962 		bss->privacy = htole32(1);
1963 	bss->rssi = htole32(ni->ni_avgrssi);
1964 	if (ic->ic_curmode == IEEE80211_MODE_11B)
1965 		bss->networktype = htole32(NDIS802_11DS);
1966 	else
1967 		bss->networktype = htole32(NDIS802_11OFDM24);
1968 	bss->config.len = htole32(sizeof(bss->config));
1969 	bss->config.bintval = htole32(ni->ni_intval);
1970 	bss->config.dsconfig = htole32(ieee80211_chan2ieee(ic, ni->ni_chan));
1971 	bss->inframode = htole32(NDIS802_11INFRASTRUCTURE);
1972 	/* XXX verify how this is supposed to look! */
1973 	memcpy(bss->supprates, ni->ni_rates.rs_rates,
1974 	    ni->ni_rates.rs_nrates);
1975 	/* Write the fixed fields of the beacon frame. */
1976 	fixed = (struct ndis_802_11_fixed_ies *)&bss[1];
1977 	memcpy(&fixed->tstamp, ni->ni_tstamp.data, 8);
1978 	fixed->bintval = htole16(ni->ni_intval);
1979 	fixed->capabilities = htole16(ni->ni_capinfo);
1980 	/* Write IEs to be included in the association request. */
1981 	frm = (uint8_t *)&fixed[1];
1982 	frm = ieee80211_add_rsn(frm, vap);
1983 	frm = ieee80211_add_wpa(frm, vap);
1984 	frm = ieee80211_add_qos(frm, ni);
1985 	if ((ic->ic_flags & IEEE80211_F_WME) &&
1986 	    (ni->ni_ies.wme_ie != NULL))
1987 		frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1988 	if (ni->ni_flags & IEEE80211_NODE_HT) {
1989 		frm = ieee80211_add_htcap(frm, ni);
1990 		frm = ieee80211_add_htinfo(frm, ni);
1991 	}
1992 	bss->ieslen = htole32(frm - (uint8_t *)fixed);
1993 	bss->len = htole32(((frm - buf) + 3) & ~3);
1994 	RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_FWCMD,
1995 	    "%s: sending join bss command to %s chan %d\n",
1996 	    __func__,
1997 	    ether_sprintf(bss->macaddr), le32toh(bss->config.dsconfig));
1998 	return (rsu_fw_cmd(sc, R92S_CMD_JOIN_BSS, buf, sizeof(buf)));
1999 }
2000 
2001 static int
2002 rsu_disconnect(struct rsu_softc *sc)
2003 {
2004 	uint32_t zero = 0;	/* :-) */
2005 
2006 	/* Disassociate from our current BSS. */
2007 	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
2008 	    "%s: sending disconnect command\n", __func__);
2009 	return (rsu_fw_cmd(sc, R92S_CMD_DISCONNECT, &zero, sizeof(zero)));
2010 }
2011 
2012 /*
2013  * Map the hardware provided RSSI value to a signal level.
2014  * For the most part it's just something we divide by and cap
2015  * so it doesn't overflow the representation by net80211.
2016  */
2017 static int
2018 rsu_hwrssi_to_rssi(struct rsu_softc *sc, int hw_rssi)
2019 {
2020 	int v;
2021 
2022 	if (hw_rssi == 0)
2023 		return (0);
2024 	v = hw_rssi >> 4;
2025 	if (v > 80)
2026 		v = 80;
2027 	return (v);
2028 }
2029 
2030 CTASSERT(MCLBYTES > sizeof(struct ieee80211_frame));
2031 
2032 static void
2033 rsu_event_survey(struct rsu_softc *sc, uint8_t *buf, int len)
2034 {
2035 	struct ieee80211com *ic = &sc->sc_ic;
2036 	struct ieee80211_frame *wh;
2037 	struct ndis_wlan_bssid_ex *bss;
2038 	struct ieee80211_rx_stats rxs;
2039 	struct mbuf *m;
2040 	uint32_t ieslen;
2041 	uint32_t pktlen;
2042 
2043 	if (__predict_false(len < sizeof(*bss)))
2044 		return;
2045 	bss = (struct ndis_wlan_bssid_ex *)buf;
2046 	ieslen = le32toh(bss->ieslen);
2047 	/* range check length of information element */
2048 	if (__predict_false(ieslen > (uint32_t)(len - sizeof(*bss))))
2049 		return;
2050 
2051 	RSU_DPRINTF(sc, RSU_DEBUG_SCAN,
2052 	    "%s: found BSS %s: len=%d chan=%d inframode=%d "
2053 	    "networktype=%d privacy=%d, RSSI=%d\n",
2054 	    __func__,
2055 	    ether_sprintf(bss->macaddr), ieslen,
2056 	    le32toh(bss->config.dsconfig), le32toh(bss->inframode),
2057 	    le32toh(bss->networktype), le32toh(bss->privacy),
2058 	    le32toh(bss->rssi));
2059 
2060 	/* Build a fake beacon frame to let net80211 do all the parsing. */
2061 	/* XXX TODO: just call the new scan API methods! */
2062 	if (__predict_false(ieslen > (size_t)(MCLBYTES - sizeof(*wh))))
2063 		return;
2064 	pktlen = sizeof(*wh) + ieslen;
2065 	m = m_get2(pktlen, M_NOWAIT, MT_DATA, M_PKTHDR);
2066 	if (__predict_false(m == NULL))
2067 		return;
2068 	wh = mtod(m, struct ieee80211_frame *);
2069 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2070 	    IEEE80211_FC0_SUBTYPE_BEACON;
2071 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2072 	USETW(wh->i_dur, 0);
2073 	IEEE80211_ADDR_COPY(wh->i_addr1, ieee80211broadcastaddr);
2074 	IEEE80211_ADDR_COPY(wh->i_addr2, bss->macaddr);
2075 	IEEE80211_ADDR_COPY(wh->i_addr3, bss->macaddr);
2076 	*(uint16_t *)wh->i_seq = 0;
2077 	memcpy(&wh[1], (uint8_t *)&bss[1], ieslen);
2078 
2079 	/* Finalize mbuf. */
2080 	m->m_pkthdr.len = m->m_len = pktlen;
2081 
2082 	/* Set channel flags for input path */
2083 	bzero(&rxs, sizeof(rxs));
2084 	rxs.r_flags |= IEEE80211_R_IEEE | IEEE80211_R_FREQ;
2085 	rxs.r_flags |= IEEE80211_R_NF | IEEE80211_R_RSSI;
2086 	rxs.c_ieee = le32toh(bss->config.dsconfig);
2087 	rxs.c_freq = ieee80211_ieee2mhz(rxs.c_ieee, IEEE80211_CHAN_2GHZ);
2088 	/* This is a number from 0..100; so let's just divide it down a bit */
2089 	rxs.c_rssi = le32toh(bss->rssi) / 2;
2090 	rxs.c_nf = -96;
2091 	if (ieee80211_add_rx_params(m, &rxs) == 0)
2092 		return;
2093 
2094 	/* XXX avoid a LOR */
2095 	RSU_UNLOCK(sc);
2096 	ieee80211_input_mimo_all(ic, m);
2097 	RSU_LOCK(sc);
2098 }
2099 
2100 static void
2101 rsu_event_join_bss(struct rsu_softc *sc, uint8_t *buf, int len)
2102 {
2103 	struct ieee80211com *ic = &sc->sc_ic;
2104 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2105 	struct ieee80211_node *ni = vap->iv_bss;
2106 	struct r92s_event_join_bss *rsp;
2107 	uint32_t tmp;
2108 	int res;
2109 
2110 	if (__predict_false(len < sizeof(*rsp)))
2111 		return;
2112 	rsp = (struct r92s_event_join_bss *)buf;
2113 	res = (int)le32toh(rsp->join_res);
2114 
2115 	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
2116 	    "%s: Rx join BSS event len=%d res=%d\n",
2117 	    __func__, len, res);
2118 
2119 	/*
2120 	 * XXX Don't do this; there's likely a better way to tell
2121 	 * the caller we failed.
2122 	 */
2123 	if (res <= 0) {
2124 		RSU_UNLOCK(sc);
2125 		ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
2126 		RSU_LOCK(sc);
2127 		return;
2128 	}
2129 
2130 	tmp = le32toh(rsp->associd);
2131 	if (tmp >= vap->iv_max_aid) {
2132 		RSU_DPRINTF(sc, RSU_DEBUG_ANY, "Assoc ID overflow\n");
2133 		tmp = 1;
2134 	}
2135 	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
2136 	    "%s: associated with %s associd=%d\n",
2137 	    __func__, ether_sprintf(rsp->bss.macaddr), tmp);
2138 	/* XXX is this required? What's the top two bits for again? */
2139 	ni->ni_associd = tmp | 0xc000;
2140 
2141 	/* Refresh Rx filter (was changed by firmware). */
2142 	sc->sc_vap_is_running = 1;
2143 	rsu_rxfilter_refresh(sc);
2144 
2145 	RSU_UNLOCK(sc);
2146 	ieee80211_new_state(vap, IEEE80211_S_RUN,
2147 	    IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
2148 	RSU_LOCK(sc);
2149 }
2150 
2151 static void
2152 rsu_event_addba_req_report(struct rsu_softc *sc, uint8_t *buf, int len)
2153 {
2154 	struct ieee80211com *ic = &sc->sc_ic;
2155 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2156 	struct r92s_add_ba_event *ba = (void *) buf;
2157 	struct ieee80211_node *ni;
2158 
2159 	if (len < sizeof(*ba)) {
2160 		device_printf(sc->sc_dev, "%s: short read (%d)\n", __func__, len);
2161 		return;
2162 	}
2163 
2164 	if (vap == NULL)
2165 		return;
2166 
2167 	RSU_DPRINTF(sc, RSU_DEBUG_AMPDU, "%s: mac=%s, tid=%d, ssn=%d\n",
2168 	    __func__,
2169 	    ether_sprintf(ba->mac_addr),
2170 	    (int) ba->tid,
2171 	    (int) le16toh(ba->ssn));
2172 
2173 	/* XXX do node lookup; this is STA specific */
2174 
2175 	ni = ieee80211_ref_node(vap->iv_bss);
2176 	ieee80211_ampdu_rx_start_ext(ni, ba->tid, le16toh(ba->ssn) >> 4, 32);
2177 	ieee80211_free_node(ni);
2178 }
2179 
2180 static void
2181 rsu_rx_event(struct rsu_softc *sc, uint8_t code, uint8_t *buf, int len)
2182 {
2183 	struct ieee80211com *ic = &sc->sc_ic;
2184 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2185 
2186 	RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD,
2187 	    "%s: Rx event code=%d len=%d\n", __func__, code, len);
2188 	switch (code) {
2189 	case R92S_EVT_SURVEY:
2190 		rsu_event_survey(sc, buf, len);
2191 		break;
2192 	case R92S_EVT_SURVEY_DONE:
2193 		RSU_DPRINTF(sc, RSU_DEBUG_SCAN,
2194 		    "%s: %s scan done, found %d BSS\n",
2195 		    __func__, sc->sc_extra_scan ? "direct" : "broadcast",
2196 		    le32toh(*(uint32_t *)buf));
2197 		if (sc->sc_extra_scan == 1) {
2198 			/* Send broadcast probe request. */
2199 			sc->sc_extra_scan = 0;
2200 			if (vap != NULL && rsu_site_survey(sc, NULL) != 0) {
2201 				RSU_UNLOCK(sc);
2202 				ieee80211_cancel_scan(vap);
2203 				RSU_LOCK(sc);
2204 			}
2205 			break;
2206 		}
2207 		if (vap != NULL) {
2208 			RSU_UNLOCK(sc);
2209 			ieee80211_scan_done(vap);
2210 			RSU_LOCK(sc);
2211 		}
2212 		break;
2213 	case R92S_EVT_JOIN_BSS:
2214 		if (vap->iv_state == IEEE80211_S_AUTH)
2215 			rsu_event_join_bss(sc, buf, len);
2216 		break;
2217 	case R92S_EVT_DEL_STA:
2218 		RSU_DPRINTF(sc, RSU_DEBUG_FWCMD | RSU_DEBUG_STATE,
2219 		    "%s: disassociated from %s\n", __func__,
2220 		    ether_sprintf(buf));
2221 		if (vap->iv_state == IEEE80211_S_RUN &&
2222 		    IEEE80211_ADDR_EQ(vap->iv_bss->ni_bssid, buf)) {
2223 			RSU_UNLOCK(sc);
2224 			ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
2225 			RSU_LOCK(sc);
2226 		}
2227 		break;
2228 	case R92S_EVT_WPS_PBC:
2229 		RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD,
2230 		    "%s: WPS PBC pushed.\n", __func__);
2231 		break;
2232 	case R92S_EVT_FWDBG:
2233 		buf[60] = '\0';
2234 		RSU_DPRINTF(sc, RSU_DEBUG_FWDBG, "FWDBG: %s\n", (char *)buf);
2235 		break;
2236 	case R92S_EVT_ADDBA_REQ_REPORT:
2237 		rsu_event_addba_req_report(sc, buf, len);
2238 		break;
2239 	default:
2240 		device_printf(sc->sc_dev, "%s: unhandled code (%d)\n", __func__, code);
2241 		break;
2242 	}
2243 }
2244 
2245 static void
2246 rsu_rx_multi_event(struct rsu_softc *sc, uint8_t *buf, int len)
2247 {
2248 	struct r92s_fw_cmd_hdr *cmd;
2249 	int cmdsz;
2250 
2251 	RSU_DPRINTF(sc, RSU_DEBUG_RX, "%s: Rx events len=%d\n", __func__, len);
2252 
2253 	/* Skip Rx status. */
2254 	buf += sizeof(struct r92s_rx_stat);
2255 	len -= sizeof(struct r92s_rx_stat);
2256 
2257 	/* Process all events. */
2258 	for (;;) {
2259 		/* Check that command header fits. */
2260 		if (__predict_false(len < sizeof(*cmd)))
2261 			break;
2262 		cmd = (struct r92s_fw_cmd_hdr *)buf;
2263 		/* Check that command payload fits. */
2264 		cmdsz = le16toh(cmd->len);
2265 		if (__predict_false(len < sizeof(*cmd) + cmdsz))
2266 			break;
2267 
2268 		/* Process firmware event. */
2269 		rsu_rx_event(sc, cmd->code, (uint8_t *)&cmd[1], cmdsz);
2270 
2271 		if (!(cmd->seq & R92S_FW_CMD_MORE))
2272 			break;
2273 		buf += sizeof(*cmd) + cmdsz;
2274 		len -= sizeof(*cmd) + cmdsz;
2275 	}
2276 }
2277 
2278 static int8_t
2279 rsu_get_rssi(struct rsu_softc *sc, int rate, void *physt)
2280 {
2281 	static const int8_t cckoff[] = { 14, -2, -20, -40 };
2282 	struct r92s_rx_phystat *phy;
2283 	struct r92s_rx_cck *cck;
2284 	uint8_t rpt;
2285 	int8_t rssi;
2286 
2287 	if (rate <= 3) {
2288 		cck = (struct r92s_rx_cck *)physt;
2289 		rpt = (cck->agc_rpt >> 6) & 0x3;
2290 		rssi = cck->agc_rpt & 0x3e;
2291 		rssi = cckoff[rpt] - rssi;
2292 	} else {	/* OFDM/HT. */
2293 		phy = (struct r92s_rx_phystat *)physt;
2294 		rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 106;
2295 	}
2296 	return (rssi);
2297 }
2298 
2299 static struct mbuf *
2300 rsu_rx_copy_to_mbuf(struct rsu_softc *sc, struct r92s_rx_stat *stat,
2301     int totlen)
2302 {
2303 	struct ieee80211com *ic = &sc->sc_ic;
2304 	struct mbuf *m;
2305 	uint32_t rxdw0;
2306 	int pktlen;
2307 
2308 	rxdw0 = le32toh(stat->rxdw0);
2309 	if (__predict_false(rxdw0 & (R92S_RXDW0_CRCERR | R92S_RXDW0_ICVERR))) {
2310 		RSU_DPRINTF(sc, RSU_DEBUG_RX,
2311 		    "%s: RX flags error (%s)\n", __func__,
2312 		    rxdw0 & R92S_RXDW0_CRCERR ? "CRC" : "ICV");
2313 		goto fail;
2314 	}
2315 
2316 	pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN);
2317 	if (__predict_false(pktlen < sizeof (struct ieee80211_frame_ack))) {
2318 		RSU_DPRINTF(sc, RSU_DEBUG_RX,
2319 		    "%s: frame is too short: %d\n", __func__, pktlen);
2320 		goto fail;
2321 	}
2322 
2323 	m = m_get2(totlen, M_NOWAIT, MT_DATA, M_PKTHDR);
2324 	if (__predict_false(m == NULL)) {
2325 		device_printf(sc->sc_dev,
2326 		    "%s: could not allocate RX mbuf, totlen %d\n",
2327 		    __func__, totlen);
2328 		goto fail;
2329 	}
2330 
2331 	/* Finalize mbuf. */
2332 	memcpy(mtod(m, uint8_t *), (uint8_t *)stat, totlen);
2333 	m->m_pkthdr.len = m->m_len = totlen;
2334 
2335 	return (m);
2336 fail:
2337 	counter_u64_add(ic->ic_ierrors, 1);
2338 	return (NULL);
2339 }
2340 
2341 static uint32_t
2342 rsu_get_tsf_low(struct rsu_softc *sc)
2343 {
2344 	return (rsu_read_4(sc, R92S_TSFTR));
2345 }
2346 
2347 static uint32_t
2348 rsu_get_tsf_high(struct rsu_softc *sc)
2349 {
2350 	return (rsu_read_4(sc, R92S_TSFTR + 4));
2351 }
2352 
2353 static struct ieee80211_node *
2354 rsu_rx_frame(struct rsu_softc *sc, struct mbuf *m)
2355 {
2356 	struct ieee80211com *ic = &sc->sc_ic;
2357 	struct ieee80211_frame_min *wh;
2358 	struct ieee80211_rx_stats rxs;
2359 	struct r92s_rx_stat *stat;
2360 	uint32_t rxdw0, rxdw3;
2361 	uint8_t cipher, rate;
2362 	int infosz;
2363 	int rssi;
2364 
2365 	stat = mtod(m, struct r92s_rx_stat *);
2366 	rxdw0 = le32toh(stat->rxdw0);
2367 	rxdw3 = le32toh(stat->rxdw3);
2368 
2369 	rate = MS(rxdw3, R92S_RXDW3_RATE);
2370 	cipher = MS(rxdw0, R92S_RXDW0_CIPHER);
2371 	infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
2372 
2373 	/* Get RSSI from PHY status descriptor if present. */
2374 	if (infosz != 0 && (rxdw0 & R92S_RXDW0_PHYST))
2375 		rssi = rsu_get_rssi(sc, rate, &stat[1]);
2376 	else {
2377 		/* Cheat and get the last calibrated RSSI */
2378 		rssi = rsu_hwrssi_to_rssi(sc, sc->sc_currssi);
2379 	}
2380 
2381 	/* Hardware does Rx TCP checksum offload. */
2382 	/*
2383 	 * This flag can be set for some other
2384 	 * (e.g., EAPOL) frame types, so don't rely on it.
2385 	 */
2386 	if (rxdw3 & R92S_RXDW3_TCPCHKVALID) {
2387 		RSU_DPRINTF(sc, RSU_DEBUG_RX,
2388 		    "%s: TCP/IP checksums: %schecked / %schecked\n",
2389 		    __func__,
2390 		    (rxdw3 & R92S_RXDW3_TCPCHKRPT) ? "" : "not ",
2391 		    (rxdw3 & R92S_RXDW3_IPCHKRPT) ? "" : "not ");
2392 
2393 		/*
2394 		 * 'IP header checksum valid' bit will not be set if
2395 		 * the frame was not checked / has incorrect checksum /
2396 		 * does not have checksum (IPv6).
2397 		 *
2398 		 * NB: if DF bit is not set then frame will not be checked.
2399 		 */
2400 		if (rxdw3 & R92S_RXDW3_IPCHKRPT) {
2401 			m->m_pkthdr.csum_flags = CSUM_IP_CHECKED;
2402 			m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
2403 		}
2404 
2405 		/*
2406 		 * This is independent of the above check.
2407 		 */
2408 		if (rxdw3 & R92S_RXDW3_TCPCHKRPT) {
2409 			m->m_pkthdr.csum_flags |= CSUM_DATA_VALID;
2410 			m->m_pkthdr.csum_flags |= CSUM_PSEUDO_HDR;
2411 			m->m_pkthdr.csum_data = 0xffff;
2412 		}
2413 	}
2414 
2415 	/* RX flags */
2416 
2417 	/* Set channel flags for input path */
2418 	bzero(&rxs, sizeof(rxs));
2419 
2420 	/* normal RSSI */
2421 	rxs.r_flags |= IEEE80211_R_NF | IEEE80211_R_RSSI;
2422 	rxs.c_rssi = rssi;
2423 	rxs.c_nf = -96;
2424 
2425 	/* Rate */
2426 	if (rate < 12) {
2427 		rxs.c_rate = ridx2rate[rate];
2428 		if (RSU_RATE_IS_CCK(rate))
2429 			rxs.c_pktflags |= IEEE80211_RX_F_CCK;
2430 		else
2431 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2432 	} else {
2433 		rxs.c_rate = IEEE80211_RATE_MCS | (rate - 12);
2434 		rxs.c_pktflags |= IEEE80211_RX_F_HT;
2435 	}
2436 
2437 	if (ieee80211_radiotap_active(ic)) {
2438 		struct rsu_rx_radiotap_header *tap = &sc->sc_rxtap;
2439 
2440 		/* Map HW rate index to 802.11 rate. */
2441 		tap->wr_flags = 0;		/* TODO */
2442 		tap->wr_tsft = rsu_get_tsf_high(sc);
2443 		if (le32toh(stat->tsf_low) > rsu_get_tsf_low(sc))
2444 			tap->wr_tsft--;
2445 		tap->wr_tsft = (uint64_t)htole32(tap->wr_tsft) << 32;
2446 		tap->wr_tsft += stat->tsf_low;
2447 
2448 		tap->wr_rate = rxs.c_rate;
2449 		tap->wr_dbm_antsignal = rssi;
2450 	};
2451 
2452 	(void) ieee80211_add_rx_params(m, &rxs);
2453 
2454 	/* Drop descriptor. */
2455 	m_adj(m, sizeof(*stat) + infosz);
2456 	wh = mtod(m, struct ieee80211_frame_min *);
2457 	if ((wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
2458 	    cipher != R92S_KEY_ALGO_NONE) {
2459 		m->m_flags |= M_WEP;
2460 	}
2461 
2462 	RSU_DPRINTF(sc, RSU_DEBUG_RX,
2463 	    "%s: Rx frame len %d, rate %d, infosz %d\n",
2464 	    __func__, m->m_len, rate, infosz);
2465 
2466 	if (m->m_len >= sizeof(*wh))
2467 		return (ieee80211_find_rxnode(ic, wh));
2468 
2469 	return (NULL);
2470 }
2471 
2472 static struct mbuf *
2473 rsu_rx_multi_frame(struct rsu_softc *sc, uint8_t *buf, int len)
2474 {
2475 	struct r92s_rx_stat *stat;
2476 	uint32_t rxdw0;
2477 	int totlen, pktlen, infosz, npkts;
2478 	struct mbuf *m, *m0 = NULL, *prevm = NULL;
2479 
2480 	/*
2481 	 * don't pass packets to the ieee80211 framework if the driver isn't
2482 	 * RUNNING.
2483 	 */
2484 	if (!sc->sc_running)
2485 		return (NULL);
2486 
2487 	/* Get the number of encapsulated frames. */
2488 	stat = (struct r92s_rx_stat *)buf;
2489 	npkts = MS(le32toh(stat->rxdw2), R92S_RXDW2_PKTCNT);
2490 	RSU_DPRINTF(sc, RSU_DEBUG_RX,
2491 	    "%s: Rx %d frames in one chunk\n", __func__, npkts);
2492 
2493 	/* Process all of them. */
2494 	while (npkts-- > 0) {
2495 		if (__predict_false(len < sizeof(*stat)))
2496 			break;
2497 		stat = (struct r92s_rx_stat *)buf;
2498 		rxdw0 = le32toh(stat->rxdw0);
2499 
2500 		pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN);
2501 		if (__predict_false(pktlen == 0))
2502 			break;
2503 
2504 		infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
2505 
2506 		/* Make sure everything fits in xfer. */
2507 		totlen = sizeof(*stat) + infosz + pktlen;
2508 		if (__predict_false(totlen > len))
2509 			break;
2510 
2511 		/* Process 802.11 frame. */
2512 		m = rsu_rx_copy_to_mbuf(sc, stat, totlen);
2513 		if (m0 == NULL)
2514 			m0 = m;
2515 		if (prevm == NULL)
2516 			prevm = m;
2517 		else {
2518 			prevm->m_next = m;
2519 			prevm = m;
2520 		}
2521 		/* Next chunk is 128-byte aligned. */
2522 		totlen = (totlen + 127) & ~127;
2523 		buf += totlen;
2524 		len -= totlen;
2525 	}
2526 
2527 	return (m0);
2528 }
2529 
2530 static struct mbuf *
2531 rsu_rxeof(struct usb_xfer *xfer, struct rsu_data *data)
2532 {
2533 	struct rsu_softc *sc = data->sc;
2534 	struct ieee80211com *ic = &sc->sc_ic;
2535 	struct r92s_rx_stat *stat;
2536 	int len;
2537 
2538 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
2539 
2540 	if (__predict_false(len < sizeof(*stat))) {
2541 		RSU_DPRINTF(sc, RSU_DEBUG_RX, "xfer too short %d\n", len);
2542 		counter_u64_add(ic->ic_ierrors, 1);
2543 		return (NULL);
2544 	}
2545 	/* Determine if it is a firmware C2H event or an 802.11 frame. */
2546 	stat = (struct r92s_rx_stat *)data->buf;
2547 	if ((le32toh(stat->rxdw1) & 0x1ff) == 0x1ff) {
2548 		rsu_rx_multi_event(sc, data->buf, len);
2549 		/* No packets to process. */
2550 		return (NULL);
2551 	} else
2552 		return (rsu_rx_multi_frame(sc, data->buf, len));
2553 }
2554 
2555 static void
2556 rsu_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
2557 {
2558 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2559 	struct ieee80211com *ic = &sc->sc_ic;
2560 	struct ieee80211_node *ni;
2561 	struct mbuf *m = NULL, *next;
2562 	struct rsu_data *data;
2563 
2564 	RSU_ASSERT_LOCKED(sc);
2565 
2566 	switch (USB_GET_STATE(xfer)) {
2567 	case USB_ST_TRANSFERRED:
2568 		data = STAILQ_FIRST(&sc->sc_rx_active);
2569 		if (data == NULL)
2570 			goto tr_setup;
2571 		STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
2572 		m = rsu_rxeof(xfer, data);
2573 		STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
2574 		/* FALLTHROUGH */
2575 	case USB_ST_SETUP:
2576 tr_setup:
2577 		data = STAILQ_FIRST(&sc->sc_rx_inactive);
2578 		if (data == NULL) {
2579 			KASSERT(m == NULL, ("mbuf isn't NULL"));
2580 			return;
2581 		}
2582 		STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next);
2583 		STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next);
2584 		usbd_xfer_set_frame_data(xfer, 0, data->buf,
2585 		    usbd_xfer_max_len(xfer));
2586 		usbd_transfer_submit(xfer);
2587 		/*
2588 		 * To avoid LOR we should unlock our private mutex here to call
2589 		 * ieee80211_input() because here is at the end of a USB
2590 		 * callback and safe to unlock.
2591 		 */
2592 		while (m != NULL) {
2593 			next = m->m_next;
2594 			m->m_next = NULL;
2595 
2596 			ni = rsu_rx_frame(sc, m);
2597 			RSU_UNLOCK(sc);
2598 
2599 			if (ni != NULL) {
2600 				if (ni->ni_flags & IEEE80211_NODE_HT)
2601 					m->m_flags |= M_AMPDU;
2602 				(void)ieee80211_input_mimo(ni, m);
2603 				ieee80211_free_node(ni);
2604 			} else
2605 				(void)ieee80211_input_mimo_all(ic, m);
2606 
2607 			RSU_LOCK(sc);
2608 			m = next;
2609 		}
2610 		break;
2611 	default:
2612 		/* needs it to the inactive queue due to a error. */
2613 		data = STAILQ_FIRST(&sc->sc_rx_active);
2614 		if (data != NULL) {
2615 			STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
2616 			STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
2617 		}
2618 		if (error != USB_ERR_CANCELLED) {
2619 			usbd_xfer_set_stall(xfer);
2620 			counter_u64_add(ic->ic_ierrors, 1);
2621 			goto tr_setup;
2622 		}
2623 		break;
2624 	}
2625 
2626 }
2627 
2628 static void
2629 rsu_txeof(struct usb_xfer *xfer, struct rsu_data *data)
2630 {
2631 #ifdef	USB_DEBUG
2632 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2633 #endif
2634 
2635 	RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: called; data=%p\n",
2636 	    __func__,
2637 	    data);
2638 
2639 	if (data->m) {
2640 		/* XXX status? */
2641 		ieee80211_tx_complete(data->ni, data->m, 0);
2642 		data->m = NULL;
2643 		data->ni = NULL;
2644 	}
2645 }
2646 
2647 static void
2648 rsu_bulk_tx_callback_sub(struct usb_xfer *xfer, usb_error_t error,
2649     uint8_t which)
2650 {
2651 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2652 	struct ieee80211com *ic = &sc->sc_ic;
2653 	struct rsu_data *data;
2654 
2655 	RSU_ASSERT_LOCKED(sc);
2656 
2657 	switch (USB_GET_STATE(xfer)) {
2658 	case USB_ST_TRANSFERRED:
2659 		data = STAILQ_FIRST(&sc->sc_tx_active[which]);
2660 		if (data == NULL)
2661 			goto tr_setup;
2662 		RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: transfer done %p\n",
2663 		    __func__, data);
2664 		STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
2665 		rsu_txeof(xfer, data);
2666 		rsu_freebuf(sc, data);
2667 		/* FALLTHROUGH */
2668 	case USB_ST_SETUP:
2669 tr_setup:
2670 		data = STAILQ_FIRST(&sc->sc_tx_pending[which]);
2671 		if (data == NULL) {
2672 			RSU_DPRINTF(sc, RSU_DEBUG_TXDONE,
2673 			    "%s: empty pending queue sc %p\n", __func__, sc);
2674 			return;
2675 		}
2676 		STAILQ_REMOVE_HEAD(&sc->sc_tx_pending[which], next);
2677 		STAILQ_INSERT_TAIL(&sc->sc_tx_active[which], data, next);
2678 		usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen);
2679 		RSU_DPRINTF(sc, RSU_DEBUG_TXDONE,
2680 		    "%s: submitting transfer %p\n",
2681 		    __func__,
2682 		    data);
2683 		usbd_transfer_submit(xfer);
2684 		break;
2685 	default:
2686 		data = STAILQ_FIRST(&sc->sc_tx_active[which]);
2687 		if (data != NULL) {
2688 			STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
2689 			rsu_txeof(xfer, data);
2690 			rsu_freebuf(sc, data);
2691 		}
2692 		counter_u64_add(ic->ic_oerrors, 1);
2693 
2694 		if (error != USB_ERR_CANCELLED) {
2695 			usbd_xfer_set_stall(xfer);
2696 			goto tr_setup;
2697 		}
2698 		break;
2699 	}
2700 
2701 	/*
2702 	 * XXX TODO: if the queue is low, flush out FF TX frames.
2703 	 * Remember to unlock the driver for now; net80211 doesn't
2704 	 * defer it for us.
2705 	 */
2706 }
2707 
2708 static void
2709 rsu_bulk_tx_callback_be_bk(struct usb_xfer *xfer, usb_error_t error)
2710 {
2711 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2712 
2713 	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_BE_BK);
2714 
2715 	/* This kicks the TX taskqueue */
2716 	rsu_start(sc);
2717 }
2718 
2719 static void
2720 rsu_bulk_tx_callback_vi_vo(struct usb_xfer *xfer, usb_error_t error)
2721 {
2722 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2723 
2724 	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_VI_VO);
2725 
2726 	/* This kicks the TX taskqueue */
2727 	rsu_start(sc);
2728 }
2729 
2730 static void
2731 rsu_bulk_tx_callback_h2c(struct usb_xfer *xfer, usb_error_t error)
2732 {
2733 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2734 
2735 	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_H2C);
2736 
2737 	/* This kicks the TX taskqueue */
2738 	rsu_start(sc);
2739 }
2740 
2741 /*
2742  * Transmit the given frame.
2743  *
2744  * This doesn't free the node or mbuf upon failure.
2745  */
2746 static int
2747 rsu_tx_start(struct rsu_softc *sc, struct ieee80211_node *ni,
2748     struct mbuf *m0, struct rsu_data *data)
2749 {
2750 	const struct ieee80211_txparam *tp = ni->ni_txparms;
2751         struct ieee80211vap *vap = ni->ni_vap;
2752 	struct ieee80211_frame *wh;
2753 	struct ieee80211_key *k = NULL;
2754 	struct r92s_tx_desc *txd;
2755 	uint8_t rate, ridx, type, cipher, qos;
2756 	int prio = 0;
2757 	uint8_t which;
2758 	int hasqos;
2759 	int ismcast;
2760 	int xferlen;
2761 	int qid;
2762 
2763 	RSU_ASSERT_LOCKED(sc);
2764 
2765 	wh = mtod(m0, struct ieee80211_frame *);
2766 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2767 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
2768 
2769 	RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: data=%p, m=%p\n",
2770 	    __func__, data, m0);
2771 
2772 	/* Choose a TX rate index. */
2773 	if (type == IEEE80211_FC0_TYPE_MGT ||
2774 	    type == IEEE80211_FC0_TYPE_CTL ||
2775 	    (m0->m_flags & M_EAPOL) != 0)
2776 		rate = tp->mgmtrate;
2777 	else if (ismcast)
2778 		rate = tp->mcastrate;
2779 	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
2780 		rate = tp->ucastrate;
2781 	else
2782 		rate = 0;
2783 
2784 	if (rate != 0)
2785 		ridx = rate2ridx(rate);
2786 
2787 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
2788 		k = ieee80211_crypto_encap(ni, m0);
2789 		if (k == NULL) {
2790 			device_printf(sc->sc_dev,
2791 			    "ieee80211_crypto_encap returns NULL.\n");
2792 			/* XXX we don't expect the fragmented frames */
2793 			return (ENOBUFS);
2794 		}
2795 		wh = mtod(m0, struct ieee80211_frame *);
2796 	}
2797 	/* If we have QoS then use it */
2798 	/* XXX TODO: mbuf WME/PRI versus TID? */
2799 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
2800 		/* Has QoS */
2801 		prio = M_WME_GETAC(m0);
2802 		which = rsu_wme_ac_xfer_map[prio];
2803 		hasqos = 1;
2804 		qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
2805 	} else {
2806 		/* Non-QoS TID */
2807 		/* XXX TODO: tid=0 for non-qos TID? */
2808 		which = rsu_wme_ac_xfer_map[WME_AC_BE];
2809 		hasqos = 0;
2810 		prio = 0;
2811 		qos = 0;
2812 	}
2813 
2814 	qid = rsu_ac2qid[prio];
2815 #if 0
2816 	switch (type) {
2817 	case IEEE80211_FC0_TYPE_CTL:
2818 	case IEEE80211_FC0_TYPE_MGT:
2819 		which = rsu_wme_ac_xfer_map[WME_AC_VO];
2820 		break;
2821 	default:
2822 		which = rsu_wme_ac_xfer_map[M_WME_GETAC(m0)];
2823 		break;
2824 	}
2825 	hasqos = 0;
2826 #endif
2827 
2828 	RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: pri=%d, which=%d, hasqos=%d\n",
2829 	    __func__,
2830 	    prio,
2831 	    which,
2832 	    hasqos);
2833 
2834 	/* Fill Tx descriptor. */
2835 	txd = (struct r92s_tx_desc *)data->buf;
2836 	memset(txd, 0, sizeof(*txd));
2837 
2838 	txd->txdw0 |= htole32(
2839 	    SM(R92S_TXDW0_PKTLEN, m0->m_pkthdr.len) |
2840 	    SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
2841 	    R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
2842 
2843 	txd->txdw1 |= htole32(
2844 	    SM(R92S_TXDW1_MACID, R92S_MACID_BSS) | SM(R92S_TXDW1_QSEL, qid));
2845 	if (!hasqos)
2846 		txd->txdw1 |= htole32(R92S_TXDW1_NONQOS);
2847 	if (k != NULL && !(k->wk_flags & IEEE80211_KEY_SWENCRYPT)) {
2848 		switch (k->wk_cipher->ic_cipher) {
2849 		case IEEE80211_CIPHER_WEP:
2850 			cipher = R92S_TXDW1_CIPHER_WEP;
2851 			break;
2852 		case IEEE80211_CIPHER_TKIP:
2853 			cipher = R92S_TXDW1_CIPHER_TKIP;
2854 			break;
2855 		case IEEE80211_CIPHER_AES_CCM:
2856 			cipher = R92S_TXDW1_CIPHER_AES;
2857 			break;
2858 		default:
2859 			cipher = R92S_TXDW1_CIPHER_NONE;
2860 		}
2861 		txd->txdw1 |= htole32(
2862 		    SM(R92S_TXDW1_CIPHER, cipher) |
2863 		    SM(R92S_TXDW1_KEYIDX, k->wk_keyix));
2864 	}
2865 	/* XXX todo: set AGGEN bit if appropriate? */
2866 	txd->txdw2 |= htole32(R92S_TXDW2_BK);
2867 	if (ismcast)
2868 		txd->txdw2 |= htole32(R92S_TXDW2_BMCAST);
2869 
2870 	if (!ismcast && (!qos || (qos & IEEE80211_QOS_ACKPOLICY) !=
2871 	    IEEE80211_QOS_ACKPOLICY_NOACK)) {
2872 		txd->txdw2 |= htole32(R92S_TXDW2_RTY_LMT_ENA);
2873 		txd->txdw2 |= htole32(SM(R92S_TXDW2_RTY_LMT, tp->maxretry));
2874 	}
2875 
2876 	/* Force mgmt / mcast / ucast rate if needed. */
2877 	if (rate != 0) {
2878 		/* Data rate fallback limit (max). */
2879 		txd->txdw5 |= htole32(SM(R92S_TXDW5_DATARATE_FB_LMT, 0x1f));
2880 		txd->txdw5 |= htole32(SM(R92S_TXDW5_DATARATE, ridx));
2881 		txd->txdw4 |= htole32(R92S_TXDW4_DRVRATE);
2882 	}
2883 
2884 	/*
2885 	 * Firmware will use and increment the sequence number for the
2886 	 * specified priority.
2887 	 */
2888 	txd->txdw3 |= htole32(SM(R92S_TXDW3_SEQ, prio));
2889 
2890 	if (ieee80211_radiotap_active_vap(vap)) {
2891 		struct rsu_tx_radiotap_header *tap = &sc->sc_txtap;
2892 
2893 		tap->wt_flags = 0;
2894 		ieee80211_radiotap_tx(vap, m0);
2895 	}
2896 
2897 	xferlen = sizeof(*txd) + m0->m_pkthdr.len;
2898 	m_copydata(m0, 0, m0->m_pkthdr.len, (caddr_t)&txd[1]);
2899 
2900 	data->buflen = xferlen;
2901 	data->ni = ni;
2902 	data->m = m0;
2903 	STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
2904 
2905 	/* start transfer, if any */
2906 	usbd_transfer_start(sc->sc_xfer[which]);
2907 	return (0);
2908 }
2909 
2910 static int
2911 rsu_transmit(struct ieee80211com *ic, struct mbuf *m)
2912 {
2913 	struct rsu_softc *sc = ic->ic_softc;
2914 	int error;
2915 
2916 	RSU_LOCK(sc);
2917 	if (!sc->sc_running) {
2918 		RSU_UNLOCK(sc);
2919 		return (ENXIO);
2920 	}
2921 
2922 	/*
2923 	 * XXX TODO: ensure that we treat 'm' as a list of frames
2924 	 * to transmit!
2925 	 */
2926 	error = mbufq_enqueue(&sc->sc_snd, m);
2927 	if (error) {
2928 		RSU_DPRINTF(sc, RSU_DEBUG_TX,
2929 		    "%s: mbufq_enable: failed (%d)\n",
2930 		    __func__,
2931 		    error);
2932 		RSU_UNLOCK(sc);
2933 		return (error);
2934 	}
2935 	RSU_UNLOCK(sc);
2936 
2937 	/* This kicks the TX taskqueue */
2938 	rsu_start(sc);
2939 
2940 	return (0);
2941 }
2942 
2943 static void
2944 rsu_drain_mbufq(struct rsu_softc *sc)
2945 {
2946 	struct mbuf *m;
2947 	struct ieee80211_node *ni;
2948 
2949 	RSU_ASSERT_LOCKED(sc);
2950 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
2951 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
2952 		m->m_pkthdr.rcvif = NULL;
2953 		ieee80211_free_node(ni);
2954 		m_freem(m);
2955 	}
2956 }
2957 
2958 static void
2959 _rsu_start(struct rsu_softc *sc)
2960 {
2961 	struct ieee80211_node *ni;
2962 	struct rsu_data *bf;
2963 	struct mbuf *m;
2964 
2965 	RSU_ASSERT_LOCKED(sc);
2966 
2967 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
2968 		bf = rsu_getbuf(sc);
2969 		if (bf == NULL) {
2970 			RSU_DPRINTF(sc, RSU_DEBUG_TX,
2971 			    "%s: failed to get buffer\n", __func__);
2972 			mbufq_prepend(&sc->sc_snd, m);
2973 			break;
2974 		}
2975 
2976 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
2977 		m->m_pkthdr.rcvif = NULL;
2978 
2979 		if (rsu_tx_start(sc, ni, m, bf) != 0) {
2980 			RSU_DPRINTF(sc, RSU_DEBUG_TX,
2981 			    "%s: failed to transmit\n", __func__);
2982 			if_inc_counter(ni->ni_vap->iv_ifp,
2983 			    IFCOUNTER_OERRORS, 1);
2984 			rsu_freebuf(sc, bf);
2985 			ieee80211_free_node(ni);
2986 			m_freem(m);
2987 			break;
2988 		}
2989 	}
2990 }
2991 
2992 static void
2993 rsu_start(struct rsu_softc *sc)
2994 {
2995 
2996 	taskqueue_enqueue(taskqueue_thread, &sc->tx_task);
2997 }
2998 
2999 static int
3000 rsu_ioctl_net(struct ieee80211com *ic, u_long cmd, void *data)
3001 {
3002 	struct rsu_softc *sc = ic->ic_softc;
3003 	struct ifreq *ifr = (struct ifreq *)data;
3004 	int error;
3005 
3006 	error = 0;
3007 	switch (cmd) {
3008 	case SIOCSIFCAP:
3009 	{
3010 		struct ieee80211vap *vap;
3011 		int rxmask;
3012 
3013 		rxmask = ifr->ifr_reqcap & (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6);
3014 
3015 		RSU_LOCK(sc);
3016 		/* Both RXCSUM bits must be set (or unset). */
3017 		if (sc->sc_rx_checksum_enable &&
3018 		    rxmask != (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6)) {
3019 			rxmask = 0;
3020 			sc->sc_rx_checksum_enable = 0;
3021 			rsu_rxfilter_set(sc, R92S_RCR_TCP_OFFLD_EN, 0);
3022 		} else if (!sc->sc_rx_checksum_enable && rxmask != 0) {
3023 			rxmask = IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6;
3024 			sc->sc_rx_checksum_enable = 1;
3025 			rsu_rxfilter_set(sc, 0, R92S_RCR_TCP_OFFLD_EN);
3026 		} else {
3027 			/* Nothing to do. */
3028 			RSU_UNLOCK(sc);
3029 			break;
3030 		}
3031 		RSU_UNLOCK(sc);
3032 
3033 		IEEE80211_LOCK(ic);	/* XXX */
3034 		TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
3035 			struct ifnet *ifp = vap->iv_ifp;
3036 
3037 			ifp->if_capenable &=
3038 			    ~(IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6);
3039 			ifp->if_capenable |= rxmask;
3040 		}
3041 		IEEE80211_UNLOCK(ic);
3042 		break;
3043 	}
3044 	default:
3045 		error = ENOTTY;		/* for net80211 */
3046 		break;
3047 	}
3048 
3049 	return (error);
3050 }
3051 
3052 static void
3053 rsu_parent(struct ieee80211com *ic)
3054 {
3055 	struct rsu_softc *sc = ic->ic_softc;
3056 
3057 	if (ic->ic_nrunning > 0) {
3058 		if (rsu_init(sc) == 0)
3059 			ieee80211_start_all(ic);
3060 		else {
3061 			struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3062 			if (vap != NULL)
3063 				ieee80211_stop(vap);
3064 		}
3065 	} else
3066 		rsu_stop(sc);
3067 }
3068 
3069 /*
3070  * Power on sequence for A-cut adapters.
3071  */
3072 static void
3073 rsu_power_on_acut(struct rsu_softc *sc)
3074 {
3075 	uint32_t reg;
3076 
3077 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
3078 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
3079 
3080 	/* Enable AFE macro block's bandgap and Mbias. */
3081 	rsu_write_1(sc, R92S_AFE_MISC,
3082 	    rsu_read_1(sc, R92S_AFE_MISC) |
3083 	    R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN);
3084 	/* Enable LDOA15 block. */
3085 	rsu_write_1(sc, R92S_LDOA15_CTRL,
3086 	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
3087 
3088 	rsu_write_1(sc, R92S_SPS1_CTRL,
3089 	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_LDEN);
3090 	rsu_ms_delay(sc, 2000);
3091 	/* Enable switch regulator block. */
3092 	rsu_write_1(sc, R92S_SPS1_CTRL,
3093 	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_SWEN);
3094 
3095 	rsu_write_4(sc, R92S_SPS1_CTRL, 0x00a7b267);
3096 
3097 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3098 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
3099 
3100 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3101 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
3102 
3103 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3104 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x90);
3105 
3106 	/* Enable AFE clock. */
3107 	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
3108 	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
3109 	/* Enable AFE PLL macro block. */
3110 	rsu_write_1(sc, R92S_AFE_PLL_CTRL,
3111 	    rsu_read_1(sc, R92S_AFE_PLL_CTRL) | 0x11);
3112 	/* Attach AFE PLL to MACTOP/BB. */
3113 	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
3114 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
3115 
3116 	/* Switch to 40MHz clock instead of 80MHz. */
3117 	rsu_write_2(sc, R92S_SYS_CLKR,
3118 	    rsu_read_2(sc, R92S_SYS_CLKR) & ~R92S_SYS_CLKSEL);
3119 
3120 	/* Enable MAC clock. */
3121 	rsu_write_2(sc, R92S_SYS_CLKR,
3122 	    rsu_read_2(sc, R92S_SYS_CLKR) |
3123 	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
3124 
3125 	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
3126 
3127 	/* Enable digital core and IOREG R/W. */
3128 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3129 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
3130 
3131 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3132 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
3133 
3134 	/* Switch the control path to firmware. */
3135 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
3136 	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
3137 	rsu_write_2(sc, R92S_SYS_CLKR, reg);
3138 
3139 	rsu_write_2(sc, R92S_CR, 0x37fc);
3140 
3141 	/* Fix USB RX FIFO issue. */
3142 	rsu_write_1(sc, 0xfe5c,
3143 	    rsu_read_1(sc, 0xfe5c) | 0x80);
3144 	rsu_write_1(sc, 0x00ab,
3145 	    rsu_read_1(sc, 0x00ab) | 0xc0);
3146 
3147 	rsu_write_1(sc, R92S_SYS_CLKR,
3148 	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
3149 }
3150 
3151 /*
3152  * Power on sequence for B-cut and C-cut adapters.
3153  */
3154 static void
3155 rsu_power_on_bcut(struct rsu_softc *sc)
3156 {
3157 	uint32_t reg;
3158 	int ntries;
3159 
3160 	/* Prevent eFuse leakage. */
3161 	rsu_write_1(sc, 0x37, 0xb0);
3162 	rsu_ms_delay(sc, 10);
3163 	rsu_write_1(sc, 0x37, 0x30);
3164 
3165 	/* Switch the control path to hardware. */
3166 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
3167 	if (reg & R92S_FWHW_SEL) {
3168 		rsu_write_2(sc, R92S_SYS_CLKR,
3169 		    reg & ~(R92S_SWHW_SEL | R92S_FWHW_SEL));
3170 	}
3171 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3172 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) & ~0x8c);
3173 	rsu_ms_delay(sc, 1);
3174 
3175 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
3176 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
3177 
3178 	reg = rsu_read_1(sc, R92S_AFE_MISC);
3179 	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN);
3180 	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN |
3181 	    R92S_AFE_MISC_MBEN | R92S_AFE_MISC_I32_EN);
3182 
3183 	/* Enable PLL. */
3184 	rsu_write_1(sc, R92S_LDOA15_CTRL,
3185 	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
3186 
3187 	rsu_write_1(sc, R92S_LDOV12D_CTRL,
3188 	    rsu_read_1(sc, R92S_LDOV12D_CTRL) | R92S_LDV12_EN);
3189 
3190 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3191 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
3192 
3193 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3194 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
3195 
3196 	/* Support 64KB IMEM. */
3197 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3198 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x97);
3199 
3200 	/* Enable AFE clock. */
3201 	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
3202 	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
3203 	/* Enable AFE PLL macro block. */
3204 	reg = rsu_read_1(sc, R92S_AFE_PLL_CTRL);
3205 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
3206 	rsu_ms_delay(sc, 1);
3207 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x51);
3208 	rsu_ms_delay(sc, 1);
3209 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
3210 	rsu_ms_delay(sc, 1);
3211 
3212 	/* Attach AFE PLL to MACTOP/BB. */
3213 	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
3214 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
3215 
3216 	/* Switch to 40MHz clock. */
3217 	rsu_write_1(sc, R92S_SYS_CLKR, 0x00);
3218 	/* Disable CPU clock and 80MHz SSC. */
3219 	rsu_write_1(sc, R92S_SYS_CLKR,
3220 	    rsu_read_1(sc, R92S_SYS_CLKR) | 0xa0);
3221 	/* Enable MAC clock. */
3222 	rsu_write_2(sc, R92S_SYS_CLKR,
3223 	    rsu_read_2(sc, R92S_SYS_CLKR) |
3224 	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
3225 
3226 	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
3227 
3228 	/* Enable digital core and IOREG R/W. */
3229 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3230 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
3231 
3232 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3233 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
3234 
3235 	/* Switch the control path to firmware. */
3236 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
3237 	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
3238 	rsu_write_2(sc, R92S_SYS_CLKR, reg);
3239 
3240 	rsu_write_2(sc, R92S_CR, 0x37fc);
3241 
3242 	/* Fix USB RX FIFO issue. */
3243 	rsu_write_1(sc, 0xfe5c,
3244 	    rsu_read_1(sc, 0xfe5c) | 0x80);
3245 
3246 	rsu_write_1(sc, R92S_SYS_CLKR,
3247 	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
3248 
3249 	rsu_write_1(sc, 0xfe1c, 0x80);
3250 
3251 	/* Make sure TxDMA is ready to download firmware. */
3252 	for (ntries = 0; ntries < 20; ntries++) {
3253 		reg = rsu_read_1(sc, R92S_TCR);
3254 		if ((reg & (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) ==
3255 		    (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT))
3256 			break;
3257 		rsu_ms_delay(sc, 1);
3258 	}
3259 	if (ntries == 20) {
3260 		RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_TX,
3261 		    "%s: TxDMA is not ready\n",
3262 		    __func__);
3263 		/* Reset TxDMA. */
3264 		reg = rsu_read_1(sc, R92S_CR);
3265 		rsu_write_1(sc, R92S_CR, reg & ~R92S_CR_TXDMA_EN);
3266 		rsu_ms_delay(sc, 1);
3267 		rsu_write_1(sc, R92S_CR, reg | R92S_CR_TXDMA_EN);
3268 	}
3269 }
3270 
3271 static void
3272 rsu_power_off(struct rsu_softc *sc)
3273 {
3274 	/* Turn RF off. */
3275 	rsu_write_1(sc, R92S_RF_CTRL, 0x00);
3276 	rsu_ms_delay(sc, 5);
3277 
3278 	/* Turn MAC off. */
3279 	/* Switch control path. */
3280 	rsu_write_1(sc, R92S_SYS_CLKR + 1, 0x38);
3281 	/* Reset MACTOP. */
3282 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x70);
3283 	rsu_write_1(sc, R92S_PMC_FSM, 0x06);
3284 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 0, 0xf9);
3285 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, 0xe8);
3286 
3287 	/* Disable AFE PLL. */
3288 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, 0x00);
3289 	/* Disable A15V. */
3290 	rsu_write_1(sc, R92S_LDOA15_CTRL, 0x54);
3291 	/* Disable eFuse 1.2V. */
3292 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x50);
3293 	rsu_write_1(sc, R92S_LDOV12D_CTRL, 0x24);
3294 	/* Enable AFE macro block's bandgap and Mbias. */
3295 	rsu_write_1(sc, R92S_AFE_MISC, 0x30);
3296 	/* Disable 1.6V LDO. */
3297 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x56);
3298 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x43);
3299 
3300 	/* Firmware - tell it to switch things off */
3301 	(void) rsu_set_fw_power_state(sc, RSU_PWR_OFF);
3302 }
3303 
3304 static int
3305 rsu_fw_loadsection(struct rsu_softc *sc, const uint8_t *buf, int len)
3306 {
3307 	const uint8_t which = rsu_wme_ac_xfer_map[WME_AC_VO];
3308 	struct rsu_data *data;
3309 	struct r92s_tx_desc *txd;
3310 	int mlen;
3311 
3312 	while (len > 0) {
3313 		data = rsu_getbuf(sc);
3314 		if (data == NULL)
3315 			return (ENOMEM);
3316 		txd = (struct r92s_tx_desc *)data->buf;
3317 		memset(txd, 0, sizeof(*txd));
3318 		if (len <= RSU_TXBUFSZ - sizeof(*txd)) {
3319 			/* Last chunk. */
3320 			txd->txdw0 |= htole32(R92S_TXDW0_LINIP);
3321 			mlen = len;
3322 		} else
3323 			mlen = RSU_TXBUFSZ - sizeof(*txd);
3324 		txd->txdw0 |= htole32(SM(R92S_TXDW0_PKTLEN, mlen));
3325 		memcpy(&txd[1], buf, mlen);
3326 		data->buflen = sizeof(*txd) + mlen;
3327 		RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FW | RSU_DEBUG_RESET,
3328 		    "%s: starting transfer %p\n",
3329 		    __func__, data);
3330 		STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
3331 		buf += mlen;
3332 		len -= mlen;
3333 	}
3334 	usbd_transfer_start(sc->sc_xfer[which]);
3335 	return (0);
3336 }
3337 
3338 CTASSERT(sizeof(size_t) >= sizeof(uint32_t));
3339 
3340 static int
3341 rsu_load_firmware(struct rsu_softc *sc)
3342 {
3343 	const struct r92s_fw_hdr *hdr;
3344 	struct r92s_fw_priv *dmem;
3345 	struct ieee80211com *ic = &sc->sc_ic;
3346 	const uint8_t *imem, *emem;
3347 	uint32_t imemsz, ememsz;
3348 	const struct firmware *fw;
3349 	size_t size;
3350 	uint32_t reg;
3351 	int ntries, error;
3352 
3353 	if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY) {
3354 		RSU_DPRINTF(sc, RSU_DEBUG_ANY,
3355 		    "%s: Firmware already loaded\n",
3356 		    __func__);
3357 		return (0);
3358 	}
3359 
3360 	RSU_UNLOCK(sc);
3361 	/* Read firmware image from the filesystem. */
3362 	if ((fw = firmware_get("rsu-rtl8712fw")) == NULL) {
3363 		device_printf(sc->sc_dev,
3364 		    "%s: failed load firmware of file rsu-rtl8712fw\n",
3365 		    __func__);
3366 		RSU_LOCK(sc);
3367 		return (ENXIO);
3368 	}
3369 	RSU_LOCK(sc);
3370 	size = fw->datasize;
3371 	if (size < sizeof(*hdr)) {
3372 		device_printf(sc->sc_dev, "firmware too short\n");
3373 		error = EINVAL;
3374 		goto fail;
3375 	}
3376 	hdr = (const struct r92s_fw_hdr *)fw->data;
3377 	if (hdr->signature != htole16(0x8712) &&
3378 	    hdr->signature != htole16(0x8192)) {
3379 		device_printf(sc->sc_dev,
3380 		    "invalid firmware signature 0x%x\n",
3381 		    le16toh(hdr->signature));
3382 		error = EINVAL;
3383 		goto fail;
3384 	}
3385 	RSU_DPRINTF(sc, RSU_DEBUG_FW, "FW V%d %02x-%02x %02x:%02x\n",
3386 	    le16toh(hdr->version), hdr->month, hdr->day, hdr->hour,
3387 	    hdr->minute);
3388 
3389 	/* Make sure that driver and firmware are in sync. */
3390 	if (hdr->privsz != htole32(sizeof(*dmem))) {
3391 		device_printf(sc->sc_dev, "unsupported firmware image\n");
3392 		error = EINVAL;
3393 		goto fail;
3394 	}
3395 	/* Get FW sections sizes. */
3396 	imemsz = le32toh(hdr->imemsz);
3397 	ememsz = le32toh(hdr->sramsz);
3398 	/* Check that all FW sections fit in image. */
3399 	if (imemsz > (size_t)(size - sizeof(*hdr)) ||
3400 	    ememsz > (size_t)(size - sizeof(*hdr) - imemsz)) {
3401 		device_printf(sc->sc_dev, "firmware too short\n");
3402 		error = EINVAL;
3403 		goto fail;
3404 	}
3405 	imem = (const uint8_t *)&hdr[1];
3406 	emem = imem + imemsz;
3407 
3408 	/* Load IMEM section. */
3409 	error = rsu_fw_loadsection(sc, imem, imemsz);
3410 	if (error != 0) {
3411 		device_printf(sc->sc_dev,
3412 		    "could not load firmware section %s\n", "IMEM");
3413 		goto fail;
3414 	}
3415 	/* Wait for load to complete. */
3416 	for (ntries = 0; ntries != 50; ntries++) {
3417 		rsu_ms_delay(sc, 10);
3418 		reg = rsu_read_1(sc, R92S_TCR);
3419 		if (reg & R92S_TCR_IMEM_CODE_DONE)
3420 			break;
3421 	}
3422 	if (ntries == 50) {
3423 		device_printf(sc->sc_dev, "timeout waiting for IMEM transfer\n");
3424 		error = ETIMEDOUT;
3425 		goto fail;
3426 	}
3427 	/* Load EMEM section. */
3428 	error = rsu_fw_loadsection(sc, emem, ememsz);
3429 	if (error != 0) {
3430 		device_printf(sc->sc_dev,
3431 		    "could not load firmware section %s\n", "EMEM");
3432 		goto fail;
3433 	}
3434 	/* Wait for load to complete. */
3435 	for (ntries = 0; ntries != 50; ntries++) {
3436 		rsu_ms_delay(sc, 10);
3437 		reg = rsu_read_2(sc, R92S_TCR);
3438 		if (reg & R92S_TCR_EMEM_CODE_DONE)
3439 			break;
3440 	}
3441 	if (ntries == 50) {
3442 		device_printf(sc->sc_dev, "timeout waiting for EMEM transfer\n");
3443 		error = ETIMEDOUT;
3444 		goto fail;
3445 	}
3446 	/* Enable CPU. */
3447 	rsu_write_1(sc, R92S_SYS_CLKR,
3448 	    rsu_read_1(sc, R92S_SYS_CLKR) | R92S_SYS_CPU_CLKSEL);
3449 	if (!(rsu_read_1(sc, R92S_SYS_CLKR) & R92S_SYS_CPU_CLKSEL)) {
3450 		device_printf(sc->sc_dev, "could not enable system clock\n");
3451 		error = EIO;
3452 		goto fail;
3453 	}
3454 	rsu_write_2(sc, R92S_SYS_FUNC_EN,
3455 	    rsu_read_2(sc, R92S_SYS_FUNC_EN) | R92S_FEN_CPUEN);
3456 	if (!(rsu_read_2(sc, R92S_SYS_FUNC_EN) & R92S_FEN_CPUEN)) {
3457 		device_printf(sc->sc_dev,
3458 		    "could not enable microcontroller\n");
3459 		error = EIO;
3460 		goto fail;
3461 	}
3462 	/* Wait for CPU to initialize. */
3463 	for (ntries = 0; ntries < 100; ntries++) {
3464 		if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_IMEM_RDY)
3465 			break;
3466 		rsu_ms_delay(sc, 1);
3467 	}
3468 	if (ntries == 100) {
3469 		device_printf(sc->sc_dev,
3470 		    "timeout waiting for microcontroller\n");
3471 		error = ETIMEDOUT;
3472 		goto fail;
3473 	}
3474 
3475 	/* Update DMEM section before loading. */
3476 	dmem = __DECONST(struct r92s_fw_priv *, &hdr->priv);
3477 	memset(dmem, 0, sizeof(*dmem));
3478 	dmem->hci_sel = R92S_HCI_SEL_USB | R92S_HCI_SEL_8172;
3479 	dmem->nendpoints = sc->sc_nendpoints;
3480 	dmem->chip_version = sc->cut;
3481 	dmem->rf_config = sc->sc_rftype;
3482 	dmem->vcs_type = R92S_VCS_TYPE_AUTO;
3483 	dmem->vcs_mode = R92S_VCS_MODE_RTS_CTS;
3484 	dmem->turbo_mode = 0;
3485 	dmem->bw40_en = !! (ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40);
3486 	dmem->amsdu2ampdu_en = !! (sc->sc_ht);
3487 	dmem->ampdu_en = !! (sc->sc_ht);
3488 	dmem->agg_offload = !! (sc->sc_ht);
3489 	dmem->qos_en = 1;
3490 	dmem->ps_offload = 1;
3491 	dmem->lowpower_mode = 1;	/* XXX TODO: configurable? */
3492 	/* Load DMEM section. */
3493 	error = rsu_fw_loadsection(sc, (uint8_t *)dmem, sizeof(*dmem));
3494 	if (error != 0) {
3495 		device_printf(sc->sc_dev,
3496 		    "could not load firmware section %s\n", "DMEM");
3497 		goto fail;
3498 	}
3499 	/* Wait for load to complete. */
3500 	for (ntries = 0; ntries < 100; ntries++) {
3501 		if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_DMEM_CODE_DONE)
3502 			break;
3503 		rsu_ms_delay(sc, 1);
3504 	}
3505 	if (ntries == 100) {
3506 		device_printf(sc->sc_dev, "timeout waiting for %s transfer\n",
3507 		    "DMEM");
3508 		error = ETIMEDOUT;
3509 		goto fail;
3510 	}
3511 	/* Wait for firmware readiness. */
3512 	for (ntries = 0; ntries < 60; ntries++) {
3513 		if (!(rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY))
3514 			break;
3515 		rsu_ms_delay(sc, 1);
3516 	}
3517 	if (ntries == 60) {
3518 		device_printf(sc->sc_dev,
3519 		    "timeout waiting for firmware readiness\n");
3520 		error = ETIMEDOUT;
3521 		goto fail;
3522 	}
3523  fail:
3524 	firmware_put(fw, FIRMWARE_UNLOAD);
3525 	return (error);
3526 }
3527 
3528 
3529 static int
3530 rsu_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
3531     const struct ieee80211_bpf_params *params)
3532 {
3533 	struct ieee80211com *ic = ni->ni_ic;
3534 	struct rsu_softc *sc = ic->ic_softc;
3535 	struct rsu_data *bf;
3536 
3537 	/* prevent management frames from being sent if we're not ready */
3538 	if (!sc->sc_running) {
3539 		m_freem(m);
3540 		return (ENETDOWN);
3541 	}
3542 	RSU_LOCK(sc);
3543 	bf = rsu_getbuf(sc);
3544 	if (bf == NULL) {
3545 		m_freem(m);
3546 		RSU_UNLOCK(sc);
3547 		return (ENOBUFS);
3548 	}
3549 	if (rsu_tx_start(sc, ni, m, bf) != 0) {
3550 		m_freem(m);
3551 		rsu_freebuf(sc, bf);
3552 		RSU_UNLOCK(sc);
3553 		return (EIO);
3554 	}
3555 	RSU_UNLOCK(sc);
3556 
3557 	return (0);
3558 }
3559 
3560 static void
3561 rsu_rxfilter_init(struct rsu_softc *sc)
3562 {
3563 	uint32_t reg;
3564 
3565 	RSU_ASSERT_LOCKED(sc);
3566 
3567 	/* Setup multicast filter. */
3568 	rsu_set_multi(sc);
3569 
3570 	/* Adjust Rx filter. */
3571 	reg = rsu_read_4(sc, R92S_RCR);
3572 	reg &= ~R92S_RCR_AICV;
3573 	reg |= R92S_RCR_APP_PHYSTS;
3574 	if (sc->sc_rx_checksum_enable)
3575 		reg |= R92S_RCR_TCP_OFFLD_EN;
3576 	rsu_write_4(sc, R92S_RCR, reg);
3577 
3578 	/* Update dynamic Rx filter parts. */
3579 	rsu_rxfilter_refresh(sc);
3580 }
3581 
3582 static void
3583 rsu_rxfilter_set(struct rsu_softc *sc, uint32_t clear, uint32_t set)
3584 {
3585 	/* NB: firmware can touch this register too. */
3586 	rsu_write_4(sc, R92S_RCR,
3587 	   (rsu_read_4(sc, R92S_RCR) & ~clear) | set);
3588 }
3589 
3590 static void
3591 rsu_rxfilter_refresh(struct rsu_softc *sc)
3592 {
3593 	struct ieee80211com *ic = &sc->sc_ic;
3594 	uint32_t mask_all, mask_min;
3595 
3596 	RSU_ASSERT_LOCKED(sc);
3597 
3598 	/* NB: RCR_AMF / RXFLTMAP_MGT are used by firmware. */
3599 	mask_all = R92S_RCR_ACF | R92S_RCR_AAP;
3600 	mask_min = R92S_RCR_APM;
3601 	if (sc->sc_vap_is_running)
3602 		mask_min |= R92S_RCR_CBSSID;
3603 	else
3604 		mask_all |= R92S_RCR_ADF;
3605 
3606 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
3607 		uint16_t rxfltmap;
3608 		if (sc->sc_vap_is_running)
3609 			rxfltmap = 0;
3610 		else
3611 			rxfltmap = R92S_RXFLTMAP_MGT_DEF;
3612 		rsu_write_2(sc, R92S_RXFLTMAP_MGT, rxfltmap);
3613 	}
3614 
3615 	if (ic->ic_promisc == 0 && ic->ic_opmode != IEEE80211_M_MONITOR)
3616 		rsu_rxfilter_set(sc, mask_all, mask_min);
3617 	else
3618 		rsu_rxfilter_set(sc, mask_min, mask_all);
3619 }
3620 
3621 static int
3622 rsu_init(struct rsu_softc *sc)
3623 {
3624 	struct ieee80211com *ic = &sc->sc_ic;
3625 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3626 	uint8_t macaddr[IEEE80211_ADDR_LEN];
3627 	int error;
3628 	int i;
3629 
3630 	RSU_LOCK(sc);
3631 
3632 	if (sc->sc_running) {
3633 		RSU_UNLOCK(sc);
3634 		return (0);
3635 	}
3636 
3637 	/* Ensure the mbuf queue is drained */
3638 	rsu_drain_mbufq(sc);
3639 
3640 	/* Reset power management state. */
3641 	rsu_write_1(sc, R92S_USB_HRPWM, 0);
3642 
3643 	/* Power on adapter. */
3644 	if (sc->cut == 1)
3645 		rsu_power_on_acut(sc);
3646 	else
3647 		rsu_power_on_bcut(sc);
3648 
3649 	/* Load firmware. */
3650 	error = rsu_load_firmware(sc);
3651 	if (error != 0)
3652 		goto fail;
3653 
3654 	rsu_write_4(sc, R92S_CR,
3655 	    rsu_read_4(sc, R92S_CR) & ~0xff000000);
3656 
3657 	/* Use 128 bytes pages. */
3658 	rsu_write_1(sc, 0x00b5,
3659 	    rsu_read_1(sc, 0x00b5) | 0x01);
3660 	/* Enable USB Rx aggregation. */
3661 	rsu_write_1(sc, 0x00bd,
3662 	    rsu_read_1(sc, 0x00bd) | 0x80);
3663 	/* Set USB Rx aggregation threshold. */
3664 	rsu_write_1(sc, 0x00d9, 0x01);
3665 	/* Set USB Rx aggregation timeout (1.7ms/4). */
3666 	rsu_write_1(sc, 0xfe5b, 0x04);
3667 	/* Fix USB Rx FIFO issue. */
3668 	rsu_write_1(sc, 0xfe5c,
3669 	    rsu_read_1(sc, 0xfe5c) | 0x80);
3670 
3671 	/* Set MAC address. */
3672 	IEEE80211_ADDR_COPY(macaddr, vap ? vap->iv_myaddr : ic->ic_macaddr);
3673 	rsu_write_region_1(sc, R92S_MACID, macaddr, IEEE80211_ADDR_LEN);
3674 
3675 	/* It really takes 1.5 seconds for the firmware to boot: */
3676 	usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(2000));
3677 
3678 	RSU_DPRINTF(sc, RSU_DEBUG_RESET, "%s: setting MAC address to %s\n",
3679 	    __func__,
3680 	    ether_sprintf(macaddr));
3681 	error = rsu_fw_cmd(sc, R92S_CMD_SET_MAC_ADDRESS, macaddr,
3682 	    IEEE80211_ADDR_LEN);
3683 	if (error != 0) {
3684 		device_printf(sc->sc_dev, "could not set MAC address\n");
3685 		goto fail;
3686 	}
3687 
3688 	/* Initialize Rx filter. */
3689 	rsu_rxfilter_init(sc);
3690 
3691 	/* Set PS mode fully active */
3692 	error = rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
3693 	if (error != 0) {
3694 		device_printf(sc->sc_dev, "could not set PS mode\n");
3695 		goto fail;
3696 	}
3697 
3698 	/* Install static keys (if any). */
3699 	error = rsu_reinit_static_keys(sc);
3700 	if (error != 0)
3701 		goto fail;
3702 
3703 	sc->sc_extra_scan = 0;
3704 	usbd_transfer_start(sc->sc_xfer[RSU_BULK_RX]);
3705 
3706 	/* We're ready to go. */
3707 	sc->sc_running = 1;
3708 	RSU_UNLOCK(sc);
3709 
3710 	return (0);
3711 fail:
3712 	/* Need to stop all failed transfers, if any */
3713 	for (i = 0; i != RSU_N_TRANSFER; i++)
3714 		usbd_transfer_stop(sc->sc_xfer[i]);
3715 	RSU_UNLOCK(sc);
3716 
3717 	return (error);
3718 }
3719 
3720 static void
3721 rsu_stop(struct rsu_softc *sc)
3722 {
3723 	int i;
3724 
3725 	RSU_LOCK(sc);
3726 	if (!sc->sc_running) {
3727 		RSU_UNLOCK(sc);
3728 		return;
3729 	}
3730 
3731 	sc->sc_running = 0;
3732 	sc->sc_vap_is_running = 0;
3733 	sc->sc_calibrating = 0;
3734 	taskqueue_cancel_timeout(taskqueue_thread, &sc->calib_task, NULL);
3735 	taskqueue_cancel(taskqueue_thread, &sc->tx_task, NULL);
3736 
3737 	/* Power off adapter. */
3738 	rsu_power_off(sc);
3739 
3740 	/*
3741 	 * CAM is not accessible after shutdown;
3742 	 * all entries are marked (by firmware?) as invalid.
3743 	 */
3744 	memset(sc->free_keys_bmap, 0, sizeof(sc->free_keys_bmap));
3745 	memset(sc->keys_bmap, 0, sizeof(sc->keys_bmap));
3746 
3747 	for (i = 0; i < RSU_N_TRANSFER; i++)
3748 		usbd_transfer_stop(sc->sc_xfer[i]);
3749 
3750 	/* Ensure the mbuf queue is drained */
3751 	rsu_drain_mbufq(sc);
3752 	RSU_UNLOCK(sc);
3753 }
3754 
3755 /*
3756  * Note: usb_pause_mtx() actually releases the mutex before calling pause(),
3757  * which breaks any kind of driver serialisation.
3758  */
3759 static void
3760 rsu_ms_delay(struct rsu_softc *sc, int ms)
3761 {
3762 
3763 	//usb_pause_mtx(&sc->sc_mtx, hz / 1000);
3764 	DELAY(ms * 1000);
3765 }
3766