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