real ll/sc emulation
cover real ll/sc emulation
I've been toying with how we might do a more faithful ll/sc emulation. Our cmpxchg based one actually had problems on some firmware code we're testing.
The using the dirty memory bitmap to detect stores coming from other CPUs and invalidating active protection / reservations seems to be a possibility. This passes some basic atomic and locking stress tests with mttcg, and boots Linux.
Excuse some of the hacky / ugly / unfinished bits of code, I missed getting into details of vfio, migration, and making it clean. Just wanted to hear thoughts on the general idea at the moment.
The code doesn't seem to be _terribly_ tricky, but there are some tricks around the store-conditional side of it where we have to take a mutex, do the tlb lookup with possible recursion into the code protected by that mutex, verify the protection is still active, and then modify memory.
There is only a single lock now, but if that beomes a problem we *might* be able to split it via physical address hash. But that doesn't help uncontended performance or contention on the same address, which are probably the two most important cases.
(I will submit the TCG TLB coherency fix patch separately, difficulty at the moment is creating a test case for it that does not require subsequent patches!)
Thanks,
Nick
Nicholas Piggin (3):
accel/tcg: Fix TCG TLB coherency race with physical dirty bit clearing
tcg: add a ll/sc protection facility
target/ppc: Implement reservation protection for larx/stcx
include/exec/cputlb.h | 7 ++ include/exec/exec-all.h | 1 - include/exec/ram_addr.h | 42 ++++++- include/exec/ramlist.h | 10 ++ include/hw/core/cpu.h | 5 + target/ppc/cpu-param.h | 4 + target/ppc/helper.h | 2 + accel/stubs/tcg-stub.c | 4 - accel/tcg/cputlb.c | 235 ++++++++++++++++++++++++++++++++++++--- hw/core/cpu-common.c | 5 + hw/vfio/common.c | 2 +- hw/virtio/vhost.c | 1 + system/memory.c | 3 + system/physmem.c | 7 ++ target/ppc/cpu_init.c | 4 + target/ppc/mem_helper.c | 132 ++++++++++++++++++++++ target/ppc/translate.c | 128 +++++---------------- system/memory_ldst.c.inc | 3 +- 18 files changed, 467 insertions(+), 128 deletions(-)
Signature · 1 line
2.42.0
RFC PATCH 1/3 accel/tcg: Fix TCG TLB coherency race with physical dirty bit clearing
The TCG TLB keeps a TLB_NOTDIRTY bit that must be kept coherent with the cpu physical dirty memory bitmaps. If any bits are clear, TLB_NOTDIRTY *must* be set in all CPUs so that the nodirty_write() slowpath is guaranteed to be called on a write access.
TLB_NOTDIRTY may be set if none of the bits are clear, it just results in a superfluous nodirty_write() call (which should remove the bit).
There is a race with clearing physical dirty bits and setting TLB_NOTDIRTY vs setting or creating TLB entries without the TLB_NOTDIRTY bit, that can cause the bit to get lost and notdirty_write() updates to be missed.
nodirty_write()
1. cpu_physical_memory_set_dirty_range()
2. if (!cpu_physical_memory_is_clean())
3. tlb_set_dirty()
vs
cpu_physical_memory_test_and_clear_dirty()
A. dirty = bitmap_test_and_clear_atomic()
if (dirty)
B. tlb_reset_dirty_range_all()
1 executes, then 2 finds no bits clean, then A clears the dirty bit and runs B to set TLB_NOTDIRTY on the TLB entries, then 3 clears the TLB_NOTDIRTY bits from the TLB entries.
This results in the physical dirty bitmap having a clear bit with a TLB entry pointing to it without TLB_NOTDIRTY, which means stores through that TLB are performed without the notdirty_write() call to set dirty bits (or invalidate tb).
Fix this by checking the physical dirty bitmap while holding the TLB lock that also covers TLB entry insertion / TLB_NOTDIRTY clearing.
---
Hi Thomas,
This is the other dirty bitmap race I saw, if you are hunting migration bugs...
Thanks,
Nick
include/exec/exec-all.h | 1 - accel/stubs/tcg-stub.c | 4 ---- accel/tcg/cputlb.c | 47 +++++++++++++++++++++++++++++------------ 3 files changed, 33 insertions(+), 19 deletions(-)
include/exec/exec-all.h +0 -1
@@ -654,7 +654,6 @@ static inline void mmap_unlock(void) {}#define WITH_MMAP_LOCK_GUARD ()void tlb_reset_dirty (CPUState *cpu,ram_addr_t start1,ram_addr_t length); -void tlb_set_dirty (CPUState *cpu,vaddr addr);MemoryRegionSection * address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
accel/stubs/tcg-stub.c +0 -4
@@ -18,10 +18,6 @@ void tb_flush(CPUState *cpu) { } -void tlb_set_dirty (CPUState *cpu,vaddr vaddr) -{ -} -int probe_access_flags (CPUArchState *env,vaddr addr,int size,MMUAccessType access_type,int mmu_idx,bool nonfault,void **phost,uintptr_t retaddr)
accel/tcg/cputlb.c +33 -14
86 lines not on this page · raw message
Signature · 1 line
2.42.0
RFC PATCH 2/3 tcg: add a ll/sc protection facility
In reply to Nicholas PigginThis uses the cpu physical memory dirty mechanism to provide a LL/SC protection system, so that a CPU can set llsc protection on a block of memory, and it can check whether any other CPUs have stored to that memory in a way that can be done race-free to perform a store conditional on that check.
QEMU TCG implements LL/SC conditional store with an atomic cmpxchg that only checks that the value of memory is the same as the value returned by the LL. This works well in practice, but it does not faithfully emulate LL/SC. Among the issues are:
1. cmpxchg incorrectly succeeds in the case that stores were performed by other CPUs, but the observed value is the same. Also known as the ABA problem.
2. Some implementations (e.g., IBM POWER) provide a protection block (reservation granule) size that is larger than the load. A store from another CPU to anywhere in the granule should cause a loss of protection. A conditional store from this CPU to anywhere in the granule could also succeed. Some IBM firmware relies on this implementation detail.
3. Some (e.g., ppc, arm) implementations of LL/SC work on physical memory. It could succeed if the store is performed at a different virtual address than the load, if they alias to the same physical memory.
4. Some implementations allow the CPU that performed the load to store a different value at that memory location with a simple store, and have the conditional-store succeed.
These can cause varying degrees of problems. 2. was observed to cause a real problem. Although most open source code doesn't seem to have a problem. And I think the more restrictie pseudo-LLSC encourages software to be clean :)
The ABA problem *almost* has an interesting memory ordering problem vs Linux spinlocks:
lock:
larx
cmp
bne busy
stcx.
bne- lock
lwsync
The lwsync barrier permits loads to be performed ahead of earleir stores so a load in the critical section can see a result before the stcx. store to set the lock is visible to other CPUs. This works because lwsync does prevent those loads being performed before the earlier larx, so they must be performed with a valid reservation that results in the lock being taken.
If another CPU could come between the larx and stcx. and take the lock, perform a critical section, and then release the lock, then if the stcx. succeeds, the lwsync would not prevent loads in the critical section being performed before it. The saving grace here is that a cmpxchg-based stcx. itself has to be implemented with a larx on the host, so it does end up ordering correctly. Maybe that is inherent in any similar kind of issue and so it's not really very interesting, but I thought it showed possible subtle issues (one of our firmware engineers spotted it).
--- include/exec/cputlb.h | 7 ++ include/exec/ram_addr.h | 42 ++++++++- include/exec/ramlist.h | 10 +++ include/hw/core/cpu.h | 5 ++ accel/tcg/cputlb.c | 188 ++++++++++++++++++++++++++++++++++++++- hw/core/cpu-common.c | 5 ++ hw/vfio/common.c | 2 +- hw/virtio/vhost.c | 1 + system/memory.c | 3 + system/physmem.c | 7 ++ system/memory_ldst.c.inc | 3 +- 11 files changed, 266 insertions(+), 7 deletions(-)
include/exec/cputlb.h +7 -0
@@ -27,4 +27,11 @@void tlb_protect_code (ram_addr_t ram_addr);void tlb_unprotect_code (ram_addr_t ram_addr);#endif + +void cpu_set_llsc_prot (CPUState *cpu,ram_addr_t addr); +bool cpu_resolve_llsc_begin (CPUState *cpu); +void cpu_resolve_llsc_abort (CPUState *cpu); +bool cpu_resolve_llsc_check (CPUState *cpu,ram_addr_t addr); +void cpu_resolve_llsc_success (CPUState *cpu); +#endif
include/exec/ram_addr.h +39 -3
90 lines not on this page · raw message
include/exec/ramlist.h +10 -0
@@ -8,10 +8,20 @@typedef struct RAMBlockNotifier RAMBlockNotifier ; +/* XXX: hack, need to work out how to do this */ +#ifndef TARGET_HAS_LLSC_PROT +#define TARGET_HAS_LLSC_PROT +#endif +#define DIRTY_MEMORY_VGA 0#define DIRTY_MEMORY_CODE 1#define DIRTY_MEMORY_MIGRATION 2 +#ifdef TARGET_HAS_LLSC_PROT +#define DIRTY_MEMORY_LLSC_PROT 3 +#define DIRTY_MEMORY_NUM 4/* num of dirty bits */ +#else #define DIRTY_MEMORY_NUM 3/* num of dirty bits */ +#endif /* The dirty memory bitmap is split into fixed-size blocks to allow growth * under RCU. The bitmap for a block can be accessed as follows:
include/hw/core/cpu.h +5 -0
@@ -489,6 +489,11 @@ struct CPUState {uint64_t random_seed;sigjmp_buf jmp_env; +int llsc_prot_block_size; +bool llsc_prot_active; +bool llsc_resolving; +hwaddr llsc_prot_address;/* ram_addr_t physical address of reservation */ +QemuMutex work_mutex; QSIMPLEQ_HEAD(, qemu_work_item) work_list;
accel/tcg/cputlb.c +186 -2
214 lines not on this page · raw message
hw/core/cpu-common.c +5 -0
@@ -250,6 +250,11 @@ static void cpu_common_initfn(Object *obj) cpu->nr_cores =1 ; cpu->nr_threads =1 ; cpu->cflags_next_tb =-1 ; +#ifdef TARGET_HAS_LLSC_PROT + cpu->llsc_prot_active = false; + cpu->llsc_prot_address =-1ULL ; + cpu->llsc_resolving = false; +#endif qemu_mutex_init (&cpu->work_mutex);qemu_lockcnt_init (&cpu->in_ioctl_lock);
hw/vfio/common.c +1 -1
@@ -1174,7 +1174,7 @@ int vfio_get_dirty_bitmap(const VFIOContainerBase *bcontainer, uint64_t iova,if (!bcontainer->dirty_pages_supported && !all_device_dirty_tracking) {cpu_physical_memory_set_dirty_range (ram_addr, size,tcg_enabled () ?DIRTY_CLIENTS_ALL : -DIRTY_CLIENTS_NOCODE ); +DIRTY_CLIENTS_ONESHOT );return 0 ; }
hw/virtio/vhost.c +1 -0
@@ -520,6 +520,7 @@ static bool vhost_section(struct vhost_dev *dev, MemoryRegionSection *section)*/ handled_dirty = (1 <<DIRTY_MEMORY_MIGRATION ) | (1 <<DIRTY_MEMORY_CODE ); +/* XXX: llsc? */ if (dirty_mask & ~handled_dirty) {trace_vhost_reject_section (mr->name,1 );
system/memory.c +3 -0
@@ -1863,6 +1863,9 @@ uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)if (tcg_enabled () && rb) {/* TCG only cares about dirty memory logging for RAM, not IOMMU. */ mask |= (1 <<DIRTY_MEMORY_CODE ); +#ifdef TARGET_HAS_LLSC_PROT + mask |= (1 <<DIRTY_MEMORY_LLSC_PROT ); +#endif }return mask; }
system/physmem.c +7 -0
@@ -2591,6 +2591,13 @@ static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr, dirty_log_mask =cpu_physical_memory_range_includes_clean (addr, length, dirty_log_mask); } +#ifdef TARGET_HAS_LLSC_PROT +if (dirty_log_mask & (1 <<DIRTY_MEMORY_LLSC_PROT )) { +assert (tcg_enabled ()); +/* XXX should invalidate CPU's llsc_prot protections here? */ + dirty_log_mask &= ~(1 <<DIRTY_MEMORY_LLSC_PROT ); + } +#endif if (dirty_log_mask & (1 <<DIRTY_MEMORY_CODE )) {assert (tcg_enabled ());tb_invalidate_phys_range (addr, addr + length -1 );
system/memory_ldst.c.inc +2 -1
@@ -286,7 +286,8 @@ void glue(address_space_stl_notdirty, SUFFIX)(ARG1_DECL, stl_p(ptr, val); dirty_log_mask = memory_region_get_dirty_log_mask(mr); - dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE); +// dirty_log_mask &= ~((1 << DIRTY_MEMORY_CODE) | (1 << DIRTY_MEMORY_LLSC_PROT)); + dirty_log_mask &= DIRTY_CLIENTS_ONESHOT; cpu_physical_memory_set_dirty_range(memory_region_get_ram_addr(mr) + addr, 4, dirty_log_mask); r = MEMTX_OK;
Signature · 1 line
2.42.0
Re: [RFC PATCH 2/3] tcg: add a ll/sc protection facility
include/exec/ram_addr.h static inline bool cpu_physical_memory_is_clean(ram_addr_t addr) · line 254
Quoted 6 lines · Nicholas Piggin
include/exec/ram_addr.h +6
-0+ bool llsc_prot = +#ifdef TARGET_HAS_LLSC_PROT +cpu_physical_memory_get_dirty_flag (addr,DIRTY_MEMORY_LLSC_PROT ); +#else + false; +#endif
We're trying to get rid of all target-specific adjustments to TCG. We are not keen to introduce another.
Just drop the ifdefs.
include/exec/ram_addr.h uint64_t cpu_physical_memory_set_dirty_lebitmap(unsigned long *bitmap, · line 382
Quoted 5 lines
include/exec/ram_addr.h +1
-0@@ -355,6 +379,8 @@ uint64_t cpu_physical_memory_set_dirty_lebitmap(unsigned long *bitmap,unsigned long hpratio =qemu_real_host_page_size () /TARGET_PAGE_SIZE ;unsigned long page =BIT_WORD (start >>TARGET_PAGE_BITS ); +assert (0 );
Left over debugging?
Quoted 5 lines
include/exec/ram_addr.h +1
-0+/* start address is aligned at the start of a word? */ if ((((page *BITS_PER_LONG ) <<TARGET_PAGE_BITS ) == start) && (hpratio ==1 )) {
include/exec/ram_addr.h uint64_t cpu_physical_memory_set_dirty_lebitmap(unsigned long *bitmap, · line 430
Quoted 9 lines
include/exec/ram_addr.h +6
-0@@ -396,6 +422,12 @@ uint64_t cpu_physical_memory_set_dirty_lebitmap(unsigned long *bitmap,if (tcg_enabled ()) {qatomic_or (&blocks[DIRTY_MEMORY_CODE ][idx][offset], temp); +#ifdef TARGET_HAS_LLSC_PROT +/* XXX? */ +qatomic_or (&blocks[DIRTY_MEMORY_LLSC_PROT ][idx][offset], + temp); +#endif +assert (0 );
Again.
include/hw/core/cpu.h struct CPUState { · line 493
Quoted 7 lines
include/hw/core/cpu.h +3
-0+++ b/include/hw/core/cpu.h@@ -489,6 +489,11 @@ struct CPUState {uint64_t random_seed;sigjmp_buf jmp_env; +int llsc_prot_block_size; +bool llsc_prot_active;
Is active identical with block_size != 0.
include/hw/core/cpu.h struct CPUState { · line 494
Quoted 1 line
include/hw/core/cpu.h +1
-0+bool llsc_resolving;
I'm not following the logic around resolving and locks...
r~
RFC PATCH 3/3 target/ppc: Implement reservation protection for larx/stcx
In reply to Nicholas PigginUse the generic llsc protection feature to implement real reservation protection for larx/stcx.
This is more complicated and quite a bit slower than the cmpxchg pseudo-reservation, so it's questionable whether it should be merged or ever made the default.
It could possibly be sped up more by tuning heuristics for managing the dirty bitmap -- being a bit more lazy about that could reduce the heavyweight bitmap cleaning and dirtying operations.
Not sure if there are other better approaches to this. One thing I have tried to implement the reservation-granule (i.e., stcx. to succeed for an address that differs from the one that established the reservation) is to first fail the stcx. if it detects an address mismatch, but then set a flag to say try the mismatched mode next time. Next larx encountered will load and save memory contents for the entire reservation granule, then stcx. verifies the granule. This works to some degree with better performance on code that doesn't behave this way, but it still misses things, not only ABA but also stores that modify values not subject to the stcx. on the first pass in case that stcx. address *does* match larx. So I consider that even more of a hack and not really suitable for upstream.
At the very least, this seems to have flushed out another bug in the cpu memory dirty bitmap code, since it hammers it much harder than typical users and simple test cases can be constructed that make failures obvious (lost updates, lost mutual exclusion, etc). so it hasn't been all for nothing even if it is a bad design :)
--- target/ppc/cpu-param.h | 4 ++ target/ppc/helper.h | 2 + target/ppc/cpu_init.c | 4 ++ target/ppc/mem_helper.c | 132 ++++++++++++++++++++++++++++++++++++++++ target/ppc/translate.c | 128 ++++++++------------------------------ 5 files changed, 168 insertions(+), 102 deletions(-)
target/ppc/cpu-param.h +4 -0
@@ -8,6 +8,10 @@#ifndef PPC_CPU_PARAM_H #define PPC_CPU_PARAM_H +#ifndef TARGET_HAS_LLSC_PROT /* XXX: hack */ +#define TARGET_HAS_LLSC_PROT 1 +#endif +#ifdef TARGET_PPC64 # define TARGET_LONG_BITS 64/*
target/ppc/helper.h +2 -0
@@ -818,4 +818,6 @@ DEF_HELPER_4(DSCLI, void, env, fprp, fprp, i32) DEF_HELPER_4(DSCLIQ, void, env, fprp, fprp, i32) DEF_HELPER_1(tbegin, void, env) +DEF_HELPER_4(larx, void, env, tl, tl, tl) +DEF_HELPER_4(stcx, void, env, tl, tl, tl)DEF_HELPER_FLAGS_1 (fixup_thrm,TCG_CALL_NO_RWG , void, env)
target/ppc/cpu_init.c +4 -0
@@ -6831,6 +6831,10 @@ static void ppc_cpu_realize(DeviceState *dev, Error **errp) goto unrealize; }init_ppc_proc (cpu); +if (tcg_enabled ()) { + cs->llsc_prot_block_size = env->dcache_line_size; +printf ("Reservation granule size %d\n" , cs->llsc_prot_block_size); + }ppc_gdb_init (cs, pcc);qemu_init_vcpu (cs);
target/ppc/mem_helper.c +132 -0
146 lines not on this page · raw message
target/ppc/translate.c +26 -102
190 lines not on this page · raw message
Signature · 1 line
2.42.0
Re: [RFC PATCH 3/3] target/ppc: Implement reservation protection for larx/stcx
target/ppc/mem_helper.c void helper_tbegin(CPUPPCState *env) · line 562
Quoted 8 lines · Nicholas Piggin
target/ppc/mem_helper.c +8
-0+ env->access_type =ACCESS_RES ; + host =probe_access (env, addr, size,MMU_DATA_LOAD , mmu_idx, raddr); +if (host) { +cpu_set_llsc_prot (cs,qemu_ram_addr_from_host_nofail (host)); + }else { +/* XXX: fault? */ +g_assert_not_reached (); + }
probe_access will not return a host address for lots of reasons, including watchpoints, plugins, etc.
Quoted 18 lines
target/ppc/mem_helper.c +18
-0+ +if (unlikely (size ==16 )) { +Int128 val16; + val16 =cpu_ld16_mmu (env, addr, +make_memop_idx (DEF_MEMOP (env,MO_128 |MO_ALIGN ), mmu_idx), + raddr); + env->gpr[reg] =int128_gethi (val16); + env->gpr[reg +1 ] =int128_getlo (val16); +return ; + } + +switch (size) { +case 1 : + val =ldub_p (host); +break ; +case 2 : + val =FIELD_EX64 (env->msr,MSR ,LE ) ?lduw_le_p (host) :lduw_be_p (host); +break ;
target/ppc/mem_helper.c void helper_tbegin(CPUPPCState *env) · line 590
Quoted 10 lines
target/ppc/mem_helper.c +10
-0+case 4 : + val =FIELD_EX64 (env->msr,MSR ,LE ) ?ldl_le_p (host) :ldl_be_p (host); +break ; +case 8 : + val =FIELD_EX64 (env->msr,MSR ,LE ) ?ldq_le_p (host) :ldq_be_p (host); +break ; +default : +g_assert_not_reached (); + } + env->gpr[reg] = val;
Passing in size and performing a switch on it is not the best organization.
You should use multiple helper functions with a common subroutine to handle the llsc setup. You should pass in the whole MemOpIdx.
Quoted 1 line
+#define
MEMOP_GET_SIZE(x)(1 << ((x) &MO_SIZE))
This is memop_size().
r~