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