util/uuid: Define UUID_STR_LEN from UUID_NONE string
[qemu/kevin.git] / docs / devel / migration.rst
blob240eb16d908786e5f9a3486e4972eb8f0a5e786c
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 .. contents::
33 Transports
34 ==========
36 The migration stream is normally just a byte stream that can be passed
37 over any transport.
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.
45 In addition, support is included for migration using RDMA, which
46 transports the page data using ``RDMA``, where the hardware takes care of
47 transporting the pages, and the load on the CPU is much lower.  While the
48 internals of RDMA migration are a bit different, this isn't really visible
49 outside the RAM migration code.
51 All these migration protocols use the same infrastructure to
52 save/restore state devices.  This infrastructure is shared with the
53 savevm/loadvm functionality.
55 Debugging
56 =========
58 The migration stream can be analyzed thanks to ``scripts/analyze-migration.py``.
60 Example usage:
62 .. code-block:: shell
64   $ qemu-system-x86_64 -display none -monitor stdio
65   (qemu) migrate "exec:cat > mig"
66   (qemu) q
67   $ ./scripts/analyze-migration.py -f mig
68   {
69     "ram (3)": {
70         "section sizes": {
71             "pc.ram": "0x0000000008000000",
72   ...
74 See also ``analyze-migration.py -h`` help for more options.
76 Common infrastructure
77 =====================
79 The files, sockets or fd's that carry the migration stream are abstracted by
80 the  ``QEMUFile`` type (see ``migration/qemu-file.h``).  In most cases this
81 is connected to a subtype of ``QIOChannel`` (see ``io/``).
84 Saving the state of one device
85 ==============================
87 For most devices, the state is saved in a single call to the migration
88 infrastructure; these are *non-iterative* devices.  The data for these
89 devices is sent at the end of precopy migration, when the CPUs are paused.
90 There are also *iterative* devices, which contain a very large amount of
91 data (e.g. RAM or large tables).  See the iterative device section below.
93 General advice for device developers
94 ------------------------------------
96 - The migration state saved should reflect the device being modelled rather
97   than the way your implementation works.  That way if you change the implementation
98   later the migration stream will stay compatible.  That model may include
99   internal state that's not directly visible in a register.
101 - When saving a migration stream the device code may walk and check
102   the state of the device.  These checks might fail in various ways (e.g.
103   discovering internal state is corrupt or that the guest has done something bad).
104   Consider carefully before asserting/aborting at this point, since the
105   normal response from users is that *migration broke their VM* since it had
106   apparently been running fine until then.  In these error cases, the device
107   should log a message indicating the cause of error, and should consider
108   putting the device into an error state, allowing the rest of the VM to
109   continue execution.
111 - The migration might happen at an inconvenient point,
112   e.g. right in the middle of the guest reprogramming the device, during
113   guest reboot or shutdown or while the device is waiting for external IO.
114   It's strongly preferred that migrations do not fail in this situation,
115   since in the cloud environment migrations might happen automatically to
116   VMs that the administrator doesn't directly control.
118 - If you do need to fail a migration, ensure that sufficient information
119   is logged to identify what went wrong.
121 - The destination should treat an incoming migration stream as hostile
122   (which we do to varying degrees in the existing code).  Check that offsets
123   into buffers and the like can't cause overruns.  Fail the incoming migration
124   in the case of a corrupted stream like this.
126 - Take care with internal device state or behaviour that might become
127   migration version dependent.  For example, the order of PCI capabilities
128   is required to stay constant across migration.  Another example would
129   be that a special case handled by subsections (see below) might become
130   much more common if a default behaviour is changed.
132 - The state of the source should not be changed or destroyed by the
133   outgoing migration.  Migrations timing out or being failed by
134   higher levels of management, or failures of the destination host are
135   not unusual, and in that case the VM is restarted on the source.
136   Note that the management layer can validly revert the migration
137   even though the QEMU level of migration has succeeded as long as it
138   does it before starting execution on the destination.
140 - Buses and devices should be able to explicitly specify addresses when
141   instantiated, and management tools should use those.  For example,
142   when hot adding USB devices it's important to specify the ports
143   and addresses, since implicit ordering based on the command line order
144   may be different on the destination.  This can result in the
145   device state being loaded into the wrong device.
147 VMState
148 -------
150 Most device data can be described using the ``VMSTATE`` macros (mostly defined
151 in ``include/migration/vmstate.h``).
153 An example (from hw/input/pckbd.c)
155 .. code:: c
157   static const VMStateDescription vmstate_kbd = {
158       .name = "pckbd",
159       .version_id = 3,
160       .minimum_version_id = 3,
161       .fields = (VMStateField[]) {
162           VMSTATE_UINT8(write_cmd, KBDState),
163           VMSTATE_UINT8(status, KBDState),
164           VMSTATE_UINT8(mode, KBDState),
165           VMSTATE_UINT8(pending, KBDState),
166           VMSTATE_END_OF_LIST()
167       }
168   };
170 We are declaring the state with name "pckbd".  The ``version_id`` is
171 3, and there are 4 uint8_t fields in the KBDState structure.  We
172 registered this ``VMSTATEDescription`` with one of the following
173 functions.  The first one will generate a device ``instance_id``
174 different for each registration.  Use the second one if you already
175 have an id that is different for each instance of the device:
177 .. code:: c
179     vmstate_register_any(NULL, &vmstate_kbd, s);
180     vmstate_register(NULL, instance_id, &vmstate_kbd, s);
182 For devices that are ``qdev`` based, we can register the device in the class
183 init function:
185 .. code:: c
187     dc->vmsd = &vmstate_kbd_isa;
189 The VMState macros take care of ensuring that the device data section
190 is formatted portably (normally big endian) and make some compile time checks
191 against the types of the fields in the structures.
193 VMState macros can include other VMStateDescriptions to store substructures
194 (see ``VMSTATE_STRUCT_``), arrays (``VMSTATE_ARRAY_``) and variable length
195 arrays (``VMSTATE_VARRAY_``).  Various other macros exist for special
196 cases.
198 Note that the format on the wire is still very raw; i.e. a VMSTATE_UINT32
199 ends up with a 4 byte bigendian representation on the wire; in the future
200 it might be possible to use a more structured format.
202 Legacy way
203 ----------
205 This way is going to disappear as soon as all current users are ported to VMSTATE;
206 although converting existing code can be tricky, and thus 'soon' is relative.
208 Each device has to register two functions, one to save the state and
209 another to load the state back.
211 .. code:: c
213   int register_savevm_live(const char *idstr,
214                            int instance_id,
215                            int version_id,
216                            SaveVMHandlers *ops,
217                            void *opaque);
219 Two functions in the ``ops`` structure are the ``save_state``
220 and ``load_state`` functions.  Notice that ``load_state`` receives a version_id
221 parameter to know what state format is receiving.  ``save_state`` doesn't
222 have a version_id parameter because it always uses the latest version.
224 Note that because the VMState macros still save the data in a raw
225 format, in many cases it's possible to replace legacy code
226 with a carefully constructed VMState description that matches the
227 byte layout of the existing code.
229 Changing migration data structures
230 ----------------------------------
232 When we migrate a device, we save/load the state as a series
233 of fields.  Sometimes, due to bugs or new functionality, we need to
234 change the state to store more/different information.  Changing the migration
235 state saved for a device can break migration compatibility unless
236 care is taken to use the appropriate techniques.  In general QEMU tries
237 to maintain forward migration compatibility (i.e. migrating from
238 QEMU n->n+1) and there are users who benefit from backward compatibility
239 as well.
241 Subsections
242 -----------
244 The most common structure change is adding new data, e.g. when adding
245 a newer form of device, or adding that state that you previously
246 forgot to migrate.  This is best solved using a subsection.
248 A subsection is "like" a device vmstate, but with a particularity, it
249 has a Boolean function that tells if that values are needed to be sent
250 or not.  If this functions returns false, the subsection is not sent.
251 Subsections have a unique name, that is looked for on the receiving
252 side.
254 On the receiving side, if we found a subsection for a device that we
255 don't understand, we just fail the migration.  If we understand all
256 the subsections, then we load the state with success.  There's no check
257 that a subsection is loaded, so a newer QEMU that knows about a subsection
258 can (with care) load a stream from an older QEMU that didn't send
259 the subsection.
261 If the new data is only needed in a rare case, then the subsection
262 can be made conditional on that case and the migration will still
263 succeed to older QEMUs in most cases.  This is OK for data that's
264 critical, but in some use cases it's preferred that the migration
265 should succeed even with the data missing.  To support this the
266 subsection can be connected to a device property and from there
267 to a versioned machine type.
269 The 'pre_load' and 'post_load' functions on subsections are only
270 called if the subsection is loaded.
272 One important note is that the outer post_load() function is called "after"
273 loading all subsections, because a newer subsection could change the same
274 value that it uses.  A flag, and the combination of outer pre_load and
275 post_load can be used to detect whether a subsection was loaded, and to
276 fall back on default behaviour when the subsection isn't present.
278 Example:
280 .. code:: c
282   static bool ide_drive_pio_state_needed(void *opaque)
283   {
284       IDEState *s = opaque;
286       return ((s->status & DRQ_STAT) != 0)
287           || (s->bus->error_status & BM_STATUS_PIO_RETRY);
288   }
290   const VMStateDescription vmstate_ide_drive_pio_state = {
291       .name = "ide_drive/pio_state",
292       .version_id = 1,
293       .minimum_version_id = 1,
294       .pre_save = ide_drive_pio_pre_save,
295       .post_load = ide_drive_pio_post_load,
296       .needed = ide_drive_pio_state_needed,
297       .fields = (VMStateField[]) {
298           VMSTATE_INT32(req_nb_sectors, IDEState),
299           VMSTATE_VARRAY_INT32(io_buffer, IDEState, io_buffer_total_len, 1,
300                                vmstate_info_uint8, uint8_t),
301           VMSTATE_INT32(cur_io_buffer_offset, IDEState),
302           VMSTATE_INT32(cur_io_buffer_len, IDEState),
303           VMSTATE_UINT8(end_transfer_fn_idx, IDEState),
304           VMSTATE_INT32(elementary_transfer_size, IDEState),
305           VMSTATE_INT32(packet_transfer_size, IDEState),
306           VMSTATE_END_OF_LIST()
307       }
308   };
310   const VMStateDescription vmstate_ide_drive = {
311       .name = "ide_drive",
312       .version_id = 3,
313       .minimum_version_id = 0,
314       .post_load = ide_drive_post_load,
315       .fields = (VMStateField[]) {
316           .... several fields ....
317           VMSTATE_END_OF_LIST()
318       },
319       .subsections = (const VMStateDescription*[]) {
320           &vmstate_ide_drive_pio_state,
321           NULL
322       }
323   };
325 Here we have a subsection for the pio state.  We only need to
326 save/send this state when we are in the middle of a pio operation
327 (that is what ``ide_drive_pio_state_needed()`` checks).  If DRQ_STAT is
328 not enabled, the values on that fields are garbage and don't need to
329 be sent.
331 Connecting subsections to properties
332 ------------------------------------
334 Using a condition function that checks a 'property' to determine whether
335 to send a subsection allows backward migration compatibility when
336 new subsections are added, especially when combined with versioned
337 machine types.
339 For example:
341    a) Add a new property using ``DEFINE_PROP_BOOL`` - e.g. support-foo and
342       default it to true.
343    b) Add an entry to the ``hw_compat_`` for the previous version that sets
344       the property to false.
345    c) Add a static bool  support_foo function that tests the property.
346    d) Add a subsection with a .needed set to the support_foo function
347    e) (potentially) Add an outer pre_load that sets up a default value
348       for 'foo' to be used if the subsection isn't loaded.
350 Now that subsection will not be generated when using an older
351 machine type and the migration stream will be accepted by older
352 QEMU versions.
354 Not sending existing elements
355 -----------------------------
357 Sometimes members of the VMState are no longer needed:
359   - removing them will break migration compatibility
361   - making them version dependent and bumping the version will break backward migration
362     compatibility.
364 Adding a dummy field into the migration stream is normally the best way to preserve
365 compatibility.
367 If the field really does need to be removed then:
369   a) Add a new property/compatibility/function in the same way for subsections above.
370   b) replace the VMSTATE macro with the _TEST version of the macro, e.g.:
372    ``VMSTATE_UINT32(foo, barstruct)``
374    becomes
376    ``VMSTATE_UINT32_TEST(foo, barstruct, pre_version_baz)``
378    Sometime in the future when we no longer care about the ancient versions these can be killed off.
379    Note that for backward compatibility it's important to fill in the structure with
380    data that the destination will understand.
382 Any difference in the predicates on the source and destination will end up
383 with different fields being enabled and data being loaded into the wrong
384 fields; for this reason conditional fields like this are very fragile.
386 Versions
387 --------
389 Version numbers are intended for major incompatible changes to the
390 migration of a device, and using them breaks backward-migration
391 compatibility; in general most changes can be made by adding Subsections
392 (see above) or _TEST macros (see above) which won't break compatibility.
394 Each version is associated with a series of fields saved.  The ``save_state`` always saves
395 the state as the newer version.  But ``load_state`` sometimes is able to
396 load state from an older version.
398 You can see that there are two version fields:
400 - ``version_id``: the maximum version_id supported by VMState for that device.
401 - ``minimum_version_id``: the minimum version_id that VMState is able to understand
402   for that device.
404 VMState is able to read versions from minimum_version_id to version_id.
406 There are *_V* forms of many ``VMSTATE_`` macros to load fields for version dependent fields,
407 e.g.
409 .. code:: c
411    VMSTATE_UINT16_V(ip_id, Slirp, 2),
413 only loads that field for versions 2 and newer.
415 Saving state will always create a section with the 'version_id' value
416 and thus can't be loaded by any older QEMU.
418 Massaging functions
419 -------------------
421 Sometimes, it is not enough to be able to save the state directly
422 from one structure, we need to fill the correct values there.  One
423 example is when we are using kvm.  Before saving the cpu state, we
424 need to ask kvm to copy to QEMU the state that it is using.  And the
425 opposite when we are loading the state, we need a way to tell kvm to
426 load the state for the cpu that we have just loaded from the QEMUFile.
428 The functions to do that are inside a vmstate definition, and are called:
430 - ``int (*pre_load)(void *opaque);``
432   This function is called before we load the state of one device.
434 - ``int (*post_load)(void *opaque, int version_id);``
436   This function is called after we load the state of one device.
438 - ``int (*pre_save)(void *opaque);``
440   This function is called before we save the state of one device.
442 - ``int (*post_save)(void *opaque);``
444   This function is called after we save the state of one device
445   (even upon failure, unless the call to pre_save returned an error).
447 Example: You can look at hpet.c, that uses the first three functions
448 to massage the state that is transferred.
450 The ``VMSTATE_WITH_TMP`` macro may be useful when the migration
451 data doesn't match the stored device data well; it allows an
452 intermediate temporary structure to be populated with migration
453 data and then transferred to the main structure.
455 If you use memory API functions that update memory layout outside
456 initialization (i.e., in response to a guest action), this is a strong
457 indication that you need to call these functions in a ``post_load`` callback.
458 Examples of such memory API functions are:
460   - memory_region_add_subregion()
461   - memory_region_del_subregion()
462   - memory_region_set_readonly()
463   - memory_region_set_nonvolatile()
464   - memory_region_set_enabled()
465   - memory_region_set_address()
466   - memory_region_set_alias_offset()
468 Iterative device migration
469 --------------------------
471 Some devices, such as RAM, Block storage or certain platform devices,
472 have large amounts of data that would mean that the CPUs would be
473 paused for too long if they were sent in one section.  For these
474 devices an *iterative* approach is taken.
476 The iterative devices generally don't use VMState macros
477 (although it may be possible in some cases) and instead use
478 qemu_put_*/qemu_get_* macros to read/write data to the stream.  Specialist
479 versions exist for high bandwidth IO.
482 An iterative device must provide:
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.
488   - A ``load_setup`` function that initialises the data structures on the
489     destination.
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.
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``.
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.
503   - A ``save_live_complete_precopy`` function that must transmit the
504     last section for the device containing any remaining data.
506   - A ``load_state`` function used to load sections generated by
507     any of the save functions that generate sections.
509   - ``cleanup`` functions for both save and load that are called
510     at the end of migration.
512 Note that the contents of the sections for iterative migration tend
513 to be open-coded by the devices; care should be taken in parsing
514 the results and structuring the stream to make them easy to validate.
516 Device ordering
517 ---------------
519 There are cases in which the ordering of device loading matters; for
520 example in some systems where a device may assert an interrupt during loading,
521 if the interrupt controller is loaded later then it might lose the state.
523 Some ordering is implicitly provided by the order in which the machine
524 definition creates devices, however this is somewhat fragile.
526 The ``MigrationPriority`` enum provides a means of explicitly enforcing
527 ordering.  Numerically higher priorities are loaded earlier.
528 The priority is set by setting the ``priority`` field of the top level
529 ``VMStateDescription`` for the device.
531 Stream structure
532 ================
534 The stream tries to be word and endian agnostic, allowing migration between hosts
535 of different characteristics running the same VM.
537   - Header
539     - Magic
540     - Version
541     - VM configuration section
543        - Machine type
544        - Target page bits
545   - List of sections
546     Each section contains a device, or one iteration of a device save.
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
559 The ``device data`` in each section consists of the data produced
560 by the code described above.  For non-iterative devices they have a single
561 section; iterative devices have an initial and last section and a set
562 of parts in between.
563 Note that there is very little checking by the common code of the integrity
564 of the ``device data`` contents, that's up to the devices themselves.
565 The ``footer mark`` provides a little bit of protection for the case where
566 the receiving side reads more or less data than expected.
568 The ``ID string`` is normally unique, having been formed from a bus name
569 and device address, PCI devices and storage devices hung off PCI controllers
570 fit this pattern well.  Some devices are fixed single instances (e.g. "pc-ram").
571 Others (especially either older devices or system devices which for
572 some reason don't have a bus concept) make use of the ``instance id``
573 for otherwise identically named devices.
575 Return path
576 -----------
578 Only a unidirectional stream is required for normal migration, however a
579 ``return path`` can be created when bidirectional communication is desired.
580 This is primarily used by postcopy, but is also used to return a success
581 flag to the source at the end of migration.
583 ``qemu_file_get_return_path(QEMUFile* fwdpath)`` gives the QEMUFile* for the return
584 path.
586   Source side
588      Forward path - written by migration thread
589      Return path  - opened by main thread, read by return-path thread
591   Destination side
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)
597 Postcopy
598 ========
600 'Postcopy' migration is a way to deal with migrations that refuse to converge
601 (or take too long to converge) its plus side is that there is an upper bound on
602 the amount of migration traffic and time it takes, the down side is that during
603 the postcopy phase, a failure of *either* side causes the guest to be lost.
605 In postcopy the destination CPUs are started before all the memory has been
606 transferred, and accesses to pages that are yet to be transferred cause
607 a fault that's translated by QEMU into a request to the source QEMU.
609 Postcopy can be combined with precopy (i.e. normal migration) so that if precopy
610 doesn't finish in a given time the switch is made to postcopy.
612 Enabling postcopy
613 -----------------
615 To enable postcopy, issue this command on the monitor (both source and
616 destination) prior to the start of migration:
618 ``migrate_set_capability postcopy-ram on``
620 The normal commands are then used to start a migration, which is still
621 started in precopy mode.  Issuing:
623 ``migrate_start_postcopy``
625 will now cause the transition from precopy to postcopy.
626 It can be issued immediately after migration is started or any
627 time later on.  Issuing it after the end of a migration is harmless.
629 Blocktime is a postcopy live migration metric, intended to show how
630 long the vCPU was in state of interruptible sleep due to pagefault.
631 That metric is calculated both for all vCPUs as overlapped value, and
632 separately for each vCPU. These values are calculated on destination
633 side.  To enable postcopy blocktime calculation, enter following
634 command on destination monitor:
636 ``migrate_set_capability postcopy-blocktime on``
638 Postcopy blocktime can be retrieved by query-migrate qmp command.
639 postcopy-blocktime value of qmp command will show overlapped blocking
640 time for all vCPU, postcopy-vcpu-blocktime will show list of blocking
641 time per vCPU.
643 .. note::
644   During the postcopy phase, the bandwidth limits set using
645   ``migrate_set_parameter`` is ignored (to avoid delaying requested pages that
646   the destination is waiting for).
648 Postcopy device transfer
649 ------------------------
651 Loading of device data may cause the device emulation to access guest RAM
652 that may trigger faults that have to be resolved by the source, as such
653 the migration stream has to be able to respond with page data *during* the
654 device load, and hence the device data has to be read from the stream completely
655 before the device load begins to free the stream up.  This is achieved by
656 'packaging' the device data into a blob that's read in one go.
658 Source behaviour
659 ----------------
661 Until postcopy is entered the migration stream is identical to normal
662 precopy, except for the addition of a 'postcopy advise' command at
663 the beginning, to tell the destination that postcopy might happen.
664 When postcopy starts the source sends the page discard data and then
665 forms the 'package' containing:
667    - Command: 'postcopy listen'
668    - The device state
670      A series of sections, identical to the precopy streams device state stream
671      containing everything except postcopiable devices (i.e. RAM)
672    - Command: 'postcopy run'
674 The 'package' is sent as the data part of a Command: ``CMD_PACKAGED``, and the
675 contents are formatted in the same way as the main migration stream.
677 During postcopy the source scans the list of dirty pages and sends them
678 to the destination without being requested (in much the same way as precopy),
679 however when a page request is received from the destination, the dirty page
680 scanning restarts from the requested location.  This causes requested pages
681 to be sent quickly, and also causes pages directly after the requested page
682 to be sent quickly in the hope that those pages are likely to be used
683 by the destination soon.
685 Destination behaviour
686 ---------------------
688 Initially the destination looks the same as precopy, with a single thread
689 reading the migration stream; the 'postcopy advise' and 'discard' commands
690 are processed to change the way RAM is managed, but don't affect the stream
691 processing.
695   ------------------------------------------------------------------------------
696                           1      2   3     4 5                      6   7
697   main -----DISCARD-CMD_PACKAGED ( LISTEN  DEVICE     DEVICE DEVICE RUN )
698   thread                             |       |
699                                      |     (page request)
700                                      |        \___
701                                      v            \
702   listen thread:                     --- page -- page -- page -- page -- page --
704                                      a   b        c
705   ------------------------------------------------------------------------------
707 - On receipt of ``CMD_PACKAGED`` (1)
709    All the data associated with the package - the ( ... ) section in the diagram -
710    is read into memory, and the main thread recurses into qemu_loadvm_state_main
711    to process the contents of the package (2) which contains commands (3,6) and
712    devices (4...)
714 - On receipt of 'postcopy listen' - 3 -(i.e. the 1st command in the package)
716    a new thread (a) is started that takes over servicing the migration stream,
717    while the main thread carries on loading the package.   It loads normal
718    background page data (b) but if during a device load a fault happens (5)
719    the returned page (c) is loaded by the listen thread allowing the main
720    threads device load to carry on.
722 - The last thing in the ``CMD_PACKAGED`` is a 'RUN' command (6)
724    letting the destination CPUs start running.  At the end of the
725    ``CMD_PACKAGED`` (7) the main thread returns to normal running behaviour and
726    is no longer used by migration, while the listen thread carries on servicing
727    page data until the end of migration.
729 Postcopy Recovery
730 -----------------
732 Comparing to precopy, postcopy is special on error handlings.  When any
733 error happens (in this case, mostly network errors), QEMU cannot easily
734 fail a migration because VM data resides in both source and destination
735 QEMU instances.  On the other hand, when issue happens QEMU on both sides
736 will go into a paused state.  It'll need a recovery phase to continue a
737 paused postcopy migration.
739 The recovery phase normally contains a few steps:
741   - When network issue occurs, both QEMU will go into PAUSED state
743   - When the network is recovered (or a new network is provided), the admin
744     can setup the new channel for migration using QMP command
745     'migrate-recover' on destination node, preparing for a resume.
747   - On source host, the admin can continue the interrupted postcopy
748     migration using QMP command 'migrate' with resume=true flag set.
750   - After the connection is re-established, QEMU will continue the postcopy
751     migration on both sides.
753 During a paused postcopy migration, the VM can logically still continue
754 running, and it will not be impacted from any page access to pages that
755 were already migrated to destination VM before the interruption happens.
756 However, if any of the missing pages got accessed on destination VM, the VM
757 thread will be halted waiting for the page to be migrated, it means it can
758 be halted until the recovery is complete.
760 The impact of accessing missing pages can be relevant to different
761 configurations of the guest.  For example, when with async page fault
762 enabled, logically the guest can proactively schedule out the threads
763 accessing missing pages.
765 Postcopy states
766 ---------------
768 Postcopy moves through a series of states (see postcopy_state) from
769 ADVISE->DISCARD->LISTEN->RUNNING->END
771  - Advise
773     Set at the start of migration if postcopy is enabled, even
774     if it hasn't had the start command; here the destination
775     checks that its OS has the support needed for postcopy, and performs
776     setup to ensure the RAM mappings are suitable for later postcopy.
777     The destination will fail early in migration at this point if the
778     required OS support is not present.
779     (Triggered by reception of POSTCOPY_ADVISE command)
781  - Discard
783     Entered on receipt of the first 'discard' command; prior to
784     the first Discard being performed, hugepages are switched off
785     (using madvise) to ensure that no new huge pages are created
786     during the postcopy phase, and to cause any huge pages that
787     have discards on them to be broken.
789  - Listen
791     The first command in the package, POSTCOPY_LISTEN, switches
792     the destination state to Listen, and starts a new thread
793     (the 'listen thread') which takes over the job of receiving
794     pages off the migration stream, while the main thread carries
795     on processing the blob.  With this thread able to process page
796     reception, the destination now 'sensitises' the RAM to detect
797     any access to missing pages (on Linux using the 'userfault'
798     system).
800  - Running
802     POSTCOPY_RUN causes the destination to synchronise all
803     state and start the CPUs and IO devices running.  The main
804     thread now finishes processing the migration package and
805     now carries on as it would for normal precopy migration
806     (although it can't do the cleanup it would do as it
807     finishes a normal migration).
809  - Paused
811     Postcopy can run into a paused state (normally on both sides when
812     happens), where all threads will be temporarily halted mostly due to
813     network errors.  When reaching paused state, migration will make sure
814     the qemu binary on both sides maintain the data without corrupting
815     the VM.  To continue the migration, the admin needs to fix the
816     migration channel using the QMP command 'migrate-recover' on the
817     destination node, then resume the migration using QMP command 'migrate'
818     again on source node, with resume=true flag set.
820  - End
822     The listen thread can now quit, and perform the cleanup of migration
823     state, the migration is now complete.
825 Source side page map
826 --------------------
828 The 'migration bitmap' in postcopy is basically the same as in the precopy,
829 where each of the bit to indicate that page is 'dirty' - i.e. needs
830 sending.  During the precopy phase this is updated as the CPU dirties
831 pages, however during postcopy the CPUs are stopped and nothing should
832 dirty anything any more. Instead, dirty bits are cleared when the relevant
833 pages are sent during postcopy.
835 Postcopy with hugepages
836 -----------------------
838 Postcopy now works with hugetlbfs backed memory:
840   a) The linux kernel on the destination must support userfault on hugepages.
841   b) The huge-page configuration on the source and destination VMs must be
842      identical; i.e. RAMBlocks on both sides must use the same page size.
843   c) Note that ``-mem-path /dev/hugepages``  will fall back to allocating normal
844      RAM if it doesn't have enough hugepages, triggering (b) to fail.
845      Using ``-mem-prealloc`` enforces the allocation using hugepages.
846   d) Care should be taken with the size of hugepage used; postcopy with 2MB
847      hugepages works well, however 1GB hugepages are likely to be problematic
848      since it takes ~1 second to transfer a 1GB hugepage across a 10Gbps link,
849      and until the full page is transferred the destination thread is blocked.
851 Postcopy with shared memory
852 ---------------------------
854 Postcopy migration with shared memory needs explicit support from the other
855 processes that share memory and from QEMU. There are restrictions on the type of
856 memory that userfault can support shared.
858 The Linux kernel userfault support works on ``/dev/shm`` memory and on ``hugetlbfs``
859 (although the kernel doesn't provide an equivalent to ``madvise(MADV_DONTNEED)``
860 for hugetlbfs which may be a problem in some configurations).
862 The vhost-user code in QEMU supports clients that have Postcopy support,
863 and the ``vhost-user-bridge`` (in ``tests/``) and the DPDK package have changes
864 to support postcopy.
866 The client needs to open a userfaultfd and register the areas
867 of memory that it maps with userfault.  The client must then pass the
868 userfaultfd back to QEMU together with a mapping table that allows
869 fault addresses in the clients address space to be converted back to
870 RAMBlock/offsets.  The client's userfaultfd is added to the postcopy
871 fault-thread and page requests are made on behalf of the client by QEMU.
872 QEMU performs 'wake' operations on the client's userfaultfd to allow it
873 to continue after a page has arrived.
875 .. note::
876   There are two future improvements that would be nice:
877     a) Some way to make QEMU ignorant of the addresses in the clients
878        address space
879     b) Avoiding the need for QEMU to perform ufd-wake calls after the
880        pages have arrived
882 Retro-fitting postcopy to existing clients is possible:
883   a) A mechanism is needed for the registration with userfault as above,
884      and the registration needs to be coordinated with the phases of
885      postcopy.  In vhost-user extra messages are added to the existing
886      control channel.
887   b) Any thread that can block due to guest memory accesses must be
888      identified and the implication understood; for example if the
889      guest memory access is made while holding a lock then all other
890      threads waiting for that lock will also be blocked.
892 Postcopy Preemption Mode
893 ------------------------
895 Postcopy preempt is a new capability introduced in 8.0 QEMU release, it
896 allows urgent pages (those got page fault requested from destination QEMU
897 explicitly) to be sent in a separate preempt channel, rather than queued in
898 the background migration channel.  Anyone who cares about latencies of page
899 faults during a postcopy migration should enable this feature.  By default,
900 it's not enabled.
902 Firmware
903 ========
905 Migration migrates the copies of RAM and ROM, and thus when running
906 on the destination it includes the firmware from the source. Even after
907 resetting a VM, the old firmware is used.  Only once QEMU has been restarted
908 is the new firmware in use.
910 - Changes in firmware size can cause changes in the required RAMBlock size
911   to hold the firmware and thus migration can fail.  In practice it's best
912   to pad firmware images to convenient powers of 2 with plenty of space
913   for growth.
915 - Care should be taken with device emulation code so that newer
916   emulation code can work with older firmware to allow forward migration.
918 - Care should be taken with newer firmware so that backward migration
919   to older systems with older device emulation code will work.
921 In some cases it may be best to tie specific firmware versions to specific
922 versioned machine types to cut down on the combinations that will need
923 support.  This is also useful when newer versions of firmware outgrow
924 the padding.
927 Backwards compatibility
928 =======================
930 How backwards compatibility works
931 ---------------------------------
933 When we do migration, we have two QEMU processes: the source and the
934 target.  There are two cases, they are the same version or they are
935 different versions.  The easy case is when they are the same version.
936 The difficult one is when they are different versions.
938 There are two things that are different, but they have very similar
939 names and sometimes get confused:
941 - QEMU version
942 - machine type version
944 Let's start with a practical example, we start with:
946 - qemu-system-x86_64 (v5.2), from now on qemu-5.2.
947 - qemu-system-x86_64 (v5.1), from now on qemu-5.1.
949 Related to this are the "latest" machine types defined on each of
950 them:
952 - pc-q35-5.2 (newer one in qemu-5.2) from now on pc-5.2
953 - pc-q35-5.1 (newer one in qemu-5.1) from now on pc-5.1
955 First of all, migration is only supposed to work if you use the same
956 machine type in both source and destination. The QEMU hardware
957 configuration needs to be the same also on source and destination.
958 Most aspects of the backend configuration can be changed at will,
959 except for a few cases where the backend features influence frontend
960 device feature exposure.  But that is not relevant for this section.
962 I am going to list the number of combinations that we can have.  Let's
963 start with the trivial ones, QEMU is the same on source and
964 destination:
966 1 - qemu-5.2 -M pc-5.2  -> migrates to -> qemu-5.2 -M pc-5.2
968   This is the latest QEMU with the latest machine type.
969   This have to work, and if it doesn't work it is a bug.
971 2 - qemu-5.1 -M pc-5.1  -> migrates to -> qemu-5.1 -M pc-5.1
973   Exactly the same case than the previous one, but for 5.1.
974   Nothing to see here either.
976 This are the easiest ones, we will not talk more about them in this
977 section.
979 Now we start with the more interesting cases.  Consider the case where
980 we have the same QEMU version in both sides (qemu-5.2) but we are using
981 the latest machine type for that version (pc-5.2) but one of an older
982 QEMU version, in this case pc-5.1.
984 3 - qemu-5.2 -M pc-5.1  -> migrates to -> qemu-5.2 -M pc-5.1
986   It needs to use the definition of pc-5.1 and the devices as they
987   were configured on 5.1, but this should be easy in the sense that
988   both sides are the same QEMU and both sides have exactly the same
989   idea of what the pc-5.1 machine is.
991 4 - qemu-5.1 -M pc-5.2  -> migrates to -> qemu-5.1 -M pc-5.2
993   This combination is not possible as the qemu-5.1 doen't understand
994   pc-5.2 machine type.  So nothing to worry here.
996 Now it comes the interesting ones, when both QEMU processes are
997 different.  Notice also that the machine type needs to be pc-5.1,
998 because we have the limitation than qemu-5.1 doesn't know pc-5.2.  So
999 the possible cases are:
1001 5 - qemu-5.2 -M pc-5.1  -> migrates to -> qemu-5.1 -M pc-5.1
1003   This migration is known as newer to older.  We need to make sure
1004   when we are developing 5.2 we need to take care about not to break
1005   migration to qemu-5.1.  Notice that we can't make updates to
1006   qemu-5.1 to understand whatever qemu-5.2 decides to change, so it is
1007   in qemu-5.2 side to make the relevant changes.
1009 6 - qemu-5.1 -M pc-5.1  -> migrates to -> qemu-5.2 -M pc-5.1
1011   This migration is known as older to newer.  We need to make sure
1012   than we are able to receive migrations from qemu-5.1. The problem is
1013   similar to the previous one.
1015 If qemu-5.1 and qemu-5.2 were the same, there will not be any
1016 compatibility problems.  But the reason that we create qemu-5.2 is to
1017 get new features, devices, defaults, etc.
1019 If we get a device that has a new feature, or change a default value,
1020 we have a problem when we try to migrate between different QEMU
1021 versions.
1023 So we need a way to tell qemu-5.2 that when we are using machine type
1024 pc-5.1, it needs to **not** use the feature, to be able to migrate to
1025 real qemu-5.1.
1027 And the equivalent part when migrating from qemu-5.1 to qemu-5.2.
1028 qemu-5.2 has to expect that it is not going to get data for the new
1029 feature, because qemu-5.1 doesn't know about it.
1031 How do we tell QEMU about these device feature changes?  In
1032 hw/core/machine.c:hw_compat_X_Y arrays.
1034 If we change a default value, we need to put back the old value on
1035 that array.  And the device, during initialization needs to look at
1036 that array to see what value it needs to get for that feature.  And
1037 what are we going to put in that array, the value of a property.
1039 To create a property for a device, we need to use one of the
1040 DEFINE_PROP_*() macros. See include/hw/qdev-properties.h to find the
1041 macros that exist.  With it, we set the default value for that
1042 property, and that is what it is going to get in the latest released
1043 version.  But if we want a different value for a previous version, we
1044 can change that in the hw_compat_X_Y arrays.
1046 hw_compat_X_Y is an array of registers that have the format:
1048 - name_device
1049 - name_property
1050 - value
1052 Let's see a practical example.
1054 In qemu-5.2 virtio-blk-device got multi queue support.  This is a
1055 change that is not backward compatible.  In qemu-5.1 it has one
1056 queue. In qemu-5.2 it has the same number of queues as the number of
1057 cpus in the system.
1059 When we are doing migration, if we migrate from a device that has 4
1060 queues to a device that have only one queue, we don't know where to
1061 put the extra information for the other 3 queues, and we fail
1062 migration.
1064 Similar problem when we migrate from qemu-5.1 that has only one queue
1065 to qemu-5.2, we only sent information for one queue, but destination
1066 has 4, and we have 3 queues that are not properly initialized and
1067 anything can happen.
1069 So, how can we address this problem.  Easy, just convince qemu-5.2
1070 that when it is running pc-5.1, it needs to set the number of queues
1071 for virtio-blk-devices to 1.
1073 That way we fix the cases 5 and 6.
1075 5 - qemu-5.2 -M pc-5.1  -> migrates to -> qemu-5.1 -M pc-5.1
1077     qemu-5.2 -M pc-5.1 sets number of queues to be 1.
1078     qemu-5.1 -M pc-5.1 expects number of queues to be 1.
1080     correct.  migration works.
1082 6 - qemu-5.1 -M pc-5.1  -> migrates to -> qemu-5.2 -M pc-5.1
1084     qemu-5.1 -M pc-5.1 sets number of queues to be 1.
1085     qemu-5.2 -M pc-5.1 expects number of queues to be 1.
1087     correct.  migration works.
1089 And now the other interesting case, case 3.  In this case we have:
1091 3 - qemu-5.2 -M pc-5.1  -> migrates to -> qemu-5.2 -M pc-5.1
1093     Here we have the same QEMU in both sides.  So it doesn't matter a
1094     lot if we have set the number of queues to 1 or not, because
1095     they are the same.
1097     WRONG!
1099     Think what happens if we do one of this double migrations:
1101     A -> migrates -> B -> migrates -> C
1103     where:
1105     A: qemu-5.1 -M pc-5.1
1106     B: qemu-5.2 -M pc-5.1
1107     C: qemu-5.2 -M pc-5.1
1109     migration A -> B is case 6, so number of queues needs to be 1.
1111     migration B -> C is case 3, so we don't care.  But actually we
1112     care because we haven't started the guest in qemu-5.2, it came
1113     migrated from qemu-5.1.  So to be in the safe place, we need to
1114     always use number of queues 1 when we are using pc-5.1.
1116 Now, how was this done in reality?  The following commit shows how it
1117 was done::
1119   commit 9445e1e15e66c19e42bea942ba810db28052cd05
1120   Author: Stefan Hajnoczi <stefanha@redhat.com>
1121   Date:   Tue Aug 18 15:33:47 2020 +0100
1123   virtio-blk-pci: default num_queues to -smp N
1125 The relevant parts for migration are::
1127     @@ -1281,7 +1284,8 @@ static Property virtio_blk_properties[] = {
1128      #endif
1129          DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
1130                          true),
1131     -    DEFINE_PROP_UINT16("num-queues", VirtIOBlock, conf.num_queues, 1),
1132     +    DEFINE_PROP_UINT16("num-queues", VirtIOBlock, conf.num_queues,
1133     +                       VIRTIO_BLK_AUTO_NUM_QUEUES),
1134          DEFINE_PROP_UINT16("queue-size", VirtIOBlock, conf.queue_size, 256),
1136 It changes the default value of num_queues.  But it fishes it for old
1137 machine types to have the right value::
1139     @@ -31,6 +31,7 @@
1140      GlobalProperty hw_compat_5_1[] = {
1141          ...
1142     +    { "virtio-blk-device", "num-queues", "1"},
1143          ...
1144      };
1146 A device with diferent features on both sides
1147 ---------------------------------------------
1149 Let's assume that we are using the same QEMU binary on both sides,
1150 just to make the things easier.  But we have a device that has
1151 different features on both sides of the migration.  That can be
1152 because the devices are different, because the kernel driver of both
1153 devices have different features, whatever.
1155 How can we get this to work with migration.  The way to do that is
1156 "theoretically" easy.  You have to get the features that the device
1157 has in the source of the migration.  The features that the device has
1158 on the target of the migration, you get the intersection of the
1159 features of both sides, and that is the way that you should launch
1160 QEMU.
1162 Notice that this is not completely related to QEMU.  The most
1163 important thing here is that this should be handled by the managing
1164 application that launches QEMU.  If QEMU is configured correctly, the
1165 migration will succeed.
1167 That said, actually doing it is complicated.  Almost all devices are
1168 bad at being able to be launched with only some features enabled.
1169 With one big exception: cpus.
1171 You can read the documentation for QEMU x86 cpu models here:
1173 https://qemu-project.gitlab.io/qemu/system/qemu-cpu-models.html
1175 See when they talk about migration they recommend that one chooses the
1176 newest cpu model that is supported for all cpus.
1178 Let's say that we have:
1180 Host A:
1182 Device X has the feature Y
1184 Host B:
1186 Device X has not the feature Y
1188 If we try to migrate without any care from host A to host B, it will
1189 fail because when migration tries to load the feature Y on
1190 destination, it will find that the hardware is not there.
1192 Doing this would be the equivalent of doing with cpus:
1194 Host A:
1196 $ qemu-system-x86_64 -cpu host
1198 Host B:
1200 $ qemu-system-x86_64 -cpu host
1202 When both hosts have different cpu features this is guaranteed to
1203 fail.  Especially if Host B has less features than host A.  If host A
1204 has less features than host B, sometimes it works.  Important word of
1205 last sentence is "sometimes".
1207 So, forgetting about cpu models and continuing with the -cpu host
1208 example, let's see that the differences of the cpus is that Host A and
1209 B have the following features:
1211 Features:   'pcid'  'stibp' 'taa-no'
1212 Host A:        X       X
1213 Host B:                        X
1215 And we want to migrate between them, the way configure both QEMU cpu
1216 will be:
1218 Host A:
1220 $ qemu-system-x86_64 -cpu host,pcid=off,stibp=off
1222 Host B:
1224 $ qemu-system-x86_64 -cpu host,taa-no=off
1226 And you would be able to migrate between them.  It is responsability
1227 of the management application or of the user to make sure that the
1228 configuration is correct.  QEMU doesn't know how to look at this kind
1229 of features in general.
1231 Notice that we don't recomend to use -cpu host for migration.  It is
1232 used in this example because it makes the example simpler.
1234 Other devices have worse control about individual features.  If they
1235 want to be able to migrate between hosts that show different features,
1236 the device needs a way to configure which ones it is going to use.
1238 In this section we have considered that we are using the same QEMU
1239 binary in both sides of the migration.  If we use different QEMU
1240 versions process, then we need to have into account all other
1241 differences and the examples become even more complicated.
1243 How to mitigate when we have a backward compatibility error
1244 -----------------------------------------------------------
1246 We broke migration for old machine types continuously during
1247 development.  But as soon as we find that there is a problem, we fix
1248 it.  The problem is what happens when we detect after we have done a
1249 release that something has gone wrong.
1251 Let see how it worked with one example.
1253 After the release of qemu-8.0 we found a problem when doing migration
1254 of the machine type pc-7.2.
1256 - $ qemu-7.2 -M pc-7.2  ->  qemu-7.2 -M pc-7.2
1258   This migration works
1260 - $ qemu-8.0 -M pc-7.2  ->  qemu-8.0 -M pc-7.2
1262   This migration works
1264 - $ qemu-8.0 -M pc-7.2  ->  qemu-7.2 -M pc-7.2
1266   This migration fails
1268 - $ qemu-7.2 -M pc-7.2  ->  qemu-8.0 -M pc-7.2
1270   This migration fails
1272 So clearly something fails when migration between qemu-7.2 and
1273 qemu-8.0 with machine type pc-7.2.  The error messages, and git bisect
1274 pointed to this commit.
1276 In qemu-8.0 we got this commit::
1278     commit 010746ae1db7f52700cb2e2c46eb94f299cfa0d2
1279     Author: Jonathan Cameron <Jonathan.Cameron@huawei.com>
1280     Date:   Thu Mar 2 13:37:02 2023 +0000
1282     hw/pci/aer: Implement PCI_ERR_UNCOR_MASK register
1285 The relevant bits of the commit for our example are this ones::
1287     --- a/hw/pci/pcie_aer.c
1288     +++ b/hw/pci/pcie_aer.c
1289     @@ -112,6 +112,10 @@ int pcie_aer_init(PCIDevice *dev,
1291          pci_set_long(dev->w1cmask + offset + PCI_ERR_UNCOR_STATUS,
1292                       PCI_ERR_UNC_SUPPORTED);
1293     +    pci_set_long(dev->config + offset + PCI_ERR_UNCOR_MASK,
1294     +                 PCI_ERR_UNC_MASK_DEFAULT);
1295     +    pci_set_long(dev->wmask + offset + PCI_ERR_UNCOR_MASK,
1296     +                 PCI_ERR_UNC_SUPPORTED);
1298          pci_set_long(dev->config + offset + PCI_ERR_UNCOR_SEVER,
1299                      PCI_ERR_UNC_SEVERITY_DEFAULT);
1301 The patch changes how we configure PCI space for AER.  But QEMU fails
1302 when the PCI space configuration is different between source and
1303 destination.
1305 The following commit shows how this got fixed::
1307     commit 5ed3dabe57dd9f4c007404345e5f5bf0e347317f
1308     Author: Leonardo Bras <leobras@redhat.com>
1309     Date:   Tue May 2 21:27:02 2023 -0300
1311     hw/pci: Disable PCI_ERR_UNCOR_MASK register for machine type < 8.0
1313     [...]
1315 The relevant parts of the fix in QEMU are as follow:
1317 First, we create a new property for the device to be able to configure
1318 the old behaviour or the new behaviour::
1320     diff --git a/hw/pci/pci.c b/hw/pci/pci.c
1321     index 8a87ccc8b0..5153ad63d6 100644
1322     --- a/hw/pci/pci.c
1323     +++ b/hw/pci/pci.c
1324     @@ -79,6 +79,8 @@ static Property pci_props[] = {
1325          DEFINE_PROP_STRING("failover_pair_id", PCIDevice,
1326                             failover_pair_id),
1327          DEFINE_PROP_UINT32("acpi-index",  PCIDevice, acpi_index, 0),
1328     +    DEFINE_PROP_BIT("x-pcie-err-unc-mask", PCIDevice, cap_present,
1329     +                    QEMU_PCIE_ERR_UNC_MASK_BITNR, true),
1330          DEFINE_PROP_END_OF_LIST()
1331      };
1333 Notice that we enable the feature for new machine types.
1335 Now we see how the fix is done.  This is going to depend on what kind
1336 of breakage happens, but in this case it is quite simple::
1338     diff --git a/hw/pci/pcie_aer.c b/hw/pci/pcie_aer.c
1339     index 103667c368..374d593ead 100644
1340     --- a/hw/pci/pcie_aer.c
1341     +++ b/hw/pci/pcie_aer.c
1342     @@ -112,10 +112,13 @@ int pcie_aer_init(PCIDevice *dev, uint8_t cap_ver,
1343     uint16_t offset,
1345          pci_set_long(dev->w1cmask + offset + PCI_ERR_UNCOR_STATUS,
1346                       PCI_ERR_UNC_SUPPORTED);
1347     -    pci_set_long(dev->config + offset + PCI_ERR_UNCOR_MASK,
1348     -                 PCI_ERR_UNC_MASK_DEFAULT);
1349     -    pci_set_long(dev->wmask + offset + PCI_ERR_UNCOR_MASK,
1350     -                 PCI_ERR_UNC_SUPPORTED);
1351     +
1352     +    if (dev->cap_present & QEMU_PCIE_ERR_UNC_MASK) {
1353     +        pci_set_long(dev->config + offset + PCI_ERR_UNCOR_MASK,
1354     +                     PCI_ERR_UNC_MASK_DEFAULT);
1355     +        pci_set_long(dev->wmask + offset + PCI_ERR_UNCOR_MASK,
1356     +                     PCI_ERR_UNC_SUPPORTED);
1357     +    }
1359          pci_set_long(dev->config + offset + PCI_ERR_UNCOR_SEVER,
1360                       PCI_ERR_UNC_SEVERITY_DEFAULT);
1362 I.e. If the property bit is enabled, we configure it as we did for
1363 qemu-8.0.  If the property bit is not set, we configure it as it was in 7.2.
1365 And now, everything that is missing is disabling the feature for old
1366 machine types::
1368     diff --git a/hw/core/machine.c b/hw/core/machine.c
1369     index 47a34841a5..07f763eb2e 100644
1370     --- a/hw/core/machine.c
1371     +++ b/hw/core/machine.c
1372     @@ -48,6 +48,7 @@ GlobalProperty hw_compat_7_2[] = {
1373          { "e1000e", "migrate-timadj", "off" },
1374          { "virtio-mem", "x-early-migration", "false" },
1375          { "migration", "x-preempt-pre-7-2", "true" },
1376     +    { TYPE_PCI_DEVICE, "x-pcie-err-unc-mask", "off" },
1377      };
1378      const size_t hw_compat_7_2_len = G_N_ELEMENTS(hw_compat_7_2);
1380 And now, when qemu-8.0.1 is released with this fix, all combinations
1381 are going to work as supposed.
1383 - $ qemu-7.2 -M pc-7.2  ->  qemu-7.2 -M pc-7.2 (works)
1384 - $ qemu-8.0.1 -M pc-7.2  ->  qemu-8.0.1 -M pc-7.2 (works)
1385 - $ qemu-8.0.1 -M pc-7.2  ->  qemu-7.2 -M pc-7.2 (works)
1386 - $ qemu-7.2 -M pc-7.2  ->  qemu-8.0.1 -M pc-7.2 (works)
1388 So the normality has been restored and everything is ok, no?
1390 Not really, now our matrix is much bigger.  We started with the easy
1391 cases, migration from the same version to the same version always
1392 works:
1394 - $ qemu-7.2 -M pc-7.2  ->  qemu-7.2 -M pc-7.2
1395 - $ qemu-8.0 -M pc-7.2  ->  qemu-8.0 -M pc-7.2
1396 - $ qemu-8.0.1 -M pc-7.2  ->  qemu-8.0.1 -M pc-7.2
1398 Now the interesting ones.  When the QEMU processes versions are
1399 different.  For the 1st set, their fail and we can do nothing, both
1400 versions are released and we can't change anything.
1402 - $ qemu-7.2 -M pc-7.2  ->  qemu-8.0 -M pc-7.2
1403 - $ qemu-8.0 -M pc-7.2  ->  qemu-7.2 -M pc-7.2
1405 This two are the ones that work. The whole point of making the
1406 change in qemu-8.0.1 release was to fix this issue:
1408 - $ qemu-7.2 -M pc-7.2  ->  qemu-8.0.1 -M pc-7.2
1409 - $ qemu-8.0.1 -M pc-7.2  ->  qemu-7.2 -M pc-7.2
1411 But now we found that qemu-8.0 neither can migrate to qemu-7.2 not
1412 qemu-8.0.1.
1414 - $ qemu-8.0 -M pc-7.2  ->  qemu-8.0.1 -M pc-7.2
1415 - $ qemu-8.0.1 -M pc-7.2  ->  qemu-8.0 -M pc-7.2
1417 So, if we start a pc-7.2 machine in qemu-8.0 we can't migrate it to
1418 anything except to qemu-8.0.
1420 Can we do better?
1422 Yeap.  If we know that we are going to do this migration:
1424 - $ qemu-8.0 -M pc-7.2  ->  qemu-8.0.1 -M pc-7.2
1426 We can launch the appropriate devices with::
1428   --device...,x-pci-e-err-unc-mask=on
1430 And now we can receive a migration from 8.0.  And from now on, we can
1431 do that migration to new machine types if we remember to enable that
1432 property for pc-7.2.  Notice that we need to remember, it is not
1433 enough to know that the source of the migration is qemu-8.0.  Think of
1434 this example:
1436 $ qemu-8.0 -M pc-7.2 -> qemu-8.0.1 -M pc-7.2 -> qemu-8.2 -M pc-7.2
1438 In the second migration, the source is not qemu-8.0, but we still have
1439 that "problem" and have that property enabled.  Notice that we need to
1440 continue having this mark/property until we have this machine
1441 rebooted.  But it is not a normal reboot (that don't reload QEMU) we
1442 need the machine to poweroff/poweron on a fixed QEMU.  And from now
1443 on we can use the proper real machine.