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