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