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