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