Announce MAC address in ether_ifattach, not in each NIC indepently.
[dragonfly.git] / sys / dev / netif / nge / if_nge.c
1 /*
2  * Copyright (c) 2001 Wind River Systems
3  * Copyright (c) 1997, 1998, 1999, 2000, 2001
4  *      Bill Paul <wpaul@bsdi.com>.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *      This product includes software developed by Bill Paul.
17  * 4. Neither the name of the author nor the names of any co-contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31  * THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  * $FreeBSD: src/sys/dev/nge/if_nge.c,v 1.13.2.13 2003/02/05 22:03:57 mbr Exp $
34  * $DragonFly: src/sys/dev/netif/nge/if_nge.c,v 1.12 2004/07/02 17:42:18 joerg Exp $
35  *
36  * $FreeBSD: src/sys/dev/nge/if_nge.c,v 1.13.2.13 2003/02/05 22:03:57 mbr Exp $
37  */
38
39 /*
40  * National Semiconductor DP83820/DP83821 gigabit ethernet driver
41  * for FreeBSD. Datasheets are available from:
42  *
43  * http://www.national.com/ds/DP/DP83820.pdf
44  * http://www.national.com/ds/DP/DP83821.pdf
45  *
46  * These chips are used on several low cost gigabit ethernet NICs
47  * sold by D-Link, Addtron, SMC and Asante. Both parts are
48  * virtually the same, except the 83820 is a 64-bit/32-bit part,
49  * while the 83821 is 32-bit only.
50  *
51  * Many cards also use National gigE transceivers, such as the
52  * DP83891, DP83861 and DP83862 gigPHYTER parts. The DP83861 datasheet
53  * contains a full register description that applies to all of these
54  * components:
55  *
56  * http://www.national.com/ds/DP/DP83861.pdf
57  *
58  * Written by Bill Paul <wpaul@bsdi.com>
59  * BSDi Open Source Solutions
60  */
61
62 /*
63  * The NatSemi DP83820 and 83821 controllers are enhanced versions
64  * of the NatSemi MacPHYTER 10/100 devices. They support 10, 100
65  * and 1000Mbps speeds with 1000baseX (ten bit interface), MII and GMII
66  * ports. Other features include 8K TX FIFO and 32K RX FIFO, TCP/IP
67  * hardware checksum offload (IPv4 only), VLAN tagging and filtering,
68  * priority TX and RX queues, a 2048 bit multicast hash filter, 4 RX pattern
69  * matching buffers, one perfect address filter buffer and interrupt
70  * moderation. The 83820 supports both 64-bit and 32-bit addressing
71  * and data transfers: the 64-bit support can be toggled on or off
72  * via software. This affects the size of certain fields in the DMA
73  * descriptors.
74  *
75  * There are two bugs/misfeatures in the 83820/83821 that I have
76  * discovered so far:
77  *
78  * - Receive buffers must be aligned on 64-bit boundaries, which means
79  *   you must resort to copying data in order to fix up the payload
80  *   alignment.
81  *
82  * - In order to transmit jumbo frames larger than 8170 bytes, you have
83  *   to turn off transmit checksum offloading, because the chip can't
84  *   compute the checksum on an outgoing frame unless it fits entirely
85  *   within the TX FIFO, which is only 8192 bytes in size. If you have
86  *   TX checksum offload enabled and you transmit attempt to transmit a
87  *   frame larger than 8170 bytes, the transmitter will wedge.
88  *
89  * To work around the latter problem, TX checksum offload is disabled
90  * if the user selects an MTU larger than 8152 (8170 - 18).
91  */
92
93 #include <sys/param.h>
94 #include <sys/systm.h>
95 #include <sys/sockio.h>
96 #include <sys/mbuf.h>
97 #include <sys/malloc.h>
98 #include <sys/kernel.h>
99 #include <sys/socket.h>
100
101 #include <net/if.h>
102 #include <net/if_arp.h>
103 #include <net/ethernet.h>
104 #include <net/if_dl.h>
105 #include <net/if_media.h>
106 #include <net/if_types.h>
107 #include <net/vlan/if_vlan_var.h>
108
109 #include <net/bpf.h>
110
111 #include <vm/vm.h>              /* for vtophys */
112 #include <vm/pmap.h>            /* for vtophys */
113 #include <machine/clock.h>      /* for DELAY */
114 #include <machine/bus_pio.h>
115 #include <machine/bus_memio.h>
116 #include <machine/bus.h>
117 #include <machine/resource.h>
118 #include <sys/bus.h>
119 #include <sys/rman.h>
120
121 #include "../mii_layer/mii.h"
122 #include "../mii_layer/miivar.h"
123
124 #include <bus/pci/pcireg.h>
125 #include <bus/pci/pcivar.h>
126
127 #define NGE_USEIOSPACE
128
129 #include "if_ngereg.h"
130
131
132 /* "controller miibus0" required.  See GENERIC if you get errors here. */
133 #include "miibus_if.h"
134
135 #define NGE_CSUM_FEATURES       (CSUM_IP | CSUM_TCP | CSUM_UDP)
136
137 /*
138  * Various supported device vendors/types and their names.
139  */
140 static struct nge_type nge_devs[] = {
141         { NGE_VENDORID, NGE_DEVICEID,
142             "National Semiconductor Gigabit Ethernet" },
143         { 0, 0, NULL }
144 };
145
146 static int nge_probe            (device_t);
147 static int nge_attach           (device_t);
148 static int nge_detach           (device_t);
149
150 static int nge_alloc_jumbo_mem  (struct nge_softc *);
151 static void nge_free_jumbo_mem  (struct nge_softc *);
152 static void *nge_jalloc         (struct nge_softc *);
153 static void nge_jfree           (caddr_t, u_int);
154 static void nge_jref            (caddr_t, u_int);
155
156 static int nge_newbuf           (struct nge_softc *,
157                                         struct nge_desc *, struct mbuf *);
158 static int nge_encap            (struct nge_softc *,
159                                         struct mbuf *, u_int32_t *);
160 static void nge_rxeof           (struct nge_softc *);
161 static void nge_txeof           (struct nge_softc *);
162 static void nge_intr            (void *);
163 static void nge_tick            (void *);
164 static void nge_start           (struct ifnet *);
165 static int nge_ioctl            (struct ifnet *, u_long, caddr_t,
166                                         struct ucred *);
167 static void nge_init            (void *);
168 static void nge_stop            (struct nge_softc *);
169 static void nge_watchdog                (struct ifnet *);
170 static void nge_shutdown                (device_t);
171 static int nge_ifmedia_upd      (struct ifnet *);
172 static void nge_ifmedia_sts     (struct ifnet *, struct ifmediareq *);
173
174 static void nge_delay           (struct nge_softc *);
175 static void nge_eeprom_idle     (struct nge_softc *);
176 static void nge_eeprom_putbyte  (struct nge_softc *, int);
177 static void nge_eeprom_getword  (struct nge_softc *, int, u_int16_t *);
178 static void nge_read_eeprom     (struct nge_softc *, caddr_t, int, int, int);
179
180 static void nge_mii_sync        (struct nge_softc *);
181 static void nge_mii_send        (struct nge_softc *, u_int32_t, int);
182 static int nge_mii_readreg      (struct nge_softc *, struct nge_mii_frame *);
183 static int nge_mii_writereg     (struct nge_softc *, struct nge_mii_frame *);
184
185 static int nge_miibus_readreg   (device_t, int, int);
186 static int nge_miibus_writereg  (device_t, int, int, int);
187 static void nge_miibus_statchg  (device_t);
188
189 static void nge_setmulti        (struct nge_softc *);
190 static u_int32_t nge_crc        (struct nge_softc *, caddr_t);
191 static void nge_reset           (struct nge_softc *);
192 static int nge_list_rx_init     (struct nge_softc *);
193 static int nge_list_tx_init     (struct nge_softc *);
194
195 #ifdef NGE_USEIOSPACE
196 #define NGE_RES                 SYS_RES_IOPORT
197 #define NGE_RID                 NGE_PCI_LOIO
198 #else
199 #define NGE_RES                 SYS_RES_MEMORY
200 #define NGE_RID                 NGE_PCI_LOMEM
201 #endif
202
203 static device_method_t nge_methods[] = {
204         /* Device interface */
205         DEVMETHOD(device_probe,         nge_probe),
206         DEVMETHOD(device_attach,        nge_attach),
207         DEVMETHOD(device_detach,        nge_detach),
208         DEVMETHOD(device_shutdown,      nge_shutdown),
209
210         /* bus interface */
211         DEVMETHOD(bus_print_child,      bus_generic_print_child),
212         DEVMETHOD(bus_driver_added,     bus_generic_driver_added),
213
214         /* MII interface */
215         DEVMETHOD(miibus_readreg,       nge_miibus_readreg),
216         DEVMETHOD(miibus_writereg,      nge_miibus_writereg),
217         DEVMETHOD(miibus_statchg,       nge_miibus_statchg),
218
219         { 0, 0 }
220 };
221
222 static driver_t nge_driver = {
223         "nge",
224         nge_methods,
225         sizeof(struct nge_softc)
226 };
227
228 static devclass_t nge_devclass;
229
230 DECLARE_DUMMY_MODULE(if_nge);
231 MODULE_DEPEND(if_nge, miibus, 1, 1, 1);
232 DRIVER_MODULE(if_nge, pci, nge_driver, nge_devclass, 0, 0);
233 DRIVER_MODULE(miibus, nge, miibus_driver, miibus_devclass, 0, 0);
234
235 #define NGE_SETBIT(sc, reg, x)                          \
236         CSR_WRITE_4(sc, reg,                            \
237                 CSR_READ_4(sc, reg) | (x))
238
239 #define NGE_CLRBIT(sc, reg, x)                          \
240         CSR_WRITE_4(sc, reg,                            \
241                 CSR_READ_4(sc, reg) & ~(x))
242
243 #define SIO_SET(x)                                      \
244         CSR_WRITE_4(sc, NGE_MEAR, CSR_READ_4(sc, NGE_MEAR) | x)
245
246 #define SIO_CLR(x)                                      \
247         CSR_WRITE_4(sc, NGE_MEAR, CSR_READ_4(sc, NGE_MEAR) & ~x)
248
249 static void nge_delay(sc)
250         struct nge_softc        *sc;
251 {
252         int                     idx;
253
254         for (idx = (300 / 33) + 1; idx > 0; idx--)
255                 CSR_READ_4(sc, NGE_CSR);
256
257         return;
258 }
259
260 static void nge_eeprom_idle(sc)
261         struct nge_softc        *sc;
262 {
263         int             i;
264
265         SIO_SET(NGE_MEAR_EE_CSEL);
266         nge_delay(sc);
267         SIO_SET(NGE_MEAR_EE_CLK);
268         nge_delay(sc);
269
270         for (i = 0; i < 25; i++) {
271                 SIO_CLR(NGE_MEAR_EE_CLK);
272                 nge_delay(sc);
273                 SIO_SET(NGE_MEAR_EE_CLK);
274                 nge_delay(sc);
275         }
276
277         SIO_CLR(NGE_MEAR_EE_CLK);
278         nge_delay(sc);
279         SIO_CLR(NGE_MEAR_EE_CSEL);
280         nge_delay(sc);
281         CSR_WRITE_4(sc, NGE_MEAR, 0x00000000);
282
283         return;
284 }
285
286 /*
287  * Send a read command and address to the EEPROM, check for ACK.
288  */
289 static void nge_eeprom_putbyte(sc, addr)
290         struct nge_softc        *sc;
291         int                     addr;
292 {
293         int             d, i;
294
295         d = addr | NGE_EECMD_READ;
296
297         /*
298          * Feed in each bit and stobe the clock.
299          */
300         for (i = 0x400; i; i >>= 1) {
301                 if (d & i) {
302                         SIO_SET(NGE_MEAR_EE_DIN);
303                 } else {
304                         SIO_CLR(NGE_MEAR_EE_DIN);
305                 }
306                 nge_delay(sc);
307                 SIO_SET(NGE_MEAR_EE_CLK);
308                 nge_delay(sc);
309                 SIO_CLR(NGE_MEAR_EE_CLK);
310                 nge_delay(sc);
311         }
312
313         return;
314 }
315
316 /*
317  * Read a word of data stored in the EEPROM at address 'addr.'
318  */
319 static void nge_eeprom_getword(sc, addr, dest)
320         struct nge_softc        *sc;
321         int                     addr;
322         u_int16_t               *dest;
323 {
324         int             i;
325         u_int16_t               word = 0;
326
327         /* Force EEPROM to idle state. */
328         nge_eeprom_idle(sc);
329
330         /* Enter EEPROM access mode. */
331         nge_delay(sc);
332         SIO_CLR(NGE_MEAR_EE_CLK);
333         nge_delay(sc);
334         SIO_SET(NGE_MEAR_EE_CSEL);
335         nge_delay(sc);
336
337         /*
338          * Send address of word we want to read.
339          */
340         nge_eeprom_putbyte(sc, addr);
341
342         /*
343          * Start reading bits from EEPROM.
344          */
345         for (i = 0x8000; i; i >>= 1) {
346                 SIO_SET(NGE_MEAR_EE_CLK);
347                 nge_delay(sc);
348                 if (CSR_READ_4(sc, NGE_MEAR) & NGE_MEAR_EE_DOUT)
349                         word |= i;
350                 nge_delay(sc);
351                 SIO_CLR(NGE_MEAR_EE_CLK);
352                 nge_delay(sc);
353         }
354
355         /* Turn off EEPROM access mode. */
356         nge_eeprom_idle(sc);
357
358         *dest = word;
359
360         return;
361 }
362
363 /*
364  * Read a sequence of words from the EEPROM.
365  */
366 static void nge_read_eeprom(sc, dest, off, cnt, swap)
367         struct nge_softc        *sc;
368         caddr_t                 dest;
369         int                     off;
370         int                     cnt;
371         int                     swap;
372 {
373         int                     i;
374         u_int16_t               word = 0, *ptr;
375
376         for (i = 0; i < cnt; i++) {
377                 nge_eeprom_getword(sc, off + i, &word);
378                 ptr = (u_int16_t *)(dest + (i * 2));
379                 if (swap)
380                         *ptr = ntohs(word);
381                 else
382                         *ptr = word;
383         }
384
385         return;
386 }
387
388 /*
389  * Sync the PHYs by setting data bit and strobing the clock 32 times.
390  */
391 static void nge_mii_sync(sc)
392         struct nge_softc                *sc;
393 {
394         int             i;
395
396         SIO_SET(NGE_MEAR_MII_DIR|NGE_MEAR_MII_DATA);
397
398         for (i = 0; i < 32; i++) {
399                 SIO_SET(NGE_MEAR_MII_CLK);
400                 DELAY(1);
401                 SIO_CLR(NGE_MEAR_MII_CLK);
402                 DELAY(1);
403         }
404
405         return;
406 }
407
408 /*
409  * Clock a series of bits through the MII.
410  */
411 static void nge_mii_send(sc, bits, cnt)
412         struct nge_softc                *sc;
413         u_int32_t               bits;
414         int                     cnt;
415 {
416         int                     i;
417
418         SIO_CLR(NGE_MEAR_MII_CLK);
419
420         for (i = (0x1 << (cnt - 1)); i; i >>= 1) {
421                 if (bits & i) {
422                         SIO_SET(NGE_MEAR_MII_DATA);
423                 } else {
424                         SIO_CLR(NGE_MEAR_MII_DATA);
425                 }
426                 DELAY(1);
427                 SIO_CLR(NGE_MEAR_MII_CLK);
428                 DELAY(1);
429                 SIO_SET(NGE_MEAR_MII_CLK);
430         }
431 }
432
433 /*
434  * Read an PHY register through the MII.
435  */
436 static int nge_mii_readreg(sc, frame)
437         struct nge_softc                *sc;
438         struct nge_mii_frame    *frame;
439         
440 {
441         int                     i, ack, s;
442
443         s = splimp();
444
445         /*
446          * Set up frame for RX.
447          */
448         frame->mii_stdelim = NGE_MII_STARTDELIM;
449         frame->mii_opcode = NGE_MII_READOP;
450         frame->mii_turnaround = 0;
451         frame->mii_data = 0;
452         
453         CSR_WRITE_4(sc, NGE_MEAR, 0);
454
455         /*
456          * Turn on data xmit.
457          */
458         SIO_SET(NGE_MEAR_MII_DIR);
459
460         nge_mii_sync(sc);
461
462         /*
463          * Send command/address info.
464          */
465         nge_mii_send(sc, frame->mii_stdelim, 2);
466         nge_mii_send(sc, frame->mii_opcode, 2);
467         nge_mii_send(sc, frame->mii_phyaddr, 5);
468         nge_mii_send(sc, frame->mii_regaddr, 5);
469
470         /* Idle bit */
471         SIO_CLR((NGE_MEAR_MII_CLK|NGE_MEAR_MII_DATA));
472         DELAY(1);
473         SIO_SET(NGE_MEAR_MII_CLK);
474         DELAY(1);
475
476         /* Turn off xmit. */
477         SIO_CLR(NGE_MEAR_MII_DIR);
478         /* Check for ack */
479         SIO_CLR(NGE_MEAR_MII_CLK);
480         DELAY(1);
481         ack = CSR_READ_4(sc, NGE_MEAR) & NGE_MEAR_MII_DATA;
482         SIO_SET(NGE_MEAR_MII_CLK);
483         DELAY(1);
484
485         /*
486          * Now try reading data bits. If the ack failed, we still
487          * need to clock through 16 cycles to keep the PHY(s) in sync.
488          */
489         if (ack) {
490                 for(i = 0; i < 16; i++) {
491                         SIO_CLR(NGE_MEAR_MII_CLK);
492                         DELAY(1);
493                         SIO_SET(NGE_MEAR_MII_CLK);
494                         DELAY(1);
495                 }
496                 goto fail;
497         }
498
499         for (i = 0x8000; i; i >>= 1) {
500                 SIO_CLR(NGE_MEAR_MII_CLK);
501                 DELAY(1);
502                 if (!ack) {
503                         if (CSR_READ_4(sc, NGE_MEAR) & NGE_MEAR_MII_DATA)
504                                 frame->mii_data |= i;
505                         DELAY(1);
506                 }
507                 SIO_SET(NGE_MEAR_MII_CLK);
508                 DELAY(1);
509         }
510
511 fail:
512
513         SIO_CLR(NGE_MEAR_MII_CLK);
514         DELAY(1);
515         SIO_SET(NGE_MEAR_MII_CLK);
516         DELAY(1);
517
518         splx(s);
519
520         if (ack)
521                 return(1);
522         return(0);
523 }
524
525 /*
526  * Write to a PHY register through the MII.
527  */
528 static int nge_mii_writereg(sc, frame)
529         struct nge_softc                *sc;
530         struct nge_mii_frame    *frame;
531         
532 {
533         int                     s;
534
535         s = splimp();
536         /*
537          * Set up frame for TX.
538          */
539
540         frame->mii_stdelim = NGE_MII_STARTDELIM;
541         frame->mii_opcode = NGE_MII_WRITEOP;
542         frame->mii_turnaround = NGE_MII_TURNAROUND;
543         
544         /*
545          * Turn on data output.
546          */
547         SIO_SET(NGE_MEAR_MII_DIR);
548
549         nge_mii_sync(sc);
550
551         nge_mii_send(sc, frame->mii_stdelim, 2);
552         nge_mii_send(sc, frame->mii_opcode, 2);
553         nge_mii_send(sc, frame->mii_phyaddr, 5);
554         nge_mii_send(sc, frame->mii_regaddr, 5);
555         nge_mii_send(sc, frame->mii_turnaround, 2);
556         nge_mii_send(sc, frame->mii_data, 16);
557
558         /* Idle bit. */
559         SIO_SET(NGE_MEAR_MII_CLK);
560         DELAY(1);
561         SIO_CLR(NGE_MEAR_MII_CLK);
562         DELAY(1);
563
564         /*
565          * Turn off xmit.
566          */
567         SIO_CLR(NGE_MEAR_MII_DIR);
568
569         splx(s);
570
571         return(0);
572 }
573
574 static int nge_miibus_readreg(dev, phy, reg)
575         device_t                dev;
576         int                     phy, reg;
577 {
578         struct nge_softc        *sc;
579         struct nge_mii_frame    frame;
580
581         sc = device_get_softc(dev);
582
583         bzero((char *)&frame, sizeof(frame));
584
585         frame.mii_phyaddr = phy;
586         frame.mii_regaddr = reg;
587         nge_mii_readreg(sc, &frame);
588
589         return(frame.mii_data);
590 }
591
592 static int nge_miibus_writereg(dev, phy, reg, data)
593         device_t                dev;
594         int                     phy, reg, data;
595 {
596         struct nge_softc        *sc;
597         struct nge_mii_frame    frame;
598
599         sc = device_get_softc(dev);
600
601         bzero((char *)&frame, sizeof(frame));
602
603         frame.mii_phyaddr = phy;
604         frame.mii_regaddr = reg;
605         frame.mii_data = data;
606         nge_mii_writereg(sc, &frame);
607
608         return(0);
609 }
610
611 static void nge_miibus_statchg(dev)
612         device_t                dev;
613 {
614         int                     status; 
615         struct nge_softc        *sc;
616         struct mii_data         *mii;
617
618         sc = device_get_softc(dev);
619         if (sc->nge_tbi) {
620                 if (IFM_SUBTYPE(sc->nge_ifmedia.ifm_cur->ifm_media)
621                     == IFM_AUTO) {
622                         status = CSR_READ_4(sc, NGE_TBI_ANLPAR);
623                         if (status == 0 || status & NGE_TBIANAR_FDX) {
624                                 NGE_SETBIT(sc, NGE_TX_CFG,
625                                     (NGE_TXCFG_IGN_HBEAT|NGE_TXCFG_IGN_CARR));
626                                 NGE_SETBIT(sc, NGE_RX_CFG, NGE_RXCFG_RX_FDX);
627                         } else {
628                                 NGE_CLRBIT(sc, NGE_TX_CFG,
629                                     (NGE_TXCFG_IGN_HBEAT|NGE_TXCFG_IGN_CARR));
630                                 NGE_CLRBIT(sc, NGE_RX_CFG, NGE_RXCFG_RX_FDX);
631                         }
632
633                 } else if ((sc->nge_ifmedia.ifm_cur->ifm_media & IFM_GMASK) 
634                         != IFM_FDX) {
635                         NGE_CLRBIT(sc, NGE_TX_CFG,
636                             (NGE_TXCFG_IGN_HBEAT|NGE_TXCFG_IGN_CARR));
637                         NGE_CLRBIT(sc, NGE_RX_CFG, NGE_RXCFG_RX_FDX);
638                 } else {
639                         NGE_SETBIT(sc, NGE_TX_CFG,
640                             (NGE_TXCFG_IGN_HBEAT|NGE_TXCFG_IGN_CARR));
641                         NGE_SETBIT(sc, NGE_RX_CFG, NGE_RXCFG_RX_FDX);
642                 }
643         } else {
644                 mii = device_get_softc(sc->nge_miibus);
645
646                 if ((mii->mii_media_active & IFM_GMASK) == IFM_FDX) {
647                         NGE_SETBIT(sc, NGE_TX_CFG,
648                             (NGE_TXCFG_IGN_HBEAT|NGE_TXCFG_IGN_CARR));
649                         NGE_SETBIT(sc, NGE_RX_CFG, NGE_RXCFG_RX_FDX);
650                 } else {
651                         NGE_CLRBIT(sc, NGE_TX_CFG,
652                             (NGE_TXCFG_IGN_HBEAT|NGE_TXCFG_IGN_CARR));
653                         NGE_CLRBIT(sc, NGE_RX_CFG, NGE_RXCFG_RX_FDX);
654                 }
655
656                 /* If we have a 1000Mbps link, set the mode_1000 bit. */
657                 if (IFM_SUBTYPE(mii->mii_media_active) == IFM_1000_TX ||
658                     IFM_SUBTYPE(mii->mii_media_active) == IFM_1000_SX) {
659                         NGE_SETBIT(sc, NGE_CFG, NGE_CFG_MODE_1000);
660                 } else {
661                         NGE_CLRBIT(sc, NGE_CFG, NGE_CFG_MODE_1000);
662                 }
663         }
664         return;
665 }
666
667 static u_int32_t nge_crc(sc, addr)
668         struct nge_softc        *sc;
669         caddr_t                 addr;
670 {
671         u_int32_t               crc, carry; 
672         int                     i, j;
673         u_int8_t                c;
674
675         /* Compute CRC for the address value. */
676         crc = 0xFFFFFFFF; /* initial value */
677
678         for (i = 0; i < 6; i++) {
679                 c = *(addr + i);
680                 for (j = 0; j < 8; j++) {
681                         carry = ((crc & 0x80000000) ? 1 : 0) ^ (c & 0x01);
682                         crc <<= 1;
683                         c >>= 1;
684                         if (carry)
685                                 crc = (crc ^ 0x04c11db6) | carry;
686                 }
687         }
688
689         /*
690          * return the filter bit position
691          */
692
693         return((crc >> 21) & 0x00000FFF);
694 }
695
696 static void nge_setmulti(sc)
697         struct nge_softc        *sc;
698 {
699         struct ifnet            *ifp;
700         struct ifmultiaddr      *ifma;
701         u_int32_t               h = 0, i, filtsave;
702         int                     bit, index;
703
704         ifp = &sc->arpcom.ac_if;
705
706         if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) {
707                 NGE_CLRBIT(sc, NGE_RXFILT_CTL,
708                     NGE_RXFILTCTL_MCHASH|NGE_RXFILTCTL_UCHASH);
709                 NGE_SETBIT(sc, NGE_RXFILT_CTL, NGE_RXFILTCTL_ALLMULTI);
710                 return;
711         }
712
713         /*
714          * We have to explicitly enable the multicast hash table
715          * on the NatSemi chip if we want to use it, which we do.
716          * We also have to tell it that we don't want to use the
717          * hash table for matching unicast addresses.
718          */
719         NGE_SETBIT(sc, NGE_RXFILT_CTL, NGE_RXFILTCTL_MCHASH);
720         NGE_CLRBIT(sc, NGE_RXFILT_CTL,
721             NGE_RXFILTCTL_ALLMULTI|NGE_RXFILTCTL_UCHASH);
722
723         filtsave = CSR_READ_4(sc, NGE_RXFILT_CTL);
724
725         /* first, zot all the existing hash bits */
726         for (i = 0; i < NGE_MCAST_FILTER_LEN; i += 2) {
727                 CSR_WRITE_4(sc, NGE_RXFILT_CTL, NGE_FILTADDR_MCAST_LO + i);
728                 CSR_WRITE_4(sc, NGE_RXFILT_DATA, 0);
729         }
730
731         /*
732          * From the 11 bits returned by the crc routine, the top 7
733          * bits represent the 16-bit word in the mcast hash table
734          * that needs to be updated, and the lower 4 bits represent
735          * which bit within that byte needs to be set.
736          */
737         LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
738                 if (ifma->ifma_addr->sa_family != AF_LINK)
739                         continue;
740                 h = nge_crc(sc, LLADDR((struct sockaddr_dl *)ifma->ifma_addr));
741                 index = (h >> 4) & 0x7F;
742                 bit = h & 0xF;
743                 CSR_WRITE_4(sc, NGE_RXFILT_CTL,
744                     NGE_FILTADDR_MCAST_LO + (index * 2));
745                 NGE_SETBIT(sc, NGE_RXFILT_DATA, (1 << bit));
746         }
747
748         CSR_WRITE_4(sc, NGE_RXFILT_CTL, filtsave);
749
750         return;
751 }
752
753 static void nge_reset(sc)
754         struct nge_softc        *sc;
755 {
756         int             i;
757
758         NGE_SETBIT(sc, NGE_CSR, NGE_CSR_RESET);
759
760         for (i = 0; i < NGE_TIMEOUT; i++) {
761                 if (!(CSR_READ_4(sc, NGE_CSR) & NGE_CSR_RESET))
762                         break;
763         }
764
765         if (i == NGE_TIMEOUT)
766                 printf("nge%d: reset never completed\n", sc->nge_unit);
767
768         /* Wait a little while for the chip to get its brains in order. */
769         DELAY(1000);
770
771         /*
772          * If this is a NetSemi chip, make sure to clear
773          * PME mode.
774          */
775         CSR_WRITE_4(sc, NGE_CLKRUN, NGE_CLKRUN_PMESTS);
776         CSR_WRITE_4(sc, NGE_CLKRUN, 0);
777
778         return;
779 }
780
781 /*
782  * Probe for an NatSemi chip. Check the PCI vendor and device
783  * IDs against our list and return a device name if we find a match.
784  */
785 static int nge_probe(dev)
786         device_t                dev;
787 {
788         struct nge_type         *t;
789
790         t = nge_devs;
791
792         while(t->nge_name != NULL) {
793                 if ((pci_get_vendor(dev) == t->nge_vid) &&
794                     (pci_get_device(dev) == t->nge_did)) {
795                         device_set_desc(dev, t->nge_name);
796                         return(0);
797                 }
798                 t++;
799         }
800
801         return(ENXIO);
802 }
803
804 /*
805  * Attach the interface. Allocate softc structures, do ifmedia
806  * setup and ethernet/BPF attach.
807  */
808 static int nge_attach(dev)
809         device_t                dev;
810 {
811         int                     s;
812         u_char                  eaddr[ETHER_ADDR_LEN];
813         u_int32_t               command;
814         struct nge_softc        *sc;
815         struct ifnet            *ifp;
816         int                     unit, error = 0, rid;
817         const char              *sep = "";
818
819         s = splimp();
820
821         sc = device_get_softc(dev);
822         unit = device_get_unit(dev);
823         bzero(sc, sizeof(struct nge_softc));
824
825         /*
826          * Handle power management nonsense.
827          */
828
829         
830         command = pci_read_config(dev, NGE_PCI_CAPID, 4) & 0x000000FF;
831         if (command == 0x01) {
832
833                 command = pci_read_config(dev, NGE_PCI_PWRMGMTCTRL, 4);
834                 if (command & NGE_PSTATE_MASK) {
835                         u_int32_t               iobase, membase, irq;
836
837                         /* Save important PCI config data. */
838                         iobase = pci_read_config(dev, NGE_PCI_LOIO, 4);
839                         membase = pci_read_config(dev, NGE_PCI_LOMEM, 4);
840                         irq = pci_read_config(dev, NGE_PCI_INTLINE, 4);
841
842                         /* Reset the power state. */
843                         printf("nge%d: chip is in D%d power mode "
844                         "-- setting to D0\n", unit, command & NGE_PSTATE_MASK);
845                         command &= 0xFFFFFFFC;
846                         pci_write_config(dev, NGE_PCI_PWRMGMTCTRL, command, 4);
847
848                         /* Restore PCI config data. */
849                         pci_write_config(dev, NGE_PCI_LOIO, iobase, 4);
850                         pci_write_config(dev, NGE_PCI_LOMEM, membase, 4);
851                         pci_write_config(dev, NGE_PCI_INTLINE, irq, 4);
852                 }
853         }
854
855         /*
856          * Map control/status registers.
857          */
858         command = pci_read_config(dev, PCIR_COMMAND, 4);
859         command |= (PCIM_CMD_PORTEN|PCIM_CMD_MEMEN|PCIM_CMD_BUSMASTEREN);
860         pci_write_config(dev, PCIR_COMMAND, command, 4);
861         command = pci_read_config(dev, PCIR_COMMAND, 4);
862
863 #ifdef NGE_USEIOSPACE
864         if (!(command & PCIM_CMD_PORTEN)) {
865                 printf("nge%d: failed to enable I/O ports!\n", unit);
866                 error = ENXIO;;
867                 goto fail;
868         }
869 #else
870         if (!(command & PCIM_CMD_MEMEN)) {
871                 printf("nge%d: failed to enable memory mapping!\n", unit);
872                 error = ENXIO;;
873                 goto fail;
874         }
875 #endif
876
877         rid = NGE_RID;
878         sc->nge_res = bus_alloc_resource(dev, NGE_RES, &rid,
879             0, ~0, 1, RF_ACTIVE);
880
881         if (sc->nge_res == NULL) {
882                 printf("nge%d: couldn't map ports/memory\n", unit);
883                 error = ENXIO;
884                 goto fail;
885         }
886
887         sc->nge_btag = rman_get_bustag(sc->nge_res);
888         sc->nge_bhandle = rman_get_bushandle(sc->nge_res);
889
890         /* Allocate interrupt */
891         rid = 0;
892         sc->nge_irq = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0, ~0, 1,
893             RF_SHAREABLE | RF_ACTIVE);
894
895         if (sc->nge_irq == NULL) {
896                 printf("nge%d: couldn't map interrupt\n", unit);
897                 bus_release_resource(dev, NGE_RES, NGE_RID, sc->nge_res);
898                 error = ENXIO;
899                 goto fail;
900         }
901
902         error = bus_setup_intr(dev, sc->nge_irq, INTR_TYPE_NET,
903             nge_intr, sc, &sc->nge_intrhand);
904
905         if (error) {
906                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->nge_irq);
907                 bus_release_resource(dev, NGE_RES, NGE_RID, sc->nge_res);
908                 printf("nge%d: couldn't set up irq\n", unit);
909                 goto fail;
910         }
911
912         /* Reset the adapter. */
913         nge_reset(sc);
914
915         /*
916          * Get station address from the EEPROM.
917          */
918         nge_read_eeprom(sc, (caddr_t)&eaddr[4], NGE_EE_NODEADDR, 1, 0);
919         nge_read_eeprom(sc, (caddr_t)&eaddr[2], NGE_EE_NODEADDR + 1, 1, 0);
920         nge_read_eeprom(sc, (caddr_t)&eaddr[0], NGE_EE_NODEADDR + 2, 1, 0);
921
922         sc->nge_unit = unit;
923
924         sc->nge_ldata = contigmalloc(sizeof(struct nge_list_data), M_DEVBUF,
925             M_NOWAIT, 0, 0xffffffff, PAGE_SIZE, 0);
926
927         if (sc->nge_ldata == NULL) {
928                 printf("nge%d: no memory for list buffers!\n", unit);
929                 bus_teardown_intr(dev, sc->nge_irq, sc->nge_intrhand);
930                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->nge_irq);
931                 bus_release_resource(dev, NGE_RES, NGE_RID, sc->nge_res);
932                 error = ENXIO;
933                 goto fail;
934         }
935         bzero(sc->nge_ldata, sizeof(struct nge_list_data));
936
937         /* Try to allocate memory for jumbo buffers. */
938         if (nge_alloc_jumbo_mem(sc)) {
939                 printf("nge%d: jumbo buffer allocation failed\n",
940                     sc->nge_unit);
941                 contigfree(sc->nge_ldata,
942                     sizeof(struct nge_list_data), M_DEVBUF);
943                 bus_teardown_intr(dev, sc->nge_irq, sc->nge_intrhand);
944                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->nge_irq);
945                 bus_release_resource(dev, NGE_RES, NGE_RID, sc->nge_res);
946                 error = ENXIO;
947                 goto fail;
948         }
949
950         ifp = &sc->arpcom.ac_if;
951         ifp->if_softc = sc;
952         if_initname(ifp, "nge", unit);
953         ifp->if_mtu = ETHERMTU;
954         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
955         ifp->if_ioctl = nge_ioctl;
956         ifp->if_output = ether_output;
957         ifp->if_start = nge_start;
958         ifp->if_watchdog = nge_watchdog;
959         ifp->if_init = nge_init;
960         ifp->if_baudrate = 1000000000;
961         ifp->if_snd.ifq_maxlen = NGE_TX_LIST_CNT - 1;
962         ifp->if_hwassist = NGE_CSUM_FEATURES;
963         ifp->if_capabilities = IFCAP_HWCSUM;
964         ifp->if_capenable = ifp->if_capabilities;
965
966         /*
967          * Do MII setup.
968          */
969         if (mii_phy_probe(dev, &sc->nge_miibus,
970                           nge_ifmedia_upd, nge_ifmedia_sts)) {
971                 if (CSR_READ_4(sc, NGE_CFG) & NGE_CFG_TBI_EN) {
972                         sc->nge_tbi = 1;
973                         device_printf(dev, "Using TBI\n");
974                         
975                         sc->nge_miibus = dev;
976
977                         ifmedia_init(&sc->nge_ifmedia, 0, nge_ifmedia_upd, 
978                                 nge_ifmedia_sts);
979 #define ADD(m, c)       ifmedia_add(&sc->nge_ifmedia, (m), (c), NULL)
980 #define PRINT(s)        printf("%s%s", sep, s); sep = ", "
981                         ADD(IFM_MAKEWORD(IFM_ETHER, IFM_NONE, 0, 0), 0);
982                         device_printf(dev, " ");
983                         ADD(IFM_MAKEWORD(IFM_ETHER, IFM_1000_SX, 0, 0), 0);
984                         PRINT("1000baseSX");
985                         ADD(IFM_MAKEWORD(IFM_ETHER, IFM_1000_SX, IFM_FDX, 0),0);
986                         PRINT("1000baseSX-FDX");
987                         ADD(IFM_MAKEWORD(IFM_ETHER, IFM_AUTO, 0, 0), 0);
988                         PRINT("auto");
989             
990                         printf("\n");
991 #undef ADD
992 #undef PRINT
993                         ifmedia_set(&sc->nge_ifmedia, 
994                                 IFM_MAKEWORD(IFM_ETHER, IFM_AUTO, 0, 0));
995             
996                         CSR_WRITE_4(sc, NGE_GPIO, CSR_READ_4(sc, NGE_GPIO)
997                                 | NGE_GPIO_GP4_OUT 
998                                 | NGE_GPIO_GP1_OUTENB | NGE_GPIO_GP2_OUTENB 
999                                 | NGE_GPIO_GP3_OUTENB
1000                                 | NGE_GPIO_GP3_IN | NGE_GPIO_GP4_IN);
1001             
1002                 } else {
1003                         printf("nge%d: MII without any PHY!\n", sc->nge_unit);
1004                         nge_free_jumbo_mem(sc);
1005                         bus_teardown_intr(dev, sc->nge_irq, sc->nge_intrhand);
1006                         bus_release_resource(dev, SYS_RES_IRQ, 0, sc->nge_irq);
1007                         bus_release_resource(dev, NGE_RES, NGE_RID, 
1008                                          sc->nge_res);
1009                         error = ENXIO;
1010                         goto fail;
1011                 }
1012         }
1013
1014         /*
1015          * Call MI attach routine.
1016          */
1017         ether_ifattach(ifp, eaddr);
1018         callout_handle_init(&sc->nge_stat_ch);
1019
1020 fail:
1021
1022         splx(s);
1023         return(error);
1024 }
1025
1026 static int nge_detach(dev)
1027         device_t                dev;
1028 {
1029         struct nge_softc        *sc;
1030         struct ifnet            *ifp;
1031         int                     s;
1032
1033         s = splimp();
1034
1035         sc = device_get_softc(dev);
1036         ifp = &sc->arpcom.ac_if;
1037
1038         nge_reset(sc);
1039         nge_stop(sc);
1040         ether_ifdetach(ifp);
1041
1042         bus_generic_detach(dev);
1043         if (!sc->nge_tbi) {
1044                 device_delete_child(dev, sc->nge_miibus);
1045         }
1046         bus_teardown_intr(dev, sc->nge_irq, sc->nge_intrhand);
1047         bus_release_resource(dev, SYS_RES_IRQ, 0, sc->nge_irq);
1048         bus_release_resource(dev, NGE_RES, NGE_RID, sc->nge_res);
1049
1050         contigfree(sc->nge_ldata, sizeof(struct nge_list_data), M_DEVBUF);
1051         nge_free_jumbo_mem(sc);
1052
1053         splx(s);
1054
1055         return(0);
1056 }
1057
1058 /*
1059  * Initialize the transmit descriptors.
1060  */
1061 static int nge_list_tx_init(sc)
1062         struct nge_softc        *sc;
1063 {
1064         struct nge_list_data    *ld;
1065         struct nge_ring_data    *cd;
1066         int                     i;
1067
1068         cd = &sc->nge_cdata;
1069         ld = sc->nge_ldata;
1070
1071         for (i = 0; i < NGE_TX_LIST_CNT; i++) {
1072                 if (i == (NGE_TX_LIST_CNT - 1)) {
1073                         ld->nge_tx_list[i].nge_nextdesc =
1074                             &ld->nge_tx_list[0];
1075                         ld->nge_tx_list[i].nge_next =
1076                             vtophys(&ld->nge_tx_list[0]);
1077                 } else {
1078                         ld->nge_tx_list[i].nge_nextdesc =
1079                             &ld->nge_tx_list[i + 1];
1080                         ld->nge_tx_list[i].nge_next =
1081                             vtophys(&ld->nge_tx_list[i + 1]);
1082                 }
1083                 ld->nge_tx_list[i].nge_mbuf = NULL;
1084                 ld->nge_tx_list[i].nge_ptr = 0;
1085                 ld->nge_tx_list[i].nge_ctl = 0;
1086         }
1087
1088         cd->nge_tx_prod = cd->nge_tx_cons = cd->nge_tx_cnt = 0;
1089
1090         return(0);
1091 }
1092
1093
1094 /*
1095  * Initialize the RX descriptors and allocate mbufs for them. Note that
1096  * we arrange the descriptors in a closed ring, so that the last descriptor
1097  * points back to the first.
1098  */
1099 static int nge_list_rx_init(sc)
1100         struct nge_softc        *sc;
1101 {
1102         struct nge_list_data    *ld;
1103         struct nge_ring_data    *cd;
1104         int                     i;
1105
1106         ld = sc->nge_ldata;
1107         cd = &sc->nge_cdata;
1108
1109         for (i = 0; i < NGE_RX_LIST_CNT; i++) {
1110                 if (nge_newbuf(sc, &ld->nge_rx_list[i], NULL) == ENOBUFS)
1111                         return(ENOBUFS);
1112                 if (i == (NGE_RX_LIST_CNT - 1)) {
1113                         ld->nge_rx_list[i].nge_nextdesc =
1114                             &ld->nge_rx_list[0];
1115                         ld->nge_rx_list[i].nge_next =
1116                             vtophys(&ld->nge_rx_list[0]);
1117                 } else {
1118                         ld->nge_rx_list[i].nge_nextdesc =
1119                             &ld->nge_rx_list[i + 1];
1120                         ld->nge_rx_list[i].nge_next =
1121                             vtophys(&ld->nge_rx_list[i + 1]);
1122                 }
1123         }
1124
1125         cd->nge_rx_prod = 0;
1126
1127         return(0);
1128 }
1129
1130 /*
1131  * Initialize an RX descriptor and attach an MBUF cluster.
1132  */
1133 static int nge_newbuf(sc, c, m)
1134         struct nge_softc        *sc;
1135         struct nge_desc         *c;
1136         struct mbuf             *m;
1137 {
1138         struct mbuf             *m_new = NULL;
1139         caddr_t                 *buf = NULL;
1140
1141         if (m == NULL) {
1142                 MGETHDR(m_new, MB_DONTWAIT, MT_DATA);
1143                 if (m_new == NULL) {
1144                         printf("nge%d: no memory for rx list "
1145                             "-- packet dropped!\n", sc->nge_unit);
1146                         return(ENOBUFS);
1147                 }
1148
1149                 /* Allocate the jumbo buffer */
1150                 buf = nge_jalloc(sc);
1151                 if (buf == NULL) {
1152 #ifdef NGE_VERBOSE
1153                         printf("nge%d: jumbo allocation failed "
1154                             "-- packet dropped!\n", sc->nge_unit);
1155 #endif
1156                         m_freem(m_new);
1157                         return(ENOBUFS);
1158                 }
1159                 /* Attach the buffer to the mbuf */
1160                 m_new->m_data = m_new->m_ext.ext_buf = (void *)buf;
1161                 m_new->m_flags |= M_EXT;
1162                 m_new->m_ext.ext_size = m_new->m_pkthdr.len =
1163                     m_new->m_len = NGE_MCLBYTES;
1164                 m_new->m_ext.ext_free = nge_jfree;
1165                 m_new->m_ext.ext_ref = nge_jref;
1166         } else {
1167                 m_new = m;
1168                 m_new->m_len = m_new->m_pkthdr.len = NGE_MCLBYTES;
1169                 m_new->m_data = m_new->m_ext.ext_buf;
1170         }
1171
1172         m_adj(m_new, sizeof(u_int64_t));
1173
1174         c->nge_mbuf = m_new;
1175         c->nge_ptr = vtophys(mtod(m_new, caddr_t));
1176         c->nge_ctl = m_new->m_len;
1177         c->nge_extsts = 0;
1178
1179         return(0);
1180 }
1181
1182 static int nge_alloc_jumbo_mem(sc)
1183         struct nge_softc        *sc;
1184 {
1185         caddr_t                 ptr;
1186         int             i;
1187         struct nge_jpool_entry   *entry;
1188
1189         /* Grab a big chunk o' storage. */
1190         sc->nge_cdata.nge_jumbo_buf = contigmalloc(NGE_JMEM, M_DEVBUF,
1191             M_NOWAIT, 0, 0xffffffff, PAGE_SIZE, 0);
1192
1193         if (sc->nge_cdata.nge_jumbo_buf == NULL) {
1194                 printf("nge%d: no memory for jumbo buffers!\n", sc->nge_unit);
1195                 return(ENOBUFS);
1196         }
1197
1198         SLIST_INIT(&sc->nge_jfree_listhead);
1199         SLIST_INIT(&sc->nge_jinuse_listhead);
1200
1201         /*
1202          * Now divide it up into 9K pieces and save the addresses
1203          * in an array.
1204          */
1205         ptr = sc->nge_cdata.nge_jumbo_buf;
1206         for (i = 0; i < NGE_JSLOTS; i++) {
1207                 u_int64_t               **aptr;
1208                 aptr = (u_int64_t **)ptr;
1209                 aptr[0] = (u_int64_t *)sc;
1210                 ptr += sizeof(u_int64_t);
1211                 sc->nge_cdata.nge_jslots[i].nge_buf = ptr;
1212                 sc->nge_cdata.nge_jslots[i].nge_inuse = 0;
1213                 ptr += NGE_MCLBYTES;
1214                 entry = malloc(sizeof(struct nge_jpool_entry), 
1215                     M_DEVBUF, M_WAITOK);
1216                 if (entry == NULL) {
1217                         printf("nge%d: no memory for jumbo "
1218                             "buffer queue!\n", sc->nge_unit);
1219                         return(ENOBUFS);
1220                 }
1221                 entry->slot = i;
1222                 SLIST_INSERT_HEAD(&sc->nge_jfree_listhead,
1223                     entry, jpool_entries);
1224         }
1225
1226         return(0);
1227 }
1228
1229 static void nge_free_jumbo_mem(sc)
1230         struct nge_softc        *sc;
1231 {
1232         int             i;
1233         struct nge_jpool_entry   *entry;
1234
1235         for (i = 0; i < NGE_JSLOTS; i++) {
1236                 entry = SLIST_FIRST(&sc->nge_jfree_listhead);
1237                 SLIST_REMOVE_HEAD(&sc->nge_jfree_listhead, jpool_entries);
1238                 free(entry, M_DEVBUF);
1239         }
1240
1241         contigfree(sc->nge_cdata.nge_jumbo_buf, NGE_JMEM, M_DEVBUF);
1242
1243         return;
1244 }
1245
1246 /*
1247  * Allocate a jumbo buffer.
1248  */
1249 static void *nge_jalloc(sc)
1250         struct nge_softc        *sc;
1251 {
1252         struct nge_jpool_entry   *entry;
1253         
1254         entry = SLIST_FIRST(&sc->nge_jfree_listhead);
1255         
1256         if (entry == NULL) {
1257 #ifdef NGE_VERBOSE
1258                 printf("nge%d: no free jumbo buffers\n", sc->nge_unit);
1259 #endif
1260                 return(NULL);
1261         }
1262
1263         SLIST_REMOVE_HEAD(&sc->nge_jfree_listhead, jpool_entries);
1264         SLIST_INSERT_HEAD(&sc->nge_jinuse_listhead, entry, jpool_entries);
1265         sc->nge_cdata.nge_jslots[entry->slot].nge_inuse = 1;
1266         return(sc->nge_cdata.nge_jslots[entry->slot].nge_buf);
1267 }
1268
1269 /*
1270  * Adjust usage count on a jumbo buffer. In general this doesn't
1271  * get used much because our jumbo buffers don't get passed around
1272  * a lot, but it's implemented for correctness.
1273  */
1274 static void nge_jref(buf, size)
1275         caddr_t                 buf;
1276         u_int                   size;
1277 {
1278         struct nge_softc        *sc;
1279         u_int64_t               **aptr;
1280         int             i;
1281
1282         /* Extract the softc struct pointer. */
1283         aptr = (u_int64_t **)(buf - sizeof(u_int64_t));
1284         sc = (struct nge_softc *)(aptr[0]);
1285
1286         if (sc == NULL)
1287                 panic("nge_jref: can't find softc pointer!");
1288
1289         if (size != NGE_MCLBYTES)
1290                 panic("nge_jref: adjusting refcount of buf of wrong size!");
1291
1292         /* calculate the slot this buffer belongs to */
1293
1294         i = ((vm_offset_t)aptr 
1295              - (vm_offset_t)sc->nge_cdata.nge_jumbo_buf) / NGE_JLEN;
1296
1297         if ((i < 0) || (i >= NGE_JSLOTS))
1298                 panic("nge_jref: asked to reference buffer "
1299                     "that we don't manage!");
1300         else if (sc->nge_cdata.nge_jslots[i].nge_inuse == 0)
1301                 panic("nge_jref: buffer already free!");
1302         else
1303                 sc->nge_cdata.nge_jslots[i].nge_inuse++;
1304
1305         return;
1306 }
1307
1308 /*
1309  * Release a jumbo buffer.
1310  */
1311 static void nge_jfree(buf, size)
1312         caddr_t                 buf;
1313         u_int                   size;
1314 {
1315         struct nge_softc        *sc;
1316         u_int64_t               **aptr;
1317         int                     i;
1318         struct nge_jpool_entry   *entry;
1319
1320         /* Extract the softc struct pointer. */
1321         aptr = (u_int64_t **)(buf - sizeof(u_int64_t));
1322         sc = (struct nge_softc *)(aptr[0]);
1323
1324         if (sc == NULL)
1325                 panic("nge_jfree: can't find softc pointer!");
1326
1327         if (size != NGE_MCLBYTES)
1328                 panic("nge_jfree: freeing buffer of wrong size!");
1329
1330         /* calculate the slot this buffer belongs to */
1331
1332         i = ((vm_offset_t)aptr 
1333              - (vm_offset_t)sc->nge_cdata.nge_jumbo_buf) / NGE_JLEN;
1334
1335         if ((i < 0) || (i >= NGE_JSLOTS))
1336                 panic("nge_jfree: asked to free buffer that we don't manage!");
1337         else if (sc->nge_cdata.nge_jslots[i].nge_inuse == 0)
1338                 panic("nge_jfree: buffer already free!");
1339         else {
1340                 sc->nge_cdata.nge_jslots[i].nge_inuse--;
1341                 if(sc->nge_cdata.nge_jslots[i].nge_inuse == 0) {
1342                         entry = SLIST_FIRST(&sc->nge_jinuse_listhead);
1343                         if (entry == NULL)
1344                                 panic("nge_jfree: buffer not in use!");
1345                         entry->slot = i;
1346                         SLIST_REMOVE_HEAD(&sc->nge_jinuse_listhead, 
1347                                           jpool_entries);
1348                         SLIST_INSERT_HEAD(&sc->nge_jfree_listhead, 
1349                                           entry, jpool_entries);
1350                 }
1351         }
1352
1353         return;
1354 }
1355 /*
1356  * A frame has been uploaded: pass the resulting mbuf chain up to
1357  * the higher level protocols.
1358  */
1359 static void nge_rxeof(sc)
1360         struct nge_softc        *sc;
1361 {
1362         struct ether_header     *eh;
1363         struct mbuf             *m;
1364         struct ifnet            *ifp;
1365         struct nge_desc         *cur_rx;
1366         int                     i, total_len = 0;
1367         u_int32_t               rxstat;
1368
1369         ifp = &sc->arpcom.ac_if;
1370         i = sc->nge_cdata.nge_rx_prod;
1371
1372         while(NGE_OWNDESC(&sc->nge_ldata->nge_rx_list[i])) {
1373                 struct mbuf             *m0 = NULL;
1374                 u_int32_t               extsts;
1375
1376 #ifdef DEVICE_POLLING
1377                 if (ifp->if_flags & IFF_POLLING) {
1378                         if (sc->rxcycles <= 0)
1379                                 break;
1380                         sc->rxcycles--;
1381                 }
1382 #endif /* DEVICE_POLLING */
1383
1384                 cur_rx = &sc->nge_ldata->nge_rx_list[i];
1385                 rxstat = cur_rx->nge_rxstat;
1386                 extsts = cur_rx->nge_extsts;
1387                 m = cur_rx->nge_mbuf;
1388                 cur_rx->nge_mbuf = NULL;
1389                 total_len = NGE_RXBYTES(cur_rx);
1390                 NGE_INC(i, NGE_RX_LIST_CNT);
1391                 /*
1392                  * If an error occurs, update stats, clear the
1393                  * status word and leave the mbuf cluster in place:
1394                  * it should simply get re-used next time this descriptor
1395                  * comes up in the ring.
1396                  */
1397                 if (!(rxstat & NGE_CMDSTS_PKT_OK)) {
1398                         ifp->if_ierrors++;
1399                         nge_newbuf(sc, cur_rx, m);
1400                         continue;
1401                 }
1402
1403                 /*
1404                  * Ok. NatSemi really screwed up here. This is the
1405                  * only gigE chip I know of with alignment constraints
1406                  * on receive buffers. RX buffers must be 64-bit aligned.
1407                  */
1408 #ifdef __i386__
1409                 /*
1410                  * By popular demand, ignore the alignment problems
1411                  * on the Intel x86 platform. The performance hit
1412                  * incurred due to unaligned accesses is much smaller
1413                  * than the hit produced by forcing buffer copies all
1414                  * the time, especially with jumbo frames. We still
1415                  * need to fix up the alignment everywhere else though.
1416                  */
1417                 if (nge_newbuf(sc, cur_rx, NULL) == ENOBUFS) {
1418 #endif
1419                         m0 = m_devget(mtod(m, char *) - ETHER_ALIGN,
1420                             total_len + ETHER_ALIGN, 0, ifp, NULL);
1421                         nge_newbuf(sc, cur_rx, m);
1422                         if (m0 == NULL) {
1423                                 printf("nge%d: no receive buffers "
1424                                     "available -- packet dropped!\n",
1425                                     sc->nge_unit);
1426                                 ifp->if_ierrors++;
1427                                 continue;
1428                         }
1429                         m_adj(m0, ETHER_ALIGN);
1430                         m = m0;
1431 #ifdef __i386__
1432                 } else {
1433                         m->m_pkthdr.rcvif = ifp;
1434                         m->m_pkthdr.len = m->m_len = total_len;
1435                 }
1436 #endif
1437
1438                 ifp->if_ipackets++;
1439                 eh = mtod(m, struct ether_header *);
1440
1441                 /* Remove header from mbuf and pass it on. */
1442                 m_adj(m, sizeof(struct ether_header));
1443
1444                 /* Do IP checksum checking. */
1445                 if (extsts & NGE_RXEXTSTS_IPPKT)
1446                         m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
1447                 if (!(extsts & NGE_RXEXTSTS_IPCSUMERR))
1448                         m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1449                 if ((extsts & NGE_RXEXTSTS_TCPPKT &&
1450                     !(extsts & NGE_RXEXTSTS_TCPCSUMERR)) ||
1451                     (extsts & NGE_RXEXTSTS_UDPPKT &&
1452                     !(extsts & NGE_RXEXTSTS_UDPCSUMERR))) {
1453                         m->m_pkthdr.csum_flags |=
1454                             CSUM_DATA_VALID|CSUM_PSEUDO_HDR;
1455                         m->m_pkthdr.csum_data = 0xffff;
1456                 }
1457
1458                 /*
1459                  * If we received a packet with a vlan tag, pass it
1460                  * to vlan_input() instead of ether_input().
1461                  */
1462                 if (extsts & NGE_RXEXTSTS_VLANPKT) {
1463                         VLAN_INPUT_TAG(eh, m, extsts & NGE_RXEXTSTS_VTCI);
1464                         continue;
1465                 }
1466
1467                 ether_input(ifp, eh, m);
1468         }
1469
1470         sc->nge_cdata.nge_rx_prod = i;
1471
1472         return;
1473 }
1474
1475 /*
1476  * A frame was downloaded to the chip. It's safe for us to clean up
1477  * the list buffers.
1478  */
1479
1480 static void nge_txeof(sc)
1481         struct nge_softc        *sc;
1482 {
1483         struct nge_desc         *cur_tx = NULL;
1484         struct ifnet            *ifp;
1485         u_int32_t               idx;
1486
1487         ifp = &sc->arpcom.ac_if;
1488
1489         /* Clear the timeout timer. */
1490         ifp->if_timer = 0;
1491
1492         /*
1493          * Go through our tx list and free mbufs for those
1494          * frames that have been transmitted.
1495          */
1496         idx = sc->nge_cdata.nge_tx_cons;
1497         while (idx != sc->nge_cdata.nge_tx_prod) {
1498                 cur_tx = &sc->nge_ldata->nge_tx_list[idx];
1499
1500                 if (NGE_OWNDESC(cur_tx))
1501                         break;
1502
1503                 if (cur_tx->nge_ctl & NGE_CMDSTS_MORE) {
1504                         sc->nge_cdata.nge_tx_cnt--;
1505                         NGE_INC(idx, NGE_TX_LIST_CNT);
1506                         continue;
1507                 }
1508
1509                 if (!(cur_tx->nge_ctl & NGE_CMDSTS_PKT_OK)) {
1510                         ifp->if_oerrors++;
1511                         if (cur_tx->nge_txstat & NGE_TXSTAT_EXCESSCOLLS)
1512                                 ifp->if_collisions++;
1513                         if (cur_tx->nge_txstat & NGE_TXSTAT_OUTOFWINCOLL)
1514                                 ifp->if_collisions++;
1515                 }
1516
1517                 ifp->if_collisions +=
1518                     (cur_tx->nge_txstat & NGE_TXSTAT_COLLCNT) >> 16;
1519
1520                 ifp->if_opackets++;
1521                 if (cur_tx->nge_mbuf != NULL) {
1522                         m_freem(cur_tx->nge_mbuf);
1523                         cur_tx->nge_mbuf = NULL;
1524                 }
1525
1526                 sc->nge_cdata.nge_tx_cnt--;
1527                 NGE_INC(idx, NGE_TX_LIST_CNT);
1528                 ifp->if_timer = 0;
1529         }
1530
1531         sc->nge_cdata.nge_tx_cons = idx;
1532
1533         if (cur_tx != NULL)
1534                 ifp->if_flags &= ~IFF_OACTIVE;
1535
1536         return;
1537 }
1538
1539 static void nge_tick(xsc)
1540         void                    *xsc;
1541 {
1542         struct nge_softc        *sc;
1543         struct mii_data         *mii;
1544         struct ifnet            *ifp;
1545         int                     s;
1546
1547         s = splimp();
1548
1549         sc = xsc;
1550         ifp = &sc->arpcom.ac_if;
1551
1552         if (sc->nge_tbi) {
1553                 if (!sc->nge_link) {
1554                         if (CSR_READ_4(sc, NGE_TBI_BMSR) 
1555                             & NGE_TBIBMSR_ANEG_DONE) {
1556                                 printf("nge%d: gigabit link up\n",
1557                                     sc->nge_unit);
1558                                 nge_miibus_statchg(sc->nge_miibus);
1559                                 sc->nge_link++;
1560                                 if (ifp->if_snd.ifq_head != NULL)
1561                                         nge_start(ifp);
1562                         }
1563                 }
1564         } else {
1565                 mii = device_get_softc(sc->nge_miibus);
1566                 mii_tick(mii);
1567
1568                 if (!sc->nge_link) {
1569                         if (mii->mii_media_status & IFM_ACTIVE &&
1570                             IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) {
1571                                 sc->nge_link++;
1572                                 if (IFM_SUBTYPE(mii->mii_media_active) 
1573                                     == IFM_1000_TX)
1574                                         printf("nge%d: gigabit link up\n",
1575                                             sc->nge_unit);
1576                                 if (ifp->if_snd.ifq_head != NULL)
1577                                         nge_start(ifp);
1578                         }
1579                 }
1580         }
1581         sc->nge_stat_ch = timeout(nge_tick, sc, hz);
1582
1583         splx(s);
1584
1585         return;
1586 }
1587
1588 #ifdef DEVICE_POLLING
1589 static poll_handler_t nge_poll;
1590
1591 static void
1592 nge_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1593 {
1594         struct  nge_softc *sc = ifp->if_softc;
1595
1596         if (cmd == POLL_DEREGISTER) {   /* final call, enable interrupts */
1597                 CSR_WRITE_4(sc, NGE_IER, 1);
1598                 return;
1599         }
1600
1601         /*
1602          * On the nge, reading the status register also clears it.
1603          * So before returning to intr mode we must make sure that all
1604          * possible pending sources of interrupts have been served.
1605          * In practice this means run to completion the *eof routines,
1606          * and then call the interrupt routine
1607          */
1608         sc->rxcycles = count;
1609         nge_rxeof(sc);
1610         nge_txeof(sc);
1611         if (ifp->if_snd.ifq_head != NULL)
1612                 nge_start(ifp);
1613
1614         if (sc->rxcycles > 0 || cmd == POLL_AND_CHECK_STATUS) {
1615                 u_int32_t       status;
1616
1617                 /* Reading the ISR register clears all interrupts. */
1618                 status = CSR_READ_4(sc, NGE_ISR);
1619
1620                 if (status & (NGE_ISR_RX_ERR|NGE_ISR_RX_OFLOW))
1621                         nge_rxeof(sc);
1622
1623                 if (status & (NGE_ISR_RX_IDLE))
1624                         NGE_SETBIT(sc, NGE_CSR, NGE_CSR_RX_ENABLE);
1625
1626                 if (status & NGE_ISR_SYSERR) {
1627                         nge_reset(sc);
1628                         nge_init(sc);
1629                 }
1630         }
1631 }
1632 #endif /* DEVICE_POLLING */
1633
1634 static void nge_intr(arg)
1635         void                    *arg;
1636 {
1637         struct nge_softc        *sc;
1638         struct ifnet            *ifp;
1639         u_int32_t               status;
1640
1641         sc = arg;
1642         ifp = &sc->arpcom.ac_if;
1643
1644 #ifdef DEVICE_POLLING
1645         if (ifp->if_flags & IFF_POLLING)
1646                 return;
1647         if (ether_poll_register(nge_poll, ifp)) { /* ok, disable interrupts */
1648                 CSR_WRITE_4(sc, NGE_IER, 0);
1649                 nge_poll(ifp, 0, 1);
1650                 return;
1651         }
1652 #endif /* DEVICE_POLLING */
1653
1654         /* Supress unwanted interrupts */
1655         if (!(ifp->if_flags & IFF_UP)) {
1656                 nge_stop(sc);
1657                 return;
1658         }
1659
1660         /* Disable interrupts. */
1661         CSR_WRITE_4(sc, NGE_IER, 0);
1662
1663         /* Data LED on for TBI mode */
1664         if(sc->nge_tbi)
1665                  CSR_WRITE_4(sc, NGE_GPIO, CSR_READ_4(sc, NGE_GPIO)
1666                              | NGE_GPIO_GP3_OUT);
1667
1668         for (;;) {
1669                 /* Reading the ISR register clears all interrupts. */
1670                 status = CSR_READ_4(sc, NGE_ISR);
1671
1672                 if ((status & NGE_INTRS) == 0)
1673                         break;
1674
1675                 if ((status & NGE_ISR_TX_DESC_OK) ||
1676                     (status & NGE_ISR_TX_ERR) ||
1677                     (status & NGE_ISR_TX_OK) ||
1678                     (status & NGE_ISR_TX_IDLE))
1679                         nge_txeof(sc);
1680
1681                 if ((status & NGE_ISR_RX_DESC_OK) ||
1682                     (status & NGE_ISR_RX_ERR) ||
1683                     (status & NGE_ISR_RX_OFLOW) ||
1684                     (status & NGE_ISR_RX_FIFO_OFLOW) ||
1685                     (status & NGE_ISR_RX_IDLE) ||
1686                     (status & NGE_ISR_RX_OK))
1687                         nge_rxeof(sc);
1688
1689                 if ((status & NGE_ISR_RX_IDLE))
1690                         NGE_SETBIT(sc, NGE_CSR, NGE_CSR_RX_ENABLE);
1691
1692                 if (status & NGE_ISR_SYSERR) {
1693                         nge_reset(sc);
1694                         ifp->if_flags &= ~IFF_RUNNING;
1695                         nge_init(sc);
1696                 }
1697
1698 #ifdef notyet
1699                 /* mii_tick should only be called once per second */
1700                 if (status & NGE_ISR_PHY_INTR) {
1701                         sc->nge_link = 0;
1702                         nge_tick(sc);
1703                 }
1704 #endif
1705         }
1706
1707         /* Re-enable interrupts. */
1708         CSR_WRITE_4(sc, NGE_IER, 1);
1709
1710         if (ifp->if_snd.ifq_head != NULL)
1711                 nge_start(ifp);
1712
1713         /* Data LED off for TBI mode */
1714
1715         if(sc->nge_tbi)
1716                 CSR_WRITE_4(sc, NGE_GPIO, CSR_READ_4(sc, NGE_GPIO)
1717                             & ~NGE_GPIO_GP3_OUT);
1718
1719         return;
1720 }
1721
1722 /*
1723  * Encapsulate an mbuf chain in a descriptor by coupling the mbuf data
1724  * pointers to the fragment pointers.
1725  */
1726 static int nge_encap(sc, m_head, txidx)
1727         struct nge_softc        *sc;
1728         struct mbuf             *m_head;
1729         u_int32_t               *txidx;
1730 {
1731         struct nge_desc         *f = NULL;
1732         struct mbuf             *m;
1733         int                     frag, cur, cnt = 0;
1734         struct ifvlan           *ifv = NULL;
1735
1736         if ((m_head->m_flags & (M_PROTO1|M_PKTHDR)) == (M_PROTO1|M_PKTHDR) &&
1737             m_head->m_pkthdr.rcvif != NULL &&
1738             m_head->m_pkthdr.rcvif->if_type == IFT_L2VLAN)
1739                 ifv = m_head->m_pkthdr.rcvif->if_softc;
1740
1741         /*
1742          * Start packing the mbufs in this chain into
1743          * the fragment pointers. Stop when we run out
1744          * of fragments or hit the end of the mbuf chain.
1745          */
1746         m = m_head;
1747         cur = frag = *txidx;
1748
1749         for (m = m_head; m != NULL; m = m->m_next) {
1750                 if (m->m_len != 0) {
1751                         if ((NGE_TX_LIST_CNT -
1752                             (sc->nge_cdata.nge_tx_cnt + cnt)) < 2)
1753                                 return(ENOBUFS);
1754                         f = &sc->nge_ldata->nge_tx_list[frag];
1755                         f->nge_ctl = NGE_CMDSTS_MORE | m->m_len;
1756                         f->nge_ptr = vtophys(mtod(m, vm_offset_t));
1757                         if (cnt != 0)
1758                                 f->nge_ctl |= NGE_CMDSTS_OWN;
1759                         cur = frag;
1760                         NGE_INC(frag, NGE_TX_LIST_CNT);
1761                         cnt++;
1762                 }
1763         }
1764
1765         if (m != NULL)
1766                 return(ENOBUFS);
1767
1768         sc->nge_ldata->nge_tx_list[*txidx].nge_extsts = 0;
1769         if (m_head->m_pkthdr.csum_flags) {
1770                 if (m_head->m_pkthdr.csum_flags & CSUM_IP)
1771                         sc->nge_ldata->nge_tx_list[*txidx].nge_extsts |=
1772                             NGE_TXEXTSTS_IPCSUM;
1773                 if (m_head->m_pkthdr.csum_flags & CSUM_TCP)
1774                         sc->nge_ldata->nge_tx_list[*txidx].nge_extsts |=
1775                             NGE_TXEXTSTS_TCPCSUM;
1776                 if (m_head->m_pkthdr.csum_flags & CSUM_UDP)
1777                         sc->nge_ldata->nge_tx_list[*txidx].nge_extsts |=
1778                             NGE_TXEXTSTS_UDPCSUM;
1779         }
1780
1781         if (ifv != NULL) {
1782                 sc->nge_ldata->nge_tx_list[cur].nge_extsts |=
1783                         (NGE_TXEXTSTS_VLANPKT|ifv->ifv_tag);
1784         }
1785
1786         sc->nge_ldata->nge_tx_list[cur].nge_mbuf = m_head;
1787         sc->nge_ldata->nge_tx_list[cur].nge_ctl &= ~NGE_CMDSTS_MORE;
1788         sc->nge_ldata->nge_tx_list[*txidx].nge_ctl |= NGE_CMDSTS_OWN;
1789         sc->nge_cdata.nge_tx_cnt += cnt;
1790         *txidx = frag;
1791
1792         return(0);
1793 }
1794
1795 /*
1796  * Main transmit routine. To avoid having to do mbuf copies, we put pointers
1797  * to the mbuf data regions directly in the transmit lists. We also save a
1798  * copy of the pointers since the transmit list fragment pointers are
1799  * physical addresses.
1800  */
1801
1802 static void nge_start(ifp)
1803         struct ifnet            *ifp;
1804 {
1805         struct nge_softc        *sc;
1806         struct mbuf             *m_head = NULL;
1807         u_int32_t               idx;
1808
1809         sc = ifp->if_softc;
1810
1811         if (!sc->nge_link)
1812                 return;
1813
1814         idx = sc->nge_cdata.nge_tx_prod;
1815
1816         if (ifp->if_flags & IFF_OACTIVE)
1817                 return;
1818
1819         while(sc->nge_ldata->nge_tx_list[idx].nge_mbuf == NULL) {
1820                 IF_DEQUEUE(&ifp->if_snd, m_head);
1821                 if (m_head == NULL)
1822                         break;
1823
1824                 if (nge_encap(sc, m_head, &idx)) {
1825                         IF_PREPEND(&ifp->if_snd, m_head);
1826                         ifp->if_flags |= IFF_OACTIVE;
1827                         break;
1828                 }
1829
1830                 /*
1831                  * If there's a BPF listener, bounce a copy of this frame
1832                  * to him.
1833                  */
1834                 if (ifp->if_bpf)
1835                         bpf_mtap(ifp, m_head);
1836
1837         }
1838
1839         /* Transmit */
1840         sc->nge_cdata.nge_tx_prod = idx;
1841         NGE_SETBIT(sc, NGE_CSR, NGE_CSR_TX_ENABLE);
1842
1843         /*
1844          * Set a timeout in case the chip goes out to lunch.
1845          */
1846         ifp->if_timer = 5;
1847
1848         return;
1849 }
1850
1851 static void nge_init(xsc)
1852         void                    *xsc;
1853 {
1854         struct nge_softc        *sc = xsc;
1855         struct ifnet            *ifp = &sc->arpcom.ac_if;
1856         struct mii_data         *mii;
1857         int                     s;
1858
1859         if (ifp->if_flags & IFF_RUNNING)
1860                 return;
1861
1862         s = splimp();
1863
1864         /*
1865          * Cancel pending I/O and free all RX/TX buffers.
1866          */
1867         nge_stop(sc);
1868         sc->nge_stat_ch = timeout(nge_tick, sc, hz);
1869
1870         if (sc->nge_tbi) {
1871                 mii = NULL;
1872         } else {
1873                 mii = device_get_softc(sc->nge_miibus);
1874         }
1875
1876         /* Set MAC address */
1877         CSR_WRITE_4(sc, NGE_RXFILT_CTL, NGE_FILTADDR_PAR0);
1878         CSR_WRITE_4(sc, NGE_RXFILT_DATA,
1879             ((u_int16_t *)sc->arpcom.ac_enaddr)[0]);
1880         CSR_WRITE_4(sc, NGE_RXFILT_CTL, NGE_FILTADDR_PAR1);
1881         CSR_WRITE_4(sc, NGE_RXFILT_DATA,
1882             ((u_int16_t *)sc->arpcom.ac_enaddr)[1]);
1883         CSR_WRITE_4(sc, NGE_RXFILT_CTL, NGE_FILTADDR_PAR2);
1884         CSR_WRITE_4(sc, NGE_RXFILT_DATA,
1885             ((u_int16_t *)sc->arpcom.ac_enaddr)[2]);
1886
1887         /* Init circular RX list. */
1888         if (nge_list_rx_init(sc) == ENOBUFS) {
1889                 printf("nge%d: initialization failed: no "
1890                         "memory for rx buffers\n", sc->nge_unit);
1891                 nge_stop(sc);
1892                 (void)splx(s);
1893                 return;
1894         }
1895
1896         /*
1897          * Init tx descriptors.
1898          */
1899         nge_list_tx_init(sc);
1900
1901         /*
1902          * For the NatSemi chip, we have to explicitly enable the
1903          * reception of ARP frames, as well as turn on the 'perfect
1904          * match' filter where we store the station address, otherwise
1905          * we won't receive unicasts meant for this host.
1906          */
1907         NGE_SETBIT(sc, NGE_RXFILT_CTL, NGE_RXFILTCTL_ARP);
1908         NGE_SETBIT(sc, NGE_RXFILT_CTL, NGE_RXFILTCTL_PERFECT);
1909
1910          /* If we want promiscuous mode, set the allframes bit. */
1911         if (ifp->if_flags & IFF_PROMISC) {
1912                 NGE_SETBIT(sc, NGE_RXFILT_CTL, NGE_RXFILTCTL_ALLPHYS);
1913         } else {
1914                 NGE_CLRBIT(sc, NGE_RXFILT_CTL, NGE_RXFILTCTL_ALLPHYS);
1915         }
1916
1917         /*
1918          * Set the capture broadcast bit to capture broadcast frames.
1919          */
1920         if (ifp->if_flags & IFF_BROADCAST) {
1921                 NGE_SETBIT(sc, NGE_RXFILT_CTL, NGE_RXFILTCTL_BROAD);
1922         } else {
1923                 NGE_CLRBIT(sc, NGE_RXFILT_CTL, NGE_RXFILTCTL_BROAD);
1924         }
1925
1926         /*
1927          * Load the multicast filter.
1928          */
1929         nge_setmulti(sc);
1930
1931         /* Turn the receive filter on */
1932         NGE_SETBIT(sc, NGE_RXFILT_CTL, NGE_RXFILTCTL_ENABLE);
1933
1934         /*
1935          * Load the address of the RX and TX lists.
1936          */
1937         CSR_WRITE_4(sc, NGE_RX_LISTPTR,
1938             vtophys(&sc->nge_ldata->nge_rx_list[0]));
1939         CSR_WRITE_4(sc, NGE_TX_LISTPTR,
1940             vtophys(&sc->nge_ldata->nge_tx_list[0]));
1941
1942         /* Set RX configuration */
1943         CSR_WRITE_4(sc, NGE_RX_CFG, NGE_RXCFG);
1944         /*
1945          * Enable hardware checksum validation for all IPv4
1946          * packets, do not reject packets with bad checksums.
1947          */
1948         CSR_WRITE_4(sc, NGE_VLAN_IP_RXCTL, NGE_VIPRXCTL_IPCSUM_ENB);
1949
1950         /*
1951          * Tell the chip to detect and strip VLAN tag info from
1952          * received frames. The tag will be provided in the extsts
1953          * field in the RX descriptors.
1954          */
1955         NGE_SETBIT(sc, NGE_VLAN_IP_RXCTL,
1956             NGE_VIPRXCTL_TAG_DETECT_ENB|NGE_VIPRXCTL_TAG_STRIP_ENB);
1957
1958         /* Set TX configuration */
1959         CSR_WRITE_4(sc, NGE_TX_CFG, NGE_TXCFG);
1960
1961         /*
1962          * Enable TX IPv4 checksumming on a per-packet basis.
1963          */
1964         CSR_WRITE_4(sc, NGE_VLAN_IP_TXCTL, NGE_VIPTXCTL_CSUM_PER_PKT);
1965
1966         /*
1967          * Tell the chip to insert VLAN tags on a per-packet basis as
1968          * dictated by the code in the frame encapsulation routine.
1969          */
1970         NGE_SETBIT(sc, NGE_VLAN_IP_TXCTL, NGE_VIPTXCTL_TAG_PER_PKT);
1971
1972         /* Set full/half duplex mode. */
1973         if (sc->nge_tbi) {
1974                 if ((sc->nge_ifmedia.ifm_cur->ifm_media & IFM_GMASK) 
1975                     == IFM_FDX) {
1976                         NGE_SETBIT(sc, NGE_TX_CFG,
1977                             (NGE_TXCFG_IGN_HBEAT|NGE_TXCFG_IGN_CARR));
1978                         NGE_SETBIT(sc, NGE_RX_CFG, NGE_RXCFG_RX_FDX);
1979                 } else {
1980                         NGE_CLRBIT(sc, NGE_TX_CFG,
1981                             (NGE_TXCFG_IGN_HBEAT|NGE_TXCFG_IGN_CARR));
1982                         NGE_CLRBIT(sc, NGE_RX_CFG, NGE_RXCFG_RX_FDX);
1983                 }
1984         } else {
1985                 if ((mii->mii_media_active & IFM_GMASK) == IFM_FDX) {
1986                         NGE_SETBIT(sc, NGE_TX_CFG,
1987                             (NGE_TXCFG_IGN_HBEAT|NGE_TXCFG_IGN_CARR));
1988                         NGE_SETBIT(sc, NGE_RX_CFG, NGE_RXCFG_RX_FDX);
1989                 } else {
1990                         NGE_CLRBIT(sc, NGE_TX_CFG,
1991                             (NGE_TXCFG_IGN_HBEAT|NGE_TXCFG_IGN_CARR));
1992                         NGE_CLRBIT(sc, NGE_RX_CFG, NGE_RXCFG_RX_FDX);
1993                 }
1994         }
1995
1996         /*
1997          * Enable the delivery of PHY interrupts based on
1998          * link/speed/duplex status changes. Also enable the
1999          * extsts field in the DMA descriptors (needed for
2000          * TCP/IP checksum offload on transmit).
2001          */
2002         NGE_SETBIT(sc, NGE_CFG, NGE_CFG_PHYINTR_SPD|
2003             NGE_CFG_PHYINTR_LNK|NGE_CFG_PHYINTR_DUP|NGE_CFG_EXTSTS_ENB);
2004
2005         /*
2006          * Configure interrupt holdoff (moderation). We can
2007          * have the chip delay interrupt delivery for a certain
2008          * period. Units are in 100us, and the max setting
2009          * is 25500us (0xFF x 100us). Default is a 100us holdoff.
2010          */
2011         CSR_WRITE_4(sc, NGE_IHR, 0x01);
2012
2013         /*
2014          * Enable interrupts.
2015          */
2016         CSR_WRITE_4(sc, NGE_IMR, NGE_INTRS);
2017 #ifdef DEVICE_POLLING
2018         /*
2019          * ... only enable interrupts if we are not polling, make sure
2020          * they are off otherwise.
2021          */
2022         if (ifp->if_flags & IFF_POLLING)
2023                 CSR_WRITE_4(sc, NGE_IER, 0);
2024         else
2025 #endif /* DEVICE_POLLING */
2026         CSR_WRITE_4(sc, NGE_IER, 1);
2027
2028         /* Enable receiver and transmitter. */
2029         NGE_CLRBIT(sc, NGE_CSR, NGE_CSR_TX_DISABLE|NGE_CSR_RX_DISABLE);
2030         NGE_SETBIT(sc, NGE_CSR, NGE_CSR_RX_ENABLE);
2031
2032         nge_ifmedia_upd(ifp);
2033
2034         ifp->if_flags |= IFF_RUNNING;
2035         ifp->if_flags &= ~IFF_OACTIVE;
2036
2037         (void)splx(s);
2038
2039         return;
2040 }
2041
2042 /*
2043  * Set media options.
2044  */
2045 static int nge_ifmedia_upd(ifp)
2046         struct ifnet            *ifp;
2047 {
2048         struct nge_softc        *sc;
2049         struct mii_data         *mii;
2050
2051         sc = ifp->if_softc;
2052
2053         if (sc->nge_tbi) {
2054                 if (IFM_SUBTYPE(sc->nge_ifmedia.ifm_cur->ifm_media) 
2055                      == IFM_AUTO) {
2056                         CSR_WRITE_4(sc, NGE_TBI_ANAR, 
2057                                 CSR_READ_4(sc, NGE_TBI_ANAR)
2058                                         | NGE_TBIANAR_HDX | NGE_TBIANAR_FDX
2059                                         | NGE_TBIANAR_PS1 | NGE_TBIANAR_PS2);
2060                         CSR_WRITE_4(sc, NGE_TBI_BMCR, NGE_TBIBMCR_ENABLE_ANEG
2061                                 | NGE_TBIBMCR_RESTART_ANEG);
2062                         CSR_WRITE_4(sc, NGE_TBI_BMCR, NGE_TBIBMCR_ENABLE_ANEG);
2063                 } else if ((sc->nge_ifmedia.ifm_cur->ifm_media 
2064                             & IFM_GMASK) == IFM_FDX) {
2065                         NGE_SETBIT(sc, NGE_TX_CFG,
2066                             (NGE_TXCFG_IGN_HBEAT|NGE_TXCFG_IGN_CARR));
2067                         NGE_SETBIT(sc, NGE_RX_CFG, NGE_RXCFG_RX_FDX);
2068
2069                         CSR_WRITE_4(sc, NGE_TBI_ANAR, 0);
2070                         CSR_WRITE_4(sc, NGE_TBI_BMCR, 0);
2071                 } else {
2072                         NGE_CLRBIT(sc, NGE_TX_CFG,
2073                             (NGE_TXCFG_IGN_HBEAT|NGE_TXCFG_IGN_CARR));
2074                         NGE_CLRBIT(sc, NGE_RX_CFG, NGE_RXCFG_RX_FDX);
2075
2076                         CSR_WRITE_4(sc, NGE_TBI_ANAR, 0);
2077                         CSR_WRITE_4(sc, NGE_TBI_BMCR, 0);
2078                 }
2079                         
2080                 CSR_WRITE_4(sc, NGE_GPIO, CSR_READ_4(sc, NGE_GPIO)
2081                             & ~NGE_GPIO_GP3_OUT);
2082         } else {
2083                 mii = device_get_softc(sc->nge_miibus);
2084                 sc->nge_link = 0;
2085                 if (mii->mii_instance) {
2086                         struct mii_softc        *miisc;
2087                         for (miisc = LIST_FIRST(&mii->mii_phys); miisc != NULL;
2088                             miisc = LIST_NEXT(miisc, mii_list))
2089                                 mii_phy_reset(miisc);
2090                 }
2091                 mii_mediachg(mii);
2092         }
2093
2094         return(0);
2095 }
2096
2097 /*
2098  * Report current media status.
2099  */
2100 static void nge_ifmedia_sts(ifp, ifmr)
2101         struct ifnet            *ifp;
2102         struct ifmediareq       *ifmr;
2103 {
2104         struct nge_softc        *sc;
2105         struct mii_data         *mii;
2106
2107         sc = ifp->if_softc;
2108
2109         if (sc->nge_tbi) {
2110                 ifmr->ifm_status = IFM_AVALID;
2111                 ifmr->ifm_active = IFM_ETHER;
2112
2113                 if (CSR_READ_4(sc, NGE_TBI_BMSR) & NGE_TBIBMSR_ANEG_DONE) {
2114                         ifmr->ifm_status |= IFM_ACTIVE;
2115                 } 
2116                 if (CSR_READ_4(sc, NGE_TBI_BMCR) & NGE_TBIBMCR_LOOPBACK)
2117                         ifmr->ifm_active |= IFM_LOOP;
2118                 if (!CSR_READ_4(sc, NGE_TBI_BMSR) & NGE_TBIBMSR_ANEG_DONE) {
2119                         ifmr->ifm_active |= IFM_NONE;
2120                         ifmr->ifm_status = 0;
2121                         return;
2122                 } 
2123                 ifmr->ifm_active |= IFM_1000_SX;
2124                 if (IFM_SUBTYPE(sc->nge_ifmedia.ifm_cur->ifm_media)
2125                     == IFM_AUTO) {
2126                         ifmr->ifm_active |= IFM_AUTO;
2127                         if (CSR_READ_4(sc, NGE_TBI_ANLPAR)
2128                             & NGE_TBIANAR_FDX) {
2129                                 ifmr->ifm_active |= IFM_FDX;
2130                         }else if (CSR_READ_4(sc, NGE_TBI_ANLPAR)
2131                                   & NGE_TBIANAR_HDX) {
2132                                 ifmr->ifm_active |= IFM_HDX;
2133                         }
2134                 } else if ((sc->nge_ifmedia.ifm_cur->ifm_media & IFM_GMASK) 
2135                         == IFM_FDX)
2136                         ifmr->ifm_active |= IFM_FDX;
2137                 else
2138                         ifmr->ifm_active |= IFM_HDX;
2139  
2140         } else {
2141                 mii = device_get_softc(sc->nge_miibus);
2142                 mii_pollstat(mii);
2143                 ifmr->ifm_active = mii->mii_media_active;
2144                 ifmr->ifm_status = mii->mii_media_status;
2145         }
2146
2147         return;
2148 }
2149
2150 static int nge_ioctl(ifp, command, data, cr)
2151         struct ifnet            *ifp;
2152         u_long                  command;
2153         caddr_t                 data;
2154         struct ucred            *cr;
2155 {
2156         struct nge_softc        *sc = ifp->if_softc;
2157         struct ifreq            *ifr = (struct ifreq *) data;
2158         struct mii_data         *mii;
2159         int                     s, error = 0;
2160
2161         s = splimp();
2162
2163         switch(command) {
2164         case SIOCSIFADDR:
2165         case SIOCGIFADDR:
2166                 error = ether_ioctl(ifp, command, data);
2167                 break;
2168         case SIOCSIFMTU:
2169                 if (ifr->ifr_mtu > NGE_JUMBO_MTU)
2170                         error = EINVAL;
2171                 else {
2172                         ifp->if_mtu = ifr->ifr_mtu;
2173                         /*
2174                          * Workaround: if the MTU is larger than
2175                          * 8152 (TX FIFO size minus 64 minus 18), turn off
2176                          * TX checksum offloading.
2177                          */
2178                         if (ifr->ifr_mtu >= 8152)
2179                                 ifp->if_hwassist = 0;
2180                         else
2181                                 ifp->if_hwassist = NGE_CSUM_FEATURES;
2182                 }
2183                 break;
2184         case SIOCSIFFLAGS:
2185                 if (ifp->if_flags & IFF_UP) {
2186                         if (ifp->if_flags & IFF_RUNNING &&
2187                             ifp->if_flags & IFF_PROMISC &&
2188                             !(sc->nge_if_flags & IFF_PROMISC)) {
2189                                 NGE_SETBIT(sc, NGE_RXFILT_CTL,
2190                                     NGE_RXFILTCTL_ALLPHYS|
2191                                     NGE_RXFILTCTL_ALLMULTI);
2192                         } else if (ifp->if_flags & IFF_RUNNING &&
2193                             !(ifp->if_flags & IFF_PROMISC) &&
2194                             sc->nge_if_flags & IFF_PROMISC) {
2195                                 NGE_CLRBIT(sc, NGE_RXFILT_CTL,
2196                                     NGE_RXFILTCTL_ALLPHYS);
2197                                 if (!(ifp->if_flags & IFF_ALLMULTI))
2198                                         NGE_CLRBIT(sc, NGE_RXFILT_CTL,
2199                                             NGE_RXFILTCTL_ALLMULTI);
2200                         } else {
2201                                 ifp->if_flags &= ~IFF_RUNNING;
2202                                 nge_init(sc);
2203                         }
2204                 } else {
2205                         if (ifp->if_flags & IFF_RUNNING)
2206                                 nge_stop(sc);
2207                 }
2208                 sc->nge_if_flags = ifp->if_flags;
2209                 error = 0;
2210                 break;
2211         case SIOCADDMULTI:
2212         case SIOCDELMULTI:
2213                 nge_setmulti(sc);
2214                 error = 0;
2215                 break;
2216         case SIOCGIFMEDIA:
2217         case SIOCSIFMEDIA:
2218                 if (sc->nge_tbi) {
2219                         error = ifmedia_ioctl(ifp, ifr, &sc->nge_ifmedia, 
2220                                               command);
2221                 } else {
2222                         mii = device_get_softc(sc->nge_miibus);
2223                         error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, 
2224                                               command);
2225                 }
2226                 break;
2227         default:
2228                 error = EINVAL;
2229                 break;
2230         }
2231
2232         (void)splx(s);
2233
2234         return(error);
2235 }
2236
2237 static void nge_watchdog(ifp)
2238         struct ifnet            *ifp;
2239 {
2240         struct nge_softc        *sc;
2241
2242         sc = ifp->if_softc;
2243
2244         ifp->if_oerrors++;
2245         printf("nge%d: watchdog timeout\n", sc->nge_unit);
2246
2247         nge_stop(sc);
2248         nge_reset(sc);
2249         ifp->if_flags &= ~IFF_RUNNING;
2250         nge_init(sc);
2251
2252         if (ifp->if_snd.ifq_head != NULL)
2253                 nge_start(ifp);
2254
2255         return;
2256 }
2257
2258 /*
2259  * Stop the adapter and free any mbufs allocated to the
2260  * RX and TX lists.
2261  */
2262 static void nge_stop(sc)
2263         struct nge_softc        *sc;
2264 {
2265         int             i;
2266         struct ifnet            *ifp;
2267         struct ifmedia_entry    *ifm;
2268         struct mii_data         *mii;
2269         int                     mtmp, itmp;
2270
2271         ifp = &sc->arpcom.ac_if;
2272         ifp->if_timer = 0;
2273         if (sc->nge_tbi) {
2274                 mii = NULL;
2275         } else {
2276                 mii = device_get_softc(sc->nge_miibus);
2277         }
2278
2279         untimeout(nge_tick, sc, sc->nge_stat_ch);
2280 #ifdef DEVICE_POLLING
2281         ether_poll_deregister(ifp);
2282 #endif
2283         CSR_WRITE_4(sc, NGE_IER, 0);
2284         CSR_WRITE_4(sc, NGE_IMR, 0);
2285         NGE_SETBIT(sc, NGE_CSR, NGE_CSR_TX_DISABLE|NGE_CSR_RX_DISABLE);
2286         DELAY(1000);
2287         CSR_WRITE_4(sc, NGE_TX_LISTPTR, 0);
2288         CSR_WRITE_4(sc, NGE_RX_LISTPTR, 0);
2289
2290         /*
2291          * Isolate/power down the PHY, but leave the media selection
2292          * unchanged so that things will be put back to normal when
2293          * we bring the interface back up.
2294          */
2295         itmp = ifp->if_flags;
2296         ifp->if_flags |= IFF_UP;
2297
2298         if (sc->nge_tbi)
2299                 ifm = sc->nge_ifmedia.ifm_cur;
2300         else
2301                 ifm = mii->mii_media.ifm_cur;
2302         
2303         mtmp = ifm->ifm_media;
2304         ifm->ifm_media = IFM_ETHER|IFM_NONE;
2305         
2306         if (!sc->nge_tbi)
2307                 mii_mediachg(mii);
2308         ifm->ifm_media = mtmp;
2309         ifp->if_flags = itmp;
2310
2311         sc->nge_link = 0;
2312
2313         /*
2314          * Free data in the RX lists.
2315          */
2316         for (i = 0; i < NGE_RX_LIST_CNT; i++) {
2317                 if (sc->nge_ldata->nge_rx_list[i].nge_mbuf != NULL) {
2318                         m_freem(sc->nge_ldata->nge_rx_list[i].nge_mbuf);
2319                         sc->nge_ldata->nge_rx_list[i].nge_mbuf = NULL;
2320                 }
2321         }
2322         bzero((char *)&sc->nge_ldata->nge_rx_list,
2323                 sizeof(sc->nge_ldata->nge_rx_list));
2324
2325         /*
2326          * Free the TX list buffers.
2327          */
2328         for (i = 0; i < NGE_TX_LIST_CNT; i++) {
2329                 if (sc->nge_ldata->nge_tx_list[i].nge_mbuf != NULL) {
2330                         m_freem(sc->nge_ldata->nge_tx_list[i].nge_mbuf);
2331                         sc->nge_ldata->nge_tx_list[i].nge_mbuf = NULL;
2332                 }
2333         }
2334
2335         bzero((char *)&sc->nge_ldata->nge_tx_list,
2336                 sizeof(sc->nge_ldata->nge_tx_list));
2337
2338         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2339
2340         return;
2341 }
2342
2343 /*
2344  * Stop all chip I/O so that the kernel's probe routines don't
2345  * get confused by errant DMAs when rebooting.
2346  */
2347 static void nge_shutdown(dev)
2348         device_t                dev;
2349 {
2350         struct nge_softc        *sc;
2351
2352         sc = device_get_softc(dev);
2353
2354         nge_reset(sc);
2355         nge_stop(sc);
2356
2357         return;
2358 }