exec.c 122 KB

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