xref: /freebsd/sys/dev/usb/wlan/if_rsu.c (revision 38069501)
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 tx a-mpdu
26  *   o hostap / ibss / mesh
27  *   o power-save operation
28  */
29 
30 #include "opt_wlan.h"
31 
32 #include <sys/param.h>
33 #include <sys/endian.h>
34 #include <sys/sockio.h>
35 #include <sys/malloc.h>
36 #include <sys/mbuf.h>
37 #include <sys/kernel.h>
38 #include <sys/socket.h>
39 #include <sys/systm.h>
40 #include <sys/conf.h>
41 #include <sys/bus.h>
42 #include <sys/rman.h>
43 #include <sys/firmware.h>
44 #include <sys/module.h>
45 
46 #include <machine/bus.h>
47 #include <machine/resource.h>
48 
49 #include <net/bpf.h>
50 #include <net/if.h>
51 #include <net/if_var.h>
52 #include <net/if_arp.h>
53 #include <net/if_dl.h>
54 #include <net/if_media.h>
55 #include <net/if_types.h>
56 
57 #include <netinet/in.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/in_var.h>
60 #include <netinet/if_ether.h>
61 #include <netinet/ip.h>
62 
63 #include <net80211/ieee80211_var.h>
64 #include <net80211/ieee80211_regdomain.h>
65 #include <net80211/ieee80211_radiotap.h>
66 
67 #include <dev/usb/usb.h>
68 #include <dev/usb/usbdi.h>
69 #include "usbdevs.h"
70 
71 #include <dev/usb/wlan/if_rsureg.h>
72 
73 #ifdef USB_DEBUG
74 static int rsu_debug = 0;
75 SYSCTL_NODE(_hw_usb, OID_AUTO, rsu, CTLFLAG_RW, 0, "USB rsu");
76 SYSCTL_INT(_hw_usb_rsu, OID_AUTO, debug, CTLFLAG_RWTUN, &rsu_debug, 0,
77     "Debug level");
78 #define	RSU_DPRINTF(_sc, _flg, ...)					\
79 	do								\
80 		if (((_flg) == (RSU_DEBUG_ANY)) || (rsu_debug & (_flg))) \
81 			device_printf((_sc)->sc_dev, __VA_ARGS__);	\
82 	while (0)
83 #else
84 #define	RSU_DPRINTF(_sc, _flg, ...)
85 #endif
86 
87 static int rsu_enable_11n = 1;
88 TUNABLE_INT("hw.usb.rsu.enable_11n", &rsu_enable_11n);
89 
90 #define	RSU_DEBUG_ANY		0xffffffff
91 #define	RSU_DEBUG_TX		0x00000001
92 #define	RSU_DEBUG_RX		0x00000002
93 #define	RSU_DEBUG_RESET		0x00000004
94 #define	RSU_DEBUG_CALIB		0x00000008
95 #define	RSU_DEBUG_STATE		0x00000010
96 #define	RSU_DEBUG_SCAN		0x00000020
97 #define	RSU_DEBUG_FWCMD		0x00000040
98 #define	RSU_DEBUG_TXDONE	0x00000080
99 #define	RSU_DEBUG_FW		0x00000100
100 #define	RSU_DEBUG_FWDBG		0x00000200
101 #define	RSU_DEBUG_AMPDU		0x00000400
102 #define	RSU_DEBUG_KEY		0x00000800
103 #define	RSU_DEBUG_USB		0x00001000
104 
105 static const STRUCT_USB_HOST_ID rsu_devs[] = {
106 #define	RSU_HT_NOT_SUPPORTED 0
107 #define	RSU_HT_SUPPORTED 1
108 #define RSU_DEV_HT(v,p)  { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \
109 				   RSU_HT_SUPPORTED) }
110 #define RSU_DEV(v,p)     { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \
111 				   RSU_HT_NOT_SUPPORTED) }
112 	RSU_DEV(ASUS,			RTL8192SU),
113 	RSU_DEV(AZUREWAVE,		RTL8192SU_4),
114 	RSU_DEV_HT(ACCTON,		RTL8192SU),
115 	RSU_DEV_HT(ASUS,		USBN10),
116 	RSU_DEV_HT(AZUREWAVE,		RTL8192SU_1),
117 	RSU_DEV_HT(AZUREWAVE,		RTL8192SU_2),
118 	RSU_DEV_HT(AZUREWAVE,		RTL8192SU_3),
119 	RSU_DEV_HT(AZUREWAVE,		RTL8192SU_5),
120 	RSU_DEV_HT(BELKIN,		RTL8192SU_1),
121 	RSU_DEV_HT(BELKIN,		RTL8192SU_2),
122 	RSU_DEV_HT(BELKIN,		RTL8192SU_3),
123 	RSU_DEV_HT(CONCEPTRONIC2,	RTL8192SU_1),
124 	RSU_DEV_HT(CONCEPTRONIC2,	RTL8192SU_2),
125 	RSU_DEV_HT(CONCEPTRONIC2,	RTL8192SU_3),
126 	RSU_DEV_HT(COREGA,		RTL8192SU),
127 	RSU_DEV_HT(DLINK2,		DWA131A1),
128 	RSU_DEV_HT(DLINK2,		RTL8192SU_1),
129 	RSU_DEV_HT(DLINK2,		RTL8192SU_2),
130 	RSU_DEV_HT(EDIMAX,		RTL8192SU_1),
131 	RSU_DEV_HT(EDIMAX,		RTL8192SU_2),
132 	RSU_DEV_HT(EDIMAX,		EW7622UMN),
133 	RSU_DEV_HT(GUILLEMOT,		HWGUN54),
134 	RSU_DEV_HT(GUILLEMOT,		HWNUM300),
135 	RSU_DEV_HT(HAWKING,		RTL8192SU_1),
136 	RSU_DEV_HT(HAWKING,		RTL8192SU_2),
137 	RSU_DEV_HT(PLANEX2,		GWUSNANO),
138 	RSU_DEV_HT(REALTEK,		RTL8171),
139 	RSU_DEV_HT(REALTEK,		RTL8172),
140 	RSU_DEV_HT(REALTEK,		RTL8173),
141 	RSU_DEV_HT(REALTEK,		RTL8174),
142 	RSU_DEV_HT(REALTEK,		RTL8192SU),
143 	RSU_DEV_HT(REALTEK,		RTL8712),
144 	RSU_DEV_HT(REALTEK,		RTL8713),
145 	RSU_DEV_HT(SENAO,		RTL8192SU_1),
146 	RSU_DEV_HT(SENAO,		RTL8192SU_2),
147 	RSU_DEV_HT(SITECOMEU,		WL349V1),
148 	RSU_DEV_HT(SITECOMEU,		WL353),
149 	RSU_DEV_HT(SWEEX2,		LW154),
150 	RSU_DEV_HT(TRENDNET,		TEW646UBH),
151 #undef RSU_DEV_HT
152 #undef RSU_DEV
153 };
154 
155 static device_probe_t   rsu_match;
156 static device_attach_t  rsu_attach;
157 static device_detach_t  rsu_detach;
158 static usb_callback_t   rsu_bulk_tx_callback_be_bk;
159 static usb_callback_t   rsu_bulk_tx_callback_vi_vo;
160 static usb_callback_t   rsu_bulk_tx_callback_h2c;
161 static usb_callback_t   rsu_bulk_rx_callback;
162 static usb_error_t	rsu_do_request(struct rsu_softc *,
163 			    struct usb_device_request *, void *);
164 static struct ieee80211vap *
165 		rsu_vap_create(struct ieee80211com *, const char name[],
166 		    int, enum ieee80211_opmode, int, const uint8_t bssid[],
167 		    const uint8_t mac[]);
168 static void	rsu_vap_delete(struct ieee80211vap *);
169 static void	rsu_scan_start(struct ieee80211com *);
170 static void	rsu_scan_end(struct ieee80211com *);
171 static void	rsu_getradiocaps(struct ieee80211com *, int, int *,
172 		    struct ieee80211_channel[]);
173 static void	rsu_set_channel(struct ieee80211com *);
174 static void	rsu_scan_curchan(struct ieee80211_scan_state *, unsigned long);
175 static void	rsu_scan_mindwell(struct ieee80211_scan_state *);
176 static void	rsu_update_promisc(struct ieee80211com *);
177 static uint8_t	rsu_get_multi_pos(const uint8_t[]);
178 static void	rsu_set_multi(struct rsu_softc *);
179 static void	rsu_update_mcast(struct ieee80211com *);
180 static int	rsu_alloc_rx_list(struct rsu_softc *);
181 static void	rsu_free_rx_list(struct rsu_softc *);
182 static int	rsu_alloc_tx_list(struct rsu_softc *);
183 static void	rsu_free_tx_list(struct rsu_softc *);
184 static void	rsu_free_list(struct rsu_softc *, struct rsu_data [], int);
185 static struct rsu_data *_rsu_getbuf(struct rsu_softc *);
186 static struct rsu_data *rsu_getbuf(struct rsu_softc *);
187 static void	rsu_freebuf(struct rsu_softc *, struct rsu_data *);
188 static int	rsu_write_region_1(struct rsu_softc *, uint16_t, uint8_t *,
189 		    int);
190 static void	rsu_write_1(struct rsu_softc *, uint16_t, uint8_t);
191 static void	rsu_write_2(struct rsu_softc *, uint16_t, uint16_t);
192 static void	rsu_write_4(struct rsu_softc *, uint16_t, uint32_t);
193 static int	rsu_read_region_1(struct rsu_softc *, uint16_t, uint8_t *,
194 		    int);
195 static uint8_t	rsu_read_1(struct rsu_softc *, uint16_t);
196 static uint16_t	rsu_read_2(struct rsu_softc *, uint16_t);
197 static uint32_t	rsu_read_4(struct rsu_softc *, uint16_t);
198 static int	rsu_fw_iocmd(struct rsu_softc *, uint32_t);
199 static uint8_t	rsu_efuse_read_1(struct rsu_softc *, uint16_t);
200 static int	rsu_read_rom(struct rsu_softc *);
201 static int	rsu_fw_cmd(struct rsu_softc *, uint8_t, void *, int);
202 static void	rsu_calib_task(void *, int);
203 static void	rsu_tx_task(void *, int);
204 static void	rsu_set_led(struct rsu_softc *, int);
205 static int	rsu_monitor_newstate(struct ieee80211vap *,
206 		    enum ieee80211_state, int);
207 static int	rsu_newstate(struct ieee80211vap *, enum ieee80211_state, int);
208 static int	rsu_key_alloc(struct ieee80211vap *, struct ieee80211_key *,
209 		    ieee80211_keyix *, ieee80211_keyix *);
210 static int	rsu_process_key(struct ieee80211vap *,
211 		    const struct ieee80211_key *, int);
212 static int	rsu_key_set(struct ieee80211vap *,
213 		    const struct ieee80211_key *);
214 static int	rsu_key_delete(struct ieee80211vap *,
215 		    const struct ieee80211_key *);
216 static int	rsu_cam_read(struct rsu_softc *, uint8_t, uint32_t *);
217 static void	rsu_cam_write(struct rsu_softc *, uint8_t, uint32_t);
218 static int	rsu_key_check(struct rsu_softc *, ieee80211_keyix, int);
219 static uint8_t	rsu_crypto_mode(struct rsu_softc *, u_int, int);
220 static int	rsu_set_key_group(struct rsu_softc *,
221 		    const struct ieee80211_key *);
222 static int	rsu_set_key_pair(struct rsu_softc *,
223 		    const struct ieee80211_key *);
224 static int	rsu_reinit_static_keys(struct rsu_softc *);
225 static int	rsu_delete_key(struct rsu_softc *sc, ieee80211_keyix);
226 static void	rsu_delete_key_pair_cb(void *, int);
227 static int	rsu_site_survey(struct rsu_softc *,
228 		    struct ieee80211_scan_ssid *);
229 static int	rsu_join_bss(struct rsu_softc *, struct ieee80211_node *);
230 static int	rsu_disconnect(struct rsu_softc *);
231 static int	rsu_hwrssi_to_rssi(struct rsu_softc *, int hw_rssi);
232 static void	rsu_event_survey(struct rsu_softc *, uint8_t *, int);
233 static void	rsu_event_join_bss(struct rsu_softc *, uint8_t *, int);
234 static void	rsu_rx_event(struct rsu_softc *, uint8_t, uint8_t *, int);
235 static void	rsu_rx_multi_event(struct rsu_softc *, uint8_t *, int);
236 static int8_t	rsu_get_rssi(struct rsu_softc *, int, void *);
237 static struct mbuf * rsu_rx_copy_to_mbuf(struct rsu_softc *,
238 		    struct r92s_rx_stat *, int);
239 static uint32_t	rsu_get_tsf_low(struct rsu_softc *);
240 static uint32_t	rsu_get_tsf_high(struct rsu_softc *);
241 static struct ieee80211_node * rsu_rx_frame(struct rsu_softc *, struct mbuf *);
242 static struct mbuf * rsu_rx_multi_frame(struct rsu_softc *, uint8_t *, int);
243 static struct mbuf *
244 		rsu_rxeof(struct usb_xfer *, struct rsu_data *);
245 static void	rsu_txeof(struct usb_xfer *, struct rsu_data *);
246 static int	rsu_raw_xmit(struct ieee80211_node *, struct mbuf *,
247 		    const struct ieee80211_bpf_params *);
248 static void	rsu_rxfilter_init(struct rsu_softc *);
249 static void	rsu_rxfilter_set(struct rsu_softc *, uint32_t, uint32_t);
250 static void	rsu_rxfilter_refresh(struct rsu_softc *);
251 static int	rsu_init(struct rsu_softc *);
252 static int	rsu_tx_start(struct rsu_softc *, struct ieee80211_node *,
253 		    struct mbuf *, struct rsu_data *);
254 static int	rsu_transmit(struct ieee80211com *, struct mbuf *);
255 static void	rsu_start(struct rsu_softc *);
256 static void	_rsu_start(struct rsu_softc *);
257 static int	rsu_ioctl_net(struct ieee80211com *, u_long, void *);
258 static void	rsu_parent(struct ieee80211com *);
259 static void	rsu_stop(struct rsu_softc *);
260 static void	rsu_ms_delay(struct rsu_softc *, int);
261 
262 static device_method_t rsu_methods[] = {
263 	DEVMETHOD(device_probe,		rsu_match),
264 	DEVMETHOD(device_attach,	rsu_attach),
265 	DEVMETHOD(device_detach,	rsu_detach),
266 
267 	DEVMETHOD_END
268 };
269 
270 static driver_t rsu_driver = {
271 	.name = "rsu",
272 	.methods = rsu_methods,
273 	.size = sizeof(struct rsu_softc)
274 };
275 
276 static devclass_t rsu_devclass;
277 
278 DRIVER_MODULE(rsu, uhub, rsu_driver, rsu_devclass, NULL, 0);
279 MODULE_DEPEND(rsu, wlan, 1, 1, 1);
280 MODULE_DEPEND(rsu, usb, 1, 1, 1);
281 MODULE_DEPEND(rsu, firmware, 1, 1, 1);
282 MODULE_VERSION(rsu, 1);
283 USB_PNP_HOST_INFO(rsu_devs);
284 
285 static const uint8_t rsu_chan_2ghz[] =
286 	{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
287 
288 static uint8_t rsu_wme_ac_xfer_map[4] = {
289 	[WME_AC_BE] = RSU_BULK_TX_BE_BK,
290 	[WME_AC_BK] = RSU_BULK_TX_BE_BK,
291 	[WME_AC_VI] = RSU_BULK_TX_VI_VO,
292 	[WME_AC_VO] = RSU_BULK_TX_VI_VO,
293 };
294 
295 /* XXX hard-coded */
296 #define	RSU_H2C_ENDPOINT	3
297 
298 static const struct usb_config rsu_config[RSU_N_TRANSFER] = {
299 	[RSU_BULK_RX] = {
300 		.type = UE_BULK,
301 		.endpoint = UE_ADDR_ANY,
302 		.direction = UE_DIR_IN,
303 		.bufsize = RSU_RXBUFSZ,
304 		.flags = {
305 			.pipe_bof = 1,
306 			.short_xfer_ok = 1
307 		},
308 		.callback = rsu_bulk_rx_callback
309 	},
310 	[RSU_BULK_TX_BE_BK] = {
311 		.type = UE_BULK,
312 		.endpoint = 0x06,
313 		.direction = UE_DIR_OUT,
314 		.bufsize = RSU_TXBUFSZ,
315 		.flags = {
316 			.ext_buffer = 1,
317 			.pipe_bof = 1,
318 			.force_short_xfer = 1
319 		},
320 		.callback = rsu_bulk_tx_callback_be_bk,
321 		.timeout = RSU_TX_TIMEOUT
322 	},
323 	[RSU_BULK_TX_VI_VO] = {
324 		.type = UE_BULK,
325 		.endpoint = 0x04,
326 		.direction = UE_DIR_OUT,
327 		.bufsize = RSU_TXBUFSZ,
328 		.flags = {
329 			.ext_buffer = 1,
330 			.pipe_bof = 1,
331 			.force_short_xfer = 1
332 		},
333 		.callback = rsu_bulk_tx_callback_vi_vo,
334 		.timeout = RSU_TX_TIMEOUT
335 	},
336 	[RSU_BULK_TX_H2C] = {
337 		.type = UE_BULK,
338 		.endpoint = 0x0d,
339 		.direction = UE_DIR_OUT,
340 		.bufsize = RSU_TXBUFSZ,
341 		.flags = {
342 			.ext_buffer = 1,
343 			.pipe_bof = 1,
344 			.short_xfer_ok = 1
345 		},
346 		.callback = rsu_bulk_tx_callback_h2c,
347 		.timeout = RSU_TX_TIMEOUT
348 	},
349 };
350 
351 static int
352 rsu_match(device_t self)
353 {
354 	struct usb_attach_arg *uaa = device_get_ivars(self);
355 
356 	if (uaa->usb_mode != USB_MODE_HOST ||
357 	    uaa->info.bIfaceIndex != 0 ||
358 	    uaa->info.bConfigIndex != 0)
359 		return (ENXIO);
360 
361 	return (usbd_lookup_id_by_uaa(rsu_devs, sizeof(rsu_devs), uaa));
362 }
363 
364 static int
365 rsu_send_mgmt(struct ieee80211_node *ni, int type, int arg)
366 {
367 
368 	return (ENOTSUP);
369 }
370 
371 static void
372 rsu_update_chw(struct ieee80211com *ic)
373 {
374 
375 }
376 
377 /*
378  * notification from net80211 that it'd like to do A-MPDU on the given TID.
379  *
380  * Note: this actually hangs traffic at the present moment, so don't use it.
381  * The firmware debug does indiciate it's sending and establishing a TX AMPDU
382  * session, but then no traffic flows.
383  */
384 static int
385 rsu_ampdu_enable(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
386 {
387 #if 0
388 	struct rsu_softc *sc = ni->ni_ic->ic_softc;
389 	struct r92s_add_ba_req req;
390 
391 	/* Don't enable if it's requested or running */
392 	if (IEEE80211_AMPDU_REQUESTED(tap))
393 		return (0);
394 	if (IEEE80211_AMPDU_RUNNING(tap))
395 		return (0);
396 
397 	/* We've decided to send addba; so send it */
398 	req.tid = htole32(tap->txa_tid);
399 
400 	/* Attempt net80211 state */
401 	if (ieee80211_ampdu_tx_request_ext(ni, tap->txa_tid) != 1)
402 		return (0);
403 
404 	/* Send the firmware command */
405 	RSU_DPRINTF(sc, RSU_DEBUG_AMPDU, "%s: establishing AMPDU TX for TID %d\n",
406 	    __func__,
407 	    tap->txa_tid);
408 
409 	RSU_LOCK(sc);
410 	if (rsu_fw_cmd(sc, R92S_CMD_ADDBA_REQ, &req, sizeof(req)) != 1) {
411 		RSU_UNLOCK(sc);
412 		/* Mark failure */
413 		(void) ieee80211_ampdu_tx_request_active_ext(ni, tap->txa_tid, 0);
414 		return (0);
415 	}
416 	RSU_UNLOCK(sc);
417 
418 	/* Mark success; we don't get any further notifications */
419 	(void) ieee80211_ampdu_tx_request_active_ext(ni, tap->txa_tid, 1);
420 #endif
421 	/* Return 0, we're driving this ourselves */
422 	return (0);
423 }
424 
425 static int
426 rsu_wme_update(struct ieee80211com *ic)
427 {
428 
429 	/* Firmware handles this; not our problem */
430 	return (0);
431 }
432 
433 static int
434 rsu_attach(device_t self)
435 {
436 	struct usb_attach_arg *uaa = device_get_ivars(self);
437 	struct rsu_softc *sc = device_get_softc(self);
438 	struct ieee80211com *ic = &sc->sc_ic;
439 	int error;
440 	uint8_t iface_index;
441 	struct usb_interface *iface;
442 	const char *rft;
443 
444 	device_set_usb_desc(self);
445 	sc->sc_udev = uaa->device;
446 	sc->sc_dev = self;
447 	sc->sc_rx_checksum_enable = 1;
448 	if (rsu_enable_11n)
449 		sc->sc_ht = !! (USB_GET_DRIVER_INFO(uaa) & RSU_HT_SUPPORTED);
450 
451 	/* Get number of endpoints */
452 	iface = usbd_get_iface(sc->sc_udev, 0);
453 	sc->sc_nendpoints = iface->idesc->bNumEndpoints;
454 
455 	/* Endpoints are hard-coded for now, so enforce 4-endpoint only */
456 	if (sc->sc_nendpoints != 4) {
457 		device_printf(sc->sc_dev,
458 		    "the driver currently only supports 4-endpoint devices\n");
459 		return (ENXIO);
460 	}
461 
462 	mtx_init(&sc->sc_mtx, device_get_nameunit(self), MTX_NETWORK_LOCK,
463 	    MTX_DEF);
464 	RSU_DELKEY_BMAP_LOCK_INIT(sc);
465 	TIMEOUT_TASK_INIT(taskqueue_thread, &sc->calib_task, 0,
466 	    rsu_calib_task, sc);
467 	TASK_INIT(&sc->del_key_task, 0, rsu_delete_key_pair_cb, sc);
468 	TASK_INIT(&sc->tx_task, 0, rsu_tx_task, sc);
469 	mbufq_init(&sc->sc_snd, ifqmaxlen);
470 
471 	/* Allocate Tx/Rx buffers. */
472 	error = rsu_alloc_rx_list(sc);
473 	if (error != 0) {
474 		device_printf(sc->sc_dev, "could not allocate Rx buffers\n");
475 		goto fail_usb;
476 	}
477 
478 	error = rsu_alloc_tx_list(sc);
479 	if (error != 0) {
480 		device_printf(sc->sc_dev, "could not allocate Tx buffers\n");
481 		rsu_free_rx_list(sc);
482 		goto fail_usb;
483 	}
484 
485 	iface_index = 0;
486 	error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
487 	    rsu_config, RSU_N_TRANSFER, sc, &sc->sc_mtx);
488 	if (error) {
489 		device_printf(sc->sc_dev,
490 		    "could not allocate USB transfers, err=%s\n",
491 		    usbd_errstr(error));
492 		goto fail_usb;
493 	}
494 	RSU_LOCK(sc);
495 	/* Read chip revision. */
496 	sc->cut = MS(rsu_read_4(sc, R92S_PMC_FSM), R92S_PMC_FSM_CUT);
497 	if (sc->cut != 3)
498 		sc->cut = (sc->cut >> 1) + 1;
499 	error = rsu_read_rom(sc);
500 	RSU_UNLOCK(sc);
501 	if (error != 0) {
502 		device_printf(self, "could not read ROM\n");
503 		goto fail_rom;
504 	}
505 
506 	/* Figure out TX/RX streams */
507 	switch (sc->rom[84]) {
508 	case 0x0:
509 		sc->sc_rftype = RTL8712_RFCONFIG_1T1R;
510 		sc->sc_nrxstream = 1;
511 		sc->sc_ntxstream = 1;
512 		rft = "1T1R";
513 		break;
514 	case 0x1:
515 		sc->sc_rftype = RTL8712_RFCONFIG_1T2R;
516 		sc->sc_nrxstream = 2;
517 		sc->sc_ntxstream = 1;
518 		rft = "1T2R";
519 		break;
520 	case 0x2:
521 		sc->sc_rftype = RTL8712_RFCONFIG_2T2R;
522 		sc->sc_nrxstream = 2;
523 		sc->sc_ntxstream = 2;
524 		rft = "2T2R";
525 		break;
526 	case 0x3:	/* "green" NIC */
527 		sc->sc_rftype = RTL8712_RFCONFIG_1T2R;
528 		sc->sc_nrxstream = 2;
529 		sc->sc_ntxstream = 1;
530 		rft = "1T2R ('green')";
531 		break;
532 	default:
533 		device_printf(sc->sc_dev,
534 		    "%s: unknown board type (rfconfig=0x%02x)\n",
535 		    __func__,
536 		    sc->rom[84]);
537 		goto fail_rom;
538 	}
539 
540 	IEEE80211_ADDR_COPY(ic->ic_macaddr, &sc->rom[0x12]);
541 	device_printf(self, "MAC/BB RTL8712 cut %d %s\n", sc->cut, rft);
542 
543 	ic->ic_softc = sc;
544 	ic->ic_name = device_get_nameunit(self);
545 	ic->ic_phytype = IEEE80211_T_OFDM;	/* Not only, but not used. */
546 	ic->ic_opmode = IEEE80211_M_STA;	/* Default to BSS mode. */
547 
548 	/* Set device capabilities. */
549 	ic->ic_caps =
550 	    IEEE80211_C_STA |		/* station mode */
551 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
552 #if 0
553 	    IEEE80211_C_BGSCAN |	/* Background scan. */
554 #endif
555 	    IEEE80211_C_SHPREAMBLE |	/* Short preamble supported. */
556 	    IEEE80211_C_WME |		/* WME/QoS */
557 	    IEEE80211_C_SHSLOT |	/* Short slot time supported. */
558 	    IEEE80211_C_WPA;		/* WPA/RSN. */
559 
560 	ic->ic_cryptocaps =
561 	    IEEE80211_CRYPTO_WEP |
562 	    IEEE80211_CRYPTO_TKIP |
563 	    IEEE80211_CRYPTO_AES_CCM;
564 
565 	/* Check if HT support is present. */
566 	if (sc->sc_ht) {
567 		device_printf(sc->sc_dev, "%s: enabling 11n\n", __func__);
568 
569 		/* Enable basic HT */
570 		ic->ic_htcaps = IEEE80211_HTC_HT |
571 #if 0
572 		    IEEE80211_HTC_AMPDU |
573 #endif
574 		    IEEE80211_HTC_AMSDU |
575 		    IEEE80211_HTCAP_MAXAMSDU_3839 |
576 		    IEEE80211_HTCAP_SMPS_OFF;
577 		ic->ic_htcaps |= IEEE80211_HTCAP_CHWIDTH40;
578 
579 		/* set number of spatial streams */
580 		ic->ic_txstream = sc->sc_ntxstream;
581 		ic->ic_rxstream = sc->sc_nrxstream;
582 	}
583 	ic->ic_flags_ext |= IEEE80211_FEXT_SCAN_OFFLOAD;
584 
585 	rsu_getradiocaps(ic, IEEE80211_CHAN_MAX, &ic->ic_nchans,
586 	    ic->ic_channels);
587 
588 	ieee80211_ifattach(ic);
589 	ic->ic_raw_xmit = rsu_raw_xmit;
590 	ic->ic_scan_start = rsu_scan_start;
591 	ic->ic_scan_end = rsu_scan_end;
592 	ic->ic_getradiocaps = rsu_getradiocaps;
593 	ic->ic_set_channel = rsu_set_channel;
594 	ic->ic_scan_curchan = rsu_scan_curchan;
595 	ic->ic_scan_mindwell = rsu_scan_mindwell;
596 	ic->ic_vap_create = rsu_vap_create;
597 	ic->ic_vap_delete = rsu_vap_delete;
598 	ic->ic_update_promisc = rsu_update_promisc;
599 	ic->ic_update_mcast = rsu_update_mcast;
600 	ic->ic_ioctl = rsu_ioctl_net;
601 	ic->ic_parent = rsu_parent;
602 	ic->ic_transmit = rsu_transmit;
603 	ic->ic_send_mgmt = rsu_send_mgmt;
604 	ic->ic_update_chw = rsu_update_chw;
605 	ic->ic_ampdu_enable = rsu_ampdu_enable;
606 	ic->ic_wme.wme_update = rsu_wme_update;
607 
608 	ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr,
609 	    sizeof(sc->sc_txtap), RSU_TX_RADIOTAP_PRESENT,
610 	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
611 	    RSU_RX_RADIOTAP_PRESENT);
612 
613 	if (bootverbose)
614 		ieee80211_announce(ic);
615 
616 	return (0);
617 
618 fail_rom:
619 	usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER);
620 fail_usb:
621 	mtx_destroy(&sc->sc_mtx);
622 	return (ENXIO);
623 }
624 
625 static int
626 rsu_detach(device_t self)
627 {
628 	struct rsu_softc *sc = device_get_softc(self);
629 	struct ieee80211com *ic = &sc->sc_ic;
630 
631 	rsu_stop(sc);
632 
633 	usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER);
634 
635 	/*
636 	 * Free buffers /before/ we detach from net80211, else node
637 	 * references to destroyed vaps will lead to a panic.
638 	 */
639 	/* Free Tx/Rx buffers. */
640 	RSU_LOCK(sc);
641 	rsu_free_tx_list(sc);
642 	rsu_free_rx_list(sc);
643 	RSU_UNLOCK(sc);
644 
645 	/* Frames are freed; detach from net80211 */
646 	ieee80211_ifdetach(ic);
647 
648 	taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task);
649 	taskqueue_drain(taskqueue_thread, &sc->del_key_task);
650 	taskqueue_drain(taskqueue_thread, &sc->tx_task);
651 
652 	RSU_DELKEY_BMAP_LOCK_DESTROY(sc);
653 	mtx_destroy(&sc->sc_mtx);
654 
655 	return (0);
656 }
657 
658 static usb_error_t
659 rsu_do_request(struct rsu_softc *sc, struct usb_device_request *req,
660     void *data)
661 {
662 	usb_error_t err;
663 	int ntries = 10;
664 
665 	RSU_ASSERT_LOCKED(sc);
666 
667 	while (ntries--) {
668 		err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
669 		    req, data, 0, NULL, 250 /* ms */);
670 		if (err == 0 || err == USB_ERR_NOT_CONFIGURED)
671 			break;
672 		RSU_DPRINTF(sc, RSU_DEBUG_USB,
673 		    "Control request failed, %s (retries left: %d)\n",
674 		    usbd_errstr(err), ntries);
675 		rsu_ms_delay(sc, 10);
676         }
677 
678         return (err);
679 }
680 
681 static struct ieee80211vap *
682 rsu_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
683     enum ieee80211_opmode opmode, int flags,
684     const uint8_t bssid[IEEE80211_ADDR_LEN],
685     const uint8_t mac[IEEE80211_ADDR_LEN])
686 {
687 	struct rsu_softc *sc = ic->ic_softc;
688 	struct rsu_vap *uvp;
689 	struct ieee80211vap *vap;
690 	struct ifnet *ifp;
691 
692 	if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
693 		return (NULL);
694 
695 	uvp =  malloc(sizeof(struct rsu_vap), M_80211_VAP, M_WAITOK | M_ZERO);
696 	vap = &uvp->vap;
697 
698 	if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
699 	    flags, bssid) != 0) {
700 		/* out of memory */
701 		free(uvp, M_80211_VAP);
702 		return (NULL);
703 	}
704 
705 	ifp = vap->iv_ifp;
706 	ifp->if_capabilities = IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6;
707 	RSU_LOCK(sc);
708 	if (sc->sc_rx_checksum_enable)
709 		ifp->if_capenable |= IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6;
710 	RSU_UNLOCK(sc);
711 
712 	/* override state transition machine */
713 	uvp->newstate = vap->iv_newstate;
714 	if (opmode == IEEE80211_M_MONITOR)
715 		vap->iv_newstate = rsu_monitor_newstate;
716 	else
717 		vap->iv_newstate = rsu_newstate;
718 	vap->iv_key_alloc = rsu_key_alloc;
719 	vap->iv_key_set = rsu_key_set;
720 	vap->iv_key_delete = rsu_key_delete;
721 
722 	/* Limits from the r92su driver */
723 	vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_16;
724 	vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_32K;
725 
726 	/* complete setup */
727 	ieee80211_vap_attach(vap, ieee80211_media_change,
728 	    ieee80211_media_status, mac);
729 	ic->ic_opmode = opmode;
730 
731 	return (vap);
732 }
733 
734 static void
735 rsu_vap_delete(struct ieee80211vap *vap)
736 {
737 	struct rsu_vap *uvp = RSU_VAP(vap);
738 
739 	ieee80211_vap_detach(vap);
740 	free(uvp, M_80211_VAP);
741 }
742 
743 static void
744 rsu_scan_start(struct ieee80211com *ic)
745 {
746 	struct rsu_softc *sc = ic->ic_softc;
747 	struct ieee80211_scan_state *ss = ic->ic_scan;
748 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
749 	int error;
750 
751 	/* Scanning is done by the firmware. */
752 	RSU_LOCK(sc);
753 	sc->sc_active_scan = !!(ss->ss_flags & IEEE80211_SCAN_ACTIVE);
754 	/* XXX TODO: force awake if in network-sleep? */
755 	error = rsu_site_survey(sc, ss->ss_nssid > 0 ? &ss->ss_ssid[0] : NULL);
756 	RSU_UNLOCK(sc);
757 	if (error != 0) {
758 		device_printf(sc->sc_dev,
759 		    "could not send site survey command\n");
760 		ieee80211_cancel_scan(vap);
761 	}
762 }
763 
764 static void
765 rsu_scan_end(struct ieee80211com *ic)
766 {
767 	/* Nothing to do here. */
768 }
769 
770 static void
771 rsu_getradiocaps(struct ieee80211com *ic,
772     int maxchans, int *nchans, struct ieee80211_channel chans[])
773 {
774 	struct rsu_softc *sc = ic->ic_softc;
775 	uint8_t bands[IEEE80211_MODE_BYTES];
776 
777 	/* Set supported .11b and .11g rates. */
778 	memset(bands, 0, sizeof(bands));
779 	setbit(bands, IEEE80211_MODE_11B);
780 	setbit(bands, IEEE80211_MODE_11G);
781 	if (sc->sc_ht)
782 		setbit(bands, IEEE80211_MODE_11NG);
783 	ieee80211_add_channel_list_2ghz(chans, maxchans, nchans,
784 	    rsu_chan_2ghz, nitems(rsu_chan_2ghz), bands,
785 	    (ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) != 0);
786 }
787 
788 static void
789 rsu_set_channel(struct ieee80211com *ic)
790 {
791 	struct rsu_softc *sc = ic->ic_softc;
792 
793 	/*
794 	 * Only need to set the channel in Monitor mode. AP scanning and auth
795 	 * are already taken care of by their respective firmware commands.
796 	 */
797 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
798 		struct r92s_set_channel cmd;
799 		int error;
800 
801 		cmd.channel = IEEE80211_CHAN2IEEE(ic->ic_curchan);
802 
803 		RSU_LOCK(sc);
804 		error = rsu_fw_cmd(sc, R92S_CMD_SET_CHANNEL, &cmd,
805 		    sizeof(cmd));
806 		if (error != 0) {
807 			device_printf(sc->sc_dev,
808 			    "%s: error %d setting channel\n", __func__,
809 			    error);
810 		}
811 		RSU_UNLOCK(sc);
812 	}
813 }
814 
815 static void
816 rsu_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
817 {
818 	/* Scan is done in rsu_scan_start(). */
819 }
820 
821 /**
822  * Called by the net80211 framework to indicate
823  * the minimum dwell time has been met, terminate the scan.
824  * We don't actually terminate the scan as the firmware will notify
825  * us when it's finished and we have no way to interrupt it.
826  */
827 static void
828 rsu_scan_mindwell(struct ieee80211_scan_state *ss)
829 {
830 	/* NB: don't try to abort scan; wait for firmware to finish */
831 }
832 
833 static void
834 rsu_update_promisc(struct ieee80211com *ic)
835 {
836 	struct rsu_softc *sc = ic->ic_softc;
837 
838 	RSU_LOCK(sc);
839 	if (sc->sc_running)
840 		rsu_rxfilter_refresh(sc);
841 	RSU_UNLOCK(sc);
842 }
843 
844 /*
845  * The same as rtwn_get_multi_pos() / rtwn_set_multi().
846  */
847 static uint8_t
848 rsu_get_multi_pos(const uint8_t maddr[])
849 {
850 	uint64_t mask = 0x00004d101df481b4;
851 	uint8_t pos = 0x27;	/* initial value */
852 	int i, j;
853 
854 	for (i = 0; i < IEEE80211_ADDR_LEN; i++)
855 		for (j = (i == 0) ? 1 : 0; j < 8; j++)
856 			if ((maddr[i] >> j) & 1)
857 				pos ^= (mask >> (i * 8 + j - 1));
858 
859 	pos &= 0x3f;
860 
861 	return (pos);
862 }
863 
864 static void
865 rsu_set_multi(struct rsu_softc *sc)
866 {
867 	struct ieee80211com *ic = &sc->sc_ic;
868 	uint32_t mfilt[2];
869 
870 	RSU_ASSERT_LOCKED(sc);
871 
872 	/* general structure was copied from ath(4). */
873 	if (ic->ic_allmulti == 0) {
874 		struct ieee80211vap *vap;
875 		struct ifnet *ifp;
876 		struct ifmultiaddr *ifma;
877 
878 		/*
879 		 * Merge multicast addresses to form the hardware filter.
880 		 */
881 		mfilt[0] = mfilt[1] = 0;
882 		TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
883 			ifp = vap->iv_ifp;
884 			if_maddr_rlock(ifp);
885 			TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
886 				caddr_t dl;
887 				uint8_t pos;
888 
889 				dl = LLADDR((struct sockaddr_dl *)
890 				    ifma->ifma_addr);
891 				pos = rsu_get_multi_pos(dl);
892 
893 				mfilt[pos / 32] |= (1 << (pos % 32));
894 			}
895 			if_maddr_runlock(ifp);
896 		}
897 	} else
898 		mfilt[0] = mfilt[1] = ~0;
899 
900 	rsu_write_4(sc, R92S_MAR + 0, mfilt[0]);
901 	rsu_write_4(sc, R92S_MAR + 4, mfilt[1]);
902 
903 	RSU_DPRINTF(sc, RSU_DEBUG_STATE, "%s: MC filter %08x:%08x\n",
904 	    __func__, mfilt[0], mfilt[1]);
905 }
906 
907 static void
908 rsu_update_mcast(struct ieee80211com *ic)
909 {
910 	struct rsu_softc *sc = ic->ic_softc;
911 
912 	RSU_LOCK(sc);
913 	if (sc->sc_running)
914 		rsu_set_multi(sc);
915 	RSU_UNLOCK(sc);
916 }
917 
918 static int
919 rsu_alloc_list(struct rsu_softc *sc, struct rsu_data data[],
920     int ndata, int maxsz)
921 {
922 	int i, error;
923 
924 	for (i = 0; i < ndata; i++) {
925 		struct rsu_data *dp = &data[i];
926 		dp->sc = sc;
927 		dp->m = NULL;
928 		dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT);
929 		if (dp->buf == NULL) {
930 			device_printf(sc->sc_dev,
931 			    "could not allocate buffer\n");
932 			error = ENOMEM;
933 			goto fail;
934 		}
935 		dp->ni = NULL;
936 	}
937 
938 	return (0);
939 fail:
940 	rsu_free_list(sc, data, ndata);
941 	return (error);
942 }
943 
944 static int
945 rsu_alloc_rx_list(struct rsu_softc *sc)
946 {
947         int error, i;
948 
949 	error = rsu_alloc_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT,
950 	    RSU_RXBUFSZ);
951 	if (error != 0)
952 		return (error);
953 
954 	STAILQ_INIT(&sc->sc_rx_active);
955 	STAILQ_INIT(&sc->sc_rx_inactive);
956 
957 	for (i = 0; i < RSU_RX_LIST_COUNT; i++)
958 		STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i], next);
959 
960 	return (0);
961 }
962 
963 static int
964 rsu_alloc_tx_list(struct rsu_softc *sc)
965 {
966 	int error, i;
967 
968 	error = rsu_alloc_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT,
969 	    RSU_TXBUFSZ);
970 	if (error != 0)
971 		return (error);
972 
973 	STAILQ_INIT(&sc->sc_tx_inactive);
974 
975 	for (i = 0; i != RSU_N_TRANSFER; i++) {
976 		STAILQ_INIT(&sc->sc_tx_active[i]);
977 		STAILQ_INIT(&sc->sc_tx_pending[i]);
978 	}
979 
980 	for (i = 0; i < RSU_TX_LIST_COUNT; i++) {
981 		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i], next);
982 	}
983 
984 	return (0);
985 }
986 
987 static void
988 rsu_free_tx_list(struct rsu_softc *sc)
989 {
990 	int i;
991 
992 	/* prevent further allocations from TX list(s) */
993 	STAILQ_INIT(&sc->sc_tx_inactive);
994 
995 	for (i = 0; i != RSU_N_TRANSFER; i++) {
996 		STAILQ_INIT(&sc->sc_tx_active[i]);
997 		STAILQ_INIT(&sc->sc_tx_pending[i]);
998 	}
999 
1000 	rsu_free_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT);
1001 }
1002 
1003 static void
1004 rsu_free_rx_list(struct rsu_softc *sc)
1005 {
1006 	/* prevent further allocations from RX list(s) */
1007 	STAILQ_INIT(&sc->sc_rx_inactive);
1008 	STAILQ_INIT(&sc->sc_rx_active);
1009 
1010 	rsu_free_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT);
1011 }
1012 
1013 static void
1014 rsu_free_list(struct rsu_softc *sc, struct rsu_data data[], int ndata)
1015 {
1016 	int i;
1017 
1018 	for (i = 0; i < ndata; i++) {
1019 		struct rsu_data *dp = &data[i];
1020 
1021 		if (dp->buf != NULL) {
1022 			free(dp->buf, M_USBDEV);
1023 			dp->buf = NULL;
1024 		}
1025 		if (dp->ni != NULL) {
1026 			ieee80211_free_node(dp->ni);
1027 			dp->ni = NULL;
1028 		}
1029 	}
1030 }
1031 
1032 static struct rsu_data *
1033 _rsu_getbuf(struct rsu_softc *sc)
1034 {
1035 	struct rsu_data *bf;
1036 
1037 	bf = STAILQ_FIRST(&sc->sc_tx_inactive);
1038 	if (bf != NULL)
1039 		STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next);
1040 	else
1041 		bf = NULL;
1042 	return (bf);
1043 }
1044 
1045 static struct rsu_data *
1046 rsu_getbuf(struct rsu_softc *sc)
1047 {
1048 	struct rsu_data *bf;
1049 
1050 	RSU_ASSERT_LOCKED(sc);
1051 
1052 	bf = _rsu_getbuf(sc);
1053 	if (bf == NULL) {
1054 		RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: no buffers\n", __func__);
1055 	}
1056 	return (bf);
1057 }
1058 
1059 static void
1060 rsu_freebuf(struct rsu_softc *sc, struct rsu_data *bf)
1061 {
1062 
1063 	RSU_ASSERT_LOCKED(sc);
1064 	STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, bf, next);
1065 }
1066 
1067 static int
1068 rsu_write_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
1069     int len)
1070 {
1071 	usb_device_request_t req;
1072 
1073 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1074 	req.bRequest = R92S_REQ_REGS;
1075 	USETW(req.wValue, addr);
1076 	USETW(req.wIndex, 0);
1077 	USETW(req.wLength, len);
1078 
1079 	return (rsu_do_request(sc, &req, buf));
1080 }
1081 
1082 static void
1083 rsu_write_1(struct rsu_softc *sc, uint16_t addr, uint8_t val)
1084 {
1085 	rsu_write_region_1(sc, addr, &val, 1);
1086 }
1087 
1088 static void
1089 rsu_write_2(struct rsu_softc *sc, uint16_t addr, uint16_t val)
1090 {
1091 	val = htole16(val);
1092 	rsu_write_region_1(sc, addr, (uint8_t *)&val, 2);
1093 }
1094 
1095 static void
1096 rsu_write_4(struct rsu_softc *sc, uint16_t addr, uint32_t val)
1097 {
1098 	val = htole32(val);
1099 	rsu_write_region_1(sc, addr, (uint8_t *)&val, 4);
1100 }
1101 
1102 static int
1103 rsu_read_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
1104     int len)
1105 {
1106 	usb_device_request_t req;
1107 
1108 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1109 	req.bRequest = R92S_REQ_REGS;
1110 	USETW(req.wValue, addr);
1111 	USETW(req.wIndex, 0);
1112 	USETW(req.wLength, len);
1113 
1114 	return (rsu_do_request(sc, &req, buf));
1115 }
1116 
1117 static uint8_t
1118 rsu_read_1(struct rsu_softc *sc, uint16_t addr)
1119 {
1120 	uint8_t val;
1121 
1122 	if (rsu_read_region_1(sc, addr, &val, 1) != 0)
1123 		return (0xff);
1124 	return (val);
1125 }
1126 
1127 static uint16_t
1128 rsu_read_2(struct rsu_softc *sc, uint16_t addr)
1129 {
1130 	uint16_t val;
1131 
1132 	if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0)
1133 		return (0xffff);
1134 	return (le16toh(val));
1135 }
1136 
1137 static uint32_t
1138 rsu_read_4(struct rsu_softc *sc, uint16_t addr)
1139 {
1140 	uint32_t val;
1141 
1142 	if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0)
1143 		return (0xffffffff);
1144 	return (le32toh(val));
1145 }
1146 
1147 static int
1148 rsu_fw_iocmd(struct rsu_softc *sc, uint32_t iocmd)
1149 {
1150 	int ntries;
1151 
1152 	rsu_write_4(sc, R92S_IOCMD_CTRL, iocmd);
1153 	rsu_ms_delay(sc, 1);
1154 	for (ntries = 0; ntries < 50; ntries++) {
1155 		if (rsu_read_4(sc, R92S_IOCMD_CTRL) == 0)
1156 			return (0);
1157 		rsu_ms_delay(sc, 1);
1158 	}
1159 	return (ETIMEDOUT);
1160 }
1161 
1162 static uint8_t
1163 rsu_efuse_read_1(struct rsu_softc *sc, uint16_t addr)
1164 {
1165 	uint32_t reg;
1166 	int ntries;
1167 
1168 	reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
1169 	reg = RW(reg, R92S_EFUSE_CTRL_ADDR, addr);
1170 	reg &= ~R92S_EFUSE_CTRL_VALID;
1171 	rsu_write_4(sc, R92S_EFUSE_CTRL, reg);
1172 	/* Wait for read operation to complete. */
1173 	for (ntries = 0; ntries < 100; ntries++) {
1174 		reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
1175 		if (reg & R92S_EFUSE_CTRL_VALID)
1176 			return (MS(reg, R92S_EFUSE_CTRL_DATA));
1177 		rsu_ms_delay(sc, 1);
1178 	}
1179 	device_printf(sc->sc_dev,
1180 	    "could not read efuse byte at address 0x%x\n", addr);
1181 	return (0xff);
1182 }
1183 
1184 static int
1185 rsu_read_rom(struct rsu_softc *sc)
1186 {
1187 	uint8_t *rom = sc->rom;
1188 	uint16_t addr = 0;
1189 	uint32_t reg;
1190 	uint8_t off, msk;
1191 	int i;
1192 
1193 	/* Make sure that ROM type is eFuse and that autoload succeeded. */
1194 	reg = rsu_read_1(sc, R92S_EE_9346CR);
1195 	if ((reg & (R92S_9356SEL | R92S_EEPROM_EN)) != R92S_EEPROM_EN)
1196 		return (EIO);
1197 
1198 	/* Turn on 2.5V to prevent eFuse leakage. */
1199 	reg = rsu_read_1(sc, R92S_EFUSE_TEST + 3);
1200 	rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg | 0x80);
1201 	rsu_ms_delay(sc, 1);
1202 	rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg & ~0x80);
1203 
1204 	/* Read full ROM image. */
1205 	memset(&sc->rom, 0xff, sizeof(sc->rom));
1206 	while (addr < 512) {
1207 		reg = rsu_efuse_read_1(sc, addr);
1208 		if (reg == 0xff)
1209 			break;
1210 		addr++;
1211 		off = reg >> 4;
1212 		msk = reg & 0xf;
1213 		for (i = 0; i < 4; i++) {
1214 			if (msk & (1 << i))
1215 				continue;
1216 			rom[off * 8 + i * 2 + 0] =
1217 			    rsu_efuse_read_1(sc, addr);
1218 			addr++;
1219 			rom[off * 8 + i * 2 + 1] =
1220 			    rsu_efuse_read_1(sc, addr);
1221 			addr++;
1222 		}
1223 	}
1224 #ifdef USB_DEBUG
1225 	if (rsu_debug & RSU_DEBUG_RESET) {
1226 		/* Dump ROM content. */
1227 		printf("\n");
1228 		for (i = 0; i < sizeof(sc->rom); i++)
1229 			printf("%02x:", rom[i]);
1230 		printf("\n");
1231 	}
1232 #endif
1233 	return (0);
1234 }
1235 
1236 static int
1237 rsu_fw_cmd(struct rsu_softc *sc, uint8_t code, void *buf, int len)
1238 {
1239 	const uint8_t which = RSU_H2C_ENDPOINT;
1240 	struct rsu_data *data;
1241 	struct r92s_tx_desc *txd;
1242 	struct r92s_fw_cmd_hdr *cmd;
1243 	int cmdsz;
1244 	int xferlen;
1245 
1246 	RSU_ASSERT_LOCKED(sc);
1247 
1248 	data = rsu_getbuf(sc);
1249 	if (data == NULL)
1250 		return (ENOMEM);
1251 
1252 	/* Blank the entire payload, just to be safe */
1253 	memset(data->buf, '\0', RSU_TXBUFSZ);
1254 
1255 	/* Round-up command length to a multiple of 8 bytes. */
1256 	/* XXX TODO: is this required? */
1257 	cmdsz = (len + 7) & ~7;
1258 
1259 	xferlen = sizeof(*txd) + sizeof(*cmd) + cmdsz;
1260 	KASSERT(xferlen <= RSU_TXBUFSZ, ("%s: invalid length", __func__));
1261 	memset(data->buf, 0, xferlen);
1262 
1263 	/* Setup Tx descriptor. */
1264 	txd = (struct r92s_tx_desc *)data->buf;
1265 	txd->txdw0 = htole32(
1266 	    SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
1267 	    SM(R92S_TXDW0_PKTLEN, sizeof(*cmd) + cmdsz) |
1268 	    R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
1269 	txd->txdw1 = htole32(SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_H2C));
1270 
1271 	/* Setup command header. */
1272 	cmd = (struct r92s_fw_cmd_hdr *)&txd[1];
1273 	cmd->len = htole16(cmdsz);
1274 	cmd->code = code;
1275 	cmd->seq = sc->cmd_seq;
1276 	sc->cmd_seq = (sc->cmd_seq + 1) & 0x7f;
1277 
1278 	/* Copy command payload. */
1279 	memcpy(&cmd[1], buf, len);
1280 
1281 	RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FWCMD,
1282 	    "%s: Tx cmd code=0x%x len=0x%x\n",
1283 	    __func__, code, cmdsz);
1284 	data->buflen = xferlen;
1285 	STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
1286 	usbd_transfer_start(sc->sc_xfer[which]);
1287 
1288 	return (0);
1289 }
1290 
1291 /* ARGSUSED */
1292 static void
1293 rsu_calib_task(void *arg, int pending __unused)
1294 {
1295 	struct rsu_softc *sc = arg;
1296 #ifdef notyet
1297 	uint32_t reg;
1298 #endif
1299 
1300 	RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "%s: running calibration task\n",
1301 	    __func__);
1302 
1303 	RSU_LOCK(sc);
1304 #ifdef notyet
1305 	/* Read WPS PBC status. */
1306 	rsu_write_1(sc, R92S_MAC_PINMUX_CTRL,
1307 	    R92S_GPIOMUX_EN | SM(R92S_GPIOSEL_GPIO, R92S_GPIOSEL_GPIO_JTAG));
1308 	rsu_write_1(sc, R92S_GPIO_IO_SEL,
1309 	    rsu_read_1(sc, R92S_GPIO_IO_SEL) & ~R92S_GPIO_WPS);
1310 	reg = rsu_read_1(sc, R92S_GPIO_CTRL);
1311 	if (reg != 0xff && (reg & R92S_GPIO_WPS))
1312 		RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "WPS PBC is pushed\n");
1313 #endif
1314 	/* Read current signal level. */
1315 	if (rsu_fw_iocmd(sc, 0xf4000001) == 0) {
1316 		sc->sc_currssi = rsu_read_4(sc, R92S_IOCMD_DATA);
1317 		RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "%s: RSSI=%d (%d)\n",
1318 		    __func__, sc->sc_currssi,
1319 		    rsu_hwrssi_to_rssi(sc, sc->sc_currssi));
1320 	}
1321 	if (sc->sc_calibrating)
1322 		taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, hz);
1323 	RSU_UNLOCK(sc);
1324 }
1325 
1326 static void
1327 rsu_tx_task(void *arg, int pending __unused)
1328 {
1329 	struct rsu_softc *sc = arg;
1330 
1331 	RSU_LOCK(sc);
1332 	_rsu_start(sc);
1333 	RSU_UNLOCK(sc);
1334 }
1335 
1336 #define	RSU_PWR_UNKNOWN		0x0
1337 #define	RSU_PWR_ACTIVE		0x1
1338 #define	RSU_PWR_OFF		0x2
1339 #define	RSU_PWR_SLEEP		0x3
1340 
1341 /*
1342  * Set the current power state.
1343  *
1344  * The rtlwifi code doesn't do this so aggressively; it
1345  * waits for an idle period after association with
1346  * no traffic before doing this.
1347  *
1348  * For now - it's on in all states except RUN, and
1349  * in RUN it'll transition to allow sleep.
1350  */
1351 
1352 struct r92s_pwr_cmd {
1353 	uint8_t mode;
1354 	uint8_t smart_ps;
1355 	uint8_t bcn_pass_time;
1356 };
1357 
1358 static int
1359 rsu_set_fw_power_state(struct rsu_softc *sc, int state)
1360 {
1361 	struct r92s_set_pwr_mode cmd;
1362 	//struct r92s_pwr_cmd cmd;
1363 	int error;
1364 
1365 	RSU_ASSERT_LOCKED(sc);
1366 
1367 	/* only change state if required */
1368 	if (sc->sc_curpwrstate == state)
1369 		return (0);
1370 
1371 	memset(&cmd, 0, sizeof(cmd));
1372 
1373 	switch (state) {
1374 	case RSU_PWR_ACTIVE:
1375 		/* Force the hardware awake */
1376 		rsu_write_1(sc, R92S_USB_HRPWM,
1377 		    R92S_USB_HRPWM_PS_ST_ACTIVE | R92S_USB_HRPWM_PS_ALL_ON);
1378 		cmd.mode = R92S_PS_MODE_ACTIVE;
1379 		break;
1380 	case RSU_PWR_SLEEP:
1381 		cmd.mode = R92S_PS_MODE_DTIM;	/* XXX configurable? */
1382 		cmd.smart_ps = 1; /* XXX 2 if doing p2p */
1383 		cmd.bcn_pass_time = 5; /* in 100mS usb.c, linux/rtlwifi */
1384 		break;
1385 	case RSU_PWR_OFF:
1386 		cmd.mode = R92S_PS_MODE_RADIOOFF;
1387 		break;
1388 	default:
1389 		device_printf(sc->sc_dev, "%s: unknown ps mode (%d)\n",
1390 		    __func__,
1391 		    state);
1392 		return (ENXIO);
1393 	}
1394 
1395 	RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1396 	    "%s: setting ps mode to %d (mode %d)\n",
1397 	    __func__, state, cmd.mode);
1398 	error = rsu_fw_cmd(sc, R92S_CMD_SET_PWR_MODE, &cmd, sizeof(cmd));
1399 	if (error == 0)
1400 		sc->sc_curpwrstate = state;
1401 
1402 	return (error);
1403 }
1404 
1405 static void
1406 rsu_set_led(struct rsu_softc *sc, int on)
1407 {
1408 	rsu_write_1(sc, R92S_LEDCFG,
1409 	    (rsu_read_1(sc, R92S_LEDCFG) & 0xf0) | (!on << 3));
1410 }
1411 
1412 static int
1413 rsu_monitor_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate,
1414     int arg)
1415 {
1416 	struct ieee80211com *ic = vap->iv_ic;
1417 	struct rsu_softc *sc = ic->ic_softc;
1418 	struct rsu_vap *uvp = RSU_VAP(vap);
1419 
1420 	if (vap->iv_state != nstate) {
1421 		IEEE80211_UNLOCK(ic);
1422 		RSU_LOCK(sc);
1423 
1424 		switch (nstate) {
1425 		case IEEE80211_S_INIT:
1426 			sc->sc_vap_is_running = 0;
1427 			rsu_set_led(sc, 0);
1428 			break;
1429 		case IEEE80211_S_RUN:
1430 			sc->sc_vap_is_running = 1;
1431 			rsu_set_led(sc, 1);
1432 			break;
1433 		default:
1434 			/* NOTREACHED */
1435 			break;
1436 		}
1437 		rsu_rxfilter_refresh(sc);
1438 
1439 		RSU_UNLOCK(sc);
1440 		IEEE80211_LOCK(ic);
1441 	}
1442 
1443 	return (uvp->newstate(vap, nstate, arg));
1444 }
1445 
1446 static int
1447 rsu_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1448 {
1449 	struct rsu_vap *uvp = RSU_VAP(vap);
1450 	struct ieee80211com *ic = vap->iv_ic;
1451 	struct rsu_softc *sc = ic->ic_softc;
1452 	struct ieee80211_node *ni;
1453 	struct ieee80211_rateset *rs;
1454 	enum ieee80211_state ostate;
1455 	int error, startcal = 0;
1456 
1457 	ostate = vap->iv_state;
1458 	RSU_DPRINTF(sc, RSU_DEBUG_STATE, "%s: %s -> %s\n",
1459 	    __func__,
1460 	    ieee80211_state_name[ostate],
1461 	    ieee80211_state_name[nstate]);
1462 
1463 	IEEE80211_UNLOCK(ic);
1464 	if (ostate == IEEE80211_S_RUN) {
1465 		RSU_LOCK(sc);
1466 		/* Stop calibration. */
1467 		sc->sc_calibrating = 0;
1468 
1469 		/* Pause Tx for AC queues. */
1470 		rsu_write_1(sc, R92S_TXPAUSE, R92S_TXPAUSE_AC);
1471 		usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(10));
1472 
1473 		RSU_UNLOCK(sc);
1474 		taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task);
1475 		taskqueue_drain(taskqueue_thread, &sc->tx_task);
1476 		RSU_LOCK(sc);
1477 		/* Disassociate from our current BSS. */
1478 		rsu_disconnect(sc);
1479 		usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(10));
1480 
1481 		/* Refresh Rx filter (may be modified by firmware). */
1482 		sc->sc_vap_is_running = 0;
1483 		rsu_rxfilter_refresh(sc);
1484 
1485 		/* Reinstall static keys. */
1486 		if (sc->sc_running)
1487 			rsu_reinit_static_keys(sc);
1488 	} else
1489 		RSU_LOCK(sc);
1490 	switch (nstate) {
1491 	case IEEE80211_S_INIT:
1492 		(void) rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
1493 		break;
1494 	case IEEE80211_S_AUTH:
1495 		ni = ieee80211_ref_node(vap->iv_bss);
1496 		(void) rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
1497 		error = rsu_join_bss(sc, ni);
1498 		ieee80211_free_node(ni);
1499 		if (error != 0) {
1500 			device_printf(sc->sc_dev,
1501 			    "could not send join command\n");
1502 		}
1503 		break;
1504 	case IEEE80211_S_RUN:
1505 		/* Flush all AC queues. */
1506 		rsu_write_1(sc, R92S_TXPAUSE, 0);
1507 
1508 		ni = ieee80211_ref_node(vap->iv_bss);
1509 		rs = &ni->ni_rates;
1510 		/* Indicate highest supported rate. */
1511 		ni->ni_txrate = rs->rs_rates[rs->rs_nrates - 1];
1512 		(void) rsu_set_fw_power_state(sc, RSU_PWR_SLEEP);
1513 		ieee80211_free_node(ni);
1514 		startcal = 1;
1515 		break;
1516 	default:
1517 		break;
1518 	}
1519 	if (startcal != 0) {
1520 		sc->sc_calibrating = 1;
1521 		/* Start periodic calibration. */
1522 		taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task,
1523 		    hz);
1524 	}
1525 	RSU_UNLOCK(sc);
1526 	IEEE80211_LOCK(ic);
1527 	return (uvp->newstate(vap, nstate, arg));
1528 }
1529 
1530 static int
1531 rsu_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,
1532     ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
1533 {
1534 	struct rsu_softc *sc = vap->iv_ic->ic_softc;
1535 	int is_checked = 0;
1536 
1537 	if (&vap->iv_nw_keys[0] <= k &&
1538 	    k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
1539 		*keyix = ieee80211_crypto_get_key_wepidx(vap, k);
1540 	} else {
1541 		if (vap->iv_opmode != IEEE80211_M_STA) {
1542 			*keyix = 0;
1543 			/* TODO: obtain keyix from node id */
1544 			is_checked = 1;
1545 			k->wk_flags |= IEEE80211_KEY_SWCRYPT;
1546 		} else
1547 			*keyix = R92S_MACID_BSS;
1548 	}
1549 
1550 	if (!is_checked) {
1551 		RSU_LOCK(sc);
1552 		if (isset(sc->keys_bmap, *keyix)) {
1553 			device_printf(sc->sc_dev,
1554 			    "%s: key slot %d is already used!\n",
1555 			    __func__, *keyix);
1556 			RSU_UNLOCK(sc);
1557 			return (0);
1558 		}
1559 		setbit(sc->keys_bmap, *keyix);
1560 		RSU_UNLOCK(sc);
1561 	}
1562 
1563 	*rxkeyix = *keyix;
1564 
1565 	return (1);
1566 }
1567 
1568 static int
1569 rsu_process_key(struct ieee80211vap *vap, const struct ieee80211_key *k,
1570     int set)
1571 {
1572 	struct rsu_softc *sc = vap->iv_ic->ic_softc;
1573 	int ret;
1574 
1575 	if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
1576 		/* Not for us. */
1577 		return (1);
1578 	}
1579 
1580 	/* Handle group keys. */
1581 	if (&vap->iv_nw_keys[0] <= k &&
1582 	    k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
1583 		KASSERT(k->wk_keyix < nitems(sc->group_keys),
1584 		    ("keyix %u > %zu\n", k->wk_keyix, nitems(sc->group_keys)));
1585 
1586 		RSU_LOCK(sc);
1587 		sc->group_keys[k->wk_keyix] = (set ? k : NULL);
1588 		if (!sc->sc_running) {
1589 			/* Static keys will be set during device startup. */
1590 			RSU_UNLOCK(sc);
1591 			return (1);
1592 		}
1593 
1594 		if (set)
1595 			ret = rsu_set_key_group(sc, k);
1596 		else
1597 			ret = rsu_delete_key(sc, k->wk_keyix);
1598 		RSU_UNLOCK(sc);
1599 
1600 		return (!ret);
1601 	}
1602 
1603 	if (set) {
1604 		/* wait for pending key removal */
1605 		taskqueue_drain(taskqueue_thread, &sc->del_key_task);
1606 
1607 		RSU_LOCK(sc);
1608 		ret = rsu_set_key_pair(sc, k);
1609 		RSU_UNLOCK(sc);
1610 	} else {
1611 		RSU_DELKEY_BMAP_LOCK(sc);
1612 		setbit(sc->free_keys_bmap, k->wk_keyix);
1613 		RSU_DELKEY_BMAP_UNLOCK(sc);
1614 
1615 		/* workaround ieee80211_node_delucastkey() locking */
1616 		taskqueue_enqueue(taskqueue_thread, &sc->del_key_task);
1617 		ret = 0;	/* fake success */
1618 	}
1619 
1620 	return (!ret);
1621 }
1622 
1623 static int
1624 rsu_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k)
1625 {
1626 	return (rsu_process_key(vap, k, 1));
1627 }
1628 
1629 static int
1630 rsu_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
1631 {
1632 	return (rsu_process_key(vap, k, 0));
1633 }
1634 
1635 static int
1636 rsu_cam_read(struct rsu_softc *sc, uint8_t addr, uint32_t *val)
1637 {
1638 	int ntries;
1639 
1640 	rsu_write_4(sc, R92S_CAMCMD,
1641 	    R92S_CAMCMD_POLLING | SM(R92S_CAMCMD_ADDR, addr));
1642 	for (ntries = 0; ntries < 10; ntries++) {
1643 		if (!(rsu_read_4(sc, R92S_CAMCMD) & R92S_CAMCMD_POLLING))
1644 			break;
1645 
1646 		usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(1));
1647 	}
1648 	if (ntries == 10) {
1649 		device_printf(sc->sc_dev,
1650 		    "%s: cannot read CAM entry at address %02X\n",
1651 		    __func__, addr);
1652 		return (ETIMEDOUT);
1653 	}
1654 
1655 	*val = rsu_read_4(sc, R92S_CAMREAD);
1656 
1657 	return (0);
1658 }
1659 
1660 static void
1661 rsu_cam_write(struct rsu_softc *sc, uint8_t addr, uint32_t data)
1662 {
1663 
1664 	rsu_write_4(sc, R92S_CAMWRITE, data);
1665 	rsu_write_4(sc, R92S_CAMCMD,
1666 	    R92S_CAMCMD_POLLING | R92S_CAMCMD_WRITE |
1667 	    SM(R92S_CAMCMD_ADDR, addr));
1668 }
1669 
1670 static int
1671 rsu_key_check(struct rsu_softc *sc, ieee80211_keyix keyix, int is_valid)
1672 {
1673 	uint32_t val;
1674 	int error, ntries;
1675 
1676 	for (ntries = 0; ntries < 20; ntries++) {
1677 		usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(1));
1678 
1679 		error = rsu_cam_read(sc, R92S_CAM_CTL0(keyix), &val);
1680 		if (error != 0) {
1681 			device_printf(sc->sc_dev,
1682 			    "%s: cannot check key status!\n", __func__);
1683 			return (error);
1684 		}
1685 		if (((val & R92S_CAM_VALID) == 0) ^ is_valid)
1686 			break;
1687 	}
1688 	if (ntries == 20) {
1689 		device_printf(sc->sc_dev,
1690 		    "%s: key %d is %s marked as valid, rejecting request\n",
1691 		    __func__, keyix, is_valid ? "not" : "still");
1692 		return (EIO);
1693 	}
1694 
1695 	return (0);
1696 }
1697 
1698 /*
1699  * Map net80211 cipher to RTL8712 security mode.
1700  */
1701 static uint8_t
1702 rsu_crypto_mode(struct rsu_softc *sc, u_int cipher, int keylen)
1703 {
1704 	switch (cipher) {
1705 	case IEEE80211_CIPHER_WEP:
1706 		return keylen < 8 ? R92S_KEY_ALGO_WEP40 : R92S_KEY_ALGO_WEP104;
1707 	case IEEE80211_CIPHER_TKIP:
1708 		return R92S_KEY_ALGO_TKIP;
1709 	case IEEE80211_CIPHER_AES_CCM:
1710 		return R92S_KEY_ALGO_AES;
1711 	default:
1712 		device_printf(sc->sc_dev, "unknown cipher %d\n", cipher);
1713 		return R92S_KEY_ALGO_INVALID;
1714 	}
1715 }
1716 
1717 static int
1718 rsu_set_key_group(struct rsu_softc *sc, const struct ieee80211_key *k)
1719 {
1720 	struct r92s_fw_cmd_set_key key;
1721 	uint8_t algo;
1722 	int error;
1723 
1724 	RSU_ASSERT_LOCKED(sc);
1725 
1726 	/* Map net80211 cipher to HW crypto algorithm. */
1727 	algo = rsu_crypto_mode(sc, k->wk_cipher->ic_cipher, k->wk_keylen);
1728 	if (algo == R92S_KEY_ALGO_INVALID)
1729 		return (EINVAL);
1730 
1731 	memset(&key, 0, sizeof(key));
1732 	key.algo = algo;
1733 	key.cam_id = k->wk_keyix;
1734 	key.grpkey = (k->wk_flags & IEEE80211_KEY_GROUP) != 0;
1735 	memcpy(key.key, k->wk_key, MIN(k->wk_keylen, sizeof(key.key)));
1736 
1737 	RSU_DPRINTF(sc, RSU_DEBUG_KEY | RSU_DEBUG_FWCMD,
1738 	    "%s: keyix %u, group %u, algo %u/%u, flags %04X, len %u, "
1739 	    "macaddr %s\n", __func__, key.cam_id, key.grpkey,
1740 	    k->wk_cipher->ic_cipher, key.algo, k->wk_flags, k->wk_keylen,
1741 	    ether_sprintf(k->wk_macaddr));
1742 
1743 	error = rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
1744 	if (error != 0) {
1745 		device_printf(sc->sc_dev,
1746 		    "%s: cannot send firmware command, error %d\n",
1747 		    __func__, error);
1748 		return (error);
1749 	}
1750 
1751 	return (rsu_key_check(sc, k->wk_keyix, 1));
1752 }
1753 
1754 static int
1755 rsu_set_key_pair(struct rsu_softc *sc, const struct ieee80211_key *k)
1756 {
1757 	struct r92s_fw_cmd_set_key_mac key;
1758 	uint8_t algo;
1759 	int error;
1760 
1761 	RSU_ASSERT_LOCKED(sc);
1762 
1763 	if (!sc->sc_running)
1764 		return (ESHUTDOWN);
1765 
1766 	/* Map net80211 cipher to HW crypto algorithm. */
1767 	algo = rsu_crypto_mode(sc, k->wk_cipher->ic_cipher, k->wk_keylen);
1768 	if (algo == R92S_KEY_ALGO_INVALID)
1769 		return (EINVAL);
1770 
1771 	memset(&key, 0, sizeof(key));
1772 	key.algo = algo;
1773 	memcpy(key.macaddr, k->wk_macaddr, sizeof(key.macaddr));
1774 	memcpy(key.key, k->wk_key, MIN(k->wk_keylen, sizeof(key.key)));
1775 
1776 	RSU_DPRINTF(sc, RSU_DEBUG_KEY | RSU_DEBUG_FWCMD,
1777 	    "%s: keyix %u, algo %u/%u, flags %04X, len %u, macaddr %s\n",
1778 	    __func__, k->wk_keyix, k->wk_cipher->ic_cipher, key.algo,
1779 	    k->wk_flags, k->wk_keylen, ether_sprintf(key.macaddr));
1780 
1781 	error = rsu_fw_cmd(sc, R92S_CMD_SET_STA_KEY, &key, sizeof(key));
1782 	if (error != 0) {
1783 		device_printf(sc->sc_dev,
1784 		    "%s: cannot send firmware command, error %d\n",
1785 		    __func__, error);
1786 		return (error);
1787 	}
1788 
1789 	return (rsu_key_check(sc, k->wk_keyix, 1));
1790 }
1791 
1792 static int
1793 rsu_reinit_static_keys(struct rsu_softc *sc)
1794 {
1795 	int i, error;
1796 
1797 	for (i = 0; i < nitems(sc->group_keys); i++) {
1798 		if (sc->group_keys[i] != NULL) {
1799 			error = rsu_set_key_group(sc, sc->group_keys[i]);
1800 			if (error != 0) {
1801 				device_printf(sc->sc_dev,
1802 				    "%s: failed to set static key %d, "
1803 				    "error %d\n", __func__, i, error);
1804 				return (error);
1805 			}
1806 		}
1807 	}
1808 
1809 	return (0);
1810 }
1811 
1812 static int
1813 rsu_delete_key(struct rsu_softc *sc, ieee80211_keyix keyix)
1814 {
1815 	struct r92s_fw_cmd_set_key key;
1816 	uint32_t val;
1817 	int error;
1818 
1819 	RSU_ASSERT_LOCKED(sc);
1820 
1821 	if (!sc->sc_running)
1822 		return (0);
1823 
1824 	/* check if it was automatically removed by firmware */
1825 	error = rsu_cam_read(sc, R92S_CAM_CTL0(keyix), &val);
1826 	if (error == 0 && (val & R92S_CAM_VALID) == 0) {
1827 		RSU_DPRINTF(sc, RSU_DEBUG_KEY,
1828 		    "%s: key %u does not exist\n", __func__, keyix);
1829 		clrbit(sc->keys_bmap, keyix);
1830 		return (0);
1831 	}
1832 
1833 	memset(&key, 0, sizeof(key));
1834 	key.cam_id = keyix;
1835 
1836 	RSU_DPRINTF(sc, RSU_DEBUG_KEY | RSU_DEBUG_FWCMD,
1837 	    "%s: removing key %u\n", __func__, key.cam_id);
1838 
1839 	error = rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
1840 	if (error != 0) {
1841 		device_printf(sc->sc_dev,
1842 		    "%s: cannot send firmware command, error %d\n",
1843 		    __func__, error);
1844 		goto finish;
1845 	}
1846 
1847 	usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(5));
1848 
1849 	/*
1850 	 * Clear 'valid' bit manually (cannot be done via firmware command).
1851 	 * Used for key check + when firmware command cannot be sent.
1852 	 */
1853 finish:
1854 	rsu_cam_write(sc, R92S_CAM_CTL0(keyix), 0);
1855 
1856 	clrbit(sc->keys_bmap, keyix);
1857 
1858 	return (rsu_key_check(sc, keyix, 0));
1859 }
1860 
1861 static void
1862 rsu_delete_key_pair_cb(void *arg, int pending __unused)
1863 {
1864 	struct rsu_softc *sc = arg;
1865 	int i;
1866 
1867 	RSU_DELKEY_BMAP_LOCK(sc);
1868 	for (i = IEEE80211_WEP_NKID; i < R92S_CAM_ENTRY_LIMIT; i++) {
1869 		if (isset(sc->free_keys_bmap, i)) {
1870 			RSU_DELKEY_BMAP_UNLOCK(sc);
1871 
1872 			RSU_LOCK(sc);
1873 			RSU_DPRINTF(sc, RSU_DEBUG_KEY,
1874 			    "%s: calling rsu_delete_key() with keyix = %d\n",
1875 			    __func__, i);
1876 			(void) rsu_delete_key(sc, i);
1877 			RSU_UNLOCK(sc);
1878 
1879 			RSU_DELKEY_BMAP_LOCK(sc);
1880 			clrbit(sc->free_keys_bmap, i);
1881 
1882 			/* bmap can be changed */
1883 			i = IEEE80211_WEP_NKID - 1;
1884 			continue;
1885 		}
1886 	}
1887 	RSU_DELKEY_BMAP_UNLOCK(sc);
1888 }
1889 
1890 static int
1891 rsu_site_survey(struct rsu_softc *sc, struct ieee80211_scan_ssid *ssid)
1892 {
1893 	struct r92s_fw_cmd_sitesurvey cmd;
1894 
1895 	RSU_ASSERT_LOCKED(sc);
1896 
1897 	memset(&cmd, 0, sizeof(cmd));
1898 	/* TODO: passive channels? */
1899 	if (sc->sc_active_scan)
1900 		cmd.active = htole32(1);
1901 	cmd.limit = htole32(48);
1902 
1903 	if (ssid != NULL) {
1904 		sc->sc_extra_scan = 1;
1905 		cmd.ssidlen = htole32(ssid->len);
1906 		memcpy(cmd.ssid, ssid->ssid, ssid->len);
1907 	}
1908 #ifdef USB_DEBUG
1909 	if (rsu_debug & (RSU_DEBUG_SCAN | RSU_DEBUG_FWCMD)) {
1910 		device_printf(sc->sc_dev,
1911 		    "sending site survey command, active %d",
1912 		    le32toh(cmd.active));
1913 		if (ssid != NULL) {
1914 			printf(", ssid: ");
1915 			ieee80211_print_essid(cmd.ssid, le32toh(cmd.ssidlen));
1916 		}
1917 		printf("\n");
1918 	}
1919 #endif
1920 	return (rsu_fw_cmd(sc, R92S_CMD_SITE_SURVEY, &cmd, sizeof(cmd)));
1921 }
1922 
1923 static int
1924 rsu_join_bss(struct rsu_softc *sc, struct ieee80211_node *ni)
1925 {
1926 	struct ieee80211com *ic = &sc->sc_ic;
1927 	struct ieee80211vap *vap = ni->ni_vap;
1928 	struct ndis_wlan_bssid_ex *bss;
1929 	struct ndis_802_11_fixed_ies *fixed;
1930 	struct r92s_fw_cmd_auth auth;
1931 	uint8_t buf[sizeof(*bss) + 128] __aligned(4);
1932 	uint8_t *frm;
1933 	uint8_t opmode;
1934 	int error;
1935 
1936 	RSU_ASSERT_LOCKED(sc);
1937 
1938 	/* Let the FW decide the opmode based on the capinfo field. */
1939 	opmode = NDIS802_11AUTOUNKNOWN;
1940 	RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1941 	    "%s: setting operating mode to %d\n",
1942 	    __func__, opmode);
1943 	error = rsu_fw_cmd(sc, R92S_CMD_SET_OPMODE, &opmode, sizeof(opmode));
1944 	if (error != 0)
1945 		return (error);
1946 
1947 	memset(&auth, 0, sizeof(auth));
1948 	if (vap->iv_flags & IEEE80211_F_WPA) {
1949 		auth.mode = R92S_AUTHMODE_WPA;
1950 		auth.dot1x = (ni->ni_authmode == IEEE80211_AUTH_8021X);
1951 	} else
1952 		auth.mode = R92S_AUTHMODE_OPEN;
1953 	RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1954 	    "%s: setting auth mode to %d\n",
1955 	    __func__, auth.mode);
1956 	error = rsu_fw_cmd(sc, R92S_CMD_SET_AUTH, &auth, sizeof(auth));
1957 	if (error != 0)
1958 		return (error);
1959 
1960 	memset(buf, 0, sizeof(buf));
1961 	bss = (struct ndis_wlan_bssid_ex *)buf;
1962 	IEEE80211_ADDR_COPY(bss->macaddr, ni->ni_bssid);
1963 	bss->ssid.ssidlen = htole32(ni->ni_esslen);
1964 	memcpy(bss->ssid.ssid, ni->ni_essid, ni->ni_esslen);
1965 	if (vap->iv_flags & (IEEE80211_F_PRIVACY | IEEE80211_F_WPA))
1966 		bss->privacy = htole32(1);
1967 	bss->rssi = htole32(ni->ni_avgrssi);
1968 	if (ic->ic_curmode == IEEE80211_MODE_11B)
1969 		bss->networktype = htole32(NDIS802_11DS);
1970 	else
1971 		bss->networktype = htole32(NDIS802_11OFDM24);
1972 	bss->config.len = htole32(sizeof(bss->config));
1973 	bss->config.bintval = htole32(ni->ni_intval);
1974 	bss->config.dsconfig = htole32(ieee80211_chan2ieee(ic, ni->ni_chan));
1975 	bss->inframode = htole32(NDIS802_11INFRASTRUCTURE);
1976 	/* XXX verify how this is supposed to look! */
1977 	memcpy(bss->supprates, ni->ni_rates.rs_rates,
1978 	    ni->ni_rates.rs_nrates);
1979 	/* Write the fixed fields of the beacon frame. */
1980 	fixed = (struct ndis_802_11_fixed_ies *)&bss[1];
1981 	memcpy(&fixed->tstamp, ni->ni_tstamp.data, 8);
1982 	fixed->bintval = htole16(ni->ni_intval);
1983 	fixed->capabilities = htole16(ni->ni_capinfo);
1984 	/* Write IEs to be included in the association request. */
1985 	frm = (uint8_t *)&fixed[1];
1986 	frm = ieee80211_add_rsn(frm, vap);
1987 	frm = ieee80211_add_wpa(frm, vap);
1988 	frm = ieee80211_add_qos(frm, ni);
1989 	if ((ic->ic_flags & IEEE80211_F_WME) &&
1990 	    (ni->ni_ies.wme_ie != NULL))
1991 		frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1992 	if (ni->ni_flags & IEEE80211_NODE_HT) {
1993 		frm = ieee80211_add_htcap(frm, ni);
1994 		frm = ieee80211_add_htinfo(frm, ni);
1995 	}
1996 	bss->ieslen = htole32(frm - (uint8_t *)fixed);
1997 	bss->len = htole32(((frm - buf) + 3) & ~3);
1998 	RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_FWCMD,
1999 	    "%s: sending join bss command to %s chan %d\n",
2000 	    __func__,
2001 	    ether_sprintf(bss->macaddr), le32toh(bss->config.dsconfig));
2002 	return (rsu_fw_cmd(sc, R92S_CMD_JOIN_BSS, buf, sizeof(buf)));
2003 }
2004 
2005 static int
2006 rsu_disconnect(struct rsu_softc *sc)
2007 {
2008 	uint32_t zero = 0;	/* :-) */
2009 
2010 	/* Disassociate from our current BSS. */
2011 	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
2012 	    "%s: sending disconnect command\n", __func__);
2013 	return (rsu_fw_cmd(sc, R92S_CMD_DISCONNECT, &zero, sizeof(zero)));
2014 }
2015 
2016 /*
2017  * Map the hardware provided RSSI value to a signal level.
2018  * For the most part it's just something we divide by and cap
2019  * so it doesn't overflow the representation by net80211.
2020  */
2021 static int
2022 rsu_hwrssi_to_rssi(struct rsu_softc *sc, int hw_rssi)
2023 {
2024 	int v;
2025 
2026 	if (hw_rssi == 0)
2027 		return (0);
2028 	v = hw_rssi >> 4;
2029 	if (v > 80)
2030 		v = 80;
2031 	return (v);
2032 }
2033 
2034 CTASSERT(MCLBYTES > sizeof(struct ieee80211_frame));
2035 
2036 static void
2037 rsu_event_survey(struct rsu_softc *sc, uint8_t *buf, int len)
2038 {
2039 	struct ieee80211com *ic = &sc->sc_ic;
2040 	struct ieee80211_frame *wh;
2041 	struct ndis_wlan_bssid_ex *bss;
2042 	struct ieee80211_rx_stats rxs;
2043 	struct mbuf *m;
2044 	uint32_t ieslen;
2045 	uint32_t pktlen;
2046 
2047 	if (__predict_false(len < sizeof(*bss)))
2048 		return;
2049 	bss = (struct ndis_wlan_bssid_ex *)buf;
2050 	ieslen = le32toh(bss->ieslen);
2051 	/* range check length of information element */
2052 	if (__predict_false(ieslen > (uint32_t)(len - sizeof(*bss))))
2053 		return;
2054 
2055 	RSU_DPRINTF(sc, RSU_DEBUG_SCAN,
2056 	    "%s: found BSS %s: len=%d chan=%d inframode=%d "
2057 	    "networktype=%d privacy=%d, RSSI=%d\n",
2058 	    __func__,
2059 	    ether_sprintf(bss->macaddr), ieslen,
2060 	    le32toh(bss->config.dsconfig), le32toh(bss->inframode),
2061 	    le32toh(bss->networktype), le32toh(bss->privacy),
2062 	    le32toh(bss->rssi));
2063 
2064 	/* Build a fake beacon frame to let net80211 do all the parsing. */
2065 	/* XXX TODO: just call the new scan API methods! */
2066 	if (__predict_false(ieslen > (size_t)(MCLBYTES - sizeof(*wh))))
2067 		return;
2068 	pktlen = sizeof(*wh) + ieslen;
2069 	m = m_get2(pktlen, M_NOWAIT, MT_DATA, M_PKTHDR);
2070 	if (__predict_false(m == NULL))
2071 		return;
2072 	wh = mtod(m, struct ieee80211_frame *);
2073 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2074 	    IEEE80211_FC0_SUBTYPE_BEACON;
2075 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2076 	USETW(wh->i_dur, 0);
2077 	IEEE80211_ADDR_COPY(wh->i_addr1, ieee80211broadcastaddr);
2078 	IEEE80211_ADDR_COPY(wh->i_addr2, bss->macaddr);
2079 	IEEE80211_ADDR_COPY(wh->i_addr3, bss->macaddr);
2080 	*(uint16_t *)wh->i_seq = 0;
2081 	memcpy(&wh[1], (uint8_t *)&bss[1], ieslen);
2082 
2083 	/* Finalize mbuf. */
2084 	m->m_pkthdr.len = m->m_len = pktlen;
2085 
2086 	/* Set channel flags for input path */
2087 	bzero(&rxs, sizeof(rxs));
2088 	rxs.r_flags |= IEEE80211_R_IEEE | IEEE80211_R_FREQ;
2089 	rxs.r_flags |= IEEE80211_R_NF | IEEE80211_R_RSSI;
2090 	rxs.c_ieee = le32toh(bss->config.dsconfig);
2091 	rxs.c_freq = ieee80211_ieee2mhz(rxs.c_ieee, IEEE80211_CHAN_2GHZ);
2092 	/* This is a number from 0..100; so let's just divide it down a bit */
2093 	rxs.c_rssi = le32toh(bss->rssi) / 2;
2094 	rxs.c_nf = -96;
2095 	if (ieee80211_add_rx_params(m, &rxs) == 0)
2096 		return;
2097 
2098 	/* XXX avoid a LOR */
2099 	RSU_UNLOCK(sc);
2100 	ieee80211_input_mimo_all(ic, m);
2101 	RSU_LOCK(sc);
2102 }
2103 
2104 static void
2105 rsu_event_join_bss(struct rsu_softc *sc, uint8_t *buf, int len)
2106 {
2107 	struct ieee80211com *ic = &sc->sc_ic;
2108 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2109 	struct ieee80211_node *ni = vap->iv_bss;
2110 	struct r92s_event_join_bss *rsp;
2111 	uint32_t tmp;
2112 	int res;
2113 
2114 	if (__predict_false(len < sizeof(*rsp)))
2115 		return;
2116 	rsp = (struct r92s_event_join_bss *)buf;
2117 	res = (int)le32toh(rsp->join_res);
2118 
2119 	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
2120 	    "%s: Rx join BSS event len=%d res=%d\n",
2121 	    __func__, len, res);
2122 
2123 	/*
2124 	 * XXX Don't do this; there's likely a better way to tell
2125 	 * the caller we failed.
2126 	 */
2127 	if (res <= 0) {
2128 		RSU_UNLOCK(sc);
2129 		ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
2130 		RSU_LOCK(sc);
2131 		return;
2132 	}
2133 
2134 	tmp = le32toh(rsp->associd);
2135 	if (tmp >= vap->iv_max_aid) {
2136 		RSU_DPRINTF(sc, RSU_DEBUG_ANY, "Assoc ID overflow\n");
2137 		tmp = 1;
2138 	}
2139 	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
2140 	    "%s: associated with %s associd=%d\n",
2141 	    __func__, ether_sprintf(rsp->bss.macaddr), tmp);
2142 	/* XXX is this required? What's the top two bits for again? */
2143 	ni->ni_associd = tmp | 0xc000;
2144 
2145 	/* Refresh Rx filter (was changed by firmware). */
2146 	sc->sc_vap_is_running = 1;
2147 	rsu_rxfilter_refresh(sc);
2148 
2149 	RSU_UNLOCK(sc);
2150 	ieee80211_new_state(vap, IEEE80211_S_RUN,
2151 	    IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
2152 	RSU_LOCK(sc);
2153 }
2154 
2155 static void
2156 rsu_event_addba_req_report(struct rsu_softc *sc, uint8_t *buf, int len)
2157 {
2158 	struct ieee80211com *ic = &sc->sc_ic;
2159 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2160 	struct r92s_add_ba_event *ba = (void *) buf;
2161 	struct ieee80211_node *ni;
2162 
2163 	if (len < sizeof(*ba)) {
2164 		device_printf(sc->sc_dev, "%s: short read (%d)\n", __func__, len);
2165 		return;
2166 	}
2167 
2168 	if (vap == NULL)
2169 		return;
2170 
2171 	RSU_DPRINTF(sc, RSU_DEBUG_AMPDU, "%s: mac=%s, tid=%d, ssn=%d\n",
2172 	    __func__,
2173 	    ether_sprintf(ba->mac_addr),
2174 	    (int) ba->tid,
2175 	    (int) le16toh(ba->ssn));
2176 
2177 	/* XXX do node lookup; this is STA specific */
2178 
2179 	ni = ieee80211_ref_node(vap->iv_bss);
2180 	ieee80211_ampdu_rx_start_ext(ni, ba->tid, le16toh(ba->ssn) >> 4, 32);
2181 	ieee80211_free_node(ni);
2182 }
2183 
2184 static void
2185 rsu_rx_event(struct rsu_softc *sc, uint8_t code, uint8_t *buf, int len)
2186 {
2187 	struct ieee80211com *ic = &sc->sc_ic;
2188 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2189 
2190 	RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD,
2191 	    "%s: Rx event code=%d len=%d\n", __func__, code, len);
2192 	switch (code) {
2193 	case R92S_EVT_SURVEY:
2194 		rsu_event_survey(sc, buf, len);
2195 		break;
2196 	case R92S_EVT_SURVEY_DONE:
2197 		RSU_DPRINTF(sc, RSU_DEBUG_SCAN,
2198 		    "%s: %s scan done, found %d BSS\n",
2199 		    __func__, sc->sc_extra_scan ? "direct" : "broadcast",
2200 		    le32toh(*(uint32_t *)buf));
2201 		if (sc->sc_extra_scan == 1) {
2202 			/* Send broadcast probe request. */
2203 			sc->sc_extra_scan = 0;
2204 			if (vap != NULL && rsu_site_survey(sc, NULL) != 0) {
2205 				RSU_UNLOCK(sc);
2206 				ieee80211_cancel_scan(vap);
2207 				RSU_LOCK(sc);
2208 			}
2209 			break;
2210 		}
2211 		if (vap != NULL) {
2212 			RSU_UNLOCK(sc);
2213 			ieee80211_scan_done(vap);
2214 			RSU_LOCK(sc);
2215 		}
2216 		break;
2217 	case R92S_EVT_JOIN_BSS:
2218 		if (vap->iv_state == IEEE80211_S_AUTH)
2219 			rsu_event_join_bss(sc, buf, len);
2220 		break;
2221 	case R92S_EVT_DEL_STA:
2222 		RSU_DPRINTF(sc, RSU_DEBUG_FWCMD | RSU_DEBUG_STATE,
2223 		    "%s: disassociated from %s\n", __func__,
2224 		    ether_sprintf(buf));
2225 		if (vap->iv_state == IEEE80211_S_RUN &&
2226 		    IEEE80211_ADDR_EQ(vap->iv_bss->ni_bssid, buf)) {
2227 			RSU_UNLOCK(sc);
2228 			ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
2229 			RSU_LOCK(sc);
2230 		}
2231 		break;
2232 	case R92S_EVT_WPS_PBC:
2233 		RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD,
2234 		    "%s: WPS PBC pushed.\n", __func__);
2235 		break;
2236 	case R92S_EVT_FWDBG:
2237 		buf[60] = '\0';
2238 		RSU_DPRINTF(sc, RSU_DEBUG_FWDBG, "FWDBG: %s\n", (char *)buf);
2239 		break;
2240 	case R92S_EVT_ADDBA_REQ_REPORT:
2241 		rsu_event_addba_req_report(sc, buf, len);
2242 		break;
2243 	default:
2244 		device_printf(sc->sc_dev, "%s: unhandled code (%d)\n", __func__, code);
2245 		break;
2246 	}
2247 }
2248 
2249 static void
2250 rsu_rx_multi_event(struct rsu_softc *sc, uint8_t *buf, int len)
2251 {
2252 	struct r92s_fw_cmd_hdr *cmd;
2253 	int cmdsz;
2254 
2255 	RSU_DPRINTF(sc, RSU_DEBUG_RX, "%s: Rx events len=%d\n", __func__, len);
2256 
2257 	/* Skip Rx status. */
2258 	buf += sizeof(struct r92s_rx_stat);
2259 	len -= sizeof(struct r92s_rx_stat);
2260 
2261 	/* Process all events. */
2262 	for (;;) {
2263 		/* Check that command header fits. */
2264 		if (__predict_false(len < sizeof(*cmd)))
2265 			break;
2266 		cmd = (struct r92s_fw_cmd_hdr *)buf;
2267 		/* Check that command payload fits. */
2268 		cmdsz = le16toh(cmd->len);
2269 		if (__predict_false(len < sizeof(*cmd) + cmdsz))
2270 			break;
2271 
2272 		/* Process firmware event. */
2273 		rsu_rx_event(sc, cmd->code, (uint8_t *)&cmd[1], cmdsz);
2274 
2275 		if (!(cmd->seq & R92S_FW_CMD_MORE))
2276 			break;
2277 		buf += sizeof(*cmd) + cmdsz;
2278 		len -= sizeof(*cmd) + cmdsz;
2279 	}
2280 }
2281 
2282 static int8_t
2283 rsu_get_rssi(struct rsu_softc *sc, int rate, void *physt)
2284 {
2285 	static const int8_t cckoff[] = { 14, -2, -20, -40 };
2286 	struct r92s_rx_phystat *phy;
2287 	struct r92s_rx_cck *cck;
2288 	uint8_t rpt;
2289 	int8_t rssi;
2290 
2291 	if (rate <= 3) {
2292 		cck = (struct r92s_rx_cck *)physt;
2293 		rpt = (cck->agc_rpt >> 6) & 0x3;
2294 		rssi = cck->agc_rpt & 0x3e;
2295 		rssi = cckoff[rpt] - rssi;
2296 	} else {	/* OFDM/HT. */
2297 		phy = (struct r92s_rx_phystat *)physt;
2298 		rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 106;
2299 	}
2300 	return (rssi);
2301 }
2302 
2303 static struct mbuf *
2304 rsu_rx_copy_to_mbuf(struct rsu_softc *sc, struct r92s_rx_stat *stat,
2305     int totlen)
2306 {
2307 	struct ieee80211com *ic = &sc->sc_ic;
2308 	struct mbuf *m;
2309 	uint32_t rxdw0;
2310 	int pktlen;
2311 
2312 	rxdw0 = le32toh(stat->rxdw0);
2313 	if (__predict_false(rxdw0 & (R92S_RXDW0_CRCERR | R92S_RXDW0_ICVERR))) {
2314 		RSU_DPRINTF(sc, RSU_DEBUG_RX,
2315 		    "%s: RX flags error (%s)\n", __func__,
2316 		    rxdw0 & R92S_RXDW0_CRCERR ? "CRC" : "ICV");
2317 		goto fail;
2318 	}
2319 
2320 	pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN);
2321 	if (__predict_false(pktlen < sizeof (struct ieee80211_frame_ack))) {
2322 		RSU_DPRINTF(sc, RSU_DEBUG_RX,
2323 		    "%s: frame is too short: %d\n", __func__, pktlen);
2324 		goto fail;
2325 	}
2326 
2327 	m = m_get2(totlen, M_NOWAIT, MT_DATA, M_PKTHDR);
2328 	if (__predict_false(m == NULL)) {
2329 		device_printf(sc->sc_dev,
2330 		    "%s: could not allocate RX mbuf, totlen %d\n",
2331 		    __func__, totlen);
2332 		goto fail;
2333 	}
2334 
2335 	/* Finalize mbuf. */
2336 	memcpy(mtod(m, uint8_t *), (uint8_t *)stat, totlen);
2337 	m->m_pkthdr.len = m->m_len = totlen;
2338 
2339 	return (m);
2340 fail:
2341 	counter_u64_add(ic->ic_ierrors, 1);
2342 	return (NULL);
2343 }
2344 
2345 static uint32_t
2346 rsu_get_tsf_low(struct rsu_softc *sc)
2347 {
2348 	return (rsu_read_4(sc, R92S_TSFTR));
2349 }
2350 
2351 static uint32_t
2352 rsu_get_tsf_high(struct rsu_softc *sc)
2353 {
2354 	return (rsu_read_4(sc, R92S_TSFTR + 4));
2355 }
2356 
2357 static struct ieee80211_node *
2358 rsu_rx_frame(struct rsu_softc *sc, struct mbuf *m)
2359 {
2360 	struct ieee80211com *ic = &sc->sc_ic;
2361 	struct ieee80211_frame_min *wh;
2362 	struct ieee80211_rx_stats rxs;
2363 	struct r92s_rx_stat *stat;
2364 	uint32_t rxdw0, rxdw3;
2365 	uint8_t cipher, rate;
2366 	int infosz;
2367 	int rssi;
2368 
2369 	stat = mtod(m, struct r92s_rx_stat *);
2370 	rxdw0 = le32toh(stat->rxdw0);
2371 	rxdw3 = le32toh(stat->rxdw3);
2372 
2373 	rate = MS(rxdw3, R92S_RXDW3_RATE);
2374 	cipher = MS(rxdw0, R92S_RXDW0_CIPHER);
2375 	infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
2376 
2377 	/* Get RSSI from PHY status descriptor if present. */
2378 	if (infosz != 0 && (rxdw0 & R92S_RXDW0_PHYST))
2379 		rssi = rsu_get_rssi(sc, rate, &stat[1]);
2380 	else {
2381 		/* Cheat and get the last calibrated RSSI */
2382 		rssi = rsu_hwrssi_to_rssi(sc, sc->sc_currssi);
2383 	}
2384 
2385 	if (ieee80211_radiotap_active(ic)) {
2386 		struct rsu_rx_radiotap_header *tap = &sc->sc_rxtap;
2387 
2388 		/* Map HW rate index to 802.11 rate. */
2389 		tap->wr_flags = 0;		/* TODO */
2390 		tap->wr_tsft = rsu_get_tsf_high(sc);
2391 		if (le32toh(stat->tsf_low) > rsu_get_tsf_low(sc))
2392 			tap->wr_tsft--;
2393 		tap->wr_tsft = (uint64_t)htole32(tap->wr_tsft) << 32;
2394 		tap->wr_tsft += stat->tsf_low;
2395 
2396 		if (rate < 12) {
2397 			switch (rate) {
2398 			/* CCK. */
2399 			case  0: tap->wr_rate =   2; break;
2400 			case  1: tap->wr_rate =   4; break;
2401 			case  2: tap->wr_rate =  11; break;
2402 			case  3: tap->wr_rate =  22; break;
2403 			/* OFDM. */
2404 			case  4: tap->wr_rate =  12; break;
2405 			case  5: tap->wr_rate =  18; break;
2406 			case  6: tap->wr_rate =  24; break;
2407 			case  7: tap->wr_rate =  36; break;
2408 			case  8: tap->wr_rate =  48; break;
2409 			case  9: tap->wr_rate =  72; break;
2410 			case 10: tap->wr_rate =  96; break;
2411 			case 11: tap->wr_rate = 108; break;
2412 			}
2413 		} else {			/* MCS0~15. */
2414 			/* Bit 7 set means HT MCS instead of rate. */
2415 			tap->wr_rate = 0x80 | (rate - 12);
2416 		}
2417 
2418 		tap->wr_dbm_antsignal = rssi;
2419 		tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
2420 		tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
2421 	};
2422 
2423 	/* Hardware does Rx TCP checksum offload. */
2424 	/*
2425 	 * This flag can be set for some other
2426 	 * (e.g., EAPOL) frame types, so don't rely on it.
2427 	 */
2428 	if (rxdw3 & R92S_RXDW3_TCPCHKVALID) {
2429 		RSU_DPRINTF(sc, RSU_DEBUG_RX,
2430 		    "%s: TCP/IP checksums: %schecked / %schecked\n",
2431 		    __func__,
2432 		    (rxdw3 & R92S_RXDW3_TCPCHKRPT) ? "" : "not ",
2433 		    (rxdw3 & R92S_RXDW3_IPCHKRPT) ? "" : "not ");
2434 
2435 		/*
2436 		 * 'IP header checksum valid' bit will not be set if
2437 		 * the frame was not checked / has incorrect checksum /
2438 		 * does not have checksum (IPv6).
2439 		 *
2440 		 * NB: if DF bit is not set then frame will not be checked.
2441 		 */
2442 		if (rxdw3 & R92S_RXDW3_IPCHKRPT) {
2443 			m->m_pkthdr.csum_flags = CSUM_IP_CHECKED;
2444 			m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
2445 		}
2446 
2447 		/*
2448 		 * This is independent of the above check.
2449 		 */
2450 		if (rxdw3 & R92S_RXDW3_TCPCHKRPT) {
2451 			m->m_pkthdr.csum_flags |= CSUM_DATA_VALID;
2452 			m->m_pkthdr.csum_flags |= CSUM_PSEUDO_HDR;
2453 			m->m_pkthdr.csum_data = 0xffff;
2454 		}
2455 	}
2456 
2457 	/* RX flags */
2458 
2459 	/* Set channel flags for input path */
2460 	bzero(&rxs, sizeof(rxs));
2461 
2462 	/* normal RSSI */
2463 	rxs.r_flags |= IEEE80211_R_NF | IEEE80211_R_RSSI;
2464 	rxs.c_rssi = rssi;
2465 	rxs.c_nf = -96;
2466 
2467 	/* Rate */
2468 	if (!(rxdw3 & R92S_RXDW3_HTC)) {
2469 		switch (rate) {
2470 		/* CCK. */
2471 		case 0:
2472 			rxs.c_rate = 2;
2473 			rxs.c_pktflags |= IEEE80211_RX_F_CCK;
2474 			break;
2475 		case 1:
2476 			rxs.c_rate = 4;
2477 			rxs.c_pktflags |= IEEE80211_RX_F_CCK;
2478 			break;
2479 		case 2:
2480 			rxs.c_rate = 11;
2481 			rxs.c_pktflags |= IEEE80211_RX_F_CCK;
2482 			break;
2483 		case 3:
2484 			rxs.c_rate = 22;
2485 			rxs.c_pktflags |= IEEE80211_RX_F_CCK;
2486 			break;
2487 		/* OFDM. */
2488 		case 4:
2489 			rxs.c_rate = 12;
2490 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2491 			break;
2492 		case 5:
2493 			rxs.c_rate = 18;
2494 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2495 			break;
2496 		case 6:
2497 			rxs.c_rate = 24;
2498 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2499 			break;
2500 		case 7:
2501 			rxs.c_rate = 36;
2502 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2503 			break;
2504 		case 8:
2505 			rxs.c_rate = 48;
2506 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2507 			break;
2508 		case 9:
2509 			rxs.c_rate = 72;
2510 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2511 			break;
2512 		case 10:
2513 			rxs.c_rate = 96;
2514 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2515 			break;
2516 		case 11:
2517 			rxs.c_rate = 108;
2518 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2519 			break;
2520 		}
2521 	} else if (rate >= 12) {	/* MCS0~15. */
2522 		/* Bit 7 set means HT MCS instead of rate. */
2523 		rxs.c_rate = (rate - 12);
2524 		rxs.c_pktflags |= IEEE80211_RX_F_HT;
2525 	}
2526 
2527 	(void) ieee80211_add_rx_params(m, &rxs);
2528 
2529 	/* Drop descriptor. */
2530 	m_adj(m, sizeof(*stat) + infosz);
2531 	wh = mtod(m, struct ieee80211_frame_min *);
2532 	if ((wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
2533 	    cipher != R92S_KEY_ALGO_NONE) {
2534 		m->m_flags |= M_WEP;
2535 	}
2536 
2537 	RSU_DPRINTF(sc, RSU_DEBUG_RX,
2538 	    "%s: Rx frame len %d, rate %d, infosz %d\n",
2539 	    __func__, m->m_len, rate, infosz);
2540 
2541 	if (m->m_len >= sizeof(*wh))
2542 		return (ieee80211_find_rxnode(ic, wh));
2543 
2544 	return (NULL);
2545 }
2546 
2547 static struct mbuf *
2548 rsu_rx_multi_frame(struct rsu_softc *sc, uint8_t *buf, int len)
2549 {
2550 	struct r92s_rx_stat *stat;
2551 	uint32_t rxdw0;
2552 	int totlen, pktlen, infosz, npkts;
2553 	struct mbuf *m, *m0 = NULL, *prevm = NULL;
2554 
2555 	/*
2556 	 * don't pass packets to the ieee80211 framework if the driver isn't
2557 	 * RUNNING.
2558 	 */
2559 	if (!sc->sc_running)
2560 		return (NULL);
2561 
2562 	/* Get the number of encapsulated frames. */
2563 	stat = (struct r92s_rx_stat *)buf;
2564 	npkts = MS(le32toh(stat->rxdw2), R92S_RXDW2_PKTCNT);
2565 	RSU_DPRINTF(sc, RSU_DEBUG_RX,
2566 	    "%s: Rx %d frames in one chunk\n", __func__, npkts);
2567 
2568 	/* Process all of them. */
2569 	while (npkts-- > 0) {
2570 		if (__predict_false(len < sizeof(*stat)))
2571 			break;
2572 		stat = (struct r92s_rx_stat *)buf;
2573 		rxdw0 = le32toh(stat->rxdw0);
2574 
2575 		pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN);
2576 		if (__predict_false(pktlen == 0))
2577 			break;
2578 
2579 		infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
2580 
2581 		/* Make sure everything fits in xfer. */
2582 		totlen = sizeof(*stat) + infosz + pktlen;
2583 		if (__predict_false(totlen > len))
2584 			break;
2585 
2586 		/* Process 802.11 frame. */
2587 		m = rsu_rx_copy_to_mbuf(sc, stat, totlen);
2588 		if (m0 == NULL)
2589 			m0 = m;
2590 		if (prevm == NULL)
2591 			prevm = m;
2592 		else {
2593 			prevm->m_next = m;
2594 			prevm = m;
2595 		}
2596 		/* Next chunk is 128-byte aligned. */
2597 		totlen = (totlen + 127) & ~127;
2598 		buf += totlen;
2599 		len -= totlen;
2600 	}
2601 
2602 	return (m0);
2603 }
2604 
2605 static struct mbuf *
2606 rsu_rxeof(struct usb_xfer *xfer, struct rsu_data *data)
2607 {
2608 	struct rsu_softc *sc = data->sc;
2609 	struct ieee80211com *ic = &sc->sc_ic;
2610 	struct r92s_rx_stat *stat;
2611 	int len;
2612 
2613 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
2614 
2615 	if (__predict_false(len < sizeof(*stat))) {
2616 		RSU_DPRINTF(sc, RSU_DEBUG_RX, "xfer too short %d\n", len);
2617 		counter_u64_add(ic->ic_ierrors, 1);
2618 		return (NULL);
2619 	}
2620 	/* Determine if it is a firmware C2H event or an 802.11 frame. */
2621 	stat = (struct r92s_rx_stat *)data->buf;
2622 	if ((le32toh(stat->rxdw1) & 0x1ff) == 0x1ff) {
2623 		rsu_rx_multi_event(sc, data->buf, len);
2624 		/* No packets to process. */
2625 		return (NULL);
2626 	} else
2627 		return (rsu_rx_multi_frame(sc, data->buf, len));
2628 }
2629 
2630 static void
2631 rsu_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
2632 {
2633 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2634 	struct ieee80211com *ic = &sc->sc_ic;
2635 	struct ieee80211_node *ni;
2636 	struct mbuf *m = NULL, *next;
2637 	struct rsu_data *data;
2638 
2639 	RSU_ASSERT_LOCKED(sc);
2640 
2641 	switch (USB_GET_STATE(xfer)) {
2642 	case USB_ST_TRANSFERRED:
2643 		data = STAILQ_FIRST(&sc->sc_rx_active);
2644 		if (data == NULL)
2645 			goto tr_setup;
2646 		STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
2647 		m = rsu_rxeof(xfer, data);
2648 		STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
2649 		/* FALLTHROUGH */
2650 	case USB_ST_SETUP:
2651 tr_setup:
2652 		data = STAILQ_FIRST(&sc->sc_rx_inactive);
2653 		if (data == NULL) {
2654 			KASSERT(m == NULL, ("mbuf isn't NULL"));
2655 			return;
2656 		}
2657 		STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next);
2658 		STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next);
2659 		usbd_xfer_set_frame_data(xfer, 0, data->buf,
2660 		    usbd_xfer_max_len(xfer));
2661 		usbd_transfer_submit(xfer);
2662 		/*
2663 		 * To avoid LOR we should unlock our private mutex here to call
2664 		 * ieee80211_input() because here is at the end of a USB
2665 		 * callback and safe to unlock.
2666 		 */
2667 		while (m != NULL) {
2668 			next = m->m_next;
2669 			m->m_next = NULL;
2670 
2671 			ni = rsu_rx_frame(sc, m);
2672 			RSU_UNLOCK(sc);
2673 
2674 			if (ni != NULL) {
2675 				if (ni->ni_flags & IEEE80211_NODE_HT)
2676 					m->m_flags |= M_AMPDU;
2677 				(void)ieee80211_input_mimo(ni, m);
2678 				ieee80211_free_node(ni);
2679 			} else
2680 				(void)ieee80211_input_mimo_all(ic, m);
2681 
2682 			RSU_LOCK(sc);
2683 			m = next;
2684 		}
2685 		break;
2686 	default:
2687 		/* needs it to the inactive queue due to a error. */
2688 		data = STAILQ_FIRST(&sc->sc_rx_active);
2689 		if (data != NULL) {
2690 			STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
2691 			STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
2692 		}
2693 		if (error != USB_ERR_CANCELLED) {
2694 			usbd_xfer_set_stall(xfer);
2695 			counter_u64_add(ic->ic_ierrors, 1);
2696 			goto tr_setup;
2697 		}
2698 		break;
2699 	}
2700 
2701 }
2702 
2703 static void
2704 rsu_txeof(struct usb_xfer *xfer, struct rsu_data *data)
2705 {
2706 #ifdef	USB_DEBUG
2707 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2708 #endif
2709 
2710 	RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: called; data=%p\n",
2711 	    __func__,
2712 	    data);
2713 
2714 	if (data->m) {
2715 		/* XXX status? */
2716 		ieee80211_tx_complete(data->ni, data->m, 0);
2717 		data->m = NULL;
2718 		data->ni = NULL;
2719 	}
2720 }
2721 
2722 static void
2723 rsu_bulk_tx_callback_sub(struct usb_xfer *xfer, usb_error_t error,
2724     uint8_t which)
2725 {
2726 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2727 	struct ieee80211com *ic = &sc->sc_ic;
2728 	struct rsu_data *data;
2729 
2730 	RSU_ASSERT_LOCKED(sc);
2731 
2732 	switch (USB_GET_STATE(xfer)) {
2733 	case USB_ST_TRANSFERRED:
2734 		data = STAILQ_FIRST(&sc->sc_tx_active[which]);
2735 		if (data == NULL)
2736 			goto tr_setup;
2737 		RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: transfer done %p\n",
2738 		    __func__, data);
2739 		STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
2740 		rsu_txeof(xfer, data);
2741 		rsu_freebuf(sc, data);
2742 		/* FALLTHROUGH */
2743 	case USB_ST_SETUP:
2744 tr_setup:
2745 		data = STAILQ_FIRST(&sc->sc_tx_pending[which]);
2746 		if (data == NULL) {
2747 			RSU_DPRINTF(sc, RSU_DEBUG_TXDONE,
2748 			    "%s: empty pending queue sc %p\n", __func__, sc);
2749 			return;
2750 		}
2751 		STAILQ_REMOVE_HEAD(&sc->sc_tx_pending[which], next);
2752 		STAILQ_INSERT_TAIL(&sc->sc_tx_active[which], data, next);
2753 		usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen);
2754 		RSU_DPRINTF(sc, RSU_DEBUG_TXDONE,
2755 		    "%s: submitting transfer %p\n",
2756 		    __func__,
2757 		    data);
2758 		usbd_transfer_submit(xfer);
2759 		break;
2760 	default:
2761 		data = STAILQ_FIRST(&sc->sc_tx_active[which]);
2762 		if (data != NULL) {
2763 			STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
2764 			rsu_txeof(xfer, data);
2765 			rsu_freebuf(sc, data);
2766 		}
2767 		counter_u64_add(ic->ic_oerrors, 1);
2768 
2769 		if (error != USB_ERR_CANCELLED) {
2770 			usbd_xfer_set_stall(xfer);
2771 			goto tr_setup;
2772 		}
2773 		break;
2774 	}
2775 
2776 	/*
2777 	 * XXX TODO: if the queue is low, flush out FF TX frames.
2778 	 * Remember to unlock the driver for now; net80211 doesn't
2779 	 * defer it for us.
2780 	 */
2781 }
2782 
2783 static void
2784 rsu_bulk_tx_callback_be_bk(struct usb_xfer *xfer, usb_error_t error)
2785 {
2786 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2787 
2788 	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_BE_BK);
2789 
2790 	/* This kicks the TX taskqueue */
2791 	rsu_start(sc);
2792 }
2793 
2794 static void
2795 rsu_bulk_tx_callback_vi_vo(struct usb_xfer *xfer, usb_error_t error)
2796 {
2797 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2798 
2799 	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_VI_VO);
2800 
2801 	/* This kicks the TX taskqueue */
2802 	rsu_start(sc);
2803 }
2804 
2805 static void
2806 rsu_bulk_tx_callback_h2c(struct usb_xfer *xfer, usb_error_t error)
2807 {
2808 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2809 
2810 	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_H2C);
2811 
2812 	/* This kicks the TX taskqueue */
2813 	rsu_start(sc);
2814 }
2815 
2816 /*
2817  * Transmit the given frame.
2818  *
2819  * This doesn't free the node or mbuf upon failure.
2820  */
2821 static int
2822 rsu_tx_start(struct rsu_softc *sc, struct ieee80211_node *ni,
2823     struct mbuf *m0, struct rsu_data *data)
2824 {
2825 	struct ieee80211com *ic = &sc->sc_ic;
2826         struct ieee80211vap *vap = ni->ni_vap;
2827 	struct ieee80211_frame *wh;
2828 	struct ieee80211_key *k = NULL;
2829 	struct r92s_tx_desc *txd;
2830 	uint8_t type, cipher;
2831 	int prio = 0;
2832 	uint8_t which;
2833 	int hasqos;
2834 	int xferlen;
2835 	int qid;
2836 
2837 	RSU_ASSERT_LOCKED(sc);
2838 
2839 	wh = mtod(m0, struct ieee80211_frame *);
2840 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2841 
2842 	RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: data=%p, m=%p\n",
2843 	    __func__, data, m0);
2844 
2845 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
2846 		k = ieee80211_crypto_encap(ni, m0);
2847 		if (k == NULL) {
2848 			device_printf(sc->sc_dev,
2849 			    "ieee80211_crypto_encap returns NULL.\n");
2850 			/* XXX we don't expect the fragmented frames */
2851 			return (ENOBUFS);
2852 		}
2853 		wh = mtod(m0, struct ieee80211_frame *);
2854 	}
2855 	/* If we have QoS then use it */
2856 	/* XXX TODO: mbuf WME/PRI versus TID? */
2857 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
2858 		/* Has QoS */
2859 		prio = M_WME_GETAC(m0);
2860 		which = rsu_wme_ac_xfer_map[prio];
2861 		hasqos = 1;
2862 	} else {
2863 		/* Non-QoS TID */
2864 		/* XXX TODO: tid=0 for non-qos TID? */
2865 		which = rsu_wme_ac_xfer_map[WME_AC_BE];
2866 		hasqos = 0;
2867 		prio = 0;
2868 	}
2869 
2870 	qid = rsu_ac2qid[prio];
2871 #if 0
2872 	switch (type) {
2873 	case IEEE80211_FC0_TYPE_CTL:
2874 	case IEEE80211_FC0_TYPE_MGT:
2875 		which = rsu_wme_ac_xfer_map[WME_AC_VO];
2876 		break;
2877 	default:
2878 		which = rsu_wme_ac_xfer_map[M_WME_GETAC(m0)];
2879 		break;
2880 	}
2881 	hasqos = 0;
2882 #endif
2883 
2884 	RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: pri=%d, which=%d, hasqos=%d\n",
2885 	    __func__,
2886 	    prio,
2887 	    which,
2888 	    hasqos);
2889 
2890 	/* Fill Tx descriptor. */
2891 	txd = (struct r92s_tx_desc *)data->buf;
2892 	memset(txd, 0, sizeof(*txd));
2893 
2894 	txd->txdw0 |= htole32(
2895 	    SM(R92S_TXDW0_PKTLEN, m0->m_pkthdr.len) |
2896 	    SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
2897 	    R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
2898 
2899 	txd->txdw1 |= htole32(
2900 	    SM(R92S_TXDW1_MACID, R92S_MACID_BSS) | SM(R92S_TXDW1_QSEL, qid));
2901 	if (!hasqos)
2902 		txd->txdw1 |= htole32(R92S_TXDW1_NONQOS);
2903 	if (k != NULL && !(k->wk_flags & IEEE80211_KEY_SWENCRYPT)) {
2904 		switch (k->wk_cipher->ic_cipher) {
2905 		case IEEE80211_CIPHER_WEP:
2906 			cipher = R92S_TXDW1_CIPHER_WEP;
2907 			break;
2908 		case IEEE80211_CIPHER_TKIP:
2909 			cipher = R92S_TXDW1_CIPHER_TKIP;
2910 			break;
2911 		case IEEE80211_CIPHER_AES_CCM:
2912 			cipher = R92S_TXDW1_CIPHER_AES;
2913 			break;
2914 		default:
2915 			cipher = R92S_TXDW1_CIPHER_NONE;
2916 		}
2917 		txd->txdw1 |= htole32(
2918 		    SM(R92S_TXDW1_CIPHER, cipher) |
2919 		    SM(R92S_TXDW1_KEYIDX, k->wk_keyix));
2920 	}
2921 	/* XXX todo: set AGGEN bit if appropriate? */
2922 	txd->txdw2 |= htole32(R92S_TXDW2_BK);
2923 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
2924 		txd->txdw2 |= htole32(R92S_TXDW2_BMCAST);
2925 	/*
2926 	 * Firmware will use and increment the sequence number for the
2927 	 * specified priority.
2928 	 */
2929 	txd->txdw3 |= htole32(SM(R92S_TXDW3_SEQ, prio));
2930 
2931 	if (ieee80211_radiotap_active_vap(vap)) {
2932 		struct rsu_tx_radiotap_header *tap = &sc->sc_txtap;
2933 
2934 		tap->wt_flags = 0;
2935 		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
2936 		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
2937 		ieee80211_radiotap_tx(vap, m0);
2938 	}
2939 
2940 	xferlen = sizeof(*txd) + m0->m_pkthdr.len;
2941 	m_copydata(m0, 0, m0->m_pkthdr.len, (caddr_t)&txd[1]);
2942 
2943 	data->buflen = xferlen;
2944 	data->ni = ni;
2945 	data->m = m0;
2946 	STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
2947 
2948 	/* start transfer, if any */
2949 	usbd_transfer_start(sc->sc_xfer[which]);
2950 	return (0);
2951 }
2952 
2953 static int
2954 rsu_transmit(struct ieee80211com *ic, struct mbuf *m)
2955 {
2956 	struct rsu_softc *sc = ic->ic_softc;
2957 	int error;
2958 
2959 	RSU_LOCK(sc);
2960 	if (!sc->sc_running) {
2961 		RSU_UNLOCK(sc);
2962 		return (ENXIO);
2963 	}
2964 
2965 	/*
2966 	 * XXX TODO: ensure that we treat 'm' as a list of frames
2967 	 * to transmit!
2968 	 */
2969 	error = mbufq_enqueue(&sc->sc_snd, m);
2970 	if (error) {
2971 		RSU_DPRINTF(sc, RSU_DEBUG_TX,
2972 		    "%s: mbufq_enable: failed (%d)\n",
2973 		    __func__,
2974 		    error);
2975 		RSU_UNLOCK(sc);
2976 		return (error);
2977 	}
2978 	RSU_UNLOCK(sc);
2979 
2980 	/* This kicks the TX taskqueue */
2981 	rsu_start(sc);
2982 
2983 	return (0);
2984 }
2985 
2986 static void
2987 rsu_drain_mbufq(struct rsu_softc *sc)
2988 {
2989 	struct mbuf *m;
2990 	struct ieee80211_node *ni;
2991 
2992 	RSU_ASSERT_LOCKED(sc);
2993 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
2994 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
2995 		m->m_pkthdr.rcvif = NULL;
2996 		ieee80211_free_node(ni);
2997 		m_freem(m);
2998 	}
2999 }
3000 
3001 static void
3002 _rsu_start(struct rsu_softc *sc)
3003 {
3004 	struct ieee80211_node *ni;
3005 	struct rsu_data *bf;
3006 	struct mbuf *m;
3007 
3008 	RSU_ASSERT_LOCKED(sc);
3009 
3010 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
3011 		bf = rsu_getbuf(sc);
3012 		if (bf == NULL) {
3013 			RSU_DPRINTF(sc, RSU_DEBUG_TX,
3014 			    "%s: failed to get buffer\n", __func__);
3015 			mbufq_prepend(&sc->sc_snd, m);
3016 			break;
3017 		}
3018 
3019 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
3020 		m->m_pkthdr.rcvif = NULL;
3021 
3022 		if (rsu_tx_start(sc, ni, m, bf) != 0) {
3023 			RSU_DPRINTF(sc, RSU_DEBUG_TX,
3024 			    "%s: failed to transmit\n", __func__);
3025 			if_inc_counter(ni->ni_vap->iv_ifp,
3026 			    IFCOUNTER_OERRORS, 1);
3027 			rsu_freebuf(sc, bf);
3028 			ieee80211_free_node(ni);
3029 			m_freem(m);
3030 			break;
3031 		}
3032 	}
3033 }
3034 
3035 static void
3036 rsu_start(struct rsu_softc *sc)
3037 {
3038 
3039 	taskqueue_enqueue(taskqueue_thread, &sc->tx_task);
3040 }
3041 
3042 static int
3043 rsu_ioctl_net(struct ieee80211com *ic, u_long cmd, void *data)
3044 {
3045 	struct rsu_softc *sc = ic->ic_softc;
3046 	struct ifreq *ifr = (struct ifreq *)data;
3047 	int error;
3048 
3049 	error = 0;
3050 	switch (cmd) {
3051 	case SIOCSIFCAP:
3052 	{
3053 		struct ieee80211vap *vap;
3054 		int rxmask;
3055 
3056 		rxmask = ifr->ifr_reqcap & (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6);
3057 
3058 		RSU_LOCK(sc);
3059 		/* Both RXCSUM bits must be set (or unset). */
3060 		if (sc->sc_rx_checksum_enable &&
3061 		    rxmask != (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6)) {
3062 			rxmask = 0;
3063 			sc->sc_rx_checksum_enable = 0;
3064 			rsu_rxfilter_set(sc, R92S_RCR_TCP_OFFLD_EN, 0);
3065 		} else if (!sc->sc_rx_checksum_enable && rxmask != 0) {
3066 			rxmask = IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6;
3067 			sc->sc_rx_checksum_enable = 1;
3068 			rsu_rxfilter_set(sc, 0, R92S_RCR_TCP_OFFLD_EN);
3069 		} else {
3070 			/* Nothing to do. */
3071 			RSU_UNLOCK(sc);
3072 			break;
3073 		}
3074 		RSU_UNLOCK(sc);
3075 
3076 		IEEE80211_LOCK(ic);	/* XXX */
3077 		TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
3078 			struct ifnet *ifp = vap->iv_ifp;
3079 
3080 			ifp->if_capenable &=
3081 			    ~(IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6);
3082 			ifp->if_capenable |= rxmask;
3083 		}
3084 		IEEE80211_UNLOCK(ic);
3085 		break;
3086 	}
3087 	default:
3088 		error = ENOTTY;		/* for net80211 */
3089 		break;
3090 	}
3091 
3092 	return (error);
3093 }
3094 
3095 static void
3096 rsu_parent(struct ieee80211com *ic)
3097 {
3098 	struct rsu_softc *sc = ic->ic_softc;
3099 
3100 	if (ic->ic_nrunning > 0) {
3101 		if (rsu_init(sc) == 0)
3102 			ieee80211_start_all(ic);
3103 		else {
3104 			struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3105 			if (vap != NULL)
3106 				ieee80211_stop(vap);
3107 		}
3108 	} else
3109 		rsu_stop(sc);
3110 }
3111 
3112 /*
3113  * Power on sequence for A-cut adapters.
3114  */
3115 static void
3116 rsu_power_on_acut(struct rsu_softc *sc)
3117 {
3118 	uint32_t reg;
3119 
3120 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
3121 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
3122 
3123 	/* Enable AFE macro block's bandgap and Mbias. */
3124 	rsu_write_1(sc, R92S_AFE_MISC,
3125 	    rsu_read_1(sc, R92S_AFE_MISC) |
3126 	    R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN);
3127 	/* Enable LDOA15 block. */
3128 	rsu_write_1(sc, R92S_LDOA15_CTRL,
3129 	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
3130 
3131 	rsu_write_1(sc, R92S_SPS1_CTRL,
3132 	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_LDEN);
3133 	rsu_ms_delay(sc, 2000);
3134 	/* Enable switch regulator block. */
3135 	rsu_write_1(sc, R92S_SPS1_CTRL,
3136 	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_SWEN);
3137 
3138 	rsu_write_4(sc, R92S_SPS1_CTRL, 0x00a7b267);
3139 
3140 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3141 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
3142 
3143 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3144 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
3145 
3146 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3147 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x90);
3148 
3149 	/* Enable AFE clock. */
3150 	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
3151 	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
3152 	/* Enable AFE PLL macro block. */
3153 	rsu_write_1(sc, R92S_AFE_PLL_CTRL,
3154 	    rsu_read_1(sc, R92S_AFE_PLL_CTRL) | 0x11);
3155 	/* Attach AFE PLL to MACTOP/BB. */
3156 	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
3157 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
3158 
3159 	/* Switch to 40MHz clock instead of 80MHz. */
3160 	rsu_write_2(sc, R92S_SYS_CLKR,
3161 	    rsu_read_2(sc, R92S_SYS_CLKR) & ~R92S_SYS_CLKSEL);
3162 
3163 	/* Enable MAC clock. */
3164 	rsu_write_2(sc, R92S_SYS_CLKR,
3165 	    rsu_read_2(sc, R92S_SYS_CLKR) |
3166 	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
3167 
3168 	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
3169 
3170 	/* Enable digital core and IOREG R/W. */
3171 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3172 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
3173 
3174 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3175 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
3176 
3177 	/* Switch the control path to firmware. */
3178 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
3179 	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
3180 	rsu_write_2(sc, R92S_SYS_CLKR, reg);
3181 
3182 	rsu_write_2(sc, R92S_CR, 0x37fc);
3183 
3184 	/* Fix USB RX FIFO issue. */
3185 	rsu_write_1(sc, 0xfe5c,
3186 	    rsu_read_1(sc, 0xfe5c) | 0x80);
3187 	rsu_write_1(sc, 0x00ab,
3188 	    rsu_read_1(sc, 0x00ab) | 0xc0);
3189 
3190 	rsu_write_1(sc, R92S_SYS_CLKR,
3191 	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
3192 }
3193 
3194 /*
3195  * Power on sequence for B-cut and C-cut adapters.
3196  */
3197 static void
3198 rsu_power_on_bcut(struct rsu_softc *sc)
3199 {
3200 	uint32_t reg;
3201 	int ntries;
3202 
3203 	/* Prevent eFuse leakage. */
3204 	rsu_write_1(sc, 0x37, 0xb0);
3205 	rsu_ms_delay(sc, 10);
3206 	rsu_write_1(sc, 0x37, 0x30);
3207 
3208 	/* Switch the control path to hardware. */
3209 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
3210 	if (reg & R92S_FWHW_SEL) {
3211 		rsu_write_2(sc, R92S_SYS_CLKR,
3212 		    reg & ~(R92S_SWHW_SEL | R92S_FWHW_SEL));
3213 	}
3214 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3215 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) & ~0x8c);
3216 	rsu_ms_delay(sc, 1);
3217 
3218 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
3219 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
3220 
3221 	reg = rsu_read_1(sc, R92S_AFE_MISC);
3222 	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN);
3223 	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN |
3224 	    R92S_AFE_MISC_MBEN | R92S_AFE_MISC_I32_EN);
3225 
3226 	/* Enable PLL. */
3227 	rsu_write_1(sc, R92S_LDOA15_CTRL,
3228 	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
3229 
3230 	rsu_write_1(sc, R92S_LDOV12D_CTRL,
3231 	    rsu_read_1(sc, R92S_LDOV12D_CTRL) | R92S_LDV12_EN);
3232 
3233 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3234 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
3235 
3236 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3237 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
3238 
3239 	/* Support 64KB IMEM. */
3240 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3241 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x97);
3242 
3243 	/* Enable AFE clock. */
3244 	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
3245 	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
3246 	/* Enable AFE PLL macro block. */
3247 	reg = rsu_read_1(sc, R92S_AFE_PLL_CTRL);
3248 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
3249 	rsu_ms_delay(sc, 1);
3250 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x51);
3251 	rsu_ms_delay(sc, 1);
3252 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
3253 	rsu_ms_delay(sc, 1);
3254 
3255 	/* Attach AFE PLL to MACTOP/BB. */
3256 	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
3257 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
3258 
3259 	/* Switch to 40MHz clock. */
3260 	rsu_write_1(sc, R92S_SYS_CLKR, 0x00);
3261 	/* Disable CPU clock and 80MHz SSC. */
3262 	rsu_write_1(sc, R92S_SYS_CLKR,
3263 	    rsu_read_1(sc, R92S_SYS_CLKR) | 0xa0);
3264 	/* Enable MAC clock. */
3265 	rsu_write_2(sc, R92S_SYS_CLKR,
3266 	    rsu_read_2(sc, R92S_SYS_CLKR) |
3267 	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
3268 
3269 	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
3270 
3271 	/* Enable digital core and IOREG R/W. */
3272 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3273 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
3274 
3275 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3276 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
3277 
3278 	/* Switch the control path to firmware. */
3279 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
3280 	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
3281 	rsu_write_2(sc, R92S_SYS_CLKR, reg);
3282 
3283 	rsu_write_2(sc, R92S_CR, 0x37fc);
3284 
3285 	/* Fix USB RX FIFO issue. */
3286 	rsu_write_1(sc, 0xfe5c,
3287 	    rsu_read_1(sc, 0xfe5c) | 0x80);
3288 
3289 	rsu_write_1(sc, R92S_SYS_CLKR,
3290 	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
3291 
3292 	rsu_write_1(sc, 0xfe1c, 0x80);
3293 
3294 	/* Make sure TxDMA is ready to download firmware. */
3295 	for (ntries = 0; ntries < 20; ntries++) {
3296 		reg = rsu_read_1(sc, R92S_TCR);
3297 		if ((reg & (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) ==
3298 		    (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT))
3299 			break;
3300 		rsu_ms_delay(sc, 1);
3301 	}
3302 	if (ntries == 20) {
3303 		RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_TX,
3304 		    "%s: TxDMA is not ready\n",
3305 		    __func__);
3306 		/* Reset TxDMA. */
3307 		reg = rsu_read_1(sc, R92S_CR);
3308 		rsu_write_1(sc, R92S_CR, reg & ~R92S_CR_TXDMA_EN);
3309 		rsu_ms_delay(sc, 1);
3310 		rsu_write_1(sc, R92S_CR, reg | R92S_CR_TXDMA_EN);
3311 	}
3312 }
3313 
3314 static void
3315 rsu_power_off(struct rsu_softc *sc)
3316 {
3317 	/* Turn RF off. */
3318 	rsu_write_1(sc, R92S_RF_CTRL, 0x00);
3319 	rsu_ms_delay(sc, 5);
3320 
3321 	/* Turn MAC off. */
3322 	/* Switch control path. */
3323 	rsu_write_1(sc, R92S_SYS_CLKR + 1, 0x38);
3324 	/* Reset MACTOP. */
3325 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x70);
3326 	rsu_write_1(sc, R92S_PMC_FSM, 0x06);
3327 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 0, 0xf9);
3328 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, 0xe8);
3329 
3330 	/* Disable AFE PLL. */
3331 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, 0x00);
3332 	/* Disable A15V. */
3333 	rsu_write_1(sc, R92S_LDOA15_CTRL, 0x54);
3334 	/* Disable eFuse 1.2V. */
3335 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x50);
3336 	rsu_write_1(sc, R92S_LDOV12D_CTRL, 0x24);
3337 	/* Enable AFE macro block's bandgap and Mbias. */
3338 	rsu_write_1(sc, R92S_AFE_MISC, 0x30);
3339 	/* Disable 1.6V LDO. */
3340 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x56);
3341 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x43);
3342 
3343 	/* Firmware - tell it to switch things off */
3344 	(void) rsu_set_fw_power_state(sc, RSU_PWR_OFF);
3345 }
3346 
3347 static int
3348 rsu_fw_loadsection(struct rsu_softc *sc, const uint8_t *buf, int len)
3349 {
3350 	const uint8_t which = rsu_wme_ac_xfer_map[WME_AC_VO];
3351 	struct rsu_data *data;
3352 	struct r92s_tx_desc *txd;
3353 	int mlen;
3354 
3355 	while (len > 0) {
3356 		data = rsu_getbuf(sc);
3357 		if (data == NULL)
3358 			return (ENOMEM);
3359 		txd = (struct r92s_tx_desc *)data->buf;
3360 		memset(txd, 0, sizeof(*txd));
3361 		if (len <= RSU_TXBUFSZ - sizeof(*txd)) {
3362 			/* Last chunk. */
3363 			txd->txdw0 |= htole32(R92S_TXDW0_LINIP);
3364 			mlen = len;
3365 		} else
3366 			mlen = RSU_TXBUFSZ - sizeof(*txd);
3367 		txd->txdw0 |= htole32(SM(R92S_TXDW0_PKTLEN, mlen));
3368 		memcpy(&txd[1], buf, mlen);
3369 		data->buflen = sizeof(*txd) + mlen;
3370 		RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FW | RSU_DEBUG_RESET,
3371 		    "%s: starting transfer %p\n",
3372 		    __func__, data);
3373 		STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
3374 		buf += mlen;
3375 		len -= mlen;
3376 	}
3377 	usbd_transfer_start(sc->sc_xfer[which]);
3378 	return (0);
3379 }
3380 
3381 CTASSERT(sizeof(size_t) >= sizeof(uint32_t));
3382 
3383 static int
3384 rsu_load_firmware(struct rsu_softc *sc)
3385 {
3386 	const struct r92s_fw_hdr *hdr;
3387 	struct r92s_fw_priv *dmem;
3388 	struct ieee80211com *ic = &sc->sc_ic;
3389 	const uint8_t *imem, *emem;
3390 	uint32_t imemsz, ememsz;
3391 	const struct firmware *fw;
3392 	size_t size;
3393 	uint32_t reg;
3394 	int ntries, error;
3395 
3396 	if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY) {
3397 		RSU_DPRINTF(sc, RSU_DEBUG_ANY,
3398 		    "%s: Firmware already loaded\n",
3399 		    __func__);
3400 		return (0);
3401 	}
3402 
3403 	RSU_UNLOCK(sc);
3404 	/* Read firmware image from the filesystem. */
3405 	if ((fw = firmware_get("rsu-rtl8712fw")) == NULL) {
3406 		device_printf(sc->sc_dev,
3407 		    "%s: failed load firmware of file rsu-rtl8712fw\n",
3408 		    __func__);
3409 		RSU_LOCK(sc);
3410 		return (ENXIO);
3411 	}
3412 	RSU_LOCK(sc);
3413 	size = fw->datasize;
3414 	if (size < sizeof(*hdr)) {
3415 		device_printf(sc->sc_dev, "firmware too short\n");
3416 		error = EINVAL;
3417 		goto fail;
3418 	}
3419 	hdr = (const struct r92s_fw_hdr *)fw->data;
3420 	if (hdr->signature != htole16(0x8712) &&
3421 	    hdr->signature != htole16(0x8192)) {
3422 		device_printf(sc->sc_dev,
3423 		    "invalid firmware signature 0x%x\n",
3424 		    le16toh(hdr->signature));
3425 		error = EINVAL;
3426 		goto fail;
3427 	}
3428 	RSU_DPRINTF(sc, RSU_DEBUG_FW, "FW V%d %02x-%02x %02x:%02x\n",
3429 	    le16toh(hdr->version), hdr->month, hdr->day, hdr->hour,
3430 	    hdr->minute);
3431 
3432 	/* Make sure that driver and firmware are in sync. */
3433 	if (hdr->privsz != htole32(sizeof(*dmem))) {
3434 		device_printf(sc->sc_dev, "unsupported firmware image\n");
3435 		error = EINVAL;
3436 		goto fail;
3437 	}
3438 	/* Get FW sections sizes. */
3439 	imemsz = le32toh(hdr->imemsz);
3440 	ememsz = le32toh(hdr->sramsz);
3441 	/* Check that all FW sections fit in image. */
3442 	if (imemsz > (size_t)(size - sizeof(*hdr)) ||
3443 	    ememsz > (size_t)(size - sizeof(*hdr) - imemsz)) {
3444 		device_printf(sc->sc_dev, "firmware too short\n");
3445 		error = EINVAL;
3446 		goto fail;
3447 	}
3448 	imem = (const uint8_t *)&hdr[1];
3449 	emem = imem + imemsz;
3450 
3451 	/* Load IMEM section. */
3452 	error = rsu_fw_loadsection(sc, imem, imemsz);
3453 	if (error != 0) {
3454 		device_printf(sc->sc_dev,
3455 		    "could not load firmware section %s\n", "IMEM");
3456 		goto fail;
3457 	}
3458 	/* Wait for load to complete. */
3459 	for (ntries = 0; ntries != 50; ntries++) {
3460 		rsu_ms_delay(sc, 10);
3461 		reg = rsu_read_1(sc, R92S_TCR);
3462 		if (reg & R92S_TCR_IMEM_CODE_DONE)
3463 			break;
3464 	}
3465 	if (ntries == 50) {
3466 		device_printf(sc->sc_dev, "timeout waiting for IMEM transfer\n");
3467 		error = ETIMEDOUT;
3468 		goto fail;
3469 	}
3470 	/* Load EMEM section. */
3471 	error = rsu_fw_loadsection(sc, emem, ememsz);
3472 	if (error != 0) {
3473 		device_printf(sc->sc_dev,
3474 		    "could not load firmware section %s\n", "EMEM");
3475 		goto fail;
3476 	}
3477 	/* Wait for load to complete. */
3478 	for (ntries = 0; ntries != 50; ntries++) {
3479 		rsu_ms_delay(sc, 10);
3480 		reg = rsu_read_2(sc, R92S_TCR);
3481 		if (reg & R92S_TCR_EMEM_CODE_DONE)
3482 			break;
3483 	}
3484 	if (ntries == 50) {
3485 		device_printf(sc->sc_dev, "timeout waiting for EMEM transfer\n");
3486 		error = ETIMEDOUT;
3487 		goto fail;
3488 	}
3489 	/* Enable CPU. */
3490 	rsu_write_1(sc, R92S_SYS_CLKR,
3491 	    rsu_read_1(sc, R92S_SYS_CLKR) | R92S_SYS_CPU_CLKSEL);
3492 	if (!(rsu_read_1(sc, R92S_SYS_CLKR) & R92S_SYS_CPU_CLKSEL)) {
3493 		device_printf(sc->sc_dev, "could not enable system clock\n");
3494 		error = EIO;
3495 		goto fail;
3496 	}
3497 	rsu_write_2(sc, R92S_SYS_FUNC_EN,
3498 	    rsu_read_2(sc, R92S_SYS_FUNC_EN) | R92S_FEN_CPUEN);
3499 	if (!(rsu_read_2(sc, R92S_SYS_FUNC_EN) & R92S_FEN_CPUEN)) {
3500 		device_printf(sc->sc_dev,
3501 		    "could not enable microcontroller\n");
3502 		error = EIO;
3503 		goto fail;
3504 	}
3505 	/* Wait for CPU to initialize. */
3506 	for (ntries = 0; ntries < 100; ntries++) {
3507 		if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_IMEM_RDY)
3508 			break;
3509 		rsu_ms_delay(sc, 1);
3510 	}
3511 	if (ntries == 100) {
3512 		device_printf(sc->sc_dev,
3513 		    "timeout waiting for microcontroller\n");
3514 		error = ETIMEDOUT;
3515 		goto fail;
3516 	}
3517 
3518 	/* Update DMEM section before loading. */
3519 	dmem = __DECONST(struct r92s_fw_priv *, &hdr->priv);
3520 	memset(dmem, 0, sizeof(*dmem));
3521 	dmem->hci_sel = R92S_HCI_SEL_USB | R92S_HCI_SEL_8172;
3522 	dmem->nendpoints = sc->sc_nendpoints;
3523 	dmem->chip_version = sc->cut;
3524 	dmem->rf_config = sc->sc_rftype;
3525 	dmem->vcs_type = R92S_VCS_TYPE_AUTO;
3526 	dmem->vcs_mode = R92S_VCS_MODE_RTS_CTS;
3527 	dmem->turbo_mode = 0;
3528 	dmem->bw40_en = !! (ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40);
3529 	dmem->amsdu2ampdu_en = !! (sc->sc_ht);
3530 	dmem->ampdu_en = !! (sc->sc_ht);
3531 	dmem->agg_offload = !! (sc->sc_ht);
3532 	dmem->qos_en = 1;
3533 	dmem->ps_offload = 1;
3534 	dmem->lowpower_mode = 1;	/* XXX TODO: configurable? */
3535 	/* Load DMEM section. */
3536 	error = rsu_fw_loadsection(sc, (uint8_t *)dmem, sizeof(*dmem));
3537 	if (error != 0) {
3538 		device_printf(sc->sc_dev,
3539 		    "could not load firmware section %s\n", "DMEM");
3540 		goto fail;
3541 	}
3542 	/* Wait for load to complete. */
3543 	for (ntries = 0; ntries < 100; ntries++) {
3544 		if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_DMEM_CODE_DONE)
3545 			break;
3546 		rsu_ms_delay(sc, 1);
3547 	}
3548 	if (ntries == 100) {
3549 		device_printf(sc->sc_dev, "timeout waiting for %s transfer\n",
3550 		    "DMEM");
3551 		error = ETIMEDOUT;
3552 		goto fail;
3553 	}
3554 	/* Wait for firmware readiness. */
3555 	for (ntries = 0; ntries < 60; ntries++) {
3556 		if (!(rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY))
3557 			break;
3558 		rsu_ms_delay(sc, 1);
3559 	}
3560 	if (ntries == 60) {
3561 		device_printf(sc->sc_dev,
3562 		    "timeout waiting for firmware readiness\n");
3563 		error = ETIMEDOUT;
3564 		goto fail;
3565 	}
3566  fail:
3567 	firmware_put(fw, FIRMWARE_UNLOAD);
3568 	return (error);
3569 }
3570 
3571 
3572 static int
3573 rsu_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
3574     const struct ieee80211_bpf_params *params)
3575 {
3576 	struct ieee80211com *ic = ni->ni_ic;
3577 	struct rsu_softc *sc = ic->ic_softc;
3578 	struct rsu_data *bf;
3579 
3580 	/* prevent management frames from being sent if we're not ready */
3581 	if (!sc->sc_running) {
3582 		m_freem(m);
3583 		return (ENETDOWN);
3584 	}
3585 	RSU_LOCK(sc);
3586 	bf = rsu_getbuf(sc);
3587 	if (bf == NULL) {
3588 		m_freem(m);
3589 		RSU_UNLOCK(sc);
3590 		return (ENOBUFS);
3591 	}
3592 	if (rsu_tx_start(sc, ni, m, bf) != 0) {
3593 		m_freem(m);
3594 		rsu_freebuf(sc, bf);
3595 		RSU_UNLOCK(sc);
3596 		return (EIO);
3597 	}
3598 	RSU_UNLOCK(sc);
3599 
3600 	return (0);
3601 }
3602 
3603 static void
3604 rsu_rxfilter_init(struct rsu_softc *sc)
3605 {
3606 	uint32_t reg;
3607 
3608 	RSU_ASSERT_LOCKED(sc);
3609 
3610 	/* Setup multicast filter. */
3611 	rsu_set_multi(sc);
3612 
3613 	/* Adjust Rx filter. */
3614 	reg = rsu_read_4(sc, R92S_RCR);
3615 	reg &= ~R92S_RCR_AICV;
3616 	reg |= R92S_RCR_APP_PHYSTS;
3617 	if (sc->sc_rx_checksum_enable)
3618 		reg |= R92S_RCR_TCP_OFFLD_EN;
3619 	rsu_write_4(sc, R92S_RCR, reg);
3620 
3621 	/* Update dynamic Rx filter parts. */
3622 	rsu_rxfilter_refresh(sc);
3623 }
3624 
3625 static void
3626 rsu_rxfilter_set(struct rsu_softc *sc, uint32_t clear, uint32_t set)
3627 {
3628 	/* NB: firmware can touch this register too. */
3629 	rsu_write_4(sc, R92S_RCR,
3630 	   (rsu_read_4(sc, R92S_RCR) & ~clear) | set);
3631 }
3632 
3633 static void
3634 rsu_rxfilter_refresh(struct rsu_softc *sc)
3635 {
3636 	struct ieee80211com *ic = &sc->sc_ic;
3637 	uint32_t mask_all, mask_min;
3638 
3639 	RSU_ASSERT_LOCKED(sc);
3640 
3641 	/* NB: RCR_AMF / RXFLTMAP_MGT are used by firmware. */
3642 	mask_all = R92S_RCR_ACF | R92S_RCR_AAP;
3643 	mask_min = R92S_RCR_APM;
3644 	if (sc->sc_vap_is_running)
3645 		mask_min |= R92S_RCR_CBSSID;
3646 	else
3647 		mask_all |= R92S_RCR_ADF;
3648 
3649 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
3650 		uint16_t rxfltmap;
3651 		if (sc->sc_vap_is_running)
3652 			rxfltmap = 0;
3653 		else
3654 			rxfltmap = R92S_RXFLTMAP_MGT_DEF;
3655 		rsu_write_2(sc, R92S_RXFLTMAP_MGT, rxfltmap);
3656 	}
3657 
3658 	if (ic->ic_promisc == 0 && ic->ic_opmode != IEEE80211_M_MONITOR)
3659 		rsu_rxfilter_set(sc, mask_all, mask_min);
3660 	else
3661 		rsu_rxfilter_set(sc, mask_min, mask_all);
3662 }
3663 
3664 static int
3665 rsu_init(struct rsu_softc *sc)
3666 {
3667 	struct ieee80211com *ic = &sc->sc_ic;
3668 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3669 	uint8_t macaddr[IEEE80211_ADDR_LEN];
3670 	int error;
3671 	int i;
3672 
3673 	RSU_LOCK(sc);
3674 
3675 	if (sc->sc_running) {
3676 		RSU_UNLOCK(sc);
3677 		return (0);
3678 	}
3679 
3680 	/* Ensure the mbuf queue is drained */
3681 	rsu_drain_mbufq(sc);
3682 
3683 	/* Reset power management state. */
3684 	rsu_write_1(sc, R92S_USB_HRPWM, 0);
3685 
3686 	/* Power on adapter. */
3687 	if (sc->cut == 1)
3688 		rsu_power_on_acut(sc);
3689 	else
3690 		rsu_power_on_bcut(sc);
3691 
3692 	/* Load firmware. */
3693 	error = rsu_load_firmware(sc);
3694 	if (error != 0)
3695 		goto fail;
3696 
3697 	rsu_write_4(sc, R92S_CR,
3698 	    rsu_read_4(sc, R92S_CR) & ~0xff000000);
3699 
3700 	/* Use 128 bytes pages. */
3701 	rsu_write_1(sc, 0x00b5,
3702 	    rsu_read_1(sc, 0x00b5) | 0x01);
3703 	/* Enable USB Rx aggregation. */
3704 	rsu_write_1(sc, 0x00bd,
3705 	    rsu_read_1(sc, 0x00bd) | 0x80);
3706 	/* Set USB Rx aggregation threshold. */
3707 	rsu_write_1(sc, 0x00d9, 0x01);
3708 	/* Set USB Rx aggregation timeout (1.7ms/4). */
3709 	rsu_write_1(sc, 0xfe5b, 0x04);
3710 	/* Fix USB Rx FIFO issue. */
3711 	rsu_write_1(sc, 0xfe5c,
3712 	    rsu_read_1(sc, 0xfe5c) | 0x80);
3713 
3714 	/* Set MAC address. */
3715 	IEEE80211_ADDR_COPY(macaddr, vap ? vap->iv_myaddr : ic->ic_macaddr);
3716 	rsu_write_region_1(sc, R92S_MACID, macaddr, IEEE80211_ADDR_LEN);
3717 
3718 	/* It really takes 1.5 seconds for the firmware to boot: */
3719 	usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(2000));
3720 
3721 	RSU_DPRINTF(sc, RSU_DEBUG_RESET, "%s: setting MAC address to %s\n",
3722 	    __func__,
3723 	    ether_sprintf(macaddr));
3724 	error = rsu_fw_cmd(sc, R92S_CMD_SET_MAC_ADDRESS, macaddr,
3725 	    IEEE80211_ADDR_LEN);
3726 	if (error != 0) {
3727 		device_printf(sc->sc_dev, "could not set MAC address\n");
3728 		goto fail;
3729 	}
3730 
3731 	/* Initialize Rx filter. */
3732 	rsu_rxfilter_init(sc);
3733 
3734 	/* Set PS mode fully active */
3735 	error = rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
3736 	if (error != 0) {
3737 		device_printf(sc->sc_dev, "could not set PS mode\n");
3738 		goto fail;
3739 	}
3740 
3741 	/* Install static keys (if any). */
3742 	error = rsu_reinit_static_keys(sc);
3743 	if (error != 0)
3744 		goto fail;
3745 
3746 	sc->sc_extra_scan = 0;
3747 	usbd_transfer_start(sc->sc_xfer[RSU_BULK_RX]);
3748 
3749 	/* We're ready to go. */
3750 	sc->sc_running = 1;
3751 	RSU_UNLOCK(sc);
3752 
3753 	return (0);
3754 fail:
3755 	/* Need to stop all failed transfers, if any */
3756 	for (i = 0; i != RSU_N_TRANSFER; i++)
3757 		usbd_transfer_stop(sc->sc_xfer[i]);
3758 	RSU_UNLOCK(sc);
3759 
3760 	return (error);
3761 }
3762 
3763 static void
3764 rsu_stop(struct rsu_softc *sc)
3765 {
3766 	int i;
3767 
3768 	RSU_LOCK(sc);
3769 	if (!sc->sc_running) {
3770 		RSU_UNLOCK(sc);
3771 		return;
3772 	}
3773 
3774 	sc->sc_running = 0;
3775 	sc->sc_vap_is_running = 0;
3776 	sc->sc_calibrating = 0;
3777 	taskqueue_cancel_timeout(taskqueue_thread, &sc->calib_task, NULL);
3778 	taskqueue_cancel(taskqueue_thread, &sc->tx_task, NULL);
3779 
3780 	/* Power off adapter. */
3781 	rsu_power_off(sc);
3782 
3783 	/*
3784 	 * CAM is not accessible after shutdown;
3785 	 * all entries are marked (by firmware?) as invalid.
3786 	 */
3787 	memset(sc->free_keys_bmap, 0, sizeof(sc->free_keys_bmap));
3788 	memset(sc->keys_bmap, 0, sizeof(sc->keys_bmap));
3789 
3790 	for (i = 0; i < RSU_N_TRANSFER; i++)
3791 		usbd_transfer_stop(sc->sc_xfer[i]);
3792 
3793 	/* Ensure the mbuf queue is drained */
3794 	rsu_drain_mbufq(sc);
3795 	RSU_UNLOCK(sc);
3796 }
3797 
3798 /*
3799  * Note: usb_pause_mtx() actually releases the mutex before calling pause(),
3800  * which breaks any kind of driver serialisation.
3801  */
3802 static void
3803 rsu_ms_delay(struct rsu_softc *sc, int ms)
3804 {
3805 
3806 	//usb_pause_mtx(&sc->sc_mtx, hz / 1000);
3807 	DELAY(ms * 1000);
3808 }
3809