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