xref: /dragonfly/sys/dev/netif/wi/if_wi.c (revision 2b3f93ea)
1 /*-
2  * Copyright (c) 1997, 1998, 1999
3  *	Bill Paul <wpaul@ctr.columbia.edu>.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by Bill Paul.
16  * 4. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
30  * THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * $FreeBSD: head/sys/dev/wi/if_wi.c 299083 2016-05-04 18:08:38Z avos $
33  */
34 
35 /*
36  * Lucent WaveLAN/IEEE 802.11 PCMCIA driver.
37  *
38  * Original FreeBSD driver written by Bill Paul <wpaul@ctr.columbia.edu>
39  * Electrical Engineering Department
40  * Columbia University, New York City
41  */
42 
43 /*
44  * The WaveLAN/IEEE adapter is the second generation of the WaveLAN
45  * from Lucent. Unlike the older cards, the new ones are programmed
46  * entirely via a firmware-driven controller called the Hermes.
47  * Unfortunately, Lucent will not release the Hermes programming manual
48  * without an NDA (if at all). What they do release is an API library
49  * called the HCF (Hardware Control Functions) which is supposed to
50  * do the device-specific operations of a device driver for you. The
51  * publicly available version of the HCF library (the 'HCF Light') is
52  * a) extremely gross, b) lacks certain features, particularly support
53  * for 802.11 frames, and c) is contaminated by the GNU Public License.
54  *
55  * This driver does not use the HCF or HCF Light at all. Instead, it
56  * programs the Hermes controller directly, using information gleaned
57  * from the HCF Light code and corresponding documentation.
58  *
59  * This driver supports the ISA, PCMCIA and PCI versions of the Lucent
60  * WaveLan cards (based on the Hermes chipset), as well as the newer
61  * Prism 2 chipsets with firmware from Intersil and Symbol.
62  */
63 
64 #include "opt_wlan.h"
65 
66 #define WI_HERMES_STATS_WAR	/* Work around stats counter bug. */
67 
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/endian.h>
71 #include <sys/sockio.h>
72 #include <sys/mbuf.h>
73 #include <sys/caps.h>
74 #include <sys/proc.h>
75 #include <sys/kernel.h>
76 #include <sys/malloc.h>
77 #include <sys/socket.h>
78 #include <sys/module.h>
79 #include <sys/bus.h>
80 #include <sys/random.h>
81 #include <sys/syslog.h>
82 #include <sys/sysctl.h>
83 
84 #if !defined(__DragonFly__)
85 #include <machine/bus.h>
86 #include <machine/resource.h>
87 #endif
88 #include <machine/atomic.h>
89 #include <sys/rman.h>
90 
91 #include <net/if.h>
92 #include <net/if_var.h>
93 #include <net/if_arp.h>
94 #include <net/ethernet.h>
95 #include <net/if_dl.h>
96 #include <net/if_llc.h>
97 #include <net/if_media.h>
98 #include <net/if_types.h>
99 
100 #if defined(__DragonFly__)
101 #include <netproto/802_11/ieee80211_var.h>
102 #include <netproto/802_11/ieee80211_ioctl.h>
103 #include <netproto/802_11/ieee80211_radiotap.h>
104 #else
105 #include <net80211/ieee80211_var.h>
106 #include <net80211/ieee80211_ioctl.h>
107 #include <net80211/ieee80211_radiotap.h>
108 #endif
109 
110 #include <netinet/in.h>
111 #include <netinet/in_systm.h>
112 #include <netinet/in_var.h>
113 #include <netinet/ip.h>
114 #include <netinet/if_ether.h>
115 
116 #include <net/bpf.h>
117 
118 #if defined(__DragonFly__)
119 #include "if_wavelan_ieee.h"
120 #include "if_wireg.h"
121 #include "if_wivar.h"
122 #else
123 #include <dev/wi/if_wavelan_ieee.h>
124 #include <dev/wi/if_wireg.h>
125 #include <dev/wi/if_wivar.h>
126 #endif
127 
128 static struct ieee80211vap *wi_vap_create(struct ieee80211com *,
129 		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
130 		    const uint8_t [IEEE80211_ADDR_LEN],
131 		    const uint8_t [IEEE80211_ADDR_LEN]);
132 static void wi_vap_delete(struct ieee80211vap *vap);
133 static int  wi_transmit(struct ieee80211com *, struct mbuf *);
134 static void wi_start(struct wi_softc *);
135 static int  wi_start_tx(struct wi_softc *, struct wi_frame *, struct mbuf *);
136 static int  wi_raw_xmit(struct ieee80211_node *, struct mbuf *,
137 		const struct ieee80211_bpf_params *);
138 static int  wi_newstate_sta(struct ieee80211vap *, enum ieee80211_state, int);
139 static int  wi_newstate_hostap(struct ieee80211vap *, enum ieee80211_state,
140 		int);
141 static void wi_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
142 		int subtype, const struct ieee80211_rx_stats *rxs,
143 		int rssi, int nf);
144 static int  wi_reset(struct wi_softc *);
145 static void wi_watchdog(void *);
146 static void wi_parent(struct ieee80211com *);
147 static void wi_media_status(struct ifnet *, struct ifmediareq *);
148 static void wi_rx_intr(struct wi_softc *);
149 static void wi_tx_intr(struct wi_softc *);
150 static void wi_tx_ex_intr(struct wi_softc *);
151 
152 static void wi_info_intr(struct wi_softc *);
153 
154 static int  wi_write_txrate(struct wi_softc *, struct ieee80211vap *);
155 static int  wi_write_wep(struct wi_softc *, struct ieee80211vap *);
156 static int  wi_write_multi(struct wi_softc *);
157 static void wi_update_mcast(struct ieee80211com *);
158 static void wi_update_promisc(struct ieee80211com *);
159 static int  wi_alloc_fid(struct wi_softc *, int, int *);
160 static void wi_read_nicid(struct wi_softc *);
161 static int  wi_write_ssid(struct wi_softc *, int, u_int8_t *, int);
162 
163 static int  wi_cmd(struct wi_softc *, int, int, int, int);
164 static int  wi_seek_bap(struct wi_softc *, int, int);
165 static int  wi_read_bap(struct wi_softc *, int, int, void *, int);
166 static int  wi_write_bap(struct wi_softc *, int, int, const void *, int);
167 static int  wi_mwrite_bap(struct wi_softc *, int, int, struct mbuf *, int);
168 static int  wi_read_rid(struct wi_softc *, int, void *, int *);
169 static int  wi_write_rid(struct wi_softc *, int, const void *, int);
170 static int  wi_write_appie(struct wi_softc *, int, const struct ieee80211_appie *);
171 
172 static void wi_scan_start(struct ieee80211com *);
173 static void wi_scan_end(struct ieee80211com *);
174 static void wi_set_channel(struct ieee80211com *);
175 
176 static __inline int
177 wi_write_val(struct wi_softc *sc, int rid, u_int16_t val)
178 {
179 
180 	val = htole16(val);
181 	return wi_write_rid(sc, rid, &val, sizeof(val));
182 }
183 
184 static SYSCTL_NODE(_hw, OID_AUTO, wi, CTLFLAG_RD, 0,
185 	    "Wireless driver parameters");
186 
187 static	struct timeval lasttxerror;	/* time of last tx error msg */
188 static	int curtxeps;			/* current tx error msgs/sec */
189 static	int wi_txerate = 0;		/* tx error rate: max msgs/sec */
190 SYSCTL_INT(_hw_wi, OID_AUTO, txerate, CTLFLAG_RW, &wi_txerate,
191 	    0, "max tx error msgs/sec; 0 to disable msgs");
192 
193 #define	WI_DEBUG
194 #ifdef WI_DEBUG
195 static	int wi_debug = 0;
196 SYSCTL_INT(_hw_wi, OID_AUTO, debug, CTLFLAG_RW, &wi_debug,
197 	    0, "control debugging printfs");
198 #define	DPRINTF(X)	if (wi_debug) kprintf X
199 #else
200 #define	DPRINTF(X)
201 #endif
202 
203 #define WI_INTRS	(WI_EV_RX | WI_EV_ALLOC | WI_EV_INFO)
204 
205 struct wi_card_ident wi_card_ident[] = {
206 	/* CARD_ID			CARD_NAME		FIRM_TYPE */
207 	{ WI_NIC_LUCENT_ID,		WI_NIC_LUCENT_STR,	WI_LUCENT },
208 	{ WI_NIC_SONY_ID,		WI_NIC_SONY_STR,	WI_LUCENT },
209 	{ WI_NIC_LUCENT_EMB_ID,		WI_NIC_LUCENT_EMB_STR,	WI_LUCENT },
210 	{ WI_NIC_EVB2_ID,		WI_NIC_EVB2_STR,	WI_INTERSIL },
211 	{ WI_NIC_HWB3763_ID,		WI_NIC_HWB3763_STR,	WI_INTERSIL },
212 	{ WI_NIC_HWB3163_ID,		WI_NIC_HWB3163_STR,	WI_INTERSIL },
213 	{ WI_NIC_HWB3163B_ID,		WI_NIC_HWB3163B_STR,	WI_INTERSIL },
214 	{ WI_NIC_EVB3_ID,		WI_NIC_EVB3_STR,	WI_INTERSIL },
215 	{ WI_NIC_HWB1153_ID,		WI_NIC_HWB1153_STR,	WI_INTERSIL },
216 	{ WI_NIC_P2_SST_ID,		WI_NIC_P2_SST_STR,	WI_INTERSIL },
217 	{ WI_NIC_EVB2_SST_ID,		WI_NIC_EVB2_SST_STR,	WI_INTERSIL },
218 	{ WI_NIC_3842_EVA_ID,		WI_NIC_3842_EVA_STR,	WI_INTERSIL },
219 	{ WI_NIC_3842_PCMCIA_AMD_ID,	WI_NIC_3842_PCMCIA_STR,	WI_INTERSIL },
220 	{ WI_NIC_3842_PCMCIA_SST_ID,	WI_NIC_3842_PCMCIA_STR,	WI_INTERSIL },
221 	{ WI_NIC_3842_PCMCIA_ATL_ID,	WI_NIC_3842_PCMCIA_STR,	WI_INTERSIL },
222 	{ WI_NIC_3842_PCMCIA_ATS_ID,	WI_NIC_3842_PCMCIA_STR,	WI_INTERSIL },
223 	{ WI_NIC_3842_MINI_AMD_ID,	WI_NIC_3842_MINI_STR,	WI_INTERSIL },
224 	{ WI_NIC_3842_MINI_SST_ID,	WI_NIC_3842_MINI_STR,	WI_INTERSIL },
225 	{ WI_NIC_3842_MINI_ATL_ID,	WI_NIC_3842_MINI_STR,	WI_INTERSIL },
226 	{ WI_NIC_3842_MINI_ATS_ID,	WI_NIC_3842_MINI_STR,	WI_INTERSIL },
227 	{ WI_NIC_3842_PCI_AMD_ID,	WI_NIC_3842_PCI_STR,	WI_INTERSIL },
228 	{ WI_NIC_3842_PCI_SST_ID,	WI_NIC_3842_PCI_STR,	WI_INTERSIL },
229 	{ WI_NIC_3842_PCI_ATS_ID,	WI_NIC_3842_PCI_STR,	WI_INTERSIL },
230 	{ WI_NIC_3842_PCI_ATL_ID,	WI_NIC_3842_PCI_STR,	WI_INTERSIL },
231 	{ WI_NIC_P3_PCMCIA_AMD_ID,	WI_NIC_P3_PCMCIA_STR,	WI_INTERSIL },
232 	{ WI_NIC_P3_PCMCIA_SST_ID,	WI_NIC_P3_PCMCIA_STR,	WI_INTERSIL },
233 	{ WI_NIC_P3_PCMCIA_ATL_ID,	WI_NIC_P3_PCMCIA_STR,	WI_INTERSIL },
234 	{ WI_NIC_P3_PCMCIA_ATS_ID,	WI_NIC_P3_PCMCIA_STR,	WI_INTERSIL },
235 	{ WI_NIC_P3_MINI_AMD_ID,	WI_NIC_P3_MINI_STR,	WI_INTERSIL },
236 	{ WI_NIC_P3_MINI_SST_ID,	WI_NIC_P3_MINI_STR,	WI_INTERSIL },
237 	{ WI_NIC_P3_MINI_ATL_ID,	WI_NIC_P3_MINI_STR,	WI_INTERSIL },
238 	{ WI_NIC_P3_MINI_ATS_ID,	WI_NIC_P3_MINI_STR,	WI_INTERSIL },
239 	{ 0,	NULL,	0 },
240 };
241 
242 static char *wi_firmware_names[] = { "none", "Hermes", "Intersil", "Symbol" };
243 
244 devclass_t wi_devclass;
245 
246 int
247 wi_attach(device_t dev)
248 {
249 	struct wi_softc	*sc = device_get_softc(dev);
250 	struct ieee80211com *ic = &sc->sc_ic;
251 	int i, nrates, buflen;
252 	u_int16_t val;
253 	u_int8_t ratebuf[2 + IEEE80211_RATE_SIZE];
254 	struct ieee80211_rateset *rs;
255 	struct sysctl_ctx_list *sctx;
256 	struct sysctl_oid *soid;
257 	static const u_int8_t empty_macaddr[IEEE80211_ADDR_LEN] = {
258 		0x00, 0x00, 0x00, 0x00, 0x00, 0x00
259 	};
260 	int error;
261 
262 	sc->sc_firmware_type = WI_NOTYPE;
263 	sc->wi_cmd_count = 500;
264 	/* Reset the NIC. */
265 	if (wi_reset(sc) != 0) {
266 		wi_free(dev);
267 		return ENXIO;		/* XXX */
268 	}
269 
270 	/* Read NIC identification */
271 	wi_read_nicid(sc);
272 	switch (sc->sc_firmware_type) {
273 	case WI_LUCENT:
274 		if (sc->sc_sta_firmware_ver < 60006)
275 			goto reject;
276 		break;
277 	case WI_INTERSIL:
278 		if (sc->sc_sta_firmware_ver < 800)
279 			goto reject;
280 		break;
281 	default:
282 	reject:
283 		device_printf(dev, "Sorry, this card is not supported "
284 		    "(type %d, firmware ver %d)\n",
285 		    sc->sc_firmware_type, sc->sc_sta_firmware_ver);
286 		wi_free(dev);
287 		return EOPNOTSUPP;
288 	}
289 
290 	/* Export info about the device via sysctl */
291 	sctx = device_get_sysctl_ctx(dev);
292 	soid = device_get_sysctl_tree(dev);
293 	SYSCTL_ADD_STRING(sctx, SYSCTL_CHILDREN(soid), OID_AUTO,
294 	    "firmware_type", CTLFLAG_RD,
295 	    wi_firmware_names[sc->sc_firmware_type], 0,
296 	    "Firmware type string");
297 	SYSCTL_ADD_INT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "sta_version",
298 	    CTLFLAG_RD, &sc->sc_sta_firmware_ver, 0,
299 	    "Station Firmware version");
300 	if (sc->sc_firmware_type == WI_INTERSIL)
301 		SYSCTL_ADD_INT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO,
302 		    "pri_version", CTLFLAG_RD, &sc->sc_pri_firmware_ver, 0,
303 		    "Primary Firmware version");
304 	SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "nic_id",
305 	    CTLFLAG_RD, &sc->sc_nic_id, 0, "NIC id");
306 	SYSCTL_ADD_STRING(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "nic_name",
307 	    CTLFLAG_RD, sc->sc_nic_name, 0, "NIC name");
308 
309 #if defined(__DragonFly__)
310 	lockinit(&sc->sc_lk, device_get_nameunit(dev), 0, LK_CANRECURSE);
311 	callout_init_lk(&sc->sc_watchdog, &sc->sc_lk);
312 #else
313 	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
314 	    MTX_DEF | MTX_RECURSE);
315 	callout_init_mtx(&sc->sc_watchdog, &sc->sc_mtx, 0);
316 #endif
317 	mbufq_init(&sc->sc_snd, ifqmaxlen);
318 
319 	/*
320 	 * Read the station address.
321 	 * And do it twice. I've seen PRISM-based cards that return
322 	 * an error when trying to read it the first time, which causes
323 	 * the probe to fail.
324 	 */
325 	buflen = IEEE80211_ADDR_LEN;
326 	error = wi_read_rid(sc, WI_RID_MAC_NODE, &ic->ic_macaddr, &buflen);
327 	if (error != 0) {
328 		buflen = IEEE80211_ADDR_LEN;
329 		error = wi_read_rid(sc, WI_RID_MAC_NODE, &ic->ic_macaddr,
330 		    &buflen);
331 	}
332 	if (error || IEEE80211_ADDR_EQ(&ic->ic_macaddr, empty_macaddr)) {
333 		if (error != 0)
334 			device_printf(dev, "mac read failed %d\n", error);
335 		else {
336 			device_printf(dev, "mac read failed (all zeros)\n");
337 			error = ENXIO;
338 		}
339 		wi_free(dev);
340 		return (error);
341 	}
342 
343 	ic->ic_softc = sc;
344 	ic->ic_name = device_get_nameunit(dev);
345 	ic->ic_phytype = IEEE80211_T_DS;
346 	ic->ic_opmode = IEEE80211_M_STA;
347 	ic->ic_caps = IEEE80211_C_STA
348 		    | IEEE80211_C_PMGT
349 		    | IEEE80211_C_MONITOR
350 		    ;
351 
352 	/*
353 	 * Query the card for available channels and setup the
354 	 * channel table.  We assume these are all 11b channels.
355 	 */
356 	buflen = sizeof(val);
357 	if (wi_read_rid(sc, WI_RID_CHANNEL_LIST, &val, &buflen) != 0)
358 		val = htole16(0x1fff);	/* assume 1-13 */
359 	KASSERT(val != 0, ("wi_attach: no available channels listed!"));
360 
361 	val <<= 1;			/* shift for base 1 indices */
362 	for (i = 1; i < 16; i++) {
363 		struct ieee80211_channel *c;
364 
365 		if (!isset((u_int8_t*)&val, i))
366 			continue;
367 		c = &ic->ic_channels[ic->ic_nchans++];
368 		c->ic_freq = ieee80211_ieee2mhz(i, IEEE80211_CHAN_B);
369 		c->ic_flags = IEEE80211_CHAN_B;
370 		c->ic_ieee = i;
371 		/* XXX txpowers? */
372 	}
373 
374 	/*
375 	 * Set flags based on firmware version.
376 	 */
377 	switch (sc->sc_firmware_type) {
378 	case WI_LUCENT:
379 		sc->sc_ntxbuf = 1;
380 		ic->ic_caps |= IEEE80211_C_IBSS;
381 
382 		sc->sc_ibss_port = WI_PORTTYPE_BSS;
383 		sc->sc_monitor_port = WI_PORTTYPE_ADHOC;
384 		sc->sc_min_rssi = WI_LUCENT_MIN_RSSI;
385 		sc->sc_max_rssi = WI_LUCENT_MAX_RSSI;
386 		sc->sc_dbm_offset = WI_LUCENT_DBM_OFFSET;
387 		break;
388 	case WI_INTERSIL:
389 		sc->sc_ntxbuf = WI_NTXBUF;
390 		sc->sc_flags |= WI_FLAGS_HAS_FRAGTHR
391 			     |  WI_FLAGS_HAS_ROAMING;
392 		/*
393 		 * Old firmware are slow, so give peace a chance.
394 		 */
395 		if (sc->sc_sta_firmware_ver < 10000)
396 			sc->wi_cmd_count = 5000;
397 		if (sc->sc_sta_firmware_ver > 10101)
398 			sc->sc_flags |= WI_FLAGS_HAS_DBMADJUST;
399 		ic->ic_caps |= IEEE80211_C_IBSS;
400 		/*
401 		 * version 0.8.3 and newer are the only ones that are known
402 		 * to currently work.  Earlier versions can be made to work,
403 		 * at least according to the Linux driver but we require
404 		 * monitor mode so this is irrelevant.
405 		 */
406 		ic->ic_caps |= IEEE80211_C_HOSTAP;
407 		if (sc->sc_sta_firmware_ver >= 10603)
408 			sc->sc_flags |= WI_FLAGS_HAS_ENHSECURITY;
409 		if (sc->sc_sta_firmware_ver >= 10700) {
410 			/*
411 			 * 1.7.0+ have the necessary support for sta mode WPA.
412 			 */
413 			sc->sc_flags |= WI_FLAGS_HAS_WPASUPPORT;
414 			ic->ic_caps |= IEEE80211_C_WPA;
415 		}
416 
417 		sc->sc_ibss_port = WI_PORTTYPE_IBSS;
418 		sc->sc_monitor_port = WI_PORTTYPE_APSILENT;
419 		sc->sc_min_rssi = WI_PRISM_MIN_RSSI;
420 		sc->sc_max_rssi = WI_PRISM_MAX_RSSI;
421 		sc->sc_dbm_offset = WI_PRISM_DBM_OFFSET;
422 		break;
423 	}
424 
425 	/*
426 	 * Find out if we support WEP on this card.
427 	 */
428 	buflen = sizeof(val);
429 	if (wi_read_rid(sc, WI_RID_WEP_AVAIL, &val, &buflen) == 0 &&
430 	    val != htole16(0))
431 		ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
432 
433 	/* Find supported rates. */
434 	buflen = sizeof(ratebuf);
435 	rs = &ic->ic_sup_rates[IEEE80211_MODE_11B];
436 	if (wi_read_rid(sc, WI_RID_DATA_RATES, ratebuf, &buflen) == 0) {
437 		nrates = le16toh(*(u_int16_t *)ratebuf);
438 		if (nrates > IEEE80211_RATE_MAXSIZE)
439 			nrates = IEEE80211_RATE_MAXSIZE;
440 		rs->rs_nrates = 0;
441 		for (i = 0; i < nrates; i++)
442 			if (ratebuf[2+i])
443 				rs->rs_rates[rs->rs_nrates++] = ratebuf[2+i];
444 	} else {
445 		/* XXX fallback on error? */
446 	}
447 
448 	buflen = sizeof(val);
449 	if ((sc->sc_flags & WI_FLAGS_HAS_DBMADJUST) &&
450 	    wi_read_rid(sc, WI_RID_DBM_ADJUST, &val, &buflen) == 0) {
451 		sc->sc_dbm_offset = le16toh(val);
452 	}
453 
454 	sc->sc_portnum = WI_DEFAULT_PORT;
455 
456 	ieee80211_ifattach(ic);
457 	ic->ic_raw_xmit = wi_raw_xmit;
458 	ic->ic_scan_start = wi_scan_start;
459 	ic->ic_scan_end = wi_scan_end;
460 	ic->ic_set_channel = wi_set_channel;
461 	ic->ic_vap_create = wi_vap_create;
462 	ic->ic_vap_delete = wi_vap_delete;
463 	ic->ic_update_mcast = wi_update_mcast;
464 	ic->ic_update_promisc = wi_update_promisc;
465 	ic->ic_transmit = wi_transmit;
466 	ic->ic_parent = wi_parent;
467 
468 	ieee80211_radiotap_attach(ic,
469 	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
470 		WI_TX_RADIOTAP_PRESENT,
471 	    &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
472 		WI_RX_RADIOTAP_PRESENT);
473 
474 	if (bootverbose)
475 		ieee80211_announce(ic);
476 
477 #if defined(__DragonFly__)
478 	error = bus_setup_intr(dev, sc->irq, INTR_MPSAFE,
479 	    wi_intr, sc, &sc->wi_intrhand, NULL);
480 #else
481 	error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
482 	    NULL, wi_intr, sc, &sc->wi_intrhand);
483 #endif
484 	if (error) {
485 		device_printf(dev, "bus_setup_intr() failed! (%d)\n", error);
486 		ieee80211_ifdetach(ic);
487 		wi_free(dev);
488 		return error;
489 	}
490 
491 	return (0);
492 }
493 
494 int
495 wi_detach(device_t dev)
496 {
497 	struct wi_softc	*sc = device_get_softc(dev);
498 	struct ieee80211com *ic = &sc->sc_ic;
499 
500 	WI_LOCK(sc);
501 
502 	/* check if device was removed */
503 	sc->wi_gone |= !bus_child_present(dev);
504 
505 	wi_stop(sc, 0);
506 	WI_UNLOCK(sc);
507 	ieee80211_ifdetach(ic);
508 
509 	bus_teardown_intr(dev, sc->irq, sc->wi_intrhand);
510 	wi_free(dev);
511 	mbufq_drain(&sc->sc_snd);
512 #if defined(__DragonFly__)
513 	lockuninit(&sc->sc_lk);
514 #else
515 	mtx_destroy(&sc->sc_mtx);
516 #endif
517 	return (0);
518 }
519 
520 static struct ieee80211vap *
521 wi_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
522     enum ieee80211_opmode opmode, int flags,
523     const uint8_t bssid[IEEE80211_ADDR_LEN],
524     const uint8_t mac[IEEE80211_ADDR_LEN])
525 {
526 	struct wi_softc *sc = ic->ic_softc;
527 	struct wi_vap *wvp;
528 	struct ieee80211vap *vap;
529 
530 	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
531 		return NULL;
532 	wvp = kmalloc(sizeof(struct wi_vap), M_80211_VAP, M_WAITOK | M_ZERO);
533 
534 	vap = &wvp->wv_vap;
535 	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid);
536 
537 	vap->iv_max_aid = WI_MAX_AID;
538 
539 	switch (opmode) {
540 	case IEEE80211_M_STA:
541 		sc->sc_porttype = WI_PORTTYPE_BSS;
542 		wvp->wv_newstate = vap->iv_newstate;
543 		vap->iv_newstate = wi_newstate_sta;
544 		/* need to filter mgt frames to avoid confusing state machine */
545 		wvp->wv_recv_mgmt = vap->iv_recv_mgmt;
546 		vap->iv_recv_mgmt = wi_recv_mgmt;
547 		break;
548 	case IEEE80211_M_IBSS:
549 		sc->sc_porttype = sc->sc_ibss_port;
550 		wvp->wv_newstate = vap->iv_newstate;
551 		vap->iv_newstate = wi_newstate_sta;
552 		break;
553 	case IEEE80211_M_AHDEMO:
554 		sc->sc_porttype = WI_PORTTYPE_ADHOC;
555 		break;
556 	case IEEE80211_M_HOSTAP:
557 		sc->sc_porttype = WI_PORTTYPE_HOSTAP;
558 		wvp->wv_newstate = vap->iv_newstate;
559 		vap->iv_newstate = wi_newstate_hostap;
560 		break;
561 	case IEEE80211_M_MONITOR:
562 		sc->sc_porttype = sc->sc_monitor_port;
563 		break;
564 	default:
565 		break;
566 	}
567 
568 	/* complete setup */
569 	ieee80211_vap_attach(vap, ieee80211_media_change, wi_media_status, mac);
570 	ic->ic_opmode = opmode;
571 	return vap;
572 }
573 
574 static void
575 wi_vap_delete(struct ieee80211vap *vap)
576 {
577 	struct wi_vap *wvp = WI_VAP(vap);
578 
579 	ieee80211_vap_detach(vap);
580 	kfree(wvp, M_80211_VAP);
581 }
582 
583 int
584 wi_shutdown(device_t dev)
585 {
586 	struct wi_softc *sc = device_get_softc(dev);
587 
588 	WI_LOCK(sc);
589 	wi_stop(sc, 1);
590 	WI_UNLOCK(sc);
591 	return (0);
592 }
593 
594 void
595 wi_intr(void *arg)
596 {
597 	struct wi_softc *sc = arg;
598 	u_int16_t status;
599 
600 	WI_LOCK(sc);
601 
602 	if (sc->wi_gone || !sc->sc_enabled ||
603 	    (sc->sc_flags & WI_FLAGS_RUNNING) == 0) {
604 		CSR_WRITE_2(sc, WI_INT_EN, 0);
605 		CSR_WRITE_2(sc, WI_EVENT_ACK, 0xFFFF);
606 		WI_UNLOCK(sc);
607 		return;
608 	}
609 
610 	/* Disable interrupts. */
611 	CSR_WRITE_2(sc, WI_INT_EN, 0);
612 
613 	status = CSR_READ_2(sc, WI_EVENT_STAT);
614 	if (status & WI_EV_RX)
615 		wi_rx_intr(sc);
616 	if (status & WI_EV_ALLOC)
617 		wi_tx_intr(sc);
618 	if (status & WI_EV_TX_EXC)
619 		wi_tx_ex_intr(sc);
620 	if (status & WI_EV_INFO)
621 		wi_info_intr(sc);
622 	if (mbufq_first(&sc->sc_snd) != NULL)
623 		wi_start(sc);
624 
625 	/* Re-enable interrupts. */
626 	CSR_WRITE_2(sc, WI_INT_EN, WI_INTRS);
627 
628 	WI_UNLOCK(sc);
629 
630 	return;
631 }
632 
633 static void
634 wi_enable(struct wi_softc *sc)
635 {
636 	/* Enable interrupts */
637 	CSR_WRITE_2(sc, WI_INT_EN, WI_INTRS);
638 
639 	/* enable port */
640 	wi_cmd(sc, WI_CMD_ENABLE | sc->sc_portnum, 0, 0, 0);
641 	sc->sc_enabled = 1;
642 }
643 
644 static int
645 wi_setup_locked(struct wi_softc *sc, int porttype, int mode,
646 	const uint8_t mac[IEEE80211_ADDR_LEN])
647 {
648 	int i;
649 
650 	wi_reset(sc);
651 
652 	wi_write_val(sc, WI_RID_PORTTYPE, porttype);
653 	wi_write_val(sc, WI_RID_CREATE_IBSS, mode);
654 	wi_write_val(sc, WI_RID_MAX_DATALEN, 2304);
655 	/* XXX IEEE80211_BPF_NOACK wants 0 */
656 	wi_write_val(sc, WI_RID_ALT_RETRY_CNT, 2);
657 	if (sc->sc_flags & WI_FLAGS_HAS_ROAMING)
658 		wi_write_val(sc, WI_RID_ROAMING_MODE, 3); /* NB: disabled */
659 
660 	wi_write_rid(sc, WI_RID_MAC_NODE, mac, IEEE80211_ADDR_LEN);
661 
662 	/* Allocate fids for the card */
663 	sc->sc_buflen = IEEE80211_MAX_LEN + sizeof(struct wi_frame);
664 	for (i = 0; i < sc->sc_ntxbuf; i++) {
665 		int error = wi_alloc_fid(sc, sc->sc_buflen,
666 		    &sc->sc_txd[i].d_fid);
667 		if (error) {
668 			device_printf(sc->sc_dev,
669 			    "tx buffer allocation failed (error %u)\n",
670 			    error);
671 			return error;
672 		}
673 		sc->sc_txd[i].d_len = 0;
674 	}
675 	sc->sc_txcur = sc->sc_txnext = 0;
676 
677 	return 0;
678 }
679 
680 void
681 wi_init(struct wi_softc *sc)
682 {
683 	int wasenabled;
684 
685 	WI_LOCK_ASSERT(sc);
686 
687 	wasenabled = sc->sc_enabled;
688 	if (wasenabled)
689 		wi_stop(sc, 1);
690 
691 	if (wi_setup_locked(sc, sc->sc_porttype, 3,
692 	    sc->sc_ic.ic_macaddr) != 0) {
693 		device_printf(sc->sc_dev, "interface not running\n");
694 		wi_stop(sc, 1);
695 		return;
696 	}
697 
698 	sc->sc_flags |= WI_FLAGS_RUNNING;
699 
700 	callout_reset(&sc->sc_watchdog, hz, wi_watchdog, sc);
701 
702 	wi_enable(sc);			/* Enable desired port */
703 }
704 
705 void
706 wi_stop(struct wi_softc *sc, int disable)
707 {
708 
709 	WI_LOCK_ASSERT(sc);
710 
711 	if (sc->sc_enabled && !sc->wi_gone) {
712 		CSR_WRITE_2(sc, WI_INT_EN, 0);
713 		wi_cmd(sc, WI_CMD_DISABLE | sc->sc_portnum, 0, 0, 0);
714 		if (disable)
715 			sc->sc_enabled = 0;
716 	} else if (sc->wi_gone && disable)	/* gone --> not enabled */
717 		sc->sc_enabled = 0;
718 
719 	callout_stop(&sc->sc_watchdog);
720 	sc->sc_tx_timer = 0;
721 	sc->sc_false_syns = 0;
722 
723 	sc->sc_flags &= ~WI_FLAGS_RUNNING;
724 }
725 
726 static void
727 wi_set_channel(struct ieee80211com *ic)
728 {
729 	struct wi_softc *sc = ic->ic_softc;
730 
731 	DPRINTF(("%s: channel %d, %sscanning\n", __func__,
732 	    ieee80211_chan2ieee(ic, ic->ic_curchan),
733 	    ic->ic_flags & IEEE80211_F_SCAN ? "" : "!"));
734 
735 	WI_LOCK(sc);
736 	wi_write_val(sc, WI_RID_OWN_CHNL,
737 	    ieee80211_chan2ieee(ic, ic->ic_curchan));
738 	WI_UNLOCK(sc);
739 }
740 
741 static void
742 wi_scan_start(struct ieee80211com *ic)
743 {
744 	struct wi_softc *sc = ic->ic_softc;
745 	struct ieee80211_scan_state *ss = ic->ic_scan;
746 
747 	DPRINTF(("%s\n", __func__));
748 
749 	WI_LOCK(sc);
750 	/*
751 	 * Switch device to monitor mode.
752 	 */
753 	wi_write_val(sc, WI_RID_PORTTYPE, sc->sc_monitor_port);
754 	if (sc->sc_firmware_type == WI_INTERSIL) {
755 		wi_cmd(sc, WI_CMD_DISABLE | WI_PORT0, 0, 0, 0);
756 		wi_cmd(sc, WI_CMD_ENABLE | WI_PORT0, 0, 0, 0);
757 	}
758 	/* force full dwell time to compensate for firmware overhead */
759 	ss->ss_mindwell = ss->ss_maxdwell = msecs_to_ticks(400);
760 	WI_UNLOCK(sc);
761 
762 }
763 
764 static void
765 wi_scan_end(struct ieee80211com *ic)
766 {
767 	struct wi_softc *sc = ic->ic_softc;
768 
769 	DPRINTF(("%s: restore port type %d\n", __func__, sc->sc_porttype));
770 
771 	WI_LOCK(sc);
772 	wi_write_val(sc, WI_RID_PORTTYPE, sc->sc_porttype);
773 	if (sc->sc_firmware_type == WI_INTERSIL) {
774 		wi_cmd(sc, WI_CMD_DISABLE | WI_PORT0, 0, 0, 0);
775 		wi_cmd(sc, WI_CMD_ENABLE | WI_PORT0, 0, 0, 0);
776 	}
777 	WI_UNLOCK(sc);
778 }
779 
780 static void
781 wi_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
782 	int subtype, const struct ieee80211_rx_stats *rxs, int rssi, int nf)
783 {
784 	struct ieee80211vap *vap = ni->ni_vap;
785 
786 	switch (subtype) {
787 	case IEEE80211_FC0_SUBTYPE_AUTH:
788 	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
789 	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
790 		/* NB: filter frames that trigger state changes */
791 		return;
792 	}
793 	WI_VAP(vap)->wv_recv_mgmt(ni, m, subtype, rxs, rssi, nf);
794 }
795 
796 static int
797 wi_newstate_sta(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
798 {
799 	struct ieee80211com *ic = vap->iv_ic;
800 	struct ieee80211_node *bss;
801 	struct wi_softc *sc = ic->ic_softc;
802 
803 	DPRINTF(("%s: %s -> %s\n", __func__,
804 		ieee80211_state_name[vap->iv_state],
805 		ieee80211_state_name[nstate]));
806 
807 	if (nstate == IEEE80211_S_AUTH) {
808 		WI_LOCK(sc);
809 		wi_setup_locked(sc, WI_PORTTYPE_BSS, 3, vap->iv_myaddr);
810 
811 		if (vap->iv_flags & IEEE80211_F_PMGTON) {
812 			wi_write_val(sc, WI_RID_MAX_SLEEP, ic->ic_lintval);
813 			wi_write_val(sc, WI_RID_PM_ENABLED, 1);
814 		}
815 		wi_write_val(sc, WI_RID_RTS_THRESH, vap->iv_rtsthreshold);
816 		if (sc->sc_flags & WI_FLAGS_HAS_FRAGTHR)
817 			wi_write_val(sc, WI_RID_FRAG_THRESH,
818 			    vap->iv_fragthreshold);
819 		wi_write_txrate(sc, vap);
820 
821 		bss = vap->iv_bss;
822 		wi_write_ssid(sc, WI_RID_DESIRED_SSID, bss->ni_essid, bss->ni_esslen);
823 		wi_write_val(sc, WI_RID_OWN_CHNL,
824 		    ieee80211_chan2ieee(ic, bss->ni_chan));
825 
826 		/* Configure WEP. */
827 		if (ic->ic_cryptocaps & IEEE80211_CRYPTO_WEP)
828 			wi_write_wep(sc, vap);
829 		else
830 			sc->sc_encryption = 0;
831 
832 		if ((sc->sc_flags & WI_FLAGS_HAS_WPASUPPORT) &&
833 		    (vap->iv_flags & IEEE80211_F_WPA)) {
834 			wi_write_val(sc, WI_RID_WPA_HANDLING, 1);
835 			if (vap->iv_appie_wpa != NULL)
836 				wi_write_appie(sc, WI_RID_WPA_DATA,
837 				    vap->iv_appie_wpa);
838 		}
839 
840 		wi_enable(sc);		/* enable port */
841 
842 		/* Lucent firmware does not support the JOIN RID. */
843 		if (sc->sc_firmware_type == WI_INTERSIL) {
844 			struct wi_joinreq join;
845 
846 			memset(&join, 0, sizeof(join));
847 			IEEE80211_ADDR_COPY(&join.wi_bssid, bss->ni_bssid);
848 			join.wi_chan = htole16(
849 			    ieee80211_chan2ieee(ic, bss->ni_chan));
850 			wi_write_rid(sc, WI_RID_JOIN_REQ, &join, sizeof(join));
851 		}
852 		WI_UNLOCK(sc);
853 
854 		/*
855 		 * NB: don't go through 802.11 layer, it'll send auth frame;
856 		 * instead we drive the state machine from the link status
857 		 * notification we get on association.
858 		 */
859 		vap->iv_state = nstate;
860 		return (0);
861 	}
862 	return WI_VAP(vap)->wv_newstate(vap, nstate, arg);
863 }
864 
865 static int
866 wi_newstate_hostap(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
867 {
868 	struct ieee80211com *ic = vap->iv_ic;
869 	struct ieee80211_node *bss;
870 	struct wi_softc *sc = ic->ic_softc;
871 	int error;
872 
873 	DPRINTF(("%s: %s -> %s\n", __func__,
874 		ieee80211_state_name[vap->iv_state],
875 		ieee80211_state_name[nstate]));
876 
877 	error = WI_VAP(vap)->wv_newstate(vap, nstate, arg);
878 	if (error == 0 && nstate == IEEE80211_S_RUN) {
879 		WI_LOCK(sc);
880 		wi_setup_locked(sc, WI_PORTTYPE_HOSTAP, 0, vap->iv_myaddr);
881 
882 		bss = vap->iv_bss;
883 		wi_write_ssid(sc, WI_RID_OWN_SSID,
884 		    bss->ni_essid, bss->ni_esslen);
885 		wi_write_val(sc, WI_RID_OWN_CHNL,
886 		    ieee80211_chan2ieee(ic, bss->ni_chan));
887 		wi_write_val(sc, WI_RID_BASIC_RATE, 0x3);
888 		wi_write_val(sc, WI_RID_SUPPORT_RATE, 0xf);
889 		wi_write_txrate(sc, vap);
890 
891 		wi_write_val(sc, WI_RID_OWN_BEACON_INT, bss->ni_intval);
892 		wi_write_val(sc, WI_RID_DTIM_PERIOD, vap->iv_dtim_period);
893 
894 		wi_write_val(sc, WI_RID_RTS_THRESH, vap->iv_rtsthreshold);
895 		if (sc->sc_flags & WI_FLAGS_HAS_FRAGTHR)
896 			wi_write_val(sc, WI_RID_FRAG_THRESH,
897 			    vap->iv_fragthreshold);
898 
899 		if ((sc->sc_flags & WI_FLAGS_HAS_ENHSECURITY) &&
900 		    (vap->iv_flags & IEEE80211_F_HIDESSID)) {
901 			/*
902 			 * bit 0 means hide SSID in beacons,
903 			 * bit 1 means don't respond to bcast probe req
904 			 */
905 			wi_write_val(sc, WI_RID_ENH_SECURITY, 0x3);
906 		}
907 
908 		if ((sc->sc_flags & WI_FLAGS_HAS_WPASUPPORT) &&
909 		    (vap->iv_flags & IEEE80211_F_WPA) &&
910 		    vap->iv_appie_wpa != NULL)
911 			wi_write_appie(sc, WI_RID_WPA_DATA, vap->iv_appie_wpa);
912 
913 		wi_write_val(sc, WI_RID_PROMISC, 0);
914 
915 		/* Configure WEP. */
916 		if (ic->ic_cryptocaps & IEEE80211_CRYPTO_WEP)
917 			wi_write_wep(sc, vap);
918 		else
919 			sc->sc_encryption = 0;
920 
921 		wi_enable(sc);		/* enable port */
922 		WI_UNLOCK(sc);
923 	}
924 	return error;
925 }
926 
927 static int
928 wi_transmit(struct ieee80211com *ic, struct mbuf *m)
929 {
930 	struct wi_softc *sc = ic->ic_softc;
931 	int error;
932 
933 	WI_LOCK(sc);
934 	if ((sc->sc_flags & WI_FLAGS_RUNNING) == 0) {
935 		WI_UNLOCK(sc);
936 		return (ENXIO);
937 	}
938 	error = mbufq_enqueue(&sc->sc_snd, m);
939 	if (error) {
940 		WI_UNLOCK(sc);
941 		return (error);
942 	}
943 	wi_start(sc);
944 	WI_UNLOCK(sc);
945 	return (0);
946 }
947 
948 static void
949 wi_start(struct wi_softc *sc)
950 {
951 	struct ieee80211_node *ni;
952 	struct ieee80211_frame *wh;
953 	struct mbuf *m0;
954 	struct ieee80211_key *k;
955 	struct wi_frame frmhdr;
956 	const struct llc *llc;
957 	int cur;
958 
959 	WI_LOCK_ASSERT(sc);
960 
961 	if (sc->wi_gone)
962 		return;
963 
964 	memset(&frmhdr, 0, sizeof(frmhdr));
965 	cur = sc->sc_txnext;
966 	while (sc->sc_txd[cur].d_len == 0 &&
967 	    (m0 = mbufq_dequeue(&sc->sc_snd)) != NULL) {
968 		ni = (struct ieee80211_node *) m0->m_pkthdr.rcvif;
969 
970 		/* reconstruct 802.3 header */
971 		wh = mtod(m0, struct ieee80211_frame *);
972 		switch (wh->i_fc[1]) {
973 		case IEEE80211_FC1_DIR_TODS:
974 			IEEE80211_ADDR_COPY(frmhdr.wi_ehdr.ether_shost,
975 			    wh->i_addr2);
976 			IEEE80211_ADDR_COPY(frmhdr.wi_ehdr.ether_dhost,
977 			    wh->i_addr3);
978 			break;
979 		case IEEE80211_FC1_DIR_NODS:
980 			IEEE80211_ADDR_COPY(frmhdr.wi_ehdr.ether_shost,
981 			    wh->i_addr2);
982 			IEEE80211_ADDR_COPY(frmhdr.wi_ehdr.ether_dhost,
983 			    wh->i_addr1);
984 			break;
985 		case IEEE80211_FC1_DIR_FROMDS:
986 			IEEE80211_ADDR_COPY(frmhdr.wi_ehdr.ether_shost,
987 			    wh->i_addr3);
988 			IEEE80211_ADDR_COPY(frmhdr.wi_ehdr.ether_dhost,
989 			    wh->i_addr1);
990 			break;
991 		}
992 		llc = (const struct llc *)(
993 		    mtod(m0, const uint8_t *) + ieee80211_hdrsize(wh));
994 		frmhdr.wi_ehdr.ether_type = llc->llc_snap.ether_type;
995 		frmhdr.wi_tx_ctl = htole16(WI_ENC_TX_802_11|WI_TXCNTL_TX_EX);
996 		if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
997 			k = ieee80211_crypto_encap(ni, m0);
998 			if (k == NULL) {
999 				ieee80211_free_node(ni);
1000 				m_freem(m0);
1001 				continue;
1002 			}
1003 			frmhdr.wi_tx_ctl |= htole16(WI_TXCNTL_NOCRYPT);
1004 		}
1005 
1006 		if (ieee80211_radiotap_active_vap(ni->ni_vap)) {
1007 			sc->sc_tx_th.wt_rate = ni->ni_txrate;
1008 			ieee80211_radiotap_tx(ni->ni_vap, m0);
1009 		}
1010 
1011 		m_copydata(m0, 0, sizeof(struct ieee80211_frame),
1012 		    (caddr_t)&frmhdr.wi_whdr);
1013 		m_adj(m0, sizeof(struct ieee80211_frame));
1014 		frmhdr.wi_dat_len = htole16(m0->m_pkthdr.len);
1015 		ieee80211_free_node(ni);
1016 		if (wi_start_tx(sc, &frmhdr, m0))
1017 			continue;
1018 
1019 		sc->sc_txnext = cur = (cur + 1) % sc->sc_ntxbuf;
1020 	}
1021 }
1022 
1023 static int
1024 wi_start_tx(struct wi_softc *sc, struct wi_frame *frmhdr, struct mbuf *m0)
1025 {
1026 	int cur = sc->sc_txnext;
1027 	int fid, off, error;
1028 
1029 	fid = sc->sc_txd[cur].d_fid;
1030 	off = sizeof(*frmhdr);
1031 	error = wi_write_bap(sc, fid, 0, frmhdr, sizeof(*frmhdr)) != 0
1032 	     || wi_mwrite_bap(sc, fid, off, m0, m0->m_pkthdr.len) != 0;
1033 	m_freem(m0);
1034 	if (error) {
1035 #if defined(__DragonFly__)
1036 		++sc->sc_ic.ic_oerrors;
1037 #else
1038 		counter_u64_add(sc->sc_ic.ic_oerrors, 1);
1039 #endif
1040 		return -1;
1041 	}
1042 	sc->sc_txd[cur].d_len = off;
1043 	if (sc->sc_txcur == cur) {
1044 		if (wi_cmd(sc, WI_CMD_TX | WI_RECLAIM, fid, 0, 0)) {
1045 			device_printf(sc->sc_dev, "xmit failed\n");
1046 			sc->sc_txd[cur].d_len = 0;
1047 			return -1;
1048 		}
1049 		sc->sc_tx_timer = 5;
1050 	}
1051 	return 0;
1052 }
1053 
1054 static int
1055 wi_raw_xmit(struct ieee80211_node *ni, struct mbuf *m0,
1056 	    const struct ieee80211_bpf_params *params)
1057 {
1058 	struct ieee80211com *ic = ni->ni_ic;
1059 	struct ieee80211vap *vap = ni->ni_vap;
1060 	struct wi_softc	*sc = ic->ic_softc;
1061 	struct ieee80211_key *k;
1062 	struct ieee80211_frame *wh;
1063 	struct wi_frame frmhdr;
1064 	int cur;
1065 	int rc = 0;
1066 
1067 	WI_LOCK(sc);
1068 
1069 	if (sc->wi_gone) {
1070 		rc = ENETDOWN;
1071 		goto out;
1072 	}
1073 	memset(&frmhdr, 0, sizeof(frmhdr));
1074 	cur = sc->sc_txnext;
1075 	if (sc->sc_txd[cur].d_len != 0) {
1076 		rc = ENOBUFS;
1077 		goto out;
1078 	}
1079 	m0->m_pkthdr.rcvif = NULL;
1080 
1081 	m_copydata(m0, 4, ETHER_ADDR_LEN * 2,
1082 	    (caddr_t)&frmhdr.wi_ehdr);
1083 	frmhdr.wi_ehdr.ether_type = 0;
1084 	wh = mtod(m0, struct ieee80211_frame *);
1085 
1086 	frmhdr.wi_tx_ctl = htole16(WI_ENC_TX_802_11|WI_TXCNTL_TX_EX);
1087 	if (params && (params->ibp_flags & IEEE80211_BPF_NOACK))
1088 		frmhdr.wi_tx_ctl |= htole16(WI_TXCNTL_ALTRTRY);
1089 	if ((wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
1090 	    (!params || (params->ibp_flags & IEEE80211_BPF_CRYPTO))) {
1091 		k = ieee80211_crypto_encap(ni, m0);
1092 		if (k == NULL) {
1093 			rc = ENOMEM;
1094 			goto out;
1095 		}
1096 		frmhdr.wi_tx_ctl |= htole16(WI_TXCNTL_NOCRYPT);
1097 	}
1098 	if (ieee80211_radiotap_active_vap(vap)) {
1099 		sc->sc_tx_th.wt_rate = ni->ni_txrate;
1100 		ieee80211_radiotap_tx(vap, m0);
1101 	}
1102 	m_copydata(m0, 0, sizeof(struct ieee80211_frame),
1103 	    (caddr_t)&frmhdr.wi_whdr);
1104 	m_adj(m0, sizeof(struct ieee80211_frame));
1105 	frmhdr.wi_dat_len = htole16(m0->m_pkthdr.len);
1106 	if (wi_start_tx(sc, &frmhdr, m0) < 0) {
1107 		m0 = NULL;
1108 		rc = EIO;
1109 		goto out;
1110 	}
1111 	m0 = NULL;
1112 	ieee80211_free_node(ni);
1113 
1114 	sc->sc_txnext = cur = (cur + 1) % sc->sc_ntxbuf;
1115 out:
1116 	WI_UNLOCK(sc);
1117 
1118 	if (m0 != NULL)
1119 		m_freem(m0);
1120 	return rc;
1121 }
1122 
1123 static int
1124 wi_reset(struct wi_softc *sc)
1125 {
1126 #define WI_INIT_TRIES 3
1127 	int i, error = 0;
1128 
1129 	for (i = 0; i < WI_INIT_TRIES; i++) {
1130 		error = wi_cmd(sc, WI_CMD_INI, 0, 0, 0);
1131 		if (error == 0)
1132 			break;
1133 		DELAY(WI_DELAY * 1000);
1134 	}
1135 	sc->sc_reset = 1;
1136 	if (i == WI_INIT_TRIES) {
1137 		device_printf(sc->sc_dev, "reset failed\n");
1138 		return error;
1139 	}
1140 
1141 	CSR_WRITE_2(sc, WI_INT_EN, 0);
1142 	CSR_WRITE_2(sc, WI_EVENT_ACK, 0xFFFF);
1143 
1144 	/* Calibrate timer. */
1145 	wi_write_val(sc, WI_RID_TICK_TIME, 8);
1146 
1147 	return 0;
1148 #undef WI_INIT_TRIES
1149 }
1150 
1151 static void
1152 wi_watchdog(void *arg)
1153 {
1154 	struct wi_softc	*sc = arg;
1155 
1156 	WI_LOCK_ASSERT(sc);
1157 
1158 	if (!sc->sc_enabled)
1159 		return;
1160 
1161 	if (sc->sc_tx_timer && --sc->sc_tx_timer == 0) {
1162 		device_printf(sc->sc_dev, "device timeout\n");
1163 #if defined(__DragonFly__)
1164 		++sc->sc_ic.ic_oerrors;
1165 #else
1166 		counter_u64_add(sc->sc_ic.ic_oerrors, 1);
1167 #endif
1168 		wi_init(sc);
1169 		return;
1170 	}
1171 	callout_reset(&sc->sc_watchdog, hz, wi_watchdog, sc);
1172 }
1173 
1174 static void
1175 wi_parent(struct ieee80211com *ic)
1176 {
1177 	struct wi_softc *sc = ic->ic_softc;
1178 	int startall = 0;
1179 
1180 	WI_LOCK(sc);
1181 	/*
1182 	 * Can't do promisc and hostap at the same time.  If all that's
1183 	 * changing is the promisc flag, try to short-circuit a call to
1184 	 * wi_init() by just setting PROMISC in the hardware.
1185 	 */
1186 	if (ic->ic_nrunning > 0) {
1187 		if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
1188 		    sc->sc_flags & WI_FLAGS_RUNNING) {
1189 			if (ic->ic_promisc > 0 &&
1190 			    (sc->sc_flags & WI_FLAGS_PROMISC) == 0) {
1191 				wi_write_val(sc, WI_RID_PROMISC, 1);
1192 				sc->sc_flags |= WI_FLAGS_PROMISC;
1193 			} else if (ic->ic_promisc == 0 &&
1194 			    (sc->sc_flags & WI_FLAGS_PROMISC) != 0) {
1195 				wi_write_val(sc, WI_RID_PROMISC, 0);
1196 				sc->sc_flags &= ~WI_FLAGS_PROMISC;
1197 			} else {
1198 				wi_init(sc);
1199 				startall = 1;
1200 			}
1201 		} else {
1202 			wi_init(sc);
1203 			startall = 1;
1204 		}
1205 	} else if (sc->sc_flags & WI_FLAGS_RUNNING) {
1206 		wi_stop(sc, 1);
1207 		sc->wi_gone = 0;
1208 	}
1209 	WI_UNLOCK(sc);
1210 	if (startall)
1211 		ieee80211_start_all(ic);
1212 }
1213 
1214 static void
1215 wi_media_status(struct ifnet *ifp, struct ifmediareq *imr)
1216 {
1217 	struct ieee80211vap *vap = ifp->if_softc;
1218 	struct ieee80211com *ic = vap->iv_ic;
1219 	struct wi_softc *sc = ic->ic_softc;
1220 	u_int16_t val;
1221 	int rate, len;
1222 
1223 	len = sizeof(val);
1224 	if (sc->sc_enabled &&
1225 	    wi_read_rid(sc, WI_RID_CUR_TX_RATE, &val, &len) == 0 &&
1226 	    len == sizeof(val)) {
1227 		/* convert to 802.11 rate */
1228 		val = le16toh(val);
1229 		rate = val * 2;
1230 		if (sc->sc_firmware_type == WI_LUCENT) {
1231 			if (rate == 10)
1232 				rate = 11;	/* 5.5Mbps */
1233 		} else {
1234 			if (rate == 4*2)
1235 				rate = 11;	/* 5.5Mbps */
1236 			else if (rate == 8*2)
1237 				rate = 22;	/* 11Mbps */
1238 		}
1239 		vap->iv_bss->ni_txrate = rate;
1240 	}
1241 	ieee80211_media_status(ifp, imr);
1242 }
1243 
1244 static void
1245 wi_sync_bssid(struct wi_softc *sc, u_int8_t new_bssid[IEEE80211_ADDR_LEN])
1246 {
1247 	struct ieee80211com *ic = &sc->sc_ic;
1248 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1249 	struct ieee80211_node *ni = vap->iv_bss;
1250 
1251 	if (IEEE80211_ADDR_EQ(new_bssid, ni->ni_bssid))
1252 		return;
1253 
1254 	DPRINTF(("wi_sync_bssid: bssid %s -> ", ether_sprintf(ni->ni_bssid)));
1255 	DPRINTF(("%s ?\n", ether_sprintf(new_bssid)));
1256 
1257 	/* In promiscuous mode, the BSSID field is not a reliable
1258 	 * indicator of the firmware's BSSID. Damp spurious
1259 	 * change-of-BSSID indications.
1260 	 */
1261 	if (ic->ic_promisc > 0 &&
1262 	    !ppsratecheck(&sc->sc_last_syn, &sc->sc_false_syns,
1263 	                 WI_MAX_FALSE_SYNS))
1264 		return;
1265 
1266 	sc->sc_false_syns = MAX(0, sc->sc_false_syns - 1);
1267 #if 0
1268 	/*
1269 	 * XXX hack; we should create a new node with the new bssid
1270 	 * and replace the existing ic_bss with it but since we don't
1271 	 * process management frames to collect state we cheat by
1272 	 * reusing the existing node as we know wi_newstate will be
1273 	 * called and it will overwrite the node state.
1274 	 */
1275 	ieee80211_sta_join(ic, ieee80211_ref_node(ni));
1276 #endif
1277 }
1278 
1279 static __noinline void
1280 wi_rx_intr(struct wi_softc *sc)
1281 {
1282 	struct ieee80211com *ic = &sc->sc_ic;
1283 	struct wi_frame frmhdr;
1284 	struct mbuf *m;
1285 	struct ieee80211_frame *wh;
1286 	struct ieee80211_node *ni;
1287 	int fid, len, off;
1288 	u_int8_t dir;
1289 	u_int16_t status;
1290 	int8_t rssi, nf;
1291 
1292 	fid = CSR_READ_2(sc, WI_RX_FID);
1293 
1294 	/* First read in the frame header */
1295 	if (wi_read_bap(sc, fid, 0, &frmhdr, sizeof(frmhdr))) {
1296 		CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_RX);
1297 #if defined(__DragonFly__)
1298 		++sc->sc_ic.ic_ierrors;
1299 #else
1300 		counter_u64_add(ic->ic_ierrors, 1);
1301 #endif
1302 		DPRINTF(("wi_rx_intr: read fid %x failed\n", fid));
1303 		return;
1304 	}
1305 
1306 	/*
1307 	 * Drop undecryptable or packets with receive errors here
1308 	 */
1309 	status = le16toh(frmhdr.wi_status);
1310 	if (status & WI_STAT_ERRSTAT) {
1311 		CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_RX);
1312 #if defined(__DragonFly__)
1313 		++sc->sc_ic.ic_ierrors;
1314 #else
1315 		counter_u64_add(ic->ic_ierrors, 1);
1316 #endif
1317 		DPRINTF(("wi_rx_intr: fid %x error status %x\n", fid, status));
1318 		return;
1319 	}
1320 
1321 	len = le16toh(frmhdr.wi_dat_len);
1322 	off = ALIGN(sizeof(struct ieee80211_frame));
1323 
1324 	/*
1325 	 * Sometimes the PRISM2.x returns bogusly large frames. Except
1326 	 * in monitor mode, just throw them away.
1327 	 */
1328 	if (off + len > MCLBYTES) {
1329 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1330 			CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_RX);
1331 #if defined(__DragonFly__)
1332 			++sc->sc_ic.ic_ierrors;
1333 #else
1334 			counter_u64_add(ic->ic_ierrors, 1);
1335 #endif
1336 			DPRINTF(("wi_rx_intr: oversized packet\n"));
1337 			return;
1338 		} else
1339 			len = 0;
1340 	}
1341 
1342 	if (off + len > MHLEN)
1343 		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1344 	else
1345 		m = m_gethdr(M_NOWAIT, MT_DATA);
1346 	if (m == NULL) {
1347 		CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_RX);
1348 #if defined(__DragonFly__)
1349 		++sc->sc_ic.ic_ierrors;
1350 #else
1351 		counter_u64_add(ic->ic_ierrors, 1);
1352 #endif
1353 		DPRINTF(("wi_rx_intr: MGET failed\n"));
1354 		return;
1355 	}
1356 	m->m_data += off - sizeof(struct ieee80211_frame);
1357 	memcpy(m->m_data, &frmhdr.wi_whdr, sizeof(struct ieee80211_frame));
1358 	wi_read_bap(sc, fid, sizeof(frmhdr),
1359 	    m->m_data + sizeof(struct ieee80211_frame), len);
1360 	m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame) + len;
1361 
1362 	CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_RX);
1363 
1364 	rssi = frmhdr.wi_rx_signal;
1365 	nf = frmhdr.wi_rx_silence;
1366 	if (ieee80211_radiotap_active(ic)) {
1367 		struct wi_rx_radiotap_header *tap = &sc->sc_rx_th;
1368 		uint32_t rstamp;
1369 
1370 		rstamp = (le16toh(frmhdr.wi_rx_tstamp0) << 16) |
1371 		    le16toh(frmhdr.wi_rx_tstamp1);
1372 		tap->wr_tsf = htole64((uint64_t)rstamp);
1373 		/* XXX replace divide by table */
1374 		tap->wr_rate = frmhdr.wi_rx_rate / 5;
1375 		tap->wr_flags = 0;
1376 		if (frmhdr.wi_status & WI_STAT_PCF)
1377 			tap->wr_flags |= IEEE80211_RADIOTAP_F_CFP;
1378 		if (m->m_flags & M_WEP)
1379 			tap->wr_flags |= IEEE80211_RADIOTAP_F_WEP;
1380 		tap->wr_antsignal = rssi;
1381 		tap->wr_antnoise = nf;
1382 	}
1383 
1384 	/* synchronize driver's BSSID with firmware's BSSID */
1385 	wh = mtod(m, struct ieee80211_frame *);
1386 	dir = wh->i_fc[1] & IEEE80211_FC1_DIR_MASK;
1387 	if (ic->ic_opmode == IEEE80211_M_IBSS && dir == IEEE80211_FC1_DIR_NODS)
1388 		wi_sync_bssid(sc, wh->i_addr3);
1389 
1390 	WI_UNLOCK(sc);
1391 
1392 	ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *));
1393 	if (ni != NULL) {
1394 		(void) ieee80211_input(ni, m, rssi, nf);
1395 		ieee80211_free_node(ni);
1396 	} else
1397 		(void) ieee80211_input_all(ic, m, rssi, nf);
1398 
1399 	WI_LOCK(sc);
1400 }
1401 
1402 static __noinline void
1403 wi_tx_ex_intr(struct wi_softc *sc)
1404 {
1405 	struct wi_frame frmhdr;
1406 	int fid;
1407 
1408 	fid = CSR_READ_2(sc, WI_TX_CMP_FID);
1409 	/* Read in the frame header */
1410 	if (wi_read_bap(sc, fid, 0, &frmhdr, sizeof(frmhdr)) == 0) {
1411 		u_int16_t status = le16toh(frmhdr.wi_status);
1412 		/*
1413 		 * Spontaneous station disconnects appear as xmit
1414 		 * errors.  Don't announce them and/or count them
1415 		 * as an output error.
1416 		 */
1417 		if ((status & WI_TXSTAT_DISCONNECT) == 0) {
1418 			if (ppsratecheck(&lasttxerror, &curtxeps, wi_txerate)) {
1419 				device_printf(sc->sc_dev, "tx failed");
1420 				if (status & WI_TXSTAT_RET_ERR)
1421 					kprintf(", retry limit exceeded");
1422 				if (status & WI_TXSTAT_AGED_ERR)
1423 					kprintf(", max transmit lifetime exceeded");
1424 				if (status & WI_TXSTAT_DISCONNECT)
1425 					kprintf(", port disconnected");
1426 				if (status & WI_TXSTAT_FORM_ERR) {
1427 #if defined(__DragonFly__)
1428 					kprintf(", invalid format (data len %u src %s)",
1429 						le16toh(frmhdr.wi_dat_len),
1430 						ether_sprintf(frmhdr.wi_ehdr.ether_shost));
1431 #else
1432 					printf(", invalid format (data len %u src %6D)",
1433 						le16toh(frmhdr.wi_dat_len),
1434 						frmhdr.wi_ehdr.ether_shost, ":");
1435 #endif
1436 				}
1437 				if (status & ~0xf)
1438 					kprintf(", status=0x%x", status);
1439 				kprintf("\n");
1440 			}
1441 #if defined(__DragonFly__)
1442 			++sc->sc_ic.ic_oerrors;
1443 #else
1444 			counter_u64_add(sc->sc_ic.ic_oerrors, 1);
1445 #endif
1446 		} else
1447 			DPRINTF(("port disconnected\n"));
1448 	} else
1449 		DPRINTF(("wi_tx_ex_intr: read fid %x failed\n", fid));
1450 	CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_TX_EXC);
1451 }
1452 
1453 static __noinline void
1454 wi_tx_intr(struct wi_softc *sc)
1455 {
1456 	int fid, cur;
1457 
1458 	if (sc->wi_gone)
1459 		return;
1460 
1461 	fid = CSR_READ_2(sc, WI_ALLOC_FID);
1462 	CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_ALLOC);
1463 
1464 	cur = sc->sc_txcur;
1465 	if (sc->sc_txd[cur].d_fid != fid) {
1466 		device_printf(sc->sc_dev, "bad alloc %x != %x, cur %d nxt %d\n",
1467 		    fid, sc->sc_txd[cur].d_fid, cur, sc->sc_txnext);
1468 		return;
1469 	}
1470 	sc->sc_tx_timer = 0;
1471 	sc->sc_txd[cur].d_len = 0;
1472 	sc->sc_txcur = cur = (cur + 1) % sc->sc_ntxbuf;
1473 	if (sc->sc_txd[cur].d_len != 0) {
1474 		if (wi_cmd(sc, WI_CMD_TX | WI_RECLAIM, sc->sc_txd[cur].d_fid,
1475 		    0, 0)) {
1476 			device_printf(sc->sc_dev, "xmit failed\n");
1477 			sc->sc_txd[cur].d_len = 0;
1478 		} else {
1479 			sc->sc_tx_timer = 5;
1480 		}
1481 	}
1482 }
1483 
1484 static __noinline void
1485 wi_info_intr(struct wi_softc *sc)
1486 {
1487 	struct ieee80211com *ic = &sc->sc_ic;
1488 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1489 	int i, fid, len, off;
1490 	u_int16_t ltbuf[2];
1491 	u_int16_t stat;
1492 	u_int32_t *ptr;
1493 
1494 	fid = CSR_READ_2(sc, WI_INFO_FID);
1495 	wi_read_bap(sc, fid, 0, ltbuf, sizeof(ltbuf));
1496 
1497 	switch (le16toh(ltbuf[1])) {
1498 	case WI_INFO_LINK_STAT:
1499 		wi_read_bap(sc, fid, sizeof(ltbuf), &stat, sizeof(stat));
1500 		DPRINTF(("wi_info_intr: LINK_STAT 0x%x\n", le16toh(stat)));
1501 
1502 		if (vap == NULL)
1503 			goto finish;
1504 
1505 		switch (le16toh(stat)) {
1506 		case WI_INFO_LINK_STAT_CONNECTED:
1507 			if (vap->iv_state == IEEE80211_S_RUN &&
1508 			    vap->iv_opmode != IEEE80211_M_IBSS)
1509 				break;
1510 			/* fall thru... */
1511 		case WI_INFO_LINK_STAT_AP_CHG:
1512 			IEEE80211_LOCK(ic);
1513 			vap->iv_bss->ni_associd = 1 | 0xc000;	/* NB: anything will do */
1514 			ieee80211_new_state(vap, IEEE80211_S_RUN, 0);
1515 			IEEE80211_UNLOCK(ic);
1516 			break;
1517 		case WI_INFO_LINK_STAT_AP_INR:
1518 			break;
1519 		case WI_INFO_LINK_STAT_DISCONNECTED:
1520 			/* we dropped off the net; e.g. due to deauth/disassoc */
1521 			IEEE80211_LOCK(ic);
1522 			vap->iv_bss->ni_associd = 0;
1523 			vap->iv_stats.is_rx_deauth++;
1524 			ieee80211_new_state(vap, IEEE80211_S_SCAN, 0);
1525 			IEEE80211_UNLOCK(ic);
1526 			break;
1527 		case WI_INFO_LINK_STAT_AP_OOR:
1528 			/* XXX does this need to be per-vap? */
1529 			ieee80211_beacon_miss(ic);
1530 			break;
1531 		case WI_INFO_LINK_STAT_ASSOC_FAILED:
1532 			if (vap->iv_opmode == IEEE80211_M_STA)
1533 				ieee80211_new_state(vap, IEEE80211_S_SCAN,
1534 				    IEEE80211_SCAN_FAIL_TIMEOUT);
1535 			break;
1536 		}
1537 		break;
1538 	case WI_INFO_COUNTERS:
1539 		/* some card versions have a larger stats structure */
1540 		len = min(le16toh(ltbuf[0]) - 1, sizeof(sc->sc_stats) / 4);
1541 		ptr = (u_int32_t *)&sc->sc_stats;
1542 		off = sizeof(ltbuf);
1543 		for (i = 0; i < len; i++, off += 2, ptr++) {
1544 			wi_read_bap(sc, fid, off, &stat, sizeof(stat));
1545 #ifdef WI_HERMES_STATS_WAR
1546 			if (stat & 0xf000)
1547 				stat = ~stat;
1548 #endif
1549 			*ptr += stat;
1550 		}
1551 		break;
1552 	default:
1553 		DPRINTF(("wi_info_intr: got fid %x type %x len %d\n", fid,
1554 		    le16toh(ltbuf[1]), le16toh(ltbuf[0])));
1555 		break;
1556 	}
1557 finish:
1558 	CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_INFO);
1559 }
1560 
1561 static int
1562 wi_write_multi(struct wi_softc *sc)
1563 {
1564 	struct ieee80211com *ic = &sc->sc_ic;
1565 	struct ieee80211vap *vap;
1566 	struct wi_mcast mlist;
1567 	int n;
1568 
1569 	if (ic->ic_allmulti > 0 || ic->ic_promisc > 0) {
1570 allmulti:
1571 		memset(&mlist, 0, sizeof(mlist));
1572 		return wi_write_rid(sc, WI_RID_MCAST_LIST, &mlist,
1573 		    sizeof(mlist));
1574 	}
1575 
1576 	n = 0;
1577 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1578 		struct ifnet *ifp;
1579 		struct ifmultiaddr *ifma;
1580 
1581 		ifp = vap->iv_ifp;
1582 #if defined(__DragonFly__)
1583 		/* nothing */
1584 #else
1585 		if_maddr_rlock(ifp);
1586 #endif
1587 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1588 			if (ifma->ifma_addr->sa_family != AF_LINK)
1589 				continue;
1590 			if (n >= 16)
1591 				goto allmulti;
1592 			IEEE80211_ADDR_COPY(&mlist.wi_mcast[n],
1593 			    (LLADDR((struct sockaddr_dl *)ifma->ifma_addr)));
1594 			n++;
1595 		}
1596 #if defined(__DragonFly__)
1597 		/* nothing */
1598 #else
1599 		if_maddr_runlock(ifp);
1600 #endif
1601 	}
1602 	return wi_write_rid(sc, WI_RID_MCAST_LIST, &mlist,
1603 	    IEEE80211_ADDR_LEN * n);
1604 }
1605 
1606 static void
1607 wi_update_mcast(struct ieee80211com *ic)
1608 {
1609 
1610 	wi_write_multi(ic->ic_softc);
1611 }
1612 
1613 static void
1614 wi_update_promisc(struct ieee80211com *ic)
1615 {
1616 	struct wi_softc *sc = ic->ic_softc;
1617 
1618 	WI_LOCK(sc);
1619 	/* XXX handle WEP special case handling? */
1620 	wi_write_val(sc, WI_RID_PROMISC,
1621 	    (ic->ic_opmode == IEEE80211_M_MONITOR ||
1622 	     (ic->ic_promisc > 0)));
1623 	WI_UNLOCK(sc);
1624 }
1625 
1626 static void
1627 wi_read_nicid(struct wi_softc *sc)
1628 {
1629 	struct wi_card_ident *id;
1630 	char *p;
1631 	int len;
1632 	u_int16_t ver[4];
1633 
1634 	/* getting chip identity */
1635 	memset(ver, 0, sizeof(ver));
1636 	len = sizeof(ver);
1637 	wi_read_rid(sc, WI_RID_CARD_ID, ver, &len);
1638 
1639 	sc->sc_firmware_type = WI_NOTYPE;
1640 	sc->sc_nic_id = le16toh(ver[0]);
1641 	for (id = wi_card_ident; id->card_name != NULL; id++) {
1642 		if (sc->sc_nic_id == id->card_id) {
1643 			sc->sc_nic_name = id->card_name;
1644 			sc->sc_firmware_type = id->firm_type;
1645 			break;
1646 		}
1647 	}
1648 	if (sc->sc_firmware_type == WI_NOTYPE) {
1649 		if (sc->sc_nic_id & 0x8000) {
1650 			sc->sc_firmware_type = WI_INTERSIL;
1651 			sc->sc_nic_name = "Unknown Prism chip";
1652 		} else {
1653 			sc->sc_firmware_type = WI_LUCENT;
1654 			sc->sc_nic_name = "Unknown Lucent chip";
1655 		}
1656 	}
1657 	if (bootverbose)
1658 		device_printf(sc->sc_dev, "using %s\n", sc->sc_nic_name);
1659 
1660 	/* get primary firmware version (Only Prism chips) */
1661 	if (sc->sc_firmware_type != WI_LUCENT) {
1662 		memset(ver, 0, sizeof(ver));
1663 		len = sizeof(ver);
1664 		wi_read_rid(sc, WI_RID_PRI_IDENTITY, ver, &len);
1665 		sc->sc_pri_firmware_ver = le16toh(ver[2]) * 10000 +
1666 		    le16toh(ver[3]) * 100 + le16toh(ver[1]);
1667 	}
1668 
1669 	/* get station firmware version */
1670 	memset(ver, 0, sizeof(ver));
1671 	len = sizeof(ver);
1672 	wi_read_rid(sc, WI_RID_STA_IDENTITY, ver, &len);
1673 	sc->sc_sta_firmware_ver = le16toh(ver[2]) * 10000 +
1674 	    le16toh(ver[3]) * 100 + le16toh(ver[1]);
1675 	if (sc->sc_firmware_type == WI_INTERSIL &&
1676 	    (sc->sc_sta_firmware_ver == 10102 ||
1677 	     sc->sc_sta_firmware_ver == 20102)) {
1678 		char ident[12];
1679 		memset(ident, 0, sizeof(ident));
1680 		len = sizeof(ident);
1681 		/* value should be the format like "V2.00-11" */
1682 		if (wi_read_rid(sc, WI_RID_SYMBOL_IDENTITY, ident, &len) == 0 &&
1683 		    *(p = (char *)ident) >= 'A' &&
1684 		    p[2] == '.' && p[5] == '-' && p[8] == '\0') {
1685 			sc->sc_firmware_type = WI_SYMBOL;
1686 			sc->sc_sta_firmware_ver = (p[1] - '0') * 10000 +
1687 			    (p[3] - '0') * 1000 + (p[4] - '0') * 100 +
1688 			    (p[6] - '0') * 10 + (p[7] - '0');
1689 		}
1690 	}
1691 	if (bootverbose) {
1692 		device_printf(sc->sc_dev, "%s Firmware: ",
1693 		    wi_firmware_names[sc->sc_firmware_type]);
1694 		if (sc->sc_firmware_type != WI_LUCENT)	/* XXX */
1695 			kprintf("Primary (%u.%u.%u), ",
1696 			    sc->sc_pri_firmware_ver / 10000,
1697 			    (sc->sc_pri_firmware_ver % 10000) / 100,
1698 			    sc->sc_pri_firmware_ver % 100);
1699 		kprintf("Station (%u.%u.%u)\n",
1700 		    sc->sc_sta_firmware_ver / 10000,
1701 		    (sc->sc_sta_firmware_ver % 10000) / 100,
1702 		    sc->sc_sta_firmware_ver % 100);
1703 	}
1704 }
1705 
1706 static int
1707 wi_write_ssid(struct wi_softc *sc, int rid, u_int8_t *buf, int buflen)
1708 {
1709 	struct wi_ssid ssid;
1710 
1711 	if (buflen > IEEE80211_NWID_LEN)
1712 		return ENOBUFS;
1713 	memset(&ssid, 0, sizeof(ssid));
1714 	ssid.wi_len = htole16(buflen);
1715 	memcpy(ssid.wi_ssid, buf, buflen);
1716 	return wi_write_rid(sc, rid, &ssid, sizeof(ssid));
1717 }
1718 
1719 static int
1720 wi_write_txrate(struct wi_softc *sc, struct ieee80211vap *vap)
1721 {
1722 	static const uint16_t lucent_rates[12] = {
1723 	    [ 0] = 3,	/* auto */
1724 	    [ 1] = 1,	/* 1Mb/s */
1725 	    [ 2] = 2,	/* 2Mb/s */
1726 	    [ 5] = 4,	/* 5.5Mb/s */
1727 	    [11] = 5	/* 11Mb/s */
1728 	};
1729 	static const uint16_t intersil_rates[12] = {
1730 	    [ 0] = 0xf,	/* auto */
1731 	    [ 1] = 0,	/* 1Mb/s */
1732 	    [ 2] = 1,	/* 2Mb/s */
1733 	    [ 5] = 2,	/* 5.5Mb/s */
1734 	    [11] = 3,	/* 11Mb/s */
1735 	};
1736 	const uint16_t *rates = sc->sc_firmware_type == WI_LUCENT ?
1737 	    lucent_rates : intersil_rates;
1738 	struct ieee80211com *ic = vap->iv_ic;
1739 	const struct ieee80211_txparam *tp;
1740 
1741 	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_bsschan)];
1742 	return wi_write_val(sc, WI_RID_TX_RATE,
1743 	    (tp->ucastrate == IEEE80211_FIXED_RATE_NONE ?
1744 		rates[0] : rates[tp->ucastrate / 2]));
1745 }
1746 
1747 static int
1748 wi_write_wep(struct wi_softc *sc, struct ieee80211vap *vap)
1749 {
1750 	int error = 0;
1751 	int i, keylen;
1752 	u_int16_t val;
1753 	struct wi_key wkey[IEEE80211_WEP_NKID];
1754 
1755 	switch (sc->sc_firmware_type) {
1756 	case WI_LUCENT:
1757 		val = (vap->iv_flags & IEEE80211_F_PRIVACY) ? 1 : 0;
1758 		error = wi_write_val(sc, WI_RID_ENCRYPTION, val);
1759 		if (error)
1760 			break;
1761 		if ((vap->iv_flags & IEEE80211_F_PRIVACY) == 0)
1762 			break;
1763 		error = wi_write_val(sc, WI_RID_TX_CRYPT_KEY, vap->iv_def_txkey);
1764 		if (error)
1765 			break;
1766 		memset(wkey, 0, sizeof(wkey));
1767 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
1768 			keylen = vap->iv_nw_keys[i].wk_keylen;
1769 			wkey[i].wi_keylen = htole16(keylen);
1770 			memcpy(wkey[i].wi_keydat, vap->iv_nw_keys[i].wk_key,
1771 			    keylen);
1772 		}
1773 		error = wi_write_rid(sc, WI_RID_DEFLT_CRYPT_KEYS,
1774 		    wkey, sizeof(wkey));
1775 		sc->sc_encryption = 0;
1776 		break;
1777 
1778 	case WI_INTERSIL:
1779 		val = HOST_ENCRYPT | HOST_DECRYPT;
1780 		if (vap->iv_flags & IEEE80211_F_PRIVACY) {
1781 			/*
1782 			 * ONLY HWB3163 EVAL-CARD Firmware version
1783 			 * less than 0.8 variant2
1784 			 *
1785 			 *   If promiscuous mode disable, Prism2 chip
1786 			 *  does not work with WEP .
1787 			 * It is under investigation for details.
1788 			 * (ichiro@netbsd.org)
1789 			 */
1790 			if (sc->sc_sta_firmware_ver < 802 ) {
1791 				/* firm ver < 0.8 variant 2 */
1792 				wi_write_val(sc, WI_RID_PROMISC, 1);
1793 			}
1794 			wi_write_val(sc, WI_RID_CNFAUTHMODE,
1795 			    vap->iv_bss->ni_authmode);
1796 			val |= PRIVACY_INVOKED;
1797 		} else {
1798 			wi_write_val(sc, WI_RID_CNFAUTHMODE, IEEE80211_AUTH_OPEN);
1799 		}
1800 		error = wi_write_val(sc, WI_RID_P2_ENCRYPTION, val);
1801 		if (error)
1802 			break;
1803 		sc->sc_encryption = val;
1804 		if ((val & PRIVACY_INVOKED) == 0)
1805 			break;
1806 		error = wi_write_val(sc, WI_RID_P2_TX_CRYPT_KEY, vap->iv_def_txkey);
1807 		break;
1808 	}
1809 	return error;
1810 }
1811 
1812 static int
1813 wi_cmd(struct wi_softc *sc, int cmd, int val0, int val1, int val2)
1814 {
1815 	int i, s = 0;
1816 
1817 	if (sc->wi_gone)
1818 		return (ENODEV);
1819 
1820 	/* wait for the busy bit to clear */
1821 	for (i = sc->wi_cmd_count; i > 0; i--) {	/* 500ms */
1822 		if (!(CSR_READ_2(sc, WI_COMMAND) & WI_CMD_BUSY))
1823 			break;
1824 		DELAY(1*1000);	/* 1ms */
1825 	}
1826 	if (i == 0) {
1827 		device_printf(sc->sc_dev, "%s: busy bit won't clear, cmd 0x%x\n",
1828 		   __func__, cmd);
1829 		sc->wi_gone = 1;
1830 		return(ETIMEDOUT);
1831 	}
1832 
1833 	CSR_WRITE_2(sc, WI_PARAM0, val0);
1834 	CSR_WRITE_2(sc, WI_PARAM1, val1);
1835 	CSR_WRITE_2(sc, WI_PARAM2, val2);
1836 	CSR_WRITE_2(sc, WI_COMMAND, cmd);
1837 
1838 	if (cmd == WI_CMD_INI) {
1839 		/* XXX: should sleep here. */
1840 		DELAY(100*1000);		/* 100ms delay for init */
1841 	}
1842 	for (i = 0; i < WI_TIMEOUT; i++) {
1843 		/*
1844 		 * Wait for 'command complete' bit to be
1845 		 * set in the event status register.
1846 		 */
1847 		s = CSR_READ_2(sc, WI_EVENT_STAT);
1848 		if (s & WI_EV_CMD) {
1849 			/* Ack the event and read result code. */
1850 			s = CSR_READ_2(sc, WI_STATUS);
1851 			CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_CMD);
1852 			if (s & WI_STAT_CMD_RESULT) {
1853 				return(EIO);
1854 			}
1855 			break;
1856 		}
1857 		DELAY(WI_DELAY);
1858 	}
1859 
1860 	if (i == WI_TIMEOUT) {
1861 		device_printf(sc->sc_dev, "%s: timeout on cmd 0x%04x; "
1862 		    "event status 0x%04x\n", __func__, cmd, s);
1863 		if (s == 0xffff)
1864 			sc->wi_gone = 1;
1865 		return(ETIMEDOUT);
1866 	}
1867 	return (0);
1868 }
1869 
1870 static int
1871 wi_seek_bap(struct wi_softc *sc, int id, int off)
1872 {
1873 	int i, status;
1874 
1875 	CSR_WRITE_2(sc, WI_SEL0, id);
1876 	CSR_WRITE_2(sc, WI_OFF0, off);
1877 
1878 	for (i = 0; ; i++) {
1879 		status = CSR_READ_2(sc, WI_OFF0);
1880 		if ((status & WI_OFF_BUSY) == 0)
1881 			break;
1882 		if (i == WI_TIMEOUT) {
1883 			device_printf(sc->sc_dev, "%s: timeout, id %x off %x\n",
1884 			    __func__, id, off);
1885 			sc->sc_bap_off = WI_OFF_ERR;	/* invalidate */
1886 			if (status == 0xffff)
1887 				sc->wi_gone = 1;
1888 			return ETIMEDOUT;
1889 		}
1890 		DELAY(1);
1891 	}
1892 	if (status & WI_OFF_ERR) {
1893 		device_printf(sc->sc_dev, "%s: error, id %x off %x\n",
1894 		    __func__, id, off);
1895 		sc->sc_bap_off = WI_OFF_ERR;	/* invalidate */
1896 		return EIO;
1897 	}
1898 	sc->sc_bap_id = id;
1899 	sc->sc_bap_off = off;
1900 	return 0;
1901 }
1902 
1903 static int
1904 wi_read_bap(struct wi_softc *sc, int id, int off, void *buf, int buflen)
1905 {
1906 	int error, cnt;
1907 
1908 	if (buflen == 0)
1909 		return 0;
1910 	if (id != sc->sc_bap_id || off != sc->sc_bap_off) {
1911 		if ((error = wi_seek_bap(sc, id, off)) != 0)
1912 			return error;
1913 	}
1914 	cnt = (buflen + 1) / 2;
1915 	CSR_READ_MULTI_STREAM_2(sc, WI_DATA0, (u_int16_t *)buf, cnt);
1916 	sc->sc_bap_off += cnt * 2;
1917 	return 0;
1918 }
1919 
1920 static int
1921 wi_write_bap(struct wi_softc *sc, int id, int off, const void *buf, int buflen)
1922 {
1923 	int error, cnt;
1924 
1925 	if (buflen == 0)
1926 		return 0;
1927 
1928 	if (id != sc->sc_bap_id || off != sc->sc_bap_off) {
1929 		if ((error = wi_seek_bap(sc, id, off)) != 0)
1930 			return error;
1931 	}
1932 	cnt = (buflen + 1) / 2;
1933 	CSR_WRITE_MULTI_STREAM_2(sc, WI_DATA0, (const uint16_t *)buf, cnt);
1934 	sc->sc_bap_off += cnt * 2;
1935 
1936 	return 0;
1937 }
1938 
1939 static int
1940 wi_mwrite_bap(struct wi_softc *sc, int id, int off, struct mbuf *m0, int totlen)
1941 {
1942 	int error, len;
1943 	struct mbuf *m;
1944 
1945 	for (m = m0; m != NULL && totlen > 0; m = m->m_next) {
1946 		if (m->m_len == 0)
1947 			continue;
1948 
1949 		len = min(m->m_len, totlen);
1950 
1951 		if (((u_long)m->m_data) % 2 != 0 || len % 2 != 0) {
1952 			m_copydata(m, 0, totlen, (caddr_t)&sc->sc_txbuf);
1953 			return wi_write_bap(sc, id, off, (caddr_t)&sc->sc_txbuf,
1954 			    totlen);
1955 		}
1956 
1957 		if ((error = wi_write_bap(sc, id, off, m->m_data, len)) != 0)
1958 			return error;
1959 
1960 		off += m->m_len;
1961 		totlen -= len;
1962 	}
1963 	return 0;
1964 }
1965 
1966 static int
1967 wi_alloc_fid(struct wi_softc *sc, int len, int *idp)
1968 {
1969 	int i;
1970 
1971 	if (wi_cmd(sc, WI_CMD_ALLOC_MEM, len, 0, 0)) {
1972 		device_printf(sc->sc_dev, "%s: failed to allocate %d bytes on NIC\n",
1973 		    __func__, len);
1974 		return ENOMEM;
1975 	}
1976 
1977 	for (i = 0; i < WI_TIMEOUT; i++) {
1978 		if (CSR_READ_2(sc, WI_EVENT_STAT) & WI_EV_ALLOC)
1979 			break;
1980 		DELAY(1);
1981 	}
1982 	if (i == WI_TIMEOUT) {
1983 		device_printf(sc->sc_dev, "%s: timeout in alloc\n", __func__);
1984 		return ETIMEDOUT;
1985 	}
1986 	*idp = CSR_READ_2(sc, WI_ALLOC_FID);
1987 	CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_ALLOC);
1988 	return 0;
1989 }
1990 
1991 static int
1992 wi_read_rid(struct wi_softc *sc, int rid, void *buf, int *buflenp)
1993 {
1994 	int error, len;
1995 	u_int16_t ltbuf[2];
1996 
1997 	/* Tell the NIC to enter record read mode. */
1998 	error = wi_cmd(sc, WI_CMD_ACCESS | WI_ACCESS_READ, rid, 0, 0);
1999 	if (error)
2000 		return error;
2001 
2002 	error = wi_read_bap(sc, rid, 0, ltbuf, sizeof(ltbuf));
2003 	if (error)
2004 		return error;
2005 
2006 	if (le16toh(ltbuf[1]) != rid) {
2007 		device_printf(sc->sc_dev, "record read mismatch, rid=%x, got=%x\n",
2008 		    rid, le16toh(ltbuf[1]));
2009 		return EIO;
2010 	}
2011 	len = (le16toh(ltbuf[0]) - 1) * 2;	 /* already got rid */
2012 	if (*buflenp < len) {
2013 		device_printf(sc->sc_dev, "record buffer is too small, "
2014 		    "rid=%x, size=%d, len=%d\n",
2015 		    rid, *buflenp, len);
2016 		return ENOSPC;
2017 	}
2018 	*buflenp = len;
2019 	return wi_read_bap(sc, rid, sizeof(ltbuf), buf, len);
2020 }
2021 
2022 static int
2023 wi_write_rid(struct wi_softc *sc, int rid, const void *buf, int buflen)
2024 {
2025 	int error;
2026 	u_int16_t ltbuf[2];
2027 
2028 	ltbuf[0] = htole16((buflen + 1) / 2 + 1);	 /* includes rid */
2029 	ltbuf[1] = htole16(rid);
2030 
2031 	error = wi_write_bap(sc, rid, 0, ltbuf, sizeof(ltbuf));
2032 	if (error) {
2033 		device_printf(sc->sc_dev, "%s: bap0 write failure, rid 0x%x\n",
2034 		    __func__, rid);
2035 		return error;
2036 	}
2037 	error = wi_write_bap(sc, rid, sizeof(ltbuf), buf, buflen);
2038 	if (error) {
2039 		device_printf(sc->sc_dev, "%s: bap1 write failure, rid 0x%x\n",
2040 		    __func__, rid);
2041 		return error;
2042 	}
2043 
2044 	return wi_cmd(sc, WI_CMD_ACCESS | WI_ACCESS_WRITE, rid, 0, 0);
2045 }
2046 
2047 static int
2048 wi_write_appie(struct wi_softc *sc, int rid, const struct ieee80211_appie *ie)
2049 {
2050 	/* NB: 42 bytes is probably ok to have on the stack */
2051 	char buf[sizeof(uint16_t) + 40];
2052 
2053 	if (ie->ie_len > 40)
2054 		return EINVAL;
2055 	/* NB: firmware requires 16-bit ie length before ie data */
2056 	*(uint16_t *) buf = htole16(ie->ie_len);
2057 	memcpy(buf + sizeof(uint16_t), ie->ie_data, ie->ie_len);
2058 	return wi_write_rid(sc, rid, buf, ie->ie_len + sizeof(uint16_t));
2059 }
2060 
2061 int
2062 wi_alloc(device_t dev, int rid)
2063 {
2064 	struct wi_softc	*sc = device_get_softc(dev);
2065 
2066 	if (sc->wi_bus_type != WI_BUS_PCI_NATIVE) {
2067 		sc->iobase_rid = rid;
2068 #if defined(__DragonFly__)
2069 		sc->iobase = bus_alloc_resource(dev, SYS_RES_IOPORT,
2070 		    &sc->iobase_rid, 0, ~0, (1 << 6),
2071 		    rman_make_alignment_flags(1 << 6) | RF_ACTIVE);
2072 #else
2073 		sc->iobase = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT,
2074 		    &sc->iobase_rid, (1 << 6),
2075 		    rman_make_alignment_flags(1 << 6) | RF_ACTIVE);
2076 #endif
2077 		if (sc->iobase == NULL) {
2078 			device_printf(dev, "No I/O space?!\n");
2079 			return ENXIO;
2080 		}
2081 
2082 		sc->wi_io_addr = rman_get_start(sc->iobase);
2083 		sc->wi_btag = rman_get_bustag(sc->iobase);
2084 		sc->wi_bhandle = rman_get_bushandle(sc->iobase);
2085 	} else {
2086 		sc->mem_rid = rid;
2087 		sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
2088 		    &sc->mem_rid, RF_ACTIVE);
2089 		if (sc->mem == NULL) {
2090 			device_printf(dev, "No Mem space on prism2.5?\n");
2091 			return ENXIO;
2092 		}
2093 
2094 		sc->wi_btag = rman_get_bustag(sc->mem);
2095 		sc->wi_bhandle = rman_get_bushandle(sc->mem);
2096 	}
2097 
2098 	sc->irq_rid = 0;
2099 	sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid,
2100 	    RF_ACTIVE |
2101 	    ((sc->wi_bus_type == WI_BUS_PCCARD) ? 0 : RF_SHAREABLE));
2102 	if (sc->irq == NULL) {
2103 		wi_free(dev);
2104 		device_printf(dev, "No irq?!\n");
2105 		return ENXIO;
2106 	}
2107 
2108 	sc->sc_dev = dev;
2109 	sc->sc_unit = device_get_unit(dev);
2110 	return 0;
2111 }
2112 
2113 void
2114 wi_free(device_t dev)
2115 {
2116 	struct wi_softc	*sc = device_get_softc(dev);
2117 
2118 	if (sc->iobase != NULL) {
2119 		bus_release_resource(dev, SYS_RES_IOPORT, sc->iobase_rid, sc->iobase);
2120 		sc->iobase = NULL;
2121 	}
2122 	if (sc->irq != NULL) {
2123 		bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, sc->irq);
2124 		sc->irq = NULL;
2125 	}
2126 	if (sc->mem != NULL) {
2127 		bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem);
2128 		sc->mem = NULL;
2129 	}
2130 }
2131