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