bcca8f522e247582a194f558770d280df6ba9359
[dragonfly.git] / sys / dev / netif / re / if_re.c
1 /*
2  * Copyright (c) 2004
3  *      Joerg Sonnenberger <joerg@bec.de>.  All rights reserved.
4  *
5  * Copyright (c) 1997, 1998-2003
6  *      Bill Paul <wpaul@windriver.com>.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by Bill Paul.
19  * 4. Neither the name of the author nor the names of any co-contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
27  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
33  * THE POSSIBILITY OF SUCH DAMAGE.
34  *
35  * $FreeBSD: src/sys/dev/re/if_re.c,v 1.25 2004/06/09 14:34:01 naddy Exp $
36  * $DragonFly: src/sys/dev/netif/re/if_re.c,v 1.10 2005/02/20 00:36:23 joerg Exp $
37  */
38
39 /*
40  * RealTek 8139C+/8169/8169S/8110S PCI NIC driver
41  *
42  * Written by Bill Paul <wpaul@windriver.com>
43  * Senior Networking Software Engineer
44  * Wind River Systems
45  */
46
47 /*
48  * This driver is designed to support RealTek's next generation of
49  * 10/100 and 10/100/1000 PCI ethernet controllers. There are currently
50  * four devices in this family: the RTL8139C+, the RTL8169, the RTL8169S
51  * and the RTL8110S.
52  *
53  * The 8139C+ is a 10/100 ethernet chip. It is backwards compatible
54  * with the older 8139 family, however it also supports a special
55  * C+ mode of operation that provides several new performance enhancing
56  * features. These include:
57  *
58  *      o Descriptor based DMA mechanism. Each descriptor represents
59  *        a single packet fragment. Data buffers may be aligned on
60  *        any byte boundary.
61  *
62  *      o 64-bit DMA
63  *
64  *      o TCP/IP checksum offload for both RX and TX
65  *
66  *      o High and normal priority transmit DMA rings
67  *
68  *      o VLAN tag insertion and extraction
69  *
70  *      o TCP large send (segmentation offload)
71  *
72  * Like the 8139, the 8139C+ also has a built-in 10/100 PHY. The C+
73  * programming API is fairly straightforward. The RX filtering, EEPROM
74  * access and PHY access is the same as it is on the older 8139 series
75  * chips.
76  *
77  * The 8169 is a 64-bit 10/100/1000 gigabit ethernet MAC. It has almost the
78  * same programming API and feature set as the 8139C+ with the following
79  * differences and additions:
80  *
81  *      o 1000Mbps mode
82  *
83  *      o Jumbo frames
84  *
85  *      o GMII and TBI ports/registers for interfacing with copper
86  *        or fiber PHYs
87  *
88  *      o RX and TX DMA rings can have up to 1024 descriptors
89  *        (the 8139C+ allows a maximum of 64)
90  *
91  *      o Slight differences in register layout from the 8139C+
92  *
93  * The TX start and timer interrupt registers are at different locations
94  * on the 8169 than they are on the 8139C+. Also, the status word in the
95  * RX descriptor has a slightly different bit layout. The 8169 does not
96  * have a built-in PHY. Most reference boards use a Marvell 88E1000 'Alaska'
97  * copper gigE PHY.
98  *
99  * The 8169S/8110S 10/100/1000 devices have built-in copper gigE PHYs
100  * (the 'S' stands for 'single-chip'). These devices have the same
101  * programming API as the older 8169, but also have some vendor-specific
102  * registers for the on-board PHY. The 8110S is a LAN-on-motherboard
103  * part designed to be pin-compatible with the RealTek 8100 10/100 chip.
104  * 
105  * This driver takes advantage of the RX and TX checksum offload and
106  * VLAN tag insertion/extraction features. It also implements TX
107  * interrupt moderation using the timer interrupt registers, which
108  * significantly reduces TX interrupt load. There is also support
109  * for jumbo frames, however the 8169/8169S/8110S can not transmit
110  * jumbo frames larger than 7.5K, so the max MTU possible with this
111  * driver is 7500 bytes.
112  */
113
114 #include <sys/param.h>
115 #include <sys/endian.h>
116 #include <sys/systm.h>
117 #include <sys/sockio.h>
118 #include <sys/mbuf.h>
119 #include <sys/malloc.h>
120 #include <sys/module.h>
121 #include <sys/kernel.h>
122 #include <sys/socket.h>
123
124 #include <net/if.h>
125 #include <net/ifq_var.h>
126 #include <net/if_arp.h>
127 #include <net/ethernet.h>
128 #include <net/if_dl.h>
129 #include <net/if_media.h>
130 #include <net/if_types.h>
131 #include <net/vlan/if_vlan_var.h>
132
133 #include <net/bpf.h>
134
135 #include <machine/bus_pio.h>
136 #include <machine/bus_memio.h>
137 #include <machine/bus.h>
138 #include <machine/resource.h>
139 #include <sys/bus.h>
140 #include <sys/rman.h>
141
142 #include <dev/netif/mii_layer/mii.h>
143 #include <dev/netif/mii_layer/miivar.h>
144
145 #include <bus/pci/pcireg.h>
146 #include <bus/pci/pcivar.h>
147
148 /* "controller miibus0" required.  See GENERIC if you get errors here. */
149 #include "miibus_if.h"
150
151 #include <dev/netif/re/if_rereg.h>
152
153 /*
154  * The hardware supports checksumming but, as usual, some chipsets screw it
155  * all up and produce bogus packets, so we disable it by default.
156  */
157 #define RE_CSUM_FEATURES    (CSUM_IP | CSUM_TCP | CSUM_UDP)
158 #define RE_DISABLE_HWCSUM
159
160 /*
161  * Various supported device vendors/types and their names.
162  */
163 static struct re_type re_devs[] = {
164         { RT_VENDORID, RT_DEVICEID_8139, RE_HWREV_8139CPLUS,
165                 "RealTek 8139C+ 10/100BaseTX" },
166         { RT_VENDORID, RT_DEVICEID_8169, RE_HWREV_8169,
167                 "RealTek 8169 Gigabit Ethernet" },
168         { RT_VENDORID, RT_DEVICEID_8169, RE_HWREV_8169S,
169                 "RealTek 8169S Single-chip Gigabit Ethernet" },
170         { RT_VENDORID, RT_DEVICEID_8169, RE_HWREV_8110S,
171                 "RealTek 8110S Single-chip Gigabit Ethernet" },
172         { 0, 0, 0, NULL }
173 };
174
175 static struct re_hwrev re_hwrevs[] = {
176         { RE_HWREV_8139CPLUS, RE_8139CPLUS, "C+"},
177         { RE_HWREV_8169, RE_8169, "8169"},
178         { RE_HWREV_8169S, RE_8169, "8169S"},
179         { RE_HWREV_8110S, RE_8169, "8110S"},
180         { 0, 0, NULL }
181 };
182
183 static int      re_probe(device_t);
184 static int      re_attach(device_t);
185 static int      re_detach(device_t);
186
187 static int      re_encap(struct re_softc *, struct mbuf **, int *, int *);
188
189 static void     re_dma_map_addr(void *, bus_dma_segment_t *, int, int);
190 static void     re_dma_map_desc(void *, bus_dma_segment_t *, int,
191                                 bus_size_t, int);
192 static int      re_allocmem(device_t, struct re_softc *);
193 static int      re_newbuf(struct re_softc *, int, struct mbuf *);
194 static int      re_rx_list_init(struct re_softc *);
195 static int      re_tx_list_init(struct re_softc *);
196 static void     re_rxeof(struct re_softc *);
197 static void     re_txeof(struct re_softc *);
198 static void     re_intr(void *);
199 static void     re_tick(void *);
200 static void     re_start(struct ifnet *);
201 static int      re_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
202 static void     re_init(void *);
203 static void     re_stop(struct re_softc *);
204 static void     re_watchdog(struct ifnet *);
205 static int      re_suspend(device_t);
206 static int      re_resume(device_t);
207 static void     re_shutdown(device_t);
208 static int      re_ifmedia_upd(struct ifnet *);
209 static void     re_ifmedia_sts(struct ifnet *, struct ifmediareq *);
210
211 static void     re_eeprom_putbyte(struct re_softc *, int);
212 static void     re_eeprom_getword(struct re_softc *, int, u_int16_t *);
213 static void     re_read_eeprom(struct re_softc *, caddr_t, int, int, int);
214 static int      re_gmii_readreg(device_t, int, int);
215 static int      re_gmii_writereg(device_t, int, int, int);
216
217 static int      re_miibus_readreg(device_t, int, int);
218 static int      re_miibus_writereg(device_t, int, int, int);
219 static void     re_miibus_statchg(device_t);
220
221 static void     re_setmulti(struct re_softc *);
222 static void     re_reset(struct re_softc *);
223
224 static int      re_diag(struct re_softc *);
225
226 static device_method_t re_methods[] = {
227         /* Device interface */
228         DEVMETHOD(device_probe,         re_probe),
229         DEVMETHOD(device_attach,        re_attach),
230         DEVMETHOD(device_detach,        re_detach),
231         DEVMETHOD(device_suspend,       re_suspend),
232         DEVMETHOD(device_resume,        re_resume),
233         DEVMETHOD(device_shutdown,      re_shutdown),
234
235         /* bus interface */
236         DEVMETHOD(bus_print_child,      bus_generic_print_child),
237         DEVMETHOD(bus_driver_added,     bus_generic_driver_added),
238
239         /* MII interface */
240         DEVMETHOD(miibus_readreg,       re_miibus_readreg),
241         DEVMETHOD(miibus_writereg,      re_miibus_writereg),
242         DEVMETHOD(miibus_statchg,       re_miibus_statchg),
243
244         { 0, 0 }
245 };
246
247 static driver_t re_driver = {
248         "re",
249         re_methods,
250         sizeof(struct re_softc)
251 };
252
253 static devclass_t re_devclass;
254
255 DECLARE_DUMMY_MODULE(if_re);
256 DRIVER_MODULE(if_re, pci, re_driver, re_devclass, 0, 0);
257 DRIVER_MODULE(if_re, cardbus, re_driver, re_devclass, 0, 0);
258 DRIVER_MODULE(miibus, re, miibus_driver, miibus_devclass, 0, 0);
259
260 #define EE_SET(x)       \
261         CSR_WRITE_1(sc, RE_EECMD, CSR_READ_1(sc, RE_EECMD) | (x))
262
263 #define EE_CLR(x)       \
264         CSR_WRITE_1(sc, RE_EECMD, CSR_READ_1(sc, RE_EECMD) & ~(x))
265
266 /*
267  * Send a read command and address to the EEPROM, check for ACK.
268  */
269 static void
270 re_eeprom_putbyte(struct re_softc *sc, int addr)
271 {
272         int d, i;
273
274         d = addr | sc->re_eecmd_read;
275
276         /*
277          * Feed in each bit and strobe the clock.
278          */
279         for (i = 0x400; i != 0; i >>= 1) {
280                 if (d & i)
281                         EE_SET(RE_EE_DATAIN);
282                 else
283                         EE_CLR(RE_EE_DATAIN);
284                 DELAY(100);
285                 EE_SET(RE_EE_CLK);
286                 DELAY(150);
287                 EE_CLR(RE_EE_CLK);
288                 DELAY(100);
289         }
290 }
291
292 /*
293  * Read a word of data stored in the EEPROM at address 'addr.'
294  */
295 static void
296 re_eeprom_getword(struct re_softc *sc, int addr, uint16_t *dest)
297 {
298         int i;
299         uint16_t word = 0;
300
301         /* Enter EEPROM access mode. */
302         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_PROGRAM|RE_EE_SEL);
303
304         /*
305          * Send address of word we want to read.
306          */
307         re_eeprom_putbyte(sc, addr);
308
309         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_PROGRAM|RE_EE_SEL);
310
311         /*
312          * Start reading bits from EEPROM.
313          */
314         for (i = 0x8000; i != 0; i >>= 1) {
315                 EE_SET(RE_EE_CLK);
316                 DELAY(100);
317                 if (CSR_READ_1(sc, RE_EECMD) & RE_EE_DATAOUT)
318                         word |= i;
319                 EE_CLR(RE_EE_CLK);
320                 DELAY(100);
321         }
322
323         /* Turn off EEPROM access mode. */
324         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_OFF);
325
326         *dest = word;
327 }
328
329 /*
330  * Read a sequence of words from the EEPROM.
331  */
332 static void
333 re_read_eeprom(struct re_softc *sc, caddr_t dest, int off, int cnt, int swap)
334 {
335         int i;
336         uint16_t word = 0, *ptr;
337
338         for (i = 0; i < cnt; i++) {
339                 re_eeprom_getword(sc, off + i, &word);
340                 ptr = (u_int16_t *)(dest + (i * 2));
341                 if (swap)
342                         *ptr = be16toh(word);
343                 else
344                         *ptr = word;
345         }
346 }
347
348 static int
349 re_gmii_readreg(device_t dev, int phy, int reg)
350 {
351         struct re_softc *sc = device_get_softc(dev);
352         u_int32_t rval;
353         int i;
354
355         if (phy != 1)
356                 return(0);
357
358         /* Let the rgephy driver read the GMEDIASTAT register */
359
360         if (reg == RE_GMEDIASTAT)
361                 return(CSR_READ_1(sc, RE_GMEDIASTAT));
362
363         CSR_WRITE_4(sc, RE_PHYAR, reg << 16);
364         DELAY(1000);
365
366         for (i = 0; i < RE_TIMEOUT; i++) {
367                 rval = CSR_READ_4(sc, RE_PHYAR);
368                 if (rval & RE_PHYAR_BUSY)
369                         break;
370                 DELAY(100);
371         }
372
373         if (i == RE_TIMEOUT) {
374                 device_printf(dev, "PHY read failed\n");
375                 return(0);
376         }
377
378         return(rval & RE_PHYAR_PHYDATA);
379 }
380
381 static int
382 re_gmii_writereg(device_t dev, int phy, int reg, int data)
383 {
384         struct re_softc *sc = device_get_softc(dev);
385         uint32_t rval;
386         int i;
387
388         CSR_WRITE_4(sc, RE_PHYAR,
389                     (reg << 16) | (data & RE_PHYAR_PHYDATA) | RE_PHYAR_BUSY);
390         DELAY(1000);
391
392         for (i = 0; i < RE_TIMEOUT; i++) {
393                 rval = CSR_READ_4(sc, RE_PHYAR);
394                 if ((rval & RE_PHYAR_BUSY) == 0)
395                         break;
396                 DELAY(100);
397         }
398
399         if (i == RE_TIMEOUT)
400                 device_printf(dev, "PHY write failed\n");
401
402         return(0);
403 }
404
405 static int
406 re_miibus_readreg(device_t dev, int phy, int reg)
407 {
408         struct re_softc *sc = device_get_softc(dev);
409         uint16_t rval = 0;
410         uint16_t re8139_reg = 0;
411
412         if (sc->re_type == RE_8169) {
413                 rval = re_gmii_readreg(dev, phy, reg);
414                 return(rval);
415         }
416
417         /* Pretend the internal PHY is only at address 0 */
418         if (phy)
419                 return(0);
420
421         switch(reg) {
422         case MII_BMCR:
423                 re8139_reg = RE_BMCR;
424                 break;
425         case MII_BMSR:
426                 re8139_reg = RE_BMSR;
427                 break;
428         case MII_ANAR:
429                 re8139_reg = RE_ANAR;
430                 break;
431         case MII_ANER:
432                 re8139_reg = RE_ANER;
433                 break;
434         case MII_ANLPAR:
435                 re8139_reg = RE_LPAR;
436                 break;
437         case MII_PHYIDR1:
438         case MII_PHYIDR2:
439                 return(0);
440         /*
441          * Allow the rlphy driver to read the media status
442          * register. If we have a link partner which does not
443          * support NWAY, this is the register which will tell
444          * us the results of parallel detection.
445          */
446         case RE_MEDIASTAT:
447                 return(CSR_READ_1(sc, RE_MEDIASTAT));
448         default:
449                 device_printf(dev, "bad phy register\n");
450                 return(0);
451         }
452         rval = CSR_READ_2(sc, re8139_reg);
453         return(rval);
454 }
455
456 static int
457 re_miibus_writereg(device_t dev, int phy, int reg, int data)
458 {
459         struct re_softc *sc= device_get_softc(dev);
460         u_int16_t re8139_reg = 0;
461
462         if (sc->re_type == RE_8169)
463                 return(re_gmii_writereg(dev, phy, reg, data));
464
465         /* Pretend the internal PHY is only at address 0 */
466         if (phy)
467                 return(0);
468
469         switch(reg) {
470         case MII_BMCR:
471                 re8139_reg = RE_BMCR;
472                 break;
473         case MII_BMSR:
474                 re8139_reg = RE_BMSR;
475                 break;
476         case MII_ANAR:
477                 re8139_reg = RE_ANAR;
478                 break;
479         case MII_ANER:
480                 re8139_reg = RE_ANER;
481                 break;
482         case MII_ANLPAR:
483                 re8139_reg = RE_LPAR;
484                 break;
485         case MII_PHYIDR1:
486         case MII_PHYIDR2:
487                 return(0);
488         default:
489                 device_printf(dev, "bad phy register\n");
490                 return(0);
491         }
492         CSR_WRITE_2(sc, re8139_reg, data);
493         return(0);
494 }
495
496 static void
497 re_miibus_statchg(device_t dev)
498 {
499 }
500
501 /*
502  * Program the 64-bit multicast hash filter.
503  */
504 static void
505 re_setmulti(struct re_softc *sc)
506 {
507         struct ifnet *ifp = &sc->arpcom.ac_if;
508         int h = 0;
509         uint32_t hashes[2] = { 0, 0 };
510         struct ifmultiaddr *ifma;
511         uint32_t rxfilt;
512         int mcnt = 0;
513
514         rxfilt = CSR_READ_4(sc, RE_RXCFG);
515
516         if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) {
517                 rxfilt |= RE_RXCFG_RX_MULTI;
518                 CSR_WRITE_4(sc, RE_RXCFG, rxfilt);
519                 CSR_WRITE_4(sc, RE_MAR0, 0xFFFFFFFF);
520                 CSR_WRITE_4(sc, RE_MAR4, 0xFFFFFFFF);
521                 return;
522         }
523
524         /* first, zot all the existing hash bits */
525         CSR_WRITE_4(sc, RE_MAR0, 0);
526         CSR_WRITE_4(sc, RE_MAR4, 0);
527
528         /* now program new ones */
529         LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
530                 if (ifma->ifma_addr->sa_family != AF_LINK)
531                         continue;
532                 h = ether_crc32_be(LLADDR((struct sockaddr_dl *)
533                     ifma->ifma_addr), ETHER_ADDR_LEN) >> 26;
534                 if (h < 32)
535                         hashes[0] |= (1 << h);
536                 else
537                         hashes[1] |= (1 << (h - 32));
538                 mcnt++;
539         }
540
541         if (mcnt)
542                 rxfilt |= RE_RXCFG_RX_MULTI;
543         else
544                 rxfilt &= ~RE_RXCFG_RX_MULTI;
545
546         CSR_WRITE_4(sc, RE_RXCFG, rxfilt);
547         CSR_WRITE_4(sc, RE_MAR0, hashes[0]);
548         CSR_WRITE_4(sc, RE_MAR4, hashes[1]);
549 }
550
551 static void
552 re_reset(struct re_softc *sc)
553 {
554         int i;
555
556         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_RESET);
557
558         for (i = 0; i < RE_TIMEOUT; i++) {
559                 DELAY(10);
560                 if ((CSR_READ_1(sc, RE_COMMAND) & RE_CMD_RESET) == 0)
561                         break;
562         }
563         if (i == RE_TIMEOUT)
564                 if_printf(&sc->arpcom.ac_if, "reset never completed!\n");
565
566         CSR_WRITE_1(sc, 0x82, 1);
567 }
568
569 /*
570  * The following routine is designed to test for a defect on some
571  * 32-bit 8169 cards. Some of these NICs have the REQ64# and ACK64#
572  * lines connected to the bus, however for a 32-bit only card, they
573  * should be pulled high. The result of this defect is that the
574  * NIC will not work right if you plug it into a 64-bit slot: DMA
575  * operations will be done with 64-bit transfers, which will fail
576  * because the 64-bit data lines aren't connected.
577  *
578  * There's no way to work around this (short of talking a soldering
579  * iron to the board), however we can detect it. The method we use
580  * here is to put the NIC into digital loopback mode, set the receiver
581  * to promiscuous mode, and then try to send a frame. We then compare
582  * the frame data we sent to what was received. If the data matches,
583  * then the NIC is working correctly, otherwise we know the user has
584  * a defective NIC which has been mistakenly plugged into a 64-bit PCI
585  * slot. In the latter case, there's no way the NIC can work correctly,
586  * so we print out a message on the console and abort the device attach.
587  */
588
589 static int
590 re_diag(struct re_softc *sc)
591 {
592         struct ifnet *ifp = &sc->arpcom.ac_if;
593         struct mbuf *m0;
594         struct ether_header *eh;
595         struct re_desc *cur_rx;
596         uint16_t status;
597         uint32_t rxstat;
598         int total_len, i, error = 0;
599         uint8_t dst[ETHER_ADDR_LEN] = { 0x00, 'h', 'e', 'l', 'l', 'o' };
600         uint8_t src[ETHER_ADDR_LEN] = { 0x00, 'w', 'o', 'r', 'l', 'd' };
601
602         /* Allocate a single mbuf */
603
604         MGETHDR(m0, MB_DONTWAIT, MT_DATA);
605         if (m0 == NULL)
606                 return(ENOBUFS);
607
608         /*
609          * Initialize the NIC in test mode. This sets the chip up
610          * so that it can send and receive frames, but performs the
611          * following special functions:
612          * - Puts receiver in promiscuous mode
613          * - Enables digital loopback mode
614          * - Leaves interrupts turned off
615          */
616
617         ifp->if_flags |= IFF_PROMISC;
618         sc->re_testmode = 1;
619         re_init(sc);
620         re_stop(sc);
621         DELAY(100000);
622         re_init(sc);
623
624         /* Put some data in the mbuf */
625
626         eh = mtod(m0, struct ether_header *);
627         bcopy (dst, eh->ether_dhost, ETHER_ADDR_LEN);
628         bcopy (src, eh->ether_shost, ETHER_ADDR_LEN);
629         eh->ether_type = htons(ETHERTYPE_IP);
630         m0->m_pkthdr.len = m0->m_len = ETHER_MIN_LEN - ETHER_CRC_LEN;
631
632         /*
633          * Queue the packet, start transmission.
634          * Note: ifq_handoff() ultimately calls re_start() for us.
635          */
636
637         CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
638         error = ifq_handoff(ifp, m0, NULL);
639         if (error) {
640                 m0 = NULL;
641                 goto done;
642         }
643         m0 = NULL;
644
645         /* Wait for it to propagate through the chip */
646
647         DELAY(100000);
648         for (i = 0; i < RE_TIMEOUT; i++) {
649                 status = CSR_READ_2(sc, RE_ISR);
650                 if ((status & (RE_ISR_TIMEOUT_EXPIRED|RE_ISR_RX_OK)) ==
651                     (RE_ISR_TIMEOUT_EXPIRED|RE_ISR_RX_OK))
652                         break;
653                 DELAY(10);
654         }
655
656         if (i == RE_TIMEOUT) {
657                 if_printf(ifp, "diagnostic failed to receive packet "
658                           "in loopback mode\n");
659                 error = EIO;
660                 goto done;
661         }
662
663         /*
664          * The packet should have been dumped into the first
665          * entry in the RX DMA ring. Grab it from there.
666          */
667
668         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
669                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
670         bus_dmamap_sync(sc->re_ldata.re_mtag, sc->re_ldata.re_rx_dmamap[0],
671                         BUS_DMASYNC_POSTWRITE);
672         bus_dmamap_unload(sc->re_ldata.re_mtag, sc->re_ldata.re_rx_dmamap[0]);
673
674         m0 = sc->re_ldata.re_rx_mbuf[0];
675         sc->re_ldata.re_rx_mbuf[0] = NULL;
676         eh = mtod(m0, struct ether_header *);
677
678         cur_rx = &sc->re_ldata.re_rx_list[0];
679         total_len = RE_RXBYTES(cur_rx);
680         rxstat = le32toh(cur_rx->re_cmdstat);
681
682         if (total_len != ETHER_MIN_LEN) {
683                 if_printf(ifp, "diagnostic failed, received short packet\n");
684                 error = EIO;
685                 goto done;
686         }
687
688         /* Test that the received packet data matches what we sent. */
689
690         if (bcmp(eh->ether_dhost, dst, ETHER_ADDR_LEN) ||
691             bcmp(eh->ether_shost, &src, ETHER_ADDR_LEN) ||
692             be16toh(eh->ether_type) != ETHERTYPE_IP) {
693                 if_printf(ifp, "WARNING, DMA FAILURE!\n");
694                 if_printf(ifp, "expected TX data: %6D/%6D/0x%x\n",
695                     dst, ":", src, ":", ETHERTYPE_IP);
696                 if_printf(ifp, "received RX data: %6D/%6D/0x%x\n",
697                     eh->ether_dhost, ":",  eh->ether_shost, ":",
698                     ntohs(eh->ether_type));
699                 if_printf(ifp, "You may have a defective 32-bit NIC plugged "
700                     "into a 64-bit PCI slot.\n");
701                 if_printf(ifp, "Please re-install the NIC in a 32-bit slot "
702                     "for proper operation.\n");
703                 if_printf(ifp, "Read the re(4) man page for more details.\n");
704                 error = EIO;
705         }
706
707 done:
708         /* Turn interface off, release resources */
709
710         sc->re_testmode = 0;
711         ifp->if_flags &= ~IFF_PROMISC;
712         re_stop(sc);
713         if (m0 != NULL)
714                 m_freem(m0);
715
716         return (error);
717 }
718
719 /*
720  * Probe for a RealTek 8139C+/8169/8110 chip. Check the PCI vendor and device
721  * IDs against our list and return a device name if we find a match.
722  */
723 static int
724 re_probe(device_t dev)
725 {
726         struct re_type *t;
727         struct re_softc *sc;
728         int rid;
729         uint32_t hwrev;
730         uint16_t vendor, product;
731
732         t = re_devs;
733
734         vendor = pci_get_vendor(dev);
735         product = pci_get_device(dev);
736
737         for (t = re_devs; t->re_name != NULL; t++) {
738                 if (product == t->re_did && vendor == t->re_vid)
739                         break;
740         }
741
742         /*
743          * Check if we found a RealTek device.
744          */
745         if (t->re_name == NULL)
746                 return(ENXIO);
747
748         /*
749          * Temporarily map the I/O space so we can read the chip ID register.
750          */
751         sc = malloc(sizeof(*sc), M_TEMP, M_WAITOK | M_ZERO);
752         rid = RE_PCI_LOIO;
753         sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
754                                             RF_ACTIVE);
755         if (sc->re_res == NULL) {
756                 device_printf(dev, "couldn't map ports/memory\n");
757                 free(sc, M_TEMP);
758                 return(ENXIO);
759         }
760
761         sc->re_btag = rman_get_bustag(sc->re_res);
762         sc->re_bhandle = rman_get_bushandle(sc->re_res);
763
764         hwrev = CSR_READ_4(sc, RE_TXCFG) & RE_TXCFG_HWREV;
765         bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO, sc->re_res);
766         free(sc, M_TEMP);
767
768         /*
769          * and continue matching for the specific chip...
770          */
771         for (; t->re_name != NULL; t++) {
772                 if (product == t->re_did && vendor == t->re_vid &&
773                     t->re_basetype == hwrev) {
774                         device_set_desc(dev, t->re_name);
775                         return(0);
776                 }
777         }
778         return(ENXIO);
779 }
780
781 /*
782  * This routine takes the segment list provided as the result of
783  * a bus_dma_map_load() operation and assigns the addresses/lengths
784  * to RealTek DMA descriptors. This can be called either by the RX
785  * code or the TX code. In the RX case, we'll probably wind up mapping
786  * at most one segment. For the TX case, there could be any number of
787  * segments since TX packets may span multiple mbufs. In either case,
788  * if the number of segments is larger than the re_maxsegs limit
789  * specified by the caller, we abort the mapping operation. Sadly,
790  * whoever designed the buffer mapping API did not provide a way to
791  * return an error from here, so we have to fake it a bit.
792  */
793
794 static void
795 re_dma_map_desc(void *arg, bus_dma_segment_t *segs, int nseg,
796                 bus_size_t mapsize, int error)
797 {
798         struct re_dmaload_arg *ctx;
799         struct re_desc *d = NULL;
800         int i = 0, idx;
801         uint32_t cmdstat;
802
803         if (error)
804                 return;
805
806         ctx = arg;
807
808         /* Signal error to caller if there's too many segments */
809         if (nseg > ctx->re_maxsegs) {
810                 ctx->re_maxsegs = 0;
811                 return;
812         }
813
814         /*
815          * Map the segment array into descriptors. Note that we set the
816          * start-of-frame and end-of-frame markers for either TX or RX, but
817          * they really only have meaning in the TX case. (In the RX case,
818          * it's the chip that tells us where packets begin and end.)
819          * We also keep track of the end of the ring and set the
820          * end-of-ring bits as needed, and we set the ownership bits
821          * in all except the very first descriptor. (The caller will
822          * set this descriptor later when it start transmission or
823          * reception.)
824          */
825         idx = ctx->re_idx;
826         for (;;) {
827                 d = &ctx->re_ring[idx];
828                 if (le32toh(d->re_cmdstat) & RE_RDESC_STAT_OWN) {
829                         ctx->re_maxsegs = 0;
830                         return;
831                 }
832                 cmdstat = segs[i].ds_len;
833                 d->re_bufaddr_lo = htole32(RE_ADDR_LO(segs[i].ds_addr));
834                 d->re_bufaddr_hi = htole32(RE_ADDR_HI(segs[i].ds_addr));
835                 if (i == 0)
836                         cmdstat |= RE_TDESC_CMD_SOF;
837                 else
838                         cmdstat |= RE_TDESC_CMD_OWN;
839                 if (idx == (RE_RX_DESC_CNT - 1))
840                         cmdstat |= RE_TDESC_CMD_EOR;
841                 d->re_cmdstat = htole32(cmdstat | ctx->re_flags);
842                 i++;
843                 if (i == nseg)
844                         break;
845                 RE_DESC_INC(idx);
846         }
847
848         d->re_cmdstat |= htole32(RE_TDESC_CMD_EOF);
849         ctx->re_maxsegs = nseg;
850         ctx->re_idx = idx;
851 }
852
853 /*
854  * Map a single buffer address.
855  */
856
857 static void
858 re_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
859 {
860         uint32_t *addr;
861
862         if (error)
863                 return;
864
865         KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
866         addr = arg;
867         *addr = segs->ds_addr;
868 }
869
870 static int
871 re_allocmem(device_t dev, struct re_softc *sc)
872 {
873         int error, i, nseg;
874
875         /*
876          * Allocate map for RX mbufs.
877          */
878         nseg = 32;
879         error = bus_dma_tag_create(sc->re_parent_tag, ETHER_ALIGN, 0,
880             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
881             NULL, MCLBYTES * nseg, nseg, MCLBYTES, BUS_DMA_ALLOCNOW,
882             &sc->re_ldata.re_mtag);
883         if (error) {
884                 device_printf(dev, "could not allocate dma tag\n");
885                 return(error);
886         }
887
888         /*
889          * Allocate map for TX descriptor list.
890          */
891         error = bus_dma_tag_create(sc->re_parent_tag, RE_RING_ALIGN,
892             0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
893             NULL, RE_TX_LIST_SZ, 1, RE_TX_LIST_SZ, BUS_DMA_ALLOCNOW,
894             &sc->re_ldata.re_tx_list_tag);
895         if (error) {
896                 device_printf(dev, "could not allocate dma tag\n");
897                 return(error);
898         }
899
900         /* Allocate DMA'able memory for the TX ring */
901
902         error = bus_dmamem_alloc(sc->re_ldata.re_tx_list_tag,
903             (void **)&sc->re_ldata.re_tx_list, BUS_DMA_WAITOK | BUS_DMA_ZERO,
904             &sc->re_ldata.re_tx_list_map);
905         if (error) {
906                 device_printf(dev, "could not allocate TX ring\n");
907                 return(error);
908         }
909
910         /* Load the map for the TX ring. */
911
912         error = bus_dmamap_load(sc->re_ldata.re_tx_list_tag,
913              sc->re_ldata.re_tx_list_map, sc->re_ldata.re_tx_list,
914              RE_TX_LIST_SZ, re_dma_map_addr,
915              &sc->re_ldata.re_tx_list_addr, BUS_DMA_NOWAIT);
916         if (error) {
917                 device_printf(dev, "could not get addres of TX ring\n");
918                 return(error);
919         }
920
921         /* Create DMA maps for TX buffers */
922
923         for (i = 0; i < RE_TX_DESC_CNT; i++) {
924                 error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
925                             &sc->re_ldata.re_tx_dmamap[i]);
926                 if (error) {
927                         device_printf(dev, "can't create DMA map for TX\n");
928                         return(error);
929                 }
930         }
931
932         /*
933          * Allocate map for RX descriptor list.
934          */
935         error = bus_dma_tag_create(sc->re_parent_tag, RE_RING_ALIGN,
936             0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
937             NULL, RE_TX_LIST_SZ, 1, RE_TX_LIST_SZ, BUS_DMA_ALLOCNOW,
938             &sc->re_ldata.re_rx_list_tag);
939         if (error) {
940                 device_printf(dev, "could not allocate dma tag\n");
941                 return(error);
942         }
943
944         /* Allocate DMA'able memory for the RX ring */
945
946         error = bus_dmamem_alloc(sc->re_ldata.re_rx_list_tag,
947             (void **)&sc->re_ldata.re_rx_list, BUS_DMA_WAITOK | BUS_DMA_ZERO,
948             &sc->re_ldata.re_rx_list_map);
949         if (error) {
950                 device_printf(dev, "could not allocate RX ring\n");
951                 return(error);
952         }
953
954         /* Load the map for the RX ring. */
955
956         error = bus_dmamap_load(sc->re_ldata.re_rx_list_tag,
957              sc->re_ldata.re_rx_list_map, sc->re_ldata.re_rx_list,
958              RE_TX_LIST_SZ, re_dma_map_addr,
959              &sc->re_ldata.re_rx_list_addr, BUS_DMA_NOWAIT);
960         if (error) {
961                 device_printf(dev, "could not get address of RX ring\n");
962                 return(error);
963         }
964
965         /* Create DMA maps for RX buffers */
966
967         for (i = 0; i < RE_RX_DESC_CNT; i++) {
968                 error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
969                             &sc->re_ldata.re_rx_dmamap[i]);
970                 if (error) {
971                         device_printf(dev, "can't create DMA map for RX\n");
972                         return(ENOMEM);
973                 }
974         }
975
976         return(0);
977 }
978
979 /*
980  * Attach the interface. Allocate softc structures, do ifmedia
981  * setup and ethernet/BPF attach.
982  */
983 static int
984 re_attach(device_t dev)
985 {
986         struct re_softc *sc = device_get_softc(dev);
987         struct ifnet *ifp;
988         struct re_hwrev *hw_rev;
989         uint8_t eaddr[ETHER_ADDR_LEN];
990         int hwrev;
991         u_int16_t re_did = 0;
992         int error = 0, rid, i;
993
994         callout_init(&sc->re_timer);
995
996 #ifndef BURN_BRIDGES
997         /*
998          * Handle power management nonsense.
999          */
1000
1001         if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
1002                 uint32_t membase, irq;
1003
1004                 /* Save important PCI config data. */
1005                 membase = pci_read_config(dev, RE_PCI_LOMEM, 4);
1006                 irq = pci_read_config(dev, PCIR_INTLINE, 4);
1007
1008                 /* Reset the power state. */
1009                 device_printf(dev, "chip is is in D%d power mode "
1010                     "-- setting to D0\n", pci_get_powerstate(dev));
1011
1012                 pci_set_powerstate(dev, PCI_POWERSTATE_D0);
1013
1014                 /* Restore PCI config data. */
1015                 pci_write_config(dev, RE_PCI_LOMEM, membase, 4);
1016                 pci_write_config(dev, PCIR_INTLINE, irq, 4);
1017         }
1018 #endif
1019         /*
1020          * Map control/status registers.
1021          */
1022         pci_enable_busmaster(dev);
1023
1024         rid = RE_PCI_LOIO;
1025         sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
1026                                             RF_ACTIVE);
1027
1028         if (sc->re_res == NULL) {
1029                 device_printf(dev, "couldn't map ports/memory\n");
1030                 error = ENXIO;
1031                 goto fail;
1032         }
1033
1034         sc->re_btag = rman_get_bustag(sc->re_res);
1035         sc->re_bhandle = rman_get_bushandle(sc->re_res);
1036
1037         /* Allocate interrupt */
1038         rid = 0;
1039         sc->re_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1040                                             RF_SHAREABLE | RF_ACTIVE);
1041
1042         if (sc->re_irq == NULL) {
1043                 device_printf(dev, "couldn't map interrupt\n");
1044                 error = ENXIO;
1045                 goto fail;
1046         }
1047
1048         /* Reset the adapter. */
1049         re_reset(sc);
1050
1051         hwrev = CSR_READ_4(sc, RE_TXCFG) & RE_TXCFG_HWREV;
1052         for (hw_rev = re_hwrevs; hw_rev->re_desc != NULL; hw_rev++) {
1053                 if (hw_rev->re_rev == hwrev) {
1054                         sc->re_type = hw_rev->re_type;
1055                         break;
1056                 }
1057         }
1058
1059         if (sc->re_type == RE_8169) {
1060                 /* Set RX length mask */
1061                 sc->re_rxlenmask = RE_RDESC_STAT_GFRAGLEN;
1062
1063                 /* Force station address autoload from the EEPROM */
1064                 CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_AUTOLOAD);
1065                 for (i = 0; i < RE_TIMEOUT; i++) {
1066                         if ((CSR_READ_1(sc, RE_EECMD) & RE_EEMODE_AUTOLOAD) == 0)
1067                                 break;
1068                         DELAY(100);
1069                 }
1070                 if (i == RE_TIMEOUT)
1071                         device_printf(dev, "eeprom autoload timed out\n");
1072
1073                 for (i = 0; i < ETHER_ADDR_LEN; i++)
1074                         eaddr[i] = CSR_READ_1(sc, RE_IDR0 + i);
1075         } else {
1076                 uint16_t as[3];
1077
1078                 /* Set RX length mask */
1079                 sc->re_rxlenmask = RE_RDESC_STAT_FRAGLEN;
1080
1081                 sc->re_eecmd_read = RE_EECMD_READ_6BIT;
1082                 re_read_eeprom(sc, (caddr_t)&re_did, 0, 1, 0);
1083                 if (re_did != 0x8129)
1084                         sc->re_eecmd_read = RE_EECMD_READ_8BIT;
1085
1086                 /*
1087                  * Get station address from the EEPROM.
1088                  */
1089                 re_read_eeprom(sc, (caddr_t)as, RE_EE_EADDR, 3, 0);
1090                 for (i = 0; i < 3; i++) {
1091                         eaddr[(i * 2) + 0] = as[i] & 0xff;
1092                         eaddr[(i * 2) + 1] = as[i] >> 8;
1093                 }
1094         }
1095
1096         /*
1097          * Allocate the parent bus DMA tag appropriate for PCI.
1098          */
1099 #define RE_NSEG_NEW 32
1100         error = bus_dma_tag_create(NULL,        /* parent */
1101                         1, 0,                   /* alignment, boundary */
1102                         BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1103                         BUS_SPACE_MAXADDR,      /* highaddr */
1104                         NULL, NULL,             /* filter, filterarg */
1105                         MAXBSIZE, RE_NSEG_NEW,  /* maxsize, nsegments */
1106                         BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
1107                         BUS_DMA_ALLOCNOW,       /* flags */
1108                         &sc->re_parent_tag);
1109         if (error)
1110                 goto fail;
1111
1112         error = re_allocmem(dev, sc);
1113
1114         if (error)
1115                 goto fail;
1116
1117         /* Do MII setup */
1118         if (mii_phy_probe(dev, &sc->re_miibus,
1119             re_ifmedia_upd, re_ifmedia_sts)) {
1120                 device_printf(dev, "MII without any phy!\n");
1121                 error = ENXIO;
1122                 goto fail;
1123         }
1124
1125         ifp = &sc->arpcom.ac_if;
1126         ifp->if_softc = sc;
1127         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1128         ifp->if_mtu = ETHERMTU;
1129         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1130         ifp->if_ioctl = re_ioctl;
1131         ifp->if_capabilities = IFCAP_VLAN_MTU;
1132         ifp->if_start = re_start;
1133         ifp->if_capabilities |= IFCAP_HWCSUM|IFCAP_VLAN_HWTAGGING;
1134 #ifdef DEVICE_POLLING
1135         ifp->if_capabilities |= IFCAP_POLLING;
1136 #endif
1137         ifp->if_watchdog = re_watchdog;
1138         ifp->if_init = re_init;
1139         if (sc->re_type == RE_8169)
1140                 ifp->if_baudrate = 1000000000;
1141         else
1142                 ifp->if_baudrate = 100000000;
1143         ifq_set_maxlen(&ifp->if_snd, RE_IFQ_MAXLEN);
1144         ifq_set_ready(&ifp->if_snd);
1145 #ifdef RE_DISABLE_HWCSUM
1146         ifp->if_capenable = ifp->if_capabilities & ~IFCAP_HWCSUM;
1147         ifp->if_hwassist = 0;
1148 #else
1149         ifp->if_capenable = ifp->if_capabilities;
1150         ifp->if_hwassist = RE_CSUM_FEATURES;
1151 #endif
1152
1153         /*
1154          * Call MI attach routine.
1155          */
1156         ether_ifattach(ifp, eaddr);
1157
1158         /* Perform hardware diagnostic. */
1159         error = re_diag(sc);
1160
1161         if (error) {
1162                 device_printf(dev, "hardware diagnostic failure\n");
1163                 ether_ifdetach(ifp);
1164                 goto fail;
1165         }
1166
1167         /* Hook interrupt last to avoid having to lock softc */
1168         error = bus_setup_intr(dev, sc->re_irq, INTR_TYPE_NET, re_intr, sc,
1169                                &sc->re_intrhand);
1170
1171         if (error) {
1172                 device_printf(dev, "couldn't set up irq\n");
1173                 ether_ifdetach(ifp);
1174                 goto fail;
1175         }
1176
1177 fail:
1178         if (error)
1179                 re_detach(dev);
1180
1181         return (error);
1182 }
1183
1184 /*
1185  * Shutdown hardware and free up resources. This can be called any
1186  * time after the mutex has been initialized. It is called in both
1187  * the error case in attach and the normal detach case so it needs
1188  * to be careful about only freeing resources that have actually been
1189  * allocated.
1190  */
1191 static int
1192 re_detach(device_t dev)
1193 {
1194         struct re_softc *sc = device_get_softc(dev);
1195         struct ifnet *ifp = &sc->arpcom.ac_if;
1196         int i, s;
1197
1198         s = splimp();
1199
1200         /* These should only be active if attach succeeded */
1201         if (device_is_attached(dev)) {
1202                 re_stop(sc);
1203                 ether_ifdetach(ifp);
1204         }
1205         if (sc->re_miibus)
1206                 device_delete_child(dev, sc->re_miibus);
1207         bus_generic_detach(dev);
1208
1209         if (sc->re_intrhand)
1210                 bus_teardown_intr(dev, sc->re_irq, sc->re_intrhand);
1211         if (sc->re_irq)
1212                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->re_irq);
1213         if (sc->re_res)
1214                 bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO,
1215                                      sc->re_res);
1216
1217         /* Unload and free the RX DMA ring memory and map */
1218
1219         if (sc->re_ldata.re_rx_list_tag) {
1220                 bus_dmamap_unload(sc->re_ldata.re_rx_list_tag,
1221                     sc->re_ldata.re_rx_list_map);
1222                 bus_dmamem_free(sc->re_ldata.re_rx_list_tag,
1223                     sc->re_ldata.re_rx_list,
1224                     sc->re_ldata.re_rx_list_map);
1225                 bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1226         }
1227
1228         /* Unload and free the TX DMA ring memory and map */
1229
1230         if (sc->re_ldata.re_tx_list_tag) {
1231                 bus_dmamap_unload(sc->re_ldata.re_tx_list_tag,
1232                     sc->re_ldata.re_tx_list_map);
1233                 bus_dmamem_free(sc->re_ldata.re_tx_list_tag,
1234                     sc->re_ldata.re_tx_list,
1235                     sc->re_ldata.re_tx_list_map);
1236                 bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
1237         }
1238
1239         /* Destroy all the RX and TX buffer maps */
1240
1241         if (sc->re_ldata.re_mtag) {
1242                 for (i = 0; i < RE_TX_DESC_CNT; i++)
1243                         bus_dmamap_destroy(sc->re_ldata.re_mtag,
1244                             sc->re_ldata.re_tx_dmamap[i]);
1245                 for (i = 0; i < RE_RX_DESC_CNT; i++)
1246                         bus_dmamap_destroy(sc->re_ldata.re_mtag,
1247                             sc->re_ldata.re_rx_dmamap[i]);
1248                 bus_dma_tag_destroy(sc->re_ldata.re_mtag);
1249         }
1250
1251         /* Unload and free the stats buffer and map */
1252
1253         if (sc->re_ldata.re_stag) {
1254                 bus_dmamap_unload(sc->re_ldata.re_stag,
1255                     sc->re_ldata.re_rx_list_map);
1256                 bus_dmamem_free(sc->re_ldata.re_stag,
1257                     sc->re_ldata.re_stats,
1258                     sc->re_ldata.re_smap);
1259                 bus_dma_tag_destroy(sc->re_ldata.re_stag);
1260         }
1261
1262         if (sc->re_parent_tag)
1263                 bus_dma_tag_destroy(sc->re_parent_tag);
1264
1265         splx(s);
1266
1267         return(0);
1268 }
1269
1270 static int
1271 re_newbuf(struct re_softc *sc, int idx, struct mbuf *m)
1272 {
1273         struct re_dmaload_arg arg;
1274         struct mbuf *n = NULL;
1275         int error;
1276
1277         if (m == NULL) {
1278                 n = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
1279                 if (n == NULL)
1280                         return(ENOBUFS);
1281                 m = n;
1282         } else
1283                 m->m_data = m->m_ext.ext_buf;
1284
1285         /*
1286          * Initialize mbuf length fields and fixup
1287          * alignment so that the frame payload is
1288          * longword aligned.
1289          */
1290         m->m_len = m->m_pkthdr.len = MCLBYTES;
1291         m_adj(m, ETHER_ALIGN);
1292
1293         arg.sc = sc;
1294         arg.re_idx = idx;
1295         arg.re_maxsegs = 1;
1296         arg.re_flags = 0;
1297         arg.re_ring = sc->re_ldata.re_rx_list;
1298
1299         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag,
1300             sc->re_ldata.re_rx_dmamap[idx], m, re_dma_map_desc,
1301             &arg, BUS_DMA_NOWAIT);
1302         if (error || arg.re_maxsegs != 1) {
1303                 if (n != NULL)
1304                         m_freem(n);
1305                 return (ENOMEM);
1306         }
1307
1308         sc->re_ldata.re_rx_list[idx].re_cmdstat |= htole32(RE_RDESC_CMD_OWN);
1309         sc->re_ldata.re_rx_mbuf[idx] = m;
1310
1311         bus_dmamap_sync(sc->re_ldata.re_mtag, sc->re_ldata.re_rx_dmamap[idx],
1312                         BUS_DMASYNC_PREREAD);
1313
1314         return(0);
1315 }
1316
1317 static int
1318 re_tx_list_init(struct re_softc *sc)
1319 {
1320         bzero(sc->re_ldata.re_tx_list, RE_TX_LIST_SZ);
1321         bzero(&sc->re_ldata.re_tx_mbuf, RE_TX_DESC_CNT * sizeof(struct mbuf *));
1322
1323         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1324                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
1325         sc->re_ldata.re_tx_prodidx = 0;
1326         sc->re_ldata.re_tx_considx = 0;
1327         sc->re_ldata.re_tx_free = RE_TX_DESC_CNT;
1328
1329         return(0);
1330 }
1331
1332 static int
1333 re_rx_list_init(struct re_softc *sc)
1334 {
1335         int i, error;
1336
1337         bzero(sc->re_ldata.re_rx_list, RE_RX_LIST_SZ);
1338         bzero(&sc->re_ldata.re_rx_mbuf, RE_RX_DESC_CNT * sizeof(struct mbuf *));
1339
1340         for (i = 0; i < RE_RX_DESC_CNT; i++) {
1341                 error = re_newbuf(sc, i, NULL);
1342                 if (error)
1343                         return(error);
1344         }
1345
1346         /* Flush the RX descriptors */
1347
1348         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1349             sc->re_ldata.re_rx_list_map,
1350             BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
1351
1352         sc->re_ldata.re_rx_prodidx = 0;
1353         sc->re_head = sc->re_tail = NULL;
1354
1355         return(0);
1356 }
1357
1358 /*
1359  * RX handler for C+ and 8169. For the gigE chips, we support
1360  * the reception of jumbo frames that have been fragmented
1361  * across multiple 2K mbuf cluster buffers.
1362  */
1363 static void
1364 re_rxeof(struct re_softc *sc)
1365 {
1366         struct ifnet *ifp = &sc->arpcom.ac_if;
1367         struct mbuf *m;
1368         struct re_desc  *cur_rx;
1369         uint32_t rxstat, rxvlan;
1370         int i, total_len;
1371
1372         /* Invalidate the descriptor memory */
1373
1374         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1375                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
1376
1377         for (i = sc->re_ldata.re_rx_prodidx;
1378              RE_OWN(&sc->re_ldata.re_rx_list[i]) == 0 ; RE_DESC_INC(i)) {
1379                 cur_rx = &sc->re_ldata.re_rx_list[i];
1380                 m = sc->re_ldata.re_rx_mbuf[i];
1381                 total_len = RE_RXBYTES(cur_rx);
1382                 rxstat = le32toh(cur_rx->re_cmdstat);
1383                 rxvlan = le32toh(cur_rx->re_vlanctl);
1384
1385                 /* Invalidate the RX mbuf and unload its map */
1386
1387                 bus_dmamap_sync(sc->re_ldata.re_mtag,
1388                                 sc->re_ldata.re_rx_dmamap[i],
1389                                 BUS_DMASYNC_POSTWRITE);
1390                 bus_dmamap_unload(sc->re_ldata.re_mtag,
1391                                   sc->re_ldata.re_rx_dmamap[i]);
1392
1393                 if ((rxstat & RE_RDESC_STAT_EOF) == 0) {
1394                         m->m_len = MCLBYTES - ETHER_ALIGN;
1395                         if (sc->re_head == NULL) {
1396                                 sc->re_head = sc->re_tail = m;
1397                         } else {
1398                                 m->m_flags &= ~M_PKTHDR;
1399                                 sc->re_tail->m_next = m;
1400                                 sc->re_tail = m;
1401                         }
1402                         re_newbuf(sc, i, NULL);
1403                         continue;
1404                 }
1405
1406                 /*
1407                  * NOTE: for the 8139C+, the frame length field
1408                  * is always 12 bits in size, but for the gigE chips,
1409                  * it is 13 bits (since the max RX frame length is 16K).
1410                  * Unfortunately, all 32 bits in the status word
1411                  * were already used, so to make room for the extra
1412                  * length bit, RealTek took out the 'frame alignment
1413                  * error' bit and shifted the other status bits
1414                  * over one slot. The OWN, EOR, FS and LS bits are
1415                  * still in the same places. We have already extracted
1416                  * the frame length and checked the OWN bit, so rather
1417                  * than using an alternate bit mapping, we shift the
1418                  * status bits one space to the right so we can evaluate
1419                  * them using the 8169 status as though it was in the
1420                  * same format as that of the 8139C+.
1421                  */
1422                 if (sc->re_type == RE_8169)
1423                         rxstat >>= 1;
1424
1425                 if (rxstat & RE_RDESC_STAT_RXERRSUM) {
1426                         ifp->if_ierrors++;
1427                         /*
1428                          * If this is part of a multi-fragment packet,
1429                          * discard all the pieces.
1430                          */
1431                         if (sc->re_head != NULL) {
1432                                 m_freem(sc->re_head);
1433                                 sc->re_head = sc->re_tail = NULL;
1434                         }
1435                         re_newbuf(sc, i, m);
1436                         continue;
1437                 }
1438
1439                 /*
1440                  * If allocating a replacement mbuf fails,
1441                  * reload the current one.
1442                  */
1443
1444                 if (re_newbuf(sc, i, NULL)) {
1445                         ifp->if_ierrors++;
1446                         if (sc->re_head != NULL) {
1447                                 m_freem(sc->re_head);
1448                                 sc->re_head = sc->re_tail = NULL;
1449                         }
1450                         re_newbuf(sc, i, m);
1451                         continue;
1452                 }
1453
1454                 if (sc->re_head != NULL) {
1455                         m->m_len = total_len % (MCLBYTES - ETHER_ALIGN);
1456                         /* 
1457                          * Special case: if there's 4 bytes or less
1458                          * in this buffer, the mbuf can be discarded:
1459                          * the last 4 bytes is the CRC, which we don't
1460                          * care about anyway.
1461                          */
1462                         if (m->m_len <= ETHER_CRC_LEN) {
1463                                 sc->re_tail->m_len -=
1464                                     (ETHER_CRC_LEN - m->m_len);
1465                                 m_freem(m);
1466                         } else {
1467                                 m->m_len -= ETHER_CRC_LEN;
1468                                 m->m_flags &= ~M_PKTHDR;
1469                                 sc->re_tail->m_next = m;
1470                         }
1471                         m = sc->re_head;
1472                         sc->re_head = sc->re_tail = NULL;
1473                         m->m_pkthdr.len = total_len - ETHER_CRC_LEN;
1474                 } else
1475                         m->m_pkthdr.len = m->m_len =
1476                             (total_len - ETHER_CRC_LEN);
1477
1478                 ifp->if_ipackets++;
1479                 m->m_pkthdr.rcvif = ifp;
1480
1481                 /* Do RX checksumming if enabled */
1482
1483                 if (ifp->if_capenable & IFCAP_RXCSUM) {
1484
1485                         /* Check IP header checksum */
1486                         if (rxstat & RE_RDESC_STAT_PROTOID)
1487                                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
1488                         if ((rxstat & RE_RDESC_STAT_IPSUMBAD) == 0)
1489                                 m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1490
1491                         /* Check TCP/UDP checksum */
1492                         if ((RE_TCPPKT(rxstat) &&
1493                             (rxstat & RE_RDESC_STAT_TCPSUMBAD) == 0) ||
1494                             (RE_UDPPKT(rxstat) &&
1495                             (rxstat & RE_RDESC_STAT_UDPSUMBAD)) == 0) {
1496                                 m->m_pkthdr.csum_flags |=
1497                                     CSUM_DATA_VALID|CSUM_PSEUDO_HDR;
1498                                 m->m_pkthdr.csum_data = 0xffff;
1499                         }
1500                 }
1501
1502                 if (rxvlan & RE_RDESC_VLANCTL_TAG)
1503                         VLAN_INPUT_TAG(m,
1504                            be16toh((rxvlan & RE_RDESC_VLANCTL_DATA)));
1505                 else
1506                         (*ifp->if_input)(ifp, m);
1507         }
1508
1509         /* Flush the RX DMA ring */
1510
1511         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1512                         sc->re_ldata.re_rx_list_map,
1513                         BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
1514
1515         sc->re_ldata.re_rx_prodidx = i;
1516 }
1517
1518 static void
1519 re_txeof(struct re_softc *sc)
1520 {
1521         struct ifnet *ifp = &sc->arpcom.ac_if;
1522         uint32_t txstat;
1523         int idx;
1524
1525         /* Invalidate the TX descriptor list */
1526
1527         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1528             sc->re_ldata.re_tx_list_map,
1529             BUS_DMASYNC_POSTREAD);
1530
1531         for (idx = sc->re_ldata.re_tx_considx;
1532              idx != sc->re_ldata.re_tx_prodidx; RE_DESC_INC(idx)) {
1533                 txstat = le32toh(sc->re_ldata.re_tx_list[idx].re_cmdstat);
1534                 if (txstat & RE_TDESC_CMD_OWN)
1535                         break;
1536
1537                 /*
1538                  * We only stash mbufs in the last descriptor
1539                  * in a fragment chain, which also happens to
1540                  * be the only place where the TX status bits
1541                  * are valid.
1542                  */
1543                 if (txstat & RE_TDESC_CMD_EOF) {
1544                         m_freem(sc->re_ldata.re_tx_mbuf[idx]);
1545                         sc->re_ldata.re_tx_mbuf[idx] = NULL;
1546                         bus_dmamap_unload(sc->re_ldata.re_mtag,
1547                             sc->re_ldata.re_tx_dmamap[idx]);
1548                         if (txstat & (RE_TDESC_STAT_EXCESSCOL|
1549                             RE_TDESC_STAT_COLCNT))
1550                                 ifp->if_collisions++;
1551                         if (txstat & RE_TDESC_STAT_TXERRSUM)
1552                                 ifp->if_oerrors++;
1553                         else
1554                                 ifp->if_opackets++;
1555                 }
1556                 sc->re_ldata.re_tx_free++;
1557         }
1558
1559         /* No changes made to the TX ring, so no flush needed */
1560         if (idx != sc->re_ldata.re_tx_considx) {
1561                 sc->re_ldata.re_tx_considx = idx;
1562                 ifp->if_flags &= ~IFF_OACTIVE;
1563                 ifp->if_timer = 0;
1564         }
1565
1566         /*
1567          * If not all descriptors have been released reaped yet,
1568          * reload the timer so that we will eventually get another
1569          * interrupt that will cause us to re-enter this routine.
1570          * This is done in case the transmitter has gone idle.
1571          */
1572         if (sc->re_ldata.re_tx_free != RE_TX_DESC_CNT)
1573                 CSR_WRITE_4(sc, RE_TIMERCNT, 1);
1574 }
1575
1576 static void
1577 re_tick(void *xsc)
1578 {
1579         struct re_softc *sc = xsc;
1580         struct mii_data *mii;
1581         int s;
1582
1583         s = splimp();
1584
1585         mii = device_get_softc(sc->re_miibus);
1586         mii_tick(mii);
1587
1588         callout_reset(&sc->re_timer, hz, re_tick, sc);
1589         splx(s);
1590 }
1591
1592 #ifdef DEVICE_POLLING
1593 static void
1594 re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1595 {
1596         struct re_softc *sc = ifp->if_softc;
1597
1598         if ((ifp->if_capenable & IFCAP_POLLING) == 0) {
1599                 ether_poll_deregister(ifp);
1600                 cmd = POLL_DEREGISTER;
1601         }
1602         if (cmd == POLL_DEREGISTER) { /* final call, enable interrupts */
1603                 CSR_WRITE_2(sc, RE_IMR, RE_INTRS_CPLUS);
1604                 return;
1605         }
1606
1607         sc->rxcycles = count;
1608         re_rxeof(sc);
1609         re_txeof(sc);
1610
1611         if (!ifq_is_empty(&ifp->if_snd))
1612                 (*ifp->if_start)(ifp);
1613
1614         if (cmd == POLL_AND_CHECK_STATUS) { /* also check status register */
1615                 uint16_t       status;
1616
1617                 status = CSR_READ_2(sc, RE_ISR);
1618                 if (status == 0xffff)
1619                         return;
1620                 if (status)
1621                         CSR_WRITE_2(sc, RE_ISR, status);
1622
1623                 /*
1624                  * XXX check behaviour on receiver stalls.
1625                  */
1626
1627                 if (status & RE_ISR_SYSTEM_ERR) {
1628                         re_reset(sc);
1629                         re_init(sc);
1630                 }
1631         }
1632 }
1633 #endif /* DEVICE_POLLING */
1634
1635 static void
1636 re_intr(void *arg)
1637 {
1638         struct re_softc *sc = arg;
1639         struct ifnet *ifp = &sc->arpcom.ac_if;
1640         uint16_t status;
1641         int s;
1642
1643         if (sc->suspended || (ifp->if_flags & IFF_UP) == 0)
1644                 return;
1645
1646 #ifdef DEVICE_POLLING
1647         if  (ifp->if_flags & IFF_POLLING)
1648                 return;
1649         if ((ifp->if_capenable & IFCAP_POLLING) &&
1650             ether_poll_register(re_poll, ifp)) { /* ok, disable interrupts */
1651                 CSR_WRITE_2(sc, RE_IMR, 0x0000);
1652                 re_poll(ifp, 0, 1);
1653                 return;
1654         }
1655 #endif /* DEVICE_POLLING */
1656
1657         s = splimp();
1658
1659         for (;;) {
1660                 status = CSR_READ_2(sc, RE_ISR);
1661                 /* If the card has gone away the read returns 0xffff. */
1662                 if (status == 0xffff)
1663                         break;
1664                 if (status)
1665                         CSR_WRITE_2(sc, RE_ISR, status);
1666
1667                 if ((status & RE_INTRS_CPLUS) == 0)
1668                         break;
1669
1670                 if (status & RE_ISR_RX_OK)
1671                         re_rxeof(sc);
1672
1673                 if (status & RE_ISR_RX_ERR)
1674                         re_rxeof(sc);
1675
1676                 if ((status & RE_ISR_TIMEOUT_EXPIRED) ||
1677                     (status & RE_ISR_TX_ERR) ||
1678                     (status & RE_ISR_TX_DESC_UNAVAIL))
1679                         re_txeof(sc);
1680
1681                 if (status & RE_ISR_SYSTEM_ERR) {
1682                         re_reset(sc);
1683                         re_init(sc);
1684                 }
1685
1686                 if (status & RE_ISR_LINKCHG)
1687                         re_tick(sc);
1688         }
1689
1690         if (!ifq_is_empty(&ifp->if_snd))
1691                 (*ifp->if_start)(ifp);
1692
1693         splx(s);
1694 }
1695
1696 static int
1697 re_encap(struct re_softc *sc, struct mbuf **m_head, int *idx, int *called_defrag)
1698 {
1699         struct ifnet *ifp = &sc->arpcom.ac_if;
1700         struct mbuf *m, *m_new = NULL;
1701         struct re_dmaload_arg   arg;
1702         bus_dmamap_t            map;
1703         int                     error;
1704
1705         *called_defrag = 0;
1706         if (sc->re_ldata.re_tx_free <= 4)
1707                 return(EFBIG);
1708
1709         m = *m_head;
1710
1711         /*
1712          * Set up checksum offload. Note: checksum offload bits must
1713          * appear in all descriptors of a multi-descriptor transmit
1714          * attempt. (This is according to testing done with an 8169
1715          * chip. I'm not sure if this is a requirement or a bug.)
1716          */
1717
1718         arg.re_flags = 0;
1719
1720         if (m->m_pkthdr.csum_flags & CSUM_IP)
1721                 arg.re_flags |= RE_TDESC_CMD_IPCSUM;
1722         if (m->m_pkthdr.csum_flags & CSUM_TCP)
1723                 arg.re_flags |= RE_TDESC_CMD_TCPCSUM;
1724         if (m->m_pkthdr.csum_flags & CSUM_UDP)
1725                 arg.re_flags |= RE_TDESC_CMD_UDPCSUM;
1726
1727         arg.sc = sc;
1728         arg.re_idx = *idx;
1729         arg.re_maxsegs = sc->re_ldata.re_tx_free;
1730         if (arg.re_maxsegs > 4)
1731                 arg.re_maxsegs -= 4;
1732         arg.re_ring = sc->re_ldata.re_tx_list;
1733
1734         map = sc->re_ldata.re_tx_dmamap[*idx];
1735         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map,
1736             m, re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1737
1738         if (error && error != EFBIG) {
1739                 if_printf(ifp, "can't map mbuf (error %d)\n", error);
1740                 return(ENOBUFS);
1741         }
1742
1743         /* Too many segments to map, coalesce into a single mbuf */
1744
1745         if (error || arg.re_maxsegs == 0) {
1746                 m_new = m_defrag_nofree(m, MB_DONTWAIT);
1747                 if (m_new == NULL)
1748                         return(1);
1749                 else {
1750                         m = m_new;
1751                         *m_head = m;
1752                 }
1753
1754                 *called_defrag = 1;
1755                 arg.sc = sc;
1756                 arg.re_idx = *idx;
1757                 arg.re_maxsegs = sc->re_ldata.re_tx_free;
1758                 arg.re_ring = sc->re_ldata.re_tx_list;
1759
1760                 error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map,
1761                     m, re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1762                 if (error) {
1763                         m_freem(m);
1764                         if_printf(ifp, "can't map mbuf (error %d)\n", error);
1765                         return(EFBIG);
1766                 }
1767         }
1768
1769         /*
1770          * Insure that the map for this transmission
1771          * is placed at the array index of the last descriptor
1772          * in this chain.
1773          */
1774         sc->re_ldata.re_tx_dmamap[*idx] =
1775             sc->re_ldata.re_tx_dmamap[arg.re_idx];
1776         sc->re_ldata.re_tx_dmamap[arg.re_idx] = map;
1777
1778         sc->re_ldata.re_tx_mbuf[arg.re_idx] = m;
1779         sc->re_ldata.re_tx_free -= arg.re_maxsegs;
1780
1781         /*
1782          * Set up hardware VLAN tagging. Note: vlan tag info must
1783          * appear in the first descriptor of a multi-descriptor
1784          * transmission attempt.
1785          */
1786
1787         if ((m->m_flags & (M_PROTO1|M_PKTHDR)) == (M_PROTO1|M_PKTHDR) &&
1788             m->m_pkthdr.rcvif != NULL &&
1789             m->m_pkthdr.rcvif->if_type == IFT_L2VLAN) {
1790                 struct ifvlan *ifv;
1791                 ifv = m->m_pkthdr.rcvif->if_softc;
1792                 if (ifv != NULL)
1793                         sc->re_ldata.re_tx_list[*idx].re_vlanctl =
1794                             htole32(htobe16(ifv->ifv_tag) | RE_TDESC_VLANCTL_TAG);
1795         }
1796
1797         /* Transfer ownership of packet to the chip. */
1798
1799         sc->re_ldata.re_tx_list[arg.re_idx].re_cmdstat |=
1800             htole32(RE_TDESC_CMD_OWN);
1801         if (*idx != arg.re_idx)
1802                 sc->re_ldata.re_tx_list[*idx].re_cmdstat |=
1803                     htole32(RE_TDESC_CMD_OWN);
1804
1805         RE_DESC_INC(arg.re_idx);
1806         *idx = arg.re_idx;
1807
1808         return(0);
1809 }
1810
1811 /*
1812  * Main transmit routine for C+ and gigE NICs.
1813  */
1814
1815 static void
1816 re_start(struct ifnet *ifp)
1817 {
1818         struct re_softc *sc = ifp->if_softc;
1819         struct mbuf *m_head = NULL, *m_head2;
1820         int called_defrag, idx, s;
1821
1822         s = splimp();
1823
1824         idx = sc->re_ldata.re_tx_prodidx;
1825
1826         while (sc->re_ldata.re_tx_mbuf[idx] == NULL) {
1827                 m_head = ifq_poll(&ifp->if_snd);
1828                 if (m_head == NULL)
1829                         break;
1830
1831                 if (re_encap(sc, &m_head, &idx, &called_defrag)) {
1832                         if (called_defrag) {
1833                                 m_head2 = ifq_dequeue(&ifp->if_snd);
1834                                 m_freem(m_head2);
1835                         }
1836                         ifp->if_flags |= IFF_OACTIVE;
1837                         break;
1838                 }
1839
1840                 m_head2 = ifq_dequeue(&ifp->if_snd);
1841                 if (called_defrag)
1842                         m_freem(m_head2);
1843
1844                 /*
1845                  * If there's a BPF listener, bounce a copy of this frame
1846                  * to him.
1847                  */
1848                 BPF_MTAP(ifp, m_head);
1849         }
1850
1851         /* Flush the TX descriptors */
1852         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1853                         sc->re_ldata.re_tx_list_map,
1854                         BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
1855
1856         sc->re_ldata.re_tx_prodidx = idx;
1857
1858         /*
1859          * RealTek put the TX poll request register in a different
1860          * location on the 8169 gigE chip. I don't know why.
1861          */
1862         if (sc->re_type == RE_8169)
1863                 CSR_WRITE_2(sc, RE_GTXSTART, RE_TXSTART_START);
1864         else
1865                 CSR_WRITE_2(sc, RE_TXSTART, RE_TXSTART_START);
1866
1867         /*
1868          * Use the countdown timer for interrupt moderation.
1869          * 'TX done' interrupts are disabled. Instead, we reset the
1870          * countdown timer, which will begin counting until it hits
1871          * the value in the TIMERINT register, and then trigger an
1872          * interrupt. Each time we write to the TIMERCNT register,
1873          * the timer count is reset to 0.
1874          */
1875         CSR_WRITE_4(sc, RE_TIMERCNT, 1);
1876
1877         splx(s);
1878
1879         /*
1880          * Set a timeout in case the chip goes out to lunch.
1881          */
1882         ifp->if_timer = 5;
1883 }
1884
1885 static void
1886 re_init(void *xsc)
1887 {
1888         struct re_softc *sc = xsc;
1889         struct ifnet *ifp = &sc->arpcom.ac_if;
1890         struct mii_data *mii;
1891         uint32_t rxcfg = 0;
1892         int s;
1893
1894         s = splimp();
1895         mii = device_get_softc(sc->re_miibus);
1896
1897         /*
1898          * Cancel pending I/O and free all RX/TX buffers.
1899          */
1900         re_stop(sc);
1901
1902         /*
1903          * Enable C+ RX and TX mode, as well as VLAN stripping and
1904          * RX checksum offload. We must configure the C+ register
1905          * before all others.
1906          */
1907         CSR_WRITE_2(sc, RE_CPLUS_CMD, RE_CPLUSCMD_RXENB | RE_CPLUSCMD_TXENB |
1908                     RE_CPLUSCMD_PCI_MRW | RE_CPLUSCMD_VLANSTRIP |
1909                     (ifp->if_capenable & IFCAP_RXCSUM ?
1910                      RE_CPLUSCMD_RXCSUM_ENB : 0));
1911
1912         /*
1913          * Init our MAC address.  Even though the chipset
1914          * documentation doesn't mention it, we need to enter "Config
1915          * register write enable" mode to modify the ID registers.
1916          */
1917         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_WRITECFG);
1918         CSR_WRITE_STREAM_4(sc, RE_IDR0,
1919             *(u_int32_t *)(&sc->arpcom.ac_enaddr[0]));
1920         CSR_WRITE_STREAM_4(sc, RE_IDR4,
1921             *(u_int32_t *)(&sc->arpcom.ac_enaddr[4]));
1922         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_OFF);
1923
1924         /*
1925          * For C+ mode, initialize the RX descriptors and mbufs.
1926          */
1927         re_rx_list_init(sc);
1928         re_tx_list_init(sc);
1929
1930         /*
1931          * Enable transmit and receive.
1932          */
1933         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
1934
1935         /*
1936          * Set the initial TX and RX configuration.
1937          */
1938         if (sc->re_testmode) {
1939                 if (sc->re_type == RE_8169)
1940                         CSR_WRITE_4(sc, RE_TXCFG,
1941                                     RE_TXCFG_CONFIG | RE_LOOPTEST_ON);
1942                 else
1943                         CSR_WRITE_4(sc, RE_TXCFG,
1944                                     RE_TXCFG_CONFIG | RE_LOOPTEST_ON_CPLUS);
1945         } else
1946                 CSR_WRITE_4(sc, RE_TXCFG, RE_TXCFG_CONFIG);
1947         CSR_WRITE_4(sc, RE_RXCFG, RE_RXCFG_CONFIG);
1948
1949         /* Set the individual bit to receive frames for this host only. */
1950         rxcfg = CSR_READ_4(sc, RE_RXCFG);
1951         rxcfg |= RE_RXCFG_RX_INDIV;
1952
1953         /* If we want promiscuous mode, set the allframes bit. */
1954         if (ifp->if_flags & IFF_PROMISC) {
1955                 rxcfg |= RE_RXCFG_RX_ALLPHYS;
1956                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
1957         } else {
1958                 rxcfg &= ~RE_RXCFG_RX_ALLPHYS;
1959                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
1960         }
1961
1962         /*
1963          * Set capture broadcast bit to capture broadcast frames.
1964          */
1965         if (ifp->if_flags & IFF_BROADCAST) {
1966                 rxcfg |= RE_RXCFG_RX_BROAD;
1967                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
1968         } else {
1969                 rxcfg &= ~RE_RXCFG_RX_BROAD;
1970                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
1971         }
1972
1973         /*
1974          * Program the multicast filter, if necessary.
1975          */
1976         re_setmulti(sc);
1977
1978 #ifdef DEVICE_POLLING
1979         /*
1980          * Disable interrupts if we are polling.
1981          */
1982         if (ifp->if_flags & IFF_POLLING)
1983                 CSR_WRITE_2(sc, RE_IMR, 0);
1984         else    /* otherwise ... */
1985 #endif /* DEVICE_POLLING */
1986         /*
1987          * Enable interrupts.
1988          */
1989         if (sc->re_testmode)
1990                 CSR_WRITE_2(sc, RE_IMR, 0);
1991         else
1992                 CSR_WRITE_2(sc, RE_IMR, RE_INTRS_CPLUS);
1993
1994         /* Set initial TX threshold */
1995         sc->re_txthresh = RE_TX_THRESH_INIT;
1996
1997         /* Start RX/TX process. */
1998         CSR_WRITE_4(sc, RE_MISSEDPKT, 0);
1999 #ifdef notdef
2000         /* Enable receiver and transmitter. */
2001         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2002 #endif
2003         /*
2004          * Load the addresses of the RX and TX lists into the chip.
2005          */
2006
2007         CSR_WRITE_4(sc, RE_RXLIST_ADDR_HI,
2008             RE_ADDR_HI(sc->re_ldata.re_rx_list_addr));
2009         CSR_WRITE_4(sc, RE_RXLIST_ADDR_LO,
2010             RE_ADDR_LO(sc->re_ldata.re_rx_list_addr));
2011
2012         CSR_WRITE_4(sc, RE_TXLIST_ADDR_HI,
2013             RE_ADDR_HI(sc->re_ldata.re_tx_list_addr));
2014         CSR_WRITE_4(sc, RE_TXLIST_ADDR_LO,
2015             RE_ADDR_LO(sc->re_ldata.re_tx_list_addr));
2016
2017         CSR_WRITE_1(sc, RE_EARLY_TX_THRESH, 16);
2018
2019         /*
2020          * Initialize the timer interrupt register so that
2021          * a timer interrupt will be generated once the timer
2022          * reaches a certain number of ticks. The timer is
2023          * reloaded on each transmit. This gives us TX interrupt
2024          * moderation, which dramatically improves TX frame rate.
2025          */
2026
2027         if (sc->re_type == RE_8169)
2028                 CSR_WRITE_4(sc, RE_TIMERINT_8169, 0x800);
2029         else
2030                 CSR_WRITE_4(sc, RE_TIMERINT, 0x400);
2031
2032         /*
2033          * For 8169 gigE NICs, set the max allowed RX packet
2034          * size so we can receive jumbo frames.
2035          */
2036         if (sc->re_type == RE_8169)
2037                 CSR_WRITE_2(sc, RE_MAXRXPKTLEN, 16383);
2038
2039         if (sc->re_testmode) {
2040                 splx(s);
2041                 return;
2042         }
2043
2044         mii_mediachg(mii);
2045
2046         CSR_WRITE_1(sc, RE_CFG1, RE_CFG1_DRVLOAD|RE_CFG1_FULLDUPLEX);
2047
2048         ifp->if_flags |= IFF_RUNNING;
2049         ifp->if_flags &= ~IFF_OACTIVE;
2050
2051         callout_reset(&sc->re_timer, hz, re_tick, sc);
2052         splx(s);
2053 }
2054
2055 /*
2056  * Set media options.
2057  */
2058 static int
2059 re_ifmedia_upd(struct ifnet *ifp)
2060 {
2061         struct re_softc *sc = ifp->if_softc;
2062         struct mii_data *mii;
2063
2064         mii = device_get_softc(sc->re_miibus);
2065         mii_mediachg(mii);
2066
2067         return(0);
2068 }
2069
2070 /*
2071  * Report current media status.
2072  */
2073 static void
2074 re_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2075 {
2076         struct re_softc *sc = ifp->if_softc;
2077         struct mii_data *mii;
2078
2079         mii = device_get_softc(sc->re_miibus);
2080
2081         mii_pollstat(mii);
2082         ifmr->ifm_active = mii->mii_media_active;
2083         ifmr->ifm_status = mii->mii_media_status;
2084 }
2085
2086 static int
2087 re_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
2088 {
2089         struct re_softc *sc = ifp->if_softc;
2090         struct ifreq *ifr = (struct ifreq *) data;
2091         struct mii_data *mii;
2092         int error = 0, s;
2093
2094         s = splimp();
2095
2096         switch(command) {
2097         case SIOCSIFMTU:
2098                 if (ifr->ifr_mtu > RE_JUMBO_MTU)
2099                         error = EINVAL;
2100                 ifp->if_mtu = ifr->ifr_mtu;
2101                 break;
2102         case SIOCSIFFLAGS:
2103                 if (ifp->if_flags & IFF_UP)
2104                         re_init(sc);
2105                 else if (ifp->if_flags & IFF_RUNNING)
2106                                 re_stop(sc);
2107                 error = 0;
2108                 break;
2109         case SIOCADDMULTI:
2110         case SIOCDELMULTI:
2111                 re_setmulti(sc);
2112                 error = 0;
2113                 break;
2114         case SIOCGIFMEDIA:
2115         case SIOCSIFMEDIA:
2116                 mii = device_get_softc(sc->re_miibus);
2117                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
2118                 break;
2119         case SIOCSIFCAP:
2120                 ifp->if_capenable &= ~(IFCAP_HWCSUM | IFCAP_POLLING);
2121                 ifp->if_capenable |=
2122                     ifr->ifr_reqcap & (IFCAP_HWCSUM | IFCAP_POLLING);
2123                 if (ifp->if_capenable & IFCAP_TXCSUM)
2124                         ifp->if_hwassist = RE_CSUM_FEATURES;
2125                 else
2126                         ifp->if_hwassist = 0;
2127                 if (ifp->if_flags & IFF_RUNNING)
2128                         re_init(sc);
2129                 break;
2130         default:
2131                 error = ether_ioctl(ifp, command, data);
2132                 break;
2133         }
2134
2135         splx(s);
2136
2137         return(error);
2138 }
2139
2140 static void
2141 re_watchdog(struct ifnet *ifp)
2142 {
2143         struct re_softc *sc = ifp->if_softc;
2144         int s;
2145
2146         s = splimp();
2147         if_printf(ifp, "watchdog timeout\n");
2148         ifp->if_oerrors++;
2149
2150         re_txeof(sc);
2151         re_rxeof(sc);
2152
2153         re_init(sc);
2154
2155         splx(s);
2156 }
2157
2158 /*
2159  * Stop the adapter and free any mbufs allocated to the
2160  * RX and TX lists.
2161  */
2162 static void
2163 re_stop(struct re_softc *sc)
2164 {
2165         struct ifnet *ifp = &sc->arpcom.ac_if;
2166         int i, s;
2167
2168         s = splimp();
2169         ifp->if_timer = 0;
2170         callout_stop(&sc->re_timer);
2171
2172         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2173 #ifdef DEVICE_POLLING
2174         ether_poll_deregister(ifp);
2175 #endif /* DEVICE_POLLING */
2176
2177         CSR_WRITE_1(sc, RE_COMMAND, 0x00);
2178         CSR_WRITE_2(sc, RE_IMR, 0x0000);
2179
2180         if (sc->re_head != NULL) {
2181                 m_freem(sc->re_head);
2182                 sc->re_head = sc->re_tail = NULL;
2183         }
2184
2185         /* Free the TX list buffers. */
2186         for (i = 0; i < RE_TX_DESC_CNT; i++) {
2187                 if (sc->re_ldata.re_tx_mbuf[i] != NULL) {
2188                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2189                                           sc->re_ldata.re_tx_dmamap[i]);
2190                         m_freem(sc->re_ldata.re_tx_mbuf[i]);
2191                         sc->re_ldata.re_tx_mbuf[i] = NULL;
2192                 }
2193         }
2194
2195         /* Free the RX list buffers. */
2196         for (i = 0; i < RE_RX_DESC_CNT; i++) {
2197                 if (sc->re_ldata.re_rx_mbuf[i] != NULL) {
2198                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2199                                           sc->re_ldata.re_rx_dmamap[i]);
2200                         m_freem(sc->re_ldata.re_rx_mbuf[i]);
2201                         sc->re_ldata.re_rx_mbuf[i] = NULL;
2202                 }
2203         }
2204
2205         splx(s);
2206 }
2207
2208 /*
2209  * Device suspend routine.  Stop the interface and save some PCI
2210  * settings in case the BIOS doesn't restore them properly on
2211  * resume.
2212  */
2213 static int
2214 re_suspend(device_t dev)
2215 {
2216 #ifndef BURN_BRIDGES
2217         int i;
2218 #endif
2219         struct re_softc *sc = device_get_softc(dev);
2220
2221         re_stop(sc);
2222
2223 #ifndef BURN_BRIDGES
2224         for (i = 0; i < 5; i++)
2225                 sc->saved_maps[i] = pci_read_config(dev, PCIR_MAPS + i * 4, 4);
2226         sc->saved_biosaddr = pci_read_config(dev, PCIR_BIOS, 4);
2227         sc->saved_intline = pci_read_config(dev, PCIR_INTLINE, 1);
2228         sc->saved_cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
2229         sc->saved_lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
2230 #endif
2231
2232         sc->suspended = 1;
2233
2234         return (0);
2235 }
2236
2237 /*
2238  * Device resume routine.  Restore some PCI settings in case the BIOS
2239  * doesn't, re-enable busmastering, and restart the interface if
2240  * appropriate.
2241  */
2242 static int
2243 re_resume(device_t dev)
2244 {
2245         struct re_softc *sc = device_get_softc(dev);
2246         struct ifnet *ifp = &sc->arpcom.ac_if;
2247 #ifndef BURN_BRIDGES
2248         int i;
2249 #endif
2250
2251 #ifndef BURN_BRIDGES
2252         /* better way to do this? */
2253         for (i = 0; i < 5; i++)
2254                 pci_write_config(dev, PCIR_MAPS + i * 4, sc->saved_maps[i], 4);
2255         pci_write_config(dev, PCIR_BIOS, sc->saved_biosaddr, 4);
2256         pci_write_config(dev, PCIR_INTLINE, sc->saved_intline, 1);
2257         pci_write_config(dev, PCIR_CACHELNSZ, sc->saved_cachelnsz, 1);
2258         pci_write_config(dev, PCIR_LATTIMER, sc->saved_lattimer, 1);
2259
2260         /* reenable busmastering */
2261         pci_enable_busmaster(dev);
2262         pci_enable_io(dev, SYS_RES_IOPORT);
2263 #endif
2264
2265         /* reinitialize interface if necessary */
2266         if (ifp->if_flags & IFF_UP)
2267                 re_init(sc);
2268
2269         sc->suspended = 0;
2270
2271         return (0);
2272 }
2273
2274 /*
2275  * Stop all chip I/O so that the kernel's probe routines don't
2276  * get confused by errant DMAs when rebooting.
2277  */
2278 static void
2279 re_shutdown(device_t dev)
2280 {
2281         struct re_softc *sc = device_get_softc(dev);
2282
2283         re_stop(sc);
2284 }