xref: /openbmc/qemu/migration/migration.h (revision e61c4d87)
1 /*
2  * QEMU live migration
3  *
4  * Copyright IBM, Corp. 2008
5  *
6  * Authors:
7  *  Anthony Liguori   <aliguori@us.ibm.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
12  */
13 
14 #ifndef QEMU_MIGRATION_H
15 #define QEMU_MIGRATION_H
16 
17 #include "exec/cpu-common.h"
18 #include "hw/qdev-core.h"
19 #include "qapi/qapi-types-migration.h"
20 #include "qapi/qmp/json-writer.h"
21 #include "qemu/thread.h"
22 #include "qemu/coroutine_int.h"
23 #include "io/channel.h"
24 #include "io/channel-buffer.h"
25 #include "net/announce.h"
26 #include "qom/object.h"
27 #include "postcopy-ram.h"
28 
29 struct PostcopyBlocktimeContext;
30 
31 #define  MIGRATION_RESUME_ACK_VALUE  (1)
32 
33 /*
34  * 1<<6=64 pages -> 256K chunk when page size is 4K.  This gives us
35  * the benefit that all the chunks are 64 pages aligned then the
36  * bitmaps are always aligned to LONG.
37  */
38 #define CLEAR_BITMAP_SHIFT_MIN             6
39 /*
40  * 1<<18=256K pages -> 1G chunk when page size is 4K.  This is the
41  * default value to use if no one specified.
42  */
43 #define CLEAR_BITMAP_SHIFT_DEFAULT        18
44 /*
45  * 1<<31=2G pages -> 8T chunk when page size is 4K.  This should be
46  * big enough and make sure we won't overflow easily.
47  */
48 #define CLEAR_BITMAP_SHIFT_MAX            31
49 
50 /* This is an abstraction of a "temp huge page" for postcopy's purpose */
51 typedef struct {
52     /*
53      * This points to a temporary huge page as a buffer for UFFDIO_COPY.  It's
54      * mmap()ed and needs to be freed when cleanup.
55      */
56     void *tmp_huge_page;
57     /*
58      * This points to the host page we're going to install for this temp page.
59      * It tells us after we've received the whole page, where we should put it.
60      */
61     void *host_addr;
62     /* Number of small pages copied (in size of TARGET_PAGE_SIZE) */
63     unsigned int target_pages;
64     /* Whether this page contains all zeros */
65     bool all_zero;
66 } PostcopyTmpPage;
67 
68 typedef enum {
69     PREEMPT_THREAD_NONE = 0,
70     PREEMPT_THREAD_CREATED,
71     PREEMPT_THREAD_QUIT,
72 } PreemptThreadStatus;
73 
74 /* State for the incoming migration */
75 struct MigrationIncomingState {
76     QEMUFile *from_src_file;
77     /* Previously received RAM's RAMBlock pointer */
78     RAMBlock *last_recv_block[RAM_CHANNEL_MAX];
79     /* A hook to allow cleanup at the end of incoming migration */
80     void *transport_data;
81     void (*transport_cleanup)(void *data);
82     /*
83      * Used to sync thread creations.  Note that we can't create threads in
84      * parallel with this sem.
85      */
86     QemuSemaphore  thread_sync_sem;
87     /*
88      * Free at the start of the main state load, set as the main thread finishes
89      * loading state.
90      */
91     QemuEvent main_thread_load_event;
92 
93     /* For network announces */
94     AnnounceTimer  announce_timer;
95 
96     size_t         largest_page_size;
97     bool           have_fault_thread;
98     QemuThread     fault_thread;
99     /* Set this when we want the fault thread to quit */
100     bool           fault_thread_quit;
101 
102     bool           have_listen_thread;
103     QemuThread     listen_thread;
104 
105     /* For the kernel to send us notifications */
106     int       userfault_fd;
107     /* To notify the fault_thread to wake, e.g., when need to quit */
108     int       userfault_event_fd;
109     QEMUFile *to_src_file;
110     QemuMutex rp_mutex;    /* We send replies from multiple threads */
111     /* RAMBlock of last request sent to source */
112     RAMBlock *last_rb;
113     /*
114      * Number of postcopy channels including the default precopy channel, so
115      * vanilla postcopy will only contain one channel which contain both
116      * precopy and postcopy streams.
117      *
118      * This is calculated when the src requests to enable postcopy but before
119      * it starts.  Its value can depend on e.g. whether postcopy preemption is
120      * enabled.
121      */
122     unsigned int postcopy_channels;
123     /* QEMUFile for postcopy only; it'll be handled by a separate thread */
124     QEMUFile *postcopy_qemufile_dst;
125     /*
126      * When postcopy_qemufile_dst is properly setup, this sem is posted.
127      * One can wait on this semaphore to wait until the preempt channel is
128      * properly setup.
129      */
130     QemuSemaphore postcopy_qemufile_dst_done;
131     /* Postcopy priority thread is used to receive postcopy requested pages */
132     QemuThread postcopy_prio_thread;
133     /*
134      * Always set by the main vm load thread only, but can be read by the
135      * postcopy preempt thread.  "volatile" makes sure all reads will be
136      * uptodate across cores.
137      */
138     volatile PreemptThreadStatus preempt_thread_status;
139     /*
140      * Used to sync between the ram load main thread and the fast ram load
141      * thread.  It protects postcopy_qemufile_dst, which is the postcopy
142      * fast channel.
143      *
144      * The ram fast load thread will take it mostly for the whole lifecycle
145      * because it needs to continuously read data from the channel, and
146      * it'll only release this mutex if postcopy is interrupted, so that
147      * the ram load main thread will take this mutex over and properly
148      * release the broken channel.
149      */
150     QemuMutex postcopy_prio_thread_mutex;
151     /*
152      * An array of temp host huge pages to be used, one for each postcopy
153      * channel.
154      */
155     PostcopyTmpPage *postcopy_tmp_pages;
156     /* This is shared for all postcopy channels */
157     void     *postcopy_tmp_zero_page;
158     /* PostCopyFD's for external userfaultfds & handlers of shared memory */
159     GArray   *postcopy_remote_fds;
160 
161     QEMUBH *bh;
162 
163     int state;
164 
165     bool have_colo_incoming_thread;
166     QemuThread colo_incoming_thread;
167     /* The coroutine we should enter (back) after failover */
168     Coroutine *migration_incoming_co;
169     QemuSemaphore colo_incoming_sem;
170 
171     /*
172      * PostcopyBlocktimeContext to keep information for postcopy
173      * live migration, to calculate vCPU block time
174      * */
175     struct PostcopyBlocktimeContext *blocktime_ctx;
176 
177     /* notify PAUSED postcopy incoming migrations to try to continue */
178     QemuSemaphore postcopy_pause_sem_dst;
179     QemuSemaphore postcopy_pause_sem_fault;
180     /*
181      * This semaphore is used to allow the ram fast load thread (only when
182      * postcopy preempt is enabled) fall into sleep when there's network
183      * interruption detected.  When the recovery is done, the main load
184      * thread will kick the fast ram load thread using this semaphore.
185      */
186     QemuSemaphore postcopy_pause_sem_fast_load;
187 
188     /* List of listening socket addresses  */
189     SocketAddressList *socket_address_list;
190 
191     /* A tree of pages that we requested to the source VM */
192     GTree *page_requested;
193     /* For debugging purpose only, but would be nice to keep */
194     int page_requested_count;
195     /*
196      * The mutex helps to maintain the requested pages that we sent to the
197      * source, IOW, to guarantee coherent between the page_requests tree and
198      * the per-ramblock receivedmap.  Note! This does not guarantee consistency
199      * of the real page copy procedures (using UFFDIO_[ZERO]COPY).  E.g., even
200      * if one bit in receivedmap is cleared, UFFDIO_COPY could have happened
201      * for that page already.  This is intended so that the mutex won't
202      * serialize and blocked by slow operations like UFFDIO_* ioctls.  However
203      * this should be enough to make sure the page_requested tree always
204      * contains valid information.
205      */
206     QemuMutex page_request_mutex;
207 };
208 
209 MigrationIncomingState *migration_incoming_get_current(void);
210 void migration_incoming_state_destroy(void);
211 void migration_incoming_transport_cleanup(MigrationIncomingState *mis);
212 /*
213  * Functions to work with blocktime context
214  */
215 void fill_destination_postcopy_migration_info(MigrationInfo *info);
216 
217 #define TYPE_MIGRATION "migration"
218 
219 typedef struct MigrationClass MigrationClass;
220 DECLARE_OBJ_CHECKERS(MigrationState, MigrationClass,
221                      MIGRATION_OBJ, TYPE_MIGRATION)
222 
223 struct MigrationClass {
224     /*< private >*/
225     DeviceClass parent_class;
226 };
227 
228 struct MigrationState {
229     /*< private >*/
230     DeviceState parent_obj;
231 
232     /*< public >*/
233     QemuThread thread;
234     QEMUBH *vm_start_bh;
235     QEMUBH *cleanup_bh;
236     /* Protected by qemu_file_lock */
237     QEMUFile *to_dst_file;
238     /* Postcopy specific transfer channel */
239     QEMUFile *postcopy_qemufile_src;
240     /*
241      * It is posted when the preempt channel is established.  Note: this is
242      * used for both the start or recover of a postcopy migration.  We'll
243      * post to this sem every time a new preempt channel is created in the
244      * main thread, and we keep post() and wait() in pair.
245      */
246     QemuSemaphore postcopy_qemufile_src_sem;
247     QIOChannelBuffer *bioc;
248     /*
249      * Protects to_dst_file/from_dst_file pointers.  We need to make sure we
250      * won't yield or hang during the critical section, since this lock will be
251      * used in OOB command handler.
252      */
253     QemuMutex qemu_file_lock;
254 
255     /*
256      * Used to allow urgent requests to override rate limiting.
257      */
258     QemuSemaphore rate_limit_sem;
259 
260     /* pages already send at the beginning of current iteration */
261     uint64_t iteration_initial_pages;
262 
263     /* pages transferred per second */
264     double pages_per_second;
265 
266     /* bytes already send at the beginning of current iteration */
267     uint64_t iteration_initial_bytes;
268     /* time at the start of current iteration */
269     int64_t iteration_start_time;
270     /*
271      * The final stage happens when the remaining data is smaller than
272      * this threshold; it's calculated from the requested downtime and
273      * measured bandwidth
274      */
275     int64_t threshold_size;
276 
277     /* params from 'migrate-set-parameters' */
278     MigrationParameters parameters;
279 
280     int state;
281 
282     /* State related to return path */
283     struct {
284         /* Protected by qemu_file_lock */
285         QEMUFile     *from_dst_file;
286         QemuThread    rp_thread;
287         bool          error;
288         /*
289          * We can also check non-zero of rp_thread, but there's no "official"
290          * way to do this, so this bool makes it slightly more elegant.
291          * Checking from_dst_file for this is racy because from_dst_file will
292          * be cleared in the rp_thread!
293          */
294         bool          rp_thread_created;
295         QemuSemaphore rp_sem;
296         /*
297          * We post to this when we got one PONG from dest. So far it's an
298          * easy way to know the main channel has successfully established
299          * on dest QEMU.
300          */
301         QemuSemaphore rp_pong_acks;
302     } rp_state;
303 
304     double mbps;
305     /* Timestamp when recent migration starts (ms) */
306     int64_t start_time;
307     /* Total time used by latest migration (ms) */
308     int64_t total_time;
309     /* Timestamp when VM is down (ms) to migrate the last stuff */
310     int64_t downtime_start;
311     int64_t downtime;
312     int64_t expected_downtime;
313     bool enabled_capabilities[MIGRATION_CAPABILITY__MAX];
314     int64_t setup_time;
315     /*
316      * Whether guest was running when we enter the completion stage.
317      * If migration is interrupted by any reason, we need to continue
318      * running the guest on source.
319      */
320     bool vm_was_running;
321 
322     /* Flag set once the migration has been asked to enter postcopy */
323     bool start_postcopy;
324     /* Flag set after postcopy has sent the device state */
325     bool postcopy_after_devices;
326 
327     /* Flag set once the migration thread is running (and needs joining) */
328     bool migration_thread_running;
329 
330     /* Flag set once the migration thread called bdrv_inactivate_all */
331     bool block_inactive;
332 
333     /* Migration is waiting for guest to unplug device */
334     QemuSemaphore wait_unplug_sem;
335 
336     /* Migration is paused due to pause-before-switchover */
337     QemuSemaphore pause_sem;
338 
339     /* The semaphore is used to notify COLO thread that failover is finished */
340     QemuSemaphore colo_exit_sem;
341 
342     /* The event is used to notify COLO thread to do checkpoint */
343     QemuEvent colo_checkpoint_event;
344     int64_t colo_checkpoint_time;
345     QEMUTimer *colo_delay_timer;
346 
347     /* The first error that has occurred.
348        We used the mutex to be able to return the 1st error message */
349     Error *error;
350     /* mutex to protect errp */
351     QemuMutex error_mutex;
352 
353     /* Do we have to clean up -b/-i from old migrate parameters */
354     /* This feature is deprecated and will be removed */
355     bool must_remove_block_options;
356 
357     /*
358      * Global switch on whether we need to store the global state
359      * during migration.
360      */
361     bool store_global_state;
362 
363     /* Whether we send QEMU_VM_CONFIGURATION during migration */
364     bool send_configuration;
365     /* Whether we send section footer during migration */
366     bool send_section_footer;
367 
368     /* Needed by postcopy-pause state */
369     QemuSemaphore postcopy_pause_sem;
370     QemuSemaphore postcopy_pause_rp_sem;
371     /*
372      * Whether we abort the migration if decompression errors are
373      * detected at the destination. It is left at false for qemu
374      * older than 3.0, since only newer qemu sends streams that
375      * do not trigger spurious decompression errors.
376      */
377     bool decompress_error_check;
378     /*
379      * This variable only affects behavior when postcopy preempt mode is
380      * enabled.
381      *
382      * When set:
383      *
384      * - postcopy preempt src QEMU instance will generate an EOS message at
385      *   the end of migration to shut the preempt channel on dest side.
386      *
387      * - postcopy preempt channel will be created at the setup phase on src
388          QEMU.
389      *
390      * When clear:
391      *
392      * - postcopy preempt src QEMU instance will _not_ generate an EOS
393      *   message at the end of migration, the dest qemu will shutdown the
394      *   channel itself.
395      *
396      * - postcopy preempt channel will be created at the switching phase
397      *   from precopy -> postcopy (to avoid race condtion of misordered
398      *   creation of channels).
399      *
400      * NOTE: See message-id <ZBoShWArKDPpX/D7@work-vm> on qemu-devel
401      * mailing list for more information on the possible race.  Everyone
402      * should probably just keep this value untouched after set by the
403      * machine type (or the default).
404      */
405     bool preempt_pre_7_2;
406 
407     /*
408      * This decides the size of guest memory chunk that will be used
409      * to track dirty bitmap clearing.  The size of memory chunk will
410      * be GUEST_PAGE_SIZE << N.  Say, N=0 means we will clear dirty
411      * bitmap for each page to send (1<<0=1); N=10 means we will clear
412      * dirty bitmap only once for 1<<10=1K continuous guest pages
413      * (which is in 4M chunk).
414      */
415     uint8_t clear_bitmap_shift;
416 
417     /*
418      * This save hostname when out-going migration starts
419      */
420     char *hostname;
421 
422     /* QEMU_VM_VMDESCRIPTION content filled for all non-iterable devices. */
423     JSONWriter *vmdesc;
424 };
425 
426 void migrate_set_state(int *state, int old_state, int new_state);
427 
428 void migration_fd_process_incoming(QEMUFile *f, Error **errp);
429 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp);
430 void migration_incoming_process(void);
431 
432 bool  migration_has_all_channels(void);
433 
434 uint64_t migrate_max_downtime(void);
435 
436 void migrate_set_error(MigrationState *s, const Error *error);
437 void migrate_fd_error(MigrationState *s, const Error *error);
438 
439 void migrate_fd_connect(MigrationState *s, Error *error_in);
440 
441 bool migration_is_setup_or_active(int state);
442 bool migration_is_running(int state);
443 
444 void migrate_init(MigrationState *s);
445 bool migration_is_blocked(Error **errp);
446 /* True if outgoing migration has entered postcopy phase */
447 bool migration_in_postcopy(void);
448 MigrationState *migrate_get_current(void);
449 
450 bool migrate_postcopy(void);
451 
452 bool migrate_release_ram(void);
453 bool migrate_postcopy_ram(void);
454 bool migrate_zero_blocks(void);
455 bool migrate_dirty_bitmaps(void);
456 bool migrate_ignore_shared(void);
457 bool migrate_validate_uuid(void);
458 
459 bool migrate_auto_converge(void);
460 bool migrate_use_multifd(void);
461 bool migrate_pause_before_switchover(void);
462 int migrate_multifd_channels(void);
463 MultiFDCompression migrate_multifd_compression(void);
464 int migrate_multifd_zlib_level(void);
465 int migrate_multifd_zstd_level(void);
466 
467 #ifdef CONFIG_LINUX
468 bool migrate_use_zero_copy_send(void);
469 #else
470 #define migrate_use_zero_copy_send() (false)
471 #endif
472 int migrate_use_tls(void);
473 int migrate_use_xbzrle(void);
474 uint64_t migrate_xbzrle_cache_size(void);
475 bool migrate_colo_enabled(void);
476 
477 bool migrate_use_block(void);
478 bool migrate_use_block_incremental(void);
479 int migrate_max_cpu_throttle(void);
480 bool migrate_use_return_path(void);
481 
482 uint64_t ram_get_total_transferred_pages(void);
483 
484 bool migrate_use_compression(void);
485 int migrate_compress_level(void);
486 int migrate_compress_threads(void);
487 int migrate_compress_wait_thread(void);
488 int migrate_decompress_threads(void);
489 bool migrate_use_events(void);
490 bool migrate_postcopy_blocktime(void);
491 bool migrate_background_snapshot(void);
492 bool migrate_postcopy_preempt(void);
493 
494 /* Sending on the return path - generic and then for each message type */
495 void migrate_send_rp_shut(MigrationIncomingState *mis,
496                           uint32_t value);
497 void migrate_send_rp_pong(MigrationIncomingState *mis,
498                           uint32_t value);
499 int migrate_send_rp_req_pages(MigrationIncomingState *mis, RAMBlock *rb,
500                               ram_addr_t start, uint64_t haddr);
501 int migrate_send_rp_message_req_pages(MigrationIncomingState *mis,
502                                       RAMBlock *rb, ram_addr_t start);
503 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
504                                  char *block_name);
505 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value);
506 
507 void dirty_bitmap_mig_before_vm_start(void);
508 void dirty_bitmap_mig_cancel_outgoing(void);
509 void dirty_bitmap_mig_cancel_incoming(void);
510 bool check_dirty_bitmap_mig_alias_map(const BitmapMigrationNodeAliasList *bbm,
511                                       Error **errp);
512 
513 void migrate_add_address(SocketAddress *address);
514 
515 int foreach_not_ignored_block(RAMBlockIterFunc func, void *opaque);
516 
517 #define qemu_ram_foreach_block \
518   #warning "Use foreach_not_ignored_block in migration code"
519 
520 void migration_make_urgent_request(void);
521 void migration_consume_urgent_request(void);
522 bool migration_rate_limit(void);
523 void migration_cancel(const Error *error);
524 
525 void populate_vfio_info(MigrationInfo *info);
526 void postcopy_temp_page_reset(PostcopyTmpPage *tmp_page);
527 
528 #endif
529