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