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