xref: /openbsd-src/sys/dev/usb/if_rsu.c (revision 9b9d2a55a62c8e82206c25f94fcc7f4e2765250e)
1 /*	$OpenBSD: if_rsu.c,v 1.27 2015/06/12 15:47:31 mpi 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 /*
20  * Driver for Realtek RTL8188SU/RTL8191SU/RTL8192SU.
21  */
22 
23 #include "bpfilter.h"
24 
25 #include <sys/param.h>
26 #include <sys/sockio.h>
27 #include <sys/mbuf.h>
28 #include <sys/kernel.h>
29 #include <sys/socket.h>
30 #include <sys/systm.h>
31 #include <sys/timeout.h>
32 #include <sys/conf.h>
33 #include <sys/device.h>
34 #include <sys/endian.h>
35 
36 #include <machine/intr.h>
37 
38 #if NBPFILTER > 0
39 #include <net/bpf.h>
40 #endif
41 #include <net/if.h>
42 #include <net/if_arp.h>
43 #include <net/if_dl.h>
44 #include <net/if_media.h>
45 #include <net/if_types.h>
46 
47 #include <netinet/in.h>
48 #include <netinet/if_ether.h>
49 
50 #include <net80211/ieee80211_var.h>
51 #include <net80211/ieee80211_radiotap.h>
52 
53 #include <dev/usb/usb.h>
54 #include <dev/usb/usbdi.h>
55 #include <dev/usb/usbdi_util.h>
56 #include <dev/usb/usbdevs.h>
57 
58 #include <dev/usb/if_rsureg.h>
59 
60 #ifdef RSU_DEBUG
61 #define DPRINTF(x)	do { if (rsu_debug) printf x; } while (0)
62 #define DPRINTFN(n, x)	do { if (rsu_debug >= (n)) printf x; } while (0)
63 int rsu_debug = 4;
64 #else
65 #define DPRINTF(x)
66 #define DPRINTFN(n, x)
67 #endif
68 
69 /*
70  * NB: When updating this list of devices, beware to also update the list
71  * of devices that have HT support disabled below, if applicable.
72  */
73 static const struct usb_devno rsu_devs[] = {
74 	{ USB_VENDOR_ACCTON,		USB_PRODUCT_ACCTON_RTL8192SU },
75 	{ USB_VENDOR_ASUS,		USB_PRODUCT_ASUS_USBN10 },
76 	{ USB_VENDOR_ASUS,		USB_PRODUCT_ASUS_RTL8192SU_1 },
77 	{ USB_VENDOR_AZUREWAVE,		USB_PRODUCT_AZUREWAVE_RTL8192SU_1 },
78 	{ USB_VENDOR_AZUREWAVE,		USB_PRODUCT_AZUREWAVE_RTL8192SU_2 },
79 	{ USB_VENDOR_AZUREWAVE,		USB_PRODUCT_AZUREWAVE_RTL8192SU_3 },
80 	{ USB_VENDOR_AZUREWAVE,		USB_PRODUCT_AZUREWAVE_RTL8192SU_4 },
81 	{ USB_VENDOR_AZUREWAVE,		USB_PRODUCT_AZUREWAVE_RTL8192SU_5 },
82 	{ USB_VENDOR_BELKIN,		USB_PRODUCT_BELKIN_RTL8192SU_1 },
83 	{ USB_VENDOR_BELKIN,		USB_PRODUCT_BELKIN_RTL8192SU_2 },
84 	{ USB_VENDOR_BELKIN,		USB_PRODUCT_BELKIN_RTL8192SU_3 },
85 	{ USB_VENDOR_CONCEPTRONIC2,	USB_PRODUCT_CONCEPTRONIC2_RTL8192SU_1 },
86 	{ USB_VENDOR_CONCEPTRONIC2,	USB_PRODUCT_CONCEPTRONIC2_RTL8192SU_2 },
87 	{ USB_VENDOR_CONCEPTRONIC2,	USB_PRODUCT_CONCEPTRONIC2_RTL8192SU_3 },
88 	{ USB_VENDOR_COREGA,		USB_PRODUCT_COREGA_RTL8192SU },
89 	{ USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_DWA131A1 },
90 	{ USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_RTL8192SU_1 },
91 	{ USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_RTL8192SU_2 },
92 	{ USB_VENDOR_EDIMAX,		USB_PRODUCT_EDIMAX_RTL8192SU_1 },
93 	{ USB_VENDOR_EDIMAX,		USB_PRODUCT_EDIMAX_RTL8192SU_2 },
94 	{ USB_VENDOR_EDIMAX,		USB_PRODUCT_EDIMAX_RTL8192SU_3 },
95 	{ USB_VENDOR_GUILLEMOT,		USB_PRODUCT_GUILLEMOT_HWGUN54 },
96 	{ USB_VENDOR_GUILLEMOT,		USB_PRODUCT_GUILLEMOT_HWNUM300 },
97 	{ USB_VENDOR_HAWKING,		USB_PRODUCT_HAWKING_RTL8192SU_1 },
98 	{ USB_VENDOR_HAWKING,		USB_PRODUCT_HAWKING_RTL8192SU_2 },
99 	{ USB_VENDOR_PLANEX2,		USB_PRODUCT_PLANEX2_GWUSNANO },
100 	{ USB_VENDOR_REALTEK,		USB_PRODUCT_REALTEK_RTL8171 },
101 	{ USB_VENDOR_REALTEK,		USB_PRODUCT_REALTEK_RTL8172 },
102 	{ USB_VENDOR_REALTEK,		USB_PRODUCT_REALTEK_RTL8173 },
103 	{ USB_VENDOR_REALTEK,		USB_PRODUCT_REALTEK_RTL8174 },
104 	{ USB_VENDOR_REALTEK,		USB_PRODUCT_REALTEK_RTL8192SU },
105 	{ USB_VENDOR_REALTEK,		USB_PRODUCT_REALTEK_RTL8712 },
106 	{ USB_VENDOR_REALTEK,		USB_PRODUCT_REALTEK_RTL8713 },
107 	{ USB_VENDOR_SENAO,		USB_PRODUCT_SENAO_RTL8192SU_1 },
108 	{ USB_VENDOR_SENAO,		USB_PRODUCT_SENAO_RTL8192SU_2 },
109 	{ USB_VENDOR_SITECOMEU,		USB_PRODUCT_SITECOMEU_WL349V1 },
110 	{ USB_VENDOR_SITECOMEU,		USB_PRODUCT_SITECOMEU_WL353 },
111 	{ USB_VENDOR_SWEEX2,		USB_PRODUCT_SWEEX2_LW154 }
112 };
113 
114 #ifndef IEEE80211_NO_HT
115 /* List of devices that have HT support disabled. */
116 static const struct usb_devno rsu_devs_noht[] = {
117 	{ USB_VENDOR_ASUS,		USB_PRODUCT_ASUS_RTL8192SU_1 },
118 	{ USB_VENDOR_AZUREWAVE,		USB_PRODUCT_AZUREWAVE_RTL8192SU_4 }
119 };
120 #endif
121 
122 int		rsu_match(struct device *, void *, void *);
123 void		rsu_attach(struct device *, struct device *, void *);
124 int		rsu_detach(struct device *, int);
125 int		rsu_open_pipes(struct rsu_softc *);
126 void		rsu_close_pipes(struct rsu_softc *);
127 int		rsu_alloc_rx_list(struct rsu_softc *);
128 void		rsu_free_rx_list(struct rsu_softc *);
129 int		rsu_alloc_tx_list(struct rsu_softc *);
130 void		rsu_free_tx_list(struct rsu_softc *);
131 void		rsu_task(void *);
132 void		rsu_do_async(struct rsu_softc *,
133 		    void (*)(struct rsu_softc *, void *), void *, int);
134 void		rsu_wait_async(struct rsu_softc *);
135 int		rsu_write_region_1(struct rsu_softc *, uint16_t, uint8_t *,
136 		    int);
137 void		rsu_write_1(struct rsu_softc *, uint16_t, uint8_t);
138 void		rsu_write_2(struct rsu_softc *, uint16_t, uint16_t);
139 void		rsu_write_4(struct rsu_softc *, uint16_t, uint32_t);
140 int		rsu_read_region_1(struct rsu_softc *, uint16_t, uint8_t *,
141 		    int);
142 uint8_t		rsu_read_1(struct rsu_softc *, uint16_t);
143 uint16_t	rsu_read_2(struct rsu_softc *, uint16_t);
144 uint32_t	rsu_read_4(struct rsu_softc *, uint16_t);
145 int		rsu_fw_iocmd(struct rsu_softc *, uint32_t);
146 uint8_t		rsu_efuse_read_1(struct rsu_softc *, uint16_t);
147 int		rsu_read_rom(struct rsu_softc *);
148 int		rsu_fw_cmd(struct rsu_softc *, uint8_t, void *, int);
149 int		rsu_media_change(struct ifnet *);
150 void		rsu_calib_to(void *);
151 void		rsu_calib_cb(struct rsu_softc *, void *);
152 int		rsu_newstate(struct ieee80211com *, enum ieee80211_state, int);
153 void		rsu_newstate_cb(struct rsu_softc *, void *);
154 int		rsu_set_key(struct ieee80211com *, struct ieee80211_node *,
155 		    struct ieee80211_key *);
156 void		rsu_set_key_cb(struct rsu_softc *, void *);
157 void		rsu_delete_key(struct ieee80211com *, struct ieee80211_node *,
158 		    struct ieee80211_key *);
159 void		rsu_delete_key_cb(struct rsu_softc *, void *);
160 int		rsu_site_survey(struct rsu_softc *);
161 int		rsu_join_bss(struct rsu_softc *, struct ieee80211_node *);
162 int		rsu_disconnect(struct rsu_softc *);
163 void		rsu_event_survey(struct rsu_softc *, uint8_t *, int);
164 void		rsu_event_join_bss(struct rsu_softc *, uint8_t *, int);
165 void		rsu_rx_event(struct rsu_softc *, uint8_t, uint8_t *, int);
166 void		rsu_rx_multi_event(struct rsu_softc *, uint8_t *, int);
167 int8_t		rsu_get_rssi(struct rsu_softc *, int, void *);
168 void		rsu_rx_frame(struct rsu_softc *, uint8_t *, int);
169 void		rsu_rx_multi_frame(struct rsu_softc *, uint8_t *, int);
170 void		rsu_rxeof(struct usbd_xfer *, void *, usbd_status);
171 void		rsu_txeof(struct usbd_xfer *, void *, usbd_status);
172 int		rsu_tx(struct rsu_softc *, struct mbuf *,
173 		    struct ieee80211_node *);
174 int		rsu_send_mgmt(struct ieee80211com *, struct ieee80211_node *,
175 		    int, int, int);
176 void		rsu_start(struct ifnet *);
177 void		rsu_watchdog(struct ifnet *);
178 int		rsu_ioctl(struct ifnet *, u_long, caddr_t);
179 void		rsu_power_on_acut(struct rsu_softc *);
180 void		rsu_power_on_bcut(struct rsu_softc *);
181 void		rsu_power_off(struct rsu_softc *);
182 int		rsu_fw_loadsection(struct rsu_softc *, uint8_t *, int);
183 int		rsu_load_firmware(struct rsu_softc *);
184 int		rsu_init(struct ifnet *);
185 void		rsu_stop(struct ifnet *);
186 
187 struct cfdriver rsu_cd = {
188 	NULL, "rsu", DV_IFNET
189 };
190 
191 const struct cfattach rsu_ca = {
192 	sizeof(struct rsu_softc), rsu_match, rsu_attach, rsu_detach,
193 };
194 
195 int
196 rsu_match(struct device *parent, void *match, void *aux)
197 {
198 	struct usb_attach_arg *uaa = aux;
199 
200 	if (uaa->iface == NULL || uaa->configno != 1)
201 		return (UMATCH_NONE);
202 
203 	return ((usb_lookup(rsu_devs, uaa->vendor, uaa->product) != NULL) ?
204 	    UMATCH_VENDOR_PRODUCT_CONF_IFACE : UMATCH_NONE);
205 }
206 
207 void
208 rsu_attach(struct device *parent, struct device *self, void *aux)
209 {
210 	struct rsu_softc *sc = (struct rsu_softc *)self;
211 	struct usb_attach_arg *uaa = aux;
212 	struct ieee80211com *ic = &sc->sc_ic;
213 	struct ifnet *ifp = &ic->ic_if;
214 	int i, error;
215 
216 	sc->sc_udev = uaa->device;
217 	sc->sc_iface = uaa->iface;
218 
219 	usb_init_task(&sc->sc_task, rsu_task, sc, USB_TASK_TYPE_GENERIC);
220 	timeout_set(&sc->calib_to, rsu_calib_to, sc);
221 
222 	/* Read chip revision. */
223 	sc->cut = MS(rsu_read_4(sc, R92S_PMC_FSM), R92S_PMC_FSM_CUT);
224 	if (sc->cut != 3)
225 		sc->cut = (sc->cut >> 1) + 1;
226 
227 	error = rsu_read_rom(sc);
228 	if (error != 0) {
229 		printf("%s: could not read ROM\n", sc->sc_dev.dv_xname);
230 		return;
231 	}
232 	IEEE80211_ADDR_COPY(ic->ic_myaddr, &sc->rom[0x12]);
233 
234 	printf("%s: MAC/BB RTL8712 cut %d, address %s\n",
235 	    sc->sc_dev.dv_xname, sc->cut, ether_sprintf(ic->ic_myaddr));
236 
237 	if (rsu_open_pipes(sc) != 0)
238 		return;
239 
240 	ic->ic_phytype = IEEE80211_T_OFDM;	/* Not only, but not used. */
241 	ic->ic_opmode = IEEE80211_M_STA;	/* Default to BSS mode. */
242 	ic->ic_state = IEEE80211_S_INIT;
243 
244 	/* Set device capabilities. */
245 	ic->ic_caps =
246 	    IEEE80211_C_SCANALL |	/* Hardware scan. */
247 	    IEEE80211_C_SHPREAMBLE |	/* Short preamble supported. */
248 	    IEEE80211_C_SHSLOT |	/* Short slot time supported. */
249 	    IEEE80211_C_WEP |		/* WEP. */
250 	    IEEE80211_C_RSN;		/* WPA/RSN. */
251 #ifndef IEEE80211_NO_HT
252 	/* Check if HT support is present. */
253 	if (usb_lookup(rsu_devs_noht, uaa->vendor, uaa->product) == NULL) {
254 		/* Set HT capabilities. */
255 		ic->ic_htcaps =
256 		    IEEE80211_HTCAP_CBW20_40 |
257 		    IEEE80211_HTCAP_DSSSCCK40;
258 		/* Set supported HT rates. */
259 		for (i = 0; i < 2; i++)
260 			ic->ic_sup_mcs[i] = 0xff;
261 	}
262 #endif
263 
264 	/* Set supported .11b and .11g rates. */
265 	ic->ic_sup_rates[IEEE80211_MODE_11B] = ieee80211_std_rateset_11b;
266 	ic->ic_sup_rates[IEEE80211_MODE_11G] = ieee80211_std_rateset_11g;
267 
268 	/* Set supported .11b and .11g channels (1 through 14). */
269 	for (i = 1; i <= 14; i++) {
270 		ic->ic_channels[i].ic_freq =
271 		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
272 		ic->ic_channels[i].ic_flags =
273 		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
274 		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
275 	}
276 
277 	ifp->if_softc = sc;
278 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
279 	ifp->if_ioctl = rsu_ioctl;
280 	ifp->if_start = rsu_start;
281 	ifp->if_watchdog = rsu_watchdog;
282 	IFQ_SET_READY(&ifp->if_snd);
283 	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
284 
285 	if_attach(ifp);
286 	ieee80211_ifattach(ifp);
287 #ifdef notyet
288 	ic->ic_set_key = rsu_set_key;
289 	ic->ic_delete_key = rsu_delete_key;
290 #endif
291 	/* Override state transition machine. */
292 	sc->sc_newstate = ic->ic_newstate;
293 	ic->ic_newstate = rsu_newstate;
294 	ic->ic_send_mgmt = rsu_send_mgmt;
295 	ieee80211_media_init(ifp, rsu_media_change, ieee80211_media_status);
296 
297 #if NBPFILTER > 0
298 	bpfattach(&sc->sc_drvbpf, ifp, DLT_IEEE802_11_RADIO,
299 	    sizeof(struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN);
300 
301 	sc->sc_rxtap_len = sizeof(sc->sc_rxtapu);
302 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
303 	sc->sc_rxtap.wr_ihdr.it_present = htole32(RSU_RX_RADIOTAP_PRESENT);
304 
305 	sc->sc_txtap_len = sizeof(sc->sc_txtapu);
306 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
307 	sc->sc_txtap.wt_ihdr.it_present = htole32(RSU_TX_RADIOTAP_PRESENT);
308 #endif
309 }
310 
311 int
312 rsu_detach(struct device *self, int flags)
313 {
314 	struct rsu_softc *sc = (struct rsu_softc *)self;
315 	struct ifnet *ifp = &sc->sc_ic.ic_if;
316 	int s;
317 
318 	s = splusb();
319 
320 	if (timeout_initialized(&sc->calib_to))
321 		timeout_del(&sc->calib_to);
322 
323 	/* Wait for all async commands to complete. */
324 	usb_rem_wait_task(sc->sc_udev, &sc->sc_task);
325 
326 	usbd_ref_wait(sc->sc_udev);
327 
328 	if (ifp->if_softc != NULL) {
329 		ieee80211_ifdetach(ifp);
330 		if_detach(ifp);
331 	}
332 
333 	/* Abort and close Tx/Rx pipes. */
334 	rsu_close_pipes(sc);
335 
336 	/* Free Tx/Rx buffers. */
337 	rsu_free_tx_list(sc);
338 	rsu_free_rx_list(sc);
339 	splx(s);
340 
341 	return (0);
342 }
343 
344 int
345 rsu_open_pipes(struct rsu_softc *sc)
346 {
347 	usb_interface_descriptor_t *id;
348 	int i, error;
349 
350 	/*
351 	 * Determine the number of Tx/Rx endpoints (there are chips with
352 	 * 4, 6 or 11 endpoints).
353 	 */
354 	id = usbd_get_interface_descriptor(sc->sc_iface);
355 	sc->npipes = id->bNumEndpoints;
356 	if (sc->npipes == 4)
357 		sc->qid2idx = rsu_qid2idx_4ep;
358 	else if (sc->npipes == 6)
359 		sc->qid2idx = rsu_qid2idx_6ep;
360 	else	/* Assume npipes==11; will fail below otherwise. */
361 		sc->qid2idx = rsu_qid2idx_11ep;
362 	DPRINTF(("%d endpoints configuration\n", sc->npipes));
363 
364 	/* Open all pipes. */
365 	for (i = 0; i < MIN(sc->npipes, nitems(r92s_epaddr)); i++) {
366 		error = usbd_open_pipe(sc->sc_iface, r92s_epaddr[i], 0,
367 		    &sc->pipe[i]);
368 		if (error != 0) {
369 			printf("%s: could not open bulk pipe 0x%02x\n",
370 			    sc->sc_dev.dv_xname, r92s_epaddr[i]);
371 			break;
372 		}
373 	}
374 	if (error != 0)
375 		rsu_close_pipes(sc);
376 	return (error);
377 }
378 
379 void
380 rsu_close_pipes(struct rsu_softc *sc)
381 {
382 	int i;
383 
384 	/* Close all pipes. */
385 	for (i = 0; i < sc->npipes; i++) {
386 		if (sc->pipe[i] == NULL)
387 			continue;
388 		usbd_abort_pipe(sc->pipe[i]);
389 		usbd_close_pipe(sc->pipe[i]);
390 	}
391 }
392 
393 int
394 rsu_alloc_rx_list(struct rsu_softc *sc)
395 {
396 	struct rsu_rx_data *data;
397 	int i, error = 0;
398 
399 	for (i = 0; i < RSU_RX_LIST_COUNT; i++) {
400 		data = &sc->rx_data[i];
401 
402 		data->sc = sc;	/* Backpointer for callbacks. */
403 
404 		data->xfer = usbd_alloc_xfer(sc->sc_udev);
405 		if (data->xfer == NULL) {
406 			printf("%s: could not allocate xfer\n",
407 			    sc->sc_dev.dv_xname);
408 			error = ENOMEM;
409 			break;
410 		}
411 		data->buf = usbd_alloc_buffer(data->xfer, RSU_RXBUFSZ);
412 		if (data->buf == NULL) {
413 			printf("%s: could not allocate xfer buffer\n",
414 			    sc->sc_dev.dv_xname);
415 			error = ENOMEM;
416 			break;
417 		}
418 	}
419 	if (error != 0)
420 		rsu_free_rx_list(sc);
421 	return (error);
422 }
423 
424 void
425 rsu_free_rx_list(struct rsu_softc *sc)
426 {
427 	int i;
428 
429 	/* NB: Caller must abort pipe first. */
430 	for (i = 0; i < RSU_RX_LIST_COUNT; i++) {
431 		if (sc->rx_data[i].xfer != NULL)
432 			usbd_free_xfer(sc->rx_data[i].xfer);
433 		sc->rx_data[i].xfer = NULL;
434 	}
435 }
436 
437 int
438 rsu_alloc_tx_list(struct rsu_softc *sc)
439 {
440 	struct rsu_tx_data *data;
441 	int i, error = 0;
442 
443 	TAILQ_INIT(&sc->tx_free_list);
444 	for (i = 0; i < RSU_TX_LIST_COUNT; i++) {
445 		data = &sc->tx_data[i];
446 
447 		data->sc = sc;	/* Backpointer for callbacks. */
448 
449 		data->xfer = usbd_alloc_xfer(sc->sc_udev);
450 		if (data->xfer == NULL) {
451 			printf("%s: could not allocate xfer\n",
452 			    sc->sc_dev.dv_xname);
453 			error = ENOMEM;
454 			break;
455 		}
456 		data->buf = usbd_alloc_buffer(data->xfer, RSU_TXBUFSZ);
457 		if (data->buf == NULL) {
458 			printf("%s: could not allocate xfer buffer\n",
459 			    sc->sc_dev.dv_xname);
460 			error = ENOMEM;
461 			break;
462 		}
463 		/* Append this Tx buffer to our free list. */
464 		TAILQ_INSERT_TAIL(&sc->tx_free_list, data, next);
465 	}
466 	if (error != 0)
467 		rsu_free_tx_list(sc);
468 	return (error);
469 }
470 
471 void
472 rsu_free_tx_list(struct rsu_softc *sc)
473 {
474 	int i;
475 
476 	/* NB: Caller must abort pipe first. */
477 	for (i = 0; i < RSU_TX_LIST_COUNT; i++) {
478 		if (sc->tx_data[i].xfer != NULL)
479 			usbd_free_xfer(sc->tx_data[i].xfer);
480 		sc->tx_data[i].xfer = NULL;
481 	}
482 }
483 
484 void
485 rsu_task(void *arg)
486 {
487 	struct rsu_softc *sc = arg;
488 	struct rsu_host_cmd_ring *ring = &sc->cmdq;
489 	struct rsu_host_cmd *cmd;
490 	int s;
491 
492 	/* Process host commands. */
493 	s = splusb();
494 	while (ring->next != ring->cur) {
495 		cmd = &ring->cmd[ring->next];
496 		splx(s);
497 		/* Invoke callback. */
498 		cmd->cb(sc, cmd->data);
499 		s = splusb();
500 		ring->queued--;
501 		ring->next = (ring->next + 1) % RSU_HOST_CMD_RING_COUNT;
502 	}
503 	splx(s);
504 }
505 
506 void
507 rsu_do_async(struct rsu_softc *sc,
508     void (*cb)(struct rsu_softc *, void *), void *arg, int len)
509 {
510 	struct rsu_host_cmd_ring *ring = &sc->cmdq;
511 	struct rsu_host_cmd *cmd;
512 	int s;
513 
514 	s = splusb();
515 	cmd = &ring->cmd[ring->cur];
516 	cmd->cb = cb;
517 	KASSERT(len <= sizeof(cmd->data));
518 	memcpy(cmd->data, arg, len);
519 	ring->cur = (ring->cur + 1) % RSU_HOST_CMD_RING_COUNT;
520 
521 	/* If there is no pending command already, schedule a task. */
522 	if (++ring->queued == 1)
523 		usb_add_task(sc->sc_udev, &sc->sc_task);
524 	splx(s);
525 }
526 
527 void
528 rsu_wait_async(struct rsu_softc *sc)
529 {
530 	/* Wait for all queued asynchronous commands to complete. */
531 	usb_wait_task(sc->sc_udev, &sc->sc_task);
532 }
533 
534 int
535 rsu_write_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
536     int len)
537 {
538 	usb_device_request_t req;
539 
540 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
541 	req.bRequest = R92S_REQ_REGS;
542 	USETW(req.wValue, addr);
543 	USETW(req.wIndex, 0);
544 	USETW(req.wLength, len);
545 	return (usbd_do_request(sc->sc_udev, &req, buf));
546 }
547 
548 void
549 rsu_write_1(struct rsu_softc *sc, uint16_t addr, uint8_t val)
550 {
551 	rsu_write_region_1(sc, addr, &val, 1);
552 }
553 
554 void
555 rsu_write_2(struct rsu_softc *sc, uint16_t addr, uint16_t val)
556 {
557 	val = htole16(val);
558 	rsu_write_region_1(sc, addr, (uint8_t *)&val, 2);
559 }
560 
561 void
562 rsu_write_4(struct rsu_softc *sc, uint16_t addr, uint32_t val)
563 {
564 	val = htole32(val);
565 	rsu_write_region_1(sc, addr, (uint8_t *)&val, 4);
566 }
567 
568 int
569 rsu_read_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
570     int len)
571 {
572 	usb_device_request_t req;
573 
574 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
575 	req.bRequest = R92S_REQ_REGS;
576 	USETW(req.wValue, addr);
577 	USETW(req.wIndex, 0);
578 	USETW(req.wLength, len);
579 	return (usbd_do_request(sc->sc_udev, &req, buf));
580 }
581 
582 uint8_t
583 rsu_read_1(struct rsu_softc *sc, uint16_t addr)
584 {
585 	uint8_t val;
586 
587 	if (rsu_read_region_1(sc, addr, &val, 1) != 0)
588 		return (0xff);
589 	return (val);
590 }
591 
592 uint16_t
593 rsu_read_2(struct rsu_softc *sc, uint16_t addr)
594 {
595 	uint16_t val;
596 
597 	if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0)
598 		return (0xffff);
599 	return (letoh16(val));
600 }
601 
602 uint32_t
603 rsu_read_4(struct rsu_softc *sc, uint16_t addr)
604 {
605 	uint32_t val;
606 
607 	if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0)
608 		return (0xffffffff);
609 	return (letoh32(val));
610 }
611 
612 int
613 rsu_fw_iocmd(struct rsu_softc *sc, uint32_t iocmd)
614 {
615 	int ntries;
616 
617 	rsu_write_4(sc, R92S_IOCMD_CTRL, iocmd);
618 	DELAY(100);
619 	for (ntries = 0; ntries < 50; ntries++) {
620 		if (rsu_read_4(sc, R92S_IOCMD_CTRL) == 0)
621 			return (0);
622 		DELAY(10);
623 	}
624 	return (ETIMEDOUT);
625 }
626 
627 uint8_t
628 rsu_efuse_read_1(struct rsu_softc *sc, uint16_t addr)
629 {
630 	uint32_t reg;
631 	int ntries;
632 
633 	reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
634 	reg = RW(reg, R92S_EFUSE_CTRL_ADDR, addr);
635 	reg &= ~R92S_EFUSE_CTRL_VALID;
636 	rsu_write_4(sc, R92S_EFUSE_CTRL, reg);
637 	/* Wait for read operation to complete. */
638 	for (ntries = 0; ntries < 100; ntries++) {
639 		reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
640 		if (reg & R92S_EFUSE_CTRL_VALID)
641 			return (MS(reg, R92S_EFUSE_CTRL_DATA));
642 		DELAY(5);
643 	}
644 	printf("%s: could not read efuse byte at address 0x%x\n",
645 	    sc->sc_dev.dv_xname, addr);
646 	return (0xff);
647 }
648 
649 int
650 rsu_read_rom(struct rsu_softc *sc)
651 {
652 	uint8_t *rom = sc->rom;
653 	uint16_t addr = 0;
654 	uint32_t reg;
655 	uint8_t off, msk;
656 	int i;
657 
658 	/* Make sure that ROM type is eFuse and that autoload succeeded. */
659 	reg = rsu_read_1(sc, R92S_EE_9346CR);
660 	if ((reg & (R92S_9356SEL | R92S_EEPROM_EN)) != R92S_EEPROM_EN)
661 		return (EIO);
662 
663 	/* Turn on 2.5V to prevent eFuse leakage. */
664 	reg = rsu_read_1(sc, R92S_EFUSE_TEST + 3);
665 	rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg | 0x80);
666 	DELAY(1000);
667 	rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg & ~0x80);
668 
669 	/* Read full ROM image. */
670 	memset(&sc->rom, 0xff, sizeof(sc->rom));
671 	while (addr < 512) {
672 		reg = rsu_efuse_read_1(sc, addr);
673 		if (reg == 0xff)
674 			break;
675 		addr++;
676 		off = reg >> 4;
677 		msk = reg & 0xf;
678 		for (i = 0; i < 4; i++) {
679 			if (msk & (1 << i))
680 				continue;
681 			rom[off * 8 + i * 2 + 0] =
682 			    rsu_efuse_read_1(sc, addr);
683 			addr++;
684 			rom[off * 8 + i * 2 + 1] =
685 			    rsu_efuse_read_1(sc, addr);
686 			addr++;
687 		}
688 	}
689 #ifdef RSU_DEBUG
690 	if (rsu_debug >= 5) {
691 		/* Dump ROM content. */
692 		printf("\n");
693 		for (i = 0; i < sizeof(sc->rom); i++)
694 			printf("%02x:", rom[i]);
695 		printf("\n");
696 	}
697 #endif
698 	return (0);
699 }
700 
701 int
702 rsu_fw_cmd(struct rsu_softc *sc, uint8_t code, void *buf, int len)
703 {
704 	struct rsu_tx_data *data;
705 	struct r92s_tx_desc *txd;
706 	struct r92s_fw_cmd_hdr *cmd;
707 	struct usbd_pipe *pipe;
708 	int cmdsz, xferlen;
709 
710 	data = sc->fwcmd_data;
711 
712 	/* Round-up command length to a multiple of 8 bytes. */
713 	cmdsz = (len + 7) & ~7;
714 
715 	xferlen = sizeof(*txd) + sizeof(*cmd) + cmdsz;
716 	KASSERT(xferlen <= RSU_TXBUFSZ);
717 	memset(data->buf, 0, xferlen);
718 
719 	/* Setup Tx descriptor. */
720 	txd = (struct r92s_tx_desc *)data->buf;
721 	txd->txdw0 = htole32(
722 	    SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
723 	    SM(R92S_TXDW0_PKTLEN, sizeof(*cmd) + cmdsz) |
724 	    R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
725 	txd->txdw1 = htole32(SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_H2C));
726 
727 	/* Setup command header. */
728 	cmd = (struct r92s_fw_cmd_hdr *)&txd[1];
729 	cmd->len = htole16(cmdsz);
730 	cmd->code = code;
731 	cmd->seq = sc->cmd_seq;
732 	sc->cmd_seq = (sc->cmd_seq + 1) & 0x7f;
733 
734 	/* Copy command payload. */
735 	memcpy(&cmd[1], buf, len);
736 
737 	DPRINTFN(2, ("Tx cmd code=%d len=%d\n", code, cmdsz));
738 	pipe = sc->pipe[sc->qid2idx[RSU_QID_H2C]];
739 	usbd_setup_xfer(data->xfer, pipe, NULL, data->buf, xferlen,
740 	    USBD_SHORT_XFER_OK | USBD_NO_COPY | USBD_SYNCHRONOUS,
741 	    RSU_CMD_TIMEOUT, NULL);
742 	return (usbd_transfer(data->xfer));
743 }
744 
745 int
746 rsu_media_change(struct ifnet *ifp)
747 {
748 	int error;
749 
750 	error = ieee80211_media_change(ifp);
751 	if (error != ENETRESET)
752 		return (error);
753 
754 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
755 	    (IFF_UP | IFF_RUNNING)) {
756 		rsu_stop(ifp);
757 		rsu_init(ifp);
758 	}
759 	return (0);
760 }
761 
762 void
763 rsu_calib_to(void *arg)
764 {
765 	struct rsu_softc *sc = arg;
766 
767 	if (usbd_is_dying(sc->sc_udev))
768 		return;
769 
770 	usbd_ref_incr(sc->sc_udev);
771 
772 	/* Do it in a process context. */
773 	rsu_do_async(sc, rsu_calib_cb, NULL, 0);
774 
775 	usbd_ref_decr(sc->sc_udev);
776 }
777 
778 /* ARGSUSED */
779 void
780 rsu_calib_cb(struct rsu_softc *sc, void *arg)
781 {
782 	uint32_t reg;
783 
784 #ifdef notyet
785 	/* Read WPS PBC status. */
786 	rsu_write_1(sc, R92S_MAC_PINMUX_CTRL,
787 	    R92S_GPIOMUX_EN | SM(R92S_GPIOSEL_GPIO, R92S_GPIOSEL_GPIO_JTAG));
788 	rsu_write_1(sc, R92S_GPIO_IO_SEL,
789 	    rsu_read_1(sc, R92S_GPIO_IO_SEL) & ~R92S_GPIO_WPS);
790 	reg = rsu_read_1(sc, R92S_GPIO_CTRL);
791 	if (reg != 0xff && (reg & R92S_GPIO_WPS))
792 		DPRINTF(("WPS PBC is pushed\n"));
793 #endif
794 	/* Read current signal level. */
795 	if (rsu_fw_iocmd(sc, 0xf4000001) == 0) {
796 		reg = rsu_read_4(sc, R92S_IOCMD_DATA);
797 		DPRINTFN(8, ("RSSI=%d%%\n", reg >> 4));
798 	}
799 
800 	if (!usbd_is_dying(sc->sc_udev))
801 		timeout_add_sec(&sc->calib_to, 2);
802 }
803 
804 int
805 rsu_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
806 {
807 	struct rsu_softc *sc = ic->ic_softc;
808 	struct rsu_cmd_newstate cmd;
809 
810 	/* Do it in a process context. */
811 	cmd.state = nstate;
812 	cmd.arg = arg;
813 	rsu_do_async(sc, rsu_newstate_cb, &cmd, sizeof(cmd));
814 	return (0);
815 }
816 
817 void
818 rsu_newstate_cb(struct rsu_softc *sc, void *arg)
819 {
820 	struct rsu_cmd_newstate *cmd = arg;
821 	struct ieee80211com *ic = &sc->sc_ic;
822 	enum ieee80211_state ostate;
823 	int error, s;
824 
825 	s = splnet();
826 	ostate = ic->ic_state;
827 	DPRINTF(("newstate %d -> %d\n", ostate, cmd->state));
828 
829 	if (ostate == IEEE80211_S_RUN) {
830 		/* Stop calibration. */
831 		timeout_del(&sc->calib_to);
832 		/* Disassociate from our current BSS. */
833 		(void)rsu_disconnect(sc);
834 	}
835 	switch (cmd->state) {
836 	case IEEE80211_S_INIT:
837 		break;
838 	case IEEE80211_S_SCAN:
839 		error = rsu_site_survey(sc);
840 		if (error != 0) {
841 			printf("%s: could not send site survey command\n",
842 			    sc->sc_dev.dv_xname);
843 		}
844 		ic->ic_state = cmd->state;
845 		splx(s);
846 		return;
847 	case IEEE80211_S_AUTH:
848 		error = rsu_join_bss(sc, ic->ic_bss);
849 		if (error != 0) {
850 			printf("%s: could not send join command\n",
851 			    sc->sc_dev.dv_xname);
852 			ieee80211_begin_scan(&ic->ic_if);
853 			splx(s);
854 			return;
855 		}
856 		ic->ic_state = cmd->state;
857 		splx(s);
858 		return;
859 	case IEEE80211_S_ASSOC:
860 		ic->ic_state = cmd->state;
861 		splx(s);
862 		return;
863 	case IEEE80211_S_RUN:
864 		/* Indicate highest supported rate. */
865 		ic->ic_bss->ni_txrate = ic->ic_bss->ni_rates.rs_nrates - 1;
866 
867 		/* Start periodic calibration. */
868 		if (!usbd_is_dying(sc->sc_udev))
869 			timeout_add_sec(&sc->calib_to, 2);
870 		break;
871 	}
872 	(void)sc->sc_newstate(ic, cmd->state, cmd->arg);
873 	splx(s);
874 }
875 
876 int
877 rsu_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
878     struct ieee80211_key *k)
879 {
880 	struct rsu_softc *sc = ic->ic_softc;
881 	struct rsu_cmd_key cmd;
882 
883 	/* Defer setting of WEP keys until interface is brought up. */
884 	if ((ic->ic_if.if_flags & (IFF_UP | IFF_RUNNING)) !=
885 	    (IFF_UP | IFF_RUNNING))
886 		return (0);
887 
888 	/* Do it in a process context. */
889 	cmd.key = *k;
890 	rsu_do_async(sc, rsu_set_key_cb, &cmd, sizeof(cmd));
891 	return (0);
892 }
893 
894 void
895 rsu_set_key_cb(struct rsu_softc *sc, void *arg)
896 {
897 	struct rsu_cmd_key *cmd = arg;
898 	struct ieee80211_key *k = &cmd->key;
899 	struct r92s_fw_cmd_set_key key;
900 
901 	memset(&key, 0, sizeof(key));
902 	/* Map net80211 cipher to HW crypto algorithm. */
903 	switch (k->k_cipher) {
904 	case IEEE80211_CIPHER_WEP40:
905 		key.algo = R92S_KEY_ALGO_WEP40;
906 		break;
907 	case IEEE80211_CIPHER_WEP104:
908 		key.algo = R92S_KEY_ALGO_WEP104;
909 		break;
910 	case IEEE80211_CIPHER_TKIP:
911 		key.algo = R92S_KEY_ALGO_TKIP;
912 		break;
913 	case IEEE80211_CIPHER_CCMP:
914 		key.algo = R92S_KEY_ALGO_AES;
915 		break;
916 	default:
917 		return;
918 	}
919 	key.id = k->k_id;
920 	key.grpkey = (k->k_flags & IEEE80211_KEY_GROUP) != 0;
921 	memcpy(key.key, k->k_key, MIN(k->k_len, sizeof(key.key)));
922 	(void)rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
923 }
924 
925 /* ARGSUSED */
926 void
927 rsu_delete_key(struct ieee80211com *ic, struct ieee80211_node *ni,
928     struct ieee80211_key *k)
929 {
930 	struct rsu_softc *sc = ic->ic_softc;
931 	struct rsu_cmd_key cmd;
932 
933 	if (!(ic->ic_if.if_flags & IFF_RUNNING) ||
934 	    ic->ic_state != IEEE80211_S_RUN)
935 		return;	/* Nothing to do. */
936 
937 	/* Do it in a process context. */
938 	cmd.key = *k;
939 	rsu_do_async(sc, rsu_delete_key_cb, &cmd, sizeof(cmd));
940 }
941 
942 void
943 rsu_delete_key_cb(struct rsu_softc *sc, void *arg)
944 {
945 	struct rsu_cmd_key *cmd = arg;
946 	struct ieee80211_key *k = &cmd->key;
947 	struct r92s_fw_cmd_set_key key;
948 
949 	memset(&key, 0, sizeof(key));
950 	key.id = k->k_id;
951 	(void)rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
952 }
953 
954 int
955 rsu_site_survey(struct rsu_softc *sc)
956 {
957 	struct ieee80211com *ic = &sc->sc_ic;
958 	struct r92s_fw_cmd_sitesurvey cmd;
959 
960 	memset(&cmd, 0, sizeof(cmd));
961 	if ((ic->ic_flags & IEEE80211_F_ASCAN) || sc->scan_pass == 1)
962 		cmd.active = htole32(1);
963 	cmd.limit = htole32(48);
964 	if (sc->scan_pass == 1) {
965 		/* Do a directed scan for second pass. */
966 		cmd.ssidlen = htole32(ic->ic_des_esslen);
967 		memcpy(cmd.ssid, ic->ic_des_essid, ic->ic_des_esslen);
968 	}
969 	DPRINTF(("sending site survey command, pass=%d\n", sc->scan_pass));
970 	return (rsu_fw_cmd(sc, R92S_CMD_SITE_SURVEY, &cmd, sizeof(cmd)));
971 }
972 
973 int
974 rsu_join_bss(struct rsu_softc *sc, struct ieee80211_node *ni)
975 {
976 	struct ieee80211com *ic = &sc->sc_ic;
977 	struct ndis_wlan_bssid_ex *bss;
978 	struct ndis_802_11_fixed_ies *fixed;
979 	struct r92s_fw_cmd_auth auth;
980 	uint8_t buf[sizeof(*bss) + 128], *frm;
981 	uint8_t opmode;
982 	int error;
983 
984 	/* Let the FW decide the opmode based on the capinfo field. */
985 	opmode = NDIS802_11AUTOUNKNOWN;
986 	DPRINTF(("setting operating mode to %d\n", opmode));
987 	error = rsu_fw_cmd(sc, R92S_CMD_SET_OPMODE, &opmode, sizeof(opmode));
988 	if (error != 0)
989 		return (error);
990 
991 	memset(&auth, 0, sizeof(auth));
992 	if (ic->ic_flags & IEEE80211_F_RSNON) {
993 		auth.mode = R92S_AUTHMODE_WPA;
994 		auth.dot1x = ieee80211_is_8021x_akm(ni->ni_rsnakms);
995 	} else
996 		auth.mode = R92S_AUTHMODE_OPEN;
997 	DPRINTF(("setting auth mode to %d\n", auth.mode));
998 	error = rsu_fw_cmd(sc, R92S_CMD_SET_AUTH, &auth, sizeof(auth));
999 	if (error != 0)
1000 		return (error);
1001 
1002 	memset(buf, 0, sizeof(buf));
1003 	bss = (struct ndis_wlan_bssid_ex *)buf;
1004 	IEEE80211_ADDR_COPY(bss->macaddr, ni->ni_bssid);
1005 	bss->ssid.ssidlen = htole32(ni->ni_esslen);
1006 	memcpy(bss->ssid.ssid, ni->ni_essid, ni->ni_esslen);
1007 	if (ic->ic_flags & (IEEE80211_F_WEPON | IEEE80211_F_RSNON))
1008 		bss->privacy = htole32(1);
1009 	bss->rssi = htole32(ni->ni_rssi);
1010 	if (ic->ic_curmode == IEEE80211_MODE_11B)
1011 		bss->networktype = htole32(NDIS802_11DS);
1012 	else
1013 		bss->networktype = htole32(NDIS802_11OFDM24);
1014 	bss->config.len = htole32(sizeof(bss->config));
1015 	bss->config.bintval = htole32(ni->ni_intval);
1016 	bss->config.dsconfig = htole32(ieee80211_chan2ieee(ic, ni->ni_chan));
1017 	bss->inframode = htole32(NDIS802_11INFRASTRUCTURE);
1018 	memcpy(bss->supprates, ni->ni_rates.rs_rates,
1019 	    ni->ni_rates.rs_nrates);
1020 	/* Write the fixed fields of the beacon frame. */
1021 	fixed = (struct ndis_802_11_fixed_ies *)&bss[1];
1022 	memcpy(&fixed->tstamp, ni->ni_tstamp, 8);
1023 	fixed->bintval = htole16(ni->ni_intval);
1024 	fixed->capabilities = htole16(ni->ni_capinfo);
1025 	/* Write IEs to be included in the association request. */
1026 	frm = (uint8_t *)&fixed[1];
1027 	if ((ic->ic_flags & IEEE80211_F_RSNON) &&
1028 	    (ni->ni_rsnprotos & IEEE80211_PROTO_RSN))
1029 		frm = ieee80211_add_rsn(frm, ic, ni);
1030 	if (ni->ni_flags & IEEE80211_NODE_QOS)
1031 		frm = ieee80211_add_qos_capability(frm, ic);
1032 #ifndef IEEE80211_NO_HT
1033 	if (ni->ni_flags & IEEE80211_NODE_HT)
1034 		frm = ieee80211_add_htcaps(frm, ic);
1035 #endif
1036 	if ((ic->ic_flags & IEEE80211_F_RSNON) &&
1037 	    (ni->ni_rsnprotos & IEEE80211_PROTO_WPA))
1038 		frm = ieee80211_add_wpa(frm, ic, ni);
1039 	bss->ieslen = htole32(frm - (uint8_t *)fixed);
1040 	bss->len = htole32(((frm - buf) + 3) & ~3);
1041 	DPRINTF(("sending join bss command to %s chan %d\n",
1042 	    ether_sprintf(bss->macaddr), letoh32(bss->config.dsconfig)));
1043 	return (rsu_fw_cmd(sc, R92S_CMD_JOIN_BSS, buf, sizeof(buf)));
1044 }
1045 
1046 int
1047 rsu_disconnect(struct rsu_softc *sc)
1048 {
1049 	uint32_t zero = 0;	/* :-) */
1050 
1051 	/* Disassociate from our current BSS. */
1052 	DPRINTF(("sending disconnect command\n"));
1053 	return (rsu_fw_cmd(sc, R92S_CMD_DISCONNECT, &zero, sizeof(zero)));
1054 }
1055 
1056 void
1057 rsu_event_survey(struct rsu_softc *sc, uint8_t *buf, int len)
1058 {
1059 	struct ieee80211com *ic = &sc->sc_ic;
1060 	struct ifnet *ifp = &ic->ic_if;
1061 	struct ieee80211_rxinfo rxi;
1062 	struct ieee80211_node *ni;
1063 	struct ieee80211_frame *wh;
1064 	struct ndis_wlan_bssid_ex *bss;
1065 	struct mbuf *m;
1066 	int pktlen;
1067 
1068 	if (__predict_false(len < sizeof(*bss)))
1069 		return;
1070 	bss = (struct ndis_wlan_bssid_ex *)buf;
1071 	if (__predict_false(len < sizeof(*bss) + letoh32(bss->ieslen)))
1072 		return;
1073 
1074 	DPRINTFN(2, ("found BSS %s: len=%d chan=%d inframode=%d "
1075 	    "networktype=%d privacy=%d\n",
1076 	    ether_sprintf(bss->macaddr), letoh32(bss->len),
1077 	    letoh32(bss->config.dsconfig), letoh32(bss->inframode),
1078 	    letoh32(bss->networktype), letoh32(bss->privacy)));
1079 
1080 	/* Build a fake beacon frame to let net80211 do all the parsing. */
1081 	pktlen = sizeof(*wh) + letoh32(bss->ieslen);
1082 	if (__predict_false(pktlen > MCLBYTES))
1083 		return;
1084 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1085 	if (__predict_false(m == NULL))
1086 		return;
1087 	if (pktlen > MHLEN) {
1088 		MCLGET(m, M_DONTWAIT);
1089 		if (!(m->m_flags & M_EXT)) {
1090 			m_free(m);
1091 			return;
1092 		}
1093 	}
1094 	wh = mtod(m, struct ieee80211_frame *);
1095 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
1096 	    IEEE80211_FC0_SUBTYPE_BEACON;
1097 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1098 	*(uint16_t *)wh->i_dur = 0;
1099 	IEEE80211_ADDR_COPY(wh->i_addr1, etherbroadcastaddr);
1100 	IEEE80211_ADDR_COPY(wh->i_addr2, bss->macaddr);
1101 	IEEE80211_ADDR_COPY(wh->i_addr3, bss->macaddr);
1102 	*(uint16_t *)wh->i_seq = 0;
1103 	memcpy(&wh[1], (uint8_t *)&bss[1], letoh32(bss->ieslen));
1104 
1105 	/* Finalize mbuf. */
1106 	m->m_pkthdr.len = m->m_len = pktlen;
1107 
1108 	ni = ieee80211_find_rxnode(ic, wh);
1109 	rxi.rxi_flags = 0;
1110 	rxi.rxi_rssi = letoh32(bss->rssi);
1111 	rxi.rxi_tstamp = 0;
1112 	ieee80211_input(ifp, m, ni, &rxi);
1113 	/* Node is no longer needed. */
1114 	ieee80211_release_node(ic, ni);
1115 }
1116 
1117 void
1118 rsu_event_join_bss(struct rsu_softc *sc, uint8_t *buf, int len)
1119 {
1120 	struct ieee80211com *ic = &sc->sc_ic;
1121 	struct ieee80211_node *ni = ic->ic_bss;
1122 	struct r92s_event_join_bss *rsp;
1123 	int res;
1124 
1125 	if (__predict_false(len < sizeof(*rsp)))
1126 		return;
1127 	rsp = (struct r92s_event_join_bss *)buf;
1128 	res = (int)letoh32(rsp->join_res);
1129 
1130 	DPRINTF(("Rx join BSS event len=%d res=%d\n", len, res));
1131 	if (res <= 0) {
1132 		ic->ic_stats.is_rx_auth_fail++;
1133 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1134 		return;
1135 	}
1136 	DPRINTF(("associated with %s associd=%d\n",
1137 	    ether_sprintf(rsp->bss.macaddr), letoh32(rsp->associd)));
1138 
1139 	ni->ni_associd = letoh32(rsp->associd) | 0xc000;
1140 	if (ic->ic_flags & IEEE80211_F_WEPON)
1141 		ni->ni_flags |= IEEE80211_NODE_TXRXPROT;
1142 
1143 	ieee80211_new_state(ic, IEEE80211_S_RUN,
1144 	    IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
1145 }
1146 
1147 void
1148 rsu_rx_event(struct rsu_softc *sc, uint8_t code, uint8_t *buf, int len)
1149 {
1150 	struct ieee80211com *ic = &sc->sc_ic;
1151 	struct ifnet *ifp = &ic->ic_if;
1152 
1153 	DPRINTFN(4, ("Rx event code=%d len=%d\n", code, len));
1154 	switch (code) {
1155 	case R92S_EVT_SURVEY:
1156 		if (ic->ic_state == IEEE80211_S_SCAN)
1157 			rsu_event_survey(sc, buf, len);
1158 		break;
1159 	case R92S_EVT_SURVEY_DONE:
1160 		DPRINTF(("site survey pass %d done, found %d BSS\n",
1161 		    sc->scan_pass, letoh32(*(uint32_t *)buf)));
1162 		if (ic->ic_state != IEEE80211_S_SCAN)
1163 			break;	/* Ignore if not scanning. */
1164 		if (sc->scan_pass == 0 && ic->ic_des_esslen != 0) {
1165 			/* Schedule a directed scan for hidden APs. */
1166 			sc->scan_pass = 1;
1167 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1168 			break;
1169 		}
1170 		ieee80211_end_scan(ifp);
1171 		sc->scan_pass = 0;
1172 		break;
1173 	case R92S_EVT_JOIN_BSS:
1174 		if (ic->ic_state == IEEE80211_S_AUTH)
1175 			rsu_event_join_bss(sc, buf, len);
1176 		break;
1177 	case R92S_EVT_DEL_STA:
1178 		DPRINTF(("disassociated from %s\n", ether_sprintf(buf)));
1179 		if (ic->ic_state == IEEE80211_S_RUN &&
1180 		    IEEE80211_ADDR_EQ(ic->ic_bss->ni_bssid, buf))
1181 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1182 		break;
1183 	case R92S_EVT_WPS_PBC:
1184 		DPRINTF(("WPS PBC pushed.\n"));
1185 		break;
1186 	case R92S_EVT_FWDBG:
1187 		if (ifp->if_flags & IFF_DEBUG) {
1188 			buf[60] = '\0';
1189 			printf("FWDBG: %s\n", (char *)buf);
1190 		}
1191 		break;
1192 	}
1193 }
1194 
1195 void
1196 rsu_rx_multi_event(struct rsu_softc *sc, uint8_t *buf, int len)
1197 {
1198 	struct r92s_fw_cmd_hdr *cmd;
1199 	int cmdsz;
1200 
1201 	DPRINTFN(6, ("Rx events len=%d\n", len));
1202 
1203 	/* Skip Rx status. */
1204 	buf += sizeof(struct r92s_rx_stat);
1205 	len -= sizeof(struct r92s_rx_stat);
1206 
1207 	/* Process all events. */
1208 	for (;;) {
1209 		/* Check that command header fits. */
1210 		if (__predict_false(len < sizeof(*cmd)))
1211 			break;
1212 		cmd = (struct r92s_fw_cmd_hdr *)buf;
1213 		/* Check that command payload fits. */
1214 		cmdsz = letoh16(cmd->len);
1215 		if (__predict_false(len < sizeof(*cmd) + cmdsz))
1216 			break;
1217 
1218 		/* Process firmware event. */
1219 		rsu_rx_event(sc, cmd->code, (uint8_t *)&cmd[1], cmdsz);
1220 
1221 		if (!(cmd->seq & R92S_FW_CMD_MORE))
1222 			break;
1223 		buf += sizeof(*cmd) + cmdsz;
1224 		len -= sizeof(*cmd) + cmdsz;
1225 	}
1226 }
1227 
1228 int8_t
1229 rsu_get_rssi(struct rsu_softc *sc, int rate, void *physt)
1230 {
1231 	static const int8_t cckoff[] = { 14, -2, -20, -40 };
1232 	struct r92s_rx_phystat *phy;
1233 	struct r92s_rx_cck *cck;
1234 	uint8_t rpt;
1235 	int8_t rssi;
1236 
1237 	if (rate <= 3) {
1238 		cck = (struct r92s_rx_cck *)physt;
1239 		rpt = (cck->agc_rpt >> 6) & 0x3;
1240 		rssi = cck->agc_rpt & 0x3e;
1241 		rssi = cckoff[rpt] - rssi;
1242 	} else {	/* OFDM/HT. */
1243 		phy = (struct r92s_rx_phystat *)physt;
1244 		rssi = ((letoh32(phy->phydw1) >> 1) & 0x7f) - 106;
1245 	}
1246 	return (rssi);
1247 }
1248 
1249 void
1250 rsu_rx_frame(struct rsu_softc *sc, uint8_t *buf, int pktlen)
1251 {
1252 	struct ieee80211com *ic = &sc->sc_ic;
1253 	struct ifnet *ifp = &ic->ic_if;
1254 	struct ieee80211_rxinfo rxi;
1255 	struct ieee80211_frame *wh;
1256 	struct ieee80211_node *ni;
1257 	struct r92s_rx_stat *stat;
1258 	uint32_t rxdw0, rxdw3;
1259 	struct mbuf *m;
1260 	uint8_t rate;
1261 	int8_t rssi = 0;
1262 	int s, infosz;
1263 
1264 	stat = (struct r92s_rx_stat *)buf;
1265 	rxdw0 = letoh32(stat->rxdw0);
1266 	rxdw3 = letoh32(stat->rxdw3);
1267 
1268 	if (__predict_false(rxdw0 & R92S_RXDW0_CRCERR)) {
1269 		ifp->if_ierrors++;
1270 		return;
1271 	}
1272 	if (__predict_false(pktlen < sizeof(*wh) || pktlen > MCLBYTES)) {
1273 		ifp->if_ierrors++;
1274 		return;
1275 	}
1276 
1277 	rate = MS(rxdw3, R92S_RXDW3_RATE);
1278 	infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
1279 
1280 	/* Get RSSI from PHY status descriptor if present. */
1281 	if (infosz != 0)
1282 		rssi = rsu_get_rssi(sc, rate, &stat[1]);
1283 
1284 	DPRINTFN(5, ("Rx frame len=%d rate=%d infosz=%d rssi=%d\n",
1285 	    pktlen, rate, infosz, rssi));
1286 
1287 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1288 	if (__predict_false(m == NULL)) {
1289 		ifp->if_ierrors++;
1290 		return;
1291 	}
1292 	if (pktlen > MHLEN) {
1293 		MCLGET(m, M_DONTWAIT);
1294 		if (__predict_false(!(m->m_flags & M_EXT))) {
1295 			ifp->if_ierrors++;
1296 			m_freem(m);
1297 			return;
1298 		}
1299 	}
1300 	/* Finalize mbuf. */
1301 	/* Hardware does Rx TCP checksum offload. */
1302 	if (rxdw3 & R92S_RXDW3_TCPCHKVALID) {
1303 		if (__predict_true(rxdw3 & R92S_RXDW3_TCPCHKRPT))
1304 			m->m_pkthdr.csum_flags |= M_TCP_CSUM_IN_OK;
1305 		else
1306 			m->m_pkthdr.csum_flags |= M_TCP_CSUM_IN_BAD;
1307 	}
1308 	wh = (struct ieee80211_frame *)((uint8_t *)&stat[1] + infosz);
1309 	memcpy(mtod(m, uint8_t *), wh, pktlen);
1310 	m->m_pkthdr.len = m->m_len = pktlen;
1311 
1312 	s = splnet();
1313 #if NBPFILTER > 0
1314 	if (__predict_false(sc->sc_drvbpf != NULL)) {
1315 		struct rsu_rx_radiotap_header *tap = &sc->sc_rxtap;
1316 		struct mbuf mb;
1317 
1318 		tap->wr_flags = 0;
1319 		/* Map HW rate index to 802.11 rate. */
1320 		tap->wr_flags = 2;
1321 		if (!(rxdw3 & R92S_RXDW3_HTC)) {
1322 			switch (rate) {
1323 			/* CCK. */
1324 			case  0: tap->wr_rate =   2; break;
1325 			case  1: tap->wr_rate =   4; break;
1326 			case  2: tap->wr_rate =  11; break;
1327 			case  3: tap->wr_rate =  22; break;
1328 			/* OFDM. */
1329 			case  4: tap->wr_rate =  12; break;
1330 			case  5: tap->wr_rate =  18; break;
1331 			case  6: tap->wr_rate =  24; break;
1332 			case  7: tap->wr_rate =  36; break;
1333 			case  8: tap->wr_rate =  48; break;
1334 			case  9: tap->wr_rate =  72; break;
1335 			case 10: tap->wr_rate =  96; break;
1336 			case 11: tap->wr_rate = 108; break;
1337 			}
1338 		} else if (rate >= 12) {	/* MCS0~15. */
1339 			/* Bit 7 set means HT MCS instead of rate. */
1340 			tap->wr_rate = 0x80 | (rate - 12);
1341 		}
1342 		tap->wr_dbm_antsignal = rssi;
1343 		tap->wr_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
1344 		tap->wr_chan_flags = htole16(ic->ic_ibss_chan->ic_flags);
1345 
1346 		mb.m_data = (caddr_t)tap;
1347 		mb.m_len = sc->sc_rxtap_len;
1348 		mb.m_next = m;
1349 		mb.m_nextpkt = NULL;
1350 		mb.m_type = 0;
1351 		mb.m_flags = 0;
1352 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_IN);
1353 	}
1354 #endif
1355 
1356 	ni = ieee80211_find_rxnode(ic, wh);
1357 	rxi.rxi_flags = 0;
1358 	rxi.rxi_rssi = rssi;
1359 	rxi.rxi_tstamp = 0;	/* Unused. */
1360 	ieee80211_input(ifp, m, ni, &rxi);
1361 	/* Node is no longer needed. */
1362 	ieee80211_release_node(ic, ni);
1363 	splx(s);
1364 }
1365 
1366 void
1367 rsu_rx_multi_frame(struct rsu_softc *sc, uint8_t *buf, int len)
1368 {
1369 	struct r92s_rx_stat *stat;
1370 	uint32_t rxdw0;
1371 	int totlen, pktlen, infosz, npkts;
1372 
1373 	/* Get the number of encapsulated frames. */
1374 	stat = (struct r92s_rx_stat *)buf;
1375 	npkts = MS(letoh32(stat->rxdw2), R92S_RXDW2_PKTCNT);
1376 	DPRINTFN(6, ("Rx %d frames in one chunk\n", npkts));
1377 
1378 	/* Process all of them. */
1379 	while (npkts-- > 0) {
1380 		if (__predict_false(len < sizeof(*stat)))
1381 			break;
1382 		stat = (struct r92s_rx_stat *)buf;
1383 		rxdw0 = letoh32(stat->rxdw0);
1384 
1385 		pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN);
1386 		if (__predict_false(pktlen == 0))
1387 			break;
1388 
1389 		infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
1390 
1391 		/* Make sure everything fits in xfer. */
1392 		totlen = sizeof(*stat) + infosz + pktlen;
1393 		if (__predict_false(totlen > len))
1394 			break;
1395 
1396 		/* Process 802.11 frame. */
1397 		rsu_rx_frame(sc, buf, pktlen);
1398 
1399 		/* Next chunk is 128-byte aligned. */
1400 		totlen = (totlen + 127) & ~127;
1401 		buf += totlen;
1402 		len -= totlen;
1403 	}
1404 }
1405 
1406 void
1407 rsu_rxeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
1408 {
1409 	struct rsu_rx_data *data = priv;
1410 	struct rsu_softc *sc = data->sc;
1411 	struct r92s_rx_stat *stat;
1412 	int len;
1413 
1414 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
1415 		DPRINTF(("RX status=%d\n", status));
1416 		if (status == USBD_STALLED)
1417 			usbd_clear_endpoint_stall_async(data->pipe);
1418 		if (status != USBD_CANCELLED)
1419 			goto resubmit;
1420 		return;
1421 	}
1422 	usbd_get_xfer_status(xfer, NULL, NULL, &len, NULL);
1423 
1424 	if (__predict_false(len < sizeof(*stat))) {
1425 		DPRINTF(("xfer too short %d\n", len));
1426 		goto resubmit;
1427 	}
1428 	/* Determine if it is a firmware C2H event or an 802.11 frame. */
1429 	stat = (struct r92s_rx_stat *)data->buf;
1430 	if ((letoh32(stat->rxdw1) & 0x1ff) == 0x1ff)
1431 		rsu_rx_multi_event(sc, data->buf, len);
1432 	else
1433 		rsu_rx_multi_frame(sc, data->buf, len);
1434 
1435  resubmit:
1436 	/* Setup a new transfer. */
1437 	usbd_setup_xfer(xfer, data->pipe, data, data->buf, RSU_RXBUFSZ,
1438 	    USBD_SHORT_XFER_OK | USBD_NO_COPY, USBD_NO_TIMEOUT, rsu_rxeof);
1439 	(void)usbd_transfer(xfer);
1440 }
1441 
1442 void
1443 rsu_txeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
1444 {
1445 	struct rsu_tx_data *data = priv;
1446 	struct rsu_softc *sc = data->sc;
1447 	struct ifnet *ifp = &sc->sc_ic.ic_if;
1448 	int s;
1449 
1450 	s = splnet();
1451 	/* Put this Tx buffer back to our free list. */
1452 	TAILQ_INSERT_TAIL(&sc->tx_free_list, data, next);
1453 
1454 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
1455 		DPRINTF(("TX status=%d\n", status));
1456 		if (status == USBD_STALLED)
1457 			usbd_clear_endpoint_stall_async(data->pipe);
1458 		ifp->if_oerrors++;
1459 		splx(s);
1460 		return;
1461 	}
1462 	sc->sc_tx_timer = 0;
1463 	ifp->if_opackets++;
1464 
1465 	/* We just released a Tx buffer, notify Tx. */
1466 	if (ifp->if_flags & IFF_OACTIVE) {
1467 		ifp->if_flags &= ~IFF_OACTIVE;
1468 		rsu_start(ifp);
1469 	}
1470 	splx(s);
1471 }
1472 
1473 int
1474 rsu_tx(struct rsu_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
1475 {
1476 	struct ieee80211com *ic = &sc->sc_ic;
1477 	struct ieee80211_frame *wh;
1478 	struct ieee80211_key *k = NULL;
1479 	struct rsu_tx_data *data;
1480 	struct r92s_tx_desc *txd;
1481 	struct usbd_pipe *pipe;
1482 	uint16_t qos;
1483 	uint8_t type, qid, tid = 0;
1484 	int hasqos, xferlen, error;
1485 
1486 	wh = mtod(m, struct ieee80211_frame *);
1487 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1488 
1489 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1490 		k = ieee80211_get_txkey(ic, wh, ni);
1491 		if ((m = ieee80211_encrypt(ic, m, k)) == NULL)
1492 			return (ENOBUFS);
1493 		wh = mtod(m, struct ieee80211_frame *);
1494 	}
1495 	if ((hasqos = ieee80211_has_qos(wh))) {
1496 		qos = ieee80211_get_qos(wh);
1497 		tid = qos & IEEE80211_QOS_TID;
1498 		qid = rsu_ac2qid[ieee80211_up_to_ac(ic, tid)];
1499 	} else
1500 		qid = RSU_QID_BE;
1501 
1502 	/* Get the USB pipe to use for this queue id. */
1503 	pipe = sc->pipe[sc->qid2idx[qid]];
1504 
1505 	/* Grab a Tx buffer from our free list. */
1506 	data = TAILQ_FIRST(&sc->tx_free_list);
1507 	TAILQ_REMOVE(&sc->tx_free_list, data, next);
1508 
1509 	/* Fill Tx descriptor. */
1510 	txd = (struct r92s_tx_desc *)data->buf;
1511 	memset(txd, 0, sizeof(*txd));
1512 
1513 	txd->txdw0 |= htole32(
1514 	    SM(R92S_TXDW0_PKTLEN, m->m_pkthdr.len) |
1515 	    SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
1516 	    R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
1517 
1518 	txd->txdw1 |= htole32(
1519 	    SM(R92S_TXDW1_MACID, R92S_MACID_BSS) |
1520 	    SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_BE));
1521 	if (!hasqos)
1522 		txd->txdw1 |= htole32(R92S_TXDW1_NONQOS);
1523 #ifdef notyet
1524 	if (k != NULL) {
1525 		switch (k->k_cipher) {
1526 		case IEEE80211_CIPHER_WEP40:
1527 		case IEEE80211_CIPHER_WEP104:
1528 			cipher = R92S_TXDW1_CIPHER_WEP;
1529 			break;
1530 		case IEEE80211_CIPHER_TKIP:
1531 			cipher = R92S_TXDW1_CIPHER_TKIP;
1532 			break;
1533 		case IEEE80211_CIPHER_CCMP:
1534 			cipher = R92S_TXDW1_CIPHER_AES;
1535 			break;
1536 		default:
1537 			cipher = R92S_TXDW1_CIPHER_NONE;
1538 		}
1539 		txd->txdw1 |= htole32(
1540 		    SM(R92S_TXDW1_CIPHER, cipher) |
1541 		    SM(R92S_TXDW1_KEYIDX, k->k_id));
1542 	}
1543 #endif
1544 	txd->txdw2 |= htole32(R92S_TXDW2_BK);
1545 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1546 		txd->txdw2 |= htole32(R92S_TXDW2_BMCAST);
1547 	/*
1548 	 * Firmware will use and increment the sequence number for the
1549 	 * specified TID.
1550 	 */
1551 	txd->txdw3 |= htole32(SM(R92S_TXDW3_SEQ, tid));
1552 
1553 #if NBPFILTER > 0
1554 	if (__predict_false(sc->sc_drvbpf != NULL)) {
1555 		struct rsu_tx_radiotap_header *tap = &sc->sc_txtap;
1556 		struct mbuf mb;
1557 
1558 		tap->wt_flags = 0;
1559 		tap->wt_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
1560 		tap->wt_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
1561 
1562 		mb.m_data = (caddr_t)tap;
1563 		mb.m_len = sc->sc_txtap_len;
1564 		mb.m_next = m;
1565 		mb.m_nextpkt = NULL;
1566 		mb.m_type = 0;
1567 		mb.m_flags = 0;
1568 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_OUT);
1569 	}
1570 #endif
1571 
1572 	xferlen = sizeof(*txd) + m->m_pkthdr.len;
1573 	m_copydata(m, 0, m->m_pkthdr.len, (caddr_t)&txd[1]);
1574 	m_freem(m);
1575 
1576 	data->pipe = pipe;
1577 	usbd_setup_xfer(data->xfer, pipe, data, data->buf, xferlen,
1578 	    USBD_FORCE_SHORT_XFER | USBD_NO_COPY, RSU_TX_TIMEOUT,
1579 	    rsu_txeof);
1580 	error = usbd_transfer(data->xfer);
1581 	if (__predict_false(error != USBD_IN_PROGRESS && error != 0)) {
1582 		/* Put this Tx buffer back to our free list. */
1583 		TAILQ_INSERT_TAIL(&sc->tx_free_list, data, next);
1584 		return (error);
1585 	}
1586 	ieee80211_release_node(ic, ni);
1587 	return (0);
1588 }
1589 
1590 /* ARGSUSED */
1591 int
1592 rsu_send_mgmt(struct ieee80211com *ic, struct ieee80211_node *ni, int type,
1593     int arg1, int arg2)
1594 {
1595 	return (EOPNOTSUPP);
1596 }
1597 
1598 void
1599 rsu_start(struct ifnet *ifp)
1600 {
1601 	struct rsu_softc *sc = ifp->if_softc;
1602 	struct ieee80211com *ic = &sc->sc_ic;
1603 	struct ieee80211_node *ni;
1604 	struct mbuf *m;
1605 
1606 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
1607 		return;
1608 
1609 	for (;;) {
1610 		if (TAILQ_EMPTY(&sc->tx_free_list)) {
1611 			ifp->if_flags |= IFF_OACTIVE;
1612 			break;
1613 		}
1614 		if (ic->ic_state != IEEE80211_S_RUN)
1615 			break;
1616 
1617 		/* Encapsulate and send data frames. */
1618 		IFQ_DEQUEUE(&ifp->if_snd, m);
1619 		if (m == NULL)
1620 			break;
1621 #if NBPFILTER > 0
1622 		if (ifp->if_bpf != NULL)
1623 			bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
1624 #endif
1625 		if ((m = ieee80211_encap(ifp, m, &ni)) == NULL)
1626 			continue;
1627 
1628 #if NBPFILTER > 0
1629 		if (ic->ic_rawbpf != NULL)
1630 			bpf_mtap(ic->ic_rawbpf, m, BPF_DIRECTION_OUT);
1631 #endif
1632 		if (rsu_tx(sc, m, ni) != 0) {
1633 			ieee80211_release_node(ic, ni);
1634 			ifp->if_oerrors++;
1635 			continue;
1636 		}
1637 
1638 		sc->sc_tx_timer = 5;
1639 		ifp->if_timer = 1;
1640 	}
1641 }
1642 
1643 void
1644 rsu_watchdog(struct ifnet *ifp)
1645 {
1646 	struct rsu_softc *sc = ifp->if_softc;
1647 
1648 	ifp->if_timer = 0;
1649 
1650 	if (sc->sc_tx_timer > 0) {
1651 		if (--sc->sc_tx_timer == 0) {
1652 			printf("%s: device timeout\n", sc->sc_dev.dv_xname);
1653 			/* rsu_init(ifp); XXX needs a process context! */
1654 			ifp->if_oerrors++;
1655 			return;
1656 		}
1657 		ifp->if_timer = 1;
1658 	}
1659 	ieee80211_watchdog(ifp);
1660 }
1661 
1662 int
1663 rsu_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1664 {
1665 	struct rsu_softc *sc = ifp->if_softc;
1666 	struct ieee80211com *ic = &sc->sc_ic;
1667 	struct ifaddr *ifa;
1668 	struct ifreq *ifr;
1669 	int s, error = 0;
1670 
1671 	if (usbd_is_dying(sc->sc_udev))
1672 		return ENXIO;
1673 
1674 	usbd_ref_incr(sc->sc_udev);
1675 
1676 	s = splnet();
1677 
1678 	switch (cmd) {
1679 	case SIOCSIFADDR:
1680 		ifa = (struct ifaddr *)data;
1681 		ifp->if_flags |= IFF_UP;
1682 		if (ifa->ifa_addr->sa_family == AF_INET)
1683 			arp_ifinit(&ic->ic_ac, ifa);
1684 		/* FALLTHROUGH */
1685 	case SIOCSIFFLAGS:
1686 		if (ifp->if_flags & IFF_UP) {
1687 			if (!(ifp->if_flags & IFF_RUNNING))
1688 				rsu_init(ifp);
1689 		} else {
1690 			if (ifp->if_flags & IFF_RUNNING)
1691 				rsu_stop(ifp);
1692 		}
1693 		break;
1694 	case SIOCADDMULTI:
1695 	case SIOCDELMULTI:
1696 		ifr = (struct ifreq *)data;
1697 		error = (cmd == SIOCADDMULTI) ?
1698 		    ether_addmulti(ifr, &ic->ic_ac) :
1699 		    ether_delmulti(ifr, &ic->ic_ac);
1700 		if (error == ENETRESET)
1701 			error = 0;
1702 		break;
1703 	default:
1704 		error = ieee80211_ioctl(ifp, cmd, data);
1705 	}
1706 
1707 	if (error == ENETRESET) {
1708 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1709 		    (IFF_UP | IFF_RUNNING)) {
1710 			rsu_stop(ifp);
1711 			rsu_init(ifp);
1712 		}
1713 		error = 0;
1714 	}
1715 	splx(s);
1716 
1717 	usbd_ref_decr(sc->sc_udev);
1718 
1719 	return (error);
1720 }
1721 
1722 /*
1723  * Power on sequence for A-cut adapters.
1724  */
1725 void
1726 rsu_power_on_acut(struct rsu_softc *sc)
1727 {
1728 	uint32_t reg;
1729 
1730 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
1731 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
1732 
1733 	/* Enable AFE macro block's bandgap and Mbias. */
1734 	rsu_write_1(sc, R92S_AFE_MISC,
1735 	    rsu_read_1(sc, R92S_AFE_MISC) |
1736 	    R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN);
1737 	/* Enable LDOA15 block. */
1738 	rsu_write_1(sc, R92S_LDOA15_CTRL,
1739 	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
1740 
1741 	rsu_write_1(sc, R92S_SPS1_CTRL,
1742 	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_LDEN);
1743 	usbd_delay_ms(sc->sc_udev, 2);
1744 	/* Enable switch regulator block. */
1745 	rsu_write_1(sc, R92S_SPS1_CTRL,
1746 	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_SWEN);
1747 
1748 	rsu_write_4(sc, R92S_SPS1_CTRL, 0x00a7b267);
1749 
1750 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1751 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
1752 
1753 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1754 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
1755 
1756 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1757 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x90);
1758 
1759 	/* Enable AFE clock. */
1760 	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
1761 	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
1762 	/* Enable AFE PLL macro block. */
1763 	rsu_write_1(sc, R92S_AFE_PLL_CTRL,
1764 	    rsu_read_1(sc, R92S_AFE_PLL_CTRL) | 0x11);
1765 	/* Attach AFE PLL to MACTOP/BB. */
1766 	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
1767 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
1768 
1769 	/* Switch to 40MHz clock instead of 80MHz. */
1770 	rsu_write_2(sc, R92S_SYS_CLKR,
1771 	    rsu_read_2(sc, R92S_SYS_CLKR) & ~R92S_SYS_CLKSEL);
1772 
1773 	/* Enable MAC clock. */
1774 	rsu_write_2(sc, R92S_SYS_CLKR,
1775 	    rsu_read_2(sc, R92S_SYS_CLKR) |
1776 	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
1777 
1778 	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
1779 
1780 	/* Enable digital core and IOREG R/W. */
1781 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1782 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
1783 
1784 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1785 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
1786 
1787 	/* Switch the control path to firmware. */
1788 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
1789 	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
1790 	rsu_write_2(sc, R92S_SYS_CLKR, reg);
1791 
1792 	rsu_write_2(sc, R92S_CR, 0x37fc);
1793 
1794 	/* Fix USB RX FIFO issue. */
1795 	rsu_write_1(sc, 0xfe5c,
1796 	    rsu_read_1(sc, 0xfe5c) | 0x80);
1797 	rsu_write_1(sc, 0x00ab,
1798 	    rsu_read_1(sc, 0x00ab) | 0xc0);
1799 
1800 	rsu_write_1(sc, R92S_SYS_CLKR,
1801 	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
1802 }
1803 
1804 /*
1805  * Power on sequence for B-cut and C-cut adapters.
1806  */
1807 void
1808 rsu_power_on_bcut(struct rsu_softc *sc)
1809 {
1810 	uint32_t reg;
1811 	int ntries;
1812 
1813 	/* Prevent eFuse leakage. */
1814 	rsu_write_1(sc, 0x37, 0xb0);
1815 	usbd_delay_ms(sc->sc_udev, 10);
1816 	rsu_write_1(sc, 0x37, 0x30);
1817 
1818 	/* Switch the control path to hardware. */
1819 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
1820 	if (reg & R92S_FWHW_SEL) {
1821 		rsu_write_2(sc, R92S_SYS_CLKR,
1822 		    reg & ~(R92S_SWHW_SEL | R92S_FWHW_SEL));
1823 	}
1824 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1825 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) & ~0x8c);
1826 	DELAY(1000);
1827 
1828 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
1829 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
1830 
1831 	reg = rsu_read_1(sc, R92S_AFE_MISC);
1832 	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN);
1833 	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN |
1834 	    R92S_AFE_MISC_MBEN | R92S_AFE_MISC_I32_EN);
1835 
1836 	/* Enable PLL. */
1837 	rsu_write_1(sc, R92S_LDOA15_CTRL,
1838 	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
1839 
1840 	rsu_write_1(sc, R92S_LDOV12D_CTRL,
1841 	    rsu_read_1(sc, R92S_LDOV12D_CTRL) | R92S_LDV12_EN);
1842 
1843 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1844 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
1845 
1846 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1847 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
1848 
1849 	/* Support 64KB IMEM. */
1850 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1851 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x97);
1852 
1853 	/* Enable AFE clock. */
1854 	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
1855 	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
1856 	/* Enable AFE PLL macro block. */
1857 	reg = rsu_read_1(sc, R92S_AFE_PLL_CTRL);
1858 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
1859 	DELAY(500);
1860 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x51);
1861 	DELAY(500);
1862 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
1863 	DELAY(500);
1864 
1865 	/* Attach AFE PLL to MACTOP/BB. */
1866 	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
1867 	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
1868 
1869 	/* Switch to 40MHz clock. */
1870 	rsu_write_1(sc, R92S_SYS_CLKR, 0x00);
1871 	/* Disable CPU clock and 80MHz SSC. */
1872 	rsu_write_1(sc, R92S_SYS_CLKR,
1873 	    rsu_read_1(sc, R92S_SYS_CLKR) | 0xa0);
1874 	/* Enable MAC clock. */
1875 	rsu_write_2(sc, R92S_SYS_CLKR,
1876 	    rsu_read_2(sc, R92S_SYS_CLKR) |
1877 	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
1878 
1879 	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
1880 
1881 	/* Enable digital core and IOREG R/W. */
1882 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1883 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
1884 
1885 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1886 	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
1887 
1888 	/* Switch the control path to firmware. */
1889 	reg = rsu_read_2(sc, R92S_SYS_CLKR);
1890 	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
1891 	rsu_write_2(sc, R92S_SYS_CLKR, reg);
1892 
1893 	rsu_write_2(sc, R92S_CR, 0x37fc);
1894 
1895 	/* Fix USB RX FIFO issue. */
1896 	rsu_write_1(sc, 0xfe5c,
1897 	    rsu_read_1(sc, 0xfe5c) | 0x80);
1898 
1899 	rsu_write_1(sc, R92S_SYS_CLKR,
1900 	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
1901 
1902 	rsu_write_1(sc, 0xfe1c, 0x80);
1903 
1904 	/* Make sure TxDMA is ready to download firmware. */
1905 	for (ntries = 0; ntries < 20; ntries++) {
1906 		reg = rsu_read_1(sc, R92S_TCR);
1907 		if ((reg & (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) ==
1908 		    (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT))
1909 			break;
1910 		DELAY(5);
1911 	}
1912 	if (ntries == 20) {
1913 		/* Reset TxDMA. */
1914 		reg = rsu_read_1(sc, R92S_CR);
1915 		rsu_write_1(sc, R92S_CR, reg & ~R92S_CR_TXDMA_EN);
1916 		DELAY(2);
1917 		rsu_write_1(sc, R92S_CR, reg | R92S_CR_TXDMA_EN);
1918 	}
1919 }
1920 
1921 void
1922 rsu_power_off(struct rsu_softc *sc)
1923 {
1924 	/* Turn RF off. */
1925 	rsu_write_1(sc, R92S_RF_CTRL, 0x00);
1926 	usbd_delay_ms(sc->sc_udev, 5);
1927 
1928 	/* Turn MAC off. */
1929 	/* Switch control path. */
1930 	rsu_write_1(sc, R92S_SYS_CLKR + 1, 0x38);
1931 	/* Reset MACTOP. */
1932 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x70);
1933 	rsu_write_1(sc, R92S_PMC_FSM, 0x06);
1934 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 0, 0xf9);
1935 	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, 0xe8);
1936 
1937 	/* Disable AFE PLL. */
1938 	rsu_write_1(sc, R92S_AFE_PLL_CTRL, 0x00);
1939 	/* Disable A15V. */
1940 	rsu_write_1(sc, R92S_LDOA15_CTRL, 0x54);
1941 	/* Disable eFuse 1.2V. */
1942 	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x50);
1943 	rsu_write_1(sc, R92S_LDOV12D_CTRL, 0x24);
1944 	/* Enable AFE macro block's bandgap and Mbias. */
1945 	rsu_write_1(sc, R92S_AFE_MISC, 0x30);
1946 	/* Disable 1.6V LDO. */
1947 	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x56);
1948 	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x43);
1949 }
1950 
1951 int
1952 rsu_fw_loadsection(struct rsu_softc *sc, uint8_t *buf, int len)
1953 {
1954 	struct rsu_tx_data *data;
1955 	struct r92s_tx_desc *txd;
1956 	struct usbd_pipe *pipe;
1957 	int mlen, error;
1958 
1959 	data = sc->fwcmd_data;
1960 	pipe = sc->pipe[sc->qid2idx[RSU_QID_VO]];
1961 	txd = (struct r92s_tx_desc *)data->buf;
1962 	while (len > 0) {
1963 		memset(txd, 0, sizeof(*txd));
1964 		if (len <= RSU_TXBUFSZ - sizeof(*txd)) {
1965 			/* Last chunk. */
1966 			txd->txdw0 |= htole32(R92S_TXDW0_LINIP);
1967 			mlen = len;
1968 		} else
1969 			mlen = RSU_TXBUFSZ - sizeof(*txd);
1970 		txd->txdw0 |= htole32(SM(R92S_TXDW0_PKTLEN, mlen));
1971 		memcpy(&txd[1], buf, mlen);
1972 
1973 		usbd_setup_xfer(data->xfer, pipe, NULL, data->buf,
1974 		    sizeof(*txd) + mlen,
1975 		    USBD_SHORT_XFER_OK | USBD_NO_COPY | USBD_SYNCHRONOUS,
1976 		    RSU_TX_TIMEOUT, NULL);
1977 		error = usbd_transfer(data->xfer);
1978 		if (error != 0)
1979 			return (error);
1980 		buf += mlen;
1981 		len -= mlen;
1982 	}
1983 	return (0);
1984 }
1985 
1986 int
1987 rsu_load_firmware(struct rsu_softc *sc)
1988 {
1989 	struct ieee80211com *ic = &sc->sc_ic;
1990 	struct r92s_fw_hdr *hdr;
1991 	struct r92s_fw_priv *dmem;
1992 	uint8_t *imem, *emem;
1993 	int imemsz, ememsz;
1994 	u_char *fw;
1995 	size_t size;
1996 	uint32_t reg;
1997 	int ntries, error;
1998 
1999 	/* Read firmware image from the filesystem. */
2000 	if ((error = loadfirmware("rsu-rtl8712fw", &fw, &size)) != 0) {
2001 		printf("%s: failed loadfirmware of file %s (error %d)\n",
2002 		    sc->sc_dev.dv_xname, "rsu-rtl8712fw", error);
2003 		return (error);
2004 	}
2005 	if (size < sizeof(*hdr)) {
2006 		printf("%s: firmware too short\n", sc->sc_dev.dv_xname);
2007 		error = EINVAL;
2008 		goto fail;
2009 	}
2010 	hdr = (struct r92s_fw_hdr *)fw;
2011 	if (hdr->signature != htole16(0x8712) &&
2012 	    hdr->signature != htole16(0x8192)) {
2013 		printf("%s: invalid firmware signature 0x%x\n",
2014 		    sc->sc_dev.dv_xname, letoh16(hdr->signature));
2015 		error = EINVAL;
2016 		goto fail;
2017 	}
2018 	DPRINTF(("FW V%d %02x-%02x %02x:%02x\n", letoh16(hdr->version),
2019 	    hdr->month, hdr->day, hdr->hour, hdr->minute));
2020 
2021 	/* Make sure that driver and firmware are in sync. */
2022 	if (hdr->privsz != htole32(sizeof(*dmem))) {
2023 		printf("%s: unsupported firmware image\n",
2024 		    sc->sc_dev.dv_xname);
2025 		error = EINVAL;
2026 		goto fail;
2027 	}
2028 	/* Get FW sections sizes. */
2029 	imemsz = letoh32(hdr->imemsz);
2030 	ememsz = letoh32(hdr->sramsz);
2031 	/* Check that all FW sections fit in image. */
2032 	if (size < sizeof(*hdr) + imemsz + ememsz) {
2033 		printf("%s: firmware too short\n", sc->sc_dev.dv_xname);
2034 		error = EINVAL;
2035 		goto fail;
2036 	}
2037 	imem = (uint8_t *)&hdr[1];
2038 	emem = imem + imemsz;
2039 
2040 	/* Load IMEM section. */
2041 	error = rsu_fw_loadsection(sc, imem, imemsz);
2042 	if (error != 0) {
2043 		printf("%s: could not load firmware section %s\n",
2044 		    sc->sc_dev.dv_xname, "IMEM");
2045 		goto fail;
2046 	}
2047 	/* Wait for load to complete. */
2048 	for (ntries = 0; ntries < 10; ntries++) {
2049 		reg = rsu_read_2(sc, R92S_TCR);
2050 		if (reg & R92S_TCR_IMEM_CODE_DONE)
2051 			break;
2052 		DELAY(10);
2053 	}
2054 	if (ntries == 10 || !(reg & R92S_TCR_IMEM_CHK_RPT)) {
2055 		printf("%s: timeout waiting for %s transfer\n",
2056 		    sc->sc_dev.dv_xname, "IMEM");
2057 		error = ETIMEDOUT;
2058 		goto fail;
2059 	}
2060 
2061 	/* Load EMEM section. */
2062 	error = rsu_fw_loadsection(sc, emem, ememsz);
2063 	if (error != 0) {
2064 		printf("%s: could not load firmware section %s\n",
2065 		    sc->sc_dev.dv_xname, "EMEM");
2066 		goto fail;
2067 	}
2068 	/* Wait for load to complete. */
2069 	for (ntries = 0; ntries < 10; ntries++) {
2070 		reg = rsu_read_2(sc, R92S_TCR);
2071 		if (reg & R92S_TCR_EMEM_CODE_DONE)
2072 			break;
2073 		DELAY(10);
2074 	}
2075 	if (ntries == 10 || !(reg & R92S_TCR_EMEM_CHK_RPT)) {
2076 		printf("%s: timeout waiting for %s transfer\n",
2077 		    sc->sc_dev.dv_xname, "EMEM");
2078 		error = ETIMEDOUT;
2079 		goto fail;
2080 	}
2081 
2082 	/* Enable CPU. */
2083 	rsu_write_1(sc, R92S_SYS_CLKR,
2084 	    rsu_read_1(sc, R92S_SYS_CLKR) | R92S_SYS_CPU_CLKSEL);
2085 	if (!(rsu_read_1(sc, R92S_SYS_CLKR) & R92S_SYS_CPU_CLKSEL)) {
2086 		printf("%s: could not enable system clock\n",
2087 		    sc->sc_dev.dv_xname);
2088 		error = EIO;
2089 		goto fail;
2090 	}
2091 	rsu_write_2(sc, R92S_SYS_FUNC_EN,
2092 	    rsu_read_2(sc, R92S_SYS_FUNC_EN) | R92S_FEN_CPUEN);
2093 	if (!(rsu_read_2(sc, R92S_SYS_FUNC_EN) & R92S_FEN_CPUEN)) {
2094 		printf("%s: could not enable microcontroller\n",
2095 		    sc->sc_dev.dv_xname);
2096 		error = EIO;
2097 		goto fail;
2098 	}
2099 	/* Wait for CPU to initialize. */
2100 	for (ntries = 0; ntries < 100; ntries++) {
2101 		if (rsu_read_2(sc, R92S_TCR) & R92S_TCR_IMEM_RDY)
2102 			break;
2103 		DELAY(1000);
2104 	}
2105 	if (ntries == 100) {
2106 		printf("%s: timeout waiting for microcontroller\n",
2107 		    sc->sc_dev.dv_xname);
2108 		error = ETIMEDOUT;
2109 		goto fail;
2110 	}
2111 
2112 	/* Update DMEM section before loading. */
2113 	dmem = &hdr->priv;
2114 	memset(dmem, 0, sizeof(*dmem));
2115 	dmem->hci_sel = R92S_HCI_SEL_USB | R92S_HCI_SEL_8172;
2116 	dmem->nendpoints = sc->npipes;
2117 	dmem->rf_config = 0x12;	/* 1T2R */
2118 	dmem->vcs_type = R92S_VCS_TYPE_AUTO;
2119 	dmem->vcs_mode = R92S_VCS_MODE_RTS_CTS;
2120 	dmem->bw40_en = (ic->ic_htcaps & IEEE80211_HTCAP_CBW20_40) != 0;
2121 	dmem->turbo_mode = 1;
2122 	/* Load DMEM section. */
2123 	error = rsu_fw_loadsection(sc, (uint8_t *)dmem, sizeof(*dmem));
2124 	if (error != 0) {
2125 		printf("%s: could not load firmware section %s\n",
2126 		    sc->sc_dev.dv_xname, "DMEM");
2127 		goto fail;
2128 	}
2129 	/* Wait for load to complete. */
2130 	for (ntries = 0; ntries < 100; ntries++) {
2131 		if (rsu_read_2(sc, R92S_TCR) & R92S_TCR_DMEM_CODE_DONE)
2132 			break;
2133 		DELAY(1000);
2134 	}
2135 	if (ntries == 100) {
2136 		printf("%s: timeout waiting for %s transfer\n",
2137 		    sc->sc_dev.dv_xname, "DMEM");
2138 		error = ETIMEDOUT;
2139 		goto fail;
2140 	}
2141 	/* Wait for firmware readiness. */
2142 	for (ntries = 0; ntries < 60; ntries++) {
2143 		if (!(rsu_read_2(sc, R92S_TCR) & R92S_TCR_FWRDY))
2144 			break;
2145 		DELAY(1000);
2146 	}
2147 	if (ntries == 60) {
2148 		printf("%s: timeout waiting for firmware readiness\n",
2149 		    sc->sc_dev.dv_xname);
2150 		error = ETIMEDOUT;
2151 		goto fail;
2152 	}
2153  fail:
2154 	free(fw, M_DEVBUF, 0);
2155 	return (error);
2156 }
2157 
2158 int
2159 rsu_init(struct ifnet *ifp)
2160 {
2161 	struct rsu_softc *sc = ifp->if_softc;
2162 	struct ieee80211com *ic = &sc->sc_ic;
2163 	struct r92s_set_pwr_mode cmd;
2164 	struct rsu_rx_data *data;
2165 	int i, error;
2166 
2167 	/* Init host async commands ring. */
2168 	sc->cmdq.cur = sc->cmdq.next = sc->cmdq.queued = 0;
2169 
2170 	/* Allocate Tx/Rx buffers. */
2171 	error = rsu_alloc_rx_list(sc);
2172 	if (error != 0) {
2173 		printf("%s: could not allocate Rx buffers\n",
2174 		    sc->sc_dev.dv_xname);
2175 		goto fail;
2176 	}
2177 	error = rsu_alloc_tx_list(sc);
2178 	if (error != 0) {
2179 		printf("%s: could not allocate Tx buffers\n",
2180 		    sc->sc_dev.dv_xname);
2181 		goto fail;
2182 	}
2183 	/* Reserve one Tx buffer for firmware commands. */
2184 	sc->fwcmd_data = TAILQ_FIRST(&sc->tx_free_list);
2185 	TAILQ_REMOVE(&sc->tx_free_list, sc->fwcmd_data, next);
2186 
2187 	/* Power on adapter. */
2188 	if (sc->cut == 1)
2189 		rsu_power_on_acut(sc);
2190 	else
2191 		rsu_power_on_bcut(sc);
2192 	/* Load firmware. */
2193 	error = rsu_load_firmware(sc);
2194 	if (error != 0)
2195 		goto fail;
2196 
2197 	/* Enable Rx TCP checksum offload. */
2198 	rsu_write_4(sc, R92S_RCR,
2199 	    rsu_read_4(sc, R92S_RCR) | 0x04000000);
2200 	/* Append PHY status. */
2201 	rsu_write_4(sc, R92S_RCR,
2202 	    rsu_read_4(sc, R92S_RCR) | 0x02000000);
2203 
2204 	rsu_write_4(sc, R92S_CR,
2205 	    rsu_read_4(sc, R92S_CR) & ~0xff000000);
2206 
2207 	/* Use 128 bytes pages. */
2208 	rsu_write_1(sc, 0x00b5,
2209 	    rsu_read_1(sc, 0x00b5) | 0x01);
2210 	/* Enable USB Rx aggregation. */
2211 	rsu_write_1(sc, 0x00bd,
2212 	    rsu_read_1(sc, 0x00bd) | 0x80);
2213 	/* Set USB Rx aggregation threshold. */
2214 	rsu_write_1(sc, 0x00d9, 0x01);
2215 	/* Set USB Rx aggregation timeout (1.7ms/4). */
2216 	rsu_write_1(sc, 0xfe5b, 0x04);
2217 	/* Fix USB Rx FIFO issue. */
2218 	rsu_write_1(sc, 0xfe5c,
2219 	    rsu_read_1(sc, 0xfe5c) | 0x80);
2220 
2221 	/* Set MAC address. */
2222 	IEEE80211_ADDR_COPY(ic->ic_myaddr, LLADDR(ifp->if_sadl));
2223 	rsu_write_region_1(sc, R92S_MACID, ic->ic_myaddr, IEEE80211_ADDR_LEN);
2224 
2225 	/* Queue Rx xfers (XXX C2H pipe for 11-pipe configurations?) */
2226 	for (i = 0; i < RSU_RX_LIST_COUNT; i++) {
2227 		data = &sc->rx_data[i];
2228 
2229 		data->pipe = sc->pipe[sc->qid2idx[RSU_QID_RXOFF]];
2230 		usbd_setup_xfer(data->xfer, data->pipe, data, data->buf,
2231 		    RSU_RXBUFSZ, USBD_SHORT_XFER_OK | USBD_NO_COPY,
2232 		    USBD_NO_TIMEOUT, rsu_rxeof);
2233 		error = usbd_transfer(data->xfer);
2234 		if (error != 0 && error != USBD_IN_PROGRESS)
2235 			goto fail;
2236 	}
2237 
2238 	/* NB: it really takes that long for firmware to boot. */
2239 	usbd_delay_ms(sc->sc_udev, 1500);
2240 
2241 	DPRINTF(("setting MAC address to %s\n", ether_sprintf(ic->ic_myaddr)));
2242 	error = rsu_fw_cmd(sc, R92S_CMD_SET_MAC_ADDRESS, ic->ic_myaddr,
2243 	    IEEE80211_ADDR_LEN);
2244 	if (error != 0) {
2245 		printf("%s: could not set MAC address\n", sc->sc_dev.dv_xname);
2246 		goto fail;
2247 	}
2248 
2249 	rsu_write_1(sc, R92S_USB_HRPWM,
2250 	    R92S_USB_HRPWM_PS_ST_ACTIVE | R92S_USB_HRPWM_PS_ALL_ON);
2251 
2252 	memset(&cmd, 0, sizeof(cmd));
2253 	cmd.mode = R92S_PS_MODE_ACTIVE;
2254 	DPRINTF(("setting ps mode to %d\n", cmd.mode));
2255 	error = rsu_fw_cmd(sc, R92S_CMD_SET_PWR_MODE, &cmd, sizeof(cmd));
2256 	if (error != 0) {
2257 		printf("%s: could not set PS mode\n", sc->sc_dev.dv_xname);
2258 		goto fail;
2259 	}
2260 
2261 	if (ic->ic_htcaps & IEEE80211_HTCAP_CBW20_40) {
2262 		/* Enable 40MHz mode. */
2263 		error = rsu_fw_iocmd(sc,
2264 		    SM(R92S_IOCMD_CLASS, 0xf4) |
2265 		    SM(R92S_IOCMD_INDEX, 0x00) |
2266 		    SM(R92S_IOCMD_VALUE, 0x0007));
2267 		if (error != 0) {
2268 			printf("%s: could not enable 40MHz mode\n",
2269 			    sc->sc_dev.dv_xname);
2270 			goto fail;
2271 		}
2272 	}
2273 
2274 	/* Set default channel. */
2275 	ic->ic_bss->ni_chan = ic->ic_ibss_chan;
2276 
2277 	/* We're ready to go. */
2278 	ifp->if_flags &= ~IFF_OACTIVE;
2279 	ifp->if_flags |= IFF_RUNNING;
2280 
2281 #ifdef notyet
2282 	if (ic->ic_flags & IEEE80211_F_WEPON) {
2283 		/* Install WEP keys. */
2284 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
2285 			rsu_set_key(ic, NULL, &ic->ic_nw_keys[i]);
2286 		rsu_wait_async(sc);
2287 	}
2288 #endif
2289 
2290 	sc->scan_pass = 0;
2291 	ieee80211_begin_scan(ifp);
2292 	return (0);
2293  fail:
2294 	rsu_stop(ifp);
2295 	return (error);
2296 }
2297 
2298 void
2299 rsu_stop(struct ifnet *ifp)
2300 {
2301 	struct rsu_softc *sc = ifp->if_softc;
2302 	struct ieee80211com *ic = &sc->sc_ic;
2303 	int i, s;
2304 
2305 	sc->sc_tx_timer = 0;
2306 	ifp->if_timer = 0;
2307 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2308 
2309 	/* In case we were scanning, release the scan "lock". */
2310 	ic->ic_scan_lock = IEEE80211_SCAN_UNLOCKED;
2311 
2312 	s = splusb();
2313 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2314 	/* Wait for all async commands to complete. */
2315 	rsu_wait_async(sc);
2316 	splx(s);
2317 
2318 	timeout_del(&sc->calib_to);
2319 
2320 	/* Power off adapter. */
2321 	rsu_power_off(sc);
2322 
2323 	/* Abort Tx/Rx. */
2324 	for (i = 0; i < sc->npipes; i++)
2325 		usbd_abort_pipe(sc->pipe[i]);
2326 
2327 	/* Free Tx/Rx buffers. */
2328 	rsu_free_tx_list(sc);
2329 	rsu_free_rx_list(sc);
2330 }
2331