migration.c 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050
  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. /*
  1621. * Newly setup incoming QEMU. Mark the block active state to reflect
  1622. * that the src currently owns the disks.
  1623. */
  1624. migration_block_active_setup(false);
  1625. once = false;
  1626. }
  1627. void qmp_migrate_recover(const char *uri, Error **errp)
  1628. {
  1629. MigrationIncomingState *mis = migration_incoming_get_current();
  1630. /*
  1631. * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
  1632. * callers (no one should ignore a recover failure); if there is, it's a
  1633. * programming error.
  1634. */
  1635. assert(errp);
  1636. if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
  1637. error_setg(errp, "Migrate recover can only be run "
  1638. "when postcopy is paused.");
  1639. return;
  1640. }
  1641. /* If there's an existing transport, release it */
  1642. migration_incoming_transport_cleanup(mis);
  1643. /*
  1644. * Note that this call will never start a real migration; it will
  1645. * only re-setup the migration stream and poke existing migration
  1646. * to continue using that newly established channel.
  1647. */
  1648. qemu_start_incoming_migration(uri, false, NULL, errp);
  1649. }
  1650. void qmp_migrate_pause(Error **errp)
  1651. {
  1652. MigrationState *ms = migrate_get_current();
  1653. MigrationIncomingState *mis = migration_incoming_get_current();
  1654. int ret = 0;
  1655. if (migration_postcopy_is_alive(ms->state)) {
  1656. /* Source side, during postcopy */
  1657. Error *error = NULL;
  1658. /* Tell the core migration that we're pausing */
  1659. error_setg(&error, "Postcopy migration is paused by the user");
  1660. migrate_set_error(ms, error);
  1661. error_free(error);
  1662. qemu_mutex_lock(&ms->qemu_file_lock);
  1663. if (ms->to_dst_file) {
  1664. ret = qemu_file_shutdown(ms->to_dst_file);
  1665. }
  1666. qemu_mutex_unlock(&ms->qemu_file_lock);
  1667. if (ret) {
  1668. error_setg(errp, "Failed to pause source migration");
  1669. }
  1670. /*
  1671. * Kick the migration thread out of any waiting windows (on behalf
  1672. * of the rp thread).
  1673. */
  1674. migration_rp_kick(ms);
  1675. return;
  1676. }
  1677. if (migration_postcopy_is_alive(mis->state)) {
  1678. ret = qemu_file_shutdown(mis->from_src_file);
  1679. if (ret) {
  1680. error_setg(errp, "Failed to pause destination migration");
  1681. }
  1682. return;
  1683. }
  1684. error_setg(errp, "migrate-pause is currently only supported "
  1685. "during postcopy-active or postcopy-recover state");
  1686. }
  1687. bool migration_is_blocked(Error **errp)
  1688. {
  1689. GSList *blockers = migration_blockers[migrate_mode()];
  1690. if (qemu_savevm_state_blocked(errp)) {
  1691. return true;
  1692. }
  1693. if (blockers) {
  1694. error_propagate(errp, error_copy(blockers->data));
  1695. return true;
  1696. }
  1697. return false;
  1698. }
  1699. /* Returns true if continue to migrate, or false if error detected */
  1700. static bool migrate_prepare(MigrationState *s, bool resume, Error **errp)
  1701. {
  1702. if (resume) {
  1703. if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
  1704. error_setg(errp, "Cannot resume if there is no "
  1705. "paused migration");
  1706. return false;
  1707. }
  1708. /*
  1709. * Postcopy recovery won't work well with release-ram
  1710. * capability since release-ram will drop the page buffer as
  1711. * long as the page is put into the send buffer. So if there
  1712. * is a network failure happened, any page buffers that have
  1713. * not yet reached the destination VM but have already been
  1714. * sent from the source VM will be lost forever. Let's refuse
  1715. * the client from resuming such a postcopy migration.
  1716. * Luckily release-ram was designed to only be used when src
  1717. * and destination VMs are on the same host, so it should be
  1718. * fine.
  1719. */
  1720. if (migrate_release_ram()) {
  1721. error_setg(errp, "Postcopy recovery cannot work "
  1722. "when release-ram capability is set");
  1723. return false;
  1724. }
  1725. migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
  1726. MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP);
  1727. /* This is a resume, skip init status */
  1728. return true;
  1729. }
  1730. if (migration_is_running()) {
  1731. error_setg(errp, "There's a migration process in progress");
  1732. return false;
  1733. }
  1734. if (runstate_check(RUN_STATE_INMIGRATE)) {
  1735. error_setg(errp, "Guest is waiting for an incoming migration");
  1736. return false;
  1737. }
  1738. if (runstate_check(RUN_STATE_POSTMIGRATE)) {
  1739. error_setg(errp, "Can't migrate the vm that was paused due to "
  1740. "previous migration");
  1741. return false;
  1742. }
  1743. if (kvm_hwpoisoned_mem()) {
  1744. error_setg(errp, "Can't migrate this vm with hardware poisoned memory, "
  1745. "please reboot the vm and try again");
  1746. return false;
  1747. }
  1748. if (migration_is_blocked(errp)) {
  1749. return false;
  1750. }
  1751. if (migrate_mapped_ram()) {
  1752. if (migrate_tls()) {
  1753. error_setg(errp, "Cannot use TLS with mapped-ram");
  1754. return false;
  1755. }
  1756. if (migrate_multifd_compression()) {
  1757. error_setg(errp, "Cannot use compression with mapped-ram");
  1758. return false;
  1759. }
  1760. }
  1761. if (migrate_mode_is_cpr(s)) {
  1762. const char *conflict = NULL;
  1763. if (migrate_postcopy()) {
  1764. conflict = "postcopy";
  1765. } else if (migrate_background_snapshot()) {
  1766. conflict = "background snapshot";
  1767. } else if (migrate_colo()) {
  1768. conflict = "COLO";
  1769. }
  1770. if (conflict) {
  1771. error_setg(errp, "Cannot use %s with CPR", conflict);
  1772. return false;
  1773. }
  1774. }
  1775. if (migrate_init(s, errp)) {
  1776. return false;
  1777. }
  1778. return true;
  1779. }
  1780. static void qmp_migrate_finish(MigrationAddress *addr, bool resume_requested,
  1781. Error **errp);
  1782. static void migrate_hup_add(MigrationState *s, QIOChannel *ioc, GSourceFunc cb,
  1783. void *opaque)
  1784. {
  1785. s->hup_source = qio_channel_create_watch(ioc, G_IO_HUP);
  1786. g_source_set_callback(s->hup_source, cb, opaque, NULL);
  1787. g_source_attach(s->hup_source, NULL);
  1788. }
  1789. static void migrate_hup_delete(MigrationState *s)
  1790. {
  1791. if (s->hup_source) {
  1792. g_source_destroy(s->hup_source);
  1793. g_source_unref(s->hup_source);
  1794. s->hup_source = NULL;
  1795. }
  1796. }
  1797. static gboolean qmp_migrate_finish_cb(QIOChannel *channel,
  1798. GIOCondition cond,
  1799. void *opaque)
  1800. {
  1801. MigrationAddress *addr = opaque;
  1802. qmp_migrate_finish(addr, false, NULL);
  1803. cpr_state_close();
  1804. migrate_hup_delete(migrate_get_current());
  1805. qapi_free_MigrationAddress(addr);
  1806. return G_SOURCE_REMOVE;
  1807. }
  1808. void qmp_migrate(const char *uri, bool has_channels,
  1809. MigrationChannelList *channels, bool has_detach, bool detach,
  1810. bool has_resume, bool resume, Error **errp)
  1811. {
  1812. bool resume_requested;
  1813. Error *local_err = NULL;
  1814. MigrationState *s = migrate_get_current();
  1815. g_autoptr(MigrationChannel) channel = NULL;
  1816. MigrationAddress *addr = NULL;
  1817. MigrationChannel *channelv[MIGRATION_CHANNEL_TYPE__MAX] = { NULL };
  1818. MigrationChannel *cpr_channel = NULL;
  1819. /*
  1820. * Having preliminary checks for uri and channel
  1821. */
  1822. if (!uri == !channels) {
  1823. error_setg(errp, "need either 'uri' or 'channels' argument");
  1824. return;
  1825. }
  1826. if (channels) {
  1827. for ( ; channels; channels = channels->next) {
  1828. MigrationChannelType type = channels->value->channel_type;
  1829. if (channelv[type]) {
  1830. error_setg(errp, "Channel list has more than one %s entry",
  1831. MigrationChannelType_str(type));
  1832. return;
  1833. }
  1834. channelv[type] = channels->value;
  1835. }
  1836. cpr_channel = channelv[MIGRATION_CHANNEL_TYPE_CPR];
  1837. addr = channelv[MIGRATION_CHANNEL_TYPE_MAIN]->addr;
  1838. if (!addr) {
  1839. error_setg(errp, "Channel list has no main entry");
  1840. return;
  1841. }
  1842. }
  1843. if (uri) {
  1844. /* caller uses the old URI syntax */
  1845. if (!migrate_uri_parse(uri, &channel, errp)) {
  1846. return;
  1847. }
  1848. addr = channel->addr;
  1849. }
  1850. /* transport mechanism not suitable for migration? */
  1851. if (!migration_channels_and_transport_compatible(addr, errp)) {
  1852. return;
  1853. }
  1854. if (s->parameters.mode == MIG_MODE_CPR_TRANSFER && !cpr_channel) {
  1855. error_setg(errp, "missing 'cpr' migration channel");
  1856. return;
  1857. }
  1858. resume_requested = has_resume && resume;
  1859. if (!migrate_prepare(s, resume_requested, errp)) {
  1860. /* Error detected, put into errp */
  1861. return;
  1862. }
  1863. if (cpr_state_save(cpr_channel, &local_err)) {
  1864. goto out;
  1865. }
  1866. /*
  1867. * For cpr-transfer, the target may not be listening yet on the migration
  1868. * channel, because first it must finish cpr_load_state. The target tells
  1869. * us it is listening by closing the cpr-state socket. Wait for that HUP
  1870. * event before connecting in qmp_migrate_finish.
  1871. *
  1872. * The HUP could occur because the target fails while reading CPR state,
  1873. * in which case the target will not listen for the incoming migration
  1874. * connection, so qmp_migrate_finish will fail to connect, and then recover.
  1875. */
  1876. if (s->parameters.mode == MIG_MODE_CPR_TRANSFER) {
  1877. migrate_hup_add(s, cpr_state_ioc(), (GSourceFunc)qmp_migrate_finish_cb,
  1878. QAPI_CLONE(MigrationAddress, addr));
  1879. } else {
  1880. qmp_migrate_finish(addr, resume_requested, errp);
  1881. }
  1882. out:
  1883. if (local_err) {
  1884. migrate_fd_error(s, local_err);
  1885. error_propagate(errp, local_err);
  1886. }
  1887. }
  1888. static void qmp_migrate_finish(MigrationAddress *addr, bool resume_requested,
  1889. Error **errp)
  1890. {
  1891. MigrationState *s = migrate_get_current();
  1892. Error *local_err = NULL;
  1893. if (!resume_requested) {
  1894. if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
  1895. return;
  1896. }
  1897. }
  1898. if (addr->transport == MIGRATION_ADDRESS_TYPE_SOCKET) {
  1899. SocketAddress *saddr = &addr->u.socket;
  1900. if (saddr->type == SOCKET_ADDRESS_TYPE_INET ||
  1901. saddr->type == SOCKET_ADDRESS_TYPE_UNIX ||
  1902. saddr->type == SOCKET_ADDRESS_TYPE_VSOCK) {
  1903. socket_start_outgoing_migration(s, saddr, &local_err);
  1904. } else if (saddr->type == SOCKET_ADDRESS_TYPE_FD) {
  1905. fd_start_outgoing_migration(s, saddr->u.fd.str, &local_err);
  1906. }
  1907. #ifdef CONFIG_RDMA
  1908. } else if (addr->transport == MIGRATION_ADDRESS_TYPE_RDMA) {
  1909. rdma_start_outgoing_migration(s, &addr->u.rdma, &local_err);
  1910. #endif
  1911. } else if (addr->transport == MIGRATION_ADDRESS_TYPE_EXEC) {
  1912. exec_start_outgoing_migration(s, addr->u.exec.args, &local_err);
  1913. } else if (addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
  1914. file_start_outgoing_migration(s, &addr->u.file, &local_err);
  1915. } else {
  1916. error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "uri",
  1917. "a valid migration protocol");
  1918. migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
  1919. MIGRATION_STATUS_FAILED);
  1920. }
  1921. if (local_err) {
  1922. if (!resume_requested) {
  1923. yank_unregister_instance(MIGRATION_YANK_INSTANCE);
  1924. }
  1925. migrate_fd_error(s, local_err);
  1926. error_propagate(errp, local_err);
  1927. return;
  1928. }
  1929. }
  1930. void qmp_migrate_cancel(Error **errp)
  1931. {
  1932. migration_cancel(NULL);
  1933. }
  1934. void qmp_migrate_continue(MigrationStatus state, Error **errp)
  1935. {
  1936. MigrationState *s = migrate_get_current();
  1937. if (s->state != state) {
  1938. error_setg(errp, "Migration not in expected state: %s",
  1939. MigrationStatus_str(s->state));
  1940. return;
  1941. }
  1942. qemu_sem_post(&s->pause_sem);
  1943. }
  1944. int migration_rp_wait(MigrationState *s)
  1945. {
  1946. /* If migration has failure already, ignore the wait */
  1947. if (migrate_has_error(s)) {
  1948. return -1;
  1949. }
  1950. qemu_sem_wait(&s->rp_state.rp_sem);
  1951. /* After wait, double check that there's no failure */
  1952. if (migrate_has_error(s)) {
  1953. return -1;
  1954. }
  1955. return 0;
  1956. }
  1957. void migration_rp_kick(MigrationState *s)
  1958. {
  1959. qemu_sem_post(&s->rp_state.rp_sem);
  1960. }
  1961. static struct rp_cmd_args {
  1962. ssize_t len; /* -1 = variable */
  1963. const char *name;
  1964. } rp_cmd_args[] = {
  1965. [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
  1966. [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
  1967. [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
  1968. [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
  1969. [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
  1970. [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
  1971. [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
  1972. [MIG_RP_MSG_SWITCHOVER_ACK] = { .len = 0, .name = "SWITCHOVER_ACK" },
  1973. [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
  1974. };
  1975. /*
  1976. * Process a request for pages received on the return path,
  1977. * We're allowed to send more than requested (e.g. to round to our page size)
  1978. * and we don't need to send pages that have already been sent.
  1979. */
  1980. static void
  1981. migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
  1982. ram_addr_t start, size_t len, Error **errp)
  1983. {
  1984. long our_host_ps = qemu_real_host_page_size();
  1985. trace_migrate_handle_rp_req_pages(rbname, start, len);
  1986. /*
  1987. * Since we currently insist on matching page sizes, just sanity check
  1988. * we're being asked for whole host pages.
  1989. */
  1990. if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
  1991. !QEMU_IS_ALIGNED(len, our_host_ps)) {
  1992. error_setg(errp, "MIG_RP_MSG_REQ_PAGES: Misaligned page request, start:"
  1993. RAM_ADDR_FMT " len: %zd", start, len);
  1994. return;
  1995. }
  1996. ram_save_queue_pages(rbname, start, len, errp);
  1997. }
  1998. static bool migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name,
  1999. Error **errp)
  2000. {
  2001. RAMBlock *block = qemu_ram_block_by_name(block_name);
  2002. if (!block) {
  2003. error_setg(errp, "MIG_RP_MSG_RECV_BITMAP has invalid block name '%s'",
  2004. block_name);
  2005. return false;
  2006. }
  2007. /* Fetch the received bitmap and refresh the dirty bitmap */
  2008. return ram_dirty_bitmap_reload(s, block, errp);
  2009. }
  2010. static bool migrate_handle_rp_resume_ack(MigrationState *s,
  2011. uint32_t value, Error **errp)
  2012. {
  2013. trace_source_return_path_thread_resume_ack(value);
  2014. if (value != MIGRATION_RESUME_ACK_VALUE) {
  2015. error_setg(errp, "illegal resume_ack value %"PRIu32, value);
  2016. return false;
  2017. }
  2018. /* Now both sides are active. */
  2019. migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
  2020. MIGRATION_STATUS_POSTCOPY_ACTIVE);
  2021. /* Notify send thread that time to continue send pages */
  2022. migration_rp_kick(s);
  2023. return true;
  2024. }
  2025. /*
  2026. * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
  2027. * existed) in a safe way.
  2028. */
  2029. static void migration_release_dst_files(MigrationState *ms)
  2030. {
  2031. QEMUFile *file = NULL;
  2032. WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
  2033. /*
  2034. * Reset the from_dst_file pointer first before releasing it, as we
  2035. * can't block within lock section
  2036. */
  2037. file = ms->rp_state.from_dst_file;
  2038. ms->rp_state.from_dst_file = NULL;
  2039. }
  2040. /*
  2041. * Do the same to postcopy fast path socket too if there is. No
  2042. * locking needed because this qemufile should only be managed by
  2043. * return path thread.
  2044. */
  2045. if (ms->postcopy_qemufile_src) {
  2046. migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src);
  2047. qemu_file_shutdown(ms->postcopy_qemufile_src);
  2048. qemu_fclose(ms->postcopy_qemufile_src);
  2049. ms->postcopy_qemufile_src = NULL;
  2050. }
  2051. qemu_fclose(file);
  2052. }
  2053. /*
  2054. * Handles messages sent on the return path towards the source VM
  2055. *
  2056. */
  2057. static void *source_return_path_thread(void *opaque)
  2058. {
  2059. MigrationState *ms = opaque;
  2060. QEMUFile *rp = ms->rp_state.from_dst_file;
  2061. uint16_t header_len, header_type;
  2062. uint8_t buf[512];
  2063. uint32_t tmp32, sibling_error;
  2064. ram_addr_t start = 0; /* =0 to silence warning */
  2065. size_t len = 0, expected_len;
  2066. Error *err = NULL;
  2067. int res;
  2068. trace_source_return_path_thread_entry();
  2069. rcu_register_thread();
  2070. while (migration_is_running()) {
  2071. trace_source_return_path_thread_loop_top();
  2072. header_type = qemu_get_be16(rp);
  2073. header_len = qemu_get_be16(rp);
  2074. if (qemu_file_get_error(rp)) {
  2075. qemu_file_get_error_obj(rp, &err);
  2076. goto out;
  2077. }
  2078. if (header_type >= MIG_RP_MSG_MAX ||
  2079. header_type == MIG_RP_MSG_INVALID) {
  2080. error_setg(&err, "Received invalid message 0x%04x length 0x%04x",
  2081. header_type, header_len);
  2082. goto out;
  2083. }
  2084. if ((rp_cmd_args[header_type].len != -1 &&
  2085. header_len != rp_cmd_args[header_type].len) ||
  2086. header_len > sizeof(buf)) {
  2087. error_setg(&err, "Received '%s' message (0x%04x) with"
  2088. "incorrect length %d expecting %zu",
  2089. rp_cmd_args[header_type].name, header_type, header_len,
  2090. (size_t)rp_cmd_args[header_type].len);
  2091. goto out;
  2092. }
  2093. /* We know we've got a valid header by this point */
  2094. res = qemu_get_buffer(rp, buf, header_len);
  2095. if (res != header_len) {
  2096. error_setg(&err, "Failed reading data for message 0x%04x"
  2097. " read %d expected %d",
  2098. header_type, res, header_len);
  2099. goto out;
  2100. }
  2101. /* OK, we have the message and the data */
  2102. switch (header_type) {
  2103. case MIG_RP_MSG_SHUT:
  2104. sibling_error = ldl_be_p(buf);
  2105. trace_source_return_path_thread_shut(sibling_error);
  2106. if (sibling_error) {
  2107. error_setg(&err, "Sibling indicated error %d", sibling_error);
  2108. }
  2109. /*
  2110. * We'll let the main thread deal with closing the RP
  2111. * we could do a shutdown(2) on it, but we're the only user
  2112. * anyway, so there's nothing gained.
  2113. */
  2114. goto out;
  2115. case MIG_RP_MSG_PONG:
  2116. tmp32 = ldl_be_p(buf);
  2117. trace_source_return_path_thread_pong(tmp32);
  2118. qemu_sem_post(&ms->rp_state.rp_pong_acks);
  2119. break;
  2120. case MIG_RP_MSG_REQ_PAGES:
  2121. start = ldq_be_p(buf);
  2122. len = ldl_be_p(buf + 8);
  2123. migrate_handle_rp_req_pages(ms, NULL, start, len, &err);
  2124. if (err) {
  2125. goto out;
  2126. }
  2127. break;
  2128. case MIG_RP_MSG_REQ_PAGES_ID:
  2129. expected_len = 12 + 1; /* header + termination */
  2130. if (header_len >= expected_len) {
  2131. start = ldq_be_p(buf);
  2132. len = ldl_be_p(buf + 8);
  2133. /* Now we expect an idstr */
  2134. tmp32 = buf[12]; /* Length of the following idstr */
  2135. buf[13 + tmp32] = '\0';
  2136. expected_len += tmp32;
  2137. }
  2138. if (header_len != expected_len) {
  2139. error_setg(&err, "Req_Page_id with length %d expecting %zd",
  2140. header_len, expected_len);
  2141. goto out;
  2142. }
  2143. migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len,
  2144. &err);
  2145. if (err) {
  2146. goto out;
  2147. }
  2148. break;
  2149. case MIG_RP_MSG_RECV_BITMAP:
  2150. if (header_len < 1) {
  2151. error_setg(&err, "MIG_RP_MSG_RECV_BITMAP missing block name");
  2152. goto out;
  2153. }
  2154. /* Format: len (1B) + idstr (<255B). This ends the idstr. */
  2155. buf[buf[0] + 1] = '\0';
  2156. if (!migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1), &err)) {
  2157. goto out;
  2158. }
  2159. break;
  2160. case MIG_RP_MSG_RESUME_ACK:
  2161. tmp32 = ldl_be_p(buf);
  2162. if (!migrate_handle_rp_resume_ack(ms, tmp32, &err)) {
  2163. goto out;
  2164. }
  2165. break;
  2166. case MIG_RP_MSG_SWITCHOVER_ACK:
  2167. ms->switchover_acked = true;
  2168. trace_source_return_path_thread_switchover_acked();
  2169. break;
  2170. default:
  2171. break;
  2172. }
  2173. }
  2174. out:
  2175. if (err) {
  2176. migrate_set_error(ms, err);
  2177. error_free(err);
  2178. trace_source_return_path_thread_bad_end();
  2179. }
  2180. if (ms->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
  2181. /*
  2182. * this will be extremely unlikely: that we got yet another network
  2183. * issue during recovering of the 1st network failure.. during this
  2184. * period the main migration thread can be waiting on rp_sem for
  2185. * this thread to sync with the other side.
  2186. *
  2187. * When this happens, explicitly kick the migration thread out of
  2188. * RECOVER stage and back to PAUSED, so the admin can try
  2189. * everything again.
  2190. */
  2191. migration_rp_kick(ms);
  2192. }
  2193. trace_source_return_path_thread_end();
  2194. rcu_unregister_thread();
  2195. return NULL;
  2196. }
  2197. static int open_return_path_on_source(MigrationState *ms)
  2198. {
  2199. ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
  2200. if (!ms->rp_state.from_dst_file) {
  2201. return -1;
  2202. }
  2203. trace_open_return_path_on_source();
  2204. qemu_thread_create(&ms->rp_state.rp_thread, MIGRATION_THREAD_SRC_RETURN,
  2205. source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
  2206. ms->rp_state.rp_thread_created = true;
  2207. trace_open_return_path_on_source_continue();
  2208. return 0;
  2209. }
  2210. /* Return true if error detected, or false otherwise */
  2211. static bool close_return_path_on_source(MigrationState *ms)
  2212. {
  2213. if (!ms->rp_state.rp_thread_created) {
  2214. return false;
  2215. }
  2216. trace_migration_return_path_end_before();
  2217. /*
  2218. * If this is a normal exit then the destination will send a SHUT
  2219. * and the rp_thread will exit, however if there's an error we
  2220. * need to cause it to exit. shutdown(2), if we have it, will
  2221. * cause it to unblock if it's stuck waiting for the destination.
  2222. */
  2223. WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
  2224. if (migrate_has_error(ms) && ms->rp_state.from_dst_file) {
  2225. qemu_file_shutdown(ms->rp_state.from_dst_file);
  2226. }
  2227. }
  2228. qemu_thread_join(&ms->rp_state.rp_thread);
  2229. ms->rp_state.rp_thread_created = false;
  2230. migration_release_dst_files(ms);
  2231. trace_migration_return_path_end_after();
  2232. /* Return path will persist the error in MigrationState when quit */
  2233. return migrate_has_error(ms);
  2234. }
  2235. static inline void
  2236. migration_wait_main_channel(MigrationState *ms)
  2237. {
  2238. /* Wait until one PONG message received */
  2239. qemu_sem_wait(&ms->rp_state.rp_pong_acks);
  2240. }
  2241. /*
  2242. * Switch from normal iteration to postcopy
  2243. * Returns non-0 on error
  2244. */
  2245. static int postcopy_start(MigrationState *ms, Error **errp)
  2246. {
  2247. int ret;
  2248. QIOChannelBuffer *bioc;
  2249. QEMUFile *fb;
  2250. /*
  2251. * Now we're 100% sure to switch to postcopy, so JSON writer won't be
  2252. * useful anymore. Free the resources early if it is there. Clearing
  2253. * the vmdesc also means any follow up vmstate_save()s will start to
  2254. * skip all JSON operations, which can shrink postcopy downtime.
  2255. */
  2256. migration_cleanup_json_writer(ms);
  2257. if (migrate_postcopy_preempt()) {
  2258. migration_wait_main_channel(ms);
  2259. if (postcopy_preempt_establish_channel(ms)) {
  2260. migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED);
  2261. error_setg(errp, "%s: Failed to establish preempt channel",
  2262. __func__);
  2263. return -1;
  2264. }
  2265. }
  2266. trace_postcopy_start();
  2267. bql_lock();
  2268. trace_postcopy_start_set_run();
  2269. ret = migration_stop_vm(ms, RUN_STATE_FINISH_MIGRATE);
  2270. if (ret < 0) {
  2271. error_setg_errno(errp, -ret, "%s: Failed to stop the VM", __func__);
  2272. goto fail;
  2273. }
  2274. if (!migration_switchover_start(ms, errp)) {
  2275. goto fail;
  2276. }
  2277. /*
  2278. * Cause any non-postcopiable, but iterative devices to
  2279. * send out their final data.
  2280. */
  2281. ret = qemu_savevm_state_complete_precopy_iterable(ms->to_dst_file, true);
  2282. if (ret) {
  2283. error_setg(errp, "Postcopy save non-postcopiable iterables failed");
  2284. goto fail;
  2285. }
  2286. /*
  2287. * in Finish migrate and with the io-lock held everything should
  2288. * be quiet, but we've potentially still got dirty pages and we
  2289. * need to tell the destination to throw any pages it's already received
  2290. * that are dirty
  2291. */
  2292. if (migrate_postcopy_ram()) {
  2293. ram_postcopy_send_discard_bitmap(ms);
  2294. }
  2295. if (migrate_postcopy_ram()) {
  2296. /* Ping just for debugging, helps line traces up */
  2297. qemu_savevm_send_ping(ms->to_dst_file, 2);
  2298. }
  2299. /*
  2300. * While loading the device state we may trigger page transfer
  2301. * requests and the fd must be free to process those, and thus
  2302. * the destination must read the whole device state off the fd before
  2303. * it starts processing it. Unfortunately the ad-hoc migration format
  2304. * doesn't allow the destination to know the size to read without fully
  2305. * parsing it through each devices load-state code (especially the open
  2306. * coded devices that use get/put).
  2307. * So we wrap the device state up in a package with a length at the start;
  2308. * to do this we use a qemu_buf to hold the whole of the device state.
  2309. */
  2310. bioc = qio_channel_buffer_new(4096);
  2311. qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
  2312. fb = qemu_file_new_output(QIO_CHANNEL(bioc));
  2313. object_unref(OBJECT(bioc));
  2314. /*
  2315. * Make sure the receiver can get incoming pages before we send the rest
  2316. * of the state
  2317. */
  2318. qemu_savevm_send_postcopy_listen(fb);
  2319. ret = qemu_savevm_state_complete_precopy_non_iterable(fb, true);
  2320. if (ret) {
  2321. error_setg(errp, "Postcopy save non-iterable device states failed");
  2322. goto fail_closefb;
  2323. }
  2324. if (migrate_postcopy_ram()) {
  2325. qemu_savevm_send_ping(fb, 3);
  2326. }
  2327. qemu_savevm_send_postcopy_run(fb);
  2328. /* <><> end of stuff going into the package */
  2329. /* Last point of recovery; as soon as we send the package the destination
  2330. * can open devices and potentially start running.
  2331. * Lets just check again we've not got any errors.
  2332. */
  2333. ret = qemu_file_get_error(ms->to_dst_file);
  2334. if (ret) {
  2335. error_setg(errp, "postcopy_start: Migration stream errored (pre package)");
  2336. goto fail_closefb;
  2337. }
  2338. /* Now send that blob */
  2339. if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
  2340. error_setg(errp, "%s: Failed to send packaged data", __func__);
  2341. goto fail_closefb;
  2342. }
  2343. qemu_fclose(fb);
  2344. /* Send a notify to give a chance for anything that needs to happen
  2345. * at the transition to postcopy and after the device state; in particular
  2346. * spice needs to trigger a transition now
  2347. */
  2348. migration_call_notifiers(ms, MIG_EVENT_PRECOPY_DONE, NULL);
  2349. migration_downtime_end(ms);
  2350. if (migrate_postcopy_ram()) {
  2351. /*
  2352. * Although this ping is just for debug, it could potentially be
  2353. * used for getting a better measurement of downtime at the source.
  2354. */
  2355. qemu_savevm_send_ping(ms->to_dst_file, 4);
  2356. }
  2357. if (migrate_release_ram()) {
  2358. ram_postcopy_migrated_memory_release(ms);
  2359. }
  2360. ret = qemu_file_get_error(ms->to_dst_file);
  2361. if (ret) {
  2362. error_setg_errno(errp, -ret, "postcopy_start: Migration stream error");
  2363. goto fail;
  2364. }
  2365. trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
  2366. /*
  2367. * Now postcopy officially started, switch to postcopy bandwidth that
  2368. * user specified.
  2369. */
  2370. migration_rate_set(migrate_max_postcopy_bandwidth());
  2371. /* Now, switchover looks all fine, switching to postcopy-active */
  2372. migrate_set_state(&ms->state, MIGRATION_STATUS_DEVICE,
  2373. MIGRATION_STATUS_POSTCOPY_ACTIVE);
  2374. bql_unlock();
  2375. return ret;
  2376. fail_closefb:
  2377. qemu_fclose(fb);
  2378. fail:
  2379. migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
  2380. MIGRATION_STATUS_FAILED);
  2381. migration_block_activate(NULL);
  2382. migration_call_notifiers(ms, MIG_EVENT_PRECOPY_FAILED, NULL);
  2383. bql_unlock();
  2384. return -1;
  2385. }
  2386. /**
  2387. * @migration_switchover_prepare: Start VM switchover procedure
  2388. *
  2389. * @s: The migration state object pointer
  2390. *
  2391. * Prepares for the switchover, depending on "pause-before-switchover"
  2392. * capability.
  2393. *
  2394. * If cap set, state machine goes like:
  2395. * [postcopy-]active -> pre-switchover -> device
  2396. *
  2397. * If cap not set:
  2398. * [postcopy-]active -> device
  2399. *
  2400. * Returns: true on success, false on interruptions.
  2401. */
  2402. static bool migration_switchover_prepare(MigrationState *s)
  2403. {
  2404. /* Concurrent cancellation? Quit */
  2405. if (s->state == MIGRATION_STATUS_CANCELLING) {
  2406. return false;
  2407. }
  2408. /*
  2409. * No matter precopy or postcopy, since we still hold BQL it must not
  2410. * change concurrently to CANCELLING, so it must be either ACTIVE or
  2411. * POSTCOPY_ACTIVE.
  2412. */
  2413. assert(migration_is_active());
  2414. /* If the pre stage not requested, directly switch to DEVICE */
  2415. if (!migrate_pause_before_switchover()) {
  2416. migrate_set_state(&s->state, s->state, MIGRATION_STATUS_DEVICE);
  2417. return true;
  2418. }
  2419. /* Since leaving this state is not atomic with posting the semaphore
  2420. * it's possible that someone could have issued multiple migrate_continue
  2421. * and the semaphore is incorrectly positive at this point;
  2422. * the docs say it's undefined to reinit a semaphore that's already
  2423. * init'd, so use timedwait to eat up any existing posts.
  2424. */
  2425. while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
  2426. /* This block intentionally left blank */
  2427. }
  2428. /* Update [POSTCOPY_]ACTIVE to PRE_SWITCHOVER */
  2429. migrate_set_state(&s->state, s->state, MIGRATION_STATUS_PRE_SWITCHOVER);
  2430. bql_unlock();
  2431. qemu_sem_wait(&s->pause_sem);
  2432. bql_lock();
  2433. /*
  2434. * After BQL released and retaken, the state can be CANCELLING if it
  2435. * happend during sem_wait().. Only change the state if it's still
  2436. * pre-switchover.
  2437. */
  2438. migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
  2439. MIGRATION_STATUS_DEVICE);
  2440. return s->state == MIGRATION_STATUS_DEVICE;
  2441. }
  2442. static bool migration_switchover_start(MigrationState *s, Error **errp)
  2443. {
  2444. ERRP_GUARD();
  2445. if (!migration_switchover_prepare(s)) {
  2446. error_setg(errp, "Switchover is interrupted");
  2447. return false;
  2448. }
  2449. /* Inactivate disks except in COLO */
  2450. if (!migrate_colo()) {
  2451. /*
  2452. * Inactivate before sending QEMU_VM_EOF so that the
  2453. * bdrv_activate_all() on the other end won't fail.
  2454. */
  2455. if (!migration_block_inactivate()) {
  2456. error_setg(errp, "Block inactivate failed during switchover");
  2457. return false;
  2458. }
  2459. }
  2460. migration_rate_set(RATE_LIMIT_DISABLED);
  2461. precopy_notify_complete();
  2462. return true;
  2463. }
  2464. static int migration_completion_precopy(MigrationState *s)
  2465. {
  2466. int ret;
  2467. bql_lock();
  2468. if (!migrate_mode_is_cpr(s)) {
  2469. ret = migration_stop_vm(s, RUN_STATE_FINISH_MIGRATE);
  2470. if (ret < 0) {
  2471. goto out_unlock;
  2472. }
  2473. }
  2474. if (!migration_switchover_start(s, NULL)) {
  2475. ret = -EFAULT;
  2476. goto out_unlock;
  2477. }
  2478. ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false);
  2479. out_unlock:
  2480. bql_unlock();
  2481. return ret;
  2482. }
  2483. static void migration_completion_postcopy(MigrationState *s)
  2484. {
  2485. trace_migration_completion_postcopy_end();
  2486. bql_lock();
  2487. qemu_savevm_state_complete_postcopy(s->to_dst_file);
  2488. bql_unlock();
  2489. /*
  2490. * Shutdown the postcopy fast path thread. This is only needed when dest
  2491. * QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need this.
  2492. */
  2493. if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
  2494. postcopy_preempt_shutdown_file(s);
  2495. }
  2496. trace_migration_completion_postcopy_end_after_complete();
  2497. }
  2498. /**
  2499. * migration_completion: Used by migration_thread when there's not much left.
  2500. * The caller 'breaks' the loop when this returns.
  2501. *
  2502. * @s: Current migration state
  2503. */
  2504. static void migration_completion(MigrationState *s)
  2505. {
  2506. int ret = 0;
  2507. Error *local_err = NULL;
  2508. if (s->state == MIGRATION_STATUS_ACTIVE) {
  2509. ret = migration_completion_precopy(s);
  2510. } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
  2511. migration_completion_postcopy(s);
  2512. } else {
  2513. ret = -1;
  2514. }
  2515. if (ret < 0) {
  2516. goto fail;
  2517. }
  2518. if (close_return_path_on_source(s)) {
  2519. goto fail;
  2520. }
  2521. if (qemu_file_get_error(s->to_dst_file)) {
  2522. trace_migration_completion_file_err();
  2523. goto fail;
  2524. }
  2525. if (migrate_colo() && s->state == MIGRATION_STATUS_ACTIVE) {
  2526. /* COLO does not support postcopy */
  2527. migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
  2528. MIGRATION_STATUS_COLO);
  2529. } else {
  2530. migration_completion_end(s);
  2531. }
  2532. return;
  2533. fail:
  2534. if (qemu_file_get_error_obj(s->to_dst_file, &local_err)) {
  2535. migrate_set_error(s, local_err);
  2536. error_free(local_err);
  2537. } else if (ret) {
  2538. error_setg_errno(&local_err, -ret, "Error in migration completion");
  2539. migrate_set_error(s, local_err);
  2540. error_free(local_err);
  2541. }
  2542. migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
  2543. }
  2544. /**
  2545. * bg_migration_completion: Used by bg_migration_thread when after all the
  2546. * RAM has been saved. The caller 'breaks' the loop when this returns.
  2547. *
  2548. * @s: Current migration state
  2549. */
  2550. static void bg_migration_completion(MigrationState *s)
  2551. {
  2552. int current_active_state = s->state;
  2553. if (s->state == MIGRATION_STATUS_ACTIVE) {
  2554. /*
  2555. * By this moment we have RAM content saved into the migration stream.
  2556. * The next step is to flush the non-RAM content (device state)
  2557. * right after the ram content. The device state has been stored into
  2558. * the temporary buffer before RAM saving started.
  2559. */
  2560. qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
  2561. qemu_fflush(s->to_dst_file);
  2562. } else if (s->state == MIGRATION_STATUS_CANCELLING) {
  2563. goto fail;
  2564. }
  2565. if (qemu_file_get_error(s->to_dst_file)) {
  2566. trace_migration_completion_file_err();
  2567. goto fail;
  2568. }
  2569. migration_completion_end(s);
  2570. return;
  2571. fail:
  2572. migrate_set_state(&s->state, current_active_state,
  2573. MIGRATION_STATUS_FAILED);
  2574. }
  2575. typedef enum MigThrError {
  2576. /* No error detected */
  2577. MIG_THR_ERR_NONE = 0,
  2578. /* Detected error, but resumed successfully */
  2579. MIG_THR_ERR_RECOVERED = 1,
  2580. /* Detected fatal error, need to exit */
  2581. MIG_THR_ERR_FATAL = 2,
  2582. } MigThrError;
  2583. static int postcopy_resume_handshake(MigrationState *s)
  2584. {
  2585. qemu_savevm_send_postcopy_resume(s->to_dst_file);
  2586. while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
  2587. if (migration_rp_wait(s)) {
  2588. return -1;
  2589. }
  2590. }
  2591. if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
  2592. return 0;
  2593. }
  2594. return -1;
  2595. }
  2596. /* Return zero if success, or <0 for error */
  2597. static int postcopy_do_resume(MigrationState *s)
  2598. {
  2599. int ret;
  2600. /*
  2601. * Call all the resume_prepare() hooks, so that modules can be
  2602. * ready for the migration resume.
  2603. */
  2604. ret = qemu_savevm_state_resume_prepare(s);
  2605. if (ret) {
  2606. error_report("%s: resume_prepare() failure detected: %d",
  2607. __func__, ret);
  2608. return ret;
  2609. }
  2610. /*
  2611. * If preempt is enabled, re-establish the preempt channel. Note that
  2612. * we do it after resume prepare to make sure the main channel will be
  2613. * created before the preempt channel. E.g. with weak network, the
  2614. * dest QEMU may get messed up with the preempt and main channels on
  2615. * the order of connection setup. This guarantees the correct order.
  2616. */
  2617. ret = postcopy_preempt_establish_channel(s);
  2618. if (ret) {
  2619. error_report("%s: postcopy_preempt_establish_channel(): %d",
  2620. __func__, ret);
  2621. return ret;
  2622. }
  2623. /*
  2624. * Last handshake with destination on the resume (destination will
  2625. * switch to postcopy-active afterwards)
  2626. */
  2627. ret = postcopy_resume_handshake(s);
  2628. if (ret) {
  2629. error_report("%s: handshake failed: %d", __func__, ret);
  2630. return ret;
  2631. }
  2632. return 0;
  2633. }
  2634. /*
  2635. * We don't return until we are in a safe state to continue current
  2636. * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
  2637. * MIG_THR_ERR_FATAL if unrecovery failure happened.
  2638. */
  2639. static MigThrError postcopy_pause(MigrationState *s)
  2640. {
  2641. assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
  2642. while (true) {
  2643. QEMUFile *file;
  2644. /*
  2645. * We're already pausing, so ignore any errors on the return
  2646. * path and just wait for the thread to finish. It will be
  2647. * re-created when we resume.
  2648. */
  2649. close_return_path_on_source(s);
  2650. /*
  2651. * Current channel is possibly broken. Release it. Note that this is
  2652. * guaranteed even without lock because to_dst_file should only be
  2653. * modified by the migration thread. That also guarantees that the
  2654. * unregister of yank is safe too without the lock. It should be safe
  2655. * even to be within the qemu_file_lock, but we didn't do that to avoid
  2656. * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
  2657. * the qemu_file_lock critical section as small as possible.
  2658. */
  2659. assert(s->to_dst_file);
  2660. migration_ioc_unregister_yank_from_file(s->to_dst_file);
  2661. qemu_mutex_lock(&s->qemu_file_lock);
  2662. file = s->to_dst_file;
  2663. s->to_dst_file = NULL;
  2664. qemu_mutex_unlock(&s->qemu_file_lock);
  2665. qemu_file_shutdown(file);
  2666. qemu_fclose(file);
  2667. migrate_set_state(&s->state, s->state,
  2668. MIGRATION_STATUS_POSTCOPY_PAUSED);
  2669. error_report("Detected IO failure for postcopy. "
  2670. "Migration paused.");
  2671. /*
  2672. * We wait until things fixed up. Then someone will setup the
  2673. * status back for us.
  2674. */
  2675. do {
  2676. qemu_sem_wait(&s->postcopy_pause_sem);
  2677. } while (postcopy_is_paused(s->state));
  2678. if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
  2679. /* Woken up by a recover procedure. Give it a shot */
  2680. /* Do the resume logic */
  2681. if (postcopy_do_resume(s) == 0) {
  2682. /* Let's continue! */
  2683. trace_postcopy_pause_continued();
  2684. return MIG_THR_ERR_RECOVERED;
  2685. } else {
  2686. /*
  2687. * Something wrong happened during the recovery, let's
  2688. * pause again. Pause is always better than throwing
  2689. * data away.
  2690. */
  2691. continue;
  2692. }
  2693. } else {
  2694. /* This is not right... Time to quit. */
  2695. return MIG_THR_ERR_FATAL;
  2696. }
  2697. }
  2698. }
  2699. void migration_file_set_error(int ret, Error *err)
  2700. {
  2701. MigrationState *s = current_migration;
  2702. WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
  2703. if (s->to_dst_file) {
  2704. qemu_file_set_error_obj(s->to_dst_file, ret, err);
  2705. } else if (err) {
  2706. error_report_err(err);
  2707. }
  2708. }
  2709. }
  2710. static MigThrError migration_detect_error(MigrationState *s)
  2711. {
  2712. int ret;
  2713. int state = s->state;
  2714. Error *local_error = NULL;
  2715. if (state == MIGRATION_STATUS_CANCELLING ||
  2716. state == MIGRATION_STATUS_CANCELLED) {
  2717. /* End the migration, but don't set the state to failed */
  2718. return MIG_THR_ERR_FATAL;
  2719. }
  2720. /*
  2721. * Try to detect any file errors. Note that postcopy_qemufile_src will
  2722. * be NULL when postcopy preempt is not enabled.
  2723. */
  2724. ret = qemu_file_get_error_obj_any(s->to_dst_file,
  2725. s->postcopy_qemufile_src,
  2726. &local_error);
  2727. if (!ret) {
  2728. /* Everything is fine */
  2729. assert(!local_error);
  2730. return MIG_THR_ERR_NONE;
  2731. }
  2732. if (local_error) {
  2733. migrate_set_error(s, local_error);
  2734. error_free(local_error);
  2735. }
  2736. if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
  2737. /*
  2738. * For postcopy, we allow the network to be down for a
  2739. * while. After that, it can be continued by a
  2740. * recovery phase.
  2741. */
  2742. return postcopy_pause(s);
  2743. } else {
  2744. /*
  2745. * For precopy (or postcopy with error outside IO), we fail
  2746. * with no time.
  2747. */
  2748. migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
  2749. trace_migration_thread_file_err();
  2750. /* Time to stop the migration, now. */
  2751. return MIG_THR_ERR_FATAL;
  2752. }
  2753. }
  2754. static void migration_completion_end(MigrationState *s)
  2755. {
  2756. uint64_t bytes = migration_transferred_bytes();
  2757. int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
  2758. int64_t transfer_time;
  2759. /*
  2760. * Take the BQL here so that query-migrate on the QMP thread sees:
  2761. * - atomic update of s->total_time and s->mbps;
  2762. * - correct ordering of s->mbps update vs. s->state;
  2763. */
  2764. bql_lock();
  2765. migration_downtime_end(s);
  2766. s->total_time = end_time - s->start_time;
  2767. transfer_time = s->total_time - s->setup_time;
  2768. if (transfer_time) {
  2769. s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
  2770. }
  2771. migrate_set_state(&s->state, s->state,
  2772. MIGRATION_STATUS_COMPLETED);
  2773. bql_unlock();
  2774. }
  2775. static void update_iteration_initial_status(MigrationState *s)
  2776. {
  2777. /*
  2778. * Update these three fields at the same time to avoid mismatch info lead
  2779. * wrong speed calculation.
  2780. */
  2781. s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
  2782. s->iteration_initial_bytes = migration_transferred_bytes();
  2783. s->iteration_initial_pages = ram_get_total_transferred_pages();
  2784. }
  2785. static void migration_update_counters(MigrationState *s,
  2786. int64_t current_time)
  2787. {
  2788. uint64_t transferred, transferred_pages, time_spent;
  2789. uint64_t current_bytes; /* bytes transferred since the beginning */
  2790. uint64_t switchover_bw;
  2791. /* Expected bandwidth when switching over to destination QEMU */
  2792. double expected_bw_per_ms;
  2793. double bandwidth;
  2794. if (current_time < s->iteration_start_time + BUFFER_DELAY) {
  2795. return;
  2796. }
  2797. switchover_bw = migrate_avail_switchover_bandwidth();
  2798. current_bytes = migration_transferred_bytes();
  2799. transferred = current_bytes - s->iteration_initial_bytes;
  2800. time_spent = current_time - s->iteration_start_time;
  2801. bandwidth = (double)transferred / time_spent;
  2802. if (switchover_bw) {
  2803. /*
  2804. * If the user specified a switchover bandwidth, let's trust the
  2805. * user so that can be more accurate than what we estimated.
  2806. */
  2807. expected_bw_per_ms = switchover_bw / 1000;
  2808. } else {
  2809. /* If the user doesn't specify bandwidth, we use the estimated */
  2810. expected_bw_per_ms = bandwidth;
  2811. }
  2812. s->threshold_size = expected_bw_per_ms * migrate_downtime_limit();
  2813. s->mbps = (((double) transferred * 8.0) /
  2814. ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
  2815. transferred_pages = ram_get_total_transferred_pages() -
  2816. s->iteration_initial_pages;
  2817. s->pages_per_second = (double) transferred_pages /
  2818. (((double) time_spent / 1000.0));
  2819. /*
  2820. * if we haven't sent anything, we don't want to
  2821. * recalculate. 10000 is a small enough number for our purposes
  2822. */
  2823. if (stat64_get(&mig_stats.dirty_pages_rate) &&
  2824. transferred > 10000) {
  2825. s->expected_downtime =
  2826. stat64_get(&mig_stats.dirty_bytes_last_sync) / expected_bw_per_ms;
  2827. }
  2828. migration_rate_reset();
  2829. update_iteration_initial_status(s);
  2830. trace_migrate_transferred(transferred, time_spent,
  2831. /* Both in unit bytes/ms */
  2832. bandwidth, switchover_bw / 1000,
  2833. s->threshold_size);
  2834. }
  2835. static bool migration_can_switchover(MigrationState *s)
  2836. {
  2837. if (!migrate_switchover_ack()) {
  2838. return true;
  2839. }
  2840. /* No reason to wait for switchover ACK if VM is stopped */
  2841. if (!runstate_is_running()) {
  2842. return true;
  2843. }
  2844. return s->switchover_acked;
  2845. }
  2846. /* Migration thread iteration status */
  2847. typedef enum {
  2848. MIG_ITERATE_RESUME, /* Resume current iteration */
  2849. MIG_ITERATE_SKIP, /* Skip current iteration */
  2850. MIG_ITERATE_BREAK, /* Break the loop */
  2851. } MigIterateState;
  2852. /*
  2853. * Return true if continue to the next iteration directly, false
  2854. * otherwise.
  2855. */
  2856. static MigIterateState migration_iteration_run(MigrationState *s)
  2857. {
  2858. uint64_t must_precopy, can_postcopy, pending_size;
  2859. Error *local_err = NULL;
  2860. bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
  2861. bool can_switchover = migration_can_switchover(s);
  2862. qemu_savevm_state_pending_estimate(&must_precopy, &can_postcopy);
  2863. pending_size = must_precopy + can_postcopy;
  2864. trace_migrate_pending_estimate(pending_size, must_precopy, can_postcopy);
  2865. if (pending_size < s->threshold_size) {
  2866. qemu_savevm_state_pending_exact(&must_precopy, &can_postcopy);
  2867. pending_size = must_precopy + can_postcopy;
  2868. trace_migrate_pending_exact(pending_size, must_precopy, can_postcopy);
  2869. }
  2870. if ((!pending_size || pending_size < s->threshold_size) && can_switchover) {
  2871. trace_migration_thread_low_pending(pending_size);
  2872. migration_completion(s);
  2873. return MIG_ITERATE_BREAK;
  2874. }
  2875. /* Still a significant amount to transfer */
  2876. if (!in_postcopy && must_precopy <= s->threshold_size && can_switchover &&
  2877. qatomic_read(&s->start_postcopy)) {
  2878. if (postcopy_start(s, &local_err)) {
  2879. migrate_set_error(s, local_err);
  2880. error_report_err(local_err);
  2881. }
  2882. return MIG_ITERATE_SKIP;
  2883. }
  2884. /* Just another iteration step */
  2885. qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
  2886. return MIG_ITERATE_RESUME;
  2887. }
  2888. static void migration_iteration_finish(MigrationState *s)
  2889. {
  2890. bql_lock();
  2891. /*
  2892. * If we enabled cpu throttling for auto-converge, turn it off.
  2893. * Stopping CPU throttle should be serialized by BQL to avoid
  2894. * racing for the throttle_dirty_sync_timer.
  2895. */
  2896. if (migrate_auto_converge()) {
  2897. cpu_throttle_stop();
  2898. }
  2899. switch (s->state) {
  2900. case MIGRATION_STATUS_COMPLETED:
  2901. runstate_set(RUN_STATE_POSTMIGRATE);
  2902. break;
  2903. case MIGRATION_STATUS_COLO:
  2904. assert(migrate_colo());
  2905. migrate_start_colo_process(s);
  2906. s->vm_old_state = RUN_STATE_RUNNING;
  2907. /* Fallthrough */
  2908. case MIGRATION_STATUS_FAILED:
  2909. case MIGRATION_STATUS_CANCELLED:
  2910. case MIGRATION_STATUS_CANCELLING:
  2911. /*
  2912. * Re-activate the block drives if they're inactivated. Note, COLO
  2913. * shouldn't use block_active at all, so it should be no-op there.
  2914. */
  2915. migration_block_activate(NULL);
  2916. if (runstate_is_live(s->vm_old_state)) {
  2917. if (!runstate_check(RUN_STATE_SHUTDOWN)) {
  2918. vm_start();
  2919. }
  2920. } else {
  2921. if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
  2922. runstate_set(s->vm_old_state);
  2923. }
  2924. }
  2925. break;
  2926. default:
  2927. /* Should not reach here, but if so, forgive the VM. */
  2928. error_report("%s: Unknown ending state %d", __func__, s->state);
  2929. break;
  2930. }
  2931. migration_bh_schedule(migrate_fd_cleanup_bh, s);
  2932. bql_unlock();
  2933. }
  2934. static void bg_migration_iteration_finish(MigrationState *s)
  2935. {
  2936. /*
  2937. * Stop tracking RAM writes - un-protect memory, un-register UFFD
  2938. * memory ranges, flush kernel wait queues and wake up threads
  2939. * waiting for write fault to be resolved.
  2940. */
  2941. ram_write_tracking_stop();
  2942. bql_lock();
  2943. switch (s->state) {
  2944. case MIGRATION_STATUS_COMPLETED:
  2945. case MIGRATION_STATUS_ACTIVE:
  2946. case MIGRATION_STATUS_FAILED:
  2947. case MIGRATION_STATUS_CANCELLED:
  2948. case MIGRATION_STATUS_CANCELLING:
  2949. break;
  2950. default:
  2951. /* Should not reach here, but if so, forgive the VM. */
  2952. error_report("%s: Unknown ending state %d", __func__, s->state);
  2953. break;
  2954. }
  2955. migration_bh_schedule(migrate_fd_cleanup_bh, s);
  2956. bql_unlock();
  2957. }
  2958. /*
  2959. * Return true if continue to the next iteration directly, false
  2960. * otherwise.
  2961. */
  2962. static MigIterateState bg_migration_iteration_run(MigrationState *s)
  2963. {
  2964. int res;
  2965. res = qemu_savevm_state_iterate(s->to_dst_file, false);
  2966. if (res > 0) {
  2967. bg_migration_completion(s);
  2968. return MIG_ITERATE_BREAK;
  2969. }
  2970. return MIG_ITERATE_RESUME;
  2971. }
  2972. void migration_make_urgent_request(void)
  2973. {
  2974. qemu_sem_post(&migrate_get_current()->rate_limit_sem);
  2975. }
  2976. void migration_consume_urgent_request(void)
  2977. {
  2978. qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
  2979. }
  2980. /* Returns true if the rate limiting was broken by an urgent request */
  2981. bool migration_rate_limit(void)
  2982. {
  2983. int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
  2984. MigrationState *s = migrate_get_current();
  2985. bool urgent = false;
  2986. migration_update_counters(s, now);
  2987. if (migration_rate_exceeded(s->to_dst_file)) {
  2988. if (qemu_file_get_error(s->to_dst_file)) {
  2989. return false;
  2990. }
  2991. /*
  2992. * Wait for a delay to do rate limiting OR
  2993. * something urgent to post the semaphore.
  2994. */
  2995. int ms = s->iteration_start_time + BUFFER_DELAY - now;
  2996. trace_migration_rate_limit_pre(ms);
  2997. if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
  2998. /*
  2999. * We were woken by one or more urgent things but
  3000. * the timedwait will have consumed one of them.
  3001. * The service routine for the urgent wake will dec
  3002. * the semaphore itself for each item it consumes,
  3003. * so add this one we just eat back.
  3004. */
  3005. qemu_sem_post(&s->rate_limit_sem);
  3006. urgent = true;
  3007. }
  3008. trace_migration_rate_limit_post(urgent);
  3009. }
  3010. return urgent;
  3011. }
  3012. /*
  3013. * if failover devices are present, wait they are completely
  3014. * unplugged
  3015. */
  3016. static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
  3017. int new_state)
  3018. {
  3019. if (qemu_savevm_state_guest_unplug_pending()) {
  3020. migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
  3021. while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
  3022. qemu_savevm_state_guest_unplug_pending()) {
  3023. qemu_sem_timedwait(&s->wait_unplug_sem, 250);
  3024. }
  3025. if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
  3026. int timeout = 120; /* 30 seconds */
  3027. /*
  3028. * migration has been canceled
  3029. * but as we have started an unplug we must wait the end
  3030. * to be able to plug back the card
  3031. */
  3032. while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
  3033. qemu_sem_timedwait(&s->wait_unplug_sem, 250);
  3034. }
  3035. if (qemu_savevm_state_guest_unplug_pending() &&
  3036. !qtest_enabled()) {
  3037. warn_report("migration: partially unplugged device on "
  3038. "failure");
  3039. }
  3040. }
  3041. migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
  3042. } else {
  3043. migrate_set_state(&s->state, old_state, new_state);
  3044. }
  3045. }
  3046. /*
  3047. * Master migration thread on the source VM.
  3048. * It drives the migration and pumps the data down the outgoing channel.
  3049. */
  3050. static void *migration_thread(void *opaque)
  3051. {
  3052. MigrationState *s = opaque;
  3053. MigrationThread *thread = NULL;
  3054. int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
  3055. MigThrError thr_error;
  3056. bool urgent = false;
  3057. Error *local_err = NULL;
  3058. int ret;
  3059. thread = migration_threads_add(MIGRATION_THREAD_SRC_MAIN,
  3060. qemu_get_thread_id());
  3061. rcu_register_thread();
  3062. update_iteration_initial_status(s);
  3063. if (!multifd_send_setup()) {
  3064. goto out;
  3065. }
  3066. bql_lock();
  3067. qemu_savevm_state_header(s->to_dst_file);
  3068. bql_unlock();
  3069. /*
  3070. * If we opened the return path, we need to make sure dst has it
  3071. * opened as well.
  3072. */
  3073. if (s->rp_state.rp_thread_created) {
  3074. /* Now tell the dest that it should open its end so it can reply */
  3075. qemu_savevm_send_open_return_path(s->to_dst_file);
  3076. /* And do a ping that will make stuff easier to debug */
  3077. qemu_savevm_send_ping(s->to_dst_file, 1);
  3078. }
  3079. if (migrate_postcopy()) {
  3080. /*
  3081. * Tell the destination that we *might* want to do postcopy later;
  3082. * if the other end can't do postcopy it should fail now, nice and
  3083. * early.
  3084. */
  3085. qemu_savevm_send_postcopy_advise(s->to_dst_file);
  3086. }
  3087. if (migrate_colo()) {
  3088. /* Notify migration destination that we enable COLO */
  3089. qemu_savevm_send_colo_enable(s->to_dst_file);
  3090. }
  3091. if (migrate_auto_converge()) {
  3092. /* Start RAMBlock dirty bitmap sync timer */
  3093. cpu_throttle_dirty_sync_timer(true);
  3094. }
  3095. bql_lock();
  3096. ret = qemu_savevm_state_setup(s->to_dst_file, &local_err);
  3097. bql_unlock();
  3098. qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
  3099. MIGRATION_STATUS_ACTIVE);
  3100. /*
  3101. * Handle SETUP failures after waiting for virtio-net-failover
  3102. * devices to unplug. This to preserve migration state transitions.
  3103. */
  3104. if (ret) {
  3105. migrate_set_error(s, local_err);
  3106. error_free(local_err);
  3107. migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
  3108. MIGRATION_STATUS_FAILED);
  3109. goto out;
  3110. }
  3111. s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
  3112. trace_migration_thread_setup_complete();
  3113. while (migration_is_active()) {
  3114. if (urgent || !migration_rate_exceeded(s->to_dst_file)) {
  3115. MigIterateState iter_state = migration_iteration_run(s);
  3116. if (iter_state == MIG_ITERATE_SKIP) {
  3117. continue;
  3118. } else if (iter_state == MIG_ITERATE_BREAK) {
  3119. break;
  3120. }
  3121. }
  3122. /*
  3123. * Try to detect any kind of failures, and see whether we
  3124. * should stop the migration now.
  3125. */
  3126. thr_error = migration_detect_error(s);
  3127. if (thr_error == MIG_THR_ERR_FATAL) {
  3128. /* Stop migration */
  3129. break;
  3130. } else if (thr_error == MIG_THR_ERR_RECOVERED) {
  3131. /*
  3132. * Just recovered from a e.g. network failure, reset all
  3133. * the local variables. This is important to avoid
  3134. * breaking transferred_bytes and bandwidth calculation
  3135. */
  3136. update_iteration_initial_status(s);
  3137. }
  3138. urgent = migration_rate_limit();
  3139. }
  3140. out:
  3141. trace_migration_thread_after_loop();
  3142. migration_iteration_finish(s);
  3143. object_unref(OBJECT(s));
  3144. rcu_unregister_thread();
  3145. migration_threads_remove(thread);
  3146. return NULL;
  3147. }
  3148. static void bg_migration_vm_start_bh(void *opaque)
  3149. {
  3150. MigrationState *s = opaque;
  3151. vm_resume(s->vm_old_state);
  3152. migration_downtime_end(s);
  3153. }
  3154. /**
  3155. * Background snapshot thread, based on live migration code.
  3156. * This is an alternative implementation of live migration mechanism
  3157. * introduced specifically to support background snapshots.
  3158. *
  3159. * It takes advantage of userfault_fd write protection mechanism introduced
  3160. * in v5.7 kernel. Compared to existing dirty page logging migration much
  3161. * lesser stream traffic is produced resulting in smaller snapshot images,
  3162. * simply cause of no page duplicates can get into the stream.
  3163. *
  3164. * Another key point is that generated vmstate stream reflects machine state
  3165. * 'frozen' at the beginning of snapshot creation compared to dirty page logging
  3166. * mechanism, which effectively results in that saved snapshot is the state of VM
  3167. * at the end of the process.
  3168. */
  3169. static void *bg_migration_thread(void *opaque)
  3170. {
  3171. MigrationState *s = opaque;
  3172. int64_t setup_start;
  3173. MigThrError thr_error;
  3174. QEMUFile *fb;
  3175. bool early_fail = true;
  3176. Error *local_err = NULL;
  3177. int ret;
  3178. rcu_register_thread();
  3179. migration_rate_set(RATE_LIMIT_DISABLED);
  3180. setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
  3181. /*
  3182. * We want to save vmstate for the moment when migration has been
  3183. * initiated but also we want to save RAM content while VM is running.
  3184. * The RAM content should appear first in the vmstate. So, we first
  3185. * stash the non-RAM part of the vmstate to the temporary buffer,
  3186. * then write RAM part of the vmstate to the migration stream
  3187. * with vCPUs running and, finally, write stashed non-RAM part of
  3188. * the vmstate from the buffer to the migration stream.
  3189. */
  3190. s->bioc = qio_channel_buffer_new(512 * 1024);
  3191. qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
  3192. fb = qemu_file_new_output(QIO_CHANNEL(s->bioc));
  3193. object_unref(OBJECT(s->bioc));
  3194. update_iteration_initial_status(s);
  3195. /*
  3196. * Prepare for tracking memory writes with UFFD-WP - populate
  3197. * RAM pages before protecting.
  3198. */
  3199. #ifdef __linux__
  3200. ram_write_tracking_prepare();
  3201. #endif
  3202. bql_lock();
  3203. qemu_savevm_state_header(s->to_dst_file);
  3204. ret = qemu_savevm_state_setup(s->to_dst_file, &local_err);
  3205. bql_unlock();
  3206. qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
  3207. MIGRATION_STATUS_ACTIVE);
  3208. /*
  3209. * Handle SETUP failures after waiting for virtio-net-failover
  3210. * devices to unplug. This to preserve migration state transitions.
  3211. */
  3212. if (ret) {
  3213. migrate_set_error(s, local_err);
  3214. error_free(local_err);
  3215. migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
  3216. MIGRATION_STATUS_FAILED);
  3217. goto fail_setup;
  3218. }
  3219. s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
  3220. trace_migration_thread_setup_complete();
  3221. bql_lock();
  3222. if (migration_stop_vm(s, RUN_STATE_PAUSED)) {
  3223. goto fail;
  3224. }
  3225. if (qemu_savevm_state_complete_precopy_non_iterable(fb, false)) {
  3226. goto fail;
  3227. }
  3228. /*
  3229. * Since we are going to get non-iterable state data directly
  3230. * from s->bioc->data, explicit flush is needed here.
  3231. */
  3232. qemu_fflush(fb);
  3233. /* Now initialize UFFD context and start tracking RAM writes */
  3234. if (ram_write_tracking_start()) {
  3235. goto fail;
  3236. }
  3237. early_fail = false;
  3238. /*
  3239. * Start VM from BH handler to avoid write-fault lock here.
  3240. * UFFD-WP protection for the whole RAM is already enabled so
  3241. * calling VM state change notifiers from vm_start() would initiate
  3242. * writes to virtio VQs memory which is in write-protected region.
  3243. */
  3244. migration_bh_schedule(bg_migration_vm_start_bh, s);
  3245. bql_unlock();
  3246. while (migration_is_active()) {
  3247. MigIterateState iter_state = bg_migration_iteration_run(s);
  3248. if (iter_state == MIG_ITERATE_SKIP) {
  3249. continue;
  3250. } else if (iter_state == MIG_ITERATE_BREAK) {
  3251. break;
  3252. }
  3253. /*
  3254. * Try to detect any kind of failures, and see whether we
  3255. * should stop the migration now.
  3256. */
  3257. thr_error = migration_detect_error(s);
  3258. if (thr_error == MIG_THR_ERR_FATAL) {
  3259. /* Stop migration */
  3260. break;
  3261. }
  3262. migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
  3263. }
  3264. trace_migration_thread_after_loop();
  3265. fail:
  3266. if (early_fail) {
  3267. migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
  3268. MIGRATION_STATUS_FAILED);
  3269. bql_unlock();
  3270. }
  3271. fail_setup:
  3272. bg_migration_iteration_finish(s);
  3273. qemu_fclose(fb);
  3274. object_unref(OBJECT(s));
  3275. rcu_unregister_thread();
  3276. return NULL;
  3277. }
  3278. void migrate_fd_connect(MigrationState *s, Error *error_in)
  3279. {
  3280. Error *local_err = NULL;
  3281. uint64_t rate_limit;
  3282. bool resume = (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP);
  3283. int ret;
  3284. /*
  3285. * If there's a previous error, free it and prepare for another one.
  3286. * Meanwhile if migration completes successfully, there won't have an error
  3287. * dumped when calling migrate_fd_cleanup().
  3288. */
  3289. migrate_error_free(s);
  3290. s->expected_downtime = migrate_downtime_limit();
  3291. if (error_in) {
  3292. migrate_fd_error(s, error_in);
  3293. if (resume) {
  3294. /*
  3295. * Don't do cleanup for resume if channel is invalid, but only dump
  3296. * the error. We wait for another channel connect from the user.
  3297. * The error_report still gives HMP user a hint on what failed.
  3298. * It's normally done in migrate_fd_cleanup(), but call it here
  3299. * explicitly.
  3300. */
  3301. error_report_err(error_copy(s->error));
  3302. } else {
  3303. migrate_fd_cleanup(s);
  3304. }
  3305. return;
  3306. }
  3307. if (resume) {
  3308. /* This is a resumed migration */
  3309. rate_limit = migrate_max_postcopy_bandwidth();
  3310. } else {
  3311. /* This is a fresh new migration */
  3312. rate_limit = migrate_max_bandwidth();
  3313. /* Notify before starting migration thread */
  3314. if (migration_call_notifiers(s, MIG_EVENT_PRECOPY_SETUP, &local_err)) {
  3315. goto fail;
  3316. }
  3317. }
  3318. migration_rate_set(rate_limit);
  3319. qemu_file_set_blocking(s->to_dst_file, true);
  3320. /*
  3321. * Open the return path. For postcopy, it is used exclusively. For
  3322. * precopy, only if user specified "return-path" capability would
  3323. * QEMU uses the return path.
  3324. */
  3325. if (migrate_postcopy_ram() || migrate_return_path()) {
  3326. if (open_return_path_on_source(s)) {
  3327. error_setg(&local_err, "Unable to open return-path for postcopy");
  3328. goto fail;
  3329. }
  3330. }
  3331. /*
  3332. * This needs to be done before resuming a postcopy. Note: for newer
  3333. * QEMUs we will delay the channel creation until postcopy_start(), to
  3334. * avoid disorder of channel creations.
  3335. */
  3336. if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
  3337. postcopy_preempt_setup(s);
  3338. }
  3339. if (resume) {
  3340. /* Wakeup the main migration thread to do the recovery */
  3341. migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP,
  3342. MIGRATION_STATUS_POSTCOPY_RECOVER);
  3343. qemu_sem_post(&s->postcopy_pause_sem);
  3344. return;
  3345. }
  3346. if (migrate_mode_is_cpr(s)) {
  3347. ret = migration_stop_vm(s, RUN_STATE_FINISH_MIGRATE);
  3348. if (ret < 0) {
  3349. error_setg(&local_err, "migration_stop_vm failed, error %d", -ret);
  3350. goto fail;
  3351. }
  3352. }
  3353. /*
  3354. * Take a refcount to make sure the migration object won't get freed by
  3355. * the main thread already in migration_shutdown().
  3356. *
  3357. * The refcount will be released at the end of the thread function.
  3358. */
  3359. object_ref(OBJECT(s));
  3360. if (migrate_background_snapshot()) {
  3361. qemu_thread_create(&s->thread, MIGRATION_THREAD_SNAPSHOT,
  3362. bg_migration_thread, s, QEMU_THREAD_JOINABLE);
  3363. } else {
  3364. qemu_thread_create(&s->thread, MIGRATION_THREAD_SRC_MAIN,
  3365. migration_thread, s, QEMU_THREAD_JOINABLE);
  3366. }
  3367. s->migration_thread_running = true;
  3368. return;
  3369. fail:
  3370. migrate_set_error(s, local_err);
  3371. migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
  3372. error_report_err(local_err);
  3373. migrate_fd_cleanup(s);
  3374. }
  3375. static void migration_class_init(ObjectClass *klass, void *data)
  3376. {
  3377. DeviceClass *dc = DEVICE_CLASS(klass);
  3378. dc->user_creatable = false;
  3379. device_class_set_props_n(dc, migration_properties,
  3380. migration_properties_count);
  3381. }
  3382. static void migration_instance_finalize(Object *obj)
  3383. {
  3384. MigrationState *ms = MIGRATION_OBJ(obj);
  3385. qemu_mutex_destroy(&ms->error_mutex);
  3386. qemu_mutex_destroy(&ms->qemu_file_lock);
  3387. qemu_sem_destroy(&ms->wait_unplug_sem);
  3388. qemu_sem_destroy(&ms->rate_limit_sem);
  3389. qemu_sem_destroy(&ms->pause_sem);
  3390. qemu_sem_destroy(&ms->postcopy_pause_sem);
  3391. qemu_sem_destroy(&ms->rp_state.rp_sem);
  3392. qemu_sem_destroy(&ms->rp_state.rp_pong_acks);
  3393. qemu_sem_destroy(&ms->postcopy_qemufile_src_sem);
  3394. error_free(ms->error);
  3395. }
  3396. static void migration_instance_init(Object *obj)
  3397. {
  3398. MigrationState *ms = MIGRATION_OBJ(obj);
  3399. ms->state = MIGRATION_STATUS_NONE;
  3400. ms->mbps = -1;
  3401. ms->pages_per_second = -1;
  3402. /* Freshly started QEMU owns all the block devices */
  3403. migration_block_active_setup(true);
  3404. qemu_sem_init(&ms->pause_sem, 0);
  3405. qemu_mutex_init(&ms->error_mutex);
  3406. migrate_params_init(&ms->parameters);
  3407. qemu_sem_init(&ms->postcopy_pause_sem, 0);
  3408. qemu_sem_init(&ms->rp_state.rp_sem, 0);
  3409. qemu_sem_init(&ms->rp_state.rp_pong_acks, 0);
  3410. qemu_sem_init(&ms->rate_limit_sem, 0);
  3411. qemu_sem_init(&ms->wait_unplug_sem, 0);
  3412. qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0);
  3413. qemu_mutex_init(&ms->qemu_file_lock);
  3414. }
  3415. /*
  3416. * Return true if check pass, false otherwise. Error will be put
  3417. * inside errp if provided.
  3418. */
  3419. static bool migration_object_check(MigrationState *ms, Error **errp)
  3420. {
  3421. /* Assuming all off */
  3422. bool old_caps[MIGRATION_CAPABILITY__MAX] = { 0 };
  3423. if (!migrate_params_check(&ms->parameters, errp)) {
  3424. return false;
  3425. }
  3426. return migrate_caps_check(old_caps, ms->capabilities, errp);
  3427. }
  3428. static const TypeInfo migration_type = {
  3429. .name = TYPE_MIGRATION,
  3430. /*
  3431. * NOTE: TYPE_MIGRATION is not really a device, as the object is
  3432. * not created using qdev_new(), it is not attached to the qdev
  3433. * device tree, and it is never realized.
  3434. *
  3435. * TODO: Make this TYPE_OBJECT once QOM provides something like
  3436. * TYPE_DEVICE's "-global" properties.
  3437. */
  3438. .parent = TYPE_DEVICE,
  3439. .class_init = migration_class_init,
  3440. .class_size = sizeof(MigrationClass),
  3441. .instance_size = sizeof(MigrationState),
  3442. .instance_init = migration_instance_init,
  3443. .instance_finalize = migration_instance_finalize,
  3444. };
  3445. static void register_migration_types(void)
  3446. {
  3447. type_register_static(&migration_type);
  3448. }
  3449. type_init(register_migration_types);