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