Merge remote-tracking branch 'remotes/amit-virtio-rng/tags/rng-2.7-1' into staging
[qemu.git] / xen-hvm.c
blobc14e778a8e6fbb191848a1091aa52f6c6e25cf5c
1 /*
2 * Copyright (C) 2010 Citrix Ltd.
4 * This work is licensed under the terms of the GNU GPL, version 2. See
5 * the COPYING file in the top-level directory.
7 * Contributions after 2012-01-13 are licensed under the terms of the
8 * GNU GPL, version 2 or (at your option) any later version.
9 */
11 #include "qemu/osdep.h"
12 #include <sys/mman.h>
14 #include "cpu.h"
15 #include "hw/pci/pci.h"
16 #include "hw/i386/pc.h"
17 #include "hw/i386/apic-msidef.h"
18 #include "hw/xen/xen_common.h"
19 #include "hw/xen/xen_backend.h"
20 #include "qmp-commands.h"
22 #include "sysemu/char.h"
23 #include "qemu/error-report.h"
24 #include "qemu/range.h"
25 #include "sysemu/xen-mapcache.h"
26 #include "trace.h"
27 #include "exec/address-spaces.h"
29 #include <xen/hvm/ioreq.h>
30 #include <xen/hvm/params.h>
31 #include <xen/hvm/e820.h>
33 //#define DEBUG_XEN_HVM
35 #ifdef DEBUG_XEN_HVM
36 #define DPRINTF(fmt, ...) \
37 do { fprintf(stderr, "xen: " fmt, ## __VA_ARGS__); } while (0)
38 #else
39 #define DPRINTF(fmt, ...) \
40 do { } while (0)
41 #endif
43 static MemoryRegion ram_memory, ram_640k, ram_lo, ram_hi;
44 static MemoryRegion *framebuffer;
45 static bool xen_in_migration;
47 /* Compatibility with older version */
49 /* This allows QEMU to build on a system that has Xen 4.5 or earlier
50 * installed. This here (not in hw/xen/xen_common.h) because xen/hvm/ioreq.h
51 * needs to be included before this block and hw/xen/xen_common.h needs to
52 * be included before xen/hvm/ioreq.h
54 #ifndef IOREQ_TYPE_VMWARE_PORT
55 #define IOREQ_TYPE_VMWARE_PORT 3
56 struct vmware_regs {
57 uint32_t esi;
58 uint32_t edi;
59 uint32_t ebx;
60 uint32_t ecx;
61 uint32_t edx;
63 typedef struct vmware_regs vmware_regs_t;
65 struct shared_vmport_iopage {
66 struct vmware_regs vcpu_vmport_regs[1];
68 typedef struct shared_vmport_iopage shared_vmport_iopage_t;
69 #endif
71 static inline uint32_t xen_vcpu_eport(shared_iopage_t *shared_page, int i)
73 return shared_page->vcpu_ioreq[i].vp_eport;
75 static inline ioreq_t *xen_vcpu_ioreq(shared_iopage_t *shared_page, int vcpu)
77 return &shared_page->vcpu_ioreq[vcpu];
80 #define BUFFER_IO_MAX_DELAY 100
82 typedef struct XenPhysmap {
83 hwaddr start_addr;
84 ram_addr_t size;
85 const char *name;
86 hwaddr phys_offset;
88 QLIST_ENTRY(XenPhysmap) list;
89 } XenPhysmap;
91 typedef struct XenIOState {
92 ioservid_t ioservid;
93 shared_iopage_t *shared_page;
94 shared_vmport_iopage_t *shared_vmport_page;
95 buffered_iopage_t *buffered_io_page;
96 QEMUTimer *buffered_io_timer;
97 CPUState **cpu_by_vcpu_id;
98 /* the evtchn port for polling the notification, */
99 evtchn_port_t *ioreq_local_port;
100 /* evtchn local port for buffered io */
101 evtchn_port_t bufioreq_local_port;
102 /* the evtchn fd for polling */
103 xenevtchn_handle *xce_handle;
104 /* which vcpu we are serving */
105 int send_vcpu;
107 struct xs_handle *xenstore;
108 MemoryListener memory_listener;
109 MemoryListener io_listener;
110 DeviceListener device_listener;
111 QLIST_HEAD(, XenPhysmap) physmap;
112 hwaddr free_phys_offset;
113 const XenPhysmap *log_for_dirtybit;
115 Notifier exit;
116 Notifier suspend;
117 Notifier wakeup;
118 } XenIOState;
120 /* Xen specific function for piix pci */
122 int xen_pci_slot_get_pirq(PCIDevice *pci_dev, int irq_num)
124 return irq_num + ((pci_dev->devfn >> 3) << 2);
127 void xen_piix3_set_irq(void *opaque, int irq_num, int level)
129 xc_hvm_set_pci_intx_level(xen_xc, xen_domid, 0, 0, irq_num >> 2,
130 irq_num & 3, level);
133 void xen_piix_pci_write_config_client(uint32_t address, uint32_t val, int len)
135 int i;
137 /* Scan for updates to PCI link routes (0x60-0x63). */
138 for (i = 0; i < len; i++) {
139 uint8_t v = (val >> (8 * i)) & 0xff;
140 if (v & 0x80) {
141 v = 0;
143 v &= 0xf;
144 if (((address + i) >= 0x60) && ((address + i) <= 0x63)) {
145 xc_hvm_set_pci_link_route(xen_xc, xen_domid, address + i - 0x60, v);
150 int xen_is_pirq_msi(uint32_t msi_data)
152 /* If vector is 0, the msi is remapped into a pirq, passed as
153 * dest_id.
155 return ((msi_data & MSI_DATA_VECTOR_MASK) >> MSI_DATA_VECTOR_SHIFT) == 0;
158 void xen_hvm_inject_msi(uint64_t addr, uint32_t data)
160 xc_hvm_inject_msi(xen_xc, xen_domid, addr, data);
163 static void xen_suspend_notifier(Notifier *notifier, void *data)
165 xc_set_hvm_param(xen_xc, xen_domid, HVM_PARAM_ACPI_S_STATE, 3);
168 /* Xen Interrupt Controller */
170 static void xen_set_irq(void *opaque, int irq, int level)
172 xc_hvm_set_isa_irq_level(xen_xc, xen_domid, irq, level);
175 qemu_irq *xen_interrupt_controller_init(void)
177 return qemu_allocate_irqs(xen_set_irq, NULL, 16);
180 /* Memory Ops */
182 static void xen_ram_init(PCMachineState *pcms,
183 ram_addr_t ram_size, MemoryRegion **ram_memory_p)
185 MemoryRegion *sysmem = get_system_memory();
186 ram_addr_t block_len;
187 uint64_t user_lowmem = object_property_get_int(qdev_get_machine(),
188 PC_MACHINE_MAX_RAM_BELOW_4G,
189 &error_abort);
191 /* Handle the machine opt max-ram-below-4g. It is basically doing
192 * min(xen limit, user limit).
194 if (HVM_BELOW_4G_RAM_END <= user_lowmem) {
195 user_lowmem = HVM_BELOW_4G_RAM_END;
198 if (ram_size >= user_lowmem) {
199 pcms->above_4g_mem_size = ram_size - user_lowmem;
200 pcms->below_4g_mem_size = user_lowmem;
201 } else {
202 pcms->above_4g_mem_size = 0;
203 pcms->below_4g_mem_size = ram_size;
205 if (!pcms->above_4g_mem_size) {
206 block_len = ram_size;
207 } else {
209 * Xen does not allocate the memory continuously, it keeps a
210 * hole of the size computed above or passed in.
212 block_len = (1ULL << 32) + pcms->above_4g_mem_size;
214 memory_region_init_ram(&ram_memory, NULL, "xen.ram", block_len,
215 &error_fatal);
216 *ram_memory_p = &ram_memory;
217 vmstate_register_ram_global(&ram_memory);
219 memory_region_init_alias(&ram_640k, NULL, "xen.ram.640k",
220 &ram_memory, 0, 0xa0000);
221 memory_region_add_subregion(sysmem, 0, &ram_640k);
222 /* Skip of the VGA IO memory space, it will be registered later by the VGA
223 * emulated device.
225 * The area between 0xc0000 and 0x100000 will be used by SeaBIOS to load
226 * the Options ROM, so it is registered here as RAM.
228 memory_region_init_alias(&ram_lo, NULL, "xen.ram.lo",
229 &ram_memory, 0xc0000,
230 pcms->below_4g_mem_size - 0xc0000);
231 memory_region_add_subregion(sysmem, 0xc0000, &ram_lo);
232 if (pcms->above_4g_mem_size > 0) {
233 memory_region_init_alias(&ram_hi, NULL, "xen.ram.hi",
234 &ram_memory, 0x100000000ULL,
235 pcms->above_4g_mem_size);
236 memory_region_add_subregion(sysmem, 0x100000000ULL, &ram_hi);
240 void xen_ram_alloc(ram_addr_t ram_addr, ram_addr_t size, MemoryRegion *mr,
241 Error **errp)
243 unsigned long nr_pfn;
244 xen_pfn_t *pfn_list;
245 int i;
247 if (runstate_check(RUN_STATE_INMIGRATE)) {
248 /* RAM already populated in Xen */
249 fprintf(stderr, "%s: do not alloc "RAM_ADDR_FMT
250 " bytes of ram at "RAM_ADDR_FMT" when runstate is INMIGRATE\n",
251 __func__, size, ram_addr);
252 return;
255 if (mr == &ram_memory) {
256 return;
259 trace_xen_ram_alloc(ram_addr, size);
261 nr_pfn = size >> TARGET_PAGE_BITS;
262 pfn_list = g_malloc(sizeof (*pfn_list) * nr_pfn);
264 for (i = 0; i < nr_pfn; i++) {
265 pfn_list[i] = (ram_addr >> TARGET_PAGE_BITS) + i;
268 if (xc_domain_populate_physmap_exact(xen_xc, xen_domid, nr_pfn, 0, 0, pfn_list)) {
269 error_setg(errp, "xen: failed to populate ram at " RAM_ADDR_FMT,
270 ram_addr);
273 g_free(pfn_list);
276 static XenPhysmap *get_physmapping(XenIOState *state,
277 hwaddr start_addr, ram_addr_t size)
279 XenPhysmap *physmap = NULL;
281 start_addr &= TARGET_PAGE_MASK;
283 QLIST_FOREACH(physmap, &state->physmap, list) {
284 if (range_covers_byte(physmap->start_addr, physmap->size, start_addr)) {
285 return physmap;
288 return NULL;
291 static hwaddr xen_phys_offset_to_gaddr(hwaddr start_addr,
292 ram_addr_t size, void *opaque)
294 hwaddr addr = start_addr & TARGET_PAGE_MASK;
295 XenIOState *xen_io_state = opaque;
296 XenPhysmap *physmap = NULL;
298 QLIST_FOREACH(physmap, &xen_io_state->physmap, list) {
299 if (range_covers_byte(physmap->phys_offset, physmap->size, addr)) {
300 return physmap->start_addr;
304 return start_addr;
307 static int xen_add_to_physmap(XenIOState *state,
308 hwaddr start_addr,
309 ram_addr_t size,
310 MemoryRegion *mr,
311 hwaddr offset_within_region)
313 unsigned long i = 0;
314 int rc = 0;
315 XenPhysmap *physmap = NULL;
316 hwaddr pfn, start_gpfn;
317 hwaddr phys_offset = memory_region_get_ram_addr(mr);
318 char path[80], value[17];
319 const char *mr_name;
321 if (get_physmapping(state, start_addr, size)) {
322 return 0;
324 if (size <= 0) {
325 return -1;
328 /* Xen can only handle a single dirty log region for now and we want
329 * the linear framebuffer to be that region.
330 * Avoid tracking any regions that is not videoram and avoid tracking
331 * the legacy vga region. */
332 if (mr == framebuffer && start_addr > 0xbffff) {
333 goto go_physmap;
335 return -1;
337 go_physmap:
338 DPRINTF("mapping vram to %"HWADDR_PRIx" - %"HWADDR_PRIx"\n",
339 start_addr, start_addr + size);
341 pfn = phys_offset >> TARGET_PAGE_BITS;
342 start_gpfn = start_addr >> TARGET_PAGE_BITS;
343 for (i = 0; i < size >> TARGET_PAGE_BITS; i++) {
344 unsigned long idx = pfn + i;
345 xen_pfn_t gpfn = start_gpfn + i;
347 rc = xen_xc_domain_add_to_physmap(xen_xc, xen_domid, XENMAPSPACE_gmfn, idx, gpfn);
348 if (rc) {
349 DPRINTF("add_to_physmap MFN %"PRI_xen_pfn" to PFN %"
350 PRI_xen_pfn" failed: %d (errno: %d)\n", idx, gpfn, rc, errno);
351 return -rc;
355 mr_name = memory_region_name(mr);
357 physmap = g_malloc(sizeof (XenPhysmap));
359 physmap->start_addr = start_addr;
360 physmap->size = size;
361 physmap->name = mr_name;
362 physmap->phys_offset = phys_offset;
364 QLIST_INSERT_HEAD(&state->physmap, physmap, list);
366 xc_domain_pin_memory_cacheattr(xen_xc, xen_domid,
367 start_addr >> TARGET_PAGE_BITS,
368 (start_addr + size - 1) >> TARGET_PAGE_BITS,
369 XEN_DOMCTL_MEM_CACHEATTR_WB);
371 snprintf(path, sizeof(path),
372 "/local/domain/0/device-model/%d/physmap/%"PRIx64"/start_addr",
373 xen_domid, (uint64_t)phys_offset);
374 snprintf(value, sizeof(value), "%"PRIx64, (uint64_t)start_addr);
375 if (!xs_write(state->xenstore, 0, path, value, strlen(value))) {
376 return -1;
378 snprintf(path, sizeof(path),
379 "/local/domain/0/device-model/%d/physmap/%"PRIx64"/size",
380 xen_domid, (uint64_t)phys_offset);
381 snprintf(value, sizeof(value), "%"PRIx64, (uint64_t)size);
382 if (!xs_write(state->xenstore, 0, path, value, strlen(value))) {
383 return -1;
385 if (mr_name) {
386 snprintf(path, sizeof(path),
387 "/local/domain/0/device-model/%d/physmap/%"PRIx64"/name",
388 xen_domid, (uint64_t)phys_offset);
389 if (!xs_write(state->xenstore, 0, path, mr_name, strlen(mr_name))) {
390 return -1;
394 return 0;
397 static int xen_remove_from_physmap(XenIOState *state,
398 hwaddr start_addr,
399 ram_addr_t size)
401 unsigned long i = 0;
402 int rc = 0;
403 XenPhysmap *physmap = NULL;
404 hwaddr phys_offset = 0;
406 physmap = get_physmapping(state, start_addr, size);
407 if (physmap == NULL) {
408 return -1;
411 phys_offset = physmap->phys_offset;
412 size = physmap->size;
414 DPRINTF("unmapping vram to %"HWADDR_PRIx" - %"HWADDR_PRIx", at "
415 "%"HWADDR_PRIx"\n", start_addr, start_addr + size, phys_offset);
417 size >>= TARGET_PAGE_BITS;
418 start_addr >>= TARGET_PAGE_BITS;
419 phys_offset >>= TARGET_PAGE_BITS;
420 for (i = 0; i < size; i++) {
421 xen_pfn_t idx = start_addr + i;
422 xen_pfn_t gpfn = phys_offset + i;
424 rc = xen_xc_domain_add_to_physmap(xen_xc, xen_domid, XENMAPSPACE_gmfn, idx, gpfn);
425 if (rc) {
426 fprintf(stderr, "add_to_physmap MFN %"PRI_xen_pfn" to PFN %"
427 PRI_xen_pfn" failed: %d (errno: %d)\n", idx, gpfn, rc, errno);
428 return -rc;
432 QLIST_REMOVE(physmap, list);
433 if (state->log_for_dirtybit == physmap) {
434 state->log_for_dirtybit = NULL;
436 g_free(physmap);
438 return 0;
441 static void xen_set_memory(struct MemoryListener *listener,
442 MemoryRegionSection *section,
443 bool add)
445 XenIOState *state = container_of(listener, XenIOState, memory_listener);
446 hwaddr start_addr = section->offset_within_address_space;
447 ram_addr_t size = int128_get64(section->size);
448 bool log_dirty = memory_region_is_logging(section->mr, DIRTY_MEMORY_VGA);
449 hvmmem_type_t mem_type;
451 if (section->mr == &ram_memory) {
452 return;
453 } else {
454 if (add) {
455 xen_map_memory_section(xen_xc, xen_domid, state->ioservid,
456 section);
457 } else {
458 xen_unmap_memory_section(xen_xc, xen_domid, state->ioservid,
459 section);
463 if (!memory_region_is_ram(section->mr)) {
464 return;
467 if (log_dirty != add) {
468 return;
471 trace_xen_client_set_memory(start_addr, size, log_dirty);
473 start_addr &= TARGET_PAGE_MASK;
474 size = TARGET_PAGE_ALIGN(size);
476 if (add) {
477 if (!memory_region_is_rom(section->mr)) {
478 xen_add_to_physmap(state, start_addr, size,
479 section->mr, section->offset_within_region);
480 } else {
481 mem_type = HVMMEM_ram_ro;
482 if (xc_hvm_set_mem_type(xen_xc, xen_domid, mem_type,
483 start_addr >> TARGET_PAGE_BITS,
484 size >> TARGET_PAGE_BITS)) {
485 DPRINTF("xc_hvm_set_mem_type error, addr: "TARGET_FMT_plx"\n",
486 start_addr);
489 } else {
490 if (xen_remove_from_physmap(state, start_addr, size) < 0) {
491 DPRINTF("physmapping does not exist at "TARGET_FMT_plx"\n", start_addr);
496 static void xen_region_add(MemoryListener *listener,
497 MemoryRegionSection *section)
499 memory_region_ref(section->mr);
500 xen_set_memory(listener, section, true);
503 static void xen_region_del(MemoryListener *listener,
504 MemoryRegionSection *section)
506 xen_set_memory(listener, section, false);
507 memory_region_unref(section->mr);
510 static void xen_io_add(MemoryListener *listener,
511 MemoryRegionSection *section)
513 XenIOState *state = container_of(listener, XenIOState, io_listener);
515 memory_region_ref(section->mr);
517 xen_map_io_section(xen_xc, xen_domid, state->ioservid, section);
520 static void xen_io_del(MemoryListener *listener,
521 MemoryRegionSection *section)
523 XenIOState *state = container_of(listener, XenIOState, io_listener);
525 xen_unmap_io_section(xen_xc, xen_domid, state->ioservid, section);
527 memory_region_unref(section->mr);
530 static void xen_device_realize(DeviceListener *listener,
531 DeviceState *dev)
533 XenIOState *state = container_of(listener, XenIOState, device_listener);
535 if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {
536 PCIDevice *pci_dev = PCI_DEVICE(dev);
538 xen_map_pcidev(xen_xc, xen_domid, state->ioservid, pci_dev);
542 static void xen_device_unrealize(DeviceListener *listener,
543 DeviceState *dev)
545 XenIOState *state = container_of(listener, XenIOState, device_listener);
547 if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {
548 PCIDevice *pci_dev = PCI_DEVICE(dev);
550 xen_unmap_pcidev(xen_xc, xen_domid, state->ioservid, pci_dev);
554 static void xen_sync_dirty_bitmap(XenIOState *state,
555 hwaddr start_addr,
556 ram_addr_t size)
558 hwaddr npages = size >> TARGET_PAGE_BITS;
559 const int width = sizeof(unsigned long) * 8;
560 unsigned long bitmap[(npages + width - 1) / width];
561 int rc, i, j;
562 const XenPhysmap *physmap = NULL;
564 physmap = get_physmapping(state, start_addr, size);
565 if (physmap == NULL) {
566 /* not handled */
567 return;
570 if (state->log_for_dirtybit == NULL) {
571 state->log_for_dirtybit = physmap;
572 } else if (state->log_for_dirtybit != physmap) {
573 /* Only one range for dirty bitmap can be tracked. */
574 return;
577 rc = xc_hvm_track_dirty_vram(xen_xc, xen_domid,
578 start_addr >> TARGET_PAGE_BITS, npages,
579 bitmap);
580 if (rc < 0) {
581 #ifndef ENODATA
582 #define ENODATA ENOENT
583 #endif
584 if (errno == ENODATA) {
585 memory_region_set_dirty(framebuffer, 0, size);
586 DPRINTF("xen: track_dirty_vram failed (0x" TARGET_FMT_plx
587 ", 0x" TARGET_FMT_plx "): %s\n",
588 start_addr, start_addr + size, strerror(errno));
590 return;
593 for (i = 0; i < ARRAY_SIZE(bitmap); i++) {
594 unsigned long map = bitmap[i];
595 while (map != 0) {
596 j = ctzl(map);
597 map &= ~(1ul << j);
598 memory_region_set_dirty(framebuffer,
599 (i * width + j) * TARGET_PAGE_SIZE,
600 TARGET_PAGE_SIZE);
605 static void xen_log_start(MemoryListener *listener,
606 MemoryRegionSection *section,
607 int old, int new)
609 XenIOState *state = container_of(listener, XenIOState, memory_listener);
611 if (new & ~old & (1 << DIRTY_MEMORY_VGA)) {
612 xen_sync_dirty_bitmap(state, section->offset_within_address_space,
613 int128_get64(section->size));
617 static void xen_log_stop(MemoryListener *listener, MemoryRegionSection *section,
618 int old, int new)
620 XenIOState *state = container_of(listener, XenIOState, memory_listener);
622 if (old & ~new & (1 << DIRTY_MEMORY_VGA)) {
623 state->log_for_dirtybit = NULL;
624 /* Disable dirty bit tracking */
625 xc_hvm_track_dirty_vram(xen_xc, xen_domid, 0, 0, NULL);
629 static void xen_log_sync(MemoryListener *listener, MemoryRegionSection *section)
631 XenIOState *state = container_of(listener, XenIOState, memory_listener);
633 xen_sync_dirty_bitmap(state, section->offset_within_address_space,
634 int128_get64(section->size));
637 static void xen_log_global_start(MemoryListener *listener)
639 if (xen_enabled()) {
640 xen_in_migration = true;
644 static void xen_log_global_stop(MemoryListener *listener)
646 xen_in_migration = false;
649 static MemoryListener xen_memory_listener = {
650 .region_add = xen_region_add,
651 .region_del = xen_region_del,
652 .log_start = xen_log_start,
653 .log_stop = xen_log_stop,
654 .log_sync = xen_log_sync,
655 .log_global_start = xen_log_global_start,
656 .log_global_stop = xen_log_global_stop,
657 .priority = 10,
660 static MemoryListener xen_io_listener = {
661 .region_add = xen_io_add,
662 .region_del = xen_io_del,
663 .priority = 10,
666 static DeviceListener xen_device_listener = {
667 .realize = xen_device_realize,
668 .unrealize = xen_device_unrealize,
671 /* get the ioreq packets from share mem */
672 static ioreq_t *cpu_get_ioreq_from_shared_memory(XenIOState *state, int vcpu)
674 ioreq_t *req = xen_vcpu_ioreq(state->shared_page, vcpu);
676 if (req->state != STATE_IOREQ_READY) {
677 DPRINTF("I/O request not ready: "
678 "%x, ptr: %x, port: %"PRIx64", "
679 "data: %"PRIx64", count: %u, size: %u\n",
680 req->state, req->data_is_ptr, req->addr,
681 req->data, req->count, req->size);
682 return NULL;
685 xen_rmb(); /* see IOREQ_READY /then/ read contents of ioreq */
687 req->state = STATE_IOREQ_INPROCESS;
688 return req;
691 /* use poll to get the port notification */
692 /* ioreq_vec--out,the */
693 /* retval--the number of ioreq packet */
694 static ioreq_t *cpu_get_ioreq(XenIOState *state)
696 int i;
697 evtchn_port_t port;
699 port = xenevtchn_pending(state->xce_handle);
700 if (port == state->bufioreq_local_port) {
701 timer_mod(state->buffered_io_timer,
702 BUFFER_IO_MAX_DELAY + qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
703 return NULL;
706 if (port != -1) {
707 for (i = 0; i < max_cpus; i++) {
708 if (state->ioreq_local_port[i] == port) {
709 break;
713 if (i == max_cpus) {
714 hw_error("Fatal error while trying to get io event!\n");
717 /* unmask the wanted port again */
718 xenevtchn_unmask(state->xce_handle, port);
720 /* get the io packet from shared memory */
721 state->send_vcpu = i;
722 return cpu_get_ioreq_from_shared_memory(state, i);
725 /* read error or read nothing */
726 return NULL;
729 static uint32_t do_inp(uint32_t addr, unsigned long size)
731 switch (size) {
732 case 1:
733 return cpu_inb(addr);
734 case 2:
735 return cpu_inw(addr);
736 case 4:
737 return cpu_inl(addr);
738 default:
739 hw_error("inp: bad size: %04x %lx", addr, size);
743 static void do_outp(uint32_t addr,
744 unsigned long size, uint32_t val)
746 switch (size) {
747 case 1:
748 return cpu_outb(addr, val);
749 case 2:
750 return cpu_outw(addr, val);
751 case 4:
752 return cpu_outl(addr, val);
753 default:
754 hw_error("outp: bad size: %04x %lx", addr, size);
759 * Helper functions which read/write an object from/to physical guest
760 * memory, as part of the implementation of an ioreq.
762 * Equivalent to
763 * cpu_physical_memory_rw(addr + (req->df ? -1 : +1) * req->size * i,
764 * val, req->size, 0/1)
765 * except without the integer overflow problems.
767 static void rw_phys_req_item(hwaddr addr,
768 ioreq_t *req, uint32_t i, void *val, int rw)
770 /* Do everything unsigned so overflow just results in a truncated result
771 * and accesses to undesired parts of guest memory, which is up
772 * to the guest */
773 hwaddr offset = (hwaddr)req->size * i;
774 if (req->df) {
775 addr -= offset;
776 } else {
777 addr += offset;
779 cpu_physical_memory_rw(addr, val, req->size, rw);
782 static inline void read_phys_req_item(hwaddr addr,
783 ioreq_t *req, uint32_t i, void *val)
785 rw_phys_req_item(addr, req, i, val, 0);
787 static inline void write_phys_req_item(hwaddr addr,
788 ioreq_t *req, uint32_t i, void *val)
790 rw_phys_req_item(addr, req, i, val, 1);
794 static void cpu_ioreq_pio(ioreq_t *req)
796 uint32_t i;
798 trace_cpu_ioreq_pio(req, req->dir, req->df, req->data_is_ptr, req->addr,
799 req->data, req->count, req->size);
801 if (req->dir == IOREQ_READ) {
802 if (!req->data_is_ptr) {
803 req->data = do_inp(req->addr, req->size);
804 trace_cpu_ioreq_pio_read_reg(req, req->data, req->addr,
805 req->size);
806 } else {
807 uint32_t tmp;
809 for (i = 0; i < req->count; i++) {
810 tmp = do_inp(req->addr, req->size);
811 write_phys_req_item(req->data, req, i, &tmp);
814 } else if (req->dir == IOREQ_WRITE) {
815 if (!req->data_is_ptr) {
816 trace_cpu_ioreq_pio_write_reg(req, req->data, req->addr,
817 req->size);
818 do_outp(req->addr, req->size, req->data);
819 } else {
820 for (i = 0; i < req->count; i++) {
821 uint32_t tmp = 0;
823 read_phys_req_item(req->data, req, i, &tmp);
824 do_outp(req->addr, req->size, tmp);
830 static void cpu_ioreq_move(ioreq_t *req)
832 uint32_t i;
834 trace_cpu_ioreq_move(req, req->dir, req->df, req->data_is_ptr, req->addr,
835 req->data, req->count, req->size);
837 if (!req->data_is_ptr) {
838 if (req->dir == IOREQ_READ) {
839 for (i = 0; i < req->count; i++) {
840 read_phys_req_item(req->addr, req, i, &req->data);
842 } else if (req->dir == IOREQ_WRITE) {
843 for (i = 0; i < req->count; i++) {
844 write_phys_req_item(req->addr, req, i, &req->data);
847 } else {
848 uint64_t tmp;
850 if (req->dir == IOREQ_READ) {
851 for (i = 0; i < req->count; i++) {
852 read_phys_req_item(req->addr, req, i, &tmp);
853 write_phys_req_item(req->data, req, i, &tmp);
855 } else if (req->dir == IOREQ_WRITE) {
856 for (i = 0; i < req->count; i++) {
857 read_phys_req_item(req->data, req, i, &tmp);
858 write_phys_req_item(req->addr, req, i, &tmp);
864 static void regs_to_cpu(vmware_regs_t *vmport_regs, ioreq_t *req)
866 X86CPU *cpu;
867 CPUX86State *env;
869 cpu = X86_CPU(current_cpu);
870 env = &cpu->env;
871 env->regs[R_EAX] = req->data;
872 env->regs[R_EBX] = vmport_regs->ebx;
873 env->regs[R_ECX] = vmport_regs->ecx;
874 env->regs[R_EDX] = vmport_regs->edx;
875 env->regs[R_ESI] = vmport_regs->esi;
876 env->regs[R_EDI] = vmport_regs->edi;
879 static void regs_from_cpu(vmware_regs_t *vmport_regs)
881 X86CPU *cpu = X86_CPU(current_cpu);
882 CPUX86State *env = &cpu->env;
884 vmport_regs->ebx = env->regs[R_EBX];
885 vmport_regs->ecx = env->regs[R_ECX];
886 vmport_regs->edx = env->regs[R_EDX];
887 vmport_regs->esi = env->regs[R_ESI];
888 vmport_regs->edi = env->regs[R_EDI];
891 static void handle_vmport_ioreq(XenIOState *state, ioreq_t *req)
893 vmware_regs_t *vmport_regs;
895 assert(state->shared_vmport_page);
896 vmport_regs =
897 &state->shared_vmport_page->vcpu_vmport_regs[state->send_vcpu];
898 QEMU_BUILD_BUG_ON(sizeof(*req) < sizeof(*vmport_regs));
900 current_cpu = state->cpu_by_vcpu_id[state->send_vcpu];
901 regs_to_cpu(vmport_regs, req);
902 cpu_ioreq_pio(req);
903 regs_from_cpu(vmport_regs);
904 current_cpu = NULL;
907 static void handle_ioreq(XenIOState *state, ioreq_t *req)
909 trace_handle_ioreq(req, req->type, req->dir, req->df, req->data_is_ptr,
910 req->addr, req->data, req->count, req->size);
912 if (!req->data_is_ptr && (req->dir == IOREQ_WRITE) &&
913 (req->size < sizeof (target_ulong))) {
914 req->data &= ((target_ulong) 1 << (8 * req->size)) - 1;
917 if (req->dir == IOREQ_WRITE)
918 trace_handle_ioreq_write(req, req->type, req->df, req->data_is_ptr,
919 req->addr, req->data, req->count, req->size);
921 switch (req->type) {
922 case IOREQ_TYPE_PIO:
923 cpu_ioreq_pio(req);
924 break;
925 case IOREQ_TYPE_COPY:
926 cpu_ioreq_move(req);
927 break;
928 case IOREQ_TYPE_VMWARE_PORT:
929 handle_vmport_ioreq(state, req);
930 break;
931 case IOREQ_TYPE_TIMEOFFSET:
932 break;
933 case IOREQ_TYPE_INVALIDATE:
934 xen_invalidate_map_cache();
935 break;
936 case IOREQ_TYPE_PCI_CONFIG: {
937 uint32_t sbdf = req->addr >> 32;
938 uint32_t val;
940 /* Fake a write to port 0xCF8 so that
941 * the config space access will target the
942 * correct device model.
944 val = (1u << 31) |
945 ((req->addr & 0x0f00) << 16) |
946 ((sbdf & 0xffff) << 8) |
947 (req->addr & 0xfc);
948 do_outp(0xcf8, 4, val);
950 /* Now issue the config space access via
951 * port 0xCFC
953 req->addr = 0xcfc | (req->addr & 0x03);
954 cpu_ioreq_pio(req);
955 break;
957 default:
958 hw_error("Invalid ioreq type 0x%x\n", req->type);
960 if (req->dir == IOREQ_READ) {
961 trace_handle_ioreq_read(req, req->type, req->df, req->data_is_ptr,
962 req->addr, req->data, req->count, req->size);
966 static int handle_buffered_iopage(XenIOState *state)
968 buffered_iopage_t *buf_page = state->buffered_io_page;
969 buf_ioreq_t *buf_req = NULL;
970 ioreq_t req;
971 int qw;
973 if (!buf_page) {
974 return 0;
977 memset(&req, 0x00, sizeof(req));
979 for (;;) {
980 uint32_t rdptr = buf_page->read_pointer, wrptr;
982 xen_rmb();
983 wrptr = buf_page->write_pointer;
984 xen_rmb();
985 if (rdptr != buf_page->read_pointer) {
986 continue;
988 if (rdptr == wrptr) {
989 break;
991 buf_req = &buf_page->buf_ioreq[rdptr % IOREQ_BUFFER_SLOT_NUM];
992 req.size = 1UL << buf_req->size;
993 req.count = 1;
994 req.addr = buf_req->addr;
995 req.data = buf_req->data;
996 req.state = STATE_IOREQ_READY;
997 req.dir = buf_req->dir;
998 req.df = 1;
999 req.type = buf_req->type;
1000 req.data_is_ptr = 0;
1001 qw = (req.size == 8);
1002 if (qw) {
1003 buf_req = &buf_page->buf_ioreq[(rdptr + 1) %
1004 IOREQ_BUFFER_SLOT_NUM];
1005 req.data |= ((uint64_t)buf_req->data) << 32;
1008 handle_ioreq(state, &req);
1010 atomic_add(&buf_page->read_pointer, qw + 1);
1013 return req.count;
1016 static void handle_buffered_io(void *opaque)
1018 XenIOState *state = opaque;
1020 if (handle_buffered_iopage(state)) {
1021 timer_mod(state->buffered_io_timer,
1022 BUFFER_IO_MAX_DELAY + qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
1023 } else {
1024 timer_del(state->buffered_io_timer);
1025 xenevtchn_unmask(state->xce_handle, state->bufioreq_local_port);
1029 static void cpu_handle_ioreq(void *opaque)
1031 XenIOState *state = opaque;
1032 ioreq_t *req = cpu_get_ioreq(state);
1034 handle_buffered_iopage(state);
1035 if (req) {
1036 handle_ioreq(state, req);
1038 if (req->state != STATE_IOREQ_INPROCESS) {
1039 fprintf(stderr, "Badness in I/O request ... not in service?!: "
1040 "%x, ptr: %x, port: %"PRIx64", "
1041 "data: %"PRIx64", count: %u, size: %u, type: %u\n",
1042 req->state, req->data_is_ptr, req->addr,
1043 req->data, req->count, req->size, req->type);
1044 destroy_hvm_domain(false);
1045 return;
1048 xen_wmb(); /* Update ioreq contents /then/ update state. */
1051 * We do this before we send the response so that the tools
1052 * have the opportunity to pick up on the reset before the
1053 * guest resumes and does a hlt with interrupts disabled which
1054 * causes Xen to powerdown the domain.
1056 if (runstate_is_running()) {
1057 if (qemu_shutdown_requested_get()) {
1058 destroy_hvm_domain(false);
1060 if (qemu_reset_requested_get()) {
1061 qemu_system_reset(VMRESET_REPORT);
1062 destroy_hvm_domain(true);
1066 req->state = STATE_IORESP_READY;
1067 xenevtchn_notify(state->xce_handle,
1068 state->ioreq_local_port[state->send_vcpu]);
1072 static void xen_main_loop_prepare(XenIOState *state)
1074 int evtchn_fd = -1;
1076 if (state->xce_handle != NULL) {
1077 evtchn_fd = xenevtchn_fd(state->xce_handle);
1080 state->buffered_io_timer = timer_new_ms(QEMU_CLOCK_REALTIME, handle_buffered_io,
1081 state);
1083 if (evtchn_fd != -1) {
1084 CPUState *cpu_state;
1086 DPRINTF("%s: Init cpu_by_vcpu_id\n", __func__);
1087 CPU_FOREACH(cpu_state) {
1088 DPRINTF("%s: cpu_by_vcpu_id[%d]=%p\n",
1089 __func__, cpu_state->cpu_index, cpu_state);
1090 state->cpu_by_vcpu_id[cpu_state->cpu_index] = cpu_state;
1092 qemu_set_fd_handler(evtchn_fd, cpu_handle_ioreq, NULL, state);
1097 static void xen_hvm_change_state_handler(void *opaque, int running,
1098 RunState rstate)
1100 XenIOState *state = opaque;
1102 if (running) {
1103 xen_main_loop_prepare(state);
1106 xen_set_ioreq_server_state(xen_xc, xen_domid,
1107 state->ioservid,
1108 (rstate == RUN_STATE_RUNNING));
1111 static void xen_exit_notifier(Notifier *n, void *data)
1113 XenIOState *state = container_of(n, XenIOState, exit);
1115 xenevtchn_close(state->xce_handle);
1116 xs_daemon_close(state->xenstore);
1119 static void xen_read_physmap(XenIOState *state)
1121 XenPhysmap *physmap = NULL;
1122 unsigned int len, num, i;
1123 char path[80], *value = NULL;
1124 char **entries = NULL;
1126 snprintf(path, sizeof(path),
1127 "/local/domain/0/device-model/%d/physmap", xen_domid);
1128 entries = xs_directory(state->xenstore, 0, path, &num);
1129 if (entries == NULL)
1130 return;
1132 for (i = 0; i < num; i++) {
1133 physmap = g_malloc(sizeof (XenPhysmap));
1134 physmap->phys_offset = strtoull(entries[i], NULL, 16);
1135 snprintf(path, sizeof(path),
1136 "/local/domain/0/device-model/%d/physmap/%s/start_addr",
1137 xen_domid, entries[i]);
1138 value = xs_read(state->xenstore, 0, path, &len);
1139 if (value == NULL) {
1140 g_free(physmap);
1141 continue;
1143 physmap->start_addr = strtoull(value, NULL, 16);
1144 free(value);
1146 snprintf(path, sizeof(path),
1147 "/local/domain/0/device-model/%d/physmap/%s/size",
1148 xen_domid, entries[i]);
1149 value = xs_read(state->xenstore, 0, path, &len);
1150 if (value == NULL) {
1151 g_free(physmap);
1152 continue;
1154 physmap->size = strtoull(value, NULL, 16);
1155 free(value);
1157 snprintf(path, sizeof(path),
1158 "/local/domain/0/device-model/%d/physmap/%s/name",
1159 xen_domid, entries[i]);
1160 physmap->name = xs_read(state->xenstore, 0, path, &len);
1162 QLIST_INSERT_HEAD(&state->physmap, physmap, list);
1164 free(entries);
1167 static void xen_wakeup_notifier(Notifier *notifier, void *data)
1169 xc_set_hvm_param(xen_xc, xen_domid, HVM_PARAM_ACPI_S_STATE, 0);
1172 void xen_hvm_init(PCMachineState *pcms, MemoryRegion **ram_memory)
1174 int i, rc;
1175 xen_pfn_t ioreq_pfn;
1176 xen_pfn_t bufioreq_pfn;
1177 evtchn_port_t bufioreq_evtchn;
1178 XenIOState *state;
1180 state = g_malloc0(sizeof (XenIOState));
1182 state->xce_handle = xenevtchn_open(NULL, 0);
1183 if (state->xce_handle == NULL) {
1184 perror("xen: event channel open");
1185 goto err;
1188 state->xenstore = xs_daemon_open();
1189 if (state->xenstore == NULL) {
1190 perror("xen: xenstore open");
1191 goto err;
1194 rc = xen_create_ioreq_server(xen_xc, xen_domid, &state->ioservid);
1195 if (rc < 0) {
1196 perror("xen: ioreq server create");
1197 goto err;
1200 state->exit.notify = xen_exit_notifier;
1201 qemu_add_exit_notifier(&state->exit);
1203 state->suspend.notify = xen_suspend_notifier;
1204 qemu_register_suspend_notifier(&state->suspend);
1206 state->wakeup.notify = xen_wakeup_notifier;
1207 qemu_register_wakeup_notifier(&state->wakeup);
1209 rc = xen_get_ioreq_server_info(xen_xc, xen_domid, state->ioservid,
1210 &ioreq_pfn, &bufioreq_pfn,
1211 &bufioreq_evtchn);
1212 if (rc < 0) {
1213 error_report("failed to get ioreq server info: error %d handle=%p",
1214 errno, xen_xc);
1215 goto err;
1218 DPRINTF("shared page at pfn %lx\n", ioreq_pfn);
1219 DPRINTF("buffered io page at pfn %lx\n", bufioreq_pfn);
1220 DPRINTF("buffered io evtchn is %x\n", bufioreq_evtchn);
1222 state->shared_page = xenforeignmemory_map(xen_fmem, xen_domid,
1223 PROT_READ|PROT_WRITE,
1224 1, &ioreq_pfn, NULL);
1225 if (state->shared_page == NULL) {
1226 error_report("map shared IO page returned error %d handle=%p",
1227 errno, xen_xc);
1228 goto err;
1231 rc = xen_get_vmport_regs_pfn(xen_xc, xen_domid, &ioreq_pfn);
1232 if (!rc) {
1233 DPRINTF("shared vmport page at pfn %lx\n", ioreq_pfn);
1234 state->shared_vmport_page =
1235 xenforeignmemory_map(xen_fmem, xen_domid, PROT_READ|PROT_WRITE,
1236 1, &ioreq_pfn, NULL);
1237 if (state->shared_vmport_page == NULL) {
1238 error_report("map shared vmport IO page returned error %d handle=%p",
1239 errno, xen_xc);
1240 goto err;
1242 } else if (rc != -ENOSYS) {
1243 error_report("get vmport regs pfn returned error %d, rc=%d",
1244 errno, rc);
1245 goto err;
1248 state->buffered_io_page = xenforeignmemory_map(xen_fmem, xen_domid,
1249 PROT_READ|PROT_WRITE,
1250 1, &bufioreq_pfn, NULL);
1251 if (state->buffered_io_page == NULL) {
1252 error_report("map buffered IO page returned error %d", errno);
1253 goto err;
1256 /* Note: cpus is empty at this point in init */
1257 state->cpu_by_vcpu_id = g_malloc0(max_cpus * sizeof(CPUState *));
1259 rc = xen_set_ioreq_server_state(xen_xc, xen_domid, state->ioservid, true);
1260 if (rc < 0) {
1261 error_report("failed to enable ioreq server info: error %d handle=%p",
1262 errno, xen_xc);
1263 goto err;
1266 state->ioreq_local_port = g_malloc0(max_cpus * sizeof (evtchn_port_t));
1268 /* FIXME: how about if we overflow the page here? */
1269 for (i = 0; i < max_cpus; i++) {
1270 rc = xenevtchn_bind_interdomain(state->xce_handle, xen_domid,
1271 xen_vcpu_eport(state->shared_page, i));
1272 if (rc == -1) {
1273 error_report("shared evtchn %d bind error %d", i, errno);
1274 goto err;
1276 state->ioreq_local_port[i] = rc;
1279 rc = xenevtchn_bind_interdomain(state->xce_handle, xen_domid,
1280 bufioreq_evtchn);
1281 if (rc == -1) {
1282 error_report("buffered evtchn bind error %d", errno);
1283 goto err;
1285 state->bufioreq_local_port = rc;
1287 /* Init RAM management */
1288 xen_map_cache_init(xen_phys_offset_to_gaddr, state);
1289 xen_ram_init(pcms, ram_size, ram_memory);
1291 qemu_add_vm_change_state_handler(xen_hvm_change_state_handler, state);
1293 state->memory_listener = xen_memory_listener;
1294 QLIST_INIT(&state->physmap);
1295 memory_listener_register(&state->memory_listener, &address_space_memory);
1296 state->log_for_dirtybit = NULL;
1298 state->io_listener = xen_io_listener;
1299 memory_listener_register(&state->io_listener, &address_space_io);
1301 state->device_listener = xen_device_listener;
1302 device_listener_register(&state->device_listener);
1304 /* Initialize backend core & drivers */
1305 if (xen_be_init() != 0) {
1306 error_report("xen backend core setup failed");
1307 goto err;
1309 xen_be_register("console", &xen_console_ops);
1310 xen_be_register("vkbd", &xen_kbdmouse_ops);
1311 xen_be_register("qdisk", &xen_blkdev_ops);
1312 xen_read_physmap(state);
1313 return;
1315 err:
1316 error_report("xen hardware virtual machine initialisation failed");
1317 exit(1);
1320 void destroy_hvm_domain(bool reboot)
1322 xc_interface *xc_handle;
1323 int sts;
1325 xc_handle = xc_interface_open(0, 0, 0);
1326 if (xc_handle == NULL) {
1327 fprintf(stderr, "Cannot acquire xenctrl handle\n");
1328 } else {
1329 sts = xc_domain_shutdown(xc_handle, xen_domid,
1330 reboot ? SHUTDOWN_reboot : SHUTDOWN_poweroff);
1331 if (sts != 0) {
1332 fprintf(stderr, "xc_domain_shutdown failed to issue %s, "
1333 "sts %d, %s\n", reboot ? "reboot" : "poweroff",
1334 sts, strerror(errno));
1335 } else {
1336 fprintf(stderr, "Issued domain %d %s\n", xen_domid,
1337 reboot ? "reboot" : "poweroff");
1339 xc_interface_close(xc_handle);
1343 void xen_register_framebuffer(MemoryRegion *mr)
1345 framebuffer = mr;
1348 void xen_shutdown_fatal_error(const char *fmt, ...)
1350 va_list ap;
1352 va_start(ap, fmt);
1353 vfprintf(stderr, fmt, ap);
1354 va_end(ap);
1355 fprintf(stderr, "Will destroy the domain.\n");
1356 /* destroy the domain */
1357 qemu_system_shutdown_request();
1360 void xen_modified_memory(ram_addr_t start, ram_addr_t length)
1362 if (unlikely(xen_in_migration)) {
1363 int rc;
1364 ram_addr_t start_pfn, nb_pages;
1366 if (length == 0) {
1367 length = TARGET_PAGE_SIZE;
1369 start_pfn = start >> TARGET_PAGE_BITS;
1370 nb_pages = ((start + length + TARGET_PAGE_SIZE - 1) >> TARGET_PAGE_BITS)
1371 - start_pfn;
1372 rc = xc_hvm_modified_memory(xen_xc, xen_domid, start_pfn, nb_pages);
1373 if (rc) {
1374 fprintf(stderr,
1375 "%s failed for "RAM_ADDR_FMT" ("RAM_ADDR_FMT"): %i, %s\n",
1376 __func__, start, nb_pages, rc, strerror(-rc));
1381 void qmp_xen_set_global_dirty_log(bool enable, Error **errp)
1383 if (enable) {
1384 memory_global_dirty_log_start();
1385 } else {
1386 memory_global_dirty_log_stop();