xref: /qemu/docs/devel/migration/main.rst (revision 19f9c044)
1===================
2Migration framework
3===================
4
5QEMU has code to load/save the state of the guest that it is running.
6These are two complementary operations.  Saving the state just does
7that, saves the state for each device that the guest is running.
8Restoring a guest is just the opposite operation: we need to load the
9state of each device.
10
11For this to work, QEMU has to be launched with the same arguments the
12two times.  I.e. it can only restore the state in one guest that has
13the same devices that the one it was saved (this last requirement can
14be relaxed a bit, but for now we can consider that configuration has
15to be exactly the same).
16
17Once that we are able to save/restore a guest, a new functionality is
18requested: migration.  This means that QEMU is able to start in one
19machine and being "migrated" to another machine.  I.e. being moved to
20another machine.
21
22Next was the "live migration" functionality.  This is important
23because some guests run with a lot of state (specially RAM), and it
24can take a while to move all state from one machine to another.  Live
25migration allows the guest to continue running while the state is
26transferred.  Only while the last part of the state is transferred has
27the guest to be stopped.  Typically the time that the guest is
28unresponsive during live migration is the low hundred of milliseconds
29(notice that this depends on a lot of things).
30
31.. contents::
32
33Transports
34==========
35
36The migration stream is normally just a byte stream that can be passed
37over any transport.
38
39- tcp migration: do the migration using tcp sockets
40- unix migration: do the migration using unix sockets
41- exec migration: do the migration using the stdin/stdout through a process.
42- fd migration: do the migration using a file descriptor that is
43  passed to QEMU.  QEMU doesn't care how this file descriptor is opened.
44- file migration: do the migration using a file that is passed to QEMU
45  by path. A file offset option is supported to allow a management
46  application to add its own metadata to the start of the file without
47  QEMU interference.
48
49In addition, support is included for migration using RDMA, which
50transports the page data using ``RDMA``, where the hardware takes care of
51transporting the pages, and the load on the CPU is much lower.  While the
52internals of RDMA migration are a bit different, this isn't really visible
53outside the RAM migration code.
54
55All these migration protocols use the same infrastructure to
56save/restore state devices.  This infrastructure is shared with the
57savevm/loadvm functionality.
58
59Common infrastructure
60=====================
61
62The files, sockets or fd's that carry the migration stream are abstracted by
63the  ``QEMUFile`` type (see ``migration/qemu-file.h``).  In most cases this
64is connected to a subtype of ``QIOChannel`` (see ``io/``).
65
66
67Saving the state of one device
68==============================
69
70For most devices, the state is saved in a single call to the migration
71infrastructure; these are *non-iterative* devices.  The data for these
72devices is sent at the end of precopy migration, when the CPUs are paused.
73There are also *iterative* devices, which contain a very large amount of
74data (e.g. RAM or large tables).  See the iterative device section below.
75
76General advice for device developers
77------------------------------------
78
79- The migration state saved should reflect the device being modelled rather
80  than the way your implementation works.  That way if you change the implementation
81  later the migration stream will stay compatible.  That model may include
82  internal state that's not directly visible in a register.
83
84- When saving a migration stream the device code may walk and check
85  the state of the device.  These checks might fail in various ways (e.g.
86  discovering internal state is corrupt or that the guest has done something bad).
87  Consider carefully before asserting/aborting at this point, since the
88  normal response from users is that *migration broke their VM* since it had
89  apparently been running fine until then.  In these error cases, the device
90  should log a message indicating the cause of error, and should consider
91  putting the device into an error state, allowing the rest of the VM to
92  continue execution.
93
94- The migration might happen at an inconvenient point,
95  e.g. right in the middle of the guest reprogramming the device, during
96  guest reboot or shutdown or while the device is waiting for external IO.
97  It's strongly preferred that migrations do not fail in this situation,
98  since in the cloud environment migrations might happen automatically to
99  VMs that the administrator doesn't directly control.
100
101- If you do need to fail a migration, ensure that sufficient information
102  is logged to identify what went wrong.
103
104- The destination should treat an incoming migration stream as hostile
105  (which we do to varying degrees in the existing code).  Check that offsets
106  into buffers and the like can't cause overruns.  Fail the incoming migration
107  in the case of a corrupted stream like this.
108
109- Take care with internal device state or behaviour that might become
110  migration version dependent.  For example, the order of PCI capabilities
111  is required to stay constant across migration.  Another example would
112  be that a special case handled by subsections (see below) might become
113  much more common if a default behaviour is changed.
114
115- The state of the source should not be changed or destroyed by the
116  outgoing migration.  Migrations timing out or being failed by
117  higher levels of management, or failures of the destination host are
118  not unusual, and in that case the VM is restarted on the source.
119  Note that the management layer can validly revert the migration
120  even though the QEMU level of migration has succeeded as long as it
121  does it before starting execution on the destination.
122
123- Buses and devices should be able to explicitly specify addresses when
124  instantiated, and management tools should use those.  For example,
125  when hot adding USB devices it's important to specify the ports
126  and addresses, since implicit ordering based on the command line order
127  may be different on the destination.  This can result in the
128  device state being loaded into the wrong device.
129
130VMState
131-------
132
133Most device data can be described using the ``VMSTATE`` macros (mostly defined
134in ``include/migration/vmstate.h``).
135
136An example (from hw/input/pckbd.c)
137
138.. code:: c
139
140  static const VMStateDescription vmstate_kbd = {
141      .name = "pckbd",
142      .version_id = 3,
143      .minimum_version_id = 3,
144      .fields = (const VMStateField[]) {
145          VMSTATE_UINT8(write_cmd, KBDState),
146          VMSTATE_UINT8(status, KBDState),
147          VMSTATE_UINT8(mode, KBDState),
148          VMSTATE_UINT8(pending, KBDState),
149          VMSTATE_END_OF_LIST()
150      }
151  };
152
153We are declaring the state with name "pckbd".  The ``version_id`` is
1543, and there are 4 uint8_t fields in the KBDState structure.  We
155registered this ``VMSTATEDescription`` with one of the following
156functions.  The first one will generate a device ``instance_id``
157different for each registration.  Use the second one if you already
158have an id that is different for each instance of the device:
159
160.. code:: c
161
162    vmstate_register_any(NULL, &vmstate_kbd, s);
163    vmstate_register(NULL, instance_id, &vmstate_kbd, s);
164
165For devices that are ``qdev`` based, we can register the device in the class
166init function:
167
168.. code:: c
169
170    dc->vmsd = &vmstate_kbd_isa;
171
172The VMState macros take care of ensuring that the device data section
173is formatted portably (normally big endian) and make some compile time checks
174against the types of the fields in the structures.
175
176VMState macros can include other VMStateDescriptions to store substructures
177(see ``VMSTATE_STRUCT_``), arrays (``VMSTATE_ARRAY_``) and variable length
178arrays (``VMSTATE_VARRAY_``).  Various other macros exist for special
179cases.
180
181Note that the format on the wire is still very raw; i.e. a VMSTATE_UINT32
182ends up with a 4 byte bigendian representation on the wire; in the future
183it might be possible to use a more structured format.
184
185Legacy way
186----------
187
188This way is going to disappear as soon as all current users are ported to VMSTATE;
189although converting existing code can be tricky, and thus 'soon' is relative.
190
191Each device has to register two functions, one to save the state and
192another to load the state back.
193
194.. code:: c
195
196  int register_savevm_live(const char *idstr,
197                           int instance_id,
198                           int version_id,
199                           SaveVMHandlers *ops,
200                           void *opaque);
201
202Two functions in the ``ops`` structure are the ``save_state``
203and ``load_state`` functions.  Notice that ``load_state`` receives a version_id
204parameter to know what state format is receiving.  ``save_state`` doesn't
205have a version_id parameter because it always uses the latest version.
206
207Note that because the VMState macros still save the data in a raw
208format, in many cases it's possible to replace legacy code
209with a carefully constructed VMState description that matches the
210byte layout of the existing code.
211
212Changing migration data structures
213----------------------------------
214
215When we migrate a device, we save/load the state as a series
216of fields.  Sometimes, due to bugs or new functionality, we need to
217change the state to store more/different information.  Changing the migration
218state saved for a device can break migration compatibility unless
219care is taken to use the appropriate techniques.  In general QEMU tries
220to maintain forward migration compatibility (i.e. migrating from
221QEMU n->n+1) and there are users who benefit from backward compatibility
222as well.
223
224Subsections
225-----------
226
227The most common structure change is adding new data, e.g. when adding
228a newer form of device, or adding that state that you previously
229forgot to migrate.  This is best solved using a subsection.
230
231A subsection is "like" a device vmstate, but with a particularity, it
232has a Boolean function that tells if that values are needed to be sent
233or not.  If this functions returns false, the subsection is not sent.
234Subsections have a unique name, that is looked for on the receiving
235side.
236
237On the receiving side, if we found a subsection for a device that we
238don't understand, we just fail the migration.  If we understand all
239the subsections, then we load the state with success.  There's no check
240that a subsection is loaded, so a newer QEMU that knows about a subsection
241can (with care) load a stream from an older QEMU that didn't send
242the subsection.
243
244If the new data is only needed in a rare case, then the subsection
245can be made conditional on that case and the migration will still
246succeed to older QEMUs in most cases.  This is OK for data that's
247critical, but in some use cases it's preferred that the migration
248should succeed even with the data missing.  To support this the
249subsection can be connected to a device property and from there
250to a versioned machine type.
251
252The 'pre_load' and 'post_load' functions on subsections are only
253called if the subsection is loaded.
254
255One important note is that the outer post_load() function is called "after"
256loading all subsections, because a newer subsection could change the same
257value that it uses.  A flag, and the combination of outer pre_load and
258post_load can be used to detect whether a subsection was loaded, and to
259fall back on default behaviour when the subsection isn't present.
260
261Example:
262
263.. code:: c
264
265  static bool ide_drive_pio_state_needed(void *opaque)
266  {
267      IDEState *s = opaque;
268
269      return ((s->status & DRQ_STAT) != 0)
270          || (s->bus->error_status & BM_STATUS_PIO_RETRY);
271  }
272
273  const VMStateDescription vmstate_ide_drive_pio_state = {
274      .name = "ide_drive/pio_state",
275      .version_id = 1,
276      .minimum_version_id = 1,
277      .pre_save = ide_drive_pio_pre_save,
278      .post_load = ide_drive_pio_post_load,
279      .needed = ide_drive_pio_state_needed,
280      .fields = (const VMStateField[]) {
281          VMSTATE_INT32(req_nb_sectors, IDEState),
282          VMSTATE_VARRAY_INT32(io_buffer, IDEState, io_buffer_total_len, 1,
283                               vmstate_info_uint8, uint8_t),
284          VMSTATE_INT32(cur_io_buffer_offset, IDEState),
285          VMSTATE_INT32(cur_io_buffer_len, IDEState),
286          VMSTATE_UINT8(end_transfer_fn_idx, IDEState),
287          VMSTATE_INT32(elementary_transfer_size, IDEState),
288          VMSTATE_INT32(packet_transfer_size, IDEState),
289          VMSTATE_END_OF_LIST()
290      }
291  };
292
293  const VMStateDescription vmstate_ide_drive = {
294      .name = "ide_drive",
295      .version_id = 3,
296      .minimum_version_id = 0,
297      .post_load = ide_drive_post_load,
298      .fields = (const VMStateField[]) {
299          .... several fields ....
300          VMSTATE_END_OF_LIST()
301      },
302      .subsections = (const VMStateDescription * const []) {
303          &vmstate_ide_drive_pio_state,
304          NULL
305      }
306  };
307
308Here we have a subsection for the pio state.  We only need to
309save/send this state when we are in the middle of a pio operation
310(that is what ``ide_drive_pio_state_needed()`` checks).  If DRQ_STAT is
311not enabled, the values on that fields are garbage and don't need to
312be sent.
313
314Connecting subsections to properties
315------------------------------------
316
317Using a condition function that checks a 'property' to determine whether
318to send a subsection allows backward migration compatibility when
319new subsections are added, especially when combined with versioned
320machine types.
321
322For example:
323
324   a) Add a new property using ``DEFINE_PROP_BOOL`` - e.g. support-foo and
325      default it to true.
326   b) Add an entry to the ``hw_compat_`` for the previous version that sets
327      the property to false.
328   c) Add a static bool  support_foo function that tests the property.
329   d) Add a subsection with a .needed set to the support_foo function
330   e) (potentially) Add an outer pre_load that sets up a default value
331      for 'foo' to be used if the subsection isn't loaded.
332
333Now that subsection will not be generated when using an older
334machine type and the migration stream will be accepted by older
335QEMU versions.
336
337Not sending existing elements
338-----------------------------
339
340Sometimes members of the VMState are no longer needed:
341
342  - removing them will break migration compatibility
343
344  - making them version dependent and bumping the version will break backward migration
345    compatibility.
346
347Adding a dummy field into the migration stream is normally the best way to preserve
348compatibility.
349
350If the field really does need to be removed then:
351
352  a) Add a new property/compatibility/function in the same way for subsections above.
353  b) replace the VMSTATE macro with the _TEST version of the macro, e.g.:
354
355   ``VMSTATE_UINT32(foo, barstruct)``
356
357   becomes
358
359   ``VMSTATE_UINT32_TEST(foo, barstruct, pre_version_baz)``
360
361   Sometime in the future when we no longer care about the ancient versions these can be killed off.
362   Note that for backward compatibility it's important to fill in the structure with
363   data that the destination will understand.
364
365Any difference in the predicates on the source and destination will end up
366with different fields being enabled and data being loaded into the wrong
367fields; for this reason conditional fields like this are very fragile.
368
369Versions
370--------
371
372Version numbers are intended for major incompatible changes to the
373migration of a device, and using them breaks backward-migration
374compatibility; in general most changes can be made by adding Subsections
375(see above) or _TEST macros (see above) which won't break compatibility.
376
377Each version is associated with a series of fields saved.  The ``save_state`` always saves
378the state as the newer version.  But ``load_state`` sometimes is able to
379load state from an older version.
380
381You can see that there are two version fields:
382
383- ``version_id``: the maximum version_id supported by VMState for that device.
384- ``minimum_version_id``: the minimum version_id that VMState is able to understand
385  for that device.
386
387VMState is able to read versions from minimum_version_id to version_id.
388
389There are *_V* forms of many ``VMSTATE_`` macros to load fields for version dependent fields,
390e.g.
391
392.. code:: c
393
394   VMSTATE_UINT16_V(ip_id, Slirp, 2),
395
396only loads that field for versions 2 and newer.
397
398Saving state will always create a section with the 'version_id' value
399and thus can't be loaded by any older QEMU.
400
401Massaging functions
402-------------------
403
404Sometimes, it is not enough to be able to save the state directly
405from one structure, we need to fill the correct values there.  One
406example is when we are using kvm.  Before saving the cpu state, we
407need to ask kvm to copy to QEMU the state that it is using.  And the
408opposite when we are loading the state, we need a way to tell kvm to
409load the state for the cpu that we have just loaded from the QEMUFile.
410
411The functions to do that are inside a vmstate definition, and are called:
412
413- ``int (*pre_load)(void *opaque);``
414
415  This function is called before we load the state of one device.
416
417- ``int (*post_load)(void *opaque, int version_id);``
418
419  This function is called after we load the state of one device.
420
421- ``int (*pre_save)(void *opaque);``
422
423  This function is called before we save the state of one device.
424
425- ``int (*post_save)(void *opaque);``
426
427  This function is called after we save the state of one device
428  (even upon failure, unless the call to pre_save returned an error).
429
430Example: You can look at hpet.c, that uses the first three functions
431to massage the state that is transferred.
432
433The ``VMSTATE_WITH_TMP`` macro may be useful when the migration
434data doesn't match the stored device data well; it allows an
435intermediate temporary structure to be populated with migration
436data and then transferred to the main structure.
437
438If you use memory or portio_list API functions that update memory layout outside
439initialization (i.e., in response to a guest action), this is a strong
440indication that you need to call these functions in a ``post_load`` callback.
441Examples of such API functions are:
442
443  - memory_region_add_subregion()
444  - memory_region_del_subregion()
445  - memory_region_set_readonly()
446  - memory_region_set_nonvolatile()
447  - memory_region_set_enabled()
448  - memory_region_set_address()
449  - memory_region_set_alias_offset()
450  - portio_list_set_address()
451  - portio_list_set_enabled()
452
453Iterative device migration
454--------------------------
455
456Some devices, such as RAM, Block storage or certain platform devices,
457have large amounts of data that would mean that the CPUs would be
458paused for too long if they were sent in one section.  For these
459devices an *iterative* approach is taken.
460
461The iterative devices generally don't use VMState macros
462(although it may be possible in some cases) and instead use
463qemu_put_*/qemu_get_* macros to read/write data to the stream.  Specialist
464versions exist for high bandwidth IO.
465
466
467An iterative device must provide:
468
469  - A ``save_setup`` function that initialises the data structures and
470    transmits a first section containing information on the device.  In the
471    case of RAM this transmits a list of RAMBlocks and sizes.
472
473  - A ``load_setup`` function that initialises the data structures on the
474    destination.
475
476  - A ``state_pending_exact`` function that indicates how much more
477    data we must save.  The core migration code will use this to
478    determine when to pause the CPUs and complete the migration.
479
480  - A ``state_pending_estimate`` function that indicates how much more
481    data we must save.  When the estimated amount is smaller than the
482    threshold, we call ``state_pending_exact``.
483
484  - A ``save_live_iterate`` function should send a chunk of data until
485    the point that stream bandwidth limits tell it to stop.  Each call
486    generates one section.
487
488  - A ``save_live_complete_precopy`` function that must transmit the
489    last section for the device containing any remaining data.
490
491  - A ``load_state`` function used to load sections generated by
492    any of the save functions that generate sections.
493
494  - ``cleanup`` functions for both save and load that are called
495    at the end of migration.
496
497Note that the contents of the sections for iterative migration tend
498to be open-coded by the devices; care should be taken in parsing
499the results and structuring the stream to make them easy to validate.
500
501Device ordering
502---------------
503
504There are cases in which the ordering of device loading matters; for
505example in some systems where a device may assert an interrupt during loading,
506if the interrupt controller is loaded later then it might lose the state.
507
508Some ordering is implicitly provided by the order in which the machine
509definition creates devices, however this is somewhat fragile.
510
511The ``MigrationPriority`` enum provides a means of explicitly enforcing
512ordering.  Numerically higher priorities are loaded earlier.
513The priority is set by setting the ``priority`` field of the top level
514``VMStateDescription`` for the device.
515
516Stream structure
517================
518
519The stream tries to be word and endian agnostic, allowing migration between hosts
520of different characteristics running the same VM.
521
522  - Header
523
524    - Magic
525    - Version
526    - VM configuration section
527
528       - Machine type
529       - Target page bits
530  - List of sections
531    Each section contains a device, or one iteration of a device save.
532
533    - section type
534    - section id
535    - ID string (First section of each device)
536    - instance id (First section of each device)
537    - version id (First section of each device)
538    - <device data>
539    - Footer mark
540  - EOF mark
541  - VM Description structure
542    Consisting of a JSON description of the contents for analysis only
543
544The ``device data`` in each section consists of the data produced
545by the code described above.  For non-iterative devices they have a single
546section; iterative devices have an initial and last section and a set
547of parts in between.
548Note that there is very little checking by the common code of the integrity
549of the ``device data`` contents, that's up to the devices themselves.
550The ``footer mark`` provides a little bit of protection for the case where
551the receiving side reads more or less data than expected.
552
553The ``ID string`` is normally unique, having been formed from a bus name
554and device address, PCI devices and storage devices hung off PCI controllers
555fit this pattern well.  Some devices are fixed single instances (e.g. "pc-ram").
556Others (especially either older devices or system devices which for
557some reason don't have a bus concept) make use of the ``instance id``
558for otherwise identically named devices.
559
560Return path
561-----------
562
563Only a unidirectional stream is required for normal migration, however a
564``return path`` can be created when bidirectional communication is desired.
565This is primarily used by postcopy, but is also used to return a success
566flag to the source at the end of migration.
567
568``qemu_file_get_return_path(QEMUFile* fwdpath)`` gives the QEMUFile* for the return
569path.
570
571  Source side
572
573     Forward path - written by migration thread
574     Return path  - opened by main thread, read by return-path thread
575
576  Destination side
577
578     Forward path - read by main thread
579     Return path  - opened by main thread, written by main thread AND postcopy
580     thread (protected by rp_mutex)
581
582