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