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