sensor: add pedometer sensor device
[sdk/emulator/qemu.git] / cpus.c
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24
25 /* Needed early for CONFIG_BSD etc. */
26 #include "config-host.h"
27
28 #include "monitor/monitor.h"
29 #include "qapi/qmp/qerror.h"
30 #include "qemu/error-report.h"
31 #include "sysemu/sysemu.h"
32 #include "exec/gdbstub.h"
33 #include "sysemu/dma.h"
34 #include "sysemu/kvm.h"
35 #include "sysemu/hax.h"
36 #include "qmp-commands.h"
37
38 #include "qemu/thread.h"
39 #include "sysemu/cpus.h"
40 #include "sysemu/qtest.h"
41 #include "qemu/main-loop.h"
42 #include "qemu/bitmap.h"
43 #include "qemu/seqlock.h"
44 #include "qapi-event.h"
45 #include "hw/nmi.h"
46 #include "sysemu/replay.h"
47
48 #ifndef _WIN32
49 #include "qemu/compatfd.h"
50 #endif
51
52 #ifdef CONFIG_LINUX
53
54 #include <sys/prctl.h>
55
56 #ifndef PR_MCE_KILL
57 #define PR_MCE_KILL 33
58 #endif
59
60 #ifndef PR_MCE_KILL_SET
61 #define PR_MCE_KILL_SET 1
62 #endif
63
64 #ifndef PR_MCE_KILL_EARLY
65 #define PR_MCE_KILL_EARLY 1
66 #endif
67
68 #endif /* CONFIG_LINUX */
69
70 static CPUState *next_cpu;
71 int64_t max_delay;
72 int64_t max_advance;
73
74 /* vcpu throttling controls */
75 static QEMUTimer *throttle_timer;
76 static unsigned int throttle_percentage;
77
78 #define CPU_THROTTLE_PCT_MIN 1
79 #define CPU_THROTTLE_PCT_MAX 99
80 #define CPU_THROTTLE_TIMESLICE_NS 10000000
81
82 bool cpu_is_stopped(CPUState *cpu)
83 {
84     return cpu->stopped || !runstate_is_running();
85 }
86
87 static bool cpu_thread_is_idle(CPUState *cpu)
88 {
89     if (cpu->stop || cpu->queued_work_first) {
90         return false;
91     }
92     if (cpu_is_stopped(cpu)) {
93         return true;
94     }
95     if (!cpu->halted || cpu_has_work(cpu) ||
96         kvm_halt_in_kernel()) {
97         return false;
98     }
99     return true;
100 }
101
102 static bool all_cpu_threads_idle(void)
103 {
104     CPUState *cpu;
105
106     CPU_FOREACH(cpu) {
107         if (!cpu_thread_is_idle(cpu)) {
108             return false;
109         }
110     }
111     return true;
112 }
113
114 /***********************************************************/
115 /* guest cycle counter */
116
117 /* Protected by TimersState seqlock */
118
119 static bool icount_sleep = true;
120 static int64_t vm_clock_warp_start = -1;
121 /* Conversion factor from emulated instructions to virtual clock ticks.  */
122 static int icount_time_shift;
123 /* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
124 #define MAX_ICOUNT_SHIFT 10
125
126 static QEMUTimer *icount_rt_timer;
127 static QEMUTimer *icount_vm_timer;
128 static QEMUTimer *icount_warp_timer;
129
130 typedef struct TimersState {
131     /* Protected by BQL.  */
132     int64_t cpu_ticks_prev;
133     int64_t cpu_ticks_offset;
134
135     /* cpu_clock_offset can be read out of BQL, so protect it with
136      * this lock.
137      */
138     QemuSeqLock vm_clock_seqlock;
139     int64_t cpu_clock_offset;
140     int32_t cpu_ticks_enabled;
141     int64_t dummy;
142
143     /* Compensate for varying guest execution speed.  */
144     int64_t qemu_icount_bias;
145     /* Only written by TCG thread */
146     int64_t qemu_icount;
147 } TimersState;
148
149 static TimersState timers_state;
150
151 int64_t cpu_get_icount_raw(void)
152 {
153     int64_t icount;
154     CPUState *cpu = current_cpu;
155
156     icount = timers_state.qemu_icount;
157     if (cpu) {
158         if (!cpu->can_do_io) {
159             fprintf(stderr, "Bad icount read\n");
160             exit(1);
161         }
162         icount -= (cpu->icount_decr.u16.low + cpu->icount_extra);
163     }
164     return icount;
165 }
166
167 /* Return the virtual CPU time, based on the instruction counter.  */
168 static int64_t cpu_get_icount_locked(void)
169 {
170     int64_t icount = cpu_get_icount_raw();
171     return timers_state.qemu_icount_bias + cpu_icount_to_ns(icount);
172 }
173
174 int64_t cpu_get_icount(void)
175 {
176     int64_t icount;
177     unsigned start;
178
179     do {
180         start = seqlock_read_begin(&timers_state.vm_clock_seqlock);
181         icount = cpu_get_icount_locked();
182     } while (seqlock_read_retry(&timers_state.vm_clock_seqlock, start));
183
184     return icount;
185 }
186
187 int64_t cpu_icount_to_ns(int64_t icount)
188 {
189     return icount << icount_time_shift;
190 }
191
192 /* return the host CPU cycle counter and handle stop/restart */
193 /* Caller must hold the BQL */
194 int64_t cpu_get_ticks(void)
195 {
196     int64_t ticks;
197
198     if (use_icount) {
199         return cpu_get_icount();
200     }
201
202     ticks = timers_state.cpu_ticks_offset;
203     if (timers_state.cpu_ticks_enabled) {
204         ticks += cpu_get_host_ticks();
205     }
206
207     if (timers_state.cpu_ticks_prev > ticks) {
208         /* Note: non increasing ticks may happen if the host uses
209            software suspend */
210         timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
211         ticks = timers_state.cpu_ticks_prev;
212     }
213
214     timers_state.cpu_ticks_prev = ticks;
215     return ticks;
216 }
217
218 static int64_t cpu_get_clock_locked(void)
219 {
220     int64_t ticks;
221
222     ticks = timers_state.cpu_clock_offset;
223     if (timers_state.cpu_ticks_enabled) {
224         ticks += get_clock();
225     }
226
227     return ticks;
228 }
229
230 /* return the host CPU monotonic timer and handle stop/restart */
231 int64_t cpu_get_clock(void)
232 {
233     int64_t ti;
234     unsigned start;
235
236     do {
237         start = seqlock_read_begin(&timers_state.vm_clock_seqlock);
238         ti = cpu_get_clock_locked();
239     } while (seqlock_read_retry(&timers_state.vm_clock_seqlock, start));
240
241     return ti;
242 }
243
244 /* enable cpu_get_ticks()
245  * Caller must hold BQL which server as mutex for vm_clock_seqlock.
246  */
247 void cpu_enable_ticks(void)
248 {
249     /* Here, the really thing protected by seqlock is cpu_clock_offset. */
250     seqlock_write_lock(&timers_state.vm_clock_seqlock);
251     if (!timers_state.cpu_ticks_enabled) {
252         timers_state.cpu_ticks_offset -= cpu_get_host_ticks();
253         timers_state.cpu_clock_offset -= get_clock();
254         timers_state.cpu_ticks_enabled = 1;
255     }
256     seqlock_write_unlock(&timers_state.vm_clock_seqlock);
257 }
258
259 /* disable cpu_get_ticks() : the clock is stopped. You must not call
260  * cpu_get_ticks() after that.
261  * Caller must hold BQL which server as mutex for vm_clock_seqlock.
262  */
263 void cpu_disable_ticks(void)
264 {
265     /* Here, the really thing protected by seqlock is cpu_clock_offset. */
266     seqlock_write_lock(&timers_state.vm_clock_seqlock);
267     if (timers_state.cpu_ticks_enabled) {
268         timers_state.cpu_ticks_offset += cpu_get_host_ticks();
269         timers_state.cpu_clock_offset = cpu_get_clock_locked();
270         timers_state.cpu_ticks_enabled = 0;
271     }
272     seqlock_write_unlock(&timers_state.vm_clock_seqlock);
273 }
274
275 /* Correlation between real and virtual time is always going to be
276    fairly approximate, so ignore small variation.
277    When the guest is idle real and virtual time will be aligned in
278    the IO wait loop.  */
279 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
280
281 static void icount_adjust(void)
282 {
283     int64_t cur_time;
284     int64_t cur_icount;
285     int64_t delta;
286
287     /* Protected by TimersState mutex.  */
288     static int64_t last_delta;
289
290     /* If the VM is not running, then do nothing.  */
291     if (!runstate_is_running()) {
292         return;
293     }
294
295     seqlock_write_lock(&timers_state.vm_clock_seqlock);
296     cur_time = cpu_get_clock_locked();
297     cur_icount = cpu_get_icount_locked();
298
299     delta = cur_icount - cur_time;
300     /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
301     if (delta > 0
302         && last_delta + ICOUNT_WOBBLE < delta * 2
303         && icount_time_shift > 0) {
304         /* The guest is getting too far ahead.  Slow time down.  */
305         icount_time_shift--;
306     }
307     if (delta < 0
308         && last_delta - ICOUNT_WOBBLE > delta * 2
309         && icount_time_shift < MAX_ICOUNT_SHIFT) {
310         /* The guest is getting too far behind.  Speed time up.  */
311         icount_time_shift++;
312     }
313     last_delta = delta;
314     timers_state.qemu_icount_bias = cur_icount
315                               - (timers_state.qemu_icount << icount_time_shift);
316     seqlock_write_unlock(&timers_state.vm_clock_seqlock);
317 }
318
319 static void icount_adjust_rt(void *opaque)
320 {
321     timer_mod(icount_rt_timer,
322               qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL_RT) + 1000);
323     icount_adjust();
324 }
325
326 static void icount_adjust_vm(void *opaque)
327 {
328     timer_mod(icount_vm_timer,
329                    qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
330                    get_ticks_per_sec() / 10);
331     icount_adjust();
332 }
333
334 static int64_t qemu_icount_round(int64_t count)
335 {
336     return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
337 }
338
339 static void icount_warp_rt(void)
340 {
341     /* The icount_warp_timer is rescheduled soon after vm_clock_warp_start
342      * changes from -1 to another value, so the race here is okay.
343      */
344     if (atomic_read(&vm_clock_warp_start) == -1) {
345         return;
346     }
347
348     seqlock_write_lock(&timers_state.vm_clock_seqlock);
349     if (runstate_is_running()) {
350         int64_t clock = REPLAY_CLOCK(REPLAY_CLOCK_VIRTUAL_RT,
351                                      cpu_get_clock_locked());
352         int64_t warp_delta;
353
354         warp_delta = clock - vm_clock_warp_start;
355         if (use_icount == 2) {
356             /*
357              * In adaptive mode, do not let QEMU_CLOCK_VIRTUAL run too
358              * far ahead of real time.
359              */
360             int64_t cur_icount = cpu_get_icount_locked();
361             int64_t delta = clock - cur_icount;
362             warp_delta = MIN(warp_delta, delta);
363         }
364         timers_state.qemu_icount_bias += warp_delta;
365     }
366     vm_clock_warp_start = -1;
367     seqlock_write_unlock(&timers_state.vm_clock_seqlock);
368
369     if (qemu_clock_expired(QEMU_CLOCK_VIRTUAL)) {
370         qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
371     }
372 }
373
374 static void icount_dummy_timer(void *opaque)
375 {
376     (void)opaque;
377 }
378
379 void qtest_clock_warp(int64_t dest)
380 {
381     int64_t clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
382     AioContext *aio_context;
383     assert(qtest_enabled());
384     aio_context = qemu_get_aio_context();
385     while (clock < dest) {
386         int64_t deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);
387         int64_t warp = qemu_soonest_timeout(dest - clock, deadline);
388
389         seqlock_write_lock(&timers_state.vm_clock_seqlock);
390         timers_state.qemu_icount_bias += warp;
391         seqlock_write_unlock(&timers_state.vm_clock_seqlock);
392
393         qemu_clock_run_timers(QEMU_CLOCK_VIRTUAL);
394         timerlist_run_timers(aio_context->tlg.tl[QEMU_CLOCK_VIRTUAL]);
395         clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
396     }
397     qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
398 }
399
400 void qemu_clock_warp(QEMUClockType type)
401 {
402     int64_t clock;
403     int64_t deadline;
404
405     /*
406      * There are too many global variables to make the "warp" behavior
407      * applicable to other clocks.  But a clock argument removes the
408      * need for if statements all over the place.
409      */
410     if (type != QEMU_CLOCK_VIRTUAL || !use_icount) {
411         return;
412     }
413
414     /* Nothing to do if the VM is stopped: QEMU_CLOCK_VIRTUAL timers
415      * do not fire, so computing the deadline does not make sense.
416      */
417     if (!runstate_is_running()) {
418         return;
419     }
420
421     /* warp clock deterministically in record/replay mode */
422     if (!replay_checkpoint(CHECKPOINT_CLOCK_WARP)) {
423         return;
424     }
425
426     if (icount_sleep) {
427         /*
428          * If the CPUs have been sleeping, advance QEMU_CLOCK_VIRTUAL timer now.
429          * This ensures that the deadline for the timer is computed correctly
430          * below.
431          * This also makes sure that the insn counter is synchronized before
432          * the CPU starts running, in case the CPU is woken by an event other
433          * than the earliest QEMU_CLOCK_VIRTUAL timer.
434          */
435         icount_warp_rt();
436         timer_del(icount_warp_timer);
437     }
438     if (!all_cpu_threads_idle()) {
439         return;
440     }
441
442     if (qtest_enabled()) {
443         /* When testing, qtest commands advance icount.  */
444         return;
445     }
446
447     /* We want to use the earliest deadline from ALL vm_clocks */
448     clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT);
449     deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);
450     if (deadline < 0) {
451         static bool notified;
452         if (!icount_sleep && !notified) {
453             error_report("WARNING: icount sleep disabled and no active timers");
454             notified = true;
455         }
456         return;
457     }
458
459     if (deadline > 0) {
460         /*
461          * Ensure QEMU_CLOCK_VIRTUAL proceeds even when the virtual CPU goes to
462          * sleep.  Otherwise, the CPU might be waiting for a future timer
463          * interrupt to wake it up, but the interrupt never comes because
464          * the vCPU isn't running any insns and thus doesn't advance the
465          * QEMU_CLOCK_VIRTUAL.
466          */
467         if (!icount_sleep) {
468             /*
469              * We never let VCPUs sleep in no sleep icount mode.
470              * If there is a pending QEMU_CLOCK_VIRTUAL timer we just advance
471              * to the next QEMU_CLOCK_VIRTUAL event and notify it.
472              * It is useful when we want a deterministic execution time,
473              * isolated from host latencies.
474              */
475             seqlock_write_lock(&timers_state.vm_clock_seqlock);
476             timers_state.qemu_icount_bias += deadline;
477             seqlock_write_unlock(&timers_state.vm_clock_seqlock);
478             qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
479         } else {
480             /*
481              * We do stop VCPUs and only advance QEMU_CLOCK_VIRTUAL after some
482              * "real" time, (related to the time left until the next event) has
483              * passed. The QEMU_CLOCK_VIRTUAL_RT clock will do this.
484              * This avoids that the warps are visible externally; for example,
485              * you will not be sending network packets continuously instead of
486              * every 100ms.
487              */
488             seqlock_write_lock(&timers_state.vm_clock_seqlock);
489             if (vm_clock_warp_start == -1 || vm_clock_warp_start > clock) {
490                 vm_clock_warp_start = clock;
491             }
492             seqlock_write_unlock(&timers_state.vm_clock_seqlock);
493             timer_mod_anticipate(icount_warp_timer, clock + deadline);
494         }
495     } else if (deadline == 0) {
496         qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
497     }
498 }
499
500 static bool icount_state_needed(void *opaque)
501 {
502     return use_icount;
503 }
504
505 /*
506  * This is a subsection for icount migration.
507  */
508 static const VMStateDescription icount_vmstate_timers = {
509     .name = "timer/icount",
510     .version_id = 1,
511     .minimum_version_id = 1,
512     .needed = icount_state_needed,
513     .fields = (VMStateField[]) {
514         VMSTATE_INT64(qemu_icount_bias, TimersState),
515         VMSTATE_INT64(qemu_icount, TimersState),
516         VMSTATE_END_OF_LIST()
517     }
518 };
519
520 static const VMStateDescription vmstate_timers = {
521     .name = "timer",
522     .version_id = 2,
523     .minimum_version_id = 1,
524     .fields = (VMStateField[]) {
525         VMSTATE_INT64(cpu_ticks_offset, TimersState),
526         VMSTATE_INT64(dummy, TimersState),
527         VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
528         VMSTATE_END_OF_LIST()
529     },
530     .subsections = (const VMStateDescription*[]) {
531         &icount_vmstate_timers,
532         NULL
533     }
534 };
535
536 static void cpu_throttle_thread(void *opaque)
537 {
538     CPUState *cpu = opaque;
539     double pct;
540     double throttle_ratio;
541     long sleeptime_ns;
542
543     if (!cpu_throttle_get_percentage()) {
544         return;
545     }
546
547     pct = (double)cpu_throttle_get_percentage()/100;
548     throttle_ratio = pct / (1 - pct);
549     sleeptime_ns = (long)(throttle_ratio * CPU_THROTTLE_TIMESLICE_NS);
550
551     qemu_mutex_unlock_iothread();
552     atomic_set(&cpu->throttle_thread_scheduled, 0);
553     g_usleep(sleeptime_ns / 1000); /* Convert ns to us for usleep call */
554     qemu_mutex_lock_iothread();
555 }
556
557 static void cpu_throttle_timer_tick(void *opaque)
558 {
559     CPUState *cpu;
560     double pct;
561
562     /* Stop the timer if needed */
563     if (!cpu_throttle_get_percentage()) {
564         return;
565     }
566     CPU_FOREACH(cpu) {
567         if (!atomic_xchg(&cpu->throttle_thread_scheduled, 1)) {
568             async_run_on_cpu(cpu, cpu_throttle_thread, cpu);
569         }
570     }
571
572     pct = (double)cpu_throttle_get_percentage()/100;
573     timer_mod(throttle_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT) +
574                                    CPU_THROTTLE_TIMESLICE_NS / (1-pct));
575 }
576
577 void cpu_throttle_set(int new_throttle_pct)
578 {
579     /* Ensure throttle percentage is within valid range */
580     new_throttle_pct = MIN(new_throttle_pct, CPU_THROTTLE_PCT_MAX);
581     new_throttle_pct = MAX(new_throttle_pct, CPU_THROTTLE_PCT_MIN);
582
583     atomic_set(&throttle_percentage, new_throttle_pct);
584
585     timer_mod(throttle_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT) +
586                                        CPU_THROTTLE_TIMESLICE_NS);
587 }
588
589 void cpu_throttle_stop(void)
590 {
591     atomic_set(&throttle_percentage, 0);
592 }
593
594 bool cpu_throttle_active(void)
595 {
596     return (cpu_throttle_get_percentage() != 0);
597 }
598
599 int cpu_throttle_get_percentage(void)
600 {
601     return atomic_read(&throttle_percentage);
602 }
603
604 void cpu_ticks_init(void)
605 {
606     seqlock_init(&timers_state.vm_clock_seqlock, NULL);
607     vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
608     throttle_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL_RT,
609                                            cpu_throttle_timer_tick, NULL);
610 }
611
612 void configure_icount(QemuOpts *opts, Error **errp)
613 {
614     const char *option;
615     char *rem_str = NULL;
616
617     option = qemu_opt_get(opts, "shift");
618     if (!option) {
619         if (qemu_opt_get(opts, "align") != NULL) {
620             error_setg(errp, "Please specify shift option when using align");
621         }
622         return;
623     }
624
625     icount_sleep = qemu_opt_get_bool(opts, "sleep", true);
626     if (icount_sleep) {
627         icount_warp_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL_RT,
628                                          icount_dummy_timer, NULL);
629     }
630
631     icount_align_option = qemu_opt_get_bool(opts, "align", false);
632
633     if (icount_align_option && !icount_sleep) {
634         error_setg(errp, "align=on and sleep=no are incompatible");
635     }
636     if (strcmp(option, "auto") != 0) {
637         errno = 0;
638         icount_time_shift = strtol(option, &rem_str, 0);
639         if (errno != 0 || *rem_str != '\0' || !strlen(option)) {
640             error_setg(errp, "icount: Invalid shift value");
641         }
642         use_icount = 1;
643         return;
644     } else if (icount_align_option) {
645         error_setg(errp, "shift=auto and align=on are incompatible");
646     } else if (!icount_sleep) {
647         error_setg(errp, "shift=auto and sleep=no are incompatible");
648     }
649
650     use_icount = 2;
651
652     /* 125MIPS seems a reasonable initial guess at the guest speed.
653        It will be corrected fairly quickly anyway.  */
654     icount_time_shift = 3;
655
656     /* Have both realtime and virtual time triggers for speed adjustment.
657        The realtime trigger catches emulated time passing too slowly,
658        the virtual time trigger catches emulated time passing too fast.
659        Realtime triggers occur even when idle, so use them less frequently
660        than VM triggers.  */
661     icount_rt_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL_RT,
662                                    icount_adjust_rt, NULL);
663     timer_mod(icount_rt_timer,
664                    qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL_RT) + 1000);
665     icount_vm_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
666                                         icount_adjust_vm, NULL);
667     timer_mod(icount_vm_timer,
668                    qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
669                    get_ticks_per_sec() / 10);
670 }
671
672 /***********************************************************/
673 void hw_error(const char *fmt, ...)
674 {
675     va_list ap;
676     CPUState *cpu;
677
678     va_start(ap, fmt);
679     fprintf(stderr, "qemu: hardware error: ");
680     vfprintf(stderr, fmt, ap);
681     fprintf(stderr, "\n");
682     CPU_FOREACH(cpu) {
683         fprintf(stderr, "CPU #%d:\n", cpu->cpu_index);
684         cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU);
685     }
686     va_end(ap);
687     abort();
688 }
689
690 void cpu_synchronize_all_states(void)
691 {
692     CPUState *cpu;
693
694     CPU_FOREACH(cpu) {
695         cpu_synchronize_state(cpu);
696     }
697 }
698
699 void cpu_synchronize_all_post_reset(void)
700 {
701     CPUState *cpu;
702
703     CPU_FOREACH(cpu) {
704         cpu_synchronize_post_reset(cpu);
705 #ifdef CONFIG_HAX
706         if (hax_enabled() && hax_ug_platform())
707             hax_cpu_synchronize_post_reset(cpu);
708 #endif
709     }
710 }
711
712 void cpu_synchronize_all_post_init(void)
713 {
714     CPUState *cpu;
715
716     CPU_FOREACH(cpu) {
717         cpu_synchronize_post_init(cpu);
718 #ifdef CONFIG_HAX
719         if (hax_enabled() && hax_ug_platform())
720             hax_cpu_synchronize_post_init(cpu);
721 #endif
722     }
723 }
724
725 static int do_vm_stop(RunState state)
726 {
727     int ret = 0;
728
729     if (runstate_is_running()) {
730         cpu_disable_ticks();
731         pause_all_vcpus();
732         runstate_set(state);
733         vm_state_notify(0, state);
734         qapi_event_send_stop(&error_abort);
735     }
736
737     bdrv_drain_all();
738     ret = bdrv_flush_all();
739
740     return ret;
741 }
742
743 static bool cpu_can_run(CPUState *cpu)
744 {
745     if (cpu->stop) {
746         return false;
747     }
748     if (cpu_is_stopped(cpu)) {
749         return false;
750     }
751     return true;
752 }
753
754 static void cpu_handle_guest_debug(CPUState *cpu)
755 {
756     gdb_set_stop_cpu(cpu);
757     qemu_system_debug_request();
758     cpu->stopped = true;
759 }
760
761 #ifdef CONFIG_LINUX
762 static void sigbus_reraise(void)
763 {
764     sigset_t set;
765     struct sigaction action;
766
767     memset(&action, 0, sizeof(action));
768     action.sa_handler = SIG_DFL;
769     if (!sigaction(SIGBUS, &action, NULL)) {
770         raise(SIGBUS);
771         sigemptyset(&set);
772         sigaddset(&set, SIGBUS);
773         sigprocmask(SIG_UNBLOCK, &set, NULL);
774     }
775     perror("Failed to re-raise SIGBUS!\n");
776     abort();
777 }
778
779 static void sigbus_handler(int n, struct qemu_signalfd_siginfo *siginfo,
780                            void *ctx)
781 {
782     if (kvm_on_sigbus(siginfo->ssi_code,
783                       (void *)(intptr_t)siginfo->ssi_addr)) {
784         sigbus_reraise();
785     }
786 }
787
788 static void qemu_init_sigbus(void)
789 {
790     struct sigaction action;
791
792     memset(&action, 0, sizeof(action));
793     action.sa_flags = SA_SIGINFO;
794     action.sa_sigaction = (void (*)(int, siginfo_t*, void*))sigbus_handler;
795     sigaction(SIGBUS, &action, NULL);
796
797     prctl(PR_MCE_KILL, PR_MCE_KILL_SET, PR_MCE_KILL_EARLY, 0, 0);
798 }
799
800 static void qemu_kvm_eat_signals(CPUState *cpu)
801 {
802     struct timespec ts = { 0, 0 };
803     siginfo_t siginfo;
804     sigset_t waitset;
805     sigset_t chkset;
806     int r;
807
808     sigemptyset(&waitset);
809     sigaddset(&waitset, SIG_IPI);
810     sigaddset(&waitset, SIGBUS);
811
812     do {
813         r = sigtimedwait(&waitset, &siginfo, &ts);
814         if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
815             perror("sigtimedwait");
816             exit(1);
817         }
818
819         switch (r) {
820         case SIGBUS:
821             if (kvm_on_sigbus_vcpu(cpu, siginfo.si_code, siginfo.si_addr)) {
822                 sigbus_reraise();
823             }
824             break;
825         default:
826             break;
827         }
828
829         r = sigpending(&chkset);
830         if (r == -1) {
831             perror("sigpending");
832             exit(1);
833         }
834     } while (sigismember(&chkset, SIG_IPI) || sigismember(&chkset, SIGBUS));
835 }
836
837 #else /* !CONFIG_LINUX */
838
839 static void qemu_init_sigbus(void)
840 {
841 }
842
843 static void qemu_kvm_eat_signals(CPUState *cpu)
844 {
845 }
846 #endif /* !CONFIG_LINUX */
847
848 #ifndef _WIN32
849 static void dummy_signal(int sig)
850 {
851 }
852
853 static void qemu_kvm_init_cpu_signals(CPUState *cpu)
854 {
855     int r;
856     sigset_t set;
857     struct sigaction sigact;
858
859     memset(&sigact, 0, sizeof(sigact));
860     sigact.sa_handler = dummy_signal;
861     sigaction(SIG_IPI, &sigact, NULL);
862
863     pthread_sigmask(SIG_BLOCK, NULL, &set);
864     sigdelset(&set, SIG_IPI);
865     sigdelset(&set, SIGBUS);
866     r = kvm_set_signal_mask(cpu, &set);
867     if (r) {
868         fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
869         exit(1);
870     }
871 }
872
873 #else /* _WIN32 */
874 static void qemu_kvm_init_cpu_signals(CPUState *cpu)
875 {
876     abort();
877 }
878 #endif /* _WIN32 */
879
880 static QemuMutex qemu_global_mutex;
881 static QemuCond qemu_io_proceeded_cond;
882 static unsigned iothread_requesting_mutex;
883
884 static QemuThread io_thread;
885
886 /* cpu creation */
887 static QemuCond qemu_cpu_cond;
888 /* system init */
889 static QemuCond qemu_pause_cond;
890 static QemuCond qemu_work_cond;
891
892 void qemu_init_cpu_loop(void)
893 {
894     qemu_init_sigbus();
895     qemu_cond_init(&qemu_cpu_cond);
896     qemu_cond_init(&qemu_pause_cond);
897     qemu_cond_init(&qemu_work_cond);
898     qemu_cond_init(&qemu_io_proceeded_cond);
899     qemu_mutex_init(&qemu_global_mutex);
900
901     qemu_thread_get_self(&io_thread);
902 }
903
904 void run_on_cpu(CPUState *cpu, void (*func)(void *data), void *data)
905 {
906     struct qemu_work_item wi;
907
908     if (qemu_cpu_is_self(cpu)) {
909         func(data);
910         return;
911     }
912
913     wi.func = func;
914     wi.data = data;
915     wi.free = false;
916
917     qemu_mutex_lock(&cpu->work_mutex);
918     if (cpu->queued_work_first == NULL) {
919         cpu->queued_work_first = &wi;
920     } else {
921         cpu->queued_work_last->next = &wi;
922     }
923     cpu->queued_work_last = &wi;
924     wi.next = NULL;
925     wi.done = false;
926     qemu_mutex_unlock(&cpu->work_mutex);
927
928     qemu_cpu_kick(cpu);
929     while (!atomic_mb_read(&wi.done)) {
930         CPUState *self_cpu = current_cpu;
931
932         qemu_cond_wait(&qemu_work_cond, &qemu_global_mutex);
933         current_cpu = self_cpu;
934     }
935 }
936
937 void async_run_on_cpu(CPUState *cpu, void (*func)(void *data), void *data)
938 {
939     struct qemu_work_item *wi;
940
941     if (qemu_cpu_is_self(cpu)) {
942         func(data);
943         return;
944     }
945
946     wi = g_malloc0(sizeof(struct qemu_work_item));
947     wi->func = func;
948     wi->data = data;
949     wi->free = true;
950
951     qemu_mutex_lock(&cpu->work_mutex);
952     if (cpu->queued_work_first == NULL) {
953         cpu->queued_work_first = wi;
954     } else {
955         cpu->queued_work_last->next = wi;
956     }
957     cpu->queued_work_last = wi;
958     wi->next = NULL;
959     wi->done = false;
960     qemu_mutex_unlock(&cpu->work_mutex);
961
962     qemu_cpu_kick(cpu);
963 }
964
965 static void flush_queued_work(CPUState *cpu)
966 {
967     struct qemu_work_item *wi;
968
969     if (cpu->queued_work_first == NULL) {
970         return;
971     }
972
973     qemu_mutex_lock(&cpu->work_mutex);
974     while (cpu->queued_work_first != NULL) {
975         wi = cpu->queued_work_first;
976         cpu->queued_work_first = wi->next;
977         if (!cpu->queued_work_first) {
978             cpu->queued_work_last = NULL;
979         }
980         qemu_mutex_unlock(&cpu->work_mutex);
981         wi->func(wi->data);
982         qemu_mutex_lock(&cpu->work_mutex);
983         if (wi->free) {
984             g_free(wi);
985         } else {
986             atomic_mb_set(&wi->done, true);
987         }
988     }
989     qemu_mutex_unlock(&cpu->work_mutex);
990     qemu_cond_broadcast(&qemu_work_cond);
991 }
992
993 static void qemu_wait_io_event_common(CPUState *cpu)
994 {
995     if (cpu->stop) {
996         cpu->stop = false;
997         cpu->stopped = true;
998         qemu_cond_signal(&qemu_pause_cond);
999     }
1000     flush_queued_work(cpu);
1001     cpu->thread_kicked = false;
1002 }
1003
1004 static void qemu_tcg_wait_io_event(CPUState *cpu)
1005 {
1006     while (all_cpu_threads_idle()) {
1007        /* Start accounting real time to the virtual clock if the CPUs
1008           are idle.  */
1009         qemu_clock_warp(QEMU_CLOCK_VIRTUAL);
1010         qemu_cond_wait(cpu->halt_cond, &qemu_global_mutex);
1011     }
1012
1013     while (iothread_requesting_mutex) {
1014         qemu_cond_wait(&qemu_io_proceeded_cond, &qemu_global_mutex);
1015     }
1016
1017     CPU_FOREACH(cpu) {
1018         qemu_wait_io_event_common(cpu);
1019     }
1020 }
1021
1022 #ifdef CONFIG_HAX
1023 static void qemu_hax_wait_io_event(CPUState *cpu)
1024 {
1025     while (cpu_thread_is_idle(cpu)) {
1026         qemu_cond_wait(cpu->halt_cond, &qemu_global_mutex);
1027     }
1028
1029     qemu_wait_io_event_common(cpu);
1030 }
1031 #endif
1032
1033 static void qemu_kvm_wait_io_event(CPUState *cpu)
1034 {
1035     while (cpu_thread_is_idle(cpu)) {
1036         qemu_cond_wait(cpu->halt_cond, &qemu_global_mutex);
1037     }
1038
1039     qemu_kvm_eat_signals(cpu);
1040     qemu_wait_io_event_common(cpu);
1041 }
1042
1043 static void *qemu_kvm_cpu_thread_fn(void *arg)
1044 {
1045     CPUState *cpu = arg;
1046     int r;
1047
1048     rcu_register_thread();
1049
1050     qemu_mutex_lock_iothread();
1051     qemu_thread_get_self(cpu->thread);
1052     cpu->thread_id = qemu_get_thread_id();
1053     cpu->can_do_io = 1;
1054     current_cpu = cpu;
1055
1056     r = kvm_init_vcpu(cpu);
1057     if (r < 0) {
1058         fprintf(stderr, "kvm_init_vcpu failed: %s\n", strerror(-r));
1059         exit(1);
1060     }
1061
1062     qemu_kvm_init_cpu_signals(cpu);
1063
1064     /* signal CPU creation */
1065     cpu->created = true;
1066     qemu_cond_signal(&qemu_cpu_cond);
1067
1068     while (1) {
1069         if (cpu_can_run(cpu)) {
1070             r = kvm_cpu_exec(cpu);
1071             if (r == EXCP_DEBUG) {
1072                 cpu_handle_guest_debug(cpu);
1073             }
1074         }
1075         qemu_kvm_wait_io_event(cpu);
1076     }
1077
1078     return NULL;
1079 }
1080
1081 static void *qemu_dummy_cpu_thread_fn(void *arg)
1082 {
1083 #ifdef _WIN32
1084     fprintf(stderr, "qtest is not supported under Windows\n");
1085     exit(1);
1086 #else
1087     CPUState *cpu = arg;
1088     sigset_t waitset;
1089     int r;
1090
1091     rcu_register_thread();
1092
1093     qemu_mutex_lock_iothread();
1094     qemu_thread_get_self(cpu->thread);
1095     cpu->thread_id = qemu_get_thread_id();
1096     cpu->can_do_io = 1;
1097
1098     sigemptyset(&waitset);
1099     sigaddset(&waitset, SIG_IPI);
1100
1101     /* signal CPU creation */
1102     cpu->created = true;
1103     qemu_cond_signal(&qemu_cpu_cond);
1104
1105     current_cpu = cpu;
1106     while (1) {
1107         current_cpu = NULL;
1108         qemu_mutex_unlock_iothread();
1109         do {
1110             int sig;
1111             r = sigwait(&waitset, &sig);
1112         } while (r == -1 && (errno == EAGAIN || errno == EINTR));
1113         if (r == -1) {
1114             perror("sigwait");
1115             exit(1);
1116         }
1117         qemu_mutex_lock_iothread();
1118         current_cpu = cpu;
1119         qemu_wait_io_event_common(cpu);
1120     }
1121
1122     return NULL;
1123 #endif
1124 }
1125
1126 static void tcg_exec_all(void);
1127
1128 static void *qemu_tcg_cpu_thread_fn(void *arg)
1129 {
1130     CPUState *cpu = arg;
1131
1132     rcu_register_thread();
1133
1134     qemu_mutex_lock_iothread();
1135     qemu_thread_get_self(cpu->thread);
1136
1137     CPU_FOREACH(cpu) {
1138         cpu->thread_id = qemu_get_thread_id();
1139         cpu->created = true;
1140         cpu->can_do_io = 1;
1141     }
1142     qemu_cond_signal(&qemu_cpu_cond);
1143
1144     /* wait for initial kick-off after machine start */
1145     while (first_cpu->stopped) {
1146         qemu_cond_wait(first_cpu->halt_cond, &qemu_global_mutex);
1147
1148         /* process any pending work */
1149         CPU_FOREACH(cpu) {
1150             qemu_wait_io_event_common(cpu);
1151         }
1152     }
1153
1154     /* process any pending work */
1155     atomic_mb_set(&exit_request, 1);
1156
1157     while (1) {
1158         tcg_exec_all();
1159
1160         if (use_icount) {
1161             int64_t deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);
1162
1163             if (deadline == 0) {
1164                 qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
1165             }
1166         }
1167         qemu_tcg_wait_io_event(QTAILQ_FIRST(&cpus));
1168     }
1169
1170     return NULL;
1171 }
1172
1173 #ifdef CONFIG_HAX
1174 static void *qemu_hax_cpu_thread_fn(void *arg)
1175 {
1176     CPUState *cpu = arg;
1177     int r;
1178     qemu_thread_get_self(cpu->thread);
1179     qemu_mutex_lock(&qemu_global_mutex);
1180
1181     cpu->thread_id = qemu_get_thread_id();
1182     cpu->created = true;
1183     cpu->halted = 0;
1184     current_cpu = cpu;
1185
1186     hax_init_vcpu(cpu);
1187     qemu_cond_signal(&qemu_cpu_cond);
1188
1189     while (1) {
1190         if (cpu_can_run(cpu)) {
1191             r = hax_smp_cpu_exec(cpu);
1192             if (r == EXCP_DEBUG) {
1193                 cpu_handle_guest_debug(cpu);
1194             }
1195         }
1196         qemu_hax_wait_io_event(cpu);
1197     }
1198     return NULL;
1199 }
1200 #endif
1201
1202 static void qemu_cpu_kick_thread(CPUState *cpu)
1203 {
1204 #ifndef _WIN32
1205     int err;
1206
1207     if (cpu->thread_kicked) {
1208         return;
1209     }
1210     cpu->thread_kicked = true;
1211     err = pthread_kill(cpu->thread->thread, SIG_IPI);
1212     if (err) {
1213         fprintf(stderr, "qemu:%s: %s", __func__, strerror(err));
1214         exit(1);
1215     }
1216
1217 # ifdef CONFIG_DARWIN
1218     /* The cpu thread cannot catch it reliably when shutdown the guest on Mac.
1219     * We can double check it and resend it
1220     */
1221     if (!exit_request) {
1222     // FIXME: check it soon
1223 //        cpu_signal(0);
1224     }
1225
1226     if (hax_enabled() && hax_ug_platform()) {
1227         cpu->exit_request = 1;
1228     }
1229 # endif
1230 #else /* _WIN32 */
1231 # ifndef CONFIG_HAX
1232     abort();
1233 # else
1234     // FIXME: check it soon
1235 #if 0
1236     if (!qemu_cpu_is_self(cpu)) {
1237         CONTEXT tcgContext;
1238
1239         if (SuspendThread(cpu->hThread) == (DWORD)-1) {
1240             fprintf(stderr, "qemu:%s: GetLastError:%lu\n", __func__,
1241                     GetLastError());
1242             exit(1);
1243         }
1244
1245         /* On multi-core systems, we are not sure that the thread is actually
1246          * suspended until we can get the context.
1247          */
1248         tcgContext.ContextFlags = CONTEXT_CONTROL;
1249         while (GetThreadContext(cpu->hThread, &tcgContext) != 0) {
1250             continue;
1251         }
1252
1253 //        cpu_signal(0);
1254
1255         if(hax_enabled() && hax_ug_platform()) {
1256             cpu->exit_request = 1;
1257         } else {
1258             abort();
1259         }
1260         if (ResumeThread(cpu->hThread) == (DWORD)-1) {
1261             fprintf(stderr, "qemu:%s: GetLastError:%lu\n", __func__,
1262                     GetLastError());
1263             exit(1);
1264         }
1265     }
1266 #endif
1267     if (!qemu_cpu_is_self(cpu)) {
1268         if(hax_enabled() && hax_ug_platform()) {
1269             cpu->exit_request = 1;
1270         }
1271     }
1272 # endif
1273 #endif
1274 }
1275
1276 static void qemu_cpu_kick_no_halt(void)
1277 {
1278     CPUState *cpu;
1279     /* Ensure whatever caused the exit has reached the CPU threads before
1280      * writing exit_request.
1281      */
1282     atomic_mb_set(&exit_request, 1);
1283     cpu = atomic_mb_read(&tcg_current_cpu);
1284     if (cpu) {
1285         cpu_exit(cpu);
1286     }
1287 }
1288
1289 void qemu_cpu_kick(CPUState *cpu)
1290 {
1291     qemu_cond_broadcast(cpu->halt_cond);
1292     if (tcg_enabled()) {
1293         qemu_cpu_kick_no_halt();
1294     } else {
1295         qemu_cpu_kick_thread(cpu);
1296     }
1297 }
1298
1299 void qemu_cpu_kick_self(void)
1300 {
1301     assert(current_cpu);
1302     qemu_cpu_kick_thread(current_cpu);
1303 }
1304
1305 bool qemu_cpu_is_self(CPUState *cpu)
1306 {
1307     return qemu_thread_is_self(cpu->thread);
1308 }
1309
1310 bool qemu_in_vcpu_thread(void)
1311 {
1312     return current_cpu && qemu_cpu_is_self(current_cpu);
1313 }
1314
1315 static __thread bool iothread_locked = false;
1316
1317 bool qemu_mutex_iothread_locked(void)
1318 {
1319     return iothread_locked;
1320 }
1321
1322 void qemu_mutex_lock_iothread(void)
1323 {
1324     atomic_inc(&iothread_requesting_mutex);
1325     /* In the simple case there is no need to bump the VCPU thread out of
1326      * TCG code execution.
1327      */
1328     if (!tcg_enabled() || qemu_in_vcpu_thread() ||
1329         !first_cpu || !first_cpu->created) {
1330         qemu_mutex_lock(&qemu_global_mutex);
1331         atomic_dec(&iothread_requesting_mutex);
1332     } else {
1333         if (qemu_mutex_trylock(&qemu_global_mutex)) {
1334             qemu_cpu_kick_no_halt();
1335             qemu_mutex_lock(&qemu_global_mutex);
1336         }
1337         atomic_dec(&iothread_requesting_mutex);
1338         qemu_cond_broadcast(&qemu_io_proceeded_cond);
1339     }
1340     iothread_locked = true;
1341 }
1342
1343 void qemu_mutex_unlock_iothread(void)
1344 {
1345     iothread_locked = false;
1346     qemu_mutex_unlock(&qemu_global_mutex);
1347 }
1348
1349 static int all_vcpus_paused(void)
1350 {
1351     CPUState *cpu;
1352
1353     CPU_FOREACH(cpu) {
1354         if (!cpu->stopped) {
1355             return 0;
1356         }
1357     }
1358
1359     return 1;
1360 }
1361
1362 void pause_all_vcpus(void)
1363 {
1364     CPUState *cpu;
1365
1366     qemu_clock_enable(QEMU_CLOCK_VIRTUAL, false);
1367     CPU_FOREACH(cpu) {
1368         cpu->stop = true;
1369         qemu_cpu_kick(cpu);
1370     }
1371
1372     if (qemu_in_vcpu_thread()) {
1373         cpu_stop_current();
1374         if (!kvm_enabled()) {
1375             CPU_FOREACH(cpu) {
1376                 cpu->stop = false;
1377                 cpu->stopped = true;
1378             }
1379             return;
1380         }
1381     }
1382
1383     while (!all_vcpus_paused()) {
1384         qemu_cond_wait(&qemu_pause_cond, &qemu_global_mutex);
1385         CPU_FOREACH(cpu) {
1386             qemu_cpu_kick(cpu);
1387         }
1388     }
1389 }
1390
1391 void cpu_resume(CPUState *cpu)
1392 {
1393     cpu->stop = false;
1394     cpu->stopped = false;
1395     qemu_cpu_kick(cpu);
1396 }
1397
1398 void resume_all_vcpus(void)
1399 {
1400     CPUState *cpu;
1401
1402     qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
1403     CPU_FOREACH(cpu) {
1404         cpu_resume(cpu);
1405     }
1406 }
1407
1408 /* For temporary buffers for forming a name */
1409 #define VCPU_THREAD_NAME_SIZE 16
1410
1411 static void qemu_tcg_init_vcpu(CPUState *cpu)
1412 {
1413 #ifdef CONFIG_HAX
1414     if (hax_enabled()) {
1415         hax_init_vcpu(cpu);
1416     }
1417 #endif
1418     char thread_name[VCPU_THREAD_NAME_SIZE];
1419     static QemuCond *tcg_halt_cond;
1420     static QemuThread *tcg_cpu_thread;
1421
1422     tcg_cpu_address_space_init(cpu, cpu->as);
1423
1424     /* share a single thread for all cpus with TCG */
1425     if (!tcg_cpu_thread) {
1426         cpu->thread = g_malloc0(sizeof(QemuThread));
1427         cpu->halt_cond = g_malloc0(sizeof(QemuCond));
1428         qemu_cond_init(cpu->halt_cond);
1429         tcg_halt_cond = cpu->halt_cond;
1430         snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/TCG",
1431                  cpu->cpu_index);
1432         qemu_thread_create(cpu->thread, thread_name, qemu_tcg_cpu_thread_fn,
1433                            cpu, QEMU_THREAD_JOINABLE);
1434 #ifdef _WIN32
1435         cpu->hThread = qemu_thread_get_handle(cpu->thread);
1436 #endif
1437         while (!cpu->created) {
1438             qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
1439         }
1440         tcg_cpu_thread = cpu->thread;
1441     } else {
1442         cpu->thread = tcg_cpu_thread;
1443         cpu->halt_cond = tcg_halt_cond;
1444     }
1445 }
1446
1447 #ifdef CONFIG_HAX
1448 static void qemu_hax_start_vcpu(CPUState *cpu)
1449 {
1450     char thread_name[VCPU_THREAD_NAME_SIZE];
1451
1452     cpu->thread = g_malloc0(sizeof(QemuThread));
1453     cpu->halt_cond = g_malloc0(sizeof(QemuCond));
1454     qemu_cond_init(cpu->halt_cond);
1455
1456     snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/HAX",
1457              cpu->cpu_index);
1458
1459     qemu_thread_create(cpu->thread, thread_name, qemu_hax_cpu_thread_fn,
1460                        cpu, QEMU_THREAD_JOINABLE);
1461 #ifdef _WIN32
1462      cpu->hThread = qemu_thread_get_handle(cpu->thread);
1463 #endif
1464     while (!cpu->created) {
1465         qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
1466     }
1467 }
1468 #endif
1469
1470 static void qemu_kvm_start_vcpu(CPUState *cpu)
1471 {
1472     char thread_name[VCPU_THREAD_NAME_SIZE];
1473
1474     cpu->thread = g_malloc0(sizeof(QemuThread));
1475     cpu->halt_cond = g_malloc0(sizeof(QemuCond));
1476     qemu_cond_init(cpu->halt_cond);
1477     snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/KVM",
1478              cpu->cpu_index);
1479     qemu_thread_create(cpu->thread, thread_name, qemu_kvm_cpu_thread_fn,
1480                        cpu, QEMU_THREAD_JOINABLE);
1481     while (!cpu->created) {
1482         qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
1483     }
1484 }
1485
1486 static void qemu_dummy_start_vcpu(CPUState *cpu)
1487 {
1488     char thread_name[VCPU_THREAD_NAME_SIZE];
1489
1490     cpu->thread = g_malloc0(sizeof(QemuThread));
1491     cpu->halt_cond = g_malloc0(sizeof(QemuCond));
1492     qemu_cond_init(cpu->halt_cond);
1493     snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/DUMMY",
1494              cpu->cpu_index);
1495     qemu_thread_create(cpu->thread, thread_name, qemu_dummy_cpu_thread_fn, cpu,
1496                        QEMU_THREAD_JOINABLE);
1497     while (!cpu->created) {
1498         qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
1499     }
1500 }
1501
1502 void qemu_init_vcpu(CPUState *cpu)
1503 {
1504     cpu->nr_cores = smp_cores;
1505     cpu->nr_threads = smp_threads;
1506     cpu->stopped = true;
1507
1508     if (kvm_enabled()) {
1509         qemu_kvm_start_vcpu(cpu);
1510 #ifdef CONFIG_HAX
1511     } else if (hax_enabled() && hax_ug_platform()) {
1512         qemu_hax_start_vcpu(cpu);
1513 #endif
1514     } else if (tcg_enabled()) {
1515         qemu_tcg_init_vcpu(cpu);
1516     } else {
1517         qemu_dummy_start_vcpu(cpu);
1518     }
1519 }
1520
1521 void cpu_stop_current(void)
1522 {
1523     if (current_cpu) {
1524         current_cpu->stop = false;
1525         current_cpu->stopped = true;
1526         cpu_exit(current_cpu);
1527         qemu_cond_signal(&qemu_pause_cond);
1528     }
1529 }
1530
1531 int vm_stop(RunState state)
1532 {
1533     if (qemu_in_vcpu_thread()) {
1534         qemu_system_vmstop_request_prepare();
1535         qemu_system_vmstop_request(state);
1536         /*
1537          * FIXME: should not return to device code in case
1538          * vm_stop() has been requested.
1539          */
1540         cpu_stop_current();
1541         return 0;
1542     }
1543
1544     return do_vm_stop(state);
1545 }
1546
1547 /* does a state transition even if the VM is already stopped,
1548    current state is forgotten forever */
1549 int vm_stop_force_state(RunState state)
1550 {
1551     if (runstate_is_running()) {
1552         return vm_stop(state);
1553     } else {
1554         runstate_set(state);
1555
1556         bdrv_drain_all();
1557         /* Make sure to return an error if the flush in a previous vm_stop()
1558          * failed. */
1559         return bdrv_flush_all();
1560     }
1561 }
1562
1563 static int64_t tcg_get_icount_limit(void)
1564 {
1565     int64_t deadline;
1566
1567     if (replay_mode != REPLAY_MODE_PLAY) {
1568         deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);
1569
1570         /* Maintain prior (possibly buggy) behaviour where if no deadline
1571          * was set (as there is no QEMU_CLOCK_VIRTUAL timer) or it is more than
1572          * INT32_MAX nanoseconds ahead, we still use INT32_MAX
1573          * nanoseconds.
1574          */
1575         if ((deadline < 0) || (deadline > INT32_MAX)) {
1576             deadline = INT32_MAX;
1577         }
1578
1579         return qemu_icount_round(deadline);
1580     } else {
1581         return replay_get_instructions();
1582     }
1583 }
1584
1585 static int tcg_cpu_exec(CPUState *cpu)
1586 {
1587     int ret;
1588 #ifdef CONFIG_PROFILER
1589     int64_t ti;
1590 #endif
1591
1592 #ifdef CONFIG_PROFILER
1593     ti = profile_getclock();
1594 #endif
1595     if (use_icount) {
1596         int64_t count;
1597         int decr;
1598         timers_state.qemu_icount -= (cpu->icount_decr.u16.low
1599                                     + cpu->icount_extra);
1600         cpu->icount_decr.u16.low = 0;
1601         cpu->icount_extra = 0;
1602         count = tcg_get_icount_limit();
1603         timers_state.qemu_icount += count;
1604         decr = (count > 0xffff) ? 0xffff : count;
1605         count -= decr;
1606         cpu->icount_decr.u16.low = decr;
1607         cpu->icount_extra = count;
1608     }
1609     ret = cpu_exec(cpu);
1610 #ifdef CONFIG_PROFILER
1611     tcg_time += profile_getclock() - ti;
1612 #endif
1613     if (use_icount) {
1614         /* Fold pending instructions back into the
1615            instruction counter, and clear the interrupt flag.  */
1616         timers_state.qemu_icount -= (cpu->icount_decr.u16.low
1617                         + cpu->icount_extra);
1618         cpu->icount_decr.u32 = 0;
1619         cpu->icount_extra = 0;
1620         replay_account_executed_instructions();
1621     }
1622     return ret;
1623 }
1624
1625 static void tcg_exec_all(void)
1626 {
1627     int r;
1628
1629     /* Account partial waits to QEMU_CLOCK_VIRTUAL.  */
1630     qemu_clock_warp(QEMU_CLOCK_VIRTUAL);
1631
1632     if (next_cpu == NULL) {
1633         next_cpu = first_cpu;
1634     }
1635     for (; next_cpu != NULL && !exit_request; next_cpu = CPU_NEXT(next_cpu)) {
1636         CPUState *cpu = next_cpu;
1637
1638         qemu_clock_enable(QEMU_CLOCK_VIRTUAL,
1639                           (cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
1640
1641         if (cpu_can_run(cpu)) {
1642             r = tcg_cpu_exec(cpu);
1643             if (r == EXCP_DEBUG) {
1644                 cpu_handle_guest_debug(cpu);
1645                 break;
1646             }
1647         } else if (cpu->stop || cpu->stopped) {
1648             break;
1649         }
1650     }
1651
1652     /* Pairs with smp_wmb in qemu_cpu_kick.  */
1653     atomic_mb_set(&exit_request, 0);
1654 }
1655
1656 void list_cpus(FILE *f, fprintf_function cpu_fprintf, const char *optarg)
1657 {
1658     /* XXX: implement xxx_cpu_list for targets that still miss it */
1659 #if defined(cpu_list)
1660     cpu_list(f, cpu_fprintf);
1661 #endif
1662 }
1663
1664 CpuInfoList *qmp_query_cpus(Error **errp)
1665 {
1666     CpuInfoList *head = NULL, *cur_item = NULL;
1667     CPUState *cpu;
1668
1669     CPU_FOREACH(cpu) {
1670         CpuInfoList *info;
1671 #if defined(TARGET_I386)
1672         X86CPU *x86_cpu = X86_CPU(cpu);
1673         CPUX86State *env = &x86_cpu->env;
1674 #elif defined(TARGET_PPC)
1675         PowerPCCPU *ppc_cpu = POWERPC_CPU(cpu);
1676         CPUPPCState *env = &ppc_cpu->env;
1677 #elif defined(TARGET_SPARC)
1678         SPARCCPU *sparc_cpu = SPARC_CPU(cpu);
1679         CPUSPARCState *env = &sparc_cpu->env;
1680 #elif defined(TARGET_MIPS)
1681         MIPSCPU *mips_cpu = MIPS_CPU(cpu);
1682         CPUMIPSState *env = &mips_cpu->env;
1683 #elif defined(TARGET_TRICORE)
1684         TriCoreCPU *tricore_cpu = TRICORE_CPU(cpu);
1685         CPUTriCoreState *env = &tricore_cpu->env;
1686 #endif
1687
1688         cpu_synchronize_state(cpu);
1689
1690         info = g_malloc0(sizeof(*info));
1691         info->value = g_malloc0(sizeof(*info->value));
1692         info->value->CPU = cpu->cpu_index;
1693         info->value->current = (cpu == first_cpu);
1694         info->value->halted = cpu->halted;
1695         info->value->qom_path = object_get_canonical_path(OBJECT(cpu));
1696         info->value->thread_id = cpu->thread_id;
1697 #if defined(TARGET_I386)
1698         info->value->has_pc = true;
1699         info->value->pc = env->eip + env->segs[R_CS].base;
1700 #elif defined(TARGET_PPC)
1701         info->value->has_nip = true;
1702         info->value->nip = env->nip;
1703 #elif defined(TARGET_SPARC)
1704         info->value->has_pc = true;
1705         info->value->pc = env->pc;
1706         info->value->has_npc = true;
1707         info->value->npc = env->npc;
1708 #elif defined(TARGET_MIPS)
1709         info->value->has_PC = true;
1710         info->value->PC = env->active_tc.PC;
1711 #elif defined(TARGET_TRICORE)
1712         info->value->has_PC = true;
1713         info->value->PC = env->PC;
1714 #endif
1715
1716         /* XXX: waiting for the qapi to support GSList */
1717         if (!cur_item) {
1718             head = cur_item = info;
1719         } else {
1720             cur_item->next = info;
1721             cur_item = info;
1722         }
1723     }
1724
1725     return head;
1726 }
1727
1728 void qmp_memsave(int64_t addr, int64_t size, const char *filename,
1729                  bool has_cpu, int64_t cpu_index, Error **errp)
1730 {
1731     FILE *f;
1732     uint32_t l;
1733     CPUState *cpu;
1734     uint8_t buf[1024];
1735     int64_t orig_addr = addr, orig_size = size;
1736
1737     if (!has_cpu) {
1738         cpu_index = 0;
1739     }
1740
1741     cpu = qemu_get_cpu(cpu_index);
1742     if (cpu == NULL) {
1743         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
1744                    "a CPU number");
1745         return;
1746     }
1747
1748     f = fopen(filename, "wb");
1749     if (!f) {
1750         error_setg_file_open(errp, errno, filename);
1751         return;
1752     }
1753
1754     while (size != 0) {
1755         l = sizeof(buf);
1756         if (l > size)
1757             l = size;
1758         if (cpu_memory_rw_debug(cpu, addr, buf, l, 0) != 0) {
1759             error_setg(errp, "Invalid addr 0x%016" PRIx64 "/size %" PRId64
1760                              " specified", orig_addr, orig_size);
1761             goto exit;
1762         }
1763         if (fwrite(buf, 1, l, f) != l) {
1764             error_setg(errp, QERR_IO_ERROR);
1765             goto exit;
1766         }
1767         addr += l;
1768         size -= l;
1769     }
1770
1771 exit:
1772     fclose(f);
1773 }
1774
1775 void qmp_pmemsave(int64_t addr, int64_t size, const char *filename,
1776                   Error **errp)
1777 {
1778     FILE *f;
1779     uint32_t l;
1780     uint8_t buf[1024];
1781
1782     f = fopen(filename, "wb");
1783     if (!f) {
1784         error_setg_file_open(errp, errno, filename);
1785         return;
1786     }
1787
1788     while (size != 0) {
1789         l = sizeof(buf);
1790         if (l > size)
1791             l = size;
1792         cpu_physical_memory_read(addr, buf, l);
1793         if (fwrite(buf, 1, l, f) != l) {
1794             error_setg(errp, QERR_IO_ERROR);
1795             goto exit;
1796         }
1797         addr += l;
1798         size -= l;
1799     }
1800
1801 exit:
1802     fclose(f);
1803 }
1804
1805 void qmp_inject_nmi(Error **errp)
1806 {
1807 #if defined(TARGET_I386)
1808     CPUState *cs;
1809
1810     CPU_FOREACH(cs) {
1811         X86CPU *cpu = X86_CPU(cs);
1812
1813         if (!cpu->apic_state) {
1814             cpu_interrupt(cs, CPU_INTERRUPT_NMI);
1815         } else {
1816             apic_deliver_nmi(cpu->apic_state);
1817         }
1818     }
1819 #else
1820     nmi_monitor_handle(monitor_get_cpu_index(), errp);
1821 #endif
1822 }
1823
1824 void dump_drift_info(FILE *f, fprintf_function cpu_fprintf)
1825 {
1826     if (!use_icount) {
1827         return;
1828     }
1829
1830     cpu_fprintf(f, "Host - Guest clock  %"PRIi64" ms\n",
1831                 (cpu_get_clock() - cpu_get_icount())/SCALE_MS);
1832     if (icount_align_option) {
1833         cpu_fprintf(f, "Max guest delay     %"PRIi64" ms\n", -max_delay/SCALE_MS);
1834         cpu_fprintf(f, "Max guest advance   %"PRIi64" ms\n", max_advance/SCALE_MS);
1835     } else {
1836         cpu_fprintf(f, "Max guest delay     NA\n");
1837         cpu_fprintf(f, "Max guest advance   NA\n");
1838     }
1839 }