Merge from vendor branch LESS:
[dragonfly.git] / sys / dev / netif / ray / if_ray.c
1 /*
2  * Copyright (C) 2000
3  * Dr. Duncan McLennan Barclay, dmlb@ragnet.demon.co.uk.
4  *
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the author nor the names of any co-contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY DUNCAN BARCLAY AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL DUNCAN BARCLAY OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  * $FreeBSD: src/sys/dev/ray/if_ray.c,v 1.47.2.4 2001/08/14 22:54:05 dmlb Exp $
32  * $DragonFly: src/sys/dev/netif/ray/Attic/if_ray.c,v 1.11 2004/03/23 22:19:02 hsu Exp $
33  *
34  */
35
36 /*      $NetBSD: if_ray.c,v 1.12 2000/02/07 09:36:27 augustss Exp $     */
37 /* 
38  * Copyright (c) 2000 Christian E. Hopps
39  * All rights reserved.
40  * 
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  * 3. Neither the name of the author nor the names of any co-contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  */
65
66 /*
67  * Card configuration
68  * ==================
69  *
70  * This card is unusual in that it uses both common and attribute
71  * memory whilst working. It should use common memory and an IO port.
72  *
73  * The bus resource allocations need to work around the brain deadness
74  * of pccardd (where it reads the CIS for common memory, sets it all
75  * up and then throws it all away assuming the card is an ed
76  * driver...). Note that this could be dangerous (because it doesn't
77  * interact with pccardd) if you use other memory mapped cards in the
78  * same pccard slot as currently old mappings are not cleaned up very well
79  * by the bus_release_resource methods or pccardd.
80  *
81  * There is no support for running this driver on 4.0.
82  *
83  * Ad-hoc and infra-structure modes
84  * ================================
85  * 
86  * The driver supports ad-hoc mode for V4 firmware and infrastructure
87  * mode for V5 firmware. V5 firmware in ad-hoc mode is untested and should
88  * work.
89  *
90  * The Linux driver also seems to have the capability to act as an AP.
91  * I wonder what facilities the "AP" can provide within a driver? We can
92  * probably use the BRIDGE code to form an ESS but I don't think
93  * power saving etc. is easy.
94  *
95  *
96  * Packet framing/encapsulation/translation
97  * ========================================
98  * 
99  * Currently we support the Webgear encapsulation:
100  *      802.11  header <net/if_ieee80211.h>struct ieee80211_frame
101  *      802.3   header <net/ethernet.h>struct ether_header
102  *      IP/ARP  payload
103  *
104  * and RFC1042 encapsulation of IP datagrams (translation):
105  *      802.11  header <net/if_ieee80211.h>struct ieee80211_frame
106  *      802.2   LLC header
107  *      802.2   SNAP header
108  *      802.3   Ethertype
109  *      IP/ARP  payload
110  *
111  * Framing should be selected via if_media stuff or link types but
112  * is currently hardcoded to:
113  *      V4      encapsulation
114  *      V5      translation
115  *
116  *
117  * Authentication
118  * ==============
119  *
120  * 802.11 provides two authentication mechanisms. The first is a very
121  * simple host based mechanism (like xhost) called Open System and the
122  * second is a more complex challenge/response called Shared Key built
123  * ontop of WEP.
124  *
125  * This driver only supports Open System and does not implement any
126  * host based control lists. In otherwords authentication is always
127  * granted to hosts wanting to authenticate with this station. This is
128  * the only sensible behaviour as the Open System mechanism uses MAC
129  * addresses to identify hosts. Send me patches if you need it!
130  */
131
132 /*
133  * ***check all XXX_INFRA code - reassoc not done well at all!
134  * ***watchdog to catch screwed up removals?
135  * ***error handling of RAY_COM_RUNQ
136  * ***error handling of ECF command completions
137  * ***can't seem to create a n/w that Win95 wants to see.
138  * ***remove panic in ray_com_ecf by re-quing or timeout
139  * ***use new ioctl stuff - probably need to change RAY_COM_FCHKRUNNING things?
140  *      consider user doing:
141  *              ifconfig ray0 192.168.200.38 -bssid "freed"
142  *              ifconfig ray0 192.168.200.38 -bssid "fred"
143  *      here the second one would be missed in this code
144  * check that v5 needs timeouts on ecf commands
145  * write up driver structure in comments above
146  * UPDATE_PARAMS seems to return via an interrupt - maybe the timeout
147  *      is needed for wrong values?
148  * proper setting of mib_hop_seq_len with country code for v4 firmware
149  *      best done with raycontrol?
150  * countrycode setting is broken I think
151  *      userupdate should trap and do via startjoin etc.
152  * fragmentation when rx level drops?
153  * v5 might not need download
154  *      defaults are as documented apart from hop_seq_length
155  *      settings are sane for ad-hoc not infra
156  *
157  * driver state
158  *      most state is implied by the sequence of commands in the runq
159  *      but in fact any of the rx and tx path that uses variables
160  *      in the sc_c are potentially going to get screwed?
161  *
162  * infra mode stuff
163  *      proper handling of the basic rate set - see the manual
164  *      all ray_sj, ray_assoc sequencues need a "nicer" solution as we
165  *              remember association and authentication
166  *      need to consider WEP
167  *      acting as ap - should be able to get working from the manual
168  *      need to finish RAY_ECMD_REJOIN_DONE
169  *      finish authenitcation code, it doesn't handle errors/timeouts/
170  *      REJOIN etc.
171  *
172  * ray_nw_param
173  *      promisc in here too? - done
174  *      should be able to update the parameters before we download to the
175  *              device. This means we must attach a desired struct to the
176  *              runq entry and maybe have another big case statement to
177  *              move these desired into current when not running.
178  *              init must then use the current settings (pre-loaded
179  *              in attach now!) and pass to download. But we can't access
180  *              current nw params outside of the runq - ahhh
181  *      differeniate between parameters set in attach and init
182  *      sc_station_addr in here too (for changing mac address)
183  *      move desired into the command structure?
184  *      take downloaded MIB from a complete nw_param?
185  *      longer term need to attach a desired nw params to the runq entry
186  *
187  *
188  * RAY_COM_RUNQ errors
189  *
190  * if sleeping in ccs_alloc with eintr/erestart/enxio/enodev
191  *      erestart        try again from the top
192  *                      XXX do not malloc more comqs
193  *                      XXX ccs allocation hard
194  *      eintr           clean up and return
195  *      enxio           clean up and return - done in macro
196  *
197  * if sleeping in runq_arr itself with eintr/erestart/enxio/enodev
198  *      erestart        try again from the top
199  *                      XXX do not malloc more comqs
200  *                      XXX ccs allocation hard
201  *                      XXX reinsert comqs at head of list
202  *      eintr           clean up and return
203  *      enxio           clean up and return - done in macro
204  */
205
206 #define XXX             0
207 #define XXX_ACTING_AP   0
208 #define XXX_INFRA       0
209 #define RAY_DEBUG       (                               \
210                         /* RAY_DBG_AUTH         | */    \
211                         /* RAY_DBG_SUBR         | */    \
212                         /* RAY_DBG_BOOTPARAM    | */    \
213                         /* RAY_DBG_STARTJOIN    | */    \
214                         /* RAY_DBG_CCS          | */    \
215                         /* RAY_DBG_IOCTL        | */    \
216                         /* RAY_DBG_MBUF         | */    \
217                         /* RAY_DBG_RX           | */    \
218                         /* RAY_DBG_CM           | */    \
219                         /* RAY_DBG_COM          | */    \
220                         /* RAY_DBG_STOP         | */    \
221                         /* RAY_DBG_CTL          | */    \
222                         /* RAY_DBG_MGT          | */    \
223                         /* RAY_DBG_TX           | */    \
224                         /* RAY_DBG_DCOM         | */    \
225                         0                               \
226                         )
227
228 /*
229  * XXX build options - move to LINT
230  */
231 #define RAY_CM_RID              0       /* pccardd abuses windows 0 and 1 */
232 #define RAY_AM_RID              3       /* pccardd abuses windows 0 and 1 */
233 #define RAY_COM_TIMEOUT         (hz/2)  /* Timeout for CCS commands */
234 #define RAY_TX_TIMEOUT          (hz/2)  /* Timeout for rescheduling TX */
235 #define RAY_ECF_SPIN_DELAY      1000    /* Wait 1ms before checking ECF ready */
236 #define RAY_ECF_SPIN_TRIES      10      /* Wait this many times for ECF ready */
237 /*
238  * XXX build options - move to LINT
239  */
240
241 #ifndef RAY_DEBUG
242 #define RAY_DEBUG               0x0000
243 #endif /* RAY_DEBUG */
244
245 #include <sys/param.h>
246 #include <sys/systm.h>
247 #include <sys/malloc.h>
248 #include <sys/kernel.h>
249
250 #include <machine/bus.h>
251 #include <machine/resource.h>
252 #include <machine/clock.h>
253 #include <sys/bus.h>
254 #include <sys/rman.h>
255
256 #include <sys/mbuf.h>
257 #include <sys/socket.h>
258 #include <sys/sockio.h>
259
260 #include <net/bpf.h>
261 #include <net/ethernet.h>
262 #include <net/if.h>
263 #include <net/if_arp.h>
264 #include <net/if_dl.h>
265 #include <net/if_ieee80211.h>
266 #include <net/if_llc.h>
267
268 #include <machine/limits.h>
269
270 #include <bus/pccard/pccardvar.h>
271 #include "card_if.h"
272
273 #include "if_rayreg.h"
274 #include "if_raymib.h"
275 #include "if_raydbg.h"
276 #include "if_rayvar.h"
277
278 /*
279  * Prototyping
280  */
281 static int      ray_attach              (device_t);
282 static int      ray_ccs_alloc           (struct ray_softc *sc, size_t *ccsp, char *wmesg);
283 static void     ray_ccs_fill            (struct ray_softc *sc, size_t ccs, u_int cmd);
284 static void     ray_ccs_free            (struct ray_softc *sc, size_t ccs);
285 static int      ray_ccs_tx              (struct ray_softc *sc, size_t *ccsp, size_t *bufpp);
286 static void     ray_com_ecf             (struct ray_softc *sc, struct ray_comq_entry *com);
287 static void     ray_com_ecf_done        (struct ray_softc *sc);
288 static void     ray_com_ecf_timo        (void *xsc);
289 static struct ray_comq_entry *
290                 ray_com_init            (struct ray_comq_entry *com, ray_comqfn_t function, int flags, char *mesg);
291 static struct ray_comq_entry *
292                 ray_com_malloc          (ray_comqfn_t function, int flags, char *mesg);
293 static void     ray_com_runq            (struct ray_softc *sc);
294 static int      ray_com_runq_add        (struct ray_softc *sc, struct ray_comq_entry *com[], int ncom, char *wmesg);
295 static void     ray_com_runq_done       (struct ray_softc *sc);
296 static int      ray_detach              (device_t);
297 static void     ray_init                (void *xsc);
298 static int      ray_init_user           (struct ray_softc *sc);
299 static void     ray_init_assoc          (struct ray_softc *sc, struct ray_comq_entry *com);
300 static void     ray_init_assoc_done     (struct ray_softc *sc, u_int8_t status, size_t ccs);
301 static void     ray_init_auth           (struct ray_softc *sc, struct ray_comq_entry *com);
302 static int      ray_init_auth_send      (struct ray_softc *sc, u_int8_t *dst, int sequence);
303 static void     ray_init_auth_done      (struct ray_softc *sc, u_int8_t status);
304 static void     ray_init_download       (struct ray_softc *sc, struct ray_comq_entry *com);
305 static void     ray_init_download_done  (struct ray_softc *sc, u_int8_t status, size_t ccs);
306 static void     ray_init_download_v4    (struct ray_softc *sc, struct ray_comq_entry *com);
307 static void     ray_init_download_v5    (struct ray_softc *sc, struct ray_comq_entry *com);
308 static void     ray_init_mcast          (struct ray_softc *sc, struct ray_comq_entry *com);
309 static void     ray_init_sj             (struct ray_softc *sc, struct ray_comq_entry *com);
310 static void     ray_init_sj_done        (struct ray_softc *sc, u_int8_t status, size_t ccs);
311 static void     ray_intr                (void *xsc);
312 static void     ray_intr_ccs            (struct ray_softc *sc, u_int8_t cmd, u_int8_t status, size_t ccs);
313 static void     ray_intr_rcs            (struct ray_softc *sc, u_int8_t cmd, size_t ccs);
314 static void     ray_intr_updt_errcntrs  (struct ray_softc *sc);
315 static int      ray_ioctl               (struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr);
316 static void     ray_mcast               (struct ray_softc *sc, struct ray_comq_entry *com); 
317 static void     ray_mcast_done          (struct ray_softc *sc, u_int8_t status, size_t ccs); 
318 static int      ray_mcast_user          (struct ray_softc *sc); 
319 static int      ray_probe               (device_t);
320 static void     ray_promisc             (struct ray_softc *sc, struct ray_comq_entry *com); 
321 static void     ray_repparams           (struct ray_softc *sc, struct ray_comq_entry *com);
322 static void     ray_repparams_done      (struct ray_softc *sc, u_int8_t status, size_t ccs);
323 static int      ray_repparams_user      (struct ray_softc *sc, struct ray_param_req *pr);
324 static int      ray_repstats_user       (struct ray_softc *sc, struct ray_stats_req *sr);
325 static int      ray_res_alloc_am        (struct ray_softc *sc);
326 static int      ray_res_alloc_cm        (struct ray_softc *sc);
327 static int      ray_res_alloc_irq       (struct ray_softc *sc);
328 static void     ray_res_release         (struct ray_softc *sc);
329 static void     ray_rx                  (struct ray_softc *sc, size_t rcs);
330 static void     ray_rx_ctl              (struct ray_softc *sc, struct mbuf *m0);
331 static void     ray_rx_data             (struct ray_softc *sc, struct mbuf *m0, u_int8_t siglev, u_int8_t antenna);
332 static void     ray_rx_mgt              (struct ray_softc *sc, struct mbuf *m0);
333 static void     ray_rx_mgt_auth         (struct ray_softc *sc, struct mbuf *m0);
334 static void     ray_rx_mgt_beacon       (struct ray_softc *sc, struct mbuf *m0);
335 static void     ray_rx_mgt_info         (struct ray_softc *sc, struct mbuf *m0, struct ieee80211_information *elements);
336 static void     ray_rx_update_cache     (struct ray_softc *sc, u_int8_t *src, u_int8_t siglev, u_int8_t antenna);
337 static void     ray_stop                (struct ray_softc *sc, struct ray_comq_entry *com);
338 static int      ray_stop_user           (struct ray_softc *sc);
339 static void     ray_tx                  (struct ifnet *ifp);
340 static void     ray_tx_done             (struct ray_softc *sc, u_int8_t status, size_t ccs);
341 static void     ray_tx_timo             (void *xsc);
342 static int      ray_tx_send             (struct ray_softc *sc, size_t ccs, int pktlen, u_int8_t *dst);
343 static size_t   ray_tx_wrhdr            (struct ray_softc *sc, size_t bufp, u_int8_t type, u_int8_t fc1, u_int8_t *addr1, u_int8_t *addr2, u_int8_t *addr3);
344 static void     ray_upparams            (struct ray_softc *sc, struct ray_comq_entry *com);
345 static void     ray_upparams_done       (struct ray_softc *sc, u_int8_t status, size_t ccs);
346 static int      ray_upparams_user       (struct ray_softc *sc, struct ray_param_req *pr);
347 static void     ray_watchdog            (struct ifnet *ifp);
348 static u_int8_t ray_tx_best_antenna     (struct ray_softc *sc, u_int8_t *dst);
349
350 #if RAY_DEBUG & RAY_DBG_COM
351 static void     ray_com_ecf_check       (struct ray_softc *sc, size_t ccs, char *mesg);
352 #endif /* RAY_DEBUG & RAY_DBG_COM */
353 #if RAY_DEBUG & RAY_DBG_MBUF
354 static void     ray_dump_mbuf           (struct ray_softc *sc, struct mbuf *m, char *s);
355 #endif /* RAY_DEBUG & RAY_DBG_MBUF */
356
357 /*
358  * PC-Card (PCMCIA) driver definition
359  */
360 static device_method_t ray_methods[] = {
361         /* Device interface */
362         DEVMETHOD(device_probe,         ray_probe),
363         DEVMETHOD(device_attach,        ray_attach),
364         DEVMETHOD(device_detach,        ray_detach),
365
366         { 0, 0 }
367 };
368
369 static driver_t ray_driver = {
370         "ray",
371         ray_methods,
372         sizeof(struct ray_softc)
373 };
374
375 static devclass_t ray_devclass;
376
377 DECLARE_DUMMY_MODULE(if_ray);
378 DRIVER_MODULE(if_ray, pccard, ray_driver, ray_devclass, 0, 0);
379
380 /* 
381  * Probe for the card by checking its startup results.
382  *
383  * Fixup any bugs/quirks for different firmware.
384  */
385 static int
386 ray_probe(device_t dev)
387 {
388         struct ray_softc *sc = device_get_softc(dev);
389         struct ray_ecf_startup_v5 *ep = &sc->sc_ecf_startup;
390         int error;
391
392         sc->dev = dev;
393         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
394
395         /*
396          * Read startup results from the card.
397          */
398         error = ray_res_alloc_cm(sc);
399         if (error)
400                 return (error);
401         error = ray_res_alloc_am(sc);
402         if (error) {
403                 ray_res_release(sc);
404                 return (error);
405         }
406         RAY_MAP_CM(sc);
407         SRAM_READ_REGION(sc, RAY_ECF_TO_HOST_BASE, ep,
408             sizeof(sc->sc_ecf_startup));
409         ray_res_release(sc);
410
411         /*
412          * Check the card is okay and work out what version we are using.
413          */
414         if (ep->e_status != RAY_ECFS_CARD_OK) {
415                 RAY_PRINTF(sc, "card failed self test 0x%b",
416                     ep->e_status, RAY_ECFS_PRINTFB);
417                 return (ENXIO);
418         }
419         if (sc->sc_version != RAY_ECFS_BUILD_4 &&
420             sc->sc_version != RAY_ECFS_BUILD_5) {
421                 RAY_PRINTF(sc, "unsupported firmware version 0x%0x",
422                     ep->e_fw_build_string);
423                 return (ENXIO);
424         }
425         RAY_DPRINTF(sc, RAY_DBG_BOOTPARAM, "found a card");
426         sc->sc_gone = 0;
427
428         /*
429          * Fixup tib size to be correct - on build 4 it is garbage
430          */
431         if (sc->sc_version == RAY_ECFS_BUILD_4 && sc->sc_tibsize == 0x55)
432                 sc->sc_tibsize = sizeof(struct ray_tx_tib);
433
434         return (0);
435 }
436
437 /*
438  * Attach the card into the kernel
439  */
440 static int
441 ray_attach(device_t dev)
442 {
443         struct ray_softc *sc = device_get_softc(dev);
444         struct ray_ecf_startup_v5 *ep = &sc->sc_ecf_startup;
445         struct ifnet *ifp = &sc->arpcom.ac_if;
446         size_t ccs;
447         int i, error;
448
449         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
450
451         if ((sc == NULL) || (sc->sc_gone))
452                 return (ENXIO);
453
454         /*
455          * Grab the resources I need
456          */
457         error = ray_res_alloc_cm(sc);
458         if (error)
459                 return (error);
460         error = ray_res_alloc_am(sc);
461         if (error) {
462                 ray_res_release(sc);
463                 return (error);
464         }
465         error = ray_res_alloc_irq(sc);
466         if (error) {
467                 ray_res_release(sc);
468                 return (error);
469         }
470
471         /*
472          * Reset any pending interrupts
473          */
474         RAY_HCS_CLEAR_INTR(sc);
475
476         /*
477          * Set the parameters that will survive stop/init and
478          * reset a few things on the card.
479          *
480          * Do not update these in ray_init_download's parameter setup
481          *
482          * XXX see the ray_init_download section for stuff to move
483          */
484         RAY_MAP_CM(sc);
485         bzero(&sc->sc_d, sizeof(struct ray_nw_param));
486         bzero(&sc->sc_c, sizeof(struct ray_nw_param));
487
488         /* Clear statistics counters */
489         sc->sc_rxoverflow = 0;
490         sc->sc_rxcksum = 0;
491         sc->sc_rxhcksum = 0;
492         sc->sc_rxnoise = 0;
493
494         /* Clear signal and antenna cache */
495         bzero(sc->sc_siglevs, sizeof(sc->sc_siglevs));
496
497         /* Set all ccs to be free */
498         bzero(sc->sc_ccsinuse, sizeof(sc->sc_ccsinuse));
499         ccs = RAY_CCS_ADDRESS(0);
500         for (i = 0; i < RAY_CCS_LAST; ccs += RAY_CCS_SIZE, i++)
501                 RAY_CCS_FREE(sc, ccs);
502
503         /*
504          * Initialise the network interface structure
505          */
506         if_initname(ifp, "ray", device_get_unit(dev));
507         ifp->if_softc = sc;
508         ifp->if_timer = 0;
509         ifp->if_flags = (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
510         ifp->if_hdrlen = sizeof(struct ieee80211_frame) + 
511             sizeof(struct ether_header);
512         ifp->if_baudrate = 1000000; /* Is this baud or bps ;-) */
513         ifp->if_output = ether_output;
514         ifp->if_start = ray_tx;
515         ifp->if_ioctl = ray_ioctl;
516         ifp->if_watchdog = ray_watchdog;
517         ifp->if_init = ray_init;
518         ifp->if_snd.ifq_maxlen = IFQ_MAXLEN;
519
520         ether_ifattach(ifp, ep->e_station_addr);
521
522         /*
523          * Initialise the timers and driver
524          */
525         callout_handle_init(&sc->com_timerh);
526         callout_handle_init(&sc->tx_timerh);
527         TAILQ_INIT(&sc->sc_comq);
528
529         /*
530          * Print out some useful information
531          */
532         if (bootverbose || (RAY_DEBUG & RAY_DBG_BOOTPARAM)) {
533                 RAY_PRINTF(sc, "start up results");
534                 if (sc->sc_version == RAY_ECFS_BUILD_4)
535                         printf(".  Firmware version 4\n");
536                 else
537                         printf(".  Firmware version 5\n");
538                 printf(".  Status 0x%b\n", ep->e_status, RAY_ECFS_PRINTFB);
539                 printf(".  Ether address %6D\n", ep->e_station_addr, ":");
540                 if (sc->sc_version == RAY_ECFS_BUILD_4) {
541                         printf(".  Program checksum %0x\n", ep->e_resv0);
542                         printf(".  CIS checksum %0x\n", ep->e_rates[0]);
543                 } else {
544                         printf(".  (reserved word) %0x\n", ep->e_resv0);
545                         printf(".  Supported rates %8D\n", ep->e_rates, ":");
546                 }
547                 printf(".  Japan call sign %12D\n", ep->e_japan_callsign, ":");
548                 if (sc->sc_version == RAY_ECFS_BUILD_5) {
549                         printf(".  Program checksum %0x\n", ep->e_prg_cksum);
550                         printf(".  CIS checksum %0x\n", ep->e_cis_cksum);
551                         printf(".  Firmware version %0x\n",
552                             ep->e_fw_build_string);
553                         printf(".  Firmware revision %0x\n", ep->e_fw_build);
554                         printf(".  (reserved word) %0x\n", ep->e_fw_resv);
555                         printf(".  ASIC version %0x\n", ep->e_asic_version);
556                         printf(".  TIB size %0x\n", ep->e_tibsize);
557                 }
558         }
559
560         return (0);
561 }
562
563 /*
564  * Detach the card
565  *
566  * This is usually called when the card is ejected, but
567  * can be caused by a modunload of a controller driver.
568  * The idea is to reset the driver's view of the device
569  * and ensure that any driver entry points such as
570  * read and write do not hang.
571  */
572 static int
573 ray_detach(device_t dev)
574 {
575         struct ray_softc *sc = device_get_softc(dev);
576         struct ifnet *ifp = &sc->arpcom.ac_if;
577         struct ray_comq_entry *com;
578         int s;
579
580         s = splimp();
581
582         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STOP, "");
583
584         if ((sc == NULL) || (sc->sc_gone))
585                 return (0);
586
587         /*
588          * Mark as not running and detach the interface.
589          *
590          * N.B. if_detach can trigger ioctls so we do it first and
591          * then clean the runq.
592          */
593         sc->sc_gone = 1;
594         sc->sc_c.np_havenet = 0;
595         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
596         ether_ifdetach(ifp);
597
598         /*
599          * Stop the runq and wake up anyone sleeping for us.
600          */
601         untimeout(ray_com_ecf_timo, sc, sc->com_timerh);
602         untimeout(ray_tx_timo, sc, sc->tx_timerh);
603         com = TAILQ_FIRST(&sc->sc_comq);
604         for (com = TAILQ_FIRST(&sc->sc_comq); com != NULL;
605             com = TAILQ_NEXT(com, c_chain)) {
606                 com->c_flags |= RAY_COM_FDETACHED;
607                 com->c_retval = 0;
608                 RAY_DPRINTF(sc, RAY_DBG_STOP, "looking at com %p %b",
609                     com, com->c_flags, RAY_COM_FLAGS_PRINTFB);
610                 if (com->c_flags & RAY_COM_FWOK) {
611                         RAY_DPRINTF(sc, RAY_DBG_STOP, "waking com %p", com);
612                         wakeup(com->c_wakeup);
613                 }
614         }
615         
616         /*
617          * Release resources
618          */
619         ray_res_release(sc);
620         RAY_DPRINTF(sc, RAY_DBG_STOP, "unloading complete");
621
622         splx(s);
623
624         return (0);
625 }
626
627 /*
628  * Network ioctl request.
629  */
630 static int
631 ray_ioctl(register struct ifnet *ifp, u_long command, caddr_t data,
632     struct ucred *cr)
633 {
634         struct ray_softc *sc = ifp->if_softc;
635         struct ray_param_req pr;
636         struct ray_stats_req sr;
637         struct ifreq *ifr = (struct ifreq *)data;
638         int s, error, error2;
639
640         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_IOCTL, "");
641
642         if ((sc == NULL) || (sc->sc_gone))
643                 return (ENXIO);
644
645         error = error2 = 0;
646         s = splimp();
647
648         switch (command) {
649
650         case SIOCGIFADDR:
651         case SIOCSIFMTU:
652         case SIOCSIFADDR:
653                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "GIFADDR/SIFMTU");
654                 error = ether_ioctl(ifp, command, data);
655 /* XXX SIFADDR used to fall through to SIOCSIFFLAGS */
656                 break;
657
658         case SIOCSIFFLAGS:
659                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "SIFFLAGS 0x%0x", ifp->if_flags);
660                 /*
661                  * If the interface is marked up we call ray_init_user.
662                  * This will deal with mcast and promisc flags as well as
663                  * initialising the hardware if it needs it.
664                  */
665                 if (ifp->if_flags & IFF_UP)
666                         error = ray_init_user(sc);
667                 else
668                         error = ray_stop_user(sc);
669                 break;
670
671         case SIOCADDMULTI:
672         case SIOCDELMULTI:
673                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "ADDMULTI/DELMULTI");
674                 error = ray_mcast_user(sc);
675                 break;
676
677         case SIOCSRAYPARAM:
678                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "SRAYPARAM");
679                 if ((error = copyin(ifr->ifr_data, &pr, sizeof(pr))))
680                         break;
681                 error = ray_upparams_user(sc, &pr);
682                 error2 = copyout(&pr, ifr->ifr_data, sizeof(pr));
683                 error = error2 ? error2 : error;
684                 break;
685
686         case SIOCGRAYPARAM:
687                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "GRAYPARAM");
688                 if ((error = copyin(ifr->ifr_data, &pr, sizeof(pr))))
689                         break;
690                 error = ray_repparams_user(sc, &pr);
691                 error2 = copyout(&pr, ifr->ifr_data, sizeof(pr));
692                 error = error2 ? error2 : error;
693                 break;
694
695         case SIOCGRAYSTATS:
696                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "GRAYSTATS");
697                 error = ray_repstats_user(sc, &sr);
698                 error2 = copyout(&sr, ifr->ifr_data, sizeof(sr));
699                 error = error2 ? error2 : error;
700                 break;
701
702         case SIOCGRAYSIGLEV:
703                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "GRAYSIGLEV");
704                 error = copyout(sc->sc_siglevs, ifr->ifr_data,
705                     sizeof(sc->sc_siglevs));
706                 break;
707
708         case SIOCGIFFLAGS:
709                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "GIFFLAGS");
710                 error = EINVAL;
711                 break;
712
713         case SIOCGIFMETRIC:
714                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "GIFMETRIC");
715                 error = EINVAL;
716                 break;
717
718         case SIOCGIFMTU:
719                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "GIFMTU");
720                 error = EINVAL;
721                 break;
722
723         case SIOCGIFPHYS:
724                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "GIFPYHS");
725                 error = EINVAL;
726                 break;
727
728         case SIOCSIFMEDIA:
729                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "SIFMEDIA");
730                 error = EINVAL;
731                 break;
732
733         case SIOCGIFMEDIA:
734                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "GIFMEDIA");
735                 error = EINVAL;
736                 break;
737
738         default:
739                 error = EINVAL;
740
741         }
742
743         splx(s);
744
745         return (error);
746 }
747
748 /*
749  * Ethernet layer entry to ray_init - discard errors
750  */
751 static void
752 ray_init(void *xsc)
753 {
754         struct ray_softc *sc = (struct ray_softc *)xsc;
755
756         ray_init_user(sc);
757 }
758
759 /*
760  * User land entry to network initialisation and changes in interface flags.
761  * 
762  * We do a very little work here, just creating runq entries to
763  * processes the actions needed to cope with interface flags. We do it
764  * this way in case there are runq entries outstanding from earlier
765  * ioctls that modify the interface flags.
766  *
767  * Returns values are either 0 for success, a varity of resource allocation
768  * failures or errors in the command sent to the card.
769  *
770  * Note, IFF_RUNNING is eventually set by init_sj_done or init_assoc_done
771  */
772 static int
773 ray_init_user(struct ray_softc *sc)
774 {
775         struct ray_comq_entry *com[6];
776         int error, ncom;
777
778         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN, "");
779
780         /*
781          * Create the following runq entries to bring the card up.
782          *
783          *              init_download   - download the network to the card
784          *              init_mcast      - reset multicast list
785          *              init_sj         - find or start a BSS
786          *              init_auth       - authenticate with a ESSID if needed
787          *              init_assoc      - associate with a ESSID if needed
788          *
789          * They are only actually executed if the card is not running.
790          * We may enter this routine from a simple change of IP
791          * address and do not need to get the card to do these things.
792          * However, we cannot perform the check here as there may be
793          * commands in the runq that change the IFF_RUNNING state of
794          * the interface.
795          */
796         ncom = 0;
797         com[ncom++] = RAY_COM_MALLOC(ray_init_download, RAY_COM_FCHKRUNNING);
798         com[ncom++] = RAY_COM_MALLOC(ray_init_mcast, RAY_COM_FCHKRUNNING);
799         com[ncom++] = RAY_COM_MALLOC(ray_init_sj, RAY_COM_FCHKRUNNING);
800         com[ncom++] = RAY_COM_MALLOC(ray_init_auth, RAY_COM_FCHKRUNNING);
801         com[ncom++] = RAY_COM_MALLOC(ray_init_assoc, RAY_COM_FCHKRUNNING);
802
803         /*
804          * Create runq entries to process flags
805          *
806          *              promisc         - set/reset PROMISC and ALLMULTI flags
807          *
808          * They are only actually executed if the card is running
809          */
810         com[ncom++] = RAY_COM_MALLOC(ray_promisc, 0);
811
812         RAY_COM_RUNQ(sc, com, ncom, "rayinit", error);
813
814         /* XXX no real error processing from anything yet! */
815
816         RAY_COM_FREE(com, ncom);
817
818         return (error);
819 }
820
821 /*
822  * Runq entry for resetting driver and downloading start up structures to card
823  */
824 static void
825 ray_init_download(struct ray_softc *sc, struct ray_comq_entry *com)
826 {
827         struct ifnet *ifp = &sc->arpcom.ac_if;
828
829         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN, "");
830
831         /* If the card already running we might not need to download */
832         RAY_COM_CHKRUNNING(sc, com, ifp);
833
834         /*
835          * Reset instance variables
836          *
837          * The first set are network parameters that are read back when
838          * the card starts or joins the network.
839          *
840          * The second set are network parameters that are downloaded to
841          * the card.
842          *
843          * The third set are driver parameters.
844          *
845          * All of the variables in these sets can be updated by the
846          * card or ioctls.
847          *
848          * XXX see the ray_attach section for stuff to move
849          */
850         sc->sc_d.np_upd_param = 0;
851         bzero(sc->sc_d.np_bss_id, ETHER_ADDR_LEN);
852         sc->sc_d.np_inited = 0;
853         sc->sc_d.np_def_txrate = RAY_MIB_BASIC_RATE_SET_DEFAULT;
854         sc->sc_d.np_encrypt = 0;
855
856         bzero(sc->sc_d.np_ssid, IEEE80211_NWID_LEN);
857         if (sc->sc_version == RAY_ECFS_BUILD_4) {
858                 sc->sc_d.np_net_type = RAY_MIB_NET_TYPE_V4;
859                 strncpy(sc->sc_d.np_ssid, RAY_MIB_SSID_V4, IEEE80211_NWID_LEN);
860                 sc->sc_d.np_ap_status = RAY_MIB_AP_STATUS_V4;
861                 sc->sc_d.np_framing = RAY_FRAMING_ENCAPSULATION;
862         } else {
863                 sc->sc_d.np_net_type = RAY_MIB_NET_TYPE_V5;
864                 strncpy(sc->sc_d.np_ssid, RAY_MIB_SSID_V5, IEEE80211_NWID_LEN);
865                 sc->sc_d.np_ap_status = RAY_MIB_AP_STATUS_V5;
866                 sc->sc_d.np_framing = RAY_FRAMING_TRANSLATION;
867         }
868         sc->sc_d.np_priv_start = RAY_MIB_PRIVACY_MUST_START_DEFAULT;
869         sc->sc_d.np_priv_join = RAY_MIB_PRIVACY_CAN_JOIN_DEFAULT;
870         sc->sc_d.np_promisc = !!(ifp->if_flags & (IFF_PROMISC | IFF_ALLMULTI));
871
872 /* XXX this is a hack whilst I transition the code. The instance
873  * XXX variables above should be set somewhere else. This is needed for
874  * XXX start_join */
875 bcopy(&sc->sc_d, &com->c_desired, sizeof(struct ray_nw_param));
876             
877         /*
878          * Download the right firmware defaults
879          */
880         if (sc->sc_version == RAY_ECFS_BUILD_4)
881                 ray_init_download_v4(sc, com);
882         else
883                 ray_init_download_v5(sc, com);
884
885         /*
886          * Kick the card
887          */
888         ray_ccs_fill(sc, com->c_ccs, RAY_CMD_DOWNLOAD_PARAMS);
889         ray_com_ecf(sc, com);
890 }
891
892 #define PUT2(p, v)      \
893     do { (p)[0] = ((v >> 8) & 0xff); (p)[1] = (v & 0xff); } while(0)
894 /*
895  * Firmware version 4 defaults - see if_raymib.h for details
896  */
897 static void
898 ray_init_download_v4(struct ray_softc *sc, struct ray_comq_entry *com)
899 {
900         struct ray_mib_4 ray_mib_4_default;
901
902         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN, "");
903         RAY_MAP_CM(sc);
904
905 #define MIB4(m)         ray_mib_4_default.m
906
907         MIB4(mib_net_type)              = com->c_desired.np_net_type;
908         MIB4(mib_ap_status)             = com->c_desired.np_ap_status;
909         bcopy(com->c_desired.np_ssid, MIB4(mib_ssid), IEEE80211_NWID_LEN);
910         MIB4(mib_scan_mode)             = RAY_MIB_SCAN_MODE_V4;
911         MIB4(mib_apm_mode)              = RAY_MIB_APM_MODE_V4;
912         bcopy(sc->sc_station_addr, MIB4(mib_mac_addr), ETHER_ADDR_LEN);
913    PUT2(MIB4(mib_frag_thresh),            RAY_MIB_FRAG_THRESH_V4);
914    PUT2(MIB4(mib_dwell_time),             RAY_MIB_DWELL_TIME_V4);
915    PUT2(MIB4(mib_beacon_period),          RAY_MIB_BEACON_PERIOD_V4);
916         MIB4(mib_dtim_interval)         = RAY_MIB_DTIM_INTERVAL_V4;
917         MIB4(mib_max_retry)             = RAY_MIB_MAX_RETRY_V4;
918         MIB4(mib_ack_timo)              = RAY_MIB_ACK_TIMO_V4;
919         MIB4(mib_sifs)                  = RAY_MIB_SIFS_V4;
920         MIB4(mib_difs)                  = RAY_MIB_DIFS_V4;
921         MIB4(mib_pifs)                  = RAY_MIB_PIFS_V4;
922    PUT2(MIB4(mib_rts_thresh),             RAY_MIB_RTS_THRESH_V4);
923    PUT2(MIB4(mib_scan_dwell),             RAY_MIB_SCAN_DWELL_V4);
924    PUT2(MIB4(mib_scan_max_dwell),         RAY_MIB_SCAN_MAX_DWELL_V4);
925         MIB4(mib_assoc_timo)            = RAY_MIB_ASSOC_TIMO_V4;
926         MIB4(mib_adhoc_scan_cycle)      = RAY_MIB_ADHOC_SCAN_CYCLE_V4;
927         MIB4(mib_infra_scan_cycle)      = RAY_MIB_INFRA_SCAN_CYCLE_V4;
928         MIB4(mib_infra_super_scan_cycle)
929                                         = RAY_MIB_INFRA_SUPER_SCAN_CYCLE_V4;
930         MIB4(mib_promisc)               = com->c_desired.np_promisc;
931    PUT2(MIB4(mib_uniq_word),              RAY_MIB_UNIQ_WORD_V4);
932         MIB4(mib_slot_time)             = RAY_MIB_SLOT_TIME_V4;
933         MIB4(mib_roam_low_snr_thresh)   = RAY_MIB_ROAM_LOW_SNR_THRESH_V4;
934         MIB4(mib_low_snr_count)         = RAY_MIB_LOW_SNR_COUNT_V4;
935         MIB4(mib_infra_missed_beacon_count)
936                                         = RAY_MIB_INFRA_MISSED_BEACON_COUNT_V4;
937         MIB4(mib_adhoc_missed_beacon_count)     
938                                         = RAY_MIB_ADHOC_MISSED_BEACON_COUNT_V4;
939         MIB4(mib_country_code)          = RAY_MIB_COUNTRY_CODE_V4;
940         MIB4(mib_hop_seq)               = RAY_MIB_HOP_SEQ_V4;
941         MIB4(mib_hop_seq_len)           = RAY_MIB_HOP_SEQ_LEN_V4;
942         MIB4(mib_cw_max)                = RAY_MIB_CW_MAX_V4;
943         MIB4(mib_cw_min)                = RAY_MIB_CW_MIN_V4;
944         MIB4(mib_noise_filter_gain)     = RAY_MIB_NOISE_FILTER_GAIN_DEFAULT;
945         MIB4(mib_noise_limit_offset)    = RAY_MIB_NOISE_LIMIT_OFFSET_DEFAULT;
946         MIB4(mib_rssi_thresh_offset)    = RAY_MIB_RSSI_THRESH_OFFSET_DEFAULT;
947         MIB4(mib_busy_thresh_offset)    = RAY_MIB_BUSY_THRESH_OFFSET_DEFAULT;
948         MIB4(mib_sync_thresh)           = RAY_MIB_SYNC_THRESH_DEFAULT;
949         MIB4(mib_test_mode)             = RAY_MIB_TEST_MODE_DEFAULT;
950         MIB4(mib_test_min_chan)         = RAY_MIB_TEST_MIN_CHAN_DEFAULT;
951         MIB4(mib_test_max_chan)         = RAY_MIB_TEST_MAX_CHAN_DEFAULT;
952 #undef MIB4
953
954         SRAM_WRITE_REGION(sc, RAY_HOST_TO_ECF_BASE,
955             &ray_mib_4_default, sizeof(ray_mib_4_default));
956 }
957
958 /*
959  * Firmware version 5 defaults - see if_raymib.h for details
960  */
961 static void
962 ray_init_download_v5(struct ray_softc *sc, struct ray_comq_entry *com)
963 {
964         struct ray_mib_5 ray_mib_5_default;
965
966         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN, "");
967         RAY_MAP_CM(sc);
968
969 #define MIB5(m)         ray_mib_5_default.m
970         MIB5(mib_net_type)              = com->c_desired.np_net_type;
971         MIB5(mib_ap_status)             = com->c_desired.np_ap_status;
972         bcopy(com->c_desired.np_ssid, MIB5(mib_ssid), IEEE80211_NWID_LEN);
973         MIB5(mib_scan_mode)             = RAY_MIB_SCAN_MODE_V5;
974         MIB5(mib_apm_mode)              = RAY_MIB_APM_MODE_V5;
975         bcopy(sc->sc_station_addr, MIB5(mib_mac_addr), ETHER_ADDR_LEN);
976    PUT2(MIB5(mib_frag_thresh),            RAY_MIB_FRAG_THRESH_V5);
977    PUT2(MIB5(mib_dwell_time),             RAY_MIB_DWELL_TIME_V5);
978    PUT2(MIB5(mib_beacon_period),          RAY_MIB_BEACON_PERIOD_V5);
979         MIB5(mib_dtim_interval)         = RAY_MIB_DTIM_INTERVAL_V5;
980         MIB5(mib_max_retry)             = RAY_MIB_MAX_RETRY_V5;
981         MIB5(mib_ack_timo)              = RAY_MIB_ACK_TIMO_V5;
982         MIB5(mib_sifs)                  = RAY_MIB_SIFS_V5;
983         MIB5(mib_difs)                  = RAY_MIB_DIFS_V5;
984         MIB5(mib_pifs)                  = RAY_MIB_PIFS_V5;
985    PUT2(MIB5(mib_rts_thresh),             RAY_MIB_RTS_THRESH_V5);
986    PUT2(MIB5(mib_scan_dwell),             RAY_MIB_SCAN_DWELL_V5);
987    PUT2(MIB5(mib_scan_max_dwell),         RAY_MIB_SCAN_MAX_DWELL_V5);
988         MIB5(mib_assoc_timo)            = RAY_MIB_ASSOC_TIMO_V5;
989         MIB5(mib_adhoc_scan_cycle)      = RAY_MIB_ADHOC_SCAN_CYCLE_V5;
990         MIB5(mib_infra_scan_cycle)      = RAY_MIB_INFRA_SCAN_CYCLE_V5;
991         MIB5(mib_infra_super_scan_cycle)
992                                         = RAY_MIB_INFRA_SUPER_SCAN_CYCLE_V5;
993         MIB5(mib_promisc)               = com->c_desired.np_promisc;
994    PUT2(MIB5(mib_uniq_word),              RAY_MIB_UNIQ_WORD_V5);
995         MIB5(mib_slot_time)             = RAY_MIB_SLOT_TIME_V5;
996         MIB5(mib_roam_low_snr_thresh)   = RAY_MIB_ROAM_LOW_SNR_THRESH_V5;
997         MIB5(mib_low_snr_count) = RAY_MIB_LOW_SNR_COUNT_V5;
998         MIB5(mib_infra_missed_beacon_count)
999                                         = RAY_MIB_INFRA_MISSED_BEACON_COUNT_V5;
1000         MIB5(mib_adhoc_missed_beacon_count)
1001                                         = RAY_MIB_ADHOC_MISSED_BEACON_COUNT_V5;
1002         MIB5(mib_country_code)          = RAY_MIB_COUNTRY_CODE_V5;
1003         MIB5(mib_hop_seq)               = RAY_MIB_HOP_SEQ_V5;
1004         MIB5(mib_hop_seq_len)           = RAY_MIB_HOP_SEQ_LEN_V5;
1005    PUT2(MIB5(mib_cw_max),                 RAY_MIB_CW_MAX_V5);
1006    PUT2(MIB5(mib_cw_min),                 RAY_MIB_CW_MIN_V5);
1007         MIB5(mib_noise_filter_gain)     = RAY_MIB_NOISE_FILTER_GAIN_DEFAULT;
1008         MIB5(mib_noise_limit_offset)    = RAY_MIB_NOISE_LIMIT_OFFSET_DEFAULT;
1009         MIB5(mib_rssi_thresh_offset)    = RAY_MIB_RSSI_THRESH_OFFSET_DEFAULT;
1010         MIB5(mib_busy_thresh_offset)    = RAY_MIB_BUSY_THRESH_OFFSET_DEFAULT;
1011         MIB5(mib_sync_thresh)           = RAY_MIB_SYNC_THRESH_DEFAULT;
1012         MIB5(mib_test_mode)             = RAY_MIB_TEST_MODE_DEFAULT;
1013         MIB5(mib_test_min_chan)         = RAY_MIB_TEST_MIN_CHAN_DEFAULT;
1014         MIB5(mib_test_max_chan)         = RAY_MIB_TEST_MAX_CHAN_DEFAULT;
1015         MIB5(mib_allow_probe_resp)      = RAY_MIB_ALLOW_PROBE_RESP_DEFAULT;
1016         MIB5(mib_privacy_must_start)    = com->c_desired.np_priv_start;
1017         MIB5(mib_privacy_can_join)      = com->c_desired.np_priv_join;
1018         MIB5(mib_basic_rate_set[0])     = com->c_desired.np_def_txrate;
1019 #undef MIB5
1020
1021         SRAM_WRITE_REGION(sc, RAY_HOST_TO_ECF_BASE,
1022             &ray_mib_5_default, sizeof(ray_mib_5_default));
1023 }
1024 #undef PUT2
1025
1026 /*
1027  * Download completion routine
1028  */
1029 static void
1030 ray_init_download_done(struct ray_softc *sc, u_int8_t status, size_t ccs)
1031 {
1032         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN, "");
1033         RAY_COM_CHECK(sc, ccs);
1034
1035         RAY_CCSERR(sc, status, if_oerrors); /* XXX error counter */
1036
1037         ray_com_ecf_done(sc);
1038 }
1039
1040 /*
1041  * Runq entry to empty the multicast filter list
1042  */
1043 static void
1044 ray_init_mcast(struct ray_softc *sc, struct ray_comq_entry *com)
1045 {
1046         struct ifnet *ifp = &sc->arpcom.ac_if;
1047
1048         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN, "");
1049         RAY_MAP_CM(sc);
1050
1051         /* If the card already running we might not need to reset the list */
1052         RAY_COM_CHKRUNNING(sc, com, ifp);
1053
1054         /*
1055          * Kick the card
1056          */
1057         ray_ccs_fill(sc, com->c_ccs, RAY_CMD_UPDATE_MCAST);
1058         SRAM_WRITE_FIELD_1(sc, com->c_ccs, ray_cmd_update_mcast, c_nmcast, 0);
1059
1060         ray_com_ecf(sc, com);
1061 }
1062
1063 /*
1064  * Runq entry to starting or joining a network
1065  */
1066 static void
1067 ray_init_sj(struct ray_softc *sc, struct ray_comq_entry *com)
1068 {
1069         struct ifnet *ifp = &sc->arpcom.ac_if;
1070         struct ray_net_params np;
1071         int update;
1072
1073         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN, "");
1074         RAY_MAP_CM(sc);
1075
1076         /* If the card already running we might not need to start the n/w */
1077         RAY_COM_CHKRUNNING(sc, com, ifp);
1078
1079         /*
1080          * Set up the right start or join command and determine
1081          * whether we should tell the card about a change in operating
1082          * parameters.
1083          */
1084         sc->sc_c.np_havenet = 0;
1085         if (sc->sc_d.np_net_type == RAY_MIB_NET_TYPE_ADHOC)
1086                 ray_ccs_fill(sc, com->c_ccs, RAY_CMD_START_NET);
1087         else
1088                 ray_ccs_fill(sc, com->c_ccs, RAY_CMD_JOIN_NET);
1089
1090         update = 0;
1091         if (sc->sc_c.np_net_type != sc->sc_d.np_net_type)
1092                 update++;
1093         if (bcmp(sc->sc_c.np_ssid, sc->sc_d.np_ssid, IEEE80211_NWID_LEN))
1094                 update++;
1095         if (sc->sc_c.np_priv_join != sc->sc_d.np_priv_join)
1096                 update++;
1097         if (sc->sc_c.np_priv_start != sc->sc_d.np_priv_start)
1098                 update++;
1099         RAY_DPRINTF(sc, RAY_DBG_STARTJOIN,
1100             "%s updating nw params", update?"is":"not");
1101         if (update) {
1102                 bzero(&np, sizeof(np));
1103                 np.p_net_type = sc->sc_d.np_net_type;
1104                 bcopy(sc->sc_d.np_ssid, np.p_ssid,  IEEE80211_NWID_LEN);
1105                 np.p_privacy_must_start = sc->sc_d.np_priv_start;
1106                 np.p_privacy_can_join = sc->sc_d.np_priv_join;
1107                 SRAM_WRITE_REGION(sc, RAY_HOST_TO_ECF_BASE, &np, sizeof(np));
1108                 SRAM_WRITE_FIELD_1(sc, com->c_ccs, ray_cmd_net, c_upd_param, 1);
1109         } else
1110                 SRAM_WRITE_FIELD_1(sc, com->c_ccs, ray_cmd_net, c_upd_param, 0);
1111
1112         /*
1113          * Kick the card
1114          */
1115         ray_com_ecf(sc, com);
1116 }
1117
1118 /*
1119  * Complete start command or intermediate step in assoc command
1120  */
1121 static void
1122 ray_init_sj_done(struct ray_softc *sc, u_int8_t status, size_t ccs)
1123 {
1124         struct ifnet *ifp = &sc->arpcom.ac_if;
1125
1126         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN, "");
1127         RAY_MAP_CM(sc);
1128         RAY_COM_CHECK(sc, ccs);
1129
1130         RAY_CCSERR(sc, status, if_oerrors); /* XXX error counter */
1131
1132         /*
1133          * Read back network parameters that the ECF sets
1134          */
1135         SRAM_READ_REGION(sc, ccs, &sc->sc_c.p_1, sizeof(struct ray_cmd_net));
1136
1137         /* Adjust values for buggy firmware */
1138         if (sc->sc_c.np_inited == 0x55)
1139                 sc->sc_c.np_inited = 0;
1140         if (sc->sc_c.np_def_txrate == 0x55)
1141                 sc->sc_c.np_def_txrate = sc->sc_d.np_def_txrate;
1142         if (sc->sc_c.np_encrypt == 0x55)
1143                 sc->sc_c.np_encrypt = sc->sc_d.np_encrypt;
1144
1145         /*
1146          * Update our local state if we updated the network parameters
1147          * when the START_NET or JOIN_NET was issued.
1148          */
1149         if (sc->sc_c.np_upd_param) {
1150                 RAY_DPRINTF(sc, RAY_DBG_STARTJOIN, "updated parameters");
1151                 SRAM_READ_REGION(sc, RAY_HOST_TO_ECF_BASE,
1152                     &sc->sc_c.p_2, sizeof(struct ray_net_params));
1153         }
1154
1155         /*
1156          * Hurrah! The network is now active.
1157          *
1158          * Clearing IFF_OACTIVE will ensure that the system will send us
1159          * packets. Just before we return from the interrupt context
1160          * we check to see if packets have been queued.
1161          */
1162         if (SRAM_READ_FIELD_1(sc, ccs, ray_cmd, c_cmd) == RAY_CMD_START_NET) {
1163                 sc->sc_c.np_havenet = 1;
1164                 sc->sc_c.np_framing = sc->sc_d.np_framing;
1165                 ifp->if_flags |= IFF_RUNNING;
1166                 ifp->if_flags &= ~IFF_OACTIVE;
1167         }
1168
1169         ray_com_ecf_done(sc);
1170 }
1171
1172 /*
1173  * Runq entry to authenticate with an access point or another station
1174  */
1175 static void
1176 ray_init_auth(struct ray_softc *sc, struct ray_comq_entry *com)
1177 {
1178         struct ifnet *ifp = &sc->arpcom.ac_if;
1179
1180         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN | RAY_DBG_AUTH, "");
1181
1182         /* If card already running we might not need to authenticate */
1183         RAY_COM_CHKRUNNING(sc, com, ifp);
1184
1185         /*
1186          * XXX Don't do anything if we are not in a managed network
1187          *
1188          * XXX V4 adhoc does not need this, V5 adhoc unknown
1189          */
1190         if (sc->sc_c.np_net_type != RAY_MIB_NET_TYPE_INFRA) {
1191                 ray_com_runq_done(sc);
1192                 return;
1193         }
1194
1195 /*
1196  * XXX_AUTH need to think of run queue when doing auths from request i.e. would
1197  * XXX_AUTH need to have auth at top of runq?
1198  * XXX_AUTH ditto for sending any auth response packets...what about timeouts?
1199  */
1200
1201         /*
1202          * Kick the card
1203          */
1204 /* XXX_AUTH check exit status and retry or fail as we can't associate without this */
1205         ray_init_auth_send(sc, sc->sc_c.np_bss_id, IEEE80211_AUTH_OPEN_REQUEST);
1206 }
1207
1208 /*
1209  * Build and send an authentication packet
1210  *
1211  * If an error occurs, returns 1 else returns 0.
1212  */
1213 static int
1214 ray_init_auth_send(struct ray_softc *sc, u_int8_t *dst, int sequence)
1215 {
1216         size_t ccs, bufp;
1217         int pktlen = 0;
1218
1219         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN | RAY_DBG_AUTH, "");
1220
1221         /* Get a control block */
1222         if (ray_ccs_tx(sc, &ccs, &bufp)) {
1223                 RAY_RECERR(sc, "could not obtain a ccs");
1224                 return (1);
1225         }
1226
1227         /* Fill the header in */
1228         bufp = ray_tx_wrhdr(sc, bufp,
1229             IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_AUTH,
1230             IEEE80211_FC1_DIR_NODS,
1231             dst,
1232             sc->arpcom.ac_enaddr,
1233             sc->sc_c.np_bss_id);
1234
1235         /* Add algorithm number */
1236         SRAM_WRITE_1(sc, bufp + pktlen++, IEEE80211_AUTH_ALG_OPEN);
1237         SRAM_WRITE_1(sc, bufp + pktlen++, 0);
1238
1239         /* Add sequence number */
1240         SRAM_WRITE_1(sc, bufp + pktlen++, sequence);
1241         SRAM_WRITE_1(sc, bufp + pktlen++, 0);
1242
1243         /* Add status code */
1244         SRAM_WRITE_1(sc, bufp + pktlen++, 0);
1245         SRAM_WRITE_1(sc, bufp + pktlen++, 0);
1246         pktlen += sizeof(struct ieee80211_frame);
1247
1248         return (ray_tx_send(sc, ccs, pktlen, dst));
1249 }
1250
1251 /*
1252  * Complete authentication runq
1253  */
1254 static void
1255 ray_init_auth_done(struct ray_softc *sc, u_int8_t status)
1256 {
1257         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN | RAY_DBG_AUTH, "");
1258
1259         if (status != IEEE80211_STATUS_SUCCESS)
1260                 RAY_RECERR(sc, "authentication failed with status %d", status);
1261 /*
1262  * XXX_AUTH retry? if not just recall ray_init_auth_send and dont clear runq?
1263  * XXX_AUTH association requires that authenitcation is successful
1264  * XXX_AUTH before we associate, and the runq is the only way to halt the
1265  * XXX_AUTH progress of associate.
1266  * XXX_AUTH In this case I might not need the RAY_AUTH_NEEDED state
1267  */
1268         ray_com_runq_done(sc);
1269 }
1270
1271 /*
1272  * Runq entry to starting an association with an access point
1273  */
1274 static void
1275 ray_init_assoc(struct ray_softc *sc, struct ray_comq_entry *com)
1276 {
1277         struct ifnet *ifp = &sc->arpcom.ac_if;
1278
1279         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN, "");
1280
1281         /* If the card already running we might not need to associate */
1282         RAY_COM_CHKRUNNING(sc, com, ifp);
1283
1284         /*
1285          * Don't do anything if we are not in a managed network
1286          */
1287         if (sc->sc_c.np_net_type != RAY_MIB_NET_TYPE_INFRA) {
1288                 ray_com_runq_done(sc);
1289                 return;
1290         }
1291
1292         /*
1293          * Kick the card
1294          */
1295         ray_ccs_fill(sc, com->c_ccs, RAY_CMD_START_ASSOC);
1296         ray_com_ecf(sc, com);
1297 }
1298
1299 /*
1300  * Complete association
1301  */
1302 static void
1303 ray_init_assoc_done(struct ray_softc *sc, u_int8_t status, size_t ccs)
1304 {
1305         struct ifnet *ifp = &sc->arpcom.ac_if;
1306
1307         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN, "");
1308         RAY_COM_CHECK(sc, ccs);
1309
1310         RAY_CCSERR(sc, status, if_oerrors); /* XXX error counter */
1311         
1312         /*
1313          * Hurrah! The network is now active.
1314          *
1315          * Clearing IFF_OACTIVE will ensure that the system will send us
1316          * packets. Just before we return from the interrupt context
1317          * we check to see if packets have been queued.
1318          */
1319         sc->sc_c.np_havenet = 1;
1320         sc->sc_c.np_framing = sc->sc_d.np_framing;
1321         ifp->if_flags |= IFF_RUNNING;
1322         ifp->if_flags &= ~IFF_OACTIVE;
1323
1324         ray_com_ecf_done(sc);
1325 }
1326
1327 /*
1328  * Network stop.
1329  *
1330  * Inhibit card - if we can't prevent reception then do not worry;
1331  * stopping a NIC only guarantees no TX.
1332  *
1333  * The change to the interface flags is done via the runq so that any
1334  * existing commands can execute normally.
1335  */
1336 static int
1337 ray_stop_user(struct ray_softc *sc)
1338 {
1339         struct ray_comq_entry *com[1];
1340         int error, ncom;
1341
1342         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STOP, "");
1343
1344         /*
1345          * Schedule the real stop routine
1346          */
1347         ncom = 0;
1348         com[ncom++] = RAY_COM_MALLOC(ray_stop, 0);
1349
1350         RAY_COM_RUNQ(sc, com, ncom, "raystop", error);
1351
1352         /* XXX no real error processing from anything yet! */
1353
1354         RAY_COM_FREE(com, ncom);
1355
1356         return (error);
1357 }
1358
1359 /*
1360  * Runq entry for stopping the interface activity
1361  */
1362 static void
1363 ray_stop(struct ray_softc *sc, struct ray_comq_entry *com)
1364 {
1365         struct ifnet *ifp = &sc->arpcom.ac_if;
1366         struct mbuf *m;
1367
1368         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STOP, "");
1369
1370         /*
1371          * Mark as not running and drain output queue
1372          */
1373         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
1374         ifp->if_timer = 0;
1375         for (;;) {
1376                 IF_DEQUEUE(&ifp->if_snd, m);
1377                 if (m == NULL)
1378                         break;
1379                 m_freem(m);
1380         }
1381
1382         ray_com_runq_done(sc);
1383 }
1384
1385 static void
1386 ray_watchdog(struct ifnet *ifp)
1387 {
1388         struct ray_softc *sc = ifp->if_softc;
1389
1390         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
1391         RAY_MAP_CM(sc);
1392
1393         if ((sc == NULL) || (sc->sc_gone))
1394                 return;
1395
1396         RAY_PRINTF(sc, "watchdog timeout");
1397 }
1398
1399 /*
1400  * Transmit packet handling
1401  */
1402
1403 /*
1404  * Send a packet.
1405  *
1406  * We make two assumptions here:
1407  *  1) That the current priority is set to splimp _before_ this code
1408  *     is called *and* is returned to the appropriate priority after
1409  *     return
1410  *  2) That the IFF_OACTIVE flag is checked before this code is called
1411  *     (i.e. that the output part of the interface is idle)
1412  *
1413  * A simple one packet at a time TX routine is used - we don't bother
1414  * chaining TX buffers. Performance is sufficient to max out the
1415  * wireless link on a P75.
1416  *
1417  * AST J30 Windows 95A (100MHz Pentium) to
1418  *   Libretto 50CT FreeBSD-3.1 (75MHz Pentium)          167.37kB/s
1419  *   Nonname box FreeBSD-3.4 (233MHz AMD K6)            161.82kB/s
1420  *
1421  * Libretto 50CT FreeBSD-3.1 (75MHz Pentium) to
1422  *   AST J30 Windows 95A (100MHz Pentium)               167.37kB/s
1423  *   Nonname box FreeBSD-3.4 (233MHz AMD K6)            161.38kB/s
1424  *
1425  * Given that 160kB/s is saturating the 2Mb/s wireless link we
1426  * are about there.
1427  *
1428  * In short I'm happy that the added complexity of chaining TX
1429  * packets together isn't worth it for my machines.
1430  */
1431 static void
1432 ray_tx(struct ifnet *ifp)
1433 {
1434         struct ray_softc *sc = ifp->if_softc;
1435         struct mbuf *m0, *m;
1436         struct ether_header *eh;
1437         struct llc *llc;
1438         size_t ccs, bufp;
1439         int pktlen, len;
1440
1441         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_TX, "");
1442         RAY_MAP_CM(sc);
1443
1444         /*
1445          * Some simple checks first - some are overkill
1446          */
1447         if ((sc == NULL) || (sc->sc_gone))
1448                 return;
1449         if (!(ifp->if_flags & IFF_RUNNING)) {
1450                 RAY_RECERR(sc, "cannot transmit - not running");
1451                 return;
1452         }
1453         if (!sc->sc_c.np_havenet) {
1454                 RAY_RECERR(sc, "cannot transmit - no network");
1455                 return;
1456         }
1457         if (!RAY_ECF_READY(sc)) {
1458                 /* Can't assume that the ECF is busy because of this driver */
1459                 if ((sc->tx_timerh.callout == NULL) ||
1460                     (!callout_active(sc->tx_timerh.callout))) {
1461                         sc->tx_timerh =
1462                             timeout(ray_tx_timo, sc, RAY_TX_TIMEOUT);
1463                         return;
1464                     }
1465         } else
1466                 untimeout(ray_tx_timo, sc, sc->tx_timerh);
1467
1468         /*
1469          * We find a ccs before we process the mbuf so that we are sure it
1470          * is worthwhile processing the packet. All errors in the mbuf
1471          * processing are either errors in the mbuf or gross configuration
1472          * errors and the packet wouldn't get through anyway.
1473          */
1474         if (ray_ccs_tx(sc, &ccs, &bufp)) {
1475                 ifp->if_flags |= IFF_OACTIVE;
1476                 return;
1477         }
1478     
1479         /*
1480          * Get the mbuf and process it - we have to remember to free the
1481          * ccs if there are any errors.
1482          */
1483         IF_DEQUEUE(&ifp->if_snd, m0);
1484         if (m0 == NULL) {
1485                 RAY_CCS_FREE(sc, ccs);
1486                 return;
1487         }
1488
1489         pktlen = m0->m_pkthdr.len;
1490         if (pktlen > ETHER_MAX_LEN - ETHER_CRC_LEN) {
1491                 RAY_RECERR(sc, "mbuf too long %d", pktlen);
1492                 RAY_CCS_FREE(sc, ccs);
1493                 ifp->if_oerrors++;
1494                 m_freem(m0);
1495                 return;
1496         }
1497
1498         m0 = m_pullup(m0, sizeof(struct ether_header));
1499         if (m0 == NULL) {
1500                 RAY_RECERR(sc, "could not pullup ether");
1501                 RAY_CCS_FREE(sc, ccs);
1502                 ifp->if_oerrors++;
1503                 return;
1504         }
1505         eh = mtod(m0, struct ether_header *);
1506
1507         /*
1508          * Write the 802.11 header according to network type etc.
1509          */
1510         if (sc->sc_c.np_net_type == RAY_MIB_NET_TYPE_ADHOC)
1511                 bufp = ray_tx_wrhdr(sc, bufp,
1512                     IEEE80211_FC0_TYPE_DATA,
1513                     IEEE80211_FC1_DIR_NODS,
1514                     eh->ether_dhost,
1515                     eh->ether_shost,
1516                     sc->sc_c.np_bss_id);
1517         else
1518                 if (sc->sc_c.np_ap_status == RAY_MIB_AP_STATUS_TERMINAL)
1519                         bufp = ray_tx_wrhdr(sc, bufp,
1520                             IEEE80211_FC0_TYPE_DATA,
1521                             IEEE80211_FC1_DIR_TODS,
1522                             sc->sc_c.np_bss_id,
1523                             eh->ether_shost,
1524                             eh->ether_dhost);
1525                 else
1526                         bufp = ray_tx_wrhdr(sc, bufp,
1527                             IEEE80211_FC0_TYPE_DATA,
1528                             IEEE80211_FC1_DIR_FROMDS,
1529                             eh->ether_dhost,
1530                             sc->sc_c.np_bss_id,
1531                             eh->ether_shost);
1532
1533         /*
1534          * Framing
1535          *
1536          * Add to the mbuf.
1537          */
1538         switch (sc->sc_c.np_framing) {
1539
1540         case RAY_FRAMING_ENCAPSULATION:
1541                 /* Nice and easy - nothing! (just add an 802.11 header) */
1542                 break;
1543
1544         case RAY_FRAMING_TRANSLATION:
1545                 /*
1546                  * Drop the first address in the ethernet header and
1547                  * write an LLC and SNAP header over the second.
1548                  */
1549                 m_adj(m0, ETHER_ADDR_LEN);
1550                 if (m0 == NULL) {
1551                         RAY_RECERR(sc, "could not get space for 802.2 header");
1552                         RAY_CCS_FREE(sc, ccs);
1553                         ifp->if_oerrors++;
1554                         return;
1555                 }
1556                 llc = mtod(m0, struct llc *);
1557                 llc->llc_dsap = LLC_SNAP_LSAP;
1558                 llc->llc_ssap = LLC_SNAP_LSAP;
1559                 llc->llc_control = LLC_UI;
1560                 llc->llc_un.type_snap.org_code[0] = 0;
1561                 llc->llc_un.type_snap.org_code[1] = 0;
1562                 llc->llc_un.type_snap.org_code[2] = 0;
1563                 break;
1564
1565         default:
1566                 RAY_RECERR(sc, "unknown framing type %d", sc->sc_c.np_framing);
1567                 RAY_CCS_FREE(sc, ccs);
1568                 ifp->if_oerrors++;
1569                 m_freem(m0);
1570                 return;
1571
1572         }
1573         if (m0 == NULL) {
1574                 RAY_RECERR(sc, "could not frame packet");
1575                 RAY_CCS_FREE(sc, ccs);
1576                 ifp->if_oerrors++;
1577                 return;
1578         }
1579         RAY_MBUF_DUMP(sc, RAY_DBG_TX, m0, "framed packet");
1580
1581         /*
1582          * Copy the mbuf to the buffer in common memory
1583          *
1584          * We drop and don't bother wrapping as Ethernet packets are 1518
1585          * bytes, we checked the mbuf earlier, and our TX buffers are 2048
1586          * bytes. We don't have 530 bytes of headers etc. so something
1587          * must be fubar.
1588          */
1589         pktlen = sizeof(struct ieee80211_frame);
1590         for (m = m0; m != NULL; m = m->m_next) {
1591                 pktlen += m->m_len;
1592                 if ((len = m->m_len) == 0)
1593                         continue;
1594                 if ((bufp + len) < RAY_TX_END)
1595                         SRAM_WRITE_REGION(sc, bufp, mtod(m, u_int8_t *), len);
1596                 else {
1597                         RAY_RECERR(sc, "tx buffer overflow");
1598                         RAY_CCS_FREE(sc, ccs);
1599                         ifp->if_oerrors++;
1600                         m_freem(m0);
1601                         return;
1602                 }
1603                 bufp += len;
1604         }
1605
1606         /*
1607          * Send it off
1608          */
1609         if (ray_tx_send(sc, ccs, pktlen, eh->ether_dhost))
1610                 ifp->if_oerrors++;
1611         else
1612                 ifp->if_opackets++;
1613         m_freem(m0);
1614 }
1615
1616 /*
1617  * Start timeout routine.
1618  *
1619  * Used when card was busy but we needed to send a packet.
1620  */
1621 static void
1622 ray_tx_timo(void *xsc)
1623 {
1624         struct ray_softc *sc = (struct ray_softc *)xsc;
1625         struct ifnet *ifp = &sc->arpcom.ac_if;
1626         int s;
1627
1628         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
1629
1630         if (!(ifp->if_flags & IFF_OACTIVE) && (ifp->if_snd.ifq_head != NULL)) {
1631                 s = splimp();
1632                 ray_tx(ifp);
1633                 splx(s);
1634         }
1635 }
1636
1637 /*
1638  * Write an 802.11 header into the Tx buffer space and return the
1639  * adjusted buffer pointer.
1640  */
1641 static size_t
1642 ray_tx_wrhdr(struct ray_softc *sc, size_t bufp, u_int8_t type, u_int8_t fc1, u_int8_t *addr1, u_int8_t *addr2, u_int8_t *addr3)
1643 {
1644         struct ieee80211_frame header;
1645
1646         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_TX, "");
1647         RAY_MAP_CM(sc);
1648
1649         bzero(&header, sizeof(struct ieee80211_frame));
1650         header.i_fc[0] = (IEEE80211_FC0_VERSION_0 | type);
1651         header.i_fc[1] = fc1;
1652         bcopy(addr1, header.i_addr1, ETHER_ADDR_LEN);
1653         bcopy(addr2, header.i_addr2, ETHER_ADDR_LEN);
1654         bcopy(addr3, header.i_addr3, ETHER_ADDR_LEN);
1655
1656         SRAM_WRITE_REGION(sc, bufp, (u_int8_t *)&header,
1657             sizeof(struct ieee80211_frame));
1658
1659         return (bufp + sizeof(struct ieee80211_frame));
1660 }
1661
1662 /*
1663  * Fill in a few loose ends and kick the card to send the packet
1664  *
1665  * Returns 0 on success, 1 on failure
1666  */
1667 static int
1668 ray_tx_send(struct ray_softc *sc, size_t ccs, int pktlen, u_int8_t *dst)
1669 {
1670         int i = 0;
1671
1672         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_TX, "");
1673         RAY_MAP_CM(sc);
1674
1675         while (!RAY_ECF_READY(sc)) {
1676                 DELAY(RAY_ECF_SPIN_DELAY);
1677                 if (++i > RAY_ECF_SPIN_TRIES) {
1678                         RAY_RECERR(sc, "ECF busy, dropping packet");
1679                         RAY_CCS_FREE(sc, ccs);
1680                         return (1);
1681                 }
1682         }
1683         if (i != 0)
1684                 RAY_RECERR(sc, "spun %d times", i);
1685
1686         SRAM_WRITE_FIELD_2(sc, ccs, ray_cmd_tx, c_len, pktlen);
1687         SRAM_WRITE_FIELD_1(sc, ccs, ray_cmd_tx, c_antenna,
1688             ray_tx_best_antenna(sc, dst));
1689         SRAM_WRITE_1(sc, RAY_SCB_CCSI, RAY_CCS_INDEX(ccs));
1690         RAY_ECF_START_CMD(sc);
1691
1692         return (0);
1693 }
1694
1695 /*
1696  * Determine best antenna to use from rx level and antenna cache
1697  */
1698 static u_int8_t
1699 ray_tx_best_antenna(struct ray_softc *sc, u_int8_t *dst)
1700 {
1701         struct ray_siglev *sl;
1702         int i;
1703         u_int8_t antenna;
1704
1705         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_TX, "");
1706
1707         if (sc->sc_version == RAY_ECFS_BUILD_4) 
1708                 return (0);
1709
1710         /* try to find host */
1711         for (i = 0; i < RAY_NSIGLEVRECS; i++) {
1712                 sl = &sc->sc_siglevs[i];
1713                 if (bcmp(sl->rsl_host, dst, ETHER_ADDR_LEN) == 0)
1714                         goto found;
1715         }
1716         /* not found, return default setting */
1717         return (0);
1718
1719 found:
1720         /* This is a simple thresholding scheme that takes the mean
1721          * of the best antenna history. This is okay but as it is a
1722          * filter, it adds a bit of lag in situations where the
1723          * best antenna swaps from one side to the other slowly. Don't know
1724          * how likely this is given the horrible fading though.
1725          */
1726         antenna = 0;
1727         for (i = 0; i < RAY_NANTENNA; i++) {
1728                 antenna += sl->rsl_antennas[i];
1729         }
1730
1731         return (antenna > (RAY_NANTENNA >> 1));
1732 }
1733
1734 /*
1735  * Transmit now complete so clear ccs and network flags.
1736  */
1737 static void
1738 ray_tx_done(struct ray_softc *sc, u_int8_t status, size_t ccs)
1739 {
1740         struct ifnet *ifp = &sc->arpcom.ac_if;
1741
1742         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_TX, "");
1743
1744         RAY_CCSERR(sc, status, if_oerrors);
1745
1746         RAY_CCS_FREE(sc, ccs);
1747         ifp->if_timer = 0;
1748         if (ifp->if_flags & IFF_OACTIVE)
1749             ifp->if_flags &= ~IFF_OACTIVE;
1750 }
1751
1752 /*
1753  * Receiver packet handling
1754  */
1755
1756 /*
1757  * Receive a packet from the card
1758  */
1759 static void
1760 ray_rx(struct ray_softc *sc, size_t rcs)
1761 {
1762         struct ieee80211_frame *header;
1763         struct ifnet *ifp = &sc->arpcom.ac_if;
1764         struct mbuf *m0;
1765         size_t pktlen, fraglen, readlen, tmplen;
1766         size_t bufp, ebufp;
1767         u_int8_t siglev, antenna;
1768         u_int first, ni, i;
1769         u_int8_t *mp;
1770
1771         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
1772         RAY_MAP_CM(sc);
1773
1774         RAY_DPRINTF(sc, RAY_DBG_CCS, "using rcs 0x%x", rcs);
1775
1776         m0 = NULL;
1777         readlen = 0;
1778
1779         /*
1780          * Get first part of packet and the length. Do some sanity checks
1781          * and get a mbuf.
1782          */
1783         first = RAY_CCS_INDEX(rcs);
1784         pktlen = SRAM_READ_FIELD_2(sc, rcs, ray_cmd_rx, c_pktlen);
1785         siglev = SRAM_READ_FIELD_1(sc, rcs, ray_cmd_rx, c_siglev);
1786         antenna = SRAM_READ_FIELD_1(sc, rcs, ray_cmd_rx, c_antenna);
1787
1788         if ((pktlen > MCLBYTES) || (pktlen < sizeof(struct ieee80211_frame))) {
1789                 RAY_RECERR(sc, "packet too big or too small");
1790                 ifp->if_ierrors++;
1791                 goto skip_read;
1792         }
1793
1794         MGETHDR(m0, M_DONTWAIT, MT_DATA);
1795         if (m0 == NULL) {
1796                 RAY_RECERR(sc, "MGETHDR failed");
1797                 ifp->if_ierrors++;
1798                 goto skip_read;
1799         }
1800         if (pktlen > MHLEN) {
1801                 MCLGET(m0, M_DONTWAIT);
1802                 if (!(m0->m_flags & M_EXT)) {
1803                         RAY_RECERR(sc, "MCLGET failed");
1804                         ifp->if_ierrors++;
1805                         m_freem(m0);
1806                         m0 = NULL;
1807                         goto skip_read;
1808                 }
1809         }
1810         m0->m_pkthdr.rcvif = ifp;
1811         m0->m_pkthdr.len = pktlen;
1812         m0->m_len = pktlen;
1813         mp = mtod(m0, u_int8_t *);
1814
1815         /*
1816          * Walk the fragment chain to build the complete packet.
1817          *
1818          * The use of two index variables removes a race with the
1819          * hardware. If one index were used the clearing of the CCS would
1820          * happen before reading the next pointer and the hardware can get in.
1821          * Not my idea but verbatim from the NetBSD driver.
1822          */
1823         i = ni = first;
1824         while ((i = ni) && (i != RAY_CCS_LINK_NULL)) {
1825                 rcs = RAY_CCS_ADDRESS(i);
1826                 ni = SRAM_READ_FIELD_1(sc, rcs, ray_cmd_rx, c_nextfrag);
1827                 bufp = SRAM_READ_FIELD_2(sc, rcs, ray_cmd_rx, c_bufp);
1828                 fraglen = SRAM_READ_FIELD_2(sc, rcs, ray_cmd_rx, c_len);
1829                 if (fraglen + readlen > pktlen) {
1830                         RAY_RECERR(sc, "bad length current 0x%x pktlen 0x%x",
1831                             fraglen + readlen, pktlen);
1832                         ifp->if_ierrors++;
1833                         m_freem(m0);
1834                         m0 = NULL;
1835                         goto skip_read;
1836                 }
1837                 if ((i < RAY_RCS_FIRST) || (i > RAY_RCS_LAST)) {
1838                         RAY_RECERR(sc, "bad rcs index 0x%x", i);
1839                         ifp->if_ierrors++;
1840                         m_freem(m0);
1841                         m0 = NULL;
1842                         goto skip_read;
1843                 }
1844
1845                 ebufp = bufp + fraglen;
1846                 if (ebufp <= RAY_RX_END)
1847                         SRAM_READ_REGION(sc, bufp, mp, fraglen);
1848                 else {
1849                         SRAM_READ_REGION(sc, bufp, mp,
1850                             (tmplen = RAY_RX_END - bufp));
1851                         SRAM_READ_REGION(sc, RAY_RX_BASE, mp + tmplen,
1852                             ebufp - RAY_RX_END);
1853                 }
1854                 mp += fraglen;
1855                 readlen += fraglen;
1856         }
1857
1858 skip_read:
1859
1860         /*
1861          * Walk the chain again to free the rcss.
1862          */
1863         i = ni = first;
1864         while ((i = ni) && (i != RAY_CCS_LINK_NULL)) {
1865                 rcs = RAY_CCS_ADDRESS(i);
1866                 ni = SRAM_READ_FIELD_1(sc, rcs, ray_cmd_rx, c_nextfrag);
1867                 RAY_CCS_FREE(sc, rcs);
1868         }
1869
1870         if (m0 == NULL)
1871                 return;
1872
1873         /*
1874          * Check the 802.11 packet type and hand off to
1875          * appropriate functions.
1876          */
1877         header = mtod(m0, struct ieee80211_frame *);
1878         if ((header->i_fc[0] & IEEE80211_FC0_VERSION_MASK)
1879             != IEEE80211_FC0_VERSION_0) {
1880                 RAY_RECERR(sc, "header not version 0 fc0 0x%x",
1881                     header->i_fc[0]);
1882                 ifp->if_ierrors++;
1883                 m_freem(m0);
1884                 return;
1885         }
1886         switch (header->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
1887
1888         case IEEE80211_FC0_TYPE_DATA:
1889                 ray_rx_data(sc, m0, siglev, antenna);
1890                 break;
1891
1892         case IEEE80211_FC0_TYPE_MGT:
1893                 ray_rx_mgt(sc, m0);
1894                 break;
1895
1896         case IEEE80211_FC0_TYPE_CTL:
1897                 ray_rx_ctl(sc, m0);
1898                 break;
1899
1900         default:
1901                 RAY_RECERR(sc, "unknown packet fc0 0x%x", header->i_fc[0]);
1902                 ifp->if_ierrors++;
1903                 m_freem(m0);
1904         }
1905 }
1906
1907 /*
1908  * Deal with DATA packet types
1909  */
1910 static void
1911 ray_rx_data(struct ray_softc *sc, struct mbuf *m0, u_int8_t siglev, u_int8_t antenna)
1912 {
1913         struct ifnet *ifp = &sc->arpcom.ac_if;
1914         struct ieee80211_frame *header = mtod(m0, struct ieee80211_frame *);
1915         struct ether_header *eh;
1916         struct llc *llc;
1917         u_int8_t *sa = NULL, *da = NULL, *ra = NULL, *ta = NULL;
1918         int trim = 0;
1919
1920         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_RX, "");
1921
1922         /*
1923          * Check the the data packet subtype, some packets have
1924          * nothing in them so we will drop them here.
1925          */
1926         switch (header->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) {
1927
1928         case IEEE80211_FC0_SUBTYPE_DATA:
1929         case IEEE80211_FC0_SUBTYPE_CF_ACK:
1930         case IEEE80211_FC0_SUBTYPE_CF_POLL:
1931         case IEEE80211_FC0_SUBTYPE_CF_ACPL:
1932                 RAY_DPRINTF(sc, RAY_DBG_RX, "DATA packet");
1933                 break;
1934
1935         case IEEE80211_FC0_SUBTYPE_NODATA:
1936         case IEEE80211_FC0_SUBTYPE_CFACK:
1937         case IEEE80211_FC0_SUBTYPE_CFPOLL:
1938         case IEEE80211_FC0_SUBTYPE_CF_ACK_CF_ACK:
1939                 RAY_DPRINTF(sc, RAY_DBG_RX, "NULL packet");
1940                 m_freem(m0);
1941                 return;
1942                 break;
1943
1944         default:
1945                 RAY_RECERR(sc, "reserved DATA packet subtype 0x%x",
1946                     header->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
1947                 ifp->if_ierrors++;
1948                 m_freem(m0);
1949                 return;
1950         }
1951
1952         /*
1953          * Parse the To DS and From DS fields to determine the length
1954          * of the 802.11 header for use later on.
1955          *
1956          * Additionally, furtle out the right destination and
1957          * source MAC addresses for the packet. Packets may come via
1958          * APs so the MAC addresses of the immediate node may be
1959          * different from the node that actually sent us the packet.
1960          *
1961          *      da      destination address of final recipient
1962          *      sa      source address of orginator
1963          *      ra      receiver address of immediate recipient
1964          *      ta      transmitter address of immediate orginator
1965          *
1966          * Address matching is performed on da or sa with the AP or
1967          * BSSID in ra and ta.
1968          */
1969         RAY_MBUF_DUMP(sc, RAY_DBG_RX, m0, "(1) packet before framing");
1970         switch (header->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
1971
1972         case IEEE80211_FC1_DIR_NODS:
1973                 da = ra = header->i_addr1;
1974                 sa = ta = header->i_addr2;
1975                 trim = sizeof(struct ieee80211_frame);
1976                 RAY_DPRINTF(sc, RAY_DBG_RX, "from %6D to %6D",
1977                     sa, ":", da, ":");
1978                 break;
1979
1980         case IEEE80211_FC1_DIR_FROMDS:
1981                 da = ra = header->i_addr1;
1982                 ta = header->i_addr2;
1983                 sa = header->i_addr3;
1984                 trim = sizeof(struct ieee80211_frame);
1985                 RAY_DPRINTF(sc, RAY_DBG_RX, "ap %6D from %6D to %6D",
1986                     ta, ":", sa, ":", da, ":");
1987                 break;
1988
1989         case IEEE80211_FC1_DIR_TODS:
1990                 ra = header->i_addr1;
1991                 sa = ta = header->i_addr2;
1992                 da = header->i_addr3;
1993                 trim = sizeof(struct ieee80211_frame);
1994                 RAY_DPRINTF(sc, RAY_DBG_RX, "from %6D to %6D ap %6D",
1995                     sa, ":", da, ":", ra, ":");
1996                 break;
1997
1998         case IEEE80211_FC1_DIR_DSTODS:
1999                 ra = header->i_addr1;
2000                 ta = header->i_addr2;
2001                 da = header->i_addr3;
2002                 sa = (u_int8_t *)header+1;
2003                 trim = sizeof(struct ieee80211_frame) + ETHER_ADDR_LEN;
2004                 RAY_DPRINTF(sc, RAY_DBG_RX, "from %6D to %6D ap %6D to %6D",
2005                     sa, ":", da, ":", ta, ":", ra, ":");
2006                 break;
2007         }
2008
2009         /*
2010          * Framing
2011          *
2012          * Each case must leave an Ethernet header and adjust trim.
2013          */
2014         switch (sc->sc_c.np_framing) {
2015
2016         case RAY_FRAMING_ENCAPSULATION:
2017                 /* A NOP as the Ethernet header is in the packet */
2018                 break;
2019
2020         case RAY_FRAMING_TRANSLATION:
2021                 /* Check that we have an LLC and SNAP sequence */
2022                 llc = (struct llc *)((u_int8_t *)header + trim);
2023                 if (llc->llc_dsap == LLC_SNAP_LSAP &&
2024                     llc->llc_ssap == LLC_SNAP_LSAP &&
2025                     llc->llc_control == LLC_UI &&
2026                     llc->llc_un.type_snap.org_code[0] == 0 &&
2027                     llc->llc_un.type_snap.org_code[1] == 0 &&
2028                     llc->llc_un.type_snap.org_code[2] == 0) {
2029                         /*
2030                          * This is not magic. RFC1042 header is 8
2031                          * bytes, with the last two bytes being the
2032                          * ether type. So all we need is another
2033                          * ETHER_ADDR_LEN bytes to write the
2034                          * destination into.
2035                          */
2036                         trim -= ETHER_ADDR_LEN;
2037                         eh = (struct ether_header *)((u_int8_t *)header + trim);
2038
2039                         /*
2040                          * Copy carefully to avoid mashing the MAC
2041                          * addresses. The address layout in the .11 header
2042                          * does make sense, honest, but it is a pain.
2043                          * 
2044                          * NODS         da sa           no risk              
2045                          * FROMDS       da ta sa        sa then da           
2046                          * DSTODS       ra ta da sa     sa then da           
2047                          * TODS         ra sa da        da then sa           
2048                          */
2049                         if (sa > da) {
2050                                 /* Copy sa first */
2051                                 bcopy(sa, eh->ether_shost, ETHER_ADDR_LEN);
2052                                 bcopy(da, eh->ether_dhost, ETHER_ADDR_LEN);
2053                         } else {
2054                                 /* Copy da first */
2055                                 bcopy(da, eh->ether_dhost, ETHER_ADDR_LEN);
2056                                 bcopy(sa, eh->ether_shost, ETHER_ADDR_LEN);
2057                         }
2058
2059                 } else {
2060
2061                         /* Assume RAY_FRAMING_ENCAPSULATION */
2062                         RAY_RECERR(sc,
2063                             "got encapsulated packet but in translation mode");
2064
2065                 }
2066                 break;
2067
2068         default:
2069                 RAY_RECERR(sc, "unknown framing type %d", sc->sc_c.np_framing);
2070                 ifp->if_ierrors++;
2071                 m_freem(m0);
2072                 return;
2073         }
2074         RAY_MBUF_DUMP(sc, RAY_DBG_RX, m0, "(2) packet after framing");
2075
2076         /*
2077          * Finally, do a bit of house keeping before sending the packet
2078          * up the stack.
2079          */
2080         m_adj(m0, trim);
2081         RAY_MBUF_DUMP(sc, RAY_DBG_RX, m0, "(3) packet after trimming");
2082         ifp->if_ipackets++;
2083         ray_rx_update_cache(sc, header->i_addr2, siglev, antenna);
2084         eh = mtod(m0, struct ether_header *);
2085         m_adj(m0, sizeof(struct ether_header));
2086         ether_input(ifp, eh, m0);
2087 }
2088
2089 /*
2090  * Deal with MGT packet types
2091  */
2092 static void
2093 ray_rx_mgt(struct ray_softc *sc, struct mbuf *m0)
2094 {
2095         struct ifnet *ifp = &sc->arpcom.ac_if;
2096         struct ieee80211_frame *header = mtod(m0, struct ieee80211_frame *);
2097
2098         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_MGT, "");
2099
2100         if ((header->i_fc[1] & IEEE80211_FC1_DIR_MASK) !=
2101             IEEE80211_FC1_DIR_NODS) {
2102                 RAY_RECERR(sc, "MGT TODS/FROMDS wrong fc1 0x%x",
2103                     header->i_fc[1] & IEEE80211_FC1_DIR_MASK);
2104                 ifp->if_ierrors++;
2105                 m_freem(m0);
2106                 return;
2107         }
2108
2109         /*
2110          * Check the the mgt packet subtype, some packets should be
2111          * dropped depending on the mode the station is in. See pg
2112          * 52(60) of docs
2113          *
2114          * P - proccess, J - Junk, E - ECF deals with, I - Illegal
2115          * ECF Proccesses
2116          *  AHDOC procces or junk
2117          *   INFRA STA process or junk
2118          *    INFRA AP process or jumk
2119          * 
2120          * +PPP IEEE80211_FC0_SUBTYPE_BEACON
2121          * +EEE IEEE80211_FC0_SUBTYPE_PROBE_REQ
2122          * +EEE IEEE80211_FC0_SUBTYPE_PROBE_RESP
2123          *  PPP IEEE80211_FC0_SUBTYPE_AUTH
2124          *  PPP IEEE80211_FC0_SUBTYPE_DEAUTH
2125          *  JJP IEEE80211_FC0_SUBTYPE_ASSOC_REQ
2126          *  JPJ IEEE80211_FC0_SUBTYPE_ASSOC_RESP
2127          *  JPP IEEE80211_FC0_SUBTYPE_DISASSOC
2128          *  JJP IEEE80211_FC0_SUBTYPE_REASSOC_REQ
2129          *  JPJ IEEE80211_FC0_SUBTYPE_REASSOC_RESP
2130          * +EEE IEEE80211_FC0_SUBTYPE_ATIM
2131          */
2132         RAY_MBUF_DUMP(sc, RAY_DBG_MGT, m0, "MGT packet");
2133         switch (header->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) {
2134
2135         case IEEE80211_FC0_SUBTYPE_BEACON:
2136                 RAY_DPRINTF(sc, RAY_DBG_MGT, "BEACON MGT packet");
2137                 ray_rx_mgt_beacon(sc, m0);
2138                 break;
2139
2140         case IEEE80211_FC0_SUBTYPE_AUTH:
2141                 RAY_DPRINTF(sc, RAY_DBG_MGT, "AUTH MGT packet");
2142                 ray_rx_mgt_auth(sc, m0);
2143                 break;
2144
2145         case IEEE80211_FC0_SUBTYPE_DEAUTH:
2146                 RAY_DPRINTF(sc, RAY_DBG_MGT, "DEAUTH MGT packet");
2147                 /* XXX ray_rx_mgt_deauth(sc, m0); */
2148                 break;
2149
2150         case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
2151         case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
2152                 RAY_DPRINTF(sc, RAY_DBG_MGT, "(RE)ASSOC_REQ MGT packet");
2153                 if ((sc->sc_c.np_net_type == RAY_MIB_NET_TYPE_INFRA) &&
2154                     (sc->sc_c.np_ap_status == RAY_MIB_AP_STATUS_AP))
2155                         RAY_RECERR(sc, "can't be an AP yet"); /* XXX_ACTING_AP */
2156                 break;
2157                         
2158         case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
2159         case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
2160                 RAY_DPRINTF(sc, RAY_DBG_MGT, "(RE)ASSOC_RESP MGT packet");
2161                 if ((sc->sc_c.np_net_type == RAY_MIB_NET_TYPE_INFRA) &&
2162                     (sc->sc_c.np_ap_status == RAY_MIB_AP_STATUS_TERMINAL))
2163                         RAY_RECERR(sc, "can't be in INFRA yet"); /* XXX_INFRA */
2164                 break;
2165
2166         case IEEE80211_FC0_SUBTYPE_DISASSOC:
2167                 RAY_DPRINTF(sc, RAY_DBG_MGT, "DISASSOC MGT packet");
2168                 if (sc->sc_c.np_net_type == RAY_MIB_NET_TYPE_INFRA)
2169                         RAY_RECERR(sc, "can't be in INFRA yet"); /* XXX_INFRA */
2170                 break;
2171
2172         case IEEE80211_FC0_SUBTYPE_PROBE_REQ:
2173         case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
2174         case IEEE80211_FC0_SUBTYPE_ATIM:
2175                 RAY_RECERR(sc, "unexpected MGT packet subtype 0x%0x",
2176                     header->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
2177                 ifp->if_ierrors++;
2178                 break;
2179                 
2180         default:
2181                 RAY_RECERR(sc, "reserved MGT packet subtype 0x%x",
2182                     header->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
2183                 ifp->if_ierrors++;
2184         }
2185
2186         m_freem(m0);
2187 }
2188
2189 /*
2190  * Deal with BEACON management packet types
2191  * XXX furtle anything interesting out
2192  * XXX Note that there are rules governing what beacons to read
2193  * XXX see 8802 S7.2.3, S11.1.2.3
2194  * XXX is this actually useful?
2195  */
2196 static void
2197 ray_rx_mgt_beacon(struct ray_softc *sc, struct mbuf *m0)
2198 {
2199         struct ieee80211_frame *header = mtod(m0, struct ieee80211_frame *);
2200         ieee80211_mgt_beacon_t beacon = (u_int8_t *)(header+1);
2201         struct ieee80211_information elements;
2202
2203         u_int64_t *timestamp;
2204
2205         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_MGT, "");
2206
2207         timestamp = (u_int64_t *)beacon;
2208
2209 RAY_DPRINTF(sc, RAY_DBG_MGT, "timestamp\t0x%x", *timestamp);
2210 RAY_DPRINTF(sc, RAY_DBG_MGT, "interval\t\t0x%x", IEEE80211_BEACON_INTERVAL(beacon));
2211 RAY_DPRINTF(sc, RAY_DBG_MGT, "capability\t0x%x", IEEE80211_BEACON_CAPABILITY(beacon));
2212
2213         ray_rx_mgt_info(sc, m0, &elements);
2214
2215 }
2216
2217 static void
2218 ray_rx_mgt_info(struct ray_softc *sc, struct mbuf *m0, struct ieee80211_information *elements)
2219 {
2220         struct ifnet *ifp = &sc->arpcom.ac_if;
2221         struct ieee80211_frame *header = mtod(m0, struct ieee80211_frame *);
2222         ieee80211_mgt_beacon_t beacon = (u_int8_t *)(header+1);
2223         ieee80211_mgt_beacon_t bp, be;
2224         int len;
2225
2226         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_MGT, "");
2227
2228         bp = beacon + 12;
2229         be = mtod(m0, u_int8_t *) + m0->m_len;
2230         
2231         while (bp < be) {
2232                 len = *(bp + 1);
2233                 RAY_DPRINTF(sc, RAY_DBG_MGT, "id 0x%02x length %d", *bp, len);
2234
2235                 switch (*bp) {
2236
2237                 case IEEE80211_ELEMID_SSID:
2238                         if (len  > IEEE80211_NWID_LEN) {
2239                                 RAY_RECERR(sc, "bad SSD length: %d from %6D",
2240                                     len, header->i_addr2, ":");
2241                         }
2242                         strncpy(elements->ssid, bp + 2, len);
2243                         elements->ssid[len] = 0;
2244                         RAY_DPRINTF(sc, RAY_DBG_MGT,
2245                             "beacon ssid %s", elements->ssid);
2246                         break; 
2247
2248                 case IEEE80211_ELEMID_RATES:
2249                         RAY_DPRINTF(sc, RAY_DBG_MGT, "rates");
2250                         break;
2251
2252                 case IEEE80211_ELEMID_FHPARMS:
2253                         elements->fh.dwell = bp[2] + (bp[3] << 8);
2254                         elements->fh.set = bp[4];
2255                         elements->fh.pattern = bp[5];
2256                         elements->fh.index = bp[6];
2257                         RAY_DPRINTF(sc, RAY_DBG_MGT,
2258                             "fhparams dwell\t0x%04x", elements->fh.dwell);
2259                         RAY_DPRINTF(sc, RAY_DBG_MGT,
2260                             "fhparams set\t0x%02x", elements->fh.set);
2261                         RAY_DPRINTF(sc, RAY_DBG_MGT,
2262                             "fhparams pattern\t0x%02x", elements->fh.pattern);
2263                         RAY_DPRINTF(sc, RAY_DBG_MGT,
2264                             "fhparams index\t0x%02x", elements->fh.index);
2265                         break;
2266
2267                 case IEEE80211_ELEMID_DSPARMS:
2268                         RAY_RECERR(sc, "got direct sequence params!");
2269                         break;
2270
2271                 case IEEE80211_ELEMID_CFPARMS:
2272                         RAY_DPRINTF(sc, RAY_DBG_MGT, "cfparams");
2273                         break;
2274
2275                 case IEEE80211_ELEMID_TIM:
2276                         elements->tim.count = bp[2];
2277                         elements->tim.period = bp[3];
2278                         elements->tim.bitctl = bp[4];
2279                         RAY_DPRINTF(sc, RAY_DBG_MGT,
2280                             "tim count\t0x%02x", elements->tim.count);
2281                         RAY_DPRINTF(sc, RAY_DBG_MGT,
2282                             "tim period\t0x%02x", elements->tim.period);
2283                         RAY_DPRINTF(sc, RAY_DBG_MGT,
2284                             "tim bitctl\t0x%02x", elements->tim.bitctl);
2285 #if RAY_DEBUG & RAY_DBG_MGT
2286                         {
2287                                 int i;
2288                                 for (i = 5; i < len + 1; i++)
2289                                         RAY_DPRINTF(sc, RAY_DBG_MGT,
2290                                             "tim pvt[%03d]\t0x%02x", i-5, bp[i]);
2291                         }
2292 #endif
2293                         break;
2294                         
2295                 case IEEE80211_ELEMID_IBSSPARMS:
2296                         elements->ibss.atim = bp[2] + (bp[3] << 8);
2297                         RAY_DPRINTF(sc, RAY_DBG_MGT,
2298                             "ibssparams atim\t0x%02x", elements->ibss.atim);
2299                         break;
2300
2301                 case IEEE80211_ELEMID_CHALLENGE:
2302                         RAY_DPRINTF(sc, RAY_DBG_MGT, "challenge");
2303                         break;
2304
2305                 default:
2306                         RAY_RECERR(sc, "reserved MGT element id 0x%x", *bp);
2307                         ifp->if_ierrors++;break;
2308                 }
2309                 bp += bp[1] + 2; 
2310         }
2311 }
2312
2313 /*
2314  * Deal with AUTH management packet types
2315  */
2316 static void
2317 ray_rx_mgt_auth(struct ray_softc *sc, struct mbuf *m0)
2318 {
2319         struct ieee80211_frame *header = mtod(m0, struct ieee80211_frame *);
2320         ieee80211_mgt_auth_t auth = (u_int8_t *)(header+1);
2321
2322         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_AUTH, "");
2323
2324         switch (IEEE80211_AUTH_ALGORITHM(auth)) {
2325             
2326         case IEEE80211_AUTH_ALG_OPEN:
2327                 RAY_DPRINTF(sc, RAY_DBG_AUTH,
2328                     "open system authentication sequence number %d",
2329                     IEEE80211_AUTH_TRANSACTION(auth));
2330                 if (IEEE80211_AUTH_TRANSACTION(auth) ==
2331                     IEEE80211_AUTH_OPEN_REQUEST) {
2332
2333 /* XXX_AUTH use ray_init_auth_send */
2334
2335                 } else if (IEEE80211_AUTH_TRANSACTION(auth) == 
2336                     IEEE80211_AUTH_OPEN_RESPONSE)
2337                         ray_init_auth_done(sc, IEEE80211_AUTH_STATUS(auth));
2338                 break;
2339
2340         case IEEE80211_AUTH_ALG_SHARED:
2341                 RAY_RECERR(sc,
2342                     "shared key authentication sequence number %d",
2343                     IEEE80211_AUTH_TRANSACTION(auth));
2344                 break;
2345         
2346         default:
2347                 RAY_RECERR(sc,
2348                     "reserved authentication subtype 0x%04hx",
2349                     IEEE80211_AUTH_ALGORITHM(auth));
2350                 break;
2351         }
2352 }
2353
2354 /*
2355  * Deal with CTL packet types
2356  */
2357 static void
2358 ray_rx_ctl(struct ray_softc *sc, struct mbuf *m0)
2359 {
2360         struct ifnet *ifp = &sc->arpcom.ac_if;
2361         struct ieee80211_frame *header = mtod(m0, struct ieee80211_frame *);
2362
2363         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_CTL, "");
2364
2365         if ((header->i_fc[1] & IEEE80211_FC1_DIR_MASK) !=
2366             IEEE80211_FC1_DIR_NODS) {
2367                 RAY_RECERR(sc, "CTL TODS/FROMDS wrong fc1 0x%x",
2368                     header->i_fc[1] & IEEE80211_FC1_DIR_MASK);
2369                 ifp->if_ierrors++;
2370                 m_freem(m0);
2371                 return;
2372         }
2373
2374         /*
2375          * Check the the ctl packet subtype, some packets should be
2376          * dropped depending on the mode the station is in. The ECF
2377          * should deal with everything but the power save poll to an
2378          * AP. See pg 52(60) of docs.
2379          */
2380         RAY_MBUF_DUMP(sc, RAY_DBG_CTL, m0, "CTL packet");
2381         switch (header->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) {
2382
2383         case IEEE80211_FC0_SUBTYPE_PS_POLL:
2384                 RAY_DPRINTF(sc, RAY_DBG_CTL, "PS_POLL CTL packet");
2385                 if ((sc->sc_d.np_net_type == RAY_MIB_NET_TYPE_INFRA) &&
2386                     (sc->sc_c.np_ap_status == RAY_MIB_AP_STATUS_AP))
2387                         RAY_RECERR(sc, "can't be an AP yet"); /* XXX_ACTING_AP */
2388                 break;
2389
2390         case IEEE80211_FC0_SUBTYPE_RTS:
2391         case IEEE80211_FC0_SUBTYPE_CTS:
2392         case IEEE80211_FC0_SUBTYPE_ACK:
2393         case IEEE80211_FC0_SUBTYPE_CF_END:
2394         case IEEE80211_FC0_SUBTYPE_CF_END_ACK:
2395                 RAY_RECERR(sc, "unexpected CTL packet subtype 0x%0x",
2396                     header->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
2397                 ifp->if_ierrors++;
2398                 break;
2399
2400         default:
2401                 RAY_RECERR(sc, "reserved CTL packet subtype 0x%x",
2402                     header->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
2403                 ifp->if_ierrors++;
2404         }
2405
2406         m_freem(m0);
2407 }
2408
2409 /*
2410  * Update rx level and antenna cache
2411  */
2412 static void
2413 ray_rx_update_cache(struct ray_softc *sc, u_int8_t *src, u_int8_t siglev, u_int8_t antenna)
2414 {
2415         struct timeval mint;
2416         struct ray_siglev *sl;
2417         int i, mini;
2418
2419         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2420
2421         /* Try to find host */
2422         for (i = 0; i < RAY_NSIGLEVRECS; i++) {
2423                 sl = &sc->sc_siglevs[i];
2424                 if (bcmp(sl->rsl_host, src, ETHER_ADDR_LEN) == 0)
2425                         goto found;
2426         }
2427         /* Not found, find oldest slot */
2428         mini = 0;
2429         mint.tv_sec = LONG_MAX;
2430         mint.tv_usec = 0;
2431         for (i = 0; i < RAY_NSIGLEVRECS; i++) {
2432                 sl = &sc->sc_siglevs[i];
2433                 if (timevalcmp(&sl->rsl_time, &mint, <)) {
2434                         mini = i;
2435                         mint = sl->rsl_time;
2436                 }
2437         }
2438         sl = &sc->sc_siglevs[mini];
2439         bzero(sl->rsl_siglevs, RAY_NSIGLEV);
2440         bzero(sl->rsl_antennas, RAY_NANTENNA);
2441         bcopy(src, sl->rsl_host, ETHER_ADDR_LEN);
2442
2443 found:
2444         microtime(&sl->rsl_time);
2445         bcopy(sl->rsl_siglevs, &sl->rsl_siglevs[1], RAY_NSIGLEV-1);
2446         sl->rsl_siglevs[0] = siglev;
2447         if (sc->sc_version != RAY_ECFS_BUILD_4) {
2448                 bcopy(sl->rsl_antennas, &sl->rsl_antennas[1], RAY_NANTENNA-1);
2449                 sl->rsl_antennas[0] = antenna;
2450         }
2451 }
2452
2453 /*
2454  * Interrupt handling
2455  */
2456
2457 /*
2458  * Process an interrupt
2459  */
2460 static void
2461 ray_intr(void *xsc)
2462 {
2463         struct ray_softc *sc = (struct ray_softc *)xsc;
2464         struct ifnet *ifp = &sc->arpcom.ac_if;
2465         size_t ccs;
2466         u_int8_t cmd, status;
2467         int ccsi;
2468
2469         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2470         RAY_MAP_CM(sc);
2471
2472         if ((sc == NULL) || (sc->sc_gone))
2473                 return;
2474
2475         /*
2476          * Check that the interrupt was for us, if so get the rcs/ccs
2477          * and vector on the command contained within it.
2478          */
2479         if (RAY_HCS_INTR(sc)) {
2480                 ccsi = SRAM_READ_1(sc, RAY_SCB_RCSI);
2481                 ccs = RAY_CCS_ADDRESS(ccsi);
2482                 cmd = SRAM_READ_FIELD_1(sc, ccs, ray_cmd, c_cmd);
2483                 status = SRAM_READ_FIELD_1(sc, ccs, ray_cmd, c_status);
2484                 if (ccsi <= RAY_CCS_LAST)
2485                         ray_intr_ccs(sc, cmd, status, ccs);
2486                 else if (ccsi <= RAY_RCS_LAST)
2487                         ray_intr_rcs(sc, cmd, ccs);
2488                 else
2489                     RAY_RECERR(sc, "bad ccs index 0x%x", ccsi);
2490                 RAY_HCS_CLEAR_INTR(sc);
2491         }
2492
2493         /* Send any packets lying around and update error counters */
2494         if (!(ifp->if_flags & IFF_OACTIVE) && (ifp->if_snd.ifq_head != NULL))
2495                 ray_tx(ifp);
2496         if ((++sc->sc_checkcounters % 32) == 0)
2497                 ray_intr_updt_errcntrs(sc);
2498 }
2499
2500 /*
2501  * Read the error counters.
2502  */
2503 static void
2504 ray_intr_updt_errcntrs(struct ray_softc *sc)
2505 {
2506         size_t csc;
2507
2508         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2509         RAY_MAP_CM(sc);
2510
2511         /*
2512          * The card implements the following protocol to keep the
2513          * values from being changed while read: It checks the `own'
2514          * bit and if zero writes the current internal counter value,
2515          * it then sets the `own' bit to 1. If the `own' bit was 1 it
2516          * incremenets its internal counter. The user thus reads the
2517          * counter if the `own' bit is one and then sets the own bit
2518          * to 0.
2519          */
2520         csc = RAY_STATUS_BASE;
2521         if (SRAM_READ_FIELD_1(sc, csc, ray_csc, csc_mrxo_own)) {
2522                 sc->sc_rxoverflow +=
2523                     SRAM_READ_FIELD_2(sc, csc, ray_csc, csc_mrx_overflow);
2524                 SRAM_WRITE_FIELD_1(sc, csc, ray_csc, csc_mrxo_own, 0);
2525         }
2526         if (SRAM_READ_FIELD_1(sc, csc, ray_csc, csc_mrxc_own)) {
2527                 sc->sc_rxcksum +=
2528                     SRAM_READ_FIELD_2(sc, csc, ray_csc, csc_mrx_overflow);
2529                 SRAM_WRITE_FIELD_1(sc, csc, ray_csc, csc_mrxc_own, 0);
2530         }
2531         if (SRAM_READ_FIELD_1(sc, csc, ray_csc, csc_rxhc_own)) {
2532                 sc->sc_rxhcksum +=
2533                     SRAM_READ_FIELD_2(sc, csc, ray_csc, csc_rx_hcksum);
2534                 SRAM_WRITE_FIELD_1(sc, csc, ray_csc, csc_rxhc_own, 0);
2535         }
2536         sc->sc_rxnoise = SRAM_READ_FIELD_1(sc, csc, ray_csc, csc_rx_noise);
2537 }
2538
2539 /*
2540  * Process CCS command completion
2541  */
2542 static void
2543 ray_intr_ccs(struct ray_softc *sc, u_int8_t cmd, u_int8_t status, size_t ccs)
2544 {
2545         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2546
2547         switch (cmd) {
2548
2549         case RAY_CMD_DOWNLOAD_PARAMS:
2550                 RAY_DPRINTF(sc, RAY_DBG_COM, "START_PARAMS");
2551                 ray_init_download_done(sc, status, ccs);
2552                 break;
2553
2554         case RAY_CMD_UPDATE_PARAMS:
2555                 RAY_DPRINTF(sc, RAY_DBG_COM, "UPDATE_PARAMS");
2556                 ray_upparams_done(sc, status, ccs);
2557                 break;
2558
2559         case RAY_CMD_REPORT_PARAMS:
2560                 RAY_DPRINTF(sc, RAY_DBG_COM, "REPORT_PARAMS");
2561                 ray_repparams_done(sc, status, ccs);
2562                 break;
2563
2564         case RAY_CMD_UPDATE_MCAST:
2565                 RAY_DPRINTF(sc, RAY_DBG_COM, "UPDATE_MCAST");
2566                 ray_mcast_done(sc, status, ccs);
2567                 break;
2568
2569         case RAY_CMD_START_NET:
2570         case RAY_CMD_JOIN_NET:
2571                 RAY_DPRINTF(sc, RAY_DBG_COM, "START|JOIN_NET");
2572                 ray_init_sj_done(sc, status, ccs);
2573                 break;
2574
2575         case RAY_CMD_TX_REQ:
2576                 RAY_DPRINTF(sc, RAY_DBG_COM, "TX_REQ");
2577                 ray_tx_done(sc, status, ccs);
2578                 break;
2579
2580         case RAY_CMD_START_ASSOC:
2581                 RAY_DPRINTF(sc, RAY_DBG_COM, "START_ASSOC");
2582                 ray_init_assoc_done(sc, status, ccs);
2583                 break;
2584
2585         case RAY_CMD_UPDATE_APM:
2586                 RAY_RECERR(sc, "unexpected UPDATE_APM");
2587                 break;
2588
2589         case RAY_CMD_TEST_MEM:
2590                 RAY_RECERR(sc, "unexpected TEST_MEM");
2591                 break;
2592
2593         case RAY_CMD_SHUTDOWN:
2594                 RAY_RECERR(sc, "unexpected SHUTDOWN");
2595                 break;
2596
2597         case RAY_CMD_DUMP_MEM:
2598                 RAY_RECERR(sc, "unexpected DUMP_MEM");
2599                 break;
2600
2601         case RAY_CMD_START_TIMER:
2602                 RAY_RECERR(sc, "unexpected START_TIMER");
2603                 break;
2604
2605         default:
2606                 RAY_RECERR(sc, "unknown command 0x%x", cmd);
2607                 break;
2608         }
2609 }
2610
2611 /*
2612  * Process ECF command request
2613  */
2614 static void
2615 ray_intr_rcs(struct ray_softc *sc, u_int8_t cmd, size_t rcs)
2616 {
2617         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2618
2619         switch (cmd) {
2620
2621         case RAY_ECMD_RX_DONE:
2622                 RAY_DPRINTF(sc, RAY_DBG_RX, "RX_DONE");
2623                 ray_rx(sc, rcs);
2624                 break;
2625
2626         case RAY_ECMD_REJOIN_DONE:
2627                 RAY_DPRINTF(sc, RAY_DBG_RX, "REJOIN_DONE");
2628                 sc->sc_c.np_havenet = 1; /* XXX Should not be here but in function */
2629                 break;
2630
2631         case RAY_ECMD_ROAM_START:
2632                 RAY_DPRINTF(sc, RAY_DBG_RX, "ROAM_START");
2633                 sc->sc_c.np_havenet = 0; /* XXX Should not be here but in function */
2634                 break;
2635
2636         case RAY_ECMD_JAPAN_CALL_SIGNAL:
2637                 RAY_RECERR(sc, "unexpected JAPAN_CALL_SIGNAL");
2638                 break;
2639
2640         default:
2641                 RAY_RECERR(sc, "unknown command 0x%x", cmd);
2642                 break;
2643         }
2644
2645         RAY_CCS_FREE(sc, rcs);
2646 }
2647
2648 /*
2649  * User land entry to multicast list changes
2650  */
2651 static int
2652 ray_mcast_user(struct ray_softc *sc)
2653 {
2654         struct ray_comq_entry *com[2];
2655         int error, ncom;
2656
2657         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2658
2659         /*
2660          * Do all checking in the runq to preserve ordering.
2661          *
2662          * We run promisc to pick up changes to the ALL_MULTI
2663          * interface flag.
2664          */
2665         ncom = 0;
2666         com[ncom++] = RAY_COM_MALLOC(ray_mcast, 0);
2667         com[ncom++] = RAY_COM_MALLOC(ray_promisc, 0);
2668
2669         RAY_COM_RUNQ(sc, com, ncom, "raymcast", error);
2670
2671         /* XXX no real error processing from anything yet! */
2672
2673         RAY_COM_FREE(com, ncom);
2674
2675         return (error);
2676 }
2677
2678 /*
2679  * Runq entry to setting the multicast filter list
2680  *
2681  * MUST always be followed by a call to ray_promisc to pick up changes
2682  * to promisc flag
2683  */
2684 static void
2685 ray_mcast(struct ray_softc *sc, struct ray_comq_entry *com)
2686 {
2687         struct ifnet *ifp = &sc->arpcom.ac_if;
2688         struct ifmultiaddr *ifma;
2689         size_t bufp;
2690         int count = 0;
2691
2692         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2693         RAY_MAP_CM(sc);
2694
2695         /*
2696          * If card is not running we don't need to update this.
2697          */
2698         if (!(ifp->if_flags & IFF_RUNNING)) {
2699                 RAY_DPRINTF(sc, RAY_DBG_IOCTL, "not running");
2700                 ray_com_runq_done(sc);
2701                 return;
2702         }
2703
2704         /*
2705          * The multicast list is only 16 items long so use promiscuous
2706          * mode and don't bother updating the multicast list.
2707          */
2708         for (ifma = ifp->if_multiaddrs.lh_first; ifma != NULL;
2709             ifma = ifma->ifma_link.le_next)
2710                 count++;
2711         if (count == 0) {
2712                 ray_com_runq_done(sc);
2713                 return;
2714         } else if (count > 16) {
2715                 ifp->if_flags |= IFF_ALLMULTI;
2716                 ray_com_runq_done(sc);
2717                 return;
2718         } else if (ifp->if_flags & IFF_ALLMULTI)
2719                 ifp->if_flags &= ~IFF_ALLMULTI;
2720
2721         /*
2722          * Kick the card
2723          */
2724         ray_ccs_fill(sc, com->c_ccs, RAY_CMD_UPDATE_MCAST);
2725         SRAM_WRITE_FIELD_1(sc, com->c_ccs,
2726             ray_cmd_update_mcast, c_nmcast, count);
2727         bufp = RAY_HOST_TO_ECF_BASE;
2728         for (ifma = ifp->if_multiaddrs.lh_first; ifma != NULL;
2729             ifma = ifma->ifma_link.le_next) {
2730                 SRAM_WRITE_REGION(
2731                     sc,
2732                     bufp,
2733                     LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
2734                     ETHER_ADDR_LEN
2735                 );
2736                 bufp += ETHER_ADDR_LEN;
2737         }
2738
2739         ray_com_ecf(sc, com);
2740 }
2741
2742 /*
2743  * Complete the multicast filter list update
2744  */
2745 static void
2746 ray_mcast_done(struct ray_softc *sc, u_int8_t status, size_t ccs)
2747 {
2748         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_STARTJOIN, "");
2749         RAY_COM_CHECK(sc, ccs);
2750
2751         RAY_CCSERR(sc, status, if_oerrors); /* XXX error counter */
2752
2753         ray_com_ecf_done(sc);
2754 }
2755
2756 /*
2757  * Runq entry to set/reset promiscuous mode
2758  */
2759 static void
2760 ray_promisc(struct ray_softc *sc, struct ray_comq_entry *com)
2761 {
2762         struct ifnet *ifp = &sc->arpcom.ac_if;
2763
2764         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2765         RAY_MAP_CM(sc);
2766
2767         /*
2768          * If card not running or we already have the right flags
2769          * we don't need to update this
2770          */
2771         sc->sc_d.np_promisc = !!(ifp->if_flags & (IFF_PROMISC | IFF_ALLMULTI));
2772         if (!(ifp->if_flags & IFF_RUNNING) ||
2773             (sc->sc_c.np_promisc == sc->sc_d.np_promisc)) {
2774                 ray_com_runq_done(sc);
2775                 return;
2776         }
2777
2778         /*
2779          * Kick the card
2780          */
2781         ray_ccs_fill(sc, com->c_ccs, RAY_CMD_UPDATE_PARAMS);
2782         SRAM_WRITE_FIELD_1(sc, com->c_ccs,
2783             ray_cmd_update, c_paramid, RAY_MIB_PROMISC);
2784         SRAM_WRITE_FIELD_1(sc, com->c_ccs, ray_cmd_update, c_nparam, 1);
2785         SRAM_WRITE_1(sc, RAY_HOST_TO_ECF_BASE, sc->sc_d.np_promisc);
2786
2787         ray_com_ecf(sc, com);
2788 }
2789
2790 /*
2791  * User land entry to parameter reporting
2792  *
2793  * As we by pass the runq to report current parameters this function
2794  * only provides a snap shot of the driver's state.
2795  */
2796 static int
2797 ray_repparams_user(struct ray_softc *sc, struct ray_param_req *pr)
2798 {
2799         struct ray_comq_entry *com[1];
2800         int error, ncom;
2801
2802         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2803
2804         /*
2805          * Test for illegal values or immediate responses
2806          */
2807         if (pr->r_paramid > RAY_MIB_MAX)
2808                 return (EINVAL);
2809         if ((sc->sc_version == RAY_ECFS_BUILD_4) &&
2810             !(mib_info[pr->r_paramid][0] & RAY_V4))
2811                 return (EINVAL);
2812         if ((sc->sc_version == RAY_ECFS_BUILD_5) &&
2813             !(mib_info[pr->r_paramid][0] & RAY_V5))
2814                 return (EINVAL);
2815         if (pr->r_paramid > RAY_MIB_LASTUSER) {
2816                 switch (pr->r_paramid) {
2817
2818                 case  RAY_MIB_VERSION:
2819                         if (sc->sc_version == RAY_ECFS_BUILD_4)
2820                             *pr->r_data = RAY_V4;
2821                         else
2822                             *pr->r_data = RAY_V5;
2823                         break;
2824                 case  RAY_MIB_CUR_BSSID:
2825                         bcopy(sc->sc_c.np_bss_id, pr->r_data, ETHER_ADDR_LEN);
2826                         break;
2827                 case  RAY_MIB_CUR_INITED:
2828                         *pr->r_data = sc->sc_c.np_inited;
2829                         break;
2830                 case  RAY_MIB_CUR_DEF_TXRATE:
2831                         *pr->r_data = sc->sc_c.np_def_txrate;
2832                         break;
2833                 case  RAY_MIB_CUR_ENCRYPT:
2834                         *pr->r_data = sc->sc_c.np_encrypt;
2835                         break;
2836                 case  RAY_MIB_CUR_NET_TYPE:
2837                         *pr->r_data = sc->sc_c.np_net_type;
2838                         break;
2839                 case  RAY_MIB_CUR_SSID:
2840                         bcopy(sc->sc_c.np_ssid, pr->r_data, IEEE80211_NWID_LEN);
2841                         break;
2842                 case  RAY_MIB_CUR_PRIV_START:
2843                         *pr->r_data = sc->sc_c.np_priv_start;
2844                         break;
2845                 case  RAY_MIB_CUR_PRIV_JOIN:
2846                         *pr->r_data = sc->sc_c.np_priv_join;
2847                         break;
2848                 case  RAY_MIB_DES_BSSID:
2849                         bcopy(sc->sc_d.np_bss_id, pr->r_data, ETHER_ADDR_LEN);
2850                         break;
2851                 case  RAY_MIB_DES_INITED:
2852                         *pr->r_data = sc->sc_d.np_inited;
2853                         break;
2854                 case  RAY_MIB_DES_DEF_TXRATE:
2855                         *pr->r_data = sc->sc_d.np_def_txrate;
2856                         break;
2857                 case  RAY_MIB_DES_ENCRYPT:
2858                         *pr->r_data = sc->sc_d.np_encrypt;
2859                         break;
2860                 case  RAY_MIB_DES_NET_TYPE:
2861                         *pr->r_data = sc->sc_d.np_net_type;
2862                         break;
2863                 case  RAY_MIB_DES_SSID:
2864                         bcopy(sc->sc_d.np_ssid, pr->r_data, IEEE80211_NWID_LEN);
2865                         break;
2866                 case  RAY_MIB_DES_PRIV_START:
2867                         *pr->r_data = sc->sc_d.np_priv_start;
2868                         break;
2869                 case  RAY_MIB_DES_PRIV_JOIN:
2870                         *pr->r_data = sc->sc_d.np_priv_join;
2871                         break;
2872                 case  RAY_MIB_CUR_AP_STATUS:
2873                         *pr->r_data = sc->sc_c.np_ap_status;
2874                         break;
2875                 case  RAY_MIB_CUR_PROMISC:
2876                         *pr->r_data = sc->sc_c.np_promisc;
2877                         break;
2878                 case  RAY_MIB_DES_AP_STATUS:
2879                         *pr->r_data = sc->sc_d.np_ap_status;
2880                         break;
2881                 case  RAY_MIB_DES_PROMISC:
2882                         *pr->r_data = sc->sc_d.np_promisc;
2883                         break;
2884                 case RAY_MIB_CUR_FRAMING:
2885                         *pr->r_data = sc->sc_c.np_framing;
2886                         break;
2887                 case RAY_MIB_DES_FRAMING:
2888                         *pr->r_data = sc->sc_d.np_framing;
2889                         break;
2890
2891                 default:
2892                         return (EINVAL);
2893                         break;
2894                 }
2895                 pr->r_failcause = 0;
2896                 if (sc->sc_version == RAY_ECFS_BUILD_4)
2897                     pr->r_len = mib_info[pr->r_paramid][RAY_MIB_INFO_SIZ4];
2898                 else if (sc->sc_version == RAY_ECFS_BUILD_5)
2899                     pr->r_len = mib_info[pr->r_paramid][RAY_MIB_INFO_SIZ5];
2900                 return (0);
2901         }
2902
2903         pr->r_failcause = 0;
2904         ncom = 0;
2905         com[ncom++] = RAY_COM_MALLOC(ray_repparams, RAY_COM_FWOK);
2906         com[ncom-1]->c_pr = pr;
2907
2908         RAY_COM_RUNQ(sc, com, ncom, "rayrparm", error);
2909
2910         /* XXX no real error processing from anything yet! */
2911         if (!com[0]->c_retval && pr->r_failcause)
2912                 error = EINVAL;
2913
2914         RAY_COM_FREE(com, ncom);
2915
2916         return (error);
2917 }
2918
2919 /*
2920  * Runq entry to read the required parameter
2921  *
2922  * The card and driver are happy for parameters to be read
2923  * whenever the card is plugged in
2924  */
2925 static void
2926 ray_repparams(struct ray_softc *sc, struct ray_comq_entry *com)
2927 {
2928         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2929         RAY_MAP_CM(sc);
2930
2931         /*
2932          * Kick the card
2933          */
2934         ray_ccs_fill(sc, com->c_ccs, RAY_CMD_REPORT_PARAMS);
2935         SRAM_WRITE_FIELD_1(sc, com->c_ccs,
2936             ray_cmd_report, c_paramid, com->c_pr->r_paramid);
2937         SRAM_WRITE_FIELD_1(sc, com->c_ccs, ray_cmd_report, c_nparam, 1);
2938
2939         ray_com_ecf(sc, com);
2940 }
2941
2942 /*
2943  * Complete the parameter reporting
2944  */
2945 static void
2946 ray_repparams_done(struct ray_softc *sc, u_int8_t status, size_t ccs)
2947 {
2948         struct ray_comq_entry *com;
2949
2950         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2951         RAY_MAP_CM(sc);
2952         RAY_COM_CHECK(sc, ccs);
2953
2954         RAY_CCSERR(sc, status, if_oerrors); /* XXX error counter */
2955
2956         com = TAILQ_FIRST(&sc->sc_comq);
2957         com->c_pr->r_failcause =
2958             SRAM_READ_FIELD_1(sc, ccs, ray_cmd_report, c_failcause);
2959         com->c_pr->r_len =
2960             SRAM_READ_FIELD_1(sc, ccs, ray_cmd_report, c_len);
2961         SRAM_READ_REGION(sc, RAY_ECF_TO_HOST_BASE,
2962             com->c_pr->r_data, com->c_pr->r_len);
2963
2964         ray_com_ecf_done(sc);
2965 }
2966
2967 /*
2968  * User land entry (and exit) to the error counters
2969  */
2970 static int
2971 ray_repstats_user(struct ray_softc *sc, struct ray_stats_req *sr)
2972 {
2973         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2974
2975         sr->rxoverflow = sc->sc_rxoverflow;
2976         sr->rxcksum = sc->sc_rxcksum;
2977         sr->rxhcksum = sc->sc_rxhcksum;
2978         sr->rxnoise = sc->sc_rxnoise;
2979
2980         return (0);
2981 }
2982
2983 /*
2984  * User land entry to parameter update changes
2985  *
2986  * As a parameter change can cause the network parameters to be
2987  * invalid we have to re-start/join.
2988  */
2989 static int
2990 ray_upparams_user(struct ray_softc *sc, struct ray_param_req *pr)
2991 {
2992         struct ray_comq_entry *com[4];
2993         int error, ncom, todo;
2994 #define RAY_UPP_SJ      0x1
2995 #define RAY_UPP_PARAMS  0x2
2996
2997         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
2998
2999         /*
3000          * Check that the parameter is available based on firmware version
3001          */
3002         pr->r_failcause = 0;
3003         if (pr->r_paramid > RAY_MIB_LASTUSER)
3004                 return (EINVAL);
3005         if ((sc->sc_version == RAY_ECFS_BUILD_4) &&
3006             !(mib_info[pr->r_paramid][0] & RAY_V4))
3007                 return (EINVAL);
3008         if ((sc->sc_version == RAY_ECFS_BUILD_5) &&
3009             !(mib_info[pr->r_paramid][0] & RAY_V5))
3010                 return (EINVAL);
3011
3012         /*
3013          * Handle certain parameters specially
3014          */
3015         todo = 0;
3016         switch (pr->r_paramid) {
3017         case RAY_MIB_NET_TYPE:          /* Updated via START_NET JOIN_NET  */
3018                 sc->sc_d.np_net_type = *pr->r_data;
3019                 todo |= RAY_UPP_SJ;
3020                 break;
3021
3022         case RAY_MIB_SSID:              /* Updated via START_NET JOIN_NET  */
3023                 bcopy(pr->r_data, sc->sc_d.np_ssid, IEEE80211_NWID_LEN);
3024                 todo |= RAY_UPP_SJ;
3025                 break;
3026
3027         case RAY_MIB_PRIVACY_MUST_START:/* Updated via START_NET */
3028                 if (sc->sc_c.np_net_type != RAY_MIB_NET_TYPE_ADHOC)
3029                         return (EINVAL);
3030                 sc->sc_d.np_priv_start = *pr->r_data;
3031                 todo |= RAY_UPP_SJ;
3032                 break;
3033
3034         case RAY_MIB_PRIVACY_CAN_JOIN:  /* Updated via START_NET JOIN_NET  */
3035                 sc->sc_d.np_priv_join = *pr->r_data;
3036                 todo |= RAY_UPP_SJ;
3037                 break;
3038
3039         case RAY_MIB_BASIC_RATE_SET:
3040                 sc->sc_d.np_def_txrate = *pr->r_data;
3041                 todo |= RAY_UPP_PARAMS;
3042                 break;
3043
3044         case RAY_MIB_AP_STATUS: /* Unsupported */
3045         case RAY_MIB_MAC_ADDR:  /* XXX Need interface up but could be done */
3046         case RAY_MIB_PROMISC:   /* BPF */
3047                 return (EINVAL);
3048                 break;
3049
3050         default:
3051                 todo |= RAY_UPP_PARAMS;
3052                 todo |= RAY_UPP_SJ;
3053                 break;
3054         }
3055
3056         /*
3057          * Generate the runq entries as needed
3058          */
3059         ncom = 0;
3060         if (todo & RAY_UPP_PARAMS) {
3061                 com[ncom++] = RAY_COM_MALLOC(ray_upparams, 0);
3062                 com[ncom-1]->c_pr = pr;
3063         }
3064         if (todo & RAY_UPP_SJ) {
3065                 com[ncom++] = RAY_COM_MALLOC(ray_init_sj, 0);
3066                 com[ncom++] = RAY_COM_MALLOC(ray_init_auth, 0);
3067                 com[ncom++] = RAY_COM_MALLOC(ray_init_assoc, 0);
3068         }
3069
3070         RAY_COM_RUNQ(sc, com, ncom, "rayuparam", error);
3071
3072         /* XXX no real error processing from anything yet! */
3073         if (!com[0]->c_retval && pr->r_failcause)
3074                 error = EINVAL;
3075
3076         RAY_COM_FREE(com, ncom);
3077
3078         return (error);
3079 }
3080
3081 /*
3082  * Runq entry to update a parameter
3083  *
3084  * The card and driver are happy for parameters to be updated
3085  * whenever the card is plugged in
3086  *
3087  * XXX the above is a little bit of a lie until _download is sorted out and we
3088  * XXX keep local copies of things
3089  */
3090 static void
3091 ray_upparams(struct ray_softc *sc, struct ray_comq_entry *com)
3092 {
3093         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
3094         RAY_MAP_CM(sc);
3095
3096         ray_ccs_fill(sc, com->c_ccs, RAY_CMD_UPDATE_PARAMS);
3097
3098         SRAM_WRITE_FIELD_1(sc, com->c_ccs,
3099             ray_cmd_update, c_paramid, com->c_pr->r_paramid);
3100         SRAM_WRITE_FIELD_1(sc, com->c_ccs, ray_cmd_update, c_nparam, 1);
3101         SRAM_WRITE_REGION(sc, RAY_HOST_TO_ECF_BASE,
3102             com->c_pr->r_data, com->c_pr->r_len);
3103
3104         ray_com_ecf(sc, com);
3105 }
3106
3107 /*
3108  * Complete the parameter update, note that promisc finishes up here too
3109  */
3110 static void
3111 ray_upparams_done(struct ray_softc *sc, u_int8_t status, size_t ccs)
3112 {
3113         struct ray_comq_entry *com;
3114
3115         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
3116         RAY_MAP_CM(sc);
3117         RAY_COM_CHECK(sc, ccs);
3118
3119         RAY_CCSERR(sc, status, if_oerrors); /* XXX error counter */
3120
3121         com = TAILQ_FIRST(&sc->sc_comq);
3122
3123         switch (SRAM_READ_FIELD_1(sc, ccs, ray_cmd_update, c_paramid)) {
3124
3125         case RAY_MIB_PROMISC:
3126                 sc->sc_c.np_promisc = SRAM_READ_1(sc, RAY_HOST_TO_ECF_BASE);
3127                 RAY_DPRINTF(sc, RAY_DBG_IOCTL,
3128                     "promisc value %d", sc->sc_c.np_promisc);
3129                 break;
3130
3131         default:
3132                 com->c_pr->r_failcause =
3133                     SRAM_READ_FIELD_1(sc, ccs, ray_cmd_update, c_failcause);
3134                 break;
3135
3136         }
3137
3138         ray_com_ecf_done(sc);
3139 }
3140
3141 /*
3142  * Command queuing and execution
3143  */
3144
3145 /*
3146  * Set up a comq entry struct
3147  */
3148 static struct ray_comq_entry *
3149 ray_com_init(struct ray_comq_entry *com, ray_comqfn_t function, int flags, char *mesg)
3150 {
3151         com->c_function = function;
3152         com->c_flags = flags;
3153         com->c_retval = 0;
3154         com->c_ccs = NULL;
3155         com->c_wakeup = NULL;
3156         com->c_pr = NULL;
3157         com->c_mesg = mesg;
3158
3159         return (com);
3160 }
3161
3162 /*
3163  * Malloc and set up a comq entry struct
3164  */
3165 static struct ray_comq_entry *
3166 ray_com_malloc(ray_comqfn_t function, int flags, char *mesg)
3167 {
3168         struct ray_comq_entry *com;
3169
3170         MALLOC(com, struct ray_comq_entry *,
3171             sizeof(struct ray_comq_entry), M_RAYCOM, M_WAITOK);
3172     
3173         return (ray_com_init(com, function, flags, mesg));
3174 }
3175
3176 /*
3177  * Add an array of commands to the runq, get some ccs's for them and
3178  * then run, waiting on the last command.
3179  *
3180  * We add the commands to the queue first to preserve ioctl ordering.
3181  *
3182  * On recoverable errors, this routine removes the entries from the
3183  * runq. A caller can requeue the commands (and still preserve its own
3184  * processes ioctl ordering) but doesn't have to. When the card is
3185  * detached we get out quickly to prevent panics and don't bother
3186  * about the runq.
3187  */
3188 static int
3189 ray_com_runq_add(struct ray_softc *sc, struct ray_comq_entry *com[], int ncom, char *wmesg)
3190 {
3191         int i, error;
3192
3193         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_COM, "");
3194
3195         error = 0;
3196         /*
3197          * Add the commands to the runq but don't let it run until
3198          * the ccs's are allocated successfully
3199          */
3200         com[0]->c_flags |= RAY_COM_FWAIT;
3201         for (i = 0; i < ncom; i++) {
3202                 com[i]->c_wakeup = com[ncom-1];
3203                 RAY_DPRINTF(sc, RAY_DBG_COM, "adding %p", com[i]);
3204                 RAY_DCOM(sc, RAY_DBG_DCOM, com[i], "adding");
3205                 TAILQ_INSERT_TAIL(&sc->sc_comq, com[i], c_chain);
3206         }
3207         com[ncom-1]->c_flags |= RAY_COM_FWOK;
3208
3209         /*
3210          * Allocate ccs's for each command.
3211          */
3212         for (i = 0; i < ncom; i++) {
3213                 error = ray_ccs_alloc(sc, &com[i]->c_ccs, wmesg);
3214                 if (error == ENXIO)
3215                         return (ENXIO);
3216                 else if (error)
3217                         goto cleanup;
3218         }
3219
3220         /*
3221          * Allow the queue to run and sleep if needed.
3222          *
3223          * Iff the FDETACHED flag is set in the com entry we waited on
3224          * the driver is in a zombie state! The softc structure has been
3225          * freed by the generic bus detach methods - eek. We tread very
3226          * carefully!
3227          */
3228         com[0]->c_flags &= ~RAY_COM_FWAIT;
3229         ray_com_runq(sc);
3230         if (TAILQ_FIRST(&sc->sc_comq) != NULL) {
3231                 RAY_DPRINTF(sc, RAY_DBG_COM, "sleeping");
3232                 error = tsleep(com[ncom-1], PCATCH, wmesg, 0);
3233                 if (com[ncom-1]->c_flags & RAY_COM_FDETACHED)
3234                         return (ENXIO);
3235                 RAY_DPRINTF(sc, RAY_DBG_COM,
3236                     "awakened, tsleep returned 0x%x", error);
3237         } else
3238                 error = 0;
3239
3240 cleanup:
3241         /*
3242          * Only clean the queue on real errors - we don't care about it
3243          * when we detach as the queue entries are freed by the callers.
3244          */
3245         if (error && (error != ENXIO))
3246                 for (i = 0; i < ncom; i++)
3247                         if (!(com[i]->c_flags & RAY_COM_FCOMPLETED)) {
3248                                 RAY_DPRINTF(sc, RAY_DBG_COM, "removing %p",
3249                                     com[i]);
3250                                 RAY_DCOM(sc, RAY_DBG_DCOM, com[i], "removing");
3251                                 TAILQ_REMOVE(&sc->sc_comq, com[i], c_chain);
3252                                 ray_ccs_free(sc, com[i]->c_ccs);
3253                                 com[i]->c_ccs = NULL;
3254                         }
3255
3256         return (error);
3257 }
3258
3259 /*
3260  * Run the command at the head of the queue (if not already running)
3261  */
3262 static void
3263 ray_com_runq(struct ray_softc *sc)
3264 {
3265         struct ray_comq_entry *com;
3266
3267         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_COM, "");
3268
3269         com = TAILQ_FIRST(&sc->sc_comq);
3270         if ((com == NULL) ||
3271             (com->c_flags & RAY_COM_FRUNNING) ||
3272             (com->c_flags & RAY_COM_FWAIT) ||
3273             (com->c_flags & RAY_COM_FDETACHED))
3274                 return;
3275
3276         com->c_flags |= RAY_COM_FRUNNING;
3277         RAY_DPRINTF(sc, RAY_DBG_COM, "running %p", com);
3278         RAY_DCOM(sc, RAY_DBG_DCOM, com, "running");
3279         com->c_function(sc, com);
3280 }
3281
3282 /*
3283  * Remove run command, free ccs and wakeup caller.
3284  *
3285  * Minimal checks are done here as we ensure that the com and command
3286  * handler were matched up earlier. Must be called at splnet or higher
3287  * so that entries on the command queue are correctly removed.
3288  *
3289  * Remove the com from the comq, and wakeup the caller if it requested
3290  * to be woken. This is used for ensuring a sequence of commands
3291  * completes. Finally, re-run the queue.
3292  */
3293 static void
3294 ray_com_runq_done(struct ray_softc *sc)
3295 {
3296         struct ray_comq_entry *com;
3297
3298         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_COM, "");
3299
3300         com = TAILQ_FIRST(&sc->sc_comq); /* XXX shall we check this as below */
3301         RAY_DPRINTF(sc, RAY_DBG_COM, "removing %p", com);
3302         RAY_DCOM(sc, RAY_DBG_DCOM, com, "removing");
3303         TAILQ_REMOVE(&sc->sc_comq, com, c_chain);
3304
3305         com->c_flags &= ~RAY_COM_FRUNNING;
3306         com->c_flags |= RAY_COM_FCOMPLETED;
3307         com->c_retval = 0;
3308         ray_ccs_free(sc, com->c_ccs);
3309         com->c_ccs = NULL;
3310
3311         if (com->c_flags & RAY_COM_FWOK)
3312                 wakeup(com->c_wakeup);
3313
3314         ray_com_runq(sc);
3315
3316         /* XXX what about error on completion then? deal with when i fix
3317          * XXX the status checking
3318          *
3319          * XXX all the runq_done calls from IFF_RUNNING checks in runq
3320          * XXX routines should return EIO but shouldn't abort the runq
3321          */
3322 }
3323
3324 /*
3325  * Send a command to the ECF.
3326  */
3327 static void
3328 ray_com_ecf(struct ray_softc *sc, struct ray_comq_entry *com)
3329 {
3330         int i = 0;
3331
3332         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_COM, "");
3333         RAY_MAP_CM(sc);
3334
3335         while (!RAY_ECF_READY(sc)) {
3336                 DELAY(RAY_ECF_SPIN_DELAY);
3337                 if (++i > RAY_ECF_SPIN_TRIES)
3338                         RAY_PANIC(sc, "spun too long");
3339         }
3340         if (i != 0)
3341                 RAY_RECERR(sc, "spun %d times", i);
3342
3343         RAY_DPRINTF(sc, RAY_DBG_COM, "sending %p", com);
3344         RAY_DCOM(sc, RAY_DBG_DCOM, com, "sending");
3345         SRAM_WRITE_1(sc, RAY_SCB_CCSI, RAY_CCS_INDEX(com->c_ccs));
3346         RAY_ECF_START_CMD(sc);
3347
3348         if (RAY_COM_NEEDS_TIMO(
3349             SRAM_READ_FIELD_1(sc, com->c_ccs, ray_cmd, c_cmd))) {
3350                 RAY_DPRINTF(sc, RAY_DBG_COM, "adding timeout");
3351                 sc->com_timerh = timeout(ray_com_ecf_timo, sc, RAY_COM_TIMEOUT);
3352         }
3353 }
3354
3355 /*
3356  * Deal with commands that require a timeout to test completion.
3357  *
3358  * This routine is coded to only expect one outstanding request for the
3359  * timed out requests at a time, but thats all that can be outstanding
3360  * per hardware limitations and all that we issue anyway.
3361  *
3362  * We don't do any fancy testing of the command currently issued as we
3363  * know it must be a timeout based one...unless I've got this wrong!
3364  */
3365 static void
3366 ray_com_ecf_timo(void *xsc)
3367 {
3368         struct ray_softc *sc = (struct ray_softc *)xsc;
3369         struct ray_comq_entry *com;
3370         u_int8_t cmd, status;
3371         int s;
3372
3373         s = splnet();
3374
3375         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_COM, "");
3376         RAY_MAP_CM(sc);
3377
3378         com = TAILQ_FIRST(&sc->sc_comq);
3379
3380         cmd = SRAM_READ_FIELD_1(sc, com->c_ccs, ray_cmd, c_cmd);
3381         status = SRAM_READ_FIELD_1(sc, com->c_ccs, ray_cmd, c_status);
3382         switch (status) {
3383
3384         case RAY_CCS_STATUS_COMPLETE:
3385         case RAY_CCS_STATUS_FREE:                       /* Buggy firmware */
3386                 ray_intr_ccs(sc, cmd, status, com->c_ccs);
3387                 break;
3388
3389         case RAY_CCS_STATUS_BUSY:
3390                 sc->com_timerh = timeout(ray_com_ecf_timo, sc, RAY_COM_TIMEOUT);
3391                 break;
3392
3393         default:                                        /* Replicates NetBSD */
3394                 if (sc->sc_ccsinuse[RAY_CCS_INDEX(com->c_ccs)] == 1) {
3395                         /* give a chance for the interrupt to occur */
3396                         sc->sc_ccsinuse[RAY_CCS_INDEX(com->c_ccs)] = 2;
3397                         sc->com_timerh = timeout(ray_com_ecf_timo, sc,
3398                             RAY_COM_TIMEOUT);
3399                 } else
3400                         ray_intr_ccs(sc, cmd, status, com->c_ccs);
3401                 break;
3402
3403         }
3404
3405         splx(s);
3406 }
3407
3408 /*
3409  * Called when interrupt handler for the command has done all it
3410  * needs to. Will be called at splnet.
3411  */
3412 static void
3413 ray_com_ecf_done(struct ray_softc *sc)
3414 {
3415         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_COM, "");
3416
3417         untimeout(ray_com_ecf_timo, sc, sc->com_timerh);
3418
3419         ray_com_runq_done(sc);
3420 }
3421
3422 #if RAY_DEBUG & RAY_DBG_COM
3423 /*
3424  * Process completed ECF commands that probably came from the command queue
3425  *
3426  * This routine is called after vectoring the completed ECF command
3427  * to the appropriate _done routine. It helps check everything is okay.
3428  */
3429 static void
3430 ray_com_ecf_check(struct ray_softc *sc, size_t ccs, char *mesg)
3431 {
3432         struct ray_comq_entry *com;
3433
3434         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_COM, "%s", mesg);
3435
3436         com = TAILQ_FIRST(&sc->sc_comq);
3437
3438         if (com == NULL)
3439                 RAY_PANIC(sc, "no command queue");
3440         if (com->c_ccs != ccs)
3441                 RAY_PANIC(sc, "ccs's don't match");
3442 }
3443 #endif /* RAY_DEBUG & RAY_DBG_COM */
3444
3445 /*
3446  * CCS allocators
3447  */
3448
3449 /*
3450  * Obtain a ccs for a commmand
3451  *
3452  * Returns 0 and in `ccsp' the bus offset of the free ccs. Will block
3453  * awaiting free ccs if needed - if the sleep is interrupted
3454  * EINTR/ERESTART is returned, if the card is ejected we return ENXIO.
3455  */
3456 static int
3457 ray_ccs_alloc(struct ray_softc *sc, size_t *ccsp, char *wmesg)
3458 {
3459         size_t ccs;
3460         u_int i;
3461         int error;
3462
3463         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_CCS, "");
3464         RAY_MAP_CM(sc);
3465
3466         for (;;) {
3467                 for (i = RAY_CCS_CMD_FIRST; i <= RAY_CCS_CMD_LAST; i++) {
3468                         /* we probe here to make the card go */
3469                         (void)SRAM_READ_FIELD_1(sc, RAY_CCS_ADDRESS(i), ray_cmd,
3470                             c_status);
3471                         if (!sc->sc_ccsinuse[i])
3472                                 break;
3473                 }
3474                 if (i > RAY_CCS_CMD_LAST) {
3475                         RAY_DPRINTF(sc, RAY_DBG_CCS, "sleeping");
3476                         error = tsleep(ray_ccs_alloc, PCATCH, wmesg, 0);
3477                         if ((sc == NULL) || (sc->sc_gone))
3478                                 return (ENXIO);
3479                         RAY_DPRINTF(sc, RAY_DBG_CCS,
3480                             "awakened, tsleep returned 0x%x", error);
3481                         if (error)
3482                                 return (error);
3483                 } else
3484                         break;
3485         }
3486         RAY_DPRINTF(sc, RAY_DBG_CCS, "allocated 0x%02x", i);
3487         sc->sc_ccsinuse[i] = 1;
3488         ccs = RAY_CCS_ADDRESS(i);
3489         *ccsp = ccs;
3490
3491         return (0);
3492 }
3493
3494 /*
3495  * Fill the easy bits in of a pre-allocated CCS
3496  */
3497 static void
3498 ray_ccs_fill(struct ray_softc *sc, size_t ccs, u_int cmd)
3499 {
3500         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_CCS, "");
3501         RAY_MAP_CM(sc);
3502
3503         if (ccs == NULL)
3504                 RAY_PANIC(sc, "ccs not allocated");
3505
3506         SRAM_WRITE_FIELD_1(sc, ccs, ray_cmd, c_status, RAY_CCS_STATUS_BUSY);
3507         SRAM_WRITE_FIELD_1(sc, ccs, ray_cmd, c_cmd, cmd);
3508         SRAM_WRITE_FIELD_1(sc, ccs, ray_cmd, c_link, RAY_CCS_LINK_NULL);
3509 }
3510
3511 /*
3512  * Free up a ccs allocated via ray_ccs_alloc
3513  *
3514  * Return the old status. This routine is only used for ccs allocated via
3515  * ray_ccs_alloc (not tx, rx or ECF command requests).
3516  */
3517 static void
3518 ray_ccs_free(struct ray_softc *sc, size_t ccs)
3519 {
3520         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_CCS, "");
3521         RAY_MAP_CM(sc);
3522
3523 #if 1 | (RAY_DEBUG & RAY_DBG_CCS)
3524         if (!sc->sc_ccsinuse[RAY_CCS_INDEX(ccs)])
3525                 RAY_RECERR(sc, "freeing free ccs 0x%02x", RAY_CCS_INDEX(ccs));
3526 #endif /* RAY_DEBUG & RAY_DBG_CCS */
3527         if (!sc->sc_gone)
3528                 RAY_CCS_FREE(sc, ccs);
3529         sc->sc_ccsinuse[RAY_CCS_INDEX(ccs)] = 0;
3530         RAY_DPRINTF(sc, RAY_DBG_CCS, "freed 0x%02x", RAY_CCS_INDEX(ccs));
3531         wakeup(ray_ccs_alloc);
3532 }
3533
3534 /*
3535  * Obtain a ccs and tx buffer to transmit with and fill them in.
3536  *
3537  * Returns 0 and in `ccsp' the bus offset of the free ccs. Will not block
3538  * and if none available and will returns EAGAIN.
3539  *
3540  * The caller must fill in the length later.
3541  * The caller must clear the ccs on errors.
3542  */
3543 static int
3544 ray_ccs_tx(struct ray_softc *sc, size_t *ccsp, size_t *bufpp)
3545 {
3546         size_t ccs, bufp;
3547         int i;
3548         u_int8_t status;
3549
3550         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_CCS, "");
3551         RAY_MAP_CM(sc);
3552
3553         i = RAY_CCS_TX_FIRST;
3554         do {
3555                 status = SRAM_READ_FIELD_1(sc, RAY_CCS_ADDRESS(i),
3556                     ray_cmd, c_status);
3557                 if (status == RAY_CCS_STATUS_FREE)
3558                         break;
3559                 i++;
3560         } while (i <= RAY_CCS_TX_LAST);
3561         if (i > RAY_CCS_TX_LAST) {
3562                 return (EAGAIN);
3563         }
3564         RAY_DPRINTF(sc, RAY_DBG_CCS, "allocated 0x%02x", i);
3565
3566         /*
3567          * Reserve and fill the ccs - must do the length later.
3568          *
3569          * Even though build 4 and build 5 have different fields all these
3570          * are common apart from tx_rate. Neither the NetBSD driver or Linux
3571          * driver bother to overwrite this for build 4 cards.
3572          *
3573          * The start of the buffer must be aligned to a 256 byte boundary
3574          * (least significant byte of address = 0x00).
3575          */
3576         ccs = RAY_CCS_ADDRESS(i);
3577         bufp = RAY_TX_BASE + i * RAY_TX_BUF_SIZE;
3578         bufp += sc->sc_tibsize;
3579         SRAM_WRITE_FIELD_1(sc, ccs, ray_cmd_tx, c_status, RAY_CCS_STATUS_BUSY);
3580         SRAM_WRITE_FIELD_1(sc, ccs, ray_cmd_tx, c_cmd, RAY_CMD_TX_REQ);
3581         SRAM_WRITE_FIELD_1(sc, ccs, ray_cmd_tx, c_link, RAY_CCS_LINK_NULL);
3582         SRAM_WRITE_FIELD_2(sc, ccs, ray_cmd_tx, c_bufp, bufp);
3583         SRAM_WRITE_FIELD_1(sc,
3584             ccs, ray_cmd_tx, c_tx_rate, sc->sc_c.np_def_txrate);
3585         SRAM_WRITE_FIELD_1(sc, ccs, ray_cmd_tx, c_apm_mode, 0);
3586         bufp += sizeof(struct ray_tx_phy_header);
3587
3588         *ccsp = ccs;
3589         *bufpp = bufp;
3590         return (0);
3591 }
3592
3593 /*
3594  * Routines to obtain resources for the card
3595  */
3596
3597 /*
3598  * Allocate the attribute memory on the card
3599  *
3600  * The attribute memory space is abused by these devices as IO space. As such
3601  * the OS card services don't have a chance of knowing that they need to keep
3602  * the attribute space mapped. We have to do it manually.
3603  */
3604 static int
3605 ray_res_alloc_am(struct ray_softc *sc)
3606 {
3607         int error;
3608
3609         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_CM, "");
3610
3611         sc->am_rid = RAY_AM_RID;
3612         sc->am_res = bus_alloc_resource(sc->dev, SYS_RES_MEMORY,
3613             &sc->am_rid, 0UL, ~0UL, 0x1000, RF_ACTIVE);
3614         if (!sc->am_res) {
3615                 RAY_PRINTF(sc, "Cannot allocate attribute memory");
3616                 return (ENOMEM);
3617         }
3618         error = CARD_SET_MEMORY_OFFSET(device_get_parent(sc->dev), sc->dev,
3619             sc->am_rid, 0, NULL);
3620         if (error) {
3621                 RAY_PRINTF(sc, "CARD_SET_MEMORY_OFFSET returned 0x%0x", error);
3622                 return (error);
3623         }
3624         error = CARD_SET_RES_FLAGS(device_get_parent(sc->dev), sc->dev,
3625             SYS_RES_MEMORY, sc->am_rid, PCCARD_A_MEM_ATTR);
3626         if (error) {
3627                 RAY_PRINTF(sc, "CARD_SET_RES_FLAGS returned 0x%0x", error);
3628                 return (error);
3629         }
3630         error = CARD_SET_RES_FLAGS(device_get_parent(sc->dev), sc->dev,
3631             SYS_RES_MEMORY, sc->am_rid, PCCARD_A_MEM_8BIT);
3632         if (error) {
3633                 RAY_PRINTF(sc, "CARD_SET_RES_FLAGS returned 0x%0x", error);
3634                 return (error);
3635         }
3636         sc->am_bsh = rman_get_bushandle(sc->am_res);
3637         sc->am_bst = rman_get_bustag(sc->am_res);
3638
3639 #if RAY_DEBUG & (RAY_DBG_CM | RAY_DBG_BOOTPARAM)
3640 {
3641         u_long flags;
3642         u_int32_t offset;
3643         CARD_GET_RES_FLAGS(device_get_parent(sc->dev), sc->dev,
3644             SYS_RES_MEMORY, sc->am_rid, &flags);
3645         CARD_GET_MEMORY_OFFSET(device_get_parent(sc->dev), sc->dev,
3646             sc->am_rid, &offset);
3647         RAY_PRINTF(sc, "allocated attribute memory:\n"
3648             ".  start 0x%0lx count 0x%0lx flags 0x%0lx offset 0x%0x",
3649             bus_get_resource_start(sc->dev, SYS_RES_MEMORY, sc->am_rid),
3650             bus_get_resource_count(sc->dev, SYS_RES_MEMORY, sc->am_rid),
3651             flags, offset);
3652 }
3653 #endif /* RAY_DEBUG & (RAY_DBG_CM | RAY_DBG_BOOTPARAM) */
3654
3655         return (0);
3656 }
3657
3658 /*
3659  * Allocate the common memory on the card
3660  *
3661  * As this memory is described in the CIS, the OS card services should
3662  * have set the map up okay, but the card uses 8 bit RAM. This is not
3663  * described in the CIS.
3664  */
3665 static int
3666 ray_res_alloc_cm(struct ray_softc *sc)
3667 {
3668         u_long start, count, end;
3669         int error;
3670
3671         RAY_DPRINTF(sc, RAY_DBG_SUBR | RAY_DBG_CM, "");
3672
3673         RAY_DPRINTF(sc,RAY_DBG_CM | RAY_DBG_BOOTPARAM,
3674             "cm start 0x%0lx count 0x%0lx",
3675             bus_get_resource_start(sc->dev, SYS_RES_MEMORY, RAY_CM_RID),
3676             bus_get_resource_count(sc->dev, SYS_RES_MEMORY, RAY_CM_RID));
3677
3678         sc->cm_rid = RAY_CM_RID;
3679         start = bus_get_resource_start(sc->dev, SYS_RES_MEMORY, sc->cm_rid);
3680         count = bus_get_resource_count(sc->dev, SYS_RES_MEMORY, sc->cm_rid);
3681         end = start + count - 1;
3682         sc->cm_res = bus_alloc_resource(sc->dev, SYS_RES_MEMORY,
3683             &sc->cm_rid, start, end, count, RF_ACTIVE);
3684         if (!sc->cm_res) {
3685                 RAY_PRINTF(sc, "Cannot allocate common memory");
3686                 return (ENOMEM);
3687         }
3688         error = CARD_SET_MEMORY_OFFSET(device_get_parent(sc->dev), sc->dev,
3689             sc->cm_rid, 0, NULL);
3690         if (error) {
3691                 RAY_PRINTF(sc, "CARD_SET_MEMORY_OFFSET returned 0x%0x", error);
3692                 return (error);
3693         }
3694         error = CARD_SET_RES_FLAGS(device_get_parent(sc->dev), sc->dev,
3695             SYS_RES_MEMORY, sc->cm_rid, PCCARD_A_MEM_COM);
3696         if (error) {
3697                 RAY_PRINTF(sc, "CARD_SET_RES_FLAGS returned 0x%0x", error);
3698                 return (error);
3699         }
3700         error = CARD_SET_RES_FLAGS(device_get_parent(sc->dev), sc->dev,
3701             SYS_RES_MEMORY, sc->cm_rid, PCCARD_A_MEM_8BIT);
3702         if (error) {
3703                 RAY_PRINTF(sc, "CARD_SET_RES_FLAGS returned 0x%0x", error);
3704                 return (error);
3705         }
3706         sc->cm_bsh = rman_get_bushandle(sc->cm_res);
3707         sc->cm_bst = rman_get_bustag(sc->cm_res);
3708
3709 #if RAY_DEBUG & (RAY_DBG_CM | RAY_DBG_BOOTPARAM)
3710 {
3711         u_long flags;
3712         u_int32_t offset;
3713         CARD_GET_RES_FLAGS(device_get_parent(sc->dev), sc->dev,
3714             SYS_RES_MEMORY, sc->cm_rid, &flags);
3715         CARD_GET_MEMORY_OFFSET(device_get_parent(sc->dev), sc->dev,
3716             sc->cm_rid, &offset);
3717         RAY_PRINTF(sc, "allocated common memory:\n"
3718             ".  start 0x%0lx count 0x%0lx flags 0x%0lx offset 0x%0x",
3719             bus_get_resource_start(sc->dev, SYS_RES_MEMORY, sc->cm_rid),
3720             bus_get_resource_count(sc->dev, SYS_RES_MEMORY, sc->cm_rid),
3721             flags, offset);
3722 }
3723 #endif /* RAY_DEBUG & (RAY_DBG_CM | RAY_DBG_BOOTPARAM) */
3724
3725         return (0);
3726 }
3727
3728 /*
3729  * Get an irq and attach it to the bus
3730  */
3731 static int
3732 ray_res_alloc_irq(struct ray_softc *sc)
3733 {
3734         int error;
3735
3736         RAY_DPRINTF(sc, RAY_DBG_SUBR, "");
3737
3738         RAY_DPRINTF(sc,RAY_DBG_CM | RAY_DBG_BOOTPARAM,
3739             "irq start 0x%0lx count 0x%0lx",
3740             bus_get_resource_start(sc->dev, SYS_RES_IRQ, 0),
3741             bus_get_resource_count(sc->dev, SYS_RES_IRQ, 0));
3742
3743         sc->irq_rid = 0;
3744         sc->irq_res = bus_alloc_resource(sc->dev, SYS_RES_IRQ, &sc->irq_rid,
3745             0, ~0, 1, RF_ACTIVE);
3746         if (!sc->irq_res) {
3747                 RAY_PRINTF(sc, "Cannot allocate irq");
3748                 return (ENOMEM);
3749         }
3750         if ((error = bus_setup_intr(sc->dev, sc->irq_res, INTR_TYPE_NET,
3751             ray_intr, sc, &sc->irq_handle)) != 0) {
3752                 RAY_PRINTF(sc, "Failed to setup irq");
3753                 return (error);
3754         }
3755         RAY_DPRINTF(sc, RAY_DBG_CM | RAY_DBG_BOOTPARAM, "allocated irq:\n"
3756             ".  start 0x%0lx count 0x%0lx",
3757             bus_get_resource_start(sc->dev, SYS_RES_IRQ, sc->irq_rid),
3758             bus_get_resource_count(sc->dev, SYS_RES_IRQ, sc->irq_rid));
3759
3760         return (0);
3761 }
3762
3763 /*
3764  * Release all of the card's resources
3765  */
3766 static void
3767 ray_res_release(struct ray_softc *sc)
3768 {
3769         if (sc->irq_res != 0) {
3770                 bus_teardown_intr(sc->dev, sc->irq_res, sc->irq_handle);
3771                 bus_release_resource(sc->dev, SYS_RES_IRQ,
3772                     sc->irq_rid, sc->irq_res);
3773                 sc->irq_res = 0;
3774         }
3775         if (sc->am_res != 0) {
3776                 bus_release_resource(sc->dev, SYS_RES_MEMORY,
3777                     sc->am_rid, sc->am_res);
3778                 sc->am_res = 0;
3779         }
3780         if (sc->cm_res != 0) {
3781                 bus_release_resource(sc->dev, SYS_RES_MEMORY,
3782                     sc->cm_rid, sc->cm_res);
3783                 sc->cm_res = 0;
3784         }
3785 }
3786
3787 /*
3788  * mbuf dump
3789  */
3790 #if RAY_DEBUG & RAY_DBG_MBUF
3791 static void
3792 ray_dump_mbuf(struct ray_softc *sc, struct mbuf *m, char *s)
3793 {
3794         u_int8_t *d, *ed;
3795         u_int i;
3796         char p[17];
3797
3798         RAY_PRINTF(sc, "%s", s);
3799         RAY_PRINTF(sc, "\nm0->data\t0x%p\nm_pkthdr.len\t%d\nm_len\t%d",
3800             mtod(m, u_int8_t *), m->m_pkthdr.len, m->m_len);
3801         i = 0;
3802         bzero(p, 17);
3803         for (; m; m = m->m_next) {
3804                 d = mtod(m, u_int8_t *);
3805                 ed = d + m->m_len;
3806
3807                 for (; d < ed; i++, d++) {
3808                         if ((i % 16) == 0) {
3809                                 printf("  %s\n\t", p);
3810                         } else if ((i % 8) == 0)
3811                                 printf("  ");
3812                         printf(" %02x", *d);
3813                         p[i % 16] = ((*d >= 0x20) && (*d < 0x80)) ? *d : '.';
3814                 }
3815         }
3816         if ((i - 1) % 16)
3817                 printf("  %s\n", p);
3818 }
3819 #endif /* RAY_DEBUG & RAY_DBG_MBUF */