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