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