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