5 QEMU has code to load/save the state of the guest that it is running.
6 These are two complementary operations. Saving the state just does
7 that, saves the state for each device that the guest is running.
8 Restoring a guest is just the opposite operation: we need to load the
11 For this to work, QEMU has to be launched with the same arguments the
12 two times. I.e. it can only restore the state in one guest that has
13 the same devices that the one it was saved (this last requirement can
14 be relaxed a bit, but for now we can consider that configuration has
15 to be exactly the same).
17 Once that we are able to save/restore a guest, a new functionality is
18 requested: migration. This means that QEMU is able to start in one
19 machine and being "migrated" to another machine. I.e. being moved to
22 Next was the "live migration" functionality. This is important
23 because some guests run with a lot of state (specially RAM), and it
24 can take a while to move all state from one machine to another. Live
25 migration allows the guest to continue running while the state is
26 transferred. Only while the last part of the state is transferred has
27 the guest to be stopped. Typically the time that the guest is
28 unresponsive during live migration is the low hundred of milliseconds
29 (notice that this depends on a lot of things).
34 Now that we have talked about live migration, there are several ways
37 - tcp migration: do the migration using tcp sockets
38 - unix migration: do the migration using unix sockets
39 - exec migration: do the migration using the stdin/stdout through a process.
40 - fd migration: do the migration using an file descriptor that is
41 passed to QEMU. QEMU doesn't care how this file descriptor is opened.
43 All these four migration protocols use the same infrastructure to
44 save/restore state devices. This infrastructure is shared with the
45 savevm/loadvm functionality.
50 This is used for RAM and block devices. It is not yet ported to vmstate.
51 <Fill more information here>
56 The files, sockets or fd's that carry the migration stream are abstracted by
57 the ``QEMUFile`` type (see `migration/qemu-file.h`). In most cases this
58 is connected to a subtype of ``QIOChannel`` (see `io/`).
60 Saving the state of one device
61 ==============================
63 The state of a device is saved using intermediate buffers. There are
64 some helper functions to assist this saving.
66 There is a new concept that we have to explain here: device state
67 version. When we migrate a device, we save/load the state as a series
68 of fields. Some times, due to bugs or new functionality, we need to
69 change the state to store more/different information. We use the
70 version to identify each time that we do a change. Each version is
71 associated with a series of fields saved. The `save_state` always saves
72 the state as the newer version. But `load_state` sometimes is able to
73 load state from an older version.
78 This way is going to disappear as soon as all current users are ported to VMSTATE.
80 Each device has to register two functions, one to save the state and
81 another to load the state back.
85 int register_savevm(DeviceState *dev,
89 SaveStateHandler *save_state,
90 LoadStateHandler *load_state,
93 typedef void SaveStateHandler(QEMUFile *f, void *opaque);
94 typedef int LoadStateHandler(QEMUFile *f, void *opaque, int version_id);
96 The important functions for the device state format are the `save_state`
97 and `load_state`. Notice that `load_state` receives a version_id
98 parameter to know what state format is receiving. `save_state` doesn't
99 have a version_id parameter because it always uses the latest version.
104 The legacy way of saving/loading state of the device had the problem
105 that we have to maintain two functions in sync. If we did one change
106 in one of them and not in the other, we would get a failed migration.
108 VMState changed the way that state is saved/loaded. Instead of using
109 a function to save the state and another to load it, it was changed to
110 a declarative way of what the state consisted of. Now VMState is able
111 to interpret that definition to be able to load/save the state. As
112 the state is declared only once, it can't go out of sync in the
115 An example (from hw/input/pckbd.c)
119 static const VMStateDescription vmstate_kbd = {
122 .minimum_version_id = 3,
123 .fields = (VMStateField[]) {
124 VMSTATE_UINT8(write_cmd, KBDState),
125 VMSTATE_UINT8(status, KBDState),
126 VMSTATE_UINT8(mode, KBDState),
127 VMSTATE_UINT8(pending, KBDState),
128 VMSTATE_END_OF_LIST()
132 We are declaring the state with name "pckbd".
133 The `version_id` is 3, and the fields are 4 uint8_t in a KBDState structure.
134 We registered this with:
138 vmstate_register(NULL, 0, &vmstate_kbd, s);
140 Note: talk about how vmstate <-> qdev interact, and what the instance ids mean.
142 You can search for ``VMSTATE_*`` macros for lots of types used in QEMU in
148 Version numbers are intended for major incompatible changes to the
149 migration of a device, and using them breaks backwards-migration
150 compatibility; in general most changes can be made by adding Subsections
151 (see below) or _TEST macros (see below) which won't break compatibility.
153 You can see that there are several version fields:
155 - `version_id`: the maximum version_id supported by VMState for that device.
156 - `minimum_version_id`: the minimum version_id that VMState is able to understand
158 - `minimum_version_id_old`: For devices that were not able to port to vmstate, we can
159 assign a function that knows how to read this old state. This field is
160 ignored if there is no `load_state_old` handler.
162 So, VMState is able to read versions from minimum_version_id to
163 version_id. And the function ``load_state_old()`` (if present) is able to
164 load state from minimum_version_id_old to minimum_version_id. This
165 function is deprecated and will be removed when no more users are left.
167 Saving state will always create a section with the 'version_id' value
168 and thus can't be loaded by any older QEMU.
173 Sometimes, it is not enough to be able to save the state directly
174 from one structure, we need to fill the correct values there. One
175 example is when we are using kvm. Before saving the cpu state, we
176 need to ask kvm to copy to QEMU the state that it is using. And the
177 opposite when we are loading the state, we need a way to tell kvm to
178 load the state for the cpu that we have just loaded from the QEMUFile.
180 The functions to do that are inside a vmstate definition, and are called:
182 - ``int (*pre_load)(void *opaque);``
184 This function is called before we load the state of one device.
186 - ``int (*post_load)(void *opaque, int version_id);``
188 This function is called after we load the state of one device.
190 - ``int (*pre_save)(void *opaque);``
192 This function is called before we save the state of one device.
194 Example: You can look at hpet.c, that uses the three function to
195 massage the state that is transferred.
197 If you use memory API functions that update memory layout outside
198 initialization (i.e., in response to a guest action), this is a strong
199 indication that you need to call these functions in a `post_load` callback.
200 Examples of such memory API functions are:
202 - memory_region_add_subregion()
203 - memory_region_del_subregion()
204 - memory_region_set_readonly()
205 - memory_region_set_enabled()
206 - memory_region_set_address()
207 - memory_region_set_alias_offset()
212 The use of version_id allows to be able to migrate from older versions
213 to newer versions of a device. But not the other way around. This
214 makes very complicated to fix bugs in stable branches. If we need to
215 add anything to the state to fix a bug, we have to disable migration
216 to older versions that don't have that bug-fix (i.e. a new field).
218 But sometimes, that bug-fix is only needed sometimes, not always. For
219 instance, if the device is in the middle of a DMA operation, it is
220 using a specific functionality, ....
222 It is impossible to create a way to make migration from any version to
223 any other version to work. But we can do better than only allowing
224 migration from older versions to newer ones. For that fields that are
225 only needed sometimes, we add the idea of subsections. A subsection
226 is "like" a device vmstate, but with a particularity, it has a Boolean
227 function that tells if that values are needed to be sent or not. If
228 this functions returns false, the subsection is not sent.
230 On the receiving side, if we found a subsection for a device that we
231 don't understand, we just fail the migration. If we understand all
232 the subsections, then we load the state with success.
234 One important note is that the post_load() function is called "after"
235 loading all subsections, because a newer subsection could change same
242 static bool ide_drive_pio_state_needed(void *opaque)
244 IDEState *s = opaque;
246 return ((s->status & DRQ_STAT) != 0)
247 || (s->bus->error_status & BM_STATUS_PIO_RETRY);
250 const VMStateDescription vmstate_ide_drive_pio_state = {
251 .name = "ide_drive/pio_state",
253 .minimum_version_id = 1,
254 .pre_save = ide_drive_pio_pre_save,
255 .post_load = ide_drive_pio_post_load,
256 .needed = ide_drive_pio_state_needed,
257 .fields = (VMStateField[]) {
258 VMSTATE_INT32(req_nb_sectors, IDEState),
259 VMSTATE_VARRAY_INT32(io_buffer, IDEState, io_buffer_total_len, 1,
260 vmstate_info_uint8, uint8_t),
261 VMSTATE_INT32(cur_io_buffer_offset, IDEState),
262 VMSTATE_INT32(cur_io_buffer_len, IDEState),
263 VMSTATE_UINT8(end_transfer_fn_idx, IDEState),
264 VMSTATE_INT32(elementary_transfer_size, IDEState),
265 VMSTATE_INT32(packet_transfer_size, IDEState),
266 VMSTATE_END_OF_LIST()
270 const VMStateDescription vmstate_ide_drive = {
273 .minimum_version_id = 0,
274 .post_load = ide_drive_post_load,
275 .fields = (VMStateField[]) {
276 .... several fields ....
277 VMSTATE_END_OF_LIST()
279 .subsections = (const VMStateDescription*[]) {
280 &vmstate_ide_drive_pio_state,
285 Here we have a subsection for the pio state. We only need to
286 save/send this state when we are in the middle of a pio operation
287 (that is what ``ide_drive_pio_state_needed()`` checks). If DRQ_STAT is
288 not enabled, the values on that fields are garbage and don't need to
291 Using a condition function that checks a 'property' to determine whether
292 to send a subsection allows backwards migration compatibility when
293 new subsections are added.
297 a) Add a new property using ``DEFINE_PROP_BOOL`` - e.g. support-foo and
299 b) Add an entry to the ``HW_COMPAT_`` for the previous version that sets
300 the property to false.
301 c) Add a static bool support_foo function that tests the property.
302 d) Add a subsection with a .needed set to the support_foo function
303 e) (potentially) Add a pre_load that sets up a default value for 'foo'
304 to be used if the subsection isn't loaded.
306 Now that subsection will not be generated when using an older
307 machine type and the migration stream will be accepted by older
308 QEMU versions. pre-load functions can be used to initialise state
309 on the newer version so that they default to suitable values
310 when loading streams created by older QEMU versions that do not
311 generate the subsection.
313 In some cases subsections are added for data that had been accidentally
314 omitted by earlier versions; if the missing data causes the migration
315 process to succeed but the guest to behave badly then it may be better
316 to send the subsection and cause the migration to explicitly fail
317 with the unknown subsection error. If the bad behaviour only happens
318 with certain data values, making the subsection conditional on
319 the data value (rather than the machine type) allows migrations to succeed
320 in most cases. In general the preference is to tie the subsection to
321 the machine type, and allow reliable migrations, unless the behaviour
322 from omission of the subsection is really bad.
324 Not sending existing elements
325 -----------------------------
327 Sometimes members of the VMState are no longer needed:
329 - removing them will break migration compatibility
331 - making them version dependent and bumping the version will break backwards migration compatibility.
335 a) Add a new property/compatibility/function in the same way for subsections above.
336 b) replace the VMSTATE macro with the _TEST version of the macro, e.g.:
338 ``VMSTATE_UINT32(foo, barstruct)``
342 ``VMSTATE_UINT32_TEST(foo, barstruct, pre_version_baz)``
344 Sometime in the future when we no longer care about the ancient versions these can be killed off.
349 In most migration scenarios there is only a single data path that runs
350 from the source VM to the destination, typically along a single fd (although
351 possibly with another fd or similar for some fast way of throwing pages across).
353 However, some uses need two way communication; in particular the Postcopy
354 destination needs to be able to request pages on demand from the source.
356 For these scenarios there is a 'return path' from the destination to the source;
357 ``qemu_file_get_return_path(QEMUFile* fwdpath)`` gives the QEMUFile* for the return
362 Forward path - written by migration thread
363 Return path - opened by main thread, read by return-path thread
367 Forward path - read by main thread
368 Return path - opened by main thread, written by main thread AND postcopy
369 thread (protected by rp_mutex)
374 'Postcopy' migration is a way to deal with migrations that refuse to converge
375 (or take too long to converge) its plus side is that there is an upper bound on
376 the amount of migration traffic and time it takes, the down side is that during
377 the postcopy phase, a failure of *either* side or the network connection causes
378 the guest to be lost.
380 In postcopy the destination CPUs are started before all the memory has been
381 transferred, and accesses to pages that are yet to be transferred cause
382 a fault that's translated by QEMU into a request to the source QEMU.
384 Postcopy can be combined with precopy (i.e. normal migration) so that if precopy
385 doesn't finish in a given time the switch is made to postcopy.
390 To enable postcopy, issue this command on the monitor prior to the
393 ``migrate_set_capability postcopy-ram on``
395 The normal commands are then used to start a migration, which is still
396 started in precopy mode. Issuing:
398 ``migrate_start_postcopy``
400 will now cause the transition from precopy to postcopy.
401 It can be issued immediately after migration is started or any
402 time later on. Issuing it after the end of a migration is harmless.
405 During the postcopy phase, the bandwidth limits set using
406 ``migrate_set_speed`` is ignored (to avoid delaying requested pages that
407 the destination is waiting for).
409 Postcopy device transfer
410 ------------------------
412 Loading of device data may cause the device emulation to access guest RAM
413 that may trigger faults that have to be resolved by the source, as such
414 the migration stream has to be able to respond with page data *during* the
415 device load, and hence the device data has to be read from the stream completely
416 before the device load begins to free the stream up. This is achieved by
417 'packaging' the device data into a blob that's read in one go.
422 Until postcopy is entered the migration stream is identical to normal
423 precopy, except for the addition of a 'postcopy advise' command at
424 the beginning, to tell the destination that postcopy might happen.
425 When postcopy starts the source sends the page discard data and then
426 forms the 'package' containing:
428 - Command: 'postcopy listen'
431 A series of sections, identical to the precopy streams device state stream
432 containing everything except postcopiable devices (i.e. RAM)
433 - Command: 'postcopy run'
435 The 'package' is sent as the data part of a Command: ``CMD_PACKAGED``, and the
436 contents are formatted in the same way as the main migration stream.
438 During postcopy the source scans the list of dirty pages and sends them
439 to the destination without being requested (in much the same way as precopy),
440 however when a page request is received from the destination, the dirty page
441 scanning restarts from the requested location. This causes requested pages
442 to be sent quickly, and also causes pages directly after the requested page
443 to be sent quickly in the hope that those pages are likely to be used
444 by the destination soon.
446 Destination behaviour
447 ---------------------
449 Initially the destination looks the same as precopy, with a single thread
450 reading the migration stream; the 'postcopy advise' and 'discard' commands
451 are processed to change the way RAM is managed, but don't affect the stream
456 ------------------------------------------------------------------------------
458 main -----DISCARD-CMD_PACKAGED ( LISTEN DEVICE DEVICE DEVICE RUN )
463 listen thread: --- page -- page -- page -- page -- page --
466 ------------------------------------------------------------------------------
468 - On receipt of ``CMD_PACKAGED`` (1)
470 All the data associated with the package - the ( ... ) section in the diagram -
471 is read into memory, and the main thread recurses into qemu_loadvm_state_main
472 to process the contents of the package (2) which contains commands (3,6) and
475 - On receipt of 'postcopy listen' - 3 -(i.e. the 1st command in the package)
477 a new thread (a) is started that takes over servicing the migration stream,
478 while the main thread carries on loading the package. It loads normal
479 background page data (b) but if during a device load a fault happens (5)
480 the returned page (c) is loaded by the listen thread allowing the main
481 threads device load to carry on.
483 - The last thing in the ``CMD_PACKAGED`` is a 'RUN' command (6)
485 letting the destination CPUs start running. At the end of the
486 ``CMD_PACKAGED`` (7) the main thread returns to normal running behaviour and
487 is no longer used by migration, while the listen thread carries on servicing
488 page data until the end of migration.
493 Postcopy moves through a series of states (see postcopy_state) from
494 ADVISE->DISCARD->LISTEN->RUNNING->END
498 Set at the start of migration if postcopy is enabled, even
499 if it hasn't had the start command; here the destination
500 checks that its OS has the support needed for postcopy, and performs
501 setup to ensure the RAM mappings are suitable for later postcopy.
502 The destination will fail early in migration at this point if the
503 required OS support is not present.
504 (Triggered by reception of POSTCOPY_ADVISE command)
508 Entered on receipt of the first 'discard' command; prior to
509 the first Discard being performed, hugepages are switched off
510 (using madvise) to ensure that no new huge pages are created
511 during the postcopy phase, and to cause any huge pages that
512 have discards on them to be broken.
516 The first command in the package, POSTCOPY_LISTEN, switches
517 the destination state to Listen, and starts a new thread
518 (the 'listen thread') which takes over the job of receiving
519 pages off the migration stream, while the main thread carries
520 on processing the blob. With this thread able to process page
521 reception, the destination now 'sensitises' the RAM to detect
522 any access to missing pages (on Linux using the 'userfault'
527 POSTCOPY_RUN causes the destination to synchronise all
528 state and start the CPUs and IO devices running. The main
529 thread now finishes processing the migration package and
530 now carries on as it would for normal precopy migration
531 (although it can't do the cleanup it would do as it
532 finishes a normal migration).
536 The listen thread can now quit, and perform the cleanup of migration
537 state, the migration is now complete.
539 Source side page maps
540 ---------------------
542 The source side keeps two bitmaps during postcopy; 'the migration bitmap'
543 and 'unsent map'. The 'migration bitmap' is basically the same as in
544 the precopy case, and holds a bit to indicate that page is 'dirty' -
545 i.e. needs sending. During the precopy phase this is updated as the CPU
546 dirties pages, however during postcopy the CPUs are stopped and nothing
547 should dirty anything any more.
549 The 'unsent map' is used for the transition to postcopy. It is a bitmap that
550 has a bit cleared whenever a page is sent to the destination, however during
551 the transition to postcopy mode it is combined with the migration bitmap
552 to form a set of pages that:
554 a) Have been sent but then redirtied (which must be discarded)
555 b) Have not yet been sent - which also must be discarded to cause any
556 transparent huge pages built during precopy to be broken.
558 Note that the contents of the unsentmap are sacrificed during the calculation
559 of the discard set and thus aren't valid once in postcopy. The dirtymap
560 is still valid and is used to ensure that no page is sent more than once. Any
561 request for a page that has already been sent is ignored. Duplicate requests
562 such as this can happen as a page is sent at about the same time the
563 destination accesses it.
565 Postcopy with hugepages
566 -----------------------
568 Postcopy now works with hugetlbfs backed memory:
570 a) The linux kernel on the destination must support userfault on hugepages.
571 b) The huge-page configuration on the source and destination VMs must be
572 identical; i.e. RAMBlocks on both sides must use the same page size.
573 c) Note that ``-mem-path /dev/hugepages`` will fall back to allocating normal
574 RAM if it doesn't have enough hugepages, triggering (b) to fail.
575 Using ``-mem-prealloc`` enforces the allocation using hugepages.
576 d) Care should be taken with the size of hugepage used; postcopy with 2MB
577 hugepages works well, however 1GB hugepages are likely to be problematic
578 since it takes ~1 second to transfer a 1GB hugepage across a 10Gbps link,
579 and until the full page is transferred the destination thread is blocked.