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