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