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