Source file src/internal/cpu/cpu.go

     1  // Copyright 2017 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 cpu implements processor feature detection
     6  // used by the Go standard library.
     7  package cpu
     8  
     9  import _ "unsafe" // for linkname
    10  
    11  // CacheLinePad is used to pad structs to avoid false sharing.
    12  type CacheLinePad struct{ _ [CacheLinePadSize]byte }
    13  
    14  // CacheLineSize is the CPU's assumed cache line size.
    15  // There is currently no runtime detection of the real cache line size
    16  // so we use the constant per GOARCH CacheLinePadSize as an approximation.
    17  var CacheLineSize uintptr = CacheLinePadSize
    18  
    19  // The booleans in X86 contain the correspondingly named cpuid feature bit.
    20  // HasAVX and HasAVX2 are only set if the OS does support XMM and YMM registers
    21  // in addition to the cpuid feature bit being set.
    22  // The struct is padded to avoid false sharing.
    23  var X86 struct {
    24  	_                   CacheLinePad
    25  	HasAES              bool
    26  	HasADX              bool
    27  	HasAVX              bool
    28  	HasAVXVNNI          bool
    29  	HasAVX2             bool
    30  	HasAVX512           bool // Virtual feature: F+CD+BW+DQ+VL
    31  	HasAVX512F          bool
    32  	HasAVX512CD         bool
    33  	HasAVX512BW         bool
    34  	HasAVX512DQ         bool
    35  	HasAVX512VL         bool
    36  	HasAVX512GFNI       bool
    37  	HasAVX512VAES       bool
    38  	HasAVX512VNNI       bool
    39  	HasAVX512VBMI       bool
    40  	HasAVX512VBMI2      bool
    41  	HasAVX512BITALG     bool
    42  	HasAVX512VPOPCNTDQ  bool
    43  	HasAVX512VPCLMULQDQ bool
    44  	HasBMI1             bool
    45  	HasBMI2             bool
    46  	HasERMS             bool
    47  	HasFSRM             bool
    48  	HasFMA              bool
    49  	HasGFNI             bool
    50  	HasOSXSAVE          bool
    51  	HasPCLMULQDQ        bool
    52  	HasPOPCNT           bool
    53  	HasRDTSCP           bool
    54  	HasSHA              bool
    55  	HasSSE3             bool
    56  	HasSSSE3            bool
    57  	HasSSE41            bool
    58  	HasSSE42            bool
    59  	HasVAES             bool
    60  	HasVPCLMULQDQ       bool
    61  	HasXGETBV1          bool // Supports XGETBV with ECX=1 (XINUSE bitmap)
    62  	_                   CacheLinePad
    63  }
    64  
    65  // The booleans in ARM contain the correspondingly named cpu feature bit.
    66  // The struct is padded to avoid false sharing.
    67  var ARM struct {
    68  	_            CacheLinePad
    69  	HasVFPv4     bool
    70  	HasIDIVA     bool
    71  	HasV7Atomics bool
    72  	_            CacheLinePad
    73  }
    74  
    75  // The booleans in ARM64 contain the correspondingly named cpu feature bit.
    76  // The struct is padded to avoid false sharing.
    77  var ARM64 struct {
    78  	_          CacheLinePad
    79  	HasAES     bool
    80  	HasPMULL   bool
    81  	HasSHA1    bool
    82  	HasSHA2    bool
    83  	HasSHA512  bool
    84  	HasSHA3    bool
    85  	HasCRC32   bool
    86  	HasATOMICS bool
    87  	HasCPUID   bool
    88  	HasDIT     bool
    89  	HasSB      bool
    90  	IsNeoverse bool
    91  	HasSVE     bool
    92  	HasSVE2    bool
    93  	_          CacheLinePad
    94  }
    95  
    96  // The booleans in Loong64 contain the correspondingly named cpu feature bit.
    97  // The struct is padded to avoid false sharing.
    98  var Loong64 struct {
    99  	_              CacheLinePad
   100  	HasLSX         bool // support 128-bit vector extension
   101  	HasLASX        bool // support 256-bit vector extension
   102  	HasCRC32       bool // support CRC instruction
   103  	HasLAMCAS      bool // support AMCAS[_DB].{B/H/W/D}
   104  	HasLAM_BH      bool // support AM{SWAP/ADD}[_DB].{B/H} instruction
   105  	HasLLACQ_SCREL bool // support LLACQ.{W/D}, SCREL.{W/D} instruction
   106  	HasSCQ         bool // support SC.Q instruction
   107  	HasDBAR_HINTS  bool // supports finer-grained DBAR hints
   108  	_              CacheLinePad
   109  }
   110  
   111  var MIPS64X struct {
   112  	_      CacheLinePad
   113  	HasMSA bool // MIPS SIMD architecture
   114  	_      CacheLinePad
   115  }
   116  
   117  // For ppc64(le), it is safe to check only for ISA level starting on ISA v3.00,
   118  // since there are no optional categories. There are some exceptions that also
   119  // require kernel support to work (darn, scv), so there are feature bits for
   120  // those as well. The minimum processor requirement is POWER8 (ISA 2.07).
   121  // The struct is padded to avoid false sharing.
   122  var PPC64 struct {
   123  	_         CacheLinePad
   124  	HasDARN   bool // Hardware random number generator (requires kernel enablement)
   125  	HasSCV    bool // Syscall vectored (requires kernel enablement)
   126  	IsPOWER8  bool // ISA v2.07 (POWER8)
   127  	IsPOWER9  bool // ISA v3.00 (POWER9)
   128  	IsPOWER10 bool // ISA v3.1  (POWER10)
   129  	_         CacheLinePad
   130  }
   131  
   132  var S390X struct {
   133  	_         CacheLinePad
   134  	HasZARCH  bool // z architecture mode is active [mandatory]
   135  	HasSTFLE  bool // store facility list extended [mandatory]
   136  	HasLDISP  bool // long (20-bit) displacements [mandatory]
   137  	HasEIMM   bool // 32-bit immediates [mandatory]
   138  	HasDFP    bool // decimal floating point
   139  	HasETF3EH bool // ETF-3 enhanced
   140  	HasMSA    bool // message security assist (CPACF)
   141  	HasAES    bool // KM-AES{128,192,256} functions
   142  	HasAESCBC bool // KMC-AES{128,192,256} functions
   143  	HasAESCTR bool // KMCTR-AES{128,192,256} functions
   144  	HasAESGCM bool // KMA-GCM-AES{128,192,256} functions
   145  	HasGHASH  bool // KIMD-GHASH function
   146  	HasSHA1   bool // K{I,L}MD-SHA-1 functions
   147  	HasSHA256 bool // K{I,L}MD-SHA-256 functions
   148  	HasSHA512 bool // K{I,L}MD-SHA-512 functions
   149  	HasSHA3   bool // K{I,L}MD-SHA3-{224,256,384,512} and K{I,L}MD-SHAKE-{128,256} functions
   150  	HasVX     bool // vector facility. Note: the runtime sets this when it processes auxv records.
   151  	HasVXE    bool // vector-enhancements facility 1
   152  	HasKDSA   bool // elliptic curve functions
   153  	HasECDSA  bool // NIST curves
   154  	HasEDDSA  bool // Edwards curves
   155  	_         CacheLinePad
   156  }
   157  
   158  // RISCV64 contains the supported CPU features and performance characteristics for riscv64
   159  // platforms. The booleans in RISCV64, with the exception of HasFastMisaligned, indicate
   160  // the presence of RISC-V extensions.
   161  // The struct is padded to avoid false sharing.
   162  var RISCV64 struct {
   163  	_                 CacheLinePad
   164  	HasFastMisaligned bool // Fast misaligned accesses
   165  	HasV              bool // Vector extension compatible with RVV 1.0
   166  	HasZbb            bool // Basic bit-manipulation extension
   167  	HasZbc            bool // Carryless multiplication extension
   168  	HasZvbb           bool // Vector Basic Bit-manipulation
   169  	HasZvbc           bool // Vector Carryless Multiplication
   170  	HasZvkg           bool // Vector GCM/GMAC
   171  	HasZvkned         bool // NIST Suite: Vector AES Block Cipher
   172  	HasZvknha         bool // NIST Suite: Vector SHA-2 Secure Hash
   173  	HasZvknhb         bool // NIST Suite: Vector SHA-2 Secure Hash
   174  	HasZvksed         bool // ShangMi Suite: SM4 Block Cipher
   175  	HasZvksh          bool // ShangMi Suite: SM3 Secure Hash
   176  	HasZvkt           bool // Vector Data-Independent Execution Latency
   177  	VLENB             uint // Vector register length in bytes, 0 if undetected
   178  	_                 CacheLinePad
   179  }
   180  
   181  // CPU feature variables are accessed by assembly code in various packages.
   182  //go:linkname X86
   183  //go:linkname ARM
   184  //go:linkname ARM64
   185  //go:linkname Loong64
   186  //go:linkname MIPS64X
   187  //go:linkname PPC64
   188  //go:linkname S390X
   189  //go:linkname RISCV64
   190  
   191  // doDerived, if non-nil, is called after processing GODEBUG to set "derived"
   192  // feature flags.
   193  var doDerived func()
   194  
   195  // Initialize examines the processor and sets the relevant variables above.
   196  // This is called by the runtime package early in program initialization,
   197  // before normal init functions are run. env is set by runtime if the OS supports
   198  // cpu feature options in GODEBUG.
   199  func Initialize(env string) {
   200  	doinit()
   201  	processOptions(env)
   202  	if doDerived != nil {
   203  		doDerived()
   204  	}
   205  }
   206  
   207  // options contains the cpu debug options that can be used in GODEBUG.
   208  // Options are arch dependent and are added by the arch specific doinit functions.
   209  // Features that are mandatory for the specific GOARCH should not be added to options
   210  // (e.g. SSE2 on amd64).
   211  var options []option
   212  
   213  // Option names should be lower case. e.g. avx instead of AVX.
   214  type option struct {
   215  	Name      string
   216  	Feature   *bool
   217  	Specified bool // whether feature value was specified in GODEBUG
   218  	Enable    bool // whether feature should be enabled
   219  }
   220  
   221  // processOptions enables or disables CPU feature values based on the parsed env string.
   222  // The env string is expected to be of the form cpu.feature1=value1,cpu.feature2=value2...
   223  // where feature names is one of the architecture specific list stored in the
   224  // cpu packages options variable and values are either 'on' or 'off'.
   225  // If env contains cpu.all=off then all cpu features referenced through the options
   226  // variable are disabled. Other feature names and values result in warning messages.
   227  func processOptions(env string) {
   228  field:
   229  	for env != "" {
   230  		field := ""
   231  		i := indexByte(env, ',')
   232  		if i < 0 {
   233  			field, env = env, ""
   234  		} else {
   235  			field, env = env[:i], env[i+1:]
   236  		}
   237  		if len(field) < 4 || field[:4] != "cpu." {
   238  			continue
   239  		}
   240  		i = indexByte(field, '=')
   241  		if i < 0 {
   242  			print("GODEBUG: no value specified for \"", field, "\"\n")
   243  			continue
   244  		}
   245  		key, value := field[4:i], field[i+1:] // e.g. "SSE2", "on"
   246  
   247  		var enable bool
   248  		switch value {
   249  		case "on":
   250  			enable = true
   251  		case "off":
   252  			enable = false
   253  		default:
   254  			print("GODEBUG: value \"", value, "\" not supported for cpu option \"", key, "\"\n")
   255  			continue field
   256  		}
   257  
   258  		if key == "all" {
   259  			for i := range options {
   260  				options[i].Specified = true
   261  				options[i].Enable = enable
   262  			}
   263  			continue field
   264  		}
   265  
   266  		for i := range options {
   267  			if options[i].Name == key {
   268  				options[i].Specified = true
   269  				options[i].Enable = enable
   270  				continue field
   271  			}
   272  		}
   273  
   274  		print("GODEBUG: unknown cpu feature \"", key, "\"\n")
   275  	}
   276  
   277  	for _, o := range options {
   278  		if !o.Specified {
   279  			continue
   280  		}
   281  
   282  		if o.Enable && !*o.Feature {
   283  			print("GODEBUG: can not enable \"", o.Name, "\", missing CPU support\n")
   284  			continue
   285  		}
   286  
   287  		*o.Feature = o.Enable
   288  	}
   289  }
   290  
   291  // indexByte returns the index of the first instance of c in s,
   292  // or -1 if c is not present in s.
   293  // indexByte is semantically the same as [strings.IndexByte].
   294  // We copy this function because "internal/cpu" should not have external dependencies.
   295  func indexByte(s string, c byte) int {
   296  	for i := 0; i < len(s); i++ {
   297  		if s[i] == c {
   298  			return i
   299  		}
   300  	}
   301  	return -1
   302  }
   303  

View as plain text