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