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