Merge remote-tracking branch 'qemu/master'
[qemu/ar7.git] / cpu-exec.c
blob34fdb0facc8e46b905470ec2f8116a729d780036
1 /*
2 * emulator main execution loop
4 * Copyright (c) 2003-2005 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 #include "cpu.h"
21 #include "trace.h"
22 #include "disas/disas.h"
23 #include "tcg.h"
24 #include "qemu/atomic.h"
25 #include "sysemu/qtest.h"
26 #include "qemu/timer.h"
27 #include "exec/address-spaces.h"
28 #include "exec/memory-internal.h"
29 #include "qemu/rcu.h"
30 #include "exec/tb-hash.h"
32 #if defined(_WIN64)
33 /* On w64, sigsetjmp is implemented by _setjmp which needs a second parameter.
34 * If this parameter is NULL, longjump does no stack unwinding.
35 * That is what we need for QEMU. Passing the value of register rsp (default)
36 * lets longjmp try a stack unwinding which will crash with generated code. */
37 #define sigsetjmp(env, savesigs) _setjmp(env, NULL)
38 #endif
40 /* -icount align implementation. */
42 typedef struct SyncClocks {
43 int64_t diff_clk;
44 int64_t last_cpu_icount;
45 int64_t realtime_clock;
46 } SyncClocks;
48 #if !defined(CONFIG_USER_ONLY)
49 /* Allow the guest to have a max 3ms advance.
50 * The difference between the 2 clocks could therefore
51 * oscillate around 0.
53 #define VM_CLOCK_ADVANCE 3000000
54 #define THRESHOLD_REDUCE 1.5
55 #define MAX_DELAY_PRINT_RATE 2000000000LL
56 #define MAX_NB_PRINTS 100
58 static void align_clocks(SyncClocks *sc, const CPUState *cpu)
60 int64_t cpu_icount;
62 if (!icount_align_option) {
63 return;
66 cpu_icount = cpu->icount_extra + cpu->icount_decr.u16.low;
67 sc->diff_clk += cpu_icount_to_ns(sc->last_cpu_icount - cpu_icount);
68 sc->last_cpu_icount = cpu_icount;
70 if (sc->diff_clk > VM_CLOCK_ADVANCE) {
71 #ifndef _WIN32
72 struct timespec sleep_delay, rem_delay;
73 sleep_delay.tv_sec = sc->diff_clk / 1000000000LL;
74 sleep_delay.tv_nsec = sc->diff_clk % 1000000000LL;
75 if (nanosleep(&sleep_delay, &rem_delay) < 0) {
76 sc->diff_clk = rem_delay.tv_sec * 1000000000LL + rem_delay.tv_nsec;
77 } else {
78 sc->diff_clk = 0;
80 #else
81 Sleep(sc->diff_clk / SCALE_MS);
82 sc->diff_clk = 0;
83 #endif
87 static void print_delay(const SyncClocks *sc)
89 static float threshold_delay;
90 static int64_t last_realtime_clock;
91 static int nb_prints;
93 if (icount_align_option &&
94 sc->realtime_clock - last_realtime_clock >= MAX_DELAY_PRINT_RATE &&
95 nb_prints < MAX_NB_PRINTS) {
96 if ((-sc->diff_clk / (float)1000000000LL > threshold_delay) ||
97 (-sc->diff_clk / (float)1000000000LL <
98 (threshold_delay - THRESHOLD_REDUCE))) {
99 threshold_delay = (-sc->diff_clk / 1000000000LL) + 1;
100 printf("Warning: The guest is now late by %.1f to %.1f seconds\n",
101 threshold_delay - 1,
102 threshold_delay);
103 nb_prints++;
104 last_realtime_clock = sc->realtime_clock;
109 static void init_delay_params(SyncClocks *sc,
110 const CPUState *cpu)
112 if (!icount_align_option) {
113 return;
115 sc->realtime_clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT);
116 sc->diff_clk = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) - sc->realtime_clock;
117 sc->last_cpu_icount = cpu->icount_extra + cpu->icount_decr.u16.low;
118 if (sc->diff_clk < max_delay) {
119 max_delay = sc->diff_clk;
121 if (sc->diff_clk > max_advance) {
122 max_advance = sc->diff_clk;
125 /* Print every 2s max if the guest is late. We limit the number
126 of printed messages to NB_PRINT_MAX(currently 100) */
127 print_delay(sc);
129 #else
130 static void align_clocks(SyncClocks *sc, const CPUState *cpu)
134 static void init_delay_params(SyncClocks *sc, const CPUState *cpu)
137 #endif /* CONFIG USER ONLY */
139 void QEMU_NORETURN cpu_loop_exit(CPUState *cpu)
141 cpu->current_tb = NULL;
142 siglongjmp(cpu->jmp_env, 1);
145 /* exit the current TB from a signal handler. The host registers are
146 restored in a state compatible with the CPU emulator
148 #if defined(CONFIG_SOFTMMU)
149 void QEMU_NORETURN cpu_resume_from_signal(CPUState *cpu, void *puc)
151 /* XXX: restore cpu registers saved in host registers */
153 cpu->exception_index = -1;
154 siglongjmp(cpu->jmp_env, 1);
157 void cpu_reload_memory_map(CPUState *cpu)
159 AddressSpaceDispatch *d;
161 if (qemu_in_vcpu_thread()) {
162 /* Do not let the guest prolong the critical section as much as it
163 * as it desires.
165 * Currently, this is prevented by the I/O thread's periodinc kicking
166 * of the VCPU thread (iothread_requesting_mutex, qemu_cpu_kick_thread)
167 * but this will go away once TCG's execution moves out of the global
168 * mutex.
170 * This pair matches cpu_exec's rcu_read_lock()/rcu_read_unlock(), which
171 * only protects cpu->as->dispatch. Since we reload it below, we can
172 * split the critical section.
174 rcu_read_unlock();
175 rcu_read_lock();
178 /* The CPU and TLB are protected by the iothread lock. */
179 d = atomic_rcu_read(&cpu->as->dispatch);
180 cpu->memory_dispatch = d;
181 tlb_flush(cpu, 1);
183 #endif
185 /* Execute a TB, and fix up the CPU state afterwards if necessary */
186 static inline tcg_target_ulong cpu_tb_exec(CPUState *cpu, uint8_t *tb_ptr)
188 CPUArchState *env = cpu->env_ptr;
189 uintptr_t next_tb;
191 #if defined(DEBUG_DISAS)
192 if (qemu_loglevel_mask(CPU_LOG_TB_CPU)) {
193 #if defined(TARGET_I386)
194 log_cpu_state(cpu, CPU_DUMP_CCOP);
195 #elif defined(TARGET_M68K)
196 /* ??? Should not modify env state for dumping. */
197 cpu_m68k_flush_flags(env, env->cc_op);
198 env->cc_op = CC_OP_FLAGS;
199 env->sr = (env->sr & 0xffe0) | env->cc_dest | (env->cc_x << 4);
200 log_cpu_state(cpu, 0);
201 #else
202 log_cpu_state(cpu, 0);
203 #endif
205 #endif /* DEBUG_DISAS */
207 cpu->can_do_io = !use_icount;
208 next_tb = tcg_qemu_tb_exec(env, tb_ptr);
209 cpu->can_do_io = 1;
210 trace_exec_tb_exit((void *) (next_tb & ~TB_EXIT_MASK),
211 next_tb & TB_EXIT_MASK);
213 if ((next_tb & TB_EXIT_MASK) > TB_EXIT_IDX1) {
214 /* We didn't start executing this TB (eg because the instruction
215 * counter hit zero); we must restore the guest PC to the address
216 * of the start of the TB.
218 CPUClass *cc = CPU_GET_CLASS(cpu);
219 TranslationBlock *tb = (TranslationBlock *)(next_tb & ~TB_EXIT_MASK);
220 if (cc->synchronize_from_tb) {
221 cc->synchronize_from_tb(cpu, tb);
222 } else {
223 assert(cc->set_pc);
224 cc->set_pc(cpu, tb->pc);
227 if ((next_tb & TB_EXIT_MASK) == TB_EXIT_REQUESTED) {
228 /* We were asked to stop executing TBs (probably a pending
229 * interrupt. We've now stopped, so clear the flag.
231 cpu->tcg_exit_req = 0;
233 return next_tb;
236 /* Execute the code without caching the generated code. An interpreter
237 could be used if available. */
238 static void cpu_exec_nocache(CPUState *cpu, int max_cycles,
239 TranslationBlock *orig_tb)
241 TranslationBlock *tb;
243 /* Should never happen.
244 We only end up here when an existing TB is too long. */
245 if (max_cycles > CF_COUNT_MASK)
246 max_cycles = CF_COUNT_MASK;
248 tb = tb_gen_code(cpu, orig_tb->pc, orig_tb->cs_base, orig_tb->flags,
249 max_cycles | CF_NOCACHE);
250 tb->orig_tb = tcg_ctx.tb_ctx.tb_invalidated_flag ? NULL : orig_tb;
251 cpu->current_tb = tb;
252 /* execute the generated code */
253 trace_exec_tb_nocache(tb, tb->pc);
254 cpu_tb_exec(cpu, tb->tc_ptr);
255 cpu->current_tb = NULL;
256 tb_phys_invalidate(tb, -1);
257 tb_free(tb);
260 static TranslationBlock *tb_find_slow(CPUState *cpu,
261 target_ulong pc,
262 target_ulong cs_base,
263 uint64_t flags)
265 CPUArchState *env = (CPUArchState *)cpu->env_ptr;
266 TranslationBlock *tb, **ptb1;
267 unsigned int h;
268 tb_page_addr_t phys_pc, phys_page1;
269 target_ulong virt_page2;
271 tcg_ctx.tb_ctx.tb_invalidated_flag = 0;
273 /* find translated block using physical mappings */
274 phys_pc = get_page_addr_code(env, pc);
275 phys_page1 = phys_pc & TARGET_PAGE_MASK;
276 h = tb_phys_hash_func(phys_pc);
277 ptb1 = &tcg_ctx.tb_ctx.tb_phys_hash[h];
278 for(;;) {
279 tb = *ptb1;
280 if (!tb)
281 goto not_found;
282 if (tb->pc == pc &&
283 tb->page_addr[0] == phys_page1 &&
284 tb->cs_base == cs_base &&
285 tb->flags == flags) {
286 /* check next page if needed */
287 if (tb->page_addr[1] != -1) {
288 tb_page_addr_t phys_page2;
290 virt_page2 = (pc & TARGET_PAGE_MASK) +
291 TARGET_PAGE_SIZE;
292 phys_page2 = get_page_addr_code(env, virt_page2);
293 if (tb->page_addr[1] == phys_page2)
294 goto found;
295 } else {
296 goto found;
299 ptb1 = &tb->phys_hash_next;
301 not_found:
302 /* if no translated code available, then translate it now */
303 tb = tb_gen_code(cpu, pc, cs_base, flags, 0);
305 found:
306 /* Move the last found TB to the head of the list */
307 if (likely(*ptb1)) {
308 *ptb1 = tb->phys_hash_next;
309 tb->phys_hash_next = tcg_ctx.tb_ctx.tb_phys_hash[h];
310 tcg_ctx.tb_ctx.tb_phys_hash[h] = tb;
312 /* we add the TB in the virtual pc hash table */
313 cpu->tb_jmp_cache[tb_jmp_cache_hash_func(pc)] = tb;
314 return tb;
317 static inline TranslationBlock *tb_find_fast(CPUState *cpu)
319 CPUArchState *env = (CPUArchState *)cpu->env_ptr;
320 TranslationBlock *tb;
321 target_ulong cs_base, pc;
322 int flags;
324 /* we record a subset of the CPU state. It will
325 always be the same before a given translated block
326 is executed. */
327 cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags);
328 tb = cpu->tb_jmp_cache[tb_jmp_cache_hash_func(pc)];
329 if (unlikely(!tb || tb->pc != pc || tb->cs_base != cs_base ||
330 tb->flags != flags)) {
331 tb = tb_find_slow(cpu, pc, cs_base, flags);
333 return tb;
336 static void cpu_handle_debug_exception(CPUState *cpu)
338 CPUClass *cc = CPU_GET_CLASS(cpu);
339 CPUWatchpoint *wp;
341 if (!cpu->watchpoint_hit) {
342 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
343 wp->flags &= ~BP_WATCHPOINT_HIT;
347 cc->debug_excp_handler(cpu);
350 /* main execution loop */
352 volatile sig_atomic_t exit_request;
354 int cpu_exec(CPUState *cpu)
356 CPUClass *cc = CPU_GET_CLASS(cpu);
357 #ifdef TARGET_I386
358 X86CPU *x86_cpu = X86_CPU(cpu);
359 CPUArchState *env = &x86_cpu->env;
360 #endif
361 int ret, interrupt_request;
362 TranslationBlock *tb;
363 uint8_t *tc_ptr;
364 uintptr_t next_tb;
365 SyncClocks sc;
367 /* This must be volatile so it is not trashed by longjmp() */
368 volatile bool have_tb_lock = false;
370 if (cpu->halted) {
371 if (!cpu_has_work(cpu)) {
372 return EXCP_HALTED;
375 cpu->halted = 0;
378 current_cpu = cpu;
380 /* As long as current_cpu is null, up to the assignment just above,
381 * requests by other threads to exit the execution loop are expected to
382 * be issued using the exit_request global. We must make sure that our
383 * evaluation of the global value is performed past the current_cpu
384 * value transition point, which requires a memory barrier as well as
385 * an instruction scheduling constraint on modern architectures. */
386 smp_mb();
388 rcu_read_lock();
390 if (unlikely(exit_request)) {
391 cpu->exit_request = 1;
394 cc->cpu_exec_enter(cpu);
396 /* Calculate difference between guest clock and host clock.
397 * This delay includes the delay of the last cycle, so
398 * what we have to do is sleep until it is 0. As for the
399 * advance/delay we gain here, we try to fix it next time.
401 init_delay_params(&sc, cpu);
403 /* prepare setjmp context for exception handling */
404 for(;;) {
405 if (sigsetjmp(cpu->jmp_env, 0) == 0) {
406 /* if an exception is pending, we execute it here */
407 if (cpu->exception_index >= 0) {
408 if (cpu->exception_index >= EXCP_INTERRUPT) {
409 /* exit request from the cpu execution loop */
410 ret = cpu->exception_index;
411 if (ret == EXCP_DEBUG) {
412 cpu_handle_debug_exception(cpu);
414 cpu->exception_index = -1;
415 break;
416 } else {
417 #if defined(CONFIG_USER_ONLY)
418 /* if user mode only, we simulate a fake exception
419 which will be handled outside the cpu execution
420 loop */
421 #if defined(TARGET_I386)
422 cc->do_interrupt(cpu);
423 #endif
424 ret = cpu->exception_index;
425 cpu->exception_index = -1;
426 break;
427 #else
428 cc->do_interrupt(cpu);
429 cpu->exception_index = -1;
430 #endif
434 next_tb = 0; /* force lookup of first TB */
435 for(;;) {
436 interrupt_request = cpu->interrupt_request;
437 if (unlikely(interrupt_request)) {
438 if (unlikely(cpu->singlestep_enabled & SSTEP_NOIRQ)) {
439 /* Mask out external interrupts for this step. */
440 interrupt_request &= ~CPU_INTERRUPT_SSTEP_MASK;
442 if (interrupt_request & CPU_INTERRUPT_DEBUG) {
443 cpu->interrupt_request &= ~CPU_INTERRUPT_DEBUG;
444 cpu->exception_index = EXCP_DEBUG;
445 cpu_loop_exit(cpu);
447 if (interrupt_request & CPU_INTERRUPT_HALT) {
448 cpu->interrupt_request &= ~CPU_INTERRUPT_HALT;
449 cpu->halted = 1;
450 cpu->exception_index = EXCP_HLT;
451 cpu_loop_exit(cpu);
453 #if defined(TARGET_I386)
454 if (interrupt_request & CPU_INTERRUPT_INIT) {
455 cpu_svm_check_intercept_param(env, SVM_EXIT_INIT, 0);
456 do_cpu_init(x86_cpu);
457 cpu->exception_index = EXCP_HALTED;
458 cpu_loop_exit(cpu);
460 #else
461 if (interrupt_request & CPU_INTERRUPT_RESET) {
462 cpu_reset(cpu);
464 #endif
465 /* The target hook has 3 exit conditions:
466 False when the interrupt isn't processed,
467 True when it is, and we should restart on a new TB,
468 and via longjmp via cpu_loop_exit. */
469 if (cc->cpu_exec_interrupt(cpu, interrupt_request)) {
470 next_tb = 0;
472 /* Don't use the cached interrupt_request value,
473 do_interrupt may have updated the EXITTB flag. */
474 if (cpu->interrupt_request & CPU_INTERRUPT_EXITTB) {
475 cpu->interrupt_request &= ~CPU_INTERRUPT_EXITTB;
476 /* ensure that no TB jump will be modified as
477 the program flow was changed */
478 next_tb = 0;
481 if (unlikely(cpu->exit_request)) {
482 cpu->exit_request = 0;
483 cpu->exception_index = EXCP_INTERRUPT;
484 cpu_loop_exit(cpu);
486 spin_lock(&tcg_ctx.tb_ctx.tb_lock);
487 have_tb_lock = true;
488 tb = tb_find_fast(cpu);
489 /* Note: we do it here to avoid a gcc bug on Mac OS X when
490 doing it in tb_find_slow */
491 if (tcg_ctx.tb_ctx.tb_invalidated_flag) {
492 /* as some TB could have been invalidated because
493 of memory exceptions while generating the code, we
494 must recompute the hash index here */
495 next_tb = 0;
496 tcg_ctx.tb_ctx.tb_invalidated_flag = 0;
498 if (qemu_loglevel_mask(CPU_LOG_EXEC)) {
499 qemu_log("Trace %p [" TARGET_FMT_lx "] %s\n",
500 tb->tc_ptr, tb->pc, lookup_symbol(tb->pc));
502 /* see if we can patch the calling TB. When the TB
503 spans two pages, we cannot safely do a direct
504 jump. */
505 if (next_tb != 0 && tb->page_addr[1] == -1) {
506 tb_add_jump((TranslationBlock *)(next_tb & ~TB_EXIT_MASK),
507 next_tb & TB_EXIT_MASK, tb);
509 have_tb_lock = false;
510 spin_unlock(&tcg_ctx.tb_ctx.tb_lock);
512 /* cpu_interrupt might be called while translating the
513 TB, but before it is linked into a potentially
514 infinite loop and becomes env->current_tb. Avoid
515 starting execution if there is a pending interrupt. */
516 cpu->current_tb = tb;
517 barrier();
518 if (likely(!cpu->exit_request)) {
519 trace_exec_tb(tb, tb->pc);
520 tc_ptr = tb->tc_ptr;
521 /* execute the generated code */
522 next_tb = cpu_tb_exec(cpu, tc_ptr);
523 switch (next_tb & TB_EXIT_MASK) {
524 case TB_EXIT_REQUESTED:
525 /* Something asked us to stop executing
526 * chained TBs; just continue round the main
527 * loop. Whatever requested the exit will also
528 * have set something else (eg exit_request or
529 * interrupt_request) which we will handle
530 * next time around the loop.
532 next_tb = 0;
533 break;
534 case TB_EXIT_ICOUNT_EXPIRED:
536 /* Instruction counter expired. */
537 int insns_left = cpu->icount_decr.u32;
538 if (cpu->icount_extra && insns_left >= 0) {
539 /* Refill decrementer and continue execution. */
540 cpu->icount_extra += insns_left;
541 insns_left = MIN(0xffff, cpu->icount_extra);
542 cpu->icount_extra -= insns_left;
543 cpu->icount_decr.u16.low = insns_left;
544 } else {
545 if (insns_left > 0) {
546 /* Execute remaining instructions. */
547 tb = (TranslationBlock *)(next_tb & ~TB_EXIT_MASK);
548 cpu_exec_nocache(cpu, insns_left, tb);
549 align_clocks(&sc, cpu);
551 cpu->exception_index = EXCP_INTERRUPT;
552 next_tb = 0;
553 cpu_loop_exit(cpu);
555 break;
557 default:
558 break;
561 cpu->current_tb = NULL;
562 /* Try to align the host and virtual clocks
563 if the guest is in advance */
564 align_clocks(&sc, cpu);
565 /* reset soft MMU for next block (it can currently
566 only be set by a memory fault) */
567 } /* for(;;) */
568 } else {
569 /* Reload env after longjmp - the compiler may have smashed all
570 * local variables as longjmp is marked 'noreturn'. */
571 /* TODO: Fix comment in 2014 - then it was wrong. */
572 g_assert(cpu == current_cpu);
573 g_assert(cc == CPU_GET_CLASS(cpu));
574 cpu->can_do_io = 1;
575 #ifdef TARGET_I386
576 g_assert(x86_cpu == X86_CPU(cpu));
577 g_assert(env == cpu->env_ptr);
578 #endif
579 if (have_tb_lock) {
580 spin_unlock(&tcg_ctx.tb_ctx.tb_lock);
581 have_tb_lock = false;
584 } /* for(;;) */
586 cc->cpu_exec_exit(cpu);
587 rcu_read_unlock();
589 /* fail safe : never use current_cpu outside cpu_exec() */
590 current_cpu = NULL;
591 return ret;