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