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