4 ms·
What I would do is have dispatch_once NOP out the call instruction that called it as one of its first operations. Inside, an atomic exchange + compare on the pr
by userbinator 12y ago
What I would do is have dispatch_once NOP out the call instruction that called it as one of its first operations. Inside, an atomic exchange + compare on the predicate to stop any other threads that slipped past the call, and that's all there is to it. CPUs are optimised for executing NOPs since they're so commonly used for alignment, so the only thing this costs is fetch bandwidth. Here's a quick x86 implementation PoC off the top of my head:
; assumptions:
; * this function is called via a 2-byte call instruction
; * cdecl register allocation
; * [esp] : return addr
; * [esp+4] : predicate ptr
; * [esp+8] : ptr to func() to be called once
dispatch_once:
pop edx ; edx = block
pop ecx ; ecx = pred ptr
mov eax, 1
xchg eax, [ecx]
test eax, eax ; was a different thread here before us?
jnz dispatch_done
mov eax, [esp] ; return address
mov [eax-2], word 0x9090 ; overwrite the call
jmp edx ; execute the block +return
dispatch_done:
ret
As the saying goes, "The fastest way to do something is to not do it at all." In this case, the compare + function call can be completely eliminated after the first time.
- MichaelGG 12y agoThis is used in JITs, too - is there a reason why the author wouldn't cover it? Other than being "cheating" so to speak? I suppose environments (like game consoles) where you cannot write to executable pages?
- mikeash 12y agoEven ignoring W^X problems, how do you ensure that the reads and writes of the data are properly ordered with respect to the reads and writes of the code?
- cfallin 12y agox86 self-modifying code semantics are actually quite strong relative to most other ISAs -- a store to the currently executing code-stream logically takes effect immediately, so you could in theory modify the instruction immediately following the store, and be OK. In other words, instruction memory ordering is exactly as strong as data memory ordering. (That said, self-modifying code is usually a bad idea when performance is concerned, because the CPU must conservatively flush the pipeline when it detects that any store might have modified the raw bytes of any instruction in the pipeline, and might have to conservatively throw away other state -- probably more expensive than whatever other atomic operations we were playing tricks to avoid.)
- k4st 12y agoMy understanding is that the semantics are not as strong as they appear, although I have no experience with other architectures, so what is said to be the case and what is the case might still be relatively easier to use than other ISAs. The optimization and software developer manuals suggest that self- and cross-modifying code must always be used with a synchronizing instruction (e.g. CPUID). Also, this LKML discussion (https://lkml.org/lkml/2009/3/2/194 https://lkml.org/lkml/2009/3/2/194) suggests that only modifying the first byte of an instruction with an int3 is safe, whereas modifying the other parts of an instruction can result in spurious faults when that instruction is next executed, unless the correct algorithm is followed.
- cfallin 12y agoFair point -- for cross-modifying code (one core's stores affect another core's fetch), this may be true. For self-modifying code, though (same core doing the store and fetch), the semantics are strong. See the Intel Developer Manual 3A [1], section 11.6: "[the processor] check[s] whether a write to a code segment may modify an instruction that has been prefetched for execution. If the write affects a prefetched instruction, the prefetch queue is invalidated." In other words, stores are checked against instructions already in the pipe. Also, I was involved in an out-of-order x86 design and know for certain that we cared about getting SMC right. No serializing instructions necessary :-) [1] http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-vol-3a-part-1-manual.pdf http://www.intel.com/content/dam/www/public/us/en/documents/...
- k4st 12y agoGood to know! I'm in a funny place in my research project where I recently found out about the limitations of cross-modifying code. I had previously assumed that everything would work out for the best (doing hot-code patching in a DBT system that runs in kernel space), and didn't (appear to) face issues on the last version of my DBT system. For the next version, I'd like to play things safer. However, I suppose I could transparently recover from GP faults, as this is something I already do for other scenarios. Do you have any suggestions (besides stop_machine-like IPIs for synchronizing all CPUs) on how to go about dynamic code patching in a JIT-based DBT-system? In my case, it's a priori unclear on whether or not the instruction being patched has been prefetched by another core.
- Marat_Dukhan 12y agoOne day the call instruction will cross cache line boundary, the two cache lines will propogate to other cores' instruction caches with a delay, some thread will try to execute partially changed call instruction, and some senior programmer will get mad trying to debug it, a la "look, I swap these two lines and it gets to work" (b/c the call instruction does not cross cache line anymore)
- userbinator 12y agoI realise this approach has its assumptions and limitations, I was just trying to show how far you can take things if you're really after absolute performance. NOP'ing out the call instruction is the subtle part, but if you can ensure that all your calls to this function are 2-byte calls and aligned, then everything works out great. Direct calls on x86 are 5 bytes so NOP'ing them out atomically is a bit more difficult; two ways of doing it I can think of: [1] use an 8-byte load/store, or [2] ensure the displacement part is aligned, and overwrite it with the address of a single RET instruction so the call immediately returns. The first way could be slower but effectively NOPs out the whole call, the second is simpler and faster to do but leaves the useless call/ret (while still eliminating the compare/branch.) Incidentally, doing this is much easier on RISCs like MIPS and ARM thanks to fixed-length instructions (that automatically align), and they tend to have much shorter pipelines too so the flush penalties are lower.
- eridius 12y agoThat requires the ability to write to the executable page, which is definitely not allowed on iOS, and not necessarily allowed elsewhere either. It also makes the assumption that a given call to `dispatch_once()` will only ever be called with the same predicate. If it selects among a set of predicates (or is given a predicate by whatever function called it), then NOPing it out would completely break the application.