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