xref: /qemu/net/vhost-vdpa.c (revision f8ed3648)
1 /*
2  * vhost-vdpa.c
3  *
4  * Copyright(c) 2017-2018 Intel Corporation.
5  * Copyright(c) 2020 Red Hat, Inc.
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2 or later.
8  * See the COPYING file in the top-level directory.
9  *
10  */
11 
12 #include "qemu/osdep.h"
13 #include "clients.h"
14 #include "hw/virtio/virtio-net.h"
15 #include "net/vhost_net.h"
16 #include "net/vhost-vdpa.h"
17 #include "hw/virtio/vhost-vdpa.h"
18 #include "qemu/config-file.h"
19 #include "qemu/error-report.h"
20 #include "qemu/log.h"
21 #include "qemu/memalign.h"
22 #include "qemu/option.h"
23 #include "qapi/error.h"
24 #include <linux/vhost.h>
25 #include <sys/ioctl.h>
26 #include <err.h>
27 #include "standard-headers/linux/virtio_net.h"
28 #include "monitor/monitor.h"
29 #include "migration/migration.h"
30 #include "migration/misc.h"
31 #include "hw/virtio/vhost.h"
32 
33 /* Todo:need to add the multiqueue support here */
34 typedef struct VhostVDPAState {
35     NetClientState nc;
36     struct vhost_vdpa vhost_vdpa;
37     Notifier migration_state;
38     VHostNetState *vhost_net;
39 
40     /* Control commands shadow buffers */
41     void *cvq_cmd_out_buffer;
42     virtio_net_ctrl_ack *status;
43 
44     /* The device always have SVQ enabled */
45     bool always_svq;
46 
47     /* The device can isolate CVQ in its own ASID */
48     bool cvq_isolated;
49 
50     bool started;
51 } VhostVDPAState;
52 
53 const int vdpa_feature_bits[] = {
54     VIRTIO_F_NOTIFY_ON_EMPTY,
55     VIRTIO_RING_F_INDIRECT_DESC,
56     VIRTIO_RING_F_EVENT_IDX,
57     VIRTIO_F_ANY_LAYOUT,
58     VIRTIO_F_VERSION_1,
59     VIRTIO_NET_F_CSUM,
60     VIRTIO_NET_F_GUEST_CSUM,
61     VIRTIO_NET_F_CTRL_GUEST_OFFLOADS,
62     VIRTIO_NET_F_GSO,
63     VIRTIO_NET_F_GUEST_TSO4,
64     VIRTIO_NET_F_GUEST_TSO6,
65     VIRTIO_NET_F_GUEST_ECN,
66     VIRTIO_NET_F_GUEST_UFO,
67     VIRTIO_NET_F_HOST_TSO4,
68     VIRTIO_NET_F_HOST_TSO6,
69     VIRTIO_NET_F_HOST_ECN,
70     VIRTIO_NET_F_HOST_UFO,
71     VIRTIO_NET_F_MRG_RXBUF,
72     VIRTIO_NET_F_MTU,
73     VIRTIO_NET_F_CTRL_RX,
74     VIRTIO_NET_F_CTRL_RX_EXTRA,
75     VIRTIO_NET_F_CTRL_VLAN,
76     VIRTIO_NET_F_CTRL_MAC_ADDR,
77     VIRTIO_NET_F_RSS,
78     VIRTIO_NET_F_MQ,
79     VIRTIO_NET_F_CTRL_VQ,
80     VIRTIO_F_IOMMU_PLATFORM,
81     VIRTIO_F_RING_PACKED,
82     VIRTIO_F_RING_RESET,
83     VIRTIO_NET_F_RSS,
84     VIRTIO_NET_F_HASH_REPORT,
85     VIRTIO_NET_F_STATUS,
86     VHOST_INVALID_FEATURE_BIT
87 };
88 
89 /** Supported device specific feature bits with SVQ */
90 static const uint64_t vdpa_svq_device_features =
91     BIT_ULL(VIRTIO_NET_F_CSUM) |
92     BIT_ULL(VIRTIO_NET_F_GUEST_CSUM) |
93     BIT_ULL(VIRTIO_NET_F_CTRL_GUEST_OFFLOADS) |
94     BIT_ULL(VIRTIO_NET_F_MTU) |
95     BIT_ULL(VIRTIO_NET_F_MAC) |
96     BIT_ULL(VIRTIO_NET_F_GUEST_TSO4) |
97     BIT_ULL(VIRTIO_NET_F_GUEST_TSO6) |
98     BIT_ULL(VIRTIO_NET_F_GUEST_ECN) |
99     BIT_ULL(VIRTIO_NET_F_GUEST_UFO) |
100     BIT_ULL(VIRTIO_NET_F_HOST_TSO4) |
101     BIT_ULL(VIRTIO_NET_F_HOST_TSO6) |
102     BIT_ULL(VIRTIO_NET_F_HOST_ECN) |
103     BIT_ULL(VIRTIO_NET_F_HOST_UFO) |
104     BIT_ULL(VIRTIO_NET_F_MRG_RXBUF) |
105     BIT_ULL(VIRTIO_NET_F_STATUS) |
106     BIT_ULL(VIRTIO_NET_F_CTRL_VQ) |
107     BIT_ULL(VIRTIO_NET_F_MQ) |
108     BIT_ULL(VIRTIO_F_ANY_LAYOUT) |
109     BIT_ULL(VIRTIO_NET_F_CTRL_MAC_ADDR) |
110     /* VHOST_F_LOG_ALL is exposed by SVQ */
111     BIT_ULL(VHOST_F_LOG_ALL) |
112     BIT_ULL(VIRTIO_NET_F_RSC_EXT) |
113     BIT_ULL(VIRTIO_NET_F_STANDBY) |
114     BIT_ULL(VIRTIO_NET_F_SPEED_DUPLEX);
115 
116 #define VHOST_VDPA_NET_CVQ_ASID 1
117 
118 VHostNetState *vhost_vdpa_get_vhost_net(NetClientState *nc)
119 {
120     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
121     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
122     return s->vhost_net;
123 }
124 
125 static size_t vhost_vdpa_net_cvq_cmd_len(void)
126 {
127     /*
128      * MAC_TABLE_SET is the ctrl command that produces the longer out buffer.
129      * In buffer is always 1 byte, so it should fit here
130      */
131     return sizeof(struct virtio_net_ctrl_hdr) +
132            2 * sizeof(struct virtio_net_ctrl_mac) +
133            MAC_TABLE_ENTRIES * ETH_ALEN;
134 }
135 
136 static size_t vhost_vdpa_net_cvq_cmd_page_len(void)
137 {
138     return ROUND_UP(vhost_vdpa_net_cvq_cmd_len(), qemu_real_host_page_size());
139 }
140 
141 static bool vhost_vdpa_net_valid_svq_features(uint64_t features, Error **errp)
142 {
143     uint64_t invalid_dev_features =
144         features & ~vdpa_svq_device_features &
145         /* Transport are all accepted at this point */
146         ~MAKE_64BIT_MASK(VIRTIO_TRANSPORT_F_START,
147                          VIRTIO_TRANSPORT_F_END - VIRTIO_TRANSPORT_F_START);
148 
149     if (invalid_dev_features) {
150         error_setg(errp, "vdpa svq does not work with features 0x%" PRIx64,
151                    invalid_dev_features);
152         return false;
153     }
154 
155     return vhost_svq_valid_features(features, errp);
156 }
157 
158 static int vhost_vdpa_net_check_device_id(struct vhost_net *net)
159 {
160     uint32_t device_id;
161     int ret;
162     struct vhost_dev *hdev;
163 
164     hdev = (struct vhost_dev *)&net->dev;
165     ret = hdev->vhost_ops->vhost_get_device_id(hdev, &device_id);
166     if (device_id != VIRTIO_ID_NET) {
167         return -ENOTSUP;
168     }
169     return ret;
170 }
171 
172 static int vhost_vdpa_add(NetClientState *ncs, void *be,
173                           int queue_pair_index, int nvqs)
174 {
175     VhostNetOptions options;
176     struct vhost_net *net = NULL;
177     VhostVDPAState *s;
178     int ret;
179 
180     options.backend_type = VHOST_BACKEND_TYPE_VDPA;
181     assert(ncs->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
182     s = DO_UPCAST(VhostVDPAState, nc, ncs);
183     options.net_backend = ncs;
184     options.opaque      = be;
185     options.busyloop_timeout = 0;
186     options.nvqs = nvqs;
187 
188     net = vhost_net_init(&options);
189     if (!net) {
190         error_report("failed to init vhost_net for queue");
191         goto err_init;
192     }
193     s->vhost_net = net;
194     ret = vhost_vdpa_net_check_device_id(net);
195     if (ret) {
196         goto err_check;
197     }
198     return 0;
199 err_check:
200     vhost_net_cleanup(net);
201     g_free(net);
202 err_init:
203     return -1;
204 }
205 
206 static void vhost_vdpa_cleanup(NetClientState *nc)
207 {
208     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
209 
210     munmap(s->cvq_cmd_out_buffer, vhost_vdpa_net_cvq_cmd_page_len());
211     munmap(s->status, vhost_vdpa_net_cvq_cmd_page_len());
212     if (s->vhost_net) {
213         vhost_net_cleanup(s->vhost_net);
214         g_free(s->vhost_net);
215         s->vhost_net = NULL;
216     }
217      if (s->vhost_vdpa.device_fd >= 0) {
218         qemu_close(s->vhost_vdpa.device_fd);
219         s->vhost_vdpa.device_fd = -1;
220     }
221 }
222 
223 static bool vhost_vdpa_has_vnet_hdr(NetClientState *nc)
224 {
225     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
226 
227     return true;
228 }
229 
230 static bool vhost_vdpa_has_ufo(NetClientState *nc)
231 {
232     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
233     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
234     uint64_t features = 0;
235     features |= (1ULL << VIRTIO_NET_F_HOST_UFO);
236     features = vhost_net_get_features(s->vhost_net, features);
237     return !!(features & (1ULL << VIRTIO_NET_F_HOST_UFO));
238 
239 }
240 
241 static bool vhost_vdpa_check_peer_type(NetClientState *nc, ObjectClass *oc,
242                                        Error **errp)
243 {
244     const char *driver = object_class_get_name(oc);
245 
246     if (!g_str_has_prefix(driver, "virtio-net-")) {
247         error_setg(errp, "vhost-vdpa requires frontend driver virtio-net-*");
248         return false;
249     }
250 
251     return true;
252 }
253 
254 /** Dummy receive in case qemu falls back to userland tap networking */
255 static ssize_t vhost_vdpa_receive(NetClientState *nc, const uint8_t *buf,
256                                   size_t size)
257 {
258     return size;
259 }
260 
261 /** From any vdpa net client, get the netclient of the first queue pair */
262 static VhostVDPAState *vhost_vdpa_net_first_nc_vdpa(VhostVDPAState *s)
263 {
264     NICState *nic = qemu_get_nic(s->nc.peer);
265     NetClientState *nc0 = qemu_get_peer(nic->ncs, 0);
266 
267     return DO_UPCAST(VhostVDPAState, nc, nc0);
268 }
269 
270 static void vhost_vdpa_net_log_global_enable(VhostVDPAState *s, bool enable)
271 {
272     struct vhost_vdpa *v = &s->vhost_vdpa;
273     VirtIONet *n;
274     VirtIODevice *vdev;
275     int data_queue_pairs, cvq, r;
276 
277     /* We are only called on the first data vqs and only if x-svq is not set */
278     if (s->vhost_vdpa.shadow_vqs_enabled == enable) {
279         return;
280     }
281 
282     vdev = v->dev->vdev;
283     n = VIRTIO_NET(vdev);
284     if (!n->vhost_started) {
285         return;
286     }
287 
288     data_queue_pairs = n->multiqueue ? n->max_queue_pairs : 1;
289     cvq = virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) ?
290                                   n->max_ncs - n->max_queue_pairs : 0;
291     /*
292      * TODO: vhost_net_stop does suspend, get_base and reset. We can be smarter
293      * in the future and resume the device if read-only operations between
294      * suspend and reset goes wrong.
295      */
296     vhost_net_stop(vdev, n->nic->ncs, data_queue_pairs, cvq);
297 
298     /* Start will check migration setup_or_active to configure or not SVQ */
299     r = vhost_net_start(vdev, n->nic->ncs, data_queue_pairs, cvq);
300     if (unlikely(r < 0)) {
301         error_report("unable to start vhost net: %s(%d)", g_strerror(-r), -r);
302     }
303 }
304 
305 static void vdpa_net_migration_state_notifier(Notifier *notifier, void *data)
306 {
307     MigrationState *migration = data;
308     VhostVDPAState *s = container_of(notifier, VhostVDPAState,
309                                      migration_state);
310 
311     if (migration_in_setup(migration)) {
312         vhost_vdpa_net_log_global_enable(s, true);
313     } else if (migration_has_failed(migration)) {
314         vhost_vdpa_net_log_global_enable(s, false);
315     }
316 }
317 
318 static void vhost_vdpa_net_data_start_first(VhostVDPAState *s)
319 {
320     struct vhost_vdpa *v = &s->vhost_vdpa;
321 
322     add_migration_state_change_notifier(&s->migration_state);
323     if (v->shadow_vqs_enabled) {
324         v->iova_tree = vhost_iova_tree_new(v->iova_range.first,
325                                            v->iova_range.last);
326     }
327 }
328 
329 static int vhost_vdpa_net_data_start(NetClientState *nc)
330 {
331     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
332     struct vhost_vdpa *v = &s->vhost_vdpa;
333 
334     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
335 
336     if (s->always_svq ||
337         migration_is_setup_or_active(migrate_get_current()->state)) {
338         v->shadow_vqs_enabled = true;
339         v->shadow_data = true;
340     } else {
341         v->shadow_vqs_enabled = false;
342         v->shadow_data = false;
343     }
344 
345     if (v->index == 0) {
346         vhost_vdpa_net_data_start_first(s);
347         return 0;
348     }
349 
350     if (v->shadow_vqs_enabled) {
351         VhostVDPAState *s0 = vhost_vdpa_net_first_nc_vdpa(s);
352         v->iova_tree = s0->vhost_vdpa.iova_tree;
353     }
354 
355     return 0;
356 }
357 
358 static void vhost_vdpa_net_client_stop(NetClientState *nc)
359 {
360     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
361     struct vhost_dev *dev;
362 
363     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
364 
365     if (s->vhost_vdpa.index == 0) {
366         remove_migration_state_change_notifier(&s->migration_state);
367     }
368 
369     dev = s->vhost_vdpa.dev;
370     if (dev->vq_index + dev->nvqs == dev->vq_index_end) {
371         g_clear_pointer(&s->vhost_vdpa.iova_tree, vhost_iova_tree_delete);
372     }
373 }
374 
375 static NetClientInfo net_vhost_vdpa_info = {
376         .type = NET_CLIENT_DRIVER_VHOST_VDPA,
377         .size = sizeof(VhostVDPAState),
378         .receive = vhost_vdpa_receive,
379         .start = vhost_vdpa_net_data_start,
380         .stop = vhost_vdpa_net_client_stop,
381         .cleanup = vhost_vdpa_cleanup,
382         .has_vnet_hdr = vhost_vdpa_has_vnet_hdr,
383         .has_ufo = vhost_vdpa_has_ufo,
384         .check_peer_type = vhost_vdpa_check_peer_type,
385 };
386 
387 static int64_t vhost_vdpa_get_vring_group(int device_fd, unsigned vq_index,
388                                           Error **errp)
389 {
390     struct vhost_vring_state state = {
391         .index = vq_index,
392     };
393     int r = ioctl(device_fd, VHOST_VDPA_GET_VRING_GROUP, &state);
394 
395     if (unlikely(r < 0)) {
396         r = -errno;
397         error_setg_errno(errp, errno, "Cannot get VQ %u group", vq_index);
398         return r;
399     }
400 
401     return state.num;
402 }
403 
404 static int vhost_vdpa_set_address_space_id(struct vhost_vdpa *v,
405                                            unsigned vq_group,
406                                            unsigned asid_num)
407 {
408     struct vhost_vring_state asid = {
409         .index = vq_group,
410         .num = asid_num,
411     };
412     int r;
413 
414     r = ioctl(v->device_fd, VHOST_VDPA_SET_GROUP_ASID, &asid);
415     if (unlikely(r < 0)) {
416         error_report("Can't set vq group %u asid %u, errno=%d (%s)",
417                      asid.index, asid.num, errno, g_strerror(errno));
418     }
419     return r;
420 }
421 
422 static void vhost_vdpa_cvq_unmap_buf(struct vhost_vdpa *v, void *addr)
423 {
424     VhostIOVATree *tree = v->iova_tree;
425     DMAMap needle = {
426         /*
427          * No need to specify size or to look for more translations since
428          * this contiguous chunk was allocated by us.
429          */
430         .translated_addr = (hwaddr)(uintptr_t)addr,
431     };
432     const DMAMap *map = vhost_iova_tree_find_iova(tree, &needle);
433     int r;
434 
435     if (unlikely(!map)) {
436         error_report("Cannot locate expected map");
437         return;
438     }
439 
440     r = vhost_vdpa_dma_unmap(v, v->address_space_id, map->iova, map->size + 1);
441     if (unlikely(r != 0)) {
442         error_report("Device cannot unmap: %s(%d)", g_strerror(r), r);
443     }
444 
445     vhost_iova_tree_remove(tree, *map);
446 }
447 
448 /** Map CVQ buffer. */
449 static int vhost_vdpa_cvq_map_buf(struct vhost_vdpa *v, void *buf, size_t size,
450                                   bool write)
451 {
452     DMAMap map = {};
453     int r;
454 
455     map.translated_addr = (hwaddr)(uintptr_t)buf;
456     map.size = size - 1;
457     map.perm = write ? IOMMU_RW : IOMMU_RO,
458     r = vhost_iova_tree_map_alloc(v->iova_tree, &map);
459     if (unlikely(r != IOVA_OK)) {
460         error_report("Cannot map injected element");
461         return r;
462     }
463 
464     r = vhost_vdpa_dma_map(v, v->address_space_id, map.iova,
465                            vhost_vdpa_net_cvq_cmd_page_len(), buf, !write);
466     if (unlikely(r < 0)) {
467         goto dma_map_err;
468     }
469 
470     return 0;
471 
472 dma_map_err:
473     vhost_iova_tree_remove(v->iova_tree, map);
474     return r;
475 }
476 
477 static int vhost_vdpa_net_cvq_start(NetClientState *nc)
478 {
479     VhostVDPAState *s, *s0;
480     struct vhost_vdpa *v;
481     int64_t cvq_group;
482     int r;
483     Error *err = NULL;
484 
485     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
486 
487     s = DO_UPCAST(VhostVDPAState, nc, nc);
488     v = &s->vhost_vdpa;
489 
490     s0 = vhost_vdpa_net_first_nc_vdpa(s);
491     v->shadow_data = s0->vhost_vdpa.shadow_vqs_enabled;
492     v->shadow_vqs_enabled = s->always_svq;
493     s->vhost_vdpa.address_space_id = VHOST_VDPA_GUEST_PA_ASID;
494 
495     if (s->vhost_vdpa.shadow_data) {
496         /* SVQ is already configured for all virtqueues */
497         goto out;
498     }
499 
500     /*
501      * If we early return in these cases SVQ will not be enabled. The migration
502      * will be blocked as long as vhost-vdpa backends will not offer _F_LOG.
503      */
504     if (!vhost_vdpa_net_valid_svq_features(v->dev->features, NULL)) {
505         return 0;
506     }
507 
508     if (!s->cvq_isolated) {
509         return 0;
510     }
511 
512     cvq_group = vhost_vdpa_get_vring_group(v->device_fd,
513                                            v->dev->vq_index_end - 1,
514                                            &err);
515     if (unlikely(cvq_group < 0)) {
516         error_report_err(err);
517         return cvq_group;
518     }
519 
520     r = vhost_vdpa_set_address_space_id(v, cvq_group, VHOST_VDPA_NET_CVQ_ASID);
521     if (unlikely(r < 0)) {
522         return r;
523     }
524 
525     v->shadow_vqs_enabled = true;
526     s->vhost_vdpa.address_space_id = VHOST_VDPA_NET_CVQ_ASID;
527 
528 out:
529     if (!s->vhost_vdpa.shadow_vqs_enabled) {
530         return 0;
531     }
532 
533     if (s0->vhost_vdpa.iova_tree) {
534         /*
535          * SVQ is already configured for all virtqueues.  Reuse IOVA tree for
536          * simplicity, whether CVQ shares ASID with guest or not, because:
537          * - Memory listener need access to guest's memory addresses allocated
538          *   in the IOVA tree.
539          * - There should be plenty of IOVA address space for both ASID not to
540          *   worry about collisions between them.  Guest's translations are
541          *   still validated with virtio virtqueue_pop so there is no risk for
542          *   the guest to access memory that it shouldn't.
543          *
544          * To allocate a iova tree per ASID is doable but it complicates the
545          * code and it is not worth it for the moment.
546          */
547         v->iova_tree = s0->vhost_vdpa.iova_tree;
548     } else {
549         v->iova_tree = vhost_iova_tree_new(v->iova_range.first,
550                                            v->iova_range.last);
551     }
552 
553     r = vhost_vdpa_cvq_map_buf(&s->vhost_vdpa, s->cvq_cmd_out_buffer,
554                                vhost_vdpa_net_cvq_cmd_page_len(), false);
555     if (unlikely(r < 0)) {
556         return r;
557     }
558 
559     r = vhost_vdpa_cvq_map_buf(&s->vhost_vdpa, s->status,
560                                vhost_vdpa_net_cvq_cmd_page_len(), true);
561     if (unlikely(r < 0)) {
562         vhost_vdpa_cvq_unmap_buf(&s->vhost_vdpa, s->cvq_cmd_out_buffer);
563     }
564 
565     return r;
566 }
567 
568 static void vhost_vdpa_net_cvq_stop(NetClientState *nc)
569 {
570     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
571 
572     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
573 
574     if (s->vhost_vdpa.shadow_vqs_enabled) {
575         vhost_vdpa_cvq_unmap_buf(&s->vhost_vdpa, s->cvq_cmd_out_buffer);
576         vhost_vdpa_cvq_unmap_buf(&s->vhost_vdpa, s->status);
577     }
578 
579     vhost_vdpa_net_client_stop(nc);
580 }
581 
582 static ssize_t vhost_vdpa_net_cvq_add(VhostVDPAState *s, size_t out_len,
583                                       size_t in_len)
584 {
585     /* Buffers for the device */
586     const struct iovec out = {
587         .iov_base = s->cvq_cmd_out_buffer,
588         .iov_len = out_len,
589     };
590     const struct iovec in = {
591         .iov_base = s->status,
592         .iov_len = sizeof(virtio_net_ctrl_ack),
593     };
594     VhostShadowVirtqueue *svq = g_ptr_array_index(s->vhost_vdpa.shadow_vqs, 0);
595     int r;
596 
597     r = vhost_svq_add(svq, &out, 1, &in, 1, NULL);
598     if (unlikely(r != 0)) {
599         if (unlikely(r == -ENOSPC)) {
600             qemu_log_mask(LOG_GUEST_ERROR, "%s: No space on device queue\n",
601                           __func__);
602         }
603         return r;
604     }
605 
606     /*
607      * We can poll here since we've had BQL from the time we sent the
608      * descriptor. Also, we need to take the answer before SVQ pulls by itself,
609      * when BQL is released
610      */
611     return vhost_svq_poll(svq);
612 }
613 
614 static ssize_t vhost_vdpa_net_load_cmd(VhostVDPAState *s, uint8_t class,
615                                        uint8_t cmd, const void *data,
616                                        size_t data_size)
617 {
618     const struct virtio_net_ctrl_hdr ctrl = {
619         .class = class,
620         .cmd = cmd,
621     };
622 
623     assert(data_size < vhost_vdpa_net_cvq_cmd_page_len() - sizeof(ctrl));
624 
625     memcpy(s->cvq_cmd_out_buffer, &ctrl, sizeof(ctrl));
626     memcpy(s->cvq_cmd_out_buffer + sizeof(ctrl), data, data_size);
627 
628     return vhost_vdpa_net_cvq_add(s, sizeof(ctrl) + data_size,
629                                   sizeof(virtio_net_ctrl_ack));
630 }
631 
632 static int vhost_vdpa_net_load_mac(VhostVDPAState *s, const VirtIONet *n)
633 {
634     if (virtio_vdev_has_feature(&n->parent_obj, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
635         ssize_t dev_written = vhost_vdpa_net_load_cmd(s, VIRTIO_NET_CTRL_MAC,
636                                                   VIRTIO_NET_CTRL_MAC_ADDR_SET,
637                                                   n->mac, sizeof(n->mac));
638         if (unlikely(dev_written < 0)) {
639             return dev_written;
640         }
641 
642         return *s->status != VIRTIO_NET_OK;
643     }
644 
645     return 0;
646 }
647 
648 static int vhost_vdpa_net_load_mq(VhostVDPAState *s,
649                                   const VirtIONet *n)
650 {
651     struct virtio_net_ctrl_mq mq;
652     ssize_t dev_written;
653 
654     if (!virtio_vdev_has_feature(&n->parent_obj, VIRTIO_NET_F_MQ)) {
655         return 0;
656     }
657 
658     mq.virtqueue_pairs = cpu_to_le16(n->curr_queue_pairs);
659     dev_written = vhost_vdpa_net_load_cmd(s, VIRTIO_NET_CTRL_MQ,
660                                           VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &mq,
661                                           sizeof(mq));
662     if (unlikely(dev_written < 0)) {
663         return dev_written;
664     }
665 
666     return *s->status != VIRTIO_NET_OK;
667 }
668 
669 static int vhost_vdpa_net_load_offloads(VhostVDPAState *s,
670                                         const VirtIONet *n)
671 {
672     uint64_t offloads;
673     ssize_t dev_written;
674 
675     if (!virtio_vdev_has_feature(&n->parent_obj,
676                                  VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)) {
677         return 0;
678     }
679 
680     if (n->curr_guest_offloads == virtio_net_supported_guest_offloads(n)) {
681         /*
682          * According to VirtIO standard, "Upon feature negotiation
683          * corresponding offload gets enabled to preserve
684          * backward compatibility.".
685          *
686          * Therefore, there is no need to send this CVQ command if the
687          * driver also enables all supported offloads, which aligns with
688          * the device's defaults.
689          *
690          * Note that the device's defaults can mismatch the driver's
691          * configuration only at live migration.
692          */
693         return 0;
694     }
695 
696     offloads = cpu_to_le64(n->curr_guest_offloads);
697     dev_written = vhost_vdpa_net_load_cmd(s, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
698                                           VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET,
699                                           &offloads, sizeof(offloads));
700     if (unlikely(dev_written < 0)) {
701         return dev_written;
702     }
703 
704     return *s->status != VIRTIO_NET_OK;
705 }
706 
707 static int vhost_vdpa_net_load(NetClientState *nc)
708 {
709     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
710     struct vhost_vdpa *v = &s->vhost_vdpa;
711     const VirtIONet *n;
712     int r;
713 
714     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
715 
716     if (!v->shadow_vqs_enabled) {
717         return 0;
718     }
719 
720     n = VIRTIO_NET(v->dev->vdev);
721     r = vhost_vdpa_net_load_mac(s, n);
722     if (unlikely(r < 0)) {
723         return r;
724     }
725     r = vhost_vdpa_net_load_mq(s, n);
726     if (unlikely(r)) {
727         return r;
728     }
729     r = vhost_vdpa_net_load_offloads(s, n);
730     if (unlikely(r)) {
731         return r;
732     }
733 
734     return 0;
735 }
736 
737 static NetClientInfo net_vhost_vdpa_cvq_info = {
738     .type = NET_CLIENT_DRIVER_VHOST_VDPA,
739     .size = sizeof(VhostVDPAState),
740     .receive = vhost_vdpa_receive,
741     .start = vhost_vdpa_net_cvq_start,
742     .load = vhost_vdpa_net_load,
743     .stop = vhost_vdpa_net_cvq_stop,
744     .cleanup = vhost_vdpa_cleanup,
745     .has_vnet_hdr = vhost_vdpa_has_vnet_hdr,
746     .has_ufo = vhost_vdpa_has_ufo,
747     .check_peer_type = vhost_vdpa_check_peer_type,
748 };
749 
750 /**
751  * Validate and copy control virtqueue commands.
752  *
753  * Following QEMU guidelines, we offer a copy of the buffers to the device to
754  * prevent TOCTOU bugs.
755  */
756 static int vhost_vdpa_net_handle_ctrl_avail(VhostShadowVirtqueue *svq,
757                                             VirtQueueElement *elem,
758                                             void *opaque)
759 {
760     VhostVDPAState *s = opaque;
761     size_t in_len;
762     virtio_net_ctrl_ack status = VIRTIO_NET_ERR;
763     /* Out buffer sent to both the vdpa device and the device model */
764     struct iovec out = {
765         .iov_base = s->cvq_cmd_out_buffer,
766     };
767     /* in buffer used for device model */
768     const struct iovec in = {
769         .iov_base = &status,
770         .iov_len = sizeof(status),
771     };
772     ssize_t dev_written = -EINVAL;
773 
774     out.iov_len = iov_to_buf(elem->out_sg, elem->out_num, 0,
775                              s->cvq_cmd_out_buffer,
776                              vhost_vdpa_net_cvq_cmd_len());
777     if (*(uint8_t *)s->cvq_cmd_out_buffer == VIRTIO_NET_CTRL_ANNOUNCE) {
778         /*
779          * Guest announce capability is emulated by qemu, so don't forward to
780          * the device.
781          */
782         dev_written = sizeof(status);
783         *s->status = VIRTIO_NET_OK;
784     } else {
785         dev_written = vhost_vdpa_net_cvq_add(s, out.iov_len, sizeof(status));
786         if (unlikely(dev_written < 0)) {
787             goto out;
788         }
789     }
790 
791     if (unlikely(dev_written < sizeof(status))) {
792         error_report("Insufficient written data (%zu)", dev_written);
793         goto out;
794     }
795 
796     if (*s->status != VIRTIO_NET_OK) {
797         goto out;
798     }
799 
800     status = VIRTIO_NET_ERR;
801     virtio_net_handle_ctrl_iov(svq->vdev, &in, 1, &out, 1);
802     if (status != VIRTIO_NET_OK) {
803         error_report("Bad CVQ processing in model");
804     }
805 
806 out:
807     in_len = iov_from_buf(elem->in_sg, elem->in_num, 0, &status,
808                           sizeof(status));
809     if (unlikely(in_len < sizeof(status))) {
810         error_report("Bad device CVQ written length");
811     }
812     vhost_svq_push_elem(svq, elem, MIN(in_len, sizeof(status)));
813     g_free(elem);
814     return dev_written < 0 ? dev_written : 0;
815 }
816 
817 static const VhostShadowVirtqueueOps vhost_vdpa_net_svq_ops = {
818     .avail_handler = vhost_vdpa_net_handle_ctrl_avail,
819 };
820 
821 /**
822  * Probe if CVQ is isolated
823  *
824  * @device_fd         The vdpa device fd
825  * @features          Features offered by the device.
826  * @cvq_index         The control vq pair index
827  *
828  * Returns <0 in case of failure, 0 if false and 1 if true.
829  */
830 static int vhost_vdpa_probe_cvq_isolation(int device_fd, uint64_t features,
831                                           int cvq_index, Error **errp)
832 {
833     uint64_t backend_features;
834     int64_t cvq_group;
835     uint8_t status = VIRTIO_CONFIG_S_ACKNOWLEDGE |
836                      VIRTIO_CONFIG_S_DRIVER |
837                      VIRTIO_CONFIG_S_FEATURES_OK;
838     int r;
839 
840     ERRP_GUARD();
841 
842     r = ioctl(device_fd, VHOST_GET_BACKEND_FEATURES, &backend_features);
843     if (unlikely(r < 0)) {
844         error_setg_errno(errp, errno, "Cannot get vdpa backend_features");
845         return r;
846     }
847 
848     if (!(backend_features & BIT_ULL(VHOST_BACKEND_F_IOTLB_ASID))) {
849         return 0;
850     }
851 
852     r = ioctl(device_fd, VHOST_SET_FEATURES, &features);
853     if (unlikely(r)) {
854         error_setg_errno(errp, errno, "Cannot set features");
855     }
856 
857     r = ioctl(device_fd, VHOST_VDPA_SET_STATUS, &status);
858     if (unlikely(r)) {
859         error_setg_errno(errp, -r, "Cannot set device features");
860         goto out;
861     }
862 
863     cvq_group = vhost_vdpa_get_vring_group(device_fd, cvq_index, errp);
864     if (unlikely(cvq_group < 0)) {
865         if (cvq_group != -ENOTSUP) {
866             r = cvq_group;
867             goto out;
868         }
869 
870         /*
871          * The kernel report VHOST_BACKEND_F_IOTLB_ASID if the vdpa frontend
872          * support ASID even if the parent driver does not.  The CVQ cannot be
873          * isolated in this case.
874          */
875         error_free(*errp);
876         *errp = NULL;
877         r = 0;
878         goto out;
879     }
880 
881     for (int i = 0; i < cvq_index; ++i) {
882         int64_t group = vhost_vdpa_get_vring_group(device_fd, i, errp);
883         if (unlikely(group < 0)) {
884             r = group;
885             goto out;
886         }
887 
888         if (group == (int64_t)cvq_group) {
889             r = 0;
890             goto out;
891         }
892     }
893 
894     r = 1;
895 
896 out:
897     status = 0;
898     ioctl(device_fd, VHOST_VDPA_SET_STATUS, &status);
899     return r;
900 }
901 
902 static NetClientState *net_vhost_vdpa_init(NetClientState *peer,
903                                        const char *device,
904                                        const char *name,
905                                        int vdpa_device_fd,
906                                        int queue_pair_index,
907                                        int nvqs,
908                                        bool is_datapath,
909                                        bool svq,
910                                        struct vhost_vdpa_iova_range iova_range,
911                                        uint64_t features,
912                                        Error **errp)
913 {
914     NetClientState *nc = NULL;
915     VhostVDPAState *s;
916     int ret = 0;
917     assert(name);
918     int cvq_isolated;
919 
920     if (is_datapath) {
921         nc = qemu_new_net_client(&net_vhost_vdpa_info, peer, device,
922                                  name);
923     } else {
924         cvq_isolated = vhost_vdpa_probe_cvq_isolation(vdpa_device_fd, features,
925                                                       queue_pair_index * 2,
926                                                       errp);
927         if (unlikely(cvq_isolated < 0)) {
928             return NULL;
929         }
930 
931         nc = qemu_new_net_control_client(&net_vhost_vdpa_cvq_info, peer,
932                                          device, name);
933     }
934     qemu_set_info_str(nc, TYPE_VHOST_VDPA);
935     s = DO_UPCAST(VhostVDPAState, nc, nc);
936 
937     s->vhost_vdpa.device_fd = vdpa_device_fd;
938     s->vhost_vdpa.index = queue_pair_index;
939     s->always_svq = svq;
940     s->migration_state.notify = vdpa_net_migration_state_notifier;
941     s->vhost_vdpa.shadow_vqs_enabled = svq;
942     s->vhost_vdpa.iova_range = iova_range;
943     s->vhost_vdpa.shadow_data = svq;
944     if (queue_pair_index == 0) {
945         vhost_vdpa_net_valid_svq_features(features,
946                                           &s->vhost_vdpa.migration_blocker);
947     } else if (!is_datapath) {
948         s->cvq_cmd_out_buffer = mmap(NULL, vhost_vdpa_net_cvq_cmd_page_len(),
949                                      PROT_READ | PROT_WRITE,
950                                      MAP_SHARED | MAP_ANONYMOUS, -1, 0);
951         s->status = mmap(NULL, vhost_vdpa_net_cvq_cmd_page_len(),
952                          PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS,
953                          -1, 0);
954 
955         s->vhost_vdpa.shadow_vq_ops = &vhost_vdpa_net_svq_ops;
956         s->vhost_vdpa.shadow_vq_ops_opaque = s;
957         s->cvq_isolated = cvq_isolated;
958 
959         /*
960          * TODO: We cannot migrate devices with CVQ and no x-svq enabled as
961          * there is no way to set the device state (MAC, MQ, etc) before
962          * starting the datapath.
963          *
964          * Migration blocker ownership now belongs to s->vhost_vdpa.
965          */
966         if (!svq) {
967             error_setg(&s->vhost_vdpa.migration_blocker,
968                        "net vdpa cannot migrate with CVQ feature");
969         }
970     }
971     ret = vhost_vdpa_add(nc, (void *)&s->vhost_vdpa, queue_pair_index, nvqs);
972     if (ret) {
973         qemu_del_net_client(nc);
974         return NULL;
975     }
976     return nc;
977 }
978 
979 static int vhost_vdpa_get_features(int fd, uint64_t *features, Error **errp)
980 {
981     int ret = ioctl(fd, VHOST_GET_FEATURES, features);
982     if (unlikely(ret < 0)) {
983         error_setg_errno(errp, errno,
984                          "Fail to query features from vhost-vDPA device");
985     }
986     return ret;
987 }
988 
989 static int vhost_vdpa_get_max_queue_pairs(int fd, uint64_t features,
990                                           int *has_cvq, Error **errp)
991 {
992     unsigned long config_size = offsetof(struct vhost_vdpa_config, buf);
993     g_autofree struct vhost_vdpa_config *config = NULL;
994     __virtio16 *max_queue_pairs;
995     int ret;
996 
997     if (features & (1 << VIRTIO_NET_F_CTRL_VQ)) {
998         *has_cvq = 1;
999     } else {
1000         *has_cvq = 0;
1001     }
1002 
1003     if (features & (1 << VIRTIO_NET_F_MQ)) {
1004         config = g_malloc0(config_size + sizeof(*max_queue_pairs));
1005         config->off = offsetof(struct virtio_net_config, max_virtqueue_pairs);
1006         config->len = sizeof(*max_queue_pairs);
1007 
1008         ret = ioctl(fd, VHOST_VDPA_GET_CONFIG, config);
1009         if (ret) {
1010             error_setg(errp, "Fail to get config from vhost-vDPA device");
1011             return -ret;
1012         }
1013 
1014         max_queue_pairs = (__virtio16 *)&config->buf;
1015 
1016         return lduw_le_p(max_queue_pairs);
1017     }
1018 
1019     return 1;
1020 }
1021 
1022 int net_init_vhost_vdpa(const Netdev *netdev, const char *name,
1023                         NetClientState *peer, Error **errp)
1024 {
1025     const NetdevVhostVDPAOptions *opts;
1026     uint64_t features;
1027     int vdpa_device_fd;
1028     g_autofree NetClientState **ncs = NULL;
1029     struct vhost_vdpa_iova_range iova_range;
1030     NetClientState *nc;
1031     int queue_pairs, r, i = 0, has_cvq = 0;
1032 
1033     assert(netdev->type == NET_CLIENT_DRIVER_VHOST_VDPA);
1034     opts = &netdev->u.vhost_vdpa;
1035     if (!opts->vhostdev && !opts->vhostfd) {
1036         error_setg(errp,
1037                    "vhost-vdpa: neither vhostdev= nor vhostfd= was specified");
1038         return -1;
1039     }
1040 
1041     if (opts->vhostdev && opts->vhostfd) {
1042         error_setg(errp,
1043                    "vhost-vdpa: vhostdev= and vhostfd= are mutually exclusive");
1044         return -1;
1045     }
1046 
1047     if (opts->vhostdev) {
1048         vdpa_device_fd = qemu_open(opts->vhostdev, O_RDWR, errp);
1049         if (vdpa_device_fd == -1) {
1050             return -errno;
1051         }
1052     } else {
1053         /* has_vhostfd */
1054         vdpa_device_fd = monitor_fd_param(monitor_cur(), opts->vhostfd, errp);
1055         if (vdpa_device_fd == -1) {
1056             error_prepend(errp, "vhost-vdpa: unable to parse vhostfd: ");
1057             return -1;
1058         }
1059     }
1060 
1061     r = vhost_vdpa_get_features(vdpa_device_fd, &features, errp);
1062     if (unlikely(r < 0)) {
1063         goto err;
1064     }
1065 
1066     queue_pairs = vhost_vdpa_get_max_queue_pairs(vdpa_device_fd, features,
1067                                                  &has_cvq, errp);
1068     if (queue_pairs < 0) {
1069         qemu_close(vdpa_device_fd);
1070         return queue_pairs;
1071     }
1072 
1073     r = vhost_vdpa_get_iova_range(vdpa_device_fd, &iova_range);
1074     if (unlikely(r < 0)) {
1075         error_setg(errp, "vhost-vdpa: get iova range failed: %s",
1076                    strerror(-r));
1077         goto err;
1078     }
1079 
1080     if (opts->x_svq && !vhost_vdpa_net_valid_svq_features(features, errp)) {
1081         goto err;
1082     }
1083 
1084     ncs = g_malloc0(sizeof(*ncs) * queue_pairs);
1085 
1086     for (i = 0; i < queue_pairs; i++) {
1087         ncs[i] = net_vhost_vdpa_init(peer, TYPE_VHOST_VDPA, name,
1088                                      vdpa_device_fd, i, 2, true, opts->x_svq,
1089                                      iova_range, features, errp);
1090         if (!ncs[i])
1091             goto err;
1092     }
1093 
1094     if (has_cvq) {
1095         nc = net_vhost_vdpa_init(peer, TYPE_VHOST_VDPA, name,
1096                                  vdpa_device_fd, i, 1, false,
1097                                  opts->x_svq, iova_range, features, errp);
1098         if (!nc)
1099             goto err;
1100     }
1101 
1102     return 0;
1103 
1104 err:
1105     if (i) {
1106         for (i--; i >= 0; i--) {
1107             qemu_del_net_client(ncs[i]);
1108         }
1109     }
1110 
1111     qemu_close(vdpa_device_fd);
1112 
1113     return -1;
1114 }
1115