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