...

Package cpuid

import "github.com/klauspost/cpuid/v2"
Overview
Index
Examples
Subdirectories

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

Code:

// 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)

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.

type CPUInfo

CPUInfo contains information about the detected system CPU.

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
    Stepping       int   // CPU stepping info
    CacheLine      int   // Cache line size in bytes. Will be 0 if undetectable.
    Hz             int64 // Clock speed, if known, 0 otherwise. Will attempt to contain base clock speed.
    BoostFreq      int64 // Max 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
    AVX10Level uint8
    // contains filtered or unexported fields
}

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.

var CPU CPUInfo

func (CPUInfo) AnyOf

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

AnyOf returns whether the CPU supports one or more of the requested features.

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

FeatureSet returns all available features as strings.

func (*CPUInfo) Has

func (c *CPUInfo) Has(id FeatureID) bool

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

func (*CPUInfo) HasAll

func (c *CPUInfo) HasAll(f Features) bool

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.

Code:

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)

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.

func (CPUInfo) X64Level

func (c CPUInfo) X64Level() int

X64Level returns the microarchitecture level detected on the CPU. If features are lacking or non x64 mode, 0 is returned. See https://en.wikipedia.org/wiki/X86-64#Microarchitecture_levels

type FeatureID

FeatureID is the ID of a specific cpu feature.

type FeatureID int
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
    AMXFP16                             // Tile computational operations on FP16 numbers
    AMXINT8                             // Tile computational operations on 8-bit integers
    AMXTILE                             // Tile architecture
    APX_F                               // Intel APX
    AVX                                 // AVX functions
    AVX10                               // If set the Intel AVX10 Converged Vector ISA is supported
    AVX10_128                           // If set indicates that AVX10 128-bit vector support is present
    AVX10_256                           // If set indicates that AVX10 256-bit vector support is present
    AVX10_512                           // If set indicates that AVX10 512-bit vector support is present
    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
    AVX512FP16                          // AVX-512 FP16 Instructions
    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
    AVXIFMA                             // AVX-IFMA instructions
    AVXNECONVERT                        // AVX-NE-CONVERT instructions
    AVXSLOW                             // Indicates the CPU performs 2 128 bit operations instead of one
    AVXVNNI                             // AVX (VEX encoded) VNNI neural network instructions
    AVXVNNIINT8                         // AVX-VNNI-INT8 instructions
    BHI_CTRL                            // Branch History Injection and Intra-mode Branch Target Injection / CVE-2022-0001, CVE-2022-0002 / INTEL-SA-00598
    BMI1                                // Bit Manipulation Instruction Set 1
    BMI2                                // Bit Manipulation Instruction Set 2
    CETIBT                              // Intel CET Indirect Branch Tracking
    CETSS                               // Intel CET Shadow Stack
    CLDEMOTE                            // Cache Line Demote
    CLMUL                               // Carry-less Multiplication
    CLZERO                              // CLZERO instruction supported
    CMOV                                // i686 CMOV
    CMPCCXADD                           // CMPCCXADD instructions
    CMPSB_SCADBS_SHORT                  // Fast short CMPSB and SCASB
    CMPXCHG8                            // CMPXCHG8 instruction
    CPBOOST                             // Core Performance Boost
    CPPC                                // AMD: Collaborative Processor Performance Control
    CX16                                // CMPXCHG16B Instruction
    EFER_LMSLE_UNS                      // AMD: =Core::X86::Msr::EFER[LMSLE] is not supported, and MBZ
    ENQCMD                              // Enqueue Command
    ERMS                                // Enhanced REP MOVSB/STOSB
    F16C                                // Half-precision floating-point conversion
    FLUSH_L1D                           // Flush L1D cache
    FMA3                                // Intel FMA 3. Does not imply AVX.
    FMA4                                // Bulldozer FMA4 functions
    FP128                               // AMD: When set, the internal FP/SIMD execution datapath is no more than 128-bits wide
    FP256                               // AMD: When set, the internal FP/SIMD execution datapath is no more than 256-bits wide
    FSRM                                // Fast Short Rep Mov
    FXSR                                // FXSAVE, FXRESTOR instructions, CR4 bit 9
    FXSROPT                             // FXSAVE/FXRSTOR optimizations
    GFNI                                // Galois Field New Instructions. May require other features (AVX, AVX512VL,AVX512F) based on usage.
    HLE                                 // Hardware Lock Elision
    HRESET                              // If set CPU supports history reset and the IA32_HRESET_ENABLE MSR
    HTT                                 // Hyperthreading (enabled)
    HWA                                 // Hardware assert supported. Indicates support for MSRC001_10
    HYBRID_CPU                          // This part has CPUs of more than one type.
    HYPERVISOR                          // This bit has been reserved by Intel & AMD for use by hypervisors
    IA32_ARCH_CAP                       // IA32_ARCH_CAPABILITIES MSR (Intel)
    IA32_CORE_CAP                       // IA32_CORE_CAPABILITIES MSR
    IBPB                                // Indirect Branch Restricted Speculation (IBRS) and Indirect Branch Predictor Barrier (IBPB)
    IBRS                                // AMD: Indirect Branch Restricted Speculation
    IBRS_PREFERRED                      // AMD: IBRS is preferred over software solution
    IBRS_PROVIDES_SMP                   // AMD: IBRS provides Same Mode Protection
    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)
    IBS_FETCH_CTLX                      // AMD: IBS fetch control extended MSR supported
    IBS_OPDATA4                         // AMD: IBS op data 4 MSR supported
    IBS_OPFUSE                          // AMD: Indicates support for IbsOpFuse
    IBS_PREVENTHOST                     // Disallowing IBS use by the host supported
    IBS_ZEN4                            // AMD: Fetch and Op IBS support IBS extensions added with Zen4
    IDPRED_CTRL                         // IPRED_DIS
    INT_WBINVD                          // WBINVD/WBNOINVD are interruptible.
    INVLPGB                             // NVLPGB and TLBSYNC instruction supported
    KEYLOCKER                           // Key locker
    KEYLOCKERW                          // Key locker wide
    LAHF                                // LAHF/SAHF in long mode
    LAM                                 // If set, CPU supports Linear Address Masking
    LBRVIRT                             // LBR virtualization
    LZCNT                               // LZCNT instruction
    MCAOVERFLOW                         // MCA overflow recovery support.
    MCDT_NO                             // Processor do not exhibit MXCSR Configuration Dependent Timing behavior and do not need to mitigate it.
    MCOMMIT                             // MCOMMIT instruction supported
    MD_CLEAR                            // VERW clears CPU buffers
    MMX                                 // standard MMX
    MMXEXT                              // SSE integer functions or AMD MMX ext
    MOVBE                               // MOVBE instruction (big-endian)
    MOVDIR64B                           // Move 64 Bytes as Direct Store
    MOVDIRI                             // Move Doubleword as Direct Store
    MOVSB_ZL                            // Fast Zero-Length MOVSB
    MOVU                                // AMD: MOVU SSE instructions are more efficient and should be preferred to SSE	MOVL/MOVH. MOVUPS is more efficient than MOVLPS/MOVHPS. MOVUPD is more efficient than MOVLPD/MOVHPD
    MPX                                 // Intel MPX (Memory Protection Extensions)
    MSRIRC                              // Instruction Retired Counter MSR available
    MSRLIST                             // Read/Write List of Model Specific Registers
    MSR_PAGEFLUSH                       // Page Flush MSR available
    NRIPS                               // Indicates support for NRIP save on VMEXIT
    NX                                  // NX (No-Execute) bit
    OSXSAVE                             // XSAVE enabled by OS
    PCONFIG                             // PCONFIG for Intel Multi-Key Total Memory Encryption
    POPCNT                              // POPCNT instruction
    PPIN                                // AMD: Protected Processor Inventory Number support. Indicates that Protected Processor Inventory Number (PPIN) capability can be enabled
    PREFETCHI                           // PREFETCHIT0/1 instructions
    PSFD                                // Predictive Store Forward Disable
    RDPRU                               // RDPRU instruction supported
    RDRAND                              // RDRAND instruction is available
    RDSEED                              // RDSEED instruction is available
    RDTSCP                              // RDTSCP Instruction
    RRSBA_CTRL                          // Restricted RSB Alternate
    RTM                                 // Restricted Transactional Memory
    RTM_ALWAYS_ABORT                    // Indicates that the loaded microcode is forcing RTM abort.
    SERIALIZE                           // Serialize Instruction Execution
    SEV                                 // AMD Secure Encrypted Virtualization supported
    SEV_64BIT                           // AMD SEV guest execution only allowed from a 64-bit host
    SEV_ALTERNATIVE                     // AMD SEV Alternate Injection supported
    SEV_DEBUGSWAP                       // Full debug state swap supported for SEV-ES guests
    SEV_ES                              // AMD SEV Encrypted State supported
    SEV_RESTRICTED                      // AMD SEV Restricted Injection supported
    SEV_SNP                             // AMD SEV Secure Nested Paging supported
    SGX                                 // Software Guard Extensions
    SGXLC                               // Software Guard Extensions Launch Control
    SHA                                 // Intel SHA Extensions
    SME                                 // AMD Secure Memory Encryption supported
    SME_COHERENT                        // AMD Hardware cache coherency across encryption domains enforced
    SPEC_CTRL_SSBD                      // Speculative Store Bypass Disable
    SRBDS_CTRL                          // SRBDS mitigation MSR available
    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
    STIBP_ALWAYSON                      // AMD: Single Thread Indirect Branch Prediction Mode has Enhanced Performance and may be left Always On
    STOSB_SHORT                         // Fast short STOSB
    SUCCOR                              // Software uncorrectable error containment and recovery capability.
    SVM                                 // AMD Secure Virtual Machine
    SVMDA                               // Indicates support for the SVM decode assists.
    SVMFBASID                           // SVM, Indicates that TLB flush events, including CR3 writes and CR4.PGE toggles, flush only the current ASID's TLB entries. Also indicates support for the extended VMCBTLB_Control
    SVML                                // AMD SVM lock. Indicates support for SVM-Lock.
    SVMNP                               // AMD SVM nested paging
    SVMPF                               // SVM pause intercept filter. Indicates support for the pause intercept filter
    SVMPFT                              // SVM PAUSE filter threshold. Indicates support for the PAUSE filter cycle count threshold
    SYSCALL                             // System-Call Extension (SCE): SYSCALL and SYSRET instructions.
    SYSEE                               // SYSENTER and SYSEXIT instructions
    TBM                                 // AMD Trailing Bit Manipulation
    TDX_GUEST                           // Intel Trust Domain Extensions Guest
    TLB_FLUSH_NESTED                    // AMD: Flushing includes all the nested translations for guest translations
    TME                                 // Intel Total Memory Encryption. The following MSRs are supported: IA32_TME_CAPABILITY, IA32_TME_ACTIVATE, IA32_TME_EXCLUDE_MASK, and IA32_TME_EXCLUDE_BASE.
    TOPEXT                              // TopologyExtensions: topology extensions support. Indicates support for CPUID Fn8000_001D_EAX_x[N:0]-CPUID Fn8000_001E_EDX.
    TSCRATEMSR                          // MSR based TSC rate control. Indicates support for MSR TSC ratio MSRC000_0104
    TSXLDTRK                            // Intel TSX Suspend Load Address Tracking
    VAES                                // Vector AES. AVX(512) versions requires additional checks.
    VMCBCLEAN                           // VMCB clean bits. Indicates support for VMCB clean bits.
    VMPL                                // AMD VM Permission Levels supported
    VMSA_REGPROT                        // AMD VMSA Register Protection supported
    VMX                                 // Virtual Machine Extensions
    VPCLMULQDQ                          // Carry-Less Multiplication Quadword. Requires AVX for 3 register versions.
    VTE                                 // AMD Virtual Transparent Encryption supported
    WAITPKG                             // TPAUSE, UMONITOR, UMWAIT
    WBNOINVD                            // Write Back and Do Not Invalidate Cache
    WRMSRNS                             // Non-Serializing Write to Model Specific Register
    X87                                 // FPU
    XGETBV1                             // Supports XGETBV with ECX = 1
    XOP                                 // Bulldozer XOP functions
    XSAVE                               // XSAVE, XRESTOR, XSETBV, XGETBV
    XSAVEC                              // Supports XSAVEC and the compacted form of XRSTOR.
    XSAVEOPT                            // XSAVEOPT available
    XSAVES                              // Supports XSAVES/XRSTORS and IA32_XSS

    // 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 Features

Features contains several features combined for a fast check using CpuInfo.HasAll

type Features *flagSet

func CombineFeatures

func CombineFeatures(ids ...FeatureID) Features

CombineFeatures allows to combine several features for a close to constant time lookup.

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

Vendor is a representation of a CPU vendor.

type Vendor int
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

Subdirectories

Name Synopsis
..
cmd
cpuid Package cpuid provides information about the CPU running the current program.