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