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