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