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