if_urtwn.c revision 252401
1/*	$OpenBSD: if_urtwn.c,v 1.16 2011/02/10 17:26:40 jakemsr 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
19#include <sys/cdefs.h>
20__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_urtwn.c 252401 2013-06-30 05:10:33Z rpaulo $");
21
22/*
23 * Driver for Realtek RTL8188CE-VAU/RTL8188CUS/RTL8188RU/RTL8192CU.
24 */
25
26#include <sys/param.h>
27#include <sys/sockio.h>
28#include <sys/sysctl.h>
29#include <sys/lock.h>
30#include <sys/mutex.h>
31#include <sys/mbuf.h>
32#include <sys/kernel.h>
33#include <sys/socket.h>
34#include <sys/systm.h>
35#include <sys/malloc.h>
36#include <sys/module.h>
37#include <sys/bus.h>
38#include <sys/endian.h>
39#include <sys/linker.h>
40#include <sys/firmware.h>
41#include <sys/kdb.h>
42
43#include <machine/bus.h>
44#include <machine/resource.h>
45#include <sys/rman.h>
46
47#include <net/bpf.h>
48#include <net/if.h>
49#include <net/if_arp.h>
50#include <net/ethernet.h>
51#include <net/if_dl.h>
52#include <net/if_media.h>
53#include <net/if_types.h>
54
55#include <netinet/in.h>
56#include <netinet/in_systm.h>
57#include <netinet/in_var.h>
58#include <netinet/if_ether.h>
59#include <netinet/ip.h>
60
61#include <net80211/ieee80211_var.h>
62#include <net80211/ieee80211_regdomain.h>
63#include <net80211/ieee80211_radiotap.h>
64#include <net80211/ieee80211_ratectl.h>
65
66#include <dev/usb/usb.h>
67#include <dev/usb/usbdi.h>
68#include "usbdevs.h"
69
70#define USB_DEBUG_VAR urtwn_debug
71#include <dev/usb/usb_debug.h>
72
73#include <dev/usb/wlan/if_urtwnreg.h>
74
75#ifdef USB_DEBUG
76static int urtwn_debug = 0;
77
78SYSCTL_NODE(_hw_usb, OID_AUTO, urtwn, CTLFLAG_RW, 0, "USB urtwn");
79SYSCTL_INT(_hw_usb_urtwn, OID_AUTO, debug, CTLFLAG_RW, &urtwn_debug, 0,
80    "Debug level");
81#endif
82
83#define	IEEE80211_HAS_ADDR4(wh)	\
84	(((wh)->i_fc[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS)
85
86/* various supported device vendors/products */
87static const STRUCT_USB_HOST_ID urtwn_devs[] = {
88#define URTWN_DEV(v,p)  { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) }
89	URTWN_DEV(ABOCOM,	RTL8188CU_1),
90	URTWN_DEV(ABOCOM,	RTL8188CU_2),
91	URTWN_DEV(ABOCOM,	RTL8192CU),
92	URTWN_DEV(ASUS,		RTL8192CU),
93	URTWN_DEV(AZUREWAVE,	RTL8188CE_1),
94	URTWN_DEV(AZUREWAVE,	RTL8188CE_2),
95	URTWN_DEV(AZUREWAVE,	RTL8188CU),
96	URTWN_DEV(BELKIN,	F7D2102),
97	URTWN_DEV(BELKIN,	RTL8188CU),
98	URTWN_DEV(BELKIN,	RTL8192CU),
99	URTWN_DEV(CHICONY,	RTL8188CUS_1),
100	URTWN_DEV(CHICONY,	RTL8188CUS_2),
101	URTWN_DEV(CHICONY,	RTL8188CUS_3),
102	URTWN_DEV(CHICONY,	RTL8188CUS_4),
103	URTWN_DEV(CHICONY,	RTL8188CUS_5),
104	URTWN_DEV(COREGA,	RTL8192CU),
105	URTWN_DEV(DLINK,	RTL8188CU),
106	URTWN_DEV(DLINK,	RTL8192CU_1),
107	URTWN_DEV(DLINK,	RTL8192CU_2),
108	URTWN_DEV(DLINK,	RTL8192CU_3),
109	URTWN_DEV(DLINK,	DWA131B),
110	URTWN_DEV(EDIMAX,	EW7811UN),
111	URTWN_DEV(EDIMAX,	RTL8192CU),
112	URTWN_DEV(FEIXUN,	RTL8188CU),
113	URTWN_DEV(FEIXUN,	RTL8192CU),
114	URTWN_DEV(GUILLEMOT,	HWNUP150),
115	URTWN_DEV(HAWKING,	RTL8192CU),
116	URTWN_DEV(HP3,		RTL8188CU),
117	URTWN_DEV(NETGEAR,	WNA1000M),
118	URTWN_DEV(NETGEAR,	RTL8192CU),
119	URTWN_DEV(NETGEAR4,	RTL8188CU),
120	URTWN_DEV(NOVATECH,	RTL8188CU),
121	URTWN_DEV(PLANEX2,	RTL8188CU_1),
122	URTWN_DEV(PLANEX2,	RTL8188CU_2),
123	URTWN_DEV(PLANEX2,	RTL8188CU_3),
124	URTWN_DEV(PLANEX2,	RTL8188CU_4),
125	URTWN_DEV(PLANEX2,	RTL8188CUS),
126	URTWN_DEV(PLANEX2,	RTL8192CU),
127	URTWN_DEV(REALTEK,	RTL8188CE_0),
128	URTWN_DEV(REALTEK,	RTL8188CE_1),
129	URTWN_DEV(REALTEK,	RTL8188CTV),
130	URTWN_DEV(REALTEK,	RTL8188CU_0),
131	URTWN_DEV(REALTEK,	RTL8188CU_1),
132	URTWN_DEV(REALTEK,	RTL8188CU_2),
133	URTWN_DEV(REALTEK,	RTL8188CU_COMBO),
134	URTWN_DEV(REALTEK,	RTL8188CUS),
135	URTWN_DEV(REALTEK,	RTL8188RU_1),
136	URTWN_DEV(REALTEK,	RTL8188RU_2),
137	URTWN_DEV(REALTEK,	RTL8191CU),
138	URTWN_DEV(REALTEK,	RTL8192CE),
139	URTWN_DEV(REALTEK,	RTL8192CU),
140	URTWN_DEV(SITECOMEU,	RTL8188CU_1),
141	URTWN_DEV(SITECOMEU,	RTL8188CU_2),
142	URTWN_DEV(SITECOMEU,	RTL8192CU),
143	URTWN_DEV(TRENDNET,	RTL8188CU),
144	URTWN_DEV(TRENDNET,	RTL8192CU),
145	URTWN_DEV(ZYXEL,	RTL8192CU),
146#undef URTWN_DEV
147};
148
149static device_probe_t	urtwn_match;
150static device_attach_t	urtwn_attach;
151static device_detach_t	urtwn_detach;
152
153static usb_callback_t   urtwn_bulk_tx_callback;
154static usb_callback_t	urtwn_bulk_rx_callback;
155
156static usb_error_t	urtwn_do_request(struct urtwn_softc *sc,
157			    struct usb_device_request *req, void *data);
158static struct ieee80211vap *urtwn_vap_create(struct ieee80211com *,
159		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
160                    const uint8_t [IEEE80211_ADDR_LEN],
161                    const uint8_t [IEEE80211_ADDR_LEN]);
162static void		urtwn_vap_delete(struct ieee80211vap *);
163static struct mbuf *	urtwn_rx_frame(struct urtwn_softc *, uint8_t *, int,
164			    int *);
165static struct mbuf *	urtwn_rxeof(struct usb_xfer *, struct urtwn_data *,
166			    int *, int8_t *);
167static void		urtwn_txeof(struct usb_xfer *, struct urtwn_data *);
168static int		urtwn_alloc_list(struct urtwn_softc *,
169			    struct urtwn_data[], int, int);
170static int		urtwn_alloc_rx_list(struct urtwn_softc *);
171static int		urtwn_alloc_tx_list(struct urtwn_softc *);
172static void		urtwn_free_tx_list(struct urtwn_softc *);
173static void		urtwn_free_rx_list(struct urtwn_softc *);
174static void		urtwn_free_list(struct urtwn_softc *,
175			    struct urtwn_data data[], int);
176static struct urtwn_data *	_urtwn_getbuf(struct urtwn_softc *);
177static struct urtwn_data *	urtwn_getbuf(struct urtwn_softc *);
178static int		urtwn_write_region_1(struct urtwn_softc *, uint16_t,
179			    uint8_t *, int);
180static void		urtwn_write_1(struct urtwn_softc *, uint16_t, uint8_t);
181static void		urtwn_write_2(struct urtwn_softc *, uint16_t, uint16_t);
182static void		urtwn_write_4(struct urtwn_softc *, uint16_t, uint32_t);
183static int		urtwn_read_region_1(struct urtwn_softc *, uint16_t,
184			    uint8_t *, int);
185static uint8_t		urtwn_read_1(struct urtwn_softc *, uint16_t);
186static uint16_t		urtwn_read_2(struct urtwn_softc *, uint16_t);
187static uint32_t		urtwn_read_4(struct urtwn_softc *, uint16_t);
188static int		urtwn_fw_cmd(struct urtwn_softc *, uint8_t,
189			    const void *, int);
190static void		urtwn_rf_write(struct urtwn_softc *, int, uint8_t,
191			    uint32_t);
192static uint32_t		urtwn_rf_read(struct urtwn_softc *, int, uint8_t);
193static int		urtwn_llt_write(struct urtwn_softc *, uint32_t,
194			    uint32_t);
195static uint8_t		urtwn_efuse_read_1(struct urtwn_softc *, uint16_t);
196static void		urtwn_efuse_read(struct urtwn_softc *);
197static int		urtwn_read_chipid(struct urtwn_softc *);
198static void		urtwn_read_rom(struct urtwn_softc *);
199static int		urtwn_ra_init(struct urtwn_softc *);
200static void		urtwn_tsf_sync_enable(struct urtwn_softc *);
201static void		urtwn_set_led(struct urtwn_softc *, int, int);
202static int		urtwn_newstate(struct ieee80211vap *,
203			    enum ieee80211_state, int);
204static void		urtwn_watchdog(void *);
205static void		urtwn_update_avgrssi(struct urtwn_softc *, int, int8_t);
206static int8_t		urtwn_get_rssi(struct urtwn_softc *, int, void *);
207static int		urtwn_tx_start(struct urtwn_softc *,
208			    struct ieee80211_node *, struct mbuf *,
209			    struct urtwn_data *);
210static void		urtwn_start(struct ifnet *);
211static int		urtwn_ioctl(struct ifnet *, u_long, caddr_t);
212static int		urtwn_power_on(struct urtwn_softc *);
213static int		urtwn_llt_init(struct urtwn_softc *);
214static void		urtwn_fw_reset(struct urtwn_softc *);
215static int		urtwn_fw_loadpage(struct urtwn_softc *, int,
216			    const uint8_t *, int);
217static int		urtwn_load_firmware(struct urtwn_softc *);
218static int		urtwn_dma_init(struct urtwn_softc *);
219static void		urtwn_mac_init(struct urtwn_softc *);
220static void		urtwn_bb_init(struct urtwn_softc *);
221static void		urtwn_rf_init(struct urtwn_softc *);
222static void		urtwn_cam_init(struct urtwn_softc *);
223static void		urtwn_pa_bias_init(struct urtwn_softc *);
224static void		urtwn_rxfilter_init(struct urtwn_softc *);
225static void		urtwn_edca_init(struct urtwn_softc *);
226static void		urtwn_write_txpower(struct urtwn_softc *, int,
227			    uint16_t[]);
228static void		urtwn_get_txpower(struct urtwn_softc *, int,
229		      	    struct ieee80211_channel *,
230			    struct ieee80211_channel *, uint16_t[]);
231static void		urtwn_set_txpower(struct urtwn_softc *,
232		    	    struct ieee80211_channel *,
233			    struct ieee80211_channel *);
234static void		urtwn_scan_start(struct ieee80211com *);
235static void		urtwn_scan_end(struct ieee80211com *);
236static void		urtwn_set_channel(struct ieee80211com *);
237static void		urtwn_set_chan(struct urtwn_softc *,
238		    	    struct ieee80211_channel *,
239			    struct ieee80211_channel *);
240static void		urtwn_update_mcast(struct ifnet *);
241static void		urtwn_iq_calib(struct urtwn_softc *);
242static void		urtwn_lc_calib(struct urtwn_softc *);
243static void		urtwn_init(void *);
244static void		urtwn_init_locked(void *);
245static void		urtwn_stop(struct ifnet *, int);
246static void		urtwn_stop_locked(struct ifnet *, int);
247static void		urtwn_abort_xfers(struct urtwn_softc *);
248static int		urtwn_raw_xmit(struct ieee80211_node *, struct mbuf *,
249			    const struct ieee80211_bpf_params *);
250
251/* Aliases. */
252#define	urtwn_bb_write	urtwn_write_4
253#define urtwn_bb_read	urtwn_read_4
254
255static const struct usb_config urtwn_config[URTWN_N_TRANSFER] = {
256	[URTWN_BULK_RX] = {
257		.type = UE_BULK,
258		.endpoint = UE_ADDR_ANY,
259		.direction = UE_DIR_IN,
260		.bufsize = URTWN_RXBUFSZ,
261		.flags = {
262			.pipe_bof = 1,
263			.short_xfer_ok = 1
264		},
265		.callback = urtwn_bulk_rx_callback,
266	},
267	[URTWN_BULK_TX_BE] = {
268		.type = UE_BULK,
269		.endpoint = 0x03,
270		.direction = UE_DIR_OUT,
271		.bufsize = URTWN_TXBUFSZ,
272		.flags = {
273			.ext_buffer = 1,
274			.pipe_bof = 1,
275			.force_short_xfer = 1
276		},
277		.callback = urtwn_bulk_tx_callback,
278		.timeout = URTWN_TX_TIMEOUT,	/* ms */
279	},
280	[URTWN_BULK_TX_BK] = {
281		.type = UE_BULK,
282		.endpoint = 0x03,
283		.direction = UE_DIR_OUT,
284		.bufsize = URTWN_TXBUFSZ,
285		.flags = {
286			.ext_buffer = 1,
287			.pipe_bof = 1,
288			.force_short_xfer = 1,
289		},
290		.callback = urtwn_bulk_tx_callback,
291		.timeout = URTWN_TX_TIMEOUT,	/* ms */
292	},
293	[URTWN_BULK_TX_VI] = {
294		.type = UE_BULK,
295		.endpoint = 0x02,
296		.direction = UE_DIR_OUT,
297		.bufsize = URTWN_TXBUFSZ,
298		.flags = {
299			.ext_buffer = 1,
300			.pipe_bof = 1,
301			.force_short_xfer = 1
302		},
303		.callback = urtwn_bulk_tx_callback,
304		.timeout = URTWN_TX_TIMEOUT,	/* ms */
305	},
306	[URTWN_BULK_TX_VO] = {
307		.type = UE_BULK,
308		.endpoint = 0x02,
309		.direction = UE_DIR_OUT,
310		.bufsize = URTWN_TXBUFSZ,
311		.flags = {
312			.ext_buffer = 1,
313			.pipe_bof = 1,
314			.force_short_xfer = 1
315		},
316		.callback = urtwn_bulk_tx_callback,
317		.timeout = URTWN_TX_TIMEOUT,	/* ms */
318	},
319};
320
321static int
322urtwn_match(device_t self)
323{
324	struct usb_attach_arg *uaa = device_get_ivars(self);
325
326	if (uaa->usb_mode != USB_MODE_HOST)
327		return (ENXIO);
328	if (uaa->info.bConfigIndex != URTWN_CONFIG_INDEX)
329		return (ENXIO);
330	if (uaa->info.bIfaceIndex != URTWN_IFACE_INDEX)
331		return (ENXIO);
332
333	return (usbd_lookup_id_by_uaa(urtwn_devs, sizeof(urtwn_devs), uaa));
334}
335
336static int
337urtwn_attach(device_t self)
338{
339	struct usb_attach_arg *uaa = device_get_ivars(self);
340	struct urtwn_softc *sc = device_get_softc(self);
341	struct ifnet *ifp;
342	struct ieee80211com *ic;
343	uint8_t iface_index, bands;
344	int error;
345
346	device_set_usb_desc(self);
347	sc->sc_udev = uaa->device;
348	sc->sc_dev = self;
349
350	mtx_init(&sc->sc_mtx, device_get_nameunit(self),
351	    MTX_NETWORK_LOCK, MTX_DEF);
352	callout_init(&sc->sc_watchdog_ch, 0);
353
354	iface_index = URTWN_IFACE_INDEX;
355	error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
356	    urtwn_config, URTWN_N_TRANSFER, sc, &sc->sc_mtx);
357	if (error) {
358		device_printf(self, "could not allocate USB transfers, "
359		    "err=%s\n", usbd_errstr(error));
360		goto detach;
361	}
362
363	URTWN_LOCK(sc);
364
365	error = urtwn_read_chipid(sc);
366	if (error) {
367		device_printf(sc->sc_dev, "unsupported test chip\n");
368		URTWN_UNLOCK(sc);
369		goto detach;
370	}
371
372	/* Determine number of Tx/Rx chains. */
373	if (sc->chip & URTWN_CHIP_92C) {
374		sc->ntxchains = (sc->chip & URTWN_CHIP_92C_1T2R) ? 1 : 2;
375		sc->nrxchains = 2;
376	} else {
377		sc->ntxchains = 1;
378		sc->nrxchains = 1;
379	}
380	urtwn_read_rom(sc);
381
382	device_printf(sc->sc_dev, "MAC/BB RTL%s, RF 6052 %dT%dR\n",
383	    (sc->chip & URTWN_CHIP_92C) ? "8192CU" :
384	    (sc->board_type == R92C_BOARD_TYPE_HIGHPA) ? "8188RU" :
385	    (sc->board_type == R92C_BOARD_TYPE_MINICARD) ? "8188CE-VAU" :
386	    "8188CUS", sc->ntxchains, sc->nrxchains);
387
388	URTWN_UNLOCK(sc);
389
390	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
391	if (ifp == NULL) {
392		device_printf(sc->sc_dev, "can not if_alloc()\n");
393		goto detach;
394	}
395	ic = ifp->if_l2com;
396
397	ifp->if_softc = sc;
398	if_initname(ifp, "urtwn", device_get_unit(sc->sc_dev));
399	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
400	ifp->if_init = urtwn_init;
401	ifp->if_ioctl = urtwn_ioctl;
402	ifp->if_start = urtwn_start;
403	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
404	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
405	IFQ_SET_READY(&ifp->if_snd);
406
407	ic->ic_ifp = ifp;
408	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
409	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
410
411	/* set device capabilities */
412	ic->ic_caps =
413		  IEEE80211_C_STA		/* station mode */
414		| IEEE80211_C_MONITOR		/* monitor mode */
415		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
416		| IEEE80211_C_SHSLOT		/* short slot time supported */
417		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
418		| IEEE80211_C_WPA		/* 802.11i */
419		;
420
421	bands = 0;
422	setbit(&bands, IEEE80211_MODE_11B);
423	setbit(&bands, IEEE80211_MODE_11G);
424	ieee80211_init_channels(ic, NULL, &bands);
425
426	ieee80211_ifattach(ic, sc->sc_bssid);
427	ic->ic_raw_xmit = urtwn_raw_xmit;
428	ic->ic_scan_start = urtwn_scan_start;
429	ic->ic_scan_end = urtwn_scan_end;
430	ic->ic_set_channel = urtwn_set_channel;
431
432	ic->ic_vap_create = urtwn_vap_create;
433	ic->ic_vap_delete = urtwn_vap_delete;
434	ic->ic_update_mcast = urtwn_update_mcast;
435
436	ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr,
437	    sizeof(sc->sc_txtap), URTWN_TX_RADIOTAP_PRESENT,
438	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
439	    URTWN_RX_RADIOTAP_PRESENT);
440
441	if (bootverbose)
442		ieee80211_announce(ic);
443
444	return (0);
445
446detach:
447	urtwn_detach(self);
448	return (ENXIO);			/* failure */
449}
450
451static int
452urtwn_detach(device_t self)
453{
454	struct urtwn_softc *sc = device_get_softc(self);
455	struct ifnet *ifp = sc->sc_ifp;
456	struct ieee80211com *ic = ifp->if_l2com;
457
458	if (!device_is_attached(self))
459		return (0);
460
461	urtwn_stop(ifp, 1);
462
463	callout_drain(&sc->sc_watchdog_ch);
464
465	/* stop all USB transfers */
466	usbd_transfer_unsetup(sc->sc_xfer, URTWN_N_TRANSFER);
467	ieee80211_ifdetach(ic);
468
469	urtwn_free_tx_list(sc);
470	urtwn_free_rx_list(sc);
471
472	if_free(ifp);
473	mtx_destroy(&sc->sc_mtx);
474
475	return (0);
476}
477
478static void
479urtwn_free_tx_list(struct urtwn_softc *sc)
480{
481	urtwn_free_list(sc, sc->sc_tx, URTWN_TX_LIST_COUNT);
482}
483
484static void
485urtwn_free_rx_list(struct urtwn_softc *sc)
486{
487	urtwn_free_list(sc, sc->sc_rx, URTWN_RX_LIST_COUNT);
488}
489
490static void
491urtwn_free_list(struct urtwn_softc *sc, struct urtwn_data data[], int ndata)
492{
493	int i;
494
495	for (i = 0; i < ndata; i++) {
496		struct urtwn_data *dp = &data[i];
497
498		if (dp->buf != NULL) {
499			free(dp->buf, M_USBDEV);
500			dp->buf = NULL;
501		}
502		if (dp->ni != NULL) {
503			ieee80211_free_node(dp->ni);
504			dp->ni = NULL;
505		}
506	}
507}
508
509static usb_error_t
510urtwn_do_request(struct urtwn_softc *sc, struct usb_device_request *req,
511    void *data)
512{
513	usb_error_t err;
514	int ntries = 10;
515
516	URTWN_ASSERT_LOCKED(sc);
517
518	while (ntries--) {
519		err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
520		    req, data, 0, NULL, 250 /* ms */);
521		if (err == 0)
522			break;
523
524		DPRINTFN(1, "Control request failed, %s (retrying)\n",
525		    usbd_errstr(err));
526		usb_pause_mtx(&sc->sc_mtx, hz / 100);
527	}
528	return (err);
529}
530
531static struct ieee80211vap *
532urtwn_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
533    enum ieee80211_opmode opmode, int flags,
534    const uint8_t bssid[IEEE80211_ADDR_LEN],
535    const uint8_t mac[IEEE80211_ADDR_LEN])
536{
537	struct urtwn_vap *uvp;
538	struct ieee80211vap *vap;
539
540	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
541		return (NULL);
542
543	uvp = (struct urtwn_vap *) malloc(sizeof(struct urtwn_vap),
544	    M_80211_VAP, M_NOWAIT | M_ZERO);
545	if (uvp == NULL)
546		return (NULL);
547	vap = &uvp->vap;
548	/* enable s/w bmiss handling for sta mode */
549	ieee80211_vap_setup(ic, vap, name, unit, opmode,
550	    flags | IEEE80211_CLONE_NOBEACONS, bssid, mac);
551
552	/* override state transition machine */
553	uvp->newstate = vap->iv_newstate;
554	vap->iv_newstate = urtwn_newstate;
555
556	/* complete setup */
557	ieee80211_vap_attach(vap, ieee80211_media_change,
558	    ieee80211_media_status);
559	ic->ic_opmode = opmode;
560	return (vap);
561}
562
563static void
564urtwn_vap_delete(struct ieee80211vap *vap)
565{
566	struct urtwn_vap *uvp = URTWN_VAP(vap);
567
568	ieee80211_vap_detach(vap);
569	free(uvp, M_80211_VAP);
570}
571
572static struct mbuf *
573urtwn_rx_frame(struct urtwn_softc *sc, uint8_t *buf, int pktlen, int *rssi_p)
574{
575	struct ifnet *ifp = sc->sc_ifp;
576	struct ieee80211com *ic = ifp->if_l2com;
577	struct ieee80211_frame *wh;
578	struct mbuf *m;
579	struct r92c_rx_stat *stat;
580	uint32_t rxdw0, rxdw3;
581	uint8_t rate;
582	int8_t rssi = 0;
583	int infosz;
584
585	/*
586	 * don't pass packets to the ieee80211 framework if the driver isn't
587	 * RUNNING.
588	 */
589	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
590		return (NULL);
591
592	stat = (struct r92c_rx_stat *)buf;
593	rxdw0 = le32toh(stat->rxdw0);
594	rxdw3 = le32toh(stat->rxdw3);
595
596	if (rxdw0 & (R92C_RXDW0_CRCERR | R92C_RXDW0_ICVERR)) {
597		/*
598		 * This should not happen since we setup our Rx filter
599		 * to not receive these frames.
600		 */
601		ifp->if_ierrors++;
602		return (NULL);
603	}
604
605	rate = MS(rxdw3, R92C_RXDW3_RATE);
606	infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8;
607
608	/* Get RSSI from PHY status descriptor if present. */
609	if (infosz != 0 && (rxdw0 & R92C_RXDW0_PHYST)) {
610		rssi = urtwn_get_rssi(sc, rate, &stat[1]);
611		/* Update our average RSSI. */
612		urtwn_update_avgrssi(sc, rate, rssi);
613	}
614
615	m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
616	if (m == NULL) {
617		device_printf(sc->sc_dev, "could not create RX mbuf\n");
618		return (NULL);
619	}
620
621	/* Finalize mbuf. */
622	m->m_pkthdr.rcvif = ifp;
623	wh = (struct ieee80211_frame *)((uint8_t *)&stat[1] + infosz);
624	memcpy(mtod(m, uint8_t *), wh, pktlen);
625	m->m_pkthdr.len = m->m_len = pktlen;
626
627	if (ieee80211_radiotap_active(ic)) {
628		struct urtwn_rx_radiotap_header *tap = &sc->sc_rxtap;
629
630		tap->wr_flags = 0;
631		/* Map HW rate index to 802.11 rate. */
632		if (!(rxdw3 & R92C_RXDW3_HT)) {
633			switch (rate) {
634			/* CCK. */
635			case  0: tap->wr_rate =   2; break;
636			case  1: tap->wr_rate =   4; break;
637			case  2: tap->wr_rate =  11; break;
638			case  3: tap->wr_rate =  22; break;
639			/* OFDM. */
640			case  4: tap->wr_rate =  12; break;
641			case  5: tap->wr_rate =  18; break;
642			case  6: tap->wr_rate =  24; break;
643			case  7: tap->wr_rate =  36; break;
644			case  8: tap->wr_rate =  48; break;
645			case  9: tap->wr_rate =  72; break;
646			case 10: tap->wr_rate =  96; break;
647			case 11: tap->wr_rate = 108; break;
648			}
649		} else if (rate >= 12) {	/* MCS0~15. */
650			/* Bit 7 set means HT MCS instead of rate. */
651			tap->wr_rate = 0x80 | (rate - 12);
652		}
653		tap->wr_dbm_antsignal = rssi;
654		tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
655		tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
656	}
657
658	*rssi_p = rssi;
659
660	return (m);
661}
662
663static struct mbuf *
664urtwn_rxeof(struct usb_xfer *xfer, struct urtwn_data *data, int *rssi,
665    int8_t *nf)
666{
667	struct urtwn_softc *sc = data->sc;
668	struct ifnet *ifp = sc->sc_ifp;
669	struct r92c_rx_stat *stat;
670	struct mbuf *m, *m0 = NULL, *prevm = NULL;
671	uint32_t rxdw0;
672	uint8_t *buf;
673	int len, totlen, pktlen, infosz, npkts;
674
675	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
676
677	if (len < sizeof(*stat)) {
678		ifp->if_ierrors++;
679		return (NULL);
680	}
681
682	buf = data->buf;
683	/* Get the number of encapsulated frames. */
684	stat = (struct r92c_rx_stat *)buf;
685	npkts = MS(le32toh(stat->rxdw2), R92C_RXDW2_PKTCNT);
686	DPRINTFN(6, "Rx %d frames in one chunk\n", npkts);
687
688	/* Process all of them. */
689	while (npkts-- > 0) {
690		if (len < sizeof(*stat))
691			break;
692		stat = (struct r92c_rx_stat *)buf;
693		rxdw0 = le32toh(stat->rxdw0);
694
695		pktlen = MS(rxdw0, R92C_RXDW0_PKTLEN);
696		if (pktlen == 0)
697			break;
698
699		infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8;
700
701		/* Make sure everything fits in xfer. */
702		totlen = sizeof(*stat) + infosz + pktlen;
703		if (totlen > len)
704			break;
705
706		m = urtwn_rx_frame(sc, buf, pktlen, rssi);
707		if (m0 == NULL)
708			m0 = m;
709		if (prevm == NULL)
710			prevm = m;
711		else {
712			prevm->m_next = m;
713			prevm = m;
714		}
715
716		/* Next chunk is 128-byte aligned. */
717		totlen = (totlen + 127) & ~127;
718		buf += totlen;
719		len -= totlen;
720	}
721
722	return (m0);
723}
724
725static void
726urtwn_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
727{
728	struct urtwn_softc *sc = usbd_xfer_softc(xfer);
729	struct ifnet *ifp = sc->sc_ifp;
730	struct ieee80211com *ic = ifp->if_l2com;
731	struct ieee80211_frame *wh;
732	struct ieee80211_node *ni;
733	struct mbuf *m = NULL, *next;
734	struct urtwn_data *data;
735	int8_t nf;
736	int rssi = 1;
737
738	URTWN_ASSERT_LOCKED(sc);
739
740	switch (USB_GET_STATE(xfer)) {
741	case USB_ST_TRANSFERRED:
742		data = STAILQ_FIRST(&sc->sc_rx_active);
743		if (data == NULL)
744			goto tr_setup;
745		STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
746		m = urtwn_rxeof(xfer, data, &rssi, &nf);
747		STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
748		/* FALLTHROUGH */
749	case USB_ST_SETUP:
750tr_setup:
751		data = STAILQ_FIRST(&sc->sc_rx_inactive);
752		if (data == NULL) {
753			KASSERT(m == NULL, ("mbuf isn't NULL"));
754			return;
755		}
756		STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next);
757		STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next);
758		usbd_xfer_set_frame_data(xfer, 0, data->buf,
759		    usbd_xfer_max_len(xfer));
760		usbd_transfer_submit(xfer);
761
762		/*
763		 * To avoid LOR we should unlock our private mutex here to call
764		 * ieee80211_input() because here is at the end of a USB
765		 * callback and safe to unlock.
766		 */
767		URTWN_UNLOCK(sc);
768		while (m != NULL) {
769			next = m->m_next;
770			m->m_next = NULL;
771			wh = mtod(m, struct ieee80211_frame *);
772			ni = ieee80211_find_rxnode(ic,
773			    (struct ieee80211_frame_min *)wh);
774			nf = URTWN_NOISE_FLOOR;
775			if (ni != NULL) {
776				(void)ieee80211_input(ni, m, rssi, nf);
777				ieee80211_free_node(ni);
778			} else
779				(void)ieee80211_input_all(ic, m, rssi, nf);
780			m = next;
781		}
782		URTWN_LOCK(sc);
783		break;
784	default:
785		/* needs it to the inactive queue due to a error. */
786		data = STAILQ_FIRST(&sc->sc_rx_active);
787		if (data != NULL) {
788			STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
789			STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
790		}
791		if (error != USB_ERR_CANCELLED) {
792			usbd_xfer_set_stall(xfer);
793			ifp->if_ierrors++;
794			goto tr_setup;
795		}
796		break;
797	}
798}
799
800static void
801urtwn_txeof(struct usb_xfer *xfer, struct urtwn_data *data)
802{
803	struct urtwn_softc *sc = usbd_xfer_softc(xfer);
804	struct ifnet *ifp = sc->sc_ifp;
805	struct mbuf *m;
806
807	URTWN_ASSERT_LOCKED(sc);
808
809	/*
810	 * Do any tx complete callback.  Note this must be done before releasing
811	 * the node reference.
812	 */
813	if (data->m) {
814		m = data->m;
815		if (m->m_flags & M_TXCB) {
816			/* XXX status? */
817			ieee80211_process_callback(data->ni, m, 0);
818		}
819		m_freem(m);
820		data->m = NULL;
821	}
822	if (data->ni) {
823		ieee80211_free_node(data->ni);
824		data->ni = NULL;
825	}
826	sc->sc_txtimer = 0;
827	ifp->if_opackets++;
828	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
829}
830
831static void
832urtwn_bulk_tx_callback(struct usb_xfer *xfer, usb_error_t error)
833{
834	struct urtwn_softc *sc = usbd_xfer_softc(xfer);
835	struct ifnet *ifp = sc->sc_ifp;
836	struct urtwn_data *data;
837
838	URTWN_ASSERT_LOCKED(sc);
839
840	switch (USB_GET_STATE(xfer)){
841	case USB_ST_TRANSFERRED:
842		data = STAILQ_FIRST(&sc->sc_tx_active);
843		if (data == NULL)
844			goto tr_setup;
845		STAILQ_REMOVE_HEAD(&sc->sc_tx_active, next);
846		urtwn_txeof(xfer, data);
847		STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, data, next);
848		/* FALLTHROUGH */
849	case USB_ST_SETUP:
850tr_setup:
851		data = STAILQ_FIRST(&sc->sc_tx_pending);
852		if (data == NULL) {
853			DPRINTF("%s: empty pending queue\n", __func__);
854			return;
855		}
856		STAILQ_REMOVE_HEAD(&sc->sc_tx_pending, next);
857		STAILQ_INSERT_TAIL(&sc->sc_tx_active, data, next);
858
859		usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen);
860		usbd_transfer_submit(xfer);
861
862		URTWN_UNLOCK(sc);
863		urtwn_start(ifp);
864		URTWN_LOCK(sc);
865		break;
866	default:
867		data = STAILQ_FIRST(&sc->sc_tx_active);
868		if (data == NULL)
869			goto tr_setup;
870		if (data->ni != NULL) {
871			ieee80211_free_node(data->ni);
872			data->ni = NULL;
873			ifp->if_oerrors++;
874		}
875		if (error != USB_ERR_CANCELLED) {
876			usbd_xfer_set_stall(xfer);
877			goto tr_setup;
878		}
879		break;
880	}
881}
882
883static struct urtwn_data *
884_urtwn_getbuf(struct urtwn_softc *sc)
885{
886	struct urtwn_data *bf;
887
888	bf = STAILQ_FIRST(&sc->sc_tx_inactive);
889	if (bf != NULL)
890		STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next);
891	else
892		bf = NULL;
893	if (bf == NULL)
894		DPRINTF("%s: %s\n", __func__, "out of xmit buffers");
895	return (bf);
896}
897
898static struct urtwn_data *
899urtwn_getbuf(struct urtwn_softc *sc)
900{
901        struct urtwn_data *bf;
902
903	URTWN_ASSERT_LOCKED(sc);
904
905	bf = _urtwn_getbuf(sc);
906	if (bf == NULL) {
907		struct ifnet *ifp = sc->sc_ifp;
908		DPRINTF("%s: stop queue\n", __func__);
909		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
910	}
911	return (bf);
912}
913
914static int
915urtwn_write_region_1(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf,
916    int len)
917{
918	usb_device_request_t req;
919
920	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
921	req.bRequest = R92C_REQ_REGS;
922	USETW(req.wValue, addr);
923	USETW(req.wIndex, 0);
924	USETW(req.wLength, len);
925	return (urtwn_do_request(sc, &req, buf));
926}
927
928static void
929urtwn_write_1(struct urtwn_softc *sc, uint16_t addr, uint8_t val)
930{
931	urtwn_write_region_1(sc, addr, &val, 1);
932}
933
934
935static void
936urtwn_write_2(struct urtwn_softc *sc, uint16_t addr, uint16_t val)
937{
938	val = htole16(val);
939	urtwn_write_region_1(sc, addr, (uint8_t *)&val, 2);
940}
941
942static void
943urtwn_write_4(struct urtwn_softc *sc, uint16_t addr, uint32_t val)
944{
945	val = htole32(val);
946	urtwn_write_region_1(sc, addr, (uint8_t *)&val, 4);
947}
948
949static int
950urtwn_read_region_1(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf,
951    int len)
952{
953	usb_device_request_t req;
954
955	req.bmRequestType = UT_READ_VENDOR_DEVICE;
956	req.bRequest = R92C_REQ_REGS;
957	USETW(req.wValue, addr);
958	USETW(req.wIndex, 0);
959	USETW(req.wLength, len);
960	return (urtwn_do_request(sc, &req, buf));
961}
962
963static uint8_t
964urtwn_read_1(struct urtwn_softc *sc, uint16_t addr)
965{
966	uint8_t val;
967
968	if (urtwn_read_region_1(sc, addr, &val, 1) != 0)
969		return (0xff);
970	return (val);
971}
972
973static uint16_t
974urtwn_read_2(struct urtwn_softc *sc, uint16_t addr)
975{
976	uint16_t val;
977
978	if (urtwn_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0)
979		return (0xffff);
980	return (le16toh(val));
981}
982
983static uint32_t
984urtwn_read_4(struct urtwn_softc *sc, uint16_t addr)
985{
986	uint32_t val;
987
988	if (urtwn_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0)
989		return (0xffffffff);
990	return (le32toh(val));
991}
992
993static int
994urtwn_fw_cmd(struct urtwn_softc *sc, uint8_t id, const void *buf, int len)
995{
996	struct r92c_fw_cmd cmd;
997	int ntries;
998
999	/* Wait for current FW box to be empty. */
1000	for (ntries = 0; ntries < 100; ntries++) {
1001		if (!(urtwn_read_1(sc, R92C_HMETFR) & (1 << sc->fwcur)))
1002			break;
1003		DELAY(1);
1004	}
1005	if (ntries == 100) {
1006		device_printf(sc->sc_dev,
1007		    "could not send firmware command\n");
1008		return (ETIMEDOUT);
1009	}
1010	memset(&cmd, 0, sizeof(cmd));
1011	cmd.id = id;
1012	if (len > 3)
1013		cmd.id |= R92C_CMD_FLAG_EXT;
1014	KASSERT(len <= sizeof(cmd.msg), ("urtwn_fw_cmd\n"));
1015	memcpy(cmd.msg, buf, len);
1016
1017	/* Write the first word last since that will trigger the FW. */
1018	urtwn_write_region_1(sc, R92C_HMEBOX_EXT(sc->fwcur),
1019	    (uint8_t *)&cmd + 4, 2);
1020	urtwn_write_region_1(sc, R92C_HMEBOX(sc->fwcur),
1021	    (uint8_t *)&cmd + 0, 4);
1022
1023	sc->fwcur = (sc->fwcur + 1) % R92C_H2C_NBOX;
1024	return (0);
1025}
1026
1027static void
1028urtwn_rf_write(struct urtwn_softc *sc, int chain, uint8_t addr, uint32_t val)
1029{
1030	urtwn_bb_write(sc, R92C_LSSI_PARAM(chain),
1031	    SM(R92C_LSSI_PARAM_ADDR, addr) |
1032	    SM(R92C_LSSI_PARAM_DATA, val));
1033}
1034
1035static uint32_t
1036urtwn_rf_read(struct urtwn_softc *sc, int chain, uint8_t addr)
1037{
1038	uint32_t reg[R92C_MAX_CHAINS], val;
1039
1040	reg[0] = urtwn_bb_read(sc, R92C_HSSI_PARAM2(0));
1041	if (chain != 0)
1042		reg[chain] = urtwn_bb_read(sc, R92C_HSSI_PARAM2(chain));
1043
1044	urtwn_bb_write(sc, R92C_HSSI_PARAM2(0),
1045	    reg[0] & ~R92C_HSSI_PARAM2_READ_EDGE);
1046	DELAY(1000);
1047
1048	urtwn_bb_write(sc, R92C_HSSI_PARAM2(chain),
1049	    RW(reg[chain], R92C_HSSI_PARAM2_READ_ADDR, addr) |
1050	    R92C_HSSI_PARAM2_READ_EDGE);
1051	DELAY(1000);
1052
1053	urtwn_bb_write(sc, R92C_HSSI_PARAM2(0),
1054	    reg[0] | R92C_HSSI_PARAM2_READ_EDGE);
1055	DELAY(1000);
1056
1057	if (urtwn_bb_read(sc, R92C_HSSI_PARAM1(chain)) & R92C_HSSI_PARAM1_PI)
1058		val = urtwn_bb_read(sc, R92C_HSPI_READBACK(chain));
1059	else
1060		val = urtwn_bb_read(sc, R92C_LSSI_READBACK(chain));
1061	return (MS(val, R92C_LSSI_READBACK_DATA));
1062}
1063
1064static int
1065urtwn_llt_write(struct urtwn_softc *sc, uint32_t addr, uint32_t data)
1066{
1067	int ntries;
1068
1069	urtwn_write_4(sc, R92C_LLT_INIT,
1070	    SM(R92C_LLT_INIT_OP, R92C_LLT_INIT_OP_WRITE) |
1071	    SM(R92C_LLT_INIT_ADDR, addr) |
1072	    SM(R92C_LLT_INIT_DATA, data));
1073	/* Wait for write operation to complete. */
1074	for (ntries = 0; ntries < 20; ntries++) {
1075		if (MS(urtwn_read_4(sc, R92C_LLT_INIT), R92C_LLT_INIT_OP) ==
1076		    R92C_LLT_INIT_OP_NO_ACTIVE)
1077			return (0);
1078		DELAY(5);
1079	}
1080	return (ETIMEDOUT);
1081}
1082
1083static uint8_t
1084urtwn_efuse_read_1(struct urtwn_softc *sc, uint16_t addr)
1085{
1086	uint32_t reg;
1087	int ntries;
1088
1089	reg = urtwn_read_4(sc, R92C_EFUSE_CTRL);
1090	reg = RW(reg, R92C_EFUSE_CTRL_ADDR, addr);
1091	reg &= ~R92C_EFUSE_CTRL_VALID;
1092	urtwn_write_4(sc, R92C_EFUSE_CTRL, reg);
1093	/* Wait for read operation to complete. */
1094	for (ntries = 0; ntries < 100; ntries++) {
1095		reg = urtwn_read_4(sc, R92C_EFUSE_CTRL);
1096		if (reg & R92C_EFUSE_CTRL_VALID)
1097			return (MS(reg, R92C_EFUSE_CTRL_DATA));
1098		DELAY(5);
1099	}
1100	device_printf(sc->sc_dev,
1101	    "could not read efuse byte at address 0x%x\n", addr);
1102	return (0xff);
1103}
1104
1105static void
1106urtwn_efuse_read(struct urtwn_softc *sc)
1107{
1108	uint8_t *rom = (uint8_t *)&sc->rom;
1109	uint16_t addr = 0;
1110	uint32_t reg;
1111	uint8_t off, msk;
1112	int i;
1113
1114	reg = urtwn_read_2(sc, R92C_SYS_ISO_CTRL);
1115	if (!(reg & R92C_SYS_ISO_CTRL_PWC_EV12V)) {
1116		urtwn_write_2(sc, R92C_SYS_ISO_CTRL,
1117		    reg | R92C_SYS_ISO_CTRL_PWC_EV12V);
1118	}
1119	reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN);
1120	if (!(reg & R92C_SYS_FUNC_EN_ELDR)) {
1121		urtwn_write_2(sc, R92C_SYS_FUNC_EN,
1122		    reg | R92C_SYS_FUNC_EN_ELDR);
1123	}
1124	reg = urtwn_read_2(sc, R92C_SYS_CLKR);
1125	if ((reg & (R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M)) !=
1126	    (R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M)) {
1127		urtwn_write_2(sc, R92C_SYS_CLKR,
1128		    reg | R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M);
1129	}
1130	memset(&sc->rom, 0xff, sizeof(sc->rom));
1131	while (addr < 512) {
1132		reg = urtwn_efuse_read_1(sc, addr);
1133		if (reg == 0xff)
1134			break;
1135		addr++;
1136		off = reg >> 4;
1137		msk = reg & 0xf;
1138		for (i = 0; i < 4; i++) {
1139			if (msk & (1 << i))
1140				continue;
1141			rom[off * 8 + i * 2 + 0] =
1142			    urtwn_efuse_read_1(sc, addr);
1143			addr++;
1144			rom[off * 8 + i * 2 + 1] =
1145			    urtwn_efuse_read_1(sc, addr);
1146			addr++;
1147		}
1148	}
1149#ifdef URTWN_DEBUG
1150	if (urtwn_debug >= 2) {
1151		/* Dump ROM content. */
1152		printf("\n");
1153		for (i = 0; i < sizeof(sc->rom); i++)
1154			printf("%02x:", rom[i]);
1155		printf("\n");
1156	}
1157#endif
1158}
1159
1160static int
1161urtwn_read_chipid(struct urtwn_softc *sc)
1162{
1163	uint32_t reg;
1164
1165	reg = urtwn_read_4(sc, R92C_SYS_CFG);
1166	if (reg & R92C_SYS_CFG_TRP_VAUX_EN)
1167		return (EIO);
1168
1169	if (reg & R92C_SYS_CFG_TYPE_92C) {
1170		sc->chip |= URTWN_CHIP_92C;
1171		/* Check if it is a castrated 8192C. */
1172		if (MS(urtwn_read_4(sc, R92C_HPON_FSM),
1173		    R92C_HPON_FSM_CHIP_BONDING_ID) ==
1174		    R92C_HPON_FSM_CHIP_BONDING_ID_92C_1T2R)
1175			sc->chip |= URTWN_CHIP_92C_1T2R;
1176	}
1177	if (reg & R92C_SYS_CFG_VENDOR_UMC) {
1178		sc->chip |= URTWN_CHIP_UMC;
1179		if (MS(reg, R92C_SYS_CFG_CHIP_VER_RTL) == 0)
1180			sc->chip |= URTWN_CHIP_UMC_A_CUT;
1181	}
1182	return (0);
1183}
1184
1185static void
1186urtwn_read_rom(struct urtwn_softc *sc)
1187{
1188	struct r92c_rom *rom = &sc->rom;
1189
1190	/* Read full ROM image. */
1191	urtwn_efuse_read(sc);
1192
1193	/* XXX Weird but this is what the vendor driver does. */
1194	sc->pa_setting = urtwn_efuse_read_1(sc, 0x1fa);
1195	DPRINTF("PA setting=0x%x\n", sc->pa_setting);
1196
1197	sc->board_type = MS(rom->rf_opt1, R92C_ROM_RF1_BOARD_TYPE);
1198
1199	sc->regulatory = MS(rom->rf_opt1, R92C_ROM_RF1_REGULATORY);
1200	DPRINTF("regulatory type=%d\n", sc->regulatory);
1201
1202	IEEE80211_ADDR_COPY(sc->sc_bssid, rom->macaddr);
1203}
1204
1205/*
1206 * Initialize rate adaptation in firmware.
1207 */
1208static int
1209urtwn_ra_init(struct urtwn_softc *sc)
1210{
1211	static const uint8_t map[] =
1212	    { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 };
1213	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
1214	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1215	struct ieee80211_node *ni;
1216	struct ieee80211_rateset *rs;
1217	struct r92c_fw_cmd_macid_cfg cmd;
1218	uint32_t rates, basicrates;
1219	uint8_t mode;
1220	int maxrate, maxbasicrate, error, i, j;
1221
1222	ni = ieee80211_ref_node(vap->iv_bss);
1223	rs = &ni->ni_rates;
1224
1225	/* Get normal and basic rates mask. */
1226	rates = basicrates = 0;
1227	maxrate = maxbasicrate = 0;
1228	for (i = 0; i < rs->rs_nrates; i++) {
1229		/* Convert 802.11 rate to HW rate index. */
1230		for (j = 0; j < nitems(map); j++)
1231			if ((rs->rs_rates[i] & IEEE80211_RATE_VAL) == map[j])
1232				break;
1233		if (j == nitems(map))	/* Unknown rate, skip. */
1234			continue;
1235		rates |= 1 << j;
1236		if (j > maxrate)
1237			maxrate = j;
1238		if (rs->rs_rates[i] & IEEE80211_RATE_BASIC) {
1239			basicrates |= 1 << j;
1240			if (j > maxbasicrate)
1241				maxbasicrate = j;
1242		}
1243	}
1244	if (ic->ic_curmode == IEEE80211_MODE_11B)
1245		mode = R92C_RAID_11B;
1246	else
1247		mode = R92C_RAID_11BG;
1248	DPRINTF("mode=0x%x rates=0x%08x, basicrates=0x%08x\n",
1249	    mode, rates, basicrates);
1250
1251	/* Set rates mask for group addressed frames. */
1252	cmd.macid = URTWN_MACID_BC | URTWN_MACID_VALID;
1253	cmd.mask = htole32(mode << 28 | basicrates);
1254	error = urtwn_fw_cmd(sc, R92C_CMD_MACID_CONFIG, &cmd, sizeof(cmd));
1255	if (error != 0) {
1256		ieee80211_free_node(ni);
1257		device_printf(sc->sc_dev,
1258		    "could not add broadcast station\n");
1259		return (error);
1260	}
1261	/* Set initial MRR rate. */
1262	DPRINTF("maxbasicrate=%d\n", maxbasicrate);
1263	urtwn_write_1(sc, R92C_INIDATA_RATE_SEL(URTWN_MACID_BC),
1264	    maxbasicrate);
1265
1266	/* Set rates mask for unicast frames. */
1267	cmd.macid = URTWN_MACID_BSS | URTWN_MACID_VALID;
1268	cmd.mask = htole32(mode << 28 | rates);
1269	error = urtwn_fw_cmd(sc, R92C_CMD_MACID_CONFIG, &cmd, sizeof(cmd));
1270	if (error != 0) {
1271		ieee80211_free_node(ni);
1272		device_printf(sc->sc_dev, "could not add BSS station\n");
1273		return (error);
1274	}
1275	/* Set initial MRR rate. */
1276	DPRINTF("maxrate=%d\n", maxrate);
1277	urtwn_write_1(sc, R92C_INIDATA_RATE_SEL(URTWN_MACID_BSS),
1278	    maxrate);
1279
1280	/* Indicate highest supported rate. */
1281	ni->ni_txrate = rs->rs_nrates - 1;
1282	ieee80211_free_node(ni);
1283
1284	return (0);
1285}
1286
1287void
1288urtwn_tsf_sync_enable(struct urtwn_softc *sc)
1289{
1290	struct ifnet *ifp = sc->sc_ifp;
1291	struct ieee80211com *ic = ifp->if_l2com;
1292	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1293	struct ieee80211_node *ni = vap->iv_bss;
1294
1295	uint64_t tsf;
1296
1297	/* Enable TSF synchronization. */
1298	urtwn_write_1(sc, R92C_BCN_CTRL,
1299	    urtwn_read_1(sc, R92C_BCN_CTRL) & ~R92C_BCN_CTRL_DIS_TSF_UDT0);
1300
1301	urtwn_write_1(sc, R92C_BCN_CTRL,
1302	    urtwn_read_1(sc, R92C_BCN_CTRL) & ~R92C_BCN_CTRL_EN_BCN);
1303
1304	/* Set initial TSF. */
1305	memcpy(&tsf, ni->ni_tstamp.data, 8);
1306	tsf = le64toh(tsf);
1307	tsf = tsf - (tsf % (vap->iv_bss->ni_intval * IEEE80211_DUR_TU));
1308	tsf -= IEEE80211_DUR_TU;
1309	urtwn_write_4(sc, R92C_TSFTR + 0, tsf);
1310	urtwn_write_4(sc, R92C_TSFTR + 4, tsf >> 32);
1311
1312	urtwn_write_1(sc, R92C_BCN_CTRL,
1313	    urtwn_read_1(sc, R92C_BCN_CTRL) | R92C_BCN_CTRL_EN_BCN);
1314}
1315
1316static void
1317urtwn_set_led(struct urtwn_softc *sc, int led, int on)
1318{
1319	uint8_t reg;
1320
1321	if (led == URTWN_LED_LINK) {
1322		reg = urtwn_read_1(sc, R92C_LEDCFG0) & 0x70;
1323		if (!on)
1324			reg |= R92C_LEDCFG0_DIS;
1325		urtwn_write_1(sc, R92C_LEDCFG0, reg);
1326		sc->ledlink = on;	/* Save LED state. */
1327	}
1328}
1329
1330static int
1331urtwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1332{
1333	struct urtwn_vap *uvp = URTWN_VAP(vap);
1334	struct ieee80211com *ic = vap->iv_ic;
1335	struct urtwn_softc *sc = ic->ic_ifp->if_softc;
1336	struct ieee80211_node *ni;
1337	enum ieee80211_state ostate;
1338	uint32_t reg;
1339
1340	ostate = vap->iv_state;
1341	DPRINTF("%s -> %s\n", ieee80211_state_name[ostate],
1342	    ieee80211_state_name[nstate]);
1343
1344	IEEE80211_UNLOCK(ic);
1345	URTWN_LOCK(sc);
1346	callout_stop(&sc->sc_watchdog_ch);
1347
1348	if (ostate == IEEE80211_S_RUN) {
1349		/* Turn link LED off. */
1350		urtwn_set_led(sc, URTWN_LED_LINK, 0);
1351
1352		/* Set media status to 'No Link'. */
1353		reg = urtwn_read_4(sc, R92C_CR);
1354		reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_NOLINK);
1355		urtwn_write_4(sc, R92C_CR, reg);
1356
1357		/* Stop Rx of data frames. */
1358		urtwn_write_2(sc, R92C_RXFLTMAP2, 0);
1359
1360		/* Rest TSF. */
1361		urtwn_write_1(sc, R92C_DUAL_TSF_RST, 0x03);
1362
1363		/* Disable TSF synchronization. */
1364		urtwn_write_1(sc, R92C_BCN_CTRL,
1365		    urtwn_read_1(sc, R92C_BCN_CTRL) |
1366		    R92C_BCN_CTRL_DIS_TSF_UDT0);
1367
1368		/* Reset EDCA parameters. */
1369		urtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002f3217);
1370		urtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005e4317);
1371		urtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x00105320);
1372		urtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a444);
1373	}
1374
1375	switch (nstate) {
1376	case IEEE80211_S_INIT:
1377		/* Turn link LED off. */
1378		urtwn_set_led(sc, URTWN_LED_LINK, 0);
1379		break;
1380	case IEEE80211_S_SCAN:
1381		if (ostate != IEEE80211_S_SCAN) {
1382			/* Allow Rx from any BSSID. */
1383			urtwn_write_4(sc, R92C_RCR,
1384			    urtwn_read_4(sc, R92C_RCR) &
1385			    ~(R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN));
1386
1387			/* Set gain for scanning. */
1388			reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(0));
1389			reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x20);
1390			urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), reg);
1391
1392			reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(1));
1393			reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x20);
1394			urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(1), reg);
1395		}
1396
1397		/* Make link LED blink during scan. */
1398		urtwn_set_led(sc, URTWN_LED_LINK, !sc->ledlink);
1399
1400		/* Pause AC Tx queues. */
1401		urtwn_write_1(sc, R92C_TXPAUSE,
1402		    urtwn_read_1(sc, R92C_TXPAUSE) | 0x0f);
1403
1404		urtwn_set_chan(sc, ic->ic_curchan, NULL);
1405		break;
1406	case IEEE80211_S_AUTH:
1407		/* Set initial gain under link. */
1408		reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(0));
1409		reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x32);
1410		urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), reg);
1411
1412		reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(1));
1413		reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x32);
1414		urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(1), reg);
1415
1416		urtwn_set_chan(sc, ic->ic_curchan, NULL);
1417		break;
1418	case IEEE80211_S_RUN:
1419		if (vap->iv_opmode == IEEE80211_M_MONITOR) {
1420			/* Enable Rx of data frames. */
1421			urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
1422
1423			/* Turn link LED on. */
1424			urtwn_set_led(sc, URTWN_LED_LINK, 1);
1425			break;
1426		}
1427
1428		ni = ieee80211_ref_node(vap->iv_bss);
1429		/* Set media status to 'Associated'. */
1430		reg = urtwn_read_4(sc, R92C_CR);
1431		reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_INFRA);
1432		urtwn_write_4(sc, R92C_CR, reg);
1433
1434		/* Set BSSID. */
1435		urtwn_write_4(sc, R92C_BSSID + 0, LE_READ_4(&ni->ni_bssid[0]));
1436		urtwn_write_4(sc, R92C_BSSID + 4, LE_READ_2(&ni->ni_bssid[4]));
1437
1438		if (ic->ic_curmode == IEEE80211_MODE_11B)
1439			urtwn_write_1(sc, R92C_INIRTS_RATE_SEL, 0);
1440		else	/* 802.11b/g */
1441			urtwn_write_1(sc, R92C_INIRTS_RATE_SEL, 3);
1442
1443		/* Enable Rx of data frames. */
1444		urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
1445
1446		/* Flush all AC queues. */
1447		urtwn_write_1(sc, R92C_TXPAUSE, 0);
1448
1449		/* Set beacon interval. */
1450		urtwn_write_2(sc, R92C_BCN_INTERVAL, ni->ni_intval);
1451
1452		/* Allow Rx from our BSSID only. */
1453		urtwn_write_4(sc, R92C_RCR,
1454		    urtwn_read_4(sc, R92C_RCR) |
1455		    R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN);
1456
1457		/* Enable TSF synchronization. */
1458		urtwn_tsf_sync_enable(sc);
1459
1460		urtwn_write_1(sc, R92C_SIFS_CCK + 1, 10);
1461		urtwn_write_1(sc, R92C_SIFS_OFDM + 1, 10);
1462		urtwn_write_1(sc, R92C_SPEC_SIFS + 1, 10);
1463		urtwn_write_1(sc, R92C_MAC_SPEC_SIFS + 1, 10);
1464		urtwn_write_1(sc, R92C_R2T_SIFS + 1, 10);
1465		urtwn_write_1(sc, R92C_T2T_SIFS + 1, 10);
1466
1467		/* Intialize rate adaptation. */
1468		urtwn_ra_init(sc);
1469		/* Turn link LED on. */
1470		urtwn_set_led(sc, URTWN_LED_LINK, 1);
1471
1472		sc->avg_pwdb = -1;	/* Reset average RSSI. */
1473		/* Reset temperature calibration state machine. */
1474		sc->thcal_state = 0;
1475		sc->thcal_lctemp = 0;
1476		ieee80211_free_node(ni);
1477		break;
1478	default:
1479		break;
1480	}
1481	URTWN_UNLOCK(sc);
1482	IEEE80211_LOCK(ic);
1483	return(uvp->newstate(vap, nstate, arg));
1484}
1485
1486static void
1487urtwn_watchdog(void *arg)
1488{
1489	struct urtwn_softc *sc = arg;
1490	struct ifnet *ifp = sc->sc_ifp;
1491
1492	if (sc->sc_txtimer > 0) {
1493		if (--sc->sc_txtimer == 0) {
1494			device_printf(sc->sc_dev, "device timeout\n");
1495			ifp->if_oerrors++;
1496			return;
1497		}
1498		callout_reset(&sc->sc_watchdog_ch, hz, urtwn_watchdog, sc);
1499	}
1500}
1501
1502static void
1503urtwn_update_avgrssi(struct urtwn_softc *sc, int rate, int8_t rssi)
1504{
1505	int pwdb;
1506
1507	/* Convert antenna signal to percentage. */
1508	if (rssi <= -100 || rssi >= 20)
1509		pwdb = 0;
1510	else if (rssi >= 0)
1511		pwdb = 100;
1512	else
1513		pwdb = 100 + rssi;
1514	if (rate <= 3) {
1515		/* CCK gain is smaller than OFDM/MCS gain. */
1516		pwdb += 6;
1517		if (pwdb > 100)
1518			pwdb = 100;
1519		if (pwdb <= 14)
1520			pwdb -= 4;
1521		else if (pwdb <= 26)
1522			pwdb -= 8;
1523		else if (pwdb <= 34)
1524			pwdb -= 6;
1525		else if (pwdb <= 42)
1526			pwdb -= 2;
1527	}
1528	if (sc->avg_pwdb == -1)	/* Init. */
1529		sc->avg_pwdb = pwdb;
1530	else if (sc->avg_pwdb < pwdb)
1531		sc->avg_pwdb = ((sc->avg_pwdb * 19 + pwdb) / 20) + 1;
1532	else
1533		sc->avg_pwdb = ((sc->avg_pwdb * 19 + pwdb) / 20);
1534	DPRINTFN(4, "PWDB=%d EMA=%d\n", pwdb, sc->avg_pwdb);
1535}
1536
1537static int8_t
1538urtwn_get_rssi(struct urtwn_softc *sc, int rate, void *physt)
1539{
1540	static const int8_t cckoff[] = { 16, -12, -26, -46 };
1541	struct r92c_rx_phystat *phy;
1542	struct r92c_rx_cck *cck;
1543	uint8_t rpt;
1544	int8_t rssi;
1545
1546	if (rate <= 3) {
1547		cck = (struct r92c_rx_cck *)physt;
1548		if (sc->sc_flags & URTWN_FLAG_CCK_HIPWR) {
1549			rpt = (cck->agc_rpt >> 5) & 0x3;
1550			rssi = (cck->agc_rpt & 0x1f) << 1;
1551		} else {
1552			rpt = (cck->agc_rpt >> 6) & 0x3;
1553			rssi = cck->agc_rpt & 0x3e;
1554		}
1555		rssi = cckoff[rpt] - rssi;
1556	} else {	/* OFDM/HT. */
1557		phy = (struct r92c_rx_phystat *)physt;
1558		rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 110;
1559	}
1560	return (rssi);
1561}
1562
1563static int
1564urtwn_tx_start(struct urtwn_softc *sc, struct ieee80211_node *ni,
1565    struct mbuf *m0, struct urtwn_data *data)
1566{
1567	struct ifnet *ifp = sc->sc_ifp;
1568	struct ieee80211_frame *wh;
1569	struct ieee80211_key *k;
1570	struct ieee80211com *ic = ifp->if_l2com;
1571	struct ieee80211vap *vap = ni->ni_vap;
1572	struct usb_xfer *xfer;
1573	struct r92c_tx_desc *txd;
1574	uint8_t raid, type;
1575	uint16_t sum;
1576	int i, hasqos, xferlen;
1577	struct usb_xfer *urtwn_pipes[4] = {
1578		sc->sc_xfer[URTWN_BULK_TX_BE],
1579		sc->sc_xfer[URTWN_BULK_TX_BK],
1580		sc->sc_xfer[URTWN_BULK_TX_VI],
1581		sc->sc_xfer[URTWN_BULK_TX_VO]
1582	};
1583
1584	URTWN_ASSERT_LOCKED(sc);
1585
1586	/*
1587	 * Software crypto.
1588	 */
1589	wh = mtod(m0, struct ieee80211_frame *);
1590	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1591		k = ieee80211_crypto_encap(ni, m0);
1592		if (k == NULL) {
1593			device_printf(sc->sc_dev,
1594			    "ieee80211_crypto_encap returns NULL.\n");
1595			/* XXX we don't expect the fragmented frames */
1596			m_freem(m0);
1597			return (ENOBUFS);
1598		}
1599
1600		/* in case packet header moved, reset pointer */
1601		wh = mtod(m0, struct ieee80211_frame *);
1602	}
1603
1604	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
1605	case IEEE80211_FC0_TYPE_CTL:
1606	case IEEE80211_FC0_TYPE_MGT:
1607		xfer = sc->sc_xfer[URTWN_BULK_TX_VO];
1608		break;
1609	default:
1610		KASSERT(M_WME_GETAC(m0) < 4,
1611		    ("unsupported WME pipe %d", M_WME_GETAC(m0)));
1612		xfer = urtwn_pipes[M_WME_GETAC(m0)];
1613		break;
1614	}
1615
1616	hasqos = 0;
1617
1618	/* Fill Tx descriptor. */
1619	txd = (struct r92c_tx_desc *)data->buf;
1620	memset(txd, 0, sizeof(*txd));
1621
1622	txd->txdw0 |= htole32(
1623	    SM(R92C_TXDW0_PKTLEN, m0->m_pkthdr.len) |
1624	    SM(R92C_TXDW0_OFFSET, sizeof(*txd)) |
1625	    R92C_TXDW0_OWN | R92C_TXDW0_FSG | R92C_TXDW0_LSG);
1626	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1627		txd->txdw0 |= htole32(R92C_TXDW0_BMCAST);
1628
1629	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1630	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1631	    type == IEEE80211_FC0_TYPE_DATA) {
1632		if (ic->ic_curmode == IEEE80211_MODE_11B)
1633			raid = R92C_RAID_11B;
1634		else
1635			raid = R92C_RAID_11BG;
1636		txd->txdw1 |= htole32(
1637		    SM(R92C_TXDW1_MACID, URTWN_MACID_BSS) |
1638		    SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_BE) |
1639		    SM(R92C_TXDW1_RAID, raid) |
1640		    R92C_TXDW1_AGGBK);
1641
1642		if (ic->ic_flags & IEEE80211_F_USEPROT) {
1643			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY) {
1644				txd->txdw4 |= htole32(R92C_TXDW4_CTS2SELF |
1645				    R92C_TXDW4_HWRTSEN);
1646			} else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS) {
1647				txd->txdw4 |= htole32(R92C_TXDW4_RTSEN |
1648				    R92C_TXDW4_HWRTSEN);
1649			}
1650		}
1651		/* Send RTS at OFDM24. */
1652		txd->txdw4 |= htole32(SM(R92C_TXDW4_RTSRATE, 8));
1653		txd->txdw5 |= htole32(0x0001ff00);
1654		/* Send data at OFDM54. */
1655		txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 11));
1656	} else {
1657		txd->txdw1 |= htole32(
1658		    SM(R92C_TXDW1_MACID, 0) |
1659		    SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_MGNT) |
1660		    SM(R92C_TXDW1_RAID, R92C_RAID_11B));
1661
1662		/* Force CCK1. */
1663		txd->txdw4 |= htole32(R92C_TXDW4_DRVRATE);
1664		txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 0));
1665	}
1666	/* Set sequence number (already little endian). */
1667	txd->txdseq |= *(uint16_t *)wh->i_seq;
1668
1669	if (!hasqos) {
1670		/* Use HW sequence numbering for non-QoS frames. */
1671		txd->txdw4  |= htole32(R92C_TXDW4_HWSEQ);
1672		txd->txdseq |= htole16(0x8000);
1673	} else
1674		txd->txdw4 |= htole32(R92C_TXDW4_QOS);
1675
1676	/* Compute Tx descriptor checksum. */
1677	sum = 0;
1678	for (i = 0; i < sizeof(*txd) / 2; i++)
1679		sum ^= ((uint16_t *)txd)[i];
1680	txd->txdsum = sum; 	/* NB: already little endian. */
1681
1682	if (ieee80211_radiotap_active_vap(vap)) {
1683		struct urtwn_tx_radiotap_header *tap = &sc->sc_txtap;
1684
1685		tap->wt_flags = 0;
1686		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1687		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1688		ieee80211_radiotap_tx(vap, m0);
1689	}
1690
1691	xferlen = sizeof(*txd) + m0->m_pkthdr.len;
1692	m_copydata(m0, 0, m0->m_pkthdr.len, (caddr_t)&txd[1]);
1693
1694	data->buflen = xferlen;
1695	data->ni = ni;
1696	data->m = m0;
1697
1698	STAILQ_INSERT_TAIL(&sc->sc_tx_pending, data, next);
1699	usbd_transfer_start(xfer);
1700	return (0);
1701}
1702
1703static void
1704urtwn_start(struct ifnet *ifp)
1705{
1706	struct urtwn_softc *sc = ifp->if_softc;
1707	struct ieee80211_node *ni;
1708	struct mbuf *m;
1709	struct urtwn_data *bf;
1710
1711	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1712		return;
1713
1714	URTWN_LOCK(sc);
1715	for (;;) {
1716		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1717		if (m == NULL)
1718			break;
1719		bf = urtwn_getbuf(sc);
1720		if (bf == NULL) {
1721			IFQ_DRV_PREPEND(&ifp->if_snd, m);
1722			break;
1723		}
1724		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
1725		m->m_pkthdr.rcvif = NULL;
1726
1727		if (urtwn_tx_start(sc, ni, m, bf) != 0) {
1728			ifp->if_oerrors++;
1729			STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
1730			ieee80211_free_node(ni);
1731			break;
1732		}
1733
1734		sc->sc_txtimer = 5;
1735		callout_reset(&sc->sc_watchdog_ch, hz, urtwn_watchdog, sc);
1736	}
1737	URTWN_UNLOCK(sc);
1738}
1739
1740static int
1741urtwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1742{
1743	struct ieee80211com *ic = ifp->if_l2com;
1744	struct ifreq *ifr = (struct ifreq *) data;
1745	int error = 0, startall = 0;
1746
1747	switch (cmd) {
1748	case SIOCSIFFLAGS:
1749		if (ifp->if_flags & IFF_UP) {
1750			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1751				urtwn_init(ifp->if_softc);
1752				startall = 1;
1753			}
1754		} else {
1755			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1756				urtwn_stop(ifp, 1);
1757		}
1758		if (startall)
1759			ieee80211_start_all(ic);
1760		break;
1761	case SIOCGIFMEDIA:
1762		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
1763		break;
1764	case SIOCGIFADDR:
1765		error = ether_ioctl(ifp, cmd, data);
1766		break;
1767	default:
1768		error = EINVAL;
1769		break;
1770	}
1771	return (error);
1772}
1773
1774static int
1775urtwn_alloc_list(struct urtwn_softc *sc, struct urtwn_data data[],
1776    int ndata, int maxsz)
1777{
1778	int i, error;
1779
1780	for (i = 0; i < ndata; i++) {
1781		struct urtwn_data *dp = &data[i];
1782		dp->sc = sc;
1783		dp->m = NULL;
1784		dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT);
1785		if (dp->buf == NULL) {
1786			device_printf(sc->sc_dev,
1787			    "could not allocate buffer\n");
1788			error = ENOMEM;
1789			goto fail;
1790		}
1791		dp->ni = NULL;
1792	}
1793
1794	return (0);
1795fail:
1796	urtwn_free_list(sc, data, ndata);
1797	return (error);
1798}
1799
1800static int
1801urtwn_alloc_rx_list(struct urtwn_softc *sc)
1802{
1803        int error, i;
1804
1805	error = urtwn_alloc_list(sc, sc->sc_rx, URTWN_RX_LIST_COUNT,
1806	    URTWN_RXBUFSZ);
1807	if (error != 0)
1808		return (error);
1809
1810	STAILQ_INIT(&sc->sc_rx_active);
1811	STAILQ_INIT(&sc->sc_rx_inactive);
1812
1813	for (i = 0; i < URTWN_RX_LIST_COUNT; i++)
1814		STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i], next);
1815
1816	return (0);
1817}
1818
1819static int
1820urtwn_alloc_tx_list(struct urtwn_softc *sc)
1821{
1822	int error, i;
1823
1824	error = urtwn_alloc_list(sc, sc->sc_tx, URTWN_TX_LIST_COUNT,
1825	    URTWN_TXBUFSZ);
1826	if (error != 0)
1827		return (error);
1828
1829	STAILQ_INIT(&sc->sc_tx_active);
1830	STAILQ_INIT(&sc->sc_tx_inactive);
1831	STAILQ_INIT(&sc->sc_tx_pending);
1832
1833	for (i = 0; i < URTWN_TX_LIST_COUNT; i++)
1834		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i], next);
1835
1836	return (0);
1837}
1838
1839static int
1840urtwn_power_on(struct urtwn_softc *sc)
1841{
1842	uint32_t reg;
1843	int ntries;
1844
1845	/* Wait for autoload done bit. */
1846	for (ntries = 0; ntries < 1000; ntries++) {
1847		if (urtwn_read_1(sc, R92C_APS_FSMCO) & R92C_APS_FSMCO_PFM_ALDN)
1848			break;
1849		DELAY(5);
1850	}
1851	if (ntries == 1000) {
1852		device_printf(sc->sc_dev,
1853		    "timeout waiting for chip autoload\n");
1854		return (ETIMEDOUT);
1855	}
1856
1857	/* Unlock ISO/CLK/Power control register. */
1858	urtwn_write_1(sc, R92C_RSV_CTRL, 0);
1859	/* Move SPS into PWM mode. */
1860	urtwn_write_1(sc, R92C_SPS0_CTRL, 0x2b);
1861	DELAY(100);
1862
1863	reg = urtwn_read_1(sc, R92C_LDOV12D_CTRL);
1864	if (!(reg & R92C_LDOV12D_CTRL_LDV12_EN)) {
1865		urtwn_write_1(sc, R92C_LDOV12D_CTRL,
1866		    reg | R92C_LDOV12D_CTRL_LDV12_EN);
1867		DELAY(100);
1868		urtwn_write_1(sc, R92C_SYS_ISO_CTRL,
1869		    urtwn_read_1(sc, R92C_SYS_ISO_CTRL) &
1870		    ~R92C_SYS_ISO_CTRL_MD2PP);
1871	}
1872
1873	/* Auto enable WLAN. */
1874	urtwn_write_2(sc, R92C_APS_FSMCO,
1875	    urtwn_read_2(sc, R92C_APS_FSMCO) | R92C_APS_FSMCO_APFM_ONMAC);
1876	for (ntries = 0; ntries < 1000; ntries++) {
1877		if (urtwn_read_2(sc, R92C_APS_FSMCO) &
1878		    R92C_APS_FSMCO_APFM_ONMAC)
1879			break;
1880		DELAY(5);
1881	}
1882	if (ntries == 1000) {
1883		device_printf(sc->sc_dev,
1884		    "timeout waiting for MAC auto ON\n");
1885		return (ETIMEDOUT);
1886	}
1887
1888	/* Enable radio, GPIO and LED functions. */
1889	urtwn_write_2(sc, R92C_APS_FSMCO,
1890	    R92C_APS_FSMCO_AFSM_HSUS |
1891	    R92C_APS_FSMCO_PDN_EN |
1892	    R92C_APS_FSMCO_PFM_ALDN);
1893	/* Release RF digital isolation. */
1894	urtwn_write_2(sc, R92C_SYS_ISO_CTRL,
1895	    urtwn_read_2(sc, R92C_SYS_ISO_CTRL) & ~R92C_SYS_ISO_CTRL_DIOR);
1896
1897	/* Initialize MAC. */
1898	urtwn_write_1(sc, R92C_APSD_CTRL,
1899	    urtwn_read_1(sc, R92C_APSD_CTRL) & ~R92C_APSD_CTRL_OFF);
1900	for (ntries = 0; ntries < 200; ntries++) {
1901		if (!(urtwn_read_1(sc, R92C_APSD_CTRL) &
1902		    R92C_APSD_CTRL_OFF_STATUS))
1903			break;
1904		DELAY(5);
1905	}
1906	if (ntries == 200) {
1907		device_printf(sc->sc_dev,
1908		    "timeout waiting for MAC initialization\n");
1909		return (ETIMEDOUT);
1910	}
1911
1912	/* Enable MAC DMA/WMAC/SCHEDULE/SEC blocks. */
1913	reg = urtwn_read_2(sc, R92C_CR);
1914	reg |= R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN |
1915	    R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN |
1916	    R92C_CR_SCHEDULE_EN | R92C_CR_MACTXEN | R92C_CR_MACRXEN |
1917	    R92C_CR_ENSEC;
1918	urtwn_write_2(sc, R92C_CR, reg);
1919
1920	urtwn_write_1(sc, 0xfe10, 0x19);
1921	return (0);
1922}
1923
1924static int
1925urtwn_llt_init(struct urtwn_softc *sc)
1926{
1927	int i, error;
1928
1929	/* Reserve pages [0; R92C_TX_PAGE_COUNT]. */
1930	for (i = 0; i < R92C_TX_PAGE_COUNT; i++) {
1931		if ((error = urtwn_llt_write(sc, i, i + 1)) != 0)
1932			return (error);
1933	}
1934	/* NB: 0xff indicates end-of-list. */
1935	if ((error = urtwn_llt_write(sc, i, 0xff)) != 0)
1936		return (error);
1937	/*
1938	 * Use pages [R92C_TX_PAGE_COUNT + 1; R92C_TXPKTBUF_COUNT - 1]
1939	 * as ring buffer.
1940	 */
1941	for (++i; i < R92C_TXPKTBUF_COUNT - 1; i++) {
1942		if ((error = urtwn_llt_write(sc, i, i + 1)) != 0)
1943			return (error);
1944	}
1945	/* Make the last page point to the beginning of the ring buffer. */
1946	error = urtwn_llt_write(sc, i, R92C_TX_PAGE_COUNT + 1);
1947	return (error);
1948}
1949
1950static void
1951urtwn_fw_reset(struct urtwn_softc *sc)
1952{
1953	uint16_t reg;
1954	int ntries;
1955
1956	/* Tell 8051 to reset itself. */
1957	urtwn_write_1(sc, R92C_HMETFR + 3, 0x20);
1958
1959	/* Wait until 8051 resets by itself. */
1960	for (ntries = 0; ntries < 100; ntries++) {
1961		reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN);
1962		if (!(reg & R92C_SYS_FUNC_EN_CPUEN))
1963			return;
1964		DELAY(50);
1965	}
1966	/* Force 8051 reset. */
1967	urtwn_write_2(sc, R92C_SYS_FUNC_EN, reg & ~R92C_SYS_FUNC_EN_CPUEN);
1968}
1969
1970static int
1971urtwn_fw_loadpage(struct urtwn_softc *sc, int page, const uint8_t *buf, int len)
1972{
1973	uint32_t reg;
1974	int off, mlen, error = 0;
1975
1976	reg = urtwn_read_4(sc, R92C_MCUFWDL);
1977	reg = RW(reg, R92C_MCUFWDL_PAGE, page);
1978	urtwn_write_4(sc, R92C_MCUFWDL, reg);
1979
1980	off = R92C_FW_START_ADDR;
1981	while (len > 0) {
1982		if (len > 196)
1983			mlen = 196;
1984		else if (len > 4)
1985			mlen = 4;
1986		else
1987			mlen = 1;
1988		/* XXX fix this deconst */
1989		error = urtwn_write_region_1(sc, off,
1990		    __DECONST(uint8_t *, buf), mlen);
1991		if (error != 0)
1992			break;
1993		off += mlen;
1994		buf += mlen;
1995		len -= mlen;
1996	}
1997	return (error);
1998}
1999
2000static int
2001urtwn_load_firmware(struct urtwn_softc *sc)
2002{
2003	const struct firmware *fw;
2004	const struct r92c_fw_hdr *hdr;
2005	const char *imagename;
2006	const u_char *ptr;
2007	size_t len;
2008	uint32_t reg;
2009	int mlen, ntries, page, error;
2010
2011	/* Read firmware image from the filesystem. */
2012	if ((sc->chip & (URTWN_CHIP_UMC_A_CUT | URTWN_CHIP_92C)) ==
2013	    URTWN_CHIP_UMC_A_CUT)
2014		imagename = "urtwn-rtl8192cfwU";
2015	else
2016		imagename = "urtwn-rtl8192cfwT";
2017
2018	fw = firmware_get(imagename);
2019	if (fw == NULL) {
2020		device_printf(sc->sc_dev,
2021		    "failed loadfirmware of file %s\n", imagename);
2022		return (ENOENT);
2023	}
2024
2025	len = fw->datasize;
2026
2027	if (len < sizeof(*hdr)) {
2028		device_printf(sc->sc_dev, "firmware too short\n");
2029		error = EINVAL;
2030		goto fail;
2031	}
2032	ptr = fw->data;
2033	hdr = (const struct r92c_fw_hdr *)ptr;
2034	/* Check if there is a valid FW header and skip it. */
2035	if ((le16toh(hdr->signature) >> 4) == 0x88c ||
2036	    (le16toh(hdr->signature) >> 4) == 0x92c) {
2037		DPRINTF("FW V%d.%d %02d-%02d %02d:%02d\n",
2038		    le16toh(hdr->version), le16toh(hdr->subversion),
2039		    hdr->month, hdr->date, hdr->hour, hdr->minute);
2040		ptr += sizeof(*hdr);
2041		len -= sizeof(*hdr);
2042	}
2043
2044	if (urtwn_read_1(sc, R92C_MCUFWDL) & 0x80) {
2045		urtwn_fw_reset(sc);
2046		urtwn_write_1(sc, R92C_MCUFWDL, 0);
2047	}
2048	urtwn_write_2(sc, R92C_SYS_FUNC_EN,
2049	    urtwn_read_2(sc, R92C_SYS_FUNC_EN) |
2050	    R92C_SYS_FUNC_EN_CPUEN);
2051	urtwn_write_1(sc, R92C_MCUFWDL,
2052	    urtwn_read_1(sc, R92C_MCUFWDL) | R92C_MCUFWDL_EN);
2053	urtwn_write_1(sc, R92C_MCUFWDL + 2,
2054	    urtwn_read_1(sc, R92C_MCUFWDL + 2) & ~0x08);
2055
2056	for (page = 0; len > 0; page++) {
2057		mlen = min(len, R92C_FW_PAGE_SIZE);
2058		error = urtwn_fw_loadpage(sc, page, ptr, mlen);
2059		if (error != 0) {
2060			device_printf(sc->sc_dev,
2061			    "could not load firmware page\n");
2062			goto fail;
2063		}
2064		ptr += mlen;
2065		len -= mlen;
2066	}
2067	urtwn_write_1(sc, R92C_MCUFWDL,
2068	    urtwn_read_1(sc, R92C_MCUFWDL) & ~R92C_MCUFWDL_EN);
2069	urtwn_write_1(sc, R92C_MCUFWDL + 1, 0);
2070
2071	/* Wait for checksum report. */
2072	for (ntries = 0; ntries < 1000; ntries++) {
2073		if (urtwn_read_4(sc, R92C_MCUFWDL) & R92C_MCUFWDL_CHKSUM_RPT)
2074			break;
2075		DELAY(5);
2076	}
2077	if (ntries == 1000) {
2078		device_printf(sc->sc_dev,
2079		    "timeout waiting for checksum report\n");
2080		error = ETIMEDOUT;
2081		goto fail;
2082	}
2083
2084	reg = urtwn_read_4(sc, R92C_MCUFWDL);
2085	reg = (reg & ~R92C_MCUFWDL_WINTINI_RDY) | R92C_MCUFWDL_RDY;
2086	urtwn_write_4(sc, R92C_MCUFWDL, reg);
2087	/* Wait for firmware readiness. */
2088	for (ntries = 0; ntries < 1000; ntries++) {
2089		if (urtwn_read_4(sc, R92C_MCUFWDL) & R92C_MCUFWDL_WINTINI_RDY)
2090			break;
2091		DELAY(5);
2092	}
2093	if (ntries == 1000) {
2094		device_printf(sc->sc_dev,
2095		    "timeout waiting for firmware readiness\n");
2096		error = ETIMEDOUT;
2097		goto fail;
2098	}
2099fail:
2100	firmware_put(fw, FIRMWARE_UNLOAD);
2101	return (error);
2102}
2103
2104static int
2105urtwn_dma_init(struct urtwn_softc *sc)
2106{
2107	int hashq, hasnq, haslq, nqueues, nqpages, nrempages;
2108	uint32_t reg;
2109	int error;
2110
2111	/* Initialize LLT table. */
2112	error = urtwn_llt_init(sc);
2113	if (error != 0)
2114		return (error);
2115
2116	/* Get Tx queues to USB endpoints mapping. */
2117	hashq = hasnq = haslq = 0;
2118	reg = urtwn_read_2(sc, R92C_USB_EP + 1);
2119	DPRINTFN(2, "USB endpoints mapping 0x%x\n", reg);
2120	if (MS(reg, R92C_USB_EP_HQ) != 0)
2121		hashq = 1;
2122	if (MS(reg, R92C_USB_EP_NQ) != 0)
2123		hasnq = 1;
2124	if (MS(reg, R92C_USB_EP_LQ) != 0)
2125		haslq = 1;
2126	nqueues = hashq + hasnq + haslq;
2127	if (nqueues == 0)
2128		return (EIO);
2129	/* Get the number of pages for each queue. */
2130	nqpages = (R92C_TX_PAGE_COUNT - R92C_PUBQ_NPAGES) / nqueues;
2131	/* The remaining pages are assigned to the high priority queue. */
2132	nrempages = (R92C_TX_PAGE_COUNT - R92C_PUBQ_NPAGES) % nqueues;
2133
2134	/* Set number of pages for normal priority queue. */
2135	urtwn_write_1(sc, R92C_RQPN_NPQ, hasnq ? nqpages : 0);
2136	urtwn_write_4(sc, R92C_RQPN,
2137	    /* Set number of pages for public queue. */
2138	    SM(R92C_RQPN_PUBQ, R92C_PUBQ_NPAGES) |
2139	    /* Set number of pages for high priority queue. */
2140	    SM(R92C_RQPN_HPQ, hashq ? nqpages + nrempages : 0) |
2141	    /* Set number of pages for low priority queue. */
2142	    SM(R92C_RQPN_LPQ, haslq ? nqpages : 0) |
2143	    /* Load values. */
2144	    R92C_RQPN_LD);
2145
2146	urtwn_write_1(sc, R92C_TXPKTBUF_BCNQ_BDNY, R92C_TX_PAGE_BOUNDARY);
2147	urtwn_write_1(sc, R92C_TXPKTBUF_MGQ_BDNY, R92C_TX_PAGE_BOUNDARY);
2148	urtwn_write_1(sc, R92C_TXPKTBUF_WMAC_LBK_BF_HD, R92C_TX_PAGE_BOUNDARY);
2149	urtwn_write_1(sc, R92C_TRXFF_BNDY, R92C_TX_PAGE_BOUNDARY);
2150	urtwn_write_1(sc, R92C_TDECTRL + 1, R92C_TX_PAGE_BOUNDARY);
2151
2152	/* Set queue to USB pipe mapping. */
2153	reg = urtwn_read_2(sc, R92C_TRXDMA_CTRL);
2154	reg &= ~R92C_TRXDMA_CTRL_QMAP_M;
2155	if (nqueues == 1) {
2156		if (hashq)
2157			reg |= R92C_TRXDMA_CTRL_QMAP_HQ;
2158		else if (hasnq)
2159			reg |= R92C_TRXDMA_CTRL_QMAP_NQ;
2160		else
2161			reg |= R92C_TRXDMA_CTRL_QMAP_LQ;
2162	} else if (nqueues == 2) {
2163		/* All 2-endpoints configs have a high priority queue. */
2164		if (!hashq)
2165			return (EIO);
2166		if (hasnq)
2167			reg |= R92C_TRXDMA_CTRL_QMAP_HQ_NQ;
2168		else
2169			reg |= R92C_TRXDMA_CTRL_QMAP_HQ_LQ;
2170	} else
2171		reg |= R92C_TRXDMA_CTRL_QMAP_3EP;
2172	urtwn_write_2(sc, R92C_TRXDMA_CTRL, reg);
2173
2174	/* Set Tx/Rx transfer page boundary. */
2175	urtwn_write_2(sc, R92C_TRXFF_BNDY + 2, 0x27ff);
2176
2177	/* Set Tx/Rx transfer page size. */
2178	urtwn_write_1(sc, R92C_PBP,
2179	    SM(R92C_PBP_PSRX, R92C_PBP_128) |
2180	    SM(R92C_PBP_PSTX, R92C_PBP_128));
2181	return (0);
2182}
2183
2184static void
2185urtwn_mac_init(struct urtwn_softc *sc)
2186{
2187	int i;
2188
2189	/* Write MAC initialization values. */
2190	for (i = 0; i < nitems(rtl8192cu_mac); i++)
2191		urtwn_write_1(sc, rtl8192cu_mac[i].reg, rtl8192cu_mac[i].val);
2192}
2193
2194static void
2195urtwn_bb_init(struct urtwn_softc *sc)
2196{
2197	const struct urtwn_bb_prog *prog;
2198	uint32_t reg;
2199	int i;
2200
2201	/* Enable BB and RF. */
2202	urtwn_write_2(sc, R92C_SYS_FUNC_EN,
2203	    urtwn_read_2(sc, R92C_SYS_FUNC_EN) |
2204	    R92C_SYS_FUNC_EN_BBRSTB | R92C_SYS_FUNC_EN_BB_GLB_RST |
2205	    R92C_SYS_FUNC_EN_DIO_RF);
2206
2207	urtwn_write_2(sc, R92C_AFE_PLL_CTRL, 0xdb83);
2208
2209	urtwn_write_1(sc, R92C_RF_CTRL,
2210	    R92C_RF_CTRL_EN | R92C_RF_CTRL_RSTB | R92C_RF_CTRL_SDMRSTB);
2211	urtwn_write_1(sc, R92C_SYS_FUNC_EN,
2212	    R92C_SYS_FUNC_EN_USBA | R92C_SYS_FUNC_EN_USBD |
2213	    R92C_SYS_FUNC_EN_BB_GLB_RST | R92C_SYS_FUNC_EN_BBRSTB);
2214
2215	urtwn_write_1(sc, R92C_LDOHCI12_CTRL, 0x0f);
2216	urtwn_write_1(sc, 0x15, 0xe9);
2217	urtwn_write_1(sc, R92C_AFE_XTAL_CTRL + 1, 0x80);
2218
2219	/* Select BB programming based on board type. */
2220	if (!(sc->chip & URTWN_CHIP_92C)) {
2221		if (sc->board_type == R92C_BOARD_TYPE_MINICARD)
2222			prog = &rtl8188ce_bb_prog;
2223		else if (sc->board_type == R92C_BOARD_TYPE_HIGHPA)
2224			prog = &rtl8188ru_bb_prog;
2225		else
2226			prog = &rtl8188cu_bb_prog;
2227	} else {
2228		if (sc->board_type == R92C_BOARD_TYPE_MINICARD)
2229			prog = &rtl8192ce_bb_prog;
2230		else
2231			prog = &rtl8192cu_bb_prog;
2232	}
2233	/* Write BB initialization values. */
2234	for (i = 0; i < prog->count; i++) {
2235		urtwn_bb_write(sc, prog->regs[i], prog->vals[i]);
2236		DELAY(1);
2237	}
2238
2239	if (sc->chip & URTWN_CHIP_92C_1T2R) {
2240		/* 8192C 1T only configuration. */
2241		reg = urtwn_bb_read(sc, R92C_FPGA0_TXINFO);
2242		reg = (reg & ~0x00000003) | 0x2;
2243		urtwn_bb_write(sc, R92C_FPGA0_TXINFO, reg);
2244
2245		reg = urtwn_bb_read(sc, R92C_FPGA1_TXINFO);
2246		reg = (reg & ~0x00300033) | 0x00200022;
2247		urtwn_bb_write(sc, R92C_FPGA1_TXINFO, reg);
2248
2249		reg = urtwn_bb_read(sc, R92C_CCK0_AFESETTING);
2250		reg = (reg & ~0xff000000) | 0x45 << 24;
2251		urtwn_bb_write(sc, R92C_CCK0_AFESETTING, reg);
2252
2253		reg = urtwn_bb_read(sc, R92C_OFDM0_TRXPATHENA);
2254		reg = (reg & ~0x000000ff) | 0x23;
2255		urtwn_bb_write(sc, R92C_OFDM0_TRXPATHENA, reg);
2256
2257		reg = urtwn_bb_read(sc, R92C_OFDM0_AGCPARAM1);
2258		reg = (reg & ~0x00000030) | 1 << 4;
2259		urtwn_bb_write(sc, R92C_OFDM0_AGCPARAM1, reg);
2260
2261		reg = urtwn_bb_read(sc, 0xe74);
2262		reg = (reg & ~0x0c000000) | 2 << 26;
2263		urtwn_bb_write(sc, 0xe74, reg);
2264		reg = urtwn_bb_read(sc, 0xe78);
2265		reg = (reg & ~0x0c000000) | 2 << 26;
2266		urtwn_bb_write(sc, 0xe78, reg);
2267		reg = urtwn_bb_read(sc, 0xe7c);
2268		reg = (reg & ~0x0c000000) | 2 << 26;
2269		urtwn_bb_write(sc, 0xe7c, reg);
2270		reg = urtwn_bb_read(sc, 0xe80);
2271		reg = (reg & ~0x0c000000) | 2 << 26;
2272		urtwn_bb_write(sc, 0xe80, reg);
2273		reg = urtwn_bb_read(sc, 0xe88);
2274		reg = (reg & ~0x0c000000) | 2 << 26;
2275		urtwn_bb_write(sc, 0xe88, reg);
2276	}
2277
2278	/* Write AGC values. */
2279	for (i = 0; i < prog->agccount; i++) {
2280		urtwn_bb_write(sc, R92C_OFDM0_AGCRSSITABLE,
2281		    prog->agcvals[i]);
2282		DELAY(1);
2283	}
2284
2285	if (urtwn_bb_read(sc, R92C_HSSI_PARAM2(0)) &
2286	    R92C_HSSI_PARAM2_CCK_HIPWR)
2287		sc->sc_flags |= URTWN_FLAG_CCK_HIPWR;
2288}
2289
2290void
2291urtwn_rf_init(struct urtwn_softc *sc)
2292{
2293	const struct urtwn_rf_prog *prog;
2294	uint32_t reg, type;
2295	int i, j, idx, off;
2296
2297	/* Select RF programming based on board type. */
2298	if (!(sc->chip & URTWN_CHIP_92C)) {
2299		if (sc->board_type == R92C_BOARD_TYPE_MINICARD)
2300			prog = rtl8188ce_rf_prog;
2301		else if (sc->board_type == R92C_BOARD_TYPE_HIGHPA)
2302			prog = rtl8188ru_rf_prog;
2303		else
2304			prog = rtl8188cu_rf_prog;
2305	} else
2306		prog = rtl8192ce_rf_prog;
2307
2308	for (i = 0; i < sc->nrxchains; i++) {
2309		/* Save RF_ENV control type. */
2310		idx = i / 2;
2311		off = (i % 2) * 16;
2312		reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(idx));
2313		type = (reg >> off) & 0x10;
2314
2315		/* Set RF_ENV enable. */
2316		reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACEOE(i));
2317		reg |= 0x100000;
2318		urtwn_bb_write(sc, R92C_FPGA0_RFIFACEOE(i), reg);
2319		DELAY(1);
2320		/* Set RF_ENV output high. */
2321		reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACEOE(i));
2322		reg |= 0x10;
2323		urtwn_bb_write(sc, R92C_FPGA0_RFIFACEOE(i), reg);
2324		DELAY(1);
2325		/* Set address and data lengths of RF registers. */
2326		reg = urtwn_bb_read(sc, R92C_HSSI_PARAM2(i));
2327		reg &= ~R92C_HSSI_PARAM2_ADDR_LENGTH;
2328		urtwn_bb_write(sc, R92C_HSSI_PARAM2(i), reg);
2329		DELAY(1);
2330		reg = urtwn_bb_read(sc, R92C_HSSI_PARAM2(i));
2331		reg &= ~R92C_HSSI_PARAM2_DATA_LENGTH;
2332		urtwn_bb_write(sc, R92C_HSSI_PARAM2(i), reg);
2333		DELAY(1);
2334
2335		/* Write RF initialization values for this chain. */
2336		for (j = 0; j < prog[i].count; j++) {
2337			if (prog[i].regs[j] >= 0xf9 &&
2338			    prog[i].regs[j] <= 0xfe) {
2339				/*
2340				 * These are fake RF registers offsets that
2341				 * indicate a delay is required.
2342				 */
2343				usb_pause_mtx(&sc->sc_mtx, 50);
2344				continue;
2345			}
2346			urtwn_rf_write(sc, i, prog[i].regs[j],
2347			    prog[i].vals[j]);
2348			DELAY(1);
2349		}
2350
2351		/* Restore RF_ENV control type. */
2352		reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(idx));
2353		reg &= ~(0x10 << off) | (type << off);
2354		urtwn_bb_write(sc, R92C_FPGA0_RFIFACESW(idx), reg);
2355
2356		/* Cache RF register CHNLBW. */
2357		sc->rf_chnlbw[i] = urtwn_rf_read(sc, i, R92C_RF_CHNLBW);
2358	}
2359
2360	if ((sc->chip & (URTWN_CHIP_UMC_A_CUT | URTWN_CHIP_92C)) ==
2361	    URTWN_CHIP_UMC_A_CUT) {
2362		urtwn_rf_write(sc, 0, R92C_RF_RX_G1, 0x30255);
2363		urtwn_rf_write(sc, 0, R92C_RF_RX_G2, 0x50a00);
2364	}
2365}
2366
2367static void
2368urtwn_cam_init(struct urtwn_softc *sc)
2369{
2370	/* Invalidate all CAM entries. */
2371	urtwn_write_4(sc, R92C_CAMCMD,
2372	    R92C_CAMCMD_POLLING | R92C_CAMCMD_CLR);
2373}
2374
2375static void
2376urtwn_pa_bias_init(struct urtwn_softc *sc)
2377{
2378	uint8_t reg;
2379	int i;
2380
2381	for (i = 0; i < sc->nrxchains; i++) {
2382		if (sc->pa_setting & (1 << i))
2383			continue;
2384		urtwn_rf_write(sc, i, R92C_RF_IPA, 0x0f406);
2385		urtwn_rf_write(sc, i, R92C_RF_IPA, 0x4f406);
2386		urtwn_rf_write(sc, i, R92C_RF_IPA, 0x8f406);
2387		urtwn_rf_write(sc, i, R92C_RF_IPA, 0xcf406);
2388	}
2389	if (!(sc->pa_setting & 0x10)) {
2390		reg = urtwn_read_1(sc, 0x16);
2391		reg = (reg & ~0xf0) | 0x90;
2392		urtwn_write_1(sc, 0x16, reg);
2393	}
2394}
2395
2396static void
2397urtwn_rxfilter_init(struct urtwn_softc *sc)
2398{
2399	/* Initialize Rx filter. */
2400	/* TODO: use better filter for monitor mode. */
2401	urtwn_write_4(sc, R92C_RCR,
2402	    R92C_RCR_AAP | R92C_RCR_APM | R92C_RCR_AM | R92C_RCR_AB |
2403	    R92C_RCR_APP_ICV | R92C_RCR_AMF | R92C_RCR_HTC_LOC_CTRL |
2404	    R92C_RCR_APP_MIC | R92C_RCR_APP_PHYSTS);
2405	/* Accept all multicast frames. */
2406	urtwn_write_4(sc, R92C_MAR + 0, 0xffffffff);
2407	urtwn_write_4(sc, R92C_MAR + 4, 0xffffffff);
2408	/* Accept all management frames. */
2409	urtwn_write_2(sc, R92C_RXFLTMAP0, 0xffff);
2410	/* Reject all control frames. */
2411	urtwn_write_2(sc, R92C_RXFLTMAP1, 0x0000);
2412	/* Accept all data frames. */
2413	urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
2414}
2415
2416static void
2417urtwn_edca_init(struct urtwn_softc *sc)
2418{
2419	urtwn_write_2(sc, R92C_SPEC_SIFS, 0x100a);
2420	urtwn_write_2(sc, R92C_MAC_SPEC_SIFS, 0x100a);
2421	urtwn_write_2(sc, R92C_SIFS_CCK, 0x100a);
2422	urtwn_write_2(sc, R92C_SIFS_OFDM, 0x100a);
2423	urtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x005ea42b);
2424	urtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a44f);
2425	urtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005ea324);
2426	urtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002fa226);
2427}
2428
2429void
2430urtwn_write_txpower(struct urtwn_softc *sc, int chain,
2431    uint16_t power[URTWN_RIDX_COUNT])
2432{
2433	uint32_t reg;
2434
2435	/* Write per-CCK rate Tx power. */
2436	if (chain == 0) {
2437		reg = urtwn_bb_read(sc, R92C_TXAGC_A_CCK1_MCS32);
2438		reg = RW(reg, R92C_TXAGC_A_CCK1,  power[0]);
2439		urtwn_bb_write(sc, R92C_TXAGC_A_CCK1_MCS32, reg);
2440		reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK11_A_CCK2_11);
2441		reg = RW(reg, R92C_TXAGC_A_CCK2,  power[1]);
2442		reg = RW(reg, R92C_TXAGC_A_CCK55, power[2]);
2443		reg = RW(reg, R92C_TXAGC_A_CCK11, power[3]);
2444		urtwn_bb_write(sc, R92C_TXAGC_B_CCK11_A_CCK2_11, reg);
2445	} else {
2446		reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK1_55_MCS32);
2447		reg = RW(reg, R92C_TXAGC_B_CCK1,  power[0]);
2448		reg = RW(reg, R92C_TXAGC_B_CCK2,  power[1]);
2449		reg = RW(reg, R92C_TXAGC_B_CCK55, power[2]);
2450		urtwn_bb_write(sc, R92C_TXAGC_B_CCK1_55_MCS32, reg);
2451		reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK11_A_CCK2_11);
2452		reg = RW(reg, R92C_TXAGC_B_CCK11, power[3]);
2453		urtwn_bb_write(sc, R92C_TXAGC_B_CCK11_A_CCK2_11, reg);
2454	}
2455	/* Write per-OFDM rate Tx power. */
2456	urtwn_bb_write(sc, R92C_TXAGC_RATE18_06(chain),
2457	    SM(R92C_TXAGC_RATE06, power[ 4]) |
2458	    SM(R92C_TXAGC_RATE09, power[ 5]) |
2459	    SM(R92C_TXAGC_RATE12, power[ 6]) |
2460	    SM(R92C_TXAGC_RATE18, power[ 7]));
2461	urtwn_bb_write(sc, R92C_TXAGC_RATE54_24(chain),
2462	    SM(R92C_TXAGC_RATE24, power[ 8]) |
2463	    SM(R92C_TXAGC_RATE36, power[ 9]) |
2464	    SM(R92C_TXAGC_RATE48, power[10]) |
2465	    SM(R92C_TXAGC_RATE54, power[11]));
2466	/* Write per-MCS Tx power. */
2467	urtwn_bb_write(sc, R92C_TXAGC_MCS03_MCS00(chain),
2468	    SM(R92C_TXAGC_MCS00,  power[12]) |
2469	    SM(R92C_TXAGC_MCS01,  power[13]) |
2470	    SM(R92C_TXAGC_MCS02,  power[14]) |
2471	    SM(R92C_TXAGC_MCS03,  power[15]));
2472	urtwn_bb_write(sc, R92C_TXAGC_MCS07_MCS04(chain),
2473	    SM(R92C_TXAGC_MCS04,  power[16]) |
2474	    SM(R92C_TXAGC_MCS05,  power[17]) |
2475	    SM(R92C_TXAGC_MCS06,  power[18]) |
2476	    SM(R92C_TXAGC_MCS07,  power[19]));
2477	urtwn_bb_write(sc, R92C_TXAGC_MCS11_MCS08(chain),
2478	    SM(R92C_TXAGC_MCS08,  power[20]) |
2479	    SM(R92C_TXAGC_MCS08,  power[21]) |
2480	    SM(R92C_TXAGC_MCS10,  power[22]) |
2481	    SM(R92C_TXAGC_MCS11,  power[23]));
2482	urtwn_bb_write(sc, R92C_TXAGC_MCS15_MCS12(chain),
2483	    SM(R92C_TXAGC_MCS12,  power[24]) |
2484	    SM(R92C_TXAGC_MCS13,  power[25]) |
2485	    SM(R92C_TXAGC_MCS14,  power[26]) |
2486	    SM(R92C_TXAGC_MCS15,  power[27]));
2487}
2488
2489void
2490urtwn_get_txpower(struct urtwn_softc *sc, int chain,
2491    struct ieee80211_channel *c, struct ieee80211_channel *extc,
2492    uint16_t power[URTWN_RIDX_COUNT])
2493{
2494	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2495	struct r92c_rom *rom = &sc->rom;
2496	uint16_t cckpow, ofdmpow, htpow, diff, max;
2497	const struct urtwn_txpwr *base;
2498	int ridx, chan, group;
2499
2500	/* Determine channel group. */
2501	chan = ieee80211_chan2ieee(ic, c);	/* XXX center freq! */
2502	if (chan <= 3)
2503		group = 0;
2504	else if (chan <= 9)
2505		group = 1;
2506	else
2507		group = 2;
2508
2509	/* Get original Tx power based on board type and RF chain. */
2510	if (!(sc->chip & URTWN_CHIP_92C)) {
2511		if (sc->board_type == R92C_BOARD_TYPE_HIGHPA)
2512			base = &rtl8188ru_txagc[chain];
2513		else
2514			base = &rtl8192cu_txagc[chain];
2515	} else
2516		base = &rtl8192cu_txagc[chain];
2517
2518	memset(power, 0, URTWN_RIDX_COUNT * sizeof(power[0]));
2519	if (sc->regulatory == 0) {
2520		for (ridx = 0; ridx <= 3; ridx++)
2521			power[ridx] = base->pwr[0][ridx];
2522	}
2523	for (ridx = 4; ridx < URTWN_RIDX_COUNT; ridx++) {
2524		if (sc->regulatory == 3) {
2525			power[ridx] = base->pwr[0][ridx];
2526			/* Apply vendor limits. */
2527			if (extc != NULL)
2528				max = rom->ht40_max_pwr[group];
2529			else
2530				max = rom->ht20_max_pwr[group];
2531			max = (max >> (chain * 4)) & 0xf;
2532			if (power[ridx] > max)
2533				power[ridx] = max;
2534		} else if (sc->regulatory == 1) {
2535			if (extc == NULL)
2536				power[ridx] = base->pwr[group][ridx];
2537		} else if (sc->regulatory != 2)
2538			power[ridx] = base->pwr[0][ridx];
2539	}
2540
2541	/* Compute per-CCK rate Tx power. */
2542	cckpow = rom->cck_tx_pwr[chain][group];
2543	for (ridx = 0; ridx <= 3; ridx++) {
2544		power[ridx] += cckpow;
2545		if (power[ridx] > R92C_MAX_TX_PWR)
2546			power[ridx] = R92C_MAX_TX_PWR;
2547	}
2548
2549	htpow = rom->ht40_1s_tx_pwr[chain][group];
2550	if (sc->ntxchains > 1) {
2551		/* Apply reduction for 2 spatial streams. */
2552		diff = rom->ht40_2s_tx_pwr_diff[group];
2553		diff = (diff >> (chain * 4)) & 0xf;
2554		htpow = (htpow > diff) ? htpow - diff : 0;
2555	}
2556
2557	/* Compute per-OFDM rate Tx power. */
2558	diff = rom->ofdm_tx_pwr_diff[group];
2559	diff = (diff >> (chain * 4)) & 0xf;
2560	ofdmpow = htpow + diff;	/* HT->OFDM correction. */
2561	for (ridx = 4; ridx <= 11; ridx++) {
2562		power[ridx] += ofdmpow;
2563		if (power[ridx] > R92C_MAX_TX_PWR)
2564			power[ridx] = R92C_MAX_TX_PWR;
2565	}
2566
2567	/* Compute per-MCS Tx power. */
2568	if (extc == NULL) {
2569		diff = rom->ht20_tx_pwr_diff[group];
2570		diff = (diff >> (chain * 4)) & 0xf;
2571		htpow += diff;	/* HT40->HT20 correction. */
2572	}
2573	for (ridx = 12; ridx <= 27; ridx++) {
2574		power[ridx] += htpow;
2575		if (power[ridx] > R92C_MAX_TX_PWR)
2576			power[ridx] = R92C_MAX_TX_PWR;
2577	}
2578#ifdef URTWN_DEBUG
2579	if (urtwn_debug >= 4) {
2580		/* Dump per-rate Tx power values. */
2581		printf("Tx power for chain %d:\n", chain);
2582		for (ridx = 0; ridx < URTWN_RIDX_COUNT; ridx++)
2583			printf("Rate %d = %u\n", ridx, power[ridx]);
2584	}
2585#endif
2586}
2587
2588void
2589urtwn_set_txpower(struct urtwn_softc *sc, struct ieee80211_channel *c,
2590    struct ieee80211_channel *extc)
2591{
2592	uint16_t power[URTWN_RIDX_COUNT];
2593	int i;
2594
2595	for (i = 0; i < sc->ntxchains; i++) {
2596		/* Compute per-rate Tx power values. */
2597		urtwn_get_txpower(sc, i, c, extc, power);
2598		/* Write per-rate Tx power values to hardware. */
2599		urtwn_write_txpower(sc, i, power);
2600	}
2601}
2602
2603static void
2604urtwn_scan_start(struct ieee80211com *ic)
2605{
2606	/* XXX do nothing?  */
2607}
2608
2609static void
2610urtwn_scan_end(struct ieee80211com *ic)
2611{
2612	/* XXX do nothing?  */
2613}
2614
2615static void
2616urtwn_set_channel(struct ieee80211com *ic)
2617{
2618	struct urtwn_softc *sc = ic->ic_ifp->if_softc;
2619
2620	URTWN_LOCK(sc);
2621	urtwn_set_chan(sc, ic->ic_curchan, NULL);
2622	URTWN_UNLOCK(sc);
2623}
2624
2625static void
2626urtwn_update_mcast(struct ifnet *ifp)
2627{
2628	/* XXX do nothing?  */
2629}
2630
2631static void
2632urtwn_set_chan(struct urtwn_softc *sc, struct ieee80211_channel *c,
2633    struct ieee80211_channel *extc)
2634{
2635	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2636	uint32_t reg;
2637	u_int chan;
2638	int i;
2639
2640	chan = ieee80211_chan2ieee(ic, c);	/* XXX center freq! */
2641	if (chan == 0 || chan == IEEE80211_CHAN_ANY) {
2642		device_printf(sc->sc_dev,
2643		    "%s: invalid channel %x\n", __func__, chan);
2644		return;
2645	}
2646
2647	/* Set Tx power for this new channel. */
2648	urtwn_set_txpower(sc, c, extc);
2649
2650	for (i = 0; i < sc->nrxchains; i++) {
2651		urtwn_rf_write(sc, i, R92C_RF_CHNLBW,
2652		    RW(sc->rf_chnlbw[i], R92C_RF_CHNLBW_CHNL, chan));
2653	}
2654#ifndef IEEE80211_NO_HT
2655	if (extc != NULL) {
2656		/* Is secondary channel below or above primary? */
2657		int prichlo = c->ic_freq < extc->ic_freq;
2658
2659		urtwn_write_1(sc, R92C_BWOPMODE,
2660		    urtwn_read_1(sc, R92C_BWOPMODE) & ~R92C_BWOPMODE_20MHZ);
2661
2662		reg = urtwn_read_1(sc, R92C_RRSR + 2);
2663		reg = (reg & ~0x6f) | (prichlo ? 1 : 2) << 5;
2664		urtwn_write_1(sc, R92C_RRSR + 2, reg);
2665
2666		urtwn_bb_write(sc, R92C_FPGA0_RFMOD,
2667		    urtwn_bb_read(sc, R92C_FPGA0_RFMOD) | R92C_RFMOD_40MHZ);
2668		urtwn_bb_write(sc, R92C_FPGA1_RFMOD,
2669		    urtwn_bb_read(sc, R92C_FPGA1_RFMOD) | R92C_RFMOD_40MHZ);
2670
2671		/* Set CCK side band. */
2672		reg = urtwn_bb_read(sc, R92C_CCK0_SYSTEM);
2673		reg = (reg & ~0x00000010) | (prichlo ? 0 : 1) << 4;
2674		urtwn_bb_write(sc, R92C_CCK0_SYSTEM, reg);
2675
2676		reg = urtwn_bb_read(sc, R92C_OFDM1_LSTF);
2677		reg = (reg & ~0x00000c00) | (prichlo ? 1 : 2) << 10;
2678		urtwn_bb_write(sc, R92C_OFDM1_LSTF, reg);
2679
2680		urtwn_bb_write(sc, R92C_FPGA0_ANAPARAM2,
2681		    urtwn_bb_read(sc, R92C_FPGA0_ANAPARAM2) &
2682		    ~R92C_FPGA0_ANAPARAM2_CBW20);
2683
2684		reg = urtwn_bb_read(sc, 0x818);
2685		reg = (reg & ~0x0c000000) | (prichlo ? 2 : 1) << 26;
2686		urtwn_bb_write(sc, 0x818, reg);
2687
2688		/* Select 40MHz bandwidth. */
2689		urtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
2690		    (sc->rf_chnlbw[0] & ~0xfff) | chan);
2691	} else
2692#endif
2693	{
2694		urtwn_write_1(sc, R92C_BWOPMODE,
2695		    urtwn_read_1(sc, R92C_BWOPMODE) | R92C_BWOPMODE_20MHZ);
2696
2697		urtwn_bb_write(sc, R92C_FPGA0_RFMOD,
2698		    urtwn_bb_read(sc, R92C_FPGA0_RFMOD) & ~R92C_RFMOD_40MHZ);
2699		urtwn_bb_write(sc, R92C_FPGA1_RFMOD,
2700		    urtwn_bb_read(sc, R92C_FPGA1_RFMOD) & ~R92C_RFMOD_40MHZ);
2701
2702		urtwn_bb_write(sc, R92C_FPGA0_ANAPARAM2,
2703		    urtwn_bb_read(sc, R92C_FPGA0_ANAPARAM2) |
2704		    R92C_FPGA0_ANAPARAM2_CBW20);
2705
2706		/* Select 20MHz bandwidth. */
2707		urtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
2708		    (sc->rf_chnlbw[0] & ~0xfff) | R92C_RF_CHNLBW_BW20 | chan);
2709	}
2710}
2711
2712static void
2713urtwn_iq_calib(struct urtwn_softc *sc)
2714{
2715	/* TODO */
2716}
2717
2718static void
2719urtwn_lc_calib(struct urtwn_softc *sc)
2720{
2721	uint32_t rf_ac[2];
2722	uint8_t txmode;
2723	int i;
2724
2725	txmode = urtwn_read_1(sc, R92C_OFDM1_LSTF + 3);
2726	if ((txmode & 0x70) != 0) {
2727		/* Disable all continuous Tx. */
2728		urtwn_write_1(sc, R92C_OFDM1_LSTF + 3, txmode & ~0x70);
2729
2730		/* Set RF mode to standby mode. */
2731		for (i = 0; i < sc->nrxchains; i++) {
2732			rf_ac[i] = urtwn_rf_read(sc, i, R92C_RF_AC);
2733			urtwn_rf_write(sc, i, R92C_RF_AC,
2734			    RW(rf_ac[i], R92C_RF_AC_MODE,
2735				R92C_RF_AC_MODE_STANDBY));
2736		}
2737	} else {
2738		/* Block all Tx queues. */
2739		urtwn_write_1(sc, R92C_TXPAUSE, 0xff);
2740	}
2741	/* Start calibration. */
2742	urtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
2743	    urtwn_rf_read(sc, 0, R92C_RF_CHNLBW) | R92C_RF_CHNLBW_LCSTART);
2744
2745	/* Give calibration the time to complete. */
2746	usb_pause_mtx(&sc->sc_mtx, 100);
2747
2748	/* Restore configuration. */
2749	if ((txmode & 0x70) != 0) {
2750		/* Restore Tx mode. */
2751		urtwn_write_1(sc, R92C_OFDM1_LSTF + 3, txmode);
2752		/* Restore RF mode. */
2753		for (i = 0; i < sc->nrxchains; i++)
2754			urtwn_rf_write(sc, i, R92C_RF_AC, rf_ac[i]);
2755	} else {
2756		/* Unblock all Tx queues. */
2757		urtwn_write_1(sc, R92C_TXPAUSE, 0x00);
2758	}
2759}
2760
2761static void
2762urtwn_init_locked(void *arg)
2763{
2764	struct urtwn_softc *sc = arg;
2765	struct ifnet *ifp = sc->sc_ifp;
2766	uint32_t reg;
2767	int error;
2768
2769	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2770		urtwn_stop_locked(ifp, 0);
2771
2772	/* Init firmware commands ring. */
2773	sc->fwcur = 0;
2774
2775	/* Allocate Tx/Rx buffers. */
2776	error = urtwn_alloc_rx_list(sc);
2777	if (error != 0)
2778		goto fail;
2779
2780	error = urtwn_alloc_tx_list(sc);
2781	if (error != 0)
2782		goto fail;
2783
2784	/* Power on adapter. */
2785	error = urtwn_power_on(sc);
2786	if (error != 0)
2787		goto fail;
2788
2789	/* Initialize DMA. */
2790	error = urtwn_dma_init(sc);
2791	if (error != 0)
2792		goto fail;
2793
2794	/* Set info size in Rx descriptors (in 64-bit words). */
2795	urtwn_write_1(sc, R92C_RX_DRVINFO_SZ, 4);
2796
2797	/* Init interrupts. */
2798	urtwn_write_4(sc, R92C_HISR, 0xffffffff);
2799	urtwn_write_4(sc, R92C_HIMR, 0xffffffff);
2800
2801	/* Set MAC address. */
2802	urtwn_write_region_1(sc, R92C_MACID, IF_LLADDR(ifp),
2803	    IEEE80211_ADDR_LEN);
2804
2805	/* Set initial network type. */
2806	reg = urtwn_read_4(sc, R92C_CR);
2807	reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_INFRA);
2808	urtwn_write_4(sc, R92C_CR, reg);
2809
2810	urtwn_rxfilter_init(sc);
2811
2812	reg = urtwn_read_4(sc, R92C_RRSR);
2813	reg = RW(reg, R92C_RRSR_RATE_BITMAP, R92C_RRSR_RATE_CCK_ONLY_1M);
2814	urtwn_write_4(sc, R92C_RRSR, reg);
2815
2816	/* Set short/long retry limits. */
2817	urtwn_write_2(sc, R92C_RL,
2818	    SM(R92C_RL_SRL, 0x30) | SM(R92C_RL_LRL, 0x30));
2819
2820	/* Initialize EDCA parameters. */
2821	urtwn_edca_init(sc);
2822
2823	/* Setup rate fallback. */
2824	urtwn_write_4(sc, R92C_DARFRC + 0, 0x00000000);
2825	urtwn_write_4(sc, R92C_DARFRC + 4, 0x10080404);
2826	urtwn_write_4(sc, R92C_RARFRC + 0, 0x04030201);
2827	urtwn_write_4(sc, R92C_RARFRC + 4, 0x08070605);
2828
2829	urtwn_write_1(sc, R92C_FWHW_TXQ_CTRL,
2830	    urtwn_read_1(sc, R92C_FWHW_TXQ_CTRL) |
2831	    R92C_FWHW_TXQ_CTRL_AMPDU_RTY_NEW);
2832	/* Set ACK timeout. */
2833	urtwn_write_1(sc, R92C_ACKTO, 0x40);
2834
2835	/* Setup USB aggregation. */
2836	reg = urtwn_read_4(sc, R92C_TDECTRL);
2837	reg = RW(reg, R92C_TDECTRL_BLK_DESC_NUM, 6);
2838	urtwn_write_4(sc, R92C_TDECTRL, reg);
2839	urtwn_write_1(sc, R92C_TRXDMA_CTRL,
2840	    urtwn_read_1(sc, R92C_TRXDMA_CTRL) |
2841	    R92C_TRXDMA_CTRL_RXDMA_AGG_EN);
2842	urtwn_write_1(sc, R92C_USB_SPECIAL_OPTION,
2843	    urtwn_read_1(sc, R92C_USB_SPECIAL_OPTION) |
2844	    R92C_USB_SPECIAL_OPTION_AGG_EN);
2845	urtwn_write_1(sc, R92C_RXDMA_AGG_PG_TH, 48);
2846	urtwn_write_1(sc, R92C_USB_DMA_AGG_TO, 4);
2847	urtwn_write_1(sc, R92C_USB_AGG_TH, 8);
2848	urtwn_write_1(sc, R92C_USB_AGG_TO, 6);
2849
2850	/* Initialize beacon parameters. */
2851	urtwn_write_2(sc, R92C_TBTT_PROHIBIT, 0x6404);
2852	urtwn_write_1(sc, R92C_DRVERLYINT, 0x05);
2853	urtwn_write_1(sc, R92C_BCNDMATIM, 0x02);
2854	urtwn_write_2(sc, R92C_BCNTCFG, 0x660f);
2855
2856	/* Setup AMPDU aggregation. */
2857	urtwn_write_4(sc, R92C_AGGLEN_LMT, 0x99997631);	/* MCS7~0 */
2858	urtwn_write_1(sc, R92C_AGGR_BREAK_TIME, 0x16);
2859	urtwn_write_2(sc, 0x4ca, 0x0708);
2860
2861	urtwn_write_1(sc, R92C_BCN_MAX_ERR, 0xff);
2862	urtwn_write_1(sc, R92C_BCN_CTRL, R92C_BCN_CTRL_DIS_TSF_UDT0);
2863
2864	/* Load 8051 microcode. */
2865	error = urtwn_load_firmware(sc);
2866	if (error != 0)
2867		goto fail;
2868
2869	/* Initialize MAC/BB/RF blocks. */
2870	urtwn_mac_init(sc);
2871	urtwn_bb_init(sc);
2872	urtwn_rf_init(sc);
2873
2874	/* Turn CCK and OFDM blocks on. */
2875	reg = urtwn_bb_read(sc, R92C_FPGA0_RFMOD);
2876	reg |= R92C_RFMOD_CCK_EN;
2877	urtwn_bb_write(sc, R92C_FPGA0_RFMOD, reg);
2878	reg = urtwn_bb_read(sc, R92C_FPGA0_RFMOD);
2879	reg |= R92C_RFMOD_OFDM_EN;
2880	urtwn_bb_write(sc, R92C_FPGA0_RFMOD, reg);
2881
2882	/* Clear per-station keys table. */
2883	urtwn_cam_init(sc);
2884
2885	/* Enable hardware sequence numbering. */
2886	urtwn_write_1(sc, R92C_HWSEQ_CTRL, 0xff);
2887
2888	/* Perform LO and IQ calibrations. */
2889	urtwn_iq_calib(sc);
2890	/* Perform LC calibration. */
2891	urtwn_lc_calib(sc);
2892
2893	/* Fix USB interference issue. */
2894	urtwn_write_1(sc, 0xfe40, 0xe0);
2895	urtwn_write_1(sc, 0xfe41, 0x8d);
2896	urtwn_write_1(sc, 0xfe42, 0x80);
2897
2898	urtwn_pa_bias_init(sc);
2899
2900	/* Initialize GPIO setting. */
2901	urtwn_write_1(sc, R92C_GPIO_MUXCFG,
2902	    urtwn_read_1(sc, R92C_GPIO_MUXCFG) & ~R92C_GPIO_MUXCFG_ENBT);
2903
2904	/* Fix for lower temperature. */
2905	urtwn_write_1(sc, 0x15, 0xe9);
2906
2907	usbd_transfer_start(sc->sc_xfer[URTWN_BULK_RX]);
2908
2909	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2910	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2911
2912	callout_reset(&sc->sc_watchdog_ch, hz, urtwn_watchdog, sc);
2913fail:
2914	return;
2915}
2916
2917static void
2918urtwn_init(void *arg)
2919{
2920	struct urtwn_softc *sc = arg;
2921
2922	URTWN_LOCK(sc);
2923	urtwn_init_locked(arg);
2924	URTWN_UNLOCK(sc);
2925}
2926
2927static void
2928urtwn_stop_locked(struct ifnet *ifp, int disable)
2929{
2930	struct urtwn_softc *sc = ifp->if_softc;
2931
2932	(void)disable;
2933	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2934
2935	callout_stop(&sc->sc_watchdog_ch);
2936	urtwn_abort_xfers(sc);
2937}
2938
2939static void
2940urtwn_stop(struct ifnet *ifp, int disable)
2941{
2942	struct urtwn_softc *sc = ifp->if_softc;
2943
2944	URTWN_LOCK(sc);
2945	urtwn_stop_locked(ifp, disable);
2946	URTWN_UNLOCK(sc);
2947}
2948
2949static void
2950urtwn_abort_xfers(struct urtwn_softc *sc)
2951{
2952	int i;
2953
2954	URTWN_ASSERT_LOCKED(sc);
2955
2956	/* abort any pending transfers */
2957	for (i = 0; i < URTWN_N_TRANSFER; i++)
2958		usbd_transfer_stop(sc->sc_xfer[i]);
2959}
2960
2961static int
2962urtwn_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2963    const struct ieee80211_bpf_params *params)
2964{
2965	struct ieee80211com *ic = ni->ni_ic;
2966	struct ifnet *ifp = ic->ic_ifp;
2967	struct urtwn_softc *sc = ifp->if_softc;
2968	struct urtwn_data *bf;
2969
2970	/* prevent management frames from being sent if we're not ready */
2971	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
2972		m_freem(m);
2973		ieee80211_free_node(ni);
2974		return (ENETDOWN);
2975	}
2976	URTWN_LOCK(sc);
2977	bf = urtwn_getbuf(sc);
2978	if (bf == NULL) {
2979		ieee80211_free_node(ni);
2980		m_freem(m);
2981		URTWN_UNLOCK(sc);
2982		return (ENOBUFS);
2983	}
2984
2985	ifp->if_opackets++;
2986	if (urtwn_tx_start(sc, ni, m, bf) != 0) {
2987		ieee80211_free_node(ni);
2988		ifp->if_oerrors++;
2989		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
2990		URTWN_UNLOCK(sc);
2991		return (EIO);
2992	}
2993	URTWN_UNLOCK(sc);
2994
2995	sc->sc_txtimer = 5;
2996	return (0);
2997}
2998
2999static device_method_t urtwn_methods[] = {
3000	/* Device interface */
3001	DEVMETHOD(device_probe,		urtwn_match),
3002	DEVMETHOD(device_attach,	urtwn_attach),
3003	DEVMETHOD(device_detach,	urtwn_detach),
3004
3005	{ 0, 0 }
3006};
3007
3008static driver_t urtwn_driver = {
3009	"urtwn",
3010	urtwn_methods,
3011	sizeof(struct urtwn_softc)
3012};
3013
3014static devclass_t urtwn_devclass;
3015
3016DRIVER_MODULE(urtwn, uhub, urtwn_driver, urtwn_devclass, NULL, NULL);
3017MODULE_DEPEND(urtwn, usb, 1, 1, 1);
3018MODULE_DEPEND(urtwn, wlan, 1, 1, 1);
3019MODULE_DEPEND(urtwn, firmware, 1, 1, 1);
3020MODULE_DEPEND(urtwn, urtwn_fw, 1, 1, 1);
3021MODULE_VERSION(urtwn, 1);
3022