b47e6a463877450a474cade02a557eb033327a32
[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.83 2008/10/16 12:29:13 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         sc->re_rx_desc_cnt = re_rx_desc_count;
1316         if (sc->re_rx_desc_cnt > RE_RX_DESC_CNT_MAX)
1317                 sc->re_rx_desc_cnt = RE_RX_DESC_CNT_MAX;
1318
1319         sc->re_tx_desc_cnt = re_tx_desc_count;
1320         if (sc->re_tx_desc_cnt > RE_TX_DESC_CNT_MAX)
1321                 sc->re_tx_desc_cnt = RE_TX_DESC_CNT_MAX;
1322
1323         qlen = RE_IFQ_MAXLEN;
1324         if (sc->re_tx_desc_cnt > qlen)
1325                 qlen = sc->re_tx_desc_cnt;
1326
1327         sc->re_tx_time = 5;             /* 125us */
1328         sc->re_rx_time = 2;             /* 50us */
1329         sc->re_sim_time = 125;          /* 125us */
1330         sc->re_imtype = RE_IMTYPE_SIM;  /* simulated interrupt moderation */
1331         re_config_imtype(sc, sc->re_imtype);
1332
1333         sysctl_ctx_init(&sc->re_sysctl_ctx);
1334         sc->re_sysctl_tree = SYSCTL_ADD_NODE(&sc->re_sysctl_ctx,
1335                                              SYSCTL_STATIC_CHILDREN(_hw),
1336                                              OID_AUTO,
1337                                              device_get_nameunit(dev),
1338                                              CTLFLAG_RD, 0, "");
1339         if (sc->re_sysctl_tree == NULL) {
1340                 device_printf(dev, "can't add sysctl node\n");
1341                 error = ENXIO;
1342                 goto fail;
1343         }
1344         SYSCTL_ADD_INT(&sc->re_sysctl_ctx,
1345                        SYSCTL_CHILDREN(sc->re_sysctl_tree), OID_AUTO,
1346                        "rx_desc_count", CTLFLAG_RD, &sc->re_rx_desc_cnt,
1347                        0, "RX desc count");
1348         SYSCTL_ADD_INT(&sc->re_sysctl_ctx,
1349                        SYSCTL_CHILDREN(sc->re_sysctl_tree), OID_AUTO,
1350                        "tx_desc_count", CTLFLAG_RD, &sc->re_tx_desc_cnt,
1351                        0, "TX desc count");
1352         SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1353                         SYSCTL_CHILDREN(sc->re_sysctl_tree),
1354                         OID_AUTO, "sim_time",
1355                         CTLTYPE_INT | CTLFLAG_RW,
1356                         sc, 0, re_sysctl_simtime, "I",
1357                         "Simulated interrupt moderation time (usec).");
1358         SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1359                         SYSCTL_CHILDREN(sc->re_sysctl_tree),
1360                         OID_AUTO, "imtype",
1361                         CTLTYPE_INT | CTLFLAG_RW,
1362                         sc, 0, re_sysctl_imtype, "I",
1363                         "Interrupt moderation type -- "
1364                         "0:disable, 1:simulated, "
1365                         "2:hardware(if supported)");
1366         if (sc->re_caps & RE_C_HWIM) {
1367                 SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1368                                 SYSCTL_CHILDREN(sc->re_sysctl_tree),
1369                                 OID_AUTO, "hw_rxtime",
1370                                 CTLTYPE_INT | CTLFLAG_RW,
1371                                 sc, 0, re_sysctl_rxtime, "I",
1372                                 "Hardware interrupt moderation time "
1373                                 "(unit: 25usec).");
1374                 SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1375                                 SYSCTL_CHILDREN(sc->re_sysctl_tree),
1376                                 OID_AUTO, "hw_txtime",
1377                                 CTLTYPE_INT | CTLFLAG_RW,
1378                                 sc, 0, re_sysctl_txtime, "I",
1379                                 "Hardware interrupt moderation time "
1380                                 "(unit: 25usec).");
1381         }
1382
1383 #ifndef BURN_BRIDGES
1384         /*
1385          * Handle power management nonsense.
1386          */
1387
1388         if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
1389                 uint32_t membase, irq;
1390
1391                 /* Save important PCI config data. */
1392                 membase = pci_read_config(dev, RE_PCI_LOMEM, 4);
1393                 irq = pci_read_config(dev, PCIR_INTLINE, 4);
1394
1395                 /* Reset the power state. */
1396                 device_printf(dev, "chip is in D%d power mode "
1397                     "-- setting to D0\n", pci_get_powerstate(dev));
1398
1399                 pci_set_powerstate(dev, PCI_POWERSTATE_D0);
1400
1401                 /* Restore PCI config data. */
1402                 pci_write_config(dev, RE_PCI_LOMEM, membase, 4);
1403                 pci_write_config(dev, PCIR_INTLINE, irq, 4);
1404         }
1405 #endif
1406         /*
1407          * Map control/status registers.
1408          */
1409         pci_enable_busmaster(dev);
1410
1411         rid = RE_PCI_LOIO;
1412         sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
1413                                             RF_ACTIVE);
1414
1415         if (sc->re_res == NULL) {
1416                 device_printf(dev, "couldn't map ports\n");
1417                 error = ENXIO;
1418                 goto fail;
1419         }
1420
1421         sc->re_btag = rman_get_bustag(sc->re_res);
1422         sc->re_bhandle = rman_get_bushandle(sc->re_res);
1423
1424         /* Allocate interrupt */
1425         rid = 0;
1426         sc->re_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1427                                             RF_SHAREABLE | RF_ACTIVE);
1428
1429         if (sc->re_irq == NULL) {
1430                 device_printf(dev, "couldn't map interrupt\n");
1431                 error = ENXIO;
1432                 goto fail;
1433         }
1434
1435         /* Reset the adapter. */
1436         re_reset(sc);
1437
1438         expr_ptr = pci_get_pciecap_ptr(dev);
1439         if (expr_ptr != 0) {
1440                 uint16_t val;
1441
1442                 /*
1443                  * We will set TX DMA burst to "unlimited" in
1444                  * re_init(), so push "max read request size"
1445                  * to the limit.
1446                  */
1447                 val = pci_read_config(dev, expr_ptr + PCIER_DEVCTRL, 2);
1448                 if ((val & PCIEM_DEVCTL_MAX_READRQ_MASK) !=
1449                     PCIEM_DEVCTL_MAX_READRQ_4096) {
1450                         device_printf(dev, "adjust device control "
1451                                       "0x%04x ", val);
1452
1453                         val &= ~PCIEM_DEVCTL_MAX_READRQ_MASK;
1454                         val |= PCIEM_DEVCTL_MAX_READRQ_4096;
1455                         pci_write_config(dev, expr_ptr + PCIER_DEVCTRL,
1456                                          val, 2);
1457
1458                         kprintf("-> 0x%04x\n", val);
1459                 }
1460                 sc->re_caps |= RE_C_PCIE;
1461
1462                 /* Reduce the simulated interrupt moderation timer a bit */
1463                 sc->re_sim_time = 75; /* 75us */
1464         }
1465
1466         if (RE_IS_8139CP(sc)) {
1467                 sc->re_bus_speed = 33; /* XXX */
1468         } else if (sc->re_caps & RE_C_PCIE) {
1469                 sc->re_bus_speed = 125;
1470         } else {
1471                 uint8_t cfg2;
1472
1473                 cfg2 = CSR_READ_1(sc, RE_CFG2);
1474                 switch (cfg2 & RE_CFG2_PCICLK_MASK) {
1475                 case RE_CFG2_PCICLK_33MHZ:
1476                         sc->re_bus_speed = 33;
1477                         break;
1478                 case RE_CFG2_PCICLK_66MHZ:
1479                         sc->re_bus_speed = 66;
1480                         break;
1481                 default:
1482                         device_printf(dev, "unknown bus speed, assume 33MHz\n");
1483                         sc->re_bus_speed = 33;
1484                         break;
1485                 }
1486                 if (cfg2 & RE_CFG2_PCI64)
1487                         sc->re_caps |= RE_C_PCI64;
1488         }
1489         device_printf(dev, "Hardware rev. 0x%08x; MAC ver. 0x%02x; "
1490                       "PCI%s %dMHz\n",
1491                       sc->re_hwrev, sc->re_macver,
1492                       (sc->re_caps & RE_C_PCIE) ?
1493                       "-E" : ((sc->re_caps & RE_C_PCI64) ? "64" : "32"),
1494                       sc->re_bus_speed);
1495
1496         /*
1497          * NOTE:
1498          * DO NOT try to adjust config1 and config5 which was spotted in
1499          * Realtek's Linux drivers.  It will _permanently_ damage certain
1500          * cards EEPROM, e.g. one of my 8168B (0x38000000) card ...
1501          */
1502
1503         re_get_eaddr(sc, eaddr);
1504
1505         if (!RE_IS_8139CP(sc)) {
1506                 /* Set RX length mask */
1507                 sc->re_rxlenmask = RE_RDESC_STAT_GFRAGLEN;
1508                 sc->re_txstart = RE_GTXSTART;
1509         } else {
1510                 /* Set RX length mask */
1511                 sc->re_rxlenmask = RE_RDESC_STAT_FRAGLEN;
1512                 sc->re_txstart = RE_TXSTART;
1513         }
1514
1515         /* Allocate DMA stuffs */
1516         error = re_allocmem(dev);
1517         if (error)
1518                 goto fail;
1519
1520         /*
1521          * Apply some magic PCI settings from Realtek ...
1522          */
1523         if (sc->re_caps & RE_C_8169)
1524                 pci_write_config(dev, PCIR_CACHELNSZ, 0x8, 1);
1525         pci_write_config(dev, PCIR_LATTIMER, 0x40, 1);
1526
1527         if (sc->re_caps & RE_C_MAC2) {
1528                 /*
1529                  * Following part is extracted from Realtek BSD driver v176.
1530                  * However, this does _not_ make much/any sense:
1531                  * 8168C's PCI Express device control is located at 0x78,
1532                  * so the reading from 0x79 (higher part of 0x78) and setting
1533                  * the 4~6bits intend to enlarge the "max read request size"
1534                  * (we have done it).  The content of the rest part of this
1535                  * register is not meaningful to other PCI registers, so
1536                  * writing the value to 0x54 could be completely wrong.
1537                  * 0x80 is the lower part of PCI Express device status, non-
1538                  * reserved bits are RW1C, writing 0 to them will not have
1539                  * any effect at all.
1540                  */
1541 #ifdef foo
1542                 uint8_t val;
1543
1544                 val = pci_read_config(dev, 0x79, 1);
1545                 val = (val & ~0x70) | 0x50;
1546                 pci_write_config(dev, 0x54, val, 1);
1547                 pci_write_config(dev, 0x80, 0, 1);
1548 #endif
1549         }
1550
1551         /*
1552          * Apply some PHY fixup from Realtek ...
1553          */
1554         if (sc->re_hwrev == RE_HWREV_8110S) {
1555                 CSR_WRITE_1(sc, 0x82, 1);
1556                 re_miibus_writereg(dev, 1, 0xb, 0);
1557         }
1558         if (sc->re_caps & RE_C_PHYPMGT) {
1559                 /* Power up PHY */
1560                 re_miibus_writereg(dev, 1, 0x1f, 0);
1561                 re_miibus_writereg(dev, 1, 0xe, 0);
1562         }
1563
1564         /* Do MII setup */
1565         if (mii_phy_probe(dev, &sc->re_miibus,
1566             re_ifmedia_upd, re_ifmedia_sts)) {
1567                 device_printf(dev, "MII without any phy!\n");
1568                 error = ENXIO;
1569                 goto fail;
1570         }
1571
1572         ifp = &sc->arpcom.ac_if;
1573         ifp->if_softc = sc;
1574         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1575         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1576         ifp->if_ioctl = re_ioctl;
1577         ifp->if_start = re_start;
1578 #ifdef DEVICE_POLLING
1579         ifp->if_poll = re_poll;
1580 #endif
1581         ifp->if_watchdog = re_watchdog;
1582         ifp->if_init = re_init;
1583         if (!RE_IS_8139CP(sc)) /* XXX */
1584                 ifp->if_baudrate = 1000000000;
1585         else
1586                 ifp->if_baudrate = 100000000;
1587         ifq_set_maxlen(&ifp->if_snd, qlen);
1588         ifq_set_ready(&ifp->if_snd);
1589
1590         ifp->if_capabilities = IFCAP_VLAN_MTU | IFCAP_VLAN_HWTAGGING;
1591         if (sc->re_caps & RE_C_HWCSUM)
1592                 ifp->if_capabilities |= IFCAP_HWCSUM;
1593
1594         ifp->if_capenable = ifp->if_capabilities;
1595         if (ifp->if_capabilities & IFCAP_HWCSUM)
1596                 ifp->if_hwassist = RE_CSUM_FEATURES;
1597         else
1598                 ifp->if_hwassist = 0;
1599
1600         /*
1601          * Call MI attach routine.
1602          */
1603         ether_ifattach(ifp, eaddr, NULL);
1604
1605 #ifdef RE_DIAG
1606         /*
1607          * Perform hardware diagnostic on the original RTL8169.
1608          * Some 32-bit cards were incorrectly wired and would
1609          * malfunction if plugged into a 64-bit slot.
1610          */
1611         if (sc->re_hwrev == RE_HWREV_8169) {
1612                 lwkt_serialize_enter(ifp->if_serializer);
1613                 error = re_diag(sc);
1614                 lwkt_serialize_exit(ifp->if_serializer);
1615
1616                 if (error) {
1617                         device_printf(dev, "hardware diagnostic failure\n");
1618                         ether_ifdetach(ifp);
1619                         goto fail;
1620                 }
1621         }
1622 #endif  /* RE_DIAG */
1623
1624         /* Hook interrupt last to avoid having to lock softc */
1625         error = bus_setup_intr(dev, sc->re_irq, INTR_MPSAFE, re_intr, sc,
1626                                &sc->re_intrhand, ifp->if_serializer);
1627
1628         if (error) {
1629                 device_printf(dev, "couldn't set up irq\n");
1630                 ether_ifdetach(ifp);
1631                 goto fail;
1632         }
1633
1634         ifp->if_cpuid = ithread_cpuid(rman_get_start(sc->re_irq));
1635         KKASSERT(ifp->if_cpuid >= 0 && ifp->if_cpuid < ncpus);
1636
1637 fail:
1638         if (error)
1639                 re_detach(dev);
1640
1641         return (error);
1642 }
1643
1644 /*
1645  * Shutdown hardware and free up resources. This can be called any
1646  * time after the mutex has been initialized. It is called in both
1647  * the error case in attach and the normal detach case so it needs
1648  * to be careful about only freeing resources that have actually been
1649  * allocated.
1650  */
1651 static int
1652 re_detach(device_t dev)
1653 {
1654         struct re_softc *sc = device_get_softc(dev);
1655         struct ifnet *ifp = &sc->arpcom.ac_if;
1656
1657         /* These should only be active if attach succeeded */
1658         if (device_is_attached(dev)) {
1659                 lwkt_serialize_enter(ifp->if_serializer);
1660                 re_stop(sc);
1661                 bus_teardown_intr(dev, sc->re_irq, sc->re_intrhand);
1662                 lwkt_serialize_exit(ifp->if_serializer);
1663
1664                 ether_ifdetach(ifp);
1665         }
1666         if (sc->re_miibus)
1667                 device_delete_child(dev, sc->re_miibus);
1668         bus_generic_detach(dev);
1669
1670         if (sc->re_sysctl_tree != NULL)
1671                 sysctl_ctx_free(&sc->re_sysctl_ctx);
1672
1673         if (sc->re_irq)
1674                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->re_irq);
1675         if (sc->re_res) {
1676                 bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO,
1677                                      sc->re_res);
1678         }
1679
1680         /* Free DMA stuffs */
1681         re_freemem(dev);
1682
1683         return(0);
1684 }
1685
1686 static void
1687 re_setup_rxdesc(struct re_softc *sc, int idx)
1688 {
1689         bus_addr_t paddr;
1690         uint32_t cmdstat;
1691         struct re_desc *d;
1692
1693         paddr = sc->re_ldata.re_rx_paddr[idx];
1694         d = &sc->re_ldata.re_rx_list[idx];
1695
1696         d->re_bufaddr_lo = htole32(RE_ADDR_LO(paddr));
1697         d->re_bufaddr_hi = htole32(RE_ADDR_HI(paddr));
1698
1699         cmdstat = MCLBYTES | RE_RDESC_CMD_OWN;
1700         if (idx == (sc->re_rx_desc_cnt - 1))
1701                 cmdstat |= RE_TDESC_CMD_EOR;
1702         d->re_cmdstat = htole32(cmdstat);
1703 }
1704
1705 static int
1706 re_newbuf(struct re_softc *sc, int idx, int init)
1707 {
1708         struct re_dmaload_arg arg;
1709         bus_dma_segment_t seg;
1710         bus_dmamap_t map;
1711         struct mbuf *m;
1712         int error;
1713
1714         m = m_getcl(init ? MB_WAIT : MB_DONTWAIT, MT_DATA, M_PKTHDR);
1715         if (m == NULL) {
1716                 error = ENOBUFS;
1717
1718                 if (init) {
1719                         if_printf(&sc->arpcom.ac_if, "m_getcl failed\n");
1720                         return error;
1721                 } else {
1722                         goto back;
1723                 }
1724         }
1725         m->m_len = m->m_pkthdr.len = MCLBYTES;
1726
1727         /*
1728          * NOTE:
1729          * Some re(4) chips(e.g. RTL8101E) need address of the receive buffer
1730          * to be 8-byte aligned, so don't call m_adj(m, ETHER_ALIGN) here.
1731          */
1732
1733         arg.re_nsegs = 1;
1734         arg.re_segs = &seg;
1735         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag,
1736                                      sc->re_ldata.re_rx_spare, m,
1737                                      re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1738         if (error || arg.re_nsegs == 0) {
1739                 if (!error) {
1740                         if_printf(&sc->arpcom.ac_if, "too many segments?!\n");
1741                         bus_dmamap_unload(sc->re_ldata.re_mtag,
1742                                           sc->re_ldata.re_rx_spare);
1743                         error = EFBIG;
1744                 }
1745                 m_freem(m);
1746
1747                 if (init) {
1748                         if_printf(&sc->arpcom.ac_if, "can't load RX mbuf\n");
1749                         return error;
1750                 } else {
1751                         goto back;
1752                 }
1753         }
1754
1755         if (!init) {
1756                 bus_dmamap_sync(sc->re_ldata.re_mtag,
1757                                 sc->re_ldata.re_rx_dmamap[idx],
1758                                 BUS_DMASYNC_POSTREAD);
1759                 bus_dmamap_unload(sc->re_ldata.re_mtag,
1760                                   sc->re_ldata.re_rx_dmamap[idx]);
1761         }
1762         sc->re_ldata.re_rx_mbuf[idx] = m;
1763         sc->re_ldata.re_rx_paddr[idx] = seg.ds_addr;
1764
1765         map = sc->re_ldata.re_rx_dmamap[idx];
1766         sc->re_ldata.re_rx_dmamap[idx] = sc->re_ldata.re_rx_spare;
1767         sc->re_ldata.re_rx_spare = map;
1768 back:
1769         re_setup_rxdesc(sc, idx);
1770         return error;
1771 }
1772
1773 static int
1774 re_tx_list_init(struct re_softc *sc)
1775 {
1776         bzero(sc->re_ldata.re_tx_list, RE_TX_LIST_SZ(sc));
1777
1778         /* Flush the TX descriptors */
1779         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1780                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
1781
1782         sc->re_ldata.re_tx_prodidx = 0;
1783         sc->re_ldata.re_tx_considx = 0;
1784         sc->re_ldata.re_tx_free = sc->re_tx_desc_cnt;
1785
1786         return(0);
1787 }
1788
1789 static int
1790 re_rx_list_init(struct re_softc *sc)
1791 {
1792         int i, error;
1793
1794         bzero(sc->re_ldata.re_rx_list, RE_RX_LIST_SZ(sc));
1795
1796         for (i = 0; i < sc->re_rx_desc_cnt; i++) {
1797                 error = re_newbuf(sc, i, 1);
1798                 if (error)
1799                         return(error);
1800         }
1801
1802         /* Flush the RX descriptors */
1803         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1804                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
1805
1806         sc->re_ldata.re_rx_prodidx = 0;
1807         sc->re_head = sc->re_tail = NULL;
1808
1809         return(0);
1810 }
1811
1812 #define RE_IP4_PACKET   0x1
1813 #define RE_TCP_PACKET   0x2
1814 #define RE_UDP_PACKET   0x4
1815
1816 static __inline uint8_t
1817 re_packet_type(struct re_softc *sc, uint32_t rxstat, uint32_t rxctrl)
1818 {
1819         uint8_t packet_type = 0;
1820
1821         if (sc->re_caps & RE_C_MAC2) {
1822                 if (rxctrl & RE_RDESC_CTL_PROTOIP4)
1823                         packet_type |= RE_IP4_PACKET;
1824         } else {
1825                 if (rxstat & RE_RDESC_STAT_PROTOID)
1826                         packet_type |= RE_IP4_PACKET;
1827         }
1828         if (RE_TCPPKT(rxstat))
1829                 packet_type |= RE_TCP_PACKET;
1830         else if (RE_UDPPKT(rxstat))
1831                 packet_type |= RE_UDP_PACKET;
1832         return packet_type;
1833 }
1834
1835 /*
1836  * RX handler for C+ and 8169. For the gigE chips, we support
1837  * the reception of jumbo frames that have been fragmented
1838  * across multiple 2K mbuf cluster buffers.
1839  */
1840 static int
1841 re_rxeof(struct re_softc *sc)
1842 {
1843         struct ifnet *ifp = &sc->arpcom.ac_if;
1844         struct mbuf *m;
1845         struct re_desc  *cur_rx;
1846         uint32_t rxstat, rxctrl;
1847         int i, total_len, rx = 0;
1848         struct mbuf_chain chain[MAXCPU];
1849
1850         /* Invalidate the descriptor memory */
1851
1852         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1853                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
1854
1855         ether_input_chain_init(chain);
1856
1857         for (i = sc->re_ldata.re_rx_prodidx;
1858              RE_OWN(&sc->re_ldata.re_rx_list[i]) == 0; RE_RXDESC_INC(sc, i)) {
1859                 cur_rx = &sc->re_ldata.re_rx_list[i];
1860                 m = sc->re_ldata.re_rx_mbuf[i];
1861                 total_len = RE_RXBYTES(cur_rx);
1862                 rxstat = le32toh(cur_rx->re_cmdstat);
1863                 rxctrl = le32toh(cur_rx->re_control);
1864
1865                 rx = 1;
1866
1867                 if ((rxstat & RE_RDESC_STAT_EOF) == 0) {
1868                         if (sc->re_drop_rxfrag) {
1869                                 re_setup_rxdesc(sc, i);
1870                                 continue;
1871                         }
1872
1873                         if (re_newbuf(sc, i, 0)) {
1874                                 /* Drop upcoming fragments */
1875                                 sc->re_drop_rxfrag = 1;
1876                                 continue;
1877                         }
1878
1879                         m->m_len = MCLBYTES;
1880                         if (sc->re_head == NULL) {
1881                                 sc->re_head = sc->re_tail = m;
1882                         } else {
1883                                 sc->re_tail->m_next = m;
1884                                 sc->re_tail = m;
1885                         }
1886                         continue;
1887                 } else if (sc->re_drop_rxfrag) {
1888                         /*
1889                          * Last fragment of a multi-fragment packet.
1890                          *
1891                          * Since error already happened, this fragment
1892                          * must be dropped as well as the fragment chain.
1893                          */
1894                         re_setup_rxdesc(sc, i);
1895                         re_free_rxchain(sc);
1896                         sc->re_drop_rxfrag = 0;
1897                         continue;
1898                 }
1899
1900                 /*
1901                  * NOTE: for the 8139C+, the frame length field
1902                  * is always 12 bits in size, but for the gigE chips,
1903                  * it is 13 bits (since the max RX frame length is 16K).
1904                  * Unfortunately, all 32 bits in the status word
1905                  * were already used, so to make room for the extra
1906                  * length bit, RealTek took out the 'frame alignment
1907                  * error' bit and shifted the other status bits
1908                  * over one slot. The OWN, EOR, FS and LS bits are
1909                  * still in the same places. We have already extracted
1910                  * the frame length and checked the OWN bit, so rather
1911                  * than using an alternate bit mapping, we shift the
1912                  * status bits one space to the right so we can evaluate
1913                  * them using the 8169 status as though it was in the
1914                  * same format as that of the 8139C+.
1915                  */
1916                 if (!RE_IS_8139CP(sc))
1917                         rxstat >>= 1;
1918
1919                 if (rxstat & RE_RDESC_STAT_RXERRSUM) {
1920                         ifp->if_ierrors++;
1921                         /*
1922                          * If this is part of a multi-fragment packet,
1923                          * discard all the pieces.
1924                          */
1925                         re_free_rxchain(sc);
1926                         re_setup_rxdesc(sc, i);
1927                         continue;
1928                 }
1929
1930                 /*
1931                  * If allocating a replacement mbuf fails,
1932                  * reload the current one.
1933                  */
1934
1935                 if (re_newbuf(sc, i, 0)) {
1936                         ifp->if_ierrors++;
1937                         re_free_rxchain(sc);
1938                         continue;
1939                 }
1940
1941                 if (sc->re_head != NULL) {
1942                         m->m_len = total_len % MCLBYTES;
1943                         /* 
1944                          * Special case: if there's 4 bytes or less
1945                          * in this buffer, the mbuf can be discarded:
1946                          * the last 4 bytes is the CRC, which we don't
1947                          * care about anyway.
1948                          */
1949                         if (m->m_len <= ETHER_CRC_LEN) {
1950                                 sc->re_tail->m_len -=
1951                                     (ETHER_CRC_LEN - m->m_len);
1952                                 m_freem(m);
1953                         } else {
1954                                 m->m_len -= ETHER_CRC_LEN;
1955                                 sc->re_tail->m_next = m;
1956                         }
1957                         m = sc->re_head;
1958                         sc->re_head = sc->re_tail = NULL;
1959                         m->m_pkthdr.len = total_len - ETHER_CRC_LEN;
1960                 } else {
1961                         m->m_pkthdr.len = m->m_len =
1962                             (total_len - ETHER_CRC_LEN);
1963                 }
1964
1965                 ifp->if_ipackets++;
1966                 m->m_pkthdr.rcvif = ifp;
1967
1968                 /* Do RX checksumming if enabled */
1969
1970                 if (ifp->if_capenable & IFCAP_RXCSUM) {
1971                         uint8_t packet_type;
1972
1973                         packet_type = re_packet_type(sc, rxstat, rxctrl);
1974
1975                         /* Check IP header checksum */
1976                         if (packet_type & RE_IP4_PACKET) {
1977                                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
1978                                 if ((rxstat & RE_RDESC_STAT_IPSUMBAD) == 0)
1979                                         m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1980                         }
1981
1982                         /* Check TCP/UDP checksum */
1983                         if (((packet_type & RE_TCP_PACKET) &&
1984                              (rxstat & RE_RDESC_STAT_TCPSUMBAD) == 0) ||
1985                             ((packet_type & RE_UDP_PACKET) &&
1986                              (rxstat & RE_RDESC_STAT_UDPSUMBAD) == 0)) {
1987                                 m->m_pkthdr.csum_flags |=
1988                                     CSUM_DATA_VALID|CSUM_PSEUDO_HDR|
1989                                     CSUM_FRAG_NOT_CHECKED;
1990                                 m->m_pkthdr.csum_data = 0xffff;
1991                         }
1992                 }
1993
1994                 if (rxctrl & RE_RDESC_CTL_HASTAG) {
1995                         m->m_flags |= M_VLANTAG;
1996                         m->m_pkthdr.ether_vlantag =
1997                                 be16toh((rxctrl & RE_RDESC_CTL_TAGDATA));
1998                 }
1999                 ether_input_chain(ifp, m, chain);
2000         }
2001
2002         ether_input_dispatch(chain);
2003
2004         /* Flush the RX DMA ring */
2005
2006         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
2007                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
2008
2009         sc->re_ldata.re_rx_prodidx = i;
2010
2011         return rx;
2012 }
2013
2014 #undef RE_IP4_PACKET
2015 #undef RE_TCP_PACKET
2016 #undef RE_UDP_PACKET
2017
2018 static int
2019 re_txeof(struct re_softc *sc)
2020 {
2021         struct ifnet *ifp = &sc->arpcom.ac_if;
2022         uint32_t txstat;
2023         int idx, tx = 0;
2024
2025         /* Invalidate the TX descriptor list */
2026
2027         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
2028                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_POSTREAD);
2029
2030         for (idx = sc->re_ldata.re_tx_considx;
2031              sc->re_ldata.re_tx_free < sc->re_tx_desc_cnt;
2032              RE_TXDESC_INC(sc, idx)) {
2033                 txstat = le32toh(sc->re_ldata.re_tx_list[idx].re_cmdstat);
2034                 if (txstat & RE_TDESC_CMD_OWN)
2035                         break;
2036
2037                 tx = 1;
2038
2039                 sc->re_ldata.re_tx_list[idx].re_bufaddr_lo = 0;
2040
2041                 /*
2042                  * We only stash mbufs in the last descriptor
2043                  * in a fragment chain, which also happens to
2044                  * be the only place where the TX status bits
2045                  * are valid.
2046                  */
2047                 if (txstat & RE_TDESC_CMD_EOF) {
2048                         m_freem(sc->re_ldata.re_tx_mbuf[idx]);
2049                         sc->re_ldata.re_tx_mbuf[idx] = NULL;
2050                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2051                             sc->re_ldata.re_tx_dmamap[idx]);
2052                         if (txstat & (RE_TDESC_STAT_EXCESSCOL|
2053                             RE_TDESC_STAT_COLCNT))
2054                                 ifp->if_collisions++;
2055                         if (txstat & RE_TDESC_STAT_TXERRSUM)
2056                                 ifp->if_oerrors++;
2057                         else
2058                                 ifp->if_opackets++;
2059                 }
2060                 sc->re_ldata.re_tx_free++;
2061         }
2062         sc->re_ldata.re_tx_considx = idx;
2063
2064         /* There is enough free TX descs */
2065         if (sc->re_ldata.re_tx_free > RE_TXDESC_SPARE)
2066                 ifp->if_flags &= ~IFF_OACTIVE;
2067
2068         /*
2069          * Some chips will ignore a second TX request issued while an
2070          * existing transmission is in progress. If the transmitter goes
2071          * idle but there are still packets waiting to be sent, we need
2072          * to restart the channel here to flush them out. This only seems
2073          * to be required with the PCIe devices.
2074          */
2075         if (sc->re_ldata.re_tx_free < sc->re_tx_desc_cnt)
2076                 CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
2077         else
2078                 ifp->if_timer = 0;
2079
2080         return tx;
2081 }
2082
2083 static void
2084 re_tick(void *xsc)
2085 {
2086         struct re_softc *sc = xsc;
2087
2088         lwkt_serialize_enter(sc->arpcom.ac_if.if_serializer);
2089         re_tick_serialized(xsc);
2090         lwkt_serialize_exit(sc->arpcom.ac_if.if_serializer);
2091 }
2092
2093 static void
2094 re_tick_serialized(void *xsc)
2095 {
2096         struct re_softc *sc = xsc;
2097         struct ifnet *ifp = &sc->arpcom.ac_if;
2098         struct mii_data *mii;
2099
2100         ASSERT_SERIALIZED(ifp->if_serializer);
2101
2102         mii = device_get_softc(sc->re_miibus);
2103         mii_tick(mii);
2104         if (sc->re_link) {
2105                 if (!(mii->mii_media_status & IFM_ACTIVE))
2106                         sc->re_link = 0;
2107         } else {
2108                 if (mii->mii_media_status & IFM_ACTIVE &&
2109                     IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) {
2110                         sc->re_link = 1;
2111                         if (!ifq_is_empty(&ifp->if_snd))
2112                                 if_devstart(ifp);
2113                 }
2114         }
2115
2116         callout_reset(&sc->re_timer, hz, re_tick, sc);
2117 }
2118
2119 #ifdef DEVICE_POLLING
2120
2121 static void
2122 re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
2123 {
2124         struct re_softc *sc = ifp->if_softc;
2125
2126         ASSERT_SERIALIZED(ifp->if_serializer);
2127
2128         switch(cmd) {
2129         case POLL_REGISTER:
2130                 /* disable interrupts */
2131                 re_setup_intr(sc, 0, RE_IMTYPE_NONE);
2132                 break;
2133
2134         case POLL_DEREGISTER:
2135                 /* enable interrupts */
2136                 re_setup_intr(sc, 1, sc->re_imtype);
2137                 break;
2138
2139         default:
2140                 sc->rxcycles = count;
2141                 re_rxeof(sc);
2142                 re_txeof(sc);
2143
2144                 if (!ifq_is_empty(&ifp->if_snd))
2145                         if_devstart(ifp);
2146
2147                 if (cmd == POLL_AND_CHECK_STATUS) { /* also check status register */
2148                         uint16_t       status;
2149
2150                         status = CSR_READ_2(sc, RE_ISR);
2151                         if (status == 0xffff)
2152                                 return;
2153                         if (status)
2154                                 CSR_WRITE_2(sc, RE_ISR, status);
2155
2156                         /*
2157                          * XXX check behaviour on receiver stalls.
2158                          */
2159
2160                         if (status & RE_ISR_SYSTEM_ERR) {
2161                                 re_reset(sc);
2162                                 re_init(sc);
2163                         }
2164                 }
2165                 break;
2166         }
2167 }
2168 #endif /* DEVICE_POLLING */
2169
2170 static void
2171 re_intr(void *arg)
2172 {
2173         struct re_softc *sc = arg;
2174         struct ifnet *ifp = &sc->arpcom.ac_if;
2175         uint16_t status;
2176         int rx, tx;
2177
2178         ASSERT_SERIALIZED(ifp->if_serializer);
2179
2180         if (sc->suspended || (ifp->if_flags & IFF_RUNNING) == 0)
2181                 return;
2182
2183         rx = tx = 0;
2184         for (;;) {
2185                 status = CSR_READ_2(sc, RE_ISR);
2186                 /* If the card has gone away the read returns 0xffff. */
2187                 if (status == 0xffff)
2188                         break;
2189                 if (status)
2190                         CSR_WRITE_2(sc, RE_ISR, status);
2191
2192                 if ((status & sc->re_intrs) == 0)
2193                         break;
2194
2195                 if (status & (sc->re_rx_ack | RE_ISR_RX_ERR))
2196                         rx |= re_rxeof(sc);
2197
2198                 if (status & (sc->re_tx_ack | RE_ISR_TX_ERR))
2199                         tx |= re_txeof(sc);
2200
2201                 if (status & RE_ISR_SYSTEM_ERR) {
2202                         re_reset(sc);
2203                         re_init(sc);
2204                 }
2205
2206                 if (status & RE_ISR_LINKCHG) {
2207                         callout_stop(&sc->re_timer);
2208                         re_tick_serialized(sc);
2209                 }
2210         }
2211
2212         if (sc->re_imtype == RE_IMTYPE_SIM) {
2213                 if ((sc->re_flags & RE_F_TIMER_INTR)) {
2214                         if ((tx | rx) == 0)
2215                                 re_setup_intr(sc, 1, RE_IMTYPE_NONE);
2216                         else
2217                                 CSR_WRITE_4(sc, RE_TIMERCNT, 1); /* reload */
2218                 } else if (tx | rx) {
2219                         re_setup_intr(sc, 1, RE_IMTYPE_SIM);
2220                 }
2221         }
2222
2223         if (tx && !ifq_is_empty(&ifp->if_snd))
2224                 if_devstart(ifp);
2225 }
2226
2227 static int
2228 re_encap(struct re_softc *sc, struct mbuf **m_head, int *idx0)
2229 {
2230         struct ifnet *ifp = &sc->arpcom.ac_if;
2231         struct mbuf *m;
2232         struct re_dmaload_arg arg;
2233         bus_dma_segment_t segs[RE_MAXSEGS];
2234         bus_dmamap_t map;
2235         int error, maxsegs, idx, i;
2236         struct re_desc *d, *tx_ring;
2237         uint32_t cmd_csum, ctl_csum;
2238
2239         KASSERT(sc->re_ldata.re_tx_free > RE_TXDESC_SPARE,
2240                 ("not enough free TX desc\n"));
2241
2242         m = *m_head;
2243         map = sc->re_ldata.re_tx_dmamap[*idx0];
2244
2245         /*
2246          * Set up checksum offload. Note: checksum offload bits must
2247          * appear in all descriptors of a multi-descriptor transmit
2248          * attempt. (This is according to testing done with an 8169
2249          * chip. I'm not sure if this is a requirement or a bug.)
2250          */
2251         cmd_csum = ctl_csum = 0;
2252         if (m->m_pkthdr.csum_flags & CSUM_IP) {
2253                 cmd_csum |= RE_TDESC_CMD_IPCSUM;
2254                 ctl_csum |= RE_TDESC_CTL_IPCSUM;
2255         }
2256         if (m->m_pkthdr.csum_flags & CSUM_TCP) {
2257                 cmd_csum |= RE_TDESC_CMD_TCPCSUM;
2258                 ctl_csum |= RE_TDESC_CTL_TCPCSUM;
2259         }
2260         if (m->m_pkthdr.csum_flags & CSUM_UDP) {
2261                 cmd_csum |= RE_TDESC_CMD_UDPCSUM;
2262                 ctl_csum |= RE_TDESC_CTL_UDPCSUM;
2263         }
2264
2265         /* For MAC2 chips, csum flags are set on re_control */
2266         if (sc->re_caps & RE_C_MAC2)
2267                 cmd_csum = 0;
2268         else
2269                 ctl_csum = 0;
2270
2271         if (m->m_pkthdr.len > sc->re_swcsum_lim &&
2272             (m->m_pkthdr.csum_flags & (CSUM_DELAY_IP | CSUM_DELAY_DATA))) {
2273                 struct ether_header *eh;
2274                 struct ip *ip;
2275                 u_short offset;
2276
2277                 m = m_pullup(m, sizeof(struct ether_header *));
2278                 if (m == NULL) {
2279                         *m_head = NULL;
2280                         return ENOBUFS;
2281                 }
2282                 eh = mtod(m, struct ether_header *);
2283
2284                 /* XXX */
2285                 if (eh->ether_type == ETHERTYPE_VLAN)
2286                         offset = sizeof(struct ether_vlan_header);
2287                 else
2288                         offset = sizeof(struct ether_header);
2289
2290                 m = m_pullup(m, offset + sizeof(struct ip *));
2291                 if (m == NULL) {
2292                         *m_head = NULL;
2293                         return ENOBUFS;
2294                 }
2295                 ip = (struct ip *)(mtod(m, uint8_t *) + offset);
2296
2297                 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2298                         u_short csum;
2299
2300                         offset += IP_VHL_HL(ip->ip_vhl) << 2;
2301                         csum = in_cksum_skip(m, ntohs(ip->ip_len), offset);
2302                         if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
2303                                 csum = 0xffff;
2304                         offset += m->m_pkthdr.csum_data;        /* checksum offset */
2305                         *(u_short *)(m->m_data + offset) = csum;
2306
2307                         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2308                 }
2309                 if (m->m_pkthdr.csum_flags & CSUM_DELAY_IP) {
2310                         ip->ip_sum = 0;
2311                         if (ip->ip_vhl == IP_VHL_BORING) {
2312                                 ip->ip_sum = in_cksum_hdr(ip);
2313                         } else {
2314                                 ip->ip_sum =
2315                                 in_cksum(m, IP_VHL_HL(ip->ip_vhl) << 2);
2316                         }
2317                         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_IP;
2318                 }
2319                 *m_head = m; /* 'm' may be changed by above two m_pullup() */
2320
2321                 /* Clear hardware CSUM flags */
2322                 cmd_csum = ctl_csum = 0;
2323         }
2324
2325         if ((sc->re_caps & RE_C_AUTOPAD) == 0) {
2326                 /*
2327                  * With some of the RealTek chips, using the checksum offload
2328                  * support in conjunction with the autopadding feature results
2329                  * in the transmission of corrupt frames. For example, if we
2330                  * need to send a really small IP fragment that's less than 60
2331                  * bytes in size, and IP header checksumming is enabled, the
2332                  * resulting ethernet frame that appears on the wire will
2333                  * have garbled payload. To work around this, if TX checksum
2334                  * offload is enabled, we always manually pad short frames out
2335                  * to the minimum ethernet frame size.
2336                  *
2337                  * Note: this appears unnecessary for TCP, and doing it for TCP
2338                  * with PCIe adapters seems to result in bad checksums.
2339                  */
2340                 if ((m->m_pkthdr.csum_flags &
2341                      (CSUM_DELAY_IP | CSUM_DELAY_DATA)) &&
2342                     (m->m_pkthdr.csum_flags & CSUM_TCP) == 0 &&
2343                     m->m_pkthdr.len < RE_MIN_FRAMELEN) {
2344                         error = re_pad_frame(m);
2345                         if (error)
2346                                 goto back;
2347                 }
2348         }
2349
2350         maxsegs = sc->re_ldata.re_tx_free;
2351         if (maxsegs > RE_MAXSEGS)
2352                 maxsegs = RE_MAXSEGS;
2353
2354         arg.re_nsegs = maxsegs;
2355         arg.re_segs = segs;
2356         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map, m,
2357                                      re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
2358         if (error && error != EFBIG) {
2359                 if_printf(ifp, "can't map mbuf (error %d)\n", error);
2360                 goto back;
2361         }
2362
2363         /*
2364          * Too many segments to map, coalesce into a single mbuf
2365          */
2366         if (!error && arg.re_nsegs == 0) {
2367                 bus_dmamap_unload(sc->re_ldata.re_mtag, map);
2368                 error = EFBIG;
2369         }
2370         if (error) {
2371                 struct mbuf *m_new;
2372
2373                 m_new = m_defrag(m, MB_DONTWAIT);
2374                 if (m_new == NULL) {
2375                         if_printf(ifp, "can't defrag TX mbuf\n");
2376                         error = ENOBUFS;
2377                         goto back;
2378                 } else {
2379                         *m_head = m = m_new;
2380                 }
2381
2382                 arg.re_nsegs = maxsegs;
2383                 arg.re_segs = segs;
2384                 error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map, m,
2385                                              re_dma_map_desc, &arg,
2386                                              BUS_DMA_NOWAIT);
2387                 if (error || arg.re_nsegs == 0) {
2388                         if (!error) {
2389                                 bus_dmamap_unload(sc->re_ldata.re_mtag, map);
2390                                 error = EFBIG;
2391                         }
2392                         if_printf(ifp, "can't map mbuf (error %d)\n", error);
2393                         goto back;
2394                 }
2395         }
2396         bus_dmamap_sync(sc->re_ldata.re_mtag, map, BUS_DMASYNC_PREWRITE);
2397
2398         /*
2399          * Map the segment array into descriptors.  We also keep track
2400          * of the end of the ring and set the end-of-ring bits as needed,
2401          * and we set the ownership bits in all except the very first
2402          * descriptor, whose ownership bits will be turned on later.
2403          */
2404         tx_ring = sc->re_ldata.re_tx_list;
2405         idx = *idx0;
2406         i = 0;
2407         for (;;) {
2408                 uint32_t cmdstat;
2409
2410                 d = &tx_ring[idx];
2411
2412                 cmdstat = segs[i].ds_len;
2413                 d->re_bufaddr_lo = htole32(RE_ADDR_LO(segs[i].ds_addr));
2414                 d->re_bufaddr_hi = htole32(RE_ADDR_HI(segs[i].ds_addr));
2415                 if (i == 0)
2416                         cmdstat |= RE_TDESC_CMD_SOF;
2417                 else
2418                         cmdstat |= RE_TDESC_CMD_OWN;
2419                 if (idx == (sc->re_tx_desc_cnt - 1))
2420                         cmdstat |= RE_TDESC_CMD_EOR;
2421                 d->re_cmdstat = htole32(cmdstat | cmd_csum);
2422                 d->re_control = htole32(ctl_csum);
2423
2424                 i++;
2425                 if (i == arg.re_nsegs)
2426                         break;
2427                 RE_TXDESC_INC(sc, idx);
2428         }
2429         d->re_cmdstat |= htole32(RE_TDESC_CMD_EOF);
2430
2431         /*
2432          * Set up hardware VLAN tagging. Note: vlan tag info must
2433          * appear in the first descriptor of a multi-descriptor
2434          * transmission attempt.
2435          */
2436         if (m->m_flags & M_VLANTAG) {
2437                 tx_ring[*idx0].re_control |=
2438                     htole32(htobe16(m->m_pkthdr.ether_vlantag) |
2439                             RE_TDESC_CTL_INSTAG);
2440         }
2441
2442         /* Transfer ownership of packet to the chip. */
2443         d->re_cmdstat |= htole32(RE_TDESC_CMD_OWN);
2444         if (*idx0 != idx)
2445                 tx_ring[*idx0].re_cmdstat |= htole32(RE_TDESC_CMD_OWN);
2446
2447         /*
2448          * Insure that the map for this transmission
2449          * is placed at the array index of the last descriptor
2450          * in this chain.
2451          */
2452         sc->re_ldata.re_tx_dmamap[*idx0] = sc->re_ldata.re_tx_dmamap[idx];
2453         sc->re_ldata.re_tx_dmamap[idx] = map;
2454
2455         sc->re_ldata.re_tx_mbuf[idx] = m;
2456         sc->re_ldata.re_tx_free -= arg.re_nsegs;
2457
2458         RE_TXDESC_INC(sc, idx);
2459         *idx0 = idx;
2460 back:
2461         if (error) {
2462                 m_freem(m);
2463                 *m_head = NULL;
2464         }
2465         return error;
2466 }
2467
2468 /*
2469  * Main transmit routine for C+ and gigE NICs.
2470  */
2471
2472 static void
2473 re_start(struct ifnet *ifp)
2474 {
2475         struct re_softc *sc = ifp->if_softc;
2476         struct mbuf *m_head;
2477         int idx, need_trans;
2478
2479         ASSERT_SERIALIZED(ifp->if_serializer);
2480
2481         if (!sc->re_link) {
2482                 ifq_purge(&ifp->if_snd);
2483                 return;
2484         }
2485
2486         if ((ifp->if_flags & (IFF_OACTIVE | IFF_RUNNING)) != IFF_RUNNING)
2487                 return;
2488
2489         idx = sc->re_ldata.re_tx_prodidx;
2490
2491         need_trans = 0;
2492         while (sc->re_ldata.re_tx_mbuf[idx] == NULL) {
2493                 if (sc->re_ldata.re_tx_free <= RE_TXDESC_SPARE) {
2494                         ifp->if_flags |= IFF_OACTIVE;
2495                         break;
2496                 }
2497
2498                 m_head = ifq_dequeue(&ifp->if_snd, NULL);
2499                 if (m_head == NULL)
2500                         break;
2501
2502                 if (re_encap(sc, &m_head, &idx)) {
2503                         /* m_head is freed by re_encap(), if we reach here */
2504                         ifp->if_oerrors++;
2505                         ifp->if_flags |= IFF_OACTIVE;
2506                         break;
2507                 }
2508
2509                 need_trans = 1;
2510
2511                 /*
2512                  * If there's a BPF listener, bounce a copy of this frame
2513                  * to him.
2514                  */
2515                 ETHER_BPF_MTAP(ifp, m_head);
2516         }
2517
2518         if (!need_trans)
2519                 return;
2520
2521         /* Flush the TX descriptors */
2522         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
2523                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
2524
2525         sc->re_ldata.re_tx_prodidx = idx;
2526
2527         /*
2528          * RealTek put the TX poll request register in a different
2529          * location on the 8169 gigE chip. I don't know why.
2530          */
2531         CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
2532
2533         /*
2534          * Set a timeout in case the chip goes out to lunch.
2535          */
2536         ifp->if_timer = 5;
2537 }
2538
2539 static void
2540 re_init(void *xsc)
2541 {
2542         struct re_softc *sc = xsc;
2543         struct ifnet *ifp = &sc->arpcom.ac_if;
2544         struct mii_data *mii;
2545         uint32_t rxcfg = 0;
2546         int error, framelen;
2547
2548         ASSERT_SERIALIZED(ifp->if_serializer);
2549
2550         mii = device_get_softc(sc->re_miibus);
2551
2552         /*
2553          * Cancel pending I/O and free all RX/TX buffers.
2554          */
2555         re_stop(sc);
2556
2557         /*
2558          * Enable C+ RX and TX mode, as well as VLAN stripping and
2559          * RX checksum offload. We must configure the C+ register
2560          * before all others.
2561          */
2562         CSR_WRITE_2(sc, RE_CPLUS_CMD, RE_CPLUSCMD_RXENB | RE_CPLUSCMD_TXENB |
2563                     RE_CPLUSCMD_PCI_MRW | RE_CPLUSCMD_VLANSTRIP |
2564                     (ifp->if_capenable & IFCAP_RXCSUM ?
2565                      RE_CPLUSCMD_RXCSUM_ENB : 0));
2566
2567         /*
2568          * Init our MAC address.  Even though the chipset
2569          * documentation doesn't mention it, we need to enter "Config
2570          * register write enable" mode to modify the ID registers.
2571          */
2572         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_WRITECFG);
2573         CSR_WRITE_4(sc, RE_IDR0,
2574             htole32(*(uint32_t *)(&sc->arpcom.ac_enaddr[0])));
2575         CSR_WRITE_2(sc, RE_IDR4,
2576             htole16(*(uint16_t *)(&sc->arpcom.ac_enaddr[4])));
2577         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_OFF);
2578
2579         /*
2580          * For C+ mode, initialize the RX descriptors and mbufs.
2581          */
2582         error = re_rx_list_init(sc);
2583         if (error) {
2584                 re_stop(sc);
2585                 return;
2586         }
2587         error = re_tx_list_init(sc);
2588         if (error) {
2589                 re_stop(sc);
2590                 return;
2591         }
2592
2593         /*
2594          * Load the addresses of the RX and TX lists into the chip.
2595          */
2596         CSR_WRITE_4(sc, RE_RXLIST_ADDR_HI,
2597             RE_ADDR_HI(sc->re_ldata.re_rx_list_addr));
2598         CSR_WRITE_4(sc, RE_RXLIST_ADDR_LO,
2599             RE_ADDR_LO(sc->re_ldata.re_rx_list_addr));
2600
2601         CSR_WRITE_4(sc, RE_TXLIST_ADDR_HI,
2602             RE_ADDR_HI(sc->re_ldata.re_tx_list_addr));
2603         CSR_WRITE_4(sc, RE_TXLIST_ADDR_LO,
2604             RE_ADDR_LO(sc->re_ldata.re_tx_list_addr));
2605
2606         /*
2607          * Enable transmit and receive.
2608          */
2609         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2610
2611         /*
2612          * Set the initial TX and RX configuration.
2613          */
2614         if (sc->re_testmode) {
2615                 if (!RE_IS_8139CP(sc))
2616                         CSR_WRITE_4(sc, RE_TXCFG,
2617                                     RE_TXCFG_CONFIG | RE_LOOPTEST_ON);
2618                 else
2619                         CSR_WRITE_4(sc, RE_TXCFG,
2620                                     RE_TXCFG_CONFIG | RE_LOOPTEST_ON_CPLUS);
2621         } else
2622                 CSR_WRITE_4(sc, RE_TXCFG, RE_TXCFG_CONFIG);
2623
2624         framelen = RE_FRAMELEN(ifp->if_mtu);
2625         if (framelen < RE_FRAMELEN_2K) {
2626                 CSR_WRITE_1(sc, RE_EARLY_TX_THRESH,
2627                             howmany(RE_FRAMELEN_2K, 128));
2628         } else {
2629                 CSR_WRITE_1(sc, RE_EARLY_TX_THRESH, howmany(framelen, 128));
2630         }
2631
2632         CSR_WRITE_4(sc, RE_RXCFG, RE_RXCFG_CONFIG);
2633
2634         /* Set the individual bit to receive frames for this host only. */
2635         rxcfg = CSR_READ_4(sc, RE_RXCFG);
2636         rxcfg |= RE_RXCFG_RX_INDIV;
2637
2638         /* If we want promiscuous mode, set the allframes bit. */
2639         if (ifp->if_flags & IFF_PROMISC) {
2640                 rxcfg |= RE_RXCFG_RX_ALLPHYS;
2641                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2642         } else {
2643                 rxcfg &= ~RE_RXCFG_RX_ALLPHYS;
2644                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2645         }
2646
2647         /*
2648          * Set capture broadcast bit to capture broadcast frames.
2649          */
2650         if (ifp->if_flags & IFF_BROADCAST) {
2651                 rxcfg |= RE_RXCFG_RX_BROAD;
2652                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2653         } else {
2654                 rxcfg &= ~RE_RXCFG_RX_BROAD;
2655                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2656         }
2657
2658         /*
2659          * Program the multicast filter, if necessary.
2660          */
2661         re_setmulti(sc);
2662
2663 #ifdef DEVICE_POLLING
2664         /*
2665          * Disable interrupts if we are polling.
2666          */
2667         if (ifp->if_flags & IFF_POLLING)
2668                 re_setup_intr(sc, 0, RE_IMTYPE_NONE);
2669         else    /* otherwise ... */
2670 #endif /* DEVICE_POLLING */
2671         /*
2672          * Enable interrupts.
2673          */
2674         if (sc->re_testmode)
2675                 CSR_WRITE_2(sc, RE_IMR, 0);
2676         else
2677                 re_setup_intr(sc, 1, sc->re_imtype);
2678         CSR_WRITE_2(sc, RE_ISR, sc->re_intrs);
2679
2680         /* Set initial TX threshold */
2681         sc->re_txthresh = RE_TX_THRESH_INIT;
2682
2683         /* Start RX/TX process. */
2684         CSR_WRITE_4(sc, RE_MISSEDPKT, 0);
2685
2686 #ifdef notdef
2687         /* Enable receiver and transmitter. */
2688         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2689 #endif
2690
2691         /*
2692          * For 8169 gigE NICs, set the max allowed RX packet
2693          * size so we can receive jumbo frames.
2694          */
2695         if (!RE_IS_8139CP(sc))
2696                 CSR_WRITE_2(sc, RE_MAXRXPKTLEN, 16383);
2697
2698         if (sc->re_testmode)
2699                 return;
2700
2701         mii_mediachg(mii);
2702
2703         CSR_WRITE_1(sc, RE_CFG1, RE_CFG1_DRVLOAD|RE_CFG1_FULLDUPLEX);
2704
2705         ifp->if_flags |= IFF_RUNNING;
2706         ifp->if_flags &= ~IFF_OACTIVE;
2707
2708         sc->re_link = 0;
2709         callout_reset(&sc->re_timer, hz, re_tick, sc);
2710 }
2711
2712 /*
2713  * Set media options.
2714  */
2715 static int
2716 re_ifmedia_upd(struct ifnet *ifp)
2717 {
2718         struct re_softc *sc = ifp->if_softc;
2719         struct mii_data *mii;
2720
2721         ASSERT_SERIALIZED(ifp->if_serializer);
2722
2723         mii = device_get_softc(sc->re_miibus);
2724         mii_mediachg(mii);
2725
2726         return(0);
2727 }
2728
2729 /*
2730  * Report current media status.
2731  */
2732 static void
2733 re_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2734 {
2735         struct re_softc *sc = ifp->if_softc;
2736         struct mii_data *mii;
2737
2738         ASSERT_SERIALIZED(ifp->if_serializer);
2739
2740         mii = device_get_softc(sc->re_miibus);
2741
2742         mii_pollstat(mii);
2743         ifmr->ifm_active = mii->mii_media_active;
2744         ifmr->ifm_status = mii->mii_media_status;
2745 }
2746
2747 static int
2748 re_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
2749 {
2750         struct re_softc *sc = ifp->if_softc;
2751         struct ifreq *ifr = (struct ifreq *) data;
2752         struct mii_data *mii;
2753         int error = 0;
2754
2755         ASSERT_SERIALIZED(ifp->if_serializer);
2756
2757         switch(command) {
2758         case SIOCSIFMTU:
2759                 if (ifr->ifr_mtu > sc->re_maxmtu) {
2760                         error = EINVAL;
2761                 } else if (ifp->if_mtu != ifr->ifr_mtu) {
2762                         ifp->if_mtu = ifr->ifr_mtu;
2763                         if (ifp->if_flags & IFF_RUNNING)
2764                                 ifp->if_init(sc);
2765                 }
2766                 break;
2767
2768         case SIOCSIFFLAGS:
2769                 if (ifp->if_flags & IFF_UP)
2770                         re_init(sc);
2771                 else if (ifp->if_flags & IFF_RUNNING)
2772                         re_stop(sc);
2773                 break;
2774         case SIOCADDMULTI:
2775         case SIOCDELMULTI:
2776                 re_setmulti(sc);
2777                 error = 0;
2778                 break;
2779         case SIOCGIFMEDIA:
2780         case SIOCSIFMEDIA:
2781                 mii = device_get_softc(sc->re_miibus);
2782                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
2783                 break;
2784         case SIOCSIFCAP:
2785                 ifp->if_capenable &= ~(IFCAP_HWCSUM);
2786                 ifp->if_capenable |=
2787                     ifr->ifr_reqcap & (IFCAP_HWCSUM);
2788                 if (ifp->if_capenable & IFCAP_TXCSUM)
2789                         ifp->if_hwassist = RE_CSUM_FEATURES;
2790                 else
2791                         ifp->if_hwassist = 0;
2792                 if (ifp->if_flags & IFF_RUNNING)
2793                         re_init(sc);
2794                 break;
2795         default:
2796                 error = ether_ioctl(ifp, command, data);
2797                 break;
2798         }
2799         return(error);
2800 }
2801
2802 static void
2803 re_watchdog(struct ifnet *ifp)
2804 {
2805         struct re_softc *sc = ifp->if_softc;
2806
2807         ASSERT_SERIALIZED(ifp->if_serializer);
2808
2809         if_printf(ifp, "watchdog timeout\n");
2810
2811         ifp->if_oerrors++;
2812
2813         re_txeof(sc);
2814         re_rxeof(sc);
2815
2816         re_init(sc);
2817
2818         if (!ifq_is_empty(&ifp->if_snd))
2819                 if_devstart(ifp);
2820 }
2821
2822 /*
2823  * Stop the adapter and free any mbufs allocated to the
2824  * RX and TX lists.
2825  */
2826 static void
2827 re_stop(struct re_softc *sc)
2828 {
2829         struct ifnet *ifp = &sc->arpcom.ac_if;
2830         int i;
2831
2832         ASSERT_SERIALIZED(ifp->if_serializer);
2833
2834         ifp->if_timer = 0;
2835         callout_stop(&sc->re_timer);
2836
2837         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2838         sc->re_flags &= ~RE_F_TIMER_INTR;
2839
2840         CSR_WRITE_1(sc, RE_COMMAND, 0x00);
2841         CSR_WRITE_2(sc, RE_IMR, 0x0000);
2842         CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
2843
2844         re_free_rxchain(sc);
2845         sc->re_drop_rxfrag = 0;
2846
2847         /* Free the TX list buffers. */
2848         for (i = 0; i < sc->re_tx_desc_cnt; i++) {
2849                 if (sc->re_ldata.re_tx_mbuf[i] != NULL) {
2850                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2851                                           sc->re_ldata.re_tx_dmamap[i]);
2852                         m_freem(sc->re_ldata.re_tx_mbuf[i]);
2853                         sc->re_ldata.re_tx_mbuf[i] = NULL;
2854                 }
2855         }
2856
2857         /* Free the RX list buffers. */
2858         for (i = 0; i < sc->re_rx_desc_cnt; i++) {
2859                 if (sc->re_ldata.re_rx_mbuf[i] != NULL) {
2860                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2861                                           sc->re_ldata.re_rx_dmamap[i]);
2862                         m_freem(sc->re_ldata.re_rx_mbuf[i]);
2863                         sc->re_ldata.re_rx_mbuf[i] = NULL;
2864                 }
2865         }
2866 }
2867
2868 /*
2869  * Device suspend routine.  Stop the interface and save some PCI
2870  * settings in case the BIOS doesn't restore them properly on
2871  * resume.
2872  */
2873 static int
2874 re_suspend(device_t dev)
2875 {
2876 #ifndef BURN_BRIDGES
2877         int i;
2878 #endif
2879         struct re_softc *sc = device_get_softc(dev);
2880         struct ifnet *ifp = &sc->arpcom.ac_if;
2881
2882         lwkt_serialize_enter(ifp->if_serializer);
2883
2884         re_stop(sc);
2885
2886 #ifndef BURN_BRIDGES
2887         for (i = 0; i < 5; i++)
2888                 sc->saved_maps[i] = pci_read_config(dev, PCIR_MAPS + i * 4, 4);
2889         sc->saved_biosaddr = pci_read_config(dev, PCIR_BIOS, 4);
2890         sc->saved_intline = pci_read_config(dev, PCIR_INTLINE, 1);
2891         sc->saved_cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
2892         sc->saved_lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
2893 #endif
2894
2895         sc->suspended = 1;
2896
2897         lwkt_serialize_exit(ifp->if_serializer);
2898
2899         return (0);
2900 }
2901
2902 /*
2903  * Device resume routine.  Restore some PCI settings in case the BIOS
2904  * doesn't, re-enable busmastering, and restart the interface if
2905  * appropriate.
2906  */
2907 static int
2908 re_resume(device_t dev)
2909 {
2910         struct re_softc *sc = device_get_softc(dev);
2911         struct ifnet *ifp = &sc->arpcom.ac_if;
2912 #ifndef BURN_BRIDGES
2913         int i;
2914 #endif
2915
2916         lwkt_serialize_enter(ifp->if_serializer);
2917
2918 #ifndef BURN_BRIDGES
2919         /* better way to do this? */
2920         for (i = 0; i < 5; i++)
2921                 pci_write_config(dev, PCIR_MAPS + i * 4, sc->saved_maps[i], 4);
2922         pci_write_config(dev, PCIR_BIOS, sc->saved_biosaddr, 4);
2923         pci_write_config(dev, PCIR_INTLINE, sc->saved_intline, 1);
2924         pci_write_config(dev, PCIR_CACHELNSZ, sc->saved_cachelnsz, 1);
2925         pci_write_config(dev, PCIR_LATTIMER, sc->saved_lattimer, 1);
2926
2927         /* reenable busmastering */
2928         pci_enable_busmaster(dev);
2929         pci_enable_io(dev, SYS_RES_IOPORT);
2930 #endif
2931
2932         /* reinitialize interface if necessary */
2933         if (ifp->if_flags & IFF_UP)
2934                 re_init(sc);
2935
2936         sc->suspended = 0;
2937
2938         lwkt_serialize_exit(ifp->if_serializer);
2939
2940         return (0);
2941 }
2942
2943 /*
2944  * Stop all chip I/O so that the kernel's probe routines don't
2945  * get confused by errant DMAs when rebooting.
2946  */
2947 static void
2948 re_shutdown(device_t dev)
2949 {
2950         struct re_softc *sc = device_get_softc(dev);
2951         struct ifnet *ifp = &sc->arpcom.ac_if;
2952
2953         lwkt_serialize_enter(ifp->if_serializer);
2954         re_stop(sc);
2955         lwkt_serialize_exit(ifp->if_serializer);
2956 }
2957
2958 static int
2959 re_pad_frame(struct mbuf *pkt)
2960 {
2961         struct mbuf *last = NULL;
2962         int padlen;
2963
2964         padlen = RE_MIN_FRAMELEN - pkt->m_pkthdr.len;
2965
2966         /* if there's only the packet-header and we can pad there, use it. */
2967         if (pkt->m_pkthdr.len == pkt->m_len &&
2968             M_TRAILINGSPACE(pkt) >= padlen) {
2969                 last = pkt;
2970         } else {
2971                 /*
2972                  * Walk packet chain to find last mbuf. We will either
2973                  * pad there, or append a new mbuf and pad it
2974                  */
2975                 for (last = pkt; last->m_next != NULL; last = last->m_next)
2976                         ; /* EMPTY */
2977
2978                 /* `last' now points to last in chain. */
2979                 if (M_TRAILINGSPACE(last) < padlen) {
2980                         struct mbuf *n;
2981
2982                         /* Allocate new empty mbuf, pad it.  Compact later. */
2983                         MGET(n, MB_DONTWAIT, MT_DATA);
2984                         if (n == NULL)
2985                                 return ENOBUFS;
2986                         n->m_len = 0;
2987                         last->m_next = n;
2988                         last = n;
2989                 }
2990         }
2991         KKASSERT(M_TRAILINGSPACE(last) >= padlen);
2992         KKASSERT(M_WRITABLE(last));
2993
2994         /* Now zero the pad area, to avoid the re cksum-assist bug */
2995         bzero(mtod(last, char *) + last->m_len, padlen);
2996         last->m_len += padlen;
2997         pkt->m_pkthdr.len += padlen;
2998         return 0;
2999 }
3000
3001 static int
3002 re_sysctl_rxtime(SYSCTL_HANDLER_ARGS)
3003 {
3004         struct re_softc *sc = arg1;
3005
3006         return re_sysctl_hwtime(oidp, arg1, arg2, req, &sc->re_rx_time);
3007 }
3008
3009 static int
3010 re_sysctl_txtime(SYSCTL_HANDLER_ARGS)
3011 {
3012         struct re_softc *sc = arg1;
3013
3014         return re_sysctl_hwtime(oidp, arg1, arg2, req, &sc->re_tx_time);
3015 }
3016
3017 static int
3018 re_sysctl_hwtime(SYSCTL_HANDLER_ARGS, int *hwtime)
3019 {
3020         struct re_softc *sc = arg1;
3021         struct ifnet *ifp = &sc->arpcom.ac_if;
3022         int error, v;
3023
3024         lwkt_serialize_enter(ifp->if_serializer);
3025
3026         v = *hwtime;
3027         error = sysctl_handle_int(oidp, &v, 0, req);
3028         if (error || req->newptr == NULL)
3029                 goto back;
3030
3031         if (v <= 0) {
3032                 error = EINVAL;
3033                 goto back;
3034         }
3035
3036         if (v != *hwtime) {
3037                 *hwtime = v;
3038
3039                 if ((ifp->if_flags & (IFF_RUNNING | IFF_POLLING)) ==
3040                     IFF_RUNNING && sc->re_imtype == RE_IMTYPE_HW)
3041                         re_setup_hw_im(sc);
3042         }
3043 back:
3044         lwkt_serialize_exit(ifp->if_serializer);
3045         return error;
3046 }
3047
3048 static int
3049 re_sysctl_simtime(SYSCTL_HANDLER_ARGS)
3050 {
3051         struct re_softc *sc = arg1;
3052         struct ifnet *ifp = &sc->arpcom.ac_if;
3053         int error, v;
3054
3055         lwkt_serialize_enter(ifp->if_serializer);
3056
3057         v = sc->re_sim_time;
3058         error = sysctl_handle_int(oidp, &v, 0, req);
3059         if (error || req->newptr == NULL)
3060                 goto back;
3061
3062         if (v <= 0) {
3063                 error = EINVAL;
3064                 goto back;
3065         }
3066
3067         if (v != sc->re_sim_time) {
3068                 sc->re_sim_time = v;
3069
3070                 if ((ifp->if_flags & (IFF_RUNNING | IFF_POLLING)) ==
3071                     IFF_RUNNING && sc->re_imtype == RE_IMTYPE_SIM) {
3072 #ifdef foo
3073                         int reg;
3074
3075                         /*
3076                          * Following code causes various strange
3077                          * performance problems.  Hmm ...
3078                          */
3079                         CSR_WRITE_2(sc, RE_IMR, 0);
3080                         if (!RE_IS_8139CP(sc))
3081                                 reg = RE_TIMERINT_8169;
3082                         else
3083                                 reg = RE_TIMERINT;
3084                         CSR_WRITE_4(sc, reg, 0);
3085                         CSR_READ_4(sc, reg); /* flush */
3086
3087                         CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
3088                         re_setup_sim_im(sc);
3089 #else
3090                         re_setup_intr(sc, 0, RE_IMTYPE_NONE);
3091                         DELAY(10);
3092                         re_setup_intr(sc, 1, RE_IMTYPE_SIM);
3093 #endif
3094                 }
3095         }
3096 back:
3097         lwkt_serialize_exit(ifp->if_serializer);
3098         return error;
3099 }
3100
3101 static int
3102 re_sysctl_imtype(SYSCTL_HANDLER_ARGS)
3103 {
3104         struct re_softc *sc = arg1;
3105         struct ifnet *ifp = &sc->arpcom.ac_if;
3106         int error, v;
3107
3108         lwkt_serialize_enter(ifp->if_serializer);
3109
3110         v = sc->re_imtype;
3111         error = sysctl_handle_int(oidp, &v, 0, req);
3112         if (error || req->newptr == NULL)
3113                 goto back;
3114
3115         if (v != RE_IMTYPE_HW && v != RE_IMTYPE_SIM && v != RE_IMTYPE_NONE) {
3116                 error = EINVAL;
3117                 goto back;
3118         }
3119         if (v == RE_IMTYPE_HW && (sc->re_caps & RE_C_HWIM) == 0) {
3120                 /* Can't do hardware interrupt moderation */
3121                 error = EOPNOTSUPP;
3122                 goto back;
3123         }
3124
3125         if (v != sc->re_imtype) {
3126                 sc->re_imtype = v;
3127                 if ((ifp->if_flags & (IFF_RUNNING | IFF_POLLING)) ==
3128                     IFF_RUNNING)
3129                         re_setup_intr(sc, 1, sc->re_imtype);
3130         }
3131 back:
3132         lwkt_serialize_exit(ifp->if_serializer);
3133         return error;
3134 }
3135
3136 static void
3137 re_setup_hw_im(struct re_softc *sc)
3138 {
3139         KKASSERT(sc->re_caps & RE_C_HWIM);
3140
3141         /*
3142          * Interrupt moderation
3143          *
3144          * 0xABCD
3145          * A - unknown (maybe TX related)
3146          * B - TX timer (unit: 25us)
3147          * C - unknown (maybe RX related)
3148          * D - RX timer (unit: 25us)
3149          *
3150          *
3151          * re(4)'s interrupt moderation is actually controlled by
3152          * two variables, like most other NICs (bge, bce etc.)
3153          * o  timer
3154          * o  number of packets [P]
3155          *
3156          * The logic relationship between these two variables is
3157          * similar to other NICs too:
3158          * if (timer expire || packets > [P])
3159          *     Interrupt is delivered
3160          *
3161          * Currently we only know how to set 'timer', but not
3162          * 'number of packets', which should be ~30, as far as I
3163          * tested (sink ~900Kpps, interrupt rate is 30KHz)
3164          */
3165         CSR_WRITE_2(sc, RE_IM,
3166                     RE_IM_RXTIME(sc->re_rx_time) |
3167                     RE_IM_TXTIME(sc->re_tx_time) |
3168                     RE_IM_MAGIC);
3169 }
3170
3171 static void
3172 re_disable_hw_im(struct re_softc *sc)
3173 {
3174         if (sc->re_caps & RE_C_HWIM)
3175                 CSR_WRITE_2(sc, RE_IM, 0);
3176 }
3177
3178 static void
3179 re_setup_sim_im(struct re_softc *sc)
3180 {
3181         if (!RE_IS_8139CP(sc)) {
3182                 uint32_t ticks;
3183
3184                 /*
3185                  * Datasheet says tick decreases at bus speed,
3186                  * but it seems the clock runs a little bit
3187                  * faster, so we do some compensation here.
3188                  */
3189                 ticks = (sc->re_sim_time * sc->re_bus_speed * 8) / 5;
3190                 CSR_WRITE_4(sc, RE_TIMERINT_8169, ticks);
3191         } else {
3192                 CSR_WRITE_4(sc, RE_TIMERINT, 0x400); /* XXX */
3193         }
3194         CSR_WRITE_4(sc, RE_TIMERCNT, 1); /* reload */
3195         sc->re_flags |= RE_F_TIMER_INTR;
3196 }
3197
3198 static void
3199 re_disable_sim_im(struct re_softc *sc)
3200 {
3201         if (!RE_IS_8139CP(sc))
3202                 CSR_WRITE_4(sc, RE_TIMERINT_8169, 0);
3203         else
3204                 CSR_WRITE_4(sc, RE_TIMERINT, 0);
3205         sc->re_flags &= ~RE_F_TIMER_INTR;
3206 }
3207
3208 static void
3209 re_config_imtype(struct re_softc *sc, int imtype)
3210 {
3211         switch (imtype) {
3212         case RE_IMTYPE_HW:
3213                 KKASSERT(sc->re_caps & RE_C_HWIM);
3214                 /* FALL THROUGH */
3215         case RE_IMTYPE_NONE:
3216                 sc->re_intrs = RE_INTRS;
3217                 sc->re_rx_ack = RE_ISR_RX_OK | RE_ISR_FIFO_OFLOW |
3218                                 RE_ISR_RX_OVERRUN;
3219                 sc->re_tx_ack = RE_ISR_TX_OK;
3220                 break;
3221
3222         case RE_IMTYPE_SIM:
3223                 sc->re_intrs = RE_INTRS_TIMER;
3224                 sc->re_rx_ack = RE_ISR_TIMEOUT_EXPIRED;
3225                 sc->re_tx_ack = RE_ISR_TIMEOUT_EXPIRED;
3226                 break;
3227
3228         default:
3229                 panic("%s: unknown imtype %d\n",
3230                       sc->arpcom.ac_if.if_xname, imtype);
3231         }
3232 }
3233
3234 static void
3235 re_setup_intr(struct re_softc *sc, int enable_intrs, int imtype)
3236 {
3237         re_config_imtype(sc, imtype);
3238
3239         if (enable_intrs)
3240                 CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
3241         else
3242                 CSR_WRITE_2(sc, RE_IMR, 0); 
3243
3244         switch (imtype) {
3245         case RE_IMTYPE_NONE:
3246                 re_disable_sim_im(sc);
3247                 re_disable_hw_im(sc);
3248                 break;
3249
3250         case RE_IMTYPE_HW:
3251                 KKASSERT(sc->re_caps & RE_C_HWIM);
3252                 re_disable_sim_im(sc);
3253                 re_setup_hw_im(sc);
3254                 break;
3255
3256         case RE_IMTYPE_SIM:
3257                 re_disable_hw_im(sc);
3258                 re_setup_sim_im(sc);
3259                 break;
3260
3261         default:
3262                 panic("%s: unknown imtype %d\n",
3263                       sc->arpcom.ac_if.if_xname, imtype);
3264         }
3265 }
3266
3267 static void
3268 re_get_eaddr(struct re_softc *sc, uint8_t *eaddr)
3269 {
3270         int i;
3271
3272         if (sc->re_macver == RE_MACVER_11 || sc->re_macver == RE_MACVER_12) {
3273                 uint16_t re_did;
3274
3275                 re_get_eewidth(sc);
3276                 re_read_eeprom(sc, (caddr_t)&re_did, 0, 1);
3277                 if (re_did == 0x8128) {
3278                         uint16_t as[ETHER_ADDR_LEN / 2];
3279
3280                         /*
3281                          * Get station address from the EEPROM.
3282                          */
3283                         re_read_eeprom(sc, (caddr_t)as, RE_EE_EADDR, 3);
3284                         for (i = 0; i < ETHER_ADDR_LEN / 2; i++)
3285                                 as[i] = le16toh(as[i]);
3286                         bcopy(as, eaddr, sizeof(eaddr));
3287                         return;
3288                 }
3289         }
3290
3291         /*
3292          * Get station address from IDRx.
3293          */
3294         for (i = 0; i < ETHER_ADDR_LEN; ++i)
3295                 eaddr[i] = CSR_READ_1(sc, RE_IDR0 + i);
3296 }