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