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