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