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