if_rsu.c revision 287763
1/*	$OpenBSD: if_rsu.c,v 1.17 2013/04/15 09:23:01 mglocker Exp $	*/
2
3/*-
4 * Copyright (c) 2010 Damien Bergamini <damien.bergamini@free.fr>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18#include <sys/cdefs.h>
19__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_rsu.c 287763 2015-09-13 19:17:26Z adrian $");
20
21/*
22 * Driver for Realtek RTL8188SU/RTL8191SU/RTL8192SU.
23 *
24 * TODO:
25 *   o 11n support
26 *   o h/w crypto
27 *   o hostap / ibss / mesh
28 */
29
30#include <sys/param.h>
31#include <sys/endian.h>
32#include <sys/sockio.h>
33#include <sys/mbuf.h>
34#include <sys/kernel.h>
35#include <sys/socket.h>
36#include <sys/systm.h>
37#include <sys/conf.h>
38#include <sys/bus.h>
39#include <sys/rman.h>
40#include <sys/firmware.h>
41#include <sys/module.h>
42
43#include <machine/bus.h>
44#include <machine/resource.h>
45
46#include <net/bpf.h>
47#include <net/if.h>
48#include <net/if_var.h>
49#include <net/if_arp.h>
50#include <net/if_dl.h>
51#include <net/if_media.h>
52#include <net/if_types.h>
53
54#include <netinet/in.h>
55#include <netinet/in_systm.h>
56#include <netinet/in_var.h>
57#include <netinet/if_ether.h>
58#include <netinet/ip.h>
59
60#include <net80211/ieee80211_var.h>
61#include <net80211/ieee80211_regdomain.h>
62#include <net80211/ieee80211_radiotap.h>
63
64#include <dev/usb/usb.h>
65#include <dev/usb/usbdi.h>
66#include "usbdevs.h"
67
68#define USB_DEBUG_VAR rsu_debug
69#include <dev/usb/usb_debug.h>
70
71#include <dev/usb/wlan/if_rsureg.h>
72
73#ifdef USB_DEBUG
74static int rsu_debug = 0;
75SYSCTL_NODE(_hw_usb, OID_AUTO, rsu, CTLFLAG_RW, 0, "USB rsu");
76SYSCTL_INT(_hw_usb_rsu, OID_AUTO, debug, CTLFLAG_RWTUN, &rsu_debug, 0,
77    "Debug level");
78#define	RSU_DPRINTF(_sc, _flg, ...)					\
79	do								\
80		if (((_flg) == (RSU_DEBUG_ANY)) || (rsu_debug & (_flg))) \
81			device_printf((_sc)->sc_dev, __VA_ARGS__);	\
82	while (0)
83#else
84#define	RSU_DPRINTF(_sc, _flg, ...)
85#endif
86
87#define	RSU_DEBUG_ANY		0xffffffff
88#define	RSU_DEBUG_TX		0x00000001
89#define	RSU_DEBUG_RX		0x00000002
90#define	RSU_DEBUG_RESET		0x00000004
91#define	RSU_DEBUG_CALIB		0x00000008
92#define	RSU_DEBUG_STATE		0x00000010
93#define	RSU_DEBUG_SCAN		0x00000020
94#define	RSU_DEBUG_FWCMD		0x00000040
95#define	RSU_DEBUG_TXDONE	0x00000080
96#define	RSU_DEBUG_FW		0x00000100
97#define	RSU_DEBUG_FWDBG		0x00000200
98
99static const STRUCT_USB_HOST_ID rsu_devs[] = {
100#define	RSU_HT_NOT_SUPPORTED 0
101#define	RSU_HT_SUPPORTED 1
102#define RSU_DEV_HT(v,p)  { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \
103				   RSU_HT_SUPPORTED) }
104#define RSU_DEV(v,p)     { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \
105				   RSU_HT_NOT_SUPPORTED) }
106	RSU_DEV(ASUS,			RTL8192SU),
107	RSU_DEV(AZUREWAVE,		RTL8192SU_4),
108	RSU_DEV_HT(ACCTON,		RTL8192SU),
109	RSU_DEV_HT(ASUS,		USBN10),
110	RSU_DEV_HT(AZUREWAVE,		RTL8192SU_1),
111	RSU_DEV_HT(AZUREWAVE,		RTL8192SU_2),
112	RSU_DEV_HT(AZUREWAVE,		RTL8192SU_3),
113	RSU_DEV_HT(AZUREWAVE,		RTL8192SU_5),
114	RSU_DEV_HT(BELKIN,		RTL8192SU_1),
115	RSU_DEV_HT(BELKIN,		RTL8192SU_2),
116	RSU_DEV_HT(BELKIN,		RTL8192SU_3),
117	RSU_DEV_HT(CONCEPTRONIC2,	RTL8192SU_1),
118	RSU_DEV_HT(CONCEPTRONIC2,	RTL8192SU_2),
119	RSU_DEV_HT(CONCEPTRONIC2,	RTL8192SU_3),
120	RSU_DEV_HT(COREGA,		RTL8192SU),
121	RSU_DEV_HT(DLINK2,		DWA131A1),
122	RSU_DEV_HT(DLINK2,		RTL8192SU_1),
123	RSU_DEV_HT(DLINK2,		RTL8192SU_2),
124	RSU_DEV_HT(EDIMAX,		RTL8192SU_1),
125	RSU_DEV_HT(EDIMAX,		RTL8192SU_2),
126	RSU_DEV_HT(EDIMAX,		EW7622UMN),
127	RSU_DEV_HT(GUILLEMOT,		HWGUN54),
128	RSU_DEV_HT(GUILLEMOT,		HWNUM300),
129	RSU_DEV_HT(HAWKING,		RTL8192SU_1),
130	RSU_DEV_HT(HAWKING,		RTL8192SU_2),
131	RSU_DEV_HT(PLANEX2,		GWUSNANO),
132	RSU_DEV_HT(REALTEK,		RTL8171),
133	RSU_DEV_HT(REALTEK,		RTL8172),
134	RSU_DEV_HT(REALTEK,		RTL8173),
135	RSU_DEV_HT(REALTEK,		RTL8174),
136	RSU_DEV_HT(REALTEK,		RTL8192SU),
137	RSU_DEV_HT(REALTEK,		RTL8712),
138	RSU_DEV_HT(REALTEK,		RTL8713),
139	RSU_DEV_HT(SENAO,		RTL8192SU_1),
140	RSU_DEV_HT(SENAO,		RTL8192SU_2),
141	RSU_DEV_HT(SITECOMEU,		WL349V1),
142	RSU_DEV_HT(SITECOMEU,		WL353),
143	RSU_DEV_HT(SWEEX2,		LW154),
144	RSU_DEV_HT(TRENDNET,		TEW646UBH),
145#undef RSU_DEV_HT
146#undef RSU_DEV
147};
148
149static device_probe_t   rsu_match;
150static device_attach_t  rsu_attach;
151static device_detach_t  rsu_detach;
152static usb_callback_t   rsu_bulk_tx_callback_be_bk;
153static usb_callback_t   rsu_bulk_tx_callback_vi_vo;
154static usb_callback_t   rsu_bulk_rx_callback;
155static usb_error_t	rsu_do_request(struct rsu_softc *,
156			    struct usb_device_request *, void *);
157static struct ieee80211vap *
158		rsu_vap_create(struct ieee80211com *, const char name[],
159		    int, enum ieee80211_opmode, int, const uint8_t bssid[],
160		    const uint8_t mac[]);
161static void	rsu_vap_delete(struct ieee80211vap *);
162static void	rsu_scan_start(struct ieee80211com *);
163static void	rsu_scan_end(struct ieee80211com *);
164static void	rsu_set_channel(struct ieee80211com *);
165static void	rsu_update_mcast(struct ieee80211com *);
166static int	rsu_alloc_rx_list(struct rsu_softc *);
167static void	rsu_free_rx_list(struct rsu_softc *);
168static int	rsu_alloc_tx_list(struct rsu_softc *);
169static void	rsu_free_tx_list(struct rsu_softc *);
170static void	rsu_free_list(struct rsu_softc *, struct rsu_data [], int);
171static struct rsu_data *_rsu_getbuf(struct rsu_softc *);
172static struct rsu_data *rsu_getbuf(struct rsu_softc *);
173static int	rsu_write_region_1(struct rsu_softc *, uint16_t, uint8_t *,
174		    int);
175static void	rsu_write_1(struct rsu_softc *, uint16_t, uint8_t);
176static void	rsu_write_2(struct rsu_softc *, uint16_t, uint16_t);
177static void	rsu_write_4(struct rsu_softc *, uint16_t, uint32_t);
178static int	rsu_read_region_1(struct rsu_softc *, uint16_t, uint8_t *,
179		    int);
180static uint8_t	rsu_read_1(struct rsu_softc *, uint16_t);
181static uint16_t	rsu_read_2(struct rsu_softc *, uint16_t);
182static uint32_t	rsu_read_4(struct rsu_softc *, uint16_t);
183static int	rsu_fw_iocmd(struct rsu_softc *, uint32_t);
184static uint8_t	rsu_efuse_read_1(struct rsu_softc *, uint16_t);
185static int	rsu_read_rom(struct rsu_softc *);
186static int	rsu_fw_cmd(struct rsu_softc *, uint8_t, void *, int);
187static void	rsu_calib_task(void *, int);
188static int	rsu_newstate(struct ieee80211vap *, enum ieee80211_state, int);
189#ifdef notyet
190static void	rsu_set_key(struct rsu_softc *, const struct ieee80211_key *);
191static void	rsu_delete_key(struct rsu_softc *, const struct ieee80211_key *);
192#endif
193static int	rsu_site_survey(struct rsu_softc *, struct ieee80211vap *);
194static int	rsu_join_bss(struct rsu_softc *, struct ieee80211_node *);
195static int	rsu_disconnect(struct rsu_softc *);
196static void	rsu_event_survey(struct rsu_softc *, uint8_t *, int);
197static void	rsu_event_join_bss(struct rsu_softc *, uint8_t *, int);
198static void	rsu_rx_event(struct rsu_softc *, uint8_t, uint8_t *, int);
199static void	rsu_rx_multi_event(struct rsu_softc *, uint8_t *, int);
200static int8_t	rsu_get_rssi(struct rsu_softc *, int, void *);
201static struct mbuf *
202		rsu_rx_frame(struct rsu_softc *, uint8_t *, int, int *);
203static struct mbuf *
204		rsu_rx_multi_frame(struct rsu_softc *, uint8_t *, int, int *);
205static struct mbuf *
206		rsu_rxeof(struct usb_xfer *, struct rsu_data *, int *);
207static void	rsu_txeof(struct usb_xfer *, struct rsu_data *);
208static int	rsu_raw_xmit(struct ieee80211_node *, struct mbuf *,
209		    const struct ieee80211_bpf_params *);
210static void	rsu_init(struct rsu_softc *);
211static int	rsu_tx_start(struct rsu_softc *, struct ieee80211_node *,
212		    struct mbuf *, struct rsu_data *);
213static int	rsu_transmit(struct ieee80211com *, struct mbuf *);
214static void	rsu_start(struct rsu_softc *);
215static void	rsu_parent(struct ieee80211com *);
216static void	rsu_stop(struct rsu_softc *);
217static void	rsu_ms_delay(struct rsu_softc *);
218
219static device_method_t rsu_methods[] = {
220	DEVMETHOD(device_probe,		rsu_match),
221	DEVMETHOD(device_attach,	rsu_attach),
222	DEVMETHOD(device_detach,	rsu_detach),
223
224	DEVMETHOD_END
225};
226
227static driver_t rsu_driver = {
228	.name = "rsu",
229	.methods = rsu_methods,
230	.size = sizeof(struct rsu_softc)
231};
232
233static devclass_t rsu_devclass;
234
235DRIVER_MODULE(rsu, uhub, rsu_driver, rsu_devclass, NULL, 0);
236MODULE_DEPEND(rsu, wlan, 1, 1, 1);
237MODULE_DEPEND(rsu, usb, 1, 1, 1);
238MODULE_DEPEND(rsu, firmware, 1, 1, 1);
239MODULE_VERSION(rsu, 1);
240
241static uint8_t rsu_wme_ac_xfer_map[4] = {
242	[WME_AC_BE] = RSU_BULK_TX_BE_BK,
243	[WME_AC_BK] = RSU_BULK_TX_BE_BK,
244	[WME_AC_VI] = RSU_BULK_TX_VI_VO,
245	[WME_AC_VO] = RSU_BULK_TX_VI_VO,
246};
247
248static const struct usb_config rsu_config[RSU_N_TRANSFER] = {
249	[RSU_BULK_RX] = {
250		.type = UE_BULK,
251		.endpoint = UE_ADDR_ANY,
252		.direction = UE_DIR_IN,
253		.bufsize = RSU_RXBUFSZ,
254		.flags = {
255			.pipe_bof = 1,
256			.short_xfer_ok = 1
257		},
258		.callback = rsu_bulk_rx_callback
259	},
260	[RSU_BULK_TX_BE_BK] = {
261		.type = UE_BULK,
262		.endpoint = 0x06,
263		.direction = UE_DIR_OUT,
264		.bufsize = RSU_TXBUFSZ,
265		.flags = {
266			.ext_buffer = 1,
267			.pipe_bof = 1,
268			.force_short_xfer = 1
269		},
270		.callback = rsu_bulk_tx_callback_be_bk,
271		.timeout = RSU_TX_TIMEOUT
272	},
273	[RSU_BULK_TX_VI_VO] = {
274		.type = UE_BULK,
275		.endpoint = 0x04,
276		.direction = UE_DIR_OUT,
277		.bufsize = RSU_TXBUFSZ,
278		.flags = {
279			.ext_buffer = 1,
280			.pipe_bof = 1,
281			.force_short_xfer = 1
282		},
283		.callback = rsu_bulk_tx_callback_vi_vo,
284		.timeout = RSU_TX_TIMEOUT
285	},
286};
287
288static int
289rsu_match(device_t self)
290{
291	struct usb_attach_arg *uaa = device_get_ivars(self);
292
293	if (uaa->usb_mode != USB_MODE_HOST ||
294	    uaa->info.bIfaceIndex != 0 ||
295	    uaa->info.bConfigIndex != 0)
296		return (ENXIO);
297
298	return (usbd_lookup_id_by_uaa(rsu_devs, sizeof(rsu_devs), uaa));
299}
300
301static int
302rsu_send_mgmt(struct ieee80211_node *ni, int type, int arg)
303{
304
305	return (ENOTSUP);
306}
307
308static int
309rsu_attach(device_t self)
310{
311	struct usb_attach_arg *uaa = device_get_ivars(self);
312	struct rsu_softc *sc = device_get_softc(self);
313	struct ieee80211com *ic = &sc->sc_ic;
314	int error;
315	uint8_t iface_index, bands;
316
317	device_set_usb_desc(self);
318	sc->sc_udev = uaa->device;
319	sc->sc_dev = self;
320
321	mtx_init(&sc->sc_mtx, device_get_nameunit(self), MTX_NETWORK_LOCK,
322	    MTX_DEF);
323	TIMEOUT_TASK_INIT(taskqueue_thread, &sc->calib_task, 0,
324	    rsu_calib_task, sc);
325	mbufq_init(&sc->sc_snd, ifqmaxlen);
326
327	/* Allocate Tx/Rx buffers. */
328	error = rsu_alloc_rx_list(sc);
329	if (error != 0) {
330		device_printf(sc->sc_dev, "could not allocate Rx buffers\n");
331		goto fail_usb;
332	}
333
334	error = rsu_alloc_tx_list(sc);
335	if (error != 0) {
336		device_printf(sc->sc_dev, "could not allocate Tx buffers\n");
337		rsu_free_rx_list(sc);
338		goto fail_usb;
339	}
340
341	iface_index = 0;
342	error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
343	    rsu_config, RSU_N_TRANSFER, sc, &sc->sc_mtx);
344	if (error) {
345		device_printf(sc->sc_dev,
346		    "could not allocate USB transfers, err=%s\n",
347		    usbd_errstr(error));
348		goto fail_usb;
349	}
350	RSU_LOCK(sc);
351	/* Read chip revision. */
352	sc->cut = MS(rsu_read_4(sc, R92S_PMC_FSM), R92S_PMC_FSM_CUT);
353	if (sc->cut != 3)
354		sc->cut = (sc->cut >> 1) + 1;
355	error = rsu_read_rom(sc);
356	RSU_UNLOCK(sc);
357	if (error != 0) {
358		device_printf(self, "could not read ROM\n");
359		goto fail_rom;
360	}
361	IEEE80211_ADDR_COPY(ic->ic_macaddr, &sc->rom[0x12]);
362	device_printf(self, "MAC/BB RTL8712 cut %d\n", sc->cut);
363
364	ic->ic_softc = sc;
365	ic->ic_name = device_get_nameunit(self);
366	ic->ic_phytype = IEEE80211_T_OFDM;	/* Not only, but not used. */
367	ic->ic_opmode = IEEE80211_M_STA;	/* Default to BSS mode. */
368
369	/* Set device capabilities. */
370	ic->ic_caps =
371	    IEEE80211_C_STA |		/* station mode */
372#if 0
373	    IEEE80211_C_BGSCAN |	/* Background scan. */
374#endif
375	    IEEE80211_C_SHPREAMBLE |	/* Short preamble supported. */
376	    IEEE80211_C_SHSLOT |	/* Short slot time supported. */
377	    IEEE80211_C_WPA;		/* WPA/RSN. */
378
379#if 0
380	/* Check if HT support is present. */
381	if (usb_lookup(rsu_devs_noht, uaa->vendor, uaa->product) == NULL) {
382		/* Set HT capabilities. */
383		ic->ic_htcaps =
384		    IEEE80211_HTCAP_CBW20_40 |
385		    IEEE80211_HTCAP_DSSSCCK40;
386		/* Set supported HT rates. */
387		for (i = 0; i < 2; i++)
388			ic->ic_sup_mcs[i] = 0xff;
389	}
390#endif
391
392	/* Set supported .11b and .11g rates. */
393	bands = 0;
394	setbit(&bands, IEEE80211_MODE_11B);
395	setbit(&bands, IEEE80211_MODE_11G);
396	ieee80211_init_channels(ic, NULL, &bands);
397
398	ieee80211_ifattach(ic);
399	ic->ic_raw_xmit = rsu_raw_xmit;
400	ic->ic_scan_start = rsu_scan_start;
401	ic->ic_scan_end = rsu_scan_end;
402	ic->ic_set_channel = rsu_set_channel;
403	ic->ic_vap_create = rsu_vap_create;
404	ic->ic_vap_delete = rsu_vap_delete;
405	ic->ic_update_mcast = rsu_update_mcast;
406	ic->ic_parent = rsu_parent;
407	ic->ic_transmit = rsu_transmit;
408	ic->ic_send_mgmt = rsu_send_mgmt;
409
410	ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr,
411	    sizeof(sc->sc_txtap), RSU_TX_RADIOTAP_PRESENT,
412	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
413	    RSU_RX_RADIOTAP_PRESENT);
414
415	if (bootverbose)
416		ieee80211_announce(ic);
417
418	return (0);
419
420fail_rom:
421	usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER);
422fail_usb:
423	mtx_destroy(&sc->sc_mtx);
424	return (ENXIO);
425}
426
427static int
428rsu_detach(device_t self)
429{
430	struct rsu_softc *sc = device_get_softc(self);
431	struct ieee80211com *ic = &sc->sc_ic;
432
433	RSU_LOCK(sc);
434	rsu_stop(sc);
435	RSU_UNLOCK(sc);
436	usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER);
437	ieee80211_ifdetach(ic);
438
439	taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task);
440
441	/* Free Tx/Rx buffers. */
442	rsu_free_tx_list(sc);
443	rsu_free_rx_list(sc);
444
445	mbufq_drain(&sc->sc_snd);
446	mtx_destroy(&sc->sc_mtx);
447
448	return (0);
449}
450
451static usb_error_t
452rsu_do_request(struct rsu_softc *sc, struct usb_device_request *req,
453    void *data)
454{
455	usb_error_t err;
456	int ntries = 10;
457
458	RSU_ASSERT_LOCKED(sc);
459
460	while (ntries--) {
461		err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
462		    req, data, 0, NULL, 250 /* ms */);
463		if (err == 0 || err == USB_ERR_NOT_CONFIGURED)
464			break;
465		DPRINTFN(1, "Control request failed, %s (retrying)\n",
466		    usbd_errstr(err));
467		usb_pause_mtx(&sc->sc_mtx, hz / 100);
468        }
469
470        return (err);
471}
472
473static struct ieee80211vap *
474rsu_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
475    enum ieee80211_opmode opmode, int flags,
476    const uint8_t bssid[IEEE80211_ADDR_LEN],
477    const uint8_t mac[IEEE80211_ADDR_LEN])
478{
479	struct rsu_vap *uvp;
480	struct ieee80211vap *vap;
481
482	if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
483		return (NULL);
484
485	uvp =  malloc(sizeof(struct rsu_vap), M_80211_VAP, M_WAITOK | M_ZERO);
486	vap = &uvp->vap;
487
488	if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
489	    flags, bssid) != 0) {
490		/* out of memory */
491		free(uvp, M_80211_VAP);
492		return (NULL);
493	}
494
495	/* override state transition machine */
496	uvp->newstate = vap->iv_newstate;
497	vap->iv_newstate = rsu_newstate;
498
499	/* complete setup */
500	ieee80211_vap_attach(vap, ieee80211_media_change,
501	    ieee80211_media_status, mac);
502	ic->ic_opmode = opmode;
503
504	return (vap);
505}
506
507static void
508rsu_vap_delete(struct ieee80211vap *vap)
509{
510	struct rsu_vap *uvp = RSU_VAP(vap);
511
512	ieee80211_vap_detach(vap);
513	free(uvp, M_80211_VAP);
514}
515
516static void
517rsu_scan_start(struct ieee80211com *ic)
518{
519	struct rsu_softc *sc = ic->ic_softc;
520	int error;
521
522	/* Scanning is done by the firmware. */
523	RSU_LOCK(sc);
524	error = rsu_site_survey(sc, TAILQ_FIRST(&ic->ic_vaps));
525	RSU_UNLOCK(sc);
526	if (error != 0)
527		device_printf(sc->sc_dev,
528		    "could not send site survey command\n");
529}
530
531static void
532rsu_scan_end(struct ieee80211com *ic)
533{
534	/* Nothing to do here. */
535}
536
537static void
538rsu_set_channel(struct ieee80211com *ic __unused)
539{
540	/* We are unable to switch channels, yet. */
541}
542
543static void
544rsu_update_mcast(struct ieee80211com *ic)
545{
546        /* XXX do nothing?  */
547}
548
549static int
550rsu_alloc_list(struct rsu_softc *sc, struct rsu_data data[],
551    int ndata, int maxsz)
552{
553	int i, error;
554
555	for (i = 0; i < ndata; i++) {
556		struct rsu_data *dp = &data[i];
557		dp->sc = sc;
558		dp->m = NULL;
559		dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT);
560		if (dp->buf == NULL) {
561			device_printf(sc->sc_dev,
562			    "could not allocate buffer\n");
563			error = ENOMEM;
564			goto fail;
565		}
566		dp->ni = NULL;
567	}
568
569	return (0);
570fail:
571	rsu_free_list(sc, data, ndata);
572	return (error);
573}
574
575static int
576rsu_alloc_rx_list(struct rsu_softc *sc)
577{
578        int error, i;
579
580	error = rsu_alloc_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT,
581	    RSU_RXBUFSZ);
582	if (error != 0)
583		return (error);
584
585	STAILQ_INIT(&sc->sc_rx_active);
586	STAILQ_INIT(&sc->sc_rx_inactive);
587
588	for (i = 0; i < RSU_RX_LIST_COUNT; i++)
589		STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i], next);
590
591	return (0);
592}
593
594static int
595rsu_alloc_tx_list(struct rsu_softc *sc)
596{
597	int error, i;
598
599	error = rsu_alloc_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT,
600	    RSU_TXBUFSZ);
601	if (error != 0)
602		return (error);
603
604	STAILQ_INIT(&sc->sc_tx_inactive);
605
606	for (i = 0; i != RSU_N_TRANSFER; i++) {
607		STAILQ_INIT(&sc->sc_tx_active[i]);
608		STAILQ_INIT(&sc->sc_tx_pending[i]);
609	}
610
611	for (i = 0; i < RSU_TX_LIST_COUNT; i++) {
612		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i], next);
613	}
614
615	return (0);
616}
617
618static void
619rsu_free_tx_list(struct rsu_softc *sc)
620{
621	int i;
622
623	/* prevent further allocations from TX list(s) */
624	STAILQ_INIT(&sc->sc_tx_inactive);
625
626	for (i = 0; i != RSU_N_TRANSFER; i++) {
627		STAILQ_INIT(&sc->sc_tx_active[i]);
628		STAILQ_INIT(&sc->sc_tx_pending[i]);
629	}
630
631	rsu_free_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT);
632}
633
634static void
635rsu_free_rx_list(struct rsu_softc *sc)
636{
637	/* prevent further allocations from RX list(s) */
638	STAILQ_INIT(&sc->sc_rx_inactive);
639	STAILQ_INIT(&sc->sc_rx_active);
640
641	rsu_free_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT);
642}
643
644static void
645rsu_free_list(struct rsu_softc *sc, struct rsu_data data[], int ndata)
646{
647	int i;
648
649	for (i = 0; i < ndata; i++) {
650		struct rsu_data *dp = &data[i];
651
652		if (dp->buf != NULL) {
653			free(dp->buf, M_USBDEV);
654			dp->buf = NULL;
655		}
656		if (dp->ni != NULL) {
657			ieee80211_free_node(dp->ni);
658			dp->ni = NULL;
659		}
660	}
661}
662
663static struct rsu_data *
664_rsu_getbuf(struct rsu_softc *sc)
665{
666	struct rsu_data *bf;
667
668	bf = STAILQ_FIRST(&sc->sc_tx_inactive);
669	if (bf != NULL)
670		STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next);
671	else
672		bf = NULL;
673	if (bf == NULL)
674		DPRINTF("out of xmit buffers\n");
675        return (bf);
676}
677
678static struct rsu_data *
679rsu_getbuf(struct rsu_softc *sc)
680{
681	struct rsu_data *bf;
682
683	RSU_ASSERT_LOCKED(sc);
684
685	bf = _rsu_getbuf(sc);
686	if (bf == NULL)
687		DPRINTF("stop queue\n");
688	return (bf);
689}
690
691static int
692rsu_write_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
693    int len)
694{
695	usb_device_request_t req;
696
697	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
698	req.bRequest = R92S_REQ_REGS;
699	USETW(req.wValue, addr);
700	USETW(req.wIndex, 0);
701	USETW(req.wLength, len);
702
703	return (rsu_do_request(sc, &req, buf));
704}
705
706static void
707rsu_write_1(struct rsu_softc *sc, uint16_t addr, uint8_t val)
708{
709	rsu_write_region_1(sc, addr, &val, 1);
710}
711
712static void
713rsu_write_2(struct rsu_softc *sc, uint16_t addr, uint16_t val)
714{
715	val = htole16(val);
716	rsu_write_region_1(sc, addr, (uint8_t *)&val, 2);
717}
718
719static void
720rsu_write_4(struct rsu_softc *sc, uint16_t addr, uint32_t val)
721{
722	val = htole32(val);
723	rsu_write_region_1(sc, addr, (uint8_t *)&val, 4);
724}
725
726static int
727rsu_read_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf,
728    int len)
729{
730	usb_device_request_t req;
731
732	req.bmRequestType = UT_READ_VENDOR_DEVICE;
733	req.bRequest = R92S_REQ_REGS;
734	USETW(req.wValue, addr);
735	USETW(req.wIndex, 0);
736	USETW(req.wLength, len);
737
738	return (rsu_do_request(sc, &req, buf));
739}
740
741static uint8_t
742rsu_read_1(struct rsu_softc *sc, uint16_t addr)
743{
744	uint8_t val;
745
746	if (rsu_read_region_1(sc, addr, &val, 1) != 0)
747		return (0xff);
748	return (val);
749}
750
751static uint16_t
752rsu_read_2(struct rsu_softc *sc, uint16_t addr)
753{
754	uint16_t val;
755
756	if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0)
757		return (0xffff);
758	return (le16toh(val));
759}
760
761static uint32_t
762rsu_read_4(struct rsu_softc *sc, uint16_t addr)
763{
764	uint32_t val;
765
766	if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0)
767		return (0xffffffff);
768	return (le32toh(val));
769}
770
771static int
772rsu_fw_iocmd(struct rsu_softc *sc, uint32_t iocmd)
773{
774	int ntries;
775
776	rsu_write_4(sc, R92S_IOCMD_CTRL, iocmd);
777	rsu_ms_delay(sc);
778	for (ntries = 0; ntries < 50; ntries++) {
779		if (rsu_read_4(sc, R92S_IOCMD_CTRL) == 0)
780			return (0);
781		rsu_ms_delay(sc);
782	}
783	return (ETIMEDOUT);
784}
785
786static uint8_t
787rsu_efuse_read_1(struct rsu_softc *sc, uint16_t addr)
788{
789	uint32_t reg;
790	int ntries;
791
792	reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
793	reg = RW(reg, R92S_EFUSE_CTRL_ADDR, addr);
794	reg &= ~R92S_EFUSE_CTRL_VALID;
795	rsu_write_4(sc, R92S_EFUSE_CTRL, reg);
796	/* Wait for read operation to complete. */
797	for (ntries = 0; ntries < 100; ntries++) {
798		reg = rsu_read_4(sc, R92S_EFUSE_CTRL);
799		if (reg & R92S_EFUSE_CTRL_VALID)
800			return (MS(reg, R92S_EFUSE_CTRL_DATA));
801		rsu_ms_delay(sc);
802	}
803	device_printf(sc->sc_dev,
804	    "could not read efuse byte at address 0x%x\n", addr);
805	return (0xff);
806}
807
808static int
809rsu_read_rom(struct rsu_softc *sc)
810{
811	uint8_t *rom = sc->rom;
812	uint16_t addr = 0;
813	uint32_t reg;
814	uint8_t off, msk;
815	int i;
816
817	/* Make sure that ROM type is eFuse and that autoload succeeded. */
818	reg = rsu_read_1(sc, R92S_EE_9346CR);
819	if ((reg & (R92S_9356SEL | R92S_EEPROM_EN)) != R92S_EEPROM_EN)
820		return (EIO);
821
822	/* Turn on 2.5V to prevent eFuse leakage. */
823	reg = rsu_read_1(sc, R92S_EFUSE_TEST + 3);
824	rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg | 0x80);
825	rsu_ms_delay(sc);
826	rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg & ~0x80);
827
828	/* Read full ROM image. */
829	memset(&sc->rom, 0xff, sizeof(sc->rom));
830	while (addr < 512) {
831		reg = rsu_efuse_read_1(sc, addr);
832		if (reg == 0xff)
833			break;
834		addr++;
835		off = reg >> 4;
836		msk = reg & 0xf;
837		for (i = 0; i < 4; i++) {
838			if (msk & (1 << i))
839				continue;
840			rom[off * 8 + i * 2 + 0] =
841			    rsu_efuse_read_1(sc, addr);
842			addr++;
843			rom[off * 8 + i * 2 + 1] =
844			    rsu_efuse_read_1(sc, addr);
845			addr++;
846		}
847	}
848#ifdef USB_DEBUG
849	if (rsu_debug >= 5) {
850		/* Dump ROM content. */
851		printf("\n");
852		for (i = 0; i < sizeof(sc->rom); i++)
853			printf("%02x:", rom[i]);
854		printf("\n");
855	}
856#endif
857	return (0);
858}
859
860static int
861rsu_fw_cmd(struct rsu_softc *sc, uint8_t code, void *buf, int len)
862{
863	const uint8_t which = rsu_wme_ac_xfer_map[WME_AC_VO];
864	struct rsu_data *data;
865	struct r92s_tx_desc *txd;
866	struct r92s_fw_cmd_hdr *cmd;
867	int cmdsz;
868	int xferlen;
869
870	data = rsu_getbuf(sc);
871	if (data == NULL)
872		return (ENOMEM);
873
874	/* Round-up command length to a multiple of 8 bytes. */
875	cmdsz = (len + 7) & ~7;
876
877	xferlen = sizeof(*txd) + sizeof(*cmd) + cmdsz;
878	KASSERT(xferlen <= RSU_TXBUFSZ, ("%s: invalid length", __func__));
879	memset(data->buf, 0, xferlen);
880
881	/* Setup Tx descriptor. */
882	txd = (struct r92s_tx_desc *)data->buf;
883	txd->txdw0 = htole32(
884	    SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
885	    SM(R92S_TXDW0_PKTLEN, sizeof(*cmd) + cmdsz) |
886	    R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
887	txd->txdw1 = htole32(SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_H2C));
888
889	/* Setup command header. */
890	cmd = (struct r92s_fw_cmd_hdr *)&txd[1];
891	cmd->len = htole16(cmdsz);
892	cmd->code = code;
893	cmd->seq = sc->cmd_seq;
894	sc->cmd_seq = (sc->cmd_seq + 1) & 0x7f;
895
896	/* Copy command payload. */
897	memcpy(&cmd[1], buf, len);
898
899	RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FWCMD,
900	    "%s: Tx cmd code=0x%x len=0x%x\n",
901	    __func__, code, cmdsz);
902	data->buflen = xferlen;
903	STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
904	usbd_transfer_start(sc->sc_xfer[which]);
905
906	return (0);
907}
908
909/* ARGSUSED */
910static void
911rsu_calib_task(void *arg, int pending __unused)
912{
913	struct rsu_softc *sc = arg;
914	uint32_t reg;
915
916	RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "%s: running calibration task\n",
917	    __func__);
918
919	RSU_LOCK(sc);
920#ifdef notyet
921	/* Read WPS PBC status. */
922	rsu_write_1(sc, R92S_MAC_PINMUX_CTRL,
923	    R92S_GPIOMUX_EN | SM(R92S_GPIOSEL_GPIO, R92S_GPIOSEL_GPIO_JTAG));
924	rsu_write_1(sc, R92S_GPIO_IO_SEL,
925	    rsu_read_1(sc, R92S_GPIO_IO_SEL) & ~R92S_GPIO_WPS);
926	reg = rsu_read_1(sc, R92S_GPIO_CTRL);
927	if (reg != 0xff && (reg & R92S_GPIO_WPS))
928		DPRINTF(("WPS PBC is pushed\n"));
929#endif
930	/* Read current signal level. */
931	if (rsu_fw_iocmd(sc, 0xf4000001) == 0) {
932		reg = rsu_read_4(sc, R92S_IOCMD_DATA);
933		RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "%s: RSSI=%d%%\n",
934		    __func__, reg >> 4);
935	}
936	if (sc->sc_calibrating)
937		taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, hz);
938	RSU_UNLOCK(sc);
939}
940
941static int
942rsu_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
943{
944	struct rsu_vap *uvp = RSU_VAP(vap);
945	struct ieee80211com *ic = vap->iv_ic;
946	struct rsu_softc *sc = ic->ic_softc;
947	struct ieee80211_node *ni;
948	struct ieee80211_rateset *rs;
949	enum ieee80211_state ostate;
950	int error, startcal = 0;
951
952	ostate = vap->iv_state;
953	RSU_DPRINTF(sc, RSU_DEBUG_STATE, "%s: %s -> %s\n",
954	    __func__,
955	    ieee80211_state_name[ostate],
956	    ieee80211_state_name[nstate]);
957
958	IEEE80211_UNLOCK(ic);
959	if (ostate == IEEE80211_S_RUN) {
960		RSU_LOCK(sc);
961		/* Stop calibration. */
962		sc->sc_calibrating = 0;
963		RSU_UNLOCK(sc);
964		taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task);
965		/* Disassociate from our current BSS. */
966		RSU_LOCK(sc);
967		rsu_disconnect(sc);
968	} else
969		RSU_LOCK(sc);
970	switch (nstate) {
971	case IEEE80211_S_INIT:
972		break;
973	case IEEE80211_S_AUTH:
974		ni = ieee80211_ref_node(vap->iv_bss);
975		error = rsu_join_bss(sc, ni);
976		ieee80211_free_node(ni);
977		if (error != 0) {
978			device_printf(sc->sc_dev,
979			    "could not send join command\n");
980		}
981		break;
982	case IEEE80211_S_RUN:
983		ni = ieee80211_ref_node(vap->iv_bss);
984		rs = &ni->ni_rates;
985		/* Indicate highest supported rate. */
986		ni->ni_txrate = rs->rs_rates[rs->rs_nrates - 1];
987		ieee80211_free_node(ni);
988		startcal = 1;
989		break;
990	default:
991		break;
992	}
993	sc->sc_calibrating = 1;
994	/* Start periodic calibration. */
995	taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, hz);
996	RSU_UNLOCK(sc);
997	IEEE80211_LOCK(ic);
998	return (uvp->newstate(vap, nstate, arg));
999}
1000
1001#ifdef notyet
1002static void
1003rsu_set_key(struct rsu_softc *sc, const struct ieee80211_key *k)
1004{
1005	struct r92s_fw_cmd_set_key key;
1006
1007	memset(&key, 0, sizeof(key));
1008	/* Map net80211 cipher to HW crypto algorithm. */
1009	switch (k->wk_cipher->ic_cipher) {
1010	case IEEE80211_CIPHER_WEP:
1011		if (k->wk_keylen < 8)
1012			key.algo = R92S_KEY_ALGO_WEP40;
1013		else
1014			key.algo = R92S_KEY_ALGO_WEP104;
1015		break;
1016	case IEEE80211_CIPHER_TKIP:
1017		key.algo = R92S_KEY_ALGO_TKIP;
1018		break;
1019	case IEEE80211_CIPHER_AES_CCM:
1020		key.algo = R92S_KEY_ALGO_AES;
1021		break;
1022	default:
1023		return;
1024	}
1025	key.id = k->wk_keyix;
1026	key.grpkey = (k->wk_flags & IEEE80211_KEY_GROUP) != 0;
1027	memcpy(key.key, k->wk_key, MIN(k->wk_keylen, sizeof(key.key)));
1028	(void)rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
1029}
1030
1031static void
1032rsu_delete_key(struct rsu_softc *sc, const struct ieee80211_key *k)
1033{
1034	struct r92s_fw_cmd_set_key key;
1035
1036	memset(&key, 0, sizeof(key));
1037	key.id = k->wk_keyix;
1038	(void)rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key));
1039}
1040#endif
1041
1042static int
1043rsu_site_survey(struct rsu_softc *sc, struct ieee80211vap *vap)
1044{
1045	struct r92s_fw_cmd_sitesurvey cmd;
1046	struct ieee80211com *ic = &sc->sc_ic;
1047
1048	memset(&cmd, 0, sizeof(cmd));
1049	if ((ic->ic_flags & IEEE80211_F_ASCAN) || sc->sc_scan_pass == 1)
1050		cmd.active = htole32(1);
1051	cmd.limit = htole32(48);
1052	if (sc->sc_scan_pass == 1 && vap->iv_des_nssid > 0) {
1053		/* Do a directed scan for second pass. */
1054		cmd.ssidlen = htole32(vap->iv_des_ssid[0].len);
1055		memcpy(cmd.ssid, vap->iv_des_ssid[0].ssid,
1056		    vap->iv_des_ssid[0].len);
1057
1058	}
1059	DPRINTF("sending site survey command, pass=%d\n", sc->sc_scan_pass);
1060	return (rsu_fw_cmd(sc, R92S_CMD_SITE_SURVEY, &cmd, sizeof(cmd)));
1061}
1062
1063static int
1064rsu_join_bss(struct rsu_softc *sc, struct ieee80211_node *ni)
1065{
1066	struct ieee80211com *ic = &sc->sc_ic;
1067	struct ieee80211vap *vap = ni->ni_vap;
1068	struct ndis_wlan_bssid_ex *bss;
1069	struct ndis_802_11_fixed_ies *fixed;
1070	struct r92s_fw_cmd_auth auth;
1071	uint8_t buf[sizeof(*bss) + 128] __aligned(4);
1072	uint8_t *frm;
1073	uint8_t opmode;
1074	int error;
1075
1076	/* Let the FW decide the opmode based on the capinfo field. */
1077	opmode = NDIS802_11AUTOUNKNOWN;
1078	RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1079	    "%s: setting operating mode to %d\n",
1080	    __func__, opmode);
1081	error = rsu_fw_cmd(sc, R92S_CMD_SET_OPMODE, &opmode, sizeof(opmode));
1082	if (error != 0)
1083		return (error);
1084
1085	memset(&auth, 0, sizeof(auth));
1086	if (vap->iv_flags & IEEE80211_F_WPA) {
1087		auth.mode = R92S_AUTHMODE_WPA;
1088		auth.dot1x = (ni->ni_authmode == IEEE80211_AUTH_8021X);
1089	} else
1090		auth.mode = R92S_AUTHMODE_OPEN;
1091	RSU_DPRINTF(sc, RSU_DEBUG_RESET,
1092	    "%s: setting auth mode to %d\n",
1093	    __func__, auth.mode);
1094	error = rsu_fw_cmd(sc, R92S_CMD_SET_AUTH, &auth, sizeof(auth));
1095	if (error != 0)
1096		return (error);
1097
1098	memset(buf, 0, sizeof(buf));
1099	bss = (struct ndis_wlan_bssid_ex *)buf;
1100	IEEE80211_ADDR_COPY(bss->macaddr, ni->ni_bssid);
1101	bss->ssid.ssidlen = htole32(ni->ni_esslen);
1102	memcpy(bss->ssid.ssid, ni->ni_essid, ni->ni_esslen);
1103	if (vap->iv_flags & (IEEE80211_F_PRIVACY | IEEE80211_F_WPA))
1104		bss->privacy = htole32(1);
1105	bss->rssi = htole32(ni->ni_avgrssi);
1106	if (ic->ic_curmode == IEEE80211_MODE_11B)
1107		bss->networktype = htole32(NDIS802_11DS);
1108	else
1109		bss->networktype = htole32(NDIS802_11OFDM24);
1110	bss->config.len = htole32(sizeof(bss->config));
1111	bss->config.bintval = htole32(ni->ni_intval);
1112	bss->config.dsconfig = htole32(ieee80211_chan2ieee(ic, ni->ni_chan));
1113	bss->inframode = htole32(NDIS802_11INFRASTRUCTURE);
1114	/* XXX verify how this is supposed to look! */
1115	memcpy(bss->supprates, ni->ni_rates.rs_rates,
1116	    ni->ni_rates.rs_nrates);
1117	/* Write the fixed fields of the beacon frame. */
1118	fixed = (struct ndis_802_11_fixed_ies *)&bss[1];
1119	memcpy(&fixed->tstamp, ni->ni_tstamp.data, 8);
1120	fixed->bintval = htole16(ni->ni_intval);
1121	fixed->capabilities = htole16(ni->ni_capinfo);
1122	/* Write IEs to be included in the association request. */
1123	frm = (uint8_t *)&fixed[1];
1124	frm = ieee80211_add_rsn(frm, vap);
1125	frm = ieee80211_add_wpa(frm, vap);
1126	frm = ieee80211_add_qos(frm, ni);
1127	if (ni->ni_flags & IEEE80211_NODE_HT)
1128		frm = ieee80211_add_htcap(frm, ni);
1129	bss->ieslen = htole32(frm - (uint8_t *)fixed);
1130	bss->len = htole32(((frm - buf) + 3) & ~3);
1131	RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_FWCMD,
1132	    "%s: sending join bss command to %s chan %d\n",
1133	    __func__,
1134	    ether_sprintf(bss->macaddr), le32toh(bss->config.dsconfig));
1135	return (rsu_fw_cmd(sc, R92S_CMD_JOIN_BSS, buf, sizeof(buf)));
1136}
1137
1138static int
1139rsu_disconnect(struct rsu_softc *sc)
1140{
1141	uint32_t zero = 0;	/* :-) */
1142
1143	/* Disassociate from our current BSS. */
1144	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
1145	    "%s: sending disconnect command\n", __func__);
1146	return (rsu_fw_cmd(sc, R92S_CMD_DISCONNECT, &zero, sizeof(zero)));
1147}
1148
1149static void
1150rsu_event_survey(struct rsu_softc *sc, uint8_t *buf, int len)
1151{
1152	struct ieee80211com *ic = &sc->sc_ic;
1153	struct ieee80211_frame *wh;
1154	struct ieee80211_channel *c;
1155	struct ndis_wlan_bssid_ex *bss;
1156	struct mbuf *m;
1157	int pktlen;
1158
1159	if (__predict_false(len < sizeof(*bss)))
1160		return;
1161	bss = (struct ndis_wlan_bssid_ex *)buf;
1162	if (__predict_false(len < sizeof(*bss) + le32toh(bss->ieslen)))
1163		return;
1164
1165	RSU_DPRINTF(sc, RSU_DEBUG_SCAN,
1166	    "%s: found BSS %s: len=%d chan=%d inframode=%d "
1167	    "networktype=%d privacy=%d, RSSI=%d\n",
1168	    __func__,
1169	    ether_sprintf(bss->macaddr), le32toh(bss->len),
1170	    le32toh(bss->config.dsconfig), le32toh(bss->inframode),
1171	    le32toh(bss->networktype), le32toh(bss->privacy),
1172	    le32toh(bss->rssi));
1173
1174	/* Build a fake beacon frame to let net80211 do all the parsing. */
1175	/* XXX TODO: just call the new scan API methods! */
1176	pktlen = sizeof(*wh) + le32toh(bss->ieslen);
1177	if (__predict_false(pktlen > MCLBYTES))
1178		return;
1179	m = m_get2(pktlen, M_NOWAIT, MT_DATA, M_PKTHDR);
1180	if (__predict_false(m == NULL))
1181		return;
1182	wh = mtod(m, struct ieee80211_frame *);
1183	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
1184	    IEEE80211_FC0_SUBTYPE_BEACON;
1185	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1186	USETW(wh->i_dur, 0);
1187	IEEE80211_ADDR_COPY(wh->i_addr1, ieee80211broadcastaddr);
1188	IEEE80211_ADDR_COPY(wh->i_addr2, bss->macaddr);
1189	IEEE80211_ADDR_COPY(wh->i_addr3, bss->macaddr);
1190	*(uint16_t *)wh->i_seq = 0;
1191	memcpy(&wh[1], (uint8_t *)&bss[1], le32toh(bss->ieslen));
1192
1193	/* Finalize mbuf. */
1194	m->m_pkthdr.len = m->m_len = pktlen;
1195	/* Fix the channel. */
1196	c = ieee80211_find_channel_byieee(ic,
1197	    le32toh(bss->config.dsconfig),
1198	    IEEE80211_CHAN_G);
1199	if (c) {
1200		ic->ic_curchan = c;
1201		ieee80211_radiotap_chan_change(ic);
1202	}
1203	/* XXX avoid a LOR */
1204	RSU_UNLOCK(sc);
1205	ieee80211_input_all(ic, m, le32toh(bss->rssi), 0);
1206	RSU_LOCK(sc);
1207}
1208
1209static void
1210rsu_event_join_bss(struct rsu_softc *sc, uint8_t *buf, int len)
1211{
1212	struct ieee80211com *ic = &sc->sc_ic;
1213	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1214	struct ieee80211_node *ni = vap->iv_bss;
1215	struct r92s_event_join_bss *rsp;
1216	uint32_t tmp;
1217	int res;
1218
1219	if (__predict_false(len < sizeof(*rsp)))
1220		return;
1221	rsp = (struct r92s_event_join_bss *)buf;
1222	res = (int)le32toh(rsp->join_res);
1223
1224	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
1225	    "%s: Rx join BSS event len=%d res=%d\n",
1226	    __func__, len, res);
1227	if (res <= 0) {
1228		RSU_UNLOCK(sc);
1229		ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1230		RSU_LOCK(sc);
1231		return;
1232	}
1233	tmp = le32toh(rsp->associd);
1234	if (tmp >= vap->iv_max_aid) {
1235		DPRINTF("Assoc ID overflow\n");
1236		tmp = 1;
1237	}
1238	RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD,
1239	    "%s: associated with %s associd=%d\n",
1240	    __func__, ether_sprintf(rsp->bss.macaddr), tmp);
1241	/* XXX is this required? What's the top two bits for again? */
1242	ni->ni_associd = tmp | 0xc000;
1243	RSU_UNLOCK(sc);
1244	ieee80211_new_state(vap, IEEE80211_S_RUN,
1245	    IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
1246	RSU_LOCK(sc);
1247}
1248
1249static void
1250rsu_rx_event(struct rsu_softc *sc, uint8_t code, uint8_t *buf, int len)
1251{
1252	struct ieee80211com *ic = &sc->sc_ic;
1253	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1254
1255	RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD,
1256	    "%s: Rx event code=%d len=%d\n", __func__, code, len);
1257	switch (code) {
1258	case R92S_EVT_SURVEY:
1259		if (vap->iv_state == IEEE80211_S_SCAN)
1260			rsu_event_survey(sc, buf, len);
1261		break;
1262	case R92S_EVT_SURVEY_DONE:
1263		RSU_DPRINTF(sc, RSU_DEBUG_SCAN,
1264		    "%s: site survey pass %d done, found %d BSS\n",
1265		    __func__, sc->sc_scan_pass, le32toh(*(uint32_t *)buf));
1266		if (vap->iv_state != IEEE80211_S_SCAN)
1267			break;	/* Ignore if not scanning. */
1268		if (sc->sc_scan_pass == 0 && vap->iv_des_nssid != 0) {
1269			/* Schedule a directed scan for hidden APs. */
1270			sc->sc_scan_pass = 1;
1271			RSU_UNLOCK(sc);
1272			ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1273			RSU_LOCK(sc);
1274			break;
1275		}
1276		sc->sc_scan_pass = 0;
1277		break;
1278	case R92S_EVT_JOIN_BSS:
1279		if (vap->iv_state == IEEE80211_S_AUTH)
1280			rsu_event_join_bss(sc, buf, len);
1281		break;
1282	case R92S_EVT_DEL_STA:
1283		RSU_DPRINTF(sc, RSU_DEBUG_FWCMD | RSU_DEBUG_STATE,
1284		    "%s: disassociated from %s\n", __func__,
1285		    ether_sprintf(buf));
1286		if (vap->iv_state == IEEE80211_S_RUN &&
1287		    IEEE80211_ADDR_EQ(vap->iv_bss->ni_bssid, buf)) {
1288			RSU_UNLOCK(sc);
1289			ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1290			RSU_LOCK(sc);
1291		}
1292		break;
1293	case R92S_EVT_WPS_PBC:
1294		RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD,
1295		    "%s: WPS PBC pushed.\n", __func__);
1296		break;
1297	case R92S_EVT_FWDBG:
1298		buf[60] = '\0';
1299		RSU_DPRINTF(sc, RSU_DEBUG_FWDBG, "FWDBG: %s\n", (char *)buf);
1300		break;
1301	default:
1302		RSU_DPRINTF(sc, RSU_DEBUG_ANY, "%s: unhandled code (%d)\n",
1303		    __func__, code);
1304		break;
1305	}
1306}
1307
1308static void
1309rsu_rx_multi_event(struct rsu_softc *sc, uint8_t *buf, int len)
1310{
1311	struct r92s_fw_cmd_hdr *cmd;
1312	int cmdsz;
1313
1314	RSU_DPRINTF(sc, RSU_DEBUG_RX, "%s: Rx events len=%d\n", __func__, len);
1315
1316	/* Skip Rx status. */
1317	buf += sizeof(struct r92s_rx_stat);
1318	len -= sizeof(struct r92s_rx_stat);
1319
1320	/* Process all events. */
1321	for (;;) {
1322		/* Check that command header fits. */
1323		if (__predict_false(len < sizeof(*cmd)))
1324			break;
1325		cmd = (struct r92s_fw_cmd_hdr *)buf;
1326		/* Check that command payload fits. */
1327		cmdsz = le16toh(cmd->len);
1328		if (__predict_false(len < sizeof(*cmd) + cmdsz))
1329			break;
1330
1331		/* Process firmware event. */
1332		rsu_rx_event(sc, cmd->code, (uint8_t *)&cmd[1], cmdsz);
1333
1334		if (!(cmd->seq & R92S_FW_CMD_MORE))
1335			break;
1336		buf += sizeof(*cmd) + cmdsz;
1337		len -= sizeof(*cmd) + cmdsz;
1338	}
1339}
1340
1341static int8_t
1342rsu_get_rssi(struct rsu_softc *sc, int rate, void *physt)
1343{
1344	static const int8_t cckoff[] = { 14, -2, -20, -40 };
1345	struct r92s_rx_phystat *phy;
1346	struct r92s_rx_cck *cck;
1347	uint8_t rpt;
1348	int8_t rssi;
1349
1350	if (rate <= 3) {
1351		cck = (struct r92s_rx_cck *)physt;
1352		rpt = (cck->agc_rpt >> 6) & 0x3;
1353		rssi = cck->agc_rpt & 0x3e;
1354		rssi = cckoff[rpt] - rssi;
1355	} else {	/* OFDM/HT. */
1356		phy = (struct r92s_rx_phystat *)physt;
1357		rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 106;
1358	}
1359	return (rssi);
1360}
1361
1362static struct mbuf *
1363rsu_rx_frame(struct rsu_softc *sc, uint8_t *buf, int pktlen, int *rssi)
1364{
1365	struct ieee80211com *ic = &sc->sc_ic;
1366	struct ieee80211_frame *wh;
1367	struct r92s_rx_stat *stat;
1368	uint32_t rxdw0, rxdw3;
1369	struct mbuf *m;
1370	uint8_t rate;
1371	int infosz;
1372
1373	stat = (struct r92s_rx_stat *)buf;
1374	rxdw0 = le32toh(stat->rxdw0);
1375	rxdw3 = le32toh(stat->rxdw3);
1376
1377	if (__predict_false(rxdw0 & R92S_RXDW0_CRCERR)) {
1378		counter_u64_add(ic->ic_ierrors, 1);
1379		return NULL;
1380	}
1381	if (__predict_false(pktlen < sizeof(*wh) || pktlen > MCLBYTES)) {
1382		counter_u64_add(ic->ic_ierrors, 1);
1383		return NULL;
1384	}
1385
1386	rate = MS(rxdw3, R92S_RXDW3_RATE);
1387	infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
1388
1389	/* Get RSSI from PHY status descriptor if present. */
1390	if (infosz != 0)
1391		*rssi = rsu_get_rssi(sc, rate, &stat[1]);
1392	else
1393		*rssi = 0;
1394
1395	RSU_DPRINTF(sc, RSU_DEBUG_RX,
1396	    "%s: Rx frame len=%d rate=%d infosz=%d rssi=%d\n",
1397	    __func__,
1398	    pktlen, rate, infosz, *rssi);
1399
1400	m = m_get2(pktlen, M_NOWAIT, MT_DATA, M_PKTHDR);
1401	if (__predict_false(m == NULL)) {
1402		counter_u64_add(ic->ic_ierrors, 1);
1403		return NULL;
1404	}
1405	/* Hardware does Rx TCP checksum offload. */
1406	if (rxdw3 & R92S_RXDW3_TCPCHKVALID) {
1407		if (__predict_true(rxdw3 & R92S_RXDW3_TCPCHKRPT))
1408			m->m_pkthdr.csum_flags |= CSUM_DATA_VALID;
1409	}
1410	wh = (struct ieee80211_frame *)((uint8_t *)&stat[1] + infosz);
1411	memcpy(mtod(m, uint8_t *), wh, pktlen);
1412	m->m_pkthdr.len = m->m_len = pktlen;
1413
1414	if (ieee80211_radiotap_active(ic)) {
1415		struct rsu_rx_radiotap_header *tap = &sc->sc_rxtap;
1416
1417		/* Map HW rate index to 802.11 rate. */
1418		tap->wr_flags = 2;
1419		if (!(rxdw3 & R92S_RXDW3_HTC)) {
1420			switch (rate) {
1421			/* CCK. */
1422			case  0: tap->wr_rate =   2; break;
1423			case  1: tap->wr_rate =   4; break;
1424			case  2: tap->wr_rate =  11; break;
1425			case  3: tap->wr_rate =  22; break;
1426			/* OFDM. */
1427			case  4: tap->wr_rate =  12; break;
1428			case  5: tap->wr_rate =  18; break;
1429			case  6: tap->wr_rate =  24; break;
1430			case  7: tap->wr_rate =  36; break;
1431			case  8: tap->wr_rate =  48; break;
1432			case  9: tap->wr_rate =  72; break;
1433			case 10: tap->wr_rate =  96; break;
1434			case 11: tap->wr_rate = 108; break;
1435			}
1436		} else if (rate >= 12) {	/* MCS0~15. */
1437			/* Bit 7 set means HT MCS instead of rate. */
1438			tap->wr_rate = 0x80 | (rate - 12);
1439		}
1440		tap->wr_dbm_antsignal = *rssi;
1441		tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
1442		tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
1443	}
1444
1445	return (m);
1446}
1447
1448static struct mbuf *
1449rsu_rx_multi_frame(struct rsu_softc *sc, uint8_t *buf, int len, int *rssi)
1450{
1451	struct r92s_rx_stat *stat;
1452	uint32_t rxdw0;
1453	int totlen, pktlen, infosz, npkts;
1454	struct mbuf *m, *m0 = NULL, *prevm = NULL;
1455
1456	/* Get the number of encapsulated frames. */
1457	stat = (struct r92s_rx_stat *)buf;
1458	npkts = MS(le32toh(stat->rxdw2), R92S_RXDW2_PKTCNT);
1459	RSU_DPRINTF(sc, RSU_DEBUG_RX,
1460	    "%s: Rx %d frames in one chunk\n", __func__, npkts);
1461
1462	/* Process all of them. */
1463	while (npkts-- > 0) {
1464		if (__predict_false(len < sizeof(*stat)))
1465			break;
1466		stat = (struct r92s_rx_stat *)buf;
1467		rxdw0 = le32toh(stat->rxdw0);
1468
1469		pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN);
1470		if (__predict_false(pktlen == 0))
1471			break;
1472
1473		infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8;
1474
1475		/* Make sure everything fits in xfer. */
1476		totlen = sizeof(*stat) + infosz + pktlen;
1477		if (__predict_false(totlen > len))
1478			break;
1479
1480		/* Process 802.11 frame. */
1481		m = rsu_rx_frame(sc, buf, pktlen, rssi);
1482		if (m0 == NULL)
1483			m0 = m;
1484		if (prevm == NULL)
1485			prevm = m;
1486		else {
1487			prevm->m_next = m;
1488			prevm = m;
1489		}
1490		/* Next chunk is 128-byte aligned. */
1491		totlen = (totlen + 127) & ~127;
1492		buf += totlen;
1493		len -= totlen;
1494	}
1495
1496	return (m0);
1497}
1498
1499static struct mbuf *
1500rsu_rxeof(struct usb_xfer *xfer, struct rsu_data *data, int *rssi)
1501{
1502	struct rsu_softc *sc = data->sc;
1503	struct ieee80211com *ic = &sc->sc_ic;
1504	struct r92s_rx_stat *stat;
1505	int len;
1506
1507	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
1508
1509	if (__predict_false(len < sizeof(*stat))) {
1510		DPRINTF("xfer too short %d\n", len);
1511		counter_u64_add(ic->ic_ierrors, 1);
1512		return (NULL);
1513	}
1514	/* Determine if it is a firmware C2H event or an 802.11 frame. */
1515	stat = (struct r92s_rx_stat *)data->buf;
1516	if ((le32toh(stat->rxdw1) & 0x1ff) == 0x1ff) {
1517		rsu_rx_multi_event(sc, data->buf, len);
1518		/* No packets to process. */
1519		return (NULL);
1520	} else
1521		return (rsu_rx_multi_frame(sc, data->buf, len, rssi));
1522}
1523
1524static void
1525rsu_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
1526{
1527	struct rsu_softc *sc = usbd_xfer_softc(xfer);
1528	struct ieee80211com *ic = &sc->sc_ic;
1529	struct ieee80211_frame *wh;
1530	struct ieee80211_node *ni;
1531	struct mbuf *m = NULL, *next;
1532	struct rsu_data *data;
1533	int rssi = 1;
1534
1535	RSU_ASSERT_LOCKED(sc);
1536
1537	switch (USB_GET_STATE(xfer)) {
1538	case USB_ST_TRANSFERRED:
1539		data = STAILQ_FIRST(&sc->sc_rx_active);
1540		if (data == NULL)
1541			goto tr_setup;
1542		STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
1543		m = rsu_rxeof(xfer, data, &rssi);
1544		STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
1545		/* FALLTHROUGH */
1546	case USB_ST_SETUP:
1547tr_setup:
1548		data = STAILQ_FIRST(&sc->sc_rx_inactive);
1549		if (data == NULL) {
1550			KASSERT(m == NULL, ("mbuf isn't NULL"));
1551			return;
1552		}
1553		STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next);
1554		STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next);
1555		usbd_xfer_set_frame_data(xfer, 0, data->buf,
1556		    usbd_xfer_max_len(xfer));
1557		usbd_transfer_submit(xfer);
1558		/*
1559		 * To avoid LOR we should unlock our private mutex here to call
1560		 * ieee80211_input() because here is at the end of a USB
1561		 * callback and safe to unlock.
1562		 */
1563		RSU_UNLOCK(sc);
1564		while (m != NULL) {
1565			next = m->m_next;
1566			m->m_next = NULL;
1567			wh = mtod(m, struct ieee80211_frame *);
1568			ni = ieee80211_find_rxnode(ic,
1569			    (struct ieee80211_frame_min *)wh);
1570			if (ni != NULL) {
1571				(void)ieee80211_input(ni, m, rssi, 0);
1572				ieee80211_free_node(ni);
1573			} else
1574				(void)ieee80211_input_all(ic, m, rssi, 0);
1575			m = next;
1576		}
1577		RSU_LOCK(sc);
1578		break;
1579	default:
1580		/* needs it to the inactive queue due to a error. */
1581		data = STAILQ_FIRST(&sc->sc_rx_active);
1582		if (data != NULL) {
1583			STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
1584			STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
1585		}
1586		if (error != USB_ERR_CANCELLED) {
1587			usbd_xfer_set_stall(xfer);
1588			counter_u64_add(ic->ic_ierrors, 1);
1589			goto tr_setup;
1590		}
1591		break;
1592	}
1593
1594}
1595
1596static void
1597rsu_txeof(struct usb_xfer *xfer, struct rsu_data *data)
1598{
1599#ifdef	USB_DEBUG
1600	struct rsu_softc *sc = usbd_xfer_softc(xfer);
1601#endif
1602
1603	RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: called; data=%p\n",
1604	    __func__,
1605	    data);
1606
1607	if (data->m) {
1608		/* XXX status? */
1609		ieee80211_tx_complete(data->ni, data->m, 0);
1610		data->m = NULL;
1611		data->ni = NULL;
1612	}
1613}
1614
1615static void
1616rsu_bulk_tx_callback_sub(struct usb_xfer *xfer, usb_error_t error,
1617    uint8_t which)
1618{
1619	struct rsu_softc *sc = usbd_xfer_softc(xfer);
1620	struct ieee80211com *ic = &sc->sc_ic;
1621	struct rsu_data *data;
1622
1623	RSU_ASSERT_LOCKED(sc);
1624
1625	switch (USB_GET_STATE(xfer)) {
1626	case USB_ST_TRANSFERRED:
1627		data = STAILQ_FIRST(&sc->sc_tx_active[which]);
1628		if (data == NULL)
1629			goto tr_setup;
1630		RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: transfer done %p\n",
1631		    __func__, data);
1632		STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
1633		rsu_txeof(xfer, data);
1634		STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, data, next);
1635		/* FALLTHROUGH */
1636	case USB_ST_SETUP:
1637tr_setup:
1638		data = STAILQ_FIRST(&sc->sc_tx_pending[which]);
1639		if (data == NULL) {
1640			RSU_DPRINTF(sc, RSU_DEBUG_TXDONE,
1641			    "%s: empty pending queue sc %p\n", __func__, sc);
1642			return;
1643		}
1644		STAILQ_REMOVE_HEAD(&sc->sc_tx_pending[which], next);
1645		STAILQ_INSERT_TAIL(&sc->sc_tx_active[which], data, next);
1646		usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen);
1647		RSU_DPRINTF(sc, RSU_DEBUG_TXDONE,
1648		    "%s: submitting transfer %p\n",
1649		    __func__,
1650		    data);
1651		usbd_transfer_submit(xfer);
1652		break;
1653	default:
1654		data = STAILQ_FIRST(&sc->sc_tx_active[which]);
1655		if (data != NULL) {
1656			STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
1657			rsu_txeof(xfer, data);
1658			STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, data, next);
1659		}
1660		counter_u64_add(ic->ic_oerrors, 1);
1661
1662		if (error != USB_ERR_CANCELLED) {
1663			usbd_xfer_set_stall(xfer);
1664			goto tr_setup;
1665		}
1666		break;
1667	}
1668}
1669
1670static void
1671rsu_bulk_tx_callback_be_bk(struct usb_xfer *xfer, usb_error_t error)
1672{
1673	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_BE_BK);
1674}
1675
1676static void
1677rsu_bulk_tx_callback_vi_vo(struct usb_xfer *xfer, usb_error_t error)
1678{
1679	rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_VI_VO);
1680}
1681
1682static int
1683rsu_tx_start(struct rsu_softc *sc, struct ieee80211_node *ni,
1684    struct mbuf *m0, struct rsu_data *data)
1685{
1686	struct ieee80211com *ic = &sc->sc_ic;
1687        struct ieee80211vap *vap = ni->ni_vap;
1688	struct ieee80211_frame *wh;
1689	struct ieee80211_key *k = NULL;
1690	struct r92s_tx_desc *txd;
1691	uint8_t type;
1692	uint8_t tid = 0;
1693	uint8_t which;
1694	int hasqos;
1695	int xferlen;
1696
1697	RSU_ASSERT_LOCKED(sc);
1698
1699	wh = mtod(m0, struct ieee80211_frame *);
1700	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1701
1702	RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: data=%p, m=%p\n",
1703	    __func__, data, m0);
1704
1705	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1706		k = ieee80211_crypto_encap(ni, m0);
1707		if (k == NULL) {
1708			device_printf(sc->sc_dev,
1709			    "ieee80211_crypto_encap returns NULL.\n");
1710			/* XXX we don't expect the fragmented frames */
1711			m_freem(m0);
1712			return (ENOBUFS);
1713		}
1714		wh = mtod(m0, struct ieee80211_frame *);
1715	}
1716	switch (type) {
1717	case IEEE80211_FC0_TYPE_CTL:
1718	case IEEE80211_FC0_TYPE_MGT:
1719		which = rsu_wme_ac_xfer_map[WME_AC_VO];
1720		break;
1721	default:
1722		which = rsu_wme_ac_xfer_map[M_WME_GETAC(m0)];
1723		break;
1724	}
1725	hasqos = 0;
1726
1727	/* Fill Tx descriptor. */
1728	txd = (struct r92s_tx_desc *)data->buf;
1729	memset(txd, 0, sizeof(*txd));
1730
1731	txd->txdw0 |= htole32(
1732	    SM(R92S_TXDW0_PKTLEN, m0->m_pkthdr.len) |
1733	    SM(R92S_TXDW0_OFFSET, sizeof(*txd)) |
1734	    R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG);
1735
1736	txd->txdw1 |= htole32(
1737	    SM(R92S_TXDW1_MACID, R92S_MACID_BSS) |
1738	    SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_BE));
1739	if (!hasqos)
1740		txd->txdw1 |= htole32(R92S_TXDW1_NONQOS);
1741#ifdef notyet
1742	if (k != NULL) {
1743		switch (k->wk_cipher->ic_cipher) {
1744		case IEEE80211_CIPHER_WEP:
1745			cipher = R92S_TXDW1_CIPHER_WEP;
1746			break;
1747		case IEEE80211_CIPHER_TKIP:
1748			cipher = R92S_TXDW1_CIPHER_TKIP;
1749			break;
1750		case IEEE80211_CIPHER_AES_CCM:
1751			cipher = R92S_TXDW1_CIPHER_AES;
1752			break;
1753		default:
1754			cipher = R92S_TXDW1_CIPHER_NONE;
1755		}
1756		txd->txdw1 |= htole32(
1757		    SM(R92S_TXDW1_CIPHER, cipher) |
1758		    SM(R92S_TXDW1_KEYIDX, k->k_id));
1759	}
1760#endif
1761	txd->txdw2 |= htole32(R92S_TXDW2_BK);
1762	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1763		txd->txdw2 |= htole32(R92S_TXDW2_BMCAST);
1764	/*
1765	 * Firmware will use and increment the sequence number for the
1766	 * specified TID.
1767	 */
1768	txd->txdw3 |= htole32(SM(R92S_TXDW3_SEQ, tid));
1769
1770	if (ieee80211_radiotap_active_vap(vap)) {
1771		struct rsu_tx_radiotap_header *tap = &sc->sc_txtap;
1772
1773		tap->wt_flags = 0;
1774		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1775		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1776		ieee80211_radiotap_tx(vap, m0);
1777	}
1778
1779	xferlen = sizeof(*txd) + m0->m_pkthdr.len;
1780	m_copydata(m0, 0, m0->m_pkthdr.len, (caddr_t)&txd[1]);
1781
1782	data->buflen = xferlen;
1783	data->ni = ni;
1784	data->m = m0;
1785	STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
1786
1787	/* start transfer, if any */
1788	usbd_transfer_start(sc->sc_xfer[which]);
1789	return (0);
1790}
1791
1792static int
1793rsu_transmit(struct ieee80211com *ic, struct mbuf *m)
1794{
1795	struct rsu_softc *sc = ic->ic_softc;
1796	int error;
1797
1798	RSU_LOCK(sc);
1799	if (!sc->sc_running) {
1800		RSU_UNLOCK(sc);
1801		return (ENXIO);
1802	}
1803	error = mbufq_enqueue(&sc->sc_snd, m);
1804	if (error) {
1805		RSU_UNLOCK(sc);
1806		return (error);
1807	}
1808	rsu_start(sc);
1809	RSU_UNLOCK(sc);
1810
1811	return (0);
1812}
1813
1814static void
1815rsu_start(struct rsu_softc *sc)
1816{
1817	struct ieee80211_node *ni;
1818	struct rsu_data *bf;
1819	struct mbuf *m;
1820
1821	RSU_ASSERT_LOCKED(sc);
1822
1823	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
1824		bf = rsu_getbuf(sc);
1825		if (bf == NULL) {
1826			mbufq_prepend(&sc->sc_snd, m);
1827			break;
1828		}
1829
1830		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
1831		m->m_pkthdr.rcvif = NULL;
1832
1833		if (rsu_tx_start(sc, ni, m, bf) != 0) {
1834			if_inc_counter(ni->ni_vap->iv_ifp,
1835			    IFCOUNTER_OERRORS, 1);
1836			STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
1837			ieee80211_free_node(ni);
1838			break;
1839		}
1840	}
1841}
1842
1843static void
1844rsu_parent(struct ieee80211com *ic)
1845{
1846	struct rsu_softc *sc = ic->ic_softc;
1847	int startall = 0;
1848
1849	RSU_LOCK(sc);
1850	if (ic->ic_nrunning > 0) {
1851		if (!sc->sc_running) {
1852			rsu_init(sc);
1853			startall = 1;
1854		}
1855	} else if (sc->sc_running)
1856		rsu_stop(sc);
1857	RSU_UNLOCK(sc);
1858
1859	if (startall)
1860		ieee80211_start_all(ic);
1861}
1862
1863/*
1864 * Power on sequence for A-cut adapters.
1865 */
1866static void
1867rsu_power_on_acut(struct rsu_softc *sc)
1868{
1869	uint32_t reg;
1870
1871	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
1872	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
1873
1874	/* Enable AFE macro block's bandgap and Mbias. */
1875	rsu_write_1(sc, R92S_AFE_MISC,
1876	    rsu_read_1(sc, R92S_AFE_MISC) |
1877	    R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN);
1878	/* Enable LDOA15 block. */
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_SPS1_CTRL,
1883	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_LDEN);
1884	usb_pause_mtx(&sc->sc_mtx, 2 * hz);
1885	/* Enable switch regulator block. */
1886	rsu_write_1(sc, R92S_SPS1_CTRL,
1887	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_SWEN);
1888
1889	rsu_write_4(sc, R92S_SPS1_CTRL, 0x00a7b267);
1890
1891	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1892	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
1893
1894	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1895	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
1896
1897	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1898	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x90);
1899
1900	/* Enable AFE clock. */
1901	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
1902	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
1903	/* Enable AFE PLL macro block. */
1904	rsu_write_1(sc, R92S_AFE_PLL_CTRL,
1905	    rsu_read_1(sc, R92S_AFE_PLL_CTRL) | 0x11);
1906	/* Attach AFE PLL to MACTOP/BB. */
1907	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
1908	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
1909
1910	/* Switch to 40MHz clock instead of 80MHz. */
1911	rsu_write_2(sc, R92S_SYS_CLKR,
1912	    rsu_read_2(sc, R92S_SYS_CLKR) & ~R92S_SYS_CLKSEL);
1913
1914	/* Enable MAC clock. */
1915	rsu_write_2(sc, R92S_SYS_CLKR,
1916	    rsu_read_2(sc, R92S_SYS_CLKR) |
1917	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
1918
1919	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
1920
1921	/* Enable digital core and IOREG R/W. */
1922	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1923	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
1924
1925	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1926	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
1927
1928	/* Switch the control path to firmware. */
1929	reg = rsu_read_2(sc, R92S_SYS_CLKR);
1930	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
1931	rsu_write_2(sc, R92S_SYS_CLKR, reg);
1932
1933	rsu_write_2(sc, R92S_CR, 0x37fc);
1934
1935	/* Fix USB RX FIFO issue. */
1936	rsu_write_1(sc, 0xfe5c,
1937	    rsu_read_1(sc, 0xfe5c) | 0x80);
1938	rsu_write_1(sc, 0x00ab,
1939	    rsu_read_1(sc, 0x00ab) | 0xc0);
1940
1941	rsu_write_1(sc, R92S_SYS_CLKR,
1942	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
1943}
1944
1945/*
1946 * Power on sequence for B-cut and C-cut adapters.
1947 */
1948static void
1949rsu_power_on_bcut(struct rsu_softc *sc)
1950{
1951	uint32_t reg;
1952	int ntries;
1953
1954	/* Prevent eFuse leakage. */
1955	rsu_write_1(sc, 0x37, 0xb0);
1956	usb_pause_mtx(&sc->sc_mtx, hz / 100);
1957	rsu_write_1(sc, 0x37, 0x30);
1958
1959	/* Switch the control path to hardware. */
1960	reg = rsu_read_2(sc, R92S_SYS_CLKR);
1961	if (reg & R92S_FWHW_SEL) {
1962		rsu_write_2(sc, R92S_SYS_CLKR,
1963		    reg & ~(R92S_SWHW_SEL | R92S_FWHW_SEL));
1964	}
1965	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1966	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) & ~0x8c);
1967	rsu_ms_delay(sc);
1968
1969	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
1970	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
1971
1972	reg = rsu_read_1(sc, R92S_AFE_MISC);
1973	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN);
1974	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN |
1975	    R92S_AFE_MISC_MBEN | R92S_AFE_MISC_I32_EN);
1976
1977	/* Enable PLL. */
1978	rsu_write_1(sc, R92S_LDOA15_CTRL,
1979	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
1980
1981	rsu_write_1(sc, R92S_LDOV12D_CTRL,
1982	    rsu_read_1(sc, R92S_LDOV12D_CTRL) | R92S_LDV12_EN);
1983
1984	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1985	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
1986
1987	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1988	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
1989
1990	/* Support 64KB IMEM. */
1991	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1992	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x97);
1993
1994	/* Enable AFE clock. */
1995	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
1996	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
1997	/* Enable AFE PLL macro block. */
1998	reg = rsu_read_1(sc, R92S_AFE_PLL_CTRL);
1999	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
2000	rsu_ms_delay(sc);
2001	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x51);
2002	rsu_ms_delay(sc);
2003	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
2004	rsu_ms_delay(sc);
2005
2006	/* Attach AFE PLL to MACTOP/BB. */
2007	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
2008	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
2009
2010	/* Switch to 40MHz clock. */
2011	rsu_write_1(sc, R92S_SYS_CLKR, 0x00);
2012	/* Disable CPU clock and 80MHz SSC. */
2013	rsu_write_1(sc, R92S_SYS_CLKR,
2014	    rsu_read_1(sc, R92S_SYS_CLKR) | 0xa0);
2015	/* Enable MAC clock. */
2016	rsu_write_2(sc, R92S_SYS_CLKR,
2017	    rsu_read_2(sc, R92S_SYS_CLKR) |
2018	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
2019
2020	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
2021
2022	/* Enable digital core and IOREG R/W. */
2023	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2024	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
2025
2026	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2027	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
2028
2029	/* Switch the control path to firmware. */
2030	reg = rsu_read_2(sc, R92S_SYS_CLKR);
2031	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
2032	rsu_write_2(sc, R92S_SYS_CLKR, reg);
2033
2034	rsu_write_2(sc, R92S_CR, 0x37fc);
2035
2036	/* Fix USB RX FIFO issue. */
2037	rsu_write_1(sc, 0xfe5c,
2038	    rsu_read_1(sc, 0xfe5c) | 0x80);
2039
2040	rsu_write_1(sc, R92S_SYS_CLKR,
2041	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
2042
2043	rsu_write_1(sc, 0xfe1c, 0x80);
2044
2045	/* Make sure TxDMA is ready to download firmware. */
2046	for (ntries = 0; ntries < 20; ntries++) {
2047		reg = rsu_read_1(sc, R92S_TCR);
2048		if ((reg & (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) ==
2049		    (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT))
2050			break;
2051		rsu_ms_delay(sc);
2052	}
2053	if (ntries == 20) {
2054		RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_TX,
2055		    "%s: TxDMA is not ready\n",
2056		    __func__);
2057		/* Reset TxDMA. */
2058		reg = rsu_read_1(sc, R92S_CR);
2059		rsu_write_1(sc, R92S_CR, reg & ~R92S_CR_TXDMA_EN);
2060		rsu_ms_delay(sc);
2061		rsu_write_1(sc, R92S_CR, reg | R92S_CR_TXDMA_EN);
2062	}
2063}
2064
2065static void
2066rsu_power_off(struct rsu_softc *sc)
2067{
2068	/* Turn RF off. */
2069	rsu_write_1(sc, R92S_RF_CTRL, 0x00);
2070	usb_pause_mtx(&sc->sc_mtx, hz / 200);
2071
2072	/* Turn MAC off. */
2073	/* Switch control path. */
2074	rsu_write_1(sc, R92S_SYS_CLKR + 1, 0x38);
2075	/* Reset MACTOP. */
2076	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x70);
2077	rsu_write_1(sc, R92S_PMC_FSM, 0x06);
2078	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 0, 0xf9);
2079	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, 0xe8);
2080
2081	/* Disable AFE PLL. */
2082	rsu_write_1(sc, R92S_AFE_PLL_CTRL, 0x00);
2083	/* Disable A15V. */
2084	rsu_write_1(sc, R92S_LDOA15_CTRL, 0x54);
2085	/* Disable eFuse 1.2V. */
2086	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x50);
2087	rsu_write_1(sc, R92S_LDOV12D_CTRL, 0x24);
2088	/* Enable AFE macro block's bandgap and Mbias. */
2089	rsu_write_1(sc, R92S_AFE_MISC, 0x30);
2090	/* Disable 1.6V LDO. */
2091	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x56);
2092	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x43);
2093}
2094
2095static int
2096rsu_fw_loadsection(struct rsu_softc *sc, const uint8_t *buf, int len)
2097{
2098	const uint8_t which = rsu_wme_ac_xfer_map[WME_AC_VO];
2099	struct rsu_data *data;
2100	struct r92s_tx_desc *txd;
2101	int mlen;
2102
2103	while (len > 0) {
2104		data = rsu_getbuf(sc);
2105		if (data == NULL)
2106			return (ENOMEM);
2107		txd = (struct r92s_tx_desc *)data->buf;
2108		memset(txd, 0, sizeof(*txd));
2109		if (len <= RSU_TXBUFSZ - sizeof(*txd)) {
2110			/* Last chunk. */
2111			txd->txdw0 |= htole32(R92S_TXDW0_LINIP);
2112			mlen = len;
2113		} else
2114			mlen = RSU_TXBUFSZ - sizeof(*txd);
2115		txd->txdw0 |= htole32(SM(R92S_TXDW0_PKTLEN, mlen));
2116		memcpy(&txd[1], buf, mlen);
2117		data->buflen = sizeof(*txd) + mlen;
2118		RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FW | RSU_DEBUG_RESET,
2119		    "%s: starting transfer %p\n",
2120		    __func__, data);
2121		STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
2122		buf += mlen;
2123		len -= mlen;
2124	}
2125	usbd_transfer_start(sc->sc_xfer[which]);
2126	return (0);
2127}
2128
2129static int
2130rsu_load_firmware(struct rsu_softc *sc)
2131{
2132	const struct r92s_fw_hdr *hdr;
2133	struct r92s_fw_priv *dmem;
2134	const uint8_t *imem, *emem;
2135	int imemsz, ememsz;
2136	const struct firmware *fw;
2137	size_t size;
2138	uint32_t reg;
2139	int ntries, error;
2140
2141	if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY) {
2142		RSU_DPRINTF(sc, RSU_DEBUG_FW | RSU_DEBUG_RESET,
2143		    "%s: Firmware already loaded\n",
2144		    __func__);
2145		return (0);
2146	}
2147
2148	RSU_UNLOCK(sc);
2149	/* Read firmware image from the filesystem. */
2150	if ((fw = firmware_get("rsu-rtl8712fw")) == NULL) {
2151		device_printf(sc->sc_dev,
2152		    "%s: failed load firmware of file rsu-rtl8712fw\n",
2153		    __func__);
2154		RSU_LOCK(sc);
2155		return (ENXIO);
2156	}
2157	RSU_LOCK(sc);
2158	size = fw->datasize;
2159	if (size < sizeof(*hdr)) {
2160		device_printf(sc->sc_dev, "firmware too short\n");
2161		error = EINVAL;
2162		goto fail;
2163	}
2164	hdr = (const struct r92s_fw_hdr *)fw->data;
2165	if (hdr->signature != htole16(0x8712) &&
2166	    hdr->signature != htole16(0x8192)) {
2167		device_printf(sc->sc_dev,
2168		    "invalid firmware signature 0x%x\n",
2169		    le16toh(hdr->signature));
2170		error = EINVAL;
2171		goto fail;
2172	}
2173	DPRINTF("FW V%d %02x-%02x %02x:%02x\n", le16toh(hdr->version),
2174	    hdr->month, hdr->day, hdr->hour, hdr->minute);
2175
2176	/* Make sure that driver and firmware are in sync. */
2177	if (hdr->privsz != htole32(sizeof(*dmem))) {
2178		device_printf(sc->sc_dev, "unsupported firmware image\n");
2179		error = EINVAL;
2180		goto fail;
2181	}
2182	/* Get FW sections sizes. */
2183	imemsz = le32toh(hdr->imemsz);
2184	ememsz = le32toh(hdr->sramsz);
2185	/* Check that all FW sections fit in image. */
2186	if (size < sizeof(*hdr) + imemsz + ememsz) {
2187		device_printf(sc->sc_dev, "firmware too short\n");
2188		error = EINVAL;
2189		goto fail;
2190	}
2191	imem = (const uint8_t *)&hdr[1];
2192	emem = imem + imemsz;
2193
2194	/* Load IMEM section. */
2195	error = rsu_fw_loadsection(sc, imem, imemsz);
2196	if (error != 0) {
2197		device_printf(sc->sc_dev,
2198		    "could not load firmware section %s\n", "IMEM");
2199		goto fail;
2200	}
2201	/* Wait for load to complete. */
2202	for (ntries = 0; ntries != 50; ntries++) {
2203		usb_pause_mtx(&sc->sc_mtx, hz / 100);
2204		reg = rsu_read_1(sc, R92S_TCR);
2205		if (reg & R92S_TCR_IMEM_CODE_DONE)
2206			break;
2207	}
2208	if (ntries == 50) {
2209		device_printf(sc->sc_dev, "timeout waiting for IMEM transfer\n");
2210		error = ETIMEDOUT;
2211		goto fail;
2212	}
2213	/* Load EMEM section. */
2214	error = rsu_fw_loadsection(sc, emem, ememsz);
2215	if (error != 0) {
2216		device_printf(sc->sc_dev,
2217		    "could not load firmware section %s\n", "EMEM");
2218		goto fail;
2219	}
2220	/* Wait for load to complete. */
2221	for (ntries = 0; ntries != 50; ntries++) {
2222		usb_pause_mtx(&sc->sc_mtx, hz / 100);
2223		reg = rsu_read_2(sc, R92S_TCR);
2224		if (reg & R92S_TCR_EMEM_CODE_DONE)
2225			break;
2226	}
2227	if (ntries == 50) {
2228		device_printf(sc->sc_dev, "timeout waiting for EMEM transfer\n");
2229		error = ETIMEDOUT;
2230		goto fail;
2231	}
2232	/* Enable CPU. */
2233	rsu_write_1(sc, R92S_SYS_CLKR,
2234	    rsu_read_1(sc, R92S_SYS_CLKR) | R92S_SYS_CPU_CLKSEL);
2235	if (!(rsu_read_1(sc, R92S_SYS_CLKR) & R92S_SYS_CPU_CLKSEL)) {
2236		device_printf(sc->sc_dev, "could not enable system clock\n");
2237		error = EIO;
2238		goto fail;
2239	}
2240	rsu_write_2(sc, R92S_SYS_FUNC_EN,
2241	    rsu_read_2(sc, R92S_SYS_FUNC_EN) | R92S_FEN_CPUEN);
2242	if (!(rsu_read_2(sc, R92S_SYS_FUNC_EN) & R92S_FEN_CPUEN)) {
2243		device_printf(sc->sc_dev,
2244		    "could not enable microcontroller\n");
2245		error = EIO;
2246		goto fail;
2247	}
2248	/* Wait for CPU to initialize. */
2249	for (ntries = 0; ntries < 100; ntries++) {
2250		if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_IMEM_RDY)
2251			break;
2252		rsu_ms_delay(sc);
2253	}
2254	if (ntries == 100) {
2255		device_printf(sc->sc_dev,
2256		    "timeout waiting for microcontroller\n");
2257		error = ETIMEDOUT;
2258		goto fail;
2259	}
2260
2261	/* Update DMEM section before loading. */
2262	dmem = __DECONST(struct r92s_fw_priv *, &hdr->priv);
2263	memset(dmem, 0, sizeof(*dmem));
2264	dmem->hci_sel = R92S_HCI_SEL_USB | R92S_HCI_SEL_8172;
2265	dmem->nendpoints = 0;
2266	dmem->rf_config = 0x12;	/* 1T2R */
2267	dmem->vcs_type = R92S_VCS_TYPE_AUTO;
2268	dmem->vcs_mode = R92S_VCS_MODE_RTS_CTS;
2269#ifdef notyet
2270	dmem->bw40_en = (ic->ic_htcaps & IEEE80211_HTCAP_CBW20_40) != 0;
2271#endif
2272	dmem->turbo_mode = 1;
2273	/* Load DMEM section. */
2274	error = rsu_fw_loadsection(sc, (uint8_t *)dmem, sizeof(*dmem));
2275	if (error != 0) {
2276		device_printf(sc->sc_dev,
2277		    "could not load firmware section %s\n", "DMEM");
2278		goto fail;
2279	}
2280	/* Wait for load to complete. */
2281	for (ntries = 0; ntries < 100; ntries++) {
2282		if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_DMEM_CODE_DONE)
2283			break;
2284		rsu_ms_delay(sc);
2285	}
2286	if (ntries == 100) {
2287		device_printf(sc->sc_dev, "timeout waiting for %s transfer\n",
2288		    "DMEM");
2289		error = ETIMEDOUT;
2290		goto fail;
2291	}
2292	/* Wait for firmware readiness. */
2293	for (ntries = 0; ntries < 60; ntries++) {
2294		if (!(rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY))
2295			break;
2296		rsu_ms_delay(sc);
2297	}
2298	if (ntries == 60) {
2299		device_printf(sc->sc_dev,
2300		    "timeout waiting for firmware readiness\n");
2301		error = ETIMEDOUT;
2302		goto fail;
2303	}
2304 fail:
2305	firmware_put(fw, FIRMWARE_UNLOAD);
2306	return (error);
2307}
2308
2309
2310static int
2311rsu_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2312    const struct ieee80211_bpf_params *params)
2313{
2314	struct ieee80211com *ic = ni->ni_ic;
2315	struct rsu_softc *sc = ic->ic_softc;
2316	struct rsu_data *bf;
2317
2318	/* prevent management frames from being sent if we're not ready */
2319	if (!sc->sc_running) {
2320		m_freem(m);
2321		ieee80211_free_node(ni);
2322		return (ENETDOWN);
2323	}
2324	RSU_LOCK(sc);
2325	bf = rsu_getbuf(sc);
2326	if (bf == NULL) {
2327		ieee80211_free_node(ni);
2328		m_freem(m);
2329		RSU_UNLOCK(sc);
2330		return (ENOBUFS);
2331	}
2332	if (rsu_tx_start(sc, ni, m, bf) != 0) {
2333		ieee80211_free_node(ni);
2334		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
2335		RSU_UNLOCK(sc);
2336		return (EIO);
2337	}
2338	RSU_UNLOCK(sc);
2339
2340	return (0);
2341}
2342
2343static void
2344rsu_init(struct rsu_softc *sc)
2345{
2346	struct ieee80211com *ic = &sc->sc_ic;
2347	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2348	uint8_t macaddr[IEEE80211_ADDR_LEN];
2349	struct r92s_set_pwr_mode cmd;
2350	int error;
2351	int i;
2352
2353	RSU_ASSERT_LOCKED(sc);
2354
2355	/* Init host async commands ring. */
2356	sc->cmdq.cur = sc->cmdq.next = sc->cmdq.queued = 0;
2357
2358	/* Power on adapter. */
2359	if (sc->cut == 1)
2360		rsu_power_on_acut(sc);
2361	else
2362		rsu_power_on_bcut(sc);
2363
2364	/* Load firmware. */
2365	error = rsu_load_firmware(sc);
2366	if (error != 0)
2367		goto fail;
2368
2369	/* Enable Rx TCP checksum offload. */
2370	rsu_write_4(sc, R92S_RCR,
2371	    rsu_read_4(sc, R92S_RCR) | 0x04000000);
2372	/* Append PHY status. */
2373	rsu_write_4(sc, R92S_RCR,
2374	    rsu_read_4(sc, R92S_RCR) | 0x02000000);
2375
2376	rsu_write_4(sc, R92S_CR,
2377	    rsu_read_4(sc, R92S_CR) & ~0xff000000);
2378
2379	/* Use 128 bytes pages. */
2380	rsu_write_1(sc, 0x00b5,
2381	    rsu_read_1(sc, 0x00b5) | 0x01);
2382	/* Enable USB Rx aggregation. */
2383	rsu_write_1(sc, 0x00bd,
2384	    rsu_read_1(sc, 0x00bd) | 0x80);
2385	/* Set USB Rx aggregation threshold. */
2386	rsu_write_1(sc, 0x00d9, 0x01);
2387	/* Set USB Rx aggregation timeout (1.7ms/4). */
2388	rsu_write_1(sc, 0xfe5b, 0x04);
2389	/* Fix USB Rx FIFO issue. */
2390	rsu_write_1(sc, 0xfe5c,
2391	    rsu_read_1(sc, 0xfe5c) | 0x80);
2392
2393	/* Set MAC address. */
2394	IEEE80211_ADDR_COPY(macaddr, vap ? vap->iv_myaddr : ic->ic_macaddr);
2395	rsu_write_region_1(sc, R92S_MACID, macaddr, IEEE80211_ADDR_LEN);
2396
2397	/* It really takes 1.5 seconds for the firmware to boot: */
2398	usb_pause_mtx(&sc->sc_mtx, (3 * hz) / 2);
2399
2400	RSU_DPRINTF(sc, RSU_DEBUG_RESET, "%s: setting MAC address to %s\n",
2401	    __func__,
2402	    ether_sprintf(macaddr));
2403	error = rsu_fw_cmd(sc, R92S_CMD_SET_MAC_ADDRESS, macaddr,
2404	    IEEE80211_ADDR_LEN);
2405	if (error != 0) {
2406		device_printf(sc->sc_dev, "could not set MAC address\n");
2407		goto fail;
2408	}
2409
2410	rsu_write_1(sc, R92S_USB_HRPWM,
2411	    R92S_USB_HRPWM_PS_ST_ACTIVE | R92S_USB_HRPWM_PS_ALL_ON);
2412
2413	/* Set PS mode fully active */
2414	memset(&cmd, 0, sizeof(cmd));
2415	cmd.mode = R92S_PS_MODE_ACTIVE;
2416	RSU_DPRINTF(sc, RSU_DEBUG_RESET, "%s: setting ps mode to %d\n",
2417	    __func__, cmd.mode);
2418	error = rsu_fw_cmd(sc, R92S_CMD_SET_PWR_MODE, &cmd, sizeof(cmd));
2419	if (error != 0) {
2420		device_printf(sc->sc_dev, "could not set PS mode\n");
2421		goto fail;
2422	}
2423
2424#if 0
2425	if (ic->ic_htcaps & IEEE80211_HTCAP_CBW20_40) {
2426		/* Enable 40MHz mode. */
2427		error = rsu_fw_iocmd(sc,
2428		    SM(R92S_IOCMD_CLASS, 0xf4) |
2429		    SM(R92S_IOCMD_INDEX, 0x00) |
2430		    SM(R92S_IOCMD_VALUE, 0x0007));
2431		if (error != 0) {
2432			device_printf(sc->sc_dev,
2433			    "could not enable 40MHz mode\n");
2434			goto fail;
2435		}
2436	}
2437
2438	/* Set default channel. */
2439	ic->ic_bss->ni_chan = ic->ic_ibss_chan;
2440#endif
2441	sc->sc_scan_pass = 0;
2442	usbd_transfer_start(sc->sc_xfer[RSU_BULK_RX]);
2443
2444	/* We're ready to go. */
2445	sc->sc_running = 1;
2446	return;
2447fail:
2448	/* Need to stop all failed transfers, if any */
2449	for (i = 0; i != RSU_N_TRANSFER; i++)
2450		usbd_transfer_stop(sc->sc_xfer[i]);
2451}
2452
2453static void
2454rsu_stop(struct rsu_softc *sc)
2455{
2456	int i;
2457
2458	sc->sc_running = 0;
2459	sc->sc_calibrating = 0;
2460	taskqueue_cancel_timeout(taskqueue_thread, &sc->calib_task, NULL);
2461
2462	/* Power off adapter. */
2463	rsu_power_off(sc);
2464
2465	for (i = 0; i < RSU_N_TRANSFER; i++)
2466		usbd_transfer_stop(sc->sc_xfer[i]);
2467}
2468
2469static void
2470rsu_ms_delay(struct rsu_softc *sc)
2471{
2472	usb_pause_mtx(&sc->sc_mtx, hz / 1000);
2473}
2474