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