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