xref: /freebsd/sys/dev/virtio/network/if_vtnet.c (revision 10b59a9b4add0320d52c15ce057dd697261e7dfc)
1 /*-
2  * Copyright (c) 2011, Bryan Venteicher <bryanv@daemoninthecloset.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice unmodified, this list of conditions, and the following
10  *    disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 /* Driver for VirtIO network devices. */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #ifdef HAVE_KERNEL_OPTION_HEADERS
33 #include "opt_device_polling.h"
34 #endif
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/kernel.h>
39 #include <sys/sockio.h>
40 #include <sys/mbuf.h>
41 #include <sys/malloc.h>
42 #include <sys/module.h>
43 #include <sys/socket.h>
44 #include <sys/sysctl.h>
45 #include <sys/taskqueue.h>
46 #include <sys/random.h>
47 #include <sys/sglist.h>
48 #include <sys/lock.h>
49 #include <sys/mutex.h>
50 
51 #include <vm/uma.h>
52 
53 #include <net/ethernet.h>
54 #include <net/if.h>
55 #include <net/if_arp.h>
56 #include <net/if_dl.h>
57 #include <net/if_types.h>
58 #include <net/if_media.h>
59 #include <net/if_vlan_var.h>
60 
61 #include <net/bpf.h>
62 
63 #include <netinet/in_systm.h>
64 #include <netinet/in.h>
65 #include <netinet/ip.h>
66 #include <netinet/ip6.h>
67 #include <netinet/udp.h>
68 #include <netinet/tcp.h>
69 #include <netinet/sctp.h>
70 
71 #include <machine/bus.h>
72 #include <machine/resource.h>
73 #include <sys/bus.h>
74 #include <sys/rman.h>
75 
76 #include <dev/virtio/virtio.h>
77 #include <dev/virtio/virtqueue.h>
78 #include <dev/virtio/network/virtio_net.h>
79 #include <dev/virtio/network/if_vtnetvar.h>
80 
81 #include "virtio_if.h"
82 
83 static int	vtnet_modevent(module_t, int, void *);
84 
85 static int	vtnet_probe(device_t);
86 static int	vtnet_attach(device_t);
87 static int	vtnet_detach(device_t);
88 static int	vtnet_suspend(device_t);
89 static int	vtnet_resume(device_t);
90 static int	vtnet_shutdown(device_t);
91 static int	vtnet_config_change(device_t);
92 
93 static void	vtnet_negotiate_features(struct vtnet_softc *);
94 static int	vtnet_alloc_virtqueues(struct vtnet_softc *);
95 static void	vtnet_get_hwaddr(struct vtnet_softc *);
96 static void	vtnet_set_hwaddr(struct vtnet_softc *);
97 static int	vtnet_is_link_up(struct vtnet_softc *);
98 static void	vtnet_update_link_status(struct vtnet_softc *);
99 static void	vtnet_watchdog(struct vtnet_softc *);
100 static void	vtnet_config_change_task(void *, int);
101 static int	vtnet_change_mtu(struct vtnet_softc *, int);
102 static int	vtnet_ioctl(struct ifnet *, u_long, caddr_t);
103 
104 static int	vtnet_init_rx_vq(struct vtnet_softc *);
105 static void	vtnet_free_rx_mbufs(struct vtnet_softc *);
106 static void	vtnet_free_tx_mbufs(struct vtnet_softc *);
107 static void	vtnet_free_ctrl_vq(struct vtnet_softc *);
108 
109 #ifdef DEVICE_POLLING
110 static poll_handler_t vtnet_poll;
111 #endif
112 
113 static struct mbuf * vtnet_alloc_rxbuf(struct vtnet_softc *, int,
114 		    struct mbuf **);
115 static int	vtnet_replace_rxbuf(struct vtnet_softc *,
116 		    struct mbuf *, int);
117 static int	vtnet_newbuf(struct vtnet_softc *);
118 static void	vtnet_discard_merged_rxbuf(struct vtnet_softc *, int);
119 static void	vtnet_discard_rxbuf(struct vtnet_softc *, struct mbuf *);
120 static int	vtnet_enqueue_rxbuf(struct vtnet_softc *, struct mbuf *);
121 static void	vtnet_vlan_tag_remove(struct mbuf *);
122 static int	vtnet_rx_csum(struct vtnet_softc *, struct mbuf *,
123 		    struct virtio_net_hdr *);
124 static int	vtnet_rxeof_merged(struct vtnet_softc *, struct mbuf *, int);
125 static int	vtnet_rxeof(struct vtnet_softc *, int, int *);
126 static void	vtnet_rx_intr_task(void *, int);
127 static int	vtnet_rx_vq_intr(void *);
128 
129 static void	vtnet_txeof(struct vtnet_softc *);
130 static struct mbuf * vtnet_tx_offload(struct vtnet_softc *, struct mbuf *,
131 		    struct virtio_net_hdr *);
132 static int	vtnet_enqueue_txbuf(struct vtnet_softc *, struct mbuf **,
133 		    struct vtnet_tx_header *);
134 static int	vtnet_encap(struct vtnet_softc *, struct mbuf **);
135 static void	vtnet_start_locked(struct ifnet *);
136 static void	vtnet_start(struct ifnet *);
137 static void	vtnet_tick(void *);
138 static void	vtnet_tx_intr_task(void *, int);
139 static int	vtnet_tx_vq_intr(void *);
140 
141 static void	vtnet_stop(struct vtnet_softc *);
142 static int	vtnet_reinit(struct vtnet_softc *);
143 static void	vtnet_init_locked(struct vtnet_softc *);
144 static void	vtnet_init(void *);
145 
146 static void	vtnet_exec_ctrl_cmd(struct vtnet_softc *, void *,
147 		    struct sglist *, int, int);
148 
149 static void	vtnet_rx_filter(struct vtnet_softc *sc);
150 static int	vtnet_ctrl_rx_cmd(struct vtnet_softc *, int, int);
151 static int	vtnet_set_promisc(struct vtnet_softc *, int);
152 static int	vtnet_set_allmulti(struct vtnet_softc *, int);
153 static void	vtnet_rx_filter_mac(struct vtnet_softc *);
154 
155 static int	vtnet_exec_vlan_filter(struct vtnet_softc *, int, uint16_t);
156 static void	vtnet_rx_filter_vlan(struct vtnet_softc *);
157 static void	vtnet_set_vlan_filter(struct vtnet_softc *, int, uint16_t);
158 static void	vtnet_register_vlan(void *, struct ifnet *, uint16_t);
159 static void	vtnet_unregister_vlan(void *, struct ifnet *, uint16_t);
160 
161 static int	vtnet_ifmedia_upd(struct ifnet *);
162 static void	vtnet_ifmedia_sts(struct ifnet *, struct ifmediareq *);
163 
164 static void	vtnet_add_statistics(struct vtnet_softc *);
165 
166 static int	vtnet_enable_rx_intr(struct vtnet_softc *);
167 static int	vtnet_enable_tx_intr(struct vtnet_softc *);
168 static void	vtnet_disable_rx_intr(struct vtnet_softc *);
169 static void	vtnet_disable_tx_intr(struct vtnet_softc *);
170 
171 /* Tunables. */
172 static int vtnet_csum_disable = 0;
173 TUNABLE_INT("hw.vtnet.csum_disable", &vtnet_csum_disable);
174 static int vtnet_tso_disable = 0;
175 TUNABLE_INT("hw.vtnet.tso_disable", &vtnet_tso_disable);
176 static int vtnet_lro_disable = 0;
177 TUNABLE_INT("hw.vtnet.lro_disable", &vtnet_lro_disable);
178 
179 /*
180  * Reducing the number of transmit completed interrupts can
181  * improve performance. To do so, the define below keeps the
182  * Tx vq interrupt disabled and adds calls to vtnet_txeof()
183  * in the start and watchdog paths. The price to pay for this
184  * is the m_free'ing of transmitted mbufs may be delayed until
185  * the watchdog fires.
186  */
187 #define VTNET_TX_INTR_MODERATION
188 
189 static uma_zone_t vtnet_tx_header_zone;
190 
191 static struct virtio_feature_desc vtnet_feature_desc[] = {
192 	{ VIRTIO_NET_F_CSUM,		"TxChecksum"	},
193 	{ VIRTIO_NET_F_GUEST_CSUM,	"RxChecksum"	},
194 	{ VIRTIO_NET_F_MAC,		"MacAddress"	},
195 	{ VIRTIO_NET_F_GSO,		"TxAllGSO"	},
196 	{ VIRTIO_NET_F_GUEST_TSO4,	"RxTSOv4"	},
197 	{ VIRTIO_NET_F_GUEST_TSO6,	"RxTSOv6"	},
198 	{ VIRTIO_NET_F_GUEST_ECN,	"RxECN"		},
199 	{ VIRTIO_NET_F_GUEST_UFO,	"RxUFO"		},
200 	{ VIRTIO_NET_F_HOST_TSO4,	"TxTSOv4"	},
201 	{ VIRTIO_NET_F_HOST_TSO6,	"TxTSOv6"	},
202 	{ VIRTIO_NET_F_HOST_ECN,	"TxTSOECN"	},
203 	{ VIRTIO_NET_F_HOST_UFO,	"TxUFO"		},
204 	{ VIRTIO_NET_F_MRG_RXBUF,	"MrgRxBuf"	},
205 	{ VIRTIO_NET_F_STATUS,		"Status"	},
206 	{ VIRTIO_NET_F_CTRL_VQ,		"ControlVq"	},
207 	{ VIRTIO_NET_F_CTRL_RX,		"RxMode"	},
208 	{ VIRTIO_NET_F_CTRL_VLAN,	"VLanFilter"	},
209 	{ VIRTIO_NET_F_CTRL_RX_EXTRA,	"RxModeExtra"	},
210 
211 	{ 0, NULL }
212 };
213 
214 static device_method_t vtnet_methods[] = {
215 	/* Device methods. */
216 	DEVMETHOD(device_probe,		vtnet_probe),
217 	DEVMETHOD(device_attach,	vtnet_attach),
218 	DEVMETHOD(device_detach,	vtnet_detach),
219 	DEVMETHOD(device_suspend,	vtnet_suspend),
220 	DEVMETHOD(device_resume,	vtnet_resume),
221 	DEVMETHOD(device_shutdown,	vtnet_shutdown),
222 
223 	/* VirtIO methods. */
224 	DEVMETHOD(virtio_config_change, vtnet_config_change),
225 
226 	{ 0, 0 }
227 };
228 
229 static driver_t vtnet_driver = {
230 	"vtnet",
231 	vtnet_methods,
232 	sizeof(struct vtnet_softc)
233 };
234 static devclass_t vtnet_devclass;
235 
236 DRIVER_MODULE(vtnet, virtio_pci, vtnet_driver, vtnet_devclass,
237     vtnet_modevent, 0);
238 MODULE_VERSION(vtnet, 1);
239 MODULE_DEPEND(vtnet, virtio, 1, 1, 1);
240 
241 static int
242 vtnet_modevent(module_t mod, int type, void *unused)
243 {
244 	int error;
245 
246 	error = 0;
247 
248 	switch (type) {
249 	case MOD_LOAD:
250 		vtnet_tx_header_zone = uma_zcreate("vtnet_tx_hdr",
251 		    sizeof(struct vtnet_tx_header),
252 		    NULL, NULL, NULL, NULL, 0, 0);
253 		break;
254 	case MOD_QUIESCE:
255 	case MOD_UNLOAD:
256 		if (uma_zone_get_cur(vtnet_tx_header_zone) > 0)
257 			error = EBUSY;
258 		else if (type == MOD_UNLOAD) {
259 			uma_zdestroy(vtnet_tx_header_zone);
260 			vtnet_tx_header_zone = NULL;
261 		}
262 		break;
263 	case MOD_SHUTDOWN:
264 		break;
265 	default:
266 		error = EOPNOTSUPP;
267 		break;
268 	}
269 
270 	return (error);
271 }
272 
273 static int
274 vtnet_probe(device_t dev)
275 {
276 
277 	if (virtio_get_device_type(dev) != VIRTIO_ID_NETWORK)
278 		return (ENXIO);
279 
280 	device_set_desc(dev, "VirtIO Networking Adapter");
281 
282 	return (BUS_PROBE_DEFAULT);
283 }
284 
285 static int
286 vtnet_attach(device_t dev)
287 {
288 	struct vtnet_softc *sc;
289 	struct ifnet *ifp;
290 	int tx_size, error;
291 
292 	sc = device_get_softc(dev);
293 	sc->vtnet_dev = dev;
294 
295 	VTNET_LOCK_INIT(sc);
296 	callout_init_mtx(&sc->vtnet_tick_ch, VTNET_MTX(sc), 0);
297 
298 	ifmedia_init(&sc->vtnet_media, IFM_IMASK, vtnet_ifmedia_upd,
299 	    vtnet_ifmedia_sts);
300 	ifmedia_add(&sc->vtnet_media, VTNET_MEDIATYPE, 0, NULL);
301 	ifmedia_set(&sc->vtnet_media, VTNET_MEDIATYPE);
302 
303 	vtnet_add_statistics(sc);
304 
305 	virtio_set_feature_desc(dev, vtnet_feature_desc);
306 	vtnet_negotiate_features(sc);
307 
308 	if (virtio_with_feature(dev, VIRTIO_NET_F_MRG_RXBUF)) {
309 		sc->vtnet_flags |= VTNET_FLAG_MRG_RXBUFS;
310 		sc->vtnet_hdr_size = sizeof(struct virtio_net_hdr_mrg_rxbuf);
311 	} else
312 		sc->vtnet_hdr_size = sizeof(struct virtio_net_hdr);
313 
314 	sc->vtnet_rx_mbuf_size = MCLBYTES;
315 	sc->vtnet_rx_mbuf_count = VTNET_NEEDED_RX_MBUFS(sc);
316 
317 	if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_VQ)) {
318 		sc->vtnet_flags |= VTNET_FLAG_CTRL_VQ;
319 
320 		if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_RX))
321 			sc->vtnet_flags |= VTNET_FLAG_CTRL_RX;
322 		if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_VLAN))
323 			sc->vtnet_flags |= VTNET_FLAG_VLAN_FILTER;
324 	}
325 
326 	vtnet_get_hwaddr(sc);
327 
328 	error = vtnet_alloc_virtqueues(sc);
329 	if (error) {
330 		device_printf(dev, "cannot allocate virtqueues\n");
331 		goto fail;
332 	}
333 
334 	ifp = sc->vtnet_ifp = if_alloc(IFT_ETHER);
335 	if (ifp == NULL) {
336 		device_printf(dev, "cannot allocate ifnet structure\n");
337 		error = ENOSPC;
338 		goto fail;
339 	}
340 
341 	ifp->if_softc = sc;
342 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
343 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
344 	ifp->if_init = vtnet_init;
345 	ifp->if_start = vtnet_start;
346 	ifp->if_ioctl = vtnet_ioctl;
347 
348 	sc->vtnet_rx_size = virtqueue_size(sc->vtnet_rx_vq);
349 	sc->vtnet_rx_process_limit = sc->vtnet_rx_size;
350 
351 	tx_size = virtqueue_size(sc->vtnet_tx_vq);
352 	sc->vtnet_tx_size = tx_size;
353 	IFQ_SET_MAXLEN(&ifp->if_snd, tx_size - 1);
354 	ifp->if_snd.ifq_drv_maxlen = tx_size - 1;
355 	IFQ_SET_READY(&ifp->if_snd);
356 
357 	ether_ifattach(ifp, sc->vtnet_hwaddr);
358 
359 	if (virtio_with_feature(dev, VIRTIO_NET_F_STATUS))
360 		ifp->if_capabilities |= IFCAP_LINKSTATE;
361 
362 	/* Tell the upper layer(s) we support long frames. */
363 	ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
364 	ifp->if_capabilities |= IFCAP_JUMBO_MTU | IFCAP_VLAN_MTU;
365 
366 	if (virtio_with_feature(dev, VIRTIO_NET_F_CSUM)) {
367 		ifp->if_capabilities |= IFCAP_TXCSUM;
368 
369 		if (virtio_with_feature(dev, VIRTIO_NET_F_HOST_TSO4))
370 			ifp->if_capabilities |= IFCAP_TSO4;
371 		if (virtio_with_feature(dev, VIRTIO_NET_F_HOST_TSO6))
372 			ifp->if_capabilities |= IFCAP_TSO6;
373 		if (ifp->if_capabilities & IFCAP_TSO)
374 			ifp->if_capabilities |= IFCAP_VLAN_HWTSO;
375 
376 		if (virtio_with_feature(dev, VIRTIO_NET_F_HOST_ECN))
377 			sc->vtnet_flags |= VTNET_FLAG_TSO_ECN;
378 	}
379 
380 	if (virtio_with_feature(dev, VIRTIO_NET_F_GUEST_CSUM)) {
381 		ifp->if_capabilities |= IFCAP_RXCSUM;
382 
383 		if (virtio_with_feature(dev, VIRTIO_NET_F_GUEST_TSO4) ||
384 		    virtio_with_feature(dev, VIRTIO_NET_F_GUEST_TSO6))
385 			ifp->if_capabilities |= IFCAP_LRO;
386 	}
387 
388 	if (ifp->if_capabilities & IFCAP_HWCSUM) {
389 		/*
390 		 * VirtIO does not support VLAN tagging, but we can fake
391 		 * it by inserting and removing the 802.1Q header during
392 		 * transmit and receive. We are then able to do checksum
393 		 * offloading of VLAN frames.
394 		 */
395 		ifp->if_capabilities |=
396 		    IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_HWCSUM;
397 	}
398 
399 	ifp->if_capenable = ifp->if_capabilities;
400 
401 	/*
402 	 * Capabilities after here are not enabled by default.
403 	 */
404 
405 	if (sc->vtnet_flags & VTNET_FLAG_VLAN_FILTER) {
406 		ifp->if_capabilities |= IFCAP_VLAN_HWFILTER;
407 
408 		sc->vtnet_vlan_attach = EVENTHANDLER_REGISTER(vlan_config,
409 		    vtnet_register_vlan, sc, EVENTHANDLER_PRI_FIRST);
410 		sc->vtnet_vlan_detach = EVENTHANDLER_REGISTER(vlan_unconfig,
411 		    vtnet_unregister_vlan, sc, EVENTHANDLER_PRI_FIRST);
412 	}
413 
414 #ifdef DEVICE_POLLING
415 	ifp->if_capabilities |= IFCAP_POLLING;
416 #endif
417 
418 	TASK_INIT(&sc->vtnet_rx_intr_task, 0, vtnet_rx_intr_task, sc);
419 	TASK_INIT(&sc->vtnet_tx_intr_task, 0, vtnet_tx_intr_task, sc);
420 	TASK_INIT(&sc->vtnet_cfgchg_task, 0, vtnet_config_change_task, sc);
421 
422 	sc->vtnet_tq = taskqueue_create_fast("vtnet_taskq", M_NOWAIT,
423 	    taskqueue_thread_enqueue, &sc->vtnet_tq);
424 	if (sc->vtnet_tq == NULL) {
425 		error = ENOMEM;
426 		device_printf(dev, "cannot allocate taskqueue\n");
427 		ether_ifdetach(ifp);
428 		goto fail;
429 	}
430 	taskqueue_start_threads(&sc->vtnet_tq, 1, PI_NET, "%s taskq",
431 	    device_get_nameunit(dev));
432 
433 	error = virtio_setup_intr(dev, INTR_TYPE_NET);
434 	if (error) {
435 		device_printf(dev, "cannot setup virtqueue interrupts\n");
436 		taskqueue_free(sc->vtnet_tq);
437 		sc->vtnet_tq = NULL;
438 		ether_ifdetach(ifp);
439 		goto fail;
440 	}
441 
442 	/*
443 	 * Device defaults to promiscuous mode for backwards
444 	 * compatibility. Turn it off if possible.
445 	 */
446 	if (sc->vtnet_flags & VTNET_FLAG_CTRL_RX) {
447 		VTNET_LOCK(sc);
448 		if (vtnet_set_promisc(sc, 0) != 0) {
449 			ifp->if_flags |= IFF_PROMISC;
450 			device_printf(dev,
451 			    "cannot disable promiscuous mode\n");
452 		}
453 		VTNET_UNLOCK(sc);
454 	} else
455 		ifp->if_flags |= IFF_PROMISC;
456 
457 fail:
458 	if (error)
459 		vtnet_detach(dev);
460 
461 	return (error);
462 }
463 
464 static int
465 vtnet_detach(device_t dev)
466 {
467 	struct vtnet_softc *sc;
468 	struct ifnet *ifp;
469 
470 	sc = device_get_softc(dev);
471 	ifp = sc->vtnet_ifp;
472 
473 	KASSERT(mtx_initialized(VTNET_MTX(sc)),
474 	    ("vtnet mutex not initialized"));
475 
476 #ifdef DEVICE_POLLING
477 	if (ifp != NULL && ifp->if_capenable & IFCAP_POLLING)
478 		ether_poll_deregister(ifp);
479 #endif
480 
481 	if (device_is_attached(dev)) {
482 		VTNET_LOCK(sc);
483 		vtnet_stop(sc);
484 		VTNET_UNLOCK(sc);
485 
486 		callout_drain(&sc->vtnet_tick_ch);
487 		taskqueue_drain(taskqueue_fast, &sc->vtnet_cfgchg_task);
488 
489 		ether_ifdetach(ifp);
490 	}
491 
492 	if (sc->vtnet_tq != NULL) {
493 		taskqueue_drain(sc->vtnet_tq, &sc->vtnet_rx_intr_task);
494 		taskqueue_drain(sc->vtnet_tq, &sc->vtnet_tx_intr_task);
495 		taskqueue_free(sc->vtnet_tq);
496 		sc->vtnet_tq = NULL;
497 	}
498 
499 	if (sc->vtnet_vlan_attach != NULL) {
500 		EVENTHANDLER_DEREGISTER(vlan_config, sc->vtnet_vlan_attach);
501 		sc->vtnet_vlan_attach = NULL;
502 	}
503 	if (sc->vtnet_vlan_detach != NULL) {
504 		EVENTHANDLER_DEREGISTER(vlan_unconfg, sc->vtnet_vlan_detach);
505 		sc->vtnet_vlan_detach = NULL;
506 	}
507 
508 	if (ifp) {
509 		if_free(ifp);
510 		sc->vtnet_ifp = NULL;
511 	}
512 
513 	if (sc->vtnet_rx_vq != NULL)
514 		vtnet_free_rx_mbufs(sc);
515 	if (sc->vtnet_tx_vq != NULL)
516 		vtnet_free_tx_mbufs(sc);
517 	if (sc->vtnet_ctrl_vq != NULL)
518 		vtnet_free_ctrl_vq(sc);
519 
520 	ifmedia_removeall(&sc->vtnet_media);
521 	VTNET_LOCK_DESTROY(sc);
522 
523 	return (0);
524 }
525 
526 static int
527 vtnet_suspend(device_t dev)
528 {
529 	struct vtnet_softc *sc;
530 
531 	sc = device_get_softc(dev);
532 
533 	VTNET_LOCK(sc);
534 	vtnet_stop(sc);
535 	sc->vtnet_flags |= VTNET_FLAG_SUSPENDED;
536 	VTNET_UNLOCK(sc);
537 
538 	return (0);
539 }
540 
541 static int
542 vtnet_resume(device_t dev)
543 {
544 	struct vtnet_softc *sc;
545 	struct ifnet *ifp;
546 
547 	sc = device_get_softc(dev);
548 	ifp = sc->vtnet_ifp;
549 
550 	VTNET_LOCK(sc);
551 	if (ifp->if_flags & IFF_UP)
552 		vtnet_init_locked(sc);
553 	sc->vtnet_flags &= ~VTNET_FLAG_SUSPENDED;
554 	VTNET_UNLOCK(sc);
555 
556 	return (0);
557 }
558 
559 static int
560 vtnet_shutdown(device_t dev)
561 {
562 
563 	/*
564 	 * Suspend already does all of what we need to
565 	 * do here; we just never expect to be resumed.
566 	 */
567 	return (vtnet_suspend(dev));
568 }
569 
570 static int
571 vtnet_config_change(device_t dev)
572 {
573 	struct vtnet_softc *sc;
574 
575 	sc = device_get_softc(dev);
576 
577 	taskqueue_enqueue_fast(taskqueue_fast, &sc->vtnet_cfgchg_task);
578 
579 	return (1);
580 }
581 
582 static void
583 vtnet_negotiate_features(struct vtnet_softc *sc)
584 {
585 	device_t dev;
586 	uint64_t mask, features;
587 
588 	dev = sc->vtnet_dev;
589 	mask = 0;
590 
591 	if (vtnet_csum_disable)
592 		mask |= VIRTIO_NET_F_CSUM | VIRTIO_NET_F_GUEST_CSUM;
593 
594 	/*
595 	 * TSO and LRO are only available when their corresponding
596 	 * checksum offload feature is also negotiated.
597 	 */
598 
599 	if (vtnet_csum_disable || vtnet_tso_disable)
600 		mask |= VIRTIO_NET_F_HOST_TSO4 | VIRTIO_NET_F_HOST_TSO6 |
601 		    VIRTIO_NET_F_HOST_ECN;
602 
603 	if (vtnet_csum_disable || vtnet_lro_disable)
604 		mask |= VTNET_LRO_FEATURES;
605 
606 	features = VTNET_FEATURES & ~mask;
607 #ifdef VTNET_TX_INTR_MODERATION
608 	features |= VIRTIO_F_NOTIFY_ON_EMPTY;
609 #endif
610 	sc->vtnet_features = virtio_negotiate_features(dev, features);
611 
612 	if (virtio_with_feature(dev, VIRTIO_NET_F_MRG_RXBUF) == 0 &&
613 	    virtio_with_feature(dev, VTNET_LRO_FEATURES)) {
614 		/*
615 		 * LRO without mergeable buffers requires special care. This
616 		 * is not ideal because every receive buffer must be large
617 		 * enough to hold the maximum TCP packet, the Ethernet header,
618 		 * and the vtnet_rx_header. This requires up to 34 descriptors
619 		 * when using MCLBYTES clusters. If we do not have indirect
620 		 * descriptors, LRO is disabled since the virtqueue will not
621 		 * be able to contain very many receive buffers.
622 		 */
623 		if (virtio_with_feature(dev,
624 		    VIRTIO_RING_F_INDIRECT_DESC) == 0) {
625 			device_printf(dev,
626 			    "LRO disabled due to lack of both mergeable "
627 			    "buffers and indirect descriptors\n");
628 
629 			sc->vtnet_features = virtio_negotiate_features(dev,
630 			    features & ~VTNET_LRO_FEATURES);
631 		} else
632 			sc->vtnet_flags |= VTNET_FLAG_LRO_NOMRG;
633 	}
634 }
635 
636 static int
637 vtnet_alloc_virtqueues(struct vtnet_softc *sc)
638 {
639 	device_t dev;
640 	struct vq_alloc_info vq_info[3];
641 	int nvqs, rxsegs;
642 
643 	dev = sc->vtnet_dev;
644 	nvqs = 2;
645 
646 	/*
647 	 * Indirect descriptors are not needed for the Rx
648 	 * virtqueue when mergeable buffers are negotiated.
649 	 * The header is placed inline with the data, not
650 	 * in a separate descriptor, and mbuf clusters are
651 	 * always physically contiguous.
652 	 */
653 	if ((sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS) == 0) {
654 		rxsegs = sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG ?
655 		    VTNET_MAX_RX_SEGS : VTNET_MIN_RX_SEGS;
656 	} else
657 		rxsegs = 0;
658 
659 	VQ_ALLOC_INFO_INIT(&vq_info[0], rxsegs,
660 	    vtnet_rx_vq_intr, sc, &sc->vtnet_rx_vq,
661 	    "%s receive", device_get_nameunit(dev));
662 
663 	VQ_ALLOC_INFO_INIT(&vq_info[1], VTNET_MAX_TX_SEGS,
664 	    vtnet_tx_vq_intr, sc, &sc->vtnet_tx_vq,
665 	    "%s transmit", device_get_nameunit(dev));
666 
667 	if (sc->vtnet_flags & VTNET_FLAG_CTRL_VQ) {
668 		nvqs++;
669 
670 		VQ_ALLOC_INFO_INIT(&vq_info[2], 0, NULL, NULL,
671 		    &sc->vtnet_ctrl_vq, "%s control",
672 		    device_get_nameunit(dev));
673 	}
674 
675 	return (virtio_alloc_virtqueues(dev, 0, nvqs, vq_info));
676 }
677 
678 static void
679 vtnet_get_hwaddr(struct vtnet_softc *sc)
680 {
681 	device_t dev;
682 
683 	dev = sc->vtnet_dev;
684 
685 	if (virtio_with_feature(dev, VIRTIO_NET_F_MAC)) {
686 		virtio_read_device_config(dev,
687 		    offsetof(struct virtio_net_config, mac),
688 		    sc->vtnet_hwaddr, ETHER_ADDR_LEN);
689 	} else {
690 		/* Generate random locally administered unicast address. */
691 		sc->vtnet_hwaddr[0] = 0xB2;
692 		arc4rand(&sc->vtnet_hwaddr[1], ETHER_ADDR_LEN - 1, 0);
693 
694 		vtnet_set_hwaddr(sc);
695 	}
696 }
697 
698 static void
699 vtnet_set_hwaddr(struct vtnet_softc *sc)
700 {
701 	device_t dev;
702 
703 	dev = sc->vtnet_dev;
704 
705 	virtio_write_device_config(dev,
706 	    offsetof(struct virtio_net_config, mac),
707 	    sc->vtnet_hwaddr, ETHER_ADDR_LEN);
708 }
709 
710 static int
711 vtnet_is_link_up(struct vtnet_softc *sc)
712 {
713 	device_t dev;
714 	struct ifnet *ifp;
715 	uint16_t status;
716 
717 	dev = sc->vtnet_dev;
718 	ifp = sc->vtnet_ifp;
719 
720 	VTNET_LOCK_ASSERT(sc);
721 
722 	if ((ifp->if_capenable & IFCAP_LINKSTATE) == 0)
723 		return (1);
724 
725 	status = virtio_read_dev_config_2(dev,
726 	    offsetof(struct virtio_net_config, status));
727 
728 	return ((status & VIRTIO_NET_S_LINK_UP) != 0);
729 }
730 
731 static void
732 vtnet_update_link_status(struct vtnet_softc *sc)
733 {
734 	device_t dev;
735 	struct ifnet *ifp;
736 	int link;
737 
738 	dev = sc->vtnet_dev;
739 	ifp = sc->vtnet_ifp;
740 
741 	link = vtnet_is_link_up(sc);
742 
743 	if (link && ((sc->vtnet_flags & VTNET_FLAG_LINK) == 0)) {
744 		sc->vtnet_flags |= VTNET_FLAG_LINK;
745 		if (bootverbose)
746 			device_printf(dev, "Link is up\n");
747 
748 		if_link_state_change(ifp, LINK_STATE_UP);
749 		if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
750 			vtnet_start_locked(ifp);
751 	} else if (!link && (sc->vtnet_flags & VTNET_FLAG_LINK)) {
752 		sc->vtnet_flags &= ~VTNET_FLAG_LINK;
753 		if (bootverbose)
754 			device_printf(dev, "Link is down\n");
755 
756 		if_link_state_change(ifp, LINK_STATE_DOWN);
757 	}
758 }
759 
760 static void
761 vtnet_watchdog(struct vtnet_softc *sc)
762 {
763 	struct ifnet *ifp;
764 
765 	ifp = sc->vtnet_ifp;
766 
767 #ifdef VTNET_TX_INTR_MODERATION
768 	vtnet_txeof(sc);
769 #endif
770 
771 	if (sc->vtnet_watchdog_timer == 0 || --sc->vtnet_watchdog_timer)
772 		return;
773 
774 	if_printf(ifp, "watchdog timeout -- resetting\n");
775 #ifdef VTNET_DEBUG
776 	virtqueue_dump(sc->vtnet_tx_vq);
777 #endif
778 	ifp->if_oerrors++;
779 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
780 	vtnet_init_locked(sc);
781 }
782 
783 static void
784 vtnet_config_change_task(void *arg, int pending)
785 {
786 	struct vtnet_softc *sc;
787 
788 	sc = arg;
789 
790 	VTNET_LOCK(sc);
791 	vtnet_update_link_status(sc);
792 	VTNET_UNLOCK(sc);
793 }
794 
795 static int
796 vtnet_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
797 {
798 	struct vtnet_softc *sc;
799 	struct ifreq *ifr;
800 	int reinit, mask, error;
801 
802 	sc = ifp->if_softc;
803 	ifr = (struct ifreq *) data;
804 	reinit = 0;
805 	error = 0;
806 
807 	switch (cmd) {
808 	case SIOCSIFMTU:
809 		if (ifr->ifr_mtu < ETHERMIN || ifr->ifr_mtu > VTNET_MAX_MTU)
810 			error = EINVAL;
811 		else if (ifp->if_mtu != ifr->ifr_mtu) {
812 			VTNET_LOCK(sc);
813 			error = vtnet_change_mtu(sc, ifr->ifr_mtu);
814 			VTNET_UNLOCK(sc);
815 		}
816 		break;
817 
818 	case SIOCSIFFLAGS:
819 		VTNET_LOCK(sc);
820 		if ((ifp->if_flags & IFF_UP) == 0) {
821 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
822 				vtnet_stop(sc);
823 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
824 			if ((ifp->if_flags ^ sc->vtnet_if_flags) &
825 			    (IFF_PROMISC | IFF_ALLMULTI)) {
826 				if (sc->vtnet_flags & VTNET_FLAG_CTRL_RX)
827 					vtnet_rx_filter(sc);
828 				else
829 					error = ENOTSUP;
830 			}
831 		} else
832 			vtnet_init_locked(sc);
833 
834 		if (error == 0)
835 			sc->vtnet_if_flags = ifp->if_flags;
836 		VTNET_UNLOCK(sc);
837 		break;
838 
839 	case SIOCADDMULTI:
840 	case SIOCDELMULTI:
841 		VTNET_LOCK(sc);
842 		if ((sc->vtnet_flags & VTNET_FLAG_CTRL_RX) &&
843 		    (ifp->if_drv_flags & IFF_DRV_RUNNING))
844 			vtnet_rx_filter_mac(sc);
845 		VTNET_UNLOCK(sc);
846 		break;
847 
848 	case SIOCSIFMEDIA:
849 	case SIOCGIFMEDIA:
850 		error = ifmedia_ioctl(ifp, ifr, &sc->vtnet_media, cmd);
851 		break;
852 
853 	case SIOCSIFCAP:
854 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
855 
856 #ifdef DEVICE_POLLING
857 		if (mask & IFCAP_POLLING) {
858 			if (ifr->ifr_reqcap & IFCAP_POLLING) {
859 				error = ether_poll_register(vtnet_poll, ifp);
860 				if (error)
861 					break;
862 
863 				VTNET_LOCK(sc);
864 				vtnet_disable_rx_intr(sc);
865 				vtnet_disable_tx_intr(sc);
866 				ifp->if_capenable |= IFCAP_POLLING;
867 				VTNET_UNLOCK(sc);
868 			} else {
869 				error = ether_poll_deregister(ifp);
870 
871 				/* Enable interrupts even in error case. */
872 				VTNET_LOCK(sc);
873 				vtnet_enable_tx_intr(sc);
874 				vtnet_enable_rx_intr(sc);
875 				ifp->if_capenable &= ~IFCAP_POLLING;
876 				VTNET_UNLOCK(sc);
877 			}
878 		}
879 #endif
880 		VTNET_LOCK(sc);
881 
882 		if (mask & IFCAP_TXCSUM) {
883 			ifp->if_capenable ^= IFCAP_TXCSUM;
884 			if (ifp->if_capenable & IFCAP_TXCSUM)
885 				ifp->if_hwassist |= VTNET_CSUM_OFFLOAD;
886 			else
887 				ifp->if_hwassist &= ~VTNET_CSUM_OFFLOAD;
888 		}
889 
890 		if (mask & IFCAP_TSO4) {
891 			ifp->if_capenable ^= IFCAP_TSO4;
892 			if (ifp->if_capenable & IFCAP_TSO4)
893 				ifp->if_hwassist |= CSUM_TSO;
894 			else
895 				ifp->if_hwassist &= ~CSUM_TSO;
896 		}
897 
898 		if (mask & IFCAP_RXCSUM) {
899 			ifp->if_capenable ^= IFCAP_RXCSUM;
900 			reinit = 1;
901 		}
902 
903 		if (mask & IFCAP_LRO) {
904 			ifp->if_capenable ^= IFCAP_LRO;
905 			reinit = 1;
906 		}
907 
908 		if (mask & IFCAP_VLAN_HWFILTER) {
909 			ifp->if_capenable ^= IFCAP_VLAN_HWFILTER;
910 			reinit = 1;
911 		}
912 
913 		if (mask & IFCAP_VLAN_HWTSO)
914 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
915 
916 		if (mask & IFCAP_VLAN_HWTAGGING)
917 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
918 
919 		if (reinit && (ifp->if_drv_flags & IFF_DRV_RUNNING)) {
920 			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
921 			vtnet_init_locked(sc);
922 		}
923 		VLAN_CAPABILITIES(ifp);
924 
925 		VTNET_UNLOCK(sc);
926 		break;
927 
928 	default:
929 		error = ether_ioctl(ifp, cmd, data);
930 		break;
931 	}
932 
933 	VTNET_LOCK_ASSERT_NOTOWNED(sc);
934 
935 	return (error);
936 }
937 
938 static int
939 vtnet_change_mtu(struct vtnet_softc *sc, int new_mtu)
940 {
941 	struct ifnet *ifp;
942 	int new_frame_size, clsize;
943 
944 	ifp = sc->vtnet_ifp;
945 
946 	if ((sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS) == 0) {
947 		new_frame_size = sizeof(struct vtnet_rx_header) +
948 		    sizeof(struct ether_vlan_header) + new_mtu;
949 
950 		if (new_frame_size > MJUM9BYTES)
951 			return (EINVAL);
952 
953 		if (new_frame_size <= MCLBYTES)
954 			clsize = MCLBYTES;
955 		else
956 			clsize = MJUM9BYTES;
957 	} else {
958 		new_frame_size = sizeof(struct virtio_net_hdr_mrg_rxbuf) +
959 		    sizeof(struct ether_vlan_header) + new_mtu;
960 
961 		if (new_frame_size <= MCLBYTES)
962 			clsize = MCLBYTES;
963 		else
964 			clsize = MJUMPAGESIZE;
965 	}
966 
967 	sc->vtnet_rx_mbuf_size = clsize;
968 	sc->vtnet_rx_mbuf_count = VTNET_NEEDED_RX_MBUFS(sc);
969 	KASSERT(sc->vtnet_rx_mbuf_count < VTNET_MAX_RX_SEGS,
970 	    ("too many rx mbufs: %d", sc->vtnet_rx_mbuf_count));
971 
972 	ifp->if_mtu = new_mtu;
973 
974 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
975 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
976 		vtnet_init_locked(sc);
977 	}
978 
979 	return (0);
980 }
981 
982 static int
983 vtnet_init_rx_vq(struct vtnet_softc *sc)
984 {
985 	struct virtqueue *vq;
986 	int nbufs, error;
987 
988 	vq = sc->vtnet_rx_vq;
989 	nbufs = 0;
990 	error = ENOSPC;
991 
992 	while (!virtqueue_full(vq)) {
993 		if ((error = vtnet_newbuf(sc)) != 0)
994 			break;
995 		nbufs++;
996 	}
997 
998 	if (nbufs > 0) {
999 		virtqueue_notify(vq);
1000 
1001 		/*
1002 		 * EMSGSIZE signifies the virtqueue did not have enough
1003 		 * entries available to hold the last mbuf. This is not
1004 		 * an error. We should not get ENOSPC since we check if
1005 		 * the virtqueue is full before attempting to add a
1006 		 * buffer.
1007 		 */
1008 		if (error == EMSGSIZE)
1009 			error = 0;
1010 	}
1011 
1012 	return (error);
1013 }
1014 
1015 static void
1016 vtnet_free_rx_mbufs(struct vtnet_softc *sc)
1017 {
1018 	struct virtqueue *vq;
1019 	struct mbuf *m;
1020 	int last;
1021 
1022 	vq = sc->vtnet_rx_vq;
1023 	last = 0;
1024 
1025 	while ((m = virtqueue_drain(vq, &last)) != NULL)
1026 		m_freem(m);
1027 
1028 	KASSERT(virtqueue_empty(vq), ("mbufs remaining in Rx Vq"));
1029 }
1030 
1031 static void
1032 vtnet_free_tx_mbufs(struct vtnet_softc *sc)
1033 {
1034 	struct virtqueue *vq;
1035 	struct vtnet_tx_header *txhdr;
1036 	int last;
1037 
1038 	vq = sc->vtnet_tx_vq;
1039 	last = 0;
1040 
1041 	while ((txhdr = virtqueue_drain(vq, &last)) != NULL) {
1042 		m_freem(txhdr->vth_mbuf);
1043 		uma_zfree(vtnet_tx_header_zone, txhdr);
1044 	}
1045 
1046 	KASSERT(virtqueue_empty(vq), ("mbufs remaining in Tx Vq"));
1047 }
1048 
1049 static void
1050 vtnet_free_ctrl_vq(struct vtnet_softc *sc)
1051 {
1052 
1053 	/*
1054 	 * The control virtqueue is only polled, therefore
1055 	 * it should already be empty.
1056 	 */
1057 	KASSERT(virtqueue_empty(sc->vtnet_ctrl_vq),
1058 	    ("Ctrl Vq not empty"));
1059 }
1060 
1061 #ifdef DEVICE_POLLING
1062 static int
1063 vtnet_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1064 {
1065 	struct vtnet_softc *sc;
1066 	int rx_done;
1067 
1068 	sc = ifp->if_softc;
1069 	rx_done = 0;
1070 
1071 	VTNET_LOCK(sc);
1072 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1073 		if (cmd == POLL_AND_CHECK_STATUS)
1074 			vtnet_update_link_status(sc);
1075 
1076 		if (virtqueue_nused(sc->vtnet_rx_vq) > 0)
1077 			vtnet_rxeof(sc, count, &rx_done);
1078 
1079 		vtnet_txeof(sc);
1080 		if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
1081 			vtnet_start_locked(ifp);
1082 	}
1083 	VTNET_UNLOCK(sc);
1084 
1085 	return (rx_done);
1086 }
1087 #endif /* DEVICE_POLLING */
1088 
1089 static struct mbuf *
1090 vtnet_alloc_rxbuf(struct vtnet_softc *sc, int nbufs, struct mbuf **m_tailp)
1091 {
1092 	struct mbuf *m_head, *m_tail, *m;
1093 	int i, clsize;
1094 
1095 	clsize = sc->vtnet_rx_mbuf_size;
1096 
1097 	m_head = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, clsize);
1098 	if (m_head == NULL)
1099 		goto fail;
1100 
1101 	m_head->m_len = clsize;
1102 	m_tail = m_head;
1103 
1104 	if (nbufs > 1) {
1105 		KASSERT(sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG,
1106 		    ("chained Rx mbuf requested without LRO_NOMRG"));
1107 
1108 		for (i = 0; i < nbufs - 1; i++) {
1109 			m = m_getjcl(M_DONTWAIT, MT_DATA, 0, clsize);
1110 			if (m == NULL)
1111 				goto fail;
1112 
1113 			m->m_len = clsize;
1114 			m_tail->m_next = m;
1115 			m_tail = m;
1116 		}
1117 	}
1118 
1119 	if (m_tailp != NULL)
1120 		*m_tailp = m_tail;
1121 
1122 	return (m_head);
1123 
1124 fail:
1125 	sc->vtnet_stats.mbuf_alloc_failed++;
1126 	m_freem(m_head);
1127 
1128 	return (NULL);
1129 }
1130 
1131 static int
1132 vtnet_replace_rxbuf(struct vtnet_softc *sc, struct mbuf *m0, int len0)
1133 {
1134 	struct mbuf *m, *m_prev;
1135 	struct mbuf *m_new, *m_tail;
1136 	int len, clsize, nreplace, error;
1137 
1138 	m = m0;
1139 	m_prev = NULL;
1140 	len = len0;
1141 
1142 	m_tail = NULL;
1143 	clsize = sc->vtnet_rx_mbuf_size;
1144 	nreplace = 0;
1145 
1146 	if (m->m_next != NULL)
1147 		KASSERT(sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG,
1148 		    ("chained Rx mbuf without LRO_NOMRG"));
1149 
1150 	/*
1151 	 * Since LRO_NOMRG mbuf chains are so large, we want to avoid
1152 	 * allocating an entire chain for each received frame. When
1153 	 * the received frame's length is less than that of the chain,
1154 	 * the unused mbufs are reassigned to the new chain.
1155 	 */
1156 	while (len > 0) {
1157 		/*
1158 		 * Something is seriously wrong if we received
1159 		 * a frame larger than the mbuf chain. Drop it.
1160 		 */
1161 		if (m == NULL) {
1162 			sc->vtnet_stats.rx_frame_too_large++;
1163 			return (EMSGSIZE);
1164 		}
1165 
1166 		KASSERT(m->m_len == clsize,
1167 		    ("mbuf length not expected cluster size: %d",
1168 		    m->m_len));
1169 
1170 		m->m_len = MIN(m->m_len, len);
1171 		len -= m->m_len;
1172 
1173 		m_prev = m;
1174 		m = m->m_next;
1175 		nreplace++;
1176 	}
1177 
1178 	KASSERT(m_prev != NULL, ("m_prev == NULL"));
1179 	KASSERT(nreplace <= sc->vtnet_rx_mbuf_count,
1180 	    ("too many replacement mbufs: %d/%d", nreplace,
1181 	    sc->vtnet_rx_mbuf_count));
1182 
1183 	m_new = vtnet_alloc_rxbuf(sc, nreplace, &m_tail);
1184 	if (m_new == NULL) {
1185 		m_prev->m_len = clsize;
1186 		return (ENOBUFS);
1187 	}
1188 
1189 	/*
1190 	 * Move unused mbufs, if any, from the original chain
1191 	 * onto the end of the new chain.
1192 	 */
1193 	if (m_prev->m_next != NULL) {
1194 		m_tail->m_next = m_prev->m_next;
1195 		m_prev->m_next = NULL;
1196 	}
1197 
1198 	error = vtnet_enqueue_rxbuf(sc, m_new);
1199 	if (error) {
1200 		/*
1201 		 * BAD! We could not enqueue the replacement mbuf chain. We
1202 		 * must restore the m0 chain to the original state if it was
1203 		 * modified so we can subsequently discard it.
1204 		 *
1205 		 * NOTE: The replacement is suppose to be an identical copy
1206 		 * to the one just dequeued so this is an unexpected error.
1207 		 */
1208 		sc->vtnet_stats.rx_enq_replacement_failed++;
1209 
1210 		if (m_tail->m_next != NULL) {
1211 			m_prev->m_next = m_tail->m_next;
1212 			m_tail->m_next = NULL;
1213 		}
1214 
1215 		m_prev->m_len = clsize;
1216 		m_freem(m_new);
1217 	}
1218 
1219 	return (error);
1220 }
1221 
1222 static int
1223 vtnet_newbuf(struct vtnet_softc *sc)
1224 {
1225 	struct mbuf *m;
1226 	int error;
1227 
1228 	m = vtnet_alloc_rxbuf(sc, sc->vtnet_rx_mbuf_count, NULL);
1229 	if (m == NULL)
1230 		return (ENOBUFS);
1231 
1232 	error = vtnet_enqueue_rxbuf(sc, m);
1233 	if (error)
1234 		m_freem(m);
1235 
1236 	return (error);
1237 }
1238 
1239 static void
1240 vtnet_discard_merged_rxbuf(struct vtnet_softc *sc, int nbufs)
1241 {
1242 	struct virtqueue *vq;
1243 	struct mbuf *m;
1244 
1245 	vq = sc->vtnet_rx_vq;
1246 
1247 	while (--nbufs > 0) {
1248 		if ((m = virtqueue_dequeue(vq, NULL)) == NULL)
1249 			break;
1250 		vtnet_discard_rxbuf(sc, m);
1251 	}
1252 }
1253 
1254 static void
1255 vtnet_discard_rxbuf(struct vtnet_softc *sc, struct mbuf *m)
1256 {
1257 	int error;
1258 
1259 	/*
1260 	 * Requeue the discarded mbuf. This should always be
1261 	 * successful since it was just dequeued.
1262 	 */
1263 	error = vtnet_enqueue_rxbuf(sc, m);
1264 	KASSERT(error == 0, ("cannot requeue discarded mbuf"));
1265 }
1266 
1267 static int
1268 vtnet_enqueue_rxbuf(struct vtnet_softc *sc, struct mbuf *m)
1269 {
1270 	struct sglist sg;
1271 	struct sglist_seg segs[VTNET_MAX_RX_SEGS];
1272 	struct vtnet_rx_header *rxhdr;
1273 	struct virtio_net_hdr *hdr;
1274 	uint8_t *mdata;
1275 	int offset, error;
1276 
1277 	VTNET_LOCK_ASSERT(sc);
1278 	if ((sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG) == 0)
1279 		KASSERT(m->m_next == NULL, ("chained Rx mbuf"));
1280 
1281 	sglist_init(&sg, VTNET_MAX_RX_SEGS, segs);
1282 
1283 	mdata = mtod(m, uint8_t *);
1284 	offset = 0;
1285 
1286 	if ((sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS) == 0) {
1287 		rxhdr = (struct vtnet_rx_header *) mdata;
1288 		hdr = &rxhdr->vrh_hdr;
1289 		offset += sizeof(struct vtnet_rx_header);
1290 
1291 		error = sglist_append(&sg, hdr, sc->vtnet_hdr_size);
1292 		KASSERT(error == 0, ("cannot add header to sglist"));
1293 	}
1294 
1295 	error = sglist_append(&sg, mdata + offset, m->m_len - offset);
1296 	if (error)
1297 		return (error);
1298 
1299 	if (m->m_next != NULL) {
1300 		error = sglist_append_mbuf(&sg, m->m_next);
1301 		if (error)
1302 			return (error);
1303 	}
1304 
1305 	return (virtqueue_enqueue(sc->vtnet_rx_vq, m, &sg, 0, sg.sg_nseg));
1306 }
1307 
1308 static void
1309 vtnet_vlan_tag_remove(struct mbuf *m)
1310 {
1311 	struct ether_vlan_header *evl;
1312 
1313 	evl = mtod(m, struct ether_vlan_header *);
1314 
1315 	m->m_pkthdr.ether_vtag = ntohs(evl->evl_tag);
1316 	m->m_flags |= M_VLANTAG;
1317 
1318 	/* Strip the 802.1Q header. */
1319 	bcopy((char *) evl, (char *) evl + ETHER_VLAN_ENCAP_LEN,
1320 	    ETHER_HDR_LEN - ETHER_TYPE_LEN);
1321 	m_adj(m, ETHER_VLAN_ENCAP_LEN);
1322 }
1323 
1324 #ifdef notyet
1325 static int
1326 vtnet_rx_csum(struct vtnet_softc *sc, struct mbuf *m,
1327     struct virtio_net_hdr *hdr)
1328 {
1329 	struct ether_header *eh;
1330 	struct ether_vlan_header *evh;
1331 	struct ip *ip;
1332 	struct ip6_hdr *ip6;
1333 	struct udphdr *udp;
1334 	int ip_offset, csum_start, csum_offset, hlen;
1335 	uint16_t eth_type;
1336 	uint8_t ip_proto;
1337 
1338 	/*
1339 	 * Convert the VirtIO checksum interface to FreeBSD's interface.
1340 	 * The host only provides us with the offset at which to start
1341 	 * checksumming, and the offset from that to place the completed
1342 	 * checksum. While this maps well with how Linux does checksums,
1343 	 * for FreeBSD, we must parse the received packet in order to set
1344 	 * the appropriate CSUM_* flags.
1345 	 */
1346 
1347 	/*
1348 	 * Every mbuf added to the receive virtqueue is always at least
1349 	 * MCLBYTES big, so assume something is amiss if the first mbuf
1350 	 * does not contain both the Ethernet and protocol headers.
1351 	 */
1352 	ip_offset = sizeof(struct ether_header);
1353 	if (m->m_len < ip_offset)
1354 		return (1);
1355 
1356 	eh = mtod(m, struct ether_header *);
1357 	eth_type = ntohs(eh->ether_type);
1358 	if (eth_type == ETHERTYPE_VLAN) {
1359 		ip_offset = sizeof(struct ether_vlan_header);
1360 		if (m->m_len < ip_offset)
1361 			return (1);
1362 		evh = mtod(m, struct ether_vlan_header *);
1363 		eth_type = ntohs(evh->evl_proto);
1364 	}
1365 
1366 	switch (eth_type) {
1367 	case ETHERTYPE_IP:
1368 		if (m->m_len < ip_offset + sizeof(struct ip))
1369 			return (1);
1370 
1371 		ip = (struct ip *)(mtod(m, uint8_t *) + ip_offset);
1372 		 /* Sanity check the IP header. */
1373 		if (ip->ip_v != IPVERSION)
1374 			return (1);
1375 		hlen = ip->ip_hl << 2;
1376 		if (hlen < sizeof(struct ip))
1377 			return (1);
1378 		if (ntohs(ip->ip_len) < hlen)
1379 			return (1);
1380 		if (ntohs(ip->ip_len) != (m->m_pkthdr.len - ip_offset))
1381 			return (1);
1382 
1383 		ip_proto = ip->ip_p;
1384 		csum_start = ip_offset + hlen;
1385 		break;
1386 
1387 	case ETHERTYPE_IPV6:
1388 		if (m->m_len < ip_offset + sizeof(struct ip6_hdr))
1389 			return (1);
1390 
1391 		/*
1392 		 * XXX FreeBSD does not handle any IPv6 checksum offloading
1393 		 * at the moment.
1394 		 */
1395 
1396 		ip6 = (struct ip6_hdr *)(mtod(m, uint8_t *) + ip_offset);
1397 		/* XXX Assume no extension headers are present. */
1398 		ip_proto = ip6->ip6_nxt;
1399 		csum_start = ip_offset + sizeof(struct ip6_hdr);
1400 		break;
1401 
1402 	default:
1403 		sc->vtnet_stats.rx_csum_bad_ethtype++;
1404 		return (1);
1405 	}
1406 
1407 	/* Assume checksum begins right after the IP header. */
1408 	if (hdr->csum_start != csum_start) {
1409 		sc->vtnet_stats.rx_csum_bad_start++;
1410 		return (1);
1411 	}
1412 
1413 	switch (ip_proto) {
1414 	case IPPROTO_TCP:
1415 		csum_offset = offsetof(struct tcphdr, th_sum);
1416 		break;
1417 
1418 	case IPPROTO_UDP:
1419 		csum_offset = offsetof(struct udphdr, uh_sum);
1420 		break;
1421 
1422 	case IPPROTO_SCTP:
1423 		csum_offset = offsetof(struct sctphdr, checksum);
1424 		break;
1425 
1426 	default:
1427 		sc->vtnet_stats.rx_csum_bad_ipproto++;
1428 		return (1);
1429 	}
1430 
1431 	if (hdr->csum_offset != csum_offset) {
1432 		sc->vtnet_stats.rx_csum_bad_offset++;
1433 		return (1);
1434 	}
1435 
1436 	/*
1437 	 * The IP header checksum is almost certainly valid but I'm
1438 	 * uncertain if that is guaranteed.
1439 	 *
1440 	 * m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED | CSUM_IP_VALID;
1441 	 */
1442 
1443 	switch (ip_proto) {
1444 	case IPPROTO_UDP:
1445 		if (m->m_len < csum_start + sizeof(struct udphdr))
1446 			return (1);
1447 
1448 		udp = (struct udphdr *)(mtod(m, uint8_t *) + csum_start);
1449 		if (udp->uh_sum == 0)
1450 			return (0);
1451 
1452 		/* FALLTHROUGH */
1453 
1454 	case IPPROTO_TCP:
1455 		m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1456 		m->m_pkthdr.csum_data = 0xFFFF;
1457 		break;
1458 
1459 	case IPPROTO_SCTP:
1460 		m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
1461 		break;
1462 	}
1463 
1464 	sc->vtnet_stats.rx_csum_offloaded++;
1465 
1466 	return (0);
1467 }
1468 #endif
1469 
1470 /*
1471  * Alternative method of doing receive checksum offloading. Rather
1472  * than parsing the received frame down to the IP header, use the
1473  * csum_offset to determine which CSUM_* flags are appropriate. We
1474  * can get by with doing this only because the checksum offsets are
1475  * unique for the things we care about.
1476  */
1477 static int
1478 vtnet_rx_csum(struct vtnet_softc *sc, struct mbuf *m,
1479     struct virtio_net_hdr *hdr)
1480 {
1481 	struct ether_header *eh;
1482 	struct ether_vlan_header *evh;
1483 	struct udphdr *udp;
1484 	int csum_len;
1485 	uint16_t eth_type;
1486 
1487 	csum_len = hdr->csum_start + hdr->csum_offset;
1488 
1489 	if (csum_len < sizeof(struct ether_header) + sizeof(struct ip))
1490 		return (1);
1491 	if (m->m_len < csum_len)
1492 		return (1);
1493 
1494 	eh = mtod(m, struct ether_header *);
1495 	eth_type = ntohs(eh->ether_type);
1496 	if (eth_type == ETHERTYPE_VLAN) {
1497 		evh = mtod(m, struct ether_vlan_header *);
1498 		eth_type = ntohs(evh->evl_proto);
1499 	}
1500 
1501 	if (eth_type != ETHERTYPE_IP && eth_type != ETHERTYPE_IPV6) {
1502 		sc->vtnet_stats.rx_csum_bad_ethtype++;
1503 		return (1);
1504 	}
1505 
1506 	/* Use the offset to determine the appropriate CSUM_* flags. */
1507 	switch (hdr->csum_offset) {
1508 	case offsetof(struct udphdr, uh_sum):
1509 		if (m->m_len < hdr->csum_start + sizeof(struct udphdr))
1510 			return (1);
1511 		udp = (struct udphdr *)(mtod(m, uint8_t *) + hdr->csum_start);
1512 		if (udp->uh_sum == 0)
1513 			return (0);
1514 
1515 		/* FALLTHROUGH */
1516 
1517 	case offsetof(struct tcphdr, th_sum):
1518 		m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1519 		m->m_pkthdr.csum_data = 0xFFFF;
1520 		break;
1521 
1522 	case offsetof(struct sctphdr, checksum):
1523 		m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
1524 		break;
1525 
1526 	default:
1527 		sc->vtnet_stats.rx_csum_bad_offset++;
1528 		return (1);
1529 	}
1530 
1531 	sc->vtnet_stats.rx_csum_offloaded++;
1532 
1533 	return (0);
1534 }
1535 
1536 static int
1537 vtnet_rxeof_merged(struct vtnet_softc *sc, struct mbuf *m_head, int nbufs)
1538 {
1539 	struct ifnet *ifp;
1540 	struct virtqueue *vq;
1541 	struct mbuf *m, *m_tail;
1542 	int len;
1543 
1544 	ifp = sc->vtnet_ifp;
1545 	vq = sc->vtnet_rx_vq;
1546 	m_tail = m_head;
1547 
1548 	while (--nbufs > 0) {
1549 		m = virtqueue_dequeue(vq, &len);
1550 		if (m == NULL) {
1551 			ifp->if_ierrors++;
1552 			goto fail;
1553 		}
1554 
1555 		if (vtnet_newbuf(sc) != 0) {
1556 			ifp->if_iqdrops++;
1557 			vtnet_discard_rxbuf(sc, m);
1558 			if (nbufs > 1)
1559 				vtnet_discard_merged_rxbuf(sc, nbufs);
1560 			goto fail;
1561 		}
1562 
1563 		if (m->m_len < len)
1564 			len = m->m_len;
1565 
1566 		m->m_len = len;
1567 		m->m_flags &= ~M_PKTHDR;
1568 
1569 		m_head->m_pkthdr.len += len;
1570 		m_tail->m_next = m;
1571 		m_tail = m;
1572 	}
1573 
1574 	return (0);
1575 
1576 fail:
1577 	sc->vtnet_stats.rx_mergeable_failed++;
1578 	m_freem(m_head);
1579 
1580 	return (1);
1581 }
1582 
1583 static int
1584 vtnet_rxeof(struct vtnet_softc *sc, int count, int *rx_npktsp)
1585 {
1586 	struct virtio_net_hdr lhdr;
1587 	struct ifnet *ifp;
1588 	struct virtqueue *vq;
1589 	struct mbuf *m;
1590 	struct ether_header *eh;
1591 	struct virtio_net_hdr *hdr;
1592 	struct virtio_net_hdr_mrg_rxbuf *mhdr;
1593 	int len, deq, nbufs, adjsz, rx_npkts;
1594 
1595 	ifp = sc->vtnet_ifp;
1596 	vq = sc->vtnet_rx_vq;
1597 	hdr = &lhdr;
1598 	deq = 0;
1599 	rx_npkts = 0;
1600 
1601 	VTNET_LOCK_ASSERT(sc);
1602 
1603 	while (--count >= 0) {
1604 		m = virtqueue_dequeue(vq, &len);
1605 		if (m == NULL)
1606 			break;
1607 		deq++;
1608 
1609 		if (len < sc->vtnet_hdr_size + ETHER_HDR_LEN) {
1610 			ifp->if_ierrors++;
1611 			vtnet_discard_rxbuf(sc, m);
1612 			continue;
1613 		}
1614 
1615 		if ((sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS) == 0) {
1616 			nbufs = 1;
1617 			adjsz = sizeof(struct vtnet_rx_header);
1618 			/*
1619 			 * Account for our pad between the header and
1620 			 * the actual start of the frame.
1621 			 */
1622 			len += VTNET_RX_HEADER_PAD;
1623 		} else {
1624 			mhdr = mtod(m, struct virtio_net_hdr_mrg_rxbuf *);
1625 			nbufs = mhdr->num_buffers;
1626 			adjsz = sizeof(struct virtio_net_hdr_mrg_rxbuf);
1627 		}
1628 
1629 		if (vtnet_replace_rxbuf(sc, m, len) != 0) {
1630 			ifp->if_iqdrops++;
1631 			vtnet_discard_rxbuf(sc, m);
1632 			if (nbufs > 1)
1633 				vtnet_discard_merged_rxbuf(sc, nbufs);
1634 			continue;
1635 		}
1636 
1637 		m->m_pkthdr.len = len;
1638 		m->m_pkthdr.rcvif = ifp;
1639 		m->m_pkthdr.csum_flags = 0;
1640 
1641 		if (nbufs > 1) {
1642 			if (vtnet_rxeof_merged(sc, m, nbufs) != 0)
1643 				continue;
1644 		}
1645 
1646 		ifp->if_ipackets++;
1647 
1648 		/*
1649 		 * Save copy of header before we strip it. For both mergeable
1650 		 * and non-mergeable, the VirtIO header is placed first in the
1651 		 * mbuf's data. We no longer need num_buffers, so always use a
1652 		 * virtio_net_hdr.
1653 		 */
1654 		memcpy(hdr, mtod(m, void *), sizeof(struct virtio_net_hdr));
1655 		m_adj(m, adjsz);
1656 
1657 		if (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) {
1658 			eh = mtod(m, struct ether_header *);
1659 			if (eh->ether_type == htons(ETHERTYPE_VLAN)) {
1660 				vtnet_vlan_tag_remove(m);
1661 
1662 				/*
1663 				 * With the 802.1Q header removed, update the
1664 				 * checksum starting location accordingly.
1665 				 */
1666 				if (hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
1667 					hdr->csum_start -=
1668 					    ETHER_VLAN_ENCAP_LEN;
1669 			}
1670 		}
1671 
1672 		if (ifp->if_capenable & IFCAP_RXCSUM &&
1673 		    hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
1674 			if (vtnet_rx_csum(sc, m, hdr) != 0)
1675 				sc->vtnet_stats.rx_csum_failed++;
1676 		}
1677 
1678 		VTNET_UNLOCK(sc);
1679 		rx_npkts++;
1680 		(*ifp->if_input)(ifp, m);
1681 		VTNET_LOCK(sc);
1682 
1683 		/*
1684 		 * The interface may have been stopped while we were
1685 		 * passing the packet up the network stack.
1686 		 */
1687 		if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1688 			break;
1689 	}
1690 
1691 	virtqueue_notify(vq);
1692 
1693 	if (rx_npktsp != NULL)
1694 		*rx_npktsp = rx_npkts;
1695 
1696 	return (count > 0 ? 0 : EAGAIN);
1697 }
1698 
1699 static void
1700 vtnet_rx_intr_task(void *arg, int pending)
1701 {
1702 	struct vtnet_softc *sc;
1703 	struct ifnet *ifp;
1704 	int more;
1705 
1706 	sc = arg;
1707 	ifp = sc->vtnet_ifp;
1708 
1709 	VTNET_LOCK(sc);
1710 
1711 #ifdef DEVICE_POLLING
1712 	if (ifp->if_capenable & IFCAP_POLLING) {
1713 		VTNET_UNLOCK(sc);
1714 		return;
1715 	}
1716 #endif
1717 
1718 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1719 		vtnet_enable_rx_intr(sc);
1720 		VTNET_UNLOCK(sc);
1721 		return;
1722 	}
1723 
1724 	more = vtnet_rxeof(sc, sc->vtnet_rx_process_limit, NULL);
1725 	if (!more && vtnet_enable_rx_intr(sc) != 0) {
1726 		vtnet_disable_rx_intr(sc);
1727 		more = 1;
1728 	}
1729 
1730 	VTNET_UNLOCK(sc);
1731 
1732 	if (more) {
1733 		sc->vtnet_stats.rx_task_rescheduled++;
1734 		taskqueue_enqueue_fast(sc->vtnet_tq,
1735 		    &sc->vtnet_rx_intr_task);
1736 	}
1737 }
1738 
1739 static int
1740 vtnet_rx_vq_intr(void *xsc)
1741 {
1742 	struct vtnet_softc *sc;
1743 
1744 	sc = xsc;
1745 
1746 	vtnet_disable_rx_intr(sc);
1747 	taskqueue_enqueue_fast(sc->vtnet_tq, &sc->vtnet_rx_intr_task);
1748 
1749 	return (1);
1750 }
1751 
1752 static void
1753 vtnet_txeof(struct vtnet_softc *sc)
1754 {
1755 	struct virtqueue *vq;
1756 	struct ifnet *ifp;
1757 	struct vtnet_tx_header *txhdr;
1758 	int deq;
1759 
1760 	vq = sc->vtnet_tx_vq;
1761 	ifp = sc->vtnet_ifp;
1762 	deq = 0;
1763 
1764 	VTNET_LOCK_ASSERT(sc);
1765 
1766 	while ((txhdr = virtqueue_dequeue(vq, NULL)) != NULL) {
1767 		deq++;
1768 		ifp->if_opackets++;
1769 		m_freem(txhdr->vth_mbuf);
1770 		uma_zfree(vtnet_tx_header_zone, txhdr);
1771 	}
1772 
1773 	if (deq > 0) {
1774 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1775 		if (virtqueue_empty(vq))
1776 			sc->vtnet_watchdog_timer = 0;
1777 	}
1778 }
1779 
1780 static struct mbuf *
1781 vtnet_tx_offload(struct vtnet_softc *sc, struct mbuf *m,
1782     struct virtio_net_hdr *hdr)
1783 {
1784 	struct ifnet *ifp;
1785 	struct ether_header *eh;
1786 	struct ether_vlan_header *evh;
1787 	struct ip *ip;
1788 	struct ip6_hdr *ip6;
1789 	struct tcphdr *tcp;
1790 	int ip_offset;
1791 	uint16_t eth_type, csum_start;
1792 	uint8_t ip_proto, gso_type;
1793 
1794 	ifp = sc->vtnet_ifp;
1795 	M_ASSERTPKTHDR(m);
1796 
1797 	ip_offset = sizeof(struct ether_header);
1798 	if (m->m_len < ip_offset) {
1799 		if ((m = m_pullup(m, ip_offset)) == NULL)
1800 			return (NULL);
1801 	}
1802 
1803 	eh = mtod(m, struct ether_header *);
1804 	eth_type = ntohs(eh->ether_type);
1805 	if (eth_type == ETHERTYPE_VLAN) {
1806 		ip_offset = sizeof(struct ether_vlan_header);
1807 		if (m->m_len < ip_offset) {
1808 			if ((m = m_pullup(m, ip_offset)) == NULL)
1809 				return (NULL);
1810 		}
1811 		evh = mtod(m, struct ether_vlan_header *);
1812 		eth_type = ntohs(evh->evl_proto);
1813 	}
1814 
1815 	switch (eth_type) {
1816 	case ETHERTYPE_IP:
1817 		if (m->m_len < ip_offset + sizeof(struct ip)) {
1818 			m = m_pullup(m, ip_offset + sizeof(struct ip));
1819 			if (m == NULL)
1820 				return (NULL);
1821 		}
1822 
1823 		ip = (struct ip *)(mtod(m, uint8_t *) + ip_offset);
1824 		ip_proto = ip->ip_p;
1825 		csum_start = ip_offset + (ip->ip_hl << 2);
1826 		gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
1827 		break;
1828 
1829 	case ETHERTYPE_IPV6:
1830 		if (m->m_len < ip_offset + sizeof(struct ip6_hdr)) {
1831 			m = m_pullup(m, ip_offset + sizeof(struct ip6_hdr));
1832 			if (m == NULL)
1833 				return (NULL);
1834 		}
1835 
1836 		ip6 = (struct ip6_hdr *)(mtod(m, uint8_t *) + ip_offset);
1837 		/*
1838 		 * XXX Assume no extension headers are present. Presently,
1839 		 * this will always be true in the case of TSO, and FreeBSD
1840 		 * does not perform checksum offloading of IPv6 yet.
1841 		 */
1842 		ip_proto = ip6->ip6_nxt;
1843 		csum_start = ip_offset + sizeof(struct ip6_hdr);
1844 		gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
1845 		break;
1846 
1847 	default:
1848 		return (m);
1849 	}
1850 
1851 	if (m->m_pkthdr.csum_flags & VTNET_CSUM_OFFLOAD) {
1852 		hdr->flags |= VIRTIO_NET_HDR_F_NEEDS_CSUM;
1853 		hdr->csum_start = csum_start;
1854 		hdr->csum_offset = m->m_pkthdr.csum_data;
1855 
1856 		sc->vtnet_stats.tx_csum_offloaded++;
1857 	}
1858 
1859 	if (m->m_pkthdr.csum_flags & CSUM_TSO) {
1860 		if (ip_proto != IPPROTO_TCP)
1861 			return (m);
1862 
1863 		if (m->m_len < csum_start + sizeof(struct tcphdr)) {
1864 			m = m_pullup(m, csum_start + sizeof(struct tcphdr));
1865 			if (m == NULL)
1866 				return (NULL);
1867 		}
1868 
1869 		tcp = (struct tcphdr *)(mtod(m, uint8_t *) + csum_start);
1870 		hdr->gso_type = gso_type;
1871 		hdr->hdr_len = csum_start + (tcp->th_off << 2);
1872 		hdr->gso_size = m->m_pkthdr.tso_segsz;
1873 
1874 		if (tcp->th_flags & TH_CWR) {
1875 			/*
1876 			 * Drop if we did not negotiate VIRTIO_NET_F_HOST_ECN.
1877 			 * ECN support is only configurable globally with the
1878 			 * net.inet.tcp.ecn.enable sysctl knob.
1879 			 */
1880 			if ((sc->vtnet_flags & VTNET_FLAG_TSO_ECN) == 0) {
1881 				if_printf(ifp, "TSO with ECN not supported "
1882 				    "by host\n");
1883 				m_freem(m);
1884 				return (NULL);
1885 			}
1886 
1887 			hdr->flags |= VIRTIO_NET_HDR_GSO_ECN;
1888 		}
1889 
1890 		sc->vtnet_stats.tx_tso_offloaded++;
1891 	}
1892 
1893 	return (m);
1894 }
1895 
1896 static int
1897 vtnet_enqueue_txbuf(struct vtnet_softc *sc, struct mbuf **m_head,
1898     struct vtnet_tx_header *txhdr)
1899 {
1900 	struct sglist sg;
1901 	struct sglist_seg segs[VTNET_MAX_TX_SEGS];
1902 	struct virtqueue *vq;
1903 	struct mbuf *m;
1904 	int collapsed, error;
1905 
1906 	vq = sc->vtnet_tx_vq;
1907 	m = *m_head;
1908 	collapsed = 0;
1909 
1910 	sglist_init(&sg, VTNET_MAX_TX_SEGS, segs);
1911 	error = sglist_append(&sg, &txhdr->vth_uhdr, sc->vtnet_hdr_size);
1912 	KASSERT(error == 0 && sg.sg_nseg == 1,
1913 	    ("cannot add header to sglist"));
1914 
1915 again:
1916 	error = sglist_append_mbuf(&sg, m);
1917 	if (error) {
1918 		if (collapsed)
1919 			goto fail;
1920 
1921 		m = m_collapse(m, M_DONTWAIT, VTNET_MAX_TX_SEGS - 1);
1922 		if (m == NULL)
1923 			goto fail;
1924 
1925 		*m_head = m;
1926 		collapsed = 1;
1927 		goto again;
1928 	}
1929 
1930 	txhdr->vth_mbuf = m;
1931 
1932 	return (virtqueue_enqueue(vq, txhdr, &sg, sg.sg_nseg, 0));
1933 
1934 fail:
1935 	m_freem(*m_head);
1936 	*m_head = NULL;
1937 
1938 	return (ENOBUFS);
1939 }
1940 
1941 static int
1942 vtnet_encap(struct vtnet_softc *sc, struct mbuf **m_head)
1943 {
1944 	struct vtnet_tx_header *txhdr;
1945 	struct virtio_net_hdr *hdr;
1946 	struct mbuf *m;
1947 	int error;
1948 
1949 	txhdr = uma_zalloc(vtnet_tx_header_zone, M_NOWAIT | M_ZERO);
1950 	if (txhdr == NULL)
1951 		return (ENOMEM);
1952 
1953 	/*
1954 	 * Always use the non-mergeable header to simplify things. When
1955 	 * the mergeable feature is negotiated, the num_buffers field
1956 	 * must be set to zero. We use vtnet_hdr_size later to enqueue
1957 	 * the correct header size to the host.
1958 	 */
1959 	hdr = &txhdr->vth_uhdr.hdr;
1960 	m = *m_head;
1961 
1962 	error = ENOBUFS;
1963 
1964 	if (m->m_flags & M_VLANTAG) {
1965 		m = ether_vlanencap(m, m->m_pkthdr.ether_vtag);
1966 		if ((*m_head = m) == NULL)
1967 			goto fail;
1968 		m->m_flags &= ~M_VLANTAG;
1969 	}
1970 
1971 	if (m->m_pkthdr.csum_flags != 0) {
1972 		m = vtnet_tx_offload(sc, m, hdr);
1973 		if ((*m_head = m) == NULL)
1974 			goto fail;
1975 	}
1976 
1977 	error = vtnet_enqueue_txbuf(sc, m_head, txhdr);
1978 fail:
1979 	if (error)
1980 		uma_zfree(vtnet_tx_header_zone, txhdr);
1981 
1982 	return (error);
1983 }
1984 
1985 static void
1986 vtnet_start(struct ifnet *ifp)
1987 {
1988 	struct vtnet_softc *sc;
1989 
1990 	sc = ifp->if_softc;
1991 
1992 	VTNET_LOCK(sc);
1993 	vtnet_start_locked(ifp);
1994 	VTNET_UNLOCK(sc);
1995 }
1996 
1997 static void
1998 vtnet_start_locked(struct ifnet *ifp)
1999 {
2000 	struct vtnet_softc *sc;
2001 	struct virtqueue *vq;
2002 	struct mbuf *m0;
2003 	int enq;
2004 
2005 	sc = ifp->if_softc;
2006 	vq = sc->vtnet_tx_vq;
2007 	enq = 0;
2008 
2009 	VTNET_LOCK_ASSERT(sc);
2010 
2011 	if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
2012 	    IFF_DRV_RUNNING || ((sc->vtnet_flags & VTNET_FLAG_LINK) == 0))
2013 		return;
2014 
2015 #ifdef VTNET_TX_INTR_MODERATION
2016 	if (virtqueue_nused(vq) >= sc->vtnet_tx_size / 2)
2017 		vtnet_txeof(sc);
2018 #endif
2019 
2020 	while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
2021 		if (virtqueue_full(vq)) {
2022 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2023 			break;
2024 		}
2025 
2026 		IFQ_DRV_DEQUEUE(&ifp->if_snd, m0);
2027 		if (m0 == NULL)
2028 			break;
2029 
2030 		if (vtnet_encap(sc, &m0) != 0) {
2031 			if (m0 == NULL)
2032 				break;
2033 			IFQ_DRV_PREPEND(&ifp->if_snd, m0);
2034 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2035 			break;
2036 		}
2037 
2038 		enq++;
2039 		ETHER_BPF_MTAP(ifp, m0);
2040 	}
2041 
2042 	if (enq > 0) {
2043 		virtqueue_notify(vq);
2044 		sc->vtnet_watchdog_timer = VTNET_WATCHDOG_TIMEOUT;
2045 	}
2046 }
2047 
2048 static void
2049 vtnet_tick(void *xsc)
2050 {
2051 	struct vtnet_softc *sc;
2052 
2053 	sc = xsc;
2054 
2055 	VTNET_LOCK_ASSERT(sc);
2056 #ifdef VTNET_DEBUG
2057 	virtqueue_dump(sc->vtnet_rx_vq);
2058 	virtqueue_dump(sc->vtnet_tx_vq);
2059 #endif
2060 
2061 	vtnet_watchdog(sc);
2062 	callout_reset(&sc->vtnet_tick_ch, hz, vtnet_tick, sc);
2063 }
2064 
2065 static void
2066 vtnet_tx_intr_task(void *arg, int pending)
2067 {
2068 	struct vtnet_softc *sc;
2069 	struct ifnet *ifp;
2070 
2071 	sc = arg;
2072 	ifp = sc->vtnet_ifp;
2073 
2074 	VTNET_LOCK(sc);
2075 
2076 #ifdef DEVICE_POLLING
2077 	if (ifp->if_capenable & IFCAP_POLLING) {
2078 		VTNET_UNLOCK(sc);
2079 		return;
2080 	}
2081 #endif
2082 
2083 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
2084 		vtnet_enable_tx_intr(sc);
2085 		VTNET_UNLOCK(sc);
2086 		return;
2087 	}
2088 
2089 	vtnet_txeof(sc);
2090 
2091 	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
2092 		vtnet_start_locked(ifp);
2093 
2094 	if (vtnet_enable_tx_intr(sc) != 0) {
2095 		vtnet_disable_tx_intr(sc);
2096 		sc->vtnet_stats.tx_task_rescheduled++;
2097 		VTNET_UNLOCK(sc);
2098 		taskqueue_enqueue_fast(sc->vtnet_tq, &sc->vtnet_tx_intr_task);
2099 		return;
2100 	}
2101 
2102 	VTNET_UNLOCK(sc);
2103 }
2104 
2105 static int
2106 vtnet_tx_vq_intr(void *xsc)
2107 {
2108 	struct vtnet_softc *sc;
2109 
2110 	sc = xsc;
2111 
2112 	vtnet_disable_tx_intr(sc);
2113 	taskqueue_enqueue_fast(sc->vtnet_tq, &sc->vtnet_tx_intr_task);
2114 
2115 	return (1);
2116 }
2117 
2118 static void
2119 vtnet_stop(struct vtnet_softc *sc)
2120 {
2121 	device_t dev;
2122 	struct ifnet *ifp;
2123 
2124 	dev = sc->vtnet_dev;
2125 	ifp = sc->vtnet_ifp;
2126 
2127 	VTNET_LOCK_ASSERT(sc);
2128 
2129 	sc->vtnet_watchdog_timer = 0;
2130 	callout_stop(&sc->vtnet_tick_ch);
2131 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2132 
2133 	vtnet_disable_rx_intr(sc);
2134 	vtnet_disable_tx_intr(sc);
2135 
2136 	/*
2137 	 * Stop the host VirtIO adapter. Note this will reset the host
2138 	 * adapter's state back to the pre-initialized state, so in
2139 	 * order to make the device usable again, we must drive it
2140 	 * through virtio_reinit() and virtio_reinit_complete().
2141 	 */
2142 	virtio_stop(dev);
2143 
2144 	sc->vtnet_flags &= ~VTNET_FLAG_LINK;
2145 
2146 	vtnet_free_rx_mbufs(sc);
2147 	vtnet_free_tx_mbufs(sc);
2148 }
2149 
2150 static int
2151 vtnet_reinit(struct vtnet_softc *sc)
2152 {
2153 	struct ifnet *ifp;
2154 	uint64_t features;
2155 
2156 	ifp = sc->vtnet_ifp;
2157 	features = sc->vtnet_features;
2158 
2159 	/*
2160 	 * Re-negotiate with the host, removing any disabled receive
2161 	 * features. Transmit features are disabled only on our side
2162 	 * via if_capenable and if_hwassist.
2163 	 */
2164 
2165 	if (ifp->if_capabilities & IFCAP_RXCSUM) {
2166 		if ((ifp->if_capenable & IFCAP_RXCSUM) == 0)
2167 			features &= ~VIRTIO_NET_F_GUEST_CSUM;
2168 	}
2169 
2170 	if (ifp->if_capabilities & IFCAP_LRO) {
2171 		if ((ifp->if_capenable & IFCAP_LRO) == 0)
2172 			features &= ~VTNET_LRO_FEATURES;
2173 	}
2174 
2175 	if (ifp->if_capabilities & IFCAP_VLAN_HWFILTER) {
2176 		if ((ifp->if_capenable & IFCAP_VLAN_HWFILTER) == 0)
2177 			features &= ~VIRTIO_NET_F_CTRL_VLAN;
2178 	}
2179 
2180 	return (virtio_reinit(sc->vtnet_dev, features));
2181 }
2182 
2183 static void
2184 vtnet_init_locked(struct vtnet_softc *sc)
2185 {
2186 	device_t dev;
2187 	struct ifnet *ifp;
2188 	int error;
2189 
2190 	dev = sc->vtnet_dev;
2191 	ifp = sc->vtnet_ifp;
2192 
2193 	VTNET_LOCK_ASSERT(sc);
2194 
2195 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2196 		return;
2197 
2198 	/* Stop host's adapter, cancel any pending I/O. */
2199 	vtnet_stop(sc);
2200 
2201 	/* Reinitialize the host device. */
2202 	error = vtnet_reinit(sc);
2203 	if (error) {
2204 		device_printf(dev,
2205 		    "reinitialization failed, stopping device...\n");
2206 		vtnet_stop(sc);
2207 		return;
2208 	}
2209 
2210 	/* Update host with assigned MAC address. */
2211 	bcopy(IF_LLADDR(ifp), sc->vtnet_hwaddr, ETHER_ADDR_LEN);
2212 	vtnet_set_hwaddr(sc);
2213 
2214 	ifp->if_hwassist = 0;
2215 	if (ifp->if_capenable & IFCAP_TXCSUM)
2216 		ifp->if_hwassist |= VTNET_CSUM_OFFLOAD;
2217 	if (ifp->if_capenable & IFCAP_TSO4)
2218 		ifp->if_hwassist |= CSUM_TSO;
2219 
2220 	error = vtnet_init_rx_vq(sc);
2221 	if (error) {
2222 		device_printf(dev,
2223 		    "cannot allocate mbufs for Rx virtqueue\n");
2224 		vtnet_stop(sc);
2225 		return;
2226 	}
2227 
2228 	if (sc->vtnet_flags & VTNET_FLAG_CTRL_VQ) {
2229 		if (sc->vtnet_flags & VTNET_FLAG_CTRL_RX) {
2230 			/* Restore promiscuous and all-multicast modes. */
2231 			vtnet_rx_filter(sc);
2232 
2233 			/* Restore filtered MAC addresses. */
2234 			vtnet_rx_filter_mac(sc);
2235 		}
2236 
2237 		/* Restore VLAN filters. */
2238 		if (ifp->if_capenable & IFCAP_VLAN_HWFILTER)
2239 			vtnet_rx_filter_vlan(sc);
2240 	}
2241 
2242 #ifdef DEVICE_POLLING
2243 	if (ifp->if_capenable & IFCAP_POLLING) {
2244 		vtnet_disable_rx_intr(sc);
2245 		vtnet_disable_tx_intr(sc);
2246 	} else
2247 #endif
2248 	{
2249 		vtnet_enable_rx_intr(sc);
2250 		vtnet_enable_tx_intr(sc);
2251 	}
2252 
2253 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2254 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2255 
2256 	virtio_reinit_complete(dev);
2257 
2258 	vtnet_update_link_status(sc);
2259 	callout_reset(&sc->vtnet_tick_ch, hz, vtnet_tick, sc);
2260 }
2261 
2262 static void
2263 vtnet_init(void *xsc)
2264 {
2265 	struct vtnet_softc *sc;
2266 
2267 	sc = xsc;
2268 
2269 	VTNET_LOCK(sc);
2270 	vtnet_init_locked(sc);
2271 	VTNET_UNLOCK(sc);
2272 }
2273 
2274 static void
2275 vtnet_exec_ctrl_cmd(struct vtnet_softc *sc, void *cookie,
2276     struct sglist *sg, int readable, int writable)
2277 {
2278 	struct virtqueue *vq;
2279 	void *c;
2280 
2281 	vq = sc->vtnet_ctrl_vq;
2282 
2283 	VTNET_LOCK_ASSERT(sc);
2284 	KASSERT(sc->vtnet_flags & VTNET_FLAG_CTRL_VQ,
2285 	    ("no control virtqueue"));
2286 	KASSERT(virtqueue_empty(vq),
2287 	    ("control command already enqueued"));
2288 
2289 	if (virtqueue_enqueue(vq, cookie, sg, readable, writable) != 0)
2290 		return;
2291 
2292 	virtqueue_notify(vq);
2293 
2294 	/*
2295 	 * Poll until the command is complete. Previously, we would
2296 	 * sleep until the control virtqueue interrupt handler woke
2297 	 * us up, but dropping the VTNET_MTX leads to serialization
2298 	 * difficulties.
2299 	 *
2300 	 * Furthermore, it appears QEMU/KVM only allocates three MSIX
2301 	 * vectors. Two of those vectors are needed for the Rx and Tx
2302 	 * virtqueues. We do not support sharing both a Vq and config
2303 	 * changed notification on the same MSIX vector.
2304 	 */
2305 	c = virtqueue_poll(vq, NULL);
2306 	KASSERT(c == cookie, ("unexpected control command response"));
2307 }
2308 
2309 static void
2310 vtnet_rx_filter(struct vtnet_softc *sc)
2311 {
2312 	device_t dev;
2313 	struct ifnet *ifp;
2314 
2315 	dev = sc->vtnet_dev;
2316 	ifp = sc->vtnet_ifp;
2317 
2318 	VTNET_LOCK_ASSERT(sc);
2319 	KASSERT(sc->vtnet_flags & VTNET_FLAG_CTRL_RX,
2320 	    ("CTRL_RX feature not negotiated"));
2321 
2322 	if (vtnet_set_promisc(sc, ifp->if_flags & IFF_PROMISC) != 0)
2323 		device_printf(dev, "cannot %s promiscuous mode\n",
2324 		    ifp->if_flags & IFF_PROMISC ? "enable" : "disable");
2325 
2326 	if (vtnet_set_allmulti(sc, ifp->if_flags & IFF_ALLMULTI) != 0)
2327 		device_printf(dev, "cannot %s all-multicast mode\n",
2328 		    ifp->if_flags & IFF_ALLMULTI ? "enable" : "disable");
2329 }
2330 
2331 static int
2332 vtnet_ctrl_rx_cmd(struct vtnet_softc *sc, int cmd, int on)
2333 {
2334 	struct virtio_net_ctrl_hdr hdr;
2335 	struct sglist_seg segs[3];
2336 	struct sglist sg;
2337 	uint8_t onoff, ack;
2338 	int error;
2339 
2340 	if ((sc->vtnet_flags & VTNET_FLAG_CTRL_RX) == 0)
2341 		return (ENOTSUP);
2342 
2343 	error = 0;
2344 
2345 	hdr.class = VIRTIO_NET_CTRL_RX;
2346 	hdr.cmd = cmd;
2347 	onoff = !!on;
2348 	ack = VIRTIO_NET_ERR;
2349 
2350 	sglist_init(&sg, 3, segs);
2351 	error |= sglist_append(&sg, &hdr, sizeof(struct virtio_net_ctrl_hdr));
2352 	error |= sglist_append(&sg, &onoff, sizeof(uint8_t));
2353 	error |= sglist_append(&sg, &ack, sizeof(uint8_t));
2354 	KASSERT(error == 0 && sg.sg_nseg == 3,
2355 	    ("error adding Rx filter message to sglist"));
2356 
2357 	vtnet_exec_ctrl_cmd(sc, &ack, &sg, sg.sg_nseg - 1, 1);
2358 
2359 	return (ack == VIRTIO_NET_OK ? 0 : EIO);
2360 }
2361 
2362 static int
2363 vtnet_set_promisc(struct vtnet_softc *sc, int on)
2364 {
2365 
2366 	return (vtnet_ctrl_rx_cmd(sc, VIRTIO_NET_CTRL_RX_PROMISC, on));
2367 }
2368 
2369 static int
2370 vtnet_set_allmulti(struct vtnet_softc *sc, int on)
2371 {
2372 
2373 	return (vtnet_ctrl_rx_cmd(sc, VIRTIO_NET_CTRL_RX_ALLMULTI, on));
2374 }
2375 
2376 static void
2377 vtnet_rx_filter_mac(struct vtnet_softc *sc)
2378 {
2379 	struct virtio_net_ctrl_hdr hdr;
2380 	struct vtnet_mac_filter *filter;
2381 	struct sglist_seg segs[4];
2382 	struct sglist sg;
2383 	struct ifnet *ifp;
2384 	struct ifaddr *ifa;
2385 	struct ifmultiaddr *ifma;
2386 	int ucnt, mcnt, promisc, allmulti, error;
2387 	uint8_t ack;
2388 
2389 	ifp = sc->vtnet_ifp;
2390 	ucnt = 0;
2391 	mcnt = 0;
2392 	promisc = 0;
2393 	allmulti = 0;
2394 	error = 0;
2395 
2396 	VTNET_LOCK_ASSERT(sc);
2397 	KASSERT(sc->vtnet_flags & VTNET_FLAG_CTRL_RX,
2398 	    ("CTRL_RX feature not negotiated"));
2399 
2400 	/*
2401 	 * Allocate the MAC filtering table. Note we could do this
2402 	 * at attach time, but it is probably not worth keeping it
2403 	 * around for an infrequent occurrence.
2404 	 */
2405 	filter = malloc(sizeof(struct vtnet_mac_filter), M_DEVBUF,
2406 	    M_NOWAIT | M_ZERO);
2407 	if (filter == NULL) {
2408 		device_printf(sc->vtnet_dev,
2409 		    "cannot allocate MAC address filtering table\n");
2410 		return;
2411 	}
2412 
2413 	/* Unicast MAC addresses: */
2414 	if_addr_rlock(ifp);
2415 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2416 		if (ifa->ifa_addr->sa_family != AF_LINK)
2417 			continue;
2418 		else if (ucnt == VTNET_MAX_MAC_ENTRIES)
2419 			break;
2420 
2421 		bcopy(LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
2422 		    &filter->vmf_unicast.macs[ucnt], ETHER_ADDR_LEN);
2423 		ucnt++;
2424 	}
2425 	if_addr_runlock(ifp);
2426 
2427 	if (ucnt >= VTNET_MAX_MAC_ENTRIES) {
2428 		promisc = 1;
2429 		filter->vmf_unicast.nentries = 0;
2430 
2431 		if_printf(ifp, "more than %d MAC addresses assigned, "
2432 		    "falling back to promiscuous mode\n",
2433 		    VTNET_MAX_MAC_ENTRIES);
2434 	} else
2435 		filter->vmf_unicast.nentries = ucnt;
2436 
2437 	/* Multicast MAC addresses: */
2438 	if_maddr_rlock(ifp);
2439 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2440 		if (ifma->ifma_addr->sa_family != AF_LINK)
2441 			continue;
2442 		else if (mcnt == VTNET_MAX_MAC_ENTRIES)
2443 			break;
2444 
2445 		bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
2446 		    &filter->vmf_multicast.macs[mcnt], ETHER_ADDR_LEN);
2447 		mcnt++;
2448 	}
2449 	if_maddr_runlock(ifp);
2450 
2451 	if (mcnt >= VTNET_MAX_MAC_ENTRIES) {
2452 		allmulti = 1;
2453 		filter->vmf_multicast.nentries = 0;
2454 
2455 		if_printf(ifp, "more than %d multicast MAC addresses "
2456 		    "assigned, falling back to all-multicast mode\n",
2457 		    VTNET_MAX_MAC_ENTRIES);
2458 	} else
2459 		filter->vmf_multicast.nentries = mcnt;
2460 
2461 	if (promisc && allmulti)
2462 		goto out;
2463 
2464 	hdr.class = VIRTIO_NET_CTRL_MAC;
2465 	hdr.cmd = VIRTIO_NET_CTRL_MAC_TABLE_SET;
2466 	ack = VIRTIO_NET_ERR;
2467 
2468 	sglist_init(&sg, 4, segs);
2469 	error |= sglist_append(&sg, &hdr, sizeof(struct virtio_net_ctrl_hdr));
2470 	error |= sglist_append(&sg, &filter->vmf_unicast,
2471 	    sizeof(struct vtnet_mac_table));
2472 	error |= sglist_append(&sg, &filter->vmf_multicast,
2473 	    sizeof(struct vtnet_mac_table));
2474 	error |= sglist_append(&sg, &ack, sizeof(uint8_t));
2475 	KASSERT(error == 0 && sg.sg_nseg == 4,
2476 	    ("error adding MAC filtering message to sglist"));
2477 
2478 	vtnet_exec_ctrl_cmd(sc, &ack, &sg, sg.sg_nseg - 1, 1);
2479 
2480 	if (ack != VIRTIO_NET_OK)
2481 		if_printf(ifp, "error setting host MAC filter table\n");
2482 
2483 out:
2484 	free(filter, M_DEVBUF);
2485 
2486 	if (promisc)
2487 		if (vtnet_set_promisc(sc, 1) != 0)
2488 			if_printf(ifp, "cannot enable promiscuous mode\n");
2489 	if (allmulti)
2490 		if (vtnet_set_allmulti(sc, 1) != 0)
2491 			if_printf(ifp, "cannot enable all-multicast mode\n");
2492 }
2493 
2494 static int
2495 vtnet_exec_vlan_filter(struct vtnet_softc *sc, int add, uint16_t tag)
2496 {
2497 	struct virtio_net_ctrl_hdr hdr;
2498 	struct sglist_seg segs[3];
2499 	struct sglist sg;
2500 	uint8_t ack;
2501 	int error;
2502 
2503 	hdr.class = VIRTIO_NET_CTRL_VLAN;
2504 	hdr.cmd = add ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL;
2505 	ack = VIRTIO_NET_ERR;
2506 	error = 0;
2507 
2508 	sglist_init(&sg, 3, segs);
2509 	error |= sglist_append(&sg, &hdr, sizeof(struct virtio_net_ctrl_hdr));
2510 	error |= sglist_append(&sg, &tag, sizeof(uint16_t));
2511 	error |= sglist_append(&sg, &ack, sizeof(uint8_t));
2512 	KASSERT(error == 0 && sg.sg_nseg == 3,
2513 	    ("error adding VLAN control message to sglist"));
2514 
2515 	vtnet_exec_ctrl_cmd(sc, &ack, &sg, sg.sg_nseg - 1, 1);
2516 
2517 	return (ack == VIRTIO_NET_OK ? 0 : EIO);
2518 }
2519 
2520 static void
2521 vtnet_rx_filter_vlan(struct vtnet_softc *sc)
2522 {
2523 	device_t dev;
2524 	uint32_t w, mask;
2525 	uint16_t tag;
2526 	int i, nvlans, error;
2527 
2528 	VTNET_LOCK_ASSERT(sc);
2529 	KASSERT(sc->vtnet_flags & VTNET_FLAG_VLAN_FILTER,
2530 	    ("VLAN_FILTER feature not negotiated"));
2531 
2532 	dev = sc->vtnet_dev;
2533 	nvlans = sc->vtnet_nvlans;
2534 	error = 0;
2535 
2536 	/* Enable filtering for each configured VLAN. */
2537 	for (i = 0; i < VTNET_VLAN_SHADOW_SIZE && nvlans > 0; i++) {
2538 		w = sc->vtnet_vlan_shadow[i];
2539 		for (mask = 1, tag = i * 32; w != 0; mask <<= 1, tag++) {
2540 			if ((w & mask) != 0) {
2541 				w &= ~mask;
2542 				nvlans--;
2543 				if (vtnet_exec_vlan_filter(sc, 1, tag) != 0)
2544 					error++;
2545 			}
2546 		}
2547 	}
2548 
2549 	KASSERT(nvlans == 0, ("VLAN count incorrect"));
2550 	if (error)
2551 		device_printf(dev, "cannot restore VLAN filter table\n");
2552 }
2553 
2554 static void
2555 vtnet_set_vlan_filter(struct vtnet_softc *sc, int add, uint16_t tag)
2556 {
2557 	struct ifnet *ifp;
2558 	int idx, bit;
2559 
2560 	KASSERT(sc->vtnet_flags & VTNET_FLAG_VLAN_FILTER,
2561 	    ("VLAN_FILTER feature not negotiated"));
2562 
2563 	if ((tag == 0) || (tag > 4095))
2564 		return;
2565 
2566 	ifp = sc->vtnet_ifp;
2567 	idx = (tag >> 5) & 0x7F;
2568 	bit = tag & 0x1F;
2569 
2570 	VTNET_LOCK(sc);
2571 
2572 	/* Update shadow VLAN table. */
2573 	if (add) {
2574 		sc->vtnet_nvlans++;
2575 		sc->vtnet_vlan_shadow[idx] |= (1 << bit);
2576 	} else {
2577 		sc->vtnet_nvlans--;
2578 		sc->vtnet_vlan_shadow[idx] &= ~(1 << bit);
2579 	}
2580 
2581 	if (ifp->if_capenable & IFCAP_VLAN_HWFILTER) {
2582 		if (vtnet_exec_vlan_filter(sc, add, tag) != 0) {
2583 			device_printf(sc->vtnet_dev,
2584 			    "cannot %s VLAN %d %s the host filter table\n",
2585 			    add ? "add" : "remove", tag,
2586 			    add ? "to" : "from");
2587 		}
2588 	}
2589 
2590 	VTNET_UNLOCK(sc);
2591 }
2592 
2593 static void
2594 vtnet_register_vlan(void *arg, struct ifnet *ifp, uint16_t tag)
2595 {
2596 
2597 	if (ifp->if_softc != arg)
2598 		return;
2599 
2600 	vtnet_set_vlan_filter(arg, 1, tag);
2601 }
2602 
2603 static void
2604 vtnet_unregister_vlan(void *arg, struct ifnet *ifp, uint16_t tag)
2605 {
2606 
2607 	if (ifp->if_softc != arg)
2608 		return;
2609 
2610 	vtnet_set_vlan_filter(arg, 0, tag);
2611 }
2612 
2613 static int
2614 vtnet_ifmedia_upd(struct ifnet *ifp)
2615 {
2616 	struct vtnet_softc *sc;
2617 	struct ifmedia *ifm;
2618 
2619 	sc = ifp->if_softc;
2620 	ifm = &sc->vtnet_media;
2621 
2622 	if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER)
2623 		return (EINVAL);
2624 
2625 	return (0);
2626 }
2627 
2628 static void
2629 vtnet_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2630 {
2631 	struct vtnet_softc *sc;
2632 
2633 	sc = ifp->if_softc;
2634 
2635 	ifmr->ifm_status = IFM_AVALID;
2636 	ifmr->ifm_active = IFM_ETHER;
2637 
2638 	VTNET_LOCK(sc);
2639 	if (vtnet_is_link_up(sc) != 0) {
2640 		ifmr->ifm_status |= IFM_ACTIVE;
2641 		ifmr->ifm_active |= VTNET_MEDIATYPE;
2642 	} else
2643 		ifmr->ifm_active |= IFM_NONE;
2644 	VTNET_UNLOCK(sc);
2645 }
2646 
2647 static void
2648 vtnet_add_statistics(struct vtnet_softc *sc)
2649 {
2650 	device_t dev;
2651 	struct vtnet_statistics *stats;
2652         struct sysctl_ctx_list *ctx;
2653 	struct sysctl_oid *tree;
2654 	struct sysctl_oid_list *child;
2655 
2656 	dev = sc->vtnet_dev;
2657 	stats = &sc->vtnet_stats;
2658 	ctx = device_get_sysctl_ctx(dev);
2659 	tree = device_get_sysctl_tree(dev);
2660 	child = SYSCTL_CHILDREN(tree);
2661 
2662 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "mbuf_alloc_failed",
2663 	    CTLFLAG_RD, &stats->mbuf_alloc_failed,
2664 	    "Mbuf cluster allocation failures");
2665 
2666 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "rx_frame_too_large",
2667 	    CTLFLAG_RD, &stats->rx_frame_too_large,
2668 	    "Received frame larger than the mbuf chain");
2669 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "rx_enq_replacement_failed",
2670 	    CTLFLAG_RD, &stats->rx_enq_replacement_failed,
2671 	    "Enqueuing the replacement receive mbuf failed");
2672 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "rx_mergeable_failed",
2673 	    CTLFLAG_RD, &stats->rx_mergeable_failed,
2674 	    "Mergeable buffers receive failures");
2675 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "rx_csum_bad_ethtype",
2676 	    CTLFLAG_RD, &stats->rx_csum_bad_ethtype,
2677 	    "Received checksum offloaded buffer with unsupported "
2678 	    "Ethernet type");
2679 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "rx_csum_bad_start",
2680 	    CTLFLAG_RD, &stats->rx_csum_bad_start,
2681 	    "Received checksum offloaded buffer with incorrect start offset");
2682 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "rx_csum_bad_ipproto",
2683 	    CTLFLAG_RD, &stats->rx_csum_bad_ipproto,
2684 	    "Received checksum offloaded buffer with incorrect IP protocol");
2685 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "rx_csum_bad_offset",
2686 	    CTLFLAG_RD, &stats->rx_csum_bad_offset,
2687 	    "Received checksum offloaded buffer with incorrect offset");
2688 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "rx_csum_failed",
2689 	    CTLFLAG_RD, &stats->rx_csum_failed,
2690 	    "Received buffer checksum offload failed");
2691 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "rx_csum_offloaded",
2692 	    CTLFLAG_RD, &stats->rx_csum_offloaded,
2693 	    "Received buffer checksum offload succeeded");
2694 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "rx_task_rescheduled",
2695 	    CTLFLAG_RD, &stats->rx_task_rescheduled,
2696 	    "Times the receive interrupt task rescheduled itself");
2697 
2698 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "tx_csum_offloaded",
2699 	    CTLFLAG_RD, &stats->tx_csum_offloaded,
2700 	    "Offloaded checksum of transmitted buffer");
2701 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "tx_tso_offloaded",
2702 	    CTLFLAG_RD, &stats->tx_tso_offloaded,
2703 	    "Segmentation offload of transmitted buffer");
2704 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "tx_csum_bad_ethtype",
2705 	    CTLFLAG_RD, &stats->tx_csum_bad_ethtype,
2706 	    "Aborted transmit of checksum offloaded buffer with unknown "
2707 	    "Ethernet type");
2708 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "tx_tso_bad_ethtype",
2709 	    CTLFLAG_RD, &stats->tx_tso_bad_ethtype,
2710 	    "Aborted transmit of TSO buffer with unknown Ethernet type");
2711 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "tx_task_rescheduled",
2712 	    CTLFLAG_RD, &stats->tx_task_rescheduled,
2713 	    "Times the transmit interrupt task rescheduled itself");
2714 }
2715 
2716 static int
2717 vtnet_enable_rx_intr(struct vtnet_softc *sc)
2718 {
2719 
2720 	return (virtqueue_enable_intr(sc->vtnet_rx_vq));
2721 }
2722 
2723 static void
2724 vtnet_disable_rx_intr(struct vtnet_softc *sc)
2725 {
2726 
2727 	virtqueue_disable_intr(sc->vtnet_rx_vq);
2728 }
2729 
2730 static int
2731 vtnet_enable_tx_intr(struct vtnet_softc *sc)
2732 {
2733 
2734 #ifdef VTNET_TX_INTR_MODERATION
2735 	return (0);
2736 #else
2737 	return (virtqueue_enable_intr(sc->vtnet_tx_vq));
2738 #endif
2739 }
2740 
2741 static void
2742 vtnet_disable_tx_intr(struct vtnet_softc *sc)
2743 {
2744 
2745 	virtqueue_disable_intr(sc->vtnet_tx_vq);
2746 }
2747