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