xref: /freebsd/sys/dev/vr/if_vr.c (revision dd21556857e8d40f66bf5ad54754d9d52669ebf7)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1997, 1998
5  *	Bill Paul <wpaul@ctr.columbia.edu>.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by Bill Paul.
18  * 4. Neither the name of the author nor the names of any co-contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
32  * THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 /*
37  * VIA Rhine fast ethernet PCI NIC driver
38  *
39  * Supports various network adapters based on the VIA Rhine
40  * and Rhine II PCI controllers, including the D-Link DFE530TX.
41  * Datasheets are available at http://www.via.com.tw.
42  *
43  * Written by Bill Paul <wpaul@ctr.columbia.edu>
44  * Electrical Engineering Department
45  * Columbia University, New York City
46  */
47 
48 /*
49  * The VIA Rhine controllers are similar in some respects to the
50  * the DEC tulip chips, except less complicated. The controller
51  * uses an MII bus and an external physical layer interface. The
52  * receiver has a one entry perfect filter and a 64-bit hash table
53  * multicast filter. Transmit and receive descriptors are similar
54  * to the tulip.
55  *
56  * Some Rhine chips has a serious flaw in its transmit DMA mechanism:
57  * transmit buffers must be longword aligned. Unfortunately,
58  * FreeBSD doesn't guarantee that mbufs will be filled in starting
59  * at longword boundaries, so we have to do a buffer copy before
60  * transmission.
61  */
62 
63 #ifdef HAVE_KERNEL_OPTION_HEADERS
64 #include "opt_device_polling.h"
65 #endif
66 
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/bus.h>
70 #include <sys/endian.h>
71 #include <sys/kernel.h>
72 #include <sys/malloc.h>
73 #include <sys/mbuf.h>
74 #include <sys/module.h>
75 #include <sys/rman.h>
76 #include <sys/socket.h>
77 #include <sys/sockio.h>
78 #include <sys/sysctl.h>
79 #include <sys/taskqueue.h>
80 
81 #include <net/bpf.h>
82 #include <net/if.h>
83 #include <net/if_var.h>
84 #include <net/ethernet.h>
85 #include <net/if_dl.h>
86 #include <net/if_media.h>
87 #include <net/if_types.h>
88 #include <net/if_vlan_var.h>
89 
90 #include <dev/mii/mii.h>
91 #include <dev/mii/miivar.h>
92 
93 #include <dev/pci/pcireg.h>
94 #include <dev/pci/pcivar.h>
95 
96 #include <machine/bus.h>
97 
98 #include <dev/vr/if_vrreg.h>
99 
100 /* "device miibus" required.  See GENERIC if you get errors here. */
101 #include "miibus_if.h"
102 
103 MODULE_DEPEND(vr, pci, 1, 1, 1);
104 MODULE_DEPEND(vr, ether, 1, 1, 1);
105 MODULE_DEPEND(vr, miibus, 1, 1, 1);
106 
107 /* Define to show Rx/Tx error status. */
108 #undef	VR_SHOW_ERRORS
109 #define	VR_CSUM_FEATURES	(CSUM_IP | CSUM_TCP | CSUM_UDP)
110 
111 /*
112  * Various supported device vendors/types, their names & quirks.
113  */
114 #define VR_Q_NEEDALIGN		(1<<0)
115 #define VR_Q_CSUM		(1<<1)
116 #define VR_Q_CAM		(1<<2)
117 
118 static const struct vr_type {
119 	u_int16_t		vr_vid;
120 	u_int16_t		vr_did;
121 	int			vr_quirks;
122 	const char		*vr_name;
123 } vr_devs[] = {
124 	{ VIA_VENDORID, VIA_DEVICEID_RHINE,
125 	    VR_Q_NEEDALIGN,
126 	    "VIA VT3043 Rhine I 10/100BaseTX" },
127 	{ VIA_VENDORID, VIA_DEVICEID_RHINE_II,
128 	    VR_Q_NEEDALIGN,
129 	    "VIA VT86C100A Rhine II 10/100BaseTX" },
130 	{ VIA_VENDORID, VIA_DEVICEID_RHINE_II_2,
131 	    0,
132 	    "VIA VT6102 Rhine II 10/100BaseTX" },
133 	{ VIA_VENDORID, VIA_DEVICEID_RHINE_III,
134 	    0,
135 	    "VIA VT6105 Rhine III 10/100BaseTX" },
136 	{ VIA_VENDORID, VIA_DEVICEID_RHINE_III_M,
137 	    VR_Q_CSUM,
138 	    "VIA VT6105M Rhine III 10/100BaseTX" },
139 	{ DELTA_VENDORID, DELTA_DEVICEID_RHINE_II,
140 	    VR_Q_NEEDALIGN,
141 	    "Delta Electronics Rhine II 10/100BaseTX" },
142 	{ ADDTRON_VENDORID, ADDTRON_DEVICEID_RHINE_II,
143 	    VR_Q_NEEDALIGN,
144 	    "Addtron Technology Rhine II 10/100BaseTX" },
145 	{ 0, 0, 0, NULL }
146 };
147 
148 static int vr_probe(device_t);
149 static int vr_attach(device_t);
150 static int vr_detach(device_t);
151 static int vr_shutdown(device_t);
152 static int vr_suspend(device_t);
153 static int vr_resume(device_t);
154 
155 static void vr_dmamap_cb(void *, bus_dma_segment_t *, int, int);
156 static int vr_dma_alloc(struct vr_softc *);
157 static void vr_dma_free(struct vr_softc *);
158 static __inline void vr_discard_rxbuf(struct vr_rxdesc *);
159 static int vr_newbuf(struct vr_softc *, int);
160 
161 #ifndef __NO_STRICT_ALIGNMENT
162 static __inline void vr_fixup_rx(struct mbuf *);
163 #endif
164 static int vr_rxeof(struct vr_softc *);
165 static void vr_txeof(struct vr_softc *);
166 static void vr_tick(void *);
167 static int vr_error(struct vr_softc *, uint16_t);
168 static void vr_tx_underrun(struct vr_softc *);
169 static int vr_intr(void *);
170 static void vr_int_task(void *, int);
171 static void vr_start(if_t);
172 static void vr_start_locked(if_t);
173 static int vr_encap(struct vr_softc *, struct mbuf **);
174 static int vr_ioctl(if_t, u_long, caddr_t);
175 static void vr_init(void *);
176 static void vr_init_locked(struct vr_softc *);
177 static void vr_tx_start(struct vr_softc *);
178 static void vr_rx_start(struct vr_softc *);
179 static int vr_tx_stop(struct vr_softc *);
180 static int vr_rx_stop(struct vr_softc *);
181 static void vr_stop(struct vr_softc *);
182 static void vr_watchdog(struct vr_softc *);
183 static int vr_ifmedia_upd(if_t);
184 static void vr_ifmedia_sts(if_t, struct ifmediareq *);
185 
186 static int vr_miibus_readreg(device_t, int, int);
187 static int vr_miibus_writereg(device_t, int, int, int);
188 static void vr_miibus_statchg(device_t);
189 
190 static void vr_cam_mask(struct vr_softc *, uint32_t, int);
191 static int vr_cam_data(struct vr_softc *, int, int, uint8_t *);
192 static void vr_set_filter(struct vr_softc *);
193 static void vr_reset(const struct vr_softc *);
194 static int vr_tx_ring_init(struct vr_softc *);
195 static int vr_rx_ring_init(struct vr_softc *);
196 static void vr_setwol(struct vr_softc *);
197 static void vr_clrwol(struct vr_softc *);
198 static int vr_sysctl_stats(SYSCTL_HANDLER_ARGS);
199 
200 static const struct vr_tx_threshold_table {
201 	int tx_cfg;
202 	int bcr_cfg;
203 	int value;
204 } vr_tx_threshold_tables[] = {
205 	{ VR_TXTHRESH_64BYTES, VR_BCR1_TXTHRESH64BYTES,	64 },
206 	{ VR_TXTHRESH_128BYTES, VR_BCR1_TXTHRESH128BYTES, 128 },
207 	{ VR_TXTHRESH_256BYTES, VR_BCR1_TXTHRESH256BYTES, 256 },
208 	{ VR_TXTHRESH_512BYTES, VR_BCR1_TXTHRESH512BYTES, 512 },
209 	{ VR_TXTHRESH_1024BYTES, VR_BCR1_TXTHRESH1024BYTES, 1024 },
210 	{ VR_TXTHRESH_STORENFWD, VR_BCR1_TXTHRESHSTORENFWD, 2048 }
211 };
212 
213 static device_method_t vr_methods[] = {
214 	/* Device interface */
215 	DEVMETHOD(device_probe,		vr_probe),
216 	DEVMETHOD(device_attach,	vr_attach),
217 	DEVMETHOD(device_detach, 	vr_detach),
218 	DEVMETHOD(device_shutdown,	vr_shutdown),
219 	DEVMETHOD(device_suspend,	vr_suspend),
220 	DEVMETHOD(device_resume,	vr_resume),
221 
222 	/* MII interface */
223 	DEVMETHOD(miibus_readreg,	vr_miibus_readreg),
224 	DEVMETHOD(miibus_writereg,	vr_miibus_writereg),
225 	DEVMETHOD(miibus_statchg,	vr_miibus_statchg),
226 
227 	DEVMETHOD_END
228 };
229 
230 static driver_t vr_driver = {
231 	"vr",
232 	vr_methods,
233 	sizeof(struct vr_softc)
234 };
235 
236 DRIVER_MODULE(vr, pci, vr_driver, 0, 0);
237 DRIVER_MODULE(miibus, vr, miibus_driver, 0, 0);
238 
239 static int
240 vr_miibus_readreg(device_t dev, int phy, int reg)
241 {
242 	struct vr_softc		*sc;
243 	int			i;
244 
245 	sc = device_get_softc(dev);
246 
247 	/* Set the register address. */
248 	CSR_WRITE_1(sc, VR_MIIADDR, reg);
249 	VR_SETBIT(sc, VR_MIICMD, VR_MIICMD_READ_ENB);
250 
251 	for (i = 0; i < VR_MII_TIMEOUT; i++) {
252 		DELAY(1);
253 		if ((CSR_READ_1(sc, VR_MIICMD) & VR_MIICMD_READ_ENB) == 0)
254 			break;
255 	}
256 	if (i == VR_MII_TIMEOUT)
257 		device_printf(sc->vr_dev, "phy read timeout %d:%d\n", phy, reg);
258 
259 	return (CSR_READ_2(sc, VR_MIIDATA));
260 }
261 
262 static int
263 vr_miibus_writereg(device_t dev, int phy, int reg, int data)
264 {
265 	struct vr_softc		*sc;
266 	int			i;
267 
268 	sc = device_get_softc(dev);
269 
270 	/* Set the register address and data to write. */
271 	CSR_WRITE_1(sc, VR_MIIADDR, reg);
272 	CSR_WRITE_2(sc, VR_MIIDATA, data);
273 	VR_SETBIT(sc, VR_MIICMD, VR_MIICMD_WRITE_ENB);
274 
275 	for (i = 0; i < VR_MII_TIMEOUT; i++) {
276 		DELAY(1);
277 		if ((CSR_READ_1(sc, VR_MIICMD) & VR_MIICMD_WRITE_ENB) == 0)
278 			break;
279 	}
280 	if (i == VR_MII_TIMEOUT)
281 		device_printf(sc->vr_dev, "phy write timeout %d:%d\n", phy,
282 		    reg);
283 
284 	return (0);
285 }
286 
287 /*
288  * In order to fiddle with the
289  * 'full-duplex' and '100Mbps' bits in the netconfig register, we
290  * first have to put the transmit and/or receive logic in the idle state.
291  */
292 static void
293 vr_miibus_statchg(device_t dev)
294 {
295 	struct vr_softc		*sc;
296 	struct mii_data		*mii;
297 	if_t			ifp;
298 	int			lfdx, mfdx;
299 	uint8_t			cr0, cr1, fc;
300 
301 	sc = device_get_softc(dev);
302 	mii = device_get_softc(sc->vr_miibus);
303 	ifp = sc->vr_ifp;
304 	if (mii == NULL || ifp == NULL ||
305 	    (if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0)
306 		return;
307 
308 	sc->vr_flags &= ~(VR_F_LINK | VR_F_TXPAUSE);
309 	if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) ==
310 	    (IFM_ACTIVE | IFM_AVALID)) {
311 		switch (IFM_SUBTYPE(mii->mii_media_active)) {
312 		case IFM_10_T:
313 		case IFM_100_TX:
314 			sc->vr_flags |= VR_F_LINK;
315 			break;
316 		default:
317 			break;
318 		}
319 	}
320 
321 	if ((sc->vr_flags & VR_F_LINK) != 0) {
322 		cr0 = CSR_READ_1(sc, VR_CR0);
323 		cr1 = CSR_READ_1(sc, VR_CR1);
324 		mfdx = (cr1 & VR_CR1_FULLDUPLEX) != 0;
325 		lfdx = (IFM_OPTIONS(mii->mii_media_active) & IFM_FDX) != 0;
326 		if (mfdx != lfdx) {
327 			if ((cr0 & (VR_CR0_TX_ON | VR_CR0_RX_ON)) != 0) {
328 				if (vr_tx_stop(sc) != 0 ||
329 				    vr_rx_stop(sc) != 0) {
330 					device_printf(sc->vr_dev,
331 					    "%s: Tx/Rx shutdown error -- "
332 					    "resetting\n", __func__);
333 					sc->vr_flags |= VR_F_RESTART;
334 					VR_UNLOCK(sc);
335 					return;
336 				}
337 			}
338 			if (lfdx)
339 				cr1 |= VR_CR1_FULLDUPLEX;
340 			else
341 				cr1 &= ~VR_CR1_FULLDUPLEX;
342 			CSR_WRITE_1(sc, VR_CR1, cr1);
343 		}
344 		fc = 0;
345 		/* Configure flow-control. */
346 		if (sc->vr_revid >= REV_ID_VT6105_A0) {
347 			fc = CSR_READ_1(sc, VR_FLOWCR1);
348 			fc &= ~(VR_FLOWCR1_TXPAUSE | VR_FLOWCR1_RXPAUSE);
349 			if ((IFM_OPTIONS(mii->mii_media_active) &
350 			    IFM_ETH_RXPAUSE) != 0)
351 				fc |= VR_FLOWCR1_RXPAUSE;
352 			if ((IFM_OPTIONS(mii->mii_media_active) &
353 			    IFM_ETH_TXPAUSE) != 0) {
354 				fc |= VR_FLOWCR1_TXPAUSE;
355 				sc->vr_flags |= VR_F_TXPAUSE;
356 			}
357 			CSR_WRITE_1(sc, VR_FLOWCR1, fc);
358 		} else if (sc->vr_revid >= REV_ID_VT6102_A) {
359 			/* No Tx puase capability available for Rhine II. */
360 			fc = CSR_READ_1(sc, VR_MISC_CR0);
361 			fc &= ~VR_MISCCR0_RXPAUSE;
362 			if ((IFM_OPTIONS(mii->mii_media_active) &
363 			    IFM_ETH_RXPAUSE) != 0)
364 				fc |= VR_MISCCR0_RXPAUSE;
365 			CSR_WRITE_1(sc, VR_MISC_CR0, fc);
366 		}
367 		vr_rx_start(sc);
368 		vr_tx_start(sc);
369 	} else {
370 		if (vr_tx_stop(sc) != 0 || vr_rx_stop(sc) != 0) {
371 			device_printf(sc->vr_dev,
372 			    "%s: Tx/Rx shutdown error -- resetting\n",
373 			    __func__);
374 			sc->vr_flags |= VR_F_RESTART;
375 		}
376 	}
377 }
378 
379 static void
380 vr_cam_mask(struct vr_softc *sc, uint32_t mask, int type)
381 {
382 
383 	if (type == VR_MCAST_CAM)
384 		CSR_WRITE_1(sc, VR_CAMCTL, VR_CAMCTL_ENA | VR_CAMCTL_MCAST);
385 	else
386 		CSR_WRITE_1(sc, VR_CAMCTL, VR_CAMCTL_ENA | VR_CAMCTL_VLAN);
387 	CSR_WRITE_4(sc, VR_CAMMASK, mask);
388 	CSR_WRITE_1(sc, VR_CAMCTL, 0);
389 }
390 
391 static int
392 vr_cam_data(struct vr_softc *sc, int type, int idx, uint8_t *mac)
393 {
394 	int	i;
395 
396 	if (type == VR_MCAST_CAM) {
397 		if (idx < 0 || idx >= VR_CAM_MCAST_CNT || mac == NULL)
398 			return (EINVAL);
399 		CSR_WRITE_1(sc, VR_CAMCTL, VR_CAMCTL_ENA | VR_CAMCTL_MCAST);
400 	} else
401 		CSR_WRITE_1(sc, VR_CAMCTL, VR_CAMCTL_ENA | VR_CAMCTL_VLAN);
402 
403 	/* Set CAM entry address. */
404 	CSR_WRITE_1(sc, VR_CAMADDR, idx);
405 	/* Set CAM entry data. */
406 	if (type == VR_MCAST_CAM) {
407 		for (i = 0; i < ETHER_ADDR_LEN; i++)
408 			CSR_WRITE_1(sc, VR_MCAM0 + i, mac[i]);
409 	} else {
410 		CSR_WRITE_1(sc, VR_VCAM0, mac[0]);
411 		CSR_WRITE_1(sc, VR_VCAM1, mac[1]);
412 	}
413 	DELAY(10);
414 	/* Write CAM and wait for self-clear of VR_CAMCTL_WRITE bit. */
415 	CSR_WRITE_1(sc, VR_CAMCTL, VR_CAMCTL_ENA | VR_CAMCTL_WRITE);
416 	for (i = 0; i < VR_TIMEOUT; i++) {
417 		DELAY(1);
418 		if ((CSR_READ_1(sc, VR_CAMCTL) & VR_CAMCTL_WRITE) == 0)
419 			break;
420 	}
421 
422 	if (i == VR_TIMEOUT)
423 		device_printf(sc->vr_dev, "%s: setting CAM filter timeout!\n",
424 		    __func__);
425 	CSR_WRITE_1(sc, VR_CAMCTL, 0);
426 
427 	return (i == VR_TIMEOUT ? ETIMEDOUT : 0);
428 }
429 
430 struct vr_hash_maddr_cam_ctx {
431 	struct vr_softc *sc;
432 	uint32_t mask;
433 	int error;
434 };
435 
436 static u_int
437 vr_hash_maddr_cam(void *arg, struct sockaddr_dl *sdl, u_int mcnt)
438 {
439 	struct vr_hash_maddr_cam_ctx *ctx = arg;
440 
441 	if (ctx->error != 0)
442 		return (0);
443 	ctx->error = vr_cam_data(ctx->sc, VR_MCAST_CAM, mcnt, LLADDR(sdl));
444 	if (ctx->error != 0) {
445 		ctx->mask = 0;
446 		return (0);
447 	}
448 	ctx->mask |= 1 << mcnt;
449 
450 	return (1);
451 }
452 
453 static u_int
454 vr_hash_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
455 {
456 	uint32_t *hashes = arg;
457 	int h;
458 
459 	h = ether_crc32_be(LLADDR(sdl), ETHER_ADDR_LEN) >> 26;
460 	if (h < 32)
461 		hashes[0] |= (1 << h);
462 	else
463 		hashes[1] |= (1 << (h - 32));
464 
465 	return (1);
466 }
467 
468 /*
469  * Program the 64-bit multicast hash filter.
470  */
471 static void
472 vr_set_filter(struct vr_softc *sc)
473 {
474 	if_t			ifp;
475 	uint32_t		hashes[2] = { 0, 0 };
476 	uint8_t			rxfilt;
477 	int			error, mcnt;
478 
479 	VR_LOCK_ASSERT(sc);
480 
481 	ifp = sc->vr_ifp;
482 	rxfilt = CSR_READ_1(sc, VR_RXCFG);
483 	rxfilt &= ~(VR_RXCFG_RX_PROMISC | VR_RXCFG_RX_BROAD |
484 	    VR_RXCFG_RX_MULTI);
485 	if (if_getflags(ifp) & IFF_BROADCAST)
486 		rxfilt |= VR_RXCFG_RX_BROAD;
487 	if (if_getflags(ifp) & IFF_ALLMULTI || if_getflags(ifp) & IFF_PROMISC) {
488 		rxfilt |= VR_RXCFG_RX_MULTI;
489 		if (if_getflags(ifp) & IFF_PROMISC)
490 			rxfilt |= VR_RXCFG_RX_PROMISC;
491 		CSR_WRITE_1(sc, VR_RXCFG, rxfilt);
492 		CSR_WRITE_4(sc, VR_MAR0, 0xFFFFFFFF);
493 		CSR_WRITE_4(sc, VR_MAR1, 0xFFFFFFFF);
494 		return;
495 	}
496 
497 	/* Now program new ones. */
498 	error = 0;
499 	if ((sc->vr_quirks & VR_Q_CAM) != 0) {
500 		struct vr_hash_maddr_cam_ctx ctx;
501 
502 		/*
503 		 * For hardwares that have CAM capability, use
504 		 * 32 entries multicast perfect filter.
505 		 */
506 		ctx.sc = sc;
507 		ctx.mask = 0;
508 		ctx.error = 0;
509 		mcnt = if_foreach_llmaddr(ifp, vr_hash_maddr_cam, &ctx);
510 		vr_cam_mask(sc, VR_MCAST_CAM, ctx.mask);
511 	}
512 
513 	if ((sc->vr_quirks & VR_Q_CAM) == 0 || error != 0) {
514 		/*
515 		 * If there are too many multicast addresses or
516 		 * setting multicast CAM filter failed, use hash
517 		 * table based filtering.
518 		 */
519 		mcnt = if_foreach_llmaddr(ifp, vr_hash_maddr, hashes);
520 	}
521 
522 	if (mcnt > 0)
523 		rxfilt |= VR_RXCFG_RX_MULTI;
524 
525 	CSR_WRITE_4(sc, VR_MAR0, hashes[0]);
526 	CSR_WRITE_4(sc, VR_MAR1, hashes[1]);
527 	CSR_WRITE_1(sc, VR_RXCFG, rxfilt);
528 }
529 
530 static void
531 vr_reset(const struct vr_softc *sc)
532 {
533 	int		i;
534 
535 	/*VR_LOCK_ASSERT(sc);*/ /* XXX: Called during attach w/o lock. */
536 
537 	CSR_WRITE_1(sc, VR_CR1, VR_CR1_RESET);
538 	if (sc->vr_revid < REV_ID_VT6102_A) {
539 		/* VT86C100A needs more delay after reset. */
540 		DELAY(100);
541 	}
542 	for (i = 0; i < VR_TIMEOUT; i++) {
543 		DELAY(10);
544 		if (!(CSR_READ_1(sc, VR_CR1) & VR_CR1_RESET))
545 			break;
546 	}
547 	if (i == VR_TIMEOUT) {
548 		if (sc->vr_revid < REV_ID_VT6102_A)
549 			device_printf(sc->vr_dev, "reset never completed!\n");
550 		else {
551 			/* Use newer force reset command. */
552 			device_printf(sc->vr_dev,
553 			    "Using force reset command.\n");
554 			VR_SETBIT(sc, VR_MISC_CR1, VR_MISCCR1_FORSRST);
555 			/*
556 			 * Wait a little while for the chip to get its brains
557 			 * in order.
558 			 */
559 			DELAY(2000);
560 		}
561 	}
562 
563 }
564 
565 /*
566  * Probe for a VIA Rhine chip. Check the PCI vendor and device
567  * IDs against our list and return a match or NULL
568  */
569 static const struct vr_type *
570 vr_match(device_t dev)
571 {
572 	const struct vr_type	*t = vr_devs;
573 
574 	for (t = vr_devs; t->vr_name != NULL; t++)
575 		if ((pci_get_vendor(dev) == t->vr_vid) &&
576 		    (pci_get_device(dev) == t->vr_did))
577 			return (t);
578 	return (NULL);
579 }
580 
581 /*
582  * Probe for a VIA Rhine chip. Check the PCI vendor and device
583  * IDs against our list and return a device name if we find a match.
584  */
585 static int
586 vr_probe(device_t dev)
587 {
588 	const struct vr_type	*t;
589 
590 	t = vr_match(dev);
591 	if (t != NULL) {
592 		device_set_desc(dev, t->vr_name);
593 		return (BUS_PROBE_DEFAULT);
594 	}
595 	return (ENXIO);
596 }
597 
598 /*
599  * Attach the interface. Allocate softc structures, do ifmedia
600  * setup and ethernet/BPF attach.
601  */
602 static int
603 vr_attach(device_t dev)
604 {
605 	struct vr_softc		*sc;
606 	if_t			ifp;
607 	const struct vr_type	*t;
608 	uint8_t			eaddr[ETHER_ADDR_LEN];
609 	int			error, rid;
610 	int			i, phy, pmc;
611 
612 	sc = device_get_softc(dev);
613 	sc->vr_dev = dev;
614 	t = vr_match(dev);
615 	KASSERT(t != NULL, ("Lost if_vr device match"));
616 	sc->vr_quirks = t->vr_quirks;
617 	device_printf(dev, "Quirks: 0x%x\n", sc->vr_quirks);
618 
619 	mtx_init(&sc->vr_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
620 	    MTX_DEF);
621 	callout_init_mtx(&sc->vr_stat_callout, &sc->vr_mtx, 0);
622 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
623 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
624 	    OID_AUTO, "stats", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
625 	    sc, 0, vr_sysctl_stats, "I", "Statistics");
626 
627 	error = 0;
628 
629 	/*
630 	 * Map control/status registers.
631 	 */
632 	pci_enable_busmaster(dev);
633 	sc->vr_revid = pci_get_revid(dev);
634 	device_printf(dev, "Revision: 0x%x\n", sc->vr_revid);
635 
636 	sc->vr_res_id = PCIR_BAR(0);
637 	sc->vr_res_type = SYS_RES_IOPORT;
638 	sc->vr_res = bus_alloc_resource_any(dev, sc->vr_res_type,
639 	    &sc->vr_res_id, RF_ACTIVE);
640 	if (sc->vr_res == NULL) {
641 		device_printf(dev, "couldn't map ports\n");
642 		error = ENXIO;
643 		goto fail;
644 	}
645 
646 	/* Allocate interrupt. */
647 	rid = 0;
648 	sc->vr_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
649 	    RF_SHAREABLE | RF_ACTIVE);
650 
651 	if (sc->vr_irq == NULL) {
652 		device_printf(dev, "couldn't map interrupt\n");
653 		error = ENXIO;
654 		goto fail;
655 	}
656 
657 	/* Allocate ifnet structure. */
658 	ifp = sc->vr_ifp = if_alloc(IFT_ETHER);
659 	if_setsoftc(ifp, sc);
660 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
661 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
662 	if_setioctlfn(ifp, vr_ioctl);
663 	if_setstartfn(ifp, vr_start);
664 	if_setinitfn(ifp, vr_init);
665 	if_setsendqlen(ifp, VR_TX_RING_CNT - 1);
666 	if_setsendqready(ifp);
667 
668 	NET_TASK_INIT(&sc->vr_inttask, 0, vr_int_task, sc);
669 
670 	/* Configure Tx FIFO threshold. */
671 	sc->vr_txthresh = VR_TXTHRESH_MIN;
672 	if (sc->vr_revid < REV_ID_VT6105_A0) {
673 		/*
674 		 * Use store and forward mode for Rhine I/II.
675 		 * Otherwise they produce a lot of Tx underruns and
676 		 * it would take a while to get working FIFO threshold
677 		 * value.
678 		 */
679 		sc->vr_txthresh = VR_TXTHRESH_MAX;
680 	}
681 	if ((sc->vr_quirks & VR_Q_CSUM) != 0) {
682 		if_sethwassist(ifp, VR_CSUM_FEATURES);
683 		if_setcapabilitiesbit(ifp, IFCAP_HWCSUM, 0);
684 		/*
685 		 * To update checksum field the hardware may need to
686 		 * store entire frames into FIFO before transmitting.
687 		 */
688 		sc->vr_txthresh = VR_TXTHRESH_MAX;
689 	}
690 
691 	if (sc->vr_revid >= REV_ID_VT6102_A &&
692 	    pci_find_cap(dev, PCIY_PMG, &pmc) == 0)
693 		if_setcapabilitiesbit(ifp, IFCAP_WOL_UCAST | IFCAP_WOL_MAGIC, 0);
694 
695 	/* Rhine supports oversized VLAN frame. */
696 	if_setcapabilitiesbit(ifp, IFCAP_VLAN_MTU, 0);
697 	if_setcapenable(ifp, if_getcapabilities(ifp));
698 #ifdef DEVICE_POLLING
699 	if_setcapabilitiesbit(ifp, IFCAP_POLLING, 0);
700 #endif
701 
702 	/*
703 	 * Windows may put the chip in suspend mode when it
704 	 * shuts down. Be sure to kick it in the head to wake it
705 	 * up again.
706 	 */
707 	if (pci_find_cap(dev, PCIY_PMG, &pmc) == 0)
708 		VR_CLRBIT(sc, VR_STICKHW, (VR_STICKHW_DS0|VR_STICKHW_DS1));
709 
710 	/*
711 	 * Get station address. The way the Rhine chips work,
712 	 * you're not allowed to directly access the EEPROM once
713 	 * they've been programmed a special way. Consequently,
714 	 * we need to read the node address from the PAR0 and PAR1
715 	 * registers.
716 	 * Reloading EEPROM also overwrites VR_CFGA, VR_CFGB,
717 	 * VR_CFGC and VR_CFGD such that memory mapped IO configured
718 	 * by driver is reset to default state.
719 	 */
720 	VR_SETBIT(sc, VR_EECSR, VR_EECSR_LOAD);
721 	for (i = VR_TIMEOUT; i > 0; i--) {
722 		DELAY(1);
723 		if ((CSR_READ_1(sc, VR_EECSR) & VR_EECSR_LOAD) == 0)
724 			break;
725 	}
726 	if (i == 0)
727 		device_printf(dev, "Reloading EEPROM timeout!\n");
728 	for (i = 0; i < ETHER_ADDR_LEN; i++)
729 		eaddr[i] = CSR_READ_1(sc, VR_PAR0 + i);
730 
731 	/* Reset the adapter. */
732 	vr_reset(sc);
733 	/* Ack intr & disable further interrupts. */
734 	CSR_WRITE_2(sc, VR_ISR, 0xFFFF);
735 	CSR_WRITE_2(sc, VR_IMR, 0);
736 	if (sc->vr_revid >= REV_ID_VT6102_A)
737 		CSR_WRITE_2(sc, VR_MII_IMR, 0);
738 
739 	if (sc->vr_revid < REV_ID_VT6102_A) {
740 		pci_write_config(dev, VR_PCI_MODE2,
741 		    pci_read_config(dev, VR_PCI_MODE2, 1) |
742 		    VR_MODE2_MODE10T, 1);
743 	} else {
744 		/* Report error instead of retrying forever. */
745 		pci_write_config(dev, VR_PCI_MODE2,
746 		    pci_read_config(dev, VR_PCI_MODE2, 1) |
747 		    VR_MODE2_PCEROPT, 1);
748         	/* Detect MII coding error. */
749 		pci_write_config(dev, VR_PCI_MODE3,
750 		    pci_read_config(dev, VR_PCI_MODE3, 1) |
751 		    VR_MODE3_MIION, 1);
752 		if (sc->vr_revid >= REV_ID_VT6105_LOM &&
753 		    sc->vr_revid < REV_ID_VT6105M_A0)
754 			pci_write_config(dev, VR_PCI_MODE2,
755 			    pci_read_config(dev, VR_PCI_MODE2, 1) |
756 			    VR_MODE2_MODE10T, 1);
757 		/* Enable Memory-Read-Multiple. */
758 		if (sc->vr_revid >= REV_ID_VT6107_A1 &&
759 		    sc->vr_revid < REV_ID_VT6105M_A0)
760 			pci_write_config(dev, VR_PCI_MODE2,
761 			    pci_read_config(dev, VR_PCI_MODE2, 1) |
762 			    VR_MODE2_MRDPL, 1);
763 	}
764 	/* Disable MII AUTOPOLL. */
765 	VR_CLRBIT(sc, VR_MIICMD, VR_MIICMD_AUTOPOLL);
766 
767 	if (vr_dma_alloc(sc) != 0) {
768 		error = ENXIO;
769 		goto fail;
770 	}
771 
772 	/* Do MII setup. */
773 	if (sc->vr_revid >= REV_ID_VT6105_A0)
774 		phy = 1;
775 	else
776 		phy = CSR_READ_1(sc, VR_PHYADDR) & VR_PHYADDR_MASK;
777 	error = mii_attach(dev, &sc->vr_miibus, ifp, vr_ifmedia_upd,
778 	    vr_ifmedia_sts, BMSR_DEFCAPMASK, phy, MII_OFFSET_ANY,
779 	    sc->vr_revid >= REV_ID_VT6102_A ? MIIF_DOPAUSE : 0);
780 	if (error != 0) {
781 		device_printf(dev, "attaching PHYs failed\n");
782 		goto fail;
783 	}
784 
785 	/* Call MI attach routine. */
786 	ether_ifattach(ifp, eaddr);
787 	/*
788 	 * Tell the upper layer(s) we support long frames.
789 	 * Must appear after the call to ether_ifattach() because
790 	 * ether_ifattach() sets ifi_hdrlen to the default value.
791 	 */
792 	if_setifheaderlen(ifp, sizeof(struct ether_vlan_header));
793 
794 	/* Hook interrupt last to avoid having to lock softc. */
795 	error = bus_setup_intr(dev, sc->vr_irq, INTR_TYPE_NET | INTR_MPSAFE,
796 	    vr_intr, NULL, sc, &sc->vr_intrhand);
797 
798 	if (error) {
799 		device_printf(dev, "couldn't set up irq\n");
800 		ether_ifdetach(ifp);
801 		goto fail;
802 	}
803 
804 fail:
805 	if (error)
806 		vr_detach(dev);
807 
808 	return (error);
809 }
810 
811 /*
812  * Shutdown hardware and free up resources. This can be called any
813  * time after the mutex has been initialized. It is called in both
814  * the error case in attach and the normal detach case so it needs
815  * to be careful about only freeing resources that have actually been
816  * allocated.
817  */
818 static int
819 vr_detach(device_t dev)
820 {
821 	struct vr_softc		*sc = device_get_softc(dev);
822 	if_t			ifp = sc->vr_ifp;
823 
824 	KASSERT(mtx_initialized(&sc->vr_mtx), ("vr mutex not initialized"));
825 
826 #ifdef DEVICE_POLLING
827 	if (ifp != NULL && if_getcapenable(ifp) & IFCAP_POLLING)
828 		ether_poll_deregister(ifp);
829 #endif
830 
831 	/* These should only be active if attach succeeded. */
832 	if (device_is_attached(dev)) {
833 		VR_LOCK(sc);
834 		sc->vr_flags |= VR_F_DETACHED;
835 		vr_stop(sc);
836 		VR_UNLOCK(sc);
837 		callout_drain(&sc->vr_stat_callout);
838 		taskqueue_drain(taskqueue_fast, &sc->vr_inttask);
839 		ether_ifdetach(ifp);
840 	}
841 	bus_generic_detach(dev);
842 
843 	if (sc->vr_intrhand)
844 		bus_teardown_intr(dev, sc->vr_irq, sc->vr_intrhand);
845 	if (sc->vr_irq)
846 		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->vr_irq);
847 	if (sc->vr_res)
848 		bus_release_resource(dev, sc->vr_res_type, sc->vr_res_id,
849 		    sc->vr_res);
850 
851 	if (ifp)
852 		if_free(ifp);
853 
854 	vr_dma_free(sc);
855 
856 	mtx_destroy(&sc->vr_mtx);
857 
858 	return (0);
859 }
860 
861 struct vr_dmamap_arg {
862 	bus_addr_t	vr_busaddr;
863 };
864 
865 static void
866 vr_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
867 {
868 	struct vr_dmamap_arg	*ctx;
869 
870 	if (error != 0)
871 		return;
872 	ctx = arg;
873 	ctx->vr_busaddr = segs[0].ds_addr;
874 }
875 
876 static int
877 vr_dma_alloc(struct vr_softc *sc)
878 {
879 	struct vr_dmamap_arg	ctx;
880 	struct vr_txdesc	*txd;
881 	struct vr_rxdesc	*rxd;
882 	bus_size_t		tx_alignment;
883 	int			error, i;
884 
885 	/* Create parent DMA tag. */
886 	error = bus_dma_tag_create(
887 	    bus_get_dma_tag(sc->vr_dev),	/* parent */
888 	    1, 0,			/* alignment, boundary */
889 	    BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
890 	    BUS_SPACE_MAXADDR,		/* highaddr */
891 	    NULL, NULL,			/* filter, filterarg */
892 	    BUS_SPACE_MAXSIZE_32BIT,	/* maxsize */
893 	    0,				/* nsegments */
894 	    BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
895 	    0,				/* flags */
896 	    NULL, NULL,			/* lockfunc, lockarg */
897 	    &sc->vr_cdata.vr_parent_tag);
898 	if (error != 0) {
899 		device_printf(sc->vr_dev, "failed to create parent DMA tag\n");
900 		goto fail;
901 	}
902 	/* Create tag for Tx ring. */
903 	error = bus_dma_tag_create(
904 	    sc->vr_cdata.vr_parent_tag,	/* parent */
905 	    VR_RING_ALIGN, 0,		/* alignment, boundary */
906 	    BUS_SPACE_MAXADDR,		/* lowaddr */
907 	    BUS_SPACE_MAXADDR,		/* highaddr */
908 	    NULL, NULL,			/* filter, filterarg */
909 	    VR_TX_RING_SIZE,		/* maxsize */
910 	    1,				/* nsegments */
911 	    VR_TX_RING_SIZE,		/* maxsegsize */
912 	    0,				/* flags */
913 	    NULL, NULL,			/* lockfunc, lockarg */
914 	    &sc->vr_cdata.vr_tx_ring_tag);
915 	if (error != 0) {
916 		device_printf(sc->vr_dev, "failed to create Tx ring DMA tag\n");
917 		goto fail;
918 	}
919 
920 	/* Create tag for Rx ring. */
921 	error = bus_dma_tag_create(
922 	    sc->vr_cdata.vr_parent_tag,	/* parent */
923 	    VR_RING_ALIGN, 0,		/* alignment, boundary */
924 	    BUS_SPACE_MAXADDR,		/* lowaddr */
925 	    BUS_SPACE_MAXADDR,		/* highaddr */
926 	    NULL, NULL,			/* filter, filterarg */
927 	    VR_RX_RING_SIZE,		/* maxsize */
928 	    1,				/* nsegments */
929 	    VR_RX_RING_SIZE,		/* maxsegsize */
930 	    0,				/* flags */
931 	    NULL, NULL,			/* lockfunc, lockarg */
932 	    &sc->vr_cdata.vr_rx_ring_tag);
933 	if (error != 0) {
934 		device_printf(sc->vr_dev, "failed to create Rx ring DMA tag\n");
935 		goto fail;
936 	}
937 
938 	if ((sc->vr_quirks & VR_Q_NEEDALIGN) != 0)
939 		tx_alignment = sizeof(uint32_t);
940 	else
941 		tx_alignment = 1;
942 	/* Create tag for Tx buffers. */
943 	error = bus_dma_tag_create(
944 	    sc->vr_cdata.vr_parent_tag,	/* parent */
945 	    tx_alignment, 0,		/* alignment, boundary */
946 	    BUS_SPACE_MAXADDR,		/* lowaddr */
947 	    BUS_SPACE_MAXADDR,		/* highaddr */
948 	    NULL, NULL,			/* filter, filterarg */
949 	    MCLBYTES * VR_MAXFRAGS,	/* maxsize */
950 	    VR_MAXFRAGS,		/* nsegments */
951 	    MCLBYTES,			/* maxsegsize */
952 	    0,				/* flags */
953 	    NULL, NULL,			/* lockfunc, lockarg */
954 	    &sc->vr_cdata.vr_tx_tag);
955 	if (error != 0) {
956 		device_printf(sc->vr_dev, "failed to create Tx DMA tag\n");
957 		goto fail;
958 	}
959 
960 	/* Create tag for Rx buffers. */
961 	error = bus_dma_tag_create(
962 	    sc->vr_cdata.vr_parent_tag,	/* parent */
963 	    VR_RX_ALIGN, 0,		/* alignment, boundary */
964 	    BUS_SPACE_MAXADDR,		/* lowaddr */
965 	    BUS_SPACE_MAXADDR,		/* highaddr */
966 	    NULL, NULL,			/* filter, filterarg */
967 	    MCLBYTES,			/* maxsize */
968 	    1,				/* nsegments */
969 	    MCLBYTES,			/* maxsegsize */
970 	    0,				/* flags */
971 	    NULL, NULL,			/* lockfunc, lockarg */
972 	    &sc->vr_cdata.vr_rx_tag);
973 	if (error != 0) {
974 		device_printf(sc->vr_dev, "failed to create Rx DMA tag\n");
975 		goto fail;
976 	}
977 
978 	/* Allocate DMA'able memory and load the DMA map for Tx ring. */
979 	error = bus_dmamem_alloc(sc->vr_cdata.vr_tx_ring_tag,
980 	    (void **)&sc->vr_rdata.vr_tx_ring, BUS_DMA_WAITOK |
981 	    BUS_DMA_COHERENT | BUS_DMA_ZERO, &sc->vr_cdata.vr_tx_ring_map);
982 	if (error != 0) {
983 		device_printf(sc->vr_dev,
984 		    "failed to allocate DMA'able memory for Tx ring\n");
985 		goto fail;
986 	}
987 
988 	ctx.vr_busaddr = 0;
989 	error = bus_dmamap_load(sc->vr_cdata.vr_tx_ring_tag,
990 	    sc->vr_cdata.vr_tx_ring_map, sc->vr_rdata.vr_tx_ring,
991 	    VR_TX_RING_SIZE, vr_dmamap_cb, &ctx, 0);
992 	if (error != 0 || ctx.vr_busaddr == 0) {
993 		device_printf(sc->vr_dev,
994 		    "failed to load DMA'able memory for Tx ring\n");
995 		goto fail;
996 	}
997 	sc->vr_rdata.vr_tx_ring_paddr = ctx.vr_busaddr;
998 
999 	/* Allocate DMA'able memory and load the DMA map for Rx ring. */
1000 	error = bus_dmamem_alloc(sc->vr_cdata.vr_rx_ring_tag,
1001 	    (void **)&sc->vr_rdata.vr_rx_ring, BUS_DMA_WAITOK |
1002 	    BUS_DMA_COHERENT | BUS_DMA_ZERO, &sc->vr_cdata.vr_rx_ring_map);
1003 	if (error != 0) {
1004 		device_printf(sc->vr_dev,
1005 		    "failed to allocate DMA'able memory for Rx ring\n");
1006 		goto fail;
1007 	}
1008 
1009 	ctx.vr_busaddr = 0;
1010 	error = bus_dmamap_load(sc->vr_cdata.vr_rx_ring_tag,
1011 	    sc->vr_cdata.vr_rx_ring_map, sc->vr_rdata.vr_rx_ring,
1012 	    VR_RX_RING_SIZE, vr_dmamap_cb, &ctx, 0);
1013 	if (error != 0 || ctx.vr_busaddr == 0) {
1014 		device_printf(sc->vr_dev,
1015 		    "failed to load DMA'able memory for Rx ring\n");
1016 		goto fail;
1017 	}
1018 	sc->vr_rdata.vr_rx_ring_paddr = ctx.vr_busaddr;
1019 
1020 	/* Create DMA maps for Tx buffers. */
1021 	for (i = 0; i < VR_TX_RING_CNT; i++) {
1022 		txd = &sc->vr_cdata.vr_txdesc[i];
1023 		txd->tx_m = NULL;
1024 		txd->tx_dmamap = NULL;
1025 		error = bus_dmamap_create(sc->vr_cdata.vr_tx_tag, 0,
1026 		    &txd->tx_dmamap);
1027 		if (error != 0) {
1028 			device_printf(sc->vr_dev,
1029 			    "failed to create Tx dmamap\n");
1030 			goto fail;
1031 		}
1032 	}
1033 	/* Create DMA maps for Rx buffers. */
1034 	if ((error = bus_dmamap_create(sc->vr_cdata.vr_rx_tag, 0,
1035 	    &sc->vr_cdata.vr_rx_sparemap)) != 0) {
1036 		device_printf(sc->vr_dev,
1037 		    "failed to create spare Rx dmamap\n");
1038 		goto fail;
1039 	}
1040 	for (i = 0; i < VR_RX_RING_CNT; i++) {
1041 		rxd = &sc->vr_cdata.vr_rxdesc[i];
1042 		rxd->rx_m = NULL;
1043 		rxd->rx_dmamap = NULL;
1044 		error = bus_dmamap_create(sc->vr_cdata.vr_rx_tag, 0,
1045 		    &rxd->rx_dmamap);
1046 		if (error != 0) {
1047 			device_printf(sc->vr_dev,
1048 			    "failed to create Rx dmamap\n");
1049 			goto fail;
1050 		}
1051 	}
1052 
1053 fail:
1054 	return (error);
1055 }
1056 
1057 static void
1058 vr_dma_free(struct vr_softc *sc)
1059 {
1060 	struct vr_txdesc	*txd;
1061 	struct vr_rxdesc	*rxd;
1062 	int			i;
1063 
1064 	/* Tx ring. */
1065 	if (sc->vr_cdata.vr_tx_ring_tag) {
1066 		if (sc->vr_rdata.vr_tx_ring_paddr)
1067 			bus_dmamap_unload(sc->vr_cdata.vr_tx_ring_tag,
1068 			    sc->vr_cdata.vr_tx_ring_map);
1069 		if (sc->vr_rdata.vr_tx_ring)
1070 			bus_dmamem_free(sc->vr_cdata.vr_tx_ring_tag,
1071 			    sc->vr_rdata.vr_tx_ring,
1072 			    sc->vr_cdata.vr_tx_ring_map);
1073 		sc->vr_rdata.vr_tx_ring = NULL;
1074 		sc->vr_rdata.vr_tx_ring_paddr = 0;
1075 		bus_dma_tag_destroy(sc->vr_cdata.vr_tx_ring_tag);
1076 		sc->vr_cdata.vr_tx_ring_tag = NULL;
1077 	}
1078 	/* Rx ring. */
1079 	if (sc->vr_cdata.vr_rx_ring_tag) {
1080 		if (sc->vr_rdata.vr_rx_ring_paddr)
1081 			bus_dmamap_unload(sc->vr_cdata.vr_rx_ring_tag,
1082 			    sc->vr_cdata.vr_rx_ring_map);
1083 		if (sc->vr_rdata.vr_rx_ring)
1084 			bus_dmamem_free(sc->vr_cdata.vr_rx_ring_tag,
1085 			    sc->vr_rdata.vr_rx_ring,
1086 			    sc->vr_cdata.vr_rx_ring_map);
1087 		sc->vr_rdata.vr_rx_ring = NULL;
1088 		sc->vr_rdata.vr_rx_ring_paddr = 0;
1089 		bus_dma_tag_destroy(sc->vr_cdata.vr_rx_ring_tag);
1090 		sc->vr_cdata.vr_rx_ring_tag = NULL;
1091 	}
1092 	/* Tx buffers. */
1093 	if (sc->vr_cdata.vr_tx_tag) {
1094 		for (i = 0; i < VR_TX_RING_CNT; i++) {
1095 			txd = &sc->vr_cdata.vr_txdesc[i];
1096 			if (txd->tx_dmamap) {
1097 				bus_dmamap_destroy(sc->vr_cdata.vr_tx_tag,
1098 				    txd->tx_dmamap);
1099 				txd->tx_dmamap = NULL;
1100 			}
1101 		}
1102 		bus_dma_tag_destroy(sc->vr_cdata.vr_tx_tag);
1103 		sc->vr_cdata.vr_tx_tag = NULL;
1104 	}
1105 	/* Rx buffers. */
1106 	if (sc->vr_cdata.vr_rx_tag) {
1107 		for (i = 0; i < VR_RX_RING_CNT; i++) {
1108 			rxd = &sc->vr_cdata.vr_rxdesc[i];
1109 			if (rxd->rx_dmamap) {
1110 				bus_dmamap_destroy(sc->vr_cdata.vr_rx_tag,
1111 				    rxd->rx_dmamap);
1112 				rxd->rx_dmamap = NULL;
1113 			}
1114 		}
1115 		if (sc->vr_cdata.vr_rx_sparemap) {
1116 			bus_dmamap_destroy(sc->vr_cdata.vr_rx_tag,
1117 			    sc->vr_cdata.vr_rx_sparemap);
1118 			sc->vr_cdata.vr_rx_sparemap = 0;
1119 		}
1120 		bus_dma_tag_destroy(sc->vr_cdata.vr_rx_tag);
1121 		sc->vr_cdata.vr_rx_tag = NULL;
1122 	}
1123 
1124 	if (sc->vr_cdata.vr_parent_tag) {
1125 		bus_dma_tag_destroy(sc->vr_cdata.vr_parent_tag);
1126 		sc->vr_cdata.vr_parent_tag = NULL;
1127 	}
1128 }
1129 
1130 /*
1131  * Initialize the transmit descriptors.
1132  */
1133 static int
1134 vr_tx_ring_init(struct vr_softc *sc)
1135 {
1136 	struct vr_ring_data	*rd;
1137 	struct vr_txdesc	*txd;
1138 	bus_addr_t		addr;
1139 	int			i;
1140 
1141 	sc->vr_cdata.vr_tx_prod = 0;
1142 	sc->vr_cdata.vr_tx_cons = 0;
1143 	sc->vr_cdata.vr_tx_cnt = 0;
1144 	sc->vr_cdata.vr_tx_pkts = 0;
1145 
1146 	rd = &sc->vr_rdata;
1147 	bzero(rd->vr_tx_ring, VR_TX_RING_SIZE);
1148 	for (i = 0; i < VR_TX_RING_CNT; i++) {
1149 		if (i == VR_TX_RING_CNT - 1)
1150 			addr = VR_TX_RING_ADDR(sc, 0);
1151 		else
1152 			addr = VR_TX_RING_ADDR(sc, i + 1);
1153 		rd->vr_tx_ring[i].vr_nextphys = htole32(VR_ADDR_LO(addr));
1154 		txd = &sc->vr_cdata.vr_txdesc[i];
1155 		txd->tx_m = NULL;
1156 	}
1157 
1158 	bus_dmamap_sync(sc->vr_cdata.vr_tx_ring_tag,
1159 	    sc->vr_cdata.vr_tx_ring_map,
1160 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1161 
1162 	return (0);
1163 }
1164 
1165 /*
1166  * Initialize the RX descriptors and allocate mbufs for them. Note that
1167  * we arrange the descriptors in a closed ring, so that the last descriptor
1168  * points back to the first.
1169  */
1170 static int
1171 vr_rx_ring_init(struct vr_softc *sc)
1172 {
1173 	struct vr_ring_data	*rd;
1174 	struct vr_rxdesc	*rxd;
1175 	bus_addr_t		addr;
1176 	int			i;
1177 
1178 	sc->vr_cdata.vr_rx_cons = 0;
1179 
1180 	rd = &sc->vr_rdata;
1181 	bzero(rd->vr_rx_ring, VR_RX_RING_SIZE);
1182 	for (i = 0; i < VR_RX_RING_CNT; i++) {
1183 		rxd = &sc->vr_cdata.vr_rxdesc[i];
1184 		rxd->rx_m = NULL;
1185 		rxd->desc = &rd->vr_rx_ring[i];
1186 		if (i == VR_RX_RING_CNT - 1)
1187 			addr = VR_RX_RING_ADDR(sc, 0);
1188 		else
1189 			addr = VR_RX_RING_ADDR(sc, i + 1);
1190 		rd->vr_rx_ring[i].vr_nextphys = htole32(VR_ADDR_LO(addr));
1191 		if (vr_newbuf(sc, i) != 0)
1192 			return (ENOBUFS);
1193 	}
1194 
1195 	bus_dmamap_sync(sc->vr_cdata.vr_rx_ring_tag,
1196 	    sc->vr_cdata.vr_rx_ring_map,
1197 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1198 
1199 	return (0);
1200 }
1201 
1202 static __inline void
1203 vr_discard_rxbuf(struct vr_rxdesc *rxd)
1204 {
1205 	struct vr_desc	*desc;
1206 
1207 	desc = rxd->desc;
1208 	desc->vr_ctl = htole32(VR_RXCTL | (MCLBYTES - sizeof(uint64_t)));
1209 	desc->vr_status = htole32(VR_RXSTAT_OWN);
1210 }
1211 
1212 /*
1213  * Initialize an RX descriptor and attach an MBUF cluster.
1214  * Note: the length fields are only 11 bits wide, which means the
1215  * largest size we can specify is 2047. This is important because
1216  * MCLBYTES is 2048, so we have to subtract one otherwise we'll
1217  * overflow the field and make a mess.
1218  */
1219 static int
1220 vr_newbuf(struct vr_softc *sc, int idx)
1221 {
1222 	struct vr_desc		*desc;
1223 	struct vr_rxdesc	*rxd;
1224 	struct mbuf		*m;
1225 	bus_dma_segment_t	segs[1];
1226 	bus_dmamap_t		map;
1227 	int			nsegs;
1228 
1229 	m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1230 	if (m == NULL)
1231 		return (ENOBUFS);
1232 	m->m_len = m->m_pkthdr.len = MCLBYTES;
1233 	m_adj(m, sizeof(uint64_t));
1234 
1235 	if (bus_dmamap_load_mbuf_sg(sc->vr_cdata.vr_rx_tag,
1236 	    sc->vr_cdata.vr_rx_sparemap, m, segs, &nsegs, 0) != 0) {
1237 		m_freem(m);
1238 		return (ENOBUFS);
1239 	}
1240 	KASSERT(nsegs == 1, ("%s: %d segments returned!", __func__, nsegs));
1241 
1242 	rxd = &sc->vr_cdata.vr_rxdesc[idx];
1243 	if (rxd->rx_m != NULL) {
1244 		bus_dmamap_sync(sc->vr_cdata.vr_rx_tag, rxd->rx_dmamap,
1245 		    BUS_DMASYNC_POSTREAD);
1246 		bus_dmamap_unload(sc->vr_cdata.vr_rx_tag, rxd->rx_dmamap);
1247 	}
1248 	map = rxd->rx_dmamap;
1249 	rxd->rx_dmamap = sc->vr_cdata.vr_rx_sparemap;
1250 	sc->vr_cdata.vr_rx_sparemap = map;
1251 	bus_dmamap_sync(sc->vr_cdata.vr_rx_tag, rxd->rx_dmamap,
1252 	    BUS_DMASYNC_PREREAD);
1253 	rxd->rx_m = m;
1254 	desc = rxd->desc;
1255 	desc->vr_data = htole32(VR_ADDR_LO(segs[0].ds_addr));
1256 	desc->vr_ctl = htole32(VR_RXCTL | segs[0].ds_len);
1257 	desc->vr_status = htole32(VR_RXSTAT_OWN);
1258 
1259 	return (0);
1260 }
1261 
1262 #ifndef __NO_STRICT_ALIGNMENT
1263 static __inline void
1264 vr_fixup_rx(struct mbuf *m)
1265 {
1266         uint16_t		*src, *dst;
1267         int			i;
1268 
1269 	src = mtod(m, uint16_t *);
1270 	dst = src - 1;
1271 
1272 	for (i = 0; i < (m->m_len / sizeof(uint16_t) + 1); i++)
1273 		*dst++ = *src++;
1274 
1275 	m->m_data -= ETHER_ALIGN;
1276 }
1277 #endif
1278 
1279 /*
1280  * A frame has been uploaded: pass the resulting mbuf chain up to
1281  * the higher level protocols.
1282  */
1283 static int
1284 vr_rxeof(struct vr_softc *sc)
1285 {
1286 	struct vr_rxdesc	*rxd;
1287 	struct mbuf		*m;
1288 	if_t			ifp;
1289 	struct vr_desc		*cur_rx;
1290 	int			cons, prog, total_len, rx_npkts;
1291 	uint32_t		rxstat, rxctl;
1292 
1293 	VR_LOCK_ASSERT(sc);
1294 	ifp = sc->vr_ifp;
1295 	cons = sc->vr_cdata.vr_rx_cons;
1296 	rx_npkts = 0;
1297 
1298 	bus_dmamap_sync(sc->vr_cdata.vr_rx_ring_tag,
1299 	    sc->vr_cdata.vr_rx_ring_map,
1300 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1301 
1302 	for (prog = 0; prog < VR_RX_RING_CNT; VR_INC(cons, VR_RX_RING_CNT)) {
1303 #ifdef DEVICE_POLLING
1304 		if (if_getcapenable(ifp) & IFCAP_POLLING) {
1305 			if (sc->rxcycles <= 0)
1306 				break;
1307 			sc->rxcycles--;
1308 		}
1309 #endif
1310 		cur_rx = &sc->vr_rdata.vr_rx_ring[cons];
1311 		rxstat = le32toh(cur_rx->vr_status);
1312 		rxctl = le32toh(cur_rx->vr_ctl);
1313 		if ((rxstat & VR_RXSTAT_OWN) == VR_RXSTAT_OWN)
1314 			break;
1315 
1316 		prog++;
1317 		rxd = &sc->vr_cdata.vr_rxdesc[cons];
1318 		m = rxd->rx_m;
1319 
1320 		/*
1321 		 * If an error occurs, update stats, clear the
1322 		 * status word and leave the mbuf cluster in place:
1323 		 * it should simply get re-used next time this descriptor
1324 		 * comes up in the ring.
1325 		 * We don't support SG in Rx path yet, so discard
1326 		 * partial frame.
1327 		 */
1328 		if ((rxstat & VR_RXSTAT_RX_OK) == 0 ||
1329 		    (rxstat & (VR_RXSTAT_FIRSTFRAG | VR_RXSTAT_LASTFRAG)) !=
1330 		    (VR_RXSTAT_FIRSTFRAG | VR_RXSTAT_LASTFRAG)) {
1331 			if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
1332 			sc->vr_stat.rx_errors++;
1333 			if (rxstat & VR_RXSTAT_CRCERR)
1334 				sc->vr_stat.rx_crc_errors++;
1335 			if (rxstat & VR_RXSTAT_FRAMEALIGNERR)
1336 				sc->vr_stat.rx_alignment++;
1337 			if (rxstat & VR_RXSTAT_FIFOOFLOW)
1338 				sc->vr_stat.rx_fifo_overflows++;
1339 			if (rxstat & VR_RXSTAT_GIANT)
1340 				sc->vr_stat.rx_giants++;
1341 			if (rxstat & VR_RXSTAT_RUNT)
1342 				sc->vr_stat.rx_runts++;
1343 			if (rxstat & VR_RXSTAT_BUFFERR)
1344 				sc->vr_stat.rx_no_buffers++;
1345 #ifdef	VR_SHOW_ERRORS
1346 			device_printf(sc->vr_dev, "%s: receive error = 0x%b\n",
1347 			    __func__, rxstat & 0xff, VR_RXSTAT_ERR_BITS);
1348 #endif
1349 			vr_discard_rxbuf(rxd);
1350 			continue;
1351 		}
1352 
1353 		if (vr_newbuf(sc, cons) != 0) {
1354 			if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
1355 			sc->vr_stat.rx_errors++;
1356 			sc->vr_stat.rx_no_mbufs++;
1357 			vr_discard_rxbuf(rxd);
1358 			continue;
1359 		}
1360 
1361 		/*
1362 		 * XXX The VIA Rhine chip includes the CRC with every
1363 		 * received frame, and there's no way to turn this
1364 		 * behavior off (at least, I can't find anything in
1365 		 * the manual that explains how to do it) so we have
1366 		 * to trim off the CRC manually.
1367 		 */
1368 		total_len = VR_RXBYTES(rxstat);
1369 		total_len -= ETHER_CRC_LEN;
1370 		m->m_pkthdr.len = m->m_len = total_len;
1371 #ifndef	__NO_STRICT_ALIGNMENT
1372 		/*
1373 		 * RX buffers must be 32-bit aligned.
1374 		 * Ignore the alignment problems on the non-strict alignment
1375 		 * platform. The performance hit incurred due to unaligned
1376 		 * accesses is much smaller than the hit produced by forcing
1377 		 * buffer copies all the time.
1378 		 */
1379 		vr_fixup_rx(m);
1380 #endif
1381 		m->m_pkthdr.rcvif = ifp;
1382 		if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
1383 		sc->vr_stat.rx_ok++;
1384 		if ((if_getcapenable(ifp) & IFCAP_RXCSUM) != 0 &&
1385 		    (rxstat & VR_RXSTAT_FRAG) == 0 &&
1386 		    (rxctl & VR_RXCTL_IP) != 0) {
1387 			/* Checksum is valid for non-fragmented IP packets. */
1388 			m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
1389 			if ((rxctl & VR_RXCTL_IPOK) == VR_RXCTL_IPOK) {
1390 				m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1391 				if (rxctl & (VR_RXCTL_TCP | VR_RXCTL_UDP)) {
1392 					m->m_pkthdr.csum_flags |=
1393 					    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1394 					if ((rxctl & VR_RXCTL_TCPUDPOK) != 0)
1395 						m->m_pkthdr.csum_data = 0xffff;
1396 				}
1397 			}
1398 		}
1399 		VR_UNLOCK(sc);
1400 		if_input(ifp, m);
1401 		VR_LOCK(sc);
1402 		rx_npkts++;
1403 	}
1404 
1405 	if (prog > 0) {
1406 		/*
1407 		 * Let controller know how many number of RX buffers
1408 		 * are posted but avoid expensive register access if
1409 		 * TX pause capability was not negotiated with link
1410 		 * partner.
1411 		 */
1412 		if ((sc->vr_flags & VR_F_TXPAUSE) != 0) {
1413 			if (prog >= VR_RX_RING_CNT)
1414 				prog = VR_RX_RING_CNT - 1;
1415 			CSR_WRITE_1(sc, VR_FLOWCR0, prog);
1416 		}
1417 		sc->vr_cdata.vr_rx_cons = cons;
1418 		bus_dmamap_sync(sc->vr_cdata.vr_rx_ring_tag,
1419 		    sc->vr_cdata.vr_rx_ring_map,
1420 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1421 	}
1422 	return (rx_npkts);
1423 }
1424 
1425 /*
1426  * A frame was downloaded to the chip. It's safe for us to clean up
1427  * the list buffers.
1428  */
1429 static void
1430 vr_txeof(struct vr_softc *sc)
1431 {
1432 	struct vr_txdesc	*txd;
1433 	struct vr_desc		*cur_tx;
1434 	if_t			ifp;
1435 	uint32_t		txctl, txstat;
1436 	int			cons, prod;
1437 
1438 	VR_LOCK_ASSERT(sc);
1439 
1440 	cons = sc->vr_cdata.vr_tx_cons;
1441 	prod = sc->vr_cdata.vr_tx_prod;
1442 	if (cons == prod)
1443 		return;
1444 
1445 	bus_dmamap_sync(sc->vr_cdata.vr_tx_ring_tag,
1446 	    sc->vr_cdata.vr_tx_ring_map,
1447 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1448 
1449 	ifp = sc->vr_ifp;
1450 	/*
1451 	 * Go through our tx list and free mbufs for those
1452 	 * frames that have been transmitted.
1453 	 */
1454 	for (; cons != prod; VR_INC(cons, VR_TX_RING_CNT)) {
1455 		cur_tx = &sc->vr_rdata.vr_tx_ring[cons];
1456 		txctl = le32toh(cur_tx->vr_ctl);
1457 		txstat = le32toh(cur_tx->vr_status);
1458 		if ((txstat & VR_TXSTAT_OWN) == VR_TXSTAT_OWN)
1459 			break;
1460 
1461 		sc->vr_cdata.vr_tx_cnt--;
1462 		if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
1463 		/* Only the first descriptor in the chain is valid. */
1464 		if ((txctl & VR_TXCTL_FIRSTFRAG) == 0)
1465 			continue;
1466 
1467 		txd = &sc->vr_cdata.vr_txdesc[cons];
1468 		KASSERT(txd->tx_m != NULL, ("%s: accessing NULL mbuf!\n",
1469 		    __func__));
1470 
1471 		if ((txstat & VR_TXSTAT_ERRSUM) != 0) {
1472 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1473 			sc->vr_stat.tx_errors++;
1474 			if ((txstat & VR_TXSTAT_ABRT) != 0) {
1475 				/* Give up and restart Tx. */
1476 				sc->vr_stat.tx_abort++;
1477 				bus_dmamap_sync(sc->vr_cdata.vr_tx_tag,
1478 				    txd->tx_dmamap, BUS_DMASYNC_POSTWRITE);
1479 				bus_dmamap_unload(sc->vr_cdata.vr_tx_tag,
1480 				    txd->tx_dmamap);
1481 				m_freem(txd->tx_m);
1482 				txd->tx_m = NULL;
1483 				VR_INC(cons, VR_TX_RING_CNT);
1484 				sc->vr_cdata.vr_tx_cons = cons;
1485 				if (vr_tx_stop(sc) != 0) {
1486 					device_printf(sc->vr_dev,
1487 					    "%s: Tx shutdown error -- "
1488 					    "resetting\n", __func__);
1489 					sc->vr_flags |= VR_F_RESTART;
1490 					return;
1491 				}
1492 				vr_tx_start(sc);
1493 				break;
1494 			}
1495 			if ((sc->vr_revid < REV_ID_VT3071_A &&
1496 			    (txstat & VR_TXSTAT_UNDERRUN)) ||
1497 			    (txstat & (VR_TXSTAT_UDF | VR_TXSTAT_TBUFF))) {
1498 				sc->vr_stat.tx_underrun++;
1499 				/* Retry and restart Tx. */
1500 				sc->vr_cdata.vr_tx_cnt++;
1501 				sc->vr_cdata.vr_tx_cons = cons;
1502 				cur_tx->vr_status = htole32(VR_TXSTAT_OWN);
1503 				bus_dmamap_sync(sc->vr_cdata.vr_tx_ring_tag,
1504 				    sc->vr_cdata.vr_tx_ring_map,
1505 				    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1506 				vr_tx_underrun(sc);
1507 				return;
1508 			}
1509 			if ((txstat & VR_TXSTAT_DEFER) != 0) {
1510 				if_inc_counter(ifp, IFCOUNTER_COLLISIONS, 1);
1511 				sc->vr_stat.tx_collisions++;
1512 			}
1513 			if ((txstat & VR_TXSTAT_LATECOLL) != 0) {
1514 				if_inc_counter(ifp, IFCOUNTER_COLLISIONS, 1);
1515 				sc->vr_stat.tx_late_collisions++;
1516 			}
1517 		} else {
1518 			sc->vr_stat.tx_ok++;
1519 			if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1520 		}
1521 
1522 		bus_dmamap_sync(sc->vr_cdata.vr_tx_tag, txd->tx_dmamap,
1523 		    BUS_DMASYNC_POSTWRITE);
1524 		bus_dmamap_unload(sc->vr_cdata.vr_tx_tag, txd->tx_dmamap);
1525 		if (sc->vr_revid < REV_ID_VT3071_A) {
1526 			if_inc_counter(ifp, IFCOUNTER_COLLISIONS,
1527 			    (txstat & VR_TXSTAT_COLLCNT) >> 3);
1528 			sc->vr_stat.tx_collisions +=
1529 			    (txstat & VR_TXSTAT_COLLCNT) >> 3;
1530 		} else {
1531 			if_inc_counter(ifp, IFCOUNTER_COLLISIONS, (txstat & 0x0f));
1532 			sc->vr_stat.tx_collisions += (txstat & 0x0f);
1533 		}
1534 		m_freem(txd->tx_m);
1535 		txd->tx_m = NULL;
1536 	}
1537 
1538 	sc->vr_cdata.vr_tx_cons = cons;
1539 	if (sc->vr_cdata.vr_tx_cnt == 0)
1540 		sc->vr_watchdog_timer = 0;
1541 }
1542 
1543 static void
1544 vr_tick(void *xsc)
1545 {
1546 	struct vr_softc		*sc;
1547 	struct mii_data		*mii;
1548 
1549 	sc = (struct vr_softc *)xsc;
1550 
1551 	VR_LOCK_ASSERT(sc);
1552 
1553 	if ((sc->vr_flags & VR_F_RESTART) != 0) {
1554 		device_printf(sc->vr_dev, "restarting\n");
1555 		sc->vr_stat.num_restart++;
1556 		if_setdrvflagbits(sc->vr_ifp, 0, IFF_DRV_RUNNING);
1557 		vr_init_locked(sc);
1558 		sc->vr_flags &= ~VR_F_RESTART;
1559 	}
1560 
1561 	mii = device_get_softc(sc->vr_miibus);
1562 	mii_tick(mii);
1563 	if ((sc->vr_flags & VR_F_LINK) == 0)
1564 		vr_miibus_statchg(sc->vr_dev);
1565 	vr_watchdog(sc);
1566 	callout_reset(&sc->vr_stat_callout, hz, vr_tick, sc);
1567 }
1568 
1569 #ifdef DEVICE_POLLING
1570 static poll_handler_t vr_poll;
1571 static poll_handler_t vr_poll_locked;
1572 
1573 static int
1574 vr_poll(if_t ifp, enum poll_cmd cmd, int count)
1575 {
1576 	struct vr_softc *sc;
1577 	int rx_npkts;
1578 
1579 	sc = if_getsoftc(ifp);
1580 	rx_npkts = 0;
1581 
1582 	VR_LOCK(sc);
1583 	if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) != 0)
1584 		rx_npkts = vr_poll_locked(ifp, cmd, count);
1585 	VR_UNLOCK(sc);
1586 	return (rx_npkts);
1587 }
1588 
1589 static int
1590 vr_poll_locked(if_t ifp, enum poll_cmd cmd, int count)
1591 {
1592 	struct vr_softc *sc;
1593 	int rx_npkts;
1594 
1595 	sc = if_getsoftc(ifp);
1596 
1597 	VR_LOCK_ASSERT(sc);
1598 
1599 	sc->rxcycles = count;
1600 	rx_npkts = vr_rxeof(sc);
1601 	vr_txeof(sc);
1602 	if (!if_sendq_empty(ifp))
1603 		vr_start_locked(ifp);
1604 
1605 	if (cmd == POLL_AND_CHECK_STATUS) {
1606 		uint16_t status;
1607 
1608 		/* Also check status register. */
1609 		status = CSR_READ_2(sc, VR_ISR);
1610 		if (status)
1611 			CSR_WRITE_2(sc, VR_ISR, status);
1612 
1613 		if ((status & VR_INTRS) == 0)
1614 			return (rx_npkts);
1615 
1616 		if ((status & (VR_ISR_BUSERR | VR_ISR_LINKSTAT2 |
1617 		    VR_ISR_STATSOFLOW)) != 0) {
1618 			if (vr_error(sc, status) != 0)
1619 				return (rx_npkts);
1620 		}
1621 		if ((status & (VR_ISR_RX_NOBUF | VR_ISR_RX_OFLOW)) != 0) {
1622 #ifdef	VR_SHOW_ERRORS
1623 			device_printf(sc->vr_dev, "%s: receive error : 0x%b\n",
1624 			    __func__, status, VR_ISR_ERR_BITS);
1625 #endif
1626 			vr_rx_start(sc);
1627 		}
1628 	}
1629 	return (rx_npkts);
1630 }
1631 #endif /* DEVICE_POLLING */
1632 
1633 /* Back off the transmit threshold. */
1634 static void
1635 vr_tx_underrun(struct vr_softc *sc)
1636 {
1637 	int	thresh;
1638 
1639 	device_printf(sc->vr_dev, "Tx underrun -- ");
1640 	if (sc->vr_txthresh < VR_TXTHRESH_MAX) {
1641 		thresh = sc->vr_txthresh;
1642 		sc->vr_txthresh++;
1643 		if (sc->vr_txthresh >= VR_TXTHRESH_MAX) {
1644 			sc->vr_txthresh = VR_TXTHRESH_MAX;
1645 			printf("using store and forward mode\n");
1646 		} else
1647 			printf("increasing Tx threshold(%d -> %d)\n",
1648 			    vr_tx_threshold_tables[thresh].value,
1649 			    vr_tx_threshold_tables[thresh + 1].value);
1650 	} else
1651 		printf("\n");
1652 	sc->vr_stat.tx_underrun++;
1653 	if (vr_tx_stop(sc) != 0) {
1654 		device_printf(sc->vr_dev, "%s: Tx shutdown error -- "
1655 		    "resetting\n", __func__);
1656 		sc->vr_flags |= VR_F_RESTART;
1657 		return;
1658 	}
1659 	vr_tx_start(sc);
1660 }
1661 
1662 static int
1663 vr_intr(void *arg)
1664 {
1665 	struct vr_softc		*sc;
1666 	uint16_t		status;
1667 
1668 	sc = (struct vr_softc *)arg;
1669 
1670 	status = CSR_READ_2(sc, VR_ISR);
1671 	if (status == 0 || status == 0xffff || (status & VR_INTRS) == 0)
1672 		return (FILTER_STRAY);
1673 
1674 	/* Disable interrupts. */
1675 	CSR_WRITE_2(sc, VR_IMR, 0x0000);
1676 
1677 	taskqueue_enqueue(taskqueue_fast, &sc->vr_inttask);
1678 
1679 	return (FILTER_HANDLED);
1680 }
1681 
1682 static void
1683 vr_int_task(void *arg, int npending)
1684 {
1685 	struct vr_softc		*sc;
1686 	if_t			ifp;
1687 	uint16_t		status;
1688 
1689 	sc = (struct vr_softc *)arg;
1690 
1691 	VR_LOCK(sc);
1692 
1693 	if ((sc->vr_flags & VR_F_SUSPENDED) != 0)
1694 		goto done_locked;
1695 
1696 	status = CSR_READ_2(sc, VR_ISR);
1697 	ifp = sc->vr_ifp;
1698 #ifdef DEVICE_POLLING
1699 	if ((if_getcapenable(ifp) & IFCAP_POLLING) != 0)
1700 		goto done_locked;
1701 #endif
1702 
1703 	/* Suppress unwanted interrupts. */
1704 	if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0 ||
1705 	    (sc->vr_flags & VR_F_RESTART) != 0) {
1706 		CSR_WRITE_2(sc, VR_IMR, 0);
1707 		CSR_WRITE_2(sc, VR_ISR, status);
1708 		goto done_locked;
1709 	}
1710 
1711 	for (; (status & VR_INTRS) != 0;) {
1712 		CSR_WRITE_2(sc, VR_ISR, status);
1713 		if ((status & (VR_ISR_BUSERR | VR_ISR_LINKSTAT2 |
1714 		    VR_ISR_STATSOFLOW)) != 0) {
1715 			if (vr_error(sc, status) != 0) {
1716 				VR_UNLOCK(sc);
1717 				return;
1718 			}
1719 		}
1720 		vr_rxeof(sc);
1721 		if ((status & (VR_ISR_RX_NOBUF | VR_ISR_RX_OFLOW)) != 0) {
1722 #ifdef	VR_SHOW_ERRORS
1723 			device_printf(sc->vr_dev, "%s: receive error = 0x%b\n",
1724 			    __func__, status, VR_ISR_ERR_BITS);
1725 #endif
1726 			/* Restart Rx if RxDMA SM was stopped. */
1727 			vr_rx_start(sc);
1728 		}
1729 		vr_txeof(sc);
1730 
1731 		if (!if_sendq_empty(ifp))
1732 			vr_start_locked(ifp);
1733 
1734 		status = CSR_READ_2(sc, VR_ISR);
1735 	}
1736 
1737 	/* Re-enable interrupts. */
1738 	CSR_WRITE_2(sc, VR_IMR, VR_INTRS);
1739 
1740 done_locked:
1741 	VR_UNLOCK(sc);
1742 }
1743 
1744 static int
1745 vr_error(struct vr_softc *sc, uint16_t status)
1746 {
1747 	uint16_t pcis;
1748 
1749 	status &= VR_ISR_BUSERR | VR_ISR_LINKSTAT2 | VR_ISR_STATSOFLOW;
1750 	if ((status & VR_ISR_BUSERR) != 0) {
1751 		status &= ~VR_ISR_BUSERR;
1752 		sc->vr_stat.bus_errors++;
1753 		/* Disable further interrupts. */
1754 		CSR_WRITE_2(sc, VR_IMR, 0);
1755 		pcis = pci_read_config(sc->vr_dev, PCIR_STATUS, 2);
1756 		device_printf(sc->vr_dev, "PCI bus error(0x%04x) -- "
1757 		    "resetting\n", pcis);
1758 		pci_write_config(sc->vr_dev, PCIR_STATUS, pcis, 2);
1759 		sc->vr_flags |= VR_F_RESTART;
1760 		return (EAGAIN);
1761 	}
1762 	if ((status & VR_ISR_LINKSTAT2) != 0) {
1763 		/* Link state change, duplex changes etc. */
1764 		status &= ~VR_ISR_LINKSTAT2;
1765 	}
1766 	if ((status & VR_ISR_STATSOFLOW) != 0) {
1767 		status &= ~VR_ISR_STATSOFLOW;
1768 		if (sc->vr_revid >= REV_ID_VT6105M_A0) {
1769 			/* Update MIB counters. */
1770 		}
1771 	}
1772 
1773 	if (status != 0)
1774 		device_printf(sc->vr_dev,
1775 		    "unhandled interrupt, status = 0x%04x\n", status);
1776 	return (0);
1777 }
1778 
1779 /*
1780  * Encapsulate an mbuf chain in a descriptor by coupling the mbuf data
1781  * pointers to the fragment pointers.
1782  */
1783 static int
1784 vr_encap(struct vr_softc *sc, struct mbuf **m_head)
1785 {
1786 	struct vr_txdesc	*txd;
1787 	struct vr_desc		*desc;
1788 	struct mbuf		*m;
1789 	bus_dma_segment_t	txsegs[VR_MAXFRAGS];
1790 	uint32_t		csum_flags, txctl;
1791 	int			error, i, nsegs, prod, si;
1792 	int			padlen;
1793 
1794 	VR_LOCK_ASSERT(sc);
1795 
1796 	M_ASSERTPKTHDR((*m_head));
1797 
1798 	/*
1799 	 * Some VIA Rhine wants packet buffers to be longword
1800 	 * aligned, but very often our mbufs aren't. Rather than
1801 	 * waste time trying to decide when to copy and when not
1802 	 * to copy, just do it all the time.
1803 	 */
1804 	if ((sc->vr_quirks & VR_Q_NEEDALIGN) != 0) {
1805 		m = m_defrag(*m_head, M_NOWAIT);
1806 		if (m == NULL) {
1807 			m_freem(*m_head);
1808 			*m_head = NULL;
1809 			return (ENOBUFS);
1810 		}
1811 		*m_head = m;
1812 	}
1813 
1814 	/*
1815 	 * The Rhine chip doesn't auto-pad, so we have to make
1816 	 * sure to pad short frames out to the minimum frame length
1817 	 * ourselves.
1818 	 */
1819 	if ((*m_head)->m_pkthdr.len < VR_MIN_FRAMELEN) {
1820 		m = *m_head;
1821 		padlen = VR_MIN_FRAMELEN - m->m_pkthdr.len;
1822 		if (M_WRITABLE(m) == 0) {
1823 			/* Get a writable copy. */
1824 			m = m_dup(*m_head, M_NOWAIT);
1825 			m_freem(*m_head);
1826 			if (m == NULL) {
1827 				*m_head = NULL;
1828 				return (ENOBUFS);
1829 			}
1830 			*m_head = m;
1831 		}
1832 		if (m->m_next != NULL || M_TRAILINGSPACE(m) < padlen) {
1833 			m = m_defrag(m, M_NOWAIT);
1834 			if (m == NULL) {
1835 				m_freem(*m_head);
1836 				*m_head = NULL;
1837 				return (ENOBUFS);
1838 			}
1839 		}
1840 		/*
1841 		 * Manually pad short frames, and zero the pad space
1842 		 * to avoid leaking data.
1843 		 */
1844 		bzero(mtod(m, char *) + m->m_pkthdr.len, padlen);
1845 		m->m_pkthdr.len += padlen;
1846 		m->m_len = m->m_pkthdr.len;
1847 		*m_head = m;
1848 	}
1849 
1850 	prod = sc->vr_cdata.vr_tx_prod;
1851 	txd = &sc->vr_cdata.vr_txdesc[prod];
1852 	error = bus_dmamap_load_mbuf_sg(sc->vr_cdata.vr_tx_tag, txd->tx_dmamap,
1853 	    *m_head, txsegs, &nsegs, BUS_DMA_NOWAIT);
1854 	if (error == EFBIG) {
1855 		m = m_collapse(*m_head, M_NOWAIT, VR_MAXFRAGS);
1856 		if (m == NULL) {
1857 			m_freem(*m_head);
1858 			*m_head = NULL;
1859 			return (ENOBUFS);
1860 		}
1861 		*m_head = m;
1862 		error = bus_dmamap_load_mbuf_sg(sc->vr_cdata.vr_tx_tag,
1863 		    txd->tx_dmamap, *m_head, txsegs, &nsegs, BUS_DMA_NOWAIT);
1864 		if (error != 0) {
1865 			m_freem(*m_head);
1866 			*m_head = NULL;
1867 			return (error);
1868 		}
1869 	} else if (error != 0)
1870 		return (error);
1871 	if (nsegs == 0) {
1872 		m_freem(*m_head);
1873 		*m_head = NULL;
1874 		return (EIO);
1875 	}
1876 
1877 	/* Check number of available descriptors. */
1878 	if (sc->vr_cdata.vr_tx_cnt + nsegs >= (VR_TX_RING_CNT - 1)) {
1879 		bus_dmamap_unload(sc->vr_cdata.vr_tx_tag, txd->tx_dmamap);
1880 		return (ENOBUFS);
1881 	}
1882 
1883 	txd->tx_m = *m_head;
1884 	bus_dmamap_sync(sc->vr_cdata.vr_tx_tag, txd->tx_dmamap,
1885 	    BUS_DMASYNC_PREWRITE);
1886 
1887 	/* Set checksum offload. */
1888 	csum_flags = 0;
1889 	if (((*m_head)->m_pkthdr.csum_flags & VR_CSUM_FEATURES) != 0) {
1890 		if ((*m_head)->m_pkthdr.csum_flags & CSUM_IP)
1891 			csum_flags |= VR_TXCTL_IPCSUM;
1892 		if ((*m_head)->m_pkthdr.csum_flags & CSUM_TCP)
1893 			csum_flags |= VR_TXCTL_TCPCSUM;
1894 		if ((*m_head)->m_pkthdr.csum_flags & CSUM_UDP)
1895 			csum_flags |= VR_TXCTL_UDPCSUM;
1896 	}
1897 
1898 	/*
1899 	 * Quite contrary to datasheet for VIA Rhine, VR_TXCTL_TLINK bit
1900 	 * is required for all descriptors regardless of single or
1901 	 * multiple buffers. Also VR_TXSTAT_OWN bit is valid only for
1902 	 * the first descriptor for a multi-fragmented frames. Without
1903 	 * that VIA Rhine chip generates Tx underrun interrupts and can't
1904 	 * send any frames.
1905 	 */
1906 	si = prod;
1907 	for (i = 0; i < nsegs; i++) {
1908 		desc = &sc->vr_rdata.vr_tx_ring[prod];
1909 		desc->vr_status = 0;
1910 		txctl = txsegs[i].ds_len | VR_TXCTL_TLINK | csum_flags;
1911 		if (i == 0)
1912 			txctl |= VR_TXCTL_FIRSTFRAG;
1913 		desc->vr_ctl = htole32(txctl);
1914 		desc->vr_data = htole32(VR_ADDR_LO(txsegs[i].ds_addr));
1915 		sc->vr_cdata.vr_tx_cnt++;
1916 		VR_INC(prod, VR_TX_RING_CNT);
1917 	}
1918 	/* Update producer index. */
1919 	sc->vr_cdata.vr_tx_prod = prod;
1920 
1921 	prod = (prod + VR_TX_RING_CNT - 1) % VR_TX_RING_CNT;
1922 	desc = &sc->vr_rdata.vr_tx_ring[prod];
1923 
1924 	/*
1925 	 * Set EOP on the last descriptor and request Tx completion
1926 	 * interrupt for every VR_TX_INTR_THRESH-th frames.
1927 	 */
1928 	VR_INC(sc->vr_cdata.vr_tx_pkts, VR_TX_INTR_THRESH);
1929 	if (sc->vr_cdata.vr_tx_pkts == 0)
1930 		desc->vr_ctl |= htole32(VR_TXCTL_LASTFRAG | VR_TXCTL_FINT);
1931 	else
1932 		desc->vr_ctl |= htole32(VR_TXCTL_LASTFRAG);
1933 
1934 	/* Lastly turn the first descriptor ownership to hardware. */
1935 	desc = &sc->vr_rdata.vr_tx_ring[si];
1936 	desc->vr_status |= htole32(VR_TXSTAT_OWN);
1937 
1938 	/* Sync descriptors. */
1939 	bus_dmamap_sync(sc->vr_cdata.vr_tx_ring_tag,
1940 	    sc->vr_cdata.vr_tx_ring_map,
1941 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1942 
1943 	return (0);
1944 }
1945 
1946 static void
1947 vr_start(if_t ifp)
1948 {
1949 	struct vr_softc		*sc;
1950 
1951 	sc = if_getsoftc(ifp);
1952 	VR_LOCK(sc);
1953 	vr_start_locked(ifp);
1954 	VR_UNLOCK(sc);
1955 }
1956 
1957 static void
1958 vr_start_locked(if_t ifp)
1959 {
1960 	struct vr_softc		*sc;
1961 	struct mbuf		*m_head;
1962 	int			enq;
1963 
1964 	sc = if_getsoftc(ifp);
1965 
1966 	VR_LOCK_ASSERT(sc);
1967 
1968 	if ((if_getdrvflags(ifp) & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
1969 	    IFF_DRV_RUNNING || (sc->vr_flags & VR_F_LINK) == 0)
1970 		return;
1971 
1972 	for (enq = 0; !if_sendq_empty(ifp) &&
1973 	    sc->vr_cdata.vr_tx_cnt < VR_TX_RING_CNT - 2; ) {
1974 		m_head = if_dequeue(ifp);
1975 		if (m_head == NULL)
1976 			break;
1977 		/*
1978 		 * Pack the data into the transmit ring. If we
1979 		 * don't have room, set the OACTIVE flag and wait
1980 		 * for the NIC to drain the ring.
1981 		 */
1982 		if (vr_encap(sc, &m_head)) {
1983 			if (m_head == NULL)
1984 				break;
1985 			if_sendq_prepend(ifp, m_head);
1986 			if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
1987 			break;
1988 		}
1989 
1990 		enq++;
1991 		/*
1992 		 * If there's a BPF listener, bounce a copy of this frame
1993 		 * to him.
1994 		 */
1995 		ETHER_BPF_MTAP(ifp, m_head);
1996 	}
1997 
1998 	if (enq > 0) {
1999 		/* Tell the chip to start transmitting. */
2000 		VR_SETBIT(sc, VR_CR0, VR_CR0_TX_GO);
2001 		/* Set a timeout in case the chip goes out to lunch. */
2002 		sc->vr_watchdog_timer = 5;
2003 	}
2004 }
2005 
2006 static void
2007 vr_init(void *xsc)
2008 {
2009 	struct vr_softc		*sc;
2010 
2011 	sc = (struct vr_softc *)xsc;
2012 	VR_LOCK(sc);
2013 	vr_init_locked(sc);
2014 	VR_UNLOCK(sc);
2015 }
2016 
2017 static void
2018 vr_init_locked(struct vr_softc *sc)
2019 {
2020 	if_t			ifp;
2021 	struct mii_data		*mii;
2022 	bus_addr_t		addr;
2023 	int			i;
2024 
2025 	VR_LOCK_ASSERT(sc);
2026 
2027 	ifp = sc->vr_ifp;
2028 	mii = device_get_softc(sc->vr_miibus);
2029 
2030 	if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) != 0)
2031 		return;
2032 
2033 	/* Cancel pending I/O and free all RX/TX buffers. */
2034 	vr_stop(sc);
2035 	vr_reset(sc);
2036 
2037 	/* Set our station address. */
2038 	for (i = 0; i < ETHER_ADDR_LEN; i++)
2039 		CSR_WRITE_1(sc, VR_PAR0 + i, if_getlladdr(sc->vr_ifp)[i]);
2040 
2041 	/* Set DMA size. */
2042 	VR_CLRBIT(sc, VR_BCR0, VR_BCR0_DMA_LENGTH);
2043 	VR_SETBIT(sc, VR_BCR0, VR_BCR0_DMA_STORENFWD);
2044 
2045 	/*
2046 	 * BCR0 and BCR1 can override the RXCFG and TXCFG registers,
2047 	 * so we must set both.
2048 	 */
2049 	VR_CLRBIT(sc, VR_BCR0, VR_BCR0_RX_THRESH);
2050 	VR_SETBIT(sc, VR_BCR0, VR_BCR0_RXTHRESH128BYTES);
2051 
2052 	VR_CLRBIT(sc, VR_BCR1, VR_BCR1_TX_THRESH);
2053 	VR_SETBIT(sc, VR_BCR1, vr_tx_threshold_tables[sc->vr_txthresh].bcr_cfg);
2054 
2055 	VR_CLRBIT(sc, VR_RXCFG, VR_RXCFG_RX_THRESH);
2056 	VR_SETBIT(sc, VR_RXCFG, VR_RXTHRESH_128BYTES);
2057 
2058 	VR_CLRBIT(sc, VR_TXCFG, VR_TXCFG_TX_THRESH);
2059 	VR_SETBIT(sc, VR_TXCFG, vr_tx_threshold_tables[sc->vr_txthresh].tx_cfg);
2060 
2061 	/* Init circular RX list. */
2062 	if (vr_rx_ring_init(sc) != 0) {
2063 		device_printf(sc->vr_dev,
2064 		    "initialization failed: no memory for rx buffers\n");
2065 		vr_stop(sc);
2066 		return;
2067 	}
2068 
2069 	/* Init tx descriptors. */
2070 	vr_tx_ring_init(sc);
2071 
2072 	if ((sc->vr_quirks & VR_Q_CAM) != 0) {
2073 		uint8_t vcam[2] = { 0, 0 };
2074 
2075 		/* Disable VLAN hardware tag insertion/stripping. */
2076 		VR_CLRBIT(sc, VR_TXCFG, VR_TXCFG_TXTAGEN | VR_TXCFG_RXTAGCTL);
2077 		/* Disable VLAN hardware filtering. */
2078 		VR_CLRBIT(sc, VR_BCR1, VR_BCR1_VLANFILT_ENB);
2079 		/* Disable all CAM entries. */
2080 		vr_cam_mask(sc, VR_MCAST_CAM, 0);
2081 		vr_cam_mask(sc, VR_VLAN_CAM, 0);
2082 		/* Enable the first VLAN CAM. */
2083 		vr_cam_data(sc, VR_VLAN_CAM, 0, vcam);
2084 		vr_cam_mask(sc, VR_VLAN_CAM, 1);
2085 	}
2086 
2087 	/*
2088 	 * Set up receive filter.
2089 	 */
2090 	vr_set_filter(sc);
2091 
2092 	/*
2093 	 * Load the address of the RX ring.
2094 	 */
2095 	addr = VR_RX_RING_ADDR(sc, 0);
2096 	CSR_WRITE_4(sc, VR_RXADDR, VR_ADDR_LO(addr));
2097 	/*
2098 	 * Load the address of the TX ring.
2099 	 */
2100 	addr = VR_TX_RING_ADDR(sc, 0);
2101 	CSR_WRITE_4(sc, VR_TXADDR, VR_ADDR_LO(addr));
2102 	/* Default : full-duplex, no Tx poll. */
2103 	CSR_WRITE_1(sc, VR_CR1, VR_CR1_FULLDUPLEX | VR_CR1_TX_NOPOLL);
2104 
2105 	/* Set flow-control parameters for Rhine III. */
2106 	if (sc->vr_revid >= REV_ID_VT6105_A0) {
2107 		/*
2108 		 * Configure Rx buffer count available for incoming
2109 		 * packet.
2110 		 * Even though data sheet says almost nothing about
2111 		 * this register, this register should be updated
2112 		 * whenever driver adds new RX buffers to controller.
2113 		 * Otherwise, XON frame is not sent to link partner
2114 		 * even if controller has enough RX buffers and you
2115 		 * would be isolated from network.
2116 		 * The controller is not smart enough to know number
2117 		 * of available RX buffers so driver have to let
2118 		 * controller know how many RX buffers are posted.
2119 		 * In other words, this register works like a residue
2120 		 * counter for RX buffers and should be initialized
2121 		 * to the number of total RX buffers  - 1 before
2122 		 * enabling RX MAC.  Note, this register is 8bits so
2123 		 * it effectively limits the maximum number of RX
2124 		 * buffer to be configured by controller is 255.
2125 		 */
2126 		CSR_WRITE_1(sc, VR_FLOWCR0, VR_RX_RING_CNT - 1);
2127 		/*
2128 		 * Tx pause low threshold : 8 free receive buffers
2129 		 * Tx pause XON high threshold : 24 free receive buffers
2130 		 */
2131 		CSR_WRITE_1(sc, VR_FLOWCR1,
2132 		    VR_FLOWCR1_TXLO8 | VR_FLOWCR1_TXHI24 | VR_FLOWCR1_XONXOFF);
2133 		/* Set Tx pause timer. */
2134 		CSR_WRITE_2(sc, VR_PAUSETIMER, 0xffff);
2135 	}
2136 
2137 	/* Enable receiver and transmitter. */
2138 	CSR_WRITE_1(sc, VR_CR0,
2139 	    VR_CR0_START | VR_CR0_TX_ON | VR_CR0_RX_ON | VR_CR0_RX_GO);
2140 
2141 	CSR_WRITE_2(sc, VR_ISR, 0xFFFF);
2142 #ifdef DEVICE_POLLING
2143 	/*
2144 	 * Disable interrupts if we are polling.
2145 	 */
2146 	if (if_getcapenable(ifp) & IFCAP_POLLING)
2147 		CSR_WRITE_2(sc, VR_IMR, 0);
2148 	else
2149 #endif
2150 	/*
2151 	 * Enable interrupts and disable MII intrs.
2152 	 */
2153 	CSR_WRITE_2(sc, VR_IMR, VR_INTRS);
2154 	if (sc->vr_revid > REV_ID_VT6102_A)
2155 		CSR_WRITE_2(sc, VR_MII_IMR, 0);
2156 
2157 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
2158 	if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
2159 
2160 	sc->vr_flags &= ~(VR_F_LINK | VR_F_TXPAUSE);
2161 	mii_mediachg(mii);
2162 
2163 	callout_reset(&sc->vr_stat_callout, hz, vr_tick, sc);
2164 }
2165 
2166 /*
2167  * Set media options.
2168  */
2169 static int
2170 vr_ifmedia_upd(if_t ifp)
2171 {
2172 	struct vr_softc		*sc;
2173 	struct mii_data		*mii;
2174 	struct mii_softc	*miisc;
2175 	int			error;
2176 
2177 	sc = if_getsoftc(ifp);
2178 	VR_LOCK(sc);
2179 	mii = device_get_softc(sc->vr_miibus);
2180 	LIST_FOREACH(miisc, &mii->mii_phys, mii_list)
2181 		PHY_RESET(miisc);
2182 	sc->vr_flags &= ~(VR_F_LINK | VR_F_TXPAUSE);
2183 	error = mii_mediachg(mii);
2184 	VR_UNLOCK(sc);
2185 
2186 	return (error);
2187 }
2188 
2189 /*
2190  * Report current media status.
2191  */
2192 static void
2193 vr_ifmedia_sts(if_t ifp, struct ifmediareq *ifmr)
2194 {
2195 	struct vr_softc		*sc;
2196 	struct mii_data		*mii;
2197 
2198 	sc = if_getsoftc(ifp);
2199 	mii = device_get_softc(sc->vr_miibus);
2200 	VR_LOCK(sc);
2201 	if ((if_getflags(ifp) & IFF_UP) == 0) {
2202 		VR_UNLOCK(sc);
2203 		return;
2204 	}
2205 	mii_pollstat(mii);
2206 	ifmr->ifm_active = mii->mii_media_active;
2207 	ifmr->ifm_status = mii->mii_media_status;
2208 	VR_UNLOCK(sc);
2209 }
2210 
2211 static int
2212 vr_ioctl(if_t ifp, u_long command, caddr_t data)
2213 {
2214 	struct vr_softc		*sc;
2215 	struct ifreq		*ifr;
2216 	struct mii_data		*mii;
2217 	int			error, mask;
2218 
2219 	sc = if_getsoftc(ifp);
2220 	ifr = (struct ifreq *)data;
2221 	error = 0;
2222 
2223 	switch (command) {
2224 	case SIOCSIFFLAGS:
2225 		VR_LOCK(sc);
2226 		if (if_getflags(ifp) & IFF_UP) {
2227 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2228 				if ((if_getflags(ifp) ^ sc->vr_if_flags) &
2229 				    (IFF_PROMISC | IFF_ALLMULTI))
2230 					vr_set_filter(sc);
2231 			} else {
2232 				if ((sc->vr_flags & VR_F_DETACHED) == 0)
2233 					vr_init_locked(sc);
2234 			}
2235 		} else {
2236 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2237 				vr_stop(sc);
2238 		}
2239 		sc->vr_if_flags = if_getflags(ifp);
2240 		VR_UNLOCK(sc);
2241 		break;
2242 	case SIOCADDMULTI:
2243 	case SIOCDELMULTI:
2244 		VR_LOCK(sc);
2245 		vr_set_filter(sc);
2246 		VR_UNLOCK(sc);
2247 		break;
2248 	case SIOCGIFMEDIA:
2249 	case SIOCSIFMEDIA:
2250 		mii = device_get_softc(sc->vr_miibus);
2251 		error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
2252 		break;
2253 	case SIOCSIFCAP:
2254 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
2255 #ifdef DEVICE_POLLING
2256 		if (mask & IFCAP_POLLING) {
2257 			if (ifr->ifr_reqcap & IFCAP_POLLING) {
2258 				error = ether_poll_register(vr_poll, ifp);
2259 				if (error != 0)
2260 					break;
2261 				VR_LOCK(sc);
2262 				/* Disable interrupts. */
2263 				CSR_WRITE_2(sc, VR_IMR, 0x0000);
2264 				if_setcapenablebit(ifp, IFCAP_POLLING, 0);
2265 				VR_UNLOCK(sc);
2266 			} else {
2267 				error = ether_poll_deregister(ifp);
2268 				/* Enable interrupts. */
2269 				VR_LOCK(sc);
2270 				CSR_WRITE_2(sc, VR_IMR, VR_INTRS);
2271 				if_setcapenablebit(ifp, 0, IFCAP_POLLING);
2272 				VR_UNLOCK(sc);
2273 			}
2274 		}
2275 #endif /* DEVICE_POLLING */
2276 		if ((mask & IFCAP_TXCSUM) != 0 &&
2277 		    (IFCAP_TXCSUM & if_getcapabilities(ifp)) != 0) {
2278 			if_togglecapenable(ifp, IFCAP_TXCSUM);
2279 			if ((IFCAP_TXCSUM & if_getcapenable(ifp)) != 0)
2280 				if_sethwassistbits(ifp, VR_CSUM_FEATURES, 0);
2281 			else
2282 				if_sethwassistbits(ifp, 0, VR_CSUM_FEATURES);
2283 		}
2284 		if ((mask & IFCAP_RXCSUM) != 0 &&
2285 		    (IFCAP_RXCSUM & if_getcapabilities(ifp)) != 0)
2286 			if_togglecapenable(ifp, IFCAP_RXCSUM);
2287 		if ((mask & IFCAP_WOL_UCAST) != 0 &&
2288 		    (if_getcapabilities(ifp) & IFCAP_WOL_UCAST) != 0)
2289 			if_togglecapenable(ifp, IFCAP_WOL_UCAST);
2290 		if ((mask & IFCAP_WOL_MAGIC) != 0 &&
2291 		    (if_getcapabilities(ifp) & IFCAP_WOL_MAGIC) != 0)
2292 			if_togglecapenable(ifp, IFCAP_WOL_MAGIC);
2293 		break;
2294 	default:
2295 		error = ether_ioctl(ifp, command, data);
2296 		break;
2297 	}
2298 
2299 	return (error);
2300 }
2301 
2302 static void
2303 vr_watchdog(struct vr_softc *sc)
2304 {
2305 	if_t			ifp;
2306 
2307 	VR_LOCK_ASSERT(sc);
2308 
2309 	if (sc->vr_watchdog_timer == 0 || --sc->vr_watchdog_timer)
2310 		return;
2311 
2312 	ifp = sc->vr_ifp;
2313 	/*
2314 	 * Reclaim first as we don't request interrupt for every packets.
2315 	 */
2316 	vr_txeof(sc);
2317 	if (sc->vr_cdata.vr_tx_cnt == 0)
2318 		return;
2319 
2320 	if ((sc->vr_flags & VR_F_LINK) == 0) {
2321 		if (bootverbose)
2322 			if_printf(sc->vr_ifp, "watchdog timeout "
2323 			   "(missed link)\n");
2324 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2325 		if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
2326 		vr_init_locked(sc);
2327 		return;
2328 	}
2329 
2330 	if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2331 	if_printf(ifp, "watchdog timeout\n");
2332 
2333 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
2334 	vr_init_locked(sc);
2335 
2336 	if (!if_sendq_empty(ifp))
2337 		vr_start_locked(ifp);
2338 }
2339 
2340 static void
2341 vr_tx_start(struct vr_softc *sc)
2342 {
2343 	bus_addr_t	addr;
2344 	uint8_t		cmd;
2345 
2346 	cmd = CSR_READ_1(sc, VR_CR0);
2347 	if ((cmd & VR_CR0_TX_ON) == 0) {
2348 		addr = VR_TX_RING_ADDR(sc, sc->vr_cdata.vr_tx_cons);
2349 		CSR_WRITE_4(sc, VR_TXADDR, VR_ADDR_LO(addr));
2350 		cmd |= VR_CR0_TX_ON;
2351 		CSR_WRITE_1(sc, VR_CR0, cmd);
2352 	}
2353 	if (sc->vr_cdata.vr_tx_cnt != 0) {
2354 		sc->vr_watchdog_timer = 5;
2355 		VR_SETBIT(sc, VR_CR0, VR_CR0_TX_GO);
2356 	}
2357 }
2358 
2359 static void
2360 vr_rx_start(struct vr_softc *sc)
2361 {
2362 	bus_addr_t	addr;
2363 	uint8_t		cmd;
2364 
2365 	cmd = CSR_READ_1(sc, VR_CR0);
2366 	if ((cmd & VR_CR0_RX_ON) == 0) {
2367 		addr = VR_RX_RING_ADDR(sc, sc->vr_cdata.vr_rx_cons);
2368 		CSR_WRITE_4(sc, VR_RXADDR, VR_ADDR_LO(addr));
2369 		cmd |= VR_CR0_RX_ON;
2370 		CSR_WRITE_1(sc, VR_CR0, cmd);
2371 	}
2372 	CSR_WRITE_1(sc, VR_CR0, cmd | VR_CR0_RX_GO);
2373 }
2374 
2375 static int
2376 vr_tx_stop(struct vr_softc *sc)
2377 {
2378 	int		i;
2379 	uint8_t		cmd;
2380 
2381 	cmd = CSR_READ_1(sc, VR_CR0);
2382 	if ((cmd & VR_CR0_TX_ON) != 0) {
2383 		cmd &= ~VR_CR0_TX_ON;
2384 		CSR_WRITE_1(sc, VR_CR0, cmd);
2385 		for (i = VR_TIMEOUT; i > 0; i--) {
2386 			DELAY(5);
2387 			cmd = CSR_READ_1(sc, VR_CR0);
2388 			if ((cmd & VR_CR0_TX_ON) == 0)
2389 				break;
2390 		}
2391 		if (i == 0)
2392 			return (ETIMEDOUT);
2393 	}
2394 	return (0);
2395 }
2396 
2397 static int
2398 vr_rx_stop(struct vr_softc *sc)
2399 {
2400 	int		i;
2401 	uint8_t		cmd;
2402 
2403 	cmd = CSR_READ_1(sc, VR_CR0);
2404 	if ((cmd & VR_CR0_RX_ON) != 0) {
2405 		cmd &= ~VR_CR0_RX_ON;
2406 		CSR_WRITE_1(sc, VR_CR0, cmd);
2407 		for (i = VR_TIMEOUT; i > 0; i--) {
2408 			DELAY(5);
2409 			cmd = CSR_READ_1(sc, VR_CR0);
2410 			if ((cmd & VR_CR0_RX_ON) == 0)
2411 				break;
2412 		}
2413 		if (i == 0)
2414 			return (ETIMEDOUT);
2415 	}
2416 	return (0);
2417 }
2418 
2419 /*
2420  * Stop the adapter and free any mbufs allocated to the
2421  * RX and TX lists.
2422  */
2423 static void
2424 vr_stop(struct vr_softc *sc)
2425 {
2426 	struct vr_txdesc	*txd;
2427 	struct vr_rxdesc	*rxd;
2428 	if_t			ifp;
2429 	int			i;
2430 
2431 	VR_LOCK_ASSERT(sc);
2432 
2433 	ifp = sc->vr_ifp;
2434 	sc->vr_watchdog_timer = 0;
2435 
2436 	callout_stop(&sc->vr_stat_callout);
2437 	if_setdrvflagbits(ifp, 0, (IFF_DRV_RUNNING | IFF_DRV_OACTIVE));
2438 
2439 	CSR_WRITE_1(sc, VR_CR0, VR_CR0_STOP);
2440 	if (vr_rx_stop(sc) != 0)
2441 		device_printf(sc->vr_dev, "%s: Rx shutdown error\n", __func__);
2442 	if (vr_tx_stop(sc) != 0)
2443 		device_printf(sc->vr_dev, "%s: Tx shutdown error\n", __func__);
2444 	/* Clear pending interrupts. */
2445 	CSR_WRITE_2(sc, VR_ISR, 0xFFFF);
2446 	CSR_WRITE_2(sc, VR_IMR, 0x0000);
2447 	CSR_WRITE_4(sc, VR_TXADDR, 0x00000000);
2448 	CSR_WRITE_4(sc, VR_RXADDR, 0x00000000);
2449 
2450 	/*
2451 	 * Free RX and TX mbufs still in the queues.
2452 	 */
2453 	for (i = 0; i < VR_RX_RING_CNT; i++) {
2454 		rxd = &sc->vr_cdata.vr_rxdesc[i];
2455 		if (rxd->rx_m != NULL) {
2456 			bus_dmamap_sync(sc->vr_cdata.vr_rx_tag,
2457 			    rxd->rx_dmamap, BUS_DMASYNC_POSTREAD);
2458 			bus_dmamap_unload(sc->vr_cdata.vr_rx_tag,
2459 			    rxd->rx_dmamap);
2460 			m_freem(rxd->rx_m);
2461 			rxd->rx_m = NULL;
2462 		}
2463         }
2464 	for (i = 0; i < VR_TX_RING_CNT; i++) {
2465 		txd = &sc->vr_cdata.vr_txdesc[i];
2466 		if (txd->tx_m != NULL) {
2467 			bus_dmamap_sync(sc->vr_cdata.vr_tx_tag,
2468 			    txd->tx_dmamap, BUS_DMASYNC_POSTWRITE);
2469 			bus_dmamap_unload(sc->vr_cdata.vr_tx_tag,
2470 			    txd->tx_dmamap);
2471 			m_freem(txd->tx_m);
2472 			txd->tx_m = NULL;
2473 		}
2474         }
2475 }
2476 
2477 /*
2478  * Stop all chip I/O so that the kernel's probe routines don't
2479  * get confused by errant DMAs when rebooting.
2480  */
2481 static int
2482 vr_shutdown(device_t dev)
2483 {
2484 
2485 	return (vr_suspend(dev));
2486 }
2487 
2488 static int
2489 vr_suspend(device_t dev)
2490 {
2491 	struct vr_softc		*sc;
2492 
2493 	sc = device_get_softc(dev);
2494 
2495 	VR_LOCK(sc);
2496 	vr_stop(sc);
2497 	vr_setwol(sc);
2498 	sc->vr_flags |= VR_F_SUSPENDED;
2499 	VR_UNLOCK(sc);
2500 
2501 	return (0);
2502 }
2503 
2504 static int
2505 vr_resume(device_t dev)
2506 {
2507 	struct vr_softc		*sc;
2508 	if_t			ifp;
2509 
2510 	sc = device_get_softc(dev);
2511 
2512 	VR_LOCK(sc);
2513 	ifp = sc->vr_ifp;
2514 	vr_clrwol(sc);
2515 	vr_reset(sc);
2516 	if (if_getflags(ifp) & IFF_UP)
2517 		vr_init_locked(sc);
2518 
2519 	sc->vr_flags &= ~VR_F_SUSPENDED;
2520 	VR_UNLOCK(sc);
2521 
2522 	return (0);
2523 }
2524 
2525 static void
2526 vr_setwol(struct vr_softc *sc)
2527 {
2528 	if_t			ifp;
2529 	int			pmc;
2530 	uint16_t		pmstat;
2531 	uint8_t			v;
2532 
2533 	VR_LOCK_ASSERT(sc);
2534 
2535 	if (sc->vr_revid < REV_ID_VT6102_A ||
2536 	    pci_find_cap(sc->vr_dev, PCIY_PMG, &pmc) != 0)
2537 		return;
2538 
2539 	ifp = sc->vr_ifp;
2540 
2541 	/* Clear WOL configuration. */
2542 	CSR_WRITE_1(sc, VR_WOLCR_CLR, 0xFF);
2543 	CSR_WRITE_1(sc, VR_WOLCFG_CLR, VR_WOLCFG_SAB | VR_WOLCFG_SAM);
2544 	CSR_WRITE_1(sc, VR_PWRCSR_CLR, 0xFF);
2545 	CSR_WRITE_1(sc, VR_PWRCFG_CLR, VR_PWRCFG_WOLEN);
2546 	if (sc->vr_revid > REV_ID_VT6105_B0) {
2547 		/* Newer Rhine III supports two additional patterns. */
2548 		CSR_WRITE_1(sc, VR_WOLCFG_CLR, VR_WOLCFG_PATTERN_PAGE);
2549 		CSR_WRITE_1(sc, VR_TESTREG_CLR, 3);
2550 		CSR_WRITE_1(sc, VR_PWRCSR1_CLR, 3);
2551 	}
2552 	if ((if_getcapenable(ifp) & IFCAP_WOL_UCAST) != 0)
2553 		CSR_WRITE_1(sc, VR_WOLCR_SET, VR_WOLCR_UCAST);
2554 	if ((if_getcapenable(ifp) & IFCAP_WOL_MAGIC) != 0)
2555 		CSR_WRITE_1(sc, VR_WOLCR_SET, VR_WOLCR_MAGIC);
2556 	/*
2557 	 * It seems that multicast wakeup frames require programming pattern
2558 	 * registers and valid CRC as well as pattern mask for each pattern.
2559 	 * While it's possible to setup such a pattern it would complicate
2560 	 * WOL configuration so ignore multicast wakeup frames.
2561 	 */
2562 	if ((if_getcapenable(ifp) & IFCAP_WOL) != 0) {
2563 		CSR_WRITE_1(sc, VR_WOLCFG_SET, VR_WOLCFG_SAB | VR_WOLCFG_SAM);
2564 		v = CSR_READ_1(sc, VR_STICKHW);
2565 		CSR_WRITE_1(sc, VR_STICKHW, v | VR_STICKHW_WOL_ENB);
2566 		CSR_WRITE_1(sc, VR_PWRCFG_SET, VR_PWRCFG_WOLEN);
2567 	}
2568 
2569 	/* Put hardware into sleep. */
2570 	v = CSR_READ_1(sc, VR_STICKHW);
2571 	v |= VR_STICKHW_DS0 | VR_STICKHW_DS1;
2572 	CSR_WRITE_1(sc, VR_STICKHW, v);
2573 
2574 	/* Request PME if WOL is requested. */
2575 	pmstat = pci_read_config(sc->vr_dev, pmc + PCIR_POWER_STATUS, 2);
2576 	pmstat &= ~(PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE);
2577 	if ((if_getcapenable(ifp) & IFCAP_WOL) != 0)
2578 		pmstat |= PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE;
2579 	pci_write_config(sc->vr_dev, pmc + PCIR_POWER_STATUS, pmstat, 2);
2580 }
2581 
2582 static void
2583 vr_clrwol(struct vr_softc *sc)
2584 {
2585 	uint8_t			v;
2586 
2587 	VR_LOCK_ASSERT(sc);
2588 
2589 	if (sc->vr_revid < REV_ID_VT6102_A)
2590 		return;
2591 
2592 	/* Take hardware out of sleep. */
2593 	v = CSR_READ_1(sc, VR_STICKHW);
2594 	v &= ~(VR_STICKHW_DS0 | VR_STICKHW_DS1 | VR_STICKHW_WOL_ENB);
2595 	CSR_WRITE_1(sc, VR_STICKHW, v);
2596 
2597 	/* Clear WOL configuration as WOL may interfere normal operation. */
2598 	CSR_WRITE_1(sc, VR_WOLCR_CLR, 0xFF);
2599 	CSR_WRITE_1(sc, VR_WOLCFG_CLR,
2600 	    VR_WOLCFG_SAB | VR_WOLCFG_SAM | VR_WOLCFG_PMEOVR);
2601 	CSR_WRITE_1(sc, VR_PWRCSR_CLR, 0xFF);
2602 	CSR_WRITE_1(sc, VR_PWRCFG_CLR, VR_PWRCFG_WOLEN);
2603 	if (sc->vr_revid > REV_ID_VT6105_B0) {
2604 		/* Newer Rhine III supports two additional patterns. */
2605 		CSR_WRITE_1(sc, VR_WOLCFG_CLR, VR_WOLCFG_PATTERN_PAGE);
2606 		CSR_WRITE_1(sc, VR_TESTREG_CLR, 3);
2607 		CSR_WRITE_1(sc, VR_PWRCSR1_CLR, 3);
2608 	}
2609 }
2610 
2611 static int
2612 vr_sysctl_stats(SYSCTL_HANDLER_ARGS)
2613 {
2614 	struct vr_softc		*sc;
2615 	struct vr_statistics	*stat;
2616 	int			error;
2617 	int			result;
2618 
2619 	result = -1;
2620 	error = sysctl_handle_int(oidp, &result, 0, req);
2621 
2622 	if (error != 0 || req->newptr == NULL)
2623 		return (error);
2624 
2625 	if (result == 1) {
2626 		sc = (struct vr_softc *)arg1;
2627 		stat = &sc->vr_stat;
2628 
2629 		printf("%s statistics:\n", device_get_nameunit(sc->vr_dev));
2630 		printf("Outbound good frames : %ju\n",
2631 		    (uintmax_t)stat->tx_ok);
2632 		printf("Inbound good frames : %ju\n",
2633 		    (uintmax_t)stat->rx_ok);
2634 		printf("Outbound errors : %u\n", stat->tx_errors);
2635 		printf("Inbound errors : %u\n", stat->rx_errors);
2636 		printf("Inbound no buffers : %u\n", stat->rx_no_buffers);
2637 		printf("Inbound no mbuf clusters: %d\n", stat->rx_no_mbufs);
2638 		printf("Inbound FIFO overflows : %d\n",
2639 		    stat->rx_fifo_overflows);
2640 		printf("Inbound CRC errors : %u\n", stat->rx_crc_errors);
2641 		printf("Inbound frame alignment errors : %u\n",
2642 		    stat->rx_alignment);
2643 		printf("Inbound giant frames : %u\n", stat->rx_giants);
2644 		printf("Inbound runt frames : %u\n", stat->rx_runts);
2645 		printf("Outbound aborted with excessive collisions : %u\n",
2646 		    stat->tx_abort);
2647 		printf("Outbound collisions : %u\n", stat->tx_collisions);
2648 		printf("Outbound late collisions : %u\n",
2649 		    stat->tx_late_collisions);
2650 		printf("Outbound underrun : %u\n", stat->tx_underrun);
2651 		printf("PCI bus errors : %u\n", stat->bus_errors);
2652 		printf("driver restarted due to Rx/Tx shutdown failure : %u\n",
2653 		    stat->num_restart);
2654 	}
2655 
2656 	return (error);
2657 }
2658