exec.c 119 KB

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