Home | History | Annotate | Line # | Download | only in ic
wi.c revision 1.247
      1 /*	$NetBSD: wi.c,v 1.247 2018/06/26 06:48:00 msaitoh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2004 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Charles M. Hannum.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1997, 1998, 1999
     34  *	Bill Paul <wpaul (at) ctr.columbia.edu>.  All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. All advertising materials mentioning features or use of this software
     45  *    must display the following acknowledgement:
     46  *	This product includes software developed by Bill Paul.
     47  * 4. Neither the name of the author nor the names of any co-contributors
     48  *    may be used to endorse or promote products derived from this software
     49  *    without specific prior written permission.
     50  *
     51  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
     52  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     53  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     54  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
     55  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     56  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     57  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     58  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     59  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     60  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
     61  * THE POSSIBILITY OF SUCH DAMAGE.
     62  */
     63 
     64 /*
     65  * Lucent WaveLAN/IEEE 802.11 PCMCIA driver for NetBSD.
     66  *
     67  * Original FreeBSD driver written by Bill Paul <wpaul (at) ctr.columbia.edu>
     68  * Electrical Engineering Department
     69  * Columbia University, New York City
     70  */
     71 
     72 /*
     73  * The WaveLAN/IEEE adapter is the second generation of the WaveLAN
     74  * from Lucent. Unlike the older cards, the new ones are programmed
     75  * entirely via a firmware-driven controller called the Hermes.
     76  * Unfortunately, Lucent will not release the Hermes programming manual
     77  * without an NDA (if at all). What they do release is an API library
     78  * called the HCF (Hardware Control Functions) which is supposed to
     79  * do the device-specific operations of a device driver for you. The
     80  * publically available version of the HCF library (the 'HCF Light') is
     81  * a) extremely gross, b) lacks certain features, particularly support
     82  * for 802.11 frames, and c) is contaminated by the GNU Public License.
     83  *
     84  * This driver does not use the HCF or HCF Light at all. Instead, it
     85  * programs the Hermes controller directly, using information gleaned
     86  * from the HCF Light code and corresponding documentation.
     87  *
     88  * This driver supports both the PCMCIA and ISA versions of the
     89  * WaveLAN/IEEE cards. Note however that the ISA card isn't really
     90  * anything of the sort: it's actually a PCMCIA bridge adapter
     91  * that fits into an ISA slot, into which a PCMCIA WaveLAN card is
     92  * inserted. Consequently, you need to use the pccard support for
     93  * both the ISA and PCMCIA adapters.
     94  */
     95 
     96 /*
     97  * FreeBSD driver ported to NetBSD by Bill Sommerfeld in the back of the
     98  * Oslo IETF plenary meeting.
     99  */
    100 
    101 #include <sys/cdefs.h>
    102 __KERNEL_RCSID(0, "$NetBSD: wi.c,v 1.247 2018/06/26 06:48:00 msaitoh Exp $");
    103 
    104 #define WI_HERMES_AUTOINC_WAR	/* Work around data write autoinc bug. */
    105 #define WI_HERMES_STATS_WAR	/* Work around stats counter bug. */
    106 #undef WI_HISTOGRAM
    107 #undef WI_RING_DEBUG
    108 #define STATIC static
    109 
    110 
    111 #include <sys/param.h>
    112 #include <sys/sysctl.h>
    113 #include <sys/systm.h>
    114 #include <sys/callout.h>
    115 #include <sys/device.h>
    116 #include <sys/socket.h>
    117 #include <sys/mbuf.h>
    118 #include <sys/ioctl.h>
    119 #include <sys/kernel.h>		/* for hz */
    120 #include <sys/proc.h>
    121 #include <sys/kauth.h>
    122 
    123 #include <net/if.h>
    124 #include <net/if_dl.h>
    125 #include <net/if_llc.h>
    126 #include <net/if_media.h>
    127 #include <net/if_ether.h>
    128 #include <net/route.h>
    129 #include <net/bpf.h>
    130 
    131 #include <net80211/ieee80211_netbsd.h>
    132 #include <net80211/ieee80211_var.h>
    133 #include <net80211/ieee80211_ioctl.h>
    134 #include <net80211/ieee80211_radiotap.h>
    135 #include <net80211/ieee80211_rssadapt.h>
    136 
    137 #include <sys/bus.h>
    138 #include <sys/intr.h>
    139 
    140 #include <dev/ic/wi_ieee.h>
    141 #include <dev/ic/wireg.h>
    142 #include <dev/ic/wivar.h>
    143 
    144 STATIC int  wi_init(struct ifnet *);
    145 STATIC void wi_stop(struct ifnet *, int);
    146 STATIC void wi_start(struct ifnet *);
    147 STATIC int  wi_reset(struct wi_softc *);
    148 STATIC void wi_watchdog(struct ifnet *);
    149 STATIC int  wi_ioctl(struct ifnet *, u_long, void *);
    150 STATIC int  wi_media_change(struct ifnet *);
    151 STATIC void wi_media_status(struct ifnet *, struct ifmediareq *);
    152 STATIC void wi_softintr(void *);
    153 
    154 static void wi_ioctl_init(struct wi_softc *);
    155 static int wi_ioctl_enter(struct wi_softc *);
    156 static void wi_ioctl_exit(struct wi_softc *);
    157 static void wi_ioctl_drain(struct wi_softc *);
    158 
    159 STATIC struct ieee80211_node *wi_node_alloc(struct ieee80211_node_table *);
    160 STATIC void wi_node_free(struct ieee80211_node *);
    161 
    162 STATIC void wi_raise_rate(struct ieee80211com *, struct ieee80211_rssdesc *);
    163 STATIC void wi_lower_rate(struct ieee80211com *, struct ieee80211_rssdesc *);
    164 STATIC int wi_choose_rate(struct ieee80211com *, struct ieee80211_node *,
    165     struct ieee80211_frame *, u_int);
    166 STATIC void wi_rssadapt_updatestats_cb(void *, struct ieee80211_node *);
    167 STATIC void wi_rssadapt_updatestats(void *);
    168 STATIC void wi_rssdescs_init(struct wi_rssdesc (*)[], wi_rssdescq_t *);
    169 STATIC void wi_rssdescs_reset(struct ieee80211com *, struct wi_rssdesc (*)[],
    170     wi_rssdescq_t *, u_int8_t (*)[]);
    171 STATIC void wi_sync_bssid(struct wi_softc *, u_int8_t new_bssid[]);
    172 
    173 STATIC void wi_rx_intr(struct wi_softc *);
    174 STATIC void wi_txalloc_intr(struct wi_softc *);
    175 STATIC void wi_cmd_intr(struct wi_softc *);
    176 STATIC void wi_tx_intr(struct wi_softc *);
    177 STATIC void wi_tx_ex_intr(struct wi_softc *);
    178 STATIC void wi_info_intr(struct wi_softc *);
    179 
    180 STATIC int wi_key_delete(struct ieee80211com *, const struct ieee80211_key *);
    181 STATIC int wi_key_set(struct ieee80211com *, const struct ieee80211_key *,
    182     const u_int8_t[IEEE80211_ADDR_LEN]);
    183 STATIC void wi_key_update_begin(struct ieee80211com *);
    184 STATIC void wi_key_update_end(struct ieee80211com *);
    185 
    186 STATIC void wi_push_packet(struct wi_softc *);
    187 STATIC int  wi_get_cfg(struct ifnet *, u_long, void *);
    188 STATIC int  wi_set_cfg(struct ifnet *, u_long, void *);
    189 STATIC int  wi_cfg_txrate(struct wi_softc *);
    190 STATIC int  wi_write_txrate(struct wi_softc *, int);
    191 STATIC int  wi_write_wep(struct wi_softc *);
    192 STATIC int  wi_write_multi(struct wi_softc *);
    193 STATIC int  wi_alloc_fid(struct wi_softc *, int, int *);
    194 STATIC void wi_read_nicid(struct wi_softc *);
    195 STATIC int  wi_write_ssid(struct wi_softc *, int, u_int8_t *, int);
    196 
    197 STATIC int  wi_cmd(struct wi_softc *, int, int, int, int);
    198 STATIC int  wi_cmd_start(struct wi_softc *, int, int, int, int);
    199 STATIC int  wi_cmd_wait(struct wi_softc *, int, int);
    200 STATIC int  wi_seek_bap(struct wi_softc *, int, int);
    201 STATIC int  wi_read_bap(struct wi_softc *, int, int, void *, int);
    202 STATIC int  wi_write_bap(struct wi_softc *, int, int, void *, int);
    203 STATIC int  wi_mwrite_bap(struct wi_softc *, int, int, struct mbuf *, int);
    204 STATIC int  wi_read_rid(struct wi_softc *, int, void *, int *);
    205 STATIC int  wi_write_rid(struct wi_softc *, int, void *, int);
    206 
    207 STATIC int  wi_newstate(struct ieee80211com *, enum ieee80211_state, int);
    208 STATIC void  wi_set_tim(struct ieee80211_node *, int);
    209 
    210 STATIC int  wi_scan_ap(struct wi_softc *, u_int16_t, u_int16_t);
    211 STATIC void wi_scan_result(struct wi_softc *, int, int);
    212 
    213 STATIC void wi_dump_pkt(struct wi_frame *, struct ieee80211_node *, int rssi);
    214 STATIC void wi_mend_flags(struct wi_softc *, enum ieee80211_state);
    215 
    216 static inline int
    217 wi_write_val(struct wi_softc *sc, int rid, u_int16_t val)
    218 {
    219 
    220 	val = htole16(val);
    221 	return wi_write_rid(sc, rid, &val, sizeof(val));
    222 }
    223 
    224 static	struct timeval lasttxerror;	/* time of last tx error msg */
    225 static	int curtxeps = 0;		/* current tx error msgs/sec */
    226 static	int wi_txerate = 0;		/* tx error rate: max msgs/sec */
    227 
    228 #ifdef WI_DEBUG
    229 #define	WI_DEBUG_MAX	2
    230 int wi_debug = 0;
    231 
    232 #define	DPRINTF(X)	if (wi_debug) printf X
    233 #define	DPRINTF2(X)	if (wi_debug > 1) printf X
    234 #define	IFF_DUMPPKTS(_ifp) \
    235 	(((_ifp)->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
    236 static int wi_sysctl_verify_debug(SYSCTLFN_PROTO);
    237 #else
    238 #define	DPRINTF(X)
    239 #define	DPRINTF2(X)
    240 #define	IFF_DUMPPKTS(_ifp)	0
    241 #endif
    242 
    243 #define WI_INTRS	(WI_EV_RX | WI_EV_ALLOC | WI_EV_INFO | \
    244 			 WI_EV_TX | WI_EV_TX_EXC | WI_EV_CMD)
    245 
    246 static const struct wi_card_ident wi_card_ident[] = {
    247 	/* CARD_ID			CARD_NAME		FIRM_TYPE */
    248 	{ WI_NIC_LUCENT_ID,		WI_NIC_LUCENT_STR,	WI_LUCENT },
    249 	{ WI_NIC_SONY_ID,		WI_NIC_SONY_STR,	WI_LUCENT },
    250 	{ WI_NIC_LUCENT_EMB_ID,		WI_NIC_LUCENT_EMB_STR,	WI_LUCENT },
    251 	{ WI_NIC_EVB2_ID,		WI_NIC_EVB2_STR,	WI_INTERSIL },
    252 	{ WI_NIC_HWB3763_ID,		WI_NIC_HWB3763_STR,	WI_INTERSIL },
    253 	{ WI_NIC_HWB3163_ID,		WI_NIC_HWB3163_STR,	WI_INTERSIL },
    254 	{ WI_NIC_HWB3163B_ID,		WI_NIC_HWB3163B_STR,	WI_INTERSIL },
    255 	{ WI_NIC_EVB3_ID,		WI_NIC_EVB3_STR,	WI_INTERSIL },
    256 	{ WI_NIC_HWB1153_ID,		WI_NIC_HWB1153_STR,	WI_INTERSIL },
    257 	{ WI_NIC_P2_SST_ID,		WI_NIC_P2_SST_STR,	WI_INTERSIL },
    258 	{ WI_NIC_EVB2_SST_ID,		WI_NIC_EVB2_SST_STR,	WI_INTERSIL },
    259 	{ WI_NIC_3842_EVA_ID,		WI_NIC_3842_EVA_STR,	WI_INTERSIL },
    260 	{ WI_NIC_3842_PCMCIA_AMD_ID,	WI_NIC_3842_PCMCIA_STR,	WI_INTERSIL },
    261 	{ WI_NIC_3842_PCMCIA_SST_ID,	WI_NIC_3842_PCMCIA_STR,	WI_INTERSIL },
    262 	{ WI_NIC_3842_PCMCIA_ATM_ID,	WI_NIC_3842_PCMCIA_STR,	WI_INTERSIL },
    263 	{ WI_NIC_3842_MINI_AMD_ID,	WI_NIC_3842_MINI_STR,	WI_INTERSIL },
    264 	{ WI_NIC_3842_MINI_SST_ID,	WI_NIC_3842_MINI_STR,	WI_INTERSIL },
    265 	{ WI_NIC_3842_MINI_ATM_ID,	WI_NIC_3842_MINI_STR,	WI_INTERSIL },
    266 	{ WI_NIC_3842_PCI_AMD_ID,	WI_NIC_3842_PCI_STR,	WI_INTERSIL },
    267 	{ WI_NIC_3842_PCI_SST_ID,	WI_NIC_3842_PCI_STR,	WI_INTERSIL },
    268 	{ WI_NIC_3842_PCI_ATM_ID,	WI_NIC_3842_PCI_STR,	WI_INTERSIL },
    269 	{ WI_NIC_P3_PCMCIA_AMD_ID,	WI_NIC_P3_PCMCIA_STR,	WI_INTERSIL },
    270 	{ WI_NIC_P3_PCMCIA_SST_ID,	WI_NIC_P3_PCMCIA_STR,	WI_INTERSIL },
    271 	{ WI_NIC_P3_MINI_AMD_ID,	WI_NIC_P3_MINI_STR,	WI_INTERSIL },
    272 	{ WI_NIC_P3_MINI_SST_ID,	WI_NIC_P3_MINI_STR,	WI_INTERSIL },
    273 	{ 0,	NULL,	0 },
    274 };
    275 
    276 #ifndef _MODULE
    277 /*
    278  * Setup sysctl(3) MIB, hw.wi.*
    279  *
    280  * TBD condition CTLFLAG_PERMANENT on being a module or not
    281  */
    282 SYSCTL_SETUP(sysctl_wi, "sysctl wi(4) subtree setup")
    283 {
    284 	int rc;
    285 	const struct sysctlnode *rnode;
    286 #ifdef WI_DEBUG
    287 	const struct sysctlnode *cnode;
    288 #endif /* WI_DEBUG */
    289 
    290 	if ((rc = sysctl_createv(clog, 0, NULL, &rnode,
    291 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "wi",
    292 	    "Lucent/Prism/Symbol 802.11 controls",
    293 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL)) != 0)
    294 		goto err;
    295 
    296 #ifdef WI_DEBUG
    297 	/* control debugging printfs */
    298 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
    299 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
    300 	    "debug", SYSCTL_DESCR("Enable debugging output"),
    301 	    wi_sysctl_verify_debug, 0, &wi_debug, 0, CTL_CREATE, CTL_EOL)) != 0)
    302 		goto err;
    303 #endif /* WI_DEBUG */
    304 	return;
    305 err:
    306 	printf("%s: sysctl_createv failed (rc = %d)\n", __func__, rc);
    307 }
    308 #endif
    309 
    310 #ifdef WI_DEBUG
    311 static int
    312 wi_sysctl_verify(SYSCTLFN_ARGS, int lower, int upper)
    313 {
    314 	int error, t;
    315 	struct sysctlnode node;
    316 
    317 	node = *rnode;
    318 	t = *(int*)rnode->sysctl_data;
    319 	node.sysctl_data = &t;
    320 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    321 	if (error || newp == NULL)
    322 		return (error);
    323 
    324 	if (t < lower || t > upper)
    325 		return (EINVAL);
    326 
    327 	*(int*)rnode->sysctl_data = t;
    328 
    329 	return (0);
    330 }
    331 
    332 static int
    333 wi_sysctl_verify_debug(SYSCTLFN_ARGS)
    334 {
    335 	return wi_sysctl_verify(SYSCTLFN_CALL(__UNCONST(rnode)),
    336 	    0, WI_DEBUG_MAX);
    337 }
    338 #endif /* WI_DEBUG */
    339 
    340 STATIC int
    341 wi_read_xrid(struct wi_softc *sc, int rid, void *buf, int ebuflen)
    342 {
    343 	int buflen, rc;
    344 
    345 	buflen = ebuflen;
    346 	if ((rc = wi_read_rid(sc, rid, buf, &buflen)) != 0)
    347 		return rc;
    348 
    349 	if (buflen < ebuflen) {
    350 #ifdef WI_DEBUG
    351 		printf("%s: rid=%#04x read %d, expected %d\n", __func__,
    352 		    rid, buflen, ebuflen);
    353 #endif
    354 		return -1;
    355 	}
    356 	return 0;
    357 }
    358 
    359 int
    360 wi_attach(struct wi_softc *sc, const u_int8_t *macaddr)
    361 {
    362 	struct ieee80211com *ic = &sc->sc_ic;
    363 	struct ifnet *ifp = &sc->sc_if;
    364 	int chan, nrate, buflen;
    365 	u_int16_t val, chanavail;
    366  	struct {
    367  		u_int16_t nrates;
    368  		char rates[IEEE80211_RATE_SIZE];
    369  	} ratebuf;
    370 	static const u_int8_t empty_macaddr[IEEE80211_ADDR_LEN] = {
    371 		0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    372 	};
    373 	int s, rv;
    374 
    375 	sc->sc_soft_ih = softint_establish(SOFTINT_NET, wi_softintr, sc);
    376 	if (sc->sc_soft_ih == NULL) {
    377 		printf(" could not establish softint\n");
    378 		goto err;
    379 	}
    380 
    381 	wi_ioctl_init(sc);
    382 
    383 	s = splnet();
    384 
    385 	/* Make sure interrupts are disabled. */
    386 	CSR_WRITE_2(sc, WI_INT_EN, 0);
    387 	CSR_WRITE_2(sc, WI_EVENT_ACK, ~0);
    388 
    389 	sc->sc_invalid = 0;
    390 
    391 	/* Reset the NIC. */
    392 	if (wi_reset(sc) != 0) {
    393 		sc->sc_invalid = 1;
    394 		goto fail;
    395 	}
    396 
    397 	if (wi_read_xrid(sc, WI_RID_MAC_NODE, ic->ic_myaddr,
    398 			 IEEE80211_ADDR_LEN) != 0 ||
    399 	    IEEE80211_ADDR_EQ(ic->ic_myaddr, empty_macaddr)) {
    400 		if (macaddr != NULL)
    401 			memcpy(ic->ic_myaddr, macaddr, IEEE80211_ADDR_LEN);
    402 		else {
    403 			printf(" could not get mac address, attach failed\n");
    404 			goto fail;
    405 		}
    406 	}
    407 
    408 	printf(" 802.11 address %s\n", ether_sprintf(ic->ic_myaddr));
    409 
    410 	/* Read NIC identification */
    411 	wi_read_nicid(sc);
    412 
    413 	memcpy(ifp->if_xname, device_xname(sc->sc_dev), IFNAMSIZ);
    414 	ifp->if_softc = sc;
    415 	ifp->if_start = wi_start;
    416 	ifp->if_ioctl = wi_ioctl;
    417 	ifp->if_watchdog = wi_watchdog;
    418 	ifp->if_init = wi_init;
    419 	ifp->if_stop = wi_stop;
    420 	ifp->if_flags =
    421 	    IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST | IFF_NOTRAILERS;
    422 	IFQ_SET_READY(&ifp->if_snd);
    423 
    424 	ic->ic_ifp = ifp;
    425 	ic->ic_phytype = IEEE80211_T_DS;
    426 	ic->ic_opmode = IEEE80211_M_STA;
    427 	ic->ic_caps = IEEE80211_C_AHDEMO;
    428 	ic->ic_state = IEEE80211_S_INIT;
    429 	ic->ic_max_aid = WI_MAX_AID;
    430 
    431 	/* Find available channel */
    432 	if (wi_read_xrid(sc, WI_RID_CHANNEL_LIST, &chanavail,
    433 	                 sizeof(chanavail)) != 0) {
    434 		aprint_normal_dev(sc->sc_dev, "using default channel list\n");
    435 		chanavail = htole16(0x1fff);	/* assume 1-13 */
    436 	}
    437 	for (chan = 16; chan > 0; chan--) {
    438 		if (!isset((u_int8_t*)&chanavail, chan - 1))
    439 			continue;
    440 		ic->ic_ibss_chan = &ic->ic_channels[chan];
    441 		ic->ic_channels[chan].ic_freq =
    442 		    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
    443 		ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_B;
    444 	}
    445 
    446 	/* Find default IBSS channel */
    447 	if (wi_read_xrid(sc, WI_RID_OWN_CHNL, &val, sizeof(val)) == 0) {
    448 		chan = le16toh(val);
    449 		if (isset((u_int8_t*)&chanavail, chan - 1))
    450 			ic->ic_ibss_chan = &ic->ic_channels[chan];
    451 	}
    452 	if (ic->ic_ibss_chan == NULL) {
    453 		aprint_error_dev(sc->sc_dev, "no available channel\n");
    454 		goto fail;
    455 	}
    456 
    457 	if (sc->sc_firmware_type == WI_LUCENT) {
    458 		sc->sc_dbm_offset = WI_LUCENT_DBM_OFFSET;
    459 	} else {
    460 		if ((sc->sc_flags & WI_FLAGS_HAS_DBMADJUST) &&
    461 		    wi_read_xrid(sc, WI_RID_DBM_ADJUST, &val, sizeof(val)) == 0)
    462 			sc->sc_dbm_offset = le16toh(val);
    463 		else
    464 			sc->sc_dbm_offset = WI_PRISM_DBM_OFFSET;
    465 	}
    466 
    467 	sc->sc_flags |= WI_FLAGS_RSSADAPTSTA;
    468 
    469 	/*
    470 	 * Set flags based on firmware version.
    471 	 */
    472 	switch (sc->sc_firmware_type) {
    473 	case WI_LUCENT:
    474 		sc->sc_flags |= WI_FLAGS_HAS_SYSSCALE;
    475 #ifdef WI_HERMES_AUTOINC_WAR
    476 		/* XXX: not confirmed, but never seen for recent firmware */
    477 		if (sc->sc_sta_firmware_ver <  40000) {
    478 			sc->sc_flags |= WI_FLAGS_BUG_AUTOINC;
    479 		}
    480 #endif
    481 		if (sc->sc_sta_firmware_ver >= 60000)
    482 			sc->sc_flags |= WI_FLAGS_HAS_MOR;
    483 		if (sc->sc_sta_firmware_ver >= 60006) {
    484 			ic->ic_caps |= IEEE80211_C_IBSS;
    485 			ic->ic_caps |= IEEE80211_C_MONITOR;
    486 		}
    487 		ic->ic_caps |= IEEE80211_C_PMGT;
    488 		sc->sc_ibss_port = 1;
    489 		break;
    490 
    491 	case WI_INTERSIL:
    492 		sc->sc_flags |= WI_FLAGS_HAS_FRAGTHR;
    493 		sc->sc_flags |= WI_FLAGS_HAS_ROAMING;
    494 		sc->sc_flags |= WI_FLAGS_HAS_SYSSCALE;
    495 		if (sc->sc_sta_firmware_ver > 10101)
    496 			sc->sc_flags |= WI_FLAGS_HAS_DBMADJUST;
    497 		if (sc->sc_sta_firmware_ver >= 800) {
    498 			if (sc->sc_sta_firmware_ver != 10402)
    499 				ic->ic_caps |= IEEE80211_C_HOSTAP;
    500 			ic->ic_caps |= IEEE80211_C_IBSS;
    501 			ic->ic_caps |= IEEE80211_C_MONITOR;
    502 		}
    503 		ic->ic_caps |= IEEE80211_C_PMGT;
    504 		sc->sc_ibss_port = 0;
    505 		sc->sc_alt_retry = 2;
    506 		break;
    507 
    508 	case WI_SYMBOL:
    509 		sc->sc_flags |= WI_FLAGS_HAS_DIVERSITY;
    510 		if (sc->sc_sta_firmware_ver >= 20000)
    511 			ic->ic_caps |= IEEE80211_C_IBSS;
    512 		sc->sc_ibss_port = 4;
    513 		break;
    514 	}
    515 
    516 	/*
    517 	 * Find out if we support WEP on this card.
    518 	 */
    519 	if (wi_read_xrid(sc, WI_RID_WEP_AVAIL, &val, sizeof(val)) == 0 &&
    520 	    val != htole16(0))
    521 		ic->ic_caps |= IEEE80211_C_WEP;
    522 
    523 	/* Find supported rates. */
    524 	buflen = sizeof(ratebuf);
    525 	if (wi_read_rid(sc, WI_RID_DATA_RATES, &ratebuf, &buflen) == 0 &&
    526 	    buflen > 2) {
    527 		nrate = le16toh(ratebuf.nrates);
    528 		if (nrate > IEEE80211_RATE_SIZE)
    529 			nrate = IEEE80211_RATE_SIZE;
    530 		memcpy(ic->ic_sup_rates[IEEE80211_MODE_11B].rs_rates,
    531 		    &ratebuf.rates[0], nrate);
    532 		ic->ic_sup_rates[IEEE80211_MODE_11B].rs_nrates = nrate;
    533 	} else {
    534 		aprint_error_dev(sc->sc_dev, "no supported rate list\n");
    535 		goto fail;
    536 	}
    537 
    538 	sc->sc_max_datalen = 2304;
    539 	sc->sc_rts_thresh = 2347;
    540 	sc->sc_frag_thresh = 2346;
    541 	sc->sc_system_scale = 1;
    542 	sc->sc_cnfauthmode = IEEE80211_AUTH_OPEN;
    543 	sc->sc_roaming_mode = 1;
    544 
    545 	callout_init(&sc->sc_rssadapt_ch, 0);
    546 
    547 	/*
    548 	 * Call MI attach routines.
    549 	 */
    550 	rv = if_initialize(ifp);
    551 	if (rv != 0) {
    552 		aprint_error_dev(sc->sc_dev, "if_initialize failed(%d)\n", rv);
    553 		goto fail_2;
    554 	}
    555 	ieee80211_ifattach(ic);
    556 	/* Use common softint-based if_input */
    557 	ifp->if_percpuq = if_percpuq_create(ifp);
    558 	if_register(ifp);
    559 
    560 	sc->sc_newstate = ic->ic_newstate;
    561 	sc->sc_set_tim = ic->ic_set_tim;
    562 	ic->ic_newstate = wi_newstate;
    563 	ic->ic_node_alloc = wi_node_alloc;
    564 	ic->ic_node_free = wi_node_free;
    565 	ic->ic_set_tim = wi_set_tim;
    566 
    567 	ic->ic_crypto.cs_key_delete = wi_key_delete;
    568 	ic->ic_crypto.cs_key_set = wi_key_set;
    569 	ic->ic_crypto.cs_key_update_begin = wi_key_update_begin;
    570 	ic->ic_crypto.cs_key_update_end = wi_key_update_end;
    571 
    572 	ieee80211_media_init(ic, wi_media_change, wi_media_status);
    573 
    574 	bpf_attach2(ifp, DLT_IEEE802_11_RADIO,
    575 	    sizeof(struct ieee80211_frame) + 64, &sc->sc_drvbpf);
    576 
    577 	memset(&sc->sc_rxtapu, 0, sizeof(sc->sc_rxtapu));
    578 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sizeof(sc->sc_rxtapu));
    579 	sc->sc_rxtap.wr_ihdr.it_present = htole32(WI_RX_RADIOTAP_PRESENT);
    580 
    581 	memset(&sc->sc_txtapu, 0, sizeof(sc->sc_txtapu));
    582 	sc->sc_txtap.wt_ihdr.it_len = htole16(sizeof(sc->sc_txtapu));
    583 	sc->sc_txtap.wt_ihdr.it_present = htole32(WI_TX_RADIOTAP_PRESENT);
    584 
    585 	/* Attach is successful. */
    586 	sc->sc_attached = 1;
    587 
    588 	splx(s);
    589 	ieee80211_announce(ic);
    590 	return 0;
    591 
    592 fail_2:
    593 	callout_destroy(&sc->sc_rssadapt_ch);
    594 
    595 fail:	splx(s);
    596 	softint_disestablish(sc->sc_soft_ih);
    597 	sc->sc_soft_ih = NULL;
    598 err:	return 1;
    599 }
    600 
    601 int
    602 wi_detach(struct wi_softc *sc)
    603 {
    604 	struct ifnet *ifp = &sc->sc_if;
    605 	int s;
    606 
    607 	if (!sc->sc_attached)
    608 		return 0;
    609 
    610 	sc->sc_invalid = 1;
    611 	s = splnet();
    612 
    613 	wi_stop(ifp, 1);
    614 
    615 	ieee80211_ifdetach(&sc->sc_ic);
    616 	if_detach(ifp);
    617 	splx(s);
    618 	wi_ioctl_drain(sc);
    619 	softint_disestablish(sc->sc_soft_ih);
    620 	sc->sc_soft_ih = NULL;
    621 	return 0;
    622 }
    623 
    624 int
    625 wi_activate(device_t self, enum devact act)
    626 {
    627 	struct wi_softc *sc = device_private(self);
    628 
    629 	switch (act) {
    630 	case DVACT_DEACTIVATE:
    631 		if_deactivate(&sc->sc_if);
    632 		return 0;
    633 	default:
    634 		return EOPNOTSUPP;
    635 	}
    636 }
    637 
    638 int
    639 wi_intr(void *arg)
    640 {
    641 	struct wi_softc	*sc = arg;
    642 	struct ifnet *ifp = &sc->sc_if;
    643 	u_int16_t status;
    644 
    645 	if (sc->sc_enabled == 0 ||
    646 	    !device_is_active(sc->sc_dev) ||
    647 	    (ifp->if_flags & IFF_RUNNING) == 0)
    648 		return 0;
    649 
    650 	if ((ifp->if_flags & IFF_UP) == 0) {
    651 		CSR_WRITE_2(sc, WI_INT_EN, 0);
    652 		CSR_WRITE_2(sc, WI_EVENT_ACK, ~0);
    653 		return 1;
    654 	}
    655 
    656 	/* This is superfluous on Prism, but Lucent breaks if we
    657 	 * do not disable interrupts.
    658 	 */
    659 	CSR_WRITE_2(sc, WI_INT_EN, 0);
    660 
    661 	status = CSR_READ_2(sc, WI_EVENT_STAT);
    662 #ifdef WI_DEBUG
    663 	if (wi_debug > 1) {
    664 		printf("%s: status %#04x\n", __func__, status);
    665 	}
    666 #endif /* WI_DEBUG */
    667 	if ((status & WI_INTRS) == 0) {
    668 		/* re-enable interrupts */
    669 		CSR_WRITE_2(sc, WI_INT_EN, WI_INTRS);
    670 		return 0;
    671 	}
    672 
    673 	softint_schedule(sc->sc_soft_ih);
    674 	return 1;
    675 }
    676 
    677 STATIC void
    678 wi_softintr(void *arg)
    679 {
    680 	int i, s;
    681 	struct wi_softc	*sc = arg;
    682 	struct ifnet *ifp = &sc->sc_if;
    683 	u_int16_t status;
    684 
    685 	if (sc->sc_enabled == 0 ||
    686 	    !device_is_active(sc->sc_dev) ||
    687 	    (ifp->if_flags & IFF_RUNNING) == 0)
    688 		goto out;
    689 
    690 	if ((ifp->if_flags & IFF_UP) == 0) {
    691 		CSR_WRITE_2(sc, WI_EVENT_ACK, ~0);
    692 		return;
    693 	}
    694 
    695 	/* maximum 10 loops per interrupt */
    696 	for (i = 0; i < 10; i++) {
    697 		status = CSR_READ_2(sc, WI_EVENT_STAT);
    698 #ifdef WI_DEBUG
    699 		if (wi_debug > 1) {
    700 			printf("%s: iter %d status %#04x\n", __func__, i,
    701 			    status);
    702 		}
    703 #endif /* WI_DEBUG */
    704 		if ((status & WI_INTRS) == 0)
    705 			break;
    706 
    707 		sc->sc_status = status;
    708 
    709 		if (status & WI_EV_RX)
    710 			wi_rx_intr(sc);
    711 
    712 		if (status & WI_EV_ALLOC)
    713 			wi_txalloc_intr(sc);
    714 
    715 		if (status & WI_EV_TX)
    716 			wi_tx_intr(sc);
    717 
    718 		if (status & WI_EV_TX_EXC)
    719 			wi_tx_ex_intr(sc);
    720 
    721 		if (status & WI_EV_INFO)
    722 			wi_info_intr(sc);
    723 
    724 		CSR_WRITE_2(sc, WI_EVENT_ACK, sc->sc_status);
    725 
    726 		if (sc->sc_status & WI_EV_CMD)
    727 			wi_cmd_intr(sc);
    728 
    729 		if ((ifp->if_flags & IFF_OACTIVE) == 0 &&
    730 		    (sc->sc_flags & WI_FLAGS_OUTRANGE) == 0 &&
    731 		    !IFQ_IS_EMPTY(&ifp->if_snd)) {
    732 			s = splnet();
    733 			wi_start(ifp);
    734 			splx(s);
    735 		}
    736 
    737 		sc->sc_status = 0;
    738 	}
    739 	if (i == 10)
    740 		softint_schedule(sc->sc_soft_ih);
    741 
    742 out:
    743 	sc->sc_status = 0;
    744 
    745 	/* re-enable interrupts */
    746 	CSR_WRITE_2(sc, WI_INT_EN, WI_INTRS);
    747 }
    748 
    749 #define arraylen(a) (sizeof(a) / sizeof((a)[0]))
    750 
    751 STATIC void
    752 wi_rssdescs_init(struct wi_rssdesc (*rssd)[WI_NTXRSS], wi_rssdescq_t *rssdfree)
    753 {
    754 	int i;
    755 	SLIST_INIT(rssdfree);
    756 	for (i = 0; i < arraylen(*rssd); i++) {
    757 		SLIST_INSERT_HEAD(rssdfree, &(*rssd)[i], rd_next);
    758 	}
    759 }
    760 
    761 STATIC void
    762 wi_rssdescs_reset(struct ieee80211com *ic, struct wi_rssdesc (*rssd)[WI_NTXRSS],
    763     wi_rssdescq_t *rssdfree, u_int8_t (*txpending)[IEEE80211_RATE_MAXSIZE])
    764 {
    765 	struct ieee80211_node *ni;
    766 	int i;
    767 	for (i = 0; i < arraylen(*rssd); i++) {
    768 		ni = (*rssd)[i].rd_desc.id_node;
    769 		(*rssd)[i].rd_desc.id_node = NULL;
    770 		if (ni != NULL && (ic->ic_ifp->if_flags & IFF_DEBUG) != 0)
    771 			printf("%s: cleaning outstanding rssadapt "
    772 			    "descriptor for %s\n",
    773 			    ic->ic_ifp->if_xname, ether_sprintf(ni->ni_macaddr));
    774 		if (ni != NULL)
    775 			ieee80211_free_node(ni);
    776 	}
    777 	memset(*txpending, 0, sizeof(*txpending));
    778 	wi_rssdescs_init(rssd, rssdfree);
    779 }
    780 
    781 STATIC int
    782 wi_init(struct ifnet *ifp)
    783 {
    784 	struct wi_softc *sc = ifp->if_softc;
    785 	struct ieee80211com *ic = &sc->sc_ic;
    786 	struct wi_joinreq join;
    787 	int i;
    788 	int error = 0, wasenabled;
    789 
    790 	DPRINTF(("wi_init: enabled %d\n", sc->sc_enabled));
    791 	wasenabled = sc->sc_enabled;
    792 	if (!sc->sc_enabled) {
    793 		if ((error = (*sc->sc_enable)(sc->sc_dev, 1)) != 0)
    794 			goto out;
    795 		sc->sc_enabled = 1;
    796 	} else
    797 		wi_stop(ifp, 0);
    798 
    799 	/* Symbol firmware cannot be initialized more than once */
    800 	if (sc->sc_firmware_type != WI_SYMBOL || !wasenabled)
    801 		if ((error = wi_reset(sc)) != 0)
    802 			goto out;
    803 
    804 	/* common 802.11 configuration */
    805 	ic->ic_flags &= ~IEEE80211_F_IBSSON;
    806 	sc->sc_flags &= ~WI_FLAGS_OUTRANGE;
    807 	switch (ic->ic_opmode) {
    808 	case IEEE80211_M_STA:
    809 		wi_write_val(sc, WI_RID_PORTTYPE, WI_PORTTYPE_BSS);
    810 		break;
    811 	case IEEE80211_M_IBSS:
    812 		wi_write_val(sc, WI_RID_PORTTYPE, sc->sc_ibss_port);
    813 		ic->ic_flags |= IEEE80211_F_IBSSON;
    814 		break;
    815 	case IEEE80211_M_AHDEMO:
    816 		wi_write_val(sc, WI_RID_PORTTYPE, WI_PORTTYPE_ADHOC);
    817 		break;
    818 	case IEEE80211_M_HOSTAP:
    819 		wi_write_val(sc, WI_RID_PORTTYPE, WI_PORTTYPE_HOSTAP);
    820 		break;
    821 	case IEEE80211_M_MONITOR:
    822 		if (sc->sc_firmware_type == WI_LUCENT)
    823 			wi_write_val(sc, WI_RID_PORTTYPE, WI_PORTTYPE_ADHOC);
    824 		wi_cmd(sc, WI_CMD_TEST | (WI_TEST_MONITOR << 8), 0, 0, 0);
    825 		break;
    826 	}
    827 
    828 	/* Intersil interprets this RID as joining ESS even in IBSS mode */
    829 	if (sc->sc_firmware_type == WI_LUCENT &&
    830 	    (ic->ic_flags & IEEE80211_F_IBSSON) && ic->ic_des_esslen > 0)
    831 		wi_write_val(sc, WI_RID_CREATE_IBSS, 1);
    832 	else
    833 		wi_write_val(sc, WI_RID_CREATE_IBSS, 0);
    834 	wi_write_val(sc, WI_RID_MAX_SLEEP, ic->ic_lintval);
    835 	wi_write_ssid(sc, WI_RID_DESIRED_SSID, ic->ic_des_essid,
    836 	    ic->ic_des_esslen);
    837 	wi_write_val(sc, WI_RID_OWN_CHNL,
    838 	    ieee80211_chan2ieee(ic, ic->ic_ibss_chan));
    839 	wi_write_ssid(sc, WI_RID_OWN_SSID, ic->ic_des_essid, ic->ic_des_esslen);
    840 	IEEE80211_ADDR_COPY(ic->ic_myaddr, CLLADDR(ifp->if_sadl));
    841 	wi_write_rid(sc, WI_RID_MAC_NODE, ic->ic_myaddr, IEEE80211_ADDR_LEN);
    842 	if (ic->ic_caps & IEEE80211_C_PMGT)
    843 		wi_write_val(sc, WI_RID_PM_ENABLED,
    844 		    (ic->ic_flags & IEEE80211_F_PMGTON) ? 1 : 0);
    845 
    846 	/* not yet common 802.11 configuration */
    847 	wi_write_val(sc, WI_RID_MAX_DATALEN, sc->sc_max_datalen);
    848 	wi_write_val(sc, WI_RID_RTS_THRESH, sc->sc_rts_thresh);
    849 	if (sc->sc_flags & WI_FLAGS_HAS_FRAGTHR)
    850 		wi_write_val(sc, WI_RID_FRAG_THRESH, sc->sc_frag_thresh);
    851 
    852 	/* driver specific 802.11 configuration */
    853 	if (sc->sc_flags & WI_FLAGS_HAS_SYSSCALE)
    854 		wi_write_val(sc, WI_RID_SYSTEM_SCALE, sc->sc_system_scale);
    855 	if (sc->sc_flags & WI_FLAGS_HAS_ROAMING)
    856 		wi_write_val(sc, WI_RID_ROAMING_MODE, sc->sc_roaming_mode);
    857 	if (sc->sc_flags & WI_FLAGS_HAS_MOR)
    858 		wi_write_val(sc, WI_RID_MICROWAVE_OVEN, sc->sc_microwave_oven);
    859 	wi_cfg_txrate(sc);
    860 	wi_write_ssid(sc, WI_RID_NODENAME, sc->sc_nodename, sc->sc_nodelen);
    861 
    862 #ifndef	IEEE80211_NO_HOSTAP
    863 	if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
    864 	    sc->sc_firmware_type == WI_INTERSIL) {
    865 		wi_write_val(sc, WI_RID_OWN_BEACON_INT, ic->ic_lintval);
    866 		wi_write_val(sc, WI_RID_DTIM_PERIOD, 1);
    867 	}
    868 #endif /* !IEEE80211_NO_HOSTAP */
    869 
    870 	if (sc->sc_firmware_type == WI_INTERSIL) {
    871 		struct ieee80211_rateset *rs =
    872 		    &ic->ic_sup_rates[IEEE80211_MODE_11B];
    873 		u_int16_t basic = 0, supported = 0, rate;
    874 
    875 		for (i = 0; i < rs->rs_nrates; i++) {
    876 			switch (rs->rs_rates[i] & IEEE80211_RATE_VAL) {
    877 			case 2:
    878 				rate = 1;
    879 				break;
    880 			case 4:
    881 				rate = 2;
    882 				break;
    883 			case 11:
    884 				rate = 4;
    885 				break;
    886 			case 22:
    887 				rate = 8;
    888 				break;
    889 			default:
    890 				rate = 0;
    891 				break;
    892 			}
    893 			if (rs->rs_rates[i] & IEEE80211_RATE_BASIC)
    894 				basic |= rate;
    895 			supported |= rate;
    896 		}
    897 		wi_write_val(sc, WI_RID_BASIC_RATE, basic);
    898 		wi_write_val(sc, WI_RID_SUPPORT_RATE, supported);
    899 		wi_write_val(sc, WI_RID_ALT_RETRY_COUNT, sc->sc_alt_retry);
    900 	}
    901 
    902 	/*
    903 	 * Initialize promisc mode.
    904 	 *	Being in Host-AP mode causes a great
    905 	 *	deal of pain if promiscuous mode is set.
    906 	 *	Therefore we avoid confusing the firmware
    907 	 *	and always reset promisc mode in Host-AP
    908 	 *	mode.  Host-AP sees all the packets anyway.
    909 	 */
    910 	if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
    911 	    (ifp->if_flags & IFF_PROMISC) != 0) {
    912 		wi_write_val(sc, WI_RID_PROMISC, 1);
    913 	} else {
    914 		wi_write_val(sc, WI_RID_PROMISC, 0);
    915 	}
    916 
    917 	/* Configure WEP. */
    918 	if (ic->ic_caps & IEEE80211_C_WEP) {
    919 		sc->sc_cnfauthmode = ic->ic_bss->ni_authmode;
    920 		wi_write_wep(sc);
    921 	}
    922 
    923 	/* Set multicast filter. */
    924 	wi_write_multi(sc);
    925 
    926 	sc->sc_txalloc = 0;
    927 	sc->sc_txalloced = 0;
    928 	sc->sc_txqueue = 0;
    929 	sc->sc_txqueued = 0;
    930 	sc->sc_txstart = 0;
    931 	sc->sc_txstarted = 0;
    932 
    933 	if (sc->sc_firmware_type != WI_SYMBOL || !wasenabled) {
    934 		sc->sc_buflen = IEEE80211_MAX_LEN + sizeof(struct wi_frame);
    935 		if (sc->sc_firmware_type == WI_SYMBOL)
    936 			sc->sc_buflen = 1585;	/* XXX */
    937 		for (i = 0; i < WI_NTXBUF; i++) {
    938 			error = wi_alloc_fid(sc, sc->sc_buflen,
    939 			    &sc->sc_txd[i].d_fid);
    940 			if (error) {
    941 				aprint_error_dev(sc->sc_dev,
    942 				    "tx buffer allocation failed\n");
    943 				goto out;
    944 			}
    945 			DPRINTF2(("wi_init: txbuf %d allocated %x\n", i,
    946 			    sc->sc_txd[i].d_fid));
    947 			++sc->sc_txalloced;
    948 		}
    949 	}
    950 
    951 	wi_rssdescs_init(&sc->sc_rssd, &sc->sc_rssdfree);
    952 
    953 	/* Enable desired port */
    954 	wi_cmd(sc, WI_CMD_ENABLE | sc->sc_portnum, 0, 0, 0);
    955 	ifp->if_flags |= IFF_RUNNING;
    956 	ifp->if_flags &= ~IFF_OACTIVE;
    957 	ic->ic_state = IEEE80211_S_INIT;
    958 
    959 	if (ic->ic_opmode == IEEE80211_M_AHDEMO ||
    960 	    ic->ic_opmode == IEEE80211_M_IBSS ||
    961 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
    962 	    ic->ic_opmode == IEEE80211_M_HOSTAP)
    963 		ieee80211_create_ibss(ic, ic->ic_ibss_chan);
    964 
    965 	/* Enable interrupts */
    966 	CSR_WRITE_2(sc, WI_INT_EN, WI_INTRS);
    967 
    968 #ifndef	IEEE80211_NO_HOSTAP
    969 	if (!wasenabled &&
    970 	    ic->ic_opmode == IEEE80211_M_HOSTAP &&
    971 	    sc->sc_firmware_type == WI_INTERSIL) {
    972 		/* XXX: some card need to be re-enabled for hostap */
    973 		wi_cmd(sc, WI_CMD_DISABLE | WI_PORT0, 0, 0, 0);
    974 		wi_cmd(sc, WI_CMD_ENABLE | WI_PORT0, 0, 0, 0);
    975 	}
    976 #endif /* !IEEE80211_NO_HOSTAP */
    977 
    978 	if (ic->ic_opmode == IEEE80211_M_STA &&
    979 	    ((ic->ic_flags & IEEE80211_F_DESBSSID) ||
    980 	    ic->ic_des_chan != IEEE80211_CHAN_ANYC)) {
    981 		memset(&join, 0, sizeof(join));
    982 		if (ic->ic_flags & IEEE80211_F_DESBSSID)
    983 			IEEE80211_ADDR_COPY(&join.wi_bssid, ic->ic_des_bssid);
    984 		if (ic->ic_des_chan != IEEE80211_CHAN_ANYC)
    985 			join.wi_chan =
    986 			    htole16(ieee80211_chan2ieee(ic, ic->ic_des_chan));
    987 		/* Lucent firmware does not support the JOIN RID. */
    988 		if (sc->sc_firmware_type != WI_LUCENT)
    989 			wi_write_rid(sc, WI_RID_JOIN_REQ, &join, sizeof(join));
    990 	}
    991 
    992  out:
    993 	if (error) {
    994 		printf("%s: interface not running\n", device_xname(sc->sc_dev));
    995 		wi_stop(ifp, 0);
    996 	}
    997 	DPRINTF(("wi_init: return %d\n", error));
    998 	return error;
    999 }
   1000 
   1001 STATIC void
   1002 wi_txcmd_wait(struct wi_softc *sc)
   1003 {
   1004 	KASSERT(sc->sc_txcmds == 1);
   1005 	if (sc->sc_status & WI_EV_CMD) {
   1006 		sc->sc_status &= ~WI_EV_CMD;
   1007 		CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_CMD);
   1008 	} else
   1009 		(void)wi_cmd_wait(sc, WI_CMD_TX | WI_RECLAIM, 0);
   1010 }
   1011 
   1012 STATIC void
   1013 wi_stop(struct ifnet *ifp, int disable)
   1014 {
   1015 	struct wi_softc	*sc = ifp->if_softc;
   1016 	struct ieee80211com *ic = &sc->sc_ic;
   1017 	int s;
   1018 
   1019 	if (!sc->sc_enabled)
   1020 		return;
   1021 
   1022 	s = splnet();
   1023 
   1024 	DPRINTF(("wi_stop: disable %d\n", disable));
   1025 
   1026 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
   1027 
   1028 	/* wait for tx command completion (deassoc, deauth) */
   1029 	while (sc->sc_txcmds > 0) {
   1030 		wi_txcmd_wait(sc);
   1031 		wi_cmd_intr(sc);
   1032 	}
   1033 
   1034 	/* TBD wait for deassoc, deauth tx completion? */
   1035 
   1036 	if (!sc->sc_invalid) {
   1037 		CSR_WRITE_2(sc, WI_INT_EN, 0);
   1038 		wi_cmd(sc, WI_CMD_DISABLE | sc->sc_portnum, 0, 0, 0);
   1039 	}
   1040 
   1041 	wi_rssdescs_reset(ic, &sc->sc_rssd, &sc->sc_rssdfree,
   1042 	    &sc->sc_txpending);
   1043 
   1044 	sc->sc_tx_timer = 0;
   1045 	sc->sc_scan_timer = 0;
   1046 	sc->sc_false_syns = 0;
   1047 	sc->sc_naps = 0;
   1048 	ifp->if_flags &= ~(IFF_OACTIVE | IFF_RUNNING);
   1049 	ifp->if_timer = 0;
   1050 
   1051 	if (disable) {
   1052 		(*sc->sc_enable)(sc->sc_dev, 0);
   1053 		sc->sc_enabled = 0;
   1054 	}
   1055 	splx(s);
   1056 }
   1057 
   1058 /*
   1059  * Choose a data rate for a packet len bytes long that suits the packet
   1060  * type and the wireless conditions.
   1061  *
   1062  * TBD Adapt fragmentation threshold.
   1063  */
   1064 STATIC int
   1065 wi_choose_rate(struct ieee80211com *ic, struct ieee80211_node *ni,
   1066     struct ieee80211_frame *wh, u_int len)
   1067 {
   1068 	struct wi_softc	*sc = ic->ic_ifp->if_softc;
   1069 	struct wi_node *wn = (void*)ni;
   1070 	struct ieee80211_rssadapt *ra = &wn->wn_rssadapt;
   1071 	int do_not_adapt, i, rateidx, s;
   1072 
   1073 	do_not_adapt = (ic->ic_opmode != IEEE80211_M_HOSTAP) &&
   1074 	    (sc->sc_flags & WI_FLAGS_RSSADAPTSTA) == 0;
   1075 
   1076 	s = splnet();
   1077 
   1078 	rateidx = ieee80211_rssadapt_choose(ra, &ni->ni_rates, wh, len,
   1079 	    ic->ic_fixed_rate,
   1080 	    ((ic->ic_ifp->if_flags & IFF_DEBUG) == 0) ? NULL : ic->ic_ifp->if_xname,
   1081 	    do_not_adapt);
   1082 
   1083 	ni->ni_txrate = rateidx;
   1084 
   1085 	if (ic->ic_opmode != IEEE80211_M_HOSTAP) {
   1086 		/* choose the slowest pending rate so that we don't
   1087 		 * accidentally send a packet on the MAC's queue
   1088 		 * too fast. TBD find out if the MAC labels Tx
   1089 		 * packets w/ rate when enqueued or dequeued.
   1090 		 */
   1091 		for (i = 0; i < rateidx && sc->sc_txpending[i] == 0; i++);
   1092 		rateidx = i;
   1093 	}
   1094 
   1095 	splx(s);
   1096 	return (rateidx);
   1097 }
   1098 
   1099 STATIC void
   1100 wi_raise_rate(struct ieee80211com *ic, struct ieee80211_rssdesc *id)
   1101 {
   1102 	struct wi_node *wn;
   1103 	int s;
   1104 
   1105 	s = splnet();
   1106 	if (id->id_node == NULL)
   1107 		goto out;
   1108 
   1109 	wn = (void*)id->id_node;
   1110 	ieee80211_rssadapt_raise_rate(ic, &wn->wn_rssadapt, id);
   1111 out:
   1112 	splx(s);
   1113 }
   1114 
   1115 STATIC void
   1116 wi_lower_rate(struct ieee80211com *ic, struct ieee80211_rssdesc *id)
   1117 {
   1118 	struct ieee80211_node *ni;
   1119 	struct wi_node *wn;
   1120 	int s;
   1121 
   1122 	s = splnet();
   1123 
   1124 	if ((ni = id->id_node) == NULL) {
   1125 		DPRINTF(("wi_lower_rate: missing node\n"));
   1126 		goto out;
   1127 	}
   1128 
   1129 	wn = (void *)ni;
   1130 
   1131 	ieee80211_rssadapt_lower_rate(ic, ni, &wn->wn_rssadapt, id);
   1132 out:
   1133 	splx(s);
   1134 }
   1135 
   1136 STATIC void
   1137 wi_start(struct ifnet *ifp)
   1138 {
   1139 	struct wi_softc	*sc = ifp->if_softc;
   1140 	struct ieee80211com *ic = &sc->sc_ic;
   1141 	struct ether_header *eh;
   1142 	struct ieee80211_node *ni;
   1143 	struct ieee80211_frame *wh;
   1144 	struct ieee80211_rateset *rs;
   1145 	struct wi_rssdesc *rd;
   1146 	struct ieee80211_rssdesc *id;
   1147 	struct mbuf *m0;
   1148 	struct wi_frame frmhdr;
   1149 	int cur, fid, off, rateidx;
   1150 
   1151 	if (!sc->sc_enabled || sc->sc_invalid)
   1152 		return;
   1153 	if (sc->sc_flags & WI_FLAGS_OUTRANGE)
   1154 		return;
   1155 
   1156 	memset(&frmhdr, 0, sizeof(frmhdr));
   1157 	cur = sc->sc_txqueue;
   1158 	for (;;) {
   1159 		ni = ic->ic_bss;
   1160 		if (sc->sc_txalloced == 0 || SLIST_EMPTY(&sc->sc_rssdfree)) {
   1161 			ifp->if_flags |= IFF_OACTIVE;
   1162 			break;
   1163 		}
   1164 		if (!IF_IS_EMPTY(&ic->ic_mgtq)) {
   1165 			IF_DEQUEUE(&ic->ic_mgtq, m0);
   1166 			m_copydata(m0, 4, ETHER_ADDR_LEN * 2,
   1167 			    (void *)&frmhdr.wi_ehdr);
   1168 			frmhdr.wi_ehdr.ether_type = 0;
   1169                         wh = mtod(m0, struct ieee80211_frame *);
   1170 			ni = M_GETCTX(m0, struct ieee80211_node *);
   1171 			M_CLEARCTX(m0);
   1172 		} else if (ic->ic_state == IEEE80211_S_RUN) {
   1173 			IFQ_POLL(&ifp->if_snd, m0);
   1174 			if (m0 == NULL)
   1175 				break;
   1176 			IFQ_DEQUEUE(&ifp->if_snd, m0);
   1177 			ifp->if_opackets++;
   1178 			m_copydata(m0, 0, ETHER_HDR_LEN,
   1179 			    (void *)&frmhdr.wi_ehdr);
   1180 			bpf_mtap(ifp, m0, BPF_D_OUT);
   1181 
   1182 			eh = mtod(m0, struct ether_header *);
   1183 			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
   1184 			if (ni == NULL) {
   1185 				ifp->if_oerrors++;
   1186 				continue;
   1187 			}
   1188 			if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
   1189 			    (m0->m_flags & M_PWR_SAV) == 0) {
   1190 				ieee80211_pwrsave(ic, ni, m0);
   1191 				goto next;
   1192 			}
   1193 			if ((m0 = ieee80211_encap(ic, m0, ni)) == NULL) {
   1194 				ieee80211_free_node(ni);
   1195 				ifp->if_oerrors++;
   1196 				continue;
   1197 			}
   1198 			wh = mtod(m0, struct ieee80211_frame *);
   1199 		} else
   1200 			break;
   1201 		bpf_mtap3(ic->ic_rawbpf, m0, BPF_D_OUT);
   1202 		frmhdr.wi_tx_ctl =
   1203 		    htole16(WI_ENC_TX_802_11|WI_TXCNTL_TX_EX|WI_TXCNTL_TX_OK);
   1204 #ifndef	IEEE80211_NO_HOSTAP
   1205 		if (ic->ic_opmode == IEEE80211_M_HOSTAP)
   1206 			frmhdr.wi_tx_ctl |= htole16(WI_TXCNTL_ALTRTRY);
   1207 		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
   1208 		    (wh->i_fc[1] & IEEE80211_FC1_WEP)) {
   1209 			if (ieee80211_crypto_encap(ic, ni, m0) == NULL) {
   1210 				m_freem(m0);
   1211 				ifp->if_oerrors++;
   1212 				goto next;
   1213 			}
   1214 			frmhdr.wi_tx_ctl |= htole16(WI_TXCNTL_NOCRYPT);
   1215 		}
   1216 #endif /* !IEEE80211_NO_HOSTAP */
   1217 
   1218 		rateidx = wi_choose_rate(ic, ni, wh, m0->m_pkthdr.len);
   1219 		rs = &ni->ni_rates;
   1220 
   1221 		if (sc->sc_drvbpf) {
   1222 			struct wi_tx_radiotap_header *tap = &sc->sc_txtap;
   1223 
   1224 			tap->wt_rate = rs->rs_rates[rateidx];
   1225 			tap->wt_chan_freq =
   1226 			    htole16(ic->ic_bss->ni_chan->ic_freq);
   1227 			tap->wt_chan_flags =
   1228 			    htole16(ic->ic_bss->ni_chan->ic_flags);
   1229 			/* TBD tap->wt_flags */
   1230 
   1231 			bpf_mtap2(sc->sc_drvbpf, tap, tap->wt_ihdr.it_len, m0,
   1232 			    BPF_D_OUT);
   1233 		}
   1234 
   1235 		rd = SLIST_FIRST(&sc->sc_rssdfree);
   1236 		id = &rd->rd_desc;
   1237 		id->id_len = m0->m_pkthdr.len;
   1238 		id->id_rateidx = ni->ni_txrate;
   1239 		id->id_rssi = ni->ni_rssi;
   1240 
   1241 		frmhdr.wi_tx_idx = rd - sc->sc_rssd;
   1242 
   1243 		if (ic->ic_opmode == IEEE80211_M_HOSTAP)
   1244 			frmhdr.wi_tx_rate = 5 * (rs->rs_rates[rateidx] &
   1245 			    IEEE80211_RATE_VAL);
   1246 		else if (sc->sc_flags & WI_FLAGS_RSSADAPTSTA)
   1247 			(void)wi_write_txrate(sc, rs->rs_rates[rateidx]);
   1248 
   1249 		m_copydata(m0, 0, sizeof(struct ieee80211_frame),
   1250 		    (void *)&frmhdr.wi_whdr);
   1251 		m_adj(m0, sizeof(struct ieee80211_frame));
   1252 		frmhdr.wi_dat_len = htole16(m0->m_pkthdr.len);
   1253 		if (IFF_DUMPPKTS(ifp))
   1254 			wi_dump_pkt(&frmhdr, ni, -1);
   1255 		fid = sc->sc_txd[cur].d_fid;
   1256 		off = sizeof(frmhdr);
   1257 		if (wi_write_bap(sc, fid, 0, &frmhdr, sizeof(frmhdr)) != 0 ||
   1258 		    wi_mwrite_bap(sc, fid, off, m0, m0->m_pkthdr.len) != 0) {
   1259 			aprint_error_dev(sc->sc_dev, "%s write fid %x failed\n",
   1260 			    __func__, fid);
   1261 			ifp->if_oerrors++;
   1262 			m_freem(m0);
   1263 			goto next;
   1264 		}
   1265 		m_freem(m0);
   1266 		sc->sc_txpending[ni->ni_txrate]++;
   1267 		--sc->sc_txalloced;
   1268 		if (sc->sc_txqueued++ == 0) {
   1269 #ifdef DIAGNOSTIC
   1270 			if (cur != sc->sc_txstart)
   1271 				printf("%s: ring is desynchronized\n",
   1272 				    device_xname(sc->sc_dev));
   1273 #endif
   1274 			wi_push_packet(sc);
   1275 		} else {
   1276 #ifdef WI_RING_DEBUG
   1277 	printf("%s: queue %04x, alloc %d queue %d start %d alloced %d queued %d started %d\n",
   1278 	    device_xname(sc->sc_dev), fid,
   1279 	    sc->sc_txalloc, sc->sc_txqueue, sc->sc_txstart,
   1280 	    sc->sc_txalloced, sc->sc_txqueued, sc->sc_txstarted);
   1281 #endif
   1282 		}
   1283 		sc->sc_txqueue = cur = (cur + 1) % WI_NTXBUF;
   1284 		SLIST_REMOVE_HEAD(&sc->sc_rssdfree, rd_next);
   1285 		id->id_node = ni;
   1286 		continue;
   1287 next:
   1288 		if (ni != NULL)
   1289 			ieee80211_free_node(ni);
   1290 	}
   1291 }
   1292 
   1293 
   1294 STATIC int
   1295 wi_reset(struct wi_softc *sc)
   1296 {
   1297 	int i, error;
   1298 
   1299 	DPRINTF(("wi_reset\n"));
   1300 
   1301 	if (sc->sc_reset)
   1302 		(*sc->sc_reset)(sc);
   1303 
   1304 	error = 0;
   1305 	for (i = 0; i < 5; i++) {
   1306 		if (sc->sc_invalid)
   1307 			return ENXIO;
   1308 		DELAY(20*1000);	/* XXX: way too long! */
   1309 		if ((error = wi_cmd(sc, WI_CMD_INI, 0, 0, 0)) == 0)
   1310 			break;
   1311 	}
   1312 	if (error) {
   1313 		aprint_error_dev(sc->sc_dev, "init failed\n");
   1314 		return error;
   1315 	}
   1316 	CSR_WRITE_2(sc, WI_INT_EN, 0);
   1317 	CSR_WRITE_2(sc, WI_EVENT_ACK, ~0);
   1318 
   1319 	/* Calibrate timer. */
   1320 	wi_write_val(sc, WI_RID_TICK_TIME, 0);
   1321 	return 0;
   1322 }
   1323 
   1324 STATIC void
   1325 wi_watchdog(struct ifnet *ifp)
   1326 {
   1327 	struct wi_softc *sc = ifp->if_softc;
   1328 
   1329 	ifp->if_timer = 0;
   1330 	if (!sc->sc_enabled)
   1331 		return;
   1332 
   1333 	if (sc->sc_tx_timer) {
   1334 		if (--sc->sc_tx_timer == 0) {
   1335 			printf("%s: device timeout\n", ifp->if_xname);
   1336 			ifp->if_oerrors++;
   1337 			wi_init(ifp);
   1338 			return;
   1339 		}
   1340 		ifp->if_timer = 1;
   1341 	}
   1342 
   1343 	if (sc->sc_scan_timer) {
   1344 		if (--sc->sc_scan_timer <= WI_SCAN_WAIT - WI_SCAN_INQWAIT &&
   1345 		    sc->sc_firmware_type == WI_INTERSIL) {
   1346 			DPRINTF(("wi_watchdog: inquire scan\n"));
   1347 			wi_cmd(sc, WI_CMD_INQUIRE, WI_INFO_SCAN_RESULTS, 0, 0);
   1348 		}
   1349 		if (sc->sc_scan_timer)
   1350 			ifp->if_timer = 1;
   1351 	}
   1352 
   1353 	/* TODO: rate control */
   1354 	ieee80211_watchdog(&sc->sc_ic);
   1355 }
   1356 
   1357 static int
   1358 wi_ioctl_enter(struct wi_softc *sc)
   1359 {
   1360 	int rc = 0;
   1361 
   1362 	mutex_enter(&sc->sc_ioctl_mtx);
   1363 	sc->sc_ioctl_nwait++;
   1364 	while (sc->sc_ioctl_lwp != NULL && sc->sc_ioctl_lwp != curlwp) {
   1365 		rc = sc->sc_ioctl_gone
   1366 		    ? ENXIO
   1367 		    : cv_wait_sig(&sc->sc_ioctl_cv, &sc->sc_ioctl_mtx);
   1368 		if (rc != 0)
   1369 			break;
   1370 	}
   1371 	if (rc == 0) {
   1372 		sc->sc_ioctl_lwp = curlwp;
   1373 		sc->sc_ioctl_depth++;
   1374 	}
   1375 	if (--sc->sc_ioctl_nwait == 0)
   1376 		cv_signal(&sc->sc_ioctl_cv);
   1377 	mutex_exit(&sc->sc_ioctl_mtx);
   1378 	return rc;
   1379 }
   1380 
   1381 static void
   1382 wi_ioctl_exit(struct wi_softc *sc)
   1383 {
   1384 	KASSERT(sc->sc_ioctl_lwp == curlwp);
   1385 	mutex_enter(&sc->sc_ioctl_mtx);
   1386 	if (--sc->sc_ioctl_depth == 0) {
   1387 		sc->sc_ioctl_lwp = NULL;
   1388 		cv_signal(&sc->sc_ioctl_cv);
   1389 	}
   1390 	mutex_exit(&sc->sc_ioctl_mtx);
   1391 }
   1392 
   1393 static void
   1394 wi_ioctl_init(struct wi_softc *sc)
   1395 {
   1396 	mutex_init(&sc->sc_ioctl_mtx, MUTEX_DEFAULT, IPL_NONE);
   1397 	cv_init(&sc->sc_ioctl_cv, device_xname(sc->sc_dev));
   1398 }
   1399 
   1400 static void
   1401 wi_ioctl_drain(struct wi_softc *sc)
   1402 {
   1403 	wi_ioctl_enter(sc);
   1404 
   1405 	mutex_enter(&sc->sc_ioctl_mtx);
   1406 	sc->sc_ioctl_gone = true;
   1407 	cv_broadcast(&sc->sc_ioctl_cv);
   1408 	while (sc->sc_ioctl_nwait != 0)
   1409 		cv_wait(&sc->sc_ioctl_cv, &sc->sc_ioctl_mtx);
   1410 	mutex_exit(&sc->sc_ioctl_mtx);
   1411 
   1412 	wi_ioctl_exit(sc);
   1413 
   1414 	mutex_destroy(&sc->sc_ioctl_mtx);
   1415 	cv_destroy(&sc->sc_ioctl_cv);
   1416 }
   1417 
   1418 STATIC int
   1419 wi_ioctl(struct ifnet *ifp, u_long cmd, void *data)
   1420 {
   1421 	struct wi_softc *sc = ifp->if_softc;
   1422 	struct ieee80211com *ic = &sc->sc_ic;
   1423 	struct ifreq *ifr = (struct ifreq *)data;
   1424 	int s, error = 0;
   1425 
   1426 	if (!device_is_active(sc->sc_dev))
   1427 		return ENXIO;
   1428 
   1429 	s = splnet();
   1430 
   1431 	if ((error = wi_ioctl_enter(sc)) != 0) {
   1432 		splx(s);
   1433 		return error;
   1434 	}
   1435 
   1436 	switch (cmd) {
   1437 	case SIOCSIFFLAGS:
   1438 		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
   1439 			break;
   1440 		/*
   1441 		 * Can't do promisc and hostap at the same time.  If all that's
   1442 		 * changing is the promisc flag, try to short-circuit a call to
   1443 		 * wi_init() by just setting PROMISC in the hardware.
   1444 		 */
   1445 		if (ifp->if_flags & IFF_UP) {
   1446 			if (sc->sc_enabled) {
   1447 				if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
   1448 				    (ifp->if_flags & IFF_PROMISC) != 0)
   1449 					wi_write_val(sc, WI_RID_PROMISC, 1);
   1450 				else
   1451 					wi_write_val(sc, WI_RID_PROMISC, 0);
   1452 			} else
   1453 				error = wi_init(ifp);
   1454 		} else if (sc->sc_enabled)
   1455 			wi_stop(ifp, 1);
   1456 		break;
   1457 	case SIOCSIFMEDIA:
   1458 	case SIOCGIFMEDIA:
   1459 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
   1460 		break;
   1461 	case SIOCADDMULTI:
   1462 	case SIOCDELMULTI:
   1463 		if ((error = ether_ioctl(ifp, cmd, data)) == ENETRESET) {
   1464 			if (ifp->if_flags & IFF_RUNNING) {
   1465 				/* do not rescan */
   1466 				error = wi_write_multi(sc);
   1467 			} else
   1468 				error = 0;
   1469 		}
   1470 		break;
   1471 	case SIOCGIFGENERIC:
   1472 		error = wi_get_cfg(ifp, cmd, data);
   1473 		break;
   1474 	case SIOCSIFGENERIC:
   1475 		error = kauth_authorize_network(curlwp->l_cred,
   1476 		    KAUTH_NETWORK_INTERFACE,
   1477 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, KAUTH_ARG(cmd),
   1478 		    NULL);
   1479 		if (error)
   1480 			break;
   1481 		error = wi_set_cfg(ifp, cmd, data);
   1482 		if (error == ENETRESET) {
   1483 			if (ifp->if_flags & IFF_RUNNING)
   1484 				error = wi_init(ifp);
   1485 			else
   1486 				error = 0;
   1487 		}
   1488 		break;
   1489 	case SIOCS80211BSSID:
   1490 		if (sc->sc_firmware_type == WI_LUCENT) {
   1491 			error = ENODEV;
   1492 			break;
   1493 		}
   1494 		/* fall through */
   1495 	default:
   1496 		ic->ic_flags |= sc->sc_ic_flags;
   1497 		error = ieee80211_ioctl(&sc->sc_ic, cmd, data);
   1498 		sc->sc_ic_flags = ic->ic_flags & IEEE80211_F_DROPUNENC;
   1499 		if (error == ENETRESET) {
   1500 			if (sc->sc_enabled)
   1501 				error = wi_init(ifp);
   1502 			else
   1503 				error = 0;
   1504 		}
   1505 		break;
   1506 	}
   1507 	wi_mend_flags(sc, ic->ic_state);
   1508 	wi_ioctl_exit(sc);
   1509 	splx(s);
   1510 	return error;
   1511 }
   1512 
   1513 STATIC int
   1514 wi_media_change(struct ifnet *ifp)
   1515 {
   1516 	struct wi_softc *sc = ifp->if_softc;
   1517 	struct ieee80211com *ic = &sc->sc_ic;
   1518 	int error;
   1519 
   1520 	error = ieee80211_media_change(ifp);
   1521 	if (error == ENETRESET) {
   1522 		if (sc->sc_enabled)
   1523 			error = wi_init(ifp);
   1524 		else
   1525 			error = 0;
   1526 	}
   1527 	ifp->if_baudrate = ifmedia_baudrate(ic->ic_media.ifm_cur->ifm_media);
   1528 
   1529 	return error;
   1530 }
   1531 
   1532 STATIC void
   1533 wi_media_status(struct ifnet *ifp, struct ifmediareq *imr)
   1534 {
   1535 	struct wi_softc *sc = ifp->if_softc;
   1536 	struct ieee80211com *ic = &sc->sc_ic;
   1537 	u_int16_t val;
   1538 	int rate;
   1539 
   1540 	if (sc->sc_enabled == 0) {
   1541 		imr->ifm_active = IFM_IEEE80211 | IFM_NONE;
   1542 		imr->ifm_status = 0;
   1543 		return;
   1544 	}
   1545 
   1546 	imr->ifm_status = IFM_AVALID;
   1547 	imr->ifm_active = IFM_IEEE80211;
   1548 	if (ic->ic_state == IEEE80211_S_RUN &&
   1549 	    (sc->sc_flags & WI_FLAGS_OUTRANGE) == 0)
   1550 		imr->ifm_status |= IFM_ACTIVE;
   1551 	if (wi_read_xrid(sc, WI_RID_CUR_TX_RATE, &val, sizeof(val)) == 0) {
   1552 		/* convert to 802.11 rate */
   1553 		val = le16toh(val);
   1554 		rate = val * 2;
   1555 		if (sc->sc_firmware_type == WI_LUCENT) {
   1556 			if (rate == 10)
   1557 				rate = 11;	/* 5.5Mbps */
   1558 		} else {
   1559 			if (rate == 4*2)
   1560 				rate = 11;	/* 5.5Mbps */
   1561 			else if (rate == 8*2)
   1562 				rate = 22;	/* 11Mbps */
   1563 		}
   1564 	} else
   1565 		rate = 0;
   1566 	imr->ifm_active |= ieee80211_rate2media(ic, rate, IEEE80211_MODE_11B);
   1567 	switch (ic->ic_opmode) {
   1568 	case IEEE80211_M_STA:
   1569 		break;
   1570 	case IEEE80211_M_IBSS:
   1571 		imr->ifm_active |= IFM_IEEE80211_ADHOC;
   1572 		break;
   1573 	case IEEE80211_M_AHDEMO:
   1574 		imr->ifm_active |= IFM_IEEE80211_ADHOC | IFM_FLAG0;
   1575 		break;
   1576 	case IEEE80211_M_HOSTAP:
   1577 		imr->ifm_active |= IFM_IEEE80211_HOSTAP;
   1578 		break;
   1579 	case IEEE80211_M_MONITOR:
   1580 		imr->ifm_active |= IFM_IEEE80211_MONITOR;
   1581 		break;
   1582 	}
   1583 }
   1584 
   1585 STATIC struct ieee80211_node *
   1586 wi_node_alloc(struct ieee80211_node_table *nt)
   1587 {
   1588 	struct wi_node *wn =
   1589 	    malloc(sizeof(struct wi_node), M_DEVBUF, M_NOWAIT | M_ZERO);
   1590 	return wn ? &wn->wn_node : NULL;
   1591 }
   1592 
   1593 STATIC void
   1594 wi_node_free(struct ieee80211_node *ni)
   1595 {
   1596 	struct wi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
   1597 	int i;
   1598 
   1599 	for (i = 0; i < WI_NTXRSS; i++) {
   1600 		if (sc->sc_rssd[i].rd_desc.id_node == ni)
   1601 			sc->sc_rssd[i].rd_desc.id_node = NULL;
   1602 	}
   1603 	free(ni, M_DEVBUF);
   1604 }
   1605 
   1606 STATIC void
   1607 wi_sync_bssid(struct wi_softc *sc, u_int8_t new_bssid[IEEE80211_ADDR_LEN])
   1608 {
   1609 	struct ieee80211com *ic = &sc->sc_ic;
   1610 	struct ieee80211_node *ni = ic->ic_bss;
   1611 	struct ifnet *ifp = &sc->sc_if;
   1612 	int s;
   1613 
   1614 	if (IEEE80211_ADDR_EQ(new_bssid, ni->ni_bssid))
   1615 		return;
   1616 
   1617 	DPRINTF(("wi_sync_bssid: bssid %s -> ", ether_sprintf(ni->ni_bssid)));
   1618 	DPRINTF(("%s ?\n", ether_sprintf(new_bssid)));
   1619 
   1620 	/* In promiscuous mode, the BSSID field is not a reliable
   1621 	 * indicator of the firmware's BSSID. Damp spurious
   1622 	 * change-of-BSSID indications.
   1623 	 */
   1624 	if ((ifp->if_flags & IFF_PROMISC) != 0 &&
   1625 	    !ppsratecheck(&sc->sc_last_syn, &sc->sc_false_syns,
   1626 	                 WI_MAX_FALSE_SYNS))
   1627 		return;
   1628 
   1629 	sc->sc_false_syns = MAX(0, sc->sc_false_syns - 1);
   1630 	/*
   1631 	 * XXX hack; we should create a new node with the new bssid
   1632 	 * and replace the existing ic_bss with it but since we don't
   1633 	 * process management frames to collect state we cheat by
   1634 	 * reusing the existing node as we know wi_newstate will be
   1635 	 * called and it will overwrite the node state.
   1636 	 */
   1637 	s = splnet();
   1638         ieee80211_sta_join(ic, ieee80211_ref_node(ni));
   1639 	splx(s);
   1640 }
   1641 
   1642 static inline void
   1643 wi_rssadapt_input(struct ieee80211com *ic, struct ieee80211_node *ni,
   1644     struct ieee80211_frame *wh, int rssi)
   1645 {
   1646 	struct wi_node *wn;
   1647 
   1648 	if (ni == NULL) {
   1649 		printf("%s: null node", __func__);
   1650 		return;
   1651 	}
   1652 
   1653 	wn = (void*)ni;
   1654 	ieee80211_rssadapt_input(ic, ni, &wn->wn_rssadapt, rssi);
   1655 }
   1656 
   1657 STATIC void
   1658 wi_rx_intr(struct wi_softc *sc)
   1659 {
   1660 	struct ieee80211com *ic = &sc->sc_ic;
   1661 	struct ifnet *ifp = &sc->sc_if;
   1662 	struct ieee80211_node *ni;
   1663 	struct wi_frame frmhdr;
   1664 	struct mbuf *m;
   1665 	struct ieee80211_frame *wh;
   1666 	int fid, len, off, rssi;
   1667 	u_int8_t dir;
   1668 	u_int16_t status;
   1669 	u_int32_t rstamp;
   1670 	int s;
   1671 
   1672 	fid = CSR_READ_2(sc, WI_RX_FID);
   1673 
   1674 	/* First read in the frame header */
   1675 	if (wi_read_bap(sc, fid, 0, &frmhdr, sizeof(frmhdr))) {
   1676 		aprint_error_dev(sc->sc_dev, "%s read fid %x failed\n",
   1677 		    __func__, fid);
   1678 		ifp->if_ierrors++;
   1679 		return;
   1680 	}
   1681 
   1682 	if (IFF_DUMPPKTS(ifp))
   1683 		wi_dump_pkt(&frmhdr, NULL, frmhdr.wi_rx_signal);
   1684 
   1685 	/*
   1686 	 * Drop undecryptable or packets with receive errors here
   1687 	 */
   1688 	status = le16toh(frmhdr.wi_status);
   1689 	if ((status & WI_STAT_ERRSTAT) != 0 &&
   1690 	    ic->ic_opmode != IEEE80211_M_MONITOR) {
   1691 		ifp->if_ierrors++;
   1692 		DPRINTF(("wi_rx_intr: fid %x error status %x\n", fid, status));
   1693 		return;
   1694 	}
   1695 	rssi = frmhdr.wi_rx_signal;
   1696 	rstamp = (le16toh(frmhdr.wi_rx_tstamp0) << 16) |
   1697 	    le16toh(frmhdr.wi_rx_tstamp1);
   1698 
   1699 	len = le16toh(frmhdr.wi_dat_len);
   1700 	off = ALIGN(sizeof(struct ieee80211_frame));
   1701 
   1702 	/* Sometimes the PRISM2.x returns bogusly large frames. Except
   1703 	 * in monitor mode, just throw them away.
   1704 	 */
   1705 	if (off + len > MCLBYTES) {
   1706 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
   1707 			ifp->if_ierrors++;
   1708 			DPRINTF(("wi_rx_intr: oversized packet\n"));
   1709 			return;
   1710 		} else
   1711 			len = 0;
   1712 	}
   1713 
   1714 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   1715 	if (m == NULL) {
   1716 		ifp->if_ierrors++;
   1717 		DPRINTF(("wi_rx_intr: MGET failed\n"));
   1718 		return;
   1719 	}
   1720 	if (off + len > MHLEN) {
   1721 		MCLGET(m, M_DONTWAIT);
   1722 		if ((m->m_flags & M_EXT) == 0) {
   1723 			m_freem(m);
   1724 			ifp->if_ierrors++;
   1725 			DPRINTF(("wi_rx_intr: MCLGET failed\n"));
   1726 			return;
   1727 		}
   1728 	}
   1729 
   1730 	m->m_data += off - sizeof(struct ieee80211_frame);
   1731 	memcpy(m->m_data, &frmhdr.wi_whdr, sizeof(struct ieee80211_frame));
   1732 	wi_read_bap(sc, fid, sizeof(frmhdr),
   1733 	    m->m_data + sizeof(struct ieee80211_frame), len);
   1734 	m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame) + len;
   1735 	m_set_rcvif(m, ifp);
   1736 
   1737 	wh = mtod(m, struct ieee80211_frame *);
   1738 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
   1739 		/*
   1740 		 * WEP is decrypted by hardware. Clear WEP bit
   1741 		 * header for ieee80211_input().
   1742 		 */
   1743 		wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
   1744 	}
   1745 
   1746 	s = splnet();
   1747 
   1748 	if (sc->sc_drvbpf) {
   1749 		struct wi_rx_radiotap_header *tap = &sc->sc_rxtap;
   1750 
   1751 		tap->wr_rate = frmhdr.wi_rx_rate / 5;
   1752 		tap->wr_antsignal = frmhdr.wi_rx_signal;
   1753 		tap->wr_antnoise = frmhdr.wi_rx_silence;
   1754 		tap->wr_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
   1755 		tap->wr_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
   1756 		if (frmhdr.wi_status & WI_STAT_PCF)
   1757 			tap->wr_flags |= IEEE80211_RADIOTAP_F_CFP;
   1758 
   1759 		/* XXX IEEE80211_RADIOTAP_F_WEP */
   1760 		bpf_mtap2(sc->sc_drvbpf, tap, tap->wr_ihdr.it_len, m,
   1761 		    BPF_D_IN);
   1762 	}
   1763 
   1764 	/* synchronize driver's BSSID with firmware's BSSID */
   1765 	dir = wh->i_fc[1] & IEEE80211_FC1_DIR_MASK;
   1766 	if (ic->ic_opmode == IEEE80211_M_IBSS && dir == IEEE80211_FC1_DIR_NODS)
   1767 		wi_sync_bssid(sc, wh->i_addr3);
   1768 
   1769 	ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *));
   1770 
   1771 	ieee80211_input(ic, m, ni, rssi, rstamp);
   1772 
   1773 	wi_rssadapt_input(ic, ni, wh, rssi);
   1774 
   1775 	/*
   1776 	 * The frame may have caused the node to be marked for
   1777 	 * reclamation (e.g. in response to a DEAUTH message)
   1778 	 * so use release_node here instead of unref_node.
   1779 	 */
   1780 	ieee80211_free_node(ni);
   1781 
   1782 	splx(s);
   1783 }
   1784 
   1785 STATIC void
   1786 wi_tx_ex_intr(struct wi_softc *sc)
   1787 {
   1788 	struct ieee80211com *ic = &sc->sc_ic;
   1789 	struct ifnet *ifp = &sc->sc_if;
   1790 	struct ieee80211_node *ni;
   1791 	struct ieee80211_rssdesc *id;
   1792 	struct wi_rssdesc *rssd;
   1793 	struct wi_frame frmhdr;
   1794 	int fid, s;
   1795 	u_int16_t status;
   1796 
   1797 	s = splnet();
   1798 
   1799 	fid = CSR_READ_2(sc, WI_TX_CMP_FID);
   1800 	/* Read in the frame header */
   1801 	if (wi_read_bap(sc, fid, 0, &frmhdr, sizeof(frmhdr)) != 0) {
   1802 		aprint_error_dev(sc->sc_dev, "%s read fid %x failed\n",
   1803 		    __func__, fid);
   1804 		wi_rssdescs_reset(ic, &sc->sc_rssd, &sc->sc_rssdfree,
   1805 		    &sc->sc_txpending);
   1806 		goto out;
   1807 	}
   1808 
   1809 	if (frmhdr.wi_tx_idx >= WI_NTXRSS) {
   1810 		aprint_error_dev(sc->sc_dev, "%s bad idx %02x\n",
   1811 		    __func__, frmhdr.wi_tx_idx);
   1812 		wi_rssdescs_reset(ic, &sc->sc_rssd, &sc->sc_rssdfree,
   1813 		    &sc->sc_txpending);
   1814 		goto out;
   1815 	}
   1816 
   1817 	status = le16toh(frmhdr.wi_status);
   1818 
   1819 	/*
   1820 	 * Spontaneous station disconnects appear as xmit
   1821 	 * errors.  Don't announce them and/or count them
   1822 	 * as an output error.
   1823 	 */
   1824 	if (ppsratecheck(&lasttxerror, &curtxeps, wi_txerate)) {
   1825 		aprint_error_dev(sc->sc_dev, "tx failed");
   1826 		if (status & WI_TXSTAT_RET_ERR)
   1827 			printf(", retry limit exceeded");
   1828 		if (status & WI_TXSTAT_AGED_ERR)
   1829 			printf(", max transmit lifetime exceeded");
   1830 		if (status & WI_TXSTAT_DISCONNECT)
   1831 			printf(", port disconnected");
   1832 		if (status & WI_TXSTAT_FORM_ERR)
   1833 			printf(", invalid format (data len %u src %s)",
   1834 				le16toh(frmhdr.wi_dat_len),
   1835 				ether_sprintf(frmhdr.wi_ehdr.ether_shost));
   1836 		if (status & ~0xf)
   1837 			printf(", status=0x%x", status);
   1838 		printf("\n");
   1839 	}
   1840 	ifp->if_oerrors++;
   1841 	rssd = &sc->sc_rssd[frmhdr.wi_tx_idx];
   1842 	id = &rssd->rd_desc;
   1843 	if ((status & WI_TXSTAT_RET_ERR) != 0)
   1844 		wi_lower_rate(ic, id);
   1845 
   1846 	ni = id->id_node;
   1847 	id->id_node = NULL;
   1848 
   1849 	if (ni == NULL) {
   1850 		aprint_error_dev(sc->sc_dev, "%s null node, rssdesc %02x\n",
   1851 		    __func__, frmhdr.wi_tx_idx);
   1852 		goto out;
   1853 	}
   1854 
   1855 	if (sc->sc_txpending[id->id_rateidx]-- == 0) {
   1856 		aprint_error_dev(sc->sc_dev, "%s txpending[%i] wraparound",
   1857 		    __func__, id->id_rateidx);
   1858 		sc->sc_txpending[id->id_rateidx] = 0;
   1859 	}
   1860 	if (ni != NULL)
   1861 		ieee80211_free_node(ni);
   1862 	SLIST_INSERT_HEAD(&sc->sc_rssdfree, rssd, rd_next);
   1863 out:
   1864 	ifp->if_flags &= ~IFF_OACTIVE;
   1865 	splx(s);
   1866 }
   1867 
   1868 STATIC void
   1869 wi_txalloc_intr(struct wi_softc *sc)
   1870 {
   1871 	int fid, cur, s;
   1872 
   1873 	s = splnet();
   1874 
   1875 	fid = CSR_READ_2(sc, WI_ALLOC_FID);
   1876 
   1877 	cur = sc->sc_txalloc;
   1878 #ifdef DIAGNOSTIC
   1879 	if (sc->sc_txstarted == 0) {
   1880 		printf("%s: spurious alloc %x != %x, alloc %d queue %d start %d alloced %d queued %d started %d\n",
   1881 		    device_xname(sc->sc_dev), fid, sc->sc_txd[cur].d_fid, cur,
   1882 		    sc->sc_txqueue, sc->sc_txstart, sc->sc_txalloced, sc->sc_txqueued, sc->sc_txstarted);
   1883 		splx(s);
   1884 		return;
   1885 	}
   1886 #endif
   1887 	--sc->sc_txstarted;
   1888 	++sc->sc_txalloced;
   1889 	sc->sc_txd[cur].d_fid = fid;
   1890 	sc->sc_txalloc = (cur + 1) % WI_NTXBUF;
   1891 #ifdef WI_RING_DEBUG
   1892 	printf("%s: alloc %04x, alloc %d queue %d start %d alloced %d queued %d started %d\n",
   1893 	    device_xname(sc->sc_dev), fid,
   1894 	    sc->sc_txalloc, sc->sc_txqueue, sc->sc_txstart,
   1895 	    sc->sc_txalloced, sc->sc_txqueued, sc->sc_txstarted);
   1896 #endif
   1897 	splx(s);
   1898 }
   1899 
   1900 STATIC void
   1901 wi_cmd_intr(struct wi_softc *sc)
   1902 {
   1903 	struct ifnet *ifp = &sc->sc_if;
   1904 	int s;
   1905 
   1906 	if (sc->sc_invalid)
   1907 		return;
   1908 
   1909 	s = splnet();
   1910 #ifdef WI_DEBUG
   1911 	if (wi_debug > 1)
   1912 		printf("%s: %d txcmds outstanding\n", __func__, sc->sc_txcmds);
   1913 #endif
   1914 	KASSERT(sc->sc_txcmds > 0);
   1915 
   1916 	--sc->sc_txcmds;
   1917 
   1918 	if (--sc->sc_txqueued == 0) {
   1919 		sc->sc_tx_timer = 0;
   1920 		ifp->if_flags &= ~IFF_OACTIVE;
   1921 #ifdef WI_RING_DEBUG
   1922 	printf("%s: cmd       , alloc %d queue %d start %d alloced %d queued %d started %d\n",
   1923 	    device_xname(sc->sc_dev),
   1924 	    sc->sc_txalloc, sc->sc_txqueue, sc->sc_txstart,
   1925 	    sc->sc_txalloced, sc->sc_txqueued, sc->sc_txstarted);
   1926 #endif
   1927 	} else
   1928 		wi_push_packet(sc);
   1929 	splx(s);
   1930 }
   1931 
   1932 STATIC void
   1933 wi_push_packet(struct wi_softc *sc)
   1934 {
   1935 	struct ifnet *ifp = &sc->sc_if;
   1936 	int cur, fid;
   1937 
   1938 	cur = sc->sc_txstart;
   1939 	fid = sc->sc_txd[cur].d_fid;
   1940 
   1941 	KASSERT(sc->sc_txcmds == 0);
   1942 
   1943 	if (wi_cmd_start(sc, WI_CMD_TX | WI_RECLAIM, fid, 0, 0)) {
   1944 		aprint_error_dev(sc->sc_dev, "xmit failed\n");
   1945 		/* XXX ring might have a hole */
   1946 	}
   1947 
   1948 	if (sc->sc_txcmds++ > 0)
   1949 		printf("%s: %d tx cmds pending!!!\n", __func__, sc->sc_txcmds);
   1950 
   1951 	++sc->sc_txstarted;
   1952 #ifdef DIAGNOSTIC
   1953 	if (sc->sc_txstarted > WI_NTXBUF)
   1954 		aprint_error_dev(sc->sc_dev, "too many buffers started\n");
   1955 #endif
   1956 	sc->sc_txstart = (cur + 1) % WI_NTXBUF;
   1957 	sc->sc_tx_timer = 5;
   1958 	ifp->if_timer = 1;
   1959 #ifdef WI_RING_DEBUG
   1960 	printf("%s: push  %04x, alloc %d queue %d start %d alloced %d queued %d started %d\n",
   1961 	    device_xname(sc->sc_dev), fid,
   1962 	    sc->sc_txalloc, sc->sc_txqueue, sc->sc_txstart,
   1963 	    sc->sc_txalloced, sc->sc_txqueued, sc->sc_txstarted);
   1964 #endif
   1965 }
   1966 
   1967 STATIC void
   1968 wi_tx_intr(struct wi_softc *sc)
   1969 {
   1970 	struct ieee80211com *ic = &sc->sc_ic;
   1971 	struct ifnet *ifp = &sc->sc_if;
   1972 	struct ieee80211_node *ni;
   1973 	struct ieee80211_rssdesc *id;
   1974 	struct wi_rssdesc *rssd;
   1975 	struct wi_frame frmhdr;
   1976 	int fid, s;
   1977 
   1978 	s = splnet();
   1979 
   1980 	fid = CSR_READ_2(sc, WI_TX_CMP_FID);
   1981 	/* Read in the frame header */
   1982 	if (wi_read_bap(sc, fid, offsetof(struct wi_frame, wi_tx_swsup2),
   1983 	                &frmhdr.wi_tx_swsup2, 2) != 0) {
   1984 		aprint_error_dev(sc->sc_dev, "%s read fid %x failed\n",
   1985 		    __func__, fid);
   1986 		wi_rssdescs_reset(ic, &sc->sc_rssd, &sc->sc_rssdfree,
   1987 		    &sc->sc_txpending);
   1988 		goto out;
   1989 	}
   1990 
   1991 	if (frmhdr.wi_tx_idx >= WI_NTXRSS) {
   1992 		aprint_error_dev(sc->sc_dev, "%s bad idx %02x\n",
   1993 		    __func__, frmhdr.wi_tx_idx);
   1994 		wi_rssdescs_reset(ic, &sc->sc_rssd, &sc->sc_rssdfree,
   1995 		    &sc->sc_txpending);
   1996 		goto out;
   1997 	}
   1998 
   1999 	rssd = &sc->sc_rssd[frmhdr.wi_tx_idx];
   2000 	id = &rssd->rd_desc;
   2001 	wi_raise_rate(ic, id);
   2002 
   2003 	ni = id->id_node;
   2004 	id->id_node = NULL;
   2005 
   2006 	if (ni == NULL) {
   2007 		aprint_error_dev(sc->sc_dev, "%s null node, rssdesc %02x\n",
   2008 		    __func__, frmhdr.wi_tx_idx);
   2009 		goto out;
   2010 	}
   2011 
   2012 	if (sc->sc_txpending[id->id_rateidx]-- == 0) {
   2013 		aprint_error_dev(sc->sc_dev, "%s txpending[%i] wraparound",
   2014 		    __func__, id->id_rateidx);
   2015 		sc->sc_txpending[id->id_rateidx] = 0;
   2016 	}
   2017 	if (ni != NULL)
   2018 		ieee80211_free_node(ni);
   2019 	SLIST_INSERT_HEAD(&sc->sc_rssdfree, rssd, rd_next);
   2020 out:
   2021 	ifp->if_flags &= ~IFF_OACTIVE;
   2022 	splx(s);
   2023 }
   2024 
   2025 STATIC void
   2026 wi_info_intr(struct wi_softc *sc)
   2027 {
   2028 	struct ieee80211com *ic = &sc->sc_ic;
   2029 	struct ifnet *ifp = &sc->sc_if;
   2030 	int i, s, fid, len, off;
   2031 	u_int16_t ltbuf[2];
   2032 	u_int16_t stat;
   2033 	u_int32_t *ptr;
   2034 
   2035 	fid = CSR_READ_2(sc, WI_INFO_FID);
   2036 	wi_read_bap(sc, fid, 0, ltbuf, sizeof(ltbuf));
   2037 
   2038 	switch (le16toh(ltbuf[1])) {
   2039 
   2040 	case WI_INFO_LINK_STAT:
   2041 		wi_read_bap(sc, fid, sizeof(ltbuf), &stat, sizeof(stat));
   2042 		DPRINTF(("wi_info_intr: LINK_STAT 0x%x\n", le16toh(stat)));
   2043 		switch (le16toh(stat)) {
   2044 		case CONNECTED:
   2045 			sc->sc_flags &= ~WI_FLAGS_OUTRANGE;
   2046 			if (ic->ic_state == IEEE80211_S_RUN &&
   2047 			    ic->ic_opmode != IEEE80211_M_IBSS)
   2048 				break;
   2049 			/* FALLTHROUGH */
   2050 		case AP_CHANGE:
   2051 			s = splnet();
   2052 			ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
   2053 			splx(s);
   2054 			break;
   2055 		case AP_IN_RANGE:
   2056 			sc->sc_flags &= ~WI_FLAGS_OUTRANGE;
   2057 			break;
   2058 		case AP_OUT_OF_RANGE:
   2059 			if (sc->sc_firmware_type == WI_SYMBOL &&
   2060 			    sc->sc_scan_timer > 0) {
   2061 				if (wi_cmd(sc, WI_CMD_INQUIRE,
   2062 				    WI_INFO_HOST_SCAN_RESULTS, 0, 0) != 0)
   2063 					sc->sc_scan_timer = 0;
   2064 				break;
   2065 			}
   2066 			if (ic->ic_opmode == IEEE80211_M_STA)
   2067 				sc->sc_flags |= WI_FLAGS_OUTRANGE;
   2068 			break;
   2069 		case DISCONNECTED:
   2070 		case ASSOC_FAILED:
   2071 			s = splnet();
   2072 			if (ic->ic_opmode == IEEE80211_M_STA)
   2073 				ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
   2074 			splx(s);
   2075 			break;
   2076 		}
   2077 		break;
   2078 
   2079 	case WI_INFO_COUNTERS:
   2080 		/* some card versions have a larger stats structure */
   2081 		len = min(le16toh(ltbuf[0]) - 1, sizeof(sc->sc_stats) / 4);
   2082 		ptr = (u_int32_t *)&sc->sc_stats;
   2083 		off = sizeof(ltbuf);
   2084 		for (i = 0; i < len; i++, off += 2, ptr++) {
   2085 			wi_read_bap(sc, fid, off, &stat, sizeof(stat));
   2086 			stat = le16toh(stat);
   2087 #ifdef WI_HERMES_STATS_WAR
   2088 			if (stat & 0xf000)
   2089 				stat = ~stat;
   2090 #endif
   2091 			*ptr += stat;
   2092 		}
   2093 		ifp->if_collisions = sc->sc_stats.wi_tx_single_retries +
   2094 		    sc->sc_stats.wi_tx_multi_retries +
   2095 		    sc->sc_stats.wi_tx_retry_limit;
   2096 		break;
   2097 
   2098 	case WI_INFO_SCAN_RESULTS:
   2099 	case WI_INFO_HOST_SCAN_RESULTS:
   2100 		wi_scan_result(sc, fid, le16toh(ltbuf[0]));
   2101 		break;
   2102 
   2103 	default:
   2104 		DPRINTF(("wi_info_intr: got fid %x type %x len %d\n", fid,
   2105 		    le16toh(ltbuf[1]), le16toh(ltbuf[0])));
   2106 		break;
   2107 	}
   2108 }
   2109 
   2110 STATIC int
   2111 wi_write_multi(struct wi_softc *sc)
   2112 {
   2113 	struct ifnet *ifp = &sc->sc_if;
   2114 	int n;
   2115 	struct wi_mcast mlist;
   2116 	struct ether_multi *enm;
   2117 	struct ether_multistep estep;
   2118 
   2119 	if ((ifp->if_flags & IFF_PROMISC) != 0) {
   2120 allmulti:
   2121 		ifp->if_flags |= IFF_ALLMULTI;
   2122 		memset(&mlist, 0, sizeof(mlist));
   2123 		return wi_write_rid(sc, WI_RID_MCAST_LIST, &mlist,
   2124 		    sizeof(mlist));
   2125 	}
   2126 
   2127 	n = 0;
   2128 	ETHER_FIRST_MULTI(estep, &sc->sc_ec, enm);
   2129 	while (enm != NULL) {
   2130 		/* Punt on ranges or too many multicast addresses. */
   2131 		if (!IEEE80211_ADDR_EQ(enm->enm_addrlo, enm->enm_addrhi) ||
   2132 		    n >= sizeof(mlist) / sizeof(mlist.wi_mcast[0]))
   2133 			goto allmulti;
   2134 
   2135 		IEEE80211_ADDR_COPY(&mlist.wi_mcast[n], enm->enm_addrlo);
   2136 		n++;
   2137 		ETHER_NEXT_MULTI(estep, enm);
   2138 	}
   2139 	ifp->if_flags &= ~IFF_ALLMULTI;
   2140 	return wi_write_rid(sc, WI_RID_MCAST_LIST, &mlist,
   2141 	    IEEE80211_ADDR_LEN * n);
   2142 }
   2143 
   2144 
   2145 STATIC void
   2146 wi_read_nicid(struct wi_softc *sc)
   2147 {
   2148 	const struct wi_card_ident *id;
   2149 	char *p;
   2150 	int len;
   2151 	u_int16_t ver[4];
   2152 
   2153 	/* getting chip identity */
   2154 	memset(ver, 0, sizeof(ver));
   2155 	len = sizeof(ver);
   2156 	wi_read_rid(sc, WI_RID_CARD_ID, ver, &len);
   2157 	printf("%s: using ", device_xname(sc->sc_dev));
   2158 DPRINTF2(("wi_read_nicid: CARD_ID: %x %x %x %x\n", le16toh(ver[0]), le16toh(ver[1]), le16toh(ver[2]), le16toh(ver[3])));
   2159 
   2160 	sc->sc_firmware_type = WI_NOTYPE;
   2161 	for (id = wi_card_ident; id->card_name != NULL; id++) {
   2162 		if (le16toh(ver[0]) == id->card_id) {
   2163 			printf("%s", id->card_name);
   2164 			sc->sc_firmware_type = id->firm_type;
   2165 			break;
   2166 		}
   2167 	}
   2168 	if (sc->sc_firmware_type == WI_NOTYPE) {
   2169 		if (le16toh(ver[0]) & 0x8000) {
   2170 			printf("Unknown PRISM2 chip");
   2171 			sc->sc_firmware_type = WI_INTERSIL;
   2172 		} else {
   2173 			printf("Unknown Lucent chip");
   2174 			sc->sc_firmware_type = WI_LUCENT;
   2175 		}
   2176 	}
   2177 
   2178 	/* get primary firmware version (Only Prism chips) */
   2179 	if (sc->sc_firmware_type != WI_LUCENT) {
   2180 		memset(ver, 0, sizeof(ver));
   2181 		len = sizeof(ver);
   2182 		wi_read_rid(sc, WI_RID_PRI_IDENTITY, ver, &len);
   2183 		sc->sc_pri_firmware_ver = le16toh(ver[2]) * 10000 +
   2184 		    le16toh(ver[3]) * 100 + le16toh(ver[1]);
   2185 	}
   2186 
   2187 	/* get station firmware version */
   2188 	memset(ver, 0, sizeof(ver));
   2189 	len = sizeof(ver);
   2190 	wi_read_rid(sc, WI_RID_STA_IDENTITY, ver, &len);
   2191 	sc->sc_sta_firmware_ver = le16toh(ver[2]) * 10000 +
   2192 	    le16toh(ver[3]) * 100 + le16toh(ver[1]);
   2193 	if (sc->sc_firmware_type == WI_INTERSIL &&
   2194 	    (sc->sc_sta_firmware_ver == 10102 ||
   2195 	     sc->sc_sta_firmware_ver == 20102)) {
   2196 		char ident[12];
   2197 		memset(ident, 0, sizeof(ident));
   2198 		len = sizeof(ident);
   2199 		/* value should be the format like "V2.00-11" */
   2200 		if (wi_read_rid(sc, WI_RID_SYMBOL_IDENTITY, ident, &len) == 0 &&
   2201 		    *(p = (char *)ident) >= 'A' &&
   2202 		    p[2] == '.' && p[5] == '-' && p[8] == '\0') {
   2203 			sc->sc_firmware_type = WI_SYMBOL;
   2204 			sc->sc_sta_firmware_ver = (p[1] - '0') * 10000 +
   2205 			    (p[3] - '0') * 1000 + (p[4] - '0') * 100 +
   2206 			    (p[6] - '0') * 10 + (p[7] - '0');
   2207 		}
   2208 	}
   2209 
   2210 	printf("\n%s: %s Firmware: ", device_xname(sc->sc_dev),
   2211 	     sc->sc_firmware_type == WI_LUCENT ? "Lucent" :
   2212 	    (sc->sc_firmware_type == WI_SYMBOL ? "Symbol" : "Intersil"));
   2213 	if (sc->sc_firmware_type != WI_LUCENT)	/* XXX */
   2214 		printf("Primary (%u.%u.%u), ",
   2215 		    sc->sc_pri_firmware_ver / 10000,
   2216 		    (sc->sc_pri_firmware_ver % 10000) / 100,
   2217 		    sc->sc_pri_firmware_ver % 100);
   2218 	printf("Station (%u.%u.%u)\n",
   2219 	    sc->sc_sta_firmware_ver / 10000,
   2220 	    (sc->sc_sta_firmware_ver % 10000) / 100,
   2221 	    sc->sc_sta_firmware_ver % 100);
   2222 }
   2223 
   2224 STATIC int
   2225 wi_write_ssid(struct wi_softc *sc, int rid, u_int8_t *buf, int buflen)
   2226 {
   2227 	struct wi_ssid ssid;
   2228 
   2229 	if (buflen > IEEE80211_NWID_LEN)
   2230 		return ENOBUFS;
   2231 	memset(&ssid, 0, sizeof(ssid));
   2232 	ssid.wi_len = htole16(buflen);
   2233 	memcpy(ssid.wi_ssid, buf, buflen);
   2234 	return wi_write_rid(sc, rid, &ssid, sizeof(ssid));
   2235 }
   2236 
   2237 STATIC int
   2238 wi_get_cfg(struct ifnet *ifp, u_long cmd, void *data)
   2239 {
   2240 	struct wi_softc *sc = ifp->if_softc;
   2241 	struct ieee80211com *ic = &sc->sc_ic;
   2242 	struct ifreq *ifr = (struct ifreq *)data;
   2243 	struct wi_req wreq;
   2244 	int len, n, error;
   2245 
   2246 	error = copyin(ifr->ifr_data, &wreq, sizeof(wreq));
   2247 	if (error)
   2248 		return error;
   2249 	len = (wreq.wi_len - 1) * 2;
   2250 	if (len < sizeof(u_int16_t))
   2251 		return ENOSPC;
   2252 	if (len > sizeof(wreq.wi_val))
   2253 		len = sizeof(wreq.wi_val);
   2254 
   2255 	switch (wreq.wi_type) {
   2256 
   2257 	case WI_RID_IFACE_STATS:
   2258 		memcpy(wreq.wi_val, &sc->sc_stats, sizeof(sc->sc_stats));
   2259 		if (len < sizeof(sc->sc_stats))
   2260 			error = ENOSPC;
   2261 		else
   2262 			len = sizeof(sc->sc_stats);
   2263 		break;
   2264 
   2265 	case WI_RID_ENCRYPTION:
   2266 	case WI_RID_TX_CRYPT_KEY:
   2267 	case WI_RID_DEFLT_CRYPT_KEYS:
   2268 	case WI_RID_TX_RATE:
   2269 		return ieee80211_cfgget(ic, cmd, data);
   2270 
   2271 	case WI_RID_MICROWAVE_OVEN:
   2272 		if (sc->sc_enabled && (sc->sc_flags & WI_FLAGS_HAS_MOR)) {
   2273 			error = wi_read_rid(sc, wreq.wi_type, wreq.wi_val,
   2274 			    &len);
   2275 			break;
   2276 		}
   2277 		wreq.wi_val[0] = htole16(sc->sc_microwave_oven);
   2278 		len = sizeof(u_int16_t);
   2279 		break;
   2280 
   2281 	case WI_RID_DBM_ADJUST:
   2282 		if (sc->sc_enabled && (sc->sc_flags & WI_FLAGS_HAS_DBMADJUST)) {
   2283 			error = wi_read_rid(sc, wreq.wi_type, wreq.wi_val,
   2284 			    &len);
   2285 			break;
   2286 		}
   2287 		wreq.wi_val[0] = htole16(sc->sc_dbm_offset);
   2288 		len = sizeof(u_int16_t);
   2289 		break;
   2290 
   2291 	case WI_RID_ROAMING_MODE:
   2292 		if (sc->sc_enabled && (sc->sc_flags & WI_FLAGS_HAS_ROAMING)) {
   2293 			error = wi_read_rid(sc, wreq.wi_type, wreq.wi_val,
   2294 			    &len);
   2295 			break;
   2296 		}
   2297 		wreq.wi_val[0] = htole16(sc->sc_roaming_mode);
   2298 		len = sizeof(u_int16_t);
   2299 		break;
   2300 
   2301 	case WI_RID_SYSTEM_SCALE:
   2302 		if (sc->sc_enabled && (sc->sc_flags & WI_FLAGS_HAS_SYSSCALE)) {
   2303 			error = wi_read_rid(sc, wreq.wi_type, wreq.wi_val,
   2304 			    &len);
   2305 			break;
   2306 		}
   2307 		wreq.wi_val[0] = htole16(sc->sc_system_scale);
   2308 		len = sizeof(u_int16_t);
   2309 		break;
   2310 
   2311 	case WI_RID_FRAG_THRESH:
   2312 		if (sc->sc_enabled && (sc->sc_flags & WI_FLAGS_HAS_FRAGTHR)) {
   2313 			error = wi_read_rid(sc, wreq.wi_type, wreq.wi_val,
   2314 			    &len);
   2315 			break;
   2316 		}
   2317 		wreq.wi_val[0] = htole16(sc->sc_frag_thresh);
   2318 		len = sizeof(u_int16_t);
   2319 		break;
   2320 
   2321 	case WI_RID_READ_APS:
   2322 #ifndef	IEEE80211_NO_HOSTAP
   2323 		if (ic->ic_opmode == IEEE80211_M_HOSTAP)
   2324 			return ieee80211_cfgget(ic, cmd, data);
   2325 #endif /* !IEEE80211_NO_HOSTAP */
   2326 		if (sc->sc_scan_timer > 0) {
   2327 			error = EINPROGRESS;
   2328 			break;
   2329 		}
   2330 		n = sc->sc_naps;
   2331 		if (len < sizeof(n)) {
   2332 			error = ENOSPC;
   2333 			break;
   2334 		}
   2335 		if (len < sizeof(n) + sizeof(struct wi_apinfo) * n)
   2336 			n = (len - sizeof(n)) / sizeof(struct wi_apinfo);
   2337 		len = sizeof(n) + sizeof(struct wi_apinfo) * n;
   2338 		memcpy(wreq.wi_val, &n, sizeof(n));
   2339 		memcpy((char *)wreq.wi_val + sizeof(n), sc->sc_aps,
   2340 		    sizeof(struct wi_apinfo) * n);
   2341 		break;
   2342 
   2343 	default:
   2344 		if (sc->sc_enabled) {
   2345 			error = wi_read_rid(sc, wreq.wi_type, wreq.wi_val,
   2346 			    &len);
   2347 			break;
   2348 		}
   2349 		switch (wreq.wi_type) {
   2350 		case WI_RID_MAX_DATALEN:
   2351 			wreq.wi_val[0] = htole16(sc->sc_max_datalen);
   2352 			len = sizeof(u_int16_t);
   2353 			break;
   2354 		case WI_RID_FRAG_THRESH:
   2355 			wreq.wi_val[0] = htole16(sc->sc_frag_thresh);
   2356 			len = sizeof(u_int16_t);
   2357 			break;
   2358 		case WI_RID_RTS_THRESH:
   2359 			wreq.wi_val[0] = htole16(sc->sc_rts_thresh);
   2360 			len = sizeof(u_int16_t);
   2361 			break;
   2362 		case WI_RID_CNFAUTHMODE:
   2363 			wreq.wi_val[0] = htole16(sc->sc_cnfauthmode);
   2364 			len = sizeof(u_int16_t);
   2365 			break;
   2366 		case WI_RID_NODENAME:
   2367 			if (len < sc->sc_nodelen + sizeof(u_int16_t)) {
   2368 				error = ENOSPC;
   2369 				break;
   2370 			}
   2371 			len = sc->sc_nodelen + sizeof(u_int16_t);
   2372 			wreq.wi_val[0] = htole16((sc->sc_nodelen + 1) / 2);
   2373 			memcpy(&wreq.wi_val[1], sc->sc_nodename,
   2374 			    sc->sc_nodelen);
   2375 			break;
   2376 		default:
   2377 			return ieee80211_cfgget(ic, cmd, data);
   2378 		}
   2379 		break;
   2380 	}
   2381 	if (error)
   2382 		return error;
   2383 	wreq.wi_len = (len + 1) / 2 + 1;
   2384 	return copyout(&wreq, ifr->ifr_data, (wreq.wi_len + 1) * 2);
   2385 }
   2386 
   2387 STATIC int
   2388 wi_set_cfg(struct ifnet *ifp, u_long cmd, void *data)
   2389 {
   2390 	struct wi_softc *sc = ifp->if_softc;
   2391 	struct ieee80211com *ic = &sc->sc_ic;
   2392 	struct ifreq *ifr = (struct ifreq *)data;
   2393 	struct ieee80211_rateset *rs = &ic->ic_sup_rates[IEEE80211_MODE_11B];
   2394 	struct wi_req wreq;
   2395 	struct mbuf *m;
   2396 	int i, len, error;
   2397 
   2398 	error = copyin(ifr->ifr_data, &wreq, sizeof(wreq));
   2399 	if (error)
   2400 		return error;
   2401 	len = (wreq.wi_len - 1) * 2;
   2402 	switch (wreq.wi_type) {
   2403         case WI_RID_MAC_NODE:
   2404 		/* XXX convert to SIOCALIFADDR, AF_LINK, IFLR_ACTIVE */
   2405 		(void)memcpy(ic->ic_myaddr, wreq.wi_val, ETHER_ADDR_LEN);
   2406 		if_set_sadl(ifp, ic->ic_myaddr, ETHER_ADDR_LEN, false);
   2407 		wi_write_rid(sc, WI_RID_MAC_NODE, ic->ic_myaddr,
   2408 		    IEEE80211_ADDR_LEN);
   2409 		break;
   2410 
   2411 	case WI_RID_DBM_ADJUST:
   2412 		return ENODEV;
   2413 
   2414 	case WI_RID_NODENAME:
   2415 		if (le16toh(wreq.wi_val[0]) * 2 > len ||
   2416 		    le16toh(wreq.wi_val[0]) > sizeof(sc->sc_nodename)) {
   2417 			error = ENOSPC;
   2418 			break;
   2419 		}
   2420 		if (sc->sc_enabled) {
   2421 			error = wi_write_rid(sc, wreq.wi_type, wreq.wi_val,
   2422 			    len);
   2423 			if (error)
   2424 				break;
   2425 		}
   2426 		sc->sc_nodelen = le16toh(wreq.wi_val[0]) * 2;
   2427 		memcpy(sc->sc_nodename, &wreq.wi_val[1], sc->sc_nodelen);
   2428 		break;
   2429 
   2430 	case WI_RID_MICROWAVE_OVEN:
   2431 	case WI_RID_ROAMING_MODE:
   2432 	case WI_RID_SYSTEM_SCALE:
   2433 	case WI_RID_FRAG_THRESH:
   2434 		if (wreq.wi_type == WI_RID_MICROWAVE_OVEN &&
   2435 		    (sc->sc_flags & WI_FLAGS_HAS_MOR) == 0)
   2436 			break;
   2437 		if (wreq.wi_type == WI_RID_ROAMING_MODE &&
   2438 		    (sc->sc_flags & WI_FLAGS_HAS_ROAMING) == 0)
   2439 			break;
   2440 		if (wreq.wi_type == WI_RID_SYSTEM_SCALE &&
   2441 		    (sc->sc_flags & WI_FLAGS_HAS_SYSSCALE) == 0)
   2442 			break;
   2443 		if (wreq.wi_type == WI_RID_FRAG_THRESH &&
   2444 		    (sc->sc_flags & WI_FLAGS_HAS_FRAGTHR) == 0)
   2445 			break;
   2446 		/* FALLTHROUGH */
   2447 	case WI_RID_RTS_THRESH:
   2448 	case WI_RID_CNFAUTHMODE:
   2449 	case WI_RID_MAX_DATALEN:
   2450 		if (sc->sc_enabled) {
   2451 			error = wi_write_rid(sc, wreq.wi_type, wreq.wi_val,
   2452 			    sizeof(u_int16_t));
   2453 			if (error)
   2454 				break;
   2455 		}
   2456 		switch (wreq.wi_type) {
   2457 		case WI_RID_FRAG_THRESH:
   2458 			sc->sc_frag_thresh = le16toh(wreq.wi_val[0]);
   2459 			break;
   2460 		case WI_RID_RTS_THRESH:
   2461 			sc->sc_rts_thresh = le16toh(wreq.wi_val[0]);
   2462 			break;
   2463 		case WI_RID_MICROWAVE_OVEN:
   2464 			sc->sc_microwave_oven = le16toh(wreq.wi_val[0]);
   2465 			break;
   2466 		case WI_RID_ROAMING_MODE:
   2467 			sc->sc_roaming_mode = le16toh(wreq.wi_val[0]);
   2468 			break;
   2469 		case WI_RID_SYSTEM_SCALE:
   2470 			sc->sc_system_scale = le16toh(wreq.wi_val[0]);
   2471 			break;
   2472 		case WI_RID_CNFAUTHMODE:
   2473 			sc->sc_cnfauthmode = le16toh(wreq.wi_val[0]);
   2474 			break;
   2475 		case WI_RID_MAX_DATALEN:
   2476 			sc->sc_max_datalen = le16toh(wreq.wi_val[0]);
   2477 			break;
   2478 		}
   2479 		break;
   2480 
   2481 	case WI_RID_TX_RATE:
   2482 		switch (le16toh(wreq.wi_val[0])) {
   2483 		case 3:
   2484 			ic->ic_fixed_rate = -1;
   2485 			break;
   2486 		default:
   2487 			for (i = 0; i < IEEE80211_RATE_SIZE; i++) {
   2488 				if ((rs->rs_rates[i] & IEEE80211_RATE_VAL)
   2489 				    / 2 == le16toh(wreq.wi_val[0]))
   2490 					break;
   2491 			}
   2492 			if (i == IEEE80211_RATE_SIZE)
   2493 				return EINVAL;
   2494 			ic->ic_fixed_rate = i;
   2495 		}
   2496 		if (sc->sc_enabled)
   2497 			error = wi_cfg_txrate(sc);
   2498 		break;
   2499 
   2500 	case WI_RID_SCAN_APS:
   2501 		if (sc->sc_enabled && ic->ic_opmode != IEEE80211_M_HOSTAP)
   2502 			error = wi_scan_ap(sc, 0x3fff, 0x000f);
   2503 		break;
   2504 
   2505 	case WI_RID_MGMT_XMIT:
   2506 		if (!sc->sc_enabled) {
   2507 			error = ENETDOWN;
   2508 			break;
   2509 		}
   2510 		if (ic->ic_mgtq.ifq_len > 5) {
   2511 			error = EAGAIN;
   2512 			break;
   2513 		}
   2514 		/* XXX wi_len looks in u_int8_t, not in u_int16_t */
   2515 		m = m_devget((char *)&wreq.wi_val, wreq.wi_len, 0, ifp, NULL);
   2516 		if (m == NULL) {
   2517 			error = ENOMEM;
   2518 			break;
   2519 		}
   2520 		IF_ENQUEUE(&ic->ic_mgtq, m);
   2521 		break;
   2522 
   2523 	default:
   2524 		if (sc->sc_enabled) {
   2525 			error = wi_write_rid(sc, wreq.wi_type, wreq.wi_val,
   2526 			    len);
   2527 			if (error)
   2528 				break;
   2529 		}
   2530 		error = ieee80211_cfgset(ic, cmd, data);
   2531 		break;
   2532 	}
   2533 	return error;
   2534 }
   2535 
   2536 /* Rate is 0 for hardware auto-select, otherwise rate is
   2537  * 2, 4, 11, or 22 (units of 500Kbps).
   2538  */
   2539 STATIC int
   2540 wi_write_txrate(struct wi_softc *sc, int rate)
   2541 {
   2542 	u_int16_t hwrate;
   2543 
   2544 	/* rate: 0, 2, 4, 11, 22 */
   2545 	switch (sc->sc_firmware_type) {
   2546 	case WI_LUCENT:
   2547 		switch (rate & IEEE80211_RATE_VAL) {
   2548 		case 2:
   2549 			hwrate = 1;
   2550 			break;
   2551 		case 4:
   2552 			hwrate = 2;
   2553 			break;
   2554 		default:
   2555 			hwrate = 3;	/* auto */
   2556 			break;
   2557 		case 11:
   2558 			hwrate = 4;
   2559 			break;
   2560 		case 22:
   2561 			hwrate = 5;
   2562 			break;
   2563 		}
   2564 		break;
   2565 	default:
   2566 		switch (rate & IEEE80211_RATE_VAL) {
   2567 		case 2:
   2568 			hwrate = 1;
   2569 			break;
   2570 		case 4:
   2571 			hwrate = 2;
   2572 			break;
   2573 		case 11:
   2574 			hwrate = 4;
   2575 			break;
   2576 		case 22:
   2577 			hwrate = 8;
   2578 			break;
   2579 		default:
   2580 			hwrate = 15;	/* auto */
   2581 			break;
   2582 		}
   2583 		break;
   2584 	}
   2585 
   2586 	if (sc->sc_tx_rate == hwrate)
   2587 		return 0;
   2588 
   2589 	if (sc->sc_if.if_flags & IFF_DEBUG)
   2590 		printf("%s: tx rate %d -> %d (%d)\n", __func__, sc->sc_tx_rate,
   2591 		    hwrate, rate);
   2592 
   2593 	sc->sc_tx_rate = hwrate;
   2594 
   2595 	return wi_write_val(sc, WI_RID_TX_RATE, sc->sc_tx_rate);
   2596 }
   2597 
   2598 STATIC int
   2599 wi_cfg_txrate(struct wi_softc *sc)
   2600 {
   2601 	struct ieee80211com *ic = &sc->sc_ic;
   2602 	struct ieee80211_rateset *rs;
   2603 	int rate;
   2604 
   2605 	rs = &ic->ic_sup_rates[IEEE80211_MODE_11B];
   2606 
   2607 	sc->sc_tx_rate = 0; /* force write to RID */
   2608 
   2609 	if (ic->ic_fixed_rate < 0)
   2610 		rate = 0;	/* auto */
   2611 	else
   2612 		rate = rs->rs_rates[ic->ic_fixed_rate];
   2613 
   2614 	return wi_write_txrate(sc, rate);
   2615 }
   2616 
   2617 STATIC int
   2618 wi_key_delete(struct ieee80211com *ic, const struct ieee80211_key *k)
   2619 {
   2620 	struct wi_softc *sc = ic->ic_ifp->if_softc;
   2621 	u_int keyix = k->wk_keyix;
   2622 
   2623 	DPRINTF(("%s: delete key %u\n", __func__, keyix));
   2624 
   2625 	if (keyix >= IEEE80211_WEP_NKID)
   2626 		return 0;
   2627 	if (k->wk_keylen != 0)
   2628 		sc->sc_flags &= ~WI_FLAGS_WEP_VALID;
   2629 
   2630 	return 1;
   2631 }
   2632 
   2633 static int
   2634 wi_key_set(struct ieee80211com *ic, const struct ieee80211_key *k,
   2635 	const u_int8_t mac[IEEE80211_ADDR_LEN])
   2636 {
   2637 	struct wi_softc *sc = ic->ic_ifp->if_softc;
   2638 
   2639 	DPRINTF(("%s: set key %u\n", __func__, k->wk_keyix));
   2640 
   2641 	if (k->wk_keyix >= IEEE80211_WEP_NKID)
   2642 		return 0;
   2643 
   2644 	sc->sc_flags &= ~WI_FLAGS_WEP_VALID;
   2645 
   2646 	return 1;
   2647 }
   2648 
   2649 STATIC void
   2650 wi_key_update_begin(struct ieee80211com *ic)
   2651 {
   2652 	DPRINTF(("%s:\n", __func__));
   2653 }
   2654 
   2655 STATIC void
   2656 wi_key_update_end(struct ieee80211com *ic)
   2657 {
   2658 	struct ifnet *ifp = ic->ic_ifp;
   2659 	struct wi_softc *sc = ifp->if_softc;
   2660 
   2661 	DPRINTF(("%s:\n", __func__));
   2662 
   2663 	if ((sc->sc_flags & WI_FLAGS_WEP_VALID) != 0)
   2664 		return;
   2665 	if ((ic->ic_caps & IEEE80211_C_WEP) != 0 && sc->sc_enabled &&
   2666 	    !sc->sc_invalid)
   2667 		(void)wi_write_wep(sc);
   2668 }
   2669 
   2670 STATIC int
   2671 wi_write_wep(struct wi_softc *sc)
   2672 {
   2673 	struct ifnet *ifp = &sc->sc_if;
   2674 	struct ieee80211com *ic = &sc->sc_ic;
   2675 	int error = 0;
   2676 	int i, keylen;
   2677 	u_int16_t val;
   2678 	struct wi_key wkey[IEEE80211_WEP_NKID];
   2679 
   2680 	if ((ifp->if_flags & IFF_RUNNING) != 0)
   2681 		wi_cmd(sc, WI_CMD_DISABLE | sc->sc_portnum, 0, 0, 0);
   2682 
   2683 	switch (sc->sc_firmware_type) {
   2684 	case WI_LUCENT:
   2685 		val = (ic->ic_flags & IEEE80211_F_PRIVACY) ? 1 : 0;
   2686 		error = wi_write_val(sc, WI_RID_ENCRYPTION, val);
   2687 		if (error)
   2688 			break;
   2689 		error = wi_write_val(sc, WI_RID_TX_CRYPT_KEY, ic->ic_def_txkey);
   2690 		if (error)
   2691 			break;
   2692 		memset(wkey, 0, sizeof(wkey));
   2693 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
   2694 			keylen = ic->ic_nw_keys[i].wk_keylen;
   2695 			wkey[i].wi_keylen = htole16(keylen);
   2696 			memcpy(wkey[i].wi_keydat, ic->ic_nw_keys[i].wk_key,
   2697 			    keylen);
   2698 		}
   2699 		error = wi_write_rid(sc, WI_RID_DEFLT_CRYPT_KEYS,
   2700 		    wkey, sizeof(wkey));
   2701 		break;
   2702 
   2703 	case WI_INTERSIL:
   2704 	case WI_SYMBOL:
   2705 		if (ic->ic_flags & IEEE80211_F_PRIVACY) {
   2706 			/*
   2707 			 * ONLY HWB3163 EVAL-CARD Firmware version
   2708 			 * less than 0.8 variant2
   2709 			 *
   2710 			 *   If promiscuous mode disable, Prism2 chip
   2711 			 *  does not work with WEP .
   2712 			 * It is under investigation for details.
   2713 			 * (ichiro (at) NetBSD.org)
   2714 			 */
   2715 			if (sc->sc_firmware_type == WI_INTERSIL &&
   2716 			    sc->sc_sta_firmware_ver < 802 ) {
   2717 				/* firm ver < 0.8 variant 2 */
   2718 				wi_write_val(sc, WI_RID_PROMISC, 1);
   2719 			}
   2720 			wi_write_val(sc, WI_RID_CNFAUTHMODE,
   2721 			    sc->sc_cnfauthmode);
   2722 			val = PRIVACY_INVOKED;
   2723 			if ((sc->sc_ic_flags & IEEE80211_F_DROPUNENC) != 0)
   2724 				val |= EXCLUDE_UNENCRYPTED;
   2725 #ifndef	IEEE80211_NO_HOSTAP
   2726 			/*
   2727 			 * Encryption firmware has a bug for HostAP mode.
   2728 			 */
   2729 			if (sc->sc_firmware_type == WI_INTERSIL &&
   2730 			    ic->ic_opmode == IEEE80211_M_HOSTAP)
   2731 				val |= HOST_ENCRYPT;
   2732 #endif /* !IEEE80211_NO_HOSTAP */
   2733 		} else {
   2734 			wi_write_val(sc, WI_RID_CNFAUTHMODE,
   2735 			    IEEE80211_AUTH_OPEN);
   2736 			val = HOST_ENCRYPT | HOST_DECRYPT;
   2737 		}
   2738 		error = wi_write_val(sc, WI_RID_P2_ENCRYPTION, val);
   2739 		if (error)
   2740 			break;
   2741 		error = wi_write_val(sc, WI_RID_P2_TX_CRYPT_KEY,
   2742 		    ic->ic_def_txkey);
   2743 		if (error)
   2744 			break;
   2745 		/*
   2746 		 * It seems that the firmware accept 104bit key only if
   2747 		 * all the keys have 104bit length.  We get the length of
   2748 		 * the transmit key and use it for all other keys.
   2749 		 * Perhaps we should use software WEP for such situation.
   2750 		 */
   2751 		if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
   2752 		    IEEE80211_KEY_UNDEFINED(ic->ic_nw_keys[ic->ic_def_txkey]))
   2753 			keylen = 13;	/* No keys => 104bit ok */
   2754 		else
   2755 			keylen = ic->ic_nw_keys[ic->ic_def_txkey].wk_keylen;
   2756 
   2757 		if (keylen > IEEE80211_WEP_KEYLEN)
   2758 			keylen = 13;	/* 104bit keys */
   2759 		else
   2760 			keylen = IEEE80211_WEP_KEYLEN;
   2761 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
   2762 			error = wi_write_rid(sc, WI_RID_P2_CRYPT_KEY0 + i,
   2763 			    ic->ic_nw_keys[i].wk_key, keylen);
   2764 			if (error)
   2765 				break;
   2766 		}
   2767 		break;
   2768 	}
   2769 	if ((ifp->if_flags & IFF_RUNNING) != 0)
   2770 		wi_cmd(sc, WI_CMD_ENABLE | sc->sc_portnum, 0, 0, 0);
   2771 	if (error == 0)
   2772 		sc->sc_flags |= WI_FLAGS_WEP_VALID;
   2773 	return error;
   2774 }
   2775 
   2776 /* Must be called at proper protection level! */
   2777 STATIC int
   2778 wi_cmd_start(struct wi_softc *sc, int cmd, int val0, int val1, int val2)
   2779 {
   2780 #ifdef WI_HISTOGRAM
   2781 	static int hist1[11];
   2782 	static int hist1count;
   2783 #endif
   2784 	int i;
   2785 
   2786 	/* wait for the busy bit to clear */
   2787 	for (i = 500; i > 0; i--) {	/* 5s */
   2788 		if ((CSR_READ_2(sc, WI_COMMAND) & WI_CMD_BUSY) == 0)
   2789 			break;
   2790 		if (sc->sc_invalid)
   2791 			return ENXIO;
   2792 		DELAY(1000);	/* 1 m sec */
   2793 	}
   2794 	if (i == 0) {
   2795 		aprint_error_dev(sc->sc_dev, "wi_cmd: busy bit won't clear.\n");
   2796 		return(ETIMEDOUT);
   2797   	}
   2798 #ifdef WI_HISTOGRAM
   2799 	if (i > 490)
   2800 		hist1[500 - i]++;
   2801 	else
   2802 		hist1[10]++;
   2803 	if (++hist1count == 1000) {
   2804 		hist1count = 0;
   2805 		printf("%s: hist1: %d %d %d %d %d %d %d %d %d %d %d\n",
   2806 		    device_xname(sc->sc_dev),
   2807 		    hist1[0], hist1[1], hist1[2], hist1[3], hist1[4],
   2808 		    hist1[5], hist1[6], hist1[7], hist1[8], hist1[9],
   2809 		    hist1[10]);
   2810 	}
   2811 #endif
   2812 	CSR_WRITE_2(sc, WI_PARAM0, val0);
   2813 	CSR_WRITE_2(sc, WI_PARAM1, val1);
   2814 	CSR_WRITE_2(sc, WI_PARAM2, val2);
   2815 	CSR_WRITE_2(sc, WI_COMMAND, cmd);
   2816 
   2817 	return 0;
   2818 }
   2819 
   2820 STATIC int
   2821 wi_cmd(struct wi_softc *sc, int cmd, int val0, int val1, int val2)
   2822 {
   2823 	int rc;
   2824 
   2825 #ifdef WI_DEBUG
   2826 	if (wi_debug) {
   2827 		printf("%s: [enter] %d txcmds outstanding\n", __func__,
   2828 		    sc->sc_txcmds);
   2829 	}
   2830 #endif
   2831 	if (sc->sc_txcmds > 0)
   2832 		wi_txcmd_wait(sc);
   2833 
   2834 	if ((rc = wi_cmd_start(sc, cmd, val0, val1, val2)) != 0)
   2835 		return rc;
   2836 
   2837 	if (cmd == WI_CMD_INI) {
   2838 		/* XXX: should sleep here. */
   2839 		if (sc->sc_invalid)
   2840 			return ENXIO;
   2841 		DELAY(100*1000);
   2842 	}
   2843 	rc = wi_cmd_wait(sc, cmd, val0);
   2844 
   2845 #ifdef WI_DEBUG
   2846 	if (wi_debug) {
   2847 		printf("%s: [     ] %d txcmds outstanding\n", __func__,
   2848 		    sc->sc_txcmds);
   2849 	}
   2850 #endif
   2851 	if (sc->sc_txcmds > 0)
   2852 		wi_cmd_intr(sc);
   2853 
   2854 #ifdef WI_DEBUG
   2855 	if (wi_debug) {
   2856 		printf("%s: [leave] %d txcmds outstanding\n", __func__,
   2857 		    sc->sc_txcmds);
   2858 	}
   2859 #endif
   2860 	return rc;
   2861 }
   2862 
   2863 STATIC int
   2864 wi_cmd_wait(struct wi_softc *sc, int cmd, int val0)
   2865 {
   2866 #ifdef WI_HISTOGRAM
   2867 	static int hist2[11];
   2868 	static int hist2count;
   2869 #endif
   2870 	int i, status;
   2871 #ifdef WI_DEBUG
   2872 	if (wi_debug > 1)
   2873 		printf("%s: cmd=%#x, arg=%#x\n", __func__, cmd, val0);
   2874 #endif /* WI_DEBUG */
   2875 
   2876 	/* wait for the cmd completed bit */
   2877 	for (i = 0; i < WI_TIMEOUT; i++) {
   2878 		if (CSR_READ_2(sc, WI_EVENT_STAT) & WI_EV_CMD)
   2879 			break;
   2880 		if (sc->sc_invalid)
   2881 			return ENXIO;
   2882 		DELAY(WI_DELAY);
   2883 	}
   2884 
   2885 #ifdef WI_HISTOGRAM
   2886 	if (i < 100)
   2887 		hist2[i/10]++;
   2888 	else
   2889 		hist2[10]++;
   2890 	if (++hist2count == 1000) {
   2891 		hist2count = 0;
   2892 		printf("%s: hist2: %d %d %d %d %d %d %d %d %d %d %d\n",
   2893 		    device_xname(sc->sc_dev),
   2894 		    hist2[0], hist2[1], hist2[2], hist2[3], hist2[4],
   2895 		    hist2[5], hist2[6], hist2[7], hist2[8], hist2[9],
   2896 		    hist2[10]);
   2897 	}
   2898 #endif
   2899 
   2900 	status = CSR_READ_2(sc, WI_STATUS);
   2901 
   2902 	if (i == WI_TIMEOUT) {
   2903 		aprint_error_dev(sc->sc_dev,
   2904 		    "command timed out, cmd=0x%x, arg=0x%x\n",
   2905 		    cmd, val0);
   2906 		return ETIMEDOUT;
   2907 	}
   2908 
   2909 	CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_CMD);
   2910 
   2911 	if (status & WI_STAT_CMD_RESULT) {
   2912 		aprint_error_dev(sc->sc_dev,
   2913 		    "command failed, cmd=0x%x, arg=0x%x\n",
   2914 		    cmd, val0);
   2915 		return EIO;
   2916 	}
   2917 	return 0;
   2918 }
   2919 
   2920 STATIC int
   2921 wi_seek_bap(struct wi_softc *sc, int id, int off)
   2922 {
   2923 #ifdef WI_HISTOGRAM
   2924 	static int hist4[11];
   2925 	static int hist4count;
   2926 #endif
   2927 	int i, status;
   2928 
   2929 	CSR_WRITE_2(sc, WI_SEL0, id);
   2930 	CSR_WRITE_2(sc, WI_OFF0, off);
   2931 
   2932 	for (i = 0; ; i++) {
   2933 		status = CSR_READ_2(sc, WI_OFF0);
   2934 		if ((status & WI_OFF_BUSY) == 0)
   2935 			break;
   2936 		if (i == WI_TIMEOUT) {
   2937 			aprint_error_dev(sc->sc_dev,
   2938 			    "timeout in wi_seek to %x/%x\n",
   2939 			    id, off);
   2940 			sc->sc_bap_off = WI_OFF_ERR;	/* invalidate */
   2941 			return ETIMEDOUT;
   2942 		}
   2943 		if (sc->sc_invalid)
   2944 			return ENXIO;
   2945 		DELAY(2);
   2946 	}
   2947 #ifdef WI_HISTOGRAM
   2948 	if (i < 100)
   2949 		hist4[i/10]++;
   2950 	else
   2951 		hist4[10]++;
   2952 	if (++hist4count == 2500) {
   2953 		hist4count = 0;
   2954 		printf("%s: hist4: %d %d %d %d %d %d %d %d %d %d %d\n",
   2955 		    device_xname(sc->sc_dev),
   2956 		    hist4[0], hist4[1], hist4[2], hist4[3], hist4[4],
   2957 		    hist4[5], hist4[6], hist4[7], hist4[8], hist4[9],
   2958 		    hist4[10]);
   2959 	}
   2960 #endif
   2961 	if (status & WI_OFF_ERR) {
   2962 		printf("%s: failed in wi_seek to %x/%x\n",
   2963 		    device_xname(sc->sc_dev), id, off);
   2964 		sc->sc_bap_off = WI_OFF_ERR;	/* invalidate */
   2965 		return EIO;
   2966 	}
   2967 	sc->sc_bap_id = id;
   2968 	sc->sc_bap_off = off;
   2969 	return 0;
   2970 }
   2971 
   2972 STATIC int
   2973 wi_read_bap(struct wi_softc *sc, int id, int off, void *buf, int buflen)
   2974 {
   2975 	int error, cnt;
   2976 
   2977 	if (buflen == 0)
   2978 		return 0;
   2979 	if (id != sc->sc_bap_id || off != sc->sc_bap_off) {
   2980 		if ((error = wi_seek_bap(sc, id, off)) != 0)
   2981 			return error;
   2982 	}
   2983 	cnt = (buflen + 1) / 2;
   2984 	CSR_READ_MULTI_STREAM_2(sc, WI_DATA0, (u_int16_t *)buf, cnt);
   2985 	sc->sc_bap_off += cnt * 2;
   2986 	return 0;
   2987 }
   2988 
   2989 STATIC int
   2990 wi_write_bap(struct wi_softc *sc, int id, int off, void *buf, int buflen)
   2991 {
   2992 	int error, cnt;
   2993 
   2994 	if (buflen == 0)
   2995 		return 0;
   2996 
   2997 #ifdef WI_HERMES_AUTOINC_WAR
   2998   again:
   2999 #endif
   3000 	if (id != sc->sc_bap_id || off != sc->sc_bap_off) {
   3001 		if ((error = wi_seek_bap(sc, id, off)) != 0)
   3002 			return error;
   3003 	}
   3004 	cnt = (buflen + 1) / 2;
   3005 	CSR_WRITE_MULTI_STREAM_2(sc, WI_DATA0, (u_int16_t *)buf, cnt);
   3006 	sc->sc_bap_off += cnt * 2;
   3007 
   3008 #ifdef WI_HERMES_AUTOINC_WAR
   3009 	/*
   3010 	 * According to the comments in the HCF Light code, there is a bug
   3011 	 * in the Hermes (or possibly in certain Hermes firmware revisions)
   3012 	 * where the chip's internal autoincrement counter gets thrown off
   3013 	 * during data writes:  the autoincrement is missed, causing one
   3014 	 * data word to be overwritten and subsequent words to be written to
   3015 	 * the wrong memory locations. The end result is that we could end
   3016 	 * up transmitting bogus frames without realizing it. The workaround
   3017 	 * for this is to write a couple of extra guard words after the end
   3018 	 * of the transfer, then attempt to read then back. If we fail to
   3019 	 * locate the guard words where we expect them, we preform the
   3020 	 * transfer over again.
   3021 	 */
   3022 	if ((sc->sc_flags & WI_FLAGS_BUG_AUTOINC) && (id & 0xf000) == 0) {
   3023 		CSR_WRITE_2(sc, WI_DATA0, 0x1234);
   3024 		CSR_WRITE_2(sc, WI_DATA0, 0x5678);
   3025 		wi_seek_bap(sc, id, sc->sc_bap_off);
   3026 		sc->sc_bap_off = WI_OFF_ERR;	/* invalidate */
   3027 		if (CSR_READ_2(sc, WI_DATA0) != 0x1234 ||
   3028 		    CSR_READ_2(sc, WI_DATA0) != 0x5678) {
   3029 			aprint_error_dev(sc->sc_dev,
   3030 			    "detect auto increment bug, try again\n");
   3031 			goto again;
   3032 		}
   3033 	}
   3034 #endif
   3035 	return 0;
   3036 }
   3037 
   3038 STATIC int
   3039 wi_mwrite_bap(struct wi_softc *sc, int id, int off, struct mbuf *m0, int totlen)
   3040 {
   3041 	int error, len;
   3042 	struct mbuf *m;
   3043 
   3044 	for (m = m0; m != NULL && totlen > 0; m = m->m_next) {
   3045 		if (m->m_len == 0)
   3046 			continue;
   3047 
   3048 		len = min(m->m_len, totlen);
   3049 
   3050 		if (((u_long)m->m_data) % 2 != 0 || len % 2 != 0) {
   3051 			m_copydata(m, 0, totlen, (void *)&sc->sc_txbuf);
   3052 			return wi_write_bap(sc, id, off, (void *)&sc->sc_txbuf,
   3053 			    totlen);
   3054 		}
   3055 
   3056 		if ((error = wi_write_bap(sc, id, off, m->m_data, len)) != 0)
   3057 			return error;
   3058 
   3059 		off += m->m_len;
   3060 		totlen -= len;
   3061 	}
   3062 	return 0;
   3063 }
   3064 
   3065 STATIC int
   3066 wi_alloc_fid(struct wi_softc *sc, int len, int *idp)
   3067 {
   3068 	int i;
   3069 
   3070 	if (wi_cmd(sc, WI_CMD_ALLOC_MEM, len, 0, 0)) {
   3071 		aprint_error_dev(sc->sc_dev, "failed to allocate %d bytes on NIC\n", len);
   3072 		return ENOMEM;
   3073 	}
   3074 
   3075 	for (i = 0; i < WI_TIMEOUT; i++) {
   3076 		if (CSR_READ_2(sc, WI_EVENT_STAT) & WI_EV_ALLOC)
   3077 			break;
   3078 		DELAY(1);
   3079 	}
   3080 	if (i == WI_TIMEOUT) {
   3081 		aprint_error_dev(sc->sc_dev, "timeout in alloc\n");
   3082 		return ETIMEDOUT;
   3083 	}
   3084 	*idp = CSR_READ_2(sc, WI_ALLOC_FID);
   3085 	CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_ALLOC);
   3086 	return 0;
   3087 }
   3088 
   3089 STATIC int
   3090 wi_read_rid(struct wi_softc *sc, int rid, void *buf, int *buflenp)
   3091 {
   3092 	int error, len;
   3093 	u_int16_t ltbuf[2];
   3094 
   3095 	/* Tell the NIC to enter record read mode. */
   3096 	error = wi_cmd(sc, WI_CMD_ACCESS | WI_ACCESS_READ, rid, 0, 0);
   3097 	if (error)
   3098 		return error;
   3099 
   3100 	error = wi_read_bap(sc, rid, 0, ltbuf, sizeof(ltbuf));
   3101 	if (error)
   3102 		return error;
   3103 
   3104 	if (le16toh(ltbuf[0]) == 0)
   3105 		return EOPNOTSUPP;
   3106 	if (le16toh(ltbuf[1]) != rid) {
   3107 		aprint_error_dev(sc->sc_dev,
   3108 		    "record read mismatch, rid=%x, got=%x\n",
   3109 		    rid, le16toh(ltbuf[1]));
   3110 		return EIO;
   3111 	}
   3112 	len = (le16toh(ltbuf[0]) - 1) * 2;	 /* already got rid */
   3113 	if (*buflenp < len) {
   3114 		aprint_error_dev(sc->sc_dev, "record buffer is too small, "
   3115 		    "rid=%x, size=%d, len=%d\n",
   3116 		    rid, *buflenp, len);
   3117 		return ENOSPC;
   3118 	}
   3119 	*buflenp = len;
   3120 	return wi_read_bap(sc, rid, sizeof(ltbuf), buf, len);
   3121 }
   3122 
   3123 STATIC int
   3124 wi_write_rid(struct wi_softc *sc, int rid, void *buf, int buflen)
   3125 {
   3126 	int error;
   3127 	u_int16_t ltbuf[2];
   3128 
   3129 	ltbuf[0] = htole16((buflen + 1) / 2 + 1);	 /* includes rid */
   3130 	ltbuf[1] = htole16(rid);
   3131 
   3132 	error = wi_write_bap(sc, rid, 0, ltbuf, sizeof(ltbuf));
   3133 	if (error)
   3134 		return error;
   3135 	error = wi_write_bap(sc, rid, sizeof(ltbuf), buf, buflen);
   3136 	if (error)
   3137 		return error;
   3138 
   3139 	return wi_cmd(sc, WI_CMD_ACCESS | WI_ACCESS_WRITE, rid, 0, 0);
   3140 }
   3141 
   3142 STATIC void
   3143 wi_rssadapt_updatestats_cb(void *arg, struct ieee80211_node *ni)
   3144 {
   3145 	struct wi_node *wn = (void*)ni;
   3146 	ieee80211_rssadapt_updatestats(&wn->wn_rssadapt);
   3147 }
   3148 
   3149 STATIC void
   3150 wi_rssadapt_updatestats(void *arg)
   3151 {
   3152 	struct wi_softc *sc = arg;
   3153 	struct ieee80211com *ic = &sc->sc_ic;
   3154 	int s;
   3155 
   3156 	s = splnet();
   3157 	ieee80211_iterate_nodes(&ic->ic_sta, wi_rssadapt_updatestats_cb, arg);
   3158 	if (ic->ic_opmode != IEEE80211_M_MONITOR &&
   3159 	    ic->ic_state == IEEE80211_S_RUN)
   3160 		callout_reset(&sc->sc_rssadapt_ch, hz / 10,
   3161 		    wi_rssadapt_updatestats, arg);
   3162 	splx(s);
   3163 }
   3164 
   3165 /*
   3166  * In HOSTAP mode, restore IEEE80211_F_DROPUNENC when operating
   3167  * with WEP enabled so that the AP drops unencoded frames at the
   3168  * 802.11 layer.
   3169  *
   3170  * In all other modes, clear IEEE80211_F_DROPUNENC when operating
   3171  * with WEP enabled so we don't drop unencoded frames at the 802.11
   3172  * layer.  This is necessary because we must strip the WEP bit from
   3173  * the 802.11 header before passing frames to ieee80211_input
   3174  * because the card has already stripped the WEP crypto header from
   3175  * the packet.
   3176  */
   3177 STATIC void
   3178 wi_mend_flags(struct wi_softc *sc, enum ieee80211_state nstate)
   3179 {
   3180 	struct ieee80211com *ic = &sc->sc_ic;
   3181 
   3182 	if (nstate == IEEE80211_S_RUN &&
   3183 	    (ic->ic_flags & IEEE80211_F_PRIVACY) != 0 &&
   3184 	    ic->ic_opmode != IEEE80211_M_HOSTAP)
   3185 		ic->ic_flags &= ~IEEE80211_F_DROPUNENC;
   3186 	else
   3187 		ic->ic_flags |= sc->sc_ic_flags;
   3188 
   3189 	DPRINTF(("%s: state %d, "
   3190 	    "ic->ic_flags & IEEE80211_F_DROPUNENC = %#" PRIx32 ", "
   3191 	    "sc->sc_ic_flags & IEEE80211_F_DROPUNENC = %#" PRIx32 "\n",
   3192 	    __func__, nstate,
   3193 	    ic->ic_flags & IEEE80211_F_DROPUNENC,
   3194 	    sc->sc_ic_flags & IEEE80211_F_DROPUNENC));
   3195 }
   3196 
   3197 STATIC int
   3198 wi_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
   3199 {
   3200 	struct ifnet *ifp = ic->ic_ifp;
   3201 	struct wi_softc *sc = ifp->if_softc;
   3202 	struct ieee80211_node *ni = ic->ic_bss;
   3203 	u_int16_t val;
   3204 	struct wi_ssid ssid;
   3205 	struct wi_macaddr bssid, old_bssid;
   3206 	enum ieee80211_state ostate __unused;
   3207 #ifdef WI_DEBUG
   3208 	static const char *stname[] =
   3209 	    { "INIT", "SCAN", "AUTH", "ASSOC", "RUN" };
   3210 #endif /* WI_DEBUG */
   3211 
   3212 	ostate = ic->ic_state;
   3213 	DPRINTF(("wi_newstate: %s -> %s\n", stname[ostate], stname[nstate]));
   3214 
   3215 	switch (nstate) {
   3216 	case IEEE80211_S_INIT:
   3217 		if (ic->ic_opmode != IEEE80211_M_MONITOR)
   3218 			callout_stop(&sc->sc_rssadapt_ch);
   3219 		ic->ic_flags &= ~IEEE80211_F_SIBSS;
   3220 		sc->sc_flags &= ~WI_FLAGS_OUTRANGE;
   3221 		break;
   3222 
   3223 	case IEEE80211_S_SCAN:
   3224 	case IEEE80211_S_AUTH:
   3225 	case IEEE80211_S_ASSOC:
   3226 		ic->ic_state = nstate; /* NB: skip normal ieee80211 handling */
   3227 		wi_mend_flags(sc, nstate);
   3228 		return 0;
   3229 
   3230 	case IEEE80211_S_RUN:
   3231 		sc->sc_flags &= ~WI_FLAGS_OUTRANGE;
   3232 		IEEE80211_ADDR_COPY(old_bssid.wi_mac_addr, ni->ni_bssid);
   3233 		wi_read_xrid(sc, WI_RID_CURRENT_BSSID, &bssid,
   3234 		    IEEE80211_ADDR_LEN);
   3235 		IEEE80211_ADDR_COPY(ni->ni_bssid, &bssid);
   3236 		IEEE80211_ADDR_COPY(ni->ni_macaddr, &bssid);
   3237 		wi_read_xrid(sc, WI_RID_CURRENT_CHAN, &val, sizeof(val));
   3238 		if (!isset(ic->ic_chan_avail, le16toh(val)))
   3239 			panic("%s: invalid channel %d\n",
   3240 			    device_xname(sc->sc_dev), le16toh(val));
   3241 		ni->ni_chan = &ic->ic_channels[le16toh(val)];
   3242 
   3243 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
   3244 #ifndef	IEEE80211_NO_HOSTAP
   3245 			ni->ni_esslen = ic->ic_des_esslen;
   3246 			memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
   3247 			ni->ni_rates = ic->ic_sup_rates[
   3248 			    ieee80211_chan2mode(ic, ni->ni_chan)];
   3249 			ni->ni_intval = ic->ic_lintval;
   3250 			ni->ni_capinfo = IEEE80211_CAPINFO_ESS;
   3251 			if (ic->ic_flags & IEEE80211_F_PRIVACY)
   3252 				ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
   3253 #endif /* !IEEE80211_NO_HOSTAP */
   3254 		} else {
   3255 			wi_read_xrid(sc, WI_RID_CURRENT_SSID, &ssid,
   3256 			    sizeof(ssid));
   3257 			ni->ni_esslen = le16toh(ssid.wi_len);
   3258 			if (ni->ni_esslen > IEEE80211_NWID_LEN)
   3259 				ni->ni_esslen = IEEE80211_NWID_LEN;	/*XXX*/
   3260 			memcpy(ni->ni_essid, ssid.wi_ssid, ni->ni_esslen);
   3261 			ni->ni_rates = ic->ic_sup_rates[
   3262 			    ieee80211_chan2mode(ic, ni->ni_chan)]; /*XXX*/
   3263 		}
   3264 		if (ic->ic_opmode != IEEE80211_M_MONITOR)
   3265 			callout_reset(&sc->sc_rssadapt_ch, hz / 10,
   3266 			    wi_rssadapt_updatestats, sc);
   3267 		/* Trigger routing socket messages. XXX Copied from
   3268 		 * ieee80211_newstate.
   3269 		 */
   3270 		if (ic->ic_opmode == IEEE80211_M_STA)
   3271 			ieee80211_notify_node_join(ic, ic->ic_bss,
   3272 				arg == IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
   3273 		break;
   3274 	}
   3275 	wi_mend_flags(sc, nstate);
   3276 	return (*sc->sc_newstate)(ic, nstate, arg);
   3277 }
   3278 
   3279 STATIC void
   3280 wi_set_tim(struct ieee80211_node *ni, int set)
   3281 {
   3282 	struct ieee80211com *ic = ni->ni_ic;
   3283 	struct wi_softc *sc = ic->ic_ifp->if_softc;
   3284 
   3285 	(*sc->sc_set_tim)(ni, set);
   3286 
   3287 	if ((ic->ic_flags & IEEE80211_F_TIMUPDATE) == 0)
   3288 		return;
   3289 
   3290 	ic->ic_flags &= ~IEEE80211_F_TIMUPDATE;
   3291 
   3292 	(void)wi_write_val(sc, WI_RID_SET_TIM,
   3293 	    IEEE80211_AID(ni->ni_associd) | (set ? 0x8000 : 0));
   3294 }
   3295 
   3296 STATIC int
   3297 wi_scan_ap(struct wi_softc *sc, u_int16_t chanmask, u_int16_t txrate)
   3298 {
   3299 	int error = 0;
   3300 	u_int16_t val[2];
   3301 
   3302 	if (!sc->sc_enabled)
   3303 		return ENXIO;
   3304 	switch (sc->sc_firmware_type) {
   3305 	case WI_LUCENT:
   3306 		(void)wi_cmd(sc, WI_CMD_INQUIRE, WI_INFO_SCAN_RESULTS, 0, 0);
   3307 		break;
   3308 	case WI_INTERSIL:
   3309 		val[0] = htole16(chanmask);	/* channel */
   3310 		val[1] = htole16(txrate);	/* tx rate */
   3311 		error = wi_write_rid(sc, WI_RID_SCAN_REQ, val, sizeof(val));
   3312 		break;
   3313 	case WI_SYMBOL:
   3314 		/*
   3315 		 * XXX only supported on 3.x ?
   3316 		 */
   3317 		val[0] = htole16(BSCAN_BCAST | BSCAN_ONETIME);
   3318 		error = wi_write_rid(sc, WI_RID_BCAST_SCAN_REQ,
   3319 		    val, sizeof(val[0]));
   3320 		break;
   3321 	}
   3322 	if (error == 0) {
   3323 		sc->sc_scan_timer = WI_SCAN_WAIT;
   3324 		sc->sc_if.if_timer = 1;
   3325 		DPRINTF(("wi_scan_ap: start scanning, "
   3326 			"chanmask 0x%x txrate 0x%x\n", chanmask, txrate));
   3327 	}
   3328 	return error;
   3329 }
   3330 
   3331 STATIC void
   3332 wi_scan_result(struct wi_softc *sc, int fid, int cnt)
   3333 {
   3334 #define	N(a)	(sizeof (a) / sizeof (a[0]))
   3335 	int i, naps, off, szbuf;
   3336 	struct wi_scan_header ws_hdr;	/* Prism2 header */
   3337 	struct wi_scan_data_p2 ws_dat;	/* Prism2 scantable*/
   3338 	struct wi_apinfo *ap;
   3339 
   3340 	off = sizeof(u_int16_t) * 2;
   3341 	memset(&ws_hdr, 0, sizeof(ws_hdr));
   3342 	switch (sc->sc_firmware_type) {
   3343 	case WI_INTERSIL:
   3344 		wi_read_bap(sc, fid, off, &ws_hdr, sizeof(ws_hdr));
   3345 		off += sizeof(ws_hdr);
   3346 		szbuf = sizeof(struct wi_scan_data_p2);
   3347 		break;
   3348 	case WI_SYMBOL:
   3349 		szbuf = sizeof(struct wi_scan_data_p2) + 6;
   3350 		break;
   3351 	case WI_LUCENT:
   3352 		szbuf = sizeof(struct wi_scan_data);
   3353 		break;
   3354 	default:
   3355 		aprint_error_dev(sc->sc_dev,
   3356 		    "wi_scan_result: unknown firmware type %u\n",
   3357 		    sc->sc_firmware_type);
   3358 		naps = 0;
   3359 		goto done;
   3360 	}
   3361 	naps = (cnt * 2 + 2 - off) / szbuf;
   3362 	if (naps > N(sc->sc_aps))
   3363 		naps = N(sc->sc_aps);
   3364 	sc->sc_naps = naps;
   3365 	/* Read Data */
   3366 	ap = sc->sc_aps;
   3367 	memset(&ws_dat, 0, sizeof(ws_dat));
   3368 	for (i = 0; i < naps; i++, ap++) {
   3369 		wi_read_bap(sc, fid, off, &ws_dat,
   3370 		    (sizeof(ws_dat) < szbuf ? sizeof(ws_dat) : szbuf));
   3371 		DPRINTF2(("wi_scan_result: #%d: off %d bssid %s\n", i, off,
   3372 		    ether_sprintf(ws_dat.wi_bssid)));
   3373 		off += szbuf;
   3374 		ap->scanreason = le16toh(ws_hdr.wi_reason);
   3375 		memcpy(ap->bssid, ws_dat.wi_bssid, sizeof(ap->bssid));
   3376 		ap->channel = le16toh(ws_dat.wi_chid);
   3377 		ap->signal  = le16toh(ws_dat.wi_signal);
   3378 		ap->noise   = le16toh(ws_dat.wi_noise);
   3379 		ap->quality = ap->signal - ap->noise;
   3380 		ap->capinfo = le16toh(ws_dat.wi_capinfo);
   3381 		ap->interval = le16toh(ws_dat.wi_interval);
   3382 		ap->rate    = le16toh(ws_dat.wi_rate);
   3383 		ap->namelen = le16toh(ws_dat.wi_namelen);
   3384 		if (ap->namelen > sizeof(ap->name))
   3385 			ap->namelen = sizeof(ap->name);
   3386 		memcpy(ap->name, ws_dat.wi_name, ap->namelen);
   3387 	}
   3388 done:
   3389 	/* Done scanning */
   3390 	sc->sc_scan_timer = 0;
   3391 	DPRINTF(("wi_scan_result: scan complete: ap %d\n", naps));
   3392 #undef N
   3393 }
   3394 
   3395 STATIC void
   3396 wi_dump_pkt(struct wi_frame *wh, struct ieee80211_node *ni, int rssi)
   3397 {
   3398 	ieee80211_dump_pkt((u_int8_t *) &wh->wi_whdr, sizeof(wh->wi_whdr),
   3399 	    ni	? ni->ni_rates.rs_rates[ni->ni_txrate] & IEEE80211_RATE_VAL
   3400 		: -1,
   3401 	    rssi);
   3402 	printf(" status 0x%x rx_tstamp1 %#x rx_tstamp0 %#x rx_silence %u\n",
   3403 		le16toh(wh->wi_status), le16toh(wh->wi_rx_tstamp1),
   3404 		le16toh(wh->wi_rx_tstamp0), wh->wi_rx_silence);
   3405 	printf(" rx_signal %u rx_rate %u rx_flow %u\n",
   3406 		wh->wi_rx_signal, wh->wi_rx_rate, wh->wi_rx_flow);
   3407 	printf(" tx_rtry %u tx_rate %u tx_ctl 0x%x dat_len %u\n",
   3408 		wh->wi_tx_rtry, wh->wi_tx_rate,
   3409 		le16toh(wh->wi_tx_ctl), le16toh(wh->wi_dat_len));
   3410 	printf(" ehdr dst %s src %s type 0x%x\n",
   3411 		ether_sprintf(wh->wi_ehdr.ether_dhost),
   3412 		ether_sprintf(wh->wi_ehdr.ether_shost),
   3413 		wh->wi_ehdr.ether_type);
   3414 }
   3415