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