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