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