xref: /openbmc/qemu/hw/vfio/migration.c (revision 94f775e428f8057ee66425f421b68fe8c94cebcc)
1 /*
2  * Migration support for VFIO devices
3  *
4  * Copyright NVIDIA, Inc. 2020
5  *
6  * This work is licensed under the terms of the GNU GPL, version 2. See
7  * the COPYING file in the top-level directory.
8  */
9 
10 #include "qemu/osdep.h"
11 #include "qemu/main-loop.h"
12 #include "qemu/cutils.h"
13 #include "qemu/units.h"
14 #include "qemu/error-report.h"
15 #include <linux/vfio.h>
16 #include <sys/ioctl.h>
17 
18 #include "sysemu/runstate.h"
19 #include "hw/vfio/vfio-common.h"
20 #include "migration/migration.h"
21 #include "migration/options.h"
22 #include "migration/savevm.h"
23 #include "migration/vmstate.h"
24 #include "migration/qemu-file.h"
25 #include "migration/register.h"
26 #include "migration/blocker.h"
27 #include "migration/misc.h"
28 #include "qapi/error.h"
29 #include "exec/ramlist.h"
30 #include "exec/ram_addr.h"
31 #include "pci.h"
32 #include "trace.h"
33 #include "hw/hw.h"
34 
35 /*
36  * Flags to be used as unique delimiters for VFIO devices in the migration
37  * stream. These flags are composed as:
38  * 0xffffffff => MSB 32-bit all 1s
39  * 0xef10     => Magic ID, represents emulated (virtual) function IO
40  * 0x0000     => 16-bits reserved for flags
41  *
42  * The beginning of state information is marked by _DEV_CONFIG_STATE,
43  * _DEV_SETUP_STATE, or _DEV_DATA_STATE, respectively. The end of a
44  * certain state information is marked by _END_OF_STATE.
45  */
46 #define VFIO_MIG_FLAG_END_OF_STATE      (0xffffffffef100001ULL)
47 #define VFIO_MIG_FLAG_DEV_CONFIG_STATE  (0xffffffffef100002ULL)
48 #define VFIO_MIG_FLAG_DEV_SETUP_STATE   (0xffffffffef100003ULL)
49 #define VFIO_MIG_FLAG_DEV_DATA_STATE    (0xffffffffef100004ULL)
50 #define VFIO_MIG_FLAG_DEV_INIT_DATA_SENT (0xffffffffef100005ULL)
51 
52 /*
53  * This is an arbitrary size based on migration of mlx5 devices, where typically
54  * total device migration size is on the order of 100s of MB. Testing with
55  * larger values, e.g. 128MB and 1GB, did not show a performance improvement.
56  */
57 #define VFIO_MIG_DEFAULT_DATA_BUFFER_SIZE (1 * MiB)
58 
59 static int64_t bytes_transferred;
60 
61 static const char *mig_state_to_str(enum vfio_device_mig_state state)
62 {
63     switch (state) {
64     case VFIO_DEVICE_STATE_ERROR:
65         return "ERROR";
66     case VFIO_DEVICE_STATE_STOP:
67         return "STOP";
68     case VFIO_DEVICE_STATE_RUNNING:
69         return "RUNNING";
70     case VFIO_DEVICE_STATE_STOP_COPY:
71         return "STOP_COPY";
72     case VFIO_DEVICE_STATE_RESUMING:
73         return "RESUMING";
74     case VFIO_DEVICE_STATE_RUNNING_P2P:
75         return "RUNNING_P2P";
76     case VFIO_DEVICE_STATE_PRE_COPY:
77         return "PRE_COPY";
78     case VFIO_DEVICE_STATE_PRE_COPY_P2P:
79         return "PRE_COPY_P2P";
80     default:
81         return "UNKNOWN STATE";
82     }
83 }
84 
85 static int vfio_migration_set_state(VFIODevice *vbasedev,
86                                     enum vfio_device_mig_state new_state,
87                                     enum vfio_device_mig_state recover_state)
88 {
89     VFIOMigration *migration = vbasedev->migration;
90     uint64_t buf[DIV_ROUND_UP(sizeof(struct vfio_device_feature) +
91                               sizeof(struct vfio_device_feature_mig_state),
92                               sizeof(uint64_t))] = {};
93     struct vfio_device_feature *feature = (struct vfio_device_feature *)buf;
94     struct vfio_device_feature_mig_state *mig_state =
95         (struct vfio_device_feature_mig_state *)feature->data;
96     int ret;
97 
98     feature->argsz = sizeof(buf);
99     feature->flags =
100         VFIO_DEVICE_FEATURE_SET | VFIO_DEVICE_FEATURE_MIG_DEVICE_STATE;
101     mig_state->device_state = new_state;
102     if (ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature)) {
103         /* Try to set the device in some good state */
104         ret = -errno;
105 
106         if (recover_state == VFIO_DEVICE_STATE_ERROR) {
107             error_report("%s: Failed setting device state to %s, err: %s. "
108                          "Recover state is ERROR. Resetting device",
109                          vbasedev->name, mig_state_to_str(new_state),
110                          strerror(errno));
111 
112             goto reset_device;
113         }
114 
115         error_report(
116             "%s: Failed setting device state to %s, err: %s. Setting device in recover state %s",
117                      vbasedev->name, mig_state_to_str(new_state),
118                      strerror(errno), mig_state_to_str(recover_state));
119 
120         mig_state->device_state = recover_state;
121         if (ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature)) {
122             ret = -errno;
123             error_report(
124                 "%s: Failed setting device in recover state, err: %s. Resetting device",
125                          vbasedev->name, strerror(errno));
126 
127             goto reset_device;
128         }
129 
130         migration->device_state = recover_state;
131 
132         return ret;
133     }
134 
135     migration->device_state = new_state;
136     if (mig_state->data_fd != -1) {
137         if (migration->data_fd != -1) {
138             /*
139              * This can happen if the device is asynchronously reset and
140              * terminates a data transfer.
141              */
142             error_report("%s: data_fd out of sync", vbasedev->name);
143             close(mig_state->data_fd);
144 
145             return -EBADF;
146         }
147 
148         migration->data_fd = mig_state->data_fd;
149     }
150 
151     trace_vfio_migration_set_state(vbasedev->name, mig_state_to_str(new_state));
152 
153     return 0;
154 
155 reset_device:
156     if (ioctl(vbasedev->fd, VFIO_DEVICE_RESET)) {
157         hw_error("%s: Failed resetting device, err: %s", vbasedev->name,
158                  strerror(errno));
159     }
160 
161     migration->device_state = VFIO_DEVICE_STATE_RUNNING;
162 
163     return ret;
164 }
165 
166 static int vfio_load_buffer(QEMUFile *f, VFIODevice *vbasedev,
167                             uint64_t data_size)
168 {
169     VFIOMigration *migration = vbasedev->migration;
170     int ret;
171 
172     ret = qemu_file_get_to_fd(f, migration->data_fd, data_size);
173     trace_vfio_load_state_device_data(vbasedev->name, data_size, ret);
174 
175     return ret;
176 }
177 
178 static int vfio_save_device_config_state(QEMUFile *f, void *opaque)
179 {
180     VFIODevice *vbasedev = opaque;
181 
182     qemu_put_be64(f, VFIO_MIG_FLAG_DEV_CONFIG_STATE);
183 
184     if (vbasedev->ops && vbasedev->ops->vfio_save_config) {
185         vbasedev->ops->vfio_save_config(vbasedev, f);
186     }
187 
188     qemu_put_be64(f, VFIO_MIG_FLAG_END_OF_STATE);
189 
190     trace_vfio_save_device_config_state(vbasedev->name);
191 
192     return qemu_file_get_error(f);
193 }
194 
195 static int vfio_load_device_config_state(QEMUFile *f, void *opaque)
196 {
197     VFIODevice *vbasedev = opaque;
198     uint64_t data;
199 
200     if (vbasedev->ops && vbasedev->ops->vfio_load_config) {
201         int ret;
202 
203         ret = vbasedev->ops->vfio_load_config(vbasedev, f);
204         if (ret) {
205             error_report("%s: Failed to load device config space",
206                          vbasedev->name);
207             return ret;
208         }
209     }
210 
211     data = qemu_get_be64(f);
212     if (data != VFIO_MIG_FLAG_END_OF_STATE) {
213         error_report("%s: Failed loading device config space, "
214                      "end flag incorrect 0x%"PRIx64, vbasedev->name, data);
215         return -EINVAL;
216     }
217 
218     trace_vfio_load_device_config_state(vbasedev->name);
219     return qemu_file_get_error(f);
220 }
221 
222 static void vfio_migration_cleanup(VFIODevice *vbasedev)
223 {
224     VFIOMigration *migration = vbasedev->migration;
225 
226     close(migration->data_fd);
227     migration->data_fd = -1;
228 }
229 
230 static int vfio_query_stop_copy_size(VFIODevice *vbasedev,
231                                      uint64_t *stop_copy_size)
232 {
233     uint64_t buf[DIV_ROUND_UP(sizeof(struct vfio_device_feature) +
234                               sizeof(struct vfio_device_feature_mig_data_size),
235                               sizeof(uint64_t))] = {};
236     struct vfio_device_feature *feature = (struct vfio_device_feature *)buf;
237     struct vfio_device_feature_mig_data_size *mig_data_size =
238         (struct vfio_device_feature_mig_data_size *)feature->data;
239 
240     feature->argsz = sizeof(buf);
241     feature->flags =
242         VFIO_DEVICE_FEATURE_GET | VFIO_DEVICE_FEATURE_MIG_DATA_SIZE;
243 
244     if (ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature)) {
245         return -errno;
246     }
247 
248     *stop_copy_size = mig_data_size->stop_copy_length;
249 
250     return 0;
251 }
252 
253 static int vfio_query_precopy_size(VFIOMigration *migration)
254 {
255     struct vfio_precopy_info precopy = {
256         .argsz = sizeof(precopy),
257     };
258 
259     migration->precopy_init_size = 0;
260     migration->precopy_dirty_size = 0;
261 
262     if (ioctl(migration->data_fd, VFIO_MIG_GET_PRECOPY_INFO, &precopy)) {
263         return -errno;
264     }
265 
266     migration->precopy_init_size = precopy.initial_bytes;
267     migration->precopy_dirty_size = precopy.dirty_bytes;
268 
269     return 0;
270 }
271 
272 /* Returns the size of saved data on success and -errno on error */
273 static ssize_t vfio_save_block(QEMUFile *f, VFIOMigration *migration)
274 {
275     ssize_t data_size;
276 
277     data_size = read(migration->data_fd, migration->data_buffer,
278                      migration->data_buffer_size);
279     if (data_size < 0) {
280         /*
281          * Pre-copy emptied all the device state for now. For more information,
282          * please refer to the Linux kernel VFIO uAPI.
283          */
284         if (errno == ENOMSG) {
285             return 0;
286         }
287 
288         return -errno;
289     }
290     if (data_size == 0) {
291         return 0;
292     }
293 
294     qemu_put_be64(f, VFIO_MIG_FLAG_DEV_DATA_STATE);
295     qemu_put_be64(f, data_size);
296     qemu_put_buffer(f, migration->data_buffer, data_size);
297     bytes_transferred += data_size;
298 
299     trace_vfio_save_block(migration->vbasedev->name, data_size);
300 
301     return qemu_file_get_error(f) ?: data_size;
302 }
303 
304 static void vfio_update_estimated_pending_data(VFIOMigration *migration,
305                                                uint64_t data_size)
306 {
307     if (!data_size) {
308         /*
309          * Pre-copy emptied all the device state for now, update estimated sizes
310          * accordingly.
311          */
312         migration->precopy_init_size = 0;
313         migration->precopy_dirty_size = 0;
314 
315         return;
316     }
317 
318     if (migration->precopy_init_size) {
319         uint64_t init_size = MIN(migration->precopy_init_size, data_size);
320 
321         migration->precopy_init_size -= init_size;
322         data_size -= init_size;
323     }
324 
325     migration->precopy_dirty_size -= MIN(migration->precopy_dirty_size,
326                                          data_size);
327 }
328 
329 static bool vfio_precopy_supported(VFIODevice *vbasedev)
330 {
331     VFIOMigration *migration = vbasedev->migration;
332 
333     return migration->mig_flags & VFIO_MIGRATION_PRE_COPY;
334 }
335 
336 /* ---------------------------------------------------------------------- */
337 
338 static int vfio_save_setup(QEMUFile *f, void *opaque)
339 {
340     VFIODevice *vbasedev = opaque;
341     VFIOMigration *migration = vbasedev->migration;
342     uint64_t stop_copy_size = VFIO_MIG_DEFAULT_DATA_BUFFER_SIZE;
343 
344     qemu_put_be64(f, VFIO_MIG_FLAG_DEV_SETUP_STATE);
345 
346     vfio_query_stop_copy_size(vbasedev, &stop_copy_size);
347     migration->data_buffer_size = MIN(VFIO_MIG_DEFAULT_DATA_BUFFER_SIZE,
348                                       stop_copy_size);
349     migration->data_buffer = g_try_malloc0(migration->data_buffer_size);
350     if (!migration->data_buffer) {
351         error_report("%s: Failed to allocate migration data buffer",
352                      vbasedev->name);
353         return -ENOMEM;
354     }
355 
356     if (vfio_precopy_supported(vbasedev)) {
357         int ret;
358 
359         switch (migration->device_state) {
360         case VFIO_DEVICE_STATE_RUNNING:
361             ret = vfio_migration_set_state(vbasedev, VFIO_DEVICE_STATE_PRE_COPY,
362                                            VFIO_DEVICE_STATE_RUNNING);
363             if (ret) {
364                 return ret;
365             }
366 
367             vfio_query_precopy_size(migration);
368 
369             break;
370         case VFIO_DEVICE_STATE_STOP:
371             /* vfio_save_complete_precopy() will go to STOP_COPY */
372             break;
373         default:
374             return -EINVAL;
375         }
376     }
377 
378     trace_vfio_save_setup(vbasedev->name, migration->data_buffer_size);
379 
380     qemu_put_be64(f, VFIO_MIG_FLAG_END_OF_STATE);
381 
382     return qemu_file_get_error(f);
383 }
384 
385 static void vfio_save_cleanup(void *opaque)
386 {
387     VFIODevice *vbasedev = opaque;
388     VFIOMigration *migration = vbasedev->migration;
389 
390     /*
391      * Changing device state from STOP_COPY to STOP can take time. Do it here,
392      * after migration has completed, so it won't increase downtime.
393      */
394     if (migration->device_state == VFIO_DEVICE_STATE_STOP_COPY) {
395         /*
396          * If setting the device in STOP state fails, the device should be
397          * reset. To do so, use ERROR state as a recover state.
398          */
399         vfio_migration_set_state(vbasedev, VFIO_DEVICE_STATE_STOP,
400                                  VFIO_DEVICE_STATE_ERROR);
401     }
402 
403     g_free(migration->data_buffer);
404     migration->data_buffer = NULL;
405     migration->precopy_init_size = 0;
406     migration->precopy_dirty_size = 0;
407     migration->initial_data_sent = false;
408     vfio_migration_cleanup(vbasedev);
409     trace_vfio_save_cleanup(vbasedev->name);
410 }
411 
412 static void vfio_state_pending_estimate(void *opaque, uint64_t *must_precopy,
413                                         uint64_t *can_postcopy)
414 {
415     VFIODevice *vbasedev = opaque;
416     VFIOMigration *migration = vbasedev->migration;
417 
418     if (!vfio_device_state_is_precopy(vbasedev)) {
419         return;
420     }
421 
422     *must_precopy +=
423         migration->precopy_init_size + migration->precopy_dirty_size;
424 
425     trace_vfio_state_pending_estimate(vbasedev->name, *must_precopy,
426                                       *can_postcopy,
427                                       migration->precopy_init_size,
428                                       migration->precopy_dirty_size);
429 }
430 
431 /*
432  * Migration size of VFIO devices can be as little as a few KBs or as big as
433  * many GBs. This value should be big enough to cover the worst case.
434  */
435 #define VFIO_MIG_STOP_COPY_SIZE (100 * GiB)
436 
437 static void vfio_state_pending_exact(void *opaque, uint64_t *must_precopy,
438                                      uint64_t *can_postcopy)
439 {
440     VFIODevice *vbasedev = opaque;
441     VFIOMigration *migration = vbasedev->migration;
442     uint64_t stop_copy_size = VFIO_MIG_STOP_COPY_SIZE;
443 
444     /*
445      * If getting pending migration size fails, VFIO_MIG_STOP_COPY_SIZE is
446      * reported so downtime limit won't be violated.
447      */
448     vfio_query_stop_copy_size(vbasedev, &stop_copy_size);
449     *must_precopy += stop_copy_size;
450 
451     if (vfio_device_state_is_precopy(vbasedev)) {
452         vfio_query_precopy_size(migration);
453 
454         *must_precopy +=
455             migration->precopy_init_size + migration->precopy_dirty_size;
456     }
457 
458     trace_vfio_state_pending_exact(vbasedev->name, *must_precopy, *can_postcopy,
459                                    stop_copy_size, migration->precopy_init_size,
460                                    migration->precopy_dirty_size);
461 }
462 
463 static bool vfio_is_active_iterate(void *opaque)
464 {
465     VFIODevice *vbasedev = opaque;
466 
467     return vfio_device_state_is_precopy(vbasedev);
468 }
469 
470 static int vfio_save_iterate(QEMUFile *f, void *opaque)
471 {
472     VFIODevice *vbasedev = opaque;
473     VFIOMigration *migration = vbasedev->migration;
474     ssize_t data_size;
475 
476     data_size = vfio_save_block(f, migration);
477     if (data_size < 0) {
478         return data_size;
479     }
480 
481     vfio_update_estimated_pending_data(migration, data_size);
482 
483     if (migrate_switchover_ack() && !migration->precopy_init_size &&
484         !migration->initial_data_sent) {
485         qemu_put_be64(f, VFIO_MIG_FLAG_DEV_INIT_DATA_SENT);
486         migration->initial_data_sent = true;
487     } else {
488         qemu_put_be64(f, VFIO_MIG_FLAG_END_OF_STATE);
489     }
490 
491     trace_vfio_save_iterate(vbasedev->name, migration->precopy_init_size,
492                             migration->precopy_dirty_size);
493 
494     /*
495      * A VFIO device's pre-copy dirty_bytes is not guaranteed to reach zero.
496      * Return 1 so following handlers will not be potentially blocked.
497      */
498     return 1;
499 }
500 
501 static int vfio_save_complete_precopy(QEMUFile *f, void *opaque)
502 {
503     VFIODevice *vbasedev = opaque;
504     ssize_t data_size;
505     int ret;
506 
507     /* We reach here with device state STOP or STOP_COPY only */
508     ret = vfio_migration_set_state(vbasedev, VFIO_DEVICE_STATE_STOP_COPY,
509                                    VFIO_DEVICE_STATE_STOP);
510     if (ret) {
511         return ret;
512     }
513 
514     do {
515         data_size = vfio_save_block(f, vbasedev->migration);
516         if (data_size < 0) {
517             return data_size;
518         }
519     } while (data_size);
520 
521     qemu_put_be64(f, VFIO_MIG_FLAG_END_OF_STATE);
522     ret = qemu_file_get_error(f);
523     if (ret) {
524         return ret;
525     }
526 
527     trace_vfio_save_complete_precopy(vbasedev->name, ret);
528 
529     return ret;
530 }
531 
532 static void vfio_save_state(QEMUFile *f, void *opaque)
533 {
534     VFIODevice *vbasedev = opaque;
535     int ret;
536 
537     ret = vfio_save_device_config_state(f, opaque);
538     if (ret) {
539         error_report("%s: Failed to save device config space",
540                      vbasedev->name);
541         qemu_file_set_error(f, ret);
542     }
543 }
544 
545 static int vfio_load_setup(QEMUFile *f, void *opaque)
546 {
547     VFIODevice *vbasedev = opaque;
548 
549     return vfio_migration_set_state(vbasedev, VFIO_DEVICE_STATE_RESUMING,
550                                    vbasedev->migration->device_state);
551 }
552 
553 static int vfio_load_cleanup(void *opaque)
554 {
555     VFIODevice *vbasedev = opaque;
556 
557     vfio_migration_cleanup(vbasedev);
558     trace_vfio_load_cleanup(vbasedev->name);
559 
560     return 0;
561 }
562 
563 static int vfio_load_state(QEMUFile *f, void *opaque, int version_id)
564 {
565     VFIODevice *vbasedev = opaque;
566     int ret = 0;
567     uint64_t data;
568 
569     data = qemu_get_be64(f);
570     while (data != VFIO_MIG_FLAG_END_OF_STATE) {
571 
572         trace_vfio_load_state(vbasedev->name, data);
573 
574         switch (data) {
575         case VFIO_MIG_FLAG_DEV_CONFIG_STATE:
576         {
577             return vfio_load_device_config_state(f, opaque);
578         }
579         case VFIO_MIG_FLAG_DEV_SETUP_STATE:
580         {
581             data = qemu_get_be64(f);
582             if (data == VFIO_MIG_FLAG_END_OF_STATE) {
583                 return ret;
584             } else {
585                 error_report("%s: SETUP STATE: EOS not found 0x%"PRIx64,
586                              vbasedev->name, data);
587                 return -EINVAL;
588             }
589             break;
590         }
591         case VFIO_MIG_FLAG_DEV_DATA_STATE:
592         {
593             uint64_t data_size = qemu_get_be64(f);
594 
595             if (data_size) {
596                 ret = vfio_load_buffer(f, vbasedev, data_size);
597                 if (ret < 0) {
598                     return ret;
599                 }
600             }
601             break;
602         }
603         case VFIO_MIG_FLAG_DEV_INIT_DATA_SENT:
604         {
605             if (!vfio_precopy_supported(vbasedev) ||
606                 !migrate_switchover_ack()) {
607                 error_report("%s: Received INIT_DATA_SENT but switchover ack "
608                              "is not used", vbasedev->name);
609                 return -EINVAL;
610             }
611 
612             ret = qemu_loadvm_approve_switchover();
613             if (ret) {
614                 error_report(
615                     "%s: qemu_loadvm_approve_switchover failed, err=%d (%s)",
616                     vbasedev->name, ret, strerror(-ret));
617             }
618 
619             return ret;
620         }
621         default:
622             error_report("%s: Unknown tag 0x%"PRIx64, vbasedev->name, data);
623             return -EINVAL;
624         }
625 
626         data = qemu_get_be64(f);
627         ret = qemu_file_get_error(f);
628         if (ret) {
629             return ret;
630         }
631     }
632     return ret;
633 }
634 
635 static bool vfio_switchover_ack_needed(void *opaque)
636 {
637     VFIODevice *vbasedev = opaque;
638 
639     return vfio_precopy_supported(vbasedev);
640 }
641 
642 static const SaveVMHandlers savevm_vfio_handlers = {
643     .save_setup = vfio_save_setup,
644     .save_cleanup = vfio_save_cleanup,
645     .state_pending_estimate = vfio_state_pending_estimate,
646     .state_pending_exact = vfio_state_pending_exact,
647     .is_active_iterate = vfio_is_active_iterate,
648     .save_live_iterate = vfio_save_iterate,
649     .save_live_complete_precopy = vfio_save_complete_precopy,
650     .save_state = vfio_save_state,
651     .load_setup = vfio_load_setup,
652     .load_cleanup = vfio_load_cleanup,
653     .load_state = vfio_load_state,
654     .switchover_ack_needed = vfio_switchover_ack_needed,
655 };
656 
657 /* ---------------------------------------------------------------------- */
658 
659 static void vfio_vmstate_change_prepare(void *opaque, bool running,
660                                         RunState state)
661 {
662     VFIODevice *vbasedev = opaque;
663     VFIOMigration *migration = vbasedev->migration;
664     enum vfio_device_mig_state new_state;
665     int ret;
666 
667     new_state = migration->device_state == VFIO_DEVICE_STATE_PRE_COPY ?
668                     VFIO_DEVICE_STATE_PRE_COPY_P2P :
669                     VFIO_DEVICE_STATE_RUNNING_P2P;
670 
671     /*
672      * If setting the device in new_state fails, the device should be reset.
673      * To do so, use ERROR state as a recover state.
674      */
675     ret = vfio_migration_set_state(vbasedev, new_state,
676                                    VFIO_DEVICE_STATE_ERROR);
677     if (ret) {
678         /*
679          * Migration should be aborted in this case, but vm_state_notify()
680          * currently does not support reporting failures.
681          */
682         if (migrate_get_current()->to_dst_file) {
683             qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
684         }
685     }
686 
687     trace_vfio_vmstate_change_prepare(vbasedev->name, running,
688                                       RunState_str(state),
689                                       mig_state_to_str(new_state));
690 }
691 
692 static void vfio_vmstate_change(void *opaque, bool running, RunState state)
693 {
694     VFIODevice *vbasedev = opaque;
695     enum vfio_device_mig_state new_state;
696     int ret;
697 
698     if (running) {
699         new_state = VFIO_DEVICE_STATE_RUNNING;
700     } else {
701         new_state =
702             (vfio_device_state_is_precopy(vbasedev) &&
703              (state == RUN_STATE_FINISH_MIGRATE || state == RUN_STATE_PAUSED)) ?
704                 VFIO_DEVICE_STATE_STOP_COPY :
705                 VFIO_DEVICE_STATE_STOP;
706     }
707 
708     /*
709      * If setting the device in new_state fails, the device should be reset.
710      * To do so, use ERROR state as a recover state.
711      */
712     ret = vfio_migration_set_state(vbasedev, new_state,
713                                    VFIO_DEVICE_STATE_ERROR);
714     if (ret) {
715         /*
716          * Migration should be aborted in this case, but vm_state_notify()
717          * currently does not support reporting failures.
718          */
719         if (migrate_get_current()->to_dst_file) {
720             qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
721         }
722     }
723 
724     trace_vfio_vmstate_change(vbasedev->name, running, RunState_str(state),
725                               mig_state_to_str(new_state));
726 }
727 
728 static void vfio_migration_state_notifier(Notifier *notifier, void *data)
729 {
730     MigrationState *s = data;
731     VFIOMigration *migration = container_of(notifier, VFIOMigration,
732                                             migration_state);
733     VFIODevice *vbasedev = migration->vbasedev;
734 
735     trace_vfio_migration_state_notifier(vbasedev->name,
736                                         MigrationStatus_str(s->state));
737 
738     switch (s->state) {
739     case MIGRATION_STATUS_CANCELLING:
740     case MIGRATION_STATUS_CANCELLED:
741     case MIGRATION_STATUS_FAILED:
742         /*
743          * If setting the device in RUNNING state fails, the device should
744          * be reset. To do so, use ERROR state as a recover state.
745          */
746         vfio_migration_set_state(vbasedev, VFIO_DEVICE_STATE_RUNNING,
747                                  VFIO_DEVICE_STATE_ERROR);
748     }
749 }
750 
751 static void vfio_migration_free(VFIODevice *vbasedev)
752 {
753     g_free(vbasedev->migration);
754     vbasedev->migration = NULL;
755 }
756 
757 static int vfio_migration_query_flags(VFIODevice *vbasedev, uint64_t *mig_flags)
758 {
759     uint64_t buf[DIV_ROUND_UP(sizeof(struct vfio_device_feature) +
760                                   sizeof(struct vfio_device_feature_migration),
761                               sizeof(uint64_t))] = {};
762     struct vfio_device_feature *feature = (struct vfio_device_feature *)buf;
763     struct vfio_device_feature_migration *mig =
764         (struct vfio_device_feature_migration *)feature->data;
765 
766     feature->argsz = sizeof(buf);
767     feature->flags = VFIO_DEVICE_FEATURE_GET | VFIO_DEVICE_FEATURE_MIGRATION;
768     if (ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature)) {
769         return -errno;
770     }
771 
772     *mig_flags = mig->flags;
773 
774     return 0;
775 }
776 
777 static bool vfio_dma_logging_supported(VFIODevice *vbasedev)
778 {
779     uint64_t buf[DIV_ROUND_UP(sizeof(struct vfio_device_feature),
780                               sizeof(uint64_t))] = {};
781     struct vfio_device_feature *feature = (struct vfio_device_feature *)buf;
782 
783     feature->argsz = sizeof(buf);
784     feature->flags = VFIO_DEVICE_FEATURE_PROBE |
785                      VFIO_DEVICE_FEATURE_DMA_LOGGING_START;
786 
787     return !ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature);
788 }
789 
790 static int vfio_migration_init(VFIODevice *vbasedev)
791 {
792     int ret;
793     Object *obj;
794     VFIOMigration *migration;
795     char id[256] = "";
796     g_autofree char *path = NULL, *oid = NULL;
797     uint64_t mig_flags = 0;
798     VMChangeStateHandler *prepare_cb;
799 
800     if (!vbasedev->ops->vfio_get_object) {
801         return -EINVAL;
802     }
803 
804     obj = vbasedev->ops->vfio_get_object(vbasedev);
805     if (!obj) {
806         return -EINVAL;
807     }
808 
809     ret = vfio_migration_query_flags(vbasedev, &mig_flags);
810     if (ret) {
811         return ret;
812     }
813 
814     /* Basic migration functionality must be supported */
815     if (!(mig_flags & VFIO_MIGRATION_STOP_COPY)) {
816         return -EOPNOTSUPP;
817     }
818 
819     vbasedev->migration = g_new0(VFIOMigration, 1);
820     migration = vbasedev->migration;
821     migration->vbasedev = vbasedev;
822     migration->device_state = VFIO_DEVICE_STATE_RUNNING;
823     migration->data_fd = -1;
824     migration->mig_flags = mig_flags;
825 
826     vbasedev->dirty_pages_supported = vfio_dma_logging_supported(vbasedev);
827 
828     oid = vmstate_if_get_id(VMSTATE_IF(DEVICE(obj)));
829     if (oid) {
830         path = g_strdup_printf("%s/vfio", oid);
831     } else {
832         path = g_strdup("vfio");
833     }
834     strpadcpy(id, sizeof(id), path, '\0');
835 
836     register_savevm_live(id, VMSTATE_INSTANCE_ID_ANY, 1, &savevm_vfio_handlers,
837                          vbasedev);
838 
839     prepare_cb = migration->mig_flags & VFIO_MIGRATION_P2P ?
840                      vfio_vmstate_change_prepare :
841                      NULL;
842     migration->vm_state = qdev_add_vm_change_state_handler_full(
843         vbasedev->dev, vfio_vmstate_change, prepare_cb, vbasedev);
844     migration->migration_state.notify = vfio_migration_state_notifier;
845     add_migration_state_change_notifier(&migration->migration_state);
846 
847     return 0;
848 }
849 
850 static void vfio_migration_deinit(VFIODevice *vbasedev)
851 {
852     VFIOMigration *migration = vbasedev->migration;
853 
854     remove_migration_state_change_notifier(&migration->migration_state);
855     qemu_del_vm_change_state_handler(migration->vm_state);
856     unregister_savevm(VMSTATE_IF(vbasedev->dev), "vfio", vbasedev);
857     vfio_migration_free(vbasedev);
858     vfio_unblock_multiple_devices_migration();
859 }
860 
861 static int vfio_block_migration(VFIODevice *vbasedev, Error *err, Error **errp)
862 {
863     int ret;
864 
865     if (vbasedev->enable_migration == ON_OFF_AUTO_ON) {
866         error_propagate(errp, err);
867         return -EINVAL;
868     }
869 
870     vbasedev->migration_blocker = error_copy(err);
871     error_free(err);
872 
873     ret = migrate_add_blocker(vbasedev->migration_blocker, errp);
874     if (ret < 0) {
875         error_free(vbasedev->migration_blocker);
876         vbasedev->migration_blocker = NULL;
877     }
878 
879     return ret;
880 }
881 
882 /* ---------------------------------------------------------------------- */
883 
884 int64_t vfio_mig_bytes_transferred(void)
885 {
886     return bytes_transferred;
887 }
888 
889 void vfio_reset_bytes_transferred(void)
890 {
891     bytes_transferred = 0;
892 }
893 
894 /*
895  * Return true when either migration initialized or blocker registered.
896  * Currently only return false when adding blocker fails which will
897  * de-register vfio device.
898  */
899 bool vfio_migration_realize(VFIODevice *vbasedev, Error **errp)
900 {
901     Error *err = NULL;
902     int ret;
903 
904     if (vbasedev->enable_migration == ON_OFF_AUTO_OFF) {
905         error_setg(&err, "%s: Migration is disabled for VFIO device",
906                    vbasedev->name);
907         return !vfio_block_migration(vbasedev, err, errp);
908     }
909 
910     ret = vfio_migration_init(vbasedev);
911     if (ret) {
912         if (ret == -ENOTTY) {
913             error_setg(&err, "%s: VFIO migration is not supported in kernel",
914                        vbasedev->name);
915         } else {
916             error_setg(&err,
917                        "%s: Migration couldn't be initialized for VFIO device, "
918                        "err: %d (%s)",
919                        vbasedev->name, ret, strerror(-ret));
920         }
921 
922         return !vfio_block_migration(vbasedev, err, errp);
923     }
924 
925     if (!vbasedev->dirty_pages_supported) {
926         if (vbasedev->enable_migration == ON_OFF_AUTO_AUTO) {
927             error_setg(&err,
928                        "%s: VFIO device doesn't support device dirty tracking",
929                        vbasedev->name);
930             goto add_blocker;
931         }
932 
933         warn_report("%s: VFIO device doesn't support device dirty tracking",
934                     vbasedev->name);
935     }
936 
937     ret = vfio_block_multiple_devices_migration(vbasedev, errp);
938     if (ret) {
939         goto out_deinit;
940     }
941 
942     if (vfio_viommu_preset(vbasedev)) {
943         error_setg(&err, "%s: Migration is currently not supported "
944                    "with vIOMMU enabled", vbasedev->name);
945         goto add_blocker;
946     }
947 
948     trace_vfio_migration_realize(vbasedev->name);
949     return true;
950 
951 add_blocker:
952     ret = vfio_block_migration(vbasedev, err, errp);
953 out_deinit:
954     if (ret) {
955         vfio_migration_deinit(vbasedev);
956     }
957     return !ret;
958 }
959 
960 void vfio_migration_exit(VFIODevice *vbasedev)
961 {
962     if (vbasedev->migration) {
963         vfio_migration_deinit(vbasedev);
964     }
965 
966     if (vbasedev->migration_blocker) {
967         migrate_del_blocker(vbasedev->migration_blocker);
968         error_free(vbasedev->migration_blocker);
969         vbasedev->migration_blocker = NULL;
970     }
971 }
972