master
c 929 lines 26.6 KB
Raw
1 /*
2 * Memory region management for Tiny Code Generator for QEMU
3 *
4 * Copyright (c) 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 #include "qemu/osdep.h"
26 #include "qemu/units.h"
27 #include "qemu/madvise.h"
28 #include "qemu/mprotect.h"
29 #include "qemu/memalign.h"
30 #include "qemu/cacheinfo.h"
31 #include "qemu/qtree.h"
32 #include "qapi/error.h"
33 #include "tcg/tcg.h"
34 #include "exec/translation-block.h"
35 #include "tcg-internal.h"
36 #include "host/cpuinfo.h"
37
38
39 /*
40 * Local source-level compatibility with Unix.
41 * Used by tcg_region_init below.
42 */
43 #if defined(_WIN32)
44 #define PROT_READ 1
45 #define PROT_WRITE 2
46 #define PROT_EXEC 4
47 #endif
48
49 struct tcg_region_tree {
50 QemuMutex lock;
51 QTree *tree;
52 /* padding to avoid false sharing is computed at run-time */
53 };
54
55 /*
56 * We divide code_gen_buffer into equally-sized "regions" that TCG threads
57 * dynamically allocate from as demand dictates. Given appropriate region
58 * sizing, this minimizes flushes even when some TCG threads generate a lot
59 * more code than others.
60 */
61 struct tcg_region_state {
62 QemuMutex lock;
63
64 /* fields set at init time */
65 void *start_aligned;
66 void *after_prologue;
67 size_t n;
68 size_t size; /* size of one region */
69 size_t stride; /* .size + guard size */
70 size_t total_size; /* size of entire buffer, >= n * stride */
71
72 /* fields protected by the lock */
73 size_t current; /* current region index */
74 size_t agg_size_full; /* aggregate size of full regions */
75 };
76
77 static struct tcg_region_state region;
78
79 /*
80 * This is an array of struct tcg_region_tree's, with padding.
81 * We use void * to simplify the computation of region_trees[i]; each
82 * struct is found every tree_size bytes.
83 */
84 static void *region_trees;
85 static size_t tree_size;
86
87 bool in_code_gen_buffer(const void *p)
88 {
89 /*
90 * Much like it is valid to have a pointer to the byte past the
91 * end of an array (so long as you don't dereference it), allow
92 * a pointer to the byte past the end of the code gen buffer.
93 */
94 return (size_t)(p - region.start_aligned) <= region.total_size;
95 }
96
97 #ifndef CONFIG_TCG_INTERPRETER
98 static int host_prot_read_exec(void)
99 {
100 #if defined(CONFIG_LINUX) && defined(HOST_AARCH64) && defined(PROT_BTI)
101 if (cpuinfo & CPUINFO_BTI) {
102 return PROT_READ | PROT_EXEC | PROT_BTI;
103 }
104 #endif
105 return PROT_READ | PROT_EXEC;
106 }
107 #endif
108
109 #ifdef CONFIG_DEBUG_TCG
110 const void *tcg_splitwx_to_rx(void *rw)
111 {
112 /* Pass NULL pointers unchanged. */
113 if (rw) {
114 g_assert(in_code_gen_buffer(rw));
115 rw += tcg_splitwx_diff;
116 }
117 return rw;
118 }
119
120 void *tcg_splitwx_to_rw(const void *rx)
121 {
122 /* Pass NULL pointers unchanged. */
123 if (rx) {
124 rx -= tcg_splitwx_diff;
125 /* Assert that we end with a pointer in the rw region. */
126 g_assert(in_code_gen_buffer(rx));
127 }
128 return (void *)rx;
129 }
130 #endif /* CONFIG_DEBUG_TCG */
131
132 /* compare a pointer @ptr and a tb_tc @s */
133 static int ptr_cmp_tb_tc(const void *ptr, const struct tb_tc *s)
134 {
135 if (ptr >= s->ptr + s->size) {
136 return 1;
137 } else if (ptr < s->ptr) {
138 return -1;
139 }
140 return 0;
141 }
142
143 static gint tb_tc_cmp(gconstpointer ap, gconstpointer bp, gpointer userdata)
144 {
145 const struct tb_tc *a = ap;
146 const struct tb_tc *b = bp;
147
148 /*
149 * When both sizes are set, we know this isn't a lookup.
150 * This is the most likely case: every TB must be inserted; lookups
151 * are a lot less frequent.
152 */
153 if (likely(a->size && b->size)) {
154 if (a->ptr > b->ptr) {
155 return 1;
156 } else if (a->ptr < b->ptr) {
157 return -1;
158 }
159 /* a->ptr == b->ptr should happen only on deletions */
160 g_assert(a->size == b->size);
161 return 0;
162 }
163 /*
164 * All lookups have either .size field set to 0.
165 * From the glib sources we see that @ap is always the lookup key. However
166 * the docs provide no guarantee, so we just mark this case as likely.
167 */
168 if (likely(a->size == 0)) {
169 return ptr_cmp_tb_tc(a->ptr, b);
170 }
171 return ptr_cmp_tb_tc(b->ptr, a);
172 }
173
174 static void tb_destroy(gpointer value)
175 {
176 TranslationBlock *tb = value;
177 qemu_spin_destroy(&tb->jmp_lock);
178 }
179
180 static void tcg_region_trees_init(void)
181 {
182 size_t i;
183
184 tree_size = ROUND_UP(sizeof(struct tcg_region_tree), qemu_dcache_linesize);
185 region_trees = qemu_memalign(qemu_dcache_linesize, region.n * tree_size);
186 for (i = 0; i < region.n; i++) {
187 struct tcg_region_tree *rt = region_trees + i * tree_size;
188
189 qemu_mutex_init(&rt->lock);
190 rt->tree = q_tree_new_full(tb_tc_cmp, NULL, NULL, tb_destroy);
191 }
192 }
193
194 static struct tcg_region_tree *tc_ptr_to_region_tree(const void *p)
195 {
196 size_t region_idx;
197
198 /*
199 * Like tcg_splitwx_to_rw, with no assert. The pc may come from
200 * a signal handler over which the caller has no control.
201 */
202 if (!in_code_gen_buffer(p)) {
203 p -= tcg_splitwx_diff;
204 if (!in_code_gen_buffer(p)) {
205 return NULL;
206 }
207 }
208
209 if (p < region.start_aligned) {
210 region_idx = 0;
211 } else {
212 ptrdiff_t offset = p - region.start_aligned;
213
214 if (offset > region.stride * (region.n - 1)) {
215 region_idx = region.n - 1;
216 } else {
217 region_idx = offset / region.stride;
218 }
219 }
220 return region_trees + region_idx * tree_size;
221 }
222
223 void tcg_tb_insert(TranslationBlock *tb)
224 {
225 struct tcg_region_tree *rt = tc_ptr_to_region_tree(tb->tc.ptr);
226
227 g_assert(rt != NULL);
228 qemu_mutex_lock(&rt->lock);
229 q_tree_insert(rt->tree, &tb->tc, tb);
230 qemu_mutex_unlock(&rt->lock);
231 }
232
233 void tcg_tb_remove(TranslationBlock *tb)
234 {
235 struct tcg_region_tree *rt = tc_ptr_to_region_tree(tb->tc.ptr);
236
237 g_assert(rt != NULL);
238 qemu_mutex_lock(&rt->lock);
239 q_tree_remove(rt->tree, &tb->tc);
240 qemu_mutex_unlock(&rt->lock);
241 }
242
243 /*
244 * Find the TB 'tb' such that
245 * tb->tc.ptr <= tc_ptr < tb->tc.ptr + tb->tc.size
246 * Return NULL if not found.
247 */
248 TranslationBlock *tcg_tb_lookup(uintptr_t tc_ptr)
249 {
250 struct tcg_region_tree *rt = tc_ptr_to_region_tree((void *)tc_ptr);
251 TranslationBlock *tb;
252 struct tb_tc s = { .ptr = (void *)tc_ptr };
253
254 if (rt == NULL) {
255 return NULL;
256 }
257
258 qemu_mutex_lock(&rt->lock);
259 tb = q_tree_lookup(rt->tree, &s);
260 qemu_mutex_unlock(&rt->lock);
261 return tb;
262 }
263
264 static void tcg_region_tree_lock_all(void)
265 {
266 size_t i;
267
268 for (i = 0; i < region.n; i++) {
269 struct tcg_region_tree *rt = region_trees + i * tree_size;
270
271 qemu_mutex_lock(&rt->lock);
272 }
273 }
274
275 static void tcg_region_tree_unlock_all(void)
276 {
277 size_t i;
278
279 for (i = 0; i < region.n; i++) {
280 struct tcg_region_tree *rt = region_trees + i * tree_size;
281
282 qemu_mutex_unlock(&rt->lock);
283 }
284 }
285
286 void tcg_tb_foreach(GTraverseFunc func, gpointer user_data)
287 {
288 size_t i;
289
290 tcg_region_tree_lock_all();
291 for (i = 0; i < region.n; i++) {
292 struct tcg_region_tree *rt = region_trees + i * tree_size;
293
294 q_tree_foreach(rt->tree, func, user_data);
295 }
296 tcg_region_tree_unlock_all();
297 }
298
299 size_t tcg_nb_tbs(void)
300 {
301 size_t nb_tbs = 0;
302 size_t i;
303
304 tcg_region_tree_lock_all();
305 for (i = 0; i < region.n; i++) {
306 struct tcg_region_tree *rt = region_trees + i * tree_size;
307
308 nb_tbs += q_tree_nnodes(rt->tree);
309 }
310 tcg_region_tree_unlock_all();
311 return nb_tbs;
312 }
313
314 static void tcg_region_tree_reset_all(void)
315 {
316 size_t i;
317
318 tcg_region_tree_lock_all();
319 for (i = 0; i < region.n; i++) {
320 struct tcg_region_tree *rt = region_trees + i * tree_size;
321
322 /* Increment the refcount first so that destroy acts as a reset */
323 q_tree_ref(rt->tree);
324 q_tree_destroy(rt->tree);
325 }
326 tcg_region_tree_unlock_all();
327 }
328
329 static void tcg_region_bounds(size_t curr_region, void **pstart, void **pend)
330 {
331 void *start, *end;
332
333 start = region.start_aligned + curr_region * region.stride;
334 end = start + region.size;
335
336 if (curr_region == 0) {
337 start = region.after_prologue;
338 }
339 /* The final region may have a few extra pages due to earlier rounding. */
340 if (curr_region == region.n - 1) {
341 end = region.start_aligned + region.total_size;
342 }
343
344 *pstart = start;
345 *pend = end;
346 }
347
348 static void tcg_region_assign(TCGContext *s, size_t curr_region)
349 {
350 void *start, *end;
351
352 tcg_region_bounds(curr_region, &start, &end);
353
354 s->code_gen_buffer = start;
355 s->code_gen_ptr = start;
356 s->code_gen_buffer_size = end - start;
357 s->code_gen_highwater = end - TCG_HIGHWATER;
358 }
359
360 static bool tcg_region_alloc__locked(TCGContext *s)
361 {
362 if (region.current == region.n) {
363 return false;
364 }
365 tcg_region_assign(s, region.current);
366 region.current++;
367 return true;
368 }
369
370 /*
371 * Request a new region once the one in use has filled up.
372 * Returns true on success.
373 */
374 bool tcg_region_alloc(TCGContext *s)
375 {
376 bool ok;
377 /* read the region size now; alloc__locked will overwrite it on success */
378 size_t size_full = s->code_gen_buffer_size;
379
380 qemu_mutex_lock(&region.lock);
381 ok = tcg_region_alloc__locked(s);
382 if (ok) {
383 region.agg_size_full += size_full - TCG_HIGHWATER;
384 }
385 qemu_mutex_unlock(&region.lock);
386 return ok;
387 }
388
389 /*
390 * Perform a context's first region allocation.
391 * This function does _not_ increment region.agg_size_full.
392 */
393 static void tcg_region_initial_alloc__locked(TCGContext *s)
394 {
395 bool ok = tcg_region_alloc__locked(s);
396 g_assert(ok);
397 }
398
399 void tcg_region_thread_initial_alloc(TCGContext *s)
400 {
401 bool ok;
402
403 qemu_mutex_lock(&region.lock);
404 ok = tcg_region_alloc__locked(s);
405 qemu_mutex_unlock(&region.lock);
406
407 /*
408 * A vCPU hotplug may happen at any time. When the new thread is
409 * started, the region pool may be exhausted. At this point in
410 * the new thread call stack, we are not in a position to fix this.
411 * Leave code_gen_ptr NULL, so that this thread's first call to
412 * tcg_tb_alloc() returns NULL, so that the translator performs
413 * a tb_flush() and retry.
414 *
415 * During the tb_flush(), tcg_region_reset_all() will assign a
416 * new region to all contexts, including this one.
417 */
418 if (!ok) {
419 s->code_gen_buffer = NULL;
420 s->code_gen_ptr = NULL;
421 s->code_gen_buffer_size = 0;
422 s->code_gen_highwater = NULL;
423 }
424 }
425
426 /* Call from a safe-work context */
427 void tcg_region_reset_all(void)
428 {
429 unsigned int n_ctxs = qatomic_read(&tcg_cur_ctxs);
430 unsigned int i;
431
432 qemu_mutex_lock(&region.lock);
433 region.current = 0;
434 region.agg_size_full = 0;
435
436 for (i = 0; i < n_ctxs; i++) {
437 TCGContext *s = qatomic_read(&tcg_ctxs[i]);
438 tcg_region_initial_alloc__locked(s);
439 }
440 qemu_mutex_unlock(&region.lock);
441
442 tcg_region_tree_reset_all();
443 }
444
445 static size_t tcg_n_regions(size_t tb_size, unsigned max_threads)
446 {
447 #ifdef CONFIG_USER_ONLY
448 return 1;
449 #else
450 size_t n_regions;
451
452 /*
453 * It is likely that some vCPUs will translate more code than others,
454 * so we first try to set more regions than threads, with those regions
455 * being of reasonable size. If that's not possible we make do by evenly
456 * dividing the code_gen_buffer among the vCPUs.
457 *
458 * Use a single region if all we have is one vCPU thread.
459 */
460 if (max_threads == 1) {
461 return 1;
462 }
463
464 /*
465 * Try to have more regions than threads, with each region being >= 2 MB.
466 * If we can't, then just allocate one region per vCPU thread.
467 */
468 n_regions = tb_size / (2 * MiB);
469 if (n_regions <= max_threads) {
470 return max_threads;
471 }
472 return MIN(n_regions, max_threads * 8);
473 #endif
474 }
475
476 /*
477 * Minimum size of the code gen buffer. This number is randomly chosen,
478 * but not so small that we can't have a fair number of TB's live.
479 *
480 * Maximum size, MAX_CODE_GEN_BUFFER_SIZE, is defined in tcg-target.h.
481 * Unless otherwise indicated, this is constrained by the range of
482 * direct branches on the host cpu, as used by the TCG implementation
483 * of goto_tb.
484 */
485 #define MIN_CODE_GEN_BUFFER_SIZE (1 * MiB)
486
487 #ifdef CONFIG_USER_ONLY
488 /*
489 * As user-mode emulation typically means running multiple instances
490 * of the translator don't go too nuts with our default code gen
491 * buffer lest we make things too hard for the OS.
492 */
493 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (128 * MiB)
494 #else
495 /*
496 * We expect most system emulation to run one or two guests per host.
497 * Users running large scale system emulation may want to tweak their
498 * runtime setup via the tb-size control on the command line.
499 */
500 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (1 * GiB)
501 #endif
502
503 #define DEFAULT_CODE_GEN_BUFFER_SIZE \
504 (DEFAULT_CODE_GEN_BUFFER_SIZE_1 < MAX_CODE_GEN_BUFFER_SIZE \
505 ? DEFAULT_CODE_GEN_BUFFER_SIZE_1 : MAX_CODE_GEN_BUFFER_SIZE)
506
507 #ifdef USE_STATIC_CODE_GEN_BUFFER
508 static uint8_t static_code_gen_buffer[DEFAULT_CODE_GEN_BUFFER_SIZE]
509 __attribute__((aligned(CODE_GEN_ALIGN)));
510
511 static int alloc_code_gen_buffer(size_t tb_size, int splitwx, Error **errp)
512 {
513 void *buf, *end;
514 size_t size;
515
516 if (splitwx > 0) {
517 error_setg(errp, "jit split-wx not supported");
518 return -1;
519 }
520
521 /* page-align the beginning and end of the buffer */
522 buf = static_code_gen_buffer;
523 end = static_code_gen_buffer + sizeof(static_code_gen_buffer);
524 buf = QEMU_ALIGN_PTR_UP(buf, qemu_real_host_page_size());
525 end = QEMU_ALIGN_PTR_DOWN(end, qemu_real_host_page_size());
526
527 size = end - buf;
528
529 /* Honor a command-line option limiting the size of the buffer. */
530 if (size > tb_size) {
531 size = QEMU_ALIGN_DOWN(tb_size, qemu_real_host_page_size());
532 }
533
534 region.start_aligned = buf;
535 region.total_size = size;
536
537 return PROT_READ | PROT_WRITE;
538 }
539 #elif defined(_WIN32)
540 static int alloc_code_gen_buffer(size_t size, int splitwx, Error **errp)
541 {
542 void *buf;
543
544 if (splitwx > 0) {
545 error_setg(errp, "jit split-wx not supported");
546 return -1;
547 }
548
549 buf = VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT,
550 PAGE_EXECUTE_READWRITE);
551 if (buf == NULL) {
552 error_setg_win32(errp, GetLastError(),
553 "allocate %zu bytes for jit buffer", size);
554 return false;
555 }
556
557 region.start_aligned = buf;
558 region.total_size = size;
559
560 return PROT_READ | PROT_WRITE | PROT_EXEC;
561 }
562 #else
563 static int alloc_code_gen_buffer_anon(size_t size, int prot,
564 int flags, Error **errp)
565 {
566 void *buf;
567
568 buf = mmap(NULL, size, prot, flags, -1, 0);
569 if (buf == MAP_FAILED) {
570 error_setg_errno(errp, errno,
571 "allocate %zu bytes for jit buffer", size);
572 return -1;
573 }
574
575 region.start_aligned = buf;
576 region.total_size = size;
577 return prot;
578 }
579
580 #ifndef CONFIG_TCG_INTERPRETER
581 #ifdef CONFIG_POSIX
582 #include "qemu/memfd.h"
583
584 static int alloc_code_gen_buffer_splitwx_memfd(size_t size, Error **errp)
585 {
586 void *buf_rw = NULL, *buf_rx = MAP_FAILED;
587 int fd = -1;
588
589 buf_rw = qemu_memfd_alloc("tcg-jit", size, 0, &fd, errp);
590 if (buf_rw == NULL) {
591 goto fail;
592 }
593
594 buf_rx = mmap(NULL, size, host_prot_read_exec(), MAP_SHARED, fd, 0);
595 if (buf_rx == MAP_FAILED) {
596 error_setg_errno(errp, errno,
597 "failed to map shared memory for execute");
598 goto fail;
599 }
600
601 close(fd);
602 region.start_aligned = buf_rw;
603 region.total_size = size;
604 tcg_splitwx_diff = buf_rx - buf_rw;
605
606 return PROT_READ | PROT_WRITE;
607
608 fail:
609 /* buf_rx is always equal to MAP_FAILED here and does not require cleanup */
610 if (buf_rw) {
611 munmap(buf_rw, size);
612 }
613 if (fd >= 0) {
614 close(fd);
615 }
616 return -1;
617 }
618 #endif /* CONFIG_POSIX */
619
620 #ifdef CONFIG_DARWIN
621 #include <mach/mach.h>
622
623 extern kern_return_t mach_vm_remap(vm_map_t target_task,
624 mach_vm_address_t *target_address,
625 mach_vm_size_t size,
626 mach_vm_offset_t mask,
627 int flags,
628 vm_map_t src_task,
629 mach_vm_address_t src_address,
630 boolean_t copy,
631 vm_prot_t *cur_protection,
632 vm_prot_t *max_protection,
633 vm_inherit_t inheritance);
634
635 static int alloc_code_gen_buffer_splitwx_vmremap(size_t size, Error **errp)
636 {
637 kern_return_t ret;
638 mach_vm_address_t buf_rw, buf_rx;
639 vm_prot_t cur_prot, max_prot;
640
641 /* Map the read-write portion via normal anon memory. */
642 if (!alloc_code_gen_buffer_anon(size, PROT_READ | PROT_WRITE,
643 MAP_PRIVATE | MAP_ANONYMOUS, errp)) {
644 return -1;
645 }
646
647 buf_rw = (mach_vm_address_t)region.start_aligned;
648 buf_rx = 0;
649 ret = mach_vm_remap(mach_task_self(),
650 &buf_rx,
651 size,
652 0,
653 VM_FLAGS_ANYWHERE,
654 mach_task_self(),
655 buf_rw,
656 false,
657 &cur_prot,
658 &max_prot,
659 VM_INHERIT_NONE);
660 if (ret != KERN_SUCCESS) {
661 /* TODO: Convert "ret" to a human readable error message. */
662 error_setg(errp, "vm_remap for jit splitwx failed");
663 munmap((void *)buf_rw, size);
664 return -1;
665 }
666
667 if (mprotect((void *)buf_rx, size, host_prot_read_exec()) != 0) {
668 error_setg_errno(errp, errno, "mprotect for jit splitwx");
669 munmap((void *)buf_rx, size);
670 munmap((void *)buf_rw, size);
671 return -1;
672 }
673
674 tcg_splitwx_diff = buf_rx - buf_rw;
675 return PROT_READ | PROT_WRITE;
676 }
677 #endif /* CONFIG_DARWIN */
678 #endif /* CONFIG_TCG_INTERPRETER */
679
680 static int alloc_code_gen_buffer_splitwx(size_t size, Error **errp)
681 {
682 #ifndef CONFIG_TCG_INTERPRETER
683 # ifdef CONFIG_DARWIN
684 return alloc_code_gen_buffer_splitwx_vmremap(size, errp);
685 # endif
686 # ifdef CONFIG_POSIX
687 return alloc_code_gen_buffer_splitwx_memfd(size, errp);
688 # endif
689 #endif
690 error_setg(errp, "jit split-wx not supported");
691 return -1;
692 }
693
694 static int alloc_code_gen_buffer(size_t size, int splitwx, Error **errp)
695 {
696 ERRP_GUARD();
697 int prot, flags;
698
699 if (splitwx) {
700 prot = alloc_code_gen_buffer_splitwx(size, errp);
701 if (prot >= 0) {
702 return prot;
703 }
704 /*
705 * If splitwx force-on (1), fail;
706 * if splitwx default-on (-1), fall through to splitwx off.
707 */
708 if (splitwx > 0) {
709 return -1;
710 }
711 error_free_or_abort(errp);
712 }
713
714 /*
715 * macOS 11.2 has a bug (Apple Feedback FB8994773) in which mprotect
716 * rejects a permission change from RWX -> NONE when reserving the
717 * guard pages later. We can go the other way with the same number
718 * of syscalls, so always begin with PROT_NONE.
719 */
720 prot = PROT_NONE;
721 flags = MAP_PRIVATE | MAP_ANONYMOUS;
722 #ifdef CONFIG_DARWIN
723 /* Applicable to both iOS and macOS (Apple Silicon). */
724 if (!splitwx) {
725 flags |= MAP_JIT;
726 }
727 #endif
728
729 return alloc_code_gen_buffer_anon(size, prot, flags, errp);
730 }
731 #endif /* USE_STATIC_CODE_GEN_BUFFER, WIN32, POSIX */
732
733 /*
734 * Initializes region partitioning.
735 *
736 * Called at init time from the parent thread (i.e. the one calling
737 * tcg_context_init), after the target's TCG globals have been set.
738 *
739 * Region partitioning works by splitting code_gen_buffer into separate regions,
740 * and then assigning regions to TCG threads so that the threads can translate
741 * code in parallel without synchronization.
742 *
743 * In system-mode the number of TCG threads is bounded by max_threads,
744 *
745 * In user-mode we use a single region. Having multiple regions in user-mode
746 * is not supported, because the number of vCPU threads (recall that each thread
747 * spawned by the guest corresponds to a vCPU thread) is only bounded by the
748 * OS, and usually this number is huge (tens of thousands is not uncommon).
749 * Thus, given this large bound on the number of vCPU threads and the fact
750 * that code_gen_buffer is allocated at compile-time, we cannot guarantee
751 * that the availability of at least one region per vCPU thread.
752 *
753 * However, this user-mode limitation is unlikely to be a significant problem
754 * in practice. Multi-threaded guests share most if not all of their translated
755 * code, which makes parallel code generation less appealing than in system-mode
756 */
757 void tcg_region_init(size_t tb_size, int splitwx, unsigned max_threads)
758 {
759 const size_t page_size = qemu_real_host_page_size();
760 size_t region_size;
761 int have_prot, need_prot;
762
763 /* Size the buffer. */
764 if (tb_size == 0) {
765 size_t phys_mem = qemu_get_host_physmem();
766 if (phys_mem == 0) {
767 tb_size = DEFAULT_CODE_GEN_BUFFER_SIZE;
768 } else {
769 tb_size = QEMU_ALIGN_DOWN(phys_mem / 8, page_size);
770 tb_size = MIN(DEFAULT_CODE_GEN_BUFFER_SIZE, tb_size);
771 }
772 }
773 if (tb_size < MIN_CODE_GEN_BUFFER_SIZE) {
774 tb_size = MIN_CODE_GEN_BUFFER_SIZE;
775 }
776 if (tb_size > MAX_CODE_GEN_BUFFER_SIZE) {
777 tb_size = MAX_CODE_GEN_BUFFER_SIZE;
778 }
779
780 have_prot = alloc_code_gen_buffer(tb_size, splitwx, &error_fatal);
781 assert(have_prot >= 0);
782
783 /* Request large pages for the buffer and the splitwx. */
784 qemu_madvise(region.start_aligned, region.total_size, QEMU_MADV_HUGEPAGE);
785 if (tcg_splitwx_diff) {
786 qemu_madvise(region.start_aligned + tcg_splitwx_diff,
787 region.total_size, QEMU_MADV_HUGEPAGE);
788 }
789
790 /*
791 * Make region_size a multiple of page_size, using aligned as the start.
792 * As a result of this we might end up with a few extra pages at the end of
793 * the buffer; we will assign those to the last region.
794 */
795 region.n = tcg_n_regions(tb_size, max_threads);
796 region_size = tb_size / region.n;
797 region_size = QEMU_ALIGN_DOWN(region_size, page_size);
798
799 /* A region must have at least 2 pages; one code, one guard */
800 g_assert(region_size >= 2 * page_size);
801 region.stride = region_size;
802
803 /* Reserve space for guard pages. */
804 region.size = region_size - page_size;
805 region.total_size -= page_size;
806
807 /*
808 * The first region will be smaller than the others, via the prologue,
809 * which has yet to be allocated. For now, the first region begins at
810 * the page boundary.
811 */
812 region.after_prologue = region.start_aligned;
813
814 /* init the region struct */
815 qemu_mutex_init(&region.lock);
816
817 /*
818 * Set guard pages in the rw buffer, as that's the one into which
819 * buffer overruns could occur. Do not set guard pages in the rx
820 * buffer -- let that one use hugepages throughout.
821 * Work with the page protections set up with the initial mapping.
822 */
823 need_prot = PROT_READ | PROT_WRITE;
824 #ifndef CONFIG_TCG_INTERPRETER
825 if (tcg_splitwx_diff == 0) {
826 need_prot |= host_prot_read_exec();
827 }
828 #endif
829 for (size_t i = 0, n = region.n; i < n; i++) {
830 void *start, *end;
831
832 tcg_region_bounds(i, &start, &end);
833 if (have_prot != need_prot) {
834 int rc;
835
836 if (need_prot == (PROT_READ | PROT_WRITE | PROT_EXEC)) {
837 rc = qemu_mprotect_rwx(start, end - start);
838 } else if (need_prot == (PROT_READ | PROT_WRITE)) {
839 rc = qemu_mprotect_rw(start, end - start);
840 } else {
841 #ifdef CONFIG_POSIX
842 rc = mprotect(start, end - start, need_prot);
843 if (rc) {
844 error_report("mprotect of jit buffer: %s",
845 strerror(errno));
846 }
847 #else
848 g_assert_not_reached();
849 #endif
850 }
851 if (rc) {
852 exit(1);
853 }
854 }
855 if (have_prot != 0) {
856 /* Guard pages are nice for bug detection but are not essential. */
857 (void)qemu_mprotect_none(end, page_size);
858 }
859 }
860
861 tcg_region_trees_init();
862
863 /*
864 * Leave the initial context initialized to the first region.
865 * This will be the context into which we generate the prologue.
866 * It is also the only context for CONFIG_USER_ONLY.
867 */
868 tcg_region_initial_alloc__locked(&tcg_init_ctx);
869 }
870
871 void tcg_region_prologue_set(TCGContext *s)
872 {
873 /* Deduct the prologue from the first region. */
874 g_assert(region.start_aligned == s->code_gen_buffer);
875 region.after_prologue = s->code_ptr;
876
877 /* Recompute boundaries of the first region. */
878 tcg_region_assign(s, 0);
879
880 /* Register the balance of the buffer with gdb. */
881 tcg_register_jit(tcg_splitwx_to_rx(region.after_prologue),
882 region.start_aligned + region.total_size -
883 region.after_prologue);
884 }
885
886 /*
887 * Returns the size (in bytes) of all translated code (i.e. from all regions)
888 * currently in the cache.
889 * See also: tcg_code_capacity()
890 * Do not confuse with tcg_current_code_size(); that one applies to a single
891 * TCG context.
892 */
893 size_t tcg_code_size(void)
894 {
895 unsigned int n_ctxs = qatomic_read(&tcg_cur_ctxs);
896 unsigned int i;
897 size_t total;
898
899 qemu_mutex_lock(&region.lock);
900 total = region.agg_size_full;
901 for (i = 0; i < n_ctxs; i++) {
902 const TCGContext *s = qatomic_read(&tcg_ctxs[i]);
903 size_t size;
904
905 size = qatomic_read(&s->code_gen_ptr) - s->code_gen_buffer;
906 g_assert(size <= s->code_gen_buffer_size);
907 total += size;
908 }
909 qemu_mutex_unlock(&region.lock);
910 return total;
911 }
912
913 /*
914 * Returns the code capacity (in bytes) of the entire cache, i.e. including all
915 * regions.
916 * See also: tcg_code_size()
917 */
918 size_t tcg_code_capacity(void)
919 {
920 size_t guard_size, capacity;
921
922 /* no need for synchronization; these variables are set at init time */
923 guard_size = region.stride - region.size;
924 capacity = region.total_size;
925 capacity -= (region.n - 1) * guard_size;
926 capacity -= region.n * TCG_HIGHWATER;
927
928 return capacity;
929 }