f5b953822cf79adc7bd6bc82c1c924211d154e4e
[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.60 2008/10/03 14:14:10 sephe Exp $
37  */
38
39 /*
40  * RealTek 8139C+/8169/8169S/8110S/8168/8111/8101E 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  * seven devices in this family: the RTL8139C+, the RTL8169, the RTL8169S,
51  * RTL8110S, the RTL8168, the RTL8111 and the RTL8101E.
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 7440, so the max MTU possible with this
111  * driver is 7422 bytes.
112  */
113
114 #define _IP_VHL
115
116 #include "opt_polling.h"
117
118 #include <sys/param.h>
119 #include <sys/bus.h>
120 #include <sys/endian.h>
121 #include <sys/kernel.h>
122 #include <sys/in_cksum.h>
123 #include <sys/interrupt.h>
124 #include <sys/malloc.h>
125 #include <sys/mbuf.h>
126 #include <sys/rman.h>
127 #include <sys/serialize.h>
128 #include <sys/socket.h>
129 #include <sys/sockio.h>
130 #include <sys/sysctl.h>
131
132 #include <net/bpf.h>
133 #include <net/ethernet.h>
134 #include <net/if.h>
135 #include <net/ifq_var.h>
136 #include <net/if_arp.h>
137 #include <net/if_dl.h>
138 #include <net/if_media.h>
139 #include <net/if_types.h>
140 #include <net/vlan/if_vlan_var.h>
141 #include <net/vlan/if_vlan_ether.h>
142
143 #include <netinet/ip.h>
144
145 #include <dev/netif/mii_layer/mii.h>
146 #include <dev/netif/mii_layer/miivar.h>
147
148 #include <bus/pci/pcidevs.h>
149 #include <bus/pci/pcireg.h>
150 #include <bus/pci/pcivar.h>
151
152 /* "device miibus" required.  See GENERIC if you get errors here. */
153 #include "miibus_if.h"
154
155 #include <dev/netif/re/if_rereg.h>
156 #include <dev/netif/re/if_revar.h>
157
158 #define RE_CSUM_FEATURES    (CSUM_IP | CSUM_TCP | CSUM_UDP)
159 #if 0
160 #define RE_DISABLE_HWCSUM
161 #endif
162
163 /*
164  * Various supported device vendors/types and their names.
165  */
166 static const struct re_type re_devs[] = {
167         { PCI_VENDOR_DLINK, PCI_PRODUCT_DLINK_DGE528T, RE_HWREV_8169S,
168                 "D-Link DGE-528(T) Gigabit Ethernet Adapter" },
169         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8139, RE_HWREV_8139CPLUS,
170                 "RealTek 8139C+ 10/100BaseTX" },
171         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8101E, RE_HWREV_8101E,
172                 "RealTek 8101E PCIe 10/100baseTX" },
173         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8101E, RE_HWREV_8102EL,
174                 "RealTek 8102EL PCIe 10/100baseTX" },
175         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168, RE_HWREV_8168_SPIN1,
176                 "RealTek 8168/8111B PCIe Gigabit Ethernet" },
177         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168, RE_HWREV_8168_SPIN2,
178                 "RealTek 8168/8111B PCIe Gigabit Ethernet" },
179         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168, RE_HWREV_8168_SPIN3,
180                 "RealTek 8168B/8111B PCIe Gigabit Ethernet" },
181         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168, RE_HWREV_8168C,
182                 "RealTek 8168C/8111C PCIe Gigabit Ethernet" },
183         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8169,
184                 "RealTek 8169 Gigabit Ethernet" },
185         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8169S,
186                 "RealTek 8169S Single-chip Gigabit Ethernet" },
187         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8169_8110SB,
188                 "RealTek 8169SB/8110SB Single-chip Gigabit Ethernet" },
189         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8169_8110SC,
190                 "RealTek 8169SC/8110SC Single-chip Gigabit Ethernet" },
191         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169SC, RE_HWREV_8169_8110SC,
192                 "RealTek 8169SC/8110SC Single-chip Gigabit Ethernet" },
193         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8110S,
194                 "RealTek 8110S Single-chip Gigabit Ethernet" },
195         { PCI_VENDOR_COREGA, PCI_PRODUCT_COREGA_CG_LAPCIGT, RE_HWREV_8169S,
196                 "Corega CG-LAPCIGT Gigabit Ethernet" },
197         { PCI_VENDOR_LINKSYS, PCI_PRODUCT_LINKSYS_EG1032, RE_HWREV_8169S,
198                 "Linksys EG1032 Gigabit Ethernet" },
199         { PCI_VENDOR_USR2, PCI_PRODUCT_USR2_997902, RE_HWREV_8169S,
200                 "US Robotics 997902 Gigabit Ethernet" },
201         { 0, 0, 0, NULL }
202 };
203
204 static const struct re_hwrev re_hwrevs[] = {
205         { RE_HWREV_8139CPLUS,   RE_8139CPLUS,   RE_F_HASMPC,    0, "C+" },
206         { RE_HWREV_8168_SPIN1,  RE_8169,        RE_F_PCIE,      0, "8168" },
207         { RE_HWREV_8168_SPIN2,  RE_8169,
208           RE_F_PCIE | RE_F_JUMBO_SWCSUM, RE_SWCSUM_LIM_8168B, "8168" },
209         { RE_HWREV_8168_SPIN3,  RE_8169,        RE_F_PCIE,      0, "8168" },
210         { RE_HWREV_8168C,       RE_8169,        RE_F_PCIE,      0, "8168C" },
211         { RE_HWREV_8169,        RE_8169,
212           RE_F_HASMPC | RE_F_JUMBO_SWCSUM, RE_SWCSUM_LIM_8169, "8169" },
213         { RE_HWREV_8169S,       RE_8169,        RE_F_HASMPC,    0, "8169S" },
214         { RE_HWREV_8110S,       RE_8169,        RE_F_HASMPC,    0, "8110S" },
215         { RE_HWREV_8169_8110SB, RE_8169,        RE_F_HASMPC,    0, "8169SB" },
216         { RE_HWREV_8169_8110SC, RE_8169,        0,              0, "8169SC" },
217         { RE_HWREV_8100E,       RE_8169,        RE_F_HASMPC,    0, "8100E" },
218         { RE_HWREV_8101E,       RE_8169,        RE_F_PCIE,      0, "8101E" },
219         { RE_HWREV_8102EL,      RE_8169,        RE_F_PCIE,      0, "8102EL" },
220         { 0, 0, 0, 0, NULL }
221 };
222
223 static int      re_probe(device_t);
224 static int      re_attach(device_t);
225 static int      re_detach(device_t);
226 static int      re_suspend(device_t);
227 static int      re_resume(device_t);
228 static void     re_shutdown(device_t);
229
230 static void     re_dma_map_addr(void *, bus_dma_segment_t *, int, int);
231 static void     re_dma_map_desc(void *, bus_dma_segment_t *, int,
232                                 bus_size_t, int);
233 static int      re_allocmem(device_t);
234 static void     re_freemem(device_t);
235 static void     re_freebufmem(struct re_softc *, int, int);
236 static int      re_encap(struct re_softc *, struct mbuf **, int *);
237 static int      re_newbuf(struct re_softc *, int, int);
238 static void     re_setup_rxdesc(struct re_softc *, int);
239 static int      re_rx_list_init(struct re_softc *);
240 static int      re_tx_list_init(struct re_softc *);
241 static void     re_rxeof(struct re_softc *);
242 static void     re_txeof(struct re_softc *);
243 static void     re_intr(void *);
244 static void     re_tick(void *);
245 static void     re_tick_serialized(void *);
246
247 static void     re_start(struct ifnet *);
248 static int      re_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
249 static void     re_init(void *);
250 static void     re_stop(struct re_softc *);
251 static void     re_watchdog(struct ifnet *);
252 static int      re_ifmedia_upd(struct ifnet *);
253 static void     re_ifmedia_sts(struct ifnet *, struct ifmediareq *);
254
255 static void     re_eeprom_putbyte(struct re_softc *, int);
256 static void     re_eeprom_getword(struct re_softc *, int, u_int16_t *);
257 static void     re_read_eeprom(struct re_softc *, caddr_t, int, int);
258 static int      re_gmii_readreg(device_t, int, int);
259 static int      re_gmii_writereg(device_t, int, int, int);
260
261 static int      re_miibus_readreg(device_t, int, int);
262 static int      re_miibus_writereg(device_t, int, int, int);
263 static void     re_miibus_statchg(device_t);
264
265 static void     re_setmulti(struct re_softc *);
266 static void     re_reset(struct re_softc *);
267 static int      re_pad_frame(struct mbuf *);
268
269 #ifdef RE_DIAG
270 static int      re_diag(struct re_softc *);
271 #endif
272
273 #ifdef DEVICE_POLLING
274 static void     re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count);
275 #endif
276
277 static int      re_sysctl_tx_moderation(SYSCTL_HANDLER_ARGS);
278
279 static device_method_t re_methods[] = {
280         /* Device interface */
281         DEVMETHOD(device_probe,         re_probe),
282         DEVMETHOD(device_attach,        re_attach),
283         DEVMETHOD(device_detach,        re_detach),
284         DEVMETHOD(device_suspend,       re_suspend),
285         DEVMETHOD(device_resume,        re_resume),
286         DEVMETHOD(device_shutdown,      re_shutdown),
287
288         /* bus interface */
289         DEVMETHOD(bus_print_child,      bus_generic_print_child),
290         DEVMETHOD(bus_driver_added,     bus_generic_driver_added),
291
292         /* MII interface */
293         DEVMETHOD(miibus_readreg,       re_miibus_readreg),
294         DEVMETHOD(miibus_writereg,      re_miibus_writereg),
295         DEVMETHOD(miibus_statchg,       re_miibus_statchg),
296
297         { 0, 0 }
298 };
299
300 static driver_t re_driver = {
301         "re",
302         re_methods,
303         sizeof(struct re_softc)
304 };
305
306 static devclass_t re_devclass;
307
308 DECLARE_DUMMY_MODULE(if_re);
309 DRIVER_MODULE(if_re, pci, re_driver, re_devclass, 0, 0);
310 DRIVER_MODULE(if_re, cardbus, re_driver, re_devclass, 0, 0);
311 DRIVER_MODULE(miibus, re, miibus_driver, miibus_devclass, 0, 0);
312
313 #define EE_SET(x)       \
314         CSR_WRITE_1(sc, RE_EECMD, CSR_READ_1(sc, RE_EECMD) | (x))
315
316 #define EE_CLR(x)       \
317         CSR_WRITE_1(sc, RE_EECMD, CSR_READ_1(sc, RE_EECMD) & ~(x))
318
319 static __inline void
320 re_free_rxchain(struct re_softc *sc)
321 {
322         if (sc->re_head != NULL) {
323                 m_freem(sc->re_head);
324                 sc->re_head = sc->re_tail = NULL;
325         }
326 }
327
328 /*
329  * Send a read command and address to the EEPROM, check for ACK.
330  */
331 static void
332 re_eeprom_putbyte(struct re_softc *sc, int addr)
333 {
334         int d, i;
335
336         d = addr | (RE_9346_READ << sc->re_eewidth);
337
338         /*
339          * Feed in each bit and strobe the clock.
340          */
341         for (i = 1 << (sc->re_eewidth + 3); i; i >>= 1) {
342                 if (d & i)
343                         EE_SET(RE_EE_DATAIN);
344                 else
345                         EE_CLR(RE_EE_DATAIN);
346                 DELAY(100);
347                 EE_SET(RE_EE_CLK);
348                 DELAY(150);
349                 EE_CLR(RE_EE_CLK);
350                 DELAY(100);
351         }
352 }
353
354 /*
355  * Read a word of data stored in the EEPROM at address 'addr.'
356  */
357 static void
358 re_eeprom_getword(struct re_softc *sc, int addr, uint16_t *dest)
359 {
360         int i;
361         uint16_t word = 0;
362
363         /*
364          * Send address of word we want to read.
365          */
366         re_eeprom_putbyte(sc, addr);
367
368         /*
369          * Start reading bits from EEPROM.
370          */
371         for (i = 0x8000; i != 0; i >>= 1) {
372                 EE_SET(RE_EE_CLK);
373                 DELAY(100);
374                 if (CSR_READ_1(sc, RE_EECMD) & RE_EE_DATAOUT)
375                         word |= i;
376                 EE_CLR(RE_EE_CLK);
377                 DELAY(100);
378         }
379
380         *dest = word;
381 }
382
383 /*
384  * Read a sequence of words from the EEPROM.
385  */
386 static void
387 re_read_eeprom(struct re_softc *sc, caddr_t dest, int off, int cnt)
388 {
389         int i;
390         uint16_t word = 0, *ptr;
391
392         CSR_SETBIT_1(sc, RE_EECMD, RE_EEMODE_PROGRAM);
393         DELAY(100);
394
395         for (i = 0; i < cnt; i++) {
396                 CSR_SETBIT_1(sc, RE_EECMD, RE_EE_SEL);
397                 re_eeprom_getword(sc, off + i, &word);
398                 CSR_CLRBIT_1(sc, RE_EECMD, RE_EE_SEL);
399                 ptr = (uint16_t *)(dest + (i * 2));
400                 *ptr = word;
401         }
402
403         CSR_CLRBIT_1(sc, RE_EECMD, RE_EEMODE_PROGRAM);
404 }
405
406 static int
407 re_gmii_readreg(device_t dev, int phy, int reg)
408 {
409         struct re_softc *sc = device_get_softc(dev);
410         u_int32_t rval;
411         int i;
412
413         if (phy != 1)
414                 return(0);
415
416         /* Let the rgephy driver read the GMEDIASTAT register */
417
418         if (reg == RE_GMEDIASTAT)
419                 return(CSR_READ_1(sc, RE_GMEDIASTAT));
420
421         CSR_WRITE_4(sc, RE_PHYAR, reg << 16);
422         DELAY(1000);
423
424         for (i = 0; i < RE_TIMEOUT; i++) {
425                 rval = CSR_READ_4(sc, RE_PHYAR);
426                 if (rval & RE_PHYAR_BUSY)
427                         break;
428                 DELAY(100);
429         }
430
431         if (i == RE_TIMEOUT) {
432                 device_printf(dev, "PHY read failed\n");
433                 return(0);
434         }
435
436         return(rval & RE_PHYAR_PHYDATA);
437 }
438
439 static int
440 re_gmii_writereg(device_t dev, int phy, int reg, int data)
441 {
442         struct re_softc *sc = device_get_softc(dev);
443         uint32_t rval;
444         int i;
445
446         CSR_WRITE_4(sc, RE_PHYAR,
447                     (reg << 16) | (data & RE_PHYAR_PHYDATA) | RE_PHYAR_BUSY);
448         DELAY(1000);
449
450         for (i = 0; i < RE_TIMEOUT; i++) {
451                 rval = CSR_READ_4(sc, RE_PHYAR);
452                 if ((rval & RE_PHYAR_BUSY) == 0)
453                         break;
454                 DELAY(100);
455         }
456
457         if (i == RE_TIMEOUT)
458                 device_printf(dev, "PHY write failed\n");
459
460         return(0);
461 }
462
463 static int
464 re_miibus_readreg(device_t dev, int phy, int reg)
465 {
466         struct re_softc *sc = device_get_softc(dev);
467         uint16_t rval = 0;
468         uint16_t re8139_reg = 0;
469
470         if (sc->re_type == RE_8169) {
471                 rval = re_gmii_readreg(dev, phy, reg);
472                 return(rval);
473         }
474
475         /* Pretend the internal PHY is only at address 0 */
476         if (phy)
477                 return(0);
478
479         switch(reg) {
480         case MII_BMCR:
481                 re8139_reg = RE_BMCR;
482                 break;
483         case MII_BMSR:
484                 re8139_reg = RE_BMSR;
485                 break;
486         case MII_ANAR:
487                 re8139_reg = RE_ANAR;
488                 break;
489         case MII_ANER:
490                 re8139_reg = RE_ANER;
491                 break;
492         case MII_ANLPAR:
493                 re8139_reg = RE_LPAR;
494                 break;
495         case MII_PHYIDR1:
496         case MII_PHYIDR2:
497                 return(0);
498         /*
499          * Allow the rlphy driver to read the media status
500          * register. If we have a link partner which does not
501          * support NWAY, this is the register which will tell
502          * us the results of parallel detection.
503          */
504         case RE_MEDIASTAT:
505                 return(CSR_READ_1(sc, RE_MEDIASTAT));
506         default:
507                 device_printf(dev, "bad phy register\n");
508                 return(0);
509         }
510         rval = CSR_READ_2(sc, re8139_reg);
511         if (sc->re_type == RE_8139CPLUS && re8139_reg == RE_BMCR) {
512                 /* 8139C+ has different bit layout. */
513                 rval &= ~(BMCR_LOOP | BMCR_ISO);
514         }
515         return(rval);
516 }
517
518 static int
519 re_miibus_writereg(device_t dev, int phy, int reg, int data)
520 {
521         struct re_softc *sc= device_get_softc(dev);
522         u_int16_t re8139_reg = 0;
523
524         if (sc->re_type == RE_8169)
525                 return(re_gmii_writereg(dev, phy, reg, data));
526
527         /* Pretend the internal PHY is only at address 0 */
528         if (phy)
529                 return(0);
530
531         switch(reg) {
532         case MII_BMCR:
533                 re8139_reg = RE_BMCR;
534                 if (sc->re_type == RE_8139CPLUS) {
535                         /* 8139C+ has different bit layout. */
536                         data &= ~(BMCR_LOOP | BMCR_ISO);
537                 }
538                 break;
539         case MII_BMSR:
540                 re8139_reg = RE_BMSR;
541                 break;
542         case MII_ANAR:
543                 re8139_reg = RE_ANAR;
544                 break;
545         case MII_ANER:
546                 re8139_reg = RE_ANER;
547                 break;
548         case MII_ANLPAR:
549                 re8139_reg = RE_LPAR;
550                 break;
551         case MII_PHYIDR1:
552         case MII_PHYIDR2:
553                 return(0);
554         default:
555                 device_printf(dev, "bad phy register\n");
556                 return(0);
557         }
558         CSR_WRITE_2(sc, re8139_reg, data);
559         return(0);
560 }
561
562 static void
563 re_miibus_statchg(device_t dev)
564 {
565 }
566
567 /*
568  * Program the 64-bit multicast hash filter.
569  */
570 static void
571 re_setmulti(struct re_softc *sc)
572 {
573         struct ifnet *ifp = &sc->arpcom.ac_if;
574         int h = 0;
575         uint32_t hashes[2] = { 0, 0 };
576         struct ifmultiaddr *ifma;
577         uint32_t rxfilt;
578         int mcnt = 0;
579
580         rxfilt = CSR_READ_4(sc, RE_RXCFG);
581
582         if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) {
583                 rxfilt |= RE_RXCFG_RX_MULTI;
584                 CSR_WRITE_4(sc, RE_RXCFG, rxfilt);
585                 CSR_WRITE_4(sc, RE_MAR0, 0xFFFFFFFF);
586                 CSR_WRITE_4(sc, RE_MAR4, 0xFFFFFFFF);
587                 return;
588         }
589
590         /* first, zot all the existing hash bits */
591         CSR_WRITE_4(sc, RE_MAR0, 0);
592         CSR_WRITE_4(sc, RE_MAR4, 0);
593
594         /* now program new ones */
595         LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
596                 if (ifma->ifma_addr->sa_family != AF_LINK)
597                         continue;
598                 h = ether_crc32_be(LLADDR((struct sockaddr_dl *)
599                     ifma->ifma_addr), ETHER_ADDR_LEN) >> 26;
600                 if (h < 32)
601                         hashes[0] |= (1 << h);
602                 else
603                         hashes[1] |= (1 << (h - 32));
604                 mcnt++;
605         }
606
607         if (mcnt)
608                 rxfilt |= RE_RXCFG_RX_MULTI;
609         else
610                 rxfilt &= ~RE_RXCFG_RX_MULTI;
611
612         CSR_WRITE_4(sc, RE_RXCFG, rxfilt);
613
614         /*
615          * For some unfathomable reason, RealTek decided to reverse
616          * the order of the multicast hash registers in the PCI Express
617          * parts. This means we have to write the hash pattern in reverse
618          * order for those devices.
619          */
620         if (sc->re_flags & RE_F_PCIE) {
621                 CSR_WRITE_4(sc, RE_MAR0, bswap32(hashes[0]));
622                 CSR_WRITE_4(sc, RE_MAR4, bswap32(hashes[1]));
623         } else {
624                 CSR_WRITE_4(sc, RE_MAR0, hashes[0]);
625                 CSR_WRITE_4(sc, RE_MAR4, hashes[1]);
626         }
627 }
628
629 static void
630 re_reset(struct re_softc *sc)
631 {
632         int i;
633
634         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_RESET);
635
636         for (i = 0; i < RE_TIMEOUT; i++) {
637                 DELAY(10);
638                 if ((CSR_READ_1(sc, RE_COMMAND) & RE_CMD_RESET) == 0)
639                         break;
640         }
641         if (i == RE_TIMEOUT)
642                 if_printf(&sc->arpcom.ac_if, "reset never completed!\n");
643
644         CSR_WRITE_1(sc, 0x82, 1);
645 }
646
647 #ifdef RE_DIAG
648 /*
649  * The following routine is designed to test for a defect on some
650  * 32-bit 8169 cards. Some of these NICs have the REQ64# and ACK64#
651  * lines connected to the bus, however for a 32-bit only card, they
652  * should be pulled high. The result of this defect is that the
653  * NIC will not work right if you plug it into a 64-bit slot: DMA
654  * operations will be done with 64-bit transfers, which will fail
655  * because the 64-bit data lines aren't connected.
656  *
657  * There's no way to work around this (short of talking a soldering
658  * iron to the board), however we can detect it. The method we use
659  * here is to put the NIC into digital loopback mode, set the receiver
660  * to promiscuous mode, and then try to send a frame. We then compare
661  * the frame data we sent to what was received. If the data matches,
662  * then the NIC is working correctly, otherwise we know the user has
663  * a defective NIC which has been mistakenly plugged into a 64-bit PCI
664  * slot. In the latter case, there's no way the NIC can work correctly,
665  * so we print out a message on the console and abort the device attach.
666  */
667
668 static int
669 re_diag(struct re_softc *sc)
670 {
671         struct ifnet *ifp = &sc->arpcom.ac_if;
672         struct mbuf *m0;
673         struct ether_header *eh;
674         struct re_desc *cur_rx;
675         uint16_t status;
676         uint32_t rxstat;
677         int total_len, i, error = 0, phyaddr;
678         uint8_t dst[ETHER_ADDR_LEN] = { 0x00, 'h', 'e', 'l', 'l', 'o' };
679         uint8_t src[ETHER_ADDR_LEN] = { 0x00, 'w', 'o', 'r', 'l', 'd' };
680
681         /* Allocate a single mbuf */
682
683         MGETHDR(m0, MB_DONTWAIT, MT_DATA);
684         if (m0 == NULL)
685                 return(ENOBUFS);
686
687         /*
688          * Initialize the NIC in test mode. This sets the chip up
689          * so that it can send and receive frames, but performs the
690          * following special functions:
691          * - Puts receiver in promiscuous mode
692          * - Enables digital loopback mode
693          * - Leaves interrupts turned off
694          */
695
696         ifp->if_flags |= IFF_PROMISC;
697         sc->re_testmode = 1;
698         re_reset(sc);
699         re_init(sc);
700         sc->re_link = 1;
701         if (sc->re_type == RE_8169)
702                 phyaddr = 1;
703         else
704                 phyaddr = 0;
705
706         re_miibus_writereg(sc->re_dev, phyaddr, MII_BMCR, BMCR_RESET);
707         for (i = 0; i < RE_TIMEOUT; i++) {
708                 status = re_miibus_readreg(sc->re_dev, phyaddr, MII_BMCR);
709                 if (!(status & BMCR_RESET))
710                         break;
711         }
712
713         re_miibus_writereg(sc->re_dev, phyaddr, MII_BMCR, BMCR_LOOP);
714         CSR_WRITE_2(sc, RE_ISR, RE_INTRS_DIAG);
715
716         DELAY(100000);
717
718         /* Put some data in the mbuf */
719
720         eh = mtod(m0, struct ether_header *);
721         bcopy (dst, eh->ether_dhost, ETHER_ADDR_LEN);
722         bcopy (src, eh->ether_shost, ETHER_ADDR_LEN);
723         eh->ether_type = htons(ETHERTYPE_IP);
724         m0->m_pkthdr.len = m0->m_len = ETHER_MIN_LEN - ETHER_CRC_LEN;
725
726         /*
727          * Queue the packet, start transmission.
728          * Note: ifq_handoff() ultimately calls re_start() for us.
729          */
730
731         CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
732         error = ifq_handoff(ifp, m0, NULL);
733         if (error) {
734                 m0 = NULL;
735                 goto done;
736         }
737         m0 = NULL;
738
739         /* Wait for it to propagate through the chip */
740
741         DELAY(100000);
742         for (i = 0; i < RE_TIMEOUT; i++) {
743                 status = CSR_READ_2(sc, RE_ISR);
744                 CSR_WRITE_2(sc, RE_ISR, status);
745                 if ((status & (RE_ISR_TIMEOUT_EXPIRED|RE_ISR_RX_OK)) ==
746                     (RE_ISR_TIMEOUT_EXPIRED|RE_ISR_RX_OK))
747                         break;
748                 DELAY(10);
749         }
750
751         if (i == RE_TIMEOUT) {
752                 if_printf(ifp, "diagnostic failed to receive packet "
753                           "in loopback mode\n");
754                 error = EIO;
755                 goto done;
756         }
757
758         /*
759          * The packet should have been dumped into the first
760          * entry in the RX DMA ring. Grab it from there.
761          */
762
763         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
764                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
765         bus_dmamap_sync(sc->re_ldata.re_mtag, sc->re_ldata.re_rx_dmamap[0],
766                         BUS_DMASYNC_POSTWRITE);
767         bus_dmamap_unload(sc->re_ldata.re_mtag, sc->re_ldata.re_rx_dmamap[0]);
768
769         m0 = sc->re_ldata.re_rx_mbuf[0];
770         sc->re_ldata.re_rx_mbuf[0] = NULL;
771         eh = mtod(m0, struct ether_header *);
772
773         cur_rx = &sc->re_ldata.re_rx_list[0];
774         total_len = RE_RXBYTES(cur_rx);
775         rxstat = le32toh(cur_rx->re_cmdstat);
776
777         if (total_len != ETHER_MIN_LEN) {
778                 if_printf(ifp, "diagnostic failed, received short packet\n");
779                 error = EIO;
780                 goto done;
781         }
782
783         /* Test that the received packet data matches what we sent. */
784
785         if (bcmp(eh->ether_dhost, dst, ETHER_ADDR_LEN) ||
786             bcmp(eh->ether_shost, &src, ETHER_ADDR_LEN) ||
787             be16toh(eh->ether_type) != ETHERTYPE_IP) {
788                 if_printf(ifp, "WARNING, DMA FAILURE!\n");
789                 if_printf(ifp, "expected TX data: %6D/%6D/0x%x\n",
790                     dst, ":", src, ":", ETHERTYPE_IP);
791                 if_printf(ifp, "received RX data: %6D/%6D/0x%x\n",
792                     eh->ether_dhost, ":",  eh->ether_shost, ":",
793                     ntohs(eh->ether_type));
794                 if_printf(ifp, "You may have a defective 32-bit NIC plugged "
795                     "into a 64-bit PCI slot.\n");
796                 if_printf(ifp, "Please re-install the NIC in a 32-bit slot "
797                     "for proper operation.\n");
798                 if_printf(ifp, "Read the re(4) man page for more details.\n");
799                 error = EIO;
800         }
801
802 done:
803         /* Turn interface off, release resources */
804
805         sc->re_testmode = 0;
806         sc->re_link = 0;
807         ifp->if_flags &= ~IFF_PROMISC;
808         re_stop(sc);
809         if (m0 != NULL)
810                 m_freem(m0);
811
812         return (error);
813 }
814 #endif  /* RE_DIAG */
815
816 /*
817  * Probe for a RealTek 8139C+/8169/8110 chip. Check the PCI vendor and device
818  * IDs against our list and return a device name if we find a match.
819  */
820 static int
821 re_probe(device_t dev)
822 {
823         const struct re_type *t;
824         struct re_softc *sc;
825         int rid;
826         uint32_t hwrev;
827         uint16_t vendor, product;
828
829         vendor = pci_get_vendor(dev);
830         product = pci_get_device(dev);
831
832         /*
833          * Only attach to rev.3 of the Linksys EG1032 adapter.
834          * Rev.2 is supported by sk(4).
835          */
836         if (vendor == PCI_VENDOR_LINKSYS &&
837             product == PCI_PRODUCT_LINKSYS_EG1032 &&
838             pci_get_subdevice(dev) != PCI_SUBDEVICE_LINKSYS_EG1032_REV3)
839                         return ENXIO;
840
841         for (t = re_devs; t->re_name != NULL; t++) {
842                 if (product == t->re_did && vendor == t->re_vid)
843                         break;
844         }
845
846         /*
847          * Check if we found a RealTek device.
848          */
849         if (t->re_name == NULL)
850                 return(ENXIO);
851
852         /*
853          * Temporarily map the I/O space so we can read the chip ID register.
854          */
855         sc = kmalloc(sizeof(*sc), M_TEMP, M_WAITOK | M_ZERO);
856         rid = RE_PCI_LOIO;
857         sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
858                                             RF_ACTIVE);
859         if (sc->re_res == NULL) {
860                 device_printf(dev, "couldn't map ports/memory\n");
861                 kfree(sc, M_TEMP);
862                 return(ENXIO);
863         }
864
865         sc->re_btag = rman_get_bustag(sc->re_res);
866         sc->re_bhandle = rman_get_bushandle(sc->re_res);
867
868         hwrev = CSR_READ_4(sc, RE_TXCFG) & RE_TXCFG_HWREV;
869         bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO, sc->re_res);
870         kfree(sc, M_TEMP);
871
872         /*
873          * and continue matching for the specific chip...
874          */
875         for (; t->re_name != NULL; t++) {
876                 if (product == t->re_did && vendor == t->re_vid &&
877                     t->re_basetype == hwrev) {
878                         device_set_desc(dev, t->re_name);
879                         return(0);
880                 }
881         }
882
883         if (bootverbose)
884                 kprintf("re: unknown hwrev %#x\n", hwrev);
885         return(ENXIO);
886 }
887
888 static void
889 re_dma_map_desc(void *xarg, bus_dma_segment_t *segs, int nsegs,
890                 bus_size_t mapsize, int error)
891 {
892         struct re_dmaload_arg *arg = xarg;
893         int i;
894
895         if (error)
896                 return;
897
898         if (nsegs > arg->re_nsegs) {
899                 arg->re_nsegs = 0;
900                 return;
901         }
902
903         arg->re_nsegs = nsegs;
904         for (i = 0; i < nsegs; ++i)
905                 arg->re_segs[i] = segs[i];
906 }
907
908 /*
909  * Map a single buffer address.
910  */
911
912 static void
913 re_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
914 {
915         uint32_t *addr;
916
917         if (error)
918                 return;
919
920         KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
921         addr = arg;
922         *addr = segs->ds_addr;
923 }
924
925 static int
926 re_allocmem(device_t dev)
927 {
928         struct re_softc *sc = device_get_softc(dev);
929         int error, i;
930
931         /*
932          * Allocate the parent bus DMA tag appropriate for PCI.
933          */
934         error = bus_dma_tag_create(NULL,        /* parent */
935                         1, 0,                   /* alignment, boundary */
936                         BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
937                         BUS_SPACE_MAXADDR,      /* highaddr */
938                         NULL, NULL,             /* filter, filterarg */
939                         MAXBSIZE, RE_MAXSEGS,   /* maxsize, nsegments */
940                         BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
941                         BUS_DMA_ALLOCNOW,       /* flags */
942                         &sc->re_parent_tag);
943         if (error) {
944                 device_printf(dev, "could not allocate parent dma tag\n");
945                 return error;
946         }
947
948         /* Allocate tag for TX descriptor list. */
949         error = bus_dma_tag_create(sc->re_parent_tag,
950                         RE_RING_ALIGN, 0,
951                         BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
952                         NULL, NULL,
953                         RE_TX_LIST_SZ, 1, RE_TX_LIST_SZ,
954                         BUS_DMA_ALLOCNOW,
955                         &sc->re_ldata.re_tx_list_tag);
956         if (error) {
957                 device_printf(dev, "could not allocate TX ring dma tag\n");
958                 return(error);
959         }
960
961         /* Allocate DMA'able memory for the TX ring */
962         error = bus_dmamem_alloc(sc->re_ldata.re_tx_list_tag,
963                         (void **)&sc->re_ldata.re_tx_list,
964                         BUS_DMA_WAITOK | BUS_DMA_ZERO,
965                         &sc->re_ldata.re_tx_list_map);
966         if (error) {
967                 device_printf(dev, "could not allocate TX ring\n");
968                 bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
969                 sc->re_ldata.re_tx_list_tag = NULL;
970                 return(error);
971         }
972
973         /* Load the map for the TX ring. */
974         error = bus_dmamap_load(sc->re_ldata.re_tx_list_tag,
975                         sc->re_ldata.re_tx_list_map,
976                         sc->re_ldata.re_tx_list, RE_TX_LIST_SZ,
977                         re_dma_map_addr, &sc->re_ldata.re_tx_list_addr,
978                         BUS_DMA_NOWAIT);
979         if (error) {
980                 device_printf(dev, "could not get address of TX ring\n");
981                 bus_dmamem_free(sc->re_ldata.re_tx_list_tag,
982                                 sc->re_ldata.re_tx_list,
983                                 sc->re_ldata.re_tx_list_map);
984                 bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
985                 sc->re_ldata.re_tx_list_tag = NULL;
986                 return(error);
987         }
988
989         /* Allocate tag for RX descriptor list. */
990         error = bus_dma_tag_create(sc->re_parent_tag,
991                         RE_RING_ALIGN, 0,
992                         BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
993                         NULL, NULL,
994                         RE_RX_LIST_SZ, 1, RE_RX_LIST_SZ,
995                         BUS_DMA_ALLOCNOW,
996                         &sc->re_ldata.re_rx_list_tag);
997         if (error) {
998                 device_printf(dev, "could not allocate RX ring dma tag\n");
999                 return(error);
1000         }
1001
1002         /* Allocate DMA'able memory for the RX ring */
1003         error = bus_dmamem_alloc(sc->re_ldata.re_rx_list_tag,
1004                         (void **)&sc->re_ldata.re_rx_list,
1005                         BUS_DMA_WAITOK | BUS_DMA_ZERO,
1006                         &sc->re_ldata.re_rx_list_map);
1007         if (error) {
1008                 device_printf(dev, "could not allocate RX ring\n");
1009                 bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1010                 sc->re_ldata.re_rx_list_tag = NULL;
1011                 return(error);
1012         }
1013
1014         /* Load the map for the RX ring. */
1015         error = bus_dmamap_load(sc->re_ldata.re_rx_list_tag,
1016                         sc->re_ldata.re_rx_list_map,
1017                         sc->re_ldata.re_rx_list, RE_RX_LIST_SZ,
1018                         re_dma_map_addr, &sc->re_ldata.re_rx_list_addr,
1019                         BUS_DMA_NOWAIT);
1020         if (error) {
1021                 device_printf(dev, "could not get address of RX ring\n");
1022                 bus_dmamem_free(sc->re_ldata.re_rx_list_tag,
1023                                 sc->re_ldata.re_rx_list,
1024                                 sc->re_ldata.re_rx_list_map);
1025                 bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1026                 sc->re_ldata.re_rx_list_tag = NULL;
1027                 return(error);
1028         }
1029
1030         /* Allocate map for RX/TX mbufs. */
1031         error = bus_dma_tag_create(sc->re_parent_tag,
1032                         ETHER_ALIGN, 0,
1033                         BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
1034                         NULL, NULL,
1035                         RE_JUMBO_FRAMELEN, RE_MAXSEGS, MCLBYTES,
1036                         BUS_DMA_ALLOCNOW,
1037                         &sc->re_ldata.re_mtag);
1038         if (error) {
1039                 device_printf(dev, "could not allocate buf dma tag\n");
1040                 return(error);
1041         }
1042
1043         /* Create spare DMA map for RX */
1044         error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
1045                         &sc->re_ldata.re_rx_spare);
1046         if (error) {
1047                 device_printf(dev, "can't create spare DMA map for RX\n");
1048                 bus_dma_tag_destroy(sc->re_ldata.re_mtag);
1049                 sc->re_ldata.re_mtag = NULL;
1050                 return error;
1051         }
1052
1053         /* Create DMA maps for TX buffers */
1054         for (i = 0; i < RE_TX_DESC_CNT; i++) {
1055                 error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
1056                                 &sc->re_ldata.re_tx_dmamap[i]);
1057                 if (error) {
1058                         device_printf(dev, "can't create DMA map for TX buf\n");
1059                         re_freebufmem(sc, i, 0);
1060                         return(error);
1061                 }
1062         }
1063
1064         /* Create DMA maps for RX buffers */
1065         for (i = 0; i < RE_RX_DESC_CNT; i++) {
1066                 error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
1067                                 &sc->re_ldata.re_rx_dmamap[i]);
1068                 if (error) {
1069                         device_printf(dev, "can't create DMA map for RX buf\n");
1070                         re_freebufmem(sc, RE_TX_DESC_CNT, i);
1071                         return(error);
1072                 }
1073         }
1074         return(0);
1075 }
1076
1077 static void
1078 re_freebufmem(struct re_softc *sc, int tx_cnt, int rx_cnt)
1079 {
1080         int i;
1081
1082         /* Destroy all the RX and TX buffer maps */
1083         if (sc->re_ldata.re_mtag) {
1084                 for (i = 0; i < tx_cnt; i++) {
1085                         bus_dmamap_destroy(sc->re_ldata.re_mtag,
1086                                            sc->re_ldata.re_tx_dmamap[i]);
1087                 }
1088                 for (i = 0; i < rx_cnt; i++) {
1089                         bus_dmamap_destroy(sc->re_ldata.re_mtag,
1090                                            sc->re_ldata.re_rx_dmamap[i]);
1091                 }
1092                 bus_dmamap_destroy(sc->re_ldata.re_mtag,
1093                                    sc->re_ldata.re_rx_spare);
1094                 bus_dma_tag_destroy(sc->re_ldata.re_mtag);
1095         }
1096 }
1097
1098 static void
1099 re_freemem(device_t dev)
1100 {
1101         struct re_softc *sc = device_get_softc(dev);
1102
1103         /* Unload and free the RX DMA ring memory and map */
1104         if (sc->re_ldata.re_rx_list_tag) {
1105                 bus_dmamap_unload(sc->re_ldata.re_rx_list_tag,
1106                                   sc->re_ldata.re_rx_list_map);
1107                 bus_dmamem_free(sc->re_ldata.re_rx_list_tag,
1108                                 sc->re_ldata.re_rx_list,
1109                                 sc->re_ldata.re_rx_list_map);
1110                 bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1111         }
1112
1113         /* Unload and free the TX DMA ring memory and map */
1114         if (sc->re_ldata.re_tx_list_tag) {
1115                 bus_dmamap_unload(sc->re_ldata.re_tx_list_tag,
1116                                   sc->re_ldata.re_tx_list_map);
1117                 bus_dmamem_free(sc->re_ldata.re_tx_list_tag,
1118                                 sc->re_ldata.re_tx_list,
1119                                 sc->re_ldata.re_tx_list_map);
1120                 bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
1121         }
1122
1123         /* Free RX/TX buf DMA stuffs */
1124         re_freebufmem(sc, RE_TX_DESC_CNT, RE_RX_DESC_CNT);
1125
1126         /* Unload and free the stats buffer and map */
1127         if (sc->re_ldata.re_stag) {
1128                 bus_dmamap_unload(sc->re_ldata.re_stag,
1129                                   sc->re_ldata.re_rx_list_map);
1130                 bus_dmamem_free(sc->re_ldata.re_stag,
1131                                 sc->re_ldata.re_stats,
1132                                 sc->re_ldata.re_smap);
1133                 bus_dma_tag_destroy(sc->re_ldata.re_stag);
1134         }
1135
1136         if (sc->re_parent_tag)
1137                 bus_dma_tag_destroy(sc->re_parent_tag);
1138 }
1139
1140 /*
1141  * Attach the interface. Allocate softc structures, do ifmedia
1142  * setup and ethernet/BPF attach.
1143  */
1144 static int
1145 re_attach(device_t dev)
1146 {
1147         struct re_softc *sc = device_get_softc(dev);
1148         struct ifnet *ifp;
1149         const struct re_hwrev *hw_rev;
1150         uint8_t eaddr[ETHER_ADDR_LEN];
1151         uint16_t as[ETHER_ADDR_LEN / 2];
1152         uint16_t re_did = 0;
1153         uint32_t hwrev;
1154         int error = 0, rid, i;
1155
1156         callout_init(&sc->re_timer);
1157 #ifdef RE_DIAG
1158         sc->re_dev = dev;
1159 #endif
1160
1161         RE_ENABLE_TX_MODERATION(sc);
1162
1163         sysctl_ctx_init(&sc->re_sysctl_ctx);
1164         sc->re_sysctl_tree = SYSCTL_ADD_NODE(&sc->re_sysctl_ctx,
1165                                              SYSCTL_STATIC_CHILDREN(_hw),
1166                                              OID_AUTO,
1167                                              device_get_nameunit(dev),
1168                                              CTLFLAG_RD, 0, "");
1169         if (sc->re_sysctl_tree == NULL) {
1170                 device_printf(dev, "can't add sysctl node\n");
1171                 error = ENXIO;
1172                 goto fail;
1173         }
1174         SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1175                         SYSCTL_CHILDREN(sc->re_sysctl_tree),
1176                         OID_AUTO, "tx_moderation",
1177                         CTLTYPE_INT | CTLFLAG_RW,
1178                         sc, 0, re_sysctl_tx_moderation, "I",
1179                         "Enable/Disable TX moderation");
1180
1181 #ifndef BURN_BRIDGES
1182         /*
1183          * Handle power management nonsense.
1184          */
1185
1186         if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
1187                 uint32_t membase, irq;
1188
1189                 /* Save important PCI config data. */
1190                 membase = pci_read_config(dev, RE_PCI_LOMEM, 4);
1191                 irq = pci_read_config(dev, PCIR_INTLINE, 4);
1192
1193                 /* Reset the power state. */
1194                 device_printf(dev, "chip is in D%d power mode "
1195                     "-- setting to D0\n", pci_get_powerstate(dev));
1196
1197                 pci_set_powerstate(dev, PCI_POWERSTATE_D0);
1198
1199                 /* Restore PCI config data. */
1200                 pci_write_config(dev, RE_PCI_LOMEM, membase, 4);
1201                 pci_write_config(dev, PCIR_INTLINE, irq, 4);
1202         }
1203 #endif
1204         /*
1205          * Map control/status registers.
1206          */
1207         pci_enable_busmaster(dev);
1208
1209         rid = RE_PCI_LOIO;
1210         sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
1211                                             RF_ACTIVE);
1212
1213         if (sc->re_res == NULL) {
1214                 device_printf(dev, "couldn't map ports\n");
1215                 error = ENXIO;
1216                 goto fail;
1217         }
1218
1219         sc->re_btag = rman_get_bustag(sc->re_res);
1220         sc->re_bhandle = rman_get_bushandle(sc->re_res);
1221
1222         /* Allocate interrupt */
1223         rid = 0;
1224         sc->re_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1225                                             RF_SHAREABLE | RF_ACTIVE);
1226
1227         if (sc->re_irq == NULL) {
1228                 device_printf(dev, "couldn't map interrupt\n");
1229                 error = ENXIO;
1230                 goto fail;
1231         }
1232
1233         /* Reset the adapter. */
1234         re_reset(sc);
1235
1236         hwrev = CSR_READ_4(sc, RE_TXCFG) & RE_TXCFG_HWREV;
1237         for (hw_rev = re_hwrevs; hw_rev->re_desc != NULL; hw_rev++) {
1238                 if (hw_rev->re_rev == hwrev) {
1239                         sc->re_type = hw_rev->re_type;
1240                         sc->re_flags = hw_rev->re_flags;
1241                         sc->re_swcsum_lim = hw_rev->re_swcsum_lim;
1242                         break;
1243                 }
1244         }
1245         device_printf(dev, "hardware rev. 0x%08x\n", hwrev);
1246
1247         sc->re_eewidth = 6;
1248         re_read_eeprom(sc, (caddr_t)&re_did, 0, 1);
1249         if (re_did != 0x8129)
1250                 sc->re_eewidth = 8;
1251
1252         /*
1253          * Get station address from the EEPROM.
1254          */
1255         re_read_eeprom(sc, (caddr_t)as, RE_EE_EADDR, 3);
1256         for (i = 0; i < ETHER_ADDR_LEN / 2; i++)
1257                 as[i] = le16toh(as[i]);
1258         bcopy(as, eaddr, sizeof(eaddr));
1259
1260         if (sc->re_type == RE_8169) {
1261                 /* Set RX length mask */
1262                 sc->re_rxlenmask = RE_RDESC_STAT_GFRAGLEN;
1263                 sc->re_txstart = RE_GTXSTART;
1264         } else {
1265                 /* Set RX length mask */
1266                 sc->re_rxlenmask = RE_RDESC_STAT_FRAGLEN;
1267                 sc->re_txstart = RE_TXSTART;
1268         }
1269
1270         /* Allocate DMA stuffs */
1271         error = re_allocmem(dev);
1272         if (error)
1273                 goto fail;
1274
1275         /* Do MII setup */
1276         if (mii_phy_probe(dev, &sc->re_miibus,
1277             re_ifmedia_upd, re_ifmedia_sts)) {
1278                 device_printf(dev, "MII without any phy!\n");
1279                 error = ENXIO;
1280                 goto fail;
1281         }
1282
1283         ifp = &sc->arpcom.ac_if;
1284         ifp->if_softc = sc;
1285         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1286         ifp->if_mtu = ETHERMTU;
1287         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1288         ifp->if_ioctl = re_ioctl;
1289         ifp->if_start = re_start;
1290         ifp->if_capabilities = IFCAP_VLAN_MTU | IFCAP_VLAN_HWTAGGING;
1291
1292         switch (hwrev) {
1293         case RE_HWREV_8168C:
1294         case RE_HWREV_8102EL:
1295                 /*
1296                  * XXX Hardware checksum does not work yet on 8168C
1297                  * and 8102EL. Disble it.
1298                  */
1299                 ifp->if_capabilities &= ~IFCAP_HWCSUM;
1300                 break;
1301         default:
1302                 ifp->if_capabilities |= IFCAP_HWCSUM;
1303                 break;
1304         }
1305 #ifdef DEVICE_POLLING
1306         ifp->if_poll = re_poll;
1307 #endif
1308         ifp->if_watchdog = re_watchdog;
1309         ifp->if_init = re_init;
1310         if (sc->re_type == RE_8169)
1311                 ifp->if_baudrate = 1000000000;
1312         else
1313                 ifp->if_baudrate = 100000000;
1314         ifq_set_maxlen(&ifp->if_snd, RE_IFQ_MAXLEN);
1315         ifq_set_ready(&ifp->if_snd);
1316
1317 #ifdef RE_DISABLE_HWCSUM
1318         ifp->if_capenable = ifp->if_capabilities & ~IFCAP_HWCSUM;
1319         ifp->if_hwassist = 0;
1320 #else
1321         ifp->if_capenable = ifp->if_capabilities;
1322         if (ifp->if_capabilities & IFCAP_HWCSUM)
1323                 ifp->if_hwassist = RE_CSUM_FEATURES;
1324         else
1325                 ifp->if_hwassist = 0;
1326 #endif  /* RE_DISABLE_HWCSUM */
1327
1328         /*
1329          * Call MI attach routine.
1330          */
1331         ether_ifattach(ifp, eaddr, NULL);
1332
1333 #ifdef RE_DIAG
1334         /*
1335          * Perform hardware diagnostic on the original RTL8169.
1336          * Some 32-bit cards were incorrectly wired and would
1337          * malfunction if plugged into a 64-bit slot.
1338          */
1339         if (hwrev == RE_HWREV_8169) {
1340                 lwkt_serialize_enter(ifp->if_serializer);
1341                 error = re_diag(sc);
1342                 lwkt_serialize_exit(ifp->if_serializer);
1343
1344                 if (error) {
1345                         device_printf(dev, "hardware diagnostic failure\n");
1346                         ether_ifdetach(ifp);
1347                         goto fail;
1348                 }
1349         }
1350 #endif  /* RE_DIAG */
1351
1352         /* Hook interrupt last to avoid having to lock softc */
1353         error = bus_setup_intr(dev, sc->re_irq, INTR_MPSAFE, re_intr, sc,
1354                                &sc->re_intrhand, ifp->if_serializer);
1355
1356         if (error) {
1357                 device_printf(dev, "couldn't set up irq\n");
1358                 ether_ifdetach(ifp);
1359                 goto fail;
1360         }
1361
1362         ifp->if_cpuid = ithread_cpuid(rman_get_start(sc->re_irq));
1363         KKASSERT(ifp->if_cpuid >= 0 && ifp->if_cpuid < ncpus);
1364
1365 fail:
1366         if (error)
1367                 re_detach(dev);
1368
1369         return (error);
1370 }
1371
1372 /*
1373  * Shutdown hardware and free up resources. This can be called any
1374  * time after the mutex has been initialized. It is called in both
1375  * the error case in attach and the normal detach case so it needs
1376  * to be careful about only freeing resources that have actually been
1377  * allocated.
1378  */
1379 static int
1380 re_detach(device_t dev)
1381 {
1382         struct re_softc *sc = device_get_softc(dev);
1383         struct ifnet *ifp = &sc->arpcom.ac_if;
1384
1385         /* These should only be active if attach succeeded */
1386         if (device_is_attached(dev)) {
1387                 lwkt_serialize_enter(ifp->if_serializer);
1388                 re_stop(sc);
1389                 bus_teardown_intr(dev, sc->re_irq, sc->re_intrhand);
1390                 lwkt_serialize_exit(ifp->if_serializer);
1391
1392                 ether_ifdetach(ifp);
1393         }
1394         if (sc->re_miibus)
1395                 device_delete_child(dev, sc->re_miibus);
1396         bus_generic_detach(dev);
1397
1398         if (sc->re_sysctl_tree != NULL)
1399                 sysctl_ctx_free(&sc->re_sysctl_ctx);
1400
1401         if (sc->re_irq)
1402                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->re_irq);
1403         if (sc->re_res) {
1404                 bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO,
1405                                      sc->re_res);
1406         }
1407
1408         /* Free DMA stuffs */
1409         re_freemem(dev);
1410
1411         return(0);
1412 }
1413
1414 static void
1415 re_setup_rxdesc(struct re_softc *sc, int idx)
1416 {
1417         bus_addr_t paddr;
1418         uint32_t cmdstat;
1419         struct re_desc *d;
1420
1421         paddr = sc->re_ldata.re_rx_paddr[idx];
1422         d = &sc->re_ldata.re_rx_list[idx];
1423
1424         d->re_bufaddr_lo = htole32(RE_ADDR_LO(paddr));
1425         d->re_bufaddr_hi = htole32(RE_ADDR_HI(paddr));
1426
1427         cmdstat = MCLBYTES | RE_RDESC_CMD_OWN;
1428         if (idx == (RE_RX_DESC_CNT - 1))
1429                 cmdstat |= RE_TDESC_CMD_EOR;
1430         d->re_cmdstat = htole32(cmdstat);
1431 }
1432
1433 static int
1434 re_newbuf(struct re_softc *sc, int idx, int init)
1435 {
1436         struct re_dmaload_arg arg;
1437         bus_dma_segment_t seg;
1438         bus_dmamap_t map;
1439         struct mbuf *m;
1440         int error;
1441
1442         m = m_getcl(init ? MB_WAIT : MB_DONTWAIT, MT_DATA, M_PKTHDR);
1443         if (m == NULL) {
1444                 error = ENOBUFS;
1445
1446                 if (init) {
1447                         if_printf(&sc->arpcom.ac_if, "m_getcl failed\n");
1448                         return error;
1449                 } else {
1450                         goto back;
1451                 }
1452         }
1453         m->m_len = m->m_pkthdr.len = MCLBYTES;
1454
1455         /*
1456          * NOTE:
1457          * Some re(4) chips(e.g. RTL8101E) need address of the receive buffer
1458          * to be 8-byte aligned, so don't call m_adj(m, ETHER_ALIGN) here.
1459          */
1460
1461         arg.re_nsegs = 1;
1462         arg.re_segs = &seg;
1463         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag,
1464                                      sc->re_ldata.re_rx_spare, m,
1465                                      re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1466         if (error || arg.re_nsegs == 0) {
1467                 if (!error) {
1468                         if_printf(&sc->arpcom.ac_if, "too many segments?!\n");
1469                         bus_dmamap_unload(sc->re_ldata.re_mtag,
1470                                           sc->re_ldata.re_rx_spare);
1471                         error = EFBIG;
1472                 }
1473                 m_freem(m);
1474
1475                 if (init) {
1476                         if_printf(&sc->arpcom.ac_if, "can't load RX mbuf\n");
1477                         return error;
1478                 } else {
1479                         goto back;
1480                 }
1481         }
1482
1483         if (!init) {
1484                 bus_dmamap_sync(sc->re_ldata.re_mtag,
1485                                 sc->re_ldata.re_rx_dmamap[idx],
1486                                 BUS_DMASYNC_POSTREAD);
1487                 bus_dmamap_unload(sc->re_ldata.re_mtag,
1488                                   sc->re_ldata.re_rx_dmamap[idx]);
1489         }
1490         sc->re_ldata.re_rx_mbuf[idx] = m;
1491         sc->re_ldata.re_rx_paddr[idx] = seg.ds_addr;
1492
1493         map = sc->re_ldata.re_rx_dmamap[idx];
1494         sc->re_ldata.re_rx_dmamap[idx] = sc->re_ldata.re_rx_spare;
1495         sc->re_ldata.re_rx_spare = map;
1496 back:
1497         re_setup_rxdesc(sc, idx);
1498         return error;
1499 }
1500
1501 static int
1502 re_tx_list_init(struct re_softc *sc)
1503 {
1504         bzero(sc->re_ldata.re_tx_list, RE_TX_LIST_SZ);
1505         bzero(&sc->re_ldata.re_tx_mbuf, RE_TX_DESC_CNT * sizeof(struct mbuf *));
1506
1507         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1508                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
1509         sc->re_ldata.re_tx_prodidx = 0;
1510         sc->re_ldata.re_tx_considx = 0;
1511         sc->re_ldata.re_tx_free = RE_TX_DESC_CNT;
1512
1513         return(0);
1514 }
1515
1516 static int
1517 re_rx_list_init(struct re_softc *sc)
1518 {
1519         int i, error;
1520
1521         bzero(sc->re_ldata.re_rx_list, RE_RX_LIST_SZ);
1522         bzero(&sc->re_ldata.re_rx_mbuf, RE_RX_DESC_CNT * sizeof(struct mbuf *));
1523
1524         for (i = 0; i < RE_RX_DESC_CNT; i++) {
1525                 error = re_newbuf(sc, i, 1);
1526                 if (error)
1527                         return(error);
1528         }
1529
1530         /* Flush the RX descriptors */
1531
1532         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1533                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
1534
1535         sc->re_ldata.re_rx_prodidx = 0;
1536         sc->re_head = sc->re_tail = NULL;
1537
1538         return(0);
1539 }
1540
1541 /*
1542  * RX handler for C+ and 8169. For the gigE chips, we support
1543  * the reception of jumbo frames that have been fragmented
1544  * across multiple 2K mbuf cluster buffers.
1545  */
1546 static void
1547 re_rxeof(struct re_softc *sc)
1548 {
1549         struct ifnet *ifp = &sc->arpcom.ac_if;
1550         struct mbuf *m;
1551         struct re_desc  *cur_rx;
1552         uint32_t rxstat, rxvlan;
1553         int i, total_len;
1554         struct mbuf_chain chain[MAXCPU];
1555
1556         /* Invalidate the descriptor memory */
1557
1558         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1559                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
1560
1561         ether_input_chain_init(chain);
1562
1563         for (i = sc->re_ldata.re_rx_prodidx;
1564              RE_OWN(&sc->re_ldata.re_rx_list[i]) == 0; RE_DESC_INC(i)) {
1565                 cur_rx = &sc->re_ldata.re_rx_list[i];
1566                 m = sc->re_ldata.re_rx_mbuf[i];
1567                 total_len = RE_RXBYTES(cur_rx);
1568                 rxstat = le32toh(cur_rx->re_cmdstat);
1569                 rxvlan = le32toh(cur_rx->re_vlanctl);
1570
1571                 if ((rxstat & RE_RDESC_STAT_EOF) == 0) {
1572                         if (sc->re_drop_rxfrag) {
1573                                 re_setup_rxdesc(sc, i);
1574                                 continue;
1575                         }
1576
1577                         if (re_newbuf(sc, i, 0)) {
1578                                 /* Drop upcoming fragments */
1579                                 sc->re_drop_rxfrag = 1;
1580                                 continue;
1581                         }
1582
1583                         m->m_len = MCLBYTES;
1584                         if (sc->re_head == NULL) {
1585                                 sc->re_head = sc->re_tail = m;
1586                         } else {
1587                                 sc->re_tail->m_next = m;
1588                                 sc->re_tail = m;
1589                         }
1590                         continue;
1591                 } else if (sc->re_drop_rxfrag) {
1592                         /*
1593                          * Last fragment of a multi-fragment packet.
1594                          *
1595                          * Since error already happened, this fragment
1596                          * must be dropped as well as the fragment chain.
1597                          */
1598                         re_setup_rxdesc(sc, i);
1599                         re_free_rxchain(sc);
1600                         sc->re_drop_rxfrag = 0;
1601                         continue;
1602                 }
1603
1604                 /*
1605                  * NOTE: for the 8139C+, the frame length field
1606                  * is always 12 bits in size, but for the gigE chips,
1607                  * it is 13 bits (since the max RX frame length is 16K).
1608                  * Unfortunately, all 32 bits in the status word
1609                  * were already used, so to make room for the extra
1610                  * length bit, RealTek took out the 'frame alignment
1611                  * error' bit and shifted the other status bits
1612                  * over one slot. The OWN, EOR, FS and LS bits are
1613                  * still in the same places. We have already extracted
1614                  * the frame length and checked the OWN bit, so rather
1615                  * than using an alternate bit mapping, we shift the
1616                  * status bits one space to the right so we can evaluate
1617                  * them using the 8169 status as though it was in the
1618                  * same format as that of the 8139C+.
1619                  */
1620                 if (sc->re_type == RE_8169)
1621                         rxstat >>= 1;
1622
1623                 if (rxstat & RE_RDESC_STAT_RXERRSUM) {
1624                         ifp->if_ierrors++;
1625                         /*
1626                          * If this is part of a multi-fragment packet,
1627                          * discard all the pieces.
1628                          */
1629                         re_free_rxchain(sc);
1630                         re_setup_rxdesc(sc, i);
1631                         continue;
1632                 }
1633
1634                 /*
1635                  * If allocating a replacement mbuf fails,
1636                  * reload the current one.
1637                  */
1638
1639                 if (re_newbuf(sc, i, 0)) {
1640                         ifp->if_ierrors++;
1641                         re_free_rxchain(sc);
1642                         continue;
1643                 }
1644
1645                 if (sc->re_head != NULL) {
1646                         m->m_len = total_len % MCLBYTES;
1647                         /* 
1648                          * Special case: if there's 4 bytes or less
1649                          * in this buffer, the mbuf can be discarded:
1650                          * the last 4 bytes is the CRC, which we don't
1651                          * care about anyway.
1652                          */
1653                         if (m->m_len <= ETHER_CRC_LEN) {
1654                                 sc->re_tail->m_len -=
1655                                     (ETHER_CRC_LEN - m->m_len);
1656                                 m_freem(m);
1657                         } else {
1658                                 m->m_len -= ETHER_CRC_LEN;
1659                                 sc->re_tail->m_next = m;
1660                         }
1661                         m = sc->re_head;
1662                         sc->re_head = sc->re_tail = NULL;
1663                         m->m_pkthdr.len = total_len - ETHER_CRC_LEN;
1664                 } else {
1665                         m->m_pkthdr.len = m->m_len =
1666                             (total_len - ETHER_CRC_LEN);
1667                 }
1668
1669                 ifp->if_ipackets++;
1670                 m->m_pkthdr.rcvif = ifp;
1671
1672                 /* Do RX checksumming if enabled */
1673
1674                 if (ifp->if_capenable & IFCAP_RXCSUM) {
1675                         /* Check IP header checksum */
1676                         if (rxstat & RE_RDESC_STAT_PROTOID)
1677                                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
1678                         if ((rxstat & RE_RDESC_STAT_IPSUMBAD) == 0)
1679                                 m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1680
1681                         /* Check TCP/UDP checksum */
1682                         if ((RE_TCPPKT(rxstat) &&
1683                             (rxstat & RE_RDESC_STAT_TCPSUMBAD) == 0) ||
1684                             (RE_UDPPKT(rxstat) &&
1685                             (rxstat & RE_RDESC_STAT_UDPSUMBAD)) == 0) {
1686                                 m->m_pkthdr.csum_flags |=
1687                                     CSUM_DATA_VALID|CSUM_PSEUDO_HDR|
1688                                     CSUM_FRAG_NOT_CHECKED;
1689                                 m->m_pkthdr.csum_data = 0xffff;
1690                         }
1691                 }
1692
1693                 if (rxvlan & RE_RDESC_VLANCTL_TAG) {
1694                         m->m_flags |= M_VLANTAG;
1695                         m->m_pkthdr.ether_vlantag =
1696                                 be16toh((rxvlan & RE_RDESC_VLANCTL_DATA));
1697                 }
1698                 ether_input_chain(ifp, m, chain);
1699         }
1700
1701         ether_input_dispatch(chain);
1702
1703         /* Flush the RX DMA ring */
1704
1705         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1706                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
1707
1708         sc->re_ldata.re_rx_prodidx = i;
1709 }
1710
1711 static void
1712 re_txeof(struct re_softc *sc)
1713 {
1714         struct ifnet *ifp = &sc->arpcom.ac_if;
1715         uint32_t txstat;
1716         int idx;
1717
1718         /* Invalidate the TX descriptor list */
1719
1720         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1721                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_POSTREAD);
1722
1723         for (idx = sc->re_ldata.re_tx_considx;
1724              sc->re_ldata.re_tx_free < RE_TX_DESC_CNT; RE_DESC_INC(idx)) {
1725                 txstat = le32toh(sc->re_ldata.re_tx_list[idx].re_cmdstat);
1726                 if (txstat & RE_TDESC_CMD_OWN)
1727                         break;
1728
1729                 sc->re_ldata.re_tx_list[idx].re_bufaddr_lo = 0;
1730
1731                 /*
1732                  * We only stash mbufs in the last descriptor
1733                  * in a fragment chain, which also happens to
1734                  * be the only place where the TX status bits
1735                  * are valid.
1736                  */
1737                 if (txstat & RE_TDESC_CMD_EOF) {
1738                         m_freem(sc->re_ldata.re_tx_mbuf[idx]);
1739                         sc->re_ldata.re_tx_mbuf[idx] = NULL;
1740                         bus_dmamap_unload(sc->re_ldata.re_mtag,
1741                             sc->re_ldata.re_tx_dmamap[idx]);
1742                         if (txstat & (RE_TDESC_STAT_EXCESSCOL|
1743                             RE_TDESC_STAT_COLCNT))
1744                                 ifp->if_collisions++;
1745                         if (txstat & RE_TDESC_STAT_TXERRSUM)
1746                                 ifp->if_oerrors++;
1747                         else
1748                                 ifp->if_opackets++;
1749                 }
1750                 sc->re_ldata.re_tx_free++;
1751         }
1752         sc->re_ldata.re_tx_considx = idx;
1753
1754         /* There is enough free TX descs */
1755         if (sc->re_ldata.re_tx_free > RE_TXDESC_SPARE)
1756                 ifp->if_flags &= ~IFF_OACTIVE;
1757
1758         /*
1759          * Some chips will ignore a second TX request issued while an
1760          * existing transmission is in progress. If the transmitter goes
1761          * idle but there are still packets waiting to be sent, we need
1762          * to restart the channel here to flush them out. This only seems
1763          * to be required with the PCIe devices.
1764          */
1765         if (sc->re_ldata.re_tx_free < RE_TX_DESC_CNT)
1766                 CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
1767         else
1768                 ifp->if_timer = 0;
1769
1770         /*
1771          * If not all descriptors have been released reaped yet,
1772          * reload the timer so that we will eventually get another
1773          * interrupt that will cause us to re-enter this routine.
1774          * This is done in case the transmitter has gone idle.
1775          */
1776         if (RE_TX_MODERATION_IS_ENABLED(sc) &&
1777             sc->re_ldata.re_tx_free < RE_TX_DESC_CNT)
1778                 CSR_WRITE_4(sc, RE_TIMERCNT, 1);
1779 }
1780
1781 static void
1782 re_tick(void *xsc)
1783 {
1784         struct re_softc *sc = xsc;
1785
1786         lwkt_serialize_enter(sc->arpcom.ac_if.if_serializer);
1787         re_tick_serialized(xsc);
1788         lwkt_serialize_exit(sc->arpcom.ac_if.if_serializer);
1789 }
1790
1791 static void
1792 re_tick_serialized(void *xsc)
1793 {
1794         struct re_softc *sc = xsc;
1795         struct ifnet *ifp = &sc->arpcom.ac_if;
1796         struct mii_data *mii;
1797
1798         ASSERT_SERIALIZED(ifp->if_serializer);
1799
1800         mii = device_get_softc(sc->re_miibus);
1801         mii_tick(mii);
1802         if (sc->re_link) {
1803                 if (!(mii->mii_media_status & IFM_ACTIVE))
1804                         sc->re_link = 0;
1805         } else {
1806                 if (mii->mii_media_status & IFM_ACTIVE &&
1807                     IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) {
1808                         sc->re_link = 1;
1809                         if (!ifq_is_empty(&ifp->if_snd))
1810                                 if_devstart(ifp);
1811                 }
1812         }
1813
1814         callout_reset(&sc->re_timer, hz, re_tick, sc);
1815 }
1816
1817 #ifdef DEVICE_POLLING
1818
1819 static void
1820 re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1821 {
1822         struct re_softc *sc = ifp->if_softc;
1823
1824         ASSERT_SERIALIZED(ifp->if_serializer);
1825
1826         switch(cmd) {
1827         case POLL_REGISTER:
1828                 /* disable interrupts */
1829                 CSR_WRITE_2(sc, RE_IMR, 0x0000);
1830                 break;
1831         case POLL_DEREGISTER:
1832                 /* enable interrupts */
1833                 CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
1834                 break;
1835         default:
1836                 sc->rxcycles = count;
1837                 re_rxeof(sc);
1838                 re_txeof(sc);
1839
1840                 if (!ifq_is_empty(&ifp->if_snd))
1841                         if_devstart(ifp);
1842
1843                 if (cmd == POLL_AND_CHECK_STATUS) { /* also check status register */
1844                         uint16_t       status;
1845
1846                         status = CSR_READ_2(sc, RE_ISR);
1847                         if (status == 0xffff)
1848                                 return;
1849                         if (status)
1850                                 CSR_WRITE_2(sc, RE_ISR, status);
1851
1852                         /*
1853                          * XXX check behaviour on receiver stalls.
1854                          */
1855
1856                         if (status & RE_ISR_SYSTEM_ERR) {
1857                                 re_reset(sc);
1858                                 re_init(sc);
1859                         }
1860                 }
1861                 break;
1862         }
1863 }
1864 #endif /* DEVICE_POLLING */
1865
1866 static void
1867 re_intr(void *arg)
1868 {
1869         struct re_softc *sc = arg;
1870         struct ifnet *ifp = &sc->arpcom.ac_if;
1871         uint16_t status;
1872
1873         ASSERT_SERIALIZED(ifp->if_serializer);
1874
1875         if (sc->suspended || (ifp->if_flags & IFF_UP) == 0)
1876                 return;
1877
1878         for (;;) {
1879                 status = CSR_READ_2(sc, RE_ISR);
1880                 /* If the card has gone away the read returns 0xffff. */
1881                 if (status == 0xffff)
1882                         break;
1883                 if (status)
1884                         CSR_WRITE_2(sc, RE_ISR, status);
1885
1886                 if ((status & sc->re_intrs) == 0)
1887                         break;
1888
1889                 if (status & (RE_ISR_RX_OK | RE_ISR_RX_ERR | RE_ISR_FIFO_OFLOW))
1890                         re_rxeof(sc);
1891
1892                 if ((status & sc->re_tx_ack) ||
1893                     (status & RE_ISR_TX_ERR) ||
1894                     (status & RE_ISR_TX_DESC_UNAVAIL))
1895                         re_txeof(sc);
1896
1897                 if (status & RE_ISR_SYSTEM_ERR) {
1898                         re_reset(sc);
1899                         re_init(sc);
1900                 }
1901
1902                 if (status & RE_ISR_LINKCHG) {
1903                         callout_stop(&sc->re_timer);
1904                         re_tick_serialized(sc);
1905                 }
1906         }
1907
1908         if (!ifq_is_empty(&ifp->if_snd))
1909                 if_devstart(ifp);
1910 }
1911
1912 static int
1913 re_encap(struct re_softc *sc, struct mbuf **m_head, int *idx0)
1914 {
1915         struct ifnet *ifp = &sc->arpcom.ac_if;
1916         struct mbuf *m;
1917         struct re_dmaload_arg arg;
1918         bus_dma_segment_t segs[RE_MAXSEGS];
1919         bus_dmamap_t map;
1920         int error, maxsegs, idx, i;
1921         struct re_desc *d, *tx_ring;
1922         uint32_t csum_flags;
1923
1924         KASSERT(sc->re_ldata.re_tx_free > RE_TXDESC_SPARE,
1925                 ("not enough free TX desc\n"));
1926
1927         m = *m_head;
1928         map = sc->re_ldata.re_tx_dmamap[*idx0];
1929
1930         /*
1931          * Set up checksum offload. Note: checksum offload bits must
1932          * appear in all descriptors of a multi-descriptor transmit
1933          * attempt. (This is according to testing done with an 8169
1934          * chip. I'm not sure if this is a requirement or a bug.)
1935          */
1936         csum_flags = 0;
1937         if (m->m_pkthdr.csum_flags & CSUM_IP)
1938                 csum_flags |= RE_TDESC_CMD_IPCSUM;
1939         if (m->m_pkthdr.csum_flags & CSUM_TCP)
1940                 csum_flags |= RE_TDESC_CMD_TCPCSUM;
1941         if (m->m_pkthdr.csum_flags & CSUM_UDP)
1942                 csum_flags |= RE_TDESC_CMD_UDPCSUM;
1943
1944         if (m->m_pkthdr.len > sc->re_swcsum_lim &&
1945             (m->m_pkthdr.csum_flags & (CSUM_DELAY_IP | CSUM_DELAY_DATA)) &&
1946             (sc->re_flags & RE_F_JUMBO_SWCSUM)) {
1947                 struct ether_header *eh;
1948                 struct ip *ip;
1949                 u_short offset;
1950
1951                 m = m_pullup(m, sizeof(struct ether_header *));
1952                 if (m == NULL) {
1953                         *m_head = NULL;
1954                         return ENOBUFS;
1955                 }
1956                 eh = mtod(m, struct ether_header *);
1957
1958                 /* XXX */
1959                 if (eh->ether_type == ETHERTYPE_VLAN)
1960                         offset = sizeof(struct ether_vlan_header);
1961                 else
1962                         offset = sizeof(struct ether_header);
1963
1964                 m = m_pullup(m, offset + sizeof(struct ip *));
1965                 if (m == NULL) {
1966                         *m_head = NULL;
1967                         return ENOBUFS;
1968                 }
1969                 ip = (struct ip *)(mtod(m, uint8_t *) + offset);
1970
1971                 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1972                         u_short csum;
1973
1974                         offset += IP_VHL_HL(ip->ip_vhl) << 2;
1975                         csum = in_cksum_skip(m, ntohs(ip->ip_len), offset);
1976                         if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
1977                                 csum = 0xffff;
1978                         offset += m->m_pkthdr.csum_data;        /* checksum offset */
1979                         *(u_short *)(m->m_data + offset) = csum;
1980
1981                         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1982                 }
1983                 if (m->m_pkthdr.csum_flags & CSUM_DELAY_IP) {
1984                         ip->ip_sum = 0;
1985                         if (ip->ip_vhl == IP_VHL_BORING) {
1986                                 ip->ip_sum = in_cksum_hdr(ip);
1987                         } else {
1988                                 ip->ip_sum =
1989                                 in_cksum(m, IP_VHL_HL(ip->ip_vhl) << 2);
1990                         }
1991                         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_IP;
1992                 }
1993                 *m_head = m; /* 'm' may be changed by above two m_pullup() */
1994         }
1995
1996         /*
1997          * With some of the RealTek chips, using the checksum offload
1998          * support in conjunction with the autopadding feature results
1999          * in the transmission of corrupt frames. For example, if we
2000          * need to send a really small IP fragment that's less than 60
2001          * bytes in size, and IP header checksumming is enabled, the
2002          * resulting ethernet frame that appears on the wire will
2003          * have garbled payload. To work around this, if TX checksum
2004          * offload is enabled, we always manually pad short frames out
2005          * to the minimum ethernet frame size. We do this by pretending
2006          * the mbuf chain has too many fragments so the coalescing code
2007          * below can assemble the packet into a single buffer that's
2008          * padded out to the mininum frame size.
2009          *
2010          * Note: this appears unnecessary for TCP, and doing it for TCP
2011          * with PCIe adapters seems to result in bad checksums.
2012          */
2013         if (csum_flags && !(csum_flags & RE_TDESC_CMD_TCPCSUM) &&
2014             m->m_pkthdr.len < RE_MIN_FRAMELEN) {
2015                 error = re_pad_frame(m);
2016                 if (error)
2017                         goto back;
2018         }
2019
2020         maxsegs = sc->re_ldata.re_tx_free;
2021         if (maxsegs > RE_MAXSEGS)
2022                 maxsegs = RE_MAXSEGS;
2023
2024         arg.re_nsegs = maxsegs;
2025         arg.re_segs = segs;
2026         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map, m,
2027                                      re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
2028         if (error && error != EFBIG) {
2029                 if_printf(ifp, "can't map mbuf (error %d)\n", error);
2030                 goto back;
2031         }
2032
2033         /*
2034          * Too many segments to map, coalesce into a single mbuf
2035          */
2036         if (!error && arg.re_nsegs == 0) {
2037                 bus_dmamap_unload(sc->re_ldata.re_mtag, map);
2038                 error = EFBIG;
2039         }
2040         if (error) {
2041                 struct mbuf *m_new;
2042
2043                 m_new = m_defrag(m, MB_DONTWAIT);
2044                 if (m_new == NULL) {
2045                         if_printf(ifp, "can't defrag TX mbuf\n");
2046                         error = ENOBUFS;
2047                         goto back;
2048                 } else {
2049                         *m_head = m = m_new;
2050                 }
2051
2052                 arg.re_nsegs = maxsegs;
2053                 arg.re_segs = segs;
2054                 error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map, m,
2055                                              re_dma_map_desc, &arg,
2056                                              BUS_DMA_NOWAIT);
2057                 if (error || arg.re_nsegs == 0) {
2058                         if (!error) {
2059                                 bus_dmamap_unload(sc->re_ldata.re_mtag, map);
2060                                 error = EFBIG;
2061                         }
2062                         if_printf(ifp, "can't map mbuf (error %d)\n", error);
2063                         goto back;
2064                 }
2065         }
2066         bus_dmamap_sync(sc->re_ldata.re_mtag, map, BUS_DMASYNC_PREWRITE);
2067
2068         /*
2069          * Map the segment array into descriptors.  We also keep track
2070          * of the end of the ring and set the end-of-ring bits as needed,
2071          * and we set the ownership bits in all except the very first
2072          * descriptor, whose ownership bits will be turned on later.
2073          */
2074         tx_ring = sc->re_ldata.re_tx_list;
2075         idx = *idx0;
2076         i = 0;
2077         for (;;) {
2078                 uint32_t cmdstat;
2079
2080                 d = &tx_ring[idx];
2081
2082                 cmdstat = segs[i].ds_len;
2083                 d->re_bufaddr_lo = htole32(RE_ADDR_LO(segs[i].ds_addr));
2084                 d->re_bufaddr_hi = htole32(RE_ADDR_HI(segs[i].ds_addr));
2085                 if (i == 0)
2086                         cmdstat |= RE_TDESC_CMD_SOF;
2087                 else
2088                         cmdstat |= RE_TDESC_CMD_OWN;
2089                 if (idx == (RE_TX_DESC_CNT - 1))
2090                         cmdstat |= RE_TDESC_CMD_EOR;
2091                 d->re_cmdstat = htole32(cmdstat | csum_flags);
2092
2093                 i++;
2094                 if (i == arg.re_nsegs)
2095                         break;
2096                 RE_DESC_INC(idx);
2097         }
2098         d->re_cmdstat |= htole32(RE_TDESC_CMD_EOF);
2099
2100         /*
2101          * Set up hardware VLAN tagging. Note: vlan tag info must
2102          * appear in the first descriptor of a multi-descriptor
2103          * transmission attempt.
2104          */
2105         if (m->m_flags & M_VLANTAG) {
2106                 tx_ring[*idx0].re_vlanctl =
2107                     htole32(htobe16(m->m_pkthdr.ether_vlantag) |
2108                             RE_TDESC_VLANCTL_TAG);
2109         }
2110
2111         /* Transfer ownership of packet to the chip. */
2112         d->re_cmdstat |= htole32(RE_TDESC_CMD_OWN);
2113         if (*idx0 != idx)
2114                 tx_ring[*idx0].re_cmdstat |= htole32(RE_TDESC_CMD_OWN);
2115
2116         /*
2117          * Insure that the map for this transmission
2118          * is placed at the array index of the last descriptor
2119          * in this chain.
2120          */
2121         sc->re_ldata.re_tx_dmamap[*idx0] = sc->re_ldata.re_tx_dmamap[idx];
2122         sc->re_ldata.re_tx_dmamap[idx] = map;
2123
2124         sc->re_ldata.re_tx_mbuf[idx] = m;
2125         sc->re_ldata.re_tx_free -= arg.re_nsegs;
2126
2127         RE_DESC_INC(idx);
2128         *idx0 = idx;
2129 back:
2130         if (error) {
2131                 m_freem(m);
2132                 *m_head = NULL;
2133         }
2134         return error;
2135 }
2136
2137 /*
2138  * Main transmit routine for C+ and gigE NICs.
2139  */
2140
2141 static void
2142 re_start(struct ifnet *ifp)
2143 {
2144         struct re_softc *sc = ifp->if_softc;
2145         struct mbuf *m_head;
2146         int idx, need_trans;
2147
2148         ASSERT_SERIALIZED(ifp->if_serializer);
2149
2150         if (!sc->re_link) {
2151                 ifq_purge(&ifp->if_snd);
2152                 return;
2153         }
2154
2155         if ((ifp->if_flags & (IFF_OACTIVE | IFF_RUNNING)) != IFF_RUNNING)
2156                 return;
2157
2158         idx = sc->re_ldata.re_tx_prodidx;
2159
2160         need_trans = 0;
2161         while (sc->re_ldata.re_tx_mbuf[idx] == NULL) {
2162                 if (sc->re_ldata.re_tx_free <= RE_TXDESC_SPARE) {
2163                         ifp->if_flags |= IFF_OACTIVE;
2164                         break;
2165                 }
2166
2167                 m_head = ifq_dequeue(&ifp->if_snd, NULL);
2168                 if (m_head == NULL)
2169                         break;
2170
2171                 if (re_encap(sc, &m_head, &idx)) {
2172                         /* m_head is freed by re_encap(), if we reach here */
2173                         ifp->if_oerrors++;
2174                         ifp->if_flags |= IFF_OACTIVE;
2175                         break;
2176                 }
2177
2178                 need_trans = 1;
2179
2180                 /*
2181                  * If there's a BPF listener, bounce a copy of this frame
2182                  * to him.
2183                  */
2184                 ETHER_BPF_MTAP(ifp, m_head);
2185         }
2186
2187         if (!need_trans) {
2188                 if (RE_TX_MODERATION_IS_ENABLED(sc) &&
2189                     sc->re_ldata.re_tx_free != RE_TX_DESC_CNT)
2190                         CSR_WRITE_4(sc, RE_TIMERCNT, 1);
2191                 return;
2192         }
2193
2194         /* Flush the TX descriptors */
2195         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
2196                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
2197
2198         sc->re_ldata.re_tx_prodidx = idx;
2199
2200         /*
2201          * RealTek put the TX poll request register in a different
2202          * location on the 8169 gigE chip. I don't know why.
2203          */
2204         CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
2205
2206         if (RE_TX_MODERATION_IS_ENABLED(sc)) {
2207                 /*
2208                  * Use the countdown timer for interrupt moderation.
2209                  * 'TX done' interrupts are disabled. Instead, we reset the
2210                  * countdown timer, which will begin counting until it hits
2211                  * the value in the TIMERINT register, and then trigger an
2212                  * interrupt. Each time we write to the TIMERCNT register,
2213                  * the timer count is reset to 0.
2214                  */
2215                 CSR_WRITE_4(sc, RE_TIMERCNT, 1);
2216         }
2217
2218         /*
2219          * Set a timeout in case the chip goes out to lunch.
2220          */
2221         ifp->if_timer = 5;
2222 }
2223
2224 static void
2225 re_init(void *xsc)
2226 {
2227         struct re_softc *sc = xsc;
2228         struct ifnet *ifp = &sc->arpcom.ac_if;
2229         struct mii_data *mii;
2230         uint32_t rxcfg = 0;
2231         int error;
2232
2233         ASSERT_SERIALIZED(ifp->if_serializer);
2234
2235         mii = device_get_softc(sc->re_miibus);
2236
2237         /*
2238          * Cancel pending I/O and free all RX/TX buffers.
2239          */
2240         re_stop(sc);
2241
2242         /*
2243          * Enable C+ RX and TX mode, as well as VLAN stripping and
2244          * RX checksum offload. We must configure the C+ register
2245          * before all others.
2246          */
2247         CSR_WRITE_2(sc, RE_CPLUS_CMD, RE_CPLUSCMD_RXENB | RE_CPLUSCMD_TXENB |
2248                     RE_CPLUSCMD_PCI_MRW | RE_CPLUSCMD_VLANSTRIP |
2249                     (ifp->if_capenable & IFCAP_RXCSUM ?
2250                      RE_CPLUSCMD_RXCSUM_ENB : 0));
2251
2252         /*
2253          * Init our MAC address.  Even though the chipset
2254          * documentation doesn't mention it, we need to enter "Config
2255          * register write enable" mode to modify the ID registers.
2256          */
2257         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_WRITECFG);
2258         CSR_WRITE_4(sc, RE_IDR0,
2259             htole32(*(uint32_t *)(&sc->arpcom.ac_enaddr[0])));
2260         CSR_WRITE_2(sc, RE_IDR4,
2261             htole16(*(uint16_t *)(&sc->arpcom.ac_enaddr[4])));
2262         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_OFF);
2263
2264         /*
2265          * For C+ mode, initialize the RX descriptors and mbufs.
2266          */
2267         error = re_rx_list_init(sc);
2268         if (error) {
2269                 re_stop(sc);
2270                 return;
2271         }
2272         error = re_tx_list_init(sc);
2273         if (error) {
2274                 re_stop(sc);
2275                 return;
2276         }
2277
2278         /*
2279          * Load the addresses of the RX and TX lists into the chip.
2280          */
2281         CSR_WRITE_4(sc, RE_RXLIST_ADDR_HI,
2282             RE_ADDR_HI(sc->re_ldata.re_rx_list_addr));
2283         CSR_WRITE_4(sc, RE_RXLIST_ADDR_LO,
2284             RE_ADDR_LO(sc->re_ldata.re_rx_list_addr));
2285
2286         CSR_WRITE_4(sc, RE_TXLIST_ADDR_HI,
2287             RE_ADDR_HI(sc->re_ldata.re_tx_list_addr));
2288         CSR_WRITE_4(sc, RE_TXLIST_ADDR_LO,
2289             RE_ADDR_LO(sc->re_ldata.re_tx_list_addr));
2290
2291         /*
2292          * Enable transmit and receive.
2293          */
2294         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2295
2296         /*
2297          * Set the initial TX and RX configuration.
2298          */
2299         if (sc->re_testmode) {
2300                 if (sc->re_type == RE_8169)
2301                         CSR_WRITE_4(sc, RE_TXCFG,
2302                                     RE_TXCFG_CONFIG | RE_LOOPTEST_ON);
2303                 else
2304                         CSR_WRITE_4(sc, RE_TXCFG,
2305                                     RE_TXCFG_CONFIG | RE_LOOPTEST_ON_CPLUS);
2306         } else
2307                 CSR_WRITE_4(sc, RE_TXCFG, RE_TXCFG_CONFIG);
2308
2309         CSR_WRITE_1(sc, RE_EARLY_TX_THRESH, 16);
2310
2311         CSR_WRITE_4(sc, RE_RXCFG, RE_RXCFG_CONFIG);
2312
2313         /* Set the individual bit to receive frames for this host only. */
2314         rxcfg = CSR_READ_4(sc, RE_RXCFG);
2315         rxcfg |= RE_RXCFG_RX_INDIV;
2316
2317         /* If we want promiscuous mode, set the allframes bit. */
2318         if (ifp->if_flags & IFF_PROMISC) {
2319                 rxcfg |= RE_RXCFG_RX_ALLPHYS;
2320                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2321         } else {
2322                 rxcfg &= ~RE_RXCFG_RX_ALLPHYS;
2323                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2324         }
2325
2326         /*
2327          * Set capture broadcast bit to capture broadcast frames.
2328          */
2329         if (ifp->if_flags & IFF_BROADCAST) {
2330                 rxcfg |= RE_RXCFG_RX_BROAD;
2331                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2332         } else {
2333                 rxcfg &= ~RE_RXCFG_RX_BROAD;
2334                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2335         }
2336
2337         /*
2338          * Program the multicast filter, if necessary.
2339          */
2340         re_setmulti(sc);
2341
2342 #ifdef DEVICE_POLLING
2343         /*
2344          * Disable interrupts if we are polling.
2345          */
2346         if (ifp->if_flags & IFF_POLLING)
2347                 CSR_WRITE_2(sc, RE_IMR, 0);
2348         else    /* otherwise ... */
2349 #endif /* DEVICE_POLLING */
2350         /*
2351          * Enable interrupts.
2352          */
2353         if (sc->re_testmode)
2354                 CSR_WRITE_2(sc, RE_IMR, 0);
2355         else
2356                 CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
2357         CSR_WRITE_2(sc, RE_ISR, sc->re_intrs);
2358
2359         /* Set initial TX threshold */
2360         sc->re_txthresh = RE_TX_THRESH_INIT;
2361
2362         /* Start RX/TX process. */
2363         if (sc->re_flags & RE_F_HASMPC)
2364                 CSR_WRITE_4(sc, RE_MISSEDPKT, 0);
2365 #ifdef notdef
2366         /* Enable receiver and transmitter. */
2367         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2368 #endif
2369
2370         if (RE_TX_MODERATION_IS_ENABLED(sc)) {
2371                 /*
2372                  * Initialize the timer interrupt register so that
2373                  * a timer interrupt will be generated once the timer
2374                  * reaches a certain number of ticks. The timer is
2375                  * reloaded on each transmit. This gives us TX interrupt
2376                  * moderation, which dramatically improves TX frame rate.
2377                  */
2378                 if (sc->re_type == RE_8169)
2379                         CSR_WRITE_4(sc, RE_TIMERINT_8169, 0x800);
2380                 else
2381                         CSR_WRITE_4(sc, RE_TIMERINT, 0x400);
2382         }
2383
2384         /*
2385          * For 8169 gigE NICs, set the max allowed RX packet
2386          * size so we can receive jumbo frames.
2387          */
2388         if (sc->re_type == RE_8169)
2389                 CSR_WRITE_2(sc, RE_MAXRXPKTLEN, 16383);
2390
2391         if (sc->re_testmode) {
2392                 return;
2393         }
2394
2395         mii_mediachg(mii);
2396
2397         CSR_WRITE_1(sc, RE_CFG1, RE_CFG1_DRVLOAD|RE_CFG1_FULLDUPLEX);
2398
2399         ifp->if_flags |= IFF_RUNNING;
2400         ifp->if_flags &= ~IFF_OACTIVE;
2401
2402         sc->re_link = 0;
2403         callout_reset(&sc->re_timer, hz, re_tick, sc);
2404 }
2405
2406 /*
2407  * Set media options.
2408  */
2409 static int
2410 re_ifmedia_upd(struct ifnet *ifp)
2411 {
2412         struct re_softc *sc = ifp->if_softc;
2413         struct mii_data *mii;
2414
2415         ASSERT_SERIALIZED(ifp->if_serializer);
2416
2417         mii = device_get_softc(sc->re_miibus);
2418         mii_mediachg(mii);
2419
2420         return(0);
2421 }
2422
2423 /*
2424  * Report current media status.
2425  */
2426 static void
2427 re_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2428 {
2429         struct re_softc *sc = ifp->if_softc;
2430         struct mii_data *mii;
2431
2432         ASSERT_SERIALIZED(ifp->if_serializer);
2433
2434         mii = device_get_softc(sc->re_miibus);
2435
2436         mii_pollstat(mii);
2437         ifmr->ifm_active = mii->mii_media_active;
2438         ifmr->ifm_status = mii->mii_media_status;
2439 }
2440
2441 static int
2442 re_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
2443 {
2444         struct re_softc *sc = ifp->if_softc;
2445         struct ifreq *ifr = (struct ifreq *) data;
2446         struct mii_data *mii;
2447         int error = 0;
2448
2449         ASSERT_SERIALIZED(ifp->if_serializer);
2450
2451         switch(command) {
2452         case SIOCSIFMTU:
2453                 if (ifr->ifr_mtu > RE_JUMBO_MTU)
2454                         error = EINVAL;
2455                 ifp->if_mtu = ifr->ifr_mtu;
2456                 break;
2457         case SIOCSIFFLAGS:
2458                 if (ifp->if_flags & IFF_UP)
2459                         re_init(sc);
2460                 else if (ifp->if_flags & IFF_RUNNING)
2461                         re_stop(sc);
2462                 break;
2463         case SIOCADDMULTI:
2464         case SIOCDELMULTI:
2465                 re_setmulti(sc);
2466                 error = 0;
2467                 break;
2468         case SIOCGIFMEDIA:
2469         case SIOCSIFMEDIA:
2470                 mii = device_get_softc(sc->re_miibus);
2471                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
2472                 break;
2473         case SIOCSIFCAP:
2474                 ifp->if_capenable &= ~(IFCAP_HWCSUM);
2475                 ifp->if_capenable |=
2476                     ifr->ifr_reqcap & (IFCAP_HWCSUM);
2477                 if (ifp->if_capenable & IFCAP_TXCSUM)
2478                         ifp->if_hwassist = RE_CSUM_FEATURES;
2479                 else
2480                         ifp->if_hwassist = 0;
2481                 if (ifp->if_flags & IFF_RUNNING)
2482                         re_init(sc);
2483                 break;
2484         default:
2485                 error = ether_ioctl(ifp, command, data);
2486                 break;
2487         }
2488         return(error);
2489 }
2490
2491 static void
2492 re_watchdog(struct ifnet *ifp)
2493 {
2494         struct re_softc *sc = ifp->if_softc;
2495
2496         ASSERT_SERIALIZED(ifp->if_serializer);
2497
2498         if_printf(ifp, "watchdog timeout\n");
2499
2500         ifp->if_oerrors++;
2501
2502         re_txeof(sc);
2503         re_rxeof(sc);
2504
2505         re_init(sc);
2506
2507         if (!ifq_is_empty(&ifp->if_snd))
2508                 if_devstart(ifp);
2509 }
2510
2511 /*
2512  * Stop the adapter and free any mbufs allocated to the
2513  * RX and TX lists.
2514  */
2515 static void
2516 re_stop(struct re_softc *sc)
2517 {
2518         struct ifnet *ifp = &sc->arpcom.ac_if;
2519         int i;
2520
2521         ASSERT_SERIALIZED(ifp->if_serializer);
2522
2523         ifp->if_timer = 0;
2524         callout_stop(&sc->re_timer);
2525
2526         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2527
2528         CSR_WRITE_1(sc, RE_COMMAND, 0x00);
2529         CSR_WRITE_2(sc, RE_IMR, 0x0000);
2530         CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
2531
2532         re_free_rxchain(sc);
2533         sc->re_drop_rxfrag = 0;
2534
2535         /* Free the TX list buffers. */
2536         for (i = 0; i < RE_TX_DESC_CNT; i++) {
2537                 if (sc->re_ldata.re_tx_mbuf[i] != NULL) {
2538                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2539                                           sc->re_ldata.re_tx_dmamap[i]);
2540                         m_freem(sc->re_ldata.re_tx_mbuf[i]);
2541                         sc->re_ldata.re_tx_mbuf[i] = NULL;
2542                 }
2543         }
2544
2545         /* Free the RX list buffers. */
2546         for (i = 0; i < RE_RX_DESC_CNT; i++) {
2547                 if (sc->re_ldata.re_rx_mbuf[i] != NULL) {
2548                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2549                                           sc->re_ldata.re_rx_dmamap[i]);
2550                         m_freem(sc->re_ldata.re_rx_mbuf[i]);
2551                         sc->re_ldata.re_rx_mbuf[i] = NULL;
2552                 }
2553         }
2554 }
2555
2556 /*
2557  * Device suspend routine.  Stop the interface and save some PCI
2558  * settings in case the BIOS doesn't restore them properly on
2559  * resume.
2560  */
2561 static int
2562 re_suspend(device_t dev)
2563 {
2564 #ifndef BURN_BRIDGES
2565         int i;
2566 #endif
2567         struct re_softc *sc = device_get_softc(dev);
2568         struct ifnet *ifp = &sc->arpcom.ac_if;
2569
2570         lwkt_serialize_enter(ifp->if_serializer);
2571
2572         re_stop(sc);
2573
2574 #ifndef BURN_BRIDGES
2575         for (i = 0; i < 5; i++)
2576                 sc->saved_maps[i] = pci_read_config(dev, PCIR_MAPS + i * 4, 4);
2577         sc->saved_biosaddr = pci_read_config(dev, PCIR_BIOS, 4);
2578         sc->saved_intline = pci_read_config(dev, PCIR_INTLINE, 1);
2579         sc->saved_cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
2580         sc->saved_lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
2581 #endif
2582
2583         sc->suspended = 1;
2584
2585         lwkt_serialize_exit(ifp->if_serializer);
2586
2587         return (0);
2588 }
2589
2590 /*
2591  * Device resume routine.  Restore some PCI settings in case the BIOS
2592  * doesn't, re-enable busmastering, and restart the interface if
2593  * appropriate.
2594  */
2595 static int
2596 re_resume(device_t dev)
2597 {
2598         struct re_softc *sc = device_get_softc(dev);
2599         struct ifnet *ifp = &sc->arpcom.ac_if;
2600 #ifndef BURN_BRIDGES
2601         int i;
2602 #endif
2603
2604         lwkt_serialize_enter(ifp->if_serializer);
2605
2606 #ifndef BURN_BRIDGES
2607         /* better way to do this? */
2608         for (i = 0; i < 5; i++)
2609                 pci_write_config(dev, PCIR_MAPS + i * 4, sc->saved_maps[i], 4);
2610         pci_write_config(dev, PCIR_BIOS, sc->saved_biosaddr, 4);
2611         pci_write_config(dev, PCIR_INTLINE, sc->saved_intline, 1);
2612         pci_write_config(dev, PCIR_CACHELNSZ, sc->saved_cachelnsz, 1);
2613         pci_write_config(dev, PCIR_LATTIMER, sc->saved_lattimer, 1);
2614
2615         /* reenable busmastering */
2616         pci_enable_busmaster(dev);
2617         pci_enable_io(dev, SYS_RES_IOPORT);
2618 #endif
2619
2620         /* reinitialize interface if necessary */
2621         if (ifp->if_flags & IFF_UP)
2622                 re_init(sc);
2623
2624         sc->suspended = 0;
2625
2626         lwkt_serialize_exit(ifp->if_serializer);
2627
2628         return (0);
2629 }
2630
2631 /*
2632  * Stop all chip I/O so that the kernel's probe routines don't
2633  * get confused by errant DMAs when rebooting.
2634  */
2635 static void
2636 re_shutdown(device_t dev)
2637 {
2638         struct re_softc *sc = device_get_softc(dev);
2639         struct ifnet *ifp = &sc->arpcom.ac_if;
2640
2641         lwkt_serialize_enter(ifp->if_serializer);
2642         re_stop(sc);
2643         lwkt_serialize_exit(ifp->if_serializer);
2644 }
2645
2646 static int
2647 re_sysctl_tx_moderation(SYSCTL_HANDLER_ARGS)
2648 {
2649         struct re_softc *sc = arg1;
2650         struct ifnet *ifp = &sc->arpcom.ac_if;
2651         int error = 0, mod, mod_old;
2652
2653         lwkt_serialize_enter(ifp->if_serializer);
2654
2655         mod_old = mod = RE_TX_MODERATION_IS_ENABLED(sc);
2656
2657         error = sysctl_handle_int(oidp, &mod, 0, req);
2658         if (error || req->newptr == NULL || mod == mod_old)
2659                 goto back;
2660         if (mod != 0 && mod != 1) {
2661                 error = EINVAL;
2662                 goto back;
2663         }
2664
2665         if (mod)
2666                 RE_ENABLE_TX_MODERATION(sc);
2667         else
2668                 RE_DISABLE_TX_MODERATION(sc);
2669
2670         if ((ifp->if_flags & (IFF_RUNNING | IFF_UP)) == (IFF_RUNNING | IFF_UP))
2671                 re_init(sc);
2672 back:
2673         lwkt_serialize_exit(ifp->if_serializer);
2674         return error;
2675 }
2676
2677 static int
2678 re_pad_frame(struct mbuf *pkt)
2679 {
2680         struct mbuf *last = NULL;
2681         int padlen;
2682
2683         padlen = RE_MIN_FRAMELEN - pkt->m_pkthdr.len;
2684
2685         /* if there's only the packet-header and we can pad there, use it. */
2686         if (pkt->m_pkthdr.len == pkt->m_len &&
2687             M_TRAILINGSPACE(pkt) >= padlen) {
2688                 last = pkt;
2689         } else {
2690                 /*
2691                  * Walk packet chain to find last mbuf. We will either
2692                  * pad there, or append a new mbuf and pad it
2693                  */
2694                 for (last = pkt; last->m_next != NULL; last = last->m_next)
2695                         ; /* EMPTY */
2696
2697                 /* `last' now points to last in chain. */
2698                 if (M_TRAILINGSPACE(last) < padlen) {
2699                         struct mbuf *n;
2700
2701                         /* Allocate new empty mbuf, pad it.  Compact later. */
2702                         MGET(n, MB_DONTWAIT, MT_DATA);
2703                         if (n == NULL)
2704                                 return ENOBUFS;
2705                         n->m_len = 0;
2706                         last->m_next = n;
2707                         last = n;
2708                 }
2709         }
2710         KKASSERT(M_TRAILINGSPACE(last) >= padlen);
2711         KKASSERT(M_WRITABLE(last));
2712
2713         /* Now zero the pad area, to avoid the re cksum-assist bug */
2714         bzero(mtod(last, char *) + last->m_len, padlen);
2715         last->m_len += padlen;
2716         pkt->m_pkthdr.len += padlen;
2717         return 0;
2718 }