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