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