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