xref: /openbmc/qemu/hw/i386/xen/xen-hvm.c (revision 4b9fa0b4)
1 /*
2  * Copyright (C) 2010       Citrix Ltd.
3  *
4  * This work is licensed under the terms of the GNU GPL, version 2.  See
5  * the COPYING file in the top-level directory.
6  *
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  */
10 
11 #include "qemu/osdep.h"
12 
13 #include "cpu.h"
14 #include "hw/pci/pci.h"
15 #include "hw/pci/pci_host.h"
16 #include "hw/i386/pc.h"
17 #include "hw/irq.h"
18 #include "hw/hw.h"
19 #include "hw/i386/apic-msidef.h"
20 #include "hw/xen/xen_common.h"
21 #include "hw/xen/xen-legacy-backend.h"
22 #include "hw/xen/xen-bus.h"
23 #include "qapi/error.h"
24 #include "qapi/qapi-commands-misc.h"
25 #include "qemu/error-report.h"
26 #include "qemu/main-loop.h"
27 #include "qemu/range.h"
28 #include "sysemu/runstate.h"
29 #include "sysemu/sysemu.h"
30 #include "sysemu/xen-mapcache.h"
31 #include "trace.h"
32 #include "exec/address-spaces.h"
33 
34 #include <xen/hvm/ioreq.h>
35 #include <xen/hvm/e820.h>
36 
37 //#define DEBUG_XEN_HVM
38 
39 #ifdef DEBUG_XEN_HVM
40 #define DPRINTF(fmt, ...) \
41     do { fprintf(stderr, "xen: " fmt, ## __VA_ARGS__); } while (0)
42 #else
43 #define DPRINTF(fmt, ...) \
44     do { } while (0)
45 #endif
46 
47 static MemoryRegion ram_memory, ram_640k, ram_lo, ram_hi;
48 static MemoryRegion *framebuffer;
49 static bool xen_in_migration;
50 
51 /* Compatibility with older version */
52 
53 /* This allows QEMU to build on a system that has Xen 4.5 or earlier
54  * installed.  This here (not in hw/xen/xen_common.h) because xen/hvm/ioreq.h
55  * needs to be included before this block and hw/xen/xen_common.h needs to
56  * be included before xen/hvm/ioreq.h
57  */
58 #ifndef IOREQ_TYPE_VMWARE_PORT
59 #define IOREQ_TYPE_VMWARE_PORT  3
60 struct vmware_regs {
61     uint32_t esi;
62     uint32_t edi;
63     uint32_t ebx;
64     uint32_t ecx;
65     uint32_t edx;
66 };
67 typedef struct vmware_regs vmware_regs_t;
68 
69 struct shared_vmport_iopage {
70     struct vmware_regs vcpu_vmport_regs[1];
71 };
72 typedef struct shared_vmport_iopage shared_vmport_iopage_t;
73 #endif
74 
75 static inline uint32_t xen_vcpu_eport(shared_iopage_t *shared_page, int i)
76 {
77     return shared_page->vcpu_ioreq[i].vp_eport;
78 }
79 static inline ioreq_t *xen_vcpu_ioreq(shared_iopage_t *shared_page, int vcpu)
80 {
81     return &shared_page->vcpu_ioreq[vcpu];
82 }
83 
84 #define BUFFER_IO_MAX_DELAY  100
85 
86 typedef struct XenPhysmap {
87     hwaddr start_addr;
88     ram_addr_t size;
89     const char *name;
90     hwaddr phys_offset;
91 
92     QLIST_ENTRY(XenPhysmap) list;
93 } XenPhysmap;
94 
95 static QLIST_HEAD(, XenPhysmap) xen_physmap;
96 
97 typedef struct XenPciDevice {
98     PCIDevice *pci_dev;
99     uint32_t sbdf;
100     QLIST_ENTRY(XenPciDevice) entry;
101 } XenPciDevice;
102 
103 typedef struct XenIOState {
104     ioservid_t ioservid;
105     shared_iopage_t *shared_page;
106     shared_vmport_iopage_t *shared_vmport_page;
107     buffered_iopage_t *buffered_io_page;
108     QEMUTimer *buffered_io_timer;
109     CPUState **cpu_by_vcpu_id;
110     /* the evtchn port for polling the notification, */
111     evtchn_port_t *ioreq_local_port;
112     /* evtchn remote and local ports for buffered io */
113     evtchn_port_t bufioreq_remote_port;
114     evtchn_port_t bufioreq_local_port;
115     /* the evtchn fd for polling */
116     xenevtchn_handle *xce_handle;
117     /* which vcpu we are serving */
118     int send_vcpu;
119 
120     struct xs_handle *xenstore;
121     MemoryListener memory_listener;
122     MemoryListener io_listener;
123     QLIST_HEAD(, XenPciDevice) dev_list;
124     DeviceListener device_listener;
125     hwaddr free_phys_offset;
126     const XenPhysmap *log_for_dirtybit;
127     /* Buffer used by xen_sync_dirty_bitmap */
128     unsigned long *dirty_bitmap;
129 
130     Notifier exit;
131     Notifier suspend;
132     Notifier wakeup;
133 } XenIOState;
134 
135 /* Xen specific function for piix pci */
136 
137 int xen_pci_slot_get_pirq(PCIDevice *pci_dev, int irq_num)
138 {
139     return irq_num + ((pci_dev->devfn >> 3) << 2);
140 }
141 
142 void xen_piix3_set_irq(void *opaque, int irq_num, int level)
143 {
144     xen_set_pci_intx_level(xen_domid, 0, 0, irq_num >> 2,
145                            irq_num & 3, level);
146 }
147 
148 void xen_piix_pci_write_config_client(uint32_t address, uint32_t val, int len)
149 {
150     int i;
151 
152     /* Scan for updates to PCI link routes (0x60-0x63). */
153     for (i = 0; i < len; i++) {
154         uint8_t v = (val >> (8 * i)) & 0xff;
155         if (v & 0x80) {
156             v = 0;
157         }
158         v &= 0xf;
159         if (((address + i) >= 0x60) && ((address + i) <= 0x63)) {
160             xen_set_pci_link_route(xen_domid, address + i - 0x60, v);
161         }
162     }
163 }
164 
165 int xen_is_pirq_msi(uint32_t msi_data)
166 {
167     /* If vector is 0, the msi is remapped into a pirq, passed as
168      * dest_id.
169      */
170     return ((msi_data & MSI_DATA_VECTOR_MASK) >> MSI_DATA_VECTOR_SHIFT) == 0;
171 }
172 
173 void xen_hvm_inject_msi(uint64_t addr, uint32_t data)
174 {
175     xen_inject_msi(xen_domid, addr, data);
176 }
177 
178 static void xen_suspend_notifier(Notifier *notifier, void *data)
179 {
180     xc_set_hvm_param(xen_xc, xen_domid, HVM_PARAM_ACPI_S_STATE, 3);
181 }
182 
183 /* Xen Interrupt Controller */
184 
185 static void xen_set_irq(void *opaque, int irq, int level)
186 {
187     xen_set_isa_irq_level(xen_domid, irq, level);
188 }
189 
190 qemu_irq *xen_interrupt_controller_init(void)
191 {
192     return qemu_allocate_irqs(xen_set_irq, NULL, 16);
193 }
194 
195 /* Memory Ops */
196 
197 static void xen_ram_init(PCMachineState *pcms,
198                          ram_addr_t ram_size, MemoryRegion **ram_memory_p)
199 {
200     X86MachineState *x86ms = X86_MACHINE(pcms);
201     MemoryRegion *sysmem = get_system_memory();
202     ram_addr_t block_len;
203     uint64_t user_lowmem =
204         object_property_get_uint(qdev_get_machine(),
205                                  X86_MACHINE_MAX_RAM_BELOW_4G,
206                                  &error_abort);
207 
208     /* Handle the machine opt max-ram-below-4g.  It is basically doing
209      * min(xen limit, user limit).
210      */
211     if (!user_lowmem) {
212         user_lowmem = HVM_BELOW_4G_RAM_END; /* default */
213     }
214     if (HVM_BELOW_4G_RAM_END <= user_lowmem) {
215         user_lowmem = HVM_BELOW_4G_RAM_END;
216     }
217 
218     if (ram_size >= user_lowmem) {
219         x86ms->above_4g_mem_size = ram_size - user_lowmem;
220         x86ms->below_4g_mem_size = user_lowmem;
221     } else {
222         x86ms->above_4g_mem_size = 0;
223         x86ms->below_4g_mem_size = ram_size;
224     }
225     if (!x86ms->above_4g_mem_size) {
226         block_len = ram_size;
227     } else {
228         /*
229          * Xen does not allocate the memory continuously, it keeps a
230          * hole of the size computed above or passed in.
231          */
232         block_len = (1ULL << 32) + x86ms->above_4g_mem_size;
233     }
234     memory_region_init_ram(&ram_memory, NULL, "xen.ram", block_len,
235                            &error_fatal);
236     *ram_memory_p = &ram_memory;
237 
238     memory_region_init_alias(&ram_640k, NULL, "xen.ram.640k",
239                              &ram_memory, 0, 0xa0000);
240     memory_region_add_subregion(sysmem, 0, &ram_640k);
241     /* Skip of the VGA IO memory space, it will be registered later by the VGA
242      * emulated device.
243      *
244      * The area between 0xc0000 and 0x100000 will be used by SeaBIOS to load
245      * the Options ROM, so it is registered here as RAM.
246      */
247     memory_region_init_alias(&ram_lo, NULL, "xen.ram.lo",
248                              &ram_memory, 0xc0000,
249                              x86ms->below_4g_mem_size - 0xc0000);
250     memory_region_add_subregion(sysmem, 0xc0000, &ram_lo);
251     if (x86ms->above_4g_mem_size > 0) {
252         memory_region_init_alias(&ram_hi, NULL, "xen.ram.hi",
253                                  &ram_memory, 0x100000000ULL,
254                                  x86ms->above_4g_mem_size);
255         memory_region_add_subregion(sysmem, 0x100000000ULL, &ram_hi);
256     }
257 }
258 
259 void xen_ram_alloc(ram_addr_t ram_addr, ram_addr_t size, MemoryRegion *mr,
260                    Error **errp)
261 {
262     unsigned long nr_pfn;
263     xen_pfn_t *pfn_list;
264     int i;
265 
266     if (runstate_check(RUN_STATE_INMIGRATE)) {
267         /* RAM already populated in Xen */
268         fprintf(stderr, "%s: do not alloc "RAM_ADDR_FMT
269                 " bytes of ram at "RAM_ADDR_FMT" when runstate is INMIGRATE\n",
270                 __func__, size, ram_addr);
271         return;
272     }
273 
274     if (mr == &ram_memory) {
275         return;
276     }
277 
278     trace_xen_ram_alloc(ram_addr, size);
279 
280     nr_pfn = size >> TARGET_PAGE_BITS;
281     pfn_list = g_malloc(sizeof (*pfn_list) * nr_pfn);
282 
283     for (i = 0; i < nr_pfn; i++) {
284         pfn_list[i] = (ram_addr >> TARGET_PAGE_BITS) + i;
285     }
286 
287     if (xc_domain_populate_physmap_exact(xen_xc, xen_domid, nr_pfn, 0, 0, pfn_list)) {
288         error_setg(errp, "xen: failed to populate ram at " RAM_ADDR_FMT,
289                    ram_addr);
290     }
291 
292     g_free(pfn_list);
293 }
294 
295 static XenPhysmap *get_physmapping(hwaddr start_addr, ram_addr_t size)
296 {
297     XenPhysmap *physmap = NULL;
298 
299     start_addr &= TARGET_PAGE_MASK;
300 
301     QLIST_FOREACH(physmap, &xen_physmap, list) {
302         if (range_covers_byte(physmap->start_addr, physmap->size, start_addr)) {
303             return physmap;
304         }
305     }
306     return NULL;
307 }
308 
309 static hwaddr xen_phys_offset_to_gaddr(hwaddr phys_offset, ram_addr_t size)
310 {
311     hwaddr addr = phys_offset & TARGET_PAGE_MASK;
312     XenPhysmap *physmap = NULL;
313 
314     QLIST_FOREACH(physmap, &xen_physmap, list) {
315         if (range_covers_byte(physmap->phys_offset, physmap->size, addr)) {
316             return physmap->start_addr + (phys_offset - physmap->phys_offset);
317         }
318     }
319 
320     return phys_offset;
321 }
322 
323 #ifdef XEN_COMPAT_PHYSMAP
324 static int xen_save_physmap(XenIOState *state, XenPhysmap *physmap)
325 {
326     char path[80], value[17];
327 
328     snprintf(path, sizeof(path),
329             "/local/domain/0/device-model/%d/physmap/%"PRIx64"/start_addr",
330             xen_domid, (uint64_t)physmap->phys_offset);
331     snprintf(value, sizeof(value), "%"PRIx64, (uint64_t)physmap->start_addr);
332     if (!xs_write(state->xenstore, 0, path, value, strlen(value))) {
333         return -1;
334     }
335     snprintf(path, sizeof(path),
336             "/local/domain/0/device-model/%d/physmap/%"PRIx64"/size",
337             xen_domid, (uint64_t)physmap->phys_offset);
338     snprintf(value, sizeof(value), "%"PRIx64, (uint64_t)physmap->size);
339     if (!xs_write(state->xenstore, 0, path, value, strlen(value))) {
340         return -1;
341     }
342     if (physmap->name) {
343         snprintf(path, sizeof(path),
344                 "/local/domain/0/device-model/%d/physmap/%"PRIx64"/name",
345                 xen_domid, (uint64_t)physmap->phys_offset);
346         if (!xs_write(state->xenstore, 0, path,
347                       physmap->name, strlen(physmap->name))) {
348             return -1;
349         }
350     }
351     return 0;
352 }
353 #else
354 static int xen_save_physmap(XenIOState *state, XenPhysmap *physmap)
355 {
356     return 0;
357 }
358 #endif
359 
360 static int xen_add_to_physmap(XenIOState *state,
361                               hwaddr start_addr,
362                               ram_addr_t size,
363                               MemoryRegion *mr,
364                               hwaddr offset_within_region)
365 {
366     unsigned long nr_pages;
367     int rc = 0;
368     XenPhysmap *physmap = NULL;
369     hwaddr pfn, start_gpfn;
370     hwaddr phys_offset = memory_region_get_ram_addr(mr);
371     const char *mr_name;
372 
373     if (get_physmapping(start_addr, size)) {
374         return 0;
375     }
376     if (size <= 0) {
377         return -1;
378     }
379 
380     /* Xen can only handle a single dirty log region for now and we want
381      * the linear framebuffer to be that region.
382      * Avoid tracking any regions that is not videoram and avoid tracking
383      * the legacy vga region. */
384     if (mr == framebuffer && start_addr > 0xbffff) {
385         goto go_physmap;
386     }
387     return -1;
388 
389 go_physmap:
390     DPRINTF("mapping vram to %"HWADDR_PRIx" - %"HWADDR_PRIx"\n",
391             start_addr, start_addr + size);
392 
393     mr_name = memory_region_name(mr);
394 
395     physmap = g_malloc(sizeof(XenPhysmap));
396 
397     physmap->start_addr = start_addr;
398     physmap->size = size;
399     physmap->name = mr_name;
400     physmap->phys_offset = phys_offset;
401 
402     QLIST_INSERT_HEAD(&xen_physmap, physmap, list);
403 
404     if (runstate_check(RUN_STATE_INMIGRATE)) {
405         /* Now when we have a physmap entry we can replace a dummy mapping with
406          * a real one of guest foreign memory. */
407         uint8_t *p = xen_replace_cache_entry(phys_offset, start_addr, size);
408         assert(p && p == memory_region_get_ram_ptr(mr));
409 
410         return 0;
411     }
412 
413     pfn = phys_offset >> TARGET_PAGE_BITS;
414     start_gpfn = start_addr >> TARGET_PAGE_BITS;
415     nr_pages = size >> TARGET_PAGE_BITS;
416     rc = xendevicemodel_relocate_memory(xen_dmod, xen_domid, nr_pages, pfn,
417                                         start_gpfn);
418     if (rc) {
419         int saved_errno = errno;
420 
421         error_report("relocate_memory %lu pages from GFN %"HWADDR_PRIx
422                      " to GFN %"HWADDR_PRIx" failed: %s",
423                      nr_pages, pfn, start_gpfn, strerror(saved_errno));
424         errno = saved_errno;
425         return -1;
426     }
427 
428     rc = xendevicemodel_pin_memory_cacheattr(xen_dmod, xen_domid,
429                                    start_addr >> TARGET_PAGE_BITS,
430                                    (start_addr + size - 1) >> TARGET_PAGE_BITS,
431                                    XEN_DOMCTL_MEM_CACHEATTR_WB);
432     if (rc) {
433         error_report("pin_memory_cacheattr failed: %s", strerror(errno));
434     }
435     return xen_save_physmap(state, physmap);
436 }
437 
438 static int xen_remove_from_physmap(XenIOState *state,
439                                    hwaddr start_addr,
440                                    ram_addr_t size)
441 {
442     int rc = 0;
443     XenPhysmap *physmap = NULL;
444     hwaddr phys_offset = 0;
445 
446     physmap = get_physmapping(start_addr, size);
447     if (physmap == NULL) {
448         return -1;
449     }
450 
451     phys_offset = physmap->phys_offset;
452     size = physmap->size;
453 
454     DPRINTF("unmapping vram to %"HWADDR_PRIx" - %"HWADDR_PRIx", at "
455             "%"HWADDR_PRIx"\n", start_addr, start_addr + size, phys_offset);
456 
457     size >>= TARGET_PAGE_BITS;
458     start_addr >>= TARGET_PAGE_BITS;
459     phys_offset >>= TARGET_PAGE_BITS;
460     rc = xendevicemodel_relocate_memory(xen_dmod, xen_domid, size, start_addr,
461                                         phys_offset);
462     if (rc) {
463         int saved_errno = errno;
464 
465         error_report("relocate_memory "RAM_ADDR_FMT" pages"
466                      " from GFN %"HWADDR_PRIx
467                      " to GFN %"HWADDR_PRIx" failed: %s",
468                      size, start_addr, phys_offset, strerror(saved_errno));
469         errno = saved_errno;
470         return -1;
471     }
472 
473     QLIST_REMOVE(physmap, list);
474     if (state->log_for_dirtybit == physmap) {
475         state->log_for_dirtybit = NULL;
476         g_free(state->dirty_bitmap);
477         state->dirty_bitmap = NULL;
478     }
479     g_free(physmap);
480 
481     return 0;
482 }
483 
484 static void xen_set_memory(struct MemoryListener *listener,
485                            MemoryRegionSection *section,
486                            bool add)
487 {
488     XenIOState *state = container_of(listener, XenIOState, memory_listener);
489     hwaddr start_addr = section->offset_within_address_space;
490     ram_addr_t size = int128_get64(section->size);
491     bool log_dirty = memory_region_is_logging(section->mr, DIRTY_MEMORY_VGA);
492     hvmmem_type_t mem_type;
493 
494     if (section->mr == &ram_memory) {
495         return;
496     } else {
497         if (add) {
498             xen_map_memory_section(xen_domid, state->ioservid,
499                                    section);
500         } else {
501             xen_unmap_memory_section(xen_domid, state->ioservid,
502                                      section);
503         }
504     }
505 
506     if (!memory_region_is_ram(section->mr)) {
507         return;
508     }
509 
510     if (log_dirty != add) {
511         return;
512     }
513 
514     trace_xen_client_set_memory(start_addr, size, log_dirty);
515 
516     start_addr &= TARGET_PAGE_MASK;
517     size = TARGET_PAGE_ALIGN(size);
518 
519     if (add) {
520         if (!memory_region_is_rom(section->mr)) {
521             xen_add_to_physmap(state, start_addr, size,
522                                section->mr, section->offset_within_region);
523         } else {
524             mem_type = HVMMEM_ram_ro;
525             if (xen_set_mem_type(xen_domid, mem_type,
526                                  start_addr >> TARGET_PAGE_BITS,
527                                  size >> TARGET_PAGE_BITS)) {
528                 DPRINTF("xen_set_mem_type error, addr: "TARGET_FMT_plx"\n",
529                         start_addr);
530             }
531         }
532     } else {
533         if (xen_remove_from_physmap(state, start_addr, size) < 0) {
534             DPRINTF("physmapping does not exist at "TARGET_FMT_plx"\n", start_addr);
535         }
536     }
537 }
538 
539 static void xen_region_add(MemoryListener *listener,
540                            MemoryRegionSection *section)
541 {
542     memory_region_ref(section->mr);
543     xen_set_memory(listener, section, true);
544 }
545 
546 static void xen_region_del(MemoryListener *listener,
547                            MemoryRegionSection *section)
548 {
549     xen_set_memory(listener, section, false);
550     memory_region_unref(section->mr);
551 }
552 
553 static void xen_io_add(MemoryListener *listener,
554                        MemoryRegionSection *section)
555 {
556     XenIOState *state = container_of(listener, XenIOState, io_listener);
557     MemoryRegion *mr = section->mr;
558 
559     if (mr->ops == &unassigned_io_ops) {
560         return;
561     }
562 
563     memory_region_ref(mr);
564 
565     xen_map_io_section(xen_domid, state->ioservid, section);
566 }
567 
568 static void xen_io_del(MemoryListener *listener,
569                        MemoryRegionSection *section)
570 {
571     XenIOState *state = container_of(listener, XenIOState, io_listener);
572     MemoryRegion *mr = section->mr;
573 
574     if (mr->ops == &unassigned_io_ops) {
575         return;
576     }
577 
578     xen_unmap_io_section(xen_domid, state->ioservid, section);
579 
580     memory_region_unref(mr);
581 }
582 
583 static void xen_device_realize(DeviceListener *listener,
584                                DeviceState *dev)
585 {
586     XenIOState *state = container_of(listener, XenIOState, device_listener);
587 
588     if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {
589         PCIDevice *pci_dev = PCI_DEVICE(dev);
590         XenPciDevice *xendev = g_new(XenPciDevice, 1);
591 
592         xendev->pci_dev = pci_dev;
593         xendev->sbdf = PCI_BUILD_BDF(pci_dev_bus_num(pci_dev),
594                                      pci_dev->devfn);
595         QLIST_INSERT_HEAD(&state->dev_list, xendev, entry);
596 
597         xen_map_pcidev(xen_domid, state->ioservid, pci_dev);
598     }
599 }
600 
601 static void xen_device_unrealize(DeviceListener *listener,
602                                  DeviceState *dev)
603 {
604     XenIOState *state = container_of(listener, XenIOState, device_listener);
605 
606     if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {
607         PCIDevice *pci_dev = PCI_DEVICE(dev);
608         XenPciDevice *xendev, *next;
609 
610         xen_unmap_pcidev(xen_domid, state->ioservid, pci_dev);
611 
612         QLIST_FOREACH_SAFE(xendev, &state->dev_list, entry, next) {
613             if (xendev->pci_dev == pci_dev) {
614                 QLIST_REMOVE(xendev, entry);
615                 g_free(xendev);
616                 break;
617             }
618         }
619     }
620 }
621 
622 static void xen_sync_dirty_bitmap(XenIOState *state,
623                                   hwaddr start_addr,
624                                   ram_addr_t size)
625 {
626     hwaddr npages = size >> TARGET_PAGE_BITS;
627     const int width = sizeof(unsigned long) * 8;
628     size_t bitmap_size = DIV_ROUND_UP(npages, width);
629     int rc, i, j;
630     const XenPhysmap *physmap = NULL;
631 
632     physmap = get_physmapping(start_addr, size);
633     if (physmap == NULL) {
634         /* not handled */
635         return;
636     }
637 
638     if (state->log_for_dirtybit == NULL) {
639         state->log_for_dirtybit = physmap;
640         state->dirty_bitmap = g_new(unsigned long, bitmap_size);
641     } else if (state->log_for_dirtybit != physmap) {
642         /* Only one range for dirty bitmap can be tracked. */
643         return;
644     }
645 
646     rc = xen_track_dirty_vram(xen_domid, start_addr >> TARGET_PAGE_BITS,
647                               npages, state->dirty_bitmap);
648     if (rc < 0) {
649 #ifndef ENODATA
650 #define ENODATA  ENOENT
651 #endif
652         if (errno == ENODATA) {
653             memory_region_set_dirty(framebuffer, 0, size);
654             DPRINTF("xen: track_dirty_vram failed (0x" TARGET_FMT_plx
655                     ", 0x" TARGET_FMT_plx "): %s\n",
656                     start_addr, start_addr + size, strerror(errno));
657         }
658         return;
659     }
660 
661     for (i = 0; i < bitmap_size; i++) {
662         unsigned long map = state->dirty_bitmap[i];
663         while (map != 0) {
664             j = ctzl(map);
665             map &= ~(1ul << j);
666             memory_region_set_dirty(framebuffer,
667                                     (i * width + j) * TARGET_PAGE_SIZE,
668                                     TARGET_PAGE_SIZE);
669         };
670     }
671 }
672 
673 static void xen_log_start(MemoryListener *listener,
674                           MemoryRegionSection *section,
675                           int old, int new)
676 {
677     XenIOState *state = container_of(listener, XenIOState, memory_listener);
678 
679     if (new & ~old & (1 << DIRTY_MEMORY_VGA)) {
680         xen_sync_dirty_bitmap(state, section->offset_within_address_space,
681                               int128_get64(section->size));
682     }
683 }
684 
685 static void xen_log_stop(MemoryListener *listener, MemoryRegionSection *section,
686                          int old, int new)
687 {
688     XenIOState *state = container_of(listener, XenIOState, memory_listener);
689 
690     if (old & ~new & (1 << DIRTY_MEMORY_VGA)) {
691         state->log_for_dirtybit = NULL;
692         g_free(state->dirty_bitmap);
693         state->dirty_bitmap = NULL;
694         /* Disable dirty bit tracking */
695         xen_track_dirty_vram(xen_domid, 0, 0, NULL);
696     }
697 }
698 
699 static void xen_log_sync(MemoryListener *listener, MemoryRegionSection *section)
700 {
701     XenIOState *state = container_of(listener, XenIOState, memory_listener);
702 
703     xen_sync_dirty_bitmap(state, section->offset_within_address_space,
704                           int128_get64(section->size));
705 }
706 
707 static void xen_log_global_start(MemoryListener *listener)
708 {
709     if (xen_enabled()) {
710         xen_in_migration = true;
711     }
712 }
713 
714 static void xen_log_global_stop(MemoryListener *listener)
715 {
716     xen_in_migration = false;
717 }
718 
719 static MemoryListener xen_memory_listener = {
720     .region_add = xen_region_add,
721     .region_del = xen_region_del,
722     .log_start = xen_log_start,
723     .log_stop = xen_log_stop,
724     .log_sync = xen_log_sync,
725     .log_global_start = xen_log_global_start,
726     .log_global_stop = xen_log_global_stop,
727     .priority = 10,
728 };
729 
730 static MemoryListener xen_io_listener = {
731     .region_add = xen_io_add,
732     .region_del = xen_io_del,
733     .priority = 10,
734 };
735 
736 static DeviceListener xen_device_listener = {
737     .realize = xen_device_realize,
738     .unrealize = xen_device_unrealize,
739 };
740 
741 /* get the ioreq packets from share mem */
742 static ioreq_t *cpu_get_ioreq_from_shared_memory(XenIOState *state, int vcpu)
743 {
744     ioreq_t *req = xen_vcpu_ioreq(state->shared_page, vcpu);
745 
746     if (req->state != STATE_IOREQ_READY) {
747         DPRINTF("I/O request not ready: "
748                 "%x, ptr: %x, port: %"PRIx64", "
749                 "data: %"PRIx64", count: %u, size: %u\n",
750                 req->state, req->data_is_ptr, req->addr,
751                 req->data, req->count, req->size);
752         return NULL;
753     }
754 
755     xen_rmb(); /* see IOREQ_READY /then/ read contents of ioreq */
756 
757     req->state = STATE_IOREQ_INPROCESS;
758     return req;
759 }
760 
761 /* use poll to get the port notification */
762 /* ioreq_vec--out,the */
763 /* retval--the number of ioreq packet */
764 static ioreq_t *cpu_get_ioreq(XenIOState *state)
765 {
766     MachineState *ms = MACHINE(qdev_get_machine());
767     unsigned int max_cpus = ms->smp.max_cpus;
768     int i;
769     evtchn_port_t port;
770 
771     port = xenevtchn_pending(state->xce_handle);
772     if (port == state->bufioreq_local_port) {
773         timer_mod(state->buffered_io_timer,
774                 BUFFER_IO_MAX_DELAY + qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
775         return NULL;
776     }
777 
778     if (port != -1) {
779         for (i = 0; i < max_cpus; i++) {
780             if (state->ioreq_local_port[i] == port) {
781                 break;
782             }
783         }
784 
785         if (i == max_cpus) {
786             hw_error("Fatal error while trying to get io event!\n");
787         }
788 
789         /* unmask the wanted port again */
790         xenevtchn_unmask(state->xce_handle, port);
791 
792         /* get the io packet from shared memory */
793         state->send_vcpu = i;
794         return cpu_get_ioreq_from_shared_memory(state, i);
795     }
796 
797     /* read error or read nothing */
798     return NULL;
799 }
800 
801 static uint32_t do_inp(uint32_t addr, unsigned long size)
802 {
803     switch (size) {
804         case 1:
805             return cpu_inb(addr);
806         case 2:
807             return cpu_inw(addr);
808         case 4:
809             return cpu_inl(addr);
810         default:
811             hw_error("inp: bad size: %04x %lx", addr, size);
812     }
813 }
814 
815 static void do_outp(uint32_t addr,
816         unsigned long size, uint32_t val)
817 {
818     switch (size) {
819         case 1:
820             return cpu_outb(addr, val);
821         case 2:
822             return cpu_outw(addr, val);
823         case 4:
824             return cpu_outl(addr, val);
825         default:
826             hw_error("outp: bad size: %04x %lx", addr, size);
827     }
828 }
829 
830 /*
831  * Helper functions which read/write an object from/to physical guest
832  * memory, as part of the implementation of an ioreq.
833  *
834  * Equivalent to
835  *   cpu_physical_memory_rw(addr + (req->df ? -1 : +1) * req->size * i,
836  *                          val, req->size, 0/1)
837  * except without the integer overflow problems.
838  */
839 static void rw_phys_req_item(hwaddr addr,
840                              ioreq_t *req, uint32_t i, void *val, int rw)
841 {
842     /* Do everything unsigned so overflow just results in a truncated result
843      * and accesses to undesired parts of guest memory, which is up
844      * to the guest */
845     hwaddr offset = (hwaddr)req->size * i;
846     if (req->df) {
847         addr -= offset;
848     } else {
849         addr += offset;
850     }
851     cpu_physical_memory_rw(addr, val, req->size, rw);
852 }
853 
854 static inline void read_phys_req_item(hwaddr addr,
855                                       ioreq_t *req, uint32_t i, void *val)
856 {
857     rw_phys_req_item(addr, req, i, val, 0);
858 }
859 static inline void write_phys_req_item(hwaddr addr,
860                                        ioreq_t *req, uint32_t i, void *val)
861 {
862     rw_phys_req_item(addr, req, i, val, 1);
863 }
864 
865 
866 static void cpu_ioreq_pio(ioreq_t *req)
867 {
868     uint32_t i;
869 
870     trace_cpu_ioreq_pio(req, req->dir, req->df, req->data_is_ptr, req->addr,
871                          req->data, req->count, req->size);
872 
873     if (req->size > sizeof(uint32_t)) {
874         hw_error("PIO: bad size (%u)", req->size);
875     }
876 
877     if (req->dir == IOREQ_READ) {
878         if (!req->data_is_ptr) {
879             req->data = do_inp(req->addr, req->size);
880             trace_cpu_ioreq_pio_read_reg(req, req->data, req->addr,
881                                          req->size);
882         } else {
883             uint32_t tmp;
884 
885             for (i = 0; i < req->count; i++) {
886                 tmp = do_inp(req->addr, req->size);
887                 write_phys_req_item(req->data, req, i, &tmp);
888             }
889         }
890     } else if (req->dir == IOREQ_WRITE) {
891         if (!req->data_is_ptr) {
892             trace_cpu_ioreq_pio_write_reg(req, req->data, req->addr,
893                                           req->size);
894             do_outp(req->addr, req->size, req->data);
895         } else {
896             for (i = 0; i < req->count; i++) {
897                 uint32_t tmp = 0;
898 
899                 read_phys_req_item(req->data, req, i, &tmp);
900                 do_outp(req->addr, req->size, tmp);
901             }
902         }
903     }
904 }
905 
906 static void cpu_ioreq_move(ioreq_t *req)
907 {
908     uint32_t i;
909 
910     trace_cpu_ioreq_move(req, req->dir, req->df, req->data_is_ptr, req->addr,
911                          req->data, req->count, req->size);
912 
913     if (req->size > sizeof(req->data)) {
914         hw_error("MMIO: bad size (%u)", req->size);
915     }
916 
917     if (!req->data_is_ptr) {
918         if (req->dir == IOREQ_READ) {
919             for (i = 0; i < req->count; i++) {
920                 read_phys_req_item(req->addr, req, i, &req->data);
921             }
922         } else if (req->dir == IOREQ_WRITE) {
923             for (i = 0; i < req->count; i++) {
924                 write_phys_req_item(req->addr, req, i, &req->data);
925             }
926         }
927     } else {
928         uint64_t tmp;
929 
930         if (req->dir == IOREQ_READ) {
931             for (i = 0; i < req->count; i++) {
932                 read_phys_req_item(req->addr, req, i, &tmp);
933                 write_phys_req_item(req->data, req, i, &tmp);
934             }
935         } else if (req->dir == IOREQ_WRITE) {
936             for (i = 0; i < req->count; i++) {
937                 read_phys_req_item(req->data, req, i, &tmp);
938                 write_phys_req_item(req->addr, req, i, &tmp);
939             }
940         }
941     }
942 }
943 
944 static void cpu_ioreq_config(XenIOState *state, ioreq_t *req)
945 {
946     uint32_t sbdf = req->addr >> 32;
947     uint32_t reg = req->addr;
948     XenPciDevice *xendev;
949 
950     if (req->size != sizeof(uint8_t) && req->size != sizeof(uint16_t) &&
951         req->size != sizeof(uint32_t)) {
952         hw_error("PCI config access: bad size (%u)", req->size);
953     }
954 
955     if (req->count != 1) {
956         hw_error("PCI config access: bad count (%u)", req->count);
957     }
958 
959     QLIST_FOREACH(xendev, &state->dev_list, entry) {
960         if (xendev->sbdf != sbdf) {
961             continue;
962         }
963 
964         if (!req->data_is_ptr) {
965             if (req->dir == IOREQ_READ) {
966                 req->data = pci_host_config_read_common(
967                     xendev->pci_dev, reg, PCI_CONFIG_SPACE_SIZE,
968                     req->size);
969                 trace_cpu_ioreq_config_read(req, xendev->sbdf, reg,
970                                             req->size, req->data);
971             } else if (req->dir == IOREQ_WRITE) {
972                 trace_cpu_ioreq_config_write(req, xendev->sbdf, reg,
973                                              req->size, req->data);
974                 pci_host_config_write_common(
975                     xendev->pci_dev, reg, PCI_CONFIG_SPACE_SIZE,
976                     req->data, req->size);
977             }
978         } else {
979             uint32_t tmp;
980 
981             if (req->dir == IOREQ_READ) {
982                 tmp = pci_host_config_read_common(
983                     xendev->pci_dev, reg, PCI_CONFIG_SPACE_SIZE,
984                     req->size);
985                 trace_cpu_ioreq_config_read(req, xendev->sbdf, reg,
986                                             req->size, tmp);
987                 write_phys_req_item(req->data, req, 0, &tmp);
988             } else if (req->dir == IOREQ_WRITE) {
989                 read_phys_req_item(req->data, req, 0, &tmp);
990                 trace_cpu_ioreq_config_write(req, xendev->sbdf, reg,
991                                              req->size, tmp);
992                 pci_host_config_write_common(
993                     xendev->pci_dev, reg, PCI_CONFIG_SPACE_SIZE,
994                     tmp, req->size);
995             }
996         }
997     }
998 }
999 
1000 static void regs_to_cpu(vmware_regs_t *vmport_regs, ioreq_t *req)
1001 {
1002     X86CPU *cpu;
1003     CPUX86State *env;
1004 
1005     cpu = X86_CPU(current_cpu);
1006     env = &cpu->env;
1007     env->regs[R_EAX] = req->data;
1008     env->regs[R_EBX] = vmport_regs->ebx;
1009     env->regs[R_ECX] = vmport_regs->ecx;
1010     env->regs[R_EDX] = vmport_regs->edx;
1011     env->regs[R_ESI] = vmport_regs->esi;
1012     env->regs[R_EDI] = vmport_regs->edi;
1013 }
1014 
1015 static void regs_from_cpu(vmware_regs_t *vmport_regs)
1016 {
1017     X86CPU *cpu = X86_CPU(current_cpu);
1018     CPUX86State *env = &cpu->env;
1019 
1020     vmport_regs->ebx = env->regs[R_EBX];
1021     vmport_regs->ecx = env->regs[R_ECX];
1022     vmport_regs->edx = env->regs[R_EDX];
1023     vmport_regs->esi = env->regs[R_ESI];
1024     vmport_regs->edi = env->regs[R_EDI];
1025 }
1026 
1027 static void handle_vmport_ioreq(XenIOState *state, ioreq_t *req)
1028 {
1029     vmware_regs_t *vmport_regs;
1030 
1031     assert(state->shared_vmport_page);
1032     vmport_regs =
1033         &state->shared_vmport_page->vcpu_vmport_regs[state->send_vcpu];
1034     QEMU_BUILD_BUG_ON(sizeof(*req) < sizeof(*vmport_regs));
1035 
1036     current_cpu = state->cpu_by_vcpu_id[state->send_vcpu];
1037     regs_to_cpu(vmport_regs, req);
1038     cpu_ioreq_pio(req);
1039     regs_from_cpu(vmport_regs);
1040     current_cpu = NULL;
1041 }
1042 
1043 static void handle_ioreq(XenIOState *state, ioreq_t *req)
1044 {
1045     trace_handle_ioreq(req, req->type, req->dir, req->df, req->data_is_ptr,
1046                        req->addr, req->data, req->count, req->size);
1047 
1048     if (!req->data_is_ptr && (req->dir == IOREQ_WRITE) &&
1049             (req->size < sizeof (target_ulong))) {
1050         req->data &= ((target_ulong) 1 << (8 * req->size)) - 1;
1051     }
1052 
1053     if (req->dir == IOREQ_WRITE)
1054         trace_handle_ioreq_write(req, req->type, req->df, req->data_is_ptr,
1055                                  req->addr, req->data, req->count, req->size);
1056 
1057     switch (req->type) {
1058         case IOREQ_TYPE_PIO:
1059             cpu_ioreq_pio(req);
1060             break;
1061         case IOREQ_TYPE_COPY:
1062             cpu_ioreq_move(req);
1063             break;
1064         case IOREQ_TYPE_VMWARE_PORT:
1065             handle_vmport_ioreq(state, req);
1066             break;
1067         case IOREQ_TYPE_TIMEOFFSET:
1068             break;
1069         case IOREQ_TYPE_INVALIDATE:
1070             xen_invalidate_map_cache();
1071             break;
1072         case IOREQ_TYPE_PCI_CONFIG:
1073             cpu_ioreq_config(state, req);
1074             break;
1075         default:
1076             hw_error("Invalid ioreq type 0x%x\n", req->type);
1077     }
1078     if (req->dir == IOREQ_READ) {
1079         trace_handle_ioreq_read(req, req->type, req->df, req->data_is_ptr,
1080                                 req->addr, req->data, req->count, req->size);
1081     }
1082 }
1083 
1084 static int handle_buffered_iopage(XenIOState *state)
1085 {
1086     buffered_iopage_t *buf_page = state->buffered_io_page;
1087     buf_ioreq_t *buf_req = NULL;
1088     ioreq_t req;
1089     int qw;
1090 
1091     if (!buf_page) {
1092         return 0;
1093     }
1094 
1095     memset(&req, 0x00, sizeof(req));
1096     req.state = STATE_IOREQ_READY;
1097     req.count = 1;
1098     req.dir = IOREQ_WRITE;
1099 
1100     for (;;) {
1101         uint32_t rdptr = buf_page->read_pointer, wrptr;
1102 
1103         xen_rmb();
1104         wrptr = buf_page->write_pointer;
1105         xen_rmb();
1106         if (rdptr != buf_page->read_pointer) {
1107             continue;
1108         }
1109         if (rdptr == wrptr) {
1110             break;
1111         }
1112         buf_req = &buf_page->buf_ioreq[rdptr % IOREQ_BUFFER_SLOT_NUM];
1113         req.size = 1U << buf_req->size;
1114         req.addr = buf_req->addr;
1115         req.data = buf_req->data;
1116         req.type = buf_req->type;
1117         xen_rmb();
1118         qw = (req.size == 8);
1119         if (qw) {
1120             if (rdptr + 1 == wrptr) {
1121                 hw_error("Incomplete quad word buffered ioreq");
1122             }
1123             buf_req = &buf_page->buf_ioreq[(rdptr + 1) %
1124                                            IOREQ_BUFFER_SLOT_NUM];
1125             req.data |= ((uint64_t)buf_req->data) << 32;
1126             xen_rmb();
1127         }
1128 
1129         handle_ioreq(state, &req);
1130 
1131         /* Only req.data may get updated by handle_ioreq(), albeit even that
1132          * should not happen as such data would never make it to the guest (we
1133          * can only usefully see writes here after all).
1134          */
1135         assert(req.state == STATE_IOREQ_READY);
1136         assert(req.count == 1);
1137         assert(req.dir == IOREQ_WRITE);
1138         assert(!req.data_is_ptr);
1139 
1140         atomic_add(&buf_page->read_pointer, qw + 1);
1141     }
1142 
1143     return req.count;
1144 }
1145 
1146 static void handle_buffered_io(void *opaque)
1147 {
1148     XenIOState *state = opaque;
1149 
1150     if (handle_buffered_iopage(state)) {
1151         timer_mod(state->buffered_io_timer,
1152                 BUFFER_IO_MAX_DELAY + qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
1153     } else {
1154         timer_del(state->buffered_io_timer);
1155         xenevtchn_unmask(state->xce_handle, state->bufioreq_local_port);
1156     }
1157 }
1158 
1159 static void cpu_handle_ioreq(void *opaque)
1160 {
1161     XenIOState *state = opaque;
1162     ioreq_t *req = cpu_get_ioreq(state);
1163 
1164     handle_buffered_iopage(state);
1165     if (req) {
1166         ioreq_t copy = *req;
1167 
1168         xen_rmb();
1169         handle_ioreq(state, &copy);
1170         req->data = copy.data;
1171 
1172         if (req->state != STATE_IOREQ_INPROCESS) {
1173             fprintf(stderr, "Badness in I/O request ... not in service?!: "
1174                     "%x, ptr: %x, port: %"PRIx64", "
1175                     "data: %"PRIx64", count: %u, size: %u, type: %u\n",
1176                     req->state, req->data_is_ptr, req->addr,
1177                     req->data, req->count, req->size, req->type);
1178             destroy_hvm_domain(false);
1179             return;
1180         }
1181 
1182         xen_wmb(); /* Update ioreq contents /then/ update state. */
1183 
1184         /*
1185          * We do this before we send the response so that the tools
1186          * have the opportunity to pick up on the reset before the
1187          * guest resumes and does a hlt with interrupts disabled which
1188          * causes Xen to powerdown the domain.
1189          */
1190         if (runstate_is_running()) {
1191             ShutdownCause request;
1192 
1193             if (qemu_shutdown_requested_get()) {
1194                 destroy_hvm_domain(false);
1195             }
1196             request = qemu_reset_requested_get();
1197             if (request) {
1198                 qemu_system_reset(request);
1199                 destroy_hvm_domain(true);
1200             }
1201         }
1202 
1203         req->state = STATE_IORESP_READY;
1204         xenevtchn_notify(state->xce_handle,
1205                          state->ioreq_local_port[state->send_vcpu]);
1206     }
1207 }
1208 
1209 static void xen_main_loop_prepare(XenIOState *state)
1210 {
1211     int evtchn_fd = -1;
1212 
1213     if (state->xce_handle != NULL) {
1214         evtchn_fd = xenevtchn_fd(state->xce_handle);
1215     }
1216 
1217     state->buffered_io_timer = timer_new_ms(QEMU_CLOCK_REALTIME, handle_buffered_io,
1218                                                  state);
1219 
1220     if (evtchn_fd != -1) {
1221         CPUState *cpu_state;
1222 
1223         DPRINTF("%s: Init cpu_by_vcpu_id\n", __func__);
1224         CPU_FOREACH(cpu_state) {
1225             DPRINTF("%s: cpu_by_vcpu_id[%d]=%p\n",
1226                     __func__, cpu_state->cpu_index, cpu_state);
1227             state->cpu_by_vcpu_id[cpu_state->cpu_index] = cpu_state;
1228         }
1229         qemu_set_fd_handler(evtchn_fd, cpu_handle_ioreq, NULL, state);
1230     }
1231 }
1232 
1233 
1234 static void xen_hvm_change_state_handler(void *opaque, int running,
1235                                          RunState rstate)
1236 {
1237     XenIOState *state = opaque;
1238 
1239     if (running) {
1240         xen_main_loop_prepare(state);
1241     }
1242 
1243     xen_set_ioreq_server_state(xen_domid,
1244                                state->ioservid,
1245                                (rstate == RUN_STATE_RUNNING));
1246 }
1247 
1248 static void xen_exit_notifier(Notifier *n, void *data)
1249 {
1250     XenIOState *state = container_of(n, XenIOState, exit);
1251 
1252     xen_destroy_ioreq_server(xen_domid, state->ioservid);
1253 
1254     xenevtchn_close(state->xce_handle);
1255     xs_daemon_close(state->xenstore);
1256 }
1257 
1258 #ifdef XEN_COMPAT_PHYSMAP
1259 static void xen_read_physmap(XenIOState *state)
1260 {
1261     XenPhysmap *physmap = NULL;
1262     unsigned int len, num, i;
1263     char path[80], *value = NULL;
1264     char **entries = NULL;
1265 
1266     snprintf(path, sizeof(path),
1267             "/local/domain/0/device-model/%d/physmap", xen_domid);
1268     entries = xs_directory(state->xenstore, 0, path, &num);
1269     if (entries == NULL)
1270         return;
1271 
1272     for (i = 0; i < num; i++) {
1273         physmap = g_malloc(sizeof (XenPhysmap));
1274         physmap->phys_offset = strtoull(entries[i], NULL, 16);
1275         snprintf(path, sizeof(path),
1276                 "/local/domain/0/device-model/%d/physmap/%s/start_addr",
1277                 xen_domid, entries[i]);
1278         value = xs_read(state->xenstore, 0, path, &len);
1279         if (value == NULL) {
1280             g_free(physmap);
1281             continue;
1282         }
1283         physmap->start_addr = strtoull(value, NULL, 16);
1284         free(value);
1285 
1286         snprintf(path, sizeof(path),
1287                 "/local/domain/0/device-model/%d/physmap/%s/size",
1288                 xen_domid, entries[i]);
1289         value = xs_read(state->xenstore, 0, path, &len);
1290         if (value == NULL) {
1291             g_free(physmap);
1292             continue;
1293         }
1294         physmap->size = strtoull(value, NULL, 16);
1295         free(value);
1296 
1297         snprintf(path, sizeof(path),
1298                 "/local/domain/0/device-model/%d/physmap/%s/name",
1299                 xen_domid, entries[i]);
1300         physmap->name = xs_read(state->xenstore, 0, path, &len);
1301 
1302         QLIST_INSERT_HEAD(&xen_physmap, physmap, list);
1303     }
1304     free(entries);
1305 }
1306 #else
1307 static void xen_read_physmap(XenIOState *state)
1308 {
1309 }
1310 #endif
1311 
1312 static void xen_wakeup_notifier(Notifier *notifier, void *data)
1313 {
1314     xc_set_hvm_param(xen_xc, xen_domid, HVM_PARAM_ACPI_S_STATE, 0);
1315 }
1316 
1317 static int xen_map_ioreq_server(XenIOState *state)
1318 {
1319     void *addr = NULL;
1320     xenforeignmemory_resource_handle *fres;
1321     xen_pfn_t ioreq_pfn;
1322     xen_pfn_t bufioreq_pfn;
1323     evtchn_port_t bufioreq_evtchn;
1324     int rc;
1325 
1326     /*
1327      * Attempt to map using the resource API and fall back to normal
1328      * foreign mapping if this is not supported.
1329      */
1330     QEMU_BUILD_BUG_ON(XENMEM_resource_ioreq_server_frame_bufioreq != 0);
1331     QEMU_BUILD_BUG_ON(XENMEM_resource_ioreq_server_frame_ioreq(0) != 1);
1332     fres = xenforeignmemory_map_resource(xen_fmem, xen_domid,
1333                                          XENMEM_resource_ioreq_server,
1334                                          state->ioservid, 0, 2,
1335                                          &addr,
1336                                          PROT_READ | PROT_WRITE, 0);
1337     if (fres != NULL) {
1338         trace_xen_map_resource_ioreq(state->ioservid, addr);
1339         state->buffered_io_page = addr;
1340         state->shared_page = addr + TARGET_PAGE_SIZE;
1341     } else if (errno != EOPNOTSUPP) {
1342         error_report("failed to map ioreq server resources: error %d handle=%p",
1343                      errno, xen_xc);
1344         return -1;
1345     }
1346 
1347     rc = xen_get_ioreq_server_info(xen_domid, state->ioservid,
1348                                    (state->shared_page == NULL) ?
1349                                    &ioreq_pfn : NULL,
1350                                    (state->buffered_io_page == NULL) ?
1351                                    &bufioreq_pfn : NULL,
1352                                    &bufioreq_evtchn);
1353     if (rc < 0) {
1354         error_report("failed to get ioreq server info: error %d handle=%p",
1355                      errno, xen_xc);
1356         return rc;
1357     }
1358 
1359     if (state->shared_page == NULL) {
1360         DPRINTF("shared page at pfn %lx\n", ioreq_pfn);
1361 
1362         state->shared_page = xenforeignmemory_map(xen_fmem, xen_domid,
1363                                                   PROT_READ | PROT_WRITE,
1364                                                   1, &ioreq_pfn, NULL);
1365         if (state->shared_page == NULL) {
1366             error_report("map shared IO page returned error %d handle=%p",
1367                          errno, xen_xc);
1368         }
1369     }
1370 
1371     if (state->buffered_io_page == NULL) {
1372         DPRINTF("buffered io page at pfn %lx\n", bufioreq_pfn);
1373 
1374         state->buffered_io_page = xenforeignmemory_map(xen_fmem, xen_domid,
1375                                                        PROT_READ | PROT_WRITE,
1376                                                        1, &bufioreq_pfn,
1377                                                        NULL);
1378         if (state->buffered_io_page == NULL) {
1379             error_report("map buffered IO page returned error %d", errno);
1380             return -1;
1381         }
1382     }
1383 
1384     if (state->shared_page == NULL || state->buffered_io_page == NULL) {
1385         return -1;
1386     }
1387 
1388     DPRINTF("buffered io evtchn is %x\n", bufioreq_evtchn);
1389 
1390     state->bufioreq_remote_port = bufioreq_evtchn;
1391 
1392     return 0;
1393 }
1394 
1395 void xen_hvm_init(PCMachineState *pcms, MemoryRegion **ram_memory)
1396 {
1397     MachineState *ms = MACHINE(pcms);
1398     unsigned int max_cpus = ms->smp.max_cpus;
1399     int i, rc;
1400     xen_pfn_t ioreq_pfn;
1401     XenIOState *state;
1402 
1403     state = g_malloc0(sizeof (XenIOState));
1404 
1405     state->xce_handle = xenevtchn_open(NULL, 0);
1406     if (state->xce_handle == NULL) {
1407         perror("xen: event channel open");
1408         goto err;
1409     }
1410 
1411     state->xenstore = xs_daemon_open();
1412     if (state->xenstore == NULL) {
1413         perror("xen: xenstore open");
1414         goto err;
1415     }
1416 
1417     xen_create_ioreq_server(xen_domid, &state->ioservid);
1418 
1419     state->exit.notify = xen_exit_notifier;
1420     qemu_add_exit_notifier(&state->exit);
1421 
1422     state->suspend.notify = xen_suspend_notifier;
1423     qemu_register_suspend_notifier(&state->suspend);
1424 
1425     state->wakeup.notify = xen_wakeup_notifier;
1426     qemu_register_wakeup_notifier(&state->wakeup);
1427 
1428     /*
1429      * Register wake-up support in QMP query-current-machine API
1430      */
1431     qemu_register_wakeup_support();
1432 
1433     rc = xen_map_ioreq_server(state);
1434     if (rc < 0) {
1435         goto err;
1436     }
1437 
1438     rc = xen_get_vmport_regs_pfn(xen_xc, xen_domid, &ioreq_pfn);
1439     if (!rc) {
1440         DPRINTF("shared vmport page at pfn %lx\n", ioreq_pfn);
1441         state->shared_vmport_page =
1442             xenforeignmemory_map(xen_fmem, xen_domid, PROT_READ|PROT_WRITE,
1443                                  1, &ioreq_pfn, NULL);
1444         if (state->shared_vmport_page == NULL) {
1445             error_report("map shared vmport IO page returned error %d handle=%p",
1446                          errno, xen_xc);
1447             goto err;
1448         }
1449     } else if (rc != -ENOSYS) {
1450         error_report("get vmport regs pfn returned error %d, rc=%d",
1451                      errno, rc);
1452         goto err;
1453     }
1454 
1455     /* Note: cpus is empty at this point in init */
1456     state->cpu_by_vcpu_id = g_malloc0(max_cpus * sizeof(CPUState *));
1457 
1458     rc = xen_set_ioreq_server_state(xen_domid, state->ioservid, true);
1459     if (rc < 0) {
1460         error_report("failed to enable ioreq server info: error %d handle=%p",
1461                      errno, xen_xc);
1462         goto err;
1463     }
1464 
1465     state->ioreq_local_port = g_malloc0(max_cpus * sizeof (evtchn_port_t));
1466 
1467     /* FIXME: how about if we overflow the page here? */
1468     for (i = 0; i < max_cpus; i++) {
1469         rc = xenevtchn_bind_interdomain(state->xce_handle, xen_domid,
1470                                         xen_vcpu_eport(state->shared_page, i));
1471         if (rc == -1) {
1472             error_report("shared evtchn %d bind error %d", i, errno);
1473             goto err;
1474         }
1475         state->ioreq_local_port[i] = rc;
1476     }
1477 
1478     rc = xenevtchn_bind_interdomain(state->xce_handle, xen_domid,
1479                                     state->bufioreq_remote_port);
1480     if (rc == -1) {
1481         error_report("buffered evtchn bind error %d", errno);
1482         goto err;
1483     }
1484     state->bufioreq_local_port = rc;
1485 
1486     /* Init RAM management */
1487 #ifdef XEN_COMPAT_PHYSMAP
1488     xen_map_cache_init(xen_phys_offset_to_gaddr, state);
1489 #else
1490     xen_map_cache_init(NULL, state);
1491 #endif
1492     xen_ram_init(pcms, ram_size, ram_memory);
1493 
1494     qemu_add_vm_change_state_handler(xen_hvm_change_state_handler, state);
1495 
1496     state->memory_listener = xen_memory_listener;
1497     memory_listener_register(&state->memory_listener, &address_space_memory);
1498     state->log_for_dirtybit = NULL;
1499 
1500     state->io_listener = xen_io_listener;
1501     memory_listener_register(&state->io_listener, &address_space_io);
1502 
1503     state->device_listener = xen_device_listener;
1504     QLIST_INIT(&state->dev_list);
1505     device_listener_register(&state->device_listener);
1506 
1507     xen_bus_init();
1508 
1509     /* Initialize backend core & drivers */
1510     if (xen_be_init() != 0) {
1511         error_report("xen backend core setup failed");
1512         goto err;
1513     }
1514     xen_be_register_common();
1515 
1516     QLIST_INIT(&xen_physmap);
1517     xen_read_physmap(state);
1518 
1519     /* Disable ACPI build because Xen handles it */
1520     pcms->acpi_build_enabled = false;
1521 
1522     return;
1523 
1524 err:
1525     error_report("xen hardware virtual machine initialisation failed");
1526     exit(1);
1527 }
1528 
1529 void destroy_hvm_domain(bool reboot)
1530 {
1531     xc_interface *xc_handle;
1532     int sts;
1533     int rc;
1534 
1535     unsigned int reason = reboot ? SHUTDOWN_reboot : SHUTDOWN_poweroff;
1536 
1537     if (xen_dmod) {
1538         rc = xendevicemodel_shutdown(xen_dmod, xen_domid, reason);
1539         if (!rc) {
1540             return;
1541         }
1542         if (errno != ENOTTY /* old Xen */) {
1543             perror("xendevicemodel_shutdown failed");
1544         }
1545         /* well, try the old thing then */
1546     }
1547 
1548     xc_handle = xc_interface_open(0, 0, 0);
1549     if (xc_handle == NULL) {
1550         fprintf(stderr, "Cannot acquire xenctrl handle\n");
1551     } else {
1552         sts = xc_domain_shutdown(xc_handle, xen_domid, reason);
1553         if (sts != 0) {
1554             fprintf(stderr, "xc_domain_shutdown failed to issue %s, "
1555                     "sts %d, %s\n", reboot ? "reboot" : "poweroff",
1556                     sts, strerror(errno));
1557         } else {
1558             fprintf(stderr, "Issued domain %d %s\n", xen_domid,
1559                     reboot ? "reboot" : "poweroff");
1560         }
1561         xc_interface_close(xc_handle);
1562     }
1563 }
1564 
1565 void xen_register_framebuffer(MemoryRegion *mr)
1566 {
1567     framebuffer = mr;
1568 }
1569 
1570 void xen_shutdown_fatal_error(const char *fmt, ...)
1571 {
1572     va_list ap;
1573 
1574     va_start(ap, fmt);
1575     vfprintf(stderr, fmt, ap);
1576     va_end(ap);
1577     fprintf(stderr, "Will destroy the domain.\n");
1578     /* destroy the domain */
1579     qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_ERROR);
1580 }
1581 
1582 void xen_hvm_modified_memory(ram_addr_t start, ram_addr_t length)
1583 {
1584     if (unlikely(xen_in_migration)) {
1585         int rc;
1586         ram_addr_t start_pfn, nb_pages;
1587 
1588         start = xen_phys_offset_to_gaddr(start, length);
1589 
1590         if (length == 0) {
1591             length = TARGET_PAGE_SIZE;
1592         }
1593         start_pfn = start >> TARGET_PAGE_BITS;
1594         nb_pages = ((start + length + TARGET_PAGE_SIZE - 1) >> TARGET_PAGE_BITS)
1595             - start_pfn;
1596         rc = xen_modified_memory(xen_domid, start_pfn, nb_pages);
1597         if (rc) {
1598             fprintf(stderr,
1599                     "%s failed for "RAM_ADDR_FMT" ("RAM_ADDR_FMT"): %i, %s\n",
1600                     __func__, start, nb_pages, errno, strerror(errno));
1601         }
1602     }
1603 }
1604 
1605 void qmp_xen_set_global_dirty_log(bool enable, Error **errp)
1606 {
1607     if (enable) {
1608         memory_global_dirty_log_start();
1609     } else {
1610         memory_global_dirty_log_stop();
1611     }
1612 }
1613