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