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