2
0

ram.c 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804
  1. /*
  2. * QEMU System Emulator
  3. *
  4. * Copyright (c) 2003-2008 Fabrice Bellard
  5. * Copyright (c) 2011-2015 Red Hat Inc
  6. *
  7. * Authors:
  8. * Juan Quintela <quintela@redhat.com>
  9. *
  10. * Permission is hereby granted, free of charge, to any person obtaining a copy
  11. * of this software and associated documentation files (the "Software"), to deal
  12. * in the Software without restriction, including without limitation the rights
  13. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. * copies of the Software, and to permit persons to whom the Software is
  15. * furnished to do so, subject to the following conditions:
  16. *
  17. * The above copyright notice and this permission notice shall be included in
  18. * all copies or substantial portions of the Software.
  19. *
  20. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  23. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. * THE SOFTWARE.
  27. */
  28. #include "qemu/osdep.h"
  29. #include "cpu.h"
  30. #include "qemu/cutils.h"
  31. #include "qemu/bitops.h"
  32. #include "qemu/bitmap.h"
  33. #include "qemu/main-loop.h"
  34. #include "xbzrle.h"
  35. #include "ram.h"
  36. #include "migration.h"
  37. #include "migration/register.h"
  38. #include "migration/misc.h"
  39. #include "qemu-file.h"
  40. #include "postcopy-ram.h"
  41. #include "page_cache.h"
  42. #include "qemu/error-report.h"
  43. #include "qapi/error.h"
  44. #include "qapi/qapi-types-migration.h"
  45. #include "qapi/qapi-events-migration.h"
  46. #include "qapi/qmp/qerror.h"
  47. #include "trace.h"
  48. #include "exec/ram_addr.h"
  49. #include "exec/target_page.h"
  50. #include "qemu/rcu_queue.h"
  51. #include "migration/colo.h"
  52. #include "block.h"
  53. #include "sysemu/sysemu.h"
  54. #include "sysemu/cpu-throttle.h"
  55. #include "savevm.h"
  56. #include "qemu/iov.h"
  57. #include "multifd.h"
  58. /***********************************************************/
  59. /* ram save/restore */
  60. /* RAM_SAVE_FLAG_ZERO used to be named RAM_SAVE_FLAG_COMPRESS, it
  61. * worked for pages that where filled with the same char. We switched
  62. * it to only search for the zero value. And to avoid confusion with
  63. * RAM_SSAVE_FLAG_COMPRESS_PAGE just rename it.
  64. */
  65. #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
  66. #define RAM_SAVE_FLAG_ZERO 0x02
  67. #define RAM_SAVE_FLAG_MEM_SIZE 0x04
  68. #define RAM_SAVE_FLAG_PAGE 0x08
  69. #define RAM_SAVE_FLAG_EOS 0x10
  70. #define RAM_SAVE_FLAG_CONTINUE 0x20
  71. #define RAM_SAVE_FLAG_XBZRLE 0x40
  72. /* 0x80 is reserved in migration.h start with 0x100 next */
  73. #define RAM_SAVE_FLAG_COMPRESS_PAGE 0x100
  74. static inline bool is_zero_range(uint8_t *p, uint64_t size)
  75. {
  76. return buffer_is_zero(p, size);
  77. }
  78. XBZRLECacheStats xbzrle_counters;
  79. /* struct contains XBZRLE cache and a static page
  80. used by the compression */
  81. static struct {
  82. /* buffer used for XBZRLE encoding */
  83. uint8_t *encoded_buf;
  84. /* buffer for storing page content */
  85. uint8_t *current_buf;
  86. /* Cache for XBZRLE, Protected by lock. */
  87. PageCache *cache;
  88. QemuMutex lock;
  89. /* it will store a page full of zeros */
  90. uint8_t *zero_target_page;
  91. /* buffer used for XBZRLE decoding */
  92. uint8_t *decoded_buf;
  93. } XBZRLE;
  94. static void XBZRLE_cache_lock(void)
  95. {
  96. if (migrate_use_xbzrle())
  97. qemu_mutex_lock(&XBZRLE.lock);
  98. }
  99. static void XBZRLE_cache_unlock(void)
  100. {
  101. if (migrate_use_xbzrle())
  102. qemu_mutex_unlock(&XBZRLE.lock);
  103. }
  104. /**
  105. * xbzrle_cache_resize: resize the xbzrle cache
  106. *
  107. * This function is called from qmp_migrate_set_cache_size in main
  108. * thread, possibly while a migration is in progress. A running
  109. * migration may be using the cache and might finish during this call,
  110. * hence changes to the cache are protected by XBZRLE.lock().
  111. *
  112. * Returns 0 for success or -1 for error
  113. *
  114. * @new_size: new cache size
  115. * @errp: set *errp if the check failed, with reason
  116. */
  117. int xbzrle_cache_resize(int64_t new_size, Error **errp)
  118. {
  119. PageCache *new_cache;
  120. int64_t ret = 0;
  121. /* Check for truncation */
  122. if (new_size != (size_t)new_size) {
  123. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
  124. "exceeding address space");
  125. return -1;
  126. }
  127. if (new_size == migrate_xbzrle_cache_size()) {
  128. /* nothing to do */
  129. return 0;
  130. }
  131. XBZRLE_cache_lock();
  132. if (XBZRLE.cache != NULL) {
  133. new_cache = cache_init(new_size, TARGET_PAGE_SIZE, errp);
  134. if (!new_cache) {
  135. ret = -1;
  136. goto out;
  137. }
  138. cache_fini(XBZRLE.cache);
  139. XBZRLE.cache = new_cache;
  140. }
  141. out:
  142. XBZRLE_cache_unlock();
  143. return ret;
  144. }
  145. static bool ramblock_is_ignored(RAMBlock *block)
  146. {
  147. return !qemu_ram_is_migratable(block) ||
  148. (migrate_ignore_shared() && qemu_ram_is_shared(block));
  149. }
  150. /* Should be holding either ram_list.mutex, or the RCU lock. */
  151. #define RAMBLOCK_FOREACH_NOT_IGNORED(block) \
  152. INTERNAL_RAMBLOCK_FOREACH(block) \
  153. if (ramblock_is_ignored(block)) {} else
  154. #define RAMBLOCK_FOREACH_MIGRATABLE(block) \
  155. INTERNAL_RAMBLOCK_FOREACH(block) \
  156. if (!qemu_ram_is_migratable(block)) {} else
  157. #undef RAMBLOCK_FOREACH
  158. int foreach_not_ignored_block(RAMBlockIterFunc func, void *opaque)
  159. {
  160. RAMBlock *block;
  161. int ret = 0;
  162. RCU_READ_LOCK_GUARD();
  163. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  164. ret = func(block, opaque);
  165. if (ret) {
  166. break;
  167. }
  168. }
  169. return ret;
  170. }
  171. static void ramblock_recv_map_init(void)
  172. {
  173. RAMBlock *rb;
  174. RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
  175. assert(!rb->receivedmap);
  176. rb->receivedmap = bitmap_new(rb->max_length >> qemu_target_page_bits());
  177. }
  178. }
  179. int ramblock_recv_bitmap_test(RAMBlock *rb, void *host_addr)
  180. {
  181. return test_bit(ramblock_recv_bitmap_offset(host_addr, rb),
  182. rb->receivedmap);
  183. }
  184. bool ramblock_recv_bitmap_test_byte_offset(RAMBlock *rb, uint64_t byte_offset)
  185. {
  186. return test_bit(byte_offset >> TARGET_PAGE_BITS, rb->receivedmap);
  187. }
  188. void ramblock_recv_bitmap_set(RAMBlock *rb, void *host_addr)
  189. {
  190. set_bit_atomic(ramblock_recv_bitmap_offset(host_addr, rb), rb->receivedmap);
  191. }
  192. void ramblock_recv_bitmap_set_range(RAMBlock *rb, void *host_addr,
  193. size_t nr)
  194. {
  195. bitmap_set_atomic(rb->receivedmap,
  196. ramblock_recv_bitmap_offset(host_addr, rb),
  197. nr);
  198. }
  199. #define RAMBLOCK_RECV_BITMAP_ENDING (0x0123456789abcdefULL)
  200. /*
  201. * Format: bitmap_size (8 bytes) + whole_bitmap (N bytes).
  202. *
  203. * Returns >0 if success with sent bytes, or <0 if error.
  204. */
  205. int64_t ramblock_recv_bitmap_send(QEMUFile *file,
  206. const char *block_name)
  207. {
  208. RAMBlock *block = qemu_ram_block_by_name(block_name);
  209. unsigned long *le_bitmap, nbits;
  210. uint64_t size;
  211. if (!block) {
  212. error_report("%s: invalid block name: %s", __func__, block_name);
  213. return -1;
  214. }
  215. nbits = block->used_length >> TARGET_PAGE_BITS;
  216. /*
  217. * Make sure the tmp bitmap buffer is big enough, e.g., on 32bit
  218. * machines we may need 4 more bytes for padding (see below
  219. * comment). So extend it a bit before hand.
  220. */
  221. le_bitmap = bitmap_new(nbits + BITS_PER_LONG);
  222. /*
  223. * Always use little endian when sending the bitmap. This is
  224. * required that when source and destination VMs are not using the
  225. * same endianess. (Note: big endian won't work.)
  226. */
  227. bitmap_to_le(le_bitmap, block->receivedmap, nbits);
  228. /* Size of the bitmap, in bytes */
  229. size = DIV_ROUND_UP(nbits, 8);
  230. /*
  231. * size is always aligned to 8 bytes for 64bit machines, but it
  232. * may not be true for 32bit machines. We need this padding to
  233. * make sure the migration can survive even between 32bit and
  234. * 64bit machines.
  235. */
  236. size = ROUND_UP(size, 8);
  237. qemu_put_be64(file, size);
  238. qemu_put_buffer(file, (const uint8_t *)le_bitmap, size);
  239. /*
  240. * Mark as an end, in case the middle part is screwed up due to
  241. * some "misterious" reason.
  242. */
  243. qemu_put_be64(file, RAMBLOCK_RECV_BITMAP_ENDING);
  244. qemu_fflush(file);
  245. g_free(le_bitmap);
  246. if (qemu_file_get_error(file)) {
  247. return qemu_file_get_error(file);
  248. }
  249. return size + sizeof(size);
  250. }
  251. /*
  252. * An outstanding page request, on the source, having been received
  253. * and queued
  254. */
  255. struct RAMSrcPageRequest {
  256. RAMBlock *rb;
  257. hwaddr offset;
  258. hwaddr len;
  259. QSIMPLEQ_ENTRY(RAMSrcPageRequest) next_req;
  260. };
  261. /* State of RAM for migration */
  262. struct RAMState {
  263. /* QEMUFile used for this migration */
  264. QEMUFile *f;
  265. /* Last block that we have visited searching for dirty pages */
  266. RAMBlock *last_seen_block;
  267. /* Last block from where we have sent data */
  268. RAMBlock *last_sent_block;
  269. /* Last dirty target page we have sent */
  270. ram_addr_t last_page;
  271. /* last ram version we have seen */
  272. uint32_t last_version;
  273. /* We are in the first round */
  274. bool ram_bulk_stage;
  275. /* The free page optimization is enabled */
  276. bool fpo_enabled;
  277. /* How many times we have dirty too many pages */
  278. int dirty_rate_high_cnt;
  279. /* these variables are used for bitmap sync */
  280. /* last time we did a full bitmap_sync */
  281. int64_t time_last_bitmap_sync;
  282. /* bytes transferred at start_time */
  283. uint64_t bytes_xfer_prev;
  284. /* number of dirty pages since start_time */
  285. uint64_t num_dirty_pages_period;
  286. /* xbzrle misses since the beginning of the period */
  287. uint64_t xbzrle_cache_miss_prev;
  288. /* Amount of xbzrle pages since the beginning of the period */
  289. uint64_t xbzrle_pages_prev;
  290. /* Amount of xbzrle encoded bytes since the beginning of the period */
  291. uint64_t xbzrle_bytes_prev;
  292. /* compression statistics since the beginning of the period */
  293. /* amount of count that no free thread to compress data */
  294. uint64_t compress_thread_busy_prev;
  295. /* amount bytes after compression */
  296. uint64_t compressed_size_prev;
  297. /* amount of compressed pages */
  298. uint64_t compress_pages_prev;
  299. /* total handled target pages at the beginning of period */
  300. uint64_t target_page_count_prev;
  301. /* total handled target pages since start */
  302. uint64_t target_page_count;
  303. /* number of dirty bits in the bitmap */
  304. uint64_t migration_dirty_pages;
  305. /* Protects modification of the bitmap and migration dirty pages */
  306. QemuMutex bitmap_mutex;
  307. /* The RAMBlock used in the last src_page_requests */
  308. RAMBlock *last_req_rb;
  309. /* Queue of outstanding page requests from the destination */
  310. QemuMutex src_page_req_mutex;
  311. QSIMPLEQ_HEAD(, RAMSrcPageRequest) src_page_requests;
  312. };
  313. typedef struct RAMState RAMState;
  314. static RAMState *ram_state;
  315. static NotifierWithReturnList precopy_notifier_list;
  316. void precopy_infrastructure_init(void)
  317. {
  318. notifier_with_return_list_init(&precopy_notifier_list);
  319. }
  320. void precopy_add_notifier(NotifierWithReturn *n)
  321. {
  322. notifier_with_return_list_add(&precopy_notifier_list, n);
  323. }
  324. void precopy_remove_notifier(NotifierWithReturn *n)
  325. {
  326. notifier_with_return_remove(n);
  327. }
  328. int precopy_notify(PrecopyNotifyReason reason, Error **errp)
  329. {
  330. PrecopyNotifyData pnd;
  331. pnd.reason = reason;
  332. pnd.errp = errp;
  333. return notifier_with_return_list_notify(&precopy_notifier_list, &pnd);
  334. }
  335. void precopy_enable_free_page_optimization(void)
  336. {
  337. if (!ram_state) {
  338. return;
  339. }
  340. ram_state->fpo_enabled = true;
  341. }
  342. uint64_t ram_bytes_remaining(void)
  343. {
  344. return ram_state ? (ram_state->migration_dirty_pages * TARGET_PAGE_SIZE) :
  345. 0;
  346. }
  347. MigrationStats ram_counters;
  348. /* used by the search for pages to send */
  349. struct PageSearchStatus {
  350. /* Current block being searched */
  351. RAMBlock *block;
  352. /* Current page to search from */
  353. unsigned long page;
  354. /* Set once we wrap around */
  355. bool complete_round;
  356. };
  357. typedef struct PageSearchStatus PageSearchStatus;
  358. CompressionStats compression_counters;
  359. struct CompressParam {
  360. bool done;
  361. bool quit;
  362. bool zero_page;
  363. QEMUFile *file;
  364. QemuMutex mutex;
  365. QemuCond cond;
  366. RAMBlock *block;
  367. ram_addr_t offset;
  368. /* internally used fields */
  369. z_stream stream;
  370. uint8_t *originbuf;
  371. };
  372. typedef struct CompressParam CompressParam;
  373. struct DecompressParam {
  374. bool done;
  375. bool quit;
  376. QemuMutex mutex;
  377. QemuCond cond;
  378. void *des;
  379. uint8_t *compbuf;
  380. int len;
  381. z_stream stream;
  382. };
  383. typedef struct DecompressParam DecompressParam;
  384. static CompressParam *comp_param;
  385. static QemuThread *compress_threads;
  386. /* comp_done_cond is used to wake up the migration thread when
  387. * one of the compression threads has finished the compression.
  388. * comp_done_lock is used to co-work with comp_done_cond.
  389. */
  390. static QemuMutex comp_done_lock;
  391. static QemuCond comp_done_cond;
  392. /* The empty QEMUFileOps will be used by file in CompressParam */
  393. static const QEMUFileOps empty_ops = { };
  394. static QEMUFile *decomp_file;
  395. static DecompressParam *decomp_param;
  396. static QemuThread *decompress_threads;
  397. static QemuMutex decomp_done_lock;
  398. static QemuCond decomp_done_cond;
  399. static bool do_compress_ram_page(QEMUFile *f, z_stream *stream, RAMBlock *block,
  400. ram_addr_t offset, uint8_t *source_buf);
  401. static void *do_data_compress(void *opaque)
  402. {
  403. CompressParam *param = opaque;
  404. RAMBlock *block;
  405. ram_addr_t offset;
  406. bool zero_page;
  407. qemu_mutex_lock(&param->mutex);
  408. while (!param->quit) {
  409. if (param->block) {
  410. block = param->block;
  411. offset = param->offset;
  412. param->block = NULL;
  413. qemu_mutex_unlock(&param->mutex);
  414. zero_page = do_compress_ram_page(param->file, &param->stream,
  415. block, offset, param->originbuf);
  416. qemu_mutex_lock(&comp_done_lock);
  417. param->done = true;
  418. param->zero_page = zero_page;
  419. qemu_cond_signal(&comp_done_cond);
  420. qemu_mutex_unlock(&comp_done_lock);
  421. qemu_mutex_lock(&param->mutex);
  422. } else {
  423. qemu_cond_wait(&param->cond, &param->mutex);
  424. }
  425. }
  426. qemu_mutex_unlock(&param->mutex);
  427. return NULL;
  428. }
  429. static void compress_threads_save_cleanup(void)
  430. {
  431. int i, thread_count;
  432. if (!migrate_use_compression() || !comp_param) {
  433. return;
  434. }
  435. thread_count = migrate_compress_threads();
  436. for (i = 0; i < thread_count; i++) {
  437. /*
  438. * we use it as a indicator which shows if the thread is
  439. * properly init'd or not
  440. */
  441. if (!comp_param[i].file) {
  442. break;
  443. }
  444. qemu_mutex_lock(&comp_param[i].mutex);
  445. comp_param[i].quit = true;
  446. qemu_cond_signal(&comp_param[i].cond);
  447. qemu_mutex_unlock(&comp_param[i].mutex);
  448. qemu_thread_join(compress_threads + i);
  449. qemu_mutex_destroy(&comp_param[i].mutex);
  450. qemu_cond_destroy(&comp_param[i].cond);
  451. deflateEnd(&comp_param[i].stream);
  452. g_free(comp_param[i].originbuf);
  453. qemu_fclose(comp_param[i].file);
  454. comp_param[i].file = NULL;
  455. }
  456. qemu_mutex_destroy(&comp_done_lock);
  457. qemu_cond_destroy(&comp_done_cond);
  458. g_free(compress_threads);
  459. g_free(comp_param);
  460. compress_threads = NULL;
  461. comp_param = NULL;
  462. }
  463. static int compress_threads_save_setup(void)
  464. {
  465. int i, thread_count;
  466. if (!migrate_use_compression()) {
  467. return 0;
  468. }
  469. thread_count = migrate_compress_threads();
  470. compress_threads = g_new0(QemuThread, thread_count);
  471. comp_param = g_new0(CompressParam, thread_count);
  472. qemu_cond_init(&comp_done_cond);
  473. qemu_mutex_init(&comp_done_lock);
  474. for (i = 0; i < thread_count; i++) {
  475. comp_param[i].originbuf = g_try_malloc(TARGET_PAGE_SIZE);
  476. if (!comp_param[i].originbuf) {
  477. goto exit;
  478. }
  479. if (deflateInit(&comp_param[i].stream,
  480. migrate_compress_level()) != Z_OK) {
  481. g_free(comp_param[i].originbuf);
  482. goto exit;
  483. }
  484. /* comp_param[i].file is just used as a dummy buffer to save data,
  485. * set its ops to empty.
  486. */
  487. comp_param[i].file = qemu_fopen_ops(NULL, &empty_ops);
  488. comp_param[i].done = true;
  489. comp_param[i].quit = false;
  490. qemu_mutex_init(&comp_param[i].mutex);
  491. qemu_cond_init(&comp_param[i].cond);
  492. qemu_thread_create(compress_threads + i, "compress",
  493. do_data_compress, comp_param + i,
  494. QEMU_THREAD_JOINABLE);
  495. }
  496. return 0;
  497. exit:
  498. compress_threads_save_cleanup();
  499. return -1;
  500. }
  501. /**
  502. * save_page_header: write page header to wire
  503. *
  504. * If this is the 1st block, it also writes the block identification
  505. *
  506. * Returns the number of bytes written
  507. *
  508. * @f: QEMUFile where to send the data
  509. * @block: block that contains the page we want to send
  510. * @offset: offset inside the block for the page
  511. * in the lower bits, it contains flags
  512. */
  513. static size_t save_page_header(RAMState *rs, QEMUFile *f, RAMBlock *block,
  514. ram_addr_t offset)
  515. {
  516. size_t size, len;
  517. if (block == rs->last_sent_block) {
  518. offset |= RAM_SAVE_FLAG_CONTINUE;
  519. }
  520. qemu_put_be64(f, offset);
  521. size = 8;
  522. if (!(offset & RAM_SAVE_FLAG_CONTINUE)) {
  523. len = strlen(block->idstr);
  524. qemu_put_byte(f, len);
  525. qemu_put_buffer(f, (uint8_t *)block->idstr, len);
  526. size += 1 + len;
  527. rs->last_sent_block = block;
  528. }
  529. return size;
  530. }
  531. /**
  532. * mig_throttle_guest_down: throotle down the guest
  533. *
  534. * Reduce amount of guest cpu execution to hopefully slow down memory
  535. * writes. If guest dirty memory rate is reduced below the rate at
  536. * which we can transfer pages to the destination then we should be
  537. * able to complete migration. Some workloads dirty memory way too
  538. * fast and will not effectively converge, even with auto-converge.
  539. */
  540. static void mig_throttle_guest_down(uint64_t bytes_dirty_period,
  541. uint64_t bytes_dirty_threshold)
  542. {
  543. MigrationState *s = migrate_get_current();
  544. uint64_t pct_initial = s->parameters.cpu_throttle_initial;
  545. uint64_t pct_increment = s->parameters.cpu_throttle_increment;
  546. bool pct_tailslow = s->parameters.cpu_throttle_tailslow;
  547. int pct_max = s->parameters.max_cpu_throttle;
  548. uint64_t throttle_now = cpu_throttle_get_percentage();
  549. uint64_t cpu_now, cpu_ideal, throttle_inc;
  550. /* We have not started throttling yet. Let's start it. */
  551. if (!cpu_throttle_active()) {
  552. cpu_throttle_set(pct_initial);
  553. } else {
  554. /* Throttling already on, just increase the rate */
  555. if (!pct_tailslow) {
  556. throttle_inc = pct_increment;
  557. } else {
  558. /* Compute the ideal CPU percentage used by Guest, which may
  559. * make the dirty rate match the dirty rate threshold. */
  560. cpu_now = 100 - throttle_now;
  561. cpu_ideal = cpu_now * (bytes_dirty_threshold * 1.0 /
  562. bytes_dirty_period);
  563. throttle_inc = MIN(cpu_now - cpu_ideal, pct_increment);
  564. }
  565. cpu_throttle_set(MIN(throttle_now + throttle_inc, pct_max));
  566. }
  567. }
  568. /**
  569. * xbzrle_cache_zero_page: insert a zero page in the XBZRLE cache
  570. *
  571. * @rs: current RAM state
  572. * @current_addr: address for the zero page
  573. *
  574. * Update the xbzrle cache to reflect a page that's been sent as all 0.
  575. * The important thing is that a stale (not-yet-0'd) page be replaced
  576. * by the new data.
  577. * As a bonus, if the page wasn't in the cache it gets added so that
  578. * when a small write is made into the 0'd page it gets XBZRLE sent.
  579. */
  580. static void xbzrle_cache_zero_page(RAMState *rs, ram_addr_t current_addr)
  581. {
  582. if (rs->ram_bulk_stage || !migrate_use_xbzrle()) {
  583. return;
  584. }
  585. /* We don't care if this fails to allocate a new cache page
  586. * as long as it updated an old one */
  587. cache_insert(XBZRLE.cache, current_addr, XBZRLE.zero_target_page,
  588. ram_counters.dirty_sync_count);
  589. }
  590. #define ENCODING_FLAG_XBZRLE 0x1
  591. /**
  592. * save_xbzrle_page: compress and send current page
  593. *
  594. * Returns: 1 means that we wrote the page
  595. * 0 means that page is identical to the one already sent
  596. * -1 means that xbzrle would be longer than normal
  597. *
  598. * @rs: current RAM state
  599. * @current_data: pointer to the address of the page contents
  600. * @current_addr: addr of the page
  601. * @block: block that contains the page we want to send
  602. * @offset: offset inside the block for the page
  603. * @last_stage: if we are at the completion stage
  604. */
  605. static int save_xbzrle_page(RAMState *rs, uint8_t **current_data,
  606. ram_addr_t current_addr, RAMBlock *block,
  607. ram_addr_t offset, bool last_stage)
  608. {
  609. int encoded_len = 0, bytes_xbzrle;
  610. uint8_t *prev_cached_page;
  611. if (!cache_is_cached(XBZRLE.cache, current_addr,
  612. ram_counters.dirty_sync_count)) {
  613. xbzrle_counters.cache_miss++;
  614. if (!last_stage) {
  615. if (cache_insert(XBZRLE.cache, current_addr, *current_data,
  616. ram_counters.dirty_sync_count) == -1) {
  617. return -1;
  618. } else {
  619. /* update *current_data when the page has been
  620. inserted into cache */
  621. *current_data = get_cached_data(XBZRLE.cache, current_addr);
  622. }
  623. }
  624. return -1;
  625. }
  626. /*
  627. * Reaching here means the page has hit the xbzrle cache, no matter what
  628. * encoding result it is (normal encoding, overflow or skipping the page),
  629. * count the page as encoded. This is used to caculate the encoding rate.
  630. *
  631. * Example: 2 pages (8KB) being encoded, first page encoding generates 2KB,
  632. * 2nd page turns out to be skipped (i.e. no new bytes written to the
  633. * page), the overall encoding rate will be 8KB / 2KB = 4, which has the
  634. * skipped page included. In this way, the encoding rate can tell if the
  635. * guest page is good for xbzrle encoding.
  636. */
  637. xbzrle_counters.pages++;
  638. prev_cached_page = get_cached_data(XBZRLE.cache, current_addr);
  639. /* save current buffer into memory */
  640. memcpy(XBZRLE.current_buf, *current_data, TARGET_PAGE_SIZE);
  641. /* XBZRLE encoding (if there is no overflow) */
  642. encoded_len = xbzrle_encode_buffer(prev_cached_page, XBZRLE.current_buf,
  643. TARGET_PAGE_SIZE, XBZRLE.encoded_buf,
  644. TARGET_PAGE_SIZE);
  645. /*
  646. * Update the cache contents, so that it corresponds to the data
  647. * sent, in all cases except where we skip the page.
  648. */
  649. if (!last_stage && encoded_len != 0) {
  650. memcpy(prev_cached_page, XBZRLE.current_buf, TARGET_PAGE_SIZE);
  651. /*
  652. * In the case where we couldn't compress, ensure that the caller
  653. * sends the data from the cache, since the guest might have
  654. * changed the RAM since we copied it.
  655. */
  656. *current_data = prev_cached_page;
  657. }
  658. if (encoded_len == 0) {
  659. trace_save_xbzrle_page_skipping();
  660. return 0;
  661. } else if (encoded_len == -1) {
  662. trace_save_xbzrle_page_overflow();
  663. xbzrle_counters.overflow++;
  664. xbzrle_counters.bytes += TARGET_PAGE_SIZE;
  665. return -1;
  666. }
  667. /* Send XBZRLE based compressed page */
  668. bytes_xbzrle = save_page_header(rs, rs->f, block,
  669. offset | RAM_SAVE_FLAG_XBZRLE);
  670. qemu_put_byte(rs->f, ENCODING_FLAG_XBZRLE);
  671. qemu_put_be16(rs->f, encoded_len);
  672. qemu_put_buffer(rs->f, XBZRLE.encoded_buf, encoded_len);
  673. bytes_xbzrle += encoded_len + 1 + 2;
  674. /*
  675. * Like compressed_size (please see update_compress_thread_counts),
  676. * the xbzrle encoded bytes don't count the 8 byte header with
  677. * RAM_SAVE_FLAG_CONTINUE.
  678. */
  679. xbzrle_counters.bytes += bytes_xbzrle - 8;
  680. ram_counters.transferred += bytes_xbzrle;
  681. return 1;
  682. }
  683. /**
  684. * migration_bitmap_find_dirty: find the next dirty page from start
  685. *
  686. * Returns the page offset within memory region of the start of a dirty page
  687. *
  688. * @rs: current RAM state
  689. * @rb: RAMBlock where to search for dirty pages
  690. * @start: page where we start the search
  691. */
  692. static inline
  693. unsigned long migration_bitmap_find_dirty(RAMState *rs, RAMBlock *rb,
  694. unsigned long start)
  695. {
  696. unsigned long size = rb->used_length >> TARGET_PAGE_BITS;
  697. unsigned long *bitmap = rb->bmap;
  698. unsigned long next;
  699. if (ramblock_is_ignored(rb)) {
  700. return size;
  701. }
  702. /*
  703. * When the free page optimization is enabled, we need to check the bitmap
  704. * to send the non-free pages rather than all the pages in the bulk stage.
  705. */
  706. if (!rs->fpo_enabled && rs->ram_bulk_stage && start > 0) {
  707. next = start + 1;
  708. } else {
  709. next = find_next_bit(bitmap, size, start);
  710. }
  711. return next;
  712. }
  713. static inline bool migration_bitmap_clear_dirty(RAMState *rs,
  714. RAMBlock *rb,
  715. unsigned long page)
  716. {
  717. bool ret;
  718. qemu_mutex_lock(&rs->bitmap_mutex);
  719. /*
  720. * Clear dirty bitmap if needed. This _must_ be called before we
  721. * send any of the page in the chunk because we need to make sure
  722. * we can capture further page content changes when we sync dirty
  723. * log the next time. So as long as we are going to send any of
  724. * the page in the chunk we clear the remote dirty bitmap for all.
  725. * Clearing it earlier won't be a problem, but too late will.
  726. */
  727. if (rb->clear_bmap && clear_bmap_test_and_clear(rb, page)) {
  728. uint8_t shift = rb->clear_bmap_shift;
  729. hwaddr size = 1ULL << (TARGET_PAGE_BITS + shift);
  730. hwaddr start = (((ram_addr_t)page) << TARGET_PAGE_BITS) & (-size);
  731. /*
  732. * CLEAR_BITMAP_SHIFT_MIN should always guarantee this... this
  733. * can make things easier sometimes since then start address
  734. * of the small chunk will always be 64 pages aligned so the
  735. * bitmap will always be aligned to unsigned long. We should
  736. * even be able to remove this restriction but I'm simply
  737. * keeping it.
  738. */
  739. assert(shift >= 6);
  740. trace_migration_bitmap_clear_dirty(rb->idstr, start, size, page);
  741. memory_region_clear_dirty_bitmap(rb->mr, start, size);
  742. }
  743. ret = test_and_clear_bit(page, rb->bmap);
  744. if (ret) {
  745. rs->migration_dirty_pages--;
  746. }
  747. qemu_mutex_unlock(&rs->bitmap_mutex);
  748. return ret;
  749. }
  750. /* Called with RCU critical section */
  751. static void ramblock_sync_dirty_bitmap(RAMState *rs, RAMBlock *rb)
  752. {
  753. uint64_t new_dirty_pages =
  754. cpu_physical_memory_sync_dirty_bitmap(rb, 0, rb->used_length);
  755. rs->migration_dirty_pages += new_dirty_pages;
  756. rs->num_dirty_pages_period += new_dirty_pages;
  757. }
  758. /**
  759. * ram_pagesize_summary: calculate all the pagesizes of a VM
  760. *
  761. * Returns a summary bitmap of the page sizes of all RAMBlocks
  762. *
  763. * For VMs with just normal pages this is equivalent to the host page
  764. * size. If it's got some huge pages then it's the OR of all the
  765. * different page sizes.
  766. */
  767. uint64_t ram_pagesize_summary(void)
  768. {
  769. RAMBlock *block;
  770. uint64_t summary = 0;
  771. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  772. summary |= block->page_size;
  773. }
  774. return summary;
  775. }
  776. uint64_t ram_get_total_transferred_pages(void)
  777. {
  778. return ram_counters.normal + ram_counters.duplicate +
  779. compression_counters.pages + xbzrle_counters.pages;
  780. }
  781. static void migration_update_rates(RAMState *rs, int64_t end_time)
  782. {
  783. uint64_t page_count = rs->target_page_count - rs->target_page_count_prev;
  784. double compressed_size;
  785. /* calculate period counters */
  786. ram_counters.dirty_pages_rate = rs->num_dirty_pages_period * 1000
  787. / (end_time - rs->time_last_bitmap_sync);
  788. if (!page_count) {
  789. return;
  790. }
  791. if (migrate_use_xbzrle()) {
  792. double encoded_size, unencoded_size;
  793. xbzrle_counters.cache_miss_rate = (double)(xbzrle_counters.cache_miss -
  794. rs->xbzrle_cache_miss_prev) / page_count;
  795. rs->xbzrle_cache_miss_prev = xbzrle_counters.cache_miss;
  796. unencoded_size = (xbzrle_counters.pages - rs->xbzrle_pages_prev) *
  797. TARGET_PAGE_SIZE;
  798. encoded_size = xbzrle_counters.bytes - rs->xbzrle_bytes_prev;
  799. if (xbzrle_counters.pages == rs->xbzrle_pages_prev || !encoded_size) {
  800. xbzrle_counters.encoding_rate = 0;
  801. } else {
  802. xbzrle_counters.encoding_rate = unencoded_size / encoded_size;
  803. }
  804. rs->xbzrle_pages_prev = xbzrle_counters.pages;
  805. rs->xbzrle_bytes_prev = xbzrle_counters.bytes;
  806. }
  807. if (migrate_use_compression()) {
  808. compression_counters.busy_rate = (double)(compression_counters.busy -
  809. rs->compress_thread_busy_prev) / page_count;
  810. rs->compress_thread_busy_prev = compression_counters.busy;
  811. compressed_size = compression_counters.compressed_size -
  812. rs->compressed_size_prev;
  813. if (compressed_size) {
  814. double uncompressed_size = (compression_counters.pages -
  815. rs->compress_pages_prev) * TARGET_PAGE_SIZE;
  816. /* Compression-Ratio = Uncompressed-size / Compressed-size */
  817. compression_counters.compression_rate =
  818. uncompressed_size / compressed_size;
  819. rs->compress_pages_prev = compression_counters.pages;
  820. rs->compressed_size_prev = compression_counters.compressed_size;
  821. }
  822. }
  823. }
  824. static void migration_trigger_throttle(RAMState *rs)
  825. {
  826. MigrationState *s = migrate_get_current();
  827. uint64_t threshold = s->parameters.throttle_trigger_threshold;
  828. uint64_t bytes_xfer_period = ram_counters.transferred - rs->bytes_xfer_prev;
  829. uint64_t bytes_dirty_period = rs->num_dirty_pages_period * TARGET_PAGE_SIZE;
  830. uint64_t bytes_dirty_threshold = bytes_xfer_period * threshold / 100;
  831. /* During block migration the auto-converge logic incorrectly detects
  832. * that ram migration makes no progress. Avoid this by disabling the
  833. * throttling logic during the bulk phase of block migration. */
  834. if (migrate_auto_converge() && !blk_mig_bulk_active()) {
  835. /* The following detection logic can be refined later. For now:
  836. Check to see if the ratio between dirtied bytes and the approx.
  837. amount of bytes that just got transferred since the last time
  838. we were in this routine reaches the threshold. If that happens
  839. twice, start or increase throttling. */
  840. if ((bytes_dirty_period > bytes_dirty_threshold) &&
  841. (++rs->dirty_rate_high_cnt >= 2)) {
  842. trace_migration_throttle();
  843. rs->dirty_rate_high_cnt = 0;
  844. mig_throttle_guest_down(bytes_dirty_period,
  845. bytes_dirty_threshold);
  846. }
  847. }
  848. }
  849. static void migration_bitmap_sync(RAMState *rs)
  850. {
  851. RAMBlock *block;
  852. int64_t end_time;
  853. ram_counters.dirty_sync_count++;
  854. if (!rs->time_last_bitmap_sync) {
  855. rs->time_last_bitmap_sync = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
  856. }
  857. trace_migration_bitmap_sync_start();
  858. memory_global_dirty_log_sync();
  859. qemu_mutex_lock(&rs->bitmap_mutex);
  860. WITH_RCU_READ_LOCK_GUARD() {
  861. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  862. ramblock_sync_dirty_bitmap(rs, block);
  863. }
  864. ram_counters.remaining = ram_bytes_remaining();
  865. }
  866. qemu_mutex_unlock(&rs->bitmap_mutex);
  867. memory_global_after_dirty_log_sync();
  868. trace_migration_bitmap_sync_end(rs->num_dirty_pages_period);
  869. end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
  870. /* more than 1 second = 1000 millisecons */
  871. if (end_time > rs->time_last_bitmap_sync + 1000) {
  872. migration_trigger_throttle(rs);
  873. migration_update_rates(rs, end_time);
  874. rs->target_page_count_prev = rs->target_page_count;
  875. /* reset period counters */
  876. rs->time_last_bitmap_sync = end_time;
  877. rs->num_dirty_pages_period = 0;
  878. rs->bytes_xfer_prev = ram_counters.transferred;
  879. }
  880. if (migrate_use_events()) {
  881. qapi_event_send_migration_pass(ram_counters.dirty_sync_count);
  882. }
  883. }
  884. static void migration_bitmap_sync_precopy(RAMState *rs)
  885. {
  886. Error *local_err = NULL;
  887. /*
  888. * The current notifier usage is just an optimization to migration, so we
  889. * don't stop the normal migration process in the error case.
  890. */
  891. if (precopy_notify(PRECOPY_NOTIFY_BEFORE_BITMAP_SYNC, &local_err)) {
  892. error_report_err(local_err);
  893. local_err = NULL;
  894. }
  895. migration_bitmap_sync(rs);
  896. if (precopy_notify(PRECOPY_NOTIFY_AFTER_BITMAP_SYNC, &local_err)) {
  897. error_report_err(local_err);
  898. }
  899. }
  900. /**
  901. * save_zero_page_to_file: send the zero page to the file
  902. *
  903. * Returns the size of data written to the file, 0 means the page is not
  904. * a zero page
  905. *
  906. * @rs: current RAM state
  907. * @file: the file where the data is saved
  908. * @block: block that contains the page we want to send
  909. * @offset: offset inside the block for the page
  910. */
  911. static int save_zero_page_to_file(RAMState *rs, QEMUFile *file,
  912. RAMBlock *block, ram_addr_t offset)
  913. {
  914. uint8_t *p = block->host + offset;
  915. int len = 0;
  916. if (is_zero_range(p, TARGET_PAGE_SIZE)) {
  917. len += save_page_header(rs, file, block, offset | RAM_SAVE_FLAG_ZERO);
  918. qemu_put_byte(file, 0);
  919. len += 1;
  920. }
  921. return len;
  922. }
  923. /**
  924. * save_zero_page: send the zero page to the stream
  925. *
  926. * Returns the number of pages written.
  927. *
  928. * @rs: current RAM state
  929. * @block: block that contains the page we want to send
  930. * @offset: offset inside the block for the page
  931. */
  932. static int save_zero_page(RAMState *rs, RAMBlock *block, ram_addr_t offset)
  933. {
  934. int len = save_zero_page_to_file(rs, rs->f, block, offset);
  935. if (len) {
  936. ram_counters.duplicate++;
  937. ram_counters.transferred += len;
  938. return 1;
  939. }
  940. return -1;
  941. }
  942. static void ram_release_pages(const char *rbname, uint64_t offset, int pages)
  943. {
  944. if (!migrate_release_ram() || !migration_in_postcopy()) {
  945. return;
  946. }
  947. ram_discard_range(rbname, offset, ((ram_addr_t)pages) << TARGET_PAGE_BITS);
  948. }
  949. /*
  950. * @pages: the number of pages written by the control path,
  951. * < 0 - error
  952. * > 0 - number of pages written
  953. *
  954. * Return true if the pages has been saved, otherwise false is returned.
  955. */
  956. static bool control_save_page(RAMState *rs, RAMBlock *block, ram_addr_t offset,
  957. int *pages)
  958. {
  959. uint64_t bytes_xmit = 0;
  960. int ret;
  961. *pages = -1;
  962. ret = ram_control_save_page(rs->f, block->offset, offset, TARGET_PAGE_SIZE,
  963. &bytes_xmit);
  964. if (ret == RAM_SAVE_CONTROL_NOT_SUPP) {
  965. return false;
  966. }
  967. if (bytes_xmit) {
  968. ram_counters.transferred += bytes_xmit;
  969. *pages = 1;
  970. }
  971. if (ret == RAM_SAVE_CONTROL_DELAYED) {
  972. return true;
  973. }
  974. if (bytes_xmit > 0) {
  975. ram_counters.normal++;
  976. } else if (bytes_xmit == 0) {
  977. ram_counters.duplicate++;
  978. }
  979. return true;
  980. }
  981. /*
  982. * directly send the page to the stream
  983. *
  984. * Returns the number of pages written.
  985. *
  986. * @rs: current RAM state
  987. * @block: block that contains the page we want to send
  988. * @offset: offset inside the block for the page
  989. * @buf: the page to be sent
  990. * @async: send to page asyncly
  991. */
  992. static int save_normal_page(RAMState *rs, RAMBlock *block, ram_addr_t offset,
  993. uint8_t *buf, bool async)
  994. {
  995. ram_counters.transferred += save_page_header(rs, rs->f, block,
  996. offset | RAM_SAVE_FLAG_PAGE);
  997. if (async) {
  998. qemu_put_buffer_async(rs->f, buf, TARGET_PAGE_SIZE,
  999. migrate_release_ram() &
  1000. migration_in_postcopy());
  1001. } else {
  1002. qemu_put_buffer(rs->f, buf, TARGET_PAGE_SIZE);
  1003. }
  1004. ram_counters.transferred += TARGET_PAGE_SIZE;
  1005. ram_counters.normal++;
  1006. return 1;
  1007. }
  1008. /**
  1009. * ram_save_page: send the given page to the stream
  1010. *
  1011. * Returns the number of pages written.
  1012. * < 0 - error
  1013. * >=0 - Number of pages written - this might legally be 0
  1014. * if xbzrle noticed the page was the same.
  1015. *
  1016. * @rs: current RAM state
  1017. * @block: block that contains the page we want to send
  1018. * @offset: offset inside the block for the page
  1019. * @last_stage: if we are at the completion stage
  1020. */
  1021. static int ram_save_page(RAMState *rs, PageSearchStatus *pss, bool last_stage)
  1022. {
  1023. int pages = -1;
  1024. uint8_t *p;
  1025. bool send_async = true;
  1026. RAMBlock *block = pss->block;
  1027. ram_addr_t offset = ((ram_addr_t)pss->page) << TARGET_PAGE_BITS;
  1028. ram_addr_t current_addr = block->offset + offset;
  1029. p = block->host + offset;
  1030. trace_ram_save_page(block->idstr, (uint64_t)offset, p);
  1031. XBZRLE_cache_lock();
  1032. if (!rs->ram_bulk_stage && !migration_in_postcopy() &&
  1033. migrate_use_xbzrle()) {
  1034. pages = save_xbzrle_page(rs, &p, current_addr, block,
  1035. offset, last_stage);
  1036. if (!last_stage) {
  1037. /* Can't send this cached data async, since the cache page
  1038. * might get updated before it gets to the wire
  1039. */
  1040. send_async = false;
  1041. }
  1042. }
  1043. /* XBZRLE overflow or normal page */
  1044. if (pages == -1) {
  1045. pages = save_normal_page(rs, block, offset, p, send_async);
  1046. }
  1047. XBZRLE_cache_unlock();
  1048. return pages;
  1049. }
  1050. static int ram_save_multifd_page(RAMState *rs, RAMBlock *block,
  1051. ram_addr_t offset)
  1052. {
  1053. if (multifd_queue_page(rs->f, block, offset) < 0) {
  1054. return -1;
  1055. }
  1056. ram_counters.normal++;
  1057. return 1;
  1058. }
  1059. static bool do_compress_ram_page(QEMUFile *f, z_stream *stream, RAMBlock *block,
  1060. ram_addr_t offset, uint8_t *source_buf)
  1061. {
  1062. RAMState *rs = ram_state;
  1063. uint8_t *p = block->host + (offset & TARGET_PAGE_MASK);
  1064. bool zero_page = false;
  1065. int ret;
  1066. if (save_zero_page_to_file(rs, f, block, offset)) {
  1067. zero_page = true;
  1068. goto exit;
  1069. }
  1070. save_page_header(rs, f, block, offset | RAM_SAVE_FLAG_COMPRESS_PAGE);
  1071. /*
  1072. * copy it to a internal buffer to avoid it being modified by VM
  1073. * so that we can catch up the error during compression and
  1074. * decompression
  1075. */
  1076. memcpy(source_buf, p, TARGET_PAGE_SIZE);
  1077. ret = qemu_put_compression_data(f, stream, source_buf, TARGET_PAGE_SIZE);
  1078. if (ret < 0) {
  1079. qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
  1080. error_report("compressed data failed!");
  1081. return false;
  1082. }
  1083. exit:
  1084. ram_release_pages(block->idstr, offset & TARGET_PAGE_MASK, 1);
  1085. return zero_page;
  1086. }
  1087. static void
  1088. update_compress_thread_counts(const CompressParam *param, int bytes_xmit)
  1089. {
  1090. ram_counters.transferred += bytes_xmit;
  1091. if (param->zero_page) {
  1092. ram_counters.duplicate++;
  1093. return;
  1094. }
  1095. /* 8 means a header with RAM_SAVE_FLAG_CONTINUE. */
  1096. compression_counters.compressed_size += bytes_xmit - 8;
  1097. compression_counters.pages++;
  1098. }
  1099. static bool save_page_use_compression(RAMState *rs);
  1100. static void flush_compressed_data(RAMState *rs)
  1101. {
  1102. int idx, len, thread_count;
  1103. if (!save_page_use_compression(rs)) {
  1104. return;
  1105. }
  1106. thread_count = migrate_compress_threads();
  1107. qemu_mutex_lock(&comp_done_lock);
  1108. for (idx = 0; idx < thread_count; idx++) {
  1109. while (!comp_param[idx].done) {
  1110. qemu_cond_wait(&comp_done_cond, &comp_done_lock);
  1111. }
  1112. }
  1113. qemu_mutex_unlock(&comp_done_lock);
  1114. for (idx = 0; idx < thread_count; idx++) {
  1115. qemu_mutex_lock(&comp_param[idx].mutex);
  1116. if (!comp_param[idx].quit) {
  1117. len = qemu_put_qemu_file(rs->f, comp_param[idx].file);
  1118. /*
  1119. * it's safe to fetch zero_page without holding comp_done_lock
  1120. * as there is no further request submitted to the thread,
  1121. * i.e, the thread should be waiting for a request at this point.
  1122. */
  1123. update_compress_thread_counts(&comp_param[idx], len);
  1124. }
  1125. qemu_mutex_unlock(&comp_param[idx].mutex);
  1126. }
  1127. }
  1128. static inline void set_compress_params(CompressParam *param, RAMBlock *block,
  1129. ram_addr_t offset)
  1130. {
  1131. param->block = block;
  1132. param->offset = offset;
  1133. }
  1134. static int compress_page_with_multi_thread(RAMState *rs, RAMBlock *block,
  1135. ram_addr_t offset)
  1136. {
  1137. int idx, thread_count, bytes_xmit = -1, pages = -1;
  1138. bool wait = migrate_compress_wait_thread();
  1139. thread_count = migrate_compress_threads();
  1140. qemu_mutex_lock(&comp_done_lock);
  1141. retry:
  1142. for (idx = 0; idx < thread_count; idx++) {
  1143. if (comp_param[idx].done) {
  1144. comp_param[idx].done = false;
  1145. bytes_xmit = qemu_put_qemu_file(rs->f, comp_param[idx].file);
  1146. qemu_mutex_lock(&comp_param[idx].mutex);
  1147. set_compress_params(&comp_param[idx], block, offset);
  1148. qemu_cond_signal(&comp_param[idx].cond);
  1149. qemu_mutex_unlock(&comp_param[idx].mutex);
  1150. pages = 1;
  1151. update_compress_thread_counts(&comp_param[idx], bytes_xmit);
  1152. break;
  1153. }
  1154. }
  1155. /*
  1156. * wait for the free thread if the user specifies 'compress-wait-thread',
  1157. * otherwise we will post the page out in the main thread as normal page.
  1158. */
  1159. if (pages < 0 && wait) {
  1160. qemu_cond_wait(&comp_done_cond, &comp_done_lock);
  1161. goto retry;
  1162. }
  1163. qemu_mutex_unlock(&comp_done_lock);
  1164. return pages;
  1165. }
  1166. /**
  1167. * find_dirty_block: find the next dirty page and update any state
  1168. * associated with the search process.
  1169. *
  1170. * Returns true if a page is found
  1171. *
  1172. * @rs: current RAM state
  1173. * @pss: data about the state of the current dirty page scan
  1174. * @again: set to false if the search has scanned the whole of RAM
  1175. */
  1176. static bool find_dirty_block(RAMState *rs, PageSearchStatus *pss, bool *again)
  1177. {
  1178. pss->page = migration_bitmap_find_dirty(rs, pss->block, pss->page);
  1179. if (pss->complete_round && pss->block == rs->last_seen_block &&
  1180. pss->page >= rs->last_page) {
  1181. /*
  1182. * We've been once around the RAM and haven't found anything.
  1183. * Give up.
  1184. */
  1185. *again = false;
  1186. return false;
  1187. }
  1188. if ((((ram_addr_t)pss->page) << TARGET_PAGE_BITS)
  1189. >= pss->block->used_length) {
  1190. /* Didn't find anything in this RAM Block */
  1191. pss->page = 0;
  1192. pss->block = QLIST_NEXT_RCU(pss->block, next);
  1193. if (!pss->block) {
  1194. /*
  1195. * If memory migration starts over, we will meet a dirtied page
  1196. * which may still exists in compression threads's ring, so we
  1197. * should flush the compressed data to make sure the new page
  1198. * is not overwritten by the old one in the destination.
  1199. *
  1200. * Also If xbzrle is on, stop using the data compression at this
  1201. * point. In theory, xbzrle can do better than compression.
  1202. */
  1203. flush_compressed_data(rs);
  1204. /* Hit the end of the list */
  1205. pss->block = QLIST_FIRST_RCU(&ram_list.blocks);
  1206. /* Flag that we've looped */
  1207. pss->complete_round = true;
  1208. rs->ram_bulk_stage = false;
  1209. }
  1210. /* Didn't find anything this time, but try again on the new block */
  1211. *again = true;
  1212. return false;
  1213. } else {
  1214. /* Can go around again, but... */
  1215. *again = true;
  1216. /* We've found something so probably don't need to */
  1217. return true;
  1218. }
  1219. }
  1220. /**
  1221. * unqueue_page: gets a page of the queue
  1222. *
  1223. * Helper for 'get_queued_page' - gets a page off the queue
  1224. *
  1225. * Returns the block of the page (or NULL if none available)
  1226. *
  1227. * @rs: current RAM state
  1228. * @offset: used to return the offset within the RAMBlock
  1229. */
  1230. static RAMBlock *unqueue_page(RAMState *rs, ram_addr_t *offset)
  1231. {
  1232. RAMBlock *block = NULL;
  1233. if (QSIMPLEQ_EMPTY_ATOMIC(&rs->src_page_requests)) {
  1234. return NULL;
  1235. }
  1236. QEMU_LOCK_GUARD(&rs->src_page_req_mutex);
  1237. if (!QSIMPLEQ_EMPTY(&rs->src_page_requests)) {
  1238. struct RAMSrcPageRequest *entry =
  1239. QSIMPLEQ_FIRST(&rs->src_page_requests);
  1240. block = entry->rb;
  1241. *offset = entry->offset;
  1242. if (entry->len > TARGET_PAGE_SIZE) {
  1243. entry->len -= TARGET_PAGE_SIZE;
  1244. entry->offset += TARGET_PAGE_SIZE;
  1245. } else {
  1246. memory_region_unref(block->mr);
  1247. QSIMPLEQ_REMOVE_HEAD(&rs->src_page_requests, next_req);
  1248. g_free(entry);
  1249. migration_consume_urgent_request();
  1250. }
  1251. }
  1252. return block;
  1253. }
  1254. /**
  1255. * get_queued_page: unqueue a page from the postcopy requests
  1256. *
  1257. * Skips pages that are already sent (!dirty)
  1258. *
  1259. * Returns true if a queued page is found
  1260. *
  1261. * @rs: current RAM state
  1262. * @pss: data about the state of the current dirty page scan
  1263. */
  1264. static bool get_queued_page(RAMState *rs, PageSearchStatus *pss)
  1265. {
  1266. RAMBlock *block;
  1267. ram_addr_t offset;
  1268. bool dirty;
  1269. do {
  1270. block = unqueue_page(rs, &offset);
  1271. /*
  1272. * We're sending this page, and since it's postcopy nothing else
  1273. * will dirty it, and we must make sure it doesn't get sent again
  1274. * even if this queue request was received after the background
  1275. * search already sent it.
  1276. */
  1277. if (block) {
  1278. unsigned long page;
  1279. page = offset >> TARGET_PAGE_BITS;
  1280. dirty = test_bit(page, block->bmap);
  1281. if (!dirty) {
  1282. trace_get_queued_page_not_dirty(block->idstr, (uint64_t)offset,
  1283. page);
  1284. } else {
  1285. trace_get_queued_page(block->idstr, (uint64_t)offset, page);
  1286. }
  1287. }
  1288. } while (block && !dirty);
  1289. if (block) {
  1290. /*
  1291. * As soon as we start servicing pages out of order, then we have
  1292. * to kill the bulk stage, since the bulk stage assumes
  1293. * in (migration_bitmap_find_and_reset_dirty) that every page is
  1294. * dirty, that's no longer true.
  1295. */
  1296. rs->ram_bulk_stage = false;
  1297. /*
  1298. * We want the background search to continue from the queued page
  1299. * since the guest is likely to want other pages near to the page
  1300. * it just requested.
  1301. */
  1302. pss->block = block;
  1303. pss->page = offset >> TARGET_PAGE_BITS;
  1304. /*
  1305. * This unqueued page would break the "one round" check, even is
  1306. * really rare.
  1307. */
  1308. pss->complete_round = false;
  1309. }
  1310. return !!block;
  1311. }
  1312. /**
  1313. * migration_page_queue_free: drop any remaining pages in the ram
  1314. * request queue
  1315. *
  1316. * It should be empty at the end anyway, but in error cases there may
  1317. * be some left. in case that there is any page left, we drop it.
  1318. *
  1319. */
  1320. static void migration_page_queue_free(RAMState *rs)
  1321. {
  1322. struct RAMSrcPageRequest *mspr, *next_mspr;
  1323. /* This queue generally should be empty - but in the case of a failed
  1324. * migration might have some droppings in.
  1325. */
  1326. RCU_READ_LOCK_GUARD();
  1327. QSIMPLEQ_FOREACH_SAFE(mspr, &rs->src_page_requests, next_req, next_mspr) {
  1328. memory_region_unref(mspr->rb->mr);
  1329. QSIMPLEQ_REMOVE_HEAD(&rs->src_page_requests, next_req);
  1330. g_free(mspr);
  1331. }
  1332. }
  1333. /**
  1334. * ram_save_queue_pages: queue the page for transmission
  1335. *
  1336. * A request from postcopy destination for example.
  1337. *
  1338. * Returns zero on success or negative on error
  1339. *
  1340. * @rbname: Name of the RAMBLock of the request. NULL means the
  1341. * same that last one.
  1342. * @start: starting address from the start of the RAMBlock
  1343. * @len: length (in bytes) to send
  1344. */
  1345. int ram_save_queue_pages(const char *rbname, ram_addr_t start, ram_addr_t len)
  1346. {
  1347. RAMBlock *ramblock;
  1348. RAMState *rs = ram_state;
  1349. ram_counters.postcopy_requests++;
  1350. RCU_READ_LOCK_GUARD();
  1351. if (!rbname) {
  1352. /* Reuse last RAMBlock */
  1353. ramblock = rs->last_req_rb;
  1354. if (!ramblock) {
  1355. /*
  1356. * Shouldn't happen, we can't reuse the last RAMBlock if
  1357. * it's the 1st request.
  1358. */
  1359. error_report("ram_save_queue_pages no previous block");
  1360. return -1;
  1361. }
  1362. } else {
  1363. ramblock = qemu_ram_block_by_name(rbname);
  1364. if (!ramblock) {
  1365. /* We shouldn't be asked for a non-existent RAMBlock */
  1366. error_report("ram_save_queue_pages no block '%s'", rbname);
  1367. return -1;
  1368. }
  1369. rs->last_req_rb = ramblock;
  1370. }
  1371. trace_ram_save_queue_pages(ramblock->idstr, start, len);
  1372. if (start+len > ramblock->used_length) {
  1373. error_report("%s request overrun start=" RAM_ADDR_FMT " len="
  1374. RAM_ADDR_FMT " blocklen=" RAM_ADDR_FMT,
  1375. __func__, start, len, ramblock->used_length);
  1376. return -1;
  1377. }
  1378. struct RAMSrcPageRequest *new_entry =
  1379. g_malloc0(sizeof(struct RAMSrcPageRequest));
  1380. new_entry->rb = ramblock;
  1381. new_entry->offset = start;
  1382. new_entry->len = len;
  1383. memory_region_ref(ramblock->mr);
  1384. qemu_mutex_lock(&rs->src_page_req_mutex);
  1385. QSIMPLEQ_INSERT_TAIL(&rs->src_page_requests, new_entry, next_req);
  1386. migration_make_urgent_request();
  1387. qemu_mutex_unlock(&rs->src_page_req_mutex);
  1388. return 0;
  1389. }
  1390. static bool save_page_use_compression(RAMState *rs)
  1391. {
  1392. if (!migrate_use_compression()) {
  1393. return false;
  1394. }
  1395. /*
  1396. * If xbzrle is on, stop using the data compression after first
  1397. * round of migration even if compression is enabled. In theory,
  1398. * xbzrle can do better than compression.
  1399. */
  1400. if (rs->ram_bulk_stage || !migrate_use_xbzrle()) {
  1401. return true;
  1402. }
  1403. return false;
  1404. }
  1405. /*
  1406. * try to compress the page before posting it out, return true if the page
  1407. * has been properly handled by compression, otherwise needs other
  1408. * paths to handle it
  1409. */
  1410. static bool save_compress_page(RAMState *rs, RAMBlock *block, ram_addr_t offset)
  1411. {
  1412. if (!save_page_use_compression(rs)) {
  1413. return false;
  1414. }
  1415. /*
  1416. * When starting the process of a new block, the first page of
  1417. * the block should be sent out before other pages in the same
  1418. * block, and all the pages in last block should have been sent
  1419. * out, keeping this order is important, because the 'cont' flag
  1420. * is used to avoid resending the block name.
  1421. *
  1422. * We post the fist page as normal page as compression will take
  1423. * much CPU resource.
  1424. */
  1425. if (block != rs->last_sent_block) {
  1426. flush_compressed_data(rs);
  1427. return false;
  1428. }
  1429. if (compress_page_with_multi_thread(rs, block, offset) > 0) {
  1430. return true;
  1431. }
  1432. compression_counters.busy++;
  1433. return false;
  1434. }
  1435. /**
  1436. * ram_save_target_page: save one target page
  1437. *
  1438. * Returns the number of pages written
  1439. *
  1440. * @rs: current RAM state
  1441. * @pss: data about the page we want to send
  1442. * @last_stage: if we are at the completion stage
  1443. */
  1444. static int ram_save_target_page(RAMState *rs, PageSearchStatus *pss,
  1445. bool last_stage)
  1446. {
  1447. RAMBlock *block = pss->block;
  1448. ram_addr_t offset = ((ram_addr_t)pss->page) << TARGET_PAGE_BITS;
  1449. int res;
  1450. if (control_save_page(rs, block, offset, &res)) {
  1451. return res;
  1452. }
  1453. if (save_compress_page(rs, block, offset)) {
  1454. return 1;
  1455. }
  1456. res = save_zero_page(rs, block, offset);
  1457. if (res > 0) {
  1458. /* Must let xbzrle know, otherwise a previous (now 0'd) cached
  1459. * page would be stale
  1460. */
  1461. if (!save_page_use_compression(rs)) {
  1462. XBZRLE_cache_lock();
  1463. xbzrle_cache_zero_page(rs, block->offset + offset);
  1464. XBZRLE_cache_unlock();
  1465. }
  1466. ram_release_pages(block->idstr, offset, res);
  1467. return res;
  1468. }
  1469. /*
  1470. * Do not use multifd for:
  1471. * 1. Compression as the first page in the new block should be posted out
  1472. * before sending the compressed page
  1473. * 2. In postcopy as one whole host page should be placed
  1474. */
  1475. if (!save_page_use_compression(rs) && migrate_use_multifd()
  1476. && !migration_in_postcopy()) {
  1477. return ram_save_multifd_page(rs, block, offset);
  1478. }
  1479. return ram_save_page(rs, pss, last_stage);
  1480. }
  1481. /**
  1482. * ram_save_host_page: save a whole host page
  1483. *
  1484. * Starting at *offset send pages up to the end of the current host
  1485. * page. It's valid for the initial offset to point into the middle of
  1486. * a host page in which case the remainder of the hostpage is sent.
  1487. * Only dirty target pages are sent. Note that the host page size may
  1488. * be a huge page for this block.
  1489. * The saving stops at the boundary of the used_length of the block
  1490. * if the RAMBlock isn't a multiple of the host page size.
  1491. *
  1492. * Returns the number of pages written or negative on error
  1493. *
  1494. * @rs: current RAM state
  1495. * @ms: current migration state
  1496. * @pss: data about the page we want to send
  1497. * @last_stage: if we are at the completion stage
  1498. */
  1499. static int ram_save_host_page(RAMState *rs, PageSearchStatus *pss,
  1500. bool last_stage)
  1501. {
  1502. int tmppages, pages = 0;
  1503. size_t pagesize_bits =
  1504. qemu_ram_pagesize(pss->block) >> TARGET_PAGE_BITS;
  1505. if (ramblock_is_ignored(pss->block)) {
  1506. error_report("block %s should not be migrated !", pss->block->idstr);
  1507. return 0;
  1508. }
  1509. do {
  1510. /* Check the pages is dirty and if it is send it */
  1511. if (!migration_bitmap_clear_dirty(rs, pss->block, pss->page)) {
  1512. pss->page++;
  1513. continue;
  1514. }
  1515. tmppages = ram_save_target_page(rs, pss, last_stage);
  1516. if (tmppages < 0) {
  1517. return tmppages;
  1518. }
  1519. pages += tmppages;
  1520. pss->page++;
  1521. /* Allow rate limiting to happen in the middle of huge pages */
  1522. migration_rate_limit();
  1523. } while ((pss->page & (pagesize_bits - 1)) &&
  1524. offset_in_ramblock(pss->block,
  1525. ((ram_addr_t)pss->page) << TARGET_PAGE_BITS));
  1526. /* The offset we leave with is the last one we looked at */
  1527. pss->page--;
  1528. return pages;
  1529. }
  1530. /**
  1531. * ram_find_and_save_block: finds a dirty page and sends it to f
  1532. *
  1533. * Called within an RCU critical section.
  1534. *
  1535. * Returns the number of pages written where zero means no dirty pages,
  1536. * or negative on error
  1537. *
  1538. * @rs: current RAM state
  1539. * @last_stage: if we are at the completion stage
  1540. *
  1541. * On systems where host-page-size > target-page-size it will send all the
  1542. * pages in a host page that are dirty.
  1543. */
  1544. static int ram_find_and_save_block(RAMState *rs, bool last_stage)
  1545. {
  1546. PageSearchStatus pss;
  1547. int pages = 0;
  1548. bool again, found;
  1549. /* No dirty page as there is zero RAM */
  1550. if (!ram_bytes_total()) {
  1551. return pages;
  1552. }
  1553. pss.block = rs->last_seen_block;
  1554. pss.page = rs->last_page;
  1555. pss.complete_round = false;
  1556. if (!pss.block) {
  1557. pss.block = QLIST_FIRST_RCU(&ram_list.blocks);
  1558. }
  1559. do {
  1560. again = true;
  1561. found = get_queued_page(rs, &pss);
  1562. if (!found) {
  1563. /* priority queue empty, so just search for something dirty */
  1564. found = find_dirty_block(rs, &pss, &again);
  1565. }
  1566. if (found) {
  1567. pages = ram_save_host_page(rs, &pss, last_stage);
  1568. }
  1569. } while (!pages && again);
  1570. rs->last_seen_block = pss.block;
  1571. rs->last_page = pss.page;
  1572. return pages;
  1573. }
  1574. void acct_update_position(QEMUFile *f, size_t size, bool zero)
  1575. {
  1576. uint64_t pages = size / TARGET_PAGE_SIZE;
  1577. if (zero) {
  1578. ram_counters.duplicate += pages;
  1579. } else {
  1580. ram_counters.normal += pages;
  1581. ram_counters.transferred += size;
  1582. qemu_update_position(f, size);
  1583. }
  1584. }
  1585. static uint64_t ram_bytes_total_common(bool count_ignored)
  1586. {
  1587. RAMBlock *block;
  1588. uint64_t total = 0;
  1589. RCU_READ_LOCK_GUARD();
  1590. if (count_ignored) {
  1591. RAMBLOCK_FOREACH_MIGRATABLE(block) {
  1592. total += block->used_length;
  1593. }
  1594. } else {
  1595. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  1596. total += block->used_length;
  1597. }
  1598. }
  1599. return total;
  1600. }
  1601. uint64_t ram_bytes_total(void)
  1602. {
  1603. return ram_bytes_total_common(false);
  1604. }
  1605. static void xbzrle_load_setup(void)
  1606. {
  1607. XBZRLE.decoded_buf = g_malloc(TARGET_PAGE_SIZE);
  1608. }
  1609. static void xbzrle_load_cleanup(void)
  1610. {
  1611. g_free(XBZRLE.decoded_buf);
  1612. XBZRLE.decoded_buf = NULL;
  1613. }
  1614. static void ram_state_cleanup(RAMState **rsp)
  1615. {
  1616. if (*rsp) {
  1617. migration_page_queue_free(*rsp);
  1618. qemu_mutex_destroy(&(*rsp)->bitmap_mutex);
  1619. qemu_mutex_destroy(&(*rsp)->src_page_req_mutex);
  1620. g_free(*rsp);
  1621. *rsp = NULL;
  1622. }
  1623. }
  1624. static void xbzrle_cleanup(void)
  1625. {
  1626. XBZRLE_cache_lock();
  1627. if (XBZRLE.cache) {
  1628. cache_fini(XBZRLE.cache);
  1629. g_free(XBZRLE.encoded_buf);
  1630. g_free(XBZRLE.current_buf);
  1631. g_free(XBZRLE.zero_target_page);
  1632. XBZRLE.cache = NULL;
  1633. XBZRLE.encoded_buf = NULL;
  1634. XBZRLE.current_buf = NULL;
  1635. XBZRLE.zero_target_page = NULL;
  1636. }
  1637. XBZRLE_cache_unlock();
  1638. }
  1639. static void ram_save_cleanup(void *opaque)
  1640. {
  1641. RAMState **rsp = opaque;
  1642. RAMBlock *block;
  1643. /* caller have hold iothread lock or is in a bh, so there is
  1644. * no writing race against the migration bitmap
  1645. */
  1646. memory_global_dirty_log_stop();
  1647. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  1648. g_free(block->clear_bmap);
  1649. block->clear_bmap = NULL;
  1650. g_free(block->bmap);
  1651. block->bmap = NULL;
  1652. }
  1653. xbzrle_cleanup();
  1654. compress_threads_save_cleanup();
  1655. ram_state_cleanup(rsp);
  1656. }
  1657. static void ram_state_reset(RAMState *rs)
  1658. {
  1659. rs->last_seen_block = NULL;
  1660. rs->last_sent_block = NULL;
  1661. rs->last_page = 0;
  1662. rs->last_version = ram_list.version;
  1663. rs->ram_bulk_stage = true;
  1664. rs->fpo_enabled = false;
  1665. }
  1666. #define MAX_WAIT 50 /* ms, half buffered_file limit */
  1667. /*
  1668. * 'expected' is the value you expect the bitmap mostly to be full
  1669. * of; it won't bother printing lines that are all this value.
  1670. * If 'todump' is null the migration bitmap is dumped.
  1671. */
  1672. void ram_debug_dump_bitmap(unsigned long *todump, bool expected,
  1673. unsigned long pages)
  1674. {
  1675. int64_t cur;
  1676. int64_t linelen = 128;
  1677. char linebuf[129];
  1678. for (cur = 0; cur < pages; cur += linelen) {
  1679. int64_t curb;
  1680. bool found = false;
  1681. /*
  1682. * Last line; catch the case where the line length
  1683. * is longer than remaining ram
  1684. */
  1685. if (cur + linelen > pages) {
  1686. linelen = pages - cur;
  1687. }
  1688. for (curb = 0; curb < linelen; curb++) {
  1689. bool thisbit = test_bit(cur + curb, todump);
  1690. linebuf[curb] = thisbit ? '1' : '.';
  1691. found = found || (thisbit != expected);
  1692. }
  1693. if (found) {
  1694. linebuf[curb] = '\0';
  1695. fprintf(stderr, "0x%08" PRIx64 " : %s\n", cur, linebuf);
  1696. }
  1697. }
  1698. }
  1699. /* **** functions for postcopy ***** */
  1700. void ram_postcopy_migrated_memory_release(MigrationState *ms)
  1701. {
  1702. struct RAMBlock *block;
  1703. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  1704. unsigned long *bitmap = block->bmap;
  1705. unsigned long range = block->used_length >> TARGET_PAGE_BITS;
  1706. unsigned long run_start = find_next_zero_bit(bitmap, range, 0);
  1707. while (run_start < range) {
  1708. unsigned long run_end = find_next_bit(bitmap, range, run_start + 1);
  1709. ram_discard_range(block->idstr,
  1710. ((ram_addr_t)run_start) << TARGET_PAGE_BITS,
  1711. ((ram_addr_t)(run_end - run_start))
  1712. << TARGET_PAGE_BITS);
  1713. run_start = find_next_zero_bit(bitmap, range, run_end + 1);
  1714. }
  1715. }
  1716. }
  1717. /**
  1718. * postcopy_send_discard_bm_ram: discard a RAMBlock
  1719. *
  1720. * Returns zero on success
  1721. *
  1722. * Callback from postcopy_each_ram_send_discard for each RAMBlock
  1723. *
  1724. * @ms: current migration state
  1725. * @block: RAMBlock to discard
  1726. */
  1727. static int postcopy_send_discard_bm_ram(MigrationState *ms, RAMBlock *block)
  1728. {
  1729. unsigned long end = block->used_length >> TARGET_PAGE_BITS;
  1730. unsigned long current;
  1731. unsigned long *bitmap = block->bmap;
  1732. for (current = 0; current < end; ) {
  1733. unsigned long one = find_next_bit(bitmap, end, current);
  1734. unsigned long zero, discard_length;
  1735. if (one >= end) {
  1736. break;
  1737. }
  1738. zero = find_next_zero_bit(bitmap, end, one + 1);
  1739. if (zero >= end) {
  1740. discard_length = end - one;
  1741. } else {
  1742. discard_length = zero - one;
  1743. }
  1744. postcopy_discard_send_range(ms, one, discard_length);
  1745. current = one + discard_length;
  1746. }
  1747. return 0;
  1748. }
  1749. /**
  1750. * postcopy_each_ram_send_discard: discard all RAMBlocks
  1751. *
  1752. * Returns 0 for success or negative for error
  1753. *
  1754. * Utility for the outgoing postcopy code.
  1755. * Calls postcopy_send_discard_bm_ram for each RAMBlock
  1756. * passing it bitmap indexes and name.
  1757. * (qemu_ram_foreach_block ends up passing unscaled lengths
  1758. * which would mean postcopy code would have to deal with target page)
  1759. *
  1760. * @ms: current migration state
  1761. */
  1762. static int postcopy_each_ram_send_discard(MigrationState *ms)
  1763. {
  1764. struct RAMBlock *block;
  1765. int ret;
  1766. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  1767. postcopy_discard_send_init(ms, block->idstr);
  1768. /*
  1769. * Postcopy sends chunks of bitmap over the wire, but it
  1770. * just needs indexes at this point, avoids it having
  1771. * target page specific code.
  1772. */
  1773. ret = postcopy_send_discard_bm_ram(ms, block);
  1774. postcopy_discard_send_finish(ms);
  1775. if (ret) {
  1776. return ret;
  1777. }
  1778. }
  1779. return 0;
  1780. }
  1781. /**
  1782. * postcopy_chunk_hostpages_pass: canonicalize bitmap in hostpages
  1783. *
  1784. * Helper for postcopy_chunk_hostpages; it's called twice to
  1785. * canonicalize the two bitmaps, that are similar, but one is
  1786. * inverted.
  1787. *
  1788. * Postcopy requires that all target pages in a hostpage are dirty or
  1789. * clean, not a mix. This function canonicalizes the bitmaps.
  1790. *
  1791. * @ms: current migration state
  1792. * @block: block that contains the page we want to canonicalize
  1793. */
  1794. static void postcopy_chunk_hostpages_pass(MigrationState *ms, RAMBlock *block)
  1795. {
  1796. RAMState *rs = ram_state;
  1797. unsigned long *bitmap = block->bmap;
  1798. unsigned int host_ratio = block->page_size / TARGET_PAGE_SIZE;
  1799. unsigned long pages = block->used_length >> TARGET_PAGE_BITS;
  1800. unsigned long run_start;
  1801. if (block->page_size == TARGET_PAGE_SIZE) {
  1802. /* Easy case - TPS==HPS for a non-huge page RAMBlock */
  1803. return;
  1804. }
  1805. /* Find a dirty page */
  1806. run_start = find_next_bit(bitmap, pages, 0);
  1807. while (run_start < pages) {
  1808. /*
  1809. * If the start of this run of pages is in the middle of a host
  1810. * page, then we need to fixup this host page.
  1811. */
  1812. if (QEMU_IS_ALIGNED(run_start, host_ratio)) {
  1813. /* Find the end of this run */
  1814. run_start = find_next_zero_bit(bitmap, pages, run_start + 1);
  1815. /*
  1816. * If the end isn't at the start of a host page, then the
  1817. * run doesn't finish at the end of a host page
  1818. * and we need to discard.
  1819. */
  1820. }
  1821. if (!QEMU_IS_ALIGNED(run_start, host_ratio)) {
  1822. unsigned long page;
  1823. unsigned long fixup_start_addr = QEMU_ALIGN_DOWN(run_start,
  1824. host_ratio);
  1825. run_start = QEMU_ALIGN_UP(run_start, host_ratio);
  1826. /* Clean up the bitmap */
  1827. for (page = fixup_start_addr;
  1828. page < fixup_start_addr + host_ratio; page++) {
  1829. /*
  1830. * Remark them as dirty, updating the count for any pages
  1831. * that weren't previously dirty.
  1832. */
  1833. rs->migration_dirty_pages += !test_and_set_bit(page, bitmap);
  1834. }
  1835. }
  1836. /* Find the next dirty page for the next iteration */
  1837. run_start = find_next_bit(bitmap, pages, run_start);
  1838. }
  1839. }
  1840. /**
  1841. * postcopy_chunk_hostpages: discard any partially sent host page
  1842. *
  1843. * Utility for the outgoing postcopy code.
  1844. *
  1845. * Discard any partially sent host-page size chunks, mark any partially
  1846. * dirty host-page size chunks as all dirty. In this case the host-page
  1847. * is the host-page for the particular RAMBlock, i.e. it might be a huge page
  1848. *
  1849. * Returns zero on success
  1850. *
  1851. * @ms: current migration state
  1852. * @block: block we want to work with
  1853. */
  1854. static int postcopy_chunk_hostpages(MigrationState *ms, RAMBlock *block)
  1855. {
  1856. postcopy_discard_send_init(ms, block->idstr);
  1857. /*
  1858. * Ensure that all partially dirty host pages are made fully dirty.
  1859. */
  1860. postcopy_chunk_hostpages_pass(ms, block);
  1861. postcopy_discard_send_finish(ms);
  1862. return 0;
  1863. }
  1864. /**
  1865. * ram_postcopy_send_discard_bitmap: transmit the discard bitmap
  1866. *
  1867. * Returns zero on success
  1868. *
  1869. * Transmit the set of pages to be discarded after precopy to the target
  1870. * these are pages that:
  1871. * a) Have been previously transmitted but are now dirty again
  1872. * b) Pages that have never been transmitted, this ensures that
  1873. * any pages on the destination that have been mapped by background
  1874. * tasks get discarded (transparent huge pages is the specific concern)
  1875. * Hopefully this is pretty sparse
  1876. *
  1877. * @ms: current migration state
  1878. */
  1879. int ram_postcopy_send_discard_bitmap(MigrationState *ms)
  1880. {
  1881. RAMState *rs = ram_state;
  1882. RAMBlock *block;
  1883. int ret;
  1884. RCU_READ_LOCK_GUARD();
  1885. /* This should be our last sync, the src is now paused */
  1886. migration_bitmap_sync(rs);
  1887. /* Easiest way to make sure we don't resume in the middle of a host-page */
  1888. rs->last_seen_block = NULL;
  1889. rs->last_sent_block = NULL;
  1890. rs->last_page = 0;
  1891. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  1892. /* Deal with TPS != HPS and huge pages */
  1893. ret = postcopy_chunk_hostpages(ms, block);
  1894. if (ret) {
  1895. return ret;
  1896. }
  1897. #ifdef DEBUG_POSTCOPY
  1898. ram_debug_dump_bitmap(block->bmap, true,
  1899. block->used_length >> TARGET_PAGE_BITS);
  1900. #endif
  1901. }
  1902. trace_ram_postcopy_send_discard_bitmap();
  1903. return postcopy_each_ram_send_discard(ms);
  1904. }
  1905. /**
  1906. * ram_discard_range: discard dirtied pages at the beginning of postcopy
  1907. *
  1908. * Returns zero on success
  1909. *
  1910. * @rbname: name of the RAMBlock of the request. NULL means the
  1911. * same that last one.
  1912. * @start: RAMBlock starting page
  1913. * @length: RAMBlock size
  1914. */
  1915. int ram_discard_range(const char *rbname, uint64_t start, size_t length)
  1916. {
  1917. trace_ram_discard_range(rbname, start, length);
  1918. RCU_READ_LOCK_GUARD();
  1919. RAMBlock *rb = qemu_ram_block_by_name(rbname);
  1920. if (!rb) {
  1921. error_report("ram_discard_range: Failed to find block '%s'", rbname);
  1922. return -1;
  1923. }
  1924. /*
  1925. * On source VM, we don't need to update the received bitmap since
  1926. * we don't even have one.
  1927. */
  1928. if (rb->receivedmap) {
  1929. bitmap_clear(rb->receivedmap, start >> qemu_target_page_bits(),
  1930. length >> qemu_target_page_bits());
  1931. }
  1932. return ram_block_discard_range(rb, start, length);
  1933. }
  1934. /*
  1935. * For every allocation, we will try not to crash the VM if the
  1936. * allocation failed.
  1937. */
  1938. static int xbzrle_init(void)
  1939. {
  1940. Error *local_err = NULL;
  1941. if (!migrate_use_xbzrle()) {
  1942. return 0;
  1943. }
  1944. XBZRLE_cache_lock();
  1945. XBZRLE.zero_target_page = g_try_malloc0(TARGET_PAGE_SIZE);
  1946. if (!XBZRLE.zero_target_page) {
  1947. error_report("%s: Error allocating zero page", __func__);
  1948. goto err_out;
  1949. }
  1950. XBZRLE.cache = cache_init(migrate_xbzrle_cache_size(),
  1951. TARGET_PAGE_SIZE, &local_err);
  1952. if (!XBZRLE.cache) {
  1953. error_report_err(local_err);
  1954. goto free_zero_page;
  1955. }
  1956. XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);
  1957. if (!XBZRLE.encoded_buf) {
  1958. error_report("%s: Error allocating encoded_buf", __func__);
  1959. goto free_cache;
  1960. }
  1961. XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);
  1962. if (!XBZRLE.current_buf) {
  1963. error_report("%s: Error allocating current_buf", __func__);
  1964. goto free_encoded_buf;
  1965. }
  1966. /* We are all good */
  1967. XBZRLE_cache_unlock();
  1968. return 0;
  1969. free_encoded_buf:
  1970. g_free(XBZRLE.encoded_buf);
  1971. XBZRLE.encoded_buf = NULL;
  1972. free_cache:
  1973. cache_fini(XBZRLE.cache);
  1974. XBZRLE.cache = NULL;
  1975. free_zero_page:
  1976. g_free(XBZRLE.zero_target_page);
  1977. XBZRLE.zero_target_page = NULL;
  1978. err_out:
  1979. XBZRLE_cache_unlock();
  1980. return -ENOMEM;
  1981. }
  1982. static int ram_state_init(RAMState **rsp)
  1983. {
  1984. *rsp = g_try_new0(RAMState, 1);
  1985. if (!*rsp) {
  1986. error_report("%s: Init ramstate fail", __func__);
  1987. return -1;
  1988. }
  1989. qemu_mutex_init(&(*rsp)->bitmap_mutex);
  1990. qemu_mutex_init(&(*rsp)->src_page_req_mutex);
  1991. QSIMPLEQ_INIT(&(*rsp)->src_page_requests);
  1992. /*
  1993. * Count the total number of pages used by ram blocks not including any
  1994. * gaps due to alignment or unplugs.
  1995. * This must match with the initial values of dirty bitmap.
  1996. */
  1997. (*rsp)->migration_dirty_pages = ram_bytes_total() >> TARGET_PAGE_BITS;
  1998. ram_state_reset(*rsp);
  1999. return 0;
  2000. }
  2001. static void ram_list_init_bitmaps(void)
  2002. {
  2003. MigrationState *ms = migrate_get_current();
  2004. RAMBlock *block;
  2005. unsigned long pages;
  2006. uint8_t shift;
  2007. /* Skip setting bitmap if there is no RAM */
  2008. if (ram_bytes_total()) {
  2009. shift = ms->clear_bitmap_shift;
  2010. if (shift > CLEAR_BITMAP_SHIFT_MAX) {
  2011. error_report("clear_bitmap_shift (%u) too big, using "
  2012. "max value (%u)", shift, CLEAR_BITMAP_SHIFT_MAX);
  2013. shift = CLEAR_BITMAP_SHIFT_MAX;
  2014. } else if (shift < CLEAR_BITMAP_SHIFT_MIN) {
  2015. error_report("clear_bitmap_shift (%u) too small, using "
  2016. "min value (%u)", shift, CLEAR_BITMAP_SHIFT_MIN);
  2017. shift = CLEAR_BITMAP_SHIFT_MIN;
  2018. }
  2019. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  2020. pages = block->max_length >> TARGET_PAGE_BITS;
  2021. /*
  2022. * The initial dirty bitmap for migration must be set with all
  2023. * ones to make sure we'll migrate every guest RAM page to
  2024. * destination.
  2025. * Here we set RAMBlock.bmap all to 1 because when rebegin a
  2026. * new migration after a failed migration, ram_list.
  2027. * dirty_memory[DIRTY_MEMORY_MIGRATION] don't include the whole
  2028. * guest memory.
  2029. */
  2030. block->bmap = bitmap_new(pages);
  2031. bitmap_set(block->bmap, 0, pages);
  2032. block->clear_bmap_shift = shift;
  2033. block->clear_bmap = bitmap_new(clear_bmap_size(pages, shift));
  2034. }
  2035. }
  2036. }
  2037. static void ram_init_bitmaps(RAMState *rs)
  2038. {
  2039. /* For memory_global_dirty_log_start below. */
  2040. qemu_mutex_lock_iothread();
  2041. qemu_mutex_lock_ramlist();
  2042. WITH_RCU_READ_LOCK_GUARD() {
  2043. ram_list_init_bitmaps();
  2044. memory_global_dirty_log_start();
  2045. migration_bitmap_sync_precopy(rs);
  2046. }
  2047. qemu_mutex_unlock_ramlist();
  2048. qemu_mutex_unlock_iothread();
  2049. }
  2050. static int ram_init_all(RAMState **rsp)
  2051. {
  2052. if (ram_state_init(rsp)) {
  2053. return -1;
  2054. }
  2055. if (xbzrle_init()) {
  2056. ram_state_cleanup(rsp);
  2057. return -1;
  2058. }
  2059. ram_init_bitmaps(*rsp);
  2060. return 0;
  2061. }
  2062. static void ram_state_resume_prepare(RAMState *rs, QEMUFile *out)
  2063. {
  2064. RAMBlock *block;
  2065. uint64_t pages = 0;
  2066. /*
  2067. * Postcopy is not using xbzrle/compression, so no need for that.
  2068. * Also, since source are already halted, we don't need to care
  2069. * about dirty page logging as well.
  2070. */
  2071. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  2072. pages += bitmap_count_one(block->bmap,
  2073. block->used_length >> TARGET_PAGE_BITS);
  2074. }
  2075. /* This may not be aligned with current bitmaps. Recalculate. */
  2076. rs->migration_dirty_pages = pages;
  2077. rs->last_seen_block = NULL;
  2078. rs->last_sent_block = NULL;
  2079. rs->last_page = 0;
  2080. rs->last_version = ram_list.version;
  2081. /*
  2082. * Disable the bulk stage, otherwise we'll resend the whole RAM no
  2083. * matter what we have sent.
  2084. */
  2085. rs->ram_bulk_stage = false;
  2086. /* Update RAMState cache of output QEMUFile */
  2087. rs->f = out;
  2088. trace_ram_state_resume_prepare(pages);
  2089. }
  2090. /*
  2091. * This function clears bits of the free pages reported by the caller from the
  2092. * migration dirty bitmap. @addr is the host address corresponding to the
  2093. * start of the continuous guest free pages, and @len is the total bytes of
  2094. * those pages.
  2095. */
  2096. void qemu_guest_free_page_hint(void *addr, size_t len)
  2097. {
  2098. RAMBlock *block;
  2099. ram_addr_t offset;
  2100. size_t used_len, start, npages;
  2101. MigrationState *s = migrate_get_current();
  2102. /* This function is currently expected to be used during live migration */
  2103. if (!migration_is_setup_or_active(s->state)) {
  2104. return;
  2105. }
  2106. for (; len > 0; len -= used_len, addr += used_len) {
  2107. block = qemu_ram_block_from_host(addr, false, &offset);
  2108. if (unlikely(!block || offset >= block->used_length)) {
  2109. /*
  2110. * The implementation might not support RAMBlock resize during
  2111. * live migration, but it could happen in theory with future
  2112. * updates. So we add a check here to capture that case.
  2113. */
  2114. error_report_once("%s unexpected error", __func__);
  2115. return;
  2116. }
  2117. if (len <= block->used_length - offset) {
  2118. used_len = len;
  2119. } else {
  2120. used_len = block->used_length - offset;
  2121. }
  2122. start = offset >> TARGET_PAGE_BITS;
  2123. npages = used_len >> TARGET_PAGE_BITS;
  2124. qemu_mutex_lock(&ram_state->bitmap_mutex);
  2125. ram_state->migration_dirty_pages -=
  2126. bitmap_count_one_with_offset(block->bmap, start, npages);
  2127. bitmap_clear(block->bmap, start, npages);
  2128. qemu_mutex_unlock(&ram_state->bitmap_mutex);
  2129. }
  2130. }
  2131. /*
  2132. * Each of ram_save_setup, ram_save_iterate and ram_save_complete has
  2133. * long-running RCU critical section. When rcu-reclaims in the code
  2134. * start to become numerous it will be necessary to reduce the
  2135. * granularity of these critical sections.
  2136. */
  2137. /**
  2138. * ram_save_setup: Setup RAM for migration
  2139. *
  2140. * Returns zero to indicate success and negative for error
  2141. *
  2142. * @f: QEMUFile where to send the data
  2143. * @opaque: RAMState pointer
  2144. */
  2145. static int ram_save_setup(QEMUFile *f, void *opaque)
  2146. {
  2147. RAMState **rsp = opaque;
  2148. RAMBlock *block;
  2149. if (compress_threads_save_setup()) {
  2150. return -1;
  2151. }
  2152. /* migration has already setup the bitmap, reuse it. */
  2153. if (!migration_in_colo_state()) {
  2154. if (ram_init_all(rsp) != 0) {
  2155. compress_threads_save_cleanup();
  2156. return -1;
  2157. }
  2158. }
  2159. (*rsp)->f = f;
  2160. WITH_RCU_READ_LOCK_GUARD() {
  2161. qemu_put_be64(f, ram_bytes_total_common(true) | RAM_SAVE_FLAG_MEM_SIZE);
  2162. RAMBLOCK_FOREACH_MIGRATABLE(block) {
  2163. qemu_put_byte(f, strlen(block->idstr));
  2164. qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
  2165. qemu_put_be64(f, block->used_length);
  2166. if (migrate_postcopy_ram() && block->page_size !=
  2167. qemu_host_page_size) {
  2168. qemu_put_be64(f, block->page_size);
  2169. }
  2170. if (migrate_ignore_shared()) {
  2171. qemu_put_be64(f, block->mr->addr);
  2172. }
  2173. }
  2174. }
  2175. ram_control_before_iterate(f, RAM_CONTROL_SETUP);
  2176. ram_control_after_iterate(f, RAM_CONTROL_SETUP);
  2177. multifd_send_sync_main(f);
  2178. qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
  2179. qemu_fflush(f);
  2180. return 0;
  2181. }
  2182. /**
  2183. * ram_save_iterate: iterative stage for migration
  2184. *
  2185. * Returns zero to indicate success and negative for error
  2186. *
  2187. * @f: QEMUFile where to send the data
  2188. * @opaque: RAMState pointer
  2189. */
  2190. static int ram_save_iterate(QEMUFile *f, void *opaque)
  2191. {
  2192. RAMState **temp = opaque;
  2193. RAMState *rs = *temp;
  2194. int ret = 0;
  2195. int i;
  2196. int64_t t0;
  2197. int done = 0;
  2198. if (blk_mig_bulk_active()) {
  2199. /* Avoid transferring ram during bulk phase of block migration as
  2200. * the bulk phase will usually take a long time and transferring
  2201. * ram updates during that time is pointless. */
  2202. goto out;
  2203. }
  2204. WITH_RCU_READ_LOCK_GUARD() {
  2205. if (ram_list.version != rs->last_version) {
  2206. ram_state_reset(rs);
  2207. }
  2208. /* Read version before ram_list.blocks */
  2209. smp_rmb();
  2210. ram_control_before_iterate(f, RAM_CONTROL_ROUND);
  2211. t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
  2212. i = 0;
  2213. while ((ret = qemu_file_rate_limit(f)) == 0 ||
  2214. !QSIMPLEQ_EMPTY(&rs->src_page_requests)) {
  2215. int pages;
  2216. if (qemu_file_get_error(f)) {
  2217. break;
  2218. }
  2219. pages = ram_find_and_save_block(rs, false);
  2220. /* no more pages to sent */
  2221. if (pages == 0) {
  2222. done = 1;
  2223. break;
  2224. }
  2225. if (pages < 0) {
  2226. qemu_file_set_error(f, pages);
  2227. break;
  2228. }
  2229. rs->target_page_count += pages;
  2230. /*
  2231. * During postcopy, it is necessary to make sure one whole host
  2232. * page is sent in one chunk.
  2233. */
  2234. if (migrate_postcopy_ram()) {
  2235. flush_compressed_data(rs);
  2236. }
  2237. /*
  2238. * we want to check in the 1st loop, just in case it was the 1st
  2239. * time and we had to sync the dirty bitmap.
  2240. * qemu_clock_get_ns() is a bit expensive, so we only check each
  2241. * some iterations
  2242. */
  2243. if ((i & 63) == 0) {
  2244. uint64_t t1 = (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - t0) /
  2245. 1000000;
  2246. if (t1 > MAX_WAIT) {
  2247. trace_ram_save_iterate_big_wait(t1, i);
  2248. break;
  2249. }
  2250. }
  2251. i++;
  2252. }
  2253. }
  2254. /*
  2255. * Must occur before EOS (or any QEMUFile operation)
  2256. * because of RDMA protocol.
  2257. */
  2258. ram_control_after_iterate(f, RAM_CONTROL_ROUND);
  2259. out:
  2260. if (ret >= 0
  2261. && migration_is_setup_or_active(migrate_get_current()->state)) {
  2262. multifd_send_sync_main(rs->f);
  2263. qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
  2264. qemu_fflush(f);
  2265. ram_counters.transferred += 8;
  2266. ret = qemu_file_get_error(f);
  2267. }
  2268. if (ret < 0) {
  2269. return ret;
  2270. }
  2271. return done;
  2272. }
  2273. /**
  2274. * ram_save_complete: function called to send the remaining amount of ram
  2275. *
  2276. * Returns zero to indicate success or negative on error
  2277. *
  2278. * Called with iothread lock
  2279. *
  2280. * @f: QEMUFile where to send the data
  2281. * @opaque: RAMState pointer
  2282. */
  2283. static int ram_save_complete(QEMUFile *f, void *opaque)
  2284. {
  2285. RAMState **temp = opaque;
  2286. RAMState *rs = *temp;
  2287. int ret = 0;
  2288. WITH_RCU_READ_LOCK_GUARD() {
  2289. if (!migration_in_postcopy()) {
  2290. migration_bitmap_sync_precopy(rs);
  2291. }
  2292. ram_control_before_iterate(f, RAM_CONTROL_FINISH);
  2293. /* try transferring iterative blocks of memory */
  2294. /* flush all remaining blocks regardless of rate limiting */
  2295. while (true) {
  2296. int pages;
  2297. pages = ram_find_and_save_block(rs, !migration_in_colo_state());
  2298. /* no more blocks to sent */
  2299. if (pages == 0) {
  2300. break;
  2301. }
  2302. if (pages < 0) {
  2303. ret = pages;
  2304. break;
  2305. }
  2306. }
  2307. flush_compressed_data(rs);
  2308. ram_control_after_iterate(f, RAM_CONTROL_FINISH);
  2309. }
  2310. if (ret >= 0) {
  2311. multifd_send_sync_main(rs->f);
  2312. qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
  2313. qemu_fflush(f);
  2314. }
  2315. return ret;
  2316. }
  2317. static void ram_save_pending(QEMUFile *f, void *opaque, uint64_t max_size,
  2318. uint64_t *res_precopy_only,
  2319. uint64_t *res_compatible,
  2320. uint64_t *res_postcopy_only)
  2321. {
  2322. RAMState **temp = opaque;
  2323. RAMState *rs = *temp;
  2324. uint64_t remaining_size;
  2325. remaining_size = rs->migration_dirty_pages * TARGET_PAGE_SIZE;
  2326. if (!migration_in_postcopy() &&
  2327. remaining_size < max_size) {
  2328. qemu_mutex_lock_iothread();
  2329. WITH_RCU_READ_LOCK_GUARD() {
  2330. migration_bitmap_sync_precopy(rs);
  2331. }
  2332. qemu_mutex_unlock_iothread();
  2333. remaining_size = rs->migration_dirty_pages * TARGET_PAGE_SIZE;
  2334. }
  2335. if (migrate_postcopy_ram()) {
  2336. /* We can do postcopy, and all the data is postcopiable */
  2337. *res_compatible += remaining_size;
  2338. } else {
  2339. *res_precopy_only += remaining_size;
  2340. }
  2341. }
  2342. static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
  2343. {
  2344. unsigned int xh_len;
  2345. int xh_flags;
  2346. uint8_t *loaded_data;
  2347. /* extract RLE header */
  2348. xh_flags = qemu_get_byte(f);
  2349. xh_len = qemu_get_be16(f);
  2350. if (xh_flags != ENCODING_FLAG_XBZRLE) {
  2351. error_report("Failed to load XBZRLE page - wrong compression!");
  2352. return -1;
  2353. }
  2354. if (xh_len > TARGET_PAGE_SIZE) {
  2355. error_report("Failed to load XBZRLE page - len overflow!");
  2356. return -1;
  2357. }
  2358. loaded_data = XBZRLE.decoded_buf;
  2359. /* load data and decode */
  2360. /* it can change loaded_data to point to an internal buffer */
  2361. qemu_get_buffer_in_place(f, &loaded_data, xh_len);
  2362. /* decode RLE */
  2363. if (xbzrle_decode_buffer(loaded_data, xh_len, host,
  2364. TARGET_PAGE_SIZE) == -1) {
  2365. error_report("Failed to load XBZRLE page - decode error!");
  2366. return -1;
  2367. }
  2368. return 0;
  2369. }
  2370. /**
  2371. * ram_block_from_stream: read a RAMBlock id from the migration stream
  2372. *
  2373. * Must be called from within a rcu critical section.
  2374. *
  2375. * Returns a pointer from within the RCU-protected ram_list.
  2376. *
  2377. * @f: QEMUFile where to read the data from
  2378. * @flags: Page flags (mostly to see if it's a continuation of previous block)
  2379. */
  2380. static inline RAMBlock *ram_block_from_stream(QEMUFile *f, int flags)
  2381. {
  2382. static RAMBlock *block = NULL;
  2383. char id[256];
  2384. uint8_t len;
  2385. if (flags & RAM_SAVE_FLAG_CONTINUE) {
  2386. if (!block) {
  2387. error_report("Ack, bad migration stream!");
  2388. return NULL;
  2389. }
  2390. return block;
  2391. }
  2392. len = qemu_get_byte(f);
  2393. qemu_get_buffer(f, (uint8_t *)id, len);
  2394. id[len] = 0;
  2395. block = qemu_ram_block_by_name(id);
  2396. if (!block) {
  2397. error_report("Can't find block %s", id);
  2398. return NULL;
  2399. }
  2400. if (ramblock_is_ignored(block)) {
  2401. error_report("block %s should not be migrated !", id);
  2402. return NULL;
  2403. }
  2404. return block;
  2405. }
  2406. static inline void *host_from_ram_block_offset(RAMBlock *block,
  2407. ram_addr_t offset)
  2408. {
  2409. if (!offset_in_ramblock(block, offset)) {
  2410. return NULL;
  2411. }
  2412. return block->host + offset;
  2413. }
  2414. static inline void *colo_cache_from_block_offset(RAMBlock *block,
  2415. ram_addr_t offset, bool record_bitmap)
  2416. {
  2417. if (!offset_in_ramblock(block, offset)) {
  2418. return NULL;
  2419. }
  2420. if (!block->colo_cache) {
  2421. error_report("%s: colo_cache is NULL in block :%s",
  2422. __func__, block->idstr);
  2423. return NULL;
  2424. }
  2425. /*
  2426. * During colo checkpoint, we need bitmap of these migrated pages.
  2427. * It help us to decide which pages in ram cache should be flushed
  2428. * into VM's RAM later.
  2429. */
  2430. if (record_bitmap &&
  2431. !test_and_set_bit(offset >> TARGET_PAGE_BITS, block->bmap)) {
  2432. ram_state->migration_dirty_pages++;
  2433. }
  2434. return block->colo_cache + offset;
  2435. }
  2436. /**
  2437. * ram_handle_compressed: handle the zero page case
  2438. *
  2439. * If a page (or a whole RDMA chunk) has been
  2440. * determined to be zero, then zap it.
  2441. *
  2442. * @host: host address for the zero page
  2443. * @ch: what the page is filled from. We only support zero
  2444. * @size: size of the zero page
  2445. */
  2446. void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)
  2447. {
  2448. if (ch != 0 || !is_zero_range(host, size)) {
  2449. memset(host, ch, size);
  2450. }
  2451. }
  2452. /* return the size after decompression, or negative value on error */
  2453. static int
  2454. qemu_uncompress_data(z_stream *stream, uint8_t *dest, size_t dest_len,
  2455. const uint8_t *source, size_t source_len)
  2456. {
  2457. int err;
  2458. err = inflateReset(stream);
  2459. if (err != Z_OK) {
  2460. return -1;
  2461. }
  2462. stream->avail_in = source_len;
  2463. stream->next_in = (uint8_t *)source;
  2464. stream->avail_out = dest_len;
  2465. stream->next_out = dest;
  2466. err = inflate(stream, Z_NO_FLUSH);
  2467. if (err != Z_STREAM_END) {
  2468. return -1;
  2469. }
  2470. return stream->total_out;
  2471. }
  2472. static void *do_data_decompress(void *opaque)
  2473. {
  2474. DecompressParam *param = opaque;
  2475. unsigned long pagesize;
  2476. uint8_t *des;
  2477. int len, ret;
  2478. qemu_mutex_lock(&param->mutex);
  2479. while (!param->quit) {
  2480. if (param->des) {
  2481. des = param->des;
  2482. len = param->len;
  2483. param->des = 0;
  2484. qemu_mutex_unlock(&param->mutex);
  2485. pagesize = TARGET_PAGE_SIZE;
  2486. ret = qemu_uncompress_data(&param->stream, des, pagesize,
  2487. param->compbuf, len);
  2488. if (ret < 0 && migrate_get_current()->decompress_error_check) {
  2489. error_report("decompress data failed");
  2490. qemu_file_set_error(decomp_file, ret);
  2491. }
  2492. qemu_mutex_lock(&decomp_done_lock);
  2493. param->done = true;
  2494. qemu_cond_signal(&decomp_done_cond);
  2495. qemu_mutex_unlock(&decomp_done_lock);
  2496. qemu_mutex_lock(&param->mutex);
  2497. } else {
  2498. qemu_cond_wait(&param->cond, &param->mutex);
  2499. }
  2500. }
  2501. qemu_mutex_unlock(&param->mutex);
  2502. return NULL;
  2503. }
  2504. static int wait_for_decompress_done(void)
  2505. {
  2506. int idx, thread_count;
  2507. if (!migrate_use_compression()) {
  2508. return 0;
  2509. }
  2510. thread_count = migrate_decompress_threads();
  2511. qemu_mutex_lock(&decomp_done_lock);
  2512. for (idx = 0; idx < thread_count; idx++) {
  2513. while (!decomp_param[idx].done) {
  2514. qemu_cond_wait(&decomp_done_cond, &decomp_done_lock);
  2515. }
  2516. }
  2517. qemu_mutex_unlock(&decomp_done_lock);
  2518. return qemu_file_get_error(decomp_file);
  2519. }
  2520. static void compress_threads_load_cleanup(void)
  2521. {
  2522. int i, thread_count;
  2523. if (!migrate_use_compression()) {
  2524. return;
  2525. }
  2526. thread_count = migrate_decompress_threads();
  2527. for (i = 0; i < thread_count; i++) {
  2528. /*
  2529. * we use it as a indicator which shows if the thread is
  2530. * properly init'd or not
  2531. */
  2532. if (!decomp_param[i].compbuf) {
  2533. break;
  2534. }
  2535. qemu_mutex_lock(&decomp_param[i].mutex);
  2536. decomp_param[i].quit = true;
  2537. qemu_cond_signal(&decomp_param[i].cond);
  2538. qemu_mutex_unlock(&decomp_param[i].mutex);
  2539. }
  2540. for (i = 0; i < thread_count; i++) {
  2541. if (!decomp_param[i].compbuf) {
  2542. break;
  2543. }
  2544. qemu_thread_join(decompress_threads + i);
  2545. qemu_mutex_destroy(&decomp_param[i].mutex);
  2546. qemu_cond_destroy(&decomp_param[i].cond);
  2547. inflateEnd(&decomp_param[i].stream);
  2548. g_free(decomp_param[i].compbuf);
  2549. decomp_param[i].compbuf = NULL;
  2550. }
  2551. g_free(decompress_threads);
  2552. g_free(decomp_param);
  2553. decompress_threads = NULL;
  2554. decomp_param = NULL;
  2555. decomp_file = NULL;
  2556. }
  2557. static int compress_threads_load_setup(QEMUFile *f)
  2558. {
  2559. int i, thread_count;
  2560. if (!migrate_use_compression()) {
  2561. return 0;
  2562. }
  2563. thread_count = migrate_decompress_threads();
  2564. decompress_threads = g_new0(QemuThread, thread_count);
  2565. decomp_param = g_new0(DecompressParam, thread_count);
  2566. qemu_mutex_init(&decomp_done_lock);
  2567. qemu_cond_init(&decomp_done_cond);
  2568. decomp_file = f;
  2569. for (i = 0; i < thread_count; i++) {
  2570. if (inflateInit(&decomp_param[i].stream) != Z_OK) {
  2571. goto exit;
  2572. }
  2573. decomp_param[i].compbuf = g_malloc0(compressBound(TARGET_PAGE_SIZE));
  2574. qemu_mutex_init(&decomp_param[i].mutex);
  2575. qemu_cond_init(&decomp_param[i].cond);
  2576. decomp_param[i].done = true;
  2577. decomp_param[i].quit = false;
  2578. qemu_thread_create(decompress_threads + i, "decompress",
  2579. do_data_decompress, decomp_param + i,
  2580. QEMU_THREAD_JOINABLE);
  2581. }
  2582. return 0;
  2583. exit:
  2584. compress_threads_load_cleanup();
  2585. return -1;
  2586. }
  2587. static void decompress_data_with_multi_threads(QEMUFile *f,
  2588. void *host, int len)
  2589. {
  2590. int idx, thread_count;
  2591. thread_count = migrate_decompress_threads();
  2592. qemu_mutex_lock(&decomp_done_lock);
  2593. while (true) {
  2594. for (idx = 0; idx < thread_count; idx++) {
  2595. if (decomp_param[idx].done) {
  2596. decomp_param[idx].done = false;
  2597. qemu_mutex_lock(&decomp_param[idx].mutex);
  2598. qemu_get_buffer(f, decomp_param[idx].compbuf, len);
  2599. decomp_param[idx].des = host;
  2600. decomp_param[idx].len = len;
  2601. qemu_cond_signal(&decomp_param[idx].cond);
  2602. qemu_mutex_unlock(&decomp_param[idx].mutex);
  2603. break;
  2604. }
  2605. }
  2606. if (idx < thread_count) {
  2607. break;
  2608. } else {
  2609. qemu_cond_wait(&decomp_done_cond, &decomp_done_lock);
  2610. }
  2611. }
  2612. qemu_mutex_unlock(&decomp_done_lock);
  2613. }
  2614. /*
  2615. * colo cache: this is for secondary VM, we cache the whole
  2616. * memory of the secondary VM, it is need to hold the global lock
  2617. * to call this helper.
  2618. */
  2619. int colo_init_ram_cache(void)
  2620. {
  2621. RAMBlock *block;
  2622. WITH_RCU_READ_LOCK_GUARD() {
  2623. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  2624. block->colo_cache = qemu_anon_ram_alloc(block->used_length,
  2625. NULL,
  2626. false);
  2627. if (!block->colo_cache) {
  2628. error_report("%s: Can't alloc memory for COLO cache of block %s,"
  2629. "size 0x" RAM_ADDR_FMT, __func__, block->idstr,
  2630. block->used_length);
  2631. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  2632. if (block->colo_cache) {
  2633. qemu_anon_ram_free(block->colo_cache, block->used_length);
  2634. block->colo_cache = NULL;
  2635. }
  2636. }
  2637. return -errno;
  2638. }
  2639. }
  2640. }
  2641. /*
  2642. * Record the dirty pages that sent by PVM, we use this dirty bitmap together
  2643. * with to decide which page in cache should be flushed into SVM's RAM. Here
  2644. * we use the same name 'ram_bitmap' as for migration.
  2645. */
  2646. if (ram_bytes_total()) {
  2647. RAMBlock *block;
  2648. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  2649. unsigned long pages = block->max_length >> TARGET_PAGE_BITS;
  2650. block->bmap = bitmap_new(pages);
  2651. }
  2652. }
  2653. ram_state_init(&ram_state);
  2654. return 0;
  2655. }
  2656. /* TODO: duplicated with ram_init_bitmaps */
  2657. void colo_incoming_start_dirty_log(void)
  2658. {
  2659. RAMBlock *block = NULL;
  2660. /* For memory_global_dirty_log_start below. */
  2661. qemu_mutex_lock_iothread();
  2662. qemu_mutex_lock_ramlist();
  2663. memory_global_dirty_log_sync();
  2664. WITH_RCU_READ_LOCK_GUARD() {
  2665. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  2666. ramblock_sync_dirty_bitmap(ram_state, block);
  2667. /* Discard this dirty bitmap record */
  2668. bitmap_zero(block->bmap, block->max_length >> TARGET_PAGE_BITS);
  2669. }
  2670. memory_global_dirty_log_start();
  2671. }
  2672. ram_state->migration_dirty_pages = 0;
  2673. qemu_mutex_unlock_ramlist();
  2674. qemu_mutex_unlock_iothread();
  2675. }
  2676. /* It is need to hold the global lock to call this helper */
  2677. void colo_release_ram_cache(void)
  2678. {
  2679. RAMBlock *block;
  2680. memory_global_dirty_log_stop();
  2681. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  2682. g_free(block->bmap);
  2683. block->bmap = NULL;
  2684. }
  2685. WITH_RCU_READ_LOCK_GUARD() {
  2686. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  2687. if (block->colo_cache) {
  2688. qemu_anon_ram_free(block->colo_cache, block->used_length);
  2689. block->colo_cache = NULL;
  2690. }
  2691. }
  2692. }
  2693. ram_state_cleanup(&ram_state);
  2694. }
  2695. /**
  2696. * ram_load_setup: Setup RAM for migration incoming side
  2697. *
  2698. * Returns zero to indicate success and negative for error
  2699. *
  2700. * @f: QEMUFile where to receive the data
  2701. * @opaque: RAMState pointer
  2702. */
  2703. static int ram_load_setup(QEMUFile *f, void *opaque)
  2704. {
  2705. if (compress_threads_load_setup(f)) {
  2706. return -1;
  2707. }
  2708. xbzrle_load_setup();
  2709. ramblock_recv_map_init();
  2710. return 0;
  2711. }
  2712. static int ram_load_cleanup(void *opaque)
  2713. {
  2714. RAMBlock *rb;
  2715. RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
  2716. qemu_ram_block_writeback(rb);
  2717. }
  2718. xbzrle_load_cleanup();
  2719. compress_threads_load_cleanup();
  2720. RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
  2721. g_free(rb->receivedmap);
  2722. rb->receivedmap = NULL;
  2723. }
  2724. return 0;
  2725. }
  2726. /**
  2727. * ram_postcopy_incoming_init: allocate postcopy data structures
  2728. *
  2729. * Returns 0 for success and negative if there was one error
  2730. *
  2731. * @mis: current migration incoming state
  2732. *
  2733. * Allocate data structures etc needed by incoming migration with
  2734. * postcopy-ram. postcopy-ram's similarly names
  2735. * postcopy_ram_incoming_init does the work.
  2736. */
  2737. int ram_postcopy_incoming_init(MigrationIncomingState *mis)
  2738. {
  2739. return postcopy_ram_incoming_init(mis);
  2740. }
  2741. /**
  2742. * ram_load_postcopy: load a page in postcopy case
  2743. *
  2744. * Returns 0 for success or -errno in case of error
  2745. *
  2746. * Called in postcopy mode by ram_load().
  2747. * rcu_read_lock is taken prior to this being called.
  2748. *
  2749. * @f: QEMUFile where to send the data
  2750. */
  2751. static int ram_load_postcopy(QEMUFile *f)
  2752. {
  2753. int flags = 0, ret = 0;
  2754. bool place_needed = false;
  2755. bool matches_target_page_size = false;
  2756. MigrationIncomingState *mis = migration_incoming_get_current();
  2757. /* Temporary page that is later 'placed' */
  2758. void *postcopy_host_page = mis->postcopy_tmp_page;
  2759. void *this_host = NULL;
  2760. bool all_zero = true;
  2761. int target_pages = 0;
  2762. while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
  2763. ram_addr_t addr;
  2764. void *host = NULL;
  2765. void *page_buffer = NULL;
  2766. void *place_source = NULL;
  2767. RAMBlock *block = NULL;
  2768. uint8_t ch;
  2769. int len;
  2770. addr = qemu_get_be64(f);
  2771. /*
  2772. * If qemu file error, we should stop here, and then "addr"
  2773. * may be invalid
  2774. */
  2775. ret = qemu_file_get_error(f);
  2776. if (ret) {
  2777. break;
  2778. }
  2779. flags = addr & ~TARGET_PAGE_MASK;
  2780. addr &= TARGET_PAGE_MASK;
  2781. trace_ram_load_postcopy_loop((uint64_t)addr, flags);
  2782. if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE |
  2783. RAM_SAVE_FLAG_COMPRESS_PAGE)) {
  2784. block = ram_block_from_stream(f, flags);
  2785. host = host_from_ram_block_offset(block, addr);
  2786. if (!host) {
  2787. error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
  2788. ret = -EINVAL;
  2789. break;
  2790. }
  2791. target_pages++;
  2792. matches_target_page_size = block->page_size == TARGET_PAGE_SIZE;
  2793. /*
  2794. * Postcopy requires that we place whole host pages atomically;
  2795. * these may be huge pages for RAMBlocks that are backed by
  2796. * hugetlbfs.
  2797. * To make it atomic, the data is read into a temporary page
  2798. * that's moved into place later.
  2799. * The migration protocol uses, possibly smaller, target-pages
  2800. * however the source ensures it always sends all the components
  2801. * of a host page in one chunk.
  2802. */
  2803. page_buffer = postcopy_host_page +
  2804. ((uintptr_t)host & (block->page_size - 1));
  2805. if (target_pages == 1) {
  2806. this_host = (void *)QEMU_ALIGN_DOWN((uintptr_t)host,
  2807. block->page_size);
  2808. } else {
  2809. /* not the 1st TP within the HP */
  2810. if (QEMU_ALIGN_DOWN((uintptr_t)host, block->page_size) !=
  2811. (uintptr_t)this_host) {
  2812. error_report("Non-same host page %p/%p",
  2813. host, this_host);
  2814. ret = -EINVAL;
  2815. break;
  2816. }
  2817. }
  2818. /*
  2819. * If it's the last part of a host page then we place the host
  2820. * page
  2821. */
  2822. if (target_pages == (block->page_size / TARGET_PAGE_SIZE)) {
  2823. place_needed = true;
  2824. }
  2825. place_source = postcopy_host_page;
  2826. }
  2827. switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
  2828. case RAM_SAVE_FLAG_ZERO:
  2829. ch = qemu_get_byte(f);
  2830. /*
  2831. * Can skip to set page_buffer when
  2832. * this is a zero page and (block->page_size == TARGET_PAGE_SIZE).
  2833. */
  2834. if (ch || !matches_target_page_size) {
  2835. memset(page_buffer, ch, TARGET_PAGE_SIZE);
  2836. }
  2837. if (ch) {
  2838. all_zero = false;
  2839. }
  2840. break;
  2841. case RAM_SAVE_FLAG_PAGE:
  2842. all_zero = false;
  2843. if (!matches_target_page_size) {
  2844. /* For huge pages, we always use temporary buffer */
  2845. qemu_get_buffer(f, page_buffer, TARGET_PAGE_SIZE);
  2846. } else {
  2847. /*
  2848. * For small pages that matches target page size, we
  2849. * avoid the qemu_file copy. Instead we directly use
  2850. * the buffer of QEMUFile to place the page. Note: we
  2851. * cannot do any QEMUFile operation before using that
  2852. * buffer to make sure the buffer is valid when
  2853. * placing the page.
  2854. */
  2855. qemu_get_buffer_in_place(f, (uint8_t **)&place_source,
  2856. TARGET_PAGE_SIZE);
  2857. }
  2858. break;
  2859. case RAM_SAVE_FLAG_COMPRESS_PAGE:
  2860. all_zero = false;
  2861. len = qemu_get_be32(f);
  2862. if (len < 0 || len > compressBound(TARGET_PAGE_SIZE)) {
  2863. error_report("Invalid compressed data length: %d", len);
  2864. ret = -EINVAL;
  2865. break;
  2866. }
  2867. decompress_data_with_multi_threads(f, page_buffer, len);
  2868. break;
  2869. case RAM_SAVE_FLAG_EOS:
  2870. /* normal exit */
  2871. multifd_recv_sync_main();
  2872. break;
  2873. default:
  2874. error_report("Unknown combination of migration flags: %#x"
  2875. " (postcopy mode)", flags);
  2876. ret = -EINVAL;
  2877. break;
  2878. }
  2879. /* Got the whole host page, wait for decompress before placing. */
  2880. if (place_needed) {
  2881. ret |= wait_for_decompress_done();
  2882. }
  2883. /* Detect for any possible file errors */
  2884. if (!ret && qemu_file_get_error(f)) {
  2885. ret = qemu_file_get_error(f);
  2886. }
  2887. if (!ret && place_needed) {
  2888. /* This gets called at the last target page in the host page */
  2889. void *place_dest = (void *)QEMU_ALIGN_DOWN((uintptr_t)host,
  2890. block->page_size);
  2891. if (all_zero) {
  2892. ret = postcopy_place_page_zero(mis, place_dest,
  2893. block);
  2894. } else {
  2895. ret = postcopy_place_page(mis, place_dest,
  2896. place_source, block);
  2897. }
  2898. place_needed = false;
  2899. target_pages = 0;
  2900. /* Assume we have a zero page until we detect something different */
  2901. all_zero = true;
  2902. }
  2903. }
  2904. return ret;
  2905. }
  2906. static bool postcopy_is_advised(void)
  2907. {
  2908. PostcopyState ps = postcopy_state_get();
  2909. return ps >= POSTCOPY_INCOMING_ADVISE && ps < POSTCOPY_INCOMING_END;
  2910. }
  2911. static bool postcopy_is_running(void)
  2912. {
  2913. PostcopyState ps = postcopy_state_get();
  2914. return ps >= POSTCOPY_INCOMING_LISTENING && ps < POSTCOPY_INCOMING_END;
  2915. }
  2916. /*
  2917. * Flush content of RAM cache into SVM's memory.
  2918. * Only flush the pages that be dirtied by PVM or SVM or both.
  2919. */
  2920. void colo_flush_ram_cache(void)
  2921. {
  2922. RAMBlock *block = NULL;
  2923. void *dst_host;
  2924. void *src_host;
  2925. unsigned long offset = 0;
  2926. memory_global_dirty_log_sync();
  2927. WITH_RCU_READ_LOCK_GUARD() {
  2928. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  2929. ramblock_sync_dirty_bitmap(ram_state, block);
  2930. }
  2931. }
  2932. trace_colo_flush_ram_cache_begin(ram_state->migration_dirty_pages);
  2933. WITH_RCU_READ_LOCK_GUARD() {
  2934. block = QLIST_FIRST_RCU(&ram_list.blocks);
  2935. while (block) {
  2936. offset = migration_bitmap_find_dirty(ram_state, block, offset);
  2937. if (((ram_addr_t)offset) << TARGET_PAGE_BITS
  2938. >= block->used_length) {
  2939. offset = 0;
  2940. block = QLIST_NEXT_RCU(block, next);
  2941. } else {
  2942. migration_bitmap_clear_dirty(ram_state, block, offset);
  2943. dst_host = block->host
  2944. + (((ram_addr_t)offset) << TARGET_PAGE_BITS);
  2945. src_host = block->colo_cache
  2946. + (((ram_addr_t)offset) << TARGET_PAGE_BITS);
  2947. memcpy(dst_host, src_host, TARGET_PAGE_SIZE);
  2948. }
  2949. }
  2950. }
  2951. trace_colo_flush_ram_cache_end();
  2952. }
  2953. /**
  2954. * ram_load_precopy: load pages in precopy case
  2955. *
  2956. * Returns 0 for success or -errno in case of error
  2957. *
  2958. * Called in precopy mode by ram_load().
  2959. * rcu_read_lock is taken prior to this being called.
  2960. *
  2961. * @f: QEMUFile where to send the data
  2962. */
  2963. static int ram_load_precopy(QEMUFile *f)
  2964. {
  2965. int flags = 0, ret = 0, invalid_flags = 0, len = 0, i = 0;
  2966. /* ADVISE is earlier, it shows the source has the postcopy capability on */
  2967. bool postcopy_advised = postcopy_is_advised();
  2968. if (!migrate_use_compression()) {
  2969. invalid_flags |= RAM_SAVE_FLAG_COMPRESS_PAGE;
  2970. }
  2971. while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
  2972. ram_addr_t addr, total_ram_bytes;
  2973. void *host = NULL, *host_bak = NULL;
  2974. uint8_t ch;
  2975. /*
  2976. * Yield periodically to let main loop run, but an iteration of
  2977. * the main loop is expensive, so do it each some iterations
  2978. */
  2979. if ((i & 32767) == 0 && qemu_in_coroutine()) {
  2980. aio_co_schedule(qemu_get_current_aio_context(),
  2981. qemu_coroutine_self());
  2982. qemu_coroutine_yield();
  2983. }
  2984. i++;
  2985. addr = qemu_get_be64(f);
  2986. flags = addr & ~TARGET_PAGE_MASK;
  2987. addr &= TARGET_PAGE_MASK;
  2988. if (flags & invalid_flags) {
  2989. if (flags & invalid_flags & RAM_SAVE_FLAG_COMPRESS_PAGE) {
  2990. error_report("Received an unexpected compressed page");
  2991. }
  2992. ret = -EINVAL;
  2993. break;
  2994. }
  2995. if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE |
  2996. RAM_SAVE_FLAG_COMPRESS_PAGE | RAM_SAVE_FLAG_XBZRLE)) {
  2997. RAMBlock *block = ram_block_from_stream(f, flags);
  2998. host = host_from_ram_block_offset(block, addr);
  2999. /*
  3000. * After going into COLO stage, we should not load the page
  3001. * into SVM's memory directly, we put them into colo_cache firstly.
  3002. * NOTE: We need to keep a copy of SVM's ram in colo_cache.
  3003. * Previously, we copied all these memory in preparing stage of COLO
  3004. * while we need to stop VM, which is a time-consuming process.
  3005. * Here we optimize it by a trick, back-up every page while in
  3006. * migration process while COLO is enabled, though it affects the
  3007. * speed of the migration, but it obviously reduce the downtime of
  3008. * back-up all SVM'S memory in COLO preparing stage.
  3009. */
  3010. if (migration_incoming_colo_enabled()) {
  3011. if (migration_incoming_in_colo_state()) {
  3012. /* In COLO stage, put all pages into cache temporarily */
  3013. host = colo_cache_from_block_offset(block, addr, true);
  3014. } else {
  3015. /*
  3016. * In migration stage but before COLO stage,
  3017. * Put all pages into both cache and SVM's memory.
  3018. */
  3019. host_bak = colo_cache_from_block_offset(block, addr, false);
  3020. }
  3021. }
  3022. if (!host) {
  3023. error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
  3024. ret = -EINVAL;
  3025. break;
  3026. }
  3027. if (!migration_incoming_in_colo_state()) {
  3028. ramblock_recv_bitmap_set(block, host);
  3029. }
  3030. trace_ram_load_loop(block->idstr, (uint64_t)addr, flags, host);
  3031. }
  3032. switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
  3033. case RAM_SAVE_FLAG_MEM_SIZE:
  3034. /* Synchronize RAM block list */
  3035. total_ram_bytes = addr;
  3036. while (!ret && total_ram_bytes) {
  3037. RAMBlock *block;
  3038. char id[256];
  3039. ram_addr_t length;
  3040. len = qemu_get_byte(f);
  3041. qemu_get_buffer(f, (uint8_t *)id, len);
  3042. id[len] = 0;
  3043. length = qemu_get_be64(f);
  3044. block = qemu_ram_block_by_name(id);
  3045. if (block && !qemu_ram_is_migratable(block)) {
  3046. error_report("block %s should not be migrated !", id);
  3047. ret = -EINVAL;
  3048. } else if (block) {
  3049. if (length != block->used_length) {
  3050. Error *local_err = NULL;
  3051. ret = qemu_ram_resize(block, length,
  3052. &local_err);
  3053. if (local_err) {
  3054. error_report_err(local_err);
  3055. }
  3056. }
  3057. /* For postcopy we need to check hugepage sizes match */
  3058. if (postcopy_advised &&
  3059. block->page_size != qemu_host_page_size) {
  3060. uint64_t remote_page_size = qemu_get_be64(f);
  3061. if (remote_page_size != block->page_size) {
  3062. error_report("Mismatched RAM page size %s "
  3063. "(local) %zd != %" PRId64,
  3064. id, block->page_size,
  3065. remote_page_size);
  3066. ret = -EINVAL;
  3067. }
  3068. }
  3069. if (migrate_ignore_shared()) {
  3070. hwaddr addr = qemu_get_be64(f);
  3071. if (ramblock_is_ignored(block) &&
  3072. block->mr->addr != addr) {
  3073. error_report("Mismatched GPAs for block %s "
  3074. "%" PRId64 "!= %" PRId64,
  3075. id, (uint64_t)addr,
  3076. (uint64_t)block->mr->addr);
  3077. ret = -EINVAL;
  3078. }
  3079. }
  3080. ram_control_load_hook(f, RAM_CONTROL_BLOCK_REG,
  3081. block->idstr);
  3082. } else {
  3083. error_report("Unknown ramblock \"%s\", cannot "
  3084. "accept migration", id);
  3085. ret = -EINVAL;
  3086. }
  3087. total_ram_bytes -= length;
  3088. }
  3089. break;
  3090. case RAM_SAVE_FLAG_ZERO:
  3091. ch = qemu_get_byte(f);
  3092. ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
  3093. break;
  3094. case RAM_SAVE_FLAG_PAGE:
  3095. qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
  3096. break;
  3097. case RAM_SAVE_FLAG_COMPRESS_PAGE:
  3098. len = qemu_get_be32(f);
  3099. if (len < 0 || len > compressBound(TARGET_PAGE_SIZE)) {
  3100. error_report("Invalid compressed data length: %d", len);
  3101. ret = -EINVAL;
  3102. break;
  3103. }
  3104. decompress_data_with_multi_threads(f, host, len);
  3105. break;
  3106. case RAM_SAVE_FLAG_XBZRLE:
  3107. if (load_xbzrle(f, addr, host) < 0) {
  3108. error_report("Failed to decompress XBZRLE page at "
  3109. RAM_ADDR_FMT, addr);
  3110. ret = -EINVAL;
  3111. break;
  3112. }
  3113. break;
  3114. case RAM_SAVE_FLAG_EOS:
  3115. /* normal exit */
  3116. multifd_recv_sync_main();
  3117. break;
  3118. default:
  3119. if (flags & RAM_SAVE_FLAG_HOOK) {
  3120. ram_control_load_hook(f, RAM_CONTROL_HOOK, NULL);
  3121. } else {
  3122. error_report("Unknown combination of migration flags: %#x",
  3123. flags);
  3124. ret = -EINVAL;
  3125. }
  3126. }
  3127. if (!ret) {
  3128. ret = qemu_file_get_error(f);
  3129. }
  3130. if (!ret && host_bak) {
  3131. memcpy(host_bak, host, TARGET_PAGE_SIZE);
  3132. }
  3133. }
  3134. ret |= wait_for_decompress_done();
  3135. return ret;
  3136. }
  3137. static int ram_load(QEMUFile *f, void *opaque, int version_id)
  3138. {
  3139. int ret = 0;
  3140. static uint64_t seq_iter;
  3141. /*
  3142. * If system is running in postcopy mode, page inserts to host memory must
  3143. * be atomic
  3144. */
  3145. bool postcopy_running = postcopy_is_running();
  3146. seq_iter++;
  3147. if (version_id != 4) {
  3148. return -EINVAL;
  3149. }
  3150. /*
  3151. * This RCU critical section can be very long running.
  3152. * When RCU reclaims in the code start to become numerous,
  3153. * it will be necessary to reduce the granularity of this
  3154. * critical section.
  3155. */
  3156. WITH_RCU_READ_LOCK_GUARD() {
  3157. if (postcopy_running) {
  3158. ret = ram_load_postcopy(f);
  3159. } else {
  3160. ret = ram_load_precopy(f);
  3161. }
  3162. }
  3163. trace_ram_load_complete(ret, seq_iter);
  3164. return ret;
  3165. }
  3166. static bool ram_has_postcopy(void *opaque)
  3167. {
  3168. RAMBlock *rb;
  3169. RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
  3170. if (ramblock_is_pmem(rb)) {
  3171. info_report("Block: %s, host: %p is a nvdimm memory, postcopy"
  3172. "is not supported now!", rb->idstr, rb->host);
  3173. return false;
  3174. }
  3175. }
  3176. return migrate_postcopy_ram();
  3177. }
  3178. /* Sync all the dirty bitmap with destination VM. */
  3179. static int ram_dirty_bitmap_sync_all(MigrationState *s, RAMState *rs)
  3180. {
  3181. RAMBlock *block;
  3182. QEMUFile *file = s->to_dst_file;
  3183. int ramblock_count = 0;
  3184. trace_ram_dirty_bitmap_sync_start();
  3185. RAMBLOCK_FOREACH_NOT_IGNORED(block) {
  3186. qemu_savevm_send_recv_bitmap(file, block->idstr);
  3187. trace_ram_dirty_bitmap_request(block->idstr);
  3188. ramblock_count++;
  3189. }
  3190. trace_ram_dirty_bitmap_sync_wait();
  3191. /* Wait until all the ramblocks' dirty bitmap synced */
  3192. while (ramblock_count--) {
  3193. qemu_sem_wait(&s->rp_state.rp_sem);
  3194. }
  3195. trace_ram_dirty_bitmap_sync_complete();
  3196. return 0;
  3197. }
  3198. static void ram_dirty_bitmap_reload_notify(MigrationState *s)
  3199. {
  3200. qemu_sem_post(&s->rp_state.rp_sem);
  3201. }
  3202. /*
  3203. * Read the received bitmap, revert it as the initial dirty bitmap.
  3204. * This is only used when the postcopy migration is paused but wants
  3205. * to resume from a middle point.
  3206. */
  3207. int ram_dirty_bitmap_reload(MigrationState *s, RAMBlock *block)
  3208. {
  3209. int ret = -EINVAL;
  3210. QEMUFile *file = s->rp_state.from_dst_file;
  3211. unsigned long *le_bitmap, nbits = block->used_length >> TARGET_PAGE_BITS;
  3212. uint64_t local_size = DIV_ROUND_UP(nbits, 8);
  3213. uint64_t size, end_mark;
  3214. trace_ram_dirty_bitmap_reload_begin(block->idstr);
  3215. if (s->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
  3216. error_report("%s: incorrect state %s", __func__,
  3217. MigrationStatus_str(s->state));
  3218. return -EINVAL;
  3219. }
  3220. /*
  3221. * Note: see comments in ramblock_recv_bitmap_send() on why we
  3222. * need the endianess convertion, and the paddings.
  3223. */
  3224. local_size = ROUND_UP(local_size, 8);
  3225. /* Add paddings */
  3226. le_bitmap = bitmap_new(nbits + BITS_PER_LONG);
  3227. size = qemu_get_be64(file);
  3228. /* The size of the bitmap should match with our ramblock */
  3229. if (size != local_size) {
  3230. error_report("%s: ramblock '%s' bitmap size mismatch "
  3231. "(0x%"PRIx64" != 0x%"PRIx64")", __func__,
  3232. block->idstr, size, local_size);
  3233. ret = -EINVAL;
  3234. goto out;
  3235. }
  3236. size = qemu_get_buffer(file, (uint8_t *)le_bitmap, local_size);
  3237. end_mark = qemu_get_be64(file);
  3238. ret = qemu_file_get_error(file);
  3239. if (ret || size != local_size) {
  3240. error_report("%s: read bitmap failed for ramblock '%s': %d"
  3241. " (size 0x%"PRIx64", got: 0x%"PRIx64")",
  3242. __func__, block->idstr, ret, local_size, size);
  3243. ret = -EIO;
  3244. goto out;
  3245. }
  3246. if (end_mark != RAMBLOCK_RECV_BITMAP_ENDING) {
  3247. error_report("%s: ramblock '%s' end mark incorrect: 0x%"PRIu64,
  3248. __func__, block->idstr, end_mark);
  3249. ret = -EINVAL;
  3250. goto out;
  3251. }
  3252. /*
  3253. * Endianess convertion. We are during postcopy (though paused).
  3254. * The dirty bitmap won't change. We can directly modify it.
  3255. */
  3256. bitmap_from_le(block->bmap, le_bitmap, nbits);
  3257. /*
  3258. * What we received is "received bitmap". Revert it as the initial
  3259. * dirty bitmap for this ramblock.
  3260. */
  3261. bitmap_complement(block->bmap, block->bmap, nbits);
  3262. trace_ram_dirty_bitmap_reload_complete(block->idstr);
  3263. /*
  3264. * We succeeded to sync bitmap for current ramblock. If this is
  3265. * the last one to sync, we need to notify the main send thread.
  3266. */
  3267. ram_dirty_bitmap_reload_notify(s);
  3268. ret = 0;
  3269. out:
  3270. g_free(le_bitmap);
  3271. return ret;
  3272. }
  3273. static int ram_resume_prepare(MigrationState *s, void *opaque)
  3274. {
  3275. RAMState *rs = *(RAMState **)opaque;
  3276. int ret;
  3277. ret = ram_dirty_bitmap_sync_all(s, rs);
  3278. if (ret) {
  3279. return ret;
  3280. }
  3281. ram_state_resume_prepare(rs, s->to_dst_file);
  3282. return 0;
  3283. }
  3284. static SaveVMHandlers savevm_ram_handlers = {
  3285. .save_setup = ram_save_setup,
  3286. .save_live_iterate = ram_save_iterate,
  3287. .save_live_complete_postcopy = ram_save_complete,
  3288. .save_live_complete_precopy = ram_save_complete,
  3289. .has_postcopy = ram_has_postcopy,
  3290. .save_live_pending = ram_save_pending,
  3291. .load_state = ram_load,
  3292. .save_cleanup = ram_save_cleanup,
  3293. .load_setup = ram_load_setup,
  3294. .load_cleanup = ram_load_cleanup,
  3295. .resume_prepare = ram_resume_prepare,
  3296. };
  3297. void ram_mig_init(void)
  3298. {
  3299. qemu_mutex_init(&XBZRLE.lock);
  3300. register_savevm_live("ram", 0, 4, &savevm_ram_handlers, &ram_state);
  3301. }