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