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