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