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