physmem.c 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169
  1. /*
  2. * RAM allocation and memory access
  3. *
  4. * Copyright (c) 2003 Fabrice Bellard
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "qemu/osdep.h"
  20. #include "exec/page-vary.h"
  21. #include "qapi/error.h"
  22. #include "qemu/cutils.h"
  23. #include "qemu/cacheflush.h"
  24. #include "qemu/hbitmap.h"
  25. #include "qemu/madvise.h"
  26. #include "qemu/lockable.h"
  27. #ifdef CONFIG_TCG
  28. #include "accel/tcg/cpu-ops.h"
  29. #endif /* CONFIG_TCG */
  30. #include "exec/exec-all.h"
  31. #include "exec/cputlb.h"
  32. #include "exec/page-protection.h"
  33. #include "exec/target_page.h"
  34. #include "exec/translation-block.h"
  35. #include "hw/qdev-core.h"
  36. #include "hw/qdev-properties.h"
  37. #include "hw/boards.h"
  38. #include "system/xen.h"
  39. #include "system/kvm.h"
  40. #include "system/tcg.h"
  41. #include "system/qtest.h"
  42. #include "qemu/timer.h"
  43. #include "qemu/config-file.h"
  44. #include "qemu/error-report.h"
  45. #include "qemu/qemu-print.h"
  46. #include "qemu/log.h"
  47. #include "qemu/memalign.h"
  48. #include "qemu/memfd.h"
  49. #include "exec/memory.h"
  50. #include "exec/ioport.h"
  51. #include "system/dma.h"
  52. #include "system/hostmem.h"
  53. #include "system/hw_accel.h"
  54. #include "system/xen-mapcache.h"
  55. #include "trace.h"
  56. #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
  57. #include <linux/falloc.h>
  58. #endif
  59. #include "qemu/rcu_queue.h"
  60. #include "qemu/main-loop.h"
  61. #include "system/replay.h"
  62. #include "exec/memory-internal.h"
  63. #include "exec/ram_addr.h"
  64. #include "qemu/pmem.h"
  65. #include "qapi/qapi-types-migration.h"
  66. #include "migration/blocker.h"
  67. #include "migration/cpr.h"
  68. #include "migration/options.h"
  69. #include "migration/vmstate.h"
  70. #include "qemu/range.h"
  71. #ifndef _WIN32
  72. #include "qemu/mmap-alloc.h"
  73. #endif
  74. #include "monitor/monitor.h"
  75. #ifdef CONFIG_LIBDAXCTL
  76. #include <daxctl/libdaxctl.h>
  77. #endif
  78. //#define DEBUG_SUBPAGE
  79. /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
  80. * are protected by the ramlist lock.
  81. */
  82. RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
  83. static MemoryRegion *system_memory;
  84. static MemoryRegion *system_io;
  85. AddressSpace address_space_io;
  86. AddressSpace address_space_memory;
  87. static MemoryRegion io_mem_unassigned;
  88. typedef struct PhysPageEntry PhysPageEntry;
  89. struct PhysPageEntry {
  90. /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
  91. uint32_t skip : 6;
  92. /* index into phys_sections (!skip) or phys_map_nodes (skip) */
  93. uint32_t ptr : 26;
  94. };
  95. #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
  96. /* Size of the L2 (and L3, etc) page tables. */
  97. #define ADDR_SPACE_BITS 64
  98. #define P_L2_BITS 9
  99. #define P_L2_SIZE (1 << P_L2_BITS)
  100. #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
  101. typedef PhysPageEntry Node[P_L2_SIZE];
  102. typedef struct PhysPageMap {
  103. struct rcu_head rcu;
  104. unsigned sections_nb;
  105. unsigned sections_nb_alloc;
  106. unsigned nodes_nb;
  107. unsigned nodes_nb_alloc;
  108. Node *nodes;
  109. MemoryRegionSection *sections;
  110. } PhysPageMap;
  111. struct AddressSpaceDispatch {
  112. MemoryRegionSection *mru_section;
  113. /* This is a multi-level map on the physical address space.
  114. * The bottom level has pointers to MemoryRegionSections.
  115. */
  116. PhysPageEntry phys_map;
  117. PhysPageMap map;
  118. };
  119. #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
  120. typedef struct subpage_t {
  121. MemoryRegion iomem;
  122. FlatView *fv;
  123. hwaddr base;
  124. uint16_t sub_section[];
  125. } subpage_t;
  126. #define PHYS_SECTION_UNASSIGNED 0
  127. static void io_mem_init(void);
  128. static void memory_map_init(void);
  129. static void tcg_log_global_after_sync(MemoryListener *listener);
  130. static void tcg_commit(MemoryListener *listener);
  131. static bool ram_is_cpr_compatible(RAMBlock *rb);
  132. /**
  133. * CPUAddressSpace: all the information a CPU needs about an AddressSpace
  134. * @cpu: the CPU whose AddressSpace this is
  135. * @as: the AddressSpace itself
  136. * @memory_dispatch: its dispatch pointer (cached, RCU protected)
  137. * @tcg_as_listener: listener for tracking changes to the AddressSpace
  138. */
  139. typedef struct CPUAddressSpace {
  140. CPUState *cpu;
  141. AddressSpace *as;
  142. struct AddressSpaceDispatch *memory_dispatch;
  143. MemoryListener tcg_as_listener;
  144. } CPUAddressSpace;
  145. struct DirtyBitmapSnapshot {
  146. ram_addr_t start;
  147. ram_addr_t end;
  148. unsigned long dirty[];
  149. };
  150. static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
  151. {
  152. static unsigned alloc_hint = 16;
  153. if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
  154. map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
  155. map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
  156. alloc_hint = map->nodes_nb_alloc;
  157. }
  158. }
  159. static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
  160. {
  161. unsigned i;
  162. uint32_t ret;
  163. PhysPageEntry e;
  164. PhysPageEntry *p;
  165. ret = map->nodes_nb++;
  166. p = map->nodes[ret];
  167. assert(ret != PHYS_MAP_NODE_NIL);
  168. assert(ret != map->nodes_nb_alloc);
  169. e.skip = leaf ? 0 : 1;
  170. e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
  171. for (i = 0; i < P_L2_SIZE; ++i) {
  172. memcpy(&p[i], &e, sizeof(e));
  173. }
  174. return ret;
  175. }
  176. static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
  177. hwaddr *index, uint64_t *nb, uint16_t leaf,
  178. int level)
  179. {
  180. PhysPageEntry *p;
  181. hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
  182. if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
  183. lp->ptr = phys_map_node_alloc(map, level == 0);
  184. }
  185. p = map->nodes[lp->ptr];
  186. lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
  187. while (*nb && lp < &p[P_L2_SIZE]) {
  188. if ((*index & (step - 1)) == 0 && *nb >= step) {
  189. lp->skip = 0;
  190. lp->ptr = leaf;
  191. *index += step;
  192. *nb -= step;
  193. } else {
  194. phys_page_set_level(map, lp, index, nb, leaf, level - 1);
  195. }
  196. ++lp;
  197. }
  198. }
  199. static void phys_page_set(AddressSpaceDispatch *d,
  200. hwaddr index, uint64_t nb,
  201. uint16_t leaf)
  202. {
  203. /* Wildly overreserve - it doesn't matter much. */
  204. phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
  205. phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
  206. }
  207. /* Compact a non leaf page entry. Simply detect that the entry has a single child,
  208. * and update our entry so we can skip it and go directly to the destination.
  209. */
  210. static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
  211. {
  212. unsigned valid_ptr = P_L2_SIZE;
  213. int valid = 0;
  214. PhysPageEntry *p;
  215. int i;
  216. if (lp->ptr == PHYS_MAP_NODE_NIL) {
  217. return;
  218. }
  219. p = nodes[lp->ptr];
  220. for (i = 0; i < P_L2_SIZE; i++) {
  221. if (p[i].ptr == PHYS_MAP_NODE_NIL) {
  222. continue;
  223. }
  224. valid_ptr = i;
  225. valid++;
  226. if (p[i].skip) {
  227. phys_page_compact(&p[i], nodes);
  228. }
  229. }
  230. /* We can only compress if there's only one child. */
  231. if (valid != 1) {
  232. return;
  233. }
  234. assert(valid_ptr < P_L2_SIZE);
  235. /* Don't compress if it won't fit in the # of bits we have. */
  236. if (P_L2_LEVELS >= (1 << 6) &&
  237. lp->skip + p[valid_ptr].skip >= (1 << 6)) {
  238. return;
  239. }
  240. lp->ptr = p[valid_ptr].ptr;
  241. if (!p[valid_ptr].skip) {
  242. /* If our only child is a leaf, make this a leaf. */
  243. /* By design, we should have made this node a leaf to begin with so we
  244. * should never reach here.
  245. * But since it's so simple to handle this, let's do it just in case we
  246. * change this rule.
  247. */
  248. lp->skip = 0;
  249. } else {
  250. lp->skip += p[valid_ptr].skip;
  251. }
  252. }
  253. void address_space_dispatch_compact(AddressSpaceDispatch *d)
  254. {
  255. if (d->phys_map.skip) {
  256. phys_page_compact(&d->phys_map, d->map.nodes);
  257. }
  258. }
  259. static inline bool section_covers_addr(const MemoryRegionSection *section,
  260. hwaddr addr)
  261. {
  262. /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
  263. * the section must cover the entire address space.
  264. */
  265. return int128_gethi(section->size) ||
  266. range_covers_byte(section->offset_within_address_space,
  267. int128_getlo(section->size), addr);
  268. }
  269. static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
  270. {
  271. PhysPageEntry lp = d->phys_map, *p;
  272. Node *nodes = d->map.nodes;
  273. MemoryRegionSection *sections = d->map.sections;
  274. hwaddr index = addr >> TARGET_PAGE_BITS;
  275. int i;
  276. for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
  277. if (lp.ptr == PHYS_MAP_NODE_NIL) {
  278. return &sections[PHYS_SECTION_UNASSIGNED];
  279. }
  280. p = nodes[lp.ptr];
  281. lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
  282. }
  283. if (section_covers_addr(&sections[lp.ptr], addr)) {
  284. return &sections[lp.ptr];
  285. } else {
  286. return &sections[PHYS_SECTION_UNASSIGNED];
  287. }
  288. }
  289. /* Called from RCU critical section */
  290. static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
  291. hwaddr addr,
  292. bool resolve_subpage)
  293. {
  294. MemoryRegionSection *section = qatomic_read(&d->mru_section);
  295. subpage_t *subpage;
  296. if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
  297. !section_covers_addr(section, addr)) {
  298. section = phys_page_find(d, addr);
  299. qatomic_set(&d->mru_section, section);
  300. }
  301. if (resolve_subpage && section->mr->subpage) {
  302. subpage = container_of(section->mr, subpage_t, iomem);
  303. section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
  304. }
  305. return section;
  306. }
  307. /* Called from RCU critical section */
  308. static MemoryRegionSection *
  309. address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
  310. hwaddr *plen, bool resolve_subpage)
  311. {
  312. MemoryRegionSection *section;
  313. MemoryRegion *mr;
  314. Int128 diff;
  315. section = address_space_lookup_region(d, addr, resolve_subpage);
  316. /* Compute offset within MemoryRegionSection */
  317. addr -= section->offset_within_address_space;
  318. /* Compute offset within MemoryRegion */
  319. *xlat = addr + section->offset_within_region;
  320. mr = section->mr;
  321. /* MMIO registers can be expected to perform full-width accesses based only
  322. * on their address, without considering adjacent registers that could
  323. * decode to completely different MemoryRegions. When such registers
  324. * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
  325. * regions overlap wildly. For this reason we cannot clamp the accesses
  326. * here.
  327. *
  328. * If the length is small (as is the case for address_space_ldl/stl),
  329. * everything works fine. If the incoming length is large, however,
  330. * the caller really has to do the clamping through memory_access_size.
  331. */
  332. if (memory_region_is_ram(mr)) {
  333. diff = int128_sub(section->size, int128_make64(addr));
  334. *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
  335. }
  336. return section;
  337. }
  338. /**
  339. * address_space_translate_iommu - translate an address through an IOMMU
  340. * memory region and then through the target address space.
  341. *
  342. * @iommu_mr: the IOMMU memory region that we start the translation from
  343. * @addr: the address to be translated through the MMU
  344. * @xlat: the translated address offset within the destination memory region.
  345. * It cannot be %NULL.
  346. * @plen_out: valid read/write length of the translated address. It
  347. * cannot be %NULL.
  348. * @page_mask_out: page mask for the translated address. This
  349. * should only be meaningful for IOMMU translated
  350. * addresses, since there may be huge pages that this bit
  351. * would tell. It can be %NULL if we don't care about it.
  352. * @is_write: whether the translation operation is for write
  353. * @is_mmio: whether this can be MMIO, set true if it can
  354. * @target_as: the address space targeted by the IOMMU
  355. * @attrs: transaction attributes
  356. *
  357. * This function is called from RCU critical section. It is the common
  358. * part of flatview_do_translate and address_space_translate_cached.
  359. */
  360. static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
  361. hwaddr *xlat,
  362. hwaddr *plen_out,
  363. hwaddr *page_mask_out,
  364. bool is_write,
  365. bool is_mmio,
  366. AddressSpace **target_as,
  367. MemTxAttrs attrs)
  368. {
  369. MemoryRegionSection *section;
  370. hwaddr page_mask = (hwaddr)-1;
  371. do {
  372. hwaddr addr = *xlat;
  373. IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
  374. int iommu_idx = 0;
  375. IOMMUTLBEntry iotlb;
  376. if (imrc->attrs_to_index) {
  377. iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
  378. }
  379. iotlb = imrc->translate(iommu_mr, addr, is_write ?
  380. IOMMU_WO : IOMMU_RO, iommu_idx);
  381. if (!(iotlb.perm & (1 << is_write))) {
  382. goto unassigned;
  383. }
  384. addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
  385. | (addr & iotlb.addr_mask));
  386. page_mask &= iotlb.addr_mask;
  387. *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
  388. *target_as = iotlb.target_as;
  389. section = address_space_translate_internal(
  390. address_space_to_dispatch(iotlb.target_as), addr, xlat,
  391. plen_out, is_mmio);
  392. iommu_mr = memory_region_get_iommu(section->mr);
  393. } while (unlikely(iommu_mr));
  394. if (page_mask_out) {
  395. *page_mask_out = page_mask;
  396. }
  397. return *section;
  398. unassigned:
  399. return (MemoryRegionSection) { .mr = &io_mem_unassigned };
  400. }
  401. /**
  402. * flatview_do_translate - translate an address in FlatView
  403. *
  404. * @fv: the flat view that we want to translate on
  405. * @addr: the address to be translated in above address space
  406. * @xlat: the translated address offset within memory region. It
  407. * cannot be @NULL.
  408. * @plen_out: valid read/write length of the translated address. It
  409. * can be @NULL when we don't care about it.
  410. * @page_mask_out: page mask for the translated address. This
  411. * should only be meaningful for IOMMU translated
  412. * addresses, since there may be huge pages that this bit
  413. * would tell. It can be @NULL if we don't care about it.
  414. * @is_write: whether the translation operation is for write
  415. * @is_mmio: whether this can be MMIO, set true if it can
  416. * @target_as: the address space targeted by the IOMMU
  417. * @attrs: memory transaction attributes
  418. *
  419. * This function is called from RCU critical section
  420. */
  421. static MemoryRegionSection flatview_do_translate(FlatView *fv,
  422. hwaddr addr,
  423. hwaddr *xlat,
  424. hwaddr *plen_out,
  425. hwaddr *page_mask_out,
  426. bool is_write,
  427. bool is_mmio,
  428. AddressSpace **target_as,
  429. MemTxAttrs attrs)
  430. {
  431. MemoryRegionSection *section;
  432. IOMMUMemoryRegion *iommu_mr;
  433. hwaddr plen = (hwaddr)(-1);
  434. if (!plen_out) {
  435. plen_out = &plen;
  436. }
  437. section = address_space_translate_internal(
  438. flatview_to_dispatch(fv), addr, xlat,
  439. plen_out, is_mmio);
  440. iommu_mr = memory_region_get_iommu(section->mr);
  441. if (unlikely(iommu_mr)) {
  442. return address_space_translate_iommu(iommu_mr, xlat,
  443. plen_out, page_mask_out,
  444. is_write, is_mmio,
  445. target_as, attrs);
  446. }
  447. if (page_mask_out) {
  448. /* Not behind an IOMMU, use default page size. */
  449. *page_mask_out = ~TARGET_PAGE_MASK;
  450. }
  451. return *section;
  452. }
  453. /* Called from RCU critical section */
  454. IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
  455. bool is_write, MemTxAttrs attrs)
  456. {
  457. MemoryRegionSection section;
  458. hwaddr xlat, page_mask;
  459. /*
  460. * This can never be MMIO, and we don't really care about plen,
  461. * but page mask.
  462. */
  463. section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
  464. NULL, &page_mask, is_write, false, &as,
  465. attrs);
  466. /* Illegal translation */
  467. if (section.mr == &io_mem_unassigned) {
  468. goto iotlb_fail;
  469. }
  470. /* Convert memory region offset into address space offset */
  471. xlat += section.offset_within_address_space -
  472. section.offset_within_region;
  473. return (IOMMUTLBEntry) {
  474. .target_as = as,
  475. .iova = addr & ~page_mask,
  476. .translated_addr = xlat & ~page_mask,
  477. .addr_mask = page_mask,
  478. /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
  479. .perm = IOMMU_RW,
  480. };
  481. iotlb_fail:
  482. return (IOMMUTLBEntry) {0};
  483. }
  484. /* Called from RCU critical section */
  485. MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
  486. hwaddr *plen, bool is_write,
  487. MemTxAttrs attrs)
  488. {
  489. MemoryRegion *mr;
  490. MemoryRegionSection section;
  491. AddressSpace *as = NULL;
  492. /* This can be MMIO, so setup MMIO bit. */
  493. section = flatview_do_translate(fv, addr, xlat, plen, NULL,
  494. is_write, true, &as, attrs);
  495. mr = section.mr;
  496. if (xen_enabled() && memory_access_is_direct(mr, is_write, attrs)) {
  497. hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
  498. *plen = MIN(page, *plen);
  499. }
  500. return mr;
  501. }
  502. typedef struct TCGIOMMUNotifier {
  503. IOMMUNotifier n;
  504. MemoryRegion *mr;
  505. CPUState *cpu;
  506. int iommu_idx;
  507. bool active;
  508. } TCGIOMMUNotifier;
  509. static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
  510. {
  511. TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
  512. if (!notifier->active) {
  513. return;
  514. }
  515. tlb_flush(notifier->cpu);
  516. notifier->active = false;
  517. /* We leave the notifier struct on the list to avoid reallocating it later.
  518. * Generally the number of IOMMUs a CPU deals with will be small.
  519. * In any case we can't unregister the iommu notifier from a notify
  520. * callback.
  521. */
  522. }
  523. static void tcg_register_iommu_notifier(CPUState *cpu,
  524. IOMMUMemoryRegion *iommu_mr,
  525. int iommu_idx)
  526. {
  527. /* Make sure this CPU has an IOMMU notifier registered for this
  528. * IOMMU/IOMMU index combination, so that we can flush its TLB
  529. * when the IOMMU tells us the mappings we've cached have changed.
  530. */
  531. MemoryRegion *mr = MEMORY_REGION(iommu_mr);
  532. TCGIOMMUNotifier *notifier = NULL;
  533. int i;
  534. for (i = 0; i < cpu->iommu_notifiers->len; i++) {
  535. notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
  536. if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
  537. break;
  538. }
  539. }
  540. if (i == cpu->iommu_notifiers->len) {
  541. /* Not found, add a new entry at the end of the array */
  542. cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
  543. notifier = g_new0(TCGIOMMUNotifier, 1);
  544. g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
  545. notifier->mr = mr;
  546. notifier->iommu_idx = iommu_idx;
  547. notifier->cpu = cpu;
  548. /* Rather than trying to register interest in the specific part
  549. * of the iommu's address space that we've accessed and then
  550. * expand it later as subsequent accesses touch more of it, we
  551. * just register interest in the whole thing, on the assumption
  552. * that iommu reconfiguration will be rare.
  553. */
  554. iommu_notifier_init(&notifier->n,
  555. tcg_iommu_unmap_notify,
  556. IOMMU_NOTIFIER_UNMAP,
  557. 0,
  558. HWADDR_MAX,
  559. iommu_idx);
  560. memory_region_register_iommu_notifier(notifier->mr, &notifier->n,
  561. &error_fatal);
  562. }
  563. if (!notifier->active) {
  564. notifier->active = true;
  565. }
  566. }
  567. void tcg_iommu_free_notifier_list(CPUState *cpu)
  568. {
  569. /* Destroy the CPU's notifier list */
  570. int i;
  571. TCGIOMMUNotifier *notifier;
  572. for (i = 0; i < cpu->iommu_notifiers->len; i++) {
  573. notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
  574. memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
  575. g_free(notifier);
  576. }
  577. g_array_free(cpu->iommu_notifiers, true);
  578. }
  579. void tcg_iommu_init_notifier_list(CPUState *cpu)
  580. {
  581. cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
  582. }
  583. /* Called from RCU critical section */
  584. MemoryRegionSection *
  585. address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr orig_addr,
  586. hwaddr *xlat, hwaddr *plen,
  587. MemTxAttrs attrs, int *prot)
  588. {
  589. MemoryRegionSection *section;
  590. IOMMUMemoryRegion *iommu_mr;
  591. IOMMUMemoryRegionClass *imrc;
  592. IOMMUTLBEntry iotlb;
  593. int iommu_idx;
  594. hwaddr addr = orig_addr;
  595. AddressSpaceDispatch *d = cpu->cpu_ases[asidx].memory_dispatch;
  596. for (;;) {
  597. section = address_space_translate_internal(d, addr, &addr, plen, false);
  598. iommu_mr = memory_region_get_iommu(section->mr);
  599. if (!iommu_mr) {
  600. break;
  601. }
  602. imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
  603. iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
  604. tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
  605. /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
  606. * doesn't short-cut its translation table walk.
  607. */
  608. iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
  609. addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
  610. | (addr & iotlb.addr_mask));
  611. /* Update the caller's prot bits to remove permissions the IOMMU
  612. * is giving us a failure response for. If we get down to no
  613. * permissions left at all we can give up now.
  614. */
  615. if (!(iotlb.perm & IOMMU_RO)) {
  616. *prot &= ~(PAGE_READ | PAGE_EXEC);
  617. }
  618. if (!(iotlb.perm & IOMMU_WO)) {
  619. *prot &= ~PAGE_WRITE;
  620. }
  621. if (!*prot) {
  622. goto translate_fail;
  623. }
  624. d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
  625. }
  626. assert(!memory_region_is_iommu(section->mr));
  627. *xlat = addr;
  628. return section;
  629. translate_fail:
  630. /*
  631. * We should be given a page-aligned address -- certainly
  632. * tlb_set_page_with_attrs() does so. The page offset of xlat
  633. * is used to index sections[], and PHYS_SECTION_UNASSIGNED = 0.
  634. * The page portion of xlat will be logged by memory_region_access_valid()
  635. * when this memory access is rejected, so use the original untranslated
  636. * physical address.
  637. */
  638. assert((orig_addr & ~TARGET_PAGE_MASK) == 0);
  639. *xlat = orig_addr;
  640. return &d->map.sections[PHYS_SECTION_UNASSIGNED];
  641. }
  642. void cpu_address_space_init(CPUState *cpu, int asidx,
  643. const char *prefix, MemoryRegion *mr)
  644. {
  645. CPUAddressSpace *newas;
  646. AddressSpace *as = g_new0(AddressSpace, 1);
  647. char *as_name;
  648. assert(mr);
  649. as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
  650. address_space_init(as, mr, as_name);
  651. g_free(as_name);
  652. /* Target code should have set num_ases before calling us */
  653. assert(asidx < cpu->num_ases);
  654. if (asidx == 0) {
  655. /* address space 0 gets the convenience alias */
  656. cpu->as = as;
  657. }
  658. /* KVM cannot currently support multiple address spaces. */
  659. assert(asidx == 0 || !kvm_enabled());
  660. if (!cpu->cpu_ases) {
  661. cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
  662. cpu->cpu_ases_count = cpu->num_ases;
  663. }
  664. newas = &cpu->cpu_ases[asidx];
  665. newas->cpu = cpu;
  666. newas->as = as;
  667. if (tcg_enabled()) {
  668. newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
  669. newas->tcg_as_listener.commit = tcg_commit;
  670. newas->tcg_as_listener.name = "tcg";
  671. memory_listener_register(&newas->tcg_as_listener, as);
  672. }
  673. }
  674. void cpu_address_space_destroy(CPUState *cpu, int asidx)
  675. {
  676. CPUAddressSpace *cpuas;
  677. assert(cpu->cpu_ases);
  678. assert(asidx >= 0 && asidx < cpu->num_ases);
  679. /* KVM cannot currently support multiple address spaces. */
  680. assert(asidx == 0 || !kvm_enabled());
  681. cpuas = &cpu->cpu_ases[asidx];
  682. if (tcg_enabled()) {
  683. memory_listener_unregister(&cpuas->tcg_as_listener);
  684. }
  685. address_space_destroy(cpuas->as);
  686. g_free_rcu(cpuas->as, rcu);
  687. if (asidx == 0) {
  688. /* reset the convenience alias for address space 0 */
  689. cpu->as = NULL;
  690. }
  691. if (--cpu->cpu_ases_count == 0) {
  692. g_free(cpu->cpu_ases);
  693. cpu->cpu_ases = NULL;
  694. }
  695. }
  696. AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
  697. {
  698. /* Return the AddressSpace corresponding to the specified index */
  699. return cpu->cpu_ases[asidx].as;
  700. }
  701. /* Called from RCU critical section */
  702. static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
  703. {
  704. RAMBlock *block;
  705. block = qatomic_rcu_read(&ram_list.mru_block);
  706. if (block && addr - block->offset < block->max_length) {
  707. return block;
  708. }
  709. RAMBLOCK_FOREACH(block) {
  710. if (addr - block->offset < block->max_length) {
  711. goto found;
  712. }
  713. }
  714. fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
  715. abort();
  716. found:
  717. /* It is safe to write mru_block outside the BQL. This
  718. * is what happens:
  719. *
  720. * mru_block = xxx
  721. * rcu_read_unlock()
  722. * xxx removed from list
  723. * rcu_read_lock()
  724. * read mru_block
  725. * mru_block = NULL;
  726. * call_rcu(reclaim_ramblock, xxx);
  727. * rcu_read_unlock()
  728. *
  729. * qatomic_rcu_set is not needed here. The block was already published
  730. * when it was placed into the list. Here we're just making an extra
  731. * copy of the pointer.
  732. */
  733. ram_list.mru_block = block;
  734. return block;
  735. }
  736. void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
  737. {
  738. CPUState *cpu;
  739. ram_addr_t start1;
  740. RAMBlock *block;
  741. ram_addr_t end;
  742. assert(tcg_enabled());
  743. end = TARGET_PAGE_ALIGN(start + length);
  744. start &= TARGET_PAGE_MASK;
  745. RCU_READ_LOCK_GUARD();
  746. block = qemu_get_ram_block(start);
  747. assert(block == qemu_get_ram_block(end - 1));
  748. start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
  749. CPU_FOREACH(cpu) {
  750. tlb_reset_dirty(cpu, start1, length);
  751. }
  752. }
  753. /* Note: start and end must be within the same ram block. */
  754. bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
  755. ram_addr_t length,
  756. unsigned client)
  757. {
  758. DirtyMemoryBlocks *blocks;
  759. unsigned long end, page, start_page;
  760. bool dirty = false;
  761. RAMBlock *ramblock;
  762. uint64_t mr_offset, mr_size;
  763. if (length == 0) {
  764. return false;
  765. }
  766. end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
  767. start_page = start >> TARGET_PAGE_BITS;
  768. page = start_page;
  769. WITH_RCU_READ_LOCK_GUARD() {
  770. blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
  771. ramblock = qemu_get_ram_block(start);
  772. /* Range sanity check on the ramblock */
  773. assert(start >= ramblock->offset &&
  774. start + length <= ramblock->offset + ramblock->used_length);
  775. while (page < end) {
  776. unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
  777. unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
  778. unsigned long num = MIN(end - page,
  779. DIRTY_MEMORY_BLOCK_SIZE - offset);
  780. dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
  781. offset, num);
  782. page += num;
  783. }
  784. mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
  785. mr_size = (end - start_page) << TARGET_PAGE_BITS;
  786. memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
  787. }
  788. if (dirty) {
  789. cpu_physical_memory_dirty_bits_cleared(start, length);
  790. }
  791. return dirty;
  792. }
  793. DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
  794. (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
  795. {
  796. DirtyMemoryBlocks *blocks;
  797. ram_addr_t start, first, last;
  798. unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
  799. DirtyBitmapSnapshot *snap;
  800. unsigned long page, end, dest;
  801. start = memory_region_get_ram_addr(mr);
  802. /* We know we're only called for RAM MemoryRegions */
  803. assert(start != RAM_ADDR_INVALID);
  804. start += offset;
  805. first = QEMU_ALIGN_DOWN(start, align);
  806. last = QEMU_ALIGN_UP(start + length, align);
  807. snap = g_malloc0(sizeof(*snap) +
  808. ((last - first) >> (TARGET_PAGE_BITS + 3)));
  809. snap->start = first;
  810. snap->end = last;
  811. page = first >> TARGET_PAGE_BITS;
  812. end = last >> TARGET_PAGE_BITS;
  813. dest = 0;
  814. WITH_RCU_READ_LOCK_GUARD() {
  815. blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
  816. while (page < end) {
  817. unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
  818. unsigned long ofs = page % DIRTY_MEMORY_BLOCK_SIZE;
  819. unsigned long num = MIN(end - page,
  820. DIRTY_MEMORY_BLOCK_SIZE - ofs);
  821. assert(QEMU_IS_ALIGNED(ofs, (1 << BITS_PER_LEVEL)));
  822. assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
  823. ofs >>= BITS_PER_LEVEL;
  824. bitmap_copy_and_clear_atomic(snap->dirty + dest,
  825. blocks->blocks[idx] + ofs,
  826. num);
  827. page += num;
  828. dest += num >> BITS_PER_LEVEL;
  829. }
  830. }
  831. cpu_physical_memory_dirty_bits_cleared(start, length);
  832. memory_region_clear_dirty_bitmap(mr, offset, length);
  833. return snap;
  834. }
  835. bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
  836. ram_addr_t start,
  837. ram_addr_t length)
  838. {
  839. unsigned long page, end;
  840. assert(start >= snap->start);
  841. assert(start + length <= snap->end);
  842. end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
  843. page = (start - snap->start) >> TARGET_PAGE_BITS;
  844. while (page < end) {
  845. if (test_bit(page, snap->dirty)) {
  846. return true;
  847. }
  848. page++;
  849. }
  850. return false;
  851. }
  852. /* Called from RCU critical section */
  853. hwaddr memory_region_section_get_iotlb(CPUState *cpu,
  854. MemoryRegionSection *section)
  855. {
  856. AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
  857. return section - d->map.sections;
  858. }
  859. static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
  860. uint16_t section);
  861. static subpage_t *subpage_init(FlatView *fv, hwaddr base);
  862. static uint16_t phys_section_add(PhysPageMap *map,
  863. MemoryRegionSection *section)
  864. {
  865. /* The physical section number is ORed with a page-aligned
  866. * pointer to produce the iotlb entries. Thus it should
  867. * never overflow into the page-aligned value.
  868. */
  869. assert(map->sections_nb < TARGET_PAGE_SIZE);
  870. if (map->sections_nb == map->sections_nb_alloc) {
  871. map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
  872. map->sections = g_renew(MemoryRegionSection, map->sections,
  873. map->sections_nb_alloc);
  874. }
  875. map->sections[map->sections_nb] = *section;
  876. memory_region_ref(section->mr);
  877. return map->sections_nb++;
  878. }
  879. static void phys_section_destroy(MemoryRegion *mr)
  880. {
  881. bool have_sub_page = mr->subpage;
  882. memory_region_unref(mr);
  883. if (have_sub_page) {
  884. subpage_t *subpage = container_of(mr, subpage_t, iomem);
  885. object_unref(OBJECT(&subpage->iomem));
  886. g_free(subpage);
  887. }
  888. }
  889. static void phys_sections_free(PhysPageMap *map)
  890. {
  891. while (map->sections_nb > 0) {
  892. MemoryRegionSection *section = &map->sections[--map->sections_nb];
  893. phys_section_destroy(section->mr);
  894. }
  895. g_free(map->sections);
  896. g_free(map->nodes);
  897. }
  898. static void register_subpage(FlatView *fv, MemoryRegionSection *section)
  899. {
  900. AddressSpaceDispatch *d = flatview_to_dispatch(fv);
  901. subpage_t *subpage;
  902. hwaddr base = section->offset_within_address_space
  903. & TARGET_PAGE_MASK;
  904. MemoryRegionSection *existing = phys_page_find(d, base);
  905. MemoryRegionSection subsection = {
  906. .offset_within_address_space = base,
  907. .size = int128_make64(TARGET_PAGE_SIZE),
  908. };
  909. hwaddr start, end;
  910. assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
  911. if (!(existing->mr->subpage)) {
  912. subpage = subpage_init(fv, base);
  913. subsection.fv = fv;
  914. subsection.mr = &subpage->iomem;
  915. phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
  916. phys_section_add(&d->map, &subsection));
  917. } else {
  918. subpage = container_of(existing->mr, subpage_t, iomem);
  919. }
  920. start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
  921. end = start + int128_get64(section->size) - 1;
  922. subpage_register(subpage, start, end,
  923. phys_section_add(&d->map, section));
  924. }
  925. static void register_multipage(FlatView *fv,
  926. MemoryRegionSection *section)
  927. {
  928. AddressSpaceDispatch *d = flatview_to_dispatch(fv);
  929. hwaddr start_addr = section->offset_within_address_space;
  930. uint16_t section_index = phys_section_add(&d->map, section);
  931. uint64_t num_pages = int128_get64(int128_rshift(section->size,
  932. TARGET_PAGE_BITS));
  933. assert(num_pages);
  934. phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
  935. }
  936. /*
  937. * The range in *section* may look like this:
  938. *
  939. * |s|PPPPPPP|s|
  940. *
  941. * where s stands for subpage and P for page.
  942. */
  943. void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
  944. {
  945. MemoryRegionSection remain = *section;
  946. Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
  947. /* register first subpage */
  948. if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
  949. uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
  950. - remain.offset_within_address_space;
  951. MemoryRegionSection now = remain;
  952. now.size = int128_min(int128_make64(left), now.size);
  953. register_subpage(fv, &now);
  954. if (int128_eq(remain.size, now.size)) {
  955. return;
  956. }
  957. remain.size = int128_sub(remain.size, now.size);
  958. remain.offset_within_address_space += int128_get64(now.size);
  959. remain.offset_within_region += int128_get64(now.size);
  960. }
  961. /* register whole pages */
  962. if (int128_ge(remain.size, page_size)) {
  963. MemoryRegionSection now = remain;
  964. now.size = int128_and(now.size, int128_neg(page_size));
  965. register_multipage(fv, &now);
  966. if (int128_eq(remain.size, now.size)) {
  967. return;
  968. }
  969. remain.size = int128_sub(remain.size, now.size);
  970. remain.offset_within_address_space += int128_get64(now.size);
  971. remain.offset_within_region += int128_get64(now.size);
  972. }
  973. /* register last subpage */
  974. register_subpage(fv, &remain);
  975. }
  976. void qemu_flush_coalesced_mmio_buffer(void)
  977. {
  978. if (kvm_enabled())
  979. kvm_flush_coalesced_mmio_buffer();
  980. }
  981. void qemu_mutex_lock_ramlist(void)
  982. {
  983. qemu_mutex_lock(&ram_list.mutex);
  984. }
  985. void qemu_mutex_unlock_ramlist(void)
  986. {
  987. qemu_mutex_unlock(&ram_list.mutex);
  988. }
  989. GString *ram_block_format(void)
  990. {
  991. RAMBlock *block;
  992. char *psize;
  993. GString *buf = g_string_new("");
  994. RCU_READ_LOCK_GUARD();
  995. g_string_append_printf(buf, "%24s %8s %18s %18s %18s %18s %3s\n",
  996. "Block Name", "PSize", "Offset", "Used", "Total",
  997. "HVA", "RO");
  998. RAMBLOCK_FOREACH(block) {
  999. psize = size_to_str(block->page_size);
  1000. g_string_append_printf(buf, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
  1001. " 0x%016" PRIx64 " 0x%016" PRIx64 " %3s\n",
  1002. block->idstr, psize,
  1003. (uint64_t)block->offset,
  1004. (uint64_t)block->used_length,
  1005. (uint64_t)block->max_length,
  1006. (uint64_t)(uintptr_t)block->host,
  1007. block->mr->readonly ? "ro" : "rw");
  1008. g_free(psize);
  1009. }
  1010. return buf;
  1011. }
  1012. static int find_min_backend_pagesize(Object *obj, void *opaque)
  1013. {
  1014. long *hpsize_min = opaque;
  1015. if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
  1016. HostMemoryBackend *backend = MEMORY_BACKEND(obj);
  1017. long hpsize = host_memory_backend_pagesize(backend);
  1018. if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
  1019. *hpsize_min = hpsize;
  1020. }
  1021. }
  1022. return 0;
  1023. }
  1024. static int find_max_backend_pagesize(Object *obj, void *opaque)
  1025. {
  1026. long *hpsize_max = opaque;
  1027. if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
  1028. HostMemoryBackend *backend = MEMORY_BACKEND(obj);
  1029. long hpsize = host_memory_backend_pagesize(backend);
  1030. if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
  1031. *hpsize_max = hpsize;
  1032. }
  1033. }
  1034. return 0;
  1035. }
  1036. /*
  1037. * TODO: We assume right now that all mapped host memory backends are
  1038. * used as RAM, however some might be used for different purposes.
  1039. */
  1040. long qemu_minrampagesize(void)
  1041. {
  1042. long hpsize = LONG_MAX;
  1043. Object *memdev_root = object_resolve_path("/objects", NULL);
  1044. object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
  1045. return hpsize;
  1046. }
  1047. long qemu_maxrampagesize(void)
  1048. {
  1049. long pagesize = 0;
  1050. Object *memdev_root = object_resolve_path("/objects", NULL);
  1051. object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
  1052. return pagesize;
  1053. }
  1054. #ifdef CONFIG_POSIX
  1055. static int64_t get_file_size(int fd)
  1056. {
  1057. int64_t size;
  1058. #if defined(__linux__)
  1059. struct stat st;
  1060. if (fstat(fd, &st) < 0) {
  1061. return -errno;
  1062. }
  1063. /* Special handling for devdax character devices */
  1064. if (S_ISCHR(st.st_mode)) {
  1065. g_autofree char *subsystem_path = NULL;
  1066. g_autofree char *subsystem = NULL;
  1067. subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
  1068. major(st.st_rdev), minor(st.st_rdev));
  1069. subsystem = g_file_read_link(subsystem_path, NULL);
  1070. if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
  1071. g_autofree char *size_path = NULL;
  1072. g_autofree char *size_str = NULL;
  1073. size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
  1074. major(st.st_rdev), minor(st.st_rdev));
  1075. if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
  1076. return g_ascii_strtoll(size_str, NULL, 0);
  1077. }
  1078. }
  1079. }
  1080. #endif /* defined(__linux__) */
  1081. /* st.st_size may be zero for special files yet lseek(2) works */
  1082. size = lseek(fd, 0, SEEK_END);
  1083. if (size < 0) {
  1084. return -errno;
  1085. }
  1086. return size;
  1087. }
  1088. static int64_t get_file_align(int fd)
  1089. {
  1090. int64_t align = -1;
  1091. #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
  1092. struct stat st;
  1093. if (fstat(fd, &st) < 0) {
  1094. return -errno;
  1095. }
  1096. /* Special handling for devdax character devices */
  1097. if (S_ISCHR(st.st_mode)) {
  1098. g_autofree char *path = NULL;
  1099. g_autofree char *rpath = NULL;
  1100. struct daxctl_ctx *ctx;
  1101. struct daxctl_region *region;
  1102. int rc = 0;
  1103. path = g_strdup_printf("/sys/dev/char/%d:%d",
  1104. major(st.st_rdev), minor(st.st_rdev));
  1105. rpath = realpath(path, NULL);
  1106. if (!rpath) {
  1107. return -errno;
  1108. }
  1109. rc = daxctl_new(&ctx);
  1110. if (rc) {
  1111. return -1;
  1112. }
  1113. daxctl_region_foreach(ctx, region) {
  1114. if (strstr(rpath, daxctl_region_get_path(region))) {
  1115. align = daxctl_region_get_align(region);
  1116. break;
  1117. }
  1118. }
  1119. daxctl_unref(ctx);
  1120. }
  1121. #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
  1122. return align;
  1123. }
  1124. static int file_ram_open(const char *path,
  1125. const char *region_name,
  1126. bool readonly,
  1127. bool *created)
  1128. {
  1129. char *filename;
  1130. char *sanitized_name;
  1131. char *c;
  1132. int fd = -1;
  1133. *created = false;
  1134. for (;;) {
  1135. fd = open(path, readonly ? O_RDONLY : O_RDWR);
  1136. if (fd >= 0) {
  1137. /*
  1138. * open(O_RDONLY) won't fail with EISDIR. Check manually if we
  1139. * opened a directory and fail similarly to how we fail ENOENT
  1140. * in readonly mode. Note that mkstemp() would imply O_RDWR.
  1141. */
  1142. if (readonly) {
  1143. struct stat file_stat;
  1144. if (fstat(fd, &file_stat)) {
  1145. close(fd);
  1146. if (errno == EINTR) {
  1147. continue;
  1148. }
  1149. return -errno;
  1150. } else if (S_ISDIR(file_stat.st_mode)) {
  1151. close(fd);
  1152. return -EISDIR;
  1153. }
  1154. }
  1155. /* @path names an existing file, use it */
  1156. break;
  1157. }
  1158. if (errno == ENOENT) {
  1159. if (readonly) {
  1160. /* Refuse to create new, readonly files. */
  1161. return -ENOENT;
  1162. }
  1163. /* @path names a file that doesn't exist, create it */
  1164. fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
  1165. if (fd >= 0) {
  1166. *created = true;
  1167. break;
  1168. }
  1169. } else if (errno == EISDIR) {
  1170. /* @path names a directory, create a file there */
  1171. /* Make name safe to use with mkstemp by replacing '/' with '_'. */
  1172. sanitized_name = g_strdup(region_name);
  1173. for (c = sanitized_name; *c != '\0'; c++) {
  1174. if (*c == '/') {
  1175. *c = '_';
  1176. }
  1177. }
  1178. filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
  1179. sanitized_name);
  1180. g_free(sanitized_name);
  1181. fd = mkstemp(filename);
  1182. if (fd >= 0) {
  1183. unlink(filename);
  1184. g_free(filename);
  1185. break;
  1186. }
  1187. g_free(filename);
  1188. }
  1189. if (errno != EEXIST && errno != EINTR) {
  1190. return -errno;
  1191. }
  1192. /*
  1193. * Try again on EINTR and EEXIST. The latter happens when
  1194. * something else creates the file between our two open().
  1195. */
  1196. }
  1197. return fd;
  1198. }
  1199. static void *file_ram_alloc(RAMBlock *block,
  1200. ram_addr_t memory,
  1201. int fd,
  1202. bool truncate,
  1203. off_t offset,
  1204. Error **errp)
  1205. {
  1206. uint32_t qemu_map_flags;
  1207. void *area;
  1208. block->page_size = qemu_fd_getpagesize(fd);
  1209. if (block->mr->align % block->page_size) {
  1210. error_setg(errp, "alignment 0x%" PRIx64
  1211. " must be multiples of page size 0x%zx",
  1212. block->mr->align, block->page_size);
  1213. return NULL;
  1214. } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
  1215. error_setg(errp, "alignment 0x%" PRIx64
  1216. " must be a power of two", block->mr->align);
  1217. return NULL;
  1218. } else if (offset % block->page_size) {
  1219. error_setg(errp, "offset 0x%" PRIx64
  1220. " must be multiples of page size 0x%zx",
  1221. offset, block->page_size);
  1222. return NULL;
  1223. }
  1224. block->mr->align = MAX(block->page_size, block->mr->align);
  1225. #if defined(__s390x__)
  1226. if (kvm_enabled()) {
  1227. block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
  1228. }
  1229. #endif
  1230. if (memory < block->page_size) {
  1231. error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
  1232. "or larger than page size 0x%zx",
  1233. memory, block->page_size);
  1234. return NULL;
  1235. }
  1236. memory = ROUND_UP(memory, block->page_size);
  1237. /*
  1238. * ftruncate is not supported by hugetlbfs in older
  1239. * hosts, so don't bother bailing out on errors.
  1240. * If anything goes wrong with it under other filesystems,
  1241. * mmap will fail.
  1242. *
  1243. * Do not truncate the non-empty backend file to avoid corrupting
  1244. * the existing data in the file. Disabling shrinking is not
  1245. * enough. For example, the current vNVDIMM implementation stores
  1246. * the guest NVDIMM labels at the end of the backend file. If the
  1247. * backend file is later extended, QEMU will not be able to find
  1248. * those labels. Therefore, extending the non-empty backend file
  1249. * is disabled as well.
  1250. */
  1251. if (truncate && ftruncate(fd, offset + memory)) {
  1252. perror("ftruncate");
  1253. }
  1254. qemu_map_flags = (block->flags & RAM_READONLY) ? QEMU_MAP_READONLY : 0;
  1255. qemu_map_flags |= (block->flags & RAM_SHARED) ? QEMU_MAP_SHARED : 0;
  1256. qemu_map_flags |= (block->flags & RAM_PMEM) ? QEMU_MAP_SYNC : 0;
  1257. qemu_map_flags |= (block->flags & RAM_NORESERVE) ? QEMU_MAP_NORESERVE : 0;
  1258. area = qemu_ram_mmap(fd, memory, block->mr->align, qemu_map_flags, offset);
  1259. if (area == MAP_FAILED) {
  1260. error_setg_errno(errp, errno,
  1261. "unable to map backing store for guest RAM");
  1262. return NULL;
  1263. }
  1264. block->fd = fd;
  1265. block->fd_offset = offset;
  1266. return area;
  1267. }
  1268. #endif
  1269. /* Allocate space within the ram_addr_t space that governs the
  1270. * dirty bitmaps.
  1271. * Called with the ramlist lock held.
  1272. */
  1273. static ram_addr_t find_ram_offset(ram_addr_t size)
  1274. {
  1275. RAMBlock *block, *next_block;
  1276. ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
  1277. assert(size != 0); /* it would hand out same offset multiple times */
  1278. if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
  1279. return 0;
  1280. }
  1281. RAMBLOCK_FOREACH(block) {
  1282. ram_addr_t candidate, next = RAM_ADDR_MAX;
  1283. /* Align blocks to start on a 'long' in the bitmap
  1284. * which makes the bitmap sync'ing take the fast path.
  1285. */
  1286. candidate = block->offset + block->max_length;
  1287. candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
  1288. /* Search for the closest following block
  1289. * and find the gap.
  1290. */
  1291. RAMBLOCK_FOREACH(next_block) {
  1292. if (next_block->offset >= candidate) {
  1293. next = MIN(next, next_block->offset);
  1294. }
  1295. }
  1296. /* If it fits remember our place and remember the size
  1297. * of gap, but keep going so that we might find a smaller
  1298. * gap to fill so avoiding fragmentation.
  1299. */
  1300. if (next - candidate >= size && next - candidate < mingap) {
  1301. offset = candidate;
  1302. mingap = next - candidate;
  1303. }
  1304. trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
  1305. }
  1306. if (offset == RAM_ADDR_MAX) {
  1307. fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
  1308. (uint64_t)size);
  1309. abort();
  1310. }
  1311. trace_find_ram_offset(size, offset);
  1312. return offset;
  1313. }
  1314. static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
  1315. {
  1316. int ret;
  1317. /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
  1318. if (!machine_dump_guest_core(current_machine)) {
  1319. ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
  1320. if (ret) {
  1321. perror("qemu_madvise");
  1322. fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
  1323. "but dump-guest-core=off specified\n");
  1324. }
  1325. }
  1326. }
  1327. const char *qemu_ram_get_idstr(RAMBlock *rb)
  1328. {
  1329. return rb->idstr;
  1330. }
  1331. void *qemu_ram_get_host_addr(RAMBlock *rb)
  1332. {
  1333. return rb->host;
  1334. }
  1335. ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
  1336. {
  1337. return rb->offset;
  1338. }
  1339. ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
  1340. {
  1341. return rb->used_length;
  1342. }
  1343. ram_addr_t qemu_ram_get_max_length(RAMBlock *rb)
  1344. {
  1345. return rb->max_length;
  1346. }
  1347. bool qemu_ram_is_shared(RAMBlock *rb)
  1348. {
  1349. return rb->flags & RAM_SHARED;
  1350. }
  1351. bool qemu_ram_is_noreserve(RAMBlock *rb)
  1352. {
  1353. return rb->flags & RAM_NORESERVE;
  1354. }
  1355. /* Note: Only set at the start of postcopy */
  1356. bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
  1357. {
  1358. return rb->flags & RAM_UF_ZEROPAGE;
  1359. }
  1360. void qemu_ram_set_uf_zeroable(RAMBlock *rb)
  1361. {
  1362. rb->flags |= RAM_UF_ZEROPAGE;
  1363. }
  1364. bool qemu_ram_is_migratable(RAMBlock *rb)
  1365. {
  1366. return rb->flags & RAM_MIGRATABLE;
  1367. }
  1368. void qemu_ram_set_migratable(RAMBlock *rb)
  1369. {
  1370. rb->flags |= RAM_MIGRATABLE;
  1371. }
  1372. void qemu_ram_unset_migratable(RAMBlock *rb)
  1373. {
  1374. rb->flags &= ~RAM_MIGRATABLE;
  1375. }
  1376. bool qemu_ram_is_named_file(RAMBlock *rb)
  1377. {
  1378. return rb->flags & RAM_NAMED_FILE;
  1379. }
  1380. int qemu_ram_get_fd(RAMBlock *rb)
  1381. {
  1382. return rb->fd;
  1383. }
  1384. /* Called with the BQL held. */
  1385. void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
  1386. {
  1387. RAMBlock *block;
  1388. assert(new_block);
  1389. assert(!new_block->idstr[0]);
  1390. if (dev) {
  1391. char *id = qdev_get_dev_path(dev);
  1392. if (id) {
  1393. snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
  1394. g_free(id);
  1395. }
  1396. }
  1397. pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
  1398. RCU_READ_LOCK_GUARD();
  1399. RAMBLOCK_FOREACH(block) {
  1400. if (block != new_block &&
  1401. !strcmp(block->idstr, new_block->idstr)) {
  1402. fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
  1403. new_block->idstr);
  1404. abort();
  1405. }
  1406. }
  1407. }
  1408. /* Called with the BQL held. */
  1409. void qemu_ram_unset_idstr(RAMBlock *block)
  1410. {
  1411. /* FIXME: arch_init.c assumes that this is not called throughout
  1412. * migration. Ignore the problem since hot-unplug during migration
  1413. * does not work anyway.
  1414. */
  1415. if (block) {
  1416. memset(block->idstr, 0, sizeof(block->idstr));
  1417. }
  1418. }
  1419. static char *cpr_name(MemoryRegion *mr)
  1420. {
  1421. const char *mr_name = memory_region_name(mr);
  1422. g_autofree char *id = mr->dev ? qdev_get_dev_path(mr->dev) : NULL;
  1423. if (id) {
  1424. return g_strdup_printf("%s/%s", id, mr_name);
  1425. } else {
  1426. return g_strdup(mr_name);
  1427. }
  1428. }
  1429. size_t qemu_ram_pagesize(RAMBlock *rb)
  1430. {
  1431. return rb->page_size;
  1432. }
  1433. /* Returns the largest size of page in use */
  1434. size_t qemu_ram_pagesize_largest(void)
  1435. {
  1436. RAMBlock *block;
  1437. size_t largest = 0;
  1438. RAMBLOCK_FOREACH(block) {
  1439. largest = MAX(largest, qemu_ram_pagesize(block));
  1440. }
  1441. return largest;
  1442. }
  1443. static int memory_try_enable_merging(void *addr, size_t len)
  1444. {
  1445. if (!machine_mem_merge(current_machine)) {
  1446. /* disabled by the user */
  1447. return 0;
  1448. }
  1449. return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
  1450. }
  1451. /*
  1452. * Resizing RAM while migrating can result in the migration being canceled.
  1453. * Care has to be taken if the guest might have already detected the memory.
  1454. *
  1455. * As memory core doesn't know how is memory accessed, it is up to
  1456. * resize callback to update device state and/or add assertions to detect
  1457. * misuse, if necessary.
  1458. */
  1459. int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
  1460. {
  1461. const ram_addr_t oldsize = block->used_length;
  1462. const ram_addr_t unaligned_size = newsize;
  1463. assert(block);
  1464. newsize = TARGET_PAGE_ALIGN(newsize);
  1465. newsize = REAL_HOST_PAGE_ALIGN(newsize);
  1466. if (block->used_length == newsize) {
  1467. /*
  1468. * We don't have to resize the ram block (which only knows aligned
  1469. * sizes), however, we have to notify if the unaligned size changed.
  1470. */
  1471. if (unaligned_size != memory_region_size(block->mr)) {
  1472. memory_region_set_size(block->mr, unaligned_size);
  1473. if (block->resized) {
  1474. block->resized(block->idstr, unaligned_size, block->host);
  1475. }
  1476. }
  1477. return 0;
  1478. }
  1479. if (!(block->flags & RAM_RESIZEABLE)) {
  1480. error_setg_errno(errp, EINVAL,
  1481. "Size mismatch: %s: 0x" RAM_ADDR_FMT
  1482. " != 0x" RAM_ADDR_FMT, block->idstr,
  1483. newsize, block->used_length);
  1484. return -EINVAL;
  1485. }
  1486. if (block->max_length < newsize) {
  1487. error_setg_errno(errp, EINVAL,
  1488. "Size too large: %s: 0x" RAM_ADDR_FMT
  1489. " > 0x" RAM_ADDR_FMT, block->idstr,
  1490. newsize, block->max_length);
  1491. return -EINVAL;
  1492. }
  1493. /* Notify before modifying the ram block and touching the bitmaps. */
  1494. if (block->host) {
  1495. ram_block_notify_resize(block->host, oldsize, newsize);
  1496. }
  1497. cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
  1498. block->used_length = newsize;
  1499. cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
  1500. DIRTY_CLIENTS_ALL);
  1501. memory_region_set_size(block->mr, unaligned_size);
  1502. if (block->resized) {
  1503. block->resized(block->idstr, unaligned_size, block->host);
  1504. }
  1505. return 0;
  1506. }
  1507. /*
  1508. * Trigger sync on the given ram block for range [start, start + length]
  1509. * with the backing store if one is available.
  1510. * Otherwise no-op.
  1511. * @Note: this is supposed to be a synchronous op.
  1512. */
  1513. void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
  1514. {
  1515. /* The requested range should fit in within the block range */
  1516. g_assert((start + length) <= block->used_length);
  1517. #ifdef CONFIG_LIBPMEM
  1518. /* The lack of support for pmem should not block the sync */
  1519. if (ramblock_is_pmem(block)) {
  1520. void *addr = ramblock_ptr(block, start);
  1521. pmem_persist(addr, length);
  1522. return;
  1523. }
  1524. #endif
  1525. if (block->fd >= 0) {
  1526. /**
  1527. * Case there is no support for PMEM or the memory has not been
  1528. * specified as persistent (or is not one) - use the msync.
  1529. * Less optimal but still achieves the same goal
  1530. */
  1531. void *addr = ramblock_ptr(block, start);
  1532. if (qemu_msync(addr, length, block->fd)) {
  1533. warn_report("%s: failed to sync memory range: start: "
  1534. RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
  1535. __func__, start, length);
  1536. }
  1537. }
  1538. }
  1539. /* Called with ram_list.mutex held */
  1540. static void dirty_memory_extend(ram_addr_t new_ram_size)
  1541. {
  1542. unsigned int old_num_blocks = ram_list.num_dirty_blocks;
  1543. unsigned int new_num_blocks = DIV_ROUND_UP(new_ram_size,
  1544. DIRTY_MEMORY_BLOCK_SIZE);
  1545. int i;
  1546. /* Only need to extend if block count increased */
  1547. if (new_num_blocks <= old_num_blocks) {
  1548. return;
  1549. }
  1550. for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
  1551. DirtyMemoryBlocks *old_blocks;
  1552. DirtyMemoryBlocks *new_blocks;
  1553. int j;
  1554. old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
  1555. new_blocks = g_malloc(sizeof(*new_blocks) +
  1556. sizeof(new_blocks->blocks[0]) * new_num_blocks);
  1557. if (old_num_blocks) {
  1558. memcpy(new_blocks->blocks, old_blocks->blocks,
  1559. old_num_blocks * sizeof(old_blocks->blocks[0]));
  1560. }
  1561. for (j = old_num_blocks; j < new_num_blocks; j++) {
  1562. new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
  1563. }
  1564. qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
  1565. if (old_blocks) {
  1566. g_free_rcu(old_blocks, rcu);
  1567. }
  1568. }
  1569. ram_list.num_dirty_blocks = new_num_blocks;
  1570. }
  1571. static void ram_block_add(RAMBlock *new_block, Error **errp)
  1572. {
  1573. const bool noreserve = qemu_ram_is_noreserve(new_block);
  1574. const bool shared = qemu_ram_is_shared(new_block);
  1575. RAMBlock *block;
  1576. RAMBlock *last_block = NULL;
  1577. bool free_on_error = false;
  1578. ram_addr_t ram_size;
  1579. Error *err = NULL;
  1580. qemu_mutex_lock_ramlist();
  1581. new_block->offset = find_ram_offset(new_block->max_length);
  1582. if (!new_block->host) {
  1583. if (xen_enabled()) {
  1584. xen_ram_alloc(new_block->offset, new_block->max_length,
  1585. new_block->mr, &err);
  1586. if (err) {
  1587. error_propagate(errp, err);
  1588. qemu_mutex_unlock_ramlist();
  1589. return;
  1590. }
  1591. } else {
  1592. new_block->host = qemu_anon_ram_alloc(new_block->max_length,
  1593. &new_block->mr->align,
  1594. shared, noreserve);
  1595. if (!new_block->host) {
  1596. error_setg_errno(errp, errno,
  1597. "cannot set up guest memory '%s'",
  1598. memory_region_name(new_block->mr));
  1599. qemu_mutex_unlock_ramlist();
  1600. return;
  1601. }
  1602. memory_try_enable_merging(new_block->host, new_block->max_length);
  1603. free_on_error = true;
  1604. }
  1605. }
  1606. if (new_block->flags & RAM_GUEST_MEMFD) {
  1607. int ret;
  1608. if (!kvm_enabled()) {
  1609. error_setg(errp, "cannot set up private guest memory for %s: KVM required",
  1610. object_get_typename(OBJECT(current_machine->cgs)));
  1611. goto out_free;
  1612. }
  1613. assert(new_block->guest_memfd < 0);
  1614. ret = ram_block_discard_require(true);
  1615. if (ret < 0) {
  1616. error_setg_errno(errp, -ret,
  1617. "cannot set up private guest memory: discard currently blocked");
  1618. error_append_hint(errp, "Are you using assigned devices?\n");
  1619. goto out_free;
  1620. }
  1621. new_block->guest_memfd = kvm_create_guest_memfd(new_block->max_length,
  1622. 0, errp);
  1623. if (new_block->guest_memfd < 0) {
  1624. qemu_mutex_unlock_ramlist();
  1625. goto out_free;
  1626. }
  1627. /*
  1628. * Add a specific guest_memfd blocker if a generic one would not be
  1629. * added by ram_block_add_cpr_blocker.
  1630. */
  1631. if (ram_is_cpr_compatible(new_block)) {
  1632. error_setg(&new_block->cpr_blocker,
  1633. "Memory region %s uses guest_memfd, "
  1634. "which is not supported with CPR.",
  1635. memory_region_name(new_block->mr));
  1636. migrate_add_blocker_modes(&new_block->cpr_blocker, errp,
  1637. MIG_MODE_CPR_TRANSFER, -1);
  1638. }
  1639. }
  1640. ram_size = (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS;
  1641. dirty_memory_extend(ram_size);
  1642. /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
  1643. * QLIST (which has an RCU-friendly variant) does not have insertion at
  1644. * tail, so save the last element in last_block.
  1645. */
  1646. RAMBLOCK_FOREACH(block) {
  1647. last_block = block;
  1648. if (block->max_length < new_block->max_length) {
  1649. break;
  1650. }
  1651. }
  1652. if (block) {
  1653. QLIST_INSERT_BEFORE_RCU(block, new_block, next);
  1654. } else if (last_block) {
  1655. QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
  1656. } else { /* list is empty */
  1657. QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
  1658. }
  1659. ram_list.mru_block = NULL;
  1660. /* Write list before version */
  1661. smp_wmb();
  1662. ram_list.version++;
  1663. qemu_mutex_unlock_ramlist();
  1664. cpu_physical_memory_set_dirty_range(new_block->offset,
  1665. new_block->used_length,
  1666. DIRTY_CLIENTS_ALL);
  1667. if (new_block->host) {
  1668. qemu_ram_setup_dump(new_block->host, new_block->max_length);
  1669. qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
  1670. /*
  1671. * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
  1672. * Configure it unless the machine is a qtest server, in which case
  1673. * KVM is not used and it may be forked (eg for fuzzing purposes).
  1674. */
  1675. if (!qtest_enabled()) {
  1676. qemu_madvise(new_block->host, new_block->max_length,
  1677. QEMU_MADV_DONTFORK);
  1678. }
  1679. ram_block_notify_add(new_block->host, new_block->used_length,
  1680. new_block->max_length);
  1681. }
  1682. return;
  1683. out_free:
  1684. if (free_on_error) {
  1685. qemu_anon_ram_free(new_block->host, new_block->max_length);
  1686. new_block->host = NULL;
  1687. }
  1688. }
  1689. #ifdef CONFIG_POSIX
  1690. RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, ram_addr_t max_size,
  1691. qemu_ram_resize_cb resized, MemoryRegion *mr,
  1692. uint32_t ram_flags, int fd, off_t offset,
  1693. bool grow,
  1694. Error **errp)
  1695. {
  1696. ERRP_GUARD();
  1697. RAMBlock *new_block;
  1698. Error *local_err = NULL;
  1699. int64_t file_size, file_align, share_flags;
  1700. share_flags = ram_flags & (RAM_PRIVATE | RAM_SHARED);
  1701. assert(share_flags != (RAM_SHARED | RAM_PRIVATE));
  1702. ram_flags &= ~RAM_PRIVATE;
  1703. /* Just support these ram flags by now. */
  1704. assert((ram_flags & ~(RAM_SHARED | RAM_PMEM | RAM_NORESERVE |
  1705. RAM_PROTECTED | RAM_NAMED_FILE | RAM_READONLY |
  1706. RAM_READONLY_FD | RAM_GUEST_MEMFD |
  1707. RAM_RESIZEABLE)) == 0);
  1708. assert(max_size >= size);
  1709. if (xen_enabled()) {
  1710. error_setg(errp, "-mem-path not supported with Xen");
  1711. return NULL;
  1712. }
  1713. if (kvm_enabled() && !kvm_has_sync_mmu()) {
  1714. error_setg(errp,
  1715. "host lacks kvm mmu notifiers, -mem-path unsupported");
  1716. return NULL;
  1717. }
  1718. size = TARGET_PAGE_ALIGN(size);
  1719. size = REAL_HOST_PAGE_ALIGN(size);
  1720. max_size = TARGET_PAGE_ALIGN(max_size);
  1721. max_size = REAL_HOST_PAGE_ALIGN(max_size);
  1722. file_size = get_file_size(fd);
  1723. if (file_size && file_size < offset + max_size && !grow) {
  1724. error_setg(errp, "%s backing store size 0x%" PRIx64
  1725. " is too small for 'size' option 0x" RAM_ADDR_FMT
  1726. " plus 'offset' option 0x%" PRIx64,
  1727. memory_region_name(mr), file_size, max_size,
  1728. (uint64_t)offset);
  1729. return NULL;
  1730. }
  1731. file_align = get_file_align(fd);
  1732. if (file_align > 0 && file_align > mr->align) {
  1733. error_setg(errp, "backing store align 0x%" PRIx64
  1734. " is larger than 'align' option 0x%" PRIx64,
  1735. file_align, mr->align);
  1736. return NULL;
  1737. }
  1738. new_block = g_malloc0(sizeof(*new_block));
  1739. new_block->mr = mr;
  1740. new_block->used_length = size;
  1741. new_block->max_length = max_size;
  1742. new_block->resized = resized;
  1743. new_block->flags = ram_flags;
  1744. new_block->guest_memfd = -1;
  1745. new_block->host = file_ram_alloc(new_block, max_size, fd,
  1746. file_size < offset + max_size,
  1747. offset, errp);
  1748. if (!new_block->host) {
  1749. g_free(new_block);
  1750. return NULL;
  1751. }
  1752. ram_block_add(new_block, &local_err);
  1753. if (local_err) {
  1754. g_free(new_block);
  1755. error_propagate(errp, local_err);
  1756. return NULL;
  1757. }
  1758. return new_block;
  1759. }
  1760. RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
  1761. uint32_t ram_flags, const char *mem_path,
  1762. off_t offset, Error **errp)
  1763. {
  1764. int fd;
  1765. bool created;
  1766. RAMBlock *block;
  1767. fd = file_ram_open(mem_path, memory_region_name(mr),
  1768. !!(ram_flags & RAM_READONLY_FD), &created);
  1769. if (fd < 0) {
  1770. error_setg_errno(errp, -fd, "can't open backing store %s for guest RAM",
  1771. mem_path);
  1772. if (!(ram_flags & RAM_READONLY_FD) && !(ram_flags & RAM_SHARED) &&
  1773. fd == -EACCES) {
  1774. /*
  1775. * If we can open the file R/O (note: will never create a new file)
  1776. * and we are dealing with a private mapping, there are still ways
  1777. * to consume such files and get RAM instead of ROM.
  1778. */
  1779. fd = file_ram_open(mem_path, memory_region_name(mr), true,
  1780. &created);
  1781. if (fd < 0) {
  1782. return NULL;
  1783. }
  1784. assert(!created);
  1785. close(fd);
  1786. error_append_hint(errp, "Consider opening the backing store"
  1787. " read-only but still creating writable RAM using"
  1788. " '-object memory-backend-file,readonly=on,rom=off...'"
  1789. " (see \"VM templating\" documentation)\n");
  1790. }
  1791. return NULL;
  1792. }
  1793. block = qemu_ram_alloc_from_fd(size, size, NULL, mr, ram_flags, fd, offset,
  1794. false, errp);
  1795. if (!block) {
  1796. if (created) {
  1797. unlink(mem_path);
  1798. }
  1799. close(fd);
  1800. return NULL;
  1801. }
  1802. return block;
  1803. }
  1804. #endif
  1805. #ifdef CONFIG_POSIX
  1806. /*
  1807. * Create MAP_SHARED RAMBlocks by mmap'ing a file descriptor, so it can be
  1808. * shared with another process if CPR is being used. Use memfd if available
  1809. * because it has no size limits, else use POSIX shm.
  1810. */
  1811. static int qemu_ram_get_shared_fd(const char *name, bool *reused, Error **errp)
  1812. {
  1813. int fd = cpr_find_fd(name, 0);
  1814. if (fd >= 0) {
  1815. *reused = true;
  1816. return fd;
  1817. }
  1818. if (qemu_memfd_check(0)) {
  1819. fd = qemu_memfd_create(name, 0, 0, 0, 0, errp);
  1820. } else {
  1821. fd = qemu_shm_alloc(0, errp);
  1822. }
  1823. if (fd >= 0) {
  1824. cpr_save_fd(name, 0, fd);
  1825. }
  1826. *reused = false;
  1827. return fd;
  1828. }
  1829. #endif
  1830. static
  1831. RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
  1832. qemu_ram_resize_cb resized,
  1833. void *host, uint32_t ram_flags,
  1834. MemoryRegion *mr, Error **errp)
  1835. {
  1836. RAMBlock *new_block;
  1837. Error *local_err = NULL;
  1838. int align, share_flags;
  1839. share_flags = ram_flags & (RAM_PRIVATE | RAM_SHARED);
  1840. assert(share_flags != (RAM_SHARED | RAM_PRIVATE));
  1841. ram_flags &= ~RAM_PRIVATE;
  1842. assert((ram_flags & ~(RAM_SHARED | RAM_RESIZEABLE | RAM_PREALLOC |
  1843. RAM_NORESERVE | RAM_GUEST_MEMFD)) == 0);
  1844. assert(!host ^ (ram_flags & RAM_PREALLOC));
  1845. assert(max_size >= size);
  1846. #ifdef CONFIG_POSIX /* ignore RAM_SHARED for Windows */
  1847. if (!host) {
  1848. if (!share_flags && current_machine->aux_ram_share) {
  1849. ram_flags |= RAM_SHARED;
  1850. }
  1851. if (ram_flags & RAM_SHARED) {
  1852. bool reused;
  1853. g_autofree char *name = cpr_name(mr);
  1854. int fd = qemu_ram_get_shared_fd(name, &reused, errp);
  1855. if (fd < 0) {
  1856. return NULL;
  1857. }
  1858. /* Use same alignment as qemu_anon_ram_alloc */
  1859. mr->align = QEMU_VMALLOC_ALIGN;
  1860. /*
  1861. * This can fail if the shm mount size is too small, or alloc from
  1862. * fd is not supported, but previous QEMU versions that called
  1863. * qemu_anon_ram_alloc for anonymous shared memory could have
  1864. * succeeded. Quietly fail and fall back.
  1865. *
  1866. * After cpr-transfer, new QEMU could create a memory region
  1867. * with a larger max size than old, so pass reused to grow the
  1868. * region if necessary. The extra space will be usable after a
  1869. * guest reset.
  1870. */
  1871. new_block = qemu_ram_alloc_from_fd(size, max_size, resized, mr,
  1872. ram_flags, fd, 0, reused, NULL);
  1873. if (new_block) {
  1874. trace_qemu_ram_alloc_shared(name, new_block->used_length,
  1875. new_block->max_length, fd,
  1876. new_block->host);
  1877. return new_block;
  1878. }
  1879. cpr_delete_fd(name, 0);
  1880. close(fd);
  1881. /* fall back to anon allocation */
  1882. }
  1883. }
  1884. #endif
  1885. align = qemu_real_host_page_size();
  1886. align = MAX(align, TARGET_PAGE_SIZE);
  1887. size = ROUND_UP(size, align);
  1888. max_size = ROUND_UP(max_size, align);
  1889. new_block = g_malloc0(sizeof(*new_block));
  1890. new_block->mr = mr;
  1891. new_block->resized = resized;
  1892. new_block->used_length = size;
  1893. new_block->max_length = max_size;
  1894. new_block->fd = -1;
  1895. new_block->guest_memfd = -1;
  1896. new_block->page_size = qemu_real_host_page_size();
  1897. new_block->host = host;
  1898. new_block->flags = ram_flags;
  1899. ram_block_add(new_block, &local_err);
  1900. if (local_err) {
  1901. g_free(new_block);
  1902. error_propagate(errp, local_err);
  1903. return NULL;
  1904. }
  1905. return new_block;
  1906. }
  1907. RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
  1908. MemoryRegion *mr, Error **errp)
  1909. {
  1910. return qemu_ram_alloc_internal(size, size, NULL, host, RAM_PREALLOC, mr,
  1911. errp);
  1912. }
  1913. RAMBlock *qemu_ram_alloc(ram_addr_t size, uint32_t ram_flags,
  1914. MemoryRegion *mr, Error **errp)
  1915. {
  1916. assert((ram_flags & ~(RAM_SHARED | RAM_NORESERVE | RAM_GUEST_MEMFD |
  1917. RAM_PRIVATE)) == 0);
  1918. return qemu_ram_alloc_internal(size, size, NULL, NULL, ram_flags, mr, errp);
  1919. }
  1920. RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
  1921. qemu_ram_resize_cb resized,
  1922. MemoryRegion *mr, Error **errp)
  1923. {
  1924. return qemu_ram_alloc_internal(size, maxsz, resized, NULL,
  1925. RAM_RESIZEABLE, mr, errp);
  1926. }
  1927. static void reclaim_ramblock(RAMBlock *block)
  1928. {
  1929. if (block->flags & RAM_PREALLOC) {
  1930. ;
  1931. } else if (xen_enabled()) {
  1932. xen_invalidate_map_cache_entry(block->host);
  1933. #ifndef _WIN32
  1934. } else if (block->fd >= 0) {
  1935. qemu_ram_munmap(block->fd, block->host, block->max_length);
  1936. close(block->fd);
  1937. #endif
  1938. } else {
  1939. qemu_anon_ram_free(block->host, block->max_length);
  1940. }
  1941. if (block->guest_memfd >= 0) {
  1942. close(block->guest_memfd);
  1943. ram_block_discard_require(false);
  1944. }
  1945. g_free(block);
  1946. }
  1947. void qemu_ram_free(RAMBlock *block)
  1948. {
  1949. g_autofree char *name = NULL;
  1950. if (!block) {
  1951. return;
  1952. }
  1953. if (block->host) {
  1954. ram_block_notify_remove(block->host, block->used_length,
  1955. block->max_length);
  1956. }
  1957. qemu_mutex_lock_ramlist();
  1958. name = cpr_name(block->mr);
  1959. cpr_delete_fd(name, 0);
  1960. QLIST_REMOVE_RCU(block, next);
  1961. ram_list.mru_block = NULL;
  1962. /* Write list before version */
  1963. smp_wmb();
  1964. ram_list.version++;
  1965. call_rcu(block, reclaim_ramblock, rcu);
  1966. qemu_mutex_unlock_ramlist();
  1967. }
  1968. #ifndef _WIN32
  1969. /* Simply remap the given VM memory location from start to start+length */
  1970. static int qemu_ram_remap_mmap(RAMBlock *block, uint64_t start, size_t length)
  1971. {
  1972. int flags, prot;
  1973. void *area;
  1974. void *host_startaddr = block->host + start;
  1975. assert(block->fd < 0);
  1976. flags = MAP_FIXED | MAP_ANONYMOUS;
  1977. flags |= block->flags & RAM_SHARED ? MAP_SHARED : MAP_PRIVATE;
  1978. flags |= block->flags & RAM_NORESERVE ? MAP_NORESERVE : 0;
  1979. prot = PROT_READ;
  1980. prot |= block->flags & RAM_READONLY ? 0 : PROT_WRITE;
  1981. area = mmap(host_startaddr, length, prot, flags, -1, 0);
  1982. return area != host_startaddr ? -errno : 0;
  1983. }
  1984. /*
  1985. * qemu_ram_remap - remap a single RAM page
  1986. *
  1987. * @addr: address in ram_addr_t address space.
  1988. *
  1989. * This function will try remapping a single page of guest RAM identified by
  1990. * @addr, essentially discarding memory to recover from previously poisoned
  1991. * memory (MCE). The page size depends on the RAMBlock (i.e., hugetlb). @addr
  1992. * does not have to point at the start of the page.
  1993. *
  1994. * This function is only to be used during system resets; it will kill the
  1995. * VM if remapping failed.
  1996. */
  1997. void qemu_ram_remap(ram_addr_t addr)
  1998. {
  1999. RAMBlock *block;
  2000. uint64_t offset;
  2001. void *vaddr;
  2002. size_t page_size;
  2003. RAMBLOCK_FOREACH(block) {
  2004. offset = addr - block->offset;
  2005. if (offset < block->max_length) {
  2006. /* Respect the pagesize of our RAMBlock */
  2007. page_size = qemu_ram_pagesize(block);
  2008. offset = QEMU_ALIGN_DOWN(offset, page_size);
  2009. vaddr = ramblock_ptr(block, offset);
  2010. if (block->flags & RAM_PREALLOC) {
  2011. ;
  2012. } else if (xen_enabled()) {
  2013. abort();
  2014. } else {
  2015. if (ram_block_discard_range(block, offset, page_size) != 0) {
  2016. /*
  2017. * Fall back to using mmap() only for anonymous mapping,
  2018. * as if a backing file is associated we may not be able
  2019. * to recover the memory in all cases.
  2020. * So don't take the risk of using only mmap and fail now.
  2021. */
  2022. if (block->fd >= 0) {
  2023. error_report("Could not remap RAM %s:%" PRIx64 "+%"
  2024. PRIx64 " +%zx", block->idstr, offset,
  2025. block->fd_offset, page_size);
  2026. exit(1);
  2027. }
  2028. if (qemu_ram_remap_mmap(block, offset, page_size) != 0) {
  2029. error_report("Could not remap RAM %s:%" PRIx64 " +%zx",
  2030. block->idstr, offset, page_size);
  2031. exit(1);
  2032. }
  2033. }
  2034. memory_try_enable_merging(vaddr, page_size);
  2035. qemu_ram_setup_dump(vaddr, page_size);
  2036. }
  2037. break;
  2038. }
  2039. }
  2040. }
  2041. #endif /* !_WIN32 */
  2042. /*
  2043. * Return a host pointer to guest's ram.
  2044. * For Xen, foreign mappings get created if they don't already exist.
  2045. *
  2046. * @block: block for the RAM to lookup (optional and may be NULL).
  2047. * @addr: address within the memory region.
  2048. * @size: pointer to requested size (optional and may be NULL).
  2049. * size may get modified and return a value smaller than
  2050. * what was requested.
  2051. * @lock: wether to lock the mapping in xen-mapcache until invalidated.
  2052. * @is_write: hint wether to map RW or RO in the xen-mapcache.
  2053. * (optional and may always be set to true).
  2054. *
  2055. * Called within RCU critical section.
  2056. */
  2057. static void *qemu_ram_ptr_length(RAMBlock *block, ram_addr_t addr,
  2058. hwaddr *size, bool lock,
  2059. bool is_write)
  2060. {
  2061. hwaddr len = 0;
  2062. if (size && *size == 0) {
  2063. return NULL;
  2064. }
  2065. if (block == NULL) {
  2066. block = qemu_get_ram_block(addr);
  2067. addr -= block->offset;
  2068. }
  2069. if (size) {
  2070. *size = MIN(*size, block->max_length - addr);
  2071. len = *size;
  2072. }
  2073. if (xen_enabled() && block->host == NULL) {
  2074. /* We need to check if the requested address is in the RAM
  2075. * because we don't want to map the entire memory in QEMU.
  2076. * In that case just map the requested area.
  2077. */
  2078. if (xen_mr_is_memory(block->mr)) {
  2079. return xen_map_cache(block->mr, block->offset + addr,
  2080. len, block->offset,
  2081. lock, lock, is_write);
  2082. }
  2083. block->host = xen_map_cache(block->mr, block->offset,
  2084. block->max_length,
  2085. block->offset,
  2086. 1, lock, is_write);
  2087. }
  2088. return ramblock_ptr(block, addr);
  2089. }
  2090. /*
  2091. * Return a host pointer to ram allocated with qemu_ram_alloc.
  2092. * This should not be used for general purpose DMA. Use address_space_map
  2093. * or address_space_rw instead. For local memory (e.g. video ram) that the
  2094. * device owns, use memory_region_get_ram_ptr.
  2095. *
  2096. * Called within RCU critical section.
  2097. */
  2098. void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
  2099. {
  2100. return qemu_ram_ptr_length(ram_block, addr, NULL, false, true);
  2101. }
  2102. /* Return the offset of a hostpointer within a ramblock */
  2103. ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
  2104. {
  2105. ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
  2106. assert((uintptr_t)host >= (uintptr_t)rb->host);
  2107. assert(res < rb->max_length);
  2108. return res;
  2109. }
  2110. RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
  2111. ram_addr_t *offset)
  2112. {
  2113. RAMBlock *block;
  2114. uint8_t *host = ptr;
  2115. if (xen_enabled()) {
  2116. ram_addr_t ram_addr;
  2117. RCU_READ_LOCK_GUARD();
  2118. ram_addr = xen_ram_addr_from_mapcache(ptr);
  2119. if (ram_addr == RAM_ADDR_INVALID) {
  2120. return NULL;
  2121. }
  2122. block = qemu_get_ram_block(ram_addr);
  2123. if (block) {
  2124. *offset = ram_addr - block->offset;
  2125. }
  2126. return block;
  2127. }
  2128. RCU_READ_LOCK_GUARD();
  2129. block = qatomic_rcu_read(&ram_list.mru_block);
  2130. if (block && block->host && host - block->host < block->max_length) {
  2131. goto found;
  2132. }
  2133. RAMBLOCK_FOREACH(block) {
  2134. /* This case append when the block is not mapped. */
  2135. if (block->host == NULL) {
  2136. continue;
  2137. }
  2138. if (host - block->host < block->max_length) {
  2139. goto found;
  2140. }
  2141. }
  2142. return NULL;
  2143. found:
  2144. *offset = (host - block->host);
  2145. if (round_offset) {
  2146. *offset &= TARGET_PAGE_MASK;
  2147. }
  2148. return block;
  2149. }
  2150. /*
  2151. * Finds the named RAMBlock
  2152. *
  2153. * name: The name of RAMBlock to find
  2154. *
  2155. * Returns: RAMBlock (or NULL if not found)
  2156. */
  2157. RAMBlock *qemu_ram_block_by_name(const char *name)
  2158. {
  2159. RAMBlock *block;
  2160. RAMBLOCK_FOREACH(block) {
  2161. if (!strcmp(name, block->idstr)) {
  2162. return block;
  2163. }
  2164. }
  2165. return NULL;
  2166. }
  2167. /*
  2168. * Some of the system routines need to translate from a host pointer
  2169. * (typically a TLB entry) back to a ram offset.
  2170. */
  2171. ram_addr_t qemu_ram_addr_from_host(void *ptr)
  2172. {
  2173. RAMBlock *block;
  2174. ram_addr_t offset;
  2175. block = qemu_ram_block_from_host(ptr, false, &offset);
  2176. if (!block) {
  2177. return RAM_ADDR_INVALID;
  2178. }
  2179. return block->offset + offset;
  2180. }
  2181. ram_addr_t qemu_ram_addr_from_host_nofail(void *ptr)
  2182. {
  2183. ram_addr_t ram_addr;
  2184. ram_addr = qemu_ram_addr_from_host(ptr);
  2185. if (ram_addr == RAM_ADDR_INVALID) {
  2186. error_report("Bad ram pointer %p", ptr);
  2187. abort();
  2188. }
  2189. return ram_addr;
  2190. }
  2191. static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
  2192. MemTxAttrs attrs, void *buf, hwaddr len);
  2193. static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
  2194. const void *buf, hwaddr len);
  2195. static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
  2196. bool is_write, MemTxAttrs attrs);
  2197. static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
  2198. unsigned len, MemTxAttrs attrs)
  2199. {
  2200. subpage_t *subpage = opaque;
  2201. uint8_t buf[8];
  2202. MemTxResult res;
  2203. #if defined(DEBUG_SUBPAGE)
  2204. printf("%s: subpage %p len %u addr " HWADDR_FMT_plx "\n", __func__,
  2205. subpage, len, addr);
  2206. #endif
  2207. res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
  2208. if (res) {
  2209. return res;
  2210. }
  2211. *data = ldn_p(buf, len);
  2212. return MEMTX_OK;
  2213. }
  2214. static MemTxResult subpage_write(void *opaque, hwaddr addr,
  2215. uint64_t value, unsigned len, MemTxAttrs attrs)
  2216. {
  2217. subpage_t *subpage = opaque;
  2218. uint8_t buf[8];
  2219. #if defined(DEBUG_SUBPAGE)
  2220. printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
  2221. " value %"PRIx64"\n",
  2222. __func__, subpage, len, addr, value);
  2223. #endif
  2224. stn_p(buf, len, value);
  2225. return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
  2226. }
  2227. static bool subpage_accepts(void *opaque, hwaddr addr,
  2228. unsigned len, bool is_write,
  2229. MemTxAttrs attrs)
  2230. {
  2231. subpage_t *subpage = opaque;
  2232. #if defined(DEBUG_SUBPAGE)
  2233. printf("%s: subpage %p %c len %u addr " HWADDR_FMT_plx "\n",
  2234. __func__, subpage, is_write ? 'w' : 'r', len, addr);
  2235. #endif
  2236. return flatview_access_valid(subpage->fv, addr + subpage->base,
  2237. len, is_write, attrs);
  2238. }
  2239. static const MemoryRegionOps subpage_ops = {
  2240. .read_with_attrs = subpage_read,
  2241. .write_with_attrs = subpage_write,
  2242. .impl.min_access_size = 1,
  2243. .impl.max_access_size = 8,
  2244. .valid.min_access_size = 1,
  2245. .valid.max_access_size = 8,
  2246. .valid.accepts = subpage_accepts,
  2247. .endianness = DEVICE_NATIVE_ENDIAN,
  2248. };
  2249. static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
  2250. uint16_t section)
  2251. {
  2252. int idx, eidx;
  2253. if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
  2254. return -1;
  2255. idx = SUBPAGE_IDX(start);
  2256. eidx = SUBPAGE_IDX(end);
  2257. #if defined(DEBUG_SUBPAGE)
  2258. printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
  2259. __func__, mmio, start, end, idx, eidx, section);
  2260. #endif
  2261. for (; idx <= eidx; idx++) {
  2262. mmio->sub_section[idx] = section;
  2263. }
  2264. return 0;
  2265. }
  2266. static subpage_t *subpage_init(FlatView *fv, hwaddr base)
  2267. {
  2268. subpage_t *mmio;
  2269. /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
  2270. mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
  2271. mmio->fv = fv;
  2272. mmio->base = base;
  2273. memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
  2274. NULL, TARGET_PAGE_SIZE);
  2275. mmio->iomem.subpage = true;
  2276. #if defined(DEBUG_SUBPAGE)
  2277. printf("%s: %p base " HWADDR_FMT_plx " len %08x\n", __func__,
  2278. mmio, base, TARGET_PAGE_SIZE);
  2279. #endif
  2280. return mmio;
  2281. }
  2282. static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
  2283. {
  2284. assert(fv);
  2285. MemoryRegionSection section = {
  2286. .fv = fv,
  2287. .mr = mr,
  2288. .offset_within_address_space = 0,
  2289. .offset_within_region = 0,
  2290. .size = int128_2_64(),
  2291. };
  2292. return phys_section_add(map, &section);
  2293. }
  2294. MemoryRegionSection *iotlb_to_section(CPUState *cpu,
  2295. hwaddr index, MemTxAttrs attrs)
  2296. {
  2297. int asidx = cpu_asidx_from_attrs(cpu, attrs);
  2298. CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
  2299. AddressSpaceDispatch *d = cpuas->memory_dispatch;
  2300. int section_index = index & ~TARGET_PAGE_MASK;
  2301. MemoryRegionSection *ret;
  2302. assert(section_index < d->map.sections_nb);
  2303. ret = d->map.sections + section_index;
  2304. assert(ret->mr);
  2305. assert(ret->mr->ops);
  2306. return ret;
  2307. }
  2308. static void io_mem_init(void)
  2309. {
  2310. memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
  2311. NULL, UINT64_MAX);
  2312. }
  2313. AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
  2314. {
  2315. AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
  2316. uint16_t n;
  2317. n = dummy_section(&d->map, fv, &io_mem_unassigned);
  2318. assert(n == PHYS_SECTION_UNASSIGNED);
  2319. d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
  2320. return d;
  2321. }
  2322. void address_space_dispatch_free(AddressSpaceDispatch *d)
  2323. {
  2324. phys_sections_free(&d->map);
  2325. g_free(d);
  2326. }
  2327. static void do_nothing(CPUState *cpu, run_on_cpu_data d)
  2328. {
  2329. }
  2330. static void tcg_log_global_after_sync(MemoryListener *listener)
  2331. {
  2332. CPUAddressSpace *cpuas;
  2333. /* Wait for the CPU to end the current TB. This avoids the following
  2334. * incorrect race:
  2335. *
  2336. * vCPU migration
  2337. * ---------------------- -------------------------
  2338. * TLB check -> slow path
  2339. * notdirty_mem_write
  2340. * write to RAM
  2341. * mark dirty
  2342. * clear dirty flag
  2343. * TLB check -> fast path
  2344. * read memory
  2345. * write to RAM
  2346. *
  2347. * by pushing the migration thread's memory read after the vCPU thread has
  2348. * written the memory.
  2349. */
  2350. if (replay_mode == REPLAY_MODE_NONE) {
  2351. /*
  2352. * VGA can make calls to this function while updating the screen.
  2353. * In record/replay mode this causes a deadlock, because
  2354. * run_on_cpu waits for rr mutex. Therefore no races are possible
  2355. * in this case and no need for making run_on_cpu when
  2356. * record/replay is enabled.
  2357. */
  2358. cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
  2359. run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
  2360. }
  2361. }
  2362. static void tcg_commit_cpu(CPUState *cpu, run_on_cpu_data data)
  2363. {
  2364. CPUAddressSpace *cpuas = data.host_ptr;
  2365. cpuas->memory_dispatch = address_space_to_dispatch(cpuas->as);
  2366. tlb_flush(cpu);
  2367. }
  2368. static void tcg_commit(MemoryListener *listener)
  2369. {
  2370. CPUAddressSpace *cpuas;
  2371. CPUState *cpu;
  2372. assert(tcg_enabled());
  2373. /* since each CPU stores ram addresses in its TLB cache, we must
  2374. reset the modified entries */
  2375. cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
  2376. cpu = cpuas->cpu;
  2377. /*
  2378. * Defer changes to as->memory_dispatch until the cpu is quiescent.
  2379. * Otherwise we race between (1) other cpu threads and (2) ongoing
  2380. * i/o for the current cpu thread, with data cached by mmu_lookup().
  2381. *
  2382. * In addition, queueing the work function will kick the cpu back to
  2383. * the main loop, which will end the RCU critical section and reclaim
  2384. * the memory data structures.
  2385. *
  2386. * That said, the listener is also called during realize, before
  2387. * all of the tcg machinery for run-on is initialized: thus halt_cond.
  2388. */
  2389. if (cpu->halt_cond) {
  2390. async_run_on_cpu(cpu, tcg_commit_cpu, RUN_ON_CPU_HOST_PTR(cpuas));
  2391. } else {
  2392. tcg_commit_cpu(cpu, RUN_ON_CPU_HOST_PTR(cpuas));
  2393. }
  2394. }
  2395. static void memory_map_init(void)
  2396. {
  2397. system_memory = g_malloc(sizeof(*system_memory));
  2398. memory_region_init(system_memory, NULL, "system", UINT64_MAX);
  2399. address_space_init(&address_space_memory, system_memory, "memory");
  2400. system_io = g_malloc(sizeof(*system_io));
  2401. memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
  2402. 65536);
  2403. address_space_init(&address_space_io, system_io, "I/O");
  2404. }
  2405. MemoryRegion *get_system_memory(void)
  2406. {
  2407. return system_memory;
  2408. }
  2409. MemoryRegion *get_system_io(void)
  2410. {
  2411. return system_io;
  2412. }
  2413. static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
  2414. hwaddr length)
  2415. {
  2416. uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
  2417. ram_addr_t ramaddr = memory_region_get_ram_addr(mr);
  2418. /* We know we're only called for RAM MemoryRegions */
  2419. assert(ramaddr != RAM_ADDR_INVALID);
  2420. addr += ramaddr;
  2421. /* No early return if dirty_log_mask is or becomes 0, because
  2422. * cpu_physical_memory_set_dirty_range will still call
  2423. * xen_modified_memory.
  2424. */
  2425. if (dirty_log_mask) {
  2426. dirty_log_mask =
  2427. cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
  2428. }
  2429. if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
  2430. assert(tcg_enabled());
  2431. tb_invalidate_phys_range(addr, addr + length - 1);
  2432. dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
  2433. }
  2434. cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
  2435. }
  2436. void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
  2437. {
  2438. /*
  2439. * In principle this function would work on other memory region types too,
  2440. * but the ROM device use case is the only one where this operation is
  2441. * necessary. Other memory regions should use the
  2442. * address_space_read/write() APIs.
  2443. */
  2444. assert(memory_region_is_romd(mr));
  2445. invalidate_and_set_dirty(mr, addr, size);
  2446. }
  2447. int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
  2448. {
  2449. unsigned access_size_max = mr->ops->valid.max_access_size;
  2450. /* Regions are assumed to support 1-4 byte accesses unless
  2451. otherwise specified. */
  2452. if (access_size_max == 0) {
  2453. access_size_max = 4;
  2454. }
  2455. /* Bound the maximum access by the alignment of the address. */
  2456. if (!mr->ops->impl.unaligned) {
  2457. unsigned align_size_max = addr & -addr;
  2458. if (align_size_max != 0 && align_size_max < access_size_max) {
  2459. access_size_max = align_size_max;
  2460. }
  2461. }
  2462. /* Don't attempt accesses larger than the maximum. */
  2463. if (l > access_size_max) {
  2464. l = access_size_max;
  2465. }
  2466. l = pow2floor(l);
  2467. return l;
  2468. }
  2469. bool prepare_mmio_access(MemoryRegion *mr)
  2470. {
  2471. bool release_lock = false;
  2472. if (!bql_locked()) {
  2473. bql_lock();
  2474. release_lock = true;
  2475. }
  2476. if (mr->flush_coalesced_mmio) {
  2477. qemu_flush_coalesced_mmio_buffer();
  2478. }
  2479. return release_lock;
  2480. }
  2481. /**
  2482. * flatview_access_allowed
  2483. * @mr: #MemoryRegion to be accessed
  2484. * @attrs: memory transaction attributes
  2485. * @addr: address within that memory region
  2486. * @len: the number of bytes to access
  2487. *
  2488. * Check if a memory transaction is allowed.
  2489. *
  2490. * Returns: true if transaction is allowed, false if denied.
  2491. */
  2492. static bool flatview_access_allowed(MemoryRegion *mr, MemTxAttrs attrs,
  2493. hwaddr addr, hwaddr len)
  2494. {
  2495. if (likely(!attrs.memory)) {
  2496. return true;
  2497. }
  2498. if (memory_region_is_ram(mr)) {
  2499. return true;
  2500. }
  2501. qemu_log_mask(LOG_INVALID_MEM,
  2502. "Invalid access to non-RAM device at "
  2503. "addr 0x%" HWADDR_PRIX ", size %" HWADDR_PRIu ", "
  2504. "region '%s'\n", addr, len, memory_region_name(mr));
  2505. return false;
  2506. }
  2507. static MemTxResult flatview_write_continue_step(MemTxAttrs attrs,
  2508. const uint8_t *buf,
  2509. hwaddr len, hwaddr mr_addr,
  2510. hwaddr *l, MemoryRegion *mr)
  2511. {
  2512. if (!flatview_access_allowed(mr, attrs, mr_addr, *l)) {
  2513. return MEMTX_ACCESS_ERROR;
  2514. }
  2515. if (!memory_access_is_direct(mr, true, attrs)) {
  2516. uint64_t val;
  2517. MemTxResult result;
  2518. bool release_lock = prepare_mmio_access(mr);
  2519. *l = memory_access_size(mr, *l, mr_addr);
  2520. /*
  2521. * XXX: could force current_cpu to NULL to avoid
  2522. * potential bugs
  2523. */
  2524. /*
  2525. * Assure Coverity (and ourselves) that we are not going to OVERRUN
  2526. * the buffer by following ldn_he_p().
  2527. */
  2528. #ifdef QEMU_STATIC_ANALYSIS
  2529. assert((*l == 1 && len >= 1) ||
  2530. (*l == 2 && len >= 2) ||
  2531. (*l == 4 && len >= 4) ||
  2532. (*l == 8 && len >= 8));
  2533. #endif
  2534. val = ldn_he_p(buf, *l);
  2535. result = memory_region_dispatch_write(mr, mr_addr, val,
  2536. size_memop(*l), attrs);
  2537. if (release_lock) {
  2538. bql_unlock();
  2539. }
  2540. return result;
  2541. } else {
  2542. /* RAM case */
  2543. uint8_t *ram_ptr = qemu_ram_ptr_length(mr->ram_block, mr_addr, l,
  2544. false, true);
  2545. memmove(ram_ptr, buf, *l);
  2546. invalidate_and_set_dirty(mr, mr_addr, *l);
  2547. return MEMTX_OK;
  2548. }
  2549. }
  2550. /* Called within RCU critical section. */
  2551. static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
  2552. MemTxAttrs attrs,
  2553. const void *ptr,
  2554. hwaddr len, hwaddr mr_addr,
  2555. hwaddr l, MemoryRegion *mr)
  2556. {
  2557. MemTxResult result = MEMTX_OK;
  2558. const uint8_t *buf = ptr;
  2559. for (;;) {
  2560. result |= flatview_write_continue_step(attrs, buf, len, mr_addr, &l,
  2561. mr);
  2562. len -= l;
  2563. buf += l;
  2564. addr += l;
  2565. if (!len) {
  2566. break;
  2567. }
  2568. l = len;
  2569. mr = flatview_translate(fv, addr, &mr_addr, &l, true, attrs);
  2570. }
  2571. return result;
  2572. }
  2573. /* Called from RCU critical section. */
  2574. static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
  2575. const void *buf, hwaddr len)
  2576. {
  2577. hwaddr l;
  2578. hwaddr mr_addr;
  2579. MemoryRegion *mr;
  2580. l = len;
  2581. mr = flatview_translate(fv, addr, &mr_addr, &l, true, attrs);
  2582. if (!flatview_access_allowed(mr, attrs, addr, len)) {
  2583. return MEMTX_ACCESS_ERROR;
  2584. }
  2585. return flatview_write_continue(fv, addr, attrs, buf, len,
  2586. mr_addr, l, mr);
  2587. }
  2588. static MemTxResult flatview_read_continue_step(MemTxAttrs attrs, uint8_t *buf,
  2589. hwaddr len, hwaddr mr_addr,
  2590. hwaddr *l,
  2591. MemoryRegion *mr)
  2592. {
  2593. if (!flatview_access_allowed(mr, attrs, mr_addr, *l)) {
  2594. return MEMTX_ACCESS_ERROR;
  2595. }
  2596. if (!memory_access_is_direct(mr, false, attrs)) {
  2597. /* I/O case */
  2598. uint64_t val;
  2599. MemTxResult result;
  2600. bool release_lock = prepare_mmio_access(mr);
  2601. *l = memory_access_size(mr, *l, mr_addr);
  2602. result = memory_region_dispatch_read(mr, mr_addr, &val, size_memop(*l),
  2603. attrs);
  2604. /*
  2605. * Assure Coverity (and ourselves) that we are not going to OVERRUN
  2606. * the buffer by following stn_he_p().
  2607. */
  2608. #ifdef QEMU_STATIC_ANALYSIS
  2609. assert((*l == 1 && len >= 1) ||
  2610. (*l == 2 && len >= 2) ||
  2611. (*l == 4 && len >= 4) ||
  2612. (*l == 8 && len >= 8));
  2613. #endif
  2614. stn_he_p(buf, *l, val);
  2615. if (release_lock) {
  2616. bql_unlock();
  2617. }
  2618. return result;
  2619. } else {
  2620. /* RAM case */
  2621. uint8_t *ram_ptr = qemu_ram_ptr_length(mr->ram_block, mr_addr, l,
  2622. false, false);
  2623. memcpy(buf, ram_ptr, *l);
  2624. return MEMTX_OK;
  2625. }
  2626. }
  2627. /* Called within RCU critical section. */
  2628. MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
  2629. MemTxAttrs attrs, void *ptr,
  2630. hwaddr len, hwaddr mr_addr, hwaddr l,
  2631. MemoryRegion *mr)
  2632. {
  2633. MemTxResult result = MEMTX_OK;
  2634. uint8_t *buf = ptr;
  2635. fuzz_dma_read_cb(addr, len, mr);
  2636. for (;;) {
  2637. result |= flatview_read_continue_step(attrs, buf, len, mr_addr, &l, mr);
  2638. len -= l;
  2639. buf += l;
  2640. addr += l;
  2641. if (!len) {
  2642. break;
  2643. }
  2644. l = len;
  2645. mr = flatview_translate(fv, addr, &mr_addr, &l, false, attrs);
  2646. }
  2647. return result;
  2648. }
  2649. /* Called from RCU critical section. */
  2650. static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
  2651. MemTxAttrs attrs, void *buf, hwaddr len)
  2652. {
  2653. hwaddr l;
  2654. hwaddr mr_addr;
  2655. MemoryRegion *mr;
  2656. l = len;
  2657. mr = flatview_translate(fv, addr, &mr_addr, &l, false, attrs);
  2658. if (!flatview_access_allowed(mr, attrs, addr, len)) {
  2659. return MEMTX_ACCESS_ERROR;
  2660. }
  2661. return flatview_read_continue(fv, addr, attrs, buf, len,
  2662. mr_addr, l, mr);
  2663. }
  2664. MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
  2665. MemTxAttrs attrs, void *buf, hwaddr len)
  2666. {
  2667. MemTxResult result = MEMTX_OK;
  2668. FlatView *fv;
  2669. if (len > 0) {
  2670. RCU_READ_LOCK_GUARD();
  2671. fv = address_space_to_flatview(as);
  2672. result = flatview_read(fv, addr, attrs, buf, len);
  2673. }
  2674. return result;
  2675. }
  2676. MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
  2677. MemTxAttrs attrs,
  2678. const void *buf, hwaddr len)
  2679. {
  2680. MemTxResult result = MEMTX_OK;
  2681. FlatView *fv;
  2682. if (len > 0) {
  2683. RCU_READ_LOCK_GUARD();
  2684. fv = address_space_to_flatview(as);
  2685. result = flatview_write(fv, addr, attrs, buf, len);
  2686. }
  2687. return result;
  2688. }
  2689. MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
  2690. void *buf, hwaddr len, bool is_write)
  2691. {
  2692. if (is_write) {
  2693. return address_space_write(as, addr, attrs, buf, len);
  2694. } else {
  2695. return address_space_read_full(as, addr, attrs, buf, len);
  2696. }
  2697. }
  2698. MemTxResult address_space_set(AddressSpace *as, hwaddr addr,
  2699. uint8_t c, hwaddr len, MemTxAttrs attrs)
  2700. {
  2701. #define FILLBUF_SIZE 512
  2702. uint8_t fillbuf[FILLBUF_SIZE];
  2703. int l;
  2704. MemTxResult error = MEMTX_OK;
  2705. memset(fillbuf, c, FILLBUF_SIZE);
  2706. while (len > 0) {
  2707. l = len < FILLBUF_SIZE ? len : FILLBUF_SIZE;
  2708. error |= address_space_write(as, addr, attrs, fillbuf, l);
  2709. len -= l;
  2710. addr += l;
  2711. }
  2712. return error;
  2713. }
  2714. void cpu_physical_memory_rw(hwaddr addr, void *buf,
  2715. hwaddr len, bool is_write)
  2716. {
  2717. address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
  2718. buf, len, is_write);
  2719. }
  2720. enum write_rom_type {
  2721. WRITE_DATA,
  2722. FLUSH_CACHE,
  2723. };
  2724. static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
  2725. hwaddr addr,
  2726. MemTxAttrs attrs,
  2727. const void *ptr,
  2728. hwaddr len,
  2729. enum write_rom_type type)
  2730. {
  2731. hwaddr l;
  2732. uint8_t *ram_ptr;
  2733. hwaddr addr1;
  2734. MemoryRegion *mr;
  2735. const uint8_t *buf = ptr;
  2736. RCU_READ_LOCK_GUARD();
  2737. while (len > 0) {
  2738. l = len;
  2739. mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
  2740. if (!memory_region_supports_direct_access(mr)) {
  2741. l = memory_access_size(mr, l, addr1);
  2742. } else {
  2743. /* ROM/RAM case */
  2744. ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
  2745. switch (type) {
  2746. case WRITE_DATA:
  2747. memcpy(ram_ptr, buf, l);
  2748. invalidate_and_set_dirty(mr, addr1, l);
  2749. break;
  2750. case FLUSH_CACHE:
  2751. flush_idcache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr, l);
  2752. break;
  2753. }
  2754. }
  2755. len -= l;
  2756. buf += l;
  2757. addr += l;
  2758. }
  2759. return MEMTX_OK;
  2760. }
  2761. /* used for ROM loading : can write in RAM and ROM */
  2762. MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
  2763. MemTxAttrs attrs,
  2764. const void *buf, hwaddr len)
  2765. {
  2766. return address_space_write_rom_internal(as, addr, attrs,
  2767. buf, len, WRITE_DATA);
  2768. }
  2769. void cpu_flush_icache_range(hwaddr start, hwaddr len)
  2770. {
  2771. /*
  2772. * This function should do the same thing as an icache flush that was
  2773. * triggered from within the guest. For TCG we are always cache coherent,
  2774. * so there is no need to flush anything. For KVM / Xen we need to flush
  2775. * the host's instruction cache at least.
  2776. */
  2777. if (tcg_enabled()) {
  2778. return;
  2779. }
  2780. address_space_write_rom_internal(&address_space_memory,
  2781. start, MEMTXATTRS_UNSPECIFIED,
  2782. NULL, len, FLUSH_CACHE);
  2783. }
  2784. /*
  2785. * A magic value stored in the first 8 bytes of the bounce buffer struct. Used
  2786. * to detect illegal pointers passed to address_space_unmap.
  2787. */
  2788. #define BOUNCE_BUFFER_MAGIC 0xb4017ceb4ffe12ed
  2789. typedef struct {
  2790. uint64_t magic;
  2791. MemoryRegion *mr;
  2792. hwaddr addr;
  2793. size_t len;
  2794. uint8_t buffer[];
  2795. } BounceBuffer;
  2796. static void
  2797. address_space_unregister_map_client_do(AddressSpaceMapClient *client)
  2798. {
  2799. QLIST_REMOVE(client, link);
  2800. g_free(client);
  2801. }
  2802. static void address_space_notify_map_clients_locked(AddressSpace *as)
  2803. {
  2804. AddressSpaceMapClient *client;
  2805. while (!QLIST_EMPTY(&as->map_client_list)) {
  2806. client = QLIST_FIRST(&as->map_client_list);
  2807. qemu_bh_schedule(client->bh);
  2808. address_space_unregister_map_client_do(client);
  2809. }
  2810. }
  2811. void address_space_register_map_client(AddressSpace *as, QEMUBH *bh)
  2812. {
  2813. AddressSpaceMapClient *client = g_malloc(sizeof(*client));
  2814. QEMU_LOCK_GUARD(&as->map_client_list_lock);
  2815. client->bh = bh;
  2816. QLIST_INSERT_HEAD(&as->map_client_list, client, link);
  2817. /* Write map_client_list before reading bounce_buffer_size. */
  2818. smp_mb();
  2819. if (qatomic_read(&as->bounce_buffer_size) < as->max_bounce_buffer_size) {
  2820. address_space_notify_map_clients_locked(as);
  2821. }
  2822. }
  2823. void cpu_exec_init_all(void)
  2824. {
  2825. qemu_mutex_init(&ram_list.mutex);
  2826. /* The data structures we set up here depend on knowing the page size,
  2827. * so no more changes can be made after this point.
  2828. * In an ideal world, nothing we did before we had finished the
  2829. * machine setup would care about the target page size, and we could
  2830. * do this much later, rather than requiring board models to state
  2831. * up front what their requirements are.
  2832. */
  2833. finalize_target_page_bits();
  2834. io_mem_init();
  2835. memory_map_init();
  2836. }
  2837. void address_space_unregister_map_client(AddressSpace *as, QEMUBH *bh)
  2838. {
  2839. AddressSpaceMapClient *client;
  2840. QEMU_LOCK_GUARD(&as->map_client_list_lock);
  2841. QLIST_FOREACH(client, &as->map_client_list, link) {
  2842. if (client->bh == bh) {
  2843. address_space_unregister_map_client_do(client);
  2844. break;
  2845. }
  2846. }
  2847. }
  2848. static void address_space_notify_map_clients(AddressSpace *as)
  2849. {
  2850. QEMU_LOCK_GUARD(&as->map_client_list_lock);
  2851. address_space_notify_map_clients_locked(as);
  2852. }
  2853. static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
  2854. bool is_write, MemTxAttrs attrs)
  2855. {
  2856. MemoryRegion *mr;
  2857. hwaddr l, xlat;
  2858. while (len > 0) {
  2859. l = len;
  2860. mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
  2861. if (!memory_access_is_direct(mr, is_write, attrs)) {
  2862. l = memory_access_size(mr, l, addr);
  2863. if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
  2864. return false;
  2865. }
  2866. }
  2867. len -= l;
  2868. addr += l;
  2869. }
  2870. return true;
  2871. }
  2872. bool address_space_access_valid(AddressSpace *as, hwaddr addr,
  2873. hwaddr len, bool is_write,
  2874. MemTxAttrs attrs)
  2875. {
  2876. FlatView *fv;
  2877. RCU_READ_LOCK_GUARD();
  2878. fv = address_space_to_flatview(as);
  2879. return flatview_access_valid(fv, addr, len, is_write, attrs);
  2880. }
  2881. static hwaddr
  2882. flatview_extend_translation(FlatView *fv, hwaddr addr,
  2883. hwaddr target_len,
  2884. MemoryRegion *mr, hwaddr base, hwaddr len,
  2885. bool is_write, MemTxAttrs attrs)
  2886. {
  2887. hwaddr done = 0;
  2888. hwaddr xlat;
  2889. MemoryRegion *this_mr;
  2890. for (;;) {
  2891. target_len -= len;
  2892. addr += len;
  2893. done += len;
  2894. if (target_len == 0) {
  2895. return done;
  2896. }
  2897. len = target_len;
  2898. this_mr = flatview_translate(fv, addr, &xlat,
  2899. &len, is_write, attrs);
  2900. if (this_mr != mr || xlat != base + done) {
  2901. return done;
  2902. }
  2903. }
  2904. }
  2905. /* Map a physical memory region into a host virtual address.
  2906. * May map a subset of the requested range, given by and returned in *plen.
  2907. * May return NULL if resources needed to perform the mapping are exhausted.
  2908. * Use only for reads OR writes - not for read-modify-write operations.
  2909. * Use address_space_register_map_client() to know when retrying the map
  2910. * operation is likely to succeed.
  2911. */
  2912. void *address_space_map(AddressSpace *as,
  2913. hwaddr addr,
  2914. hwaddr *plen,
  2915. bool is_write,
  2916. MemTxAttrs attrs)
  2917. {
  2918. hwaddr len = *plen;
  2919. hwaddr l, xlat;
  2920. MemoryRegion *mr;
  2921. FlatView *fv;
  2922. trace_address_space_map(as, addr, len, is_write, *(uint32_t *) &attrs);
  2923. if (len == 0) {
  2924. return NULL;
  2925. }
  2926. l = len;
  2927. RCU_READ_LOCK_GUARD();
  2928. fv = address_space_to_flatview(as);
  2929. mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
  2930. if (!memory_access_is_direct(mr, is_write, attrs)) {
  2931. size_t used = qatomic_read(&as->bounce_buffer_size);
  2932. for (;;) {
  2933. hwaddr alloc = MIN(as->max_bounce_buffer_size - used, l);
  2934. size_t new_size = used + alloc;
  2935. size_t actual =
  2936. qatomic_cmpxchg(&as->bounce_buffer_size, used, new_size);
  2937. if (actual == used) {
  2938. l = alloc;
  2939. break;
  2940. }
  2941. used = actual;
  2942. }
  2943. if (l == 0) {
  2944. *plen = 0;
  2945. return NULL;
  2946. }
  2947. BounceBuffer *bounce = g_malloc0(l + sizeof(BounceBuffer));
  2948. bounce->magic = BOUNCE_BUFFER_MAGIC;
  2949. memory_region_ref(mr);
  2950. bounce->mr = mr;
  2951. bounce->addr = addr;
  2952. bounce->len = l;
  2953. if (!is_write) {
  2954. flatview_read(fv, addr, attrs,
  2955. bounce->buffer, l);
  2956. }
  2957. *plen = l;
  2958. return bounce->buffer;
  2959. }
  2960. memory_region_ref(mr);
  2961. *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
  2962. l, is_write, attrs);
  2963. fuzz_dma_read_cb(addr, *plen, mr);
  2964. return qemu_ram_ptr_length(mr->ram_block, xlat, plen, true, is_write);
  2965. }
  2966. /* Unmaps a memory region previously mapped by address_space_map().
  2967. * Will also mark the memory as dirty if is_write is true. access_len gives
  2968. * the amount of memory that was actually read or written by the caller.
  2969. */
  2970. void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
  2971. bool is_write, hwaddr access_len)
  2972. {
  2973. MemoryRegion *mr;
  2974. ram_addr_t addr1;
  2975. mr = memory_region_from_host(buffer, &addr1);
  2976. if (mr != NULL) {
  2977. if (is_write) {
  2978. invalidate_and_set_dirty(mr, addr1, access_len);
  2979. }
  2980. if (xen_enabled()) {
  2981. xen_invalidate_map_cache_entry(buffer);
  2982. }
  2983. memory_region_unref(mr);
  2984. return;
  2985. }
  2986. BounceBuffer *bounce = container_of(buffer, BounceBuffer, buffer);
  2987. assert(bounce->magic == BOUNCE_BUFFER_MAGIC);
  2988. if (is_write) {
  2989. address_space_write(as, bounce->addr, MEMTXATTRS_UNSPECIFIED,
  2990. bounce->buffer, access_len);
  2991. }
  2992. qatomic_sub(&as->bounce_buffer_size, bounce->len);
  2993. bounce->magic = ~BOUNCE_BUFFER_MAGIC;
  2994. memory_region_unref(bounce->mr);
  2995. g_free(bounce);
  2996. /* Write bounce_buffer_size before reading map_client_list. */
  2997. smp_mb();
  2998. address_space_notify_map_clients(as);
  2999. }
  3000. void *cpu_physical_memory_map(hwaddr addr,
  3001. hwaddr *plen,
  3002. bool is_write)
  3003. {
  3004. return address_space_map(&address_space_memory, addr, plen, is_write,
  3005. MEMTXATTRS_UNSPECIFIED);
  3006. }
  3007. void cpu_physical_memory_unmap(void *buffer, hwaddr len,
  3008. bool is_write, hwaddr access_len)
  3009. {
  3010. return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
  3011. }
  3012. #define ARG1_DECL AddressSpace *as
  3013. #define ARG1 as
  3014. #define SUFFIX
  3015. #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
  3016. #define RCU_READ_LOCK(...) rcu_read_lock()
  3017. #define RCU_READ_UNLOCK(...) rcu_read_unlock()
  3018. #include "memory_ldst.c.inc"
  3019. int64_t address_space_cache_init(MemoryRegionCache *cache,
  3020. AddressSpace *as,
  3021. hwaddr addr,
  3022. hwaddr len,
  3023. bool is_write)
  3024. {
  3025. AddressSpaceDispatch *d;
  3026. hwaddr l;
  3027. MemoryRegion *mr;
  3028. Int128 diff;
  3029. assert(len > 0);
  3030. l = len;
  3031. cache->fv = address_space_get_flatview(as);
  3032. d = flatview_to_dispatch(cache->fv);
  3033. cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
  3034. /*
  3035. * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
  3036. * Take that into account to compute how many bytes are there between
  3037. * cache->xlat and the end of the section.
  3038. */
  3039. diff = int128_sub(cache->mrs.size,
  3040. int128_make64(cache->xlat - cache->mrs.offset_within_region));
  3041. l = int128_get64(int128_min(diff, int128_make64(l)));
  3042. mr = cache->mrs.mr;
  3043. memory_region_ref(mr);
  3044. if (memory_access_is_direct(mr, is_write, MEMTXATTRS_UNSPECIFIED)) {
  3045. /* We don't care about the memory attributes here as we're only
  3046. * doing this if we found actual RAM, which behaves the same
  3047. * regardless of attributes; so UNSPECIFIED is fine.
  3048. */
  3049. l = flatview_extend_translation(cache->fv, addr, len, mr,
  3050. cache->xlat, l, is_write,
  3051. MEMTXATTRS_UNSPECIFIED);
  3052. cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true,
  3053. is_write);
  3054. } else {
  3055. cache->ptr = NULL;
  3056. }
  3057. cache->len = l;
  3058. cache->is_write = is_write;
  3059. return l;
  3060. }
  3061. void address_space_cache_invalidate(MemoryRegionCache *cache,
  3062. hwaddr addr,
  3063. hwaddr access_len)
  3064. {
  3065. assert(cache->is_write);
  3066. if (likely(cache->ptr)) {
  3067. invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
  3068. }
  3069. }
  3070. void address_space_cache_destroy(MemoryRegionCache *cache)
  3071. {
  3072. if (!cache->mrs.mr) {
  3073. return;
  3074. }
  3075. if (xen_enabled()) {
  3076. xen_invalidate_map_cache_entry(cache->ptr);
  3077. }
  3078. memory_region_unref(cache->mrs.mr);
  3079. flatview_unref(cache->fv);
  3080. cache->mrs.mr = NULL;
  3081. cache->fv = NULL;
  3082. }
  3083. /* Called from RCU critical section. This function has the same
  3084. * semantics as address_space_translate, but it only works on a
  3085. * predefined range of a MemoryRegion that was mapped with
  3086. * address_space_cache_init.
  3087. */
  3088. static inline MemoryRegion *address_space_translate_cached(
  3089. MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
  3090. hwaddr *plen, bool is_write, MemTxAttrs attrs)
  3091. {
  3092. MemoryRegionSection section;
  3093. MemoryRegion *mr;
  3094. IOMMUMemoryRegion *iommu_mr;
  3095. AddressSpace *target_as;
  3096. assert(!cache->ptr);
  3097. *xlat = addr + cache->xlat;
  3098. mr = cache->mrs.mr;
  3099. iommu_mr = memory_region_get_iommu(mr);
  3100. if (!iommu_mr) {
  3101. /* MMIO region. */
  3102. return mr;
  3103. }
  3104. section = address_space_translate_iommu(iommu_mr, xlat, plen,
  3105. NULL, is_write, true,
  3106. &target_as, attrs);
  3107. return section.mr;
  3108. }
  3109. /* Called within RCU critical section. */
  3110. static MemTxResult address_space_write_continue_cached(MemTxAttrs attrs,
  3111. const void *ptr,
  3112. hwaddr len,
  3113. hwaddr mr_addr,
  3114. hwaddr l,
  3115. MemoryRegion *mr)
  3116. {
  3117. MemTxResult result = MEMTX_OK;
  3118. const uint8_t *buf = ptr;
  3119. for (;;) {
  3120. result |= flatview_write_continue_step(attrs, buf, len, mr_addr, &l,
  3121. mr);
  3122. len -= l;
  3123. buf += l;
  3124. mr_addr += l;
  3125. if (!len) {
  3126. break;
  3127. }
  3128. l = len;
  3129. }
  3130. return result;
  3131. }
  3132. /* Called within RCU critical section. */
  3133. static MemTxResult address_space_read_continue_cached(MemTxAttrs attrs,
  3134. void *ptr, hwaddr len,
  3135. hwaddr mr_addr, hwaddr l,
  3136. MemoryRegion *mr)
  3137. {
  3138. MemTxResult result = MEMTX_OK;
  3139. uint8_t *buf = ptr;
  3140. for (;;) {
  3141. result |= flatview_read_continue_step(attrs, buf, len, mr_addr, &l, mr);
  3142. len -= l;
  3143. buf += l;
  3144. mr_addr += l;
  3145. if (!len) {
  3146. break;
  3147. }
  3148. l = len;
  3149. }
  3150. return result;
  3151. }
  3152. /* Called from RCU critical section. address_space_read_cached uses this
  3153. * out of line function when the target is an MMIO or IOMMU region.
  3154. */
  3155. MemTxResult
  3156. address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
  3157. void *buf, hwaddr len)
  3158. {
  3159. hwaddr mr_addr, l;
  3160. MemoryRegion *mr;
  3161. l = len;
  3162. mr = address_space_translate_cached(cache, addr, &mr_addr, &l, false,
  3163. MEMTXATTRS_UNSPECIFIED);
  3164. return address_space_read_continue_cached(MEMTXATTRS_UNSPECIFIED,
  3165. buf, len, mr_addr, l, mr);
  3166. }
  3167. /* Called from RCU critical section. address_space_write_cached uses this
  3168. * out of line function when the target is an MMIO or IOMMU region.
  3169. */
  3170. MemTxResult
  3171. address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
  3172. const void *buf, hwaddr len)
  3173. {
  3174. hwaddr mr_addr, l;
  3175. MemoryRegion *mr;
  3176. l = len;
  3177. mr = address_space_translate_cached(cache, addr, &mr_addr, &l, true,
  3178. MEMTXATTRS_UNSPECIFIED);
  3179. return address_space_write_continue_cached(MEMTXATTRS_UNSPECIFIED,
  3180. buf, len, mr_addr, l, mr);
  3181. }
  3182. #define ARG1_DECL MemoryRegionCache *cache
  3183. #define ARG1 cache
  3184. #define SUFFIX _cached_slow
  3185. #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
  3186. #define RCU_READ_LOCK() ((void)0)
  3187. #define RCU_READ_UNLOCK() ((void)0)
  3188. #include "memory_ldst.c.inc"
  3189. /* virtual memory access for debug (includes writing to ROM) */
  3190. int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
  3191. void *ptr, size_t len, bool is_write)
  3192. {
  3193. hwaddr phys_addr;
  3194. vaddr l, page;
  3195. uint8_t *buf = ptr;
  3196. cpu_synchronize_state(cpu);
  3197. while (len > 0) {
  3198. int asidx;
  3199. MemTxAttrs attrs;
  3200. MemTxResult res;
  3201. page = addr & TARGET_PAGE_MASK;
  3202. phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
  3203. asidx = cpu_asidx_from_attrs(cpu, attrs);
  3204. /* if no physical page mapped, return an error */
  3205. if (phys_addr == -1)
  3206. return -1;
  3207. l = (page + TARGET_PAGE_SIZE) - addr;
  3208. if (l > len)
  3209. l = len;
  3210. phys_addr += (addr & ~TARGET_PAGE_MASK);
  3211. res = address_space_rw(cpu->cpu_ases[asidx].as, phys_addr, attrs, buf,
  3212. l, is_write);
  3213. if (res != MEMTX_OK) {
  3214. return -1;
  3215. }
  3216. len -= l;
  3217. buf += l;
  3218. addr += l;
  3219. }
  3220. return 0;
  3221. }
  3222. bool cpu_physical_memory_is_io(hwaddr phys_addr)
  3223. {
  3224. MemoryRegion*mr;
  3225. hwaddr l = 1;
  3226. RCU_READ_LOCK_GUARD();
  3227. mr = address_space_translate(&address_space_memory,
  3228. phys_addr, &phys_addr, &l, false,
  3229. MEMTXATTRS_UNSPECIFIED);
  3230. return !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
  3231. }
  3232. int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
  3233. {
  3234. RAMBlock *block;
  3235. int ret = 0;
  3236. RCU_READ_LOCK_GUARD();
  3237. RAMBLOCK_FOREACH(block) {
  3238. ret = func(block, opaque);
  3239. if (ret) {
  3240. break;
  3241. }
  3242. }
  3243. return ret;
  3244. }
  3245. /*
  3246. * Unmap pages of memory from start to start+length such that
  3247. * they a) read as 0, b) Trigger whatever fault mechanism
  3248. * the OS provides for postcopy.
  3249. * The pages must be unmapped by the end of the function.
  3250. * Returns: 0 on success, none-0 on failure
  3251. *
  3252. */
  3253. int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
  3254. {
  3255. int ret = -1;
  3256. uint8_t *host_startaddr = rb->host + start;
  3257. if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
  3258. error_report("%s: Unaligned start address: %p",
  3259. __func__, host_startaddr);
  3260. goto err;
  3261. }
  3262. if ((start + length) <= rb->max_length) {
  3263. bool need_madvise, need_fallocate;
  3264. if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
  3265. error_report("%s: Unaligned length: %zx", __func__, length);
  3266. goto err;
  3267. }
  3268. errno = ENOTSUP; /* If we are missing MADVISE etc */
  3269. /* The logic here is messy;
  3270. * madvise DONTNEED fails for hugepages
  3271. * fallocate works on hugepages and shmem
  3272. * shared anonymous memory requires madvise REMOVE
  3273. */
  3274. need_madvise = (rb->page_size == qemu_real_host_page_size());
  3275. need_fallocate = rb->fd != -1;
  3276. if (need_fallocate) {
  3277. /* For a file, this causes the area of the file to be zero'd
  3278. * if read, and for hugetlbfs also causes it to be unmapped
  3279. * so a userfault will trigger.
  3280. */
  3281. #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
  3282. /*
  3283. * fallocate() will fail with readonly files. Let's print a
  3284. * proper error message.
  3285. */
  3286. if (rb->flags & RAM_READONLY_FD) {
  3287. error_report("%s: Discarding RAM with readonly files is not"
  3288. " supported", __func__);
  3289. goto err;
  3290. }
  3291. /*
  3292. * We'll discard data from the actual file, even though we only
  3293. * have a MAP_PRIVATE mapping, possibly messing with other
  3294. * MAP_PRIVATE/MAP_SHARED mappings. There is no easy way to
  3295. * change that behavior whithout violating the promised
  3296. * semantics of ram_block_discard_range().
  3297. *
  3298. * Only warn, because it works as long as nobody else uses that
  3299. * file.
  3300. */
  3301. if (!qemu_ram_is_shared(rb)) {
  3302. warn_report_once("%s: Discarding RAM"
  3303. " in private file mappings is possibly"
  3304. " dangerous, because it will modify the"
  3305. " underlying file and will affect other"
  3306. " users of the file", __func__);
  3307. }
  3308. ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
  3309. start + rb->fd_offset, length);
  3310. if (ret) {
  3311. ret = -errno;
  3312. error_report("%s: Failed to fallocate %s:%" PRIx64 "+%" PRIx64
  3313. " +%zx (%d)", __func__, rb->idstr, start,
  3314. rb->fd_offset, length, ret);
  3315. goto err;
  3316. }
  3317. #else
  3318. ret = -ENOSYS;
  3319. error_report("%s: fallocate not available/file"
  3320. "%s:%" PRIx64 "+%" PRIx64 " +%zx (%d)", __func__,
  3321. rb->idstr, start, rb->fd_offset, length, ret);
  3322. goto err;
  3323. #endif
  3324. }
  3325. if (need_madvise) {
  3326. /* For normal RAM this causes it to be unmapped,
  3327. * for shared memory it causes the local mapping to disappear
  3328. * and to fall back on the file contents (which we just
  3329. * fallocate'd away).
  3330. */
  3331. #if defined(CONFIG_MADVISE)
  3332. if (qemu_ram_is_shared(rb) && rb->fd < 0) {
  3333. ret = madvise(host_startaddr, length, QEMU_MADV_REMOVE);
  3334. } else {
  3335. ret = madvise(host_startaddr, length, QEMU_MADV_DONTNEED);
  3336. }
  3337. if (ret) {
  3338. ret = -errno;
  3339. error_report("%s: Failed to discard range "
  3340. "%s:%" PRIx64 " +%zx (%d)",
  3341. __func__, rb->idstr, start, length, ret);
  3342. goto err;
  3343. }
  3344. #else
  3345. ret = -ENOSYS;
  3346. error_report("%s: MADVISE not available %s:%" PRIx64 " +%zx (%d)",
  3347. __func__, rb->idstr, start, length, ret);
  3348. goto err;
  3349. #endif
  3350. }
  3351. trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
  3352. need_madvise, need_fallocate, ret);
  3353. } else {
  3354. error_report("%s: Overrun block '%s' (%" PRIu64 "/%zx/" RAM_ADDR_FMT")",
  3355. __func__, rb->idstr, start, length, rb->max_length);
  3356. }
  3357. err:
  3358. return ret;
  3359. }
  3360. int ram_block_discard_guest_memfd_range(RAMBlock *rb, uint64_t start,
  3361. size_t length)
  3362. {
  3363. int ret = -1;
  3364. #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
  3365. /* ignore fd_offset with guest_memfd */
  3366. ret = fallocate(rb->guest_memfd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
  3367. start, length);
  3368. if (ret) {
  3369. ret = -errno;
  3370. error_report("%s: Failed to fallocate %s:%" PRIx64 " +%zx (%d)",
  3371. __func__, rb->idstr, start, length, ret);
  3372. }
  3373. #else
  3374. ret = -ENOSYS;
  3375. error_report("%s: fallocate not available %s:%" PRIx64 " +%zx (%d)",
  3376. __func__, rb->idstr, start, length, ret);
  3377. #endif
  3378. return ret;
  3379. }
  3380. bool ramblock_is_pmem(RAMBlock *rb)
  3381. {
  3382. return rb->flags & RAM_PMEM;
  3383. }
  3384. static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
  3385. {
  3386. if (start == end - 1) {
  3387. qemu_printf("\t%3d ", start);
  3388. } else {
  3389. qemu_printf("\t%3d..%-3d ", start, end - 1);
  3390. }
  3391. qemu_printf(" skip=%d ", skip);
  3392. if (ptr == PHYS_MAP_NODE_NIL) {
  3393. qemu_printf(" ptr=NIL");
  3394. } else if (!skip) {
  3395. qemu_printf(" ptr=#%d", ptr);
  3396. } else {
  3397. qemu_printf(" ptr=[%d]", ptr);
  3398. }
  3399. qemu_printf("\n");
  3400. }
  3401. #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
  3402. int128_sub((size), int128_one())) : 0)
  3403. void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
  3404. {
  3405. int i;
  3406. qemu_printf(" Dispatch\n");
  3407. qemu_printf(" Physical sections\n");
  3408. for (i = 0; i < d->map.sections_nb; ++i) {
  3409. MemoryRegionSection *s = d->map.sections + i;
  3410. const char *names[] = { " [unassigned]", " [not dirty]",
  3411. " [ROM]", " [watch]" };
  3412. qemu_printf(" #%d @" HWADDR_FMT_plx ".." HWADDR_FMT_plx
  3413. " %s%s%s%s%s",
  3414. i,
  3415. s->offset_within_address_space,
  3416. s->offset_within_address_space + MR_SIZE(s->size),
  3417. s->mr->name ? s->mr->name : "(noname)",
  3418. i < ARRAY_SIZE(names) ? names[i] : "",
  3419. s->mr == root ? " [ROOT]" : "",
  3420. s == d->mru_section ? " [MRU]" : "",
  3421. s->mr->is_iommu ? " [iommu]" : "");
  3422. if (s->mr->alias) {
  3423. qemu_printf(" alias=%s", s->mr->alias->name ?
  3424. s->mr->alias->name : "noname");
  3425. }
  3426. qemu_printf("\n");
  3427. }
  3428. qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
  3429. P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
  3430. for (i = 0; i < d->map.nodes_nb; ++i) {
  3431. int j, jprev;
  3432. PhysPageEntry prev;
  3433. Node *n = d->map.nodes + i;
  3434. qemu_printf(" [%d]\n", i);
  3435. for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
  3436. PhysPageEntry *pe = *n + j;
  3437. if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
  3438. continue;
  3439. }
  3440. mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
  3441. jprev = j;
  3442. prev = *pe;
  3443. }
  3444. if (jprev != ARRAY_SIZE(*n)) {
  3445. mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
  3446. }
  3447. }
  3448. }
  3449. /* Require any discards to work. */
  3450. static unsigned int ram_block_discard_required_cnt;
  3451. /* Require only coordinated discards to work. */
  3452. static unsigned int ram_block_coordinated_discard_required_cnt;
  3453. /* Disable any discards. */
  3454. static unsigned int ram_block_discard_disabled_cnt;
  3455. /* Disable only uncoordinated discards. */
  3456. static unsigned int ram_block_uncoordinated_discard_disabled_cnt;
  3457. static QemuMutex ram_block_discard_disable_mutex;
  3458. static void ram_block_discard_disable_mutex_lock(void)
  3459. {
  3460. static gsize initialized;
  3461. if (g_once_init_enter(&initialized)) {
  3462. qemu_mutex_init(&ram_block_discard_disable_mutex);
  3463. g_once_init_leave(&initialized, 1);
  3464. }
  3465. qemu_mutex_lock(&ram_block_discard_disable_mutex);
  3466. }
  3467. static void ram_block_discard_disable_mutex_unlock(void)
  3468. {
  3469. qemu_mutex_unlock(&ram_block_discard_disable_mutex);
  3470. }
  3471. int ram_block_discard_disable(bool state)
  3472. {
  3473. int ret = 0;
  3474. ram_block_discard_disable_mutex_lock();
  3475. if (!state) {
  3476. ram_block_discard_disabled_cnt--;
  3477. } else if (ram_block_discard_required_cnt ||
  3478. ram_block_coordinated_discard_required_cnt) {
  3479. ret = -EBUSY;
  3480. } else {
  3481. ram_block_discard_disabled_cnt++;
  3482. }
  3483. ram_block_discard_disable_mutex_unlock();
  3484. return ret;
  3485. }
  3486. int ram_block_uncoordinated_discard_disable(bool state)
  3487. {
  3488. int ret = 0;
  3489. ram_block_discard_disable_mutex_lock();
  3490. if (!state) {
  3491. ram_block_uncoordinated_discard_disabled_cnt--;
  3492. } else if (ram_block_discard_required_cnt) {
  3493. ret = -EBUSY;
  3494. } else {
  3495. ram_block_uncoordinated_discard_disabled_cnt++;
  3496. }
  3497. ram_block_discard_disable_mutex_unlock();
  3498. return ret;
  3499. }
  3500. int ram_block_discard_require(bool state)
  3501. {
  3502. int ret = 0;
  3503. ram_block_discard_disable_mutex_lock();
  3504. if (!state) {
  3505. ram_block_discard_required_cnt--;
  3506. } else if (ram_block_discard_disabled_cnt ||
  3507. ram_block_uncoordinated_discard_disabled_cnt) {
  3508. ret = -EBUSY;
  3509. } else {
  3510. ram_block_discard_required_cnt++;
  3511. }
  3512. ram_block_discard_disable_mutex_unlock();
  3513. return ret;
  3514. }
  3515. int ram_block_coordinated_discard_require(bool state)
  3516. {
  3517. int ret = 0;
  3518. ram_block_discard_disable_mutex_lock();
  3519. if (!state) {
  3520. ram_block_coordinated_discard_required_cnt--;
  3521. } else if (ram_block_discard_disabled_cnt) {
  3522. ret = -EBUSY;
  3523. } else {
  3524. ram_block_coordinated_discard_required_cnt++;
  3525. }
  3526. ram_block_discard_disable_mutex_unlock();
  3527. return ret;
  3528. }
  3529. bool ram_block_discard_is_disabled(void)
  3530. {
  3531. return qatomic_read(&ram_block_discard_disabled_cnt) ||
  3532. qatomic_read(&ram_block_uncoordinated_discard_disabled_cnt);
  3533. }
  3534. bool ram_block_discard_is_required(void)
  3535. {
  3536. return qatomic_read(&ram_block_discard_required_cnt) ||
  3537. qatomic_read(&ram_block_coordinated_discard_required_cnt);
  3538. }
  3539. /*
  3540. * Return true if ram is compatible with CPR. Do not exclude rom,
  3541. * because the rom file could change in new QEMU.
  3542. */
  3543. static bool ram_is_cpr_compatible(RAMBlock *rb)
  3544. {
  3545. MemoryRegion *mr = rb->mr;
  3546. if (!mr || !memory_region_is_ram(mr)) {
  3547. return true;
  3548. }
  3549. /* Ram device is remapped in new QEMU */
  3550. if (memory_region_is_ram_device(mr)) {
  3551. return true;
  3552. }
  3553. /*
  3554. * A file descriptor is passed to new QEMU and remapped, or its backing
  3555. * file is reopened and mapped. It must be shared to avoid COW.
  3556. */
  3557. if (rb->fd >= 0 && qemu_ram_is_shared(rb)) {
  3558. return true;
  3559. }
  3560. return false;
  3561. }
  3562. /*
  3563. * Add a blocker for each volatile ram block. This function should only be
  3564. * called after we know that the block is migratable. Non-migratable blocks
  3565. * are either re-created in new QEMU, or are handled specially, or are covered
  3566. * by a device-level CPR blocker.
  3567. */
  3568. void ram_block_add_cpr_blocker(RAMBlock *rb, Error **errp)
  3569. {
  3570. assert(qemu_ram_is_migratable(rb));
  3571. if (ram_is_cpr_compatible(rb)) {
  3572. return;
  3573. }
  3574. error_setg(&rb->cpr_blocker,
  3575. "Memory region %s is not compatible with CPR. share=on is "
  3576. "required for memory-backend objects, and aux-ram-share=on is "
  3577. "required.", memory_region_name(rb->mr));
  3578. migrate_add_blocker_modes(&rb->cpr_blocker, errp, MIG_MODE_CPR_TRANSFER,
  3579. -1);
  3580. }
  3581. void ram_block_del_cpr_blocker(RAMBlock *rb)
  3582. {
  3583. migrate_del_blocker(&rb->cpr_blocker);
  3584. }