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