4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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
25 /* Needed early for CONFIG_BSD etc. */
26 #include "config-host.h"
38 #include <sys/prctl.h>
42 #define SIG_IPI (SIGRTMIN+4)
44 #define SIG_IPI SIGUSR1
48 #define PR_MCE_KILL 33
51 static CPUState *next_cpu;
53 /***********************************************************/
54 void hw_error(const char *fmt, ...)
60 fprintf(stderr, "qemu: hardware error: ");
61 vfprintf(stderr, fmt, ap);
62 fprintf(stderr, "\n");
63 for(env = first_cpu; env != NULL; env = env->next_cpu) {
64 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
66 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
68 cpu_dump_state(env, stderr, fprintf, 0);
75 void cpu_synchronize_all_states(void)
79 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
80 cpu_synchronize_state(cpu);
84 void cpu_synchronize_all_post_reset(void)
88 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
89 cpu_synchronize_post_reset(cpu);
93 void cpu_synchronize_all_post_init(void)
97 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
98 cpu_synchronize_post_init(cpu);
102 int cpu_is_stopped(CPUState *env)
104 return !vm_running || env->stopped;
107 static void do_vm_stop(int reason)
113 vm_state_notify(0, reason);
116 monitor_protocol_event(QEVENT_STOP, NULL);
120 static int cpu_can_run(CPUState *env)
124 if (env->stopped || !vm_running)
129 static int cpu_has_work(CPUState *env)
133 if (env->queued_work_first)
135 if (env->stopped || !vm_running)
139 if (qemu_cpu_has_work(env))
144 static int any_cpu_has_work(void)
148 for (env = first_cpu; env != NULL; env = env->next_cpu)
149 if (cpu_has_work(env))
154 static void cpu_debug_handler(CPUState *env)
156 gdb_set_stop_cpu(env);
157 debug_requested = EXCP_DEBUG;
162 static int io_thread_fd = -1;
164 static void qemu_event_increment(void)
166 /* Write 8 bytes to be compatible with eventfd. */
167 static const uint64_t val = 1;
170 if (io_thread_fd == -1)
174 ret = write(io_thread_fd, &val, sizeof(val));
175 } while (ret < 0 && errno == EINTR);
177 /* EAGAIN is fine, a read must be pending. */
178 if (ret < 0 && errno != EAGAIN) {
179 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
185 static void qemu_event_read(void *opaque)
187 int fd = (unsigned long)opaque;
191 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
193 len = read(fd, buffer, sizeof(buffer));
194 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
197 static int qemu_event_init(void)
202 err = qemu_eventfd(fds);
206 err = fcntl_setfl(fds[0], O_NONBLOCK);
210 err = fcntl_setfl(fds[1], O_NONBLOCK);
214 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
215 (void *)(unsigned long)fds[0]);
217 io_thread_fd = fds[1];
226 #ifdef CONFIG_IOTHREAD
227 static void dummy_signal(int sig)
234 HANDLE qemu_event_handle;
236 static void dummy_event_handler(void *opaque)
240 static int qemu_event_init(void)
242 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
243 if (!qemu_event_handle) {
244 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
247 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
251 static void qemu_event_increment(void)
253 if (!SetEvent(qemu_event_handle)) {
254 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
261 #ifndef CONFIG_IOTHREAD
262 int qemu_init_main_loop(void)
264 cpu_set_debug_excp_handler(cpu_debug_handler);
266 return qemu_event_init();
269 void qemu_main_loop_start(void)
273 void qemu_init_vcpu(void *_env)
275 CPUState *env = _env;
278 env->nr_cores = smp_cores;
279 env->nr_threads = smp_threads;
282 r = kvm_init_vcpu(env);
284 fprintf(stderr, "kvm_init_vcpu failed: %s\n", strerror(-r));
290 int qemu_cpu_self(void *env)
295 void run_on_cpu(CPUState *env, void (*func)(void *data), void *data)
300 void resume_all_vcpus(void)
304 void pause_all_vcpus(void)
308 void qemu_cpu_kick(void *env)
313 void qemu_notify_event(void)
315 CPUState *env = cpu_single_env;
317 qemu_event_increment ();
321 if (next_cpu && env != next_cpu) {
327 void qemu_mutex_lock_iothread(void) {}
328 void qemu_mutex_unlock_iothread(void) {}
330 void cpu_stop_current(void)
334 void vm_stop(int reason)
339 #else /* CONFIG_IOTHREAD */
341 #include "qemu-thread.h"
343 QemuMutex qemu_global_mutex;
344 static QemuMutex qemu_fair_mutex;
346 static QemuThread io_thread;
348 static QemuThread *tcg_cpu_thread;
349 static QemuCond *tcg_halt_cond;
351 static int qemu_system_ready;
353 static QemuCond qemu_cpu_cond;
355 static QemuCond qemu_system_cond;
356 static QemuCond qemu_pause_cond;
357 static QemuCond qemu_work_cond;
359 /* If we have signalfd, we mask out the signals we want to handle and then
360 * use signalfd to listen for them. We rely on whatever the current signal
361 * handler is to dispatch the signals when we receive them.
363 static void sigfd_handler(void *opaque)
365 int fd = (unsigned long) opaque;
366 struct qemu_signalfd_siginfo info;
367 struct sigaction action;
372 len = read(fd, &info, sizeof(info));
373 } while (len == -1 && errno == EINTR);
375 if (len == -1 && errno == EAGAIN) {
379 if (len != sizeof(info)) {
380 printf("read from sigfd returned %zd: %m\n", len);
384 sigaction(info.ssi_signo, NULL, &action);
385 if ((action.sa_flags & SA_SIGINFO) && action.sa_sigaction) {
386 action.sa_sigaction(info.ssi_signo,
387 (siginfo_t *)&info, NULL);
388 } else if (action.sa_handler) {
389 action.sa_handler(info.ssi_signo);
394 static void cpu_signal(int sig)
396 if (cpu_single_env) {
397 cpu_exit(cpu_single_env);
402 static void qemu_kvm_init_cpu_signals(CPUState *env)
406 struct sigaction sigact;
408 memset(&sigact, 0, sizeof(sigact));
409 sigact.sa_handler = dummy_signal;
410 sigaction(SIG_IPI, &sigact, NULL);
412 pthread_sigmask(SIG_BLOCK, NULL, &set);
413 sigdelset(&set, SIG_IPI);
414 sigdelset(&set, SIGBUS);
415 r = kvm_set_signal_mask(env, &set);
417 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
422 static void qemu_tcg_init_cpu_signals(void)
425 struct sigaction sigact;
427 memset(&sigact, 0, sizeof(sigact));
428 sigact.sa_handler = cpu_signal;
429 sigaction(SIG_IPI, &sigact, NULL);
432 sigaddset(&set, SIG_IPI);
433 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
436 static void sigbus_handler(int n, struct qemu_signalfd_siginfo *siginfo,
439 static sigset_t block_io_signals(void)
442 struct sigaction action;
444 /* SIGUSR2 used by posix-aio-compat.c */
446 sigaddset(&set, SIGUSR2);
447 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
450 sigaddset(&set, SIGIO);
451 sigaddset(&set, SIGALRM);
452 sigaddset(&set, SIG_IPI);
453 sigaddset(&set, SIGBUS);
454 pthread_sigmask(SIG_BLOCK, &set, NULL);
456 memset(&action, 0, sizeof(action));
457 action.sa_flags = SA_SIGINFO;
458 action.sa_sigaction = (void (*)(int, siginfo_t*, void*))sigbus_handler;
459 sigaction(SIGBUS, &action, NULL);
460 prctl(PR_MCE_KILL, 1, 1, 0, 0);
465 static int qemu_signalfd_init(sigset_t mask)
469 sigfd = qemu_signalfd(&mask);
471 fprintf(stderr, "failed to create signalfd\n");
475 fcntl_setfl(sigfd, O_NONBLOCK);
477 qemu_set_fd_handler2(sigfd, NULL, sigfd_handler, NULL,
478 (void *)(unsigned long) sigfd);
483 int qemu_init_main_loop(void)
486 sigset_t blocked_signals;
488 cpu_set_debug_excp_handler(cpu_debug_handler);
490 blocked_signals = block_io_signals();
492 ret = qemu_signalfd_init(blocked_signals);
496 /* Note eventfd must be drained before signalfd handlers run */
497 ret = qemu_event_init();
501 qemu_cond_init(&qemu_pause_cond);
502 qemu_cond_init(&qemu_system_cond);
503 qemu_mutex_init(&qemu_fair_mutex);
504 qemu_mutex_init(&qemu_global_mutex);
505 qemu_mutex_lock(&qemu_global_mutex);
507 qemu_thread_self(&io_thread);
512 void qemu_main_loop_start(void)
514 qemu_system_ready = 1;
515 qemu_cond_broadcast(&qemu_system_cond);
518 void run_on_cpu(CPUState *env, void (*func)(void *data), void *data)
520 struct qemu_work_item wi;
522 if (qemu_cpu_self(env)) {
529 if (!env->queued_work_first)
530 env->queued_work_first = &wi;
532 env->queued_work_last->next = &wi;
533 env->queued_work_last = &wi;
539 CPUState *self_env = cpu_single_env;
541 qemu_cond_wait(&qemu_work_cond, &qemu_global_mutex);
542 cpu_single_env = self_env;
546 static void flush_queued_work(CPUState *env)
548 struct qemu_work_item *wi;
550 if (!env->queued_work_first)
553 while ((wi = env->queued_work_first)) {
554 env->queued_work_first = wi->next;
558 env->queued_work_last = NULL;
559 qemu_cond_broadcast(&qemu_work_cond);
562 static void qemu_wait_io_event_common(CPUState *env)
567 qemu_cond_signal(&qemu_pause_cond);
569 flush_queued_work(env);
570 env->thread_kicked = false;
573 static void qemu_tcg_wait_io_event(void)
577 while (!any_cpu_has_work())
578 qemu_cond_timedwait(tcg_halt_cond, &qemu_global_mutex, 1000);
580 qemu_mutex_unlock(&qemu_global_mutex);
583 * Users of qemu_global_mutex can be starved, having no chance
584 * to acquire it since this path will get to it first.
585 * So use another lock to provide fairness.
587 qemu_mutex_lock(&qemu_fair_mutex);
588 qemu_mutex_unlock(&qemu_fair_mutex);
590 qemu_mutex_lock(&qemu_global_mutex);
592 for (env = first_cpu; env != NULL; env = env->next_cpu) {
593 qemu_wait_io_event_common(env);
597 static void sigbus_reraise(void)
600 struct sigaction action;
602 memset(&action, 0, sizeof(action));
603 action.sa_handler = SIG_DFL;
604 if (!sigaction(SIGBUS, &action, NULL)) {
607 sigaddset(&set, SIGBUS);
608 sigprocmask(SIG_UNBLOCK, &set, NULL);
610 perror("Failed to re-raise SIGBUS!\n");
614 static void sigbus_handler(int n, struct qemu_signalfd_siginfo *siginfo,
617 if (kvm_on_sigbus(siginfo->ssi_code, (void *)(intptr_t)siginfo->ssi_addr)) {
622 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
630 ts.tv_sec = timeout / 1000;
631 ts.tv_nsec = (timeout % 1000) * 1000000;
633 sigemptyset(&waitset);
634 sigaddset(&waitset, SIG_IPI);
635 sigaddset(&waitset, SIGBUS);
638 qemu_mutex_unlock(&qemu_global_mutex);
640 r = sigtimedwait(&waitset, &siginfo, &ts);
643 qemu_mutex_lock(&qemu_global_mutex);
645 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
646 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
652 if (kvm_on_sigbus_vcpu(env, siginfo.si_code, siginfo.si_addr)) {
660 r = sigpending(&chkset);
662 fprintf(stderr, "sigpending: %s\n", strerror(e));
665 } while (sigismember(&chkset, SIG_IPI) || sigismember(&chkset, SIGBUS));
668 static void qemu_kvm_wait_io_event(CPUState *env)
670 while (!cpu_has_work(env))
671 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
673 qemu_kvm_eat_signal(env, 0);
674 qemu_wait_io_event_common(env);
677 static int qemu_cpu_exec(CPUState *env);
679 static void *kvm_cpu_thread_fn(void *arg)
684 qemu_mutex_lock(&qemu_global_mutex);
685 qemu_thread_self(env->thread);
687 r = kvm_init_vcpu(env);
689 fprintf(stderr, "kvm_init_vcpu failed: %s\n", strerror(-r));
693 qemu_kvm_init_cpu_signals(env);
695 /* signal CPU creation */
697 qemu_cond_signal(&qemu_cpu_cond);
699 /* and wait for machine initialization */
700 while (!qemu_system_ready)
701 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
704 if (cpu_can_run(env))
706 qemu_kvm_wait_io_event(env);
712 static void *tcg_cpu_thread_fn(void *arg)
716 qemu_tcg_init_cpu_signals();
717 qemu_thread_self(env->thread);
719 /* signal CPU creation */
720 qemu_mutex_lock(&qemu_global_mutex);
721 for (env = first_cpu; env != NULL; env = env->next_cpu)
723 qemu_cond_signal(&qemu_cpu_cond);
725 /* and wait for machine initialization */
726 while (!qemu_system_ready)
727 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
731 qemu_tcg_wait_io_event();
737 void qemu_cpu_kick(void *_env)
739 CPUState *env = _env;
740 qemu_cond_broadcast(env->halt_cond);
741 if (!env->thread_kicked) {
742 qemu_thread_signal(env->thread, SIG_IPI);
743 env->thread_kicked = true;
747 int qemu_cpu_self(void *_env)
749 CPUState *env = _env;
752 qemu_thread_self(&this);
754 return qemu_thread_equal(&this, env->thread);
757 void qemu_mutex_lock_iothread(void)
760 qemu_mutex_lock(&qemu_global_mutex);
762 qemu_mutex_lock(&qemu_fair_mutex);
763 if (qemu_mutex_trylock(&qemu_global_mutex)) {
764 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
765 qemu_mutex_lock(&qemu_global_mutex);
767 qemu_mutex_unlock(&qemu_fair_mutex);
771 void qemu_mutex_unlock_iothread(void)
773 qemu_mutex_unlock(&qemu_global_mutex);
776 static int all_vcpus_paused(void)
778 CPUState *penv = first_cpu;
783 penv = (CPUState *)penv->next_cpu;
789 void pause_all_vcpus(void)
791 CPUState *penv = first_cpu;
796 penv = (CPUState *)penv->next_cpu;
799 while (!all_vcpus_paused()) {
800 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
804 penv = (CPUState *)penv->next_cpu;
809 void resume_all_vcpus(void)
811 CPUState *penv = first_cpu;
817 penv = (CPUState *)penv->next_cpu;
821 static void tcg_init_vcpu(void *_env)
823 CPUState *env = _env;
824 /* share a single thread for all cpus with TCG */
825 if (!tcg_cpu_thread) {
826 env->thread = qemu_mallocz(sizeof(QemuThread));
827 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
828 qemu_cond_init(env->halt_cond);
829 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
830 while (env->created == 0)
831 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
832 tcg_cpu_thread = env->thread;
833 tcg_halt_cond = env->halt_cond;
835 env->thread = tcg_cpu_thread;
836 env->halt_cond = tcg_halt_cond;
840 static void kvm_start_vcpu(CPUState *env)
842 env->thread = qemu_mallocz(sizeof(QemuThread));
843 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
844 qemu_cond_init(env->halt_cond);
845 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
846 while (env->created == 0)
847 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
850 void qemu_init_vcpu(void *_env)
852 CPUState *env = _env;
854 env->nr_cores = smp_cores;
855 env->nr_threads = smp_threads;
862 void qemu_notify_event(void)
864 qemu_event_increment();
867 static void qemu_system_vmstop_request(int reason)
869 vmstop_requested = reason;
873 void cpu_stop_current(void)
875 if (cpu_single_env) {
876 cpu_single_env->stopped = 1;
877 cpu_exit(cpu_single_env);
881 void vm_stop(int reason)
884 qemu_thread_self(&me);
886 if (!qemu_thread_equal(&me, &io_thread)) {
887 qemu_system_vmstop_request(reason);
889 * FIXME: should not return to device code in case
890 * vm_stop() has been requested.
900 static int qemu_cpu_exec(CPUState *env)
903 #ifdef CONFIG_PROFILER
907 #ifdef CONFIG_PROFILER
908 ti = profile_getclock();
913 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
914 env->icount_decr.u16.low = 0;
915 env->icount_extra = 0;
916 count = qemu_icount_round (qemu_next_deadline());
917 qemu_icount += count;
918 decr = (count > 0xffff) ? 0xffff : count;
920 env->icount_decr.u16.low = decr;
921 env->icount_extra = count;
924 #ifdef CONFIG_PROFILER
925 qemu_time += profile_getclock() - ti;
928 /* Fold pending instructions back into the
929 instruction counter, and clear the interrupt flag. */
930 qemu_icount -= (env->icount_decr.u16.low
931 + env->icount_extra);
932 env->icount_decr.u32 = 0;
933 env->icount_extra = 0;
938 bool cpu_exec_all(void)
940 if (next_cpu == NULL)
941 next_cpu = first_cpu;
942 for (; next_cpu != NULL && !exit_request; next_cpu = next_cpu->next_cpu) {
943 CPUState *env = next_cpu;
945 qemu_clock_enable(vm_clock,
946 (env->singlestep_enabled & SSTEP_NOTIMER) == 0);
948 if (qemu_alarm_pending())
950 if (cpu_can_run(env)) {
951 if (qemu_cpu_exec(env) == EXCP_DEBUG) {
954 } else if (env->stop) {
959 return any_cpu_has_work();
962 void set_numa_modes(void)
967 for (env = first_cpu; env != NULL; env = env->next_cpu) {
968 for (i = 0; i < nb_numa_nodes; i++) {
969 if (node_cpumask[i] & (1 << env->cpu_index)) {
976 void set_cpu_log(const char *optarg)
979 const CPULogItem *item;
981 mask = cpu_str_to_log_mask(optarg);
983 printf("Log items (comma separated):\n");
984 for (item = cpu_log_items; item->mask != 0; item++) {
985 printf("%-10s %s\n", item->name, item->help);
992 /* Return the virtual CPU time, based on the instruction counter. */
993 int64_t cpu_get_icount(void)
996 CPUState *env = cpu_single_env;;
998 icount = qemu_icount;
1000 if (!can_do_io(env)) {
1001 fprintf(stderr, "Bad clock read\n");
1003 icount -= (env->icount_decr.u16.low + env->icount_extra);
1005 return qemu_icount_bias + (icount << icount_time_shift);
1008 void list_cpus(FILE *f, fprintf_function cpu_fprintf, const char *optarg)
1010 /* XXX: implement xxx_cpu_list for targets that still miss it */
1011 #if defined(cpu_list_id)
1012 cpu_list_id(f, cpu_fprintf, optarg);
1013 #elif defined(cpu_list)
1014 cpu_list(f, cpu_fprintf); /* deprecated */