sync with latest
[sdk/emulator/qemu.git] / xen-all.c
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 <sys/mman.h>
12
13 #include "hw/pci.h"
14 #include "hw/pc.h"
15 #include "hw/xen_common.h"
16 #include "hw/xen_backend.h"
17
18 #include "range.h"
19 #include "xen-mapcache.h"
20 #include "trace.h"
21 #include "exec-memory.h"
22
23 #include <xen/hvm/ioreq.h>
24 #include <xen/hvm/params.h>
25 #include <xen/hvm/e820.h>
26
27 //#define DEBUG_XEN
28
29 #ifdef DEBUG_XEN
30 #define DPRINTF(fmt, ...) \
31     do { fprintf(stderr, "xen: " fmt, ## __VA_ARGS__); } while (0)
32 #else
33 #define DPRINTF(fmt, ...) \
34     do { } while (0)
35 #endif
36
37 static MemoryRegion ram_memory, ram_640k, ram_lo, ram_hi;
38 static MemoryRegion *framebuffer;
39
40 /* Compatibility with older version */
41 #if __XEN_LATEST_INTERFACE_VERSION__ < 0x0003020a
42 static inline uint32_t xen_vcpu_eport(shared_iopage_t *shared_page, int i)
43 {
44     return shared_page->vcpu_iodata[i].vp_eport;
45 }
46 static inline ioreq_t *xen_vcpu_ioreq(shared_iopage_t *shared_page, int vcpu)
47 {
48     return &shared_page->vcpu_iodata[vcpu].vp_ioreq;
49 }
50 #  define FMT_ioreq_size PRIx64
51 #else
52 static inline uint32_t xen_vcpu_eport(shared_iopage_t *shared_page, int i)
53 {
54     return shared_page->vcpu_ioreq[i].vp_eport;
55 }
56 static inline ioreq_t *xen_vcpu_ioreq(shared_iopage_t *shared_page, int vcpu)
57 {
58     return &shared_page->vcpu_ioreq[vcpu];
59 }
60 #  define FMT_ioreq_size "u"
61 #endif
62 #ifndef HVM_PARAM_BUFIOREQ_EVTCHN
63 #define HVM_PARAM_BUFIOREQ_EVTCHN 26
64 #endif
65
66 #define BUFFER_IO_MAX_DELAY  100
67
68 typedef struct XenPhysmap {
69     target_phys_addr_t start_addr;
70     ram_addr_t size;
71     char *name;
72     target_phys_addr_t phys_offset;
73
74     QLIST_ENTRY(XenPhysmap) list;
75 } XenPhysmap;
76
77 typedef struct XenIOState {
78     shared_iopage_t *shared_page;
79     buffered_iopage_t *buffered_io_page;
80     QEMUTimer *buffered_io_timer;
81     /* the evtchn port for polling the notification, */
82     evtchn_port_t *ioreq_local_port;
83     /* evtchn local port for buffered io */
84     evtchn_port_t bufioreq_local_port;
85     /* the evtchn fd for polling */
86     XenEvtchn xce_handle;
87     /* which vcpu we are serving */
88     int send_vcpu;
89
90     struct xs_handle *xenstore;
91     MemoryListener memory_listener;
92     QLIST_HEAD(, XenPhysmap) physmap;
93     target_phys_addr_t free_phys_offset;
94     const XenPhysmap *log_for_dirtybit;
95
96     Notifier exit;
97     Notifier suspend;
98 } XenIOState;
99
100 /* Xen specific function for piix pci */
101
102 int xen_pci_slot_get_pirq(PCIDevice *pci_dev, int irq_num)
103 {
104     return irq_num + ((pci_dev->devfn >> 3) << 2);
105 }
106
107 void xen_piix3_set_irq(void *opaque, int irq_num, int level)
108 {
109     xc_hvm_set_pci_intx_level(xen_xc, xen_domid, 0, 0, irq_num >> 2,
110                               irq_num & 3, level);
111 }
112
113 void xen_piix_pci_write_config_client(uint32_t address, uint32_t val, int len)
114 {
115     int i;
116
117     /* Scan for updates to PCI link routes (0x60-0x63). */
118     for (i = 0; i < len; i++) {
119         uint8_t v = (val >> (8 * i)) & 0xff;
120         if (v & 0x80) {
121             v = 0;
122         }
123         v &= 0xf;
124         if (((address + i) >= 0x60) && ((address + i) <= 0x63)) {
125             xc_hvm_set_pci_link_route(xen_xc, xen_domid, address + i - 0x60, v);
126         }
127     }
128 }
129
130 void xen_hvm_inject_msi(uint64_t addr, uint32_t data)
131 {
132     xen_xc_hvm_inject_msi(xen_xc, xen_domid, addr, data);
133 }
134
135 static void xen_suspend_notifier(Notifier *notifier, void *data)
136 {
137     xc_set_hvm_param(xen_xc, xen_domid, HVM_PARAM_ACPI_S_STATE, 3);
138 }
139
140 /* Xen Interrupt Controller */
141
142 static void xen_set_irq(void *opaque, int irq, int level)
143 {
144     xc_hvm_set_isa_irq_level(xen_xc, xen_domid, irq, level);
145 }
146
147 qemu_irq *xen_interrupt_controller_init(void)
148 {
149     return qemu_allocate_irqs(xen_set_irq, NULL, 16);
150 }
151
152 /* Memory Ops */
153
154 static void xen_ram_init(ram_addr_t ram_size)
155 {
156     MemoryRegion *sysmem = get_system_memory();
157     ram_addr_t below_4g_mem_size, above_4g_mem_size = 0;
158     ram_addr_t block_len;
159
160     block_len = ram_size;
161     if (ram_size >= HVM_BELOW_4G_RAM_END) {
162         /* Xen does not allocate the memory continuously, and keep a hole at
163          * HVM_BELOW_4G_MMIO_START of HVM_BELOW_4G_MMIO_LENGTH
164          */
165         block_len += HVM_BELOW_4G_MMIO_LENGTH;
166     }
167     memory_region_init_ram(&ram_memory, "xen.ram", block_len);
168     vmstate_register_ram_global(&ram_memory);
169
170     if (ram_size >= HVM_BELOW_4G_RAM_END) {
171         above_4g_mem_size = ram_size - HVM_BELOW_4G_RAM_END;
172         below_4g_mem_size = HVM_BELOW_4G_RAM_END;
173     } else {
174         below_4g_mem_size = ram_size;
175     }
176
177     memory_region_init_alias(&ram_640k, "xen.ram.640k",
178                              &ram_memory, 0, 0xa0000);
179     memory_region_add_subregion(sysmem, 0, &ram_640k);
180     /* Skip of the VGA IO memory space, it will be registered later by the VGA
181      * emulated device.
182      *
183      * The area between 0xc0000 and 0x100000 will be used by SeaBIOS to load
184      * the Options ROM, so it is registered here as RAM.
185      */
186     memory_region_init_alias(&ram_lo, "xen.ram.lo",
187                              &ram_memory, 0xc0000, below_4g_mem_size - 0xc0000);
188     memory_region_add_subregion(sysmem, 0xc0000, &ram_lo);
189     if (above_4g_mem_size > 0) {
190         memory_region_init_alias(&ram_hi, "xen.ram.hi",
191                                  &ram_memory, 0x100000000ULL,
192                                  above_4g_mem_size);
193         memory_region_add_subregion(sysmem, 0x100000000ULL, &ram_hi);
194     }
195 }
196
197 void xen_ram_alloc(ram_addr_t ram_addr, ram_addr_t size, MemoryRegion *mr)
198 {
199     unsigned long nr_pfn;
200     xen_pfn_t *pfn_list;
201     int i;
202
203     if (runstate_check(RUN_STATE_INMIGRATE)) {
204         /* RAM already populated in Xen */
205         fprintf(stderr, "%s: do not alloc "RAM_ADDR_FMT
206                 " bytes of ram at "RAM_ADDR_FMT" when runstate is INMIGRATE\n",
207                 __func__, size, ram_addr); 
208         return;
209     }
210
211     if (mr == &ram_memory) {
212         return;
213     }
214
215     trace_xen_ram_alloc(ram_addr, size);
216
217     nr_pfn = size >> TARGET_PAGE_BITS;
218     pfn_list = g_malloc(sizeof (*pfn_list) * nr_pfn);
219
220     for (i = 0; i < nr_pfn; i++) {
221         pfn_list[i] = (ram_addr >> TARGET_PAGE_BITS) + i;
222     }
223
224     if (xc_domain_populate_physmap_exact(xen_xc, xen_domid, nr_pfn, 0, 0, pfn_list)) {
225         hw_error("xen: failed to populate ram at " RAM_ADDR_FMT, ram_addr);
226     }
227
228     g_free(pfn_list);
229 }
230
231 static XenPhysmap *get_physmapping(XenIOState *state,
232                                    target_phys_addr_t start_addr, ram_addr_t size)
233 {
234     XenPhysmap *physmap = NULL;
235
236     start_addr &= TARGET_PAGE_MASK;
237
238     QLIST_FOREACH(physmap, &state->physmap, list) {
239         if (range_covers_byte(physmap->start_addr, physmap->size, start_addr)) {
240             return physmap;
241         }
242     }
243     return NULL;
244 }
245
246 static target_phys_addr_t xen_phys_offset_to_gaddr(target_phys_addr_t start_addr,
247                                                    ram_addr_t size, void *opaque)
248 {
249     target_phys_addr_t addr = start_addr & TARGET_PAGE_MASK;
250     XenIOState *xen_io_state = opaque;
251     XenPhysmap *physmap = NULL;
252
253     QLIST_FOREACH(physmap, &xen_io_state->physmap, list) {
254         if (range_covers_byte(physmap->phys_offset, physmap->size, addr)) {
255             return physmap->start_addr;
256         }
257     }
258
259     return start_addr;
260 }
261
262 #if CONFIG_XEN_CTRL_INTERFACE_VERSION >= 340
263 static int xen_add_to_physmap(XenIOState *state,
264                               target_phys_addr_t start_addr,
265                               ram_addr_t size,
266                               MemoryRegion *mr,
267                               target_phys_addr_t offset_within_region)
268 {
269     unsigned long i = 0;
270     int rc = 0;
271     XenPhysmap *physmap = NULL;
272     target_phys_addr_t pfn, start_gpfn;
273     target_phys_addr_t phys_offset = memory_region_get_ram_addr(mr);
274     char path[80], value[17];
275
276     if (get_physmapping(state, start_addr, size)) {
277         return 0;
278     }
279     if (size <= 0) {
280         return -1;
281     }
282
283     /* Xen can only handle a single dirty log region for now and we want
284      * the linear framebuffer to be that region.
285      * Avoid tracking any regions that is not videoram and avoid tracking
286      * the legacy vga region. */
287     if (mr == framebuffer && start_addr > 0xbffff) {
288         goto go_physmap;
289     }
290     return -1;
291
292 go_physmap:
293     DPRINTF("mapping vram to %llx - %llx\n", start_addr, start_addr + size);
294
295     pfn = phys_offset >> TARGET_PAGE_BITS;
296     start_gpfn = start_addr >> TARGET_PAGE_BITS;
297     for (i = 0; i < size >> TARGET_PAGE_BITS; i++) {
298         unsigned long idx = pfn + i;
299         xen_pfn_t gpfn = start_gpfn + i;
300
301         rc = xc_domain_add_to_physmap(xen_xc, xen_domid, XENMAPSPACE_gmfn, idx, gpfn);
302         if (rc) {
303             DPRINTF("add_to_physmap MFN %"PRI_xen_pfn" to PFN %"
304                     PRI_xen_pfn" failed: %d\n", idx, gpfn, rc);
305             return -rc;
306         }
307     }
308
309     physmap = g_malloc(sizeof (XenPhysmap));
310
311     physmap->start_addr = start_addr;
312     physmap->size = size;
313     physmap->name = (char *)mr->name;
314     physmap->phys_offset = phys_offset;
315
316     QLIST_INSERT_HEAD(&state->physmap, physmap, list);
317
318     xc_domain_pin_memory_cacheattr(xen_xc, xen_domid,
319                                    start_addr >> TARGET_PAGE_BITS,
320                                    (start_addr + size) >> TARGET_PAGE_BITS,
321                                    XEN_DOMCTL_MEM_CACHEATTR_WB);
322
323     snprintf(path, sizeof(path),
324             "/local/domain/0/device-model/%d/physmap/%"PRIx64"/start_addr",
325             xen_domid, (uint64_t)phys_offset);
326     snprintf(value, sizeof(value), "%"PRIx64, (uint64_t)start_addr);
327     if (!xs_write(state->xenstore, 0, path, value, strlen(value))) {
328         return -1;
329     }
330     snprintf(path, sizeof(path),
331             "/local/domain/0/device-model/%d/physmap/%"PRIx64"/size",
332             xen_domid, (uint64_t)phys_offset);
333     snprintf(value, sizeof(value), "%"PRIx64, (uint64_t)size);
334     if (!xs_write(state->xenstore, 0, path, value, strlen(value))) {
335         return -1;
336     }
337     if (mr->name) {
338         snprintf(path, sizeof(path),
339                 "/local/domain/0/device-model/%d/physmap/%"PRIx64"/name",
340                 xen_domid, (uint64_t)phys_offset);
341         if (!xs_write(state->xenstore, 0, path, mr->name, strlen(mr->name))) {
342             return -1;
343         }
344     }
345
346     return 0;
347 }
348
349 static int xen_remove_from_physmap(XenIOState *state,
350                                    target_phys_addr_t start_addr,
351                                    ram_addr_t size)
352 {
353     unsigned long i = 0;
354     int rc = 0;
355     XenPhysmap *physmap = NULL;
356     target_phys_addr_t phys_offset = 0;
357
358     physmap = get_physmapping(state, start_addr, size);
359     if (physmap == NULL) {
360         return -1;
361     }
362
363     phys_offset = physmap->phys_offset;
364     size = physmap->size;
365
366     DPRINTF("unmapping vram to %llx - %llx, from %llx\n",
367             phys_offset, phys_offset + size, start_addr);
368
369     size >>= TARGET_PAGE_BITS;
370     start_addr >>= TARGET_PAGE_BITS;
371     phys_offset >>= TARGET_PAGE_BITS;
372     for (i = 0; i < size; i++) {
373         unsigned long idx = start_addr + i;
374         xen_pfn_t gpfn = phys_offset + i;
375
376         rc = xc_domain_add_to_physmap(xen_xc, xen_domid, XENMAPSPACE_gmfn, idx, gpfn);
377         if (rc) {
378             fprintf(stderr, "add_to_physmap MFN %"PRI_xen_pfn" to PFN %"
379                     PRI_xen_pfn" failed: %d\n", idx, gpfn, rc);
380             return -rc;
381         }
382     }
383
384     QLIST_REMOVE(physmap, list);
385     if (state->log_for_dirtybit == physmap) {
386         state->log_for_dirtybit = NULL;
387     }
388     free(physmap);
389
390     return 0;
391 }
392
393 #else
394 static int xen_add_to_physmap(XenIOState *state,
395                               target_phys_addr_t start_addr,
396                               ram_addr_t size,
397                               MemoryRegion *mr,
398                               target_phys_addr_t offset_within_region)
399 {
400     return -ENOSYS;
401 }
402
403 static int xen_remove_from_physmap(XenIOState *state,
404                                    target_phys_addr_t start_addr,
405                                    ram_addr_t size)
406 {
407     return -ENOSYS;
408 }
409 #endif
410
411 static void xen_set_memory(struct MemoryListener *listener,
412                            MemoryRegionSection *section,
413                            bool add)
414 {
415     XenIOState *state = container_of(listener, XenIOState, memory_listener);
416     target_phys_addr_t start_addr = section->offset_within_address_space;
417     ram_addr_t size = section->size;
418     bool log_dirty = memory_region_is_logging(section->mr);
419     hvmmem_type_t mem_type;
420
421     if (!memory_region_is_ram(section->mr)) {
422         return;
423     }
424
425     if (!(section->mr != &ram_memory
426           && ( (log_dirty && add) || (!log_dirty && !add)))) {
427         return;
428     }
429
430     trace_xen_client_set_memory(start_addr, size, log_dirty);
431
432     start_addr &= TARGET_PAGE_MASK;
433     size = TARGET_PAGE_ALIGN(size);
434
435     if (add) {
436         if (!memory_region_is_rom(section->mr)) {
437             xen_add_to_physmap(state, start_addr, size,
438                                section->mr, section->offset_within_region);
439         } else {
440             mem_type = HVMMEM_ram_ro;
441             if (xc_hvm_set_mem_type(xen_xc, xen_domid, mem_type,
442                                     start_addr >> TARGET_PAGE_BITS,
443                                     size >> TARGET_PAGE_BITS)) {
444                 DPRINTF("xc_hvm_set_mem_type error, addr: "TARGET_FMT_plx"\n",
445                         start_addr);
446             }
447         }
448     } else {
449         if (xen_remove_from_physmap(state, start_addr, size) < 0) {
450             DPRINTF("physmapping does not exist at "TARGET_FMT_plx"\n", start_addr);
451         }
452     }
453 }
454
455 static void xen_begin(MemoryListener *listener)
456 {
457 }
458
459 static void xen_commit(MemoryListener *listener)
460 {
461 }
462
463 static void xen_region_add(MemoryListener *listener,
464                            MemoryRegionSection *section)
465 {
466     xen_set_memory(listener, section, true);
467 }
468
469 static void xen_region_del(MemoryListener *listener,
470                            MemoryRegionSection *section)
471 {
472     xen_set_memory(listener, section, false);
473 }
474
475 static void xen_region_nop(MemoryListener *listener,
476                            MemoryRegionSection *section)
477 {
478 }
479
480 static void xen_sync_dirty_bitmap(XenIOState *state,
481                                   target_phys_addr_t start_addr,
482                                   ram_addr_t size)
483 {
484     target_phys_addr_t npages = size >> TARGET_PAGE_BITS;
485     const int width = sizeof(unsigned long) * 8;
486     unsigned long bitmap[(npages + width - 1) / width];
487     int rc, i, j;
488     const XenPhysmap *physmap = NULL;
489
490     physmap = get_physmapping(state, start_addr, size);
491     if (physmap == NULL) {
492         /* not handled */
493         return;
494     }
495
496     if (state->log_for_dirtybit == NULL) {
497         state->log_for_dirtybit = physmap;
498     } else if (state->log_for_dirtybit != physmap) {
499         /* Only one range for dirty bitmap can be tracked. */
500         return;
501     }
502
503     rc = xc_hvm_track_dirty_vram(xen_xc, xen_domid,
504                                  start_addr >> TARGET_PAGE_BITS, npages,
505                                  bitmap);
506     if (rc < 0) {
507         if (rc != -ENODATA) {
508             fprintf(stderr, "xen: track_dirty_vram failed (0x" TARGET_FMT_plx
509                     ", 0x" TARGET_FMT_plx "): %s\n",
510                     start_addr, start_addr + size, strerror(-rc));
511         }
512         return;
513     }
514
515     for (i = 0; i < ARRAY_SIZE(bitmap); i++) {
516         unsigned long map = bitmap[i];
517         while (map != 0) {
518             j = ffsl(map) - 1;
519             map &= ~(1ul << j);
520             memory_region_set_dirty(framebuffer,
521                                     (i * width + j) * TARGET_PAGE_SIZE,
522                                     TARGET_PAGE_SIZE);
523         };
524     }
525 }
526
527 static void xen_log_start(MemoryListener *listener,
528                           MemoryRegionSection *section)
529 {
530     XenIOState *state = container_of(listener, XenIOState, memory_listener);
531
532     xen_sync_dirty_bitmap(state, section->offset_within_address_space,
533                           section->size);
534 }
535
536 static void xen_log_stop(MemoryListener *listener, MemoryRegionSection *section)
537 {
538     XenIOState *state = container_of(listener, XenIOState, memory_listener);
539
540     state->log_for_dirtybit = NULL;
541     /* Disable dirty bit tracking */
542     xc_hvm_track_dirty_vram(xen_xc, xen_domid, 0, 0, NULL);
543 }
544
545 static void xen_log_sync(MemoryListener *listener, MemoryRegionSection *section)
546 {
547     XenIOState *state = container_of(listener, XenIOState, memory_listener);
548
549     xen_sync_dirty_bitmap(state, section->offset_within_address_space,
550                           section->size);
551 }
552
553 static void xen_log_global_start(MemoryListener *listener)
554 {
555 }
556
557 static void xen_log_global_stop(MemoryListener *listener)
558 {
559 }
560
561 static void xen_eventfd_add(MemoryListener *listener,
562                             MemoryRegionSection *section,
563                             bool match_data, uint64_t data,
564                             EventNotifier *e)
565 {
566 }
567
568 static void xen_eventfd_del(MemoryListener *listener,
569                             MemoryRegionSection *section,
570                             bool match_data, uint64_t data,
571                             EventNotifier *e)
572 {
573 }
574
575 static MemoryListener xen_memory_listener = {
576     .begin = xen_begin,
577     .commit = xen_commit,
578     .region_add = xen_region_add,
579     .region_del = xen_region_del,
580     .region_nop = xen_region_nop,
581     .log_start = xen_log_start,
582     .log_stop = xen_log_stop,
583     .log_sync = xen_log_sync,
584     .log_global_start = xen_log_global_start,
585     .log_global_stop = xen_log_global_stop,
586     .eventfd_add = xen_eventfd_add,
587     .eventfd_del = xen_eventfd_del,
588     .priority = 10,
589 };
590
591 /* VCPU Operations, MMIO, IO ring ... */
592
593 static void xen_reset_vcpu(void *opaque)
594 {
595     CPUArchState *env = opaque;
596
597     env->halted = 1;
598 }
599
600 void xen_vcpu_init(void)
601 {
602     CPUArchState *first_cpu;
603
604     if ((first_cpu = qemu_get_cpu(0))) {
605         qemu_register_reset(xen_reset_vcpu, first_cpu);
606         xen_reset_vcpu(first_cpu);
607     }
608     /* if rtc_clock is left to default (host_clock), disable it */
609     if (rtc_clock == host_clock) {
610         qemu_clock_enable(rtc_clock, false);
611     }
612 }
613
614 /* get the ioreq packets from share mem */
615 static ioreq_t *cpu_get_ioreq_from_shared_memory(XenIOState *state, int vcpu)
616 {
617     ioreq_t *req = xen_vcpu_ioreq(state->shared_page, vcpu);
618
619     if (req->state != STATE_IOREQ_READY) {
620         DPRINTF("I/O request not ready: "
621                 "%x, ptr: %x, port: %"PRIx64", "
622                 "data: %"PRIx64", count: %" FMT_ioreq_size ", size: %" FMT_ioreq_size "\n",
623                 req->state, req->data_is_ptr, req->addr,
624                 req->data, req->count, req->size);
625         return NULL;
626     }
627
628     xen_rmb(); /* see IOREQ_READY /then/ read contents of ioreq */
629
630     req->state = STATE_IOREQ_INPROCESS;
631     return req;
632 }
633
634 /* use poll to get the port notification */
635 /* ioreq_vec--out,the */
636 /* retval--the number of ioreq packet */
637 static ioreq_t *cpu_get_ioreq(XenIOState *state)
638 {
639     int i;
640     evtchn_port_t port;
641
642     port = xc_evtchn_pending(state->xce_handle);
643     if (port == state->bufioreq_local_port) {
644         qemu_mod_timer(state->buffered_io_timer,
645                 BUFFER_IO_MAX_DELAY + qemu_get_clock_ms(rt_clock));
646         return NULL;
647     }
648
649     if (port != -1) {
650         for (i = 0; i < smp_cpus; i++) {
651             if (state->ioreq_local_port[i] == port) {
652                 break;
653             }
654         }
655
656         if (i == smp_cpus) {
657             hw_error("Fatal error while trying to get io event!\n");
658         }
659
660         /* unmask the wanted port again */
661         xc_evtchn_unmask(state->xce_handle, port);
662
663         /* get the io packet from shared memory */
664         state->send_vcpu = i;
665         return cpu_get_ioreq_from_shared_memory(state, i);
666     }
667
668     /* read error or read nothing */
669     return NULL;
670 }
671
672 static uint32_t do_inp(pio_addr_t addr, unsigned long size)
673 {
674     switch (size) {
675         case 1:
676             return cpu_inb(addr);
677         case 2:
678             return cpu_inw(addr);
679         case 4:
680             return cpu_inl(addr);
681         default:
682             hw_error("inp: bad size: %04"FMT_pioaddr" %lx", addr, size);
683     }
684 }
685
686 static void do_outp(pio_addr_t addr,
687         unsigned long size, uint32_t val)
688 {
689     switch (size) {
690         case 1:
691             return cpu_outb(addr, val);
692         case 2:
693             return cpu_outw(addr, val);
694         case 4:
695             return cpu_outl(addr, val);
696         default:
697             hw_error("outp: bad size: %04"FMT_pioaddr" %lx", addr, size);
698     }
699 }
700
701 static void cpu_ioreq_pio(ioreq_t *req)
702 {
703     int i, sign;
704
705     sign = req->df ? -1 : 1;
706
707     if (req->dir == IOREQ_READ) {
708         if (!req->data_is_ptr) {
709             req->data = do_inp(req->addr, req->size);
710         } else {
711             uint32_t tmp;
712
713             for (i = 0; i < req->count; i++) {
714                 tmp = do_inp(req->addr, req->size);
715                 cpu_physical_memory_write(
716                         req->data + (sign * i * (int64_t)req->size),
717                         (uint8_t *) &tmp, req->size);
718             }
719         }
720     } else if (req->dir == IOREQ_WRITE) {
721         if (!req->data_is_ptr) {
722             do_outp(req->addr, req->size, req->data);
723         } else {
724             for (i = 0; i < req->count; i++) {
725                 uint32_t tmp = 0;
726
727                 cpu_physical_memory_read(
728                         req->data + (sign * i * (int64_t)req->size),
729                         (uint8_t*) &tmp, req->size);
730                 do_outp(req->addr, req->size, tmp);
731             }
732         }
733     }
734 }
735
736 static void cpu_ioreq_move(ioreq_t *req)
737 {
738     int i, sign;
739
740     sign = req->df ? -1 : 1;
741
742     if (!req->data_is_ptr) {
743         if (req->dir == IOREQ_READ) {
744             for (i = 0; i < req->count; i++) {
745                 cpu_physical_memory_read(
746                         req->addr + (sign * i * (int64_t)req->size),
747                         (uint8_t *) &req->data, req->size);
748             }
749         } else if (req->dir == IOREQ_WRITE) {
750             for (i = 0; i < req->count; i++) {
751                 cpu_physical_memory_write(
752                         req->addr + (sign * i * (int64_t)req->size),
753                         (uint8_t *) &req->data, req->size);
754             }
755         }
756     } else {
757         uint64_t tmp;
758
759         if (req->dir == IOREQ_READ) {
760             for (i = 0; i < req->count; i++) {
761                 cpu_physical_memory_read(
762                         req->addr + (sign * i * (int64_t)req->size),
763                         (uint8_t*) &tmp, req->size);
764                 cpu_physical_memory_write(
765                         req->data + (sign * i * (int64_t)req->size),
766                         (uint8_t*) &tmp, req->size);
767             }
768         } else if (req->dir == IOREQ_WRITE) {
769             for (i = 0; i < req->count; i++) {
770                 cpu_physical_memory_read(
771                         req->data + (sign * i * (int64_t)req->size),
772                         (uint8_t*) &tmp, req->size);
773                 cpu_physical_memory_write(
774                         req->addr + (sign * i * (int64_t)req->size),
775                         (uint8_t*) &tmp, req->size);
776             }
777         }
778     }
779 }
780
781 static void handle_ioreq(ioreq_t *req)
782 {
783     if (!req->data_is_ptr && (req->dir == IOREQ_WRITE) &&
784             (req->size < sizeof (target_ulong))) {
785         req->data &= ((target_ulong) 1 << (8 * req->size)) - 1;
786     }
787
788     switch (req->type) {
789         case IOREQ_TYPE_PIO:
790             cpu_ioreq_pio(req);
791             break;
792         case IOREQ_TYPE_COPY:
793             cpu_ioreq_move(req);
794             break;
795         case IOREQ_TYPE_TIMEOFFSET:
796             break;
797         case IOREQ_TYPE_INVALIDATE:
798             xen_invalidate_map_cache();
799             break;
800         default:
801             hw_error("Invalid ioreq type 0x%x\n", req->type);
802     }
803 }
804
805 static int handle_buffered_iopage(XenIOState *state)
806 {
807     buf_ioreq_t *buf_req = NULL;
808     ioreq_t req;
809     int qw;
810
811     if (!state->buffered_io_page) {
812         return 0;
813     }
814
815     memset(&req, 0x00, sizeof(req));
816
817     while (state->buffered_io_page->read_pointer != state->buffered_io_page->write_pointer) {
818         buf_req = &state->buffered_io_page->buf_ioreq[
819             state->buffered_io_page->read_pointer % IOREQ_BUFFER_SLOT_NUM];
820         req.size = 1UL << buf_req->size;
821         req.count = 1;
822         req.addr = buf_req->addr;
823         req.data = buf_req->data;
824         req.state = STATE_IOREQ_READY;
825         req.dir = buf_req->dir;
826         req.df = 1;
827         req.type = buf_req->type;
828         req.data_is_ptr = 0;
829         qw = (req.size == 8);
830         if (qw) {
831             buf_req = &state->buffered_io_page->buf_ioreq[
832                 (state->buffered_io_page->read_pointer + 1) % IOREQ_BUFFER_SLOT_NUM];
833             req.data |= ((uint64_t)buf_req->data) << 32;
834         }
835
836         handle_ioreq(&req);
837
838         xen_mb();
839         state->buffered_io_page->read_pointer += qw ? 2 : 1;
840     }
841
842     return req.count;
843 }
844
845 static void handle_buffered_io(void *opaque)
846 {
847     XenIOState *state = opaque;
848
849     if (handle_buffered_iopage(state)) {
850         qemu_mod_timer(state->buffered_io_timer,
851                 BUFFER_IO_MAX_DELAY + qemu_get_clock_ms(rt_clock));
852     } else {
853         qemu_del_timer(state->buffered_io_timer);
854         xc_evtchn_unmask(state->xce_handle, state->bufioreq_local_port);
855     }
856 }
857
858 static void cpu_handle_ioreq(void *opaque)
859 {
860     XenIOState *state = opaque;
861     ioreq_t *req = cpu_get_ioreq(state);
862
863     handle_buffered_iopage(state);
864     if (req) {
865         handle_ioreq(req);
866
867         if (req->state != STATE_IOREQ_INPROCESS) {
868             fprintf(stderr, "Badness in I/O request ... not in service?!: "
869                     "%x, ptr: %x, port: %"PRIx64", "
870                     "data: %"PRIx64", count: %" FMT_ioreq_size ", size: %" FMT_ioreq_size "\n",
871                     req->state, req->data_is_ptr, req->addr,
872                     req->data, req->count, req->size);
873             destroy_hvm_domain(false);
874             return;
875         }
876
877         xen_wmb(); /* Update ioreq contents /then/ update state. */
878
879         /*
880          * We do this before we send the response so that the tools
881          * have the opportunity to pick up on the reset before the
882          * guest resumes and does a hlt with interrupts disabled which
883          * causes Xen to powerdown the domain.
884          */
885         if (runstate_is_running()) {
886             if (qemu_shutdown_requested_get()) {
887                 destroy_hvm_domain(false);
888             }
889             if (qemu_reset_requested_get()) {
890                 qemu_system_reset(VMRESET_REPORT);
891                 destroy_hvm_domain(true);
892             }
893         }
894
895         req->state = STATE_IORESP_READY;
896         xc_evtchn_notify(state->xce_handle, state->ioreq_local_port[state->send_vcpu]);
897     }
898 }
899
900 static int store_dev_info(int domid, CharDriverState *cs, const char *string)
901 {
902     struct xs_handle *xs = NULL;
903     char *path = NULL;
904     char *newpath = NULL;
905     char *pts = NULL;
906     int ret = -1;
907
908     /* Only continue if we're talking to a pty. */
909     if (strncmp(cs->filename, "pty:", 4)) {
910         return 0;
911     }
912     pts = cs->filename + 4;
913
914     /* We now have everything we need to set the xenstore entry. */
915     xs = xs_open(0);
916     if (xs == NULL) {
917         fprintf(stderr, "Could not contact XenStore\n");
918         goto out;
919     }
920
921     path = xs_get_domain_path(xs, domid);
922     if (path == NULL) {
923         fprintf(stderr, "xs_get_domain_path() error\n");
924         goto out;
925     }
926     newpath = realloc(path, (strlen(path) + strlen(string) +
927                 strlen("/tty") + 1));
928     if (newpath == NULL) {
929         fprintf(stderr, "realloc error\n");
930         goto out;
931     }
932     path = newpath;
933
934     strcat(path, string);
935     strcat(path, "/tty");
936     if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
937         fprintf(stderr, "xs_write for '%s' fail", string);
938         goto out;
939     }
940     ret = 0;
941
942 out:
943     free(path);
944     xs_close(xs);
945
946     return ret;
947 }
948
949 void xenstore_store_pv_console_info(int i, CharDriverState *chr)
950 {
951     if (i == 0) {
952         store_dev_info(xen_domid, chr, "/console");
953     } else {
954         char buf[32];
955         snprintf(buf, sizeof(buf), "/device/console/%d", i);
956         store_dev_info(xen_domid, chr, buf);
957     }
958 }
959
960 static void xenstore_record_dm_state(struct xs_handle *xs, const char *state)
961 {
962     char path[50];
963
964     if (xs == NULL) {
965         fprintf(stderr, "xenstore connection not initialized\n");
966         exit(1);
967     }
968
969     snprintf(path, sizeof (path), "/local/domain/0/device-model/%u/state", xen_domid);
970     if (!xs_write(xs, XBT_NULL, path, state, strlen(state))) {
971         fprintf(stderr, "error recording dm state\n");
972         exit(1);
973     }
974 }
975
976 static void xen_main_loop_prepare(XenIOState *state)
977 {
978     int evtchn_fd = -1;
979
980     if (state->xce_handle != XC_HANDLER_INITIAL_VALUE) {
981         evtchn_fd = xc_evtchn_fd(state->xce_handle);
982     }
983
984     state->buffered_io_timer = qemu_new_timer_ms(rt_clock, handle_buffered_io,
985                                                  state);
986
987     if (evtchn_fd != -1) {
988         qemu_set_fd_handler(evtchn_fd, cpu_handle_ioreq, NULL, state);
989     }
990 }
991
992
993 /* Initialise Xen */
994
995 static void xen_change_state_handler(void *opaque, int running,
996                                      RunState state)
997 {
998     if (running) {
999         /* record state running */
1000         xenstore_record_dm_state(xenstore, "running");
1001     }
1002 }
1003
1004 static void xen_hvm_change_state_handler(void *opaque, int running,
1005                                          RunState rstate)
1006 {
1007     XenIOState *xstate = opaque;
1008     if (running) {
1009         xen_main_loop_prepare(xstate);
1010     }
1011 }
1012
1013 static void xen_exit_notifier(Notifier *n, void *data)
1014 {
1015     XenIOState *state = container_of(n, XenIOState, exit);
1016
1017     xc_evtchn_close(state->xce_handle);
1018     xs_daemon_close(state->xenstore);
1019 }
1020
1021 int xen_init(void)
1022 {
1023     xen_xc = xen_xc_interface_open(0, 0, 0);
1024     if (xen_xc == XC_HANDLER_INITIAL_VALUE) {
1025         xen_be_printf(NULL, 0, "can't open xen interface\n");
1026         return -1;
1027     }
1028     qemu_add_vm_change_state_handler(xen_change_state_handler, NULL);
1029
1030     return 0;
1031 }
1032
1033 static void xen_read_physmap(XenIOState *state)
1034 {
1035     XenPhysmap *physmap = NULL;
1036     unsigned int len, num, i;
1037     char path[80], *value = NULL;
1038     char **entries = NULL;
1039
1040     snprintf(path, sizeof(path),
1041             "/local/domain/0/device-model/%d/physmap", xen_domid);
1042     entries = xs_directory(state->xenstore, 0, path, &num);
1043     if (entries == NULL)
1044         return;
1045
1046     for (i = 0; i < num; i++) {
1047         physmap = g_malloc(sizeof (XenPhysmap));
1048         physmap->phys_offset = strtoull(entries[i], NULL, 16);
1049         snprintf(path, sizeof(path),
1050                 "/local/domain/0/device-model/%d/physmap/%s/start_addr",
1051                 xen_domid, entries[i]);
1052         value = xs_read(state->xenstore, 0, path, &len);
1053         if (value == NULL) {
1054             free(physmap);
1055             continue;
1056         }
1057         physmap->start_addr = strtoull(value, NULL, 16);
1058         free(value);
1059
1060         snprintf(path, sizeof(path),
1061                 "/local/domain/0/device-model/%d/physmap/%s/size",
1062                 xen_domid, entries[i]);
1063         value = xs_read(state->xenstore, 0, path, &len);
1064         if (value == NULL) {
1065             free(physmap);
1066             continue;
1067         }
1068         physmap->size = strtoull(value, NULL, 16);
1069         free(value);
1070
1071         snprintf(path, sizeof(path),
1072                 "/local/domain/0/device-model/%d/physmap/%s/name",
1073                 xen_domid, entries[i]);
1074         physmap->name = xs_read(state->xenstore, 0, path, &len);
1075
1076         QLIST_INSERT_HEAD(&state->physmap, physmap, list);
1077     }
1078     free(entries);
1079     return;
1080 }
1081
1082 int xen_hvm_init(void)
1083 {
1084     int i, rc;
1085     unsigned long ioreq_pfn;
1086     unsigned long bufioreq_evtchn;
1087     XenIOState *state;
1088
1089     state = g_malloc0(sizeof (XenIOState));
1090
1091     state->xce_handle = xen_xc_evtchn_open(NULL, 0);
1092     if (state->xce_handle == XC_HANDLER_INITIAL_VALUE) {
1093         perror("xen: event channel open");
1094         return -errno;
1095     }
1096
1097     state->xenstore = xs_daemon_open();
1098     if (state->xenstore == NULL) {
1099         perror("xen: xenstore open");
1100         return -errno;
1101     }
1102
1103     state->exit.notify = xen_exit_notifier;
1104     qemu_add_exit_notifier(&state->exit);
1105
1106     state->suspend.notify = xen_suspend_notifier;
1107     qemu_register_suspend_notifier(&state->suspend);
1108
1109     xc_get_hvm_param(xen_xc, xen_domid, HVM_PARAM_IOREQ_PFN, &ioreq_pfn);
1110     DPRINTF("shared page at pfn %lx\n", ioreq_pfn);
1111     state->shared_page = xc_map_foreign_range(xen_xc, xen_domid, XC_PAGE_SIZE,
1112                                               PROT_READ|PROT_WRITE, ioreq_pfn);
1113     if (state->shared_page == NULL) {
1114         hw_error("map shared IO page returned error %d handle=" XC_INTERFACE_FMT,
1115                  errno, xen_xc);
1116     }
1117
1118     xc_get_hvm_param(xen_xc, xen_domid, HVM_PARAM_BUFIOREQ_PFN, &ioreq_pfn);
1119     DPRINTF("buffered io page at pfn %lx\n", ioreq_pfn);
1120     state->buffered_io_page = xc_map_foreign_range(xen_xc, xen_domid, XC_PAGE_SIZE,
1121                                                    PROT_READ|PROT_WRITE, ioreq_pfn);
1122     if (state->buffered_io_page == NULL) {
1123         hw_error("map buffered IO page returned error %d", errno);
1124     }
1125
1126     state->ioreq_local_port = g_malloc0(smp_cpus * sizeof (evtchn_port_t));
1127
1128     /* FIXME: how about if we overflow the page here? */
1129     for (i = 0; i < smp_cpus; i++) {
1130         rc = xc_evtchn_bind_interdomain(state->xce_handle, xen_domid,
1131                                         xen_vcpu_eport(state->shared_page, i));
1132         if (rc == -1) {
1133             fprintf(stderr, "bind interdomain ioctl error %d\n", errno);
1134             return -1;
1135         }
1136         state->ioreq_local_port[i] = rc;
1137     }
1138
1139     rc = xc_get_hvm_param(xen_xc, xen_domid, HVM_PARAM_BUFIOREQ_EVTCHN,
1140             &bufioreq_evtchn);
1141     if (rc < 0) {
1142         fprintf(stderr, "failed to get HVM_PARAM_BUFIOREQ_EVTCHN\n");
1143         return -1;
1144     }
1145     rc = xc_evtchn_bind_interdomain(state->xce_handle, xen_domid,
1146             (uint32_t)bufioreq_evtchn);
1147     if (rc == -1) {
1148         fprintf(stderr, "bind interdomain ioctl error %d\n", errno);
1149         return -1;
1150     }
1151     state->bufioreq_local_port = rc;
1152
1153     /* Init RAM management */
1154     xen_map_cache_init(xen_phys_offset_to_gaddr, state);
1155     xen_ram_init(ram_size);
1156
1157     qemu_add_vm_change_state_handler(xen_hvm_change_state_handler, state);
1158
1159     state->memory_listener = xen_memory_listener;
1160     QLIST_INIT(&state->physmap);
1161     memory_listener_register(&state->memory_listener, get_system_memory());
1162     state->log_for_dirtybit = NULL;
1163
1164     /* Initialize backend core & drivers */
1165     if (xen_be_init() != 0) {
1166         fprintf(stderr, "%s: xen backend core setup failed\n", __FUNCTION__);
1167         exit(1);
1168     }
1169     xen_be_register("console", &xen_console_ops);
1170     xen_be_register("vkbd", &xen_kbdmouse_ops);
1171     xen_be_register("qdisk", &xen_blkdev_ops);
1172     xen_read_physmap(state);
1173
1174     return 0;
1175 }
1176
1177 void destroy_hvm_domain(bool reboot)
1178 {
1179     XenXC xc_handle;
1180     int sts;
1181
1182     xc_handle = xen_xc_interface_open(0, 0, 0);
1183     if (xc_handle == XC_HANDLER_INITIAL_VALUE) {
1184         fprintf(stderr, "Cannot acquire xenctrl handle\n");
1185     } else {
1186         sts = xc_domain_shutdown(xc_handle, xen_domid,
1187                                  reboot ? SHUTDOWN_reboot : SHUTDOWN_poweroff);
1188         if (sts != 0) {
1189             fprintf(stderr, "xc_domain_shutdown failed to issue %s, "
1190                     "sts %d, %s\n", reboot ? "reboot" : "poweroff",
1191                     sts, strerror(errno));
1192         } else {
1193             fprintf(stderr, "Issued domain %d %s\n", xen_domid,
1194                     reboot ? "reboot" : "poweroff");
1195         }
1196         xc_interface_close(xc_handle);
1197     }
1198 }
1199
1200 void xen_register_framebuffer(MemoryRegion *mr)
1201 {
1202     framebuffer = mr;
1203 }
1204
1205 void xen_shutdown_fatal_error(const char *fmt, ...)
1206 {
1207     va_list ap;
1208
1209     va_start(ap, fmt);
1210     vfprintf(stderr, fmt, ap);
1211     va_end(ap);
1212     fprintf(stderr, "Will destroy the domain.\n");
1213     /* destroy the domain */
1214     qemu_system_shutdown_request();
1215 }