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