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