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