Skip to content

Commit

Permalink
internal/runtime/atomic: add Xchg8 for amd64
Browse files Browse the repository at this point in the history
For #68578

Change-Id: Idecfdbb793f46560dd69287af9170c07cf4ee973
Reviewed-on: https://go-review.googlesource.com/c/go/+/606900
Reviewed-by: Keith Randall <[email protected]>
Reviewed-by: Mauri de Souza Meneguzzo <[email protected]>
Auto-Submit: Rhys Hiltner <[email protected]>
LUCI-TryBot-Result: Go LUCI <[email protected]>
Reviewed-by: Keith Randall <[email protected]>
Reviewed-by: Michael Knyszek <[email protected]>
  • Loading branch information
rhysh authored and gopherbot committed Oct 2, 2024
1 parent 03103a5 commit 841bb62
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/internal/runtime/atomic/atomic_amd64.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ func Xadd64(ptr *uint64, delta int64) uint64
//go:noescape
func Xadduintptr(ptr *uintptr, delta uintptr) uintptr

//go:noescape
func Xchg8(ptr *uint8, new uint8) uint8

//go:noescape
func Xchg(ptr *uint32, new uint32) uint32

Expand Down
12 changes: 12 additions & 0 deletions src/internal/runtime/atomic/atomic_amd64.s
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,18 @@ TEXT ·Xaddint64(SB), NOSPLIT, $0-24
TEXT ·Xadduintptr(SB), NOSPLIT, $0-24
JMP ·Xadd64(SB)

// uint8 Xchg(ptr *uint8, new uint8)
// Atomically:
// old := *ptr;
// *ptr = new;
// return old;
TEXT ·Xchg8(SB), NOSPLIT, $0-17
MOVQ ptr+0(FP), BX
MOVB new+8(FP), AX
XCHGB AX, 0(BX)
MOVB AX, ret+16(FP)
RET

// uint32 Xchg(ptr *uint32, new uint32)
// Atomically:
// old := *ptr;
Expand Down
39 changes: 39 additions & 0 deletions src/internal/runtime/atomic/xchg8_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build amd64

package atomic_test

import (
"internal/runtime/atomic"
"testing"
)

func TestXchg8(t *testing.T) {
var a [16]uint8
for i := range a {
next := uint8(i + 50)
a[i] = next
}
b := a

// Compare behavior against non-atomic implementation. Expect the operation
// to work at any byte offset and to not clobber neighboring values.
for i := range a {
next := uint8(i + 100)
pa := atomic.Xchg8(&a[i], next)
pb := b[i]
b[i] = next
if pa != pb {
t.Errorf("atomic.Xchg8(a[%d]); %d != %d", i, pa, pb)
}
if a != b {
t.Errorf("after atomic.Xchg8(a[%d]); %d != %d", i, a, b)
}
if t.Failed() {
break
}
}
}

0 comments on commit 841bb62

Please sign in to comment.