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