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