2
0

migration.h 21 KB

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