migration.c 123 KB

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