target/ppc: Add support for scv and rfscv instructions
[qemu/ar7.git] / docs / devel / migration.rst
blob2eb08624fc369ccf8852604b1ebbf83eb9ac3f39
1 =========
2 Migration
3 =========
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
9 state of each device.
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
20 another machine.
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).
31 Transports
32 ==========
34 The migration stream is normally just a byte stream that can be passed
35 over any transport.
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 a file descriptor that is
41   passed to QEMU.  QEMU doesn't care how this file descriptor is opened.
43 In addition, support is included for migration using RDMA, which
44 transports the page data using ``RDMA``, where the hardware takes care of
45 transporting the pages, and the load on the CPU is much lower.  While the
46 internals of RDMA migration are a bit different, this isn't really visible
47 outside the RAM migration code.
49 All these migration protocols use the same infrastructure to
50 save/restore state devices.  This infrastructure is shared with the
51 savevm/loadvm functionality.
53 Debugging
54 =========
56 The migration stream can be analyzed thanks to `scripts/analyze_migration.py`.
58 Example usage:
60 .. code-block:: shell
62   $ qemu-system-x86_64
63    (qemu) migrate "exec:cat > mig"
64   $ ./scripts/analyze_migration.py -f mig
65   {
66     "ram (3)": {
67         "section sizes": {
68             "pc.ram": "0x0000000008000000",
69   ...
71 See also ``analyze_migration.py -h`` help for more options.
73 Common infrastructure
74 =====================
76 The files, sockets or fd's that carry the migration stream are abstracted by
77 the  ``QEMUFile`` type (see `migration/qemu-file.h`).  In most cases this
78 is connected to a subtype of ``QIOChannel`` (see `io/`).
81 Saving the state of one device
82 ==============================
84 For most devices, the state is saved in a single call to the migration
85 infrastructure; these are *non-iterative* devices.  The data for these
86 devices is sent at the end of precopy migration, when the CPUs are paused.
87 There are also *iterative* devices, which contain a very large amount of
88 data (e.g. RAM or large tables).  See the iterative device section below.
90 General advice for device developers
91 ------------------------------------
93 - The migration state saved should reflect the device being modelled rather
94   than the way your implementation works.  That way if you change the implementation
95   later the migration stream will stay compatible.  That model may include
96   internal state that's not directly visible in a register.
98 - When saving a migration stream the device code may walk and check
99   the state of the device.  These checks might fail in various ways (e.g.
100   discovering internal state is corrupt or that the guest has done something bad).
101   Consider carefully before asserting/aborting at this point, since the
102   normal response from users is that *migration broke their VM* since it had
103   apparently been running fine until then.  In these error cases, the device
104   should log a message indicating the cause of error, and should consider
105   putting the device into an error state, allowing the rest of the VM to
106   continue execution.
108 - The migration might happen at an inconvenient point,
109   e.g. right in the middle of the guest reprogramming the device, during
110   guest reboot or shutdown or while the device is waiting for external IO.
111   It's strongly preferred that migrations do not fail in this situation,
112   since in the cloud environment migrations might happen automatically to
113   VMs that the administrator doesn't directly control.
115 - If you do need to fail a migration, ensure that sufficient information
116   is logged to identify what went wrong.
118 - The destination should treat an incoming migration stream as hostile
119   (which we do to varying degrees in the existing code).  Check that offsets
120   into buffers and the like can't cause overruns.  Fail the incoming migration
121   in the case of a corrupted stream like this.
123 - Take care with internal device state or behaviour that might become
124   migration version dependent.  For example, the order of PCI capabilities
125   is required to stay constant across migration.  Another example would
126   be that a special case handled by subsections (see below) might become
127   much more common if a default behaviour is changed.
129 - The state of the source should not be changed or destroyed by the
130   outgoing migration.  Migrations timing out or being failed by
131   higher levels of management, or failures of the destination host are
132   not unusual, and in that case the VM is restarted on the source.
133   Note that the management layer can validly revert the migration
134   even though the QEMU level of migration has succeeded as long as it
135   does it before starting execution on the destination.
137 - Buses and devices should be able to explicitly specify addresses when
138   instantiated, and management tools should use those.  For example,
139   when hot adding USB devices it's important to specify the ports
140   and addresses, since implicit ordering based on the command line order
141   may be different on the destination.  This can result in the
142   device state being loaded into the wrong device.
144 VMState
145 -------
147 Most device data can be described using the ``VMSTATE`` macros (mostly defined
148 in ``include/migration/vmstate.h``).
150 An example (from hw/input/pckbd.c)
152 .. code:: c
154   static const VMStateDescription vmstate_kbd = {
155       .name = "pckbd",
156       .version_id = 3,
157       .minimum_version_id = 3,
158       .fields = (VMStateField[]) {
159           VMSTATE_UINT8(write_cmd, KBDState),
160           VMSTATE_UINT8(status, KBDState),
161           VMSTATE_UINT8(mode, KBDState),
162           VMSTATE_UINT8(pending, KBDState),
163           VMSTATE_END_OF_LIST()
164       }
165   };
167 We are declaring the state with name "pckbd".
168 The `version_id` is 3, and the fields are 4 uint8_t in a KBDState structure.
169 We registered this with:
171 .. code:: c
173     vmstate_register(NULL, 0, &vmstate_kbd, s);
175 For devices that are `qdev` based, we can register the device in the class
176 init function:
178 .. code:: c
180     dc->vmsd = &vmstate_kbd_isa;
182 The VMState macros take care of ensuring that the device data section
183 is formatted portably (normally big endian) and make some compile time checks
184 against the types of the fields in the structures.
186 VMState macros can include other VMStateDescriptions to store substructures
187 (see ``VMSTATE_STRUCT_``), arrays (``VMSTATE_ARRAY_``) and variable length
188 arrays (``VMSTATE_VARRAY_``).  Various other macros exist for special
189 cases.
191 Note that the format on the wire is still very raw; i.e. a VMSTATE_UINT32
192 ends up with a 4 byte bigendian representation on the wire; in the future
193 it might be possible to use a more structured format.
195 Legacy way
196 ----------
198 This way is going to disappear as soon as all current users are ported to VMSTATE;
199 although converting existing code can be tricky, and thus 'soon' is relative.
201 Each device has to register two functions, one to save the state and
202 another to load the state back.
204 .. code:: c
206   int register_savevm_live(const char *idstr,
207                            int instance_id,
208                            int version_id,
209                            SaveVMHandlers *ops,
210                            void *opaque);
212 Two functions in the ``ops`` structure are the `save_state`
213 and `load_state` functions.  Notice that `load_state` receives a version_id
214 parameter to know what state format is receiving.  `save_state` doesn't
215 have a version_id parameter because it always uses the latest version.
217 Note that because the VMState macros still save the data in a raw
218 format, in many cases it's possible to replace legacy code
219 with a carefully constructed VMState description that matches the
220 byte layout of the existing code.
222 Changing migration data structures
223 ----------------------------------
225 When we migrate a device, we save/load the state as a series
226 of fields.  Sometimes, due to bugs or new functionality, we need to
227 change the state to store more/different information.  Changing the migration
228 state saved for a device can break migration compatibility unless
229 care is taken to use the appropriate techniques.  In general QEMU tries
230 to maintain forward migration compatibility (i.e. migrating from
231 QEMU n->n+1) and there are users who benefit from backward compatibility
232 as well.
234 Subsections
235 -----------
237 The most common structure change is adding new data, e.g. when adding
238 a newer form of device, or adding that state that you previously
239 forgot to migrate.  This is best solved using a subsection.
241 A subsection is "like" a device vmstate, but with a particularity, it
242 has a Boolean function that tells if that values are needed to be sent
243 or not.  If this functions returns false, the subsection is not sent.
244 Subsections have a unique name, that is looked for on the receiving
245 side.
247 On the receiving side, if we found a subsection for a device that we
248 don't understand, we just fail the migration.  If we understand all
249 the subsections, then we load the state with success.  There's no check
250 that a subsection is loaded, so a newer QEMU that knows about a subsection
251 can (with care) load a stream from an older QEMU that didn't send
252 the subsection.
254 If the new data is only needed in a rare case, then the subsection
255 can be made conditional on that case and the migration will still
256 succeed to older QEMUs in most cases.  This is OK for data that's
257 critical, but in some use cases it's preferred that the migration
258 should succeed even with the data missing.  To support this the
259 subsection can be connected to a device property and from there
260 to a versioned machine type.
262 The 'pre_load' and 'post_load' functions on subsections are only
263 called if the subsection is loaded.
265 One important note is that the outer post_load() function is called "after"
266 loading all subsections, because a newer subsection could change the same
267 value that it uses.  A flag, and the combination of outer pre_load and
268 post_load can be used to detect whether a subsection was loaded, and to
269 fall back on default behaviour when the subsection isn't present.
271 Example:
273 .. code:: c
275   static bool ide_drive_pio_state_needed(void *opaque)
276   {
277       IDEState *s = opaque;
279       return ((s->status & DRQ_STAT) != 0)
280           || (s->bus->error_status & BM_STATUS_PIO_RETRY);
281   }
283   const VMStateDescription vmstate_ide_drive_pio_state = {
284       .name = "ide_drive/pio_state",
285       .version_id = 1,
286       .minimum_version_id = 1,
287       .pre_save = ide_drive_pio_pre_save,
288       .post_load = ide_drive_pio_post_load,
289       .needed = ide_drive_pio_state_needed,
290       .fields = (VMStateField[]) {
291           VMSTATE_INT32(req_nb_sectors, IDEState),
292           VMSTATE_VARRAY_INT32(io_buffer, IDEState, io_buffer_total_len, 1,
293                                vmstate_info_uint8, uint8_t),
294           VMSTATE_INT32(cur_io_buffer_offset, IDEState),
295           VMSTATE_INT32(cur_io_buffer_len, IDEState),
296           VMSTATE_UINT8(end_transfer_fn_idx, IDEState),
297           VMSTATE_INT32(elementary_transfer_size, IDEState),
298           VMSTATE_INT32(packet_transfer_size, IDEState),
299           VMSTATE_END_OF_LIST()
300       }
301   };
303   const VMStateDescription vmstate_ide_drive = {
304       .name = "ide_drive",
305       .version_id = 3,
306       .minimum_version_id = 0,
307       .post_load = ide_drive_post_load,
308       .fields = (VMStateField[]) {
309           .... several fields ....
310           VMSTATE_END_OF_LIST()
311       },
312       .subsections = (const VMStateDescription*[]) {
313           &vmstate_ide_drive_pio_state,
314           NULL
315       }
316   };
318 Here we have a subsection for the pio state.  We only need to
319 save/send this state when we are in the middle of a pio operation
320 (that is what ``ide_drive_pio_state_needed()`` checks).  If DRQ_STAT is
321 not enabled, the values on that fields are garbage and don't need to
322 be sent.
324 Connecting subsections to properties
325 ------------------------------------
327 Using a condition function that checks a 'property' to determine whether
328 to send a subsection allows backward migration compatibility when
329 new subsections are added, especially when combined with versioned
330 machine types.
332 For example:
334    a) Add a new property using ``DEFINE_PROP_BOOL`` - e.g. support-foo and
335       default it to true.
336    b) Add an entry to the ``hw_compat_`` for the previous version that sets
337       the property to false.
338    c) Add a static bool  support_foo function that tests the property.
339    d) Add a subsection with a .needed set to the support_foo function
340    e) (potentially) Add an outer pre_load that sets up a default value
341       for 'foo' to be used if the subsection isn't loaded.
343 Now that subsection will not be generated when using an older
344 machine type and the migration stream will be accepted by older
345 QEMU versions.
347 Not sending existing elements
348 -----------------------------
350 Sometimes members of the VMState are no longer needed:
352   - removing them will break migration compatibility
354   - making them version dependent and bumping the version will break backward migration
355     compatibility.
357 Adding a dummy field into the migration stream is normally the best way to preserve
358 compatibility.
360 If the field really does need to be removed then:
362   a) Add a new property/compatibility/function in the same way for subsections above.
363   b) replace the VMSTATE macro with the _TEST version of the macro, e.g.:
365    ``VMSTATE_UINT32(foo, barstruct)``
367    becomes
369    ``VMSTATE_UINT32_TEST(foo, barstruct, pre_version_baz)``
371    Sometime in the future when we no longer care about the ancient versions these can be killed off.
372    Note that for backward compatibility it's important to fill in the structure with
373    data that the destination will understand.
375 Any difference in the predicates on the source and destination will end up
376 with different fields being enabled and data being loaded into the wrong
377 fields; for this reason conditional fields like this are very fragile.
379 Versions
380 --------
382 Version numbers are intended for major incompatible changes to the
383 migration of a device, and using them breaks backward-migration
384 compatibility; in general most changes can be made by adding Subsections
385 (see above) or _TEST macros (see above) which won't break compatibility.
387 Each version is associated with a series of fields saved.  The `save_state` always saves
388 the state as the newer version.  But `load_state` sometimes is able to
389 load state from an older version.
391 You can see that there are several version fields:
393 - `version_id`: the maximum version_id supported by VMState for that device.
394 - `minimum_version_id`: the minimum version_id that VMState is able to understand
395   for that device.
396 - `minimum_version_id_old`: For devices that were not able to port to vmstate, we can
397   assign a function that knows how to read this old state. This field is
398   ignored if there is no `load_state_old` handler.
400 VMState is able to read versions from minimum_version_id to
401 version_id.  And the function ``load_state_old()`` (if present) is able to
402 load state from minimum_version_id_old to minimum_version_id.  This
403 function is deprecated and will be removed when no more users are left.
405 There are *_V* forms of many ``VMSTATE_`` macros to load fields for version dependent fields,
406 e.g.
408 .. code:: c
410    VMSTATE_UINT16_V(ip_id, Slirp, 2),
412 only loads that field for versions 2 and newer.
414 Saving state will always create a section with the 'version_id' value
415 and thus can't be loaded by any older QEMU.
417 Massaging functions
418 -------------------
420 Sometimes, it is not enough to be able to save the state directly
421 from one structure, we need to fill the correct values there.  One
422 example is when we are using kvm.  Before saving the cpu state, we
423 need to ask kvm to copy to QEMU the state that it is using.  And the
424 opposite when we are loading the state, we need a way to tell kvm to
425 load the state for the cpu that we have just loaded from the QEMUFile.
427 The functions to do that are inside a vmstate definition, and are called:
429 - ``int (*pre_load)(void *opaque);``
431   This function is called before we load the state of one device.
433 - ``int (*post_load)(void *opaque, int version_id);``
435   This function is called after we load the state of one device.
437 - ``int (*pre_save)(void *opaque);``
439   This function is called before we save the state of one device.
441 - ``int (*post_save)(void *opaque);``
443   This function is called after we save the state of one device
444   (even upon failure, unless the call to pre_save returned an error).
446 Example: You can look at hpet.c, that uses the first three functions
447 to massage the state that is transferred.
449 The ``VMSTATE_WITH_TMP`` macro may be useful when the migration
450 data doesn't match the stored device data well; it allows an
451 intermediate temporary structure to be populated with migration
452 data and then transferred to the main structure.
454 If you use memory API functions that update memory layout outside
455 initialization (i.e., in response to a guest action), this is a strong
456 indication that you need to call these functions in a `post_load` callback.
457 Examples of such memory API functions are:
459   - memory_region_add_subregion()
460   - memory_region_del_subregion()
461   - memory_region_set_readonly()
462   - memory_region_set_nonvolatile()
463   - memory_region_set_enabled()
464   - memory_region_set_address()
465   - memory_region_set_alias_offset()
467 Iterative device migration
468 --------------------------
470 Some devices, such as RAM, Block storage or certain platform devices,
471 have large amounts of data that would mean that the CPUs would be
472 paused for too long if they were sent in one section.  For these
473 devices an *iterative* approach is taken.
475 The iterative devices generally don't use VMState macros
476 (although it may be possible in some cases) and instead use
477 qemu_put_*/qemu_get_* macros to read/write data to the stream.  Specialist
478 versions exist for high bandwidth IO.
481 An iterative device must provide:
483   - A ``save_setup`` function that initialises the data structures and
484     transmits a first section containing information on the device.  In the
485     case of RAM this transmits a list of RAMBlocks and sizes.
487   - A ``load_setup`` function that initialises the data structures on the
488     destination.
490   - A ``save_live_pending`` function that is called repeatedly and must
491     indicate how much more data the iterative data must save.  The core
492     migration code will use this to determine when to pause the CPUs
493     and complete the migration.
495   - A ``save_live_iterate`` function (called after ``save_live_pending``
496     when there is significant data still to be sent).  It should send
497     a chunk of data until the point that stream bandwidth limits tell it
498     to stop.  Each call generates one section.
500   - A ``save_live_complete_precopy`` function that must transmit the
501     last section for the device containing any remaining data.
503   - A ``load_state`` function used to load sections generated by
504     any of the save functions that generate sections.
506   - ``cleanup`` functions for both save and load that are called
507     at the end of migration.
509 Note that the contents of the sections for iterative migration tend
510 to be open-coded by the devices; care should be taken in parsing
511 the results and structuring the stream to make them easy to validate.
513 Device ordering
514 ---------------
516 There are cases in which the ordering of device loading matters; for
517 example in some systems where a device may assert an interrupt during loading,
518 if the interrupt controller is loaded later then it might lose the state.
520 Some ordering is implicitly provided by the order in which the machine
521 definition creates devices, however this is somewhat fragile.
523 The ``MigrationPriority`` enum provides a means of explicitly enforcing
524 ordering.  Numerically higher priorities are loaded earlier.
525 The priority is set by setting the ``priority`` field of the top level
526 ``VMStateDescription`` for the device.
528 Stream structure
529 ================
531 The stream tries to be word and endian agnostic, allowing migration between hosts
532 of different characteristics running the same VM.
534   - Header
536     - Magic
537     - Version
538     - VM configuration section
540        - Machine type
541        - Target page bits
542   - List of sections
543     Each section contains a device, or one iteration of a device save.
545     - section type
546     - section id
547     - ID string (First section of each device)
548     - instance id (First section of each device)
549     - version id (First section of each device)
550     - <device data>
551     - Footer mark
552   - EOF mark
553   - VM Description structure
554     Consisting of a JSON description of the contents for analysis only
556 The ``device data`` in each section consists of the data produced
557 by the code described above.  For non-iterative devices they have a single
558 section; iterative devices have an initial and last section and a set
559 of parts in between.
560 Note that there is very little checking by the common code of the integrity
561 of the ``device data`` contents, that's up to the devices themselves.
562 The ``footer mark`` provides a little bit of protection for the case where
563 the receiving side reads more or less data than expected.
565 The ``ID string`` is normally unique, having been formed from a bus name
566 and device address, PCI devices and storage devices hung off PCI controllers
567 fit this pattern well.  Some devices are fixed single instances (e.g. "pc-ram").
568 Others (especially either older devices or system devices which for
569 some reason don't have a bus concept) make use of the ``instance id``
570 for otherwise identically named devices.
572 Return path
573 -----------
575 Only a unidirectional stream is required for normal migration, however a
576 ``return path`` can be created when bidirectional communication is desired.
577 This is primarily used by postcopy, but is also used to return a success
578 flag to the source at the end of migration.
580 ``qemu_file_get_return_path(QEMUFile* fwdpath)`` gives the QEMUFile* for the return
581 path.
583   Source side
585      Forward path - written by migration thread
586      Return path  - opened by main thread, read by return-path thread
588   Destination side
590      Forward path - read by main thread
591      Return path  - opened by main thread, written by main thread AND postcopy
592      thread (protected by rp_mutex)
594 Postcopy
595 ========
597 'Postcopy' migration is a way to deal with migrations that refuse to converge
598 (or take too long to converge) its plus side is that there is an upper bound on
599 the amount of migration traffic and time it takes, the down side is that during
600 the postcopy phase, a failure of *either* side or the network connection causes
601 the guest to be lost.
603 In postcopy the destination CPUs are started before all the memory has been
604 transferred, and accesses to pages that are yet to be transferred cause
605 a fault that's translated by QEMU into a request to the source QEMU.
607 Postcopy can be combined with precopy (i.e. normal migration) so that if precopy
608 doesn't finish in a given time the switch is made to postcopy.
610 Enabling postcopy
611 -----------------
613 To enable postcopy, issue this command on the monitor (both source and
614 destination) prior to the start of migration:
616 ``migrate_set_capability postcopy-ram on``
618 The normal commands are then used to start a migration, which is still
619 started in precopy mode.  Issuing:
621 ``migrate_start_postcopy``
623 will now cause the transition from precopy to postcopy.
624 It can be issued immediately after migration is started or any
625 time later on.  Issuing it after the end of a migration is harmless.
627 Blocktime is a postcopy live migration metric, intended to show how
628 long the vCPU was in state of interruptable sleep due to pagefault.
629 That metric is calculated both for all vCPUs as overlapped value, and
630 separately for each vCPU. These values are calculated on destination
631 side.  To enable postcopy blocktime calculation, enter following
632 command on destination monitor:
634 ``migrate_set_capability postcopy-blocktime on``
636 Postcopy blocktime can be retrieved by query-migrate qmp command.
637 postcopy-blocktime value of qmp command will show overlapped blocking
638 time for all vCPU, postcopy-vcpu-blocktime will show list of blocking
639 time per vCPU.
641 .. note::
642   During the postcopy phase, the bandwidth limits set using
643   ``migrate_set_speed`` is ignored (to avoid delaying requested pages that
644   the destination is waiting for).
646 Postcopy device transfer
647 ------------------------
649 Loading of device data may cause the device emulation to access guest RAM
650 that may trigger faults that have to be resolved by the source, as such
651 the migration stream has to be able to respond with page data *during* the
652 device load, and hence the device data has to be read from the stream completely
653 before the device load begins to free the stream up.  This is achieved by
654 'packaging' the device data into a blob that's read in one go.
656 Source behaviour
657 ----------------
659 Until postcopy is entered the migration stream is identical to normal
660 precopy, except for the addition of a 'postcopy advise' command at
661 the beginning, to tell the destination that postcopy might happen.
662 When postcopy starts the source sends the page discard data and then
663 forms the 'package' containing:
665    - Command: 'postcopy listen'
666    - The device state
668      A series of sections, identical to the precopy streams device state stream
669      containing everything except postcopiable devices (i.e. RAM)
670    - Command: 'postcopy run'
672 The 'package' is sent as the data part of a Command: ``CMD_PACKAGED``, and the
673 contents are formatted in the same way as the main migration stream.
675 During postcopy the source scans the list of dirty pages and sends them
676 to the destination without being requested (in much the same way as precopy),
677 however when a page request is received from the destination, the dirty page
678 scanning restarts from the requested location.  This causes requested pages
679 to be sent quickly, and also causes pages directly after the requested page
680 to be sent quickly in the hope that those pages are likely to be used
681 by the destination soon.
683 Destination behaviour
684 ---------------------
686 Initially the destination looks the same as precopy, with a single thread
687 reading the migration stream; the 'postcopy advise' and 'discard' commands
688 are processed to change the way RAM is managed, but don't affect the stream
689 processing.
693   ------------------------------------------------------------------------------
694                           1      2   3     4 5                      6   7
695   main -----DISCARD-CMD_PACKAGED ( LISTEN  DEVICE     DEVICE DEVICE RUN )
696   thread                             |       |
697                                      |     (page request)
698                                      |        \___
699                                      v            \
700   listen thread:                     --- page -- page -- page -- page -- page --
702                                      a   b        c
703   ------------------------------------------------------------------------------
705 - On receipt of ``CMD_PACKAGED`` (1)
707    All the data associated with the package - the ( ... ) section in the diagram -
708    is read into memory, and the main thread recurses into qemu_loadvm_state_main
709    to process the contents of the package (2) which contains commands (3,6) and
710    devices (4...)
712 - On receipt of 'postcopy listen' - 3 -(i.e. the 1st command in the package)
714    a new thread (a) is started that takes over servicing the migration stream,
715    while the main thread carries on loading the package.   It loads normal
716    background page data (b) but if during a device load a fault happens (5)
717    the returned page (c) is loaded by the listen thread allowing the main
718    threads device load to carry on.
720 - The last thing in the ``CMD_PACKAGED`` is a 'RUN' command (6)
722    letting the destination CPUs start running.  At the end of the
723    ``CMD_PACKAGED`` (7) the main thread returns to normal running behaviour and
724    is no longer used by migration, while the listen thread carries on servicing
725    page data until the end of migration.
727 Postcopy states
728 ---------------
730 Postcopy moves through a series of states (see postcopy_state) from
731 ADVISE->DISCARD->LISTEN->RUNNING->END
733  - Advise
735     Set at the start of migration if postcopy is enabled, even
736     if it hasn't had the start command; here the destination
737     checks that its OS has the support needed for postcopy, and performs
738     setup to ensure the RAM mappings are suitable for later postcopy.
739     The destination will fail early in migration at this point if the
740     required OS support is not present.
741     (Triggered by reception of POSTCOPY_ADVISE command)
743  - Discard
745     Entered on receipt of the first 'discard' command; prior to
746     the first Discard being performed, hugepages are switched off
747     (using madvise) to ensure that no new huge pages are created
748     during the postcopy phase, and to cause any huge pages that
749     have discards on them to be broken.
751  - Listen
753     The first command in the package, POSTCOPY_LISTEN, switches
754     the destination state to Listen, and starts a new thread
755     (the 'listen thread') which takes over the job of receiving
756     pages off the migration stream, while the main thread carries
757     on processing the blob.  With this thread able to process page
758     reception, the destination now 'sensitises' the RAM to detect
759     any access to missing pages (on Linux using the 'userfault'
760     system).
762  - Running
764     POSTCOPY_RUN causes the destination to synchronise all
765     state and start the CPUs and IO devices running.  The main
766     thread now finishes processing the migration package and
767     now carries on as it would for normal precopy migration
768     (although it can't do the cleanup it would do as it
769     finishes a normal migration).
771  - End
773     The listen thread can now quit, and perform the cleanup of migration
774     state, the migration is now complete.
776 Source side page maps
777 ---------------------
779 The source side keeps two bitmaps during postcopy; 'the migration bitmap'
780 and 'unsent map'.  The 'migration bitmap' is basically the same as in
781 the precopy case, and holds a bit to indicate that page is 'dirty' -
782 i.e. needs sending.  During the precopy phase this is updated as the CPU
783 dirties pages, however during postcopy the CPUs are stopped and nothing
784 should dirty anything any more.
786 The 'unsent map' is used for the transition to postcopy. It is a bitmap that
787 has a bit cleared whenever a page is sent to the destination, however during
788 the transition to postcopy mode it is combined with the migration bitmap
789 to form a set of pages that:
791    a) Have been sent but then redirtied (which must be discarded)
792    b) Have not yet been sent - which also must be discarded to cause any
793       transparent huge pages built during precopy to be broken.
795 Note that the contents of the unsentmap are sacrificed during the calculation
796 of the discard set and thus aren't valid once in postcopy.  The dirtymap
797 is still valid and is used to ensure that no page is sent more than once.  Any
798 request for a page that has already been sent is ignored.  Duplicate requests
799 such as this can happen as a page is sent at about the same time the
800 destination accesses it.
802 Postcopy with hugepages
803 -----------------------
805 Postcopy now works with hugetlbfs backed memory:
807   a) The linux kernel on the destination must support userfault on hugepages.
808   b) The huge-page configuration on the source and destination VMs must be
809      identical; i.e. RAMBlocks on both sides must use the same page size.
810   c) Note that ``-mem-path /dev/hugepages``  will fall back to allocating normal
811      RAM if it doesn't have enough hugepages, triggering (b) to fail.
812      Using ``-mem-prealloc`` enforces the allocation using hugepages.
813   d) Care should be taken with the size of hugepage used; postcopy with 2MB
814      hugepages works well, however 1GB hugepages are likely to be problematic
815      since it takes ~1 second to transfer a 1GB hugepage across a 10Gbps link,
816      and until the full page is transferred the destination thread is blocked.
818 Postcopy with shared memory
819 ---------------------------
821 Postcopy migration with shared memory needs explicit support from the other
822 processes that share memory and from QEMU. There are restrictions on the type of
823 memory that userfault can support shared.
825 The Linux kernel userfault support works on `/dev/shm` memory and on `hugetlbfs`
826 (although the kernel doesn't provide an equivalent to `madvise(MADV_DONTNEED)`
827 for hugetlbfs which may be a problem in some configurations).
829 The vhost-user code in QEMU supports clients that have Postcopy support,
830 and the `vhost-user-bridge` (in `tests/`) and the DPDK package have changes
831 to support postcopy.
833 The client needs to open a userfaultfd and register the areas
834 of memory that it maps with userfault.  The client must then pass the
835 userfaultfd back to QEMU together with a mapping table that allows
836 fault addresses in the clients address space to be converted back to
837 RAMBlock/offsets.  The client's userfaultfd is added to the postcopy
838 fault-thread and page requests are made on behalf of the client by QEMU.
839 QEMU performs 'wake' operations on the client's userfaultfd to allow it
840 to continue after a page has arrived.
842 .. note::
843   There are two future improvements that would be nice:
844     a) Some way to make QEMU ignorant of the addresses in the clients
845        address space
846     b) Avoiding the need for QEMU to perform ufd-wake calls after the
847        pages have arrived
849 Retro-fitting postcopy to existing clients is possible:
850   a) A mechanism is needed for the registration with userfault as above,
851      and the registration needs to be coordinated with the phases of
852      postcopy.  In vhost-user extra messages are added to the existing
853      control channel.
854   b) Any thread that can block due to guest memory accesses must be
855      identified and the implication understood; for example if the
856      guest memory access is made while holding a lock then all other
857      threads waiting for that lock will also be blocked.
859 Firmware
860 ========
862 Migration migrates the copies of RAM and ROM, and thus when running
863 on the destination it includes the firmware from the source. Even after
864 resetting a VM, the old firmware is used.  Only once QEMU has been restarted
865 is the new firmware in use.
867 - Changes in firmware size can cause changes in the required RAMBlock size
868   to hold the firmware and thus migration can fail.  In practice it's best
869   to pad firmware images to convenient powers of 2 with plenty of space
870   for growth.
872 - Care should be taken with device emulation code so that newer
873   emulation code can work with older firmware to allow forward migration.
875 - Care should be taken with newer firmware so that backward migration
876   to older systems with older device emulation code will work.
878 In some cases it may be best to tie specific firmware versions to specific
879 versioned machine types to cut down on the combinations that will need
880 support.  This is also useful when newer versions of firmware outgrow
881 the padding.