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