Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / sys / dev / netif / xe / if_xe.c
1 /*-
2  * Copyright (c) 1998, 1999 Scott Mitchell
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  *      $Id: if_xe.c,v 1.20 1999/06/13 19:17:40 scott Exp $
27  * $FreeBSD: src/sys/dev/xe/if_xe.c,v 1.13.2.6 2003/02/05 22:03:57 mbr Exp $
28  * $DragonFly: src/sys/dev/netif/xe/if_xe.c,v 1.2 2003/06/17 04:28:33 dillon Exp $
29  */
30
31 /*
32  * XXX TODO XXX
33  *
34  * I've pushed this fairly far, but there are some things that need to be
35  * done here.  I'm documenting them here in case I get destracted. -- imp
36  *
37  * xe_cem56fix -- need to figure out how to map the extra stuff.
38  */
39
40 /*
41  * Portions of this software were derived from Werner Koch's xirc2ps driver
42  * for Linux under the terms of the following license (from v1.30 of the
43  * xirc2ps driver):
44  *
45  * Copyright (c) 1997 by Werner Koch (dd9jn)
46  *
47  * Redistribution and use in source and binary forms, with or without
48  * modification, are permitted provided that the following conditions
49  * are met:
50  * 1. Redistributions of source code must retain the above copyright
51  *    notice, and the entire permission notice in its entirety,
52  *    including the disclaimer of warranties.
53  * 2. Redistributions in binary form must reproduce the above copyright
54  *    notice, this list of conditions and the following disclaimer in the
55  *    documentation and/or other materials provided with the distribution.
56  * 3. The name of the author may not be used to endorse or promote
57  *    products derived from this software without specific prior
58  *    written permission.
59  *
60  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
61  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
62  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
63  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
64  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
65  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
66  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
68  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
69  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
70  * OF THE POSSIBILITY OF SUCH DAMAGE.
71  */
72
73 /*              
74  * FreeBSD device driver for Xircom CreditCard PCMCIA Ethernet adapters.  The
75  * following cards are currently known to work with the driver:
76  *   Xircom CreditCard 10/100 (CE3)
77  *   Xircom CreditCard Ethernet + Modem 28 (CEM28)
78  *   Xircom CreditCard Ethernet 10/100 + Modem 56 (CEM56)
79  *   Xircom RealPort Ethernet 10
80  *   Xircom RealPort Ethernet 10/100
81  *   Xircom RealPort Ethernet 10/100 + Modem 56 (REM56, REM56G)
82  *   Intel EtherExpress Pro/100 PC Card Mobile Adapter 16 (Pro/100 M16A)
83  *   Compaq Netelligent 10/100 PC Card (CPQ-10/100)
84  *
85  * Some other cards *should* work, but support for them is either broken or in 
86  * an unknown state at the moment.  I'm always interested in hearing from
87  * people who own any of these cards:
88  *   Xircom CreditCard 10Base-T (PS-CE2-10)
89  *   Xircom CreditCard Ethernet + ModemII (CEM2)
90  *   Xircom CEM28 and CEM33 Ethernet/Modem cards (may be variants of CEM2?)
91  *
92  * Thanks to all who assisted with the development and testing of the driver,
93  * especially: Werner Koch, Duke Kamstra, Duncan Barclay, Jason George, Dru
94  * Nelson, Mike Kephart, Bill Rainey and Douglas Rand.  Apologies if I've left
95  * out anyone who deserves a mention here.
96  *
97  * Special thanks to Ade Lovett for both hosting the mailing list and doing
98  * the CEM56/REM56 support code; and the FreeBSD UK Users' Group for hosting
99  * the web pages.
100  *
101  * Contact points:
102  *
103  * Driver web page: http://ukug.uk.freebsd.org/~scott/xe_drv/
104  *
105  * Mailing list: http://www.lovett.com/lists/freebsd-xircom/
106  * or send "subscribe freebsd-xircom" to <majordomo@lovett.com>
107  *
108  * Author email: <scott@uk.freebsd.org>
109  */
110
111
112 #include <sys/param.h>
113 #include <sys/cdefs.h>
114 #include <sys/errno.h>
115 #include <sys/kernel.h>
116 #include <sys/mbuf.h>
117 #include <sys/select.h>
118 #include <sys/socket.h>
119 #include <sys/sockio.h>
120 #include <sys/systm.h>
121 #include <sys/uio.h>
122
123 #include <sys/module.h>
124 #include <sys/bus.h>
125
126 #include <machine/bus.h>
127 #include <machine/resource.h>
128 #include <sys/rman.h>
129  
130 #include <net/ethernet.h>
131 #include <net/if.h>
132 #include <net/if_arp.h>
133 #include <net/if_dl.h>
134 #include <net/if_media.h>
135 #include <net/if_mib.h>
136 #include <net/bpf.h>
137
138 #include <dev/pccard/pccardvar.h>
139 #include "card_if.h"
140
141 #include <dev/xe/if_xereg.h>
142 #include <dev/xe/if_xevar.h>
143
144 #include <machine/clock.h>
145
146 /*
147  * MII command structure
148  */
149 struct xe_mii_frame {
150   u_int8_t  mii_stdelim;
151   u_int8_t  mii_opcode;
152   u_int8_t  mii_phyaddr;
153   u_int8_t  mii_regaddr;
154   u_int8_t  mii_turnaround;
155   u_int16_t mii_data;
156 };
157
158 /*
159  * Media autonegotiation progress constants
160  */
161 #define XE_AUTONEG_NONE         0       /* No autonegotiation in progress */
162 #define XE_AUTONEG_WAITING      1       /* Waiting for transmitter to go idle */
163 #define XE_AUTONEG_STARTED      2       /* Waiting for autonegotiation to complete */
164 #define XE_AUTONEG_100TX        3       /* Trying to force 100baseTX link */
165 #define XE_AUTONEG_FAIL         4       /* Autonegotiation failed */
166
167
168 /*
169  * Prototypes start here
170  */
171 static int       xe_probe               (device_t dev);
172 static int       xe_attach              (device_t dev);
173 static int       xe_detach              (device_t dev);
174 static int       xe_activate            (device_t dev);
175 static void      xe_deactivate          (device_t dev);
176 static void      xe_init                (void *xscp);
177 static void      xe_start               (struct ifnet *ifp);
178 static int       xe_ioctl               (struct ifnet *ifp, u_long command, caddr_t data);
179 static void      xe_watchdog            (struct ifnet *ifp);
180 static int       xe_media_change        (struct ifnet *ifp);
181 static void      xe_media_status        (struct ifnet *ifp, struct ifmediareq *mrp);
182 static timeout_t xe_setmedia;
183 static void      xe_hard_reset          (struct xe_softc *scp);
184 static void      xe_soft_reset          (struct xe_softc *scp);
185 static void      xe_stop                (struct xe_softc *scp);
186 static void      xe_enable_intr         (struct xe_softc *scp);
187 static void      xe_disable_intr        (struct xe_softc *scp);
188 static void      xe_setmulti            (struct xe_softc *scp);
189 static void      xe_setaddrs            (struct xe_softc *scp);
190 static int       xe_pio_write_packet    (struct xe_softc *scp, struct mbuf *mbp);
191 static u_int32_t xe_compute_crc         (u_int8_t *data, int len);
192 static int       xe_compute_hashbit     (u_int32_t crc);
193
194 /*
195  * MII functions
196  */
197 static void      xe_mii_sync            (struct xe_softc *scp);
198 static int       xe_mii_init            (struct xe_softc *scp);
199 static void      xe_mii_send            (struct xe_softc *scp, u_int32_t bits, int cnt);
200 static int       xe_mii_readreg         (struct xe_softc *scp, struct xe_mii_frame *frame);
201 static int       xe_mii_writereg        (struct xe_softc *scp, struct xe_mii_frame *frame);
202 static u_int16_t xe_phy_readreg         (struct xe_softc *scp, u_int16_t reg);
203 static void      xe_phy_writereg        (struct xe_softc *scp, u_int16_t reg, u_int16_t data);
204
205 /*
206  * Debug functions -- uncomment for VERY verbose dignostic information.
207  * Set to 1 for less verbose information
208  */
209 /* #define XE_DEBUG 2 */
210 #ifdef XE_DEBUG
211 #define XE_REG_DUMP(scp)                xe_reg_dump((scp))
212 #define XE_MII_DUMP(scp)                xe_mii_dump((scp))
213 static void      xe_reg_dump            (struct xe_softc *scp);
214 static void      xe_mii_dump            (struct xe_softc *scp);
215 #else
216 #define XE_REG_DUMP(scp)
217 #define XE_MII_DUMP(scp)
218 #endif
219
220 /*
221  * Fixing for RealPort cards - they need a little furtling to get the
222  * ethernet working
223  */
224 static int
225 xe_cem56fix(device_t dev)
226 {
227   struct xe_softc *sc = (struct xe_softc *) device_get_softc(dev);
228   bus_space_tag_t bst;
229   bus_space_handle_t bsh;
230   struct resource *r;
231   int rid;
232   int ioport;
233
234 #ifdef XE_DEBUG
235   device_printf(dev, "Hacking your Realport, master\n");
236 #endif
237  
238 #if XE_DEBUG > 1
239   device_printf(dev, "Realport port 0x%0lx, size 0x%0lx\n",
240       bus_get_resource_start(dev, SYS_RES_IOPORT, sc->port_rid),
241       bus_get_resource_count(dev, SYS_RES_IOPORT, sc->port_rid));
242 #endif
243
244   rid = 0;
245   r = bus_alloc_resource(dev, SYS_RES_MEMORY, &rid, 0, ~0, 4 << 10, RF_ACTIVE);
246   if (!r) {
247 #if XE_DEBUG > 0
248     device_printf(dev, "Can't map in attribute memory\n");
249 #endif
250     return -1;
251   }
252
253   bsh = rman_get_bushandle(r);
254   bst = rman_get_bustag(r);
255
256   CARD_SET_RES_FLAGS(device_get_parent(dev), dev, SYS_RES_MEMORY, rid,
257       PCCARD_A_MEM_ATTR);
258
259   bus_space_write_1(bst, bsh, DINGO_ECOR, DINGO_ECOR_IRQ_LEVEL |
260                                           DINGO_ECOR_INT_ENABLE |
261                                           DINGO_ECOR_IOB_ENABLE |
262                                           DINGO_ECOR_ETH_ENABLE);
263   ioport = bus_get_resource_start(dev, SYS_RES_IOPORT, sc->port_rid);
264   bus_space_write_1(bst, bsh, DINGO_EBAR0, ioport & 0xff);
265   bus_space_write_1(bst, bsh, DINGO_EBAR1, (ioport >> 8) & 0xff);
266
267   bus_space_write_1(bst, bsh, DINGO_DCOR0, DINGO_DCOR0_SF_INT);
268   bus_space_write_1(bst, bsh, DINGO_DCOR1, DINGO_DCOR1_INT_LEVEL |
269                                            DINGO_DCOR1_EEDIO);
270   bus_space_write_1(bst, bsh, DINGO_DCOR2, 0x00);
271   bus_space_write_1(bst, bsh, DINGO_DCOR3, 0x00);
272   bus_space_write_1(bst, bsh, DINGO_DCOR4, 0x00);
273
274   bus_release_resource(dev, SYS_RES_MEMORY, rid, r);
275
276   /* success! */
277   return 0;
278 }
279         
280 /*
281  * PCMCIA probe routine.
282  * Probe and identify the device.  Called by the slot manager when the card is 
283  * inserted or the machine wakes up from suspend mode.  Assmes that the slot
284  * structure has been initialised already.
285  */
286 static int
287 xe_probe(device_t dev)
288 {
289   struct xe_softc *scp = (struct xe_softc *) device_get_softc(dev);
290   bus_space_tag_t bst;
291   bus_space_handle_t bsh;
292   int buf;
293   u_char ver_str[CISTPL_BUFSIZE>>1];
294   off_t offs;
295   int success, rc, i;
296   int rid;
297   struct resource *r;
298
299   success = 0;
300
301 #ifdef XE_DEBUG
302   device_printf(dev, "xe: Probing\n");
303 #endif
304
305   /* Map in the CIS */
306   rid = 0;
307   r = bus_alloc_resource(dev, SYS_RES_MEMORY, &rid, 0, ~0, 4 << 10, RF_ACTIVE);
308   if (!r) {
309 #ifdef XE_DEBUG
310     device_printf(dev, "Can't map in cis\n");
311 #endif
312     return ENOMEM;
313   }
314   bsh = rman_get_bushandle(r);
315   bst = rman_get_bustag(r);
316   buf = 0;
317
318   CARD_SET_RES_FLAGS(device_get_parent(dev), dev, SYS_RES_MEMORY, rid,
319       PCCARD_A_MEM_ATTR);
320
321   /* Grep through CIS looking for relevant tuples */
322   offs = 0;
323   do {
324     u_int16_t vendor;
325     u_int8_t rev, media, prod;
326
327     switch (CISTPL_TYPE(buf)) {
328
329     case 0x15:  /* Grab version string (needed to ID some weird CE2's) */
330 #if XE_DEBUG > 1
331       device_printf(dev, "Got version string (0x15)\n");
332 #endif
333       for (i = 0; i < CISTPL_LEN(buf); ver_str[i] = CISTPL_DATA(buf, i++));
334       ver_str[i] = '\0';
335       ver_str[(CISTPL_BUFSIZE>>1) - 1] = CISTPL_LEN(buf);
336       success++;
337       break;
338
339     case 0x20:  /* Figure out what type of card we have */
340 #if XE_DEBUG > 1
341       device_printf(dev, "Got card ID (0x20)\n");
342 #endif
343       vendor = CISTPL_DATA(buf, 0) + (CISTPL_DATA(buf, 1) << 8);
344       rev = CISTPL_DATA(buf, 2);
345       media = CISTPL_DATA(buf, 3);
346       prod = CISTPL_DATA(buf, 4);
347
348       switch (vendor) { /* Get vendor ID */
349       case 0x0105:
350         scp->vendor = "Xircom"; break;
351       case 0x0138:
352       case 0x0183:
353         scp->vendor = "Compaq"; break;
354       case 0x0089:
355         scp->vendor = "Intel"; break;
356       default:
357         scp->vendor = "Unknown";
358       }
359
360       if (!((prod & 0x40) && (media & 0x01))) {
361 #if XE_DEBUG > 1
362         device_printf(dev, "Not a PCMCIA Ethernet card!\n");
363 #endif
364         rc = ENODEV;            /* Not a PCMCIA Ethernet device */
365       } else {
366         if (media & 0x10) {     /* Ethernet/modem cards */
367 #if XE_DEBUG > 1
368           device_printf(dev, "Card is Ethernet/modem combo\n");
369 #endif
370           scp->modem = 1;
371           switch (prod & 0x0f) {
372           case 1:
373             scp->card_type = "CEM"; break;
374           case 2:
375             scp->ce2 = 1;
376             scp->card_type = "CEM2"; break;
377           case 3:
378             scp->ce2 = 1;
379             scp->card_type = "CEM3"; break;
380           case 4:
381             scp->ce2 = 1;
382             scp->card_type = "CEM33"; break;
383           case 5:
384             scp->mohawk = 1;
385             scp->card_type = "CEM56M"; break;
386           case 6:
387           case 7:               /* Some kind of RealPort card */
388             scp->mohawk = 1;
389             scp->dingo = 1;
390             scp->card_type = "CEM56"; break;
391           default:
392             rc = ENODEV;
393           }
394         } else {                /* Ethernet-only cards */
395 #if XE_DEBUG > 1
396           device_printf(dev, "Card is Ethernet only\n");
397 #endif
398           switch (prod & 0x0f) {
399           case 1:
400             scp->card_type = "CE"; break;
401           case 2:
402             scp->ce2 = 1;
403             scp->card_type = "CE2"; break;
404           case 3:
405             scp->mohawk = 1;
406             scp->card_type = "CE3"; break;
407           default:
408             rc = ENODEV;
409           }
410         }
411       }
412       success++;
413       break;
414
415     case 0x22:  /* Get MAC address */
416       if ((CISTPL_LEN(buf) == 8) &&
417           (CISTPL_DATA(buf, 0) == 0x04) &&
418           (CISTPL_DATA(buf, 1) == ETHER_ADDR_LEN)) {
419 #if XE_DEBUG > 1
420         device_printf(dev, "Got MAC address (0x22)\n");
421 #endif
422         for (i = 0; i < ETHER_ADDR_LEN; i++)
423           scp->arpcom.ac_enaddr[i] = CISTPL_DATA(buf, i+2);
424       }
425       success++;
426       break;
427     default:
428       break;
429     }
430
431     if (CISTPL_TYPE(buf) == 0xff)
432       break;
433     /* Skip to next tuple */
434     buf += ((CISTPL_LEN(buf) + 2) << 1);
435
436   } while (1);
437
438   /* unmap the cis */
439   bus_release_resource(dev, SYS_RES_MEMORY, rid, r);
440
441   /* Die now if something went wrong above */
442   if (success < 3)
443     return ENXIO;
444
445   /* Check for certain strange CE2's that look like CE's */
446   if (strcmp(scp->card_type, "CE") == 0) {
447     u_char *str = ver_str;
448 #if XE_DEBUG > 1
449     device_printf(dev, "Checking for weird CE2 string\n");
450 #endif
451     str += strlen(str) + 1;                     /* Skip forward to 3rd version string */
452     str += strlen(str) + 1;
453     str += strlen(str) + 1;
454     for (i = 0; i < strlen(str) - 2; i++) {
455       if (bcmp(&str[i], "CE2", 3) ==0) {        /* Look for "CE2" string */
456         scp->card_type = "CE2";
457       }
458     }
459   }
460
461   /* Reject unsupported cards */
462   if (strcmp(scp->card_type, "CE") == 0 || strcmp(scp->card_type, "CEM") == 0) {
463     device_printf(dev, "Sorry, your %s card is not supported :(\n",
464      scp->card_type);
465     return ENODEV;
466   }
467
468   /* Success */
469   return 0;
470 }
471
472 /*
473  * The device entry is being removed, probably because someone ejected the
474  * card.  The interface should have been brought down manually before calling
475  * this function; if not you may well lose packets.  In any case, I shut down
476  * the card and the interface, and hope for the best.
477  */
478 static int
479 xe_detach(device_t dev) {
480   struct xe_softc *sc = device_get_softc(dev);
481
482   sc->arpcom.ac_if.if_flags &= ~IFF_RUNNING; 
483   ether_ifdetach(&sc->arpcom.ac_if, ETHER_BPF_SUPPORTED);
484   xe_deactivate(dev);
485   return 0;
486 }
487
488 /*
489  * Attach a device.
490  */
491 static int
492 xe_attach (device_t dev) {
493   struct xe_softc *scp = device_get_softc(dev);
494   int err;
495
496 #ifdef XE_DEBUG
497   device_printf(dev, "attach\n");
498 #endif
499
500   if ((err = xe_activate(dev)) != 0)
501     return (err);
502
503   /* Fill in some private data */
504   scp->ifp = &scp->arpcom.ac_if;
505   scp->ifm = &scp->ifmedia;
506   scp->autoneg_status = 0;
507
508   /* Hack RealPorts into submission */
509   if (scp->dingo && xe_cem56fix(dev) < 0) {
510     device_printf(dev, "Unable to fix your RealPort\n");
511     xe_deactivate(dev);
512     return ENODEV;
513   }
514
515   /* Hopefully safe to read this here */
516   XE_SELECT_PAGE(4);
517   scp->version = XE_INB(XE_BOV);
518
519   scp->dev = dev;
520   /* Initialise the ifnet structure */
521   if (!scp->ifp->if_name) {
522     scp->ifp->if_softc = scp;
523     scp->ifp->if_name = "xe";
524     scp->ifp->if_unit = device_get_unit(dev);
525     scp->ifp->if_timer = 0;
526     scp->ifp->if_flags = (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
527     scp->ifp->if_linkmib = &scp->mibdata;
528     scp->ifp->if_linkmiblen = sizeof scp->mibdata;
529     scp->ifp->if_output = ether_output;
530     scp->ifp->if_start = xe_start;
531     scp->ifp->if_ioctl = xe_ioctl;
532     scp->ifp->if_watchdog = xe_watchdog;
533     scp->ifp->if_init = xe_init;
534     scp->ifp->if_snd.ifq_maxlen = IFQ_MAXLEN;
535   }
536
537   /* Initialise the ifmedia structure */
538   ifmedia_init(scp->ifm, 0, xe_media_change, xe_media_status);
539   callout_handle_init(&scp->chand);
540
541   /*
542    * Fill in supported media types.  Some cards _do_ support full duplex
543    * operation, but this driver doesn't, yet.  Therefore we leave those modes
544    * out of the list.  We support some form of autoselection in all cases.
545    */
546   if (scp->mohawk) {
547     ifmedia_add(scp->ifm, IFM_ETHER|IFM_100_TX, 0, NULL);
548     ifmedia_add(scp->ifm, IFM_ETHER|IFM_10_T, 0, NULL);
549   }
550   else {
551     ifmedia_add(scp->ifm, IFM_ETHER|IFM_10_T, 0, NULL);
552     ifmedia_add(scp->ifm, IFM_ETHER|IFM_10_2, 0, NULL);
553   }
554   ifmedia_add(scp->ifm, IFM_ETHER|IFM_AUTO, 0, NULL);
555
556   /* Default is to autoselect best supported media type */
557   ifmedia_set(scp->ifm, IFM_ETHER|IFM_AUTO);
558
559   /* Print some useful information */
560   device_printf(dev, "%s %s, bonding version %#x%s%s\n",
561          scp->vendor,
562          scp->card_type,
563          scp->version,
564          scp->mohawk ? ", 100Mbps capable" : "",
565          scp->modem ?  ", with modem"      : "");
566   if (scp->mohawk) {
567     XE_SELECT_PAGE(0x10);
568     device_printf(dev, "DingoID = %#x, RevisionID = %#x, VendorID = %#x\n",
569            XE_INW(XE_DINGOID),
570            XE_INW(XE_RevID),
571            XE_INW(XE_VendorID));
572   }
573   if (scp->ce2) {
574     XE_SELECT_PAGE(0x45);
575     device_printf(dev, "CE2 version = %#x\n", XE_INB(XE_REV));
576   }
577
578   /* Print MAC address */
579   device_printf(dev, "Ethernet address %6D\n", scp->arpcom.ac_enaddr, ":");
580
581   /* Attach the interface */
582   ether_ifattach(scp->ifp, ETHER_BPF_SUPPORTED);
583
584   /* Done */
585   return 0;
586 }
587
588
589 /*
590  * Initialize device.  Completes the reset procedure on the card and starts
591  * output.  If there's an autonegotiation in progress we DON'T do anything;
592  * the media selection code will call us again when it's done.
593  */
594 static void
595 xe_init(void *xscp) {
596   struct xe_softc *scp = xscp;
597   int s;
598
599 #ifdef XE_DEBUG
600   device_printf(scp->dev, "init\n");
601 #endif
602
603   if (TAILQ_EMPTY(&scp->ifp->if_addrhead)) return;
604
605   /* Reset transmitter flags */
606   scp->tx_queued = 0;
607   scp->tx_tpr = 0;
608   scp->tx_collisions = 0;
609   scp->ifp->if_timer = 0;
610
611   s = splimp();
612
613   XE_SELECT_PAGE(0x42);
614   XE_OUTB(XE_SWC0, 0x20);       /* Disable source insertion (WTF is that?) */
615
616   /*
617    * Set the 'local memory dividing line' -- splits the 32K card memory into
618    * 8K for transmit buffers and 24K for receive.  This is done automatically
619    * on newer revision cards.
620    */
621   if (scp->srev != 1) {
622     XE_SELECT_PAGE(2);
623     XE_OUTW(XE_RBS, 0x2000);
624   }
625
626   /* Set up multicast addresses */
627   xe_setmulti(scp);
628
629   /* Fix the data offset register -- reset leaves it off-by-one */
630   XE_SELECT_PAGE(0);
631   XE_OUTW(XE_DO, 0x2000);
632
633   /*
634    * Set MAC interrupt masks and clear status regs.  The bit names are direct
635    * from the Linux code; I have no idea what most of them do.
636    */
637   XE_SELECT_PAGE(0x40);         /* Bit 7..0 */
638   XE_OUTB(XE_RX0Msk, 0xff);     /* ROK, RAB, rsv, RO,  CRC, AE,  PTL, MP  */
639   XE_OUTB(XE_TX0Msk, 0xff);     /* TOK, TAB, SQE, LL,  TU,  JAB, EXC, CRS */
640   XE_OUTB(XE_TX0Msk+1, 0xb0);   /* rsv, rsv, PTD, EXT, rsv, rsv, rsv, rsv */
641   XE_OUTB(XE_RST0, 0x00);       /* ROK, RAB, REN, RO,  CRC, AE,  PTL, MP  */
642   XE_OUTB(XE_TXST0, 0x00);      /* TOK, TAB, SQE, LL,  TU,  JAB, EXC, CRS */
643   XE_OUTB(XE_TXST1, 0x00);      /* TEN, rsv, PTD, EXT, retry_counter:4    */
644
645   /*
646    * Check for an in-progress autonegotiation.  If one is active, just set
647    * IFF_RUNNING and return.  The media selection code will call us again when 
648    * it's done.
649    */
650   if (scp->autoneg_status) {
651     scp->ifp->if_flags |= IFF_RUNNING;
652   }
653   else {
654     /* Enable receiver, put MAC online */
655     XE_SELECT_PAGE(0x40);
656     XE_OUTB(XE_CMD0, XE_CMD0_RX_ENABLE|XE_CMD0_ONLINE);
657
658     /* Set up IMR, enable interrupts */
659     xe_enable_intr(scp);
660
661     /* Attempt to start output */
662     scp->ifp->if_flags |= IFF_RUNNING;
663     scp->ifp->if_flags &= ~IFF_OACTIVE;
664     xe_start(scp->ifp);
665   }
666
667   (void)splx(s);
668 }
669
670
671 /*
672  * Start output on interface.  We make two assumptions here:
673  *  1) that the current priority is set to splimp _before_ this code
674  *     is called *and* is returned to the appropriate priority after
675  *     return
676  *  2) that the IFF_OACTIVE flag is checked before this code is called
677  *     (i.e. that the output part of the interface is idle)
678  */
679 static void
680 xe_start(struct ifnet *ifp) {
681   struct xe_softc *scp = ifp->if_softc;
682   struct mbuf *mbp;
683
684   /*
685    * Loop while there are packets to be sent, and space to send them.
686    */
687   while (1) {
688     IF_DEQUEUE(&ifp->if_snd, mbp);      /* Suck a packet off the send queue */
689
690     if (mbp == NULL) {
691       /*
692        * We are using the !OACTIVE flag to indicate to the outside world that
693        * we can accept an additional packet rather than that the transmitter
694        * is _actually_ active. Indeed, the transmitter may be active, but if
695        * we haven't filled all the buffers with data then we still want to
696        * accept more.
697        */
698       ifp->if_flags &= ~IFF_OACTIVE;
699       return;
700     }
701
702     if (xe_pio_write_packet(scp, mbp) != 0) {
703       IF_PREPEND(&ifp->if_snd, mbp);    /* Push the packet back onto the queue */
704       ifp->if_flags |= IFF_OACTIVE;
705       return;
706     }
707
708     /* Tap off here if there is a bpf listener */
709     if (ifp->if_bpf) {
710 #if XE_DEBUG > 1
711       device_printf(scp->dev, "sending output packet to BPF\n");
712 #endif
713       bpf_mtap(ifp, mbp);
714     }
715
716     ifp->if_timer = 5;                  /* In case we don't hear from the card again */
717     scp->tx_queued++;
718
719     m_freem(mbp);
720   }
721 }
722
723
724 /*
725  * Process an ioctl request.  Adapted from the ed driver.
726  */
727 static int
728 xe_ioctl (register struct ifnet *ifp, u_long command, caddr_t data) {
729   struct xe_softc *scp;
730   int s, error;
731
732   scp = ifp->if_softc;
733   error = 0;
734
735   s = splimp();
736
737   switch (command) {
738
739    case SIOCSIFADDR:
740    case SIOCGIFADDR:
741    case SIOCSIFMTU:
742     error = ether_ioctl(ifp, command, data);
743     break;
744
745    case SIOCSIFFLAGS:
746     /*
747      * If the interface is marked up and stopped, then start it.  If it is
748      * marked down and running, then stop it.
749      */
750     if (ifp->if_flags & IFF_UP) {
751       if (!(ifp->if_flags & IFF_RUNNING)) {
752         xe_hard_reset(scp);
753         xe_setmedia(scp);
754         xe_init(scp);
755       }
756     }
757     else {
758       if (ifp->if_flags & IFF_RUNNING)
759         xe_stop(scp);
760     }
761
762    case SIOCADDMULTI:
763    case SIOCDELMULTI:
764     /*
765      * Multicast list has (maybe) changed; set the hardware filter
766      * accordingly.  This also serves to deal with promiscuous mode if we have 
767      * a BPF listener active.
768      */
769     xe_setmulti(scp);
770     error = 0;
771     break;
772
773    case SIOCSIFMEDIA:
774    case SIOCGIFMEDIA:
775     /*
776      * Someone wants to get/set media options.
777      */
778     error = ifmedia_ioctl(ifp, (struct ifreq *)data, &scp->ifmedia, command);
779     break;
780
781    default:
782     error = EINVAL;
783   }
784
785   (void)splx(s);
786
787   return error;
788 }
789
790
791 /*
792  * Card interrupt handler.
793  *
794  * This function is probably more complicated than it needs to be, as it
795  * attempts to deal with the case where multiple packets get sent between
796  * interrupts.  This is especially annoying when working out the collision
797  * stats.  Not sure whether this case ever really happens or not (maybe on a
798  * slow/heavily loaded machine?) so it's probably best to leave this like it
799  * is.
800  *
801  * Note that the crappy PIO used to get packets on and off the card means that 
802  * you will spend a lot of time in this routine -- I can get my P150 to spend
803  * 90% of its time servicing interrupts if I really hammer the network.  Could 
804  * fix this, but then you'd start dropping/losing packets.  The moral of this
805  * story?  If you want good network performance _and_ some cycles left over to 
806  * get your work done, don't buy a Xircom card.  Or convince them to tell me
807  * how to do memory-mapped I/O :)
808  */
809 static void
810 xe_intr(void *xscp) 
811 {
812   struct xe_softc *scp = (struct xe_softc *) xscp;
813   struct ifnet *ifp;
814   int result;
815   u_int16_t rx_bytes, rxs, txs;
816   u_int8_t psr, isr, esr, rsr;
817
818   ifp = &scp->arpcom.ac_if;
819   rx_bytes = 0;                 /* Bytes received on this interrupt */
820   result = 0;                   /* Set true if the interrupt is for us */
821
822   if (scp->mohawk) {
823     XE_OUTB(XE_CR, 0);          /* Disable interrupts */
824   }
825
826   psr = XE_INB(XE_PR);          /* Stash the current register page */
827
828   /*
829    * Read ISR to see what caused this interrupt.  Note that this clears the
830    * ISR on CE2 type cards.
831    */
832   if ((isr = XE_INB(XE_ISR)) && isr != 0xff) {
833
834     result = 1;                 /* This device did generate an int */
835     esr = XE_INB(XE_ESR);       /* Read the other status registers */
836     XE_SELECT_PAGE(0x40);
837     rxs = XE_INB(XE_RST0);
838     XE_OUTB(XE_RST0, ~rxs & 0xff);
839     txs = XE_INB(XE_TXST0);
840     txs |= XE_INB(XE_TXST1) << 8;
841     XE_OUTB(XE_TXST0, 0);
842     XE_OUTB(XE_TXST1, 0);
843     XE_SELECT_PAGE(0);
844
845 #if XE_DEBUG > 2
846     printf("xe%d: ISR=%#2.2x ESR=%#2.2x RST=%#2.2x TXST=%#4.4x\n", unit, isr, esr, rxs, txs);
847 #endif
848
849     /*
850      * Handle transmit interrupts
851      */
852     if (isr & XE_ISR_TX_PACKET) {
853       u_int8_t new_tpr, sent;
854       
855       if ((new_tpr = XE_INB(XE_TPR)) < scp->tx_tpr)     /* Update packet count */
856         sent = (0xff - scp->tx_tpr) + new_tpr;          /* TPR rolled over */
857       else
858         sent = new_tpr - scp->tx_tpr;
859
860       if (sent > 0) {                           /* Packets sent since last interrupt */
861         scp->tx_tpr = new_tpr;
862         scp->tx_queued -= sent;
863         ifp->if_opackets += sent;
864         ifp->if_collisions += scp->tx_collisions;
865
866         /*
867          * Collision stats are a PITA.  If multiples frames have been sent, we 
868          * distribute any outstanding collision count equally amongst them.
869          * However, if we're missing interrupts we're quite likely to also
870          * miss some collisions; thus the total count will be off anyway.
871          * Likewise, if we miss a frame dropped due to excessive collisions
872          * any outstanding collisions count will be held against the next
873          * frame to be successfully sent.  Hopefully it averages out in the
874          * end!
875          * XXX - This will screw up if tx_collisions/sent > 14. FIX IT!
876          */
877         switch (scp->tx_collisions) {
878          case 0:
879           break;
880          case 1:
881           scp->mibdata.dot3StatsSingleCollisionFrames++;
882           scp->mibdata.dot3StatsCollFrequencies[0]++;
883           break;
884          default:
885           if (sent == 1) {
886             scp->mibdata.dot3StatsMultipleCollisionFrames++;
887             scp->mibdata.dot3StatsCollFrequencies[scp->tx_collisions-1]++;
888           }
889           else {                /* Distribute across multiple frames */
890             scp->mibdata.dot3StatsMultipleCollisionFrames += sent;
891             scp->mibdata.
892               dot3StatsCollFrequencies[scp->tx_collisions/sent] += sent - scp->tx_collisions%sent;
893             scp->mibdata.
894               dot3StatsCollFrequencies[scp->tx_collisions/sent + 1] += scp->tx_collisions%sent;
895           }
896         }
897         scp->tx_collisions = 0;
898       }
899       ifp->if_timer = 0;
900       ifp->if_flags &= ~IFF_OACTIVE;
901     }
902     if (txs & 0x0002) {         /* Excessive collisions (packet dropped) */
903       ifp->if_collisions += 16;
904       ifp->if_oerrors++;
905       scp->tx_collisions = 0;
906       scp->mibdata.dot3StatsExcessiveCollisions++;
907       scp->mibdata.dot3StatsMultipleCollisionFrames++;
908       scp->mibdata.dot3StatsCollFrequencies[15]++;
909       XE_OUTB(XE_CR, XE_CR_RESTART_TX);
910     }
911     if (txs & 0x0040)           /* Transmit aborted -- probably collisions */
912       scp->tx_collisions++;
913
914
915     /*
916      * Handle receive interrupts 
917      */
918     while ((esr = XE_INB(XE_ESR)) & XE_ESR_FULL_PACKET_RX) {
919
920       if ((rsr = XE_INB(XE_RSR)) & XE_RSR_RX_OK) {
921         struct ether_header *ehp;
922         struct mbuf *mbp;
923         u_int16_t len;
924
925         len = XE_INW(XE_RBC);
926
927         if (len == 0)
928           continue;
929
930 #if 0
931         /*
932          * Limit the amount of time we spend in this loop, dropping packets if 
933          * necessary.  The Linux code does this with considerably more
934          * finesse, adjusting the threshold dynamically.
935          */
936         if ((rx_bytes += len) > 22000) {
937           ifp->if_iqdrops++;
938           scp->mibData.dot3StatsMissedFrames++;
939           XE_OUTW(XE_DO, 0x8000);
940           continue;
941         }
942 #endif
943
944         if (len & 0x01)
945           len++;
946
947         MGETHDR(mbp, M_DONTWAIT, MT_DATA);      /* Allocate a header mbuf */
948         if (mbp != NULL) {
949           mbp->m_pkthdr.rcvif = ifp;
950           mbp->m_pkthdr.len = mbp->m_len = len;
951
952           /*
953            * If the mbuf header isn't big enough for the packet, attach an
954            * mbuf cluster to hold it.  The +2 is to allow for the nasty little 
955            * alignment hack below.
956            */
957           if (len + 2 > MHLEN) {
958             MCLGET(mbp, M_DONTWAIT);
959             if ((mbp->m_flags & M_EXT) == 0) {
960               m_freem(mbp);
961               mbp = NULL;
962             }
963           }
964         }
965
966         if (mbp != NULL) {
967           /*
968            * The Ethernet header is 14 bytes long; thus the actual packet data 
969            * won't be 32-bit aligned when it's dumped into the mbuf.  We
970            * offset everything by 2 bytes to fix this.  Apparently the
971            * alignment is important for NFS, damn its eyes.
972            */
973           mbp->m_data += 2;
974           ehp = mtod(mbp, struct ether_header *);
975
976           /*
977            * Now get the packet, including the Ethernet header and trailer (?)
978            * We use programmed I/O, because we don't know how to do shared
979            * memory with these cards.  So yes, it's real slow, and heavy on
980            * the interrupts (CPU on my P150 maxed out at ~950KBps incoming).
981            */
982           if (scp->srev == 0) {         /* Workaround a bug in old cards */
983             u_short rhs;
984
985             XE_SELECT_PAGE(5);
986             rhs = XE_INW(XE_RHSA);
987             XE_SELECT_PAGE(0);
988
989             rhs += 3;                    /* Skip control info */
990
991             if (rhs >= 0x8000)
992               rhs = 0;
993
994             if (rhs + len > 0x8000) {
995               int i;
996
997               /*
998                * XXX - This i-- seems very wrong, but it's what the Linux guys 
999                * XXX - do.  Need someone with an old CE2 to test this for me.
1000                * XXX - 99/3/28: Changed the first i-- to an i++, maybe that'll
1001                * XXX - fix it?  It seems as though the previous version would
1002                * XXX - have caused an infinite loop (what, another one?).
1003                */
1004               for (i = 0; i < len; i++, rhs++) {
1005                 ((char *)ehp)[i] = XE_INB(XE_EDP);
1006                 if (rhs == 0x8000) {
1007                   rhs = 0;
1008                   i--;
1009                 }
1010               }
1011             }
1012             else
1013               bus_space_read_multi_2(scp->bst, scp->bsh, XE_EDP, 
1014                (u_int16_t *) ehp, len >> 1);
1015           }
1016           else
1017             bus_space_read_multi_2(scp->bst, scp->bsh, XE_EDP, 
1018              (u_int16_t *) ehp, len >> 1);
1019
1020           /* Deliver packet to upper layers */
1021           if (mbp != NULL) {
1022             mbp->m_pkthdr.len = mbp->m_len = len - ETHER_HDR_LEN;
1023             mbp->m_data += ETHER_HDR_LEN;       /* Strip off Ethernet header */
1024             ether_input(ifp, ehp, mbp);         /* Send the packet on its way */
1025             ifp->if_ipackets++;                 /* Success! */
1026           }
1027           XE_OUTW(XE_DO, 0x8000);               /* skip_rx_packet command */
1028         }
1029       }
1030       else if (rsr & XE_RSR_LONG_PACKET) {      /* Packet length >1518 bytes */
1031         scp->mibdata.dot3StatsFrameTooLongs++;
1032         ifp->if_ierrors++;
1033       }
1034       else if (rsr & XE_RSR_CRC_ERROR) {        /* Bad checksum on packet */
1035         scp->mibdata.dot3StatsFCSErrors++;
1036         ifp->if_ierrors++;
1037       }
1038       else if (rsr & XE_RSR_ALIGN_ERROR) {      /* Packet alignment error */
1039         scp->mibdata.dot3StatsAlignmentErrors++;
1040         ifp->if_ierrors++;
1041       }
1042     }
1043     if (rxs & 0x10) {                           /* Receiver overrun */
1044       scp->mibdata.dot3StatsInternalMacReceiveErrors++;
1045       ifp->if_ierrors++;
1046       XE_OUTB(XE_CR, XE_CR_CLEAR_OVERRUN);
1047     }
1048   }
1049
1050   XE_SELECT_PAGE(psr);                          /* Restore saved page */
1051   XE_OUTB(XE_CR, XE_CR_ENABLE_INTR);            /* Re-enable interrupts */
1052
1053   /* Could force an int here, instead of dropping packets? */
1054   /* XE_OUTB(XE_CR, XE_CR_ENABLE_INTR|XE_CE_FORCE_INTR); */
1055
1056   return;
1057 }
1058
1059
1060 /*
1061  * Device timeout/watchdog routine.  Called automatically if we queue a packet 
1062  * for transmission but don't get an interrupt within a specified timeout
1063  * (usually 5 seconds).  When this happens we assume the worst and reset the
1064  * card.
1065  */
1066 static void
1067 xe_watchdog(struct ifnet *ifp) {
1068   struct xe_softc *scp = ifp->if_softc;
1069
1070   device_printf(scp->dev, "watchdog timeout; resetting card\n");
1071   scp->tx_timeouts++;
1072   ifp->if_oerrors += scp->tx_queued;
1073   xe_stop(scp);
1074   xe_hard_reset(scp);
1075   xe_setmedia(scp);
1076   xe_init(scp);
1077 }
1078
1079
1080 /*
1081  * Change media selection.
1082  */
1083 static int
1084 xe_media_change(struct ifnet *ifp) {
1085   struct xe_softc *scp = ifp->if_softc;
1086
1087 #ifdef XE_DEBUG
1088   printf("xe%d: media_change\n", ifp->if_unit);
1089 #endif
1090
1091   if (IFM_TYPE(scp->ifm->ifm_media) != IFM_ETHER)
1092     return(EINVAL);
1093
1094   /*
1095    * Some card/media combos aren't always possible -- filter those out here.
1096    */
1097   if ((IFM_SUBTYPE(scp->ifm->ifm_media) == IFM_AUTO ||
1098        IFM_SUBTYPE(scp->ifm->ifm_media) == IFM_100_TX) && !scp->phy_ok)
1099     return (EINVAL);
1100
1101   xe_setmedia(scp);
1102
1103   return 0;
1104 }
1105
1106
1107 /*
1108  * Return current media selection.
1109  */
1110 static void
1111 xe_media_status(struct ifnet *ifp, struct ifmediareq *mrp) {
1112
1113 #ifdef XE_DEBUG
1114   printf("xe%d: media_status\n", ifp->if_unit);
1115 #endif
1116
1117   mrp->ifm_active = ((struct xe_softc *)ifp->if_softc)->media;
1118
1119   return;
1120 }
1121
1122
1123 /*
1124  * Select active media.
1125  */
1126 static void xe_setmedia(void *xscp) {
1127   struct xe_softc *scp = xscp;
1128   u_int16_t bmcr, bmsr, anar, lpar;
1129
1130 #ifdef XE_DEBUG
1131   device_printf(scp->dev, "setmedia\n");
1132 #endif
1133
1134   /* Cancel any pending timeout */
1135   untimeout(xe_setmedia, scp, scp->chand);
1136   xe_disable_intr(scp);
1137
1138   /* Select media */
1139   scp->media = IFM_ETHER;
1140   switch (IFM_SUBTYPE(scp->ifm->ifm_media)) {
1141
1142    case IFM_AUTO:       /* Autoselect media */
1143     scp->media = IFM_ETHER|IFM_AUTO;
1144
1145     /*
1146      * Autoselection is really awful.  It goes something like this:
1147      *
1148      * Wait until the transmitter goes idle (2sec timeout).
1149      * Reset card
1150      *   IF a 100Mbit PHY exists
1151      *     Start NWAY autonegotiation (3.5sec timeout)
1152      *     IF that succeeds
1153      *       Select 100baseTX or 10baseT, whichever was detected
1154      *     ELSE
1155      *       Reset card
1156      *       IF a 100Mbit PHY exists
1157      *         Try to force a 100baseTX link (3sec timeout)
1158      *         IF that succeeds
1159      *           Select 100baseTX
1160      *         ELSE
1161      *           Disable the PHY
1162      *         ENDIF
1163      *       ENDIF
1164      *     ENDIF
1165      *   ENDIF
1166      * IF nothing selected so far
1167      *   IF a 100Mbit PHY exists
1168      *     Select 10baseT
1169      *   ELSE
1170      *     Select 10baseT or 10base2, whichever is connected
1171      *   ENDIF
1172      * ENDIF
1173      */
1174     switch (scp->autoneg_status) {
1175
1176      case XE_AUTONEG_NONE:
1177 #if XE_DEBUG > 1
1178       device_printf(scp->dev, "Waiting for idle transmitter\n");
1179 #endif
1180       scp->arpcom.ac_if.if_flags |= IFF_OACTIVE;
1181       scp->autoneg_status = XE_AUTONEG_WAITING;
1182       scp->chand = timeout(xe_setmedia, scp, hz * 2);
1183       return;
1184
1185      case XE_AUTONEG_WAITING:
1186       xe_soft_reset(scp);
1187       if (scp->phy_ok) {
1188 #if XE_DEBUG > 1
1189         device_printf(scp->dev, "Starting autonegotiation\n");
1190 #endif
1191         bmcr = xe_phy_readreg(scp, PHY_BMCR);
1192         bmcr &= ~(PHY_BMCR_AUTONEGENBL);
1193         xe_phy_writereg(scp, PHY_BMCR, bmcr);
1194         anar = xe_phy_readreg(scp, PHY_ANAR);
1195         anar &= ~(PHY_ANAR_100BT4|PHY_ANAR_100BTXFULL|PHY_ANAR_10BTFULL);
1196         anar |= PHY_ANAR_100BTXHALF|PHY_ANAR_10BTHALF;
1197         xe_phy_writereg(scp, PHY_ANAR, anar);
1198         bmcr |= PHY_BMCR_AUTONEGENBL|PHY_BMCR_AUTONEGRSTR;
1199         xe_phy_writereg(scp, PHY_BMCR, bmcr);
1200         scp->autoneg_status = XE_AUTONEG_STARTED;
1201         scp->chand = timeout(xe_setmedia, scp, hz * 7/2);
1202         return;
1203       }
1204       else {
1205         scp->autoneg_status = XE_AUTONEG_FAIL;
1206       }
1207       break;
1208
1209      case XE_AUTONEG_STARTED:
1210       bmsr = xe_phy_readreg(scp, PHY_BMSR);
1211       lpar = xe_phy_readreg(scp, PHY_LPAR);
1212       if (bmsr & (PHY_BMSR_AUTONEGCOMP|PHY_BMSR_LINKSTAT)) {
1213 #if XE_DEBUG > 1
1214         device_printf(scp->dev, "Autonegotiation complete!\n");
1215 #endif
1216         /*
1217          * XXX - Shouldn't have to do this, but (on my hub at least) the
1218          * XXX - transmitter won't work after a successful autoneg.  So we see 
1219          * XXX - what the negotiation result was and force that mode.  I'm
1220          * XXX - sure there is an easy fix for this.
1221          */
1222         if (lpar & PHY_LPAR_100BTXHALF) {
1223           xe_phy_writereg(scp, PHY_BMCR, PHY_BMCR_SPEEDSEL);
1224           XE_MII_DUMP(scp);
1225           XE_SELECT_PAGE(2);
1226           XE_OUTB(XE_MSR, XE_INB(XE_MSR) | 0x08);
1227           scp->media = IFM_ETHER|IFM_100_TX;
1228           scp->autoneg_status = XE_AUTONEG_NONE;
1229         }
1230         else {
1231           /*
1232            * XXX - Bit of a hack going on in here.
1233            * XXX - This is derived from Ken Hughes patch to the Linux driver
1234            * XXX - to make it work with 10Mbit _autonegotiated_ links on CE3B
1235            * XXX - cards.  What's a CE3B and how's it differ from a plain CE3?
1236            * XXX - these are the things we need to find out.
1237            */
1238           xe_phy_writereg(scp, PHY_BMCR, 0x0000);
1239           XE_SELECT_PAGE(2);
1240           /* BEGIN HACK */
1241           XE_OUTB(XE_MSR, XE_INB(XE_MSR) | 0x08);
1242           XE_SELECT_PAGE(0x42);
1243           XE_OUTB(XE_SWC1, 0x80);
1244           scp->media = IFM_ETHER|IFM_10_T;
1245           scp->autoneg_status = XE_AUTONEG_NONE;
1246           /* END HACK */
1247           /*XE_OUTB(XE_MSR, XE_INB(XE_MSR) & ~0x08);*/  /* Disable PHY? */
1248           /*scp->autoneg_status = XE_AUTONEG_FAIL;*/
1249         }
1250       }
1251       else {
1252 #if XE_DEBUG > 1
1253         device_printf(scp->dev, "Autonegotiation failed; trying 100baseTX\n");
1254 #endif
1255         XE_MII_DUMP(scp);
1256         xe_soft_reset(scp);
1257         if (scp->phy_ok) {
1258           xe_phy_writereg(scp, PHY_BMCR, PHY_BMCR_SPEEDSEL);
1259           scp->autoneg_status = XE_AUTONEG_100TX;
1260           scp->chand = timeout(xe_setmedia, scp, hz * 3);
1261           return;
1262         }
1263         else {
1264           scp->autoneg_status = XE_AUTONEG_FAIL;
1265         }
1266       }
1267       break;
1268
1269      case XE_AUTONEG_100TX:
1270       (void)xe_phy_readreg(scp, PHY_BMSR);
1271       bmsr = xe_phy_readreg(scp, PHY_BMSR);
1272       if (bmsr & PHY_BMSR_LINKSTAT) {
1273 #if XE_DEBUG > 1
1274         device_printf(scp->dev, "Got 100baseTX link!\n");
1275 #endif
1276         XE_MII_DUMP(scp);
1277         XE_SELECT_PAGE(2);
1278         XE_OUTB(XE_MSR, XE_INB(XE_MSR) | 0x08);
1279         scp->media = IFM_ETHER|IFM_100_TX;
1280         scp->autoneg_status = XE_AUTONEG_NONE;
1281       }
1282       else {
1283 #if XE_DEBUG > 1
1284         device_printf(scp->dev, "Autonegotiation failed; disabling PHY\n");
1285 #endif
1286         XE_MII_DUMP(scp);
1287         xe_phy_writereg(scp, PHY_BMCR, 0x0000);
1288         XE_SELECT_PAGE(2);
1289         XE_OUTB(XE_MSR, XE_INB(XE_MSR) & ~0x08);        /* Disable PHY? */
1290         scp->autoneg_status = XE_AUTONEG_FAIL;
1291       }
1292       break;
1293     }
1294
1295     /*
1296      * If we got down here _and_ autoneg_status is XE_AUTONEG_FAIL, then
1297      * either autonegotiation failed, or never got started to begin with.  In
1298      * either case, select a suitable 10Mbit media and hope it works.  We
1299      * don't need to reset the card again, since it will have been done
1300      * already by the big switch above.
1301      */
1302     if (scp->autoneg_status == XE_AUTONEG_FAIL) {
1303 #if XE_DEBUG > 1
1304       device_printf(scp->dev, "Selecting 10baseX\n");
1305 #endif
1306       if (scp->mohawk) {
1307         XE_SELECT_PAGE(0x42);
1308         XE_OUTB(XE_SWC1, 0x80);
1309         scp->media = IFM_ETHER|IFM_10_T;
1310         scp->autoneg_status = XE_AUTONEG_NONE;
1311       }
1312       else {
1313         XE_SELECT_PAGE(4);
1314         XE_OUTB(XE_GPR0, 4);
1315         DELAY(50000);
1316         XE_SELECT_PAGE(0x42);
1317         XE_OUTB(XE_SWC1, (XE_INB(XE_ESR) & XE_ESR_MEDIA_SELECT) ? 0x80 : 0xc0);
1318         scp->media = IFM_ETHER|((XE_INB(XE_ESR) & XE_ESR_MEDIA_SELECT) ? IFM_10_T : IFM_10_2);
1319         scp->autoneg_status = XE_AUTONEG_NONE;
1320       }
1321     }
1322     break;
1323
1324
1325     /*
1326      * If a specific media has been requested, we just reset the card and
1327      * select it (one small exception -- if 100baseTX is requested by there is 
1328      * no PHY, we fall back to 10baseT operation).
1329      */
1330    case IFM_100_TX:     /* Force 100baseTX */
1331     xe_soft_reset(scp);
1332     if (scp->phy_ok) {
1333 #if XE_DEBUG > 1
1334       device_printf(scp->dev, "Selecting 100baseTX\n");
1335 #endif
1336       XE_SELECT_PAGE(0x42);
1337       XE_OUTB(XE_SWC1, 0);
1338       xe_phy_writereg(scp, PHY_BMCR, PHY_BMCR_SPEEDSEL);
1339       XE_SELECT_PAGE(2);
1340       XE_OUTB(XE_MSR, XE_INB(XE_MSR) | 0x08);
1341       scp->media |= IFM_100_TX;
1342       break;
1343     }
1344     /* FALLTHROUGH */
1345
1346    case IFM_10_T:       /* Force 10baseT */
1347     xe_soft_reset(scp);
1348 #if XE_DEBUG > 1
1349     device_printf(scp->dev, "Selecting 10baseT\n");
1350 #endif
1351     if (scp->phy_ok) {
1352       xe_phy_writereg(scp, PHY_BMCR, 0x0000);
1353       XE_SELECT_PAGE(2);
1354       XE_OUTB(XE_MSR, XE_INB(XE_MSR) & ~0x08);  /* Disable PHY */
1355     }
1356     XE_SELECT_PAGE(0x42);
1357     XE_OUTB(XE_SWC1, 0x80);
1358     scp->media |= IFM_10_T;
1359     break;
1360
1361    case IFM_10_2:
1362     xe_soft_reset(scp);
1363 #if XE_DEBUG > 1
1364     device_printf(scp->dev, "Selecting 10base2\n");
1365 #endif
1366     XE_SELECT_PAGE(0x42);
1367     XE_OUTB(XE_SWC1, 0xc0);
1368     scp->media |= IFM_10_2;
1369     break;
1370   }
1371
1372
1373   /*
1374    * Finally, the LEDs are set to match whatever media was chosen and the
1375    * transmitter is unblocked. 
1376    */
1377 #if XE_DEBUG > 1
1378   device_printf(scp->dev, "Setting LEDs\n");
1379 #endif
1380   XE_SELECT_PAGE(2);
1381   switch (IFM_SUBTYPE(scp->media)) {
1382    case IFM_100_TX:
1383    case IFM_10_T:
1384     XE_OUTB(XE_LED, 0x3b);
1385     if (scp->dingo)
1386       XE_OUTB(0x0b, 0x04);      /* 100Mbit LED */
1387     break;
1388
1389    case IFM_10_2:
1390     XE_OUTB(XE_LED, 0x3a);
1391     break;
1392   }
1393
1394   /* Restart output? */
1395   scp->ifp->if_flags &= ~IFF_OACTIVE;
1396   xe_init(scp);
1397 }
1398
1399
1400 /*
1401  * Hard reset (power cycle) the card.
1402  */
1403 static void
1404 xe_hard_reset(struct xe_softc *scp) {
1405   int s;
1406
1407 #ifdef XE_DEBUG
1408   device_printf(scp->dev, "hard_reset\n");
1409 #endif
1410
1411   s = splimp();
1412
1413   /*
1414    * Power cycle the card.
1415    */
1416   XE_SELECT_PAGE(4);
1417   XE_OUTB(XE_GPR1, 0);          /* Power off */
1418   DELAY(40000);
1419
1420   if (scp->mohawk)
1421     XE_OUTB(XE_GPR1, 1);        /* And back on again */
1422   else
1423     XE_OUTB(XE_GPR1, 5);        /* Also set AIC bit, whatever that is */
1424   DELAY(40000);
1425   XE_SELECT_PAGE(0);
1426
1427   (void)splx(s);
1428 }
1429
1430
1431 /*
1432  * Soft reset the card.  Also makes sure that the ML6692 and 10Mbit controller 
1433  * are powered up, sets the silicon revision number in softc, disables
1434  * interrupts and checks for the prescence of a 100Mbit PHY.  This should
1435  * leave us in a position where we can access the PHY and do media
1436  * selection. The function imposes a 0.5s delay while the hardware powers up.
1437  */
1438 static void
1439 xe_soft_reset(struct xe_softc *scp) {
1440   int s;
1441
1442 #ifdef XE_DEBUG
1443   device_printf(scp->dev, "soft_reset\n");
1444 #endif
1445
1446   s = splimp();
1447
1448   /*
1449    * Reset the card, (again).
1450    */
1451   XE_SELECT_PAGE(0);
1452   XE_OUTB(XE_CR, XE_CR_SOFT_RESET);
1453   DELAY(40000);
1454   XE_OUTB(XE_CR, 0);
1455   DELAY(40000);
1456
1457   if (scp->mohawk) {
1458     /*
1459      * set GP1 and GP2 as outputs (bits 2 & 3)
1460      * set GP1 low to power on the ML6692 (bit 0)
1461      * set GP2 high to power on the 10Mhz chip (bit 1)
1462      */
1463     XE_SELECT_PAGE(4);
1464     XE_OUTB(XE_GPR0, 0x0e);
1465   }
1466
1467   /*
1468    * Wait for everything to wake up.
1469    */
1470   DELAY(500000);
1471
1472   /*
1473    * Get silicon revision number.
1474    */
1475   XE_SELECT_PAGE(4);
1476   if (scp->mohawk)
1477     scp->srev = (XE_INB(XE_BOV) & 0x70) >> 4;
1478   else
1479     scp->srev = (XE_INB(XE_BOV) & 0x30) >> 4;
1480 #ifdef XE_DEBUG
1481   device_printf(scp->dev, "silicon revision = %d\n", scp->srev);
1482 #endif
1483   
1484   /*
1485    * Shut off interrupts.
1486    */
1487   xe_disable_intr(scp);
1488
1489   /*
1490    * Check for PHY.
1491    */
1492   if (scp->mohawk) {
1493     scp->phy_ok = xe_mii_init(scp);
1494   }
1495
1496   XE_SELECT_PAGE(0);
1497
1498   (void)splx(s);
1499 }
1500
1501
1502 /*
1503  * Take interface offline.  This is done by powering down the device, which I
1504  * assume means just shutting down the transceiver and Ethernet logic.  This
1505  * requires a _hard_ reset to recover from, as we need to power up again.
1506  */
1507 static void
1508 xe_stop(struct xe_softc *scp) {
1509   int s;
1510
1511 #ifdef XE_DEBUG
1512   device_printf(scp->dev, "stop\n");
1513 #endif
1514
1515   s = splimp();
1516
1517   /*
1518    * Shut off interrupts.
1519    */
1520   xe_disable_intr(scp);
1521
1522   /*
1523    * Power down.
1524    */
1525   XE_SELECT_PAGE(4);
1526   XE_OUTB(XE_GPR1, 0);
1527   XE_SELECT_PAGE(0);
1528
1529   /*
1530    * ~IFF_RUNNING == interface down.
1531    */
1532   scp->ifp->if_flags &= ~IFF_RUNNING;
1533   scp->ifp->if_flags &= ~IFF_OACTIVE;
1534   scp->ifp->if_timer = 0;
1535
1536   (void)splx(s);
1537 }
1538
1539
1540 /*
1541  * Enable Ethernet interrupts from the card.
1542  */
1543 static void
1544 xe_enable_intr(struct xe_softc *scp) {
1545 #ifdef XE_DEBUG
1546   device_printf(scp->dev, "enable_intr\n");
1547 #endif
1548
1549   XE_SELECT_PAGE(1);
1550   XE_OUTB(XE_IMR0, 0xff);               /* Unmask everything */
1551   XE_OUTB(XE_IMR1, 0x01);               /* Unmask TX underrun detection */
1552   DELAY(1);
1553
1554   XE_SELECT_PAGE(0);
1555   XE_OUTB(XE_CR, XE_CR_ENABLE_INTR);    /* Enable interrupts */
1556   if (scp->modem && !scp->dingo) {      /* This bit is just magic */
1557     if (!(XE_INB(0x10) & 0x01)) {
1558       XE_OUTB(0x10, 0x11);              /* Unmask master int enable bit */
1559     }
1560   }
1561 }
1562
1563
1564 /*
1565  * Disable all Ethernet interrupts from the card.
1566  */
1567 static void
1568 xe_disable_intr(struct xe_softc *scp) {
1569 #ifdef XE_DEBUG
1570   device_printf(scp->dev, "disable_intr\n");
1571 #endif
1572
1573   XE_SELECT_PAGE(0);
1574   XE_OUTB(XE_CR, 0);                    /* Disable interrupts */
1575   if (scp->modem && !scp->dingo) {      /* More magic (does this work?) */
1576     XE_OUTB(0x10, 0x10);                /* Mask the master int enable bit */
1577   }
1578
1579   XE_SELECT_PAGE(1);
1580   XE_OUTB(XE_IMR0, 0);                  /* Forbid all interrupts */
1581   XE_OUTB(XE_IMR1, 0);
1582   XE_SELECT_PAGE(0);
1583 }
1584
1585
1586 /*
1587  * Set up multicast filter and promiscuous mode
1588  */
1589 static void
1590 xe_setmulti(struct xe_softc *scp) {
1591   struct ifnet *ifp;
1592   struct ifmultiaddr *maddr;
1593   int count;
1594
1595   ifp = &scp->arpcom.ac_if;
1596   maddr = ifp->if_multiaddrs.lh_first;
1597
1598   /* Get length of multicast list */
1599   for (count = 0; maddr != NULL; maddr = maddr->ifma_link.le_next, count++);
1600
1601   if ((ifp->if_flags & IFF_PROMISC) || (ifp->if_flags & IFF_ALLMULTI) || (count > 9)) {
1602     /*
1603      * Go into promiscuous mode if either of the PROMISC or ALLMULTI flags are
1604      * set, or if we have been asked to deal with more than 9 multicast
1605      * addresses.  To do this: set MPE and PME in SWC1
1606      */
1607     XE_SELECT_PAGE(0x42);
1608     XE_OUTB(XE_SWC1, 0x06);
1609   }
1610   else if ((ifp->if_flags & IFF_MULTICAST) && (count > 0)) {
1611     /*
1612      * Program the filters for up to 9 addresses
1613      */
1614     XE_SELECT_PAGE(0x42);
1615     XE_OUTB(XE_SWC1, 0x01);
1616     XE_SELECT_PAGE(0x40);
1617     XE_OUTB(XE_CMD0, XE_CMD0_OFFLINE);
1618     /*xe_reg_dump(scp);*/
1619     xe_setaddrs(scp);
1620     /*xe_reg_dump(scp);*/
1621     XE_SELECT_PAGE(0x40);
1622     XE_OUTB(XE_CMD0, XE_CMD0_RX_ENABLE|XE_CMD0_ONLINE);
1623   }
1624   else {
1625     /*
1626      * No multicast operation (default)
1627      */
1628     XE_SELECT_PAGE(0x42);
1629     XE_OUTB(XE_SWC1, 0);
1630   }
1631   XE_SELECT_PAGE(0);
1632 }
1633
1634
1635 /*
1636  * Set up all on-chip addresses (for multicast).  AFAICS, there are 10
1637  * of these things; the first is our MAC address, the other 9 are mcast
1638  * addresses, padded with the MAC address if there aren't enough.
1639  * XXX - This doesn't work right, but I'm not sure why yet.  We seem to be
1640  * XXX - doing much the same as the Linux code, which is weird enough that
1641  * XXX - it's probably right (despite my earlier comments to the contrary).
1642  */
1643 static void
1644 xe_setaddrs(struct xe_softc *scp) {
1645   struct ifmultiaddr *maddr;
1646   u_int8_t *addr;
1647   u_int8_t page, slot, byte, i;
1648
1649   maddr = scp->arpcom.ac_if.if_multiaddrs.lh_first;
1650
1651   XE_SELECT_PAGE(page = 0x50);
1652
1653   for (slot = 0, byte = 8; slot < 10; slot++) {
1654
1655     if (slot == 0)
1656       addr = (u_int8_t *)(&scp->arpcom.ac_enaddr);
1657     else {
1658       while (maddr != NULL && maddr->ifma_addr->sa_family != AF_LINK)
1659         maddr = maddr->ifma_link.le_next;
1660       if (maddr != NULL)
1661         addr = LLADDR((struct sockaddr_dl *)maddr->ifma_addr);
1662       else
1663         addr = (u_int8_t *)(&scp->arpcom.ac_enaddr);
1664     }
1665
1666     for (i = 0; i < 6; i++, byte++) {
1667 #if XE_DEBUG > 2
1668       if (i)
1669         printf(":%x", addr[i]);
1670       else
1671         device_printf(scp->dev, "individual addresses %d: %x", slot, addr[0]);
1672 #endif
1673
1674       if (byte > 15) {
1675         page++;
1676         byte = 8;
1677         XE_SELECT_PAGE(page);
1678       }
1679
1680       if (scp->mohawk)
1681         XE_OUTB(byte, addr[5 - i]);
1682       else
1683         XE_OUTB(byte, addr[i]);
1684     }
1685 #if XE_DEBUG > 2
1686     printf("\n");
1687 #endif
1688   }
1689
1690   XE_SELECT_PAGE(0);
1691 }
1692
1693
1694 /*
1695  * Write an outgoing packet to the card using programmed I/O.
1696  */
1697 static int
1698 xe_pio_write_packet(struct xe_softc *scp, struct mbuf *mbp) {
1699   struct mbuf *mbp2;
1700   u_int16_t len, pad, free, ok;
1701   u_int8_t *data;
1702   u_int8_t savebyte[2], wantbyte;
1703
1704   /* Get total packet length */
1705   for (len = 0, mbp2 = mbp; mbp2 != NULL; len += mbp2->m_len, mbp2 = mbp2->m_next);
1706
1707   /* Packets < minimum length may need to be padded out */
1708   pad = 0;
1709   if (len < ETHER_MIN_LEN - ETHER_CRC_LEN) {
1710     pad = (ETHER_MIN_LEN - ETHER_CRC_LEN - len + 1) >> 1;
1711     len = ETHER_MIN_LEN - ETHER_CRC_LEN;
1712   }
1713
1714   /* Check transmit buffer space */
1715   XE_SELECT_PAGE(0);
1716   XE_OUTW(XE_TRS, len+2);
1717   free = XE_INW(XE_TSO);
1718   ok = free & 0x8000;
1719   free &= 0x7fff;
1720   if (free <= len + 2)
1721     return 1;
1722
1723   /* Send packet length to card */
1724   XE_OUTW(XE_EDP, len);
1725
1726   /*
1727    * Write packet to card using PIO (code stolen from the ed driver)
1728    */
1729   wantbyte = 0;
1730   while (mbp != NULL) {
1731     len = mbp->m_len;
1732     if (len > 0) {
1733       data = mtod(mbp, caddr_t);
1734       if (wantbyte) {           /* Finish the last word */
1735         savebyte[1] = *data;
1736         XE_OUTW(XE_EDP, *(u_short *)savebyte);
1737         data++;
1738         len--;
1739         wantbyte = 0;
1740       }
1741       if (len > 1) {            /* Output contiguous words */
1742         bus_space_write_multi_2(scp->bst, scp->bsh, XE_EDP, (u_int16_t *) data,
1743          len >> 1);
1744         data += len & ~1;
1745         len &= 1;
1746       }
1747       if (len == 1) {           /* Save last byte, if necessary */
1748         savebyte[0] = *data;
1749         wantbyte = 1;
1750       }
1751     }
1752     mbp = mbp->m_next;
1753   }
1754   if (wantbyte)                 /* Last byte for odd-length packets */
1755     XE_OUTW(XE_EDP, *(u_short *)savebyte);
1756
1757   /*
1758    * For CE3 cards, just tell 'em to send -- apparently the card will pad out
1759    * short packets with random cruft.  Otherwise, write nonsense words to fill 
1760    * out the packet.  I guess it is then sent automatically (?)
1761    */
1762   if (scp->mohawk)
1763     XE_OUTB(XE_CR, XE_CR_TX_PACKET|XE_CR_ENABLE_INTR);
1764   else
1765     while (pad > 0) {
1766       XE_OUTW(XE_EDP, 0xdead);
1767       pad--;
1768     }
1769
1770   return 0;
1771 }
1772
1773 /*
1774  * Compute the 32-bit Ethernet CRC for the given buffer.
1775  */
1776 static u_int32_t
1777 xe_compute_crc(u_int8_t *data, int len) {
1778   u_int32_t crc = 0xffffffff;
1779   u_int32_t poly = 0x04c11db6;
1780   u_int8_t current, crc31, bit;
1781   int i, k;
1782
1783   for (i = 0; i < len; i++) {
1784     current = data[i];
1785     for (k = 1; k <= 8; k++) {
1786       if (crc & 0x80000000) {
1787         crc31 = 0x01;
1788       }
1789       else {
1790         crc31 = 0;
1791       }
1792       bit = crc31 ^ (current & 0x01);
1793       crc <<= 1;
1794       current >>= 1;
1795       if (bit) {
1796         crc = (crc ^ poly)|1;
1797       }
1798     }
1799   }
1800   return crc;
1801 }
1802
1803
1804 /*
1805  * Convert a CRC into an index into the multicast hash table.  What we do is
1806  * take the most-significant 6 bits of the CRC, reverse them, and use that as
1807  * the bit number in the hash table.  Bits 5:3 of the result give the byte
1808  * within the table (0-7); bits 2:0 give the bit number within that byte (also 
1809  * 0-7), ie. the number of shifts needed to get it into the lsb position.
1810  */
1811 static int
1812 xe_compute_hashbit(u_int32_t crc) {
1813   u_int8_t hashbit = 0;
1814   int i;
1815
1816   for (i = 0; i < 6; i++) {
1817     hashbit >>= 1;
1818     if (crc & 0x80000000) {
1819       hashbit &= 0x80;
1820     }
1821     crc <<= 1;
1822   }
1823   return (hashbit >> 2);
1824 }
1825
1826
1827
1828 /**************************************************************
1829  *                                                            *
1830  *                  M I I  F U N C T I O N S                  *
1831  *                                                            *
1832  **************************************************************/
1833
1834 /*
1835  * Alternative MII/PHY handling code adapted from the xl driver.  It doesn't
1836  * seem to work any better than the xirc2_ps stuff, but it's cleaner code.
1837  * XXX - this stuff shouldn't be here.  It should all be abstracted off to
1838  * XXX - some kind of common MII-handling code, shared by all drivers.  But
1839  * XXX - that's a whole other mission.
1840  */
1841 #define XE_MII_SET(x)   XE_OUTB(XE_GPR2, (XE_INB(XE_GPR2) | 0x04) | (x))
1842 #define XE_MII_CLR(x)   XE_OUTB(XE_GPR2, (XE_INB(XE_GPR2) | 0x04) & ~(x))
1843
1844
1845 /*
1846  * Sync the PHYs by setting data bit and strobing the clock 32 times.
1847  */
1848 static void
1849 xe_mii_sync(struct xe_softc *scp) {
1850   register int i;
1851
1852   XE_SELECT_PAGE(2);
1853   XE_MII_SET(XE_MII_DIR|XE_MII_WRD);
1854
1855   for (i = 0; i < 32; i++) {
1856     XE_MII_SET(XE_MII_CLK);
1857     DELAY(1);
1858     XE_MII_CLR(XE_MII_CLK);
1859     DELAY(1);
1860   }
1861 }
1862
1863
1864 /*
1865  * Look for a MII-compliant PHY.  If we find one, reset it.
1866  */
1867 static int
1868 xe_mii_init(struct xe_softc *scp) {
1869   u_int16_t status;
1870
1871   status = xe_phy_readreg(scp, PHY_BMSR);
1872   if ((status & 0xff00) != 0x7800) {
1873 #if XE_DEBUG > 1
1874     device_printf(scp->dev, "no PHY found, %0x\n", status);
1875 #endif
1876     return 0;
1877   }
1878   else {
1879 #if XE_DEBUG > 1
1880     device_printf(scp->dev, "PHY OK!\n");
1881 #endif
1882
1883     /* Reset the PHY */
1884     xe_phy_writereg(scp, PHY_BMCR, PHY_BMCR_RESET);
1885     DELAY(500);
1886     while(xe_phy_readreg(scp, PHY_BMCR) & PHY_BMCR_RESET);
1887     XE_MII_DUMP(scp);
1888     return 1;
1889   }
1890 }
1891
1892
1893 /*
1894  * Clock a series of bits through the MII.
1895  */
1896 static void
1897 xe_mii_send(struct xe_softc *scp, u_int32_t bits, int cnt) {
1898   int i;
1899
1900   XE_SELECT_PAGE(2);
1901   XE_MII_CLR(XE_MII_CLK);
1902   
1903   for (i = (0x1 << (cnt - 1)); i; i >>= 1) {
1904     if (bits & i) {
1905       XE_MII_SET(XE_MII_WRD);
1906     } else {
1907       XE_MII_CLR(XE_MII_WRD);
1908     }
1909     DELAY(1);
1910     XE_MII_CLR(XE_MII_CLK);
1911     DELAY(1);
1912     XE_MII_SET(XE_MII_CLK);
1913   }
1914 }
1915
1916
1917 /*
1918  * Read an PHY register through the MII.
1919  */
1920 static int
1921 xe_mii_readreg(struct xe_softc *scp, struct xe_mii_frame *frame) {
1922   int i, ack, s;
1923
1924   s = splimp();
1925
1926   /*
1927    * Set up frame for RX.
1928    */
1929   frame->mii_stdelim = XE_MII_STARTDELIM;
1930   frame->mii_opcode = XE_MII_READOP;
1931   frame->mii_turnaround = 0;
1932   frame->mii_data = 0;
1933         
1934   XE_SELECT_PAGE(2);
1935   XE_OUTB(XE_GPR2, 0);
1936
1937   /*
1938    * Turn on data xmit.
1939    */
1940   XE_MII_SET(XE_MII_DIR);
1941
1942   xe_mii_sync(scp);
1943
1944   /*    
1945    * Send command/address info.
1946    */
1947   xe_mii_send(scp, frame->mii_stdelim, 2);
1948   xe_mii_send(scp, frame->mii_opcode, 2);
1949   xe_mii_send(scp, frame->mii_phyaddr, 5);
1950   xe_mii_send(scp, frame->mii_regaddr, 5);
1951
1952   /* Idle bit */
1953   XE_MII_CLR((XE_MII_CLK|XE_MII_WRD));
1954   DELAY(1);
1955   XE_MII_SET(XE_MII_CLK);
1956   DELAY(1);
1957
1958   /* Turn off xmit. */
1959   XE_MII_CLR(XE_MII_DIR);
1960
1961   /* Check for ack */
1962   XE_MII_CLR(XE_MII_CLK);
1963   DELAY(1);
1964   ack = XE_INB(XE_GPR2) & XE_MII_RDD;
1965   XE_MII_SET(XE_MII_CLK);
1966   DELAY(1);
1967
1968   /*
1969    * Now try reading data bits. If the ack failed, we still
1970    * need to clock through 16 cycles to keep the PHY(s) in sync.
1971    */
1972   if (ack) {
1973     for(i = 0; i < 16; i++) {
1974       XE_MII_CLR(XE_MII_CLK);
1975       DELAY(1);
1976       XE_MII_SET(XE_MII_CLK);
1977       DELAY(1);
1978     }
1979     goto fail;
1980   }
1981
1982   for (i = 0x8000; i; i >>= 1) {
1983     XE_MII_CLR(XE_MII_CLK);
1984     DELAY(1);
1985     if (!ack) {
1986       if (XE_INB(XE_GPR2) & XE_MII_RDD)
1987         frame->mii_data |= i;
1988       DELAY(1);
1989     }
1990     XE_MII_SET(XE_MII_CLK);
1991     DELAY(1);
1992   }
1993
1994 fail:
1995
1996   XE_MII_CLR(XE_MII_CLK);
1997   DELAY(1);
1998   XE_MII_SET(XE_MII_CLK);
1999   DELAY(1);
2000
2001   splx(s);
2002
2003   if (ack)
2004     return(1);
2005   return(0);
2006 }
2007
2008
2009 /*
2010  * Write to a PHY register through the MII.
2011  */
2012 static int
2013 xe_mii_writereg(struct xe_softc *scp, struct xe_mii_frame *frame) {
2014   int s;
2015
2016   s = splimp();
2017
2018   /*
2019    * Set up frame for TX.
2020    */
2021   frame->mii_stdelim = XE_MII_STARTDELIM;
2022   frame->mii_opcode = XE_MII_WRITEOP;
2023   frame->mii_turnaround = XE_MII_TURNAROUND;
2024         
2025   XE_SELECT_PAGE(2);
2026
2027   /*            
2028    * Turn on data output.
2029    */
2030   XE_MII_SET(XE_MII_DIR);
2031
2032   xe_mii_sync(scp);
2033
2034   xe_mii_send(scp, frame->mii_stdelim, 2);
2035   xe_mii_send(scp, frame->mii_opcode, 2);
2036   xe_mii_send(scp, frame->mii_phyaddr, 5);
2037   xe_mii_send(scp, frame->mii_regaddr, 5);
2038   xe_mii_send(scp, frame->mii_turnaround, 2);
2039   xe_mii_send(scp, frame->mii_data, 16);
2040
2041   /* Idle bit. */
2042   XE_MII_SET(XE_MII_CLK);
2043   DELAY(1);
2044   XE_MII_CLR(XE_MII_CLK);
2045   DELAY(1);
2046
2047   /*
2048    * Turn off xmit.
2049    */
2050   XE_MII_CLR(XE_MII_DIR);
2051
2052   splx(s);
2053
2054   return(0);
2055 }
2056
2057
2058 /*
2059  * Read a register from the PHY.
2060  */
2061 static u_int16_t
2062 xe_phy_readreg(struct xe_softc *scp, u_int16_t reg) {
2063   struct xe_mii_frame frame;
2064
2065   bzero((char *)&frame, sizeof(frame));
2066
2067   frame.mii_phyaddr = 0;
2068   frame.mii_regaddr = reg;
2069   xe_mii_readreg(scp, &frame);
2070
2071   return(frame.mii_data);
2072 }
2073
2074
2075 /*
2076  * Write to a PHY register.
2077  */
2078 static void
2079 xe_phy_writereg(struct xe_softc *scp, u_int16_t reg, u_int16_t data) {
2080   struct xe_mii_frame frame;
2081
2082   bzero((char *)&frame, sizeof(frame));
2083
2084   frame.mii_phyaddr = 0;
2085   frame.mii_regaddr = reg;
2086   frame.mii_data = data;
2087   xe_mii_writereg(scp, &frame);
2088
2089   return;
2090 }
2091
2092
2093 #ifdef XE_DEBUG
2094 /*
2095  * A bit of debugging code.
2096  */
2097 static void
2098 xe_mii_dump(struct xe_softc *scp) {
2099   int i, s;
2100
2101   s = splimp();
2102
2103   device_printf(scp->dev, "MII registers: ");
2104   for (i = 0; i < 2; i++) {
2105     printf(" %d:%04x", i, xe_phy_readreg(scp, i));
2106   }
2107   for (i = 4; i < 7; i++) {
2108     printf(" %d:%04x", i, xe_phy_readreg(scp, i));
2109   }
2110   printf("\n");
2111
2112   (void)splx(s);
2113 }
2114
2115 static void
2116 xe_reg_dump(struct xe_softc *scp) {
2117   int page, i, s;
2118
2119   s = splimp();
2120
2121   device_printf(scp->dev, "Common registers: ");
2122   for (i = 0; i < 8; i++) {
2123     printf(" %2.2x", XE_INB(i));
2124   }
2125   printf("\n");
2126
2127   for (page = 0; page <= 8; page++) {
2128     device_printf(scp->dev, "Register page %2.2x: ", page);
2129     XE_SELECT_PAGE(page);
2130     for (i = 8; i < 16; i++) {
2131       printf(" %2.2x", XE_INB(i));
2132     }
2133     printf("\n");
2134   }
2135
2136   for (page = 0x10; page < 0x5f; page++) {
2137     if ((page >= 0x11 && page <= 0x3f) ||
2138         (page == 0x41) ||
2139         (page >= 0x43 && page <= 0x4f) ||
2140         (page >= 0x59))
2141       continue;
2142     device_printf(scp->dev, "Register page %2.2x: ", page);
2143     XE_SELECT_PAGE(page);
2144     for (i = 8; i < 16; i++) {
2145       printf(" %2.2x", XE_INB(i));
2146     }
2147     printf("\n");
2148   }
2149
2150   (void)splx(s);
2151 }
2152 #endif
2153
2154 int
2155 xe_activate(device_t dev)
2156 {
2157         struct xe_softc *sc = device_get_softc(dev);
2158         int start, err;
2159
2160         if (!sc->dingo) {
2161                 sc->port_rid = 0;       /* 0 is managed by pccard */
2162                 sc->port_res = bus_alloc_resource(dev, SYS_RES_IOPORT,
2163                     &sc->port_rid, 0, ~0, 16, RF_ACTIVE);
2164         } else {
2165                 /*
2166                  * Find a 16 byte aligned ioport for the card.
2167                  */
2168 #if XE_DEBUG > 0
2169                 device_printf(dev, "Finding an aligned port for RealPort\n");
2170 #endif /* XE_DEBUG */
2171                 sc->port_rid = 1;       /* 0 is managed by pccard */
2172                 start = 0x100;
2173                 do {
2174                         sc->port_res = bus_alloc_resource(dev,
2175                             SYS_RES_IOPORT, &sc->port_rid, start, 0x3ff, 16,
2176                             RF_ACTIVE);
2177                         if (sc->port_res == 0)
2178                                 break;          /* we failed */
2179                         if ((rman_get_start(sc->port_res) & 0xf) == 0)
2180                                 break;          /* good */
2181                         bus_release_resource(dev, SYS_RES_IOPORT, sc->port_rid, 
2182                             sc->port_res);
2183                         start = (rman_get_start(sc->port_res) + 15) & ~0xf;
2184                 } while (1);
2185 #if XE_DEBUG > 2
2186                 device_printf(dev, "port 0x%0lx, size 0x%0lx\n",
2187                     bus_get_resource_start(dev, SYS_RES_IOPORT, sc->port_rid),
2188                     bus_get_resource_count(dev, SYS_RES_IOPORT, sc->port_rid));
2189 #endif /* XE_DEBUG */
2190         }
2191         if (!sc->port_res) {
2192 #if XE_DEBUG > 0
2193                 device_printf(dev, "Cannot allocate ioport\n");
2194 #endif          
2195                 return ENOMEM;
2196         }
2197
2198         sc->irq_rid = 0;
2199         sc->irq_res = bus_alloc_resource(dev, SYS_RES_IRQ, &sc->irq_rid, 
2200             0, ~0, 1, RF_ACTIVE);
2201         if (!sc->irq_res) {
2202 #if XE_DEBUG > 0
2203                 device_printf(dev, "Cannot allocate irq\n");
2204 #endif
2205                 xe_deactivate(dev);
2206                 return ENOMEM;
2207         }
2208         if ((err = bus_setup_intr(dev, sc->irq_res, INTR_TYPE_NET, xe_intr, sc,
2209             &sc->intrhand)) != 0) {
2210                 xe_deactivate(dev);
2211                 return err;
2212         }
2213
2214         sc->bst = rman_get_bustag(sc->port_res);
2215         sc->bsh = rman_get_bushandle(sc->port_res);
2216         return (0);
2217 }
2218
2219 void
2220 xe_deactivate(device_t dev)
2221 {
2222         struct xe_softc *sc = device_get_softc(dev);
2223         
2224         if (sc->intrhand)
2225                 bus_teardown_intr(dev, sc->irq_res, sc->intrhand);
2226         sc->intrhand = 0;
2227         if (sc->port_res)
2228                 bus_release_resource(dev, SYS_RES_IOPORT, sc->port_rid, 
2229                     sc->port_res);
2230         sc->port_res = 0;
2231         if (sc->irq_res)
2232                 bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, 
2233                     sc->irq_res);
2234         sc->irq_res = 0;
2235         return;
2236 }
2237
2238 static device_method_t xe_pccard_methods[] = {
2239         /* Device interface */
2240         DEVMETHOD(device_probe,         xe_probe),
2241         DEVMETHOD(device_attach,        xe_attach),
2242         DEVMETHOD(device_detach,        xe_detach),
2243
2244         { 0, 0 }
2245 };
2246
2247 static driver_t xe_pccard_driver = {
2248         "xe",
2249         xe_pccard_methods,
2250         sizeof(struct xe_softc),
2251 };
2252
2253 devclass_t xe_devclass;
2254
2255 DRIVER_MODULE(xe, pccard, xe_pccard_driver, xe_devclass, 0, 0);