cpuid

package module
v2.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 22, 2021 License: MIT Imports: 6 Imported by: 152

README

cpuid

Package cpuid provides information about the CPU running the current program.

CPU features are detected on startup, and kept for fast access through the life of the application. Currently x86 / x64 (AMD64/i386) and ARM (ARM64) is supported, and no external C (cgo) code is used, which should make the library very easy to use.

You can access the CPU information by accessing the shared CPU variable of the cpuid library.

Package home: https://github.com/klauspost/cpuid

PkgGoDev Build Status

installing

go get -u github.com/klauspost/cpuid/v2 using modules.

Drop v2 for others.

example

package main

import (
	"fmt"
	"strings"

	. "github.com/klauspost/cpuid/v2"
)

func main() {
	// Print basic CPU information:
	fmt.Println("Name:", CPU.BrandName)
	fmt.Println("PhysicalCores:", CPU.PhysicalCores)
	fmt.Println("ThreadsPerCore:", CPU.ThreadsPerCore)
	fmt.Println("LogicalCores:", CPU.LogicalCores)
	fmt.Println("Family", CPU.Family, "Model:", CPU.Model, "Vendor ID:", CPU.VendorID)
	fmt.Println("Features:", fmt.Sprintf(strings.Join(CPU.FeatureSet(), ",")))
	fmt.Println("Cacheline bytes:", CPU.CacheLine)
	fmt.Println("L1 Data Cache:", CPU.Cache.L1D, "bytes")
	fmt.Println("L1 Instruction Cache:", CPU.Cache.L1D, "bytes")
	fmt.Println("L2 Cache:", CPU.Cache.L2, "bytes")
	fmt.Println("L3 Cache:", CPU.Cache.L3, "bytes")
	fmt.Println("Frequency", CPU.Hz, "hz")

	// Test if we have these specific features:
	if CPU.Supports(SSE, SSE2) {
		fmt.Println("We have Streaming SIMD 2 Extensions")
	}
}

Sample output:

>go run main.go
Name: AMD Ryzen 9 3950X 16-Core Processor
PhysicalCores: 16
ThreadsPerCore: 2
LogicalCores: 32
Family 23 Model: 113 Vendor ID: AMD
Features: ADX,AESNI,AVX,AVX2,BMI1,BMI2,CLMUL,CMOV,CX16,F16C,FMA3,HTT,HYPERVISOR,LZCNT,MMX,MMXEXT,NX,POPCNT,RDRAND,RDSEED,RDTSCP,SHA,SSE,SSE2,SSE3,SSE4,SSE42,SSE4A,SSSE3
Cacheline bytes: 64
L1 Data Cache: 32768 bytes
L1 Instruction Cache: 32768 bytes
L2 Cache: 524288 bytes
L3 Cache: 16777216 bytes
Frequency 0 hz
We have Streaming SIMD 2 Extensions

usage

The cpuid.CPU provides access to CPU features. Use cpuid.CPU.Supports() to check for CPU features. A faster cpuid.CPU.Has() is provided which will usually be inlined by the gc compiler.

Note that for some cpu/os combinations some features will not be detected. amd64 has rather good support and should work reliably on all platforms.

Note that hypervisors may not pass through all CPU features.

arm64 feature detection

Not all operating systems provide ARM features directly and there is no safe way to do so for the rest.

Currently arm64/linux and arm64/freebsd should be quite reliable. arm64/darwin adds features expected from the M1 processor, but a lot remains undetected.

A DetectARM() can be used if you are able to control your deployment, it will detect CPU features, but may crash if the OS doesn't intercept the calls. A -cpu.arm flag for detecting unsafe ARM features can be added. See below.

Note that currently only features are detected on ARM, no additional information is currently available.

flags

It is possible to add flags that affects cpu detection.

For this the Flags() command is provided.

This must be called before flag.Parse() AND after the flags have been parsed Detect() must be called.

This means that any detection used in init() functions will not contain these flags.

Example:

package main

import (
	"flag"
	"fmt"
	"strings"

	"github.com/klauspost/cpuid/v2"
)

func main() {
	cpuid.Flags()
	flag.Parse()
	cpuid.Detect()

	// Test if we have these specific features:
	if cpuid.CPU.Supports(cpuid.SSE, cpuid.SSE2) {
		fmt.Println("We have Streaming SIMD 2 Extensions")
	}
}

license

This code is published under an MIT license. See LICENSE file for more information.

Documentation

Overview

Package cpuid provides information about the CPU running the current program.

CPU features are detected on startup, and kept for fast access through the life of the application. Currently x86 / x64 (AMD64) as well as arm64 is supported.

You can access the CPU information by accessing the shared CPU variable of the cpuid library.

Package home: https://github.com/klauspost/cpuid

Example
// Print basic CPU information:
fmt.Println("Name:", CPU.BrandName)
fmt.Println("PhysicalCores:", CPU.PhysicalCores)
fmt.Println("ThreadsPerCore:", CPU.ThreadsPerCore)
fmt.Println("LogicalCores:", CPU.LogicalCores)
fmt.Println("Family", CPU.Family, "Model:", CPU.Model)
fmt.Println("Features:", CPU.FeatureSet())
fmt.Println("Cacheline bytes:", CPU.CacheLine)
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Detect

func Detect()

Detect will re-detect current CPU info. This will replace the content of the exported CPU variable.

Unless you expect the CPU to change while you are running your program you should not need to call this function. If you call this, you must ensure that no other goroutine is accessing the exported CPU variable.

func DetectARM

func DetectARM()

DetectARM will detect ARM64 features. This is NOT done automatically since it can potentially crash if the OS does not handle the command. If in the future this can be done safely this function may not do anything.

func Flags

func Flags()

Flags will enable flags. This must be called *before* flag.Parse AND Detect must be called after the flags have been parsed. Note that this means that any detection used in init() functions will not contain these flags.

Types

type CPUInfo

type CPUInfo struct {
	BrandName    string // Brand name reported by the CPU
	VendorID     Vendor // Comparable CPU vendor ID
	VendorString string // Raw vendor string.

	PhysicalCores  int   // Number of physical processor cores in your CPU. Will be 0 if undetectable.
	ThreadsPerCore int   // Number of threads per physical core. Will be 1 if undetectable.
	LogicalCores   int   // Number of physical cores times threads that can run on each core through the use of hyperthreading. Will be 0 if undetectable.
	Family         int   // CPU family number
	Model          int   // CPU model number
	CacheLine      int   // Cache line size in bytes. Will be 0 if undetectable.
	Hz             int64 // Clock speed, if known, 0 otherwise
	Cache          struct {
		L1I int // L1 Instruction Cache (per core or shared). Will be -1 if undetected
		L1D int // L1 Data Cache (per core or shared). Will be -1 if undetected
		L2  int // L2 Cache (per core or shared). Will be -1 if undetected
		L3  int // L3 Cache (per core, per ccx or shared). Will be -1 if undetected
	}
	SGX SGXSupport
	// contains filtered or unexported fields
}

CPUInfo contains information about the detected system CPU.

var CPU CPUInfo

CPU contains information about the CPU as detected on startup, or when Detect last was called.

Use this as the primary entry point to you data.

func (*CPUInfo) Disable

func (c *CPUInfo) Disable(ids ...FeatureID) bool

Disable will disable one or several features.

func (*CPUInfo) Enable

func (c *CPUInfo) Enable(ids ...FeatureID) bool

Enable will disable one or several features even if they were undetected. This is of course not recommended for obvious reasons.

func (CPUInfo) FeatureSet

func (c CPUInfo) FeatureSet() []string

func (CPUInfo) Has added in v2.0.3

func (c CPUInfo) Has(id FeatureID) bool

Has allows for checking a single feature. Should be inlined by the compiler.

func (CPUInfo) Ia32TscAux

func (c CPUInfo) Ia32TscAux() uint32

Ia32TscAux returns the IA32_TSC_AUX part of the RDTSCP. This variable is OS dependent, but on Linux contains information about the current cpu/core the code is running on. If the RDTSCP instruction isn't supported on the CPU, the value 0 is returned.

Example

This example will calculate the chip/core number on Linux Linux encodes numa id (<<12) and core id (8bit) into TSC_AUX.

ecx := CPU.Ia32TscAux()
if ecx == 0 {
	fmt.Println("Unknown CPU ID")
	return
}
chip := (ecx & 0xFFF000) >> 12
core := ecx & 0xFFF
fmt.Println("Chip, Core:", chip, core)
Output:

func (CPUInfo) IsVendor

func (c CPUInfo) IsVendor(v Vendor) bool

IsVendor returns true if vendor is recognized as Intel

func (CPUInfo) LogicalCPU

func (c CPUInfo) LogicalCPU() int

LogicalCPU will return the Logical CPU the code is currently executing on. This is likely to change when the OS re-schedules the running thread to another CPU. If the current core cannot be detected, -1 will be returned.

func (CPUInfo) RTCounter

func (c CPUInfo) RTCounter() uint64

RTCounter returns the 64-bit time-stamp counter Uses the RDTSCP instruction. The value 0 is returned if the CPU does not support the instruction.

func (CPUInfo) Supports

func (c CPUInfo) Supports(ids ...FeatureID) bool

Supports returns whether the CPU supports all of the requested features.

func (CPUInfo) VM

func (c CPUInfo) VM() bool

VM Will return true if the cpu id indicates we are in a virtual machine.

type FeatureID

type FeatureID int

FeatureID is the ID of a specific cpu feature.

const (
	// Keep index -1 as unknown
	UNKNOWN = -1

	// Add features
	ADX                FeatureID = iota // Intel ADX (Multi-Precision Add-Carry Instruction Extensions)
	AESNI                               // Advanced Encryption Standard New Instructions
	AMD3DNOW                            // AMD 3DNOW
	AMD3DNOWEXT                         // AMD 3DNowExt
	AMXBF16                             // Tile computational operations on BFLOAT16 numbers
	AMXINT8                             // Tile computational operations on 8-bit integers
	AMXTILE                             // Tile architecture
	AVX                                 // AVX functions
	AVX2                                // AVX2 functions
	AVX512BF16                          // AVX-512 BFLOAT16 Instructions
	AVX512BITALG                        // AVX-512 Bit Algorithms
	AVX512BW                            // AVX-512 Byte and Word Instructions
	AVX512CD                            // AVX-512 Conflict Detection Instructions
	AVX512DQ                            // AVX-512 Doubleword and Quadword Instructions
	AVX512ER                            // AVX-512 Exponential and Reciprocal Instructions
	AVX512F                             // AVX-512 Foundation
	AVX512IFMA                          // AVX-512 Integer Fused Multiply-Add Instructions
	AVX512PF                            // AVX-512 Prefetch Instructions
	AVX512VBMI                          // AVX-512 Vector Bit Manipulation Instructions
	AVX512VBMI2                         // AVX-512 Vector Bit Manipulation Instructions, Version 2
	AVX512VL                            // AVX-512 Vector Length Extensions
	AVX512VNNI                          // AVX-512 Vector Neural Network Instructions
	AVX512VP2INTERSECT                  // AVX-512 Intersect for D/Q
	AVX512VPOPCNTDQ                     // AVX-512 Vector Population Count Doubleword and Quadword
	AVXSLOW                             // Indicates the CPU performs 2 128 bit operations instead of one.
	BMI1                                // Bit Manipulation Instruction Set 1
	BMI2                                // Bit Manipulation Instruction Set 2
	CLDEMOTE                            // Cache Line Demote
	CLMUL                               // Carry-less Multiplication
	CMOV                                // i686 CMOV
	CX16                                // CMPXCHG16B Instruction
	ENQCMD                              // Enqueue Command
	ERMS                                // Enhanced REP MOVSB/STOSB
	F16C                                // Half-precision floating-point conversion
	FMA3                                // Intel FMA 3. Does not imply AVX.
	FMA4                                // Bulldozer FMA4 functions
	GFNI                                // Galois Field New Instructions
	HLE                                 // Hardware Lock Elision
	HTT                                 // Hyperthreading (enabled)
	HYPERVISOR                          // This bit has been reserved by Intel & AMD for use by hypervisors
	IBPB                                // Indirect Branch Restricted Speculation (IBRS) and Indirect Branch Predictor Barrier (IBPB)
	IBS                                 // Instruction Based Sampling (AMD)
	IBSBRNTRGT                          // Instruction Based Sampling Feature (AMD)
	IBSFETCHSAM                         // Instruction Based Sampling Feature (AMD)
	IBSFFV                              // Instruction Based Sampling Feature (AMD)
	IBSOPCNT                            // Instruction Based Sampling Feature (AMD)
	IBSOPCNTEXT                         // Instruction Based Sampling Feature (AMD)
	IBSOPSAM                            // Instruction Based Sampling Feature (AMD)
	IBSRDWROPCNT                        // Instruction Based Sampling Feature (AMD)
	IBSRIPINVALIDCHK                    // Instruction Based Sampling Feature (AMD)
	LZCNT                               // LZCNT instruction
	MMX                                 // standard MMX
	MMXEXT                              // SSE integer functions or AMD MMX ext
	MOVDIR64B                           // Move 64 Bytes as Direct Store
	MOVDIRI                             // Move Doubleword as Direct Store
	MPX                                 // Intel MPX (Memory Protection Extensions)
	NX                                  // NX (No-Execute) bit
	POPCNT                              // POPCNT instruction
	RDRAND                              // RDRAND instruction is available
	RDSEED                              // RDSEED instruction is available
	RDTSCP                              // RDTSCP Instruction
	RTM                                 // Restricted Transactional Memory
	SERIALIZE                           // Serialize Instruction Execution
	SGX                                 // Software Guard Extensions
	SGXLC                               // Software Guard Extensions Launch Control
	SHA                                 // Intel SHA Extensions
	SSE                                 // SSE functions
	SSE2                                // P4 SSE functions
	SSE3                                // Prescott SSE3 functions
	SSE4                                // Penryn SSE4.1 functions
	SSE42                               // Nehalem SSE4.2 functions
	SSE4A                               // AMD Barcelona microarchitecture SSE4a instructions
	SSSE3                               // Conroe SSSE3 functions
	STIBP                               // Single Thread Indirect Branch Predictors
	TBM                                 // AMD Trailing Bit Manipulation
	TSXLDTRK                            // Intel TSX Suspend Load Address Tracking
	VAES                                // Vector AES
	VMX                                 // Virtual Machine Extensions
	VPCLMULQDQ                          // Carry-Less Multiplication Quadword
	WAITPKG                             // TPAUSE, UMONITOR, UMWAIT
	WBNOINVD                            // Write Back and Do Not Invalidate Cache
	XOP                                 // Bulldozer XOP functions

	// ARM features:
	AESARM   // AES instructions
	ARMCPUID // Some CPU ID registers readable at user-level
	ASIMD    // Advanced SIMD
	ASIMDDP  // SIMD Dot Product
	ASIMDHP  // Advanced SIMD half-precision floating point
	ASIMDRDM // Rounding Double Multiply Accumulate/Subtract (SQRDMLAH/SQRDMLSH)
	ATOMICS  // Large System Extensions (LSE)
	CRC32    // CRC32/CRC32C instructions
	DCPOP    // Data cache clean to Point of Persistence (DC CVAP)
	EVTSTRM  // Generic timer
	FCMA     // Floatin point complex number addition and multiplication
	FP       // Single-precision and double-precision floating point
	FPHP     // Half-precision floating point
	GPA      // Generic Pointer Authentication
	JSCVT    // Javascript-style double->int convert (FJCVTZS)
	LRCPC    // Weaker release consistency (LDAPR, etc)
	PMULL    // Polynomial Multiply instructions (PMULL/PMULL2)
	SHA1     // SHA-1 instructions (SHA1C, etc)
	SHA2     // SHA-2 instructions (SHA256H, etc)
	SHA3     // SHA-3 instructions (EOR3, RAXI, XAR, BCAX)
	SHA512   // SHA512 instructions
	SM3      // SM3 instructions
	SM4      // SM4 instructions
	SVE      // Scalable Vector Extension

)

func ParseFeature

func ParseFeature(s string) FeatureID

ParseFeature will parse the string and return the ID of the matching feature. Will return UNKNOWN if not found.

func (FeatureID) String

func (i FeatureID) String() string

type SGXEPCSection

type SGXEPCSection struct {
	BaseAddress uint64
	EPCSize     uint64
}

type SGXSupport

type SGXSupport struct {
	Available           bool
	LaunchControl       bool
	SGX1Supported       bool
	SGX2Supported       bool
	MaxEnclaveSizeNot64 int64
	MaxEnclaveSize64    int64
	EPCSections         []SGXEPCSection
}

type Vendor

type Vendor int

Vendor is a representation of a CPU vendor.

const (
	VendorUnknown Vendor = iota
	Intel
	AMD
	VIA
	Transmeta
	NSC
	KVM  // Kernel-based Virtual Machine
	MSVM // Microsoft Hyper-V or Windows Virtual PC
	VMware
	XenHVM
	Bhyve
	Hygon
	SiS
	RDC

	Ampere
	ARM
	Broadcom
	Cavium
	DEC
	Fujitsu
	Infineon
	Motorola
	NVIDIA
	AMCC
	Qualcomm
	Marvell
)

func (Vendor) String

func (i Vendor) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL