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

4043 Zeilen
119KB

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