CPUID

In the x86 architecture, the CPUID instruction (identified by a CPUID opcode) is a processor supplementary instruction (its name derived from CPU IDentification) allowing software to discover details of the processor. It was introduced by Intel in 1993 with the launch of the Pentium and SL-enhanced 486 processors.[1]

A program can use the CPUID to determine processor type and whether features such as MMX/SSE are implemented.

History

Prior to the general availability of the CPUID instruction, programmers would write esoteric machine code which exploited minor differences in CPU behavior in order to determine the processor make and model.[2][3] With the introduction of the 80386 processor, EDX on reset indicated the revision but this was only readable after reset and there was no standard way for applications to read the value.

Outside the x86 family, developers are mostly still required to use esoteric processes (involving instruction timing or CPU fault triggers) to determine the variations in CPU design that are present.

In the Motorola 680x0 family — that never had a CPUID instruction of any kind — certain specific instructions required elevated privileges. These could be used to tell various CPU family members apart. In the Motorola 68010 the instruction MOVE from SR became privileged. This notable instruction (and state machine) change allowed the 68010 to meet the Popek and Goldberg virtualization requirements. Because the 68000 offered an unprivileged MOVE from SR the 2 different CPUs could be told apart by a CPU error condition being triggered.

While the CPUID instruction is specific to the x86 architecture, other architectures (like ARM) often provide on-chip registers which can be read in prescribed ways to obtain the same sorts of information provided by the x86 CPUID instruction.

Calling CPUID

The CPUID opcode is 0Fh, A2h (as two bytes, or A20Fh as a single word).

In assembly language, the CPUID instruction takes no parameters as CPUID implicitly uses the EAX register to determine the main category of information returned. In Intel's more recent terminology, this is called the CPUID leaf. CPUID should be called with EAX = 0 first, as this will store in the EAX register the highest EAX calling parameter (leaf) that the CPU implements.

To obtain extended function information CPUID should be called with the most significant bit of EAX set. To determine the highest extended function calling parameter, call CPUID with EAX = 80000000h.

CPUID leaves greater than 3 but less than 80000000 are accessible only when the model-specific registers have IA32_MISC_ENABLE.BOOT_NT4 [bit 22] = 0 (which is so by default). As the name suggests, Windows NT 4.0 until SP6 did not boot properly unless this bit was set,[4] but later versions of Windows do not need it, so basic leaves greater than 4 can be assumed visible on current Windows systems. As of July 2014, basic valid leaves go up to 14h, but the information returned by some leaves are not disclosed in publicly available documentation, i.e. they are "reserved".

Some of the more recently added leaves also have sub-leaves, which are selected via the ECX register before calling CPUID.

EAX=0: Highest Function Parameter and Manufacturer ID

This returns the CPU's manufacturer ID string  a twelve-character ASCII string stored in EBX, EDX, ECX (in that order). The highest basic calling parameter (largest value that EAX can be set to before calling CPUID) is returned in EAX.

Here is a list of processors and the highest function implemented.

Highest Function Parameter
ProcessorsBasicExtended
Earlier Intel 486CPUID Not Implemented
Later Intel 486 and Pentium0x01Not Implemented
Pentium Pro, Pentium II and Celeron0x02Not Implemented
Pentium III0x03Not Implemented
Pentium 40x020x8000 0004
Xeon0x020x8000 0004
Pentium M0x020x8000 0004
Pentium 4 with Hyper-Threading0x050x8000 0008
Pentium D (8xx)0x050x8000 0008
Pentium D (9xx)0x060x8000 0008
Core Duo0x0A0x8000 0008
Core 2 Duo0x0A0x8000 0008
Xeon 3000, 5100, 5200, 5300, 5400 (5000 series)0x0A0x8000 0008
Core 2 Duo 8000 series0x0D0x8000 0008
Xeon 5200, 5400 series0x0A0x8000 0008
Atom0x0A0x8000 0008
Nehalem-based processors0x0B0x8000 0008
Ivy Bridge-based processors 0x0D 0x8000 0008
Skylake-based processors (proc base & max freq; Bus ref. freq) 0x16 0x8000 0008
System-On-Chip Vendor Attribute Enumeration Main Leaf 0x17 0x8000 0008

The following are known processor manufacturer ID strings:

The following are ID strings used by open source soft CPU cores:

  • "GenuineAO486"  ao486 CPU[5]
  • "GenuineIntel"  v586 core[6] (this is identical to the Intel ID string)

The following are known ID strings from virtual machines:

For instance, on a GenuineIntel processor values returned in EBX is 0x756e6547, EDX is 0x49656e69 and ECX is 0x6c65746e. The following code is written in GNU Assembler for the x86-64 architecture and displays the vendor ID string as well as the highest calling parameter that the CPU implements.

	.data

s0:	.asciz	"CPUID: %x\n"
s1:	.asciz	"Largest basic function number implemented: %i\n"
s2:	.asciz	"Vendor ID: %.12s\n"

	.text

	.align	32
	.globl	main

main:
	pushq	%rbp
	movq	%rsp,%rbp
	subq	$16,%rsp

	movl	$1,%eax
	cpuid

	movq	$s0,%rdi
	movl	%eax,%esi
	xorl	%eax,%eax
	call	printf

	pushq	%rbx  // -fPIC

	xorl	%eax,%eax
	cpuid

	movl	%ebx,0(%rsp)
	movl	%edx,4(%rsp)
	movl	%ecx,8(%rsp)

	popq	%rbx  // -fPIC

	movq	$s1,%rdi
	movl	%eax,%esi
	xorl	%eax,%eax
	call	printf

	movq	$s2,%rdi
	movq	%rsp,%rsi
	xorl	%eax,%eax
	call	printf

	movq	%rbp,%rsp
	popq	%rbp
//	ret
	movl	$1,%eax
	int	$0x80

EAX=1: Processor Info and Feature Bits

This returns the CPU's stepping, model, and family information in register EAX (also called the signature of a CPU), feature flags in registers EDX and ECX, and additional feature info in register EBX.[7]

Processor Version Information
EAX
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Reserved Extended Family ID Extended Model ID Reserved Processor Type Family ID Model Stepping ID
  • Stepping ID is a product revision number assigned due to fixed errata or other changes.
  • The actual processor model is derived from the Model, Extended Model ID and Family ID fields. If the Family ID field is either 6 or 15, the model is equal to the sum of the Extended Model ID field shifted left by 4 bits and the Model field. Otherwise, the model is equal to the value of the Model field.
  • The actual processor family is derived from the Family ID and Extended Family ID fields. If the Family ID field is equal to 15, the family is equal to the sum of the Extended Family ID and the Family ID fields. Otherwise, the family is equal to value of the Family ID field.
  • The meaning of the Processor Type field is given by the table below.
Processor Type
Type Encoding in Binary
Original OEM Processor 00
Intel Overdrive Processor 01
Dual processor (not applicable to Intel486 processors) 10
Reserved value 11
Additional Information
Bits EBX Valid
7:0 Brand Index
15:8 CLFLUSH line size (Value . 8 = cache line size in bytes) if CLFLUSH feature flag is set.

CPUID.01.EDX.CLFSH [bit 19]= 1

23:16 Maximum number of addressable IDs for logical processors in this physical package;

The nearest power-of-2 integer that is not smaller than this value is the number of unique initial APIC IDs reserved for addressing different logical processors in a physical package.

Former use: Number of logical processors per physical processor; two for the Pentium 4 processor with Hyper-Threading Technology.[8]

if Hyper-threading feature flag is set.

CPUID.01.EDX.HTT [bit 28]= 1

31:24 Local APIC ID: The initial APIC-ID is used to identify the executing logical processor.

It can also be identified via the cpuid 0BH leaf ( CPUID.0Bh.EDX[x2APIC-ID] ).

Pentium 4 and subsequent processors.

The processor info and feature flags are manufacturer specific but usually the Intel values are used by other manufacturers for the sake of compatibility.

Feature Information
BitEDXECX
ShortFeatureShortFeature
0 fpuOnboard x87 FPUsse3Prescott New Instructions-SSE3 (PNI)
1 vmeVirtual 8086 mode extensions (such as VIF, VIP, PIV)pclmulqdqPCLMULQDQ
2 deDebugging extensions (CR4 bit 3)dtes6464-bit debug store (edx bit 21)
3 psePage Size ExtensionmonitorMONITOR and MWAIT instructions (SSE3)
4 tscTime Stamp Counterds-cplCPL qualified debug store
5 msrModel-specific registersvmxVirtual Machine eXtensions
6 paePhysical Address ExtensionsmxSafer Mode Extensions (LaGrande)
7 mceMachine Check ExceptionestEnhanced SpeedStep
8 cx8CMPXCHG8 (compare-and-swap) instructiontm2Thermal Monitor 2
9 apicOnboard Advanced Programmable Interrupt Controllerssse3Supplemental SSE3 instructions
10 (reserved)cnxt-idL1 Context ID
11 sepSYSENTER and SYSEXIT instructionssdbgSilicon Debug interface
12 mtrrMemory Type Range RegistersfmaFused multiply-add (FMA3)
13 pgePage Global Enable bit in CR4cx16CMPXCHG16B instruction
14 mcaMachine check architecturextprCan disable sending task priority messages
15 cmovConditional move and FCMOV instructionspdcmPerfmon & debug capability
16 patPage Attribute Table(reserved)
17 pse-3636-bit page size extensionpcidProcess context identifiers (CR4 bit 17)
18 psnProcessor Serial NumberdcaDirect cache access for DMA writes[9][10]
19 clfshCLFLUSH instruction (SSE2)sse4.1SSE4.1 instructions
20 (reserved)sse4.2SSE4.2 instructions
21 dsDebug store: save trace of executed jumpsx2apicx2APIC
22 acpiOnboard thermal control MSRs for ACPImovbeMOVBE instruction (big-endian)
23 mmxMMX instructionspopcntPOPCNT instruction
24 fxsrFXSAVE, FXRESTOR instructions, CR4 bit 9tsc-deadlineAPIC implements one-shot operation using a TSC deadline value
25 sseSSE instructions (a.k.a. Katmai New Instructions)aesAES instruction set
26 sse2SSE2 instructionsxsaveXSAVE, XRESTOR, XSETBV, XGETBV
27 ssCPU cache implements self-snooposxsaveXSAVE enabled by OS
28 httHyper-threadingavxAdvanced Vector Extensions
29 tmThermal monitor automatically limits temperaturef16cF16C (half-precision) FP feature
30 ia64IA64 processor emulating x86rdrndRDRAND (on-chip random number generator) feature
31 pbePending Break Enable (PBE# pin) wakeup capabilityhypervisorHypervisor present (always zero on physical CPUs)[11][12]

Reserved fields should be masked before using them for processor identification purposes.

EAX=2: Cache and TLB Descriptor information

This returns a list of descriptors indicating cache and TLB capabilities in EAX, EBX, ECX and EDX registers.

EAX=3: Processor Serial Number

This returns the processor's serial number. The processor serial number was introduced on Intel Pentium III, but due to privacy concerns, this feature is no longer implemented on later models (the PSN feature bit is always cleared). Transmeta's Efficeon and Crusoe processors also provide this feature. AMD CPUs however, do not implement this feature in any CPU models.

For Intel Pentium III CPUs, the serial number is returned in the EDX:ECX registers. For Transmeta Efficeon CPUs, it is returned in the EBX:EAX registers. And for Transmeta Crusoe CPUs, it is returned in the EBX register only.

Note that the processor serial number feature must be enabled in the BIOS setting in order to function.

EAX=4 and EAX=Bh: Intel thread/core and cache topology

These two leaves are used for processor topology (thread, core, package) and cache hierarchy enumeration in Intel multi-core (and hyperthreaded) processors.[13] As of 2013 AMD does not use these leaves but has alternate ways of doing the core enumeration.[14]

Unlike most other CPUID leaves, leaf Bh will return different values in EDX depending on which logical processor the CPUID instruction runs; the value returned in EDX is actually the x2APIC id of the logical processor. The x2APIC id space is not continuously mapped to logical processors, however; there can be gaps in the mapping, meaning that some intermediate x2APIC ids don't necessarily correspond to any logical processor. Additional information for mapping the x2APIC ids to cores is provided in the other registers. Although the leaf Bh has sub-leaves (selected by ECX as described further below), the value returned in EDX is only affected by the logical processor on which the instruction is running but not by the subleaf.

The processor(s) topology exposed by leaf Bh is a hierarchical one, but with the strange caveat that the order of (logical) levels in this hierarchy doesn't necessarily correspond the order in the physical hierarchy (SMT/core/package). However, every logical level can be queried as an ECX subleaf (of the Bh leaf) for its correspondence to a "level type", which can be either SMT, core, or "invalid". The level id space starts at 0 and is continuous, meaning that if a level id is invalid, all higher level ids will also be invalid. The level type is returned in bits 15:08 of ECX, while the number of logical processors at the level queried is returned in EBX. Finally, the connection between these levels and x2APIC ids is returned in EAX[4:0] as the number of bits that the x2APIC id must be shifted in order to obtain a unique id at the next level.

As an example, a dual-core Westmere processor capable of hyperthreading (thus having two cores and four threads in total) could have x2APIC ids 0, 1, 4 and 5 for its four logical processors. Leaf Bh (=EAX), subleaf 0 (=ECX) of CPUID could for instance return 100h in ECX, meaning that level 0 describes the SMT (hyperthreading) layer, and return 2 in EBX because there are two logical processors (SMT units) per physical core. The value returned in EAX for this 0-subleaf should be 1 in this case, because shifting the aforementioned x2APIC ids to the right by one bit gives a unique core number (at the next level of the level id hierarchy) and erases the SMT id bit inside each core. A simpler way to interpret this information is that the last bit (bit number 0) of the x2APIC id identifies the SMT/hyperthreading unit inside each core in our example. Advancing to subleaf 1 (by making another call to CPUID with EAX=Bh and ECX=1) could for instance return 201h in ECX, meaning that this is a core-type level, and 4 in EBX because there are 4 logical processors in the package; EAX returned could be any value greater than 3, because it so happens that bit number 2 is used to identify the core in the x2APIC id. Note that bit number 1 of the x2APIC id is not used in this example. However EAX returned at this level could well be 4 (and it happens to be so on a Clarkdale Core i3 5x0) because that also gives a unique id at the package level (=0 obviously) when shifting the x2APIC id by 4 bits. Finally, you may wonder what the EAX=4 leaf can tell us that we didn't find out already. In EAX[31:26] it returns the APIC mask bits reserved for a package; that would be 111b in our example because bits 0 to 2 are used for identifying logical processors inside this package, but bit 1 is also reserved although not used as part of the logical processor identification scheme. In other words, APIC ids 0 to 7 are reserved for the package, even though half of these values don't map to a logical processor.

The cache hierarchy of the processor is explored by looking at the sub-leaves of leaf 4. The APIC ids are also used in this hierarchy to convey information about how the different levels of cache are shared by the SMT units and cores. To continue our example, the L2 cache, which is shared by SMT units of the same core but not between physical cores on the Westmere is indicated by EAX[26:14] being set to 1, while the information that the L3 cache is shared by the whole package is indicated by setting those bits to (at least) 111b. The cache details, including cache type, size, and associativity are communicated via the other registers on leaf 4.

Beware that older versions of the Intel app note 485 contain some misleading information, particularly with respect to identifying and counting cores in a multi-core processor;[15] errors from misinterpreting this information have even been incorporated in the Microsoft sample code for using cpuid, even for the 2013 edition of Visual Studio,[16] and also in the sandpile.org page for CPUID,[17] but the Intel code sample for identifying processor topology[13] has the correct interpretation, and the current Intel Software Developer’s Manual has more clear language. The (open source) cross-platform production code[18] from Wildfire Games also implements the correct interpretation of the Intel documentation.

Topology detection examples involving older (pre-2010) Intel processors that lack x2APIC (thus don't implement the EAX=Bh leaf) are given in a 2010 Intel presentation.[19] Beware that using that older detection method on 2010 and newer Intel processors may overestimate the number of cores and logical processors because the old detection method assumes there are no gaps in the APIC id space, and this assumption is violated by some newer processors (starting with the Core i3 5x0 series), but these newer processors also come with an x2APIC, so their topology can be correctly determined using the EAX=Bh leaf method.

EAX=7, ECX=0: Extended Features

This returns extended feature flags in EBX, ECX, and EDX.

EAX=7 CPUID feature bits
BitEBXECXEDX
ShortFeatureShortFeatureShortFeature
0 fsgsbaseAccess to base of %fs and %gsprefetchwt1PREFETCHWT1 instruction(reserved)
1 IA32_TSC_ADJUSTavx512_vbmiAVX-512 Vector Bit Manipulation Instructions(reserved)
2 sgxSoftware Guard ExtensionsumipUser-mode Instruction Preventionavx512_4vnniwAVX-512 4-register Neural Network Instructions
3 bmi1Bit Manipulation Instruction Set 1pkuMemory Protection Keys for User-mode pagesavx512_4fmapsAVX-512 4-register Multiply Accumulation Single precision
4 hleTSX Hardware Lock ElisionospkePKU enabled by OSfsrmFast Short REP MOVSB
5 avx2Advanced Vector Extensions 2waitpkgTimed pause and user-level monitor/wait(reserved)
6 FDP_EXCPTN_ONLYavx512_vbmi2AVX-512 Vector Bit Manipulation Instructions 2
7 smepSupervisor Mode Execution Preventioncet_ssControl flow enforcement (CET) shadow stack
8 bmi2Bit Manipulation Instruction Set 2gfniGalois Field instructionsavx512_vp2intersectAVX-512 VP2INTERSECT Doubleword and Quadword Instructions
9 ermsEnhanced REP MOVSB/STOSBvaesVector AES instruction set (VEX-256/EVEX)SRBDS_CTRLSpecial Register Buffer Data Sampling Mitigations
10 invpcidINVPCID instructionvpclmulqdqCLMUL instruction set (VEX-256/EVEX)md_clearVERW instruction clears CPU buffers
11 rtmTSX Restricted Transactional Memoryavx512_vnniAVX-512 Vector Neural Network Instructions(reserved)
12 pqmPlatform Quality of Service Monitoringavx512_bitalgAVX-512 BITALG instructions
13 FPU CS and FPU DS deprecated(reserved)tsx_force_abort
14 mpxIntel MPX (Memory Protection Extensions)avx512_vpopcntdqAVX-512 Vector Population Count Double and Quad-wordSERIALIZESerialize instruction execution
15 pqePlatform Quality of Service Enforcement(reserved)Hybrid
16 avx512_fAVX-512 Foundation5-level pagingTSXLDTRKTSX suspend load address tracking
17 avx512_dqAVX-512 Doubleword and Quadword InstructionsmawauThe value of userspace MPX Address-Width Adjust used by the BNDLDX and BNDSTX Intel MPX instructions in 64-bit mode(reserved)
18 rdseedRDSEED instructionpconfigPlatform configuration (Memory Encryption Technologies Instructions)
19 adxIntel ADX (Multi-Precision Add-Carry Instruction Extensions)lbrArchitectural Last Branch Records
20 smapSupervisor Mode Access Preventioncet_ibtControl flow enforcement (CET) indirect branch tracking
21 avx512_ifmaAVX-512 Integer Fused Multiply-Add Instructions(reserved)
22 pcommitPCOMMIT instructionrdpidRead Processor ID and IA32_TSC_AUXamx-bf16Tile computation on bfloat16 numbers
23 clflushoptCLFLUSHOPT instruction(reserved)(reserved)
24 clwbCLWB instruction(reserved)amx-tileTile architecture
25 intel_ptIntel Processor TracecldemoteCache line demoteamx-int8Tile computation on 8-bit integers
26 avx512_pfAVX-512 Prefetch Instructions(reserved)IBRS_IBPB / spec_ctrlSpeculation Control, part of Indirect Branch Control (IBC):
Indirect Branch Restricted Speculation (IBRS) and
Indirect Branch Prediction Barrier (IBPB)[20][21]
27 avx512_erAVX-512 Exponential and Reciprocal InstructionsMOVDIRIstibp Single Thread Indirect Branch Predictor, part of IBC[20]
28 avx512_cdAVX-512 Conflict Detection InstructionsMOVDIR64BL1D_FLUSHIA32_FLUSH_CMD MSR
29 shaIntel SHA extensionsENQCMDEnqueue StoresIA32_ARCH_CAPABILITIESSpeculative Side Channel Mitigations[20]
30 avx512_bwAVX-512 Byte and Word Instructionssgx_lcSGX Launch ConfigurationIA32_CORE_CAPABILITIESSupport for a MSR listing model-specific core capabilities
31 avx512_vlAVX-512 Vector Length ExtensionspksProtection keys for supervisor-mode pagesssbdSpeculative Store Bypass Disable,[20] as mitigation for Speculative Store Bypass (IA32_SPEC_CTRL)

EAX=7, ECX=1: Extended Features

This returns extended feature flags in EAX.


EAX=7 CPUID feature bits
BitEAX
ShortFeature
0 (reserved)
1 (reserved)
2 (reserved)
3 (reserved)
4 (reserved)
5 avx512_bf16AVX-512 BFLOAT16 instructions
6 (reserved)
7 (reserved)
8 (reserved)
9 (reserved)
10 (reserved)
11 (reserved)
12 (reserved)
13 (reserved)
14 (reserved)
15 (reserved)
16 (reserved)
17 (reserved)
18 (reserved)
19 (reserved)
20 (reserved)
21 (reserved)
22 (reserved)
23 (reserved)
24 (reserved)
25 (reserved)
26 (reserved)
27 (reserved)
28 (reserved)
29 (reserved)
30 (reserved)
31 (reserved)

EAX=80000000h: Get Highest Extended Function Implemented

The highest calling parameter is returned in EAX.

EAX=80000001h: Extended Processor Info and Feature Bits

This returns extended feature flags in EDX and ECX.

AMD feature flags are as follows:[22][23]

EAX=80000001h CPUID feature bits
BitEDXECX
ShortFeatureShortFeature
0 fpuOnboard x87 FPUlahf_lmLAHF/SAHF in long mode
1 vmeVirtual mode extensions (VIF)cmp_legacyHyperthreading not valid
2 deDebugging extensions (CR4 bit 3)svmSecure Virtual Machine
3 psePage Size ExtensionextapicExtended APIC space
4 tscTime Stamp Countercr8_legacyCR8 in 32-bit mode
5 msrModel-specific registersabmAdvanced bit manipulation (lzcnt and popcnt)
6 paePhysical Address Extensionsse4aSSE4a
7 mceMachine Check ExceptionmisalignsseMisaligned SSE mode
8 cx8CMPXCHG8 (compare-and-swap) instruction3dnowprefetchPREFETCH and PREFETCHW instructions
9 apicOnboard Advanced Programmable Interrupt ControllerosvwOS Visible Workaround
10 (reserved)ibsInstruction Based Sampling
11 syscallSYSCALL and SYSRET instructionsxopXOP instruction set
12 mtrrMemory Type Range RegistersskinitSKINIT/STGI instructions
13 pgePage Global Enable bit in CR4wdtWatchdog timer
14 mcaMachine check architecture(reserved)
15 cmovConditional move and FCMOV instructionslwpLight Weight Profiling[24]
16 patPage Attribute Tablefma44 operands fused multiply-add
17 pse3636-bit page size extensiontceTranslation Cache Extension
18 (reserved)
19 mpMultiprocessor Capablenodeid_msrNodeID MSR
20 nxNX bit(reserved)
21 (reserved)tbmTrailing Bit Manipulation
22 mmxextExtended MMXtopoextTopology Extensions
23 mmxMMX instructionsperfctr_coreCore performance counter extensions
24 fxsrFXSAVE, FXRSTOR instructions, CR4 bit 9perfctr_nbNB performance counter extensions
25 fxsr_optFXSAVE/FXRSTOR optimizations(reserved)
26 pdpe1gbGibibyte pagesdbxData breakpoint extensions
27 rdtscpRDTSCP instructionperftscPerformance TSC
28 (reserved)pcx_l2iL2I perf counter extensions
29 lmLong mode(reserved)
30 3dnowextExtended 3DNow!(reserved)
31 3dnow3DNow!(reserved)

EAX=80000002h,80000003h,80000004h: Processor Brand String

These return the processor brand string in EAX, EBX, ECX and EDX. CPUID must be issued with each parameter in sequence to get the entire 48-byte null-terminated ASCII processor brand string.[25] It is necessary to check whether the feature is present in the CPU by issuing CPUID with EAX = 80000000h first and checking if the returned value is greater or equal to 80000004h.

#include <cpuid.h>  // GCC-provided
#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint32_t brand[12];

    if (!__get_cpuid_max(0x80000004, NULL)) {
        fprintf(stderr, "Feature not implemented.");
        return 2;
    }

    __get_cpuid(0x80000002, brand+0x0, brand+0x1, brand+0x2, brand+0x3);
    __get_cpuid(0x80000003, brand+0x4, brand+0x5, brand+0x6, brand+0x7);
    __get_cpuid(0x80000004, brand+0x8, brand+0x9, brand+0xa, brand+0xb);
    printf("Brand: %s\n", brand);
}

EAX=80000005h: L1 Cache and TLB Identifiers

This function contains the processor’s L1 cache and TLB characteristics.

EAX=80000006h: Extended L2 Cache Features

Returns details of the L2 cache in ECX, including the line size in bytes (Bits 07 - 00), type of associativity (encoded by a 4 bits field; Bits 15 - 12) and the cache size in KiB (Bits 31 - 16).

#include <cpuid.h>  // GCC-provided
#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint32_t eax, ebx, ecx, edx;
    if (__get_cpuid(0x80000006, &eax, &ebx, &ecx, &edx)) {
        printf("Line size: %d B, Assoc. Type: %d; Cache Size: %d KB.\n", ecx & 0xff, (ecx >> 12) & 0x07, (ecx >> 16) & 0xffff);
        return 0;
    } else {
        fputs(stderr, "CPU does not support 0x80000006");
        return 2;
    }
}

EAX=80000007h: Advanced Power Management Information

This function provides advanced power management feature identifiers. EDX bit 8 indicates support for invariant TSC.

EAX=80000008h: Virtual and Physical address Sizes

Returns largest virtual and physical address sizes in EAX.

  • Bits 07-00: #Physical Address Bits.
  • Bits 15-8: #Linear Address Bits.
  • Bits 31-16: Reserved = 0.

It could be used by the hypervisor in a virtual machine system to report physical/virtual address sizes possible with the virtual CPU.

EBX is used for features:

  • Bit 0: CLZERO, Clear cache line with address in RAX.
  • Bit 4: RDPRU, Read MPERF or APERF from ring 3.
  • Bit 8: MCOMMIT, commit stores to memory. For memory fencing and retrieving ECC errors.
  • Bit 9: WBNOINVD, Write Back and Do Not Invalidate Cache.

ECX provides core count.

  • Bits 07-00: #Physical Cores minus one.
  • Bits 11-8: Reserved = 0.
  • Bits 15-12: #APIC ID Bits. 2 raised to this power would be the physical core count, as long as it's non-zero.
  • Bits 17-16: Performance time-stamp counter size.
  • Bits 31-18: Reserved = 0.

EDX provides information specific to RDPRU (the maximum register identifier allowed) in 31-16. The current number as of Zen 2 is 1 for MPERF and APERF.

EAX=8FFFFFFFh: AMD Easter Egg

Specific to AMD K7 and K8 CPUs, this returns the string "IT'S HAMMER TIME" in EAX, EBX, ECX and EDX.[26]

CPUID usage from high-level languages

Inline assembly

This information is easy to access from other languages as well. For instance, the C code for gcc below prints the first five values, returned by the cpuid:

#include <stdio.h>

/* This works on 32 and 64-bit systems. See [[Inline assembler#In actual compilers]] for hints on reading this code. */
int main()
{
  /* The four registers do not need to be initialized as the processor will write over it. */
  int infotype, a, b, c, d;

  for (infotype = 0; infotype < 5; infotype ++)
  {
    __asm__("cpuid"
            : "=a" (a), "=b" (b), "=c" (c), "=d" (d)   // The output variables. EAX -> a and vice versa.
            : "0" (infotype));                         // Put the infotype into EAX.
    printf ("InfoType %x\nEAX: %x\nEBX: %x\nECX: %x\nEDX: %x\n", infotype, a, b, c, d);
  }

  return 0;
}

In MSVC and Borland/Embarcadero C compilers (bcc32) flavored inline assembly, the clobbering information is implicit in the instructions:

#include <stdio.h>
int main()
{
  unsigned int InfoType = 0;
  unsigned int a, b, c, d;
  __asm {
    /* Do the call. */
    mov EAX, InfoType;
    cpuid;
    /* Save results. */
    mov a, EAX;
    mov b, EBX;
    mov c, ECX;
    mov d, EDX;
  }
  printf ("InfoType %x\nEAX: %x\nEBX: %x\nECX: %x\nEDX: %x\n", InfoType, a, b, c, d);
  return 0;
}

If either version was written in plain assembly language, the programmer must manually save the results of EAX, EBX, ECX, and EDX elsewhere if they want to keep using the values.

Wrapper functions

GCC also provides a header called <cpuid.h> on systems that have CPUID. The __cpuid is a macro expanding to inline assembly. Typical usage would be:

#include <cpuid.h>
#include <stdio.h>

int
main (void)
{
  int a, b, c, d;
  __cpuid (0 /* vendor string */, a, b, c, d);
  printf ("EAX: %x\nEBX: %x\nECX: %x\nEDX: %x\n", a, b, c, d);
  return 0;
}

But if one requested an extended feature not present on this CPU, they would not notice and might get random, unexpected results. Safer version is also provided in <cpuid.h>. It checks for extended features and does some more safety checks. The output values are not passed using reference-like macro parameters, but more conventional pointers.

#include <cpuid.h>
#include <stdio.h>

int
main (void)
{
  int a, b, c, d;
  if (!__get_cpuid (0x81234567 /* nonexistent, but assume it exists */, &a, &b, &c, &d))
    {
      fprintf (stderr, "Warning: CPUID request 0x81234567 not valid!\n");
    }
  printf("EAX: %x\nEBX: %x\nECX: %x\nEDX: %x\n", a, b, c, d);
  return 0;
}

Notice the ampersands in &a, &b, &c, &d and the conditional statement. If the __get_cpuid call receives a correct request, it will return a non-zero value, if it fails, zero.[27]

Microsoft Visual C compiler has builtin function __cpuid() so the cpuid instruction may be embedded without using inline assembly, which is handy since the x86-64 version of MSVC does not allow inline assembly at all. The same program for MSVC would be:

#include <iostream>
#include <intrin.h>

int main()
{
  int cpuInfo[4];

  for (int a = 0; a < 5; a++)
  {
    __cpuid(cpuInfo, a);
    std::cout << "The code " << a << " gives " << cpuInfo[0] << ", " << cpuInfo[1] << ", " << cpuInfo[2] << ", " << cpuInfo[3] << '\n';
  }

  return 0;
}

Many interpreted or compiled scripting languages are capable of using CPUID via an FFI library. One such implementation shows usage of the Ruby FFI module to execute assembly language that includes the CPUID opcode.

CPU-specific information outside x86

Some of the non-x86 CPU architectures also provide certain forms of structured information about the processor's abilities, commonly as a set of special registers:

  • ARM architectures have a CPUID coprocessor register which requires EL1 or above to access.[28]
  • The IBM System z mainframe processors have a Store CPU ID (STIDP) instruction since the 1983 IBM 4381[29] for querying the processor ID.[30]
  • The IBM System z mainframe processors also have a Store Facilities List Extended (STFLE) instruction which lists the installed hardware features.[30]
  • The MIPS32/64 architecture defines a mandatory Processor Identification (PrId) and a series of daisy-chained Configuration Registers.[31]
  • The PowerPC processor has the 32-bit read-only Processor Version Register (PVR) identifying the processor model in use. The instruction requires supervisor access level.[32]

DSP and transputer-like chip families have not taken up the instruction in any noticeable way, in spite of having (in relative terms) as many variations in design. Alternate ways of silicon identification might be present; for example, DSPs from Texas Instruments contain a memory-based register set for each functional unit that starts with identifiers determining the unit type and model, its ASIC design revision and features selected at the design phase, and continues with unit-specific control and data registers. Access to these areas is performed by simply using the existing load and store instructions; thus, for such devices there is no need for extending the register set for the device identification purposes.

See also

References

  1. "Intel 64 and IA-32 Architectures Software Developer's Manual" (PDF). Intel.com. Retrieved 2013-04-11.
  2. "Detecting Intel Processors - Knowing the generation of a system CPU". Rcollins.org. Retrieved 2013-04-11.
  3. "LXR linux-old/arch/i386/kernel/head.S". Lxr.linux.no. Archived from the original on 2012-07-13. Retrieved 2013-04-11.
  4. "CPUID, EAX=4 - Strange results (Solved)". Software.intel.com. Retrieved 2014-07-10.
  5. "ao486 CPUID instruction".
  6. "v586: 586 compatible soft core for FPGA".
  7. "Chapter 3 Instruction Set Reference, A-L" (PDF). Intel® 64 and IA-32 Architectures Software Developer's Manual. Intel Corporation. 2018-12-20. Retrieved 2018-12-20.
  8. http://bochs.sourceforge.net/techspec/24161821.pdf
  9. Huggahalli, Ram; Iyer, Ravi; Tetrick, Scott (2005). "Direct Cache Access for High Bandwidth Network I/O". ACM SIGARCH Computer Architecture News. 33 (2): 50–59. doi:10.1145/1080695.1069976. CiteSeerX:10.1.1.91.957.
  10. Drepper, Ulrich (2007), What Every Programmer Should Know About Memory, CiteSeerX:10.1.1.91.957
  11. "Mechanisms to determine if software is running in a VMware virtual machine". VMware Knowledge Base. VMWare. 2015-05-01. Intel and AMD CPUs have reserved bit 31 of ECX of CPUID leaf 0x1 as the hypervisor present bit. This bit allows hypervisors to indicate their presence to the guest operating system. Hypervisors set this bit and physical CPUs (all existing and future CPUs) set this bit to zero. Guest operating systems can test bit 31 to detect if they are running inside a virtual machine.
  12. Kataria, Alok; Hecht, Dan (2008-10-01). "Hypervisor CPUID Interface Proposal". LKML Archive on lore.kernel.org. Archived from the original on 2019-03-15. Bit 31 of ECX of CPUID leaf 0x1. This bit has been reserved by Intel & AMD for use by hypervisors, and indicates the presence of a hypervisor. Virtual CPU's (hypervisors) set this bit to 1 and physical CPU's (all existing and future cpu's) set this bit to zero. This bit can be probed by the guest software to detect whether they are running inside a virtual machine.
  13. Shih Kuo (Jan 27, 2012). "Intel® 64 Architecture Processor Topology Enumeration".
  14. "Processor and Core Enumeration Using CPUID | AMD". Developer.amd.com. Archived from the original on 2014-07-14. Retrieved 2014-07-10.
  15. "Sandybridge processors report incorrect core number?". Software.intel.com. 2012-12-29. Retrieved 2014-07-10.
  16. "cpuid, __cpuidex". Msdn.microsoft.com. 2014-06-20. Retrieved 2014-07-10.
  17. "x86 architecture - CPUID". sandpile.org. Retrieved 2014-07-10.
  18. "topology.cpp in ps/trunk/source/lib/sysdep/arch/x86_x64 – Wildfire Games". Trac.wildfiregames.com. 2011-12-27. Retrieved 2014-07-10.
  19. Hyper-Threading Technology and Multi-Core Processor Detection
  20. "Speculative Execution Side Channel Mitigations" (PDF). Revision 2.0. Intel. May 2018 [January 2018]. Document Number: 336996-002. Retrieved 2018-05-26.
  21. "IBRS patch series [LWN.net]".
  22. CPUID Specification (PDF), AMD, September 2010, retrieved 2013-04-02
  23. Linux kernel source code
  24. Lightweight Profiling Specification (PDF), AMD, August 2010, retrieved 2013-04-03
  25. "Intel® Processor Identification and the CPUID Instruction" (PDF). Download.intel.com. 2012-03-06. Retrieved 2013-04-11.
  26. Ferrie, Peter. "Attacks on Virtual Machine Emulators" (PDF). symantec.com. Symantec Advanced Threat Research. Archived from the original (PDF) on 2007-02-07. Retrieved 15 March 2017.
  27. https://github.com/gcc-mirror/gcc/blob/master/gcc/config/i386/cpuid.h
  28. "ARM Information Center". Infocenter.arm.com. Retrieved 2013-04-11.
  29. "Processor version codes and SRM constants". Archived from the original on 2014-09-08. Retrieved 2014-09-08.
  30. "IBM System z10 Enterprise Class Technical Guide" (PDF).
  31. "MIPS32 Architecture For Programmers, Volume III: The MIPS32 Privileged Resource Architecture" (PDF). MIPS Technologies, Inc. 2001-03-12.
  32. "PowerPC Operating Environment Architecture, book III" (PDF).

Further reading

This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.