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