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