xref: /freebsd/sys/dev/usb/wlan/if_rsu.c (revision 325151a3)
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 h/w crypto
26  *   o hostap / ibss / mesh
27  *   o sensible RSSI levels
28  *   o power-save operation
29  */
30 
31 #include "opt_wlan.h"
32 
33 #include <sys/param.h>
34 #include <sys/endian.h>
35 #include <sys/sockio.h>
36 #include <sys/mbuf.h>
37 #include <sys/kernel.h>
38 #include <sys/socket.h>
39 #include <sys/systm.h>
40 #include <sys/conf.h>
41 #include <sys/bus.h>
42 #include <sys/rman.h>
43 #include <sys/firmware.h>
44 #include <sys/module.h>
45 
46 #include <machine/bus.h>
47 #include <machine/resource.h>
48 
49 #include <net/bpf.h>
50 #include <net/if.h>
51 #include <net/if_var.h>
52 #include <net/if_arp.h>
53 #include <net/if_dl.h>
54 #include <net/if_media.h>
55 #include <net/if_types.h>
56 
57 #include <netinet/in.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/in_var.h>
60 #include <netinet/if_ether.h>
61 #include <netinet/ip.h>
62 
63 #include <net80211/ieee80211_var.h>
64 #include <net80211/ieee80211_regdomain.h>
65 #include <net80211/ieee80211_radiotap.h>
66 
67 #include <dev/usb/usb.h>
68 #include <dev/usb/usbdi.h>
69 #include "usbdevs.h"
70 
71 #define USB_DEBUG_VAR rsu_debug
72 #include <dev/usb/usb_debug.h>
73 
74 #include <dev/usb/wlan/if_rsureg.h>
75 
76 #ifdef USB_DEBUG
77 static int rsu_debug = 0;
78 SYSCTL_NODE(_hw_usb, OID_AUTO, rsu, CTLFLAG_RW, 0, "USB rsu");
79 SYSCTL_INT(_hw_usb_rsu, OID_AUTO, debug, CTLFLAG_RWTUN, &rsu_debug, 0,
80     "Debug level");
81 #define	RSU_DPRINTF(_sc, _flg, ...)					\
82 	do								\
83 		if (((_flg) == (RSU_DEBUG_ANY)) || (rsu_debug & (_flg))) \
84 			device_printf((_sc)->sc_dev, __VA_ARGS__);	\
85 	while (0)
86 #else
87 #define	RSU_DPRINTF(_sc, _flg, ...)
88 #endif
89 
90 static int rsu_enable_11n = 1;
91 TUNABLE_INT("hw.usb.rsu.enable_11n", &rsu_enable_11n);
92 
93 #define	RSU_DEBUG_ANY		0xffffffff
94 #define	RSU_DEBUG_TX		0x00000001
95 #define	RSU_DEBUG_RX		0x00000002
96 #define	RSU_DEBUG_RESET		0x00000004
97 #define	RSU_DEBUG_CALIB		0x00000008
98 #define	RSU_DEBUG_STATE		0x00000010
99 #define	RSU_DEBUG_SCAN		0x00000020
100 #define	RSU_DEBUG_FWCMD		0x00000040
101 #define	RSU_DEBUG_TXDONE	0x00000080
102 #define	RSU_DEBUG_FW		0x00000100
103 #define	RSU_DEBUG_FWDBG		0x00000200
104 #define	RSU_DEBUG_AMPDU		0x00000400
105 
106 static const STRUCT_USB_HOST_ID rsu_devs[] = {
107 #define	RSU_HT_NOT_SUPPORTED 0
108 #define	RSU_HT_SUPPORTED 1
109 #define RSU_DEV_HT(v,p)  { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \
110 				   RSU_HT_SUPPORTED) }
111 #define RSU_DEV(v,p)     { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \
112 				   RSU_HT_NOT_SUPPORTED) }
113 	RSU_DEV(ASUS,			RTL8192SU),
114 	RSU_DEV(AZUREWAVE,		RTL8192SU_4),
115 	RSU_DEV_HT(ACCTON,		RTL8192SU),
116 	RSU_DEV_HT(ASUS,		USBN10),
117 	RSU_DEV_HT(AZUREWAVE,		RTL8192SU_1),
118 	RSU_DEV_HT(AZUREWAVE,		RTL8192SU_2),
119 	RSU_DEV_HT(AZUREWAVE,		RTL8192SU_3),
120 	RSU_DEV_HT(AZUREWAVE,		RTL8192SU_5),
121 	RSU_DEV_HT(BELKIN,		RTL8192SU_1),
122 	RSU_DEV_HT(BELKIN,		RTL8192SU_2),
123 	RSU_DEV_HT(BELKIN,		RTL8192SU_3),
124 	RSU_DEV_HT(CONCEPTRONIC2,	RTL8192SU_1),
125 	RSU_DEV_HT(CONCEPTRONIC2,	RTL8192SU_2),
126 	RSU_DEV_HT(CONCEPTRONIC2,	RTL8192SU_3),
127 	RSU_DEV_HT(COREGA,		RTL8192SU),
128 	RSU_DEV_HT(DLINK2,		DWA131A1),
129 	RSU_DEV_HT(DLINK2,		RTL8192SU_1),
130 	RSU_DEV_HT(DLINK2,		RTL8192SU_2),
131 	RSU_DEV_HT(EDIMAX,		RTL8192SU_1),
132 	RSU_DEV_HT(EDIMAX,		RTL8192SU_2),
133 	RSU_DEV_HT(EDIMAX,		EW7622UMN),
134 	RSU_DEV_HT(GUILLEMOT,		HWGUN54),
135 	RSU_DEV_HT(GUILLEMOT,		HWNUM300),
136 	RSU_DEV_HT(HAWKING,		RTL8192SU_1),
137 	RSU_DEV_HT(HAWKING,		RTL8192SU_2),
138 	RSU_DEV_HT(PLANEX2,		GWUSNANO),
139 	RSU_DEV_HT(REALTEK,		RTL8171),
140 	RSU_DEV_HT(REALTEK,		RTL8172),
141 	RSU_DEV_HT(REALTEK,		RTL8173),
142 	RSU_DEV_HT(REALTEK,		RTL8174),
143 	RSU_DEV_HT(REALTEK,		RTL8192SU),
144 	RSU_DEV_HT(REALTEK,		RTL8712),
145 	RSU_DEV_HT(REALTEK,		RTL8713),
146 	RSU_DEV_HT(SENAO,		RTL8192SU_1),
147 	RSU_DEV_HT(SENAO,		RTL8192SU_2),
148 	RSU_DEV_HT(SITECOMEU,		WL349V1),
149 	RSU_DEV_HT(SITECOMEU,		WL353),
150 	RSU_DEV_HT(SWEEX2,		LW154),
151 	RSU_DEV_HT(TRENDNET,		TEW646UBH),
152 #undef RSU_DEV_HT
153 #undef RSU_DEV
154 };
155 
156 static device_probe_t   rsu_match;
157 static device_attach_t  rsu_attach;
158 static device_detach_t  rsu_detach;
159 static usb_callback_t   rsu_bulk_tx_callback_be_bk;
160 static usb_callback_t   rsu_bulk_tx_callback_vi_vo;
161 static usb_callback_t   rsu_bulk_tx_callback_h2c;
162 static usb_callback_t   rsu_bulk_rx_callback;
163 static usb_error_t	rsu_do_request(struct rsu_softc *,
164 			    struct usb_device_request *, void *);
165 static struct ieee80211vap *
166 		rsu_vap_create(struct ieee80211com *, const char name[],
167 		    int, enum ieee80211_opmode, int, const uint8_t bssid[],
168 		    const uint8_t mac[]);
169 static void	rsu_vap_delete(struct ieee80211vap *);
170 static void	rsu_scan_start(struct ieee80211com *);
171 static void	rsu_scan_end(struct ieee80211com *);
172 static void	rsu_set_channel(struct ieee80211com *);
173 static void	rsu_update_mcast(struct ieee80211com *);
174 static int	rsu_alloc_rx_list(struct rsu_softc *);
175 static void	rsu_free_rx_list(struct rsu_softc *);
176 static int	rsu_alloc_tx_list(struct rsu_softc *);
177 static void	rsu_free_tx_list(struct rsu_softc *);
178 static void	rsu_free_list(struct rsu_softc *, struct rsu_data [], int);
179 static struct rsu_data *_rsu_getbuf(struct rsu_softc *);
180 static struct rsu_data *rsu_getbuf(struct rsu_softc *);
181 static void	rsu_freebuf(struct rsu_softc *, struct rsu_data *);
182 static int	rsu_write_region_1(struct rsu_softc *, uint16_t, uint8_t *,
183 		    int);
184 static void	rsu_write_1(struct rsu_softc *, uint16_t, uint8_t);
185 static void	rsu_write_2(struct rsu_softc *, uint16_t, uint16_t);
186 static void	rsu_write_4(struct rsu_softc *, uint16_t, uint32_t);
187 static int	rsu_read_region_1(struct rsu_softc *, uint16_t, uint8_t *,
188 		    int);
189 static uint8_t	rsu_read_1(struct rsu_softc *, uint16_t);
190 static uint16_t	rsu_read_2(struct rsu_softc *, uint16_t);
191 static uint32_t	rsu_read_4(struct rsu_softc *, uint16_t);
192 static int	rsu_fw_iocmd(struct rsu_softc *, uint32_t);
193 static uint8_t	rsu_efuse_read_1(struct rsu_softc *, uint16_t);
194 static int	rsu_read_rom(struct rsu_softc *);
195 static int	rsu_fw_cmd(struct rsu_softc *, uint8_t, void *, int);
196 static void	rsu_calib_task(void *, int);
197 static void	rsu_tx_task(void *, int);
198 static int	rsu_newstate(struct ieee80211vap *, enum ieee80211_state, int);
199 #ifdef notyet
200 static void	rsu_set_key(struct rsu_softc *, const struct ieee80211_key *);
201 static void	rsu_delete_key(struct rsu_softc *, const struct ieee80211_key *);
202 #endif
203 static int	rsu_site_survey(struct rsu_softc *, struct ieee80211vap *);
204 static int	rsu_join_bss(struct rsu_softc *, struct ieee80211_node *);
205 static int	rsu_disconnect(struct rsu_softc *);
206 static int	rsu_hwrssi_to_rssi(struct rsu_softc *, int hw_rssi);
207 static void	rsu_event_survey(struct rsu_softc *, uint8_t *, int);
208 static void	rsu_event_join_bss(struct rsu_softc *, uint8_t *, int);
209 static void	rsu_rx_event(struct rsu_softc *, uint8_t, uint8_t *, int);
210 static void	rsu_rx_multi_event(struct rsu_softc *, uint8_t *, int);
211 #if 0
212 static int8_t	rsu_get_rssi(struct rsu_softc *, int, void *);
213 #endif
214 static struct mbuf * rsu_rx_frame(struct rsu_softc *, uint8_t *, int);
215 static struct mbuf * rsu_rx_multi_frame(struct rsu_softc *, uint8_t *, int);
216 static struct mbuf *
217 		rsu_rxeof(struct usb_xfer *, struct rsu_data *);
218 static void	rsu_txeof(struct usb_xfer *, struct rsu_data *);
219 static int	rsu_raw_xmit(struct ieee80211_node *, struct mbuf *,
220 		    const struct ieee80211_bpf_params *);
221 static void	rsu_init(struct rsu_softc *);
222 static int	rsu_tx_start(struct rsu_softc *, struct ieee80211_node *,
223 		    struct mbuf *, struct rsu_data *);
224 static int	rsu_transmit(struct ieee80211com *, struct mbuf *);
225 static void	rsu_start(struct rsu_softc *);
226 static void	_rsu_start(struct rsu_softc *);
227 static void	rsu_parent(struct ieee80211com *);
228 static void	rsu_stop(struct rsu_softc *);
229 static void	rsu_ms_delay(struct rsu_softc *, int);
230 
231 static device_method_t rsu_methods[] = {
232 	DEVMETHOD(device_probe,		rsu_match),
233 	DEVMETHOD(device_attach,	rsu_attach),
234 	DEVMETHOD(device_detach,	rsu_detach),
235 
236 	DEVMETHOD_END
237 };
238 
239 static driver_t rsu_driver = {
240 	.name = "rsu",
241 	.methods = rsu_methods,
242 	.size = sizeof(struct rsu_softc)
243 };
244 
245 static devclass_t rsu_devclass;
246 
247 DRIVER_MODULE(rsu, uhub, rsu_driver, rsu_devclass, NULL, 0);
248 MODULE_DEPEND(rsu, wlan, 1, 1, 1);
249 MODULE_DEPEND(rsu, usb, 1, 1, 1);
250 MODULE_DEPEND(rsu, firmware, 1, 1, 1);
251 MODULE_VERSION(rsu, 1);
252 
253 static uint8_t rsu_wme_ac_xfer_map[4] = {
254 	[WME_AC_BE] = RSU_BULK_TX_BE_BK,
255 	[WME_AC_BK] = RSU_BULK_TX_BE_BK,
256 	[WME_AC_VI] = RSU_BULK_TX_VI_VO,
257 	[WME_AC_VO] = RSU_BULK_TX_VI_VO,
258 };
259 
260 /* XXX hard-coded */
261 #define	RSU_H2C_ENDPOINT	3
262 
263 static const struct usb_config rsu_config[RSU_N_TRANSFER] = {
264 	[RSU_BULK_RX] = {
265 		.type = UE_BULK,
266 		.endpoint = UE_ADDR_ANY,
267 		.direction = UE_DIR_IN,
268 		.bufsize = RSU_RXBUFSZ,
269 		.flags = {
270 			.pipe_bof = 1,
271 			.short_xfer_ok = 1
272 		},
273 		.callback = rsu_bulk_rx_callback
274 	},
275 	[RSU_BULK_TX_BE_BK] = {
276 		.type = UE_BULK,
277 		.endpoint = 0x06,
278 		.direction = UE_DIR_OUT,
279 		.bufsize = RSU_TXBUFSZ,
280 		.flags = {
281 			.ext_buffer = 1,
282 			.pipe_bof = 1,
283 			.force_short_xfer = 1
284 		},
285 		.callback = rsu_bulk_tx_callback_be_bk,
286 		.timeout = RSU_TX_TIMEOUT
287 	},
288 	[RSU_BULK_TX_VI_VO] = {
289 		.type = UE_BULK,
290 		.endpoint = 0x04,
291 		.direction = UE_DIR_OUT,
292 		.bufsize = RSU_TXBUFSZ,
293 		.flags = {
294 			.ext_buffer = 1,
295 			.pipe_bof = 1,
296 			.force_short_xfer = 1
297 		},
298 		.callback = rsu_bulk_tx_callback_vi_vo,
299 		.timeout = RSU_TX_TIMEOUT
300 	},
301 	[RSU_BULK_TX_H2C] = {
302 		.type = UE_BULK,
303 		.endpoint = 0x0d,
304 		.direction = UE_DIR_OUT,
305 		.bufsize = RSU_TXBUFSZ,
306 		.flags = {
307 			.ext_buffer = 1,
308 			.pipe_bof = 1,
309 			.short_xfer_ok = 1
310 		},
311 		.callback = rsu_bulk_tx_callback_h2c,
312 		.timeout = RSU_TX_TIMEOUT
313 	},
314 };
315 
316 static int
317 rsu_match(device_t self)
318 {
319 	struct usb_attach_arg *uaa = device_get_ivars(self);
320 
321 	if (uaa->usb_mode != USB_MODE_HOST ||
322 	    uaa->info.bIfaceIndex != 0 ||
323 	    uaa->info.bConfigIndex != 0)
324 		return (ENXIO);
325 
326 	return (usbd_lookup_id_by_uaa(rsu_devs, sizeof(rsu_devs), uaa));
327 }
328 
329 static int
330 rsu_send_mgmt(struct ieee80211_node *ni, int type, int arg)
331 {
332 
333 	return (ENOTSUP);
334 }
335 
336 static void
337 rsu_update_chw(struct ieee80211com *ic)
338 {
339 
340 }
341 
342 /*
343  * notification from net80211 that it'd like to do A-MPDU on the given TID.
344  *
345  * Note: this actually hangs traffic at the present moment, so don't use it.
346  * The firmware debug does indiciate it's sending and establishing a TX AMPDU
347  * session, but then no traffic flows.
348  */
349 static int
350 rsu_ampdu_enable(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
351 {
352 #if 0
353 	struct rsu_softc *sc = ni->ni_ic->ic_softc;
354 	struct r92s_add_ba_req req;
355 
356 	/* Don't enable if it's requested or running */
357 	if (IEEE80211_AMPDU_REQUESTED(tap))
358 		return (0);
359 	if (IEEE80211_AMPDU_RUNNING(tap))
360 		return (0);
361 
362 	/* We've decided to send addba; so send it */
363 	req.tid = htole32(tap->txa_tid);
364 
365 	/* Attempt net80211 state */
366 	if (ieee80211_ampdu_tx_request_ext(ni, tap->txa_tid) != 1)
367 		return (0);
368 
369 	/* Send the firmware command */
370 	RSU_DPRINTF(sc, RSU_DEBUG_AMPDU, "%s: establishing AMPDU TX for TID %d\n",
371 	    __func__,
372 	    tap->txa_tid);
373 
374 	RSU_LOCK(sc);
375 	if (rsu_fw_cmd(sc, R92S_CMD_ADDBA_REQ, &req, sizeof(req)) != 1) {
376 		RSU_UNLOCK(sc);
377 		/* Mark failure */
378 		(void) ieee80211_ampdu_tx_request_active_ext(ni, tap->txa_tid, 0);
379 		return (0);
380 	}
381 	RSU_UNLOCK(sc);
382 
383 	/* Mark success; we don't get any further notifications */
384 	(void) ieee80211_ampdu_tx_request_active_ext(ni, tap->txa_tid, 1);
385 #endif
386 	/* Return 0, we're driving this ourselves */
387 	return (0);
388 }
389 
390 static int
391 rsu_wme_update(struct ieee80211com *ic)
392 {
393 
394 	/* Firmware handles this; not our problem */
395 	return (0);
396 }
397 
398 static int
399 rsu_attach(device_t self)
400 {
401 	struct usb_attach_arg *uaa = device_get_ivars(self);
402 	struct rsu_softc *sc = device_get_softc(self);
403 	struct ieee80211com *ic = &sc->sc_ic;
404 	int error;
405 	uint8_t iface_index, bands;
406 	struct usb_interface *iface;
407 	const char *rft;
408 
409 	device_set_usb_desc(self);
410 	sc->sc_udev = uaa->device;
411 	sc->sc_dev = self;
412 	if (rsu_enable_11n)
413 		sc->sc_ht = !! (USB_GET_DRIVER_INFO(uaa) & RSU_HT_SUPPORTED);
414 
415 	/* Get number of endpoints */
416 	iface = usbd_get_iface(sc->sc_udev, 0);
417 	sc->sc_nendpoints = iface->idesc->bNumEndpoints;
418 
419 	/* Endpoints are hard-coded for now, so enforce 4-endpoint only */
420 	if (sc->sc_nendpoints != 4) {
421 		device_printf(sc->sc_dev,
422 		    "the driver currently only supports 4-endpoint devices\n");
423 		return (ENXIO);
424 	}
425 
426 	mtx_init(&sc->sc_mtx, device_get_nameunit(self), MTX_NETWORK_LOCK,
427 	    MTX_DEF);
428 	TIMEOUT_TASK_INIT(taskqueue_thread, &sc->calib_task, 0,
429 	    rsu_calib_task, sc);
430 	TASK_INIT(&sc->tx_task, 0, rsu_tx_task, sc);
431 	mbufq_init(&sc->sc_snd, ifqmaxlen);
432 
433 	/* Allocate Tx/Rx buffers. */
434 	error = rsu_alloc_rx_list(sc);
435 	if (error != 0) {
436 		device_printf(sc->sc_dev, "could not allocate Rx buffers\n");
437 		goto fail_usb;
438 	}
439 
440 	error = rsu_alloc_tx_list(sc);
441 	if (error != 0) {
442 		device_printf(sc->sc_dev, "could not allocate Tx buffers\n");
443 		rsu_free_rx_list(sc);
444 		goto fail_usb;
445 	}
446 
447 	iface_index = 0;
448 	error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
449 	    rsu_config, RSU_N_TRANSFER, sc, &sc->sc_mtx);
450 	if (error) {
451 		device_printf(sc->sc_dev,
452 		    "could not allocate USB transfers, err=%s\n",
453 		    usbd_errstr(error));
454 		goto fail_usb;
455 	}
456 	RSU_LOCK(sc);
457 	/* Read chip revision. */
458 	sc->cut = MS(rsu_read_4(sc, R92S_PMC_FSM), R92S_PMC_FSM_CUT);
459 	if (sc->cut != 3)
460 		sc->cut = (sc->cut >> 1) + 1;
461 	error = rsu_read_rom(sc);
462 	RSU_UNLOCK(sc);
463 	if (error != 0) {
464 		device_printf(self, "could not read ROM\n");
465 		goto fail_rom;
466 	}
467 
468 	/* Figure out TX/RX streams */
469 	switch (sc->rom[84]) {
470 	case 0x0:
471 		sc->sc_rftype = RTL8712_RFCONFIG_1T1R;
472 		sc->sc_nrxstream = 1;
473 		sc->sc_ntxstream = 1;
474 		rft = "1T1R";
475 		break;
476 	case 0x1:
477 		sc->sc_rftype = RTL8712_RFCONFIG_1T2R;
478 		sc->sc_nrxstream = 2;
479 		sc->sc_ntxstream = 1;
480 		rft = "1T2R";
481 		break;
482 	case 0x2:
483 		sc->sc_rftype = RTL8712_RFCONFIG_2T2R;
484 		sc->sc_nrxstream = 2;
485 		sc->sc_ntxstream = 2;
486 		rft = "2T2R";
487 		break;
488 	default:
489 		device_printf(sc->sc_dev,
490 		    "%s: unknown board type (rfconfig=0x%02x)\n",
491 		    __func__,
492 		    sc->rom[84]);
493 		goto fail_rom;
494 	}
495 
496 	IEEE80211_ADDR_COPY(ic->ic_macaddr, &sc->rom[0x12]);
497 	device_printf(self, "MAC/BB RTL8712 cut %d %s\n", sc->cut, rft);
498 
499 	ic->ic_softc = sc;
500 	ic->ic_name = device_get_nameunit(self);
501 	ic->ic_phytype = IEEE80211_T_OFDM;	/* Not only, but not used. */
502 	ic->ic_opmode = IEEE80211_M_STA;	/* Default to BSS mode. */
503 
504 	/* Set device capabilities. */
505 	ic->ic_caps =
506 	    IEEE80211_C_STA |		/* station mode */
507 #if 0
508 	    IEEE80211_C_BGSCAN |	/* Background scan. */
509 #endif
510 	    IEEE80211_C_SHPREAMBLE |	/* Short preamble supported. */
511 	    IEEE80211_C_WME |		/* WME/QoS */
512 	    IEEE80211_C_SHSLOT |	/* Short slot time supported. */
513 	    IEEE80211_C_WPA;		/* WPA/RSN. */
514 
515 	/* Check if HT support is present. */
516 	if (sc->sc_ht) {
517 		device_printf(sc->sc_dev, "%s: enabling 11n\n", __func__);
518 
519 		/* Enable basic HT */
520 		ic->ic_htcaps = IEEE80211_HTC_HT |
521 		    IEEE80211_HTC_AMPDU |
522 		    IEEE80211_HTC_AMSDU |
523 		    IEEE80211_HTCAP_MAXAMSDU_3839 |
524 		    IEEE80211_HTCAP_SMPS_OFF;
525 		ic->ic_htcaps |= IEEE80211_HTCAP_CHWIDTH40;
526 
527 		/* set number of spatial streams */
528 		ic->ic_txstream = sc->sc_ntxstream;
529 		ic->ic_rxstream = sc->sc_nrxstream;
530 	}
531 
532 	/* Set supported .11b and .11g rates. */
533 	bands = 0;
534 	setbit(&bands, IEEE80211_MODE_11B);
535 	setbit(&bands, IEEE80211_MODE_11G);
536 	if (sc->sc_ht)
537 		setbit(&bands, IEEE80211_MODE_11NG);
538 	ieee80211_init_channels(ic, NULL, &bands);
539 
540 	ieee80211_ifattach(ic);
541 	ic->ic_raw_xmit = rsu_raw_xmit;
542 	ic->ic_scan_start = rsu_scan_start;
543 	ic->ic_scan_end = rsu_scan_end;
544 	ic->ic_set_channel = rsu_set_channel;
545 	ic->ic_vap_create = rsu_vap_create;
546 	ic->ic_vap_delete = rsu_vap_delete;
547 	ic->ic_update_mcast = rsu_update_mcast;
548 	ic->ic_parent = rsu_parent;
549 	ic->ic_transmit = rsu_transmit;
550 	ic->ic_send_mgmt = rsu_send_mgmt;
551 	ic->ic_update_chw = rsu_update_chw;
552 	ic->ic_ampdu_enable = rsu_ampdu_enable;
553 	ic->ic_wme.wme_update = rsu_wme_update;
554 
555 	ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr,
556 	    sizeof(sc->sc_txtap), RSU_TX_RADIOTAP_PRESENT,
557 	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
558 	    RSU_RX_RADIOTAP_PRESENT);
559 
560 	if (bootverbose)
561 		ieee80211_announce(ic);
562 
563 	return (0);
564 
565 fail_rom:
566 	usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER);
567 fail_usb:
568 	mtx_destroy(&sc->sc_mtx);
569 	return (ENXIO);
570 }
571 
572 static int
573 rsu_detach(device_t self)
574 {
575 	struct rsu_softc *sc = device_get_softc(self);
576 	struct ieee80211com *ic = &sc->sc_ic;
577 
578 	RSU_LOCK(sc);
579 	rsu_stop(sc);
580 	RSU_UNLOCK(sc);
581 
582 	usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER);
583 
584 	/*
585 	 * Free buffers /before/ we detach from net80211, else node
586 	 * references to destroyed vaps will lead to a panic.
587 	 */
588 	/* Free Tx/Rx buffers. */
589 	RSU_LOCK(sc);
590 	rsu_free_tx_list(sc);
591 	rsu_free_rx_list(sc);
592 	RSU_UNLOCK(sc);
593 
594 	/* Frames are freed; detach from net80211 */
595 	ieee80211_ifdetach(ic);
596 
597 	taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task);
598 	taskqueue_drain(taskqueue_thread, &sc->tx_task);
599 
600 	mtx_destroy(&sc->sc_mtx);
601 
602 	return (0);
603 }
604 
605 static usb_error_t
606 rsu_do_request(struct rsu_softc *sc, struct usb_device_request *req,
607     void *data)
608 {
609 	usb_error_t err;
610 	int ntries = 10;
611 
612 	RSU_ASSERT_LOCKED(sc);
613 
614 	while (ntries--) {
615 		err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
616 		    req, data, 0, NULL, 250 /* ms */);
617 		if (err == 0 || err == USB_ERR_NOT_CONFIGURED)
618 			break;
619 		DPRINTFN(1, "Control request failed, %s (retrying)\n",
620 		    usbd_errstr(err));
621 		rsu_ms_delay(sc, 10);
622         }
623 
624         return (err);
625 }
626 
627 static struct ieee80211vap *
628 rsu_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
629     enum ieee80211_opmode opmode, int flags,
630     const uint8_t bssid[IEEE80211_ADDR_LEN],
631     const uint8_t mac[IEEE80211_ADDR_LEN])
632 {
633 	struct rsu_vap *uvp;
634 	struct ieee80211vap *vap;
635 
636 	if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
637 		return (NULL);
638 
639 	uvp =  malloc(sizeof(struct rsu_vap), M_80211_VAP, M_WAITOK | M_ZERO);
640 	vap = &uvp->vap;
641 
642 	if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
643 	    flags, bssid) != 0) {
644 		/* out of memory */
645 		free(uvp, M_80211_VAP);
646 		return (NULL);
647 	}
648 
649 	/* override state transition machine */
650 	uvp->newstate = vap->iv_newstate;
651 	vap->iv_newstate = rsu_newstate;
652 
653 	/* Limits from the r92su driver */
654 	vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_16;
655 	vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_32K;
656 
657 	/* complete setup */
658 	ieee80211_vap_attach(vap, ieee80211_media_change,
659 	    ieee80211_media_status, mac);
660 	ic->ic_opmode = opmode;
661 
662 	return (vap);
663 }
664 
665 static void
666 rsu_vap_delete(struct ieee80211vap *vap)
667 {
668 	struct rsu_vap *uvp = RSU_VAP(vap);
669 
670 	ieee80211_vap_detach(vap);
671 	free(uvp, M_80211_VAP);
672 }
673 
674 static void
675 rsu_scan_start(struct ieee80211com *ic)
676 {
677 	struct rsu_softc *sc = ic->ic_softc;
678 	int error;
679 
680 	/* Scanning is done by the firmware. */
681 	RSU_LOCK(sc);
682 	/* XXX TODO: force awake if in in network-sleep? */
683 	error = rsu_site_survey(sc, TAILQ_FIRST(&ic->ic_vaps));
684 	RSU_UNLOCK(sc);
685 	if (error != 0)
686 		device_printf(sc->sc_dev,
687 		    "could not send site survey command\n");
688 }
689 
690 static void
691 rsu_scan_end(struct ieee80211com *ic)
692 {
693 	/* Nothing to do here. */
694 }
695 
696 static void
697 rsu_set_channel(struct ieee80211com *ic __unused)
698 {
699 	/* We are unable to switch channels, yet. */
700 }
701 
702 static void
703 rsu_update_mcast(struct ieee80211com *ic)
704 {
705         /* XXX do nothing?  */
706 }
707 
708 static int
709 rsu_alloc_list(struct rsu_softc *sc, struct rsu_data data[],
710     int ndata, int maxsz)
711 {
712 	int i, error;
713 
714 	for (i = 0; i < ndata; i++) {
715 		struct rsu_data *dp = &data[i];
716 		dp->sc = sc;
717 		dp->m = NULL;
718 		dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT);
719 		if (dp->buf == NULL) {
720 			device_printf(sc->sc_dev,
721 			    "could not allocate buffer\n");
722 			error = ENOMEM;
723 			goto fail;
724 		}
725 		dp->ni = NULL;
726 	}
727 
728 	return (0);
729 fail:
730 	rsu_free_list(sc, data, ndata);
731 	return (error);
732 }
733 
734 static int
735 rsu_alloc_rx_list(struct rsu_softc *sc)
736 {
737         int error, i;
738 
739 	error = rsu_alloc_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT,
740 	    RSU_RXBUFSZ);
741 	if (error != 0)
742 		return (error);
743 
744 	STAILQ_INIT(&sc->sc_rx_active);
745 	STAILQ_INIT(&sc->sc_rx_inactive);
746 
747 	for (i = 0; i < RSU_RX_LIST_COUNT; i++)
748 		STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i], next);
749 
750 	return (0);
751 }
752 
753 static int
754 rsu_alloc_tx_list(struct rsu_softc *sc)
755 {
756 	int error, i;
757 
758 	error = rsu_alloc_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT,
759 	    RSU_TXBUFSZ);
760 	if (error != 0)
761 		return (error);
762 
763 	STAILQ_INIT(&sc->sc_tx_inactive);
764 
765 	for (i = 0; i != RSU_N_TRANSFER; i++) {
766 		STAILQ_INIT(&sc->sc_tx_active[i]);
767 		STAILQ_INIT(&sc->sc_tx_pending[i]);
768 	}
769 
770 	for (i = 0; i < RSU_TX_LIST_COUNT; i++) {
771 		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i], next);
772 	}
773 
774 	return (0);
775 }
776 
777 static void
778 rsu_free_tx_list(struct rsu_softc *sc)
779 {
780 	int i;
781 
782 	/* prevent further allocations from TX list(s) */
783 	STAILQ_INIT(&sc->sc_tx_inactive);
784 
785 	for (i = 0; i != RSU_N_TRANSFER; i++) {
786 		STAILQ_INIT(&sc->sc_tx_active[i]);
787 		STAILQ_INIT(&sc->sc_tx_pending[i]);
788 	}
789 
790 	rsu_free_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT);
791 }
792 
793 static void
794 rsu_free_rx_list(struct rsu_softc *sc)
795 {
796 	/* prevent further allocations from RX list(s) */
797 	STAILQ_INIT(&sc->sc_rx_inactive);
798 	STAILQ_INIT(&sc->sc_rx_active);
799 
800 	rsu_free_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT);
801 }
802 
803 static void
804 rsu_free_list(struct rsu_softc *sc, struct rsu_data data[], int ndata)
805 {
806 	int i;
807 
808 	for (i = 0; i < ndata; i++) {
809 		struct rsu_data *dp = &data[i];
810 
811 		if (dp->buf != NULL) {
812 			free(dp->buf, M_USBDEV);
813 			dp->buf = NULL;
814 		}
815 		if (dp->ni != NULL) {
816 			ieee80211_free_node(dp->ni);
817 			dp->ni = NULL;
818 		}
819 	}
820 }
821 
822 static struct rsu_data *
823 _rsu_getbuf(struct rsu_softc *sc)
824 {
825 	struct rsu_data *bf;
826 
827 	bf = STAILQ_FIRST(&sc->sc_tx_inactive);
828 	if (bf != NULL)
829 		STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next);
830 	else
831 		bf = NULL;
832 	return (bf);
833 }
834 
835 static struct rsu_data *
836 rsu_getbuf(struct rsu_softc *sc)
837 {
838 	struct rsu_data *bf;
839 
840 	RSU_ASSERT_LOCKED(sc);
841 
842 	bf = _rsu_getbuf(sc);
843 	if (bf == NULL) {
844 		RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: no buffers\n", __func__);
845 	}
846 	return (bf);
847 }
848 
849 static void
850 rsu_freebuf(struct rsu_softc *sc, struct rsu_data *bf)
851 {
852 
853 	RSU_ASSERT_LOCKED(sc);
854 	STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, bf, next);
855 }
856 
857 static int
858 rsu_write_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
859     int len)
860 {
861 	usb_device_request_t req;
862 
863 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
864 	req.bRequest = R92S_REQ_REGS;
865 	USETW(req.wValue, addr);
866 	USETW(req.wIndex, 0);
867 	USETW(req.wLength, len);
868 
869 	return (rsu_do_request(sc, &req, buf));
870 }
871 
872 static void
873 rsu_write_1(struct rsu_softc *sc, uint16_t addr, uint8_t val)
874 {
875 	rsu_write_region_1(sc, addr, &val, 1);
876 }
877 
878 static void
879 rsu_write_2(struct rsu_softc *sc, uint16_t addr, uint16_t val)
880 {
881 	val = htole16(val);
882 	rsu_write_region_1(sc, addr, (uint8_t *)&val, 2);
883 }
884 
885 static void
886 rsu_write_4(struct rsu_softc *sc, uint16_t addr, uint32_t val)
887 {
888 	val = htole32(val);
889 	rsu_write_region_1(sc, addr, (uint8_t *)&val, 4);
890 }
891 
892 static int
893 rsu_read_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
894     int len)
895 {
896 	usb_device_request_t req;
897 
898 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
899 	req.bRequest = R92S_REQ_REGS;
900 	USETW(req.wValue, addr);
901 	USETW(req.wIndex, 0);
902 	USETW(req.wLength, len);
903 
904 	return (rsu_do_request(sc, &req, buf));
905 }
906 
907 static uint8_t
908 rsu_read_1(struct rsu_softc *sc, uint16_t addr)
909 {
910 	uint8_t val;
911 
912 	if (rsu_read_region_1(sc, addr, &val, 1) != 0)
913 		return (0xff);
914 	return (val);
915 }
916 
917 static uint16_t
918 rsu_read_2(struct rsu_softc *sc, uint16_t addr)
919 {
920 	uint16_t val;
921 
922 	if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0)
923 		return (0xffff);
924 	return (le16toh(val));
925 }
926 
927 static uint32_t
928 rsu_read_4(struct rsu_softc *sc, uint16_t addr)
929 {
930 	uint32_t val;
931 
932 	if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0)
933 		return (0xffffffff);
934 	return (le32toh(val));
935 }
936 
937 static int
938 rsu_fw_iocmd(struct rsu_softc *sc, uint32_t iocmd)
939 {
940 	int ntries;
941 
942 	rsu_write_4(sc, R92S_IOCMD_CTRL, iocmd);
943 	rsu_ms_delay(sc, 1);
944 	for (ntries = 0; ntries < 50; ntries++) {
945 		if (rsu_read_4(sc, R92S_IOCMD_CTRL) == 0)
946 			return (0);
947 		rsu_ms_delay(sc, 1);
948 	}
949 	return (ETIMEDOUT);
950 }
951 
952 static uint8_t
953 rsu_efuse_read_1(struct rsu_softc *sc, uint16_t addr)
954 {
955 	uint32_t reg;
956 	int ntries;
957 
958 	reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
959 	reg = RW(reg, R92S_EFUSE_CTRL_ADDR, addr);
960 	reg &= ~R92S_EFUSE_CTRL_VALID;
961 	rsu_write_4(sc, R92S_EFUSE_CTRL, reg);
962 	/* Wait for read operation to complete. */
963 	for (ntries = 0; ntries < 100; ntries++) {
964 		reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
965 		if (reg & R92S_EFUSE_CTRL_VALID)
966 			return (MS(reg, R92S_EFUSE_CTRL_DATA));
967 		rsu_ms_delay(sc, 1);
968 	}
969 	device_printf(sc->sc_dev,
970 	    "could not read efuse byte at address 0x%x\n", addr);
971 	return (0xff);
972 }
973 
974 static int
975 rsu_read_rom(struct rsu_softc *sc)
976 {
977 	uint8_t *rom = sc->rom;
978 	uint16_t addr = 0;
979 	uint32_t reg;
980 	uint8_t off, msk;
981 	int i;
982 
983 	/* Make sure that ROM type is eFuse and that autoload succeeded. */
984 	reg = rsu_read_1(sc, R92S_EE_9346CR);
985 	if ((reg & (R92S_9356SEL | R92S_EEPROM_EN)) != R92S_EEPROM_EN)
986 		return (EIO);
987 
988 	/* Turn on 2.5V to prevent eFuse leakage. */
989 	reg = rsu_read_1(sc, R92S_EFUSE_TEST + 3);
990 	rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg | 0x80);
991 	rsu_ms_delay(sc, 1);
992 	rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg & ~0x80);
993 
994 	/* Read full ROM image. */
995 	memset(&sc->rom, 0xff, sizeof(sc->rom));
996 	while (addr < 512) {
997 		reg = rsu_efuse_read_1(sc, addr);
998 		if (reg == 0xff)
999 			break;
1000 		addr++;
1001 		off = reg >> 4;
1002 		msk = reg & 0xf;
1003 		for (i = 0; i < 4; i++) {
1004 			if (msk & (1 << i))
1005 				continue;
1006 			rom[off * 8 + i * 2 + 0] =
1007 			    rsu_efuse_read_1(sc, addr);
1008 			addr++;
1009 			rom[off * 8 + i * 2 + 1] =
1010 			    rsu_efuse_read_1(sc, addr);
1011 			addr++;
1012 		}
1013 	}
1014 #ifdef USB_DEBUG
1015 	if (rsu_debug >= 5) {
1016 		/* Dump ROM content. */
1017 		printf("\n");
1018 		for (i = 0; i < sizeof(sc->rom); i++)
1019 			printf("%02x:", rom[i]);
1020 		printf("\n");
1021 	}
1022 #endif
1023 	return (0);
1024 }
1025 
1026 static int
1027 rsu_fw_cmd(struct rsu_softc *sc, uint8_t code, void *buf, int len)
1028 {
1029 	const uint8_t which = RSU_H2C_ENDPOINT;
1030 	struct rsu_data *data;
1031 	struct r92s_tx_desc *txd;
1032 	struct r92s_fw_cmd_hdr *cmd;
1033 	int cmdsz;
1034 	int xferlen;
1035 
1036 	RSU_ASSERT_LOCKED(sc);
1037 
1038 	data = rsu_getbuf(sc);
1039 	if (data == NULL)
1040 		return (ENOMEM);
1041 
1042 	/* Blank the entire payload, just to be safe */
1043 	memset(data->buf, '\0', RSU_TXBUFSZ);
1044 
1045 	/* Round-up command length to a multiple of 8 bytes. */
1046 	/* XXX TODO: is this required? */
1047 	cmdsz = (len + 7) & ~7;
1048 
1049 	xferlen = sizeof(*txd) + sizeof(*cmd) + cmdsz;
1050 	KASSERT(xferlen <= RSU_TXBUFSZ, ("%s: invalid length", __func__));
1051 	memset(data->buf, 0, xferlen);
1052 
1053 	/* Setup Tx descriptor. */
1054 	txd = (struct r92s_tx_desc *)data->buf;
1055 	txd->txdw0 = htole32(
1056 	    SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
1057 	    SM(R92S_TXDW0_PKTLEN, sizeof(*cmd) + cmdsz) |
1058 	    R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
1059 	txd->txdw1 = htole32(SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_H2C));
1060 
1061 	/* Setup command header. */
1062 	cmd = (struct r92s_fw_cmd_hdr *)&txd[1];
1063 	cmd->len = htole16(cmdsz);
1064 	cmd->code = code;
1065 	cmd->seq = sc->cmd_seq;
1066 	sc->cmd_seq = (sc->cmd_seq + 1) & 0x7f;
1067 
1068 	/* Copy command payload. */
1069 	memcpy(&cmd[1], buf, len);
1070 
1071 	RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FWCMD,
1072 	    "%s: Tx cmd code=0x%x len=0x%x\n",
1073 	    __func__, code, cmdsz);
1074 	data->buflen = xferlen;
1075 	STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
1076 	usbd_transfer_start(sc->sc_xfer[which]);
1077 
1078 	return (0);
1079 }
1080 
1081 /* ARGSUSED */
1082 static void
1083 rsu_calib_task(void *arg, int pending __unused)
1084 {
1085 	struct rsu_softc *sc = arg;
1086 #ifdef notyet
1087 	uint32_t reg;
1088 #endif
1089 
1090 	RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "%s: running calibration task\n",
1091 	    __func__);
1092 
1093 	RSU_LOCK(sc);
1094 #ifdef notyet
1095 	/* Read WPS PBC status. */
1096 	rsu_write_1(sc, R92S_MAC_PINMUX_CTRL,
1097 	    R92S_GPIOMUX_EN | SM(R92S_GPIOSEL_GPIO, R92S_GPIOSEL_GPIO_JTAG));
1098 	rsu_write_1(sc, R92S_GPIO_IO_SEL,
1099 	    rsu_read_1(sc, R92S_GPIO_IO_SEL) & ~R92S_GPIO_WPS);
1100 	reg = rsu_read_1(sc, R92S_GPIO_CTRL);
1101 	if (reg != 0xff && (reg & R92S_GPIO_WPS))
1102 		DPRINTF(("WPS PBC is pushed\n"));
1103 #endif
1104 	/* Read current signal level. */
1105 	if (rsu_fw_iocmd(sc, 0xf4000001) == 0) {
1106 		sc->sc_currssi = rsu_read_4(sc, R92S_IOCMD_DATA);
1107 		RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "%s: RSSI=%d (%d)\n",
1108 		    __func__, sc->sc_currssi,
1109 		    rsu_hwrssi_to_rssi(sc, sc->sc_currssi));
1110 	}
1111 	if (sc->sc_calibrating)
1112 		taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, hz);
1113 	RSU_UNLOCK(sc);
1114 }
1115 
1116 static void
1117 rsu_tx_task(void *arg, int pending __unused)
1118 {
1119 	struct rsu_softc *sc = arg;
1120 
1121 	RSU_LOCK(sc);
1122 	_rsu_start(sc);
1123 	RSU_UNLOCK(sc);
1124 }
1125 
1126 #define	RSU_PWR_UNKNOWN		0x0
1127 #define	RSU_PWR_ACTIVE		0x1
1128 #define	RSU_PWR_OFF		0x2
1129 #define	RSU_PWR_SLEEP		0x3
1130 
1131 /*
1132  * Set the current power state.
1133  *
1134  * The rtlwifi code doesn't do this so aggressively; it
1135  * waits for an idle period after association with
1136  * no traffic before doing this.
1137  *
1138  * For now - it's on in all states except RUN, and
1139  * in RUN it'll transition to allow sleep.
1140  */
1141 
1142 struct r92s_pwr_cmd {
1143 	uint8_t mode;
1144 	uint8_t smart_ps;
1145 	uint8_t bcn_pass_time;
1146 };
1147 
1148 static int
1149 rsu_set_fw_power_state(struct rsu_softc *sc, int state)
1150 {
1151 	struct r92s_set_pwr_mode cmd;
1152 	//struct r92s_pwr_cmd cmd;
1153 	int error;
1154 
1155 	RSU_ASSERT_LOCKED(sc);
1156 
1157 	/* only change state if required */
1158 	if (sc->sc_curpwrstate == state)
1159 		return (0);
1160 
1161 	memset(&cmd, 0, sizeof(cmd));
1162 
1163 	switch (state) {
1164 	case RSU_PWR_ACTIVE:
1165 		/* Force the hardware awake */
1166 		rsu_write_1(sc, R92S_USB_HRPWM,
1167 		    R92S_USB_HRPWM_PS_ST_ACTIVE | R92S_USB_HRPWM_PS_ALL_ON);
1168 		cmd.mode = R92S_PS_MODE_ACTIVE;
1169 		break;
1170 	case RSU_PWR_SLEEP:
1171 		cmd.mode = R92S_PS_MODE_DTIM;	/* XXX configurable? */
1172 		cmd.smart_ps = 1; /* XXX 2 if doing p2p */
1173 		cmd.bcn_pass_time = 5; /* in 100mS usb.c, linux/rtlwifi */
1174 		break;
1175 	case RSU_PWR_OFF:
1176 		cmd.mode = R92S_PS_MODE_RADIOOFF;
1177 		break;
1178 	default:
1179 		device_printf(sc->sc_dev, "%s: unknown ps mode (%d)\n",
1180 		    __func__,
1181 		    state);
1182 		return (ENXIO);
1183 	}
1184 
1185 	RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1186 	    "%s: setting ps mode to %d (mode %d)\n",
1187 	    __func__, state, cmd.mode);
1188 	error = rsu_fw_cmd(sc, R92S_CMD_SET_PWR_MODE, &cmd, sizeof(cmd));
1189 	if (error == 0)
1190 		sc->sc_curpwrstate = state;
1191 
1192 	return (error);
1193 }
1194 
1195 static int
1196 rsu_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1197 {
1198 	struct rsu_vap *uvp = RSU_VAP(vap);
1199 	struct ieee80211com *ic = vap->iv_ic;
1200 	struct rsu_softc *sc = ic->ic_softc;
1201 	struct ieee80211_node *ni;
1202 	struct ieee80211_rateset *rs;
1203 	enum ieee80211_state ostate;
1204 	int error, startcal = 0;
1205 
1206 	ostate = vap->iv_state;
1207 	RSU_DPRINTF(sc, RSU_DEBUG_STATE, "%s: %s -> %s\n",
1208 	    __func__,
1209 	    ieee80211_state_name[ostate],
1210 	    ieee80211_state_name[nstate]);
1211 
1212 	IEEE80211_UNLOCK(ic);
1213 	if (ostate == IEEE80211_S_RUN) {
1214 		RSU_LOCK(sc);
1215 		/* Stop calibration. */
1216 		sc->sc_calibrating = 0;
1217 		RSU_UNLOCK(sc);
1218 		taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task);
1219 		taskqueue_drain(taskqueue_thread, &sc->tx_task);
1220 		/* Disassociate from our current BSS. */
1221 		RSU_LOCK(sc);
1222 		rsu_disconnect(sc);
1223 	} else
1224 		RSU_LOCK(sc);
1225 	switch (nstate) {
1226 	case IEEE80211_S_INIT:
1227 		(void) rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
1228 		break;
1229 	case IEEE80211_S_AUTH:
1230 		ni = ieee80211_ref_node(vap->iv_bss);
1231 		(void) rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
1232 		error = rsu_join_bss(sc, ni);
1233 		ieee80211_free_node(ni);
1234 		if (error != 0) {
1235 			device_printf(sc->sc_dev,
1236 			    "could not send join command\n");
1237 		}
1238 		break;
1239 	case IEEE80211_S_RUN:
1240 		ni = ieee80211_ref_node(vap->iv_bss);
1241 		rs = &ni->ni_rates;
1242 		/* Indicate highest supported rate. */
1243 		ni->ni_txrate = rs->rs_rates[rs->rs_nrates - 1];
1244 		(void) rsu_set_fw_power_state(sc, RSU_PWR_SLEEP);
1245 		ieee80211_free_node(ni);
1246 		startcal = 1;
1247 		break;
1248 	default:
1249 		break;
1250 	}
1251 	sc->sc_calibrating = 1;
1252 	/* Start periodic calibration. */
1253 	taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, hz);
1254 	RSU_UNLOCK(sc);
1255 	IEEE80211_LOCK(ic);
1256 	return (uvp->newstate(vap, nstate, arg));
1257 }
1258 
1259 #ifdef notyet
1260 static void
1261 rsu_set_key(struct rsu_softc *sc, const struct ieee80211_key *k)
1262 {
1263 	struct r92s_fw_cmd_set_key key;
1264 
1265 	memset(&key, 0, sizeof(key));
1266 	/* Map net80211 cipher to HW crypto algorithm. */
1267 	switch (k->wk_cipher->ic_cipher) {
1268 	case IEEE80211_CIPHER_WEP:
1269 		if (k->wk_keylen < 8)
1270 			key.algo = R92S_KEY_ALGO_WEP40;
1271 		else
1272 			key.algo = R92S_KEY_ALGO_WEP104;
1273 		break;
1274 	case IEEE80211_CIPHER_TKIP:
1275 		key.algo = R92S_KEY_ALGO_TKIP;
1276 		break;
1277 	case IEEE80211_CIPHER_AES_CCM:
1278 		key.algo = R92S_KEY_ALGO_AES;
1279 		break;
1280 	default:
1281 		return;
1282 	}
1283 	key.id = k->wk_keyix;
1284 	key.grpkey = (k->wk_flags & IEEE80211_KEY_GROUP) != 0;
1285 	memcpy(key.key, k->wk_key, MIN(k->wk_keylen, sizeof(key.key)));
1286 	(void)rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
1287 }
1288 
1289 static void
1290 rsu_delete_key(struct rsu_softc *sc, const struct ieee80211_key *k)
1291 {
1292 	struct r92s_fw_cmd_set_key key;
1293 
1294 	memset(&key, 0, sizeof(key));
1295 	key.id = k->wk_keyix;
1296 	(void)rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
1297 }
1298 #endif
1299 
1300 static int
1301 rsu_site_survey(struct rsu_softc *sc, struct ieee80211vap *vap)
1302 {
1303 	struct r92s_fw_cmd_sitesurvey cmd;
1304 	struct ieee80211com *ic = &sc->sc_ic;
1305 	int r;
1306 
1307 	RSU_ASSERT_LOCKED(sc);
1308 
1309 	memset(&cmd, 0, sizeof(cmd));
1310 	if ((ic->ic_flags & IEEE80211_F_ASCAN) || sc->sc_scan_pass == 1)
1311 		cmd.active = htole32(1);
1312 	cmd.limit = htole32(48);
1313 	if (sc->sc_scan_pass == 1 && vap->iv_des_nssid > 0) {
1314 		/* Do a directed scan for second pass. */
1315 		cmd.ssidlen = htole32(vap->iv_des_ssid[0].len);
1316 		memcpy(cmd.ssid, vap->iv_des_ssid[0].ssid,
1317 		    vap->iv_des_ssid[0].len);
1318 
1319 	}
1320 	DPRINTF("sending site survey command, pass=%d\n", sc->sc_scan_pass);
1321 	r = rsu_fw_cmd(sc, R92S_CMD_SITE_SURVEY, &cmd, sizeof(cmd));
1322 	if (r == 0) {
1323 		sc->sc_scanning = 1;
1324 	}
1325 	return (r);
1326 }
1327 
1328 static int
1329 rsu_join_bss(struct rsu_softc *sc, struct ieee80211_node *ni)
1330 {
1331 	struct ieee80211com *ic = &sc->sc_ic;
1332 	struct ieee80211vap *vap = ni->ni_vap;
1333 	struct ndis_wlan_bssid_ex *bss;
1334 	struct ndis_802_11_fixed_ies *fixed;
1335 	struct r92s_fw_cmd_auth auth;
1336 	uint8_t buf[sizeof(*bss) + 128] __aligned(4);
1337 	uint8_t *frm;
1338 	uint8_t opmode;
1339 	int error;
1340 	int cnt;
1341 	char *msg = "rsujoin";
1342 
1343 	RSU_ASSERT_LOCKED(sc);
1344 
1345 	/*
1346 	 * Until net80211 scanning doesn't automatically finish
1347 	 * before we tell it to, let's just wait until any pending
1348 	 * scan is done.
1349 	 *
1350 	 * XXX TODO: yes, this releases and re-acquires the lock.
1351 	 * We should re-verify the state whenever we re-attempt this!
1352 	 */
1353 	cnt = 0;
1354 	while (sc->sc_scanning && cnt < 10) {
1355 		device_printf(sc->sc_dev,
1356 		    "%s: still scanning! (attempt %d)\n",
1357 		    __func__, cnt);
1358 		msleep(msg, &sc->sc_mtx, 0, msg, hz / 2);
1359 		cnt++;
1360 	}
1361 
1362 	/* Let the FW decide the opmode based on the capinfo field. */
1363 	opmode = NDIS802_11AUTOUNKNOWN;
1364 	RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1365 	    "%s: setting operating mode to %d\n",
1366 	    __func__, opmode);
1367 	error = rsu_fw_cmd(sc, R92S_CMD_SET_OPMODE, &opmode, sizeof(opmode));
1368 	if (error != 0)
1369 		return (error);
1370 
1371 	memset(&auth, 0, sizeof(auth));
1372 	if (vap->iv_flags & IEEE80211_F_WPA) {
1373 		auth.mode = R92S_AUTHMODE_WPA;
1374 		auth.dot1x = (ni->ni_authmode == IEEE80211_AUTH_8021X);
1375 	} else
1376 		auth.mode = R92S_AUTHMODE_OPEN;
1377 	RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1378 	    "%s: setting auth mode to %d\n",
1379 	    __func__, auth.mode);
1380 	error = rsu_fw_cmd(sc, R92S_CMD_SET_AUTH, &auth, sizeof(auth));
1381 	if (error != 0)
1382 		return (error);
1383 
1384 	memset(buf, 0, sizeof(buf));
1385 	bss = (struct ndis_wlan_bssid_ex *)buf;
1386 	IEEE80211_ADDR_COPY(bss->macaddr, ni->ni_bssid);
1387 	bss->ssid.ssidlen = htole32(ni->ni_esslen);
1388 	memcpy(bss->ssid.ssid, ni->ni_essid, ni->ni_esslen);
1389 	if (vap->iv_flags & (IEEE80211_F_PRIVACY | IEEE80211_F_WPA))
1390 		bss->privacy = htole32(1);
1391 	bss->rssi = htole32(ni->ni_avgrssi);
1392 	if (ic->ic_curmode == IEEE80211_MODE_11B)
1393 		bss->networktype = htole32(NDIS802_11DS);
1394 	else
1395 		bss->networktype = htole32(NDIS802_11OFDM24);
1396 	bss->config.len = htole32(sizeof(bss->config));
1397 	bss->config.bintval = htole32(ni->ni_intval);
1398 	bss->config.dsconfig = htole32(ieee80211_chan2ieee(ic, ni->ni_chan));
1399 	bss->inframode = htole32(NDIS802_11INFRASTRUCTURE);
1400 	/* XXX verify how this is supposed to look! */
1401 	memcpy(bss->supprates, ni->ni_rates.rs_rates,
1402 	    ni->ni_rates.rs_nrates);
1403 	/* Write the fixed fields of the beacon frame. */
1404 	fixed = (struct ndis_802_11_fixed_ies *)&bss[1];
1405 	memcpy(&fixed->tstamp, ni->ni_tstamp.data, 8);
1406 	fixed->bintval = htole16(ni->ni_intval);
1407 	fixed->capabilities = htole16(ni->ni_capinfo);
1408 	/* Write IEs to be included in the association request. */
1409 	frm = (uint8_t *)&fixed[1];
1410 	frm = ieee80211_add_rsn(frm, vap);
1411 	frm = ieee80211_add_wpa(frm, vap);
1412 	frm = ieee80211_add_qos(frm, ni);
1413 	if ((ic->ic_flags & IEEE80211_F_WME) &&
1414 	    (ni->ni_ies.wme_ie != NULL))
1415 		frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1416 	if (ni->ni_flags & IEEE80211_NODE_HT) {
1417 		frm = ieee80211_add_htcap(frm, ni);
1418 		frm = ieee80211_add_htinfo(frm, ni);
1419 	}
1420 	bss->ieslen = htole32(frm - (uint8_t *)fixed);
1421 	bss->len = htole32(((frm - buf) + 3) & ~3);
1422 	RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_FWCMD,
1423 	    "%s: sending join bss command to %s chan %d\n",
1424 	    __func__,
1425 	    ether_sprintf(bss->macaddr), le32toh(bss->config.dsconfig));
1426 	return (rsu_fw_cmd(sc, R92S_CMD_JOIN_BSS, buf, sizeof(buf)));
1427 }
1428 
1429 static int
1430 rsu_disconnect(struct rsu_softc *sc)
1431 {
1432 	uint32_t zero = 0;	/* :-) */
1433 
1434 	/* Disassociate from our current BSS. */
1435 	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
1436 	    "%s: sending disconnect command\n", __func__);
1437 	return (rsu_fw_cmd(sc, R92S_CMD_DISCONNECT, &zero, sizeof(zero)));
1438 }
1439 
1440 /*
1441  * Map the hardware provided RSSI value to a signal level.
1442  * For the most part it's just something we divide by and cap
1443  * so it doesn't overflow the representation by net80211.
1444  */
1445 static int
1446 rsu_hwrssi_to_rssi(struct rsu_softc *sc, int hw_rssi)
1447 {
1448 	int v;
1449 
1450 	if (hw_rssi == 0)
1451 		return (0);
1452 	v = hw_rssi >> 4;
1453 	if (v > 80)
1454 		v = 80;
1455 	return (v);
1456 }
1457 
1458 static void
1459 rsu_event_survey(struct rsu_softc *sc, uint8_t *buf, int len)
1460 {
1461 	struct ieee80211com *ic = &sc->sc_ic;
1462 	struct ieee80211_frame *wh;
1463 	struct ndis_wlan_bssid_ex *bss;
1464 	struct ieee80211_rx_stats rxs;
1465 	struct mbuf *m;
1466 	int pktlen;
1467 
1468 	if (__predict_false(len < sizeof(*bss)))
1469 		return;
1470 	bss = (struct ndis_wlan_bssid_ex *)buf;
1471 	if (__predict_false(len < sizeof(*bss) + le32toh(bss->ieslen)))
1472 		return;
1473 
1474 	RSU_DPRINTF(sc, RSU_DEBUG_SCAN,
1475 	    "%s: found BSS %s: len=%d chan=%d inframode=%d "
1476 	    "networktype=%d privacy=%d, RSSI=%d\n",
1477 	    __func__,
1478 	    ether_sprintf(bss->macaddr), le32toh(bss->len),
1479 	    le32toh(bss->config.dsconfig), le32toh(bss->inframode),
1480 	    le32toh(bss->networktype), le32toh(bss->privacy),
1481 	    le32toh(bss->rssi));
1482 
1483 	/* Build a fake beacon frame to let net80211 do all the parsing. */
1484 	/* XXX TODO: just call the new scan API methods! */
1485 	pktlen = sizeof(*wh) + le32toh(bss->ieslen);
1486 	if (__predict_false(pktlen > MCLBYTES))
1487 		return;
1488 	m = m_get2(pktlen, M_NOWAIT, MT_DATA, M_PKTHDR);
1489 	if (__predict_false(m == NULL))
1490 		return;
1491 	wh = mtod(m, struct ieee80211_frame *);
1492 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
1493 	    IEEE80211_FC0_SUBTYPE_BEACON;
1494 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1495 	USETW(wh->i_dur, 0);
1496 	IEEE80211_ADDR_COPY(wh->i_addr1, ieee80211broadcastaddr);
1497 	IEEE80211_ADDR_COPY(wh->i_addr2, bss->macaddr);
1498 	IEEE80211_ADDR_COPY(wh->i_addr3, bss->macaddr);
1499 	*(uint16_t *)wh->i_seq = 0;
1500 	memcpy(&wh[1], (uint8_t *)&bss[1], le32toh(bss->ieslen));
1501 
1502 	/* Finalize mbuf. */
1503 	m->m_pkthdr.len = m->m_len = pktlen;
1504 
1505 	/* Set channel flags for input path */
1506 	bzero(&rxs, sizeof(rxs));
1507 	rxs.r_flags |= IEEE80211_R_IEEE | IEEE80211_R_FREQ;
1508 	rxs.r_flags |= IEEE80211_R_NF | IEEE80211_R_RSSI;
1509 	rxs.c_ieee = le32toh(bss->config.dsconfig);
1510 	rxs.c_freq = ieee80211_ieee2mhz(rxs.c_ieee, IEEE80211_CHAN_2GHZ);
1511 	/* This is a number from 0..100; so let's just divide it down a bit */
1512 	rxs.rssi = le32toh(bss->rssi) / 2;
1513 	rxs.nf = -96;
1514 
1515 	/* XXX avoid a LOR */
1516 	RSU_UNLOCK(sc);
1517 	ieee80211_input_mimo_all(ic, m, &rxs);
1518 	RSU_LOCK(sc);
1519 }
1520 
1521 static void
1522 rsu_event_join_bss(struct rsu_softc *sc, uint8_t *buf, int len)
1523 {
1524 	struct ieee80211com *ic = &sc->sc_ic;
1525 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1526 	struct ieee80211_node *ni = vap->iv_bss;
1527 	struct r92s_event_join_bss *rsp;
1528 	uint32_t tmp;
1529 	int res;
1530 
1531 	if (__predict_false(len < sizeof(*rsp)))
1532 		return;
1533 	rsp = (struct r92s_event_join_bss *)buf;
1534 	res = (int)le32toh(rsp->join_res);
1535 
1536 	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
1537 	    "%s: Rx join BSS event len=%d res=%d\n",
1538 	    __func__, len, res);
1539 
1540 	/*
1541 	 * XXX Don't do this; there's likely a better way to tell
1542 	 * the caller we failed.
1543 	 */
1544 	if (res <= 0) {
1545 		RSU_UNLOCK(sc);
1546 		ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1547 		RSU_LOCK(sc);
1548 		return;
1549 	}
1550 
1551 	tmp = le32toh(rsp->associd);
1552 	if (tmp >= vap->iv_max_aid) {
1553 		DPRINTF("Assoc ID overflow\n");
1554 		tmp = 1;
1555 	}
1556 	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
1557 	    "%s: associated with %s associd=%d\n",
1558 	    __func__, ether_sprintf(rsp->bss.macaddr), tmp);
1559 	/* XXX is this required? What's the top two bits for again? */
1560 	ni->ni_associd = tmp | 0xc000;
1561 	RSU_UNLOCK(sc);
1562 	ieee80211_new_state(vap, IEEE80211_S_RUN,
1563 	    IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
1564 	RSU_LOCK(sc);
1565 }
1566 
1567 static void
1568 rsu_event_addba_req_report(struct rsu_softc *sc, uint8_t *buf, int len)
1569 {
1570 	struct ieee80211com *ic = &sc->sc_ic;
1571 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1572 	struct r92s_add_ba_event *ba = (void *) buf;
1573 	struct ieee80211_node *ni;
1574 
1575 	if (len < sizeof(*ba)) {
1576 		device_printf(sc->sc_dev, "%s: short read (%d)\n", __func__, len);
1577 		return;
1578 	}
1579 
1580 	if (vap == NULL)
1581 		return;
1582 
1583 	RSU_DPRINTF(sc, RSU_DEBUG_AMPDU, "%s: mac=%s, tid=%d, ssn=%d\n",
1584 	    __func__,
1585 	    ether_sprintf(ba->mac_addr),
1586 	    (int) ba->tid,
1587 	    (int) le16toh(ba->ssn));
1588 
1589 	/* XXX do node lookup; this is STA specific */
1590 
1591 	ni = ieee80211_ref_node(vap->iv_bss);
1592 	ieee80211_ampdu_rx_start_ext(ni, ba->tid, le16toh(ba->ssn) >> 4, 32);
1593 	ieee80211_free_node(ni);
1594 }
1595 
1596 static void
1597 rsu_rx_event(struct rsu_softc *sc, uint8_t code, uint8_t *buf, int len)
1598 {
1599 	struct ieee80211com *ic = &sc->sc_ic;
1600 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1601 
1602 	RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD,
1603 	    "%s: Rx event code=%d len=%d\n", __func__, code, len);
1604 	switch (code) {
1605 	case R92S_EVT_SURVEY:
1606 		rsu_event_survey(sc, buf, len);
1607 		break;
1608 	case R92S_EVT_SURVEY_DONE:
1609 		RSU_DPRINTF(sc, RSU_DEBUG_SCAN,
1610 		    "%s: site survey pass %d done, found %d BSS\n",
1611 		    __func__, sc->sc_scan_pass, le32toh(*(uint32_t *)buf));
1612 		sc->sc_scanning = 0;
1613 		if (vap->iv_state != IEEE80211_S_SCAN)
1614 			break;	/* Ignore if not scanning. */
1615 
1616 		/*
1617 		 * XXX TODO: This needs to be done without a transition to
1618 		 * the SCAN state again.  Grr.
1619 		 */
1620 		if (sc->sc_scan_pass == 0 && vap->iv_des_nssid != 0) {
1621 			/* Schedule a directed scan for hidden APs. */
1622 			/* XXX bad! */
1623 			sc->sc_scan_pass = 1;
1624 			RSU_UNLOCK(sc);
1625 			ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1626 			RSU_LOCK(sc);
1627 			break;
1628 		}
1629 		sc->sc_scan_pass = 0;
1630 		break;
1631 	case R92S_EVT_JOIN_BSS:
1632 		if (vap->iv_state == IEEE80211_S_AUTH)
1633 			rsu_event_join_bss(sc, buf, len);
1634 		break;
1635 	case R92S_EVT_DEL_STA:
1636 		RSU_DPRINTF(sc, RSU_DEBUG_FWCMD | RSU_DEBUG_STATE,
1637 		    "%s: disassociated from %s\n", __func__,
1638 		    ether_sprintf(buf));
1639 		if (vap->iv_state == IEEE80211_S_RUN &&
1640 		    IEEE80211_ADDR_EQ(vap->iv_bss->ni_bssid, buf)) {
1641 			RSU_UNLOCK(sc);
1642 			ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1643 			RSU_LOCK(sc);
1644 		}
1645 		break;
1646 	case R92S_EVT_WPS_PBC:
1647 		RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD,
1648 		    "%s: WPS PBC pushed.\n", __func__);
1649 		break;
1650 	case R92S_EVT_FWDBG:
1651 		buf[60] = '\0';
1652 		RSU_DPRINTF(sc, RSU_DEBUG_FWDBG, "FWDBG: %s\n", (char *)buf);
1653 		break;
1654 	case R92S_EVT_ADDBA_REQ_REPORT:
1655 		rsu_event_addba_req_report(sc, buf, len);
1656 		break;
1657 	default:
1658 		device_printf(sc->sc_dev, "%s: unhandled code (%d)\n", __func__, code);
1659 		break;
1660 	}
1661 }
1662 
1663 static void
1664 rsu_rx_multi_event(struct rsu_softc *sc, uint8_t *buf, int len)
1665 {
1666 	struct r92s_fw_cmd_hdr *cmd;
1667 	int cmdsz;
1668 
1669 	RSU_DPRINTF(sc, RSU_DEBUG_RX, "%s: Rx events len=%d\n", __func__, len);
1670 
1671 	/* Skip Rx status. */
1672 	buf += sizeof(struct r92s_rx_stat);
1673 	len -= sizeof(struct r92s_rx_stat);
1674 
1675 	/* Process all events. */
1676 	for (;;) {
1677 		/* Check that command header fits. */
1678 		if (__predict_false(len < sizeof(*cmd)))
1679 			break;
1680 		cmd = (struct r92s_fw_cmd_hdr *)buf;
1681 		/* Check that command payload fits. */
1682 		cmdsz = le16toh(cmd->len);
1683 		if (__predict_false(len < sizeof(*cmd) + cmdsz))
1684 			break;
1685 
1686 		/* Process firmware event. */
1687 		rsu_rx_event(sc, cmd->code, (uint8_t *)&cmd[1], cmdsz);
1688 
1689 		if (!(cmd->seq & R92S_FW_CMD_MORE))
1690 			break;
1691 		buf += sizeof(*cmd) + cmdsz;
1692 		len -= sizeof(*cmd) + cmdsz;
1693 	}
1694 }
1695 
1696 #if 0
1697 static int8_t
1698 rsu_get_rssi(struct rsu_softc *sc, int rate, void *physt)
1699 {
1700 	static const int8_t cckoff[] = { 14, -2, -20, -40 };
1701 	struct r92s_rx_phystat *phy;
1702 	struct r92s_rx_cck *cck;
1703 	uint8_t rpt;
1704 	int8_t rssi;
1705 
1706 	if (rate <= 3) {
1707 		cck = (struct r92s_rx_cck *)physt;
1708 		rpt = (cck->agc_rpt >> 6) & 0x3;
1709 		rssi = cck->agc_rpt & 0x3e;
1710 		rssi = cckoff[rpt] - rssi;
1711 	} else {	/* OFDM/HT. */
1712 		phy = (struct r92s_rx_phystat *)physt;
1713 		rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 106;
1714 	}
1715 	return (rssi);
1716 }
1717 #endif
1718 
1719 static struct mbuf *
1720 rsu_rx_frame(struct rsu_softc *sc, uint8_t *buf, int pktlen)
1721 {
1722 	struct ieee80211com *ic = &sc->sc_ic;
1723 	struct ieee80211_frame *wh;
1724 	struct r92s_rx_stat *stat;
1725 	uint32_t rxdw0, rxdw3;
1726 	struct mbuf *m;
1727 	uint8_t rate;
1728 	int infosz;
1729 
1730 	stat = (struct r92s_rx_stat *)buf;
1731 	rxdw0 = le32toh(stat->rxdw0);
1732 	rxdw3 = le32toh(stat->rxdw3);
1733 
1734 	if (__predict_false(rxdw0 & R92S_RXDW0_CRCERR)) {
1735 		counter_u64_add(ic->ic_ierrors, 1);
1736 		return NULL;
1737 	}
1738 	if (__predict_false(pktlen < sizeof(*wh) || pktlen > MCLBYTES)) {
1739 		counter_u64_add(ic->ic_ierrors, 1);
1740 		return NULL;
1741 	}
1742 
1743 	rate = MS(rxdw3, R92S_RXDW3_RATE);
1744 	infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
1745 
1746 #if 0
1747 	/* Get RSSI from PHY status descriptor if present. */
1748 	if (infosz != 0)
1749 		*rssi = rsu_get_rssi(sc, rate, &stat[1]);
1750 	else
1751 		*rssi = 0;
1752 #endif
1753 
1754 	RSU_DPRINTF(sc, RSU_DEBUG_RX,
1755 	    "%s: Rx frame len=%d rate=%d infosz=%d\n",
1756 	    __func__, pktlen, rate, infosz);
1757 
1758 	m = m_get2(pktlen, M_NOWAIT, MT_DATA, M_PKTHDR);
1759 	if (__predict_false(m == NULL)) {
1760 		counter_u64_add(ic->ic_ierrors, 1);
1761 		return NULL;
1762 	}
1763 	/* Hardware does Rx TCP checksum offload. */
1764 	if (rxdw3 & R92S_RXDW3_TCPCHKVALID) {
1765 		if (__predict_true(rxdw3 & R92S_RXDW3_TCPCHKRPT))
1766 			m->m_pkthdr.csum_flags |= CSUM_DATA_VALID;
1767 	}
1768 	wh = (struct ieee80211_frame *)((uint8_t *)&stat[1] + infosz);
1769 	memcpy(mtod(m, uint8_t *), wh, pktlen);
1770 	m->m_pkthdr.len = m->m_len = pktlen;
1771 
1772 	if (ieee80211_radiotap_active(ic)) {
1773 		struct rsu_rx_radiotap_header *tap = &sc->sc_rxtap;
1774 
1775 		/* Map HW rate index to 802.11 rate. */
1776 		tap->wr_flags = 2;
1777 		if (!(rxdw3 & R92S_RXDW3_HTC)) {
1778 			switch (rate) {
1779 			/* CCK. */
1780 			case  0: tap->wr_rate =   2; break;
1781 			case  1: tap->wr_rate =   4; break;
1782 			case  2: tap->wr_rate =  11; break;
1783 			case  3: tap->wr_rate =  22; break;
1784 			/* OFDM. */
1785 			case  4: tap->wr_rate =  12; break;
1786 			case  5: tap->wr_rate =  18; break;
1787 			case  6: tap->wr_rate =  24; break;
1788 			case  7: tap->wr_rate =  36; break;
1789 			case  8: tap->wr_rate =  48; break;
1790 			case  9: tap->wr_rate =  72; break;
1791 			case 10: tap->wr_rate =  96; break;
1792 			case 11: tap->wr_rate = 108; break;
1793 			}
1794 		} else if (rate >= 12) {	/* MCS0~15. */
1795 			/* Bit 7 set means HT MCS instead of rate. */
1796 			tap->wr_rate = 0x80 | (rate - 12);
1797 		}
1798 #if 0
1799 		tap->wr_dbm_antsignal = *rssi;
1800 #endif
1801 		/* XXX not nice */
1802 		tap->wr_dbm_antsignal = rsu_hwrssi_to_rssi(sc, sc->sc_currssi);
1803 		tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
1804 		tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
1805 	}
1806 
1807 	return (m);
1808 }
1809 
1810 static struct mbuf *
1811 rsu_rx_multi_frame(struct rsu_softc *sc, uint8_t *buf, int len)
1812 {
1813 	struct r92s_rx_stat *stat;
1814 	uint32_t rxdw0;
1815 	int totlen, pktlen, infosz, npkts;
1816 	struct mbuf *m, *m0 = NULL, *prevm = NULL;
1817 
1818 	/* Get the number of encapsulated frames. */
1819 	stat = (struct r92s_rx_stat *)buf;
1820 	npkts = MS(le32toh(stat->rxdw2), R92S_RXDW2_PKTCNT);
1821 	RSU_DPRINTF(sc, RSU_DEBUG_RX,
1822 	    "%s: Rx %d frames in one chunk\n", __func__, npkts);
1823 
1824 	/* Process all of them. */
1825 	while (npkts-- > 0) {
1826 		if (__predict_false(len < sizeof(*stat)))
1827 			break;
1828 		stat = (struct r92s_rx_stat *)buf;
1829 		rxdw0 = le32toh(stat->rxdw0);
1830 
1831 		pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN);
1832 		if (__predict_false(pktlen == 0))
1833 			break;
1834 
1835 		infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
1836 
1837 		/* Make sure everything fits in xfer. */
1838 		totlen = sizeof(*stat) + infosz + pktlen;
1839 		if (__predict_false(totlen > len))
1840 			break;
1841 
1842 		/* Process 802.11 frame. */
1843 		m = rsu_rx_frame(sc, buf, pktlen);
1844 		if (m0 == NULL)
1845 			m0 = m;
1846 		if (prevm == NULL)
1847 			prevm = m;
1848 		else {
1849 			prevm->m_next = m;
1850 			prevm = m;
1851 		}
1852 		/* Next chunk is 128-byte aligned. */
1853 		totlen = (totlen + 127) & ~127;
1854 		buf += totlen;
1855 		len -= totlen;
1856 	}
1857 
1858 	return (m0);
1859 }
1860 
1861 static struct mbuf *
1862 rsu_rxeof(struct usb_xfer *xfer, struct rsu_data *data)
1863 {
1864 	struct rsu_softc *sc = data->sc;
1865 	struct ieee80211com *ic = &sc->sc_ic;
1866 	struct r92s_rx_stat *stat;
1867 	int len;
1868 
1869 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
1870 
1871 	if (__predict_false(len < sizeof(*stat))) {
1872 		DPRINTF("xfer too short %d\n", len);
1873 		counter_u64_add(ic->ic_ierrors, 1);
1874 		return (NULL);
1875 	}
1876 	/* Determine if it is a firmware C2H event or an 802.11 frame. */
1877 	stat = (struct r92s_rx_stat *)data->buf;
1878 	if ((le32toh(stat->rxdw1) & 0x1ff) == 0x1ff) {
1879 		rsu_rx_multi_event(sc, data->buf, len);
1880 		/* No packets to process. */
1881 		return (NULL);
1882 	} else
1883 		return (rsu_rx_multi_frame(sc, data->buf, len));
1884 }
1885 
1886 static void
1887 rsu_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
1888 {
1889 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
1890 	struct ieee80211com *ic = &sc->sc_ic;
1891 	struct ieee80211_frame *wh;
1892 	struct ieee80211_node *ni;
1893 	struct mbuf *m = NULL, *next;
1894 	struct rsu_data *data;
1895 
1896 	RSU_ASSERT_LOCKED(sc);
1897 
1898 	switch (USB_GET_STATE(xfer)) {
1899 	case USB_ST_TRANSFERRED:
1900 		data = STAILQ_FIRST(&sc->sc_rx_active);
1901 		if (data == NULL)
1902 			goto tr_setup;
1903 		STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
1904 		m = rsu_rxeof(xfer, data);
1905 		STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
1906 		/* FALLTHROUGH */
1907 	case USB_ST_SETUP:
1908 tr_setup:
1909 		/*
1910 		 * XXX TODO: if we have an mbuf list, but then
1911 		 * we hit data == NULL, what now?
1912 		 */
1913 		data = STAILQ_FIRST(&sc->sc_rx_inactive);
1914 		if (data == NULL) {
1915 			KASSERT(m == NULL, ("mbuf isn't NULL"));
1916 			return;
1917 		}
1918 		STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next);
1919 		STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next);
1920 		usbd_xfer_set_frame_data(xfer, 0, data->buf,
1921 		    usbd_xfer_max_len(xfer));
1922 		usbd_transfer_submit(xfer);
1923 		/*
1924 		 * To avoid LOR we should unlock our private mutex here to call
1925 		 * ieee80211_input() because here is at the end of a USB
1926 		 * callback and safe to unlock.
1927 		 */
1928 		RSU_UNLOCK(sc);
1929 		while (m != NULL) {
1930 			int rssi;
1931 
1932 			/* Cheat and get the last calibrated RSSI */
1933 			rssi = rsu_hwrssi_to_rssi(sc, sc->sc_currssi);
1934 
1935 			next = m->m_next;
1936 			m->m_next = NULL;
1937 			wh = mtod(m, struct ieee80211_frame *);
1938 			ni = ieee80211_find_rxnode(ic,
1939 			    (struct ieee80211_frame_min *)wh);
1940 			if (ni != NULL) {
1941 				if (ni->ni_flags & IEEE80211_NODE_HT)
1942 					m->m_flags |= M_AMPDU;
1943 				(void)ieee80211_input(ni, m, rssi, -96);
1944 				ieee80211_free_node(ni);
1945 			} else
1946 				(void)ieee80211_input_all(ic, m, rssi, -96);
1947 			m = next;
1948 		}
1949 		RSU_LOCK(sc);
1950 		break;
1951 	default:
1952 		/* needs it to the inactive queue due to a error. */
1953 		data = STAILQ_FIRST(&sc->sc_rx_active);
1954 		if (data != NULL) {
1955 			STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
1956 			STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
1957 		}
1958 		if (error != USB_ERR_CANCELLED) {
1959 			usbd_xfer_set_stall(xfer);
1960 			counter_u64_add(ic->ic_ierrors, 1);
1961 			goto tr_setup;
1962 		}
1963 		break;
1964 	}
1965 
1966 }
1967 
1968 static void
1969 rsu_txeof(struct usb_xfer *xfer, struct rsu_data *data)
1970 {
1971 #ifdef	USB_DEBUG
1972 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
1973 #endif
1974 
1975 	RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: called; data=%p\n",
1976 	    __func__,
1977 	    data);
1978 
1979 	if (data->m) {
1980 		/* XXX status? */
1981 		ieee80211_tx_complete(data->ni, data->m, 0);
1982 		data->m = NULL;
1983 		data->ni = NULL;
1984 	}
1985 }
1986 
1987 static void
1988 rsu_bulk_tx_callback_sub(struct usb_xfer *xfer, usb_error_t error,
1989     uint8_t which)
1990 {
1991 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
1992 	struct ieee80211com *ic = &sc->sc_ic;
1993 	struct rsu_data *data;
1994 
1995 	RSU_ASSERT_LOCKED(sc);
1996 
1997 	switch (USB_GET_STATE(xfer)) {
1998 	case USB_ST_TRANSFERRED:
1999 		data = STAILQ_FIRST(&sc->sc_tx_active[which]);
2000 		if (data == NULL)
2001 			goto tr_setup;
2002 		RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: transfer done %p\n",
2003 		    __func__, data);
2004 		STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
2005 		rsu_txeof(xfer, data);
2006 		rsu_freebuf(sc, data);
2007 		/* FALLTHROUGH */
2008 	case USB_ST_SETUP:
2009 tr_setup:
2010 		data = STAILQ_FIRST(&sc->sc_tx_pending[which]);
2011 		if (data == NULL) {
2012 			RSU_DPRINTF(sc, RSU_DEBUG_TXDONE,
2013 			    "%s: empty pending queue sc %p\n", __func__, sc);
2014 			return;
2015 		}
2016 		STAILQ_REMOVE_HEAD(&sc->sc_tx_pending[which], next);
2017 		STAILQ_INSERT_TAIL(&sc->sc_tx_active[which], data, next);
2018 		usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen);
2019 		RSU_DPRINTF(sc, RSU_DEBUG_TXDONE,
2020 		    "%s: submitting transfer %p\n",
2021 		    __func__,
2022 		    data);
2023 		usbd_transfer_submit(xfer);
2024 		break;
2025 	default:
2026 		data = STAILQ_FIRST(&sc->sc_tx_active[which]);
2027 		if (data != NULL) {
2028 			STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
2029 			rsu_txeof(xfer, data);
2030 			rsu_freebuf(sc, data);
2031 		}
2032 		counter_u64_add(ic->ic_oerrors, 1);
2033 
2034 		if (error != USB_ERR_CANCELLED) {
2035 			usbd_xfer_set_stall(xfer);
2036 			goto tr_setup;
2037 		}
2038 		break;
2039 	}
2040 
2041 	/*
2042 	 * XXX TODO: if the queue is low, flush out FF TX frames.
2043 	 * Remember to unlock the driver for now; net80211 doesn't
2044 	 * defer it for us.
2045 	 */
2046 }
2047 
2048 static void
2049 rsu_bulk_tx_callback_be_bk(struct usb_xfer *xfer, usb_error_t error)
2050 {
2051 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2052 
2053 	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_BE_BK);
2054 
2055 	/* This kicks the TX taskqueue */
2056 	rsu_start(sc);
2057 }
2058 
2059 static void
2060 rsu_bulk_tx_callback_vi_vo(struct usb_xfer *xfer, usb_error_t error)
2061 {
2062 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2063 
2064 	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_VI_VO);
2065 
2066 	/* This kicks the TX taskqueue */
2067 	rsu_start(sc);
2068 }
2069 
2070 static void
2071 rsu_bulk_tx_callback_h2c(struct usb_xfer *xfer, usb_error_t error)
2072 {
2073 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2074 
2075 	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_H2C);
2076 
2077 	/* This kicks the TX taskqueue */
2078 	rsu_start(sc);
2079 }
2080 
2081 /*
2082  * Transmit the given frame.
2083  *
2084  * This doesn't free the node or mbuf upon failure.
2085  */
2086 static int
2087 rsu_tx_start(struct rsu_softc *sc, struct ieee80211_node *ni,
2088     struct mbuf *m0, struct rsu_data *data)
2089 {
2090 	struct ieee80211com *ic = &sc->sc_ic;
2091         struct ieee80211vap *vap = ni->ni_vap;
2092 	struct ieee80211_frame *wh;
2093 	struct ieee80211_key *k = NULL;
2094 	struct r92s_tx_desc *txd;
2095 	uint8_t type;
2096 	int prio = 0;
2097 	uint8_t which;
2098 	int hasqos;
2099 	int xferlen;
2100 	int qid;
2101 
2102 	RSU_ASSERT_LOCKED(sc);
2103 
2104 	wh = mtod(m0, struct ieee80211_frame *);
2105 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2106 
2107 	RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: data=%p, m=%p\n",
2108 	    __func__, data, m0);
2109 
2110 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
2111 		k = ieee80211_crypto_encap(ni, m0);
2112 		if (k == NULL) {
2113 			device_printf(sc->sc_dev,
2114 			    "ieee80211_crypto_encap returns NULL.\n");
2115 			/* XXX we don't expect the fragmented frames */
2116 			return (ENOBUFS);
2117 		}
2118 		wh = mtod(m0, struct ieee80211_frame *);
2119 	}
2120 	/* If we have QoS then use it */
2121 	/* XXX TODO: mbuf WME/PRI versus TID? */
2122 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
2123 		/* Has QoS */
2124 		prio = M_WME_GETAC(m0);
2125 		which = rsu_wme_ac_xfer_map[prio];
2126 		hasqos = 1;
2127 	} else {
2128 		/* Non-QoS TID */
2129 		/* XXX TODO: tid=0 for non-qos TID? */
2130 		which = rsu_wme_ac_xfer_map[WME_AC_BE];
2131 		hasqos = 0;
2132 		prio = 0;
2133 	}
2134 
2135 	qid = rsu_ac2qid[prio];
2136 #if 0
2137 	switch (type) {
2138 	case IEEE80211_FC0_TYPE_CTL:
2139 	case IEEE80211_FC0_TYPE_MGT:
2140 		which = rsu_wme_ac_xfer_map[WME_AC_VO];
2141 		break;
2142 	default:
2143 		which = rsu_wme_ac_xfer_map[M_WME_GETAC(m0)];
2144 		break;
2145 	}
2146 	hasqos = 0;
2147 #endif
2148 
2149 	RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: pri=%d, which=%d, hasqos=%d\n",
2150 	    __func__,
2151 	    prio,
2152 	    which,
2153 	    hasqos);
2154 
2155 	/* Fill Tx descriptor. */
2156 	txd = (struct r92s_tx_desc *)data->buf;
2157 	memset(txd, 0, sizeof(*txd));
2158 
2159 	txd->txdw0 |= htole32(
2160 	    SM(R92S_TXDW0_PKTLEN, m0->m_pkthdr.len) |
2161 	    SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
2162 	    R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
2163 
2164 	txd->txdw1 |= htole32(
2165 	    SM(R92S_TXDW1_MACID, R92S_MACID_BSS) | SM(R92S_TXDW1_QSEL, qid));
2166 	if (!hasqos)
2167 		txd->txdw1 |= htole32(R92S_TXDW1_NONQOS);
2168 #ifdef notyet
2169 	if (k != NULL) {
2170 		switch (k->wk_cipher->ic_cipher) {
2171 		case IEEE80211_CIPHER_WEP:
2172 			cipher = R92S_TXDW1_CIPHER_WEP;
2173 			break;
2174 		case IEEE80211_CIPHER_TKIP:
2175 			cipher = R92S_TXDW1_CIPHER_TKIP;
2176 			break;
2177 		case IEEE80211_CIPHER_AES_CCM:
2178 			cipher = R92S_TXDW1_CIPHER_AES;
2179 			break;
2180 		default:
2181 			cipher = R92S_TXDW1_CIPHER_NONE;
2182 		}
2183 		txd->txdw1 |= htole32(
2184 		    SM(R92S_TXDW1_CIPHER, cipher) |
2185 		    SM(R92S_TXDW1_KEYIDX, k->k_id));
2186 	}
2187 #endif
2188 	/* XXX todo: set AGGEN bit if appropriate? */
2189 	txd->txdw2 |= htole32(R92S_TXDW2_BK);
2190 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
2191 		txd->txdw2 |= htole32(R92S_TXDW2_BMCAST);
2192 	/*
2193 	 * Firmware will use and increment the sequence number for the
2194 	 * specified priority.
2195 	 */
2196 	txd->txdw3 |= htole32(SM(R92S_TXDW3_SEQ, prio));
2197 
2198 	if (ieee80211_radiotap_active_vap(vap)) {
2199 		struct rsu_tx_radiotap_header *tap = &sc->sc_txtap;
2200 
2201 		tap->wt_flags = 0;
2202 		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
2203 		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
2204 		ieee80211_radiotap_tx(vap, m0);
2205 	}
2206 
2207 	xferlen = sizeof(*txd) + m0->m_pkthdr.len;
2208 	m_copydata(m0, 0, m0->m_pkthdr.len, (caddr_t)&txd[1]);
2209 
2210 	data->buflen = xferlen;
2211 	data->ni = ni;
2212 	data->m = m0;
2213 	STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
2214 
2215 	/* start transfer, if any */
2216 	usbd_transfer_start(sc->sc_xfer[which]);
2217 	return (0);
2218 }
2219 
2220 static int
2221 rsu_transmit(struct ieee80211com *ic, struct mbuf *m)
2222 {
2223 	struct rsu_softc *sc = ic->ic_softc;
2224 	int error;
2225 
2226 	RSU_LOCK(sc);
2227 	if (!sc->sc_running) {
2228 		RSU_UNLOCK(sc);
2229 		return (ENXIO);
2230 	}
2231 
2232 	/*
2233 	 * XXX TODO: ensure that we treat 'm' as a list of frames
2234 	 * to transmit!
2235 	 */
2236 	error = mbufq_enqueue(&sc->sc_snd, m);
2237 	if (error) {
2238 		RSU_DPRINTF(sc, RSU_DEBUG_TX,
2239 		    "%s: mbufq_enable: failed (%d)\n",
2240 		    __func__,
2241 		    error);
2242 		RSU_UNLOCK(sc);
2243 		return (error);
2244 	}
2245 	RSU_UNLOCK(sc);
2246 
2247 	/* This kicks the TX taskqueue */
2248 	rsu_start(sc);
2249 
2250 	return (0);
2251 }
2252 
2253 static void
2254 rsu_drain_mbufq(struct rsu_softc *sc)
2255 {
2256 	struct mbuf *m;
2257 	struct ieee80211_node *ni;
2258 
2259 	RSU_ASSERT_LOCKED(sc);
2260 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
2261 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
2262 		m->m_pkthdr.rcvif = NULL;
2263 		ieee80211_free_node(ni);
2264 		m_freem(m);
2265 	}
2266 }
2267 
2268 static void
2269 _rsu_start(struct rsu_softc *sc)
2270 {
2271 	struct ieee80211_node *ni;
2272 	struct rsu_data *bf;
2273 	struct mbuf *m;
2274 
2275 	RSU_ASSERT_LOCKED(sc);
2276 
2277 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
2278 		bf = rsu_getbuf(sc);
2279 		if (bf == NULL) {
2280 			RSU_DPRINTF(sc, RSU_DEBUG_TX,
2281 			    "%s: failed to get buffer\n", __func__);
2282 			mbufq_prepend(&sc->sc_snd, m);
2283 			break;
2284 		}
2285 
2286 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
2287 		m->m_pkthdr.rcvif = NULL;
2288 
2289 		if (rsu_tx_start(sc, ni, m, bf) != 0) {
2290 			RSU_DPRINTF(sc, RSU_DEBUG_TX,
2291 			    "%s: failed to transmit\n", __func__);
2292 			if_inc_counter(ni->ni_vap->iv_ifp,
2293 			    IFCOUNTER_OERRORS, 1);
2294 			rsu_freebuf(sc, bf);
2295 			ieee80211_free_node(ni);
2296 			m_freem(m);
2297 			break;
2298 		}
2299 	}
2300 }
2301 
2302 static void
2303 rsu_start(struct rsu_softc *sc)
2304 {
2305 
2306 	taskqueue_enqueue(taskqueue_thread, &sc->tx_task);
2307 }
2308 
2309 static void
2310 rsu_parent(struct ieee80211com *ic)
2311 {
2312 	struct rsu_softc *sc = ic->ic_softc;
2313 	int startall = 0;
2314 
2315 	RSU_LOCK(sc);
2316 	if (ic->ic_nrunning > 0) {
2317 		if (!sc->sc_running) {
2318 			rsu_init(sc);
2319 			startall = 1;
2320 		}
2321 	} else if (sc->sc_running)
2322 		rsu_stop(sc);
2323 	RSU_UNLOCK(sc);
2324 
2325 	if (startall)
2326 		ieee80211_start_all(ic);
2327 }
2328 
2329 /*
2330  * Power on sequence for A-cut adapters.
2331  */
2332 static void
2333 rsu_power_on_acut(struct rsu_softc *sc)
2334 {
2335 	uint32_t reg;
2336 
2337 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
2338 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
2339 
2340 	/* Enable AFE macro block's bandgap and Mbias. */
2341 	rsu_write_1(sc, R92S_AFE_MISC,
2342 	    rsu_read_1(sc, R92S_AFE_MISC) |
2343 	    R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN);
2344 	/* Enable LDOA15 block. */
2345 	rsu_write_1(sc, R92S_LDOA15_CTRL,
2346 	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
2347 
2348 	rsu_write_1(sc, R92S_SPS1_CTRL,
2349 	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_LDEN);
2350 	rsu_ms_delay(sc, 2000);
2351 	/* Enable switch regulator block. */
2352 	rsu_write_1(sc, R92S_SPS1_CTRL,
2353 	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_SWEN);
2354 
2355 	rsu_write_4(sc, R92S_SPS1_CTRL, 0x00a7b267);
2356 
2357 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
2358 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
2359 
2360 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2361 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
2362 
2363 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
2364 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x90);
2365 
2366 	/* Enable AFE clock. */
2367 	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
2368 	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
2369 	/* Enable AFE PLL macro block. */
2370 	rsu_write_1(sc, R92S_AFE_PLL_CTRL,
2371 	    rsu_read_1(sc, R92S_AFE_PLL_CTRL) | 0x11);
2372 	/* Attach AFE PLL to MACTOP/BB. */
2373 	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
2374 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
2375 
2376 	/* Switch to 40MHz clock instead of 80MHz. */
2377 	rsu_write_2(sc, R92S_SYS_CLKR,
2378 	    rsu_read_2(sc, R92S_SYS_CLKR) & ~R92S_SYS_CLKSEL);
2379 
2380 	/* Enable MAC clock. */
2381 	rsu_write_2(sc, R92S_SYS_CLKR,
2382 	    rsu_read_2(sc, R92S_SYS_CLKR) |
2383 	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
2384 
2385 	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
2386 
2387 	/* Enable digital core and IOREG R/W. */
2388 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2389 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
2390 
2391 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2392 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
2393 
2394 	/* Switch the control path to firmware. */
2395 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
2396 	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
2397 	rsu_write_2(sc, R92S_SYS_CLKR, reg);
2398 
2399 	rsu_write_2(sc, R92S_CR, 0x37fc);
2400 
2401 	/* Fix USB RX FIFO issue. */
2402 	rsu_write_1(sc, 0xfe5c,
2403 	    rsu_read_1(sc, 0xfe5c) | 0x80);
2404 	rsu_write_1(sc, 0x00ab,
2405 	    rsu_read_1(sc, 0x00ab) | 0xc0);
2406 
2407 	rsu_write_1(sc, R92S_SYS_CLKR,
2408 	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
2409 }
2410 
2411 /*
2412  * Power on sequence for B-cut and C-cut adapters.
2413  */
2414 static void
2415 rsu_power_on_bcut(struct rsu_softc *sc)
2416 {
2417 	uint32_t reg;
2418 	int ntries;
2419 
2420 	/* Prevent eFuse leakage. */
2421 	rsu_write_1(sc, 0x37, 0xb0);
2422 	rsu_ms_delay(sc, 10);
2423 	rsu_write_1(sc, 0x37, 0x30);
2424 
2425 	/* Switch the control path to hardware. */
2426 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
2427 	if (reg & R92S_FWHW_SEL) {
2428 		rsu_write_2(sc, R92S_SYS_CLKR,
2429 		    reg & ~(R92S_SWHW_SEL | R92S_FWHW_SEL));
2430 	}
2431 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2432 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) & ~0x8c);
2433 	rsu_ms_delay(sc, 1);
2434 
2435 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
2436 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
2437 
2438 	reg = rsu_read_1(sc, R92S_AFE_MISC);
2439 	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN);
2440 	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN |
2441 	    R92S_AFE_MISC_MBEN | R92S_AFE_MISC_I32_EN);
2442 
2443 	/* Enable PLL. */
2444 	rsu_write_1(sc, R92S_LDOA15_CTRL,
2445 	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
2446 
2447 	rsu_write_1(sc, R92S_LDOV12D_CTRL,
2448 	    rsu_read_1(sc, R92S_LDOV12D_CTRL) | R92S_LDV12_EN);
2449 
2450 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
2451 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
2452 
2453 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2454 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
2455 
2456 	/* Support 64KB IMEM. */
2457 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
2458 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x97);
2459 
2460 	/* Enable AFE clock. */
2461 	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
2462 	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
2463 	/* Enable AFE PLL macro block. */
2464 	reg = rsu_read_1(sc, R92S_AFE_PLL_CTRL);
2465 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
2466 	rsu_ms_delay(sc, 1);
2467 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x51);
2468 	rsu_ms_delay(sc, 1);
2469 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
2470 	rsu_ms_delay(sc, 1);
2471 
2472 	/* Attach AFE PLL to MACTOP/BB. */
2473 	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
2474 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
2475 
2476 	/* Switch to 40MHz clock. */
2477 	rsu_write_1(sc, R92S_SYS_CLKR, 0x00);
2478 	/* Disable CPU clock and 80MHz SSC. */
2479 	rsu_write_1(sc, R92S_SYS_CLKR,
2480 	    rsu_read_1(sc, R92S_SYS_CLKR) | 0xa0);
2481 	/* Enable MAC clock. */
2482 	rsu_write_2(sc, R92S_SYS_CLKR,
2483 	    rsu_read_2(sc, R92S_SYS_CLKR) |
2484 	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
2485 
2486 	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
2487 
2488 	/* Enable digital core and IOREG R/W. */
2489 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2490 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
2491 
2492 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2493 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
2494 
2495 	/* Switch the control path to firmware. */
2496 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
2497 	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
2498 	rsu_write_2(sc, R92S_SYS_CLKR, reg);
2499 
2500 	rsu_write_2(sc, R92S_CR, 0x37fc);
2501 
2502 	/* Fix USB RX FIFO issue. */
2503 	rsu_write_1(sc, 0xfe5c,
2504 	    rsu_read_1(sc, 0xfe5c) | 0x80);
2505 
2506 	rsu_write_1(sc, R92S_SYS_CLKR,
2507 	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
2508 
2509 	rsu_write_1(sc, 0xfe1c, 0x80);
2510 
2511 	/* Make sure TxDMA is ready to download firmware. */
2512 	for (ntries = 0; ntries < 20; ntries++) {
2513 		reg = rsu_read_1(sc, R92S_TCR);
2514 		if ((reg & (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) ==
2515 		    (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT))
2516 			break;
2517 		rsu_ms_delay(sc, 1);
2518 	}
2519 	if (ntries == 20) {
2520 		RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_TX,
2521 		    "%s: TxDMA is not ready\n",
2522 		    __func__);
2523 		/* Reset TxDMA. */
2524 		reg = rsu_read_1(sc, R92S_CR);
2525 		rsu_write_1(sc, R92S_CR, reg & ~R92S_CR_TXDMA_EN);
2526 		rsu_ms_delay(sc, 1);
2527 		rsu_write_1(sc, R92S_CR, reg | R92S_CR_TXDMA_EN);
2528 	}
2529 }
2530 
2531 static void
2532 rsu_power_off(struct rsu_softc *sc)
2533 {
2534 	/* Turn RF off. */
2535 	rsu_write_1(sc, R92S_RF_CTRL, 0x00);
2536 	rsu_ms_delay(sc, 5);
2537 
2538 	/* Turn MAC off. */
2539 	/* Switch control path. */
2540 	rsu_write_1(sc, R92S_SYS_CLKR + 1, 0x38);
2541 	/* Reset MACTOP. */
2542 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x70);
2543 	rsu_write_1(sc, R92S_PMC_FSM, 0x06);
2544 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 0, 0xf9);
2545 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, 0xe8);
2546 
2547 	/* Disable AFE PLL. */
2548 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, 0x00);
2549 	/* Disable A15V. */
2550 	rsu_write_1(sc, R92S_LDOA15_CTRL, 0x54);
2551 	/* Disable eFuse 1.2V. */
2552 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x50);
2553 	rsu_write_1(sc, R92S_LDOV12D_CTRL, 0x24);
2554 	/* Enable AFE macro block's bandgap and Mbias. */
2555 	rsu_write_1(sc, R92S_AFE_MISC, 0x30);
2556 	/* Disable 1.6V LDO. */
2557 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x56);
2558 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x43);
2559 
2560 	/* Firmware - tell it to switch things off */
2561 	(void) rsu_set_fw_power_state(sc, RSU_PWR_OFF);
2562 }
2563 
2564 static int
2565 rsu_fw_loadsection(struct rsu_softc *sc, const uint8_t *buf, int len)
2566 {
2567 	const uint8_t which = rsu_wme_ac_xfer_map[WME_AC_VO];
2568 	struct rsu_data *data;
2569 	struct r92s_tx_desc *txd;
2570 	int mlen;
2571 
2572 	while (len > 0) {
2573 		data = rsu_getbuf(sc);
2574 		if (data == NULL)
2575 			return (ENOMEM);
2576 		txd = (struct r92s_tx_desc *)data->buf;
2577 		memset(txd, 0, sizeof(*txd));
2578 		if (len <= RSU_TXBUFSZ - sizeof(*txd)) {
2579 			/* Last chunk. */
2580 			txd->txdw0 |= htole32(R92S_TXDW0_LINIP);
2581 			mlen = len;
2582 		} else
2583 			mlen = RSU_TXBUFSZ - sizeof(*txd);
2584 		txd->txdw0 |= htole32(SM(R92S_TXDW0_PKTLEN, mlen));
2585 		memcpy(&txd[1], buf, mlen);
2586 		data->buflen = sizeof(*txd) + mlen;
2587 		RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FW | RSU_DEBUG_RESET,
2588 		    "%s: starting transfer %p\n",
2589 		    __func__, data);
2590 		STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
2591 		buf += mlen;
2592 		len -= mlen;
2593 	}
2594 	usbd_transfer_start(sc->sc_xfer[which]);
2595 	return (0);
2596 }
2597 
2598 static int
2599 rsu_load_firmware(struct rsu_softc *sc)
2600 {
2601 	const struct r92s_fw_hdr *hdr;
2602 	struct r92s_fw_priv *dmem;
2603 	struct ieee80211com *ic = &sc->sc_ic;
2604 	const uint8_t *imem, *emem;
2605 	int imemsz, ememsz;
2606 	const struct firmware *fw;
2607 	size_t size;
2608 	uint32_t reg;
2609 	int ntries, error;
2610 
2611 	if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY) {
2612 		RSU_DPRINTF(sc, RSU_DEBUG_ANY,
2613 		    "%s: Firmware already loaded\n",
2614 		    __func__);
2615 		return (0);
2616 	}
2617 
2618 	RSU_UNLOCK(sc);
2619 	/* Read firmware image from the filesystem. */
2620 	if ((fw = firmware_get("rsu-rtl8712fw")) == NULL) {
2621 		device_printf(sc->sc_dev,
2622 		    "%s: failed load firmware of file rsu-rtl8712fw\n",
2623 		    __func__);
2624 		RSU_LOCK(sc);
2625 		return (ENXIO);
2626 	}
2627 	RSU_LOCK(sc);
2628 	size = fw->datasize;
2629 	if (size < sizeof(*hdr)) {
2630 		device_printf(sc->sc_dev, "firmware too short\n");
2631 		error = EINVAL;
2632 		goto fail;
2633 	}
2634 	hdr = (const struct r92s_fw_hdr *)fw->data;
2635 	if (hdr->signature != htole16(0x8712) &&
2636 	    hdr->signature != htole16(0x8192)) {
2637 		device_printf(sc->sc_dev,
2638 		    "invalid firmware signature 0x%x\n",
2639 		    le16toh(hdr->signature));
2640 		error = EINVAL;
2641 		goto fail;
2642 	}
2643 	DPRINTF("FW V%d %02x-%02x %02x:%02x\n", le16toh(hdr->version),
2644 	    hdr->month, hdr->day, hdr->hour, hdr->minute);
2645 
2646 	/* Make sure that driver and firmware are in sync. */
2647 	if (hdr->privsz != htole32(sizeof(*dmem))) {
2648 		device_printf(sc->sc_dev, "unsupported firmware image\n");
2649 		error = EINVAL;
2650 		goto fail;
2651 	}
2652 	/* Get FW sections sizes. */
2653 	imemsz = le32toh(hdr->imemsz);
2654 	ememsz = le32toh(hdr->sramsz);
2655 	/* Check that all FW sections fit in image. */
2656 	if (size < sizeof(*hdr) + imemsz + ememsz) {
2657 		device_printf(sc->sc_dev, "firmware too short\n");
2658 		error = EINVAL;
2659 		goto fail;
2660 	}
2661 	imem = (const uint8_t *)&hdr[1];
2662 	emem = imem + imemsz;
2663 
2664 	/* Load IMEM section. */
2665 	error = rsu_fw_loadsection(sc, imem, imemsz);
2666 	if (error != 0) {
2667 		device_printf(sc->sc_dev,
2668 		    "could not load firmware section %s\n", "IMEM");
2669 		goto fail;
2670 	}
2671 	/* Wait for load to complete. */
2672 	for (ntries = 0; ntries != 50; ntries++) {
2673 		rsu_ms_delay(sc, 10);
2674 		reg = rsu_read_1(sc, R92S_TCR);
2675 		if (reg & R92S_TCR_IMEM_CODE_DONE)
2676 			break;
2677 	}
2678 	if (ntries == 50) {
2679 		device_printf(sc->sc_dev, "timeout waiting for IMEM transfer\n");
2680 		error = ETIMEDOUT;
2681 		goto fail;
2682 	}
2683 	/* Load EMEM section. */
2684 	error = rsu_fw_loadsection(sc, emem, ememsz);
2685 	if (error != 0) {
2686 		device_printf(sc->sc_dev,
2687 		    "could not load firmware section %s\n", "EMEM");
2688 		goto fail;
2689 	}
2690 	/* Wait for load to complete. */
2691 	for (ntries = 0; ntries != 50; ntries++) {
2692 		rsu_ms_delay(sc, 10);
2693 		reg = rsu_read_2(sc, R92S_TCR);
2694 		if (reg & R92S_TCR_EMEM_CODE_DONE)
2695 			break;
2696 	}
2697 	if (ntries == 50) {
2698 		device_printf(sc->sc_dev, "timeout waiting for EMEM transfer\n");
2699 		error = ETIMEDOUT;
2700 		goto fail;
2701 	}
2702 	/* Enable CPU. */
2703 	rsu_write_1(sc, R92S_SYS_CLKR,
2704 	    rsu_read_1(sc, R92S_SYS_CLKR) | R92S_SYS_CPU_CLKSEL);
2705 	if (!(rsu_read_1(sc, R92S_SYS_CLKR) & R92S_SYS_CPU_CLKSEL)) {
2706 		device_printf(sc->sc_dev, "could not enable system clock\n");
2707 		error = EIO;
2708 		goto fail;
2709 	}
2710 	rsu_write_2(sc, R92S_SYS_FUNC_EN,
2711 	    rsu_read_2(sc, R92S_SYS_FUNC_EN) | R92S_FEN_CPUEN);
2712 	if (!(rsu_read_2(sc, R92S_SYS_FUNC_EN) & R92S_FEN_CPUEN)) {
2713 		device_printf(sc->sc_dev,
2714 		    "could not enable microcontroller\n");
2715 		error = EIO;
2716 		goto fail;
2717 	}
2718 	/* Wait for CPU to initialize. */
2719 	for (ntries = 0; ntries < 100; ntries++) {
2720 		if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_IMEM_RDY)
2721 			break;
2722 		rsu_ms_delay(sc, 1);
2723 	}
2724 	if (ntries == 100) {
2725 		device_printf(sc->sc_dev,
2726 		    "timeout waiting for microcontroller\n");
2727 		error = ETIMEDOUT;
2728 		goto fail;
2729 	}
2730 
2731 	/* Update DMEM section before loading. */
2732 	dmem = __DECONST(struct r92s_fw_priv *, &hdr->priv);
2733 	memset(dmem, 0, sizeof(*dmem));
2734 	dmem->hci_sel = R92S_HCI_SEL_USB | R92S_HCI_SEL_8172;
2735 	dmem->nendpoints = sc->sc_nendpoints;
2736 	dmem->chip_version = sc->cut;
2737 	dmem->rf_config = sc->sc_rftype;
2738 	dmem->vcs_type = R92S_VCS_TYPE_AUTO;
2739 	dmem->vcs_mode = R92S_VCS_MODE_RTS_CTS;
2740 	dmem->turbo_mode = 0;
2741 	dmem->bw40_en = !! (ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40);
2742 	dmem->amsdu2ampdu_en = !! (sc->sc_ht);
2743 	dmem->ampdu_en = !! (sc->sc_ht);
2744 	dmem->agg_offload = !! (sc->sc_ht);
2745 	dmem->qos_en = 1;
2746 	dmem->ps_offload = 1;
2747 	dmem->lowpower_mode = 1;	/* XXX TODO: configurable? */
2748 	/* Load DMEM section. */
2749 	error = rsu_fw_loadsection(sc, (uint8_t *)dmem, sizeof(*dmem));
2750 	if (error != 0) {
2751 		device_printf(sc->sc_dev,
2752 		    "could not load firmware section %s\n", "DMEM");
2753 		goto fail;
2754 	}
2755 	/* Wait for load to complete. */
2756 	for (ntries = 0; ntries < 100; ntries++) {
2757 		if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_DMEM_CODE_DONE)
2758 			break;
2759 		rsu_ms_delay(sc, 1);
2760 	}
2761 	if (ntries == 100) {
2762 		device_printf(sc->sc_dev, "timeout waiting for %s transfer\n",
2763 		    "DMEM");
2764 		error = ETIMEDOUT;
2765 		goto fail;
2766 	}
2767 	/* Wait for firmware readiness. */
2768 	for (ntries = 0; ntries < 60; ntries++) {
2769 		if (!(rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY))
2770 			break;
2771 		rsu_ms_delay(sc, 1);
2772 	}
2773 	if (ntries == 60) {
2774 		device_printf(sc->sc_dev,
2775 		    "timeout waiting for firmware readiness\n");
2776 		error = ETIMEDOUT;
2777 		goto fail;
2778 	}
2779  fail:
2780 	firmware_put(fw, FIRMWARE_UNLOAD);
2781 	return (error);
2782 }
2783 
2784 
2785 static int
2786 rsu_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2787     const struct ieee80211_bpf_params *params)
2788 {
2789 	struct ieee80211com *ic = ni->ni_ic;
2790 	struct rsu_softc *sc = ic->ic_softc;
2791 	struct rsu_data *bf;
2792 
2793 	/* prevent management frames from being sent if we're not ready */
2794 	if (!sc->sc_running) {
2795 		m_freem(m);
2796 		return (ENETDOWN);
2797 	}
2798 	RSU_LOCK(sc);
2799 	bf = rsu_getbuf(sc);
2800 	if (bf == NULL) {
2801 		m_freem(m);
2802 		RSU_UNLOCK(sc);
2803 		return (ENOBUFS);
2804 	}
2805 	if (rsu_tx_start(sc, ni, m, bf) != 0) {
2806 		m_freem(m);
2807 		rsu_freebuf(sc, bf);
2808 		RSU_UNLOCK(sc);
2809 		return (EIO);
2810 	}
2811 	RSU_UNLOCK(sc);
2812 
2813 	return (0);
2814 }
2815 
2816 static void
2817 rsu_init(struct rsu_softc *sc)
2818 {
2819 	struct ieee80211com *ic = &sc->sc_ic;
2820 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2821 	uint8_t macaddr[IEEE80211_ADDR_LEN];
2822 	int error;
2823 	int i;
2824 
2825 	RSU_ASSERT_LOCKED(sc);
2826 
2827 	/* Ensure the mbuf queue is drained */
2828 	rsu_drain_mbufq(sc);
2829 
2830 	/* Init host async commands ring. */
2831 	sc->cmdq.cur = sc->cmdq.next = sc->cmdq.queued = 0;
2832 
2833 	/* Reset power management state. */
2834 	rsu_write_1(sc, R92S_USB_HRPWM, 0);
2835 
2836 	/* Power on adapter. */
2837 	if (sc->cut == 1)
2838 		rsu_power_on_acut(sc);
2839 	else
2840 		rsu_power_on_bcut(sc);
2841 
2842 	/* Load firmware. */
2843 	error = rsu_load_firmware(sc);
2844 	if (error != 0)
2845 		goto fail;
2846 
2847 	/* Enable Rx TCP checksum offload. */
2848 	rsu_write_4(sc, R92S_RCR,
2849 	    rsu_read_4(sc, R92S_RCR) | 0x04000000);
2850 	/* Append PHY status. */
2851 	rsu_write_4(sc, R92S_RCR,
2852 	    rsu_read_4(sc, R92S_RCR) | 0x02000000);
2853 
2854 	rsu_write_4(sc, R92S_CR,
2855 	    rsu_read_4(sc, R92S_CR) & ~0xff000000);
2856 
2857 	/* Use 128 bytes pages. */
2858 	rsu_write_1(sc, 0x00b5,
2859 	    rsu_read_1(sc, 0x00b5) | 0x01);
2860 	/* Enable USB Rx aggregation. */
2861 	rsu_write_1(sc, 0x00bd,
2862 	    rsu_read_1(sc, 0x00bd) | 0x80);
2863 	/* Set USB Rx aggregation threshold. */
2864 	rsu_write_1(sc, 0x00d9, 0x01);
2865 	/* Set USB Rx aggregation timeout (1.7ms/4). */
2866 	rsu_write_1(sc, 0xfe5b, 0x04);
2867 	/* Fix USB Rx FIFO issue. */
2868 	rsu_write_1(sc, 0xfe5c,
2869 	    rsu_read_1(sc, 0xfe5c) | 0x80);
2870 
2871 	/* Set MAC address. */
2872 	IEEE80211_ADDR_COPY(macaddr, vap ? vap->iv_myaddr : ic->ic_macaddr);
2873 	rsu_write_region_1(sc, R92S_MACID, macaddr, IEEE80211_ADDR_LEN);
2874 
2875 	/* It really takes 1.5 seconds for the firmware to boot: */
2876 	rsu_ms_delay(sc, 2000);
2877 
2878 	RSU_DPRINTF(sc, RSU_DEBUG_RESET, "%s: setting MAC address to %s\n",
2879 	    __func__,
2880 	    ether_sprintf(macaddr));
2881 	error = rsu_fw_cmd(sc, R92S_CMD_SET_MAC_ADDRESS, macaddr,
2882 	    IEEE80211_ADDR_LEN);
2883 	if (error != 0) {
2884 		device_printf(sc->sc_dev, "could not set MAC address\n");
2885 		goto fail;
2886 	}
2887 
2888 	/* Set PS mode fully active */
2889 	error = rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
2890 
2891 	if (error != 0) {
2892 		device_printf(sc->sc_dev, "could not set PS mode\n");
2893 		goto fail;
2894 	}
2895 
2896 	sc->sc_scan_pass = 0;
2897 	usbd_transfer_start(sc->sc_xfer[RSU_BULK_RX]);
2898 
2899 	/* We're ready to go. */
2900 	sc->sc_running = 1;
2901 	sc->sc_scanning = 0;
2902 	return;
2903 fail:
2904 	/* Need to stop all failed transfers, if any */
2905 	for (i = 0; i != RSU_N_TRANSFER; i++)
2906 		usbd_transfer_stop(sc->sc_xfer[i]);
2907 }
2908 
2909 static void
2910 rsu_stop(struct rsu_softc *sc)
2911 {
2912 	int i;
2913 
2914 	RSU_ASSERT_LOCKED(sc);
2915 
2916 	sc->sc_running = 0;
2917 	sc->sc_calibrating = 0;
2918 	taskqueue_cancel_timeout(taskqueue_thread, &sc->calib_task, NULL);
2919 	taskqueue_cancel(taskqueue_thread, &sc->tx_task, NULL);
2920 
2921 	/* Power off adapter. */
2922 	rsu_power_off(sc);
2923 
2924 	for (i = 0; i < RSU_N_TRANSFER; i++)
2925 		usbd_transfer_stop(sc->sc_xfer[i]);
2926 
2927 	/* Ensure the mbuf queue is drained */
2928 	rsu_drain_mbufq(sc);
2929 }
2930 
2931 /*
2932  * Note: usb_pause_mtx() actually releases the mutex before calling pause(),
2933  * which breaks any kind of driver serialisation.
2934  */
2935 static void
2936 rsu_ms_delay(struct rsu_softc *sc, int ms)
2937 {
2938 
2939 	//usb_pause_mtx(&sc->sc_mtx, hz / 1000);
2940 	DELAY(ms * 1000);
2941 }
2942