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