xref: /qemu/net/vhost-vdpa.c (revision 6ff5da16000f908140723e164d33a0b51a6c4162)
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/misc.h"
30 #include "hw/virtio/vhost.h"
31 #include "trace.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     NotifierWithReturn 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 /*
54  * The array is sorted alphabetically in ascending order,
55  * with the exception of VHOST_INVALID_FEATURE_BIT,
56  * which should always be the last entry.
57  */
58 const int vdpa_feature_bits[] = {
59     VIRTIO_F_ANY_LAYOUT,
60     VIRTIO_F_IOMMU_PLATFORM,
61     VIRTIO_F_NOTIFY_ON_EMPTY,
62     VIRTIO_F_RING_PACKED,
63     VIRTIO_F_RING_RESET,
64     VIRTIO_F_VERSION_1,
65     VIRTIO_F_IN_ORDER,
66     VIRTIO_F_NOTIFICATION_DATA,
67     VIRTIO_NET_F_CSUM,
68     VIRTIO_NET_F_CTRL_GUEST_OFFLOADS,
69     VIRTIO_NET_F_CTRL_MAC_ADDR,
70     VIRTIO_NET_F_CTRL_RX,
71     VIRTIO_NET_F_CTRL_RX_EXTRA,
72     VIRTIO_NET_F_CTRL_VLAN,
73     VIRTIO_NET_F_CTRL_VQ,
74     VIRTIO_NET_F_GSO,
75     VIRTIO_NET_F_GUEST_CSUM,
76     VIRTIO_NET_F_GUEST_ECN,
77     VIRTIO_NET_F_GUEST_TSO4,
78     VIRTIO_NET_F_GUEST_TSO6,
79     VIRTIO_NET_F_GUEST_UFO,
80     VIRTIO_NET_F_GUEST_USO4,
81     VIRTIO_NET_F_GUEST_USO6,
82     VIRTIO_NET_F_HASH_REPORT,
83     VIRTIO_NET_F_HOST_ECN,
84     VIRTIO_NET_F_HOST_TSO4,
85     VIRTIO_NET_F_HOST_TSO6,
86     VIRTIO_NET_F_HOST_UFO,
87     VIRTIO_NET_F_HOST_USO,
88     VIRTIO_NET_F_MQ,
89     VIRTIO_NET_F_MRG_RXBUF,
90     VIRTIO_NET_F_MTU,
91     VIRTIO_NET_F_RSC_EXT,
92     VIRTIO_NET_F_RSS,
93     VIRTIO_NET_F_STATUS,
94     VIRTIO_RING_F_EVENT_IDX,
95     VIRTIO_RING_F_INDIRECT_DESC,
96 
97     /* VHOST_INVALID_FEATURE_BIT should always be the last entry */
98     VHOST_INVALID_FEATURE_BIT
99 };
100 
101 /** Supported device specific feature bits with SVQ */
102 static const uint64_t vdpa_svq_device_features =
103     BIT_ULL(VIRTIO_NET_F_CSUM) |
104     BIT_ULL(VIRTIO_NET_F_GUEST_CSUM) |
105     BIT_ULL(VIRTIO_NET_F_CTRL_GUEST_OFFLOADS) |
106     BIT_ULL(VIRTIO_NET_F_MTU) |
107     BIT_ULL(VIRTIO_NET_F_MAC) |
108     BIT_ULL(VIRTIO_NET_F_GUEST_TSO4) |
109     BIT_ULL(VIRTIO_NET_F_GUEST_TSO6) |
110     BIT_ULL(VIRTIO_NET_F_GUEST_ECN) |
111     BIT_ULL(VIRTIO_NET_F_GUEST_UFO) |
112     BIT_ULL(VIRTIO_NET_F_HOST_TSO4) |
113     BIT_ULL(VIRTIO_NET_F_HOST_TSO6) |
114     BIT_ULL(VIRTIO_NET_F_HOST_ECN) |
115     BIT_ULL(VIRTIO_NET_F_HOST_UFO) |
116     BIT_ULL(VIRTIO_NET_F_MRG_RXBUF) |
117     BIT_ULL(VIRTIO_NET_F_STATUS) |
118     BIT_ULL(VIRTIO_NET_F_CTRL_VQ) |
119     BIT_ULL(VIRTIO_NET_F_CTRL_RX) |
120     BIT_ULL(VIRTIO_NET_F_CTRL_VLAN) |
121     BIT_ULL(VIRTIO_NET_F_CTRL_RX_EXTRA) |
122     BIT_ULL(VIRTIO_NET_F_MQ) |
123     BIT_ULL(VIRTIO_F_ANY_LAYOUT) |
124     BIT_ULL(VIRTIO_NET_F_CTRL_MAC_ADDR) |
125     /* VHOST_F_LOG_ALL is exposed by SVQ */
126     BIT_ULL(VHOST_F_LOG_ALL) |
127     BIT_ULL(VIRTIO_NET_F_HASH_REPORT) |
128     BIT_ULL(VIRTIO_NET_F_RSS) |
129     BIT_ULL(VIRTIO_NET_F_RSC_EXT) |
130     BIT_ULL(VIRTIO_NET_F_STANDBY) |
131     BIT_ULL(VIRTIO_NET_F_SPEED_DUPLEX);
132 
133 #define VHOST_VDPA_NET_CVQ_ASID 1
134 
135 VHostNetState *vhost_vdpa_get_vhost_net(NetClientState *nc)
136 {
137     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
138     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
139     return s->vhost_net;
140 }
141 
142 static size_t vhost_vdpa_net_cvq_cmd_len(void)
143 {
144     /*
145      * MAC_TABLE_SET is the ctrl command that produces the longer out buffer.
146      * In buffer is always 1 byte, so it should fit here
147      */
148     return sizeof(struct virtio_net_ctrl_hdr) +
149            2 * sizeof(struct virtio_net_ctrl_mac) +
150            MAC_TABLE_ENTRIES * ETH_ALEN;
151 }
152 
153 static size_t vhost_vdpa_net_cvq_cmd_page_len(void)
154 {
155     return ROUND_UP(vhost_vdpa_net_cvq_cmd_len(), qemu_real_host_page_size());
156 }
157 
158 static bool vhost_vdpa_net_valid_svq_features(uint64_t features, Error **errp)
159 {
160     uint64_t invalid_dev_features =
161         features & ~vdpa_svq_device_features &
162         /* Transport are all accepted at this point */
163         ~MAKE_64BIT_MASK(VIRTIO_TRANSPORT_F_START,
164                          VIRTIO_TRANSPORT_F_END - VIRTIO_TRANSPORT_F_START);
165 
166     if (invalid_dev_features) {
167         error_setg(errp, "vdpa svq does not work with features 0x%" PRIx64,
168                    invalid_dev_features);
169         return false;
170     }
171 
172     return vhost_svq_valid_features(features, errp);
173 }
174 
175 static int vhost_vdpa_net_check_device_id(struct vhost_net *net)
176 {
177     uint32_t device_id;
178     int ret;
179     struct vhost_dev *hdev;
180 
181     hdev = (struct vhost_dev *)&net->dev;
182     ret = hdev->vhost_ops->vhost_get_device_id(hdev, &device_id);
183     if (device_id != VIRTIO_ID_NET) {
184         return -ENOTSUP;
185     }
186     return ret;
187 }
188 
189 static int vhost_vdpa_add(NetClientState *ncs, void *be,
190                           int queue_pair_index, int nvqs)
191 {
192     VhostNetOptions options;
193     struct vhost_net *net = NULL;
194     VhostVDPAState *s;
195     int ret;
196 
197     options.backend_type = VHOST_BACKEND_TYPE_VDPA;
198     assert(ncs->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
199     s = DO_UPCAST(VhostVDPAState, nc, ncs);
200     options.net_backend = ncs;
201     options.opaque      = be;
202     options.busyloop_timeout = 0;
203     options.nvqs = nvqs;
204 
205     net = vhost_net_init(&options);
206     if (!net) {
207         error_report("failed to init vhost_net for queue");
208         goto err_init;
209     }
210     s->vhost_net = net;
211     ret = vhost_vdpa_net_check_device_id(net);
212     if (ret) {
213         goto err_check;
214     }
215     return 0;
216 err_check:
217     vhost_net_cleanup(net);
218     g_free(net);
219 err_init:
220     return -1;
221 }
222 
223 static void vhost_vdpa_cleanup(NetClientState *nc)
224 {
225     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
226 
227     /*
228      * If a peer NIC is attached, do not cleanup anything.
229      * Cleanup will happen as a part of qemu_cleanup() -> net_cleanup()
230      * when the guest is shutting down.
231      */
232     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
233         return;
234     }
235     munmap(s->cvq_cmd_out_buffer, vhost_vdpa_net_cvq_cmd_page_len());
236     munmap(s->status, vhost_vdpa_net_cvq_cmd_page_len());
237     if (s->vhost_net) {
238         vhost_net_cleanup(s->vhost_net);
239         g_free(s->vhost_net);
240         s->vhost_net = NULL;
241     }
242     if (s->vhost_vdpa.index != 0) {
243         return;
244     }
245     qemu_close(s->vhost_vdpa.shared->device_fd);
246     g_free(s->vhost_vdpa.shared);
247 }
248 
249 /** Dummy SetSteeringEBPF to support RSS for vhost-vdpa backend  */
250 static bool vhost_vdpa_set_steering_ebpf(NetClientState *nc, int prog_fd)
251 {
252     return true;
253 }
254 
255 static bool vhost_vdpa_has_vnet_hdr(NetClientState *nc)
256 {
257     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
258 
259     return true;
260 }
261 
262 static bool vhost_vdpa_has_ufo(NetClientState *nc)
263 {
264     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
265     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
266     uint64_t features = 0;
267     features |= (1ULL << VIRTIO_NET_F_HOST_UFO);
268     features = vhost_net_get_features(s->vhost_net, features);
269     return !!(features & (1ULL << VIRTIO_NET_F_HOST_UFO));
270 
271 }
272 
273 static bool vhost_vdpa_check_peer_type(NetClientState *nc, ObjectClass *oc,
274                                        Error **errp)
275 {
276     const char *driver = object_class_get_name(oc);
277 
278     if (!g_str_has_prefix(driver, "virtio-net-")) {
279         error_setg(errp, "vhost-vdpa requires frontend driver virtio-net-*");
280         return false;
281     }
282 
283     return true;
284 }
285 
286 /** Dummy receive in case qemu falls back to userland tap networking */
287 static ssize_t vhost_vdpa_receive(NetClientState *nc, const uint8_t *buf,
288                                   size_t size)
289 {
290     return size;
291 }
292 
293 
294 /** From any vdpa net client, get the netclient of the i-th queue pair */
295 static VhostVDPAState *vhost_vdpa_net_get_nc_vdpa(VhostVDPAState *s, int i)
296 {
297     NICState *nic = qemu_get_nic(s->nc.peer);
298     NetClientState *nc_i = qemu_get_peer(nic->ncs, i);
299 
300     return DO_UPCAST(VhostVDPAState, nc, nc_i);
301 }
302 
303 static VhostVDPAState *vhost_vdpa_net_first_nc_vdpa(VhostVDPAState *s)
304 {
305     return vhost_vdpa_net_get_nc_vdpa(s, 0);
306 }
307 
308 static void vhost_vdpa_net_log_global_enable(VhostVDPAState *s, bool enable)
309 {
310     struct vhost_vdpa *v = &s->vhost_vdpa;
311     VirtIONet *n;
312     VirtIODevice *vdev;
313     int data_queue_pairs, cvq, r;
314 
315     /* We are only called on the first data vqs and only if x-svq is not set */
316     if (s->vhost_vdpa.shadow_vqs_enabled == enable) {
317         return;
318     }
319 
320     vdev = v->dev->vdev;
321     n = VIRTIO_NET(vdev);
322     if (!n->vhost_started) {
323         return;
324     }
325 
326     data_queue_pairs = n->multiqueue ? n->max_queue_pairs : 1;
327     cvq = virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) ?
328                                   n->max_ncs - n->max_queue_pairs : 0;
329     v->shared->svq_switching = enable ?
330         SVQ_TSTATE_ENABLING : SVQ_TSTATE_DISABLING;
331     /*
332      * TODO: vhost_net_stop does suspend, get_base and reset. We can be smarter
333      * in the future and resume the device if read-only operations between
334      * suspend and reset goes wrong.
335      */
336     vhost_net_stop(vdev, n->nic->ncs, data_queue_pairs, cvq);
337 
338     /* Start will check migration setup_or_active to configure or not SVQ */
339     r = vhost_net_start(vdev, n->nic->ncs, data_queue_pairs, cvq);
340     if (unlikely(r < 0)) {
341         error_report("unable to start vhost net: %s(%d)", g_strerror(-r), -r);
342     }
343     v->shared->svq_switching = SVQ_TSTATE_DONE;
344 }
345 
346 static int vdpa_net_migration_state_notifier(NotifierWithReturn *notifier,
347                                              MigrationEvent *e, Error **errp)
348 {
349     VhostVDPAState *s = container_of(notifier, VhostVDPAState, migration_state);
350 
351     if (e->type == MIG_EVENT_PRECOPY_SETUP) {
352         vhost_vdpa_net_log_global_enable(s, true);
353     } else if (e->type == MIG_EVENT_PRECOPY_FAILED) {
354         vhost_vdpa_net_log_global_enable(s, false);
355     }
356     return 0;
357 }
358 
359 static void vhost_vdpa_net_data_start_first(VhostVDPAState *s)
360 {
361     struct vhost_vdpa *v = &s->vhost_vdpa;
362 
363     migration_add_notifier(&s->migration_state,
364                            vdpa_net_migration_state_notifier);
365     if (v->shadow_vqs_enabled) {
366         v->shared->iova_tree = vhost_iova_tree_new(v->shared->iova_range.first,
367                                                    v->shared->iova_range.last);
368     }
369 }
370 
371 static int vhost_vdpa_net_data_start(NetClientState *nc)
372 {
373     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
374     struct vhost_vdpa *v = &s->vhost_vdpa;
375 
376     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
377 
378     if (s->always_svq || migration_is_running()) {
379         v->shadow_vqs_enabled = true;
380     } else {
381         v->shadow_vqs_enabled = false;
382     }
383 
384     if (v->index == 0) {
385         v->shared->shadow_data = v->shadow_vqs_enabled;
386         vhost_vdpa_net_data_start_first(s);
387         return 0;
388     }
389 
390     return 0;
391 }
392 
393 static int vhost_vdpa_net_data_load(NetClientState *nc)
394 {
395     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
396     struct vhost_vdpa *v = &s->vhost_vdpa;
397     bool has_cvq = v->dev->vq_index_end % 2;
398 
399     if (has_cvq) {
400         return 0;
401     }
402 
403     for (int i = 0; i < v->dev->nvqs; ++i) {
404         int ret = vhost_vdpa_set_vring_ready(v, i + v->dev->vq_index);
405         if (ret < 0) {
406             return ret;
407         }
408     }
409     return 0;
410 }
411 
412 static void vhost_vdpa_net_client_stop(NetClientState *nc)
413 {
414     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
415     struct vhost_dev *dev;
416 
417     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
418 
419     if (s->vhost_vdpa.index == 0) {
420         migration_remove_notifier(&s->migration_state);
421     }
422 
423     dev = s->vhost_vdpa.dev;
424     if (dev->vq_index + dev->nvqs == dev->vq_index_end) {
425         g_clear_pointer(&s->vhost_vdpa.shared->iova_tree,
426                         vhost_iova_tree_delete);
427     }
428 }
429 
430 static NetClientInfo net_vhost_vdpa_info = {
431         .type = NET_CLIENT_DRIVER_VHOST_VDPA,
432         .size = sizeof(VhostVDPAState),
433         .receive = vhost_vdpa_receive,
434         .start = vhost_vdpa_net_data_start,
435         .load = vhost_vdpa_net_data_load,
436         .stop = vhost_vdpa_net_client_stop,
437         .cleanup = vhost_vdpa_cleanup,
438         .has_vnet_hdr = vhost_vdpa_has_vnet_hdr,
439         .has_ufo = vhost_vdpa_has_ufo,
440         .check_peer_type = vhost_vdpa_check_peer_type,
441         .set_steering_ebpf = vhost_vdpa_set_steering_ebpf,
442 };
443 
444 static int64_t vhost_vdpa_get_vring_group(int device_fd, unsigned vq_index,
445                                           Error **errp)
446 {
447     struct vhost_vring_state state = {
448         .index = vq_index,
449     };
450     int r = ioctl(device_fd, VHOST_VDPA_GET_VRING_GROUP, &state);
451 
452     if (unlikely(r < 0)) {
453         r = -errno;
454         error_setg_errno(errp, errno, "Cannot get VQ %u group", vq_index);
455         return r;
456     }
457 
458     return state.num;
459 }
460 
461 static int vhost_vdpa_set_address_space_id(struct vhost_vdpa *v,
462                                            unsigned vq_group,
463                                            unsigned asid_num)
464 {
465     struct vhost_vring_state asid = {
466         .index = vq_group,
467         .num = asid_num,
468     };
469     int r;
470 
471     trace_vhost_vdpa_set_address_space_id(v, vq_group, asid_num);
472 
473     r = ioctl(v->shared->device_fd, VHOST_VDPA_SET_GROUP_ASID, &asid);
474     if (unlikely(r < 0)) {
475         error_report("Can't set vq group %u asid %u, errno=%d (%s)",
476                      asid.index, asid.num, errno, g_strerror(errno));
477     }
478     return r;
479 }
480 
481 static void vhost_vdpa_cvq_unmap_buf(struct vhost_vdpa *v, void *addr)
482 {
483     VhostIOVATree *tree = v->shared->iova_tree;
484     DMAMap needle = {
485         /*
486          * No need to specify size or to look for more translations since
487          * this contiguous chunk was allocated by us.
488          */
489         .translated_addr = (hwaddr)(uintptr_t)addr,
490     };
491     const DMAMap *map = vhost_iova_tree_find_iova(tree, &needle);
492     int r;
493 
494     if (unlikely(!map)) {
495         error_report("Cannot locate expected map");
496         return;
497     }
498 
499     r = vhost_vdpa_dma_unmap(v->shared, v->address_space_id, map->iova,
500                              map->size + 1);
501     if (unlikely(r != 0)) {
502         error_report("Device cannot unmap: %s(%d)", g_strerror(r), r);
503     }
504 
505     vhost_iova_tree_remove(tree, *map);
506 }
507 
508 /** Map CVQ buffer. */
509 static int vhost_vdpa_cvq_map_buf(struct vhost_vdpa *v, void *buf, size_t size,
510                                   bool write)
511 {
512     DMAMap map = {};
513     hwaddr taddr = (hwaddr)(uintptr_t)buf;
514     int r;
515 
516     map.size = size - 1;
517     map.perm = write ? IOMMU_RW : IOMMU_RO,
518     r = vhost_iova_tree_map_alloc(v->shared->iova_tree, &map, taddr);
519     if (unlikely(r != IOVA_OK)) {
520         error_report("Cannot map injected element");
521 
522         if (map.translated_addr == taddr) {
523             error_report("Insertion to IOVA->HVA tree failed");
524             /* Remove the mapping from the IOVA-only tree */
525             goto dma_map_err;
526         }
527         return r;
528     }
529 
530     r = vhost_vdpa_dma_map(v->shared, v->address_space_id, map.iova,
531                            vhost_vdpa_net_cvq_cmd_page_len(), buf, !write);
532     if (unlikely(r < 0)) {
533         goto dma_map_err;
534     }
535 
536     return 0;
537 
538 dma_map_err:
539     vhost_iova_tree_remove(v->shared->iova_tree, map);
540     return r;
541 }
542 
543 static int vhost_vdpa_net_cvq_start(NetClientState *nc)
544 {
545     VhostVDPAState *s, *s0;
546     struct vhost_vdpa *v;
547     int64_t cvq_group;
548     int r;
549     Error *err = NULL;
550 
551     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
552 
553     s = DO_UPCAST(VhostVDPAState, nc, nc);
554     v = &s->vhost_vdpa;
555 
556     s0 = vhost_vdpa_net_first_nc_vdpa(s);
557     v->shadow_vqs_enabled = s0->vhost_vdpa.shadow_vqs_enabled;
558     s->vhost_vdpa.address_space_id = VHOST_VDPA_GUEST_PA_ASID;
559 
560     if (v->shared->shadow_data) {
561         /* SVQ is already configured for all virtqueues */
562         goto out;
563     }
564 
565     /*
566      * If we early return in these cases SVQ will not be enabled. The migration
567      * will be blocked as long as vhost-vdpa backends will not offer _F_LOG.
568      */
569     if (!vhost_vdpa_net_valid_svq_features(v->dev->features, NULL)) {
570         return 0;
571     }
572 
573     if (!s->cvq_isolated) {
574         return 0;
575     }
576 
577     cvq_group = vhost_vdpa_get_vring_group(v->shared->device_fd,
578                                            v->dev->vq_index_end - 1,
579                                            &err);
580     if (unlikely(cvq_group < 0)) {
581         error_report_err(err);
582         return cvq_group;
583     }
584 
585     r = vhost_vdpa_set_address_space_id(v, cvq_group, VHOST_VDPA_NET_CVQ_ASID);
586     if (unlikely(r < 0)) {
587         return r;
588     }
589 
590     v->shadow_vqs_enabled = true;
591     s->vhost_vdpa.address_space_id = VHOST_VDPA_NET_CVQ_ASID;
592 
593 out:
594     if (!s->vhost_vdpa.shadow_vqs_enabled) {
595         return 0;
596     }
597 
598     /*
599      * If other vhost_vdpa already have an iova_tree, reuse it for simplicity,
600      * whether CVQ shares ASID with guest or not, because:
601      * - Memory listener need access to guest's memory addresses allocated in
602      *   the IOVA tree.
603      * - There should be plenty of IOVA address space for both ASID not to
604      *   worry about collisions between them.  Guest's translations are still
605      *   validated with virtio virtqueue_pop so there is no risk for the guest
606      *   to access memory that it shouldn't.
607      *
608      * To allocate a iova tree per ASID is doable but it complicates the code
609      * and it is not worth it for the moment.
610      */
611     if (!v->shared->iova_tree) {
612         v->shared->iova_tree = vhost_iova_tree_new(v->shared->iova_range.first,
613                                                    v->shared->iova_range.last);
614     }
615 
616     r = vhost_vdpa_cvq_map_buf(&s->vhost_vdpa, s->cvq_cmd_out_buffer,
617                                vhost_vdpa_net_cvq_cmd_page_len(), false);
618     if (unlikely(r < 0)) {
619         return r;
620     }
621 
622     r = vhost_vdpa_cvq_map_buf(&s->vhost_vdpa, s->status,
623                                vhost_vdpa_net_cvq_cmd_page_len(), true);
624     if (unlikely(r < 0)) {
625         vhost_vdpa_cvq_unmap_buf(&s->vhost_vdpa, s->cvq_cmd_out_buffer);
626     }
627 
628     return r;
629 }
630 
631 static void vhost_vdpa_net_cvq_stop(NetClientState *nc)
632 {
633     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
634 
635     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
636 
637     if (s->vhost_vdpa.shadow_vqs_enabled) {
638         vhost_vdpa_cvq_unmap_buf(&s->vhost_vdpa, s->cvq_cmd_out_buffer);
639         vhost_vdpa_cvq_unmap_buf(&s->vhost_vdpa, s->status);
640     }
641 
642     vhost_vdpa_net_client_stop(nc);
643 }
644 
645 static ssize_t vhost_vdpa_net_cvq_add(VhostVDPAState *s,
646                                     const struct iovec *out_sg, size_t out_num,
647                                     const struct iovec *in_sg, size_t in_num)
648 {
649     VhostShadowVirtqueue *svq = g_ptr_array_index(s->vhost_vdpa.shadow_vqs, 0);
650     int r;
651 
652     r = vhost_svq_add(svq, out_sg, out_num, NULL, in_sg, in_num, NULL, NULL);
653     if (unlikely(r != 0)) {
654         if (unlikely(r == -ENOSPC)) {
655             qemu_log_mask(LOG_GUEST_ERROR, "%s: No space on device queue\n",
656                           __func__);
657         }
658     }
659 
660     return r;
661 }
662 
663 /*
664  * Convenience wrapper to poll SVQ for multiple control commands.
665  *
666  * Caller should hold the BQL when invoking this function, and should take
667  * the answer before SVQ pulls by itself when BQL is released.
668  */
669 static ssize_t vhost_vdpa_net_svq_poll(VhostVDPAState *s, size_t cmds_in_flight)
670 {
671     VhostShadowVirtqueue *svq = g_ptr_array_index(s->vhost_vdpa.shadow_vqs, 0);
672     return vhost_svq_poll(svq, cmds_in_flight);
673 }
674 
675 static void vhost_vdpa_net_load_cursor_reset(VhostVDPAState *s,
676                                              struct iovec *out_cursor,
677                                              struct iovec *in_cursor)
678 {
679     /* reset the cursor of the output buffer for the device */
680     out_cursor->iov_base = s->cvq_cmd_out_buffer;
681     out_cursor->iov_len = vhost_vdpa_net_cvq_cmd_page_len();
682 
683     /* reset the cursor of the in buffer for the device */
684     in_cursor->iov_base = s->status;
685     in_cursor->iov_len = vhost_vdpa_net_cvq_cmd_page_len();
686 }
687 
688 /*
689  * Poll SVQ for multiple pending control commands and check the device's ack.
690  *
691  * Caller should hold the BQL when invoking this function.
692  *
693  * @s: The VhostVDPAState
694  * @len: The length of the pending status shadow buffer
695  */
696 static ssize_t vhost_vdpa_net_svq_flush(VhostVDPAState *s, size_t len)
697 {
698     /* device uses a one-byte length ack for each control command */
699     ssize_t dev_written = vhost_vdpa_net_svq_poll(s, len);
700     if (unlikely(dev_written != len)) {
701         return -EIO;
702     }
703 
704     /* check the device's ack */
705     for (int i = 0; i < len; ++i) {
706         if (s->status[i] != VIRTIO_NET_OK) {
707             return -EIO;
708         }
709     }
710     return 0;
711 }
712 
713 static ssize_t vhost_vdpa_net_load_cmd(VhostVDPAState *s,
714                                        struct iovec *out_cursor,
715                                        struct iovec *in_cursor, uint8_t class,
716                                        uint8_t cmd, const struct iovec *data_sg,
717                                        size_t data_num)
718 {
719     const struct virtio_net_ctrl_hdr ctrl = {
720         .class = class,
721         .cmd = cmd,
722     };
723     size_t data_size = iov_size(data_sg, data_num), cmd_size;
724     struct iovec out, in;
725     ssize_t r;
726     unsigned dummy_cursor_iov_cnt;
727     VhostShadowVirtqueue *svq = g_ptr_array_index(s->vhost_vdpa.shadow_vqs, 0);
728 
729     assert(data_size < vhost_vdpa_net_cvq_cmd_page_len() - sizeof(ctrl));
730     cmd_size = sizeof(ctrl) + data_size;
731     trace_vhost_vdpa_net_load_cmd(s, class, cmd, data_num, data_size);
732     if (vhost_svq_available_slots(svq) < 2 ||
733         iov_size(out_cursor, 1) < cmd_size) {
734         /*
735          * It is time to flush all pending control commands if SVQ is full
736          * or control commands shadow buffers are full.
737          *
738          * We can poll here since we've had BQL from the time
739          * we sent the descriptor.
740          */
741         r = vhost_vdpa_net_svq_flush(s, in_cursor->iov_base -
742                                      (void *)s->status);
743         if (unlikely(r < 0)) {
744             return r;
745         }
746 
747         vhost_vdpa_net_load_cursor_reset(s, out_cursor, in_cursor);
748     }
749 
750     /* pack the CVQ command header */
751     iov_from_buf(out_cursor, 1, 0, &ctrl, sizeof(ctrl));
752     /* pack the CVQ command command-specific-data */
753     iov_to_buf(data_sg, data_num, 0,
754                out_cursor->iov_base + sizeof(ctrl), data_size);
755 
756     /* extract the required buffer from the cursor for output */
757     iov_copy(&out, 1, out_cursor, 1, 0, cmd_size);
758     /* extract the required buffer from the cursor for input */
759     iov_copy(&in, 1, in_cursor, 1, 0, sizeof(*s->status));
760 
761     r = vhost_vdpa_net_cvq_add(s, &out, 1, &in, 1);
762     if (unlikely(r < 0)) {
763         trace_vhost_vdpa_net_load_cmd_retval(s, class, cmd, r);
764         return r;
765     }
766 
767     /* iterate the cursors */
768     dummy_cursor_iov_cnt = 1;
769     iov_discard_front(&out_cursor, &dummy_cursor_iov_cnt, cmd_size);
770     dummy_cursor_iov_cnt = 1;
771     iov_discard_front(&in_cursor, &dummy_cursor_iov_cnt, sizeof(*s->status));
772 
773     return 0;
774 }
775 
776 static int vhost_vdpa_net_load_mac(VhostVDPAState *s, const VirtIONet *n,
777                                    struct iovec *out_cursor,
778                                    struct iovec *in_cursor)
779 {
780     if (virtio_vdev_has_feature(&n->parent_obj, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
781         const struct iovec data = {
782             .iov_base = (void *)n->mac,
783             .iov_len = sizeof(n->mac),
784         };
785         ssize_t r = vhost_vdpa_net_load_cmd(s, out_cursor, in_cursor,
786                                             VIRTIO_NET_CTRL_MAC,
787                                             VIRTIO_NET_CTRL_MAC_ADDR_SET,
788                                             &data, 1);
789         if (unlikely(r < 0)) {
790             return r;
791         }
792     }
793 
794     /*
795      * According to VirtIO standard, "The device MUST have an
796      * empty MAC filtering table on reset.".
797      *
798      * Therefore, there is no need to send this CVQ command if the
799      * driver also sets an empty MAC filter table, which aligns with
800      * the device's defaults.
801      *
802      * Note that the device's defaults can mismatch the driver's
803      * configuration only at live migration.
804      */
805     if (!virtio_vdev_has_feature(&n->parent_obj, VIRTIO_NET_F_CTRL_RX) ||
806         n->mac_table.in_use == 0) {
807         return 0;
808     }
809 
810     uint32_t uni_entries = n->mac_table.first_multi,
811              uni_macs_size = uni_entries * ETH_ALEN,
812              mul_entries = n->mac_table.in_use - uni_entries,
813              mul_macs_size = mul_entries * ETH_ALEN;
814     struct virtio_net_ctrl_mac uni = {
815         .entries = cpu_to_le32(uni_entries),
816     };
817     struct virtio_net_ctrl_mac mul = {
818         .entries = cpu_to_le32(mul_entries),
819     };
820     const struct iovec data[] = {
821         {
822             .iov_base = &uni,
823             .iov_len = sizeof(uni),
824         }, {
825             .iov_base = n->mac_table.macs,
826             .iov_len = uni_macs_size,
827         }, {
828             .iov_base = &mul,
829             .iov_len = sizeof(mul),
830         }, {
831             .iov_base = &n->mac_table.macs[uni_macs_size],
832             .iov_len = mul_macs_size,
833         },
834     };
835     ssize_t r = vhost_vdpa_net_load_cmd(s, out_cursor, in_cursor,
836                                         VIRTIO_NET_CTRL_MAC,
837                                         VIRTIO_NET_CTRL_MAC_TABLE_SET,
838                                         data, ARRAY_SIZE(data));
839     if (unlikely(r < 0)) {
840         return r;
841     }
842 
843     return 0;
844 }
845 
846 static int vhost_vdpa_net_load_rss(VhostVDPAState *s, const VirtIONet *n,
847                                    struct iovec *out_cursor,
848                                    struct iovec *in_cursor, bool do_rss)
849 {
850     struct virtio_net_rss_config cfg = {};
851     ssize_t r;
852     g_autofree uint16_t *table = NULL;
853 
854     /*
855      * According to VirtIO standard, "Initially the device has all hash
856      * types disabled and reports only VIRTIO_NET_HASH_REPORT_NONE.".
857      *
858      * Therefore, there is no need to send this CVQ command if the
859      * driver disables the all hash types, which aligns with
860      * the device's defaults.
861      *
862      * Note that the device's defaults can mismatch the driver's
863      * configuration only at live migration.
864      */
865     if (!n->rss_data.enabled ||
866         n->rss_data.hash_types == VIRTIO_NET_HASH_REPORT_NONE) {
867         return 0;
868     }
869 
870     table = g_malloc_n(n->rss_data.indirections_len,
871                        sizeof(n->rss_data.indirections_table[0]));
872     cfg.hash_types = cpu_to_le32(n->rss_data.hash_types);
873 
874     if (do_rss) {
875         /*
876          * According to VirtIO standard, "Number of entries in indirection_table
877          * is (indirection_table_mask + 1)".
878          */
879         cfg.indirection_table_mask = cpu_to_le16(n->rss_data.indirections_len -
880                                                  1);
881         cfg.unclassified_queue = cpu_to_le16(n->rss_data.default_queue);
882         for (int i = 0; i < n->rss_data.indirections_len; ++i) {
883             table[i] = cpu_to_le16(n->rss_data.indirections_table[i]);
884         }
885         cfg.max_tx_vq = cpu_to_le16(n->curr_queue_pairs);
886     } else {
887         /*
888          * According to VirtIO standard, "Field reserved MUST contain zeroes.
889          * It is defined to make the structure to match the layout of
890          * virtio_net_rss_config structure, defined in 5.1.6.5.7.".
891          *
892          * Therefore, we need to zero the fields in
893          * struct virtio_net_rss_config, which corresponds to the
894          * `reserved` field in struct virtio_net_hash_config.
895          *
896          * Note that all other fields are zeroed at their definitions,
897          * except for the `indirection_table` field, where the actual data
898          * is stored in the `table` variable to ensure compatibility
899          * with RSS case. Therefore, we need to zero the `table` variable here.
900          */
901         table[0] = 0;
902     }
903 
904     /*
905      * Considering that virtio_net_handle_rss() currently does not restore
906      * the hash key length parsed from the CVQ command sent from the guest
907      * into n->rss_data and uses the maximum key length in other code, so
908      * we also employ the maximum key length here.
909      */
910     cfg.hash_key_length = sizeof(n->rss_data.key);
911 
912     const struct iovec data[] = {
913         {
914             .iov_base = &cfg,
915             .iov_len = offsetof(struct virtio_net_rss_config,
916                                 indirection_table),
917         }, {
918             .iov_base = table,
919             .iov_len = n->rss_data.indirections_len *
920                        sizeof(n->rss_data.indirections_table[0]),
921         }, {
922             .iov_base = &cfg.max_tx_vq,
923             .iov_len = offsetof(struct virtio_net_rss_config, hash_key_data) -
924                        offsetof(struct virtio_net_rss_config, max_tx_vq),
925         }, {
926             .iov_base = (void *)n->rss_data.key,
927             .iov_len = sizeof(n->rss_data.key),
928         }
929     };
930 
931     r = vhost_vdpa_net_load_cmd(s, out_cursor, in_cursor,
932                                 VIRTIO_NET_CTRL_MQ,
933                                 do_rss ? VIRTIO_NET_CTRL_MQ_RSS_CONFIG :
934                                 VIRTIO_NET_CTRL_MQ_HASH_CONFIG,
935                                 data, ARRAY_SIZE(data));
936     if (unlikely(r < 0)) {
937         return r;
938     }
939 
940     return 0;
941 }
942 
943 static int vhost_vdpa_net_load_mq(VhostVDPAState *s,
944                                   const VirtIONet *n,
945                                   struct iovec *out_cursor,
946                                   struct iovec *in_cursor)
947 {
948     struct virtio_net_ctrl_mq mq;
949     ssize_t r;
950 
951     if (!virtio_vdev_has_feature(&n->parent_obj, VIRTIO_NET_F_MQ)) {
952         return 0;
953     }
954 
955     trace_vhost_vdpa_net_load_mq(s, n->curr_queue_pairs);
956 
957     mq.virtqueue_pairs = cpu_to_le16(n->curr_queue_pairs);
958     const struct iovec data = {
959         .iov_base = &mq,
960         .iov_len = sizeof(mq),
961     };
962     r = vhost_vdpa_net_load_cmd(s, out_cursor, in_cursor,
963                                 VIRTIO_NET_CTRL_MQ,
964                                 VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET,
965                                 &data, 1);
966     if (unlikely(r < 0)) {
967         return r;
968     }
969 
970     if (virtio_vdev_has_feature(&n->parent_obj, VIRTIO_NET_F_RSS)) {
971         /* load the receive-side scaling state */
972         r = vhost_vdpa_net_load_rss(s, n, out_cursor, in_cursor, true);
973         if (unlikely(r < 0)) {
974             return r;
975         }
976     } else if (virtio_vdev_has_feature(&n->parent_obj,
977                                        VIRTIO_NET_F_HASH_REPORT)) {
978         /* load the hash calculation state */
979         r = vhost_vdpa_net_load_rss(s, n, out_cursor, in_cursor, false);
980         if (unlikely(r < 0)) {
981             return r;
982         }
983     }
984 
985     return 0;
986 }
987 
988 static int vhost_vdpa_net_load_offloads(VhostVDPAState *s,
989                                         const VirtIONet *n,
990                                         struct iovec *out_cursor,
991                                         struct iovec *in_cursor)
992 {
993     uint64_t offloads;
994     ssize_t r;
995 
996     if (!virtio_vdev_has_feature(&n->parent_obj,
997                                  VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)) {
998         return 0;
999     }
1000 
1001     if (n->curr_guest_offloads == virtio_net_supported_guest_offloads(n)) {
1002         /*
1003          * According to VirtIO standard, "Upon feature negotiation
1004          * corresponding offload gets enabled to preserve
1005          * backward compatibility.".
1006          *
1007          * Therefore, there is no need to send this CVQ command if the
1008          * driver also enables all supported offloads, which aligns with
1009          * the device's defaults.
1010          *
1011          * Note that the device's defaults can mismatch the driver's
1012          * configuration only at live migration.
1013          */
1014         return 0;
1015     }
1016 
1017     offloads = cpu_to_le64(n->curr_guest_offloads);
1018     const struct iovec data = {
1019         .iov_base = &offloads,
1020         .iov_len = sizeof(offloads),
1021     };
1022     r = vhost_vdpa_net_load_cmd(s, out_cursor, in_cursor,
1023                                 VIRTIO_NET_CTRL_GUEST_OFFLOADS,
1024                                 VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET,
1025                                 &data, 1);
1026     if (unlikely(r < 0)) {
1027         return r;
1028     }
1029 
1030     return 0;
1031 }
1032 
1033 static int vhost_vdpa_net_load_rx_mode(VhostVDPAState *s,
1034                                        struct iovec *out_cursor,
1035                                        struct iovec *in_cursor,
1036                                        uint8_t cmd,
1037                                        uint8_t on)
1038 {
1039     const struct iovec data = {
1040         .iov_base = &on,
1041         .iov_len = sizeof(on),
1042     };
1043     ssize_t r;
1044 
1045     r = vhost_vdpa_net_load_cmd(s, out_cursor, in_cursor,
1046                                 VIRTIO_NET_CTRL_RX, cmd, &data, 1);
1047     if (unlikely(r < 0)) {
1048         return r;
1049     }
1050 
1051     return 0;
1052 }
1053 
1054 static int vhost_vdpa_net_load_rx(VhostVDPAState *s,
1055                                   const VirtIONet *n,
1056                                   struct iovec *out_cursor,
1057                                   struct iovec *in_cursor)
1058 {
1059     ssize_t r;
1060 
1061     if (!virtio_vdev_has_feature(&n->parent_obj, VIRTIO_NET_F_CTRL_RX)) {
1062         return 0;
1063     }
1064 
1065     /*
1066      * According to virtio_net_reset(), device turns promiscuous mode
1067      * on by default.
1068      *
1069      * Additionally, according to VirtIO standard, "Since there are
1070      * no guarantees, it can use a hash filter or silently switch to
1071      * allmulti or promiscuous mode if it is given too many addresses.".
1072      * QEMU marks `n->mac_table.uni_overflow` if guest sets too many
1073      * non-multicast MAC addresses, indicating that promiscuous mode
1074      * should be enabled.
1075      *
1076      * Therefore, QEMU should only send this CVQ command if the
1077      * `n->mac_table.uni_overflow` is not marked and `n->promisc` is off,
1078      * which sets promiscuous mode on, different from the device's defaults.
1079      *
1080      * Note that the device's defaults can mismatch the driver's
1081      * configuration only at live migration.
1082      */
1083     if (!n->mac_table.uni_overflow && !n->promisc) {
1084         r = vhost_vdpa_net_load_rx_mode(s, out_cursor, in_cursor,
1085                                         VIRTIO_NET_CTRL_RX_PROMISC, 0);
1086         if (unlikely(r < 0)) {
1087             return r;
1088         }
1089     }
1090 
1091     /*
1092      * According to virtio_net_reset(), device turns all-multicast mode
1093      * off by default.
1094      *
1095      * According to VirtIO standard, "Since there are no guarantees,
1096      * it can use a hash filter or silently switch to allmulti or
1097      * promiscuous mode if it is given too many addresses.". QEMU marks
1098      * `n->mac_table.multi_overflow` if guest sets too many
1099      * non-multicast MAC addresses.
1100      *
1101      * Therefore, QEMU should only send this CVQ command if the
1102      * `n->mac_table.multi_overflow` is marked or `n->allmulti` is on,
1103      * which sets all-multicast mode on, different from the device's defaults.
1104      *
1105      * Note that the device's defaults can mismatch the driver's
1106      * configuration only at live migration.
1107      */
1108     if (n->mac_table.multi_overflow || n->allmulti) {
1109         r = vhost_vdpa_net_load_rx_mode(s, out_cursor, in_cursor,
1110                                         VIRTIO_NET_CTRL_RX_ALLMULTI, 1);
1111         if (unlikely(r < 0)) {
1112             return r;
1113         }
1114     }
1115 
1116     if (!virtio_vdev_has_feature(&n->parent_obj, VIRTIO_NET_F_CTRL_RX_EXTRA)) {
1117         return 0;
1118     }
1119 
1120     /*
1121      * According to virtio_net_reset(), device turns all-unicast mode
1122      * off by default.
1123      *
1124      * Therefore, QEMU should only send this CVQ command if the driver
1125      * sets all-unicast mode on, different from the device's defaults.
1126      *
1127      * Note that the device's defaults can mismatch the driver's
1128      * configuration only at live migration.
1129      */
1130     if (n->alluni) {
1131         r = vhost_vdpa_net_load_rx_mode(s, out_cursor, in_cursor,
1132                                         VIRTIO_NET_CTRL_RX_ALLUNI, 1);
1133         if (r < 0) {
1134             return r;
1135         }
1136     }
1137 
1138     /*
1139      * According to virtio_net_reset(), device turns non-multicast mode
1140      * off by default.
1141      *
1142      * Therefore, QEMU should only send this CVQ command if the driver
1143      * sets non-multicast mode on, different from the device's defaults.
1144      *
1145      * Note that the device's defaults can mismatch the driver's
1146      * configuration only at live migration.
1147      */
1148     if (n->nomulti) {
1149         r = vhost_vdpa_net_load_rx_mode(s, out_cursor, in_cursor,
1150                                         VIRTIO_NET_CTRL_RX_NOMULTI, 1);
1151         if (r < 0) {
1152             return r;
1153         }
1154     }
1155 
1156     /*
1157      * According to virtio_net_reset(), device turns non-unicast mode
1158      * off by default.
1159      *
1160      * Therefore, QEMU should only send this CVQ command if the driver
1161      * sets non-unicast mode on, different from the device's defaults.
1162      *
1163      * Note that the device's defaults can mismatch the driver's
1164      * configuration only at live migration.
1165      */
1166     if (n->nouni) {
1167         r = vhost_vdpa_net_load_rx_mode(s, out_cursor, in_cursor,
1168                                         VIRTIO_NET_CTRL_RX_NOUNI, 1);
1169         if (r < 0) {
1170             return r;
1171         }
1172     }
1173 
1174     /*
1175      * According to virtio_net_reset(), device turns non-broadcast mode
1176      * off by default.
1177      *
1178      * Therefore, QEMU should only send this CVQ command if the driver
1179      * sets non-broadcast mode on, different from the device's defaults.
1180      *
1181      * Note that the device's defaults can mismatch the driver's
1182      * configuration only at live migration.
1183      */
1184     if (n->nobcast) {
1185         r = vhost_vdpa_net_load_rx_mode(s, out_cursor, in_cursor,
1186                                         VIRTIO_NET_CTRL_RX_NOBCAST, 1);
1187         if (r < 0) {
1188             return r;
1189         }
1190     }
1191 
1192     return 0;
1193 }
1194 
1195 static int vhost_vdpa_net_load_single_vlan(VhostVDPAState *s,
1196                                            const VirtIONet *n,
1197                                            struct iovec *out_cursor,
1198                                            struct iovec *in_cursor,
1199                                            uint16_t vid)
1200 {
1201     const struct iovec data = {
1202         .iov_base = &vid,
1203         .iov_len = sizeof(vid),
1204     };
1205     ssize_t r = vhost_vdpa_net_load_cmd(s, out_cursor, in_cursor,
1206                                         VIRTIO_NET_CTRL_VLAN,
1207                                         VIRTIO_NET_CTRL_VLAN_ADD,
1208                                         &data, 1);
1209     if (unlikely(r < 0)) {
1210         return r;
1211     }
1212 
1213     return 0;
1214 }
1215 
1216 static int vhost_vdpa_net_load_vlan(VhostVDPAState *s,
1217                                     const VirtIONet *n,
1218                                     struct iovec *out_cursor,
1219                                     struct iovec *in_cursor)
1220 {
1221     int r;
1222 
1223     if (!virtio_vdev_has_feature(&n->parent_obj, VIRTIO_NET_F_CTRL_VLAN)) {
1224         return 0;
1225     }
1226 
1227     for (int i = 0; i < MAX_VLAN >> 5; i++) {
1228         for (int j = 0; n->vlans[i] && j <= 0x1f; j++) {
1229             if (n->vlans[i] & (1U << j)) {
1230                 r = vhost_vdpa_net_load_single_vlan(s, n, out_cursor,
1231                                                     in_cursor, (i << 5) + j);
1232                 if (unlikely(r != 0)) {
1233                     return r;
1234                 }
1235             }
1236         }
1237     }
1238 
1239     return 0;
1240 }
1241 
1242 static int vhost_vdpa_net_cvq_load(NetClientState *nc)
1243 {
1244     VhostVDPAState *s = DO_UPCAST(VhostVDPAState, nc, nc);
1245     struct vhost_vdpa *v = &s->vhost_vdpa;
1246     const VirtIONet *n;
1247     int r;
1248     struct iovec out_cursor, in_cursor;
1249 
1250     assert(nc->info->type == NET_CLIENT_DRIVER_VHOST_VDPA);
1251 
1252     r = vhost_vdpa_set_vring_ready(v, v->dev->vq_index);
1253     if (unlikely(r < 0)) {
1254         return r;
1255     }
1256 
1257     if (v->shadow_vqs_enabled) {
1258         n = VIRTIO_NET(v->dev->vdev);
1259         vhost_vdpa_net_load_cursor_reset(s, &out_cursor, &in_cursor);
1260         r = vhost_vdpa_net_load_mac(s, n, &out_cursor, &in_cursor);
1261         if (unlikely(r < 0)) {
1262             return r;
1263         }
1264         r = vhost_vdpa_net_load_mq(s, n, &out_cursor, &in_cursor);
1265         if (unlikely(r)) {
1266             return r;
1267         }
1268         r = vhost_vdpa_net_load_offloads(s, n, &out_cursor, &in_cursor);
1269         if (unlikely(r)) {
1270             return r;
1271         }
1272         r = vhost_vdpa_net_load_rx(s, n, &out_cursor, &in_cursor);
1273         if (unlikely(r)) {
1274             return r;
1275         }
1276         r = vhost_vdpa_net_load_vlan(s, n, &out_cursor, &in_cursor);
1277         if (unlikely(r)) {
1278             return r;
1279         }
1280 
1281         /*
1282          * We need to poll and check all pending device's used buffers.
1283          *
1284          * We can poll here since we've had BQL from the time
1285          * we sent the descriptor.
1286          */
1287         r = vhost_vdpa_net_svq_flush(s, in_cursor.iov_base - (void *)s->status);
1288         if (unlikely(r)) {
1289             return r;
1290         }
1291     }
1292 
1293     for (int i = 0; i < v->dev->vq_index; ++i) {
1294         r = vhost_vdpa_set_vring_ready(v, i);
1295         if (unlikely(r < 0)) {
1296             return r;
1297         }
1298     }
1299 
1300     return 0;
1301 }
1302 
1303 static NetClientInfo net_vhost_vdpa_cvq_info = {
1304     .type = NET_CLIENT_DRIVER_VHOST_VDPA,
1305     .size = sizeof(VhostVDPAState),
1306     .receive = vhost_vdpa_receive,
1307     .start = vhost_vdpa_net_cvq_start,
1308     .load = vhost_vdpa_net_cvq_load,
1309     .stop = vhost_vdpa_net_cvq_stop,
1310     .cleanup = vhost_vdpa_cleanup,
1311     .has_vnet_hdr = vhost_vdpa_has_vnet_hdr,
1312     .has_ufo = vhost_vdpa_has_ufo,
1313     .check_peer_type = vhost_vdpa_check_peer_type,
1314     .set_steering_ebpf = vhost_vdpa_set_steering_ebpf,
1315 };
1316 
1317 /*
1318  * Forward the excessive VIRTIO_NET_CTRL_MAC_TABLE_SET CVQ command to
1319  * vdpa device.
1320  *
1321  * Considering that QEMU cannot send the entire filter table to the
1322  * vdpa device, it should send the VIRTIO_NET_CTRL_RX_PROMISC CVQ
1323  * command to enable promiscuous mode to receive all packets,
1324  * according to VirtIO standard, "Since there are no guarantees,
1325  * it can use a hash filter or silently switch to allmulti or
1326  * promiscuous mode if it is given too many addresses.".
1327  *
1328  * Since QEMU ignores MAC addresses beyond `MAC_TABLE_ENTRIES` and
1329  * marks `n->mac_table.x_overflow` accordingly, it should have
1330  * the same effect on the device model to receive
1331  * (`MAC_TABLE_ENTRIES` + 1) or more non-multicast MAC addresses.
1332  * The same applies to multicast MAC addresses.
1333  *
1334  * Therefore, QEMU can provide the device model with a fake
1335  * VIRTIO_NET_CTRL_MAC_TABLE_SET command with (`MAC_TABLE_ENTRIES` + 1)
1336  * non-multicast MAC addresses and (`MAC_TABLE_ENTRIES` + 1) multicast
1337  * MAC addresses. This ensures that the device model marks
1338  * `n->mac_table.uni_overflow` and `n->mac_table.multi_overflow`,
1339  * allowing all packets to be received, which aligns with the
1340  * state of the vdpa device.
1341  */
1342 static int vhost_vdpa_net_excessive_mac_filter_cvq_add(VhostVDPAState *s,
1343                                                        VirtQueueElement *elem,
1344                                                        struct iovec *out,
1345                                                        const struct iovec *in)
1346 {
1347     struct virtio_net_ctrl_mac mac_data, *mac_ptr;
1348     struct virtio_net_ctrl_hdr *hdr_ptr;
1349     uint32_t cursor;
1350     ssize_t r;
1351     uint8_t on = 1;
1352 
1353     /* parse the non-multicast MAC address entries from CVQ command */
1354     cursor = sizeof(*hdr_ptr);
1355     r = iov_to_buf(elem->out_sg, elem->out_num, cursor,
1356                    &mac_data, sizeof(mac_data));
1357     if (unlikely(r != sizeof(mac_data))) {
1358         /*
1359          * If the CVQ command is invalid, we should simulate the vdpa device
1360          * to reject the VIRTIO_NET_CTRL_MAC_TABLE_SET CVQ command
1361          */
1362         *s->status = VIRTIO_NET_ERR;
1363         return sizeof(*s->status);
1364     }
1365     cursor += sizeof(mac_data) + le32_to_cpu(mac_data.entries) * ETH_ALEN;
1366 
1367     /* parse the multicast MAC address entries from CVQ command */
1368     r = iov_to_buf(elem->out_sg, elem->out_num, cursor,
1369                    &mac_data, sizeof(mac_data));
1370     if (r != sizeof(mac_data)) {
1371         /*
1372          * If the CVQ command is invalid, we should simulate the vdpa device
1373          * to reject the VIRTIO_NET_CTRL_MAC_TABLE_SET CVQ command
1374          */
1375         *s->status = VIRTIO_NET_ERR;
1376         return sizeof(*s->status);
1377     }
1378     cursor += sizeof(mac_data) + le32_to_cpu(mac_data.entries) * ETH_ALEN;
1379 
1380     /* validate the CVQ command */
1381     if (iov_size(elem->out_sg, elem->out_num) != cursor) {
1382         /*
1383          * If the CVQ command is invalid, we should simulate the vdpa device
1384          * to reject the VIRTIO_NET_CTRL_MAC_TABLE_SET CVQ command
1385          */
1386         *s->status = VIRTIO_NET_ERR;
1387         return sizeof(*s->status);
1388     }
1389 
1390     /*
1391      * According to VirtIO standard, "Since there are no guarantees,
1392      * it can use a hash filter or silently switch to allmulti or
1393      * promiscuous mode if it is given too many addresses.".
1394      *
1395      * Therefore, considering that QEMU is unable to send the entire
1396      * filter table to the vdpa device, it should send the
1397      * VIRTIO_NET_CTRL_RX_PROMISC CVQ command to enable promiscuous mode
1398      */
1399     hdr_ptr = out->iov_base;
1400     out->iov_len = sizeof(*hdr_ptr) + sizeof(on);
1401 
1402     hdr_ptr->class = VIRTIO_NET_CTRL_RX;
1403     hdr_ptr->cmd = VIRTIO_NET_CTRL_RX_PROMISC;
1404     iov_from_buf(out, 1, sizeof(*hdr_ptr), &on, sizeof(on));
1405     r = vhost_vdpa_net_cvq_add(s, out, 1, in, 1);
1406     if (unlikely(r < 0)) {
1407         return r;
1408     }
1409 
1410     /*
1411      * We can poll here since we've had BQL from the time
1412      * we sent the descriptor.
1413      */
1414     r = vhost_vdpa_net_svq_poll(s, 1);
1415     if (unlikely(r < sizeof(*s->status))) {
1416         return r;
1417     }
1418     if (*s->status != VIRTIO_NET_OK) {
1419         return sizeof(*s->status);
1420     }
1421 
1422     /*
1423      * QEMU should also send a fake VIRTIO_NET_CTRL_MAC_TABLE_SET CVQ
1424      * command to the device model, including (`MAC_TABLE_ENTRIES` + 1)
1425      * non-multicast MAC addresses and (`MAC_TABLE_ENTRIES` + 1)
1426      * multicast MAC addresses.
1427      *
1428      * By doing so, the device model can mark `n->mac_table.uni_overflow`
1429      * and `n->mac_table.multi_overflow`, enabling all packets to be
1430      * received, which aligns with the state of the vdpa device.
1431      */
1432     cursor = 0;
1433     uint32_t fake_uni_entries = MAC_TABLE_ENTRIES + 1,
1434              fake_mul_entries = MAC_TABLE_ENTRIES + 1,
1435              fake_cvq_size = sizeof(struct virtio_net_ctrl_hdr) +
1436                              sizeof(mac_data) + fake_uni_entries * ETH_ALEN +
1437                              sizeof(mac_data) + fake_mul_entries * ETH_ALEN;
1438 
1439     assert(fake_cvq_size < vhost_vdpa_net_cvq_cmd_page_len());
1440     out->iov_len = fake_cvq_size;
1441 
1442     /* pack the header for fake CVQ command */
1443     hdr_ptr = out->iov_base + cursor;
1444     hdr_ptr->class = VIRTIO_NET_CTRL_MAC;
1445     hdr_ptr->cmd = VIRTIO_NET_CTRL_MAC_TABLE_SET;
1446     cursor += sizeof(*hdr_ptr);
1447 
1448     /*
1449      * Pack the non-multicast MAC addresses part for fake CVQ command.
1450      *
1451      * According to virtio_net_handle_mac(), QEMU doesn't verify the MAC
1452      * addresses provided in CVQ command. Therefore, only the entries
1453      * field need to be prepared in the CVQ command.
1454      */
1455     mac_ptr = out->iov_base + cursor;
1456     mac_ptr->entries = cpu_to_le32(fake_uni_entries);
1457     cursor += sizeof(*mac_ptr) + fake_uni_entries * ETH_ALEN;
1458 
1459     /*
1460      * Pack the multicast MAC addresses part for fake CVQ command.
1461      *
1462      * According to virtio_net_handle_mac(), QEMU doesn't verify the MAC
1463      * addresses provided in CVQ command. Therefore, only the entries
1464      * field need to be prepared in the CVQ command.
1465      */
1466     mac_ptr = out->iov_base + cursor;
1467     mac_ptr->entries = cpu_to_le32(fake_mul_entries);
1468 
1469     /*
1470      * Simulating QEMU poll a vdpa device used buffer
1471      * for VIRTIO_NET_CTRL_MAC_TABLE_SET CVQ command
1472      */
1473     return sizeof(*s->status);
1474 }
1475 
1476 /**
1477  * Validate and copy control virtqueue commands.
1478  *
1479  * Following QEMU guidelines, we offer a copy of the buffers to the device to
1480  * prevent TOCTOU bugs.
1481  */
1482 static int vhost_vdpa_net_handle_ctrl_avail(VhostShadowVirtqueue *svq,
1483                                             VirtQueueElement *elem,
1484                                             void *opaque)
1485 {
1486     VhostVDPAState *s = opaque;
1487     size_t in_len;
1488     const struct virtio_net_ctrl_hdr *ctrl;
1489     virtio_net_ctrl_ack status = VIRTIO_NET_ERR;
1490     /* Out buffer sent to both the vdpa device and the device model */
1491     struct iovec out = {
1492         .iov_base = s->cvq_cmd_out_buffer,
1493     };
1494     /* in buffer used for device model */
1495     const struct iovec model_in = {
1496         .iov_base = &status,
1497         .iov_len = sizeof(status),
1498     };
1499     /* in buffer used for vdpa device */
1500     const struct iovec vdpa_in = {
1501         .iov_base = s->status,
1502         .iov_len = sizeof(*s->status),
1503     };
1504     ssize_t dev_written = -EINVAL;
1505 
1506     out.iov_len = iov_to_buf(elem->out_sg, elem->out_num, 0,
1507                              s->cvq_cmd_out_buffer,
1508                              vhost_vdpa_net_cvq_cmd_page_len());
1509 
1510     ctrl = s->cvq_cmd_out_buffer;
1511     if (ctrl->class == VIRTIO_NET_CTRL_ANNOUNCE) {
1512         /*
1513          * Guest announce capability is emulated by qemu, so don't forward to
1514          * the device.
1515          */
1516         dev_written = sizeof(status);
1517         *s->status = VIRTIO_NET_OK;
1518     } else if (unlikely(ctrl->class == VIRTIO_NET_CTRL_MAC &&
1519                         ctrl->cmd == VIRTIO_NET_CTRL_MAC_TABLE_SET &&
1520                         iov_size(elem->out_sg, elem->out_num) > out.iov_len)) {
1521         /*
1522          * Due to the size limitation of the out buffer sent to the vdpa device,
1523          * which is determined by vhost_vdpa_net_cvq_cmd_page_len(), excessive
1524          * MAC addresses set by the driver for the filter table can cause
1525          * truncation of the CVQ command in QEMU. As a result, the vdpa device
1526          * rejects the flawed CVQ command.
1527          *
1528          * Therefore, QEMU must handle this situation instead of sending
1529          * the CVQ command directly.
1530          */
1531         dev_written = vhost_vdpa_net_excessive_mac_filter_cvq_add(s, elem,
1532                                                             &out, &vdpa_in);
1533         if (unlikely(dev_written < 0)) {
1534             goto out;
1535         }
1536     } else {
1537         ssize_t r;
1538         r = vhost_vdpa_net_cvq_add(s, &out, 1, &vdpa_in, 1);
1539         if (unlikely(r < 0)) {
1540             dev_written = r;
1541             goto out;
1542         }
1543 
1544         /*
1545          * We can poll here since we've had BQL from the time
1546          * we sent the descriptor.
1547          */
1548         dev_written = vhost_vdpa_net_svq_poll(s, 1);
1549     }
1550 
1551     if (unlikely(dev_written < sizeof(status))) {
1552         error_report("Insufficient written data (%zu)", dev_written);
1553         goto out;
1554     }
1555 
1556     if (*s->status != VIRTIO_NET_OK) {
1557         goto out;
1558     }
1559 
1560     status = VIRTIO_NET_ERR;
1561     virtio_net_handle_ctrl_iov(svq->vdev, &model_in, 1, &out, 1);
1562     if (status != VIRTIO_NET_OK) {
1563         error_report("Bad CVQ processing in model");
1564     }
1565 
1566 out:
1567     in_len = iov_from_buf(elem->in_sg, elem->in_num, 0, &status,
1568                           sizeof(status));
1569     if (unlikely(in_len < sizeof(status))) {
1570         error_report("Bad device CVQ written length");
1571     }
1572     vhost_svq_push_elem(svq, elem, MIN(in_len, sizeof(status)));
1573     /*
1574      * `elem` belongs to vhost_vdpa_net_handle_ctrl_avail() only when
1575      * the function successfully forwards the CVQ command, indicated
1576      * by a non-negative value of `dev_written`. Otherwise, it still
1577      * belongs to SVQ.
1578      * This function should only free the `elem` when it owns.
1579      */
1580     if (dev_written >= 0) {
1581         g_free(elem);
1582     }
1583     return dev_written < 0 ? dev_written : 0;
1584 }
1585 
1586 static const VhostShadowVirtqueueOps vhost_vdpa_net_svq_ops = {
1587     .avail_handler = vhost_vdpa_net_handle_ctrl_avail,
1588 };
1589 
1590 /**
1591  * Probe if CVQ is isolated
1592  *
1593  * @device_fd         The vdpa device fd
1594  * @features          Features offered by the device.
1595  * @cvq_index         The control vq pair index
1596  *
1597  * Returns <0 in case of failure, 0 if false and 1 if true.
1598  */
1599 static int vhost_vdpa_probe_cvq_isolation(int device_fd, uint64_t features,
1600                                           int cvq_index, Error **errp)
1601 {
1602     ERRP_GUARD();
1603     uint64_t backend_features;
1604     int64_t cvq_group;
1605     uint8_t status = VIRTIO_CONFIG_S_ACKNOWLEDGE |
1606                      VIRTIO_CONFIG_S_DRIVER;
1607     int r;
1608 
1609     r = ioctl(device_fd, VHOST_GET_BACKEND_FEATURES, &backend_features);
1610     if (unlikely(r < 0)) {
1611         error_setg_errno(errp, errno, "Cannot get vdpa backend_features");
1612         return r;
1613     }
1614 
1615     if (!(backend_features & BIT_ULL(VHOST_BACKEND_F_IOTLB_ASID))) {
1616         return 0;
1617     }
1618 
1619     r = ioctl(device_fd, VHOST_VDPA_SET_STATUS, &status);
1620     if (unlikely(r)) {
1621         error_setg_errno(errp, -r, "Cannot set device status");
1622         goto out;
1623     }
1624 
1625     r = ioctl(device_fd, VHOST_SET_FEATURES, &features);
1626     if (unlikely(r)) {
1627         error_setg_errno(errp, -r, "Cannot set features");
1628         goto out;
1629     }
1630 
1631     status |= VIRTIO_CONFIG_S_FEATURES_OK;
1632     r = ioctl(device_fd, VHOST_VDPA_SET_STATUS, &status);
1633     if (unlikely(r)) {
1634         error_setg_errno(errp, -r, "Cannot set device status");
1635         goto out;
1636     }
1637 
1638     cvq_group = vhost_vdpa_get_vring_group(device_fd, cvq_index, errp);
1639     if (unlikely(cvq_group < 0)) {
1640         if (cvq_group != -ENOTSUP) {
1641             r = cvq_group;
1642             goto out;
1643         }
1644 
1645         /*
1646          * The kernel report VHOST_BACKEND_F_IOTLB_ASID if the vdpa frontend
1647          * support ASID even if the parent driver does not.  The CVQ cannot be
1648          * isolated in this case.
1649          */
1650         error_free(*errp);
1651         *errp = NULL;
1652         r = 0;
1653         goto out;
1654     }
1655 
1656     for (int i = 0; i < cvq_index; ++i) {
1657         int64_t group = vhost_vdpa_get_vring_group(device_fd, i, errp);
1658         if (unlikely(group < 0)) {
1659             r = group;
1660             goto out;
1661         }
1662 
1663         if (group == (int64_t)cvq_group) {
1664             r = 0;
1665             goto out;
1666         }
1667     }
1668 
1669     r = 1;
1670 
1671 out:
1672     status = 0;
1673     ioctl(device_fd, VHOST_VDPA_SET_STATUS, &status);
1674     return r;
1675 }
1676 
1677 static NetClientState *net_vhost_vdpa_init(NetClientState *peer,
1678                                        const char *device,
1679                                        const char *name,
1680                                        int vdpa_device_fd,
1681                                        int queue_pair_index,
1682                                        int nvqs,
1683                                        bool is_datapath,
1684                                        bool svq,
1685                                        struct vhost_vdpa_iova_range iova_range,
1686                                        uint64_t features,
1687                                        VhostVDPAShared *shared,
1688                                        Error **errp)
1689 {
1690     NetClientState *nc = NULL;
1691     VhostVDPAState *s;
1692     int ret = 0;
1693     assert(name);
1694     int cvq_isolated = 0;
1695 
1696     if (is_datapath) {
1697         nc = qemu_new_net_client(&net_vhost_vdpa_info, peer, device,
1698                                  name);
1699     } else {
1700         cvq_isolated = vhost_vdpa_probe_cvq_isolation(vdpa_device_fd, features,
1701                                                       queue_pair_index * 2,
1702                                                       errp);
1703         if (unlikely(cvq_isolated < 0)) {
1704             return NULL;
1705         }
1706 
1707         nc = qemu_new_net_control_client(&net_vhost_vdpa_cvq_info, peer,
1708                                          device, name);
1709     }
1710     qemu_set_info_str(nc, TYPE_VHOST_VDPA);
1711     s = DO_UPCAST(VhostVDPAState, nc, nc);
1712 
1713     s->vhost_vdpa.index = queue_pair_index;
1714     s->always_svq = svq;
1715     s->migration_state.notify = NULL;
1716     s->vhost_vdpa.shadow_vqs_enabled = svq;
1717     if (queue_pair_index == 0) {
1718         vhost_vdpa_net_valid_svq_features(features,
1719                                           &s->vhost_vdpa.migration_blocker);
1720         s->vhost_vdpa.shared = g_new0(VhostVDPAShared, 1);
1721         s->vhost_vdpa.shared->device_fd = vdpa_device_fd;
1722         s->vhost_vdpa.shared->iova_range = iova_range;
1723         s->vhost_vdpa.shared->shadow_data = svq;
1724     } else if (!is_datapath) {
1725         s->cvq_cmd_out_buffer = mmap(NULL, vhost_vdpa_net_cvq_cmd_page_len(),
1726                                      PROT_READ | PROT_WRITE,
1727                                      MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1728         s->status = mmap(NULL, vhost_vdpa_net_cvq_cmd_page_len(),
1729                          PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS,
1730                          -1, 0);
1731 
1732         s->vhost_vdpa.shadow_vq_ops = &vhost_vdpa_net_svq_ops;
1733         s->vhost_vdpa.shadow_vq_ops_opaque = s;
1734         s->cvq_isolated = cvq_isolated;
1735     }
1736     if (queue_pair_index != 0) {
1737         s->vhost_vdpa.shared = shared;
1738     }
1739 
1740     ret = vhost_vdpa_add(nc, (void *)&s->vhost_vdpa, queue_pair_index, nvqs);
1741     if (ret) {
1742         qemu_del_net_client(nc);
1743         return NULL;
1744     }
1745 
1746     return nc;
1747 }
1748 
1749 static int vhost_vdpa_get_features(int fd, uint64_t *features, Error **errp)
1750 {
1751     int ret = ioctl(fd, VHOST_GET_FEATURES, features);
1752     if (unlikely(ret < 0)) {
1753         error_setg_errno(errp, errno,
1754                          "Fail to query features from vhost-vDPA device");
1755     }
1756     return ret;
1757 }
1758 
1759 static int vhost_vdpa_get_max_queue_pairs(int fd, uint64_t features,
1760                                           int *has_cvq, Error **errp)
1761 {
1762     unsigned long config_size = offsetof(struct vhost_vdpa_config, buf);
1763     g_autofree struct vhost_vdpa_config *config = NULL;
1764     __virtio16 *max_queue_pairs;
1765     int ret;
1766 
1767     if (features & (1 << VIRTIO_NET_F_CTRL_VQ)) {
1768         *has_cvq = 1;
1769     } else {
1770         *has_cvq = 0;
1771     }
1772 
1773     if (features & (1 << VIRTIO_NET_F_MQ)) {
1774         config = g_malloc0(config_size + sizeof(*max_queue_pairs));
1775         config->off = offsetof(struct virtio_net_config, max_virtqueue_pairs);
1776         config->len = sizeof(*max_queue_pairs);
1777 
1778         ret = ioctl(fd, VHOST_VDPA_GET_CONFIG, config);
1779         if (ret) {
1780             error_setg(errp, "Fail to get config from vhost-vDPA device");
1781             return -ret;
1782         }
1783 
1784         max_queue_pairs = (__virtio16 *)&config->buf;
1785 
1786         return lduw_le_p(max_queue_pairs);
1787     }
1788 
1789     return 1;
1790 }
1791 
1792 int net_init_vhost_vdpa(const Netdev *netdev, const char *name,
1793                         NetClientState *peer, Error **errp)
1794 {
1795     ERRP_GUARD();
1796     const NetdevVhostVDPAOptions *opts;
1797     uint64_t features;
1798     int vdpa_device_fd;
1799     g_autofree NetClientState **ncs = NULL;
1800     struct vhost_vdpa_iova_range iova_range;
1801     NetClientState *nc;
1802     int queue_pairs, r, i = 0, has_cvq = 0;
1803 
1804     assert(netdev->type == NET_CLIENT_DRIVER_VHOST_VDPA);
1805     opts = &netdev->u.vhost_vdpa;
1806     if (!opts->vhostdev && !opts->vhostfd) {
1807         error_setg(errp,
1808                    "vhost-vdpa: neither vhostdev= nor vhostfd= was specified");
1809         return -1;
1810     }
1811 
1812     if (opts->vhostdev && opts->vhostfd) {
1813         error_setg(errp,
1814                    "vhost-vdpa: vhostdev= and vhostfd= are mutually exclusive");
1815         return -1;
1816     }
1817 
1818     if (opts->vhostdev) {
1819         vdpa_device_fd = qemu_open(opts->vhostdev, O_RDWR, errp);
1820         if (vdpa_device_fd == -1) {
1821             return -errno;
1822         }
1823     } else {
1824         /* has_vhostfd */
1825         vdpa_device_fd = monitor_fd_param(monitor_cur(), opts->vhostfd, errp);
1826         if (vdpa_device_fd == -1) {
1827             error_prepend(errp, "vhost-vdpa: unable to parse vhostfd: ");
1828             return -1;
1829         }
1830     }
1831 
1832     r = vhost_vdpa_get_features(vdpa_device_fd, &features, errp);
1833     if (unlikely(r < 0)) {
1834         goto err;
1835     }
1836 
1837     queue_pairs = vhost_vdpa_get_max_queue_pairs(vdpa_device_fd, features,
1838                                                  &has_cvq, errp);
1839     if (queue_pairs < 0) {
1840         qemu_close(vdpa_device_fd);
1841         return queue_pairs;
1842     }
1843 
1844     r = vhost_vdpa_get_iova_range(vdpa_device_fd, &iova_range);
1845     if (unlikely(r < 0)) {
1846         error_setg(errp, "vhost-vdpa: get iova range failed: %s",
1847                    strerror(-r));
1848         goto err;
1849     }
1850 
1851     if (opts->x_svq && !vhost_vdpa_net_valid_svq_features(features, errp)) {
1852         goto err;
1853     }
1854 
1855     ncs = g_malloc0(sizeof(*ncs) * queue_pairs);
1856 
1857     for (i = 0; i < queue_pairs; i++) {
1858         VhostVDPAShared *shared = NULL;
1859 
1860         if (i) {
1861             shared = DO_UPCAST(VhostVDPAState, nc, ncs[0])->vhost_vdpa.shared;
1862         }
1863         ncs[i] = net_vhost_vdpa_init(peer, TYPE_VHOST_VDPA, name,
1864                                      vdpa_device_fd, i, 2, true, opts->x_svq,
1865                                      iova_range, features, shared, errp);
1866         if (!ncs[i])
1867             goto err;
1868     }
1869 
1870     if (has_cvq) {
1871         VhostVDPAState *s0 = DO_UPCAST(VhostVDPAState, nc, ncs[0]);
1872         VhostVDPAShared *shared = s0->vhost_vdpa.shared;
1873 
1874         nc = net_vhost_vdpa_init(peer, TYPE_VHOST_VDPA, name,
1875                                  vdpa_device_fd, i, 1, false,
1876                                  opts->x_svq, iova_range, features, shared,
1877                                  errp);
1878         if (!nc)
1879             goto err;
1880     }
1881 
1882     return 0;
1883 
1884 err:
1885     if (i) {
1886         for (i--; i >= 0; i--) {
1887             qemu_del_net_client(ncs[i]);
1888         }
1889     }
1890 
1891     qemu_close(vdpa_device_fd);
1892 
1893     return -1;
1894 }
1895