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