According to wpaul's comment, 8139C+ only support 64 TX/RX descriptors
[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.84 2008/10/16 12:46:40 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
160 /*
161  * Various supported device vendors/types and their names.
162  */
163 static const struct re_type {
164         uint16_t        re_vid;
165         uint16_t        re_did;
166         const char      *re_name;
167 } re_devs[] = {
168         { PCI_VENDOR_DLINK, PCI_PRODUCT_DLINK_DGE528T,
169           "D-Link DGE-528(T) Gigabit Ethernet Adapter" },
170
171         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8139,
172           "RealTek 8139C+ 10/100BaseTX" },
173
174         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8101E,
175           "RealTek 810x PCIe 10/100baseTX" },
176
177         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168,
178           "RealTek 8111/8168 PCIe Gigabit Ethernet" },
179
180         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169,
181           "RealTek 8110/8169 Gigabit Ethernet" },
182
183         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169SC,
184           "RealTek 8169SC/8110SC Single-chip Gigabit Ethernet" },
185
186         { PCI_VENDOR_COREGA, PCI_PRODUCT_COREGA_CG_LAPCIGT,
187                 "Corega CG-LAPCIGT Gigabit Ethernet" },
188
189         { PCI_VENDOR_LINKSYS, PCI_PRODUCT_LINKSYS_EG1032,
190           "Linksys EG1032 Gigabit Ethernet" },
191
192         { PCI_VENDOR_USR2, PCI_PRODUCT_USR2_997902,
193           "US Robotics 997902 Gigabit Ethernet" },
194
195         { 0, 0, NULL }
196 };
197
198 static const struct re_hwrev re_hwrevs[] = {
199         { RE_HWREV_8139CPLUS,   RE_MACVER_UNKN,
200           RE_C_HWCSUM | RE_C_8139CP },
201
202         { RE_HWREV_8169,        RE_MACVER_UNKN,
203           RE_C_HWCSUM | RE_C_JUMBO | RE_C_8169 },
204
205         { RE_HWREV_8110S,       RE_MACVER_03,
206           RE_C_HWCSUM | RE_C_JUMBO | RE_C_8169 },
207
208         { RE_HWREV_8169S,       RE_MACVER_03,
209           RE_C_HWCSUM | RE_C_JUMBO | RE_C_8169 },
210
211         { RE_HWREV_8169SB,      RE_MACVER_04,
212           RE_C_HWCSUM | RE_C_JUMBO | RE_C_PHYPMGT | RE_C_8169 },
213
214         { RE_HWREV_8169SC1,     RE_MACVER_05,
215           RE_C_HWCSUM | RE_C_JUMBO | RE_C_PHYPMGT | RE_C_8169 },
216
217         { RE_HWREV_8169SC2,     RE_MACVER_06,
218           RE_C_HWCSUM | RE_C_JUMBO | RE_C_PHYPMGT | RE_C_8169 },
219
220         { RE_HWREV_8168B1,      RE_MACVER_21,
221           RE_C_HWIM | RE_C_HWCSUM | RE_C_JUMBO | RE_C_PHYPMGT },
222
223         { RE_HWREV_8168B2,      RE_MACVER_23,
224           RE_C_HWIM | RE_C_HWCSUM | RE_C_JUMBO | RE_C_PHYPMGT | RE_C_AUTOPAD },
225
226         { RE_HWREV_8168B3,      RE_MACVER_23,
227           RE_C_HWIM | RE_C_HWCSUM | RE_C_JUMBO | RE_C_PHYPMGT | RE_C_AUTOPAD },
228
229         { RE_HWREV_8168C,       RE_MACVER_29,
230           RE_C_HWIM | RE_C_HWCSUM | RE_C_JUMBO | RE_C_MAC2 | RE_C_PHYPMGT |
231           RE_C_AUTOPAD },
232
233         { RE_HWREV_8168CP,      RE_MACVER_2B,
234           RE_C_HWIM | RE_C_HWCSUM | RE_C_JUMBO | RE_C_MAC2 | RE_C_PHYPMGT |
235           RE_C_AUTOPAD },
236
237         { RE_HWREV_8168D,       RE_MACVER_2A,
238           RE_C_HWIM | RE_C_HWCSUM | RE_C_JUMBO | RE_C_MAC2 | RE_C_PHYPMGT |
239           RE_C_AUTOPAD },
240
241         { RE_HWREV_8100E,       RE_MACVER_UNKN,
242           RE_C_HWCSUM },
243
244         { RE_HWREV_8101E1,      RE_MACVER_16,
245           RE_C_HWCSUM },
246
247         { RE_HWREV_8101E2,      RE_MACVER_16,
248           RE_C_HWCSUM },
249
250         { RE_HWREV_8102E,       RE_MACVER_15,
251           RE_C_HWCSUM | RE_C_MAC2 | RE_C_AUTOPAD },
252
253         { RE_HWREV_8102EL,      RE_MACVER_15,
254           RE_C_HWCSUM | RE_C_MAC2 | RE_C_AUTOPAD },
255
256         { RE_HWREV_NULL, 0, 0 }
257 };
258
259 static int      re_probe(device_t);
260 static int      re_attach(device_t);
261 static int      re_detach(device_t);
262 static int      re_suspend(device_t);
263 static int      re_resume(device_t);
264 static void     re_shutdown(device_t);
265
266 static void     re_dma_map_addr(void *, bus_dma_segment_t *, int, int);
267 static void     re_dma_map_desc(void *, bus_dma_segment_t *, int,
268                                 bus_size_t, int);
269 static int      re_allocmem(device_t);
270 static void     re_freemem(device_t);
271 static void     re_freebufmem(struct re_softc *, int, int);
272 static int      re_encap(struct re_softc *, struct mbuf **, int *);
273 static int      re_newbuf(struct re_softc *, int, int);
274 static void     re_setup_rxdesc(struct re_softc *, int);
275 static int      re_rx_list_init(struct re_softc *);
276 static int      re_tx_list_init(struct re_softc *);
277 static int      re_rxeof(struct re_softc *);
278 static int      re_txeof(struct re_softc *);
279 static void     re_intr(void *);
280 static void     re_tick(void *);
281 static void     re_tick_serialized(void *);
282
283 static void     re_start(struct ifnet *);
284 static int      re_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
285 static void     re_init(void *);
286 static void     re_stop(struct re_softc *);
287 static void     re_watchdog(struct ifnet *);
288 static int      re_ifmedia_upd(struct ifnet *);
289 static void     re_ifmedia_sts(struct ifnet *, struct ifmediareq *);
290
291 static void     re_eeprom_putbyte(struct re_softc *, int);
292 static void     re_eeprom_getword(struct re_softc *, int, u_int16_t *);
293 static void     re_read_eeprom(struct re_softc *, caddr_t, int, int);
294 static void     re_get_eewidth(struct re_softc *);
295
296 static int      re_gmii_readreg(device_t, int, int);
297 static int      re_gmii_writereg(device_t, int, int, int);
298
299 static int      re_miibus_readreg(device_t, int, int);
300 static int      re_miibus_writereg(device_t, int, int, int);
301 static void     re_miibus_statchg(device_t);
302
303 static void     re_setmulti(struct re_softc *);
304 static void     re_reset(struct re_softc *);
305 static void     re_get_eaddr(struct re_softc *, uint8_t *);
306 static int      re_pad_frame(struct mbuf *);
307
308 static void     re_setup_hw_im(struct re_softc *);
309 static void     re_setup_sim_im(struct re_softc *);
310 static void     re_disable_hw_im(struct re_softc *);
311 static void     re_disable_sim_im(struct re_softc *);
312 static void     re_config_imtype(struct re_softc *, int);
313 static void     re_setup_intr(struct re_softc *, int, int);
314
315 static int      re_sysctl_hwtime(SYSCTL_HANDLER_ARGS, int *);
316 static int      re_sysctl_rxtime(SYSCTL_HANDLER_ARGS);
317 static int      re_sysctl_txtime(SYSCTL_HANDLER_ARGS);
318 static int      re_sysctl_simtime(SYSCTL_HANDLER_ARGS);
319 static int      re_sysctl_imtype(SYSCTL_HANDLER_ARGS);
320
321 #ifdef RE_DIAG
322 static int      re_diag(struct re_softc *);
323 #endif
324
325 #ifdef DEVICE_POLLING
326 static void     re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count);
327 #endif
328
329 static device_method_t re_methods[] = {
330         /* Device interface */
331         DEVMETHOD(device_probe,         re_probe),
332         DEVMETHOD(device_attach,        re_attach),
333         DEVMETHOD(device_detach,        re_detach),
334         DEVMETHOD(device_suspend,       re_suspend),
335         DEVMETHOD(device_resume,        re_resume),
336         DEVMETHOD(device_shutdown,      re_shutdown),
337
338         /* bus interface */
339         DEVMETHOD(bus_print_child,      bus_generic_print_child),
340         DEVMETHOD(bus_driver_added,     bus_generic_driver_added),
341
342         /* MII interface */
343         DEVMETHOD(miibus_readreg,       re_miibus_readreg),
344         DEVMETHOD(miibus_writereg,      re_miibus_writereg),
345         DEVMETHOD(miibus_statchg,       re_miibus_statchg),
346
347         { 0, 0 }
348 };
349
350 static driver_t re_driver = {
351         "re",
352         re_methods,
353         sizeof(struct re_softc)
354 };
355
356 static devclass_t re_devclass;
357
358 DECLARE_DUMMY_MODULE(if_re);
359 DRIVER_MODULE(if_re, pci, re_driver, re_devclass, 0, 0);
360 DRIVER_MODULE(if_re, cardbus, re_driver, re_devclass, 0, 0);
361 DRIVER_MODULE(miibus, re, miibus_driver, miibus_devclass, 0, 0);
362
363 static int      re_rx_desc_count = RE_RX_DESC_CNT_DEF;
364 static int      re_tx_desc_count = RE_TX_DESC_CNT_DEF;
365
366 TUNABLE_INT("hw.re.rx_desc_count", &re_rx_desc_count);
367 TUNABLE_INT("hw.re.tx_desc_count", &re_tx_desc_count);
368
369 #define EE_SET(x)       \
370         CSR_WRITE_1(sc, RE_EECMD, CSR_READ_1(sc, RE_EECMD) | (x))
371
372 #define EE_CLR(x)       \
373         CSR_WRITE_1(sc, RE_EECMD, CSR_READ_1(sc, RE_EECMD) & ~(x))
374
375 static __inline void
376 re_free_rxchain(struct re_softc *sc)
377 {
378         if (sc->re_head != NULL) {
379                 m_freem(sc->re_head);
380                 sc->re_head = sc->re_tail = NULL;
381         }
382 }
383
384 /*
385  * Send a read command and address to the EEPROM, check for ACK.
386  */
387 static void
388 re_eeprom_putbyte(struct re_softc *sc, int addr)
389 {
390         int d, i;
391
392         d = addr | (RE_9346_READ << sc->re_eewidth);
393
394         /*
395          * Feed in each bit and strobe the clock.
396          */
397         for (i = 1 << (sc->re_eewidth + 3); i; i >>= 1) {
398                 if (d & i)
399                         EE_SET(RE_EE_DATAIN);
400                 else
401                         EE_CLR(RE_EE_DATAIN);
402                 DELAY(100);
403                 EE_SET(RE_EE_CLK);
404                 DELAY(150);
405                 EE_CLR(RE_EE_CLK);
406                 DELAY(100);
407         }
408 }
409
410 /*
411  * Read a word of data stored in the EEPROM at address 'addr.'
412  */
413 static void
414 re_eeprom_getword(struct re_softc *sc, int addr, uint16_t *dest)
415 {
416         int i;
417         uint16_t word = 0;
418
419         /*
420          * Send address of word we want to read.
421          */
422         re_eeprom_putbyte(sc, addr);
423
424         /*
425          * Start reading bits from EEPROM.
426          */
427         for (i = 0x8000; i != 0; i >>= 1) {
428                 EE_SET(RE_EE_CLK);
429                 DELAY(100);
430                 if (CSR_READ_1(sc, RE_EECMD) & RE_EE_DATAOUT)
431                         word |= i;
432                 EE_CLR(RE_EE_CLK);
433                 DELAY(100);
434         }
435
436         *dest = word;
437 }
438
439 /*
440  * Read a sequence of words from the EEPROM.
441  */
442 static void
443 re_read_eeprom(struct re_softc *sc, caddr_t dest, int off, int cnt)
444 {
445         int i;
446         uint16_t word = 0, *ptr;
447
448         CSR_SETBIT_1(sc, RE_EECMD, RE_EEMODE_PROGRAM);
449         DELAY(100);
450
451         for (i = 0; i < cnt; i++) {
452                 CSR_SETBIT_1(sc, RE_EECMD, RE_EE_SEL);
453                 re_eeprom_getword(sc, off + i, &word);
454                 CSR_CLRBIT_1(sc, RE_EECMD, RE_EE_SEL);
455                 ptr = (uint16_t *)(dest + (i * 2));
456                 *ptr = word;
457         }
458
459         CSR_CLRBIT_1(sc, RE_EECMD, RE_EEMODE_PROGRAM);
460 }
461
462 static void
463 re_get_eewidth(struct re_softc *sc)
464 {
465         uint16_t re_did = 0;
466
467         sc->re_eewidth = 6;
468         re_read_eeprom(sc, (caddr_t)&re_did, 0, 1);
469         if (re_did != 0x8129)
470                 sc->re_eewidth = 8;
471 }
472
473 static int
474 re_gmii_readreg(device_t dev, int phy, int reg)
475 {
476         struct re_softc *sc = device_get_softc(dev);
477         u_int32_t rval;
478         int i;
479
480         if (phy != 1)
481                 return(0);
482
483         /* Let the rgephy driver read the GMEDIASTAT register */
484
485         if (reg == RE_GMEDIASTAT)
486                 return(CSR_READ_1(sc, RE_GMEDIASTAT));
487
488         CSR_WRITE_4(sc, RE_PHYAR, reg << 16);
489         DELAY(1000);
490
491         for (i = 0; i < RE_TIMEOUT; i++) {
492                 rval = CSR_READ_4(sc, RE_PHYAR);
493                 if (rval & RE_PHYAR_BUSY)
494                         break;
495                 DELAY(100);
496         }
497
498         if (i == RE_TIMEOUT) {
499                 device_printf(dev, "PHY read failed\n");
500                 return(0);
501         }
502
503         return(rval & RE_PHYAR_PHYDATA);
504 }
505
506 static int
507 re_gmii_writereg(device_t dev, int phy, int reg, int data)
508 {
509         struct re_softc *sc = device_get_softc(dev);
510         uint32_t rval;
511         int i;
512
513         CSR_WRITE_4(sc, RE_PHYAR,
514                     (reg << 16) | (data & RE_PHYAR_PHYDATA) | RE_PHYAR_BUSY);
515         DELAY(1000);
516
517         for (i = 0; i < RE_TIMEOUT; i++) {
518                 rval = CSR_READ_4(sc, RE_PHYAR);
519                 if ((rval & RE_PHYAR_BUSY) == 0)
520                         break;
521                 DELAY(100);
522         }
523
524         if (i == RE_TIMEOUT)
525                 device_printf(dev, "PHY write failed\n");
526
527         return(0);
528 }
529
530 static int
531 re_miibus_readreg(device_t dev, int phy, int reg)
532 {
533         struct re_softc *sc = device_get_softc(dev);
534         uint16_t rval = 0;
535         uint16_t re8139_reg = 0;
536
537         if (!RE_IS_8139CP(sc)) {
538                 rval = re_gmii_readreg(dev, phy, reg);
539                 return(rval);
540         }
541
542         /* Pretend the internal PHY is only at address 0 */
543         if (phy)
544                 return(0);
545
546         switch(reg) {
547         case MII_BMCR:
548                 re8139_reg = RE_BMCR;
549                 break;
550         case MII_BMSR:
551                 re8139_reg = RE_BMSR;
552                 break;
553         case MII_ANAR:
554                 re8139_reg = RE_ANAR;
555                 break;
556         case MII_ANER:
557                 re8139_reg = RE_ANER;
558                 break;
559         case MII_ANLPAR:
560                 re8139_reg = RE_LPAR;
561                 break;
562         case MII_PHYIDR1:
563         case MII_PHYIDR2:
564                 return(0);
565         /*
566          * Allow the rlphy driver to read the media status
567          * register. If we have a link partner which does not
568          * support NWAY, this is the register which will tell
569          * us the results of parallel detection.
570          */
571         case RE_MEDIASTAT:
572                 return(CSR_READ_1(sc, RE_MEDIASTAT));
573         default:
574                 device_printf(dev, "bad phy register\n");
575                 return(0);
576         }
577         rval = CSR_READ_2(sc, re8139_reg);
578         if (re8139_reg == RE_BMCR) {
579                 /* 8139C+ has different bit layout. */
580                 rval &= ~(BMCR_LOOP | BMCR_ISO);
581         }
582         return(rval);
583 }
584
585 static int
586 re_miibus_writereg(device_t dev, int phy, int reg, int data)
587 {
588         struct re_softc *sc= device_get_softc(dev);
589         u_int16_t re8139_reg = 0;
590
591         if (!RE_IS_8139CP(sc))
592                 return(re_gmii_writereg(dev, phy, reg, data));
593
594         /* Pretend the internal PHY is only at address 0 */
595         if (phy)
596                 return(0);
597
598         switch(reg) {
599         case MII_BMCR:
600                 re8139_reg = RE_BMCR;
601                 /* 8139C+ has different bit layout. */
602                 data &= ~(BMCR_LOOP | BMCR_ISO);
603                 break;
604         case MII_BMSR:
605                 re8139_reg = RE_BMSR;
606                 break;
607         case MII_ANAR:
608                 re8139_reg = RE_ANAR;
609                 break;
610         case MII_ANER:
611                 re8139_reg = RE_ANER;
612                 break;
613         case MII_ANLPAR:
614                 re8139_reg = RE_LPAR;
615                 break;
616         case MII_PHYIDR1:
617         case MII_PHYIDR2:
618                 return(0);
619         default:
620                 device_printf(dev, "bad phy register\n");
621                 return(0);
622         }
623         CSR_WRITE_2(sc, re8139_reg, data);
624         return(0);
625 }
626
627 static void
628 re_miibus_statchg(device_t dev)
629 {
630 }
631
632 /*
633  * Program the 64-bit multicast hash filter.
634  */
635 static void
636 re_setmulti(struct re_softc *sc)
637 {
638         struct ifnet *ifp = &sc->arpcom.ac_if;
639         int h = 0;
640         uint32_t hashes[2] = { 0, 0 };
641         struct ifmultiaddr *ifma;
642         uint32_t rxfilt;
643         int mcnt = 0;
644
645         rxfilt = CSR_READ_4(sc, RE_RXCFG);
646
647         if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) {
648                 rxfilt |= RE_RXCFG_RX_MULTI;
649                 CSR_WRITE_4(sc, RE_RXCFG, rxfilt);
650                 CSR_WRITE_4(sc, RE_MAR0, 0xFFFFFFFF);
651                 CSR_WRITE_4(sc, RE_MAR4, 0xFFFFFFFF);
652                 return;
653         }
654
655         /* first, zot all the existing hash bits */
656         CSR_WRITE_4(sc, RE_MAR0, 0);
657         CSR_WRITE_4(sc, RE_MAR4, 0);
658
659         /* now program new ones */
660         LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
661                 if (ifma->ifma_addr->sa_family != AF_LINK)
662                         continue;
663                 h = ether_crc32_be(LLADDR((struct sockaddr_dl *)
664                     ifma->ifma_addr), ETHER_ADDR_LEN) >> 26;
665                 if (h < 32)
666                         hashes[0] |= (1 << h);
667                 else
668                         hashes[1] |= (1 << (h - 32));
669                 mcnt++;
670         }
671
672         if (mcnt)
673                 rxfilt |= RE_RXCFG_RX_MULTI;
674         else
675                 rxfilt &= ~RE_RXCFG_RX_MULTI;
676
677         CSR_WRITE_4(sc, RE_RXCFG, rxfilt);
678
679         /*
680          * For some unfathomable reason, RealTek decided to reverse
681          * the order of the multicast hash registers in the PCI Express
682          * parts. This means we have to write the hash pattern in reverse
683          * order for those devices.
684          */
685         if (sc->re_caps & RE_C_PCIE) {
686                 CSR_WRITE_4(sc, RE_MAR0, bswap32(hashes[0]));
687                 CSR_WRITE_4(sc, RE_MAR4, bswap32(hashes[1]));
688         } else {
689                 CSR_WRITE_4(sc, RE_MAR0, hashes[0]);
690                 CSR_WRITE_4(sc, RE_MAR4, hashes[1]);
691         }
692 }
693
694 static void
695 re_reset(struct re_softc *sc)
696 {
697         int i;
698
699         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_RESET);
700
701         for (i = 0; i < RE_TIMEOUT; i++) {
702                 DELAY(10);
703                 if ((CSR_READ_1(sc, RE_COMMAND) & RE_CMD_RESET) == 0)
704                         break;
705         }
706         if (i == RE_TIMEOUT)
707                 if_printf(&sc->arpcom.ac_if, "reset never completed!\n");
708
709         CSR_WRITE_1(sc, 0x82, 1);
710 }
711
712 #ifdef RE_DIAG
713 /*
714  * The following routine is designed to test for a defect on some
715  * 32-bit 8169 cards. Some of these NICs have the REQ64# and ACK64#
716  * lines connected to the bus, however for a 32-bit only card, they
717  * should be pulled high. The result of this defect is that the
718  * NIC will not work right if you plug it into a 64-bit slot: DMA
719  * operations will be done with 64-bit transfers, which will fail
720  * because the 64-bit data lines aren't connected.
721  *
722  * There's no way to work around this (short of talking a soldering
723  * iron to the board), however we can detect it. The method we use
724  * here is to put the NIC into digital loopback mode, set the receiver
725  * to promiscuous mode, and then try to send a frame. We then compare
726  * the frame data we sent to what was received. If the data matches,
727  * then the NIC is working correctly, otherwise we know the user has
728  * a defective NIC which has been mistakenly plugged into a 64-bit PCI
729  * slot. In the latter case, there's no way the NIC can work correctly,
730  * so we print out a message on the console and abort the device attach.
731  */
732
733 static int
734 re_diag(struct re_softc *sc)
735 {
736         struct ifnet *ifp = &sc->arpcom.ac_if;
737         struct mbuf *m0;
738         struct ether_header *eh;
739         struct re_desc *cur_rx;
740         uint16_t status;
741         uint32_t rxstat;
742         int total_len, i, error = 0, phyaddr;
743         uint8_t dst[ETHER_ADDR_LEN] = { 0x00, 'h', 'e', 'l', 'l', 'o' };
744         uint8_t src[ETHER_ADDR_LEN] = { 0x00, 'w', 'o', 'r', 'l', 'd' };
745
746         /* Allocate a single mbuf */
747
748         MGETHDR(m0, MB_DONTWAIT, MT_DATA);
749         if (m0 == NULL)
750                 return(ENOBUFS);
751
752         /*
753          * Initialize the NIC in test mode. This sets the chip up
754          * so that it can send and receive frames, but performs the
755          * following special functions:
756          * - Puts receiver in promiscuous mode
757          * - Enables digital loopback mode
758          * - Leaves interrupts turned off
759          */
760
761         ifp->if_flags |= IFF_PROMISC;
762         sc->re_testmode = 1;
763         re_reset(sc);
764         re_init(sc);
765         sc->re_link = 1;
766         if (!RE_IS_8139CP(sc))
767                 phyaddr = 1;
768         else
769                 phyaddr = 0;
770
771         re_miibus_writereg(sc->re_dev, phyaddr, MII_BMCR, BMCR_RESET);
772         for (i = 0; i < RE_TIMEOUT; i++) {
773                 status = re_miibus_readreg(sc->re_dev, phyaddr, MII_BMCR);
774                 if (!(status & BMCR_RESET))
775                         break;
776         }
777
778         re_miibus_writereg(sc->re_dev, phyaddr, MII_BMCR, BMCR_LOOP);
779         CSR_WRITE_2(sc, RE_ISR, RE_INTRS_DIAG);
780
781         DELAY(100000);
782
783         /* Put some data in the mbuf */
784
785         eh = mtod(m0, struct ether_header *);
786         bcopy (dst, eh->ether_dhost, ETHER_ADDR_LEN);
787         bcopy (src, eh->ether_shost, ETHER_ADDR_LEN);
788         eh->ether_type = htons(ETHERTYPE_IP);
789         m0->m_pkthdr.len = m0->m_len = ETHER_MIN_LEN - ETHER_CRC_LEN;
790
791         /*
792          * Queue the packet, start transmission.
793          * Note: ifq_handoff() ultimately calls re_start() for us.
794          */
795
796         CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
797         error = ifq_handoff(ifp, m0, NULL);
798         if (error) {
799                 m0 = NULL;
800                 goto done;
801         }
802         m0 = NULL;
803
804         /* Wait for it to propagate through the chip */
805
806         DELAY(100000);
807         for (i = 0; i < RE_TIMEOUT; i++) {
808                 status = CSR_READ_2(sc, RE_ISR);
809                 CSR_WRITE_2(sc, RE_ISR, status);
810                 if ((status & (RE_ISR_TIMEOUT_EXPIRED|RE_ISR_RX_OK)) ==
811                     (RE_ISR_TIMEOUT_EXPIRED|RE_ISR_RX_OK))
812                         break;
813                 DELAY(10);
814         }
815
816         if (i == RE_TIMEOUT) {
817                 if_printf(ifp, "diagnostic failed to receive packet "
818                           "in loopback mode\n");
819                 error = EIO;
820                 goto done;
821         }
822
823         /*
824          * The packet should have been dumped into the first
825          * entry in the RX DMA ring. Grab it from there.
826          */
827
828         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
829                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
830         bus_dmamap_sync(sc->re_ldata.re_mtag, sc->re_ldata.re_rx_dmamap[0],
831                         BUS_DMASYNC_POSTWRITE);
832         bus_dmamap_unload(sc->re_ldata.re_mtag, sc->re_ldata.re_rx_dmamap[0]);
833
834         m0 = sc->re_ldata.re_rx_mbuf[0];
835         sc->re_ldata.re_rx_mbuf[0] = NULL;
836         eh = mtod(m0, struct ether_header *);
837
838         cur_rx = &sc->re_ldata.re_rx_list[0];
839         total_len = RE_RXBYTES(cur_rx);
840         rxstat = le32toh(cur_rx->re_cmdstat);
841
842         if (total_len != ETHER_MIN_LEN) {
843                 if_printf(ifp, "diagnostic failed, received short packet\n");
844                 error = EIO;
845                 goto done;
846         }
847
848         /* Test that the received packet data matches what we sent. */
849
850         if (bcmp(eh->ether_dhost, dst, ETHER_ADDR_LEN) ||
851             bcmp(eh->ether_shost, &src, ETHER_ADDR_LEN) ||
852             be16toh(eh->ether_type) != ETHERTYPE_IP) {
853                 if_printf(ifp, "WARNING, DMA FAILURE!\n");
854                 if_printf(ifp, "expected TX data: %6D/%6D/0x%x\n",
855                     dst, ":", src, ":", ETHERTYPE_IP);
856                 if_printf(ifp, "received RX data: %6D/%6D/0x%x\n",
857                     eh->ether_dhost, ":",  eh->ether_shost, ":",
858                     ntohs(eh->ether_type));
859                 if_printf(ifp, "You may have a defective 32-bit NIC plugged "
860                     "into a 64-bit PCI slot.\n");
861                 if_printf(ifp, "Please re-install the NIC in a 32-bit slot "
862                     "for proper operation.\n");
863                 if_printf(ifp, "Read the re(4) man page for more details.\n");
864                 error = EIO;
865         }
866
867 done:
868         /* Turn interface off, release resources */
869
870         sc->re_testmode = 0;
871         sc->re_link = 0;
872         ifp->if_flags &= ~IFF_PROMISC;
873         re_stop(sc);
874         if (m0 != NULL)
875                 m_freem(m0);
876
877         return (error);
878 }
879 #endif  /* RE_DIAG */
880
881 /*
882  * Probe for a RealTek 8139C+/8169/8110 chip. Check the PCI vendor and device
883  * IDs against our list and return a device name if we find a match.
884  */
885 static int
886 re_probe(device_t dev)
887 {
888         const struct re_type *t;
889         const struct re_hwrev *hw_rev;
890         struct re_softc *sc;
891         int rid;
892         uint32_t hwrev, macmode, txcfg;
893         uint16_t vendor, product;
894
895         vendor = pci_get_vendor(dev);
896         product = pci_get_device(dev);
897
898         /*
899          * Only attach to rev.3 of the Linksys EG1032 adapter.
900          * Rev.2 is supported by sk(4).
901          */
902         if (vendor == PCI_VENDOR_LINKSYS &&
903             product == PCI_PRODUCT_LINKSYS_EG1032 &&
904             pci_get_subdevice(dev) != PCI_SUBDEVICE_LINKSYS_EG1032_REV3)
905                 return ENXIO;
906
907         for (t = re_devs; t->re_name != NULL; t++) {
908                 if (product == t->re_did && vendor == t->re_vid)
909                         break;
910         }
911
912         /*
913          * Check if we found a RealTek device.
914          */
915         if (t->re_name == NULL)
916                 return ENXIO;
917
918         /*
919          * Temporarily map the I/O space so we can read the chip ID register.
920          */
921         sc = kmalloc(sizeof(*sc), M_TEMP, M_WAITOK | M_ZERO);
922         rid = RE_PCI_LOIO;
923         sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
924                                             RF_ACTIVE);
925         if (sc->re_res == NULL) {
926                 device_printf(dev, "couldn't map ports/memory\n");
927                 kfree(sc, M_TEMP);
928                 return ENXIO;
929         }
930
931         sc->re_btag = rman_get_bustag(sc->re_res);
932         sc->re_bhandle = rman_get_bushandle(sc->re_res);
933
934         txcfg = CSR_READ_4(sc, RE_TXCFG);
935         hwrev = txcfg & RE_TXCFG_HWREV;
936         macmode = txcfg & RE_TXCFG_MACMODE;
937         bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO, sc->re_res);
938         kfree(sc, M_TEMP);
939
940         /*
941          * and continue matching for the specific chip...
942          */
943         for (hw_rev = re_hwrevs; hw_rev->re_hwrev != RE_HWREV_NULL; hw_rev++) {
944                 if (hw_rev->re_hwrev == hwrev) {
945                         sc = device_get_softc(dev);
946
947                         sc->re_hwrev = hw_rev->re_hwrev;
948                         sc->re_macver = hw_rev->re_macver;
949                         sc->re_caps = hw_rev->re_caps;
950
951                         if (sc->re_caps & RE_C_JUMBO) {
952                                 sc->re_swcsum_lim = RE_JUMBO_MTU;
953                                 sc->re_maxmtu = RE_JUMBO_MTU;
954                         } else {
955                                 sc->re_swcsum_lim = ETHERMTU;
956                                 sc->re_maxmtu = ETHERMTU;
957                         }
958                         sc->re_swcsum_lim += ETHER_HDR_LEN;
959
960                         /*
961                          * Apply chip property fixup
962                          */
963                         switch (sc->re_hwrev) {
964                         case RE_HWREV_8169:
965                                 sc->re_swcsum_lim = RE_SWCSUM_LIM_8169;
966                                 break;
967                         case RE_HWREV_8101E1:
968                         case RE_HWREV_8101E2:
969                                 if (macmode == 0)
970                                         sc->re_macver = RE_MACVER_11;
971                                 else if (macmode == 0x200000)
972                                         sc->re_macver = RE_MACVER_12;
973                                 break;
974                         case RE_HWREV_8102E:
975                         case RE_HWREV_8102EL:
976                                 if (macmode == 0)
977                                         sc->re_macver = RE_MACVER_13;
978                                 else if (macmode == 0x100000)
979                                         sc->re_macver = RE_MACVER_14;
980                                 break;
981                         case RE_HWREV_8168B2:
982                         case RE_HWREV_8168B3:
983                                 if (macmode == 0)
984                                         sc->re_macver = RE_MACVER_22;
985                                 break;
986                         case RE_HWREV_8168C:
987                                 if (macmode == 0)
988                                         sc->re_macver = RE_MACVER_24;
989                                 else if (macmode == 0x200000)
990                                         sc->re_macver = RE_MACVER_25;
991                                 else if (macmode == 0x300000)
992                                         sc->re_macver = RE_MACVER_27;
993                                 break;
994                         case RE_HWREV_8168CP:
995                                 if (macmode == 0)
996                                         sc->re_macver = RE_MACVER_26;
997                                 else if (macmode == 0x100000)
998                                         sc->re_macver = RE_MACVER_28;
999                                 break;
1000                         }
1001                         device_set_desc(dev, t->re_name);
1002                         return 0;
1003                 }
1004         }
1005         device_printf(dev, "unknown hwrev 0x%08x, macmode 0x%08x\n",
1006                       hwrev, macmode);
1007         return ENXIO;
1008 }
1009
1010 static void
1011 re_dma_map_desc(void *xarg, bus_dma_segment_t *segs, int nsegs,
1012                 bus_size_t mapsize, int error)
1013 {
1014         struct re_dmaload_arg *arg = xarg;
1015         int i;
1016
1017         if (error)
1018                 return;
1019
1020         if (nsegs > arg->re_nsegs) {
1021                 arg->re_nsegs = 0;
1022                 return;
1023         }
1024
1025         arg->re_nsegs = nsegs;
1026         for (i = 0; i < nsegs; ++i)
1027                 arg->re_segs[i] = segs[i];
1028 }
1029
1030 /*
1031  * Map a single buffer address.
1032  */
1033
1034 static void
1035 re_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1036 {
1037         uint32_t *addr;
1038
1039         if (error)
1040                 return;
1041
1042         KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
1043         addr = arg;
1044         *addr = segs->ds_addr;
1045 }
1046
1047 static int
1048 re_allocmem(device_t dev)
1049 {
1050         struct re_softc *sc = device_get_softc(dev);
1051         int error, i;
1052
1053         /*
1054          * Allocate list data
1055          */
1056         sc->re_ldata.re_tx_mbuf =
1057         kmalloc(sc->re_tx_desc_cnt * sizeof(struct mbuf *),
1058                 M_DEVBUF, M_ZERO | M_WAITOK);
1059
1060         sc->re_ldata.re_rx_mbuf =
1061         kmalloc(sc->re_rx_desc_cnt * sizeof(struct mbuf *),
1062                 M_DEVBUF, M_ZERO | M_WAITOK);
1063
1064         sc->re_ldata.re_rx_paddr =
1065         kmalloc(sc->re_rx_desc_cnt * sizeof(bus_addr_t),
1066                 M_DEVBUF, M_ZERO | M_WAITOK);
1067
1068         sc->re_ldata.re_tx_dmamap =
1069         kmalloc(sc->re_tx_desc_cnt * sizeof(bus_dmamap_t),
1070                 M_DEVBUF, M_ZERO | M_WAITOK);
1071
1072         sc->re_ldata.re_rx_dmamap =
1073         kmalloc(sc->re_rx_desc_cnt * sizeof(bus_dmamap_t),
1074                 M_DEVBUF, M_ZERO | M_WAITOK);
1075
1076         /*
1077          * Allocate the parent bus DMA tag appropriate for PCI.
1078          */
1079         error = bus_dma_tag_create(NULL,        /* parent */
1080                         1, 0,                   /* alignment, boundary */
1081                         BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1082                         BUS_SPACE_MAXADDR,      /* highaddr */
1083                         NULL, NULL,             /* filter, filterarg */
1084                         MAXBSIZE, RE_MAXSEGS,   /* maxsize, nsegments */
1085                         BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
1086                         BUS_DMA_ALLOCNOW,       /* flags */
1087                         &sc->re_parent_tag);
1088         if (error) {
1089                 device_printf(dev, "could not allocate parent dma tag\n");
1090                 return error;
1091         }
1092
1093         /* Allocate tag for TX descriptor list. */
1094         error = bus_dma_tag_create(sc->re_parent_tag,
1095                         RE_RING_ALIGN, 0,
1096                         BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
1097                         NULL, NULL,
1098                         RE_TX_LIST_SZ(sc), 1, RE_TX_LIST_SZ(sc),
1099                         BUS_DMA_ALLOCNOW,
1100                         &sc->re_ldata.re_tx_list_tag);
1101         if (error) {
1102                 device_printf(dev, "could not allocate TX ring dma tag\n");
1103                 return(error);
1104         }
1105
1106         /* Allocate DMA'able memory for the TX ring */
1107         error = bus_dmamem_alloc(sc->re_ldata.re_tx_list_tag,
1108                         (void **)&sc->re_ldata.re_tx_list,
1109                         BUS_DMA_WAITOK | BUS_DMA_ZERO,
1110                         &sc->re_ldata.re_tx_list_map);
1111         if (error) {
1112                 device_printf(dev, "could not allocate TX ring\n");
1113                 bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
1114                 sc->re_ldata.re_tx_list_tag = NULL;
1115                 return(error);
1116         }
1117
1118         /* Load the map for the TX ring. */
1119         error = bus_dmamap_load(sc->re_ldata.re_tx_list_tag,
1120                         sc->re_ldata.re_tx_list_map,
1121                         sc->re_ldata.re_tx_list, RE_TX_LIST_SZ(sc),
1122                         re_dma_map_addr, &sc->re_ldata.re_tx_list_addr,
1123                         BUS_DMA_NOWAIT);
1124         if (error) {
1125                 device_printf(dev, "could not get address of TX ring\n");
1126                 bus_dmamem_free(sc->re_ldata.re_tx_list_tag,
1127                                 sc->re_ldata.re_tx_list,
1128                                 sc->re_ldata.re_tx_list_map);
1129                 bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
1130                 sc->re_ldata.re_tx_list_tag = NULL;
1131                 return(error);
1132         }
1133
1134         /* Allocate tag for RX descriptor list. */
1135         error = bus_dma_tag_create(sc->re_parent_tag,
1136                         RE_RING_ALIGN, 0,
1137                         BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
1138                         NULL, NULL,
1139                         RE_RX_LIST_SZ(sc), 1, RE_RX_LIST_SZ(sc),
1140                         BUS_DMA_ALLOCNOW,
1141                         &sc->re_ldata.re_rx_list_tag);
1142         if (error) {
1143                 device_printf(dev, "could not allocate RX ring dma tag\n");
1144                 return(error);
1145         }
1146
1147         /* Allocate DMA'able memory for the RX ring */
1148         error = bus_dmamem_alloc(sc->re_ldata.re_rx_list_tag,
1149                         (void **)&sc->re_ldata.re_rx_list,
1150                         BUS_DMA_WAITOK | BUS_DMA_ZERO,
1151                         &sc->re_ldata.re_rx_list_map);
1152         if (error) {
1153                 device_printf(dev, "could not allocate RX ring\n");
1154                 bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1155                 sc->re_ldata.re_rx_list_tag = NULL;
1156                 return(error);
1157         }
1158
1159         /* Load the map for the RX ring. */
1160         error = bus_dmamap_load(sc->re_ldata.re_rx_list_tag,
1161                         sc->re_ldata.re_rx_list_map,
1162                         sc->re_ldata.re_rx_list, RE_RX_LIST_SZ(sc),
1163                         re_dma_map_addr, &sc->re_ldata.re_rx_list_addr,
1164                         BUS_DMA_NOWAIT);
1165         if (error) {
1166                 device_printf(dev, "could not get address of RX ring\n");
1167                 bus_dmamem_free(sc->re_ldata.re_rx_list_tag,
1168                                 sc->re_ldata.re_rx_list,
1169                                 sc->re_ldata.re_rx_list_map);
1170                 bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1171                 sc->re_ldata.re_rx_list_tag = NULL;
1172                 return(error);
1173         }
1174
1175         /* Allocate map for RX/TX mbufs. */
1176         error = bus_dma_tag_create(sc->re_parent_tag,
1177                         ETHER_ALIGN, 0,
1178                         BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
1179                         NULL, NULL,
1180                         RE_JUMBO_FRAMELEN, RE_MAXSEGS, MCLBYTES,
1181                         BUS_DMA_ALLOCNOW,
1182                         &sc->re_ldata.re_mtag);
1183         if (error) {
1184                 device_printf(dev, "could not allocate buf dma tag\n");
1185                 return(error);
1186         }
1187
1188         /* Create spare DMA map for RX */
1189         error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
1190                         &sc->re_ldata.re_rx_spare);
1191         if (error) {
1192                 device_printf(dev, "can't create spare DMA map for RX\n");
1193                 bus_dma_tag_destroy(sc->re_ldata.re_mtag);
1194                 sc->re_ldata.re_mtag = NULL;
1195                 return error;
1196         }
1197
1198         /* Create DMA maps for TX buffers */
1199         for (i = 0; i < sc->re_tx_desc_cnt; i++) {
1200                 error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
1201                                 &sc->re_ldata.re_tx_dmamap[i]);
1202                 if (error) {
1203                         device_printf(dev, "can't create DMA map for TX buf\n");
1204                         re_freebufmem(sc, i, 0);
1205                         return(error);
1206                 }
1207         }
1208
1209         /* Create DMA maps for RX buffers */
1210         for (i = 0; i < sc->re_rx_desc_cnt; i++) {
1211                 error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
1212                                 &sc->re_ldata.re_rx_dmamap[i]);
1213                 if (error) {
1214                         device_printf(dev, "can't create DMA map for RX buf\n");
1215                         re_freebufmem(sc, sc->re_tx_desc_cnt, i);
1216                         return(error);
1217                 }
1218         }
1219         return(0);
1220 }
1221
1222 static void
1223 re_freebufmem(struct re_softc *sc, int tx_cnt, int rx_cnt)
1224 {
1225         int i;
1226
1227         /* Destroy all the RX and TX buffer maps */
1228         if (sc->re_ldata.re_mtag) {
1229                 for (i = 0; i < tx_cnt; i++) {
1230                         bus_dmamap_destroy(sc->re_ldata.re_mtag,
1231                                            sc->re_ldata.re_tx_dmamap[i]);
1232                 }
1233                 for (i = 0; i < rx_cnt; i++) {
1234                         bus_dmamap_destroy(sc->re_ldata.re_mtag,
1235                                            sc->re_ldata.re_rx_dmamap[i]);
1236                 }
1237                 bus_dmamap_destroy(sc->re_ldata.re_mtag,
1238                                    sc->re_ldata.re_rx_spare);
1239                 bus_dma_tag_destroy(sc->re_ldata.re_mtag);
1240                 sc->re_ldata.re_mtag = NULL;
1241         }
1242 }
1243
1244 static void
1245 re_freemem(device_t dev)
1246 {
1247         struct re_softc *sc = device_get_softc(dev);
1248
1249         /* Unload and free the RX DMA ring memory and map */
1250         if (sc->re_ldata.re_rx_list_tag) {
1251                 bus_dmamap_unload(sc->re_ldata.re_rx_list_tag,
1252                                   sc->re_ldata.re_rx_list_map);
1253                 bus_dmamem_free(sc->re_ldata.re_rx_list_tag,
1254                                 sc->re_ldata.re_rx_list,
1255                                 sc->re_ldata.re_rx_list_map);
1256                 bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1257         }
1258
1259         /* Unload and free the TX DMA ring memory and map */
1260         if (sc->re_ldata.re_tx_list_tag) {
1261                 bus_dmamap_unload(sc->re_ldata.re_tx_list_tag,
1262                                   sc->re_ldata.re_tx_list_map);
1263                 bus_dmamem_free(sc->re_ldata.re_tx_list_tag,
1264                                 sc->re_ldata.re_tx_list,
1265                                 sc->re_ldata.re_tx_list_map);
1266                 bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
1267         }
1268
1269         /* Free RX/TX buf DMA stuffs */
1270         re_freebufmem(sc, sc->re_tx_desc_cnt, sc->re_rx_desc_cnt);
1271
1272         /* Unload and free the stats buffer and map */
1273         if (sc->re_ldata.re_stag) {
1274                 bus_dmamap_unload(sc->re_ldata.re_stag,
1275                                   sc->re_ldata.re_rx_list_map);
1276                 bus_dmamem_free(sc->re_ldata.re_stag,
1277                                 sc->re_ldata.re_stats,
1278                                 sc->re_ldata.re_smap);
1279                 bus_dma_tag_destroy(sc->re_ldata.re_stag);
1280         }
1281
1282         if (sc->re_parent_tag)
1283                 bus_dma_tag_destroy(sc->re_parent_tag);
1284
1285         if (sc->re_ldata.re_tx_mbuf != NULL)
1286                 kfree(sc->re_ldata.re_tx_mbuf, M_DEVBUF);
1287         if (sc->re_ldata.re_rx_mbuf != NULL)
1288                 kfree(sc->re_ldata.re_rx_mbuf, M_DEVBUF);
1289         if (sc->re_ldata.re_rx_paddr != NULL)
1290                 kfree(sc->re_ldata.re_rx_paddr, M_DEVBUF);
1291         if (sc->re_ldata.re_tx_dmamap != NULL)
1292                 kfree(sc->re_ldata.re_tx_dmamap, M_DEVBUF);
1293         if (sc->re_ldata.re_rx_dmamap != NULL)
1294                 kfree(sc->re_ldata.re_rx_dmamap, M_DEVBUF);
1295 }
1296
1297 /*
1298  * Attach the interface. Allocate softc structures, do ifmedia
1299  * setup and ethernet/BPF attach.
1300  */
1301 static int
1302 re_attach(device_t dev)
1303 {
1304         struct re_softc *sc = device_get_softc(dev);
1305         struct ifnet *ifp;
1306         uint8_t eaddr[ETHER_ADDR_LEN];
1307         int error = 0, rid, qlen;
1308         uint8_t expr_ptr;
1309
1310         callout_init(&sc->re_timer);
1311 #ifdef RE_DIAG
1312         sc->re_dev = dev;
1313 #endif
1314
1315         if (RE_IS_8139CP(sc)) {
1316                 sc->re_rx_desc_cnt = RE_RX_DESC_CNT_8139CP;
1317                 sc->re_tx_desc_cnt = RE_TX_DESC_CNT_8139CP;
1318         } else {
1319                 sc->re_rx_desc_cnt = re_rx_desc_count;
1320                 if (sc->re_rx_desc_cnt > RE_RX_DESC_CNT_MAX)
1321                         sc->re_rx_desc_cnt = RE_RX_DESC_CNT_MAX;
1322
1323                 sc->re_tx_desc_cnt = re_tx_desc_count;
1324                 if (sc->re_tx_desc_cnt > RE_TX_DESC_CNT_MAX)
1325                         sc->re_tx_desc_cnt = RE_TX_DESC_CNT_MAX;
1326         }
1327
1328         qlen = RE_IFQ_MAXLEN;
1329         if (sc->re_tx_desc_cnt > qlen)
1330                 qlen = sc->re_tx_desc_cnt;
1331
1332         sc->re_tx_time = 5;             /* 125us */
1333         sc->re_rx_time = 2;             /* 50us */
1334         sc->re_sim_time = 125;          /* 125us */
1335         sc->re_imtype = RE_IMTYPE_SIM;  /* simulated interrupt moderation */
1336         re_config_imtype(sc, sc->re_imtype);
1337
1338         sysctl_ctx_init(&sc->re_sysctl_ctx);
1339         sc->re_sysctl_tree = SYSCTL_ADD_NODE(&sc->re_sysctl_ctx,
1340                                              SYSCTL_STATIC_CHILDREN(_hw),
1341                                              OID_AUTO,
1342                                              device_get_nameunit(dev),
1343                                              CTLFLAG_RD, 0, "");
1344         if (sc->re_sysctl_tree == NULL) {
1345                 device_printf(dev, "can't add sysctl node\n");
1346                 error = ENXIO;
1347                 goto fail;
1348         }
1349         SYSCTL_ADD_INT(&sc->re_sysctl_ctx,
1350                        SYSCTL_CHILDREN(sc->re_sysctl_tree), OID_AUTO,
1351                        "rx_desc_count", CTLFLAG_RD, &sc->re_rx_desc_cnt,
1352                        0, "RX desc count");
1353         SYSCTL_ADD_INT(&sc->re_sysctl_ctx,
1354                        SYSCTL_CHILDREN(sc->re_sysctl_tree), OID_AUTO,
1355                        "tx_desc_count", CTLFLAG_RD, &sc->re_tx_desc_cnt,
1356                        0, "TX desc count");
1357         SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1358                         SYSCTL_CHILDREN(sc->re_sysctl_tree),
1359                         OID_AUTO, "sim_time",
1360                         CTLTYPE_INT | CTLFLAG_RW,
1361                         sc, 0, re_sysctl_simtime, "I",
1362                         "Simulated interrupt moderation time (usec).");
1363         SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1364                         SYSCTL_CHILDREN(sc->re_sysctl_tree),
1365                         OID_AUTO, "imtype",
1366                         CTLTYPE_INT | CTLFLAG_RW,
1367                         sc, 0, re_sysctl_imtype, "I",
1368                         "Interrupt moderation type -- "
1369                         "0:disable, 1:simulated, "
1370                         "2:hardware(if supported)");
1371         if (sc->re_caps & RE_C_HWIM) {
1372                 SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1373                                 SYSCTL_CHILDREN(sc->re_sysctl_tree),
1374                                 OID_AUTO, "hw_rxtime",
1375                                 CTLTYPE_INT | CTLFLAG_RW,
1376                                 sc, 0, re_sysctl_rxtime, "I",
1377                                 "Hardware interrupt moderation time "
1378                                 "(unit: 25usec).");
1379                 SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1380                                 SYSCTL_CHILDREN(sc->re_sysctl_tree),
1381                                 OID_AUTO, "hw_txtime",
1382                                 CTLTYPE_INT | CTLFLAG_RW,
1383                                 sc, 0, re_sysctl_txtime, "I",
1384                                 "Hardware interrupt moderation time "
1385                                 "(unit: 25usec).");
1386         }
1387
1388 #ifndef BURN_BRIDGES
1389         /*
1390          * Handle power management nonsense.
1391          */
1392
1393         if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
1394                 uint32_t membase, irq;
1395
1396                 /* Save important PCI config data. */
1397                 membase = pci_read_config(dev, RE_PCI_LOMEM, 4);
1398                 irq = pci_read_config(dev, PCIR_INTLINE, 4);
1399
1400                 /* Reset the power state. */
1401                 device_printf(dev, "chip is in D%d power mode "
1402                     "-- setting to D0\n", pci_get_powerstate(dev));
1403
1404                 pci_set_powerstate(dev, PCI_POWERSTATE_D0);
1405
1406                 /* Restore PCI config data. */
1407                 pci_write_config(dev, RE_PCI_LOMEM, membase, 4);
1408                 pci_write_config(dev, PCIR_INTLINE, irq, 4);
1409         }
1410 #endif
1411         /*
1412          * Map control/status registers.
1413          */
1414         pci_enable_busmaster(dev);
1415
1416         rid = RE_PCI_LOIO;
1417         sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
1418                                             RF_ACTIVE);
1419
1420         if (sc->re_res == NULL) {
1421                 device_printf(dev, "couldn't map ports\n");
1422                 error = ENXIO;
1423                 goto fail;
1424         }
1425
1426         sc->re_btag = rman_get_bustag(sc->re_res);
1427         sc->re_bhandle = rman_get_bushandle(sc->re_res);
1428
1429         /* Allocate interrupt */
1430         rid = 0;
1431         sc->re_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1432                                             RF_SHAREABLE | RF_ACTIVE);
1433
1434         if (sc->re_irq == NULL) {
1435                 device_printf(dev, "couldn't map interrupt\n");
1436                 error = ENXIO;
1437                 goto fail;
1438         }
1439
1440         /* Reset the adapter. */
1441         re_reset(sc);
1442
1443         expr_ptr = pci_get_pciecap_ptr(dev);
1444         if (expr_ptr != 0) {
1445                 uint16_t val;
1446
1447                 /*
1448                  * We will set TX DMA burst to "unlimited" in
1449                  * re_init(), so push "max read request size"
1450                  * to the limit.
1451                  */
1452                 val = pci_read_config(dev, expr_ptr + PCIER_DEVCTRL, 2);
1453                 if ((val & PCIEM_DEVCTL_MAX_READRQ_MASK) !=
1454                     PCIEM_DEVCTL_MAX_READRQ_4096) {
1455                         device_printf(dev, "adjust device control "
1456                                       "0x%04x ", val);
1457
1458                         val &= ~PCIEM_DEVCTL_MAX_READRQ_MASK;
1459                         val |= PCIEM_DEVCTL_MAX_READRQ_4096;
1460                         pci_write_config(dev, expr_ptr + PCIER_DEVCTRL,
1461                                          val, 2);
1462
1463                         kprintf("-> 0x%04x\n", val);
1464                 }
1465                 sc->re_caps |= RE_C_PCIE;
1466
1467                 /* Reduce the simulated interrupt moderation timer a bit */
1468                 sc->re_sim_time = 75; /* 75us */
1469         }
1470
1471         if (RE_IS_8139CP(sc)) {
1472                 sc->re_bus_speed = 33; /* XXX */
1473         } else if (sc->re_caps & RE_C_PCIE) {
1474                 sc->re_bus_speed = 125;
1475         } else {
1476                 uint8_t cfg2;
1477
1478                 cfg2 = CSR_READ_1(sc, RE_CFG2);
1479                 switch (cfg2 & RE_CFG2_PCICLK_MASK) {
1480                 case RE_CFG2_PCICLK_33MHZ:
1481                         sc->re_bus_speed = 33;
1482                         break;
1483                 case RE_CFG2_PCICLK_66MHZ:
1484                         sc->re_bus_speed = 66;
1485                         break;
1486                 default:
1487                         device_printf(dev, "unknown bus speed, assume 33MHz\n");
1488                         sc->re_bus_speed = 33;
1489                         break;
1490                 }
1491                 if (cfg2 & RE_CFG2_PCI64)
1492                         sc->re_caps |= RE_C_PCI64;
1493         }
1494         device_printf(dev, "Hardware rev. 0x%08x; MAC ver. 0x%02x; "
1495                       "PCI%s %dMHz\n",
1496                       sc->re_hwrev, sc->re_macver,
1497                       (sc->re_caps & RE_C_PCIE) ?
1498                       "-E" : ((sc->re_caps & RE_C_PCI64) ? "64" : "32"),
1499                       sc->re_bus_speed);
1500
1501         /*
1502          * NOTE:
1503          * DO NOT try to adjust config1 and config5 which was spotted in
1504          * Realtek's Linux drivers.  It will _permanently_ damage certain
1505          * cards EEPROM, e.g. one of my 8168B (0x38000000) card ...
1506          */
1507
1508         re_get_eaddr(sc, eaddr);
1509
1510         if (!RE_IS_8139CP(sc)) {
1511                 /* Set RX length mask */
1512                 sc->re_rxlenmask = RE_RDESC_STAT_GFRAGLEN;
1513                 sc->re_txstart = RE_GTXSTART;
1514         } else {
1515                 /* Set RX length mask */
1516                 sc->re_rxlenmask = RE_RDESC_STAT_FRAGLEN;
1517                 sc->re_txstart = RE_TXSTART;
1518         }
1519
1520         /* Allocate DMA stuffs */
1521         error = re_allocmem(dev);
1522         if (error)
1523                 goto fail;
1524
1525         /*
1526          * Apply some magic PCI settings from Realtek ...
1527          */
1528         if (sc->re_caps & RE_C_8169)
1529                 pci_write_config(dev, PCIR_CACHELNSZ, 0x8, 1);
1530         pci_write_config(dev, PCIR_LATTIMER, 0x40, 1);
1531
1532         if (sc->re_caps & RE_C_MAC2) {
1533                 /*
1534                  * Following part is extracted from Realtek BSD driver v176.
1535                  * However, this does _not_ make much/any sense:
1536                  * 8168C's PCI Express device control is located at 0x78,
1537                  * so the reading from 0x79 (higher part of 0x78) and setting
1538                  * the 4~6bits intend to enlarge the "max read request size"
1539                  * (we have done it).  The content of the rest part of this
1540                  * register is not meaningful to other PCI registers, so
1541                  * writing the value to 0x54 could be completely wrong.
1542                  * 0x80 is the lower part of PCI Express device status, non-
1543                  * reserved bits are RW1C, writing 0 to them will not have
1544                  * any effect at all.
1545                  */
1546 #ifdef foo
1547                 uint8_t val;
1548
1549                 val = pci_read_config(dev, 0x79, 1);
1550                 val = (val & ~0x70) | 0x50;
1551                 pci_write_config(dev, 0x54, val, 1);
1552                 pci_write_config(dev, 0x80, 0, 1);
1553 #endif
1554         }
1555
1556         /*
1557          * Apply some PHY fixup from Realtek ...
1558          */
1559         if (sc->re_hwrev == RE_HWREV_8110S) {
1560                 CSR_WRITE_1(sc, 0x82, 1);
1561                 re_miibus_writereg(dev, 1, 0xb, 0);
1562         }
1563         if (sc->re_caps & RE_C_PHYPMGT) {
1564                 /* Power up PHY */
1565                 re_miibus_writereg(dev, 1, 0x1f, 0);
1566                 re_miibus_writereg(dev, 1, 0xe, 0);
1567         }
1568
1569         /* Do MII setup */
1570         if (mii_phy_probe(dev, &sc->re_miibus,
1571             re_ifmedia_upd, re_ifmedia_sts)) {
1572                 device_printf(dev, "MII without any phy!\n");
1573                 error = ENXIO;
1574                 goto fail;
1575         }
1576
1577         ifp = &sc->arpcom.ac_if;
1578         ifp->if_softc = sc;
1579         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1580         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1581         ifp->if_ioctl = re_ioctl;
1582         ifp->if_start = re_start;
1583 #ifdef DEVICE_POLLING
1584         ifp->if_poll = re_poll;
1585 #endif
1586         ifp->if_watchdog = re_watchdog;
1587         ifp->if_init = re_init;
1588         if (!RE_IS_8139CP(sc)) /* XXX */
1589                 ifp->if_baudrate = 1000000000;
1590         else
1591                 ifp->if_baudrate = 100000000;
1592         ifq_set_maxlen(&ifp->if_snd, qlen);
1593         ifq_set_ready(&ifp->if_snd);
1594
1595         ifp->if_capabilities = IFCAP_VLAN_MTU | IFCAP_VLAN_HWTAGGING;
1596         if (sc->re_caps & RE_C_HWCSUM)
1597                 ifp->if_capabilities |= IFCAP_HWCSUM;
1598
1599         ifp->if_capenable = ifp->if_capabilities;
1600         if (ifp->if_capabilities & IFCAP_HWCSUM)
1601                 ifp->if_hwassist = RE_CSUM_FEATURES;
1602         else
1603                 ifp->if_hwassist = 0;
1604
1605         /*
1606          * Call MI attach routine.
1607          */
1608         ether_ifattach(ifp, eaddr, NULL);
1609
1610 #ifdef RE_DIAG
1611         /*
1612          * Perform hardware diagnostic on the original RTL8169.
1613          * Some 32-bit cards were incorrectly wired and would
1614          * malfunction if plugged into a 64-bit slot.
1615          */
1616         if (sc->re_hwrev == RE_HWREV_8169) {
1617                 lwkt_serialize_enter(ifp->if_serializer);
1618                 error = re_diag(sc);
1619                 lwkt_serialize_exit(ifp->if_serializer);
1620
1621                 if (error) {
1622                         device_printf(dev, "hardware diagnostic failure\n");
1623                         ether_ifdetach(ifp);
1624                         goto fail;
1625                 }
1626         }
1627 #endif  /* RE_DIAG */
1628
1629         /* Hook interrupt last to avoid having to lock softc */
1630         error = bus_setup_intr(dev, sc->re_irq, INTR_MPSAFE, re_intr, sc,
1631                                &sc->re_intrhand, ifp->if_serializer);
1632
1633         if (error) {
1634                 device_printf(dev, "couldn't set up irq\n");
1635                 ether_ifdetach(ifp);
1636                 goto fail;
1637         }
1638
1639         ifp->if_cpuid = ithread_cpuid(rman_get_start(sc->re_irq));
1640         KKASSERT(ifp->if_cpuid >= 0 && ifp->if_cpuid < ncpus);
1641
1642 fail:
1643         if (error)
1644                 re_detach(dev);
1645
1646         return (error);
1647 }
1648
1649 /*
1650  * Shutdown hardware and free up resources. This can be called any
1651  * time after the mutex has been initialized. It is called in both
1652  * the error case in attach and the normal detach case so it needs
1653  * to be careful about only freeing resources that have actually been
1654  * allocated.
1655  */
1656 static int
1657 re_detach(device_t dev)
1658 {
1659         struct re_softc *sc = device_get_softc(dev);
1660         struct ifnet *ifp = &sc->arpcom.ac_if;
1661
1662         /* These should only be active if attach succeeded */
1663         if (device_is_attached(dev)) {
1664                 lwkt_serialize_enter(ifp->if_serializer);
1665                 re_stop(sc);
1666                 bus_teardown_intr(dev, sc->re_irq, sc->re_intrhand);
1667                 lwkt_serialize_exit(ifp->if_serializer);
1668
1669                 ether_ifdetach(ifp);
1670         }
1671         if (sc->re_miibus)
1672                 device_delete_child(dev, sc->re_miibus);
1673         bus_generic_detach(dev);
1674
1675         if (sc->re_sysctl_tree != NULL)
1676                 sysctl_ctx_free(&sc->re_sysctl_ctx);
1677
1678         if (sc->re_irq)
1679                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->re_irq);
1680         if (sc->re_res) {
1681                 bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO,
1682                                      sc->re_res);
1683         }
1684
1685         /* Free DMA stuffs */
1686         re_freemem(dev);
1687
1688         return(0);
1689 }
1690
1691 static void
1692 re_setup_rxdesc(struct re_softc *sc, int idx)
1693 {
1694         bus_addr_t paddr;
1695         uint32_t cmdstat;
1696         struct re_desc *d;
1697
1698         paddr = sc->re_ldata.re_rx_paddr[idx];
1699         d = &sc->re_ldata.re_rx_list[idx];
1700
1701         d->re_bufaddr_lo = htole32(RE_ADDR_LO(paddr));
1702         d->re_bufaddr_hi = htole32(RE_ADDR_HI(paddr));
1703
1704         cmdstat = MCLBYTES | RE_RDESC_CMD_OWN;
1705         if (idx == (sc->re_rx_desc_cnt - 1))
1706                 cmdstat |= RE_TDESC_CMD_EOR;
1707         d->re_cmdstat = htole32(cmdstat);
1708 }
1709
1710 static int
1711 re_newbuf(struct re_softc *sc, int idx, int init)
1712 {
1713         struct re_dmaload_arg arg;
1714         bus_dma_segment_t seg;
1715         bus_dmamap_t map;
1716         struct mbuf *m;
1717         int error;
1718
1719         m = m_getcl(init ? MB_WAIT : MB_DONTWAIT, MT_DATA, M_PKTHDR);
1720         if (m == NULL) {
1721                 error = ENOBUFS;
1722
1723                 if (init) {
1724                         if_printf(&sc->arpcom.ac_if, "m_getcl failed\n");
1725                         return error;
1726                 } else {
1727                         goto back;
1728                 }
1729         }
1730         m->m_len = m->m_pkthdr.len = MCLBYTES;
1731
1732         /*
1733          * NOTE:
1734          * Some re(4) chips(e.g. RTL8101E) need address of the receive buffer
1735          * to be 8-byte aligned, so don't call m_adj(m, ETHER_ALIGN) here.
1736          */
1737
1738         arg.re_nsegs = 1;
1739         arg.re_segs = &seg;
1740         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag,
1741                                      sc->re_ldata.re_rx_spare, m,
1742                                      re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1743         if (error || arg.re_nsegs == 0) {
1744                 if (!error) {
1745                         if_printf(&sc->arpcom.ac_if, "too many segments?!\n");
1746                         bus_dmamap_unload(sc->re_ldata.re_mtag,
1747                                           sc->re_ldata.re_rx_spare);
1748                         error = EFBIG;
1749                 }
1750                 m_freem(m);
1751
1752                 if (init) {
1753                         if_printf(&sc->arpcom.ac_if, "can't load RX mbuf\n");
1754                         return error;
1755                 } else {
1756                         goto back;
1757                 }
1758         }
1759
1760         if (!init) {
1761                 bus_dmamap_sync(sc->re_ldata.re_mtag,
1762                                 sc->re_ldata.re_rx_dmamap[idx],
1763                                 BUS_DMASYNC_POSTREAD);
1764                 bus_dmamap_unload(sc->re_ldata.re_mtag,
1765                                   sc->re_ldata.re_rx_dmamap[idx]);
1766         }
1767         sc->re_ldata.re_rx_mbuf[idx] = m;
1768         sc->re_ldata.re_rx_paddr[idx] = seg.ds_addr;
1769
1770         map = sc->re_ldata.re_rx_dmamap[idx];
1771         sc->re_ldata.re_rx_dmamap[idx] = sc->re_ldata.re_rx_spare;
1772         sc->re_ldata.re_rx_spare = map;
1773 back:
1774         re_setup_rxdesc(sc, idx);
1775         return error;
1776 }
1777
1778 static int
1779 re_tx_list_init(struct re_softc *sc)
1780 {
1781         bzero(sc->re_ldata.re_tx_list, RE_TX_LIST_SZ(sc));
1782
1783         /* Flush the TX descriptors */
1784         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1785                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
1786
1787         sc->re_ldata.re_tx_prodidx = 0;
1788         sc->re_ldata.re_tx_considx = 0;
1789         sc->re_ldata.re_tx_free = sc->re_tx_desc_cnt;
1790
1791         return(0);
1792 }
1793
1794 static int
1795 re_rx_list_init(struct re_softc *sc)
1796 {
1797         int i, error;
1798
1799         bzero(sc->re_ldata.re_rx_list, RE_RX_LIST_SZ(sc));
1800
1801         for (i = 0; i < sc->re_rx_desc_cnt; i++) {
1802                 error = re_newbuf(sc, i, 1);
1803                 if (error)
1804                         return(error);
1805         }
1806
1807         /* Flush the RX descriptors */
1808         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1809                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
1810
1811         sc->re_ldata.re_rx_prodidx = 0;
1812         sc->re_head = sc->re_tail = NULL;
1813
1814         return(0);
1815 }
1816
1817 #define RE_IP4_PACKET   0x1
1818 #define RE_TCP_PACKET   0x2
1819 #define RE_UDP_PACKET   0x4
1820
1821 static __inline uint8_t
1822 re_packet_type(struct re_softc *sc, uint32_t rxstat, uint32_t rxctrl)
1823 {
1824         uint8_t packet_type = 0;
1825
1826         if (sc->re_caps & RE_C_MAC2) {
1827                 if (rxctrl & RE_RDESC_CTL_PROTOIP4)
1828                         packet_type |= RE_IP4_PACKET;
1829         } else {
1830                 if (rxstat & RE_RDESC_STAT_PROTOID)
1831                         packet_type |= RE_IP4_PACKET;
1832         }
1833         if (RE_TCPPKT(rxstat))
1834                 packet_type |= RE_TCP_PACKET;
1835         else if (RE_UDPPKT(rxstat))
1836                 packet_type |= RE_UDP_PACKET;
1837         return packet_type;
1838 }
1839
1840 /*
1841  * RX handler for C+ and 8169. For the gigE chips, we support
1842  * the reception of jumbo frames that have been fragmented
1843  * across multiple 2K mbuf cluster buffers.
1844  */
1845 static int
1846 re_rxeof(struct re_softc *sc)
1847 {
1848         struct ifnet *ifp = &sc->arpcom.ac_if;
1849         struct mbuf *m;
1850         struct re_desc  *cur_rx;
1851         uint32_t rxstat, rxctrl;
1852         int i, total_len, rx = 0;
1853         struct mbuf_chain chain[MAXCPU];
1854
1855         /* Invalidate the descriptor memory */
1856
1857         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1858                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
1859
1860         ether_input_chain_init(chain);
1861
1862         for (i = sc->re_ldata.re_rx_prodidx;
1863              RE_OWN(&sc->re_ldata.re_rx_list[i]) == 0; RE_RXDESC_INC(sc, i)) {
1864                 cur_rx = &sc->re_ldata.re_rx_list[i];
1865                 m = sc->re_ldata.re_rx_mbuf[i];
1866                 total_len = RE_RXBYTES(cur_rx);
1867                 rxstat = le32toh(cur_rx->re_cmdstat);
1868                 rxctrl = le32toh(cur_rx->re_control);
1869
1870                 rx = 1;
1871
1872                 if ((rxstat & RE_RDESC_STAT_EOF) == 0) {
1873                         if (sc->re_drop_rxfrag) {
1874                                 re_setup_rxdesc(sc, i);
1875                                 continue;
1876                         }
1877
1878                         if (re_newbuf(sc, i, 0)) {
1879                                 /* Drop upcoming fragments */
1880                                 sc->re_drop_rxfrag = 1;
1881                                 continue;
1882                         }
1883
1884                         m->m_len = MCLBYTES;
1885                         if (sc->re_head == NULL) {
1886                                 sc->re_head = sc->re_tail = m;
1887                         } else {
1888                                 sc->re_tail->m_next = m;
1889                                 sc->re_tail = m;
1890                         }
1891                         continue;
1892                 } else if (sc->re_drop_rxfrag) {
1893                         /*
1894                          * Last fragment of a multi-fragment packet.
1895                          *
1896                          * Since error already happened, this fragment
1897                          * must be dropped as well as the fragment chain.
1898                          */
1899                         re_setup_rxdesc(sc, i);
1900                         re_free_rxchain(sc);
1901                         sc->re_drop_rxfrag = 0;
1902                         continue;
1903                 }
1904
1905                 /*
1906                  * NOTE: for the 8139C+, the frame length field
1907                  * is always 12 bits in size, but for the gigE chips,
1908                  * it is 13 bits (since the max RX frame length is 16K).
1909                  * Unfortunately, all 32 bits in the status word
1910                  * were already used, so to make room for the extra
1911                  * length bit, RealTek took out the 'frame alignment
1912                  * error' bit and shifted the other status bits
1913                  * over one slot. The OWN, EOR, FS and LS bits are
1914                  * still in the same places. We have already extracted
1915                  * the frame length and checked the OWN bit, so rather
1916                  * than using an alternate bit mapping, we shift the
1917                  * status bits one space to the right so we can evaluate
1918                  * them using the 8169 status as though it was in the
1919                  * same format as that of the 8139C+.
1920                  */
1921                 if (!RE_IS_8139CP(sc))
1922                         rxstat >>= 1;
1923
1924                 if (rxstat & RE_RDESC_STAT_RXERRSUM) {
1925                         ifp->if_ierrors++;
1926                         /*
1927                          * If this is part of a multi-fragment packet,
1928                          * discard all the pieces.
1929                          */
1930                         re_free_rxchain(sc);
1931                         re_setup_rxdesc(sc, i);
1932                         continue;
1933                 }
1934
1935                 /*
1936                  * If allocating a replacement mbuf fails,
1937                  * reload the current one.
1938                  */
1939
1940                 if (re_newbuf(sc, i, 0)) {
1941                         ifp->if_ierrors++;
1942                         re_free_rxchain(sc);
1943                         continue;
1944                 }
1945
1946                 if (sc->re_head != NULL) {
1947                         m->m_len = total_len % MCLBYTES;
1948                         /* 
1949                          * Special case: if there's 4 bytes or less
1950                          * in this buffer, the mbuf can be discarded:
1951                          * the last 4 bytes is the CRC, which we don't
1952                          * care about anyway.
1953                          */
1954                         if (m->m_len <= ETHER_CRC_LEN) {
1955                                 sc->re_tail->m_len -=
1956                                     (ETHER_CRC_LEN - m->m_len);
1957                                 m_freem(m);
1958                         } else {
1959                                 m->m_len -= ETHER_CRC_LEN;
1960                                 sc->re_tail->m_next = m;
1961                         }
1962                         m = sc->re_head;
1963                         sc->re_head = sc->re_tail = NULL;
1964                         m->m_pkthdr.len = total_len - ETHER_CRC_LEN;
1965                 } else {
1966                         m->m_pkthdr.len = m->m_len =
1967                             (total_len - ETHER_CRC_LEN);
1968                 }
1969
1970                 ifp->if_ipackets++;
1971                 m->m_pkthdr.rcvif = ifp;
1972
1973                 /* Do RX checksumming if enabled */
1974
1975                 if (ifp->if_capenable & IFCAP_RXCSUM) {
1976                         uint8_t packet_type;
1977
1978                         packet_type = re_packet_type(sc, rxstat, rxctrl);
1979
1980                         /* Check IP header checksum */
1981                         if (packet_type & RE_IP4_PACKET) {
1982                                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
1983                                 if ((rxstat & RE_RDESC_STAT_IPSUMBAD) == 0)
1984                                         m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1985                         }
1986
1987                         /* Check TCP/UDP checksum */
1988                         if (((packet_type & RE_TCP_PACKET) &&
1989                              (rxstat & RE_RDESC_STAT_TCPSUMBAD) == 0) ||
1990                             ((packet_type & RE_UDP_PACKET) &&
1991                              (rxstat & RE_RDESC_STAT_UDPSUMBAD) == 0)) {
1992                                 m->m_pkthdr.csum_flags |=
1993                                     CSUM_DATA_VALID|CSUM_PSEUDO_HDR|
1994                                     CSUM_FRAG_NOT_CHECKED;
1995                                 m->m_pkthdr.csum_data = 0xffff;
1996                         }
1997                 }
1998
1999                 if (rxctrl & RE_RDESC_CTL_HASTAG) {
2000                         m->m_flags |= M_VLANTAG;
2001                         m->m_pkthdr.ether_vlantag =
2002                                 be16toh((rxctrl & RE_RDESC_CTL_TAGDATA));
2003                 }
2004                 ether_input_chain(ifp, m, chain);
2005         }
2006
2007         ether_input_dispatch(chain);
2008
2009         /* Flush the RX DMA ring */
2010
2011         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
2012                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
2013
2014         sc->re_ldata.re_rx_prodidx = i;
2015
2016         return rx;
2017 }
2018
2019 #undef RE_IP4_PACKET
2020 #undef RE_TCP_PACKET
2021 #undef RE_UDP_PACKET
2022
2023 static int
2024 re_txeof(struct re_softc *sc)
2025 {
2026         struct ifnet *ifp = &sc->arpcom.ac_if;
2027         uint32_t txstat;
2028         int idx, tx = 0;
2029
2030         /* Invalidate the TX descriptor list */
2031
2032         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
2033                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_POSTREAD);
2034
2035         for (idx = sc->re_ldata.re_tx_considx;
2036              sc->re_ldata.re_tx_free < sc->re_tx_desc_cnt;
2037              RE_TXDESC_INC(sc, idx)) {
2038                 txstat = le32toh(sc->re_ldata.re_tx_list[idx].re_cmdstat);
2039                 if (txstat & RE_TDESC_CMD_OWN)
2040                         break;
2041
2042                 tx = 1;
2043
2044                 sc->re_ldata.re_tx_list[idx].re_bufaddr_lo = 0;
2045
2046                 /*
2047                  * We only stash mbufs in the last descriptor
2048                  * in a fragment chain, which also happens to
2049                  * be the only place where the TX status bits
2050                  * are valid.
2051                  */
2052                 if (txstat & RE_TDESC_CMD_EOF) {
2053                         m_freem(sc->re_ldata.re_tx_mbuf[idx]);
2054                         sc->re_ldata.re_tx_mbuf[idx] = NULL;
2055                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2056                             sc->re_ldata.re_tx_dmamap[idx]);
2057                         if (txstat & (RE_TDESC_STAT_EXCESSCOL|
2058                             RE_TDESC_STAT_COLCNT))
2059                                 ifp->if_collisions++;
2060                         if (txstat & RE_TDESC_STAT_TXERRSUM)
2061                                 ifp->if_oerrors++;
2062                         else
2063                                 ifp->if_opackets++;
2064                 }
2065                 sc->re_ldata.re_tx_free++;
2066         }
2067         sc->re_ldata.re_tx_considx = idx;
2068
2069         /* There is enough free TX descs */
2070         if (sc->re_ldata.re_tx_free > RE_TXDESC_SPARE)
2071                 ifp->if_flags &= ~IFF_OACTIVE;
2072
2073         /*
2074          * Some chips will ignore a second TX request issued while an
2075          * existing transmission is in progress. If the transmitter goes
2076          * idle but there are still packets waiting to be sent, we need
2077          * to restart the channel here to flush them out. This only seems
2078          * to be required with the PCIe devices.
2079          */
2080         if (sc->re_ldata.re_tx_free < sc->re_tx_desc_cnt)
2081                 CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
2082         else
2083                 ifp->if_timer = 0;
2084
2085         return tx;
2086 }
2087
2088 static void
2089 re_tick(void *xsc)
2090 {
2091         struct re_softc *sc = xsc;
2092
2093         lwkt_serialize_enter(sc->arpcom.ac_if.if_serializer);
2094         re_tick_serialized(xsc);
2095         lwkt_serialize_exit(sc->arpcom.ac_if.if_serializer);
2096 }
2097
2098 static void
2099 re_tick_serialized(void *xsc)
2100 {
2101         struct re_softc *sc = xsc;
2102         struct ifnet *ifp = &sc->arpcom.ac_if;
2103         struct mii_data *mii;
2104
2105         ASSERT_SERIALIZED(ifp->if_serializer);
2106
2107         mii = device_get_softc(sc->re_miibus);
2108         mii_tick(mii);
2109         if (sc->re_link) {
2110                 if (!(mii->mii_media_status & IFM_ACTIVE))
2111                         sc->re_link = 0;
2112         } else {
2113                 if (mii->mii_media_status & IFM_ACTIVE &&
2114                     IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) {
2115                         sc->re_link = 1;
2116                         if (!ifq_is_empty(&ifp->if_snd))
2117                                 if_devstart(ifp);
2118                 }
2119         }
2120
2121         callout_reset(&sc->re_timer, hz, re_tick, sc);
2122 }
2123
2124 #ifdef DEVICE_POLLING
2125
2126 static void
2127 re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
2128 {
2129         struct re_softc *sc = ifp->if_softc;
2130
2131         ASSERT_SERIALIZED(ifp->if_serializer);
2132
2133         switch(cmd) {
2134         case POLL_REGISTER:
2135                 /* disable interrupts */
2136                 re_setup_intr(sc, 0, RE_IMTYPE_NONE);
2137                 break;
2138
2139         case POLL_DEREGISTER:
2140                 /* enable interrupts */
2141                 re_setup_intr(sc, 1, sc->re_imtype);
2142                 break;
2143
2144         default:
2145                 sc->rxcycles = count;
2146                 re_rxeof(sc);
2147                 re_txeof(sc);
2148
2149                 if (!ifq_is_empty(&ifp->if_snd))
2150                         if_devstart(ifp);
2151
2152                 if (cmd == POLL_AND_CHECK_STATUS) { /* also check status register */
2153                         uint16_t       status;
2154
2155                         status = CSR_READ_2(sc, RE_ISR);
2156                         if (status == 0xffff)
2157                                 return;
2158                         if (status)
2159                                 CSR_WRITE_2(sc, RE_ISR, status);
2160
2161                         /*
2162                          * XXX check behaviour on receiver stalls.
2163                          */
2164
2165                         if (status & RE_ISR_SYSTEM_ERR) {
2166                                 re_reset(sc);
2167                                 re_init(sc);
2168                         }
2169                 }
2170                 break;
2171         }
2172 }
2173 #endif /* DEVICE_POLLING */
2174
2175 static void
2176 re_intr(void *arg)
2177 {
2178         struct re_softc *sc = arg;
2179         struct ifnet *ifp = &sc->arpcom.ac_if;
2180         uint16_t status;
2181         int rx, tx;
2182
2183         ASSERT_SERIALIZED(ifp->if_serializer);
2184
2185         if (sc->suspended || (ifp->if_flags & IFF_RUNNING) == 0)
2186                 return;
2187
2188         rx = tx = 0;
2189         for (;;) {
2190                 status = CSR_READ_2(sc, RE_ISR);
2191                 /* If the card has gone away the read returns 0xffff. */
2192                 if (status == 0xffff)
2193                         break;
2194                 if (status)
2195                         CSR_WRITE_2(sc, RE_ISR, status);
2196
2197                 if ((status & sc->re_intrs) == 0)
2198                         break;
2199
2200                 if (status & (sc->re_rx_ack | RE_ISR_RX_ERR))
2201                         rx |= re_rxeof(sc);
2202
2203                 if (status & (sc->re_tx_ack | RE_ISR_TX_ERR))
2204                         tx |= re_txeof(sc);
2205
2206                 if (status & RE_ISR_SYSTEM_ERR) {
2207                         re_reset(sc);
2208                         re_init(sc);
2209                 }
2210
2211                 if (status & RE_ISR_LINKCHG) {
2212                         callout_stop(&sc->re_timer);
2213                         re_tick_serialized(sc);
2214                 }
2215         }
2216
2217         if (sc->re_imtype == RE_IMTYPE_SIM) {
2218                 if ((sc->re_flags & RE_F_TIMER_INTR)) {
2219                         if ((tx | rx) == 0)
2220                                 re_setup_intr(sc, 1, RE_IMTYPE_NONE);
2221                         else
2222                                 CSR_WRITE_4(sc, RE_TIMERCNT, 1); /* reload */
2223                 } else if (tx | rx) {
2224                         re_setup_intr(sc, 1, RE_IMTYPE_SIM);
2225                 }
2226         }
2227
2228         if (tx && !ifq_is_empty(&ifp->if_snd))
2229                 if_devstart(ifp);
2230 }
2231
2232 static int
2233 re_encap(struct re_softc *sc, struct mbuf **m_head, int *idx0)
2234 {
2235         struct ifnet *ifp = &sc->arpcom.ac_if;
2236         struct mbuf *m;
2237         struct re_dmaload_arg arg;
2238         bus_dma_segment_t segs[RE_MAXSEGS];
2239         bus_dmamap_t map;
2240         int error, maxsegs, idx, i;
2241         struct re_desc *d, *tx_ring;
2242         uint32_t cmd_csum, ctl_csum;
2243
2244         KASSERT(sc->re_ldata.re_tx_free > RE_TXDESC_SPARE,
2245                 ("not enough free TX desc\n"));
2246
2247         m = *m_head;
2248         map = sc->re_ldata.re_tx_dmamap[*idx0];
2249
2250         /*
2251          * Set up checksum offload. Note: checksum offload bits must
2252          * appear in all descriptors of a multi-descriptor transmit
2253          * attempt. (This is according to testing done with an 8169
2254          * chip. I'm not sure if this is a requirement or a bug.)
2255          */
2256         cmd_csum = ctl_csum = 0;
2257         if (m->m_pkthdr.csum_flags & CSUM_IP) {
2258                 cmd_csum |= RE_TDESC_CMD_IPCSUM;
2259                 ctl_csum |= RE_TDESC_CTL_IPCSUM;
2260         }
2261         if (m->m_pkthdr.csum_flags & CSUM_TCP) {
2262                 cmd_csum |= RE_TDESC_CMD_TCPCSUM;
2263                 ctl_csum |= RE_TDESC_CTL_TCPCSUM;
2264         }
2265         if (m->m_pkthdr.csum_flags & CSUM_UDP) {
2266                 cmd_csum |= RE_TDESC_CMD_UDPCSUM;
2267                 ctl_csum |= RE_TDESC_CTL_UDPCSUM;
2268         }
2269
2270         /* For MAC2 chips, csum flags are set on re_control */
2271         if (sc->re_caps & RE_C_MAC2)
2272                 cmd_csum = 0;
2273         else
2274                 ctl_csum = 0;
2275
2276         if (m->m_pkthdr.len > sc->re_swcsum_lim &&
2277             (m->m_pkthdr.csum_flags & (CSUM_DELAY_IP | CSUM_DELAY_DATA))) {
2278                 struct ether_header *eh;
2279                 struct ip *ip;
2280                 u_short offset;
2281
2282                 m = m_pullup(m, sizeof(struct ether_header *));
2283                 if (m == NULL) {
2284                         *m_head = NULL;
2285                         return ENOBUFS;
2286                 }
2287                 eh = mtod(m, struct ether_header *);
2288
2289                 /* XXX */
2290                 if (eh->ether_type == ETHERTYPE_VLAN)
2291                         offset = sizeof(struct ether_vlan_header);
2292                 else
2293                         offset = sizeof(struct ether_header);
2294
2295                 m = m_pullup(m, offset + sizeof(struct ip *));
2296                 if (m == NULL) {
2297                         *m_head = NULL;
2298                         return ENOBUFS;
2299                 }
2300                 ip = (struct ip *)(mtod(m, uint8_t *) + offset);
2301
2302                 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2303                         u_short csum;
2304
2305                         offset += IP_VHL_HL(ip->ip_vhl) << 2;
2306                         csum = in_cksum_skip(m, ntohs(ip->ip_len), offset);
2307                         if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
2308                                 csum = 0xffff;
2309                         offset += m->m_pkthdr.csum_data;        /* checksum offset */
2310                         *(u_short *)(m->m_data + offset) = csum;
2311
2312                         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2313                 }
2314                 if (m->m_pkthdr.csum_flags & CSUM_DELAY_IP) {
2315                         ip->ip_sum = 0;
2316                         if (ip->ip_vhl == IP_VHL_BORING) {
2317                                 ip->ip_sum = in_cksum_hdr(ip);
2318                         } else {
2319                                 ip->ip_sum =
2320                                 in_cksum(m, IP_VHL_HL(ip->ip_vhl) << 2);
2321                         }
2322                         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_IP;
2323                 }
2324                 *m_head = m; /* 'm' may be changed by above two m_pullup() */
2325
2326                 /* Clear hardware CSUM flags */
2327                 cmd_csum = ctl_csum = 0;
2328         }
2329
2330         if ((sc->re_caps & RE_C_AUTOPAD) == 0) {
2331                 /*
2332                  * With some of the RealTek chips, using the checksum offload
2333                  * support in conjunction with the autopadding feature results
2334                  * in the transmission of corrupt frames. For example, if we
2335                  * need to send a really small IP fragment that's less than 60
2336                  * bytes in size, and IP header checksumming is enabled, the
2337                  * resulting ethernet frame that appears on the wire will
2338                  * have garbled payload. To work around this, if TX checksum
2339                  * offload is enabled, we always manually pad short frames out
2340                  * to the minimum ethernet frame size.
2341                  *
2342                  * Note: this appears unnecessary for TCP, and doing it for TCP
2343                  * with PCIe adapters seems to result in bad checksums.
2344                  */
2345                 if ((m->m_pkthdr.csum_flags &
2346                      (CSUM_DELAY_IP | CSUM_DELAY_DATA)) &&
2347                     (m->m_pkthdr.csum_flags & CSUM_TCP) == 0 &&
2348                     m->m_pkthdr.len < RE_MIN_FRAMELEN) {
2349                         error = re_pad_frame(m);
2350                         if (error)
2351                                 goto back;
2352                 }
2353         }
2354
2355         maxsegs = sc->re_ldata.re_tx_free;
2356         if (maxsegs > RE_MAXSEGS)
2357                 maxsegs = RE_MAXSEGS;
2358
2359         arg.re_nsegs = maxsegs;
2360         arg.re_segs = segs;
2361         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map, m,
2362                                      re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
2363         if (error && error != EFBIG) {
2364                 if_printf(ifp, "can't map mbuf (error %d)\n", error);
2365                 goto back;
2366         }
2367
2368         /*
2369          * Too many segments to map, coalesce into a single mbuf
2370          */
2371         if (!error && arg.re_nsegs == 0) {
2372                 bus_dmamap_unload(sc->re_ldata.re_mtag, map);
2373                 error = EFBIG;
2374         }
2375         if (error) {
2376                 struct mbuf *m_new;
2377
2378                 m_new = m_defrag(m, MB_DONTWAIT);
2379                 if (m_new == NULL) {
2380                         if_printf(ifp, "can't defrag TX mbuf\n");
2381                         error = ENOBUFS;
2382                         goto back;
2383                 } else {
2384                         *m_head = m = m_new;
2385                 }
2386
2387                 arg.re_nsegs = maxsegs;
2388                 arg.re_segs = segs;
2389                 error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map, m,
2390                                              re_dma_map_desc, &arg,
2391                                              BUS_DMA_NOWAIT);
2392                 if (error || arg.re_nsegs == 0) {
2393                         if (!error) {
2394                                 bus_dmamap_unload(sc->re_ldata.re_mtag, map);
2395                                 error = EFBIG;
2396                         }
2397                         if_printf(ifp, "can't map mbuf (error %d)\n", error);
2398                         goto back;
2399                 }
2400         }
2401         bus_dmamap_sync(sc->re_ldata.re_mtag, map, BUS_DMASYNC_PREWRITE);
2402
2403         /*
2404          * Map the segment array into descriptors.  We also keep track
2405          * of the end of the ring and set the end-of-ring bits as needed,
2406          * and we set the ownership bits in all except the very first
2407          * descriptor, whose ownership bits will be turned on later.
2408          */
2409         tx_ring = sc->re_ldata.re_tx_list;
2410         idx = *idx0;
2411         i = 0;
2412         for (;;) {
2413                 uint32_t cmdstat;
2414
2415                 d = &tx_ring[idx];
2416
2417                 cmdstat = segs[i].ds_len;
2418                 d->re_bufaddr_lo = htole32(RE_ADDR_LO(segs[i].ds_addr));
2419                 d->re_bufaddr_hi = htole32(RE_ADDR_HI(segs[i].ds_addr));
2420                 if (i == 0)
2421                         cmdstat |= RE_TDESC_CMD_SOF;
2422                 else
2423                         cmdstat |= RE_TDESC_CMD_OWN;
2424                 if (idx == (sc->re_tx_desc_cnt - 1))
2425                         cmdstat |= RE_TDESC_CMD_EOR;
2426                 d->re_cmdstat = htole32(cmdstat | cmd_csum);
2427                 d->re_control = htole32(ctl_csum);
2428
2429                 i++;
2430                 if (i == arg.re_nsegs)
2431                         break;
2432                 RE_TXDESC_INC(sc, idx);
2433         }
2434         d->re_cmdstat |= htole32(RE_TDESC_CMD_EOF);
2435
2436         /*
2437          * Set up hardware VLAN tagging. Note: vlan tag info must
2438          * appear in the first descriptor of a multi-descriptor
2439          * transmission attempt.
2440          */
2441         if (m->m_flags & M_VLANTAG) {
2442                 tx_ring[*idx0].re_control |=
2443                     htole32(htobe16(m->m_pkthdr.ether_vlantag) |
2444                             RE_TDESC_CTL_INSTAG);
2445         }
2446
2447         /* Transfer ownership of packet to the chip. */
2448         d->re_cmdstat |= htole32(RE_TDESC_CMD_OWN);
2449         if (*idx0 != idx)
2450                 tx_ring[*idx0].re_cmdstat |= htole32(RE_TDESC_CMD_OWN);
2451
2452         /*
2453          * Insure that the map for this transmission
2454          * is placed at the array index of the last descriptor
2455          * in this chain.
2456          */
2457         sc->re_ldata.re_tx_dmamap[*idx0] = sc->re_ldata.re_tx_dmamap[idx];
2458         sc->re_ldata.re_tx_dmamap[idx] = map;
2459
2460         sc->re_ldata.re_tx_mbuf[idx] = m;
2461         sc->re_ldata.re_tx_free -= arg.re_nsegs;
2462
2463         RE_TXDESC_INC(sc, idx);
2464         *idx0 = idx;
2465 back:
2466         if (error) {
2467                 m_freem(m);
2468                 *m_head = NULL;
2469         }
2470         return error;
2471 }
2472
2473 /*
2474  * Main transmit routine for C+ and gigE NICs.
2475  */
2476
2477 static void
2478 re_start(struct ifnet *ifp)
2479 {
2480         struct re_softc *sc = ifp->if_softc;
2481         struct mbuf *m_head;
2482         int idx, need_trans;
2483
2484         ASSERT_SERIALIZED(ifp->if_serializer);
2485
2486         if (!sc->re_link) {
2487                 ifq_purge(&ifp->if_snd);
2488                 return;
2489         }
2490
2491         if ((ifp->if_flags & (IFF_OACTIVE | IFF_RUNNING)) != IFF_RUNNING)
2492                 return;
2493
2494         idx = sc->re_ldata.re_tx_prodidx;
2495
2496         need_trans = 0;
2497         while (sc->re_ldata.re_tx_mbuf[idx] == NULL) {
2498                 if (sc->re_ldata.re_tx_free <= RE_TXDESC_SPARE) {
2499                         ifp->if_flags |= IFF_OACTIVE;
2500                         break;
2501                 }
2502
2503                 m_head = ifq_dequeue(&ifp->if_snd, NULL);
2504                 if (m_head == NULL)
2505                         break;
2506
2507                 if (re_encap(sc, &m_head, &idx)) {
2508                         /* m_head is freed by re_encap(), if we reach here */
2509                         ifp->if_oerrors++;
2510                         ifp->if_flags |= IFF_OACTIVE;
2511                         break;
2512                 }
2513
2514                 need_trans = 1;
2515
2516                 /*
2517                  * If there's a BPF listener, bounce a copy of this frame
2518                  * to him.
2519                  */
2520                 ETHER_BPF_MTAP(ifp, m_head);
2521         }
2522
2523         if (!need_trans)
2524                 return;
2525
2526         /* Flush the TX descriptors */
2527         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
2528                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
2529
2530         sc->re_ldata.re_tx_prodidx = idx;
2531
2532         /*
2533          * RealTek put the TX poll request register in a different
2534          * location on the 8169 gigE chip. I don't know why.
2535          */
2536         CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
2537
2538         /*
2539          * Set a timeout in case the chip goes out to lunch.
2540          */
2541         ifp->if_timer = 5;
2542 }
2543
2544 static void
2545 re_init(void *xsc)
2546 {
2547         struct re_softc *sc = xsc;
2548         struct ifnet *ifp = &sc->arpcom.ac_if;
2549         struct mii_data *mii;
2550         uint32_t rxcfg = 0;
2551         int error, framelen;
2552
2553         ASSERT_SERIALIZED(ifp->if_serializer);
2554
2555         mii = device_get_softc(sc->re_miibus);
2556
2557         /*
2558          * Cancel pending I/O and free all RX/TX buffers.
2559          */
2560         re_stop(sc);
2561
2562         /*
2563          * Enable C+ RX and TX mode, as well as VLAN stripping and
2564          * RX checksum offload. We must configure the C+ register
2565          * before all others.
2566          */
2567         CSR_WRITE_2(sc, RE_CPLUS_CMD, RE_CPLUSCMD_RXENB | RE_CPLUSCMD_TXENB |
2568                     RE_CPLUSCMD_PCI_MRW | RE_CPLUSCMD_VLANSTRIP |
2569                     (ifp->if_capenable & IFCAP_RXCSUM ?
2570                      RE_CPLUSCMD_RXCSUM_ENB : 0));
2571
2572         /*
2573          * Init our MAC address.  Even though the chipset
2574          * documentation doesn't mention it, we need to enter "Config
2575          * register write enable" mode to modify the ID registers.
2576          */
2577         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_WRITECFG);
2578         CSR_WRITE_4(sc, RE_IDR0,
2579             htole32(*(uint32_t *)(&sc->arpcom.ac_enaddr[0])));
2580         CSR_WRITE_2(sc, RE_IDR4,
2581             htole16(*(uint16_t *)(&sc->arpcom.ac_enaddr[4])));
2582         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_OFF);
2583
2584         /*
2585          * For C+ mode, initialize the RX descriptors and mbufs.
2586          */
2587         error = re_rx_list_init(sc);
2588         if (error) {
2589                 re_stop(sc);
2590                 return;
2591         }
2592         error = re_tx_list_init(sc);
2593         if (error) {
2594                 re_stop(sc);
2595                 return;
2596         }
2597
2598         /*
2599          * Load the addresses of the RX and TX lists into the chip.
2600          */
2601         CSR_WRITE_4(sc, RE_RXLIST_ADDR_HI,
2602             RE_ADDR_HI(sc->re_ldata.re_rx_list_addr));
2603         CSR_WRITE_4(sc, RE_RXLIST_ADDR_LO,
2604             RE_ADDR_LO(sc->re_ldata.re_rx_list_addr));
2605
2606         CSR_WRITE_4(sc, RE_TXLIST_ADDR_HI,
2607             RE_ADDR_HI(sc->re_ldata.re_tx_list_addr));
2608         CSR_WRITE_4(sc, RE_TXLIST_ADDR_LO,
2609             RE_ADDR_LO(sc->re_ldata.re_tx_list_addr));
2610
2611         /*
2612          * Enable transmit and receive.
2613          */
2614         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2615
2616         /*
2617          * Set the initial TX and RX configuration.
2618          */
2619         if (sc->re_testmode) {
2620                 if (!RE_IS_8139CP(sc))
2621                         CSR_WRITE_4(sc, RE_TXCFG,
2622                                     RE_TXCFG_CONFIG | RE_LOOPTEST_ON);
2623                 else
2624                         CSR_WRITE_4(sc, RE_TXCFG,
2625                                     RE_TXCFG_CONFIG | RE_LOOPTEST_ON_CPLUS);
2626         } else
2627                 CSR_WRITE_4(sc, RE_TXCFG, RE_TXCFG_CONFIG);
2628
2629         framelen = RE_FRAMELEN(ifp->if_mtu);
2630         if (framelen < RE_FRAMELEN_2K) {
2631                 CSR_WRITE_1(sc, RE_EARLY_TX_THRESH,
2632                             howmany(RE_FRAMELEN_2K, 128));
2633         } else {
2634                 CSR_WRITE_1(sc, RE_EARLY_TX_THRESH, howmany(framelen, 128));
2635         }
2636
2637         CSR_WRITE_4(sc, RE_RXCFG, RE_RXCFG_CONFIG);
2638
2639         /* Set the individual bit to receive frames for this host only. */
2640         rxcfg = CSR_READ_4(sc, RE_RXCFG);
2641         rxcfg |= RE_RXCFG_RX_INDIV;
2642
2643         /* If we want promiscuous mode, set the allframes bit. */
2644         if (ifp->if_flags & IFF_PROMISC) {
2645                 rxcfg |= RE_RXCFG_RX_ALLPHYS;
2646                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2647         } else {
2648                 rxcfg &= ~RE_RXCFG_RX_ALLPHYS;
2649                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2650         }
2651
2652         /*
2653          * Set capture broadcast bit to capture broadcast frames.
2654          */
2655         if (ifp->if_flags & IFF_BROADCAST) {
2656                 rxcfg |= RE_RXCFG_RX_BROAD;
2657                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2658         } else {
2659                 rxcfg &= ~RE_RXCFG_RX_BROAD;
2660                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2661         }
2662
2663         /*
2664          * Program the multicast filter, if necessary.
2665          */
2666         re_setmulti(sc);
2667
2668 #ifdef DEVICE_POLLING
2669         /*
2670          * Disable interrupts if we are polling.
2671          */
2672         if (ifp->if_flags & IFF_POLLING)
2673                 re_setup_intr(sc, 0, RE_IMTYPE_NONE);
2674         else    /* otherwise ... */
2675 #endif /* DEVICE_POLLING */
2676         /*
2677          * Enable interrupts.
2678          */
2679         if (sc->re_testmode)
2680                 CSR_WRITE_2(sc, RE_IMR, 0);
2681         else
2682                 re_setup_intr(sc, 1, sc->re_imtype);
2683         CSR_WRITE_2(sc, RE_ISR, sc->re_intrs);
2684
2685         /* Set initial TX threshold */
2686         sc->re_txthresh = RE_TX_THRESH_INIT;
2687
2688         /* Start RX/TX process. */
2689         CSR_WRITE_4(sc, RE_MISSEDPKT, 0);
2690
2691 #ifdef notdef
2692         /* Enable receiver and transmitter. */
2693         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2694 #endif
2695
2696         /*
2697          * For 8169 gigE NICs, set the max allowed RX packet
2698          * size so we can receive jumbo frames.
2699          */
2700         if (!RE_IS_8139CP(sc))
2701                 CSR_WRITE_2(sc, RE_MAXRXPKTLEN, 16383);
2702
2703         if (sc->re_testmode)
2704                 return;
2705
2706         mii_mediachg(mii);
2707
2708         CSR_WRITE_1(sc, RE_CFG1, RE_CFG1_DRVLOAD|RE_CFG1_FULLDUPLEX);
2709
2710         ifp->if_flags |= IFF_RUNNING;
2711         ifp->if_flags &= ~IFF_OACTIVE;
2712
2713         sc->re_link = 0;
2714         callout_reset(&sc->re_timer, hz, re_tick, sc);
2715 }
2716
2717 /*
2718  * Set media options.
2719  */
2720 static int
2721 re_ifmedia_upd(struct ifnet *ifp)
2722 {
2723         struct re_softc *sc = ifp->if_softc;
2724         struct mii_data *mii;
2725
2726         ASSERT_SERIALIZED(ifp->if_serializer);
2727
2728         mii = device_get_softc(sc->re_miibus);
2729         mii_mediachg(mii);
2730
2731         return(0);
2732 }
2733
2734 /*
2735  * Report current media status.
2736  */
2737 static void
2738 re_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2739 {
2740         struct re_softc *sc = ifp->if_softc;
2741         struct mii_data *mii;
2742
2743         ASSERT_SERIALIZED(ifp->if_serializer);
2744
2745         mii = device_get_softc(sc->re_miibus);
2746
2747         mii_pollstat(mii);
2748         ifmr->ifm_active = mii->mii_media_active;
2749         ifmr->ifm_status = mii->mii_media_status;
2750 }
2751
2752 static int
2753 re_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
2754 {
2755         struct re_softc *sc = ifp->if_softc;
2756         struct ifreq *ifr = (struct ifreq *) data;
2757         struct mii_data *mii;
2758         int error = 0;
2759
2760         ASSERT_SERIALIZED(ifp->if_serializer);
2761
2762         switch(command) {
2763         case SIOCSIFMTU:
2764                 if (ifr->ifr_mtu > sc->re_maxmtu) {
2765                         error = EINVAL;
2766                 } else if (ifp->if_mtu != ifr->ifr_mtu) {
2767                         ifp->if_mtu = ifr->ifr_mtu;
2768                         if (ifp->if_flags & IFF_RUNNING)
2769                                 ifp->if_init(sc);
2770                 }
2771                 break;
2772
2773         case SIOCSIFFLAGS:
2774                 if (ifp->if_flags & IFF_UP)
2775                         re_init(sc);
2776                 else if (ifp->if_flags & IFF_RUNNING)
2777                         re_stop(sc);
2778                 break;
2779         case SIOCADDMULTI:
2780         case SIOCDELMULTI:
2781                 re_setmulti(sc);
2782                 error = 0;
2783                 break;
2784         case SIOCGIFMEDIA:
2785         case SIOCSIFMEDIA:
2786                 mii = device_get_softc(sc->re_miibus);
2787                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
2788                 break;
2789         case SIOCSIFCAP:
2790                 ifp->if_capenable &= ~(IFCAP_HWCSUM);
2791                 ifp->if_capenable |=
2792                     ifr->ifr_reqcap & (IFCAP_HWCSUM);
2793                 if (ifp->if_capenable & IFCAP_TXCSUM)
2794                         ifp->if_hwassist = RE_CSUM_FEATURES;
2795                 else
2796                         ifp->if_hwassist = 0;
2797                 if (ifp->if_flags & IFF_RUNNING)
2798                         re_init(sc);
2799                 break;
2800         default:
2801                 error = ether_ioctl(ifp, command, data);
2802                 break;
2803         }
2804         return(error);
2805 }
2806
2807 static void
2808 re_watchdog(struct ifnet *ifp)
2809 {
2810         struct re_softc *sc = ifp->if_softc;
2811
2812         ASSERT_SERIALIZED(ifp->if_serializer);
2813
2814         if_printf(ifp, "watchdog timeout\n");
2815
2816         ifp->if_oerrors++;
2817
2818         re_txeof(sc);
2819         re_rxeof(sc);
2820
2821         re_init(sc);
2822
2823         if (!ifq_is_empty(&ifp->if_snd))
2824                 if_devstart(ifp);
2825 }
2826
2827 /*
2828  * Stop the adapter and free any mbufs allocated to the
2829  * RX and TX lists.
2830  */
2831 static void
2832 re_stop(struct re_softc *sc)
2833 {
2834         struct ifnet *ifp = &sc->arpcom.ac_if;
2835         int i;
2836
2837         ASSERT_SERIALIZED(ifp->if_serializer);
2838
2839         ifp->if_timer = 0;
2840         callout_stop(&sc->re_timer);
2841
2842         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2843         sc->re_flags &= ~RE_F_TIMER_INTR;
2844
2845         CSR_WRITE_1(sc, RE_COMMAND, 0x00);
2846         CSR_WRITE_2(sc, RE_IMR, 0x0000);
2847         CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
2848
2849         re_free_rxchain(sc);
2850         sc->re_drop_rxfrag = 0;
2851
2852         /* Free the TX list buffers. */
2853         for (i = 0; i < sc->re_tx_desc_cnt; i++) {
2854                 if (sc->re_ldata.re_tx_mbuf[i] != NULL) {
2855                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2856                                           sc->re_ldata.re_tx_dmamap[i]);
2857                         m_freem(sc->re_ldata.re_tx_mbuf[i]);
2858                         sc->re_ldata.re_tx_mbuf[i] = NULL;
2859                 }
2860         }
2861
2862         /* Free the RX list buffers. */
2863         for (i = 0; i < sc->re_rx_desc_cnt; i++) {
2864                 if (sc->re_ldata.re_rx_mbuf[i] != NULL) {
2865                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2866                                           sc->re_ldata.re_rx_dmamap[i]);
2867                         m_freem(sc->re_ldata.re_rx_mbuf[i]);
2868                         sc->re_ldata.re_rx_mbuf[i] = NULL;
2869                 }
2870         }
2871 }
2872
2873 /*
2874  * Device suspend routine.  Stop the interface and save some PCI
2875  * settings in case the BIOS doesn't restore them properly on
2876  * resume.
2877  */
2878 static int
2879 re_suspend(device_t dev)
2880 {
2881 #ifndef BURN_BRIDGES
2882         int i;
2883 #endif
2884         struct re_softc *sc = device_get_softc(dev);
2885         struct ifnet *ifp = &sc->arpcom.ac_if;
2886
2887         lwkt_serialize_enter(ifp->if_serializer);
2888
2889         re_stop(sc);
2890
2891 #ifndef BURN_BRIDGES
2892         for (i = 0; i < 5; i++)
2893                 sc->saved_maps[i] = pci_read_config(dev, PCIR_MAPS + i * 4, 4);
2894         sc->saved_biosaddr = pci_read_config(dev, PCIR_BIOS, 4);
2895         sc->saved_intline = pci_read_config(dev, PCIR_INTLINE, 1);
2896         sc->saved_cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
2897         sc->saved_lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
2898 #endif
2899
2900         sc->suspended = 1;
2901
2902         lwkt_serialize_exit(ifp->if_serializer);
2903
2904         return (0);
2905 }
2906
2907 /*
2908  * Device resume routine.  Restore some PCI settings in case the BIOS
2909  * doesn't, re-enable busmastering, and restart the interface if
2910  * appropriate.
2911  */
2912 static int
2913 re_resume(device_t dev)
2914 {
2915         struct re_softc *sc = device_get_softc(dev);
2916         struct ifnet *ifp = &sc->arpcom.ac_if;
2917 #ifndef BURN_BRIDGES
2918         int i;
2919 #endif
2920
2921         lwkt_serialize_enter(ifp->if_serializer);
2922
2923 #ifndef BURN_BRIDGES
2924         /* better way to do this? */
2925         for (i = 0; i < 5; i++)
2926                 pci_write_config(dev, PCIR_MAPS + i * 4, sc->saved_maps[i], 4);
2927         pci_write_config(dev, PCIR_BIOS, sc->saved_biosaddr, 4);
2928         pci_write_config(dev, PCIR_INTLINE, sc->saved_intline, 1);
2929         pci_write_config(dev, PCIR_CACHELNSZ, sc->saved_cachelnsz, 1);
2930         pci_write_config(dev, PCIR_LATTIMER, sc->saved_lattimer, 1);
2931
2932         /* reenable busmastering */
2933         pci_enable_busmaster(dev);
2934         pci_enable_io(dev, SYS_RES_IOPORT);
2935 #endif
2936
2937         /* reinitialize interface if necessary */
2938         if (ifp->if_flags & IFF_UP)
2939                 re_init(sc);
2940
2941         sc->suspended = 0;
2942
2943         lwkt_serialize_exit(ifp->if_serializer);
2944
2945         return (0);
2946 }
2947
2948 /*
2949  * Stop all chip I/O so that the kernel's probe routines don't
2950  * get confused by errant DMAs when rebooting.
2951  */
2952 static void
2953 re_shutdown(device_t dev)
2954 {
2955         struct re_softc *sc = device_get_softc(dev);
2956         struct ifnet *ifp = &sc->arpcom.ac_if;
2957
2958         lwkt_serialize_enter(ifp->if_serializer);
2959         re_stop(sc);
2960         lwkt_serialize_exit(ifp->if_serializer);
2961 }
2962
2963 static int
2964 re_pad_frame(struct mbuf *pkt)
2965 {
2966         struct mbuf *last = NULL;
2967         int padlen;
2968
2969         padlen = RE_MIN_FRAMELEN - pkt->m_pkthdr.len;
2970
2971         /* if there's only the packet-header and we can pad there, use it. */
2972         if (pkt->m_pkthdr.len == pkt->m_len &&
2973             M_TRAILINGSPACE(pkt) >= padlen) {
2974                 last = pkt;
2975         } else {
2976                 /*
2977                  * Walk packet chain to find last mbuf. We will either
2978                  * pad there, or append a new mbuf and pad it
2979                  */
2980                 for (last = pkt; last->m_next != NULL; last = last->m_next)
2981                         ; /* EMPTY */
2982
2983                 /* `last' now points to last in chain. */
2984                 if (M_TRAILINGSPACE(last) < padlen) {
2985                         struct mbuf *n;
2986
2987                         /* Allocate new empty mbuf, pad it.  Compact later. */
2988                         MGET(n, MB_DONTWAIT, MT_DATA);
2989                         if (n == NULL)
2990                                 return ENOBUFS;
2991                         n->m_len = 0;
2992                         last->m_next = n;
2993                         last = n;
2994                 }
2995         }
2996         KKASSERT(M_TRAILINGSPACE(last) >= padlen);
2997         KKASSERT(M_WRITABLE(last));
2998
2999         /* Now zero the pad area, to avoid the re cksum-assist bug */
3000         bzero(mtod(last, char *) + last->m_len, padlen);
3001         last->m_len += padlen;
3002         pkt->m_pkthdr.len += padlen;
3003         return 0;
3004 }
3005
3006 static int
3007 re_sysctl_rxtime(SYSCTL_HANDLER_ARGS)
3008 {
3009         struct re_softc *sc = arg1;
3010
3011         return re_sysctl_hwtime(oidp, arg1, arg2, req, &sc->re_rx_time);
3012 }
3013
3014 static int
3015 re_sysctl_txtime(SYSCTL_HANDLER_ARGS)
3016 {
3017         struct re_softc *sc = arg1;
3018
3019         return re_sysctl_hwtime(oidp, arg1, arg2, req, &sc->re_tx_time);
3020 }
3021
3022 static int
3023 re_sysctl_hwtime(SYSCTL_HANDLER_ARGS, int *hwtime)
3024 {
3025         struct re_softc *sc = arg1;
3026         struct ifnet *ifp = &sc->arpcom.ac_if;
3027         int error, v;
3028
3029         lwkt_serialize_enter(ifp->if_serializer);
3030
3031         v = *hwtime;
3032         error = sysctl_handle_int(oidp, &v, 0, req);
3033         if (error || req->newptr == NULL)
3034                 goto back;
3035
3036         if (v <= 0) {
3037                 error = EINVAL;
3038                 goto back;
3039         }
3040
3041         if (v != *hwtime) {
3042                 *hwtime = v;
3043
3044                 if ((ifp->if_flags & (IFF_RUNNING | IFF_POLLING)) ==
3045                     IFF_RUNNING && sc->re_imtype == RE_IMTYPE_HW)
3046                         re_setup_hw_im(sc);
3047         }
3048 back:
3049         lwkt_serialize_exit(ifp->if_serializer);
3050         return error;
3051 }
3052
3053 static int
3054 re_sysctl_simtime(SYSCTL_HANDLER_ARGS)
3055 {
3056         struct re_softc *sc = arg1;
3057         struct ifnet *ifp = &sc->arpcom.ac_if;
3058         int error, v;
3059
3060         lwkt_serialize_enter(ifp->if_serializer);
3061
3062         v = sc->re_sim_time;
3063         error = sysctl_handle_int(oidp, &v, 0, req);
3064         if (error || req->newptr == NULL)
3065                 goto back;
3066
3067         if (v <= 0) {
3068                 error = EINVAL;
3069                 goto back;
3070         }
3071
3072         if (v != sc->re_sim_time) {
3073                 sc->re_sim_time = v;
3074
3075                 if ((ifp->if_flags & (IFF_RUNNING | IFF_POLLING)) ==
3076                     IFF_RUNNING && sc->re_imtype == RE_IMTYPE_SIM) {
3077 #ifdef foo
3078                         int reg;
3079
3080                         /*
3081                          * Following code causes various strange
3082                          * performance problems.  Hmm ...
3083                          */
3084                         CSR_WRITE_2(sc, RE_IMR, 0);
3085                         if (!RE_IS_8139CP(sc))
3086                                 reg = RE_TIMERINT_8169;
3087                         else
3088                                 reg = RE_TIMERINT;
3089                         CSR_WRITE_4(sc, reg, 0);
3090                         CSR_READ_4(sc, reg); /* flush */
3091
3092                         CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
3093                         re_setup_sim_im(sc);
3094 #else
3095                         re_setup_intr(sc, 0, RE_IMTYPE_NONE);
3096                         DELAY(10);
3097                         re_setup_intr(sc, 1, RE_IMTYPE_SIM);
3098 #endif
3099                 }
3100         }
3101 back:
3102         lwkt_serialize_exit(ifp->if_serializer);
3103         return error;
3104 }
3105
3106 static int
3107 re_sysctl_imtype(SYSCTL_HANDLER_ARGS)
3108 {
3109         struct re_softc *sc = arg1;
3110         struct ifnet *ifp = &sc->arpcom.ac_if;
3111         int error, v;
3112
3113         lwkt_serialize_enter(ifp->if_serializer);
3114
3115         v = sc->re_imtype;
3116         error = sysctl_handle_int(oidp, &v, 0, req);
3117         if (error || req->newptr == NULL)
3118                 goto back;
3119
3120         if (v != RE_IMTYPE_HW && v != RE_IMTYPE_SIM && v != RE_IMTYPE_NONE) {
3121                 error = EINVAL;
3122                 goto back;
3123         }
3124         if (v == RE_IMTYPE_HW && (sc->re_caps & RE_C_HWIM) == 0) {
3125                 /* Can't do hardware interrupt moderation */
3126                 error = EOPNOTSUPP;
3127                 goto back;
3128         }
3129
3130         if (v != sc->re_imtype) {
3131                 sc->re_imtype = v;
3132                 if ((ifp->if_flags & (IFF_RUNNING | IFF_POLLING)) ==
3133                     IFF_RUNNING)
3134                         re_setup_intr(sc, 1, sc->re_imtype);
3135         }
3136 back:
3137         lwkt_serialize_exit(ifp->if_serializer);
3138         return error;
3139 }
3140
3141 static void
3142 re_setup_hw_im(struct re_softc *sc)
3143 {
3144         KKASSERT(sc->re_caps & RE_C_HWIM);
3145
3146         /*
3147          * Interrupt moderation
3148          *
3149          * 0xABCD
3150          * A - unknown (maybe TX related)
3151          * B - TX timer (unit: 25us)
3152          * C - unknown (maybe RX related)
3153          * D - RX timer (unit: 25us)
3154          *
3155          *
3156          * re(4)'s interrupt moderation is actually controlled by
3157          * two variables, like most other NICs (bge, bce etc.)
3158          * o  timer
3159          * o  number of packets [P]
3160          *
3161          * The logic relationship between these two variables is
3162          * similar to other NICs too:
3163          * if (timer expire || packets > [P])
3164          *     Interrupt is delivered
3165          *
3166          * Currently we only know how to set 'timer', but not
3167          * 'number of packets', which should be ~30, as far as I
3168          * tested (sink ~900Kpps, interrupt rate is 30KHz)
3169          */
3170         CSR_WRITE_2(sc, RE_IM,
3171                     RE_IM_RXTIME(sc->re_rx_time) |
3172                     RE_IM_TXTIME(sc->re_tx_time) |
3173                     RE_IM_MAGIC);
3174 }
3175
3176 static void
3177 re_disable_hw_im(struct re_softc *sc)
3178 {
3179         if (sc->re_caps & RE_C_HWIM)
3180                 CSR_WRITE_2(sc, RE_IM, 0);
3181 }
3182
3183 static void
3184 re_setup_sim_im(struct re_softc *sc)
3185 {
3186         if (!RE_IS_8139CP(sc)) {
3187                 uint32_t ticks;
3188
3189                 /*
3190                  * Datasheet says tick decreases at bus speed,
3191                  * but it seems the clock runs a little bit
3192                  * faster, so we do some compensation here.
3193                  */
3194                 ticks = (sc->re_sim_time * sc->re_bus_speed * 8) / 5;
3195                 CSR_WRITE_4(sc, RE_TIMERINT_8169, ticks);
3196         } else {
3197                 CSR_WRITE_4(sc, RE_TIMERINT, 0x400); /* XXX */
3198         }
3199         CSR_WRITE_4(sc, RE_TIMERCNT, 1); /* reload */
3200         sc->re_flags |= RE_F_TIMER_INTR;
3201 }
3202
3203 static void
3204 re_disable_sim_im(struct re_softc *sc)
3205 {
3206         if (!RE_IS_8139CP(sc))
3207                 CSR_WRITE_4(sc, RE_TIMERINT_8169, 0);
3208         else
3209                 CSR_WRITE_4(sc, RE_TIMERINT, 0);
3210         sc->re_flags &= ~RE_F_TIMER_INTR;
3211 }
3212
3213 static void
3214 re_config_imtype(struct re_softc *sc, int imtype)
3215 {
3216         switch (imtype) {
3217         case RE_IMTYPE_HW:
3218                 KKASSERT(sc->re_caps & RE_C_HWIM);
3219                 /* FALL THROUGH */
3220         case RE_IMTYPE_NONE:
3221                 sc->re_intrs = RE_INTRS;
3222                 sc->re_rx_ack = RE_ISR_RX_OK | RE_ISR_FIFO_OFLOW |
3223                                 RE_ISR_RX_OVERRUN;
3224                 sc->re_tx_ack = RE_ISR_TX_OK;
3225                 break;
3226
3227         case RE_IMTYPE_SIM:
3228                 sc->re_intrs = RE_INTRS_TIMER;
3229                 sc->re_rx_ack = RE_ISR_TIMEOUT_EXPIRED;
3230                 sc->re_tx_ack = RE_ISR_TIMEOUT_EXPIRED;
3231                 break;
3232
3233         default:
3234                 panic("%s: unknown imtype %d\n",
3235                       sc->arpcom.ac_if.if_xname, imtype);
3236         }
3237 }
3238
3239 static void
3240 re_setup_intr(struct re_softc *sc, int enable_intrs, int imtype)
3241 {
3242         re_config_imtype(sc, imtype);
3243
3244         if (enable_intrs)
3245                 CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
3246         else
3247                 CSR_WRITE_2(sc, RE_IMR, 0); 
3248
3249         switch (imtype) {
3250         case RE_IMTYPE_NONE:
3251                 re_disable_sim_im(sc);
3252                 re_disable_hw_im(sc);
3253                 break;
3254
3255         case RE_IMTYPE_HW:
3256                 KKASSERT(sc->re_caps & RE_C_HWIM);
3257                 re_disable_sim_im(sc);
3258                 re_setup_hw_im(sc);
3259                 break;
3260
3261         case RE_IMTYPE_SIM:
3262                 re_disable_hw_im(sc);
3263                 re_setup_sim_im(sc);
3264                 break;
3265
3266         default:
3267                 panic("%s: unknown imtype %d\n",
3268                       sc->arpcom.ac_if.if_xname, imtype);
3269         }
3270 }
3271
3272 static void
3273 re_get_eaddr(struct re_softc *sc, uint8_t *eaddr)
3274 {
3275         int i;
3276
3277         if (sc->re_macver == RE_MACVER_11 || sc->re_macver == RE_MACVER_12) {
3278                 uint16_t re_did;
3279
3280                 re_get_eewidth(sc);
3281                 re_read_eeprom(sc, (caddr_t)&re_did, 0, 1);
3282                 if (re_did == 0x8128) {
3283                         uint16_t as[ETHER_ADDR_LEN / 2];
3284
3285                         /*
3286                          * Get station address from the EEPROM.
3287                          */
3288                         re_read_eeprom(sc, (caddr_t)as, RE_EE_EADDR, 3);
3289                         for (i = 0; i < ETHER_ADDR_LEN / 2; i++)
3290                                 as[i] = le16toh(as[i]);
3291                         bcopy(as, eaddr, sizeof(eaddr));
3292                         return;
3293                 }
3294         }
3295
3296         /*
3297          * Get station address from IDRx.
3298          */
3299         for (i = 0; i < ETHER_ADDR_LEN; ++i)
3300                 eaddr[i] = CSR_READ_1(sc, RE_IDR0 + i);
3301 }