exec.c 98 KB

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