main.rst 24 KB

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