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