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