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