Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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