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