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