xref: /freebsd/sys/dev/usb/wlan/if_rsu.c (revision 3416500aef140042c64bc149cb1ec6620483bc44)
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 static void
2035 rsu_event_survey(struct rsu_softc *sc, uint8_t *buf, int len)
2036 {
2037 	struct ieee80211com *ic = &sc->sc_ic;
2038 	struct ieee80211_frame *wh;
2039 	struct ndis_wlan_bssid_ex *bss;
2040 	struct ieee80211_rx_stats rxs;
2041 	struct mbuf *m;
2042 	int pktlen;
2043 
2044 	if (__predict_false(len < sizeof(*bss)))
2045 		return;
2046 	bss = (struct ndis_wlan_bssid_ex *)buf;
2047 	if (__predict_false(len < sizeof(*bss) + le32toh(bss->ieslen)))
2048 		return;
2049 
2050 	RSU_DPRINTF(sc, RSU_DEBUG_SCAN,
2051 	    "%s: found BSS %s: len=%d chan=%d inframode=%d "
2052 	    "networktype=%d privacy=%d, RSSI=%d\n",
2053 	    __func__,
2054 	    ether_sprintf(bss->macaddr), le32toh(bss->len),
2055 	    le32toh(bss->config.dsconfig), le32toh(bss->inframode),
2056 	    le32toh(bss->networktype), le32toh(bss->privacy),
2057 	    le32toh(bss->rssi));
2058 
2059 	/* Build a fake beacon frame to let net80211 do all the parsing. */
2060 	/* XXX TODO: just call the new scan API methods! */
2061 	pktlen = sizeof(*wh) + le32toh(bss->ieslen);
2062 	if (__predict_false(pktlen > MCLBYTES))
2063 		return;
2064 	m = m_get2(pktlen, M_NOWAIT, MT_DATA, M_PKTHDR);
2065 	if (__predict_false(m == NULL))
2066 		return;
2067 	wh = mtod(m, struct ieee80211_frame *);
2068 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2069 	    IEEE80211_FC0_SUBTYPE_BEACON;
2070 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2071 	USETW(wh->i_dur, 0);
2072 	IEEE80211_ADDR_COPY(wh->i_addr1, ieee80211broadcastaddr);
2073 	IEEE80211_ADDR_COPY(wh->i_addr2, bss->macaddr);
2074 	IEEE80211_ADDR_COPY(wh->i_addr3, bss->macaddr);
2075 	*(uint16_t *)wh->i_seq = 0;
2076 	memcpy(&wh[1], (uint8_t *)&bss[1], le32toh(bss->ieslen));
2077 
2078 	/* Finalize mbuf. */
2079 	m->m_pkthdr.len = m->m_len = pktlen;
2080 
2081 	/* Set channel flags for input path */
2082 	bzero(&rxs, sizeof(rxs));
2083 	rxs.r_flags |= IEEE80211_R_IEEE | IEEE80211_R_FREQ;
2084 	rxs.r_flags |= IEEE80211_R_NF | IEEE80211_R_RSSI;
2085 	rxs.c_ieee = le32toh(bss->config.dsconfig);
2086 	rxs.c_freq = ieee80211_ieee2mhz(rxs.c_ieee, IEEE80211_CHAN_2GHZ);
2087 	/* This is a number from 0..100; so let's just divide it down a bit */
2088 	rxs.c_rssi = le32toh(bss->rssi) / 2;
2089 	rxs.c_nf = -96;
2090 	if (ieee80211_add_rx_params(m, &rxs) == 0)
2091 		return;
2092 
2093 	/* XXX avoid a LOR */
2094 	RSU_UNLOCK(sc);
2095 	ieee80211_input_mimo_all(ic, m);
2096 	RSU_LOCK(sc);
2097 }
2098 
2099 static void
2100 rsu_event_join_bss(struct rsu_softc *sc, uint8_t *buf, int len)
2101 {
2102 	struct ieee80211com *ic = &sc->sc_ic;
2103 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2104 	struct ieee80211_node *ni = vap->iv_bss;
2105 	struct r92s_event_join_bss *rsp;
2106 	uint32_t tmp;
2107 	int res;
2108 
2109 	if (__predict_false(len < sizeof(*rsp)))
2110 		return;
2111 	rsp = (struct r92s_event_join_bss *)buf;
2112 	res = (int)le32toh(rsp->join_res);
2113 
2114 	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
2115 	    "%s: Rx join BSS event len=%d res=%d\n",
2116 	    __func__, len, res);
2117 
2118 	/*
2119 	 * XXX Don't do this; there's likely a better way to tell
2120 	 * the caller we failed.
2121 	 */
2122 	if (res <= 0) {
2123 		RSU_UNLOCK(sc);
2124 		ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
2125 		RSU_LOCK(sc);
2126 		return;
2127 	}
2128 
2129 	tmp = le32toh(rsp->associd);
2130 	if (tmp >= vap->iv_max_aid) {
2131 		RSU_DPRINTF(sc, RSU_DEBUG_ANY, "Assoc ID overflow\n");
2132 		tmp = 1;
2133 	}
2134 	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
2135 	    "%s: associated with %s associd=%d\n",
2136 	    __func__, ether_sprintf(rsp->bss.macaddr), tmp);
2137 	/* XXX is this required? What's the top two bits for again? */
2138 	ni->ni_associd = tmp | 0xc000;
2139 
2140 	/* Refresh Rx filter (was changed by firmware). */
2141 	sc->sc_vap_is_running = 1;
2142 	rsu_rxfilter_refresh(sc);
2143 
2144 	RSU_UNLOCK(sc);
2145 	ieee80211_new_state(vap, IEEE80211_S_RUN,
2146 	    IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
2147 	RSU_LOCK(sc);
2148 }
2149 
2150 static void
2151 rsu_event_addba_req_report(struct rsu_softc *sc, uint8_t *buf, int len)
2152 {
2153 	struct ieee80211com *ic = &sc->sc_ic;
2154 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2155 	struct r92s_add_ba_event *ba = (void *) buf;
2156 	struct ieee80211_node *ni;
2157 
2158 	if (len < sizeof(*ba)) {
2159 		device_printf(sc->sc_dev, "%s: short read (%d)\n", __func__, len);
2160 		return;
2161 	}
2162 
2163 	if (vap == NULL)
2164 		return;
2165 
2166 	RSU_DPRINTF(sc, RSU_DEBUG_AMPDU, "%s: mac=%s, tid=%d, ssn=%d\n",
2167 	    __func__,
2168 	    ether_sprintf(ba->mac_addr),
2169 	    (int) ba->tid,
2170 	    (int) le16toh(ba->ssn));
2171 
2172 	/* XXX do node lookup; this is STA specific */
2173 
2174 	ni = ieee80211_ref_node(vap->iv_bss);
2175 	ieee80211_ampdu_rx_start_ext(ni, ba->tid, le16toh(ba->ssn) >> 4, 32);
2176 	ieee80211_free_node(ni);
2177 }
2178 
2179 static void
2180 rsu_rx_event(struct rsu_softc *sc, uint8_t code, uint8_t *buf, int len)
2181 {
2182 	struct ieee80211com *ic = &sc->sc_ic;
2183 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2184 
2185 	RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD,
2186 	    "%s: Rx event code=%d len=%d\n", __func__, code, len);
2187 	switch (code) {
2188 	case R92S_EVT_SURVEY:
2189 		rsu_event_survey(sc, buf, len);
2190 		break;
2191 	case R92S_EVT_SURVEY_DONE:
2192 		RSU_DPRINTF(sc, RSU_DEBUG_SCAN,
2193 		    "%s: %s scan done, found %d BSS\n",
2194 		    __func__, sc->sc_extra_scan ? "direct" : "broadcast",
2195 		    le32toh(*(uint32_t *)buf));
2196 		if (sc->sc_extra_scan == 1) {
2197 			/* Send broadcast probe request. */
2198 			sc->sc_extra_scan = 0;
2199 			if (vap != NULL && rsu_site_survey(sc, NULL) != 0) {
2200 				RSU_UNLOCK(sc);
2201 				ieee80211_cancel_scan(vap);
2202 				RSU_LOCK(sc);
2203 			}
2204 			break;
2205 		}
2206 		if (vap != NULL) {
2207 			RSU_UNLOCK(sc);
2208 			ieee80211_scan_done(vap);
2209 			RSU_LOCK(sc);
2210 		}
2211 		break;
2212 	case R92S_EVT_JOIN_BSS:
2213 		if (vap->iv_state == IEEE80211_S_AUTH)
2214 			rsu_event_join_bss(sc, buf, len);
2215 		break;
2216 	case R92S_EVT_DEL_STA:
2217 		RSU_DPRINTF(sc, RSU_DEBUG_FWCMD | RSU_DEBUG_STATE,
2218 		    "%s: disassociated from %s\n", __func__,
2219 		    ether_sprintf(buf));
2220 		if (vap->iv_state == IEEE80211_S_RUN &&
2221 		    IEEE80211_ADDR_EQ(vap->iv_bss->ni_bssid, buf)) {
2222 			RSU_UNLOCK(sc);
2223 			ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
2224 			RSU_LOCK(sc);
2225 		}
2226 		break;
2227 	case R92S_EVT_WPS_PBC:
2228 		RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD,
2229 		    "%s: WPS PBC pushed.\n", __func__);
2230 		break;
2231 	case R92S_EVT_FWDBG:
2232 		buf[60] = '\0';
2233 		RSU_DPRINTF(sc, RSU_DEBUG_FWDBG, "FWDBG: %s\n", (char *)buf);
2234 		break;
2235 	case R92S_EVT_ADDBA_REQ_REPORT:
2236 		rsu_event_addba_req_report(sc, buf, len);
2237 		break;
2238 	default:
2239 		device_printf(sc->sc_dev, "%s: unhandled code (%d)\n", __func__, code);
2240 		break;
2241 	}
2242 }
2243 
2244 static void
2245 rsu_rx_multi_event(struct rsu_softc *sc, uint8_t *buf, int len)
2246 {
2247 	struct r92s_fw_cmd_hdr *cmd;
2248 	int cmdsz;
2249 
2250 	RSU_DPRINTF(sc, RSU_DEBUG_RX, "%s: Rx events len=%d\n", __func__, len);
2251 
2252 	/* Skip Rx status. */
2253 	buf += sizeof(struct r92s_rx_stat);
2254 	len -= sizeof(struct r92s_rx_stat);
2255 
2256 	/* Process all events. */
2257 	for (;;) {
2258 		/* Check that command header fits. */
2259 		if (__predict_false(len < sizeof(*cmd)))
2260 			break;
2261 		cmd = (struct r92s_fw_cmd_hdr *)buf;
2262 		/* Check that command payload fits. */
2263 		cmdsz = le16toh(cmd->len);
2264 		if (__predict_false(len < sizeof(*cmd) + cmdsz))
2265 			break;
2266 
2267 		/* Process firmware event. */
2268 		rsu_rx_event(sc, cmd->code, (uint8_t *)&cmd[1], cmdsz);
2269 
2270 		if (!(cmd->seq & R92S_FW_CMD_MORE))
2271 			break;
2272 		buf += sizeof(*cmd) + cmdsz;
2273 		len -= sizeof(*cmd) + cmdsz;
2274 	}
2275 }
2276 
2277 static int8_t
2278 rsu_get_rssi(struct rsu_softc *sc, int rate, void *physt)
2279 {
2280 	static const int8_t cckoff[] = { 14, -2, -20, -40 };
2281 	struct r92s_rx_phystat *phy;
2282 	struct r92s_rx_cck *cck;
2283 	uint8_t rpt;
2284 	int8_t rssi;
2285 
2286 	if (rate <= 3) {
2287 		cck = (struct r92s_rx_cck *)physt;
2288 		rpt = (cck->agc_rpt >> 6) & 0x3;
2289 		rssi = cck->agc_rpt & 0x3e;
2290 		rssi = cckoff[rpt] - rssi;
2291 	} else {	/* OFDM/HT. */
2292 		phy = (struct r92s_rx_phystat *)physt;
2293 		rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 106;
2294 	}
2295 	return (rssi);
2296 }
2297 
2298 static struct mbuf *
2299 rsu_rx_copy_to_mbuf(struct rsu_softc *sc, struct r92s_rx_stat *stat,
2300     int totlen)
2301 {
2302 	struct ieee80211com *ic = &sc->sc_ic;
2303 	struct mbuf *m;
2304 	uint32_t rxdw0;
2305 	int pktlen;
2306 
2307 	rxdw0 = le32toh(stat->rxdw0);
2308 	if (__predict_false(rxdw0 & (R92S_RXDW0_CRCERR | R92S_RXDW0_ICVERR))) {
2309 		RSU_DPRINTF(sc, RSU_DEBUG_RX,
2310 		    "%s: RX flags error (%s)\n", __func__,
2311 		    rxdw0 & R92S_RXDW0_CRCERR ? "CRC" : "ICV");
2312 		goto fail;
2313 	}
2314 
2315 	pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN);
2316 	if (__predict_false(pktlen < sizeof (struct ieee80211_frame_ack))) {
2317 		RSU_DPRINTF(sc, RSU_DEBUG_RX,
2318 		    "%s: frame is too short: %d\n", __func__, pktlen);
2319 		goto fail;
2320 	}
2321 
2322 	m = m_get2(totlen, M_NOWAIT, MT_DATA, M_PKTHDR);
2323 	if (__predict_false(m == NULL)) {
2324 		device_printf(sc->sc_dev,
2325 		    "%s: could not allocate RX mbuf, totlen %d\n",
2326 		    __func__, totlen);
2327 		goto fail;
2328 	}
2329 
2330 	/* Finalize mbuf. */
2331 	memcpy(mtod(m, uint8_t *), (uint8_t *)stat, totlen);
2332 	m->m_pkthdr.len = m->m_len = totlen;
2333 
2334 	return (m);
2335 fail:
2336 	counter_u64_add(ic->ic_ierrors, 1);
2337 	return (NULL);
2338 }
2339 
2340 static uint32_t
2341 rsu_get_tsf_low(struct rsu_softc *sc)
2342 {
2343 	return (rsu_read_4(sc, R92S_TSFTR));
2344 }
2345 
2346 static uint32_t
2347 rsu_get_tsf_high(struct rsu_softc *sc)
2348 {
2349 	return (rsu_read_4(sc, R92S_TSFTR + 4));
2350 }
2351 
2352 static struct ieee80211_node *
2353 rsu_rx_frame(struct rsu_softc *sc, struct mbuf *m)
2354 {
2355 	struct ieee80211com *ic = &sc->sc_ic;
2356 	struct ieee80211_frame_min *wh;
2357 	struct ieee80211_rx_stats rxs;
2358 	struct r92s_rx_stat *stat;
2359 	uint32_t rxdw0, rxdw3;
2360 	uint8_t cipher, rate;
2361 	int infosz;
2362 	int rssi;
2363 
2364 	stat = mtod(m, struct r92s_rx_stat *);
2365 	rxdw0 = le32toh(stat->rxdw0);
2366 	rxdw3 = le32toh(stat->rxdw3);
2367 
2368 	rate = MS(rxdw3, R92S_RXDW3_RATE);
2369 	cipher = MS(rxdw0, R92S_RXDW0_CIPHER);
2370 	infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
2371 
2372 	/* Get RSSI from PHY status descriptor if present. */
2373 	if (infosz != 0 && (rxdw0 & R92S_RXDW0_PHYST))
2374 		rssi = rsu_get_rssi(sc, rate, &stat[1]);
2375 	else {
2376 		/* Cheat and get the last calibrated RSSI */
2377 		rssi = rsu_hwrssi_to_rssi(sc, sc->sc_currssi);
2378 	}
2379 
2380 	if (ieee80211_radiotap_active(ic)) {
2381 		struct rsu_rx_radiotap_header *tap = &sc->sc_rxtap;
2382 
2383 		/* Map HW rate index to 802.11 rate. */
2384 		tap->wr_flags = 0;		/* TODO */
2385 		tap->wr_tsft = rsu_get_tsf_high(sc);
2386 		if (le32toh(stat->tsf_low) > rsu_get_tsf_low(sc))
2387 			tap->wr_tsft--;
2388 		tap->wr_tsft = (uint64_t)htole32(tap->wr_tsft) << 32;
2389 		tap->wr_tsft += stat->tsf_low;
2390 
2391 		if (rate < 12) {
2392 			switch (rate) {
2393 			/* CCK. */
2394 			case  0: tap->wr_rate =   2; break;
2395 			case  1: tap->wr_rate =   4; break;
2396 			case  2: tap->wr_rate =  11; break;
2397 			case  3: tap->wr_rate =  22; break;
2398 			/* OFDM. */
2399 			case  4: tap->wr_rate =  12; break;
2400 			case  5: tap->wr_rate =  18; break;
2401 			case  6: tap->wr_rate =  24; break;
2402 			case  7: tap->wr_rate =  36; break;
2403 			case  8: tap->wr_rate =  48; break;
2404 			case  9: tap->wr_rate =  72; break;
2405 			case 10: tap->wr_rate =  96; break;
2406 			case 11: tap->wr_rate = 108; break;
2407 			}
2408 		} else {			/* MCS0~15. */
2409 			/* Bit 7 set means HT MCS instead of rate. */
2410 			tap->wr_rate = 0x80 | (rate - 12);
2411 		}
2412 
2413 		tap->wr_dbm_antsignal = rssi;
2414 		tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
2415 		tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
2416 	};
2417 
2418 	/* Hardware does Rx TCP checksum offload. */
2419 	/*
2420 	 * This flag can be set for some other
2421 	 * (e.g., EAPOL) frame types, so don't rely on it.
2422 	 */
2423 	if (rxdw3 & R92S_RXDW3_TCPCHKVALID) {
2424 		RSU_DPRINTF(sc, RSU_DEBUG_RX,
2425 		    "%s: TCP/IP checksums: %schecked / %schecked\n",
2426 		    __func__,
2427 		    (rxdw3 & R92S_RXDW3_TCPCHKRPT) ? "" : "not ",
2428 		    (rxdw3 & R92S_RXDW3_IPCHKRPT) ? "" : "not ");
2429 
2430 		/*
2431 		 * 'IP header checksum valid' bit will not be set if
2432 		 * the frame was not checked / has incorrect checksum /
2433 		 * does not have checksum (IPv6).
2434 		 *
2435 		 * NB: if DF bit is not set then frame will not be checked.
2436 		 */
2437 		if (rxdw3 & R92S_RXDW3_IPCHKRPT) {
2438 			m->m_pkthdr.csum_flags = CSUM_IP_CHECKED;
2439 			m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
2440 		}
2441 
2442 		/*
2443 		 * This is independent of the above check.
2444 		 */
2445 		if (rxdw3 & R92S_RXDW3_TCPCHKRPT) {
2446 			m->m_pkthdr.csum_flags |= CSUM_DATA_VALID;
2447 			m->m_pkthdr.csum_flags |= CSUM_PSEUDO_HDR;
2448 			m->m_pkthdr.csum_data = 0xffff;
2449 		}
2450 	}
2451 
2452 	/* RX flags */
2453 
2454 	/* Set channel flags for input path */
2455 	bzero(&rxs, sizeof(rxs));
2456 
2457 	/* normal RSSI */
2458 	rxs.r_flags |= IEEE80211_R_NF | IEEE80211_R_RSSI;
2459 	rxs.c_rssi = rssi;
2460 	rxs.c_nf = -96;
2461 
2462 	/* Rate */
2463 	if (!(rxdw3 & R92S_RXDW3_HTC)) {
2464 		switch (rate) {
2465 		/* CCK. */
2466 		case 0:
2467 			rxs.c_rate = 2;
2468 			rxs.c_pktflags |= IEEE80211_RX_F_CCK;
2469 			break;
2470 		case 1:
2471 			rxs.c_rate = 4;
2472 			rxs.c_pktflags |= IEEE80211_RX_F_CCK;
2473 			break;
2474 		case 2:
2475 			rxs.c_rate = 11;
2476 			rxs.c_pktflags |= IEEE80211_RX_F_CCK;
2477 			break;
2478 		case 3:
2479 			rxs.c_rate = 22;
2480 			rxs.c_pktflags |= IEEE80211_RX_F_CCK;
2481 			break;
2482 		/* OFDM. */
2483 		case 4:
2484 			rxs.c_rate = 12;
2485 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2486 			break;
2487 		case 5:
2488 			rxs.c_rate = 18;
2489 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2490 			break;
2491 		case 6:
2492 			rxs.c_rate = 24;
2493 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2494 			break;
2495 		case 7:
2496 			rxs.c_rate = 36;
2497 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2498 			break;
2499 		case 8:
2500 			rxs.c_rate = 48;
2501 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2502 			break;
2503 		case 9:
2504 			rxs.c_rate = 72;
2505 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2506 			break;
2507 		case 10:
2508 			rxs.c_rate = 96;
2509 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2510 			break;
2511 		case 11:
2512 			rxs.c_rate = 108;
2513 			rxs.c_pktflags |= IEEE80211_RX_F_OFDM;
2514 			break;
2515 		}
2516 	} else if (rate >= 12) {	/* MCS0~15. */
2517 		/* Bit 7 set means HT MCS instead of rate. */
2518 		rxs.c_rate = (rate - 12);
2519 		rxs.c_pktflags |= IEEE80211_RX_F_HT;
2520 	}
2521 
2522 	(void) ieee80211_add_rx_params(m, &rxs);
2523 
2524 	/* Drop descriptor. */
2525 	m_adj(m, sizeof(*stat) + infosz);
2526 	wh = mtod(m, struct ieee80211_frame_min *);
2527 	if ((wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
2528 	    cipher != R92S_KEY_ALGO_NONE) {
2529 		m->m_flags |= M_WEP;
2530 	}
2531 
2532 	RSU_DPRINTF(sc, RSU_DEBUG_RX,
2533 	    "%s: Rx frame len %d, rate %d, infosz %d\n",
2534 	    __func__, m->m_len, rate, infosz);
2535 
2536 	if (m->m_len >= sizeof(*wh))
2537 		return (ieee80211_find_rxnode(ic, wh));
2538 
2539 	return (NULL);
2540 }
2541 
2542 static struct mbuf *
2543 rsu_rx_multi_frame(struct rsu_softc *sc, uint8_t *buf, int len)
2544 {
2545 	struct r92s_rx_stat *stat;
2546 	uint32_t rxdw0;
2547 	int totlen, pktlen, infosz, npkts;
2548 	struct mbuf *m, *m0 = NULL, *prevm = NULL;
2549 
2550 	/*
2551 	 * don't pass packets to the ieee80211 framework if the driver isn't
2552 	 * RUNNING.
2553 	 */
2554 	if (!sc->sc_running)
2555 		return (NULL);
2556 
2557 	/* Get the number of encapsulated frames. */
2558 	stat = (struct r92s_rx_stat *)buf;
2559 	npkts = MS(le32toh(stat->rxdw2), R92S_RXDW2_PKTCNT);
2560 	RSU_DPRINTF(sc, RSU_DEBUG_RX,
2561 	    "%s: Rx %d frames in one chunk\n", __func__, npkts);
2562 
2563 	/* Process all of them. */
2564 	while (npkts-- > 0) {
2565 		if (__predict_false(len < sizeof(*stat)))
2566 			break;
2567 		stat = (struct r92s_rx_stat *)buf;
2568 		rxdw0 = le32toh(stat->rxdw0);
2569 
2570 		pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN);
2571 		if (__predict_false(pktlen == 0))
2572 			break;
2573 
2574 		infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
2575 
2576 		/* Make sure everything fits in xfer. */
2577 		totlen = sizeof(*stat) + infosz + pktlen;
2578 		if (__predict_false(totlen > len))
2579 			break;
2580 
2581 		/* Process 802.11 frame. */
2582 		m = rsu_rx_copy_to_mbuf(sc, stat, totlen);
2583 		if (m0 == NULL)
2584 			m0 = m;
2585 		if (prevm == NULL)
2586 			prevm = m;
2587 		else {
2588 			prevm->m_next = m;
2589 			prevm = m;
2590 		}
2591 		/* Next chunk is 128-byte aligned. */
2592 		totlen = (totlen + 127) & ~127;
2593 		buf += totlen;
2594 		len -= totlen;
2595 	}
2596 
2597 	return (m0);
2598 }
2599 
2600 static struct mbuf *
2601 rsu_rxeof(struct usb_xfer *xfer, struct rsu_data *data)
2602 {
2603 	struct rsu_softc *sc = data->sc;
2604 	struct ieee80211com *ic = &sc->sc_ic;
2605 	struct r92s_rx_stat *stat;
2606 	int len;
2607 
2608 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
2609 
2610 	if (__predict_false(len < sizeof(*stat))) {
2611 		RSU_DPRINTF(sc, RSU_DEBUG_RX, "xfer too short %d\n", len);
2612 		counter_u64_add(ic->ic_ierrors, 1);
2613 		return (NULL);
2614 	}
2615 	/* Determine if it is a firmware C2H event or an 802.11 frame. */
2616 	stat = (struct r92s_rx_stat *)data->buf;
2617 	if ((le32toh(stat->rxdw1) & 0x1ff) == 0x1ff) {
2618 		rsu_rx_multi_event(sc, data->buf, len);
2619 		/* No packets to process. */
2620 		return (NULL);
2621 	} else
2622 		return (rsu_rx_multi_frame(sc, data->buf, len));
2623 }
2624 
2625 static void
2626 rsu_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
2627 {
2628 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2629 	struct ieee80211com *ic = &sc->sc_ic;
2630 	struct ieee80211_node *ni;
2631 	struct mbuf *m = NULL, *next;
2632 	struct rsu_data *data;
2633 
2634 	RSU_ASSERT_LOCKED(sc);
2635 
2636 	switch (USB_GET_STATE(xfer)) {
2637 	case USB_ST_TRANSFERRED:
2638 		data = STAILQ_FIRST(&sc->sc_rx_active);
2639 		if (data == NULL)
2640 			goto tr_setup;
2641 		STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
2642 		m = rsu_rxeof(xfer, data);
2643 		STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
2644 		/* FALLTHROUGH */
2645 	case USB_ST_SETUP:
2646 tr_setup:
2647 		data = STAILQ_FIRST(&sc->sc_rx_inactive);
2648 		if (data == NULL) {
2649 			KASSERT(m == NULL, ("mbuf isn't NULL"));
2650 			return;
2651 		}
2652 		STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next);
2653 		STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next);
2654 		usbd_xfer_set_frame_data(xfer, 0, data->buf,
2655 		    usbd_xfer_max_len(xfer));
2656 		usbd_transfer_submit(xfer);
2657 		/*
2658 		 * To avoid LOR we should unlock our private mutex here to call
2659 		 * ieee80211_input() because here is at the end of a USB
2660 		 * callback and safe to unlock.
2661 		 */
2662 		while (m != NULL) {
2663 			next = m->m_next;
2664 			m->m_next = NULL;
2665 
2666 			ni = rsu_rx_frame(sc, m);
2667 			RSU_UNLOCK(sc);
2668 
2669 			if (ni != NULL) {
2670 				if (ni->ni_flags & IEEE80211_NODE_HT)
2671 					m->m_flags |= M_AMPDU;
2672 				(void)ieee80211_input_mimo(ni, m);
2673 				ieee80211_free_node(ni);
2674 			} else
2675 				(void)ieee80211_input_mimo_all(ic, m);
2676 
2677 			RSU_LOCK(sc);
2678 			m = next;
2679 		}
2680 		break;
2681 	default:
2682 		/* needs it to the inactive queue due to a error. */
2683 		data = STAILQ_FIRST(&sc->sc_rx_active);
2684 		if (data != NULL) {
2685 			STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
2686 			STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
2687 		}
2688 		if (error != USB_ERR_CANCELLED) {
2689 			usbd_xfer_set_stall(xfer);
2690 			counter_u64_add(ic->ic_ierrors, 1);
2691 			goto tr_setup;
2692 		}
2693 		break;
2694 	}
2695 
2696 }
2697 
2698 static void
2699 rsu_txeof(struct usb_xfer *xfer, struct rsu_data *data)
2700 {
2701 #ifdef	USB_DEBUG
2702 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2703 #endif
2704 
2705 	RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: called; data=%p\n",
2706 	    __func__,
2707 	    data);
2708 
2709 	if (data->m) {
2710 		/* XXX status? */
2711 		ieee80211_tx_complete(data->ni, data->m, 0);
2712 		data->m = NULL;
2713 		data->ni = NULL;
2714 	}
2715 }
2716 
2717 static void
2718 rsu_bulk_tx_callback_sub(struct usb_xfer *xfer, usb_error_t error,
2719     uint8_t which)
2720 {
2721 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2722 	struct ieee80211com *ic = &sc->sc_ic;
2723 	struct rsu_data *data;
2724 
2725 	RSU_ASSERT_LOCKED(sc);
2726 
2727 	switch (USB_GET_STATE(xfer)) {
2728 	case USB_ST_TRANSFERRED:
2729 		data = STAILQ_FIRST(&sc->sc_tx_active[which]);
2730 		if (data == NULL)
2731 			goto tr_setup;
2732 		RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: transfer done %p\n",
2733 		    __func__, data);
2734 		STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
2735 		rsu_txeof(xfer, data);
2736 		rsu_freebuf(sc, data);
2737 		/* FALLTHROUGH */
2738 	case USB_ST_SETUP:
2739 tr_setup:
2740 		data = STAILQ_FIRST(&sc->sc_tx_pending[which]);
2741 		if (data == NULL) {
2742 			RSU_DPRINTF(sc, RSU_DEBUG_TXDONE,
2743 			    "%s: empty pending queue sc %p\n", __func__, sc);
2744 			return;
2745 		}
2746 		STAILQ_REMOVE_HEAD(&sc->sc_tx_pending[which], next);
2747 		STAILQ_INSERT_TAIL(&sc->sc_tx_active[which], data, next);
2748 		usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen);
2749 		RSU_DPRINTF(sc, RSU_DEBUG_TXDONE,
2750 		    "%s: submitting transfer %p\n",
2751 		    __func__,
2752 		    data);
2753 		usbd_transfer_submit(xfer);
2754 		break;
2755 	default:
2756 		data = STAILQ_FIRST(&sc->sc_tx_active[which]);
2757 		if (data != NULL) {
2758 			STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
2759 			rsu_txeof(xfer, data);
2760 			rsu_freebuf(sc, data);
2761 		}
2762 		counter_u64_add(ic->ic_oerrors, 1);
2763 
2764 		if (error != USB_ERR_CANCELLED) {
2765 			usbd_xfer_set_stall(xfer);
2766 			goto tr_setup;
2767 		}
2768 		break;
2769 	}
2770 
2771 	/*
2772 	 * XXX TODO: if the queue is low, flush out FF TX frames.
2773 	 * Remember to unlock the driver for now; net80211 doesn't
2774 	 * defer it for us.
2775 	 */
2776 }
2777 
2778 static void
2779 rsu_bulk_tx_callback_be_bk(struct usb_xfer *xfer, usb_error_t error)
2780 {
2781 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2782 
2783 	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_BE_BK);
2784 
2785 	/* This kicks the TX taskqueue */
2786 	rsu_start(sc);
2787 }
2788 
2789 static void
2790 rsu_bulk_tx_callback_vi_vo(struct usb_xfer *xfer, usb_error_t error)
2791 {
2792 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2793 
2794 	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_VI_VO);
2795 
2796 	/* This kicks the TX taskqueue */
2797 	rsu_start(sc);
2798 }
2799 
2800 static void
2801 rsu_bulk_tx_callback_h2c(struct usb_xfer *xfer, usb_error_t error)
2802 {
2803 	struct rsu_softc *sc = usbd_xfer_softc(xfer);
2804 
2805 	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_H2C);
2806 
2807 	/* This kicks the TX taskqueue */
2808 	rsu_start(sc);
2809 }
2810 
2811 /*
2812  * Transmit the given frame.
2813  *
2814  * This doesn't free the node or mbuf upon failure.
2815  */
2816 static int
2817 rsu_tx_start(struct rsu_softc *sc, struct ieee80211_node *ni,
2818     struct mbuf *m0, struct rsu_data *data)
2819 {
2820 	struct ieee80211com *ic = &sc->sc_ic;
2821         struct ieee80211vap *vap = ni->ni_vap;
2822 	struct ieee80211_frame *wh;
2823 	struct ieee80211_key *k = NULL;
2824 	struct r92s_tx_desc *txd;
2825 	uint8_t type, cipher;
2826 	int prio = 0;
2827 	uint8_t which;
2828 	int hasqos;
2829 	int xferlen;
2830 	int qid;
2831 
2832 	RSU_ASSERT_LOCKED(sc);
2833 
2834 	wh = mtod(m0, struct ieee80211_frame *);
2835 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2836 
2837 	RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: data=%p, m=%p\n",
2838 	    __func__, data, m0);
2839 
2840 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
2841 		k = ieee80211_crypto_encap(ni, m0);
2842 		if (k == NULL) {
2843 			device_printf(sc->sc_dev,
2844 			    "ieee80211_crypto_encap returns NULL.\n");
2845 			/* XXX we don't expect the fragmented frames */
2846 			return (ENOBUFS);
2847 		}
2848 		wh = mtod(m0, struct ieee80211_frame *);
2849 	}
2850 	/* If we have QoS then use it */
2851 	/* XXX TODO: mbuf WME/PRI versus TID? */
2852 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
2853 		/* Has QoS */
2854 		prio = M_WME_GETAC(m0);
2855 		which = rsu_wme_ac_xfer_map[prio];
2856 		hasqos = 1;
2857 	} else {
2858 		/* Non-QoS TID */
2859 		/* XXX TODO: tid=0 for non-qos TID? */
2860 		which = rsu_wme_ac_xfer_map[WME_AC_BE];
2861 		hasqos = 0;
2862 		prio = 0;
2863 	}
2864 
2865 	qid = rsu_ac2qid[prio];
2866 #if 0
2867 	switch (type) {
2868 	case IEEE80211_FC0_TYPE_CTL:
2869 	case IEEE80211_FC0_TYPE_MGT:
2870 		which = rsu_wme_ac_xfer_map[WME_AC_VO];
2871 		break;
2872 	default:
2873 		which = rsu_wme_ac_xfer_map[M_WME_GETAC(m0)];
2874 		break;
2875 	}
2876 	hasqos = 0;
2877 #endif
2878 
2879 	RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: pri=%d, which=%d, hasqos=%d\n",
2880 	    __func__,
2881 	    prio,
2882 	    which,
2883 	    hasqos);
2884 
2885 	/* Fill Tx descriptor. */
2886 	txd = (struct r92s_tx_desc *)data->buf;
2887 	memset(txd, 0, sizeof(*txd));
2888 
2889 	txd->txdw0 |= htole32(
2890 	    SM(R92S_TXDW0_PKTLEN, m0->m_pkthdr.len) |
2891 	    SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
2892 	    R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
2893 
2894 	txd->txdw1 |= htole32(
2895 	    SM(R92S_TXDW1_MACID, R92S_MACID_BSS) | SM(R92S_TXDW1_QSEL, qid));
2896 	if (!hasqos)
2897 		txd->txdw1 |= htole32(R92S_TXDW1_NONQOS);
2898 	if (k != NULL && !(k->wk_flags & IEEE80211_KEY_SWENCRYPT)) {
2899 		switch (k->wk_cipher->ic_cipher) {
2900 		case IEEE80211_CIPHER_WEP:
2901 			cipher = R92S_TXDW1_CIPHER_WEP;
2902 			break;
2903 		case IEEE80211_CIPHER_TKIP:
2904 			cipher = R92S_TXDW1_CIPHER_TKIP;
2905 			break;
2906 		case IEEE80211_CIPHER_AES_CCM:
2907 			cipher = R92S_TXDW1_CIPHER_AES;
2908 			break;
2909 		default:
2910 			cipher = R92S_TXDW1_CIPHER_NONE;
2911 		}
2912 		txd->txdw1 |= htole32(
2913 		    SM(R92S_TXDW1_CIPHER, cipher) |
2914 		    SM(R92S_TXDW1_KEYIDX, k->wk_keyix));
2915 	}
2916 	/* XXX todo: set AGGEN bit if appropriate? */
2917 	txd->txdw2 |= htole32(R92S_TXDW2_BK);
2918 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
2919 		txd->txdw2 |= htole32(R92S_TXDW2_BMCAST);
2920 	/*
2921 	 * Firmware will use and increment the sequence number for the
2922 	 * specified priority.
2923 	 */
2924 	txd->txdw3 |= htole32(SM(R92S_TXDW3_SEQ, prio));
2925 
2926 	if (ieee80211_radiotap_active_vap(vap)) {
2927 		struct rsu_tx_radiotap_header *tap = &sc->sc_txtap;
2928 
2929 		tap->wt_flags = 0;
2930 		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
2931 		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
2932 		ieee80211_radiotap_tx(vap, m0);
2933 	}
2934 
2935 	xferlen = sizeof(*txd) + m0->m_pkthdr.len;
2936 	m_copydata(m0, 0, m0->m_pkthdr.len, (caddr_t)&txd[1]);
2937 
2938 	data->buflen = xferlen;
2939 	data->ni = ni;
2940 	data->m = m0;
2941 	STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
2942 
2943 	/* start transfer, if any */
2944 	usbd_transfer_start(sc->sc_xfer[which]);
2945 	return (0);
2946 }
2947 
2948 static int
2949 rsu_transmit(struct ieee80211com *ic, struct mbuf *m)
2950 {
2951 	struct rsu_softc *sc = ic->ic_softc;
2952 	int error;
2953 
2954 	RSU_LOCK(sc);
2955 	if (!sc->sc_running) {
2956 		RSU_UNLOCK(sc);
2957 		return (ENXIO);
2958 	}
2959 
2960 	/*
2961 	 * XXX TODO: ensure that we treat 'm' as a list of frames
2962 	 * to transmit!
2963 	 */
2964 	error = mbufq_enqueue(&sc->sc_snd, m);
2965 	if (error) {
2966 		RSU_DPRINTF(sc, RSU_DEBUG_TX,
2967 		    "%s: mbufq_enable: failed (%d)\n",
2968 		    __func__,
2969 		    error);
2970 		RSU_UNLOCK(sc);
2971 		return (error);
2972 	}
2973 	RSU_UNLOCK(sc);
2974 
2975 	/* This kicks the TX taskqueue */
2976 	rsu_start(sc);
2977 
2978 	return (0);
2979 }
2980 
2981 static void
2982 rsu_drain_mbufq(struct rsu_softc *sc)
2983 {
2984 	struct mbuf *m;
2985 	struct ieee80211_node *ni;
2986 
2987 	RSU_ASSERT_LOCKED(sc);
2988 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
2989 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
2990 		m->m_pkthdr.rcvif = NULL;
2991 		ieee80211_free_node(ni);
2992 		m_freem(m);
2993 	}
2994 }
2995 
2996 static void
2997 _rsu_start(struct rsu_softc *sc)
2998 {
2999 	struct ieee80211_node *ni;
3000 	struct rsu_data *bf;
3001 	struct mbuf *m;
3002 
3003 	RSU_ASSERT_LOCKED(sc);
3004 
3005 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
3006 		bf = rsu_getbuf(sc);
3007 		if (bf == NULL) {
3008 			RSU_DPRINTF(sc, RSU_DEBUG_TX,
3009 			    "%s: failed to get buffer\n", __func__);
3010 			mbufq_prepend(&sc->sc_snd, m);
3011 			break;
3012 		}
3013 
3014 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
3015 		m->m_pkthdr.rcvif = NULL;
3016 
3017 		if (rsu_tx_start(sc, ni, m, bf) != 0) {
3018 			RSU_DPRINTF(sc, RSU_DEBUG_TX,
3019 			    "%s: failed to transmit\n", __func__);
3020 			if_inc_counter(ni->ni_vap->iv_ifp,
3021 			    IFCOUNTER_OERRORS, 1);
3022 			rsu_freebuf(sc, bf);
3023 			ieee80211_free_node(ni);
3024 			m_freem(m);
3025 			break;
3026 		}
3027 	}
3028 }
3029 
3030 static void
3031 rsu_start(struct rsu_softc *sc)
3032 {
3033 
3034 	taskqueue_enqueue(taskqueue_thread, &sc->tx_task);
3035 }
3036 
3037 static int
3038 rsu_ioctl_net(struct ieee80211com *ic, u_long cmd, void *data)
3039 {
3040 	struct rsu_softc *sc = ic->ic_softc;
3041 	struct ifreq *ifr = (struct ifreq *)data;
3042 	int error;
3043 
3044 	error = 0;
3045 	switch (cmd) {
3046 	case SIOCSIFCAP:
3047 	{
3048 		struct ieee80211vap *vap;
3049 		int rxmask;
3050 
3051 		rxmask = ifr->ifr_reqcap & (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6);
3052 
3053 		RSU_LOCK(sc);
3054 		/* Both RXCSUM bits must be set (or unset). */
3055 		if (sc->sc_rx_checksum_enable &&
3056 		    rxmask != (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6)) {
3057 			rxmask = 0;
3058 			sc->sc_rx_checksum_enable = 0;
3059 			rsu_rxfilter_set(sc, R92S_RCR_TCP_OFFLD_EN, 0);
3060 		} else if (!sc->sc_rx_checksum_enable && rxmask != 0) {
3061 			rxmask = IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6;
3062 			sc->sc_rx_checksum_enable = 1;
3063 			rsu_rxfilter_set(sc, 0, R92S_RCR_TCP_OFFLD_EN);
3064 		} else {
3065 			/* Nothing to do. */
3066 			RSU_UNLOCK(sc);
3067 			break;
3068 		}
3069 		RSU_UNLOCK(sc);
3070 
3071 		IEEE80211_LOCK(ic);	/* XXX */
3072 		TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
3073 			struct ifnet *ifp = vap->iv_ifp;
3074 
3075 			ifp->if_capenable &=
3076 			    ~(IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6);
3077 			ifp->if_capenable |= rxmask;
3078 		}
3079 		IEEE80211_UNLOCK(ic);
3080 		break;
3081 	}
3082 	default:
3083 		error = ENOTTY;		/* for net80211 */
3084 		break;
3085 	}
3086 
3087 	return (error);
3088 }
3089 
3090 static void
3091 rsu_parent(struct ieee80211com *ic)
3092 {
3093 	struct rsu_softc *sc = ic->ic_softc;
3094 
3095 	if (ic->ic_nrunning > 0) {
3096 		if (rsu_init(sc) == 0)
3097 			ieee80211_start_all(ic);
3098 		else {
3099 			struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3100 			if (vap != NULL)
3101 				ieee80211_stop(vap);
3102 		}
3103 	} else
3104 		rsu_stop(sc);
3105 }
3106 
3107 /*
3108  * Power on sequence for A-cut adapters.
3109  */
3110 static void
3111 rsu_power_on_acut(struct rsu_softc *sc)
3112 {
3113 	uint32_t reg;
3114 
3115 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
3116 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
3117 
3118 	/* Enable AFE macro block's bandgap and Mbias. */
3119 	rsu_write_1(sc, R92S_AFE_MISC,
3120 	    rsu_read_1(sc, R92S_AFE_MISC) |
3121 	    R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN);
3122 	/* Enable LDOA15 block. */
3123 	rsu_write_1(sc, R92S_LDOA15_CTRL,
3124 	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
3125 
3126 	rsu_write_1(sc, R92S_SPS1_CTRL,
3127 	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_LDEN);
3128 	rsu_ms_delay(sc, 2000);
3129 	/* Enable switch regulator block. */
3130 	rsu_write_1(sc, R92S_SPS1_CTRL,
3131 	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_SWEN);
3132 
3133 	rsu_write_4(sc, R92S_SPS1_CTRL, 0x00a7b267);
3134 
3135 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3136 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
3137 
3138 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3139 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
3140 
3141 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3142 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x90);
3143 
3144 	/* Enable AFE clock. */
3145 	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
3146 	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
3147 	/* Enable AFE PLL macro block. */
3148 	rsu_write_1(sc, R92S_AFE_PLL_CTRL,
3149 	    rsu_read_1(sc, R92S_AFE_PLL_CTRL) | 0x11);
3150 	/* Attach AFE PLL to MACTOP/BB. */
3151 	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
3152 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
3153 
3154 	/* Switch to 40MHz clock instead of 80MHz. */
3155 	rsu_write_2(sc, R92S_SYS_CLKR,
3156 	    rsu_read_2(sc, R92S_SYS_CLKR) & ~R92S_SYS_CLKSEL);
3157 
3158 	/* Enable MAC clock. */
3159 	rsu_write_2(sc, R92S_SYS_CLKR,
3160 	    rsu_read_2(sc, R92S_SYS_CLKR) |
3161 	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
3162 
3163 	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
3164 
3165 	/* Enable digital core and IOREG R/W. */
3166 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3167 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
3168 
3169 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3170 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
3171 
3172 	/* Switch the control path to firmware. */
3173 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
3174 	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
3175 	rsu_write_2(sc, R92S_SYS_CLKR, reg);
3176 
3177 	rsu_write_2(sc, R92S_CR, 0x37fc);
3178 
3179 	/* Fix USB RX FIFO issue. */
3180 	rsu_write_1(sc, 0xfe5c,
3181 	    rsu_read_1(sc, 0xfe5c) | 0x80);
3182 	rsu_write_1(sc, 0x00ab,
3183 	    rsu_read_1(sc, 0x00ab) | 0xc0);
3184 
3185 	rsu_write_1(sc, R92S_SYS_CLKR,
3186 	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
3187 }
3188 
3189 /*
3190  * Power on sequence for B-cut and C-cut adapters.
3191  */
3192 static void
3193 rsu_power_on_bcut(struct rsu_softc *sc)
3194 {
3195 	uint32_t reg;
3196 	int ntries;
3197 
3198 	/* Prevent eFuse leakage. */
3199 	rsu_write_1(sc, 0x37, 0xb0);
3200 	rsu_ms_delay(sc, 10);
3201 	rsu_write_1(sc, 0x37, 0x30);
3202 
3203 	/* Switch the control path to hardware. */
3204 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
3205 	if (reg & R92S_FWHW_SEL) {
3206 		rsu_write_2(sc, R92S_SYS_CLKR,
3207 		    reg & ~(R92S_SWHW_SEL | R92S_FWHW_SEL));
3208 	}
3209 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3210 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) & ~0x8c);
3211 	rsu_ms_delay(sc, 1);
3212 
3213 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
3214 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
3215 
3216 	reg = rsu_read_1(sc, R92S_AFE_MISC);
3217 	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN);
3218 	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN |
3219 	    R92S_AFE_MISC_MBEN | R92S_AFE_MISC_I32_EN);
3220 
3221 	/* Enable PLL. */
3222 	rsu_write_1(sc, R92S_LDOA15_CTRL,
3223 	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
3224 
3225 	rsu_write_1(sc, R92S_LDOV12D_CTRL,
3226 	    rsu_read_1(sc, R92S_LDOV12D_CTRL) | R92S_LDV12_EN);
3227 
3228 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3229 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
3230 
3231 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3232 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
3233 
3234 	/* Support 64KB IMEM. */
3235 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
3236 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x97);
3237 
3238 	/* Enable AFE clock. */
3239 	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
3240 	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
3241 	/* Enable AFE PLL macro block. */
3242 	reg = rsu_read_1(sc, R92S_AFE_PLL_CTRL);
3243 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
3244 	rsu_ms_delay(sc, 1);
3245 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x51);
3246 	rsu_ms_delay(sc, 1);
3247 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
3248 	rsu_ms_delay(sc, 1);
3249 
3250 	/* Attach AFE PLL to MACTOP/BB. */
3251 	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
3252 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
3253 
3254 	/* Switch to 40MHz clock. */
3255 	rsu_write_1(sc, R92S_SYS_CLKR, 0x00);
3256 	/* Disable CPU clock and 80MHz SSC. */
3257 	rsu_write_1(sc, R92S_SYS_CLKR,
3258 	    rsu_read_1(sc, R92S_SYS_CLKR) | 0xa0);
3259 	/* Enable MAC clock. */
3260 	rsu_write_2(sc, R92S_SYS_CLKR,
3261 	    rsu_read_2(sc, R92S_SYS_CLKR) |
3262 	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
3263 
3264 	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
3265 
3266 	/* Enable digital core and IOREG R/W. */
3267 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3268 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
3269 
3270 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
3271 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
3272 
3273 	/* Switch the control path to firmware. */
3274 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
3275 	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
3276 	rsu_write_2(sc, R92S_SYS_CLKR, reg);
3277 
3278 	rsu_write_2(sc, R92S_CR, 0x37fc);
3279 
3280 	/* Fix USB RX FIFO issue. */
3281 	rsu_write_1(sc, 0xfe5c,
3282 	    rsu_read_1(sc, 0xfe5c) | 0x80);
3283 
3284 	rsu_write_1(sc, R92S_SYS_CLKR,
3285 	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
3286 
3287 	rsu_write_1(sc, 0xfe1c, 0x80);
3288 
3289 	/* Make sure TxDMA is ready to download firmware. */
3290 	for (ntries = 0; ntries < 20; ntries++) {
3291 		reg = rsu_read_1(sc, R92S_TCR);
3292 		if ((reg & (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) ==
3293 		    (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT))
3294 			break;
3295 		rsu_ms_delay(sc, 1);
3296 	}
3297 	if (ntries == 20) {
3298 		RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_TX,
3299 		    "%s: TxDMA is not ready\n",
3300 		    __func__);
3301 		/* Reset TxDMA. */
3302 		reg = rsu_read_1(sc, R92S_CR);
3303 		rsu_write_1(sc, R92S_CR, reg & ~R92S_CR_TXDMA_EN);
3304 		rsu_ms_delay(sc, 1);
3305 		rsu_write_1(sc, R92S_CR, reg | R92S_CR_TXDMA_EN);
3306 	}
3307 }
3308 
3309 static void
3310 rsu_power_off(struct rsu_softc *sc)
3311 {
3312 	/* Turn RF off. */
3313 	rsu_write_1(sc, R92S_RF_CTRL, 0x00);
3314 	rsu_ms_delay(sc, 5);
3315 
3316 	/* Turn MAC off. */
3317 	/* Switch control path. */
3318 	rsu_write_1(sc, R92S_SYS_CLKR + 1, 0x38);
3319 	/* Reset MACTOP. */
3320 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x70);
3321 	rsu_write_1(sc, R92S_PMC_FSM, 0x06);
3322 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 0, 0xf9);
3323 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, 0xe8);
3324 
3325 	/* Disable AFE PLL. */
3326 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, 0x00);
3327 	/* Disable A15V. */
3328 	rsu_write_1(sc, R92S_LDOA15_CTRL, 0x54);
3329 	/* Disable eFuse 1.2V. */
3330 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x50);
3331 	rsu_write_1(sc, R92S_LDOV12D_CTRL, 0x24);
3332 	/* Enable AFE macro block's bandgap and Mbias. */
3333 	rsu_write_1(sc, R92S_AFE_MISC, 0x30);
3334 	/* Disable 1.6V LDO. */
3335 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x56);
3336 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x43);
3337 
3338 	/* Firmware - tell it to switch things off */
3339 	(void) rsu_set_fw_power_state(sc, RSU_PWR_OFF);
3340 }
3341 
3342 static int
3343 rsu_fw_loadsection(struct rsu_softc *sc, const uint8_t *buf, int len)
3344 {
3345 	const uint8_t which = rsu_wme_ac_xfer_map[WME_AC_VO];
3346 	struct rsu_data *data;
3347 	struct r92s_tx_desc *txd;
3348 	int mlen;
3349 
3350 	while (len > 0) {
3351 		data = rsu_getbuf(sc);
3352 		if (data == NULL)
3353 			return (ENOMEM);
3354 		txd = (struct r92s_tx_desc *)data->buf;
3355 		memset(txd, 0, sizeof(*txd));
3356 		if (len <= RSU_TXBUFSZ - sizeof(*txd)) {
3357 			/* Last chunk. */
3358 			txd->txdw0 |= htole32(R92S_TXDW0_LINIP);
3359 			mlen = len;
3360 		} else
3361 			mlen = RSU_TXBUFSZ - sizeof(*txd);
3362 		txd->txdw0 |= htole32(SM(R92S_TXDW0_PKTLEN, mlen));
3363 		memcpy(&txd[1], buf, mlen);
3364 		data->buflen = sizeof(*txd) + mlen;
3365 		RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FW | RSU_DEBUG_RESET,
3366 		    "%s: starting transfer %p\n",
3367 		    __func__, data);
3368 		STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
3369 		buf += mlen;
3370 		len -= mlen;
3371 	}
3372 	usbd_transfer_start(sc->sc_xfer[which]);
3373 	return (0);
3374 }
3375 
3376 static int
3377 rsu_load_firmware(struct rsu_softc *sc)
3378 {
3379 	const struct r92s_fw_hdr *hdr;
3380 	struct r92s_fw_priv *dmem;
3381 	struct ieee80211com *ic = &sc->sc_ic;
3382 	const uint8_t *imem, *emem;
3383 	int imemsz, ememsz;
3384 	const struct firmware *fw;
3385 	size_t size;
3386 	uint32_t reg;
3387 	int ntries, error;
3388 
3389 	if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY) {
3390 		RSU_DPRINTF(sc, RSU_DEBUG_ANY,
3391 		    "%s: Firmware already loaded\n",
3392 		    __func__);
3393 		return (0);
3394 	}
3395 
3396 	RSU_UNLOCK(sc);
3397 	/* Read firmware image from the filesystem. */
3398 	if ((fw = firmware_get("rsu-rtl8712fw")) == NULL) {
3399 		device_printf(sc->sc_dev,
3400 		    "%s: failed load firmware of file rsu-rtl8712fw\n",
3401 		    __func__);
3402 		RSU_LOCK(sc);
3403 		return (ENXIO);
3404 	}
3405 	RSU_LOCK(sc);
3406 	size = fw->datasize;
3407 	if (size < sizeof(*hdr)) {
3408 		device_printf(sc->sc_dev, "firmware too short\n");
3409 		error = EINVAL;
3410 		goto fail;
3411 	}
3412 	hdr = (const struct r92s_fw_hdr *)fw->data;
3413 	if (hdr->signature != htole16(0x8712) &&
3414 	    hdr->signature != htole16(0x8192)) {
3415 		device_printf(sc->sc_dev,
3416 		    "invalid firmware signature 0x%x\n",
3417 		    le16toh(hdr->signature));
3418 		error = EINVAL;
3419 		goto fail;
3420 	}
3421 	RSU_DPRINTF(sc, RSU_DEBUG_FW, "FW V%d %02x-%02x %02x:%02x\n",
3422 	    le16toh(hdr->version), hdr->month, hdr->day, hdr->hour,
3423 	    hdr->minute);
3424 
3425 	/* Make sure that driver and firmware are in sync. */
3426 	if (hdr->privsz != htole32(sizeof(*dmem))) {
3427 		device_printf(sc->sc_dev, "unsupported firmware image\n");
3428 		error = EINVAL;
3429 		goto fail;
3430 	}
3431 	/* Get FW sections sizes. */
3432 	imemsz = le32toh(hdr->imemsz);
3433 	ememsz = le32toh(hdr->sramsz);
3434 	/* Check that all FW sections fit in image. */
3435 	if (size < sizeof(*hdr) + imemsz + ememsz) {
3436 		device_printf(sc->sc_dev, "firmware too short\n");
3437 		error = EINVAL;
3438 		goto fail;
3439 	}
3440 	imem = (const uint8_t *)&hdr[1];
3441 	emem = imem + imemsz;
3442 
3443 	/* Load IMEM section. */
3444 	error = rsu_fw_loadsection(sc, imem, imemsz);
3445 	if (error != 0) {
3446 		device_printf(sc->sc_dev,
3447 		    "could not load firmware section %s\n", "IMEM");
3448 		goto fail;
3449 	}
3450 	/* Wait for load to complete. */
3451 	for (ntries = 0; ntries != 50; ntries++) {
3452 		rsu_ms_delay(sc, 10);
3453 		reg = rsu_read_1(sc, R92S_TCR);
3454 		if (reg & R92S_TCR_IMEM_CODE_DONE)
3455 			break;
3456 	}
3457 	if (ntries == 50) {
3458 		device_printf(sc->sc_dev, "timeout waiting for IMEM transfer\n");
3459 		error = ETIMEDOUT;
3460 		goto fail;
3461 	}
3462 	/* Load EMEM section. */
3463 	error = rsu_fw_loadsection(sc, emem, ememsz);
3464 	if (error != 0) {
3465 		device_printf(sc->sc_dev,
3466 		    "could not load firmware section %s\n", "EMEM");
3467 		goto fail;
3468 	}
3469 	/* Wait for load to complete. */
3470 	for (ntries = 0; ntries != 50; ntries++) {
3471 		rsu_ms_delay(sc, 10);
3472 		reg = rsu_read_2(sc, R92S_TCR);
3473 		if (reg & R92S_TCR_EMEM_CODE_DONE)
3474 			break;
3475 	}
3476 	if (ntries == 50) {
3477 		device_printf(sc->sc_dev, "timeout waiting for EMEM transfer\n");
3478 		error = ETIMEDOUT;
3479 		goto fail;
3480 	}
3481 	/* Enable CPU. */
3482 	rsu_write_1(sc, R92S_SYS_CLKR,
3483 	    rsu_read_1(sc, R92S_SYS_CLKR) | R92S_SYS_CPU_CLKSEL);
3484 	if (!(rsu_read_1(sc, R92S_SYS_CLKR) & R92S_SYS_CPU_CLKSEL)) {
3485 		device_printf(sc->sc_dev, "could not enable system clock\n");
3486 		error = EIO;
3487 		goto fail;
3488 	}
3489 	rsu_write_2(sc, R92S_SYS_FUNC_EN,
3490 	    rsu_read_2(sc, R92S_SYS_FUNC_EN) | R92S_FEN_CPUEN);
3491 	if (!(rsu_read_2(sc, R92S_SYS_FUNC_EN) & R92S_FEN_CPUEN)) {
3492 		device_printf(sc->sc_dev,
3493 		    "could not enable microcontroller\n");
3494 		error = EIO;
3495 		goto fail;
3496 	}
3497 	/* Wait for CPU to initialize. */
3498 	for (ntries = 0; ntries < 100; ntries++) {
3499 		if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_IMEM_RDY)
3500 			break;
3501 		rsu_ms_delay(sc, 1);
3502 	}
3503 	if (ntries == 100) {
3504 		device_printf(sc->sc_dev,
3505 		    "timeout waiting for microcontroller\n");
3506 		error = ETIMEDOUT;
3507 		goto fail;
3508 	}
3509 
3510 	/* Update DMEM section before loading. */
3511 	dmem = __DECONST(struct r92s_fw_priv *, &hdr->priv);
3512 	memset(dmem, 0, sizeof(*dmem));
3513 	dmem->hci_sel = R92S_HCI_SEL_USB | R92S_HCI_SEL_8172;
3514 	dmem->nendpoints = sc->sc_nendpoints;
3515 	dmem->chip_version = sc->cut;
3516 	dmem->rf_config = sc->sc_rftype;
3517 	dmem->vcs_type = R92S_VCS_TYPE_AUTO;
3518 	dmem->vcs_mode = R92S_VCS_MODE_RTS_CTS;
3519 	dmem->turbo_mode = 0;
3520 	dmem->bw40_en = !! (ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40);
3521 	dmem->amsdu2ampdu_en = !! (sc->sc_ht);
3522 	dmem->ampdu_en = !! (sc->sc_ht);
3523 	dmem->agg_offload = !! (sc->sc_ht);
3524 	dmem->qos_en = 1;
3525 	dmem->ps_offload = 1;
3526 	dmem->lowpower_mode = 1;	/* XXX TODO: configurable? */
3527 	/* Load DMEM section. */
3528 	error = rsu_fw_loadsection(sc, (uint8_t *)dmem, sizeof(*dmem));
3529 	if (error != 0) {
3530 		device_printf(sc->sc_dev,
3531 		    "could not load firmware section %s\n", "DMEM");
3532 		goto fail;
3533 	}
3534 	/* Wait for load to complete. */
3535 	for (ntries = 0; ntries < 100; ntries++) {
3536 		if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_DMEM_CODE_DONE)
3537 			break;
3538 		rsu_ms_delay(sc, 1);
3539 	}
3540 	if (ntries == 100) {
3541 		device_printf(sc->sc_dev, "timeout waiting for %s transfer\n",
3542 		    "DMEM");
3543 		error = ETIMEDOUT;
3544 		goto fail;
3545 	}
3546 	/* Wait for firmware readiness. */
3547 	for (ntries = 0; ntries < 60; ntries++) {
3548 		if (!(rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY))
3549 			break;
3550 		rsu_ms_delay(sc, 1);
3551 	}
3552 	if (ntries == 60) {
3553 		device_printf(sc->sc_dev,
3554 		    "timeout waiting for firmware readiness\n");
3555 		error = ETIMEDOUT;
3556 		goto fail;
3557 	}
3558  fail:
3559 	firmware_put(fw, FIRMWARE_UNLOAD);
3560 	return (error);
3561 }
3562 
3563 
3564 static int
3565 rsu_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
3566     const struct ieee80211_bpf_params *params)
3567 {
3568 	struct ieee80211com *ic = ni->ni_ic;
3569 	struct rsu_softc *sc = ic->ic_softc;
3570 	struct rsu_data *bf;
3571 
3572 	/* prevent management frames from being sent if we're not ready */
3573 	if (!sc->sc_running) {
3574 		m_freem(m);
3575 		return (ENETDOWN);
3576 	}
3577 	RSU_LOCK(sc);
3578 	bf = rsu_getbuf(sc);
3579 	if (bf == NULL) {
3580 		m_freem(m);
3581 		RSU_UNLOCK(sc);
3582 		return (ENOBUFS);
3583 	}
3584 	if (rsu_tx_start(sc, ni, m, bf) != 0) {
3585 		m_freem(m);
3586 		rsu_freebuf(sc, bf);
3587 		RSU_UNLOCK(sc);
3588 		return (EIO);
3589 	}
3590 	RSU_UNLOCK(sc);
3591 
3592 	return (0);
3593 }
3594 
3595 static void
3596 rsu_rxfilter_init(struct rsu_softc *sc)
3597 {
3598 	uint32_t reg;
3599 
3600 	RSU_ASSERT_LOCKED(sc);
3601 
3602 	/* Setup multicast filter. */
3603 	rsu_set_multi(sc);
3604 
3605 	/* Adjust Rx filter. */
3606 	reg = rsu_read_4(sc, R92S_RCR);
3607 	reg &= ~R92S_RCR_AICV;
3608 	reg |= R92S_RCR_APP_PHYSTS;
3609 	if (sc->sc_rx_checksum_enable)
3610 		reg |= R92S_RCR_TCP_OFFLD_EN;
3611 	rsu_write_4(sc, R92S_RCR, reg);
3612 
3613 	/* Update dynamic Rx filter parts. */
3614 	rsu_rxfilter_refresh(sc);
3615 }
3616 
3617 static void
3618 rsu_rxfilter_set(struct rsu_softc *sc, uint32_t clear, uint32_t set)
3619 {
3620 	/* NB: firmware can touch this register too. */
3621 	rsu_write_4(sc, R92S_RCR,
3622 	   (rsu_read_4(sc, R92S_RCR) & ~clear) | set);
3623 }
3624 
3625 static void
3626 rsu_rxfilter_refresh(struct rsu_softc *sc)
3627 {
3628 	struct ieee80211com *ic = &sc->sc_ic;
3629 	uint32_t mask_all, mask_min;
3630 
3631 	RSU_ASSERT_LOCKED(sc);
3632 
3633 	/* NB: RCR_AMF / RXFLTMAP_MGT are used by firmware. */
3634 	mask_all = R92S_RCR_ACF | R92S_RCR_AAP;
3635 	mask_min = R92S_RCR_APM;
3636 	if (sc->sc_vap_is_running)
3637 		mask_min |= R92S_RCR_CBSSID;
3638 	else
3639 		mask_all |= R92S_RCR_ADF;
3640 
3641 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
3642 		uint16_t rxfltmap;
3643 		if (sc->sc_vap_is_running)
3644 			rxfltmap = 0;
3645 		else
3646 			rxfltmap = R92S_RXFLTMAP_MGT_DEF;
3647 		rsu_write_2(sc, R92S_RXFLTMAP_MGT, rxfltmap);
3648 	}
3649 
3650 	if (ic->ic_promisc == 0 && ic->ic_opmode != IEEE80211_M_MONITOR)
3651 		rsu_rxfilter_set(sc, mask_all, mask_min);
3652 	else
3653 		rsu_rxfilter_set(sc, mask_min, mask_all);
3654 }
3655 
3656 static int
3657 rsu_init(struct rsu_softc *sc)
3658 {
3659 	struct ieee80211com *ic = &sc->sc_ic;
3660 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3661 	uint8_t macaddr[IEEE80211_ADDR_LEN];
3662 	int error;
3663 	int i;
3664 
3665 	RSU_LOCK(sc);
3666 
3667 	if (sc->sc_running) {
3668 		RSU_UNLOCK(sc);
3669 		return (0);
3670 	}
3671 
3672 	/* Ensure the mbuf queue is drained */
3673 	rsu_drain_mbufq(sc);
3674 
3675 	/* Reset power management state. */
3676 	rsu_write_1(sc, R92S_USB_HRPWM, 0);
3677 
3678 	/* Power on adapter. */
3679 	if (sc->cut == 1)
3680 		rsu_power_on_acut(sc);
3681 	else
3682 		rsu_power_on_bcut(sc);
3683 
3684 	/* Load firmware. */
3685 	error = rsu_load_firmware(sc);
3686 	if (error != 0)
3687 		goto fail;
3688 
3689 	rsu_write_4(sc, R92S_CR,
3690 	    rsu_read_4(sc, R92S_CR) & ~0xff000000);
3691 
3692 	/* Use 128 bytes pages. */
3693 	rsu_write_1(sc, 0x00b5,
3694 	    rsu_read_1(sc, 0x00b5) | 0x01);
3695 	/* Enable USB Rx aggregation. */
3696 	rsu_write_1(sc, 0x00bd,
3697 	    rsu_read_1(sc, 0x00bd) | 0x80);
3698 	/* Set USB Rx aggregation threshold. */
3699 	rsu_write_1(sc, 0x00d9, 0x01);
3700 	/* Set USB Rx aggregation timeout (1.7ms/4). */
3701 	rsu_write_1(sc, 0xfe5b, 0x04);
3702 	/* Fix USB Rx FIFO issue. */
3703 	rsu_write_1(sc, 0xfe5c,
3704 	    rsu_read_1(sc, 0xfe5c) | 0x80);
3705 
3706 	/* Set MAC address. */
3707 	IEEE80211_ADDR_COPY(macaddr, vap ? vap->iv_myaddr : ic->ic_macaddr);
3708 	rsu_write_region_1(sc, R92S_MACID, macaddr, IEEE80211_ADDR_LEN);
3709 
3710 	/* It really takes 1.5 seconds for the firmware to boot: */
3711 	usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(2000));
3712 
3713 	RSU_DPRINTF(sc, RSU_DEBUG_RESET, "%s: setting MAC address to %s\n",
3714 	    __func__,
3715 	    ether_sprintf(macaddr));
3716 	error = rsu_fw_cmd(sc, R92S_CMD_SET_MAC_ADDRESS, macaddr,
3717 	    IEEE80211_ADDR_LEN);
3718 	if (error != 0) {
3719 		device_printf(sc->sc_dev, "could not set MAC address\n");
3720 		goto fail;
3721 	}
3722 
3723 	/* Initialize Rx filter. */
3724 	rsu_rxfilter_init(sc);
3725 
3726 	/* Set PS mode fully active */
3727 	error = rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE);
3728 	if (error != 0) {
3729 		device_printf(sc->sc_dev, "could not set PS mode\n");
3730 		goto fail;
3731 	}
3732 
3733 	/* Install static keys (if any). */
3734 	error = rsu_reinit_static_keys(sc);
3735 	if (error != 0)
3736 		goto fail;
3737 
3738 	sc->sc_extra_scan = 0;
3739 	usbd_transfer_start(sc->sc_xfer[RSU_BULK_RX]);
3740 
3741 	/* We're ready to go. */
3742 	sc->sc_running = 1;
3743 	RSU_UNLOCK(sc);
3744 
3745 	return (0);
3746 fail:
3747 	/* Need to stop all failed transfers, if any */
3748 	for (i = 0; i != RSU_N_TRANSFER; i++)
3749 		usbd_transfer_stop(sc->sc_xfer[i]);
3750 	RSU_UNLOCK(sc);
3751 
3752 	return (error);
3753 }
3754 
3755 static void
3756 rsu_stop(struct rsu_softc *sc)
3757 {
3758 	int i;
3759 
3760 	RSU_LOCK(sc);
3761 	if (!sc->sc_running) {
3762 		RSU_UNLOCK(sc);
3763 		return;
3764 	}
3765 
3766 	sc->sc_running = 0;
3767 	sc->sc_vap_is_running = 0;
3768 	sc->sc_calibrating = 0;
3769 	taskqueue_cancel_timeout(taskqueue_thread, &sc->calib_task, NULL);
3770 	taskqueue_cancel(taskqueue_thread, &sc->tx_task, NULL);
3771 
3772 	/* Power off adapter. */
3773 	rsu_power_off(sc);
3774 
3775 	/*
3776 	 * CAM is not accessible after shutdown;
3777 	 * all entries are marked (by firmware?) as invalid.
3778 	 */
3779 	memset(sc->free_keys_bmap, 0, sizeof(sc->free_keys_bmap));
3780 	memset(sc->keys_bmap, 0, sizeof(sc->keys_bmap));
3781 
3782 	for (i = 0; i < RSU_N_TRANSFER; i++)
3783 		usbd_transfer_stop(sc->sc_xfer[i]);
3784 
3785 	/* Ensure the mbuf queue is drained */
3786 	rsu_drain_mbufq(sc);
3787 	RSU_UNLOCK(sc);
3788 }
3789 
3790 /*
3791  * Note: usb_pause_mtx() actually releases the mutex before calling pause(),
3792  * which breaks any kind of driver serialisation.
3793  */
3794 static void
3795 rsu_ms_delay(struct rsu_softc *sc, int ms)
3796 {
3797 
3798 	//usb_pause_mtx(&sc->sc_mtx, hz / 1000);
3799 	DELAY(ms * 1000);
3800 }
3801