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