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