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