2
0

exec.c 113 KB

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