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