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