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