main.rst 24 KB

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