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