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