exec.c 100.6 KB
Newer Older
B
bellard 已提交
1
/*
2
 *  Virtual page mapping
3
 *
B
bellard 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16
 *  Copyright (c) 2003 Fabrice Bellard
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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/>.
B
bellard 已提交
18
 */
B
bellard 已提交
19
#include "config.h"
20
#ifndef _WIN32
B
bellard 已提交
21
#include <sys/types.h>
B
bellard 已提交
22 23
#include <sys/mman.h>
#endif
B
bellard 已提交
24

25
#include "qemu-common.h"
B
bellard 已提交
26
#include "cpu.h"
B
bellard 已提交
27
#include "tcg.h"
28
#include "hw/hw.h"
29
#if !defined(CONFIG_USER_ONLY)
30
#include "hw/boards.h"
31
#endif
32
#include "hw/qdev.h"
33
#include "qemu/osdep.h"
34
#include "sysemu/kvm.h"
35
#include "sysemu/sysemu.h"
P
Paolo Bonzini 已提交
36
#include "hw/xen/xen.h"
37 38
#include "qemu/timer.h"
#include "qemu/config-file.h"
39
#include "qemu/error-report.h"
40
#include "exec/memory.h"
41
#include "sysemu/dma.h"
42
#include "exec/address-spaces.h"
43 44
#if defined(CONFIG_USER_ONLY)
#include <qemu.h>
J
Jun Nakajima 已提交
45
#else /* !CONFIG_USER_ONLY */
46
#include "sysemu/xen-mapcache.h"
47
#include "trace.h"
48
#endif
49
#include "exec/cpu-all.h"
M
Mike Day 已提交
50
#include "qemu/rcu_queue.h"
51
#include "qemu/main-loop.h"
52
#include "translate-all.h"
53

54
#include "exec/memory-internal.h"
55
#include "exec/ram_addr.h"
56

57
#include "qemu/range.h"
58 59 60
#ifndef _WIN32
#include "qemu/mmap-alloc.h"
#endif
61

62
//#define DEBUG_SUBPAGE
T
ths 已提交
63

64
#if !defined(CONFIG_USER_ONLY)
M
Mike Day 已提交
65 66 67
/* ram_list is read under rcu_read_lock()/rcu_read_unlock().  Writes
 * are protected by the ramlist lock.
 */
M
Mike Day 已提交
68
RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
A
Avi Kivity 已提交
69 70

static MemoryRegion *system_memory;
71
static MemoryRegion *system_io;
A
Avi Kivity 已提交
72

73 74
AddressSpace address_space_io;
AddressSpace address_space_memory;
75

76
MemoryRegion io_mem_rom, io_mem_notdirty;
77
static MemoryRegion io_mem_unassigned;
78

79 80 81
/* RAM is pre-allocated and passed into qemu_ram_alloc_from_ptr */
#define RAM_PREALLOC   (1 << 0)

82 83 84
/* RAM is mmap-ed with MAP_SHARED */
#define RAM_SHARED     (1 << 1)

85 86 87 88 89
/* Only a portion of RAM (used_length) is actually used, and migrated.
 * This used_length size can change across reboots.
 */
#define RAM_RESIZEABLE (1 << 2)

90
/* RAM is backed by an mmapped file.
91
 */
92
#define RAM_FILE (1 << 3)
93
#endif
94

A
Andreas Färber 已提交
95
struct CPUTailQ cpus = QTAILQ_HEAD_INITIALIZER(cpus);
B
bellard 已提交
96 97
/* current CPU in the current thread. It is only valid inside
   cpu_exec() */
P
Paolo Bonzini 已提交
98
__thread CPUState *current_cpu;
P
pbrook 已提交
99
/* 0 = Do not count executed instructions.
T
ths 已提交
100
   1 = Precise instruction counting.
P
pbrook 已提交
101
   2 = Adaptive rate instruction counting.  */
102
int use_icount;
B
bellard 已提交
103

104
#if !defined(CONFIG_USER_ONLY)
105

106 107 108
typedef struct PhysPageEntry PhysPageEntry;

struct PhysPageEntry {
M
Michael S. Tsirkin 已提交
109
    /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
110
    uint32_t skip : 6;
M
Michael S. Tsirkin 已提交
111
     /* index into phys_sections (!skip) or phys_map_nodes (skip) */
112
    uint32_t ptr : 26;
113 114
};

115 116
#define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)

117
/* Size of the L2 (and L3, etc) page tables.  */
118
#define ADDR_SPACE_BITS 64
119

M
Michael S. Tsirkin 已提交
120
#define P_L2_BITS 9
121 122 123 124 125
#define P_L2_SIZE (1 << P_L2_BITS)

#define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)

typedef PhysPageEntry Node[P_L2_SIZE];
126

127
typedef struct PhysPageMap {
128 129
    struct rcu_head rcu;

130 131 132 133 134 135 136 137
    unsigned sections_nb;
    unsigned sections_nb_alloc;
    unsigned nodes_nb;
    unsigned nodes_nb_alloc;
    Node *nodes;
    MemoryRegionSection *sections;
} PhysPageMap;

138
struct AddressSpaceDispatch {
139 140
    struct rcu_head rcu;

141 142 143 144
    /* This is a multi-level map on the physical address space.
     * The bottom level has pointers to MemoryRegionSections.
     */
    PhysPageEntry phys_map;
145
    PhysPageMap map;
146
    AddressSpace *as;
147 148
};

149 150 151
#define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
typedef struct subpage_t {
    MemoryRegion iomem;
152
    AddressSpace *as;
153 154 155 156
    hwaddr base;
    uint16_t sub_section[TARGET_PAGE_SIZE];
} subpage_t;

157 158 159 160
#define PHYS_SECTION_UNASSIGNED 0
#define PHYS_SECTION_NOTDIRTY 1
#define PHYS_SECTION_ROM 2
#define PHYS_SECTION_WATCH 3
161

162
static void io_mem_init(void);
A
Avi Kivity 已提交
163
static void memory_map_init(void);
164
static void tcg_commit(MemoryListener *listener);
165

166
static MemoryRegion io_mem_watch;
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

/**
 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
 * @cpu: the CPU whose AddressSpace this is
 * @as: the AddressSpace itself
 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
 * @tcg_as_listener: listener for tracking changes to the AddressSpace
 */
struct CPUAddressSpace {
    CPUState *cpu;
    AddressSpace *as;
    struct AddressSpaceDispatch *memory_dispatch;
    MemoryListener tcg_as_listener;
};

182
#endif
B
bellard 已提交
183

184
#if !defined(CONFIG_USER_ONLY)
185

186
static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
187
{
188 189 190 191
    if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
        map->nodes_nb_alloc = MAX(map->nodes_nb_alloc * 2, 16);
        map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, map->nodes_nb + nodes);
        map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
192
    }
193 194
}

195
static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
196 197
{
    unsigned i;
198
    uint32_t ret;
199 200
    PhysPageEntry e;
    PhysPageEntry *p;
201

202
    ret = map->nodes_nb++;
203
    p = map->nodes[ret];
204
    assert(ret != PHYS_MAP_NODE_NIL);
205
    assert(ret != map->nodes_nb_alloc);
206 207 208

    e.skip = leaf ? 0 : 1;
    e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
209
    for (i = 0; i < P_L2_SIZE; ++i) {
210
        memcpy(&p[i], &e, sizeof(e));
211
    }
212
    return ret;
213 214
}

215 216
static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
                                hwaddr *index, hwaddr *nb, uint16_t leaf,
217
                                int level)
218 219
{
    PhysPageEntry *p;
220
    hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
221

M
Michael S. Tsirkin 已提交
222
    if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
223
        lp->ptr = phys_map_node_alloc(map, level == 0);
B
bellard 已提交
224
    }
225
    p = map->nodes[lp->ptr];
226
    lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
227

228
    while (*nb && lp < &p[P_L2_SIZE]) {
229
        if ((*index & (step - 1)) == 0 && *nb >= step) {
M
Michael S. Tsirkin 已提交
230
            lp->skip = 0;
231
            lp->ptr = leaf;
232 233
            *index += step;
            *nb -= step;
234
        } else {
235
            phys_page_set_level(map, lp, index, nb, leaf, level - 1);
236 237
        }
        ++lp;
238 239 240
    }
}

A
Avi Kivity 已提交
241
static void phys_page_set(AddressSpaceDispatch *d,
A
Avi Kivity 已提交
242
                          hwaddr index, hwaddr nb,
243
                          uint16_t leaf)
244
{
245
    /* Wildly overreserve - it doesn't matter much. */
246
    phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
247

248
    phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
B
bellard 已提交
249 250
}

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
/* Compact a non leaf page entry. Simply detect that the entry has a single child,
 * and update our entry so we can skip it and go directly to the destination.
 */
static void phys_page_compact(PhysPageEntry *lp, Node *nodes, unsigned long *compacted)
{
    unsigned valid_ptr = P_L2_SIZE;
    int valid = 0;
    PhysPageEntry *p;
    int i;

    if (lp->ptr == PHYS_MAP_NODE_NIL) {
        return;
    }

    p = nodes[lp->ptr];
    for (i = 0; i < P_L2_SIZE; i++) {
        if (p[i].ptr == PHYS_MAP_NODE_NIL) {
            continue;
        }

        valid_ptr = i;
        valid++;
        if (p[i].skip) {
            phys_page_compact(&p[i], nodes, compacted);
        }
    }

    /* We can only compress if there's only one child. */
    if (valid != 1) {
        return;
    }

    assert(valid_ptr < P_L2_SIZE);

    /* Don't compress if it won't fit in the # of bits we have. */
    if (lp->skip + p[valid_ptr].skip >= (1 << 3)) {
        return;
    }

    lp->ptr = p[valid_ptr].ptr;
    if (!p[valid_ptr].skip) {
        /* If our only child is a leaf, make this a leaf. */
        /* By design, we should have made this node a leaf to begin with so we
         * should never reach here.
         * But since it's so simple to handle this, let's do it just in case we
         * change this rule.
         */
        lp->skip = 0;
    } else {
        lp->skip += p[valid_ptr].skip;
    }
}

static void phys_page_compact_all(AddressSpaceDispatch *d, int nodes_nb)
{
    DECLARE_BITMAP(compacted, nodes_nb);

    if (d->phys_map.skip) {
309
        phys_page_compact(&d->phys_map, d->map.nodes, compacted);
310 311 312
    }
}

313
static MemoryRegionSection *phys_page_find(PhysPageEntry lp, hwaddr addr,
314
                                           Node *nodes, MemoryRegionSection *sections)
B
bellard 已提交
315
{
316
    PhysPageEntry *p;
317
    hwaddr index = addr >> TARGET_PAGE_BITS;
318
    int i;
319

M
Michael S. Tsirkin 已提交
320
    for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
321
        if (lp.ptr == PHYS_MAP_NODE_NIL) {
322
            return &sections[PHYS_SECTION_UNASSIGNED];
323
        }
324
        p = nodes[lp.ptr];
325
        lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
326
    }
327 328 329 330 331 332 333 334

    if (sections[lp.ptr].size.hi ||
        range_covers_byte(sections[lp.ptr].offset_within_address_space,
                          sections[lp.ptr].size.lo, addr)) {
        return &sections[lp.ptr];
    } else {
        return &sections[PHYS_SECTION_UNASSIGNED];
    }
335 336
}

B
Blue Swirl 已提交
337 338
bool memory_region_is_unassigned(MemoryRegion *mr)
{
P
Paolo Bonzini 已提交
339
    return mr != &io_mem_rom && mr != &io_mem_notdirty && !mr->rom_device
340
        && mr != &io_mem_watch;
B
bellard 已提交
341
}
342

343
/* Called from RCU critical section */
344
static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
345 346
                                                        hwaddr addr,
                                                        bool resolve_subpage)
347
{
348 349 350
    MemoryRegionSection *section;
    subpage_t *subpage;

351
    section = phys_page_find(d->phys_map, addr, d->map.nodes, d->map.sections);
352 353
    if (resolve_subpage && section->mr->subpage) {
        subpage = container_of(section->mr, subpage_t, iomem);
354
        section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
355 356
    }
    return section;
357 358
}

359
/* Called from RCU critical section */
360
static MemoryRegionSection *
361
address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
362
                                 hwaddr *plen, bool resolve_subpage)
363 364
{
    MemoryRegionSection *section;
365
    MemoryRegion *mr;
366
    Int128 diff;
367

368
    section = address_space_lookup_region(d, addr, resolve_subpage);
369 370 371 372 373 374
    /* Compute offset within MemoryRegionSection */
    addr -= section->offset_within_address_space;

    /* Compute offset within MemoryRegion */
    *xlat = addr + section->offset_within_region;

375
    mr = section->mr;
376 377 378 379 380 381 382 383 384 385 386 387

    /* MMIO registers can be expected to perform full-width accesses based only
     * on their address, without considering adjacent registers that could
     * decode to completely different MemoryRegions.  When such registers
     * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
     * regions overlap wildly.  For this reason we cannot clamp the accesses
     * here.
     *
     * If the length is small (as is the case for address_space_ldl/stl),
     * everything works fine.  If the incoming length is large, however,
     * the caller really has to do the clamping through memory_access_size.
     */
388
    if (memory_region_is_ram(mr)) {
389
        diff = int128_sub(section->size, int128_make64(addr));
390 391
        *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
    }
392 393
    return section;
}
394

395 396 397 398 399 400 401 402 403 404 405 406
static inline bool memory_access_is_direct(MemoryRegion *mr, bool is_write)
{
    if (memory_region_is_ram(mr)) {
        return !(is_write && mr->readonly);
    }
    if (memory_region_is_romd(mr)) {
        return !is_write;
    }

    return false;
}

407
/* Called from RCU critical section */
408 409 410
MemoryRegion *address_space_translate(AddressSpace *as, hwaddr addr,
                                      hwaddr *xlat, hwaddr *plen,
                                      bool is_write)
411
{
A
Avi Kivity 已提交
412 413 414 415 416
    IOMMUTLBEntry iotlb;
    MemoryRegionSection *section;
    MemoryRegion *mr;

    for (;;) {
417 418
        AddressSpaceDispatch *d = atomic_rcu_read(&as->dispatch);
        section = address_space_translate_internal(d, addr, &addr, plen, true);
A
Avi Kivity 已提交
419 420 421 422 423 424
        mr = section->mr;

        if (!mr->iommu_ops) {
            break;
        }

425
        iotlb = mr->iommu_ops->translate(mr, addr, is_write);
A
Avi Kivity 已提交
426 427
        addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
                | (addr & iotlb.addr_mask));
428
        *plen = MIN(*plen, (addr | iotlb.addr_mask) - addr + 1);
A
Avi Kivity 已提交
429 430 431 432 433 434 435 436
        if (!(iotlb.perm & (1 << is_write))) {
            mr = &io_mem_unassigned;
            break;
        }

        as = iotlb.target_as;
    }

437
    if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
438
        hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
439
        *plen = MIN(page, *plen);
440 441
    }

A
Avi Kivity 已提交
442 443
    *xlat = addr;
    return mr;
444 445
}

446
/* Called from RCU critical section */
447
MemoryRegionSection *
P
Paolo Bonzini 已提交
448 449
address_space_translate_for_iotlb(CPUState *cpu, hwaddr addr,
                                  hwaddr *xlat, hwaddr *plen)
450
{
A
Avi Kivity 已提交
451
    MemoryRegionSection *section;
452
    section = address_space_translate_internal(cpu->cpu_ases[0].memory_dispatch,
P
Paolo Bonzini 已提交
453
                                               addr, xlat, plen, false);
A
Avi Kivity 已提交
454 455 456

    assert(!section->mr->iommu_ops);
    return section;
457
}
458
#endif
B
bellard 已提交
459

460
#if !defined(CONFIG_USER_ONLY)
461 462

static int cpu_common_post_load(void *opaque, int version_id)
B
bellard 已提交
463
{
464
    CPUState *cpu = opaque;
B
bellard 已提交
465

466 467
    /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
       version_id is increased. */
468
    cpu->interrupt_request &= ~0x01;
469
    tlb_flush(cpu, 1);
470 471

    return 0;
B
bellard 已提交
472
}
B
bellard 已提交
473

474 475 476 477
static int cpu_common_pre_load(void *opaque)
{
    CPUState *cpu = opaque;

478
    cpu->exception_index = -1;
479 480 481 482 483 484 485 486

    return 0;
}

static bool cpu_common_exception_index_needed(void *opaque)
{
    CPUState *cpu = opaque;

487
    return tcg_enabled() && cpu->exception_index != -1;
488 489 490 491 492 493
}

static const VMStateDescription vmstate_cpu_common_exception_index = {
    .name = "cpu_common/exception_index",
    .version_id = 1,
    .minimum_version_id = 1,
494
    .needed = cpu_common_exception_index_needed,
495 496 497 498 499 500
    .fields = (VMStateField[]) {
        VMSTATE_INT32(exception_index, CPUState),
        VMSTATE_END_OF_LIST()
    }
};

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
static bool cpu_common_crash_occurred_needed(void *opaque)
{
    CPUState *cpu = opaque;

    return cpu->crash_occurred;
}

static const VMStateDescription vmstate_cpu_common_crash_occurred = {
    .name = "cpu_common/crash_occurred",
    .version_id = 1,
    .minimum_version_id = 1,
    .needed = cpu_common_crash_occurred_needed,
    .fields = (VMStateField[]) {
        VMSTATE_BOOL(crash_occurred, CPUState),
        VMSTATE_END_OF_LIST()
    }
};

519
const VMStateDescription vmstate_cpu_common = {
520 521 522
    .name = "cpu_common",
    .version_id = 1,
    .minimum_version_id = 1,
523
    .pre_load = cpu_common_pre_load,
524
    .post_load = cpu_common_post_load,
525
    .fields = (VMStateField[]) {
526 527
        VMSTATE_UINT32(halted, CPUState),
        VMSTATE_UINT32(interrupt_request, CPUState),
528
        VMSTATE_END_OF_LIST()
529
    },
530 531
    .subsections = (const VMStateDescription*[]) {
        &vmstate_cpu_common_exception_index,
532
        &vmstate_cpu_common_crash_occurred,
533
        NULL
534 535
    }
};
536

537
#endif
B
bellard 已提交
538

539
CPUState *qemu_get_cpu(int index)
B
bellard 已提交
540
{
A
Andreas Färber 已提交
541
    CPUState *cpu;
B
bellard 已提交
542

A
Andreas Färber 已提交
543
    CPU_FOREACH(cpu) {
544
        if (cpu->cpu_index == index) {
A
Andreas Färber 已提交
545
            return cpu;
546
        }
B
bellard 已提交
547
    }
548

A
Andreas Färber 已提交
549
    return NULL;
B
bellard 已提交
550 551
}

552 553 554 555 556 557
#if !defined(CONFIG_USER_ONLY)
void tcg_cpu_address_space_init(CPUState *cpu, AddressSpace *as)
{
    /* We only support one address space per cpu at the moment.  */
    assert(cpu->as == as);

558 559 560
    if (cpu->cpu_ases) {
        /* We've already registered the listener for our only AS */
        return;
561
    }
562 563 564 565 566 567

    cpu->cpu_ases = g_new0(CPUAddressSpace, 1);
    cpu->cpu_ases[0].cpu = cpu;
    cpu->cpu_ases[0].as = as;
    cpu->cpu_ases[0].tcg_as_listener.commit = tcg_commit;
    memory_listener_register(&cpu->cpu_ases[0].tcg_as_listener, as);
568 569 570
}
#endif

571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
#ifndef CONFIG_USER_ONLY
static DECLARE_BITMAP(cpu_index_map, MAX_CPUMASK_BITS);

static int cpu_get_free_index(Error **errp)
{
    int cpu = find_first_zero_bit(cpu_index_map, MAX_CPUMASK_BITS);

    if (cpu >= MAX_CPUMASK_BITS) {
        error_setg(errp, "Trying to use more CPUs than max of %d",
                   MAX_CPUMASK_BITS);
        return -1;
    }

    bitmap_set(cpu_index_map, cpu, 1);
    return cpu;
}

void cpu_exec_exit(CPUState *cpu)
{
    if (cpu->cpu_index == -1) {
        /* cpu_index was never allocated by this @cpu or was already freed. */
        return;
    }

    bitmap_clear(cpu_index_map, cpu->cpu_index, 1);
    cpu->cpu_index = -1;
}
#else

static int cpu_get_free_index(Error **errp)
{
    CPUState *some_cpu;
    int cpu_index = 0;

    CPU_FOREACH(some_cpu) {
        cpu_index++;
    }
    return cpu_index;
}

void cpu_exec_exit(CPUState *cpu)
{
}
#endif

616
void cpu_exec_init(CPUState *cpu, Error **errp)
B
bellard 已提交
617
{
618
    CPUClass *cc = CPU_GET_CLASS(cpu);
619
    int cpu_index;
620
    Error *local_err = NULL;
621

622 623 624 625 626
#ifndef CONFIG_USER_ONLY
    cpu->as = &address_space_memory;
    cpu->thread_id = qemu_get_thread_id();
#endif

627 628 629
#if defined(CONFIG_USER_ONLY)
    cpu_list_lock();
#endif
630 631 632 633 634 635 636
    cpu_index = cpu->cpu_index = cpu_get_free_index(&local_err);
    if (local_err) {
        error_propagate(errp, local_err);
#if defined(CONFIG_USER_ONLY)
        cpu_list_unlock();
#endif
        return;
637
    }
A
Andreas Färber 已提交
638
    QTAILQ_INSERT_TAIL(&cpus, cpu, node);
639 640 641
#if defined(CONFIG_USER_ONLY)
    cpu_list_unlock();
#endif
642 643 644
    if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
        vmstate_register(NULL, cpu_index, &vmstate_cpu_common, cpu);
    }
645 646
#if defined(CPU_SAVE_VERSION) && !defined(CONFIG_USER_ONLY)
    register_savevm(NULL, "cpu", cpu_index, CPU_SAVE_VERSION,
647
                    cpu_save, cpu_load, cpu->env_ptr);
648
    assert(cc->vmsd == NULL);
649
    assert(qdev_get_vmsd(DEVICE(cpu)) == NULL);
650
#endif
651 652 653
    if (cc->vmsd != NULL) {
        vmstate_register(NULL, cpu_index, cc->vmsd, cpu);
    }
B
bellard 已提交
654 655
}

656
#if defined(CONFIG_USER_ONLY)
657
static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
658 659 660 661
{
    tb_invalidate_phys_page_range(pc, pc + 1, 0);
}
#else
662
static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
663
{
664 665
    hwaddr phys = cpu_get_phys_page_debug(cpu, pc);
    if (phys != -1) {
666
        tb_invalidate_phys_addr(cpu->as,
667
                                phys | (pc & ~TARGET_PAGE_MASK));
668
    }
669
}
B
bellard 已提交
670
#endif
B
bellard 已提交
671

672
#if defined(CONFIG_USER_ONLY)
673
void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
674 675 676 677

{
}

678 679 680 681 682 683 684 685 686 687
int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
                          int flags)
{
    return -ENOSYS;
}

void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
{
}

688
int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
689 690 691 692 693
                          int flags, CPUWatchpoint **watchpoint)
{
    return -ENOSYS;
}
#else
694
/* Add a watchpoint.  */
695
int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
696
                          int flags, CPUWatchpoint **watchpoint)
697
{
698
    CPUWatchpoint *wp;
699

700
    /* forbid ranges which are empty or run off the end of the address space */
701
    if (len == 0 || (addr + len - 1) < addr) {
702 703
        error_report("tried to set invalid watchpoint at %"
                     VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
704 705
        return -EINVAL;
    }
706
    wp = g_malloc(sizeof(*wp));
707 708

    wp->vaddr = addr;
709
    wp->len = len;
710 711
    wp->flags = flags;

712
    /* keep all GDB-injected watchpoints in front */
713 714 715 716 717
    if (flags & BP_GDB) {
        QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
    } else {
        QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
    }
718

719
    tlb_flush_page(cpu, addr);
720 721 722 723

    if (watchpoint)
        *watchpoint = wp;
    return 0;
724 725
}

726
/* Remove a specific watchpoint.  */
727
int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
728
                          int flags)
729
{
730
    CPUWatchpoint *wp;
731

732
    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
733
        if (addr == wp->vaddr && len == wp->len
734
                && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
735
            cpu_watchpoint_remove_by_ref(cpu, wp);
736 737 738
            return 0;
        }
    }
739
    return -ENOENT;
740 741
}

742
/* Remove a specific watchpoint by reference.  */
743
void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
744
{
745
    QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
746

747
    tlb_flush_page(cpu, watchpoint->vaddr);
748

749
    g_free(watchpoint);
750 751 752
}

/* Remove all matching watchpoints.  */
753
void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
754
{
755
    CPUWatchpoint *wp, *next;
756

757
    QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
758 759 760
        if (wp->flags & mask) {
            cpu_watchpoint_remove_by_ref(cpu, wp);
        }
761
    }
762
}
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783

/* Return true if this watchpoint address matches the specified
 * access (ie the address range covered by the watchpoint overlaps
 * partially or completely with the address range covered by the
 * access).
 */
static inline bool cpu_watchpoint_address_matches(CPUWatchpoint *wp,
                                                  vaddr addr,
                                                  vaddr len)
{
    /* We know the lengths are non-zero, but a little caution is
     * required to avoid errors in the case where the range ends
     * exactly at the top of the address space and so addr + len
     * wraps round to zero.
     */
    vaddr wpend = wp->vaddr + wp->len - 1;
    vaddr addrend = addr + len - 1;

    return !(addr > wpend || wp->vaddr > addrend);
}

784
#endif
785

786
/* Add a breakpoint.  */
787
int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
788
                          CPUBreakpoint **breakpoint)
B
bellard 已提交
789
{
790
    CPUBreakpoint *bp;
791

792
    bp = g_malloc(sizeof(*bp));
B
bellard 已提交
793

794 795 796
    bp->pc = pc;
    bp->flags = flags;

797
    /* keep all GDB-injected breakpoints in front */
798
    if (flags & BP_GDB) {
799
        QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
800
    } else {
801
        QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
802
    }
803

804
    breakpoint_invalidate(cpu, pc);
805

806
    if (breakpoint) {
807
        *breakpoint = bp;
808
    }
B
bellard 已提交
809 810 811
    return 0;
}

812
/* Remove a specific breakpoint.  */
813
int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
814 815 816
{
    CPUBreakpoint *bp;

817
    QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
818
        if (bp->pc == pc && bp->flags == flags) {
819
            cpu_breakpoint_remove_by_ref(cpu, bp);
820 821
            return 0;
        }
822
    }
823
    return -ENOENT;
824 825
}

826
/* Remove a specific breakpoint by reference.  */
827
void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
B
bellard 已提交
828
{
829 830 831
    QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);

    breakpoint_invalidate(cpu, breakpoint->pc);
832

833
    g_free(breakpoint);
834 835 836
}

/* Remove all matching breakpoints. */
837
void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
838
{
839
    CPUBreakpoint *bp, *next;
840

841
    QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
842 843 844
        if (bp->flags & mask) {
            cpu_breakpoint_remove_by_ref(cpu, bp);
        }
845
    }
B
bellard 已提交
846 847
}

B
bellard 已提交
848 849
/* enable or disable single step mode. EXCP_DEBUG is returned by the
   CPU loop after each instruction */
850
void cpu_single_step(CPUState *cpu, int enabled)
B
bellard 已提交
851
{
852 853 854
    if (cpu->singlestep_enabled != enabled) {
        cpu->singlestep_enabled = enabled;
        if (kvm_enabled()) {
855
            kvm_update_guest_debug(cpu, 0);
856
        } else {
S
Stuart Brady 已提交
857
            /* must flush all the translated code to avoid inconsistencies */
858
            /* XXX: only flush what is necessary */
859
            tb_flush(cpu);
860
        }
B
bellard 已提交
861 862 863
    }
}

864
void cpu_abort(CPUState *cpu, const char *fmt, ...)
B
bellard 已提交
865 866
{
    va_list ap;
P
pbrook 已提交
867
    va_list ap2;
B
bellard 已提交
868 869

    va_start(ap, fmt);
P
pbrook 已提交
870
    va_copy(ap2, ap);
B
bellard 已提交
871 872 873
    fprintf(stderr, "qemu: fatal: ");
    vfprintf(stderr, fmt, ap);
    fprintf(stderr, "\n");
874
    cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU | CPU_DUMP_CCOP);
875 876 877 878
    if (qemu_log_enabled()) {
        qemu_log("qemu: fatal: ");
        qemu_log_vprintf(fmt, ap2);
        qemu_log("\n");
879
        log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
880
        qemu_log_flush();
881
        qemu_log_close();
882
    }
P
pbrook 已提交
883
    va_end(ap2);
884
    va_end(ap);
885 886 887 888 889 890 891 892
#if defined(CONFIG_USER_ONLY)
    {
        struct sigaction act;
        sigfillset(&act.sa_mask);
        act.sa_handler = SIG_DFL;
        sigaction(SIGABRT, &act, NULL);
    }
#endif
B
bellard 已提交
893 894 895
    abort();
}

896
#if !defined(CONFIG_USER_ONLY)
M
Mike Day 已提交
897
/* Called from RCU critical section */
P
Paolo Bonzini 已提交
898 899 900 901
static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
{
    RAMBlock *block;

P
Paolo Bonzini 已提交
902
    block = atomic_rcu_read(&ram_list.mru_block);
903
    if (block && addr - block->offset < block->max_length) {
P
Paolo Bonzini 已提交
904 905
        goto found;
    }
M
Mike Day 已提交
906
    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
907
        if (addr - block->offset < block->max_length) {
P
Paolo Bonzini 已提交
908 909 910 911 912 913 914 915
            goto found;
        }
    }

    fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
    abort();

found:
P
Paolo Bonzini 已提交
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
    /* It is safe to write mru_block outside the iothread lock.  This
     * is what happens:
     *
     *     mru_block = xxx
     *     rcu_read_unlock()
     *                                        xxx removed from list
     *                  rcu_read_lock()
     *                  read mru_block
     *                                        mru_block = NULL;
     *                                        call_rcu(reclaim_ramblock, xxx);
     *                  rcu_read_unlock()
     *
     * atomic_rcu_set is not needed here.  The block was already published
     * when it was placed into the list.  Here we're just making an extra
     * copy of the pointer.
     */
P
Paolo Bonzini 已提交
932 933 934 935
    ram_list.mru_block = block;
    return block;
}

936
static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
J
Juan Quintela 已提交
937
{
938
    CPUState *cpu;
P
Paolo Bonzini 已提交
939
    ram_addr_t start1;
940 941 942 943 944
    RAMBlock *block;
    ram_addr_t end;

    end = TARGET_PAGE_ALIGN(start + length);
    start &= TARGET_PAGE_MASK;
J
Juan Quintela 已提交
945

M
Mike Day 已提交
946
    rcu_read_lock();
P
Paolo Bonzini 已提交
947 948
    block = qemu_get_ram_block(start);
    assert(block == qemu_get_ram_block(end - 1));
949
    start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
950 951 952
    CPU_FOREACH(cpu) {
        tlb_reset_dirty(cpu, start1, length);
    }
M
Mike Day 已提交
953
    rcu_read_unlock();
J
Juan Quintela 已提交
954 955
}

P
pbrook 已提交
956
/* Note: start and end must be within the same ram block.  */
957 958 959
bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
                                              ram_addr_t length,
                                              unsigned client)
960
{
961 962 963 964 965 966
    unsigned long end, page;
    bool dirty;

    if (length == 0) {
        return false;
    }
B
bellard 已提交
967

968 969 970 971 972 973
    end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
    page = start >> TARGET_PAGE_BITS;
    dirty = bitmap_test_and_clear_atomic(ram_list.dirty_memory[client],
                                         page, end - page);

    if (dirty && tcg_enabled()) {
974
        tlb_reset_dirty_range_all(start, length);
P
pbrook 已提交
975
    }
976 977

    return dirty;
978 979
}

980
/* Called from RCU critical section */
981
hwaddr memory_region_section_get_iotlb(CPUState *cpu,
982 983 984 985 986
                                       MemoryRegionSection *section,
                                       target_ulong vaddr,
                                       hwaddr paddr, hwaddr xlat,
                                       int prot,
                                       target_ulong *address)
B
Blue Swirl 已提交
987
{
A
Avi Kivity 已提交
988
    hwaddr iotlb;
B
Blue Swirl 已提交
989 990
    CPUWatchpoint *wp;

991
    if (memory_region_is_ram(section->mr)) {
B
Blue Swirl 已提交
992 993
        /* Normal RAM.  */
        iotlb = (memory_region_get_ram_addr(section->mr) & TARGET_PAGE_MASK)
994
            + xlat;
B
Blue Swirl 已提交
995
        if (!section->readonly) {
996
            iotlb |= PHYS_SECTION_NOTDIRTY;
B
Blue Swirl 已提交
997
        } else {
998
            iotlb |= PHYS_SECTION_ROM;
B
Blue Swirl 已提交
999 1000
        }
    } else {
1001 1002 1003 1004
        AddressSpaceDispatch *d;

        d = atomic_rcu_read(&section->address_space->dispatch);
        iotlb = section - d->map.sections;
1005
        iotlb += xlat;
B
Blue Swirl 已提交
1006 1007 1008 1009
    }

    /* Make accesses to pages with watchpoints go via the
       watchpoint trap routines.  */
1010
    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1011
        if (cpu_watchpoint_address_matches(wp, vaddr, TARGET_PAGE_SIZE)) {
B
Blue Swirl 已提交
1012 1013
            /* Avoid trapping reads of pages with a write breakpoint. */
            if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
1014
                iotlb = PHYS_SECTION_WATCH + paddr;
B
Blue Swirl 已提交
1015 1016 1017 1018 1019 1020 1021 1022
                *address |= TLB_MMIO;
                break;
            }
        }
    }

    return iotlb;
}
1023 1024
#endif /* defined(CONFIG_USER_ONLY) */

1025
#if !defined(CONFIG_USER_ONLY)
1026

A
Anthony Liguori 已提交
1027
static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
1028
                             uint16_t section);
1029
static subpage_t *subpage_init(AddressSpace *as, hwaddr base);
1030

1031 1032
static void *(*phys_mem_alloc)(size_t size, uint64_t *align) =
                               qemu_anon_ram_alloc;
1033 1034 1035 1036 1037 1038

/*
 * Set a custom physical guest memory alloator.
 * Accelerators with unusual needs may need this.  Hopefully, we can
 * get rid of it eventually.
 */
1039
void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align))
1040 1041 1042 1043
{
    phys_mem_alloc = alloc;
}

1044 1045
static uint16_t phys_section_add(PhysPageMap *map,
                                 MemoryRegionSection *section)
1046
{
1047 1048 1049 1050
    /* The physical section number is ORed with a page-aligned
     * pointer to produce the iotlb entries.  Thus it should
     * never overflow into the page-aligned value.
     */
1051
    assert(map->sections_nb < TARGET_PAGE_SIZE);
1052

1053 1054 1055 1056
    if (map->sections_nb == map->sections_nb_alloc) {
        map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
        map->sections = g_renew(MemoryRegionSection, map->sections,
                                map->sections_nb_alloc);
1057
    }
1058
    map->sections[map->sections_nb] = *section;
P
Paolo Bonzini 已提交
1059
    memory_region_ref(section->mr);
1060
    return map->sections_nb++;
1061 1062
}

1063 1064
static void phys_section_destroy(MemoryRegion *mr)
{
P
Paolo Bonzini 已提交
1065 1066
    memory_region_unref(mr);

1067 1068
    if (mr->subpage) {
        subpage_t *subpage = container_of(mr, subpage_t, iomem);
P
Peter Crosthwaite 已提交
1069
        object_unref(OBJECT(&subpage->iomem));
1070 1071 1072 1073
        g_free(subpage);
    }
}

P
Paolo Bonzini 已提交
1074
static void phys_sections_free(PhysPageMap *map)
1075
{
1076 1077
    while (map->sections_nb > 0) {
        MemoryRegionSection *section = &map->sections[--map->sections_nb];
1078 1079
        phys_section_destroy(section->mr);
    }
1080 1081
    g_free(map->sections);
    g_free(map->nodes);
1082 1083
}

A
Avi Kivity 已提交
1084
static void register_subpage(AddressSpaceDispatch *d, MemoryRegionSection *section)
1085 1086
{
    subpage_t *subpage;
A
Avi Kivity 已提交
1087
    hwaddr base = section->offset_within_address_space
1088
        & TARGET_PAGE_MASK;
1089
    MemoryRegionSection *existing = phys_page_find(d->phys_map, base,
1090
                                                   d->map.nodes, d->map.sections);
1091 1092
    MemoryRegionSection subsection = {
        .offset_within_address_space = base,
1093
        .size = int128_make64(TARGET_PAGE_SIZE),
1094
    };
A
Avi Kivity 已提交
1095
    hwaddr start, end;
1096

1097
    assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1098

1099
    if (!(existing->mr->subpage)) {
1100
        subpage = subpage_init(d->as, base);
1101
        subsection.address_space = d->as;
1102
        subsection.mr = &subpage->iomem;
A
Avi Kivity 已提交
1103
        phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1104
                      phys_section_add(&d->map, &subsection));
1105
    } else {
1106
        subpage = container_of(existing->mr, subpage_t, iomem);
1107 1108
    }
    start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1109
    end = start + int128_get64(section->size) - 1;
1110 1111
    subpage_register(subpage, start, end,
                     phys_section_add(&d->map, section));
1112 1113 1114
}


1115 1116
static void register_multipage(AddressSpaceDispatch *d,
                               MemoryRegionSection *section)
1117
{
A
Avi Kivity 已提交
1118
    hwaddr start_addr = section->offset_within_address_space;
1119
    uint16_t section_index = phys_section_add(&d->map, section);
1120 1121
    uint64_t num_pages = int128_get64(int128_rshift(section->size,
                                                    TARGET_PAGE_BITS));
1122

1123 1124
    assert(num_pages);
    phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1125 1126
}

A
Avi Kivity 已提交
1127
static void mem_add(MemoryListener *listener, MemoryRegionSection *section)
1128
{
1129
    AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
1130
    AddressSpaceDispatch *d = as->next_dispatch;
1131
    MemoryRegionSection now = *section, remain = *section;
1132
    Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1133

1134 1135 1136 1137
    if (now.offset_within_address_space & ~TARGET_PAGE_MASK) {
        uint64_t left = TARGET_PAGE_ALIGN(now.offset_within_address_space)
                       - now.offset_within_address_space;

1138
        now.size = int128_min(int128_make64(left), now.size);
A
Avi Kivity 已提交
1139
        register_subpage(d, &now);
1140
    } else {
1141
        now.size = int128_zero();
1142
    }
1143 1144 1145 1146
    while (int128_ne(remain.size, now.size)) {
        remain.size = int128_sub(remain.size, now.size);
        remain.offset_within_address_space += int128_get64(now.size);
        remain.offset_within_region += int128_get64(now.size);
1147
        now = remain;
1148
        if (int128_lt(remain.size, page_size)) {
1149
            register_subpage(d, &now);
1150
        } else if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1151
            now.size = page_size;
A
Avi Kivity 已提交
1152
            register_subpage(d, &now);
1153
        } else {
1154
            now.size = int128_and(now.size, int128_neg(page_size));
A
Avi Kivity 已提交
1155
            register_multipage(d, &now);
1156
        }
1157 1158 1159
    }
}

1160 1161 1162 1163 1164 1165
void qemu_flush_coalesced_mmio_buffer(void)
{
    if (kvm_enabled())
        kvm_flush_coalesced_mmio_buffer();
}

1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
void qemu_mutex_lock_ramlist(void)
{
    qemu_mutex_lock(&ram_list.mutex);
}

void qemu_mutex_unlock_ramlist(void)
{
    qemu_mutex_unlock(&ram_list.mutex);
}

1176
#ifdef __linux__
1177 1178 1179 1180 1181

#include <sys/vfs.h>

#define HUGETLBFS_MAGIC       0x958458f6

1182
static long gethugepagesize(const char *path, Error **errp)
1183 1184 1185 1186 1187
{
    struct statfs fs;
    int ret;

    do {
Y
Yoshiaki Tamura 已提交
1188
        ret = statfs(path, &fs);
1189 1190 1191
    } while (ret != 0 && errno == EINTR);

    if (ret != 0) {
1192 1193
        error_setg_errno(errp, errno, "failed to get page size of file %s",
                         path);
Y
Yoshiaki Tamura 已提交
1194
        return 0;
1195 1196 1197
    }

    if (fs.f_type != HUGETLBFS_MAGIC)
Y
Yoshiaki Tamura 已提交
1198
        fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
1199 1200 1201 1202

    return fs.f_bsize;
}

A
Alex Williamson 已提交
1203 1204
static void *file_ram_alloc(RAMBlock *block,
                            ram_addr_t memory,
1205 1206
                            const char *path,
                            Error **errp)
1207
{
1208
    struct stat st;
1209
    char *filename;
1210 1211
    char *sanitized_name;
    char *c;
1212
    void *area;
1213
    int fd;
1214
    uint64_t hpagesize;
1215
    Error *local_err = NULL;
1216

1217 1218 1219
    hpagesize = gethugepagesize(path, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
1220
        goto error;
1221
    }
1222
    block->mr->align = hpagesize;
1223 1224

    if (memory < hpagesize) {
1225 1226 1227 1228
        error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
                   "or larger than huge page size 0x%" PRIx64,
                   memory, hpagesize);
        goto error;
1229 1230 1231
    }

    if (kvm_enabled() && !kvm_has_sync_mmu()) {
1232 1233
        error_setg(errp,
                   "host lacks kvm mmu notifiers, -mem-path unsupported");
1234
        goto error;
1235 1236
    }

1237 1238 1239 1240 1241 1242 1243 1244
    if (!stat(path, &st) && S_ISDIR(st.st_mode)) {
        /* Make name safe to use with mkstemp by replacing '/' with '_'. */
        sanitized_name = g_strdup(memory_region_name(block->mr));
        for (c = sanitized_name; *c != '\0'; c++) {
            if (*c == '/') {
                *c = '_';
            }
        }
1245

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
        filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
                                   sanitized_name);
        g_free(sanitized_name);

        fd = mkstemp(filename);
        if (fd >= 0) {
            unlink(filename);
        }
        g_free(filename);
    } else {
        fd = open(path, O_RDWR | O_CREAT, 0644);
    }
1258 1259

    if (fd < 0) {
1260 1261
        error_setg_errno(errp, errno,
                         "unable to create backing store for hugepages");
1262
        goto error;
1263 1264
    }

1265
    memory = ROUND_UP(memory, hpagesize);
1266 1267 1268 1269 1270 1271 1272

    /*
     * ftruncate is not supported by hugetlbfs in older
     * hosts, so don't bother bailing out on errors.
     * If anything goes wrong with it under other filesystems,
     * mmap will fail.
     */
1273
    if (ftruncate(fd, memory)) {
Y
Yoshiaki Tamura 已提交
1274
        perror("ftruncate");
1275
    }
1276

1277
    area = qemu_ram_mmap(fd, memory, hpagesize, block->flags & RAM_SHARED);
1278
    if (area == MAP_FAILED) {
1279 1280
        error_setg_errno(errp, errno,
                         "unable to map backing store for hugepages");
Y
Yoshiaki Tamura 已提交
1281
        close(fd);
1282
        goto error;
1283
    }
1284 1285

    if (mem_prealloc) {
1286
        os_mem_prealloc(fd, area, memory);
1287 1288
    }

A
Alex Williamson 已提交
1289
    block->fd = fd;
1290
    return area;
1291 1292 1293

error:
    return NULL;
1294 1295 1296
}
#endif

M
Mike Day 已提交
1297
/* Called with the ramlist lock held.  */
1298
static ram_addr_t find_ram_offset(ram_addr_t size)
A
Alex Williamson 已提交
1299 1300
{
    RAMBlock *block, *next_block;
A
Alex Williamson 已提交
1301
    ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
A
Alex Williamson 已提交
1302

1303 1304
    assert(size != 0); /* it would hand out same offset multiple times */

M
Mike Day 已提交
1305
    if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
A
Alex Williamson 已提交
1306
        return 0;
M
Mike Day 已提交
1307
    }
A
Alex Williamson 已提交
1308

M
Mike Day 已提交
1309
    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1310
        ram_addr_t end, next = RAM_ADDR_MAX;
A
Alex Williamson 已提交
1311

1312
        end = block->offset + block->max_length;
A
Alex Williamson 已提交
1313

M
Mike Day 已提交
1314
        QLIST_FOREACH_RCU(next_block, &ram_list.blocks, next) {
A
Alex Williamson 已提交
1315 1316 1317 1318 1319
            if (next_block->offset >= end) {
                next = MIN(next, next_block->offset);
            }
        }
        if (next - end >= size && next - end < mingap) {
A
Alex Williamson 已提交
1320
            offset = end;
A
Alex Williamson 已提交
1321 1322 1323
            mingap = next - end;
        }
    }
A
Alex Williamson 已提交
1324 1325 1326 1327 1328 1329 1330

    if (offset == RAM_ADDR_MAX) {
        fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
                (uint64_t)size);
        abort();
    }

A
Alex Williamson 已提交
1331 1332 1333
    return offset;
}

J
Juan Quintela 已提交
1334
ram_addr_t last_ram_offset(void)
1335 1336 1337 1338
{
    RAMBlock *block;
    ram_addr_t last = 0;

M
Mike Day 已提交
1339 1340
    rcu_read_lock();
    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1341
        last = MAX(last, block->offset + block->max_length);
M
Mike Day 已提交
1342
    }
M
Mike Day 已提交
1343
    rcu_read_unlock();
1344 1345 1346
    return last;
}

1347 1348 1349 1350 1351
static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
{
    int ret;

    /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1352
    if (!machine_dump_guest_core(current_machine)) {
1353 1354 1355 1356 1357 1358 1359 1360 1361
        ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
        if (ret) {
            perror("qemu_madvise");
            fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
                            "but dump_guest_core=off specified\n");
        }
    }
}

M
Mike Day 已提交
1362 1363 1364
/* Called within an RCU critical section, or while the ramlist lock
 * is held.
 */
1365
static RAMBlock *find_ram_block(ram_addr_t addr)
1366
{
1367
    RAMBlock *block;
1368

M
Mike Day 已提交
1369
    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1370
        if (block->offset == addr) {
1371
            return block;
1372 1373
        }
    }
1374 1375 1376 1377

    return NULL;
}

1378
/* Called with iothread lock held.  */
1379 1380
void qemu_ram_set_idstr(ram_addr_t addr, const char *name, DeviceState *dev)
{
1381
    RAMBlock *new_block, *block;
1382

M
Mike Day 已提交
1383
    rcu_read_lock();
1384
    new_block = find_ram_block(addr);
1385 1386
    assert(new_block);
    assert(!new_block->idstr[0]);
1387

1388 1389
    if (dev) {
        char *id = qdev_get_dev_path(dev);
1390 1391
        if (id) {
            snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1392
            g_free(id);
1393 1394 1395 1396
        }
    }
    pstrcat(new_block->idstr, sizeof(new_block->idstr), name);

M
Mike Day 已提交
1397
    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1398
        if (block != new_block && !strcmp(block->idstr, new_block->idstr)) {
1399 1400 1401 1402 1403
            fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
                    new_block->idstr);
            abort();
        }
    }
M
Mike Day 已提交
1404
    rcu_read_unlock();
1405 1406
}

1407
/* Called with iothread lock held.  */
1408 1409
void qemu_ram_unset_idstr(ram_addr_t addr)
{
1410
    RAMBlock *block;
1411

1412 1413 1414 1415 1416
    /* FIXME: arch_init.c assumes that this is not called throughout
     * migration.  Ignore the problem since hot-unplug during migration
     * does not work anyway.
     */

M
Mike Day 已提交
1417
    rcu_read_lock();
1418
    block = find_ram_block(addr);
1419 1420 1421
    if (block) {
        memset(block->idstr, 0, sizeof(block->idstr));
    }
M
Mike Day 已提交
1422
    rcu_read_unlock();
1423 1424
}

1425 1426
static int memory_try_enable_merging(void *addr, size_t len)
{
1427
    if (!machine_mem_merge(current_machine)) {
1428 1429 1430 1431 1432 1433 1434
        /* disabled by the user */
        return 0;
    }

    return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
}

1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
/* Only legal before guest might have detected the memory size: e.g. on
 * incoming migration, or right after reset.
 *
 * As memory core doesn't know how is memory accessed, it is up to
 * resize callback to update device state and/or add assertions to detect
 * misuse, if necessary.
 */
int qemu_ram_resize(ram_addr_t base, ram_addr_t newsize, Error **errp)
{
    RAMBlock *block = find_ram_block(base);

    assert(block);

1448 1449
    newsize = TARGET_PAGE_ALIGN(newsize);

1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
    if (block->used_length == newsize) {
        return 0;
    }

    if (!(block->flags & RAM_RESIZEABLE)) {
        error_setg_errno(errp, EINVAL,
                         "Length mismatch: %s: 0x" RAM_ADDR_FMT
                         " in != 0x" RAM_ADDR_FMT, block->idstr,
                         newsize, block->used_length);
        return -EINVAL;
    }

    if (block->max_length < newsize) {
        error_setg_errno(errp, EINVAL,
                         "Length too large: %s: 0x" RAM_ADDR_FMT
                         " > 0x" RAM_ADDR_FMT, block->idstr,
                         newsize, block->max_length);
        return -EINVAL;
    }

    cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
    block->used_length = newsize;
1472 1473
    cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
                                        DIRTY_CLIENTS_ALL);
1474 1475 1476 1477 1478 1479 1480
    memory_region_set_size(block->mr, newsize);
    if (block->resized) {
        block->resized(block->idstr, newsize, block->host);
    }
    return 0;
}

1481
static ram_addr_t ram_block_add(RAMBlock *new_block, Error **errp)
1482
{
1483
    RAMBlock *block;
M
Mike Day 已提交
1484
    RAMBlock *last_block = NULL;
1485 1486 1487
    ram_addr_t old_ram_size, new_ram_size;

    old_ram_size = last_ram_offset() >> TARGET_PAGE_BITS;
1488

1489
    qemu_mutex_lock_ramlist();
1490
    new_block->offset = find_ram_offset(new_block->max_length);
1491 1492 1493

    if (!new_block->host) {
        if (xen_enabled()) {
1494 1495
            xen_ram_alloc(new_block->offset, new_block->max_length,
                          new_block->mr);
1496
        } else {
1497
            new_block->host = phys_mem_alloc(new_block->max_length,
1498
                                             &new_block->mr->align);
1499
            if (!new_block->host) {
1500 1501 1502 1503 1504
                error_setg_errno(errp, errno,
                                 "cannot set up guest memory '%s'",
                                 memory_region_name(new_block->mr));
                qemu_mutex_unlock_ramlist();
                return -1;
1505
            }
1506
            memory_try_enable_merging(new_block->host, new_block->max_length);
1507
        }
1508
    }
P
pbrook 已提交
1509

L
Li Zhijian 已提交
1510 1511 1512 1513 1514
    new_ram_size = MAX(old_ram_size,
              (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
    if (new_ram_size > old_ram_size) {
        migration_bitmap_extend(old_ram_size, new_ram_size);
    }
M
Mike Day 已提交
1515 1516 1517 1518
    /* Keep the list sorted from biggest to smallest block.  Unlike QTAILQ,
     * QLIST (which has an RCU-friendly variant) does not have insertion at
     * tail, so save the last element in last_block.
     */
M
Mike Day 已提交
1519
    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
M
Mike Day 已提交
1520
        last_block = block;
1521
        if (block->max_length < new_block->max_length) {
1522 1523 1524 1525
            break;
        }
    }
    if (block) {
M
Mike Day 已提交
1526
        QLIST_INSERT_BEFORE_RCU(block, new_block, next);
M
Mike Day 已提交
1527
    } else if (last_block) {
M
Mike Day 已提交
1528
        QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
M
Mike Day 已提交
1529
    } else { /* list is empty */
M
Mike Day 已提交
1530
        QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1531
    }
1532
    ram_list.mru_block = NULL;
P
pbrook 已提交
1533

M
Mike Day 已提交
1534 1535
    /* Write list before version */
    smp_wmb();
U
Umesh Deshpande 已提交
1536
    ram_list.version++;
1537
    qemu_mutex_unlock_ramlist();
U
Umesh Deshpande 已提交
1538

1539 1540 1541
    new_ram_size = last_ram_offset() >> TARGET_PAGE_BITS;

    if (new_ram_size > old_ram_size) {
1542
        int i;
1543 1544

        /* ram_list.dirty_memory[] is protected by the iothread lock.  */
1545 1546 1547 1548 1549
        for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
            ram_list.dirty_memory[i] =
                bitmap_zero_extend(ram_list.dirty_memory[i],
                                   old_ram_size, new_ram_size);
       }
1550
    }
1551
    cpu_physical_memory_set_dirty_range(new_block->offset,
1552 1553
                                        new_block->used_length,
                                        DIRTY_CLIENTS_ALL);
P
pbrook 已提交
1554

1555 1556 1557 1558 1559 1560 1561
    if (new_block->host) {
        qemu_ram_setup_dump(new_block->host, new_block->max_length);
        qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
        qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
        if (kvm_enabled()) {
            kvm_setup_guest_memory(new_block->host, new_block->max_length);
        }
1562
    }
1563

P
pbrook 已提交
1564 1565
    return new_block->offset;
}
B
bellard 已提交
1566

1567
#ifdef __linux__
1568
ram_addr_t qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
1569
                                    bool share, const char *mem_path,
1570
                                    Error **errp)
1571 1572
{
    RAMBlock *new_block;
1573 1574
    ram_addr_t addr;
    Error *local_err = NULL;
1575 1576

    if (xen_enabled()) {
1577 1578
        error_setg(errp, "-mem-path not supported with Xen");
        return -1;
1579 1580 1581 1582 1583 1584 1585 1586
    }

    if (phys_mem_alloc != qemu_anon_ram_alloc) {
        /*
         * file_ram_alloc() needs to allocate just like
         * phys_mem_alloc, but we haven't bothered to provide
         * a hook there.
         */
1587 1588 1589
        error_setg(errp,
                   "-mem-path not supported with this accelerator");
        return -1;
1590 1591 1592 1593 1594
    }

    size = TARGET_PAGE_ALIGN(size);
    new_block = g_malloc0(sizeof(*new_block));
    new_block->mr = mr;
1595 1596
    new_block->used_length = size;
    new_block->max_length = size;
1597
    new_block->flags = share ? RAM_SHARED : 0;
1598
    new_block->flags |= RAM_FILE;
1599 1600 1601 1602 1603 1604 1605
    new_block->host = file_ram_alloc(new_block, size,
                                     mem_path, errp);
    if (!new_block->host) {
        g_free(new_block);
        return -1;
    }

1606 1607 1608 1609 1610 1611 1612
    addr = ram_block_add(new_block, &local_err);
    if (local_err) {
        g_free(new_block);
        error_propagate(errp, local_err);
        return -1;
    }
    return addr;
1613
}
1614
#endif
1615

1616 1617 1618 1619 1620 1621
static
ram_addr_t qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
                                   void (*resized)(const char*,
                                                   uint64_t length,
                                                   void *host),
                                   void *host, bool resizeable,
1622
                                   MemoryRegion *mr, Error **errp)
1623 1624
{
    RAMBlock *new_block;
1625 1626
    ram_addr_t addr;
    Error *local_err = NULL;
1627 1628

    size = TARGET_PAGE_ALIGN(size);
1629
    max_size = TARGET_PAGE_ALIGN(max_size);
1630 1631
    new_block = g_malloc0(sizeof(*new_block));
    new_block->mr = mr;
1632
    new_block->resized = resized;
1633 1634
    new_block->used_length = size;
    new_block->max_length = max_size;
1635
    assert(max_size >= size);
1636 1637 1638
    new_block->fd = -1;
    new_block->host = host;
    if (host) {
1639
        new_block->flags |= RAM_PREALLOC;
1640
    }
1641 1642 1643
    if (resizeable) {
        new_block->flags |= RAM_RESIZEABLE;
    }
1644 1645 1646 1647 1648 1649 1650
    addr = ram_block_add(new_block, &local_err);
    if (local_err) {
        g_free(new_block);
        error_propagate(errp, local_err);
        return -1;
    }
    return addr;
1651 1652
}

1653 1654 1655 1656 1657 1658
ram_addr_t qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
                                   MemoryRegion *mr, Error **errp)
{
    return qemu_ram_alloc_internal(size, size, NULL, host, false, mr, errp);
}

1659
ram_addr_t qemu_ram_alloc(ram_addr_t size, MemoryRegion *mr, Error **errp)
1660
{
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
    return qemu_ram_alloc_internal(size, size, NULL, NULL, false, mr, errp);
}

ram_addr_t qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
                                     void (*resized)(const char*,
                                                     uint64_t length,
                                                     void *host),
                                     MemoryRegion *mr, Error **errp)
{
    return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true, mr, errp);
1671 1672
}

1673 1674 1675 1676
void qemu_ram_free_from_ptr(ram_addr_t addr)
{
    RAMBlock *block;

1677
    qemu_mutex_lock_ramlist();
M
Mike Day 已提交
1678
    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1679
        if (addr == block->offset) {
M
Mike Day 已提交
1680
            QLIST_REMOVE_RCU(block, next);
1681
            ram_list.mru_block = NULL;
M
Mike Day 已提交
1682 1683
            /* Write list before version */
            smp_wmb();
U
Umesh Deshpande 已提交
1684
            ram_list.version++;
P
Paolo Bonzini 已提交
1685
            g_free_rcu(block, rcu);
1686
            break;
1687 1688
        }
    }
1689
    qemu_mutex_unlock_ramlist();
1690 1691
}

P
Paolo Bonzini 已提交
1692 1693 1694 1695 1696 1697 1698 1699
static void reclaim_ramblock(RAMBlock *block)
{
    if (block->flags & RAM_PREALLOC) {
        ;
    } else if (xen_enabled()) {
        xen_invalidate_map_cache_entry(block->host);
#ifndef _WIN32
    } else if (block->fd >= 0) {
1700 1701
        if (block->flags & RAM_FILE) {
            qemu_ram_munmap(block->host, block->max_length);
1702 1703 1704
        } else {
            munmap(block->host, block->max_length);
        }
P
Paolo Bonzini 已提交
1705 1706 1707 1708 1709 1710 1711 1712
        close(block->fd);
#endif
    } else {
        qemu_anon_ram_free(block->host, block->max_length);
    }
    g_free(block);
}

A
Anthony Liguori 已提交
1713
void qemu_ram_free(ram_addr_t addr)
B
bellard 已提交
1714
{
A
Alex Williamson 已提交
1715 1716
    RAMBlock *block;

1717
    qemu_mutex_lock_ramlist();
M
Mike Day 已提交
1718
    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
A
Alex Williamson 已提交
1719
        if (addr == block->offset) {
M
Mike Day 已提交
1720
            QLIST_REMOVE_RCU(block, next);
1721
            ram_list.mru_block = NULL;
M
Mike Day 已提交
1722 1723
            /* Write list before version */
            smp_wmb();
U
Umesh Deshpande 已提交
1724
            ram_list.version++;
P
Paolo Bonzini 已提交
1725
            call_rcu(block, reclaim_ramblock, rcu);
1726
            break;
A
Alex Williamson 已提交
1727 1728
        }
    }
1729
    qemu_mutex_unlock_ramlist();
B
bellard 已提交
1730 1731
}

H
Huang Ying 已提交
1732 1733 1734 1735 1736 1737 1738 1739
#ifndef _WIN32
void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
{
    RAMBlock *block;
    ram_addr_t offset;
    int flags;
    void *area, *vaddr;

M
Mike Day 已提交
1740
    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
H
Huang Ying 已提交
1741
        offset = addr - block->offset;
1742
        if (offset < block->max_length) {
1743
            vaddr = ramblock_ptr(block, offset);
1744
            if (block->flags & RAM_PREALLOC) {
H
Huang Ying 已提交
1745
                ;
1746 1747
            } else if (xen_enabled()) {
                abort();
H
Huang Ying 已提交
1748 1749
            } else {
                flags = MAP_FIXED;
1750
                if (block->fd >= 0) {
1751 1752
                    flags |= (block->flags & RAM_SHARED ?
                              MAP_SHARED : MAP_PRIVATE);
1753 1754
                    area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
                                flags, block->fd, offset);
H
Huang Ying 已提交
1755
                } else {
1756 1757 1758 1759 1760 1761 1762
                    /*
                     * Remap needs to match alloc.  Accelerators that
                     * set phys_mem_alloc never remap.  If they did,
                     * we'd need a remap hook here.
                     */
                    assert(phys_mem_alloc == qemu_anon_ram_alloc);

H
Huang Ying 已提交
1763 1764 1765 1766 1767
                    flags |= MAP_PRIVATE | MAP_ANONYMOUS;
                    area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
                                flags, -1, 0);
                }
                if (area != vaddr) {
1768 1769
                    fprintf(stderr, "Could not remap addr: "
                            RAM_ADDR_FMT "@" RAM_ADDR_FMT "\n",
H
Huang Ying 已提交
1770 1771 1772
                            length, addr);
                    exit(1);
                }
1773
                memory_try_enable_merging(vaddr, length);
1774
                qemu_ram_setup_dump(vaddr, length);
H
Huang Ying 已提交
1775 1776 1777 1778 1779 1780
            }
        }
    }
}
#endif /* !_WIN32 */

1781 1782
int qemu_get_ram_fd(ram_addr_t addr)
{
1783 1784
    RAMBlock *block;
    int fd;
1785

M
Mike Day 已提交
1786
    rcu_read_lock();
1787 1788
    block = qemu_get_ram_block(addr);
    fd = block->fd;
M
Mike Day 已提交
1789
    rcu_read_unlock();
1790
    return fd;
1791 1792
}

1793 1794
void *qemu_get_ram_block_host_ptr(ram_addr_t addr)
{
1795 1796
    RAMBlock *block;
    void *ptr;
1797

M
Mike Day 已提交
1798
    rcu_read_lock();
1799 1800
    block = qemu_get_ram_block(addr);
    ptr = ramblock_ptr(block, 0);
M
Mike Day 已提交
1801
    rcu_read_unlock();
1802
    return ptr;
1803 1804
}

1805
/* Return a host pointer to ram allocated with qemu_ram_alloc.
1806 1807 1808
 * This should not be used for general purpose DMA.  Use address_space_map
 * or address_space_rw instead. For local memory (e.g. video ram) that the
 * device owns, use memory_region_get_ram_ptr.
M
Mike Day 已提交
1809 1810 1811 1812 1813 1814
 *
 * By the time this function returns, the returned pointer is not protected
 * by RCU anymore.  If the caller is not within an RCU critical section and
 * does not hold the iothread lock, it must have other means of protecting the
 * pointer, such as a reference to the region that includes the incoming
 * ram_addr_t.
1815 1816 1817
 */
void *qemu_get_ram_ptr(ram_addr_t addr)
{
1818 1819
    RAMBlock *block;
    void *ptr;
1820

M
Mike Day 已提交
1821
    rcu_read_lock();
1822 1823 1824
    block = qemu_get_ram_block(addr);

    if (xen_enabled() && block->host == NULL) {
1825 1826 1827 1828 1829
        /* We need to check if the requested address is in the RAM
         * because we don't want to map the entire memory in QEMU.
         * In that case just map until the end of the page.
         */
        if (block->offset == 0) {
1830
            ptr = xen_map_cache(addr, 0, 0);
M
Mike Day 已提交
1831
            goto unlock;
1832
        }
1833 1834

        block->host = xen_map_cache(block->offset, block->max_length, 1);
1835
    }
1836 1837
    ptr = ramblock_ptr(block, addr - block->offset);

M
Mike Day 已提交
1838 1839
unlock:
    rcu_read_unlock();
1840
    return ptr;
1841 1842
}

1843
/* Return a host pointer to guest's ram. Similar to qemu_get_ram_ptr
1844
 * but takes a size argument.
M
Mike Day 已提交
1845 1846 1847 1848 1849 1850
 *
 * By the time this function returns, the returned pointer is not protected
 * by RCU anymore.  If the caller is not within an RCU critical section and
 * does not hold the iothread lock, it must have other means of protecting the
 * pointer, such as a reference to the region that includes the incoming
 * ram_addr_t.
1851
 */
1852
static void *qemu_ram_ptr_length(ram_addr_t addr, hwaddr *size)
1853
{
1854
    void *ptr;
1855 1856 1857
    if (*size == 0) {
        return NULL;
    }
1858
    if (xen_enabled()) {
J
Jan Kiszka 已提交
1859
        return xen_map_cache(addr, *size, 1);
1860
    } else {
1861
        RAMBlock *block;
M
Mike Day 已提交
1862 1863
        rcu_read_lock();
        QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1864 1865 1866
            if (addr - block->offset < block->max_length) {
                if (addr - block->offset + *size > block->max_length)
                    *size = block->max_length - addr + block->offset;
1867
                ptr = ramblock_ptr(block, addr - block->offset);
M
Mike Day 已提交
1868
                rcu_read_unlock();
1869
                return ptr;
1870 1871 1872 1873 1874 1875 1876 1877
            }
        }

        fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
        abort();
    }
}

1878
/* Some of the softmmu routines need to translate from a host pointer
1879 1880 1881 1882 1883 1884 1885 1886
 * (typically a TLB entry) back to a ram offset.
 *
 * By the time this function returns, the returned pointer is not protected
 * by RCU anymore.  If the caller is not within an RCU critical section and
 * does not hold the iothread lock, it must have other means of protecting the
 * pointer, such as a reference to the region that includes the incoming
 * ram_addr_t.
 */
1887
MemoryRegion *qemu_ram_addr_from_host(void *ptr, ram_addr_t *ram_addr)
P
pbrook 已提交
1888
{
P
pbrook 已提交
1889 1890
    RAMBlock *block;
    uint8_t *host = ptr;
1891
    MemoryRegion *mr;
P
pbrook 已提交
1892

1893
    if (xen_enabled()) {
M
Mike Day 已提交
1894
        rcu_read_lock();
J
Jan Kiszka 已提交
1895
        *ram_addr = xen_ram_addr_from_mapcache(ptr);
1896
        mr = qemu_get_ram_block(*ram_addr)->mr;
M
Mike Day 已提交
1897
        rcu_read_unlock();
1898
        return mr;
1899 1900
    }

M
Mike Day 已提交
1901 1902
    rcu_read_lock();
    block = atomic_rcu_read(&ram_list.mru_block);
1903
    if (block && block->host && host - block->host < block->max_length) {
1904 1905 1906
        goto found;
    }

M
Mike Day 已提交
1907
    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
J
Jun Nakajima 已提交
1908 1909 1910 1911
        /* This case append when the block is not mapped. */
        if (block->host == NULL) {
            continue;
        }
1912
        if (host - block->host < block->max_length) {
1913
            goto found;
A
Alex Williamson 已提交
1914
        }
P
pbrook 已提交
1915
    }
J
Jun Nakajima 已提交
1916

M
Mike Day 已提交
1917
    rcu_read_unlock();
1918
    return NULL;
1919 1920 1921

found:
    *ram_addr = block->offset + (host - block->host);
1922
    mr = block->mr;
M
Mike Day 已提交
1923
    rcu_read_unlock();
1924
    return mr;
M
Marcelo Tosatti 已提交
1925
}
A
Alex Williamson 已提交
1926

A
Avi Kivity 已提交
1927
static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
1928
                               uint64_t val, unsigned size)
1929
{
1930
    if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
1931
        tb_invalidate_phys_page_fast(ram_addr, size);
1932
    }
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
    switch (size) {
    case 1:
        stb_p(qemu_get_ram_ptr(ram_addr), val);
        break;
    case 2:
        stw_p(qemu_get_ram_ptr(ram_addr), val);
        break;
    case 4:
        stl_p(qemu_get_ram_ptr(ram_addr), val);
        break;
    default:
        abort();
1945
    }
1946 1947 1948 1949 1950
    /* Set both VGA and migration bits for simplicity and to remove
     * the notdirty callback faster.
     */
    cpu_physical_memory_set_dirty_range(ram_addr, size,
                                        DIRTY_CLIENTS_NOCODE);
B
bellard 已提交
1951 1952
    /* we remove the notdirty callback only if the code has been
       flushed */
1953
    if (!cpu_physical_memory_is_clean(ram_addr)) {
1954
        tlb_set_dirty(current_cpu, current_cpu->mem_io_vaddr);
1955
    }
1956 1957
}

1958 1959 1960 1961 1962 1963
static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
                                 unsigned size, bool is_write)
{
    return is_write;
}

1964 1965
static const MemoryRegionOps notdirty_mem_ops = {
    .write = notdirty_mem_write,
1966
    .valid.accepts = notdirty_mem_accepts,
1967
    .endianness = DEVICE_NATIVE_ENDIAN,
1968 1969
};

P
pbrook 已提交
1970
/* Generate a debug exception if a watchpoint has been hit.  */
1971
static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
P
pbrook 已提交
1972
{
1973 1974
    CPUState *cpu = current_cpu;
    CPUArchState *env = cpu->env_ptr;
1975
    target_ulong pc, cs_base;
P
pbrook 已提交
1976
    target_ulong vaddr;
1977
    CPUWatchpoint *wp;
1978
    int cpu_flags;
P
pbrook 已提交
1979

1980
    if (cpu->watchpoint_hit) {
1981 1982 1983
        /* We re-entered the check after replacing the TB. Now raise
         * the debug interrupt so that is will trigger after the
         * current instruction. */
1984
        cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
1985 1986
        return;
    }
1987
    vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
1988
    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1989 1990
        if (cpu_watchpoint_address_matches(wp, vaddr, len)
            && (wp->flags & flags)) {
1991 1992 1993 1994 1995 1996
            if (flags == BP_MEM_READ) {
                wp->flags |= BP_WATCHPOINT_HIT_READ;
            } else {
                wp->flags |= BP_WATCHPOINT_HIT_WRITE;
            }
            wp->hitaddr = vaddr;
1997
            wp->hitattrs = attrs;
1998 1999
            if (!cpu->watchpoint_hit) {
                cpu->watchpoint_hit = wp;
2000
                tb_check_watchpoint(cpu);
2001
                if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2002
                    cpu->exception_index = EXCP_DEBUG;
2003
                    cpu_loop_exit(cpu);
2004 2005
                } else {
                    cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags);
2006
                    tb_gen_code(cpu, pc, cs_base, cpu_flags, 1);
2007
                    cpu_resume_from_signal(cpu, NULL);
2008
                }
2009
            }
2010 2011
        } else {
            wp->flags &= ~BP_WATCHPOINT_HIT;
P
pbrook 已提交
2012 2013 2014 2015
        }
    }
}

2016 2017 2018
/* Watchpoint access routines.  Watchpoints are inserted using TLB tricks,
   so these check for a hit then pass through to the normal out-of-line
   phys routines.  */
2019 2020
static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
                                  unsigned size, MemTxAttrs attrs)
2021
{
2022 2023 2024 2025
    MemTxResult res;
    uint64_t data;

    check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2026
    switch (size) {
2027 2028 2029 2030 2031 2032 2033 2034 2035
    case 1:
        data = address_space_ldub(&address_space_memory, addr, attrs, &res);
        break;
    case 2:
        data = address_space_lduw(&address_space_memory, addr, attrs, &res);
        break;
    case 4:
        data = address_space_ldl(&address_space_memory, addr, attrs, &res);
        break;
2036 2037
    default: abort();
    }
2038 2039
    *pdata = data;
    return res;
2040 2041
}

2042 2043 2044
static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
                                   uint64_t val, unsigned size,
                                   MemTxAttrs attrs)
2045
{
2046 2047 2048
    MemTxResult res;

    check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2049
    switch (size) {
2050
    case 1:
2051
        address_space_stb(&address_space_memory, addr, val, attrs, &res);
2052 2053
        break;
    case 2:
2054
        address_space_stw(&address_space_memory, addr, val, attrs, &res);
2055 2056
        break;
    case 4:
2057
        address_space_stl(&address_space_memory, addr, val, attrs, &res);
2058
        break;
2059 2060
    default: abort();
    }
2061
    return res;
2062 2063
}

2064
static const MemoryRegionOps watch_mem_ops = {
2065 2066
    .read_with_attrs = watch_mem_read,
    .write_with_attrs = watch_mem_write,
2067
    .endianness = DEVICE_NATIVE_ENDIAN,
2068 2069
};

2070 2071
static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
                                unsigned len, MemTxAttrs attrs)
2072
{
2073
    subpage_t *subpage = opaque;
2074
    uint8_t buf[8];
2075
    MemTxResult res;
2076

2077
#if defined(DEBUG_SUBPAGE)
A
Amos Kong 已提交
2078
    printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2079
           subpage, len, addr);
2080
#endif
2081 2082 2083 2084
    res = address_space_read(subpage->as, addr + subpage->base,
                             attrs, buf, len);
    if (res) {
        return res;
2085
    }
2086 2087
    switch (len) {
    case 1:
2088 2089
        *data = ldub_p(buf);
        return MEMTX_OK;
2090
    case 2:
2091 2092
        *data = lduw_p(buf);
        return MEMTX_OK;
2093
    case 4:
2094 2095
        *data = ldl_p(buf);
        return MEMTX_OK;
2096
    case 8:
2097 2098
        *data = ldq_p(buf);
        return MEMTX_OK;
2099 2100 2101
    default:
        abort();
    }
2102 2103
}

2104 2105
static MemTxResult subpage_write(void *opaque, hwaddr addr,
                                 uint64_t value, unsigned len, MemTxAttrs attrs)
2106
{
2107
    subpage_t *subpage = opaque;
2108
    uint8_t buf[8];
2109

2110
#if defined(DEBUG_SUBPAGE)
A
Amos Kong 已提交
2111
    printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2112 2113
           " value %"PRIx64"\n",
           __func__, subpage, len, addr, value);
2114
#endif
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
    switch (len) {
    case 1:
        stb_p(buf, value);
        break;
    case 2:
        stw_p(buf, value);
        break;
    case 4:
        stl_p(buf, value);
        break;
2125 2126 2127
    case 8:
        stq_p(buf, value);
        break;
2128 2129 2130
    default:
        abort();
    }
2131 2132
    return address_space_write(subpage->as, addr + subpage->base,
                               attrs, buf, len);
2133 2134
}

2135
static bool subpage_accepts(void *opaque, hwaddr addr,
A
Amos Kong 已提交
2136
                            unsigned len, bool is_write)
2137
{
2138
    subpage_t *subpage = opaque;
2139
#if defined(DEBUG_SUBPAGE)
A
Amos Kong 已提交
2140
    printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2141
           __func__, subpage, is_write ? 'w' : 'r', len, addr);
2142 2143
#endif

2144
    return address_space_access_valid(subpage->as, addr + subpage->base,
A
Amos Kong 已提交
2145
                                      len, is_write);
2146 2147
}

2148
static const MemoryRegionOps subpage_ops = {
2149 2150
    .read_with_attrs = subpage_read,
    .write_with_attrs = subpage_write,
2151 2152 2153 2154
    .impl.min_access_size = 1,
    .impl.max_access_size = 8,
    .valid.min_access_size = 1,
    .valid.max_access_size = 8,
2155
    .valid.accepts = subpage_accepts,
2156
    .endianness = DEVICE_NATIVE_ENDIAN,
2157 2158
};

A
Anthony Liguori 已提交
2159
static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
2160
                             uint16_t section)
2161 2162 2163 2164 2165 2166 2167 2168
{
    int idx, eidx;

    if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
        return -1;
    idx = SUBPAGE_IDX(start);
    eidx = SUBPAGE_IDX(end);
#if defined(DEBUG_SUBPAGE)
A
Amos Kong 已提交
2169 2170
    printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
           __func__, mmio, start, end, idx, eidx, section);
2171 2172
#endif
    for (; idx <= eidx; idx++) {
2173
        mmio->sub_section[idx] = section;
2174 2175 2176 2177 2178
    }

    return 0;
}

2179
static subpage_t *subpage_init(AddressSpace *as, hwaddr base)
2180
{
A
Anthony Liguori 已提交
2181
    subpage_t *mmio;
2182

2183
    mmio = g_malloc0(sizeof(subpage_t));
2184

2185
    mmio->as = as;
2186
    mmio->base = base;
2187
    memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
P
Peter Crosthwaite 已提交
2188
                          NULL, TARGET_PAGE_SIZE);
A
Avi Kivity 已提交
2189
    mmio->iomem.subpage = true;
2190
#if defined(DEBUG_SUBPAGE)
A
Amos Kong 已提交
2191 2192
    printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
           mmio, base, TARGET_PAGE_SIZE);
2193
#endif
2194
    subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
2195 2196 2197 2198

    return mmio;
}

2199 2200
static uint16_t dummy_section(PhysPageMap *map, AddressSpace *as,
                              MemoryRegion *mr)
2201
{
2202
    assert(as);
2203
    MemoryRegionSection section = {
2204
        .address_space = as,
2205 2206 2207
        .mr = mr,
        .offset_within_address_space = 0,
        .offset_within_region = 0,
2208
        .size = int128_2_64(),
2209 2210
    };

2211
    return phys_section_add(map, &section);
2212 2213
}

P
Paolo Bonzini 已提交
2214
MemoryRegion *iotlb_to_region(CPUState *cpu, hwaddr index)
2215
{
2216 2217
    CPUAddressSpace *cpuas = &cpu->cpu_ases[0];
    AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
2218
    MemoryRegionSection *sections = d->map.sections;
P
Paolo Bonzini 已提交
2219 2220

    return sections[index & ~TARGET_PAGE_MASK].mr;
2221 2222
}

A
Avi Kivity 已提交
2223 2224
static void io_mem_init(void)
{
2225
    memory_region_init_io(&io_mem_rom, NULL, &unassigned_mem_ops, NULL, NULL, UINT64_MAX);
2226
    memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2227
                          NULL, UINT64_MAX);
2228
    memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
2229
                          NULL, UINT64_MAX);
2230
    memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
2231
                          NULL, UINT64_MAX);
A
Avi Kivity 已提交
2232 2233
}

A
Avi Kivity 已提交
2234
static void mem_begin(MemoryListener *listener)
2235 2236
{
    AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
2237 2238 2239
    AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
    uint16_t n;

2240
    n = dummy_section(&d->map, as, &io_mem_unassigned);
2241
    assert(n == PHYS_SECTION_UNASSIGNED);
2242
    n = dummy_section(&d->map, as, &io_mem_notdirty);
2243
    assert(n == PHYS_SECTION_NOTDIRTY);
2244
    n = dummy_section(&d->map, as, &io_mem_rom);
2245
    assert(n == PHYS_SECTION_ROM);
2246
    n = dummy_section(&d->map, as, &io_mem_watch);
2247
    assert(n == PHYS_SECTION_WATCH);
2248

M
Michael S. Tsirkin 已提交
2249
    d->phys_map  = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2250 2251 2252 2253
    d->as = as;
    as->next_dispatch = d;
}

2254 2255 2256 2257 2258 2259
static void address_space_dispatch_free(AddressSpaceDispatch *d)
{
    phys_sections_free(&d->map);
    g_free(d);
}

2260
static void mem_commit(MemoryListener *listener)
A
Avi Kivity 已提交
2261
{
2262
    AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
2263 2264 2265
    AddressSpaceDispatch *cur = as->dispatch;
    AddressSpaceDispatch *next = as->next_dispatch;

2266
    phys_page_compact_all(next, next->map.nodes_nb);
2267

2268
    atomic_rcu_set(&as->dispatch, next);
2269
    if (cur) {
2270
        call_rcu(cur, address_space_dispatch_free, rcu);
2271
    }
2272 2273
}

2274
static void tcg_commit(MemoryListener *listener)
2275
{
2276 2277
    CPUAddressSpace *cpuas;
    AddressSpaceDispatch *d;
2278 2279 2280

    /* since each CPU stores ram addresses in its TLB cache, we must
       reset the modified entries */
2281 2282 2283 2284 2285 2286 2287 2288 2289
    cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
    cpu_reloading_memory_map();
    /* The CPU and TLB are protected by the iothread lock.
     * We reload the dispatch pointer now because cpu_reloading_memory_map()
     * may have split the RCU critical section.
     */
    d = atomic_rcu_read(&cpuas->as->dispatch);
    cpuas->memory_dispatch = d;
    tlb_flush(cpuas->cpu, 1);
2290 2291
}

A
Avi Kivity 已提交
2292 2293
void address_space_init_dispatch(AddressSpace *as)
{
2294
    as->dispatch = NULL;
2295
    as->dispatch_listener = (MemoryListener) {
A
Avi Kivity 已提交
2296
        .begin = mem_begin,
2297
        .commit = mem_commit,
A
Avi Kivity 已提交
2298 2299 2300 2301
        .region_add = mem_add,
        .region_nop = mem_add,
        .priority = 0,
    };
2302
    memory_listener_register(&as->dispatch_listener, as);
A
Avi Kivity 已提交
2303 2304
}

2305 2306 2307 2308 2309
void address_space_unregister(AddressSpace *as)
{
    memory_listener_unregister(&as->dispatch_listener);
}

A
Avi Kivity 已提交
2310 2311 2312 2313
void address_space_destroy_dispatch(AddressSpace *as)
{
    AddressSpaceDispatch *d = as->dispatch;

2314 2315 2316 2317
    atomic_rcu_set(&as->dispatch, NULL);
    if (d) {
        call_rcu(d, address_space_dispatch_free, rcu);
    }
A
Avi Kivity 已提交
2318 2319
}

A
Avi Kivity 已提交
2320 2321
static void memory_map_init(void)
{
2322
    system_memory = g_malloc(sizeof(*system_memory));
2323

2324
    memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2325
    address_space_init(&address_space_memory, system_memory, "memory");
2326

2327
    system_io = g_malloc(sizeof(*system_io));
2328 2329
    memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
                          65536);
2330
    address_space_init(&address_space_io, system_io, "I/O");
A
Avi Kivity 已提交
2331 2332 2333 2334 2335 2336 2337
}

MemoryRegion *get_system_memory(void)
{
    return system_memory;
}

2338 2339 2340 2341 2342
MemoryRegion *get_system_io(void)
{
    return system_io;
}

2343 2344
#endif /* !defined(CONFIG_USER_ONLY) */

B
bellard 已提交
2345 2346
/* physical memory access (slow version, mainly for debug) */
#if defined(CONFIG_USER_ONLY)
2347
int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
P
Paul Brook 已提交
2348
                        uint8_t *buf, int len, int is_write)
B
bellard 已提交
2349 2350 2351
{
    int l, flags;
    target_ulong page;
2352
    void * p;
B
bellard 已提交
2353 2354 2355 2356 2357 2358 2359 2360

    while (len > 0) {
        page = addr & TARGET_PAGE_MASK;
        l = (page + TARGET_PAGE_SIZE) - addr;
        if (l > len)
            l = len;
        flags = page_get_flags(page);
        if (!(flags & PAGE_VALID))
P
Paul Brook 已提交
2361
            return -1;
B
bellard 已提交
2362 2363
        if (is_write) {
            if (!(flags & PAGE_WRITE))
P
Paul Brook 已提交
2364
                return -1;
2365
            /* XXX: this code should not depend on lock_user */
A
aurel32 已提交
2366
            if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
P
Paul Brook 已提交
2367
                return -1;
A
aurel32 已提交
2368 2369
            memcpy(p, buf, l);
            unlock_user(p, addr, l);
B
bellard 已提交
2370 2371
        } else {
            if (!(flags & PAGE_READ))
P
Paul Brook 已提交
2372
                return -1;
2373
            /* XXX: this code should not depend on lock_user */
A
aurel32 已提交
2374
            if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
P
Paul Brook 已提交
2375
                return -1;
A
aurel32 已提交
2376
            memcpy(buf, p, l);
A
aurel32 已提交
2377
            unlock_user(p, addr, 0);
B
bellard 已提交
2378 2379 2380 2381 2382
        }
        len -= l;
        buf += l;
        addr += l;
    }
P
Paul Brook 已提交
2383
    return 0;
B
bellard 已提交
2384
}
B
bellard 已提交
2385

B
bellard 已提交
2386
#else
2387

2388
static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
A
Avi Kivity 已提交
2389
                                     hwaddr length)
2390
{
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
    uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
    /* No early return if dirty_log_mask is or becomes 0, because
     * cpu_physical_memory_set_dirty_range will still call
     * xen_modified_memory.
     */
    if (dirty_log_mask) {
        dirty_log_mask =
            cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
    }
    if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
        tb_invalidate_phys_range(addr, addr + length);
        dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2403
    }
2404
    cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2405 2406
}

2407
static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2408
{
2409
    unsigned access_size_max = mr->ops->valid.max_access_size;
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422

    /* Regions are assumed to support 1-4 byte accesses unless
       otherwise specified.  */
    if (access_size_max == 0) {
        access_size_max = 4;
    }

    /* Bound the maximum access by the alignment of the address.  */
    if (!mr->ops->impl.unaligned) {
        unsigned align_size_max = addr & -addr;
        if (align_size_max != 0 && align_size_max < access_size_max) {
            access_size_max = align_size_max;
        }
2423
    }
2424 2425 2426 2427

    /* Don't attempt accesses larger than the maximum.  */
    if (l > access_size_max) {
        l = access_size_max;
2428
    }
2429
    l = pow2floor(l);
2430 2431

    return l;
2432 2433
}

2434
static bool prepare_mmio_access(MemoryRegion *mr)
2435
{
2436 2437 2438 2439 2440 2441 2442 2443
    bool unlocked = !qemu_mutex_iothread_locked();
    bool release_lock = false;

    if (unlocked && mr->global_locking) {
        qemu_mutex_lock_iothread();
        unlocked = false;
        release_lock = true;
    }
2444
    if (mr->flush_coalesced_mmio) {
2445 2446 2447
        if (unlocked) {
            qemu_mutex_lock_iothread();
        }
2448
        qemu_flush_coalesced_mmio_buffer();
2449 2450 2451
        if (unlocked) {
            qemu_mutex_unlock_iothread();
        }
2452
    }
2453 2454

    return release_lock;
2455 2456
}

2457 2458
MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
                             uint8_t *buf, int len, bool is_write)
B
bellard 已提交
2459
{
2460
    hwaddr l;
B
bellard 已提交
2461
    uint8_t *ptr;
2462
    uint64_t val;
2463
    hwaddr addr1;
2464
    MemoryRegion *mr;
2465
    MemTxResult result = MEMTX_OK;
2466
    bool release_lock = false;
2467

2468
    rcu_read_lock();
B
bellard 已提交
2469
    while (len > 0) {
2470
        l = len;
2471
        mr = address_space_translate(as, addr, &addr1, &l, is_write);
2472

B
bellard 已提交
2473
        if (is_write) {
2474
            if (!memory_access_is_direct(mr, is_write)) {
2475
                release_lock |= prepare_mmio_access(mr);
2476
                l = memory_access_size(mr, l, addr1);
2477
                /* XXX: could force current_cpu to NULL to avoid
B
bellard 已提交
2478
                   potential bugs */
2479 2480 2481 2482
                switch (l) {
                case 8:
                    /* 64 bit write access */
                    val = ldq_p(buf);
2483 2484
                    result |= memory_region_dispatch_write(mr, addr1, val, 8,
                                                           attrs);
2485 2486
                    break;
                case 4:
B
bellard 已提交
2487
                    /* 32 bit write access */
B
bellard 已提交
2488
                    val = ldl_p(buf);
2489 2490
                    result |= memory_region_dispatch_write(mr, addr1, val, 4,
                                                           attrs);
2491 2492
                    break;
                case 2:
B
bellard 已提交
2493
                    /* 16 bit write access */
B
bellard 已提交
2494
                    val = lduw_p(buf);
2495 2496
                    result |= memory_region_dispatch_write(mr, addr1, val, 2,
                                                           attrs);
2497 2498
                    break;
                case 1:
B
bellard 已提交
2499
                    /* 8 bit write access */
B
bellard 已提交
2500
                    val = ldub_p(buf);
2501 2502
                    result |= memory_region_dispatch_write(mr, addr1, val, 1,
                                                           attrs);
2503 2504 2505
                    break;
                default:
                    abort();
B
bellard 已提交
2506
                }
2507
            } else {
2508
                addr1 += memory_region_get_ram_addr(mr);
B
bellard 已提交
2509
                /* RAM case */
P
pbrook 已提交
2510
                ptr = qemu_get_ram_ptr(addr1);
B
bellard 已提交
2511
                memcpy(ptr, buf, l);
2512
                invalidate_and_set_dirty(mr, addr1, l);
B
bellard 已提交
2513 2514
            }
        } else {
2515
            if (!memory_access_is_direct(mr, is_write)) {
B
bellard 已提交
2516
                /* I/O case */
2517
                release_lock |= prepare_mmio_access(mr);
2518
                l = memory_access_size(mr, l, addr1);
2519 2520 2521
                switch (l) {
                case 8:
                    /* 64 bit read access */
2522 2523
                    result |= memory_region_dispatch_read(mr, addr1, &val, 8,
                                                          attrs);
2524 2525 2526
                    stq_p(buf, val);
                    break;
                case 4:
B
bellard 已提交
2527
                    /* 32 bit read access */
2528 2529
                    result |= memory_region_dispatch_read(mr, addr1, &val, 4,
                                                          attrs);
B
bellard 已提交
2530
                    stl_p(buf, val);
2531 2532
                    break;
                case 2:
B
bellard 已提交
2533
                    /* 16 bit read access */
2534 2535
                    result |= memory_region_dispatch_read(mr, addr1, &val, 2,
                                                          attrs);
B
bellard 已提交
2536
                    stw_p(buf, val);
2537 2538
                    break;
                case 1:
B
bellard 已提交
2539
                    /* 8 bit read access */
2540 2541
                    result |= memory_region_dispatch_read(mr, addr1, &val, 1,
                                                          attrs);
B
bellard 已提交
2542
                    stb_p(buf, val);
2543 2544 2545
                    break;
                default:
                    abort();
B
bellard 已提交
2546 2547 2548
                }
            } else {
                /* RAM case */
2549
                ptr = qemu_get_ram_ptr(mr->ram_addr + addr1);
2550
                memcpy(buf, ptr, l);
B
bellard 已提交
2551 2552
            }
        }
2553 2554 2555 2556 2557 2558

        if (release_lock) {
            qemu_mutex_unlock_iothread();
            release_lock = false;
        }

B
bellard 已提交
2559 2560 2561 2562
        len -= l;
        buf += l;
        addr += l;
    }
2563
    rcu_read_unlock();
2564

2565
    return result;
B
bellard 已提交
2566
}
B
bellard 已提交
2567

2568 2569
MemTxResult address_space_write(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
                                const uint8_t *buf, int len)
A
Avi Kivity 已提交
2570
{
2571
    return address_space_rw(as, addr, attrs, (uint8_t *)buf, len, true);
A
Avi Kivity 已提交
2572 2573
}

2574 2575
MemTxResult address_space_read(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
                               uint8_t *buf, int len)
A
Avi Kivity 已提交
2576
{
2577
    return address_space_rw(as, addr, attrs, buf, len, false);
A
Avi Kivity 已提交
2578 2579 2580
}


A
Avi Kivity 已提交
2581
void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
A
Avi Kivity 已提交
2582 2583
                            int len, int is_write)
{
2584 2585
    address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
                     buf, len, is_write);
A
Avi Kivity 已提交
2586 2587
}

2588 2589 2590 2591 2592
enum write_rom_type {
    WRITE_DATA,
    FLUSH_CACHE,
};

2593
static inline void cpu_physical_memory_write_rom_internal(AddressSpace *as,
2594
    hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
B
bellard 已提交
2595
{
2596
    hwaddr l;
B
bellard 已提交
2597
    uint8_t *ptr;
2598
    hwaddr addr1;
2599
    MemoryRegion *mr;
2600

2601
    rcu_read_lock();
B
bellard 已提交
2602
    while (len > 0) {
2603
        l = len;
2604
        mr = address_space_translate(as, addr, &addr1, &l, true);
2605

2606 2607
        if (!(memory_region_is_ram(mr) ||
              memory_region_is_romd(mr))) {
2608
            l = memory_access_size(mr, l, addr1);
B
bellard 已提交
2609
        } else {
2610
            addr1 += memory_region_get_ram_addr(mr);
B
bellard 已提交
2611
            /* ROM/RAM case */
P
pbrook 已提交
2612
            ptr = qemu_get_ram_ptr(addr1);
2613 2614 2615
            switch (type) {
            case WRITE_DATA:
                memcpy(ptr, buf, l);
2616
                invalidate_and_set_dirty(mr, addr1, l);
2617 2618 2619 2620 2621
                break;
            case FLUSH_CACHE:
                flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
                break;
            }
B
bellard 已提交
2622 2623 2624 2625 2626
        }
        len -= l;
        buf += l;
        addr += l;
    }
2627
    rcu_read_unlock();
B
bellard 已提交
2628 2629
}

2630
/* used for ROM loading : can write in RAM and ROM */
2631
void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
2632 2633
                                   const uint8_t *buf, int len)
{
2634
    cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648
}

void cpu_flush_icache_range(hwaddr start, int len)
{
    /*
     * This function should do the same thing as an icache flush that was
     * triggered from within the guest. For TCG we are always cache coherent,
     * so there is no need to flush anything. For KVM / Xen we need to flush
     * the host's instruction cache at least.
     */
    if (tcg_enabled()) {
        return;
    }

2649 2650
    cpu_physical_memory_write_rom_internal(&address_space_memory,
                                           start, NULL, len, FLUSH_CACHE);
2651 2652
}

2653
typedef struct {
2654
    MemoryRegion *mr;
2655
    void *buffer;
A
Avi Kivity 已提交
2656 2657
    hwaddr addr;
    hwaddr len;
F
Fam Zheng 已提交
2658
    bool in_use;
2659 2660 2661 2662
} BounceBuffer;

static BounceBuffer bounce;

2663
typedef struct MapClient {
2664
    QEMUBH *bh;
B
Blue Swirl 已提交
2665
    QLIST_ENTRY(MapClient) link;
2666 2667
} MapClient;

2668
QemuMutex map_client_list_lock;
B
Blue Swirl 已提交
2669 2670
static QLIST_HEAD(map_client_list, MapClient) map_client_list
    = QLIST_HEAD_INITIALIZER(map_client_list);
2671

2672 2673 2674 2675 2676 2677
static void cpu_unregister_map_client_do(MapClient *client)
{
    QLIST_REMOVE(client, link);
    g_free(client);
}

2678 2679 2680 2681 2682 2683
static void cpu_notify_map_clients_locked(void)
{
    MapClient *client;

    while (!QLIST_EMPTY(&map_client_list)) {
        client = QLIST_FIRST(&map_client_list);
2684 2685
        qemu_bh_schedule(client->bh);
        cpu_unregister_map_client_do(client);
2686 2687 2688
    }
}

2689
void cpu_register_map_client(QEMUBH *bh)
2690
{
2691
    MapClient *client = g_malloc(sizeof(*client));
2692

2693
    qemu_mutex_lock(&map_client_list_lock);
2694
    client->bh = bh;
B
Blue Swirl 已提交
2695
    QLIST_INSERT_HEAD(&map_client_list, client, link);
2696 2697 2698
    if (!atomic_read(&bounce.in_use)) {
        cpu_notify_map_clients_locked();
    }
2699
    qemu_mutex_unlock(&map_client_list_lock);
2700 2701
}

2702
void cpu_exec_init_all(void)
2703
{
2704 2705
    qemu_mutex_init(&ram_list.mutex);
    io_mem_init();
2706
    memory_map_init();
2707
    qemu_mutex_init(&map_client_list_lock);
2708 2709
}

2710
void cpu_unregister_map_client(QEMUBH *bh)
2711 2712 2713
{
    MapClient *client;

2714 2715 2716 2717 2718 2719
    qemu_mutex_lock(&map_client_list_lock);
    QLIST_FOREACH(client, &map_client_list, link) {
        if (client->bh == bh) {
            cpu_unregister_map_client_do(client);
            break;
        }
2720
    }
2721
    qemu_mutex_unlock(&map_client_list_lock);
2722 2723 2724 2725
}

static void cpu_notify_map_clients(void)
{
2726
    qemu_mutex_lock(&map_client_list_lock);
2727
    cpu_notify_map_clients_locked();
2728
    qemu_mutex_unlock(&map_client_list_lock);
2729 2730
}

2731 2732
bool address_space_access_valid(AddressSpace *as, hwaddr addr, int len, bool is_write)
{
2733
    MemoryRegion *mr;
2734 2735
    hwaddr l, xlat;

2736
    rcu_read_lock();
2737 2738
    while (len > 0) {
        l = len;
2739 2740 2741 2742
        mr = address_space_translate(as, addr, &xlat, &l, is_write);
        if (!memory_access_is_direct(mr, is_write)) {
            l = memory_access_size(mr, l, addr);
            if (!memory_region_access_valid(mr, xlat, l, is_write)) {
2743 2744 2745 2746 2747 2748 2749
                return false;
            }
        }

        len -= l;
        addr += l;
    }
2750
    rcu_read_unlock();
2751 2752 2753
    return true;
}

2754 2755 2756 2757
/* Map a physical memory region into a host virtual address.
 * May map a subset of the requested range, given by and returned in *plen.
 * May return NULL if resources needed to perform the mapping are exhausted.
 * Use only for reads OR writes - not for read-modify-write operations.
2758 2759
 * Use cpu_register_map_client() to know when retrying the map operation is
 * likely to succeed.
2760
 */
A
Avi Kivity 已提交
2761
void *address_space_map(AddressSpace *as,
A
Avi Kivity 已提交
2762 2763
                        hwaddr addr,
                        hwaddr *plen,
A
Avi Kivity 已提交
2764
                        bool is_write)
2765
{
A
Avi Kivity 已提交
2766
    hwaddr len = *plen;
2767 2768 2769 2770
    hwaddr done = 0;
    hwaddr l, xlat, base;
    MemoryRegion *mr, *this_mr;
    ram_addr_t raddr;
2771

2772 2773 2774
    if (len == 0) {
        return NULL;
    }
2775

2776
    l = len;
2777
    rcu_read_lock();
2778
    mr = address_space_translate(as, addr, &xlat, &l, is_write);
2779

2780
    if (!memory_access_is_direct(mr, is_write)) {
F
Fam Zheng 已提交
2781
        if (atomic_xchg(&bounce.in_use, true)) {
2782
            rcu_read_unlock();
2783
            return NULL;
2784
        }
2785 2786 2787
        /* Avoid unbounded allocations */
        l = MIN(l, TARGET_PAGE_SIZE);
        bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
2788 2789
        bounce.addr = addr;
        bounce.len = l;
2790 2791 2792

        memory_region_ref(mr);
        bounce.mr = mr;
2793
        if (!is_write) {
2794 2795
            address_space_read(as, addr, MEMTXATTRS_UNSPECIFIED,
                               bounce.buffer, l);
2796
        }
2797

2798
        rcu_read_unlock();
2799 2800 2801 2802 2803 2804 2805 2806
        *plen = l;
        return bounce.buffer;
    }

    base = xlat;
    raddr = memory_region_get_ram_addr(mr);

    for (;;) {
2807 2808
        len -= l;
        addr += l;
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818
        done += l;
        if (len == 0) {
            break;
        }

        l = len;
        this_mr = address_space_translate(as, addr, &xlat, &l, is_write);
        if (this_mr != mr || xlat != base + done) {
            break;
        }
2819
    }
2820

2821
    memory_region_ref(mr);
2822
    rcu_read_unlock();
2823 2824
    *plen = done;
    return qemu_ram_ptr_length(raddr + base, plen);
2825 2826
}

A
Avi Kivity 已提交
2827
/* Unmaps a memory region previously mapped by address_space_map().
2828 2829 2830
 * Will also mark the memory as dirty if is_write == 1.  access_len gives
 * the amount of memory that was actually read or written by the caller.
 */
A
Avi Kivity 已提交
2831 2832
void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
                         int is_write, hwaddr access_len)
2833 2834
{
    if (buffer != bounce.buffer) {
2835 2836 2837 2838 2839
        MemoryRegion *mr;
        ram_addr_t addr1;

        mr = qemu_ram_addr_from_host(buffer, &addr1);
        assert(mr != NULL);
2840
        if (is_write) {
2841
            invalidate_and_set_dirty(mr, addr1, access_len);
2842
        }
2843
        if (xen_enabled()) {
J
Jan Kiszka 已提交
2844
            xen_invalidate_map_cache_entry(buffer);
A
Anthony PERARD 已提交
2845
        }
2846
        memory_region_unref(mr);
2847 2848 2849
        return;
    }
    if (is_write) {
2850 2851
        address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
                            bounce.buffer, access_len);
2852
    }
2853
    qemu_vfree(bounce.buffer);
2854
    bounce.buffer = NULL;
2855
    memory_region_unref(bounce.mr);
F
Fam Zheng 已提交
2856
    atomic_mb_set(&bounce.in_use, false);
2857
    cpu_notify_map_clients();
2858
}
B
bellard 已提交
2859

A
Avi Kivity 已提交
2860 2861
void *cpu_physical_memory_map(hwaddr addr,
                              hwaddr *plen,
A
Avi Kivity 已提交
2862 2863 2864 2865 2866
                              int is_write)
{
    return address_space_map(&address_space_memory, addr, plen, is_write);
}

A
Avi Kivity 已提交
2867 2868
void cpu_physical_memory_unmap(void *buffer, hwaddr len,
                               int is_write, hwaddr access_len)
A
Avi Kivity 已提交
2869 2870 2871 2872
{
    return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
}

B
bellard 已提交
2873
/* warning: addr must be aligned */
2874 2875 2876 2877
static inline uint32_t address_space_ldl_internal(AddressSpace *as, hwaddr addr,
                                                  MemTxAttrs attrs,
                                                  MemTxResult *result,
                                                  enum device_endian endian)
B
bellard 已提交
2878 2879
{
    uint8_t *ptr;
2880
    uint64_t val;
2881
    MemoryRegion *mr;
2882 2883
    hwaddr l = 4;
    hwaddr addr1;
2884
    MemTxResult r;
2885
    bool release_lock = false;
B
bellard 已提交
2886

2887
    rcu_read_lock();
2888
    mr = address_space_translate(as, addr, &addr1, &l, false);
2889
    if (l < 4 || !memory_access_is_direct(mr, false)) {
2890
        release_lock |= prepare_mmio_access(mr);
2891

B
bellard 已提交
2892
        /* I/O case */
2893
        r = memory_region_dispatch_read(mr, addr1, &val, 4, attrs);
2894 2895 2896 2897 2898 2899 2900 2901 2902
#if defined(TARGET_WORDS_BIGENDIAN)
        if (endian == DEVICE_LITTLE_ENDIAN) {
            val = bswap32(val);
        }
#else
        if (endian == DEVICE_BIG_ENDIAN) {
            val = bswap32(val);
        }
#endif
B
bellard 已提交
2903 2904
    } else {
        /* RAM case */
2905
        ptr = qemu_get_ram_ptr((memory_region_get_ram_addr(mr)
2906
                                & TARGET_PAGE_MASK)
2907
                               + addr1);
2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918
        switch (endian) {
        case DEVICE_LITTLE_ENDIAN:
            val = ldl_le_p(ptr);
            break;
        case DEVICE_BIG_ENDIAN:
            val = ldl_be_p(ptr);
            break;
        default:
            val = ldl_p(ptr);
            break;
        }
2919 2920 2921 2922
        r = MEMTX_OK;
    }
    if (result) {
        *result = r;
B
bellard 已提交
2923
    }
2924 2925 2926
    if (release_lock) {
        qemu_mutex_unlock_iothread();
    }
2927
    rcu_read_unlock();
B
bellard 已提交
2928 2929 2930
    return val;
}

2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951
uint32_t address_space_ldl(AddressSpace *as, hwaddr addr,
                           MemTxAttrs attrs, MemTxResult *result)
{
    return address_space_ldl_internal(as, addr, attrs, result,
                                      DEVICE_NATIVE_ENDIAN);
}

uint32_t address_space_ldl_le(AddressSpace *as, hwaddr addr,
                              MemTxAttrs attrs, MemTxResult *result)
{
    return address_space_ldl_internal(as, addr, attrs, result,
                                      DEVICE_LITTLE_ENDIAN);
}

uint32_t address_space_ldl_be(AddressSpace *as, hwaddr addr,
                              MemTxAttrs attrs, MemTxResult *result)
{
    return address_space_ldl_internal(as, addr, attrs, result,
                                      DEVICE_BIG_ENDIAN);
}

2952
uint32_t ldl_phys(AddressSpace *as, hwaddr addr)
2953
{
2954
    return address_space_ldl(as, addr, MEMTXATTRS_UNSPECIFIED, NULL);
2955 2956
}

2957
uint32_t ldl_le_phys(AddressSpace *as, hwaddr addr)
2958
{
2959
    return address_space_ldl_le(as, addr, MEMTXATTRS_UNSPECIFIED, NULL);
2960 2961
}

2962
uint32_t ldl_be_phys(AddressSpace *as, hwaddr addr)
2963
{
2964
    return address_space_ldl_be(as, addr, MEMTXATTRS_UNSPECIFIED, NULL);
2965 2966
}

B
bellard 已提交
2967
/* warning: addr must be aligned */
2968 2969 2970 2971
static inline uint64_t address_space_ldq_internal(AddressSpace *as, hwaddr addr,
                                                  MemTxAttrs attrs,
                                                  MemTxResult *result,
                                                  enum device_endian endian)
B
bellard 已提交
2972 2973 2974
{
    uint8_t *ptr;
    uint64_t val;
2975
    MemoryRegion *mr;
2976 2977
    hwaddr l = 8;
    hwaddr addr1;
2978
    MemTxResult r;
2979
    bool release_lock = false;
B
bellard 已提交
2980

2981
    rcu_read_lock();
2982
    mr = address_space_translate(as, addr, &addr1, &l,
2983 2984
                                 false);
    if (l < 8 || !memory_access_is_direct(mr, false)) {
2985
        release_lock |= prepare_mmio_access(mr);
2986

B
bellard 已提交
2987
        /* I/O case */
2988
        r = memory_region_dispatch_read(mr, addr1, &val, 8, attrs);
2989 2990 2991 2992 2993 2994 2995 2996
#if defined(TARGET_WORDS_BIGENDIAN)
        if (endian == DEVICE_LITTLE_ENDIAN) {
            val = bswap64(val);
        }
#else
        if (endian == DEVICE_BIG_ENDIAN) {
            val = bswap64(val);
        }
B
bellard 已提交
2997 2998 2999
#endif
    } else {
        /* RAM case */
3000
        ptr = qemu_get_ram_ptr((memory_region_get_ram_addr(mr)
3001
                                & TARGET_PAGE_MASK)
3002
                               + addr1);
3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013
        switch (endian) {
        case DEVICE_LITTLE_ENDIAN:
            val = ldq_le_p(ptr);
            break;
        case DEVICE_BIG_ENDIAN:
            val = ldq_be_p(ptr);
            break;
        default:
            val = ldq_p(ptr);
            break;
        }
3014 3015 3016 3017
        r = MEMTX_OK;
    }
    if (result) {
        *result = r;
B
bellard 已提交
3018
    }
3019 3020 3021
    if (release_lock) {
        qemu_mutex_unlock_iothread();
    }
3022
    rcu_read_unlock();
B
bellard 已提交
3023 3024 3025
    return val;
}

3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046
uint64_t address_space_ldq(AddressSpace *as, hwaddr addr,
                           MemTxAttrs attrs, MemTxResult *result)
{
    return address_space_ldq_internal(as, addr, attrs, result,
                                      DEVICE_NATIVE_ENDIAN);
}

uint64_t address_space_ldq_le(AddressSpace *as, hwaddr addr,
                           MemTxAttrs attrs, MemTxResult *result)
{
    return address_space_ldq_internal(as, addr, attrs, result,
                                      DEVICE_LITTLE_ENDIAN);
}

uint64_t address_space_ldq_be(AddressSpace *as, hwaddr addr,
                           MemTxAttrs attrs, MemTxResult *result)
{
    return address_space_ldq_internal(as, addr, attrs, result,
                                      DEVICE_BIG_ENDIAN);
}

3047
uint64_t ldq_phys(AddressSpace *as, hwaddr addr)
3048
{
3049
    return address_space_ldq(as, addr, MEMTXATTRS_UNSPECIFIED, NULL);
3050 3051
}

3052
uint64_t ldq_le_phys(AddressSpace *as, hwaddr addr)
3053
{
3054
    return address_space_ldq_le(as, addr, MEMTXATTRS_UNSPECIFIED, NULL);
3055 3056
}

3057
uint64_t ldq_be_phys(AddressSpace *as, hwaddr addr)
3058
{
3059
    return address_space_ldq_be(as, addr, MEMTXATTRS_UNSPECIFIED, NULL);
3060 3061
}

B
bellard 已提交
3062
/* XXX: optimize */
3063 3064
uint32_t address_space_ldub(AddressSpace *as, hwaddr addr,
                            MemTxAttrs attrs, MemTxResult *result)
B
bellard 已提交
3065 3066
{
    uint8_t val;
3067 3068 3069 3070 3071 3072
    MemTxResult r;

    r = address_space_rw(as, addr, attrs, &val, 1, 0);
    if (result) {
        *result = r;
    }
B
bellard 已提交
3073 3074 3075
    return val;
}

3076 3077 3078 3079 3080
uint32_t ldub_phys(AddressSpace *as, hwaddr addr)
{
    return address_space_ldub(as, addr, MEMTXATTRS_UNSPECIFIED, NULL);
}

3081
/* warning: addr must be aligned */
3082 3083 3084 3085 3086
static inline uint32_t address_space_lduw_internal(AddressSpace *as,
                                                   hwaddr addr,
                                                   MemTxAttrs attrs,
                                                   MemTxResult *result,
                                                   enum device_endian endian)
B
bellard 已提交
3087
{
3088 3089
    uint8_t *ptr;
    uint64_t val;
3090
    MemoryRegion *mr;
3091 3092
    hwaddr l = 2;
    hwaddr addr1;
3093
    MemTxResult r;
3094
    bool release_lock = false;
3095

3096
    rcu_read_lock();
3097
    mr = address_space_translate(as, addr, &addr1, &l,
3098 3099
                                 false);
    if (l < 2 || !memory_access_is_direct(mr, false)) {
3100
        release_lock |= prepare_mmio_access(mr);
3101

3102
        /* I/O case */
3103
        r = memory_region_dispatch_read(mr, addr1, &val, 2, attrs);
3104 3105 3106 3107 3108 3109 3110 3111 3112
#if defined(TARGET_WORDS_BIGENDIAN)
        if (endian == DEVICE_LITTLE_ENDIAN) {
            val = bswap16(val);
        }
#else
        if (endian == DEVICE_BIG_ENDIAN) {
            val = bswap16(val);
        }
#endif
3113 3114
    } else {
        /* RAM case */
3115
        ptr = qemu_get_ram_ptr((memory_region_get_ram_addr(mr)
3116
                                & TARGET_PAGE_MASK)
3117
                               + addr1);
3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
        switch (endian) {
        case DEVICE_LITTLE_ENDIAN:
            val = lduw_le_p(ptr);
            break;
        case DEVICE_BIG_ENDIAN:
            val = lduw_be_p(ptr);
            break;
        default:
            val = lduw_p(ptr);
            break;
        }
3129 3130 3131 3132
        r = MEMTX_OK;
    }
    if (result) {
        *result = r;
3133
    }
3134 3135 3136
    if (release_lock) {
        qemu_mutex_unlock_iothread();
    }
3137
    rcu_read_unlock();
3138
    return val;
B
bellard 已提交
3139 3140
}

3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161
uint32_t address_space_lduw(AddressSpace *as, hwaddr addr,
                           MemTxAttrs attrs, MemTxResult *result)
{
    return address_space_lduw_internal(as, addr, attrs, result,
                                       DEVICE_NATIVE_ENDIAN);
}

uint32_t address_space_lduw_le(AddressSpace *as, hwaddr addr,
                           MemTxAttrs attrs, MemTxResult *result)
{
    return address_space_lduw_internal(as, addr, attrs, result,
                                       DEVICE_LITTLE_ENDIAN);
}

uint32_t address_space_lduw_be(AddressSpace *as, hwaddr addr,
                           MemTxAttrs attrs, MemTxResult *result)
{
    return address_space_lduw_internal(as, addr, attrs, result,
                                       DEVICE_BIG_ENDIAN);
}

3162
uint32_t lduw_phys(AddressSpace *as, hwaddr addr)
3163
{
3164
    return address_space_lduw(as, addr, MEMTXATTRS_UNSPECIFIED, NULL);
3165 3166
}

3167
uint32_t lduw_le_phys(AddressSpace *as, hwaddr addr)
3168
{
3169
    return address_space_lduw_le(as, addr, MEMTXATTRS_UNSPECIFIED, NULL);
3170 3171
}

3172
uint32_t lduw_be_phys(AddressSpace *as, hwaddr addr)
3173
{
3174
    return address_space_lduw_be(as, addr, MEMTXATTRS_UNSPECIFIED, NULL);
3175 3176
}

B
bellard 已提交
3177 3178 3179
/* warning: addr must be aligned. The ram page is not masked as dirty
   and the code inside is not invalidated. It is useful if the dirty
   bits are used to track modified PTEs */
3180 3181
void address_space_stl_notdirty(AddressSpace *as, hwaddr addr, uint32_t val,
                                MemTxAttrs attrs, MemTxResult *result)
B
bellard 已提交
3182 3183
{
    uint8_t *ptr;
3184
    MemoryRegion *mr;
3185 3186
    hwaddr l = 4;
    hwaddr addr1;
3187
    MemTxResult r;
3188
    uint8_t dirty_log_mask;
3189
    bool release_lock = false;
B
bellard 已提交
3190

3191
    rcu_read_lock();
3192
    mr = address_space_translate(as, addr, &addr1, &l,
3193 3194
                                 true);
    if (l < 4 || !memory_access_is_direct(mr, true)) {
3195
        release_lock |= prepare_mmio_access(mr);
3196

3197
        r = memory_region_dispatch_write(mr, addr1, val, 4, attrs);
B
bellard 已提交
3198
    } else {
3199
        addr1 += memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK;
P
pbrook 已提交
3200
        ptr = qemu_get_ram_ptr(addr1);
B
bellard 已提交
3201
        stl_p(ptr, val);
A
aliguori 已提交
3202

3203 3204
        dirty_log_mask = memory_region_get_dirty_log_mask(mr);
        dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
3205
        cpu_physical_memory_set_dirty_range(addr1, 4, dirty_log_mask);
3206 3207 3208 3209
        r = MEMTX_OK;
    }
    if (result) {
        *result = r;
B
bellard 已提交
3210
    }
3211 3212 3213
    if (release_lock) {
        qemu_mutex_unlock_iothread();
    }
3214
    rcu_read_unlock();
B
bellard 已提交
3215 3216
}

3217 3218 3219 3220 3221
void stl_phys_notdirty(AddressSpace *as, hwaddr addr, uint32_t val)
{
    address_space_stl_notdirty(as, addr, val, MEMTXATTRS_UNSPECIFIED, NULL);
}

B
bellard 已提交
3222
/* warning: addr must be aligned */
3223 3224 3225 3226 3227
static inline void address_space_stl_internal(AddressSpace *as,
                                              hwaddr addr, uint32_t val,
                                              MemTxAttrs attrs,
                                              MemTxResult *result,
                                              enum device_endian endian)
B
bellard 已提交
3228 3229
{
    uint8_t *ptr;
3230
    MemoryRegion *mr;
3231 3232
    hwaddr l = 4;
    hwaddr addr1;
3233
    MemTxResult r;
3234
    bool release_lock = false;
B
bellard 已提交
3235

3236
    rcu_read_lock();
3237
    mr = address_space_translate(as, addr, &addr1, &l,
3238 3239
                                 true);
    if (l < 4 || !memory_access_is_direct(mr, true)) {
3240
        release_lock |= prepare_mmio_access(mr);
3241

3242 3243 3244 3245 3246 3247 3248 3249 3250
#if defined(TARGET_WORDS_BIGENDIAN)
        if (endian == DEVICE_LITTLE_ENDIAN) {
            val = bswap32(val);
        }
#else
        if (endian == DEVICE_BIG_ENDIAN) {
            val = bswap32(val);
        }
#endif
3251
        r = memory_region_dispatch_write(mr, addr1, val, 4, attrs);
B
bellard 已提交
3252 3253
    } else {
        /* RAM case */
3254
        addr1 += memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK;
P
pbrook 已提交
3255
        ptr = qemu_get_ram_ptr(addr1);
3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266
        switch (endian) {
        case DEVICE_LITTLE_ENDIAN:
            stl_le_p(ptr, val);
            break;
        case DEVICE_BIG_ENDIAN:
            stl_be_p(ptr, val);
            break;
        default:
            stl_p(ptr, val);
            break;
        }
3267
        invalidate_and_set_dirty(mr, addr1, 4);
3268 3269 3270 3271
        r = MEMTX_OK;
    }
    if (result) {
        *result = r;
B
bellard 已提交
3272
    }
3273 3274 3275
    if (release_lock) {
        qemu_mutex_unlock_iothread();
    }
3276
    rcu_read_unlock();
B
bellard 已提交
3277 3278
}

3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299
void address_space_stl(AddressSpace *as, hwaddr addr, uint32_t val,
                       MemTxAttrs attrs, MemTxResult *result)
{
    address_space_stl_internal(as, addr, val, attrs, result,
                               DEVICE_NATIVE_ENDIAN);
}

void address_space_stl_le(AddressSpace *as, hwaddr addr, uint32_t val,
                       MemTxAttrs attrs, MemTxResult *result)
{
    address_space_stl_internal(as, addr, val, attrs, result,
                               DEVICE_LITTLE_ENDIAN);
}

void address_space_stl_be(AddressSpace *as, hwaddr addr, uint32_t val,
                       MemTxAttrs attrs, MemTxResult *result)
{
    address_space_stl_internal(as, addr, val, attrs, result,
                               DEVICE_BIG_ENDIAN);
}

3300
void stl_phys(AddressSpace *as, hwaddr addr, uint32_t val)
3301
{
3302
    address_space_stl(as, addr, val, MEMTXATTRS_UNSPECIFIED, NULL);
3303 3304
}

3305
void stl_le_phys(AddressSpace *as, hwaddr addr, uint32_t val)
3306
{
3307
    address_space_stl_le(as, addr, val, MEMTXATTRS_UNSPECIFIED, NULL);
3308 3309
}

3310
void stl_be_phys(AddressSpace *as, hwaddr addr, uint32_t val)
3311
{
3312
    address_space_stl_be(as, addr, val, MEMTXATTRS_UNSPECIFIED, NULL);
3313 3314
}

B
bellard 已提交
3315
/* XXX: optimize */
3316 3317
void address_space_stb(AddressSpace *as, hwaddr addr, uint32_t val,
                       MemTxAttrs attrs, MemTxResult *result)
B
bellard 已提交
3318 3319
{
    uint8_t v = val;
3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330
    MemTxResult r;

    r = address_space_rw(as, addr, attrs, &v, 1, 1);
    if (result) {
        *result = r;
    }
}

void stb_phys(AddressSpace *as, hwaddr addr, uint32_t val)
{
    address_space_stb(as, addr, val, MEMTXATTRS_UNSPECIFIED, NULL);
B
bellard 已提交
3331 3332
}

3333
/* warning: addr must be aligned */
3334 3335 3336 3337 3338
static inline void address_space_stw_internal(AddressSpace *as,
                                              hwaddr addr, uint32_t val,
                                              MemTxAttrs attrs,
                                              MemTxResult *result,
                                              enum device_endian endian)
B
bellard 已提交
3339
{
3340
    uint8_t *ptr;
3341
    MemoryRegion *mr;
3342 3343
    hwaddr l = 2;
    hwaddr addr1;
3344
    MemTxResult r;
3345
    bool release_lock = false;
3346

3347
    rcu_read_lock();
3348
    mr = address_space_translate(as, addr, &addr1, &l, true);
3349
    if (l < 2 || !memory_access_is_direct(mr, true)) {
3350
        release_lock |= prepare_mmio_access(mr);
3351

3352 3353 3354 3355 3356 3357 3358 3359 3360
#if defined(TARGET_WORDS_BIGENDIAN)
        if (endian == DEVICE_LITTLE_ENDIAN) {
            val = bswap16(val);
        }
#else
        if (endian == DEVICE_BIG_ENDIAN) {
            val = bswap16(val);
        }
#endif
3361
        r = memory_region_dispatch_write(mr, addr1, val, 2, attrs);
3362 3363
    } else {
        /* RAM case */
3364
        addr1 += memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK;
3365
        ptr = qemu_get_ram_ptr(addr1);
3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376
        switch (endian) {
        case DEVICE_LITTLE_ENDIAN:
            stw_le_p(ptr, val);
            break;
        case DEVICE_BIG_ENDIAN:
            stw_be_p(ptr, val);
            break;
        default:
            stw_p(ptr, val);
            break;
        }
3377
        invalidate_and_set_dirty(mr, addr1, 2);
3378 3379 3380 3381
        r = MEMTX_OK;
    }
    if (result) {
        *result = r;
3382
    }
3383 3384 3385
    if (release_lock) {
        qemu_mutex_unlock_iothread();
    }
3386
    rcu_read_unlock();
B
bellard 已提交
3387 3388
}

3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409
void address_space_stw(AddressSpace *as, hwaddr addr, uint32_t val,
                       MemTxAttrs attrs, MemTxResult *result)
{
    address_space_stw_internal(as, addr, val, attrs, result,
                               DEVICE_NATIVE_ENDIAN);
}

void address_space_stw_le(AddressSpace *as, hwaddr addr, uint32_t val,
                       MemTxAttrs attrs, MemTxResult *result)
{
    address_space_stw_internal(as, addr, val, attrs, result,
                               DEVICE_LITTLE_ENDIAN);
}

void address_space_stw_be(AddressSpace *as, hwaddr addr, uint32_t val,
                       MemTxAttrs attrs, MemTxResult *result)
{
    address_space_stw_internal(as, addr, val, attrs, result,
                               DEVICE_BIG_ENDIAN);
}

3410
void stw_phys(AddressSpace *as, hwaddr addr, uint32_t val)
3411
{
3412
    address_space_stw(as, addr, val, MEMTXATTRS_UNSPECIFIED, NULL);
3413 3414
}

3415
void stw_le_phys(AddressSpace *as, hwaddr addr, uint32_t val)
3416
{
3417
    address_space_stw_le(as, addr, val, MEMTXATTRS_UNSPECIFIED, NULL);
3418 3419
}

3420
void stw_be_phys(AddressSpace *as, hwaddr addr, uint32_t val)
3421
{
3422
    address_space_stw_be(as, addr, val, MEMTXATTRS_UNSPECIFIED, NULL);
3423 3424
}

B
bellard 已提交
3425
/* XXX: optimize */
3426 3427
void address_space_stq(AddressSpace *as, hwaddr addr, uint64_t val,
                       MemTxAttrs attrs, MemTxResult *result)
B
bellard 已提交
3428
{
3429
    MemTxResult r;
B
bellard 已提交
3430
    val = tswap64(val);
3431 3432 3433 3434
    r = address_space_rw(as, addr, attrs, (void *) &val, 8, 1);
    if (result) {
        *result = r;
    }
B
bellard 已提交
3435 3436
}

3437 3438
void address_space_stq_le(AddressSpace *as, hwaddr addr, uint64_t val,
                       MemTxAttrs attrs, MemTxResult *result)
3439
{
3440
    MemTxResult r;
3441
    val = cpu_to_le64(val);
3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465
    r = address_space_rw(as, addr, attrs, (void *) &val, 8, 1);
    if (result) {
        *result = r;
    }
}
void address_space_stq_be(AddressSpace *as, hwaddr addr, uint64_t val,
                       MemTxAttrs attrs, MemTxResult *result)
{
    MemTxResult r;
    val = cpu_to_be64(val);
    r = address_space_rw(as, addr, attrs, (void *) &val, 8, 1);
    if (result) {
        *result = r;
    }
}

void stq_phys(AddressSpace *as, hwaddr addr, uint64_t val)
{
    address_space_stq(as, addr, val, MEMTXATTRS_UNSPECIFIED, NULL);
}

void stq_le_phys(AddressSpace *as, hwaddr addr, uint64_t val)
{
    address_space_stq_le(as, addr, val, MEMTXATTRS_UNSPECIFIED, NULL);
3466 3467
}

3468
void stq_be_phys(AddressSpace *as, hwaddr addr, uint64_t val)
3469
{
3470
    address_space_stq_be(as, addr, val, MEMTXATTRS_UNSPECIFIED, NULL);
3471 3472
}

3473
/* virtual memory access for debug (includes writing to ROM) */
3474
int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3475
                        uint8_t *buf, int len, int is_write)
B
bellard 已提交
3476 3477
{
    int l;
A
Avi Kivity 已提交
3478
    hwaddr phys_addr;
3479
    target_ulong page;
B
bellard 已提交
3480 3481 3482

    while (len > 0) {
        page = addr & TARGET_PAGE_MASK;
3483
        phys_addr = cpu_get_phys_page_debug(cpu, page);
B
bellard 已提交
3484 3485 3486 3487 3488 3489
        /* if no physical page mapped, return an error */
        if (phys_addr == -1)
            return -1;
        l = (page + TARGET_PAGE_SIZE) - addr;
        if (l > len)
            l = len;
3490
        phys_addr += (addr & ~TARGET_PAGE_MASK);
3491 3492 3493
        if (is_write) {
            cpu_physical_memory_write_rom(cpu->as, phys_addr, buf, l);
        } else {
3494 3495
            address_space_rw(cpu->as, phys_addr, MEMTXATTRS_UNSPECIFIED,
                             buf, l, 0);
3496
        }
B
bellard 已提交
3497 3498 3499 3500 3501 3502
        len -= l;
        buf += l;
        addr += l;
    }
    return 0;
}
P
Paul Brook 已提交
3503
#endif
B
bellard 已提交
3504

3505 3506 3507 3508
/*
 * A helper function for the _utterly broken_ virtio device model to find out if
 * it's running on a big endian machine. Don't do this at home kids!
 */
3509 3510
bool target_words_bigendian(void);
bool target_words_bigendian(void)
3511 3512 3513 3514 3515 3516 3517 3518
{
#if defined(TARGET_WORDS_BIGENDIAN)
    return true;
#else
    return false;
#endif
}

3519
#ifndef CONFIG_USER_ONLY
A
Avi Kivity 已提交
3520
bool cpu_physical_memory_is_io(hwaddr phys_addr)
3521
{
3522
    MemoryRegion*mr;
3523
    hwaddr l = 1;
3524
    bool res;
3525

3526
    rcu_read_lock();
3527 3528
    mr = address_space_translate(&address_space_memory,
                                 phys_addr, &phys_addr, &l, false);
3529

3530 3531 3532
    res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
    rcu_read_unlock();
    return res;
3533
}
3534

3535
int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3536 3537
{
    RAMBlock *block;
3538
    int ret = 0;
3539

M
Mike Day 已提交
3540 3541
    rcu_read_lock();
    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
3542 3543 3544 3545 3546
        ret = func(block->idstr, block->host, block->offset,
                   block->used_length, opaque);
        if (ret) {
            break;
        }
3547
    }
M
Mike Day 已提交
3548
    rcu_read_unlock();
3549
    return ret;
3550
}
3551
#endif