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