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