Home | History | Annotate | Line # | Download | only in ic
wi.c revision 1.251
      1 /*	$NetBSD: wi.c,v 1.251 2019/05/23 10:57:28 msaitoh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2004 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Charles M. Hannum.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1997, 1998, 1999
     34  *	Bill Paul <wpaul (at) ctr.columbia.edu>.  All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. All advertising materials mentioning features or use of this software
     45  *    must display the following acknowledgement:
     46  *	This product includes software developed by Bill Paul.
     47  * 4. Neither the name of the author nor the names of any co-contributors
     48  *    may be used to endorse or promote products derived from this software
     49  *    without specific prior written permission.
     50  *
     51  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
     52  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     53  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     54  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
     55  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     56  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     57  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     58  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     59  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     60  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
     61  * THE POSSIBILITY OF SUCH DAMAGE.
     62  */
     63 
     64 /*
     65  * Lucent WaveLAN/IEEE 802.11 PCMCIA driver for NetBSD.
     66  *
     67  * Original FreeBSD driver written by Bill Paul <wpaul (at) ctr.columbia.edu>
     68  * Electrical Engineering Department
     69  * Columbia University, New York City
     70  */
     71 
     72 /*
     73  * The WaveLAN/IEEE adapter is the second generation of the WaveLAN
     74  * from Lucent. Unlike the older cards, the new ones are programmed
     75  * entirely via a firmware-driven controller called the Hermes.
     76  * Unfortunately, Lucent will not release the Hermes programming manual
     77  * without an NDA (if at all). What they do release is an API library
     78  * called the HCF (Hardware Control Functions) which is supposed to
     79  * do the device-specific operations of a device driver for you. The
     80  * publically available version of the HCF library (the 'HCF Light') is
     81  * a) extremely gross, b) lacks certain features, particularly support
     82  * for 802.11 frames, and c) is contaminated by the GNU Public License.
     83  *
     84  * This driver does not use the HCF or HCF Light at all. Instead, it
     85  * programs the Hermes controller directly, using information gleaned
     86  * from the HCF Light code and corresponding documentation.
     87  *
     88  * This driver supports both the PCMCIA and ISA versions of the
     89  * WaveLAN/IEEE cards. Note however that the ISA card isn't really
     90  * anything of the sort: it's actually a PCMCIA bridge adapter
     91  * that fits into an ISA slot, into which a PCMCIA WaveLAN card is
     92  * inserted. Consequently, you need to use the pccard support for
     93  * both the ISA and PCMCIA adapters.
     94  */
     95 
     96 /*
     97  * FreeBSD driver ported to NetBSD by Bill Sommerfeld in the back of the
     98  * Oslo IETF plenary meeting.
     99  */
    100 
    101 #include <sys/cdefs.h>
    102 __KERNEL_RCSID(0, "$NetBSD: wi.c,v 1.251 2019/05/23 10:57:28 msaitoh Exp $");
    103 
    104 #define WI_HERMES_AUTOINC_WAR	/* Work around data write autoinc bug. */
    105 #define WI_HERMES_STATS_WAR	/* Work around stats counter bug. */
    106 #undef WI_HISTOGRAM
    107 #undef WI_RING_DEBUG
    108 #define STATIC static
    109 
    110 
    111 #include <sys/param.h>
    112 #include <sys/sysctl.h>
    113 #include <sys/systm.h>
    114 #include <sys/callout.h>
    115 #include <sys/device.h>
    116 #include <sys/socket.h>
    117 #include <sys/mbuf.h>
    118 #include <sys/ioctl.h>
    119 #include <sys/kernel.h>		/* for hz */
    120 #include <sys/proc.h>
    121 #include <sys/kauth.h>
    122 
    123 #include <net/if.h>
    124 #include <net/if_dl.h>
    125 #include <net/if_llc.h>
    126 #include <net/if_media.h>
    127 #include <net/if_ether.h>
    128 #include <net/route.h>
    129 #include <net/bpf.h>
    130 
    131 #include <net80211/ieee80211_netbsd.h>
    132 #include <net80211/ieee80211_var.h>
    133 #include <net80211/ieee80211_ioctl.h>
    134 #include <net80211/ieee80211_radiotap.h>
    135 #include <net80211/ieee80211_rssadapt.h>
    136 
    137 #include <sys/bus.h>
    138 #include <sys/intr.h>
    139 
    140 #include <dev/ic/wi_ieee.h>
    141 #include <dev/ic/wireg.h>
    142 #include <dev/ic/wivar.h>
    143 
    144 STATIC int  wi_init(struct ifnet *);
    145 STATIC void wi_stop(struct ifnet *, int);
    146 STATIC void wi_start(struct ifnet *);
    147 STATIC int  wi_reset(struct wi_softc *);
    148 STATIC void wi_watchdog(struct ifnet *);
    149 STATIC int  wi_ioctl(struct ifnet *, u_long, void *);
    150 STATIC int  wi_media_change(struct ifnet *);
    151 STATIC void wi_media_status(struct ifnet *, struct ifmediareq *);
    152 STATIC void wi_softintr(void *);
    153 
    154 static void wi_ioctl_init(struct wi_softc *);
    155 static int wi_ioctl_enter(struct wi_softc *);
    156 static void wi_ioctl_exit(struct wi_softc *);
    157 static void wi_ioctl_drain(struct wi_softc *);
    158 
    159 STATIC struct ieee80211_node *wi_node_alloc(struct ieee80211_node_table *);
    160 STATIC void wi_node_free(struct ieee80211_node *);
    161 
    162 STATIC void wi_raise_rate(struct ieee80211com *, struct ieee80211_rssdesc *);
    163 STATIC void wi_lower_rate(struct ieee80211com *, struct ieee80211_rssdesc *);
    164 STATIC int wi_choose_rate(struct ieee80211com *, struct ieee80211_node *,
    165     struct ieee80211_frame *, u_int);
    166 STATIC void wi_rssadapt_updatestats_cb(void *, struct ieee80211_node *);
    167 STATIC void wi_rssadapt_updatestats(void *);
    168 STATIC void wi_rssdescs_init(struct wi_rssdesc (*)[], wi_rssdescq_t *);
    169 STATIC void wi_rssdescs_reset(struct ieee80211com *, struct wi_rssdesc (*)[],
    170     wi_rssdescq_t *, 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 			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 				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 				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 				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 			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 			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 	struct ifreq *ifr = (struct ifreq *)data;
   1423 	int s, error = 0;
   1424 
   1425 	if (!device_is_active(sc->sc_dev))
   1426 		return ENXIO;
   1427 
   1428 	s = splnet();
   1429 
   1430 	if ((error = wi_ioctl_enter(sc)) != 0) {
   1431 		splx(s);
   1432 		return error;
   1433 	}
   1434 
   1435 	switch (cmd) {
   1436 	case SIOCSIFFLAGS:
   1437 		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
   1438 			break;
   1439 		/*
   1440 		 * Can't do promisc and hostap at the same time.  If all that's
   1441 		 * changing is the promisc flag, try to short-circuit a call to
   1442 		 * wi_init() by just setting PROMISC in the hardware.
   1443 		 */
   1444 		if (ifp->if_flags & IFF_UP) {
   1445 			if (sc->sc_enabled) {
   1446 				if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
   1447 				    (ifp->if_flags & IFF_PROMISC) != 0)
   1448 					wi_write_val(sc, WI_RID_PROMISC, 1);
   1449 				else
   1450 					wi_write_val(sc, WI_RID_PROMISC, 0);
   1451 			} else
   1452 				error = wi_init(ifp);
   1453 		} else if (sc->sc_enabled)
   1454 			wi_stop(ifp, 1);
   1455 		break;
   1456 	case SIOCSIFMEDIA:
   1457 	case SIOCGIFMEDIA:
   1458 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
   1459 		break;
   1460 	case SIOCADDMULTI:
   1461 	case SIOCDELMULTI:
   1462 		if ((error = ether_ioctl(ifp, cmd, data)) == ENETRESET) {
   1463 			if (ifp->if_flags & IFF_RUNNING) {
   1464 				/* do not rescan */
   1465 				error = wi_write_multi(sc);
   1466 			} else
   1467 				error = 0;
   1468 		}
   1469 		break;
   1470 	case SIOCGIFGENERIC:
   1471 		error = wi_get_cfg(ifp, cmd, data);
   1472 		break;
   1473 	case SIOCSIFGENERIC:
   1474 		error = kauth_authorize_network(curlwp->l_cred,
   1475 		    KAUTH_NETWORK_INTERFACE,
   1476 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, KAUTH_ARG(cmd),
   1477 		    NULL);
   1478 		if (error)
   1479 			break;
   1480 		error = wi_set_cfg(ifp, cmd, data);
   1481 		if (error == ENETRESET) {
   1482 			if (ifp->if_flags & IFF_RUNNING)
   1483 				error = wi_init(ifp);
   1484 			else
   1485 				error = 0;
   1486 		}
   1487 		break;
   1488 	case SIOCS80211BSSID:
   1489 		if (sc->sc_firmware_type == WI_LUCENT) {
   1490 			error = ENODEV;
   1491 			break;
   1492 		}
   1493 		/* fall through */
   1494 	default:
   1495 		ic->ic_flags |= sc->sc_ic_flags;
   1496 		error = ieee80211_ioctl(&sc->sc_ic, cmd, data);
   1497 		sc->sc_ic_flags = ic->ic_flags & IEEE80211_F_DROPUNENC;
   1498 		if (error == ENETRESET) {
   1499 			if (sc->sc_enabled)
   1500 				error = wi_init(ifp);
   1501 			else
   1502 				error = 0;
   1503 		}
   1504 		break;
   1505 	}
   1506 	wi_mend_flags(sc, ic->ic_state);
   1507 	wi_ioctl_exit(sc);
   1508 	splx(s);
   1509 	return error;
   1510 }
   1511 
   1512 STATIC int
   1513 wi_media_change(struct ifnet *ifp)
   1514 {
   1515 	struct wi_softc *sc = ifp->if_softc;
   1516 	struct ieee80211com *ic = &sc->sc_ic;
   1517 	int error;
   1518 
   1519 	error = ieee80211_media_change(ifp);
   1520 	if (error == ENETRESET) {
   1521 		if (sc->sc_enabled)
   1522 			error = wi_init(ifp);
   1523 		else
   1524 			error = 0;
   1525 	}
   1526 	ifp->if_baudrate = ifmedia_baudrate(ic->ic_media.ifm_cur->ifm_media);
   1527 
   1528 	return error;
   1529 }
   1530 
   1531 STATIC void
   1532 wi_media_status(struct ifnet *ifp, struct ifmediareq *imr)
   1533 {
   1534 	struct wi_softc *sc = ifp->if_softc;
   1535 	struct ieee80211com *ic = &sc->sc_ic;
   1536 	uint16_t val;
   1537 	int rate;
   1538 
   1539 	if (sc->sc_enabled == 0) {
   1540 		imr->ifm_active = IFM_IEEE80211 | IFM_NONE;
   1541 		imr->ifm_status = 0;
   1542 		return;
   1543 	}
   1544 
   1545 	imr->ifm_status = IFM_AVALID;
   1546 	imr->ifm_active = IFM_IEEE80211;
   1547 	if (ic->ic_state == IEEE80211_S_RUN &&
   1548 	    (sc->sc_flags & WI_FLAGS_OUTRANGE) == 0)
   1549 		imr->ifm_status |= IFM_ACTIVE;
   1550 	if (wi_read_xrid(sc, WI_RID_CUR_TX_RATE, &val, sizeof(val)) == 0) {
   1551 		/* convert to 802.11 rate */
   1552 		val = le16toh(val);
   1553 		rate = val * 2;
   1554 		if (sc->sc_firmware_type == WI_LUCENT) {
   1555 			if (rate == 10)
   1556 				rate = 11;	/* 5.5Mbps */
   1557 		} else {
   1558 			if (rate == 4*2)
   1559 				rate = 11;	/* 5.5Mbps */
   1560 			else if (rate == 8*2)
   1561 				rate = 22;	/* 11Mbps */
   1562 		}
   1563 	} else
   1564 		rate = 0;
   1565 	imr->ifm_active |= ieee80211_rate2media(ic, rate, IEEE80211_MODE_11B);
   1566 	switch (ic->ic_opmode) {
   1567 	case IEEE80211_M_STA:
   1568 		break;
   1569 	case IEEE80211_M_IBSS:
   1570 		imr->ifm_active |= IFM_IEEE80211_ADHOC;
   1571 		break;
   1572 	case IEEE80211_M_AHDEMO:
   1573 		imr->ifm_active |= IFM_IEEE80211_ADHOC | IFM_FLAG0;
   1574 		break;
   1575 	case IEEE80211_M_HOSTAP:
   1576 		imr->ifm_active |= IFM_IEEE80211_HOSTAP;
   1577 		break;
   1578 	case IEEE80211_M_MONITOR:
   1579 		imr->ifm_active |= IFM_IEEE80211_MONITOR;
   1580 		break;
   1581 	}
   1582 }
   1583 
   1584 STATIC struct ieee80211_node *
   1585 wi_node_alloc(struct ieee80211_node_table *nt)
   1586 {
   1587 	struct wi_node *wn =
   1588 	    malloc(sizeof(struct wi_node), M_DEVBUF, M_NOWAIT | M_ZERO);
   1589 	return wn ? &wn->wn_node : NULL;
   1590 }
   1591 
   1592 STATIC void
   1593 wi_node_free(struct ieee80211_node *ni)
   1594 {
   1595 	struct wi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
   1596 	int i;
   1597 
   1598 	for (i = 0; i < WI_NTXRSS; i++) {
   1599 		if (sc->sc_rssd[i].rd_desc.id_node == ni)
   1600 			sc->sc_rssd[i].rd_desc.id_node = NULL;
   1601 	}
   1602 	free(ni, M_DEVBUF);
   1603 }
   1604 
   1605 STATIC void
   1606 wi_sync_bssid(struct wi_softc *sc, uint8_t new_bssid[IEEE80211_ADDR_LEN])
   1607 {
   1608 	struct ieee80211com *ic = &sc->sc_ic;
   1609 	struct ieee80211_node *ni = ic->ic_bss;
   1610 	struct ifnet *ifp = &sc->sc_if;
   1611 	int s;
   1612 
   1613 	if (IEEE80211_ADDR_EQ(new_bssid, ni->ni_bssid))
   1614 		return;
   1615 
   1616 	DPRINTF(("wi_sync_bssid: bssid %s -> ", ether_sprintf(ni->ni_bssid)));
   1617 	DPRINTF(("%s ?\n", ether_sprintf(new_bssid)));
   1618 
   1619 	/* In promiscuous mode, the BSSID field is not a reliable
   1620 	 * indicator of the firmware's BSSID. Damp spurious
   1621 	 * change-of-BSSID indications.
   1622 	 */
   1623 	if ((ifp->if_flags & IFF_PROMISC) != 0 &&
   1624 	    !ppsratecheck(&sc->sc_last_syn, &sc->sc_false_syns,
   1625 	                 WI_MAX_FALSE_SYNS))
   1626 		return;
   1627 
   1628 	sc->sc_false_syns = MAX(0, sc->sc_false_syns - 1);
   1629 	/*
   1630 	 * XXX hack; we should create a new node with the new bssid
   1631 	 * and replace the existing ic_bss with it but since we don't
   1632 	 * process management frames to collect state we cheat by
   1633 	 * reusing the existing node as we know wi_newstate will be
   1634 	 * called and it will overwrite the node state.
   1635 	 */
   1636 	s = splnet();
   1637         ieee80211_sta_join(ic, ieee80211_ref_node(ni));
   1638 	splx(s);
   1639 }
   1640 
   1641 static inline void
   1642 wi_rssadapt_input(struct ieee80211com *ic, struct ieee80211_node *ni,
   1643     struct ieee80211_frame *wh, int rssi)
   1644 {
   1645 	struct wi_node *wn;
   1646 
   1647 	if (ni == NULL) {
   1648 		printf("%s: null node", __func__);
   1649 		return;
   1650 	}
   1651 
   1652 	wn = (void*)ni;
   1653 	ieee80211_rssadapt_input(ic, ni, &wn->wn_rssadapt, rssi);
   1654 }
   1655 
   1656 STATIC void
   1657 wi_rx_intr(struct wi_softc *sc)
   1658 {
   1659 	struct ieee80211com *ic = &sc->sc_ic;
   1660 	struct ifnet *ifp = &sc->sc_if;
   1661 	struct ieee80211_node *ni;
   1662 	struct wi_frame frmhdr;
   1663 	struct mbuf *m;
   1664 	struct ieee80211_frame *wh;
   1665 	int fid, len, off, rssi;
   1666 	uint8_t dir;
   1667 	uint16_t status;
   1668 	uint32_t rstamp;
   1669 	int s;
   1670 
   1671 	fid = CSR_READ_2(sc, WI_RX_FID);
   1672 
   1673 	/* First read in the frame header */
   1674 	if (wi_read_bap(sc, fid, 0, &frmhdr, sizeof(frmhdr))) {
   1675 		aprint_error_dev(sc->sc_dev, "%s read fid %x failed\n",
   1676 		    __func__, fid);
   1677 		ifp->if_ierrors++;
   1678 		return;
   1679 	}
   1680 
   1681 	if (IFF_DUMPPKTS(ifp))
   1682 		wi_dump_pkt(&frmhdr, NULL, frmhdr.wi_rx_signal);
   1683 
   1684 	/*
   1685 	 * Drop undecryptable or packets with receive errors here
   1686 	 */
   1687 	status = le16toh(frmhdr.wi_status);
   1688 	if ((status & WI_STAT_ERRSTAT) != 0 &&
   1689 	    ic->ic_opmode != IEEE80211_M_MONITOR) {
   1690 		ifp->if_ierrors++;
   1691 		DPRINTF(("wi_rx_intr: fid %x error status %x\n", fid, status));
   1692 		return;
   1693 	}
   1694 	rssi = frmhdr.wi_rx_signal;
   1695 	rstamp = (le16toh(frmhdr.wi_rx_tstamp0) << 16) |
   1696 	    le16toh(frmhdr.wi_rx_tstamp1);
   1697 
   1698 	len = le16toh(frmhdr.wi_dat_len);
   1699 	off = ALIGN(sizeof(struct ieee80211_frame));
   1700 
   1701 	/* Sometimes the PRISM2.x returns bogusly large frames. Except
   1702 	 * in monitor mode, just throw them away.
   1703 	 */
   1704 	if (off + len > MCLBYTES) {
   1705 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
   1706 			ifp->if_ierrors++;
   1707 			DPRINTF(("wi_rx_intr: oversized packet\n"));
   1708 			return;
   1709 		} else
   1710 			len = 0;
   1711 	}
   1712 
   1713 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   1714 	if (m == NULL) {
   1715 		ifp->if_ierrors++;
   1716 		DPRINTF(("wi_rx_intr: MGET failed\n"));
   1717 		return;
   1718 	}
   1719 	if (off + len > MHLEN) {
   1720 		MCLGET(m, M_DONTWAIT);
   1721 		if ((m->m_flags & M_EXT) == 0) {
   1722 			m_freem(m);
   1723 			ifp->if_ierrors++;
   1724 			DPRINTF(("wi_rx_intr: MCLGET failed\n"));
   1725 			return;
   1726 		}
   1727 	}
   1728 
   1729 	m->m_data += off - sizeof(struct ieee80211_frame);
   1730 	memcpy(m->m_data, &frmhdr.wi_whdr, sizeof(struct ieee80211_frame));
   1731 	wi_read_bap(sc, fid, sizeof(frmhdr),
   1732 	    m->m_data + sizeof(struct ieee80211_frame), len);
   1733 	m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame) + len;
   1734 	m_set_rcvif(m, ifp);
   1735 
   1736 	wh = mtod(m, struct ieee80211_frame *);
   1737 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
   1738 		/*
   1739 		 * WEP is decrypted by hardware. Clear WEP bit
   1740 		 * header for ieee80211_input().
   1741 		 */
   1742 		wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
   1743 	}
   1744 
   1745 	s = splnet();
   1746 
   1747 	if (sc->sc_drvbpf) {
   1748 		struct wi_rx_radiotap_header *tap = &sc->sc_rxtap;
   1749 
   1750 		tap->wr_rate = frmhdr.wi_rx_rate / 5;
   1751 		tap->wr_antsignal = frmhdr.wi_rx_signal;
   1752 		tap->wr_antnoise = frmhdr.wi_rx_silence;
   1753 		tap->wr_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
   1754 		tap->wr_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
   1755 		if (frmhdr.wi_status & WI_STAT_PCF)
   1756 			tap->wr_flags |= IEEE80211_RADIOTAP_F_CFP;
   1757 
   1758 		/* XXX IEEE80211_RADIOTAP_F_WEP */
   1759 		bpf_mtap2(sc->sc_drvbpf, tap, tap->wr_ihdr.it_len, m,
   1760 		    BPF_D_IN);
   1761 	}
   1762 
   1763 	/* synchronize driver's BSSID with firmware's BSSID */
   1764 	dir = wh->i_fc[1] & IEEE80211_FC1_DIR_MASK;
   1765 	if (ic->ic_opmode == IEEE80211_M_IBSS && dir == IEEE80211_FC1_DIR_NODS)
   1766 		wi_sync_bssid(sc, wh->i_addr3);
   1767 
   1768 	ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *));
   1769 
   1770 	ieee80211_input(ic, m, ni, rssi, rstamp);
   1771 
   1772 	wi_rssadapt_input(ic, ni, wh, rssi);
   1773 
   1774 	/*
   1775 	 * The frame may have caused the node to be marked for
   1776 	 * reclamation (e.g. in response to a DEAUTH message)
   1777 	 * so use release_node here instead of unref_node.
   1778 	 */
   1779 	ieee80211_free_node(ni);
   1780 
   1781 	splx(s);
   1782 }
   1783 
   1784 STATIC void
   1785 wi_tx_ex_intr(struct wi_softc *sc)
   1786 {
   1787 	struct ieee80211com *ic = &sc->sc_ic;
   1788 	struct ifnet *ifp = &sc->sc_if;
   1789 	struct ieee80211_node *ni;
   1790 	struct ieee80211_rssdesc *id;
   1791 	struct wi_rssdesc *rssd;
   1792 	struct wi_frame frmhdr;
   1793 	int fid, s;
   1794 	uint16_t status;
   1795 
   1796 	s = splnet();
   1797 
   1798 	fid = CSR_READ_2(sc, WI_TX_CMP_FID);
   1799 	/* Read in the frame header */
   1800 	if (wi_read_bap(sc, fid, 0, &frmhdr, sizeof(frmhdr)) != 0) {
   1801 		aprint_error_dev(sc->sc_dev, "%s read fid %x failed\n",
   1802 		    __func__, fid);
   1803 		wi_rssdescs_reset(ic, &sc->sc_rssd, &sc->sc_rssdfree,
   1804 		    &sc->sc_txpending);
   1805 		goto out;
   1806 	}
   1807 
   1808 	if (frmhdr.wi_tx_idx >= WI_NTXRSS) {
   1809 		aprint_error_dev(sc->sc_dev, "%s bad idx %02x\n",
   1810 		    __func__, frmhdr.wi_tx_idx);
   1811 		wi_rssdescs_reset(ic, &sc->sc_rssd, &sc->sc_rssdfree,
   1812 		    &sc->sc_txpending);
   1813 		goto out;
   1814 	}
   1815 
   1816 	status = le16toh(frmhdr.wi_status);
   1817 
   1818 	/*
   1819 	 * Spontaneous station disconnects appear as xmit
   1820 	 * errors.  Don't announce them and/or count them
   1821 	 * as an output error.
   1822 	 */
   1823 	if (ppsratecheck(&lasttxerror, &curtxeps, wi_txerate)) {
   1824 		aprint_error_dev(sc->sc_dev, "tx failed");
   1825 		if (status & WI_TXSTAT_RET_ERR)
   1826 			printf(", retry limit exceeded");
   1827 		if (status & WI_TXSTAT_AGED_ERR)
   1828 			printf(", max transmit lifetime exceeded");
   1829 		if (status & WI_TXSTAT_DISCONNECT)
   1830 			printf(", port disconnected");
   1831 		if (status & WI_TXSTAT_FORM_ERR)
   1832 			printf(", invalid format (data len %u src %s)",
   1833 				le16toh(frmhdr.wi_dat_len),
   1834 				ether_sprintf(frmhdr.wi_ehdr.ether_shost));
   1835 		if (status & ~0xf)
   1836 			printf(", status=0x%x", status);
   1837 		printf("\n");
   1838 	}
   1839 	ifp->if_oerrors++;
   1840 	rssd = &sc->sc_rssd[frmhdr.wi_tx_idx];
   1841 	id = &rssd->rd_desc;
   1842 	if ((status & WI_TXSTAT_RET_ERR) != 0)
   1843 		wi_lower_rate(ic, id);
   1844 
   1845 	ni = id->id_node;
   1846 	id->id_node = NULL;
   1847 
   1848 	if (ni == NULL) {
   1849 		aprint_error_dev(sc->sc_dev, "%s null node, rssdesc %02x\n",
   1850 		    __func__, frmhdr.wi_tx_idx);
   1851 		goto out;
   1852 	}
   1853 
   1854 	if (sc->sc_txpending[id->id_rateidx]-- == 0) {
   1855 		aprint_error_dev(sc->sc_dev, "%s txpending[%i] wraparound",
   1856 		    __func__, id->id_rateidx);
   1857 		sc->sc_txpending[id->id_rateidx] = 0;
   1858 	}
   1859 	if (ni != NULL)
   1860 		ieee80211_free_node(ni);
   1861 	SLIST_INSERT_HEAD(&sc->sc_rssdfree, rssd, rd_next);
   1862 out:
   1863 	ifp->if_flags &= ~IFF_OACTIVE;
   1864 	splx(s);
   1865 }
   1866 
   1867 STATIC void
   1868 wi_txalloc_intr(struct wi_softc *sc)
   1869 {
   1870 	int fid, cur, s;
   1871 
   1872 	s = splnet();
   1873 
   1874 	fid = CSR_READ_2(sc, WI_ALLOC_FID);
   1875 
   1876 	cur = sc->sc_txalloc;
   1877 #ifdef DIAGNOSTIC
   1878 	if (sc->sc_txstarted == 0) {
   1879 		printf("%s: spurious alloc %x != %x, alloc %d queue %d start %d alloced %d queued %d started %d\n",
   1880 		    device_xname(sc->sc_dev), fid, sc->sc_txd[cur].d_fid, cur,
   1881 		    sc->sc_txqueue, sc->sc_txstart, sc->sc_txalloced, sc->sc_txqueued, sc->sc_txstarted);
   1882 		splx(s);
   1883 		return;
   1884 	}
   1885 #endif
   1886 	--sc->sc_txstarted;
   1887 	++sc->sc_txalloced;
   1888 	sc->sc_txd[cur].d_fid = fid;
   1889 	sc->sc_txalloc = (cur + 1) % WI_NTXBUF;
   1890 #ifdef WI_RING_DEBUG
   1891 	printf("%s: alloc %04x, alloc %d queue %d start %d alloced %d queued %d started %d\n",
   1892 	    device_xname(sc->sc_dev), fid,
   1893 	    sc->sc_txalloc, sc->sc_txqueue, sc->sc_txstart,
   1894 	    sc->sc_txalloced, sc->sc_txqueued, sc->sc_txstarted);
   1895 #endif
   1896 	splx(s);
   1897 }
   1898 
   1899 STATIC void
   1900 wi_cmd_intr(struct wi_softc *sc)
   1901 {
   1902 	struct ifnet *ifp = &sc->sc_if;
   1903 	int s;
   1904 
   1905 	if (sc->sc_invalid)
   1906 		return;
   1907 
   1908 	s = splnet();
   1909 #ifdef WI_DEBUG
   1910 	if (wi_debug > 1)
   1911 		printf("%s: %d txcmds outstanding\n", __func__, sc->sc_txcmds);
   1912 #endif
   1913 	KASSERT(sc->sc_txcmds > 0);
   1914 
   1915 	--sc->sc_txcmds;
   1916 
   1917 	if (--sc->sc_txqueued == 0) {
   1918 		sc->sc_tx_timer = 0;
   1919 		ifp->if_flags &= ~IFF_OACTIVE;
   1920 #ifdef WI_RING_DEBUG
   1921 	printf("%s: cmd       , alloc %d queue %d start %d alloced %d queued %d started %d\n",
   1922 	    device_xname(sc->sc_dev),
   1923 	    sc->sc_txalloc, sc->sc_txqueue, sc->sc_txstart,
   1924 	    sc->sc_txalloced, sc->sc_txqueued, sc->sc_txstarted);
   1925 #endif
   1926 	} else
   1927 		wi_push_packet(sc);
   1928 	splx(s);
   1929 }
   1930 
   1931 STATIC void
   1932 wi_push_packet(struct wi_softc *sc)
   1933 {
   1934 	struct ifnet *ifp = &sc->sc_if;
   1935 	int cur, fid;
   1936 
   1937 	cur = sc->sc_txstart;
   1938 	fid = sc->sc_txd[cur].d_fid;
   1939 
   1940 	KASSERT(sc->sc_txcmds == 0);
   1941 
   1942 	if (wi_cmd_start(sc, WI_CMD_TX | WI_RECLAIM, fid, 0, 0)) {
   1943 		aprint_error_dev(sc->sc_dev, "xmit failed\n");
   1944 		/* XXX ring might have a hole */
   1945 	}
   1946 
   1947 	if (sc->sc_txcmds++ > 0)
   1948 		printf("%s: %d tx cmds pending!!!\n", __func__, sc->sc_txcmds);
   1949 
   1950 	++sc->sc_txstarted;
   1951 #ifdef DIAGNOSTIC
   1952 	if (sc->sc_txstarted > WI_NTXBUF)
   1953 		aprint_error_dev(sc->sc_dev, "too many buffers started\n");
   1954 #endif
   1955 	sc->sc_txstart = (cur + 1) % WI_NTXBUF;
   1956 	sc->sc_tx_timer = 5;
   1957 	ifp->if_timer = 1;
   1958 #ifdef WI_RING_DEBUG
   1959 	printf("%s: push  %04x, alloc %d queue %d start %d alloced %d queued %d started %d\n",
   1960 	    device_xname(sc->sc_dev), fid,
   1961 	    sc->sc_txalloc, sc->sc_txqueue, sc->sc_txstart,
   1962 	    sc->sc_txalloced, sc->sc_txqueued, sc->sc_txstarted);
   1963 #endif
   1964 }
   1965 
   1966 STATIC void
   1967 wi_tx_intr(struct wi_softc *sc)
   1968 {
   1969 	struct ieee80211com *ic = &sc->sc_ic;
   1970 	struct ifnet *ifp = &sc->sc_if;
   1971 	struct ieee80211_node *ni;
   1972 	struct ieee80211_rssdesc *id;
   1973 	struct wi_rssdesc *rssd;
   1974 	struct wi_frame frmhdr;
   1975 	int fid, s;
   1976 
   1977 	s = splnet();
   1978 
   1979 	fid = CSR_READ_2(sc, WI_TX_CMP_FID);
   1980 	/* Read in the frame header */
   1981 	if (wi_read_bap(sc, fid, offsetof(struct wi_frame, wi_tx_swsup2),
   1982 	                &frmhdr.wi_tx_swsup2, 2) != 0) {
   1983 		aprint_error_dev(sc->sc_dev, "%s read fid %x failed\n",
   1984 		    __func__, fid);
   1985 		wi_rssdescs_reset(ic, &sc->sc_rssd, &sc->sc_rssdfree,
   1986 		    &sc->sc_txpending);
   1987 		goto out;
   1988 	}
   1989 
   1990 	if (frmhdr.wi_tx_idx >= WI_NTXRSS) {
   1991 		aprint_error_dev(sc->sc_dev, "%s bad idx %02x\n",
   1992 		    __func__, frmhdr.wi_tx_idx);
   1993 		wi_rssdescs_reset(ic, &sc->sc_rssd, &sc->sc_rssdfree,
   1994 		    &sc->sc_txpending);
   1995 		goto out;
   1996 	}
   1997 
   1998 	rssd = &sc->sc_rssd[frmhdr.wi_tx_idx];
   1999 	id = &rssd->rd_desc;
   2000 	wi_raise_rate(ic, id);
   2001 
   2002 	ni = id->id_node;
   2003 	id->id_node = NULL;
   2004 
   2005 	if (ni == NULL) {
   2006 		aprint_error_dev(sc->sc_dev, "%s null node, rssdesc %02x\n",
   2007 		    __func__, frmhdr.wi_tx_idx);
   2008 		goto out;
   2009 	}
   2010 
   2011 	if (sc->sc_txpending[id->id_rateidx]-- == 0) {
   2012 		aprint_error_dev(sc->sc_dev, "%s txpending[%i] wraparound",
   2013 		    __func__, id->id_rateidx);
   2014 		sc->sc_txpending[id->id_rateidx] = 0;
   2015 	}
   2016 	if (ni != NULL)
   2017 		ieee80211_free_node(ni);
   2018 	SLIST_INSERT_HEAD(&sc->sc_rssdfree, rssd, rd_next);
   2019 out:
   2020 	ifp->if_flags &= ~IFF_OACTIVE;
   2021 	splx(s);
   2022 }
   2023 
   2024 STATIC void
   2025 wi_info_intr(struct wi_softc *sc)
   2026 {
   2027 	struct ieee80211com *ic = &sc->sc_ic;
   2028 	struct ifnet *ifp = &sc->sc_if;
   2029 	int i, s, fid, len, off;
   2030 	uint16_t ltbuf[2];
   2031 	uint16_t stat;
   2032 	uint32_t *ptr;
   2033 
   2034 	fid = CSR_READ_2(sc, WI_INFO_FID);
   2035 	wi_read_bap(sc, fid, 0, ltbuf, sizeof(ltbuf));
   2036 
   2037 	switch (le16toh(ltbuf[1])) {
   2038 
   2039 	case WI_INFO_LINK_STAT:
   2040 		wi_read_bap(sc, fid, sizeof(ltbuf), &stat, sizeof(stat));
   2041 		DPRINTF(("wi_info_intr: LINK_STAT 0x%x\n", le16toh(stat)));
   2042 		switch (le16toh(stat)) {
   2043 		case CONNECTED:
   2044 			sc->sc_flags &= ~WI_FLAGS_OUTRANGE;
   2045 			if (ic->ic_state == IEEE80211_S_RUN &&
   2046 			    ic->ic_opmode != IEEE80211_M_IBSS)
   2047 				break;
   2048 			/* FALLTHROUGH */
   2049 		case AP_CHANGE:
   2050 			s = splnet();
   2051 			ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
   2052 			splx(s);
   2053 			break;
   2054 		case AP_IN_RANGE:
   2055 			sc->sc_flags &= ~WI_FLAGS_OUTRANGE;
   2056 			break;
   2057 		case AP_OUT_OF_RANGE:
   2058 			if (sc->sc_firmware_type == WI_SYMBOL &&
   2059 			    sc->sc_scan_timer > 0) {
   2060 				if (wi_cmd(sc, WI_CMD_INQUIRE,
   2061 				    WI_INFO_HOST_SCAN_RESULTS, 0, 0) != 0)
   2062 					sc->sc_scan_timer = 0;
   2063 				break;
   2064 			}
   2065 			if (ic->ic_opmode == IEEE80211_M_STA)
   2066 				sc->sc_flags |= WI_FLAGS_OUTRANGE;
   2067 			break;
   2068 		case DISCONNECTED:
   2069 		case ASSOC_FAILED:
   2070 			s = splnet();
   2071 			if (ic->ic_opmode == IEEE80211_M_STA)
   2072 				ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
   2073 			splx(s);
   2074 			break;
   2075 		}
   2076 		break;
   2077 
   2078 	case WI_INFO_COUNTERS:
   2079 		/* some card versions have a larger stats structure */
   2080 		len = uimin(le16toh(ltbuf[0]) - 1, sizeof(sc->sc_stats) / 4);
   2081 		ptr = (uint32_t *)&sc->sc_stats;
   2082 		off = sizeof(ltbuf);
   2083 		for (i = 0; i < len; i++, off += 2, ptr++) {
   2084 			wi_read_bap(sc, fid, off, &stat, sizeof(stat));
   2085 			stat = le16toh(stat);
   2086 #ifdef WI_HERMES_STATS_WAR
   2087 			if (stat & 0xf000)
   2088 				stat = ~stat;
   2089 #endif
   2090 			*ptr += stat;
   2091 		}
   2092 		ifp->if_collisions = sc->sc_stats.wi_tx_single_retries +
   2093 		    sc->sc_stats.wi_tx_multi_retries +
   2094 		    sc->sc_stats.wi_tx_retry_limit;
   2095 		break;
   2096 
   2097 	case WI_INFO_SCAN_RESULTS:
   2098 	case WI_INFO_HOST_SCAN_RESULTS:
   2099 		wi_scan_result(sc, fid, le16toh(ltbuf[0]));
   2100 		break;
   2101 
   2102 	default:
   2103 		DPRINTF(("wi_info_intr: got fid %x type %x len %d\n", fid,
   2104 		    le16toh(ltbuf[1]), le16toh(ltbuf[0])));
   2105 		break;
   2106 	}
   2107 }
   2108 
   2109 STATIC int
   2110 wi_write_multi(struct wi_softc *sc)
   2111 {
   2112 	struct ifnet *ifp = &sc->sc_if;
   2113 	int n;
   2114 	struct wi_mcast mlist;
   2115 	struct ether_multi *enm;
   2116 	struct ether_multistep estep;
   2117 
   2118 	if ((ifp->if_flags & IFF_PROMISC) != 0) {
   2119 allmulti:
   2120 		ifp->if_flags |= IFF_ALLMULTI;
   2121 		memset(&mlist, 0, sizeof(mlist));
   2122 		return wi_write_rid(sc, WI_RID_MCAST_LIST, &mlist,
   2123 		    sizeof(mlist));
   2124 	}
   2125 
   2126 	n = 0;
   2127 	ETHER_FIRST_MULTI(estep, &sc->sc_ec, enm);
   2128 	while (enm != NULL) {
   2129 		/* Punt on ranges or too many multicast addresses. */
   2130 		if (!IEEE80211_ADDR_EQ(enm->enm_addrlo, enm->enm_addrhi) ||
   2131 		    n >= sizeof(mlist) / sizeof(mlist.wi_mcast[0]))
   2132 			goto allmulti;
   2133 
   2134 		IEEE80211_ADDR_COPY(&mlist.wi_mcast[n], enm->enm_addrlo);
   2135 		n++;
   2136 		ETHER_NEXT_MULTI(estep, enm);
   2137 	}
   2138 	ifp->if_flags &= ~IFF_ALLMULTI;
   2139 	return wi_write_rid(sc, WI_RID_MCAST_LIST, &mlist,
   2140 	    IEEE80211_ADDR_LEN * n);
   2141 }
   2142 
   2143 
   2144 STATIC void
   2145 wi_read_nicid(struct wi_softc *sc)
   2146 {
   2147 	const struct wi_card_ident *id;
   2148 	char *p;
   2149 	int len;
   2150 	uint16_t ver[4];
   2151 
   2152 	/* getting chip identity */
   2153 	memset(ver, 0, sizeof(ver));
   2154 	len = sizeof(ver);
   2155 	wi_read_rid(sc, WI_RID_CARD_ID, ver, &len);
   2156 	printf("%s: using ", device_xname(sc->sc_dev));
   2157 DPRINTF2(("wi_read_nicid: CARD_ID: %x %x %x %x\n", le16toh(ver[0]), le16toh(ver[1]), le16toh(ver[2]), le16toh(ver[3])));
   2158 
   2159 	sc->sc_firmware_type = WI_NOTYPE;
   2160 	for (id = wi_card_ident; id->card_name != NULL; id++) {
   2161 		if (le16toh(ver[0]) == id->card_id) {
   2162 			printf("%s", id->card_name);
   2163 			sc->sc_firmware_type = id->firm_type;
   2164 			break;
   2165 		}
   2166 	}
   2167 	if (sc->sc_firmware_type == WI_NOTYPE) {
   2168 		if (le16toh(ver[0]) & 0x8000) {
   2169 			printf("Unknown PRISM2 chip");
   2170 			sc->sc_firmware_type = WI_INTERSIL;
   2171 		} else {
   2172 			printf("Unknown Lucent chip");
   2173 			sc->sc_firmware_type = WI_LUCENT;
   2174 		}
   2175 	}
   2176 
   2177 	/* get primary firmware version (Only Prism chips) */
   2178 	if (sc->sc_firmware_type != WI_LUCENT) {
   2179 		memset(ver, 0, sizeof(ver));
   2180 		len = sizeof(ver);
   2181 		wi_read_rid(sc, WI_RID_PRI_IDENTITY, ver, &len);
   2182 		sc->sc_pri_firmware_ver = le16toh(ver[2]) * 10000 +
   2183 		    le16toh(ver[3]) * 100 + le16toh(ver[1]);
   2184 	}
   2185 
   2186 	/* get station firmware version */
   2187 	memset(ver, 0, sizeof(ver));
   2188 	len = sizeof(ver);
   2189 	wi_read_rid(sc, WI_RID_STA_IDENTITY, ver, &len);
   2190 	sc->sc_sta_firmware_ver = le16toh(ver[2]) * 10000 +
   2191 	    le16toh(ver[3]) * 100 + le16toh(ver[1]);
   2192 	if (sc->sc_firmware_type == WI_INTERSIL &&
   2193 	    (sc->sc_sta_firmware_ver == 10102 ||
   2194 	     sc->sc_sta_firmware_ver == 20102)) {
   2195 		char ident[12];
   2196 		memset(ident, 0, sizeof(ident));
   2197 		len = sizeof(ident);
   2198 		/* value should be the format like "V2.00-11" */
   2199 		if (wi_read_rid(sc, WI_RID_SYMBOL_IDENTITY, ident, &len) == 0 &&
   2200 		    *(p = (char *)ident) >= 'A' &&
   2201 		    p[2] == '.' && p[5] == '-' && p[8] == '\0') {
   2202 			sc->sc_firmware_type = WI_SYMBOL;
   2203 			sc->sc_sta_firmware_ver = (p[1] - '0') * 10000 +
   2204 			    (p[3] - '0') * 1000 + (p[4] - '0') * 100 +
   2205 			    (p[6] - '0') * 10 + (p[7] - '0');
   2206 		}
   2207 	}
   2208 
   2209 	printf("\n%s: %s Firmware: ", device_xname(sc->sc_dev),
   2210 	     sc->sc_firmware_type == WI_LUCENT ? "Lucent" :
   2211 	    (sc->sc_firmware_type == WI_SYMBOL ? "Symbol" : "Intersil"));
   2212 	if (sc->sc_firmware_type != WI_LUCENT)	/* XXX */
   2213 		printf("Primary (%u.%u.%u), ",
   2214 		    sc->sc_pri_firmware_ver / 10000,
   2215 		    (sc->sc_pri_firmware_ver % 10000) / 100,
   2216 		    sc->sc_pri_firmware_ver % 100);
   2217 	printf("Station (%u.%u.%u)\n",
   2218 	    sc->sc_sta_firmware_ver / 10000,
   2219 	    (sc->sc_sta_firmware_ver % 10000) / 100,
   2220 	    sc->sc_sta_firmware_ver % 100);
   2221 }
   2222 
   2223 STATIC int
   2224 wi_write_ssid(struct wi_softc *sc, int rid, uint8_t *buf, int buflen)
   2225 {
   2226 	struct wi_ssid ssid;
   2227 
   2228 	if (buflen > IEEE80211_NWID_LEN)
   2229 		return ENOBUFS;
   2230 	memset(&ssid, 0, sizeof(ssid));
   2231 	ssid.wi_len = htole16(buflen);
   2232 	memcpy(ssid.wi_ssid, buf, buflen);
   2233 	return wi_write_rid(sc, rid, &ssid, sizeof(ssid));
   2234 }
   2235 
   2236 STATIC int
   2237 wi_get_cfg(struct ifnet *ifp, u_long cmd, void *data)
   2238 {
   2239 	struct wi_softc *sc = ifp->if_softc;
   2240 	struct ieee80211com *ic = &sc->sc_ic;
   2241 	struct ifreq *ifr = (struct ifreq *)data;
   2242 	struct wi_req wreq;
   2243 	int len, n, error;
   2244 
   2245 	error = copyin(ifr->ifr_data, &wreq, sizeof(wreq));
   2246 	if (error)
   2247 		return error;
   2248 	len = (wreq.wi_len - 1) * 2;
   2249 	if (len < sizeof(uint16_t))
   2250 		return ENOSPC;
   2251 	if (len > sizeof(wreq.wi_val))
   2252 		len = sizeof(wreq.wi_val);
   2253 
   2254 	switch (wreq.wi_type) {
   2255 
   2256 	case WI_RID_IFACE_STATS:
   2257 		memcpy(wreq.wi_val, &sc->sc_stats, sizeof(sc->sc_stats));
   2258 		if (len < sizeof(sc->sc_stats))
   2259 			error = ENOSPC;
   2260 		else
   2261 			len = sizeof(sc->sc_stats);
   2262 		break;
   2263 
   2264 	case WI_RID_ENCRYPTION:
   2265 	case WI_RID_TX_CRYPT_KEY:
   2266 	case WI_RID_DEFLT_CRYPT_KEYS:
   2267 	case WI_RID_TX_RATE:
   2268 		return ieee80211_cfgget(ic, cmd, data);
   2269 
   2270 	case WI_RID_MICROWAVE_OVEN:
   2271 		if (sc->sc_enabled && (sc->sc_flags & WI_FLAGS_HAS_MOR)) {
   2272 			error = wi_read_rid(sc, wreq.wi_type, wreq.wi_val,
   2273 			    &len);
   2274 			break;
   2275 		}
   2276 		wreq.wi_val[0] = htole16(sc->sc_microwave_oven);
   2277 		len = sizeof(uint16_t);
   2278 		break;
   2279 
   2280 	case WI_RID_DBM_ADJUST:
   2281 		if (sc->sc_enabled && (sc->sc_flags & WI_FLAGS_HAS_DBMADJUST)) {
   2282 			error = wi_read_rid(sc, wreq.wi_type, wreq.wi_val,
   2283 			    &len);
   2284 			break;
   2285 		}
   2286 		wreq.wi_val[0] = htole16(sc->sc_dbm_offset);
   2287 		len = sizeof(uint16_t);
   2288 		break;
   2289 
   2290 	case WI_RID_ROAMING_MODE:
   2291 		if (sc->sc_enabled && (sc->sc_flags & WI_FLAGS_HAS_ROAMING)) {
   2292 			error = wi_read_rid(sc, wreq.wi_type, wreq.wi_val,
   2293 			    &len);
   2294 			break;
   2295 		}
   2296 		wreq.wi_val[0] = htole16(sc->sc_roaming_mode);
   2297 		len = sizeof(uint16_t);
   2298 		break;
   2299 
   2300 	case WI_RID_SYSTEM_SCALE:
   2301 		if (sc->sc_enabled && (sc->sc_flags & WI_FLAGS_HAS_SYSSCALE)) {
   2302 			error = wi_read_rid(sc, wreq.wi_type, wreq.wi_val,
   2303 			    &len);
   2304 			break;
   2305 		}
   2306 		wreq.wi_val[0] = htole16(sc->sc_system_scale);
   2307 		len = sizeof(uint16_t);
   2308 		break;
   2309 
   2310 	case WI_RID_FRAG_THRESH:
   2311 		if (sc->sc_enabled && (sc->sc_flags & WI_FLAGS_HAS_FRAGTHR)) {
   2312 			error = wi_read_rid(sc, wreq.wi_type, wreq.wi_val,
   2313 			    &len);
   2314 			break;
   2315 		}
   2316 		wreq.wi_val[0] = htole16(sc->sc_frag_thresh);
   2317 		len = sizeof(uint16_t);
   2318 		break;
   2319 
   2320 	case WI_RID_READ_APS:
   2321 #ifndef	IEEE80211_NO_HOSTAP
   2322 		if (ic->ic_opmode == IEEE80211_M_HOSTAP)
   2323 			return ieee80211_cfgget(ic, cmd, data);
   2324 #endif /* !IEEE80211_NO_HOSTAP */
   2325 		if (sc->sc_scan_timer > 0) {
   2326 			error = EINPROGRESS;
   2327 			break;
   2328 		}
   2329 		n = sc->sc_naps;
   2330 		if (len < sizeof(n)) {
   2331 			error = ENOSPC;
   2332 			break;
   2333 		}
   2334 		if (len < sizeof(n) + sizeof(struct wi_apinfo) * n)
   2335 			n = (len - sizeof(n)) / sizeof(struct wi_apinfo);
   2336 		len = sizeof(n) + sizeof(struct wi_apinfo) * n;
   2337 		memcpy(wreq.wi_val, &n, sizeof(n));
   2338 		memcpy((char *)wreq.wi_val + sizeof(n), sc->sc_aps,
   2339 		    sizeof(struct wi_apinfo) * n);
   2340 		break;
   2341 
   2342 	default:
   2343 		if (sc->sc_enabled) {
   2344 			error = wi_read_rid(sc, wreq.wi_type, wreq.wi_val,
   2345 			    &len);
   2346 			break;
   2347 		}
   2348 		switch (wreq.wi_type) {
   2349 		case WI_RID_MAX_DATALEN:
   2350 			wreq.wi_val[0] = htole16(sc->sc_max_datalen);
   2351 			len = sizeof(uint16_t);
   2352 			break;
   2353 		case WI_RID_FRAG_THRESH:
   2354 			wreq.wi_val[0] = htole16(sc->sc_frag_thresh);
   2355 			len = sizeof(uint16_t);
   2356 			break;
   2357 		case WI_RID_RTS_THRESH:
   2358 			wreq.wi_val[0] = htole16(sc->sc_rts_thresh);
   2359 			len = sizeof(uint16_t);
   2360 			break;
   2361 		case WI_RID_CNFAUTHMODE:
   2362 			wreq.wi_val[0] = htole16(sc->sc_cnfauthmode);
   2363 			len = sizeof(uint16_t);
   2364 			break;
   2365 		case WI_RID_NODENAME:
   2366 			if (len < sc->sc_nodelen + sizeof(uint16_t)) {
   2367 				error = ENOSPC;
   2368 				break;
   2369 			}
   2370 			len = sc->sc_nodelen + sizeof(uint16_t);
   2371 			wreq.wi_val[0] = htole16((sc->sc_nodelen + 1) / 2);
   2372 			memcpy(&wreq.wi_val[1], sc->sc_nodename,
   2373 			    sc->sc_nodelen);
   2374 			break;
   2375 		default:
   2376 			return ieee80211_cfgget(ic, cmd, data);
   2377 		}
   2378 		break;
   2379 	}
   2380 	if (error)
   2381 		return error;
   2382 	wreq.wi_len = (len + 1) / 2 + 1;
   2383 	return copyout(&wreq, ifr->ifr_data, (wreq.wi_len + 1) * 2);
   2384 }
   2385 
   2386 STATIC int
   2387 wi_set_cfg(struct ifnet *ifp, u_long cmd, void *data)
   2388 {
   2389 	struct wi_softc *sc = ifp->if_softc;
   2390 	struct ieee80211com *ic = &sc->sc_ic;
   2391 	struct ifreq *ifr = (struct ifreq *)data;
   2392 	struct ieee80211_rateset *rs = &ic->ic_sup_rates[IEEE80211_MODE_11B];
   2393 	struct wi_req wreq;
   2394 	struct mbuf *m;
   2395 	int i, len, error;
   2396 
   2397 	error = copyin(ifr->ifr_data, &wreq, sizeof(wreq));
   2398 	if (error)
   2399 		return error;
   2400 	len = (wreq.wi_len - 1) * 2;
   2401 	switch (wreq.wi_type) {
   2402         case WI_RID_MAC_NODE:
   2403 		/* XXX convert to SIOCALIFADDR, AF_LINK, IFLR_ACTIVE */
   2404 		(void)memcpy(ic->ic_myaddr, wreq.wi_val, ETHER_ADDR_LEN);
   2405 		if_set_sadl(ifp, ic->ic_myaddr, ETHER_ADDR_LEN, false);
   2406 		wi_write_rid(sc, WI_RID_MAC_NODE, ic->ic_myaddr,
   2407 		    IEEE80211_ADDR_LEN);
   2408 		break;
   2409 
   2410 	case WI_RID_DBM_ADJUST:
   2411 		return ENODEV;
   2412 
   2413 	case WI_RID_NODENAME:
   2414 		if (le16toh(wreq.wi_val[0]) * 2 > len ||
   2415 		    le16toh(wreq.wi_val[0]) > sizeof(sc->sc_nodename)) {
   2416 			error = ENOSPC;
   2417 			break;
   2418 		}
   2419 		if (sc->sc_enabled) {
   2420 			error = wi_write_rid(sc, wreq.wi_type, wreq.wi_val,
   2421 			    len);
   2422 			if (error)
   2423 				break;
   2424 		}
   2425 		sc->sc_nodelen = le16toh(wreq.wi_val[0]) * 2;
   2426 		memcpy(sc->sc_nodename, &wreq.wi_val[1], sc->sc_nodelen);
   2427 		break;
   2428 
   2429 	case WI_RID_MICROWAVE_OVEN:
   2430 	case WI_RID_ROAMING_MODE:
   2431 	case WI_RID_SYSTEM_SCALE:
   2432 	case WI_RID_FRAG_THRESH:
   2433 		if (wreq.wi_type == WI_RID_MICROWAVE_OVEN &&
   2434 		    (sc->sc_flags & WI_FLAGS_HAS_MOR) == 0)
   2435 			break;
   2436 		if (wreq.wi_type == WI_RID_ROAMING_MODE &&
   2437 		    (sc->sc_flags & WI_FLAGS_HAS_ROAMING) == 0)
   2438 			break;
   2439 		if (wreq.wi_type == WI_RID_SYSTEM_SCALE &&
   2440 		    (sc->sc_flags & WI_FLAGS_HAS_SYSSCALE) == 0)
   2441 			break;
   2442 		if (wreq.wi_type == WI_RID_FRAG_THRESH &&
   2443 		    (sc->sc_flags & WI_FLAGS_HAS_FRAGTHR) == 0)
   2444 			break;
   2445 		/* FALLTHROUGH */
   2446 	case WI_RID_RTS_THRESH:
   2447 	case WI_RID_CNFAUTHMODE:
   2448 	case WI_RID_MAX_DATALEN:
   2449 		if (sc->sc_enabled) {
   2450 			error = wi_write_rid(sc, wreq.wi_type, wreq.wi_val,
   2451 			    sizeof(uint16_t));
   2452 			if (error)
   2453 				break;
   2454 		}
   2455 		switch (wreq.wi_type) {
   2456 		case WI_RID_FRAG_THRESH:
   2457 			sc->sc_frag_thresh = le16toh(wreq.wi_val[0]);
   2458 			break;
   2459 		case WI_RID_RTS_THRESH:
   2460 			sc->sc_rts_thresh = le16toh(wreq.wi_val[0]);
   2461 			break;
   2462 		case WI_RID_MICROWAVE_OVEN:
   2463 			sc->sc_microwave_oven = le16toh(wreq.wi_val[0]);
   2464 			break;
   2465 		case WI_RID_ROAMING_MODE:
   2466 			sc->sc_roaming_mode = le16toh(wreq.wi_val[0]);
   2467 			break;
   2468 		case WI_RID_SYSTEM_SCALE:
   2469 			sc->sc_system_scale = le16toh(wreq.wi_val[0]);
   2470 			break;
   2471 		case WI_RID_CNFAUTHMODE:
   2472 			sc->sc_cnfauthmode = le16toh(wreq.wi_val[0]);
   2473 			break;
   2474 		case WI_RID_MAX_DATALEN:
   2475 			sc->sc_max_datalen = le16toh(wreq.wi_val[0]);
   2476 			break;
   2477 		}
   2478 		break;
   2479 
   2480 	case WI_RID_TX_RATE:
   2481 		switch (le16toh(wreq.wi_val[0])) {
   2482 		case 3:
   2483 			ic->ic_fixed_rate = -1;
   2484 			break;
   2485 		default:
   2486 			for (i = 0; i < IEEE80211_RATE_SIZE; i++) {
   2487 				if ((rs->rs_rates[i] & IEEE80211_RATE_VAL)
   2488 				    / 2 == le16toh(wreq.wi_val[0]))
   2489 					break;
   2490 			}
   2491 			if (i == IEEE80211_RATE_SIZE)
   2492 				return EINVAL;
   2493 			ic->ic_fixed_rate = i;
   2494 		}
   2495 		if (sc->sc_enabled)
   2496 			error = wi_cfg_txrate(sc);
   2497 		break;
   2498 
   2499 	case WI_RID_SCAN_APS:
   2500 		if (sc->sc_enabled && ic->ic_opmode != IEEE80211_M_HOSTAP)
   2501 			error = wi_scan_ap(sc, 0x3fff, 0x000f);
   2502 		break;
   2503 
   2504 	case WI_RID_MGMT_XMIT:
   2505 		if (!sc->sc_enabled) {
   2506 			error = ENETDOWN;
   2507 			break;
   2508 		}
   2509 		if (ic->ic_mgtq.ifq_len > 5) {
   2510 			error = EAGAIN;
   2511 			break;
   2512 		}
   2513 		/* XXX wi_len looks in uint8_t, not in uint16_t */
   2514 		m = m_devget((char *)&wreq.wi_val, wreq.wi_len, 0, ifp);
   2515 		if (m == NULL) {
   2516 			error = ENOMEM;
   2517 			break;
   2518 		}
   2519 		IF_ENQUEUE(&ic->ic_mgtq, m);
   2520 		break;
   2521 
   2522 	default:
   2523 		if (sc->sc_enabled) {
   2524 			error = wi_write_rid(sc, wreq.wi_type, wreq.wi_val,
   2525 			    len);
   2526 			if (error)
   2527 				break;
   2528 		}
   2529 		error = ieee80211_cfgset(ic, cmd, data);
   2530 		break;
   2531 	}
   2532 	return error;
   2533 }
   2534 
   2535 /* Rate is 0 for hardware auto-select, otherwise rate is
   2536  * 2, 4, 11, or 22 (units of 500Kbps).
   2537  */
   2538 STATIC int
   2539 wi_write_txrate(struct wi_softc *sc, int rate)
   2540 {
   2541 	uint16_t hwrate;
   2542 
   2543 	/* rate: 0, 2, 4, 11, 22 */
   2544 	switch (sc->sc_firmware_type) {
   2545 	case WI_LUCENT:
   2546 		switch (rate & IEEE80211_RATE_VAL) {
   2547 		case 2:
   2548 			hwrate = 1;
   2549 			break;
   2550 		case 4:
   2551 			hwrate = 2;
   2552 			break;
   2553 		default:
   2554 			hwrate = 3;	/* auto */
   2555 			break;
   2556 		case 11:
   2557 			hwrate = 4;
   2558 			break;
   2559 		case 22:
   2560 			hwrate = 5;
   2561 			break;
   2562 		}
   2563 		break;
   2564 	default:
   2565 		switch (rate & IEEE80211_RATE_VAL) {
   2566 		case 2:
   2567 			hwrate = 1;
   2568 			break;
   2569 		case 4:
   2570 			hwrate = 2;
   2571 			break;
   2572 		case 11:
   2573 			hwrate = 4;
   2574 			break;
   2575 		case 22:
   2576 			hwrate = 8;
   2577 			break;
   2578 		default:
   2579 			hwrate = 15;	/* auto */
   2580 			break;
   2581 		}
   2582 		break;
   2583 	}
   2584 
   2585 	if (sc->sc_tx_rate == hwrate)
   2586 		return 0;
   2587 
   2588 	if (sc->sc_if.if_flags & IFF_DEBUG)
   2589 		printf("%s: tx rate %d -> %d (%d)\n", __func__, sc->sc_tx_rate,
   2590 		    hwrate, rate);
   2591 
   2592 	sc->sc_tx_rate = hwrate;
   2593 
   2594 	return wi_write_val(sc, WI_RID_TX_RATE, sc->sc_tx_rate);
   2595 }
   2596 
   2597 STATIC int
   2598 wi_cfg_txrate(struct wi_softc *sc)
   2599 {
   2600 	struct ieee80211com *ic = &sc->sc_ic;
   2601 	struct ieee80211_rateset *rs;
   2602 	int rate;
   2603 
   2604 	rs = &ic->ic_sup_rates[IEEE80211_MODE_11B];
   2605 
   2606 	sc->sc_tx_rate = 0; /* force write to RID */
   2607 
   2608 	if (ic->ic_fixed_rate < 0)
   2609 		rate = 0;	/* auto */
   2610 	else
   2611 		rate = rs->rs_rates[ic->ic_fixed_rate];
   2612 
   2613 	return wi_write_txrate(sc, rate);
   2614 }
   2615 
   2616 STATIC int
   2617 wi_key_delete(struct ieee80211com *ic, const struct ieee80211_key *k)
   2618 {
   2619 	struct wi_softc *sc = ic->ic_ifp->if_softc;
   2620 	u_int keyix = k->wk_keyix;
   2621 
   2622 	DPRINTF(("%s: delete key %u\n", __func__, keyix));
   2623 
   2624 	if (keyix >= IEEE80211_WEP_NKID)
   2625 		return 0;
   2626 	if (k->wk_keylen != 0)
   2627 		sc->sc_flags &= ~WI_FLAGS_WEP_VALID;
   2628 
   2629 	return 1;
   2630 }
   2631 
   2632 static int
   2633 wi_key_set(struct ieee80211com *ic, const struct ieee80211_key *k,
   2634 	const uint8_t mac[IEEE80211_ADDR_LEN])
   2635 {
   2636 	struct wi_softc *sc = ic->ic_ifp->if_softc;
   2637 
   2638 	DPRINTF(("%s: set key %u\n", __func__, k->wk_keyix));
   2639 
   2640 	if (k->wk_keyix >= IEEE80211_WEP_NKID)
   2641 		return 0;
   2642 
   2643 	sc->sc_flags &= ~WI_FLAGS_WEP_VALID;
   2644 
   2645 	return 1;
   2646 }
   2647 
   2648 STATIC void
   2649 wi_key_update_begin(struct ieee80211com *ic)
   2650 {
   2651 	DPRINTF(("%s:\n", __func__));
   2652 }
   2653 
   2654 STATIC void
   2655 wi_key_update_end(struct ieee80211com *ic)
   2656 {
   2657 	struct ifnet *ifp = ic->ic_ifp;
   2658 	struct wi_softc *sc = ifp->if_softc;
   2659 
   2660 	DPRINTF(("%s:\n", __func__));
   2661 
   2662 	if ((sc->sc_flags & WI_FLAGS_WEP_VALID) != 0)
   2663 		return;
   2664 	if ((ic->ic_caps & IEEE80211_C_WEP) != 0 && sc->sc_enabled &&
   2665 	    !sc->sc_invalid)
   2666 		(void)wi_write_wep(sc);
   2667 }
   2668 
   2669 STATIC int
   2670 wi_write_wep(struct wi_softc *sc)
   2671 {
   2672 	struct ifnet *ifp = &sc->sc_if;
   2673 	struct ieee80211com *ic = &sc->sc_ic;
   2674 	int error = 0;
   2675 	int i, keylen;
   2676 	uint16_t val;
   2677 	struct wi_key wkey[IEEE80211_WEP_NKID];
   2678 
   2679 	if ((ifp->if_flags & IFF_RUNNING) != 0)
   2680 		wi_cmd(sc, WI_CMD_DISABLE | sc->sc_portnum, 0, 0, 0);
   2681 
   2682 	switch (sc->sc_firmware_type) {
   2683 	case WI_LUCENT:
   2684 		val = (ic->ic_flags & IEEE80211_F_PRIVACY) ? 1 : 0;
   2685 		error = wi_write_val(sc, WI_RID_ENCRYPTION, val);
   2686 		if (error)
   2687 			break;
   2688 		error = wi_write_val(sc, WI_RID_TX_CRYPT_KEY, ic->ic_def_txkey);
   2689 		if (error)
   2690 			break;
   2691 		memset(wkey, 0, sizeof(wkey));
   2692 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
   2693 			keylen = ic->ic_nw_keys[i].wk_keylen;
   2694 			wkey[i].wi_keylen = htole16(keylen);
   2695 			memcpy(wkey[i].wi_keydat, ic->ic_nw_keys[i].wk_key,
   2696 			    keylen);
   2697 		}
   2698 		error = wi_write_rid(sc, WI_RID_DEFLT_CRYPT_KEYS,
   2699 		    wkey, sizeof(wkey));
   2700 		break;
   2701 
   2702 	case WI_INTERSIL:
   2703 	case WI_SYMBOL:
   2704 		if (ic->ic_flags & IEEE80211_F_PRIVACY) {
   2705 			/*
   2706 			 * ONLY HWB3163 EVAL-CARD Firmware version
   2707 			 * less than 0.8 variant2
   2708 			 *
   2709 			 *   If promiscuous mode disable, Prism2 chip
   2710 			 *  does not work with WEP .
   2711 			 * It is under investigation for details.
   2712 			 * (ichiro (at) NetBSD.org)
   2713 			 */
   2714 			if (sc->sc_firmware_type == WI_INTERSIL &&
   2715 			    sc->sc_sta_firmware_ver < 802 ) {
   2716 				/* firm ver < 0.8 variant 2 */
   2717 				wi_write_val(sc, WI_RID_PROMISC, 1);
   2718 			}
   2719 			wi_write_val(sc, WI_RID_CNFAUTHMODE,
   2720 			    sc->sc_cnfauthmode);
   2721 			val = PRIVACY_INVOKED;
   2722 			if ((sc->sc_ic_flags & IEEE80211_F_DROPUNENC) != 0)
   2723 				val |= EXCLUDE_UNENCRYPTED;
   2724 #ifndef	IEEE80211_NO_HOSTAP
   2725 			/*
   2726 			 * Encryption firmware has a bug for HostAP mode.
   2727 			 */
   2728 			if (sc->sc_firmware_type == WI_INTERSIL &&
   2729 			    ic->ic_opmode == IEEE80211_M_HOSTAP)
   2730 				val |= HOST_ENCRYPT;
   2731 #endif /* !IEEE80211_NO_HOSTAP */
   2732 		} else {
   2733 			wi_write_val(sc, WI_RID_CNFAUTHMODE,
   2734 			    IEEE80211_AUTH_OPEN);
   2735 			val = HOST_ENCRYPT | HOST_DECRYPT;
   2736 		}
   2737 		error = wi_write_val(sc, WI_RID_P2_ENCRYPTION, val);
   2738 		if (error)
   2739 			break;
   2740 		error = wi_write_val(sc, WI_RID_P2_TX_CRYPT_KEY,
   2741 		    ic->ic_def_txkey);
   2742 		if (error)
   2743 			break;
   2744 		/*
   2745 		 * It seems that the firmware accept 104bit key only if
   2746 		 * all the keys have 104bit length.  We get the length of
   2747 		 * the transmit key and use it for all other keys.
   2748 		 * Perhaps we should use software WEP for such situation.
   2749 		 */
   2750 		if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
   2751 		    IEEE80211_KEY_UNDEFINED(ic->ic_nw_keys[ic->ic_def_txkey]))
   2752 			keylen = 13;	/* No keys => 104bit ok */
   2753 		else
   2754 			keylen = ic->ic_nw_keys[ic->ic_def_txkey].wk_keylen;
   2755 
   2756 		if (keylen > IEEE80211_WEP_KEYLEN)
   2757 			keylen = 13;	/* 104bit keys */
   2758 		else
   2759 			keylen = IEEE80211_WEP_KEYLEN;
   2760 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
   2761 			error = wi_write_rid(sc, WI_RID_P2_CRYPT_KEY0 + i,
   2762 			    ic->ic_nw_keys[i].wk_key, keylen);
   2763 			if (error)
   2764 				break;
   2765 		}
   2766 		break;
   2767 	}
   2768 	if ((ifp->if_flags & IFF_RUNNING) != 0)
   2769 		wi_cmd(sc, WI_CMD_ENABLE | sc->sc_portnum, 0, 0, 0);
   2770 	if (error == 0)
   2771 		sc->sc_flags |= WI_FLAGS_WEP_VALID;
   2772 	return error;
   2773 }
   2774 
   2775 /* Must be called at proper protection level! */
   2776 STATIC int
   2777 wi_cmd_start(struct wi_softc *sc, int cmd, int val0, int val1, int val2)
   2778 {
   2779 #ifdef WI_HISTOGRAM
   2780 	static int hist1[11];
   2781 	static int hist1count;
   2782 #endif
   2783 	int i;
   2784 
   2785 	/* wait for the busy bit to clear */
   2786 	for (i = 500; i > 0; i--) {	/* 5s */
   2787 		if ((CSR_READ_2(sc, WI_COMMAND) & WI_CMD_BUSY) == 0)
   2788 			break;
   2789 		if (sc->sc_invalid)
   2790 			return ENXIO;
   2791 		DELAY(1000);	/* 1 m sec */
   2792 	}
   2793 	if (i == 0) {
   2794 		aprint_error_dev(sc->sc_dev, "wi_cmd: busy bit won't clear.\n");
   2795 		return (ETIMEDOUT);
   2796   	}
   2797 #ifdef WI_HISTOGRAM
   2798 	if (i > 490)
   2799 		hist1[500 - i]++;
   2800 	else
   2801 		hist1[10]++;
   2802 	if (++hist1count == 1000) {
   2803 		hist1count = 0;
   2804 		printf("%s: hist1: %d %d %d %d %d %d %d %d %d %d %d\n",
   2805 		    device_xname(sc->sc_dev),
   2806 		    hist1[0], hist1[1], hist1[2], hist1[3], hist1[4],
   2807 		    hist1[5], hist1[6], hist1[7], hist1[8], hist1[9],
   2808 		    hist1[10]);
   2809 	}
   2810 #endif
   2811 	CSR_WRITE_2(sc, WI_PARAM0, val0);
   2812 	CSR_WRITE_2(sc, WI_PARAM1, val1);
   2813 	CSR_WRITE_2(sc, WI_PARAM2, val2);
   2814 	CSR_WRITE_2(sc, WI_COMMAND, cmd);
   2815 
   2816 	return 0;
   2817 }
   2818 
   2819 STATIC int
   2820 wi_cmd(struct wi_softc *sc, int cmd, int val0, int val1, int val2)
   2821 {
   2822 	int rc;
   2823 
   2824 #ifdef WI_DEBUG
   2825 	if (wi_debug) {
   2826 		printf("%s: [enter] %d txcmds outstanding\n", __func__,
   2827 		    sc->sc_txcmds);
   2828 	}
   2829 #endif
   2830 	if (sc->sc_txcmds > 0)
   2831 		wi_txcmd_wait(sc);
   2832 
   2833 	if ((rc = wi_cmd_start(sc, cmd, val0, val1, val2)) != 0)
   2834 		return rc;
   2835 
   2836 	if (cmd == WI_CMD_INI) {
   2837 		/* XXX: should sleep here. */
   2838 		if (sc->sc_invalid)
   2839 			return ENXIO;
   2840 		DELAY(100*1000);
   2841 	}
   2842 	rc = wi_cmd_wait(sc, cmd, val0);
   2843 
   2844 #ifdef WI_DEBUG
   2845 	if (wi_debug) {
   2846 		printf("%s: [     ] %d txcmds outstanding\n", __func__,
   2847 		    sc->sc_txcmds);
   2848 	}
   2849 #endif
   2850 	if (sc->sc_txcmds > 0)
   2851 		wi_cmd_intr(sc);
   2852 
   2853 #ifdef WI_DEBUG
   2854 	if (wi_debug) {
   2855 		printf("%s: [leave] %d txcmds outstanding\n", __func__,
   2856 		    sc->sc_txcmds);
   2857 	}
   2858 #endif
   2859 	return rc;
   2860 }
   2861 
   2862 STATIC int
   2863 wi_cmd_wait(struct wi_softc *sc, int cmd, int val0)
   2864 {
   2865 #ifdef WI_HISTOGRAM
   2866 	static int hist2[11];
   2867 	static int hist2count;
   2868 #endif
   2869 	int i, status;
   2870 #ifdef WI_DEBUG
   2871 	if (wi_debug > 1)
   2872 		printf("%s: cmd=%#x, arg=%#x\n", __func__, cmd, val0);
   2873 #endif /* WI_DEBUG */
   2874 
   2875 	/* wait for the cmd completed bit */
   2876 	for (i = 0; i < WI_TIMEOUT; i++) {
   2877 		if (CSR_READ_2(sc, WI_EVENT_STAT) & WI_EV_CMD)
   2878 			break;
   2879 		if (sc->sc_invalid)
   2880 			return ENXIO;
   2881 		DELAY(WI_DELAY);
   2882 	}
   2883 
   2884 #ifdef WI_HISTOGRAM
   2885 	if (i < 100)
   2886 		hist2[i/10]++;
   2887 	else
   2888 		hist2[10]++;
   2889 	if (++hist2count == 1000) {
   2890 		hist2count = 0;
   2891 		printf("%s: hist2: %d %d %d %d %d %d %d %d %d %d %d\n",
   2892 		    device_xname(sc->sc_dev),
   2893 		    hist2[0], hist2[1], hist2[2], hist2[3], hist2[4],
   2894 		    hist2[5], hist2[6], hist2[7], hist2[8], hist2[9],
   2895 		    hist2[10]);
   2896 	}
   2897 #endif
   2898 
   2899 	status = CSR_READ_2(sc, WI_STATUS);
   2900 
   2901 	if (i == WI_TIMEOUT) {
   2902 		aprint_error_dev(sc->sc_dev,
   2903 		    "command timed out, cmd=0x%x, arg=0x%x\n",
   2904 		    cmd, val0);
   2905 		return ETIMEDOUT;
   2906 	}
   2907 
   2908 	CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_CMD);
   2909 
   2910 	if (status & WI_STAT_CMD_RESULT) {
   2911 		aprint_error_dev(sc->sc_dev,
   2912 		    "command failed, cmd=0x%x, arg=0x%x\n",
   2913 		    cmd, val0);
   2914 		return EIO;
   2915 	}
   2916 	return 0;
   2917 }
   2918 
   2919 STATIC int
   2920 wi_seek_bap(struct wi_softc *sc, int id, int off)
   2921 {
   2922 #ifdef WI_HISTOGRAM
   2923 	static int hist4[11];
   2924 	static int hist4count;
   2925 #endif
   2926 	int i, status;
   2927 
   2928 	CSR_WRITE_2(sc, WI_SEL0, id);
   2929 	CSR_WRITE_2(sc, WI_OFF0, off);
   2930 
   2931 	for (i = 0; ; i++) {
   2932 		status = CSR_READ_2(sc, WI_OFF0);
   2933 		if ((status & WI_OFF_BUSY) == 0)
   2934 			break;
   2935 		if (i == WI_TIMEOUT) {
   2936 			aprint_error_dev(sc->sc_dev,
   2937 			    "timeout in wi_seek to %x/%x\n",
   2938 			    id, off);
   2939 			sc->sc_bap_off = WI_OFF_ERR;	/* invalidate */
   2940 			return ETIMEDOUT;
   2941 		}
   2942 		if (sc->sc_invalid)
   2943 			return ENXIO;
   2944 		DELAY(2);
   2945 	}
   2946 #ifdef WI_HISTOGRAM
   2947 	if (i < 100)
   2948 		hist4[i/10]++;
   2949 	else
   2950 		hist4[10]++;
   2951 	if (++hist4count == 2500) {
   2952 		hist4count = 0;
   2953 		printf("%s: hist4: %d %d %d %d %d %d %d %d %d %d %d\n",
   2954 		    device_xname(sc->sc_dev),
   2955 		    hist4[0], hist4[1], hist4[2], hist4[3], hist4[4],
   2956 		    hist4[5], hist4[6], hist4[7], hist4[8], hist4[9],
   2957 		    hist4[10]);
   2958 	}
   2959 #endif
   2960 	if (status & WI_OFF_ERR) {
   2961 		printf("%s: failed in wi_seek to %x/%x\n",
   2962 		    device_xname(sc->sc_dev), id, off);
   2963 		sc->sc_bap_off = WI_OFF_ERR;	/* invalidate */
   2964 		return EIO;
   2965 	}
   2966 	sc->sc_bap_id = id;
   2967 	sc->sc_bap_off = off;
   2968 	return 0;
   2969 }
   2970 
   2971 STATIC int
   2972 wi_read_bap(struct wi_softc *sc, int id, int off, void *buf, int buflen)
   2973 {
   2974 	int error, cnt;
   2975 
   2976 	if (buflen == 0)
   2977 		return 0;
   2978 	if (id != sc->sc_bap_id || off != sc->sc_bap_off) {
   2979 		if ((error = wi_seek_bap(sc, id, off)) != 0)
   2980 			return error;
   2981 	}
   2982 	cnt = (buflen + 1) / 2;
   2983 	CSR_READ_MULTI_STREAM_2(sc, WI_DATA0, (uint16_t *)buf, cnt);
   2984 	sc->sc_bap_off += cnt * 2;
   2985 	return 0;
   2986 }
   2987 
   2988 STATIC int
   2989 wi_write_bap(struct wi_softc *sc, int id, int off, void *buf, int buflen)
   2990 {
   2991 	int error, cnt;
   2992 
   2993 	if (buflen == 0)
   2994 		return 0;
   2995 
   2996 #ifdef WI_HERMES_AUTOINC_WAR
   2997   again:
   2998 #endif
   2999 	if (id != sc->sc_bap_id || off != sc->sc_bap_off) {
   3000 		if ((error = wi_seek_bap(sc, id, off)) != 0)
   3001 			return error;
   3002 	}
   3003 	cnt = (buflen + 1) / 2;
   3004 	CSR_WRITE_MULTI_STREAM_2(sc, WI_DATA0, (uint16_t *)buf, cnt);
   3005 	sc->sc_bap_off += cnt * 2;
   3006 
   3007 #ifdef WI_HERMES_AUTOINC_WAR
   3008 	/*
   3009 	 * According to the comments in the HCF Light code, there is a bug
   3010 	 * in the Hermes (or possibly in certain Hermes firmware revisions)
   3011 	 * where the chip's internal autoincrement counter gets thrown off
   3012 	 * during data writes:  the autoincrement is missed, causing one
   3013 	 * data word to be overwritten and subsequent words to be written to
   3014 	 * the wrong memory locations. The end result is that we could end
   3015 	 * up transmitting bogus frames without realizing it. The workaround
   3016 	 * for this is to write a couple of extra guard words after the end
   3017 	 * of the transfer, then attempt to read then back. If we fail to
   3018 	 * locate the guard words where we expect them, we preform the
   3019 	 * transfer over again.
   3020 	 */
   3021 	if ((sc->sc_flags & WI_FLAGS_BUG_AUTOINC) && (id & 0xf000) == 0) {
   3022 		CSR_WRITE_2(sc, WI_DATA0, 0x1234);
   3023 		CSR_WRITE_2(sc, WI_DATA0, 0x5678);
   3024 		wi_seek_bap(sc, id, sc->sc_bap_off);
   3025 		sc->sc_bap_off = WI_OFF_ERR;	/* invalidate */
   3026 		if (CSR_READ_2(sc, WI_DATA0) != 0x1234 ||
   3027 		    CSR_READ_2(sc, WI_DATA0) != 0x5678) {
   3028 			aprint_error_dev(sc->sc_dev,
   3029 			    "detect auto increment bug, try again\n");
   3030 			goto again;
   3031 		}
   3032 	}
   3033 #endif
   3034 	return 0;
   3035 }
   3036 
   3037 STATIC int
   3038 wi_mwrite_bap(struct wi_softc *sc, int id, int off, struct mbuf *m0, int totlen)
   3039 {
   3040 	int error, len;
   3041 	struct mbuf *m;
   3042 
   3043 	for (m = m0; m != NULL && totlen > 0; m = m->m_next) {
   3044 		if (m->m_len == 0)
   3045 			continue;
   3046 
   3047 		len = uimin(m->m_len, totlen);
   3048 
   3049 		if (((u_long)m->m_data) % 2 != 0 || len % 2 != 0) {
   3050 			m_copydata(m, 0, totlen, (void *)&sc->sc_txbuf);
   3051 			return wi_write_bap(sc, id, off, (void *)&sc->sc_txbuf,
   3052 			    totlen);
   3053 		}
   3054 
   3055 		if ((error = wi_write_bap(sc, id, off, m->m_data, len)) != 0)
   3056 			return error;
   3057 
   3058 		off += m->m_len;
   3059 		totlen -= len;
   3060 	}
   3061 	return 0;
   3062 }
   3063 
   3064 STATIC int
   3065 wi_alloc_fid(struct wi_softc *sc, int len, int *idp)
   3066 {
   3067 	int i;
   3068 
   3069 	if (wi_cmd(sc, WI_CMD_ALLOC_MEM, len, 0, 0)) {
   3070 		aprint_error_dev(sc->sc_dev, "failed to allocate %d bytes on NIC\n", len);
   3071 		return ENOMEM;
   3072 	}
   3073 
   3074 	for (i = 0; i < WI_TIMEOUT; i++) {
   3075 		if (CSR_READ_2(sc, WI_EVENT_STAT) & WI_EV_ALLOC)
   3076 			break;
   3077 		DELAY(1);
   3078 	}
   3079 	if (i == WI_TIMEOUT) {
   3080 		aprint_error_dev(sc->sc_dev, "timeout in alloc\n");
   3081 		return ETIMEDOUT;
   3082 	}
   3083 	*idp = CSR_READ_2(sc, WI_ALLOC_FID);
   3084 	CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_ALLOC);
   3085 	return 0;
   3086 }
   3087 
   3088 STATIC int
   3089 wi_read_rid(struct wi_softc *sc, int rid, void *buf, int *buflenp)
   3090 {
   3091 	int error, len;
   3092 	uint16_t ltbuf[2];
   3093 
   3094 	/* Tell the NIC to enter record read mode. */
   3095 	error = wi_cmd(sc, WI_CMD_ACCESS | WI_ACCESS_READ, rid, 0, 0);
   3096 	if (error)
   3097 		return error;
   3098 
   3099 	error = wi_read_bap(sc, rid, 0, ltbuf, sizeof(ltbuf));
   3100 	if (error)
   3101 		return error;
   3102 
   3103 	if (le16toh(ltbuf[0]) == 0)
   3104 		return EOPNOTSUPP;
   3105 	if (le16toh(ltbuf[1]) != rid) {
   3106 		aprint_error_dev(sc->sc_dev,
   3107 		    "record read mismatch, rid=%x, got=%x\n",
   3108 		    rid, le16toh(ltbuf[1]));
   3109 		return EIO;
   3110 	}
   3111 	len = (le16toh(ltbuf[0]) - 1) * 2;	 /* already got rid */
   3112 	if (*buflenp < len) {
   3113 		aprint_error_dev(sc->sc_dev, "record buffer is too small, "
   3114 		    "rid=%x, size=%d, len=%d\n",
   3115 		    rid, *buflenp, len);
   3116 		return ENOSPC;
   3117 	}
   3118 	*buflenp = len;
   3119 	return wi_read_bap(sc, rid, sizeof(ltbuf), buf, len);
   3120 }
   3121 
   3122 STATIC int
   3123 wi_write_rid(struct wi_softc *sc, int rid, void *buf, int buflen)
   3124 {
   3125 	int error;
   3126 	uint16_t ltbuf[2];
   3127 
   3128 	ltbuf[0] = htole16((buflen + 1) / 2 + 1);	 /* includes rid */
   3129 	ltbuf[1] = htole16(rid);
   3130 
   3131 	error = wi_write_bap(sc, rid, 0, ltbuf, sizeof(ltbuf));
   3132 	if (error)
   3133 		return error;
   3134 	error = wi_write_bap(sc, rid, sizeof(ltbuf), buf, buflen);
   3135 	if (error)
   3136 		return error;
   3137 
   3138 	return wi_cmd(sc, WI_CMD_ACCESS | WI_ACCESS_WRITE, rid, 0, 0);
   3139 }
   3140 
   3141 STATIC void
   3142 wi_rssadapt_updatestats_cb(void *arg, struct ieee80211_node *ni)
   3143 {
   3144 	struct wi_node *wn = (void*)ni;
   3145 	ieee80211_rssadapt_updatestats(&wn->wn_rssadapt);
   3146 }
   3147 
   3148 STATIC void
   3149 wi_rssadapt_updatestats(void *arg)
   3150 {
   3151 	struct wi_softc *sc = arg;
   3152 	struct ieee80211com *ic = &sc->sc_ic;
   3153 	int s;
   3154 
   3155 	s = splnet();
   3156 	ieee80211_iterate_nodes(&ic->ic_sta, wi_rssadapt_updatestats_cb, arg);
   3157 	if (ic->ic_opmode != IEEE80211_M_MONITOR &&
   3158 	    ic->ic_state == IEEE80211_S_RUN)
   3159 		callout_reset(&sc->sc_rssadapt_ch, hz / 10,
   3160 		    wi_rssadapt_updatestats, arg);
   3161 	splx(s);
   3162 }
   3163 
   3164 /*
   3165  * In HOSTAP mode, restore IEEE80211_F_DROPUNENC when operating
   3166  * with WEP enabled so that the AP drops unencoded frames at the
   3167  * 802.11 layer.
   3168  *
   3169  * In all other modes, clear IEEE80211_F_DROPUNENC when operating
   3170  * with WEP enabled so we don't drop unencoded frames at the 802.11
   3171  * layer.  This is necessary because we must strip the WEP bit from
   3172  * the 802.11 header before passing frames to ieee80211_input
   3173  * because the card has already stripped the WEP crypto header from
   3174  * the packet.
   3175  */
   3176 STATIC void
   3177 wi_mend_flags(struct wi_softc *sc, enum ieee80211_state nstate)
   3178 {
   3179 	struct ieee80211com *ic = &sc->sc_ic;
   3180 
   3181 	if (nstate == IEEE80211_S_RUN &&
   3182 	    (ic->ic_flags & IEEE80211_F_PRIVACY) != 0 &&
   3183 	    ic->ic_opmode != IEEE80211_M_HOSTAP)
   3184 		ic->ic_flags &= ~IEEE80211_F_DROPUNENC;
   3185 	else
   3186 		ic->ic_flags |= sc->sc_ic_flags;
   3187 
   3188 	DPRINTF(("%s: state %d, "
   3189 	    "ic->ic_flags & IEEE80211_F_DROPUNENC = %#" PRIx32 ", "
   3190 	    "sc->sc_ic_flags & IEEE80211_F_DROPUNENC = %#" PRIx32 "\n",
   3191 	    __func__, nstate,
   3192 	    ic->ic_flags & IEEE80211_F_DROPUNENC,
   3193 	    sc->sc_ic_flags & IEEE80211_F_DROPUNENC));
   3194 }
   3195 
   3196 STATIC int
   3197 wi_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
   3198 {
   3199 	struct ifnet *ifp = ic->ic_ifp;
   3200 	struct wi_softc *sc = ifp->if_softc;
   3201 	struct ieee80211_node *ni = ic->ic_bss;
   3202 	uint16_t val;
   3203 	struct wi_ssid ssid;
   3204 	struct wi_macaddr bssid, old_bssid;
   3205 	enum ieee80211_state ostate __unused;
   3206 #ifdef WI_DEBUG
   3207 	static const char *stname[] =
   3208 	    { "INIT", "SCAN", "AUTH", "ASSOC", "RUN" };
   3209 #endif /* WI_DEBUG */
   3210 
   3211 	ostate = ic->ic_state;
   3212 	DPRINTF(("wi_newstate: %s -> %s\n", stname[ostate], stname[nstate]));
   3213 
   3214 	switch (nstate) {
   3215 	case IEEE80211_S_INIT:
   3216 		if (ic->ic_opmode != IEEE80211_M_MONITOR)
   3217 			callout_stop(&sc->sc_rssadapt_ch);
   3218 		ic->ic_flags &= ~IEEE80211_F_SIBSS;
   3219 		sc->sc_flags &= ~WI_FLAGS_OUTRANGE;
   3220 		break;
   3221 
   3222 	case IEEE80211_S_SCAN:
   3223 	case IEEE80211_S_AUTH:
   3224 	case IEEE80211_S_ASSOC:
   3225 		ic->ic_state = nstate; /* NB: skip normal ieee80211 handling */
   3226 		wi_mend_flags(sc, nstate);
   3227 		return 0;
   3228 
   3229 	case IEEE80211_S_RUN:
   3230 		sc->sc_flags &= ~WI_FLAGS_OUTRANGE;
   3231 		IEEE80211_ADDR_COPY(old_bssid.wi_mac_addr, ni->ni_bssid);
   3232 		wi_read_xrid(sc, WI_RID_CURRENT_BSSID, &bssid,
   3233 		    IEEE80211_ADDR_LEN);
   3234 		IEEE80211_ADDR_COPY(ni->ni_bssid, &bssid);
   3235 		IEEE80211_ADDR_COPY(ni->ni_macaddr, &bssid);
   3236 		wi_read_xrid(sc, WI_RID_CURRENT_CHAN, &val, sizeof(val));
   3237 		if (!isset(ic->ic_chan_avail, le16toh(val)))
   3238 			panic("%s: invalid channel %d\n",
   3239 			    device_xname(sc->sc_dev), le16toh(val));
   3240 		ni->ni_chan = &ic->ic_channels[le16toh(val)];
   3241 
   3242 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
   3243 #ifndef	IEEE80211_NO_HOSTAP
   3244 			ni->ni_esslen = ic->ic_des_esslen;
   3245 			memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
   3246 			ni->ni_rates = ic->ic_sup_rates[
   3247 			    ieee80211_chan2mode(ic, ni->ni_chan)];
   3248 			ni->ni_intval = ic->ic_lintval;
   3249 			ni->ni_capinfo = IEEE80211_CAPINFO_ESS;
   3250 			if (ic->ic_flags & IEEE80211_F_PRIVACY)
   3251 				ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
   3252 #endif /* !IEEE80211_NO_HOSTAP */
   3253 		} else {
   3254 			wi_read_xrid(sc, WI_RID_CURRENT_SSID, &ssid,
   3255 			    sizeof(ssid));
   3256 			ni->ni_esslen = le16toh(ssid.wi_len);
   3257 			if (ni->ni_esslen > IEEE80211_NWID_LEN)
   3258 				ni->ni_esslen = IEEE80211_NWID_LEN;	/*XXX*/
   3259 			memcpy(ni->ni_essid, ssid.wi_ssid, ni->ni_esslen);
   3260 			ni->ni_rates = ic->ic_sup_rates[
   3261 			    ieee80211_chan2mode(ic, ni->ni_chan)]; /*XXX*/
   3262 		}
   3263 		if (ic->ic_opmode != IEEE80211_M_MONITOR)
   3264 			callout_reset(&sc->sc_rssadapt_ch, hz / 10,
   3265 			    wi_rssadapt_updatestats, sc);
   3266 		/* Trigger routing socket messages. XXX Copied from
   3267 		 * ieee80211_newstate.
   3268 		 */
   3269 		if (ic->ic_opmode == IEEE80211_M_STA)
   3270 			ieee80211_notify_node_join(ic, ic->ic_bss,
   3271 				arg == IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
   3272 		break;
   3273 	}
   3274 	wi_mend_flags(sc, nstate);
   3275 	return (*sc->sc_newstate)(ic, nstate, arg);
   3276 }
   3277 
   3278 STATIC void
   3279 wi_set_tim(struct ieee80211_node *ni, int set)
   3280 {
   3281 	struct ieee80211com *ic = ni->ni_ic;
   3282 	struct wi_softc *sc = ic->ic_ifp->if_softc;
   3283 
   3284 	(*sc->sc_set_tim)(ni, set);
   3285 
   3286 	if ((ic->ic_flags & IEEE80211_F_TIMUPDATE) == 0)
   3287 		return;
   3288 
   3289 	ic->ic_flags &= ~IEEE80211_F_TIMUPDATE;
   3290 
   3291 	(void)wi_write_val(sc, WI_RID_SET_TIM,
   3292 	    IEEE80211_AID(ni->ni_associd) | (set ? 0x8000 : 0));
   3293 }
   3294 
   3295 STATIC int
   3296 wi_scan_ap(struct wi_softc *sc, uint16_t chanmask, uint16_t txrate)
   3297 {
   3298 	int error = 0;
   3299 	uint16_t val[2];
   3300 
   3301 	if (!sc->sc_enabled)
   3302 		return ENXIO;
   3303 	switch (sc->sc_firmware_type) {
   3304 	case WI_LUCENT:
   3305 		(void)wi_cmd(sc, WI_CMD_INQUIRE, WI_INFO_SCAN_RESULTS, 0, 0);
   3306 		break;
   3307 	case WI_INTERSIL:
   3308 		val[0] = htole16(chanmask);	/* channel */
   3309 		val[1] = htole16(txrate);	/* tx rate */
   3310 		error = wi_write_rid(sc, WI_RID_SCAN_REQ, val, sizeof(val));
   3311 		break;
   3312 	case WI_SYMBOL:
   3313 		/*
   3314 		 * XXX only supported on 3.x ?
   3315 		 */
   3316 		val[0] = htole16(BSCAN_BCAST | BSCAN_ONETIME);
   3317 		error = wi_write_rid(sc, WI_RID_BCAST_SCAN_REQ,
   3318 		    val, sizeof(val[0]));
   3319 		break;
   3320 	}
   3321 	if (error == 0) {
   3322 		sc->sc_scan_timer = WI_SCAN_WAIT;
   3323 		sc->sc_if.if_timer = 1;
   3324 		DPRINTF(("wi_scan_ap: start scanning, "
   3325 			"chanmask 0x%x txrate 0x%x\n", chanmask, txrate));
   3326 	}
   3327 	return error;
   3328 }
   3329 
   3330 STATIC void
   3331 wi_scan_result(struct wi_softc *sc, int fid, int cnt)
   3332 {
   3333 #define	N(a)	(sizeof (a) / sizeof (a[0]))
   3334 	int i, naps, off, szbuf;
   3335 	struct wi_scan_header ws_hdr;	/* Prism2 header */
   3336 	struct wi_scan_data_p2 ws_dat;	/* Prism2 scantable*/
   3337 	struct wi_apinfo *ap;
   3338 
   3339 	off = sizeof(uint16_t) * 2;
   3340 	memset(&ws_hdr, 0, sizeof(ws_hdr));
   3341 	switch (sc->sc_firmware_type) {
   3342 	case WI_INTERSIL:
   3343 		wi_read_bap(sc, fid, off, &ws_hdr, sizeof(ws_hdr));
   3344 		off += sizeof(ws_hdr);
   3345 		szbuf = sizeof(struct wi_scan_data_p2);
   3346 		break;
   3347 	case WI_SYMBOL:
   3348 		szbuf = sizeof(struct wi_scan_data_p2) + 6;
   3349 		break;
   3350 	case WI_LUCENT:
   3351 		szbuf = sizeof(struct wi_scan_data);
   3352 		break;
   3353 	default:
   3354 		aprint_error_dev(sc->sc_dev,
   3355 		    "wi_scan_result: unknown firmware type %u\n",
   3356 		    sc->sc_firmware_type);
   3357 		naps = 0;
   3358 		goto done;
   3359 	}
   3360 	naps = (cnt * 2 + 2 - off) / szbuf;
   3361 	if (naps > N(sc->sc_aps))
   3362 		naps = N(sc->sc_aps);
   3363 	sc->sc_naps = naps;
   3364 	/* Read Data */
   3365 	ap = sc->sc_aps;
   3366 	memset(&ws_dat, 0, sizeof(ws_dat));
   3367 	for (i = 0; i < naps; i++, ap++) {
   3368 		wi_read_bap(sc, fid, off, &ws_dat,
   3369 		    (sizeof(ws_dat) < szbuf ? sizeof(ws_dat) : szbuf));
   3370 		DPRINTF2(("wi_scan_result: #%d: off %d bssid %s\n", i, off,
   3371 		    ether_sprintf(ws_dat.wi_bssid)));
   3372 		off += szbuf;
   3373 		ap->scanreason = le16toh(ws_hdr.wi_reason);
   3374 		memcpy(ap->bssid, ws_dat.wi_bssid, sizeof(ap->bssid));
   3375 		ap->channel = le16toh(ws_dat.wi_chid);
   3376 		ap->signal  = le16toh(ws_dat.wi_signal);
   3377 		ap->noise   = le16toh(ws_dat.wi_noise);
   3378 		ap->quality = ap->signal - ap->noise;
   3379 		ap->capinfo = le16toh(ws_dat.wi_capinfo);
   3380 		ap->interval = le16toh(ws_dat.wi_interval);
   3381 		ap->rate    = le16toh(ws_dat.wi_rate);
   3382 		ap->namelen = le16toh(ws_dat.wi_namelen);
   3383 		if (ap->namelen > sizeof(ap->name))
   3384 			ap->namelen = sizeof(ap->name);
   3385 		memcpy(ap->name, ws_dat.wi_name, ap->namelen);
   3386 	}
   3387 done:
   3388 	/* Done scanning */
   3389 	sc->sc_scan_timer = 0;
   3390 	DPRINTF(("wi_scan_result: scan complete: ap %d\n", naps));
   3391 #undef N
   3392 }
   3393 
   3394 STATIC void
   3395 wi_dump_pkt(struct wi_frame *wh, struct ieee80211_node *ni, int rssi)
   3396 {
   3397 	ieee80211_dump_pkt((uint8_t *) &wh->wi_whdr, sizeof(wh->wi_whdr),
   3398 	    ni	? ni->ni_rates.rs_rates[ni->ni_txrate] & IEEE80211_RATE_VAL
   3399 		: -1,
   3400 	    rssi);
   3401 	printf(" status 0x%x rx_tstamp1 %#x rx_tstamp0 %#x rx_silence %u\n",
   3402 		le16toh(wh->wi_status), le16toh(wh->wi_rx_tstamp1),
   3403 		le16toh(wh->wi_rx_tstamp0), wh->wi_rx_silence);
   3404 	printf(" rx_signal %u rx_rate %u rx_flow %u\n",
   3405 		wh->wi_rx_signal, wh->wi_rx_rate, wh->wi_rx_flow);
   3406 	printf(" tx_rtry %u tx_rate %u tx_ctl 0x%x dat_len %u\n",
   3407 		wh->wi_tx_rtry, wh->wi_tx_rate,
   3408 		le16toh(wh->wi_tx_ctl), le16toh(wh->wi_dat_len));
   3409 	printf(" ehdr dst %s src %s type 0x%x\n",
   3410 		ether_sprintf(wh->wi_ehdr.ether_dhost),
   3411 		ether_sprintf(wh->wi_ehdr.ether_shost),
   3412 		wh->wi_ehdr.ether_type);
   3413 }
   3414