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/>.
22 #include "disas/disas.h"
24 #include "qemu/atomic.h"
25 #include "sysemu/qtest.h"
26 #include "qemu/timer.h"
27 #include "exec/address-spaces.h"
29 #include "exec/tb-hash.h"
30 #if defined(TARGET_I386) && !defined(CONFIG_USER_ONLY)
31 #include "hw/i386/apic.h"
33 #include "sysemu/replay.h"
36 /* On w64, sigsetjmp is implemented by _setjmp which needs a second parameter.
37 * If this parameter is NULL, longjump does no stack unwinding.
38 * That is what we need for QEMU. Passing the value of register rsp (default)
39 * lets longjmp try a stack unwinding which will crash with generated code. */
40 #define sigsetjmp(env, savesigs) _setjmp(env, NULL)
43 /* -icount align implementation. */
45 typedef struct SyncClocks
{
47 int64_t last_cpu_icount
;
48 int64_t realtime_clock
;
51 #if !defined(CONFIG_USER_ONLY)
52 /* Allow the guest to have a max 3ms advance.
53 * The difference between the 2 clocks could therefore
56 #define VM_CLOCK_ADVANCE 3000000
57 #define THRESHOLD_REDUCE 1.5
58 #define MAX_DELAY_PRINT_RATE 2000000000LL
59 #define MAX_NB_PRINTS 100
61 static void align_clocks(SyncClocks
*sc
, const CPUState
*cpu
)
65 if (!icount_align_option
) {
69 cpu_icount
= cpu
->icount_extra
+ cpu
->icount_decr
.u16
.low
;
70 sc
->diff_clk
+= cpu_icount_to_ns(sc
->last_cpu_icount
- cpu_icount
);
71 sc
->last_cpu_icount
= cpu_icount
;
73 if (sc
->diff_clk
> VM_CLOCK_ADVANCE
) {
75 struct timespec sleep_delay
, rem_delay
;
76 sleep_delay
.tv_sec
= sc
->diff_clk
/ 1000000000LL;
77 sleep_delay
.tv_nsec
= sc
->diff_clk
% 1000000000LL;
78 if (nanosleep(&sleep_delay
, &rem_delay
) < 0) {
79 sc
->diff_clk
= rem_delay
.tv_sec
* 1000000000LL + rem_delay
.tv_nsec
;
84 Sleep(sc
->diff_clk
/ SCALE_MS
);
90 static void print_delay(const SyncClocks
*sc
)
92 static float threshold_delay
;
93 static int64_t last_realtime_clock
;
96 if (icount_align_option
&&
97 sc
->realtime_clock
- last_realtime_clock
>= MAX_DELAY_PRINT_RATE
&&
98 nb_prints
< MAX_NB_PRINTS
) {
99 if ((-sc
->diff_clk
/ (float)1000000000LL > threshold_delay
) ||
100 (-sc
->diff_clk
/ (float)1000000000LL <
101 (threshold_delay
- THRESHOLD_REDUCE
))) {
102 threshold_delay
= (-sc
->diff_clk
/ 1000000000LL) + 1;
103 printf("Warning: The guest is now late by %.1f to %.1f seconds\n",
107 last_realtime_clock
= sc
->realtime_clock
;
112 static void init_delay_params(SyncClocks
*sc
,
115 if (!icount_align_option
) {
118 sc
->realtime_clock
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT
);
119 sc
->diff_clk
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
) - sc
->realtime_clock
;
120 sc
->last_cpu_icount
= cpu
->icount_extra
+ cpu
->icount_decr
.u16
.low
;
121 if (sc
->diff_clk
< max_delay
) {
122 max_delay
= sc
->diff_clk
;
124 if (sc
->diff_clk
> max_advance
) {
125 max_advance
= sc
->diff_clk
;
128 /* Print every 2s max if the guest is late. We limit the number
129 of printed messages to NB_PRINT_MAX(currently 100) */
133 static void align_clocks(SyncClocks
*sc
, const CPUState
*cpu
)
137 static void init_delay_params(SyncClocks
*sc
, const CPUState
*cpu
)
140 #endif /* CONFIG USER ONLY */
142 /* Execute a TB, and fix up the CPU state afterwards if necessary */
143 static inline tcg_target_ulong
cpu_tb_exec(CPUState
*cpu
, uint8_t *tb_ptr
)
145 CPUArchState
*env
= cpu
->env_ptr
;
148 #if defined(DEBUG_DISAS)
149 if (qemu_loglevel_mask(CPU_LOG_TB_CPU
)) {
150 #if defined(TARGET_I386)
151 log_cpu_state(cpu
, CPU_DUMP_CCOP
);
152 #elif defined(TARGET_M68K)
153 /* ??? Should not modify env state for dumping. */
154 cpu_m68k_flush_flags(env
, env
->cc_op
);
155 env
->cc_op
= CC_OP_FLAGS
;
156 env
->sr
= (env
->sr
& 0xffe0) | env
->cc_dest
| (env
->cc_x
<< 4);
157 log_cpu_state(cpu
, 0);
159 log_cpu_state(cpu
, 0);
162 #endif /* DEBUG_DISAS */
164 cpu
->can_do_io
= !use_icount
;
165 next_tb
= tcg_qemu_tb_exec(env
, tb_ptr
);
167 trace_exec_tb_exit((void *) (next_tb
& ~TB_EXIT_MASK
),
168 next_tb
& TB_EXIT_MASK
);
170 if ((next_tb
& TB_EXIT_MASK
) > TB_EXIT_IDX1
) {
171 /* We didn't start executing this TB (eg because the instruction
172 * counter hit zero); we must restore the guest PC to the address
173 * of the start of the TB.
175 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
176 TranslationBlock
*tb
= (TranslationBlock
*)(next_tb
& ~TB_EXIT_MASK
);
177 if (cc
->synchronize_from_tb
) {
178 cc
->synchronize_from_tb(cpu
, tb
);
181 cc
->set_pc(cpu
, tb
->pc
);
184 if ((next_tb
& TB_EXIT_MASK
) == TB_EXIT_REQUESTED
) {
185 /* We were asked to stop executing TBs (probably a pending
186 * interrupt. We've now stopped, so clear the flag.
188 cpu
->tcg_exit_req
= 0;
193 /* Execute the code without caching the generated code. An interpreter
194 could be used if available. */
195 static void cpu_exec_nocache(CPUState
*cpu
, int max_cycles
,
196 TranslationBlock
*orig_tb
, bool ignore_icount
)
198 TranslationBlock
*tb
;
200 /* Should never happen.
201 We only end up here when an existing TB is too long. */
202 if (max_cycles
> CF_COUNT_MASK
)
203 max_cycles
= CF_COUNT_MASK
;
205 tb
= tb_gen_code(cpu
, orig_tb
->pc
, orig_tb
->cs_base
, orig_tb
->flags
,
206 max_cycles
| CF_NOCACHE
207 | (ignore_icount
? CF_IGNORE_ICOUNT
: 0));
208 tb
->orig_tb
= tcg_ctx
.tb_ctx
.tb_invalidated_flag
? NULL
: orig_tb
;
209 cpu
->current_tb
= tb
;
210 /* execute the generated code */
211 trace_exec_tb_nocache(tb
, tb
->pc
);
212 cpu_tb_exec(cpu
, tb
->tc_ptr
);
213 cpu
->current_tb
= NULL
;
214 tb_phys_invalidate(tb
, -1);
218 static TranslationBlock
*tb_find_physical(CPUState
*cpu
,
220 target_ulong cs_base
,
223 CPUArchState
*env
= (CPUArchState
*)cpu
->env_ptr
;
224 TranslationBlock
*tb
, **ptb1
;
226 tb_page_addr_t phys_pc
, phys_page1
;
227 target_ulong virt_page2
;
229 tcg_ctx
.tb_ctx
.tb_invalidated_flag
= 0;
231 /* find translated block using physical mappings */
232 phys_pc
= get_page_addr_code(env
, pc
);
233 phys_page1
= phys_pc
& TARGET_PAGE_MASK
;
234 h
= tb_phys_hash_func(phys_pc
);
235 ptb1
= &tcg_ctx
.tb_ctx
.tb_phys_hash
[h
];
242 tb
->page_addr
[0] == phys_page1
&&
243 tb
->cs_base
== cs_base
&&
244 tb
->flags
== flags
) {
245 /* check next page if needed */
246 if (tb
->page_addr
[1] != -1) {
247 tb_page_addr_t phys_page2
;
249 virt_page2
= (pc
& TARGET_PAGE_MASK
) +
251 phys_page2
= get_page_addr_code(env
, virt_page2
);
252 if (tb
->page_addr
[1] == phys_page2
) {
259 ptb1
= &tb
->phys_hash_next
;
262 /* Move the TB to the head of the list */
263 *ptb1
= tb
->phys_hash_next
;
264 tb
->phys_hash_next
= tcg_ctx
.tb_ctx
.tb_phys_hash
[h
];
265 tcg_ctx
.tb_ctx
.tb_phys_hash
[h
] = tb
;
269 static TranslationBlock
*tb_find_slow(CPUState
*cpu
,
271 target_ulong cs_base
,
274 TranslationBlock
*tb
;
276 tb
= tb_find_physical(cpu
, pc
, cs_base
, flags
);
281 #ifdef CONFIG_USER_ONLY
282 /* mmap_lock is needed by tb_gen_code, and mmap_lock must be
283 * taken outside tb_lock. Since we're momentarily dropping
284 * tb_lock, there's a chance that our desired tb has been
290 tb
= tb_find_physical(cpu
, pc
, cs_base
, flags
);
297 /* if no translated code available, then translate it now */
298 tb
= tb_gen_code(cpu
, pc
, cs_base
, flags
, 0);
300 #ifdef CONFIG_USER_ONLY
305 /* we add the TB in the virtual pc hash table */
306 cpu
->tb_jmp_cache
[tb_jmp_cache_hash_func(pc
)] = tb
;
310 static inline TranslationBlock
*tb_find_fast(CPUState
*cpu
)
312 CPUArchState
*env
= (CPUArchState
*)cpu
->env_ptr
;
313 TranslationBlock
*tb
;
314 target_ulong cs_base
, pc
;
317 /* we record a subset of the CPU state. It will
318 always be the same before a given translated block
320 cpu_get_tb_cpu_state(env
, &pc
, &cs_base
, &flags
);
321 tb
= cpu
->tb_jmp_cache
[tb_jmp_cache_hash_func(pc
)];
322 if (unlikely(!tb
|| tb
->pc
!= pc
|| tb
->cs_base
!= cs_base
||
323 tb
->flags
!= flags
)) {
324 tb
= tb_find_slow(cpu
, pc
, cs_base
, flags
);
329 static void cpu_handle_debug_exception(CPUState
*cpu
)
331 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
334 if (!cpu
->watchpoint_hit
) {
335 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
336 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
340 cc
->debug_excp_handler(cpu
);
343 /* main execution loop */
345 int cpu_exec(CPUState
*cpu
)
347 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
349 X86CPU
*x86_cpu
= X86_CPU(cpu
);
350 CPUArchState
*env
= &x86_cpu
->env
;
352 int ret
, interrupt_request
;
353 TranslationBlock
*tb
;
358 /* replay_interrupt may need current_cpu */
362 #if defined(TARGET_I386) && !defined(CONFIG_USER_ONLY)
363 if ((cpu
->interrupt_request
& CPU_INTERRUPT_POLL
)
364 && replay_interrupt()) {
365 apic_poll_irq(x86_cpu
->apic_state
);
366 cpu_reset_interrupt(cpu
, CPU_INTERRUPT_POLL
);
369 if (!cpu_has_work(cpu
)) {
377 atomic_mb_set(&tcg_current_cpu
, cpu
);
380 if (unlikely(atomic_mb_read(&exit_request
))) {
381 cpu
->exit_request
= 1;
384 cc
->cpu_exec_enter(cpu
);
386 /* Calculate difference between guest clock and host clock.
387 * This delay includes the delay of the last cycle, so
388 * what we have to do is sleep until it is 0. As for the
389 * advance/delay we gain here, we try to fix it next time.
391 init_delay_params(&sc
, cpu
);
393 /* prepare setjmp context for exception handling */
395 if (sigsetjmp(cpu
->jmp_env
, 0) == 0) {
396 /* if an exception is pending, we execute it here */
397 if (cpu
->exception_index
>= 0) {
398 if (cpu
->exception_index
>= EXCP_INTERRUPT
) {
399 /* exit request from the cpu execution loop */
400 ret
= cpu
->exception_index
;
401 if (ret
== EXCP_DEBUG
) {
402 cpu_handle_debug_exception(cpu
);
404 cpu
->exception_index
= -1;
407 #if defined(CONFIG_USER_ONLY)
408 /* if user mode only, we simulate a fake exception
409 which will be handled outside the cpu execution
411 #if defined(TARGET_I386)
412 cc
->do_interrupt(cpu
);
414 ret
= cpu
->exception_index
;
415 cpu
->exception_index
= -1;
418 if (replay_exception()) {
419 cc
->do_interrupt(cpu
);
420 cpu
->exception_index
= -1;
421 } else if (!replay_has_interrupt()) {
422 /* give a chance to iothread in replay mode */
423 ret
= EXCP_INTERRUPT
;
428 } else if (replay_has_exception()
429 && cpu
->icount_decr
.u16
.low
+ cpu
->icount_extra
== 0) {
430 /* try to cause an exception pending in the log */
431 cpu_exec_nocache(cpu
, 1, tb_find_fast(cpu
), true);
436 next_tb
= 0; /* force lookup of first TB */
438 interrupt_request
= cpu
->interrupt_request
;
439 if (unlikely(interrupt_request
)) {
440 if (unlikely(cpu
->singlestep_enabled
& SSTEP_NOIRQ
)) {
441 /* Mask out external interrupts for this step. */
442 interrupt_request
&= ~CPU_INTERRUPT_SSTEP_MASK
;
444 if (interrupt_request
& CPU_INTERRUPT_DEBUG
) {
445 cpu
->interrupt_request
&= ~CPU_INTERRUPT_DEBUG
;
446 cpu
->exception_index
= EXCP_DEBUG
;
449 if (replay_mode
== REPLAY_MODE_PLAY
450 && !replay_has_interrupt()) {
452 } else if (interrupt_request
& CPU_INTERRUPT_HALT
) {
454 cpu
->interrupt_request
&= ~CPU_INTERRUPT_HALT
;
456 cpu
->exception_index
= EXCP_HLT
;
459 #if defined(TARGET_I386)
460 else if (interrupt_request
& CPU_INTERRUPT_INIT
) {
462 cpu_svm_check_intercept_param(env
, SVM_EXIT_INIT
, 0);
463 do_cpu_init(x86_cpu
);
464 cpu
->exception_index
= EXCP_HALTED
;
468 else if (interrupt_request
& CPU_INTERRUPT_RESET
) {
474 /* The target hook has 3 exit conditions:
475 False when the interrupt isn't processed,
476 True when it is, and we should restart on a new TB,
477 and via longjmp via cpu_loop_exit. */
480 if (cc
->cpu_exec_interrupt(cpu
, interrupt_request
)) {
484 /* Don't use the cached interrupt_request value,
485 do_interrupt may have updated the EXITTB flag. */
486 if (cpu
->interrupt_request
& CPU_INTERRUPT_EXITTB
) {
487 cpu
->interrupt_request
&= ~CPU_INTERRUPT_EXITTB
;
488 /* ensure that no TB jump will be modified as
489 the program flow was changed */
493 if (unlikely(cpu
->exit_request
494 || replay_has_interrupt())) {
495 cpu
->exit_request
= 0;
496 cpu
->exception_index
= EXCP_INTERRUPT
;
500 tb
= tb_find_fast(cpu
);
501 /* Note: we do it here to avoid a gcc bug on Mac OS X when
502 doing it in tb_find_slow */
503 if (tcg_ctx
.tb_ctx
.tb_invalidated_flag
) {
504 /* as some TB could have been invalidated because
505 of memory exceptions while generating the code, we
506 must recompute the hash index here */
508 tcg_ctx
.tb_ctx
.tb_invalidated_flag
= 0;
510 if (qemu_loglevel_mask(CPU_LOG_EXEC
)) {
511 qemu_log("Trace %p [" TARGET_FMT_lx
"] %s\n",
512 tb
->tc_ptr
, tb
->pc
, lookup_symbol(tb
->pc
));
514 /* see if we can patch the calling TB. When the TB
515 spans two pages, we cannot safely do a direct
517 if (next_tb
!= 0 && tb
->page_addr
[1] == -1
518 && !qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN
)) {
519 tb_add_jump((TranslationBlock
*)(next_tb
& ~TB_EXIT_MASK
),
520 next_tb
& TB_EXIT_MASK
, tb
);
523 if (likely(!cpu
->exit_request
)) {
524 trace_exec_tb(tb
, tb
->pc
);
526 /* execute the generated code */
527 cpu
->current_tb
= tb
;
528 next_tb
= cpu_tb_exec(cpu
, tc_ptr
);
529 cpu
->current_tb
= NULL
;
530 switch (next_tb
& TB_EXIT_MASK
) {
531 case TB_EXIT_REQUESTED
:
532 /* Something asked us to stop executing
533 * chained TBs; just continue round the main
534 * loop. Whatever requested the exit will also
535 * have set something else (eg exit_request or
536 * interrupt_request) which we will handle
537 * next time around the loop. But we need to
538 * ensure the tcg_exit_req read in generated code
539 * comes before the next read of cpu->exit_request
540 * or cpu->interrupt_request.
545 case TB_EXIT_ICOUNT_EXPIRED
:
547 /* Instruction counter expired. */
548 int insns_left
= cpu
->icount_decr
.u32
;
549 if (cpu
->icount_extra
&& insns_left
>= 0) {
550 /* Refill decrementer and continue execution. */
551 cpu
->icount_extra
+= insns_left
;
552 insns_left
= MIN(0xffff, cpu
->icount_extra
);
553 cpu
->icount_extra
-= insns_left
;
554 cpu
->icount_decr
.u16
.low
= insns_left
;
556 if (insns_left
> 0) {
557 /* Execute remaining instructions. */
558 tb
= (TranslationBlock
*)(next_tb
& ~TB_EXIT_MASK
);
559 cpu_exec_nocache(cpu
, insns_left
, tb
, false);
560 align_clocks(&sc
, cpu
);
562 cpu
->exception_index
= EXCP_INTERRUPT
;
572 /* Try to align the host and virtual clocks
573 if the guest is in advance */
574 align_clocks(&sc
, cpu
);
575 /* reset soft MMU for next block (it can currently
576 only be set by a memory fault) */
579 #if defined(__clang__) || !QEMU_GNUC_PREREQ(4, 6)
580 /* Some compilers wrongly smash all local variables after
581 * siglongjmp. There were bug reports for gcc 4.5.0 and clang.
582 * Reload essential local variables here for those compilers.
583 * Newer versions of gcc would complain about this code (-Wclobbered). */
585 cc
= CPU_GET_CLASS(cpu
);
587 x86_cpu
= X86_CPU(cpu
);
590 #else /* buggy compiler */
591 /* Assert that the compiler does not smash local variables. */
592 g_assert(cpu
== current_cpu
);
593 g_assert(cc
== CPU_GET_CLASS(cpu
));
595 g_assert(x86_cpu
== X86_CPU(cpu
));
596 g_assert(env
== &x86_cpu
->env
);
598 #endif /* buggy compiler */
604 cc
->cpu_exec_exit(cpu
);
607 /* fail safe : never use current_cpu outside cpu_exec() */
610 /* Does not need atomic_mb_set because a spurious wakeup is okay. */
611 atomic_set(&tcg_current_cpu
, NULL
);