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