/*
 * @author  xamidev <xamidev@riseup.net>
 * @brief   x86 CPU identification
 * @license GPL-3.0-only
 */

#include <stdint.h>
#include <stddef.h>
#include <kernel.h>
#include <string/string.h>

/*
 * cpuid - Wrapper for CPUID instruction
 * @leaf: Requested leaf (input EAX)
 * @eax: EAX register value (output)
 * @ebx: EBX register value (output)
 * @ecx: ECX register value (output)
 * @edx: EDX register value (output)
*/
void cpuid(uint32_t leaf, uint32_t* eax, uint32_t* ebx, uint32_t* ecx, uint32_t* edx)
{
    __asm__ volatile("cpuid" : "=a"(*eax), "=b"(*ebx), "=c"(*ecx), "=d"(*edx) : "a"(leaf));
}

/*
 * cpuid_get_vendor_string - Get the CPU vendor string
 * @str: String at least 13 bytes long (for output)
 *
 * Return:
 * %0 - on success
 */
int cpuid_get_vendor_string(char* str)
{
    uint32_t eax, ebx, ecx, edx;
    
    cpuid(0, &eax, &ebx, &ecx, &edx);
    char output[13] = {0};

    uint32_t regs[3] = {ebx, edx, ecx};
    for (unsigned int j=0; j<3; j++) {
        for (unsigned int i=0; i<4; i++) {
            output[4*j+i] = (char)((regs[j] >> 8*i) & 0xff);
        }   
    }

    strncpy(str, output, 13);
    return 0;
}