ram.c 144 KB

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