tcg: tb_lock removal
PATCH 1/22 disas/arm: fix 'instuction' typo in comment
In reply to Emilio G. Cota--- disas/arm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
disas/arm.c +1 -1
@@ -1651,7 +1651,7 @@ print_insn_coprocessor (bfd_vma pc, struct disassemble_info *info, long given, }else { -/* Only match unconditional instuctions against unconditional +/* Only match unconditional instructions against unconditional patterns. */ if ((given &0xf0000000 ) ==0xf0000000 ) {
Signature · 1 line
2.7.4
PATCH 2/22 linux-user: fix 'finshed' typo in comment
In reply to Emilio G. Cota--- linux-user/syscall.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
linux-user/syscall.c +1 -1
@@ -6231,7 +6231,7 @@ static void *clone_func(void *arg)pthread_mutex_lock (&info->mutex);pthread_cond_broadcast (&info->cond);pthread_mutex_unlock (&info->mutex); -/* Wait until the parent has finshed initializing the tls state. */ +/* Wait until the parent has finished initializing the tls state. */ pthread_mutex_lock (&clone_lock);pthread_mutex_unlock (&clone_lock);cpu_loop (env);
Signature · 1 line
2.7.4
cover tcg: tb_lock removal
This series applies on top of the "multiple TCG contexts" series, v4:
https://lists.gnu.org/archive/html/qemu-devel/2017-07/msg06769.html
Highlights:
- First, fix a few typos I encountered while working on this (patches 1-3). I could send them separately to qemu-trivial if you prefer.
- QHT: use a proper cmp function, instead of just checking pointer values to determine equality of matches.
- Use a binary search tree for each TCG region.
- Make l1_map lockless by using cmpxchg
- Introduce page locks (for !user-mode), so that tb_lock is not needed when operating on a page
- Introduce page_collection, to lock a range of pages
- Introduce tb->jmp_lock to protect TB jump lists.
- Remove tb_lock. User-mode uses just mmap_lock and tb->jmp_lock's; !user-mode uses the same jump locks as well as page locks.
Performance numbers are in patch 22. We get nice speedups, but I still see a lot of idling when booting many cores. I suspect it comes from cross-CPU events (e.g. TLB invalidations), but I need to profile it better (perf is not good for this; mutrace doesn't quite work). But anyway that's for another patchset.
You can fetch these changes from:
https://github.com/cota/qemu/tree/multi-tcg-v4-parallel
Please review!
Thanks,
Emilio
diffstat:
accel/tcg/cpu-exec.c | 58 +- accel/tcg/cputlb.c | 8 - accel/tcg/translate-all.c | 958 +++++++++++++++-------- accel/tcg/translate-all.h | 6 +- disas/arm.c | 2 +- docs/devel/multi-thread-tcg.txt | 21 +- exec.c | 25 +- include/exec/cpu-common.h | 1 - include/exec/exec-all.h | 86 +- include/exec/tb-context.h | 4 - include/qemu/qht.h | 36 +- linux-user/main.c | 3 - linux-user/syscall.c | 2 +- tcg/tcg.c | 205 +++++ tcg/tcg.h | 13 +- tests/qht-bench.c | 18 +- tests/test-qht.c | 20 +- util/qht.c | 30 +- 18 files changed, 1022 insertions(+), 474 deletions(-)
PATCH 3/22 translate-all: fix 'consisits' typo in comment
--- accel/tcg/translate-all.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
accel/tcg/translate-all.c +1 -1
@@ -257,7 +257,7 @@ static target_long decode_sleb128(uint8_t **pp)/* Encode the data collected about the instructions while compiling TB. Place the data at BLOCK, and return the number of bytes consumed. -The logical table consisits of TARGET_INSN_START_WORDS target_ulong's, +The logical table consists of TARGET_INSN_START_WORDS target_ulong's, which come from the target's insn_start data, followed by a uintptr_t which comes from the host pc of the end of the code implementing the insn.
Signature · 1 line
2.7.4
PATCH 4/22 qht: fix kernel-doc markup in qht.h
In reply to Emilio G. CotaWhile at it, s/stuct/struct/.
--- include/qemu/qht.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
include/qemu/qht.h +3 -3
@@ -166,7 +166,7 @@ void qht_iter(struct qht *ht, qht_iter_func_t func, void *userp);/** * qht_statistics_init - Gather statistics from a QHT * @ht: QHT to gather statistics from -* @stats: pointer to a struct qht_stats to be filled in +* @stats: pointer to a &struct qht_stats to be filled in * * Does NOT need to be called under an RCU read-critical section, * since it does not dereference any pointers stored in the hash table.
@@ -177,8 +177,8 @@ void qht_iter(struct qht *ht, qht_iter_func_t func, void *userp);void qht_statistics_init (struct qht *ht,struct qht_stats *stats);/** -* qht_statistics_destroy - Destroy a struct qht_stats -* @stats: stuct qht_stats to be destroyed +* qht_statistics_destroy - Destroy a &struct qht_stats +* @stats: &struct qht_stats to be destroyed * * See also: qht_statistics_init(). */
Signature · 1 line
2.7.4
PATCH 6/22 qht: return existing entry when qht_insert fails
In reply to Emilio G. CotaThe meaning of "existing" is now changed to "matches in hash and ht->cmp result". This is saner than just checking the pointer value.
Note that we now return NULL on insertion success, or the existing pointer on failure. We can do this because NULL pointers are not allowed to be inserted in QHT.
--- include/qemu/qht.h | 7 ++++--- tests/qht-bench.c | 4 ++-- tests/test-qht.c | 5 ++++- util/qht.c | 17 +++++++++-------- 4 files changed, 19 insertions(+), 14 deletions(-)
include/qemu/qht.h +4 -3
@@ -77,10 +77,11 @@ void qht_destroy(struct qht *ht);* In case of successful operation, smp_wmb() is implied before the pointer is * inserted into the hash table. * -* Returns true on success. -* Returns false if the @p-@hash pair already exists in the hash table. +* On success, returns NULL. +* On failure, returns the pointer from an entry that is equivalent (i.e. +* ht->cmp matches and the hash is the same) to @p-@h. */ -bool qht_insert (struct qht *ht,void *p,uint32_t hash); +void *qht_insert (struct qht *ht,void *p,uint32_t hash);/** * qht_lookup_custom - Look up a pointer using a custom comparison function.
tests/qht-bench.c +2 -2
@@ -163,7 +163,7 @@ static void do_rw(struct thread_info *info)bool written = false;if (qht_lookup (&ht, p, hash) ==NULL ) { - written =qht_insert (&ht, p, hash); + written = !qht_insert (&ht, p, hash); }if (written) { stats->in++;
@@ -322,7 +322,7 @@ static void htable_init(void) r =xorshift64star (r); p = &keys[r & (init_range -1 )]; hash =h (*p); -if (qht_insert (&ht, p, hash)) { +if (!qht_insert (&ht, p, hash)) {break ; } retries++;
tests/test-qht.c +4 -1
@@ -27,11 +27,14 @@ static void insert(int a, int b)for (i = a; i < b; i++) {uint32_t hash; +void *existing; arr[i] = i; hash = i; -qht_insert (&ht, &arr[i], hash); +g_assert_true (!qht_insert (&ht, &arr[i], hash)); + existing =qht_insert (&ht, &arr[i], hash); +g_assert_true (existing == &arr[i]); } }
util/qht.c +9 -8
@@ -510,9 +510,9 @@ void *qht_lookup(struct qht *ht, const void *userp, uint32_t hash) }/* call with head->lock held */ -static bool qht_insert__locked (struct qht *ht,struct qht_map *map, -struct qht_bucket *head,void *p,uint32_t hash, -bool *needs_resize) +static void *qht_insert__locked (struct qht *ht,struct qht_map *map, +struct qht_bucket *head,void *p,uint32_t hash, +bool *needs_resize) {struct qht_bucket *b = head;struct qht_bucket *prev =NULL ;
@@ -522,8 +522,9 @@ static bool qht_insert__locked(struct qht *ht, struct qht_map *map, do { for (i = 0; i < QHT_BUCKET_ENTRIES; i++) { if (b->pointers[i]) { - if (unlikely(b->pointers[i] == p)) { - return false; + if (unlikely(b->hashes[i] == hash && + ht->cmp(b->pointers[i], p))) { + return b->pointers[i]; } } else { goto found;
@@ -552,7 +553,7 @@ static bool qht_insert__locked(struct qht *ht, struct qht_map *map,atomic_set (&b->hashes[i], hash);atomic_set (&b->pointers[i], p);seqlock_write_end (&head->sequence); -return true; +return NULL ; }static __attribute__((noinline))void qht_grow_maybe (struct qht *ht)
@@ -576,12 +577,12 @@ static __attribute__((noinline)) void qht_grow_maybe(struct qht *ht)qemu_mutex_unlock (&ht->lock); } -bool qht_insert (struct qht *ht,void *p,uint32_t hash) +void *qht_insert (struct qht *ht,void *p,uint32_t hash) {struct qht_bucket *b;struct qht_map *map;bool needs_resize = false; -bool ret; +void *ret;/* NULL pointers are not supported */ qht_debug_assert (p);
Signature · 1 line
2.7.4
PATCH 8/22 tcg: move tb_ctx.tb_phys_invalidate_count to tcg_ctx
In reply to Emilio G. CotaThereby making it per-TCGContext. Once we remove tb_lock, this will avoid an atomic increment every time a TB is invalidated.
--- include/exec/tb-context.h | 1 - tcg/tcg.h | 3 +++ accel/tcg/translate-all.c | 5 +++-- tcg/tcg.c | 14 ++++++++++++++ 4 files changed, 20 insertions(+), 3 deletions(-)
include/exec/tb-context.h +0 -1
@@ -37,7 +37,6 @@ struct TBContext {/* statistics */ unsigned tb_flush_count; -int tb_phys_invalidate_count; };extern TBContext tb_ctx;
tcg/tcg.h +3 -0
@@ -709,6 +709,8 @@ struct TCGContext {/* Threshold to flush the translated code buffer. */ void *code_gen_highwater; +size_t tb_phys_invalidate_count; +/* Track which vCPU triggers events */ CPUState *cpu;/* *_trans */ TCGv_env tcg_env;/* *_exec */
@@ -768,6 +770,7 @@ size_t tcg_code_capacity(void);void tcg_tb_insert (TranslationBlock *tb);void tcg_tb_remove (TranslationBlock *tb); +size_t tcg_tb_phys_invalidate_count (void );TranslationBlock *tcg_tb_lookup (uintptr_t tc_ptr);void tcg_tb_foreach (GTraverseFunc func,gpointer user_data);size_t tcg_nb_tbs (void );
accel/tcg/translate-all.c +3 -2
@@ -1067,7 +1067,8 @@ void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr)/* suppress any remaining jumps to this TB */ tb_jmp_unlink (tb); - tb_ctx.tb_phys_invalidate_count++; +atomic_set (&tcg_ctx->tb_phys_invalidate_count, + tcg_ctx->tb_phys_invalidate_count +1 ); }#ifdef CONFIG_SOFTMMU
@@ -1858,7 +1859,7 @@ void dump_exec_info(FILE *f, fprintf_function cpu_fprintf)cpu_fprintf (f,"\nStatistics:\n" );cpu_fprintf (f,"TB flush count %u\n" ,atomic_read (&tb_ctx.tb_flush_count)); -cpu_fprintf (f,"TB invalidate count %d\n" , tb_ctx.tb_phys_invalidate_count); +cpu_fprintf (f,"TB invalidate count %zu\n" ,tcg_tb_phys_invalidate_count ());cpu_fprintf (f,"TLB flush count %zu\n" ,tlb_flush_count ());tcg_dump_info (f, cpu_fprintf);
tcg/tcg.c +14 -0
@@ -769,6 +769,20 @@ size_t tcg_code_capacity(void)return capacity; } +size_t tcg_tb_phys_invalidate_count (void ) +{ +unsigned int n_ctxs =atomic_read (&n_tcg_ctxs); +unsigned int i; +size_t total =0 ; + +for (i =0 ; i < n_ctxs; i++) { +const TCGContext *s =atomic_read (&tcg_ctxs[i]); + + total +=atomic_read (&s->tb_phys_invalidate_count); + } +return total; +} +/* pool based memory allocation */ void *tcg_malloc_internal (TCGContext *s,int size) {
Signature · 1 line
2.7.4
PATCH 9/22 translate-all: introduce iterator macros for tagged TB lists
In reply to Emilio G. CotaThese will soon gain a couple of users.
--- accel/tcg/translate-all.c | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+)
accel/tcg/translate-all.c +19 -0
@@ -115,6 +115,25 @@ typedef struct PageDesc {#endif } PageDesc; +/* list iterators for lists of tagged pointers in TranslationBlock */ +#define tb_for_each_tagged (head, tb, n, field) \ + for (n = (head) & 1, \ + tb = (TranslationBlock *)((head) & ~1); \ + tb; \ + tb = (TranslationBlock *)tb->field[n], \ + n = (uintptr_t)tb & 1, \ + tb = (TranslationBlock *)((uintptr_t)tb & ~1)) + +/* prev is a *uintptr_t. It allows us to safely remove tb */ +#define tb_for_each_tagged_safe (head, tb, n, field, prev) \ + for (prev = &(head), \ + n = *prev & 1, \ + tb = (TranslationBlock *)(*prev & ~1); \ + tb; \ + prev = &tb->field[n], \ + n = (uintptr_t)*prev & 1, \ + tb = (TranslationBlock *)(*prev & ~1)) +/* In system mode we want L1_MAP to be based on ram offsets, while in user mode we want it to be based on virtual addresses. */ #if !defined(CONFIG_USER_ONLY )
Signature · 1 line
2.7.4
PATCH 11/22 translate-all: exit from tb_phys_invalidate if qht_remove fails
In reply to Emilio G. CotaGroundwork for supporting parallel TCG generation.
Once tb_lock goes away, it is conceivable that two (or more) threads might race while invalidating the same TB. We currently do not check for this, which means we would wrongly invalidate the same TB more than once.
Fix this by using qht_remove as the synchronization point; if it fails, that means the TB has already been invalidated, and therefore there is nothing left to do in tb_phys_invalidate.
--- accel/tcg/translate-all.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
accel/tcg/translate-all.c +3 -1
@@ -1061,7 +1061,9 @@ void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr) phys_pc = tb->page_addr[0 ] + (tb->pc & ~TARGET_PAGE_MASK ); h =tb_hash_func (phys_pc, tb->pc, tb->flags, tb->cflags &CF_HASH_MASK , tb->trace_vcpu_dstate); -qht_remove (&tb_ctx.htable, tb, h); +if (!qht_remove (&tb_ctx.htable, tb, h)) { +return ; + }/* remove the TB from the page list */ if (tb->page_addr[0 ] != page_addr) {
Signature · 1 line
2.7.4
PATCH 5/22 qht: require a default comparison function
In reply to Emilio G. Cotaqht_lookup now uses the default cmp function. qht_lookup_custom is defined to retain the old behaviour, that is a cmp function is explicitly provided.
qht_insert will gain use of the default cmp in the next patch.
--- include/qemu/qht.h | 23 +++++++++++++++++++---- accel/tcg/cpu-exec.c | 4 ++-- accel/tcg/translate-all.c | 16 +++++++++++++++- tests/qht-bench.c | 14 +++++++------- tests/test-qht.c | 15 ++++++++++----- util/qht.c | 13 ++++++++++--- 6 files changed, 63 insertions(+), 22 deletions(-)
include/qemu/qht.h +19 -4
@@ -11,8 +11,11 @@#include "qemu/thread.h" #include "qemu/qdist.h" +typedef bool (*qht_cmp_func_t )(const void *a,const void *b); +struct qht {struct qht_map *map; +qht_cmp_func_t cmp;QemuMutex lock;/* serializes setters of ht->map */ unsigned int mode; };
@@ -47,10 +50,12 @@ typedef void (*qht_iter_func_t)(struct qht *ht, void *p, uint32_t h, void *up);/** * qht_init - Initialize a QHT * @ht: QHT to be initialized +* @cmp: default comparison function. Cannot be NULL. * @n_elems: number of entries the hash table should be optimized for. * @mode: bitmask with OR'ed QHT_MODE_* */ -void qht_init (struct qht *ht,size_t n_elems,unsigned int mode); +void qht_init (struct qht *ht,qht_cmp_func_t cmp,size_t n_elems, +unsigned int mode);/** * qht_destroy - destroy a previously initialized QHT
@@ -78,7 +83,7 @@ void qht_destroy(struct qht *ht);bool qht_insert (struct qht *ht,void *p,uint32_t hash);/** -* qht_lookup - Look up a pointer in a QHT +* qht_lookup_custom - Look up a pointer using a custom comparison function. * @ht: QHT to be looked up * @func: function to compare existing pointers against @userp * @userp: pointer to pass to @func
@@ -94,8 +99,18 @@ bool qht_insert(struct qht *ht, void *p, uint32_t hash);* Returns the corresponding pointer when a match is found. * Returns NULL otherwise. */ -void *qht_lookup (struct qht *ht,qht_lookup_func_t func,const void *userp, -uint32_t hash); +void *qht_lookup_custom (struct qht *ht,qht_lookup_func_t func, +const void *userp,uint32_t hash); + +/** +* qht_lookup - Look up a pointer in a QHT +* @ht: QHT to be looked up +* @userp: pointer to pass to @func +* @hash: hash of the pointer to be looked up +* +* Calls qht_lookup_custom() using @ht's default comparison function. +*/ +void *qht_lookup (struct qht *ht,const void *userp,uint32_t hash);/** * qht_remove - remove a pointer from the hash table
accel/tcg/cpu-exec.c +2 -2
@@ -280,7 +280,7 @@ struct tb_desc {uint32_t trace_vcpu_dstate; }; -static bool tb_cmp (const void *p,const void *d) +static bool tb_lookup_cmp (const void *p,const void *d) {const TranslationBlock *tb = p;const struct tb_desc *desc = d;
@@ -325,7 +325,7 @@ TranslationBlock *tb_htable_lookup(CPUState *cpu, target_ulong pc, phys_pc =get_page_addr_code (desc.env, pc); desc.phys_page1 = phys_pc &TARGET_PAGE_MASK ; h =tb_hash_func (phys_pc, pc, flags, cf_mask, *cpu->trace_dstate); -return qht_lookup (&tb_ctx.htable, tb_cmp, &desc, h); +return qht_lookup_custom (&tb_ctx.htable, tb_lookup_cmp, &desc, h); } static inline TranslationBlock *tb_find(CPUState *cpu,
accel/tcg/translate-all.c +15 -1
@@ -782,11 +782,25 @@ static inline void code_gen_alloc(size_t tb_size)qemu_mutex_init (&tb_ctx.tb_lock); } +static bool tb_cmp (const void *ap,const void *bp) +{ +const TranslationBlock *a = ap; +const TranslationBlock *b = bp; + +return a->pc == b->pc && + a->cs_base == b->cs_base && + a->flags == b->flags && + (tb_cflags (a) &CF_HASH_MASK ) == (tb_cflags (b) &CF_HASH_MASK ) && + a->trace_vcpu_dstate == b->trace_vcpu_dstate && + a->page_addr[0 ] == b->page_addr[0 ] && + a->page_addr[1 ] == b->page_addr[1 ]; +} +static void tb_htable_init (void ) {unsigned int mode =QHT_MODE_AUTO_RESIZE ; -qht_init (&tb_ctx.htable,CODE_GEN_HTABLE_SIZE , mode); +qht_init (&tb_ctx.htable, tb_cmp,CODE_GEN_HTABLE_SIZE , mode); }/* Must be called before using the QEMU cpus. 'tb_size' is the size
tests/qht-bench.c +7 -7
@@ -93,10 +93,10 @@ static void usage_complete(int argc, char *argv[])exit (-1 ); } -static bool is_equal (const void *obj,const void *userp) +static bool is_equal (const void *ap,const void *bp) { -const long *a = obj; -const long *b = userp; +const long *a = ap; +const long *b = bp;return *a == *b; }
@@ -150,7 +150,7 @@ static void do_rw(struct thread_info *info) p = &keys[info->r & (lookup_range -1 )]; hash =h (*p); - read =qht_lookup (&ht, is_equal, p, hash); + read =qht_lookup (&ht, p, hash);if (read) { stats->rd++; }else {
@@ -162,7 +162,7 @@ static void do_rw(struct thread_info *info)if (info->write_op) {bool written = false; -if (qht_lookup (&ht, is_equal, p, hash) ==NULL ) { +if (qht_lookup (&ht, p, hash) ==NULL ) { written =qht_insert (&ht, p, hash); }if (written) {
@@ -173,7 +173,7 @@ static void do_rw(struct thread_info *info) }else {bool removed = false; -if (qht_lookup (&ht, is_equal, p, hash)) { +if (qht_lookup (&ht, p, hash)) { removed =qht_remove (&ht, p, hash); }if (removed) {
@@ -308,7 +308,7 @@ static void htable_init(void) }/* initialize the hash table */ -qht_init (&ht, qht_n_elems, qht_mode); +qht_init (&ht, is_equal, qht_n_elems, qht_mode);assert (init_size <= init_range);pr_params ();
tests/test-qht.c +10 -5
@@ -13,10 +13,10 @@static struct qht ht;static int32_t arr[N *2 ]; -static bool is_equal (const void *obj,const void *userp) +static bool is_equal (const void *ap,const void *bp) { -const int32_t *a = obj; -const int32_t *b = userp; +const int32_t *a = ap; +const int32_t *b = bp;return *a == *b; }
@@ -60,7 +60,12 @@ static void check(int a, int b, bool expected) val = i; hash = i; - p =qht_lookup (&ht, is_equal, &val, hash); +/* test both lookup variants; results should be the same */ +if (i %2 ) { + p =qht_lookup (&ht, &val, hash); + }else { + p =qht_lookup_custom (&ht, is_equal, &val, hash); + }g_assert_true (!!p == expected); }rcu_read_unlock ();
@@ -102,7 +107,7 @@ static void qht_do_test(unsigned int mode, size_t init_entries)/* under KVM we might fetch stats from an uninitialized qht */ check_n (0 ); -qht_init (&ht,0 , mode); +qht_init (&ht, is_equal,0 , mode);check_n (0 );insert (0 ,N );
util/qht.c +10 -3
@@ -351,11 +351,13 @@ static struct qht_map *qht_map_create(size_t n_buckets)return map; } -void qht_init (struct qht *ht,size_t n_elems,unsigned int mode) +void qht_init (struct qht *ht,qht_cmp_func_t cmp,size_t n_elems, +unsigned int mode) {struct qht_map *map;size_t n_buckets =qht_elems_to_buckets (n_elems); + ht->cmp = cmp; ht->mode = mode;qemu_mutex_init (&ht->lock); map =qht_map_create (n_buckets);
@@ -479,8 +481,8 @@ void *qht_lookup__slowpath(struct qht_bucket *b, qht_lookup_func_t func,return ret; } -void *qht_lookup (struct qht *ht,qht_lookup_func_t func,const void *userp, -uint32_t hash) +void *qht_lookup_custom (struct qht *ht,qht_lookup_func_t func, +const void *userp,uint32_t hash) {struct qht_bucket *b;struct qht_map *map;
@@ -502,6 +504,11 @@ void *qht_lookup(struct qht *ht, qht_lookup_func_t func, const void *userp,return qht_lookup__slowpath (b, func, userp, hash); } +void *qht_lookup (struct qht *ht,const void *userp,uint32_t hash) +{ +return qht_lookup_custom (ht, ht->cmp, userp, hash); +} +/* call with head->lock held */ static bool qht_insert__locked(struct qht *ht, struct qht_map *map, struct qht_bucket *head, void *p, uint32_t hash,
Signature · 1 line
2.7.4
PATCH 12/22 translate-all: make l1_map lockless
In reply to Emilio G. CotaGroundwork for supporting parallel TCG generation.
We never remove entries from the radix tree, so we can use cmpxchg to implement lockless insertions.
--- docs/devel/multi-thread-tcg.txt | 4 ++-- accel/tcg/translate-all.c | 24 ++++++++++++++---------- 2 files changed, 16 insertions(+), 12 deletions(-)
docs/devel/multi-thread-tcg.txt +2 -2
@@ -134,8 +134,8 @@ tb_set_jmp_target() code. Modification to the linked lists that allow searching for linked pages are done under the protect of the tb_lock(). -The global page table is protected by the tb_lock() in system-mode and -mmap_lock() in linux-user mode. +The global page table is a lockless radix tree; cmpxchg is used +to atomically insert new elements. The lookup caches are updated atomically and the lookup hash uses QHT which is designed for concurrent safe lookup.
accel/tcg/translate-all.c +14 -10
@@ -482,20 +482,12 @@ static void page_init(void)#endif } -/* If alloc=1: -* Called with tb_lock held for system emulation. -* Called with mmap_lock held for user-mode emulation. -*/ static PageDesc *page_find_alloc (tb_page_addr_t index,int alloc) {PageDesc *pd;void **lp;int i; -if (alloc) { -assert_memory_lock (); - } -/* Level 1. Always allocated. */ lp = l1_map + ((index >> v_l1_shift) & (v_l1_size -1 ));
@@ -504,11 +496,17 @@ static PageDesc *page_find_alloc(tb_page_addr_t index, int alloc)void **p =atomic_rcu_read (lp);if (p ==NULL ) { +void *existing; +if (!alloc) {return NULL ; } p = g_new0(void *, V_L2_SIZE); -atomic_rcu_set (lp, p); + existing =atomic_cmpxchg (lp,NULL , p); +if (unlikely (existing)) { +g_free (p); + p = existing; + } } lp = p + ((index >> (i *V_L2_BITS )) & (V_L2_SIZE -1 ));
@@ -516,11 +514,17 @@ static PageDesc *page_find_alloc(tb_page_addr_t index, int alloc) pd =atomic_rcu_read (lp);if (pd ==NULL ) { +void *existing; +if (!alloc) {return NULL ; } pd =g_new0 (PageDesc,V_L2_SIZE ); -atomic_rcu_set (lp, pd); + existing =atomic_cmpxchg (lp,NULL , pd); +if (unlikely (existing)) { +g_free (pd); + pd = existing; + } }return pd + (index & (V_L2_SIZE -1 ));
Signature · 1 line
2.7.4
PATCH 13/22 translate-all: remove hole in PageDesc
In reply to Emilio G. CotaGroundwork for supporting parallel TCG generation.
Move the hole to the end of the struct, so that a u32 field can be added there without bloating the struct.
--- accel/tcg/translate-all.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
accel/tcg/translate-all.c +1 -1
@@ -108,8 +108,8 @@ typedef struct PageDesc {#ifdef CONFIG_SOFTMMU /* in order to optimize self modifying code, we count the number of lookups we do to a given page to use a bitmap */ -unsigned int code_write_count;unsigned long *code_bitmap; +unsigned int code_write_count;#else unsigned long flags;#endif
Signature · 1 line
2.7.4
PATCH 10/22 translate-all: iterate over TBs in a page with page_for_each_tb
In reply to Emilio G. CotaThis commit does several things, but to avoid churn I merged them all into the same commit. To wit:
- Use uintptr_t instead of TranslationBlock * for the list of TBs in a page. Just like we did in (c37e6d7e "tcg: Use uintptr_t type for jmp_list_{next|first} fields of TB"), the rationale is the same: these are tagged pointers, not pointers. So use a more appropriate type.
- Only check the least significant bit of the tagged pointers. Masking with 3/~3 is unnecessary and confusing.
- Use the new tb_for_each_tagged macros to define page_for_each_tb(_safe), which improves readability.
- Update tb_page_remove to use page_for_each_tb_safe(). In case there is a bug and we attempt to remove a TB that is not in the list, instead of segfaulting (since the list is NULL-terminated) we will reach g_assert_not_reached().
--- include/exec/exec-all.h | 2 +- accel/tcg/translate-all.c | 57 ++++++++++++++++++++--------------------------- 2 files changed, 25 insertions(+), 34 deletions(-)
include/exec/exec-all.h +1 -1
@@ -381,7 +381,7 @@ struct TranslationBlock {struct TranslationBlock *orig_tb;/* first and second physical page containing code. The lower bit of the pointer tells the index in page_next[] */ -struct TranslationBlock *page_next[2 ]; +uintptr_t page_next[2 ];tb_page_addr_t page_addr[2 ];/* The following data are used to directly call another TB from
accel/tcg/translate-all.c +24 -33
155 lines not on this page · raw message
Signature · 1 line
2.7.4
PATCH 14/22 translate-all: work page-by-page in tb_invalidate_phys_range_1
In reply to Emilio G. CotaSo that we pass a same-page range to tb_invalidate_phys_page_range, instead of always passing an end address that could be on a different page.
As discussed with Peter Maydell on the list, tb_invalidate_phys_page_range doesn't actually do much with 'end', which explains why we have never hit a bug despite going against what the comment on top of tb_invalidate_phys_page_range requires:
Quoted 2 lines
* Invalidate all TBs which intersect with the target physical address range
* [start;end[. NOTE: start and end must refer to the *same* physical page.
The appended honours the comment, which avoids confusion.
While at it, rework the loop into a for loop, which is less error prone (e.g. "continue" won't result in an infinite loop).
--- accel/tcg/translate-all.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
accel/tcg/translate-all.c +8 -4
@@ -1372,10 +1372,14 @@ TranslationBlock *tb_gen_code(CPUState *cpu,*/ static void tb_invalidate_phys_range_1 (tb_page_addr_t start,tb_page_addr_t end) { -while (start < end) { -tb_invalidate_phys_page_range (start, end,0 ); - start &=TARGET_PAGE_MASK ; - start +=TARGET_PAGE_SIZE ; +tb_page_addr_t next; + +for (next = (start &TARGET_PAGE_MASK ) +TARGET_PAGE_SIZE ; + start < end; + start = next, next +=TARGET_PAGE_SIZE ) { +tb_page_addr_t bound =MIN (next, end); + +tb_invalidate_phys_page_range (start, bound,0 ); } }
Signature · 1 line
2.7.4
PATCH 15/22 translate-all: move tb_invalidate_phys_page_range up in the file
In reply to Emilio G. CotaThis greatly simplifies next commit's diff.
--- accel/tcg/translate-all.c | 77 ++++++++++++++++++++++++----------------------- 1 file changed, 39 insertions(+), 38 deletions(-)
accel/tcg/translate-all.c +39 -38
@@ -1362,44 +1362,6 @@ TranslationBlock *tb_gen_code(CPUState *cpu,/* * Invalidate all TBs which intersect with the target physical address range -* [start;end[. NOTE: start and end may refer to *different* physical pages. -* 'is_cpu_write_access' should be true if called from a real cpu write -* access: the virtual CPU will exit the current TB if code is modified inside -* this TB. -* -* Called with mmap_lock held for user-mode emulation, grabs tb_lock -* Called with tb_lock held for system-mode emulation -*/ -static void tb_invalidate_phys_range_1 (tb_page_addr_t start,tb_page_addr_t end) -{ -tb_page_addr_t next; - -for (next = (start &TARGET_PAGE_MASK ) +TARGET_PAGE_SIZE ; - start < end; - start = next, next +=TARGET_PAGE_SIZE ) { -tb_page_addr_t bound =MIN (next, end); - -tb_invalidate_phys_page_range (start, bound,0 ); - } -} - -#ifdef CONFIG_SOFTMMU -void tb_invalidate_phys_range (tb_page_addr_t start,tb_page_addr_t end) -{ -assert_tb_locked (); -tb_invalidate_phys_range_1 (start, end); -} -#else -void tb_invalidate_phys_range (tb_page_addr_t start,tb_page_addr_t end) -{ -assert_memory_lock (); -tb_lock (); -tb_invalidate_phys_range_1 (start, end); -tb_unlock (); -} -#endif -/* -* Invalidate all TBs which intersect with the target physical address range * [start;end[. NOTE: start and end must refer to the *same* physical page. * 'is_cpu_write_access' should be true if called from a real cpu write * access: the virtual CPU will exit the current TB if code is modified inside
@@ -1501,6 +1463,45 @@ void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end,#endif } +/* +* Invalidate all TBs which intersect with the target physical address range +* [start;end[. NOTE: start and end may refer to *different* physical pages. +* 'is_cpu_write_access' should be true if called from a real cpu write +* access: the virtual CPU will exit the current TB if code is modified inside +* this TB. +* +* Called with mmap_lock held for user-mode emulation, grabs tb_lock +* Called with tb_lock held for system-mode emulation +*/ +static void tb_invalidate_phys_range_1 (tb_page_addr_t start,tb_page_addr_t end) +{ +tb_page_addr_t next; + +for (next = (start &TARGET_PAGE_MASK ) +TARGET_PAGE_SIZE ; + start < end; + start = next, next +=TARGET_PAGE_SIZE ) { +tb_page_addr_t bound =MIN (next, end); + +tb_invalidate_phys_page_range (start, bound,0 ); + } +} + +#ifdef CONFIG_SOFTMMU +void tb_invalidate_phys_range (tb_page_addr_t start,tb_page_addr_t end) +{ +assert_tb_locked (); +tb_invalidate_phys_range_1 (start, end); +} +#else +void tb_invalidate_phys_range (tb_page_addr_t start,tb_page_addr_t end) +{ +assert_memory_lock (); +tb_lock (); +tb_invalidate_phys_range_1 (start, end); +tb_unlock (); +} +#endif +#ifdef CONFIG_SOFTMMU /* len must be <= 8 and start must be a multiple of len. * Called via softmmu_template.h when code areas are written to with
Signature · 1 line
2.7.4
PATCH 7/22 tcg: track TBs with per-region BST's
In reply to Emilio G. CotaThis paves the way for enabling scalable parallel generation of TCG code.
Instead of tracking TBs with a single binary search tree (BST), use a BST for each TCG region, protecting it with a lock. This is as scalable as it gets, since each TCG thread operates on a separate region.
The core of this change is the introduction of struct tcg_region_tree, which contains a pointer to a GTree and an associated lock to serialize accesses to it. We then allocate an array of tcg_region_tree's, adding the appropriate padding to avoid false sharing based on qemu_dcache_linesize.
Given a tc_ptr, we first find the corresponding region_tree. This is done by special-casing the first and last regions first, since they might be of size != region.size; otherwise we just divide the offset by region.stride. I was worried about this division (several dozen cycles of latency), but profiling shows that this is not a fast path. Note that region.stride is not required to be a power of two; it is only required to be a multiple of the host's page size.
Note that with this design we can also provide consistent snapshots about all region trees at once; for instance, tcg_tb_foreach acquires/releases all region_tree locks before/after iterating over them.
As an alternative I considered implementing a concurrent BST, but this can be tricky to get right, offers no consistent snapshots of the BST, and performance and scalability-wise I don't think it could ever beat having separate GTrees, given that our workload is insert-mostly (all concurrent BST designs I've seen focus, understandably, on making lookups fast, which comes at the expense of convoluted, non-wait-free insertions/removals).
--- include/exec/exec-all.h | 1 - include/exec/tb-context.h | 1 - tcg/tcg.h | 6 ++ accel/tcg/cpu-exec.c | 2 +- accel/tcg/translate-all.c | 97 ++++------------------- tcg/tcg.c | 191 ++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 213 insertions(+), 85 deletions(-)
include/exec/exec-all.h +0 -1
@@ -428,7 +428,6 @@ static inline uint32_t curr_cflags(void)return parallel_cpus ?CF_PARALLEL :0 ; } -void tb_remove (TranslationBlock *tb);void tb_flush (CPUState *cpu);void tb_phys_invalidate (TranslationBlock *tb,tb_page_addr_t page_addr); TranslationBlock *tb_htable_lookup(CPUState *cpu, target_ulong pc,
include/exec/tb-context.h +0 -1
@@ -31,7 +31,6 @@ typedef struct TBContext TBContext;struct TBContext { -GTree *tb_tree;struct qht htable;/* any access to the tbs or the page table must use this lock */ QemuMutex tb_lock;
tcg/tcg.h +6 -0
@@ -766,6 +766,12 @@ void tcg_region_reset_all(void);size_t tcg_code_size (void );size_t tcg_code_capacity (void ); +void tcg_tb_insert (TranslationBlock *tb); +void tcg_tb_remove (TranslationBlock *tb); +TranslationBlock *tcg_tb_lookup (uintptr_t tc_ptr); +void tcg_tb_foreach (GTraverseFunc func,gpointer user_data); +size_t tcg_nb_tbs (void ); +/* user-mode: Called with tb_lock held. */ static inline void *tcg_malloc (int size) {
accel/tcg/cpu-exec.c +1 -1
@@ -218,7 +218,7 @@ static void cpu_exec_nocache(CPUState *cpu, int max_cycles,tb_lock ();tb_phys_invalidate (tb,-1 ); -tb_remove (tb); +tcg_tb_remove (tb); tb_unlock(); }#endif
accel/tcg/translate-all.c +15 -82
212 lines not on this page · raw message
tcg/tcg.c +191 -0
221 lines not on this page · raw message
Signature · 1 line
2.7.4
PATCH 17/22 translate-all: discard TB when tb_link_page returns an existing matching TB
In reply to Emilio G. CotaUse the recently-gained QHT feature of returning the matching TB if it already exists. This allows us to get rid of the lookup we perform right after acquiring tb_lock.
--- accel/tcg/cpu-exec.c | 14 ++------------ accel/tcg/translate-all.c | 47 ++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 40 insertions(+), 21 deletions(-)
accel/tcg/cpu-exec.c +2 -12
@@ -237,10 +237,7 @@ void cpu_exec_step_atomic(CPUState *cpu)if (tb ==NULL ) {mmap_lock ();tb_lock (); - tb =tb_htable_lookup (cpu, pc, cs_base, flags, cf_mask); -if (likely (tb ==NULL )) { - tb =tb_gen_code (cpu, pc, cs_base, flags, cflags); - } + tb =tb_gen_code (cpu, pc, cs_base, flags, cflags);tb_unlock ();mmap_unlock (); }
@@ -348,14 +345,7 @@ static inline TranslationBlock *tb_find(CPUState *cpu,tb_lock (); acquired_tb_lock = true; -/* There's a chance that our desired tb has been translated while -* taking the locks so we check again inside the lock. -*/ - tb =tb_htable_lookup (cpu, pc, cs_base, flags, cf_mask); -if (likely (tb ==NULL )) { -/* if no translated code available, then translate it now */ - tb =tb_gen_code (cpu, pc, cs_base, flags, cf_mask); - } + tb =tb_gen_code (cpu, pc, cs_base, flags, cf_mask);mmap_unlock ();/* We add the TB in the virtual pc hash table for the fast lookup */
accel/tcg/translate-all.c +38 -9
91 lines not on this page · raw message
Signature · 1 line
2.7.4
PATCH 19/22 cputlb: remove tb_lock from tlb_flush functions
In reply to Emilio G. CotaThe acquisition of tb_lock was added when the async tlb_flush was introduced in e3b9ca810 ("cputlb: introduce tlb_flush_* async work.")
tb_lock was there to allow us to do memset() on the tb_jmp_cache's. However, since f3ced3c5928 ("tcg: consistently access cpu->tb_jmp_cache atomically") all accesses to tb_jmp_cache are atomic, so tb_lock is not needed here. Get rid of it.
--- accel/tcg/cputlb.c | 8 -------- 1 file changed, 8 deletions(-)
accel/tcg/cputlb.c +0 -8
@@ -125,8 +125,6 @@ static void tlb_flush_nocheck(CPUState *cpu)atomic_set (&env->tlb_flush_count, env->tlb_flush_count +1 );tlb_debug ("(count: %zu)\n" ,tlb_flush_count ()); -tb_lock (); -memset (env->tlb_table,-1 ,sizeof (env->tlb_table));memset (env->tlb_v_table,-1 ,sizeof (env->tlb_v_table));cpu_tb_jmp_cache_clear (cpu);
@@ -135,8 +133,6 @@ static void tlb_flush_nocheck(CPUState *cpu) env->tlb_flush_addr =-1 ; env->tlb_flush_mask =0 ; -tb_unlock (); -atomic_mb_set (&cpu->pending_tlb_flush,0 ); }
@@ -180,8 +176,6 @@ static void tlb_flush_by_mmuidx_async_work(CPUState *cpu, run_on_cpu_data data)assert_cpu_is_self (cpu); -tb_lock (); -tlb_debug ("start: mmu_idx:0x%04lx\n" , mmu_idx_bitmask);for (mmu_idx =0 ; mmu_idx <NB_MMU_MODES ; mmu_idx++) {
@@ -197,8 +191,6 @@ static void tlb_flush_by_mmuidx_async_work(CPUState *cpu, run_on_cpu_data data)cpu_tb_jmp_cache_clear (cpu);tlb_debug ("done\n" ); - -tb_unlock (); }void tlb_flush_by_mmuidx (CPUState *cpu,uint16_t idxmap)
Signature · 1 line
2.7.4
PATCH 20/22 exec: remove tb_lock from notdirty_mem_write
In reply to Emilio G. CotaBy passing a locked page_collection to tb_invalidate_phys_page_fast.
--- accel/tcg/translate-all.h | 3 ++- accel/tcg/translate-all.c | 8 ++++---- exec.c | 11 +++++------ 3 files changed, 11 insertions(+), 11 deletions(-)
accel/tcg/translate-all.h +2 -1
@@ -26,7 +26,8 @@struct page_collection *page_collection_lock (tb_page_addr_t start,tb_page_addr_t end);void page_collection_unlock (struct page_collection *set); -void tb_invalidate_phys_page_fast (tb_page_addr_t start,int len); +void tb_invalidate_phys_page_fast (struct page_collection *pages, +tb_page_addr_t start,int len);void tb_invalidate_phys_page_range (tb_page_addr_t start,tb_page_addr_t end,int is_cpu_write_access);void tb_invalidate_phys_range (tb_page_addr_t start,tb_page_addr_t end);
accel/tcg/translate-all.c +4 -4
@@ -1915,10 +1915,12 @@ void tb_invalidate_phys_range(tb_page_addr_t start, tb_page_addr_t end)/* len must be <= 8 and start must be a multiple of len. * Called via softmmu_template.h when code areas are written to with * iothread mutex not held. +* +* Call with all @pages in the range [@start, @start + len[ locked. */ -void tb_invalidate_phys_page_fast (tb_page_addr_t start,int len) +void tb_invalidate_phys_page_fast (struct page_collection *pages, +tb_page_addr_t start,int len) { -struct page_collection *pages;PageDesc *p;#if 0
@@ -1937,7 +1939,6 @@ void tb_invalidate_phys_page_fast(tb_page_addr_t start, int len)return ; } - pages =page_collection_lock (start, start + len);if (!p->code_bitmap && ++p->code_write_count >=SMC_BITMAP_USE_THRESHOLD ) {build_page_bitmap (p);
@@ -1955,7 +1956,6 @@ void tb_invalidate_phys_page_fast(tb_page_addr_t start, int len) do_invalidate: tb_invalidate_phys_page_range__locked(pages, p, start, start + len, 1); } -page_collection_unlock (pages); }#else /* Called with mmap_lock held. If pc is not 0 then it indicates the
exec.c +5 -6
@@ -2331,13 +2331,12 @@ ram_addr_t qemu_ram_addr_from_host(void *ptr)static void notdirty_mem_write (void *opaque,hwaddr ram_addr,uint64_t val,unsigned size) { -bool locked = false; +struct page_collection *pages =NULL ;assert (tcg_enabled ());if (!cpu_physical_memory_get_dirty_flag (ram_addr,DIRTY_MEMORY_CODE )) { - locked = true; -tb_lock (); -tb_invalidate_phys_page_fast (ram_addr, size); + pages =page_collection_lock (ram_addr, ram_addr + size); +tb_invalidate_phys_page_fast (pages, ram_addr, size); }switch (size) {case 1 :
@@ -2353,8 +2352,8 @@ static void notdirty_mem_write(void *opaque, hwaddr ram_addr,abort (); } -if (locked) { -tb_unlock (); +if (pages) { +page_collection_unlock (pages); }/* Set both VGA and migration bits for simplicity and to remove
Signature · 1 line
2.7.4
PATCH 21/22 translate-all: remove tb_lock mention from cpu_restore_state_from_tb
In reply to Emilio G. Cotatb_lock was needed when the function did retranslation. However, since fca8a500d519 ("tcg: Save insn data and use it in cpu_restore_state_from_tb") we don't do retranslation.
Get rid of the comment.
--- accel/tcg/translate-all.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
accel/tcg/translate-all.c +1 -3
@@ -376,9 +376,7 @@ static int encode_search(TranslationBlock *tb, uint8_t *block)return p - block; } -/* The cpu state corresponding to 'searched_pc' is restored. -* Called with tb_lock held. -*/ +/* The cpu state corresponding to 'searched_pc' is restored */ static int cpu_restore_state_from_tb (CPUState *cpu,TranslationBlock *tb,uintptr_t searched_pc) {
Signature · 1 line
2.7.4
PATCH 18/22 translate-all: protect TB jumps with a per-destination-TB lock
In reply to Emilio G. CotaThis applies to both user-mode and !user-mode emulation.
Instead of relying on a global lock, protect the list of incoming jumps with tb->jmp_lock.
In order to find the destination TB (and therefore its jmp_lock) from the origin TB, we introduce tb->jmp_dest[]. This results in TranslationBlock using 3 cache lines on many systems instead of 2, but benchmarking doesn't seem to suffer much because of it.
I considered not using a linked list of jumps, which simplifies code and keeps the struct under two cache lines. However, it unnecessarily increases memory usage, which results in a performance decrease. See for instance these numbers booting+shutting down debian-arm:
Time (s) Rel. err (%) Abs. err (s) Rel. slowdown (%)
------------------------------------------------------------------------------
before 20.88 0.74 0.154512 0. after 20.81 0.38 0.079078 -0.33524904 GTree 21.02 0.28 0.058856 0.67049808 GHashTable + xxhash 21.63 1.08 0.233604 3.5919540
Using a hash table or a binary tree to keep track of the jumps doesn't really pay off, not only due to the increased memory usage, but also because most TBs have only 0 or 1 jumps to them. The maximum number of jumps when booting debian-arm that I measured is 35, but as we can see in the histogram below a TB with that many incoming jumps is extremely rare; the average TB has 0.80 incoming jumps.
n_jumps: 379208; avg jumps/tb: 0.801099
dist: [0.0,1.0)|▄█▁▁▁▁▁▁▁▁▁▁▁ ▁▁▁▁▁▁ ▁▁▁ ▁▁▁ ▁|[34.0,35.0]
--- docs/devel/multi-thread-tcg.txt | 6 ++- include/exec/exec-all.h | 76 ++++++++++++++++++--------- accel/tcg/cpu-exec.c | 4 +- accel/tcg/translate-all.c | 110 +++++++++++++++++++++++++--------------- 4 files changed, 126 insertions(+), 70 deletions(-)
docs/devel/multi-thread-tcg.txt +4 -2
@@ -131,8 +131,10 @@ DESIGN REQUIREMENT: Safely handle invalidation of TBs The direct jump themselves are updated atomically by the TCG tb_set_jmp_target() code. Modification to the linked lists that allow -searching for linked pages are done under the protect of the -tb_lock(). +searching for linked pages are done under the protection of tb->jmp_lock, +where tb is the destination block of a jump. Each origin block keeps a +pointer to its destinations so that the appropriate lock can be acquired before +iterating over a jump list. The global page table is a lockless radix tree; cmpxchg is used to atomically insert new elements.
include/exec/exec-all.h +51 -25
106 lines not on this page · raw message
accel/tcg/cpu-exec.c +1 -3
@@ -366,9 +366,7 @@ static inline TranslationBlock *tb_find(CPUState *cpu,tb_lock (); acquired_tb_lock = true; } -if (!(tb->cflags &CF_INVALID )) { -tb_add_jump (last_tb, tb_exit, tb); - } +tb_add_jump (last_tb, tb_exit, tb); }if (acquired_tb_lock) {tb_unlock ();
accel/tcg/translate-all.c +70 -40
150 lines not on this page · raw message
Signature · 1 line
2.7.4
PATCH 16/22 translate-all: use per-page locking in !user-mode
In reply to Emilio G. CotaGroundwork for supporting parallel TCG generation.
Instead of using a global lock (tb_lock) to protect changes to pages, use fine-grained, per-page locks in !user-mode. User-mode stays with mmap_lock.
Sometimes changes need to happen atomically on more than one page (e.g. when a TB that spans across two pages is added/invalidated, or when a range of pages is invalidated). We therefore introduce struct page_collection, which helps us keep track of a set of pages that have been locked in the appropriate locking order (i.e. by ascending page index).
This commit first introduces the structs and the function helpers, to then convert the calling code to use per-page locking. Note that tb_lock is not removed yet.
While at it, rename tb_alloc_page to tb_page_add, which pairs with tb_page_remove.
--- accel/tcg/translate-all.h | 3 + include/exec/exec-all.h | 3 +- accel/tcg/translate-all.c | 433 +++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 397 insertions(+), 42 deletions(-)
accel/tcg/translate-all.h +3 -0
@@ -23,6 +23,9 @@/* translate-all.c */ +struct page_collection *page_collection_lock (tb_page_addr_t start, +tb_page_addr_t end); +void page_collection_unlock (struct page_collection *set);void tb_invalidate_phys_page_fast (tb_page_addr_t start,int len);void tb_invalidate_phys_page_range (tb_page_addr_t start,tb_page_addr_t end,int is_cpu_write_access);
include/exec/exec-all.h +2 -1
@@ -380,7 +380,8 @@ struct TranslationBlock {/* original tb when cflags has CF_NOCACHE */ struct TranslationBlock *orig_tb;/* first and second physical page containing code. The lower bit -of the pointer tells the index in page_next[] */ +of the pointer tells the index in page_next[]. +The list is protected by the TB's page('s) lock(s) */ uintptr_t page_next[2 ];tb_page_addr_t page_addr[2 ];
accel/tcg/translate-all.c +392 -41
593 lines not on this page · raw message
Signature · 1 line
2.7.4
PATCH 22/22 tcg: remove tb_lock
In reply to Emilio G. CotaUse mmap_lock in user-mode to protect TCG state and the page descriptors.
In !user-mode, each vCPU has its own TCG state, so no locks needed. Per-page locks are used to protect the page descriptors.
Per-TB locks are used in both modes to protect TB jumps.
Some notes:
- tcg_tb_lookup/remove/insert/etc have their own internal lock(s), so there is no need to further serialize access to them.
- do_tb_flush is run in a safe async context, meaning no other vCPU threads are running. Therefore acquiring mmap_lock there is just to please tools such as thread sanitizer.
- Not visible in the diff, but tb_invalidate_phys_page already has an assert_memory_lock.
- cpu_io_recompile is !user-only, so no mmap_lock there.
- Added mmap_unlock()'s before all siglongjmp's that could be called in user-mode while mmap_lock is held.
+ Added an assert for !have_mmap_lock() after returning from the longjmp in cpu_exec, just like we do in cpu_exec_step_atomic.
Performance numbers for the entire series (i.e. since "tcg: enable multiple TCG contexts in softmmu"):
Host: Intel(R) Xeon(R) CPU E5-2690 0 @ 2.90GHz, 16 2-way cores
- Single-threaded, debian-arm bootup+shutdown (5 runs):
* Before:
20.617793812 seconds time elapsed ( +- 0.73% )
* After:
20.713322693 seconds time elapsed ( +- 0.93% )- "-smp 8", debian-arm bootup+shutdown (5 runs):
* Before:
16.900252299 seconds time elapsed ( +- 1.30% )
* After:
12.777150639 seconds time elapsed ( +- 1.11% )- "-smp 16", bootup+shutdown of ubuntu-17.10-ppc64el (5 runs):
[ NB. The actual times are 27s longer, but I'm subtracting that
since that's the time it takes on this host to start loading the guest kernel (there's grub, etc) ]
* Before:
115.382853773 seconds time elapsed ( +- 1.24% )
* After:
76.361623367 seconds time elapsed ( +- 0.49% )--- docs/devel/multi-thread-tcg.txt | 11 ++-- include/exec/cpu-common.h | 1 - include/exec/exec-all.h | 4 -- include/exec/tb-context.h | 2 - tcg/tcg.h | 4 +- accel/tcg/cpu-exec.c | 34 +++------- accel/tcg/translate-all.c | 135 ++++++++++++---------------------------- exec.c | 14 ++--- linux-user/main.c | 3 - 9 files changed, 62 insertions(+), 146 deletions(-)
docs/devel/multi-thread-tcg.txt +7 -4
@@ -61,6 +61,7 @@ have their block-to-block jumps patched. Global TCG State ---------------- +### User-mode emulation We need to protect the entire code generation cycle including any post generation patching of the translated code. This also implies a shared translation buffer which contains code running on all cores. Any
@@ -75,9 +76,11 @@ patching. (Current solution) -Mainly as part of the linux-user work all code generation is -serialised with a tb_lock(). For the SoftMMU tb_lock() also takes the -place of mmap_lock() in linux-user. +Code generation is serialised with mmap_lock(). + +### !User-mode emulation +Each vCPU has its own TCG context and associated TCG region, thereby +requiring no locking. Translation Blocks ------------------
@@ -192,7 +195,7 @@ work as "safe work" and exiting the cpu run loop. This ensure by the time execution restarts all flush operations have completed. TLB flag updates are all done atomically and are also protected by the -tb_lock() which is used by the functions that update the TLB in bulk. +corresponding page lock. (Known limitation)
include/exec/cpu-common.h +0 -1
@@ -23,7 +23,6 @@ typedef struct CPUListState {FILE *file; } CPUListState; -/* The CPU list lock nests outside tb_lock/tb_unlock. */ void qemu_init_cpu_list (void );void cpu_list_lock (void );void cpu_list_unlock (void );
include/exec/exec-all.h +0 -4
@@ -557,10 +557,6 @@ extern uintptr_t tci_tb_ptr;smaller than 4 bytes, so we don't worry about special-casing this. */ #define GETPC_ADJ 2 -void tb_lock (void ); -void tb_unlock (void ); -void tb_lock_reset (void ); -#if !defined(CONFIG_USER_ONLY ) struct MemoryRegion *iotlb_to_region(CPUState *cpu,
include/exec/tb-context.h +0 -2
@@ -32,8 +32,6 @@ typedef struct TBContext TBContext;struct TBContext {struct qht htable; -/* any access to the tbs or the page table must use this lock */ -QemuMutex tb_lock;/* statistics */ unsigned tb_flush_count;
tcg/tcg.h +2 -2
@@ -757,7 +757,7 @@ static inline bool tcg_op_buf_full(void)/* pool based memory allocation */ -/* user-mode: tb_lock must be held for tcg_malloc_internal. */ +/* user-mode: mmap_lock must be held for tcg_malloc_internal. */ void *tcg_malloc_internal (TCGContext *s,int size);void tcg_pool_reset (TCGContext *s);TranslationBlock *tcg_tb_alloc (TCGContext *s);
@@ -775,7 +775,7 @@ TranslationBlock *tcg_tb_lookup(uintptr_t tc_ptr);void tcg_tb_foreach (GTraverseFunc func,gpointer user_data);size_t tcg_nb_tbs (void ); -/* user-mode: Called with tb_lock held. */ +/* user-mode: Called with mmap_lock held. */ static inline void *tcg_malloc (int size) {TCGContext *s = tcg_ctx;
accel/tcg/cpu-exec.c +8 -26
@@ -204,22 +204,22 @@ static void cpu_exec_nocache(CPUState *cpu, int max_cycles,if (max_cycles >CF_COUNT_MASK ) max_cycles =CF_COUNT_MASK ; -tb_lock (); +mmap_lock (); tb =tb_gen_code (cpu, orig_tb->pc, orig_tb->cs_base, orig_tb->flags, max_cycles |CF_NOCACHE | (ignore_icount ?CF_IGNORE_ICOUNT :0 ) |curr_cflags ()); tb->orig_tb = orig_tb; -tb_unlock (); +mmap_unlock ();/* execute the generated code */ trace_exec_tb_nocache (tb, tb->pc);cpu_tb_exec (cpu, tb); -tb_lock (); +mmap_lock ();tb_phys_invalidate (tb,-1 ); +mmap_unlock (); tcg_tb_remove(tb); - tb_unlock(); }#endif
@@ -236,9 +236,7 @@ void cpu_exec_step_atomic(CPUState *cpu) tb =tb_lookup__cpu_state (cpu, &pc, &cs_base, &flags, cf_mask);if (tb ==NULL ) {mmap_lock (); -tb_lock (); tb =tb_gen_code (cpu, pc, cs_base, flags, cflags); -tb_unlock ();mmap_unlock (); }
@@ -255,15 +253,13 @@ void cpu_exec_step_atomic(CPUState *cpu)end_exclusive (); }else { -/* We may have exited due to another problem here, so we need -* to reset any tb_locks we may have taken but didn't release. +/* * The mmap_lock is dropped by tb_gen_code if it runs out of * memory. */ #ifndef CONFIG_SOFTMMU tcg_debug_assert (!have_mmap_lock ());#endif -tb_lock_reset (); } }
@@ -332,21 +328,12 @@ static inline TranslationBlock *tb_find(CPUState *cpu,TranslationBlock *tb;target_ulong cs_base, pc;uint32_t flags; -bool acquired_tb_lock = false;uint32_t cf_mask =curr_cflags (); tb =tb_lookup__cpu_state (cpu, &pc, &cs_base, &flags, cf_mask);if (tb ==NULL ) { -/* mmap_lock is needed by tb_gen_code, and mmap_lock must be -* taken outside tb_lock. As system emulation is currently -* single threaded the locks are NOPs. -*/ mmap_lock (); -tb_lock (); - acquired_tb_lock = true; - tb =tb_gen_code (cpu, pc, cs_base, flags, cf_mask); -mmap_unlock ();/* We add the TB in the virtual pc hash table for the fast lookup */ atomic_set (&cpu->tb_jmp_cache[tb_jmp_cache_hash_func (pc)], tb);
@@ -362,15 +349,8 @@ static inline TranslationBlock *tb_find(CPUState *cpu,#endif /* See if we can patch the calling TB. */ if (last_tb && !qemu_loglevel_mask (CPU_LOG_TB_NOCHAIN )) { -if (!acquired_tb_lock) { -tb_lock (); - acquired_tb_lock = true; - }tb_add_jump (last_tb, tb_exit, tb); } -if (acquired_tb_lock) { -tb_unlock (); - }return tb; }
@@ -636,7 +616,9 @@ int cpu_exec(CPUState *cpu)g_assert (cc ==CPU_GET_CLASS (cpu));#endif /* buggy compiler */ cpu->can_do_io =1 ; -tb_lock_reset (); +#ifndef CONFIG_SOFTMMU +tcg_debug_assert (!have_mmap_lock ()); +#endif if (qemu_mutex_iothread_locked ()) {qemu_mutex_unlock_iothread (); }
accel/tcg/translate-all.c +40 -95
352 lines not on this page · raw message
exec.c +5 -9
@@ -782,9 +782,7 @@ void cpu_exec_realizefn(CPUState *cpu, Error **errp)static void breakpoint_invalidate (CPUState *cpu,target_ulong pc) {mmap_lock (); -tb_lock ();tb_invalidate_phys_page_range (pc, pc +1 ,0 ); -tb_unlock ();mmap_unlock (); }#else
@@ -2419,18 +2417,16 @@ static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags) } cpu->watchpoint_hit = wp; -/* Both tb_lock and iothread_mutex will be reset when -* cpu_loop_exit or cpu_loop_exit_noexc longjmp -* back into the cpu_exec main loop. -*/ -tb_lock (); +mmap_lock ();tb_check_watchpoint (cpu);if (wp->flags &BP_STOP_BEFORE_ACCESS ) { cpu->exception_index =EXCP_DEBUG ; +mmap_unlock ();cpu_loop_exit (cpu); }else {cpu_get_tb_cpu_state (env, &pc, &cs_base, &cpu_flags);tb_gen_code (cpu, pc, cs_base, cpu_flags,1 |curr_cflags ()); +mmap_unlock ();cpu_loop_exit_noexc (cpu); } }
@@ -2838,9 +2834,9 @@ static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr, }if (dirty_log_mask & (1 <<DIRTY_MEMORY_CODE )) {assert (tcg_enabled ()); -tb_lock (); +mmap_lock ();tb_invalidate_phys_range (addr, addr + length); -tb_unlock (); +mmap_unlock (); dirty_log_mask &= ~(1 <<DIRTY_MEMORY_CODE ); }cpu_physical_memory_set_dirty_range (addr, length, dirty_log_mask);
linux-user/main.c +0 -3
@@ -114,7 +114,6 @@ int cpu_get_pic_interrupt(CPUX86State *env)void fork_start (void ) {cpu_list_lock (); -qemu_mutex_lock (&tb_ctx.tb_lock);mmap_fork_start (); }
@@ -130,11 +129,9 @@ void fork_end(int child)QTAILQ_REMOVE (&cpus, cpu, node); } } -qemu_mutex_init (&tb_ctx.tb_lock);qemu_init_cpu_list ();gdbserver_fork (thread_cpu); }else { -qemu_mutex_unlock (&tb_ctx.tb_lock);cpu_list_unlock (); } }
Signature · 1 line
2.7.4
Quoted 18 lines · Emilio G. Cota
This series applies on top of the "multiple TCG contexts" series, v4:
https://lists.gnu.org/archive/html/qemu-devel/2017-07/msg06769.htmlHighlights:
- First, fix a few typos I encountered while working on this (patches 1-3). I could send them separately to qemu-trivial if you prefer.
- QHT: use a proper cmp function, instead of just checking pointer values to determine equality of matches.
- Use a binary search tree for each TCG region.
- Makel1_maplockless by using cmpxchg
- Introduce page locks (for !user-mode), so thattb_lockis not needed when operating on a page
- Introducepage_collection, to lock a range of pages
- Introducetb->jmp_lockto protect TB jump lists.
- Removetb_lock. User-mode uses justmmap_lockand tb->jmp_lock's; !user-mode uses the same jump locks as well as page locks.
Quoted 5 lines
Performance numbers are in patch 22. We get nice speedups, but I still see a lot of idling when booting many cores. I suspect it comes from cross-CPU events (e.g. TLB invalidations), but I need to profile it better (perf is not good for this; mutrace doesn't quite work). But anyway that's for another patchset.
The idling is due to BQL contention related to interrupt handling. In the case of ARM, this boils down to the GICv3 code being single-threaded. I don't have time right now to make it multi-threaded, but at least we know where the scalability bottleneck is.
BTW if there's interest I can submit the lock profiler to the list. The code is in this branch:
https://github.com/cota/qemu/tree/lock-profiler
The first commit has sample output: https://github.com/cota/qemu/commit/c5bda634
Also, any feedback on the parent (tb_lock removal) patchset would be appreciated.
To make the 2.11 merge easier, I rebased this patchset (as well as the multi-tcg-v4 set it is based on) on top of rth's tcg-generic-15, fixing a good bunch of annoying conflicts. The resulting branch is available at:
https://github.com/cota/qemu/tree/tcg-generic-15%2Bmulti-tcg-v4-parallel
Thanks,
Emilio
Quoted 2 lines · Emilio G. Cota
This series applies on top of the "multiple TCG contexts" series, v4:
https://lists.gnu.org/archive/html/qemu-devel/2017-07/msg06769.html
(snip)
Quoted 1 line
Please review!
Turns out this patchset breaks icount, even after fixing the patchset it is based on (see [1]).
The last good patch in the series is patch 10:
"translate-all: work page-by-page in tb_invalidate_phys_range_1". I have no time to look into fixing that, so if you end up reviewing this set, please review only patches 1-10.
The good news is that patches > 10 get really hairy, so this should reduce the review burden substantially.
Thanks,
Emilio
[1] https://lists.gnu.org/archive/html/qemu-devel/2017-10/msg01198.html
Quoted 8 lines · Emilio G. Cota
Quoted 2 lines · Emilio G. Cota
This series applies on top of the "multiple TCG contexts" series, v4:
https://lists.gnu.org/archive/html/qemu-devel/2017-07/msg06769.html(snip)
Quoted 1 line
Please review!
Turns out this patchset breaks icount, even after fixing the patchset it is based on (see [1]).
Isn't icount only used in single-threaded mode though?
Quoted 6 lines
The last good patch in the series is patch 10:
"translate-all: work page-by-page intb_invalidate_phys_range_1". I have no time to look into fixing that, so if you end up reviewing this set, please review only patches 1-10.
Quoted 8 lines
The good news is that patches > 10 get really hairy, so this should reduce the review burden substantially.
Thanks,
Emilio
[1] https://lists.gnu.org/archive/html/qemu-devel/2017-10/msg01198.html
--
Alex Bennée
Quoted 6 lines · Alex Bennée
Quoted 3 lines · Emilio G. Cota
Quoted 2 lines · Emilio G. Cota
This series applies on top of the "multiple TCG contexts" series, v4:
https://lists.gnu.org/archive/html/qemu-devel/2017-07/msg06769.html
Quoted 7 lines
Quoted 5 lines
(snip)
Quoted 1 line
Please review!
Turns out this patchset breaks icount, even after fixing the patchset it is based on (see [1]).
Isn't icount only used in single-threaded mode though?
Yes, but it also hits some code paths that get executed very rarely (or not at all) in !icount mode. And we still acquire locks in single-threaded mode -- the breakage is most likely due to a missing page_unlock somewhere.
Cheers,
Emilio