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