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