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