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