]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/wi/if_wi.c
MFV r358616:
[FreeBSD/FreeBSD.git] / sys / dev / wi / if_wi.c
1 /*-
2  * Copyright (c) 1997, 1998, 1999
3  *      Bill Paul <wpaul@ctr.columbia.edu>.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by Bill Paul.
16  * 4. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
30  * THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 /*
34  * Lucent WaveLAN/IEEE 802.11 PCMCIA driver.
35  *
36  * Original FreeBSD driver written by Bill Paul <wpaul@ctr.columbia.edu>
37  * Electrical Engineering Department
38  * Columbia University, New York City
39  */
40
41 /*
42  * The WaveLAN/IEEE adapter is the second generation of the WaveLAN
43  * from Lucent. Unlike the older cards, the new ones are programmed
44  * entirely via a firmware-driven controller called the Hermes.
45  * Unfortunately, Lucent will not release the Hermes programming manual
46  * without an NDA (if at all). What they do release is an API library
47  * called the HCF (Hardware Control Functions) which is supposed to
48  * do the device-specific operations of a device driver for you. The
49  * publicly available version of the HCF library (the 'HCF Light') is 
50  * a) extremely gross, b) lacks certain features, particularly support
51  * for 802.11 frames, and c) is contaminated by the GNU Public License.
52  *
53  * This driver does not use the HCF or HCF Light at all. Instead, it
54  * programs the Hermes controller directly, using information gleaned
55  * from the HCF Light code and corresponding documentation.
56  *
57  * This driver supports the ISA, PCMCIA and PCI versions of the Lucent
58  * WaveLan cards (based on the Hermes chipset), as well as the newer
59  * Prism 2 chipsets with firmware from Intersil and Symbol.
60  */
61
62 #include <sys/cdefs.h>
63 __FBSDID("$FreeBSD$");
64
65 #include "opt_wlan.h"
66
67 #define WI_HERMES_STATS_WAR     /* Work around stats counter bug. */
68
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/endian.h>
72 #include <sys/sockio.h>
73 #include <sys/mbuf.h>
74 #include <sys/priv.h>
75 #include <sys/proc.h>
76 #include <sys/kernel.h>
77 #include <sys/malloc.h>
78 #include <sys/socket.h>
79 #include <sys/module.h>
80 #include <sys/bus.h>
81 #include <sys/random.h>
82 #include <sys/syslog.h>
83 #include <sys/sysctl.h>
84
85 #include <machine/bus.h>
86 #include <machine/resource.h>
87 #include <machine/atomic.h>
88 #include <sys/rman.h>
89
90 #include <net/if.h>
91 #include <net/if_var.h>
92 #include <net/if_arp.h>
93 #include <net/ethernet.h>
94 #include <net/if_dl.h>
95 #include <net/if_llc.h>
96 #include <net/if_media.h>
97 #include <net/if_types.h>
98
99 #include <net80211/ieee80211_var.h>
100 #include <net80211/ieee80211_ioctl.h>
101 #include <net80211/ieee80211_radiotap.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/wi/if_wavelan_ieee.h>
112 #include <dev/wi/if_wireg.h>
113 #include <dev/wi/if_wivar.h>
114
115 static struct ieee80211vap *wi_vap_create(struct ieee80211com *,
116                     const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
117                     const uint8_t [IEEE80211_ADDR_LEN],
118                     const uint8_t [IEEE80211_ADDR_LEN]);
119 static void wi_vap_delete(struct ieee80211vap *vap);
120 static int  wi_transmit(struct ieee80211com *, struct mbuf *);
121 static void wi_start(struct wi_softc *);
122 static int  wi_start_tx(struct wi_softc *, struct wi_frame *, struct mbuf *);
123 static int  wi_raw_xmit(struct ieee80211_node *, struct mbuf *,
124                 const struct ieee80211_bpf_params *);
125 static int  wi_newstate_sta(struct ieee80211vap *, enum ieee80211_state, int);
126 static int  wi_newstate_hostap(struct ieee80211vap *, enum ieee80211_state,
127                 int);
128 static void wi_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
129                 int subtype, const struct ieee80211_rx_stats *rxs,
130                 int rssi, int nf);
131 static int  wi_reset(struct wi_softc *);
132 static void wi_watchdog(void *);
133 static void wi_parent(struct ieee80211com *);
134 static void wi_media_status(struct ifnet *, struct ifmediareq *);
135 static void wi_rx_intr(struct wi_softc *);
136 static void wi_tx_intr(struct wi_softc *);
137 static void wi_tx_ex_intr(struct wi_softc *);
138
139 static void wi_info_intr(struct wi_softc *);
140
141 static int  wi_write_txrate(struct wi_softc *, struct ieee80211vap *);
142 static int  wi_write_wep(struct wi_softc *, struct ieee80211vap *);
143 static int  wi_write_multi(struct wi_softc *);
144 static void wi_update_mcast(struct ieee80211com *);
145 static void wi_update_promisc(struct ieee80211com *);
146 static int  wi_alloc_fid(struct wi_softc *, int, int *);
147 static void wi_read_nicid(struct wi_softc *);
148 static int  wi_write_ssid(struct wi_softc *, int, u_int8_t *, int);
149
150 static int  wi_cmd(struct wi_softc *, int, int, int, int);
151 static int  wi_seek_bap(struct wi_softc *, int, int);
152 static int  wi_read_bap(struct wi_softc *, int, int, void *, int);
153 static int  wi_write_bap(struct wi_softc *, int, int, const void *, int);
154 static int  wi_mwrite_bap(struct wi_softc *, int, int, struct mbuf *, int);
155 static int  wi_read_rid(struct wi_softc *, int, void *, int *);
156 static int  wi_write_rid(struct wi_softc *, int, const void *, int);
157 static int  wi_write_appie(struct wi_softc *, int, const struct ieee80211_appie *);
158 static u_int16_t wi_read_chanmask(struct wi_softc *);
159
160 static void wi_scan_start(struct ieee80211com *);
161 static void wi_scan_end(struct ieee80211com *);
162 static void wi_getradiocaps(struct ieee80211com *, int, int *,
163                 struct ieee80211_channel[]);
164 static void wi_set_channel(struct ieee80211com *);
165         
166 static __inline int
167 wi_write_val(struct wi_softc *sc, int rid, u_int16_t val)
168 {
169
170         val = htole16(val);
171         return wi_write_rid(sc, rid, &val, sizeof(val));
172 }
173
174 static SYSCTL_NODE(_hw, OID_AUTO, wi, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
175     "Wireless driver parameters");
176
177 static  struct timeval lasttxerror;     /* time of last tx error msg */
178 static  int curtxeps;                   /* current tx error msgs/sec */
179 static  int wi_txerate = 0;             /* tx error rate: max msgs/sec */
180 SYSCTL_INT(_hw_wi, OID_AUTO, txerate, CTLFLAG_RW, &wi_txerate,
181             0, "max tx error msgs/sec; 0 to disable msgs");
182
183 #define WI_DEBUG
184 #ifdef WI_DEBUG
185 static  int wi_debug = 0;
186 SYSCTL_INT(_hw_wi, OID_AUTO, debug, CTLFLAG_RW, &wi_debug,
187             0, "control debugging printfs");
188 #define DPRINTF(X)      if (wi_debug) printf X
189 #else
190 #define DPRINTF(X)
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 static char *wi_firmware_names[] = { "none", "Hermes", "Intersil", "Symbol" };
233
234 devclass_t wi_devclass;
235
236 int
237 wi_attach(device_t dev)
238 {
239         struct wi_softc *sc = device_get_softc(dev);
240         struct ieee80211com *ic = &sc->sc_ic;
241         int i, nrates, buflen;
242         u_int16_t val;
243         u_int8_t ratebuf[2 + IEEE80211_RATE_SIZE];
244         struct ieee80211_rateset *rs;
245         struct sysctl_ctx_list *sctx;
246         struct sysctl_oid *soid;
247         static const u_int8_t empty_macaddr[IEEE80211_ADDR_LEN] = {
248                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
249         };
250         int error;
251
252         sc->sc_firmware_type = WI_NOTYPE;
253         sc->wi_cmd_count = 500;
254         /* Reset the NIC. */
255         if (wi_reset(sc) != 0) {
256                 wi_free(dev);
257                 return ENXIO;           /* XXX */
258         }
259
260         /* Read NIC identification */
261         wi_read_nicid(sc);
262         switch (sc->sc_firmware_type) {
263         case WI_LUCENT:
264                 if (sc->sc_sta_firmware_ver < 60006)
265                         goto reject;
266                 break;
267         case WI_INTERSIL:
268                 if (sc->sc_sta_firmware_ver < 800)
269                         goto reject;
270                 break;
271         default:
272         reject:
273                 device_printf(dev, "Sorry, this card is not supported "
274                     "(type %d, firmware ver %d)\n",
275                     sc->sc_firmware_type, sc->sc_sta_firmware_ver);
276                 wi_free(dev);
277                 return EOPNOTSUPP; 
278         }
279
280         /* Export info about the device via sysctl */
281         sctx = device_get_sysctl_ctx(dev);
282         soid = device_get_sysctl_tree(dev);
283         SYSCTL_ADD_STRING(sctx, SYSCTL_CHILDREN(soid), OID_AUTO,
284             "firmware_type", CTLFLAG_RD,
285             wi_firmware_names[sc->sc_firmware_type], 0,
286             "Firmware type string");
287         SYSCTL_ADD_INT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "sta_version",
288             CTLFLAG_RD, &sc->sc_sta_firmware_ver, 0,
289             "Station Firmware version");
290         if (sc->sc_firmware_type == WI_INTERSIL)
291                 SYSCTL_ADD_INT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO,
292                     "pri_version", CTLFLAG_RD, &sc->sc_pri_firmware_ver, 0,
293                     "Primary Firmware version");
294         SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "nic_id",
295             CTLFLAG_RD, &sc->sc_nic_id, 0, "NIC id");
296         SYSCTL_ADD_STRING(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "nic_name",
297             CTLFLAG_RD, sc->sc_nic_name, 0, "NIC name");
298
299         mtx_init(&sc->sc_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
300             MTX_DEF | MTX_RECURSE);
301         callout_init_mtx(&sc->sc_watchdog, &sc->sc_mtx, 0);
302         mbufq_init(&sc->sc_snd, ifqmaxlen);
303
304         /*
305          * Read the station address.
306          * And do it twice. I've seen PRISM-based cards that return
307          * an error when trying to read it the first time, which causes
308          * the probe to fail.
309          */
310         buflen = IEEE80211_ADDR_LEN;
311         error = wi_read_rid(sc, WI_RID_MAC_NODE, &ic->ic_macaddr, &buflen);
312         if (error != 0) {
313                 buflen = IEEE80211_ADDR_LEN;
314                 error = wi_read_rid(sc, WI_RID_MAC_NODE, &ic->ic_macaddr,
315                     &buflen);
316         }
317         if (error || IEEE80211_ADDR_EQ(&ic->ic_macaddr, empty_macaddr)) {
318                 if (error != 0)
319                         device_printf(dev, "mac read failed %d\n", error);
320                 else {
321                         device_printf(dev, "mac read failed (all zeros)\n");
322                         error = ENXIO;
323                 }
324                 wi_free(dev);
325                 return (error);
326         }
327
328         ic->ic_softc = sc;
329         ic->ic_name = device_get_nameunit(dev);
330         ic->ic_phytype = IEEE80211_T_DS;
331         ic->ic_opmode = IEEE80211_M_STA;
332         ic->ic_caps = IEEE80211_C_STA
333                     | IEEE80211_C_PMGT
334                     | IEEE80211_C_MONITOR
335                     ;
336
337         /*
338          * Query the card for available channels and setup the
339          * channel table.  We assume these are all 11b channels.
340          */
341         sc->sc_chanmask = wi_read_chanmask(sc);
342         wi_getradiocaps(ic, IEEE80211_CHAN_MAX, &ic->ic_nchans,
343             ic->ic_channels);
344
345         /*
346          * Set flags based on firmware version.
347          */
348         switch (sc->sc_firmware_type) {
349         case WI_LUCENT:
350                 sc->sc_ntxbuf = 1;
351                 ic->ic_caps |= IEEE80211_C_IBSS;
352
353                 sc->sc_ibss_port = WI_PORTTYPE_BSS;
354                 sc->sc_monitor_port = WI_PORTTYPE_ADHOC;
355                 sc->sc_min_rssi = WI_LUCENT_MIN_RSSI;
356                 sc->sc_max_rssi = WI_LUCENT_MAX_RSSI;
357                 sc->sc_dbm_offset = WI_LUCENT_DBM_OFFSET;
358                 break;
359         case WI_INTERSIL:
360                 sc->sc_ntxbuf = WI_NTXBUF;
361                 sc->sc_flags |= WI_FLAGS_HAS_FRAGTHR
362                              |  WI_FLAGS_HAS_ROAMING;
363                 /*
364                  * Old firmware are slow, so give peace a chance.
365                  */
366                 if (sc->sc_sta_firmware_ver < 10000)
367                         sc->wi_cmd_count = 5000;
368                 if (sc->sc_sta_firmware_ver > 10101)
369                         sc->sc_flags |= WI_FLAGS_HAS_DBMADJUST;
370                 ic->ic_caps |= IEEE80211_C_IBSS;
371                 /*
372                  * version 0.8.3 and newer are the only ones that are known
373                  * to currently work.  Earlier versions can be made to work,
374                  * at least according to the Linux driver but we require
375                  * monitor mode so this is irrelevant.
376                  */
377                 ic->ic_caps |= IEEE80211_C_HOSTAP;
378                 if (sc->sc_sta_firmware_ver >= 10603)
379                         sc->sc_flags |= WI_FLAGS_HAS_ENHSECURITY;
380                 if (sc->sc_sta_firmware_ver >= 10700) {
381                         /*
382                          * 1.7.0+ have the necessary support for sta mode WPA.
383                          */
384                         sc->sc_flags |= WI_FLAGS_HAS_WPASUPPORT;
385                         ic->ic_caps |= IEEE80211_C_WPA;
386                 }
387
388                 sc->sc_ibss_port = WI_PORTTYPE_IBSS;
389                 sc->sc_monitor_port = WI_PORTTYPE_APSILENT;
390                 sc->sc_min_rssi = WI_PRISM_MIN_RSSI;
391                 sc->sc_max_rssi = WI_PRISM_MAX_RSSI;
392                 sc->sc_dbm_offset = WI_PRISM_DBM_OFFSET;
393                 break;
394         }
395
396         /*
397          * Find out if we support WEP on this card.
398          */
399         buflen = sizeof(val);
400         if (wi_read_rid(sc, WI_RID_WEP_AVAIL, &val, &buflen) == 0 &&
401             val != htole16(0))
402                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
403
404         /* Find supported rates. */
405         buflen = sizeof(ratebuf);
406         rs = &ic->ic_sup_rates[IEEE80211_MODE_11B];
407         if (wi_read_rid(sc, WI_RID_DATA_RATES, ratebuf, &buflen) == 0) {
408                 nrates = le16toh(*(u_int16_t *)ratebuf);
409                 if (nrates > IEEE80211_RATE_MAXSIZE)
410                         nrates = IEEE80211_RATE_MAXSIZE;
411                 rs->rs_nrates = 0;
412                 for (i = 0; i < nrates; i++)
413                         if (ratebuf[2+i])
414                                 rs->rs_rates[rs->rs_nrates++] = ratebuf[2+i];
415         } else {
416                 /* XXX fallback on error? */
417         }
418
419         buflen = sizeof(val);
420         if ((sc->sc_flags & WI_FLAGS_HAS_DBMADJUST) &&
421             wi_read_rid(sc, WI_RID_DBM_ADJUST, &val, &buflen) == 0) {
422                 sc->sc_dbm_offset = le16toh(val);
423         }
424
425         sc->sc_portnum = WI_DEFAULT_PORT;
426
427         ieee80211_ifattach(ic);
428         ic->ic_raw_xmit = wi_raw_xmit;
429         ic->ic_scan_start = wi_scan_start;
430         ic->ic_scan_end = wi_scan_end;
431         ic->ic_getradiocaps = wi_getradiocaps;
432         ic->ic_set_channel = wi_set_channel;
433         ic->ic_vap_create = wi_vap_create;
434         ic->ic_vap_delete = wi_vap_delete;
435         ic->ic_update_mcast = wi_update_mcast;
436         ic->ic_update_promisc = wi_update_promisc;
437         ic->ic_transmit = wi_transmit;
438         ic->ic_parent = wi_parent;
439
440         ieee80211_radiotap_attach(ic,
441             &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
442                 WI_TX_RADIOTAP_PRESENT,
443             &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
444                 WI_RX_RADIOTAP_PRESENT);
445
446         if (bootverbose)
447                 ieee80211_announce(ic);
448
449         error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
450             NULL, wi_intr, sc, &sc->wi_intrhand);
451         if (error) {
452                 device_printf(dev, "bus_setup_intr() failed! (%d)\n", error);
453                 ieee80211_ifdetach(ic);
454                 wi_free(dev);
455                 return error;
456         }
457
458         return (0);
459 }
460
461 int
462 wi_detach(device_t dev)
463 {
464         struct wi_softc *sc = device_get_softc(dev);
465         struct ieee80211com *ic = &sc->sc_ic;
466
467         WI_LOCK(sc);
468
469         /* check if device was removed */
470         sc->wi_gone |= !bus_child_present(dev);
471
472         wi_stop(sc, 0);
473         WI_UNLOCK(sc);
474         ieee80211_ifdetach(ic);
475
476         bus_teardown_intr(dev, sc->irq, sc->wi_intrhand);
477         wi_free(dev);
478         mbufq_drain(&sc->sc_snd);
479         mtx_destroy(&sc->sc_mtx);
480         return (0);
481 }
482
483 static struct ieee80211vap *
484 wi_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
485     enum ieee80211_opmode opmode, int flags,
486     const uint8_t bssid[IEEE80211_ADDR_LEN],
487     const uint8_t mac[IEEE80211_ADDR_LEN])
488 {
489         struct wi_softc *sc = ic->ic_softc;
490         struct wi_vap *wvp;
491         struct ieee80211vap *vap;
492
493         if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
494                 return NULL;
495         wvp = malloc(sizeof(struct wi_vap), M_80211_VAP, M_WAITOK | M_ZERO);
496
497         vap = &wvp->wv_vap;
498         ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid);
499
500         vap->iv_max_aid = WI_MAX_AID;
501
502         switch (opmode) {
503         case IEEE80211_M_STA:
504                 sc->sc_porttype = WI_PORTTYPE_BSS;
505                 wvp->wv_newstate = vap->iv_newstate;
506                 vap->iv_newstate = wi_newstate_sta;
507                 /* need to filter mgt frames to avoid confusing state machine */
508                 wvp->wv_recv_mgmt = vap->iv_recv_mgmt;
509                 vap->iv_recv_mgmt = wi_recv_mgmt;
510                 break;
511         case IEEE80211_M_IBSS:
512                 sc->sc_porttype = sc->sc_ibss_port;
513                 wvp->wv_newstate = vap->iv_newstate;
514                 vap->iv_newstate = wi_newstate_sta;
515                 break;
516         case IEEE80211_M_AHDEMO:
517                 sc->sc_porttype = WI_PORTTYPE_ADHOC;
518                 break;
519         case IEEE80211_M_HOSTAP:
520                 sc->sc_porttype = WI_PORTTYPE_HOSTAP;
521                 wvp->wv_newstate = vap->iv_newstate;
522                 vap->iv_newstate = wi_newstate_hostap;
523                 break;
524         case IEEE80211_M_MONITOR:
525                 sc->sc_porttype = sc->sc_monitor_port;
526                 break;
527         default:
528                 break;
529         }
530
531         /* complete setup */
532         ieee80211_vap_attach(vap, ieee80211_media_change, wi_media_status, mac);
533         ic->ic_opmode = opmode;
534         return vap;
535 }
536
537 static void
538 wi_vap_delete(struct ieee80211vap *vap)
539 {
540         struct wi_vap *wvp = WI_VAP(vap);
541
542         ieee80211_vap_detach(vap);
543         free(wvp, M_80211_VAP);
544 }
545
546 int
547 wi_shutdown(device_t dev)
548 {
549         struct wi_softc *sc = device_get_softc(dev);
550
551         WI_LOCK(sc);
552         wi_stop(sc, 1);
553         WI_UNLOCK(sc);
554         return (0);
555 }
556
557 void
558 wi_intr(void *arg)
559 {
560         struct wi_softc *sc = arg;
561         u_int16_t status;
562
563         WI_LOCK(sc);
564
565         if (sc->wi_gone || !sc->sc_enabled ||
566             (sc->sc_flags & WI_FLAGS_RUNNING) == 0) {
567                 CSR_WRITE_2(sc, WI_INT_EN, 0);
568                 CSR_WRITE_2(sc, WI_EVENT_ACK, 0xFFFF);
569                 WI_UNLOCK(sc);
570                 return;
571         }
572
573         /* Disable interrupts. */
574         CSR_WRITE_2(sc, WI_INT_EN, 0);
575
576         status = CSR_READ_2(sc, WI_EVENT_STAT);
577         if (status & WI_EV_RX)
578                 wi_rx_intr(sc);
579         if (status & WI_EV_ALLOC)
580                 wi_tx_intr(sc);
581         if (status & WI_EV_TX_EXC)
582                 wi_tx_ex_intr(sc);
583         if (status & WI_EV_INFO)
584                 wi_info_intr(sc);
585         if (mbufq_first(&sc->sc_snd) != NULL)
586                 wi_start(sc);
587
588         /* Re-enable interrupts. */
589         CSR_WRITE_2(sc, WI_INT_EN, WI_INTRS);
590
591         WI_UNLOCK(sc);
592
593         return;
594 }
595
596 static void
597 wi_enable(struct wi_softc *sc)
598 {
599         /* Enable interrupts */
600         CSR_WRITE_2(sc, WI_INT_EN, WI_INTRS);
601
602         /* enable port */
603         wi_cmd(sc, WI_CMD_ENABLE | sc->sc_portnum, 0, 0, 0);
604         sc->sc_enabled = 1;
605 }
606
607 static int
608 wi_setup_locked(struct wi_softc *sc, int porttype, int mode,
609         const uint8_t mac[IEEE80211_ADDR_LEN])
610 {
611         int i;
612
613         wi_reset(sc);
614
615         wi_write_val(sc, WI_RID_PORTTYPE, porttype);
616         wi_write_val(sc, WI_RID_CREATE_IBSS, mode);
617         wi_write_val(sc, WI_RID_MAX_DATALEN, 2304);
618         /* XXX IEEE80211_BPF_NOACK wants 0 */
619         wi_write_val(sc, WI_RID_ALT_RETRY_CNT, 2);
620         if (sc->sc_flags & WI_FLAGS_HAS_ROAMING)
621                 wi_write_val(sc, WI_RID_ROAMING_MODE, 3); /* NB: disabled */
622
623         wi_write_rid(sc, WI_RID_MAC_NODE, mac, IEEE80211_ADDR_LEN);
624
625         /* Allocate fids for the card */
626         sc->sc_buflen = IEEE80211_MAX_LEN + sizeof(struct wi_frame);
627         for (i = 0; i < sc->sc_ntxbuf; i++) {
628                 int error = wi_alloc_fid(sc, sc->sc_buflen,
629                     &sc->sc_txd[i].d_fid);
630                 if (error) {
631                         device_printf(sc->sc_dev,
632                             "tx buffer allocation failed (error %u)\n",
633                             error);
634                         return error;
635                 }
636                 sc->sc_txd[i].d_len = 0;
637         }
638         sc->sc_txcur = sc->sc_txnext = 0;
639
640         return 0;
641 }
642
643 void
644 wi_init(struct wi_softc *sc)
645 {
646         int wasenabled;
647
648         WI_LOCK_ASSERT(sc);
649
650         wasenabled = sc->sc_enabled;
651         if (wasenabled)
652                 wi_stop(sc, 1);
653
654         if (wi_setup_locked(sc, sc->sc_porttype, 3,
655             sc->sc_ic.ic_macaddr) != 0) {
656                 device_printf(sc->sc_dev, "interface not running\n");
657                 wi_stop(sc, 1);
658                 return;
659         }
660
661         sc->sc_flags |= WI_FLAGS_RUNNING;
662
663         callout_reset(&sc->sc_watchdog, hz, wi_watchdog, sc);
664
665         wi_enable(sc);                  /* Enable desired port */
666 }
667
668 void
669 wi_stop(struct wi_softc *sc, int disable)
670 {
671
672         WI_LOCK_ASSERT(sc);
673
674         if (sc->sc_enabled && !sc->wi_gone) {
675                 CSR_WRITE_2(sc, WI_INT_EN, 0);
676                 wi_cmd(sc, WI_CMD_DISABLE | sc->sc_portnum, 0, 0, 0);
677                 if (disable)
678                         sc->sc_enabled = 0;
679         } else if (sc->wi_gone && disable)      /* gone --> not enabled */
680                 sc->sc_enabled = 0;
681
682         callout_stop(&sc->sc_watchdog);
683         sc->sc_tx_timer = 0;
684         sc->sc_false_syns = 0;
685
686         sc->sc_flags &= ~WI_FLAGS_RUNNING;
687 }
688
689 static void
690 wi_getradiocaps(struct ieee80211com *ic,
691     int maxchans, int *nchans, struct ieee80211_channel chans[])
692 {
693         struct wi_softc *sc = ic->ic_softc;
694         u_int8_t bands[IEEE80211_MODE_BYTES];
695         int i;
696
697         memset(bands, 0, sizeof(bands));
698         setbit(bands, IEEE80211_MODE_11B);
699
700         for (i = 1; i < 16; i++) {
701                 if (sc->sc_chanmask & (1 << i)) {
702                         /* XXX txpowers? */
703                         ieee80211_add_channel(chans, maxchans, nchans,
704                             i, 0, 0, 0, bands);
705                 }
706         }
707 }
708
709 static void
710 wi_set_channel(struct ieee80211com *ic)
711 {
712         struct wi_softc *sc = ic->ic_softc;
713
714         DPRINTF(("%s: channel %d, %sscanning\n", __func__,
715             ieee80211_chan2ieee(ic, ic->ic_curchan),
716             ic->ic_flags & IEEE80211_F_SCAN ? "" : "!"));
717
718         WI_LOCK(sc);
719         wi_write_val(sc, WI_RID_OWN_CHNL,
720             ieee80211_chan2ieee(ic, ic->ic_curchan));
721         WI_UNLOCK(sc);
722 }
723
724 static void
725 wi_scan_start(struct ieee80211com *ic)
726 {
727         struct wi_softc *sc = ic->ic_softc;
728         struct ieee80211_scan_state *ss = ic->ic_scan;
729
730         DPRINTF(("%s\n", __func__));
731
732         WI_LOCK(sc);
733         /*
734          * Switch device to monitor mode.
735          */
736         wi_write_val(sc, WI_RID_PORTTYPE, sc->sc_monitor_port);
737         if (sc->sc_firmware_type == WI_INTERSIL) {
738                 wi_cmd(sc, WI_CMD_DISABLE | WI_PORT0, 0, 0, 0);
739                 wi_cmd(sc, WI_CMD_ENABLE | WI_PORT0, 0, 0, 0);
740         }
741         /* force full dwell time to compensate for firmware overhead */
742         ss->ss_mindwell = ss->ss_maxdwell = msecs_to_ticks(400);
743         WI_UNLOCK(sc);
744
745 }
746
747 static void
748 wi_scan_end(struct ieee80211com *ic)
749 {
750         struct wi_softc *sc = ic->ic_softc;
751
752         DPRINTF(("%s: restore port type %d\n", __func__, sc->sc_porttype));
753
754         WI_LOCK(sc);
755         wi_write_val(sc, WI_RID_PORTTYPE, sc->sc_porttype);
756         if (sc->sc_firmware_type == WI_INTERSIL) {
757                 wi_cmd(sc, WI_CMD_DISABLE | WI_PORT0, 0, 0, 0);
758                 wi_cmd(sc, WI_CMD_ENABLE | WI_PORT0, 0, 0, 0);
759         }
760         WI_UNLOCK(sc);
761 }
762
763 static void
764 wi_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
765         int subtype, const struct ieee80211_rx_stats *rxs, int rssi, int nf)
766 {
767         struct ieee80211vap *vap = ni->ni_vap;
768
769         switch (subtype) {
770         case IEEE80211_FC0_SUBTYPE_AUTH:
771         case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
772         case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
773                 /* NB: filter frames that trigger state changes */
774                 return;
775         }
776         WI_VAP(vap)->wv_recv_mgmt(ni, m, subtype, rxs, rssi, nf);
777 }
778
779 static int
780 wi_newstate_sta(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
781 {
782         struct ieee80211com *ic = vap->iv_ic;
783         struct ieee80211_node *bss;
784         struct wi_softc *sc = ic->ic_softc;
785
786         DPRINTF(("%s: %s -> %s\n", __func__,
787                 ieee80211_state_name[vap->iv_state],
788                 ieee80211_state_name[nstate]));
789
790         if (nstate == IEEE80211_S_AUTH) {
791                 WI_LOCK(sc);
792                 wi_setup_locked(sc, WI_PORTTYPE_BSS, 3, vap->iv_myaddr);
793
794                 if (vap->iv_flags & IEEE80211_F_PMGTON) {
795                         wi_write_val(sc, WI_RID_MAX_SLEEP, ic->ic_lintval);
796                         wi_write_val(sc, WI_RID_PM_ENABLED, 1);
797                 }
798                 wi_write_val(sc, WI_RID_RTS_THRESH, vap->iv_rtsthreshold);
799                 if (sc->sc_flags & WI_FLAGS_HAS_FRAGTHR)
800                         wi_write_val(sc, WI_RID_FRAG_THRESH,
801                             vap->iv_fragthreshold);
802                 wi_write_txrate(sc, vap);
803
804                 bss = vap->iv_bss;
805                 wi_write_ssid(sc, WI_RID_DESIRED_SSID, bss->ni_essid, bss->ni_esslen);
806                 wi_write_val(sc, WI_RID_OWN_CHNL,
807                     ieee80211_chan2ieee(ic, bss->ni_chan));
808
809                 /* Configure WEP. */
810                 if (ic->ic_cryptocaps & IEEE80211_CRYPTO_WEP)
811                         wi_write_wep(sc, vap);
812                 else
813                         sc->sc_encryption = 0;
814
815                 if ((sc->sc_flags & WI_FLAGS_HAS_WPASUPPORT) &&
816                     (vap->iv_flags & IEEE80211_F_WPA)) {
817                         wi_write_val(sc, WI_RID_WPA_HANDLING, 1);
818                         if (vap->iv_appie_wpa != NULL)
819                                 wi_write_appie(sc, WI_RID_WPA_DATA,
820                                     vap->iv_appie_wpa);
821                 }
822
823                 wi_enable(sc);          /* enable port */
824
825                 /* Lucent firmware does not support the JOIN RID. */
826                 if (sc->sc_firmware_type == WI_INTERSIL) {
827                         struct wi_joinreq join;
828
829                         memset(&join, 0, sizeof(join));
830                         IEEE80211_ADDR_COPY(&join.wi_bssid, bss->ni_bssid);
831                         join.wi_chan = htole16(
832                             ieee80211_chan2ieee(ic, bss->ni_chan));
833                         wi_write_rid(sc, WI_RID_JOIN_REQ, &join, sizeof(join));
834                 }
835                 WI_UNLOCK(sc);
836
837                 /*
838                  * NB: don't go through 802.11 layer, it'll send auth frame;
839                  * instead we drive the state machine from the link status
840                  * notification we get on association.
841                  */
842                 vap->iv_state = nstate;
843                 return (0);
844         }
845         return WI_VAP(vap)->wv_newstate(vap, nstate, arg);
846 }
847
848 static int
849 wi_newstate_hostap(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
850 {
851         struct ieee80211com *ic = vap->iv_ic;
852         struct ieee80211_node *bss;
853         struct wi_softc *sc = ic->ic_softc;
854         int error;
855
856         DPRINTF(("%s: %s -> %s\n", __func__,
857                 ieee80211_state_name[vap->iv_state],
858                 ieee80211_state_name[nstate]));
859
860         error = WI_VAP(vap)->wv_newstate(vap, nstate, arg);
861         if (error == 0 && nstate == IEEE80211_S_RUN) {
862                 WI_LOCK(sc);
863                 wi_setup_locked(sc, WI_PORTTYPE_HOSTAP, 0, vap->iv_myaddr);
864
865                 bss = vap->iv_bss;
866                 wi_write_ssid(sc, WI_RID_OWN_SSID,
867                     bss->ni_essid, bss->ni_esslen);
868                 wi_write_val(sc, WI_RID_OWN_CHNL,
869                     ieee80211_chan2ieee(ic, bss->ni_chan));
870                 wi_write_val(sc, WI_RID_BASIC_RATE, 0x3);
871                 wi_write_val(sc, WI_RID_SUPPORT_RATE, 0xf);
872                 wi_write_txrate(sc, vap);
873
874                 wi_write_val(sc, WI_RID_OWN_BEACON_INT, bss->ni_intval);
875                 wi_write_val(sc, WI_RID_DTIM_PERIOD, vap->iv_dtim_period);
876
877                 wi_write_val(sc, WI_RID_RTS_THRESH, vap->iv_rtsthreshold);
878                 if (sc->sc_flags & WI_FLAGS_HAS_FRAGTHR)
879                         wi_write_val(sc, WI_RID_FRAG_THRESH,
880                             vap->iv_fragthreshold);
881
882                 if ((sc->sc_flags & WI_FLAGS_HAS_ENHSECURITY) &&
883                     (vap->iv_flags & IEEE80211_F_HIDESSID)) {
884                         /*
885                          * bit 0 means hide SSID in beacons,
886                          * bit 1 means don't respond to bcast probe req
887                          */
888                         wi_write_val(sc, WI_RID_ENH_SECURITY, 0x3);
889                 }
890
891                 if ((sc->sc_flags & WI_FLAGS_HAS_WPASUPPORT) &&
892                     (vap->iv_flags & IEEE80211_F_WPA) && 
893                     vap->iv_appie_wpa != NULL)
894                         wi_write_appie(sc, WI_RID_WPA_DATA, vap->iv_appie_wpa);
895
896                 wi_write_val(sc, WI_RID_PROMISC, 0);
897
898                 /* Configure WEP. */
899                 if (ic->ic_cryptocaps & IEEE80211_CRYPTO_WEP)
900                         wi_write_wep(sc, vap);
901                 else
902                         sc->sc_encryption = 0;
903
904                 wi_enable(sc);          /* enable port */
905                 WI_UNLOCK(sc);
906         }
907         return error;
908 }
909
910 static int
911 wi_transmit(struct ieee80211com *ic, struct mbuf *m)
912 {
913         struct wi_softc *sc = ic->ic_softc;
914         int error;
915
916         WI_LOCK(sc);
917         if ((sc->sc_flags & WI_FLAGS_RUNNING) == 0) {
918                 WI_UNLOCK(sc);
919                 return (ENXIO);
920         }
921         error = mbufq_enqueue(&sc->sc_snd, m);
922         if (error) {
923                 WI_UNLOCK(sc);
924                 return (error);
925         }
926         wi_start(sc);
927         WI_UNLOCK(sc);
928         return (0);
929 }
930
931 static void
932 wi_start(struct wi_softc *sc)
933 {
934         struct ieee80211_node *ni;
935         struct ieee80211_frame *wh;
936         struct mbuf *m0;
937         struct ieee80211_key *k;
938         struct wi_frame frmhdr;
939         const struct llc *llc;
940         int cur;
941
942         WI_LOCK_ASSERT(sc);
943
944         if (sc->wi_gone)
945                 return;
946
947         memset(&frmhdr, 0, sizeof(frmhdr));
948         cur = sc->sc_txnext;
949         while (sc->sc_txd[cur].d_len == 0 &&
950             (m0 = mbufq_dequeue(&sc->sc_snd)) != NULL) {
951                 ni = (struct ieee80211_node *) m0->m_pkthdr.rcvif;
952
953                 /* reconstruct 802.3 header */
954                 wh = mtod(m0, struct ieee80211_frame *);
955                 switch (wh->i_fc[1]) {
956                 case IEEE80211_FC1_DIR_TODS:
957                         IEEE80211_ADDR_COPY(frmhdr.wi_ehdr.ether_shost,
958                             wh->i_addr2);
959                         IEEE80211_ADDR_COPY(frmhdr.wi_ehdr.ether_dhost,
960                             wh->i_addr3);
961                         break;
962                 case IEEE80211_FC1_DIR_NODS:
963                         IEEE80211_ADDR_COPY(frmhdr.wi_ehdr.ether_shost,
964                             wh->i_addr2);
965                         IEEE80211_ADDR_COPY(frmhdr.wi_ehdr.ether_dhost,
966                             wh->i_addr1);
967                         break;
968                 case IEEE80211_FC1_DIR_FROMDS:
969                         IEEE80211_ADDR_COPY(frmhdr.wi_ehdr.ether_shost,
970                             wh->i_addr3);
971                         IEEE80211_ADDR_COPY(frmhdr.wi_ehdr.ether_dhost,
972                             wh->i_addr1);
973                         break;
974                 }
975                 llc = (const struct llc *)(
976                     mtod(m0, const uint8_t *) + ieee80211_hdrsize(wh));
977                 frmhdr.wi_ehdr.ether_type = llc->llc_snap.ether_type;
978                 frmhdr.wi_tx_ctl = htole16(WI_ENC_TX_802_11|WI_TXCNTL_TX_EX);
979                 if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
980                         k = ieee80211_crypto_encap(ni, m0);
981                         if (k == NULL) {
982                                 ieee80211_free_node(ni);
983                                 m_freem(m0);
984                                 continue;
985                         }
986                         frmhdr.wi_tx_ctl |= htole16(WI_TXCNTL_NOCRYPT);
987                 }
988
989                 if (ieee80211_radiotap_active_vap(ni->ni_vap)) {
990                         sc->sc_tx_th.wt_rate = ni->ni_txrate;
991                         ieee80211_radiotap_tx(ni->ni_vap, m0);
992                 }
993
994                 m_copydata(m0, 0, sizeof(struct ieee80211_frame),
995                     (caddr_t)&frmhdr.wi_whdr);
996                 m_adj(m0, sizeof(struct ieee80211_frame));
997                 frmhdr.wi_dat_len = htole16(m0->m_pkthdr.len);
998                 ieee80211_free_node(ni);
999                 if (wi_start_tx(sc, &frmhdr, m0))
1000                         continue;
1001
1002                 sc->sc_txnext = cur = (cur + 1) % sc->sc_ntxbuf;
1003         }
1004 }
1005
1006 static int
1007 wi_start_tx(struct wi_softc *sc, struct wi_frame *frmhdr, struct mbuf *m0)
1008 {
1009         int cur = sc->sc_txnext;
1010         int fid, off, error;
1011
1012         fid = sc->sc_txd[cur].d_fid;
1013         off = sizeof(*frmhdr);
1014         error = wi_write_bap(sc, fid, 0, frmhdr, sizeof(*frmhdr)) != 0
1015              || wi_mwrite_bap(sc, fid, off, m0, m0->m_pkthdr.len) != 0;
1016         m_freem(m0);
1017         if (error) {
1018                 counter_u64_add(sc->sc_ic.ic_oerrors, 1);
1019                 return -1;
1020         }
1021         sc->sc_txd[cur].d_len = off;
1022         if (sc->sc_txcur == cur) {
1023                 if (wi_cmd(sc, WI_CMD_TX | WI_RECLAIM, fid, 0, 0)) {
1024                         device_printf(sc->sc_dev, "xmit failed\n");
1025                         sc->sc_txd[cur].d_len = 0;
1026                         return -1;
1027                 }
1028                 sc->sc_tx_timer = 5;
1029         }
1030         return 0;
1031 }
1032
1033 static int
1034 wi_raw_xmit(struct ieee80211_node *ni, struct mbuf *m0,
1035             const struct ieee80211_bpf_params *params)
1036 {
1037         struct ieee80211com *ic = ni->ni_ic;
1038         struct ieee80211vap *vap = ni->ni_vap;
1039         struct wi_softc *sc = ic->ic_softc;
1040         struct ieee80211_key *k;
1041         struct ieee80211_frame *wh;
1042         struct wi_frame frmhdr;
1043         int cur;
1044         int rc = 0;
1045
1046         WI_LOCK(sc);
1047
1048         if (sc->wi_gone) {
1049                 rc = ENETDOWN;
1050                 goto out;
1051         }
1052         memset(&frmhdr, 0, sizeof(frmhdr));
1053         cur = sc->sc_txnext;
1054         if (sc->sc_txd[cur].d_len != 0) {
1055                 rc = ENOBUFS;
1056                 goto out;
1057         }
1058         m0->m_pkthdr.rcvif = NULL;
1059
1060         m_copydata(m0, 4, ETHER_ADDR_LEN * 2,
1061             (caddr_t)&frmhdr.wi_ehdr);
1062         frmhdr.wi_ehdr.ether_type = 0;
1063         wh = mtod(m0, struct ieee80211_frame *);
1064                         
1065         frmhdr.wi_tx_ctl = htole16(WI_ENC_TX_802_11|WI_TXCNTL_TX_EX);
1066         if (params && (params->ibp_flags & IEEE80211_BPF_NOACK))
1067                 frmhdr.wi_tx_ctl |= htole16(WI_TXCNTL_ALTRTRY);
1068         if ((wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
1069             (!params || (params && (params->ibp_flags & IEEE80211_BPF_CRYPTO)))) {
1070                 k = ieee80211_crypto_encap(ni, m0);
1071                 if (k == NULL) {
1072                         rc = ENOMEM;
1073                         goto out;
1074                 }
1075                 frmhdr.wi_tx_ctl |= htole16(WI_TXCNTL_NOCRYPT);
1076         }
1077         if (ieee80211_radiotap_active_vap(vap)) {
1078                 sc->sc_tx_th.wt_rate = ni->ni_txrate;
1079                 ieee80211_radiotap_tx(vap, m0);
1080         }
1081         m_copydata(m0, 0, sizeof(struct ieee80211_frame),
1082             (caddr_t)&frmhdr.wi_whdr);
1083         m_adj(m0, sizeof(struct ieee80211_frame));
1084         frmhdr.wi_dat_len = htole16(m0->m_pkthdr.len);
1085         if (wi_start_tx(sc, &frmhdr, m0) < 0) {
1086                 m0 = NULL;
1087                 rc = EIO;
1088                 goto out;
1089         }
1090         m0 = NULL;
1091         ieee80211_free_node(ni);
1092
1093         sc->sc_txnext = cur = (cur + 1) % sc->sc_ntxbuf;
1094 out:
1095         WI_UNLOCK(sc);
1096
1097         if (m0 != NULL)
1098                 m_freem(m0);
1099         return rc;
1100 }
1101
1102 static int
1103 wi_reset(struct wi_softc *sc)
1104 {
1105 #define WI_INIT_TRIES 3
1106         int i, error = 0;
1107
1108         for (i = 0; i < WI_INIT_TRIES; i++) {
1109                 error = wi_cmd(sc, WI_CMD_INI, 0, 0, 0);
1110                 if (error == 0)
1111                         break;
1112                 DELAY(WI_DELAY * 1000);
1113         }
1114         sc->sc_reset = 1;
1115         if (i == WI_INIT_TRIES) {
1116                 device_printf(sc->sc_dev, "reset failed\n");
1117                 return error;
1118         }
1119
1120         CSR_WRITE_2(sc, WI_INT_EN, 0);
1121         CSR_WRITE_2(sc, WI_EVENT_ACK, 0xFFFF);
1122
1123         /* Calibrate timer. */
1124         wi_write_val(sc, WI_RID_TICK_TIME, 8);
1125
1126         return 0;
1127 #undef WI_INIT_TRIES
1128 }
1129
1130 static void
1131 wi_watchdog(void *arg)
1132 {
1133         struct wi_softc *sc = arg;
1134
1135         WI_LOCK_ASSERT(sc);
1136
1137         if (!sc->sc_enabled)
1138                 return;
1139
1140         if (sc->sc_tx_timer && --sc->sc_tx_timer == 0) {
1141                 device_printf(sc->sc_dev, "device timeout\n");
1142                 counter_u64_add(sc->sc_ic.ic_oerrors, 1);
1143                 wi_init(sc);
1144                 return;
1145         }
1146         callout_reset(&sc->sc_watchdog, hz, wi_watchdog, sc);
1147 }
1148
1149 static void
1150 wi_parent(struct ieee80211com *ic)
1151 {
1152         struct wi_softc *sc = ic->ic_softc;
1153         int startall = 0;
1154
1155         WI_LOCK(sc);
1156         /*
1157          * Can't do promisc and hostap at the same time.  If all that's
1158          * changing is the promisc flag, try to short-circuit a call to
1159          * wi_init() by just setting PROMISC in the hardware.
1160          */
1161         if (ic->ic_nrunning > 0) {
1162                 if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
1163                     sc->sc_flags & WI_FLAGS_RUNNING) {
1164                         if (ic->ic_promisc > 0 &&
1165                             (sc->sc_flags & WI_FLAGS_PROMISC) == 0) {
1166                                 wi_write_val(sc, WI_RID_PROMISC, 1);
1167                                 sc->sc_flags |= WI_FLAGS_PROMISC;
1168                         } else if (ic->ic_promisc == 0 &&
1169                             (sc->sc_flags & WI_FLAGS_PROMISC) != 0) {
1170                                 wi_write_val(sc, WI_RID_PROMISC, 0);
1171                                 sc->sc_flags &= ~WI_FLAGS_PROMISC;
1172                         } else {
1173                                 wi_init(sc);
1174                                 startall = 1;
1175                         }
1176                 } else {
1177                         wi_init(sc);
1178                         startall = 1;
1179                 }
1180         } else if (sc->sc_flags & WI_FLAGS_RUNNING) {
1181                 wi_stop(sc, 1);
1182                 sc->wi_gone = 0;
1183         }
1184         WI_UNLOCK(sc);
1185         if (startall)
1186                 ieee80211_start_all(ic);
1187 }
1188
1189 static void
1190 wi_media_status(struct ifnet *ifp, struct ifmediareq *imr)
1191 {
1192         struct ieee80211vap *vap = ifp->if_softc;
1193         struct ieee80211com *ic = vap->iv_ic;
1194         struct wi_softc *sc = ic->ic_softc;
1195         u_int16_t val;
1196         int rate, len;
1197
1198         len = sizeof(val);
1199         if (sc->sc_enabled &&
1200             wi_read_rid(sc, WI_RID_CUR_TX_RATE, &val, &len) == 0 &&
1201             len == sizeof(val)) {
1202                 /* convert to 802.11 rate */
1203                 val = le16toh(val);
1204                 rate = val * 2;
1205                 if (sc->sc_firmware_type == WI_LUCENT) {
1206                         if (rate == 10)
1207                                 rate = 11;      /* 5.5Mbps */
1208                 } else {
1209                         if (rate == 4*2)
1210                                 rate = 11;      /* 5.5Mbps */
1211                         else if (rate == 8*2)
1212                                 rate = 22;      /* 11Mbps */
1213                 }
1214                 vap->iv_bss->ni_txrate = rate;
1215         }
1216         ieee80211_media_status(ifp, imr);
1217 }
1218
1219 static void
1220 wi_sync_bssid(struct wi_softc *sc, u_int8_t new_bssid[IEEE80211_ADDR_LEN])
1221 {
1222         struct ieee80211com *ic = &sc->sc_ic;
1223         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1224         struct ieee80211_node *ni = vap->iv_bss;
1225
1226         if (IEEE80211_ADDR_EQ(new_bssid, ni->ni_bssid))
1227                 return;
1228
1229         DPRINTF(("wi_sync_bssid: bssid %s -> ", ether_sprintf(ni->ni_bssid)));
1230         DPRINTF(("%s ?\n", ether_sprintf(new_bssid)));
1231
1232         /* In promiscuous mode, the BSSID field is not a reliable
1233          * indicator of the firmware's BSSID. Damp spurious
1234          * change-of-BSSID indications.
1235          */
1236         if (ic->ic_promisc > 0 &&
1237             !ppsratecheck(&sc->sc_last_syn, &sc->sc_false_syns,
1238                          WI_MAX_FALSE_SYNS))
1239                 return;
1240
1241         sc->sc_false_syns = MAX(0, sc->sc_false_syns - 1);
1242 #if 0
1243         /*
1244          * XXX hack; we should create a new node with the new bssid
1245          * and replace the existing ic_bss with it but since we don't
1246          * process management frames to collect state we cheat by
1247          * reusing the existing node as we know wi_newstate will be
1248          * called and it will overwrite the node state.
1249          */
1250         ieee80211_sta_join(ic, ieee80211_ref_node(ni));
1251 #endif
1252 }
1253
1254 static __noinline void
1255 wi_rx_intr(struct wi_softc *sc)
1256 {
1257         struct epoch_tracker et;
1258         struct ieee80211com *ic = &sc->sc_ic;
1259         struct wi_frame frmhdr;
1260         struct mbuf *m;
1261         struct ieee80211_frame *wh;
1262         struct ieee80211_node *ni;
1263         int fid, len, off;
1264         u_int8_t dir;
1265         u_int16_t status;
1266         int8_t rssi, nf;
1267
1268         fid = CSR_READ_2(sc, WI_RX_FID);
1269
1270         /* First read in the frame header */
1271         if (wi_read_bap(sc, fid, 0, &frmhdr, sizeof(frmhdr))) {
1272                 CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_RX);
1273                 counter_u64_add(ic->ic_ierrors, 1);
1274                 DPRINTF(("wi_rx_intr: read fid %x failed\n", fid));
1275                 return;
1276         }
1277
1278         /*
1279          * Drop undecryptable or packets with receive errors here
1280          */
1281         status = le16toh(frmhdr.wi_status);
1282         if (status & WI_STAT_ERRSTAT) {
1283                 CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_RX);
1284                 counter_u64_add(ic->ic_ierrors, 1);
1285                 DPRINTF(("wi_rx_intr: fid %x error status %x\n", fid, status));
1286                 return;
1287         }
1288
1289         len = le16toh(frmhdr.wi_dat_len);
1290         off = ALIGN(sizeof(struct ieee80211_frame));
1291
1292         /*
1293          * Sometimes the PRISM2.x returns bogusly large frames. Except
1294          * in monitor mode, just throw them away.
1295          */
1296         if (off + len > MCLBYTES) {
1297                 if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1298                         CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_RX);
1299                         counter_u64_add(ic->ic_ierrors, 1);
1300                         DPRINTF(("wi_rx_intr: oversized packet\n"));
1301                         return;
1302                 } else
1303                         len = 0;
1304         }
1305
1306         if (off + len > MHLEN)
1307                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1308         else
1309                 m = m_gethdr(M_NOWAIT, MT_DATA);
1310         if (m == NULL) {
1311                 CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_RX);
1312                 counter_u64_add(ic->ic_ierrors, 1);
1313                 DPRINTF(("wi_rx_intr: MGET failed\n"));
1314                 return;
1315         }
1316         m->m_data += off - sizeof(struct ieee80211_frame);
1317         memcpy(m->m_data, &frmhdr.wi_whdr, sizeof(struct ieee80211_frame));
1318         wi_read_bap(sc, fid, sizeof(frmhdr),
1319             m->m_data + sizeof(struct ieee80211_frame), len);
1320         m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame) + len;
1321
1322         CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_RX);
1323
1324         rssi = frmhdr.wi_rx_signal;
1325         nf = frmhdr.wi_rx_silence;
1326         if (ieee80211_radiotap_active(ic)) {
1327                 struct wi_rx_radiotap_header *tap = &sc->sc_rx_th;
1328                 uint32_t rstamp;
1329
1330                 rstamp = (le16toh(frmhdr.wi_rx_tstamp0) << 16) |
1331                     le16toh(frmhdr.wi_rx_tstamp1);
1332                 tap->wr_tsf = htole64((uint64_t)rstamp);
1333                 /* XXX replace divide by table */
1334                 tap->wr_rate = frmhdr.wi_rx_rate / 5;
1335                 tap->wr_flags = 0;
1336                 if (frmhdr.wi_status & WI_STAT_PCF)
1337                         tap->wr_flags |= IEEE80211_RADIOTAP_F_CFP;
1338                 if (m->m_flags & M_WEP)
1339                         tap->wr_flags |= IEEE80211_RADIOTAP_F_WEP;
1340                 tap->wr_antsignal = rssi;
1341                 tap->wr_antnoise = nf;
1342         }
1343
1344         /* synchronize driver's BSSID with firmware's BSSID */
1345         wh = mtod(m, struct ieee80211_frame *);
1346         dir = wh->i_fc[1] & IEEE80211_FC1_DIR_MASK;
1347         if (ic->ic_opmode == IEEE80211_M_IBSS && dir == IEEE80211_FC1_DIR_NODS)
1348                 wi_sync_bssid(sc, wh->i_addr3);
1349
1350         WI_UNLOCK(sc);
1351
1352         ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *));
1353
1354         NET_EPOCH_ENTER(et);
1355         if (ni != NULL) {
1356                 (void) ieee80211_input(ni, m, rssi, nf);
1357                 ieee80211_free_node(ni);
1358         } else
1359                 (void) ieee80211_input_all(ic, m, rssi, nf);
1360         NET_EPOCH_EXIT(et);
1361
1362         WI_LOCK(sc);
1363 }
1364
1365 static __noinline void
1366 wi_tx_ex_intr(struct wi_softc *sc)
1367 {
1368         struct wi_frame frmhdr;
1369         int fid;
1370
1371         fid = CSR_READ_2(sc, WI_TX_CMP_FID);
1372         /* Read in the frame header */
1373         if (wi_read_bap(sc, fid, 0, &frmhdr, sizeof(frmhdr)) == 0) {
1374                 u_int16_t status = le16toh(frmhdr.wi_status);
1375                 /*
1376                  * Spontaneous station disconnects appear as xmit
1377                  * errors.  Don't announce them and/or count them
1378                  * as an output error.
1379                  */
1380                 if ((status & WI_TXSTAT_DISCONNECT) == 0) {
1381                         if (ppsratecheck(&lasttxerror, &curtxeps, wi_txerate)) {
1382                                 device_printf(sc->sc_dev, "tx failed");
1383                                 if (status & WI_TXSTAT_RET_ERR)
1384                                         printf(", retry limit exceeded");
1385                                 if (status & WI_TXSTAT_AGED_ERR)
1386                                         printf(", max transmit lifetime exceeded");
1387                                 if (status & WI_TXSTAT_DISCONNECT)
1388                                         printf(", port disconnected");
1389                                 if (status & WI_TXSTAT_FORM_ERR)
1390                                         printf(", invalid format (data len %u src %6D)",
1391                                                 le16toh(frmhdr.wi_dat_len),
1392                                                 frmhdr.wi_ehdr.ether_shost, ":");
1393                                 if (status & ~0xf)
1394                                         printf(", status=0x%x", status);
1395                                 printf("\n");
1396                         }
1397                         counter_u64_add(sc->sc_ic.ic_oerrors, 1);
1398                 } else
1399                         DPRINTF(("port disconnected\n"));
1400         } else
1401                 DPRINTF(("wi_tx_ex_intr: read fid %x failed\n", fid));
1402         CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_TX_EXC);
1403 }
1404
1405 static __noinline void
1406 wi_tx_intr(struct wi_softc *sc)
1407 {
1408         int fid, cur;
1409
1410         if (sc->wi_gone)
1411                 return;
1412
1413         fid = CSR_READ_2(sc, WI_ALLOC_FID);
1414         CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_ALLOC);
1415
1416         cur = sc->sc_txcur;
1417         if (sc->sc_txd[cur].d_fid != fid) {
1418                 device_printf(sc->sc_dev, "bad alloc %x != %x, cur %d nxt %d\n",
1419                     fid, sc->sc_txd[cur].d_fid, cur, sc->sc_txnext);
1420                 return;
1421         }
1422         sc->sc_tx_timer = 0;
1423         sc->sc_txd[cur].d_len = 0;
1424         sc->sc_txcur = cur = (cur + 1) % sc->sc_ntxbuf;
1425         if (sc->sc_txd[cur].d_len != 0) {
1426                 if (wi_cmd(sc, WI_CMD_TX | WI_RECLAIM, sc->sc_txd[cur].d_fid,
1427                     0, 0)) {
1428                         device_printf(sc->sc_dev, "xmit failed\n");
1429                         sc->sc_txd[cur].d_len = 0;
1430                 } else {
1431                         sc->sc_tx_timer = 5;
1432                 }
1433         }
1434 }
1435
1436 static __noinline void
1437 wi_info_intr(struct wi_softc *sc)
1438 {
1439         struct ieee80211com *ic = &sc->sc_ic;
1440         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1441         int i, fid, len, off;
1442         u_int16_t ltbuf[2];
1443         u_int16_t stat;
1444         u_int32_t *ptr;
1445
1446         fid = CSR_READ_2(sc, WI_INFO_FID);
1447         wi_read_bap(sc, fid, 0, ltbuf, sizeof(ltbuf));
1448
1449         switch (le16toh(ltbuf[1])) {
1450         case WI_INFO_LINK_STAT:
1451                 wi_read_bap(sc, fid, sizeof(ltbuf), &stat, sizeof(stat));
1452                 DPRINTF(("wi_info_intr: LINK_STAT 0x%x\n", le16toh(stat)));
1453
1454                 if (vap == NULL)
1455                         goto finish;
1456
1457                 switch (le16toh(stat)) {
1458                 case WI_INFO_LINK_STAT_CONNECTED:
1459                         if (vap->iv_state == IEEE80211_S_RUN &&
1460                             vap->iv_opmode != IEEE80211_M_IBSS)
1461                                 break;
1462                         /* fall thru... */
1463                 case WI_INFO_LINK_STAT_AP_CHG:
1464                         IEEE80211_LOCK(ic);
1465                         vap->iv_bss->ni_associd = 1 | 0xc000;   /* NB: anything will do */
1466                         ieee80211_new_state(vap, IEEE80211_S_RUN, 0);
1467                         IEEE80211_UNLOCK(ic);
1468                         break;
1469                 case WI_INFO_LINK_STAT_AP_INR:
1470                         break;
1471                 case WI_INFO_LINK_STAT_DISCONNECTED:
1472                         /* we dropped off the net; e.g. due to deauth/disassoc */
1473                         IEEE80211_LOCK(ic);
1474                         vap->iv_bss->ni_associd = 0;
1475                         vap->iv_stats.is_rx_deauth++;
1476                         ieee80211_new_state(vap, IEEE80211_S_SCAN, 0);
1477                         IEEE80211_UNLOCK(ic);
1478                         break;
1479                 case WI_INFO_LINK_STAT_AP_OOR:
1480                         /* XXX does this need to be per-vap? */
1481                         ieee80211_beacon_miss(ic);
1482                         break;
1483                 case WI_INFO_LINK_STAT_ASSOC_FAILED:
1484                         if (vap->iv_opmode == IEEE80211_M_STA)
1485                                 ieee80211_new_state(vap, IEEE80211_S_SCAN,
1486                                     IEEE80211_SCAN_FAIL_TIMEOUT);
1487                         break;
1488                 }
1489                 break;
1490         case WI_INFO_COUNTERS:
1491                 /* some card versions have a larger stats structure */
1492                 len = min(le16toh(ltbuf[0]) - 1, sizeof(sc->sc_stats) / 4);
1493                 ptr = (u_int32_t *)&sc->sc_stats;
1494                 off = sizeof(ltbuf);
1495                 for (i = 0; i < len; i++, off += 2, ptr++) {
1496                         wi_read_bap(sc, fid, off, &stat, sizeof(stat));
1497 #ifdef WI_HERMES_STATS_WAR
1498                         if (stat & 0xf000)
1499                                 stat = ~stat;
1500 #endif
1501                         *ptr += stat;
1502                 }
1503                 break;
1504         default:
1505                 DPRINTF(("wi_info_intr: got fid %x type %x len %d\n", fid,
1506                     le16toh(ltbuf[1]), le16toh(ltbuf[0])));
1507                 break;
1508         }
1509 finish:
1510         CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_INFO);
1511 }
1512
1513 struct wi_mcast_ctx {
1514         struct wi_mcast mlist;
1515         int mcnt;
1516 };
1517
1518 static u_int
1519 wi_copy_mcast(void *arg, struct sockaddr_dl *sdl, u_int count)
1520 {
1521         struct wi_mcast_ctx *ctx = arg;
1522
1523         if (ctx->mcnt >= 16)
1524                 return (0);
1525         IEEE80211_ADDR_COPY(&ctx->mlist.wi_mcast[ctx->mcnt++], LLADDR(sdl));
1526
1527         return (1);
1528 }
1529
1530 static int
1531 wi_write_multi(struct wi_softc *sc)
1532 {
1533         struct ieee80211com *ic = &sc->sc_ic;
1534         struct ieee80211vap *vap;
1535         struct wi_mcast_ctx ctx;
1536
1537         if (ic->ic_allmulti > 0 || ic->ic_promisc > 0) {
1538 allmulti:
1539                 memset(&ctx.mlist, 0, sizeof(ctx.mlist));
1540                 return wi_write_rid(sc, WI_RID_MCAST_LIST, &ctx.mlist,
1541                     sizeof(ctx.mlist));
1542         }
1543
1544         ctx.mcnt = 0;
1545         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1546                 if_foreach_llmaddr(vap->iv_ifp, wi_copy_mcast, &ctx);
1547                 if (ctx.mcnt >= 16)
1548                         goto allmulti;
1549         }
1550         return wi_write_rid(sc, WI_RID_MCAST_LIST, &ctx.mlist,
1551             IEEE80211_ADDR_LEN * ctx.mcnt);
1552 }
1553
1554 static void
1555 wi_update_mcast(struct ieee80211com *ic)
1556 {
1557
1558         wi_write_multi(ic->ic_softc);
1559 }
1560
1561 static void
1562 wi_update_promisc(struct ieee80211com *ic)
1563 {
1564         struct wi_softc *sc = ic->ic_softc;
1565
1566         WI_LOCK(sc);
1567         /* XXX handle WEP special case handling? */
1568         wi_write_val(sc, WI_RID_PROMISC, 
1569             (ic->ic_opmode == IEEE80211_M_MONITOR ||
1570              (ic->ic_promisc > 0)));
1571         WI_UNLOCK(sc);
1572 }
1573
1574 static void
1575 wi_read_nicid(struct wi_softc *sc)
1576 {
1577         struct wi_card_ident *id;
1578         char *p;
1579         int len;
1580         u_int16_t ver[4];
1581
1582         /* getting chip identity */
1583         memset(ver, 0, sizeof(ver));
1584         len = sizeof(ver);
1585         wi_read_rid(sc, WI_RID_CARD_ID, ver, &len);
1586
1587         sc->sc_firmware_type = WI_NOTYPE;
1588         sc->sc_nic_id = le16toh(ver[0]);
1589         for (id = wi_card_ident; id->card_name != NULL; id++) {
1590                 if (sc->sc_nic_id == id->card_id) {
1591                         sc->sc_nic_name = id->card_name;
1592                         sc->sc_firmware_type = id->firm_type;
1593                         break;
1594                 }
1595         }
1596         if (sc->sc_firmware_type == WI_NOTYPE) {
1597                 if (sc->sc_nic_id & 0x8000) {
1598                         sc->sc_firmware_type = WI_INTERSIL;
1599                         sc->sc_nic_name = "Unknown Prism chip";
1600                 } else {
1601                         sc->sc_firmware_type = WI_LUCENT;
1602                         sc->sc_nic_name = "Unknown Lucent chip";
1603                 }
1604         }
1605         if (bootverbose)
1606                 device_printf(sc->sc_dev, "using %s\n", sc->sc_nic_name);
1607
1608         /* get primary firmware version (Only Prism chips) */
1609         if (sc->sc_firmware_type != WI_LUCENT) {
1610                 memset(ver, 0, sizeof(ver));
1611                 len = sizeof(ver);
1612                 wi_read_rid(sc, WI_RID_PRI_IDENTITY, ver, &len);
1613                 sc->sc_pri_firmware_ver = le16toh(ver[2]) * 10000 +
1614                     le16toh(ver[3]) * 100 + le16toh(ver[1]);
1615         }
1616
1617         /* get station firmware version */
1618         memset(ver, 0, sizeof(ver));
1619         len = sizeof(ver);
1620         wi_read_rid(sc, WI_RID_STA_IDENTITY, ver, &len);
1621         sc->sc_sta_firmware_ver = le16toh(ver[2]) * 10000 +
1622             le16toh(ver[3]) * 100 + le16toh(ver[1]);
1623         if (sc->sc_firmware_type == WI_INTERSIL &&
1624             (sc->sc_sta_firmware_ver == 10102 ||
1625              sc->sc_sta_firmware_ver == 20102)) {
1626                 char ident[12];
1627                 memset(ident, 0, sizeof(ident));
1628                 len = sizeof(ident);
1629                 /* value should be the format like "V2.00-11" */
1630                 if (wi_read_rid(sc, WI_RID_SYMBOL_IDENTITY, ident, &len) == 0 &&
1631                     *(p = (char *)ident) >= 'A' &&
1632                     p[2] == '.' && p[5] == '-' && p[8] == '\0') {
1633                         sc->sc_firmware_type = WI_SYMBOL;
1634                         sc->sc_sta_firmware_ver = (p[1] - '0') * 10000 +
1635                             (p[3] - '0') * 1000 + (p[4] - '0') * 100 +
1636                             (p[6] - '0') * 10 + (p[7] - '0');
1637                 }
1638         }
1639         if (bootverbose) {
1640                 device_printf(sc->sc_dev, "%s Firmware: ",
1641                     wi_firmware_names[sc->sc_firmware_type]);
1642                 if (sc->sc_firmware_type != WI_LUCENT)  /* XXX */
1643                         printf("Primary (%u.%u.%u), ",
1644                             sc->sc_pri_firmware_ver / 10000,
1645                             (sc->sc_pri_firmware_ver % 10000) / 100,
1646                             sc->sc_pri_firmware_ver % 100);
1647                 printf("Station (%u.%u.%u)\n",
1648                     sc->sc_sta_firmware_ver / 10000,
1649                     (sc->sc_sta_firmware_ver % 10000) / 100,
1650                     sc->sc_sta_firmware_ver % 100);
1651         }
1652 }
1653
1654 static int
1655 wi_write_ssid(struct wi_softc *sc, int rid, u_int8_t *buf, int buflen)
1656 {
1657         struct wi_ssid ssid;
1658
1659         if (buflen > IEEE80211_NWID_LEN)
1660                 return ENOBUFS;
1661         memset(&ssid, 0, sizeof(ssid));
1662         ssid.wi_len = htole16(buflen);
1663         memcpy(ssid.wi_ssid, buf, buflen);
1664         return wi_write_rid(sc, rid, &ssid, sizeof(ssid));
1665 }
1666
1667 static int
1668 wi_write_txrate(struct wi_softc *sc, struct ieee80211vap *vap)
1669 {
1670         static const uint16_t lucent_rates[12] = {
1671             [ 0] = 3,   /* auto */
1672             [ 1] = 1,   /* 1Mb/s */
1673             [ 2] = 2,   /* 2Mb/s */
1674             [ 5] = 4,   /* 5.5Mb/s */
1675             [11] = 5    /* 11Mb/s */
1676         };
1677         static const uint16_t intersil_rates[12] = {
1678             [ 0] = 0xf, /* auto */
1679             [ 1] = 0,   /* 1Mb/s */
1680             [ 2] = 1,   /* 2Mb/s */
1681             [ 5] = 2,   /* 5.5Mb/s */
1682             [11] = 3,   /* 11Mb/s */
1683         };
1684         const uint16_t *rates = sc->sc_firmware_type == WI_LUCENT ?
1685             lucent_rates : intersil_rates;
1686         struct ieee80211com *ic = vap->iv_ic;
1687         const struct ieee80211_txparam *tp;
1688
1689         tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_bsschan)];
1690         return wi_write_val(sc, WI_RID_TX_RATE,
1691             (tp->ucastrate == IEEE80211_FIXED_RATE_NONE ?
1692                 rates[0] : rates[tp->ucastrate / 2]));
1693 }
1694
1695 static int
1696 wi_write_wep(struct wi_softc *sc, struct ieee80211vap *vap)
1697 {
1698         int error = 0;
1699         int i, keylen;
1700         u_int16_t val;
1701         struct wi_key wkey[IEEE80211_WEP_NKID];
1702
1703         switch (sc->sc_firmware_type) {
1704         case WI_LUCENT:
1705                 val = (vap->iv_flags & IEEE80211_F_PRIVACY) ? 1 : 0;
1706                 error = wi_write_val(sc, WI_RID_ENCRYPTION, val);
1707                 if (error)
1708                         break;
1709                 if ((vap->iv_flags & IEEE80211_F_PRIVACY) == 0)
1710                         break;
1711                 error = wi_write_val(sc, WI_RID_TX_CRYPT_KEY, vap->iv_def_txkey);
1712                 if (error)
1713                         break;
1714                 memset(wkey, 0, sizeof(wkey));
1715                 for (i = 0; i < IEEE80211_WEP_NKID; i++) {
1716                         keylen = vap->iv_nw_keys[i].wk_keylen;
1717                         wkey[i].wi_keylen = htole16(keylen);
1718                         memcpy(wkey[i].wi_keydat, vap->iv_nw_keys[i].wk_key,
1719                             keylen);
1720                 }
1721                 error = wi_write_rid(sc, WI_RID_DEFLT_CRYPT_KEYS,
1722                     wkey, sizeof(wkey));
1723                 sc->sc_encryption = 0;
1724                 break;
1725
1726         case WI_INTERSIL:
1727                 val = HOST_ENCRYPT | HOST_DECRYPT;
1728                 if (vap->iv_flags & IEEE80211_F_PRIVACY) {
1729                         /*
1730                          * ONLY HWB3163 EVAL-CARD Firmware version
1731                          * less than 0.8 variant2
1732                          *
1733                          *   If promiscuous mode disable, Prism2 chip
1734                          *  does not work with WEP .
1735                          * It is under investigation for details.
1736                          * (ichiro@netbsd.org)
1737                          */
1738                         if (sc->sc_sta_firmware_ver < 802 ) {
1739                                 /* firm ver < 0.8 variant 2 */
1740                                 wi_write_val(sc, WI_RID_PROMISC, 1);
1741                         }
1742                         wi_write_val(sc, WI_RID_CNFAUTHMODE,
1743                             vap->iv_bss->ni_authmode);
1744                         val |= PRIVACY_INVOKED;
1745                 } else {
1746                         wi_write_val(sc, WI_RID_CNFAUTHMODE, IEEE80211_AUTH_OPEN);
1747                 }
1748                 error = wi_write_val(sc, WI_RID_P2_ENCRYPTION, val);
1749                 if (error)
1750                         break;
1751                 sc->sc_encryption = val;
1752                 if ((val & PRIVACY_INVOKED) == 0)
1753                         break;
1754                 error = wi_write_val(sc, WI_RID_P2_TX_CRYPT_KEY, vap->iv_def_txkey);
1755                 break;
1756         }
1757         return error;
1758 }
1759
1760 static int
1761 wi_cmd(struct wi_softc *sc, int cmd, int val0, int val1, int val2)
1762 {
1763         int i, s = 0;
1764
1765         if (sc->wi_gone)
1766                 return (ENODEV);
1767
1768         /* wait for the busy bit to clear */
1769         for (i = sc->wi_cmd_count; i > 0; i--) {        /* 500ms */
1770                 if (!(CSR_READ_2(sc, WI_COMMAND) & WI_CMD_BUSY))
1771                         break;
1772                 DELAY(1*1000);  /* 1ms */
1773         }
1774         if (i == 0) {
1775                 device_printf(sc->sc_dev, "%s: busy bit won't clear, cmd 0x%x\n",
1776                    __func__, cmd);
1777                 sc->wi_gone = 1;
1778                 return(ETIMEDOUT);
1779         }
1780
1781         CSR_WRITE_2(sc, WI_PARAM0, val0);
1782         CSR_WRITE_2(sc, WI_PARAM1, val1);
1783         CSR_WRITE_2(sc, WI_PARAM2, val2);
1784         CSR_WRITE_2(sc, WI_COMMAND, cmd);
1785
1786         if (cmd == WI_CMD_INI) {
1787                 /* XXX: should sleep here. */
1788                 DELAY(100*1000);                /* 100ms delay for init */
1789         }
1790         for (i = 0; i < WI_TIMEOUT; i++) {
1791                 /*
1792                  * Wait for 'command complete' bit to be
1793                  * set in the event status register.
1794                  */
1795                 s = CSR_READ_2(sc, WI_EVENT_STAT);
1796                 if (s & WI_EV_CMD) {
1797                         /* Ack the event and read result code. */
1798                         s = CSR_READ_2(sc, WI_STATUS);
1799                         CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_CMD);
1800                         if (s & WI_STAT_CMD_RESULT) {
1801                                 return(EIO);
1802                         }
1803                         break;
1804                 }
1805                 DELAY(WI_DELAY);
1806         }
1807
1808         if (i == WI_TIMEOUT) {
1809                 device_printf(sc->sc_dev, "%s: timeout on cmd 0x%04x; "
1810                     "event status 0x%04x\n", __func__, cmd, s);
1811                 if (s == 0xffff)
1812                         sc->wi_gone = 1;
1813                 return(ETIMEDOUT);
1814         }
1815         return (0);
1816 }
1817
1818 static int
1819 wi_seek_bap(struct wi_softc *sc, int id, int off)
1820 {
1821         int i, status;
1822
1823         CSR_WRITE_2(sc, WI_SEL0, id);
1824         CSR_WRITE_2(sc, WI_OFF0, off);
1825
1826         for (i = 0; ; i++) {
1827                 status = CSR_READ_2(sc, WI_OFF0);
1828                 if ((status & WI_OFF_BUSY) == 0)
1829                         break;
1830                 if (i == WI_TIMEOUT) {
1831                         device_printf(sc->sc_dev, "%s: timeout, id %x off %x\n",
1832                             __func__, id, off);
1833                         sc->sc_bap_off = WI_OFF_ERR;    /* invalidate */
1834                         if (status == 0xffff)
1835                                 sc->wi_gone = 1;
1836                         return ETIMEDOUT;
1837                 }
1838                 DELAY(1);
1839         }
1840         if (status & WI_OFF_ERR) {
1841                 device_printf(sc->sc_dev, "%s: error, id %x off %x\n",
1842                     __func__, id, off);
1843                 sc->sc_bap_off = WI_OFF_ERR;    /* invalidate */
1844                 return EIO;
1845         }
1846         sc->sc_bap_id = id;
1847         sc->sc_bap_off = off;
1848         return 0;
1849 }
1850
1851 static int
1852 wi_read_bap(struct wi_softc *sc, int id, int off, void *buf, int buflen)
1853 {
1854         int error, cnt;
1855
1856         if (buflen == 0)
1857                 return 0;
1858         if (id != sc->sc_bap_id || off != sc->sc_bap_off) {
1859                 if ((error = wi_seek_bap(sc, id, off)) != 0)
1860                         return error;
1861         }
1862         cnt = (buflen + 1) / 2;
1863         CSR_READ_MULTI_STREAM_2(sc, WI_DATA0, (u_int16_t *)buf, cnt);
1864         sc->sc_bap_off += cnt * 2;
1865         return 0;
1866 }
1867
1868 static int
1869 wi_write_bap(struct wi_softc *sc, int id, int off, const void *buf, int buflen)
1870 {
1871         int error, cnt;
1872
1873         if (buflen == 0)
1874                 return 0;
1875
1876         if (id != sc->sc_bap_id || off != sc->sc_bap_off) {
1877                 if ((error = wi_seek_bap(sc, id, off)) != 0)
1878                         return error;
1879         }
1880         cnt = (buflen + 1) / 2;
1881         CSR_WRITE_MULTI_STREAM_2(sc, WI_DATA0, (const uint16_t *)buf, cnt);
1882         sc->sc_bap_off += cnt * 2;
1883
1884         return 0;
1885 }
1886
1887 static int
1888 wi_mwrite_bap(struct wi_softc *sc, int id, int off, struct mbuf *m0, int totlen)
1889 {
1890         int error, len;
1891         struct mbuf *m;
1892
1893         for (m = m0; m != NULL && totlen > 0; m = m->m_next) {
1894                 if (m->m_len == 0)
1895                         continue;
1896
1897                 len = min(m->m_len, totlen);
1898
1899                 if (((u_long)m->m_data) % 2 != 0 || len % 2 != 0) {
1900                         m_copydata(m, 0, totlen, (caddr_t)&sc->sc_txbuf);
1901                         return wi_write_bap(sc, id, off, (caddr_t)&sc->sc_txbuf,
1902                             totlen);
1903                 }
1904
1905                 if ((error = wi_write_bap(sc, id, off, m->m_data, len)) != 0)
1906                         return error;
1907
1908                 off += m->m_len;
1909                 totlen -= len;
1910         }
1911         return 0;
1912 }
1913
1914 static int
1915 wi_alloc_fid(struct wi_softc *sc, int len, int *idp)
1916 {
1917         int i;
1918
1919         if (wi_cmd(sc, WI_CMD_ALLOC_MEM, len, 0, 0)) {
1920                 device_printf(sc->sc_dev, "%s: failed to allocate %d bytes on NIC\n",
1921                     __func__, len);
1922                 return ENOMEM;
1923         }
1924
1925         for (i = 0; i < WI_TIMEOUT; i++) {
1926                 if (CSR_READ_2(sc, WI_EVENT_STAT) & WI_EV_ALLOC)
1927                         break;
1928                 DELAY(1);
1929         }
1930         if (i == WI_TIMEOUT) {
1931                 device_printf(sc->sc_dev, "%s: timeout in alloc\n", __func__);
1932                 return ETIMEDOUT;
1933         }
1934         *idp = CSR_READ_2(sc, WI_ALLOC_FID);
1935         CSR_WRITE_2(sc, WI_EVENT_ACK, WI_EV_ALLOC);
1936         return 0;
1937 }
1938
1939 static int
1940 wi_read_rid(struct wi_softc *sc, int rid, void *buf, int *buflenp)
1941 {
1942         int error, len;
1943         u_int16_t ltbuf[2];
1944
1945         /* Tell the NIC to enter record read mode. */
1946         error = wi_cmd(sc, WI_CMD_ACCESS | WI_ACCESS_READ, rid, 0, 0);
1947         if (error)
1948                 return error;
1949
1950         error = wi_read_bap(sc, rid, 0, ltbuf, sizeof(ltbuf));
1951         if (error)
1952                 return error;
1953
1954         if (le16toh(ltbuf[1]) != rid) {
1955                 device_printf(sc->sc_dev, "record read mismatch, rid=%x, got=%x\n",
1956                     rid, le16toh(ltbuf[1]));
1957                 return EIO;
1958         }
1959         len = (le16toh(ltbuf[0]) - 1) * 2;       /* already got rid */
1960         if (*buflenp < len) {
1961                 device_printf(sc->sc_dev, "record buffer is too small, "
1962                     "rid=%x, size=%d, len=%d\n",
1963                     rid, *buflenp, len);
1964                 return ENOSPC;
1965         }
1966         *buflenp = len;
1967         return wi_read_bap(sc, rid, sizeof(ltbuf), buf, len);
1968 }
1969
1970 static int
1971 wi_write_rid(struct wi_softc *sc, int rid, const void *buf, int buflen)
1972 {
1973         int error;
1974         u_int16_t ltbuf[2];
1975
1976         ltbuf[0] = htole16((buflen + 1) / 2 + 1);        /* includes rid */
1977         ltbuf[1] = htole16(rid);
1978
1979         error = wi_write_bap(sc, rid, 0, ltbuf, sizeof(ltbuf));
1980         if (error) {
1981                 device_printf(sc->sc_dev, "%s: bap0 write failure, rid 0x%x\n",
1982                     __func__, rid);
1983                 return error;
1984         }
1985         error = wi_write_bap(sc, rid, sizeof(ltbuf), buf, buflen);
1986         if (error) {
1987                 device_printf(sc->sc_dev, "%s: bap1 write failure, rid 0x%x\n",
1988                     __func__, rid);
1989                 return error;
1990         }
1991
1992         return wi_cmd(sc, WI_CMD_ACCESS | WI_ACCESS_WRITE, rid, 0, 0);
1993 }
1994
1995 static int
1996 wi_write_appie(struct wi_softc *sc, int rid, const struct ieee80211_appie *ie)
1997 {
1998         /* NB: 42 bytes is probably ok to have on the stack */
1999         char buf[sizeof(uint16_t) + 40];
2000
2001         if (ie->ie_len > 40)
2002                 return EINVAL;
2003         /* NB: firmware requires 16-bit ie length before ie data */
2004         *(uint16_t *) buf = htole16(ie->ie_len);
2005         memcpy(buf + sizeof(uint16_t), ie->ie_data, ie->ie_len);
2006         return wi_write_rid(sc, rid, buf, ie->ie_len + sizeof(uint16_t));
2007 }
2008
2009 static u_int16_t
2010 wi_read_chanmask(struct wi_softc *sc)
2011 {
2012         u_int16_t val;
2013         int buflen;
2014
2015         buflen = sizeof(val);
2016         if (wi_read_rid(sc, WI_RID_CHANNEL_LIST, &val, &buflen) != 0)
2017                 val = htole16(0x1fff);  /* assume 1-13 */
2018         KASSERT(val != 0, ("%s: no available channels listed!", __func__));
2019
2020         val <<= 1;                      /* shift for base 1 indices */
2021
2022         return (val);
2023 }
2024
2025 int
2026 wi_alloc(device_t dev, int rid)
2027 {
2028         struct wi_softc *sc = device_get_softc(dev);
2029
2030         if (sc->wi_bus_type != WI_BUS_PCI_NATIVE) {
2031                 sc->iobase_rid = rid;
2032                 sc->iobase = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT,
2033                     &sc->iobase_rid, (1 << 6),
2034                     rman_make_alignment_flags(1 << 6) | RF_ACTIVE);
2035                 if (sc->iobase == NULL) {
2036                         device_printf(dev, "No I/O space?!\n");
2037                         return ENXIO;
2038                 }
2039
2040                 sc->wi_io_addr = rman_get_start(sc->iobase);
2041                 sc->wi_btag = rman_get_bustag(sc->iobase);
2042                 sc->wi_bhandle = rman_get_bushandle(sc->iobase);
2043         } else {
2044                 sc->mem_rid = rid;
2045                 sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
2046                     &sc->mem_rid, RF_ACTIVE);
2047                 if (sc->mem == NULL) {
2048                         device_printf(dev, "No Mem space on prism2.5?\n");
2049                         return ENXIO;
2050                 }
2051
2052                 sc->wi_btag = rman_get_bustag(sc->mem);
2053                 sc->wi_bhandle = rman_get_bushandle(sc->mem);
2054         }
2055
2056         sc->irq_rid = 0;
2057         sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid,
2058             RF_ACTIVE |
2059             ((sc->wi_bus_type == WI_BUS_PCCARD) ? 0 : RF_SHAREABLE));
2060         if (sc->irq == NULL) {
2061                 wi_free(dev);
2062                 device_printf(dev, "No irq?!\n");
2063                 return ENXIO;
2064         }
2065
2066         sc->sc_dev = dev;
2067         sc->sc_unit = device_get_unit(dev);
2068         return 0;
2069 }
2070
2071 void
2072 wi_free(device_t dev)
2073 {
2074         struct wi_softc *sc = device_get_softc(dev);
2075
2076         if (sc->iobase != NULL) {
2077                 bus_release_resource(dev, SYS_RES_IOPORT, sc->iobase_rid, sc->iobase);
2078                 sc->iobase = NULL;
2079         }
2080         if (sc->irq != NULL) {
2081                 bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, sc->irq);
2082                 sc->irq = NULL;
2083         }
2084         if (sc->mem != NULL) {
2085                 bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem);
2086                 sc->mem = NULL;
2087         }
2088 }