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