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