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