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