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