Source file src/crypto/internal/entropy/scratch/scratch.go
1 // Copyright 2026 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package scratch provides the scratch memory used by the FIPS 140-3 CPU 6 // jitter entropy source. It's outside the module boundary and the certified 7 // entropy source, so we can change how the memory is allocated. 8 package scratch 9 10 import ( 11 "internal/bytealg" 12 "sync" 13 ) 14 15 var shared struct { 16 sync.Mutex 17 buf []byte 18 mapped bool 19 refs int 20 } 21 22 // Acquire returns a buffer of n bytes with unspecified contents, which must be 23 // passed to [Release] when no longer in use. n must be the same for all calls. 24 // 25 // Concurrent callers may get the same buffer, so the contents may change at 26 // any time, and must only be accessed with atomic operations. 27 func Acquire(n int) []byte { 28 shared.Lock() 29 defer shared.Unlock() 30 if shared.refs == 0 { 31 // Get the memory directly from the operating system if possible, so 32 // that it doesn't count towards the garbage collector's heap goal, 33 // and is returned as soon as it's released. 34 if b, err := mmap(n); err == nil { 35 shared.buf = b 36 shared.mapped = true 37 } else { 38 // The contents are never used, so skip zeroing. 39 shared.buf = bytealg.MakeNoZero(n) 40 shared.mapped = false 41 } 42 } 43 if len(shared.buf) != n { 44 panic("scratch: inconsistent buffer size") 45 } 46 shared.refs++ 47 return shared.buf 48 } 49 50 // Release releases a buffer returned by [Acquire]. 51 // The buffer must not be used after it's released. 52 func Release(b []byte) { 53 shared.Lock() 54 defer shared.Unlock() 55 if shared.refs--; shared.refs == 0 { 56 if shared.mapped { 57 munmap(shared.buf) 58 } 59 shared.buf = nil 60 } 61 } 62