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