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