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