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