xref: /freebsd-12.1/sys/dev/virtio/network/if_vtnet.c (revision 5ad00fa2)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011, Bryan Venteicher <[email protected]>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice unmodified, this list of conditions, and the following
12  *    disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /* Driver for VirtIO network devices. */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/param.h>
35 #include <sys/eventhandler.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/sockio.h>
39 #include <sys/mbuf.h>
40 #include <sys/malloc.h>
41 #include <sys/module.h>
42 #include <sys/socket.h>
43 #include <sys/sysctl.h>
44 #include <sys/random.h>
45 #include <sys/sglist.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/taskqueue.h>
49 #include <sys/smp.h>
50 #include <machine/smp.h>
51 
52 #include <vm/uma.h>
53 
54 #include <net/ethernet.h>
55 #include <net/if.h>
56 #include <net/if_var.h>
57 #include <net/if_arp.h>
58 #include <net/if_dl.h>
59 #include <net/if_types.h>
60 #include <net/if_media.h>
61 #include <net/if_vlan_var.h>
62 
63 #include <net/bpf.h>
64 
65 #include <netinet/in_systm.h>
66 #include <netinet/in.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip6.h>
69 #include <netinet6/ip6_var.h>
70 #include <netinet/udp.h>
71 #include <netinet/tcp.h>
72 #include <netinet/sctp.h>
73 
74 #include <machine/bus.h>
75 #include <machine/resource.h>
76 #include <sys/bus.h>
77 #include <sys/rman.h>
78 
79 #include <dev/virtio/virtio.h>
80 #include <dev/virtio/virtqueue.h>
81 #include <dev/virtio/network/virtio_net.h>
82 #include <dev/virtio/network/if_vtnetvar.h>
83 
84 #include "virtio_if.h"
85 
86 #include "opt_inet.h"
87 #include "opt_inet6.h"
88 
89 static int	vtnet_modevent(module_t, int, void *);
90 
91 static int	vtnet_probe(device_t);
92 static int	vtnet_attach(device_t);
93 static int	vtnet_detach(device_t);
94 static int	vtnet_suspend(device_t);
95 static int	vtnet_resume(device_t);
96 static int	vtnet_shutdown(device_t);
97 static int	vtnet_attach_completed(device_t);
98 static int	vtnet_config_change(device_t);
99 
100 static void	vtnet_negotiate_features(struct vtnet_softc *);
101 static void	vtnet_setup_features(struct vtnet_softc *);
102 static int	vtnet_init_rxq(struct vtnet_softc *, int);
103 static int	vtnet_init_txq(struct vtnet_softc *, int);
104 static int	vtnet_alloc_rxtx_queues(struct vtnet_softc *);
105 static void	vtnet_free_rxtx_queues(struct vtnet_softc *);
106 static int	vtnet_alloc_rx_filters(struct vtnet_softc *);
107 static void	vtnet_free_rx_filters(struct vtnet_softc *);
108 static int	vtnet_alloc_virtqueues(struct vtnet_softc *);
109 static int	vtnet_setup_interface(struct vtnet_softc *);
110 static int	vtnet_change_mtu(struct vtnet_softc *, int);
111 static int	vtnet_ioctl(struct ifnet *, u_long, caddr_t);
112 static uint64_t	vtnet_get_counter(struct ifnet *, ift_counter);
113 
114 static int	vtnet_rxq_populate(struct vtnet_rxq *);
115 static void	vtnet_rxq_free_mbufs(struct vtnet_rxq *);
116 static struct mbuf *
117 		vtnet_rx_alloc_buf(struct vtnet_softc *, int , struct mbuf **);
118 static int	vtnet_rxq_replace_lro_nomgr_buf(struct vtnet_rxq *,
119 		    struct mbuf *, int);
120 static int	vtnet_rxq_replace_buf(struct vtnet_rxq *, struct mbuf *, int);
121 static int	vtnet_rxq_enqueue_buf(struct vtnet_rxq *, struct mbuf *);
122 static int	vtnet_rxq_new_buf(struct vtnet_rxq *);
123 static int	vtnet_rxq_csum(struct vtnet_rxq *, struct mbuf *,
124 		     struct virtio_net_hdr *);
125 static void	vtnet_rxq_discard_merged_bufs(struct vtnet_rxq *, int);
126 static void	vtnet_rxq_discard_buf(struct vtnet_rxq *, struct mbuf *);
127 static int	vtnet_rxq_merged_eof(struct vtnet_rxq *, struct mbuf *, int);
128 static void	vtnet_rxq_input(struct vtnet_rxq *, struct mbuf *,
129 		    struct virtio_net_hdr *);
130 static int	vtnet_rxq_eof(struct vtnet_rxq *);
131 static void	vtnet_rx_vq_intr(void *);
132 static void	vtnet_rxq_tq_intr(void *, int);
133 
134 static int	vtnet_txq_below_threshold(struct vtnet_txq *);
135 static int	vtnet_txq_notify(struct vtnet_txq *);
136 static void	vtnet_txq_free_mbufs(struct vtnet_txq *);
137 static int	vtnet_txq_offload_ctx(struct vtnet_txq *, struct mbuf *,
138 		    int *, int *, int *);
139 static int	vtnet_txq_offload_tso(struct vtnet_txq *, struct mbuf *, int,
140 		    int, struct virtio_net_hdr *);
141 static struct mbuf *
142 		vtnet_txq_offload(struct vtnet_txq *, struct mbuf *,
143 		    struct virtio_net_hdr *);
144 static int	vtnet_txq_enqueue_buf(struct vtnet_txq *, struct mbuf **,
145 		    struct vtnet_tx_header *);
146 static int	vtnet_txq_encap(struct vtnet_txq *, struct mbuf **);
147 #ifdef VTNET_LEGACY_TX
148 static void	vtnet_start_locked(struct vtnet_txq *, struct ifnet *);
149 static void	vtnet_start(struct ifnet *);
150 #else
151 static int	vtnet_txq_mq_start_locked(struct vtnet_txq *, struct mbuf *);
152 static int	vtnet_txq_mq_start(struct ifnet *, struct mbuf *);
153 static void	vtnet_txq_tq_deferred(void *, int);
154 #endif
155 static void	vtnet_txq_start(struct vtnet_txq *);
156 static void	vtnet_txq_tq_intr(void *, int);
157 static int	vtnet_txq_eof(struct vtnet_txq *);
158 static void	vtnet_tx_vq_intr(void *);
159 static void	vtnet_tx_start_all(struct vtnet_softc *);
160 
161 #ifndef VTNET_LEGACY_TX
162 static void	vtnet_qflush(struct ifnet *);
163 #endif
164 
165 static int	vtnet_watchdog(struct vtnet_txq *);
166 static void	vtnet_accum_stats(struct vtnet_softc *,
167 		    struct vtnet_rxq_stats *, struct vtnet_txq_stats *);
168 static void	vtnet_tick(void *);
169 
170 static void	vtnet_start_taskqueues(struct vtnet_softc *);
171 static void	vtnet_free_taskqueues(struct vtnet_softc *);
172 static void	vtnet_drain_taskqueues(struct vtnet_softc *);
173 
174 static void	vtnet_drain_rxtx_queues(struct vtnet_softc *);
175 static void	vtnet_stop_rendezvous(struct vtnet_softc *);
176 static void	vtnet_stop(struct vtnet_softc *);
177 static int	vtnet_virtio_reinit(struct vtnet_softc *);
178 static void	vtnet_init_rx_filters(struct vtnet_softc *);
179 static int	vtnet_init_rx_queues(struct vtnet_softc *);
180 static int	vtnet_init_tx_queues(struct vtnet_softc *);
181 static int	vtnet_init_rxtx_queues(struct vtnet_softc *);
182 static void	vtnet_set_active_vq_pairs(struct vtnet_softc *);
183 static int	vtnet_reinit(struct vtnet_softc *);
184 static void	vtnet_init_locked(struct vtnet_softc *);
185 static void	vtnet_init(void *);
186 
187 static void	vtnet_free_ctrl_vq(struct vtnet_softc *);
188 static void	vtnet_exec_ctrl_cmd(struct vtnet_softc *, void *,
189 		    struct sglist *, int, int);
190 static int	vtnet_ctrl_mac_cmd(struct vtnet_softc *, uint8_t *);
191 static int	vtnet_ctrl_mq_cmd(struct vtnet_softc *, uint16_t);
192 static int	vtnet_ctrl_rx_cmd(struct vtnet_softc *, int, int);
193 static int	vtnet_set_promisc(struct vtnet_softc *, int);
194 static int	vtnet_set_allmulti(struct vtnet_softc *, int);
195 static void	vtnet_attach_disable_promisc(struct vtnet_softc *);
196 static void	vtnet_rx_filter(struct vtnet_softc *);
197 static void	vtnet_rx_filter_mac(struct vtnet_softc *);
198 static int	vtnet_exec_vlan_filter(struct vtnet_softc *, int, uint16_t);
199 static void	vtnet_rx_filter_vlan(struct vtnet_softc *);
200 static void	vtnet_update_vlan_filter(struct vtnet_softc *, int, uint16_t);
201 static void	vtnet_register_vlan(void *, struct ifnet *, uint16_t);
202 static void	vtnet_unregister_vlan(void *, struct ifnet *, uint16_t);
203 
204 static int	vtnet_is_link_up(struct vtnet_softc *);
205 static void	vtnet_update_link_status(struct vtnet_softc *);
206 static int	vtnet_ifmedia_upd(struct ifnet *);
207 static void	vtnet_ifmedia_sts(struct ifnet *, struct ifmediareq *);
208 static void	vtnet_get_hwaddr(struct vtnet_softc *);
209 static void	vtnet_set_hwaddr(struct vtnet_softc *);
210 static void	vtnet_vlan_tag_remove(struct mbuf *);
211 static void	vtnet_set_rx_process_limit(struct vtnet_softc *);
212 static void	vtnet_set_tx_intr_threshold(struct vtnet_softc *);
213 
214 static void	vtnet_setup_rxq_sysctl(struct sysctl_ctx_list *,
215 		    struct sysctl_oid_list *, struct vtnet_rxq *);
216 static void	vtnet_setup_txq_sysctl(struct sysctl_ctx_list *,
217 		    struct sysctl_oid_list *, struct vtnet_txq *);
218 static void	vtnet_setup_queue_sysctl(struct vtnet_softc *);
219 static void	vtnet_setup_sysctl(struct vtnet_softc *);
220 
221 static int	vtnet_rxq_enable_intr(struct vtnet_rxq *);
222 static void	vtnet_rxq_disable_intr(struct vtnet_rxq *);
223 static int	vtnet_txq_enable_intr(struct vtnet_txq *);
224 static void	vtnet_txq_disable_intr(struct vtnet_txq *);
225 static void	vtnet_enable_rx_interrupts(struct vtnet_softc *);
226 static void	vtnet_enable_tx_interrupts(struct vtnet_softc *);
227 static void	vtnet_enable_interrupts(struct vtnet_softc *);
228 static void	vtnet_disable_rx_interrupts(struct vtnet_softc *);
229 static void	vtnet_disable_tx_interrupts(struct vtnet_softc *);
230 static void	vtnet_disable_interrupts(struct vtnet_softc *);
231 
232 static int	vtnet_tunable_int(struct vtnet_softc *, const char *, int);
233 
234 /* Tunables. */
235 static SYSCTL_NODE(_hw, OID_AUTO, vtnet, CTLFLAG_RD, 0, "VNET driver parameters");
236 static int vtnet_csum_disable = 0;
237 TUNABLE_INT("hw.vtnet.csum_disable", &vtnet_csum_disable);
238 SYSCTL_INT(_hw_vtnet, OID_AUTO, csum_disable, CTLFLAG_RDTUN,
239     &vtnet_csum_disable, 0, "Disables receive and send checksum offload");
240 static int vtnet_tso_disable = 0;
241 TUNABLE_INT("hw.vtnet.tso_disable", &vtnet_tso_disable);
242 SYSCTL_INT(_hw_vtnet, OID_AUTO, tso_disable, CTLFLAG_RDTUN, &vtnet_tso_disable,
243     0, "Disables TCP Segmentation Offload");
244 static int vtnet_lro_disable = 0;
245 TUNABLE_INT("hw.vtnet.lro_disable", &vtnet_lro_disable);
246 SYSCTL_INT(_hw_vtnet, OID_AUTO, lro_disable, CTLFLAG_RDTUN, &vtnet_lro_disable,
247     0, "Disables TCP Large Receive Offload");
248 static int vtnet_mq_disable = 0;
249 TUNABLE_INT("hw.vtnet.mq_disable", &vtnet_mq_disable);
250 SYSCTL_INT(_hw_vtnet, OID_AUTO, mq_disable, CTLFLAG_RDTUN, &vtnet_mq_disable,
251     0, "Disables Multi Queue support");
252 static int vtnet_mq_max_pairs = VTNET_MAX_QUEUE_PAIRS;
253 TUNABLE_INT("hw.vtnet.mq_max_pairs", &vtnet_mq_max_pairs);
254 SYSCTL_INT(_hw_vtnet, OID_AUTO, mq_max_pairs, CTLFLAG_RDTUN,
255     &vtnet_mq_max_pairs, 0, "Sets the maximum number of Multi Queue pairs");
256 static int vtnet_rx_process_limit = 512;
257 TUNABLE_INT("hw.vtnet.rx_process_limit", &vtnet_rx_process_limit);
258 SYSCTL_INT(_hw_vtnet, OID_AUTO, rx_process_limit, CTLFLAG_RDTUN,
259     &vtnet_rx_process_limit, 0,
260     "Limits the number RX segments processed in a single pass");
261 
262 static uma_zone_t vtnet_tx_header_zone;
263 
264 static struct virtio_feature_desc vtnet_feature_desc[] = {
265 	{ VIRTIO_NET_F_CSUM,		"TxChecksum"	},
266 	{ VIRTIO_NET_F_GUEST_CSUM,	"RxChecksum"	},
267 	{ VIRTIO_NET_F_MAC,		"MacAddress"	},
268 	{ VIRTIO_NET_F_GSO,		"TxAllGSO"	},
269 	{ VIRTIO_NET_F_GUEST_TSO4,	"RxTSOv4"	},
270 	{ VIRTIO_NET_F_GUEST_TSO6,	"RxTSOv6"	},
271 	{ VIRTIO_NET_F_GUEST_ECN,	"RxECN"		},
272 	{ VIRTIO_NET_F_GUEST_UFO,	"RxUFO"		},
273 	{ VIRTIO_NET_F_HOST_TSO4,	"TxTSOv4"	},
274 	{ VIRTIO_NET_F_HOST_TSO6,	"TxTSOv6"	},
275 	{ VIRTIO_NET_F_HOST_ECN,	"TxTSOECN"	},
276 	{ VIRTIO_NET_F_HOST_UFO,	"TxUFO"		},
277 	{ VIRTIO_NET_F_MRG_RXBUF,	"MrgRxBuf"	},
278 	{ VIRTIO_NET_F_STATUS,		"Status"	},
279 	{ VIRTIO_NET_F_CTRL_VQ,		"ControlVq"	},
280 	{ VIRTIO_NET_F_CTRL_RX,		"RxMode"	},
281 	{ VIRTIO_NET_F_CTRL_VLAN,	"VLanFilter"	},
282 	{ VIRTIO_NET_F_CTRL_RX_EXTRA,	"RxModeExtra"	},
283 	{ VIRTIO_NET_F_GUEST_ANNOUNCE,	"GuestAnnounce"	},
284 	{ VIRTIO_NET_F_MQ,		"Multiqueue"	},
285 	{ VIRTIO_NET_F_CTRL_MAC_ADDR,	"SetMacAddress"	},
286 
287 	{ 0, NULL }
288 };
289 
290 static device_method_t vtnet_methods[] = {
291 	/* Device methods. */
292 	DEVMETHOD(device_probe,			vtnet_probe),
293 	DEVMETHOD(device_attach,		vtnet_attach),
294 	DEVMETHOD(device_detach,		vtnet_detach),
295 	DEVMETHOD(device_suspend,		vtnet_suspend),
296 	DEVMETHOD(device_resume,		vtnet_resume),
297 	DEVMETHOD(device_shutdown,		vtnet_shutdown),
298 
299 	/* VirtIO methods. */
300 	DEVMETHOD(virtio_attach_completed,	vtnet_attach_completed),
301 	DEVMETHOD(virtio_config_change,		vtnet_config_change),
302 
303 	DEVMETHOD_END
304 };
305 
306 #ifdef DEV_NETMAP
307 #include <dev/netmap/if_vtnet_netmap.h>
308 #endif /* DEV_NETMAP */
309 
310 static driver_t vtnet_driver = {
311 	"vtnet",
312 	vtnet_methods,
313 	sizeof(struct vtnet_softc)
314 };
315 static devclass_t vtnet_devclass;
316 
317 DRIVER_MODULE(vtnet, virtio_mmio, vtnet_driver, vtnet_devclass,
318     vtnet_modevent, 0);
319 DRIVER_MODULE(vtnet, virtio_pci, vtnet_driver, vtnet_devclass,
320     vtnet_modevent, 0);
321 MODULE_VERSION(vtnet, 1);
322 MODULE_DEPEND(vtnet, virtio, 1, 1, 1);
323 #ifdef DEV_NETMAP
324 MODULE_DEPEND(vtnet, netmap, 1, 1, 1);
325 #endif /* DEV_NETMAP */
326 
327 static int
328 vtnet_modevent(module_t mod, int type, void *unused)
329 {
330 	int error = 0;
331 	static int loaded = 0;
332 
333 	switch (type) {
334 	case MOD_LOAD:
335 		if (loaded++ == 0)
336 			vtnet_tx_header_zone = uma_zcreate("vtnet_tx_hdr",
337 				sizeof(struct vtnet_tx_header),
338 				NULL, NULL, NULL, NULL, 0, 0);
339 		break;
340 	case MOD_QUIESCE:
341 		if (uma_zone_get_cur(vtnet_tx_header_zone) > 0)
342 			error = EBUSY;
343 		break;
344 	case MOD_UNLOAD:
345 		if (--loaded == 0) {
346 			uma_zdestroy(vtnet_tx_header_zone);
347 			vtnet_tx_header_zone = NULL;
348 		}
349 		break;
350 	case MOD_SHUTDOWN:
351 		break;
352 	default:
353 		error = EOPNOTSUPP;
354 		break;
355 	}
356 
357 	return (error);
358 }
359 
360 static int
361 vtnet_probe(device_t dev)
362 {
363 
364 	if (virtio_get_device_type(dev) != VIRTIO_ID_NETWORK)
365 		return (ENXIO);
366 
367 	device_set_desc(dev, "VirtIO Networking Adapter");
368 
369 	return (BUS_PROBE_DEFAULT);
370 }
371 
372 static int
373 vtnet_attach(device_t dev)
374 {
375 	struct vtnet_softc *sc;
376 	int error;
377 
378 	sc = device_get_softc(dev);
379 	sc->vtnet_dev = dev;
380 
381 	/* Register our feature descriptions. */
382 	virtio_set_feature_desc(dev, vtnet_feature_desc);
383 
384 	VTNET_CORE_LOCK_INIT(sc);
385 	callout_init_mtx(&sc->vtnet_tick_ch, VTNET_CORE_MTX(sc), 0);
386 
387 	vtnet_setup_sysctl(sc);
388 	vtnet_setup_features(sc);
389 
390 	error = vtnet_alloc_rx_filters(sc);
391 	if (error) {
392 		device_printf(dev, "cannot allocate Rx filters\n");
393 		goto fail;
394 	}
395 
396 	error = vtnet_alloc_rxtx_queues(sc);
397 	if (error) {
398 		device_printf(dev, "cannot allocate queues\n");
399 		goto fail;
400 	}
401 
402 	error = vtnet_alloc_virtqueues(sc);
403 	if (error) {
404 		device_printf(dev, "cannot allocate virtqueues\n");
405 		goto fail;
406 	}
407 
408 	error = vtnet_setup_interface(sc);
409 	if (error) {
410 		device_printf(dev, "cannot setup interface\n");
411 		goto fail;
412 	}
413 
414 	error = virtio_setup_intr(dev, INTR_TYPE_NET);
415 	if (error) {
416 		device_printf(dev, "cannot setup virtqueue interrupts\n");
417 		/* BMV: This will crash if during boot! */
418 		ether_ifdetach(sc->vtnet_ifp);
419 		goto fail;
420 	}
421 
422 #ifdef DEV_NETMAP
423 	vtnet_netmap_attach(sc);
424 #endif /* DEV_NETMAP */
425 
426 	vtnet_start_taskqueues(sc);
427 
428 fail:
429 	if (error)
430 		vtnet_detach(dev);
431 
432 	return (error);
433 }
434 
435 static int
436 vtnet_detach(device_t dev)
437 {
438 	struct vtnet_softc *sc;
439 	struct ifnet *ifp;
440 
441 	sc = device_get_softc(dev);
442 	ifp = sc->vtnet_ifp;
443 
444 	if (device_is_attached(dev)) {
445 		VTNET_CORE_LOCK(sc);
446 		vtnet_stop(sc);
447 		VTNET_CORE_UNLOCK(sc);
448 
449 		callout_drain(&sc->vtnet_tick_ch);
450 		vtnet_drain_taskqueues(sc);
451 
452 		ether_ifdetach(ifp);
453 	}
454 
455 #ifdef DEV_NETMAP
456 	netmap_detach(ifp);
457 #endif /* DEV_NETMAP */
458 
459 	vtnet_free_taskqueues(sc);
460 
461 	if (sc->vtnet_vlan_attach != NULL) {
462 		EVENTHANDLER_DEREGISTER(vlan_config, sc->vtnet_vlan_attach);
463 		sc->vtnet_vlan_attach = NULL;
464 	}
465 	if (sc->vtnet_vlan_detach != NULL) {
466 		EVENTHANDLER_DEREGISTER(vlan_unconfig, sc->vtnet_vlan_detach);
467 		sc->vtnet_vlan_detach = NULL;
468 	}
469 
470 	ifmedia_removeall(&sc->vtnet_media);
471 
472 	if (ifp != NULL) {
473 		if_free(ifp);
474 		sc->vtnet_ifp = NULL;
475 	}
476 
477 	vtnet_free_rxtx_queues(sc);
478 	vtnet_free_rx_filters(sc);
479 
480 	if (sc->vtnet_ctrl_vq != NULL)
481 		vtnet_free_ctrl_vq(sc);
482 
483 	VTNET_CORE_LOCK_DESTROY(sc);
484 
485 	return (0);
486 }
487 
488 static int
489 vtnet_suspend(device_t dev)
490 {
491 	struct vtnet_softc *sc;
492 
493 	sc = device_get_softc(dev);
494 
495 	VTNET_CORE_LOCK(sc);
496 	vtnet_stop(sc);
497 	sc->vtnet_flags |= VTNET_FLAG_SUSPENDED;
498 	VTNET_CORE_UNLOCK(sc);
499 
500 	return (0);
501 }
502 
503 static int
504 vtnet_resume(device_t dev)
505 {
506 	struct vtnet_softc *sc;
507 	struct ifnet *ifp;
508 
509 	sc = device_get_softc(dev);
510 	ifp = sc->vtnet_ifp;
511 
512 	VTNET_CORE_LOCK(sc);
513 	if (ifp->if_flags & IFF_UP)
514 		vtnet_init_locked(sc);
515 	sc->vtnet_flags &= ~VTNET_FLAG_SUSPENDED;
516 	VTNET_CORE_UNLOCK(sc);
517 
518 	return (0);
519 }
520 
521 static int
522 vtnet_shutdown(device_t dev)
523 {
524 
525 	/*
526 	 * Suspend already does all of what we need to
527 	 * do here; we just never expect to be resumed.
528 	 */
529 	return (vtnet_suspend(dev));
530 }
531 
532 static int
533 vtnet_attach_completed(device_t dev)
534 {
535 
536 	vtnet_attach_disable_promisc(device_get_softc(dev));
537 
538 	return (0);
539 }
540 
541 static int
542 vtnet_config_change(device_t dev)
543 {
544 	struct vtnet_softc *sc;
545 
546 	sc = device_get_softc(dev);
547 
548 	VTNET_CORE_LOCK(sc);
549 	vtnet_update_link_status(sc);
550 	if (sc->vtnet_link_active != 0)
551 		vtnet_tx_start_all(sc);
552 	VTNET_CORE_UNLOCK(sc);
553 
554 	return (0);
555 }
556 
557 static void
558 vtnet_negotiate_features(struct vtnet_softc *sc)
559 {
560 	device_t dev;
561 	uint64_t mask, features;
562 
563 	dev = sc->vtnet_dev;
564 	mask = 0;
565 
566 	/*
567 	 * TSO and LRO are only available when their corresponding checksum
568 	 * offload feature is also negotiated.
569 	 */
570 	if (vtnet_tunable_int(sc, "csum_disable", vtnet_csum_disable)) {
571 		mask |= VIRTIO_NET_F_CSUM | VIRTIO_NET_F_GUEST_CSUM;
572 		mask |= VTNET_TSO_FEATURES | VTNET_LRO_FEATURES;
573 	}
574 	if (vtnet_tunable_int(sc, "tso_disable", vtnet_tso_disable))
575 		mask |= VTNET_TSO_FEATURES;
576 	if (vtnet_tunable_int(sc, "lro_disable", vtnet_lro_disable))
577 		mask |= VTNET_LRO_FEATURES;
578 #ifndef VTNET_LEGACY_TX
579 	if (vtnet_tunable_int(sc, "mq_disable", vtnet_mq_disable))
580 		mask |= VIRTIO_NET_F_MQ;
581 #else
582 	mask |= VIRTIO_NET_F_MQ;
583 #endif
584 
585 	features = VTNET_FEATURES & ~mask;
586 	sc->vtnet_features = virtio_negotiate_features(dev, features);
587 
588 	if (virtio_with_feature(dev, VTNET_LRO_FEATURES) &&
589 	    virtio_with_feature(dev, VIRTIO_NET_F_MRG_RXBUF) == 0) {
590 		/*
591 		 * LRO without mergeable buffers requires special care. This
592 		 * is not ideal because every receive buffer must be large
593 		 * enough to hold the maximum TCP packet, the Ethernet header,
594 		 * and the header. This requires up to 34 descriptors with
595 		 * MCLBYTES clusters. If we do not have indirect descriptors,
596 		 * LRO is disabled since the virtqueue will not contain very
597 		 * many receive buffers.
598 		 */
599 		if (!virtio_with_feature(dev, VIRTIO_RING_F_INDIRECT_DESC)) {
600 			device_printf(dev,
601 			    "LRO disabled due to both mergeable buffers and "
602 			    "indirect descriptors not negotiated\n");
603 
604 			features &= ~VTNET_LRO_FEATURES;
605 			sc->vtnet_features =
606 			    virtio_negotiate_features(dev, features);
607 		} else
608 			sc->vtnet_flags |= VTNET_FLAG_LRO_NOMRG;
609 	}
610 }
611 
612 static void
613 vtnet_setup_features(struct vtnet_softc *sc)
614 {
615 	device_t dev;
616 
617 	dev = sc->vtnet_dev;
618 
619 	vtnet_negotiate_features(sc);
620 
621 	if (virtio_with_feature(dev, VIRTIO_RING_F_INDIRECT_DESC))
622 		sc->vtnet_flags |= VTNET_FLAG_INDIRECT;
623 	if (virtio_with_feature(dev, VIRTIO_RING_F_EVENT_IDX))
624 		sc->vtnet_flags |= VTNET_FLAG_EVENT_IDX;
625 
626 	if (virtio_with_feature(dev, VIRTIO_NET_F_MAC)) {
627 		/* This feature should always be negotiated. */
628 		sc->vtnet_flags |= VTNET_FLAG_MAC;
629 	}
630 
631 	if (virtio_with_feature(dev, VIRTIO_NET_F_MRG_RXBUF)) {
632 		sc->vtnet_flags |= VTNET_FLAG_MRG_RXBUFS;
633 		sc->vtnet_hdr_size = sizeof(struct virtio_net_hdr_mrg_rxbuf);
634 	} else
635 		sc->vtnet_hdr_size = sizeof(struct virtio_net_hdr);
636 
637 	if (sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS)
638 		sc->vtnet_rx_nsegs = VTNET_MRG_RX_SEGS;
639 	else if (sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG)
640 		sc->vtnet_rx_nsegs = VTNET_MAX_RX_SEGS;
641 	else
642 		sc->vtnet_rx_nsegs = VTNET_MIN_RX_SEGS;
643 
644 	if (virtio_with_feature(dev, VIRTIO_NET_F_GSO) ||
645 	    virtio_with_feature(dev, VIRTIO_NET_F_HOST_TSO4) ||
646 	    virtio_with_feature(dev, VIRTIO_NET_F_HOST_TSO6))
647 		sc->vtnet_tx_nsegs = VTNET_MAX_TX_SEGS;
648 	else
649 		sc->vtnet_tx_nsegs = VTNET_MIN_TX_SEGS;
650 
651 	if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_VQ)) {
652 		sc->vtnet_flags |= VTNET_FLAG_CTRL_VQ;
653 
654 		if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_RX))
655 			sc->vtnet_flags |= VTNET_FLAG_CTRL_RX;
656 		if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_VLAN))
657 			sc->vtnet_flags |= VTNET_FLAG_VLAN_FILTER;
658 		if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_MAC_ADDR))
659 			sc->vtnet_flags |= VTNET_FLAG_CTRL_MAC;
660 	}
661 
662 	if (virtio_with_feature(dev, VIRTIO_NET_F_MQ) &&
663 	    sc->vtnet_flags & VTNET_FLAG_CTRL_VQ) {
664 		sc->vtnet_max_vq_pairs = virtio_read_dev_config_2(dev,
665 		    offsetof(struct virtio_net_config, max_virtqueue_pairs));
666 	} else
667 		sc->vtnet_max_vq_pairs = 1;
668 
669 	if (sc->vtnet_max_vq_pairs > 1) {
670 		/*
671 		 * Limit the maximum number of queue pairs to the lower of
672 		 * the number of CPUs and the configured maximum.
673 		 * The actual number of queues that get used may be less.
674 		 */
675 		int max;
676 
677 		max = vtnet_tunable_int(sc, "mq_max_pairs", vtnet_mq_max_pairs);
678 		if (max > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN) {
679 			if (max > mp_ncpus)
680 				max = mp_ncpus;
681 			if (max > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX)
682 				max = VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX;
683 			if (max > 1) {
684 				sc->vtnet_requested_vq_pairs = max;
685 				sc->vtnet_flags |= VTNET_FLAG_MULTIQ;
686 			}
687 		}
688 	}
689 }
690 
691 static int
692 vtnet_init_rxq(struct vtnet_softc *sc, int id)
693 {
694 	struct vtnet_rxq *rxq;
695 
696 	rxq = &sc->vtnet_rxqs[id];
697 
698 	snprintf(rxq->vtnrx_name, sizeof(rxq->vtnrx_name), "%s-rx%d",
699 	    device_get_nameunit(sc->vtnet_dev), id);
700 	mtx_init(&rxq->vtnrx_mtx, rxq->vtnrx_name, NULL, MTX_DEF);
701 
702 	rxq->vtnrx_sc = sc;
703 	rxq->vtnrx_id = id;
704 
705 	rxq->vtnrx_sg = sglist_alloc(sc->vtnet_rx_nsegs, M_NOWAIT);
706 	if (rxq->vtnrx_sg == NULL)
707 		return (ENOMEM);
708 
709 	TASK_INIT(&rxq->vtnrx_intrtask, 0, vtnet_rxq_tq_intr, rxq);
710 	rxq->vtnrx_tq = taskqueue_create(rxq->vtnrx_name, M_NOWAIT,
711 	    taskqueue_thread_enqueue, &rxq->vtnrx_tq);
712 
713 	return (rxq->vtnrx_tq == NULL ? ENOMEM : 0);
714 }
715 
716 static int
717 vtnet_init_txq(struct vtnet_softc *sc, int id)
718 {
719 	struct vtnet_txq *txq;
720 
721 	txq = &sc->vtnet_txqs[id];
722 
723 	snprintf(txq->vtntx_name, sizeof(txq->vtntx_name), "%s-tx%d",
724 	    device_get_nameunit(sc->vtnet_dev), id);
725 	mtx_init(&txq->vtntx_mtx, txq->vtntx_name, NULL, MTX_DEF);
726 
727 	txq->vtntx_sc = sc;
728 	txq->vtntx_id = id;
729 
730 	txq->vtntx_sg = sglist_alloc(sc->vtnet_tx_nsegs, M_NOWAIT);
731 	if (txq->vtntx_sg == NULL)
732 		return (ENOMEM);
733 
734 #ifndef VTNET_LEGACY_TX
735 	txq->vtntx_br = buf_ring_alloc(VTNET_DEFAULT_BUFRING_SIZE, M_DEVBUF,
736 	    M_NOWAIT, &txq->vtntx_mtx);
737 	if (txq->vtntx_br == NULL)
738 		return (ENOMEM);
739 
740 	TASK_INIT(&txq->vtntx_defrtask, 0, vtnet_txq_tq_deferred, txq);
741 #endif
742 	TASK_INIT(&txq->vtntx_intrtask, 0, vtnet_txq_tq_intr, txq);
743 	txq->vtntx_tq = taskqueue_create(txq->vtntx_name, M_NOWAIT,
744 	    taskqueue_thread_enqueue, &txq->vtntx_tq);
745 	if (txq->vtntx_tq == NULL)
746 		return (ENOMEM);
747 
748 	return (0);
749 }
750 
751 static int
752 vtnet_alloc_rxtx_queues(struct vtnet_softc *sc)
753 {
754 	int i, npairs, error;
755 
756 	npairs = sc->vtnet_max_vq_pairs;
757 
758 	sc->vtnet_rxqs = mallocarray(npairs, sizeof(struct vtnet_rxq), M_DEVBUF,
759 	    M_NOWAIT | M_ZERO);
760 	sc->vtnet_txqs = mallocarray(npairs, sizeof(struct vtnet_txq), M_DEVBUF,
761 	    M_NOWAIT | M_ZERO);
762 	if (sc->vtnet_rxqs == NULL || sc->vtnet_txqs == NULL)
763 		return (ENOMEM);
764 
765 	for (i = 0; i < npairs; i++) {
766 		error = vtnet_init_rxq(sc, i);
767 		if (error)
768 			return (error);
769 		error = vtnet_init_txq(sc, i);
770 		if (error)
771 			return (error);
772 	}
773 
774 	vtnet_setup_queue_sysctl(sc);
775 
776 	return (0);
777 }
778 
779 static void
780 vtnet_destroy_rxq(struct vtnet_rxq *rxq)
781 {
782 
783 	rxq->vtnrx_sc = NULL;
784 	rxq->vtnrx_id = -1;
785 
786 	if (rxq->vtnrx_sg != NULL) {
787 		sglist_free(rxq->vtnrx_sg);
788 		rxq->vtnrx_sg = NULL;
789 	}
790 
791 	if (mtx_initialized(&rxq->vtnrx_mtx) != 0)
792 		mtx_destroy(&rxq->vtnrx_mtx);
793 }
794 
795 static void
796 vtnet_destroy_txq(struct vtnet_txq *txq)
797 {
798 
799 	txq->vtntx_sc = NULL;
800 	txq->vtntx_id = -1;
801 
802 	if (txq->vtntx_sg != NULL) {
803 		sglist_free(txq->vtntx_sg);
804 		txq->vtntx_sg = NULL;
805 	}
806 
807 #ifndef VTNET_LEGACY_TX
808 	if (txq->vtntx_br != NULL) {
809 		buf_ring_free(txq->vtntx_br, M_DEVBUF);
810 		txq->vtntx_br = NULL;
811 	}
812 #endif
813 
814 	if (mtx_initialized(&txq->vtntx_mtx) != 0)
815 		mtx_destroy(&txq->vtntx_mtx);
816 }
817 
818 static void
819 vtnet_free_rxtx_queues(struct vtnet_softc *sc)
820 {
821 	int i;
822 
823 	if (sc->vtnet_rxqs != NULL) {
824 		for (i = 0; i < sc->vtnet_max_vq_pairs; i++)
825 			vtnet_destroy_rxq(&sc->vtnet_rxqs[i]);
826 		free(sc->vtnet_rxqs, M_DEVBUF);
827 		sc->vtnet_rxqs = NULL;
828 	}
829 
830 	if (sc->vtnet_txqs != NULL) {
831 		for (i = 0; i < sc->vtnet_max_vq_pairs; i++)
832 			vtnet_destroy_txq(&sc->vtnet_txqs[i]);
833 		free(sc->vtnet_txqs, M_DEVBUF);
834 		sc->vtnet_txqs = NULL;
835 	}
836 }
837 
838 static int
839 vtnet_alloc_rx_filters(struct vtnet_softc *sc)
840 {
841 
842 	if (sc->vtnet_flags & VTNET_FLAG_CTRL_RX) {
843 		sc->vtnet_mac_filter = malloc(sizeof(struct vtnet_mac_filter),
844 		    M_DEVBUF, M_NOWAIT | M_ZERO);
845 		if (sc->vtnet_mac_filter == NULL)
846 			return (ENOMEM);
847 	}
848 
849 	if (sc->vtnet_flags & VTNET_FLAG_VLAN_FILTER) {
850 		sc->vtnet_vlan_filter = malloc(sizeof(uint32_t) *
851 		    VTNET_VLAN_FILTER_NWORDS, M_DEVBUF, M_NOWAIT | M_ZERO);
852 		if (sc->vtnet_vlan_filter == NULL)
853 			return (ENOMEM);
854 	}
855 
856 	return (0);
857 }
858 
859 static void
860 vtnet_free_rx_filters(struct vtnet_softc *sc)
861 {
862 
863 	if (sc->vtnet_mac_filter != NULL) {
864 		free(sc->vtnet_mac_filter, M_DEVBUF);
865 		sc->vtnet_mac_filter = NULL;
866 	}
867 
868 	if (sc->vtnet_vlan_filter != NULL) {
869 		free(sc->vtnet_vlan_filter, M_DEVBUF);
870 		sc->vtnet_vlan_filter = NULL;
871 	}
872 }
873 
874 static int
875 vtnet_alloc_virtqueues(struct vtnet_softc *sc)
876 {
877 	device_t dev;
878 	struct vq_alloc_info *info;
879 	struct vtnet_rxq *rxq;
880 	struct vtnet_txq *txq;
881 	int i, idx, flags, nvqs, error;
882 
883 	dev = sc->vtnet_dev;
884 	flags = 0;
885 
886 	nvqs = sc->vtnet_max_vq_pairs * 2;
887 	if (sc->vtnet_flags & VTNET_FLAG_CTRL_VQ)
888 		nvqs++;
889 
890 	info = mallocarray(nvqs, sizeof(struct vq_alloc_info), M_TEMP,
891 	    M_NOWAIT);
892 	if (info == NULL)
893 		return (ENOMEM);
894 
895 	for (i = 0, idx = 0; i < sc->vtnet_max_vq_pairs; i++, idx+=2) {
896 		rxq = &sc->vtnet_rxqs[i];
897 		VQ_ALLOC_INFO_INIT(&info[idx], sc->vtnet_rx_nsegs,
898 		    vtnet_rx_vq_intr, rxq, &rxq->vtnrx_vq,
899 		    "%s-%d rx", device_get_nameunit(dev), rxq->vtnrx_id);
900 
901 		txq = &sc->vtnet_txqs[i];
902 		VQ_ALLOC_INFO_INIT(&info[idx+1], sc->vtnet_tx_nsegs,
903 		    vtnet_tx_vq_intr, txq, &txq->vtntx_vq,
904 		    "%s-%d tx", device_get_nameunit(dev), txq->vtntx_id);
905 	}
906 
907 	if (sc->vtnet_flags & VTNET_FLAG_CTRL_VQ) {
908 		VQ_ALLOC_INFO_INIT(&info[idx], 0, NULL, NULL,
909 		    &sc->vtnet_ctrl_vq, "%s ctrl", device_get_nameunit(dev));
910 	}
911 
912 	/*
913 	 * Enable interrupt binding if this is multiqueue. This only matters
914 	 * when per-vq MSIX is available.
915 	 */
916 	if (sc->vtnet_flags & VTNET_FLAG_MULTIQ)
917 		flags |= 0;
918 
919 	error = virtio_alloc_virtqueues(dev, flags, nvqs, info);
920 	free(info, M_TEMP);
921 
922 	return (error);
923 }
924 
925 static int
926 vtnet_setup_interface(struct vtnet_softc *sc)
927 {
928 	device_t dev;
929 	struct ifnet *ifp;
930 
931 	dev = sc->vtnet_dev;
932 
933 	ifp = sc->vtnet_ifp = if_alloc(IFT_ETHER);
934 	if (ifp == NULL) {
935 		device_printf(dev, "cannot allocate ifnet structure\n");
936 		return (ENOSPC);
937 	}
938 
939 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
940 	ifp->if_baudrate = IF_Gbps(10);	/* Approx. */
941 	ifp->if_softc = sc;
942 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
943 	ifp->if_init = vtnet_init;
944 	ifp->if_ioctl = vtnet_ioctl;
945 	ifp->if_get_counter = vtnet_get_counter;
946 #ifndef VTNET_LEGACY_TX
947 	ifp->if_transmit = vtnet_txq_mq_start;
948 	ifp->if_qflush = vtnet_qflush;
949 #else
950 	struct virtqueue *vq = sc->vtnet_txqs[0].vtntx_vq;
951 	ifp->if_start = vtnet_start;
952 	IFQ_SET_MAXLEN(&ifp->if_snd, virtqueue_size(vq) - 1);
953 	ifp->if_snd.ifq_drv_maxlen = virtqueue_size(vq) - 1;
954 	IFQ_SET_READY(&ifp->if_snd);
955 #endif
956 
957 	ifmedia_init(&sc->vtnet_media, IFM_IMASK, vtnet_ifmedia_upd,
958 	    vtnet_ifmedia_sts);
959 	ifmedia_add(&sc->vtnet_media, VTNET_MEDIATYPE, 0, NULL);
960 	ifmedia_set(&sc->vtnet_media, VTNET_MEDIATYPE);
961 
962 	/* Read (or generate) the MAC address for the adapter. */
963 	vtnet_get_hwaddr(sc);
964 
965 	ether_ifattach(ifp, sc->vtnet_hwaddr);
966 
967 	if (virtio_with_feature(dev, VIRTIO_NET_F_STATUS))
968 		ifp->if_capabilities |= IFCAP_LINKSTATE;
969 
970 	/* Tell the upper layer(s) we support long frames. */
971 	ifp->if_hdrlen = sizeof(struct ether_vlan_header);
972 	ifp->if_capabilities |= IFCAP_JUMBO_MTU | IFCAP_VLAN_MTU;
973 
974 	if (virtio_with_feature(dev, VIRTIO_NET_F_CSUM)) {
975 		ifp->if_capabilities |= IFCAP_TXCSUM | IFCAP_TXCSUM_IPV6;
976 
977 		if (virtio_with_feature(dev, VIRTIO_NET_F_GSO)) {
978 			ifp->if_capabilities |= IFCAP_TSO4 | IFCAP_TSO6;
979 			sc->vtnet_flags |= VTNET_FLAG_TSO_ECN;
980 		} else {
981 			if (virtio_with_feature(dev, VIRTIO_NET_F_HOST_TSO4))
982 				ifp->if_capabilities |= IFCAP_TSO4;
983 			if (virtio_with_feature(dev, VIRTIO_NET_F_HOST_TSO6))
984 				ifp->if_capabilities |= IFCAP_TSO6;
985 			if (virtio_with_feature(dev, VIRTIO_NET_F_HOST_ECN))
986 				sc->vtnet_flags |= VTNET_FLAG_TSO_ECN;
987 		}
988 
989 		if (ifp->if_capabilities & IFCAP_TSO)
990 			ifp->if_capabilities |= IFCAP_VLAN_HWTSO;
991 	}
992 
993 	if (virtio_with_feature(dev, VIRTIO_NET_F_GUEST_CSUM)) {
994 		ifp->if_capabilities |= IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6;
995 
996 		if (virtio_with_feature(dev, VIRTIO_NET_F_GUEST_TSO4) ||
997 		    virtio_with_feature(dev, VIRTIO_NET_F_GUEST_TSO6))
998 			ifp->if_capabilities |= IFCAP_LRO;
999 	}
1000 
1001 	if (ifp->if_capabilities & IFCAP_HWCSUM) {
1002 		/*
1003 		 * VirtIO does not support VLAN tagging, but we can fake
1004 		 * it by inserting and removing the 802.1Q header during
1005 		 * transmit and receive. We are then able to do checksum
1006 		 * offloading of VLAN frames.
1007 		 */
1008 		ifp->if_capabilities |=
1009 		    IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_HWCSUM;
1010 	}
1011 
1012 	ifp->if_capenable = ifp->if_capabilities;
1013 
1014 	/*
1015 	 * Capabilities after here are not enabled by default.
1016 	 */
1017 
1018 	if (sc->vtnet_flags & VTNET_FLAG_VLAN_FILTER) {
1019 		ifp->if_capabilities |= IFCAP_VLAN_HWFILTER;
1020 
1021 		sc->vtnet_vlan_attach = EVENTHANDLER_REGISTER(vlan_config,
1022 		    vtnet_register_vlan, sc, EVENTHANDLER_PRI_FIRST);
1023 		sc->vtnet_vlan_detach = EVENTHANDLER_REGISTER(vlan_unconfig,
1024 		    vtnet_unregister_vlan, sc, EVENTHANDLER_PRI_FIRST);
1025 	}
1026 
1027 	vtnet_set_rx_process_limit(sc);
1028 	vtnet_set_tx_intr_threshold(sc);
1029 
1030 	return (0);
1031 }
1032 
1033 static int
1034 vtnet_change_mtu(struct vtnet_softc *sc, int new_mtu)
1035 {
1036 	struct ifnet *ifp;
1037 	int frame_size, clsize;
1038 
1039 	ifp = sc->vtnet_ifp;
1040 
1041 	if (new_mtu < ETHERMIN || new_mtu > VTNET_MAX_MTU)
1042 		return (EINVAL);
1043 
1044 	frame_size = sc->vtnet_hdr_size + sizeof(struct ether_vlan_header) +
1045 	    new_mtu;
1046 
1047 	/*
1048 	 * Based on the new MTU (and hence frame size) determine which
1049 	 * cluster size is most appropriate for the receive queues.
1050 	 */
1051 	if (frame_size <= MCLBYTES) {
1052 		clsize = MCLBYTES;
1053 	} else if ((sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS) == 0) {
1054 		/* Avoid going past 9K jumbos. */
1055 		if (frame_size > MJUM9BYTES)
1056 			return (EINVAL);
1057 		clsize = MJUM9BYTES;
1058 	} else
1059 		clsize = MJUMPAGESIZE;
1060 
1061 	ifp->if_mtu = new_mtu;
1062 	sc->vtnet_rx_new_clsize = clsize;
1063 
1064 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1065 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1066 		vtnet_init_locked(sc);
1067 	}
1068 
1069 	return (0);
1070 }
1071 
1072 static int
1073 vtnet_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1074 {
1075 	struct vtnet_softc *sc;
1076 	struct ifreq *ifr;
1077 	int reinit, mask, error;
1078 
1079 	sc = ifp->if_softc;
1080 	ifr = (struct ifreq *) data;
1081 	error = 0;
1082 
1083 	switch (cmd) {
1084 	case SIOCSIFMTU:
1085 		if (ifp->if_mtu != ifr->ifr_mtu) {
1086 			VTNET_CORE_LOCK(sc);
1087 			error = vtnet_change_mtu(sc, ifr->ifr_mtu);
1088 			VTNET_CORE_UNLOCK(sc);
1089 		}
1090 		break;
1091 
1092 	case SIOCSIFFLAGS:
1093 		VTNET_CORE_LOCK(sc);
1094 		if ((ifp->if_flags & IFF_UP) == 0) {
1095 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1096 				vtnet_stop(sc);
1097 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1098 			if ((ifp->if_flags ^ sc->vtnet_if_flags) &
1099 			    (IFF_PROMISC | IFF_ALLMULTI)) {
1100 				if (sc->vtnet_flags & VTNET_FLAG_CTRL_RX)
1101 					vtnet_rx_filter(sc);
1102 				else {
1103 					ifp->if_flags |= IFF_PROMISC;
1104 					if ((ifp->if_flags ^ sc->vtnet_if_flags)
1105 					    & IFF_ALLMULTI)
1106 						error = ENOTSUP;
1107 				}
1108 			}
1109 		} else
1110 			vtnet_init_locked(sc);
1111 
1112 		if (error == 0)
1113 			sc->vtnet_if_flags = ifp->if_flags;
1114 		VTNET_CORE_UNLOCK(sc);
1115 		break;
1116 
1117 	case SIOCADDMULTI:
1118 	case SIOCDELMULTI:
1119 		if ((sc->vtnet_flags & VTNET_FLAG_CTRL_RX) == 0)
1120 			break;
1121 		VTNET_CORE_LOCK(sc);
1122 		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1123 			vtnet_rx_filter_mac(sc);
1124 		VTNET_CORE_UNLOCK(sc);
1125 		break;
1126 
1127 	case SIOCSIFMEDIA:
1128 	case SIOCGIFMEDIA:
1129 		error = ifmedia_ioctl(ifp, ifr, &sc->vtnet_media, cmd);
1130 		break;
1131 
1132 	case SIOCSIFCAP:
1133 		VTNET_CORE_LOCK(sc);
1134 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1135 
1136 		if (mask & IFCAP_TXCSUM)
1137 			ifp->if_capenable ^= IFCAP_TXCSUM;
1138 		if (mask & IFCAP_TXCSUM_IPV6)
1139 			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
1140 		if (mask & IFCAP_TSO4)
1141 			ifp->if_capenable ^= IFCAP_TSO4;
1142 		if (mask & IFCAP_TSO6)
1143 			ifp->if_capenable ^= IFCAP_TSO6;
1144 
1145 		if (mask & (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6 | IFCAP_LRO |
1146 		    IFCAP_VLAN_HWFILTER)) {
1147 			/* These Rx features require us to renegotiate. */
1148 			reinit = 1;
1149 
1150 			if (mask & IFCAP_RXCSUM)
1151 				ifp->if_capenable ^= IFCAP_RXCSUM;
1152 			if (mask & IFCAP_RXCSUM_IPV6)
1153 				ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
1154 			if (mask & IFCAP_LRO)
1155 				ifp->if_capenable ^= IFCAP_LRO;
1156 			if (mask & IFCAP_VLAN_HWFILTER)
1157 				ifp->if_capenable ^= IFCAP_VLAN_HWFILTER;
1158 		} else
1159 			reinit = 0;
1160 
1161 		if (mask & IFCAP_VLAN_HWTSO)
1162 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
1163 		if (mask & IFCAP_VLAN_HWTAGGING)
1164 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
1165 
1166 		if (reinit && (ifp->if_drv_flags & IFF_DRV_RUNNING)) {
1167 			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1168 			vtnet_init_locked(sc);
1169 		}
1170 
1171 		VTNET_CORE_UNLOCK(sc);
1172 		VLAN_CAPABILITIES(ifp);
1173 
1174 		break;
1175 
1176 	default:
1177 		error = ether_ioctl(ifp, cmd, data);
1178 		break;
1179 	}
1180 
1181 	VTNET_CORE_LOCK_ASSERT_NOTOWNED(sc);
1182 
1183 	return (error);
1184 }
1185 
1186 static int
1187 vtnet_rxq_populate(struct vtnet_rxq *rxq)
1188 {
1189 	struct virtqueue *vq;
1190 	int nbufs, error;
1191 
1192 	vq = rxq->vtnrx_vq;
1193 	error = ENOSPC;
1194 
1195 	for (nbufs = 0; !virtqueue_full(vq); nbufs++) {
1196 		error = vtnet_rxq_new_buf(rxq);
1197 		if (error)
1198 			break;
1199 	}
1200 
1201 	if (nbufs > 0) {
1202 		virtqueue_notify(vq);
1203 		/*
1204 		 * EMSGSIZE signifies the virtqueue did not have enough
1205 		 * entries available to hold the last mbuf. This is not
1206 		 * an error.
1207 		 */
1208 		if (error == EMSGSIZE)
1209 			error = 0;
1210 	}
1211 
1212 	return (error);
1213 }
1214 
1215 static void
1216 vtnet_rxq_free_mbufs(struct vtnet_rxq *rxq)
1217 {
1218 	struct virtqueue *vq;
1219 	struct mbuf *m;
1220 	int last;
1221 
1222 	vq = rxq->vtnrx_vq;
1223 	last = 0;
1224 
1225 	while ((m = virtqueue_drain(vq, &last)) != NULL)
1226 		m_freem(m);
1227 
1228 	KASSERT(virtqueue_empty(vq),
1229 	    ("%s: mbufs remaining in rx queue %p", __func__, rxq));
1230 }
1231 
1232 static struct mbuf *
1233 vtnet_rx_alloc_buf(struct vtnet_softc *sc, int nbufs, struct mbuf **m_tailp)
1234 {
1235 	struct mbuf *m_head, *m_tail, *m;
1236 	int i, clsize;
1237 
1238 	clsize = sc->vtnet_rx_clsize;
1239 
1240 	KASSERT(nbufs == 1 || sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG,
1241 	    ("%s: chained mbuf %d request without LRO_NOMRG", __func__, nbufs));
1242 
1243 	m_head = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, clsize);
1244 	if (m_head == NULL)
1245 		goto fail;
1246 
1247 	m_head->m_len = clsize;
1248 	m_tail = m_head;
1249 
1250 	/* Allocate the rest of the chain. */
1251 	for (i = 1; i < nbufs; i++) {
1252 		m = m_getjcl(M_NOWAIT, MT_DATA, 0, clsize);
1253 		if (m == NULL)
1254 			goto fail;
1255 
1256 		m->m_len = clsize;
1257 		m_tail->m_next = m;
1258 		m_tail = m;
1259 	}
1260 
1261 	if (m_tailp != NULL)
1262 		*m_tailp = m_tail;
1263 
1264 	return (m_head);
1265 
1266 fail:
1267 	sc->vtnet_stats.mbuf_alloc_failed++;
1268 	m_freem(m_head);
1269 
1270 	return (NULL);
1271 }
1272 
1273 /*
1274  * Slow path for when LRO without mergeable buffers is negotiated.
1275  */
1276 static int
1277 vtnet_rxq_replace_lro_nomgr_buf(struct vtnet_rxq *rxq, struct mbuf *m0,
1278     int len0)
1279 {
1280 	struct vtnet_softc *sc;
1281 	struct mbuf *m, *m_prev;
1282 	struct mbuf *m_new, *m_tail;
1283 	int len, clsize, nreplace, error;
1284 
1285 	sc = rxq->vtnrx_sc;
1286 	clsize = sc->vtnet_rx_clsize;
1287 
1288 	m_prev = NULL;
1289 	m_tail = NULL;
1290 	nreplace = 0;
1291 
1292 	m = m0;
1293 	len = len0;
1294 
1295 	/*
1296 	 * Since these mbuf chains are so large, we avoid allocating an
1297 	 * entire replacement chain if possible. When the received frame
1298 	 * did not consume the entire chain, the unused mbufs are moved
1299 	 * to the replacement chain.
1300 	 */
1301 	while (len > 0) {
1302 		/*
1303 		 * Something is seriously wrong if we received a frame
1304 		 * larger than the chain. Drop it.
1305 		 */
1306 		if (m == NULL) {
1307 			sc->vtnet_stats.rx_frame_too_large++;
1308 			return (EMSGSIZE);
1309 		}
1310 
1311 		/* We always allocate the same cluster size. */
1312 		KASSERT(m->m_len == clsize,
1313 		    ("%s: mbuf size %d is not the cluster size %d",
1314 		    __func__, m->m_len, clsize));
1315 
1316 		m->m_len = MIN(m->m_len, len);
1317 		len -= m->m_len;
1318 
1319 		m_prev = m;
1320 		m = m->m_next;
1321 		nreplace++;
1322 	}
1323 
1324 	KASSERT(nreplace <= sc->vtnet_rx_nmbufs,
1325 	    ("%s: too many replacement mbufs %d max %d", __func__, nreplace,
1326 	    sc->vtnet_rx_nmbufs));
1327 
1328 	m_new = vtnet_rx_alloc_buf(sc, nreplace, &m_tail);
1329 	if (m_new == NULL) {
1330 		m_prev->m_len = clsize;
1331 		return (ENOBUFS);
1332 	}
1333 
1334 	/*
1335 	 * Move any unused mbufs from the received chain onto the end
1336 	 * of the new chain.
1337 	 */
1338 	if (m_prev->m_next != NULL) {
1339 		m_tail->m_next = m_prev->m_next;
1340 		m_prev->m_next = NULL;
1341 	}
1342 
1343 	error = vtnet_rxq_enqueue_buf(rxq, m_new);
1344 	if (error) {
1345 		/*
1346 		 * BAD! We could not enqueue the replacement mbuf chain. We
1347 		 * must restore the m0 chain to the original state if it was
1348 		 * modified so we can subsequently discard it.
1349 		 *
1350 		 * NOTE: The replacement is suppose to be an identical copy
1351 		 * to the one just dequeued so this is an unexpected error.
1352 		 */
1353 		sc->vtnet_stats.rx_enq_replacement_failed++;
1354 
1355 		if (m_tail->m_next != NULL) {
1356 			m_prev->m_next = m_tail->m_next;
1357 			m_tail->m_next = NULL;
1358 		}
1359 
1360 		m_prev->m_len = clsize;
1361 		m_freem(m_new);
1362 	}
1363 
1364 	return (error);
1365 }
1366 
1367 static int
1368 vtnet_rxq_replace_buf(struct vtnet_rxq *rxq, struct mbuf *m, int len)
1369 {
1370 	struct vtnet_softc *sc;
1371 	struct mbuf *m_new;
1372 	int error;
1373 
1374 	sc = rxq->vtnrx_sc;
1375 
1376 	KASSERT(sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG || m->m_next == NULL,
1377 	    ("%s: chained mbuf without LRO_NOMRG", __func__));
1378 
1379 	if (m->m_next == NULL) {
1380 		/* Fast-path for the common case of just one mbuf. */
1381 		if (m->m_len < len)
1382 			return (EINVAL);
1383 
1384 		m_new = vtnet_rx_alloc_buf(sc, 1, NULL);
1385 		if (m_new == NULL)
1386 			return (ENOBUFS);
1387 
1388 		error = vtnet_rxq_enqueue_buf(rxq, m_new);
1389 		if (error) {
1390 			/*
1391 			 * The new mbuf is suppose to be an identical
1392 			 * copy of the one just dequeued so this is an
1393 			 * unexpected error.
1394 			 */
1395 			m_freem(m_new);
1396 			sc->vtnet_stats.rx_enq_replacement_failed++;
1397 		} else
1398 			m->m_len = len;
1399 	} else
1400 		error = vtnet_rxq_replace_lro_nomgr_buf(rxq, m, len);
1401 
1402 	return (error);
1403 }
1404 
1405 static int
1406 vtnet_rxq_enqueue_buf(struct vtnet_rxq *rxq, struct mbuf *m)
1407 {
1408 	struct vtnet_softc *sc;
1409 	struct sglist *sg;
1410 	struct vtnet_rx_header *rxhdr;
1411 	uint8_t *mdata;
1412 	int offset, error;
1413 
1414 	sc = rxq->vtnrx_sc;
1415 	sg = rxq->vtnrx_sg;
1416 	mdata = mtod(m, uint8_t *);
1417 
1418 	VTNET_RXQ_LOCK_ASSERT(rxq);
1419 	KASSERT(sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG || m->m_next == NULL,
1420 	    ("%s: chained mbuf without LRO_NOMRG", __func__));
1421 	KASSERT(m->m_len == sc->vtnet_rx_clsize,
1422 	    ("%s: unexpected cluster size %d/%d", __func__, m->m_len,
1423 	     sc->vtnet_rx_clsize));
1424 
1425 	sglist_reset(sg);
1426 	if ((sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS) == 0) {
1427 		MPASS(sc->vtnet_hdr_size == sizeof(struct virtio_net_hdr));
1428 		rxhdr = (struct vtnet_rx_header *) mdata;
1429 		sglist_append(sg, &rxhdr->vrh_hdr, sc->vtnet_hdr_size);
1430 		offset = sizeof(struct vtnet_rx_header);
1431 	} else
1432 		offset = 0;
1433 
1434 	sglist_append(sg, mdata + offset, m->m_len - offset);
1435 	if (m->m_next != NULL) {
1436 		error = sglist_append_mbuf(sg, m->m_next);
1437 		MPASS(error == 0);
1438 	}
1439 
1440 	error = virtqueue_enqueue(rxq->vtnrx_vq, m, sg, 0, sg->sg_nseg);
1441 
1442 	return (error);
1443 }
1444 
1445 static int
1446 vtnet_rxq_new_buf(struct vtnet_rxq *rxq)
1447 {
1448 	struct vtnet_softc *sc;
1449 	struct mbuf *m;
1450 	int error;
1451 
1452 	sc = rxq->vtnrx_sc;
1453 
1454 	m = vtnet_rx_alloc_buf(sc, sc->vtnet_rx_nmbufs, NULL);
1455 	if (m == NULL)
1456 		return (ENOBUFS);
1457 
1458 	error = vtnet_rxq_enqueue_buf(rxq, m);
1459 	if (error)
1460 		m_freem(m);
1461 
1462 	return (error);
1463 }
1464 
1465 /*
1466  * Use the checksum offset in the VirtIO header to set the
1467  * correct CSUM_* flags.
1468  */
1469 static int
1470 vtnet_rxq_csum_by_offset(struct vtnet_rxq *rxq, struct mbuf *m,
1471     uint16_t eth_type, int ip_start, struct virtio_net_hdr *hdr)
1472 {
1473 	struct vtnet_softc *sc;
1474 #if defined(INET) || defined(INET6)
1475 	int offset = hdr->csum_start + hdr->csum_offset;
1476 #endif
1477 
1478 	sc = rxq->vtnrx_sc;
1479 
1480 	/* Only do a basic sanity check on the offset. */
1481 	switch (eth_type) {
1482 #if defined(INET)
1483 	case ETHERTYPE_IP:
1484 		if (__predict_false(offset < ip_start + sizeof(struct ip)))
1485 			return (1);
1486 		break;
1487 #endif
1488 #if defined(INET6)
1489 	case ETHERTYPE_IPV6:
1490 		if (__predict_false(offset < ip_start + sizeof(struct ip6_hdr)))
1491 			return (1);
1492 		break;
1493 #endif
1494 	default:
1495 		sc->vtnet_stats.rx_csum_bad_ethtype++;
1496 		return (1);
1497 	}
1498 
1499 	/*
1500 	 * Use the offset to determine the appropriate CSUM_* flags. This is
1501 	 * a bit dirty, but we can get by with it since the checksum offsets
1502 	 * happen to be different. We assume the host host does not do IPv4
1503 	 * header checksum offloading.
1504 	 */
1505 	switch (hdr->csum_offset) {
1506 	case offsetof(struct udphdr, uh_sum):
1507 	case offsetof(struct tcphdr, th_sum):
1508 		m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1509 		m->m_pkthdr.csum_data = 0xFFFF;
1510 		break;
1511 	case offsetof(struct sctphdr, checksum):
1512 		m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
1513 		break;
1514 	default:
1515 		sc->vtnet_stats.rx_csum_bad_offset++;
1516 		return (1);
1517 	}
1518 
1519 	return (0);
1520 }
1521 
1522 static int
1523 vtnet_rxq_csum_by_parse(struct vtnet_rxq *rxq, struct mbuf *m,
1524     uint16_t eth_type, int ip_start, struct virtio_net_hdr *hdr)
1525 {
1526 	struct vtnet_softc *sc;
1527 	int offset, proto;
1528 
1529 	sc = rxq->vtnrx_sc;
1530 
1531 	switch (eth_type) {
1532 #if defined(INET)
1533 	case ETHERTYPE_IP: {
1534 		struct ip *ip;
1535 		if (__predict_false(m->m_len < ip_start + sizeof(struct ip)))
1536 			return (1);
1537 		ip = (struct ip *)(m->m_data + ip_start);
1538 		proto = ip->ip_p;
1539 		offset = ip_start + (ip->ip_hl << 2);
1540 		break;
1541 	}
1542 #endif
1543 #if defined(INET6)
1544 	case ETHERTYPE_IPV6:
1545 		if (__predict_false(m->m_len < ip_start +
1546 		    sizeof(struct ip6_hdr)))
1547 			return (1);
1548 		offset = ip6_lasthdr(m, ip_start, IPPROTO_IPV6, &proto);
1549 		if (__predict_false(offset < 0))
1550 			return (1);
1551 		break;
1552 #endif
1553 	default:
1554 		sc->vtnet_stats.rx_csum_bad_ethtype++;
1555 		return (1);
1556 	}
1557 
1558 	switch (proto) {
1559 	case IPPROTO_TCP:
1560 		if (__predict_false(m->m_len < offset + sizeof(struct tcphdr)))
1561 			return (1);
1562 		m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1563 		m->m_pkthdr.csum_data = 0xFFFF;
1564 		break;
1565 	case IPPROTO_UDP:
1566 		if (__predict_false(m->m_len < offset + sizeof(struct udphdr)))
1567 			return (1);
1568 		m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1569 		m->m_pkthdr.csum_data = 0xFFFF;
1570 		break;
1571 	case IPPROTO_SCTP:
1572 		if (__predict_false(m->m_len < offset + sizeof(struct sctphdr)))
1573 			return (1);
1574 		m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
1575 		break;
1576 	default:
1577 		/*
1578 		 * For the remaining protocols, FreeBSD does not support
1579 		 * checksum offloading, so the checksum will be recomputed.
1580 		 */
1581 #if 0
1582 		if_printf(sc->vtnet_ifp, "cksum offload of unsupported "
1583 		    "protocol eth_type=%#x proto=%d csum_start=%d "
1584 		    "csum_offset=%d\n", __func__, eth_type, proto,
1585 		    hdr->csum_start, hdr->csum_offset);
1586 #endif
1587 		break;
1588 	}
1589 
1590 	return (0);
1591 }
1592 
1593 /*
1594  * Set the appropriate CSUM_* flags. Unfortunately, the information
1595  * provided is not directly useful to us. The VirtIO header gives the
1596  * offset of the checksum, which is all Linux needs, but this is not
1597  * how FreeBSD does things. We are forced to peek inside the packet
1598  * a bit.
1599  *
1600  * It would be nice if VirtIO gave us the L4 protocol or if FreeBSD
1601  * could accept the offsets and let the stack figure it out.
1602  */
1603 static int
1604 vtnet_rxq_csum(struct vtnet_rxq *rxq, struct mbuf *m,
1605     struct virtio_net_hdr *hdr)
1606 {
1607 	struct ether_header *eh;
1608 	struct ether_vlan_header *evh;
1609 	uint16_t eth_type;
1610 	int offset, error;
1611 
1612 	eh = mtod(m, struct ether_header *);
1613 	eth_type = ntohs(eh->ether_type);
1614 	if (eth_type == ETHERTYPE_VLAN) {
1615 		/* BMV: We should handle nested VLAN tags too. */
1616 		evh = mtod(m, struct ether_vlan_header *);
1617 		eth_type = ntohs(evh->evl_proto);
1618 		offset = sizeof(struct ether_vlan_header);
1619 	} else
1620 		offset = sizeof(struct ether_header);
1621 
1622 	if (hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
1623 		error = vtnet_rxq_csum_by_offset(rxq, m, eth_type, offset, hdr);
1624 	else
1625 		error = vtnet_rxq_csum_by_parse(rxq, m, eth_type, offset, hdr);
1626 
1627 	return (error);
1628 }
1629 
1630 static void
1631 vtnet_rxq_discard_merged_bufs(struct vtnet_rxq *rxq, int nbufs)
1632 {
1633 	struct mbuf *m;
1634 
1635 	while (--nbufs > 0) {
1636 		m = virtqueue_dequeue(rxq->vtnrx_vq, NULL);
1637 		if (m == NULL)
1638 			break;
1639 		vtnet_rxq_discard_buf(rxq, m);
1640 	}
1641 }
1642 
1643 static void
1644 vtnet_rxq_discard_buf(struct vtnet_rxq *rxq, struct mbuf *m)
1645 {
1646 	int error;
1647 
1648 	/*
1649 	 * Requeue the discarded mbuf. This should always be successful
1650 	 * since it was just dequeued.
1651 	 */
1652 	error = vtnet_rxq_enqueue_buf(rxq, m);
1653 	KASSERT(error == 0,
1654 	    ("%s: cannot requeue discarded mbuf %d", __func__, error));
1655 }
1656 
1657 static int
1658 vtnet_rxq_merged_eof(struct vtnet_rxq *rxq, struct mbuf *m_head, int nbufs)
1659 {
1660 	struct vtnet_softc *sc;
1661 	struct virtqueue *vq;
1662 	struct mbuf *m, *m_tail;
1663 	int len;
1664 
1665 	sc = rxq->vtnrx_sc;
1666 	vq = rxq->vtnrx_vq;
1667 	m_tail = m_head;
1668 
1669 	while (--nbufs > 0) {
1670 		m = virtqueue_dequeue(vq, &len);
1671 		if (m == NULL) {
1672 			rxq->vtnrx_stats.vrxs_ierrors++;
1673 			goto fail;
1674 		}
1675 
1676 		if (vtnet_rxq_new_buf(rxq) != 0) {
1677 			rxq->vtnrx_stats.vrxs_iqdrops++;
1678 			vtnet_rxq_discard_buf(rxq, m);
1679 			if (nbufs > 1)
1680 				vtnet_rxq_discard_merged_bufs(rxq, nbufs);
1681 			goto fail;
1682 		}
1683 
1684 		if (m->m_len < len)
1685 			len = m->m_len;
1686 
1687 		m->m_len = len;
1688 		m->m_flags &= ~M_PKTHDR;
1689 
1690 		m_head->m_pkthdr.len += len;
1691 		m_tail->m_next = m;
1692 		m_tail = m;
1693 	}
1694 
1695 	return (0);
1696 
1697 fail:
1698 	sc->vtnet_stats.rx_mergeable_failed++;
1699 	m_freem(m_head);
1700 
1701 	return (1);
1702 }
1703 
1704 static void
1705 vtnet_rxq_input(struct vtnet_rxq *rxq, struct mbuf *m,
1706     struct virtio_net_hdr *hdr)
1707 {
1708 	struct vtnet_softc *sc;
1709 	struct ifnet *ifp;
1710 	struct ether_header *eh;
1711 
1712 	sc = rxq->vtnrx_sc;
1713 	ifp = sc->vtnet_ifp;
1714 
1715 	if (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) {
1716 		eh = mtod(m, struct ether_header *);
1717 		if (eh->ether_type == htons(ETHERTYPE_VLAN)) {
1718 			vtnet_vlan_tag_remove(m);
1719 			/*
1720 			 * With the 802.1Q header removed, update the
1721 			 * checksum starting location accordingly.
1722 			 */
1723 			if (hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
1724 				hdr->csum_start -= ETHER_VLAN_ENCAP_LEN;
1725 		}
1726 	}
1727 
1728 	m->m_pkthdr.flowid = rxq->vtnrx_id;
1729 	M_HASHTYPE_SET(m, M_HASHTYPE_OPAQUE);
1730 
1731 	/*
1732 	 * BMV: FreeBSD does not have the UNNECESSARY and PARTIAL checksum
1733 	 * distinction that Linux does. Need to reevaluate if performing
1734 	 * offloading for the NEEDS_CSUM case is really appropriate.
1735 	 */
1736 	if (hdr->flags & (VIRTIO_NET_HDR_F_NEEDS_CSUM |
1737 	    VIRTIO_NET_HDR_F_DATA_VALID)) {
1738 		if (vtnet_rxq_csum(rxq, m, hdr) == 0)
1739 			rxq->vtnrx_stats.vrxs_csum++;
1740 		else
1741 			rxq->vtnrx_stats.vrxs_csum_failed++;
1742 	}
1743 
1744 	rxq->vtnrx_stats.vrxs_ipackets++;
1745 	rxq->vtnrx_stats.vrxs_ibytes += m->m_pkthdr.len;
1746 
1747 	VTNET_RXQ_UNLOCK(rxq);
1748 	(*ifp->if_input)(ifp, m);
1749 	VTNET_RXQ_LOCK(rxq);
1750 }
1751 
1752 static int
1753 vtnet_rxq_eof(struct vtnet_rxq *rxq)
1754 {
1755 	struct virtio_net_hdr lhdr, *hdr;
1756 	struct vtnet_softc *sc;
1757 	struct ifnet *ifp;
1758 	struct virtqueue *vq;
1759 	struct mbuf *m;
1760 	struct virtio_net_hdr_mrg_rxbuf *mhdr;
1761 	int len, deq, nbufs, adjsz, count;
1762 
1763 	sc = rxq->vtnrx_sc;
1764 	vq = rxq->vtnrx_vq;
1765 	ifp = sc->vtnet_ifp;
1766 	hdr = &lhdr;
1767 	deq = 0;
1768 	count = sc->vtnet_rx_process_limit;
1769 
1770 	VTNET_RXQ_LOCK_ASSERT(rxq);
1771 
1772 #ifdef DEV_NETMAP
1773 	if (netmap_rx_irq(ifp, 0, &deq)) {
1774 		return (FALSE);
1775 	}
1776 #endif /* DEV_NETMAP */
1777 
1778 	while (count-- > 0) {
1779 		m = virtqueue_dequeue(vq, &len);
1780 		if (m == NULL)
1781 			break;
1782 		deq++;
1783 
1784 		if (len < sc->vtnet_hdr_size + ETHER_HDR_LEN) {
1785 			rxq->vtnrx_stats.vrxs_ierrors++;
1786 			vtnet_rxq_discard_buf(rxq, m);
1787 			continue;
1788 		}
1789 
1790 		if ((sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS) == 0) {
1791 			nbufs = 1;
1792 			adjsz = sizeof(struct vtnet_rx_header);
1793 			/*
1794 			 * Account for our pad inserted between the header
1795 			 * and the actual start of the frame.
1796 			 */
1797 			len += VTNET_RX_HEADER_PAD;
1798 		} else {
1799 			mhdr = mtod(m, struct virtio_net_hdr_mrg_rxbuf *);
1800 			nbufs = mhdr->num_buffers;
1801 			adjsz = sizeof(struct virtio_net_hdr_mrg_rxbuf);
1802 		}
1803 
1804 		if (vtnet_rxq_replace_buf(rxq, m, len) != 0) {
1805 			rxq->vtnrx_stats.vrxs_iqdrops++;
1806 			vtnet_rxq_discard_buf(rxq, m);
1807 			if (nbufs > 1)
1808 				vtnet_rxq_discard_merged_bufs(rxq, nbufs);
1809 			continue;
1810 		}
1811 
1812 		m->m_pkthdr.len = len;
1813 		m->m_pkthdr.rcvif = ifp;
1814 		m->m_pkthdr.csum_flags = 0;
1815 
1816 		if (nbufs > 1) {
1817 			/* Dequeue the rest of chain. */
1818 			if (vtnet_rxq_merged_eof(rxq, m, nbufs) != 0)
1819 				continue;
1820 		}
1821 
1822 		/*
1823 		 * Save copy of header before we strip it. For both mergeable
1824 		 * and non-mergeable, the header is at the beginning of the
1825 		 * mbuf data. We no longer need num_buffers, so always use a
1826 		 * regular header.
1827 		 *
1828 		 * BMV: Is this memcpy() expensive? We know the mbuf data is
1829 		 * still valid even after the m_adj().
1830 		 */
1831 		memcpy(hdr, mtod(m, void *), sizeof(struct virtio_net_hdr));
1832 		m_adj(m, adjsz);
1833 
1834 		vtnet_rxq_input(rxq, m, hdr);
1835 
1836 		/* Must recheck after dropping the Rx lock. */
1837 		if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1838 			break;
1839 	}
1840 
1841 	if (deq > 0)
1842 		virtqueue_notify(vq);
1843 
1844 	return (count > 0 ? 0 : EAGAIN);
1845 }
1846 
1847 static void
1848 vtnet_rx_vq_intr(void *xrxq)
1849 {
1850 	struct vtnet_softc *sc;
1851 	struct vtnet_rxq *rxq;
1852 	struct ifnet *ifp;
1853 	int tries, more;
1854 
1855 	rxq = xrxq;
1856 	sc = rxq->vtnrx_sc;
1857 	ifp = sc->vtnet_ifp;
1858 	tries = 0;
1859 
1860 	if (__predict_false(rxq->vtnrx_id >= sc->vtnet_act_vq_pairs)) {
1861 		/*
1862 		 * Ignore this interrupt. Either this is a spurious interrupt
1863 		 * or multiqueue without per-VQ MSIX so every queue needs to
1864 		 * be polled (a brain dead configuration we could try harder
1865 		 * to avoid).
1866 		 */
1867 		vtnet_rxq_disable_intr(rxq);
1868 		return;
1869 	}
1870 
1871 	VTNET_RXQ_LOCK(rxq);
1872 
1873 again:
1874 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1875 		VTNET_RXQ_UNLOCK(rxq);
1876 		return;
1877 	}
1878 
1879 	more = vtnet_rxq_eof(rxq);
1880 	if (more || vtnet_rxq_enable_intr(rxq) != 0) {
1881 		if (!more)
1882 			vtnet_rxq_disable_intr(rxq);
1883 		/*
1884 		 * This is an occasional condition or race (when !more),
1885 		 * so retry a few times before scheduling the taskqueue.
1886 		 */
1887 		if (tries++ < VTNET_INTR_DISABLE_RETRIES)
1888 			goto again;
1889 
1890 		VTNET_RXQ_UNLOCK(rxq);
1891 		rxq->vtnrx_stats.vrxs_rescheduled++;
1892 		taskqueue_enqueue(rxq->vtnrx_tq, &rxq->vtnrx_intrtask);
1893 	} else
1894 		VTNET_RXQ_UNLOCK(rxq);
1895 }
1896 
1897 static void
1898 vtnet_rxq_tq_intr(void *xrxq, int pending)
1899 {
1900 	struct vtnet_softc *sc;
1901 	struct vtnet_rxq *rxq;
1902 	struct ifnet *ifp;
1903 	int more;
1904 
1905 	rxq = xrxq;
1906 	sc = rxq->vtnrx_sc;
1907 	ifp = sc->vtnet_ifp;
1908 
1909 	VTNET_RXQ_LOCK(rxq);
1910 
1911 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1912 		VTNET_RXQ_UNLOCK(rxq);
1913 		return;
1914 	}
1915 
1916 	more = vtnet_rxq_eof(rxq);
1917 	if (more || vtnet_rxq_enable_intr(rxq) != 0) {
1918 		if (!more)
1919 			vtnet_rxq_disable_intr(rxq);
1920 		rxq->vtnrx_stats.vrxs_rescheduled++;
1921 		taskqueue_enqueue(rxq->vtnrx_tq, &rxq->vtnrx_intrtask);
1922 	}
1923 
1924 	VTNET_RXQ_UNLOCK(rxq);
1925 }
1926 
1927 static int
1928 vtnet_txq_below_threshold(struct vtnet_txq *txq)
1929 {
1930 	struct vtnet_softc *sc;
1931 	struct virtqueue *vq;
1932 
1933 	sc = txq->vtntx_sc;
1934 	vq = txq->vtntx_vq;
1935 
1936 	return (virtqueue_nfree(vq) <= sc->vtnet_tx_intr_thresh);
1937 }
1938 
1939 static int
1940 vtnet_txq_notify(struct vtnet_txq *txq)
1941 {
1942 	struct virtqueue *vq;
1943 
1944 	vq = txq->vtntx_vq;
1945 
1946 	txq->vtntx_watchdog = VTNET_TX_TIMEOUT;
1947 	virtqueue_notify(vq);
1948 
1949 	if (vtnet_txq_enable_intr(txq) == 0)
1950 		return (0);
1951 
1952 	/*
1953 	 * Drain frames that were completed since last checked. If this
1954 	 * causes the queue to go above the threshold, the caller should
1955 	 * continue transmitting.
1956 	 */
1957 	if (vtnet_txq_eof(txq) != 0 && vtnet_txq_below_threshold(txq) == 0) {
1958 		virtqueue_disable_intr(vq);
1959 		return (1);
1960 	}
1961 
1962 	return (0);
1963 }
1964 
1965 static void
1966 vtnet_txq_free_mbufs(struct vtnet_txq *txq)
1967 {
1968 	struct virtqueue *vq;
1969 	struct vtnet_tx_header *txhdr;
1970 	int last;
1971 
1972 	vq = txq->vtntx_vq;
1973 	last = 0;
1974 
1975 	while ((txhdr = virtqueue_drain(vq, &last)) != NULL) {
1976 		m_freem(txhdr->vth_mbuf);
1977 		uma_zfree(vtnet_tx_header_zone, txhdr);
1978 	}
1979 
1980 	KASSERT(virtqueue_empty(vq),
1981 	    ("%s: mbufs remaining in tx queue %p", __func__, txq));
1982 }
1983 
1984 /*
1985  * BMV: Much of this can go away once we finally have offsets in
1986  * the mbuf packet header. Bug andre@.
1987  */
1988 static int
1989 vtnet_txq_offload_ctx(struct vtnet_txq *txq, struct mbuf *m,
1990     int *etype, int *proto, int *start)
1991 {
1992 	struct vtnet_softc *sc;
1993 	struct ether_vlan_header *evh;
1994 	int offset;
1995 
1996 	sc = txq->vtntx_sc;
1997 
1998 	evh = mtod(m, struct ether_vlan_header *);
1999 	if (evh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
2000 		/* BMV: We should handle nested VLAN tags too. */
2001 		*etype = ntohs(evh->evl_proto);
2002 		offset = sizeof(struct ether_vlan_header);
2003 	} else {
2004 		*etype = ntohs(evh->evl_encap_proto);
2005 		offset = sizeof(struct ether_header);
2006 	}
2007 
2008 	switch (*etype) {
2009 #if defined(INET)
2010 	case ETHERTYPE_IP: {
2011 		struct ip *ip, iphdr;
2012 		if (__predict_false(m->m_len < offset + sizeof(struct ip))) {
2013 			m_copydata(m, offset, sizeof(struct ip),
2014 			    (caddr_t) &iphdr);
2015 			ip = &iphdr;
2016 		} else
2017 			ip = (struct ip *)(m->m_data + offset);
2018 		*proto = ip->ip_p;
2019 		*start = offset + (ip->ip_hl << 2);
2020 		break;
2021 	}
2022 #endif
2023 #if defined(INET6)
2024 	case ETHERTYPE_IPV6:
2025 		*proto = -1;
2026 		*start = ip6_lasthdr(m, offset, IPPROTO_IPV6, proto);
2027 		/* Assert the network stack sent us a valid packet. */
2028 		KASSERT(*start > offset,
2029 		    ("%s: mbuf %p start %d offset %d proto %d", __func__, m,
2030 		    *start, offset, *proto));
2031 		break;
2032 #endif
2033 	default:
2034 		sc->vtnet_stats.tx_csum_bad_ethtype++;
2035 		return (EINVAL);
2036 	}
2037 
2038 	return (0);
2039 }
2040 
2041 static int
2042 vtnet_txq_offload_tso(struct vtnet_txq *txq, struct mbuf *m, int eth_type,
2043     int offset, struct virtio_net_hdr *hdr)
2044 {
2045 	static struct timeval lastecn;
2046 	static int curecn;
2047 	struct vtnet_softc *sc;
2048 	struct tcphdr *tcp, tcphdr;
2049 
2050 	sc = txq->vtntx_sc;
2051 
2052 	if (__predict_false(m->m_len < offset + sizeof(struct tcphdr))) {
2053 		m_copydata(m, offset, sizeof(struct tcphdr), (caddr_t) &tcphdr);
2054 		tcp = &tcphdr;
2055 	} else
2056 		tcp = (struct tcphdr *)(m->m_data + offset);
2057 
2058 	hdr->hdr_len = offset + (tcp->th_off << 2);
2059 	hdr->gso_size = m->m_pkthdr.tso_segsz;
2060 	hdr->gso_type = eth_type == ETHERTYPE_IP ? VIRTIO_NET_HDR_GSO_TCPV4 :
2061 	    VIRTIO_NET_HDR_GSO_TCPV6;
2062 
2063 	if (tcp->th_flags & TH_CWR) {
2064 		/*
2065 		 * Drop if VIRTIO_NET_F_HOST_ECN was not negotiated. In FreeBSD,
2066 		 * ECN support is not on a per-interface basis, but globally via
2067 		 * the net.inet.tcp.ecn.enable sysctl knob. The default is off.
2068 		 */
2069 		if ((sc->vtnet_flags & VTNET_FLAG_TSO_ECN) == 0) {
2070 			if (ppsratecheck(&lastecn, &curecn, 1))
2071 				if_printf(sc->vtnet_ifp,
2072 				    "TSO with ECN not negotiated with host\n");
2073 			return (ENOTSUP);
2074 		}
2075 		hdr->gso_type |= VIRTIO_NET_HDR_GSO_ECN;
2076 	}
2077 
2078 	txq->vtntx_stats.vtxs_tso++;
2079 
2080 	return (0);
2081 }
2082 
2083 static struct mbuf *
2084 vtnet_txq_offload(struct vtnet_txq *txq, struct mbuf *m,
2085     struct virtio_net_hdr *hdr)
2086 {
2087 	struct vtnet_softc *sc;
2088 	int flags, etype, csum_start, proto, error;
2089 
2090 	sc = txq->vtntx_sc;
2091 	flags = m->m_pkthdr.csum_flags;
2092 
2093 	error = vtnet_txq_offload_ctx(txq, m, &etype, &proto, &csum_start);
2094 	if (error)
2095 		goto drop;
2096 
2097 	if ((etype == ETHERTYPE_IP && flags & VTNET_CSUM_OFFLOAD) ||
2098 	    (etype == ETHERTYPE_IPV6 && flags & VTNET_CSUM_OFFLOAD_IPV6)) {
2099 		/*
2100 		 * We could compare the IP protocol vs the CSUM_ flag too,
2101 		 * but that really should not be necessary.
2102 		 */
2103 		hdr->flags |= VIRTIO_NET_HDR_F_NEEDS_CSUM;
2104 		hdr->csum_start = csum_start;
2105 		hdr->csum_offset = m->m_pkthdr.csum_data;
2106 		txq->vtntx_stats.vtxs_csum++;
2107 	}
2108 
2109 	if (flags & CSUM_TSO) {
2110 		if (__predict_false(proto != IPPROTO_TCP)) {
2111 			/* Likely failed to correctly parse the mbuf. */
2112 			sc->vtnet_stats.tx_tso_not_tcp++;
2113 			goto drop;
2114 		}
2115 
2116 		KASSERT(hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM,
2117 		    ("%s: mbuf %p TSO without checksum offload %#x",
2118 		    __func__, m, flags));
2119 
2120 		error = vtnet_txq_offload_tso(txq, m, etype, csum_start, hdr);
2121 		if (error)
2122 			goto drop;
2123 	}
2124 
2125 	return (m);
2126 
2127 drop:
2128 	m_freem(m);
2129 	return (NULL);
2130 }
2131 
2132 static int
2133 vtnet_txq_enqueue_buf(struct vtnet_txq *txq, struct mbuf **m_head,
2134     struct vtnet_tx_header *txhdr)
2135 {
2136 	struct vtnet_softc *sc;
2137 	struct virtqueue *vq;
2138 	struct sglist *sg;
2139 	struct mbuf *m;
2140 	int error;
2141 
2142 	sc = txq->vtntx_sc;
2143 	vq = txq->vtntx_vq;
2144 	sg = txq->vtntx_sg;
2145 	m = *m_head;
2146 
2147 	sglist_reset(sg);
2148 	error = sglist_append(sg, &txhdr->vth_uhdr, sc->vtnet_hdr_size);
2149 	KASSERT(error == 0 && sg->sg_nseg == 1,
2150 	    ("%s: error %d adding header to sglist", __func__, error));
2151 
2152 	error = sglist_append_mbuf(sg, m);
2153 	if (error) {
2154 		m = m_defrag(m, M_NOWAIT);
2155 		if (m == NULL)
2156 			goto fail;
2157 
2158 		*m_head = m;
2159 		sc->vtnet_stats.tx_defragged++;
2160 
2161 		error = sglist_append_mbuf(sg, m);
2162 		if (error)
2163 			goto fail;
2164 	}
2165 
2166 	txhdr->vth_mbuf = m;
2167 	error = virtqueue_enqueue(vq, txhdr, sg, sg->sg_nseg, 0);
2168 
2169 	return (error);
2170 
2171 fail:
2172 	sc->vtnet_stats.tx_defrag_failed++;
2173 	m_freem(*m_head);
2174 	*m_head = NULL;
2175 
2176 	return (ENOBUFS);
2177 }
2178 
2179 static int
2180 vtnet_txq_encap(struct vtnet_txq *txq, struct mbuf **m_head)
2181 {
2182 	struct vtnet_tx_header *txhdr;
2183 	struct virtio_net_hdr *hdr;
2184 	struct mbuf *m;
2185 	int error;
2186 
2187 	m = *m_head;
2188 	M_ASSERTPKTHDR(m);
2189 
2190 	txhdr = uma_zalloc(vtnet_tx_header_zone, M_NOWAIT | M_ZERO);
2191 	if (txhdr == NULL) {
2192 		m_freem(m);
2193 		*m_head = NULL;
2194 		return (ENOMEM);
2195 	}
2196 
2197 	/*
2198 	 * Always use the non-mergeable header, regardless if the feature
2199 	 * was negotiated. For transmit, num_buffers is always zero. The
2200 	 * vtnet_hdr_size is used to enqueue the correct header size.
2201 	 */
2202 	hdr = &txhdr->vth_uhdr.hdr;
2203 
2204 	if (m->m_flags & M_VLANTAG) {
2205 		m = ether_vlanencap(m, m->m_pkthdr.ether_vtag);
2206 		if ((*m_head = m) == NULL) {
2207 			error = ENOBUFS;
2208 			goto fail;
2209 		}
2210 		m->m_flags &= ~M_VLANTAG;
2211 	}
2212 
2213 	if (m->m_pkthdr.csum_flags & VTNET_CSUM_ALL_OFFLOAD) {
2214 		m = vtnet_txq_offload(txq, m, hdr);
2215 		if ((*m_head = m) == NULL) {
2216 			error = ENOBUFS;
2217 			goto fail;
2218 		}
2219 	}
2220 
2221 	error = vtnet_txq_enqueue_buf(txq, m_head, txhdr);
2222 	if (error == 0)
2223 		return (0);
2224 
2225 fail:
2226 	uma_zfree(vtnet_tx_header_zone, txhdr);
2227 
2228 	return (error);
2229 }
2230 
2231 #ifdef VTNET_LEGACY_TX
2232 
2233 static void
2234 vtnet_start_locked(struct vtnet_txq *txq, struct ifnet *ifp)
2235 {
2236 	struct vtnet_softc *sc;
2237 	struct virtqueue *vq;
2238 	struct mbuf *m0;
2239 	int tries, enq;
2240 
2241 	sc = txq->vtntx_sc;
2242 	vq = txq->vtntx_vq;
2243 	tries = 0;
2244 
2245 	VTNET_TXQ_LOCK_ASSERT(txq);
2246 
2247 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
2248 	    sc->vtnet_link_active == 0)
2249 		return;
2250 
2251 	vtnet_txq_eof(txq);
2252 
2253 again:
2254 	enq = 0;
2255 
2256 	while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
2257 		if (virtqueue_full(vq))
2258 			break;
2259 
2260 		IFQ_DRV_DEQUEUE(&ifp->if_snd, m0);
2261 		if (m0 == NULL)
2262 			break;
2263 
2264 		if (vtnet_txq_encap(txq, &m0) != 0) {
2265 			if (m0 != NULL)
2266 				IFQ_DRV_PREPEND(&ifp->if_snd, m0);
2267 			break;
2268 		}
2269 
2270 		enq++;
2271 		ETHER_BPF_MTAP(ifp, m0);
2272 	}
2273 
2274 	if (enq > 0 && vtnet_txq_notify(txq) != 0) {
2275 		if (tries++ < VTNET_NOTIFY_RETRIES)
2276 			goto again;
2277 
2278 		txq->vtntx_stats.vtxs_rescheduled++;
2279 		taskqueue_enqueue(txq->vtntx_tq, &txq->vtntx_intrtask);
2280 	}
2281 }
2282 
2283 static void
2284 vtnet_start(struct ifnet *ifp)
2285 {
2286 	struct vtnet_softc *sc;
2287 	struct vtnet_txq *txq;
2288 
2289 	sc = ifp->if_softc;
2290 	txq = &sc->vtnet_txqs[0];
2291 
2292 	VTNET_TXQ_LOCK(txq);
2293 	vtnet_start_locked(txq, ifp);
2294 	VTNET_TXQ_UNLOCK(txq);
2295 }
2296 
2297 #else /* !VTNET_LEGACY_TX */
2298 
2299 static int
2300 vtnet_txq_mq_start_locked(struct vtnet_txq *txq, struct mbuf *m)
2301 {
2302 	struct vtnet_softc *sc;
2303 	struct virtqueue *vq;
2304 	struct buf_ring *br;
2305 	struct ifnet *ifp;
2306 	int enq, tries, error;
2307 
2308 	sc = txq->vtntx_sc;
2309 	vq = txq->vtntx_vq;
2310 	br = txq->vtntx_br;
2311 	ifp = sc->vtnet_ifp;
2312 	tries = 0;
2313 	error = 0;
2314 
2315 	VTNET_TXQ_LOCK_ASSERT(txq);
2316 
2317 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
2318 	    sc->vtnet_link_active == 0) {
2319 		if (m != NULL)
2320 			error = drbr_enqueue(ifp, br, m);
2321 		return (error);
2322 	}
2323 
2324 	if (m != NULL) {
2325 		error = drbr_enqueue(ifp, br, m);
2326 		if (error)
2327 			return (error);
2328 	}
2329 
2330 	vtnet_txq_eof(txq);
2331 
2332 again:
2333 	enq = 0;
2334 
2335 	while ((m = drbr_peek(ifp, br)) != NULL) {
2336 		if (virtqueue_full(vq)) {
2337 			drbr_putback(ifp, br, m);
2338 			break;
2339 		}
2340 
2341 		if (vtnet_txq_encap(txq, &m) != 0) {
2342 			if (m != NULL)
2343 				drbr_putback(ifp, br, m);
2344 			else
2345 				drbr_advance(ifp, br);
2346 			break;
2347 		}
2348 		drbr_advance(ifp, br);
2349 
2350 		enq++;
2351 		ETHER_BPF_MTAP(ifp, m);
2352 	}
2353 
2354 	if (enq > 0 && vtnet_txq_notify(txq) != 0) {
2355 		if (tries++ < VTNET_NOTIFY_RETRIES)
2356 			goto again;
2357 
2358 		txq->vtntx_stats.vtxs_rescheduled++;
2359 		taskqueue_enqueue(txq->vtntx_tq, &txq->vtntx_intrtask);
2360 	}
2361 
2362 	return (0);
2363 }
2364 
2365 static int
2366 vtnet_txq_mq_start(struct ifnet *ifp, struct mbuf *m)
2367 {
2368 	struct vtnet_softc *sc;
2369 	struct vtnet_txq *txq;
2370 	int i, npairs, error;
2371 
2372 	sc = ifp->if_softc;
2373 	npairs = sc->vtnet_act_vq_pairs;
2374 
2375 	/* check if flowid is set */
2376 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2377 		i = m->m_pkthdr.flowid % npairs;
2378 	else
2379 		i = curcpu % npairs;
2380 
2381 	txq = &sc->vtnet_txqs[i];
2382 
2383 	if (VTNET_TXQ_TRYLOCK(txq) != 0) {
2384 		error = vtnet_txq_mq_start_locked(txq, m);
2385 		VTNET_TXQ_UNLOCK(txq);
2386 	} else {
2387 		error = drbr_enqueue(ifp, txq->vtntx_br, m);
2388 		taskqueue_enqueue(txq->vtntx_tq, &txq->vtntx_defrtask);
2389 	}
2390 
2391 	return (error);
2392 }
2393 
2394 static void
2395 vtnet_txq_tq_deferred(void *xtxq, int pending)
2396 {
2397 	struct vtnet_softc *sc;
2398 	struct vtnet_txq *txq;
2399 
2400 	txq = xtxq;
2401 	sc = txq->vtntx_sc;
2402 
2403 	VTNET_TXQ_LOCK(txq);
2404 	if (!drbr_empty(sc->vtnet_ifp, txq->vtntx_br))
2405 		vtnet_txq_mq_start_locked(txq, NULL);
2406 	VTNET_TXQ_UNLOCK(txq);
2407 }
2408 
2409 #endif /* VTNET_LEGACY_TX */
2410 
2411 static void
2412 vtnet_txq_start(struct vtnet_txq *txq)
2413 {
2414 	struct vtnet_softc *sc;
2415 	struct ifnet *ifp;
2416 
2417 	sc = txq->vtntx_sc;
2418 	ifp = sc->vtnet_ifp;
2419 
2420 #ifdef VTNET_LEGACY_TX
2421 	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
2422 		vtnet_start_locked(txq, ifp);
2423 #else
2424 	if (!drbr_empty(ifp, txq->vtntx_br))
2425 		vtnet_txq_mq_start_locked(txq, NULL);
2426 #endif
2427 }
2428 
2429 static void
2430 vtnet_txq_tq_intr(void *xtxq, int pending)
2431 {
2432 	struct vtnet_softc *sc;
2433 	struct vtnet_txq *txq;
2434 	struct ifnet *ifp;
2435 
2436 	txq = xtxq;
2437 	sc = txq->vtntx_sc;
2438 	ifp = sc->vtnet_ifp;
2439 
2440 	VTNET_TXQ_LOCK(txq);
2441 
2442 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
2443 		VTNET_TXQ_UNLOCK(txq);
2444 		return;
2445 	}
2446 
2447 	vtnet_txq_eof(txq);
2448 	vtnet_txq_start(txq);
2449 
2450 	VTNET_TXQ_UNLOCK(txq);
2451 }
2452 
2453 static int
2454 vtnet_txq_eof(struct vtnet_txq *txq)
2455 {
2456 	struct virtqueue *vq;
2457 	struct vtnet_tx_header *txhdr;
2458 	struct mbuf *m;
2459 	int deq;
2460 
2461 	vq = txq->vtntx_vq;
2462 	deq = 0;
2463 	VTNET_TXQ_LOCK_ASSERT(txq);
2464 
2465 #ifdef DEV_NETMAP
2466 	if (netmap_tx_irq(txq->vtntx_sc->vtnet_ifp, txq->vtntx_id)) {
2467 		virtqueue_disable_intr(vq); // XXX luigi
2468 		return 0; // XXX or 1 ?
2469 	}
2470 #endif /* DEV_NETMAP */
2471 
2472 	while ((txhdr = virtqueue_dequeue(vq, NULL)) != NULL) {
2473 		m = txhdr->vth_mbuf;
2474 		deq++;
2475 
2476 		txq->vtntx_stats.vtxs_opackets++;
2477 		txq->vtntx_stats.vtxs_obytes += m->m_pkthdr.len;
2478 		if (m->m_flags & M_MCAST)
2479 			txq->vtntx_stats.vtxs_omcasts++;
2480 
2481 		m_freem(m);
2482 		uma_zfree(vtnet_tx_header_zone, txhdr);
2483 	}
2484 
2485 	if (virtqueue_empty(vq))
2486 		txq->vtntx_watchdog = 0;
2487 
2488 	return (deq);
2489 }
2490 
2491 static void
2492 vtnet_tx_vq_intr(void *xtxq)
2493 {
2494 	struct vtnet_softc *sc;
2495 	struct vtnet_txq *txq;
2496 	struct ifnet *ifp;
2497 
2498 	txq = xtxq;
2499 	sc = txq->vtntx_sc;
2500 	ifp = sc->vtnet_ifp;
2501 
2502 	if (__predict_false(txq->vtntx_id >= sc->vtnet_act_vq_pairs)) {
2503 		/*
2504 		 * Ignore this interrupt. Either this is a spurious interrupt
2505 		 * or multiqueue without per-VQ MSIX so every queue needs to
2506 		 * be polled (a brain dead configuration we could try harder
2507 		 * to avoid).
2508 		 */
2509 		vtnet_txq_disable_intr(txq);
2510 		return;
2511 	}
2512 
2513 	VTNET_TXQ_LOCK(txq);
2514 
2515 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
2516 		VTNET_TXQ_UNLOCK(txq);
2517 		return;
2518 	}
2519 
2520 	vtnet_txq_eof(txq);
2521 	vtnet_txq_start(txq);
2522 
2523 	VTNET_TXQ_UNLOCK(txq);
2524 }
2525 
2526 static void
2527 vtnet_tx_start_all(struct vtnet_softc *sc)
2528 {
2529 	struct vtnet_txq *txq;
2530 	int i;
2531 
2532 	VTNET_CORE_LOCK_ASSERT(sc);
2533 
2534 	for (i = 0; i < sc->vtnet_act_vq_pairs; i++) {
2535 		txq = &sc->vtnet_txqs[i];
2536 
2537 		VTNET_TXQ_LOCK(txq);
2538 		vtnet_txq_start(txq);
2539 		VTNET_TXQ_UNLOCK(txq);
2540 	}
2541 }
2542 
2543 #ifndef VTNET_LEGACY_TX
2544 static void
2545 vtnet_qflush(struct ifnet *ifp)
2546 {
2547 	struct vtnet_softc *sc;
2548 	struct vtnet_txq *txq;
2549 	struct mbuf *m;
2550 	int i;
2551 
2552 	sc = ifp->if_softc;
2553 
2554 	for (i = 0; i < sc->vtnet_act_vq_pairs; i++) {
2555 		txq = &sc->vtnet_txqs[i];
2556 
2557 		VTNET_TXQ_LOCK(txq);
2558 		while ((m = buf_ring_dequeue_sc(txq->vtntx_br)) != NULL)
2559 			m_freem(m);
2560 		VTNET_TXQ_UNLOCK(txq);
2561 	}
2562 
2563 	if_qflush(ifp);
2564 }
2565 #endif
2566 
2567 static int
2568 vtnet_watchdog(struct vtnet_txq *txq)
2569 {
2570 	struct ifnet *ifp;
2571 
2572 	ifp = txq->vtntx_sc->vtnet_ifp;
2573 
2574 	VTNET_TXQ_LOCK(txq);
2575 	if (txq->vtntx_watchdog == 1) {
2576 		/*
2577 		 * Only drain completed frames if the watchdog is about to
2578 		 * expire. If any frames were drained, there may be enough
2579 		 * free descriptors now available to transmit queued frames.
2580 		 * In that case, the timer will immediately be decremented
2581 		 * below, but the timeout is generous enough that should not
2582 		 * be a problem.
2583 		 */
2584 		if (vtnet_txq_eof(txq) != 0)
2585 			vtnet_txq_start(txq);
2586 	}
2587 
2588 	if (txq->vtntx_watchdog == 0 || --txq->vtntx_watchdog) {
2589 		VTNET_TXQ_UNLOCK(txq);
2590 		return (0);
2591 	}
2592 	VTNET_TXQ_UNLOCK(txq);
2593 
2594 	if_printf(ifp, "watchdog timeout on queue %d\n", txq->vtntx_id);
2595 	return (1);
2596 }
2597 
2598 static void
2599 vtnet_accum_stats(struct vtnet_softc *sc, struct vtnet_rxq_stats *rxacc,
2600     struct vtnet_txq_stats *txacc)
2601 {
2602 
2603 	bzero(rxacc, sizeof(struct vtnet_rxq_stats));
2604 	bzero(txacc, sizeof(struct vtnet_txq_stats));
2605 
2606 	for (int i = 0; i < sc->vtnet_max_vq_pairs; i++) {
2607 		struct vtnet_rxq_stats *rxst;
2608 		struct vtnet_txq_stats *txst;
2609 
2610 		rxst = &sc->vtnet_rxqs[i].vtnrx_stats;
2611 		rxacc->vrxs_ipackets += rxst->vrxs_ipackets;
2612 		rxacc->vrxs_ibytes += rxst->vrxs_ibytes;
2613 		rxacc->vrxs_iqdrops += rxst->vrxs_iqdrops;
2614 		rxacc->vrxs_csum += rxst->vrxs_csum;
2615 		rxacc->vrxs_csum_failed += rxst->vrxs_csum_failed;
2616 		rxacc->vrxs_rescheduled += rxst->vrxs_rescheduled;
2617 
2618 		txst = &sc->vtnet_txqs[i].vtntx_stats;
2619 		txacc->vtxs_opackets += txst->vtxs_opackets;
2620 		txacc->vtxs_obytes += txst->vtxs_obytes;
2621 		txacc->vtxs_csum += txst->vtxs_csum;
2622 		txacc->vtxs_tso += txst->vtxs_tso;
2623 		txacc->vtxs_rescheduled += txst->vtxs_rescheduled;
2624 	}
2625 }
2626 
2627 static uint64_t
2628 vtnet_get_counter(if_t ifp, ift_counter cnt)
2629 {
2630 	struct vtnet_softc *sc;
2631 	struct vtnet_rxq_stats rxaccum;
2632 	struct vtnet_txq_stats txaccum;
2633 
2634 	sc = if_getsoftc(ifp);
2635 	vtnet_accum_stats(sc, &rxaccum, &txaccum);
2636 
2637 	switch (cnt) {
2638 	case IFCOUNTER_IPACKETS:
2639 		return (rxaccum.vrxs_ipackets);
2640 	case IFCOUNTER_IQDROPS:
2641 		return (rxaccum.vrxs_iqdrops);
2642 	case IFCOUNTER_IERRORS:
2643 		return (rxaccum.vrxs_ierrors);
2644 	case IFCOUNTER_OPACKETS:
2645 		return (txaccum.vtxs_opackets);
2646 #ifndef VTNET_LEGACY_TX
2647 	case IFCOUNTER_OBYTES:
2648 		return (txaccum.vtxs_obytes);
2649 	case IFCOUNTER_OMCASTS:
2650 		return (txaccum.vtxs_omcasts);
2651 #endif
2652 	default:
2653 		return (if_get_counter_default(ifp, cnt));
2654 	}
2655 }
2656 
2657 static void
2658 vtnet_tick(void *xsc)
2659 {
2660 	struct vtnet_softc *sc;
2661 	struct ifnet *ifp;
2662 	int i, timedout;
2663 
2664 	sc = xsc;
2665 	ifp = sc->vtnet_ifp;
2666 	timedout = 0;
2667 
2668 	VTNET_CORE_LOCK_ASSERT(sc);
2669 
2670 	for (i = 0; i < sc->vtnet_act_vq_pairs; i++)
2671 		timedout |= vtnet_watchdog(&sc->vtnet_txqs[i]);
2672 
2673 	if (timedout != 0) {
2674 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
2675 		vtnet_init_locked(sc);
2676 	} else
2677 		callout_schedule(&sc->vtnet_tick_ch, hz);
2678 }
2679 
2680 static void
2681 vtnet_start_taskqueues(struct vtnet_softc *sc)
2682 {
2683 	device_t dev;
2684 	struct vtnet_rxq *rxq;
2685 	struct vtnet_txq *txq;
2686 	int i, error;
2687 
2688 	dev = sc->vtnet_dev;
2689 
2690 	/*
2691 	 * Errors here are very difficult to recover from - we cannot
2692 	 * easily fail because, if this is during boot, we will hang
2693 	 * when freeing any successfully started taskqueues because
2694 	 * the scheduler isn't up yet.
2695 	 *
2696 	 * Most drivers just ignore the return value - it only fails
2697 	 * with ENOMEM so an error is not likely.
2698 	 */
2699 	for (i = 0; i < sc->vtnet_max_vq_pairs; i++) {
2700 		rxq = &sc->vtnet_rxqs[i];
2701 		error = taskqueue_start_threads(&rxq->vtnrx_tq, 1, PI_NET,
2702 		    "%s rxq %d", device_get_nameunit(dev), rxq->vtnrx_id);
2703 		if (error) {
2704 			device_printf(dev, "failed to start rx taskq %d\n",
2705 			    rxq->vtnrx_id);
2706 		}
2707 
2708 		txq = &sc->vtnet_txqs[i];
2709 		error = taskqueue_start_threads(&txq->vtntx_tq, 1, PI_NET,
2710 		    "%s txq %d", device_get_nameunit(dev), txq->vtntx_id);
2711 		if (error) {
2712 			device_printf(dev, "failed to start tx taskq %d\n",
2713 			    txq->vtntx_id);
2714 		}
2715 	}
2716 }
2717 
2718 static void
2719 vtnet_free_taskqueues(struct vtnet_softc *sc)
2720 {
2721 	struct vtnet_rxq *rxq;
2722 	struct vtnet_txq *txq;
2723 	int i;
2724 
2725 	for (i = 0; i < sc->vtnet_max_vq_pairs; i++) {
2726 		rxq = &sc->vtnet_rxqs[i];
2727 		if (rxq->vtnrx_tq != NULL) {
2728 			taskqueue_free(rxq->vtnrx_tq);
2729 			rxq->vtnrx_vq = NULL;
2730 		}
2731 
2732 		txq = &sc->vtnet_txqs[i];
2733 		if (txq->vtntx_tq != NULL) {
2734 			taskqueue_free(txq->vtntx_tq);
2735 			txq->vtntx_tq = NULL;
2736 		}
2737 	}
2738 }
2739 
2740 static void
2741 vtnet_drain_taskqueues(struct vtnet_softc *sc)
2742 {
2743 	struct vtnet_rxq *rxq;
2744 	struct vtnet_txq *txq;
2745 	int i;
2746 
2747 	for (i = 0; i < sc->vtnet_max_vq_pairs; i++) {
2748 		rxq = &sc->vtnet_rxqs[i];
2749 		if (rxq->vtnrx_tq != NULL)
2750 			taskqueue_drain(rxq->vtnrx_tq, &rxq->vtnrx_intrtask);
2751 
2752 		txq = &sc->vtnet_txqs[i];
2753 		if (txq->vtntx_tq != NULL) {
2754 			taskqueue_drain(txq->vtntx_tq, &txq->vtntx_intrtask);
2755 #ifndef VTNET_LEGACY_TX
2756 			taskqueue_drain(txq->vtntx_tq, &txq->vtntx_defrtask);
2757 #endif
2758 		}
2759 	}
2760 }
2761 
2762 static void
2763 vtnet_drain_rxtx_queues(struct vtnet_softc *sc)
2764 {
2765 	struct vtnet_rxq *rxq;
2766 	struct vtnet_txq *txq;
2767 	int i;
2768 
2769 #ifdef DEV_NETMAP
2770 	if (nm_native_on(NA(sc->vtnet_ifp)))
2771 		return;
2772 #endif /* DEV_NETMAP */
2773 
2774 	for (i = 0; i < sc->vtnet_act_vq_pairs; i++) {
2775 		rxq = &sc->vtnet_rxqs[i];
2776 		vtnet_rxq_free_mbufs(rxq);
2777 
2778 		txq = &sc->vtnet_txqs[i];
2779 		vtnet_txq_free_mbufs(txq);
2780 	}
2781 }
2782 
2783 static void
2784 vtnet_stop_rendezvous(struct vtnet_softc *sc)
2785 {
2786 	struct vtnet_rxq *rxq;
2787 	struct vtnet_txq *txq;
2788 	int i;
2789 
2790 	/*
2791 	 * Lock and unlock the per-queue mutex so we known the stop
2792 	 * state is visible. Doing only the active queues should be
2793 	 * sufficient, but it does not cost much extra to do all the
2794 	 * queues. Note we hold the core mutex here too.
2795 	 */
2796 	for (i = 0; i < sc->vtnet_max_vq_pairs; i++) {
2797 		rxq = &sc->vtnet_rxqs[i];
2798 		VTNET_RXQ_LOCK(rxq);
2799 		VTNET_RXQ_UNLOCK(rxq);
2800 
2801 		txq = &sc->vtnet_txqs[i];
2802 		VTNET_TXQ_LOCK(txq);
2803 		VTNET_TXQ_UNLOCK(txq);
2804 	}
2805 }
2806 
2807 static void
2808 vtnet_stop(struct vtnet_softc *sc)
2809 {
2810 	device_t dev;
2811 	struct ifnet *ifp;
2812 
2813 	dev = sc->vtnet_dev;
2814 	ifp = sc->vtnet_ifp;
2815 
2816 	VTNET_CORE_LOCK_ASSERT(sc);
2817 
2818 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
2819 	sc->vtnet_link_active = 0;
2820 	callout_stop(&sc->vtnet_tick_ch);
2821 
2822 	/* Only advisory. */
2823 	vtnet_disable_interrupts(sc);
2824 
2825 	/*
2826 	 * Stop the host adapter. This resets it to the pre-initialized
2827 	 * state. It will not generate any interrupts until after it is
2828 	 * reinitialized.
2829 	 */
2830 	virtio_stop(dev);
2831 	vtnet_stop_rendezvous(sc);
2832 
2833 	/* Free any mbufs left in the virtqueues. */
2834 	vtnet_drain_rxtx_queues(sc);
2835 }
2836 
2837 static int
2838 vtnet_virtio_reinit(struct vtnet_softc *sc)
2839 {
2840 	device_t dev;
2841 	struct ifnet *ifp;
2842 	uint64_t features;
2843 	int mask, error;
2844 
2845 	dev = sc->vtnet_dev;
2846 	ifp = sc->vtnet_ifp;
2847 	features = sc->vtnet_features;
2848 
2849 	mask = 0;
2850 #if defined(INET)
2851 	mask |= IFCAP_RXCSUM;
2852 #endif
2853 #if defined (INET6)
2854 	mask |= IFCAP_RXCSUM_IPV6;
2855 #endif
2856 
2857 	/*
2858 	 * Re-negotiate with the host, removing any disabled receive
2859 	 * features. Transmit features are disabled only on our side
2860 	 * via if_capenable and if_hwassist.
2861 	 */
2862 
2863 	if (ifp->if_capabilities & mask) {
2864 		/*
2865 		 * We require both IPv4 and IPv6 offloading to be enabled
2866 		 * in order to negotiated it: VirtIO does not distinguish
2867 		 * between the two.
2868 		 */
2869 		if ((ifp->if_capenable & mask) != mask)
2870 			features &= ~VIRTIO_NET_F_GUEST_CSUM;
2871 	}
2872 
2873 	if (ifp->if_capabilities & IFCAP_LRO) {
2874 		if ((ifp->if_capenable & IFCAP_LRO) == 0)
2875 			features &= ~VTNET_LRO_FEATURES;
2876 	}
2877 
2878 	if (ifp->if_capabilities & IFCAP_VLAN_HWFILTER) {
2879 		if ((ifp->if_capenable & IFCAP_VLAN_HWFILTER) == 0)
2880 			features &= ~VIRTIO_NET_F_CTRL_VLAN;
2881 	}
2882 
2883 	error = virtio_reinit(dev, features);
2884 	if (error)
2885 		device_printf(dev, "virtio reinit error %d\n", error);
2886 
2887 	return (error);
2888 }
2889 
2890 static void
2891 vtnet_init_rx_filters(struct vtnet_softc *sc)
2892 {
2893 	struct ifnet *ifp;
2894 
2895 	ifp = sc->vtnet_ifp;
2896 
2897 	if (sc->vtnet_flags & VTNET_FLAG_CTRL_RX) {
2898 		/* Restore promiscuous and all-multicast modes. */
2899 		vtnet_rx_filter(sc);
2900 		/* Restore filtered MAC addresses. */
2901 		vtnet_rx_filter_mac(sc);
2902 	}
2903 
2904 	if (ifp->if_capenable & IFCAP_VLAN_HWFILTER)
2905 		vtnet_rx_filter_vlan(sc);
2906 }
2907 
2908 static int
2909 vtnet_init_rx_queues(struct vtnet_softc *sc)
2910 {
2911 	device_t dev;
2912 	struct vtnet_rxq *rxq;
2913 	int i, clsize, error;
2914 
2915 	dev = sc->vtnet_dev;
2916 
2917 	/*
2918 	 * Use the new cluster size if one has been set (via a MTU
2919 	 * change). Otherwise, use the standard 2K clusters.
2920 	 *
2921 	 * BMV: It might make sense to use page sized clusters as
2922 	 * the default (depending on the features negotiated).
2923 	 */
2924 	if (sc->vtnet_rx_new_clsize != 0) {
2925 		clsize = sc->vtnet_rx_new_clsize;
2926 		sc->vtnet_rx_new_clsize = 0;
2927 	} else
2928 		clsize = MCLBYTES;
2929 
2930 	sc->vtnet_rx_clsize = clsize;
2931 	sc->vtnet_rx_nmbufs = VTNET_NEEDED_RX_MBUFS(sc, clsize);
2932 
2933 	KASSERT(sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS ||
2934 	    sc->vtnet_rx_nmbufs < sc->vtnet_rx_nsegs,
2935 	    ("%s: too many rx mbufs %d for %d segments", __func__,
2936 	    sc->vtnet_rx_nmbufs, sc->vtnet_rx_nsegs));
2937 
2938 #ifdef DEV_NETMAP
2939 	if (vtnet_netmap_init_rx_buffers(sc))
2940 		return 0;
2941 #endif /* DEV_NETMAP */
2942 
2943 	for (i = 0; i < sc->vtnet_act_vq_pairs; i++) {
2944 		rxq = &sc->vtnet_rxqs[i];
2945 
2946 		/* Hold the lock to satisfy asserts. */
2947 		VTNET_RXQ_LOCK(rxq);
2948 		error = vtnet_rxq_populate(rxq);
2949 		VTNET_RXQ_UNLOCK(rxq);
2950 
2951 		if (error) {
2952 			device_printf(dev,
2953 			    "cannot allocate mbufs for Rx queue %d\n", i);
2954 			return (error);
2955 		}
2956 	}
2957 
2958 	return (0);
2959 }
2960 
2961 static int
2962 vtnet_init_tx_queues(struct vtnet_softc *sc)
2963 {
2964 	struct vtnet_txq *txq;
2965 	int i;
2966 
2967 	for (i = 0; i < sc->vtnet_act_vq_pairs; i++) {
2968 		txq = &sc->vtnet_txqs[i];
2969 		txq->vtntx_watchdog = 0;
2970 	}
2971 
2972 	return (0);
2973 }
2974 
2975 static int
2976 vtnet_init_rxtx_queues(struct vtnet_softc *sc)
2977 {
2978 	int error;
2979 
2980 	error = vtnet_init_rx_queues(sc);
2981 	if (error)
2982 		return (error);
2983 
2984 	error = vtnet_init_tx_queues(sc);
2985 	if (error)
2986 		return (error);
2987 
2988 	return (0);
2989 }
2990 
2991 static void
2992 vtnet_set_active_vq_pairs(struct vtnet_softc *sc)
2993 {
2994 	device_t dev;
2995 	int npairs;
2996 
2997 	dev = sc->vtnet_dev;
2998 
2999 	if ((sc->vtnet_flags & VTNET_FLAG_MULTIQ) == 0) {
3000 		sc->vtnet_act_vq_pairs = 1;
3001 		return;
3002 	}
3003 
3004 	npairs = sc->vtnet_requested_vq_pairs;
3005 
3006 	if (vtnet_ctrl_mq_cmd(sc, npairs) != 0) {
3007 		device_printf(dev,
3008 		    "cannot set active queue pairs to %d\n", npairs);
3009 		npairs = 1;
3010 	}
3011 
3012 	sc->vtnet_act_vq_pairs = npairs;
3013 }
3014 
3015 static int
3016 vtnet_reinit(struct vtnet_softc *sc)
3017 {
3018 	struct ifnet *ifp;
3019 	int error;
3020 
3021 	ifp = sc->vtnet_ifp;
3022 
3023 	/* Use the current MAC address. */
3024 	bcopy(IF_LLADDR(ifp), sc->vtnet_hwaddr, ETHER_ADDR_LEN);
3025 	vtnet_set_hwaddr(sc);
3026 
3027 	vtnet_set_active_vq_pairs(sc);
3028 
3029 	ifp->if_hwassist = 0;
3030 	if (ifp->if_capenable & IFCAP_TXCSUM)
3031 		ifp->if_hwassist |= VTNET_CSUM_OFFLOAD;
3032 	if (ifp->if_capenable & IFCAP_TXCSUM_IPV6)
3033 		ifp->if_hwassist |= VTNET_CSUM_OFFLOAD_IPV6;
3034 	if (ifp->if_capenable & IFCAP_TSO4)
3035 		ifp->if_hwassist |= CSUM_IP_TSO;
3036 	if (ifp->if_capenable & IFCAP_TSO6)
3037 		ifp->if_hwassist |= CSUM_IP6_TSO;
3038 
3039 	if (sc->vtnet_flags & VTNET_FLAG_CTRL_VQ)
3040 		vtnet_init_rx_filters(sc);
3041 
3042 	error = vtnet_init_rxtx_queues(sc);
3043 	if (error)
3044 		return (error);
3045 
3046 	vtnet_enable_interrupts(sc);
3047 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
3048 
3049 	return (0);
3050 }
3051 
3052 static void
3053 vtnet_init_locked(struct vtnet_softc *sc)
3054 {
3055 	device_t dev;
3056 	struct ifnet *ifp;
3057 
3058 	dev = sc->vtnet_dev;
3059 	ifp = sc->vtnet_ifp;
3060 
3061 	VTNET_CORE_LOCK_ASSERT(sc);
3062 
3063 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
3064 		return;
3065 
3066 	vtnet_stop(sc);
3067 
3068 	/* Reinitialize with the host. */
3069 	if (vtnet_virtio_reinit(sc) != 0)
3070 		goto fail;
3071 
3072 	if (vtnet_reinit(sc) != 0)
3073 		goto fail;
3074 
3075 	virtio_reinit_complete(dev);
3076 
3077 	vtnet_update_link_status(sc);
3078 	callout_reset(&sc->vtnet_tick_ch, hz, vtnet_tick, sc);
3079 
3080 	return;
3081 
3082 fail:
3083 	vtnet_stop(sc);
3084 }
3085 
3086 static void
3087 vtnet_init(void *xsc)
3088 {
3089 	struct vtnet_softc *sc;
3090 
3091 	sc = xsc;
3092 
3093 #ifdef DEV_NETMAP
3094 	if (!NA(sc->vtnet_ifp)) {
3095 		D("try to attach again");
3096 		vtnet_netmap_attach(sc);
3097 	}
3098 #endif /* DEV_NETMAP */
3099 
3100 	VTNET_CORE_LOCK(sc);
3101 	vtnet_init_locked(sc);
3102 	VTNET_CORE_UNLOCK(sc);
3103 }
3104 
3105 static void
3106 vtnet_free_ctrl_vq(struct vtnet_softc *sc)
3107 {
3108 	struct virtqueue *vq;
3109 
3110 	vq = sc->vtnet_ctrl_vq;
3111 
3112 	/*
3113 	 * The control virtqueue is only polled and therefore it should
3114 	 * already be empty.
3115 	 */
3116 	KASSERT(virtqueue_empty(vq),
3117 	    ("%s: ctrl vq %p not empty", __func__, vq));
3118 }
3119 
3120 static void
3121 vtnet_exec_ctrl_cmd(struct vtnet_softc *sc, void *cookie,
3122     struct sglist *sg, int readable, int writable)
3123 {
3124 	struct virtqueue *vq;
3125 
3126 	vq = sc->vtnet_ctrl_vq;
3127 
3128 	VTNET_CORE_LOCK_ASSERT(sc);
3129 	KASSERT(sc->vtnet_flags & VTNET_FLAG_CTRL_VQ,
3130 	    ("%s: CTRL_VQ feature not negotiated", __func__));
3131 
3132 	if (!virtqueue_empty(vq))
3133 		return;
3134 	if (virtqueue_enqueue(vq, cookie, sg, readable, writable) != 0)
3135 		return;
3136 
3137 	/*
3138 	 * Poll for the response, but the command is likely already
3139 	 * done when we return from the notify.
3140 	 */
3141 	virtqueue_notify(vq);
3142 	virtqueue_poll(vq, NULL);
3143 }
3144 
3145 static int
3146 vtnet_ctrl_mac_cmd(struct vtnet_softc *sc, uint8_t *hwaddr)
3147 {
3148 	struct virtio_net_ctrl_hdr hdr __aligned(2);
3149 	struct sglist_seg segs[3];
3150 	struct sglist sg;
3151 	uint8_t ack;
3152 	int error;
3153 
3154 	hdr.class = VIRTIO_NET_CTRL_MAC;
3155 	hdr.cmd = VIRTIO_NET_CTRL_MAC_ADDR_SET;
3156 	ack = VIRTIO_NET_ERR;
3157 
3158 	sglist_init(&sg, 3, segs);
3159 	error = 0;
3160 	error |= sglist_append(&sg, &hdr, sizeof(struct virtio_net_ctrl_hdr));
3161 	error |= sglist_append(&sg, hwaddr, ETHER_ADDR_LEN);
3162 	error |= sglist_append(&sg, &ack, sizeof(uint8_t));
3163 	KASSERT(error == 0 && sg.sg_nseg == 3,
3164 	    ("%s: error %d adding set MAC msg to sglist", __func__, error));
3165 
3166 	vtnet_exec_ctrl_cmd(sc, &ack, &sg, sg.sg_nseg - 1, 1);
3167 
3168 	return (ack == VIRTIO_NET_OK ? 0 : EIO);
3169 }
3170 
3171 static int
3172 vtnet_ctrl_mq_cmd(struct vtnet_softc *sc, uint16_t npairs)
3173 {
3174 	struct sglist_seg segs[3];
3175 	struct sglist sg;
3176 	struct {
3177 		struct virtio_net_ctrl_hdr hdr;
3178 		uint8_t pad1;
3179 		struct virtio_net_ctrl_mq mq;
3180 		uint8_t pad2;
3181 		uint8_t ack;
3182 	} s __aligned(2);
3183 	int error;
3184 
3185 	s.hdr.class = VIRTIO_NET_CTRL_MQ;
3186 	s.hdr.cmd = VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET;
3187 	s.mq.virtqueue_pairs = npairs;
3188 	s.ack = VIRTIO_NET_ERR;
3189 
3190 	sglist_init(&sg, 3, segs);
3191 	error = 0;
3192 	error |= sglist_append(&sg, &s.hdr, sizeof(struct virtio_net_ctrl_hdr));
3193 	error |= sglist_append(&sg, &s.mq, sizeof(struct virtio_net_ctrl_mq));
3194 	error |= sglist_append(&sg, &s.ack, sizeof(uint8_t));
3195 	KASSERT(error == 0 && sg.sg_nseg == 3,
3196 	    ("%s: error %d adding MQ message to sglist", __func__, error));
3197 
3198 	vtnet_exec_ctrl_cmd(sc, &s.ack, &sg, sg.sg_nseg - 1, 1);
3199 
3200 	return (s.ack == VIRTIO_NET_OK ? 0 : EIO);
3201 }
3202 
3203 static int
3204 vtnet_ctrl_rx_cmd(struct vtnet_softc *sc, int cmd, int on)
3205 {
3206 	struct sglist_seg segs[3];
3207 	struct sglist sg;
3208 	struct {
3209 		struct virtio_net_ctrl_hdr hdr;
3210 		uint8_t pad1;
3211 		uint8_t onoff;
3212 		uint8_t pad2;
3213 		uint8_t ack;
3214 	} s __aligned(2);
3215 	int error;
3216 
3217 	KASSERT(sc->vtnet_flags & VTNET_FLAG_CTRL_RX,
3218 	    ("%s: CTRL_RX feature not negotiated", __func__));
3219 
3220 	s.hdr.class = VIRTIO_NET_CTRL_RX;
3221 	s.hdr.cmd = cmd;
3222 	s.onoff = !!on;
3223 	s.ack = VIRTIO_NET_ERR;
3224 
3225 	sglist_init(&sg, 3, segs);
3226 	error = 0;
3227 	error |= sglist_append(&sg, &s.hdr, sizeof(struct virtio_net_ctrl_hdr));
3228 	error |= sglist_append(&sg, &s.onoff, sizeof(uint8_t));
3229 	error |= sglist_append(&sg, &s.ack, sizeof(uint8_t));
3230 	KASSERT(error == 0 && sg.sg_nseg == 3,
3231 	    ("%s: error %d adding Rx message to sglist", __func__, error));
3232 
3233 	vtnet_exec_ctrl_cmd(sc, &s.ack, &sg, sg.sg_nseg - 1, 1);
3234 
3235 	return (s.ack == VIRTIO_NET_OK ? 0 : EIO);
3236 }
3237 
3238 static int
3239 vtnet_set_promisc(struct vtnet_softc *sc, int on)
3240 {
3241 
3242 	return (vtnet_ctrl_rx_cmd(sc, VIRTIO_NET_CTRL_RX_PROMISC, on));
3243 }
3244 
3245 static int
3246 vtnet_set_allmulti(struct vtnet_softc *sc, int on)
3247 {
3248 
3249 	return (vtnet_ctrl_rx_cmd(sc, VIRTIO_NET_CTRL_RX_ALLMULTI, on));
3250 }
3251 
3252 /*
3253  * The device defaults to promiscuous mode for backwards compatibility.
3254  * Turn it off at attach time if possible.
3255  */
3256 static void
3257 vtnet_attach_disable_promisc(struct vtnet_softc *sc)
3258 {
3259 	struct ifnet *ifp;
3260 
3261 	ifp = sc->vtnet_ifp;
3262 
3263 	VTNET_CORE_LOCK(sc);
3264 	if ((sc->vtnet_flags & VTNET_FLAG_CTRL_RX) == 0) {
3265 		ifp->if_flags |= IFF_PROMISC;
3266 	} else if (vtnet_set_promisc(sc, 0) != 0) {
3267 		ifp->if_flags |= IFF_PROMISC;
3268 		device_printf(sc->vtnet_dev,
3269 		    "cannot disable default promiscuous mode\n");
3270 	}
3271 	VTNET_CORE_UNLOCK(sc);
3272 }
3273 
3274 static void
3275 vtnet_rx_filter(struct vtnet_softc *sc)
3276 {
3277 	device_t dev;
3278 	struct ifnet *ifp;
3279 
3280 	dev = sc->vtnet_dev;
3281 	ifp = sc->vtnet_ifp;
3282 
3283 	VTNET_CORE_LOCK_ASSERT(sc);
3284 
3285 	if (vtnet_set_promisc(sc, ifp->if_flags & IFF_PROMISC) != 0)
3286 		device_printf(dev, "cannot %s promiscuous mode\n",
3287 		    ifp->if_flags & IFF_PROMISC ? "enable" : "disable");
3288 
3289 	if (vtnet_set_allmulti(sc, ifp->if_flags & IFF_ALLMULTI) != 0)
3290 		device_printf(dev, "cannot %s all-multicast mode\n",
3291 		    ifp->if_flags & IFF_ALLMULTI ? "enable" : "disable");
3292 }
3293 
3294 static void
3295 vtnet_rx_filter_mac(struct vtnet_softc *sc)
3296 {
3297 	struct virtio_net_ctrl_hdr hdr __aligned(2);
3298 	struct vtnet_mac_filter *filter;
3299 	struct sglist_seg segs[4];
3300 	struct sglist sg;
3301 	struct ifnet *ifp;
3302 	struct ifaddr *ifa;
3303 	struct ifmultiaddr *ifma;
3304 	int ucnt, mcnt, promisc, allmulti, error;
3305 	uint8_t ack;
3306 
3307 	ifp = sc->vtnet_ifp;
3308 	filter = sc->vtnet_mac_filter;
3309 	ucnt = 0;
3310 	mcnt = 0;
3311 	promisc = 0;
3312 	allmulti = 0;
3313 
3314 	VTNET_CORE_LOCK_ASSERT(sc);
3315 	KASSERT(sc->vtnet_flags & VTNET_FLAG_CTRL_RX,
3316 	    ("%s: CTRL_RX feature not negotiated", __func__));
3317 
3318 	/* Unicast MAC addresses: */
3319 	if_addr_rlock(ifp);
3320 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
3321 		if (ifa->ifa_addr->sa_family != AF_LINK)
3322 			continue;
3323 		else if (memcmp(LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
3324 		    sc->vtnet_hwaddr, ETHER_ADDR_LEN) == 0)
3325 			continue;
3326 		else if (ucnt == VTNET_MAX_MAC_ENTRIES) {
3327 			promisc = 1;
3328 			break;
3329 		}
3330 
3331 		bcopy(LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
3332 		    &filter->vmf_unicast.macs[ucnt], ETHER_ADDR_LEN);
3333 		ucnt++;
3334 	}
3335 	if_addr_runlock(ifp);
3336 
3337 	if (promisc != 0) {
3338 		filter->vmf_unicast.nentries = 0;
3339 		if_printf(ifp, "more than %d MAC addresses assigned, "
3340 		    "falling back to promiscuous mode\n",
3341 		    VTNET_MAX_MAC_ENTRIES);
3342 	} else
3343 		filter->vmf_unicast.nentries = ucnt;
3344 
3345 	/* Multicast MAC addresses: */
3346 	if_maddr_rlock(ifp);
3347 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3348 		if (ifma->ifma_addr->sa_family != AF_LINK)
3349 			continue;
3350 		else if (mcnt == VTNET_MAX_MAC_ENTRIES) {
3351 			allmulti = 1;
3352 			break;
3353 		}
3354 
3355 		bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
3356 		    &filter->vmf_multicast.macs[mcnt], ETHER_ADDR_LEN);
3357 		mcnt++;
3358 	}
3359 	if_maddr_runlock(ifp);
3360 
3361 	if (allmulti != 0) {
3362 		filter->vmf_multicast.nentries = 0;
3363 		if_printf(ifp, "more than %d multicast MAC addresses "
3364 		    "assigned, falling back to all-multicast mode\n",
3365 		    VTNET_MAX_MAC_ENTRIES);
3366 	} else
3367 		filter->vmf_multicast.nentries = mcnt;
3368 
3369 	if (promisc != 0 && allmulti != 0)
3370 		goto out;
3371 
3372 	hdr.class = VIRTIO_NET_CTRL_MAC;
3373 	hdr.cmd = VIRTIO_NET_CTRL_MAC_TABLE_SET;
3374 	ack = VIRTIO_NET_ERR;
3375 
3376 	sglist_init(&sg, 4, segs);
3377 	error = 0;
3378 	error |= sglist_append(&sg, &hdr, sizeof(struct virtio_net_ctrl_hdr));
3379 	error |= sglist_append(&sg, &filter->vmf_unicast,
3380 	    sizeof(uint32_t) + filter->vmf_unicast.nentries * ETHER_ADDR_LEN);
3381 	error |= sglist_append(&sg, &filter->vmf_multicast,
3382 	    sizeof(uint32_t) + filter->vmf_multicast.nentries * ETHER_ADDR_LEN);
3383 	error |= sglist_append(&sg, &ack, sizeof(uint8_t));
3384 	KASSERT(error == 0 && sg.sg_nseg == 4,
3385 	    ("%s: error %d adding MAC filter msg to sglist", __func__, error));
3386 
3387 	vtnet_exec_ctrl_cmd(sc, &ack, &sg, sg.sg_nseg - 1, 1);
3388 
3389 	if (ack != VIRTIO_NET_OK)
3390 		if_printf(ifp, "error setting host MAC filter table\n");
3391 
3392 out:
3393 	if (promisc != 0 && vtnet_set_promisc(sc, 1) != 0)
3394 		if_printf(ifp, "cannot enable promiscuous mode\n");
3395 	if (allmulti != 0 && vtnet_set_allmulti(sc, 1) != 0)
3396 		if_printf(ifp, "cannot enable all-multicast mode\n");
3397 }
3398 
3399 static int
3400 vtnet_exec_vlan_filter(struct vtnet_softc *sc, int add, uint16_t tag)
3401 {
3402 	struct sglist_seg segs[3];
3403 	struct sglist sg;
3404 	struct {
3405 		struct virtio_net_ctrl_hdr hdr;
3406 		uint8_t pad1;
3407 		uint16_t tag;
3408 		uint8_t pad2;
3409 		uint8_t ack;
3410 	} s __aligned(2);
3411 	int error;
3412 
3413 	s.hdr.class = VIRTIO_NET_CTRL_VLAN;
3414 	s.hdr.cmd = add ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL;
3415 	s.tag = tag;
3416 	s.ack = VIRTIO_NET_ERR;
3417 
3418 	sglist_init(&sg, 3, segs);
3419 	error = 0;
3420 	error |= sglist_append(&sg, &s.hdr, sizeof(struct virtio_net_ctrl_hdr));
3421 	error |= sglist_append(&sg, &s.tag, sizeof(uint16_t));
3422 	error |= sglist_append(&sg, &s.ack, sizeof(uint8_t));
3423 	KASSERT(error == 0 && sg.sg_nseg == 3,
3424 	    ("%s: error %d adding VLAN message to sglist", __func__, error));
3425 
3426 	vtnet_exec_ctrl_cmd(sc, &s.ack, &sg, sg.sg_nseg - 1, 1);
3427 
3428 	return (s.ack == VIRTIO_NET_OK ? 0 : EIO);
3429 }
3430 
3431 static void
3432 vtnet_rx_filter_vlan(struct vtnet_softc *sc)
3433 {
3434 	uint32_t w;
3435 	uint16_t tag;
3436 	int i, bit;
3437 
3438 	VTNET_CORE_LOCK_ASSERT(sc);
3439 	KASSERT(sc->vtnet_flags & VTNET_FLAG_VLAN_FILTER,
3440 	    ("%s: VLAN_FILTER feature not negotiated", __func__));
3441 
3442 	/* Enable the filter for each configured VLAN. */
3443 	for (i = 0; i < VTNET_VLAN_FILTER_NWORDS; i++) {
3444 		w = sc->vtnet_vlan_filter[i];
3445 
3446 		while ((bit = ffs(w) - 1) != -1) {
3447 			w &= ~(1 << bit);
3448 			tag = sizeof(w) * CHAR_BIT * i + bit;
3449 
3450 			if (vtnet_exec_vlan_filter(sc, 1, tag) != 0) {
3451 				device_printf(sc->vtnet_dev,
3452 				    "cannot enable VLAN %d filter\n", tag);
3453 			}
3454 		}
3455 	}
3456 }
3457 
3458 static void
3459 vtnet_update_vlan_filter(struct vtnet_softc *sc, int add, uint16_t tag)
3460 {
3461 	struct ifnet *ifp;
3462 	int idx, bit;
3463 
3464 	ifp = sc->vtnet_ifp;
3465 	idx = (tag >> 5) & 0x7F;
3466 	bit = tag & 0x1F;
3467 
3468 	if (tag == 0 || tag > 4095)
3469 		return;
3470 
3471 	VTNET_CORE_LOCK(sc);
3472 
3473 	if (add)
3474 		sc->vtnet_vlan_filter[idx] |= (1 << bit);
3475 	else
3476 		sc->vtnet_vlan_filter[idx] &= ~(1 << bit);
3477 
3478 	if (ifp->if_capenable & IFCAP_VLAN_HWFILTER &&
3479 	    ifp->if_drv_flags & IFF_DRV_RUNNING &&
3480 	    vtnet_exec_vlan_filter(sc, add, tag) != 0) {
3481 		device_printf(sc->vtnet_dev,
3482 		    "cannot %s VLAN %d %s the host filter table\n",
3483 		    add ? "add" : "remove", tag, add ? "to" : "from");
3484 	}
3485 
3486 	VTNET_CORE_UNLOCK(sc);
3487 }
3488 
3489 static void
3490 vtnet_register_vlan(void *arg, struct ifnet *ifp, uint16_t tag)
3491 {
3492 
3493 	if (ifp->if_softc != arg)
3494 		return;
3495 
3496 	vtnet_update_vlan_filter(arg, 1, tag);
3497 }
3498 
3499 static void
3500 vtnet_unregister_vlan(void *arg, struct ifnet *ifp, uint16_t tag)
3501 {
3502 
3503 	if (ifp->if_softc != arg)
3504 		return;
3505 
3506 	vtnet_update_vlan_filter(arg, 0, tag);
3507 }
3508 
3509 static int
3510 vtnet_is_link_up(struct vtnet_softc *sc)
3511 {
3512 	device_t dev;
3513 	struct ifnet *ifp;
3514 	uint16_t status;
3515 
3516 	dev = sc->vtnet_dev;
3517 	ifp = sc->vtnet_ifp;
3518 
3519 	if ((ifp->if_capabilities & IFCAP_LINKSTATE) == 0)
3520 		status = VIRTIO_NET_S_LINK_UP;
3521 	else
3522 		status = virtio_read_dev_config_2(dev,
3523 		    offsetof(struct virtio_net_config, status));
3524 
3525 	return ((status & VIRTIO_NET_S_LINK_UP) != 0);
3526 }
3527 
3528 static void
3529 vtnet_update_link_status(struct vtnet_softc *sc)
3530 {
3531 	struct ifnet *ifp;
3532 	int link;
3533 
3534 	ifp = sc->vtnet_ifp;
3535 
3536 	VTNET_CORE_LOCK_ASSERT(sc);
3537 	link = vtnet_is_link_up(sc);
3538 
3539 	/* Notify if the link status has changed. */
3540 	if (link != 0 && sc->vtnet_link_active == 0) {
3541 		sc->vtnet_link_active = 1;
3542 		if_link_state_change(ifp, LINK_STATE_UP);
3543 	} else if (link == 0 && sc->vtnet_link_active != 0) {
3544 		sc->vtnet_link_active = 0;
3545 		if_link_state_change(ifp, LINK_STATE_DOWN);
3546 	}
3547 }
3548 
3549 static int
3550 vtnet_ifmedia_upd(struct ifnet *ifp)
3551 {
3552 	struct vtnet_softc *sc;
3553 	struct ifmedia *ifm;
3554 
3555 	sc = ifp->if_softc;
3556 	ifm = &sc->vtnet_media;
3557 
3558 	if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER)
3559 		return (EINVAL);
3560 
3561 	return (0);
3562 }
3563 
3564 static void
3565 vtnet_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
3566 {
3567 	struct vtnet_softc *sc;
3568 
3569 	sc = ifp->if_softc;
3570 
3571 	ifmr->ifm_status = IFM_AVALID;
3572 	ifmr->ifm_active = IFM_ETHER;
3573 
3574 	VTNET_CORE_LOCK(sc);
3575 	if (vtnet_is_link_up(sc) != 0) {
3576 		ifmr->ifm_status |= IFM_ACTIVE;
3577 		ifmr->ifm_active |= VTNET_MEDIATYPE;
3578 	} else
3579 		ifmr->ifm_active |= IFM_NONE;
3580 	VTNET_CORE_UNLOCK(sc);
3581 }
3582 
3583 static void
3584 vtnet_set_hwaddr(struct vtnet_softc *sc)
3585 {
3586 	device_t dev;
3587 	int i;
3588 
3589 	dev = sc->vtnet_dev;
3590 
3591 	if (sc->vtnet_flags & VTNET_FLAG_CTRL_MAC) {
3592 		if (vtnet_ctrl_mac_cmd(sc, sc->vtnet_hwaddr) != 0)
3593 			device_printf(dev, "unable to set MAC address\n");
3594 	} else if (sc->vtnet_flags & VTNET_FLAG_MAC) {
3595 		for (i = 0; i < ETHER_ADDR_LEN; i++) {
3596 			virtio_write_dev_config_1(dev,
3597 			    offsetof(struct virtio_net_config, mac) + i,
3598 			    sc->vtnet_hwaddr[i]);
3599 		}
3600 	}
3601 }
3602 
3603 static void
3604 vtnet_get_hwaddr(struct vtnet_softc *sc)
3605 {
3606 	device_t dev;
3607 	int i;
3608 
3609 	dev = sc->vtnet_dev;
3610 
3611 	if ((sc->vtnet_flags & VTNET_FLAG_MAC) == 0) {
3612 		/*
3613 		 * Generate a random locally administered unicast address.
3614 		 *
3615 		 * It would be nice to generate the same MAC address across
3616 		 * reboots, but it seems all the hosts currently available
3617 		 * support the MAC feature, so this isn't too important.
3618 		 */
3619 		sc->vtnet_hwaddr[0] = 0xB2;
3620 		arc4rand(&sc->vtnet_hwaddr[1], ETHER_ADDR_LEN - 1, 0);
3621 		vtnet_set_hwaddr(sc);
3622 		return;
3623 	}
3624 
3625 	for (i = 0; i < ETHER_ADDR_LEN; i++) {
3626 		sc->vtnet_hwaddr[i] = virtio_read_dev_config_1(dev,
3627 		    offsetof(struct virtio_net_config, mac) + i);
3628 	}
3629 }
3630 
3631 static void
3632 vtnet_vlan_tag_remove(struct mbuf *m)
3633 {
3634 	struct ether_vlan_header *evh;
3635 
3636 	evh = mtod(m, struct ether_vlan_header *);
3637 	m->m_pkthdr.ether_vtag = ntohs(evh->evl_tag);
3638 	m->m_flags |= M_VLANTAG;
3639 
3640 	/* Strip the 802.1Q header. */
3641 	bcopy((char *) evh, (char *) evh + ETHER_VLAN_ENCAP_LEN,
3642 	    ETHER_HDR_LEN - ETHER_TYPE_LEN);
3643 	m_adj(m, ETHER_VLAN_ENCAP_LEN);
3644 }
3645 
3646 static void
3647 vtnet_set_rx_process_limit(struct vtnet_softc *sc)
3648 {
3649 	int limit;
3650 
3651 	limit = vtnet_tunable_int(sc, "rx_process_limit",
3652 	    vtnet_rx_process_limit);
3653 	if (limit < 0)
3654 		limit = INT_MAX;
3655 	sc->vtnet_rx_process_limit = limit;
3656 }
3657 
3658 static void
3659 vtnet_set_tx_intr_threshold(struct vtnet_softc *sc)
3660 {
3661 	int size, thresh;
3662 
3663 	size = virtqueue_size(sc->vtnet_txqs[0].vtntx_vq);
3664 
3665 	/*
3666 	 * The Tx interrupt is disabled until the queue free count falls
3667 	 * below our threshold. Completed frames are drained from the Tx
3668 	 * virtqueue before transmitting new frames and in the watchdog
3669 	 * callout, so the frequency of Tx interrupts is greatly reduced,
3670 	 * at the cost of not freeing mbufs as quickly as they otherwise
3671 	 * would be.
3672 	 *
3673 	 * N.B. We assume all the Tx queues are the same size.
3674 	 */
3675 	thresh = size / 4;
3676 
3677 	/*
3678 	 * Without indirect descriptors, leave enough room for the most
3679 	 * segments we handle.
3680 	 */
3681 	if ((sc->vtnet_flags & VTNET_FLAG_INDIRECT) == 0 &&
3682 	    thresh < sc->vtnet_tx_nsegs)
3683 		thresh = sc->vtnet_tx_nsegs;
3684 
3685 	sc->vtnet_tx_intr_thresh = thresh;
3686 }
3687 
3688 static void
3689 vtnet_setup_rxq_sysctl(struct sysctl_ctx_list *ctx,
3690     struct sysctl_oid_list *child, struct vtnet_rxq *rxq)
3691 {
3692 	struct sysctl_oid *node;
3693 	struct sysctl_oid_list *list;
3694 	struct vtnet_rxq_stats *stats;
3695 	char namebuf[16];
3696 
3697 	snprintf(namebuf, sizeof(namebuf), "rxq%d", rxq->vtnrx_id);
3698 	node = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, namebuf,
3699 	    CTLFLAG_RD, NULL, "Receive Queue");
3700 	list = SYSCTL_CHILDREN(node);
3701 
3702 	stats = &rxq->vtnrx_stats;
3703 
3704 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "ipackets", CTLFLAG_RD,
3705 	    &stats->vrxs_ipackets, "Receive packets");
3706 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "ibytes", CTLFLAG_RD,
3707 	    &stats->vrxs_ibytes, "Receive bytes");
3708 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "iqdrops", CTLFLAG_RD,
3709 	    &stats->vrxs_iqdrops, "Receive drops");
3710 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "ierrors", CTLFLAG_RD,
3711 	    &stats->vrxs_ierrors, "Receive errors");
3712 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "csum", CTLFLAG_RD,
3713 	    &stats->vrxs_csum, "Receive checksum offloaded");
3714 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "csum_failed", CTLFLAG_RD,
3715 	    &stats->vrxs_csum_failed, "Receive checksum offload failed");
3716 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "rescheduled", CTLFLAG_RD,
3717 	    &stats->vrxs_rescheduled,
3718 	    "Receive interrupt handler rescheduled");
3719 }
3720 
3721 static void
3722 vtnet_setup_txq_sysctl(struct sysctl_ctx_list *ctx,
3723     struct sysctl_oid_list *child, struct vtnet_txq *txq)
3724 {
3725 	struct sysctl_oid *node;
3726 	struct sysctl_oid_list *list;
3727 	struct vtnet_txq_stats *stats;
3728 	char namebuf[16];
3729 
3730 	snprintf(namebuf, sizeof(namebuf), "txq%d", txq->vtntx_id);
3731 	node = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, namebuf,
3732 	    CTLFLAG_RD, NULL, "Transmit Queue");
3733 	list = SYSCTL_CHILDREN(node);
3734 
3735 	stats = &txq->vtntx_stats;
3736 
3737 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "opackets", CTLFLAG_RD,
3738 	    &stats->vtxs_opackets, "Transmit packets");
3739 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "obytes", CTLFLAG_RD,
3740 	    &stats->vtxs_obytes, "Transmit bytes");
3741 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "omcasts", CTLFLAG_RD,
3742 	    &stats->vtxs_omcasts, "Transmit multicasts");
3743 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "csum", CTLFLAG_RD,
3744 	    &stats->vtxs_csum, "Transmit checksum offloaded");
3745 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "tso", CTLFLAG_RD,
3746 	    &stats->vtxs_tso, "Transmit segmentation offloaded");
3747 	SYSCTL_ADD_UQUAD(ctx, list, OID_AUTO, "rescheduled", CTLFLAG_RD,
3748 	    &stats->vtxs_rescheduled,
3749 	    "Transmit interrupt handler rescheduled");
3750 }
3751 
3752 static void
3753 vtnet_setup_queue_sysctl(struct vtnet_softc *sc)
3754 {
3755 	device_t dev;
3756 	struct sysctl_ctx_list *ctx;
3757 	struct sysctl_oid *tree;
3758 	struct sysctl_oid_list *child;
3759 	int i;
3760 
3761 	dev = sc->vtnet_dev;
3762 	ctx = device_get_sysctl_ctx(dev);
3763 	tree = device_get_sysctl_tree(dev);
3764 	child = SYSCTL_CHILDREN(tree);
3765 
3766 	for (i = 0; i < sc->vtnet_max_vq_pairs; i++) {
3767 		vtnet_setup_rxq_sysctl(ctx, child, &sc->vtnet_rxqs[i]);
3768 		vtnet_setup_txq_sysctl(ctx, child, &sc->vtnet_txqs[i]);
3769 	}
3770 }
3771 
3772 static void
3773 vtnet_setup_stat_sysctl(struct sysctl_ctx_list *ctx,
3774     struct sysctl_oid_list *child, struct vtnet_softc *sc)
3775 {
3776 	struct vtnet_statistics *stats;
3777 	struct vtnet_rxq_stats rxaccum;
3778 	struct vtnet_txq_stats txaccum;
3779 
3780 	vtnet_accum_stats(sc, &rxaccum, &txaccum);
3781 
3782 	stats = &sc->vtnet_stats;
3783 	stats->rx_csum_offloaded = rxaccum.vrxs_csum;
3784 	stats->rx_csum_failed = rxaccum.vrxs_csum_failed;
3785 	stats->rx_task_rescheduled = rxaccum.vrxs_rescheduled;
3786 	stats->tx_csum_offloaded = txaccum.vtxs_csum;
3787 	stats->tx_tso_offloaded = txaccum.vtxs_tso;
3788 	stats->tx_task_rescheduled = txaccum.vtxs_rescheduled;
3789 
3790 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "mbuf_alloc_failed",
3791 	    CTLFLAG_RD, &stats->mbuf_alloc_failed,
3792 	    "Mbuf cluster allocation failures");
3793 
3794 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_frame_too_large",
3795 	    CTLFLAG_RD, &stats->rx_frame_too_large,
3796 	    "Received frame larger than the mbuf chain");
3797 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_enq_replacement_failed",
3798 	    CTLFLAG_RD, &stats->rx_enq_replacement_failed,
3799 	    "Enqueuing the replacement receive mbuf failed");
3800 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_mergeable_failed",
3801 	    CTLFLAG_RD, &stats->rx_mergeable_failed,
3802 	    "Mergeable buffers receive failures");
3803 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_csum_bad_ethtype",
3804 	    CTLFLAG_RD, &stats->rx_csum_bad_ethtype,
3805 	    "Received checksum offloaded buffer with unsupported "
3806 	    "Ethernet type");
3807 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_csum_bad_ipproto",
3808 	    CTLFLAG_RD, &stats->rx_csum_bad_ipproto,
3809 	    "Received checksum offloaded buffer with incorrect IP protocol");
3810 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_csum_bad_offset",
3811 	    CTLFLAG_RD, &stats->rx_csum_bad_offset,
3812 	    "Received checksum offloaded buffer with incorrect offset");
3813 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_csum_bad_proto",
3814 	    CTLFLAG_RD, &stats->rx_csum_bad_proto,
3815 	    "Received checksum offloaded buffer with incorrect protocol");
3816 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_csum_failed",
3817 	    CTLFLAG_RD, &stats->rx_csum_failed,
3818 	    "Received buffer checksum offload failed");
3819 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_csum_offloaded",
3820 	    CTLFLAG_RD, &stats->rx_csum_offloaded,
3821 	    "Received buffer checksum offload succeeded");
3822 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_task_rescheduled",
3823 	    CTLFLAG_RD, &stats->rx_task_rescheduled,
3824 	    "Times the receive interrupt task rescheduled itself");
3825 
3826 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_csum_bad_ethtype",
3827 	    CTLFLAG_RD, &stats->tx_csum_bad_ethtype,
3828 	    "Aborted transmit of checksum offloaded buffer with unknown "
3829 	    "Ethernet type");
3830 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_tso_bad_ethtype",
3831 	    CTLFLAG_RD, &stats->tx_tso_bad_ethtype,
3832 	    "Aborted transmit of TSO buffer with unknown Ethernet type");
3833 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_tso_not_tcp",
3834 	    CTLFLAG_RD, &stats->tx_tso_not_tcp,
3835 	    "Aborted transmit of TSO buffer with non TCP protocol");
3836 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_defragged",
3837 	    CTLFLAG_RD, &stats->tx_defragged,
3838 	    "Transmit mbufs defragged");
3839 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_defrag_failed",
3840 	    CTLFLAG_RD, &stats->tx_defrag_failed,
3841 	    "Aborted transmit of buffer because defrag failed");
3842 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_csum_offloaded",
3843 	    CTLFLAG_RD, &stats->tx_csum_offloaded,
3844 	    "Offloaded checksum of transmitted buffer");
3845 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_tso_offloaded",
3846 	    CTLFLAG_RD, &stats->tx_tso_offloaded,
3847 	    "Segmentation offload of transmitted buffer");
3848 	SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_task_rescheduled",
3849 	    CTLFLAG_RD, &stats->tx_task_rescheduled,
3850 	    "Times the transmit interrupt task rescheduled itself");
3851 }
3852 
3853 static void
3854 vtnet_setup_sysctl(struct vtnet_softc *sc)
3855 {
3856 	device_t dev;
3857 	struct sysctl_ctx_list *ctx;
3858 	struct sysctl_oid *tree;
3859 	struct sysctl_oid_list *child;
3860 
3861 	dev = sc->vtnet_dev;
3862 	ctx = device_get_sysctl_ctx(dev);
3863 	tree = device_get_sysctl_tree(dev);
3864 	child = SYSCTL_CHILDREN(tree);
3865 
3866 	SYSCTL_ADD_INT(ctx, child, OID_AUTO, "max_vq_pairs",
3867 	    CTLFLAG_RD, &sc->vtnet_max_vq_pairs, 0,
3868 	    "Maximum number of supported virtqueue pairs");
3869 	SYSCTL_ADD_INT(ctx, child, OID_AUTO, "requested_vq_pairs",
3870 	    CTLFLAG_RD, &sc->vtnet_requested_vq_pairs, 0,
3871 	    "Requested number of virtqueue pairs");
3872 	SYSCTL_ADD_INT(ctx, child, OID_AUTO, "act_vq_pairs",
3873 	    CTLFLAG_RD, &sc->vtnet_act_vq_pairs, 0,
3874 	    "Number of active virtqueue pairs");
3875 
3876 	vtnet_setup_stat_sysctl(ctx, child, sc);
3877 }
3878 
3879 static int
3880 vtnet_rxq_enable_intr(struct vtnet_rxq *rxq)
3881 {
3882 
3883 	return (virtqueue_enable_intr(rxq->vtnrx_vq));
3884 }
3885 
3886 static void
3887 vtnet_rxq_disable_intr(struct vtnet_rxq *rxq)
3888 {
3889 
3890 	virtqueue_disable_intr(rxq->vtnrx_vq);
3891 }
3892 
3893 static int
3894 vtnet_txq_enable_intr(struct vtnet_txq *txq)
3895 {
3896 	struct virtqueue *vq;
3897 
3898 	vq = txq->vtntx_vq;
3899 
3900 	if (vtnet_txq_below_threshold(txq) != 0)
3901 		return (virtqueue_postpone_intr(vq, VQ_POSTPONE_LONG));
3902 
3903 	/*
3904 	 * The free count is above our threshold. Keep the Tx interrupt
3905 	 * disabled until the queue is fuller.
3906 	 */
3907 	return (0);
3908 }
3909 
3910 static void
3911 vtnet_txq_disable_intr(struct vtnet_txq *txq)
3912 {
3913 
3914 	virtqueue_disable_intr(txq->vtntx_vq);
3915 }
3916 
3917 static void
3918 vtnet_enable_rx_interrupts(struct vtnet_softc *sc)
3919 {
3920 	int i;
3921 
3922 	for (i = 0; i < sc->vtnet_act_vq_pairs; i++)
3923 		vtnet_rxq_enable_intr(&sc->vtnet_rxqs[i]);
3924 }
3925 
3926 static void
3927 vtnet_enable_tx_interrupts(struct vtnet_softc *sc)
3928 {
3929 	int i;
3930 
3931 	for (i = 0; i < sc->vtnet_act_vq_pairs; i++)
3932 		vtnet_txq_enable_intr(&sc->vtnet_txqs[i]);
3933 }
3934 
3935 static void
3936 vtnet_enable_interrupts(struct vtnet_softc *sc)
3937 {
3938 
3939 	vtnet_enable_rx_interrupts(sc);
3940 	vtnet_enable_tx_interrupts(sc);
3941 }
3942 
3943 static void
3944 vtnet_disable_rx_interrupts(struct vtnet_softc *sc)
3945 {
3946 	int i;
3947 
3948 	for (i = 0; i < sc->vtnet_act_vq_pairs; i++)
3949 		vtnet_rxq_disable_intr(&sc->vtnet_rxqs[i]);
3950 }
3951 
3952 static void
3953 vtnet_disable_tx_interrupts(struct vtnet_softc *sc)
3954 {
3955 	int i;
3956 
3957 	for (i = 0; i < sc->vtnet_act_vq_pairs; i++)
3958 		vtnet_txq_disable_intr(&sc->vtnet_txqs[i]);
3959 }
3960 
3961 static void
3962 vtnet_disable_interrupts(struct vtnet_softc *sc)
3963 {
3964 
3965 	vtnet_disable_rx_interrupts(sc);
3966 	vtnet_disable_tx_interrupts(sc);
3967 }
3968 
3969 static int
3970 vtnet_tunable_int(struct vtnet_softc *sc, const char *knob, int def)
3971 {
3972 	char path[64];
3973 
3974 	snprintf(path, sizeof(path),
3975 	    "hw.vtnet.%d.%s", device_get_unit(sc->vtnet_dev), knob);
3976 	TUNABLE_INT_FETCH(path, &def);
3977 
3978 	return (def);
3979 }
3980