exec.c 102 KB

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