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