Skip to content

Commit

Permalink
runtime: fix formula for computing number of padding bytes
Browse files Browse the repository at this point in the history
In order to prevent false sharing of cache lines, structs are
padded with some number of bytes. These bytes are unused, serving
only to make the size of the struct a multiple of the size of the
cache line.

The current calculation of how much to pad is an overestimation,
when the struct size is already a multiple of the cache line size
without padding. For these cases, no padding is necessary, and
the size of the inner pad field should be 0. The bug is that the
pad field is sized to a whole 'nother cache line, wasting space.

Here is the current formula that can never return 0:
cpu.CacheLinePadSize - unsafe.Sizeof(myStruct{})%cpu.CacheLinePadSize

This change simply mods that calculation by cpu.CacheLinePadSize,
so that 0 will be returned instead of cpu.CacheLinePadSize.

Change-Id: I26a2b287171bf47a3b9121873b2722f728381b5e
Reviewed-on: https://go-review.googlesource.com/c/go/+/414214
Reviewed-by: Keith Randall <[email protected]>
Run-TryBot: Michael Pratt <[email protected]>
Auto-Submit: Michael Pratt <[email protected]>
Reviewed-by: Keith Randall <[email protected]>
Reviewed-by: Joedian Reid <[email protected]>
TryBot-Result: Gopher Robot <[email protected]>
  • Loading branch information
ludi317 authored and gopherbot committed Aug 19, 2022
1 parent dee9adc commit f15761b
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/runtime/mheap.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ type mheap struct {
// central is indexed by spanClass.
central [numSpanClasses]struct {
mcentral mcentral
pad [cpu.CacheLinePadSize - unsafe.Sizeof(mcentral{})%cpu.CacheLinePadSize]byte
pad [(cpu.CacheLinePadSize - unsafe.Sizeof(mcentral{})%cpu.CacheLinePadSize) % cpu.CacheLinePadSize]byte
}

spanalloc fixalloc // allocator for span*
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ const (
// There is a free list for each order.
var stackpool [_NumStackOrders]struct {
item stackpoolItem
_ [cpu.CacheLinePadSize - unsafe.Sizeof(stackpoolItem{})%cpu.CacheLinePadSize]byte
_ [(cpu.CacheLinePadSize - unsafe.Sizeof(stackpoolItem{})%cpu.CacheLinePadSize) % cpu.CacheLinePadSize]byte
}

type stackpoolItem struct {
Expand Down

0 comments on commit f15761b

Please sign in to comment.