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