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