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