cpu-exec.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. /*
  2. * emulator main execution loop
  3. *
  4. * Copyright (c) 2003-2005 Fabrice Bellard
  5. *
  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.1 of the License, or (at your option) any later version.
  10. *
  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.
  15. *
  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/>.
  18. */
  19. #include "qemu/osdep.h"
  20. #include "qemu/qemu-print.h"
  21. #include "qapi/error.h"
  22. #include "qapi/type-helpers.h"
  23. #include "hw/core/tcg-cpu-ops.h"
  24. #include "trace.h"
  25. #include "disas/disas.h"
  26. #include "exec/exec-all.h"
  27. #include "tcg/tcg.h"
  28. #include "tcg/tcg-apple-jit.h"
  29. #include "qemu/atomic.h"
  30. #include "qemu/rcu.h"
  31. #include "exec/log.h"
  32. #include "qemu/main-loop.h"
  33. #include "sysemu/cpus.h"
  34. #include "exec/cpu-all.h"
  35. #include "sysemu/cpu-timers.h"
  36. #include "exec/replay-core.h"
  37. #include "sysemu/tcg.h"
  38. #include "exec/helper-proto-common.h"
  39. #include "tb-jmp-cache.h"
  40. #include "tb-hash.h"
  41. #include "tb-context.h"
  42. #include "internal-common.h"
  43. #include "internal-target.h"
  44. /* -icount align implementation. */
  45. typedef struct SyncClocks {
  46. int64_t diff_clk;
  47. int64_t last_cpu_icount;
  48. int64_t realtime_clock;
  49. } SyncClocks;
  50. #if !defined(CONFIG_USER_ONLY)
  51. /* Allow the guest to have a max 3ms advance.
  52. * The difference between the 2 clocks could therefore
  53. * oscillate around 0.
  54. */
  55. #define VM_CLOCK_ADVANCE 3000000
  56. #define THRESHOLD_REDUCE 1.5
  57. #define MAX_DELAY_PRINT_RATE 2000000000LL
  58. #define MAX_NB_PRINTS 100
  59. int64_t max_delay;
  60. int64_t max_advance;
  61. static void align_clocks(SyncClocks *sc, CPUState *cpu)
  62. {
  63. int64_t cpu_icount;
  64. if (!icount_align_option) {
  65. return;
  66. }
  67. cpu_icount = cpu->icount_extra + cpu->neg.icount_decr.u16.low;
  68. sc->diff_clk += icount_to_ns(sc->last_cpu_icount - cpu_icount);
  69. 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;
  79. }
  80. #else
  81. Sleep(sc->diff_clk / SCALE_MS);
  82. sc->diff_clk = 0;
  83. #endif
  84. }
  85. }
  86. static void print_delay(const SyncClocks *sc)
  87. {
  88. static float threshold_delay;
  89. static int64_t last_realtime_clock;
  90. static int nb_prints;
  91. if (icount_align_option &&
  92. sc->realtime_clock - last_realtime_clock >= MAX_DELAY_PRINT_RATE &&
  93. nb_prints < MAX_NB_PRINTS) {
  94. if ((-sc->diff_clk / (float)1000000000LL > threshold_delay) ||
  95. (-sc->diff_clk / (float)1000000000LL <
  96. (threshold_delay - THRESHOLD_REDUCE))) {
  97. threshold_delay = (-sc->diff_clk / 1000000000LL) + 1;
  98. qemu_printf("Warning: The guest is now late by %.1f to %.1f seconds\n",
  99. threshold_delay - 1,
  100. threshold_delay);
  101. nb_prints++;
  102. last_realtime_clock = sc->realtime_clock;
  103. }
  104. }
  105. }
  106. static void init_delay_params(SyncClocks *sc, CPUState *cpu)
  107. {
  108. if (!icount_align_option) {
  109. return;
  110. }
  111. sc->realtime_clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT);
  112. sc->diff_clk = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) - sc->realtime_clock;
  113. sc->last_cpu_icount
  114. = cpu->icount_extra + cpu->neg.icount_decr.u16.low;
  115. if (sc->diff_clk < max_delay) {
  116. max_delay = sc->diff_clk;
  117. }
  118. if (sc->diff_clk > max_advance) {
  119. max_advance = sc->diff_clk;
  120. }
  121. /* Print every 2s max if the guest is late. We limit the number
  122. of printed messages to NB_PRINT_MAX(currently 100) */
  123. print_delay(sc);
  124. }
  125. #else
  126. static void align_clocks(SyncClocks *sc, const CPUState *cpu)
  127. {
  128. }
  129. static void init_delay_params(SyncClocks *sc, const CPUState *cpu)
  130. {
  131. }
  132. #endif /* CONFIG USER ONLY */
  133. bool tcg_cflags_has(CPUState *cpu, uint32_t flags)
  134. {
  135. return cpu->tcg_cflags & flags;
  136. }
  137. void tcg_cflags_set(CPUState *cpu, uint32_t flags)
  138. {
  139. cpu->tcg_cflags |= flags;
  140. }
  141. uint32_t curr_cflags(CPUState *cpu)
  142. {
  143. uint32_t cflags = cpu->tcg_cflags;
  144. /*
  145. * Record gdb single-step. We should be exiting the TB by raising
  146. * EXCP_DEBUG, but to simplify other tests, disable chaining too.
  147. *
  148. * For singlestep and -d nochain, suppress goto_tb so that
  149. * we can log -d cpu,exec after every TB.
  150. */
  151. if (unlikely(cpu->singlestep_enabled)) {
  152. cflags |= CF_NO_GOTO_TB | CF_NO_GOTO_PTR | CF_SINGLE_STEP | 1;
  153. } else if (qatomic_read(&one_insn_per_tb)) {
  154. cflags |= CF_NO_GOTO_TB | 1;
  155. } else if (qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) {
  156. cflags |= CF_NO_GOTO_TB;
  157. }
  158. return cflags;
  159. }
  160. struct tb_desc {
  161. vaddr pc;
  162. uint64_t cs_base;
  163. CPUArchState *env;
  164. tb_page_addr_t page_addr0;
  165. uint32_t flags;
  166. uint32_t cflags;
  167. };
  168. static bool tb_lookup_cmp(const void *p, const void *d)
  169. {
  170. const TranslationBlock *tb = p;
  171. const struct tb_desc *desc = d;
  172. if ((tb_cflags(tb) & CF_PCREL || tb->pc == desc->pc) &&
  173. tb_page_addr0(tb) == desc->page_addr0 &&
  174. tb->cs_base == desc->cs_base &&
  175. tb->flags == desc->flags &&
  176. tb_cflags(tb) == desc->cflags) {
  177. /* check next page if needed */
  178. tb_page_addr_t tb_phys_page1 = tb_page_addr1(tb);
  179. if (tb_phys_page1 == -1) {
  180. return true;
  181. } else {
  182. tb_page_addr_t phys_page1;
  183. vaddr virt_page1;
  184. /*
  185. * We know that the first page matched, and an otherwise valid TB
  186. * encountered an incomplete instruction at the end of that page,
  187. * therefore we know that generating a new TB from the current PC
  188. * must also require reading from the next page -- even if the
  189. * second pages do not match, and therefore the resulting insn
  190. * is different for the new TB. Therefore any exception raised
  191. * here by the faulting lookup is not premature.
  192. */
  193. virt_page1 = TARGET_PAGE_ALIGN(desc->pc);
  194. phys_page1 = get_page_addr_code(desc->env, virt_page1);
  195. if (tb_phys_page1 == phys_page1) {
  196. return true;
  197. }
  198. }
  199. }
  200. return false;
  201. }
  202. static TranslationBlock *tb_htable_lookup(CPUState *cpu, vaddr pc,
  203. uint64_t cs_base, uint32_t flags,
  204. uint32_t cflags)
  205. {
  206. tb_page_addr_t phys_pc;
  207. struct tb_desc desc;
  208. uint32_t h;
  209. desc.env = cpu_env(cpu);
  210. desc.cs_base = cs_base;
  211. desc.flags = flags;
  212. desc.cflags = cflags;
  213. desc.pc = pc;
  214. phys_pc = get_page_addr_code(desc.env, pc);
  215. if (phys_pc == -1) {
  216. return NULL;
  217. }
  218. desc.page_addr0 = phys_pc;
  219. h = tb_hash_func(phys_pc, (cflags & CF_PCREL ? 0 : pc),
  220. flags, cs_base, cflags);
  221. return qht_lookup_custom(&tb_ctx.htable, &desc, h, tb_lookup_cmp);
  222. }
  223. /* Might cause an exception, so have a longjmp destination ready */
  224. static inline TranslationBlock *tb_lookup(CPUState *cpu, vaddr pc,
  225. uint64_t cs_base, uint32_t flags,
  226. uint32_t cflags)
  227. {
  228. TranslationBlock *tb;
  229. CPUJumpCache *jc;
  230. uint32_t hash;
  231. /* we should never be trying to look up an INVALID tb */
  232. tcg_debug_assert(!(cflags & CF_INVALID));
  233. hash = tb_jmp_cache_hash_func(pc);
  234. jc = cpu->tb_jmp_cache;
  235. tb = qatomic_read(&jc->array[hash].tb);
  236. if (likely(tb &&
  237. jc->array[hash].pc == pc &&
  238. tb->cs_base == cs_base &&
  239. tb->flags == flags &&
  240. tb_cflags(tb) == cflags)) {
  241. goto hit;
  242. }
  243. tb = tb_htable_lookup(cpu, pc, cs_base, flags, cflags);
  244. if (tb == NULL) {
  245. return NULL;
  246. }
  247. jc->array[hash].pc = pc;
  248. qatomic_set(&jc->array[hash].tb, tb);
  249. hit:
  250. /*
  251. * As long as tb is not NULL, the contents are consistent. Therefore,
  252. * the virtual PC has to match for non-CF_PCREL translations.
  253. */
  254. assert((tb_cflags(tb) & CF_PCREL) || tb->pc == pc);
  255. return tb;
  256. }
  257. static void log_cpu_exec(vaddr pc, CPUState *cpu,
  258. const TranslationBlock *tb)
  259. {
  260. if (qemu_log_in_addr_range(pc)) {
  261. qemu_log_mask(CPU_LOG_EXEC,
  262. "Trace %d: %p [%08" PRIx64
  263. "/%016" VADDR_PRIx "/%08x/%08x] %s\n",
  264. cpu->cpu_index, tb->tc.ptr, tb->cs_base, pc,
  265. tb->flags, tb->cflags, lookup_symbol(pc));
  266. if (qemu_loglevel_mask(CPU_LOG_TB_CPU)) {
  267. FILE *logfile = qemu_log_trylock();
  268. if (logfile) {
  269. int flags = 0;
  270. if (qemu_loglevel_mask(CPU_LOG_TB_FPU)) {
  271. flags |= CPU_DUMP_FPU;
  272. }
  273. #if defined(TARGET_I386)
  274. flags |= CPU_DUMP_CCOP;
  275. #endif
  276. if (qemu_loglevel_mask(CPU_LOG_TB_VPU)) {
  277. flags |= CPU_DUMP_VPU;
  278. }
  279. cpu_dump_state(cpu, logfile, flags);
  280. qemu_log_unlock(logfile);
  281. }
  282. }
  283. }
  284. }
  285. static bool check_for_breakpoints_slow(CPUState *cpu, vaddr pc,
  286. uint32_t *cflags)
  287. {
  288. CPUBreakpoint *bp;
  289. bool match_page = false;
  290. /*
  291. * Singlestep overrides breakpoints.
  292. * This requirement is visible in the record-replay tests, where
  293. * we would fail to make forward progress in reverse-continue.
  294. *
  295. * TODO: gdb singlestep should only override gdb breakpoints,
  296. * so that one could (gdb) singlestep into the guest kernel's
  297. * architectural breakpoint handler.
  298. */
  299. if (cpu->singlestep_enabled) {
  300. return false;
  301. }
  302. QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
  303. /*
  304. * If we have an exact pc match, trigger the breakpoint.
  305. * Otherwise, note matches within the page.
  306. */
  307. if (pc == bp->pc) {
  308. bool match_bp = false;
  309. if (bp->flags & BP_GDB) {
  310. match_bp = true;
  311. } else if (bp->flags & BP_CPU) {
  312. #ifdef CONFIG_USER_ONLY
  313. g_assert_not_reached();
  314. #else
  315. const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
  316. assert(tcg_ops->debug_check_breakpoint);
  317. match_bp = tcg_ops->debug_check_breakpoint(cpu);
  318. #endif
  319. }
  320. if (match_bp) {
  321. cpu->exception_index = EXCP_DEBUG;
  322. return true;
  323. }
  324. } else if (((pc ^ bp->pc) & TARGET_PAGE_MASK) == 0) {
  325. match_page = true;
  326. }
  327. }
  328. /*
  329. * Within the same page as a breakpoint, single-step,
  330. * returning to helper_lookup_tb_ptr after each insn looking
  331. * for the actual breakpoint.
  332. *
  333. * TODO: Perhaps better to record all of the TBs associated
  334. * with a given virtual page that contains a breakpoint, and
  335. * then invalidate them when a new overlapping breakpoint is
  336. * set on the page. Non-overlapping TBs would not be
  337. * invalidated, nor would any TB need to be invalidated as
  338. * breakpoints are removed.
  339. */
  340. if (match_page) {
  341. *cflags = (*cflags & ~CF_COUNT_MASK) | CF_NO_GOTO_TB | CF_BP_PAGE | 1;
  342. }
  343. return false;
  344. }
  345. static inline bool check_for_breakpoints(CPUState *cpu, vaddr pc,
  346. uint32_t *cflags)
  347. {
  348. return unlikely(!QTAILQ_EMPTY(&cpu->breakpoints)) &&
  349. check_for_breakpoints_slow(cpu, pc, cflags);
  350. }
  351. /**
  352. * helper_lookup_tb_ptr: quick check for next tb
  353. * @env: current cpu state
  354. *
  355. * Look for an existing TB matching the current cpu state.
  356. * If found, return the code pointer. If not found, return
  357. * the tcg epilogue so that we return into cpu_tb_exec.
  358. */
  359. const void *HELPER(lookup_tb_ptr)(CPUArchState *env)
  360. {
  361. CPUState *cpu = env_cpu(env);
  362. TranslationBlock *tb;
  363. vaddr pc;
  364. uint64_t cs_base;
  365. uint32_t flags, cflags;
  366. /*
  367. * By definition we've just finished a TB, so I/O is OK.
  368. * Avoid the possibility of calling cpu_io_recompile() if
  369. * a page table walk triggered by tb_lookup() calling
  370. * probe_access_internal() happens to touch an MMIO device.
  371. * The next TB, if we chain to it, will clear the flag again.
  372. */
  373. cpu->neg.can_do_io = true;
  374. cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags);
  375. cflags = curr_cflags(cpu);
  376. if (check_for_breakpoints(cpu, pc, &cflags)) {
  377. cpu_loop_exit(cpu);
  378. }
  379. tb = tb_lookup(cpu, pc, cs_base, flags, cflags);
  380. if (tb == NULL) {
  381. return tcg_code_gen_epilogue;
  382. }
  383. if (qemu_loglevel_mask(CPU_LOG_TB_CPU | CPU_LOG_EXEC)) {
  384. log_cpu_exec(pc, cpu, tb);
  385. }
  386. return tb->tc.ptr;
  387. }
  388. /* Execute a TB, and fix up the CPU state afterwards if necessary */
  389. /*
  390. * Disable CFI checks.
  391. * TCG creates binary blobs at runtime, with the transformed code.
  392. * A TB is a blob of binary code, created at runtime and called with an
  393. * indirect function call. Since such function did not exist at compile time,
  394. * the CFI runtime has no way to verify its signature and would fail.
  395. * TCG is not considered a security-sensitive part of QEMU so this does not
  396. * affect the impact of CFI in environment with high security requirements
  397. */
  398. static inline TranslationBlock * QEMU_DISABLE_CFI
  399. cpu_tb_exec(CPUState *cpu, TranslationBlock *itb, int *tb_exit)
  400. {
  401. uintptr_t ret;
  402. TranslationBlock *last_tb;
  403. const void *tb_ptr = itb->tc.ptr;
  404. if (qemu_loglevel_mask(CPU_LOG_TB_CPU | CPU_LOG_EXEC)) {
  405. log_cpu_exec(log_pc(cpu, itb), cpu, itb);
  406. }
  407. qemu_thread_jit_execute();
  408. ret = tcg_qemu_tb_exec(cpu_env(cpu), tb_ptr);
  409. cpu->neg.can_do_io = true;
  410. qemu_plugin_disable_mem_helpers(cpu);
  411. /*
  412. * TODO: Delay swapping back to the read-write region of the TB
  413. * until we actually need to modify the TB. The read-only copy,
  414. * coming from the rx region, shares the same host TLB entry as
  415. * the code that executed the exit_tb opcode that arrived here.
  416. * If we insist on touching both the RX and the RW pages, we
  417. * double the host TLB pressure.
  418. */
  419. last_tb = tcg_splitwx_to_rw((void *)(ret & ~TB_EXIT_MASK));
  420. *tb_exit = ret & TB_EXIT_MASK;
  421. trace_exec_tb_exit(last_tb, *tb_exit);
  422. if (*tb_exit > TB_EXIT_IDX1) {
  423. /* We didn't start executing this TB (eg because the instruction
  424. * counter hit zero); we must restore the guest PC to the address
  425. * of the start of the TB.
  426. */
  427. CPUClass *cc = cpu->cc;
  428. const TCGCPUOps *tcg_ops = cc->tcg_ops;
  429. if (tcg_ops->synchronize_from_tb) {
  430. tcg_ops->synchronize_from_tb(cpu, last_tb);
  431. } else {
  432. tcg_debug_assert(!(tb_cflags(last_tb) & CF_PCREL));
  433. assert(cc->set_pc);
  434. cc->set_pc(cpu, last_tb->pc);
  435. }
  436. if (qemu_loglevel_mask(CPU_LOG_EXEC)) {
  437. vaddr pc = log_pc(cpu, last_tb);
  438. if (qemu_log_in_addr_range(pc)) {
  439. qemu_log("Stopped execution of TB chain before %p [%016"
  440. VADDR_PRIx "] %s\n",
  441. last_tb->tc.ptr, pc, lookup_symbol(pc));
  442. }
  443. }
  444. }
  445. /*
  446. * If gdb single-step, and we haven't raised another exception,
  447. * raise a debug exception. Single-step with another exception
  448. * is handled in cpu_handle_exception.
  449. */
  450. if (unlikely(cpu->singlestep_enabled) && cpu->exception_index == -1) {
  451. cpu->exception_index = EXCP_DEBUG;
  452. cpu_loop_exit(cpu);
  453. }
  454. return last_tb;
  455. }
  456. static void cpu_exec_enter(CPUState *cpu)
  457. {
  458. const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
  459. if (tcg_ops->cpu_exec_enter) {
  460. tcg_ops->cpu_exec_enter(cpu);
  461. }
  462. }
  463. static void cpu_exec_exit(CPUState *cpu)
  464. {
  465. const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
  466. if (tcg_ops->cpu_exec_exit) {
  467. tcg_ops->cpu_exec_exit(cpu);
  468. }
  469. }
  470. static void cpu_exec_longjmp_cleanup(CPUState *cpu)
  471. {
  472. /* Non-buggy compilers preserve this; assert the correct value. */
  473. g_assert(cpu == current_cpu);
  474. #ifdef CONFIG_USER_ONLY
  475. clear_helper_retaddr();
  476. if (have_mmap_lock()) {
  477. mmap_unlock();
  478. }
  479. #else
  480. /*
  481. * For softmmu, a tlb_fill fault during translation will land here,
  482. * and we need to release any page locks held. In system mode we
  483. * have one tcg_ctx per thread, so we know it was this cpu doing
  484. * the translation.
  485. *
  486. * Alternative 1: Install a cleanup to be called via an exception
  487. * handling safe longjmp. It seems plausible that all our hosts
  488. * support such a thing. We'd have to properly register unwind info
  489. * for the JIT for EH, rather that just for GDB.
  490. *
  491. * Alternative 2: Set and restore cpu->jmp_env in tb_gen_code to
  492. * capture the cpu_loop_exit longjmp, perform the cleanup, and
  493. * jump again to arrive here.
  494. */
  495. if (tcg_ctx->gen_tb) {
  496. tb_unlock_pages(tcg_ctx->gen_tb);
  497. tcg_ctx->gen_tb = NULL;
  498. }
  499. #endif
  500. if (bql_locked()) {
  501. bql_unlock();
  502. }
  503. assert_no_pages_locked();
  504. }
  505. void cpu_exec_step_atomic(CPUState *cpu)
  506. {
  507. CPUArchState *env = cpu_env(cpu);
  508. TranslationBlock *tb;
  509. vaddr pc;
  510. uint64_t cs_base;
  511. uint32_t flags, cflags;
  512. int tb_exit;
  513. if (sigsetjmp(cpu->jmp_env, 0) == 0) {
  514. start_exclusive();
  515. g_assert(cpu == current_cpu);
  516. g_assert(!cpu->running);
  517. cpu->running = true;
  518. cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags);
  519. cflags = curr_cflags(cpu);
  520. /* Execute in a serial context. */
  521. cflags &= ~CF_PARALLEL;
  522. /* After 1 insn, return and release the exclusive lock. */
  523. cflags |= CF_NO_GOTO_TB | CF_NO_GOTO_PTR | 1;
  524. /*
  525. * No need to check_for_breakpoints here.
  526. * We only arrive in cpu_exec_step_atomic after beginning execution
  527. * of an insn that includes an atomic operation we can't handle.
  528. * Any breakpoint for this insn will have been recognized earlier.
  529. */
  530. tb = tb_lookup(cpu, pc, cs_base, flags, cflags);
  531. if (tb == NULL) {
  532. mmap_lock();
  533. tb = tb_gen_code(cpu, pc, cs_base, flags, cflags);
  534. mmap_unlock();
  535. }
  536. cpu_exec_enter(cpu);
  537. /* execute the generated code */
  538. trace_exec_tb(tb, pc);
  539. cpu_tb_exec(cpu, tb, &tb_exit);
  540. cpu_exec_exit(cpu);
  541. } else {
  542. cpu_exec_longjmp_cleanup(cpu);
  543. }
  544. /*
  545. * As we start the exclusive region before codegen we must still
  546. * be in the region if we longjump out of either the codegen or
  547. * the execution.
  548. */
  549. g_assert(cpu_in_exclusive_context(cpu));
  550. cpu->running = false;
  551. end_exclusive();
  552. }
  553. void tb_set_jmp_target(TranslationBlock *tb, int n, uintptr_t addr)
  554. {
  555. /*
  556. * Get the rx view of the structure, from which we find the
  557. * executable code address, and tb_target_set_jmp_target can
  558. * produce a pc-relative displacement to jmp_target_addr[n].
  559. */
  560. const TranslationBlock *c_tb = tcg_splitwx_to_rx(tb);
  561. uintptr_t offset = tb->jmp_insn_offset[n];
  562. uintptr_t jmp_rx = (uintptr_t)tb->tc.ptr + offset;
  563. uintptr_t jmp_rw = jmp_rx - tcg_splitwx_diff;
  564. tb->jmp_target_addr[n] = addr;
  565. tb_target_set_jmp_target(c_tb, n, jmp_rx, jmp_rw);
  566. }
  567. static inline void tb_add_jump(TranslationBlock *tb, int n,
  568. TranslationBlock *tb_next)
  569. {
  570. uintptr_t old;
  571. qemu_thread_jit_write();
  572. assert(n < ARRAY_SIZE(tb->jmp_list_next));
  573. qemu_spin_lock(&tb_next->jmp_lock);
  574. /* make sure the destination TB is valid */
  575. if (tb_next->cflags & CF_INVALID) {
  576. goto out_unlock_next;
  577. }
  578. /* Atomically claim the jump destination slot only if it was NULL */
  579. old = qatomic_cmpxchg(&tb->jmp_dest[n], (uintptr_t)NULL,
  580. (uintptr_t)tb_next);
  581. if (old) {
  582. goto out_unlock_next;
  583. }
  584. /* patch the native jump address */
  585. tb_set_jmp_target(tb, n, (uintptr_t)tb_next->tc.ptr);
  586. /* add in TB jmp list */
  587. tb->jmp_list_next[n] = tb_next->jmp_list_head;
  588. tb_next->jmp_list_head = (uintptr_t)tb | n;
  589. qemu_spin_unlock(&tb_next->jmp_lock);
  590. qemu_log_mask(CPU_LOG_EXEC, "Linking TBs %p index %d -> %p\n",
  591. tb->tc.ptr, n, tb_next->tc.ptr);
  592. return;
  593. out_unlock_next:
  594. qemu_spin_unlock(&tb_next->jmp_lock);
  595. return;
  596. }
  597. static inline bool cpu_handle_halt(CPUState *cpu)
  598. {
  599. #ifndef CONFIG_USER_ONLY
  600. if (cpu->halted) {
  601. const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
  602. bool leave_halt = tcg_ops->cpu_exec_halt(cpu);
  603. if (!leave_halt) {
  604. return true;
  605. }
  606. cpu->halted = 0;
  607. }
  608. #endif /* !CONFIG_USER_ONLY */
  609. return false;
  610. }
  611. static inline void cpu_handle_debug_exception(CPUState *cpu)
  612. {
  613. const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
  614. CPUWatchpoint *wp;
  615. if (!cpu->watchpoint_hit) {
  616. QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
  617. wp->flags &= ~BP_WATCHPOINT_HIT;
  618. }
  619. }
  620. if (tcg_ops->debug_excp_handler) {
  621. tcg_ops->debug_excp_handler(cpu);
  622. }
  623. }
  624. static inline bool cpu_handle_exception(CPUState *cpu, int *ret)
  625. {
  626. if (cpu->exception_index < 0) {
  627. #ifndef CONFIG_USER_ONLY
  628. if (replay_has_exception()
  629. && cpu->neg.icount_decr.u16.low + cpu->icount_extra == 0) {
  630. /* Execute just one insn to trigger exception pending in the log */
  631. cpu->cflags_next_tb = (curr_cflags(cpu) & ~CF_USE_ICOUNT)
  632. | CF_NOIRQ | 1;
  633. }
  634. #endif
  635. return false;
  636. }
  637. if (cpu->exception_index >= EXCP_INTERRUPT) {
  638. /* exit request from the cpu execution loop */
  639. *ret = cpu->exception_index;
  640. if (*ret == EXCP_DEBUG) {
  641. cpu_handle_debug_exception(cpu);
  642. }
  643. cpu->exception_index = -1;
  644. return true;
  645. }
  646. #if defined(CONFIG_USER_ONLY)
  647. /*
  648. * If user mode only, we simulate a fake exception which will be
  649. * handled outside the cpu execution loop.
  650. */
  651. #if defined(TARGET_I386)
  652. const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
  653. tcg_ops->fake_user_interrupt(cpu);
  654. #endif /* TARGET_I386 */
  655. *ret = cpu->exception_index;
  656. cpu->exception_index = -1;
  657. return true;
  658. #else
  659. if (replay_exception()) {
  660. const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
  661. bql_lock();
  662. tcg_ops->do_interrupt(cpu);
  663. bql_unlock();
  664. cpu->exception_index = -1;
  665. if (unlikely(cpu->singlestep_enabled)) {
  666. /*
  667. * After processing the exception, ensure an EXCP_DEBUG is
  668. * raised when single-stepping so that GDB doesn't miss the
  669. * next instruction.
  670. */
  671. *ret = EXCP_DEBUG;
  672. cpu_handle_debug_exception(cpu);
  673. return true;
  674. }
  675. } else if (!replay_has_interrupt()) {
  676. /* give a chance to iothread in replay mode */
  677. *ret = EXCP_INTERRUPT;
  678. return true;
  679. }
  680. #endif
  681. return false;
  682. }
  683. static inline bool icount_exit_request(CPUState *cpu)
  684. {
  685. if (!icount_enabled()) {
  686. return false;
  687. }
  688. if (cpu->cflags_next_tb != -1 && !(cpu->cflags_next_tb & CF_USE_ICOUNT)) {
  689. return false;
  690. }
  691. return cpu->neg.icount_decr.u16.low + cpu->icount_extra == 0;
  692. }
  693. static inline bool cpu_handle_interrupt(CPUState *cpu,
  694. TranslationBlock **last_tb)
  695. {
  696. /*
  697. * If we have requested custom cflags with CF_NOIRQ we should
  698. * skip checking here. Any pending interrupts will get picked up
  699. * by the next TB we execute under normal cflags.
  700. */
  701. if (cpu->cflags_next_tb != -1 && cpu->cflags_next_tb & CF_NOIRQ) {
  702. return false;
  703. }
  704. /* Clear the interrupt flag now since we're processing
  705. * cpu->interrupt_request and cpu->exit_request.
  706. * Ensure zeroing happens before reading cpu->exit_request or
  707. * cpu->interrupt_request (see also smp_wmb in cpu_exit())
  708. */
  709. qatomic_set_mb(&cpu->neg.icount_decr.u16.high, 0);
  710. if (unlikely(qatomic_read(&cpu->interrupt_request))) {
  711. int interrupt_request;
  712. bql_lock();
  713. interrupt_request = cpu->interrupt_request;
  714. if (unlikely(cpu->singlestep_enabled & SSTEP_NOIRQ)) {
  715. /* Mask out external interrupts for this step. */
  716. interrupt_request &= ~CPU_INTERRUPT_SSTEP_MASK;
  717. }
  718. if (interrupt_request & CPU_INTERRUPT_DEBUG) {
  719. cpu->interrupt_request &= ~CPU_INTERRUPT_DEBUG;
  720. cpu->exception_index = EXCP_DEBUG;
  721. bql_unlock();
  722. return true;
  723. }
  724. #if !defined(CONFIG_USER_ONLY)
  725. if (replay_mode == REPLAY_MODE_PLAY && !replay_has_interrupt()) {
  726. /* Do nothing */
  727. } else if (interrupt_request & CPU_INTERRUPT_HALT) {
  728. replay_interrupt();
  729. cpu->interrupt_request &= ~CPU_INTERRUPT_HALT;
  730. cpu->halted = 1;
  731. cpu->exception_index = EXCP_HLT;
  732. bql_unlock();
  733. return true;
  734. }
  735. #if defined(TARGET_I386)
  736. else if (interrupt_request & CPU_INTERRUPT_INIT) {
  737. X86CPU *x86_cpu = X86_CPU(cpu);
  738. CPUArchState *env = &x86_cpu->env;
  739. replay_interrupt();
  740. cpu_svm_check_intercept_param(env, SVM_EXIT_INIT, 0, 0);
  741. do_cpu_init(x86_cpu);
  742. cpu->exception_index = EXCP_HALTED;
  743. bql_unlock();
  744. return true;
  745. }
  746. #else
  747. else if (interrupt_request & CPU_INTERRUPT_RESET) {
  748. replay_interrupt();
  749. cpu_reset(cpu);
  750. bql_unlock();
  751. return true;
  752. }
  753. #endif /* !TARGET_I386 */
  754. /* The target hook has 3 exit conditions:
  755. False when the interrupt isn't processed,
  756. True when it is, and we should restart on a new TB,
  757. and via longjmp via cpu_loop_exit. */
  758. else {
  759. const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
  760. if (tcg_ops->cpu_exec_interrupt(cpu, interrupt_request)) {
  761. if (!tcg_ops->need_replay_interrupt ||
  762. tcg_ops->need_replay_interrupt(interrupt_request)) {
  763. replay_interrupt();
  764. }
  765. /*
  766. * After processing the interrupt, ensure an EXCP_DEBUG is
  767. * raised when single-stepping so that GDB doesn't miss the
  768. * next instruction.
  769. */
  770. if (unlikely(cpu->singlestep_enabled)) {
  771. cpu->exception_index = EXCP_DEBUG;
  772. bql_unlock();
  773. return true;
  774. }
  775. cpu->exception_index = -1;
  776. *last_tb = NULL;
  777. }
  778. /* The target hook may have updated the 'cpu->interrupt_request';
  779. * reload the 'interrupt_request' value */
  780. interrupt_request = cpu->interrupt_request;
  781. }
  782. #endif /* !CONFIG_USER_ONLY */
  783. if (interrupt_request & CPU_INTERRUPT_EXITTB) {
  784. cpu->interrupt_request &= ~CPU_INTERRUPT_EXITTB;
  785. /* ensure that no TB jump will be modified as
  786. the program flow was changed */
  787. *last_tb = NULL;
  788. }
  789. /* If we exit via cpu_loop_exit/longjmp it is reset in cpu_exec */
  790. bql_unlock();
  791. }
  792. /* Finally, check if we need to exit to the main loop. */
  793. if (unlikely(qatomic_read(&cpu->exit_request)) || icount_exit_request(cpu)) {
  794. qatomic_set(&cpu->exit_request, 0);
  795. if (cpu->exception_index == -1) {
  796. cpu->exception_index = EXCP_INTERRUPT;
  797. }
  798. return true;
  799. }
  800. return false;
  801. }
  802. static inline void cpu_loop_exec_tb(CPUState *cpu, TranslationBlock *tb,
  803. vaddr pc, TranslationBlock **last_tb,
  804. int *tb_exit)
  805. {
  806. trace_exec_tb(tb, pc);
  807. tb = cpu_tb_exec(cpu, tb, tb_exit);
  808. if (*tb_exit != TB_EXIT_REQUESTED) {
  809. *last_tb = tb;
  810. return;
  811. }
  812. *last_tb = NULL;
  813. if (cpu_loop_exit_requested(cpu)) {
  814. /* Something asked us to stop executing chained TBs; just
  815. * continue round the main loop. Whatever requested the exit
  816. * will also have set something else (eg exit_request or
  817. * interrupt_request) which will be handled by
  818. * cpu_handle_interrupt. cpu_handle_interrupt will also
  819. * clear cpu->icount_decr.u16.high.
  820. */
  821. return;
  822. }
  823. /* Instruction counter expired. */
  824. assert(icount_enabled());
  825. #ifndef CONFIG_USER_ONLY
  826. /* Ensure global icount has gone forward */
  827. icount_update(cpu);
  828. /* Refill decrementer and continue execution. */
  829. int32_t insns_left = MIN(0xffff, cpu->icount_budget);
  830. cpu->neg.icount_decr.u16.low = insns_left;
  831. cpu->icount_extra = cpu->icount_budget - insns_left;
  832. /*
  833. * If the next tb has more instructions than we have left to
  834. * execute we need to ensure we find/generate a TB with exactly
  835. * insns_left instructions in it.
  836. */
  837. if (insns_left > 0 && insns_left < tb->icount) {
  838. assert(insns_left <= CF_COUNT_MASK);
  839. assert(cpu->icount_extra == 0);
  840. cpu->cflags_next_tb = (tb->cflags & ~CF_COUNT_MASK) | insns_left;
  841. }
  842. #endif
  843. }
  844. /* main execution loop */
  845. static int __attribute__((noinline))
  846. cpu_exec_loop(CPUState *cpu, SyncClocks *sc)
  847. {
  848. int ret;
  849. /* if an exception is pending, we execute it here */
  850. while (!cpu_handle_exception(cpu, &ret)) {
  851. TranslationBlock *last_tb = NULL;
  852. int tb_exit = 0;
  853. while (!cpu_handle_interrupt(cpu, &last_tb)) {
  854. TranslationBlock *tb;
  855. vaddr pc;
  856. uint64_t cs_base;
  857. uint32_t flags, cflags;
  858. cpu_get_tb_cpu_state(cpu_env(cpu), &pc, &cs_base, &flags);
  859. /*
  860. * When requested, use an exact setting for cflags for the next
  861. * execution. This is used for icount, precise smc, and stop-
  862. * after-access watchpoints. Since this request should never
  863. * have CF_INVALID set, -1 is a convenient invalid value that
  864. * does not require tcg headers for cpu_common_reset.
  865. */
  866. cflags = cpu->cflags_next_tb;
  867. if (cflags == -1) {
  868. cflags = curr_cflags(cpu);
  869. } else {
  870. cpu->cflags_next_tb = -1;
  871. }
  872. if (check_for_breakpoints(cpu, pc, &cflags)) {
  873. break;
  874. }
  875. tb = tb_lookup(cpu, pc, cs_base, flags, cflags);
  876. if (tb == NULL) {
  877. CPUJumpCache *jc;
  878. uint32_t h;
  879. mmap_lock();
  880. tb = tb_gen_code(cpu, pc, cs_base, flags, cflags);
  881. mmap_unlock();
  882. /*
  883. * We add the TB in the virtual pc hash table
  884. * for the fast lookup
  885. */
  886. h = tb_jmp_cache_hash_func(pc);
  887. jc = cpu->tb_jmp_cache;
  888. jc->array[h].pc = pc;
  889. qatomic_set(&jc->array[h].tb, tb);
  890. }
  891. #ifndef CONFIG_USER_ONLY
  892. /*
  893. * We don't take care of direct jumps when address mapping
  894. * changes in system emulation. So it's not safe to make a
  895. * direct jump to a TB spanning two pages because the mapping
  896. * for the second page can change.
  897. */
  898. if (tb_page_addr1(tb) != -1) {
  899. last_tb = NULL;
  900. }
  901. #endif
  902. /* See if we can patch the calling TB. */
  903. if (last_tb) {
  904. tb_add_jump(last_tb, tb_exit, tb);
  905. }
  906. cpu_loop_exec_tb(cpu, tb, pc, &last_tb, &tb_exit);
  907. /* Try to align the host and virtual clocks
  908. if the guest is in advance */
  909. align_clocks(sc, cpu);
  910. }
  911. }
  912. return ret;
  913. }
  914. static int cpu_exec_setjmp(CPUState *cpu, SyncClocks *sc)
  915. {
  916. /* Prepare setjmp context for exception handling. */
  917. if (unlikely(sigsetjmp(cpu->jmp_env, 0) != 0)) {
  918. cpu_exec_longjmp_cleanup(cpu);
  919. }
  920. return cpu_exec_loop(cpu, sc);
  921. }
  922. int cpu_exec(CPUState *cpu)
  923. {
  924. int ret;
  925. SyncClocks sc = { 0 };
  926. /* replay_interrupt may need current_cpu */
  927. current_cpu = cpu;
  928. if (cpu_handle_halt(cpu)) {
  929. return EXCP_HALTED;
  930. }
  931. RCU_READ_LOCK_GUARD();
  932. cpu_exec_enter(cpu);
  933. /*
  934. * Calculate difference between guest clock and host clock.
  935. * This delay includes the delay of the last cycle, so
  936. * what we have to do is sleep until it is 0. As for the
  937. * advance/delay we gain here, we try to fix it next time.
  938. */
  939. init_delay_params(&sc, cpu);
  940. ret = cpu_exec_setjmp(cpu, &sc);
  941. cpu_exec_exit(cpu);
  942. return ret;
  943. }
  944. bool tcg_exec_realizefn(CPUState *cpu, Error **errp)
  945. {
  946. static bool tcg_target_initialized;
  947. if (!tcg_target_initialized) {
  948. /* Check mandatory TCGCPUOps handlers */
  949. #ifndef CONFIG_USER_ONLY
  950. assert(cpu->cc->tcg_ops->cpu_exec_halt);
  951. assert(cpu->cc->tcg_ops->cpu_exec_interrupt);
  952. #endif /* !CONFIG_USER_ONLY */
  953. cpu->cc->tcg_ops->initialize();
  954. tcg_target_initialized = true;
  955. }
  956. cpu->tb_jmp_cache = g_new0(CPUJumpCache, 1);
  957. tlb_init(cpu);
  958. #ifndef CONFIG_USER_ONLY
  959. tcg_iommu_init_notifier_list(cpu);
  960. #endif /* !CONFIG_USER_ONLY */
  961. /* qemu_plugin_vcpu_init_hook delayed until cpu_index assigned. */
  962. return true;
  963. }
  964. /* undo the initializations in reverse order */
  965. void tcg_exec_unrealizefn(CPUState *cpu)
  966. {
  967. #ifndef CONFIG_USER_ONLY
  968. tcg_iommu_free_notifier_list(cpu);
  969. #endif /* !CONFIG_USER_ONLY */
  970. tlb_destroy(cpu);
  971. g_free_rcu(cpu->tb_jmp_cache, rcu);
  972. }