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