2
0

ram.c 113 KB

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