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