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