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