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