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