2
0

migration.rst 35 KB

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