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