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