exec.c 117 KB

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