2
0

ram.c 134 KB

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