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