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