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