migration.c 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042
  1. /*
  2. * QEMU live migration
  3. *
  4. * Copyright IBM, Corp. 2008
  5. *
  6. * Authors:
  7. * Anthony Liguori <aliguori@us.ibm.com>
  8. *
  9. * This work is licensed under the terms of the GNU GPL, version 2. See
  10. * the COPYING file in the top-level directory.
  11. *
  12. * Contributions after 2012-01-13 are licensed under the terms of the
  13. * GNU GPL, version 2 or (at your option) any later version.
  14. */
  15. #include "qemu/osdep.h"
  16. #include "qemu/ctype.h"
  17. #include "qemu/cutils.h"
  18. #include "qemu/error-report.h"
  19. #include "qemu/main-loop.h"
  20. #include "migration/blocker.h"
  21. #include "exec.h"
  22. #include "fd.h"
  23. #include "file.h"
  24. #include "socket.h"
  25. #include "system/runstate.h"
  26. #include "system/system.h"
  27. #include "system/cpu-throttle.h"
  28. #include "rdma.h"
  29. #include "ram.h"
  30. #include "migration/cpr.h"
  31. #include "migration/global_state.h"
  32. #include "migration/misc.h"
  33. #include "migration.h"
  34. #include "migration-stats.h"
  35. #include "savevm.h"
  36. #include "qemu-file.h"
  37. #include "channel.h"
  38. #include "migration/vmstate.h"
  39. #include "block/block.h"
  40. #include "qapi/error.h"
  41. #include "qapi/clone-visitor.h"
  42. #include "qapi/qapi-visit-migration.h"
  43. #include "qapi/qapi-visit-sockets.h"
  44. #include "qapi/qapi-commands-migration.h"
  45. #include "qapi/qapi-events-migration.h"
  46. #include "qapi/qmp/qerror.h"
  47. #include "qobject/qnull.h"
  48. #include "qemu/rcu.h"
  49. #include "postcopy-ram.h"
  50. #include "qemu/thread.h"
  51. #include "trace.h"
  52. #include "exec/target_page.h"
  53. #include "io/channel-buffer.h"
  54. #include "io/channel-tls.h"
  55. #include "migration/colo.h"
  56. #include "hw/boards.h"
  57. #include "monitor/monitor.h"
  58. #include "net/announce.h"
  59. #include "qemu/queue.h"
  60. #include "multifd.h"
  61. #include "threadinfo.h"
  62. #include "qemu/yank.h"
  63. #include "system/cpus.h"
  64. #include "yank_functions.h"
  65. #include "system/qtest.h"
  66. #include "options.h"
  67. #include "system/dirtylimit.h"
  68. #include "qemu/sockets.h"
  69. #include "system/kvm.h"
  70. #define NOTIFIER_ELEM_INIT(array, elem) \
  71. [elem] = NOTIFIER_WITH_RETURN_LIST_INITIALIZER((array)[elem])
  72. #define INMIGRATE_DEFAULT_EXIT_ON_ERROR true
  73. static NotifierWithReturnList migration_state_notifiers[] = {
  74. NOTIFIER_ELEM_INIT(migration_state_notifiers, MIG_MODE_NORMAL),
  75. NOTIFIER_ELEM_INIT(migration_state_notifiers, MIG_MODE_CPR_REBOOT),
  76. NOTIFIER_ELEM_INIT(migration_state_notifiers, MIG_MODE_CPR_TRANSFER),
  77. };
  78. /* Messages sent on the return path from destination to source */
  79. enum mig_rp_message_type {
  80. MIG_RP_MSG_INVALID = 0, /* Must be 0 */
  81. MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
  82. MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
  83. MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
  84. MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
  85. MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
  86. MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
  87. MIG_RP_MSG_SWITCHOVER_ACK, /* Tell source it's OK to do switchover */
  88. MIG_RP_MSG_MAX
  89. };
  90. /* When we add fault tolerance, we could have several
  91. migrations at once. For now we don't need to add
  92. dynamic creation of migration */
  93. static MigrationState *current_migration;
  94. static MigrationIncomingState *current_incoming;
  95. static GSList *migration_blockers[MIG_MODE__MAX];
  96. static bool migration_object_check(MigrationState *ms, Error **errp);
  97. static bool migration_switchover_start(MigrationState *s, Error **errp);
  98. static void migrate_fd_cancel(MigrationState *s);
  99. static bool close_return_path_on_source(MigrationState *s);
  100. static void migration_completion_end(MigrationState *s);
  101. static void migrate_hup_delete(MigrationState *s);
  102. static void migration_downtime_start(MigrationState *s)
  103. {
  104. trace_vmstate_downtime_checkpoint("src-downtime-start");
  105. s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
  106. }
  107. static void migration_downtime_end(MigrationState *s)
  108. {
  109. int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
  110. /*
  111. * If downtime already set, should mean that postcopy already set it,
  112. * then that should be the real downtime already.
  113. */
  114. if (!s->downtime) {
  115. s->downtime = now - s->downtime_start;
  116. trace_vmstate_downtime_checkpoint("src-downtime-end");
  117. }
  118. }
  119. static void precopy_notify_complete(void)
  120. {
  121. Error *local_err = NULL;
  122. if (precopy_notify(PRECOPY_NOTIFY_COMPLETE, &local_err)) {
  123. error_report_err(local_err);
  124. }
  125. trace_migration_precopy_complete();
  126. }
  127. static bool migration_needs_multiple_sockets(void)
  128. {
  129. return migrate_multifd() || migrate_postcopy_preempt();
  130. }
  131. static RunState migration_get_target_runstate(void)
  132. {
  133. /*
  134. * When the global state is not migrated, it means we don't know the
  135. * runstate of the src QEMU. We don't have much choice but assuming
  136. * the VM is running. NOTE: this is pretty rare case, so far only Xen
  137. * uses it.
  138. */
  139. if (!global_state_received()) {
  140. return RUN_STATE_RUNNING;
  141. }
  142. return global_state_get_runstate();
  143. }
  144. static bool transport_supports_multi_channels(MigrationAddress *addr)
  145. {
  146. if (addr->transport == MIGRATION_ADDRESS_TYPE_SOCKET) {
  147. SocketAddress *saddr = &addr->u.socket;
  148. return (saddr->type == SOCKET_ADDRESS_TYPE_INET ||
  149. saddr->type == SOCKET_ADDRESS_TYPE_UNIX ||
  150. saddr->type == SOCKET_ADDRESS_TYPE_VSOCK);
  151. } else if (addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
  152. return migrate_mapped_ram();
  153. } else {
  154. return false;
  155. }
  156. }
  157. static bool migration_needs_seekable_channel(void)
  158. {
  159. return migrate_mapped_ram();
  160. }
  161. static bool migration_needs_extra_fds(void)
  162. {
  163. /*
  164. * When doing direct-io, multifd requires two different,
  165. * non-duplicated file descriptors so we can use one of them for
  166. * unaligned IO.
  167. */
  168. return migrate_multifd() && migrate_direct_io();
  169. }
  170. static bool transport_supports_seeking(MigrationAddress *addr)
  171. {
  172. if (addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
  173. return true;
  174. }
  175. return false;
  176. }
  177. static bool transport_supports_extra_fds(MigrationAddress *addr)
  178. {
  179. /* file: works because QEMU can open it multiple times */
  180. return addr->transport == MIGRATION_ADDRESS_TYPE_FILE;
  181. }
  182. static bool
  183. migration_channels_and_transport_compatible(MigrationAddress *addr,
  184. Error **errp)
  185. {
  186. if (migration_needs_seekable_channel() &&
  187. !transport_supports_seeking(addr)) {
  188. error_setg(errp, "Migration requires seekable transport (e.g. file)");
  189. return false;
  190. }
  191. if (migration_needs_multiple_sockets() &&
  192. !transport_supports_multi_channels(addr)) {
  193. error_setg(errp, "Migration requires multi-channel URIs (e.g. tcp)");
  194. return false;
  195. }
  196. if (migration_needs_extra_fds() &&
  197. !transport_supports_extra_fds(addr)) {
  198. error_setg(errp,
  199. "Migration requires a transport that allows for extra fds (e.g. file)");
  200. return false;
  201. }
  202. if (migrate_mode() == MIG_MODE_CPR_TRANSFER &&
  203. addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
  204. error_setg(errp, "Migration requires streamable transport (eg unix)");
  205. return false;
  206. }
  207. return true;
  208. }
  209. static gint page_request_addr_cmp(gconstpointer ap, gconstpointer bp)
  210. {
  211. uintptr_t a = (uintptr_t) ap, b = (uintptr_t) bp;
  212. return (a > b) - (a < b);
  213. }
  214. static int migration_stop_vm(MigrationState *s, RunState state)
  215. {
  216. int ret;
  217. migration_downtime_start(s);
  218. s->vm_old_state = runstate_get();
  219. global_state_store();
  220. ret = vm_stop_force_state(state);
  221. trace_vmstate_downtime_checkpoint("src-vm-stopped");
  222. trace_migration_completion_vm_stop(ret);
  223. return ret;
  224. }
  225. void migration_object_init(void)
  226. {
  227. /* This can only be called once. */
  228. assert(!current_migration);
  229. current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
  230. /*
  231. * Init the migrate incoming object as well no matter whether
  232. * we'll use it or not.
  233. */
  234. assert(!current_incoming);
  235. current_incoming = g_new0(MigrationIncomingState, 1);
  236. current_incoming->state = MIGRATION_STATUS_NONE;
  237. current_incoming->postcopy_remote_fds =
  238. g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
  239. qemu_mutex_init(&current_incoming->rp_mutex);
  240. qemu_mutex_init(&current_incoming->postcopy_prio_thread_mutex);
  241. qemu_event_init(&current_incoming->main_thread_load_event, false);
  242. qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
  243. qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
  244. qemu_sem_init(&current_incoming->postcopy_pause_sem_fast_load, 0);
  245. qemu_sem_init(&current_incoming->postcopy_qemufile_dst_done, 0);
  246. qemu_mutex_init(&current_incoming->page_request_mutex);
  247. qemu_cond_init(&current_incoming->page_request_cond);
  248. current_incoming->page_requested = g_tree_new(page_request_addr_cmp);
  249. current_incoming->exit_on_error = INMIGRATE_DEFAULT_EXIT_ON_ERROR;
  250. migration_object_check(current_migration, &error_fatal);
  251. ram_mig_init();
  252. dirty_bitmap_mig_init();
  253. /* Initialize cpu throttle timers */
  254. cpu_throttle_init();
  255. }
  256. typedef struct {
  257. QEMUBH *bh;
  258. QEMUBHFunc *cb;
  259. void *opaque;
  260. } MigrationBH;
  261. static void migration_bh_dispatch_bh(void *opaque)
  262. {
  263. MigrationState *s = migrate_get_current();
  264. MigrationBH *migbh = opaque;
  265. /* cleanup this BH */
  266. qemu_bh_delete(migbh->bh);
  267. migbh->bh = NULL;
  268. /* dispatch the other one */
  269. migbh->cb(migbh->opaque);
  270. object_unref(OBJECT(s));
  271. g_free(migbh);
  272. }
  273. void migration_bh_schedule(QEMUBHFunc *cb, void *opaque)
  274. {
  275. MigrationState *s = migrate_get_current();
  276. MigrationBH *migbh = g_new0(MigrationBH, 1);
  277. QEMUBH *bh = qemu_bh_new(migration_bh_dispatch_bh, migbh);
  278. /* Store these to dispatch when the BH runs */
  279. migbh->bh = bh;
  280. migbh->cb = cb;
  281. migbh->opaque = opaque;
  282. /*
  283. * Ref the state for bh, because it may be called when
  284. * there're already no other refs
  285. */
  286. object_ref(OBJECT(s));
  287. qemu_bh_schedule(bh);
  288. }
  289. void migration_cancel(const Error *error)
  290. {
  291. if (error) {
  292. migrate_set_error(current_migration, error);
  293. }
  294. if (migrate_dirty_limit()) {
  295. qmp_cancel_vcpu_dirty_limit(false, -1, NULL);
  296. }
  297. migrate_fd_cancel(current_migration);
  298. }
  299. void migration_shutdown(void)
  300. {
  301. /*
  302. * When the QEMU main thread exit, the COLO thread
  303. * may wait a semaphore. So, we should wakeup the
  304. * COLO thread before migration shutdown.
  305. */
  306. colo_shutdown();
  307. /*
  308. * Cancel the current migration - that will (eventually)
  309. * stop the migration using this structure
  310. */
  311. migration_cancel(NULL);
  312. object_unref(OBJECT(current_migration));
  313. /*
  314. * Cancel outgoing migration of dirty bitmaps. It should
  315. * at least unref used block nodes.
  316. */
  317. dirty_bitmap_mig_cancel_outgoing();
  318. /*
  319. * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
  320. * are non-critical data, and their loss never considered as
  321. * something serious.
  322. */
  323. dirty_bitmap_mig_cancel_incoming();
  324. }
  325. /* For outgoing */
  326. MigrationState *migrate_get_current(void)
  327. {
  328. /* This can only be called after the object created. */
  329. assert(current_migration);
  330. return current_migration;
  331. }
  332. MigrationIncomingState *migration_incoming_get_current(void)
  333. {
  334. assert(current_incoming);
  335. return current_incoming;
  336. }
  337. void migration_incoming_transport_cleanup(MigrationIncomingState *mis)
  338. {
  339. if (mis->socket_address_list) {
  340. qapi_free_SocketAddressList(mis->socket_address_list);
  341. mis->socket_address_list = NULL;
  342. }
  343. if (mis->transport_cleanup) {
  344. mis->transport_cleanup(mis->transport_data);
  345. mis->transport_data = mis->transport_cleanup = NULL;
  346. }
  347. }
  348. void migration_incoming_state_destroy(void)
  349. {
  350. struct MigrationIncomingState *mis = migration_incoming_get_current();
  351. multifd_recv_cleanup();
  352. /*
  353. * RAM state cleanup needs to happen after multifd cleanup, because
  354. * multifd threads can use some of its states (receivedmap).
  355. */
  356. qemu_loadvm_state_cleanup();
  357. if (mis->to_src_file) {
  358. /* Tell source that we are done */
  359. migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
  360. qemu_fclose(mis->to_src_file);
  361. mis->to_src_file = NULL;
  362. }
  363. if (mis->from_src_file) {
  364. migration_ioc_unregister_yank_from_file(mis->from_src_file);
  365. qemu_fclose(mis->from_src_file);
  366. mis->from_src_file = NULL;
  367. }
  368. if (mis->postcopy_remote_fds) {
  369. g_array_free(mis->postcopy_remote_fds, TRUE);
  370. mis->postcopy_remote_fds = NULL;
  371. }
  372. migration_incoming_transport_cleanup(mis);
  373. qemu_event_reset(&mis->main_thread_load_event);
  374. if (mis->page_requested) {
  375. g_tree_destroy(mis->page_requested);
  376. mis->page_requested = NULL;
  377. }
  378. if (mis->postcopy_qemufile_dst) {
  379. migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
  380. qemu_fclose(mis->postcopy_qemufile_dst);
  381. mis->postcopy_qemufile_dst = NULL;
  382. }
  383. cpr_set_incoming_mode(MIG_MODE_NONE);
  384. yank_unregister_instance(MIGRATION_YANK_INSTANCE);
  385. }
  386. static void migrate_generate_event(MigrationStatus new_state)
  387. {
  388. if (migrate_events()) {
  389. qapi_event_send_migration(new_state);
  390. }
  391. }
  392. /*
  393. * Send a message on the return channel back to the source
  394. * of the migration.
  395. */
  396. static int migrate_send_rp_message(MigrationIncomingState *mis,
  397. enum mig_rp_message_type message_type,
  398. uint16_t len, void *data)
  399. {
  400. int ret = 0;
  401. trace_migrate_send_rp_message((int)message_type, len);
  402. QEMU_LOCK_GUARD(&mis->rp_mutex);
  403. /*
  404. * It's possible that the file handle got lost due to network
  405. * failures.
  406. */
  407. if (!mis->to_src_file) {
  408. ret = -EIO;
  409. return ret;
  410. }
  411. qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
  412. qemu_put_be16(mis->to_src_file, len);
  413. qemu_put_buffer(mis->to_src_file, data, len);
  414. return qemu_fflush(mis->to_src_file);
  415. }
  416. /* Request one page from the source VM at the given start address.
  417. * rb: the RAMBlock to request the page in
  418. * Start: Address offset within the RB
  419. * Len: Length in bytes required - must be a multiple of pagesize
  420. */
  421. int migrate_send_rp_message_req_pages(MigrationIncomingState *mis,
  422. RAMBlock *rb, ram_addr_t start)
  423. {
  424. uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
  425. size_t msglen = 12; /* start + len */
  426. size_t len = qemu_ram_pagesize(rb);
  427. enum mig_rp_message_type msg_type;
  428. const char *rbname;
  429. int rbname_len;
  430. *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
  431. *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
  432. /*
  433. * We maintain the last ramblock that we requested for page. Note that we
  434. * don't need locking because this function will only be called within the
  435. * postcopy ram fault thread.
  436. */
  437. if (rb != mis->last_rb) {
  438. mis->last_rb = rb;
  439. rbname = qemu_ram_get_idstr(rb);
  440. rbname_len = strlen(rbname);
  441. assert(rbname_len < 256);
  442. bufc[msglen++] = rbname_len;
  443. memcpy(bufc + msglen, rbname, rbname_len);
  444. msglen += rbname_len;
  445. msg_type = MIG_RP_MSG_REQ_PAGES_ID;
  446. } else {
  447. msg_type = MIG_RP_MSG_REQ_PAGES;
  448. }
  449. return migrate_send_rp_message(mis, msg_type, msglen, bufc);
  450. }
  451. int migrate_send_rp_req_pages(MigrationIncomingState *mis,
  452. RAMBlock *rb, ram_addr_t start, uint64_t haddr)
  453. {
  454. void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb));
  455. bool received = false;
  456. WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
  457. received = ramblock_recv_bitmap_test_byte_offset(rb, start);
  458. if (!received && !g_tree_lookup(mis->page_requested, aligned)) {
  459. /*
  460. * The page has not been received, and it's not yet in the page
  461. * request list. Queue it. Set the value of element to 1, so that
  462. * things like g_tree_lookup() will return TRUE (1) when found.
  463. */
  464. g_tree_insert(mis->page_requested, aligned, (gpointer)1);
  465. qatomic_inc(&mis->page_requested_count);
  466. trace_postcopy_page_req_add(aligned, mis->page_requested_count);
  467. }
  468. }
  469. /*
  470. * If the page is there, skip sending the message. We don't even need the
  471. * lock because as long as the page arrived, it'll be there forever.
  472. */
  473. if (received) {
  474. return 0;
  475. }
  476. return migrate_send_rp_message_req_pages(mis, rb, start);
  477. }
  478. static bool migration_colo_enabled;
  479. bool migration_incoming_colo_enabled(void)
  480. {
  481. return migration_colo_enabled;
  482. }
  483. void migration_incoming_disable_colo(void)
  484. {
  485. ram_block_discard_disable(false);
  486. migration_colo_enabled = false;
  487. }
  488. int migration_incoming_enable_colo(void)
  489. {
  490. #ifndef CONFIG_REPLICATION
  491. error_report("ENABLE_COLO command come in migration stream, but the "
  492. "replication module is not built in");
  493. return -ENOTSUP;
  494. #endif
  495. if (!migrate_colo()) {
  496. error_report("ENABLE_COLO command come in migration stream, but x-colo "
  497. "capability is not set");
  498. return -EINVAL;
  499. }
  500. if (ram_block_discard_disable(true)) {
  501. error_report("COLO: cannot disable RAM discard");
  502. return -EBUSY;
  503. }
  504. migration_colo_enabled = true;
  505. return 0;
  506. }
  507. void migrate_add_address(SocketAddress *address)
  508. {
  509. MigrationIncomingState *mis = migration_incoming_get_current();
  510. QAPI_LIST_PREPEND(mis->socket_address_list,
  511. QAPI_CLONE(SocketAddress, address));
  512. }
  513. bool migrate_is_uri(const char *uri)
  514. {
  515. while (*uri && *uri != ':') {
  516. if (!qemu_isalpha(*uri++)) {
  517. return false;
  518. }
  519. }
  520. return *uri == ':';
  521. }
  522. bool migrate_uri_parse(const char *uri, MigrationChannel **channel,
  523. Error **errp)
  524. {
  525. g_autoptr(MigrationChannel) val = g_new0(MigrationChannel, 1);
  526. g_autoptr(MigrationAddress) addr = g_new0(MigrationAddress, 1);
  527. InetSocketAddress *isock = &addr->u.rdma;
  528. strList **tail = &addr->u.exec.args;
  529. if (strstart(uri, "exec:", NULL)) {
  530. addr->transport = MIGRATION_ADDRESS_TYPE_EXEC;
  531. #ifdef WIN32
  532. QAPI_LIST_APPEND(tail, g_strdup(exec_get_cmd_path()));
  533. QAPI_LIST_APPEND(tail, g_strdup("/c"));
  534. #else
  535. QAPI_LIST_APPEND(tail, g_strdup("/bin/sh"));
  536. QAPI_LIST_APPEND(tail, g_strdup("-c"));
  537. #endif
  538. QAPI_LIST_APPEND(tail, g_strdup(uri + strlen("exec:")));
  539. } else if (strstart(uri, "rdma:", NULL)) {
  540. if (inet_parse(isock, uri + strlen("rdma:"), errp)) {
  541. qapi_free_InetSocketAddress(isock);
  542. return false;
  543. }
  544. addr->transport = MIGRATION_ADDRESS_TYPE_RDMA;
  545. } else if (strstart(uri, "tcp:", NULL) ||
  546. strstart(uri, "unix:", NULL) ||
  547. strstart(uri, "vsock:", NULL) ||
  548. strstart(uri, "fd:", NULL)) {
  549. addr->transport = MIGRATION_ADDRESS_TYPE_SOCKET;
  550. SocketAddress *saddr = socket_parse(uri, errp);
  551. if (!saddr) {
  552. return false;
  553. }
  554. addr->u.socket.type = saddr->type;
  555. addr->u.socket.u = saddr->u;
  556. /* Don't free the objects inside; their ownership moved to "addr" */
  557. g_free(saddr);
  558. } else if (strstart(uri, "file:", NULL)) {
  559. addr->transport = MIGRATION_ADDRESS_TYPE_FILE;
  560. addr->u.file.filename = g_strdup(uri + strlen("file:"));
  561. if (file_parse_offset(addr->u.file.filename, &addr->u.file.offset,
  562. errp)) {
  563. return false;
  564. }
  565. } else {
  566. error_setg(errp, "unknown migration protocol: %s", uri);
  567. return false;
  568. }
  569. val->channel_type = MIGRATION_CHANNEL_TYPE_MAIN;
  570. val->addr = g_steal_pointer(&addr);
  571. *channel = g_steal_pointer(&val);
  572. return true;
  573. }
  574. static bool
  575. migration_incoming_state_setup(MigrationIncomingState *mis, Error **errp)
  576. {
  577. MigrationStatus current = mis->state;
  578. if (current == MIGRATION_STATUS_POSTCOPY_PAUSED) {
  579. /*
  580. * Incoming postcopy migration will stay in PAUSED state even if
  581. * reconnection happened.
  582. */
  583. return true;
  584. }
  585. if (current != MIGRATION_STATUS_NONE) {
  586. error_setg(errp, "Illegal migration incoming state: %s",
  587. MigrationStatus_str(current));
  588. return false;
  589. }
  590. migrate_set_state(&mis->state, current, MIGRATION_STATUS_SETUP);
  591. return true;
  592. }
  593. static void qemu_start_incoming_migration(const char *uri, bool has_channels,
  594. MigrationChannelList *channels,
  595. Error **errp)
  596. {
  597. g_autoptr(MigrationChannel) channel = NULL;
  598. MigrationAddress *addr = NULL;
  599. MigrationIncomingState *mis = migration_incoming_get_current();
  600. /*
  601. * Having preliminary checks for uri and channel
  602. */
  603. if (!uri == !channels) {
  604. error_setg(errp, "need either 'uri' or 'channels' argument");
  605. return;
  606. }
  607. if (channels) {
  608. /* To verify that Migrate channel list has only item */
  609. if (channels->next) {
  610. error_setg(errp, "Channel list must have only one entry, "
  611. "for type 'main'");
  612. return;
  613. }
  614. addr = channels->value->addr;
  615. }
  616. if (uri) {
  617. /* caller uses the old URI syntax */
  618. if (!migrate_uri_parse(uri, &channel, errp)) {
  619. return;
  620. }
  621. addr = channel->addr;
  622. }
  623. /* transport mechanism not suitable for migration? */
  624. if (!migration_channels_and_transport_compatible(addr, errp)) {
  625. return;
  626. }
  627. if (!migration_incoming_state_setup(mis, errp)) {
  628. return;
  629. }
  630. if (addr->transport == MIGRATION_ADDRESS_TYPE_SOCKET) {
  631. SocketAddress *saddr = &addr->u.socket;
  632. if (saddr->type == SOCKET_ADDRESS_TYPE_INET ||
  633. saddr->type == SOCKET_ADDRESS_TYPE_UNIX ||
  634. saddr->type == SOCKET_ADDRESS_TYPE_VSOCK) {
  635. socket_start_incoming_migration(saddr, errp);
  636. } else if (saddr->type == SOCKET_ADDRESS_TYPE_FD) {
  637. fd_start_incoming_migration(saddr->u.fd.str, errp);
  638. }
  639. #ifdef CONFIG_RDMA
  640. } else if (addr->transport == MIGRATION_ADDRESS_TYPE_RDMA) {
  641. if (migrate_xbzrle()) {
  642. error_setg(errp, "RDMA and XBZRLE can't be used together");
  643. return;
  644. }
  645. if (migrate_multifd()) {
  646. error_setg(errp, "RDMA and multifd can't be used together");
  647. return;
  648. }
  649. rdma_start_incoming_migration(&addr->u.rdma, errp);
  650. #endif
  651. } else if (addr->transport == MIGRATION_ADDRESS_TYPE_EXEC) {
  652. exec_start_incoming_migration(addr->u.exec.args, errp);
  653. } else if (addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
  654. file_start_incoming_migration(&addr->u.file, errp);
  655. } else {
  656. error_setg(errp, "unknown migration protocol: %s", uri);
  657. }
  658. /* Close cpr socket to tell source that we are listening */
  659. cpr_state_close();
  660. }
  661. static void process_incoming_migration_bh(void *opaque)
  662. {
  663. MigrationIncomingState *mis = opaque;
  664. trace_vmstate_downtime_checkpoint("dst-precopy-bh-enter");
  665. /*
  666. * This must happen after all error conditions are dealt with and
  667. * we're sure the VM is going to be running on this host.
  668. */
  669. qemu_announce_self(&mis->announce_timer, migrate_announce_params());
  670. trace_vmstate_downtime_checkpoint("dst-precopy-bh-announced");
  671. multifd_recv_shutdown();
  672. dirty_bitmap_mig_before_vm_start();
  673. if (runstate_is_live(migration_get_target_runstate())) {
  674. if (autostart) {
  675. /*
  676. * Block activation is always delayed until VM starts, either
  677. * here (which means we need to start the dest VM right now..),
  678. * or until qmp_cont() later.
  679. *
  680. * We used to have cap 'late-block-activate' but now we do this
  681. * unconditionally, as it has no harm but only benefit. E.g.,
  682. * it's not part of migration ABI on the time of disk activation.
  683. *
  684. * Make sure all file formats throw away their mutable
  685. * metadata. If error, don't restart the VM yet.
  686. */
  687. if (migration_block_activate(NULL)) {
  688. vm_start();
  689. }
  690. } else {
  691. runstate_set(RUN_STATE_PAUSED);
  692. }
  693. } else if (migration_incoming_colo_enabled()) {
  694. migration_incoming_disable_colo();
  695. vm_start();
  696. } else {
  697. runstate_set(global_state_get_runstate());
  698. }
  699. trace_vmstate_downtime_checkpoint("dst-precopy-bh-vm-started");
  700. /*
  701. * This must happen after any state changes since as soon as an external
  702. * observer sees this event they might start to prod at the VM assuming
  703. * it's ready to use.
  704. */
  705. migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
  706. MIGRATION_STATUS_COMPLETED);
  707. migration_incoming_state_destroy();
  708. }
  709. static void coroutine_fn
  710. process_incoming_migration_co(void *opaque)
  711. {
  712. MigrationState *s = migrate_get_current();
  713. MigrationIncomingState *mis = migration_incoming_get_current();
  714. PostcopyState ps;
  715. int ret;
  716. Error *local_err = NULL;
  717. assert(mis->from_src_file);
  718. mis->largest_page_size = qemu_ram_pagesize_largest();
  719. postcopy_state_set(POSTCOPY_INCOMING_NONE);
  720. migrate_set_state(&mis->state, MIGRATION_STATUS_SETUP,
  721. MIGRATION_STATUS_ACTIVE);
  722. mis->loadvm_co = qemu_coroutine_self();
  723. ret = qemu_loadvm_state(mis->from_src_file);
  724. mis->loadvm_co = NULL;
  725. trace_vmstate_downtime_checkpoint("dst-precopy-loadvm-completed");
  726. ps = postcopy_state_get();
  727. trace_process_incoming_migration_co_end(ret, ps);
  728. if (ps != POSTCOPY_INCOMING_NONE) {
  729. if (ps == POSTCOPY_INCOMING_ADVISE) {
  730. /*
  731. * Where a migration had postcopy enabled (and thus went to advise)
  732. * but managed to complete within the precopy period, we can use
  733. * the normal exit.
  734. */
  735. postcopy_ram_incoming_cleanup(mis);
  736. } else if (ret >= 0) {
  737. /*
  738. * Postcopy was started, cleanup should happen at the end of the
  739. * postcopy thread.
  740. */
  741. trace_process_incoming_migration_co_postcopy_end_main();
  742. return;
  743. }
  744. /* Else if something went wrong then just fall out of the normal exit */
  745. }
  746. if (ret < 0) {
  747. error_setg(&local_err, "load of migration failed: %s", strerror(-ret));
  748. goto fail;
  749. }
  750. if (migration_incoming_colo_enabled()) {
  751. /* yield until COLO exit */
  752. colo_incoming_co();
  753. }
  754. migration_bh_schedule(process_incoming_migration_bh, mis);
  755. return;
  756. fail:
  757. migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
  758. MIGRATION_STATUS_FAILED);
  759. migrate_set_error(s, local_err);
  760. error_free(local_err);
  761. migration_incoming_state_destroy();
  762. if (mis->exit_on_error) {
  763. WITH_QEMU_LOCK_GUARD(&s->error_mutex) {
  764. error_report_err(s->error);
  765. s->error = NULL;
  766. }
  767. exit(EXIT_FAILURE);
  768. }
  769. }
  770. /**
  771. * migration_incoming_setup: Setup incoming migration
  772. * @f: file for main migration channel
  773. */
  774. static void migration_incoming_setup(QEMUFile *f)
  775. {
  776. MigrationIncomingState *mis = migration_incoming_get_current();
  777. if (!mis->from_src_file) {
  778. mis->from_src_file = f;
  779. }
  780. qemu_file_set_blocking(f, false);
  781. }
  782. void migration_incoming_process(void)
  783. {
  784. Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
  785. qemu_coroutine_enter(co);
  786. }
  787. /* Returns true if recovered from a paused migration, otherwise false */
  788. static bool postcopy_try_recover(void)
  789. {
  790. MigrationIncomingState *mis = migration_incoming_get_current();
  791. if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
  792. /* Resumed from a paused postcopy migration */
  793. /* This should be set already in migration_incoming_setup() */
  794. assert(mis->from_src_file);
  795. /* Postcopy has standalone thread to do vm load */
  796. qemu_file_set_blocking(mis->from_src_file, true);
  797. /* Re-configure the return path */
  798. mis->to_src_file = qemu_file_get_return_path(mis->from_src_file);
  799. migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
  800. MIGRATION_STATUS_POSTCOPY_RECOVER);
  801. /*
  802. * Here, we only wake up the main loading thread (while the
  803. * rest threads will still be waiting), so that we can receive
  804. * commands from source now, and answer it if needed. The
  805. * rest threads will be woken up afterwards until we are sure
  806. * that source is ready to reply to page requests.
  807. */
  808. qemu_sem_post(&mis->postcopy_pause_sem_dst);
  809. return true;
  810. }
  811. return false;
  812. }
  813. void migration_fd_process_incoming(QEMUFile *f)
  814. {
  815. migration_incoming_setup(f);
  816. if (postcopy_try_recover()) {
  817. return;
  818. }
  819. migration_incoming_process();
  820. }
  821. /*
  822. * Returns true when we want to start a new incoming migration process,
  823. * false otherwise.
  824. */
  825. static bool migration_should_start_incoming(bool main_channel)
  826. {
  827. /* Multifd doesn't start unless all channels are established */
  828. if (migrate_multifd()) {
  829. return migration_has_all_channels();
  830. }
  831. /* Preempt channel only starts when the main channel is created */
  832. if (migrate_postcopy_preempt()) {
  833. return main_channel;
  834. }
  835. /*
  836. * For all the rest types of migration, we should only reach here when
  837. * it's the main channel that's being created, and we should always
  838. * proceed with this channel.
  839. */
  840. assert(main_channel);
  841. return true;
  842. }
  843. void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
  844. {
  845. MigrationIncomingState *mis = migration_incoming_get_current();
  846. Error *local_err = NULL;
  847. QEMUFile *f;
  848. bool default_channel = true;
  849. uint32_t channel_magic = 0;
  850. int ret = 0;
  851. if (migrate_multifd() && !migrate_mapped_ram() &&
  852. !migrate_postcopy_ram() &&
  853. qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) {
  854. /*
  855. * With multiple channels, it is possible that we receive channels
  856. * out of order on destination side, causing incorrect mapping of
  857. * source channels on destination side. Check channel MAGIC to
  858. * decide type of channel. Please note this is best effort, postcopy
  859. * preempt channel does not send any magic number so avoid it for
  860. * postcopy live migration. Also tls live migration already does
  861. * tls handshake while initializing main channel so with tls this
  862. * issue is not possible.
  863. */
  864. ret = migration_channel_read_peek(ioc, (void *)&channel_magic,
  865. sizeof(channel_magic), errp);
  866. if (ret != 0) {
  867. return;
  868. }
  869. default_channel = (channel_magic == cpu_to_be32(QEMU_VM_FILE_MAGIC));
  870. } else {
  871. default_channel = !mis->from_src_file;
  872. }
  873. if (multifd_recv_setup(errp) != 0) {
  874. return;
  875. }
  876. if (default_channel) {
  877. f = qemu_file_new_input(ioc);
  878. migration_incoming_setup(f);
  879. } else {
  880. /* Multiple connections */
  881. assert(migration_needs_multiple_sockets());
  882. if (migrate_multifd()) {
  883. multifd_recv_new_channel(ioc, &local_err);
  884. } else {
  885. assert(migrate_postcopy_preempt());
  886. f = qemu_file_new_input(ioc);
  887. postcopy_preempt_new_channel(mis, f);
  888. }
  889. if (local_err) {
  890. error_propagate(errp, local_err);
  891. return;
  892. }
  893. }
  894. if (migration_should_start_incoming(default_channel)) {
  895. /* If it's a recovery, we're done */
  896. if (postcopy_try_recover()) {
  897. return;
  898. }
  899. migration_incoming_process();
  900. }
  901. }
  902. /**
  903. * @migration_has_all_channels: We have received all channels that we need
  904. *
  905. * Returns true when we have got connections to all the channels that
  906. * we need for migration.
  907. */
  908. bool migration_has_all_channels(void)
  909. {
  910. MigrationIncomingState *mis = migration_incoming_get_current();
  911. if (!mis->from_src_file) {
  912. return false;
  913. }
  914. if (migrate_multifd()) {
  915. return multifd_recv_all_channels_created();
  916. }
  917. if (migrate_postcopy_preempt()) {
  918. return mis->postcopy_qemufile_dst != NULL;
  919. }
  920. return true;
  921. }
  922. int migrate_send_rp_switchover_ack(MigrationIncomingState *mis)
  923. {
  924. return migrate_send_rp_message(mis, MIG_RP_MSG_SWITCHOVER_ACK, 0, NULL);
  925. }
  926. /*
  927. * Send a 'SHUT' message on the return channel with the given value
  928. * to indicate that we've finished with the RP. Non-0 value indicates
  929. * error.
  930. */
  931. void migrate_send_rp_shut(MigrationIncomingState *mis,
  932. uint32_t value)
  933. {
  934. uint32_t buf;
  935. buf = cpu_to_be32(value);
  936. migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
  937. }
  938. /*
  939. * Send a 'PONG' message on the return channel with the given value
  940. * (normally in response to a 'PING')
  941. */
  942. void migrate_send_rp_pong(MigrationIncomingState *mis,
  943. uint32_t value)
  944. {
  945. uint32_t buf;
  946. buf = cpu_to_be32(value);
  947. migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
  948. }
  949. void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
  950. char *block_name)
  951. {
  952. char buf[512];
  953. int len;
  954. int64_t res;
  955. /*
  956. * First, we send the header part. It contains only the len of
  957. * idstr, and the idstr itself.
  958. */
  959. len = strlen(block_name);
  960. buf[0] = len;
  961. memcpy(buf + 1, block_name, len);
  962. if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
  963. error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
  964. __func__);
  965. return;
  966. }
  967. migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
  968. /*
  969. * Next, we dump the received bitmap to the stream.
  970. *
  971. * TODO: currently we are safe since we are the only one that is
  972. * using the to_src_file handle (fault thread is still paused),
  973. * and it's ok even not taking the mutex. However the best way is
  974. * to take the lock before sending the message header, and release
  975. * the lock after sending the bitmap.
  976. */
  977. qemu_mutex_lock(&mis->rp_mutex);
  978. res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
  979. qemu_mutex_unlock(&mis->rp_mutex);
  980. trace_migrate_send_rp_recv_bitmap(block_name, res);
  981. }
  982. void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
  983. {
  984. uint32_t buf;
  985. buf = cpu_to_be32(value);
  986. migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
  987. }
  988. bool migration_is_running(void)
  989. {
  990. MigrationState *s = current_migration;
  991. if (!s) {
  992. return false;
  993. }
  994. switch (s->state) {
  995. case MIGRATION_STATUS_ACTIVE:
  996. case MIGRATION_STATUS_POSTCOPY_ACTIVE:
  997. case MIGRATION_STATUS_POSTCOPY_PAUSED:
  998. case MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP:
  999. case MIGRATION_STATUS_POSTCOPY_RECOVER:
  1000. case MIGRATION_STATUS_SETUP:
  1001. case MIGRATION_STATUS_PRE_SWITCHOVER:
  1002. case MIGRATION_STATUS_DEVICE:
  1003. case MIGRATION_STATUS_WAIT_UNPLUG:
  1004. case MIGRATION_STATUS_CANCELLING:
  1005. case MIGRATION_STATUS_COLO:
  1006. return true;
  1007. default:
  1008. return false;
  1009. }
  1010. }
  1011. static bool migration_is_active(void)
  1012. {
  1013. MigrationState *s = current_migration;
  1014. return (s->state == MIGRATION_STATUS_ACTIVE ||
  1015. s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
  1016. }
  1017. static bool migrate_show_downtime(MigrationState *s)
  1018. {
  1019. return (s->state == MIGRATION_STATUS_COMPLETED) || migration_in_postcopy();
  1020. }
  1021. static void populate_time_info(MigrationInfo *info, MigrationState *s)
  1022. {
  1023. info->has_status = true;
  1024. info->has_setup_time = true;
  1025. info->setup_time = s->setup_time;
  1026. if (s->state == MIGRATION_STATUS_COMPLETED) {
  1027. info->has_total_time = true;
  1028. info->total_time = s->total_time;
  1029. } else {
  1030. info->has_total_time = true;
  1031. info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
  1032. s->start_time;
  1033. }
  1034. if (migrate_show_downtime(s)) {
  1035. info->has_downtime = true;
  1036. info->downtime = s->downtime;
  1037. } else {
  1038. info->has_expected_downtime = true;
  1039. info->expected_downtime = s->expected_downtime;
  1040. }
  1041. }
  1042. static void populate_ram_info(MigrationInfo *info, MigrationState *s)
  1043. {
  1044. size_t page_size = qemu_target_page_size();
  1045. info->ram = g_malloc0(sizeof(*info->ram));
  1046. info->ram->transferred = migration_transferred_bytes();
  1047. info->ram->total = ram_bytes_total();
  1048. info->ram->duplicate = stat64_get(&mig_stats.zero_pages);
  1049. info->ram->normal = stat64_get(&mig_stats.normal_pages);
  1050. info->ram->normal_bytes = info->ram->normal * page_size;
  1051. info->ram->mbps = s->mbps;
  1052. info->ram->dirty_sync_count =
  1053. stat64_get(&mig_stats.dirty_sync_count);
  1054. info->ram->dirty_sync_missed_zero_copy =
  1055. stat64_get(&mig_stats.dirty_sync_missed_zero_copy);
  1056. info->ram->postcopy_requests =
  1057. stat64_get(&mig_stats.postcopy_requests);
  1058. info->ram->page_size = page_size;
  1059. info->ram->multifd_bytes = stat64_get(&mig_stats.multifd_bytes);
  1060. info->ram->pages_per_second = s->pages_per_second;
  1061. info->ram->precopy_bytes = stat64_get(&mig_stats.precopy_bytes);
  1062. info->ram->downtime_bytes = stat64_get(&mig_stats.downtime_bytes);
  1063. info->ram->postcopy_bytes = stat64_get(&mig_stats.postcopy_bytes);
  1064. if (migrate_xbzrle()) {
  1065. info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
  1066. info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
  1067. info->xbzrle_cache->bytes = xbzrle_counters.bytes;
  1068. info->xbzrle_cache->pages = xbzrle_counters.pages;
  1069. info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
  1070. info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
  1071. info->xbzrle_cache->encoding_rate = xbzrle_counters.encoding_rate;
  1072. info->xbzrle_cache->overflow = xbzrle_counters.overflow;
  1073. }
  1074. if (cpu_throttle_active()) {
  1075. info->has_cpu_throttle_percentage = true;
  1076. info->cpu_throttle_percentage = cpu_throttle_get_percentage();
  1077. }
  1078. if (s->state != MIGRATION_STATUS_COMPLETED) {
  1079. info->ram->remaining = ram_bytes_remaining();
  1080. info->ram->dirty_pages_rate =
  1081. stat64_get(&mig_stats.dirty_pages_rate);
  1082. }
  1083. if (migrate_dirty_limit() && dirtylimit_in_service()) {
  1084. info->has_dirty_limit_throttle_time_per_round = true;
  1085. info->dirty_limit_throttle_time_per_round =
  1086. dirtylimit_throttle_time_per_round();
  1087. info->has_dirty_limit_ring_full_time = true;
  1088. info->dirty_limit_ring_full_time = dirtylimit_ring_full_time();
  1089. }
  1090. }
  1091. static void fill_source_migration_info(MigrationInfo *info)
  1092. {
  1093. MigrationState *s = migrate_get_current();
  1094. int state = qatomic_read(&s->state);
  1095. GSList *cur_blocker = migration_blockers[migrate_mode()];
  1096. info->blocked_reasons = NULL;
  1097. /*
  1098. * There are two types of reasons a migration might be blocked;
  1099. * a) devices marked in VMState as non-migratable, and
  1100. * b) Explicit migration blockers
  1101. * We need to add both of them here.
  1102. */
  1103. qemu_savevm_non_migratable_list(&info->blocked_reasons);
  1104. while (cur_blocker) {
  1105. QAPI_LIST_PREPEND(info->blocked_reasons,
  1106. g_strdup(error_get_pretty(cur_blocker->data)));
  1107. cur_blocker = g_slist_next(cur_blocker);
  1108. }
  1109. info->has_blocked_reasons = info->blocked_reasons != NULL;
  1110. switch (state) {
  1111. case MIGRATION_STATUS_NONE:
  1112. /* no migration has happened ever */
  1113. /* do not overwrite destination migration status */
  1114. return;
  1115. case MIGRATION_STATUS_SETUP:
  1116. info->has_status = true;
  1117. info->has_total_time = false;
  1118. break;
  1119. case MIGRATION_STATUS_ACTIVE:
  1120. case MIGRATION_STATUS_CANCELLING:
  1121. case MIGRATION_STATUS_POSTCOPY_ACTIVE:
  1122. case MIGRATION_STATUS_PRE_SWITCHOVER:
  1123. case MIGRATION_STATUS_DEVICE:
  1124. case MIGRATION_STATUS_POSTCOPY_PAUSED:
  1125. case MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP:
  1126. case MIGRATION_STATUS_POSTCOPY_RECOVER:
  1127. /* TODO add some postcopy stats */
  1128. populate_time_info(info, s);
  1129. populate_ram_info(info, s);
  1130. migration_populate_vfio_info(info);
  1131. break;
  1132. case MIGRATION_STATUS_COLO:
  1133. info->has_status = true;
  1134. /* TODO: display COLO specific information (checkpoint info etc.) */
  1135. break;
  1136. case MIGRATION_STATUS_COMPLETED:
  1137. populate_time_info(info, s);
  1138. populate_ram_info(info, s);
  1139. migration_populate_vfio_info(info);
  1140. break;
  1141. case MIGRATION_STATUS_FAILED:
  1142. info->has_status = true;
  1143. break;
  1144. case MIGRATION_STATUS_CANCELLED:
  1145. info->has_status = true;
  1146. break;
  1147. case MIGRATION_STATUS_WAIT_UNPLUG:
  1148. info->has_status = true;
  1149. break;
  1150. }
  1151. info->status = state;
  1152. QEMU_LOCK_GUARD(&s->error_mutex);
  1153. if (s->error) {
  1154. info->error_desc = g_strdup(error_get_pretty(s->error));
  1155. }
  1156. }
  1157. static void fill_destination_migration_info(MigrationInfo *info)
  1158. {
  1159. MigrationIncomingState *mis = migration_incoming_get_current();
  1160. if (mis->socket_address_list) {
  1161. info->has_socket_address = true;
  1162. info->socket_address =
  1163. QAPI_CLONE(SocketAddressList, mis->socket_address_list);
  1164. }
  1165. switch (mis->state) {
  1166. case MIGRATION_STATUS_SETUP:
  1167. case MIGRATION_STATUS_CANCELLING:
  1168. case MIGRATION_STATUS_CANCELLED:
  1169. case MIGRATION_STATUS_ACTIVE:
  1170. case MIGRATION_STATUS_POSTCOPY_ACTIVE:
  1171. case MIGRATION_STATUS_POSTCOPY_PAUSED:
  1172. case MIGRATION_STATUS_POSTCOPY_RECOVER:
  1173. case MIGRATION_STATUS_FAILED:
  1174. case MIGRATION_STATUS_COLO:
  1175. info->has_status = true;
  1176. break;
  1177. case MIGRATION_STATUS_COMPLETED:
  1178. info->has_status = true;
  1179. fill_destination_postcopy_migration_info(info);
  1180. break;
  1181. default:
  1182. return;
  1183. }
  1184. info->status = mis->state;
  1185. if (!info->error_desc) {
  1186. MigrationState *s = migrate_get_current();
  1187. QEMU_LOCK_GUARD(&s->error_mutex);
  1188. if (s->error) {
  1189. info->error_desc = g_strdup(error_get_pretty(s->error));
  1190. }
  1191. }
  1192. }
  1193. MigrationInfo *qmp_query_migrate(Error **errp)
  1194. {
  1195. MigrationInfo *info = g_malloc0(sizeof(*info));
  1196. fill_destination_migration_info(info);
  1197. fill_source_migration_info(info);
  1198. return info;
  1199. }
  1200. void qmp_migrate_start_postcopy(Error **errp)
  1201. {
  1202. MigrationState *s = migrate_get_current();
  1203. if (!migrate_postcopy()) {
  1204. error_setg(errp, "Enable postcopy with migrate_set_capability before"
  1205. " the start of migration");
  1206. return;
  1207. }
  1208. if (s->state == MIGRATION_STATUS_NONE) {
  1209. error_setg(errp, "Postcopy must be started after migration has been"
  1210. " started");
  1211. return;
  1212. }
  1213. /*
  1214. * we don't error if migration has finished since that would be racy
  1215. * with issuing this command.
  1216. */
  1217. qatomic_set(&s->start_postcopy, true);
  1218. }
  1219. /* shared migration helpers */
  1220. void migrate_set_state(MigrationStatus *state, MigrationStatus old_state,
  1221. MigrationStatus new_state)
  1222. {
  1223. assert(new_state < MIGRATION_STATUS__MAX);
  1224. if (qatomic_cmpxchg(state, old_state, new_state) == old_state) {
  1225. trace_migrate_set_state(MigrationStatus_str(new_state));
  1226. migrate_generate_event(new_state);
  1227. }
  1228. }
  1229. static void migration_cleanup_json_writer(MigrationState *s)
  1230. {
  1231. g_clear_pointer(&s->vmdesc, json_writer_free);
  1232. }
  1233. static void migrate_fd_cleanup(MigrationState *s)
  1234. {
  1235. MigrationEventType type;
  1236. QEMUFile *tmp = NULL;
  1237. trace_migrate_fd_cleanup();
  1238. migration_cleanup_json_writer(s);
  1239. g_free(s->hostname);
  1240. s->hostname = NULL;
  1241. qemu_savevm_state_cleanup();
  1242. cpr_state_close();
  1243. migrate_hup_delete(s);
  1244. close_return_path_on_source(s);
  1245. if (s->migration_thread_running) {
  1246. bql_unlock();
  1247. qemu_thread_join(&s->thread);
  1248. s->migration_thread_running = false;
  1249. bql_lock();
  1250. }
  1251. WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
  1252. /*
  1253. * Close the file handle without the lock to make sure the critical
  1254. * section won't block for long.
  1255. */
  1256. tmp = s->to_dst_file;
  1257. s->to_dst_file = NULL;
  1258. }
  1259. if (tmp) {
  1260. /*
  1261. * We only need to shutdown multifd if tmp!=NULL, because if
  1262. * tmp==NULL, it means the main channel isn't established, while
  1263. * multifd is only setup after that (in migration_thread()).
  1264. */
  1265. multifd_send_shutdown();
  1266. migration_ioc_unregister_yank_from_file(tmp);
  1267. qemu_fclose(tmp);
  1268. }
  1269. assert(!migration_is_active());
  1270. if (s->state == MIGRATION_STATUS_CANCELLING) {
  1271. migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
  1272. MIGRATION_STATUS_CANCELLED);
  1273. }
  1274. if (s->error) {
  1275. /* It is used on info migrate. We can't free it */
  1276. error_report_err(error_copy(s->error));
  1277. }
  1278. type = migration_has_failed(s) ? MIG_EVENT_PRECOPY_FAILED :
  1279. MIG_EVENT_PRECOPY_DONE;
  1280. migration_call_notifiers(s, type, NULL);
  1281. yank_unregister_instance(MIGRATION_YANK_INSTANCE);
  1282. }
  1283. static void migrate_fd_cleanup_bh(void *opaque)
  1284. {
  1285. migrate_fd_cleanup(opaque);
  1286. }
  1287. void migrate_set_error(MigrationState *s, const Error *error)
  1288. {
  1289. QEMU_LOCK_GUARD(&s->error_mutex);
  1290. trace_migrate_error(error_get_pretty(error));
  1291. if (!s->error) {
  1292. s->error = error_copy(error);
  1293. }
  1294. }
  1295. bool migrate_has_error(MigrationState *s)
  1296. {
  1297. /* The lock is not helpful here, but still follow the rule */
  1298. QEMU_LOCK_GUARD(&s->error_mutex);
  1299. return qatomic_read(&s->error);
  1300. }
  1301. static void migrate_error_free(MigrationState *s)
  1302. {
  1303. QEMU_LOCK_GUARD(&s->error_mutex);
  1304. if (s->error) {
  1305. error_free(s->error);
  1306. s->error = NULL;
  1307. }
  1308. }
  1309. static void migrate_fd_error(MigrationState *s, const Error *error)
  1310. {
  1311. MigrationStatus current = s->state;
  1312. MigrationStatus next;
  1313. assert(s->to_dst_file == NULL);
  1314. switch (current) {
  1315. case MIGRATION_STATUS_SETUP:
  1316. next = MIGRATION_STATUS_FAILED;
  1317. break;
  1318. case MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP:
  1319. /* Never fail a postcopy migration; switch back to PAUSED instead */
  1320. next = MIGRATION_STATUS_POSTCOPY_PAUSED;
  1321. break;
  1322. default:
  1323. /*
  1324. * This really shouldn't happen. Just be careful to not crash a VM
  1325. * just for this. Instead, dump something.
  1326. */
  1327. error_report("%s: Illegal migration status (%s) detected",
  1328. __func__, MigrationStatus_str(current));
  1329. return;
  1330. }
  1331. migrate_set_state(&s->state, current, next);
  1332. migrate_set_error(s, error);
  1333. }
  1334. static void migrate_fd_cancel(MigrationState *s)
  1335. {
  1336. int old_state ;
  1337. bool setup = (s->state == MIGRATION_STATUS_SETUP);
  1338. trace_migrate_fd_cancel();
  1339. WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
  1340. if (s->rp_state.from_dst_file) {
  1341. /* shutdown the rp socket, so causing the rp thread to shutdown */
  1342. qemu_file_shutdown(s->rp_state.from_dst_file);
  1343. }
  1344. }
  1345. do {
  1346. old_state = s->state;
  1347. if (!migration_is_running()) {
  1348. break;
  1349. }
  1350. /* If the migration is paused, kick it out of the pause */
  1351. if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
  1352. qemu_sem_post(&s->pause_sem);
  1353. }
  1354. migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
  1355. } while (s->state != MIGRATION_STATUS_CANCELLING);
  1356. /*
  1357. * If we're unlucky the migration code might be stuck somewhere in a
  1358. * send/write while the network has failed and is waiting to timeout;
  1359. * if we've got shutdown(2) available then we can force it to quit.
  1360. */
  1361. if (s->state == MIGRATION_STATUS_CANCELLING) {
  1362. WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
  1363. if (s->to_dst_file) {
  1364. qemu_file_shutdown(s->to_dst_file);
  1365. }
  1366. }
  1367. }
  1368. /*
  1369. * If qmp_migrate_finish has not been called, then there is no path that
  1370. * will complete the cancellation. Do it now.
  1371. */
  1372. if (setup && !s->to_dst_file) {
  1373. migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
  1374. MIGRATION_STATUS_CANCELLED);
  1375. cpr_state_close();
  1376. migrate_hup_delete(s);
  1377. }
  1378. }
  1379. void migration_add_notifier_mode(NotifierWithReturn *notify,
  1380. MigrationNotifyFunc func, MigMode mode)
  1381. {
  1382. notify->notify = (NotifierWithReturnFunc)func;
  1383. notifier_with_return_list_add(&migration_state_notifiers[mode], notify);
  1384. }
  1385. void migration_add_notifier(NotifierWithReturn *notify,
  1386. MigrationNotifyFunc func)
  1387. {
  1388. migration_add_notifier_mode(notify, func, MIG_MODE_NORMAL);
  1389. }
  1390. void migration_remove_notifier(NotifierWithReturn *notify)
  1391. {
  1392. if (notify->notify) {
  1393. notifier_with_return_remove(notify);
  1394. notify->notify = NULL;
  1395. }
  1396. }
  1397. int migration_call_notifiers(MigrationState *s, MigrationEventType type,
  1398. Error **errp)
  1399. {
  1400. MigMode mode = s->parameters.mode;
  1401. MigrationEvent e;
  1402. int ret;
  1403. e.type = type;
  1404. ret = notifier_with_return_list_notify(&migration_state_notifiers[mode],
  1405. &e, errp);
  1406. assert(!ret || type == MIG_EVENT_PRECOPY_SETUP);
  1407. return ret;
  1408. }
  1409. bool migration_has_failed(MigrationState *s)
  1410. {
  1411. return (s->state == MIGRATION_STATUS_CANCELLED ||
  1412. s->state == MIGRATION_STATUS_FAILED);
  1413. }
  1414. bool migration_in_postcopy(void)
  1415. {
  1416. MigrationState *s = migrate_get_current();
  1417. switch (s->state) {
  1418. case MIGRATION_STATUS_POSTCOPY_ACTIVE:
  1419. case MIGRATION_STATUS_POSTCOPY_PAUSED:
  1420. case MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP:
  1421. case MIGRATION_STATUS_POSTCOPY_RECOVER:
  1422. return true;
  1423. default:
  1424. return false;
  1425. }
  1426. }
  1427. bool migration_postcopy_is_alive(MigrationStatus state)
  1428. {
  1429. switch (state) {
  1430. case MIGRATION_STATUS_POSTCOPY_ACTIVE:
  1431. case MIGRATION_STATUS_POSTCOPY_RECOVER:
  1432. return true;
  1433. default:
  1434. return false;
  1435. }
  1436. }
  1437. bool migration_in_incoming_postcopy(void)
  1438. {
  1439. PostcopyState ps = postcopy_state_get();
  1440. return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END;
  1441. }
  1442. bool migration_incoming_postcopy_advised(void)
  1443. {
  1444. PostcopyState ps = postcopy_state_get();
  1445. return ps >= POSTCOPY_INCOMING_ADVISE && ps < POSTCOPY_INCOMING_END;
  1446. }
  1447. bool migration_in_bg_snapshot(void)
  1448. {
  1449. return migrate_background_snapshot() && migration_is_running();
  1450. }
  1451. bool migration_thread_is_self(void)
  1452. {
  1453. MigrationState *s = current_migration;
  1454. return qemu_thread_is_self(&s->thread);
  1455. }
  1456. bool migrate_mode_is_cpr(MigrationState *s)
  1457. {
  1458. MigMode mode = s->parameters.mode;
  1459. return mode == MIG_MODE_CPR_REBOOT ||
  1460. mode == MIG_MODE_CPR_TRANSFER;
  1461. }
  1462. int migrate_init(MigrationState *s, Error **errp)
  1463. {
  1464. int ret;
  1465. ret = qemu_savevm_state_prepare(errp);
  1466. if (ret) {
  1467. return ret;
  1468. }
  1469. /*
  1470. * Reinitialise all migration state, except
  1471. * parameters/capabilities that the user set, and
  1472. * locks.
  1473. */
  1474. s->to_dst_file = NULL;
  1475. s->state = MIGRATION_STATUS_NONE;
  1476. s->rp_state.from_dst_file = NULL;
  1477. s->mbps = 0.0;
  1478. s->pages_per_second = 0.0;
  1479. s->downtime = 0;
  1480. s->expected_downtime = 0;
  1481. s->setup_time = 0;
  1482. s->start_postcopy = false;
  1483. s->migration_thread_running = false;
  1484. error_free(s->error);
  1485. s->error = NULL;
  1486. if (should_send_vmdesc()) {
  1487. s->vmdesc = json_writer_new(false);
  1488. }
  1489. migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
  1490. s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
  1491. s->total_time = 0;
  1492. s->vm_old_state = -1;
  1493. s->iteration_initial_bytes = 0;
  1494. s->threshold_size = 0;
  1495. s->switchover_acked = false;
  1496. s->rdma_migration = false;
  1497. /*
  1498. * set mig_stats memory to zero for a new migration
  1499. */
  1500. memset(&mig_stats, 0, sizeof(mig_stats));
  1501. migration_reset_vfio_bytes_transferred();
  1502. return 0;
  1503. }
  1504. static bool is_busy(Error **reasonp, Error **errp)
  1505. {
  1506. ERRP_GUARD();
  1507. /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
  1508. if (runstate_check(RUN_STATE_SAVE_VM) || migration_is_running()) {
  1509. error_propagate_prepend(errp, *reasonp,
  1510. "disallowing migration blocker "
  1511. "(migration/snapshot in progress) for: ");
  1512. *reasonp = NULL;
  1513. return true;
  1514. }
  1515. return false;
  1516. }
  1517. static bool is_only_migratable(Error **reasonp, Error **errp, int modes)
  1518. {
  1519. ERRP_GUARD();
  1520. if (only_migratable && (modes & BIT(MIG_MODE_NORMAL))) {
  1521. error_propagate_prepend(errp, *reasonp,
  1522. "disallowing migration blocker "
  1523. "(--only-migratable) for: ");
  1524. *reasonp = NULL;
  1525. return true;
  1526. }
  1527. return false;
  1528. }
  1529. static int get_modes(MigMode mode, va_list ap)
  1530. {
  1531. int modes = 0;
  1532. while (mode != -1 && mode != MIG_MODE_ALL) {
  1533. assert(mode >= MIG_MODE_NORMAL && mode < MIG_MODE__MAX);
  1534. modes |= BIT(mode);
  1535. mode = va_arg(ap, MigMode);
  1536. }
  1537. if (mode == MIG_MODE_ALL) {
  1538. modes = BIT(MIG_MODE__MAX) - 1;
  1539. }
  1540. return modes;
  1541. }
  1542. static int add_blockers(Error **reasonp, Error **errp, int modes)
  1543. {
  1544. for (MigMode mode = 0; mode < MIG_MODE__MAX; mode++) {
  1545. if (modes & BIT(mode)) {
  1546. migration_blockers[mode] = g_slist_prepend(migration_blockers[mode],
  1547. *reasonp);
  1548. }
  1549. }
  1550. return 0;
  1551. }
  1552. int migrate_add_blocker(Error **reasonp, Error **errp)
  1553. {
  1554. return migrate_add_blocker_modes(reasonp, errp, MIG_MODE_ALL);
  1555. }
  1556. int migrate_add_blocker_normal(Error **reasonp, Error **errp)
  1557. {
  1558. return migrate_add_blocker_modes(reasonp, errp, MIG_MODE_NORMAL, -1);
  1559. }
  1560. int migrate_add_blocker_modes(Error **reasonp, Error **errp, MigMode mode, ...)
  1561. {
  1562. int modes;
  1563. va_list ap;
  1564. va_start(ap, mode);
  1565. modes = get_modes(mode, ap);
  1566. va_end(ap);
  1567. if (is_only_migratable(reasonp, errp, modes)) {
  1568. return -EACCES;
  1569. } else if (is_busy(reasonp, errp)) {
  1570. return -EBUSY;
  1571. }
  1572. return add_blockers(reasonp, errp, modes);
  1573. }
  1574. int migrate_add_blocker_internal(Error **reasonp, Error **errp)
  1575. {
  1576. int modes = BIT(MIG_MODE__MAX) - 1;
  1577. if (is_busy(reasonp, errp)) {
  1578. return -EBUSY;
  1579. }
  1580. return add_blockers(reasonp, errp, modes);
  1581. }
  1582. void migrate_del_blocker(Error **reasonp)
  1583. {
  1584. if (*reasonp) {
  1585. for (MigMode mode = 0; mode < MIG_MODE__MAX; mode++) {
  1586. migration_blockers[mode] = g_slist_remove(migration_blockers[mode],
  1587. *reasonp);
  1588. }
  1589. error_free(*reasonp);
  1590. *reasonp = NULL;
  1591. }
  1592. }
  1593. void qmp_migrate_incoming(const char *uri, bool has_channels,
  1594. MigrationChannelList *channels,
  1595. bool has_exit_on_error, bool exit_on_error,
  1596. Error **errp)
  1597. {
  1598. Error *local_err = NULL;
  1599. static bool once = true;
  1600. MigrationIncomingState *mis = migration_incoming_get_current();
  1601. if (!once) {
  1602. error_setg(errp, "The incoming migration has already been started");
  1603. return;
  1604. }
  1605. if (!runstate_check(RUN_STATE_INMIGRATE)) {
  1606. error_setg(errp, "'-incoming' was not specified on the command line");
  1607. return;
  1608. }
  1609. if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
  1610. return;
  1611. }
  1612. mis->exit_on_error =
  1613. has_exit_on_error ? exit_on_error : INMIGRATE_DEFAULT_EXIT_ON_ERROR;
  1614. qemu_start_incoming_migration(uri, has_channels, channels, &local_err);
  1615. if (local_err) {
  1616. yank_unregister_instance(MIGRATION_YANK_INSTANCE);
  1617. error_propagate(errp, local_err);
  1618. return;
  1619. }
  1620. once = false;
  1621. }
  1622. void qmp_migrate_recover(const char *uri, Error **errp)
  1623. {
  1624. MigrationIncomingState *mis = migration_incoming_get_current();
  1625. /*
  1626. * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
  1627. * callers (no one should ignore a recover failure); if there is, it's a
  1628. * programming error.
  1629. */
  1630. assert(errp);
  1631. if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
  1632. error_setg(errp, "Migrate recover can only be run "
  1633. "when postcopy is paused.");
  1634. return;
  1635. }
  1636. /* If there's an existing transport, release it */
  1637. migration_incoming_transport_cleanup(mis);
  1638. /*
  1639. * Note that this call will never start a real migration; it will
  1640. * only re-setup the migration stream and poke existing migration
  1641. * to continue using that newly established channel.
  1642. */
  1643. qemu_start_incoming_migration(uri, false, NULL, errp);
  1644. }
  1645. void qmp_migrate_pause(Error **errp)
  1646. {
  1647. MigrationState *ms = migrate_get_current();
  1648. MigrationIncomingState *mis = migration_incoming_get_current();
  1649. int ret = 0;
  1650. if (migration_postcopy_is_alive(ms->state)) {
  1651. /* Source side, during postcopy */
  1652. Error *error = NULL;
  1653. /* Tell the core migration that we're pausing */
  1654. error_setg(&error, "Postcopy migration is paused by the user");
  1655. migrate_set_error(ms, error);
  1656. error_free(error);
  1657. qemu_mutex_lock(&ms->qemu_file_lock);
  1658. if (ms->to_dst_file) {
  1659. ret = qemu_file_shutdown(ms->to_dst_file);
  1660. }
  1661. qemu_mutex_unlock(&ms->qemu_file_lock);
  1662. if (ret) {
  1663. error_setg(errp, "Failed to pause source migration");
  1664. }
  1665. /*
  1666. * Kick the migration thread out of any waiting windows (on behalf
  1667. * of the rp thread).
  1668. */
  1669. migration_rp_kick(ms);
  1670. return;
  1671. }
  1672. if (migration_postcopy_is_alive(mis->state)) {
  1673. ret = qemu_file_shutdown(mis->from_src_file);
  1674. if (ret) {
  1675. error_setg(errp, "Failed to pause destination migration");
  1676. }
  1677. return;
  1678. }
  1679. error_setg(errp, "migrate-pause is currently only supported "
  1680. "during postcopy-active or postcopy-recover state");
  1681. }
  1682. bool migration_is_blocked(Error **errp)
  1683. {
  1684. GSList *blockers = migration_blockers[migrate_mode()];
  1685. if (qemu_savevm_state_blocked(errp)) {
  1686. return true;
  1687. }
  1688. if (blockers) {
  1689. error_propagate(errp, error_copy(blockers->data));
  1690. return true;
  1691. }
  1692. return false;
  1693. }
  1694. /* Returns true if continue to migrate, or false if error detected */
  1695. static bool migrate_prepare(MigrationState *s, bool resume, Error **errp)
  1696. {
  1697. if (resume) {
  1698. if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
  1699. error_setg(errp, "Cannot resume if there is no "
  1700. "paused migration");
  1701. return false;
  1702. }
  1703. /*
  1704. * Postcopy recovery won't work well with release-ram
  1705. * capability since release-ram will drop the page buffer as
  1706. * long as the page is put into the send buffer. So if there
  1707. * is a network failure happened, any page buffers that have
  1708. * not yet reached the destination VM but have already been
  1709. * sent from the source VM will be lost forever. Let's refuse
  1710. * the client from resuming such a postcopy migration.
  1711. * Luckily release-ram was designed to only be used when src
  1712. * and destination VMs are on the same host, so it should be
  1713. * fine.
  1714. */
  1715. if (migrate_release_ram()) {
  1716. error_setg(errp, "Postcopy recovery cannot work "
  1717. "when release-ram capability is set");
  1718. return false;
  1719. }
  1720. migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
  1721. MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP);
  1722. /* This is a resume, skip init status */
  1723. return true;
  1724. }
  1725. if (migration_is_running()) {
  1726. error_setg(errp, "There's a migration process in progress");
  1727. return false;
  1728. }
  1729. if (runstate_check(RUN_STATE_INMIGRATE)) {
  1730. error_setg(errp, "Guest is waiting for an incoming migration");
  1731. return false;
  1732. }
  1733. if (runstate_check(RUN_STATE_POSTMIGRATE)) {
  1734. error_setg(errp, "Can't migrate the vm that was paused due to "
  1735. "previous migration");
  1736. return false;
  1737. }
  1738. if (kvm_hwpoisoned_mem()) {
  1739. error_setg(errp, "Can't migrate this vm with hardware poisoned memory, "
  1740. "please reboot the vm and try again");
  1741. return false;
  1742. }
  1743. if (migration_is_blocked(errp)) {
  1744. return false;
  1745. }
  1746. if (migrate_mapped_ram()) {
  1747. if (migrate_tls()) {
  1748. error_setg(errp, "Cannot use TLS with mapped-ram");
  1749. return false;
  1750. }
  1751. if (migrate_multifd_compression()) {
  1752. error_setg(errp, "Cannot use compression with mapped-ram");
  1753. return false;
  1754. }
  1755. }
  1756. if (migrate_mode_is_cpr(s)) {
  1757. const char *conflict = NULL;
  1758. if (migrate_postcopy()) {
  1759. conflict = "postcopy";
  1760. } else if (migrate_background_snapshot()) {
  1761. conflict = "background snapshot";
  1762. } else if (migrate_colo()) {
  1763. conflict = "COLO";
  1764. }
  1765. if (conflict) {
  1766. error_setg(errp, "Cannot use %s with CPR", conflict);
  1767. return false;
  1768. }
  1769. }
  1770. if (migrate_init(s, errp)) {
  1771. return false;
  1772. }
  1773. return true;
  1774. }
  1775. static void qmp_migrate_finish(MigrationAddress *addr, bool resume_requested,
  1776. Error **errp);
  1777. static void migrate_hup_add(MigrationState *s, QIOChannel *ioc, GSourceFunc cb,
  1778. void *opaque)
  1779. {
  1780. s->hup_source = qio_channel_create_watch(ioc, G_IO_HUP);
  1781. g_source_set_callback(s->hup_source, cb, opaque, NULL);
  1782. g_source_attach(s->hup_source, NULL);
  1783. }
  1784. static void migrate_hup_delete(MigrationState *s)
  1785. {
  1786. if (s->hup_source) {
  1787. g_source_destroy(s->hup_source);
  1788. g_source_unref(s->hup_source);
  1789. s->hup_source = NULL;
  1790. }
  1791. }
  1792. static gboolean qmp_migrate_finish_cb(QIOChannel *channel,
  1793. GIOCondition cond,
  1794. void *opaque)
  1795. {
  1796. MigrationAddress *addr = opaque;
  1797. qmp_migrate_finish(addr, false, NULL);
  1798. cpr_state_close();
  1799. migrate_hup_delete(migrate_get_current());
  1800. qapi_free_MigrationAddress(addr);
  1801. return G_SOURCE_REMOVE;
  1802. }
  1803. void qmp_migrate(const char *uri, bool has_channels,
  1804. MigrationChannelList *channels, bool has_detach, bool detach,
  1805. bool has_resume, bool resume, Error **errp)
  1806. {
  1807. bool resume_requested;
  1808. Error *local_err = NULL;
  1809. MigrationState *s = migrate_get_current();
  1810. g_autoptr(MigrationChannel) channel = NULL;
  1811. MigrationAddress *addr = NULL;
  1812. MigrationChannel *channelv[MIGRATION_CHANNEL_TYPE__MAX] = { NULL };
  1813. MigrationChannel *cpr_channel = NULL;
  1814. /*
  1815. * Having preliminary checks for uri and channel
  1816. */
  1817. if (!uri == !channels) {
  1818. error_setg(errp, "need either 'uri' or 'channels' argument");
  1819. return;
  1820. }
  1821. if (channels) {
  1822. for ( ; channels; channels = channels->next) {
  1823. MigrationChannelType type = channels->value->channel_type;
  1824. if (channelv[type]) {
  1825. error_setg(errp, "Channel list has more than one %s entry",
  1826. MigrationChannelType_str(type));
  1827. return;
  1828. }
  1829. channelv[type] = channels->value;
  1830. }
  1831. cpr_channel = channelv[MIGRATION_CHANNEL_TYPE_CPR];
  1832. addr = channelv[MIGRATION_CHANNEL_TYPE_MAIN]->addr;
  1833. if (!addr) {
  1834. error_setg(errp, "Channel list has no main entry");
  1835. return;
  1836. }
  1837. }
  1838. if (uri) {
  1839. /* caller uses the old URI syntax */
  1840. if (!migrate_uri_parse(uri, &channel, errp)) {
  1841. return;
  1842. }
  1843. addr = channel->addr;
  1844. }
  1845. /* transport mechanism not suitable for migration? */
  1846. if (!migration_channels_and_transport_compatible(addr, errp)) {
  1847. return;
  1848. }
  1849. if (s->parameters.mode == MIG_MODE_CPR_TRANSFER && !cpr_channel) {
  1850. error_setg(errp, "missing 'cpr' migration channel");
  1851. return;
  1852. }
  1853. resume_requested = has_resume && resume;
  1854. if (!migrate_prepare(s, resume_requested, errp)) {
  1855. /* Error detected, put into errp */
  1856. return;
  1857. }
  1858. if (cpr_state_save(cpr_channel, &local_err)) {
  1859. goto out;
  1860. }
  1861. /*
  1862. * For cpr-transfer, the target may not be listening yet on the migration
  1863. * channel, because first it must finish cpr_load_state. The target tells
  1864. * us it is listening by closing the cpr-state socket. Wait for that HUP
  1865. * event before connecting in qmp_migrate_finish.
  1866. *
  1867. * The HUP could occur because the target fails while reading CPR state,
  1868. * in which case the target will not listen for the incoming migration
  1869. * connection, so qmp_migrate_finish will fail to connect, and then recover.
  1870. */
  1871. if (s->parameters.mode == MIG_MODE_CPR_TRANSFER) {
  1872. migrate_hup_add(s, cpr_state_ioc(), (GSourceFunc)qmp_migrate_finish_cb,
  1873. QAPI_CLONE(MigrationAddress, addr));
  1874. } else {
  1875. qmp_migrate_finish(addr, resume_requested, errp);
  1876. }
  1877. out:
  1878. if (local_err) {
  1879. migrate_fd_error(s, local_err);
  1880. error_propagate(errp, local_err);
  1881. }
  1882. }
  1883. static void qmp_migrate_finish(MigrationAddress *addr, bool resume_requested,
  1884. Error **errp)
  1885. {
  1886. MigrationState *s = migrate_get_current();
  1887. Error *local_err = NULL;
  1888. if (!resume_requested) {
  1889. if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
  1890. return;
  1891. }
  1892. }
  1893. if (addr->transport == MIGRATION_ADDRESS_TYPE_SOCKET) {
  1894. SocketAddress *saddr = &addr->u.socket;
  1895. if (saddr->type == SOCKET_ADDRESS_TYPE_INET ||
  1896. saddr->type == SOCKET_ADDRESS_TYPE_UNIX ||
  1897. saddr->type == SOCKET_ADDRESS_TYPE_VSOCK) {
  1898. socket_start_outgoing_migration(s, saddr, &local_err);
  1899. } else if (saddr->type == SOCKET_ADDRESS_TYPE_FD) {
  1900. fd_start_outgoing_migration(s, saddr->u.fd.str, &local_err);
  1901. }
  1902. #ifdef CONFIG_RDMA
  1903. } else if (addr->transport == MIGRATION_ADDRESS_TYPE_RDMA) {
  1904. rdma_start_outgoing_migration(s, &addr->u.rdma, &local_err);
  1905. #endif
  1906. } else if (addr->transport == MIGRATION_ADDRESS_TYPE_EXEC) {
  1907. exec_start_outgoing_migration(s, addr->u.exec.args, &local_err);
  1908. } else if (addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
  1909. file_start_outgoing_migration(s, &addr->u.file, &local_err);
  1910. } else {
  1911. error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "uri",
  1912. "a valid migration protocol");
  1913. migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
  1914. MIGRATION_STATUS_FAILED);
  1915. }
  1916. if (local_err) {
  1917. if (!resume_requested) {
  1918. yank_unregister_instance(MIGRATION_YANK_INSTANCE);
  1919. }
  1920. migrate_fd_error(s, local_err);
  1921. error_propagate(errp, local_err);
  1922. return;
  1923. }
  1924. }
  1925. void qmp_migrate_cancel(Error **errp)
  1926. {
  1927. migration_cancel(NULL);
  1928. }
  1929. void qmp_migrate_continue(MigrationStatus state, Error **errp)
  1930. {
  1931. MigrationState *s = migrate_get_current();
  1932. if (s->state != state) {
  1933. error_setg(errp, "Migration not in expected state: %s",
  1934. MigrationStatus_str(s->state));
  1935. return;
  1936. }
  1937. qemu_sem_post(&s->pause_sem);
  1938. }
  1939. int migration_rp_wait(MigrationState *s)
  1940. {
  1941. /* If migration has failure already, ignore the wait */
  1942. if (migrate_has_error(s)) {
  1943. return -1;
  1944. }
  1945. qemu_sem_wait(&s->rp_state.rp_sem);
  1946. /* After wait, double check that there's no failure */
  1947. if (migrate_has_error(s)) {
  1948. return -1;
  1949. }
  1950. return 0;
  1951. }
  1952. void migration_rp_kick(MigrationState *s)
  1953. {
  1954. qemu_sem_post(&s->rp_state.rp_sem);
  1955. }
  1956. static struct rp_cmd_args {
  1957. ssize_t len; /* -1 = variable */
  1958. const char *name;
  1959. } rp_cmd_args[] = {
  1960. [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
  1961. [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
  1962. [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
  1963. [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
  1964. [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
  1965. [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
  1966. [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
  1967. [MIG_RP_MSG_SWITCHOVER_ACK] = { .len = 0, .name = "SWITCHOVER_ACK" },
  1968. [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
  1969. };
  1970. /*
  1971. * Process a request for pages received on the return path,
  1972. * We're allowed to send more than requested (e.g. to round to our page size)
  1973. * and we don't need to send pages that have already been sent.
  1974. */
  1975. static void
  1976. migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
  1977. ram_addr_t start, size_t len, Error **errp)
  1978. {
  1979. long our_host_ps = qemu_real_host_page_size();
  1980. trace_migrate_handle_rp_req_pages(rbname, start, len);
  1981. /*
  1982. * Since we currently insist on matching page sizes, just sanity check
  1983. * we're being asked for whole host pages.
  1984. */
  1985. if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
  1986. !QEMU_IS_ALIGNED(len, our_host_ps)) {
  1987. error_setg(errp, "MIG_RP_MSG_REQ_PAGES: Misaligned page request, start:"
  1988. RAM_ADDR_FMT " len: %zd", start, len);
  1989. return;
  1990. }
  1991. ram_save_queue_pages(rbname, start, len, errp);
  1992. }
  1993. static bool migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name,
  1994. Error **errp)
  1995. {
  1996. RAMBlock *block = qemu_ram_block_by_name(block_name);
  1997. if (!block) {
  1998. error_setg(errp, "MIG_RP_MSG_RECV_BITMAP has invalid block name '%s'",
  1999. block_name);
  2000. return false;
  2001. }
  2002. /* Fetch the received bitmap and refresh the dirty bitmap */
  2003. return ram_dirty_bitmap_reload(s, block, errp);
  2004. }
  2005. static bool migrate_handle_rp_resume_ack(MigrationState *s,
  2006. uint32_t value, Error **errp)
  2007. {
  2008. trace_source_return_path_thread_resume_ack(value);
  2009. if (value != MIGRATION_RESUME_ACK_VALUE) {
  2010. error_setg(errp, "illegal resume_ack value %"PRIu32, value);
  2011. return false;
  2012. }
  2013. /* Now both sides are active. */
  2014. migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
  2015. MIGRATION_STATUS_POSTCOPY_ACTIVE);
  2016. /* Notify send thread that time to continue send pages */
  2017. migration_rp_kick(s);
  2018. return true;
  2019. }
  2020. /*
  2021. * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
  2022. * existed) in a safe way.
  2023. */
  2024. static void migration_release_dst_files(MigrationState *ms)
  2025. {
  2026. QEMUFile *file = NULL;
  2027. WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
  2028. /*
  2029. * Reset the from_dst_file pointer first before releasing it, as we
  2030. * can't block within lock section
  2031. */
  2032. file = ms->rp_state.from_dst_file;
  2033. ms->rp_state.from_dst_file = NULL;
  2034. }
  2035. /*
  2036. * Do the same to postcopy fast path socket too if there is. No
  2037. * locking needed because this qemufile should only be managed by
  2038. * return path thread.
  2039. */
  2040. if (ms->postcopy_qemufile_src) {
  2041. migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src);
  2042. qemu_file_shutdown(ms->postcopy_qemufile_src);
  2043. qemu_fclose(ms->postcopy_qemufile_src);
  2044. ms->postcopy_qemufile_src = NULL;
  2045. }
  2046. qemu_fclose(file);
  2047. }
  2048. /*
  2049. * Handles messages sent on the return path towards the source VM
  2050. *
  2051. */
  2052. static void *source_return_path_thread(void *opaque)
  2053. {
  2054. MigrationState *ms = opaque;
  2055. QEMUFile *rp = ms->rp_state.from_dst_file;
  2056. uint16_t header_len, header_type;
  2057. uint8_t buf[512];
  2058. uint32_t tmp32, sibling_error;
  2059. ram_addr_t start = 0; /* =0 to silence warning */
  2060. size_t len = 0, expected_len;
  2061. Error *err = NULL;
  2062. int res;
  2063. trace_source_return_path_thread_entry();
  2064. rcu_register_thread();
  2065. while (migration_is_running()) {
  2066. trace_source_return_path_thread_loop_top();
  2067. header_type = qemu_get_be16(rp);
  2068. header_len = qemu_get_be16(rp);
  2069. if (qemu_file_get_error(rp)) {
  2070. qemu_file_get_error_obj(rp, &err);
  2071. goto out;
  2072. }
  2073. if (header_type >= MIG_RP_MSG_MAX ||
  2074. header_type == MIG_RP_MSG_INVALID) {
  2075. error_setg(&err, "Received invalid message 0x%04x length 0x%04x",
  2076. header_type, header_len);
  2077. goto out;
  2078. }
  2079. if ((rp_cmd_args[header_type].len != -1 &&
  2080. header_len != rp_cmd_args[header_type].len) ||
  2081. header_len > sizeof(buf)) {
  2082. error_setg(&err, "Received '%s' message (0x%04x) with"
  2083. "incorrect length %d expecting %zu",
  2084. rp_cmd_args[header_type].name, header_type, header_len,
  2085. (size_t)rp_cmd_args[header_type].len);
  2086. goto out;
  2087. }
  2088. /* We know we've got a valid header by this point */
  2089. res = qemu_get_buffer(rp, buf, header_len);
  2090. if (res != header_len) {
  2091. error_setg(&err, "Failed reading data for message 0x%04x"
  2092. " read %d expected %d",
  2093. header_type, res, header_len);
  2094. goto out;
  2095. }
  2096. /* OK, we have the message and the data */
  2097. switch (header_type) {
  2098. case MIG_RP_MSG_SHUT:
  2099. sibling_error = ldl_be_p(buf);
  2100. trace_source_return_path_thread_shut(sibling_error);
  2101. if (sibling_error) {
  2102. error_setg(&err, "Sibling indicated error %d", sibling_error);
  2103. }
  2104. /*
  2105. * We'll let the main thread deal with closing the RP
  2106. * we could do a shutdown(2) on it, but we're the only user
  2107. * anyway, so there's nothing gained.
  2108. */
  2109. goto out;
  2110. case MIG_RP_MSG_PONG:
  2111. tmp32 = ldl_be_p(buf);
  2112. trace_source_return_path_thread_pong(tmp32);
  2113. qemu_sem_post(&ms->rp_state.rp_pong_acks);
  2114. break;
  2115. case MIG_RP_MSG_REQ_PAGES:
  2116. start = ldq_be_p(buf);
  2117. len = ldl_be_p(buf + 8);
  2118. migrate_handle_rp_req_pages(ms, NULL, start, len, &err);
  2119. if (err) {
  2120. goto out;
  2121. }
  2122. break;
  2123. case MIG_RP_MSG_REQ_PAGES_ID:
  2124. expected_len = 12 + 1; /* header + termination */
  2125. if (header_len >= expected_len) {
  2126. start = ldq_be_p(buf);
  2127. len = ldl_be_p(buf + 8);
  2128. /* Now we expect an idstr */
  2129. tmp32 = buf[12]; /* Length of the following idstr */
  2130. buf[13 + tmp32] = '\0';
  2131. expected_len += tmp32;
  2132. }
  2133. if (header_len != expected_len) {
  2134. error_setg(&err, "Req_Page_id with length %d expecting %zd",
  2135. header_len, expected_len);
  2136. goto out;
  2137. }
  2138. migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len,
  2139. &err);
  2140. if (err) {
  2141. goto out;
  2142. }
  2143. break;
  2144. case MIG_RP_MSG_RECV_BITMAP:
  2145. if (header_len < 1) {
  2146. error_setg(&err, "MIG_RP_MSG_RECV_BITMAP missing block name");
  2147. goto out;
  2148. }
  2149. /* Format: len (1B) + idstr (<255B). This ends the idstr. */
  2150. buf[buf[0] + 1] = '\0';
  2151. if (!migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1), &err)) {
  2152. goto out;
  2153. }
  2154. break;
  2155. case MIG_RP_MSG_RESUME_ACK:
  2156. tmp32 = ldl_be_p(buf);
  2157. if (!migrate_handle_rp_resume_ack(ms, tmp32, &err)) {
  2158. goto out;
  2159. }
  2160. break;
  2161. case MIG_RP_MSG_SWITCHOVER_ACK:
  2162. ms->switchover_acked = true;
  2163. trace_source_return_path_thread_switchover_acked();
  2164. break;
  2165. default:
  2166. break;
  2167. }
  2168. }
  2169. out:
  2170. if (err) {
  2171. migrate_set_error(ms, err);
  2172. error_free(err);
  2173. trace_source_return_path_thread_bad_end();
  2174. }
  2175. if (ms->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
  2176. /*
  2177. * this will be extremely unlikely: that we got yet another network
  2178. * issue during recovering of the 1st network failure.. during this
  2179. * period the main migration thread can be waiting on rp_sem for
  2180. * this thread to sync with the other side.
  2181. *
  2182. * When this happens, explicitly kick the migration thread out of
  2183. * RECOVER stage and back to PAUSED, so the admin can try
  2184. * everything again.
  2185. */
  2186. migration_rp_kick(ms);
  2187. }
  2188. trace_source_return_path_thread_end();
  2189. rcu_unregister_thread();
  2190. return NULL;
  2191. }
  2192. static int open_return_path_on_source(MigrationState *ms)
  2193. {
  2194. ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
  2195. if (!ms->rp_state.from_dst_file) {
  2196. return -1;
  2197. }
  2198. trace_open_return_path_on_source();
  2199. qemu_thread_create(&ms->rp_state.rp_thread, MIGRATION_THREAD_SRC_RETURN,
  2200. source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
  2201. ms->rp_state.rp_thread_created = true;
  2202. trace_open_return_path_on_source_continue();
  2203. return 0;
  2204. }
  2205. /* Return true if error detected, or false otherwise */
  2206. static bool close_return_path_on_source(MigrationState *ms)
  2207. {
  2208. if (!ms->rp_state.rp_thread_created) {
  2209. return false;
  2210. }
  2211. trace_migration_return_path_end_before();
  2212. /*
  2213. * If this is a normal exit then the destination will send a SHUT
  2214. * and the rp_thread will exit, however if there's an error we
  2215. * need to cause it to exit. shutdown(2), if we have it, will
  2216. * cause it to unblock if it's stuck waiting for the destination.
  2217. */
  2218. WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
  2219. if (migrate_has_error(ms) && ms->rp_state.from_dst_file) {
  2220. qemu_file_shutdown(ms->rp_state.from_dst_file);
  2221. }
  2222. }
  2223. qemu_thread_join(&ms->rp_state.rp_thread);
  2224. ms->rp_state.rp_thread_created = false;
  2225. migration_release_dst_files(ms);
  2226. trace_migration_return_path_end_after();
  2227. /* Return path will persist the error in MigrationState when quit */
  2228. return migrate_has_error(ms);
  2229. }
  2230. static inline void
  2231. migration_wait_main_channel(MigrationState *ms)
  2232. {
  2233. /* Wait until one PONG message received */
  2234. qemu_sem_wait(&ms->rp_state.rp_pong_acks);
  2235. }
  2236. /*
  2237. * Switch from normal iteration to postcopy
  2238. * Returns non-0 on error
  2239. */
  2240. static int postcopy_start(MigrationState *ms, Error **errp)
  2241. {
  2242. int ret;
  2243. QIOChannelBuffer *bioc;
  2244. QEMUFile *fb;
  2245. /*
  2246. * Now we're 100% sure to switch to postcopy, so JSON writer won't be
  2247. * useful anymore. Free the resources early if it is there. Clearing
  2248. * the vmdesc also means any follow up vmstate_save()s will start to
  2249. * skip all JSON operations, which can shrink postcopy downtime.
  2250. */
  2251. migration_cleanup_json_writer(ms);
  2252. if (migrate_postcopy_preempt()) {
  2253. migration_wait_main_channel(ms);
  2254. if (postcopy_preempt_establish_channel(ms)) {
  2255. migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED);
  2256. error_setg(errp, "%s: Failed to establish preempt channel",
  2257. __func__);
  2258. return -1;
  2259. }
  2260. }
  2261. trace_postcopy_start();
  2262. bql_lock();
  2263. trace_postcopy_start_set_run();
  2264. ret = migration_stop_vm(ms, RUN_STATE_FINISH_MIGRATE);
  2265. if (ret < 0) {
  2266. error_setg_errno(errp, -ret, "%s: Failed to stop the VM", __func__);
  2267. goto fail;
  2268. }
  2269. if (!migration_switchover_start(ms, errp)) {
  2270. goto fail;
  2271. }
  2272. /*
  2273. * Cause any non-postcopiable, but iterative devices to
  2274. * send out their final data.
  2275. */
  2276. ret = qemu_savevm_state_complete_precopy_iterable(ms->to_dst_file, true);
  2277. if (ret) {
  2278. error_setg(errp, "Postcopy save non-postcopiable iterables failed");
  2279. goto fail;
  2280. }
  2281. /*
  2282. * in Finish migrate and with the io-lock held everything should
  2283. * be quiet, but we've potentially still got dirty pages and we
  2284. * need to tell the destination to throw any pages it's already received
  2285. * that are dirty
  2286. */
  2287. if (migrate_postcopy_ram()) {
  2288. ram_postcopy_send_discard_bitmap(ms);
  2289. }
  2290. if (migrate_postcopy_ram()) {
  2291. /* Ping just for debugging, helps line traces up */
  2292. qemu_savevm_send_ping(ms->to_dst_file, 2);
  2293. }
  2294. /*
  2295. * While loading the device state we may trigger page transfer
  2296. * requests and the fd must be free to process those, and thus
  2297. * the destination must read the whole device state off the fd before
  2298. * it starts processing it. Unfortunately the ad-hoc migration format
  2299. * doesn't allow the destination to know the size to read without fully
  2300. * parsing it through each devices load-state code (especially the open
  2301. * coded devices that use get/put).
  2302. * So we wrap the device state up in a package with a length at the start;
  2303. * to do this we use a qemu_buf to hold the whole of the device state.
  2304. */
  2305. bioc = qio_channel_buffer_new(4096);
  2306. qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
  2307. fb = qemu_file_new_output(QIO_CHANNEL(bioc));
  2308. object_unref(OBJECT(bioc));
  2309. /*
  2310. * Make sure the receiver can get incoming pages before we send the rest
  2311. * of the state
  2312. */
  2313. qemu_savevm_send_postcopy_listen(fb);
  2314. ret = qemu_savevm_state_complete_precopy_non_iterable(fb, true);
  2315. if (ret) {
  2316. error_setg(errp, "Postcopy save non-iterable device states failed");
  2317. goto fail_closefb;
  2318. }
  2319. if (migrate_postcopy_ram()) {
  2320. qemu_savevm_send_ping(fb, 3);
  2321. }
  2322. qemu_savevm_send_postcopy_run(fb);
  2323. /* <><> end of stuff going into the package */
  2324. /* Last point of recovery; as soon as we send the package the destination
  2325. * can open devices and potentially start running.
  2326. * Lets just check again we've not got any errors.
  2327. */
  2328. ret = qemu_file_get_error(ms->to_dst_file);
  2329. if (ret) {
  2330. error_setg(errp, "postcopy_start: Migration stream errored (pre package)");
  2331. goto fail_closefb;
  2332. }
  2333. /* Now send that blob */
  2334. if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
  2335. error_setg(errp, "%s: Failed to send packaged data", __func__);
  2336. goto fail_closefb;
  2337. }
  2338. qemu_fclose(fb);
  2339. /* Send a notify to give a chance for anything that needs to happen
  2340. * at the transition to postcopy and after the device state; in particular
  2341. * spice needs to trigger a transition now
  2342. */
  2343. migration_call_notifiers(ms, MIG_EVENT_PRECOPY_DONE, NULL);
  2344. migration_downtime_end(ms);
  2345. if (migrate_postcopy_ram()) {
  2346. /*
  2347. * Although this ping is just for debug, it could potentially be
  2348. * used for getting a better measurement of downtime at the source.
  2349. */
  2350. qemu_savevm_send_ping(ms->to_dst_file, 4);
  2351. }
  2352. if (migrate_release_ram()) {
  2353. ram_postcopy_migrated_memory_release(ms);
  2354. }
  2355. ret = qemu_file_get_error(ms->to_dst_file);
  2356. if (ret) {
  2357. error_setg_errno(errp, -ret, "postcopy_start: Migration stream error");
  2358. goto fail;
  2359. }
  2360. trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
  2361. /*
  2362. * Now postcopy officially started, switch to postcopy bandwidth that
  2363. * user specified.
  2364. */
  2365. migration_rate_set(migrate_max_postcopy_bandwidth());
  2366. /* Now, switchover looks all fine, switching to postcopy-active */
  2367. migrate_set_state(&ms->state, MIGRATION_STATUS_DEVICE,
  2368. MIGRATION_STATUS_POSTCOPY_ACTIVE);
  2369. bql_unlock();
  2370. return ret;
  2371. fail_closefb:
  2372. qemu_fclose(fb);
  2373. fail:
  2374. migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
  2375. MIGRATION_STATUS_FAILED);
  2376. migration_block_activate(NULL);
  2377. migration_call_notifiers(ms, MIG_EVENT_PRECOPY_FAILED, NULL);
  2378. bql_unlock();
  2379. return -1;
  2380. }
  2381. /**
  2382. * @migration_switchover_prepare: Start VM switchover procedure
  2383. *
  2384. * @s: The migration state object pointer
  2385. *
  2386. * Prepares for the switchover, depending on "pause-before-switchover"
  2387. * capability.
  2388. *
  2389. * If cap set, state machine goes like:
  2390. * [postcopy-]active -> pre-switchover -> device
  2391. *
  2392. * If cap not set:
  2393. * [postcopy-]active -> device
  2394. *
  2395. * Returns: true on success, false on interruptions.
  2396. */
  2397. static bool migration_switchover_prepare(MigrationState *s)
  2398. {
  2399. /* Concurrent cancellation? Quit */
  2400. if (s->state == MIGRATION_STATUS_CANCELLING) {
  2401. return false;
  2402. }
  2403. /*
  2404. * No matter precopy or postcopy, since we still hold BQL it must not
  2405. * change concurrently to CANCELLING, so it must be either ACTIVE or
  2406. * POSTCOPY_ACTIVE.
  2407. */
  2408. assert(migration_is_active());
  2409. /* If the pre stage not requested, directly switch to DEVICE */
  2410. if (!migrate_pause_before_switchover()) {
  2411. migrate_set_state(&s->state, s->state, MIGRATION_STATUS_DEVICE);
  2412. return true;
  2413. }
  2414. /* Since leaving this state is not atomic with posting the semaphore
  2415. * it's possible that someone could have issued multiple migrate_continue
  2416. * and the semaphore is incorrectly positive at this point;
  2417. * the docs say it's undefined to reinit a semaphore that's already
  2418. * init'd, so use timedwait to eat up any existing posts.
  2419. */
  2420. while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
  2421. /* This block intentionally left blank */
  2422. }
  2423. /* Update [POSTCOPY_]ACTIVE to PRE_SWITCHOVER */
  2424. migrate_set_state(&s->state, s->state, MIGRATION_STATUS_PRE_SWITCHOVER);
  2425. bql_unlock();
  2426. qemu_sem_wait(&s->pause_sem);
  2427. bql_lock();
  2428. /*
  2429. * After BQL released and retaken, the state can be CANCELLING if it
  2430. * happend during sem_wait().. Only change the state if it's still
  2431. * pre-switchover.
  2432. */
  2433. migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
  2434. MIGRATION_STATUS_DEVICE);
  2435. return s->state == MIGRATION_STATUS_DEVICE;
  2436. }
  2437. static bool migration_switchover_start(MigrationState *s, Error **errp)
  2438. {
  2439. ERRP_GUARD();
  2440. if (!migration_switchover_prepare(s)) {
  2441. error_setg(errp, "Switchover is interrupted");
  2442. return false;
  2443. }
  2444. /* Inactivate disks except in COLO */
  2445. if (!migrate_colo()) {
  2446. /*
  2447. * Inactivate before sending QEMU_VM_EOF so that the
  2448. * bdrv_activate_all() on the other end won't fail.
  2449. */
  2450. if (!migration_block_inactivate()) {
  2451. error_setg(errp, "Block inactivate failed during switchover");
  2452. return false;
  2453. }
  2454. }
  2455. migration_rate_set(RATE_LIMIT_DISABLED);
  2456. precopy_notify_complete();
  2457. return true;
  2458. }
  2459. static int migration_completion_precopy(MigrationState *s)
  2460. {
  2461. int ret;
  2462. bql_lock();
  2463. if (!migrate_mode_is_cpr(s)) {
  2464. ret = migration_stop_vm(s, RUN_STATE_FINISH_MIGRATE);
  2465. if (ret < 0) {
  2466. goto out_unlock;
  2467. }
  2468. }
  2469. if (!migration_switchover_start(s, NULL)) {
  2470. ret = -EFAULT;
  2471. goto out_unlock;
  2472. }
  2473. ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false);
  2474. out_unlock:
  2475. bql_unlock();
  2476. return ret;
  2477. }
  2478. static void migration_completion_postcopy(MigrationState *s)
  2479. {
  2480. trace_migration_completion_postcopy_end();
  2481. bql_lock();
  2482. qemu_savevm_state_complete_postcopy(s->to_dst_file);
  2483. bql_unlock();
  2484. /*
  2485. * Shutdown the postcopy fast path thread. This is only needed when dest
  2486. * QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need this.
  2487. */
  2488. if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
  2489. postcopy_preempt_shutdown_file(s);
  2490. }
  2491. trace_migration_completion_postcopy_end_after_complete();
  2492. }
  2493. /**
  2494. * migration_completion: Used by migration_thread when there's not much left.
  2495. * The caller 'breaks' the loop when this returns.
  2496. *
  2497. * @s: Current migration state
  2498. */
  2499. static void migration_completion(MigrationState *s)
  2500. {
  2501. int ret = 0;
  2502. Error *local_err = NULL;
  2503. if (s->state == MIGRATION_STATUS_ACTIVE) {
  2504. ret = migration_completion_precopy(s);
  2505. } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
  2506. migration_completion_postcopy(s);
  2507. } else {
  2508. ret = -1;
  2509. }
  2510. if (ret < 0) {
  2511. goto fail;
  2512. }
  2513. if (close_return_path_on_source(s)) {
  2514. goto fail;
  2515. }
  2516. if (qemu_file_get_error(s->to_dst_file)) {
  2517. trace_migration_completion_file_err();
  2518. goto fail;
  2519. }
  2520. if (migrate_colo() && s->state == MIGRATION_STATUS_ACTIVE) {
  2521. /* COLO does not support postcopy */
  2522. migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
  2523. MIGRATION_STATUS_COLO);
  2524. } else {
  2525. migration_completion_end(s);
  2526. }
  2527. return;
  2528. fail:
  2529. if (qemu_file_get_error_obj(s->to_dst_file, &local_err)) {
  2530. migrate_set_error(s, local_err);
  2531. error_free(local_err);
  2532. } else if (ret) {
  2533. error_setg_errno(&local_err, -ret, "Error in migration completion");
  2534. migrate_set_error(s, local_err);
  2535. error_free(local_err);
  2536. }
  2537. migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
  2538. }
  2539. /**
  2540. * bg_migration_completion: Used by bg_migration_thread when after all the
  2541. * RAM has been saved. The caller 'breaks' the loop when this returns.
  2542. *
  2543. * @s: Current migration state
  2544. */
  2545. static void bg_migration_completion(MigrationState *s)
  2546. {
  2547. int current_active_state = s->state;
  2548. if (s->state == MIGRATION_STATUS_ACTIVE) {
  2549. /*
  2550. * By this moment we have RAM content saved into the migration stream.
  2551. * The next step is to flush the non-RAM content (device state)
  2552. * right after the ram content. The device state has been stored into
  2553. * the temporary buffer before RAM saving started.
  2554. */
  2555. qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
  2556. qemu_fflush(s->to_dst_file);
  2557. } else if (s->state == MIGRATION_STATUS_CANCELLING) {
  2558. goto fail;
  2559. }
  2560. if (qemu_file_get_error(s->to_dst_file)) {
  2561. trace_migration_completion_file_err();
  2562. goto fail;
  2563. }
  2564. migration_completion_end(s);
  2565. return;
  2566. fail:
  2567. migrate_set_state(&s->state, current_active_state,
  2568. MIGRATION_STATUS_FAILED);
  2569. }
  2570. typedef enum MigThrError {
  2571. /* No error detected */
  2572. MIG_THR_ERR_NONE = 0,
  2573. /* Detected error, but resumed successfully */
  2574. MIG_THR_ERR_RECOVERED = 1,
  2575. /* Detected fatal error, need to exit */
  2576. MIG_THR_ERR_FATAL = 2,
  2577. } MigThrError;
  2578. static int postcopy_resume_handshake(MigrationState *s)
  2579. {
  2580. qemu_savevm_send_postcopy_resume(s->to_dst_file);
  2581. while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
  2582. if (migration_rp_wait(s)) {
  2583. return -1;
  2584. }
  2585. }
  2586. if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
  2587. return 0;
  2588. }
  2589. return -1;
  2590. }
  2591. /* Return zero if success, or <0 for error */
  2592. static int postcopy_do_resume(MigrationState *s)
  2593. {
  2594. int ret;
  2595. /*
  2596. * Call all the resume_prepare() hooks, so that modules can be
  2597. * ready for the migration resume.
  2598. */
  2599. ret = qemu_savevm_state_resume_prepare(s);
  2600. if (ret) {
  2601. error_report("%s: resume_prepare() failure detected: %d",
  2602. __func__, ret);
  2603. return ret;
  2604. }
  2605. /*
  2606. * If preempt is enabled, re-establish the preempt channel. Note that
  2607. * we do it after resume prepare to make sure the main channel will be
  2608. * created before the preempt channel. E.g. with weak network, the
  2609. * dest QEMU may get messed up with the preempt and main channels on
  2610. * the order of connection setup. This guarantees the correct order.
  2611. */
  2612. ret = postcopy_preempt_establish_channel(s);
  2613. if (ret) {
  2614. error_report("%s: postcopy_preempt_establish_channel(): %d",
  2615. __func__, ret);
  2616. return ret;
  2617. }
  2618. /*
  2619. * Last handshake with destination on the resume (destination will
  2620. * switch to postcopy-active afterwards)
  2621. */
  2622. ret = postcopy_resume_handshake(s);
  2623. if (ret) {
  2624. error_report("%s: handshake failed: %d", __func__, ret);
  2625. return ret;
  2626. }
  2627. return 0;
  2628. }
  2629. /*
  2630. * We don't return until we are in a safe state to continue current
  2631. * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
  2632. * MIG_THR_ERR_FATAL if unrecovery failure happened.
  2633. */
  2634. static MigThrError postcopy_pause(MigrationState *s)
  2635. {
  2636. assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
  2637. while (true) {
  2638. QEMUFile *file;
  2639. /*
  2640. * We're already pausing, so ignore any errors on the return
  2641. * path and just wait for the thread to finish. It will be
  2642. * re-created when we resume.
  2643. */
  2644. close_return_path_on_source(s);
  2645. /*
  2646. * Current channel is possibly broken. Release it. Note that this is
  2647. * guaranteed even without lock because to_dst_file should only be
  2648. * modified by the migration thread. That also guarantees that the
  2649. * unregister of yank is safe too without the lock. It should be safe
  2650. * even to be within the qemu_file_lock, but we didn't do that to avoid
  2651. * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
  2652. * the qemu_file_lock critical section as small as possible.
  2653. */
  2654. assert(s->to_dst_file);
  2655. migration_ioc_unregister_yank_from_file(s->to_dst_file);
  2656. qemu_mutex_lock(&s->qemu_file_lock);
  2657. file = s->to_dst_file;
  2658. s->to_dst_file = NULL;
  2659. qemu_mutex_unlock(&s->qemu_file_lock);
  2660. qemu_file_shutdown(file);
  2661. qemu_fclose(file);
  2662. migrate_set_state(&s->state, s->state,
  2663. MIGRATION_STATUS_POSTCOPY_PAUSED);
  2664. error_report("Detected IO failure for postcopy. "
  2665. "Migration paused.");
  2666. /*
  2667. * We wait until things fixed up. Then someone will setup the
  2668. * status back for us.
  2669. */
  2670. do {
  2671. qemu_sem_wait(&s->postcopy_pause_sem);
  2672. } while (postcopy_is_paused(s->state));
  2673. if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
  2674. /* Woken up by a recover procedure. Give it a shot */
  2675. /* Do the resume logic */
  2676. if (postcopy_do_resume(s) == 0) {
  2677. /* Let's continue! */
  2678. trace_postcopy_pause_continued();
  2679. return MIG_THR_ERR_RECOVERED;
  2680. } else {
  2681. /*
  2682. * Something wrong happened during the recovery, let's
  2683. * pause again. Pause is always better than throwing
  2684. * data away.
  2685. */
  2686. continue;
  2687. }
  2688. } else {
  2689. /* This is not right... Time to quit. */
  2690. return MIG_THR_ERR_FATAL;
  2691. }
  2692. }
  2693. }
  2694. void migration_file_set_error(int ret, Error *err)
  2695. {
  2696. MigrationState *s = current_migration;
  2697. WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
  2698. if (s->to_dst_file) {
  2699. qemu_file_set_error_obj(s->to_dst_file, ret, err);
  2700. } else if (err) {
  2701. error_report_err(err);
  2702. }
  2703. }
  2704. }
  2705. static MigThrError migration_detect_error(MigrationState *s)
  2706. {
  2707. int ret;
  2708. int state = s->state;
  2709. Error *local_error = NULL;
  2710. if (state == MIGRATION_STATUS_CANCELLING ||
  2711. state == MIGRATION_STATUS_CANCELLED) {
  2712. /* End the migration, but don't set the state to failed */
  2713. return MIG_THR_ERR_FATAL;
  2714. }
  2715. /*
  2716. * Try to detect any file errors. Note that postcopy_qemufile_src will
  2717. * be NULL when postcopy preempt is not enabled.
  2718. */
  2719. ret = qemu_file_get_error_obj_any(s->to_dst_file,
  2720. s->postcopy_qemufile_src,
  2721. &local_error);
  2722. if (!ret) {
  2723. /* Everything is fine */
  2724. assert(!local_error);
  2725. return MIG_THR_ERR_NONE;
  2726. }
  2727. if (local_error) {
  2728. migrate_set_error(s, local_error);
  2729. error_free(local_error);
  2730. }
  2731. if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
  2732. /*
  2733. * For postcopy, we allow the network to be down for a
  2734. * while. After that, it can be continued by a
  2735. * recovery phase.
  2736. */
  2737. return postcopy_pause(s);
  2738. } else {
  2739. /*
  2740. * For precopy (or postcopy with error outside IO), we fail
  2741. * with no time.
  2742. */
  2743. migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
  2744. trace_migration_thread_file_err();
  2745. /* Time to stop the migration, now. */
  2746. return MIG_THR_ERR_FATAL;
  2747. }
  2748. }
  2749. static void migration_completion_end(MigrationState *s)
  2750. {
  2751. uint64_t bytes = migration_transferred_bytes();
  2752. int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
  2753. int64_t transfer_time;
  2754. /*
  2755. * Take the BQL here so that query-migrate on the QMP thread sees:
  2756. * - atomic update of s->total_time and s->mbps;
  2757. * - correct ordering of s->mbps update vs. s->state;
  2758. */
  2759. bql_lock();
  2760. migration_downtime_end(s);
  2761. s->total_time = end_time - s->start_time;
  2762. transfer_time = s->total_time - s->setup_time;
  2763. if (transfer_time) {
  2764. s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
  2765. }
  2766. migrate_set_state(&s->state, s->state,
  2767. MIGRATION_STATUS_COMPLETED);
  2768. bql_unlock();
  2769. }
  2770. static void update_iteration_initial_status(MigrationState *s)
  2771. {
  2772. /*
  2773. * Update these three fields at the same time to avoid mismatch info lead
  2774. * wrong speed calculation.
  2775. */
  2776. s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
  2777. s->iteration_initial_bytes = migration_transferred_bytes();
  2778. s->iteration_initial_pages = ram_get_total_transferred_pages();
  2779. }
  2780. static void migration_update_counters(MigrationState *s,
  2781. int64_t current_time)
  2782. {
  2783. uint64_t transferred, transferred_pages, time_spent;
  2784. uint64_t current_bytes; /* bytes transferred since the beginning */
  2785. uint64_t switchover_bw;
  2786. /* Expected bandwidth when switching over to destination QEMU */
  2787. double expected_bw_per_ms;
  2788. double bandwidth;
  2789. if (current_time < s->iteration_start_time + BUFFER_DELAY) {
  2790. return;
  2791. }
  2792. switchover_bw = migrate_avail_switchover_bandwidth();
  2793. current_bytes = migration_transferred_bytes();
  2794. transferred = current_bytes - s->iteration_initial_bytes;
  2795. time_spent = current_time - s->iteration_start_time;
  2796. bandwidth = (double)transferred / time_spent;
  2797. if (switchover_bw) {
  2798. /*
  2799. * If the user specified a switchover bandwidth, let's trust the
  2800. * user so that can be more accurate than what we estimated.
  2801. */
  2802. expected_bw_per_ms = switchover_bw / 1000;
  2803. } else {
  2804. /* If the user doesn't specify bandwidth, we use the estimated */
  2805. expected_bw_per_ms = bandwidth;
  2806. }
  2807. s->threshold_size = expected_bw_per_ms * migrate_downtime_limit();
  2808. s->mbps = (((double) transferred * 8.0) /
  2809. ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
  2810. transferred_pages = ram_get_total_transferred_pages() -
  2811. s->iteration_initial_pages;
  2812. s->pages_per_second = (double) transferred_pages /
  2813. (((double) time_spent / 1000.0));
  2814. /*
  2815. * if we haven't sent anything, we don't want to
  2816. * recalculate. 10000 is a small enough number for our purposes
  2817. */
  2818. if (stat64_get(&mig_stats.dirty_pages_rate) &&
  2819. transferred > 10000) {
  2820. s->expected_downtime =
  2821. stat64_get(&mig_stats.dirty_bytes_last_sync) / expected_bw_per_ms;
  2822. }
  2823. migration_rate_reset();
  2824. update_iteration_initial_status(s);
  2825. trace_migrate_transferred(transferred, time_spent,
  2826. /* Both in unit bytes/ms */
  2827. bandwidth, switchover_bw / 1000,
  2828. s->threshold_size);
  2829. }
  2830. static bool migration_can_switchover(MigrationState *s)
  2831. {
  2832. if (!migrate_switchover_ack()) {
  2833. return true;
  2834. }
  2835. /* No reason to wait for switchover ACK if VM is stopped */
  2836. if (!runstate_is_running()) {
  2837. return true;
  2838. }
  2839. return s->switchover_acked;
  2840. }
  2841. /* Migration thread iteration status */
  2842. typedef enum {
  2843. MIG_ITERATE_RESUME, /* Resume current iteration */
  2844. MIG_ITERATE_SKIP, /* Skip current iteration */
  2845. MIG_ITERATE_BREAK, /* Break the loop */
  2846. } MigIterateState;
  2847. /*
  2848. * Return true if continue to the next iteration directly, false
  2849. * otherwise.
  2850. */
  2851. static MigIterateState migration_iteration_run(MigrationState *s)
  2852. {
  2853. uint64_t must_precopy, can_postcopy, pending_size;
  2854. Error *local_err = NULL;
  2855. bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
  2856. bool can_switchover = migration_can_switchover(s);
  2857. qemu_savevm_state_pending_estimate(&must_precopy, &can_postcopy);
  2858. pending_size = must_precopy + can_postcopy;
  2859. trace_migrate_pending_estimate(pending_size, must_precopy, can_postcopy);
  2860. if (pending_size < s->threshold_size) {
  2861. qemu_savevm_state_pending_exact(&must_precopy, &can_postcopy);
  2862. pending_size = must_precopy + can_postcopy;
  2863. trace_migrate_pending_exact(pending_size, must_precopy, can_postcopy);
  2864. }
  2865. if ((!pending_size || pending_size < s->threshold_size) && can_switchover) {
  2866. trace_migration_thread_low_pending(pending_size);
  2867. migration_completion(s);
  2868. return MIG_ITERATE_BREAK;
  2869. }
  2870. /* Still a significant amount to transfer */
  2871. if (!in_postcopy && must_precopy <= s->threshold_size && can_switchover &&
  2872. qatomic_read(&s->start_postcopy)) {
  2873. if (postcopy_start(s, &local_err)) {
  2874. migrate_set_error(s, local_err);
  2875. error_report_err(local_err);
  2876. }
  2877. return MIG_ITERATE_SKIP;
  2878. }
  2879. /* Just another iteration step */
  2880. qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
  2881. return MIG_ITERATE_RESUME;
  2882. }
  2883. static void migration_iteration_finish(MigrationState *s)
  2884. {
  2885. bql_lock();
  2886. /*
  2887. * If we enabled cpu throttling for auto-converge, turn it off.
  2888. * Stopping CPU throttle should be serialized by BQL to avoid
  2889. * racing for the throttle_dirty_sync_timer.
  2890. */
  2891. if (migrate_auto_converge()) {
  2892. cpu_throttle_stop();
  2893. }
  2894. switch (s->state) {
  2895. case MIGRATION_STATUS_COMPLETED:
  2896. runstate_set(RUN_STATE_POSTMIGRATE);
  2897. break;
  2898. case MIGRATION_STATUS_COLO:
  2899. assert(migrate_colo());
  2900. migrate_start_colo_process(s);
  2901. s->vm_old_state = RUN_STATE_RUNNING;
  2902. /* Fallthrough */
  2903. case MIGRATION_STATUS_FAILED:
  2904. case MIGRATION_STATUS_CANCELLED:
  2905. case MIGRATION_STATUS_CANCELLING:
  2906. /*
  2907. * Re-activate the block drives if they're inactivated. Note, COLO
  2908. * shouldn't use block_active at all, so it should be no-op there.
  2909. */
  2910. migration_block_activate(NULL);
  2911. if (runstate_is_live(s->vm_old_state)) {
  2912. if (!runstate_check(RUN_STATE_SHUTDOWN)) {
  2913. vm_start();
  2914. }
  2915. } else {
  2916. if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
  2917. runstate_set(s->vm_old_state);
  2918. }
  2919. }
  2920. break;
  2921. default:
  2922. /* Should not reach here, but if so, forgive the VM. */
  2923. error_report("%s: Unknown ending state %d", __func__, s->state);
  2924. break;
  2925. }
  2926. migration_bh_schedule(migrate_fd_cleanup_bh, s);
  2927. bql_unlock();
  2928. }
  2929. static void bg_migration_iteration_finish(MigrationState *s)
  2930. {
  2931. /*
  2932. * Stop tracking RAM writes - un-protect memory, un-register UFFD
  2933. * memory ranges, flush kernel wait queues and wake up threads
  2934. * waiting for write fault to be resolved.
  2935. */
  2936. ram_write_tracking_stop();
  2937. bql_lock();
  2938. switch (s->state) {
  2939. case MIGRATION_STATUS_COMPLETED:
  2940. case MIGRATION_STATUS_ACTIVE:
  2941. case MIGRATION_STATUS_FAILED:
  2942. case MIGRATION_STATUS_CANCELLED:
  2943. case MIGRATION_STATUS_CANCELLING:
  2944. break;
  2945. default:
  2946. /* Should not reach here, but if so, forgive the VM. */
  2947. error_report("%s: Unknown ending state %d", __func__, s->state);
  2948. break;
  2949. }
  2950. migration_bh_schedule(migrate_fd_cleanup_bh, s);
  2951. bql_unlock();
  2952. }
  2953. /*
  2954. * Return true if continue to the next iteration directly, false
  2955. * otherwise.
  2956. */
  2957. static MigIterateState bg_migration_iteration_run(MigrationState *s)
  2958. {
  2959. int res;
  2960. res = qemu_savevm_state_iterate(s->to_dst_file, false);
  2961. if (res > 0) {
  2962. bg_migration_completion(s);
  2963. return MIG_ITERATE_BREAK;
  2964. }
  2965. return MIG_ITERATE_RESUME;
  2966. }
  2967. void migration_make_urgent_request(void)
  2968. {
  2969. qemu_sem_post(&migrate_get_current()->rate_limit_sem);
  2970. }
  2971. void migration_consume_urgent_request(void)
  2972. {
  2973. qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
  2974. }
  2975. /* Returns true if the rate limiting was broken by an urgent request */
  2976. bool migration_rate_limit(void)
  2977. {
  2978. int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
  2979. MigrationState *s = migrate_get_current();
  2980. bool urgent = false;
  2981. migration_update_counters(s, now);
  2982. if (migration_rate_exceeded(s->to_dst_file)) {
  2983. if (qemu_file_get_error(s->to_dst_file)) {
  2984. return false;
  2985. }
  2986. /*
  2987. * Wait for a delay to do rate limiting OR
  2988. * something urgent to post the semaphore.
  2989. */
  2990. int ms = s->iteration_start_time + BUFFER_DELAY - now;
  2991. trace_migration_rate_limit_pre(ms);
  2992. if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
  2993. /*
  2994. * We were woken by one or more urgent things but
  2995. * the timedwait will have consumed one of them.
  2996. * The service routine for the urgent wake will dec
  2997. * the semaphore itself for each item it consumes,
  2998. * so add this one we just eat back.
  2999. */
  3000. qemu_sem_post(&s->rate_limit_sem);
  3001. urgent = true;
  3002. }
  3003. trace_migration_rate_limit_post(urgent);
  3004. }
  3005. return urgent;
  3006. }
  3007. /*
  3008. * if failover devices are present, wait they are completely
  3009. * unplugged
  3010. */
  3011. static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
  3012. int new_state)
  3013. {
  3014. if (qemu_savevm_state_guest_unplug_pending()) {
  3015. migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
  3016. while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
  3017. qemu_savevm_state_guest_unplug_pending()) {
  3018. qemu_sem_timedwait(&s->wait_unplug_sem, 250);
  3019. }
  3020. if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
  3021. int timeout = 120; /* 30 seconds */
  3022. /*
  3023. * migration has been canceled
  3024. * but as we have started an unplug we must wait the end
  3025. * to be able to plug back the card
  3026. */
  3027. while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
  3028. qemu_sem_timedwait(&s->wait_unplug_sem, 250);
  3029. }
  3030. if (qemu_savevm_state_guest_unplug_pending() &&
  3031. !qtest_enabled()) {
  3032. warn_report("migration: partially unplugged device on "
  3033. "failure");
  3034. }
  3035. }
  3036. migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
  3037. } else {
  3038. migrate_set_state(&s->state, old_state, new_state);
  3039. }
  3040. }
  3041. /*
  3042. * Master migration thread on the source VM.
  3043. * It drives the migration and pumps the data down the outgoing channel.
  3044. */
  3045. static void *migration_thread(void *opaque)
  3046. {
  3047. MigrationState *s = opaque;
  3048. MigrationThread *thread = NULL;
  3049. int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
  3050. MigThrError thr_error;
  3051. bool urgent = false;
  3052. Error *local_err = NULL;
  3053. int ret;
  3054. thread = migration_threads_add(MIGRATION_THREAD_SRC_MAIN,
  3055. qemu_get_thread_id());
  3056. rcu_register_thread();
  3057. update_iteration_initial_status(s);
  3058. if (!multifd_send_setup()) {
  3059. goto out;
  3060. }
  3061. bql_lock();
  3062. qemu_savevm_state_header(s->to_dst_file);
  3063. bql_unlock();
  3064. /*
  3065. * If we opened the return path, we need to make sure dst has it
  3066. * opened as well.
  3067. */
  3068. if (s->rp_state.rp_thread_created) {
  3069. /* Now tell the dest that it should open its end so it can reply */
  3070. qemu_savevm_send_open_return_path(s->to_dst_file);
  3071. /* And do a ping that will make stuff easier to debug */
  3072. qemu_savevm_send_ping(s->to_dst_file, 1);
  3073. }
  3074. if (migrate_postcopy()) {
  3075. /*
  3076. * Tell the destination that we *might* want to do postcopy later;
  3077. * if the other end can't do postcopy it should fail now, nice and
  3078. * early.
  3079. */
  3080. qemu_savevm_send_postcopy_advise(s->to_dst_file);
  3081. }
  3082. if (migrate_colo()) {
  3083. /* Notify migration destination that we enable COLO */
  3084. qemu_savevm_send_colo_enable(s->to_dst_file);
  3085. }
  3086. if (migrate_auto_converge()) {
  3087. /* Start RAMBlock dirty bitmap sync timer */
  3088. cpu_throttle_dirty_sync_timer(true);
  3089. }
  3090. bql_lock();
  3091. ret = qemu_savevm_state_setup(s->to_dst_file, &local_err);
  3092. bql_unlock();
  3093. qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
  3094. MIGRATION_STATUS_ACTIVE);
  3095. /*
  3096. * Handle SETUP failures after waiting for virtio-net-failover
  3097. * devices to unplug. This to preserve migration state transitions.
  3098. */
  3099. if (ret) {
  3100. migrate_set_error(s, local_err);
  3101. error_free(local_err);
  3102. migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
  3103. MIGRATION_STATUS_FAILED);
  3104. goto out;
  3105. }
  3106. s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
  3107. trace_migration_thread_setup_complete();
  3108. while (migration_is_active()) {
  3109. if (urgent || !migration_rate_exceeded(s->to_dst_file)) {
  3110. MigIterateState iter_state = migration_iteration_run(s);
  3111. if (iter_state == MIG_ITERATE_SKIP) {
  3112. continue;
  3113. } else if (iter_state == MIG_ITERATE_BREAK) {
  3114. break;
  3115. }
  3116. }
  3117. /*
  3118. * Try to detect any kind of failures, and see whether we
  3119. * should stop the migration now.
  3120. */
  3121. thr_error = migration_detect_error(s);
  3122. if (thr_error == MIG_THR_ERR_FATAL) {
  3123. /* Stop migration */
  3124. break;
  3125. } else if (thr_error == MIG_THR_ERR_RECOVERED) {
  3126. /*
  3127. * Just recovered from a e.g. network failure, reset all
  3128. * the local variables. This is important to avoid
  3129. * breaking transferred_bytes and bandwidth calculation
  3130. */
  3131. update_iteration_initial_status(s);
  3132. }
  3133. urgent = migration_rate_limit();
  3134. }
  3135. out:
  3136. trace_migration_thread_after_loop();
  3137. migration_iteration_finish(s);
  3138. object_unref(OBJECT(s));
  3139. rcu_unregister_thread();
  3140. migration_threads_remove(thread);
  3141. return NULL;
  3142. }
  3143. static void bg_migration_vm_start_bh(void *opaque)
  3144. {
  3145. MigrationState *s = opaque;
  3146. vm_resume(s->vm_old_state);
  3147. migration_downtime_end(s);
  3148. }
  3149. /**
  3150. * Background snapshot thread, based on live migration code.
  3151. * This is an alternative implementation of live migration mechanism
  3152. * introduced specifically to support background snapshots.
  3153. *
  3154. * It takes advantage of userfault_fd write protection mechanism introduced
  3155. * in v5.7 kernel. Compared to existing dirty page logging migration much
  3156. * lesser stream traffic is produced resulting in smaller snapshot images,
  3157. * simply cause of no page duplicates can get into the stream.
  3158. *
  3159. * Another key point is that generated vmstate stream reflects machine state
  3160. * 'frozen' at the beginning of snapshot creation compared to dirty page logging
  3161. * mechanism, which effectively results in that saved snapshot is the state of VM
  3162. * at the end of the process.
  3163. */
  3164. static void *bg_migration_thread(void *opaque)
  3165. {
  3166. MigrationState *s = opaque;
  3167. int64_t setup_start;
  3168. MigThrError thr_error;
  3169. QEMUFile *fb;
  3170. bool early_fail = true;
  3171. Error *local_err = NULL;
  3172. int ret;
  3173. rcu_register_thread();
  3174. migration_rate_set(RATE_LIMIT_DISABLED);
  3175. setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
  3176. /*
  3177. * We want to save vmstate for the moment when migration has been
  3178. * initiated but also we want to save RAM content while VM is running.
  3179. * The RAM content should appear first in the vmstate. So, we first
  3180. * stash the non-RAM part of the vmstate to the temporary buffer,
  3181. * then write RAM part of the vmstate to the migration stream
  3182. * with vCPUs running and, finally, write stashed non-RAM part of
  3183. * the vmstate from the buffer to the migration stream.
  3184. */
  3185. s->bioc = qio_channel_buffer_new(512 * 1024);
  3186. qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
  3187. fb = qemu_file_new_output(QIO_CHANNEL(s->bioc));
  3188. object_unref(OBJECT(s->bioc));
  3189. update_iteration_initial_status(s);
  3190. /*
  3191. * Prepare for tracking memory writes with UFFD-WP - populate
  3192. * RAM pages before protecting.
  3193. */
  3194. #ifdef __linux__
  3195. ram_write_tracking_prepare();
  3196. #endif
  3197. bql_lock();
  3198. qemu_savevm_state_header(s->to_dst_file);
  3199. ret = qemu_savevm_state_setup(s->to_dst_file, &local_err);
  3200. bql_unlock();
  3201. qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
  3202. MIGRATION_STATUS_ACTIVE);
  3203. /*
  3204. * Handle SETUP failures after waiting for virtio-net-failover
  3205. * devices to unplug. This to preserve migration state transitions.
  3206. */
  3207. if (ret) {
  3208. migrate_set_error(s, local_err);
  3209. error_free(local_err);
  3210. migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
  3211. MIGRATION_STATUS_FAILED);
  3212. goto fail_setup;
  3213. }
  3214. s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
  3215. trace_migration_thread_setup_complete();
  3216. bql_lock();
  3217. if (migration_stop_vm(s, RUN_STATE_PAUSED)) {
  3218. goto fail;
  3219. }
  3220. if (qemu_savevm_state_complete_precopy_non_iterable(fb, false)) {
  3221. goto fail;
  3222. }
  3223. /*
  3224. * Since we are going to get non-iterable state data directly
  3225. * from s->bioc->data, explicit flush is needed here.
  3226. */
  3227. qemu_fflush(fb);
  3228. /* Now initialize UFFD context and start tracking RAM writes */
  3229. if (ram_write_tracking_start()) {
  3230. goto fail;
  3231. }
  3232. early_fail = false;
  3233. /*
  3234. * Start VM from BH handler to avoid write-fault lock here.
  3235. * UFFD-WP protection for the whole RAM is already enabled so
  3236. * calling VM state change notifiers from vm_start() would initiate
  3237. * writes to virtio VQs memory which is in write-protected region.
  3238. */
  3239. migration_bh_schedule(bg_migration_vm_start_bh, s);
  3240. bql_unlock();
  3241. while (migration_is_active()) {
  3242. MigIterateState iter_state = bg_migration_iteration_run(s);
  3243. if (iter_state == MIG_ITERATE_SKIP) {
  3244. continue;
  3245. } else if (iter_state == MIG_ITERATE_BREAK) {
  3246. break;
  3247. }
  3248. /*
  3249. * Try to detect any kind of failures, and see whether we
  3250. * should stop the migration now.
  3251. */
  3252. thr_error = migration_detect_error(s);
  3253. if (thr_error == MIG_THR_ERR_FATAL) {
  3254. /* Stop migration */
  3255. break;
  3256. }
  3257. migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
  3258. }
  3259. trace_migration_thread_after_loop();
  3260. fail:
  3261. if (early_fail) {
  3262. migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
  3263. MIGRATION_STATUS_FAILED);
  3264. bql_unlock();
  3265. }
  3266. fail_setup:
  3267. bg_migration_iteration_finish(s);
  3268. qemu_fclose(fb);
  3269. object_unref(OBJECT(s));
  3270. rcu_unregister_thread();
  3271. return NULL;
  3272. }
  3273. void migrate_fd_connect(MigrationState *s, Error *error_in)
  3274. {
  3275. Error *local_err = NULL;
  3276. uint64_t rate_limit;
  3277. bool resume = (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP);
  3278. int ret;
  3279. /*
  3280. * If there's a previous error, free it and prepare for another one.
  3281. * Meanwhile if migration completes successfully, there won't have an error
  3282. * dumped when calling migrate_fd_cleanup().
  3283. */
  3284. migrate_error_free(s);
  3285. s->expected_downtime = migrate_downtime_limit();
  3286. if (error_in) {
  3287. migrate_fd_error(s, error_in);
  3288. if (resume) {
  3289. /*
  3290. * Don't do cleanup for resume if channel is invalid, but only dump
  3291. * the error. We wait for another channel connect from the user.
  3292. * The error_report still gives HMP user a hint on what failed.
  3293. * It's normally done in migrate_fd_cleanup(), but call it here
  3294. * explicitly.
  3295. */
  3296. error_report_err(error_copy(s->error));
  3297. } else {
  3298. migrate_fd_cleanup(s);
  3299. }
  3300. return;
  3301. }
  3302. if (resume) {
  3303. /* This is a resumed migration */
  3304. rate_limit = migrate_max_postcopy_bandwidth();
  3305. } else {
  3306. /* This is a fresh new migration */
  3307. rate_limit = migrate_max_bandwidth();
  3308. /* Notify before starting migration thread */
  3309. if (migration_call_notifiers(s, MIG_EVENT_PRECOPY_SETUP, &local_err)) {
  3310. goto fail;
  3311. }
  3312. }
  3313. migration_rate_set(rate_limit);
  3314. qemu_file_set_blocking(s->to_dst_file, true);
  3315. /*
  3316. * Open the return path. For postcopy, it is used exclusively. For
  3317. * precopy, only if user specified "return-path" capability would
  3318. * QEMU uses the return path.
  3319. */
  3320. if (migrate_postcopy_ram() || migrate_return_path()) {
  3321. if (open_return_path_on_source(s)) {
  3322. error_setg(&local_err, "Unable to open return-path for postcopy");
  3323. goto fail;
  3324. }
  3325. }
  3326. /*
  3327. * This needs to be done before resuming a postcopy. Note: for newer
  3328. * QEMUs we will delay the channel creation until postcopy_start(), to
  3329. * avoid disorder of channel creations.
  3330. */
  3331. if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
  3332. postcopy_preempt_setup(s);
  3333. }
  3334. if (resume) {
  3335. /* Wakeup the main migration thread to do the recovery */
  3336. migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP,
  3337. MIGRATION_STATUS_POSTCOPY_RECOVER);
  3338. qemu_sem_post(&s->postcopy_pause_sem);
  3339. return;
  3340. }
  3341. if (migrate_mode_is_cpr(s)) {
  3342. ret = migration_stop_vm(s, RUN_STATE_FINISH_MIGRATE);
  3343. if (ret < 0) {
  3344. error_setg(&local_err, "migration_stop_vm failed, error %d", -ret);
  3345. goto fail;
  3346. }
  3347. }
  3348. /*
  3349. * Take a refcount to make sure the migration object won't get freed by
  3350. * the main thread already in migration_shutdown().
  3351. *
  3352. * The refcount will be released at the end of the thread function.
  3353. */
  3354. object_ref(OBJECT(s));
  3355. if (migrate_background_snapshot()) {
  3356. qemu_thread_create(&s->thread, MIGRATION_THREAD_SNAPSHOT,
  3357. bg_migration_thread, s, QEMU_THREAD_JOINABLE);
  3358. } else {
  3359. qemu_thread_create(&s->thread, MIGRATION_THREAD_SRC_MAIN,
  3360. migration_thread, s, QEMU_THREAD_JOINABLE);
  3361. }
  3362. s->migration_thread_running = true;
  3363. return;
  3364. fail:
  3365. migrate_set_error(s, local_err);
  3366. migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
  3367. error_report_err(local_err);
  3368. migrate_fd_cleanup(s);
  3369. }
  3370. static void migration_class_init(ObjectClass *klass, void *data)
  3371. {
  3372. DeviceClass *dc = DEVICE_CLASS(klass);
  3373. dc->user_creatable = false;
  3374. device_class_set_props_n(dc, migration_properties,
  3375. migration_properties_count);
  3376. }
  3377. static void migration_instance_finalize(Object *obj)
  3378. {
  3379. MigrationState *ms = MIGRATION_OBJ(obj);
  3380. qemu_mutex_destroy(&ms->error_mutex);
  3381. qemu_mutex_destroy(&ms->qemu_file_lock);
  3382. qemu_sem_destroy(&ms->wait_unplug_sem);
  3383. qemu_sem_destroy(&ms->rate_limit_sem);
  3384. qemu_sem_destroy(&ms->pause_sem);
  3385. qemu_sem_destroy(&ms->postcopy_pause_sem);
  3386. qemu_sem_destroy(&ms->rp_state.rp_sem);
  3387. qemu_sem_destroy(&ms->rp_state.rp_pong_acks);
  3388. qemu_sem_destroy(&ms->postcopy_qemufile_src_sem);
  3389. error_free(ms->error);
  3390. }
  3391. static void migration_instance_init(Object *obj)
  3392. {
  3393. MigrationState *ms = MIGRATION_OBJ(obj);
  3394. ms->state = MIGRATION_STATUS_NONE;
  3395. ms->mbps = -1;
  3396. ms->pages_per_second = -1;
  3397. qemu_sem_init(&ms->pause_sem, 0);
  3398. qemu_mutex_init(&ms->error_mutex);
  3399. migrate_params_init(&ms->parameters);
  3400. qemu_sem_init(&ms->postcopy_pause_sem, 0);
  3401. qemu_sem_init(&ms->rp_state.rp_sem, 0);
  3402. qemu_sem_init(&ms->rp_state.rp_pong_acks, 0);
  3403. qemu_sem_init(&ms->rate_limit_sem, 0);
  3404. qemu_sem_init(&ms->wait_unplug_sem, 0);
  3405. qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0);
  3406. qemu_mutex_init(&ms->qemu_file_lock);
  3407. }
  3408. /*
  3409. * Return true if check pass, false otherwise. Error will be put
  3410. * inside errp if provided.
  3411. */
  3412. static bool migration_object_check(MigrationState *ms, Error **errp)
  3413. {
  3414. /* Assuming all off */
  3415. bool old_caps[MIGRATION_CAPABILITY__MAX] = { 0 };
  3416. if (!migrate_params_check(&ms->parameters, errp)) {
  3417. return false;
  3418. }
  3419. return migrate_caps_check(old_caps, ms->capabilities, errp);
  3420. }
  3421. static const TypeInfo migration_type = {
  3422. .name = TYPE_MIGRATION,
  3423. /*
  3424. * NOTE: TYPE_MIGRATION is not really a device, as the object is
  3425. * not created using qdev_new(), it is not attached to the qdev
  3426. * device tree, and it is never realized.
  3427. *
  3428. * TODO: Make this TYPE_OBJECT once QOM provides something like
  3429. * TYPE_DEVICE's "-global" properties.
  3430. */
  3431. .parent = TYPE_DEVICE,
  3432. .class_init = migration_class_init,
  3433. .class_size = sizeof(MigrationClass),
  3434. .instance_size = sizeof(MigrationState),
  3435. .instance_init = migration_instance_init,
  3436. .instance_finalize = migration_instance_finalize,
  3437. };
  3438. static void register_migration_types(void)
  3439. {
  3440. type_register_static(&migration_type);
  3441. }
  3442. type_init(register_migration_types);