En la arquitectura x86 , la instrucción CPUID (identificada por un CPUID
código de operación ) es una instrucción complementaria del procesador (su nombre deriva de CPU Identification) que permite al software descubrir detalles del procesador. Fue introducida por Intel en 1993 con el lanzamiento de los procesadores Pentium y SL-enhanced 486. [1]
Un programa puede usarlo CPUID
para determinar el tipo de procesador y si están implementadas funciones como MMX / SSE .
Antes de la disponibilidad general de la CPUID
instrucción, los programadores escribían código de máquina esotérico que explotaba pequeñas diferencias en el comportamiento de la CPU para determinar la marca y el modelo del procesador. [2] [3] [4] [5] Con la introducción del procesador 80386, EDX al reiniciar indicaba la revisión, pero esto solo era legible después del reinicio y no había una forma estándar para que las aplicaciones leyeran el valor.
Fuera de la familia x86, los desarrolladores todavía deben utilizar procesos esotéricos (que involucran sincronización de instrucciones o desencadenadores de fallas de CPU) para determinar las variaciones en el diseño de CPU que están presentes.
Por ejemplo, en la familia Motorola 680x0 (que nunca tuvo una CPUID
instrucción de ningún tipo), ciertas instrucciones específicas requerían privilegios elevados. Estos se podían usar para diferenciar a varios miembros de la familia de CPU. En el Motorola 68010, la instrucción MOVE de SR se volvió privilegiada. Este notable cambio de instrucción (y máquina de estados) permitió que el 68010 cumpliera con los requisitos de virtualización de Popek y Goldberg . Debido a que el 68000 ofrecía una instrucción MOVE sin privilegios de SR, las 2 CPU diferentes se podían diferenciar mediante una condición de error de CPU que se desencadenaba.
Si bien la CPUID
instrucción es específica de la arquitectura x86, otras arquitecturas (como ARM) a menudo proporcionan registros en el chip que pueden leerse de formas prescritas para obtener los mismos tipos de información proporcionada por la CPUID
instrucción x86.
El CPUID
código de operación es 0F A2
.
En lenguaje ensamblador , la CPUID
instrucción no toma parámetros, ya que CPUID
utiliza implícitamente el registro EAX para determinar la categoría principal de información devuelta. En la terminología más reciente de Intel, esto se denomina hoja CPUID. CPUID
debe llamarse con EAX = 0
primero, ya que esto almacenará en el registro EAX el parámetro de llamada EAX más alto (hoja) que implementa la CPU.
Para obtener información sobre la función extendida, CPUID
se debe llamar con el bit más significativo de EAX establecido. Para determinar el parámetro de llamada de función extendida más alto, llame CPUID
con EAX = 80000000h
.
Las hojas de CPUID mayores que 3 pero menores que 80000000 son accesibles solo cuando los registros específicos del modelo tienen IA32_MISC_ENABLE.BOOT_NT4 [bit 22] = 0 (que es así por defecto). Como sugiere el nombre, Windows NT 4.0 hasta SP6 no arrancaba correctamente a menos que este bit estuviera configurado, [6] pero las versiones posteriores de Windows no lo necesitan, por lo que se puede asumir que las hojas básicas mayores que 4 son visibles en los sistemas Windows actuales. A partir de abril de 2024 [update], las hojas básicas válidas llegan hasta 23h, pero la información devuelta por algunas hojas no se divulga en la documentación disponible públicamente, es decir, están "reservadas".
Algunas de las hojas agregadas más recientemente también tienen subhojas, que se seleccionan a través del registro ECX antes de llamar CPUID
.
Esto devuelve la cadena de identificación del fabricante de la CPU: una cadena ASCII de doce caracteres almacenada en EBX, EDX, ECX (en ese orden). El parámetro de llamada básico más alto (el valor más grande en el que se puede configurar EAX antes de llamar CPUID
) se devuelve en EAX.
Aquí hay una lista de procesadores y la función más alta implementada.
Las siguientes son cadenas de identificación de fabricantes de procesadores conocidas:
"AuthenticAMD"
– AMD"CentaurHauls"
– IDT WinChip/ Centaur (incluidas algunas CPU VIA y Zhaoxin)"CyrixInstead"
– Cyrix /primeros STMicroelectronics e IBM"GenuineIntel"
– Inteligencia"GenuineIotel"
– Intel (raro) [7] [8]"TransmetaCPU"
– Transmeta"GenuineTMx86"
– Transmeta"Geode by NSC"
– Semiconductor Nacional"NexGenDriven"
– NexGen"RiseRiseRise"
- Elevar"SiS SiS SiS "
– Hermana"UMC UMC UMC "
– Iglesia Metodista Unida"Vortex86 SoC"
– DM&P Vortex86" Shanghai "
– Zhaoxin"HygonGenuine"
– Hygon"Genuine RDC"
– RDC Semiconductor Co. Ltd. [9]"E2K MACHINE"
– Estación de tren de alta velocidad Elbrus [10]"VIA VIA VIA "
– VIA [ cita requerida ]"AMD ISBETTER"
– primeras muestras de ingeniería del procesador AMD K5 [11] [12] [ se necesita una mejor fuente ]Las siguientes son cadenas de identificación utilizadas por núcleos de CPU de código abierto :
"GenuineAO486"
– CPU ao486 (antigua) [13] [14]"MiSTer AO486"
– CPU ao486 (nueva) [15] [14]"GenuineIntel"
– v586 core [16] (esto es idéntico a la cadena de identificación de Intel)Las siguientes son cadenas de identificación conocidas de máquinas virtuales:
"MicrosoftXTA"
– Microsoft x86 a ARM [17]"GenuineIntel"
– Rosetta 2 de Apple [18]"VirtualApple"
– Versiones más nuevas de Apple Rosetta 2Por ejemplo, en un procesador GenuineIntel, los valores devueltos en EBX son 0x756e6547, EDX es 0x49656e69 y ECX es 0x6c65746e. El siguiente código de ejemplo muestra la cadena de identificación del proveedor, así como el parámetro de llamada más alto que implementa la CPU.
.intel_syntax sin prefijo .texto.m0: .string "CPUID: %x\n" .m1: .string "Número de función básica más grande implementado: %i\n" .m2: .string "ID del proveedor: %s\n" .globl principal principal:Empujar r12 movimiento eax , 1 subtítulo rsp , 16 identificador de CPU Lea RDI , .m0 [ rip ] movimiento esi , eax llamar a printfmovimiento eax , 0 identificador de CPULea RDI , .m1 [ rip ] movimiento esi , eax movimiento r12d , edx movimiento ebp , ecx llamar a printf movimiento 3 [ rsp ], ebx leer rsi , 3 [ rsp ] Lea RDI , .m2 [ rip ] movimiento 7 [ rsp ], r12d mov 11 [ rsp ], ebp llamar a printfañadir rsp , 16 estallido r12 retirado .sección .nota.GNU - pila , "" , @ progbits
En algunos procesadores, es posible modificar la cadena de identificación del fabricante informada por CPUID.(EAX=0) escribiendo una nueva cadena de identificación en MSR ( registros específicos del modelo ) particulares mediante la WRMSR
instrucción. Esto se ha utilizado en procesadores que no son Intel para habilitar funciones y optimizaciones que se han deshabilitado en el software para CPU que no devuelven la GenuineIntel
cadena de identificación. [19] Los procesadores que se sabe que poseen dichos MSR incluyen:
Esto devuelve la información de la versión , el modelo y la familia de la CPU en el registro EAX (también llamado la firma de una CPU), los indicadores de características en los registros EDX y ECX, y la información de características adicionales en el registro EBX. [27]
A partir de octubre de 2023, se conocen los siguientes identificadores de familia de procesadores x86: [29]
CPUID
instrucción; sin embargo, devuelve el ID de familia 3h
en el valor de reinicio de EDX.8h
La información del procesador y las características son específicas del fabricante, pero generalmente los valores de Intel son utilizados por otros fabricantes por razones de compatibilidad.
CPUID
con un índice de hoja (EAX) mayor que 0 puede dejar EBX y ECX sin modificar, manteniendo sus valores anteriores. Por este motivo, se recomienda poner a cero EBX y ECX antes de ejecutar CPUID
con un índice de hoja de 1.Entre los procesadores que presentan este comportamiento se incluyen Cyrix MII [45] e IDT WinChip 2. [46]
CentaurHauls
, GenuineTMx86
y RiseRiseRise
), la CMPXCHG8B
instrucción siempre es compatible, sin embargo, el bit de característica para la instrucción podría no estar configurado. Esta es una solución temporal para un error en Windows NT. [47]AuthenticAMD
Familia 5 Modelo 0), el bit 9 de EDX solía indicar compatibilidad con PGE. Esto se trasladó al bit 13 a partir del K5 Modelo 1 en adelante. [48]GenuineIntel
Familia 6 Modelo 1), el bit EDX 11 no es válido: el bit está configurado, pero las instrucciones SYSENTER
y SYSEXIT
no son compatibles con Pentium Pro. [50]FCMOV
y FCOMI
las instrucciones solo están disponibles si también está presente la FPU x87 incorporada (indicada por el bit 0 de EDX).119h
( BBL_CR_CTL
) en 1. Al hacerlo, se eliminará la hoja 3 y hará que CPUID.(EAX=1):EDX[bit 18] devuelva 0.En documentación anterior, este bit a menudo se menciona como un indicador de " Tecnología Hyper-Threading " [55] ; sin embargo, si bien este indicador es un requisito previo para la compatibilidad con Hyper-Threading, no indica por sí mismo compatibilidad con Hyper-Threading y se ha configurado en muchas CPU que no cuentan con ningún tipo de tecnología multi-threading. [56]
Los campos reservados deben enmascararse antes de usarlos para fines de identificación del procesador.
Esto devuelve una lista de descriptores que indican las capacidades de caché y TLB en los registros EAX, EBX, ECX y EDX.
En los procesadores que admiten esta hoja, la llamada CPUID
con EAX=2 hará que el byte inferior de EAX se establezca en 01h
[a] y los 15 bytes restantes de EAX/EBX/ECX/EDX se llenen con 15 descriptores, un byte cada uno. Estos descriptores proporcionan información sobre las memorias caché, las TLB y la precarga del procesador. Normalmente se trata de una memoria caché o TLB por descriptor, pero algunos valores de descriptor también proporcionan otra información; en particular, 00h
se utiliza para un descriptor vacío, FFh
indica que la hoja no contiene información de memoria caché válida y que se debe utilizar la hoja 4h en su lugar, e FEh
indica que la hoja no contiene información de TLB válida y que se debe utilizar la hoja 18h en su lugar. Los descriptores pueden aparecer en cualquier orden.
Para cada uno de los cuatro registros (EAX, EBX, ECX, EDX), si se establece el bit 31, entonces no se debe considerar que el registro contenga descriptores válidos (por ejemplo, en Itanium en modo IA-32, CPUID(EAX=2) retorna 80000000h
en EDX - esto se debe interpretar como que EDX no contiene información válida, no que contiene un caché L2 de 512K).
La siguiente tabla proporciona, para valores de descriptor conocidos, una descripción condensada de la caché o TLB indicada por ese valor de descriptor (u otra información, cuando corresponda). Los sufijos utilizados en la tabla son:
CPUID
debe llamar a la función con EAX=2 para obtener todos los descriptores de caché/TLB. Sin embargo, todos los procesadores conocidos que implementan esta hoja devuelven 01h
este byte, y la documentación más reciente de Intel (SDM rev 053 [60] y posteriores) especifica que este byte tiene el valor 01h
.10h
, 15h
, 1Ah
, 88h
, 89h
, 8Ah
, 90h
, 96h
, 9Bh
están documentados únicamente para el modo de operación IA-32 de Itanium . [61]26h
, 27h
, 28h
y 81h
no están incluidos en la documentación de Intel y no se utilizan en ninguna CPU conocida, pero se ha informado que son reconocidos por el kernel de Windows NT v5.1 ( Windows XP ) y superiores. 81h
también es reconocido por v5.0 ( Windows 2000 ). [68]39h-3Eh
73h
39h
49h
indica un caché de nivel 3 en GenuineIntel
las CPU de la familia 0Fh modelo 6 (Xeon basado en Pentium 4) y un caché de nivel 2 en otras CPU.4Fh
. Los procesadores que utilizan este descriptor (Intel Atom "Bonnell" [64] ) se enumeran en otros lugares como si tuvieran un ITLB de 32 entradas totalmente asociativo. [65]CyrixInstead
y Geode by NSC
), los descriptores 70h
y 80h
tienen un significado diferente: [66]70h
indica una TLB asociativa de conjunto de 4 vías con instrucciones+datos compartidos y 32 entradas con un tamaño de página de 4K.80h
indica un caché L1 de instrucciones+datos compartido de 16 KB con asociatividad de conjuntos de 4 vías y un tamaño de línea de caché de 16 bytes.76h
aparece como un caché L2 de 1 MB en la rev 37 de Intel AP-485, [67] pero como una TLB de instrucciones en la rev 38 y en toda la documentación de Intel posterior.77h
7Eh
8Dh
B1h
, la capacidad de TLB es de 8 elementos cuando se utilizan páginas de 2 MB, pero se reduce a 4 elementos cuando se utilizan páginas de 4 MB.F0h
y F1h
es el paso recomendado para la precarga de memoria con la PREFETCHNTA
instrucción. [73]Esto devuelve el número de serie del procesador. El número de serie del procesador se introdujo en Intel Pentium III , pero debido a cuestiones de privacidad, esta función ya no se implementa en los modelos posteriores (el bit de la función PSN siempre se borra). Los procesadores Efficeon y Crusoe de Transmeta también ofrecen esta función. Sin embargo, las CPU AMD no implementan esta función en ningún modelo de CPU.
En el caso de las CPU Intel Pentium III, el número de serie se devuelve en los registros EDX:ECX. En el caso de las CPU Transmeta Efficeon, se devuelve en los registros EBX:EAX. Y en el caso de las CPU Transmeta Crusoe, se devuelve únicamente en el registro EBX.
Tenga en cuenta que la función de número de serie del procesador debe estar habilitada en la configuración del BIOS para funcionar.
Estas dos hojas se utilizan para proporcionar información sobre los niveles de jerarquía de caché disponibles para el núcleo del procesador en el que CPUID
se ejecuta la instrucción. Leaf 4
se utiliza en procesadores Intel y leaf 8000001Dh
se utiliza en procesadores AMD: ambos devuelven datos en EAX, EBX, ECX y EDX, utilizando el mismo formato de datos excepto que leaf 4
devuelve algunos campos adicionales que se consideran "reservados" para leaf 8000001Dh
. Ambos proporcionan información de caché de CPU en una serie de subhojas seleccionadas por ECX: para obtener información sobre todos los niveles de caché, es necesario invocar CPUID
repetidamente, con EAX= 4
o 8000001Dh
y ECX configurados en valores crecientes comenzando desde 0 (0,1,2,...) hasta que se encuentre una subhoja que no describa ninguna caché (EAX[4:0]=0). Las subhojas que devuelven información de caché pueden aparecer en cualquier orden, pero todas aparecerán antes de la primera subhoja que no describa ninguna caché.
En la siguiente tabla, los campos que están definidos para la hoja 4
pero no para la hoja 8000001Dh
están resaltados con color de celda amarillo y un elemento (#4) .
GenuineIntel
Familia 0Bh
). [39] Para otros procesadores, se deben usar en su lugar los bits 1:0 de EDX.Para cualquier caché que sea válido y no totalmente asociativo, el valor devuelto en ECX es la cantidad de conjuntos en el caché menos 1. (Para cachés totalmente asociativos, ECX debe tratarse como si devolviera el valor 0). Para cualquier caché dado descrito por una subhoja de CPUID
leaf 4
o 8000001Dh
, el tamaño total del caché en bytes se puede calcular como:CacheSize = (EBX[11:0]+1) * (EBX[21:12]+1) * (EBX[31:22]+1) * (ECX+1)
Estas dos hojas se utilizan para la topología del procesador (subproceso, núcleo, paquete) y la enumeración de la jerarquía de caché en los procesadores multinúcleo (y con hiperproceso) de Intel. [74] A partir de 2013, [update]AMD no utiliza estas hojas, pero tiene formas alternativas de realizar la enumeración de núcleos. [75]
A diferencia de la mayoría de las otras hojas CPUID, la hoja Bh devolverá diferentes valores en EDX dependiendo de qué procesador lógico ejecute la instrucción CPUID; el valor devuelto en EDX es en realidad el id x2APIC del procesador lógico. Sin embargo, el espacio de id x2APIC no se asigna continuamente a procesadores lógicos; puede haber brechas en la asignación, lo que significa que algunos id x2APIC intermedios no necesariamente corresponden a ningún procesador lógico. En los otros registros se proporciona información adicional para asignar los id x2APIC a núcleos. Aunque la hoja Bh tiene subhojas (seleccionadas por ECX como se describe más adelante), el valor devuelto en EDX solo se ve afectado por el procesador lógico en el que se ejecuta la instrucción, pero no por la subhoja.
La topología de procesadores expuesta por la hoja Bh es jerárquica, pero con la extraña salvedad de que el orden de los niveles (lógicos) en esta jerarquía no necesariamente corresponde al orden en la jerarquía física ( SMT /núcleo/paquete). Sin embargo, cada nivel lógico puede ser consultado como una subhoja ECX (de la hoja Bh) para su correspondencia con un "tipo de nivel", que puede ser SMT, núcleo o "inválido". El espacio de identificación de nivel comienza en 0 y es continuo, lo que significa que si una identificación de nivel es inválida, todas las identificaciones de nivel superior también lo serán. El tipo de nivel se devuelve en los bits 15:08 de ECX, mientras que la cantidad de procesadores lógicos en el nivel consultado se devuelve en EBX. Finalmente, la conexión entre estos niveles y las identificaciones de x2APIC se devuelve en EAX[4:0] como la cantidad de bits que la identificación de x2APIC debe desplazarse para obtener una identificación única en el siguiente nivel.
Como ejemplo, un procesador Westmere de doble núcleo capaz de realizar hyperthreading (y, por lo tanto, tener dos núcleos y cuatro subprocesos en total) podría tener los identificadores x2APIC 0, 1, 4 y 5 para sus cuatro procesadores lógicos. La hoja Bh (=EAX), subhoja 0 (=ECX) de CPUID podría, por ejemplo, devolver 100h en ECX, lo que significa que el nivel 0 describe la capa SMT (hyperthreading), y devolver 2 en EBX porque hay dos procesadores lógicos (unidades SMT) por núcleo físico. El valor devuelto en EAX para esta subhoja 0 debería ser 1 en este caso, porque desplazar los identificadores x2APIC antes mencionados a la derecha en un bit proporciona un número de núcleo único (en el siguiente nivel de la jerarquía de identificadores de nivel) y borra el bit de identificador SMT dentro de cada núcleo. Una forma más sencilla de interpretar esta información es que el último bit (bit número 0) del id de x2APIC identifica la unidad SMT/hyperthreading dentro de cada núcleo en nuestro ejemplo. Avanzar a la subhoja 1 (haciendo otra llamada a CPUID con EAX=Bh y ECX=1) podría, por ejemplo, devolver 201h en ECX, lo que significa que este es un nivel de tipo de núcleo, y 4 en EBX porque hay 4 procesadores lógicos en el paquete; EAX devuelto podría ser cualquier valor mayor que 3, porque resulta que el bit número 2 se utiliza para identificar el núcleo en el id de x2APIC. Tenga en cuenta que el bit número 1 del id de x2APIC no se utiliza en este ejemplo. Sin embargo, EAX devuelto en este nivel bien podría ser 4 (y resulta ser así en un Clarkdale Core i3 5x0) porque eso también proporciona un id único en el nivel de paquete (=0 obviamente) al cambiar el id de x2APIC por 4 bits. Por último, puede que te preguntes qué nos puede decir la hoja EAX=4 que no hayamos descubierto ya. En EAX[31:26] devuelve los bits de máscara APIC reservados para un paquete; en nuestro ejemplo, serían 111b porque los bits 0 a 2 se utilizan para identificar procesadores lógicos dentro de este paquete, pero el bit 1 también está reservado, aunque no se utiliza como parte del esquema de identificación de procesadores lógicos. En otras palabras, los identificadores APIC 0 a 7 están reservados para el paquete, aunque la mitad de estos valores no se asignan a un procesador lógico.
La jerarquía de caché del procesador se explora observando las subhojas de la hoja 4. Los identificadores APIC también se utilizan en esta jerarquía para transmitir información sobre cómo los diferentes niveles de caché son compartidos por las unidades SMT y los núcleos. Para continuar con nuestro ejemplo, la caché L2, que es compartida por las unidades SMT del mismo núcleo pero no entre núcleos físicos en Westmere, se indica mediante EAX[26:14] establecido en 1, mientras que la información de que la caché L3 es compartida por todo el paquete se indica estableciendo esos bits en (al menos) 111b. Los detalles de la caché, incluidos el tipo de caché, el tamaño y la asociatividad, se comunican a través de los otros registros en la hoja 4.
Tenga en cuenta que las versiones anteriores de la nota de aplicación 485 de Intel contienen información engañosa, en particular con respecto a la identificación y el recuento de núcleos en un procesador multinúcleo; [76] incluso se han incorporado errores por malinterpretar esta información en el código de muestra de Microsoft para usar CPUID, incluso para la edición 2013 de Visual Studio, [77] y también en la página sandpile.org para CPUID, [78] pero el ejemplo de código de Intel para identificar la topología del procesador [74] tiene la interpretación correcta, y el Manual del desarrollador de software de Intel actual tiene un lenguaje más claro. El código de producción multiplataforma (de código abierto) [79] de Wildfire Games también implementa la interpretación correcta de la documentación de Intel.
En una presentación de Intel de 2010 se ofrecen ejemplos de detección de topología que involucran procesadores Intel más antiguos (anteriores a 2010) que carecen de x2APIC (y, por lo tanto, no implementan la hoja EAX=Bh). [80] Tenga en cuenta que el uso de ese método de detección más antiguo en procesadores Intel de 2010 y más nuevos puede sobreestimar la cantidad de núcleos y procesadores lógicos porque el método de detección antiguo supone que no hay espacios en el espacio de identificación de APIC, y esta suposición es violada por algunos procesadores más nuevos (comenzando con la serie Core i3 5x0), pero estos procesadores más nuevos también vienen con un x2APIC, por lo que su topología se puede determinar correctamente utilizando el método de hoja EAX=Bh.
Esto devuelve información de funciones relacionada con las instrucciones MONITOR
y MWAIT
en los registros EAX, EBX, ECX y EDX.
Esto devuelve bits de características en el registro EAX e información adicional en los registros EBX, ECX y EDX.
IA32_HWP_REQUEST
MSR en las CPU que lo admiten, es necesario establecer el bit 0 del FAST_UNCORE_MSRS_CTL
( 657h
) MSR.Esto devuelve indicadores de funciones extendidas en EBX, ECX y EDX. Devuelve el valor ECX máximo para EAX=7 en EAX.
Esto devuelve indicadores de funciones extendidas en los cuatro registros.
MWAIT
instrucción puede indicarse mediante CPUID.(EAX=1).ECX[3] o CPUID.(EAX=7,ECX=1).EDX[23]. (Se pueden configurar uno o ambos). El primero MONITOR
también indica soporte para la instrucción, mientras que el último no indica de una forma u otra si la MONITOR
instrucción está presente. MWAIT
without MONITOR
puede estar presente en sistemas que admiten la característica "Monitorless MWAIT" (que se indica mediante CPUID.(EAX=5).ECX[3] ).Esto devuelve indicadores de funciones extendidas en EDX.
EAX, EBX y ECX están reservados.
Esta hoja se utiliza para enumerar las características y los componentes de estado de XSAVE.
La extensión del conjunto de instrucciones XSAVE está diseñada para guardar/restaurar el estado extendido de la CPU (normalmente con el fin de cambiar de contexto ) de una manera que se pueda ampliar para cubrir nuevas extensiones del conjunto de instrucciones sin que el código de cambio de contexto del SO necesite comprender los detalles de las nuevas extensiones. Esto se hace definiendo una serie de componentes de estado , cada uno con un tamaño y un desplazamiento dentro de un área de almacenamiento determinada, y cada uno correspondiente a un subconjunto del estado necesario para una extensión de CPU u otra. La EAX=0Dh
hoja CPUID se utiliza para proporcionar información sobre qué componentes de estado admite la CPU y cuáles son sus tamaños/desplazamientos, de modo que el SO pueda reservar la cantidad adecuada de espacio y establecer los bits de habilitación asociados.
Los componentes de estado se pueden subdividir en dos grupos: estado de usuario (elementos de estado que son visibles para la aplicación, por ejemplo, registros vectoriales AVX-512 ) y estado de supervisor (elementos de estado que afectan a la aplicación pero no son directamente visibles para el usuario, por ejemplo, configuración de interrupción del modo usuario). Los elementos de estado de usuario se habilitan configurando sus bits asociados en el XCR0
registro de control, mientras que los elementos de estado de supervisor se habilitan configurando sus bits asociados en el MSR IA32_XSS
( 0DA0h
) - los elementos de estado indicados se convierten entonces en los componentes de estado que se pueden guardar y restaurar con la familia de instrucciones XSAVE
/ XRSTOR
.
El mecanismo XSAVE puede manejar hasta 63 componentes de estado de esta manera. Los componentes de estado 0 y 1 ( x87 y SSE , respectivamente) tienen desplazamientos y tamaños fijos; para los componentes de estado 2 a 62, se pueden consultar sus tamaños, desplazamientos y algunos indicadores adicionales ejecutando CPUID
con EAX=0Dh
y ECX
estableciendo el índice del componente de estado. Esto devolverá los siguientes elementos en EAX, EBX y ECX (con EDX reservado):
Intentar consultar un componente de estado no compatible de esta manera da como resultado que EAX, EBX, ECX y EDX se establezcan en 0.
Las subhojas 0 y 1 de CPUID
la hoja 0Dh
se utilizan para proporcionar información sobre las características:
A partir de julio de 2023, los componentes de estado XSAVE que se han definido arquitectónicamente son:
XCR0
está cableado a 1, de modo que las instrucciones XSAVE siempre admitirán guardar/restaurar el estado x87.XCR0
y IA32_XSS
, el bit 63 está reservado específicamente para la expansión del vector de bits: esto impide la existencia de un componente de estado 63.This leaf provides information about the supported capabilities of the Intel Software Guard Extensions (SGX) feature. The leaf provides multiple sub-leaves, selected with ECX.
Sub-leaf 0 provides information about supported SGX leaf functions in EAX and maximum supported SGX enclave sizes in EDX; ECX is reserved. EBX provides a bitmap of bits that can be set in the MISCSELECT field in the SECS (SGX Enclave Control Structure) - this field is used to control information written to the MISC region of the SSA (SGX Save State Area) when an AEX (SGX Asynchronous Enclave Exit) occurs.
Sub-leaf 1 provides a bitmap of which bits can be set in the 128-bit ATTRIBUTES field of SECS in EDX:ECX:EBX:EAX (this applies to the SECS copy used as input to the ENCLS[ECREATE]
leaf function). The top 64 bits (given in EDX:ECX) are a bitmap of which bits can be set in the XFRM (X-feature request mask) - this mask is a bitmask of which CPU state-components (see leaf 0Dh) will be saved to the SSA in case of an AEX; this has the same layout as the XCR0
control register. The other bits are given in EAX and EBX, as follows:
ENCLS[EINIT]
. This bit must be 0 in the SECS copy that is given as input to ENCLS[CREATE]
.Sub-leaves 2 and up are used to provide information about which physical memory regions are available for use as EPC (Enclave Page Cache) sections under SGX.
This sub-leaf provides feature information for Intel Processor Trace (also known as Real Time Instruction Trace).
The value returned in EAX is the index of the highest sub-leaf supported for CPUID with EAX=14h. EBX and ECX provide feature flags, EDX is reserved.
These two leaves provide information about various frequencies in the CPU in EAX, EBX and ECX (EDX is reserved in both leaves).
If the returned values in EBX and ECX of leaf 15h are both nonzero, then the TSC (Time Stamp Counter) frequency in Hz is given by TSCFreq = ECX*(EBX/EAX)
.
On some processors (e.g. Intel Skylake), CPUID_15h_ECX is zero but CPUID_16h_EAX is present and not zero. On all known processors where this is the case,[100] the TSC frequency is equal to the Processor Base Frequency, and the Core Crystal Clock Frequency in Hz can be computed as CoreCrystalFreq = (CPUID_16h_EAX * 10000000) * (CPUID_15h_EAX/CPUID_15h_EBX)
.
On processors that enumerate the TSC/Core Crystal Clock ratio in CPUID leaf 15h, the APIC timer frequency will be the Core Crystal Clock frequency divided by the divisor specified by the APIC's Divide Configuration Register.[101]
This leaf is present in systems where an x86 CPU IP core is implemented in an SoC (System on chip) from another vendor - whereas the other leaves of CPUID
provide information about the x86 CPU core, this leaf provides information about the SoC. This leaf takes a sub-leaf index in ECX.
Sub-leaf 0 returns a maximum sub-leaf index in EAX (at least 3), and SoC identification information in EBX/ECX/EDX:
Sub-leaves 1 to 3 return a 48-byte SoC vendor brand string in UTF-8 format. Sub-leaf 1 returns the first 16 bytes in EAX,EBX,ECX,EDX (in that order); sub-leaf 2 returns the next 16 bytes and sub-leaf 3 returns the last 16 bytes. The string is allowed but not required to be null-terminated.
This leaf provides feature information for Intel Key Locker in EAX, EBX and ECX. EDX is reserved.
When Intel TDX (Trust Domain Extensions) is active, attempts to execute the CPUID
instruction by a TD (Trust Domain) guest will be intercepted by the TDX module. This module will, when CPUID
is invoked with EAX=21h
and ECX=0
(leaf 21h
, sub-leaf 0), return the index of the highest supported sub-leaf for leaf 21h
in EAX
and a TDX module vendor ID string as a 12-byte ASCII string in EBX,EDX,ECX (in that order). Intel's own module implementation returns the vendor ID string "IntelTDX "
(with four trailing spaces)[103] - for this module, additional feature information is not available through CPUID
and must instead be obtained through the TDX-specific TDCALL
instruction.
This leaf is reserved in hardware and will (on processors whose highest basic leaf is 21h
or higher) return 0 in EAX/EBX/ECX/EDX when run directly on the CPU.
This returns a maximum supported sub-leaf in EAX and AVX10 feature information in EBX.[95] (ECX and EDX are reserved.)
Subleaf 1 is reserved for AVX10 features not bound to a version. None are currently defined.
When the CPUID
instruction is executed under Intel VT-x or AMD-v virtualization, it will be intercepted by the hypervisor, enabling the hypervisor to return CPUID
feature flags that differ from those of the underlying hardware. CPUID
leaves 40000000h
to 4FFFFFFFh
are not implemented in hardware, and are reserved for use by hypervisors to provide hypervisor-specific identification and feature information through this interception mechanism.
For leaf 40000000h
, the hypervisor is expected to return the index of the highest supported hypervisor CPUID leaf in EAX, and a 12-character hypervisor ID string in EBX,ECX,EDX (in that order). For leaf 40000001h
, the hypervisor may return an interface identification signature in EAX - e.g. hypervisors that wish to advertise that they are Hyper-V compatible may return 0x31237648
—“Hv#1”
in EAX.[104][105] The formats of leaves 40000001h
and up to the highest supported leaf are otherwise hypervisor-specific. Hypervisors that implement these leaves will normally also set bit 31 of ECX for CPUID leaf 1 to indicate their presence.
Hypervisors that expose more than one hypervisor interface may provide additional sets of CPUID leaves for the additional interfaces, at a spacing of 100h
leaves per interface. For example, when QEMU is configured to provide both Hyper-V and KVM interfaces, it will provide Hyper-V information starting from CPUID leaf 40000000h
and KVM information starting from leaf 40000100h
.[106][107]
Some hypervisors that are known to return a hypervisor ID string in leaf 40000000h
include:
The highest calling parameter is returned in EAX.
EBX/ECX/EDX return the manufacturer ID string (same as EAX=0) on AMD but not Intel CPUs.
This returns extended feature flags in EDX and ECX.
Many of the bits in EDX
(bits 0 through 9, 12 through 17, 23, and 24) are duplicates of EDX
from the EAX=1
leaf - these bits are highlighted in light yellow. (These duplicated bits are present on AMD but not Intel CPUs.)
AMD feature flags are as follows:[126][127]
SYSCALL
/SYSRET
is only valid on AuthenticAMD
Family 5 Model 7 CPUs (AMD K6, 250nm "Little Foot") - for all other processors, EDX bit 11 should be used instead.These instructions were first introduced on Model 7[128] - the CPUID bit to indicate their support was moved[129] to EDX bit 11 from Model 8 (AMD K6-2) onwards.
SYSCALL
/SYSRET
is only set if the CPUID
instruction is executed in 64-bit mode.[130]FCMOV
) supportedAuthenticAMD
Family 6 processors only - the bit is, combined with processor signature and FSB speed, used to identify processors as either multiprocessor-capable or carrying the Sempron brand name.[135]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 ASCII processor brand string.[138] 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 not less than 80000004h
.
The string is specified in Intel/AMD documentation to be null-terminated, however this is not always the case (e.g. DM&P Vortex86DX3 and AMD Ryzen 7 6800HS are known to return non-null-terminated brand strings in leaves 80000002h
-80000004h
[139][140]), and software should not rely on it.
#include <stdio.h>#include <string.h>#include <cpuid.h>int main(){ unsigned int regs[12]; char str[sizeof(regs)+1]; __cpuid(0x80000000, regs[0], regs[1], regs[2], regs[3]); if (regs[0] < 0x80000004) return 1; __cpuid(0x80000002, regs[0], regs[1], regs[2], regs[3]); __cpuid(0x80000003, regs[4], regs[5], regs[6], regs[7]); __cpuid(0x80000004, regs[8], regs[9], regs[10], regs[11]); memcpy(str, regs, sizeof(regs)); str[sizeof(regs)] = '\0'; printf("%s\n", str); return 0;}
On AMD processors, from 180nm Athlon onwards (AuthenticAMD
Family 6 Model 2 and later), it is possible to modify the processor brand string returned by CPUID leaves 80000002h
-80000004h
by using the WRMSR
instruction to write a 48-byte replacement string to MSRs C0010030h
-C0010035h
.[135][141] This can also be done on AMD Geode GX/LX, albeit using MSRs 300Ah
-300Fh
.[142]
In some cases, determining the CPU vendor requires examining not just the Vendor ID in CPUID leaf 0 and the CPU signature in leaf 1, but also the Processor Brand String in leaves 80000002h
-80000004h
. Known cases include:
Montage
in the brand string of the Montage CPUs (e.g. Montage Jintide C2460[143] and Intel Xeon Platinum 8160[144] - both of which identify themselves as GenuineIntel
Family 6 Model 55h Stepping 4 - can be distinguished in this manner.)CentaurHauls
Family 6 CPUs may be either VIA or Zhaoxin CPUs - these can be distinguished by the presence of the substring ZHAOXIN
in the brand string of the Zhaoxin CPUs (e.g. Zhaoxin KaiXian ZX-C+ C4580[145] and VIA Eden X4 C4250[146] - both of which identify themselves as CentaurHauls
Family 6 Model 0Fh Stepping 0Eh - can be distinguished in this manner.)This provides information about the processor's level-1 cache and TLB characteristics in EAX, EBX, ECX and EDX as follows:[a]
CyrixInstead
/Geode by NSC
Family 5 Model 4 CPUs only), leaf 80000005h
exists but has a completely different format, similar to that of leaf 2.[147]0x80000005
in EAX. This has the same meaning as EAX=0, i.e. no hugepage TLBs.FFh
is used to indicate a 256-entry TLB.80000005h
, the following values are used: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 KB (Bits 31 - 16).
#include <stdio.h>#include <cpuid.h>int main(){ unsigned int eax, ebx, ecx, edx; unsigned int lsize, assoc, cache; __cpuid(0x80000006, eax, ebx, ecx, edx); lsize = ecx & 0xff; assoc = (ecx >> 12) & 0x07; cache = (ecx >> 16) & 0xffff; printf("Line size: %d B, Assoc. type: %d, Cache size: %d KB.\n", lsize, assoc, cache); return 0;}
This function provides information about power management, power reporting and RAS (Reliability, availability and serviceability) capabilities of the CPU.
AuthenticAMD
Family 0Fh Model 14h[152] (90nm Athlon64/Opteron) CPUs and is present in all later AMD CPUs - except the ones with the 'no_efer_lmsle' flag set.This leaf returns information about AMD SVM (Secure Virtual Machine) features in EAX, EBX and EDX.
Later AMD documentation, such as #25481 "CPUID specification" rev 2.18[155] and later, only lists the bit as reserved.
In rev 2.30[156] and later, a different bit is listed as reserved for hypervisor use: CPUID.(EAX=1):ECX[bit 31].
Rev 2.28 of #25481 lists the bit as "Ssse3Sse5Dis"[158] - in rev 2.34, it is listed as having been removed from the spec at rev 2.32 under the name "SseIsa10Compat".[159]
Several AMD CPU models will, for CPUID with EAX=8FFFFFFFh
, return an Easter Egg string in EAX, EBX, ECX and EDX.[164][165] Known Easter Egg strings include:
Returns index of highest Centaur leaf in EAX. If the returned value in EAX is less than C0000001h
, then Centaur extended leaves are not supported.
Present in CPUs from VIA and Zhaoxin.
On IDT WinChip CPUs (CentaurHauls
Family 5), the extended leaves C0000001h-C0000005h
do not encode any Centaur-specific functionality but are instead aliases of leaves 80000001h-80000005h
.[167]
This leaf returns Centaur feature information (mainly VIA PadLock) in EDX.[168][169] (EAX, EBX and ECX are reserved.)
CentaurHauls
Family 6 Model 9 only),[170] bits 0,1,4,5 are used differently:0x110A
) presentFEMMS
instruction (opcode 0F 0E
) presentThis 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>#include <cpuid.h>int main(){ unsigned int i, eax, ebx, ecx, edx; for (i = 0; i < 5; i++) { __cpuid(i, eax, ebx, ecx, edx); printf ("InfoType %x\nEAX: %x\nEBX: %x\nECX: %x\nEDX: %x\n", i, eax, ebx, ecx, edx); } 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 a, b, c, d, i = 0; __asm { /* Do the call. */ mov EAX, i; 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", i, 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.
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 <stdio.h>#include <cpuid.h>int main(){ unsigned int eax, ebx, ecx, edx; __cpuid(0 /* vendor string */, eax, ebx, ecx, edx); printf("EAX: %x\nEBX: %x\nECX: %x\nEDX: %x\n", eax, ebx, ecx, edx); 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 <stdio.h>#include <cpuid.h>int main(){ unsigned int eax, ebx, ecx, edx; /* 0x81234567 is nonexistent, but assume it exists */ if (!__get_cpuid (0x81234567, &eax, &ebx, &ecx, &edx)) { printf("Warning: CPUID request 0x81234567 not valid!\n"); return 1; } printf("EAX: %x\nEBX: %x\nECX: %x\nEDX: %x\n", eax, ebx, ecx, edx); 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.[171]
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 <stdio.h>#ifdef __MSVC__ #include <intrin.h>#endifint main(){ unsigned int regs[4]; int i; for (i = 0; i < 4; i++) { __cpuid(regs, i); printf("The code %d gives %d, %d, %d, %d", regs[0], regs[1], regs[2], regs[3]); } 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.
.NET 5 and later versions provide the System.Runtime.Intrinsics.X86.X86base.CpuId
method. For instance, the C# code below prints the processor brand if it supports CPUID instruction:
using System.Runtime.InteropServices;using System.Runtime.Intrinsics.X86;using System.Text;namespace X86CPUID { class CPUBrandString { public static void Main(string[] args) { if (!X86Base.IsSupported) { Console.WriteLine("Your CPU does not support CPUID instruction."); } else { Span<int> raw = stackalloc int[12]; (raw[0], raw[1], raw[2], raw[3]) = X86Base.CpuId(unchecked((int)0x80000002), 0); (raw[4], raw[5], raw[6], raw[7]) = X86Base.CpuId(unchecked((int)0x80000003), 0); (raw[8], raw[9], raw[10], raw[11]) = X86Base.CpuId(unchecked((int)0x80000004), 0); Span<byte> bytes = MemoryMarshal.AsBytes(raw); string brand = Encoding.UTF8.GetString(bytes).Trim(); Console.WriteLine(brand); } } }}
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:
CPUID
coprocessor register which requires exception level EL1 or above to access.[172]STIDP
) instruction since the 1983 IBM 4381[173] for querying the processor ID.[174]STFLE
) instruction which lists the installed hardware features.[174]PrId
) and a series of daisy-chained Configuration Registers.[175]PVR
) identifying the processor model in use. The instruction requires supervisor access level.[176]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 device identification purposes.[citation needed]
CPUID
to identify various system settingsIntel 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.
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.
15.2.2 Guest Mode This new processor mode is entered through the VMRUN instruction. When in guest mode, the behavior of some x86 instructions changes to facilitate virtualization. The CPUID function numbers 4000_0000h-4000_00FFh have been reserved for software use. Hypervisors can use these function numbers to provide an interface to pass information from the hypervisor to the guest. This is similar to extracting information about a physical CPU by using CPUID. Hypervisors use the CPUID Fn 400000[FF:00] bit to denote a virtual platform. Feature bit CPUID Fn0000_0001_ECX[31] has been reserved for use by hypervisors to indicate the presence of a hypervisor. Hypervisors set this bit to 1 and physical 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.
8FFFFFFFh
. Retrieved 22 December 2022.