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