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