{"id":102790,"date":"2019-08-19T07:00:00","date_gmt":"2019-08-19T14:00:00","guid":{"rendered":"http:\/\/devblogs.microsoft.com\/oldnewthing\/?p=102790"},"modified":"2019-09-13T21:48:38","modified_gmt":"2019-09-14T04:48:38","slug":"20190819-00","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/oldnewthing\/20190819-00\/?p=102790","title":{"rendered":"The SuperH-3, part 11: Atomic operations"},"content":{"rendered":"<p>The SH-3 has <a href=\"https:\/\/devblogs.microsoft.com\/oldnewthing\/20190813-00\/?p=102780\"> a very limited number of read-modify-write operations<\/a>. To recap:<\/p>\n<pre>    AND.B #imm, @(r0, GBR)  ; @(r0 + gbr) &amp;= 8-bit immediate\r\n    OR.B  #imm, @(r0, GBR)  ; @(r0 + gbr) |= 8-bit immediate\r\n    XOR.B #imm, @(r0, GBR)  ; @(r0 + gbr) ^= 8-bit immediate\r\n    TAS.B @Rn               ; T = (@Rn == 0), @Rn |= 0x80\r\n<\/pre>\n<p>These instructions are &#8220;atomic&#8221; in the sense that they occur within a single instruction and are hence non-interruptible. Technically, only the last one is truly atomic in the sense that the processor holds the data bus locked for the duration of the instruction.<\/p>\n<p>Let&#8217;s not quibble about such details. Let&#8217;s just say we&#8217;re looking for non-interruptible instructions.<\/p>\n<p>The SH-3 does not support symmetric multiprocessing, so we don&#8217;t have to worry about competing accesses from other main processors (although there may be competing accesses from coprocessors or hardware devices). But how are we going to build atomic increment, decrement, and exchange out of these guys?<\/p>\n<p>Let&#8217;s be honest. We can&#8217;t.<\/p>\n<p>We&#8217;ll have to fake it.<\/p>\n<p>Windows CE takes a different approach from <a href=\"https:\/\/blogs.msdn.microsoft.com\/oldnewthing\/20040506-00\/?p=39463\"> how Windows 98 created atomic operations on a processor that didn&#8217;t support them<\/a>.<\/p>\n<p>On Windows CE, the kernel is in cahoots with the implementations of the interlocked operations. If it discovers that it interrupted a special uninterruptible sequence, it resets the program counter back to the start of the uninterruptible sequence before allowing user mode to resume.\u00b9 In this way, the kernel manufactures multi-instruction uninterruptible sequences.<\/p>\n<p>These sequences have to be carefully written so that they are restartable. This means that they cannot mutate any input parameters, and there are no memory updates until the final instruction in the sequence.<\/p>\n<p>For example, we could try to implement our fake <code>Interlocked\u00adIncrement<\/code> like this:<\/p>\n<pre>; on entry:\r\n;   r4 = address to increment\r\n; on exit:\r\n;   r0 = incremented value\r\n\r\nInterlockedIncrement:\r\n    mov.l   @r4, r0     ; load current value    ; (1)\r\n    add     #1, r0      ; increment it          ; (2)\r\n    mov.l   r0, @r4     ; store updated value   ; (3)\r\n    rts                 ; return                ; (4)\r\n<\/pre>\n<p>We load the current value from memory, add 1, store it back, and return. If this sequence is interrupt at any point, the kernel moves the program counter back to the first instruction and restarts the entire operation.<\/p>\n<p>Let&#8217;s walk through the possible interrupts.<\/p>\n<ul>\n<li>If interrupted prior to the first instruction, then moving the program counter back to the first instruction has no effect because that&#8217;s where it already was. So no problems there.<\/li>\n<li>If interrupted prior to the second instruction, then we will perform the <code>mov.l @r4, r0<\/code> a second time. Since we haven&#8217;t changed <var>r4<\/var>, this will read the desired memory location. It&#8217;s a redundant read, but at least it&#8217;s not harmful.<\/li>\n<li>If interrupted prior to the third instruction, then we will reload and re-increment the existing value. Again, since we haven&#8217;t changed <var>r4<\/var>, this will read the correct location.<\/li>\n<li>If interrupted prior to the fourth instruction, then we&#8217;re in trouble. We have already written the updated value back to memory, and restarting the operation will increment it a second time! <b>This code is broken.<\/b><\/li>\n<\/ul>\n<p>Aha, but we forgot about the branch delay slot of the <code>rts<\/code> instruction, and in fact it&#8217;s the branch delay slot that provides our escape hatch: Move the final store <i>into the branch delay slot<\/i>.<\/p>\n<pre>; on entry:\r\n;   r4 = address to increment\r\n; on exit:\r\n;   r0 = incremented value\r\n\r\nInterlockedIncrement:\r\n    mov.l   @r4, r0     ; load current value    ; (1)\r\n    add     #1, r0      ; increment it          ; (2)\r\n    rts                 ; return                ; (3)\r\n    mov.l   r0, @r4     ; store updated value   ; (4)\r\n<\/pre>\n<p>Okay, let&#8217;s run our analysis again.<\/p>\n<ul>\n<li>If interrupted prior to the first instruction, our analysis from above is still correct.<\/li>\n<li>If interrupted prior to the second instruction, our analysis from above is still correct.<\/li>\n<li>If interrupted prior to the third instruction, our analysis from above is still correct.<\/li>\n<li>An interrupt between the third and fourth instruction is not possible because the processor disables interrupts between a delayed branch instruction and its delay slot. But if an exception occurred (say, because the memory was copy-on-write), we can safely restart the operation because we haven&#8217;t modified <var>r4<\/var> or the value in memory at <var>r4<\/var>.\u00b2<\/li>\n<li>If interrupted after the fourth instruction, then the program counter isn&#8217;t in our special code region, so the kernel won&#8217;t restart the sequence.<\/li>\n<\/ul>\n<p>The branch delay slot saved us!<\/p>\n<p>You never thought you&#8217;d see the day when you&#8217;d be thankful for a branch delay slot.<\/p>\n<p>The kernel puts these special uninterruptible sequences in a contiguous region of memory. Let&#8217;s say that it starts each special uninterruptible sequence on a 16-byte boundary. This means that the &#8220;special uninterruptible sequence detector&#8221; can go something like this:<\/p>\n<pre>    mov.l   @(usermode_pc), r0          ; see where we're returning to\r\n    mov.l   #start_of_sequences, r1     ; the start of our special sequences\r\n    mov     #length_of_sequences, r2    ; the size in bytes\r\n    sub     r1, r0\r\n    cmp\/hs  r0, r2                      ; is it in the magic region?\r\n    bf      fixme                       ; Y: then go fix it\r\nreturn_to_user_mode:\r\n    ... continue as usual ...\r\n\r\nfixme:\r\n    mov     #-15, r2                    ; mask out the bottom 4 bits\r\n    and     r2, r0                      ; to go back to start of special sequence\r\n    add     r1, r0                      ; convert from offset back to address\r\n    bra     return_to_user_mode\r\n    mov.l   r0, @(usermode_pc)          ; update user mode program counter\r\n<\/pre>\n<p>This is not actually how it goes, but it gives you the basic idea. In reality, the special uninterruptible sequences start on 8-byte boundaries, in order to pack them more tightly. Sequences that are longer than 4 instructions need to be arranged so that every 8 bytes is a valid restart point. I just used 16-byte sequences to make the explanation simpler.<\/p>\n<p>For example, <code>Interlocked\u00adCompare\u00adExchange<\/code> really went like this:<\/p>\n<pre>; on entry:\r\n;   r4 = address of value to test\r\n;   r5 = replacement value (if current value matches expected value)\r\n;   r6 = expected value\r\n; on exit:\r\n;   r0 = previous value\r\n\r\nInterlockedCompareExchange:\r\n    mov.l   @r4, r0     ; load current value\r\n    cmp\/eq  r0, r6      ; is it the expected value?\r\n    bf      nope        ; Nope, just return current value\r\n    mov.l   r5, @r4     ; Store the replacement value\r\nnope:\r\n    rts\r\n    nop\r\n<\/pre>\n<p>There is a second restart point after four instructions, at the <code>rts<\/code>, and it&#8217;s okay to restart there because the operation is complete. All we&#8217;re doing is returning to our caller.<\/p>\n<p>This trick for creating restartable multi-instruction sequences was not unique to the SH-3. Windows CE employed it to synthesize pseudo-atomic operations for other processors, too.<\/p>\n<p>One curious side effect of this design for restartable multi-instruction sequences is that you can&#8217;t debug them! If you try to single-step through these multi-instruction sequences, you&#8217;ll get stuck on the first instruction: The breakpoint will fire, and the kernel will reset the program counter back to the first instruction.<\/p>\n<p><a href=\"https:\/\/devblogs.microsoft.com\/oldnewthing\/20190820-00\/?p=102792\"> Next time, we&#8217;ll look at the Windows CE calling convention<\/a>.<\/p>\n<p><b>Bonus chatter<\/b>: The SH-4A processor added load-locked and store-conditional instructions, bringing it in line with other RISC processors.<\/p>\n<pre>    MOVLI.L @Rm,r0          ; Load from @Rm, remember lock\r\n    MOVCO.L r0,@Rn          ; Store to @Rn provided lock is still valid\r\n                            ; T = 1 if store succeeded, 0 if failed\r\n<\/pre>\n<p><b>Bonus chatter 2<\/b>: What about the TEB? Where does Windows keep per-thread information?<\/p>\n<p>Turn out this is easier than it sounds. The SH-3 doesn&#8217;t support symmetric multiprocessing, so there is only one processor, which therefore can be executing only one thread at a time. A pointer to the per-thread information is stored at a fixed location, and that pointer is updated at each thread switch.<\/p>\n<p>\u00b9 <a href=\"http:\/\/discolab.rutgers.edu\/classes\/cs519\/papers\/fast-mutex.pdf\"> Fast Mutual Exclusion for Uniprocessors<\/a>. Brian Bershad, David Redell, and John Ellis, Proceedings of the fifth international conference on Architectural support for programming languages and operating systems, 1992.<\/p>\n<p>\u00b2 Suppose an exception occurs in the delay slot because the memory isn&#8217;t writable, and the exception handler fixes the problem (by making the memory writable on demand). Resuming execution will rewind the instruction pointer back to the start of the sequence because the memory value may have changed as part of handling the exception.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>How do you create an atomic operation when the processor doesn&#8217;t support them?<\/p>\n","protected":false},"author":1069,"featured_media":111744,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[2],"class_list":["post-102790","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldnewthing","tag-history"],"acf":[],"blog_post_summary":"<p>How do you create an atomic operation when the processor doesn&#8217;t support them?<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/102790","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/users\/1069"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/comments?post=102790"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/102790\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media\/111744"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media?parent=102790"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/categories?post=102790"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/tags?post=102790"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}