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