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