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