xref: /netbsd-src/sys/dev/ic/an.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /*	$NetBSD: an.c,v 1.54 2008/11/12 12:36:11 ad Exp $	*/
2 /*
3  * Copyright (c) 1997, 1998, 1999
4  *	Bill Paul <wpaul@ctr.columbia.edu>.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *	This product includes software developed by Bill Paul.
17  * 4. Neither the name of the author nor the names of any co-contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31  * THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  * $FreeBSD: src/sys/dev/an/if_an.c,v 1.12 2000/11/13 23:04:12 wpaul Exp $
34  */
35 /*
36  * Copyright (c) 2004, 2005 David Young.  All rights reserved.
37  * Copyright (c) 2004, 2005 OJC Technologies.  All rights reserved.
38  * Copyright (c) 2004, 2005 Dayton Data Center Services, LLC.  All
39  *     rights reserved.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  * 3. Neither the name of the author nor the names of any co-contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY David Young AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL David Young AND CONTRIBUTORS
57  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
58  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
59  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
60  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
61  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
62  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
63  * THE POSSIBILITY OF SUCH DAMAGE.
64  */
65 
66 /*
67  * Aironet 4500/4800 802.11 PCMCIA/ISA/PCI driver for FreeBSD.
68  *
69  * Written by Bill Paul <wpaul@ctr.columbia.edu>
70  * Electrical Engineering Department
71  * Columbia University, New York City
72  */
73 
74 /*
75  * Ported to NetBSD from FreeBSD by Atsushi Onoe at the San Diego
76  * IETF meeting.
77  */
78 
79 #include <sys/cdefs.h>
80 __KERNEL_RCSID(0, "$NetBSD: an.c,v 1.54 2008/11/12 12:36:11 ad Exp $");
81 
82 #include "bpfilter.h"
83 
84 #include <sys/param.h>
85 #include <sys/callout.h>
86 #include <sys/sysctl.h>
87 #include <sys/systm.h>
88 #include <sys/sockio.h>
89 #include <sys/mbuf.h>
90 #include <sys/kernel.h>
91 #include <sys/ucred.h>
92 #include <sys/socket.h>
93 #include <sys/device.h>
94 #include <sys/proc.h>
95 #include <sys/md4.h>
96 #include <sys/endian.h>
97 #include <sys/kauth.h>
98 
99 #include <sys/bus.h>
100 
101 #include <net/if.h>
102 #include <net/if_dl.h>
103 #include <net/if_ether.h>
104 #include <net/if_llc.h>
105 #include <net/if_media.h>
106 #include <net/if_types.h>
107 
108 #include <net80211/ieee80211_netbsd.h>
109 #include <net80211/ieee80211_var.h>
110 #include <net80211/ieee80211_radiotap.h>
111 
112 #if NBPFILTER > 0
113 #include <net/bpf.h>
114 #include <net/bpfdesc.h>
115 #endif
116 
117 #include <dev/ic/anreg.h>
118 #include <dev/ic/anvar.h>
119 
120 static int	an_reset(struct an_softc *);
121 static void	an_wait(struct an_softc *);
122 static int	an_init(struct ifnet *);
123 static void	an_stop(struct ifnet *, int);
124 static void	an_start(struct ifnet *);
125 static void	an_watchdog(struct ifnet *);
126 static int	an_ioctl(struct ifnet *, u_long, void *);
127 static int	an_media_change(struct ifnet *);
128 static void	an_media_status(struct ifnet *, struct ifmediareq *);
129 
130 static int	an_set_nwkey(struct an_softc *, struct ieee80211_nwkey *);
131 static int	an_set_nwkey_wep(struct an_softc *, struct ieee80211_nwkey *);
132 static int	an_set_nwkey_eap(struct an_softc *, struct ieee80211_nwkey *);
133 static int	an_get_nwkey(struct an_softc *, struct ieee80211_nwkey *);
134 static int	an_write_wepkey(struct an_softc *, int, struct an_wepkey *,
135 				int);
136 
137 static void	an_rx_intr(struct an_softc *);
138 static void	an_tx_intr(struct an_softc *, int);
139 static void	an_linkstat_intr(struct an_softc *);
140 
141 static int	an_cmd(struct an_softc *, int, int);
142 static int	an_seek_bap(struct an_softc *, int, int);
143 static int	an_read_bap(struct an_softc *, int, int, void *, int);
144 static int	an_write_bap(struct an_softc *, int, int, void *, int);
145 static int	an_mwrite_bap(struct an_softc *, int, int, struct mbuf *, int);
146 static int	an_read_rid(struct an_softc *, int, void *, int *);
147 static int	an_write_rid(struct an_softc *, int, void *, int);
148 
149 static int	an_alloc_fid(struct an_softc *, int, int *);
150 
151 static int	an_newstate(struct ieee80211com *, enum ieee80211_state, int);
152 
153 #ifdef AN_DEBUG
154 int an_debug = 0;
155 
156 #define	DPRINTF(X)	if (an_debug) printf X
157 #define	DPRINTF2(X)	if (an_debug > 1) printf X
158 static int an_sysctl_verify(SYSCTLFN_PROTO, int lower, int upper);
159 static int an_sysctl_verify_debug(SYSCTLFN_PROTO);
160 #else
161 #define	DPRINTF(X)
162 #define	DPRINTF2(X)
163 #endif
164 
165 int
166 an_attach(struct an_softc *sc)
167 {
168 	struct ieee80211com *ic = &sc->sc_ic;
169 	struct ifnet *ifp = &sc->sc_if;
170 	int i, s;
171 	struct an_rid_wepkey *akey;
172 	int buflen, kid, rid;
173 	int chan, chan_min, chan_max;
174 
175 	s = splnet();
176 	sc->sc_invalid = 0;
177 
178 	an_wait(sc);
179 	if (an_reset(sc) != 0) {
180 		sc->sc_invalid = 1;
181 		splx(s);
182 		return 1;
183 	}
184 
185 	/* Load factory config */
186 	if (an_cmd(sc, AN_CMD_READCFG, 0) != 0) {
187 		splx(s);
188 		aprint_error_dev(sc->sc_dev, "failed to load config data\n");
189 		return 1;
190 	}
191 
192 	/* Read the current configuration */
193 	buflen = sizeof(sc->sc_config);
194 	if (an_read_rid(sc, AN_RID_GENCONFIG, &sc->sc_config, &buflen) != 0) {
195 		splx(s);
196 		aprint_error_dev(sc->sc_dev, "read config failed\n");
197 		return 1;
198 	}
199 
200 	/* Read the card capabilities */
201 	buflen = sizeof(sc->sc_caps);
202 	if (an_read_rid(sc, AN_RID_CAPABILITIES, &sc->sc_caps, &buflen) != 0) {
203 		splx(s);
204 		aprint_error_dev(sc->sc_dev, "read caps failed\n");
205 		return 1;
206 	}
207 
208 #ifdef AN_DEBUG
209 	if (an_debug) {
210 		static const int dumprid[] = {
211 		    AN_RID_GENCONFIG, AN_RID_CAPABILITIES, AN_RID_SSIDLIST,
212 		    AN_RID_APLIST, AN_RID_STATUS, AN_RID_ENCAP
213 		};
214 
215 		for (rid = 0; rid < sizeof(dumprid)/sizeof(dumprid[0]); rid++) {
216 			buflen = sizeof(sc->sc_buf);
217 			if (an_read_rid(sc, dumprid[rid], &sc->sc_buf, &buflen)
218 			    != 0)
219 				continue;
220 			printf("%04x (%d):\n", dumprid[rid], buflen);
221 			for (i = 0; i < (buflen + 1) / 2; i++)
222 				printf(" %04x", sc->sc_buf.sc_val[i]);
223 			printf("\n");
224 		}
225 	}
226 #endif
227 
228 	/* Read WEP settings from persistent memory */
229 	akey = &sc->sc_buf.sc_wepkey;
230 	buflen = sizeof(struct an_rid_wepkey);
231 	rid = AN_RID_WEP_VOLATILE;	/* first persistent key */
232 	while (an_read_rid(sc, rid, akey, &buflen) == 0) {
233 		kid = le16toh(akey->an_key_index);
234 		DPRINTF(("an_attach: wep rid=0x%x len=%d(%zu) index=0x%04x "
235 		    "mac[0]=%02x keylen=%d\n",
236 		    rid, buflen, sizeof(*akey), kid,
237 		    akey->an_mac_addr[0], le16toh(akey->an_key_len)));
238 		if (kid == 0xffff) {
239 			sc->sc_tx_perskey = akey->an_mac_addr[0];
240 			sc->sc_tx_key = -1;
241 			break;
242 		}
243 		if (kid >= IEEE80211_WEP_NKID)
244 			break;
245 		sc->sc_perskeylen[kid] = le16toh(akey->an_key_len);
246 		sc->sc_wepkeys[kid].an_wep_keylen = -1;
247 		rid = AN_RID_WEP_PERSISTENT;	/* for next key */
248 		buflen = sizeof(struct an_rid_wepkey);
249 	}
250 
251 	aprint_normal_dev(sc->sc_dev, "%s %s (firmware %s)\n",
252 	    sc->sc_caps.an_manufname, sc->sc_caps.an_prodname,
253 	    sc->sc_caps.an_prodvers);
254 
255 	memcpy(ifp->if_xname, device_xname(sc->sc_dev), IFNAMSIZ);
256 
257 	ifp->if_softc = sc;
258 	ifp->if_flags = IFF_BROADCAST | IFF_NOTRAILERS | IFF_SIMPLEX |
259 	    IFF_MULTICAST | IFF_ALLMULTI;
260 	ifp->if_ioctl = an_ioctl;
261 	ifp->if_start = an_start;
262 	ifp->if_init = an_init;
263 	ifp->if_stop = an_stop;
264 	ifp->if_watchdog = an_watchdog;
265 	IFQ_SET_READY(&ifp->if_snd);
266 
267 	ic->ic_ifp = ifp;
268 	ic->ic_phytype = IEEE80211_T_DS;
269 	ic->ic_opmode = IEEE80211_M_STA;
270 	ic->ic_caps = IEEE80211_C_WEP | IEEE80211_C_PMGT | IEEE80211_C_IBSS |
271 	    IEEE80211_C_MONITOR;
272 	ic->ic_state = IEEE80211_S_INIT;
273 	IEEE80211_ADDR_COPY(ic->ic_myaddr, sc->sc_caps.an_oemaddr);
274 
275 	switch (le16toh(sc->sc_caps.an_regdomain)) {
276 	default:
277 	case AN_REGDOMAIN_USA:
278 	case AN_REGDOMAIN_CANADA:
279 		chan_min = 1; chan_max = 11; break;
280 	case AN_REGDOMAIN_EUROPE:
281 	case AN_REGDOMAIN_AUSTRALIA:
282 		chan_min = 1; chan_max = 13; break;
283 	case AN_REGDOMAIN_JAPAN:
284 		chan_min = 14; chan_max = 14; break;
285 	case AN_REGDOMAIN_SPAIN:
286 		chan_min = 10; chan_max = 11; break;
287 	case AN_REGDOMAIN_FRANCE:
288 		chan_min = 10; chan_max = 13; break;
289 	case AN_REGDOMAIN_JAPANWIDE:
290 		chan_min = 1; chan_max = 14; break;
291 	}
292 
293 	for (chan = chan_min; chan <= chan_max; chan++) {
294 		ic->ic_channels[chan].ic_freq =
295 		    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
296 		ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_B;
297 	}
298 	ic->ic_ibss_chan = &ic->ic_channels[chan_min];
299 
300 	aprint_normal("%s: 802.11 address: %s, channel: %d-%d\n",
301 	    ifp->if_xname, ether_sprintf(ic->ic_myaddr), chan_min, chan_max);
302 
303 	/* Find supported rate */
304 	for (i = 0; i < sizeof(sc->sc_caps.an_rates); i++) {
305 		if (sc->sc_caps.an_rates[i] == 0)
306 			continue;
307 		ic->ic_sup_rates[IEEE80211_MODE_11B].rs_rates[
308 		    ic->ic_sup_rates[IEEE80211_MODE_11B].rs_nrates++] =
309 		    sc->sc_caps.an_rates[i];
310 	}
311 
312 	/*
313 	 * Call MI attach routine.
314 	 */
315 	if_attach(ifp);
316 	ieee80211_ifattach(ic);
317 
318 	sc->sc_newstate = ic->ic_newstate;
319 	ic->ic_newstate = an_newstate;
320 
321 	ieee80211_media_init(ic, an_media_change, an_media_status);
322 
323 	/*
324 	 * radiotap BPF device
325 	 */
326 #if NBPFILTER > 0
327 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
328 	    sizeof(struct ieee80211_frame) + 64, &sc->sc_drvbpf);
329 #endif
330 
331 	memset(&sc->sc_rxtapu, 0, sizeof(sc->sc_rxtapu));
332 	sc->sc_rxtap.ar_ihdr.it_len = htole16(sizeof(sc->sc_rxtapu));
333 	sc->sc_rxtap.ar_ihdr.it_present = htole32(AN_RX_RADIOTAP_PRESENT);
334 
335 	memset(&sc->sc_txtapu, 0, sizeof(sc->sc_txtapu));
336 	sc->sc_txtap.at_ihdr.it_len = htole16(sizeof(sc->sc_txtapu));
337 	sc->sc_txtap.at_ihdr.it_present = htole32(AN_TX_RADIOTAP_PRESENT);
338 
339 	sc->sc_attached = 1;
340 	splx(s);
341 
342 	ieee80211_announce(ic);
343 	return 0;
344 }
345 
346 #ifdef AN_DEBUG
347 /*
348  * Setup sysctl(3) MIB, hw.an.*
349  *
350  * TBD condition CTLFLAG_PERMANENT on being a module or not
351  */
352 SYSCTL_SETUP(sysctl_an, "sysctl an(4) subtree setup")
353 {
354 	int rc;
355 	const struct sysctlnode *cnode, *rnode;
356 
357 	if ((rc = sysctl_createv(clog, 0, NULL, &rnode,
358 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "hw", NULL,
359 	    NULL, 0, NULL, 0, CTL_HW, CTL_EOL)) != 0)
360 		goto err;
361 
362 	if ((rc = sysctl_createv(clog, 0, &rnode, &rnode,
363 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "an",
364 	    "Cisco/Aironet 802.11 controls",
365 	    NULL, 0, NULL, 0, CTL_CREATE, CTL_EOL)) != 0)
366 		goto err;
367 
368 	/* control debugging printfs */
369 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
370 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
371 	    "debug", SYSCTL_DESCR("Enable Cisco/Aironet debugging output"),
372 	    an_sysctl_verify_debug, 0, &an_debug, 0,
373 	    CTL_CREATE, CTL_EOL)) != 0)
374 		goto err;
375 
376 	return;
377 err:
378 	printf("%s: sysctl_createv failed (rc = %d)\n", __func__, rc);
379 }
380 
381 static int
382 an_sysctl_verify(SYSCTLFN_ARGS, int lower, int upper)
383 {
384 	int error, t;
385 	struct sysctlnode node;
386 
387 	node = *rnode;
388 	t = *(int*)rnode->sysctl_data;
389 	node.sysctl_data = &t;
390 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
391 	if (error || newp == NULL)
392 		return (error);
393 
394 	if (t < lower || t > upper)
395 		return (EINVAL);
396 
397 	*(int*)rnode->sysctl_data = t;
398 
399 	return (0);
400 }
401 
402 static int
403 an_sysctl_verify_debug(SYSCTLFN_ARGS)
404 {
405 	return an_sysctl_verify(SYSCTLFN_CALL(rnode), 0, 2);
406 }
407 #endif /* AN_DEBUG */
408 
409 int
410 an_detach(struct an_softc *sc)
411 {
412 	struct ieee80211com *ic = &sc->sc_ic;
413 	struct ifnet *ifp = &sc->sc_if;
414 	int s;
415 
416 	if (!sc->sc_attached)
417 		return 0;
418 
419 	s = splnet();
420 	sc->sc_invalid = 1;
421 	an_stop(ifp, 1);
422 	ieee80211_ifdetach(ic);
423 	if_detach(ifp);
424 	splx(s);
425 	return 0;
426 }
427 
428 int
429 an_activate(struct device *self, enum devact act)
430 {
431 	struct an_softc *sc = (struct an_softc *)self;
432 	int s, error = 0;
433 
434 	s = splnet();
435 	switch (act) {
436 	case DVACT_ACTIVATE:
437 		error = EOPNOTSUPP;
438 		break;
439 
440 	case DVACT_DEACTIVATE:
441 		sc->sc_invalid = 1;
442 		if_deactivate(&sc->sc_if);
443 		break;
444 	}
445 	splx(s);
446 
447 	return error;
448 }
449 
450 int
451 an_intr(void *arg)
452 {
453 	struct an_softc *sc = arg;
454 	struct ifnet *ifp = &sc->sc_if;
455 	int i;
456 	u_int16_t status;
457 
458 	if (!sc->sc_enabled || sc->sc_invalid ||
459 	    !device_is_active(sc->sc_dev) ||
460 	    (ifp->if_flags & IFF_RUNNING) == 0)
461 		return 0;
462 
463 	if ((ifp->if_flags & IFF_UP) == 0) {
464 		CSR_WRITE_2(sc, AN_INT_EN, 0);
465 		CSR_WRITE_2(sc, AN_EVENT_ACK, ~0);
466 		return 1;
467 	}
468 
469 	/* maximum 10 loops per interrupt */
470 	for (i = 0; i < 10; i++) {
471 		if (!sc->sc_enabled || sc->sc_invalid)
472 			return 1;
473 		if (CSR_READ_2(sc, AN_SW0) != AN_MAGIC) {
474 			DPRINTF(("an_intr: magic number changed: %x\n",
475 			    CSR_READ_2(sc, AN_SW0)));
476 			sc->sc_invalid = 1;
477 			return 1;
478 		}
479 		status = CSR_READ_2(sc, AN_EVENT_STAT);
480 		CSR_WRITE_2(sc, AN_EVENT_ACK, status & ~(AN_INTRS));
481 		if ((status & AN_INTRS) == 0)
482 			break;
483 
484 		if (status & AN_EV_RX)
485 			an_rx_intr(sc);
486 
487 		if (status & (AN_EV_TX | AN_EV_TX_EXC))
488 			an_tx_intr(sc, status);
489 
490 		if (status & AN_EV_LINKSTAT)
491 			an_linkstat_intr(sc);
492 
493 		if ((ifp->if_flags & IFF_OACTIVE) == 0 &&
494 		    sc->sc_ic.ic_state == IEEE80211_S_RUN &&
495 		    !IFQ_IS_EMPTY(&ifp->if_snd))
496 			an_start(ifp);
497 	}
498 
499 	return 1;
500 }
501 
502 static int
503 an_init(struct ifnet *ifp)
504 {
505 	struct an_softc *sc = ifp->if_softc;
506 	struct ieee80211com *ic = &sc->sc_ic;
507 	int i, error, fid;
508 
509 	DPRINTF(("an_init: enabled %d\n", sc->sc_enabled));
510 	if (!sc->sc_enabled) {
511 		if (sc->sc_enable)
512 			(*sc->sc_enable)(sc);
513 		an_wait(sc);
514 		sc->sc_enabled = 1;
515 	} else {
516 		an_stop(ifp, 0);
517 		if ((error = an_reset(sc)) != 0) {
518 			printf("%s: failed to reset\n", ifp->if_xname);
519 			an_stop(ifp, 1);
520 			return error;
521 		}
522 	}
523 	CSR_WRITE_2(sc, AN_SW0, AN_MAGIC);
524 
525 	/* Allocate the TX buffers */
526 	for (i = 0; i < AN_TX_RING_CNT; i++) {
527 		if ((error = an_alloc_fid(sc, AN_TX_MAX_LEN, &fid)) != 0) {
528 			printf("%s: failed to allocate nic memory\n",
529 			    ifp->if_xname);
530 			an_stop(ifp, 1);
531 			return error;
532 		}
533 		DPRINTF2(("an_init: txbuf %d allocated %x\n", i, fid));
534 		sc->sc_txd[i].d_fid = fid;
535 		sc->sc_txd[i].d_inuse = 0;
536 	}
537 	sc->sc_txcur = sc->sc_txnext = 0;
538 
539 	IEEE80211_ADDR_COPY(sc->sc_config.an_macaddr, ic->ic_myaddr);
540 	sc->sc_config.an_scanmode = htole16(AN_SCANMODE_ACTIVE);
541 	sc->sc_config.an_authtype = htole16(AN_AUTHTYPE_OPEN);	/*XXX*/
542 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
543 		sc->sc_config.an_authtype |=
544 		    htole16(AN_AUTHTYPE_PRIVACY_IN_USE);
545 		if (sc->sc_use_leap)
546 			sc->sc_config.an_authtype |=
547 			    htole16(AN_AUTHTYPE_LEAP);
548 	}
549 	sc->sc_config.an_listen_interval = htole16(ic->ic_lintval);
550 	sc->sc_config.an_beacon_period = htole16(ic->ic_lintval);
551 	if (ic->ic_flags & IEEE80211_F_PMGTON)
552 		sc->sc_config.an_psave_mode = htole16(AN_PSAVE_PSP);
553 	else
554 		sc->sc_config.an_psave_mode = htole16(AN_PSAVE_CAM);
555 	sc->sc_config.an_ds_channel =
556 	    htole16(ieee80211_chan2ieee(ic, ic->ic_ibss_chan));
557 
558 	switch (ic->ic_opmode) {
559 	case IEEE80211_M_STA:
560 		sc->sc_config.an_opmode =
561 		    htole16(AN_OPMODE_INFRASTRUCTURE_STATION);
562 		sc->sc_config.an_rxmode = htole16(AN_RXMODE_BC_MC_ADDR);
563 		break;
564 	case IEEE80211_M_IBSS:
565 		sc->sc_config.an_opmode = htole16(AN_OPMODE_IBSS_ADHOC);
566 		sc->sc_config.an_rxmode = htole16(AN_RXMODE_BC_MC_ADDR);
567 		break;
568 	case IEEE80211_M_MONITOR:
569 		sc->sc_config.an_opmode =
570 		    htole16(AN_OPMODE_INFRASTRUCTURE_STATION);
571 		sc->sc_config.an_rxmode =
572 		    htole16(AN_RXMODE_80211_MONITOR_ANYBSS);
573 		sc->sc_config.an_authtype = htole16(AN_AUTHTYPE_NONE);
574 		if (ic->ic_flags & IEEE80211_F_PRIVACY)
575 			sc->sc_config.an_authtype |=
576 			    htole16(AN_AUTHTYPE_PRIVACY_IN_USE |
577 		            AN_AUTHTYPE_ALLOW_UNENCRYPTED);
578 		break;
579 	default:
580 		printf("%s: bad opmode %d\n", ifp->if_xname, ic->ic_opmode);
581 		an_stop(ifp, 1);
582 		return EIO;
583 	}
584 	sc->sc_config.an_rxmode |= htole16(AN_RXMODE_NO_8023_HEADER);
585 
586 	/* Set the ssid list */
587 	memset(&sc->sc_buf, 0, sizeof(sc->sc_buf.sc_ssidlist));
588 	sc->sc_buf.sc_ssidlist.an_entry[0].an_ssid_len =
589 	    htole16(ic->ic_des_esslen);
590 	if (ic->ic_des_esslen)
591 		memcpy(sc->sc_buf.sc_ssidlist.an_entry[0].an_ssid,
592 		    ic->ic_des_essid, ic->ic_des_esslen);
593 	if (an_write_rid(sc, AN_RID_SSIDLIST, &sc->sc_buf,
594 	    sizeof(sc->sc_buf.sc_ssidlist)) != 0) {
595 		printf("%s: failed to write ssid list\n", ifp->if_xname);
596 		an_stop(ifp, 1);
597 		return error;
598 	}
599 
600 	/* Set the AP list */
601 	memset(&sc->sc_buf, 0, sizeof(sc->sc_buf.sc_aplist));
602 	(void)an_write_rid(sc, AN_RID_APLIST, &sc->sc_buf,
603 	    sizeof(sc->sc_buf.sc_aplist));
604 
605 	/* Set the encapsulation */
606 	for (i = 0; i < AN_ENCAP_NENTS; i++) {
607 		sc->sc_buf.sc_encap.an_entry[i].an_ethertype = htole16(0);
608 		sc->sc_buf.sc_encap.an_entry[i].an_action =
609 		    htole16(AN_RXENCAP_RFC1024 | AN_TXENCAP_RFC1024);
610 	}
611 	(void)an_write_rid(sc, AN_RID_ENCAP, &sc->sc_buf,
612 	    sizeof(sc->sc_buf.sc_encap));
613 
614 	/* Set the WEP Keys */
615 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
616 		an_write_wepkey(sc, AN_RID_WEP_VOLATILE, sc->sc_wepkeys,
617 		    sc->sc_tx_key);
618 
619 	/* Set the configuration */
620 #ifdef AN_DEBUG
621 	if (an_debug) {
622 		printf("write config:\n");
623 		for (i = 0; i < sizeof(sc->sc_config) / 2; i++)
624 			printf(" %04x", ((u_int16_t *)&sc->sc_config)[i]);
625 		printf("\n");
626 	}
627 #endif
628 	if (an_write_rid(sc, AN_RID_GENCONFIG, &sc->sc_config,
629 	    sizeof(sc->sc_config)) != 0) {
630 		printf("%s: failed to write config\n", ifp->if_xname);
631 		an_stop(ifp, 1);
632 		return error;
633 	}
634 
635 	/* Enable the MAC */
636 	if (an_cmd(sc, AN_CMD_ENABLE, 0)) {
637 		aprint_error_dev(sc->sc_dev, "failed to enable MAC\n");
638 		an_stop(ifp, 1);
639 		return ENXIO;
640 	}
641 	if (ifp->if_flags & IFF_PROMISC)
642 		an_cmd(sc, AN_CMD_SET_MODE, 0xffff);
643 
644 	ifp->if_flags |= IFF_RUNNING;
645 	ifp->if_flags &= ~IFF_OACTIVE;
646 	ic->ic_state = IEEE80211_S_INIT;
647 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
648 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
649 
650 	/* enable interrupts */
651 	CSR_WRITE_2(sc, AN_INT_EN, AN_INTRS);
652 	return 0;
653 }
654 
655 static void
656 an_stop(struct ifnet *ifp, int disable)
657 {
658 	struct an_softc *sc = ifp->if_softc;
659 	int i, s;
660 
661 	if (!sc->sc_enabled)
662 		return;
663 
664 	DPRINTF(("an_stop: disable %d\n", disable));
665 
666 	s = splnet();
667 	ieee80211_new_state(&sc->sc_ic, IEEE80211_S_INIT, -1);
668 	if (!sc->sc_invalid) {
669 		an_cmd(sc, AN_CMD_FORCE_SYNCLOSS, 0);
670 		CSR_WRITE_2(sc, AN_INT_EN, 0);
671 		an_cmd(sc, AN_CMD_DISABLE, 0);
672 
673 		for (i = 0; i < AN_TX_RING_CNT; i++)
674 			an_cmd(sc, AN_CMD_DEALLOC_MEM, sc->sc_txd[i].d_fid);
675 	}
676 
677 	sc->sc_tx_timer = 0;
678 	ifp->if_timer = 0;
679 	ifp->if_flags &= ~(IFF_RUNNING|IFF_OACTIVE);
680 
681 	if (disable) {
682 		if (sc->sc_disable)
683 			(*sc->sc_disable)(sc);
684 		sc->sc_enabled = 0;
685 	}
686 	splx(s);
687 }
688 
689 static void
690 an_start(struct ifnet *ifp)
691 {
692 	struct an_softc *sc = (struct an_softc *)ifp->if_softc;
693 	struct ieee80211com *ic = &sc->sc_ic;
694 	struct ieee80211_node *ni;
695 	struct ieee80211_frame *wh;
696 	struct an_txframe frmhdr;
697 	struct ether_header *eh;
698 	struct mbuf *m;
699 	u_int16_t len;
700 	int cur, fid;
701 
702 	if (!sc->sc_enabled || sc->sc_invalid) {
703 		DPRINTF(("an_start: noop: enabled %d invalid %d\n",
704 		    sc->sc_enabled, sc->sc_invalid));
705 		return;
706 	}
707 
708 	memset(&frmhdr, 0, sizeof(frmhdr));
709 	cur = sc->sc_txnext;
710 	for (;;) {
711 		if (ic->ic_state != IEEE80211_S_RUN) {
712 			DPRINTF(("an_start: not running %d\n", ic->ic_state));
713 			break;
714 		}
715 		IFQ_POLL(&ifp->if_snd, m);
716 		if (m == NULL) {
717 			DPRINTF2(("an_start: no pending mbuf\n"));
718 			break;
719 		}
720 		if (sc->sc_txd[cur].d_inuse) {
721 			DPRINTF2(("an_start: %x/%d busy\n",
722 			    sc->sc_txd[cur].d_fid, cur));
723 			ifp->if_flags |= IFF_OACTIVE;
724 			break;
725 		}
726 		IFQ_DEQUEUE(&ifp->if_snd, m);
727 		ifp->if_opackets++;
728 #if NBPFILTER > 0
729 		if (ifp->if_bpf)
730 			bpf_mtap(ifp->if_bpf, m);
731 #endif
732 		eh = mtod(m, struct ether_header *);
733 		ni = ieee80211_find_txnode(ic, eh->ether_dhost);
734 		if (ni == NULL) {
735 			/* NB: ieee80211_find_txnode does stat+msg */
736 			goto bad;
737 		}
738 		if ((m = ieee80211_encap(ic, m, ni)) == NULL)
739 			goto bad;
740 		ieee80211_free_node(ni);
741 #if NBPFILTER > 0
742 		if (ic->ic_rawbpf)
743 			bpf_mtap(ic->ic_rawbpf, m);
744 #endif
745 
746 		wh = mtod(m, struct ieee80211_frame *);
747 		if (ic->ic_flags & IEEE80211_F_PRIVACY)
748 			wh->i_fc[1] |= IEEE80211_FC1_WEP;
749 		m_copydata(m, 0, sizeof(struct ieee80211_frame),
750 		    (void *)&frmhdr.an_whdr);
751 
752 		/* insert payload length in front of llc/snap */
753 		len = htons(m->m_pkthdr.len - sizeof(struct ieee80211_frame));
754 		m_adj(m, sizeof(struct ieee80211_frame) - sizeof(len));
755 		if (mtod(m, u_long) & 0x01)
756 			memcpy(mtod(m, void *), &len, sizeof(len));
757 		else
758 			*mtod(m, u_int16_t *) = len;
759 
760 		/*
761 		 * XXX Aironet firmware apparently convert the packet
762 		 * with longer than 1500 bytes in length into LLC/SNAP.
763 		 * If we have 1500 bytes in ethernet payload, it is
764 		 * 1508 bytes including LLC/SNAP and will be inserted
765 		 * additional LLC/SNAP header with 1501-1508 in its
766 		 * ethertype !!
767 		 * So we skip LLC/SNAP header and force firmware to
768 		 * convert it to LLC/SNAP again.
769 		 */
770 		m_adj(m, sizeof(struct llc));
771 
772 		frmhdr.an_tx_ctl = htole16(AN_TXCTL_80211);
773 		frmhdr.an_tx_payload_len = htole16(m->m_pkthdr.len);
774 		frmhdr.an_gaplen = htole16(AN_TXGAP_802_11);
775 
776 		if (ic->ic_fixed_rate != -1)
777 			frmhdr.an_tx_rate =
778 			    ic->ic_sup_rates[IEEE80211_MODE_11B].rs_rates[
779 			    ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
780 		else
781 			frmhdr.an_tx_rate = 0;
782 
783 		/* XXX radiotap for tx must be completed */
784 #if NBPFILTER > 0
785 		if (sc->sc_drvbpf) {
786 			struct an_tx_radiotap_header *tap = &sc->sc_txtap;
787 			tap->at_rate = ic->ic_bss->ni_rates.rs_rates[ic->ic_bss->ni_txrate];
788 			tap->at_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
789 			tap->at_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
790 			/* TBD tap->wt_flags */
791 			bpf_mtap2(sc->sc_drvbpf, tap, tap->at_ihdr.it_len, m);
792 		}
793 #endif
794 
795 #ifdef AN_DEBUG
796 		if ((ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) ==
797 		    (IFF_DEBUG|IFF_LINK2)) {
798 			ieee80211_dump_pkt((u_int8_t *)&frmhdr.an_whdr,
799 			    sizeof(struct ieee80211_frame), -1, 0);
800 			printf(" txctl 0x%x plen %u\n",
801 			    le16toh(frmhdr.an_tx_ctl),
802 			    le16toh(frmhdr.an_tx_payload_len));
803 		}
804 #endif
805 		if (sizeof(frmhdr) + AN_TXGAP_802_11 + sizeof(len) +
806 		    m->m_pkthdr.len > AN_TX_MAX_LEN)
807 			goto bad;
808 
809 		fid = sc->sc_txd[cur].d_fid;
810 		if (an_write_bap(sc, fid, 0, &frmhdr, sizeof(frmhdr)) != 0)
811 			goto bad;
812 		/* dummy write to avoid seek. */
813 		an_write_bap(sc, fid, -1, &frmhdr, AN_TXGAP_802_11);
814 		an_mwrite_bap(sc, fid, -1, m, m->m_pkthdr.len);
815 		m_freem(m);
816 
817 		DPRINTF2(("an_start: send %zu byte via %x/%d\n",
818 		    ntohs(len) + sizeof(struct ieee80211_frame),
819 		    fid, cur));
820 		sc->sc_txd[cur].d_inuse = 1;
821 		if (an_cmd(sc, AN_CMD_TX, fid)) {
822 			printf("%s: xmit failed\n", ifp->if_xname);
823 			sc->sc_txd[cur].d_inuse = 0;
824 			continue;
825 		}
826 		sc->sc_tx_timer = 5;
827 		ifp->if_timer = 1;
828 		AN_INC(cur, AN_TX_RING_CNT);
829 		sc->sc_txnext = cur;
830 		continue;
831 bad:
832 		ifp->if_oerrors++;
833 		m_freem(m);
834 	}
835 }
836 
837 static int
838 an_reset(struct an_softc *sc)
839 {
840 
841 	DPRINTF(("an_reset\n"));
842 
843 	if (!sc->sc_enabled)
844 		return ENXIO;
845 
846 	an_cmd(sc, AN_CMD_ENABLE, 0);
847 	an_cmd(sc, AN_CMD_FW_RESTART, 0);
848 	an_cmd(sc, AN_CMD_NOOP2, 0);
849 
850 	if (an_cmd(sc, AN_CMD_FORCE_SYNCLOSS, 0) == ETIMEDOUT) {
851 		aprint_error_dev(sc->sc_dev, "reset failed\n");
852 		return ETIMEDOUT;
853 	}
854 
855 	an_cmd(sc, AN_CMD_DISABLE, 0);
856 	return 0;
857 }
858 
859 static void
860 an_watchdog(struct ifnet *ifp)
861 {
862 	struct an_softc *sc = ifp->if_softc;
863 
864 	if (!sc->sc_enabled)
865 		return;
866 
867 	if (sc->sc_tx_timer) {
868 		if (--sc->sc_tx_timer == 0) {
869 			printf("%s: device timeout\n", ifp->if_xname);
870 			ifp->if_oerrors++;
871 			an_init(ifp);
872 			return;
873 		}
874 		ifp->if_timer = 1;
875 	}
876 	ieee80211_watchdog(&sc->sc_ic);
877 }
878 
879 static int
880 an_ioctl(struct ifnet *ifp, u_long command, void *data)
881 {
882 	struct an_softc *sc = ifp->if_softc;
883 	int s, error = 0;
884 
885 	if (!device_is_active(sc->sc_dev))
886 		return ENXIO;
887 
888 	s = splnet();
889 
890 	switch (command) {
891 	case SIOCSIFFLAGS:
892 		if ((error = ifioctl_common(ifp, command, data)) != 0)
893 			break;
894 		if (ifp->if_flags & IFF_UP) {
895 			if (sc->sc_enabled) {
896 				/*
897 				 * To avoid rescanning another access point,
898 				 * do not call an_init() here.  Instead, only
899 				 * reflect promisc mode settings.
900 				 */
901 				error = an_cmd(sc, AN_CMD_SET_MODE,
902 				    (ifp->if_flags & IFF_PROMISC) ? 0xffff : 0);
903 			} else
904 				error = an_init(ifp);
905 		} else if (sc->sc_enabled)
906 			an_stop(ifp, 1);
907 		break;
908 	case SIOCADDMULTI:
909 	case SIOCDELMULTI:
910 		error = ether_ioctl(ifp, command, data);
911 		if (error == ENETRESET) {
912 			/* we don't have multicast filter. */
913 			error = 0;
914 		}
915 		break;
916 	case SIOCS80211NWKEY:
917 		error = an_set_nwkey(sc, (struct ieee80211_nwkey *)data);
918 			break;
919 	case SIOCG80211NWKEY:
920 		error = an_get_nwkey(sc, (struct ieee80211_nwkey *)data);
921 		break;
922 	default:
923 		error = ieee80211_ioctl(&sc->sc_ic, command, data);
924 		break;
925 	}
926 	if (error == ENETRESET) {
927 		if (sc->sc_enabled)
928 			error = an_init(ifp);
929 		else
930 			error = 0;
931 	}
932 	splx(s);
933 	return error;
934 }
935 
936 /* TBD factor with ieee80211_media_change */
937 static int
938 an_media_change(struct ifnet *ifp)
939 {
940 	struct an_softc *sc = ifp->if_softc;
941 	struct ieee80211com *ic = &sc->sc_ic;
942 	struct ifmedia_entry *ime;
943 	enum ieee80211_opmode newmode;
944 	int i, rate, error = 0;
945 
946 	ime = ic->ic_media.ifm_cur;
947 	if (IFM_SUBTYPE(ime->ifm_media) == IFM_AUTO) {
948 		i = -1;
949 	} else {
950 		struct ieee80211_rateset *rs =
951 		    &ic->ic_sup_rates[IEEE80211_MODE_11B];
952 		rate = ieee80211_media2rate(ime->ifm_media);
953 		if (rate == 0)
954 			return EINVAL;
955 		for (i = 0; i < rs->rs_nrates; i++) {
956 			if ((rs->rs_rates[i] & IEEE80211_RATE_VAL) == rate)
957 				break;
958 		}
959 		if (i == rs->rs_nrates)
960 			return EINVAL;
961 	}
962 	if (ic->ic_fixed_rate != i) {
963 		ic->ic_fixed_rate = i;
964 		error = ENETRESET;
965 	}
966 
967 	if (ime->ifm_media & IFM_IEEE80211_ADHOC)
968 		newmode = IEEE80211_M_IBSS;
969 	else if (ime->ifm_media & IFM_IEEE80211_HOSTAP)
970 		newmode = IEEE80211_M_HOSTAP;
971 	else if (ime->ifm_media & IFM_IEEE80211_MONITOR)
972 		newmode = IEEE80211_M_MONITOR;
973 	else
974 		newmode = IEEE80211_M_STA;
975 	if (ic->ic_opmode != newmode) {
976 		ic->ic_opmode = newmode;
977 		error = ENETRESET;
978 	}
979 	if (error == ENETRESET) {
980 		if (sc->sc_enabled)
981 			error = an_init(ifp);
982 		else
983 			error = 0;
984 	}
985 	ifp->if_baudrate = ifmedia_baudrate(ic->ic_media.ifm_cur->ifm_media);
986 
987 	return error;
988 }
989 
990 static void
991 an_media_status(struct ifnet *ifp, struct ifmediareq *imr)
992 {
993 	struct an_softc *sc = ifp->if_softc;
994 	struct ieee80211com *ic = &sc->sc_ic;
995 	int rate, buflen;
996 
997 	if (sc->sc_enabled == 0) {
998 		imr->ifm_active = IFM_IEEE80211 | IFM_NONE;
999 		imr->ifm_status = 0;
1000 		return;
1001 	}
1002 
1003 	imr->ifm_status = IFM_AVALID;
1004 	imr->ifm_active = IFM_IEEE80211;
1005 	if (ic->ic_state == IEEE80211_S_RUN)
1006 		imr->ifm_status |= IFM_ACTIVE;
1007 	buflen = sizeof(sc->sc_buf);
1008 	if (ic->ic_fixed_rate != -1)
1009 		rate = ic->ic_sup_rates[IEEE80211_MODE_11B].rs_rates[
1010 		    ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
1011 	else if (an_read_rid(sc, AN_RID_STATUS, &sc->sc_buf, &buflen) != 0)
1012 		rate = 0;
1013 	else
1014 		rate = le16toh(sc->sc_buf.sc_status.an_current_tx_rate);
1015 	imr->ifm_active |= ieee80211_rate2media(ic, rate, IEEE80211_MODE_11B);
1016 	switch (ic->ic_opmode) {
1017 	case IEEE80211_M_STA:
1018 		break;
1019 	case IEEE80211_M_IBSS:
1020 		imr->ifm_active |= IFM_IEEE80211_ADHOC;
1021 		break;
1022 	case IEEE80211_M_HOSTAP:
1023 		imr->ifm_active |= IFM_IEEE80211_HOSTAP;
1024 		break;
1025 	case IEEE80211_M_MONITOR:
1026 		imr->ifm_active |= IFM_IEEE80211_MONITOR;
1027 		break;
1028 	default:
1029 		break;
1030 	}
1031 }
1032 
1033 static int
1034 an_set_nwkey(struct an_softc *sc, struct ieee80211_nwkey *nwkey)
1035 {
1036 	int error;
1037 	struct ieee80211com *ic = &sc->sc_ic;
1038 	u_int16_t prevauth;
1039 
1040 	error = 0;
1041 	prevauth = sc->sc_config.an_authtype;
1042 
1043 	switch (nwkey->i_wepon) {
1044 	case IEEE80211_NWKEY_OPEN:
1045 		sc->sc_config.an_authtype = AN_AUTHTYPE_OPEN;
1046 		ic->ic_flags &= ~IEEE80211_F_PRIVACY;
1047 		break;
1048 
1049 	case IEEE80211_NWKEY_WEP:
1050 	case IEEE80211_NWKEY_WEP | IEEE80211_NWKEY_PERSIST:
1051 		error = an_set_nwkey_wep(sc, nwkey);
1052 		if (error == 0 || error == ENETRESET) {
1053 			sc->sc_config.an_authtype =
1054 			    AN_AUTHTYPE_OPEN | AN_AUTHTYPE_PRIVACY_IN_USE;
1055 			ic->ic_flags |= IEEE80211_F_PRIVACY;
1056 		}
1057 		break;
1058 
1059 	case IEEE80211_NWKEY_EAP:
1060 		error = an_set_nwkey_eap(sc, nwkey);
1061 		if (error == 0 || error == ENETRESET) {
1062 			sc->sc_config.an_authtype = AN_AUTHTYPE_OPEN |
1063 			    AN_AUTHTYPE_PRIVACY_IN_USE | AN_AUTHTYPE_LEAP;
1064 			ic->ic_flags |= IEEE80211_F_PRIVACY;
1065 		}
1066 		break;
1067 	default:
1068 		error = EINVAL;
1069 		break;
1070 	}
1071 	if (error == 0 && prevauth != sc->sc_config.an_authtype)
1072 		error = ENETRESET;
1073 	return error;
1074 }
1075 
1076 static int
1077 an_set_nwkey_wep(struct an_softc *sc, struct ieee80211_nwkey *nwkey)
1078 {
1079 	int i, txkey, anysetkey, needreset, error;
1080 	struct an_wepkey keys[IEEE80211_WEP_NKID];
1081 
1082 	error = 0;
1083 	memset(keys, 0, sizeof(keys));
1084 	anysetkey = needreset = 0;
1085 
1086 	/* load argument and sanity check */
1087 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
1088 		keys[i].an_wep_keylen = nwkey->i_key[i].i_keylen;
1089 		if (keys[i].an_wep_keylen < 0)
1090 			continue;
1091 		if (keys[i].an_wep_keylen != 0 &&
1092 		    keys[i].an_wep_keylen < IEEE80211_WEP_KEYLEN)
1093 			return EINVAL;
1094 		if (keys[i].an_wep_keylen > sizeof(keys[i].an_wep_key))
1095 			return EINVAL;
1096 		if ((error = copyin(nwkey->i_key[i].i_keydat,
1097 		    keys[i].an_wep_key, keys[i].an_wep_keylen)) != 0)
1098 			return error;
1099 		anysetkey++;
1100 	}
1101 	txkey = nwkey->i_defkid - 1;
1102 	if (txkey >= 0) {
1103 		if (txkey >= IEEE80211_WEP_NKID)
1104 			return EINVAL;
1105 		/* default key must have a valid value */
1106 		if (keys[txkey].an_wep_keylen == 0 ||
1107 		    (keys[txkey].an_wep_keylen < 0 &&
1108 		    sc->sc_perskeylen[txkey] == 0))
1109 			return EINVAL;
1110 		anysetkey++;
1111 	}
1112 	DPRINTF(("an_set_nwkey_wep: %s: %sold(%d:%d,%d,%d,%d) "
1113 	    "pers(%d:%d,%d,%d,%d) new(%d:%d,%d,%d,%d)\n",
1114 	    device_xname(sc->sc_dev),
1115 	    ((nwkey->i_wepon & IEEE80211_NWKEY_PERSIST) ? "persist: " : ""),
1116 	    sc->sc_tx_key,
1117 	    sc->sc_wepkeys[0].an_wep_keylen, sc->sc_wepkeys[1].an_wep_keylen,
1118 	    sc->sc_wepkeys[2].an_wep_keylen, sc->sc_wepkeys[3].an_wep_keylen,
1119 	    sc->sc_tx_perskey,
1120 	    sc->sc_perskeylen[0], sc->sc_perskeylen[1],
1121 	    sc->sc_perskeylen[2], sc->sc_perskeylen[3],
1122 	    txkey,
1123 	    keys[0].an_wep_keylen, keys[1].an_wep_keylen,
1124 	    keys[2].an_wep_keylen, keys[3].an_wep_keylen));
1125 	if (!(nwkey->i_wepon & IEEE80211_NWKEY_PERSIST)) {
1126 		/* set temporary keys */
1127 		sc->sc_tx_key = txkey;
1128 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
1129 			if (keys[i].an_wep_keylen < 0)
1130 				continue;
1131 			memcpy(&sc->sc_wepkeys[i], &keys[i], sizeof(keys[i]));
1132 		}
1133 	} else {
1134 		/* set persist keys */
1135 		if (anysetkey) {
1136 			/* prepare to write nvram */
1137 			if (!sc->sc_enabled) {
1138 				if (sc->sc_enable)
1139 					(*sc->sc_enable)(sc);
1140 				an_wait(sc);
1141 				sc->sc_enabled = 1;
1142 				error = an_write_wepkey(sc,
1143 				    AN_RID_WEP_PERSISTENT, keys, txkey);
1144 				if (sc->sc_disable)
1145 					(*sc->sc_disable)(sc);
1146 				sc->sc_enabled = 0;
1147 			} else {
1148 				an_cmd(sc, AN_CMD_DISABLE, 0);
1149 				error = an_write_wepkey(sc,
1150 				    AN_RID_WEP_PERSISTENT, keys, txkey);
1151 				an_cmd(sc, AN_CMD_ENABLE, 0);
1152 			}
1153 			if (error)
1154 				return error;
1155 		}
1156 		if (txkey >= 0)
1157 			sc->sc_tx_perskey = txkey;
1158 		if (sc->sc_tx_key >= 0) {
1159 			sc->sc_tx_key = -1;
1160 			needreset++;
1161 		}
1162 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
1163 			if (sc->sc_wepkeys[i].an_wep_keylen >= 0) {
1164 				memset(&sc->sc_wepkeys[i].an_wep_key, 0,
1165 				    sizeof(sc->sc_wepkeys[i].an_wep_key));
1166 				sc->sc_wepkeys[i].an_wep_keylen = -1;
1167 				needreset++;
1168 			}
1169 			if (keys[i].an_wep_keylen >= 0)
1170 				sc->sc_perskeylen[i] = keys[i].an_wep_keylen;
1171 		}
1172 	}
1173 	if (needreset) {
1174 		/* firmware restart to reload persistent key */
1175 		an_reset(sc);
1176 	}
1177 	if (anysetkey || needreset)
1178 		error = ENETRESET;
1179 	return error;
1180 }
1181 
1182 static int
1183 an_set_nwkey_eap(struct an_softc *sc, struct ieee80211_nwkey *nwkey)
1184 {
1185 	int i, error, len;
1186 	struct ifnet *ifp = &sc->sc_if;
1187 	struct an_rid_leapkey *key;
1188 	u_int16_t unibuf[sizeof(key->an_key)];
1189 	static const int leap_rid[] = { AN_RID_LEAP_PASS, AN_RID_LEAP_USER };
1190 	MD4_CTX ctx;
1191 
1192 	error = 0;
1193 
1194 	if (nwkey->i_key[0].i_keydat == NULL &&
1195 	    nwkey->i_key[1].i_keydat == NULL)
1196 		return 0;
1197 	if (!sc->sc_enabled)
1198 		return ENXIO;
1199 	an_cmd(sc, AN_CMD_DISABLE, 0);
1200 	key = &sc->sc_buf.sc_leapkey;
1201 	for (i = 0; i < 2; i++) {
1202 		if (nwkey->i_key[i].i_keydat == NULL)
1203 			continue;
1204 		len = nwkey->i_key[i].i_keylen;
1205 		if (len > sizeof(key->an_key))
1206 			return EINVAL;
1207 		memset(key, 0, sizeof(*key));
1208 		key->an_key_len = htole16(len);
1209 		if ((error = copyin(nwkey->i_key[i].i_keydat, key->an_key,
1210 		    len)) != 0)
1211 			return error;
1212 		if (i == 1) {
1213 			/*
1214 			 * Cisco seems to use PasswordHash and PasswordHashHash
1215 			 * in RFC-2759 (MS-CHAP-V2).
1216 			 */
1217 			memset(unibuf, 0, sizeof(unibuf));
1218 			/* XXX: convert password to unicode */
1219 			for (i = 0; i < len; i++)
1220 				unibuf[i] = key->an_key[i];
1221 			/* set PasswordHash */
1222 			MD4Init(&ctx);
1223 			MD4Update(&ctx, (u_int8_t *)unibuf, len * 2);
1224 			MD4Final(key->an_key, &ctx);
1225 			/* set PasswordHashHash */
1226 			MD4Init(&ctx);
1227 			MD4Update(&ctx, key->an_key, 16);
1228 			MD4Final(key->an_key + 16, &ctx);
1229 			key->an_key_len = htole16(32);
1230 		}
1231 		if ((error = an_write_rid(sc, leap_rid[i], key,
1232 		    sizeof(*key))) != 0) {
1233 			printf("%s: LEAP set failed\n", ifp->if_xname);
1234 			return error;
1235 		}
1236 	}
1237 	error = an_cmd(sc, AN_CMD_ENABLE, 0);
1238 	if (error)
1239 		printf("%s: an_set_nwkey: failed to enable MAC\n",
1240 		    ifp->if_xname);
1241 	else
1242 		error = ENETRESET;
1243 	return error;
1244 }
1245 
1246 static int
1247 an_get_nwkey(struct an_softc *sc, struct ieee80211_nwkey *nwkey)
1248 {
1249 	int i, error;
1250 
1251 	error = 0;
1252 	if (sc->sc_config.an_authtype & AN_AUTHTYPE_LEAP)
1253 		nwkey->i_wepon = IEEE80211_NWKEY_EAP;
1254 	else if (sc->sc_config.an_authtype & AN_AUTHTYPE_PRIVACY_IN_USE)
1255 		nwkey->i_wepon = IEEE80211_NWKEY_WEP;
1256 	else
1257 		nwkey->i_wepon = IEEE80211_NWKEY_OPEN;
1258 	if (sc->sc_tx_key == -1)
1259 		nwkey->i_defkid = sc->sc_tx_perskey + 1;
1260 	else
1261 		nwkey->i_defkid = sc->sc_tx_key + 1;
1262 	if (nwkey->i_key[0].i_keydat == NULL)
1263 		return 0;
1264 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
1265 		if (nwkey->i_key[i].i_keydat == NULL)
1266 			continue;
1267 		/* do not show any keys to non-root user */
1268 		if ((error = kauth_authorize_generic(curlwp->l_cred,
1269 		    KAUTH_GENERIC_ISSUSER, NULL)) != 0)
1270 			break;
1271 		nwkey->i_key[i].i_keylen = sc->sc_wepkeys[i].an_wep_keylen;
1272 		if (nwkey->i_key[i].i_keylen < 0) {
1273 			if (sc->sc_perskeylen[i] == 0)
1274 				nwkey->i_key[i].i_keylen = 0;
1275 			continue;
1276 		}
1277 		if ((error = copyout(sc->sc_wepkeys[i].an_wep_key,
1278 		    nwkey->i_key[i].i_keydat,
1279 		    sc->sc_wepkeys[i].an_wep_keylen)) != 0)
1280 			break;
1281 	}
1282 	return error;
1283 }
1284 
1285 static int
1286 an_write_wepkey(struct an_softc *sc, int type, struct an_wepkey *keys, int kid)
1287 {
1288 	int i, error;
1289 	struct an_rid_wepkey *akey;
1290 
1291 	error = 0;
1292 	akey = &sc->sc_buf.sc_wepkey;
1293 	memset(akey, 0, sizeof(struct an_rid_wepkey));
1294 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
1295 		if (keys[i].an_wep_keylen < 0 ||
1296 		    keys[i].an_wep_keylen > sizeof(akey->an_key))
1297 			continue;
1298 		akey->an_key_len = htole16(keys[i].an_wep_keylen);
1299 		akey->an_key_index = htole16(i);
1300 		akey->an_mac_addr[0] = 1;	/* default mac */
1301 		memcpy(akey->an_key, keys[i].an_wep_key, keys[i].an_wep_keylen);
1302 		if ((error = an_write_rid(sc, type, akey, sizeof(*akey))) != 0)
1303 			return error;
1304 	}
1305 	if (kid >= 0) {
1306 		akey->an_key_index = htole16(0xffff);
1307 		akey->an_mac_addr[0] = kid;
1308 		akey->an_key_len = htole16(0);
1309 		memset(akey->an_key, 0, sizeof(akey->an_key));
1310 		error = an_write_rid(sc, type, akey, sizeof(*akey));
1311 	}
1312 	return error;
1313 }
1314 
1315 #ifdef AN_DEBUG
1316 static void
1317 an_dump_pkt(const char *devname, struct mbuf *m)
1318 {
1319 	int col, col0, i;
1320 	uint8_t *pkt = mtod(m, uint8_t *);
1321 	const char *delim = "";
1322 	int delimw = 0;
1323 
1324 	printf("%s: pkt ", devname);
1325 	col = col0 = strlen(devname) + strlen(": pkt ");
1326 	for (i = 0; i < m->m_len; i++) {
1327 		printf("%s%02x", delim, pkt[i]);
1328 		delim = ":";
1329 		delimw = 1;
1330 		col += delimw + 2;
1331 		if (col >= 72) {
1332 			printf("\n%*s", col0, "");
1333 			col = col0;
1334 			delim = "";
1335 			delimw = 0;
1336 		}
1337 	}
1338 	if (col != 0)
1339 		printf("\n");
1340 }
1341 #endif /* AN_DEBUG */
1342 
1343 /*
1344  * Low level functions
1345  */
1346 
1347 static void
1348 an_rx_intr(struct an_softc *sc)
1349 {
1350 	struct ieee80211com *ic = &sc->sc_ic;
1351 	struct ifnet *ifp = &sc->sc_if;
1352 	struct ieee80211_frame_min *wh;
1353 	struct ieee80211_node *ni;
1354 	struct an_rxframe frmhdr;
1355 	struct mbuf *m;
1356 	u_int16_t status;
1357 	int fid, gaplen, len, off;
1358 	uint8_t *gap;
1359 
1360 	fid = CSR_READ_2(sc, AN_RX_FID);
1361 
1362 	/* First read in the frame header */
1363 	if (an_read_bap(sc, fid, 0, &frmhdr, sizeof(frmhdr)) != 0) {
1364 		CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_RX);
1365 		ifp->if_ierrors++;
1366 		DPRINTF(("an_rx_intr: read fid %x failed\n", fid));
1367 		return;
1368 	}
1369 
1370 #ifdef AN_DEBUG
1371 	if ((ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2)) {
1372 		ieee80211_dump_pkt((u_int8_t *)&frmhdr.an_whdr,
1373 		    sizeof(struct ieee80211_frame), frmhdr.an_rx_rate,
1374 		    frmhdr.an_rx_signal_strength);
1375 		printf(" time 0x%x status 0x%x plen %u chan %u"
1376 		    " plcp %02x %02x %02x %02x gap %u\n",
1377 		    le32toh(frmhdr.an_rx_time), le16toh(frmhdr.an_rx_status),
1378 		    le16toh(frmhdr.an_rx_payload_len), frmhdr.an_rx_chan,
1379 		    frmhdr.an_plcp_hdr[0], frmhdr.an_plcp_hdr[1],
1380 		    frmhdr.an_plcp_hdr[2], frmhdr.an_plcp_hdr[3],
1381 		    le16toh(frmhdr.an_gaplen));
1382 	}
1383 #endif
1384 
1385 	status = le16toh(frmhdr.an_rx_status);
1386 	if ((status & AN_STAT_ERRSTAT) != 0 &&
1387 	    ic->ic_opmode != IEEE80211_M_MONITOR) {
1388 		CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_RX);
1389 		ifp->if_ierrors++;
1390 		DPRINTF(("an_rx_intr: fid %x status %x\n", fid, status));
1391 		return;
1392 	}
1393 
1394 	/* the payload length field includes a 16-bit "mystery field" */
1395 	len = le16toh(frmhdr.an_rx_payload_len) - sizeof(uint16_t);
1396 	off = ALIGN(sizeof(struct ieee80211_frame));
1397 
1398 	if (off + len > MCLBYTES) {
1399 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1400 			CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_RX);
1401 			ifp->if_ierrors++;
1402 			DPRINTF(("an_rx_intr: oversized packet %d\n", len));
1403 			return;
1404 		}
1405 		len = 0;
1406 	}
1407 
1408 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1409 	if (m == NULL) {
1410 		CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_RX);
1411 		ifp->if_ierrors++;
1412 		DPRINTF(("an_rx_intr: MGET failed\n"));
1413 		return;
1414 	}
1415 	if (off + len + AN_GAPLEN_MAX > MHLEN) {
1416 		MCLGET(m, M_DONTWAIT);
1417 		if ((m->m_flags & M_EXT) == 0) {
1418 			CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_RX);
1419 			m_freem(m);
1420 			ifp->if_ierrors++;
1421 			DPRINTF(("an_rx_intr: MCLGET failed\n"));
1422 			return;
1423 		}
1424 	}
1425 	m->m_data += off - sizeof(struct ieee80211_frame);
1426 
1427 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1428 		gaplen = le16toh(frmhdr.an_gaplen);
1429 		if (gaplen > AN_GAPLEN_MAX) {
1430 			CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_RX);
1431 			m_freem(m);
1432 			ifp->if_ierrors++;
1433 			DPRINTF(("%s: gap too long\n", __func__));
1434 			return;
1435 		}
1436 		/*
1437 		 * We don't need the 16-bit mystery field (payload length?),
1438 		 * so read it into the region reserved for the 802.11 header.
1439 		 *
1440 		 * When Cisco Aironet 350 cards w/ firmware version 5 or
1441 		 * greater operate with certain Cisco 350 APs,
1442 		 * the "gap" is filled with the SNAP header.  Read
1443 		 * it in after the 802.11 header.
1444 		 */
1445 		gap = m->m_data + sizeof(struct ieee80211_frame) -
1446 		    sizeof(uint16_t);
1447 		an_read_bap(sc, fid, -1, gap, gaplen + sizeof(u_int16_t));
1448 #ifdef AN_DEBUG
1449 		if ((ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) ==
1450 		    (IFF_DEBUG|IFF_LINK2)) {
1451 			int i;
1452 			printf(" gap&len");
1453 			for (i = 0; i < gaplen + sizeof(u_int16_t); i++)
1454 				printf(" %02x", gap[i]);
1455 			printf("\n");
1456 		}
1457 #endif
1458 	} else
1459 		gaplen = 0;
1460 
1461 	an_read_bap(sc, fid, -1,
1462 	    m->m_data + sizeof(struct ieee80211_frame) + gaplen, len);
1463 	m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame) + gaplen +
1464 	    len;
1465 
1466 	memcpy(m->m_data, &frmhdr.an_whdr, sizeof(struct ieee80211_frame));
1467 	m->m_pkthdr.rcvif = ifp;
1468 	CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_RX);
1469 
1470 #if NBPFILTER > 0
1471 	if (sc->sc_drvbpf) {
1472 		struct an_rx_radiotap_header *tap = &sc->sc_rxtap;
1473 
1474 		tap->ar_rate = frmhdr.an_rx_rate;
1475 		tap->ar_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
1476 		tap->ar_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
1477 		tap->ar_antsignal = frmhdr.an_rx_signal_strength;
1478 		if ((le16toh(frmhdr.an_rx_status) & AN_STAT_BADCRC) ||
1479 		    (le16toh(frmhdr.an_rx_status) & AN_STAT_ERRSTAT) ||
1480 		    (le16toh(frmhdr.an_rx_status) & AN_STAT_UNDECRYPTABLE))
1481 		    tap->ar_flags |= IEEE80211_RADIOTAP_F_BADFCS;
1482 
1483 		bpf_mtap2(sc->sc_drvbpf, tap, tap->ar_ihdr.it_len, m);
1484 	}
1485 #endif
1486 	wh = mtod(m, struct ieee80211_frame_min *);
1487 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1488 		/*
1489 		 * WEP is decrypted by hardware. Clear WEP bit
1490 		 * header for ieee80211_input().
1491 		 */
1492 		wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
1493 	}
1494 
1495 #ifdef AN_DEBUG
1496 	if (an_debug > 1)
1497 		an_dump_pkt(device_xname(sc->sc_dev), m);
1498 #endif /* AN_DEBUG */
1499 
1500 	ni = ieee80211_find_rxnode(ic, wh);
1501 	ieee80211_input(ic, m, ni, frmhdr.an_rx_signal_strength,
1502 	    le32toh(frmhdr.an_rx_time));
1503 	ieee80211_free_node(ni);
1504 }
1505 
1506 static void
1507 an_tx_intr(struct an_softc *sc, int status)
1508 {
1509 	struct ifnet *ifp = &sc->sc_if;
1510 	int cur, fid;
1511 
1512 	sc->sc_tx_timer = 0;
1513 	ifp->if_flags &= ~IFF_OACTIVE;
1514 
1515 	fid = CSR_READ_2(sc, AN_TX_CMP_FID);
1516 	CSR_WRITE_2(sc, AN_EVENT_ACK, status & (AN_EV_TX | AN_EV_TX_EXC));
1517 
1518 	if (status & AN_EV_TX_EXC)
1519 		ifp->if_oerrors++;
1520 	else
1521 		ifp->if_opackets++;
1522 
1523 	cur = sc->sc_txcur;
1524 	if (sc->sc_txd[cur].d_fid == fid) {
1525 		sc->sc_txd[cur].d_inuse = 0;
1526 		DPRINTF2(("an_tx_intr: sent %x/%d\n", fid, cur));
1527 		AN_INC(cur, AN_TX_RING_CNT);
1528 		sc->sc_txcur = cur;
1529 	} else {
1530 		for (cur = 0; cur < AN_TX_RING_CNT; cur++) {
1531 			if (fid == sc->sc_txd[cur].d_fid) {
1532 				sc->sc_txd[cur].d_inuse = 0;
1533 				break;
1534 			}
1535 		}
1536 		if (ifp->if_flags & IFF_DEBUG)
1537 			printf("%s: tx mismatch: "
1538 			    "expected %x(%d), actual %x(%d)\n",
1539 			    device_xname(sc->sc_dev),
1540 			    sc->sc_txd[sc->sc_txcur].d_fid, sc->sc_txcur,
1541 			    fid, cur);
1542 	}
1543 
1544 	return;
1545 }
1546 
1547 static void
1548 an_linkstat_intr(struct an_softc *sc)
1549 {
1550 	struct ieee80211com *ic = &sc->sc_ic;
1551 	u_int16_t status;
1552 
1553 	status = CSR_READ_2(sc, AN_LINKSTAT);
1554 	CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_LINKSTAT);
1555 	DPRINTF(("an_linkstat_intr: status 0x%x\n", status));
1556 
1557 	if (status == AN_LINKSTAT_ASSOCIATED) {
1558 		if (ic->ic_state != IEEE80211_S_RUN ||
1559 		    ic->ic_opmode == IEEE80211_M_IBSS)
1560 			ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1561 	} else {
1562 		if (ic->ic_opmode == IEEE80211_M_STA)
1563 			ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
1564 	}
1565 }
1566 
1567 /* Must be called at proper protection level! */
1568 static int
1569 an_cmd(struct an_softc *sc, int cmd, int val)
1570 {
1571 	int i, status;
1572 
1573 	/* make sure that previous command completed */
1574 	if (CSR_READ_2(sc, AN_COMMAND) & AN_CMD_BUSY) {
1575 		if (sc->sc_if.if_flags & IFF_DEBUG)
1576 			printf("%s: command 0x%x busy\n", device_xname(sc->sc_dev),
1577 			    CSR_READ_2(sc, AN_COMMAND));
1578 		CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_CLR_STUCK_BUSY);
1579 	}
1580 
1581 	CSR_WRITE_2(sc, AN_PARAM0, val);
1582 	CSR_WRITE_2(sc, AN_PARAM1, 0);
1583 	CSR_WRITE_2(sc, AN_PARAM2, 0);
1584 	CSR_WRITE_2(sc, AN_COMMAND, cmd);
1585 
1586 	if (cmd == AN_CMD_FW_RESTART) {
1587 		/* XXX: should sleep here */
1588 		DELAY(100*1000);
1589 	}
1590 
1591 	for (i = 0; i < AN_TIMEOUT; i++) {
1592 		if (CSR_READ_2(sc, AN_EVENT_STAT) & AN_EV_CMD)
1593 			break;
1594 		DELAY(10);
1595 	}
1596 
1597 	status = CSR_READ_2(sc, AN_STATUS);
1598 
1599 	/* clear stuck command busy if necessary */
1600 	if (CSR_READ_2(sc, AN_COMMAND) & AN_CMD_BUSY)
1601 		CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_CLR_STUCK_BUSY);
1602 
1603 	/* Ack the command */
1604 	CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_CMD);
1605 
1606 	if (i == AN_TIMEOUT) {
1607 		if (sc->sc_if.if_flags & IFF_DEBUG)
1608 			printf("%s: command 0x%x param 0x%x timeout\n",
1609 			    device_xname(sc->sc_dev), cmd, val);
1610 		return ETIMEDOUT;
1611 	}
1612 	if (status & AN_STAT_CMD_RESULT) {
1613 		if (sc->sc_if.if_flags & IFF_DEBUG)
1614 			printf("%s: command 0x%x param 0x%x status 0x%x "
1615 			    "resp 0x%x 0x%x 0x%x\n",
1616 			    device_xname(sc->sc_dev), cmd, val, status,
1617 			    CSR_READ_2(sc, AN_RESP0), CSR_READ_2(sc, AN_RESP1),
1618 			    CSR_READ_2(sc, AN_RESP2));
1619 		return EIO;
1620 	}
1621 
1622 	return 0;
1623 }
1624 
1625 
1626 /*
1627  * Wait for firmware come up after power enabled.
1628  */
1629 static void
1630 an_wait(struct an_softc *sc)
1631 {
1632 	int i;
1633 
1634 	CSR_WRITE_2(sc, AN_COMMAND, AN_CMD_NOOP2);
1635 	for (i = 0; i < 3*hz; i++) {
1636 		if (CSR_READ_2(sc, AN_EVENT_STAT) & AN_EV_CMD)
1637 			break;
1638 		(void)tsleep(sc, PWAIT, "anatch", 1);
1639 	}
1640 	CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_CMD);
1641 }
1642 
1643 static int
1644 an_seek_bap(struct an_softc *sc, int id, int off)
1645 {
1646 	int i, status;
1647 
1648 	CSR_WRITE_2(sc, AN_SEL0, id);
1649 	CSR_WRITE_2(sc, AN_OFF0, off);
1650 
1651 	for (i = 0; ; i++) {
1652 		status = CSR_READ_2(sc, AN_OFF0);
1653 		if ((status & AN_OFF_BUSY) == 0)
1654 			break;
1655 		if (i == AN_TIMEOUT) {
1656 			printf("%s: timeout in an_seek_bap to 0x%x/0x%x\n",
1657 			    device_xname(sc->sc_dev), id, off);
1658 			sc->sc_bap_off = AN_OFF_ERR;	/* invalidate */
1659 			return ETIMEDOUT;
1660 		}
1661 		DELAY(10);
1662 	}
1663 	if (status & AN_OFF_ERR) {
1664 		aprint_error_dev(sc->sc_dev, "failed in an_seek_bap to 0x%x/0x%x\n",
1665 		    id, off);
1666 		sc->sc_bap_off = AN_OFF_ERR;	/* invalidate */
1667 		return EIO;
1668 	}
1669 	sc->sc_bap_id = id;
1670 	sc->sc_bap_off = off;
1671 	return 0;
1672 }
1673 
1674 static int
1675 an_read_bap(struct an_softc *sc, int id, int off, void *buf, int buflen)
1676 {
1677 	int error, cnt;
1678 
1679 	if (buflen == 0)
1680 		return 0;
1681 	if (off == -1)
1682 		off = sc->sc_bap_off;
1683 	if (id != sc->sc_bap_id || off != sc->sc_bap_off) {
1684 		if ((error = an_seek_bap(sc, id, off)) != 0)
1685 			return EIO;
1686 	}
1687 
1688 	cnt = (buflen + 1) / 2;
1689 	CSR_READ_MULTI_STREAM_2(sc, AN_DATA0, (u_int16_t *)buf, cnt);
1690 	sc->sc_bap_off += cnt * 2;
1691 	return 0;
1692 }
1693 
1694 static int
1695 an_write_bap(struct an_softc *sc, int id, int off, void *buf, int buflen)
1696 {
1697 	int error, cnt;
1698 
1699 	if (buflen == 0)
1700 		return 0;
1701 	if (off == -1)
1702 		off = sc->sc_bap_off;
1703 	if (id != sc->sc_bap_id || off != sc->sc_bap_off) {
1704 		if ((error = an_seek_bap(sc, id, off)) != 0)
1705 			return EIO;
1706 	}
1707 
1708 	cnt = (buflen + 1) / 2;
1709 	CSR_WRITE_MULTI_STREAM_2(sc, AN_DATA0, (u_int16_t *)buf, cnt);
1710 	sc->sc_bap_off += cnt * 2;
1711 	return 0;
1712 }
1713 
1714 static int
1715 an_mwrite_bap(struct an_softc *sc, int id, int off, struct mbuf *m, int totlen)
1716 {
1717 	int error, len, cnt;
1718 
1719 	if (off == -1)
1720 		off = sc->sc_bap_off;
1721 	if (id != sc->sc_bap_id || off != sc->sc_bap_off) {
1722 		if ((error = an_seek_bap(sc, id, off)) != 0)
1723 			return EIO;
1724 	}
1725 
1726 	for (len = 0; m != NULL; m = m->m_next) {
1727 		if (m->m_len == 0)
1728 			continue;
1729 		len = min(m->m_len, totlen);
1730 
1731 		if ((mtod(m, u_long) & 0x1) || (len & 0x1)) {
1732 			m_copydata(m, 0, totlen, (void *)&sc->sc_buf.sc_txbuf);
1733 			cnt = (totlen + 1) / 2;
1734 			CSR_WRITE_MULTI_STREAM_2(sc, AN_DATA0,
1735 			    sc->sc_buf.sc_val, cnt);
1736 			off += cnt * 2;
1737 			break;
1738 		}
1739 		cnt = len / 2;
1740 		CSR_WRITE_MULTI_STREAM_2(sc, AN_DATA0, mtod(m, u_int16_t *),
1741 		    cnt);
1742 		off += len;
1743 		totlen -= len;
1744 	}
1745 	sc->sc_bap_off = off;
1746 	return 0;
1747 }
1748 
1749 static int
1750 an_alloc_fid(struct an_softc *sc, int len, int *idp)
1751 {
1752 	int i;
1753 
1754 	if (an_cmd(sc, AN_CMD_ALLOC_MEM, len)) {
1755 		aprint_error_dev(sc->sc_dev, "failed to allocate %d bytes on NIC\n",
1756 		    len);
1757 		return ENOMEM;
1758 	}
1759 
1760 	for (i = 0; i < AN_TIMEOUT; i++) {
1761 		if (CSR_READ_2(sc, AN_EVENT_STAT) & AN_EV_ALLOC)
1762 			break;
1763 		if (i == AN_TIMEOUT) {
1764 			printf("%s: timeout in alloc\n", device_xname(sc->sc_dev));
1765 			return ETIMEDOUT;
1766 		}
1767 		DELAY(10);
1768 	}
1769 
1770 	*idp = CSR_READ_2(sc, AN_ALLOC_FID);
1771 	CSR_WRITE_2(sc, AN_EVENT_ACK, AN_EV_ALLOC);
1772 	return 0;
1773 }
1774 
1775 static int
1776 an_read_rid(struct an_softc *sc, int rid, void *buf, int *buflenp)
1777 {
1778 	int error;
1779 	u_int16_t len;
1780 
1781 	/* Tell the NIC to enter record read mode. */
1782 	error = an_cmd(sc, AN_CMD_ACCESS | AN_ACCESS_READ, rid);
1783 	if (error)
1784 		return error;
1785 
1786 	/* length in byte, including length itself */
1787 	error = an_read_bap(sc, rid, 0, &len, sizeof(len));
1788 	if (error)
1789 		return error;
1790 
1791 	len = le16toh(len) - 2;
1792 	if (*buflenp < len) {
1793 		aprint_error_dev(sc->sc_dev, "record buffer is too small, "
1794 		    "rid=%x, size=%d, len=%d\n",
1795 		    rid, *buflenp, len);
1796 		return ENOSPC;
1797 	}
1798 	*buflenp = len;
1799 	return an_read_bap(sc, rid, sizeof(len), buf, len);
1800 }
1801 
1802 static int
1803 an_write_rid(struct an_softc *sc, int rid, void *buf, int buflen)
1804 {
1805 	int error;
1806 	u_int16_t len;
1807 
1808 	/* length in byte, including length itself */
1809 	len = htole16(buflen + 2);
1810 
1811 	error = an_write_bap(sc, rid, 0, &len, sizeof(len));
1812 	if (error)
1813 		return error;
1814 	error = an_write_bap(sc, rid, sizeof(len), buf, buflen);
1815 	if (error)
1816 		return error;
1817 
1818 	return an_cmd(sc, AN_CMD_ACCESS | AN_ACCESS_WRITE, rid);
1819 }
1820 
1821 static int
1822 an_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
1823 {
1824 	struct an_softc *sc = (struct an_softc *)ic->ic_ifp->if_softc;
1825 	struct ieee80211_node *ni = ic->ic_bss;
1826 	enum ieee80211_state ostate;
1827 	int buflen;
1828 
1829 	ostate = ic->ic_state;
1830 	DPRINTF(("an_newstate: %s -> %s\n", ieee80211_state_name[ostate],
1831 	    ieee80211_state_name[nstate]));
1832 
1833 	switch (nstate) {
1834 	case IEEE80211_S_INIT:
1835 		ic->ic_flags &= ~IEEE80211_F_IBSSON;
1836 		return (*sc->sc_newstate)(ic, nstate, arg);
1837 
1838 	case IEEE80211_S_SCAN:
1839 	case IEEE80211_S_AUTH:
1840 	case IEEE80211_S_ASSOC:
1841 		ic->ic_state = nstate; /* NB: skip normal ieee80211 handling */
1842 		return 0;
1843 
1844 	case IEEE80211_S_RUN:
1845 		buflen = sizeof(sc->sc_buf);
1846 		an_read_rid(sc, AN_RID_STATUS, &sc->sc_buf, &buflen);
1847 		IEEE80211_ADDR_COPY(ni->ni_bssid,
1848 		    sc->sc_buf.sc_status.an_cur_bssid);
1849 		IEEE80211_ADDR_COPY(ni->ni_macaddr, ni->ni_bssid);
1850 		ni->ni_chan = &ic->ic_channels[
1851 		    le16toh(sc->sc_buf.sc_status.an_cur_channel)];
1852 		ni->ni_esslen = le16toh(sc->sc_buf.sc_status.an_ssidlen);
1853 		if (ni->ni_esslen > IEEE80211_NWID_LEN)
1854 			ni->ni_esslen = IEEE80211_NWID_LEN;	/*XXX*/
1855 		memcpy(ni->ni_essid, sc->sc_buf.sc_status.an_ssid,
1856 		    ni->ni_esslen);
1857 		ni->ni_rates = ic->ic_sup_rates[IEEE80211_MODE_11B];	/*XXX*/
1858 		if (ic->ic_ifp->if_flags & IFF_DEBUG) {
1859 			printf("%s: ", device_xname(sc->sc_dev));
1860 			if (ic->ic_opmode == IEEE80211_M_STA)
1861 				printf("associated ");
1862 			else
1863 				printf("synchronized ");
1864 			printf("with %s ssid ", ether_sprintf(ni->ni_bssid));
1865 			ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
1866 			printf(" channel %u start %uMb\n",
1867 			    le16toh(sc->sc_buf.sc_status.an_cur_channel),
1868 			    le16toh(sc->sc_buf.sc_status.an_current_tx_rate)/2);
1869 		}
1870 		break;
1871 
1872 	default:
1873 		break;
1874 	}
1875 	return (*sc->sc_newstate)(ic, nstate, arg);
1876 }
1877