xref: /netbsd-src/sys/dev/usb/if_urtwn.c (revision afab4e300d3a9fb07dd8c80daf53d0feb3345706)
1 /*	$NetBSD: if_urtwn.c,v 1.105 2022/07/31 12:59:26 mlelstv Exp $	*/
2 /*	$OpenBSD: if_urtwn.c,v 1.42 2015/02/10 23:25:46 mpi Exp $	*/
3 
4 /*-
5  * Copyright (c) 2010 Damien Bergamini <damien.bergamini@free.fr>
6  * Copyright (c) 2014 Kevin Lo <kevlo@FreeBSD.org>
7  * Copyright (c) 2016 Nathanial Sloss <nathanialsloss@yahoo.com.au>
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20  */
21 
22 /*-
23  * Driver for Realtek RTL8188CE-VAU/RTL8188CUS/RTL8188EU/RTL8188RU/RTL8192CU
24  * RTL8192EU.
25  */
26 
27 #include <sys/cdefs.h>
28 __KERNEL_RCSID(0, "$NetBSD: if_urtwn.c,v 1.105 2022/07/31 12:59:26 mlelstv Exp $");
29 
30 #ifdef _KERNEL_OPT
31 #include "opt_inet.h"
32 #include "opt_usb.h"
33 #endif
34 
35 #include <sys/param.h>
36 #include <sys/sockio.h>
37 #include <sys/sysctl.h>
38 #include <sys/mbuf.h>
39 #include <sys/kernel.h>
40 #include <sys/socket.h>
41 #include <sys/systm.h>
42 #include <sys/module.h>
43 #include <sys/conf.h>
44 #include <sys/device.h>
45 #include <sys/rndsource.h>
46 
47 #include <sys/bus.h>
48 #include <machine/endian.h>
49 #include <sys/intr.h>
50 
51 #include <net/bpf.h>
52 #include <net/if.h>
53 #include <net/if_arp.h>
54 #include <net/if_dl.h>
55 #include <net/if_ether.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/ip.h>
63 #include <netinet/if_inarp.h>
64 
65 #include <net80211/ieee80211_netbsd.h>
66 #include <net80211/ieee80211_var.h>
67 #include <net80211/ieee80211_radiotap.h>
68 
69 #include <dev/firmload.h>
70 
71 #include <dev/usb/usb.h>
72 #include <dev/usb/usbdi.h>
73 #include <dev/usb/usbdivar.h>
74 #include <dev/usb/usbdi_util.h>
75 #include <dev/usb/usbdevs.h>
76 #include <dev/usb/usbhist.h>
77 
78 #include <dev/ic/rtwnreg.h>
79 #include <dev/ic/rtwn_data.h>
80 #include <dev/usb/if_urtwnreg.h>
81 #include <dev/usb/if_urtwnvar.h>
82 
83 /*
84  * The sc_write_mtx locking is to prevent sequences of writes from
85  * being intermingled with each other.  I don't know if this is really
86  * needed.  I have added it just to be on the safe side.
87  */
88 
89 #ifdef URTWN_DEBUG
90 #define	DBG_INIT	__BIT(0)
91 #define	DBG_FN		__BIT(1)
92 #define	DBG_TX		__BIT(2)
93 #define	DBG_RX		__BIT(3)
94 #define	DBG_STM		__BIT(4)
95 #define	DBG_RF		__BIT(5)
96 #define	DBG_REG		__BIT(6)
97 #define	DBG_ALL		0xffffffffU
98 u_int urtwn_debug = 0;
99 #define DPRINTFN(n, fmt, a, b, c, d) do {			\
100 	if (urtwn_debug & (n)) {				\
101 		KERNHIST_LOG(usbhist, fmt, a, b, c, d);		\
102 	}							\
103 } while (/*CONSTCOND*/0)
104 #define URTWNHIST_FUNC() USBHIST_FUNC()
105 #define URTWNHIST_CALLED() do {					\
106 	if (urtwn_debug & DBG_FN) {				\
107 		KERNHIST_CALLED(usbhist);			\
108 	}							\
109 } while(/*CONSTCOND*/0)
110 #define URTWNHIST_CALLARGS(fmt, a, b, c, d) do {		\
111 	if (urtwn_debug & DBG_FN) {				\
112 		KERNHIST_CALLARGS(usbhist, fmt, a, b, c, d);	\
113 	}							\
114 } while(/*CONSTCOND*/0)
115 #else
116 #define DPRINTFN(n, fmt, a, b, c, d)
117 #define URTWNHIST_FUNC()
118 #define URTWNHIST_CALLED()
119 #define URTWNHIST_CALLARGS(fmt, a, b, c, d)
120 #endif
121 
122 #define URTWN_DEV(v,p)	{ { USB_VENDOR_##v, USB_PRODUCT_##v##_##p }, 0 }
123 #define URTWN_RTL8188E_DEV(v,p) \
124 	{ { USB_VENDOR_##v, USB_PRODUCT_##v##_##p }, FLAG_RTL8188E }
125 #define URTWN_RTL8192EU_DEV(v,p) \
126 	{ { USB_VENDOR_##v, USB_PRODUCT_##v##_##p }, FLAG_RTL8192E }
127 static const struct urtwn_dev {
128 	struct usb_devno	dev;
129 	uint32_t		flags;
130 #define	FLAG_RTL8188E	__BIT(0)
131 #define	FLAG_RTL8192E	__BIT(1)
132 } urtwn_devs[] = {
133 	URTWN_DEV(ABOCOM,	RTL8188CU_1),
134 	URTWN_DEV(ABOCOM,	RTL8188CU_2),
135 	URTWN_DEV(ABOCOM,	RTL8192CU),
136 	URTWN_DEV(ASUSTEK,	RTL8192CU),
137 	URTWN_DEV(ASUSTEK,	RTL8192CU_3),
138 	URTWN_DEV(ASUSTEK,	USBN10NANO),
139 	URTWN_DEV(ASUSTEK,	RTL8192CU_3),
140 	URTWN_DEV(AZUREWAVE,	RTL8188CE_1),
141 	URTWN_DEV(AZUREWAVE,	RTL8188CE_2),
142 	URTWN_DEV(AZUREWAVE,	RTL8188CU),
143 	URTWN_DEV(BELKIN,	F7D2102),
144 	URTWN_DEV(BELKIN,	RTL8188CU),
145 	URTWN_DEV(BELKIN,	RTL8188CUS),
146 	URTWN_DEV(BELKIN,	RTL8192CU),
147 	URTWN_DEV(BELKIN,	RTL8192CU_1),
148 	URTWN_DEV(BELKIN,	RTL8192CU_2),
149 	URTWN_DEV(CHICONY,	RTL8188CUS_1),
150 	URTWN_DEV(CHICONY,	RTL8188CUS_2),
151 	URTWN_DEV(CHICONY,	RTL8188CUS_3),
152 	URTWN_DEV(CHICONY,	RTL8188CUS_4),
153 	URTWN_DEV(CHICONY,	RTL8188CUS_5),
154 	URTWN_DEV(CHICONY,	RTL8188CUS_6),
155 	URTWN_DEV(COMPARE,	RTL8192CU),
156 	URTWN_DEV(COREGA,	RTL8192CU),
157 	URTWN_DEV(DLINK,	DWA131B),
158 	URTWN_DEV(DLINK,	RTL8188CU),
159 	URTWN_DEV(DLINK,	RTL8192CU_1),
160 	URTWN_DEV(DLINK,	RTL8192CU_2),
161 	URTWN_DEV(DLINK,	RTL8192CU_3),
162 	URTWN_DEV(DLINK,	RTL8192CU_4),
163 	URTWN_DEV(EDIMAX,	RTL8188CU),
164 	URTWN_DEV(EDIMAX,	RTL8192CU),
165 	URTWN_DEV(FEIXUN,	RTL8188CU),
166 	URTWN_DEV(FEIXUN,	RTL8192CU),
167 	URTWN_DEV(GUILLEMOT,	HWNUP150),
168 	URTWN_DEV(GUILLEMOT,	RTL8192CU),
169 	URTWN_DEV(HAWKING,	RTL8192CU),
170 	URTWN_DEV(HAWKING,	RTL8192CU_2),
171 	URTWN_DEV(HP3,		RTL8188CU),
172 	URTWN_DEV(IODATA,	WNG150UM),
173 	URTWN_DEV(IODATA,	RTL8192CU),
174 	URTWN_DEV(NETGEAR,	WNA1000M),
175 	URTWN_DEV(NETGEAR,	RTL8192CU),
176 	URTWN_DEV(NETGEAR4,	RTL8188CU),
177 	URTWN_DEV(NOVATECH,	RTL8188CU),
178 	URTWN_DEV(PLANEX2,	RTL8188CU_1),
179 	URTWN_DEV(PLANEX2,	RTL8188CU_2),
180 	URTWN_DEV(PLANEX2,	RTL8192CU),
181 	URTWN_DEV(PLANEX2,	RTL8188CU_3),
182 	URTWN_DEV(PLANEX2,	RTL8188CU_4),
183 	URTWN_DEV(PLANEX2,	RTL8188CUS),
184 	URTWN_DEV(REALTEK,	RTL8188CE_0),
185 	URTWN_DEV(REALTEK,	RTL8188CE_1),
186 	URTWN_DEV(REALTEK,	RTL8188CTV),
187 	URTWN_DEV(REALTEK,	RTL8188CU_0),
188 	URTWN_DEV(REALTEK,	RTL8188CU_1),
189 	URTWN_DEV(REALTEK,	RTL8188CU_2),
190 	URTWN_DEV(REALTEK,	RTL8188CU_3),
191 	URTWN_DEV(REALTEK,	RTL8188CU_COMBO),
192 	URTWN_DEV(REALTEK,	RTL8188CUS),
193 	URTWN_DEV(REALTEK,	RTL8188RU),
194 	URTWN_DEV(REALTEK,	RTL8188RU_2),
195 	URTWN_DEV(REALTEK,	RTL8188RU_3),
196 	URTWN_DEV(REALTEK,	RTL8191CU),
197 	URTWN_DEV(REALTEK,	RTL8192CE),
198 	URTWN_DEV(REALTEK,	RTL8192CU),
199 	URTWN_DEV(SITECOMEU,	RTL8188CU),
200 	URTWN_DEV(SITECOMEU,	RTL8188CU_2),
201 	URTWN_DEV(SITECOMEU,	RTL8192CU),
202 	URTWN_DEV(SITECOMEU,	RTL8192CUR2),
203 	URTWN_DEV(TPLINK,	RTL8192CU),
204 	URTWN_DEV(TRENDNET,	RTL8188CU),
205 	URTWN_DEV(TRENDNET,	RTL8192CU),
206 	URTWN_DEV(TRENDNET,	TEW648UBM),
207 	URTWN_DEV(ZYXEL,	RTL8192CU),
208 
209 	/* URTWN_RTL8188E */
210 	URTWN_RTL8188E_DEV(DLINK, DWA125D1),
211 	URTWN_RTL8188E_DEV(ELECOM, WDC150SU2M),
212 	URTWN_RTL8188E_DEV(REALTEK, RTL8188ETV),
213 	URTWN_RTL8188E_DEV(REALTEK, RTL8188EU),
214 	URTWN_RTL8188E_DEV(ABOCOM, RTL8188EU),
215 	URTWN_RTL8188E_DEV(TPLINK, RTL8188EU),
216 	URTWN_RTL8188E_DEV(DLINK, DWA121B1),
217 	URTWN_RTL8188E_DEV(EDIMAX, EW7811UNV2),
218 
219 	/* URTWN_RTL8192EU */
220 	URTWN_RTL8192EU_DEV(DLINK,	DWA131E),
221 	URTWN_RTL8192EU_DEV(REALTEK,	RTL8192EU),
222 	URTWN_RTL8192EU_DEV(TPLINK,	WN821NV5),
223 	URTWN_RTL8192EU_DEV(TPLINK,	WN822NV4),
224 	URTWN_RTL8192EU_DEV(TPLINK,	WN823NV2),
225 };
226 #undef URTWN_DEV
227 #undef URTWN_RTL8188E_DEV
228 #undef URTWN_RTL8192EU_DEV
229 
230 static int	urtwn_match(device_t, cfdata_t, void *);
231 static void	urtwn_attach(device_t, device_t, void *);
232 static int	urtwn_detach(device_t, int);
233 static int	urtwn_activate(device_t, enum devact);
234 
235 CFATTACH_DECL_NEW(urtwn, sizeof(struct urtwn_softc), urtwn_match,
236     urtwn_attach, urtwn_detach, urtwn_activate);
237 
238 static int	urtwn_open_pipes(struct urtwn_softc *);
239 static void	urtwn_close_pipes(struct urtwn_softc *);
240 static int	urtwn_alloc_rx_list(struct urtwn_softc *);
241 static void	urtwn_free_rx_list(struct urtwn_softc *);
242 static int	urtwn_alloc_tx_list(struct urtwn_softc *);
243 static void	urtwn_free_tx_list(struct urtwn_softc *);
244 static void	urtwn_task(void *);
245 static void	urtwn_do_async(struct urtwn_softc *,
246 		    void (*)(struct urtwn_softc *, void *), void *, int);
247 static void	urtwn_wait_async(struct urtwn_softc *);
248 static int	urtwn_write_region_1(struct urtwn_softc *, uint16_t, uint8_t *,
249 		    int);
250 static void	urtwn_write_1(struct urtwn_softc *, uint16_t, uint8_t);
251 static void	urtwn_write_2(struct urtwn_softc *, uint16_t, uint16_t);
252 static void	urtwn_write_4(struct urtwn_softc *, uint16_t, uint32_t);
253 static int	urtwn_write_region(struct urtwn_softc *, uint16_t, uint8_t *,
254 		    int);
255 static int	urtwn_read_region_1(struct urtwn_softc *, uint16_t, uint8_t *,
256 		    int);
257 static uint8_t	urtwn_read_1(struct urtwn_softc *, uint16_t);
258 static uint16_t	urtwn_read_2(struct urtwn_softc *, uint16_t);
259 static uint32_t	urtwn_read_4(struct urtwn_softc *, uint16_t);
260 static int	urtwn_fw_cmd(struct urtwn_softc *, uint8_t, const void *, int);
261 static void	urtwn_r92c_rf_write(struct urtwn_softc *, int, uint8_t,
262 		    uint32_t);
263 static void	urtwn_r88e_rf_write(struct urtwn_softc *, int, uint8_t,
264 		    uint32_t);
265 static void	urtwn_r92e_rf_write(struct urtwn_softc *, int, uint8_t,
266 		    uint32_t);
267 static uint32_t	urtwn_rf_read(struct urtwn_softc *, int, uint8_t);
268 static int	urtwn_llt_write(struct urtwn_softc *, uint32_t, uint32_t);
269 static uint8_t	urtwn_efuse_read_1(struct urtwn_softc *, uint16_t);
270 static void	urtwn_efuse_read(struct urtwn_softc *);
271 static void	urtwn_efuse_switch_power(struct urtwn_softc *);
272 static int	urtwn_read_chipid(struct urtwn_softc *);
273 #ifdef URTWN_DEBUG
274 static void	urtwn_dump_rom(struct urtwn_softc *, struct r92c_rom *);
275 #endif
276 static void	urtwn_read_rom(struct urtwn_softc *);
277 static void	urtwn_r88e_read_rom(struct urtwn_softc *);
278 static int	urtwn_media_change(struct ifnet *);
279 static int	urtwn_ra_init(struct urtwn_softc *);
280 static int	urtwn_get_nettype(struct urtwn_softc *);
281 static void	urtwn_set_nettype0_msr(struct urtwn_softc *, uint8_t);
282 static void	urtwn_tsf_sync_enable(struct urtwn_softc *);
283 static void	urtwn_set_led(struct urtwn_softc *, int, int);
284 static void	urtwn_calib_to(void *);
285 static void	urtwn_calib_to_cb(struct urtwn_softc *, void *);
286 static void	urtwn_next_scan(void *);
287 static int	urtwn_newstate(struct ieee80211com *, enum ieee80211_state,
288 		    int);
289 static void	urtwn_newstate_cb(struct urtwn_softc *, void *);
290 static int	urtwn_wme_update(struct ieee80211com *);
291 static void	urtwn_wme_update_cb(struct urtwn_softc *, void *);
292 static void	urtwn_update_avgrssi(struct urtwn_softc *, int, int8_t);
293 static int8_t	urtwn_get_rssi(struct urtwn_softc *, int, void *);
294 static int8_t	urtwn_r88e_get_rssi(struct urtwn_softc *, int, void *);
295 static void	urtwn_rx_frame(struct urtwn_softc *, uint8_t *, int);
296 static void	urtwn_rxeof(struct usbd_xfer *, void *, usbd_status);
297 static void	urtwn_txeof(struct usbd_xfer *, void *, usbd_status);
298 static int	urtwn_tx(struct urtwn_softc *, struct mbuf *,
299 		    struct ieee80211_node *, struct urtwn_tx_data *);
300 static struct urtwn_tx_data *
301 		urtwn_get_tx_data(struct urtwn_softc *, size_t);
302 static void	urtwn_start(struct ifnet *);
303 static void	urtwn_watchdog(struct ifnet *);
304 static int	urtwn_ioctl(struct ifnet *, u_long, void *);
305 static int	urtwn_r92c_power_on(struct urtwn_softc *);
306 static int	urtwn_r92e_power_on(struct urtwn_softc *);
307 static int	urtwn_r88e_power_on(struct urtwn_softc *);
308 static int	urtwn_llt_init(struct urtwn_softc *);
309 static void	urtwn_fw_reset(struct urtwn_softc *);
310 static void	urtwn_r88e_fw_reset(struct urtwn_softc *);
311 static int	urtwn_fw_loadpage(struct urtwn_softc *, int, uint8_t *, int);
312 static int	urtwn_load_firmware(struct urtwn_softc *);
313 static int	urtwn_r92c_dma_init(struct urtwn_softc *);
314 static int	urtwn_r88e_dma_init(struct urtwn_softc *);
315 static void	urtwn_mac_init(struct urtwn_softc *);
316 static void	urtwn_bb_init(struct urtwn_softc *);
317 static void	urtwn_rf_init(struct urtwn_softc *);
318 static void	urtwn_cam_init(struct urtwn_softc *);
319 static void	urtwn_pa_bias_init(struct urtwn_softc *);
320 static void	urtwn_rxfilter_init(struct urtwn_softc *);
321 static void	urtwn_edca_init(struct urtwn_softc *);
322 static void	urtwn_write_txpower(struct urtwn_softc *, int, uint16_t[]);
323 static void	urtwn_get_txpower(struct urtwn_softc *, size_t, u_int, u_int,
324 		    uint16_t[]);
325 static void	urtwn_r88e_get_txpower(struct urtwn_softc *, size_t, u_int,
326 		    u_int, uint16_t[]);
327 static void	urtwn_set_txpower(struct urtwn_softc *, u_int, u_int);
328 static void	urtwn_set_chan(struct urtwn_softc *, struct ieee80211_channel *,
329 		    u_int);
330 static void	urtwn_iq_calib(struct urtwn_softc *, bool);
331 static void	urtwn_lc_calib(struct urtwn_softc *);
332 static void	urtwn_temp_calib(struct urtwn_softc *);
333 static int	urtwn_init(struct ifnet *);
334 static void	urtwn_stop(struct ifnet *, int);
335 static int	urtwn_reset(struct ifnet *);
336 static void	urtwn_chip_stop(struct urtwn_softc *);
337 static void	urtwn_newassoc(struct ieee80211_node *, int);
338 static void	urtwn_delay_ms(struct urtwn_softc *, int ms);
339 
340 /* Aliases. */
341 #define	urtwn_bb_write	urtwn_write_4
342 #define	urtwn_bb_read	urtwn_read_4
343 
344 #define	urtwn_lookup(d,v,p)	((const struct urtwn_dev *)usb_lookup(d,v,p))
345 
346 static const uint16_t addaReg[] = {
347 	R92C_FPGA0_XCD_SWITCHCTL, R92C_BLUETOOTH, R92C_RX_WAIT_CCA,
348 	R92C_TX_CCK_RFON, R92C_TX_CCK_BBON, R92C_TX_OFDM_RFON,
349 	R92C_TX_OFDM_BBON, R92C_TX_TO_RX, R92C_TX_TO_TX, R92C_RX_CCK,
350 	R92C_RX_OFDM, R92C_RX_WAIT_RIFS, R92C_RX_TO_RX,
351 	R92C_STANDBY, R92C_SLEEP, R92C_PMPD_ANAEN
352 };
353 
354 static int
355 urtwn_match(device_t parent, cfdata_t match, void *aux)
356 {
357 	struct usb_attach_arg *uaa = aux;
358 
359 	return urtwn_lookup(urtwn_devs, uaa->uaa_vendor, uaa->uaa_product) !=
360 	    NULL ?  UMATCH_VENDOR_PRODUCT : UMATCH_NONE;
361 }
362 
363 static void
364 urtwn_attach(device_t parent, device_t self, void *aux)
365 {
366 	struct urtwn_softc *sc = device_private(self);
367 	struct ieee80211com *ic = &sc->sc_ic;
368 	struct ifnet *ifp = &sc->sc_if;
369 	struct usb_attach_arg *uaa = aux;
370 	char *devinfop;
371 	const struct urtwn_dev *dev;
372 	usb_device_request_t req;
373 	size_t i;
374 	int error;
375 
376 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
377 
378 	sc->sc_dev = self;
379 	sc->sc_udev = uaa->uaa_device;
380 
381 	sc->chip = 0;
382 	dev = urtwn_lookup(urtwn_devs, uaa->uaa_vendor, uaa->uaa_product);
383 	if (dev != NULL && ISSET(dev->flags, FLAG_RTL8188E))
384 		SET(sc->chip, URTWN_CHIP_88E);
385 	if (dev != NULL && ISSET(dev->flags, FLAG_RTL8192E))
386 		SET(sc->chip, URTWN_CHIP_92EU);
387 
388 	aprint_naive("\n");
389 	aprint_normal("\n");
390 
391 	devinfop = usbd_devinfo_alloc(sc->sc_udev, 0);
392 	aprint_normal_dev(self, "%s\n", devinfop);
393 	usbd_devinfo_free(devinfop);
394 
395 	req.bmRequestType = UT_WRITE_DEVICE;
396 	req.bRequest = UR_SET_FEATURE;
397 	USETW(req.wValue, UF_DEVICE_REMOTE_WAKEUP);
398 	USETW(req.wIndex, UHF_PORT_SUSPEND);
399 	USETW(req.wLength, 0);
400 
401 	(void) usbd_do_request(sc->sc_udev, &req, 0);
402 
403 	cv_init(&sc->sc_task_cv, "urtwntsk");
404 	mutex_init(&sc->sc_task_mtx, MUTEX_DEFAULT, IPL_NET);
405 	mutex_init(&sc->sc_tx_mtx, MUTEX_DEFAULT, IPL_NONE);
406 	mutex_init(&sc->sc_rx_mtx, MUTEX_DEFAULT, IPL_NONE);
407 	mutex_init(&sc->sc_fwcmd_mtx, MUTEX_DEFAULT, IPL_NONE);
408 	mutex_init(&sc->sc_write_mtx, MUTEX_DEFAULT, IPL_NONE);
409 
410 	usb_init_task(&sc->sc_task, urtwn_task, sc, 0);
411 
412 	callout_init(&sc->sc_scan_to, 0);
413 	callout_setfunc(&sc->sc_scan_to, urtwn_next_scan, sc);
414 	callout_init(&sc->sc_calib_to, 0);
415 	callout_setfunc(&sc->sc_calib_to, urtwn_calib_to, sc);
416 
417 	rnd_attach_source(&sc->rnd_source, device_xname(sc->sc_dev),
418 	    RND_TYPE_NET, RND_FLAG_DEFAULT);
419 
420 	error = usbd_set_config_no(sc->sc_udev, 1, 0);
421 	if (error != 0) {
422 		aprint_error_dev(self, "failed to set configuration"
423 		    ", err=%s\n", usbd_errstr(error));
424 		goto fail;
425 	}
426 
427 	/* Get the first interface handle. */
428 	error = usbd_device2interface_handle(sc->sc_udev, 0, &sc->sc_iface);
429 	if (error != 0) {
430 		aprint_error_dev(self, "could not get interface handle\n");
431 		goto fail;
432 	}
433 
434 	error = urtwn_read_chipid(sc);
435 	if (error != 0) {
436 		aprint_error_dev(self, "unsupported test chip\n");
437 		goto fail;
438 	}
439 
440 	/* Determine number of Tx/Rx chains. */
441 	if (sc->chip & URTWN_CHIP_92C) {
442 		sc->ntxchains = (sc->chip & URTWN_CHIP_92C_1T2R) ? 1 : 2;
443 		sc->nrxchains = 2;
444 	} else if (sc->chip & URTWN_CHIP_92EU) {
445 		sc->ntxchains = 2;
446 		sc->nrxchains = 2;
447 	} else {
448 		sc->ntxchains = 1;
449 		sc->nrxchains = 1;
450 	}
451 
452 	if (ISSET(sc->chip, URTWN_CHIP_88E) ||
453 	    ISSET(sc->chip, URTWN_CHIP_92EU))
454 		urtwn_r88e_read_rom(sc);
455 	else
456 		urtwn_read_rom(sc);
457 
458 	aprint_normal_dev(self, "MAC/BB RTL%s, RF 6052 %zdT%zdR, address %s\n",
459 	    (sc->chip & URTWN_CHIP_92EU) ? "8192EU" :
460 	    (sc->chip & URTWN_CHIP_92C) ? "8192CU" :
461 	    (sc->chip & URTWN_CHIP_88E) ? "8188EU" :
462 	    (sc->board_type == R92C_BOARD_TYPE_HIGHPA) ? "8188RU" :
463 	    (sc->board_type == R92C_BOARD_TYPE_MINICARD) ? "8188CE-VAU" :
464 	    "8188CUS", sc->ntxchains, sc->nrxchains,
465 	    ether_sprintf(ic->ic_myaddr));
466 
467 	error = urtwn_open_pipes(sc);
468 	if (error != 0) {
469 		aprint_error_dev(sc->sc_dev, "could not open pipes\n");
470 		goto fail;
471 	}
472 	aprint_normal_dev(self, "%d rx pipe%s, %d tx pipe%s\n",
473 	    sc->rx_npipe, sc->rx_npipe > 1 ? "s" : "",
474 	    sc->tx_npipe, sc->tx_npipe > 1 ? "s" : "");
475 
476 	/*
477 	 * Setup the 802.11 device.
478 	 */
479 	ic->ic_ifp = ifp;
480 	ic->ic_phytype = IEEE80211_T_OFDM;	/* Not only, but not used. */
481 	ic->ic_opmode = IEEE80211_M_STA;	/* Default to BSS mode. */
482 	ic->ic_state = IEEE80211_S_INIT;
483 
484 	/* Set device capabilities. */
485 	ic->ic_caps =
486 	    IEEE80211_C_MONITOR |	/* Monitor mode supported. */
487 	    IEEE80211_C_IBSS |		/* IBSS mode supported */
488 	    IEEE80211_C_HOSTAP |	/* HostAp mode supported */
489 	    IEEE80211_C_SHPREAMBLE |	/* Short preamble supported. */
490 	    IEEE80211_C_SHSLOT |	/* Short slot time supported. */
491 	    IEEE80211_C_WME |		/* 802.11e */
492 	    IEEE80211_C_WPA;		/* 802.11i */
493 
494 	/* Set supported .11b and .11g rates. */
495 	ic->ic_sup_rates[IEEE80211_MODE_11B] = ieee80211_std_rateset_11b;
496 	ic->ic_sup_rates[IEEE80211_MODE_11G] = ieee80211_std_rateset_11g;
497 
498 	/* Set supported .11b and .11g channels (1 through 14). */
499 	for (i = 1; i <= 14; i++) {
500 		ic->ic_channels[i].ic_freq =
501 		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
502 		ic->ic_channels[i].ic_flags =
503 		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
504 		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
505 	}
506 
507 	ifp->if_softc = sc;
508 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
509 	ifp->if_init = urtwn_init;
510 	ifp->if_ioctl = urtwn_ioctl;
511 	ifp->if_start = urtwn_start;
512 	ifp->if_watchdog = urtwn_watchdog;
513 	IFQ_SET_READY(&ifp->if_snd);
514 	memcpy(ifp->if_xname, device_xname(sc->sc_dev), IFNAMSIZ);
515 
516 	if_initialize(ifp);
517 	ieee80211_ifattach(ic);
518 
519 	/* override default methods */
520 	ic->ic_newassoc = urtwn_newassoc;
521 	ic->ic_reset = urtwn_reset;
522 	ic->ic_wme.wme_update = urtwn_wme_update;
523 
524 	/* Override state transition machine. */
525 	sc->sc_newstate = ic->ic_newstate;
526 	ic->ic_newstate = urtwn_newstate;
527 
528 	/* XXX media locking needs revisiting */
529 	mutex_init(&sc->sc_media_mtx, MUTEX_DEFAULT, IPL_SOFTUSB);
530 	ieee80211_media_init_with_lock(ic,
531 	    urtwn_media_change, ieee80211_media_status, &sc->sc_media_mtx);
532 
533 	bpf_attach2(ifp, DLT_IEEE802_11_RADIO,
534 	    sizeof(struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN,
535 	    &sc->sc_drvbpf);
536 
537 	sc->sc_rxtap_len = sizeof(sc->sc_rxtapu);
538 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
539 	sc->sc_rxtap.wr_ihdr.it_present = htole32(URTWN_RX_RADIOTAP_PRESENT);
540 
541 	sc->sc_txtap_len = sizeof(sc->sc_txtapu);
542 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
543 	sc->sc_txtap.wt_ihdr.it_present = htole32(URTWN_TX_RADIOTAP_PRESENT);
544 
545 	ifp->if_percpuq = if_percpuq_create(ifp);
546 	if_register(ifp);
547 
548 	ieee80211_announce(ic);
549 
550 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
551 
552 	if (!pmf_device_register(self, NULL, NULL))
553 		aprint_error_dev(self, "couldn't establish power handler\n");
554 
555 	SET(sc->sc_flags, URTWN_FLAG_ATTACHED);
556 	return;
557 
558  fail:
559 	sc->sc_dying = 1;
560 	aprint_error_dev(self, "attach failed\n");
561 }
562 
563 static int
564 urtwn_detach(device_t self, int flags)
565 {
566 	struct urtwn_softc *sc = device_private(self);
567 	struct ifnet *ifp = &sc->sc_if;
568 	int s;
569 
570 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
571 
572 	pmf_device_deregister(self);
573 
574 	s = splusb();
575 
576 	sc->sc_dying = 1;
577 
578 	callout_halt(&sc->sc_scan_to, NULL);
579 	callout_halt(&sc->sc_calib_to, NULL);
580 
581 	if (ISSET(sc->sc_flags, URTWN_FLAG_ATTACHED)) {
582 		urtwn_stop(ifp, 0);
583 		usb_rem_task_wait(sc->sc_udev, &sc->sc_task, USB_TASKQ_DRIVER,
584 		    NULL);
585 
586 		ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
587 		bpf_detach(ifp);
588 		ieee80211_ifdetach(&sc->sc_ic);
589 		if_detach(ifp);
590 
591 		mutex_destroy(&sc->sc_media_mtx);
592 
593 		/* Close Tx/Rx pipes.  Abort done by urtwn_stop. */
594 		urtwn_close_pipes(sc);
595 	}
596 
597 	splx(s);
598 
599 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
600 
601 	rnd_detach_source(&sc->rnd_source);
602 
603 	callout_destroy(&sc->sc_scan_to);
604 	callout_destroy(&sc->sc_calib_to);
605 
606 	cv_destroy(&sc->sc_task_cv);
607 	mutex_destroy(&sc->sc_write_mtx);
608 	mutex_destroy(&sc->sc_fwcmd_mtx);
609 	mutex_destroy(&sc->sc_tx_mtx);
610 	mutex_destroy(&sc->sc_rx_mtx);
611 	mutex_destroy(&sc->sc_task_mtx);
612 
613 	return 0;
614 }
615 
616 static int
617 urtwn_activate(device_t self, enum devact act)
618 {
619 	struct urtwn_softc *sc = device_private(self);
620 
621 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
622 
623 	switch (act) {
624 	case DVACT_DEACTIVATE:
625 		if_deactivate(sc->sc_ic.ic_ifp);
626 		return 0;
627 	default:
628 		return EOPNOTSUPP;
629 	}
630 }
631 
632 static int
633 urtwn_open_pipes(struct urtwn_softc *sc)
634 {
635 	/* Bulk-out endpoints addresses (from highest to lowest prio). */
636 	static uint8_t epaddr[R92C_MAX_EPOUT];
637 	static uint8_t rxepaddr[R92C_MAX_EPIN];
638 	usb_interface_descriptor_t *id;
639 	usb_endpoint_descriptor_t *ed;
640 	size_t i, ntx = 0, nrx = 0;
641 	int error;
642 
643 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
644 
645 	/* Determine the number of bulk-out pipes. */
646 	id = usbd_get_interface_descriptor(sc->sc_iface);
647 	for (i = 0; i < id->bNumEndpoints; i++) {
648 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
649 		if (ed == NULL || UE_GET_XFERTYPE(ed->bmAttributes) != UE_BULK) {
650 			continue;
651 		}
652 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT) {
653 			if (ntx < sizeof(epaddr))
654 				epaddr[ntx] = ed->bEndpointAddress;
655 			ntx++;
656 		}
657 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN) {
658 			if (nrx < sizeof(rxepaddr))
659 				rxepaddr[nrx] = ed->bEndpointAddress;
660 			nrx++;
661 		}
662 	}
663 	if (nrx == 0 || nrx > R92C_MAX_EPIN) {
664 		aprint_error_dev(sc->sc_dev,
665 		    "%zd: invalid number of Rx bulk pipes\n", nrx);
666 		return EIO;
667 	}
668 	if (ntx == 0 || ntx > R92C_MAX_EPOUT) {
669 		aprint_error_dev(sc->sc_dev,
670 		    "%zd: invalid number of Tx bulk pipes\n", ntx);
671 		return EIO;
672 	}
673 	DPRINTFN(DBG_INIT, "found %jd/%jd bulk-in/out pipes",
674 	    nrx, ntx, 0, 0);
675 	sc->rx_npipe = nrx;
676 	sc->tx_npipe = ntx;
677 
678 	/* Open bulk-in pipe at address 0x81. */
679 	for (i = 0; i < nrx; i++) {
680 		error = usbd_open_pipe(sc->sc_iface, rxepaddr[i],
681 		    USBD_EXCLUSIVE_USE, &sc->rx_pipe[i]);
682 		if (error != 0) {
683 			aprint_error_dev(sc->sc_dev,
684 			    "could not open Rx bulk pipe 0x%02x: %d\n",
685 			    rxepaddr[i], error);
686 			goto fail;
687 		}
688 	}
689 
690 	/* Open bulk-out pipes (up to 3). */
691 	for (i = 0; i < ntx; i++) {
692 		error = usbd_open_pipe(sc->sc_iface, epaddr[i],
693 		    USBD_EXCLUSIVE_USE, &sc->tx_pipe[i]);
694 		if (error != 0) {
695 			aprint_error_dev(sc->sc_dev,
696 			    "could not open Tx bulk pipe 0x%02x: %d\n",
697 			    epaddr[i], error);
698 			goto fail;
699 		}
700 	}
701 
702 	/* Map 802.11 access categories to USB pipes. */
703 	sc->ac2idx[WME_AC_BK] =
704 	sc->ac2idx[WME_AC_BE] = (ntx == 3) ? 2 : ((ntx == 2) ? 1 : 0);
705 	sc->ac2idx[WME_AC_VI] = (ntx == 3) ? 1 : 0;
706 	sc->ac2idx[WME_AC_VO] = 0;	/* Always use highest prio. */
707 
708  fail:
709 	if (error != 0)
710 		urtwn_close_pipes(sc);
711 	return error;
712 }
713 
714 static void
715 urtwn_close_pipes(struct urtwn_softc *sc)
716 {
717 	struct usbd_pipe *pipe;
718 	size_t i;
719 
720 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
721 
722 	/* Close Rx pipes. */
723 	CTASSERT(sizeof(pipe) == sizeof(void *));
724 	for (i = 0; i < sc->rx_npipe; i++) {
725 		pipe = atomic_swap_ptr(&sc->rx_pipe[i], NULL);
726 		if (pipe != NULL) {
727 			usbd_close_pipe(pipe);
728 		}
729 	}
730 
731 	/* Close Tx pipes. */
732 	for (i = 0; i < sc->tx_npipe; i++) {
733 		pipe = atomic_swap_ptr(&sc->tx_pipe[i], NULL);
734 		if (pipe != NULL) {
735 			usbd_close_pipe(pipe);
736 		}
737 	}
738 }
739 
740 static int __noinline
741 urtwn_alloc_rx_list(struct urtwn_softc *sc)
742 {
743 	struct urtwn_rx_data *data;
744 	size_t i;
745 	int error = 0;
746 
747 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
748 
749 	for (size_t j = 0; j < sc->rx_npipe; j++) {
750 		TAILQ_INIT(&sc->rx_free_list[j]);
751 		for (i = 0; i < URTWN_RX_LIST_COUNT; i++) {
752 			data = &sc->rx_data[j][i];
753 
754 			data->sc = sc;	/* Backpointer for callbacks. */
755 
756 			error = usbd_create_xfer(sc->rx_pipe[j], URTWN_RXBUFSZ,
757 			    0, 0, &data->xfer);
758 			if (error) {
759 				aprint_error_dev(sc->sc_dev,
760 				    "could not allocate xfer\n");
761 				break;
762 			}
763 
764 			data->buf = usbd_get_buffer(data->xfer);
765 			TAILQ_INSERT_TAIL(&sc->rx_free_list[j], data, next);
766 		}
767 	}
768 	if (error != 0)
769 		urtwn_free_rx_list(sc);
770 	return error;
771 }
772 
773 static void
774 urtwn_free_rx_list(struct urtwn_softc *sc)
775 {
776 	struct usbd_xfer *xfer;
777 	size_t i;
778 
779 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
780 
781 	/* NB: Caller must abort pipe first. */
782 	for (size_t j = 0; j < sc->rx_npipe; j++) {
783 		for (i = 0; i < URTWN_RX_LIST_COUNT; i++) {
784 			CTASSERT(sizeof(xfer) == sizeof(void *));
785 			xfer = atomic_swap_ptr(&sc->rx_data[j][i].xfer, NULL);
786 			if (xfer != NULL)
787 				usbd_destroy_xfer(xfer);
788 		}
789 	}
790 }
791 
792 static int __noinline
793 urtwn_alloc_tx_list(struct urtwn_softc *sc)
794 {
795 	struct urtwn_tx_data *data;
796 	size_t i;
797 	int error = 0;
798 
799 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
800 
801 	mutex_enter(&sc->sc_tx_mtx);
802 	for (size_t j = 0; j < sc->tx_npipe; j++) {
803 		TAILQ_INIT(&sc->tx_free_list[j]);
804 		for (i = 0; i < URTWN_TX_LIST_COUNT; i++) {
805 			data = &sc->tx_data[j][i];
806 
807 			data->sc = sc;	/* Backpointer for callbacks. */
808 			data->pidx = j;
809 
810 			error = usbd_create_xfer(sc->tx_pipe[j],
811 			    URTWN_TXBUFSZ, USBD_FORCE_SHORT_XFER, 0,
812 			    &data->xfer);
813 			if (error) {
814 				aprint_error_dev(sc->sc_dev,
815 				    "could not allocate xfer\n");
816 				goto fail;
817 			}
818 
819 			data->buf = usbd_get_buffer(data->xfer);
820 
821 			/* Append this Tx buffer to our free list. */
822 			TAILQ_INSERT_TAIL(&sc->tx_free_list[j], data, next);
823 		}
824 	}
825 	mutex_exit(&sc->sc_tx_mtx);
826 	return 0;
827 
828  fail:
829 	urtwn_free_tx_list(sc);
830 	mutex_exit(&sc->sc_tx_mtx);
831 	return error;
832 }
833 
834 static void
835 urtwn_free_tx_list(struct urtwn_softc *sc)
836 {
837 	struct usbd_xfer *xfer;
838 	size_t i;
839 
840 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
841 
842 	/* NB: Caller must abort pipe first. */
843 	for (size_t j = 0; j < sc->tx_npipe; j++) {
844 		for (i = 0; i < URTWN_TX_LIST_COUNT; i++) {
845 			CTASSERT(sizeof(xfer) == sizeof(void *));
846 			xfer = atomic_swap_ptr(&sc->tx_data[j][i].xfer, NULL);
847 			if (xfer != NULL)
848 				usbd_destroy_xfer(xfer);
849 		}
850 	}
851 }
852 
853 static int
854 urtwn_tx_beacon(struct urtwn_softc *sc, struct mbuf *m,
855     struct ieee80211_node *ni)
856 {
857 	struct urtwn_tx_data *data =
858 	    urtwn_get_tx_data(sc, sc->ac2idx[WME_AC_VO]);
859 
860 	if (data == NULL)
861 		return ENOBUFS;
862 
863 	return urtwn_tx(sc, m, ni, data);
864 }
865 
866 static void
867 urtwn_task(void *arg)
868 {
869 	struct urtwn_softc *sc = arg;
870 	struct ieee80211com *ic = &sc->sc_ic;
871 	struct urtwn_host_cmd_ring *ring = &sc->cmdq;
872 	struct urtwn_host_cmd *cmd;
873 	int s;
874 
875 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
876 	if (ic->ic_state == IEEE80211_S_RUN &&
877 	    (ic->ic_opmode == IEEE80211_M_HOSTAP ||
878 	    ic->ic_opmode == IEEE80211_M_IBSS)) {
879 
880 		struct mbuf *m = ieee80211_beacon_alloc(ic, ic->ic_bss,
881 		    &sc->sc_bo);
882 		if (m == NULL) {
883 			aprint_error_dev(sc->sc_dev,
884 			    "could not allocate beacon");
885 		}
886 
887 		if (urtwn_tx_beacon(sc, m, ic->ic_bss) != 0) {
888 			aprint_error_dev(sc->sc_dev, "could not send beacon\n");
889 		}
890 
891 		/* beacon is no longer needed */
892 		m_freem(m);
893 	}
894 
895 	/* Process host commands. */
896 	s = splusb();
897 	mutex_spin_enter(&sc->sc_task_mtx);
898 	while (ring->next != ring->cur) {
899 		cmd = &ring->cmd[ring->next];
900 		mutex_spin_exit(&sc->sc_task_mtx);
901 		splx(s);
902 		/* Invoke callback with kernel lock held. */
903 		cmd->cb(sc, cmd->data);
904 		s = splusb();
905 		mutex_spin_enter(&sc->sc_task_mtx);
906 		ring->queued--;
907 		ring->next = (ring->next + 1) % URTWN_HOST_CMD_RING_COUNT;
908 	}
909 	cv_broadcast(&sc->sc_task_cv);
910 	mutex_spin_exit(&sc->sc_task_mtx);
911 	splx(s);
912 }
913 
914 static void
915 urtwn_do_async(struct urtwn_softc *sc, void (*cb)(struct urtwn_softc *, void *),
916     void *arg, int len)
917 {
918 	struct urtwn_host_cmd_ring *ring = &sc->cmdq;
919 	struct urtwn_host_cmd *cmd;
920 	int s;
921 
922 	URTWNHIST_FUNC();
923 	URTWNHIST_CALLARGS("cb=%#jx, arg=%#jx, len=%jd",
924 	    (uintptr_t)cb, (uintptr_t)arg, len, 0);
925 
926 	s = splusb();
927 	mutex_spin_enter(&sc->sc_task_mtx);
928 	cmd = &ring->cmd[ring->cur];
929 	cmd->cb = cb;
930 	KASSERT(len <= sizeof(cmd->data));
931 	memcpy(cmd->data, arg, len);
932 	ring->cur = (ring->cur + 1) % URTWN_HOST_CMD_RING_COUNT;
933 
934 	/* If there is no pending command already, schedule a task. */
935 	if (!sc->sc_dying && ++ring->queued == 1) {
936 		mutex_spin_exit(&sc->sc_task_mtx);
937 		usb_add_task(sc->sc_udev, &sc->sc_task, USB_TASKQ_DRIVER);
938 	} else
939 		mutex_spin_exit(&sc->sc_task_mtx);
940 	splx(s);
941 }
942 
943 static void
944 urtwn_wait_async(struct urtwn_softc *sc)
945 {
946 
947 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
948 
949 	/* Wait for all queued asynchronous commands to complete. */
950 	mutex_spin_enter(&sc->sc_task_mtx);
951 	while (sc->cmdq.queued > 0)
952 		cv_wait(&sc->sc_task_cv, &sc->sc_task_mtx);
953 	mutex_spin_exit(&sc->sc_task_mtx);
954 }
955 
956 static int
957 urtwn_write_region_1(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf,
958     int len)
959 {
960 	usb_device_request_t req;
961 	usbd_status error;
962 
963 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
964 	KASSERT(mutex_owned(&sc->sc_write_mtx));
965 
966 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
967 	req.bRequest = R92C_REQ_REGS;
968 	USETW(req.wValue, addr);
969 	USETW(req.wIndex, 0);
970 	USETW(req.wLength, len);
971 	error = usbd_do_request(sc->sc_udev, &req, buf);
972 	if (error != USBD_NORMAL_COMPLETION) {
973 		DPRINTFN(DBG_REG, "error=%jd: addr=%#jx, len=%jd",
974 		    error, addr, len, 0);
975 	}
976 	return error;
977 }
978 
979 static void
980 urtwn_write_1(struct urtwn_softc *sc, uint16_t addr, uint8_t val)
981 {
982 
983 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
984 	DPRINTFN(DBG_REG, "addr=%#jx, val=%#jx", addr, val, 0, 0);
985 
986 	urtwn_write_region_1(sc, addr, &val, 1);
987 }
988 
989 static void
990 urtwn_write_2(struct urtwn_softc *sc, uint16_t addr, uint16_t val)
991 {
992 	uint8_t buf[2];
993 
994 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
995 	DPRINTFN(DBG_REG, "addr=%#jx, val=%#jx", addr, val, 0, 0);
996 
997 	buf[0] = (uint8_t)val;
998 	buf[1] = (uint8_t)(val >> 8);
999 	urtwn_write_region_1(sc, addr, buf, 2);
1000 }
1001 
1002 static void
1003 urtwn_write_4(struct urtwn_softc *sc, uint16_t addr, uint32_t val)
1004 {
1005 	uint8_t buf[4];
1006 
1007 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1008 	DPRINTFN(DBG_REG, "addr=%#jx, val=%#jx", addr, val, 0, 0);
1009 
1010 	buf[0] = (uint8_t)val;
1011 	buf[1] = (uint8_t)(val >> 8);
1012 	buf[2] = (uint8_t)(val >> 16);
1013 	buf[3] = (uint8_t)(val >> 24);
1014 	urtwn_write_region_1(sc, addr, buf, 4);
1015 }
1016 
1017 static int
1018 urtwn_write_region(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf, int len)
1019 {
1020 
1021 	URTWNHIST_FUNC();
1022 	URTWNHIST_CALLARGS("addr=%#jx, len=%#jx", addr, len, 0, 0);
1023 
1024 	return urtwn_write_region_1(sc, addr, buf, len);
1025 }
1026 
1027 static int
1028 urtwn_read_region_1(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf,
1029     int len)
1030 {
1031 	usb_device_request_t req;
1032 	usbd_status error;
1033 
1034 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1035 
1036 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1037 	req.bRequest = R92C_REQ_REGS;
1038 	USETW(req.wValue, addr);
1039 	USETW(req.wIndex, 0);
1040 	USETW(req.wLength, len);
1041 	error = usbd_do_request(sc->sc_udev, &req, buf);
1042 	if (error != USBD_NORMAL_COMPLETION) {
1043 		DPRINTFN(DBG_REG, "error=%jd: addr=%#jx, len=%jd",
1044 		    error, addr, len, 0);
1045 	}
1046 	return error;
1047 }
1048 
1049 static uint8_t
1050 urtwn_read_1(struct urtwn_softc *sc, uint16_t addr)
1051 {
1052 	uint8_t val;
1053 
1054 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1055 
1056 	if (urtwn_read_region_1(sc, addr, &val, 1) != USBD_NORMAL_COMPLETION)
1057 		return 0xff;
1058 
1059 	DPRINTFN(DBG_REG, "addr=%#jx, val=%#jx", addr, val, 0, 0);
1060 	return val;
1061 }
1062 
1063 static uint16_t
1064 urtwn_read_2(struct urtwn_softc *sc, uint16_t addr)
1065 {
1066 	uint8_t buf[2];
1067 	uint16_t val;
1068 
1069 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1070 
1071 	if (urtwn_read_region_1(sc, addr, buf, 2) != USBD_NORMAL_COMPLETION)
1072 		return 0xffff;
1073 
1074 	val = LE_READ_2(&buf[0]);
1075 	DPRINTFN(DBG_REG, "addr=%#jx, val=%#jx", addr, val, 0, 0);
1076 	return val;
1077 }
1078 
1079 static uint32_t
1080 urtwn_read_4(struct urtwn_softc *sc, uint16_t addr)
1081 {
1082 	uint8_t buf[4];
1083 	uint32_t val;
1084 
1085 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1086 
1087 	if (urtwn_read_region_1(sc, addr, buf, 4) != USBD_NORMAL_COMPLETION)
1088 		return 0xffffffff;
1089 
1090 	val = LE_READ_4(&buf[0]);
1091 	DPRINTFN(DBG_REG, "addr=%#jx, val=%#jx", addr, val, 0, 0);
1092 	return val;
1093 }
1094 
1095 static int
1096 urtwn_fw_cmd(struct urtwn_softc *sc, uint8_t id, const void *buf, int len)
1097 {
1098 	struct r92c_fw_cmd cmd;
1099 	uint8_t *cp;
1100 	int fwcur;
1101 	int ntries;
1102 
1103 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1104 	DPRINTFN(DBG_REG, "id=%jd, buf=%#jx, len=%jd", id, (uintptr_t)buf, len, 0);
1105 
1106 	KASSERT(mutex_owned(&sc->sc_write_mtx));
1107 
1108 	mutex_enter(&sc->sc_fwcmd_mtx);
1109 	fwcur = sc->fwcur;
1110 	sc->fwcur = (sc->fwcur + 1) % R92C_H2C_NBOX;
1111 
1112 	/* Wait for current FW box to be empty. */
1113 	for (ntries = 0; ntries < 100; ntries++) {
1114 		if (!(urtwn_read_1(sc, R92C_HMETFR) & (1 << fwcur)))
1115 			break;
1116 		urtwn_delay_ms(sc, 2);
1117 	}
1118 	if (ntries == 100) {
1119 		aprint_error_dev(sc->sc_dev,
1120 		    "could not send firmware command %d\n", id);
1121 		mutex_exit(&sc->sc_fwcmd_mtx);
1122 		return ETIMEDOUT;
1123 	}
1124 
1125 	memset(&cmd, 0, sizeof(cmd));
1126 	KASSERT(len <= sizeof(cmd.msg));
1127 	memcpy(cmd.msg, buf, len);
1128 
1129 	/* Write the first word last since that will trigger the FW. */
1130 	cp = (uint8_t *)&cmd;
1131 	cmd.id = id;
1132 	if (len >= 4) {
1133 		if (!ISSET(sc->chip, URTWN_CHIP_92EU)) {
1134 			cmd.id |= R92C_CMD_FLAG_EXT;
1135 			urtwn_write_region(sc, R92C_HMEBOX_EXT(fwcur),
1136 			    &cp[1], 2);
1137 			urtwn_write_4(sc, R92C_HMEBOX(fwcur),
1138 			    cp[0] + (cp[3] << 8) + (cp[4] << 16) +
1139 			    ((uint32_t)cp[5] << 24));
1140 		} else {
1141 			urtwn_write_region(sc, R92E_HMEBOX_EXT(fwcur),
1142 			    &cp[4], 2);
1143 			urtwn_write_4(sc, R92C_HMEBOX(fwcur),
1144 			    cp[0] + (cp[1] << 8) + (cp[2] << 16) +
1145 			    ((uint32_t)cp[3] << 24));
1146 		}
1147 	} else {
1148 		urtwn_write_region(sc, R92C_HMEBOX(fwcur), cp, len);
1149 	}
1150 	mutex_exit(&sc->sc_fwcmd_mtx);
1151 
1152 	return 0;
1153 }
1154 
1155 static __inline void
1156 urtwn_rf_write(struct urtwn_softc *sc, int chain, uint8_t addr, uint32_t val)
1157 {
1158 
1159 	sc->sc_rf_write(sc, chain, addr, val);
1160 }
1161 
1162 static void
1163 urtwn_r92c_rf_write(struct urtwn_softc *sc, int chain, uint8_t addr,
1164     uint32_t val)
1165 {
1166 
1167 	urtwn_bb_write(sc, R92C_LSSI_PARAM(chain),
1168 	    SM(R92C_LSSI_PARAM_ADDR, addr) | SM(R92C_LSSI_PARAM_DATA, val));
1169 }
1170 
1171 static void
1172 urtwn_r88e_rf_write(struct urtwn_softc *sc, int chain, uint8_t addr,
1173     uint32_t val)
1174 {
1175 
1176 	urtwn_bb_write(sc, R92C_LSSI_PARAM(chain),
1177 	    SM(R88E_LSSI_PARAM_ADDR, addr) | SM(R92C_LSSI_PARAM_DATA, val));
1178 }
1179 
1180 static void
1181 urtwn_r92e_rf_write(struct urtwn_softc *sc, int chain, uint8_t addr,
1182     uint32_t val)
1183 {
1184 
1185 	urtwn_bb_write(sc, R92C_LSSI_PARAM(chain),
1186 	    SM(R88E_LSSI_PARAM_ADDR, addr) | SM(R92C_LSSI_PARAM_DATA, val));
1187 }
1188 
1189 static uint32_t
1190 urtwn_rf_read(struct urtwn_softc *sc, int chain, uint8_t addr)
1191 {
1192 	uint32_t reg[R92C_MAX_CHAINS], val;
1193 
1194 	reg[0] = urtwn_bb_read(sc, R92C_HSSI_PARAM2(0));
1195 	if (chain != 0) {
1196 		reg[chain] = urtwn_bb_read(sc, R92C_HSSI_PARAM2(chain));
1197 	}
1198 
1199 	urtwn_bb_write(sc, R92C_HSSI_PARAM2(0),
1200 	    reg[0] & ~R92C_HSSI_PARAM2_READ_EDGE);
1201 	urtwn_delay_ms(sc, 1);
1202 
1203 	urtwn_bb_write(sc, R92C_HSSI_PARAM2(chain),
1204 	    RW(reg[chain], R92C_HSSI_PARAM2_READ_ADDR, addr) |
1205 	    R92C_HSSI_PARAM2_READ_EDGE);
1206 	urtwn_delay_ms(sc, 1);
1207 
1208 	urtwn_bb_write(sc, R92C_HSSI_PARAM2(0),
1209 	    reg[0] | R92C_HSSI_PARAM2_READ_EDGE);
1210 	urtwn_delay_ms(sc, 1);
1211 
1212 	if (urtwn_bb_read(sc, R92C_HSSI_PARAM1(chain)) & R92C_HSSI_PARAM1_PI) {
1213 		val = urtwn_bb_read(sc, R92C_HSPI_READBACK(chain));
1214 	} else {
1215 		val = urtwn_bb_read(sc, R92C_LSSI_READBACK(chain));
1216 	}
1217 	return MS(val, R92C_LSSI_READBACK_DATA);
1218 }
1219 
1220 static int
1221 urtwn_llt_write(struct urtwn_softc *sc, uint32_t addr, uint32_t data)
1222 {
1223 	int ntries;
1224 
1225 	KASSERT(mutex_owned(&sc->sc_write_mtx));
1226 
1227 	urtwn_write_4(sc, R92C_LLT_INIT,
1228 	    SM(R92C_LLT_INIT_OP, R92C_LLT_INIT_OP_WRITE) |
1229 	    SM(R92C_LLT_INIT_ADDR, addr) |
1230 	    SM(R92C_LLT_INIT_DATA, data));
1231 	/* Wait for write operation to complete. */
1232 	for (ntries = 0; ntries < 20; ntries++) {
1233 		if (MS(urtwn_read_4(sc, R92C_LLT_INIT), R92C_LLT_INIT_OP) ==
1234 		    R92C_LLT_INIT_OP_NO_ACTIVE) {
1235 			/* Done */
1236 			return 0;
1237 		}
1238 		DELAY(5);
1239 	}
1240 	return ETIMEDOUT;
1241 }
1242 
1243 static uint8_t
1244 urtwn_efuse_read_1(struct urtwn_softc *sc, uint16_t addr)
1245 {
1246 	uint32_t reg;
1247 	int ntries;
1248 
1249 	KASSERT(mutex_owned(&sc->sc_write_mtx));
1250 
1251 	reg = urtwn_read_4(sc, R92C_EFUSE_CTRL);
1252 	reg = RW(reg, R92C_EFUSE_CTRL_ADDR, addr);
1253 	reg &= ~R92C_EFUSE_CTRL_VALID;
1254 	urtwn_write_4(sc, R92C_EFUSE_CTRL, reg);
1255 
1256 	/* Wait for read operation to complete. */
1257 	for (ntries = 0; ntries < 100; ntries++) {
1258 		reg = urtwn_read_4(sc, R92C_EFUSE_CTRL);
1259 		if (reg & R92C_EFUSE_CTRL_VALID) {
1260 			/* Done */
1261 			return MS(reg, R92C_EFUSE_CTRL_DATA);
1262 		}
1263 		DELAY(5);
1264 	}
1265 	aprint_error_dev(sc->sc_dev,
1266 	    "could not read efuse byte at address 0x%04x\n", addr);
1267 	return 0xff;
1268 }
1269 
1270 static void
1271 urtwn_efuse_read(struct urtwn_softc *sc)
1272 {
1273 	uint8_t *rom = (uint8_t *)&sc->rom;
1274 	uint32_t reg;
1275 	uint16_t addr = 0;
1276 	uint8_t off, msk;
1277 	size_t i;
1278 
1279 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1280 
1281 	KASSERT(mutex_owned(&sc->sc_write_mtx));
1282 
1283 	urtwn_efuse_switch_power(sc);
1284 
1285 	memset(&sc->rom, 0xff, sizeof(sc->rom));
1286 	while (addr < 512) {
1287 		reg = urtwn_efuse_read_1(sc, addr);
1288 		if (reg == 0xff)
1289 			break;
1290 		addr++;
1291 		off = reg >> 4;
1292 		msk = reg & 0xf;
1293 		for (i = 0; i < 4; i++) {
1294 			if (msk & (1U << i))
1295 				continue;
1296 
1297 			rom[off * 8 + i * 2 + 0] = urtwn_efuse_read_1(sc, addr);
1298 			addr++;
1299 			rom[off * 8 + i * 2 + 1] = urtwn_efuse_read_1(sc, addr);
1300 			addr++;
1301 		}
1302 	}
1303 #ifdef URTWN_DEBUG
1304 	/* Dump ROM content. */
1305 	for (i = 0; i < (int)sizeof(sc->rom); i++)
1306 		DPRINTFN(DBG_INIT, "%04jx: %02jx", i, rom[i], 0, 0);
1307 #endif
1308 }
1309 
1310 static void
1311 urtwn_efuse_switch_power(struct urtwn_softc *sc)
1312 {
1313 	uint32_t reg;
1314 
1315 	reg = urtwn_read_2(sc, R92C_SYS_ISO_CTRL);
1316 	if (!(reg & R92C_SYS_ISO_CTRL_PWC_EV12V)) {
1317 		urtwn_write_2(sc, R92C_SYS_ISO_CTRL,
1318 		    reg | R92C_SYS_ISO_CTRL_PWC_EV12V);
1319 	}
1320 	reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN);
1321 	if (!(reg & R92C_SYS_FUNC_EN_ELDR)) {
1322 		urtwn_write_2(sc, R92C_SYS_FUNC_EN,
1323 		    reg | R92C_SYS_FUNC_EN_ELDR);
1324 	}
1325 	reg = urtwn_read_2(sc, R92C_SYS_CLKR);
1326 	if ((reg & (R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M)) !=
1327 	    (R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M)) {
1328 		urtwn_write_2(sc, R92C_SYS_CLKR,
1329 		    reg | R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M);
1330 	}
1331 }
1332 
1333 static int
1334 urtwn_read_chipid(struct urtwn_softc *sc)
1335 {
1336 	uint32_t reg;
1337 
1338 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1339 
1340 	if (ISSET(sc->chip, URTWN_CHIP_88E) ||
1341 	    ISSET(sc->chip, URTWN_CHIP_92EU))
1342 		return 0;
1343 
1344 	reg = urtwn_read_4(sc, R92C_SYS_CFG);
1345 	if (reg & R92C_SYS_CFG_TRP_VAUX_EN) {
1346 		/* test chip, not supported */
1347 		return EIO;
1348 	}
1349 	if (reg & R92C_SYS_CFG_TYPE_92C) {
1350 		sc->chip |= URTWN_CHIP_92C;
1351 		/* Check if it is a castrated 8192C. */
1352 		if (MS(urtwn_read_4(sc, R92C_HPON_FSM),
1353 		    R92C_HPON_FSM_CHIP_BONDING_ID) ==
1354 		    R92C_HPON_FSM_CHIP_BONDING_ID_92C_1T2R) {
1355 			sc->chip |= URTWN_CHIP_92C_1T2R;
1356 		}
1357 	}
1358 	if (reg & R92C_SYS_CFG_VENDOR_UMC) {
1359 		sc->chip |= URTWN_CHIP_UMC;
1360 		if (MS(reg, R92C_SYS_CFG_CHIP_VER_RTL) == 0) {
1361 			sc->chip |= URTWN_CHIP_UMC_A_CUT;
1362 		}
1363 	}
1364 	return 0;
1365 }
1366 
1367 #ifdef URTWN_DEBUG
1368 static void
1369 urtwn_dump_rom(struct urtwn_softc *sc, struct r92c_rom *rp)
1370 {
1371 
1372 	aprint_normal_dev(sc->sc_dev,
1373 	    "id 0x%04x, dbg_sel %#x, vid %#x, pid %#x\n",
1374 	    rp->id, rp->dbg_sel, rp->vid, rp->pid);
1375 
1376 	aprint_normal_dev(sc->sc_dev,
1377 	    "usb_opt %#x, ep_setting %#x, usb_phy %#x\n",
1378 	    rp->usb_opt, rp->ep_setting, rp->usb_phy);
1379 
1380 	aprint_normal_dev(sc->sc_dev,
1381 	    "macaddr %s\n",
1382 	    ether_sprintf(rp->macaddr));
1383 
1384 	aprint_normal_dev(sc->sc_dev,
1385 	    "string %s, subcustomer_id %#x\n",
1386 	    rp->string, rp->subcustomer_id);
1387 
1388 	aprint_normal_dev(sc->sc_dev,
1389 	    "cck_tx_pwr c0: %d %d %d, c1: %d %d %d\n",
1390 	    rp->cck_tx_pwr[0][0], rp->cck_tx_pwr[0][1], rp->cck_tx_pwr[0][2],
1391 	    rp->cck_tx_pwr[1][0], rp->cck_tx_pwr[1][1], rp->cck_tx_pwr[1][2]);
1392 
1393 	aprint_normal_dev(sc->sc_dev,
1394 	    "ht40_1s_tx_pwr c0 %d %d %d, c1 %d %d %d\n",
1395 	    rp->ht40_1s_tx_pwr[0][0], rp->ht40_1s_tx_pwr[0][1],
1396 	    rp->ht40_1s_tx_pwr[0][2],
1397 	    rp->ht40_1s_tx_pwr[1][0], rp->ht40_1s_tx_pwr[1][1],
1398 	    rp->ht40_1s_tx_pwr[1][2]);
1399 
1400 	aprint_normal_dev(sc->sc_dev,
1401 	    "ht40_2s_tx_pwr_diff c0: %d %d %d, c1: %d %d %d\n",
1402 	    rp->ht40_2s_tx_pwr_diff[0] & 0xf, rp->ht40_2s_tx_pwr_diff[1] & 0xf,
1403 	    rp->ht40_2s_tx_pwr_diff[2] & 0xf,
1404 	    rp->ht40_2s_tx_pwr_diff[0] >> 4, rp->ht40_2s_tx_pwr_diff[1] & 0xf,
1405 	    rp->ht40_2s_tx_pwr_diff[2] >> 4);
1406 
1407 	aprint_normal_dev(sc->sc_dev,
1408 	    "ht20_tx_pwr_diff c0: %d %d %d, c1: %d %d %d\n",
1409 	    rp->ht20_tx_pwr_diff[0] & 0xf, rp->ht20_tx_pwr_diff[1] & 0xf,
1410 	    rp->ht20_tx_pwr_diff[2] & 0xf,
1411 	    rp->ht20_tx_pwr_diff[0] >> 4, rp->ht20_tx_pwr_diff[1] >> 4,
1412 	    rp->ht20_tx_pwr_diff[2] >> 4);
1413 
1414 	aprint_normal_dev(sc->sc_dev,
1415 	    "ofdm_tx_pwr_diff c0: %d %d %d, c1: %d %d %d\n",
1416 	    rp->ofdm_tx_pwr_diff[0] & 0xf, rp->ofdm_tx_pwr_diff[1] & 0xf,
1417 	    rp->ofdm_tx_pwr_diff[2] & 0xf,
1418 	    rp->ofdm_tx_pwr_diff[0] >> 4, rp->ofdm_tx_pwr_diff[1] >> 4,
1419 	    rp->ofdm_tx_pwr_diff[2] >> 4);
1420 
1421 	aprint_normal_dev(sc->sc_dev,
1422 	    "ht40_max_pwr_offset c0: %d %d %d, c1: %d %d %d\n",
1423 	    rp->ht40_max_pwr[0] & 0xf, rp->ht40_max_pwr[1] & 0xf,
1424 	    rp->ht40_max_pwr[2] & 0xf,
1425 	    rp->ht40_max_pwr[0] >> 4, rp->ht40_max_pwr[1] >> 4,
1426 	    rp->ht40_max_pwr[2] >> 4);
1427 
1428 	aprint_normal_dev(sc->sc_dev,
1429 	    "ht20_max_pwr_offset c0: %d %d %d, c1: %d %d %d\n",
1430 	    rp->ht20_max_pwr[0] & 0xf, rp->ht20_max_pwr[1] & 0xf,
1431 	    rp->ht20_max_pwr[2] & 0xf,
1432 	    rp->ht20_max_pwr[0] >> 4, rp->ht20_max_pwr[1] >> 4,
1433 	    rp->ht20_max_pwr[2] >> 4);
1434 
1435 	aprint_normal_dev(sc->sc_dev,
1436 	    "xtal_calib %d, tssi %d %d, thermal %d\n",
1437 	    rp->xtal_calib, rp->tssi[0], rp->tssi[1], rp->thermal_meter);
1438 
1439 	aprint_normal_dev(sc->sc_dev,
1440 	    "rf_opt1 %#x, rf_opt2 %#x, rf_opt3 %#x, rf_opt4 %#x\n",
1441 	    rp->rf_opt1, rp->rf_opt2, rp->rf_opt3, rp->rf_opt4);
1442 
1443 	aprint_normal_dev(sc->sc_dev,
1444 	    "channnel_plan %d, version %d customer_id %#x\n",
1445 	    rp->channel_plan, rp->version, rp->curstomer_id);
1446 }
1447 #endif
1448 
1449 static void
1450 urtwn_read_rom(struct urtwn_softc *sc)
1451 {
1452 	struct ieee80211com *ic = &sc->sc_ic;
1453 	struct r92c_rom *rom = &sc->rom;
1454 
1455 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1456 
1457 	mutex_enter(&sc->sc_write_mtx);
1458 
1459 	/* Read full ROM image. */
1460 	urtwn_efuse_read(sc);
1461 #ifdef URTWN_DEBUG
1462 	if (urtwn_debug & DBG_REG)
1463 		urtwn_dump_rom(sc, rom);
1464 #endif
1465 
1466 	/* XXX Weird but this is what the vendor driver does. */
1467 	sc->pa_setting = urtwn_efuse_read_1(sc, 0x1fa);
1468 	sc->board_type = MS(rom->rf_opt1, R92C_ROM_RF1_BOARD_TYPE);
1469 	sc->regulatory = MS(rom->rf_opt1, R92C_ROM_RF1_REGULATORY);
1470 
1471 	DPRINTFN(DBG_INIT,
1472 	    "PA setting=%#jx, board=%#jx, regulatory=%jd",
1473 	    sc->pa_setting, sc->board_type, sc->regulatory, 0);
1474 
1475 	IEEE80211_ADDR_COPY(ic->ic_myaddr, rom->macaddr);
1476 
1477 	sc->sc_rf_write = urtwn_r92c_rf_write;
1478 	sc->sc_power_on = urtwn_r92c_power_on;
1479 	sc->sc_dma_init = urtwn_r92c_dma_init;
1480 
1481 	mutex_exit(&sc->sc_write_mtx);
1482 }
1483 
1484 static void
1485 urtwn_r88e_read_rom(struct urtwn_softc *sc)
1486 {
1487 	struct ieee80211com *ic = &sc->sc_ic;
1488 	uint8_t *rom = sc->r88e_rom;
1489 	uint32_t reg;
1490 	uint16_t addr = 0;
1491 	uint8_t off, msk, tmp;
1492 	int i;
1493 
1494 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1495 
1496 	mutex_enter(&sc->sc_write_mtx);
1497 
1498 	off = 0;
1499 	urtwn_efuse_switch_power(sc);
1500 
1501 	/* Read full ROM image. */
1502 	memset(&sc->r88e_rom, 0xff, sizeof(sc->r88e_rom));
1503 	while (addr < 4096) {
1504 		reg = urtwn_efuse_read_1(sc, addr);
1505 		if (reg == 0xff)
1506 			break;
1507 		addr++;
1508 		if ((reg & 0x1f) == 0x0f) {
1509 			tmp = (reg & 0xe0) >> 5;
1510 			reg = urtwn_efuse_read_1(sc, addr);
1511 			if ((reg & 0x0f) != 0x0f)
1512 				off = ((reg & 0xf0) >> 1) | tmp;
1513 			addr++;
1514 		} else
1515 			off = reg >> 4;
1516 		msk = reg & 0xf;
1517 		for (i = 0; i < 4; i++) {
1518 			if (msk & (1 << i))
1519 				continue;
1520 			rom[off * 8 + i * 2 + 0] = urtwn_efuse_read_1(sc, addr);
1521 			addr++;
1522 			rom[off * 8 + i * 2 + 1] = urtwn_efuse_read_1(sc, addr);
1523 			addr++;
1524 		}
1525 	}
1526 #ifdef URTWN_DEBUG
1527 	if (urtwn_debug & DBG_REG) {
1528 	}
1529 #endif
1530 
1531 	addr = 0x10;
1532 	for (i = 0; i < 6; i++)
1533 		sc->cck_tx_pwr[i] = sc->r88e_rom[addr++];
1534 	for (i = 0; i < 5; i++)
1535 		sc->ht40_tx_pwr[i] = sc->r88e_rom[addr++];
1536 	sc->bw20_tx_pwr_diff = (sc->r88e_rom[addr] & 0xf0) >> 4;
1537 	if (sc->bw20_tx_pwr_diff & 0x08)
1538 		sc->bw20_tx_pwr_diff |= 0xf0;
1539 	sc->ofdm_tx_pwr_diff = (sc->r88e_rom[addr] & 0xf);
1540 	if (sc->ofdm_tx_pwr_diff & 0x08)
1541 		sc->ofdm_tx_pwr_diff |= 0xf0;
1542 	sc->regulatory = MS(sc->r88e_rom[0xc1], R92C_ROM_RF1_REGULATORY);
1543 
1544 	IEEE80211_ADDR_COPY(ic->ic_myaddr, &sc->r88e_rom[0xd7]);
1545 
1546 	if (ISSET(sc->chip, URTWN_CHIP_92EU)) {
1547 		sc->sc_power_on = urtwn_r92e_power_on;
1548 		sc->sc_rf_write = urtwn_r92e_rf_write;
1549 	} else {
1550 		sc->sc_power_on = urtwn_r88e_power_on;
1551 		sc->sc_rf_write = urtwn_r88e_rf_write;
1552 	}
1553 	sc->sc_dma_init = urtwn_r88e_dma_init;
1554 
1555 	mutex_exit(&sc->sc_write_mtx);
1556 }
1557 
1558 static int
1559 urtwn_media_change(struct ifnet *ifp)
1560 {
1561 	int error;
1562 
1563 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1564 
1565 	if ((error = ieee80211_media_change(ifp)) != ENETRESET)
1566 		return error;
1567 
1568 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1569 	    (IFF_UP | IFF_RUNNING)) {
1570 		urtwn_init(ifp);
1571 	}
1572 	return 0;
1573 }
1574 
1575 /*
1576  * Initialize rate adaptation in firmware.
1577  */
1578 static int __noinline
1579 urtwn_ra_init(struct urtwn_softc *sc)
1580 {
1581 	static const uint8_t map[] = {
1582 		2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108
1583 	};
1584 	struct ieee80211com *ic = &sc->sc_ic;
1585 	struct ieee80211_node *ni = ic->ic_bss;
1586 	struct ieee80211_rateset *rs = &ni->ni_rates;
1587 	struct r92c_fw_cmd_macid_cfg cmd;
1588 	uint32_t rates, basicrates;
1589 	uint32_t rrsr_mask, rrsr_rate;
1590 	uint8_t mode;
1591 	size_t maxrate, maxbasicrate, i, j;
1592 	int error;
1593 
1594 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1595 
1596 	KASSERT(mutex_owned(&sc->sc_write_mtx));
1597 
1598 	/* Get normal and basic rates mask. */
1599 	rates = basicrates = 1;
1600 	maxrate = maxbasicrate = 0;
1601 	for (i = 0; i < rs->rs_nrates; i++) {
1602 		/* Convert 802.11 rate to HW rate index. */
1603 		for (j = 0; j < __arraycount(map); j++) {
1604 			if ((rs->rs_rates[i] & IEEE80211_RATE_VAL) == map[j]) {
1605 				break;
1606 			}
1607 		}
1608 		if (j == __arraycount(map)) {
1609 			/* Unknown rate, skip. */
1610 			continue;
1611 		}
1612 
1613 		rates |= 1U << j;
1614 		if (j > maxrate) {
1615 			maxrate = j;
1616 		}
1617 
1618 		if (rs->rs_rates[i] & IEEE80211_RATE_BASIC) {
1619 			basicrates |= 1U << j;
1620 			if (j > maxbasicrate) {
1621 				maxbasicrate = j;
1622 			}
1623 		}
1624 	}
1625 	if (ic->ic_curmode == IEEE80211_MODE_11B) {
1626 		mode = R92C_RAID_11B;
1627 	} else {
1628 		mode = R92C_RAID_11BG;
1629 	}
1630 	DPRINTFN(DBG_INIT, "mode=%#jx", mode, 0, 0, 0);
1631 	DPRINTFN(DBG_INIT, "rates=%#jx, basicrates=%#jx, "
1632 	    "maxrate=%jx, maxbasicrate=%jx",
1633 	    rates, basicrates, maxrate, maxbasicrate);
1634 
1635 	if (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) {
1636 		maxbasicrate |= R92C_RATE_SHORTGI;
1637 		maxrate |= R92C_RATE_SHORTGI;
1638 	}
1639 
1640 	/* Set rates mask for group addressed frames. */
1641 	cmd.macid = RTWN_MACID_BC | RTWN_MACID_VALID;
1642 	if (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)
1643 		cmd.macid |= RTWN_MACID_SHORTGI;
1644 	cmd.mask = htole32((mode << 28) | basicrates);
1645 	error = urtwn_fw_cmd(sc, R92C_CMD_MACID_CONFIG, &cmd, sizeof(cmd));
1646 	if (error != 0) {
1647 		aprint_error_dev(sc->sc_dev,
1648 		    "could not add broadcast station\n");
1649 		return error;
1650 	}
1651 	/* Set initial MRR rate. */
1652 	DPRINTFN(DBG_INIT, "maxbasicrate=%jd", maxbasicrate, 0, 0, 0);
1653 	urtwn_write_1(sc, R92C_INIDATA_RATE_SEL(RTWN_MACID_BC), maxbasicrate);
1654 
1655 	/* Set rates mask for unicast frames. */
1656 	cmd.macid = RTWN_MACID_BSS | RTWN_MACID_VALID;
1657 	if (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)
1658 		cmd.macid |= RTWN_MACID_SHORTGI;
1659 	cmd.mask = htole32((mode << 28) | rates);
1660 	error = urtwn_fw_cmd(sc, R92C_CMD_MACID_CONFIG, &cmd, sizeof(cmd));
1661 	if (error != 0) {
1662 		aprint_error_dev(sc->sc_dev, "could not add BSS station\n");
1663 		return error;
1664 	}
1665 	/* Set initial MRR rate. */
1666 	DPRINTFN(DBG_INIT, "maxrate=%jd", maxrate, 0, 0, 0);
1667 	urtwn_write_1(sc, R92C_INIDATA_RATE_SEL(RTWN_MACID_BSS), maxrate);
1668 
1669 	rrsr_rate = ic->ic_fixed_rate;
1670 	if (rrsr_rate == -1)
1671 		rrsr_rate = 11;
1672 
1673 	rrsr_mask = 0xffff >> (15 - rrsr_rate);
1674 	urtwn_write_2(sc, R92C_RRSR, rrsr_mask);
1675 
1676 	/* Indicate highest supported rate. */
1677 	ni->ni_txrate = rs->rs_nrates - 1;
1678 
1679 	return 0;
1680 }
1681 
1682 static int
1683 urtwn_get_nettype(struct urtwn_softc *sc)
1684 {
1685 	struct ieee80211com *ic = &sc->sc_ic;
1686 	int type;
1687 
1688 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1689 
1690 	switch (ic->ic_opmode) {
1691 	case IEEE80211_M_STA:
1692 		type = R92C_CR_NETTYPE_INFRA;
1693 		break;
1694 
1695 	case IEEE80211_M_IBSS:
1696 		type = R92C_CR_NETTYPE_ADHOC;
1697 		break;
1698 
1699 	default:
1700 		type = R92C_CR_NETTYPE_NOLINK;
1701 		break;
1702 	}
1703 
1704 	return type;
1705 }
1706 
1707 static void
1708 urtwn_set_nettype0_msr(struct urtwn_softc *sc, uint8_t type)
1709 {
1710 	uint8_t	reg;
1711 
1712 	URTWNHIST_FUNC();
1713 	URTWNHIST_CALLARGS("type=%jd", type, 0, 0, 0);
1714 
1715 	KASSERT(mutex_owned(&sc->sc_write_mtx));
1716 
1717 	reg = urtwn_read_1(sc, R92C_CR + 2) & 0x0c;
1718 	urtwn_write_1(sc, R92C_CR + 2, reg | type);
1719 }
1720 
1721 static void
1722 urtwn_tsf_sync_enable(struct urtwn_softc *sc)
1723 {
1724 	struct ieee80211_node *ni = sc->sc_ic.ic_bss;
1725 	uint64_t tsf;
1726 
1727 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1728 
1729 	KASSERT(mutex_owned(&sc->sc_write_mtx));
1730 
1731 	/* Enable TSF synchronization. */
1732 	urtwn_write_1(sc, R92C_BCN_CTRL,
1733 	    urtwn_read_1(sc, R92C_BCN_CTRL) & ~R92C_BCN_CTRL_DIS_TSF_UDT0);
1734 
1735 	/* Correct TSF */
1736 	urtwn_write_1(sc, R92C_BCN_CTRL,
1737 	    urtwn_read_1(sc, R92C_BCN_CTRL) & ~R92C_BCN_CTRL_EN_BCN);
1738 
1739 	/* Set initial TSF. */
1740 	tsf = ni->ni_tstamp.tsf;
1741 	tsf = le64toh(tsf);
1742 	tsf = tsf - (tsf % (ni->ni_intval * IEEE80211_DUR_TU));
1743 	tsf -= IEEE80211_DUR_TU;
1744 	urtwn_write_4(sc, R92C_TSFTR + 0, (uint32_t)tsf);
1745 	urtwn_write_4(sc, R92C_TSFTR + 4, (uint32_t)(tsf >> 32));
1746 
1747 	urtwn_write_1(sc, R92C_BCN_CTRL,
1748 	    urtwn_read_1(sc, R92C_BCN_CTRL) | R92C_BCN_CTRL_EN_BCN);
1749 }
1750 
1751 static void
1752 urtwn_set_led(struct urtwn_softc *sc, int led, int on)
1753 {
1754 	uint8_t reg;
1755 
1756 	URTWNHIST_FUNC();
1757 	URTWNHIST_CALLARGS("led=%jd, on=%jd", led, on, 0, 0);
1758 
1759 	KASSERT(mutex_owned(&sc->sc_write_mtx));
1760 
1761 	if (led == URTWN_LED_LINK) {
1762 		if (ISSET(sc->chip, URTWN_CHIP_92EU)) {
1763 			urtwn_write_1(sc, 0x64, urtwn_read_1(sc, 0x64) & 0xfe);
1764 			reg = urtwn_read_1(sc, R92C_LEDCFG1) & R92E_LEDSON;
1765 			urtwn_write_1(sc, R92C_LEDCFG1, reg |
1766 			    (R92C_LEDCFG0_DIS << 1));
1767 			if (on) {
1768 				reg = urtwn_read_1(sc, R92C_LEDCFG1) &
1769 				    R92E_LEDSON;
1770 				urtwn_write_1(sc, R92C_LEDCFG1, reg);
1771 			}
1772 		} else if (ISSET(sc->chip, URTWN_CHIP_88E)) {
1773 			reg = urtwn_read_1(sc, R92C_LEDCFG2) & 0xf0;
1774 			urtwn_write_1(sc, R92C_LEDCFG2, reg | 0x60);
1775 			if (!on) {
1776 				reg = urtwn_read_1(sc, R92C_LEDCFG2) & 0x90;
1777 				urtwn_write_1(sc, R92C_LEDCFG2,
1778 				    reg | R92C_LEDCFG0_DIS);
1779 				reg = urtwn_read_1(sc, R92C_MAC_PINMUX_CFG);
1780 				urtwn_write_1(sc, R92C_MAC_PINMUX_CFG,
1781 				    reg & 0xfe);
1782 			}
1783 		} else {
1784 			reg = urtwn_read_1(sc, R92C_LEDCFG0) & 0x70;
1785 			if (!on) {
1786 				reg |= R92C_LEDCFG0_DIS;
1787 			}
1788 			urtwn_write_1(sc, R92C_LEDCFG0, reg);
1789 		}
1790 		sc->ledlink = on;	/* Save LED state. */
1791 	}
1792 }
1793 
1794 static void
1795 urtwn_calib_to(void *arg)
1796 {
1797 	struct urtwn_softc *sc = arg;
1798 
1799 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1800 
1801 	if (sc->sc_dying)
1802 		return;
1803 
1804 	/* Do it in a process context. */
1805 	urtwn_do_async(sc, urtwn_calib_to_cb, NULL, 0);
1806 }
1807 
1808 /* ARGSUSED */
1809 static void
1810 urtwn_calib_to_cb(struct urtwn_softc *sc, void *arg)
1811 {
1812 	struct r92c_fw_cmd_rssi cmd;
1813 	struct r92e_fw_cmd_rssi cmde;
1814 
1815 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1816 
1817 	if (sc->sc_ic.ic_state != IEEE80211_S_RUN)
1818 		goto restart_timer;
1819 
1820 	mutex_enter(&sc->sc_write_mtx);
1821 	if (sc->avg_pwdb != -1) {
1822 		/* Indicate Rx signal strength to FW for rate adaptation. */
1823 		memset(&cmd, 0, sizeof(cmd));
1824 		memset(&cmde, 0, sizeof(cmde));
1825 		cmd.macid = 0;	/* BSS. */
1826 		cmde.macid = 0;	/* BSS. */
1827 		cmd.pwdb = sc->avg_pwdb;
1828 		cmde.pwdb = sc->avg_pwdb;
1829 		DPRINTFN(DBG_RF, "sending RSSI command avg=%jd",
1830 		    sc->avg_pwdb, 0, 0, 0);
1831 		if (!ISSET(sc->chip, URTWN_CHIP_92EU)) {
1832 			urtwn_fw_cmd(sc, R92C_CMD_RSSI_SETTING, &cmd,
1833 			    sizeof(cmd));
1834 		} else {
1835 			urtwn_fw_cmd(sc, R92E_CMD_RSSI_REPORT, &cmde,
1836 			    sizeof(cmde));
1837 		}
1838 	}
1839 
1840 	/* Do temperature compensation. */
1841 	urtwn_temp_calib(sc);
1842 	mutex_exit(&sc->sc_write_mtx);
1843 
1844  restart_timer:
1845 	if (!sc->sc_dying) {
1846 		/* Restart calibration timer. */
1847 		callout_schedule(&sc->sc_calib_to, hz);
1848 	}
1849 }
1850 
1851 static void
1852 urtwn_next_scan(void *arg)
1853 {
1854 	struct urtwn_softc *sc = arg;
1855 	int s;
1856 
1857 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1858 
1859 	if (sc->sc_dying)
1860 		return;
1861 
1862 	s = splnet();
1863 	if (sc->sc_ic.ic_state == IEEE80211_S_SCAN)
1864 		ieee80211_next_scan(&sc->sc_ic);
1865 	splx(s);
1866 }
1867 
1868 static void
1869 urtwn_newassoc(struct ieee80211_node *ni, int isnew)
1870 {
1871 	URTWNHIST_FUNC();
1872 	URTWNHIST_CALLARGS("new node %06jx%06jx",
1873 	    ni->ni_macaddr[0] << 2 |
1874 	    ni->ni_macaddr[1] << 1 |
1875 	    ni->ni_macaddr[2],
1876 	    ni->ni_macaddr[3] << 2 |
1877 	    ni->ni_macaddr[4] << 1 |
1878 	    ni->ni_macaddr[5],
1879 	    0, 0);
1880 	/* start with lowest Tx rate */
1881 	ni->ni_txrate = 0;
1882 }
1883 
1884 static int
1885 urtwn_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
1886 {
1887 	struct urtwn_softc *sc = ic->ic_ifp->if_softc;
1888 	struct urtwn_cmd_newstate cmd;
1889 
1890 	URTWNHIST_FUNC();
1891 	URTWNHIST_CALLARGS("nstate=%jd, arg=%jd", nstate, arg, 0, 0);
1892 
1893 	callout_stop(&sc->sc_scan_to);
1894 	callout_stop(&sc->sc_calib_to);
1895 
1896 	/* Do it in a process context. */
1897 	cmd.state = nstate;
1898 	cmd.arg = arg;
1899 	urtwn_do_async(sc, urtwn_newstate_cb, &cmd, sizeof(cmd));
1900 	return 0;
1901 }
1902 
1903 static void
1904 urtwn_newstate_cb(struct urtwn_softc *sc, void *arg)
1905 {
1906 	struct urtwn_cmd_newstate *cmd = arg;
1907 	struct ieee80211com *ic = &sc->sc_ic;
1908 	struct ieee80211_node *ni;
1909 	enum ieee80211_state ostate = ic->ic_state;
1910 	enum ieee80211_state nstate = cmd->state;
1911 	uint32_t reg;
1912 	uint8_t sifs_time, msr;
1913 	int s;
1914 
1915 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
1916 	DPRINTFN(DBG_STM, "%jd->%jd", ostate, nstate, 0, 0);
1917 
1918 	s = splnet();
1919 	mutex_enter(&sc->sc_write_mtx);
1920 
1921 	callout_stop(&sc->sc_scan_to);
1922 	callout_stop(&sc->sc_calib_to);
1923 
1924 	switch (ostate) {
1925 	case IEEE80211_S_INIT:
1926 		break;
1927 
1928 	case IEEE80211_S_SCAN:
1929 		if (nstate != IEEE80211_S_SCAN) {
1930 			/*
1931 			 * End of scanning
1932 			 */
1933 			/* flush 4-AC Queue after site_survey */
1934 			urtwn_write_1(sc, R92C_TXPAUSE, 0x0);
1935 
1936 			/* Allow Rx from our BSSID only. */
1937 			urtwn_write_4(sc, R92C_RCR,
1938 			    urtwn_read_4(sc, R92C_RCR) |
1939 			      R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN);
1940 		}
1941 		break;
1942 
1943 	case IEEE80211_S_AUTH:
1944 	case IEEE80211_S_ASSOC:
1945 		break;
1946 
1947 	case IEEE80211_S_RUN:
1948 		/* Turn link LED off. */
1949 		urtwn_set_led(sc, URTWN_LED_LINK, 0);
1950 
1951 		/* Set media status to 'No Link'. */
1952 		urtwn_set_nettype0_msr(sc, R92C_CR_NETTYPE_NOLINK);
1953 
1954 		/* Stop Rx of data frames. */
1955 		urtwn_write_2(sc, R92C_RXFLTMAP2, 0);
1956 
1957 		/* Reset TSF. */
1958 		urtwn_write_1(sc, R92C_DUAL_TSF_RST, 0x03);
1959 
1960 		/* Disable TSF synchronization. */
1961 		urtwn_write_1(sc, R92C_BCN_CTRL,
1962 		    urtwn_read_1(sc, R92C_BCN_CTRL) |
1963 		      R92C_BCN_CTRL_DIS_TSF_UDT0);
1964 
1965 		/* Back to 20MHz mode */
1966 		urtwn_set_chan(sc, ic->ic_curchan,
1967 		    IEEE80211_HTINFO_2NDCHAN_NONE);
1968 
1969 		if (ic->ic_opmode == IEEE80211_M_IBSS ||
1970 		    ic->ic_opmode == IEEE80211_M_HOSTAP) {
1971 			/* Stop BCN */
1972 			urtwn_write_1(sc, R92C_BCN_CTRL,
1973 			    urtwn_read_1(sc, R92C_BCN_CTRL) &
1974 			    ~(R92C_BCN_CTRL_EN_BCN | R92C_BCN_CTRL_TXBCN_RPT));
1975 		}
1976 
1977 		/* Reset EDCA parameters. */
1978 		urtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002f3217);
1979 		urtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005e4317);
1980 		urtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x00105320);
1981 		urtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a444);
1982 
1983 		/* flush all cam entries */
1984 		urtwn_cam_init(sc);
1985 		break;
1986 	}
1987 
1988 	switch (nstate) {
1989 	case IEEE80211_S_INIT:
1990 		/* Turn link LED off. */
1991 		urtwn_set_led(sc, URTWN_LED_LINK, 0);
1992 		break;
1993 
1994 	case IEEE80211_S_SCAN:
1995 		if (ostate != IEEE80211_S_SCAN) {
1996 			/*
1997 			 * Begin of scanning
1998 			 */
1999 
2000 			/* Set gain for scanning. */
2001 			reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(0));
2002 			reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x20);
2003 			urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), reg);
2004 
2005 			if (!ISSET(sc->chip, URTWN_CHIP_88E)) {
2006 				reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(1));
2007 				reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x20);
2008 				urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(1), reg);
2009 			}
2010 
2011 			/* Set media status to 'No Link'. */
2012 			urtwn_set_nettype0_msr(sc, R92C_CR_NETTYPE_NOLINK);
2013 
2014 			/* Allow Rx from any BSSID. */
2015 			urtwn_write_4(sc, R92C_RCR,
2016 			    urtwn_read_4(sc, R92C_RCR) &
2017 			    ~(R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN));
2018 
2019 			/* Stop Rx of data frames. */
2020 			urtwn_write_2(sc, R92C_RXFLTMAP2, 0);
2021 
2022 			/* Disable update TSF */
2023 			urtwn_write_1(sc, R92C_BCN_CTRL,
2024 			    urtwn_read_1(sc, R92C_BCN_CTRL) |
2025 			      R92C_BCN_CTRL_DIS_TSF_UDT0);
2026 		}
2027 
2028 		/* Make link LED blink during scan. */
2029 		urtwn_set_led(sc, URTWN_LED_LINK, !sc->ledlink);
2030 
2031 		/* Pause AC Tx queues. */
2032 		urtwn_write_1(sc, R92C_TXPAUSE,
2033 		    urtwn_read_1(sc, R92C_TXPAUSE) | 0x0f);
2034 
2035 		urtwn_set_chan(sc, ic->ic_curchan,
2036 		    IEEE80211_HTINFO_2NDCHAN_NONE);
2037 
2038 		/* Start periodic scan. */
2039 		if (!sc->sc_dying)
2040 			callout_schedule(&sc->sc_scan_to, hz / 5);
2041 		break;
2042 
2043 	case IEEE80211_S_AUTH:
2044 		/* Set initial gain under link. */
2045 		reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(0));
2046 		reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x32);
2047 		urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), reg);
2048 
2049 		if (!ISSET(sc->chip, URTWN_CHIP_88E)) {
2050 			reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(1));
2051 			reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x32);
2052 			urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(1), reg);
2053 		}
2054 
2055 		/* Set media status to 'No Link'. */
2056 		urtwn_set_nettype0_msr(sc, R92C_CR_NETTYPE_NOLINK);
2057 
2058 		/* Allow Rx from any BSSID. */
2059 		urtwn_write_4(sc, R92C_RCR,
2060 		    urtwn_read_4(sc, R92C_RCR) &
2061 		      ~(R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN));
2062 
2063 		urtwn_set_chan(sc, ic->ic_curchan,
2064 		    IEEE80211_HTINFO_2NDCHAN_NONE);
2065 		break;
2066 
2067 	case IEEE80211_S_ASSOC:
2068 		break;
2069 
2070 	case IEEE80211_S_RUN:
2071 		ni = ic->ic_bss;
2072 
2073 		/* XXX: Set 20MHz mode */
2074 		urtwn_set_chan(sc, ic->ic_curchan,
2075 		    IEEE80211_HTINFO_2NDCHAN_NONE);
2076 
2077 		if (ic->ic_opmode == IEEE80211_M_MONITOR) {
2078 			/* Back to 20MHz mode */
2079 			urtwn_set_chan(sc, ic->ic_curchan,
2080 			    IEEE80211_HTINFO_2NDCHAN_NONE);
2081 
2082 			/* Set media status to 'No Link'. */
2083 			urtwn_set_nettype0_msr(sc, R92C_CR_NETTYPE_NOLINK);
2084 
2085 			/* Enable Rx of data frames. */
2086 			urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
2087 
2088 			/* Allow Rx from any BSSID. */
2089 			urtwn_write_4(sc, R92C_RCR,
2090 			    urtwn_read_4(sc, R92C_RCR) &
2091 			    ~(R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN));
2092 
2093 			/* Accept Rx data/control/management frames */
2094 			urtwn_write_4(sc, R92C_RCR,
2095 			    urtwn_read_4(sc, R92C_RCR) |
2096 			    R92C_RCR_ADF | R92C_RCR_ACF | R92C_RCR_AMF);
2097 
2098 			/* Turn link LED on. */
2099 			urtwn_set_led(sc, URTWN_LED_LINK, 1);
2100 			break;
2101 		}
2102 
2103 		/* Set media status to 'Associated'. */
2104 		urtwn_set_nettype0_msr(sc, urtwn_get_nettype(sc));
2105 
2106 		/* Set BSSID. */
2107 		urtwn_write_4(sc, R92C_BSSID + 0, LE_READ_4(&ni->ni_bssid[0]));
2108 		urtwn_write_4(sc, R92C_BSSID + 4, LE_READ_2(&ni->ni_bssid[4]));
2109 
2110 		if (ic->ic_curmode == IEEE80211_MODE_11B) {
2111 			urtwn_write_1(sc, R92C_INIRTS_RATE_SEL, 0);
2112 		} else {
2113 			/* 802.11b/g */
2114 			urtwn_write_1(sc, R92C_INIRTS_RATE_SEL, 3);
2115 		}
2116 
2117 		/* Enable Rx of data frames. */
2118 		urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
2119 
2120 		/* Set beacon interval. */
2121 		urtwn_write_2(sc, R92C_BCN_INTERVAL, ni->ni_intval);
2122 
2123 		msr = urtwn_read_1(sc, R92C_MSR);
2124 		msr &= R92C_MSR_MASK;
2125 		switch (ic->ic_opmode) {
2126 		case IEEE80211_M_STA:
2127 			/* Allow Rx from our BSSID only. */
2128 			urtwn_write_4(sc, R92C_RCR,
2129 			    urtwn_read_4(sc, R92C_RCR) |
2130 			      R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN);
2131 
2132 			/* Enable TSF synchronization. */
2133 			urtwn_tsf_sync_enable(sc);
2134 
2135 			msr |= R92C_MSR_INFRA;
2136 			break;
2137 		case IEEE80211_M_HOSTAP:
2138 			urtwn_write_2(sc, R92C_BCNTCFG, 0x000f);
2139 
2140 			/* Allow Rx from any BSSID. */
2141 			urtwn_write_4(sc, R92C_RCR,
2142 			    urtwn_read_4(sc, R92C_RCR) &
2143 			    ~(R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN));
2144 
2145 			/* Reset TSF timer to zero. */
2146 			reg = urtwn_read_4(sc, R92C_TCR);
2147 			reg &= ~0x01;
2148 			urtwn_write_4(sc, R92C_TCR, reg);
2149 			reg |= 0x01;
2150 			urtwn_write_4(sc, R92C_TCR, reg);
2151 
2152 			msr |= R92C_MSR_AP;
2153 			break;
2154 		default:
2155 			msr |= R92C_MSR_ADHOC;
2156 			break;
2157 		}
2158 		urtwn_write_1(sc, R92C_MSR, msr);
2159 
2160 		sifs_time = 10;
2161 		urtwn_write_1(sc, R92C_SIFS_CCK + 1, sifs_time);
2162 		urtwn_write_1(sc, R92C_SIFS_OFDM + 1, sifs_time);
2163 		urtwn_write_1(sc, R92C_SPEC_SIFS + 1, sifs_time);
2164 		urtwn_write_1(sc, R92C_MAC_SPEC_SIFS + 1, sifs_time);
2165 		urtwn_write_1(sc, R92C_R2T_SIFS + 1, sifs_time);
2166 		urtwn_write_1(sc, R92C_T2T_SIFS + 1, sifs_time);
2167 
2168 		/* Initialize rate adaptation. */
2169 		if (ISSET(sc->chip, URTWN_CHIP_88E) ||
2170 		    ISSET(sc->chip, URTWN_CHIP_92EU))
2171 			ni->ni_txrate = ni->ni_rates.rs_nrates - 1;
2172 		else
2173 			urtwn_ra_init(sc);
2174 
2175 		/* Turn link LED on. */
2176 		urtwn_set_led(sc, URTWN_LED_LINK, 1);
2177 
2178 		/* Reset average RSSI. */
2179 		sc->avg_pwdb = -1;
2180 
2181 		/* Reset temperature calibration state machine. */
2182 		sc->thcal_state = 0;
2183 		sc->thcal_lctemp = 0;
2184 
2185 		/* Start periodic calibration. */
2186 		if (!sc->sc_dying)
2187 			callout_schedule(&sc->sc_calib_to, hz);
2188 		break;
2189 	}
2190 
2191 	(*sc->sc_newstate)(ic, nstate, cmd->arg);
2192 
2193 	mutex_exit(&sc->sc_write_mtx);
2194 	splx(s);
2195 }
2196 
2197 static int
2198 urtwn_wme_update(struct ieee80211com *ic)
2199 {
2200 	struct urtwn_softc *sc = ic->ic_ifp->if_softc;
2201 
2202 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
2203 
2204 	/* don't override default WME values if WME is not actually enabled */
2205 	if (!(ic->ic_flags & IEEE80211_F_WME))
2206 		return 0;
2207 
2208 	/* Do it in a process context. */
2209 	urtwn_do_async(sc, urtwn_wme_update_cb, NULL, 0);
2210 	return 0;
2211 }
2212 
2213 static void
2214 urtwn_wme_update_cb(struct urtwn_softc *sc, void *arg)
2215 {
2216 	static const uint16_t ac2reg[WME_NUM_AC] = {
2217 		R92C_EDCA_BE_PARAM,
2218 		R92C_EDCA_BK_PARAM,
2219 		R92C_EDCA_VI_PARAM,
2220 		R92C_EDCA_VO_PARAM
2221 	};
2222 	struct ieee80211com *ic = &sc->sc_ic;
2223 	const struct wmeParams *wmep;
2224 	int ac, aifs, slottime;
2225 	int s;
2226 
2227 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
2228 	DPRINTFN(DBG_STM, "called", 0, 0, 0, 0);
2229 
2230 	s = splnet();
2231 	mutex_enter(&sc->sc_write_mtx);
2232 	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
2233 	for (ac = 0; ac < WME_NUM_AC; ac++) {
2234 		wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
2235 		/* AIFS[AC] = AIFSN[AC] * aSlotTime + aSIFSTime. */
2236 		aifs = wmep->wmep_aifsn * slottime + 10;
2237 		urtwn_write_4(sc, ac2reg[ac],
2238 		    SM(R92C_EDCA_PARAM_TXOP, wmep->wmep_txopLimit) |
2239 		    SM(R92C_EDCA_PARAM_ECWMIN, wmep->wmep_logcwmin) |
2240 		    SM(R92C_EDCA_PARAM_ECWMAX, wmep->wmep_logcwmax) |
2241 		    SM(R92C_EDCA_PARAM_AIFS, aifs));
2242 	}
2243 	mutex_exit(&sc->sc_write_mtx);
2244 	splx(s);
2245 }
2246 
2247 static void
2248 urtwn_update_avgrssi(struct urtwn_softc *sc, int rate, int8_t rssi)
2249 {
2250 	int pwdb;
2251 
2252 	URTWNHIST_FUNC();
2253 	URTWNHIST_CALLARGS("rate=%jd, rsst=%jd", rate, rssi, 0, 0);
2254 
2255 	/* Convert antenna signal to percentage. */
2256 	if (rssi <= -100 || rssi >= 20)
2257 		pwdb = 0;
2258 	else if (rssi >= 0)
2259 		pwdb = 100;
2260 	else
2261 		pwdb = 100 + rssi;
2262 	if (!ISSET(sc->chip, URTWN_CHIP_88E)) {
2263 		if (rate <= 3) {
2264 			/* CCK gain is smaller than OFDM/MCS gain. */
2265 			pwdb += 6;
2266 			if (pwdb > 100)
2267 				pwdb = 100;
2268 			if (pwdb <= 14)
2269 				pwdb -= 4;
2270 			else if (pwdb <= 26)
2271 				pwdb -= 8;
2272 			else if (pwdb <= 34)
2273 				pwdb -= 6;
2274 			else if (pwdb <= 42)
2275 				pwdb -= 2;
2276 		}
2277 	}
2278 	if (sc->avg_pwdb == -1)	/* Init. */
2279 		sc->avg_pwdb = pwdb;
2280 	else if (sc->avg_pwdb < pwdb)
2281 		sc->avg_pwdb = ((sc->avg_pwdb * 19 + pwdb) / 20) + 1;
2282 	else
2283 		sc->avg_pwdb = ((sc->avg_pwdb * 19 + pwdb) / 20);
2284 
2285 	DPRINTFN(DBG_RF, "rate=%jd rssi=%jd PWDB=%jd EMA=%jd",
2286 	    rate, rssi, pwdb, sc->avg_pwdb);
2287 }
2288 
2289 static int8_t
2290 urtwn_get_rssi(struct urtwn_softc *sc, int rate, void *physt)
2291 {
2292 	static const int8_t cckoff[] = { 16, -12, -26, -46 };
2293 	struct r92c_rx_phystat *phy;
2294 	struct r92c_rx_cck *cck;
2295 	uint8_t rpt;
2296 	int8_t rssi;
2297 
2298 	URTWNHIST_FUNC();
2299 	URTWNHIST_CALLARGS("rate=%jd", rate, 0, 0, 0);
2300 
2301 	if (rate <= 3) {
2302 		cck = (struct r92c_rx_cck *)physt;
2303 		if (ISSET(sc->sc_flags, URTWN_FLAG_CCK_HIPWR)) {
2304 			rpt = (cck->agc_rpt >> 5) & 0x3;
2305 			rssi = (cck->agc_rpt & 0x1f) << 1;
2306 		} else {
2307 			rpt = (cck->agc_rpt >> 6) & 0x3;
2308 			rssi = cck->agc_rpt & 0x3e;
2309 		}
2310 		rssi = cckoff[rpt] - rssi;
2311 	} else {	/* OFDM/HT. */
2312 		phy = (struct r92c_rx_phystat *)physt;
2313 		rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 110;
2314 	}
2315 	return rssi;
2316 }
2317 
2318 static int8_t
2319 urtwn_r88e_get_rssi(struct urtwn_softc *sc, int rate, void *physt)
2320 {
2321 	struct r92c_rx_phystat *phy;
2322 	struct r88e_rx_cck *cck;
2323 	uint8_t cck_agc_rpt, lna_idx, vga_idx;
2324 	int8_t rssi;
2325 
2326 	URTWNHIST_FUNC();
2327 	URTWNHIST_CALLARGS("rate=%jd", rate, 0, 0, 0);
2328 
2329 	rssi = 0;
2330 	if (rate <= 3) {
2331 		cck = (struct r88e_rx_cck *)physt;
2332 		cck_agc_rpt = cck->agc_rpt;
2333 		lna_idx = (cck_agc_rpt & 0xe0) >> 5;
2334 		vga_idx = cck_agc_rpt & 0x1f;
2335 		switch (lna_idx) {
2336 		case 7:
2337 			if (vga_idx <= 27)
2338 				rssi = -100 + 2* (27 - vga_idx);
2339 			else
2340 				rssi = -100;
2341 			break;
2342 		case 6:
2343 			rssi = -48 + 2 * (2 - vga_idx);
2344 			break;
2345 		case 5:
2346 			rssi = -42 + 2 * (7 - vga_idx);
2347 			break;
2348 		case 4:
2349 			rssi = -36 + 2 * (7 - vga_idx);
2350 			break;
2351 		case 3:
2352 			rssi = -24 + 2 * (7 - vga_idx);
2353 			break;
2354 		case 2:
2355 			rssi = -12 + 2 * (5 - vga_idx);
2356 			break;
2357 		case 1:
2358 			rssi = 8 - (2 * vga_idx);
2359 			break;
2360 		case 0:
2361 			rssi = 14 - (2 * vga_idx);
2362 			break;
2363 		}
2364 		rssi += 6;
2365 	} else {	/* OFDM/HT. */
2366 		phy = (struct r92c_rx_phystat *)physt;
2367 		rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 110;
2368 	}
2369 	return rssi;
2370 }
2371 
2372 static void
2373 urtwn_rx_frame(struct urtwn_softc *sc, uint8_t *buf, int pktlen)
2374 {
2375 	struct ieee80211com *ic = &sc->sc_ic;
2376 	struct ifnet *ifp = ic->ic_ifp;
2377 	struct ieee80211_frame *wh;
2378 	struct ieee80211_node *ni;
2379 	struct r92c_rx_desc_usb *stat;
2380 	uint32_t rxdw0, rxdw3;
2381 	struct mbuf *m;
2382 	uint8_t rate;
2383 	int8_t rssi = 0;
2384 	int s, infosz;
2385 
2386 	URTWNHIST_FUNC();
2387 	URTWNHIST_CALLARGS("buf=%jp, pktlen=%#jd", (uintptr_t)buf, pktlen, 0, 0);
2388 
2389 	stat = (struct r92c_rx_desc_usb *)buf;
2390 	rxdw0 = le32toh(stat->rxdw0);
2391 	rxdw3 = le32toh(stat->rxdw3);
2392 
2393 	if (__predict_false(rxdw0 & (R92C_RXDW0_CRCERR | R92C_RXDW0_ICVERR))) {
2394 		/*
2395 		 * This should not happen since we setup our Rx filter
2396 		 * to not receive these frames.
2397 		 */
2398 		DPRINTFN(DBG_RX, "CRC error", 0, 0, 0, 0);
2399 		if_statinc(ifp, if_ierrors);
2400 		return;
2401 	}
2402 	/*
2403 	 * XXX: This will drop most control packets.  Do we really
2404 	 * want this in IEEE80211_M_MONITOR mode?
2405 	 */
2406 //	if (__predict_false(pktlen < (int)sizeof(*wh))) {
2407 	if (__predict_false(pktlen < (int)sizeof(struct ieee80211_frame_ack))) {
2408 		DPRINTFN(DBG_RX, "packet too short %jd", pktlen, 0, 0, 0);
2409 		ic->ic_stats.is_rx_tooshort++;
2410 		if_statinc(ifp, if_ierrors);
2411 		return;
2412 	}
2413 	if (__predict_false(pktlen > MCLBYTES)) {
2414 		DPRINTFN(DBG_RX, "packet too big %jd", pktlen, 0, 0, 0);
2415 		if_statinc(ifp, if_ierrors);
2416 		return;
2417 	}
2418 
2419 	rate = MS(rxdw3, R92C_RXDW3_RATE);
2420 	infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8;
2421 
2422 	/* Get RSSI from PHY status descriptor if present. */
2423 	if (infosz != 0 && (rxdw0 & R92C_RXDW0_PHYST)) {
2424 		if (!ISSET(sc->chip, URTWN_CHIP_92C))
2425 			rssi = urtwn_r88e_get_rssi(sc, rate, &stat[1]);
2426 		else
2427 			rssi = urtwn_get_rssi(sc, rate, &stat[1]);
2428 		/* Update our average RSSI. */
2429 		urtwn_update_avgrssi(sc, rate, rssi);
2430 	}
2431 
2432 	DPRINTFN(DBG_RX, "Rx frame len=%jd rate=%jd infosz=%jd rssi=%jd",
2433 	    pktlen, rate, infosz, rssi);
2434 
2435 	MGETHDR(m, M_DONTWAIT, MT_DATA);
2436 	if (__predict_false(m == NULL)) {
2437 		aprint_error_dev(sc->sc_dev, "couldn't allocate rx mbuf\n");
2438 		ic->ic_stats.is_rx_nobuf++;
2439 		if_statinc(ifp, if_ierrors);
2440 		return;
2441 	}
2442 	if (pktlen > (int)MHLEN) {
2443 		MCLGET(m, M_DONTWAIT);
2444 		if (__predict_false(!(m->m_flags & M_EXT))) {
2445 			aprint_error_dev(sc->sc_dev,
2446 			    "couldn't allocate rx mbuf cluster\n");
2447 			m_freem(m);
2448 			ic->ic_stats.is_rx_nobuf++;
2449 			if_statinc(ifp, if_ierrors);
2450 			return;
2451 		}
2452 	}
2453 
2454 	/* Finalize mbuf. */
2455 	m_set_rcvif(m, ifp);
2456 	wh = (struct ieee80211_frame *)((uint8_t *)&stat[1] + infosz);
2457 	memcpy(mtod(m, uint8_t *), wh, pktlen);
2458 	m->m_pkthdr.len = m->m_len = pktlen;
2459 
2460 	s = splnet();
2461 	if (__predict_false(sc->sc_drvbpf != NULL)) {
2462 		struct urtwn_rx_radiotap_header *tap = &sc->sc_rxtap;
2463 
2464 		tap->wr_flags = 0;
2465 		if (!(rxdw3 & R92C_RXDW3_HT)) {
2466 			switch (rate) {
2467 			/* CCK. */
2468 			case  0: tap->wr_rate =   2; break;
2469 			case  1: tap->wr_rate =   4; break;
2470 			case  2: tap->wr_rate =  11; break;
2471 			case  3: tap->wr_rate =  22; break;
2472 			/* OFDM. */
2473 			case  4: tap->wr_rate =  12; break;
2474 			case  5: tap->wr_rate =  18; break;
2475 			case  6: tap->wr_rate =  24; break;
2476 			case  7: tap->wr_rate =  36; break;
2477 			case  8: tap->wr_rate =  48; break;
2478 			case  9: tap->wr_rate =  72; break;
2479 			case 10: tap->wr_rate =  96; break;
2480 			case 11: tap->wr_rate = 108; break;
2481 			}
2482 		} else if (rate >= 12) {	/* MCS0~15. */
2483 			/* Bit 7 set means HT MCS instead of rate. */
2484 			tap->wr_rate = 0x80 | (rate - 12);
2485 		}
2486 		tap->wr_dbm_antsignal = rssi;
2487 		tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
2488 		tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
2489 
2490 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m, BPF_D_IN);
2491 	}
2492 
2493 	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
2494 
2495 	/* push the frame up to the 802.11 stack */
2496 	ieee80211_input(ic, m, ni, rssi, 0);
2497 
2498 	/* Node is no longer needed. */
2499 	ieee80211_free_node(ni);
2500 
2501 	splx(s);
2502 }
2503 
2504 static void
2505 urtwn_rxeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
2506 {
2507 	struct urtwn_rx_data *data = priv;
2508 	struct urtwn_softc *sc = data->sc;
2509 	struct r92c_rx_desc_usb *stat;
2510 	size_t pidx = data->pidx;
2511 	uint32_t rxdw0;
2512 	uint8_t *buf;
2513 	int len, totlen, pktlen, infosz, npkts;
2514 
2515 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
2516 	DPRINTFN(DBG_RX, "status=%jd", status, 0, 0, 0);
2517 
2518 	mutex_enter(&sc->sc_rx_mtx);
2519 	TAILQ_REMOVE(&sc->rx_free_list[pidx], data, next);
2520 	TAILQ_INSERT_TAIL(&sc->rx_free_list[pidx], data, next);
2521 	/* Put this Rx buffer back to our free list. */
2522 	mutex_exit(&sc->sc_rx_mtx);
2523 
2524 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
2525 		if (status == USBD_STALLED)
2526 			usbd_clear_endpoint_stall_async(sc->rx_pipe[pidx]);
2527 		else if (status != USBD_CANCELLED)
2528 			goto resubmit;
2529 		return;
2530 	}
2531 	usbd_get_xfer_status(xfer, NULL, NULL, &len, NULL);
2532 
2533 	if (__predict_false(len < (int)sizeof(*stat))) {
2534 		DPRINTFN(DBG_RX, "xfer too short %jd", len, 0, 0, 0);
2535 		goto resubmit;
2536 	}
2537 	buf = data->buf;
2538 
2539 	/* Get the number of encapsulated frames. */
2540 	stat = (struct r92c_rx_desc_usb *)buf;
2541 	if (ISSET(sc->chip, URTWN_CHIP_92EU))
2542 		npkts = MS(le32toh(stat->rxdw2), R92E_RXDW2_PKTCNT);
2543 	else
2544 		npkts = MS(le32toh(stat->rxdw2), R92C_RXDW2_PKTCNT);
2545 	DPRINTFN(DBG_RX, "Rx %jd frames in one chunk", npkts, 0, 0, 0);
2546 
2547 	if (npkts != 0)
2548 		rnd_add_uint32(&sc->rnd_source, npkts);
2549 
2550 	/* Process all of them. */
2551 	while (npkts-- > 0) {
2552 		if (__predict_false(len < (int)sizeof(*stat))) {
2553 			DPRINTFN(DBG_RX, "len(%jd) is short than header",
2554 			    len, 0, 0, 0);
2555 			break;
2556 		}
2557 		stat = (struct r92c_rx_desc_usb *)buf;
2558 		rxdw0 = le32toh(stat->rxdw0);
2559 
2560 		pktlen = MS(rxdw0, R92C_RXDW0_PKTLEN);
2561 		if (__predict_false(pktlen == 0)) {
2562 			DPRINTFN(DBG_RX, "pktlen is 0 byte", 0, 0, 0, 0);
2563 			break;
2564 		}
2565 
2566 		infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8;
2567 
2568 		/* Make sure everything fits in xfer. */
2569 		totlen = sizeof(*stat) + infosz + pktlen;
2570 		if (__predict_false(totlen > len)) {
2571 			DPRINTFN(DBG_RX, "pktlen (%jd+%jd+%jd) > %jd",
2572 			    (int)sizeof(*stat), infosz, pktlen, len);
2573 			break;
2574 		}
2575 
2576 		/* Process 802.11 frame. */
2577 		urtwn_rx_frame(sc, buf, pktlen);
2578 
2579 		/* Next chunk is 128-byte aligned. */
2580 		totlen = roundup2(totlen, 128);
2581 		buf += totlen;
2582 		len -= totlen;
2583 	}
2584 
2585  resubmit:
2586 	/* Setup a new transfer. */
2587 	usbd_setup_xfer(xfer, data, data->buf, URTWN_RXBUFSZ,
2588 	    USBD_SHORT_XFER_OK, USBD_NO_TIMEOUT, urtwn_rxeof);
2589 	(void)usbd_transfer(xfer);
2590 }
2591 
2592 static void
2593 urtwn_put_tx_data(struct urtwn_softc *sc, struct urtwn_tx_data *data)
2594 {
2595 	size_t pidx = data->pidx;
2596 
2597 	mutex_enter(&sc->sc_tx_mtx);
2598 	/* Put this Tx buffer back to our free list. */
2599 	TAILQ_INSERT_TAIL(&sc->tx_free_list[pidx], data, next);
2600 	mutex_exit(&sc->sc_tx_mtx);
2601 }
2602 
2603 static void
2604 urtwn_txeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
2605 {
2606 	struct urtwn_tx_data *data = priv;
2607 	struct urtwn_softc *sc = data->sc;
2608 	struct ifnet *ifp = &sc->sc_if;
2609 	size_t pidx = data->pidx;
2610 	int s;
2611 
2612 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
2613 	DPRINTFN(DBG_TX, "status=%jd", status, 0, 0, 0);
2614 
2615 	urtwn_put_tx_data(sc, data);
2616 
2617 	s = splnet();
2618 	sc->tx_timer = 0;
2619 	ifp->if_flags &= ~IFF_OACTIVE;
2620 
2621 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
2622 		if (status != USBD_NOT_STARTED && status != USBD_CANCELLED) {
2623 			if (status == USBD_STALLED) {
2624 				struct usbd_pipe *pipe = sc->tx_pipe[pidx];
2625 				usbd_clear_endpoint_stall_async(pipe);
2626 			}
2627 			device_printf(sc->sc_dev, "transmit failed, %s\n",
2628 			              usbd_errstr(status));
2629 			if_statinc(ifp, if_oerrors);
2630 		}
2631 		splx(s);
2632 		return;
2633 	}
2634 
2635 	if_statinc(ifp, if_opackets);
2636 	urtwn_start(ifp);
2637 	splx(s);
2638 
2639 }
2640 
2641 static int
2642 urtwn_tx(struct urtwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni,
2643     struct urtwn_tx_data *data)
2644 {
2645 	struct ieee80211com *ic = &sc->sc_ic;
2646 	struct ieee80211_frame *wh;
2647 	struct ieee80211_key *k = NULL;
2648 	struct r92c_tx_desc_usb *txd;
2649 	size_t i, padsize, xferlen, txd_len;
2650 	uint16_t seq, sum;
2651 	uint8_t raid, type, tid;
2652 	int s, hasqos, error;
2653 
2654 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
2655 
2656 	wh = mtod(m, struct ieee80211_frame *);
2657 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2658 	txd_len = sizeof(*txd);
2659 
2660 	if (!ISSET(sc->chip, URTWN_CHIP_92EU))
2661 		txd_len = 32;
2662 
2663 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
2664 		k = ieee80211_crypto_encap(ic, ni, m);
2665 		if (k == NULL) {
2666 			urtwn_put_tx_data(sc, data);
2667 			m_free(m);
2668 			return ENOBUFS;
2669 		}
2670 
2671 		/* packet header may have moved, reset our local pointer */
2672 		wh = mtod(m, struct ieee80211_frame *);
2673 	}
2674 
2675 	if (__predict_false(sc->sc_drvbpf != NULL)) {
2676 		struct urtwn_tx_radiotap_header *tap = &sc->sc_txtap;
2677 
2678 		tap->wt_flags = 0;
2679 		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
2680 		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
2681 		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
2682 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
2683 
2684 		/* XXX: set tap->wt_rate? */
2685 
2686 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m, BPF_D_OUT);
2687 	}
2688 
2689 	/* non-qos data frames */
2690 	tid = R92C_TXDW1_QSEL_BE;
2691 	if ((hasqos = ieee80211_has_qos(wh))) {
2692 		/* data frames in 11n mode */
2693 		struct ieee80211_qosframe *qwh = (void *)wh;
2694 		tid = qwh->i_qos[0] & IEEE80211_QOS_TID;
2695 	} else if (type != IEEE80211_FC0_TYPE_DATA) {
2696 		tid = R92C_TXDW1_QSEL_MGNT;
2697 	}
2698 
2699 	if (((txd_len + m->m_pkthdr.len) % 64) == 0) /* XXX: 64 */
2700 		padsize = 8;
2701 	else
2702 		padsize = 0;
2703 
2704 	if (ISSET(sc->chip, URTWN_CHIP_92EU))
2705 		padsize = 0;
2706 
2707 	/* Fill Tx descriptor. */
2708 	txd = (struct r92c_tx_desc_usb *)data->buf;
2709 	memset(txd, 0, txd_len + padsize);
2710 
2711 	txd->txdw0 |= htole32(
2712 	    SM(R92C_TXDW0_PKTLEN, m->m_pkthdr.len) |
2713 	    SM(R92C_TXDW0_OFFSET, txd_len));
2714 	if (!ISSET(sc->chip, URTWN_CHIP_92EU)) {
2715 		txd->txdw0 |= htole32(
2716 		    R92C_TXDW0_OWN | R92C_TXDW0_FSG | R92C_TXDW0_LSG);
2717 	}
2718 
2719 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
2720 		txd->txdw0 |= htole32(R92C_TXDW0_BMCAST);
2721 
2722 	/* fix pad field */
2723 	if (padsize > 0) {
2724 		DPRINTFN(DBG_TX, "padding: size=%jd", padsize, 0, 0, 0);
2725 		txd->txdw1 |= htole32(SM(R92C_TXDW1_PKTOFF, (padsize / 8)));
2726 	}
2727 
2728 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
2729 	    type == IEEE80211_FC0_TYPE_DATA) {
2730 		if (ic->ic_curmode == IEEE80211_MODE_11B)
2731 			raid = R92C_RAID_11B;
2732 		else
2733 			raid = R92C_RAID_11BG;
2734 		DPRINTFN(DBG_TX, "data packet: tid=%jd, raid=%jd",
2735 		    tid, raid, 0, 0);
2736 
2737 		if (!ISSET(sc->chip, URTWN_CHIP_92C)) {
2738 			txd->txdw1 |= htole32(
2739 			    SM(R88E_TXDW1_MACID, RTWN_MACID_BSS) |
2740 			    SM(R92C_TXDW1_QSEL, tid) |
2741 			    SM(R92C_TXDW1_RAID, raid) |
2742 			    R92C_TXDW1_AGGBK);
2743 		} else
2744 			txd->txdw1 |= htole32(
2745 			    SM(R92C_TXDW1_MACID, RTWN_MACID_BSS) |
2746 			    SM(R92C_TXDW1_QSEL, tid) |
2747 			    SM(R92C_TXDW1_RAID, raid) |
2748 			    R92C_TXDW1_AGGBK);
2749 
2750 		if (ISSET(sc->chip, URTWN_CHIP_88E))
2751 			txd->txdw2 |= htole32(R88E_TXDW2_AGGBK);
2752 		if (ISSET(sc->chip, URTWN_CHIP_92EU))
2753 			txd->txdw3 |= htole32(R92E_TXDW3_AGGBK);
2754 
2755 		if (hasqos) {
2756 			txd->txdw4 |= htole32(R92C_TXDW4_QOS);
2757 		}
2758 
2759 		if (ic->ic_flags & IEEE80211_F_USEPROT) {
2760 			/* for 11g */
2761 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY) {
2762 				txd->txdw4 |= htole32(R92C_TXDW4_CTS2SELF |
2763 				    R92C_TXDW4_HWRTSEN);
2764 			} else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS) {
2765 				txd->txdw4 |= htole32(R92C_TXDW4_RTSEN |
2766 				    R92C_TXDW4_HWRTSEN);
2767 			}
2768 		}
2769 		/* Send RTS at OFDM24. */
2770 		txd->txdw4 |= htole32(SM(R92C_TXDW4_RTSRATE, 8));
2771 		txd->txdw5 |= htole32(0x0001ff00);
2772 		/* Send data at OFDM54. */
2773 		if (ISSET(sc->chip, URTWN_CHIP_88E))
2774 			txd->txdw5 |= htole32(0x13 & 0x3f);
2775 		else
2776 			txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 11));
2777 	} else if (type == IEEE80211_FC0_TYPE_MGT) {
2778 		DPRINTFN(DBG_TX, "mgmt packet", 0, 0, 0, 0);
2779 		txd->txdw1 |= htole32(
2780 		    SM(R92C_TXDW1_MACID, RTWN_MACID_BSS) |
2781 		    SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_MGNT) |
2782 		    SM(R92C_TXDW1_RAID, R92C_RAID_11B));
2783 
2784 		/* Force CCK1. */
2785 		txd->txdw4 |= htole32(R92C_TXDW4_DRVRATE);
2786 		/* Use 1Mbps */
2787 		txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 0));
2788 	} else {
2789 		/* broadcast or multicast packets */
2790 		DPRINTFN(DBG_TX, "bc or mc packet", 0, 0, 0, 0);
2791 		txd->txdw1 |= htole32(
2792 		    SM(R92C_TXDW1_MACID, RTWN_MACID_BC) |
2793 		    SM(R92C_TXDW1_RAID, R92C_RAID_11B));
2794 
2795 		/* Force CCK1. */
2796 		txd->txdw4 |= htole32(R92C_TXDW4_DRVRATE);
2797 		/* Use 1Mbps */
2798 		txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 0));
2799 	}
2800 	/* Set sequence number */
2801 	seq = LE_READ_2(&wh->i_seq[0]) >> IEEE80211_SEQ_SEQ_SHIFT;
2802 	if (!ISSET(sc->chip, URTWN_CHIP_92EU)) {
2803 		txd->txdseq |= htole16(seq);
2804 
2805 		if (!hasqos) {
2806 			/* Use HW sequence numbering for non-QoS frames. */
2807 			txd->txdw4  |= htole32(R92C_TXDW4_HWSEQ);
2808 			txd->txdseq |= htole16(R92C_HWSEQ_EN);
2809 		}
2810 	} else {
2811 		txd->txdseq2 |= htole16((seq & R92E_HWSEQ_MASK) <<
2812 		    R92E_HWSEQ_SHIFT);
2813 		if (!hasqos) {
2814 			/* Use HW sequence numbering for non-QoS frames. */
2815 			txd->txdw4  |= htole32(R92C_TXDW4_HWSEQ);
2816 			txd->txdw7 |= htole16(R92C_HWSEQ_EN);
2817 		}
2818 	}
2819 
2820 	/* Compute Tx descriptor checksum. */
2821 	sum = 0;
2822 	for (i = 0; i < R92C_TXDESC_SUMSIZE / 2; i++)
2823 		sum ^= ((uint16_t *)txd)[i];
2824 	txd->txdsum = sum;	/* NB: already little endian. */
2825 
2826 	xferlen = txd_len + m->m_pkthdr.len + padsize;
2827 	m_copydata(m, 0, m->m_pkthdr.len, (char *)&txd[0] + txd_len + padsize);
2828 
2829 	s = splnet();
2830 	usbd_setup_xfer(data->xfer, data, data->buf, xferlen,
2831 	    USBD_FORCE_SHORT_XFER, URTWN_TX_TIMEOUT,
2832 	    urtwn_txeof);
2833 	error = usbd_transfer(data->xfer);
2834 	if (__predict_false(error != USBD_NORMAL_COMPLETION &&
2835 	    error != USBD_IN_PROGRESS)) {
2836 		splx(s);
2837 		DPRINTFN(DBG_TX, "transfer failed %jd", error, 0, 0, 0);
2838 		return error;
2839 	}
2840 	splx(s);
2841 	return 0;
2842 }
2843 
2844 struct urtwn_tx_data *
2845 urtwn_get_tx_data(struct urtwn_softc *sc, size_t pidx)
2846 {
2847 	struct urtwn_tx_data *data = NULL;
2848 
2849 	mutex_enter(&sc->sc_tx_mtx);
2850 	if (!TAILQ_EMPTY(&sc->tx_free_list[pidx])) {
2851 		data = TAILQ_FIRST(&sc->tx_free_list[pidx]);
2852 		TAILQ_REMOVE(&sc->tx_free_list[pidx], data, next);
2853 	}
2854 	mutex_exit(&sc->sc_tx_mtx);
2855 
2856 	return data;
2857 }
2858 
2859 static void
2860 urtwn_start(struct ifnet *ifp)
2861 {
2862 	struct urtwn_softc *sc = ifp->if_softc;
2863 	struct ieee80211com *ic = &sc->sc_ic;
2864 	struct urtwn_tx_data *data;
2865 	struct ether_header *eh;
2866 	struct ieee80211_node *ni;
2867 	struct mbuf *m;
2868 
2869 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
2870 
2871 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
2872 		return;
2873 
2874 	data = NULL;
2875 	for (;;) {
2876 		/* Send pending management frames first. */
2877 		IF_POLL(&ic->ic_mgtq, m);
2878 		if (m != NULL) {
2879 			/* Use AC_VO for management frames. */
2880 
2881 			data = urtwn_get_tx_data(sc, sc->ac2idx[WME_AC_VO]);
2882 
2883 			if (data == NULL) {
2884 				ifp->if_flags |= IFF_OACTIVE;
2885 				DPRINTFN(DBG_TX, "empty tx_free_list",
2886 				    0, 0, 0, 0);
2887 				return;
2888 			}
2889 			IF_DEQUEUE(&ic->ic_mgtq, m);
2890 			ni = M_GETCTX(m, struct ieee80211_node *);
2891 			M_CLEARCTX(m);
2892 			goto sendit;
2893 		}
2894 		if (ic->ic_state != IEEE80211_S_RUN)
2895 			break;
2896 
2897 		/* Encapsulate and send data frames. */
2898 		IFQ_POLL(&ifp->if_snd, m);
2899 		if (m == NULL)
2900 			break;
2901 
2902 		struct ieee80211_frame *wh = mtod(m, struct ieee80211_frame *);
2903 		uint8_t type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2904 		uint8_t qid = WME_AC_BE;
2905 		if (ieee80211_has_qos(wh)) {
2906 			/* data frames in 11n mode */
2907 			struct ieee80211_qosframe *qwh = (void *)wh;
2908 			uint8_t tid = qwh->i_qos[0] & IEEE80211_QOS_TID;
2909 			qid = TID_TO_WME_AC(tid);
2910 		} else if (type != IEEE80211_FC0_TYPE_DATA) {
2911 			qid = WME_AC_VO;
2912 		}
2913 		data = urtwn_get_tx_data(sc, sc->ac2idx[qid]);
2914 
2915 		if (data == NULL) {
2916 			ifp->if_flags |= IFF_OACTIVE;
2917 			DPRINTFN(DBG_TX, "empty tx_free_list", 0, 0, 0, 0);
2918 			return;
2919 		}
2920 		IFQ_DEQUEUE(&ifp->if_snd, m);
2921 
2922 		if (m->m_len < (int)sizeof(*eh) &&
2923 		    (m = m_pullup(m, sizeof(*eh))) == NULL) {
2924 			device_printf(sc->sc_dev, "m_pullup failed\n");
2925 			if_statinc(ifp, if_oerrors);
2926 			urtwn_put_tx_data(sc, data);
2927 			m_freem(m);
2928 			continue;
2929 		}
2930 		eh = mtod(m, struct ether_header *);
2931 		ni = ieee80211_find_txnode(ic, eh->ether_dhost);
2932 		if (ni == NULL) {
2933 			device_printf(sc->sc_dev,
2934 			    "unable to find transmit node\n");
2935 			if_statinc(ifp, if_oerrors);
2936 			urtwn_put_tx_data(sc, data);
2937 			m_freem(m);
2938 			continue;
2939 		}
2940 
2941 		bpf_mtap(ifp, m, BPF_D_OUT);
2942 
2943 		if ((m = ieee80211_encap(ic, m, ni)) == NULL) {
2944 			ieee80211_free_node(ni);
2945 			device_printf(sc->sc_dev,
2946 			    "unable to encapsulate packet\n");
2947 			if_statinc(ifp, if_oerrors);
2948 			urtwn_put_tx_data(sc, data);
2949 			m_freem(m);
2950 			continue;
2951 		}
2952  sendit:
2953 		bpf_mtap3(ic->ic_rawbpf, m, BPF_D_OUT);
2954 
2955 		if (urtwn_tx(sc, m, ni, data) != 0) {
2956 			m_freem(m);
2957 			ieee80211_free_node(ni);
2958 			device_printf(sc->sc_dev,
2959 			    "unable to transmit packet\n");
2960 			if_statinc(ifp, if_oerrors);
2961 			continue;
2962 		}
2963 		m_freem(m);
2964 		ieee80211_free_node(ni);
2965 		sc->tx_timer = 5;
2966 		ifp->if_timer = 1;
2967 	}
2968 }
2969 
2970 static void
2971 urtwn_watchdog(struct ifnet *ifp)
2972 {
2973 	struct urtwn_softc *sc = ifp->if_softc;
2974 
2975 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
2976 
2977 	ifp->if_timer = 0;
2978 
2979 	if (sc->tx_timer > 0) {
2980 		if (--sc->tx_timer == 0) {
2981 			device_printf(sc->sc_dev, "device timeout\n");
2982 			/* urtwn_init(ifp); XXX needs a process context! */
2983 			if_statinc(ifp, if_oerrors);
2984 			return;
2985 		}
2986 		ifp->if_timer = 1;
2987 	}
2988 	ieee80211_watchdog(&sc->sc_ic);
2989 }
2990 
2991 static int
2992 urtwn_ioctl(struct ifnet *ifp, u_long cmd, void *data)
2993 {
2994 	struct urtwn_softc *sc = ifp->if_softc;
2995 	struct ieee80211com *ic = &sc->sc_ic;
2996 	int s, error = 0;
2997 
2998 	URTWNHIST_FUNC();
2999 	URTWNHIST_CALLARGS("cmd=0x%08jx, data=%#jx", cmd, (uintptr_t)data,
3000 	    0, 0);
3001 
3002 	s = splnet();
3003 
3004 	switch (cmd) {
3005 	case SIOCSIFFLAGS:
3006 		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
3007 			break;
3008 		switch (ifp->if_flags & (IFF_UP | IFF_RUNNING)) {
3009 		case IFF_UP | IFF_RUNNING:
3010 			break;
3011 		case IFF_UP:
3012 			urtwn_init(ifp);
3013 			break;
3014 		case IFF_RUNNING:
3015 			urtwn_stop(ifp, 1);
3016 			break;
3017 		case 0:
3018 			break;
3019 		}
3020 		break;
3021 
3022 	case SIOCADDMULTI:
3023 	case SIOCDELMULTI:
3024 		if ((error = ether_ioctl(ifp, cmd, data)) == ENETRESET) {
3025 			/* setup multicast filter, etc */
3026 			error = 0;
3027 		}
3028 		break;
3029 
3030 	case SIOCS80211CHANNEL:
3031 		/*
3032 		 * This allows for fast channel switching in monitor mode
3033 		 * (used by kismet). In IBSS mode, we must explicitly reset
3034 		 * the interface to generate a new beacon frame.
3035 		 */
3036 		error = ieee80211_ioctl(ic, cmd, data);
3037 		if (error == ENETRESET &&
3038 		    ic->ic_opmode == IEEE80211_M_MONITOR) {
3039 			urtwn_set_chan(sc, ic->ic_curchan,
3040 			    IEEE80211_HTINFO_2NDCHAN_NONE);
3041 			error = 0;
3042 		}
3043 		break;
3044 
3045 	default:
3046 		error = ieee80211_ioctl(ic, cmd, data);
3047 		break;
3048 	}
3049 	if (error == ENETRESET) {
3050 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
3051 		    (IFF_UP | IFF_RUNNING) &&
3052 		    ic->ic_roaming != IEEE80211_ROAMING_MANUAL) {
3053 			urtwn_init(ifp);
3054 		}
3055 		error = 0;
3056 	}
3057 
3058 	splx(s);
3059 
3060 	return error;
3061 }
3062 
3063 static __inline int
3064 urtwn_power_on(struct urtwn_softc *sc)
3065 {
3066 
3067 	return sc->sc_power_on(sc);
3068 }
3069 
3070 static int
3071 urtwn_r92c_power_on(struct urtwn_softc *sc)
3072 {
3073 	uint32_t reg;
3074 	int ntries;
3075 
3076 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
3077 
3078 	KASSERT(mutex_owned(&sc->sc_write_mtx));
3079 
3080 	/* Wait for autoload done bit. */
3081 	for (ntries = 0; ntries < 1000; ntries++) {
3082 		if (urtwn_read_1(sc, R92C_APS_FSMCO) & R92C_APS_FSMCO_PFM_ALDN)
3083 			break;
3084 		DELAY(5);
3085 	}
3086 	if (ntries == 1000) {
3087 		aprint_error_dev(sc->sc_dev,
3088 		    "timeout waiting for chip autoload\n");
3089 		return ETIMEDOUT;
3090 	}
3091 
3092 	/* Unlock ISO/CLK/Power control register. */
3093 	urtwn_write_1(sc, R92C_RSV_CTRL, 0);
3094 	DELAY(5);
3095 	/* Move SPS into PWM mode. */
3096 	urtwn_write_1(sc, R92C_SPS0_CTRL, 0x2b);
3097 	DELAY(5);
3098 
3099 	reg = urtwn_read_1(sc, R92C_LDOV12D_CTRL);
3100 	if (!(reg & R92C_LDOV12D_CTRL_LDV12_EN)) {
3101 		urtwn_write_1(sc, R92C_LDOV12D_CTRL,
3102 		    reg | R92C_LDOV12D_CTRL_LDV12_EN);
3103 		DELAY(100);
3104 		urtwn_write_1(sc, R92C_SYS_ISO_CTRL,
3105 		    urtwn_read_1(sc, R92C_SYS_ISO_CTRL) &
3106 		    ~R92C_SYS_ISO_CTRL_MD2PP);
3107 	}
3108 
3109 	/* Auto enable WLAN. */
3110 	urtwn_write_2(sc, R92C_APS_FSMCO,
3111 	    urtwn_read_2(sc, R92C_APS_FSMCO) | R92C_APS_FSMCO_APFM_ONMAC);
3112 	for (ntries = 0; ntries < 1000; ntries++) {
3113 		if (!(urtwn_read_2(sc, R92C_APS_FSMCO) &
3114 		    R92C_APS_FSMCO_APFM_ONMAC))
3115 			break;
3116 		DELAY(100);
3117 	}
3118 	if (ntries == 1000) {
3119 		aprint_error_dev(sc->sc_dev,
3120 		    "timeout waiting for MAC auto ON\n");
3121 		return ETIMEDOUT;
3122 	}
3123 
3124 	/* Enable radio, GPIO and LED functions. */
3125 	KASSERT((R92C_APS_FSMCO_AFSM_HSUS | R92C_APS_FSMCO_PDN_EN |
3126 	    R92C_APS_FSMCO_PFM_ALDN) == 0x0812);
3127 	urtwn_write_2(sc, R92C_APS_FSMCO,
3128 	    R92C_APS_FSMCO_AFSM_HSUS |
3129 	    R92C_APS_FSMCO_PDN_EN |
3130 	    R92C_APS_FSMCO_PFM_ALDN);
3131 
3132 	/* Release RF digital isolation. */
3133 	urtwn_write_2(sc, R92C_SYS_ISO_CTRL,
3134 	    urtwn_read_2(sc, R92C_SYS_ISO_CTRL) & ~R92C_SYS_ISO_CTRL_DIOR);
3135 
3136 	/* Initialize MAC. */
3137 	urtwn_write_1(sc, R92C_APSD_CTRL,
3138 	    urtwn_read_1(sc, R92C_APSD_CTRL) & ~R92C_APSD_CTRL_OFF);
3139 	for (ntries = 0; ntries < 200; ntries++) {
3140 		if (!(urtwn_read_1(sc, R92C_APSD_CTRL) &
3141 		    R92C_APSD_CTRL_OFF_STATUS))
3142 			break;
3143 		DELAY(5);
3144 	}
3145 	if (ntries == 200) {
3146 		aprint_error_dev(sc->sc_dev,
3147 		    "timeout waiting for MAC initialization\n");
3148 		return ETIMEDOUT;
3149 	}
3150 
3151 	/* Enable MAC DMA/WMAC/SCHEDULE/SEC blocks. */
3152 	reg = urtwn_read_2(sc, R92C_CR);
3153 	reg |= R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN |
3154 	    R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN |
3155 	    R92C_CR_SCHEDULE_EN | R92C_CR_MACTXEN | R92C_CR_MACRXEN |
3156 	    R92C_CR_ENSEC;
3157 	urtwn_write_2(sc, R92C_CR, reg);
3158 
3159 	urtwn_write_1(sc, 0xfe10, 0x19);
3160 
3161 	urtwn_delay_ms(sc, 1);
3162 
3163 	return 0;
3164 }
3165 
3166 static int
3167 urtwn_r92e_power_on(struct urtwn_softc *sc)
3168 {
3169 	uint32_t reg;
3170 	uint32_t val;
3171 	int ntries;
3172 
3173 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
3174 
3175 	KASSERT(mutex_owned(&sc->sc_write_mtx));
3176 
3177 	/* Enable radio, GPIO and LED functions. */
3178 	KASSERT((R92C_APS_FSMCO_AFSM_HSUS | R92C_APS_FSMCO_PDN_EN |
3179 	    R92C_APS_FSMCO_PFM_ALDN) == 0x0812);
3180 	urtwn_write_2(sc, R92C_APS_FSMCO,
3181 	    R92C_APS_FSMCO_AFSM_HSUS |
3182 	    R92C_APS_FSMCO_PDN_EN |
3183 	    R92C_APS_FSMCO_PFM_ALDN);
3184 
3185 	if (urtwn_read_4(sc, R92E_SYS_CFG1_8192E) & R92E_SPSLDO_SEL){
3186 		/* LDO. */
3187 		urtwn_write_1(sc, R92E_LDO_SWR_CTRL, 0xc3);
3188 	}
3189 	else	{
3190 		urtwn_write_2(sc, R92C_SYS_SWR_CTRL2, urtwn_read_2(sc,
3191 		    R92C_SYS_SWR_CTRL2) & 0xffff);
3192 		urtwn_write_1(sc, R92E_LDO_SWR_CTRL, 0x83);
3193 	}
3194 
3195 	for (ntries = 0; ntries < 2; ntries++) {
3196 		urtwn_write_1(sc, R92C_AFE_PLL_CTRL,
3197 		    urtwn_read_1(sc, R92C_AFE_PLL_CTRL));
3198 		urtwn_write_2(sc, R92C_AFE_CTRL4, urtwn_read_2(sc,
3199 		    R92C_AFE_CTRL4));
3200 	}
3201 
3202 	/* Reset BB. */
3203 	urtwn_write_1(sc, R92C_SYS_FUNC_EN,
3204 	urtwn_read_1(sc, R92C_SYS_FUNC_EN) & ~(R92C_SYS_FUNC_EN_BBRSTB |
3205 	    R92C_SYS_FUNC_EN_BB_GLB_RST));
3206 
3207 	urtwn_write_1(sc, R92C_AFE_XTAL_CTRL + 2, urtwn_read_1(sc,
3208 	    R92C_AFE_XTAL_CTRL + 2) | 0x80);
3209 
3210 	/* Disable HWPDN. */
3211 	urtwn_write_2(sc, R92C_APS_FSMCO, urtwn_read_2(sc,
3212 	    R92C_APS_FSMCO) & ~R92C_APS_FSMCO_APDM_HPDN);
3213 
3214 	/* Disable WL suspend. */
3215 	urtwn_write_2(sc, R92C_APS_FSMCO, urtwn_read_2(sc,
3216 	    R92C_APS_FSMCO) & ~(R92C_APS_FSMCO_AFSM_PCIE |
3217 	    R92C_APS_FSMCO_AFSM_HSUS));
3218 
3219 	urtwn_write_4(sc, R92C_APS_FSMCO, urtwn_read_4(sc,
3220 	    R92C_APS_FSMCO) | R92C_APS_FSMCO_RDY_MACON);
3221 	urtwn_write_2(sc, R92C_APS_FSMCO, urtwn_read_2(sc,
3222 	    R92C_APS_FSMCO) | R92C_APS_FSMCO_APFM_ONMAC);
3223 	for (ntries = 0; ntries < 10000; ntries++) {
3224 		val = urtwn_read_2(sc, R92C_APS_FSMCO) &
3225 		 R92C_APS_FSMCO_APFM_ONMAC;
3226 		if (val == 0x0)
3227 			break;
3228 		DELAY(10);
3229 	}
3230 	if (ntries == 10000) {
3231 		aprint_error_dev(sc->sc_dev,
3232 		    "timeout waiting for chip power up\n");
3233 		return ETIMEDOUT;
3234 	}
3235 
3236 	urtwn_write_2(sc, R92C_CR, 0x00);
3237 	reg = urtwn_read_2(sc, R92C_CR);
3238 	reg |= R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN |
3239 	    R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN |
3240 	    R92C_CR_SCHEDULE_EN | R92C_CR_ENSEC;
3241 	urtwn_write_2(sc, R92C_CR, reg);
3242 
3243 	return 0;
3244 }
3245 
3246 static int
3247 urtwn_r88e_power_on(struct urtwn_softc *sc)
3248 {
3249 	uint32_t reg;
3250 	uint8_t val;
3251 	int ntries;
3252 
3253 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
3254 
3255 	KASSERT(mutex_owned(&sc->sc_write_mtx));
3256 
3257 	/* Wait for power ready bit. */
3258 	for (ntries = 0; ntries < 5000; ntries++) {
3259 		val = urtwn_read_1(sc, 0x6) & 0x2;
3260 		if (val == 0x2)
3261 			break;
3262 		DELAY(10);
3263 	}
3264 	if (ntries == 5000) {
3265 		aprint_error_dev(sc->sc_dev,
3266 		    "timeout waiting for chip power up\n");
3267 		return ETIMEDOUT;
3268 	}
3269 
3270 	/* Reset BB. */
3271 	urtwn_write_1(sc, R92C_SYS_FUNC_EN,
3272 	urtwn_read_1(sc, R92C_SYS_FUNC_EN) & ~(R92C_SYS_FUNC_EN_BBRSTB |
3273 	    R92C_SYS_FUNC_EN_BB_GLB_RST));
3274 
3275 	urtwn_write_1(sc, 0x26, urtwn_read_1(sc, 0x26) | 0x80);
3276 
3277 	/* Disable HWPDN. */
3278 	urtwn_write_1(sc, 0x5, urtwn_read_1(sc, 0x5) & ~0x80);
3279 
3280 	/* Disable WL suspend. */
3281 	urtwn_write_1(sc, 0x5, urtwn_read_1(sc, 0x5) & ~0x18);
3282 
3283 	urtwn_write_1(sc, 0x5, urtwn_read_1(sc, 0x5) | 0x1);
3284 	for (ntries = 0; ntries < 5000; ntries++) {
3285 		if (!(urtwn_read_1(sc, 0x5) & 0x1))
3286 			break;
3287 		DELAY(10);
3288 	}
3289 	if (ntries == 5000)
3290 		return ETIMEDOUT;
3291 
3292 	/* Enable LDO normal mode. */
3293 	urtwn_write_1(sc, 0x23, urtwn_read_1(sc, 0x23) & ~0x10);
3294 
3295 	/* Enable MAC DMA/WMAC/SCHEDULE/SEC blocks. */
3296 	urtwn_write_2(sc, R92C_CR, 0);
3297 	reg = urtwn_read_2(sc, R92C_CR);
3298 	reg |= R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN |
3299 	    R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN |
3300 	    R92C_CR_SCHEDULE_EN | R92C_CR_ENSEC | R92C_CR_CALTMR_EN;
3301 	urtwn_write_2(sc, R92C_CR, reg);
3302 
3303 	return 0;
3304 }
3305 
3306 static int __noinline
3307 urtwn_llt_init(struct urtwn_softc *sc)
3308 {
3309 	size_t i, page_count, pktbuf_count;
3310 	uint32_t val;
3311 	int error;
3312 
3313 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
3314 
3315 	KASSERT(mutex_owned(&sc->sc_write_mtx));
3316 
3317 	if (sc->chip & URTWN_CHIP_88E)
3318 		page_count = R88E_TX_PAGE_COUNT;
3319 	else if (sc->chip & URTWN_CHIP_92EU)
3320 		page_count = R92E_TX_PAGE_COUNT;
3321 	else
3322 		page_count = R92C_TX_PAGE_COUNT;
3323 	if (sc->chip & URTWN_CHIP_88E)
3324 		pktbuf_count = R88E_TXPKTBUF_COUNT;
3325 	else if (sc->chip & URTWN_CHIP_92EU)
3326 		pktbuf_count = R88E_TXPKTBUF_COUNT;
3327 	else
3328 		pktbuf_count = R92C_TXPKTBUF_COUNT;
3329 
3330 	if (sc->chip & URTWN_CHIP_92EU) {
3331 		val = urtwn_read_4(sc, R92E_AUTO_LLT) | R92E_AUTO_LLT_EN;
3332 		urtwn_write_4(sc, R92E_AUTO_LLT, val);
3333 		DELAY(100);
3334 		val = urtwn_read_4(sc, R92E_AUTO_LLT);
3335 		if (val & R92E_AUTO_LLT_EN)
3336 			return EIO;
3337 		return 0;
3338 	}
3339 
3340 	/* Reserve pages [0; page_count]. */
3341 	for (i = 0; i < page_count; i++) {
3342 		if ((error = urtwn_llt_write(sc, i, i + 1)) != 0)
3343 			return error;
3344 	}
3345 	/* NB: 0xff indicates end-of-list. */
3346 	if ((error = urtwn_llt_write(sc, i, 0xff)) != 0)
3347 		return error;
3348 	/*
3349 	 * Use pages [page_count + 1; pktbuf_count - 1]
3350 	 * as ring buffer.
3351 	 */
3352 	for (++i; i < pktbuf_count - 1; i++) {
3353 		if ((error = urtwn_llt_write(sc, i, i + 1)) != 0)
3354 			return error;
3355 	}
3356 	/* Make the last page point to the beginning of the ring buffer. */
3357 	error = urtwn_llt_write(sc, i, pktbuf_count + 1);
3358 	return error;
3359 }
3360 
3361 static void
3362 urtwn_fw_reset(struct urtwn_softc *sc)
3363 {
3364 	uint16_t reg;
3365 	int ntries;
3366 
3367 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
3368 
3369 	KASSERT(mutex_owned(&sc->sc_write_mtx));
3370 
3371 	/* Tell 8051 to reset itself. */
3372 	mutex_enter(&sc->sc_fwcmd_mtx);
3373 	urtwn_write_1(sc, R92C_HMETFR + 3, 0x20);
3374 	sc->fwcur = 0;
3375 	mutex_exit(&sc->sc_fwcmd_mtx);
3376 
3377 	/* Wait until 8051 resets by itself. */
3378 	for (ntries = 0; ntries < 100; ntries++) {
3379 		reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN);
3380 		if (!(reg & R92C_SYS_FUNC_EN_CPUEN))
3381 			return;
3382 		DELAY(50);
3383 	}
3384 	/* Force 8051 reset. */
3385 	urtwn_write_2(sc, R92C_SYS_FUNC_EN,
3386 	    urtwn_read_2(sc, R92C_SYS_FUNC_EN) & ~R92C_SYS_FUNC_EN_CPUEN);
3387 }
3388 
3389 static void
3390 urtwn_r88e_fw_reset(struct urtwn_softc *sc)
3391 {
3392 	uint16_t reg;
3393 
3394 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
3395 
3396 	KASSERT(mutex_owned(&sc->sc_write_mtx));
3397 
3398 	if (ISSET(sc->chip, URTWN_CHIP_92EU)) {
3399 		reg = urtwn_read_2(sc, R92C_RSV_CTRL) & ~R92E_RSV_MIO_EN;
3400 		urtwn_write_2(sc,R92C_RSV_CTRL, reg);
3401 	}
3402 	DELAY(50);
3403 
3404 	reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN);
3405 	urtwn_write_2(sc, R92C_SYS_FUNC_EN, reg & ~R92C_SYS_FUNC_EN_CPUEN);
3406 	DELAY(50);
3407 
3408 	urtwn_write_2(sc, R92C_SYS_FUNC_EN, reg | R92C_SYS_FUNC_EN_CPUEN);
3409 	DELAY(50);
3410 
3411 	if (ISSET(sc->chip, URTWN_CHIP_92EU)) {
3412 		reg = urtwn_read_2(sc, R92C_RSV_CTRL) | R92E_RSV_MIO_EN;
3413 		urtwn_write_2(sc,R92C_RSV_CTRL, reg);
3414 	}
3415 	DELAY(50);
3416 
3417 	mutex_enter(&sc->sc_fwcmd_mtx);
3418 	/* Init firmware commands ring. */
3419 	sc->fwcur = 0;
3420 	mutex_exit(&sc->sc_fwcmd_mtx);
3421 
3422 }
3423 
3424 static int
3425 urtwn_fw_loadpage(struct urtwn_softc *sc, int page, uint8_t *buf, int len)
3426 {
3427 	uint32_t reg;
3428 	int off, mlen, error = 0;
3429 
3430 	URTWNHIST_FUNC();
3431 	URTWNHIST_CALLARGS("page=%jd, buf=%#jx, len=%jd",
3432 	    page, (uintptr_t)buf, len, 0);
3433 
3434 	reg = urtwn_read_4(sc, R92C_MCUFWDL);
3435 	reg = RW(reg, R92C_MCUFWDL_PAGE, page);
3436 	urtwn_write_4(sc, R92C_MCUFWDL, reg);
3437 
3438 	off = R92C_FW_START_ADDR;
3439 	while (len > 0) {
3440 		if (len > 196)
3441 			mlen = 196;
3442 		else if (len > 4)
3443 			mlen = 4;
3444 		else
3445 			mlen = 1;
3446 		error = urtwn_write_region(sc, off, buf, mlen);
3447 		if (error != 0)
3448 			break;
3449 		off += mlen;
3450 		buf += mlen;
3451 		len -= mlen;
3452 	}
3453 	return error;
3454 }
3455 
3456 static int __noinline
3457 urtwn_load_firmware(struct urtwn_softc *sc)
3458 {
3459 	firmware_handle_t fwh;
3460 	const struct r92c_fw_hdr *hdr;
3461 	const char *name;
3462 	u_char *fw, *ptr;
3463 	size_t len;
3464 	uint32_t reg;
3465 	int mlen, ntries, page, error;
3466 
3467 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
3468 
3469 	KASSERT(mutex_owned(&sc->sc_write_mtx));
3470 
3471 	/* Read firmware image from the filesystem. */
3472 	if (ISSET(sc->chip, URTWN_CHIP_88E))
3473 		name = "rtl8188eufw.bin";
3474 	else if (ISSET(sc->chip, URTWN_CHIP_92EU))
3475 		name = "rtl8192eefw.bin";
3476 	else if ((sc->chip & (URTWN_CHIP_UMC_A_CUT | URTWN_CHIP_92C)) ==
3477 	    URTWN_CHIP_UMC_A_CUT)
3478 		name = "rtl8192cfwU.bin";
3479 	else
3480 		name = "rtl8192cfw.bin";
3481 	if ((error = firmware_open("if_urtwn", name, &fwh)) != 0) {
3482 		aprint_error_dev(sc->sc_dev,
3483 		    "failed load firmware of file %s (error %d)\n", name,
3484 		    error);
3485 		return error;
3486 	}
3487 	const size_t fwlen = len = firmware_get_size(fwh);
3488 	fw = firmware_malloc(len);
3489 	if (fw == NULL) {
3490 		aprint_error_dev(sc->sc_dev,
3491 		    "failed to allocate firmware memory\n");
3492 		firmware_close(fwh);
3493 		return ENOMEM;
3494 	}
3495 	error = firmware_read(fwh, 0, fw, len);
3496 	firmware_close(fwh);
3497 	if (error != 0) {
3498 		aprint_error_dev(sc->sc_dev,
3499 		    "failed to read firmware (error %d)\n", error);
3500 		firmware_free(fw, fwlen);
3501 		return error;
3502 	}
3503 
3504 	len = fwlen;
3505 	ptr = fw;
3506 	hdr = (const struct r92c_fw_hdr *)ptr;
3507 	/* Check if there is a valid FW header and skip it. */
3508 	if ((le16toh(hdr->signature) >> 4) == 0x88c ||
3509 	    (le16toh(hdr->signature) >> 4) == 0x88e ||
3510 	    (le16toh(hdr->signature) >> 4) == 0x92e ||
3511 	    (le16toh(hdr->signature) >> 4) == 0x92c) {
3512 		DPRINTFN(DBG_INIT, "FW V%jd.%jd",
3513 		    le16toh(hdr->version), le16toh(hdr->subversion), 0, 0);
3514 		DPRINTFN(DBG_INIT, "%02jd-%02jd %02jd:%02jd",
3515 		    hdr->month, hdr->date, hdr->hour, hdr->minute);
3516 		ptr += sizeof(*hdr);
3517 		len -= sizeof(*hdr);
3518 	}
3519 
3520 	if (urtwn_read_1(sc, R92C_MCUFWDL) & R92C_MCUFWDL_RAM_DL_SEL) {
3521 		/* Reset MCU ready status */
3522 		urtwn_write_1(sc, R92C_MCUFWDL, 0);
3523 		if (ISSET(sc->chip, URTWN_CHIP_88E) ||
3524 		    ISSET(sc->chip, URTWN_CHIP_92EU))
3525 			urtwn_r88e_fw_reset(sc);
3526 		else
3527 			urtwn_fw_reset(sc);
3528 	}
3529 	if (!ISSET(sc->chip, URTWN_CHIP_88E) &&
3530 	    !ISSET(sc->chip, URTWN_CHIP_92EU)) {
3531 		urtwn_write_2(sc, R92C_SYS_FUNC_EN,
3532 		    urtwn_read_2(sc, R92C_SYS_FUNC_EN) |
3533 		    R92C_SYS_FUNC_EN_CPUEN);
3534 	}
3535 
3536 	/* download enabled */
3537 	urtwn_write_1(sc, R92C_MCUFWDL,
3538 	    urtwn_read_1(sc, R92C_MCUFWDL) | R92C_MCUFWDL_EN);
3539 	urtwn_write_1(sc, R92C_MCUFWDL + 2,
3540 	    urtwn_read_1(sc, R92C_MCUFWDL + 2) & ~0x08);
3541 
3542 	/* Reset the FWDL checksum. */
3543 	urtwn_write_1(sc, R92C_MCUFWDL,
3544 	urtwn_read_1(sc, R92C_MCUFWDL) | R92C_MCUFWDL_CHKSUM_RPT);
3545 
3546 	DELAY(50);
3547 	/* download firmware */
3548 	for (page = 0; len > 0; page++) {
3549 		mlen = MIN(len, R92C_FW_PAGE_SIZE);
3550 		error = urtwn_fw_loadpage(sc, page, ptr, mlen);
3551 		if (error != 0) {
3552 			aprint_error_dev(sc->sc_dev,
3553 			    "could not load firmware page %d\n", page);
3554 			goto fail;
3555 		}
3556 		ptr += mlen;
3557 		len -= mlen;
3558 	}
3559 
3560 	/* download disable */
3561 	urtwn_write_1(sc, R92C_MCUFWDL,
3562 	    urtwn_read_1(sc, R92C_MCUFWDL) & ~R92C_MCUFWDL_EN);
3563 	urtwn_write_1(sc, R92C_MCUFWDL + 1, 0);
3564 
3565 	/* Wait for checksum report. */
3566 	for (ntries = 0; ntries < 1000; ntries++) {
3567 		if (urtwn_read_4(sc, R92C_MCUFWDL) & R92C_MCUFWDL_CHKSUM_RPT)
3568 			break;
3569 		DELAY(5);
3570 	}
3571 	if (ntries == 1000) {
3572 		aprint_error_dev(sc->sc_dev,
3573 		    "timeout waiting for checksum report\n");
3574 		error = ETIMEDOUT;
3575 		goto fail;
3576 	}
3577 
3578 	/* Wait for firmware readiness. */
3579 	reg = urtwn_read_4(sc, R92C_MCUFWDL);
3580 	reg = (reg & ~R92C_MCUFWDL_WINTINI_RDY) | R92C_MCUFWDL_RDY;
3581 	urtwn_write_4(sc, R92C_MCUFWDL, reg);
3582 	if (ISSET(sc->chip, URTWN_CHIP_88E) ||
3583 	    ISSET(sc->chip, URTWN_CHIP_92EU))
3584 		urtwn_r88e_fw_reset(sc);
3585 	for (ntries = 0; ntries < 6000; ntries++) {
3586 		if (urtwn_read_4(sc, R92C_MCUFWDL) & R92C_MCUFWDL_WINTINI_RDY)
3587 			break;
3588 		DELAY(5);
3589 	}
3590 	if (ntries == 6000) {
3591 		aprint_error_dev(sc->sc_dev,
3592 		    "timeout waiting for firmware readiness\n");
3593 		error = ETIMEDOUT;
3594 		goto fail;
3595 	}
3596  fail:
3597 	firmware_free(fw, fwlen);
3598 	return error;
3599 }
3600 
3601 static __inline int
3602 urtwn_dma_init(struct urtwn_softc *sc)
3603 {
3604 
3605 	return sc->sc_dma_init(sc);
3606 }
3607 
3608 static int
3609 urtwn_r92c_dma_init(struct urtwn_softc *sc)
3610 {
3611 	int hashq, hasnq, haslq, nqueues, nqpages, nrempages;
3612 	uint32_t reg;
3613 	int error;
3614 
3615 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
3616 
3617 	KASSERT(mutex_owned(&sc->sc_write_mtx));
3618 
3619 	/* Initialize LLT table. */
3620 	error = urtwn_llt_init(sc);
3621 	if (error != 0)
3622 		return error;
3623 
3624 	/* Get Tx queues to USB endpoints mapping. */
3625 	hashq = hasnq = haslq = 0;
3626 	reg = urtwn_read_2(sc, R92C_USB_EP + 1);
3627 	DPRINTFN(DBG_INIT, "USB endpoints mapping %#jx", reg, 0, 0, 0);
3628 	if (MS(reg, R92C_USB_EP_HQ) != 0)
3629 		hashq = 1;
3630 	if (MS(reg, R92C_USB_EP_NQ) != 0)
3631 		hasnq = 1;
3632 	if (MS(reg, R92C_USB_EP_LQ) != 0)
3633 		haslq = 1;
3634 	nqueues = hashq + hasnq + haslq;
3635 	if (nqueues == 0)
3636 		return EIO;
3637 	/* Get the number of pages for each queue. */
3638 	nqpages = (R92C_TX_PAGE_COUNT - R92C_PUBQ_NPAGES) / nqueues;
3639 	/* The remaining pages are assigned to the high priority queue. */
3640 	nrempages = (R92C_TX_PAGE_COUNT - R92C_PUBQ_NPAGES) % nqueues;
3641 
3642 	/* Set number of pages for normal priority queue. */
3643 	urtwn_write_1(sc, R92C_RQPN_NPQ, hasnq ? nqpages : 0);
3644 	urtwn_write_4(sc, R92C_RQPN,
3645 	    /* Set number of pages for public queue. */
3646 	    SM(R92C_RQPN_PUBQ, R92C_PUBQ_NPAGES) |
3647 	    /* Set number of pages for high priority queue. */
3648 	    SM(R92C_RQPN_HPQ, hashq ? nqpages + nrempages : 0) |
3649 	    /* Set number of pages for low priority queue. */
3650 	    SM(R92C_RQPN_LPQ, haslq ? nqpages : 0) |
3651 	    /* Load values. */
3652 	    R92C_RQPN_LD);
3653 
3654 	urtwn_write_1(sc, R92C_TXPKTBUF_BCNQ_BDNY, R92C_TX_PAGE_BOUNDARY);
3655 	urtwn_write_1(sc, R92C_TXPKTBUF_MGQ_BDNY, R92C_TX_PAGE_BOUNDARY);
3656 	urtwn_write_1(sc, R92C_TXPKTBUF_WMAC_LBK_BF_HD, R92C_TX_PAGE_BOUNDARY);
3657 	urtwn_write_1(sc, R92C_TRXFF_BNDY, R92C_TX_PAGE_BOUNDARY);
3658 	urtwn_write_1(sc, R92C_TDECTRL + 1, R92C_TX_PAGE_BOUNDARY);
3659 
3660 	/* Set queue to USB pipe mapping. */
3661 	reg = urtwn_read_2(sc, R92C_TRXDMA_CTRL);
3662 	reg &= ~R92C_TRXDMA_CTRL_QMAP_M;
3663 	if (nqueues == 1) {
3664 		if (hashq) {
3665 			reg |= R92C_TRXDMA_CTRL_QMAP_HQ;
3666 		} else if (hasnq) {
3667 			reg |= R92C_TRXDMA_CTRL_QMAP_NQ;
3668 		} else {
3669 			reg |= R92C_TRXDMA_CTRL_QMAP_LQ;
3670 		}
3671 	} else if (nqueues == 2) {
3672 		/* All 2-endpoints configs have a high priority queue. */
3673 		if (!hashq) {
3674 			return EIO;
3675 		}
3676 		if (hasnq) {
3677 			reg |= R92C_TRXDMA_CTRL_QMAP_HQ_NQ;
3678 		} else {
3679 			reg |= R92C_TRXDMA_CTRL_QMAP_HQ_LQ;
3680 		}
3681 	} else {
3682 		reg |= R92C_TRXDMA_CTRL_QMAP_3EP;
3683 	}
3684 	urtwn_write_2(sc, R92C_TRXDMA_CTRL, reg);
3685 
3686 	/* Set Tx/Rx transfer page boundary. */
3687 	urtwn_write_2(sc, R92C_TRXFF_BNDY + 2, 0x27ff);
3688 
3689 	/* Set Tx/Rx transfer page size. */
3690 	urtwn_write_1(sc, R92C_PBP,
3691 	    SM(R92C_PBP_PSRX, R92C_PBP_128) | SM(R92C_PBP_PSTX, R92C_PBP_128));
3692 	return 0;
3693 }
3694 
3695 static int
3696 urtwn_r88e_dma_init(struct urtwn_softc *sc)
3697 {
3698 	usb_interface_descriptor_t *id;
3699 	uint32_t reg;
3700 	int nqueues;
3701 	int error;
3702 
3703 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
3704 
3705 	KASSERT(mutex_owned(&sc->sc_write_mtx));
3706 
3707 	/* Initialize LLT table. */
3708 	error = urtwn_llt_init(sc);
3709 	if (error != 0)
3710 		return error;
3711 
3712 	/* Get Tx queues to USB endpoints mapping. */
3713 	id = usbd_get_interface_descriptor(sc->sc_iface);
3714 	nqueues = id->bNumEndpoints - 1;
3715 	if (nqueues == 0)
3716 		return EIO;
3717 
3718 	/* Set number of pages for normal priority queue. */
3719 	urtwn_write_2(sc, R92C_RQPN_NPQ, 0);
3720 	urtwn_write_2(sc, R92C_RQPN_NPQ, 0x000d);
3721 	urtwn_write_4(sc, R92C_RQPN, 0x808e000d);
3722 
3723 	urtwn_write_1(sc, R92C_TXPKTBUF_BCNQ_BDNY, R88E_TX_PAGE_BOUNDARY);
3724 	urtwn_write_1(sc, R92C_TXPKTBUF_MGQ_BDNY, R88E_TX_PAGE_BOUNDARY);
3725 	urtwn_write_1(sc, R92C_TXPKTBUF_WMAC_LBK_BF_HD, R88E_TX_PAGE_BOUNDARY);
3726 	urtwn_write_1(sc, R92C_TRXFF_BNDY, R88E_TX_PAGE_BOUNDARY);
3727 	urtwn_write_1(sc, R92C_TDECTRL + 1, R88E_TX_PAGE_BOUNDARY);
3728 
3729 	/* Set queue to USB pipe mapping. */
3730 	reg = urtwn_read_2(sc, R92C_TRXDMA_CTRL);
3731 	reg &= ~R92C_TRXDMA_CTRL_QMAP_M;
3732 	if (nqueues == 1)
3733 		reg |= R92C_TRXDMA_CTRL_QMAP_LQ;
3734 	else if (nqueues == 2)
3735 		reg |= R92C_TRXDMA_CTRL_QMAP_HQ_NQ;
3736 	else
3737 		reg |= R92C_TRXDMA_CTRL_QMAP_3EP;
3738 	urtwn_write_2(sc, R92C_TRXDMA_CTRL, reg);
3739 
3740 	/* Set Tx/Rx transfer page boundary. */
3741 	urtwn_write_2(sc, R92C_TRXFF_BNDY + 2, 0x23ff);
3742 
3743 	/* Set Tx/Rx transfer page size. */
3744 	urtwn_write_1(sc, R92C_PBP,
3745 	    SM(R92C_PBP_PSRX, R92C_PBP_128) | SM(R92C_PBP_PSTX, R92C_PBP_128));
3746 
3747 	return 0;
3748 }
3749 
3750 static void __noinline
3751 urtwn_mac_init(struct urtwn_softc *sc)
3752 {
3753 	size_t i;
3754 
3755 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
3756 
3757 	KASSERT(mutex_owned(&sc->sc_write_mtx));
3758 
3759 	/* Write MAC initialization values. */
3760 	if (ISSET(sc->chip, URTWN_CHIP_88E)) {
3761 		for (i = 0; i < __arraycount(rtl8188eu_mac); i++)
3762 			urtwn_write_1(sc, rtl8188eu_mac[i].reg,
3763 			    rtl8188eu_mac[i].val);
3764 	} else if (ISSET(sc->chip, URTWN_CHIP_92EU)) {
3765 		for (i = 0; i < __arraycount(rtl8192eu_mac); i++)
3766 			urtwn_write_1(sc, rtl8192eu_mac[i].reg,
3767 			    rtl8192eu_mac[i].val);
3768 	} else {
3769 		for (i = 0; i < __arraycount(rtl8192cu_mac); i++)
3770 			urtwn_write_1(sc, rtl8192cu_mac[i].reg,
3771 			    rtl8192cu_mac[i].val);
3772 	}
3773 }
3774 
3775 static void __noinline
3776 urtwn_bb_init(struct urtwn_softc *sc)
3777 {
3778 	const struct rtwn_bb_prog *prog;
3779 	uint32_t reg;
3780 	uint8_t crystalcap;
3781 	size_t i;
3782 
3783 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
3784 
3785 	KASSERT(mutex_owned(&sc->sc_write_mtx));
3786 
3787 	/* Enable BB and RF. */
3788 	urtwn_write_2(sc, R92C_SYS_FUNC_EN,
3789 	    urtwn_read_2(sc, R92C_SYS_FUNC_EN) |
3790 	    R92C_SYS_FUNC_EN_BBRSTB | R92C_SYS_FUNC_EN_BB_GLB_RST |
3791 	    R92C_SYS_FUNC_EN_DIO_RF);
3792 
3793 	if (!ISSET(sc->chip, URTWN_CHIP_88E) &&
3794 	    !ISSET(sc->chip, URTWN_CHIP_92EU)) {
3795 		urtwn_write_1(sc, R92C_AFE_PLL_CTRL, 0x83);
3796 		urtwn_write_1(sc, R92C_AFE_PLL_CTRL + 1, 0xdb);
3797 	}
3798 
3799 	urtwn_write_1(sc, R92C_RF_CTRL,
3800 	    R92C_RF_CTRL_EN | R92C_RF_CTRL_RSTB | R92C_RF_CTRL_SDMRSTB);
3801 	urtwn_write_1(sc, R92C_SYS_FUNC_EN,
3802 	    R92C_SYS_FUNC_EN_USBA | R92C_SYS_FUNC_EN_USBD |
3803 	    R92C_SYS_FUNC_EN_BB_GLB_RST | R92C_SYS_FUNC_EN_BBRSTB);
3804 
3805 	if (!ISSET(sc->chip, URTWN_CHIP_88E) &&
3806 	    !ISSET(sc->chip, URTWN_CHIP_92EU)) {
3807 		urtwn_write_1(sc, R92C_LDOHCI12_CTRL, 0x0f);
3808 		urtwn_write_1(sc, 0x15, 0xe9);
3809 		urtwn_write_1(sc, R92C_AFE_XTAL_CTRL + 1, 0x80);
3810 	}
3811 
3812 	/* Select BB programming based on board type. */
3813 	if (ISSET(sc->chip, URTWN_CHIP_88E))
3814 		prog = &rtl8188eu_bb_prog;
3815 	else if (ISSET(sc->chip, URTWN_CHIP_92EU))
3816 		prog = &rtl8192eu_bb_prog;
3817 	else if (!(sc->chip & URTWN_CHIP_92C)) {
3818 		if (sc->board_type == R92C_BOARD_TYPE_MINICARD) {
3819 			prog = &rtl8188ce_bb_prog;
3820 		} else if (sc->board_type == R92C_BOARD_TYPE_HIGHPA) {
3821 			prog = &rtl8188ru_bb_prog;
3822 		} else {
3823 			prog = &rtl8188cu_bb_prog;
3824 		}
3825 	} else {
3826 		if (sc->board_type == R92C_BOARD_TYPE_MINICARD) {
3827 			prog = &rtl8192ce_bb_prog;
3828 		} else {
3829 			prog = &rtl8192cu_bb_prog;
3830 		}
3831 	}
3832 	/* Write BB initialization values. */
3833 	for (i = 0; i < prog->count; i++) {
3834 		/* additional delay depend on registers */
3835 		switch (prog->regs[i]) {
3836 		case 0xfe:
3837 			urtwn_delay_ms(sc, 50);
3838 			break;
3839 		case 0xfd:
3840 			urtwn_delay_ms(sc, 5);
3841 			break;
3842 		case 0xfc:
3843 			urtwn_delay_ms(sc, 1);
3844 			break;
3845 		case 0xfb:
3846 			DELAY(50);
3847 			break;
3848 		case 0xfa:
3849 			DELAY(5);
3850 			break;
3851 		case 0xf9:
3852 			DELAY(1);
3853 			break;
3854 		}
3855 		urtwn_bb_write(sc, prog->regs[i], prog->vals[i]);
3856 		DELAY(1);
3857 	}
3858 
3859 	if (sc->chip & URTWN_CHIP_92C_1T2R) {
3860 		/* 8192C 1T only configuration. */
3861 		reg = urtwn_bb_read(sc, R92C_FPGA0_TXINFO);
3862 		reg = (reg & ~0x00000003) | 0x2;
3863 		urtwn_bb_write(sc, R92C_FPGA0_TXINFO, reg);
3864 
3865 		reg = urtwn_bb_read(sc, R92C_FPGA1_TXINFO);
3866 		reg = (reg & ~0x00300033) | 0x00200022;
3867 		urtwn_bb_write(sc, R92C_FPGA1_TXINFO, reg);
3868 
3869 		reg = urtwn_bb_read(sc, R92C_CCK0_AFESETTING);
3870 		reg = (reg & ~0xff000000) | (0x45 << 24);
3871 		urtwn_bb_write(sc, R92C_CCK0_AFESETTING, reg);
3872 
3873 		reg = urtwn_bb_read(sc, R92C_OFDM0_TRXPATHENA);
3874 		reg = (reg & ~0x000000ff) | 0x23;
3875 		urtwn_bb_write(sc, R92C_OFDM0_TRXPATHENA, reg);
3876 
3877 		reg = urtwn_bb_read(sc, R92C_OFDM0_AGCPARAM1);
3878 		reg = (reg & ~0x00000030) | (1 << 4);
3879 		urtwn_bb_write(sc, R92C_OFDM0_AGCPARAM1, reg);
3880 
3881 		reg = urtwn_bb_read(sc, 0xe74);
3882 		reg = (reg & ~0x0c000000) | (2 << 26);
3883 		urtwn_bb_write(sc, 0xe74, reg);
3884 		reg = urtwn_bb_read(sc, 0xe78);
3885 		reg = (reg & ~0x0c000000) | (2 << 26);
3886 		urtwn_bb_write(sc, 0xe78, reg);
3887 		reg = urtwn_bb_read(sc, 0xe7c);
3888 		reg = (reg & ~0x0c000000) | (2 << 26);
3889 		urtwn_bb_write(sc, 0xe7c, reg);
3890 		reg = urtwn_bb_read(sc, 0xe80);
3891 		reg = (reg & ~0x0c000000) | (2 << 26);
3892 		urtwn_bb_write(sc, 0xe80, reg);
3893 		reg = urtwn_bb_read(sc, 0xe88);
3894 		reg = (reg & ~0x0c000000) | (2 << 26);
3895 		urtwn_bb_write(sc, 0xe88, reg);
3896 	}
3897 
3898 	/* Write AGC values. */
3899 	for (i = 0; i < prog->agccount; i++) {
3900 		urtwn_bb_write(sc, R92C_OFDM0_AGCRSSITABLE, prog->agcvals[i]);
3901 		DELAY(1);
3902 	}
3903 
3904 	if (ISSET(sc->chip, URTWN_CHIP_88E) ||
3905 	    ISSET(sc->chip, URTWN_CHIP_92EU)) {
3906 		urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), 0x69553422);
3907 		DELAY(1);
3908 		urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), 0x69553420);
3909 		DELAY(1);
3910 	}
3911 
3912 	if (ISSET(sc->chip, URTWN_CHIP_92EU)) {
3913 		crystalcap = sc->r88e_rom[0xb9];
3914 		if (crystalcap == 0x00)
3915 			crystalcap = 0x20;
3916 		crystalcap &= 0x3f;
3917 		reg = urtwn_bb_read(sc, R92C_AFE_CTRL3);
3918 		urtwn_bb_write(sc, R92C_AFE_CTRL3,
3919 		    RW(reg, R92C_AFE_XTAL_CTRL_ADDR,
3920 		    crystalcap | crystalcap << 6));
3921 		urtwn_write_4(sc, R92C_AFE_XTAL_CTRL, 0xf81fb);
3922 	} else if (ISSET(sc->chip, URTWN_CHIP_88E)) {
3923 		crystalcap = sc->r88e_rom[0xb9];
3924 		if (crystalcap == 0xff)
3925 			crystalcap = 0x20;
3926 		crystalcap &= 0x3f;
3927 		reg = urtwn_bb_read(sc, R92C_AFE_XTAL_CTRL);
3928 		urtwn_bb_write(sc, R92C_AFE_XTAL_CTRL,
3929 		    RW(reg, R92C_AFE_XTAL_CTRL_ADDR,
3930 		    crystalcap | crystalcap << 6));
3931 	} else {
3932 		if (urtwn_bb_read(sc, R92C_HSSI_PARAM2(0)) &
3933 		    R92C_HSSI_PARAM2_CCK_HIPWR) {
3934 			SET(sc->sc_flags, URTWN_FLAG_CCK_HIPWR);
3935 		}
3936 	}
3937 }
3938 
3939 static void __noinline
3940 urtwn_rf_init(struct urtwn_softc *sc)
3941 {
3942 	const struct rtwn_rf_prog *prog;
3943 	uint32_t reg, mask, saved;
3944 	size_t i, j, idx;
3945 
3946 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
3947 
3948 	/* Select RF programming based on board type. */
3949 	if (ISSET(sc->chip, URTWN_CHIP_88E))
3950 		prog = rtl8188eu_rf_prog;
3951 	else if (ISSET(sc->chip, URTWN_CHIP_92EU))
3952 		prog = rtl8192eu_rf_prog;
3953 	else if (!(sc->chip & URTWN_CHIP_92C)) {
3954 		if (sc->board_type == R92C_BOARD_TYPE_MINICARD) {
3955 			prog = rtl8188ce_rf_prog;
3956 		} else if (sc->board_type == R92C_BOARD_TYPE_HIGHPA) {
3957 			prog = rtl8188ru_rf_prog;
3958 		} else {
3959 			prog = rtl8188cu_rf_prog;
3960 		}
3961 	} else {
3962 		prog = rtl8192ce_rf_prog;
3963 	}
3964 
3965 	for (i = 0; i < sc->nrxchains; i++) {
3966 		/* Save RF_ENV control type. */
3967 		idx = i / 2;
3968 		mask = 0xffffU << ((i % 2) * 16);
3969 		saved = urtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(idx)) & mask;
3970 
3971 		/* Set RF_ENV enable. */
3972 		reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACEOE(i));
3973 		reg |= 0x100000;
3974 		urtwn_bb_write(sc, R92C_FPGA0_RFIFACEOE(i), reg);
3975 		DELAY(50);
3976 
3977 		/* Set RF_ENV output high. */
3978 		reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACEOE(i));
3979 		reg |= 0x10;
3980 		urtwn_bb_write(sc, R92C_FPGA0_RFIFACEOE(i), reg);
3981 		DELAY(50);
3982 
3983 		/* Set address and data lengths of RF registers. */
3984 		reg = urtwn_bb_read(sc, R92C_HSSI_PARAM2(i));
3985 		reg &= ~R92C_HSSI_PARAM2_ADDR_LENGTH;
3986 		urtwn_bb_write(sc, R92C_HSSI_PARAM2(i), reg);
3987 		DELAY(50);
3988 		reg = urtwn_bb_read(sc, R92C_HSSI_PARAM2(i));
3989 		reg &= ~R92C_HSSI_PARAM2_DATA_LENGTH;
3990 		urtwn_bb_write(sc, R92C_HSSI_PARAM2(i), reg);
3991 		DELAY(50);
3992 
3993 		/* Write RF initialization values for this chain. */
3994 		for (j = 0; j < prog[i].count; j++) {
3995 			if (prog[i].regs[j] >= 0xf9 &&
3996 			    prog[i].regs[j] <= 0xfe) {
3997 				/*
3998 				 * These are fake RF registers offsets that
3999 				 * indicate a delay is required.
4000 				 */
4001 				urtwn_delay_ms(sc, 50);
4002 				continue;
4003 			}
4004 			urtwn_rf_write(sc, i, prog[i].regs[j], prog[i].vals[j]);
4005 			DELAY(5);
4006 		}
4007 
4008 		/* Restore RF_ENV control type. */
4009 		reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(idx)) & ~mask;
4010 		urtwn_bb_write(sc, R92C_FPGA0_RFIFACESW(idx), reg | saved);
4011 	}
4012 
4013 	if ((sc->chip & (URTWN_CHIP_UMC_A_CUT | URTWN_CHIP_92C)) ==
4014 	    URTWN_CHIP_UMC_A_CUT) {
4015 		urtwn_rf_write(sc, 0, R92C_RF_RX_G1, 0x30255);
4016 		urtwn_rf_write(sc, 0, R92C_RF_RX_G2, 0x50a00);
4017 	}
4018 
4019 	/* Cache RF register CHNLBW. */
4020 	for (i = 0; i < 2; i++) {
4021 		sc->rf_chnlbw[i] = urtwn_rf_read(sc, i, R92C_RF_CHNLBW);
4022 	}
4023 }
4024 
4025 static void __noinline
4026 urtwn_cam_init(struct urtwn_softc *sc)
4027 {
4028 	uint32_t content, command;
4029 	uint8_t idx;
4030 	size_t i;
4031 
4032 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
4033 
4034 	KASSERT(mutex_owned(&sc->sc_write_mtx));
4035 	if (ISSET(sc->chip, URTWN_CHIP_92EU))
4036 		return;
4037 
4038 	for (idx = 0; idx < R92C_CAM_ENTRY_COUNT; idx++) {
4039 		content = (idx & 3)
4040 		    | (R92C_CAM_ALGO_AES << R92C_CAM_ALGO_S)
4041 		    | R92C_CAM_VALID;
4042 
4043 		command = R92C_CAMCMD_POLLING
4044 		    | R92C_CAMCMD_WRITE
4045 		    | R92C_CAM_CTL0(idx);
4046 
4047 		urtwn_write_4(sc, R92C_CAMWRITE, content);
4048 		urtwn_write_4(sc, R92C_CAMCMD, command);
4049 	}
4050 
4051 	for (idx = 0; idx < R92C_CAM_ENTRY_COUNT; idx++) {
4052 		for (i = 0; i < /* CAM_CONTENT_COUNT */ 8; i++) {
4053 			if (i == 0) {
4054 				content = (idx & 3)
4055 				    | (R92C_CAM_ALGO_AES << R92C_CAM_ALGO_S)
4056 				    | R92C_CAM_VALID;
4057 			} else {
4058 				content = 0;
4059 			}
4060 
4061 			command = R92C_CAMCMD_POLLING
4062 			    | R92C_CAMCMD_WRITE
4063 			    | R92C_CAM_CTL0(idx)
4064 			    | i;
4065 
4066 			urtwn_write_4(sc, R92C_CAMWRITE, content);
4067 			urtwn_write_4(sc, R92C_CAMCMD, command);
4068 		}
4069 	}
4070 
4071 	/* Invalidate all CAM entries. */
4072 	urtwn_write_4(sc, R92C_CAMCMD, R92C_CAMCMD_POLLING | R92C_CAMCMD_CLR);
4073 }
4074 
4075 static void __noinline
4076 urtwn_pa_bias_init(struct urtwn_softc *sc)
4077 {
4078 	uint8_t reg;
4079 	size_t i;
4080 
4081 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
4082 
4083 	KASSERT(mutex_owned(&sc->sc_write_mtx));
4084 
4085 	for (i = 0; i < sc->nrxchains; i++) {
4086 		if (sc->pa_setting & (1U << i))
4087 			continue;
4088 
4089 		urtwn_rf_write(sc, i, R92C_RF_IPA, 0x0f406);
4090 		urtwn_rf_write(sc, i, R92C_RF_IPA, 0x4f406);
4091 		urtwn_rf_write(sc, i, R92C_RF_IPA, 0x8f406);
4092 		urtwn_rf_write(sc, i, R92C_RF_IPA, 0xcf406);
4093 	}
4094 	if (!(sc->pa_setting & 0x10)) {
4095 		reg = urtwn_read_1(sc, 0x16);
4096 		reg = (reg & ~0xf0) | 0x90;
4097 		urtwn_write_1(sc, 0x16, reg);
4098 	}
4099 }
4100 
4101 static void __noinline
4102 urtwn_rxfilter_init(struct urtwn_softc *sc)
4103 {
4104 
4105 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
4106 
4107 	KASSERT(mutex_owned(&sc->sc_write_mtx));
4108 
4109 	/* Initialize Rx filter. */
4110 	/* TODO: use better filter for monitor mode. */
4111 	urtwn_write_4(sc, R92C_RCR,
4112 	    R92C_RCR_AAP | R92C_RCR_APM | R92C_RCR_AM | R92C_RCR_AB |
4113 	    R92C_RCR_APP_ICV | R92C_RCR_AMF | R92C_RCR_HTC_LOC_CTRL |
4114 	    R92C_RCR_APP_MIC | R92C_RCR_APP_PHYSTS);
4115 	/* Accept all multicast frames. */
4116 	urtwn_write_4(sc, R92C_MAR + 0, 0xffffffff);
4117 	urtwn_write_4(sc, R92C_MAR + 4, 0xffffffff);
4118 	/* Accept all management frames. */
4119 	urtwn_write_2(sc, R92C_RXFLTMAP0, 0xffff);
4120 	/* Reject all control frames. */
4121 	urtwn_write_2(sc, R92C_RXFLTMAP1, 0x0000);
4122 	/* Accept all data frames. */
4123 	urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
4124 }
4125 
4126 static void __noinline
4127 urtwn_edca_init(struct urtwn_softc *sc)
4128 {
4129 
4130 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
4131 
4132 	KASSERT(mutex_owned(&sc->sc_write_mtx));
4133 
4134 	/* set spec SIFS (used in NAV) */
4135 	urtwn_write_2(sc, R92C_SPEC_SIFS, 0x100a);
4136 	urtwn_write_2(sc, R92C_MAC_SPEC_SIFS, 0x100a);
4137 
4138 	/* set SIFS CCK/OFDM */
4139 	urtwn_write_2(sc, R92C_SIFS_CCK, 0x100a);
4140 	urtwn_write_2(sc, R92C_SIFS_OFDM, 0x100a);
4141 
4142 	/* TXOP */
4143 	urtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x005ea42b);
4144 	urtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a44f);
4145 	urtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005ea324);
4146 	urtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002fa226);
4147 }
4148 
4149 static void
4150 urtwn_write_txpower(struct urtwn_softc *sc, int chain,
4151     uint16_t power[URTWN_RIDX_COUNT])
4152 {
4153 	uint32_t reg;
4154 
4155 	URTWNHIST_FUNC();
4156 	URTWNHIST_CALLARGS("chain=%jd", chain, 0, 0, 0);
4157 
4158 	/* Write per-CCK rate Tx power. */
4159 	if (chain == 0) {
4160 		reg = urtwn_bb_read(sc, R92C_TXAGC_A_CCK1_MCS32);
4161 		reg = RW(reg, R92C_TXAGC_A_CCK1,  power[0]);
4162 		urtwn_bb_write(sc, R92C_TXAGC_A_CCK1_MCS32, reg);
4163 
4164 		reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK11_A_CCK2_11);
4165 		reg = RW(reg, R92C_TXAGC_A_CCK2,  power[1]);
4166 		reg = RW(reg, R92C_TXAGC_A_CCK55, power[2]);
4167 		reg = RW(reg, R92C_TXAGC_A_CCK11, power[3]);
4168 		urtwn_bb_write(sc, R92C_TXAGC_B_CCK11_A_CCK2_11, reg);
4169 	} else {
4170 		reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK1_55_MCS32);
4171 		reg = RW(reg, R92C_TXAGC_B_CCK1,  power[0]);
4172 		reg = RW(reg, R92C_TXAGC_B_CCK2,  power[1]);
4173 		reg = RW(reg, R92C_TXAGC_B_CCK55, power[2]);
4174 		urtwn_bb_write(sc, R92C_TXAGC_B_CCK1_55_MCS32, reg);
4175 
4176 		reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK11_A_CCK2_11);
4177 		reg = RW(reg, R92C_TXAGC_B_CCK11, power[3]);
4178 		urtwn_bb_write(sc, R92C_TXAGC_B_CCK11_A_CCK2_11, reg);
4179 	}
4180 	/* Write per-OFDM rate Tx power. */
4181 	urtwn_bb_write(sc, R92C_TXAGC_RATE18_06(chain),
4182 	    SM(R92C_TXAGC_RATE06, power[ 4]) |
4183 	    SM(R92C_TXAGC_RATE09, power[ 5]) |
4184 	    SM(R92C_TXAGC_RATE12, power[ 6]) |
4185 	    SM(R92C_TXAGC_RATE18, power[ 7]));
4186 	urtwn_bb_write(sc, R92C_TXAGC_RATE54_24(chain),
4187 	    SM(R92C_TXAGC_RATE24, power[ 8]) |
4188 	    SM(R92C_TXAGC_RATE36, power[ 9]) |
4189 	    SM(R92C_TXAGC_RATE48, power[10]) |
4190 	    SM(R92C_TXAGC_RATE54, power[11]));
4191 	/* Write per-MCS Tx power. */
4192 	urtwn_bb_write(sc, R92C_TXAGC_MCS03_MCS00(chain),
4193 	    SM(R92C_TXAGC_MCS00,  power[12]) |
4194 	    SM(R92C_TXAGC_MCS01,  power[13]) |
4195 	    SM(R92C_TXAGC_MCS02,  power[14]) |
4196 	    SM(R92C_TXAGC_MCS03,  power[15]));
4197 	urtwn_bb_write(sc, R92C_TXAGC_MCS07_MCS04(chain),
4198 	    SM(R92C_TXAGC_MCS04,  power[16]) |
4199 	    SM(R92C_TXAGC_MCS05,  power[17]) |
4200 	    SM(R92C_TXAGC_MCS06,  power[18]) |
4201 	    SM(R92C_TXAGC_MCS07,  power[19]));
4202 	urtwn_bb_write(sc, R92C_TXAGC_MCS11_MCS08(chain),
4203 	    SM(R92C_TXAGC_MCS08,  power[20]) |
4204 	    SM(R92C_TXAGC_MCS09,  power[21]) |
4205 	    SM(R92C_TXAGC_MCS10,  power[22]) |
4206 	    SM(R92C_TXAGC_MCS11,  power[23]));
4207 	urtwn_bb_write(sc, R92C_TXAGC_MCS15_MCS12(chain),
4208 	    SM(R92C_TXAGC_MCS12,  power[24]) |
4209 	    SM(R92C_TXAGC_MCS13,  power[25]) |
4210 	    SM(R92C_TXAGC_MCS14,  power[26]) |
4211 	    SM(R92C_TXAGC_MCS15,  power[27]));
4212 }
4213 
4214 static void
4215 urtwn_get_txpower(struct urtwn_softc *sc, size_t chain, u_int chan, u_int ht40m,
4216     uint16_t power[URTWN_RIDX_COUNT])
4217 {
4218 	struct r92c_rom *rom = &sc->rom;
4219 	uint16_t cckpow, ofdmpow, htpow, diff, maxpow;
4220 	const struct rtwn_txpwr *base;
4221 	int ridx, group;
4222 
4223 	URTWNHIST_FUNC();
4224 	URTWNHIST_CALLARGS("chain=%jd, chan=%jd", chain, chan, 0, 0);
4225 
4226 	/* Determine channel group. */
4227 	if (chan <= 3) {
4228 		group = 0;
4229 	} else if (chan <= 9) {
4230 		group = 1;
4231 	} else {
4232 		group = 2;
4233 	}
4234 
4235 	/* Get original Tx power based on board type and RF chain. */
4236 	if (!(sc->chip & URTWN_CHIP_92C)) {
4237 		if (sc->board_type == R92C_BOARD_TYPE_HIGHPA) {
4238 			base = &rtl8188ru_txagc[chain];
4239 		} else {
4240 			base = &rtl8192cu_txagc[chain];
4241 		}
4242 	} else {
4243 		base = &rtl8192cu_txagc[chain];
4244 	}
4245 
4246 	memset(power, 0, URTWN_RIDX_COUNT * sizeof(power[0]));
4247 	if (sc->regulatory == 0) {
4248 		for (ridx = 0; ridx <= 3; ridx++) {
4249 			power[ridx] = base->pwr[0][ridx];
4250 		}
4251 	}
4252 	for (ridx = 4; ridx < URTWN_RIDX_COUNT; ridx++) {
4253 		if (sc->regulatory == 3) {
4254 			power[ridx] = base->pwr[0][ridx];
4255 			/* Apply vendor limits. */
4256 			if (ht40m != IEEE80211_HTINFO_2NDCHAN_NONE) {
4257 				maxpow = rom->ht40_max_pwr[group];
4258 			} else {
4259 				maxpow = rom->ht20_max_pwr[group];
4260 			}
4261 			maxpow = (maxpow >> (chain * 4)) & 0xf;
4262 			if (power[ridx] > maxpow) {
4263 				power[ridx] = maxpow;
4264 			}
4265 		} else if (sc->regulatory == 1) {
4266 			if (ht40m == IEEE80211_HTINFO_2NDCHAN_NONE) {
4267 				power[ridx] = base->pwr[group][ridx];
4268 			}
4269 		} else if (sc->regulatory != 2) {
4270 			power[ridx] = base->pwr[0][ridx];
4271 		}
4272 	}
4273 
4274 	/* Compute per-CCK rate Tx power. */
4275 	cckpow = rom->cck_tx_pwr[chain][group];
4276 	for (ridx = 0; ridx <= 3; ridx++) {
4277 		power[ridx] += cckpow;
4278 		if (power[ridx] > R92C_MAX_TX_PWR) {
4279 			power[ridx] = R92C_MAX_TX_PWR;
4280 		}
4281 	}
4282 
4283 	htpow = rom->ht40_1s_tx_pwr[chain][group];
4284 	if (sc->ntxchains > 1) {
4285 		/* Apply reduction for 2 spatial streams. */
4286 		diff = rom->ht40_2s_tx_pwr_diff[group];
4287 		diff = (diff >> (chain * 4)) & 0xf;
4288 		htpow = (htpow > diff) ? htpow - diff : 0;
4289 	}
4290 
4291 	/* Compute per-OFDM rate Tx power. */
4292 	diff = rom->ofdm_tx_pwr_diff[group];
4293 	diff = (diff >> (chain * 4)) & 0xf;
4294 	ofdmpow = htpow + diff;	/* HT->OFDM correction. */
4295 	for (ridx = 4; ridx <= 11; ridx++) {
4296 		power[ridx] += ofdmpow;
4297 		if (power[ridx] > R92C_MAX_TX_PWR) {
4298 			power[ridx] = R92C_MAX_TX_PWR;
4299 		}
4300 	}
4301 
4302 	/* Compute per-MCS Tx power. */
4303 	if (ht40m == IEEE80211_HTINFO_2NDCHAN_NONE) {
4304 		diff = rom->ht20_tx_pwr_diff[group];
4305 		diff = (diff >> (chain * 4)) & 0xf;
4306 		htpow += diff;	/* HT40->HT20 correction. */
4307 	}
4308 	for (ridx = 12; ridx < URTWN_RIDX_COUNT; ridx++) {
4309 		power[ridx] += htpow;
4310 		if (power[ridx] > R92C_MAX_TX_PWR) {
4311 			power[ridx] = R92C_MAX_TX_PWR;
4312 		}
4313 	}
4314 #ifdef URTWN_DEBUG
4315 	if (urtwn_debug & DBG_RF) {
4316 		/* Dump per-rate Tx power values. */
4317 		DPRINTFN(DBG_RF, "Tx power for chain %jd:", chain, 0, 0, 0);
4318 		for (ridx = 0; ridx < URTWN_RIDX_COUNT; ridx++)
4319 			DPRINTFN(DBG_RF, "Rate %jd = %ju", ridx, power[ridx], 0, 0);
4320 	}
4321 #endif
4322 }
4323 
4324 void
4325 urtwn_r88e_get_txpower(struct urtwn_softc *sc, size_t chain, u_int chan,
4326     u_int ht40m, uint16_t power[URTWN_RIDX_COUNT])
4327 {
4328 	uint16_t cckpow, ofdmpow, bw20pow, htpow;
4329 	const struct rtwn_r88e_txpwr *base;
4330 	int ridx, group;
4331 
4332 	URTWNHIST_FUNC();
4333 	URTWNHIST_CALLARGS("chain=%jd, chan=%jd", chain, chan, 0, 0);
4334 
4335 	/* Determine channel group. */
4336 	if (chan <= 2)
4337 		group = 0;
4338 	else if (chan <= 5)
4339 		group = 1;
4340 	else if (chan <= 8)
4341 		group = 2;
4342 	else if (chan <= 11)
4343 		group = 3;
4344 	else if (chan <= 13)
4345 		group = 4;
4346 	else
4347 		group = 5;
4348 
4349 	/* Get original Tx power based on board type and RF chain. */
4350 	base = &rtl8188eu_txagc[chain];
4351 
4352 	memset(power, 0, URTWN_RIDX_COUNT * sizeof(power[0]));
4353 	if (sc->regulatory == 0) {
4354 		for (ridx = 0; ridx <= 3; ridx++)
4355 			power[ridx] = base->pwr[0][ridx];
4356 	}
4357 	for (ridx = 4; ridx < URTWN_RIDX_COUNT; ridx++) {
4358 		if (sc->regulatory == 3)
4359 			power[ridx] = base->pwr[0][ridx];
4360 		else if (sc->regulatory == 1) {
4361 			if (ht40m == IEEE80211_HTINFO_2NDCHAN_NONE)
4362 				power[ridx] = base->pwr[group][ridx];
4363 		} else if (sc->regulatory != 2)
4364 			power[ridx] = base->pwr[0][ridx];
4365 	}
4366 
4367 	/* Compute per-CCK rate Tx power. */
4368 	cckpow = sc->cck_tx_pwr[group];
4369 	for (ridx = 0; ridx <= 3; ridx++) {
4370 		power[ridx] += cckpow;
4371 		if (power[ridx] > R92C_MAX_TX_PWR)
4372 			power[ridx] = R92C_MAX_TX_PWR;
4373 	}
4374 
4375 	htpow = sc->ht40_tx_pwr[group];
4376 
4377 	/* Compute per-OFDM rate Tx power. */
4378 	ofdmpow = htpow + sc->ofdm_tx_pwr_diff;
4379 	for (ridx = 4; ridx <= 11; ridx++) {
4380 		power[ridx] += ofdmpow;
4381 		if (power[ridx] > R92C_MAX_TX_PWR)
4382 			power[ridx] = R92C_MAX_TX_PWR;
4383 	}
4384 
4385 	bw20pow = htpow + sc->bw20_tx_pwr_diff;
4386 	for (ridx = 12; ridx <= 27; ridx++) {
4387 		power[ridx] += bw20pow;
4388 		if (power[ridx] > R92C_MAX_TX_PWR)
4389 			power[ridx] = R92C_MAX_TX_PWR;
4390 	}
4391 }
4392 
4393 static void
4394 urtwn_set_txpower(struct urtwn_softc *sc, u_int chan, u_int ht40m)
4395 {
4396 	uint16_t power[URTWN_RIDX_COUNT];
4397 	size_t i;
4398 
4399 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
4400 
4401 	for (i = 0; i < sc->ntxchains; i++) {
4402 		/* Compute per-rate Tx power values. */
4403 		if (ISSET(sc->chip, URTWN_CHIP_88E) ||
4404 		    ISSET(sc->chip, URTWN_CHIP_92EU))
4405 			urtwn_r88e_get_txpower(sc, i, chan, ht40m, power);
4406 		else
4407 			urtwn_get_txpower(sc, i, chan, ht40m, power);
4408 		/* Write per-rate Tx power values to hardware. */
4409 		urtwn_write_txpower(sc, i, power);
4410 	}
4411 }
4412 
4413 static void __noinline
4414 urtwn_set_chan(struct urtwn_softc *sc, struct ieee80211_channel *c, u_int ht40m)
4415 {
4416 	struct ieee80211com *ic = &sc->sc_ic;
4417 	u_int chan;
4418 	size_t i;
4419 
4420 	chan = ieee80211_chan2ieee(ic, c);	/* XXX center freq! */
4421 
4422 	URTWNHIST_FUNC();
4423 	URTWNHIST_CALLARGS("chan=%jd", chan, 0, 0, 0);
4424 
4425 	KASSERT(mutex_owned(&sc->sc_write_mtx));
4426 
4427 	if (ht40m == IEEE80211_HTINFO_2NDCHAN_ABOVE) {
4428 		chan += 2;
4429 	} else if (ht40m == IEEE80211_HTINFO_2NDCHAN_BELOW){
4430 		chan -= 2;
4431 	}
4432 
4433 	/* Set Tx power for this new channel. */
4434 	urtwn_set_txpower(sc, chan, ht40m);
4435 
4436 	for (i = 0; i < sc->nrxchains; i++) {
4437 		urtwn_rf_write(sc, i, R92C_RF_CHNLBW,
4438 		    RW(sc->rf_chnlbw[i], R92C_RF_CHNLBW_CHNL, chan));
4439 	}
4440 
4441 	if (ht40m) {
4442 		/* Is secondary channel below or above primary? */
4443 		int prichlo = (ht40m == IEEE80211_HTINFO_2NDCHAN_ABOVE);
4444 		uint32_t reg;
4445 
4446 		urtwn_write_1(sc, R92C_BWOPMODE,
4447 		    urtwn_read_1(sc, R92C_BWOPMODE) & ~R92C_BWOPMODE_20MHZ);
4448 
4449 		reg = urtwn_read_1(sc, R92C_RRSR + 2);
4450 		reg = (reg & ~0x6f) | (prichlo ? 1 : 2) << 5;
4451 		urtwn_write_1(sc, R92C_RRSR + 2, (uint8_t)reg);
4452 
4453 		urtwn_bb_write(sc, R92C_FPGA0_RFMOD,
4454 		    urtwn_bb_read(sc, R92C_FPGA0_RFMOD) | R92C_RFMOD_40MHZ);
4455 		urtwn_bb_write(sc, R92C_FPGA1_RFMOD,
4456 		    urtwn_bb_read(sc, R92C_FPGA1_RFMOD) | R92C_RFMOD_40MHZ);
4457 
4458 		/* Set CCK side band. */
4459 		reg = urtwn_bb_read(sc, R92C_CCK0_SYSTEM);
4460 		reg = (reg & ~0x00000010) | (prichlo ? 0 : 1) << 4;
4461 		urtwn_bb_write(sc, R92C_CCK0_SYSTEM, reg);
4462 
4463 		reg = urtwn_bb_read(sc, R92C_OFDM1_LSTF);
4464 		reg = (reg & ~0x00000c00) | (prichlo ? 1 : 2) << 10;
4465 		urtwn_bb_write(sc, R92C_OFDM1_LSTF, reg);
4466 
4467 		urtwn_bb_write(sc, R92C_FPGA0_ANAPARAM2,
4468 		    urtwn_bb_read(sc, R92C_FPGA0_ANAPARAM2) &
4469 		    ~R92C_FPGA0_ANAPARAM2_CBW20);
4470 
4471 		reg = urtwn_bb_read(sc, 0x818);
4472 		reg = (reg & ~0x0c000000) | (prichlo ? 2 : 1) << 26;
4473 		urtwn_bb_write(sc, 0x818, reg);
4474 
4475 		/* Select 40MHz bandwidth. */
4476 		urtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
4477 		    (sc->rf_chnlbw[0] & ~0xfff) | chan);
4478 	} else {
4479 		urtwn_write_1(sc, R92C_BWOPMODE,
4480 		    urtwn_read_1(sc, R92C_BWOPMODE) | R92C_BWOPMODE_20MHZ);
4481 
4482 		urtwn_bb_write(sc, R92C_FPGA0_RFMOD,
4483 		    urtwn_bb_read(sc, R92C_FPGA0_RFMOD) & ~R92C_RFMOD_40MHZ);
4484 		urtwn_bb_write(sc, R92C_FPGA1_RFMOD,
4485 		    urtwn_bb_read(sc, R92C_FPGA1_RFMOD) & ~R92C_RFMOD_40MHZ);
4486 
4487 		if (!ISSET(sc->chip, URTWN_CHIP_88E) &&
4488 		    !ISSET(sc->chip, URTWN_CHIP_92EU)) {
4489 			urtwn_bb_write(sc, R92C_FPGA0_ANAPARAM2,
4490 			    urtwn_bb_read(sc, R92C_FPGA0_ANAPARAM2) |
4491 			    R92C_FPGA0_ANAPARAM2_CBW20);
4492 		}
4493 
4494 		/* Select 20MHz bandwidth. */
4495 		urtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
4496 		    (sc->rf_chnlbw[0] & ~0xfff) | chan |
4497 		    (ISSET(sc->chip, URTWN_CHIP_88E) ||
4498 		     ISSET(sc->chip, URTWN_CHIP_92EU) ?
4499 		      R88E_RF_CHNLBW_BW20 : R92C_RF_CHNLBW_BW20));
4500 	}
4501 }
4502 
4503 static void __noinline
4504 urtwn_iq_calib(struct urtwn_softc *sc, bool inited)
4505 {
4506 
4507 	URTWNHIST_FUNC();
4508 	URTWNHIST_CALLARGS("inited=%jd", inited, 0, 0, 0);
4509 
4510 	uint32_t addaBackup[16], iqkBackup[4], piMode;
4511 
4512 #ifdef notyet
4513 	uint32_t odfm0_agccore_regs[3];
4514 	uint32_t ant_regs[3];
4515 	uint32_t rf_regs[8];
4516 #endif
4517 	uint32_t reg0, reg1, reg2;
4518 	int i, attempt;
4519 
4520 #ifdef notyet
4521 	urtwn_write_1(sc, R92E_STBC_SETTING + 2, urtwn_read_1(sc,
4522 	    R92E_STBC_SETTING + 2));
4523 	urtwn_write_1(sc, R92C_ACLK_MON, 0);
4524 	/* Save AGCCORE regs. */
4525 	for (i = 0; i < sc->nrxchains; i++) {
4526 		odfm0_agccore_regs[i] = urtwn_read_4(sc,
4527 		    R92C_OFDM0_AGCCORE1(i));
4528 	}
4529 #endif
4530 	/* Save BB regs. */
4531 	reg0 = urtwn_bb_read(sc, R92C_OFDM0_TRXPATHENA);
4532 	reg1 = urtwn_bb_read(sc, R92C_OFDM0_TRMUXPAR);
4533 	reg2 = urtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(1));
4534 
4535 	/* Save adda regs to be restored when finished. */
4536 	for (i = 0; i < __arraycount(addaReg); i++)
4537 		addaBackup[i] = urtwn_bb_read(sc, addaReg[i]);
4538 	/* Save mac regs. */
4539 	iqkBackup[0] = urtwn_read_1(sc, R92C_TXPAUSE);
4540 	iqkBackup[1] = urtwn_read_1(sc, R92C_BCN_CTRL);
4541 	iqkBackup[2] = urtwn_read_1(sc, R92C_BCN_CTRL1);
4542 	iqkBackup[3] = urtwn_read_4(sc, R92C_GPIO_MUXCFG);
4543 
4544 #ifdef notyet
4545 	ant_regs[0] = urtwn_read_4(sc, R92C_CONFIG_ANT_A);
4546 	ant_regs[1] = urtwn_read_4(sc, R92C_CONFIG_ANT_B);
4547 
4548 	rf_regs[0] = urtwn_read_4(sc, R92C_FPGA0_RFIFACESW(0));
4549 	for (i = 0; i < sc->nrxchains; i++)
4550 		rf_regs[i+1] = urtwn_read_4(sc, R92C_FPGA0_RFIFACEOE(i));
4551 	reg4 = urtwn_read_4(sc, R92C_CCK0_AFESETTING);
4552 #endif
4553 
4554 	piMode = (urtwn_bb_read(sc, R92C_HSSI_PARAM1(0)) &
4555 	    R92C_HSSI_PARAM1_PI);
4556 	if (piMode == 0) {
4557 		urtwn_bb_write(sc, R92C_HSSI_PARAM1(0),
4558 		    urtwn_bb_read(sc, R92C_HSSI_PARAM1(0))|
4559 		    R92C_HSSI_PARAM1_PI);
4560 		urtwn_bb_write(sc, R92C_HSSI_PARAM1(1),
4561 		    urtwn_bb_read(sc, R92C_HSSI_PARAM1(1))|
4562 		    R92C_HSSI_PARAM1_PI);
4563 	}
4564 
4565 	attempt = 1;
4566 
4567 next_attempt:
4568 
4569 	/* Set mac regs for calibration. */
4570 	for (i = 0; i < __arraycount(addaReg); i++) {
4571 		urtwn_bb_write(sc, addaReg[i],
4572 		    addaReg[__arraycount(addaReg) - 1]);
4573 	}
4574 	urtwn_write_2(sc, R92C_CCK0_AFESETTING, urtwn_read_2(sc,
4575 	    R92C_CCK0_AFESETTING));
4576 	urtwn_write_2(sc, R92C_OFDM0_TRXPATHENA, R92C_IQK_TRXPATHENA);
4577 	urtwn_write_2(sc, R92C_OFDM0_TRMUXPAR, R92C_IQK_TRMUXPAR);
4578 	urtwn_write_2(sc, R92C_FPGA0_RFIFACESW(1), R92C_IQK_RFIFACESW1);
4579 	urtwn_write_4(sc, R92C_LSSI_PARAM(0), R92C_IQK_LSSI_PARAM);
4580 
4581 	if (sc->ntxchains > 1)
4582 		urtwn_bb_write(sc, R92C_LSSI_PARAM(1), R92C_IQK_LSSI_PARAM);
4583 
4584 	urtwn_write_1(sc, R92C_TXPAUSE, (~R92C_TXPAUSE_BCN) & R92C_TXPAUSE_ALL);
4585 	urtwn_write_1(sc, R92C_BCN_CTRL, (iqkBackup[1] &
4586 	    ~R92C_BCN_CTRL_EN_BCN));
4587 	urtwn_write_1(sc, R92C_BCN_CTRL1, (iqkBackup[2] &
4588 	    ~R92C_BCN_CTRL_EN_BCN));
4589 
4590 	urtwn_write_1(sc, R92C_GPIO_MUXCFG, (iqkBackup[3] &
4591 	    ~R92C_GPIO_MUXCFG_ENBT));
4592 
4593 	urtwn_bb_write(sc, R92C_CONFIG_ANT_A, R92C_IQK_CONFIG_ANT);
4594 
4595 	if (sc->ntxchains > 1)
4596 		urtwn_bb_write(sc, R92C_CONFIG_ANT_B, R92C_IQK_CONFIG_ANT);
4597 	urtwn_bb_write(sc, R92C_FPGA0_IQK, R92C_FPGA0_IQK_SETTING);
4598 	urtwn_bb_write(sc, R92C_TX_IQK, R92C_TX_IQK_SETTING);
4599 	urtwn_bb_write(sc, R92C_RX_IQK, R92C_RX_IQK_SETTING);
4600 
4601 	/* Restore BB regs. */
4602 	urtwn_bb_write(sc, R92C_OFDM0_TRXPATHENA, reg0);
4603 	urtwn_bb_write(sc, R92C_FPGA0_RFIFACESW(1), reg2);
4604 	urtwn_bb_write(sc, R92C_OFDM0_TRMUXPAR, reg1);
4605 
4606 	urtwn_bb_write(sc, R92C_FPGA0_IQK, 0x0);
4607 	urtwn_bb_write(sc, R92C_LSSI_PARAM(0), R92C_IQK_LSSI_RESTORE);
4608 	if (sc->nrxchains > 1)
4609 		urtwn_bb_write(sc, R92C_LSSI_PARAM(1), R92C_IQK_LSSI_RESTORE);
4610 
4611 	if (attempt-- > 0)
4612 		goto next_attempt;
4613 
4614 	/* Restore mode. */
4615 	if (piMode == 0) {
4616 		urtwn_bb_write(sc, R92C_HSSI_PARAM1(0),
4617 		    urtwn_bb_read(sc, R92C_HSSI_PARAM1(0)) &
4618 		    ~R92C_HSSI_PARAM1_PI);
4619 		urtwn_bb_write(sc, R92C_HSSI_PARAM1(1),
4620 		    urtwn_bb_read(sc, R92C_HSSI_PARAM1(1)) &
4621 		    ~R92C_HSSI_PARAM1_PI);
4622 	}
4623 
4624 #ifdef notyet
4625 	for (i = 0; i < sc->nrxchains; i++) {
4626 		urtwn_write_4(sc, R92C_OFDM0_AGCCORE1(i),
4627 		    odfm0_agccore_regs[i]);
4628 	}
4629 #endif
4630 
4631 	/* Restore adda regs. */
4632 	for (i = 0; i < __arraycount(addaReg); i++)
4633 		urtwn_bb_write(sc, addaReg[i], addaBackup[i]);
4634 	/* Restore mac regs. */
4635 	urtwn_write_1(sc, R92C_TXPAUSE, iqkBackup[0]);
4636 	urtwn_write_1(sc, R92C_BCN_CTRL, iqkBackup[1]);
4637 	urtwn_write_1(sc, R92C_USTIME_TSF, iqkBackup[2]);
4638 	urtwn_write_4(sc, R92C_GPIO_MUXCFG, iqkBackup[3]);
4639 
4640 #ifdef notyet
4641 	urtwn_write_4(sc, R92C_CONFIG_ANT_A, ant_regs[0]);
4642 	urtwn_write_4(sc, R92C_CONFIG_ANT_B, ant_regs[1]);
4643 
4644 	urtwn_write_4(sc, R92C_FPGA0_RFIFACESW(0), rf_regs[0]);
4645 	for (i = 0; i < sc->nrxchains; i++)
4646 		urtwn_write_4(sc, R92C_FPGA0_RFIFACEOE(i), rf_regs[i+1]);
4647 	urtwn_write_4(sc, R92C_CCK0_AFESETTING, reg4);
4648 #endif
4649 }
4650 
4651 static void
4652 urtwn_lc_calib(struct urtwn_softc *sc)
4653 {
4654 	uint32_t rf_ac[2];
4655 	uint8_t txmode;
4656 	size_t i;
4657 
4658 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
4659 
4660 	KASSERT(mutex_owned(&sc->sc_write_mtx));
4661 
4662 	txmode = urtwn_read_1(sc, R92C_OFDM1_LSTF + 3);
4663 	if ((txmode & 0x70) != 0) {
4664 		/* Disable all continuous Tx. */
4665 		urtwn_write_1(sc, R92C_OFDM1_LSTF + 3, txmode & ~0x70);
4666 
4667 		/* Set RF mode to standby mode. */
4668 		for (i = 0; i < sc->nrxchains; i++) {
4669 			rf_ac[i] = urtwn_rf_read(sc, i, R92C_RF_AC);
4670 			urtwn_rf_write(sc, i, R92C_RF_AC,
4671 			    RW(rf_ac[i], R92C_RF_AC_MODE,
4672 				R92C_RF_AC_MODE_STANDBY));
4673 		}
4674 	} else {
4675 		/* Block all Tx queues. */
4676 		urtwn_write_1(sc, R92C_TXPAUSE, 0xff);
4677 	}
4678 	/* Start calibration. */
4679 	urtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
4680 	    urtwn_rf_read(sc, 0, R92C_RF_CHNLBW) | R92C_RF_CHNLBW_LCSTART);
4681 
4682 	/* Give calibration the time to complete. */
4683 	urtwn_delay_ms(sc, 100);
4684 
4685 	/* Restore configuration. */
4686 	if ((txmode & 0x70) != 0) {
4687 		/* Restore Tx mode. */
4688 		urtwn_write_1(sc, R92C_OFDM1_LSTF + 3, txmode);
4689 		/* Restore RF mode. */
4690 		for (i = 0; i < sc->nrxchains; i++) {
4691 			urtwn_rf_write(sc, i, R92C_RF_AC, rf_ac[i]);
4692 		}
4693 	} else {
4694 		/* Unblock all Tx queues. */
4695 		urtwn_write_1(sc, R92C_TXPAUSE, 0x00);
4696 	}
4697 }
4698 
4699 static void
4700 urtwn_temp_calib(struct urtwn_softc *sc)
4701 {
4702 	int temp, t_meter_reg;
4703 
4704 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
4705 
4706 	KASSERT(mutex_owned(&sc->sc_write_mtx));
4707 
4708 	if (!ISSET(sc->chip, URTWN_CHIP_92EU))
4709 		t_meter_reg = R92C_RF_T_METER;
4710 	else
4711 		t_meter_reg = R92E_RF_T_METER;
4712 
4713 	if (sc->thcal_state == 0) {
4714 		/* Start measuring temperature. */
4715 		DPRINTFN(DBG_RF, "start measuring temperature", 0, 0, 0, 0);
4716 		urtwn_rf_write(sc, 0, t_meter_reg, 0x60);
4717 		sc->thcal_state = 1;
4718 		return;
4719 	}
4720 	sc->thcal_state = 0;
4721 
4722 	/* Read measured temperature. */
4723 	temp = urtwn_rf_read(sc, 0, R92C_RF_T_METER) & 0x1f;
4724 	DPRINTFN(DBG_RF, "temperature=%jd", temp, 0, 0, 0);
4725 	if (temp == 0)		/* Read failed, skip. */
4726 		return;
4727 
4728 	/*
4729 	 * Redo LC calibration if temperature changed significantly since
4730 	 * last calibration.
4731 	 */
4732 	if (sc->thcal_lctemp == 0) {
4733 		/* First LC calibration is performed in urtwn_init(). */
4734 		sc->thcal_lctemp = temp;
4735 	} else if (abs(temp - sc->thcal_lctemp) > 1) {
4736 		DPRINTFN(DBG_RF, "LC calib triggered by temp: %jd -> %jd",
4737 		    sc->thcal_lctemp, temp, 0, 0);
4738 		urtwn_lc_calib(sc);
4739 		/* Record temperature of last LC calibration. */
4740 		sc->thcal_lctemp = temp;
4741 	}
4742 }
4743 
4744 static int
4745 urtwn_init(struct ifnet *ifp)
4746 {
4747 	struct urtwn_softc *sc = ifp->if_softc;
4748 	struct ieee80211com *ic = &sc->sc_ic;
4749 	struct urtwn_rx_data *data;
4750 	uint32_t reg;
4751 	size_t i;
4752 	int error;
4753 
4754 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
4755 
4756 	urtwn_stop(ifp, 0);
4757 
4758 	mutex_enter(&sc->sc_write_mtx);
4759 
4760 	mutex_enter(&sc->sc_task_mtx);
4761 	/* Init host async commands ring. */
4762 	sc->cmdq.cur = sc->cmdq.next = sc->cmdq.queued = 0;
4763 	mutex_exit(&sc->sc_task_mtx);
4764 
4765 	mutex_enter(&sc->sc_fwcmd_mtx);
4766 	/* Init firmware commands ring. */
4767 	sc->fwcur = 0;
4768 	mutex_exit(&sc->sc_fwcmd_mtx);
4769 
4770 	/* Allocate Tx/Rx buffers. */
4771 	error = urtwn_alloc_rx_list(sc);
4772 	if (error != 0) {
4773 		aprint_error_dev(sc->sc_dev,
4774 		    "could not allocate Rx buffers\n");
4775 		goto fail;
4776 	}
4777 	error = urtwn_alloc_tx_list(sc);
4778 	if (error != 0) {
4779 		aprint_error_dev(sc->sc_dev,
4780 		    "could not allocate Tx buffers\n");
4781 		goto fail;
4782 	}
4783 
4784 	/* Power on adapter. */
4785 	error = urtwn_power_on(sc);
4786 	if (error != 0)
4787 		goto fail;
4788 
4789 	/* Initialize DMA. */
4790 	error = urtwn_dma_init(sc);
4791 	if (error != 0)
4792 		goto fail;
4793 
4794 	/* Set info size in Rx descriptors (in 64-bit words). */
4795 	urtwn_write_1(sc, R92C_RX_DRVINFO_SZ, 4);
4796 
4797 	/* Init interrupts. */
4798 	if (ISSET(sc->chip, URTWN_CHIP_88E) ||
4799 	     ISSET(sc->chip, URTWN_CHIP_92EU)) {
4800 		urtwn_write_4(sc, R88E_HISR, 0xffffffff);
4801 		urtwn_write_4(sc, R88E_HIMR, R88E_HIMR_CPWM | R88E_HIMR_CPWM2 |
4802 		    R88E_HIMR_TBDER | R88E_HIMR_PSTIMEOUT);
4803 		urtwn_write_4(sc, R88E_HIMRE, R88E_HIMRE_RXFOVW |
4804 		    R88E_HIMRE_TXFOVW | R88E_HIMRE_RXERR | R88E_HIMRE_TXERR);
4805 		if (ISSET(sc->chip, URTWN_CHIP_88E)) {
4806 			urtwn_write_1(sc, R92C_USB_SPECIAL_OPTION,
4807 			    urtwn_read_1(sc, R92C_USB_SPECIAL_OPTION) |
4808 			      R92C_USB_SPECIAL_OPTION_INT_BULK_SEL);
4809 		}
4810 		if (ISSET(sc->chip, URTWN_CHIP_92EU))
4811 			urtwn_write_1(sc, R92C_USB_HRPWM, 0);
4812 	} else {
4813 		urtwn_write_4(sc, R92C_HISR, 0xffffffff);
4814 		urtwn_write_4(sc, R92C_HIMR, 0xffffffff);
4815 	}
4816 
4817 	/* Set MAC address. */
4818 	IEEE80211_ADDR_COPY(ic->ic_myaddr, CLLADDR(ifp->if_sadl));
4819 	urtwn_write_region(sc, R92C_MACID, ic->ic_myaddr, IEEE80211_ADDR_LEN);
4820 
4821 	/* Set initial network type. */
4822 	reg = urtwn_read_4(sc, R92C_CR);
4823 	switch (ic->ic_opmode) {
4824 	case IEEE80211_M_STA:
4825 	default:
4826 		reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_INFRA);
4827 		break;
4828 
4829 	case IEEE80211_M_IBSS:
4830 		reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_ADHOC);
4831 		break;
4832 	}
4833 	urtwn_write_4(sc, R92C_CR, reg);
4834 
4835 	/* Set response rate */
4836 	reg = urtwn_read_4(sc, R92C_RRSR);
4837 	reg = RW(reg, R92C_RRSR_RATE_BITMAP, R92C_RRSR_RATE_CCK_ONLY_1M);
4838 	urtwn_write_4(sc, R92C_RRSR, reg);
4839 
4840 	/* SIFS (used in NAV) */
4841 	urtwn_write_2(sc, R92C_SPEC_SIFS,
4842 	    SM(R92C_SPEC_SIFS_CCK, 0x10) | SM(R92C_SPEC_SIFS_OFDM, 0x10));
4843 
4844 	/* Set short/long retry limits. */
4845 	urtwn_write_2(sc, R92C_RL,
4846 	    SM(R92C_RL_SRL, 0x30) | SM(R92C_RL_LRL, 0x30));
4847 
4848 	/* Initialize EDCA parameters. */
4849 	urtwn_edca_init(sc);
4850 
4851 	/* Setup rate fallback. */
4852 	if (!ISSET(sc->chip, URTWN_CHIP_88E) &&
4853 	    !ISSET(sc->chip, URTWN_CHIP_92EU)) {
4854 		urtwn_write_4(sc, R92C_DARFRC + 0, 0x00000000);
4855 		urtwn_write_4(sc, R92C_DARFRC + 4, 0x10080404);
4856 		urtwn_write_4(sc, R92C_RARFRC + 0, 0x04030201);
4857 		urtwn_write_4(sc, R92C_RARFRC + 4, 0x08070605);
4858 	}
4859 
4860 	urtwn_write_1(sc, R92C_FWHW_TXQ_CTRL,
4861 	    urtwn_read_1(sc, R92C_FWHW_TXQ_CTRL) |
4862 	    R92C_FWHW_TXQ_CTRL_AMPDU_RTY_NEW);
4863 	/* Set ACK timeout. */
4864 	urtwn_write_1(sc, R92C_ACKTO, 0x40);
4865 
4866 	/* Setup USB aggregation. */
4867 	/* Tx */
4868 	reg = urtwn_read_4(sc, R92C_TDECTRL);
4869 	reg = RW(reg, R92C_TDECTRL_BLK_DESC_NUM, 6);
4870 	urtwn_write_4(sc, R92C_TDECTRL, reg);
4871 	/* Rx */
4872 	urtwn_write_1(sc, R92C_TRXDMA_CTRL,
4873 	    urtwn_read_1(sc, R92C_TRXDMA_CTRL) |
4874 	      R92C_TRXDMA_CTRL_RXDMA_AGG_EN);
4875 	urtwn_write_1(sc, R92C_USB_SPECIAL_OPTION,
4876 	    urtwn_read_1(sc, R92C_USB_SPECIAL_OPTION) &
4877 	      ~R92C_USB_SPECIAL_OPTION_AGG_EN);
4878 	urtwn_write_1(sc, R92C_RXDMA_AGG_PG_TH, 48);
4879 	if (ISSET(sc->chip, URTWN_CHIP_88E) ||
4880 	    ISSET(sc->chip, URTWN_CHIP_92EU))
4881 		urtwn_write_1(sc, R92C_RXDMA_AGG_PG_TH + 1, 4);
4882 	else
4883 		urtwn_write_1(sc, R92C_USB_DMA_AGG_TO, 4);
4884 
4885 	/* Initialize beacon parameters. */
4886 	urtwn_write_2(sc, R92C_BCN_CTRL, 0x1010);
4887 	urtwn_write_2(sc, R92C_TBTT_PROHIBIT, 0x6404);
4888 	urtwn_write_1(sc, R92C_DRVERLYINT, R92C_DRVERLYINT_INIT_TIME);
4889 	urtwn_write_1(sc, R92C_BCNDMATIM, R92C_BCNDMATIM_INIT_TIME);
4890 	urtwn_write_2(sc, R92C_BCNTCFG, 0x660f);
4891 
4892 	if (!ISSET(sc->chip, URTWN_CHIP_88E) &&
4893 	    !ISSET(sc->chip, URTWN_CHIP_92EU)) {
4894 		/* Setup AMPDU aggregation. */
4895 		urtwn_write_4(sc, R92C_AGGLEN_LMT, 0x99997631);	/* MCS7~0 */
4896 		urtwn_write_1(sc, R92C_AGGR_BREAK_TIME, 0x16);
4897 		urtwn_write_2(sc, 0x4ca, 0x0708);
4898 
4899 		urtwn_write_1(sc, R92C_BCN_MAX_ERR, 0xff);
4900 		urtwn_write_1(sc, R92C_BCN_CTRL, R92C_BCN_CTRL_DIS_TSF_UDT0);
4901 	}
4902 
4903 	/* Load 8051 microcode. */
4904 	error = urtwn_load_firmware(sc);
4905 	if (error != 0)
4906 		goto fail;
4907 	SET(sc->sc_flags, URTWN_FLAG_FWREADY);
4908 
4909 	/* Initialize MAC/BB/RF blocks. */
4910 	/*
4911 	 * XXX: urtwn_mac_init() sets R92C_RCR[0:15] = R92C_RCR_APM |
4912 	 * R92C_RCR_AM | R92C_RCR_AB | R92C_RCR_AICV | R92C_RCR_AMF.
4913 	 * XXX: This setting should be removed from rtl8192cu_mac[].
4914 	 */
4915 	urtwn_mac_init(sc);		// sets R92C_RCR[0:15]
4916 	urtwn_rxfilter_init(sc);	// reset R92C_RCR
4917 	urtwn_bb_init(sc);
4918 	urtwn_rf_init(sc);
4919 
4920 	if (ISSET(sc->chip, URTWN_CHIP_88E) ||
4921 	    ISSET(sc->chip, URTWN_CHIP_92EU)) {
4922 		urtwn_write_2(sc, R92C_CR,
4923 		    urtwn_read_2(sc, R92C_CR) | R92C_CR_MACTXEN |
4924 		      R92C_CR_MACRXEN);
4925 	}
4926 
4927 	/* Turn CCK and OFDM blocks on. */
4928 	reg = urtwn_bb_read(sc, R92C_FPGA0_RFMOD);
4929 	reg |= R92C_RFMOD_CCK_EN;
4930 	urtwn_bb_write(sc, R92C_FPGA0_RFMOD, reg);
4931 	reg = urtwn_bb_read(sc, R92C_FPGA0_RFMOD);
4932 	reg |= R92C_RFMOD_OFDM_EN;
4933 	urtwn_bb_write(sc, R92C_FPGA0_RFMOD, reg);
4934 
4935 	/* Clear per-station keys table. */
4936 	urtwn_cam_init(sc);
4937 
4938 	/* Enable hardware sequence numbering. */
4939 	urtwn_write_1(sc, R92C_HWSEQ_CTRL, 0xff);
4940 
4941 	/* Perform LO and IQ calibrations. */
4942 	urtwn_iq_calib(sc, sc->iqk_inited);
4943 	sc->iqk_inited = true;
4944 
4945 	/* Perform LC calibration. */
4946 	urtwn_lc_calib(sc);
4947 
4948 	if (!ISSET(sc->chip, URTWN_CHIP_88E) &&
4949 	    !ISSET(sc->chip, URTWN_CHIP_92EU)) {
4950 		/* Fix USB interference issue. */
4951 		urtwn_write_1(sc, 0xfe40, 0xe0);
4952 		urtwn_write_1(sc, 0xfe41, 0x8d);
4953 		urtwn_write_1(sc, 0xfe42, 0x80);
4954 		urtwn_write_4(sc, 0x20c, 0xfd0320);
4955 
4956 		urtwn_pa_bias_init(sc);
4957 	}
4958 
4959 	if (!(sc->chip & (URTWN_CHIP_92C | URTWN_CHIP_92C_1T2R)) ||
4960 	    !(sc->chip & URTWN_CHIP_92EU)) {
4961 		/* 1T1R */
4962 		urtwn_bb_write(sc, R92C_FPGA0_RFPARAM(0),
4963 		    urtwn_bb_read(sc, R92C_FPGA0_RFPARAM(0)) | __BIT(13));
4964 	}
4965 
4966 	/* Initialize GPIO setting. */
4967 	urtwn_write_1(sc, R92C_GPIO_MUXCFG,
4968 	    urtwn_read_1(sc, R92C_GPIO_MUXCFG) & ~R92C_GPIO_MUXCFG_ENBT);
4969 
4970 	/* Fix for lower temperature. */
4971 	if (!ISSET(sc->chip, URTWN_CHIP_88E) &&
4972 	    !ISSET(sc->chip, URTWN_CHIP_92EU))
4973 		urtwn_write_1(sc, 0x15, 0xe9);
4974 
4975 	/* Set default channel. */
4976 	urtwn_set_chan(sc, ic->ic_curchan, IEEE80211_HTINFO_2NDCHAN_NONE);
4977 
4978 	/* Queue Rx xfers. */
4979 	for (size_t j = 0; j < sc->rx_npipe; j++) {
4980 		for (i = 0; i < URTWN_RX_LIST_COUNT; i++) {
4981 			data = &sc->rx_data[j][i];
4982 			usbd_setup_xfer(data->xfer, data, data->buf,
4983 			    URTWN_RXBUFSZ, USBD_SHORT_XFER_OK, USBD_NO_TIMEOUT,
4984 			    urtwn_rxeof);
4985 			error = usbd_transfer(data->xfer);
4986 			if (__predict_false(error != USBD_NORMAL_COMPLETION &&
4987 			    error != USBD_IN_PROGRESS))
4988 				goto fail;
4989 		}
4990 	}
4991 
4992 	/* We're ready to go. */
4993 	ifp->if_flags &= ~IFF_OACTIVE;
4994 	ifp->if_flags |= IFF_RUNNING;
4995 	sc->sc_running = true;
4996 
4997 	mutex_exit(&sc->sc_write_mtx);
4998 
4999 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
5000 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
5001 	else if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
5002 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
5003 	urtwn_wait_async(sc);
5004 
5005 	return 0;
5006 
5007  fail:
5008 	mutex_exit(&sc->sc_write_mtx);
5009 
5010 	urtwn_stop(ifp, 1);
5011 	return error;
5012 }
5013 
5014 static void __noinline
5015 urtwn_stop(struct ifnet *ifp, int disable)
5016 {
5017 	struct urtwn_softc *sc = ifp->if_softc;
5018 	struct ieee80211com *ic = &sc->sc_ic;
5019 	size_t i;
5020 	int s;
5021 
5022 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
5023 
5024 	s = splusb();
5025 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
5026 	urtwn_wait_async(sc);
5027 	splx(s);
5028 
5029 	sc->tx_timer = 0;
5030 	ifp->if_timer = 0;
5031 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
5032 
5033 	callout_stop(&sc->sc_scan_to);
5034 	callout_stop(&sc->sc_calib_to);
5035 
5036 	/* Abort Tx. */
5037 	for (i = 0; i < sc->tx_npipe; i++) {
5038 		if (sc->tx_pipe[i] != NULL)
5039 			usbd_abort_pipe(sc->tx_pipe[i]);
5040 	}
5041 
5042 	/* Stop Rx pipe. */
5043 	for (i = 0; i < sc->rx_npipe; i++) {
5044 		if (sc->rx_pipe[i] != NULL)
5045 			usbd_abort_pipe(sc->rx_pipe[i]);
5046 	}
5047 
5048 	/* Free Tx/Rx buffers. */
5049 	urtwn_free_tx_list(sc);
5050 	urtwn_free_rx_list(sc);
5051 
5052 	sc->sc_running = false;
5053 	if (disable)
5054 		urtwn_chip_stop(sc);
5055 }
5056 
5057 static int
5058 urtwn_reset(struct ifnet *ifp)
5059 {
5060 	struct urtwn_softc *sc = ifp->if_softc;
5061 	struct ieee80211com *ic = &sc->sc_ic;
5062 
5063 	if (ic->ic_opmode != IEEE80211_M_MONITOR)
5064 		return ENETRESET;
5065 
5066 	urtwn_set_chan(sc, ic->ic_curchan, IEEE80211_HTINFO_2NDCHAN_NONE);
5067 
5068 	return 0;
5069 }
5070 
5071 static void
5072 urtwn_chip_stop(struct urtwn_softc *sc)
5073 {
5074 	uint32_t reg;
5075 	bool disabled = true;
5076 
5077 	URTWNHIST_FUNC(); URTWNHIST_CALLED();
5078 
5079 	if (ISSET(sc->chip, URTWN_CHIP_88E) ||
5080 	    ISSET(sc->chip, URTWN_CHIP_92EU))
5081 		return;
5082 
5083 	mutex_enter(&sc->sc_write_mtx);
5084 
5085 	/*
5086 	 * RF Off Sequence
5087 	 */
5088 	/* Pause MAC TX queue */
5089 	urtwn_write_1(sc, R92C_TXPAUSE, 0xFF);
5090 
5091 	/* Disable RF */
5092 	urtwn_rf_write(sc, 0, 0, 0);
5093 
5094 	urtwn_write_1(sc, R92C_APSD_CTRL, R92C_APSD_CTRL_OFF);
5095 
5096 	/* Reset BB state machine */
5097 	urtwn_write_1(sc, R92C_SYS_FUNC_EN,
5098 	    R92C_SYS_FUNC_EN_USBD |
5099 	    R92C_SYS_FUNC_EN_USBA |
5100 	    R92C_SYS_FUNC_EN_BB_GLB_RST);
5101 	urtwn_write_1(sc, R92C_SYS_FUNC_EN,
5102 	    R92C_SYS_FUNC_EN_USBD | R92C_SYS_FUNC_EN_USBA);
5103 
5104 	/*
5105 	 * Reset digital sequence
5106 	 */
5107 	if (urtwn_read_1(sc, R92C_MCUFWDL) & R92C_MCUFWDL_RDY) {
5108 		/* Reset MCU ready status */
5109 		urtwn_write_1(sc, R92C_MCUFWDL, 0);
5110 		/* If firmware in ram code, do reset */
5111 		if (ISSET(sc->sc_flags, URTWN_FLAG_FWREADY)) {
5112 			if (ISSET(sc->chip, URTWN_CHIP_88E) ||
5113 			    ISSET(sc->chip, URTWN_CHIP_92EU))
5114 				urtwn_r88e_fw_reset(sc);
5115 			else
5116 				urtwn_fw_reset(sc);
5117 			CLR(sc->sc_flags, URTWN_FLAG_FWREADY);
5118 		}
5119 	}
5120 
5121 	/* Reset MAC and Enable 8051 */
5122 	urtwn_write_1(sc, R92C_SYS_FUNC_EN + 1, 0x54);
5123 
5124 	/* Reset MCU ready status */
5125 	urtwn_write_1(sc, R92C_MCUFWDL, 0);
5126 
5127 	if (disabled) {
5128 		/* Disable MAC clock */
5129 		urtwn_write_2(sc, R92C_SYS_CLKR, 0x70A3);
5130 		/* Disable AFE PLL */
5131 		urtwn_write_1(sc, R92C_AFE_PLL_CTRL, 0x80);
5132 		/* Gated AFE DIG_CLOCK */
5133 		urtwn_write_2(sc, R92C_AFE_XTAL_CTRL, 0x880F);
5134 		/* Isolated digital to PON */
5135 		urtwn_write_1(sc, R92C_SYS_ISO_CTRL, 0xF9);
5136 	}
5137 
5138 	/*
5139 	 * Pull GPIO PIN to balance level and LED control
5140 	 */
5141 	/* 1. Disable GPIO[7:0] */
5142 	urtwn_write_2(sc, R92C_GPIO_PIN_CTRL + 2, 0x0000);
5143 
5144 	reg = urtwn_read_4(sc, R92C_GPIO_PIN_CTRL) & ~0x0000ff00;
5145 	reg |= ((reg << 8) & 0x0000ff00) | 0x00ff0000;
5146 	urtwn_write_4(sc, R92C_GPIO_PIN_CTRL, reg);
5147 
5148 	/* Disable GPIO[10:8] */
5149 	urtwn_write_1(sc, R92C_GPIO_MUXCFG + 3, 0x00);
5150 
5151 	reg = urtwn_read_2(sc, R92C_GPIO_MUXCFG + 2) & ~0x00f0;
5152 	reg |= (((reg & 0x000f) << 4) | 0x0780);
5153 	urtwn_write_2(sc, R92C_GPIO_MUXCFG + 2, reg);
5154 
5155 	/* Disable LED0 & 1 */
5156 	urtwn_write_2(sc, R92C_LEDCFG0, 0x8080);
5157 
5158 	/*
5159 	 * Reset digital sequence
5160 	 */
5161 	if (disabled) {
5162 		/* Disable ELDR clock */
5163 		urtwn_write_2(sc, R92C_SYS_CLKR, 0x70A3);
5164 		/* Isolated ELDR to PON */
5165 		urtwn_write_1(sc, R92C_SYS_ISO_CTRL + 1, 0x82);
5166 	}
5167 
5168 	/*
5169 	 * Disable analog sequence
5170 	 */
5171 	if (disabled) {
5172 		/* Disable A15 power */
5173 		urtwn_write_1(sc, R92C_LDOA15_CTRL, 0x04);
5174 		/* Disable digital core power */
5175 		urtwn_write_1(sc, R92C_LDOV12D_CTRL,
5176 		    urtwn_read_1(sc, R92C_LDOV12D_CTRL) &
5177 		      ~R92C_LDOV12D_CTRL_LDV12_EN);
5178 	}
5179 
5180 	/* Enter PFM mode */
5181 	urtwn_write_1(sc, R92C_SPS0_CTRL, 0x23);
5182 
5183 	/* Set USB suspend */
5184 	urtwn_write_2(sc, R92C_APS_FSMCO,
5185 	    R92C_APS_FSMCO_APDM_HOST |
5186 	    R92C_APS_FSMCO_AFSM_HSUS |
5187 	    R92C_APS_FSMCO_PFM_ALDN);
5188 
5189 	urtwn_write_1(sc, R92C_RSV_CTRL, 0x0E);
5190 
5191 	mutex_exit(&sc->sc_write_mtx);
5192 }
5193 
5194 static void
5195 urtwn_delay_ms(struct urtwn_softc *sc, int ms)
5196 {
5197 	if (sc->sc_running == false)
5198 		DELAY(ms * 1000);
5199 	else
5200 		usbd_delay_ms(sc->sc_udev, ms);
5201 }
5202 
5203 MODULE(MODULE_CLASS_DRIVER, if_urtwn, NULL);
5204 
5205 #ifdef _MODULE
5206 #include "ioconf.c"
5207 #endif
5208 
5209 static int
5210 if_urtwn_modcmd(modcmd_t cmd, void *aux)
5211 {
5212 	int error = 0;
5213 
5214 	switch (cmd) {
5215 	case MODULE_CMD_INIT:
5216 #ifdef _MODULE
5217 		error = config_init_component(cfdriver_ioconf_urtwn,
5218 		    cfattach_ioconf_urtwn, cfdata_ioconf_urtwn);
5219 #endif
5220 		return error;
5221 	case MODULE_CMD_FINI:
5222 #ifdef _MODULE
5223 		error = config_fini_component(cfdriver_ioconf_urtwn,
5224 		    cfattach_ioconf_urtwn, cfdata_ioconf_urtwn);
5225 #endif
5226 		return error;
5227 	default:
5228 		return ENOTTY;
5229 	}
5230 }
5231