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