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