if_rsu.c revision 283527
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 283527 2015-05-25 13:51:13Z glebius $");
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 ifnet *);
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_name = device_get_nameunit(self);
359	ic->ic_phytype = IEEE80211_T_OFDM;	/* Not only, but not used. */
360	ic->ic_opmode = IEEE80211_M_STA;	/* Default to BSS mode. */
361
362	/* Set device capabilities. */
363	ic->ic_caps =
364	    IEEE80211_C_STA |		/* station mode */
365	    IEEE80211_C_BGSCAN |	/* Background scan. */
366	    IEEE80211_C_SHPREAMBLE |	/* Short preamble supported. */
367	    IEEE80211_C_SHSLOT |	/* Short slot time supported. */
368	    IEEE80211_C_WPA;		/* WPA/RSN. */
369
370#if 0
371	/* Check if HT support is present. */
372	if (usb_lookup(rsu_devs_noht, uaa->vendor, uaa->product) == NULL) {
373		/* Set HT capabilities. */
374		ic->ic_htcaps =
375		    IEEE80211_HTCAP_CBW20_40 |
376		    IEEE80211_HTCAP_DSSSCCK40;
377		/* Set supported HT rates. */
378		for (i = 0; i < 2; i++)
379			ic->ic_sup_mcs[i] = 0xff;
380	}
381#endif
382
383	/* Set supported .11b and .11g rates. */
384	bands = 0;
385	setbit(&bands, IEEE80211_MODE_11B);
386	setbit(&bands, IEEE80211_MODE_11G);
387	ieee80211_init_channels(ic, NULL, &bands);
388
389	ieee80211_ifattach(ic, sc->sc_bssid);
390	ic->ic_raw_xmit = rsu_raw_xmit;
391	ic->ic_scan_start = rsu_scan_start;
392	ic->ic_scan_end = rsu_scan_end;
393	ic->ic_set_channel = rsu_set_channel;
394	ic->ic_vap_create = rsu_vap_create;
395	ic->ic_vap_delete = rsu_vap_delete;
396	ic->ic_update_mcast = rsu_update_mcast;
397
398	ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr,
399	    sizeof(sc->sc_txtap), RSU_TX_RADIOTAP_PRESENT,
400	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
401	    RSU_RX_RADIOTAP_PRESENT);
402
403	if (bootverbose)
404		ieee80211_announce(ic);
405
406	return (0);
407
408fail_ifalloc:
409fail_rom:
410	usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER);
411fail_usb:
412	mtx_destroy(&sc->sc_mtx);
413	return (ENXIO);
414}
415
416static int
417rsu_detach(device_t self)
418{
419	struct rsu_softc *sc = device_get_softc(self);
420	struct ifnet *ifp = sc->sc_ifp;
421	struct ieee80211com *ic = ifp->if_l2com;
422
423	rsu_stop(ifp, 1);
424	usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER);
425	ieee80211_ifdetach(ic);
426
427	taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task);
428
429	/* Free Tx/Rx buffers. */
430	rsu_free_tx_list(sc);
431	rsu_free_rx_list(sc);
432
433	if_free(ifp);
434	mtx_destroy(&sc->sc_mtx);
435
436	return (0);
437}
438
439static usb_error_t
440rsu_do_request(struct rsu_softc *sc, struct usb_device_request *req,
441    void *data)
442{
443	usb_error_t err;
444	int ntries = 10;
445
446	RSU_ASSERT_LOCKED(sc);
447
448	while (ntries--) {
449		err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
450		    req, data, 0, NULL, 250 /* ms */);
451		if (err == 0 || err == USB_ERR_NOT_CONFIGURED)
452			break;
453		DPRINTFN(1, "Control request failed, %s (retrying)\n",
454		    usbd_errstr(err));
455		usb_pause_mtx(&sc->sc_mtx, hz / 100);
456        }
457
458        return (err);
459}
460
461static struct ieee80211vap *
462rsu_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
463    enum ieee80211_opmode opmode, int flags,
464    const uint8_t bssid[IEEE80211_ADDR_LEN],
465    const uint8_t mac[IEEE80211_ADDR_LEN])
466{
467	struct rsu_vap *uvp;
468	struct ieee80211vap *vap;
469
470	if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
471		return (NULL);
472
473	uvp = (struct rsu_vap *) malloc(sizeof(struct rsu_vap),
474	    M_80211_VAP, M_NOWAIT | M_ZERO);
475	if (uvp == NULL)
476		return (NULL);
477	vap = &uvp->vap;
478
479	if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
480	    flags, bssid, mac) != 0) {
481		/* out of memory */
482		free(uvp, M_80211_VAP);
483		return (NULL);
484	}
485
486	/* override state transition machine */
487	uvp->newstate = vap->iv_newstate;
488	vap->iv_newstate = rsu_newstate;
489
490	/* complete setup */
491	ieee80211_vap_attach(vap, ieee80211_media_change,
492	    ieee80211_media_status);
493	ic->ic_opmode = opmode;
494
495	return (vap);
496}
497
498static void
499rsu_vap_delete(struct ieee80211vap *vap)
500{
501	struct rsu_vap *uvp = RSU_VAP(vap);
502
503	ieee80211_vap_detach(vap);
504	free(uvp, M_80211_VAP);
505}
506
507static void
508rsu_scan_start(struct ieee80211com *ic)
509{
510	int error;
511	struct ifnet *ifp = ic->ic_ifp;
512	struct rsu_softc *sc = ifp->if_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 ifnet *ifp)
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_ifp->if_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 ifreq *ifr = (struct ifreq *) data;
1822	int error = 0, startall = 0;
1823
1824	switch (cmd) {
1825	case SIOCSIFFLAGS:
1826		if (ifp->if_flags & IFF_UP) {
1827			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1828				rsu_init(ifp->if_softc);
1829				startall = 1;
1830			}
1831		} else {
1832			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1833				rsu_stop(ifp, 1);
1834		}
1835		if (startall)
1836			ieee80211_start_all(ic);
1837		break;
1838	case SIOCGIFMEDIA:
1839		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
1840		break;
1841	case SIOCGIFADDR:
1842		error = ether_ioctl(ifp, cmd, data);
1843		break;
1844	default:
1845		error = EINVAL;
1846		break;
1847	}
1848
1849	return (error);
1850}
1851
1852/*
1853 * Power on sequence for A-cut adapters.
1854 */
1855static void
1856rsu_power_on_acut(struct rsu_softc *sc)
1857{
1858	uint32_t reg;
1859
1860	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
1861	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
1862
1863	/* Enable AFE macro block's bandgap and Mbias. */
1864	rsu_write_1(sc, R92S_AFE_MISC,
1865	    rsu_read_1(sc, R92S_AFE_MISC) |
1866	    R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN);
1867	/* Enable LDOA15 block. */
1868	rsu_write_1(sc, R92S_LDOA15_CTRL,
1869	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
1870
1871	rsu_write_1(sc, R92S_SPS1_CTRL,
1872	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_LDEN);
1873	usb_pause_mtx(&sc->sc_mtx, 2 * hz);
1874	/* Enable switch regulator block. */
1875	rsu_write_1(sc, R92S_SPS1_CTRL,
1876	    rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_SWEN);
1877
1878	rsu_write_4(sc, R92S_SPS1_CTRL, 0x00a7b267);
1879
1880	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1881	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
1882
1883	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1884	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
1885
1886	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1887	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x90);
1888
1889	/* Enable AFE clock. */
1890	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
1891	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
1892	/* Enable AFE PLL macro block. */
1893	rsu_write_1(sc, R92S_AFE_PLL_CTRL,
1894	    rsu_read_1(sc, R92S_AFE_PLL_CTRL) | 0x11);
1895	/* Attach AFE PLL to MACTOP/BB. */
1896	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
1897	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
1898
1899	/* Switch to 40MHz clock instead of 80MHz. */
1900	rsu_write_2(sc, R92S_SYS_CLKR,
1901	    rsu_read_2(sc, R92S_SYS_CLKR) & ~R92S_SYS_CLKSEL);
1902
1903	/* Enable MAC clock. */
1904	rsu_write_2(sc, R92S_SYS_CLKR,
1905	    rsu_read_2(sc, R92S_SYS_CLKR) |
1906	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
1907
1908	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
1909
1910	/* Enable digital core and IOREG R/W. */
1911	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1912	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
1913
1914	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1915	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
1916
1917	/* Switch the control path to firmware. */
1918	reg = rsu_read_2(sc, R92S_SYS_CLKR);
1919	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
1920	rsu_write_2(sc, R92S_SYS_CLKR, reg);
1921
1922	rsu_write_2(sc, R92S_CR, 0x37fc);
1923
1924	/* Fix USB RX FIFO issue. */
1925	rsu_write_1(sc, 0xfe5c,
1926	    rsu_read_1(sc, 0xfe5c) | 0x80);
1927	rsu_write_1(sc, 0x00ab,
1928	    rsu_read_1(sc, 0x00ab) | 0xc0);
1929
1930	rsu_write_1(sc, R92S_SYS_CLKR,
1931	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
1932}
1933
1934/*
1935 * Power on sequence for B-cut and C-cut adapters.
1936 */
1937static void
1938rsu_power_on_bcut(struct rsu_softc *sc)
1939{
1940	uint32_t reg;
1941	int ntries;
1942
1943	/* Prevent eFuse leakage. */
1944	rsu_write_1(sc, 0x37, 0xb0);
1945	usb_pause_mtx(&sc->sc_mtx, hz / 100);
1946	rsu_write_1(sc, 0x37, 0x30);
1947
1948	/* Switch the control path to hardware. */
1949	reg = rsu_read_2(sc, R92S_SYS_CLKR);
1950	if (reg & R92S_FWHW_SEL) {
1951		rsu_write_2(sc, R92S_SYS_CLKR,
1952		    reg & ~(R92S_SWHW_SEL | R92S_FWHW_SEL));
1953	}
1954	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1955	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) & ~0x8c);
1956	rsu_ms_delay(sc);
1957
1958	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53);
1959	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57);
1960
1961	reg = rsu_read_1(sc, R92S_AFE_MISC);
1962	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN);
1963	rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN |
1964	    R92S_AFE_MISC_MBEN | R92S_AFE_MISC_I32_EN);
1965
1966	/* Enable PLL. */
1967	rsu_write_1(sc, R92S_LDOA15_CTRL,
1968	    rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN);
1969
1970	rsu_write_1(sc, R92S_LDOV12D_CTRL,
1971	    rsu_read_1(sc, R92S_LDOV12D_CTRL) | R92S_LDV12_EN);
1972
1973	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1974	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08);
1975
1976	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
1977	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20);
1978
1979	/* Support 64KB IMEM. */
1980	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1,
1981	    rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x97);
1982
1983	/* Enable AFE clock. */
1984	rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1,
1985	    rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04);
1986	/* Enable AFE PLL macro block. */
1987	reg = rsu_read_1(sc, R92S_AFE_PLL_CTRL);
1988	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
1989	rsu_ms_delay(sc);
1990	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x51);
1991	rsu_ms_delay(sc);
1992	rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11);
1993	rsu_ms_delay(sc);
1994
1995	/* Attach AFE PLL to MACTOP/BB. */
1996	rsu_write_1(sc, R92S_SYS_ISO_CTRL,
1997	    rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11);
1998
1999	/* Switch to 40MHz clock. */
2000	rsu_write_1(sc, R92S_SYS_CLKR, 0x00);
2001	/* Disable CPU clock and 80MHz SSC. */
2002	rsu_write_1(sc, R92S_SYS_CLKR,
2003	    rsu_read_1(sc, R92S_SYS_CLKR) | 0xa0);
2004	/* Enable MAC clock. */
2005	rsu_write_2(sc, R92S_SYS_CLKR,
2006	    rsu_read_2(sc, R92S_SYS_CLKR) |
2007	    R92S_MAC_CLK_EN | R92S_SYS_CLK_EN);
2008
2009	rsu_write_1(sc, R92S_PMC_FSM, 0x02);
2010
2011	/* Enable digital core and IOREG R/W. */
2012	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2013	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08);
2014
2015	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1,
2016	    rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80);
2017
2018	/* Switch the control path to firmware. */
2019	reg = rsu_read_2(sc, R92S_SYS_CLKR);
2020	reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL;
2021	rsu_write_2(sc, R92S_SYS_CLKR, reg);
2022
2023	rsu_write_2(sc, R92S_CR, 0x37fc);
2024
2025	/* Fix USB RX FIFO issue. */
2026	rsu_write_1(sc, 0xfe5c,
2027	    rsu_read_1(sc, 0xfe5c) | 0x80);
2028
2029	rsu_write_1(sc, R92S_SYS_CLKR,
2030	    rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL);
2031
2032	rsu_write_1(sc, 0xfe1c, 0x80);
2033
2034	/* Make sure TxDMA is ready to download firmware. */
2035	for (ntries = 0; ntries < 20; ntries++) {
2036		reg = rsu_read_1(sc, R92S_TCR);
2037		if ((reg & (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) ==
2038		    (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT))
2039			break;
2040		rsu_ms_delay(sc);
2041	}
2042	if (ntries == 20) {
2043		DPRINTF("TxDMA is not ready\n");
2044		/* Reset TxDMA. */
2045		reg = rsu_read_1(sc, R92S_CR);
2046		rsu_write_1(sc, R92S_CR, reg & ~R92S_CR_TXDMA_EN);
2047		rsu_ms_delay(sc);
2048		rsu_write_1(sc, R92S_CR, reg | R92S_CR_TXDMA_EN);
2049	}
2050}
2051
2052static void
2053rsu_power_off(struct rsu_softc *sc)
2054{
2055	/* Turn RF off. */
2056	rsu_write_1(sc, R92S_RF_CTRL, 0x00);
2057	usb_pause_mtx(&sc->sc_mtx, hz / 200);
2058
2059	/* Turn MAC off. */
2060	/* Switch control path. */
2061	rsu_write_1(sc, R92S_SYS_CLKR + 1, 0x38);
2062	/* Reset MACTOP. */
2063	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x70);
2064	rsu_write_1(sc, R92S_PMC_FSM, 0x06);
2065	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 0, 0xf9);
2066	rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, 0xe8);
2067
2068	/* Disable AFE PLL. */
2069	rsu_write_1(sc, R92S_AFE_PLL_CTRL, 0x00);
2070	/* Disable A15V. */
2071	rsu_write_1(sc, R92S_LDOA15_CTRL, 0x54);
2072	/* Disable eFuse 1.2V. */
2073	rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x50);
2074	rsu_write_1(sc, R92S_LDOV12D_CTRL, 0x24);
2075	/* Enable AFE macro block's bandgap and Mbias. */
2076	rsu_write_1(sc, R92S_AFE_MISC, 0x30);
2077	/* Disable 1.6V LDO. */
2078	rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x56);
2079	rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x43);
2080}
2081
2082static int
2083rsu_fw_loadsection(struct rsu_softc *sc, const uint8_t *buf, int len)
2084{
2085	const uint8_t which = rsu_wme_ac_xfer_map[WME_AC_VO];
2086	struct rsu_data *data;
2087	struct r92s_tx_desc *txd;
2088	int mlen;
2089
2090	while (len > 0) {
2091		data = rsu_getbuf(sc);
2092		if (data == NULL)
2093			return (ENOMEM);
2094		txd = (struct r92s_tx_desc *)data->buf;
2095		memset(txd, 0, sizeof(*txd));
2096		if (len <= RSU_TXBUFSZ - sizeof(*txd)) {
2097			/* Last chunk. */
2098			txd->txdw0 |= htole32(R92S_TXDW0_LINIP);
2099			mlen = len;
2100		} else
2101			mlen = RSU_TXBUFSZ - sizeof(*txd);
2102		txd->txdw0 |= htole32(SM(R92S_TXDW0_PKTLEN, mlen));
2103		memcpy(&txd[1], buf, mlen);
2104		data->buflen = sizeof(*txd) + mlen;
2105		DPRINTF("starting transfer %p\n", data);
2106		STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next);
2107		buf += mlen;
2108		len -= mlen;
2109	}
2110	usbd_transfer_start(sc->sc_xfer[which]);
2111	return (0);
2112}
2113
2114static int
2115rsu_load_firmware(struct rsu_softc *sc)
2116{
2117	const struct r92s_fw_hdr *hdr;
2118	struct r92s_fw_priv *dmem;
2119	const uint8_t *imem, *emem;
2120	int imemsz, ememsz;
2121	const struct firmware *fw;
2122	size_t size;
2123	uint32_t reg;
2124	int ntries, error;
2125
2126	if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY) {
2127		DPRINTF("Firmware already loaded\n");
2128		return (0);
2129	}
2130
2131	RSU_UNLOCK(sc);
2132	/* Read firmware image from the filesystem. */
2133	if ((fw = firmware_get("rsu-rtl8712fw")) == NULL) {
2134		device_printf(sc->sc_dev,
2135		    "%s: failed load firmware of file rsu-rtl8712fw\n",
2136		    __func__);
2137		RSU_LOCK(sc);
2138		return (ENXIO);
2139	}
2140	RSU_LOCK(sc);
2141	size = fw->datasize;
2142	if (size < sizeof(*hdr)) {
2143		device_printf(sc->sc_dev, "firmware too short\n");
2144		error = EINVAL;
2145		goto fail;
2146	}
2147	hdr = (const struct r92s_fw_hdr *)fw->data;
2148	if (hdr->signature != htole16(0x8712) &&
2149	    hdr->signature != htole16(0x8192)) {
2150		device_printf(sc->sc_dev,
2151		    "invalid firmware signature 0x%x\n",
2152		    le16toh(hdr->signature));
2153		error = EINVAL;
2154		goto fail;
2155	}
2156	DPRINTF("FW V%d %02x-%02x %02x:%02x\n", le16toh(hdr->version),
2157	    hdr->month, hdr->day, hdr->hour, hdr->minute);
2158
2159	/* Make sure that driver and firmware are in sync. */
2160	if (hdr->privsz != htole32(sizeof(*dmem))) {
2161		device_printf(sc->sc_dev, "unsupported firmware image\n");
2162		error = EINVAL;
2163		goto fail;
2164	}
2165	/* Get FW sections sizes. */
2166	imemsz = le32toh(hdr->imemsz);
2167	ememsz = le32toh(hdr->sramsz);
2168	/* Check that all FW sections fit in image. */
2169	if (size < sizeof(*hdr) + imemsz + ememsz) {
2170		device_printf(sc->sc_dev, "firmware too short\n");
2171		error = EINVAL;
2172		goto fail;
2173	}
2174	imem = (const uint8_t *)&hdr[1];
2175	emem = imem + imemsz;
2176
2177	/* Load IMEM section. */
2178	error = rsu_fw_loadsection(sc, imem, imemsz);
2179	if (error != 0) {
2180		device_printf(sc->sc_dev,
2181		    "could not load firmware section %s\n", "IMEM");
2182		goto fail;
2183	}
2184	/* Wait for load to complete. */
2185	for (ntries = 0; ntries != 50; ntries++) {
2186		usb_pause_mtx(&sc->sc_mtx, hz / 100);
2187		reg = rsu_read_1(sc, R92S_TCR);
2188		if (reg & R92S_TCR_IMEM_CODE_DONE)
2189			break;
2190	}
2191	if (ntries == 50) {
2192		device_printf(sc->sc_dev, "timeout waiting for IMEM transfer\n");
2193		error = ETIMEDOUT;
2194		goto fail;
2195	}
2196	/* Load EMEM section. */
2197	error = rsu_fw_loadsection(sc, emem, ememsz);
2198	if (error != 0) {
2199		device_printf(sc->sc_dev,
2200		    "could not load firmware section %s\n", "EMEM");
2201		goto fail;
2202	}
2203	/* Wait for load to complete. */
2204	for (ntries = 0; ntries != 50; ntries++) {
2205		usb_pause_mtx(&sc->sc_mtx, hz / 100);
2206		reg = rsu_read_2(sc, R92S_TCR);
2207		if (reg & R92S_TCR_EMEM_CODE_DONE)
2208			break;
2209	}
2210	if (ntries == 50) {
2211		device_printf(sc->sc_dev, "timeout waiting for EMEM transfer\n");
2212		error = ETIMEDOUT;
2213		goto fail;
2214	}
2215	/* Enable CPU. */
2216	rsu_write_1(sc, R92S_SYS_CLKR,
2217	    rsu_read_1(sc, R92S_SYS_CLKR) | R92S_SYS_CPU_CLKSEL);
2218	if (!(rsu_read_1(sc, R92S_SYS_CLKR) & R92S_SYS_CPU_CLKSEL)) {
2219		device_printf(sc->sc_dev, "could not enable system clock\n");
2220		error = EIO;
2221		goto fail;
2222	}
2223	rsu_write_2(sc, R92S_SYS_FUNC_EN,
2224	    rsu_read_2(sc, R92S_SYS_FUNC_EN) | R92S_FEN_CPUEN);
2225	if (!(rsu_read_2(sc, R92S_SYS_FUNC_EN) & R92S_FEN_CPUEN)) {
2226		device_printf(sc->sc_dev,
2227		    "could not enable microcontroller\n");
2228		error = EIO;
2229		goto fail;
2230	}
2231	/* Wait for CPU to initialize. */
2232	for (ntries = 0; ntries < 100; ntries++) {
2233		if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_IMEM_RDY)
2234			break;
2235		rsu_ms_delay(sc);
2236	}
2237	if (ntries == 100) {
2238		device_printf(sc->sc_dev,
2239		    "timeout waiting for microcontroller\n");
2240		error = ETIMEDOUT;
2241		goto fail;
2242	}
2243
2244	/* Update DMEM section before loading. */
2245	dmem = __DECONST(struct r92s_fw_priv *, &hdr->priv);
2246	memset(dmem, 0, sizeof(*dmem));
2247	dmem->hci_sel = R92S_HCI_SEL_USB | R92S_HCI_SEL_8172;
2248	dmem->nendpoints = 0;
2249	dmem->rf_config = 0x12;	/* 1T2R */
2250	dmem->vcs_type = R92S_VCS_TYPE_AUTO;
2251	dmem->vcs_mode = R92S_VCS_MODE_RTS_CTS;
2252#ifdef notyet
2253	dmem->bw40_en = (ic->ic_htcaps & IEEE80211_HTCAP_CBW20_40) != 0;
2254#endif
2255	dmem->turbo_mode = 1;
2256	/* Load DMEM section. */
2257	error = rsu_fw_loadsection(sc, (uint8_t *)dmem, sizeof(*dmem));
2258	if (error != 0) {
2259		device_printf(sc->sc_dev,
2260		    "could not load firmware section %s\n", "DMEM");
2261		goto fail;
2262	}
2263	/* Wait for load to complete. */
2264	for (ntries = 0; ntries < 100; ntries++) {
2265		if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_DMEM_CODE_DONE)
2266			break;
2267		rsu_ms_delay(sc);
2268	}
2269	if (ntries == 100) {
2270		device_printf(sc->sc_dev, "timeout waiting for %s transfer\n",
2271		    "DMEM");
2272		error = ETIMEDOUT;
2273		goto fail;
2274	}
2275	/* Wait for firmware readiness. */
2276	for (ntries = 0; ntries < 60; ntries++) {
2277		if (!(rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY))
2278			break;
2279		rsu_ms_delay(sc);
2280	}
2281	if (ntries == 60) {
2282		device_printf(sc->sc_dev,
2283		    "timeout waiting for firmware readiness\n");
2284		error = ETIMEDOUT;
2285		goto fail;
2286	}
2287 fail:
2288	firmware_put(fw, FIRMWARE_UNLOAD);
2289	return (error);
2290}
2291
2292
2293static int
2294rsu_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2295    const struct ieee80211_bpf_params *params)
2296{
2297	struct ieee80211com *ic = ni->ni_ic;
2298	struct ifnet *ifp = ic->ic_ifp;
2299	struct rsu_softc *sc = ifp->if_softc;
2300	struct rsu_data *bf;
2301
2302	/* prevent management frames from being sent if we're not ready */
2303	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
2304		m_freem(m);
2305		ieee80211_free_node(ni);
2306		return (ENETDOWN);
2307	}
2308	RSU_LOCK(sc);
2309	bf = rsu_getbuf(sc);
2310	if (bf == NULL) {
2311		ieee80211_free_node(ni);
2312		m_freem(m);
2313		RSU_UNLOCK(sc);
2314		return (ENOBUFS);
2315	}
2316	if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
2317	if (rsu_tx_start(sc, ni, m, bf) != 0) {
2318		ieee80211_free_node(ni);
2319		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2320		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
2321		RSU_UNLOCK(sc);
2322		return (EIO);
2323	}
2324	RSU_UNLOCK(sc);
2325
2326	return (0);
2327}
2328
2329static void
2330rsu_init(void *arg)
2331{
2332	struct rsu_softc *sc = arg;
2333
2334	RSU_LOCK(sc);
2335	rsu_init_locked(arg);
2336	RSU_UNLOCK(sc);
2337}
2338
2339static void
2340rsu_init_locked(struct rsu_softc *sc)
2341{
2342	struct ifnet *ifp = sc->sc_ifp;
2343	struct r92s_set_pwr_mode cmd;
2344	int error;
2345	int i;
2346
2347	/* Init host async commands ring. */
2348	sc->cmdq.cur = sc->cmdq.next = sc->cmdq.queued = 0;
2349
2350	/* Power on adapter. */
2351	if (sc->cut == 1)
2352		rsu_power_on_acut(sc);
2353	else
2354		rsu_power_on_bcut(sc);
2355
2356	/* Load firmware. */
2357	error = rsu_load_firmware(sc);
2358	if (error != 0)
2359		goto fail;
2360
2361	/* Enable Rx TCP checksum offload. */
2362	rsu_write_4(sc, R92S_RCR,
2363	    rsu_read_4(sc, R92S_RCR) | 0x04000000);
2364	/* Append PHY status. */
2365	rsu_write_4(sc, R92S_RCR,
2366	    rsu_read_4(sc, R92S_RCR) | 0x02000000);
2367
2368	rsu_write_4(sc, R92S_CR,
2369	    rsu_read_4(sc, R92S_CR) & ~0xff000000);
2370
2371	/* Use 128 bytes pages. */
2372	rsu_write_1(sc, 0x00b5,
2373	    rsu_read_1(sc, 0x00b5) | 0x01);
2374	/* Enable USB Rx aggregation. */
2375	rsu_write_1(sc, 0x00bd,
2376	    rsu_read_1(sc, 0x00bd) | 0x80);
2377	/* Set USB Rx aggregation threshold. */
2378	rsu_write_1(sc, 0x00d9, 0x01);
2379	/* Set USB Rx aggregation timeout (1.7ms/4). */
2380	rsu_write_1(sc, 0xfe5b, 0x04);
2381	/* Fix USB Rx FIFO issue. */
2382	rsu_write_1(sc, 0xfe5c,
2383	    rsu_read_1(sc, 0xfe5c) | 0x80);
2384
2385	/* Set MAC address. */
2386	rsu_write_region_1(sc, R92S_MACID, IF_LLADDR(ifp),
2387	    IEEE80211_ADDR_LEN);
2388
2389	/* It really takes 1.5 seconds for the firmware to boot: */
2390	usb_pause_mtx(&sc->sc_mtx, (3 * hz) / 2);
2391
2392	DPRINTF("setting MAC address to %s\n", ether_sprintf(IF_LLADDR(ifp)));
2393	error = rsu_fw_cmd(sc, R92S_CMD_SET_MAC_ADDRESS, IF_LLADDR(ifp),
2394	    IEEE80211_ADDR_LEN);
2395	if (error != 0) {
2396		device_printf(sc->sc_dev, "could not set MAC address\n");
2397		goto fail;
2398	}
2399
2400	rsu_write_1(sc, R92S_USB_HRPWM,
2401	    R92S_USB_HRPWM_PS_ST_ACTIVE | R92S_USB_HRPWM_PS_ALL_ON);
2402
2403	memset(&cmd, 0, sizeof(cmd));
2404	cmd.mode = R92S_PS_MODE_ACTIVE;
2405	DPRINTF("setting ps mode to %d\n", cmd.mode);
2406	error = rsu_fw_cmd(sc, R92S_CMD_SET_PWR_MODE, &cmd, sizeof(cmd));
2407	if (error != 0) {
2408		device_printf(sc->sc_dev, "could not set PS mode\n");
2409		goto fail;
2410	}
2411
2412#if 0
2413	if (ic->ic_htcaps & IEEE80211_HTCAP_CBW20_40) {
2414		/* Enable 40MHz mode. */
2415		error = rsu_fw_iocmd(sc,
2416		    SM(R92S_IOCMD_CLASS, 0xf4) |
2417		    SM(R92S_IOCMD_INDEX, 0x00) |
2418		    SM(R92S_IOCMD_VALUE, 0x0007));
2419		if (error != 0) {
2420			device_printf(sc->sc_dev,
2421			    "could not enable 40MHz mode\n");
2422			goto fail;
2423		}
2424	}
2425
2426	/* Set default channel. */
2427	ic->ic_bss->ni_chan = ic->ic_ibss_chan;
2428#endif
2429	sc->scan_pass = 0;
2430	usbd_transfer_start(sc->sc_xfer[RSU_BULK_RX]);
2431
2432	/* We're ready to go. */
2433	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2434	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2435	return;
2436fail:
2437	/* Need to stop all failed transfers, if any */
2438	for (i = 0; i != RSU_N_TRANSFER; i++)
2439		usbd_transfer_stop(sc->sc_xfer[i]);
2440}
2441
2442static void
2443rsu_stop(struct ifnet *ifp, int disable)
2444{
2445	struct rsu_softc *sc = ifp->if_softc;
2446
2447	RSU_LOCK(sc);
2448	rsu_stop_locked(ifp, disable);
2449	RSU_UNLOCK(sc);
2450}
2451
2452static void
2453rsu_stop_locked(struct ifnet *ifp, int disable __unused)
2454{
2455	struct rsu_softc *sc = ifp->if_softc;
2456	int i;
2457
2458	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2459	sc->sc_calibrating = 0;
2460	taskqueue_cancel_timeout(taskqueue_thread, &sc->calib_task, NULL);
2461
2462	/* Power off adapter. */
2463	rsu_power_off(sc);
2464
2465	for (i = 0; i < RSU_N_TRANSFER; i++)
2466		usbd_transfer_stop(sc->sc_xfer[i]);
2467}
2468
2469static void
2470rsu_ms_delay(struct rsu_softc *sc)
2471{
2472	usb_pause_mtx(&sc->sc_mtx, hz / 1000);
2473}
2474