From fb790b07aeba8e22e4190cf3e1834d11ecde6c96 Mon Sep 17 00:00:00 2001 From: Amlal Date: Fri, 25 Apr 2025 13:08:33 +0200 Subject: dev: better .clang-format, ran format command. Signed-off-by: Amlal --- dev/kernel/HALKit/AMD64/CPUID.h | 147 +++--- dev/kernel/HALKit/AMD64/HalACPIFactoryInterface.cc | 195 ++++---- dev/kernel/HALKit/AMD64/HalAPICController.cc | 62 ++- dev/kernel/HALKit/AMD64/HalApplicationProcessor.cc | 436 ++++++++--------- .../HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc | 265 +++++----- dev/kernel/HALKit/AMD64/HalDebugOutput.cc | 267 +++++------ dev/kernel/HALKit/AMD64/HalDebugPort.cc | 41 +- dev/kernel/HALKit/AMD64/HalDescriptorLoader.cc | 155 +++--- dev/kernel/HALKit/AMD64/HalKernelMain.cc | 204 ++++---- dev/kernel/HALKit/AMD64/HalKernelPanic.cc | 87 ++-- dev/kernel/HALKit/AMD64/HalPagingMgrAMD64.cc | 276 +++++------ dev/kernel/HALKit/AMD64/HalProcessorAMD64.cc | 155 +++--- .../AMD64/HalSchedulerCorePrimitivesAMD64.cc | 86 ++-- dev/kernel/HALKit/AMD64/HalTimerAMD64.cc | 114 +++-- dev/kernel/HALKit/AMD64/Hypervisor.h | 31 +- dev/kernel/HALKit/AMD64/PCI/DMA.cc | 105 ++-- dev/kernel/HALKit/AMD64/PCI/Database.cc | 6 +- dev/kernel/HALKit/AMD64/PCI/Device.cc | 285 +++++------ dev/kernel/HALKit/AMD64/PCI/Express.cc | 6 +- dev/kernel/HALKit/AMD64/PCI/IO.cc | 2 +- dev/kernel/HALKit/AMD64/PCI/Iterator.cc | 49 +- dev/kernel/HALKit/AMD64/PCI/PCI.cc | 2 +- dev/kernel/HALKit/AMD64/Paging.h | 83 ++-- dev/kernel/HALKit/AMD64/Processor.h | 518 ++++++++++---------- dev/kernel/HALKit/AMD64/Storage/AHCI+Generic.cc | 534 ++++++++++----------- dev/kernel/HALKit/AMD64/Storage/DMA+Generic.cc | 200 ++++---- dev/kernel/HALKit/AMD64/Storage/PIO+Generic.cc | 314 ++++++------ dev/kernel/HALKit/AMD64/Storage/SCSI+Generic.cc | 6 +- dev/kernel/HALKit/ARM64/APM/APM+IO.cc | 40 +- dev/kernel/HALKit/ARM64/ApplicationProcessor.h | 9 +- dev/kernel/HALKit/ARM64/HalACPIFactoryInterface.cc | 36 +- dev/kernel/HALKit/ARM64/HalApplicationProcessor.cc | 191 ++++---- dev/kernel/HALKit/ARM64/HalDebugOutput.cc | 118 ++--- dev/kernel/HALKit/ARM64/HalKernelMain.cc | 84 ++-- dev/kernel/HALKit/ARM64/HalKernelPanic.cc | 98 ++-- dev/kernel/HALKit/ARM64/HalPagingMgrARM64.cc | 143 +++--- dev/kernel/HALKit/ARM64/HalSchedulerCoreARM64.cc | 29 +- .../ARM64/HalSchedulerCorePrimitivesARM64.cc | 49 +- dev/kernel/HALKit/ARM64/HalTimerARM64.cc | 10 +- dev/kernel/HALKit/ARM64/Paging.h | 151 +++--- dev/kernel/HALKit/ARM64/Processor.h | 141 +++--- dev/kernel/HALKit/ARM64/Storage/SCSI+Generic.cc | 6 +- dev/kernel/HALKit/ARM64/Storage/UFS+Generic.cc | 2 +- dev/kernel/HALKit/POWER/AP.h | 56 ++- dev/kernel/HALKit/POWER/HalApplicationProcessor.cc | 60 ++- dev/kernel/HALKit/POWER/HalDebugOutput.cc | 21 +- dev/kernel/HALKit/POWER/HalHardwareThread.cc | 2 +- dev/kernel/HALKit/POWER/HalVirtualMemory.cc | 51 +- dev/kernel/HALKit/POWER/Processor.h | 76 ++- dev/kernel/HALKit/RISCV/AP.h | 48 +- dev/kernel/HALKit/RISCV/HalApplicationProcessor.cc | 64 ++- 51 files changed, 2831 insertions(+), 3285 deletions(-) (limited to 'dev/kernel/HALKit') diff --git a/dev/kernel/HALKit/AMD64/CPUID.h b/dev/kernel/HALKit/AMD64/CPUID.h index 9b9c3a1c..8250dfad 100644 --- a/dev/kernel/HALKit/AMD64/CPUID.h +++ b/dev/kernel/HALKit/AMD64/CPUID.h @@ -1,13 +1,13 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: CPUID.h - Purpose: CPUID flags. + File: CPUID.h + Purpose: CPUID flags. - Revision History: + Revision History: - 30/01/24: Added file (amlel) + 30/01/24: Added file (amlel) ------------------------------------------- */ @@ -15,78 +15,75 @@ #include -EXTERN_C -{ +EXTERN_C { #include } -namespace Kernel -{ +namespace Kernel { - enum - { - kCPUFeatureSSE3 = 1 << 0, - kCPUFeaturePCLMUL = 1 << 1, - kCPUFeatureDTES64 = 1 << 2, - kCPUFeatureMONITOR = 1 << 3, - kCPUFeatureDS_CPL = 1 << 4, - kCPUFeatureVMX = 1 << 5, - kCPUFeatureSMX = 1 << 6, - kCPUFeatureEST = 1 << 7, - kCPUFeatureTM2 = 1 << 8, - kCPUFeatureSSSE3 = 1 << 9, - kCPUFeatureCID = 1 << 10, - kCPUFeatureSDBG = 1 << 11, - kCPUFeatureFMA = 1 << 12, - kCPUFeatureCX16 = 1 << 13, - kCPUFeatureXTPR = 1 << 14, - kCPUFeaturePDCM = 1 << 15, - kCPUFeaturePCID = 1 << 17, - kCPUFeatureDCA = 1 << 18, - kCPUFeatureSSE4_1 = 1 << 19, - kCPUFeatureSSE4_2 = 1 << 20, - kCPUFeatureX2APIC = 1 << 21, - kCPUFeatureMOVBE = 1 << 22, - kCPUFeaturePOP3C = 1 << 23, - kCPUFeatureECXTSC = 1 << 24, - kCPUFeatureAES = 1 << 25, - kCPUFeatureXSAVE = 1 << 26, - kCPUFeatureOSXSAVE = 1 << 27, - kCPUFeatureAVX = 1 << 28, - kCPUFeatureF16C = 1 << 29, - kCPUFeatureRDRAND = 1 << 30, - kCPUFeatureHYPERVISOR = 1 << 31, - kCPUFeatureFPU = 1 << 0, - kCPUFeatureVME = 1 << 1, - kCPUFeatureDE = 1 << 2, - kCPUFeaturePSE = 1 << 3, - kCPUFeatureEDXTSC = 1 << 4, - kCPUFeatureMSR = 1 << 5, - kCPUFeaturePAE = 1 << 6, - kCPUFeatureMCE = 1 << 7, - kCPUFeatureCX8 = 1 << 8, - kCPUFeatureAPIC = 1 << 9, - kCPUFeatureSEP = 1 << 11, - kCPUFeatureMTRR = 1 << 12, - kCPUFeaturePGE = 1 << 13, - kCPUFeatureMCA = 1 << 14, - kCPUFeatureCMOV = 1 << 15, - kCPUFeaturePAT = 1 << 16, - kCPUFeaturePSE36 = 1 << 17, - kCPUFeaturePSN = 1 << 18, - kCPUFeatureCLFLUSH = 1 << 19, - kCPUFeatureDS = 1 << 21, - kCPUFeatureACPI = 1 << 22, - kCPUFeatureMMX = 1 << 23, - kCPUFeatureFXSR = 1 << 24, - kCPUFeatureSSE = 1 << 25, - kCPUFeatureSSE2 = 1 << 26, - kCPUFeatureSS = 1 << 27, - kCPUFeatureHTT = 1 << 28, - kCPUFeatureTM = 1 << 29, - kCPUFeatureIA64 = 1 << 30, - kCPUFeaturePBE = 1 << 31 - }; +enum { + kCPUFeatureSSE3 = 1 << 0, + kCPUFeaturePCLMUL = 1 << 1, + kCPUFeatureDTES64 = 1 << 2, + kCPUFeatureMONITOR = 1 << 3, + kCPUFeatureDS_CPL = 1 << 4, + kCPUFeatureVMX = 1 << 5, + kCPUFeatureSMX = 1 << 6, + kCPUFeatureEST = 1 << 7, + kCPUFeatureTM2 = 1 << 8, + kCPUFeatureSSSE3 = 1 << 9, + kCPUFeatureCID = 1 << 10, + kCPUFeatureSDBG = 1 << 11, + kCPUFeatureFMA = 1 << 12, + kCPUFeatureCX16 = 1 << 13, + kCPUFeatureXTPR = 1 << 14, + kCPUFeaturePDCM = 1 << 15, + kCPUFeaturePCID = 1 << 17, + kCPUFeatureDCA = 1 << 18, + kCPUFeatureSSE4_1 = 1 << 19, + kCPUFeatureSSE4_2 = 1 << 20, + kCPUFeatureX2APIC = 1 << 21, + kCPUFeatureMOVBE = 1 << 22, + kCPUFeaturePOP3C = 1 << 23, + kCPUFeatureECXTSC = 1 << 24, + kCPUFeatureAES = 1 << 25, + kCPUFeatureXSAVE = 1 << 26, + kCPUFeatureOSXSAVE = 1 << 27, + kCPUFeatureAVX = 1 << 28, + kCPUFeatureF16C = 1 << 29, + kCPUFeatureRDRAND = 1 << 30, + kCPUFeatureHYPERVISOR = 1 << 31, + kCPUFeatureFPU = 1 << 0, + kCPUFeatureVME = 1 << 1, + kCPUFeatureDE = 1 << 2, + kCPUFeaturePSE = 1 << 3, + kCPUFeatureEDXTSC = 1 << 4, + kCPUFeatureMSR = 1 << 5, + kCPUFeaturePAE = 1 << 6, + kCPUFeatureMCE = 1 << 7, + kCPUFeatureCX8 = 1 << 8, + kCPUFeatureAPIC = 1 << 9, + kCPUFeatureSEP = 1 << 11, + kCPUFeatureMTRR = 1 << 12, + kCPUFeaturePGE = 1 << 13, + kCPUFeatureMCA = 1 << 14, + kCPUFeatureCMOV = 1 << 15, + kCPUFeaturePAT = 1 << 16, + kCPUFeaturePSE36 = 1 << 17, + kCPUFeaturePSN = 1 << 18, + kCPUFeatureCLFLUSH = 1 << 19, + kCPUFeatureDS = 1 << 21, + kCPUFeatureACPI = 1 << 22, + kCPUFeatureMMX = 1 << 23, + kCPUFeatureFXSR = 1 << 24, + kCPUFeatureSSE = 1 << 25, + kCPUFeatureSSE2 = 1 << 26, + kCPUFeatureSS = 1 << 27, + kCPUFeatureHTT = 1 << 28, + kCPUFeatureTM = 1 << 29, + kCPUFeatureIA64 = 1 << 30, + kCPUFeaturePBE = 1 << 31 +}; - typedef Int64 CPUID; -} // namespace Kernel +typedef Int64 CPUID; +} // namespace Kernel diff --git a/dev/kernel/HALKit/AMD64/HalACPIFactoryInterface.cc b/dev/kernel/HALKit/AMD64/HalACPIFactoryInterface.cc index 2430da07..f4dd1347 100644 --- a/dev/kernel/HALKit/AMD64/HalACPIFactoryInterface.cc +++ b/dev/kernel/HALKit/AMD64/HalACPIFactoryInterface.cc @@ -1,120 +1,113 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ -#include -#include -#include #include +#include #include +#include +#include -namespace Kernel -{ - namespace Detail - { - struct FADT final : public SDT - { - UInt32 FirmwareCtrl; - UInt32 Dsdt; +namespace Kernel { +namespace Detail { + struct FADT final : public SDT { + UInt32 FirmwareCtrl; + UInt32 Dsdt; - // field used in ACPI 1.0; no longer in use, for compatibility only - UInt8 Reserved; + // field used in ACPI 1.0; no longer in use, for compatibility only + UInt8 Reserved; - UInt8 PreferredPowerManagementProfile; - UInt16 SCI_Interrupt; - UInt32 SMI_CommandPort; - UInt8 AcpiEnable; - UInt8 AcpiDisable; - UInt8 S4BIOS_REQ; - UInt8 PSTATE_Control; - UInt32 PM1aEventBlock; - UInt32 PM1bEventBlock; - UInt32 PM1aControlBlock; - UInt32 PM1bControlBlock; - UInt32 PM2ControlBlock; - UInt32 PMTimerBlock; - UInt32 GPE0Block; - UInt32 GPE1Block; - UInt8 PM1EventLength; - UInt8 PM1ControlLength; - UInt8 PM2ControlLength; - UInt8 PMTimerLength; - UInt8 GPE0Length; - UInt8 GPE1Length; - UInt8 GPE1Base; - UInt8 CStateControl; - UInt16 WorstC2Latency; - UInt16 WorstC3Latency; - UInt16 FlushSize; - UInt16 FlushStride; - UInt8 DutyOffset; - UInt8 DutyWidth; - UInt8 DayAlarm; - UInt8 MonthAlarm; - UInt8 Century; + UInt8 PreferredPowerManagementProfile; + UInt16 SCI_Interrupt; + UInt32 SMI_CommandPort; + UInt8 AcpiEnable; + UInt8 AcpiDisable; + UInt8 S4BIOS_REQ; + UInt8 PSTATE_Control; + UInt32 PM1aEventBlock; + UInt32 PM1bEventBlock; + UInt32 PM1aControlBlock; + UInt32 PM1bControlBlock; + UInt32 PM2ControlBlock; + UInt32 PMTimerBlock; + UInt32 GPE0Block; + UInt32 GPE1Block; + UInt8 PM1EventLength; + UInt8 PM1ControlLength; + UInt8 PM2ControlLength; + UInt8 PMTimerLength; + UInt8 GPE0Length; + UInt8 GPE1Length; + UInt8 GPE1Base; + UInt8 CStateControl; + UInt16 WorstC2Latency; + UInt16 WorstC3Latency; + UInt16 FlushSize; + UInt16 FlushStride; + UInt8 DutyOffset; + UInt8 DutyWidth; + UInt8 DayAlarm; + UInt8 MonthAlarm; + UInt8 Century; - // reserved in ACPI 1.0; used since ACPI 2.0+ - UInt16 BootArchitecturkMMFlags; + // reserved in ACPI 1.0; used since ACPI 2.0+ + UInt16 BootArchitecturkMMFlags; - UInt8 Reserved2; - UInt32 Flags; + UInt8 Reserved2; + UInt32 Flags; - // 12 byte structure; see below for details - ACPI_ADDRESS ResetReg; + // 12 byte structure; see below for details + ACPI_ADDRESS ResetReg; - UInt8 ResetValue; - UInt8 Reserved3[3]; + UInt8 ResetValue; + UInt8 Reserved3[3]; - // 64bit pointers - Available on ACPI 2.0+ - UInt64 X_FirmwareControl; - UInt64 X_Dsdt; + // 64bit pointers - Available on ACPI 2.0+ + UInt64 X_FirmwareControl; + UInt64 X_Dsdt; - ACPI_ADDRESS X_PM1aEventBlock; - ACPI_ADDRESS X_PM1bEventBlock; - ACPI_ADDRESS X_PM1aControlBlock; - ACPI_ADDRESS X_PM1bControlBlock; - ACPI_ADDRESS X_PM2ControlBlock; - ACPI_ADDRESS X_PMTimerBlock; - ACPI_ADDRESS X_GPE0Block; - ACPI_ADDRESS X_GPE1Block; - }; - } // namespace Detail + ACPI_ADDRESS X_PM1aEventBlock; + ACPI_ADDRESS X_PM1bEventBlock; + ACPI_ADDRESS X_PM1aControlBlock; + ACPI_ADDRESS X_PM1bControlBlock; + ACPI_ADDRESS X_PM2ControlBlock; + ACPI_ADDRESS X_PMTimerBlock; + ACPI_ADDRESS X_GPE0Block; + ACPI_ADDRESS X_GPE1Block; + }; +} // namespace Detail - ACPIFactoryInterface::ACPIFactoryInterface(VoidPtr rsp_ptr) - : fRsdp(rsp_ptr), fEntries(0) - { - } +ACPIFactoryInterface::ACPIFactoryInterface(VoidPtr rsp_ptr) : fRsdp(rsp_ptr), fEntries(0) {} - Bool ACPIFactoryInterface::Shutdown() - { - return NO; - } +Bool ACPIFactoryInterface::Shutdown() { + return NO; +} - /// @brief Reboot machine in either ACPI or by triple faulting. - /// @return nothing it's a reboot. - Void ACPIFactoryInterface::Reboot() - { - asm volatile(".intel_syntax noprefix; " - "rt_reset_hardware:; " - "cli; " - "wait_gate1: ; " - "in al,0x64 ; " - "and al,2 ; " - "jnz wait_gate1 ; " - "mov al,0x0D1 ; " - "out 0x64,al ; " - "wait_gate2: ; " - "in al,0x64 ; " - "and al,2 ; " - "jnz wait_gate2 ; " - "mov al,0x0FE ; " - "out 0x60,al ; " - "xor rax,rax ; " - "lidt [rax] ; " - "reset_wait: ; " - "jmp reset_wait ; " - ".att_syntax; "); - } -} // namespace Kernel +/// @brief Reboot machine in either ACPI or by triple faulting. +/// @return nothing it's a reboot. +Void ACPIFactoryInterface::Reboot() { + asm volatile( + ".intel_syntax noprefix; " + "rt_reset_hardware:; " + "cli; " + "wait_gate1: ; " + "in al,0x64 ; " + "and al,2 ; " + "jnz wait_gate1 ; " + "mov al,0x0D1 ; " + "out 0x64,al ; " + "wait_gate2: ; " + "in al,0x64 ; " + "and al,2 ; " + "jnz wait_gate2 ; " + "mov al,0x0FE ; " + "out 0x60,al ; " + "xor rax,rax ; " + "lidt [rax] ; " + "reset_wait: ; " + "jmp reset_wait ; " + ".att_syntax; "); +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/AMD64/HalAPICController.cc b/dev/kernel/HALKit/AMD64/HalAPICController.cc index 5a020014..758e2f52 100644 --- a/dev/kernel/HALKit/AMD64/HalAPICController.cc +++ b/dev/kernel/HALKit/AMD64/HalAPICController.cc @@ -1,44 +1,38 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ -#include #include +#include #define cIOAPICRegVal (4) #define cIOAPICRegReg (0) -namespace Kernel::HAL -{ - APICController::APICController(VoidPtr base) - : fApic(base) - { - } - - /// @brief Read from APIC controller. - /// @param reg register. - UInt32 APICController::Read(UInt32 reg) noexcept - { - MUST_PASS(this->fApic); - - UInt32 volatile* io_apic = (UInt32 volatile*)this->fApic; - io_apic[cIOAPICRegReg] = (reg & 0xFF); - - return io_apic[cIOAPICRegVal]; - } - - /// @brief Write to APIC controller. - /// @param reg register. - /// @param value value. - Void APICController::Write(UInt32 reg, UInt32 value) noexcept - { - MUST_PASS(this->fApic); - - UInt32 volatile* io_apic = (UInt32 volatile*)this->fApic; - - io_apic[cIOAPICRegReg] = (reg & 0xFF); - io_apic[cIOAPICRegVal] = value; - } -} // namespace Kernel::HAL +namespace Kernel::HAL { +APICController::APICController(VoidPtr base) : fApic(base) {} + +/// @brief Read from APIC controller. +/// @param reg register. +UInt32 APICController::Read(UInt32 reg) noexcept { + MUST_PASS(this->fApic); + + UInt32 volatile* io_apic = (UInt32 volatile*) this->fApic; + io_apic[cIOAPICRegReg] = (reg & 0xFF); + + return io_apic[cIOAPICRegVal]; +} + +/// @brief Write to APIC controller. +/// @param reg register. +/// @param value value. +Void APICController::Write(UInt32 reg, UInt32 value) noexcept { + MUST_PASS(this->fApic); + + UInt32 volatile* io_apic = (UInt32 volatile*) this->fApic; + + io_apic[cIOAPICRegReg] = (reg & 0xFF); + io_apic[cIOAPICRegVal] = value; +} +} // namespace Kernel::HAL diff --git a/dev/kernel/HALKit/AMD64/HalApplicationProcessor.cc b/dev/kernel/HALKit/AMD64/HalApplicationProcessor.cc index fc50380a..dd9a36ed 100644 --- a/dev/kernel/HALKit/AMD64/HalApplicationProcessor.cc +++ b/dev/kernel/HALKit/AMD64/HalApplicationProcessor.cc @@ -1,29 +1,28 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ -#include -#include -#include #include +#include #include +#include #include #include -#include #include -#include +#include +#include #define kAPIC_Signature "APIC" -#define kAPIC_ICR_Low 0x300 -#define kAPIC_ICR_High 0x310 +#define kAPIC_ICR_Low 0x300 +#define kAPIC_ICR_High 0x310 #define kAPIC_SIPI_Vector 0x00500 #define kAPIC_EIPI_Vector 0x00400 -#define kAPIC_BASE_MSR 0x1B -#define kAPIC_BASE_MSR_BSP 0x100 +#define kAPIC_BASE_MSR 0x1B +#define kAPIC_BASE_MSR_BSP 0x100 #define kAPIC_BASE_MSR_ENABLE 0x800 /// @note: _hal_switch_context is internal @@ -34,231 +33,208 @@ /////////////////////////////////////////////////////////////////////////////////////// -namespace Kernel::HAL -{ - struct HAL_APIC_MADT; - struct HAL_HARDWARE_THREAD; - - struct HAL_HARDWARE_THREAD final - { - HAL::StackFramePtr mFramePtr; - ProcessID mProcessID{0}; - UInt8 mCoreID{0}; - }; - - STATIC HAL_APIC_MADT* kMADTBlock = nullptr; - STATIC Bool kSMPAware = false; - STATIC Int64 kSMPCount = 0; - - STATIC UIntPtr kApicBaseAddress = 0UL; - - STATIC Int32 kSMPInterrupt = 0; - STATIC UInt64 kAPICLocales[kSchedProcessLimitPerTeam] = {0}; - STATIC VoidPtr kRawMADT = nullptr; - - /// @brief Multiple APIC Descriptor Table. - struct HAL_APIC_MADT final SDT_OBJECT - { - UInt32 Address; // Madt address - UInt8 Flags; // Madt flags - - struct - { - UInt8 Type; - UInt8 Len; - - union APIC { - struct IOAPIC - { - UInt8 IoID; - UInt8 Zero; - UInt32 IoAddress; - UInt32 GISBase; - } IOAPIC; - - struct LAPIC_NMI - { - UInt8 Source; - UInt8 IRQSource; - UInt32 GSI; - UInt16 Flags; - } LApicNMI; - - struct LAPIC - { - UInt8 ProcessorID; - UInt16 Flags; - UInt8 LINT; - } LAPIC; - - struct LAPIC_OVERRIDE - { - UInt16 Reserved; - UInt64 Address; - } LApicOverride; - - struct LAPIC_X2 - { - UInt16 Reserved; - UInt32 x2APICID; - UInt32 Flags; - UInt32 AcpiID; - } LocalApicX2; - } Apic; - } List[1]; // Records List - }; - - /////////////////////////////////////////////////////////////////////////////////////// - - /***********************************************************************************/ - /// @brief Send IPI command to APIC. - /// @param apic_id programmable interrupt controller id. - /// @param vector vector interrupt. - /// @param target target APIC adress. - /// @return - /***********************************************************************************/ - - Void hal_send_start_ipi(UInt32 target, UInt32 apic_id) - { - Kernel::ke_dma_write(target, kAPIC_ICR_High, apic_id << 24); - Kernel::ke_dma_write(target, kAPIC_ICR_Low, 0x00000500 | 0x00004000 | 0x00000000); - - while (Kernel::ke_dma_read(target, kAPIC_ICR_Low) & 0x1000) - { - ; - } - } - - /***********************************************************************************/ - /// @brief Send end IPI for CPU. - /// @param apic_id - /// @param vector - /// @param target - /// @return - /***********************************************************************************/ - Void hal_send_sipi(UInt32 target, UInt32 apic_id, UInt8 vector) - { - Kernel::ke_dma_write(target, kAPIC_ICR_High, apic_id << 24); - Kernel::ke_dma_write(target, kAPIC_ICR_Low, 0x00000600 | 0x00004000 | 0x00000000 | vector); - - while (Kernel::ke_dma_read(target, kAPIC_ICR_Low) & 0x1000) - { - NE_UNUSED(0); - } - } - - STATIC HAL_HARDWARE_THREAD kHWThread[kSchedProcessLimitPerTeam] = {{}}; - - EXTERN_C HAL::StackFramePtr mp_get_current_context(Int64 pid) - { - const auto process_index = pid % kSchedProcessLimitPerTeam; - - return kHWThread[process_index].mFramePtr; - } - - EXTERN_C BOOL mp_register_process(HAL::StackFramePtr stack_frame, ProcessID pid) - { - MUST_PASS(stack_frame); - - const auto process_index = pid % kSchedProcessLimitPerTeam; - - kHWThread[process_index].mFramePtr = stack_frame; - kHWThread[process_index].mProcessID = pid; - - kHWThread[process_index].mCoreID = kAPICLocales[0]; - - hal_send_sipi(kApicBaseAddress, kHWThread[process_index].mCoreID, (UInt8)(((UIntPtr)stack_frame->BP) >> 12)); - - return YES; - } - - /***********************************************************************************/ - /// @brief Is the current config SMP aware? - /// @return True if YES, False if not. - /***********************************************************************************/ - Bool mp_is_smp(Void) noexcept - { - return kSMPAware; - } - - /***********************************************************************************/ - /// @brief Assembly symbol to bootstrap AP. - /***********************************************************************************/ - EXTERN_C Char* hal_ap_blob_start; - - /***********************************************************************************/ - /// @brief Assembly symbol to bootstrap AP. - /***********************************************************************************/ - EXTERN_C Char* hal_ap_blob_end; - - /***********************************************************************************/ - /// @brief Fetch and enable SMP scheduler. - /// @param vendor_ptr SMP containing structure. - /***********************************************************************************/ - Void mp_init_cores(VoidPtr vendor_ptr) noexcept - { - if (!vendor_ptr) - return; - - if (!kHandoverHeader->f_HardwareTables.f_MultiProcessingEnabled) - { - kSMPAware = NO; - return; - } - - auto hw_and_pow_int = PowerFactoryInterface(vendor_ptr); - kRawMADT = hw_and_pow_int.Find(kAPIC_Signature).Leak().Leak(); - - kMADTBlock = reinterpret_cast(kRawMADT); - kSMPAware = NO; - - if (kMADTBlock) - { - SizeT index = 1; - - kSMPInterrupt = 0; - kSMPCount = 0; - - kout << "SMP: Starting APs...\r"; - - kApicBaseAddress = kMADTBlock->Address; - - while (Yes) - { - /// @note Anything bigger than x2APIC type doesn't exist. - if (kMADTBlock->List[index].Type > 9 || - kSMPCount > kSchedProcessLimitPerTeam) - break; - - switch (kMADTBlock->List[index].Type) - { - case 0x00: { - if (kMADTBlock->List[kSMPCount].Apic.LAPIC.ProcessorID < 1) - break; - - kAPICLocales[kSMPCount] = kMADTBlock->List[kSMPCount].Apic.LAPIC.ProcessorID; - (Void)(kout << "SMP: APIC ID: " << number(kAPICLocales[kSMPCount]) << kendl); +namespace Kernel::HAL { +struct HAL_APIC_MADT; +struct HAL_HARDWARE_THREAD; + +struct HAL_HARDWARE_THREAD final { + HAL::StackFramePtr mFramePtr; + ProcessID mProcessID{0}; + UInt8 mCoreID{0}; +}; + +STATIC HAL_APIC_MADT* kMADTBlock = nullptr; +STATIC Bool kSMPAware = false; +STATIC Int64 kSMPCount = 0; + +STATIC UIntPtr kApicBaseAddress = 0UL; + +STATIC Int32 kSMPInterrupt = 0; +STATIC UInt64 kAPICLocales[kSchedProcessLimitPerTeam] = {0}; +STATIC VoidPtr kRawMADT = nullptr; + +/// @brief Multiple APIC Descriptor Table. +struct HAL_APIC_MADT final SDT_OBJECT { + UInt32 Address; // Madt address + UInt8 Flags; // Madt flags + + struct { + UInt8 Type; + UInt8 Len; + + union APIC { + struct IOAPIC { + UInt8 IoID; + UInt8 Zero; + UInt32 IoAddress; + UInt32 GISBase; + } IOAPIC; + + struct LAPIC_NMI { + UInt8 Source; + UInt8 IRQSource; + UInt32 GSI; + UInt16 Flags; + } LApicNMI; + + struct LAPIC { + UInt8 ProcessorID; + UInt16 Flags; + UInt8 LINT; + } LAPIC; + + struct LAPIC_OVERRIDE { + UInt16 Reserved; + UInt64 Address; + } LApicOverride; + + struct LAPIC_X2 { + UInt16 Reserved; + UInt32 x2APICID; + UInt32 Flags; + UInt32 AcpiID; + } LocalApicX2; + } Apic; + } List[1]; // Records List +}; + +/////////////////////////////////////////////////////////////////////////////////////// + +/***********************************************************************************/ +/// @brief Send IPI command to APIC. +/// @param apic_id programmable interrupt controller id. +/// @param vector vector interrupt. +/// @param target target APIC adress. +/// @return +/***********************************************************************************/ + +Void hal_send_start_ipi(UInt32 target, UInt32 apic_id) { + Kernel::ke_dma_write(target, kAPIC_ICR_High, apic_id << 24); + Kernel::ke_dma_write(target, kAPIC_ICR_Low, 0x00000500 | 0x00004000 | 0x00000000); + + while (Kernel::ke_dma_read(target, kAPIC_ICR_Low) & 0x1000) { + ; + } +} + +/***********************************************************************************/ +/// @brief Send end IPI for CPU. +/// @param apic_id +/// @param vector +/// @param target +/// @return +/***********************************************************************************/ +Void hal_send_sipi(UInt32 target, UInt32 apic_id, UInt8 vector) { + Kernel::ke_dma_write(target, kAPIC_ICR_High, apic_id << 24); + Kernel::ke_dma_write(target, kAPIC_ICR_Low, + 0x00000600 | 0x00004000 | 0x00000000 | vector); + + while (Kernel::ke_dma_read(target, kAPIC_ICR_Low) & 0x1000) { + NE_UNUSED(0); + } +} + +STATIC HAL_HARDWARE_THREAD kHWThread[kSchedProcessLimitPerTeam] = {{}}; + +EXTERN_C HAL::StackFramePtr mp_get_current_context(Int64 pid) { + const auto process_index = pid % kSchedProcessLimitPerTeam; + + return kHWThread[process_index].mFramePtr; +} + +EXTERN_C BOOL mp_register_process(HAL::StackFramePtr stack_frame, ProcessID pid) { + MUST_PASS(stack_frame); + + const auto process_index = pid % kSchedProcessLimitPerTeam; + + kHWThread[process_index].mFramePtr = stack_frame; + kHWThread[process_index].mProcessID = pid; + + kHWThread[process_index].mCoreID = kAPICLocales[0]; + + hal_send_sipi(kApicBaseAddress, kHWThread[process_index].mCoreID, + (UInt8) (((UIntPtr) stack_frame->BP) >> 12)); + + return YES; +} + +/***********************************************************************************/ +/// @brief Is the current config SMP aware? +/// @return True if YES, False if not. +/***********************************************************************************/ +Bool mp_is_smp(Void) noexcept { + return kSMPAware; +} + +/***********************************************************************************/ +/// @brief Assembly symbol to bootstrap AP. +/***********************************************************************************/ +EXTERN_C Char* hal_ap_blob_start; + +/***********************************************************************************/ +/// @brief Assembly symbol to bootstrap AP. +/***********************************************************************************/ +EXTERN_C Char* hal_ap_blob_end; + +/***********************************************************************************/ +/// @brief Fetch and enable SMP scheduler. +/// @param vendor_ptr SMP containing structure. +/***********************************************************************************/ +Void mp_init_cores(VoidPtr vendor_ptr) noexcept { + if (!vendor_ptr) return; + + if (!kHandoverHeader->f_HardwareTables.f_MultiProcessingEnabled) { + kSMPAware = NO; + return; + } + + auto hw_and_pow_int = PowerFactoryInterface(vendor_ptr); + kRawMADT = hw_and_pow_int.Find(kAPIC_Signature).Leak().Leak(); + + kMADTBlock = reinterpret_cast(kRawMADT); + kSMPAware = NO; + + if (kMADTBlock) { + SizeT index = 1; + + kSMPInterrupt = 0; + kSMPCount = 0; + + kout << "SMP: Starting APs...\r"; + + kApicBaseAddress = kMADTBlock->Address; + + while (Yes) { + /// @note Anything bigger than x2APIC type doesn't exist. + if (kMADTBlock->List[index].Type > 9 || kSMPCount > kSchedProcessLimitPerTeam) break; + + switch (kMADTBlock->List[index].Type) { + case 0x00: { + if (kMADTBlock->List[kSMPCount].Apic.LAPIC.ProcessorID < 1) break; + + kAPICLocales[kSMPCount] = kMADTBlock->List[kSMPCount].Apic.LAPIC.ProcessorID; + (Void)(kout << "SMP: APIC ID: " << number(kAPICLocales[kSMPCount]) << kendl); - ++kSMPCount; - break; - } - default: - break; - } + ++kSMPCount; + break; + } + default: + break; + } - ++index; - } + ++index; + } - (Void)(kout << "SMP: Number of APs: " << number(kSMPCount) << kendl); + (Void)(kout << "SMP: Number of APs: " << number(kSMPCount) << kendl); - // Kernel is now SMP aware. - // That means that the scheduler is now available (on MP Kernels) + // Kernel is now SMP aware. + // That means that the scheduler is now available (on MP Kernels) - kSMPAware = true; + kSMPAware = true; - /// TODO: Notify Boot AP that it must start. - } - } -} // namespace Kernel::HAL + /// TODO: Notify Boot AP that it must start. + } +} +} // namespace Kernel::HAL /////////////////////////////////////////////////////////////////////////////////////// diff --git a/dev/kernel/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc b/dev/kernel/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc index 4c873554..641fb8e4 100644 --- a/dev/kernel/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc +++ b/dev/kernel/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -13,232 +13,201 @@ STATIC BOOL kIsScheduling = NO; /// @brief Handle GPF fault. /// @param rsp -EXTERN_C void idt_handle_gpf(Kernel::UIntPtr rsp) -{ - auto process = Kernel::UserProcessScheduler::The().CurrentProcess(); +EXTERN_C void idt_handle_gpf(Kernel::UIntPtr rsp) { + auto process = Kernel::UserProcessScheduler::The().CurrentProcess(); - if (process.Leak().Status != Kernel::ProcessStatusKind::kRunning) - return; + if (process.Leak().Status != Kernel::ProcessStatusKind::kRunning) return; - kIsScheduling = NO; + kIsScheduling = NO; - Kernel::kout << "Kernel: General Protection Fault.\r"; + Kernel::kout << "Kernel: General Protection Fault.\r"; - process.Leak().Signal.SignalArg = rsp; - process.Leak().Signal.SignalID = SIGKILL; - process.Leak().Signal.Status = process.Leak().Status; + process.Leak().Signal.SignalArg = rsp; + process.Leak().Signal.SignalID = SIGKILL; + process.Leak().Signal.Status = process.Leak().Status; - Kernel::kout << "Kernel: SIGKILL status.\r"; + Kernel::kout << "Kernel: SIGKILL status.\r"; - process.Leak().Status = Kernel::ProcessStatusKind::kKilled; + process.Leak().Status = Kernel::ProcessStatusKind::kKilled; - process.Leak().Crash(); + process.Leak().Crash(); } /// @brief Handle page fault. /// @param rsp -EXTERN_C void idt_handle_pf(Kernel::UIntPtr rsp) -{ - auto process = Kernel::UserProcessScheduler::The().CurrentProcess(); +EXTERN_C void idt_handle_pf(Kernel::UIntPtr rsp) { + auto process = Kernel::UserProcessScheduler::The().CurrentProcess(); - if (process.Leak().Status != Kernel::ProcessStatusKind::kRunning) - return; + if (process.Leak().Status != Kernel::ProcessStatusKind::kRunning) return; - kIsScheduling = NO; + kIsScheduling = NO; - Kernel::kout << "Kernel: Page Fault.\r"; - Kernel::kout << "Kernel: SIGKILL\r"; + Kernel::kout << "Kernel: Page Fault.\r"; + Kernel::kout << "Kernel: SIGKILL\r"; - process.Leak().Signal.SignalArg = rsp; - process.Leak().Signal.SignalID = SIGKILL; - process.Leak().Signal.Status = process.Leak().Status; + process.Leak().Signal.SignalArg = rsp; + process.Leak().Signal.SignalID = SIGKILL; + process.Leak().Signal.Status = process.Leak().Status; - process.Leak().Status = Kernel::ProcessStatusKind::kKilled; + process.Leak().Status = Kernel::ProcessStatusKind::kKilled; - process.Leak().Crash(); + process.Leak().Crash(); } -namespace Kernel::Detail -{ - constexpr static Int32 kTimeoutCount = 100000UL; +namespace Kernel::Detail { +constexpr static Int32 kTimeoutCount = 100000UL; } /// @brief Handle scheduler interrupt. -EXTERN_C void idt_handle_scheduler(Kernel::UIntPtr rsp) -{ - NE_UNUSED(rsp); +EXTERN_C void idt_handle_scheduler(Kernel::UIntPtr rsp) { + NE_UNUSED(rsp); - static Kernel::Int64 try_count_before_brute = Kernel::Detail::kTimeoutCount; + static Kernel::Int64 try_count_before_brute = Kernel::Detail::kTimeoutCount; - while (kIsScheduling) - { - --try_count_before_brute; + while (kIsScheduling) { + --try_count_before_brute; - if (try_count_before_brute < 1) - break; - } + if (try_count_before_brute < 1) break; + } - try_count_before_brute = Kernel::Detail::kTimeoutCount; - kIsScheduling = YES; + try_count_before_brute = Kernel::Detail::kTimeoutCount; + kIsScheduling = YES; - Kernel::UserProcessHelper::StartScheduling(); + Kernel::UserProcessHelper::StartScheduling(); - kIsScheduling = NO; + kIsScheduling = NO; } /// @brief Handle math fault. /// @param rsp -EXTERN_C void idt_handle_math(Kernel::UIntPtr rsp) -{ - auto process = Kernel::UserProcessScheduler::The().CurrentProcess(); +EXTERN_C void idt_handle_math(Kernel::UIntPtr rsp) { + auto process = Kernel::UserProcessScheduler::The().CurrentProcess(); - if (process.Leak().Status != Kernel::ProcessStatusKind::kRunning) - return; + if (process.Leak().Status != Kernel::ProcessStatusKind::kRunning) return; - kIsScheduling = NO; + kIsScheduling = NO; - Kernel::kout << "Kernel: Math error (division by zero?).\r"; + Kernel::kout << "Kernel: Math error (division by zero?).\r"; - process.Leak().Signal.SignalArg = rsp; - process.Leak().Signal.SignalID = SIGKILL; - process.Leak().Signal.Status = process.Leak().Status; + process.Leak().Signal.SignalArg = rsp; + process.Leak().Signal.SignalID = SIGKILL; + process.Leak().Signal.Status = process.Leak().Status; - Kernel::kout << "Kernel: SIGKILL status.\r"; + Kernel::kout << "Kernel: SIGKILL status.\r"; - process.Leak().Status = Kernel::ProcessStatusKind::kKilled; + process.Leak().Status = Kernel::ProcessStatusKind::kKilled; - process.Leak().Crash(); + process.Leak().Crash(); } /// @brief Handle any generic fault. /// @param rsp -EXTERN_C void idt_handle_generic(Kernel::UIntPtr rsp) -{ - auto process = Kernel::UserProcessScheduler::The().CurrentProcess(); +EXTERN_C void idt_handle_generic(Kernel::UIntPtr rsp) { + auto process = Kernel::UserProcessScheduler::The().CurrentProcess(); - if (process.Leak().Status != Kernel::ProcessStatusKind::kRunning) - return; + if (process.Leak().Status != Kernel::ProcessStatusKind::kRunning) return; - kIsScheduling = NO; + kIsScheduling = NO; - Kernel::kout << "Kernel: Generic Process Fault.\r"; + Kernel::kout << "Kernel: Generic Process Fault.\r"; - process.Leak().Signal.SignalArg = rsp; - process.Leak().Signal.SignalID = SIGKILL; - process.Leak().Signal.Status = process.Leak().Status; + process.Leak().Signal.SignalArg = rsp; + process.Leak().Signal.SignalID = SIGKILL; + process.Leak().Signal.Status = process.Leak().Status; - Kernel::kout << "Kernel: SIGKILL status.\r"; + Kernel::kout << "Kernel: SIGKILL status.\r"; - process.Leak().Status = Kernel::ProcessStatusKind::kKilled; + process.Leak().Status = Kernel::ProcessStatusKind::kKilled; - process.Leak().Crash(); + process.Leak().Crash(); } -EXTERN_C Kernel::Void idt_handle_breakpoint(Kernel::UIntPtr rip) -{ - auto process = Kernel::UserProcessScheduler::The().CurrentProcess(); +EXTERN_C Kernel::Void idt_handle_breakpoint(Kernel::UIntPtr rip) { + auto process = Kernel::UserProcessScheduler::The().CurrentProcess(); - if (process.Leak().Status != Kernel::ProcessStatusKind::kRunning) - { - Kernel::kout << "Kernel: SIGTRAP\r"; + if (process.Leak().Status != Kernel::ProcessStatusKind::kRunning) { + Kernel::kout << "Kernel: SIGTRAP\r"; - while (YES) - ; - } + while (YES); + } - kIsScheduling = NO; + kIsScheduling = NO; - (Void)(Kernel::kout << "Kernel: Process RIP: " << Kernel::hex_number(rip) << Kernel::kendl); - Kernel::kout << "Kernel: SIGTRAP\r"; + (Void)(Kernel::kout << "Kernel: Process RIP: " << Kernel::hex_number(rip) << Kernel::kendl); + Kernel::kout << "Kernel: SIGTRAP\r"; - process.Leak().Signal.SignalArg = rip; - process.Leak().Signal.SignalID = SIGTRAP; + process.Leak().Signal.SignalArg = rip; + process.Leak().Signal.SignalID = SIGTRAP; - process.Leak().Signal.Status = process.Leak().Status; + process.Leak().Signal.Status = process.Leak().Status; - Kernel::kout << "Kernel: SIGTRAP status.\r"; + Kernel::kout << "Kernel: SIGTRAP status.\r"; - process.Leak().Status = Kernel::ProcessStatusKind::kFrozen; + process.Leak().Status = Kernel::ProcessStatusKind::kFrozen; } /// @brief Handle #UD fault. /// @param rsp -EXTERN_C void idt_handle_ud(Kernel::UIntPtr rsp) -{ - auto process = Kernel::UserProcessScheduler::The().CurrentProcess(); +EXTERN_C void idt_handle_ud(Kernel::UIntPtr rsp) { + auto process = Kernel::UserProcessScheduler::The().CurrentProcess(); - if (process.Leak().Status != Kernel::ProcessStatusKind::kRunning) - return; + if (process.Leak().Status != Kernel::ProcessStatusKind::kRunning) return; - kIsScheduling = NO; + kIsScheduling = NO; - Kernel::kout << "Kernel: Undefined Opcode.\r"; + Kernel::kout << "Kernel: Undefined Opcode.\r"; - process.Leak().Signal.SignalArg = rsp; - process.Leak().Signal.SignalID = SIGKILL; - process.Leak().Signal.Status = process.Leak().Status; + process.Leak().Signal.SignalArg = rsp; + process.Leak().Signal.SignalID = SIGKILL; + process.Leak().Signal.Status = process.Leak().Status; - Kernel::kout << "Kernel: SIGKILL status.\r"; + Kernel::kout << "Kernel: SIGKILL status.\r"; - process.Leak().Status = Kernel::ProcessStatusKind::kKilled; + process.Leak().Status = Kernel::ProcessStatusKind::kKilled; - process.Leak().Crash(); + process.Leak().Crash(); } /// @brief Enter syscall from assembly. /// @param stack the stack pushed from assembly routine. /// @return nothing. -EXTERN_C Kernel::Void hal_system_call_enter(Kernel::UIntPtr rcx_syscall_index, Kernel::UIntPtr rdx_syscall_struct) -{ - if (rcx_syscall_index < kSysCalls.Count()) - { - Kernel::kout << "syscall: Enter Syscall.\r"; - - if (kSysCalls[rcx_syscall_index].fHooked) - { - if (kSysCalls[rcx_syscall_index].fProc) - { - (kSysCalls[rcx_syscall_index].fProc)((Kernel::VoidPtr)rdx_syscall_struct); - } - else - { - Kernel::kout << "syscall: syscall isn't valid at all! (is nullptr)\r"; - } - } - else - { - Kernel::kout << "syscall: syscall isn't hooked at all! (is set to false)\r"; - } - - Kernel::kout << "syscall: Exit Syscall.\r"; - } +EXTERN_C Kernel::Void hal_system_call_enter(Kernel::UIntPtr rcx_syscall_index, + Kernel::UIntPtr rdx_syscall_struct) { + if (rcx_syscall_index < kSysCalls.Count()) { + Kernel::kout << "syscall: Enter Syscall.\r"; + + if (kSysCalls[rcx_syscall_index].fHooked) { + if (kSysCalls[rcx_syscall_index].fProc) { + (kSysCalls[rcx_syscall_index].fProc)((Kernel::VoidPtr) rdx_syscall_struct); + } else { + Kernel::kout << "syscall: syscall isn't valid at all! (is nullptr)\r"; + } + } else { + Kernel::kout << "syscall: syscall isn't hooked at all! (is set to false)\r"; + } + + Kernel::kout << "syscall: Exit Syscall.\r"; + } } /// @brief Enter Kernel call from assembly (DDK only). /// @param stack the stack pushed from assembly routine. /// @return nothing. -EXTERN_C Kernel::Void hal_kernel_call_enter(Kernel::UIntPtr rcx_kerncall_index, Kernel::UIntPtr rdx_kerncall_struct) -{ - if (rcx_kerncall_index < kKernCalls.Count()) - { - Kernel::kout << "kerncall: Enter Kernel Call List.\r"; - - if (kKernCalls[rcx_kerncall_index].fHooked) - { - if (kKernCalls[rcx_kerncall_index].fProc) - { - (kKernCalls[rcx_kerncall_index].fProc)((Kernel::VoidPtr)rdx_kerncall_struct); - } - else - { - Kernel::kout << "kerncall: Kernel call isn't valid at all! (is nullptr)\r"; - } - } - else - { - Kernel::kout << "kerncall: Kernel call isn't hooked at all! (is set to false)\r"; - } - - Kernel::kout << "kerncall: Exit Kernel Call List.\r"; - } +EXTERN_C Kernel::Void hal_kernel_call_enter(Kernel::UIntPtr rcx_kerncall_index, + Kernel::UIntPtr rdx_kerncall_struct) { + if (rcx_kerncall_index < kKernCalls.Count()) { + Kernel::kout << "kerncall: Enter Kernel Call List.\r"; + + if (kKernCalls[rcx_kerncall_index].fHooked) { + if (kKernCalls[rcx_kerncall_index].fProc) { + (kKernCalls[rcx_kerncall_index].fProc)((Kernel::VoidPtr) rdx_kerncall_struct); + } else { + Kernel::kout << "kerncall: Kernel call isn't valid at all! (is nullptr)\r"; + } + } else { + Kernel::kout << "kerncall: Kernel call isn't hooked at all! (is set to false)\r"; + } + + Kernel::kout << "kerncall: Exit Kernel Call List.\r"; + } } diff --git a/dev/kernel/HALKit/AMD64/HalDebugOutput.cc b/dev/kernel/HALKit/AMD64/HalDebugOutput.cc index 84c8c348..9d290708 100644 --- a/dev/kernel/HALKit/AMD64/HalDebugOutput.cc +++ b/dev/kernel/HALKit/AMD64/HalDebugOutput.cc @@ -1,193 +1,170 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #include #include -#include #include +#include #include #include -namespace Kernel -{ - enum CommStatus : UInt16 - { - kStateInvalid, - kStateReady = 0xCF, - kStateTransmit = 0xFC, - kStateCnt = 3 - }; - - namespace Detail - { - constexpr const UInt16 kPort = 0x3F8; - static UInt16 kState = kStateInvalid; - - /// @brief Init COM1. - /// @return - template - bool hal_serial_init() noexcept - { - if (kState == kStateReady || kState == kStateTransmit) - return true; - - HAL::rt_out8(PORT + 1, 0x00); // Disable all interrupts - HAL::rt_out8(PORT + 3, 0x80); // Enable DLAB (set baud rate divisor) - HAL::rt_out8(PORT + 0, 0x03); // Set divisor to 3 (lo byte) 38400 baud - HAL::rt_out8(PORT + 1, 0x00); // (hi byte) - HAL::rt_out8(PORT + 3, 0x03); // 8 bits, no parity, one stop bit - HAL::rt_out8(PORT + 2, 0xC7); // Enable FIFO, clear them, with 14-byte threshold - HAL::rt_out8(PORT + 4, 0x0B); // IRQs enabled, RTS/DSR set - HAL::rt_out8(PORT + 4, 0x1E); // Set in loopback mode, test the serial chip - HAL::rt_out8(PORT + 0, 0xAE); // Test serial chip (send byte 0xAE and check if - // serial returns same byte) - - // Check if serial is faulty (i.e: not same byte as sent) - if (HAL::rt_in8(PORT) != 0xAE) - { - return false; - } - - kState = kStateReady; - - // If serial is not faulty set it in normal operation mode - // (not-loopback with IRQs enabled and OUT#1 and OUT#2 bits enabled) - HAL::rt_out8(PORT + 4, 0x0F); - - return true; - } - } // namespace Detail - - TerminalDevice::~TerminalDevice() = default; - - EXTERN_C void ke_io_write(IDeviceObject* obj, const Char* bytes) - { - NE_UNUSED(obj); +namespace Kernel { +enum CommStatus : UInt16 { + kStateInvalid, + kStateReady = 0xCF, + kStateTransmit = 0xFC, + kStateCnt = 3 +}; + +namespace Detail { + constexpr const UInt16 kPort = 0x3F8; + static UInt16 kState = kStateInvalid; + + /// @brief Init COM1. + /// @return + template + bool hal_serial_init() noexcept { + if (kState == kStateReady || kState == kStateTransmit) return true; + + HAL::rt_out8(PORT + 1, 0x00); // Disable all interrupts + HAL::rt_out8(PORT + 3, 0x80); // Enable DLAB (set baud rate divisor) + HAL::rt_out8(PORT + 0, 0x03); // Set divisor to 3 (lo byte) 38400 baud + HAL::rt_out8(PORT + 1, 0x00); // (hi byte) + HAL::rt_out8(PORT + 3, 0x03); // 8 bits, no parity, one stop bit + HAL::rt_out8(PORT + 2, 0xC7); // Enable FIFO, clear them, with 14-byte threshold + HAL::rt_out8(PORT + 4, 0x0B); // IRQs enabled, RTS/DSR set + HAL::rt_out8(PORT + 4, 0x1E); // Set in loopback mode, test the serial chip + HAL::rt_out8(PORT + 0, 0xAE); // Test serial chip (send byte 0xAE and check if + // serial returns same byte) + + // Check if serial is faulty (i.e: not same byte as sent) + if (HAL::rt_in8(PORT) != 0xAE) { + return false; + } + + kState = kStateReady; + + // If serial is not faulty set it in normal operation mode + // (not-loopback with IRQs enabled and OUT#1 and OUT#2 bits enabled) + HAL::rt_out8(PORT + 4, 0x0F); + + return true; + } +} // namespace Detail + +TerminalDevice::~TerminalDevice() = default; + +EXTERN_C void ke_io_write(IDeviceObject* obj, const Char* bytes) { + NE_UNUSED(obj); #ifdef __DEBUG__ - Detail::hal_serial_init(); + Detail::hal_serial_init(); - if (!bytes || Detail::kState != kStateReady) - return; + if (!bytes || Detail::kState != kStateReady) return; - if (*bytes == 0) - return; + if (*bytes == 0) return; - Detail::kState = kStateTransmit; + Detail::kState = kStateTransmit; - SizeT index = 0; - SizeT len = 0; + SizeT index = 0; + SizeT len = 0; - index = 0; - len = rt_string_len(bytes, 256U); + index = 0; + len = rt_string_len(bytes, 256U); - static SizeT x = kFontSizeX, y = kFontSizeY; + static SizeT x = kFontSizeX, y = kFontSizeY; - static BOOL not_important = YES; + static BOOL not_important = YES; - while (index < len) - { - if (bytes[index] == '\r') - HAL::rt_out8(Detail::kPort, '\r'); + while (index < len) { + if (bytes[index] == '\r') HAL::rt_out8(Detail::kPort, '\r'); - HAL::rt_out8(Detail::kPort, bytes[index] == '\r' ? '\n' : bytes[index]); + HAL::rt_out8(Detail::kPort, bytes[index] == '\r' ? '\n' : bytes[index]); - char tmp_str[2]; - tmp_str[0] = bytes[index]; - tmp_str[1] = 0; + char tmp_str[2]; + tmp_str[0] = bytes[index]; + tmp_str[1] = 0; - if (bytes[index] == '*') - { - if (not_important) - not_important = NO; - else - not_important = YES; + if (bytes[index] == '*') { + if (not_important) + not_important = NO; + else + not_important = YES; - ++index; + ++index; - continue; - } + continue; + } - fb_render_string(tmp_str, y, x, not_important ? RGB(0xff, 0xff, 0xff) : RGB(0x00, 0x00, 0xff)); + fb_render_string(tmp_str, y, x, not_important ? RGB(0xff, 0xff, 0xff) : RGB(0x00, 0x00, 0xff)); - if (bytes[index] == '\r') - { - y += kFontSizeY; - x = kFontSizeX; - } + if (bytes[index] == '\r') { + y += kFontSizeY; + x = kFontSizeX; + } - x += kFontSizeX; + x += kFontSizeX; - if (x > kHandoverHeader->f_GOP.f_Width) - { - x = kFontSizeX; - } + if (x > kHandoverHeader->f_GOP.f_Width) { + x = kFontSizeX; + } - if (y > kHandoverHeader->f_GOP.f_Height) - { - y = kFontSizeY; + if (y > kHandoverHeader->f_GOP.f_Height) { + y = kFontSizeY; - FBDrawInRegion(fb_get_clear_clr(), FB::FBAccessibilty::Height(), FB::FBAccessibilty::Width(), - 0, 0); - } + FBDrawInRegion(fb_get_clear_clr(), FB::FBAccessibilty::Height(), FB::FBAccessibilty::Width(), + 0, 0); + } - ++index; - } + ++index; + } - Detail::kState = kStateReady; -#endif // __DEBUG__ - } + Detail::kState = kStateReady; +#endif // __DEBUG__ +} - EXTERN_C void ke_io_read(IDeviceObject*, const Char* bytes) - { +EXTERN_C void ke_io_read(IDeviceObject*, const Char* bytes) { #ifdef __DEBUG__ - Detail::hal_serial_init(); + Detail::hal_serial_init(); - if (!bytes || Detail::kState != kStateReady) - return; + if (!bytes || Detail::kState != kStateReady) return; - Detail::kState = kStateTransmit; + Detail::kState = kStateTransmit; - SizeT index = 0; + SizeT index = 0; - ///! TODO: Look on how to wait for the UART to complete. - while (true) - { - auto in = HAL::rt_in8(Detail::kPort); + ///! TODO: Look on how to wait for the UART to complete. + while (true) { + auto in = HAL::rt_in8(Detail::kPort); - ///! If enter pressed then break. - if (in == 0xD) - { - break; - } + ///! If enter pressed then break. + if (in == 0xD) { + break; + } - if (in < '0' || in < 'A' || in < 'a') - { - if (in != '@' || in != '!' || in != '?' || in != '.' || in != '/' || - in != ':') - { - continue; - } - } + if (in < '0' || in < 'A' || in < 'a') { + if (in != '@' || in != '!' || in != '?' || in != '.' || in != '/' || in != ':') { + continue; + } + } - ((char*)bytes)[index] = in; + ((char*) bytes)[index] = in; - ++index; - } + ++index; + } - ((char*)bytes)[index] = 0; + ((char*) bytes)[index] = 0; - Detail::kState = kStateReady; -#endif // __DEBUG__ - } + Detail::kState = kStateReady; +#endif // __DEBUG__ +} - TerminalDevice TerminalDevice::The() noexcept - { - TerminalDevice out(Kernel::ke_io_write, Kernel::ke_io_read); - return out; - } +TerminalDevice TerminalDevice::The() noexcept { + TerminalDevice out(Kernel::ke_io_write, Kernel::ke_io_read); + return out; +} -} // namespace Kernel +} // namespace Kernel diff --git a/dev/kernel/HALKit/AMD64/HalDebugPort.cc b/dev/kernel/HALKit/AMD64/HalDebugPort.cc index 63bc99bd..6289ff1f 100644 --- a/dev/kernel/HALKit/AMD64/HalDebugPort.cc +++ b/dev/kernel/HALKit/AMD64/HalDebugPort.cc @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -12,31 +12,26 @@ // after that we have start of additional data. -namespace Kernel -{ - void rt_debug_listen(DebuggerPortHeader* theHook) noexcept - { - if (theHook == nullptr) - return; +namespace Kernel { +void rt_debug_listen(DebuggerPortHeader* theHook) noexcept { + if (theHook == nullptr) return; - for (UInt32 i = 0U; i < kDebugMaxPorts; ++i) - { - HAL::rt_out16(theHook->fPort[i], kDebugMag0); - HAL::rt_wait_400ns(); + for (UInt32 i = 0U; i < kDebugMaxPorts; ++i) { + HAL::rt_out16(theHook->fPort[i], kDebugMag0); + HAL::rt_wait_400ns(); - HAL::rt_out16(theHook->fPort[i], kDebugMag1); - HAL::rt_wait_400ns(); + HAL::rt_out16(theHook->fPort[i], kDebugMag1); + HAL::rt_wait_400ns(); - HAL::rt_out16(theHook->fPort[i], kDebugMag2); - HAL::rt_wait_400ns(); + HAL::rt_out16(theHook->fPort[i], kDebugMag2); + HAL::rt_wait_400ns(); - HAL::rt_out16(theHook->fPort[i], kDebugMag3); - HAL::rt_wait_400ns(); + HAL::rt_out16(theHook->fPort[i], kDebugMag3); + HAL::rt_wait_400ns(); - if (HAL::rt_in16(theHook->fPort[i]) != kDebugUnboundPort) - ++theHook->fPortCnt; + if (HAL::rt_in16(theHook->fPort[i]) != kDebugUnboundPort) ++theHook->fPortCnt; - HAL::rt_wait_400ns(); - } - } -} // namespace Kernel + HAL::rt_wait_400ns(); + } +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/AMD64/HalDescriptorLoader.cc b/dev/kernel/HALKit/AMD64/HalDescriptorLoader.cc index f205e766..e6d57be2 100644 --- a/dev/kernel/HALKit/AMD64/HalDescriptorLoader.cc +++ b/dev/kernel/HALKit/AMD64/HalDescriptorLoader.cc @@ -1,21 +1,19 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ -#include #include +#include #include #define kPITDefaultTicks (1000U) -namespace Kernel::HAL -{ - namespace Detail - { - STATIC ::Kernel::Detail::AMD64::InterruptDescriptorAMD64 - kInterruptVectorTable[kKernelIdtSize] = {}; +namespace Kernel::HAL { +namespace Detail { + STATIC ::Kernel::Detail::AMD64::InterruptDescriptorAMD64 kInterruptVectorTable[kKernelIdtSize] = + {}; #if 0 STATIC void hal_set_irq_mask(UInt8 irql) [[maybe_unused]] @@ -36,101 +34,88 @@ namespace Kernel::HAL value = rt_in8(port) | (1 << irql); rt_out8(port, value); } -#endif // make gcc shut up +#endif // make gcc shut up - STATIC void hal_clear_irq_mask(UInt8 irql) [[maybe_unused]] - { - UInt16 port; - UInt8 value; + STATIC void hal_clear_irq_mask(UInt8 irql) [[maybe_unused]] { + UInt16 port; + UInt8 value; - if (irql < 8) - { - port = kPICData; - } - else - { - port = kPIC2Data; - irql -= 8; - } + if (irql < 8) { + port = kPICData; + } else { + port = kPIC2Data; + irql -= 8; + } - value = rt_in8(port) & ~(1 << irql); - rt_out8(port, value); - } + value = rt_in8(port) & ~(1 << irql); + rt_out8(port, value); + } - STATIC Void hal_enable_pit(UInt16 ticks) noexcept - { - if (ticks == 0) - ticks = kPITDefaultTicks; + STATIC Void hal_enable_pit(UInt16 ticks) noexcept { + if (ticks == 0) ticks = kPITDefaultTicks; - // Configure PIT to receieve scheduler interrupts. + // Configure PIT to receieve scheduler interrupts. - UInt16 kPITCommDivisor = kPITFrequency / ticks; // 100 Hz. + UInt16 kPITCommDivisor = kPITFrequency / ticks; // 100 Hz. - HAL::rt_out8(kPITControlPort, 0x36); // Command to PIT - HAL::rt_out8(kPITChannel0Port, kPITCommDivisor & 0xFF); // Send low byte - HAL::rt_out8(kPITChannel0Port, (kPITCommDivisor >> 8) & 0xFF); // Send high byte + HAL::rt_out8(kPITControlPort, 0x36); // Command to PIT + HAL::rt_out8(kPITChannel0Port, kPITCommDivisor & 0xFF); // Send low byte + HAL::rt_out8(kPITChannel0Port, (kPITCommDivisor >> 8) & 0xFF); // Send high byte - hal_clear_irq_mask(32); - } - } // namespace Detail + hal_clear_irq_mask(32); + } +} // namespace Detail - /// @brief Loads the provided Global Descriptor Table. - /// @param gdt - /// @return - Void GDTLoader::Load(Register64& gdt) - { - hal_load_gdt(gdt); - } +/// @brief Loads the provided Global Descriptor Table. +/// @param gdt +/// @return +Void GDTLoader::Load(Register64& gdt) { + hal_load_gdt(gdt); +} - Void IDTLoader::Load(Register64& idt) - { - rt_cli(); +Void IDTLoader::Load(Register64& idt) { + rt_cli(); - const Int16 kPITTickForScheduler = kPITDefaultTicks; + const Int16 kPITTickForScheduler = kPITDefaultTicks; - volatile ::Kernel::UIntPtr** ptr_ivt = (volatile ::Kernel::UIntPtr**)idt.Base; + volatile ::Kernel::UIntPtr** ptr_ivt = (volatile ::Kernel::UIntPtr**) idt.Base; - for (SizeT idt_indx = 0; idt_indx < kKernelIdtSize; ++idt_indx) - { - Detail::kInterruptVectorTable[idt_indx].Selector = kIDTSelector; - Detail::kInterruptVectorTable[idt_indx].Ist = 0; - Detail::kInterruptVectorTable[idt_indx].TypeAttributes = kInterruptGate; - Detail::kInterruptVectorTable[idt_indx].OffsetLow = ((UIntPtr)ptr_ivt[idt_indx] & 0xFFFF); - Detail::kInterruptVectorTable[idt_indx].OffsetMid = (((UIntPtr)ptr_ivt[idt_indx] >> 16) & 0xFFFF); - Detail::kInterruptVectorTable[idt_indx].OffsetHigh = - (((UIntPtr)ptr_ivt[idt_indx] >> 32) & 0xFFFFFFFF); - - Detail::kInterruptVectorTable[idt_indx].Zero = 0; - } + for (SizeT idt_indx = 0; idt_indx < kKernelIdtSize; ++idt_indx) { + Detail::kInterruptVectorTable[idt_indx].Selector = kIDTSelector; + Detail::kInterruptVectorTable[idt_indx].Ist = 0; + Detail::kInterruptVectorTable[idt_indx].TypeAttributes = kInterruptGate; + Detail::kInterruptVectorTable[idt_indx].OffsetLow = ((UIntPtr) ptr_ivt[idt_indx] & 0xFFFF); + Detail::kInterruptVectorTable[idt_indx].OffsetMid = + (((UIntPtr) ptr_ivt[idt_indx] >> 16) & 0xFFFF); + Detail::kInterruptVectorTable[idt_indx].OffsetHigh = + (((UIntPtr) ptr_ivt[idt_indx] >> 32) & 0xFFFFFFFF); + + Detail::kInterruptVectorTable[idt_indx].Zero = 0; + } - idt.Base = (UIntPtr)&Detail::kInterruptVectorTable[0]; - idt.Limit = sizeof(::Kernel::Detail::AMD64::InterruptDescriptorAMD64) * - (kKernelIdtSize); + idt.Base = (UIntPtr) &Detail::kInterruptVectorTable[0]; + idt.Limit = sizeof(::Kernel::Detail::AMD64::InterruptDescriptorAMD64) * (kKernelIdtSize); - Detail::hal_enable_pit(kPITTickForScheduler); + Detail::hal_enable_pit(kPITTickForScheduler); - hal_load_idt(idt); + hal_load_idt(idt); - rt_sti(); - } + rt_sti(); +} - /// @brief Loads the Global Descriptor Table into the CPU. - /// @param gdt GDT register wrapped in a ref. - void GDTLoader::Load(Ref& gdt) - { - if (!gdt) - return; +/// @brief Loads the Global Descriptor Table into the CPU. +/// @param gdt GDT register wrapped in a ref. +void GDTLoader::Load(Ref& gdt) { + if (!gdt) return; - GDTLoader::Load(gdt.Leak()); - } + GDTLoader::Load(gdt.Leak()); +} - /// @brief Loads the IDT, for interupts. - /// @param idt IDT register wrapped in a ref. - void IDTLoader::Load(Ref& idt) - { - if (!idt) - return; +/// @brief Loads the IDT, for interupts. +/// @param idt IDT register wrapped in a ref. +void IDTLoader::Load(Ref& idt) { + if (!idt) return; - IDTLoader::Load(idt.Leak()); - } -} // namespace Kernel::HAL + IDTLoader::Load(idt.Leak()); +} +} // namespace Kernel::HAL diff --git a/dev/kernel/HALKit/AMD64/HalKernelMain.cc b/dev/kernel/HALKit/AMD64/HalKernelMain.cc index 0c680f97..82020520 100644 --- a/dev/kernel/HALKit/AMD64/HalKernelMain.cc +++ b/dev/kernel/HALKit/AMD64/HalKernelMain.cc @@ -1,125 +1,143 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ -#include #include -#include -#include -#include -#include -#include #include -#include -#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include EXTERN_C Kernel::VoidPtr kInterruptVectorTable[]; -STATIC Kernel::Void hal_pre_init_scheduler() noexcept -{ - for (Kernel::SizeT i = 0U; i < Kernel::UserProcessScheduler::The().CurrentTeam().AsArray().Count(); ++i) - { - Kernel::UserProcessScheduler::The().CurrentTeam().AsArray()[i] = Kernel::USER_PROCESS(); - } +STATIC Kernel::Void hal_pre_init_scheduler() noexcept { + for (Kernel::SizeT i = 0U; + i < Kernel::UserProcessScheduler::The().CurrentTeam().AsArray().Count(); ++i) { + Kernel::UserProcessScheduler::The().CurrentTeam().AsArray()[i] = Kernel::USER_PROCESS(); + } } /// @brief Kernel init procedure. -EXTERN_C Int32 hal_init_platform( - Kernel::HEL::BootInfoHeader* handover_hdr) -{ - if (handover_hdr->f_Magic != kHandoverMagic && - handover_hdr->f_Version != kHandoverVersion) - { - return kEfiFail; - } - - kHandoverHeader = handover_hdr; - - FB::fb_clear_video(); - - fw_init_efi((EfiSystemTable*)handover_hdr->f_FirmwareCustomTables[1]); - - Boot::ExitBootServices(handover_hdr->f_HardwareTables.f_ImageKey, handover_hdr->f_HardwareTables.f_ImageHandle); - - /************************************** */ - /* INITIALIZE BIT MAP. */ - /************************************** */ - - kKernelBitMpSize = kHandoverHeader->f_BitMapSize; - kKernelBitMpStart = reinterpret_cast( - reinterpret_cast(kHandoverHeader->f_BitMapStart)); - - /************************************** */ - /* INITIALIZE GDT AND SEGMENTS. */ - /************************************** */ - - STATIC CONST auto kGDTEntriesCount = 6; - - /* GDT, mostly descriptors for user and kernel segments. */ - STATIC Kernel::HAL::Detail::NE_GDT_ENTRY ALIGN(0x08) kGDTArray[kGDTEntriesCount] = { - {.fLimitLow = 0, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0x00, .fFlags = 0x00, .fBaseHigh = 0}, // Null entry - {.fLimitLow = 0x0, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0x9A, .fFlags = 0xAF, .fBaseHigh = 0}, // Kernel code - {.fLimitLow = 0x0, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0x92, .fFlags = 0xCF, .fBaseHigh = 0}, // Kernel data - {.fLimitLow = 0x0, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0xFA, .fFlags = 0xAF, .fBaseHigh = 0}, // User code - {.fLimitLow = 0x0, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0xF2, .fFlags = 0xCF, .fBaseHigh = 0}, // User data - }; - - // Load memory descriptors. - Kernel::HAL::Register64 gdt_reg; - - gdt_reg.Base = reinterpret_cast(kGDTArray); - gdt_reg.Limit = (sizeof(Kernel::HAL::Detail::NE_GDT_ENTRY) * kGDTEntriesCount) - 1; - - //! GDT will load hal_read_init after it successfully loads the segments. - Kernel::HAL::GDTLoader gdt_loader; - gdt_loader.Load(gdt_reg); - - return kEfiFail; +EXTERN_C Int32 hal_init_platform(Kernel::HEL::BootInfoHeader* handover_hdr) { + if (handover_hdr->f_Magic != kHandoverMagic && handover_hdr->f_Version != kHandoverVersion) { + return kEfiFail; + } + + kHandoverHeader = handover_hdr; + + FB::fb_clear_video(); + + fw_init_efi((EfiSystemTable*) handover_hdr->f_FirmwareCustomTables[1]); + + Boot::ExitBootServices(handover_hdr->f_HardwareTables.f_ImageKey, + handover_hdr->f_HardwareTables.f_ImageHandle); + + /************************************** */ + /* INITIALIZE BIT MAP. */ + /************************************** */ + + kKernelBitMpSize = kHandoverHeader->f_BitMapSize; + kKernelBitMpStart = reinterpret_cast( + reinterpret_cast(kHandoverHeader->f_BitMapStart)); + + /************************************** */ + /* INITIALIZE GDT AND SEGMENTS. */ + /************************************** */ + + STATIC CONST auto kGDTEntriesCount = 6; + + /* GDT, mostly descriptors for user and kernel segments. */ + STATIC Kernel::HAL::Detail::NE_GDT_ENTRY ALIGN(0x08) kGDTArray[kGDTEntriesCount] = { + {.fLimitLow = 0, + .fBaseLow = 0, + .fBaseMid = 0, + .fAccessByte = 0x00, + .fFlags = 0x00, + .fBaseHigh = 0}, // Null entry + {.fLimitLow = 0x0, + .fBaseLow = 0, + .fBaseMid = 0, + .fAccessByte = 0x9A, + .fFlags = 0xAF, + .fBaseHigh = 0}, // Kernel code + {.fLimitLow = 0x0, + .fBaseLow = 0, + .fBaseMid = 0, + .fAccessByte = 0x92, + .fFlags = 0xCF, + .fBaseHigh = 0}, // Kernel data + {.fLimitLow = 0x0, + .fBaseLow = 0, + .fBaseMid = 0, + .fAccessByte = 0xFA, + .fFlags = 0xAF, + .fBaseHigh = 0}, // User code + {.fLimitLow = 0x0, + .fBaseLow = 0, + .fBaseMid = 0, + .fAccessByte = 0xF2, + .fFlags = 0xCF, + .fBaseHigh = 0}, // User data + }; + + // Load memory descriptors. + Kernel::HAL::Register64 gdt_reg; + + gdt_reg.Base = reinterpret_cast(kGDTArray); + gdt_reg.Limit = (sizeof(Kernel::HAL::Detail::NE_GDT_ENTRY) * kGDTEntriesCount) - 1; + + //! GDT will load hal_read_init after it successfully loads the segments. + Kernel::HAL::GDTLoader gdt_loader; + gdt_loader.Load(gdt_reg); + + return kEfiFail; } -EXTERN_C Kernel::Void hal_real_init(Kernel::Void) noexcept -{ - hal_pre_init_scheduler(); +EXTERN_C Kernel::Void hal_real_init(Kernel::Void) noexcept { + hal_pre_init_scheduler(); - Kernel::NeFS::fs_init_nefs(); + Kernel::NeFS::fs_init_nefs(); - Kernel::HAL::mp_init_cores(kHandoverHeader->f_HardwareTables.f_VendorPtr); + Kernel::HAL::mp_init_cores(kHandoverHeader->f_HardwareTables.f_VendorPtr); - Kernel::HAL::Register64 idt_reg; - idt_reg.Base = (Kernel::UIntPtr)kInterruptVectorTable; + Kernel::HAL::Register64 idt_reg; + idt_reg.Base = (Kernel::UIntPtr) kInterruptVectorTable; - Kernel::HAL::IDTLoader idt_loader; + Kernel::HAL::IDTLoader idt_loader; - idt_loader.Load(idt_reg); + idt_loader.Load(idt_reg); - /// after the scheduler runs, we must look over teams, every 5000s in order to schedule every process according to their affinity fairly. + /// after the scheduler runs, we must look over teams, every 5000s in order to schedule every + /// process according to their affinity fairly. - auto constexpr kSchedTeamSwitchMS = 5U; /// @brief Team switch time in milliseconds. + auto constexpr kSchedTeamSwitchMS = 5U; /// @brief Team switch time in milliseconds. - Kernel::HardwareTimer timer(rtl_milliseconds(kSchedTeamSwitchMS)); + Kernel::HardwareTimer timer(rtl_milliseconds(kSchedTeamSwitchMS)); - STATIC Kernel::Array kTeams; + STATIC Kernel::Array kTeams; - SizeT team_index = 0U; + SizeT team_index = 0U; - /// @brief This just loops over the teams and switches between them. - /// @details Not even round-robin, just a simple loop in this boot core we're at. - while (YES) - { - if (team_index > (kSchedTeamCount - 1)) - { - team_index = 0U; - } + /// @brief This just loops over the teams and switches between them. + /// @details Not even round-robin, just a simple loop in this boot core we're at. + while (YES) { + if (team_index > (kSchedTeamCount - 1)) { + team_index = 0U; + } - while (!UserProcessScheduler::The().SwitchTeam(kTeams[team_index])) - ; + while (!UserProcessScheduler::The().SwitchTeam(kTeams[team_index])); - timer.Wait(); + timer.Wait(); - ++team_index; - } + ++team_index; + } } diff --git a/dev/kernel/HALKit/AMD64/HalKernelPanic.cc b/dev/kernel/HALKit/AMD64/HalKernelPanic.cc index 9c8a235a..3a35f9b1 100644 --- a/dev/kernel/HALKit/AMD64/HalKernelPanic.cc +++ b/dev/kernel/HALKit/AMD64/HalKernelPanic.cc @@ -1,61 +1,54 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ -#include #include -#include -#include -#include #include +#include #include +#include +#include +#include +#include #include #include -#include /* Each error code is attributed with an ID, which will prompt a string onto the * screen. Wait for debugger... */ -namespace Kernel -{ - /// @brief Dumping factory class. - class RecoveryFactory final - { - public: - STATIC Void Recover() noexcept; - }; - - /***********************************************************************************/ - /// @brief Stops execution of the kernel. - /// @param id kernel stop ID. - /***********************************************************************************/ - Void ke_panic(const Kernel::Int32& id, const Char* message) - { - (Void)(kout << "Kernel_Panic_MSG: " << message << kendl); - (Void)(kout << "Kernel_Panic_ID: " << hex_number(id) << kendl); - (Void)(kout << "Kernel_Panic_CR2: " << hex_number((UIntPtr)hal_read_cr2()) << kendl); - - RecoveryFactory::Recover(); - } - - Void RecoveryFactory::Recover() noexcept - { - while (YES) - { - HAL::rt_halt(); - } - } - - void ke_runtime_check(bool expr, const Char* file, const Char* line) - { - if (!expr) - { - (Void)(kout << "Kernel_Panic_File: " << file << kendl); - (Void)(kout << "Kernel_Panic_Line: " << line << kendl); - - ke_panic(RUNTIME_CHECK_FAILED, file); // Runtime Check failed - } - } -} // namespace Kernel +namespace Kernel { +/// @brief Dumping factory class. +class RecoveryFactory final { + public: + STATIC Void Recover() noexcept; +}; + +/***********************************************************************************/ +/// @brief Stops execution of the kernel. +/// @param id kernel stop ID. +/***********************************************************************************/ +Void ke_panic(const Kernel::Int32& id, const Char* message) { + (Void)(kout << "Kernel_Panic_MSG: " << message << kendl); + (Void)(kout << "Kernel_Panic_ID: " << hex_number(id) << kendl); + (Void)(kout << "Kernel_Panic_CR2: " << hex_number((UIntPtr) hal_read_cr2()) << kendl); + + RecoveryFactory::Recover(); +} + +Void RecoveryFactory::Recover() noexcept { + while (YES) { + HAL::rt_halt(); + } +} + +void ke_runtime_check(bool expr, const Char* file, const Char* line) { + if (!expr) { + (Void)(kout << "Kernel_Panic_File: " << file << kendl); + (Void)(kout << "Kernel_Panic_Line: " << line << kendl); + + ke_panic(RUNTIME_CHECK_FAILED, file); // Runtime Check failed + } +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/AMD64/HalPagingMgrAMD64.cc b/dev/kernel/HALKit/AMD64/HalPagingMgrAMD64.cc index 08caed82..8e80c4d8 100644 --- a/dev/kernel/HALKit/AMD64/HalPagingMgrAMD64.cc +++ b/dev/kernel/HALKit/AMD64/HalPagingMgrAMD64.cc @@ -1,156 +1,142 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: HalPagingMgr.cc - Purpose: Platform Paging Manager. + File: HalPagingMgr.cc + Purpose: Platform Paging Manager. ------------------------------------------- */ #include #include -namespace Kernel::HAL -{ - namespace Detail - { - /// @brief Page Table Entry for AMD64. - struct PTE - { - UInt64 Present : 1; - UInt64 Wr : 1; - UInt64 User : 1; - UInt64 Pwt : 1; // Page-level Write-Through - UInt64 Pcd : 1; // Page-level Cache Disable - UInt64 Accessed : 1; - UInt64 Dirty : 1; - UInt64 Pat : 1; // Page Attribute Table (or PS for PDE) - UInt64 Global : 1; - UInt64 Ignored1 : 3; // Available to software - UInt64 PhysicalAddress : 40; // Physical page frame address (bits 12–51) - UInt64 Ignored2 : 7; // More software bits / reserved - UInt64 ProtectionKey : 4; // Optional (if PKU enabled) - UInt64 Reserved : 1; // Usually reserved - UInt64 Nx : 1; // No Execute - }; - } // namespace Detail - - /***********************************************************************************/ - /// \brief Retrieve the page status of a PTE. - /// \param pte Page Table Entry pointer. - /***********************************************************************************/ - STATIC Void mmi_page_status(Detail::PTE* pte) - { - (Void)(kout << (pte->Present ? "Present" : "Not Present") << kendl); - (Void)(kout << (pte->Wr ? "W/R" : "Not W/R") << kendl); - (Void)(kout << (pte->Nx ? "NX" : "Not NX") << kendl); - (Void)(kout << (pte->User ? "User" : "Not User") << kendl); - (Void)(kout << (pte->Pcd ? "Not Cached" : "Cached") << kendl); - (Void)(kout << (pte->Accessed ? "Accessed" : "Not Accessed") << kendl); - (Void)(kout << hex_number(pte->PhysicalAddress) << kendl); - (Void)(kout << (pte->ProtectionKey ? "Protected" : "Not Protected/PKU Disabled") << kendl); - } - - /***********************************************************************************/ - /// @brief Gets a physical address from a virtual address. - /// @param virt a valid virtual address. - /// @return Physical address. - /***********************************************************************************/ - UIntPtr hal_get_phys_address(VoidPtr virt) - { - const UInt64 kVMAddr = (UInt64)virt; - const UInt64 kMask9Bits = 0x1FFULL; - const UInt64 kPageOffsetMask = 0xFFFULL; - - UInt64 cr3 = (UInt64)hal_read_cr3() & ~kPageOffsetMask; - - // Level 4 - auto pml4 = reinterpret_cast(cr3); - UInt64 pml4e = pml4[(kVMAddr >> 39) & kMask9Bits]; - - if (!(pml4e & 1)) - return 0; - - // Level 3 - auto pdpt = reinterpret_cast(pml4e & ~kPageOffsetMask); - UInt64 pdpte = pdpt[(kVMAddr >> 30) & kMask9Bits]; - - if (!(pdpte & 1)) - return 0; - - // Level 2 - auto pd = reinterpret_cast(pdpte & ~kPageOffsetMask); - UInt64 pde = pd[(kVMAddr >> 21) & kMask9Bits]; - - if (!(pde & 1)) - return 0; - - // 1 GiB page support - if (pde & (1 << 7)) - { - return (pde & ~((1ULL << 30) - 1)) | (kVMAddr & ((1ULL << 30) - 1)); - } - - // Level 1 - auto pt = reinterpret_cast(pde & ~kPageOffsetMask); - Detail::PTE* pte = (Detail::PTE*)pt[(kVMAddr >> 12) & kMask9Bits]; - - if (!pte->Present) - return 0; - - mmi_page_status((Detail::PTE*)pte); - - return pte->PhysicalAddress; - } - - /***********************************************************************************/ - /// @brief Maps or allocates a page from virtual_address. - /// @param virtual_address a valid virtual address. - /// @param phys_addr point to physical address. - /// @param flags the flags to put on the page. - /// @return Status code of page manipulation process. - /***********************************************************************************/ - EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags) - { - const UInt64 kVMAddr = (UInt64)virtual_address; - constexpr UInt64 kMask9 = 0x1FF; - constexpr UInt64 kPageMask = 0xFFF; - - UInt64 cr3 = (UIntPtr)hal_read_cr3() & ~kPageMask; - - auto pml4 = reinterpret_cast(cr3); - UInt64 pml4e = pml4[(kVMAddr >> 39) & kMask9]; - - if (!(pml4e & 1)) - return kErrorInvalidData; - - UInt64* pdpt = reinterpret_cast(pml4e & ~kPageMask); - UInt64 pdpte = pdpt[(kVMAddr >> 30) & kMask9]; - - if (!(pdpte & 1)) - return kErrorInvalidData; - - UInt64* pd = reinterpret_cast(pdpte & ~kPageMask); - UInt64 pde = pd[(kVMAddr >> 21) & kMask9]; - - if (!(pde & 1)) - return kErrorInvalidData; - - UInt64* pt = reinterpret_cast(pde & ~kPageMask); - Detail::PTE* pte = (Detail::PTE*)pt[(kVMAddr >> 12) & kMask9]; - - pte->Present = !!(flags & kMMFlagsPresent); - pte->Wr = !!(flags & kMMFlagsWr); - pte->User = !!(flags & kMMFlagsUser); - pte->Nx = !!(flags & kMMFlagsNX); - pte->Pcd = !!(flags & kMMFlagsPCD); - pte->Pwt = !!(flags & kMMFlagsPwt); - pte->PhysicalAddress = ((UIntPtr)(physical_address)); - - hal_invl_tlb(virtual_address); +namespace Kernel::HAL { +namespace Detail { + /// @brief Page Table Entry for AMD64. + struct PTE { + UInt64 Present : 1; + UInt64 Wr : 1; + UInt64 User : 1; + UInt64 Pwt : 1; // Page-level Write-Through + UInt64 Pcd : 1; // Page-level Cache Disable + UInt64 Accessed : 1; + UInt64 Dirty : 1; + UInt64 Pat : 1; // Page Attribute Table (or PS for PDE) + UInt64 Global : 1; + UInt64 Ignored1 : 3; // Available to software + UInt64 PhysicalAddress : 40; // Physical page frame address (bits 12–51) + UInt64 Ignored2 : 7; // More software bits / reserved + UInt64 ProtectionKey : 4; // Optional (if PKU enabled) + UInt64 Reserved : 1; // Usually reserved + UInt64 Nx : 1; // No Execute + }; +} // namespace Detail + +/***********************************************************************************/ +/// \brief Retrieve the page status of a PTE. +/// \param pte Page Table Entry pointer. +/***********************************************************************************/ +STATIC Void mmi_page_status(Detail::PTE* pte) { + (Void)(kout << (pte->Present ? "Present" : "Not Present") << kendl); + (Void)(kout << (pte->Wr ? "W/R" : "Not W/R") << kendl); + (Void)(kout << (pte->Nx ? "NX" : "Not NX") << kendl); + (Void)(kout << (pte->User ? "User" : "Not User") << kendl); + (Void)(kout << (pte->Pcd ? "Not Cached" : "Cached") << kendl); + (Void)(kout << (pte->Accessed ? "Accessed" : "Not Accessed") << kendl); + (Void)(kout << hex_number(pte->PhysicalAddress) << kendl); + (Void)(kout << (pte->ProtectionKey ? "Protected" : "Not Protected/PKU Disabled") << kendl); +} + +/***********************************************************************************/ +/// @brief Gets a physical address from a virtual address. +/// @param virt a valid virtual address. +/// @return Physical address. +/***********************************************************************************/ +UIntPtr hal_get_phys_address(VoidPtr virt) { + const UInt64 kVMAddr = (UInt64) virt; + const UInt64 kMask9Bits = 0x1FFULL; + const UInt64 kPageOffsetMask = 0xFFFULL; + + UInt64 cr3 = (UInt64) hal_read_cr3() & ~kPageOffsetMask; + + // Level 4 + auto pml4 = reinterpret_cast(cr3); + UInt64 pml4e = pml4[(kVMAddr >> 39) & kMask9Bits]; + + if (!(pml4e & 1)) return 0; + + // Level 3 + auto pdpt = reinterpret_cast(pml4e & ~kPageOffsetMask); + UInt64 pdpte = pdpt[(kVMAddr >> 30) & kMask9Bits]; + + if (!(pdpte & 1)) return 0; + + // Level 2 + auto pd = reinterpret_cast(pdpte & ~kPageOffsetMask); + UInt64 pde = pd[(kVMAddr >> 21) & kMask9Bits]; + + if (!(pde & 1)) return 0; + + // 1 GiB page support + if (pde & (1 << 7)) { + return (pde & ~((1ULL << 30) - 1)) | (kVMAddr & ((1ULL << 30) - 1)); + } + + // Level 1 + auto pt = reinterpret_cast(pde & ~kPageOffsetMask); + Detail::PTE* pte = (Detail::PTE*) pt[(kVMAddr >> 12) & kMask9Bits]; + + if (!pte->Present) return 0; + + mmi_page_status((Detail::PTE*) pte); + + return pte->PhysicalAddress; +} + +/***********************************************************************************/ +/// @brief Maps or allocates a page from virtual_address. +/// @param virtual_address a valid virtual address. +/// @param phys_addr point to physical address. +/// @param flags the flags to put on the page. +/// @return Status code of page manipulation process. +/***********************************************************************************/ +EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags) { + const UInt64 kVMAddr = (UInt64) virtual_address; + constexpr UInt64 kMask9 = 0x1FF; + constexpr UInt64 kPageMask = 0xFFF; + + UInt64 cr3 = (UIntPtr) hal_read_cr3() & ~kPageMask; + + auto pml4 = reinterpret_cast(cr3); + UInt64 pml4e = pml4[(kVMAddr >> 39) & kMask9]; + + if (!(pml4e & 1)) return kErrorInvalidData; + + UInt64* pdpt = reinterpret_cast(pml4e & ~kPageMask); + UInt64 pdpte = pdpt[(kVMAddr >> 30) & kMask9]; + + if (!(pdpte & 1)) return kErrorInvalidData; + + UInt64* pd = reinterpret_cast(pdpte & ~kPageMask); + UInt64 pde = pd[(kVMAddr >> 21) & kMask9]; + + if (!(pde & 1)) return kErrorInvalidData; + + UInt64* pt = reinterpret_cast(pde & ~kPageMask); + Detail::PTE* pte = (Detail::PTE*) pt[(kVMAddr >> 12) & kMask9]; + + pte->Present = !!(flags & kMMFlagsPresent); + pte->Wr = !!(flags & kMMFlagsWr); + pte->User = !!(flags & kMMFlagsUser); + pte->Nx = !!(flags & kMMFlagsNX); + pte->Pcd = !!(flags & kMMFlagsPCD); + pte->Pwt = !!(flags & kMMFlagsPwt); + pte->PhysicalAddress = ((UIntPtr) (physical_address)); + + hal_invl_tlb(virtual_address); - mmi_page_status(pte); + mmi_page_status(pte); - return kErrorSuccess; - } -} // namespace Kernel::HAL + return kErrorSuccess; +} +} // namespace Kernel::HAL diff --git a/dev/kernel/HALKit/AMD64/HalProcessorAMD64.cc b/dev/kernel/HALKit/AMD64/HalProcessorAMD64.cc index e6b94ece..66f27c24 100644 --- a/dev/kernel/HALKit/AMD64/HalProcessorAMD64.cc +++ b/dev/kernel/HALKit/AMD64/HalProcessorAMD64.cc @@ -1,9 +1,9 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: HalCPU.cc - Purpose: Platform processor routines. + File: HalCPU.cc + Purpose: Platform processor routines. ------------------------------------------- */ @@ -15,94 +15,61 @@ * @brief Common CPU API. */ -namespace Kernel::HAL -{ - Void hal_set_msr(UInt32 msr, UInt32 lo, UInt32 hi) noexcept - { - asm volatile("wrmsr" - : - : "a"(lo), "d"(hi), "c"(msr)); - } - - Void lrt_hal_out8(UInt16 port, UInt8 value) - { - asm volatile("outb %%al, %1" - : - : "a"(value), "Nd"(port) - : "memory"); - } - - Void lrt_hal_out16(UInt16 port, UInt16 value) - { - asm volatile("outw %%ax, %1" - : - : "a"(value), "Nd"(port) - : "memory"); - } - - Void lrt_hal_out32(UInt16 port, UInt32 value) - { - asm volatile("outl %%eax, %1" - : - : "a"(value), "Nd"(port) - : "memory"); - } - - UInt8 lrt_hal_in8(UInt16 port) - { - UInt8 value = 0UL; - asm volatile("inb %1, %%al" - : "=a"(value) - : "Nd"(port) - : "memory"); - - return value; - } - - UInt16 lrt_hal_in16(UInt16 port) - { - UInt16 value = 0UL; - asm volatile("inw %1, %%ax" - : "=a"(value) - : "Nd"(port) - : "memory"); - - return value; - } - - UInt32 lrt_hal_in32(UInt16 port) - { - UInt32 value = 0UL; - asm volatile("inl %1, %%eax" - : "=a"(value) - : "Nd"(port) - : "memory"); - - return value; - } - - Void rt_halt() - { - asm volatile("hlt"); - } - - Void rt_cli() - { - asm volatile("cli"); - } - - Void rt_sti() - { - asm volatile("sti"); - } - - Void rt_cld() - { - asm volatile("cld"); - } - - Void rt_std() - { - asm volatile("std"); - } -} // namespace Kernel::HAL +namespace Kernel::HAL { +Void hal_set_msr(UInt32 msr, UInt32 lo, UInt32 hi) noexcept { + asm volatile("wrmsr" : : "a"(lo), "d"(hi), "c"(msr)); +} + +Void lrt_hal_out8(UInt16 port, UInt8 value) { + asm volatile("outb %%al, %1" : : "a"(value), "Nd"(port) : "memory"); +} + +Void lrt_hal_out16(UInt16 port, UInt16 value) { + asm volatile("outw %%ax, %1" : : "a"(value), "Nd"(port) : "memory"); +} + +Void lrt_hal_out32(UInt16 port, UInt32 value) { + asm volatile("outl %%eax, %1" : : "a"(value), "Nd"(port) : "memory"); +} + +UInt8 lrt_hal_in8(UInt16 port) { + UInt8 value = 0UL; + asm volatile("inb %1, %%al" : "=a"(value) : "Nd"(port) : "memory"); + + return value; +} + +UInt16 lrt_hal_in16(UInt16 port) { + UInt16 value = 0UL; + asm volatile("inw %1, %%ax" : "=a"(value) : "Nd"(port) : "memory"); + + return value; +} + +UInt32 lrt_hal_in32(UInt16 port) { + UInt32 value = 0UL; + asm volatile("inl %1, %%eax" : "=a"(value) : "Nd"(port) : "memory"); + + return value; +} + +Void rt_halt() { + asm volatile("hlt"); +} + +Void rt_cli() { + asm volatile("cli"); +} + +Void rt_sti() { + asm volatile("sti"); +} + +Void rt_cld() { + asm volatile("cld"); +} + +Void rt_std() { + asm volatile("std"); +} +} // namespace Kernel::HAL diff --git a/dev/kernel/HALKit/AMD64/HalSchedulerCorePrimitivesAMD64.cc b/dev/kernel/HALKit/AMD64/HalSchedulerCorePrimitivesAMD64.cc index 56ed4b34..8f7ffdaf 100644 --- a/dev/kernel/HALKit/AMD64/HalSchedulerCorePrimitivesAMD64.cc +++ b/dev/kernel/HALKit/AMD64/HalSchedulerCorePrimitivesAMD64.cc @@ -1,55 +1,47 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #include #include -namespace Kernel -{ - /***********************************************************************************/ - /// @brief Unimplemented function (crashes by default) - /// @param - /***********************************************************************************/ - - EXTERN_C Void __zka_pure_call(USER_PROCESS* process) - { - if (process) - process->Crash(); - } - - /***********************************************************************************/ - /// @brief Validate user stack. - /// @param stack_ptr the frame pointer. - /***********************************************************************************/ - - EXTERN_C Bool hal_check_stack(HAL::StackFramePtr stack_ptr) - { - if (!stack_ptr) - return No; - - return stack_ptr->SP != 0 && stack_ptr->BP != 0; - } - - /// @brief Wakes up thread. - /// Wakes up thread from the hang state. - Void mp_wakeup_thread(HAL::StackFrame* stack) - { - NE_UNUSED(stack); - Kernel::UserProcessHelper::StartScheduling(); - } - - /// @brief makes the thread sleep on a loop. - /// hooks and hangs thread to prevent code from executing. - Void mp_hang_thread(HAL::StackFrame* stack) - { - NE_UNUSED(stack); - - while (Yes) - { - /* Nothing to do, code is spinning */ - } - } -} // namespace Kernel +namespace Kernel { +/***********************************************************************************/ +/// @brief Unimplemented function (crashes by default) +/// @param +/***********************************************************************************/ + +EXTERN_C Void __zka_pure_call(USER_PROCESS* process) { + if (process) process->Crash(); +} + +/***********************************************************************************/ +/// @brief Validate user stack. +/// @param stack_ptr the frame pointer. +/***********************************************************************************/ + +EXTERN_C Bool hal_check_stack(HAL::StackFramePtr stack_ptr) { + if (!stack_ptr) return No; + + return stack_ptr->SP != 0 && stack_ptr->BP != 0; +} + +/// @brief Wakes up thread. +/// Wakes up thread from the hang state. +Void mp_wakeup_thread(HAL::StackFrame* stack) { + NE_UNUSED(stack); + Kernel::UserProcessHelper::StartScheduling(); +} + +/// @brief makes the thread sleep on a loop. +/// hooks and hangs thread to prevent code from executing. +Void mp_hang_thread(HAL::StackFrame* stack) { + NE_UNUSED(stack); + + while (Yes) { + /* Nothing to do, code is spinning */ + } +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/AMD64/HalTimerAMD64.cc b/dev/kernel/HALKit/AMD64/HalTimerAMD64.cc index ade41d2f..79165289 100644 --- a/dev/kernel/HALKit/AMD64/HalTimerAMD64.cc +++ b/dev/kernel/HALKit/AMD64/HalTimerAMD64.cc @@ -1,101 +1,95 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: HalTimer.cc - Purpose: HAL timer + File: HalTimer.cc + Purpose: HAL timer - Revision History: + Revision History: - 07/07/24: Added file (amlel) + 07/07/24: Added file (amlel) ------------------------------------------- */ -#include #include #include +#include // timer slot 0 -#define kHPETCounterRegValue (0x00) -#define kHPETConfigRegValue (0x20) -#define kHPETCompRegValue (0x24) +#define kHPETCounterRegValue (0x00) +#define kHPETConfigRegValue (0x20) +#define kHPETCompRegValue (0x24) #define kHPETInterruptRegValue (0x2C) ///! BUGS: 0 ///! @file HalTimer.cc ///! @brief Hardware Timer (HPET) -namespace Kernel::Detail -{ - struct HPET_BLOCK : public Kernel::SDT - { - Kernel::UInt8 hardware_rev_id; - Kernel::UInt8 comparator_count : 5; - Kernel::UInt8 counter_size : 1; - Kernel::UInt8 reserved : 1; - Kernel::UInt8 legacy_replacement : 1; - Kernel::UInt16 pci_vendor_id; - ACPI_ADDRESS address; - Kernel::UInt8 hpet_number; - Kernel::UInt16 minimum_tick; - Kernel::UInt8 page_protection; - } PACKED; -} // namespace Kernel::Detail +namespace Kernel::Detail { +struct HPET_BLOCK : public Kernel::SDT { + Kernel::UInt8 hardware_rev_id; + Kernel::UInt8 comparator_count : 5; + Kernel::UInt8 counter_size : 1; + Kernel::UInt8 reserved : 1; + Kernel::UInt8 legacy_replacement : 1; + Kernel::UInt16 pci_vendor_id; + ACPI_ADDRESS address; + Kernel::UInt8 hpet_number; + Kernel::UInt16 minimum_tick; + Kernel::UInt8 page_protection; +} PACKED; +} // namespace Kernel::Detail using namespace Kernel; -HardwareTimer::HardwareTimer(UInt64 ms) - : fWaitFor(ms) -{ - auto power = PowerFactoryInterface(kHandoverHeader->f_HardwareTables.f_VendorPtr); +HardwareTimer::HardwareTimer(UInt64 ms) : fWaitFor(ms) { + auto power = PowerFactoryInterface(kHandoverHeader->f_HardwareTables.f_VendorPtr); - auto hpet = (Detail::HPET_BLOCK*)power.Find("HPET").Leak().Leak(); - MUST_PASS(hpet); + auto hpet = (Detail::HPET_BLOCK*) power.Find("HPET").Leak().Leak(); + MUST_PASS(hpet); - fDigitalTimer = (UInt8*)hpet->address.Address; + fDigitalTimer = (UInt8*) hpet->address.Address; - if (hpet->page_protection) - { - HAL::mm_map_page((VoidPtr)fDigitalTimer, (VoidPtr)fDigitalTimer, HAL::kMMFlagsWr | HAL::kMMFlagsPCD | HAL::kMMFlagsPwt); - } + if (hpet->page_protection) { + HAL::mm_map_page((VoidPtr) fDigitalTimer, (VoidPtr) fDigitalTimer, + HAL::kMMFlagsWr | HAL::kMMFlagsPCD | HAL::kMMFlagsPwt); + } - // if not enabled yet. - if (!(*((volatile UInt64*)((UInt8*)fDigitalTimer + kHPETConfigRegValue)) & (1 << 0))) - { - *((volatile UInt64*)((UInt8*)fDigitalTimer + kHPETConfigRegValue)) = *((volatile UInt64*)((UInt8*)fDigitalTimer + kHPETConfigRegValue)) | (1 << 0); // enable timer - *((volatile UInt64*)((UInt8*)fDigitalTimer + kHPETConfigRegValue)) = *((volatile UInt64*)((UInt8*)fDigitalTimer + kHPETConfigRegValue)) | (1 << 3); // one shot conf - } + // if not enabled yet. + if (!(*((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) & (1 << 0))) { + *((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) = + *((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) | + (1 << 0); // enable timer + *((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) = + *((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) | + (1 << 3); // one shot conf + } } -HardwareTimer::~HardwareTimer() -{ - fDigitalTimer = nullptr; - fWaitFor = 0; +HardwareTimer::~HardwareTimer() { + fDigitalTimer = nullptr; + fWaitFor = 0; } /***********************************************************************************/ /// @brief Wait for the timer to stop spinning. /***********************************************************************************/ -BOOL HardwareTimer::Wait() noexcept -{ - if (fWaitFor < 1) - return NO; +BOOL HardwareTimer::Wait() noexcept { + if (fWaitFor < 1) return NO; - UInt64 hpet_cap = *((volatile UInt64*)(fDigitalTimer + kHPETCounterRegValue)); - UInt64 femtoseconds_per_tick = (hpet_cap >> 32); + UInt64 hpet_cap = *((volatile UInt64*) (fDigitalTimer + kHPETCounterRegValue)); + UInt64 femtoseconds_per_tick = (hpet_cap >> 32); - if (femtoseconds_per_tick == 0) - return NO; + if (femtoseconds_per_tick == 0) return NO; - volatile UInt64* timer = (volatile UInt64*)(fDigitalTimer + kHPETCounterRegValue); + volatile UInt64* timer = (volatile UInt64*) (fDigitalTimer + kHPETCounterRegValue); - UInt64 now = *timer; - UInt64 prev = now + (fWaitFor / femtoseconds_per_tick); + UInt64 now = *timer; + UInt64 prev = now + (fWaitFor / femtoseconds_per_tick); - while (*timer < (prev)) - asm volatile("pause"); + while (*timer < (prev)) asm volatile("pause"); - return YES; + return YES; } diff --git a/dev/kernel/HALKit/AMD64/Hypervisor.h b/dev/kernel/HALKit/AMD64/Hypervisor.h index 848f79bb..df88b02b 100644 --- a/dev/kernel/HALKit/AMD64/Hypervisor.h +++ b/dev/kernel/HALKit/AMD64/Hypervisor.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -8,18 +8,17 @@ #include -namespace Kernel -{ - MAKE_STRING_ENUM(HYPERVISOR) - ENUM_STRING(Qemu, "TCGTCGTCGTCG"); - ENUM_STRING(KVM, " KVMKVMKVM "); - ENUM_STRING(VMWare, "VMwareVMware"); - ENUM_STRING(VirtualBox, "VBoxVBoxVBox"); - ENUM_STRING(Xen, "XenVMMXenVMM"); - ENUM_STRING(Microsoft, "Microsoft Hv"); - ENUM_STRING(Parallels, " prl hyperv "); - ENUM_STRING(ParallelsAlt, " lrpepyh vr "); - ENUM_STRING(Bhyve, "bhyve bhyve "); - ENUM_STRING(Qnx, " QNXQVMBSQG "); - END_STRING_ENUM() -} // namespace Kernel +namespace Kernel { +MAKE_STRING_ENUM(HYPERVISOR) +ENUM_STRING(Qemu, "TCGTCGTCGTCG"); +ENUM_STRING(KVM, " KVMKVMKVM "); +ENUM_STRING(VMWare, "VMwareVMware"); +ENUM_STRING(VirtualBox, "VBoxVBoxVBox"); +ENUM_STRING(Xen, "XenVMMXenVMM"); +ENUM_STRING(Microsoft, "Microsoft Hv"); +ENUM_STRING(Parallels, " prl hyperv "); +ENUM_STRING(ParallelsAlt, " lrpepyh vr "); +ENUM_STRING(Bhyve, "bhyve bhyve "); +ENUM_STRING(Qnx, " QNXQVMBSQG "); +END_STRING_ENUM() +} // namespace Kernel diff --git a/dev/kernel/HALKit/AMD64/PCI/DMA.cc b/dev/kernel/HALKit/AMD64/PCI/DMA.cc index b16039d4..38533448 100644 --- a/dev/kernel/HALKit/AMD64/PCI/DMA.cc +++ b/dev/kernel/HALKit/AMD64/PCI/DMA.cc @@ -1,85 +1,72 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ -#include #include +#include -namespace Kernel -{ - DMAWrapper::operator bool() - { - return this->fAddress; - } +namespace Kernel { +DMAWrapper::operator bool() { + return this->fAddress; +} - bool DMAWrapper::operator!() - { - return !this->fAddress; - } +bool DMAWrapper::operator!() { + return !this->fAddress; +} - Boolean DMAWrapper::Check(UIntPtr offset) const - { - if (!this->fAddress) - return false; +Boolean DMAWrapper::Check(UIntPtr offset) const { + if (!this->fAddress) return false; - if (offset == 0) - return false; + if (offset == 0) return false; - kout << "[DMAWrapper::IsIn] Checking offset...\r"; - return reinterpret_cast(this->fAddress) >= offset; - } + kout << "[DMAWrapper::IsIn] Checking offset...\r"; + return reinterpret_cast(this->fAddress) >= offset; +} - bool DMAWrapper::Write(UIntPtr& bit, const UInt32& offset) - { - kout << "[DMAWrapper::Read] Checking this->fAddress...\r"; +bool DMAWrapper::Write(UIntPtr& bit, const UInt32& offset) { + kout << "[DMAWrapper::Read] Checking this->fAddress...\r"; - if (!this->fAddress) - return false; + if (!this->fAddress) return false; - (Void)(kout << "[DMAWrapper::Write] Writing at address: " << hex_number(reinterpret_cast(this->fAddress) + offset) << kendl); + (Void)(kout << "[DMAWrapper::Write] Writing at address: " + << hex_number(reinterpret_cast(this->fAddress) + offset) << kendl); - ke_dma_write(reinterpret_cast(this->fAddress), offset, bit); + ke_dma_write(reinterpret_cast(this->fAddress), offset, bit); - return true; - } + return true; +} - UIntPtr DMAWrapper::Read(const UInt32& offset) - { - kout << "[DMAWrapper::Read] Checking this->fAddress...\r"; +UIntPtr DMAWrapper::Read(const UInt32& offset) { + kout << "[DMAWrapper::Read] Checking this->fAddress...\r"; - if (!this->fAddress) - return ~0; + if (!this->fAddress) return ~0; - (Void)(kout << "[DMAWrapper::Write] Writing at address: " << hex_number(reinterpret_cast(this->fAddress) + offset) << kendl); + (Void)(kout << "[DMAWrapper::Write] Writing at address: " + << hex_number(reinterpret_cast(this->fAddress) + offset) << kendl); - return (UIntPtr)ke_dma_read(reinterpret_cast(this->fAddress), offset); - } + return (UIntPtr) ke_dma_read(reinterpret_cast(this->fAddress), offset); +} - UIntPtr DMAWrapper::operator[](UIntPtr& offset) - { - return this->Read(offset); - } +UIntPtr DMAWrapper::operator[](UIntPtr& offset) { + return this->Read(offset); +} - OwnPtr> DMAFactory::Construct(OwnPtr& dma) - { - if (!dma) - return {}; +OwnPtr> DMAFactory::Construct(OwnPtr& dma) { + if (!dma) return {}; - OwnPtr> dmaOwnPtr = - mm_make_own_ptr, char*>(reinterpret_cast(dma->fAddress)); + OwnPtr> dmaOwnPtr = + mm_make_own_ptr, char*>(reinterpret_cast(dma->fAddress)); - if (!dmaOwnPtr) - return {}; + if (!dmaOwnPtr) return {}; - kout << "Returning the new OwnPtr>!\r"; - return dmaOwnPtr; - } + kout << "Returning the new OwnPtr>!\r"; + return dmaOwnPtr; +} - DMAWrapper& DMAWrapper::operator=(voidPtr Ptr) - { - this->fAddress = Ptr; - return *this; - } -} // namespace Kernel +DMAWrapper& DMAWrapper::operator=(voidPtr Ptr) { + this->fAddress = Ptr; + return *this; +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/AMD64/PCI/Database.cc b/dev/kernel/HALKit/AMD64/PCI/Database.cc index 356792e4..9e6c349b 100644 --- a/dev/kernel/HALKit/AMD64/PCI/Database.cc +++ b/dev/kernel/HALKit/AMD64/PCI/Database.cc @@ -1,11 +1,9 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #include -namespace Kernel -{ -} +namespace Kernel {} diff --git a/dev/kernel/HALKit/AMD64/PCI/Device.cc b/dev/kernel/HALKit/AMD64/PCI/Device.cc index ced473ed..f11f7777 100644 --- a/dev/kernel/HALKit/AMD64/PCI/Device.cc +++ b/dev/kernel/HALKit/AMD64/PCI/Device.cc @@ -1,173 +1,142 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #include #include -#define PCI_BAR_IO (0x01) -#define PCI_BAR_LOWMEM (0x02) -#define PCI_BAR_64 (0x04) +#define PCI_BAR_IO (0x01) +#define PCI_BAR_LOWMEM (0x02) +#define PCI_BAR_64 (0x04) #define PCI_BAR_PREFETCH (0x08) -#define PCI_ENABLE_BIT (0x80000000) +#define PCI_ENABLE_BIT (0x80000000) -static Kernel::UInt NE_PCIReadRaw(Kernel::UInt bar, Kernel::UShort bus, Kernel::UShort dev, Kernel::UShort fun) -{ - Kernel::UInt target = PCI_ENABLE_BIT | ((Kernel::UInt)bus << 16) | - ((Kernel::UInt)dev << 11) | ((Kernel::UInt)fun << 8) | - (bar & 0xFC); +static Kernel::UInt NE_PCIReadRaw(Kernel::UInt bar, Kernel::UShort bus, Kernel::UShort dev, + Kernel::UShort fun) { + Kernel::UInt target = PCI_ENABLE_BIT | ((Kernel::UInt) bus << 16) | ((Kernel::UInt) dev << 11) | + ((Kernel::UInt) fun << 8) | (bar & 0xFC); - Kernel::HAL::rt_out32((Kernel::UShort)Kernel::PCI::PciConfigKind::ConfigAddress, - target); + Kernel::HAL::rt_out32((Kernel::UShort) Kernel::PCI::PciConfigKind::ConfigAddress, target); - Kernel::HAL::rt_wait_400ns(); + Kernel::HAL::rt_wait_400ns(); - return Kernel::HAL::rt_in32((Kernel::UShort)Kernel::PCI::PciConfigKind::ConfigData); + return Kernel::HAL::rt_in32((Kernel::UShort) Kernel::PCI::PciConfigKind::ConfigData); } - -static Kernel::Void NE_PCISetCfgTarget(Kernel::UInt bar, Kernel::UShort bus, Kernel::UShort dev, Kernel::UShort fun) -{ - Kernel::UInt target = 0x80000000 | ((Kernel::UInt)bus << 16) | - ((Kernel::UInt)dev << 11) | ((Kernel::UInt)fun << 8) | - (bar & 0xFC); - - Kernel::HAL::rt_out32((Kernel::UShort)Kernel::PCI::PciConfigKind::ConfigAddress, - target); - - Kernel::HAL::rt_wait_400ns(); + +static Kernel::Void NE_PCISetCfgTarget(Kernel::UInt bar, Kernel::UShort bus, Kernel::UShort dev, + Kernel::UShort fun) { + Kernel::UInt target = 0x80000000 | ((Kernel::UInt) bus << 16) | ((Kernel::UInt) dev << 11) | + ((Kernel::UInt) fun << 8) | (bar & 0xFC); + + Kernel::HAL::rt_out32((Kernel::UShort) Kernel::PCI::PciConfigKind::ConfigAddress, target); + + Kernel::HAL::rt_wait_400ns(); +} + +namespace Kernel::PCI { +Device::Device(UShort bus, UShort device, UShort func, UInt32 bar) + : fBus(bus), fDevice(device), fFunction(func), fBar(bar) {} + +Device::~Device() = default; + +UInt Device::Read(UInt bar, Size sz) { + // Ensure aligned access by masking to 4-byte boundary + NE_PCISetCfgTarget(bar & 0xFC, fBus, fDevice, fFunction); + + // Read 4 bytes and shift out the correct value + UInt data = HAL::rt_in32((UShort) PciConfigKind::ConfigData); + + if (sz == 4) return data; + if (sz == 2) return (data >> ((bar & 2) * 8)) & 0xFFFF; + if (sz == 1) return (data >> ((bar & 3) * 8)) & 0xFF; + + return (UShort) PciConfigKind::Invalid; +} + +void Device::Write(UInt bar, UIntPtr data, Size sz) { + NE_PCISetCfgTarget(bar & 0xFC, fBus, fDevice, fFunction); + + if (sz == 4) { + HAL::rt_out32((UShort) PciConfigKind::ConfigAddress, (UInt) data); + } else if (sz == 2) { + UInt temp = HAL::rt_in32((UShort) PciConfigKind::ConfigData); + + temp &= ~(0xFFFF << ((bar & 2) * 8)); + temp |= (data & 0xFFFF) << ((bar & 2) * 8); + + HAL::rt_out32((UShort) PciConfigKind::ConfigAddress, temp); + } else if (sz == 1) { + UInt temp = HAL::rt_in32((UShort) PciConfigKind::ConfigData); + + temp &= ~(0xFF << ((bar & 3) * 8)); + temp |= (data & 0xFF) << ((bar & 3) * 8); + + HAL::rt_out32((UShort) PciConfigKind::ConfigAddress, temp); + } +} + +UShort Device::DeviceId() { + return (UShort) (NE_PCIReadRaw(0x0, fBus, fDevice, fFunction) >> 16); +} + +UShort Device::VendorId() { + return (UShort) (NE_PCIReadRaw(0x0, fBus, fDevice, fFunction) & 0xFFFF); +} + +UShort Device::InterfaceId() { + return (UShort) (NE_PCIReadRaw(0x09, fBus, fDevice, fFunction) >> 16); +} + +UChar Device::Class() { + return (UChar) (NE_PCIReadRaw(0x08, fBus, fDevice, fFunction) >> 24); +} + +UChar Device::Subclass() { + return (UChar) (NE_PCIReadRaw(0x08, fBus, fDevice, fFunction) >> 16); +} + +UChar Device::ProgIf() { + return (UChar) (NE_PCIReadRaw(0x08, fBus, fDevice, fFunction) >> 8); +} + +UChar Device::HeaderType() { + return (UChar) (NE_PCIReadRaw(0xC, fBus, fDevice, fFunction) >> 16); +} + +void Device::EnableMmio() { + UInt32 command = Read(0x04, sizeof(UInt32)); + command |= (1 << 1); // Memory Space Enable (bit 1) + + Write(0x04, command, sizeof(UInt32)); +} + +void Device::BecomeBusMaster() { + UInt32 command = Read(0x04, sizeof(UInt32)); + command |= (1 << 2); // Bus Master Enable (bit 2) + Write(0x04, command, sizeof(UInt32)); +} + +UIntPtr Device::Bar(UInt32 bar_in) { + UInt32 bar = NE_PCIReadRaw(bar_in, fBus, fDevice, fFunction); + + if (bar & PCI_BAR_IO) return static_cast(bar & ~0x03); + + if (bar & PCI_BAR_64) { + UInt32 high = NE_PCIReadRaw((bar_in + 4) & ~0x03, fBus, fDevice, fFunction); + return (static_cast(high) << 32) | (bar & ~0x0F); + } + + return static_cast(bar & ~0x0F); +} + +UShort Device::Vendor() { + UShort vendor = this->VendorId(); + return vendor; +} + +Device::operator bool() { + return this->VendorId() != (UShort) PciConfigKind::Invalid; } - -namespace Kernel::PCI -{ - Device::Device(UShort bus, UShort device, UShort func, UInt32 bar) - : fBus(bus), fDevice(device), fFunction(func), fBar(bar) - { - } - - Device::~Device() = default; - - UInt Device::Read(UInt bar, Size sz) - { - // Ensure aligned access by masking to 4-byte boundary - NE_PCISetCfgTarget(bar & 0xFC, fBus, fDevice, fFunction); - - // Read 4 bytes and shift out the correct value - UInt data = HAL::rt_in32((UShort)PciConfigKind::ConfigData); - - if (sz == 4) - return data; - if (sz == 2) - return (data >> ((bar & 2) * 8)) & 0xFFFF; - if (sz == 1) - return (data >> ((bar & 3) * 8)) & 0xFF; - - return (UShort)PciConfigKind::Invalid; - } - - void Device::Write(UInt bar, UIntPtr data, Size sz) - { - NE_PCISetCfgTarget(bar & 0xFC, fBus, fDevice, fFunction); - - if (sz == 4) - { - HAL::rt_out32((UShort)PciConfigKind::ConfigAddress, (UInt)data); - } - else if (sz == 2) - { - UInt temp = HAL::rt_in32((UShort)PciConfigKind::ConfigData); - - temp &= ~(0xFFFF << ((bar & 2) * 8)); - temp |= (data & 0xFFFF) << ((bar & 2) * 8); - - HAL::rt_out32((UShort)PciConfigKind::ConfigAddress, temp); - } - else if (sz == 1) - { - UInt temp = HAL::rt_in32((UShort)PciConfigKind::ConfigData); - - temp &= ~(0xFF << ((bar & 3) * 8)); - temp |= (data & 0xFF) << ((bar & 3) * 8); - - HAL::rt_out32((UShort)PciConfigKind::ConfigAddress, temp); - } - } - - UShort Device::DeviceId() - { - return (UShort)(NE_PCIReadRaw(0x0, fBus, fDevice, fFunction) >> 16); - } - - UShort Device::VendorId() - { - return (UShort)(NE_PCIReadRaw(0x0, fBus, fDevice, fFunction) & 0xFFFF); - } - - UShort Device::InterfaceId() - { - return (UShort)(NE_PCIReadRaw(0x09, fBus, fDevice, fFunction) >> 16); - } - - UChar Device::Class() - { - return (UChar)(NE_PCIReadRaw(0x08, fBus, fDevice, fFunction) >> 24); - } - - UChar Device::Subclass() - { - return (UChar)(NE_PCIReadRaw(0x08, fBus, fDevice, fFunction) >> 16); - } - - UChar Device::ProgIf() - { - return (UChar)(NE_PCIReadRaw(0x08, fBus, fDevice, fFunction) >> 8); - } - - UChar Device::HeaderType() - { - return (UChar)(NE_PCIReadRaw(0xC, fBus, fDevice, fFunction) >> 16); - } - - void Device::EnableMmio() - { - UInt32 command = Read(0x04, sizeof(UInt32)); - command |= (1 << 1); // Memory Space Enable (bit 1) - - Write(0x04, command, sizeof(UInt32)); - } - - void Device::BecomeBusMaster() - { - UInt32 command = Read(0x04, sizeof(UInt32)); - command |= (1 << 2); // Bus Master Enable (bit 2) - Write(0x04, command, sizeof(UInt32)); - } - - UIntPtr Device::Bar(UInt32 bar_in) - { - UInt32 bar = NE_PCIReadRaw(bar_in, fBus, fDevice, fFunction); - - if (bar & PCI_BAR_IO) - return static_cast(bar & ~0x03); - - if (bar & PCI_BAR_64) - { - UInt32 high = NE_PCIReadRaw((bar_in + 4) & ~0x03, fBus, fDevice, fFunction); - return (static_cast(high) << 32) | (bar & ~0x0F); - } - - return static_cast(bar & ~0x0F); - } - - UShort Device::Vendor() - { - UShort vendor = this->VendorId(); - return vendor; - } - - Device::operator bool() - { - return this->VendorId() != (UShort)PciConfigKind::Invalid; - } -} // namespace Kernel::PCI +} // namespace Kernel::PCI diff --git a/dev/kernel/HALKit/AMD64/PCI/Express.cc b/dev/kernel/HALKit/AMD64/PCI/Express.cc index 6d257531..6031e792 100644 --- a/dev/kernel/HALKit/AMD64/PCI/Express.cc +++ b/dev/kernel/HALKit/AMD64/PCI/Express.cc @@ -1,11 +1,9 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #include -namespace Kernel -{ -} +namespace Kernel {} diff --git a/dev/kernel/HALKit/AMD64/PCI/IO.cc b/dev/kernel/HALKit/AMD64/PCI/IO.cc index 7d43707e..1d72316a 100644 --- a/dev/kernel/HALKit/AMD64/PCI/IO.cc +++ b/dev/kernel/HALKit/AMD64/PCI/IO.cc @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ diff --git a/dev/kernel/HALKit/AMD64/PCI/Iterator.cc b/dev/kernel/HALKit/AMD64/PCI/Iterator.cc index 09cfb2d2..2590aa94 100644 --- a/dev/kernel/HALKit/AMD64/PCI/Iterator.cc +++ b/dev/kernel/HALKit/AMD64/PCI/Iterator.cc @@ -1,39 +1,30 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #include -namespace Kernel::PCI -{ - Iterator::Iterator(const Types::PciDeviceKind& type) - { - // probe devices. - for (int bus = 0; bus < NE_BUS_COUNT; ++bus) - { - for (int device = 0; device < NE_DEVICE_COUNT; ++device) - { - for (int function = 0; function < NE_FUNCTION_COUNT; ++function) - { - Device dev(bus, device, function, 0x00); +namespace Kernel::PCI { +Iterator::Iterator(const Types::PciDeviceKind& type) { + // probe devices. + for (int bus = 0; bus < NE_BUS_COUNT; ++bus) { + for (int device = 0; device < NE_DEVICE_COUNT; ++device) { + for (int function = 0; function < NE_FUNCTION_COUNT; ++function) { + Device dev(bus, device, function, 0x00); - if (dev.Class() == type) - { - fDevices[bus] = dev; - } - } - } - } - } + if (dev.Class() == type) { + fDevices[bus] = dev; + } + } + } + } +} - Iterator::~Iterator() - { - } +Iterator::~Iterator() {} - Ref Iterator::operator[](const Size& at) - { - return fDevices[at]; - } -} // namespace Kernel::PCI +Ref Iterator::operator[](const Size& at) { + return fDevices[at]; +} +} // namespace Kernel::PCI diff --git a/dev/kernel/HALKit/AMD64/PCI/PCI.cc b/dev/kernel/HALKit/AMD64/PCI/PCI.cc index c3e93084..616b3eea 100644 --- a/dev/kernel/HALKit/AMD64/PCI/PCI.cc +++ b/dev/kernel/HALKit/AMD64/PCI/PCI.cc @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ diff --git a/dev/kernel/HALKit/AMD64/Paging.h b/dev/kernel/HALKit/AMD64/Paging.h index ea20dece..074c1113 100644 --- a/dev/kernel/HALKit/AMD64/Paging.h +++ b/dev/kernel/HALKit/AMD64/Paging.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -8,7 +8,7 @@ /** --------------------------------------------------- - * THIS FILE CONTAINS CODE FOR X86_64 PAGING. + * THIS FILE CONTAINS CODE FOR X86_64 PAGING. ------------------------------------------------------- */ @@ -16,60 +16,55 @@ #ifndef kPageMax #define kPageMax (0x200) -#endif //! kPageMax +#endif //! kPageMax #ifndef kPageAlign #define kPageAlign (0x08) -#endif //! kPageAlign +#endif //! kPageAlign #ifndef kPageSize #define kPageSize (0x1000) -#endif // !kPageSize +#endif // !kPageSize #ifndef kAlign #define kAlign __BIGGEST_ALIGNMENT__ -#endif // !kAlign +#endif // !kAlign EXTERN_C void hal_flush_tlb(); EXTERN_C void hal_invl_tlb(Kernel::VoidPtr addr); EXTERN_C void hal_write_cr3(Kernel::VoidPtr cr3); EXTERN_C void hal_write_cr0(Kernel::VoidPtr bit); -EXTERN_C Kernel::VoidPtr hal_read_cr0(); // @brief CPU control register. -EXTERN_C Kernel::VoidPtr hal_read_cr2(); // @brief Fault address. -EXTERN_C Kernel::VoidPtr hal_read_cr3(); // @brief Page table. - -namespace Kernel::HAL -{ - namespace Detail - { - enum class ControlRegisterBits - { - ProtectedModeEnable = 0, - MonitorCoProcessor = 1, - Emulation = 2, - TaskSwitched = 3, - ExtensionType = 4, - NumericError = 5, - WriteProtect = 16, - AlignementMask = 18, - NotWriteThrough = 29, - CacheDisable = 30, - PageEnable = 31, - }; - - inline UInt8 control_register_cast(ControlRegisterBits reg) - { - return static_cast(reg); - } - } // namespace Detail - - auto mm_alloc_bitmap(Boolean wr, Boolean user, SizeT size, Bool is_page, SizeT pad = 0) -> VoidPtr; - auto mm_free_bitmap(VoidPtr page_ptr) -> Bool; -} // namespace Kernel::HAL - -namespace Kernel -{ - typedef VoidPtr PTE; - typedef VoidPtr PDE; -} // namespace Kernel +EXTERN_C Kernel::VoidPtr hal_read_cr0(); // @brief CPU control register. +EXTERN_C Kernel::VoidPtr hal_read_cr2(); // @brief Fault address. +EXTERN_C Kernel::VoidPtr hal_read_cr3(); // @brief Page table. + +namespace Kernel::HAL { +namespace Detail { + enum class ControlRegisterBits { + ProtectedModeEnable = 0, + MonitorCoProcessor = 1, + Emulation = 2, + TaskSwitched = 3, + ExtensionType = 4, + NumericError = 5, + WriteProtect = 16, + AlignementMask = 18, + NotWriteThrough = 29, + CacheDisable = 30, + PageEnable = 31, + }; + + inline UInt8 control_register_cast(ControlRegisterBits reg) { + return static_cast(reg); + } +} // namespace Detail + +auto mm_alloc_bitmap(Boolean wr, Boolean user, SizeT size, Bool is_page, SizeT pad = 0) -> VoidPtr; +auto mm_free_bitmap(VoidPtr page_ptr) -> Bool; +} // namespace Kernel::HAL + +namespace Kernel { +typedef VoidPtr PTE; +typedef VoidPtr PDE; +} // namespace Kernel diff --git a/dev/kernel/HALKit/AMD64/Processor.h b/dev/kernel/HALKit/AMD64/Processor.h index 13819f3e..1319277f 100644 --- a/dev/kernel/HALKit/AMD64/Processor.h +++ b/dev/kernel/HALKit/AMD64/Processor.h @@ -1,32 +1,32 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: Prcoessor.h - Purpose: AMD64 processor abstraction. + File: Prcoessor.h + Purpose: AMD64 processor abstraction. - Revision History: + Revision History: - 30/01/24: Added file (amlel) + 30/01/24: Added file (amlel) ------------------------------------------- */ #pragma once +#include +#include #include #include #include -#include -#include -#define kPITControlPort (0x43) +#define kPITControlPort (0x43) #define kPITChannel0Port (0x40) -#define kPITFrequency (1193180) +#define kPITFrequency (1193180) -#define kPICCommand (0x20) -#define kPICData (0x21) +#define kPICCommand (0x20) +#define kPICData (0x21) #define kPIC2Command (0xA0) -#define kPIC2Data (0xA1) +#define kPIC2Data (0xA1) #include @@ -38,269 +38,241 @@ /// @brief interrupt for system call. #define kKernelInterruptId (0x32) -#define IsActiveLow(FLG) (FLG & 2) +#define IsActiveLow(FLG) (FLG & 2) #define IsLevelTriggered(FLG) (FLG & 8) #define kInterruptGate (0x8E) -#define kTrapGate (0xEF) -#define kTaskGate (0b10001100) -#define kIDTSelector (0x08) - -namespace Kernel -{ - namespace Detail::AMD64 - { - struct PACKED InterruptDescriptorAMD64 final - { - UInt16 OffsetLow; // offset bits 0..15 - UInt16 Selector; // a code segment selector in GDT or LDT - UInt8 Ist; - UInt8 TypeAttributes; - UInt16 OffsetMid; - UInt32 OffsetHigh; - UInt32 Zero; // reserved - }; - } // namespace Detail::AMD64 -} // namespace Kernel - -namespace Kernel::HAL -{ - /// @brief Memory Manager mapping flags. - enum - { - kMMFlagsInvalid = 1 << 0, - kMMFlagsPresent = 1 << 1, - kMMFlagsWr = 1 << 2, - kMMFlagsUser = 1 << 3, - kMMFlagsNX = 1 << 4, - kMMFlagsPCD = 1 << 5, - kMMFlagsPwt = 1 << 6, - kMMFlagsCount = 4, - }; - - struct PACKED Register64 final - { - UShort Limit; - UIntPtr Base; - }; - - using RawRegister = UInt64; - using Reg = RawRegister; - using InterruptId = UInt16; /* For each element in the IVT */ - - /// @brief Stack frame (as retrieved from assembly.) - struct PACKED StackFrame final - { - RawRegister R8{0}; - RawRegister R9{0}; - RawRegister R10{0}; - RawRegister FS{0}; - RawRegister R12{0}; - RawRegister R13{0}; - RawRegister R14{0}; - RawRegister R15{0}; - RawRegister GS{0}; - RawRegister SP{0}; - RawRegister BP{0}; - }; - - typedef StackFrame* StackFramePtr; - - class InterruptDescriptor final - { - public: - UShort Offset; - UShort Selector; - UChar Ist; - UChar Atrributes; - - UShort SecondOffset; - UInt ThirdOffset; - UInt Zero; - - operator bool() - { - return Offset != 0xFFFF; - } - }; - - using InterruptDescriptorArray = Array; - - class SegmentDescriptor final - { - public: - UInt16 Base; - UInt8 BaseMiddle; - UInt8 BaseHigh; - - UShort Limit; - UChar Gran; - UChar AccessByte; - }; - - /*** - * @brief Segment Boolean operations - */ - class SegmentDescriptorComparator final - { - public: - Bool IsValid(SegmentDescriptor& seg) - { - return seg.Base > seg.Limit; - } - - Bool Equals(SegmentDescriptor& seg, SegmentDescriptor& segRight) - { - return seg.Base == segRight.Base && seg.Limit == segRight.Limit; - } - }; - - using SegmentArray = Array; - - class GDTLoader final - { - public: - static Void Load(Register64& gdt); - static Void Load(Ref& gdt); - }; - - class IDTLoader final - { - public: - static Void Load(Register64& idt); - static Void Load(Ref& idt); - }; - - /***********************************************************************************/ - /// @brief Is the current config SMP aware? - /// @return True if YES, False if not. - /***********************************************************************************/ - - Bool mp_is_smp(Void) noexcept; - - /***********************************************************************************/ - /// @brief Fetch and enable SMP scheduler. - /// @param vendor_ptr SMP containing structure. - /***********************************************************************************/ - Void mp_init_cores(VoidPtr vendor_ptr) noexcept; - - /***********************************************************************************/ - /// @brief Do a cpuid to check if MSR exists on CPU. - /// @retval true it does exists. - /// @retval false it doesn't. - /***********************************************************************************/ - inline Bool hal_has_msr() noexcept - { - static UInt32 eax, unused, edx; // eax, edx - - __get_cpuid(1, &eax, &unused, &unused, &edx); - - // edx returns the flag for MSR (which is 1 shifted to 5.) - return edx & (1 << 5); - } - - UIntPtr hal_get_phys_address(VoidPtr virtual_address); - - /***********************************************************************************/ - /// @brief Get Model specific register inside core. - /// @param msr MSR - /// @param lo low byte - /// @param hi high byte - /***********************************************************************************/ - inline UInt32 hal_get_msr(UInt32 msr, UInt32* lo, UInt32* hi) noexcept - { - if (!lo || !hi) - return 0; - - asm volatile("rdmsr" - : "=a"(*lo), "=d"(*hi) - : "c"(msr)); - - return *lo + *hi; - } - - /// @brief Set Model-specific register. - /// @param msr MSR - /// @param lo low byte - /// @param hi high byte - Void hal_set_msr(UInt32 msr, UInt32 lo, UInt32 hi) noexcept; - - /// @brief Processor specific namespace. - namespace Detail - { - /* @brief TSS struct. */ - struct NE_TSS final - { - UInt32 fReserved1; - UInt64 fRsp0; - UInt64 fRsp1; - UInt64 fRsp2; - UInt64 fReserved2; - UInt64 fIst1; - UInt64 fIst2; - UInt64 fIst3; - UInt64 fIst4; - UInt64 fIst5; - UInt64 fIst6; - UInt64 fIst7; - UInt64 fReserved3; - UInt16 fReserved4; - UInt16 fIopb; - }; - - /** - @brief Global descriptor table entry, either null, code or data. - */ - - struct PACKED NE_GDT_ENTRY final - { - UInt16 fLimitLow; - UInt16 fBaseLow; - UInt8 fBaseMid; - UInt8 fAccessByte; - UInt8 fFlags; - UInt8 fBaseHigh; - }; - } // namespace Detail - - class APICController final - { - public: - explicit APICController(VoidPtr base); - ~APICController() = default; - - NE_COPY_DEFAULT(APICController) - - public: - UInt32 Read(UInt32 reg) noexcept; - Void Write(UInt32 reg, UInt32 value) noexcept; - - private: - VoidPtr fApic{nullptr}; - }; - - /// @brief Set a PTE from pd_base. - /// @param virt_addr a valid virtual address. - /// @param phys_addr point to physical address. - /// @param flags the flags to put on the page. - /// @return Status code of page manip. - EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags); - - EXTERN_C UInt8 rt_in8(UInt16 port); - EXTERN_C UInt16 rt_in16(UInt16 port); - EXTERN_C UInt32 rt_in32(UInt16 port); - - EXTERN_C Void rt_out16(UShort port, UShort byte); - EXTERN_C Void rt_out8(UShort port, UChar byte); - EXTERN_C Void rt_out32(UShort port, UInt byte); - - EXTERN_C Void rt_wait_400ns(); - EXTERN_C Void rt_halt(); - EXTERN_C Void rt_cli(); - EXTERN_C Void rt_sti(); - EXTERN_C Void rt_cld(); - EXTERN_C Void rt_std(); -} // namespace Kernel::HAL +#define kTrapGate (0xEF) +#define kTaskGate (0b10001100) +#define kIDTSelector (0x08) + +namespace Kernel { +namespace Detail::AMD64 { + struct PACKED InterruptDescriptorAMD64 final { + UInt16 OffsetLow; // offset bits 0..15 + UInt16 Selector; // a code segment selector in GDT or LDT + UInt8 Ist; + UInt8 TypeAttributes; + UInt16 OffsetMid; + UInt32 OffsetHigh; + UInt32 Zero; // reserved + }; +} // namespace Detail::AMD64 +} // namespace Kernel + +namespace Kernel::HAL { +/// @brief Memory Manager mapping flags. +enum { + kMMFlagsInvalid = 1 << 0, + kMMFlagsPresent = 1 << 1, + kMMFlagsWr = 1 << 2, + kMMFlagsUser = 1 << 3, + kMMFlagsNX = 1 << 4, + kMMFlagsPCD = 1 << 5, + kMMFlagsPwt = 1 << 6, + kMMFlagsCount = 4, +}; + +struct PACKED Register64 final { + UShort Limit; + UIntPtr Base; +}; + +using RawRegister = UInt64; +using Reg = RawRegister; +using InterruptId = UInt16; /* For each element in the IVT */ + +/// @brief Stack frame (as retrieved from assembly.) +struct PACKED StackFrame final { + RawRegister R8{0}; + RawRegister R9{0}; + RawRegister R10{0}; + RawRegister FS{0}; + RawRegister R12{0}; + RawRegister R13{0}; + RawRegister R14{0}; + RawRegister R15{0}; + RawRegister GS{0}; + RawRegister SP{0}; + RawRegister BP{0}; +}; + +typedef StackFrame* StackFramePtr; + +class InterruptDescriptor final { + public: + UShort Offset; + UShort Selector; + UChar Ist; + UChar Atrributes; + + UShort SecondOffset; + UInt ThirdOffset; + UInt Zero; + + operator bool() { return Offset != 0xFFFF; } +}; + +using InterruptDescriptorArray = Array; + +class SegmentDescriptor final { + public: + UInt16 Base; + UInt8 BaseMiddle; + UInt8 BaseHigh; + + UShort Limit; + UChar Gran; + UChar AccessByte; +}; + +/*** + * @brief Segment Boolean operations + */ +class SegmentDescriptorComparator final { + public: + Bool IsValid(SegmentDescriptor& seg) { return seg.Base > seg.Limit; } + + Bool Equals(SegmentDescriptor& seg, SegmentDescriptor& segRight) { + return seg.Base == segRight.Base && seg.Limit == segRight.Limit; + } +}; + +using SegmentArray = Array; + +class GDTLoader final { + public: + static Void Load(Register64& gdt); + static Void Load(Ref& gdt); +}; + +class IDTLoader final { + public: + static Void Load(Register64& idt); + static Void Load(Ref& idt); +}; + +/***********************************************************************************/ +/// @brief Is the current config SMP aware? +/// @return True if YES, False if not. +/***********************************************************************************/ + +Bool mp_is_smp(Void) noexcept; + +/***********************************************************************************/ +/// @brief Fetch and enable SMP scheduler. +/// @param vendor_ptr SMP containing structure. +/***********************************************************************************/ +Void mp_init_cores(VoidPtr vendor_ptr) noexcept; + +/***********************************************************************************/ +/// @brief Do a cpuid to check if MSR exists on CPU. +/// @retval true it does exists. +/// @retval false it doesn't. +/***********************************************************************************/ +inline Bool hal_has_msr() noexcept { + static UInt32 eax, unused, edx; // eax, edx + + __get_cpuid(1, &eax, &unused, &unused, &edx); + + // edx returns the flag for MSR (which is 1 shifted to 5.) + return edx & (1 << 5); +} + +UIntPtr hal_get_phys_address(VoidPtr virtual_address); + +/***********************************************************************************/ +/// @brief Get Model specific register inside core. +/// @param msr MSR +/// @param lo low byte +/// @param hi high byte +/***********************************************************************************/ +inline UInt32 hal_get_msr(UInt32 msr, UInt32* lo, UInt32* hi) noexcept { + if (!lo || !hi) return 0; + + asm volatile("rdmsr" : "=a"(*lo), "=d"(*hi) : "c"(msr)); + + return *lo + *hi; +} + +/// @brief Set Model-specific register. +/// @param msr MSR +/// @param lo low byte +/// @param hi high byte +Void hal_set_msr(UInt32 msr, UInt32 lo, UInt32 hi) noexcept; + +/// @brief Processor specific namespace. +namespace Detail { + /* @brief TSS struct. */ + struct NE_TSS final { + UInt32 fReserved1; + UInt64 fRsp0; + UInt64 fRsp1; + UInt64 fRsp2; + UInt64 fReserved2; + UInt64 fIst1; + UInt64 fIst2; + UInt64 fIst3; + UInt64 fIst4; + UInt64 fIst5; + UInt64 fIst6; + UInt64 fIst7; + UInt64 fReserved3; + UInt16 fReserved4; + UInt16 fIopb; + }; + + /** + @brief Global descriptor table entry, either null, code or data. + */ + + struct PACKED NE_GDT_ENTRY final { + UInt16 fLimitLow; + UInt16 fBaseLow; + UInt8 fBaseMid; + UInt8 fAccessByte; + UInt8 fFlags; + UInt8 fBaseHigh; + }; +} // namespace Detail + +class APICController final { + public: + explicit APICController(VoidPtr base); + ~APICController() = default; + + NE_COPY_DEFAULT(APICController) + + public: + UInt32 Read(UInt32 reg) noexcept; + Void Write(UInt32 reg, UInt32 value) noexcept; + + private: + VoidPtr fApic{nullptr}; +}; + +/// @brief Set a PTE from pd_base. +/// @param virt_addr a valid virtual address. +/// @param phys_addr point to physical address. +/// @param flags the flags to put on the page. +/// @return Status code of page manip. +EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags); + +EXTERN_C UInt8 rt_in8(UInt16 port); +EXTERN_C UInt16 rt_in16(UInt16 port); +EXTERN_C UInt32 rt_in32(UInt16 port); + +EXTERN_C Void rt_out16(UShort port, UShort byte); +EXTERN_C Void rt_out8(UShort port, UChar byte); +EXTERN_C Void rt_out32(UShort port, UInt byte); + +EXTERN_C Void rt_wait_400ns(); +EXTERN_C Void rt_halt(); +EXTERN_C Void rt_cli(); +EXTERN_C Void rt_sti(); +EXTERN_C Void rt_cld(); +EXTERN_C Void rt_std(); +} // namespace Kernel::HAL EXTERN_C Kernel::Void idt_handle_generic(Kernel::UIntPtr rsp); EXTERN_C Kernel::Void idt_handle_gpf(Kernel::UIntPtr rsp); @@ -311,4 +283,4 @@ EXTERN_C ATTRIBUTE(naked) Kernel::Void hal_load_idt(Kernel::HAL::Register64 ptr) EXTERN_C ATTRIBUTE(naked) Kernel::Void hal_load_gdt(Kernel::HAL::Register64 ptr); inline Kernel::VoidPtr kKernelBitMpStart = nullptr; -inline Kernel::UIntPtr kKernelBitMpSize = 0UL; +inline Kernel::UIntPtr kKernelBitMpSize = 0UL; diff --git a/dev/kernel/HALKit/AMD64/Storage/AHCI+Generic.cc b/dev/kernel/HALKit/AMD64/Storage/AHCI+Generic.cc index 576c151b..aa9ab2cb 100644 --- a/dev/kernel/HALKit/AMD64/Storage/AHCI+Generic.cc +++ b/dev/kernel/HALKit/AMD64/Storage/AHCI+Generic.cc @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss Corporation, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss Corporation, all rights reserved. ------------------------------------------- */ @@ -15,23 +15,23 @@ * */ +#include #include #include -#include #include -#include -#include -#include -#include +#include #include +#include #include -#include +#include +#include +#include #define kHBAErrTaskFile (1 << 30) -#define kHBAPxCmdST (0x0001) -#define kHBAPxCmdFre (0x0010) -#define kHBAPxCmdFR (0x4000) -#define kHBAPxCmdCR (0x8000) +#define kHBAPxCmdST (0x0001) +#define kHBAPxCmdFre (0x0010) +#define kHBAPxCmdFR (0x4000) +#define kHBAPxCmdCR (0x8000) #define kSATALBAMode (1 << 6) @@ -39,87 +39,84 @@ #define kSATASRDrq (0x08) #define kHBABohcBiosOwned (1 << 0) -#define kHBABohcOSOwned (1 << 1) +#define kHBABohcOSOwned (1 << 1) #define kSATAPortCnt (0x20) -#define kSATASig (0x00000101) +#define kSATASig (0x00000101) #define kSATAPISig (0xEB140101) #define kSATAProgIfAHCI (0x01) -#define kSATASubClass (0x06) -#define kSATABar5 (0x24) +#define kSATASubClass (0x06) +#define kSATABar5 (0x24) using namespace Kernel; STATIC PCI::Device kSATADev; STATIC HbaMemRef kSATAHba; -STATIC Lba kSATASectorCount = 0UL; -STATIC UInt16 kSATAIndex = 0U; -STATIC Char kCurrentDiskModel[50] = {"GENERIC SATA"}; -STATIC UInt16 kSATAPortsImplemented = 0U; +STATIC Lba kSATASectorCount = 0UL; +STATIC UInt16 kSATAIndex = 0U; +STATIC Char kCurrentDiskModel[50] = {"GENERIC SATA"}; +STATIC UInt16 kSATAPortsImplemented = 0U; template -STATIC Void drv_std_input_output_ahci(UInt64 lba, UInt8* buffer, SizeT sector_sz, SizeT size_buffer) noexcept; +STATIC Void drv_std_input_output_ahci(UInt64 lba, UInt8* buffer, SizeT sector_sz, + SizeT size_buffer) noexcept; STATIC Int32 drv_find_cmd_slot_ahci(HbaPort* port) noexcept; STATIC Void drv_compute_disk_ahci() noexcept; -STATIC Void drv_compute_disk_ahci() noexcept -{ - kSATASectorCount = 0UL; +STATIC Void drv_compute_disk_ahci() noexcept { + kSATASectorCount = 0UL; - /// Normally 512 bytes, but add an additional 512 bytes to make 1 KIB. - const UInt16 kSzIdent = 512; + /// Normally 512 bytes, but add an additional 512 bytes to make 1 KIB. + const UInt16 kSzIdent = 512; - /// Push it to the stack - UInt8* identify_data = new UInt8[kSzIdent]; + /// Push it to the stack + UInt8* identify_data = new UInt8[kSzIdent]; - /// Send AHCI command for identification. - drv_std_input_output_ahci(0, identify_data, kAHCISectorSize, kSzIdent); + /// Send AHCI command for identification. + drv_std_input_output_ahci(0, identify_data, kAHCISectorSize, kSzIdent); - /// Extract 48-bit LBA. - UInt64 lba48_sectors = 0; - lba48_sectors |= (UInt64)identify_data[100]; - lba48_sectors |= (UInt64)identify_data[101] << 16; - lba48_sectors |= (UInt64)identify_data[102] << 32; + /// Extract 48-bit LBA. + UInt64 lba48_sectors = 0; + lba48_sectors |= (UInt64) identify_data[100]; + lba48_sectors |= (UInt64) identify_data[101] << 16; + lba48_sectors |= (UInt64) identify_data[102] << 32; - /// Now verify if lba48 - if (lba48_sectors == 0) - kSATASectorCount = (identify_data[61] << 16) | identify_data[60]; - else - kSATASectorCount = lba48_sectors; + /// Now verify if lba48 + if (lba48_sectors == 0) + kSATASectorCount = (identify_data[61] << 16) | identify_data[60]; + else + kSATASectorCount = lba48_sectors; - for (Int32 i = 0; i < 20; i++) - { - kCurrentDiskModel[i * 2] = (identify_data[27 + i] >> 8) & 0xFF; - kCurrentDiskModel[i * 2 + 1] = identify_data[27 + i] & 0xFF; - } + for (Int32 i = 0; i < 20; i++) { + kCurrentDiskModel[i * 2] = (identify_data[27 + i] >> 8) & 0xFF; + kCurrentDiskModel[i * 2 + 1] = identify_data[27 + i] & 0xFF; + } - kCurrentDiskModel[40] = '\0'; + kCurrentDiskModel[40] = '\0'; - (Void)(kout << "SATA Sector Count: " << hex_number(kSATASectorCount) << kendl); - (Void)(kout << "SATA Disk Model: " << kCurrentDiskModel << kendl); + (Void)(kout << "SATA Sector Count: " << hex_number(kSATASectorCount) << kendl); + (Void)(kout << "SATA Disk Model: " << kCurrentDiskModel << kendl); - delete[] identify_data; - identify_data = nullptr; + delete[] identify_data; + identify_data = nullptr; } /// @brief Finds a command slot for a HBA port. /// @param port The port to search on. /// @return The slot, or ~0. -STATIC Int32 drv_find_cmd_slot_ahci(HbaPort* port) noexcept -{ - UInt32 slots = port->Sact | port->Ci; +STATIC Int32 drv_find_cmd_slot_ahci(HbaPort* port) noexcept { + UInt32 slots = port->Sact | port->Ci; - for (Int32 i = 0; i < kSATAPortCnt; ++i) // AHCI supports up to 32 slots - { - if ((slots & (1U << i)) == 0) - return i; - } + for (Int32 i = 0; i < kSATAPortCnt; ++i) // AHCI supports up to 32 slots + { + if ((slots & (1U << i)) == 0) return i; + } - return -1; // no free slot found + return -1; // no free slot found } /// @brief Send an AHCI command, according to the template parameters. @@ -128,225 +125,204 @@ STATIC Int32 drv_find_cmd_slot_ahci(HbaPort* port) noexcept /// @param sector_sz The disk's sector size (unused) /// @param size_buffer The size of the **buffer** parameter. template -STATIC Void drv_std_input_output_ahci(UInt64 lba, UInt8* buffer, SizeT sector_sz, SizeT size_buffer) noexcept -{ - UIntPtr slot = 0UL; +STATIC Void drv_std_input_output_ahci(UInt64 lba, UInt8* buffer, SizeT sector_sz, + SizeT size_buffer) noexcept { + UIntPtr slot = 0UL; - slot = drv_find_cmd_slot_ahci(&kSATAHba->Ports[kSATAIndex]); + slot = drv_find_cmd_slot_ahci(&kSATAHba->Ports[kSATAIndex]); - if (slot == ~0UL) - { - err_global_get() = kErrorDisk; - return; - } + if (slot == ~0UL) { + err_global_get() = kErrorDisk; + return; + } - if (size_buffer > mib_cast(4) || - sector_sz > kAHCISectorSize) - return; + if (size_buffer > mib_cast(4) || sector_sz > kAHCISectorSize) return; - if (!Write) - { - // Zero-memory the buffer field. - rt_set_memory(buffer, 0, size_buffer); - } + if (!Write) { + // Zero-memory the buffer field. + rt_set_memory(buffer, 0, size_buffer); + } - /// prepare command header. - volatile HbaCmdHeader* command_header = ((volatile HbaCmdHeader*)(((UInt64)kSATAHba->Ports[kSATAIndex].Clb))); + /// prepare command header. + volatile HbaCmdHeader* command_header = + ((volatile HbaCmdHeader*) (((UInt64) kSATAHba->Ports[kSATAIndex].Clb))); - /// Offset to specific command slot. - command_header += slot; + /// Offset to specific command slot. + command_header += slot; - /// check for command header. - MUST_PASS(command_header); + /// check for command header. + MUST_PASS(command_header); - command_header->Struc.Cfl = sizeof(FisRegH2D) / sizeof(UInt32); - command_header->Struc.Write = Write; - command_header->Prdtl = 8; + command_header->Struc.Cfl = sizeof(FisRegH2D) / sizeof(UInt32); + command_header->Struc.Write = Write; + command_header->Prdtl = 8; - auto ctba_phys = ((UInt64)command_header->Ctbau << 32) | command_header->Ctba; - auto command_table = reinterpret_cast(ctba_phys); + auto ctba_phys = ((UInt64) command_header->Ctbau << 32) | command_header->Ctba; + auto command_table = reinterpret_cast(ctba_phys); - MUST_PASS(command_table); + MUST_PASS(command_table); - UIntPtr buffer_phys = HAL::hal_get_phys_address(buffer); - SizeT bytes_remaining = size_buffer; + UIntPtr buffer_phys = HAL::hal_get_phys_address(buffer); + SizeT bytes_remaining = size_buffer; - command_table->Prdt[0].Dba = (UInt32)(buffer_phys & 0xFFFFFFFF); - command_table->Prdt[0].Dbau = (UInt32)(buffer_phys >> 32); - command_table->Prdt[0].Dbc = bytes_remaining - 1; - command_table->Prdt[0].Ie = NO; + command_table->Prdt[0].Dba = (UInt32) (buffer_phys & 0xFFFFFFFF); + command_table->Prdt[0].Dbau = (UInt32) (buffer_phys >> 32); + command_table->Prdt[0].Dbc = bytes_remaining - 1; + command_table->Prdt[0].Ie = NO; - volatile FisRegH2D* h2d_fis = (volatile FisRegH2D*)(&command_table->Cfis[0]); + volatile FisRegH2D* h2d_fis = (volatile FisRegH2D*) (&command_table->Cfis[0]); - h2d_fis->FisType = kFISTypeRegH2D; - h2d_fis->CmdOrCtrl = CommandOrCTRL; - h2d_fis->Command = (Identify ? (kAHCICmdIdentify) : (Write ? kAHCICmdWriteDmaEx : kAHCICmdReadDmaEx)); + h2d_fis->FisType = kFISTypeRegH2D; + h2d_fis->CmdOrCtrl = CommandOrCTRL; + h2d_fis->Command = + (Identify ? (kAHCICmdIdentify) : (Write ? kAHCICmdWriteDmaEx : kAHCICmdReadDmaEx)); - h2d_fis->Lba0 = (lba)&0xFF; - h2d_fis->Lba1 = (lba >> 8) & 0xFF; - h2d_fis->Lba2 = (lba >> 16) & 0xFF; + h2d_fis->Lba0 = (lba) & 0xFF; + h2d_fis->Lba1 = (lba >> 8) & 0xFF; + h2d_fis->Lba2 = (lba >> 16) & 0xFF; - h2d_fis->Device = kSATALBAMode; + h2d_fis->Device = kSATALBAMode; - h2d_fis->Lba3 = (lba >> 24) & 0xFF; - h2d_fis->Lba4 = (lba >> 32) & 0xFF; - h2d_fis->Lba5 = (lba >> 40) & 0xFF; + h2d_fis->Lba3 = (lba >> 24) & 0xFF; + h2d_fis->Lba4 = (lba >> 32) & 0xFF; + h2d_fis->Lba5 = (lba >> 40) & 0xFF; - h2d_fis->CountLow = (size_buffer)&0xFF; - h2d_fis->CountHigh = (size_buffer >> 8) & 0xFF; + h2d_fis->CountLow = (size_buffer) & 0xFF; + h2d_fis->CountHigh = (size_buffer >> 8) & 0xFF; - kSATAHba->Ports[kSATAIndex].Ci = (1 << slot); + kSATAHba->Ports[kSATAIndex].Ci = (1 << slot); - for (Int32 i = 0; i < 1000000; ++i) - { - if (!(kSATAHba->Ports[kSATAIndex].Ci & (1 << slot))) - break; - } + for (Int32 i = 0; i < 1000000; ++i) { + if (!(kSATAHba->Ports[kSATAIndex].Ci & (1 << slot))) break; + } - if (kSATAHba->Is & kHBAErrTaskFile) - { - err_global_get() = kErrorDiskIsCorrupted; - return; - } + if (kSATAHba->Is & kHBAErrTaskFile) { + err_global_get() = kErrorDiskIsCorrupted; + return; + } - err_global_get() = kErrorSuccess; + err_global_get() = kErrorSuccess; } /*** - @brief Gets the number of sectors inside the drive. - @return Sector size in bytes. + @brief Gets the number of sectors inside the drive. + @return Sector size in bytes. */ -SizeT drv_get_sector_count_ahci() -{ - return kSATASectorCount; +SizeT drv_get_sector_count_ahci() { + return kSATASectorCount; } /// @brief Get the drive size. /// @return Disk size in bytes. -SizeT drv_get_size_ahci() -{ - return drv_get_sector_count() * kAHCISectorSize; +SizeT drv_get_size_ahci() { + return drv_get_sector_count() * kAHCISectorSize; } /// @brief Enable Host and probe using the IDENTIFY command. -STATIC BOOL ahci_enable_and_probe() -{ - if (kSATAHba->Cap == 0x0) - return NO; +STATIC BOOL ahci_enable_and_probe() { + if (kSATAHba->Cap == 0x0) return NO; - kSATAHba->Ports[kSATAIndex].Cmd &= ~kHBAPxCmdFre; - kSATAHba->Ports[kSATAIndex].Cmd &= ~kHBAPxCmdST; + kSATAHba->Ports[kSATAIndex].Cmd &= ~kHBAPxCmdFre; + kSATAHba->Ports[kSATAIndex].Cmd &= ~kHBAPxCmdST; - while (YES) - { - if (kSATAHba->Ports[kSATAIndex].Cmd & kHBAPxCmdCR) - continue; + while (YES) { + if (kSATAHba->Ports[kSATAIndex].Cmd & kHBAPxCmdCR) continue; - if (kSATAHba->Ports[kSATAIndex].Cmd & kHBAPxCmdFR) - continue; + if (kSATAHba->Ports[kSATAIndex].Cmd & kHBAPxCmdFR) continue; - break; - } + break; + } - // Now we are ready. + // Now we are ready. - kSATAHba->Ports[kSATAIndex].Cmd |= kHBAPxCmdFre; - kSATAHba->Ports[kSATAIndex].Cmd |= kHBAPxCmdST; + kSATAHba->Ports[kSATAIndex].Cmd |= kHBAPxCmdFre; + kSATAHba->Ports[kSATAIndex].Cmd |= kHBAPxCmdST; - if (kSATAHba->Bohc & kHBABohcBiosOwned) - { - kSATAHba->Bohc |= kHBABohcOSOwned; + if (kSATAHba->Bohc & kHBABohcBiosOwned) { + kSATAHba->Bohc |= kHBABohcOSOwned; - while (kSATAHba->Bohc & kHBABohcBiosOwned) - { - ; - } - } + while (kSATAHba->Bohc & kHBABohcBiosOwned) { + ; + } + } - drv_compute_disk_ahci(); + drv_compute_disk_ahci(); - return YES; + return YES; } /// @brief Initializes an AHCI disk. /// @param pi the amount of ports that have been detected. /// @param atapi reference value, tells whether we should detect ATAPI instead of SATA. /// @return if the disk was successfully initialized or not. -STATIC Bool drv_std_init_ahci(UInt16& pi, BOOL& atapi) -{ - PCI::Iterator iterator(Types::PciDeviceKind::MassStorageController); +STATIC Bool drv_std_init_ahci(UInt16& pi, BOOL& atapi) { + PCI::Iterator iterator(Types::PciDeviceKind::MassStorageController); - for (SizeT device_index = 0; device_index < NE_BUS_COUNT; ++device_index) - { - kSATADev = iterator[device_index].Leak(); // Leak device. + for (SizeT device_index = 0; device_index < NE_BUS_COUNT; ++device_index) { + kSATADev = iterator[device_index].Leak(); // Leak device. - if (kSATADev.Subclass() == kSATASubClass && - kSATADev.ProgIf() == kSATAProgIfAHCI) - { - kSATADev.EnableMmio(); - kSATADev.BecomeBusMaster(); + if (kSATADev.Subclass() == kSATASubClass && kSATADev.ProgIf() == kSATAProgIfAHCI) { + kSATADev.EnableMmio(); + kSATADev.BecomeBusMaster(); - HbaMem* mem_ahci = (HbaMem*)kSATADev.Bar(kSATABar5); + HbaMem* mem_ahci = (HbaMem*) kSATADev.Bar(kSATABar5); - HAL::mm_map_page((VoidPtr)mem_ahci, (VoidPtr)mem_ahci, HAL::kMMFlagsPresent | HAL::kMMFlagsWr | HAL::kMMFlagsPCD | HAL::kMMFlagsPwt); + HAL::mm_map_page( + (VoidPtr) mem_ahci, (VoidPtr) mem_ahci, + HAL::kMMFlagsPresent | HAL::kMMFlagsWr | HAL::kMMFlagsPCD | HAL::kMMFlagsPwt); - UInt32 ports_implemented = mem_ahci->Pi; - UInt16 ahci_index = 0; + UInt32 ports_implemented = mem_ahci->Pi; + UInt16 ahci_index = 0; - pi = ports_implemented; + pi = ports_implemented; - const UInt16 kSATAMaxPortsImplemented = ports_implemented; - const UInt32 kSATASignature = kSATASig; - const UInt32 kSATAPISignature = kSATAPISig; - const UInt8 kSATAPresent = 0x03; - const UInt8 kSATAIPMActive = 0x01; + const UInt16 kSATAMaxPortsImplemented = ports_implemented; + const UInt32 kSATASignature = kSATASig; + const UInt32 kSATAPISignature = kSATAPISig; + const UInt8 kSATAPresent = 0x03; + const UInt8 kSATAIPMActive = 0x01; - if (kSATAMaxPortsImplemented < 1) - continue; + if (kSATAMaxPortsImplemented < 1) continue; - while (ports_implemented) - { - UInt8 ipm = (mem_ahci->Ports[ahci_index].Ssts >> 8) & 0x0F; - UInt8 det = (mem_ahci->Ports[ahci_index].Ssts & 0x0F); + while (ports_implemented) { + UInt8 ipm = (mem_ahci->Ports[ahci_index].Ssts >> 8) & 0x0F; + UInt8 det = (mem_ahci->Ports[ahci_index].Ssts & 0x0F); - if (det != kSATAPresent || ipm != kSATAIPMActive) - continue; + if (det != kSATAPresent || ipm != kSATAIPMActive) continue; - if ((mem_ahci->Ports[ahci_index].Sig == kSATASignature) || - (atapi && kSATAPISignature == mem_ahci->Ports[ahci_index].Sig)) - { - kSATAIndex = ahci_index; - kSATAHba = mem_ahci; + if ((mem_ahci->Ports[ahci_index].Sig == kSATASignature) || + (atapi && kSATAPISignature == mem_ahci->Ports[ahci_index].Sig)) { + kSATAIndex = ahci_index; + kSATAHba = mem_ahci; - goto success_hba_fetch; - } + goto success_hba_fetch; + } - ports_implemented >>= 1; - ++ahci_index; - } - } - } + ports_implemented >>= 1; + ++ahci_index; + } + } + } - err_global_get() = kErrorDisk; + err_global_get() = kErrorDisk; - return NO; + return NO; success_hba_fetch: - if (ahci_enable_and_probe()) - { - err_global_get() = kErrorSuccess; + if (ahci_enable_and_probe()) { + err_global_get() = kErrorSuccess; - return YES; - } + return YES; + } - return NO; + return NO; } /// @brief Checks if an AHCI device is detected. /// @return Either if detected, or not found. -Bool drv_std_detected_ahci() -{ - return kSATADev.DeviceId() != (UShort)PCI::PciConfigKind::Invalid && kSATADev.Bar(kSATABar5) != 0; +Bool drv_std_detected_ahci() { + return kSATADev.DeviceId() != (UShort) PCI::PciConfigKind::Invalid && + kSATADev.Bar(kSATABar5) != 0; } // ================================================================================================ @@ -362,133 +338,121 @@ Bool drv_std_detected_ahci() //////////////////////////////////////////////////// /// //////////////////////////////////////////////////// -Void drv_std_write(UInt64 lba, Char* buffer, SizeT sector_sz, SizeT size_buffer) -{ - drv_std_input_output_ahci(lba, reinterpret_cast(buffer), sector_sz, size_buffer); +Void drv_std_write(UInt64 lba, Char* buffer, SizeT sector_sz, SizeT size_buffer) { + drv_std_input_output_ahci(lba, reinterpret_cast(buffer), sector_sz, + size_buffer); } //////////////////////////////////////////////////// /// //////////////////////////////////////////////////// -Void drv_std_read(UInt64 lba, Char* buffer, SizeT sector_sz, SizeT size_buffer) -{ - drv_std_input_output_ahci(lba, reinterpret_cast(buffer), sector_sz, size_buffer); +Void drv_std_read(UInt64 lba, Char* buffer, SizeT sector_sz, SizeT size_buffer) { + drv_std_input_output_ahci(lba, reinterpret_cast(buffer), sector_sz, + size_buffer); } //////////////////////////////////////////////////// /// //////////////////////////////////////////////////// -Bool drv_std_init(UInt16& pi) -{ - BOOL atapi = NO; - return drv_std_init_ahci(pi, atapi); +Bool drv_std_init(UInt16& pi) { + BOOL atapi = NO; + return drv_std_init_ahci(pi, atapi); } //////////////////////////////////////////////////// /// //////////////////////////////////////////////////// -Bool drv_std_detected(Void) -{ - return drv_std_detected_ahci(); +Bool drv_std_detected(Void) { + return drv_std_detected_ahci(); } //////////////////////////////////////////////////// /** - @brief Gets the number of sectors inside the drive. - @return Sector size in bytes. + @brief Gets the number of sectors inside the drive. + @return Sector size in bytes. */ //////////////////////////////////////////////////// -SizeT drv_get_sector_count() -{ - return drv_get_sector_count_ahci(); +SizeT drv_get_sector_count() { + return drv_get_sector_count_ahci(); } //////////////////////////////////////////////////// /// @brief Get the drive size. /// @return Disk size in bytes. //////////////////////////////////////////////////// -SizeT drv_get_size() -{ - return drv_get_size_ahci(); +SizeT drv_get_size() { + return drv_get_size_ahci(); } -#endif // ifdef __AHCI__ +#endif // ifdef __AHCI__ -namespace Kernel -{ - /// @brief Initialize an AHCI device (StorageKit) - UInt16 sk_init_ahci_device(BOOL atapi) - { - UInt16 pi = 0; +namespace Kernel { +/// @brief Initialize an AHCI device (StorageKit) +UInt16 sk_init_ahci_device(BOOL atapi) { + UInt16 pi = 0; - if (drv_std_init_ahci(pi, atapi)) - kSATAPortsImplemented = pi; + if (drv_std_init_ahci(pi, atapi)) kSATAPortsImplemented = pi; - return pi; - } + return pi; +} - /// @brief Implementation details namespace. - namespace Detail - { - /// @brief Read AHCI device. - /// @param self device - /// @param mnt mounted disk. - STATIC Void sk_io_read_ahci(IDeviceObject* self, MountpointInterface* mnt) - { - AHCIDeviceInterface* dev = (AHCIDeviceInterface*)self; +/// @brief Implementation details namespace. +namespace Detail { + /// @brief Read AHCI device. + /// @param self device + /// @param mnt mounted disk. + STATIC Void sk_io_read_ahci(IDeviceObject* self, MountpointInterface* mnt) { + AHCIDeviceInterface* dev = (AHCIDeviceInterface*) self; - err_global_get() = kErrorDisk; + err_global_get() = kErrorDisk; - if (!dev) - return; + if (!dev) return; - auto disk = mnt->GetAddressOf(dev->GetIndex()); + auto disk = mnt->GetAddressOf(dev->GetIndex()); - if (!disk) - return; + if (!disk) return; - err_global_get() = kErrorSuccess; + err_global_get() = kErrorSuccess; - drv_std_input_output_ahci(disk->fPacket.fPacketLba, (UInt8*)disk->fPacket.fPacketContent, kAHCISectorSize, disk->fPacket.fPacketSize); - } + drv_std_input_output_ahci(disk->fPacket.fPacketLba, + (UInt8*) disk->fPacket.fPacketContent, kAHCISectorSize, + disk->fPacket.fPacketSize); + } - /// @brief Write AHCI device. - /// @param self device - /// @param mnt mounted disk. - STATIC Void sk_io_write_ahci(IDeviceObject* self, MountpointInterface* mnt) - { - AHCIDeviceInterface* dev = (AHCIDeviceInterface*)self; + /// @brief Write AHCI device. + /// @param self device + /// @param mnt mounted disk. + STATIC Void sk_io_write_ahci(IDeviceObject* self, + MountpointInterface* mnt) { + AHCIDeviceInterface* dev = (AHCIDeviceInterface*) self; - err_global_get() = kErrorDisk; + err_global_get() = kErrorDisk; - if (!dev) - return; + if (!dev) return; - auto disk = mnt->GetAddressOf(dev->GetIndex()); + auto disk = mnt->GetAddressOf(dev->GetIndex()); - if (!disk) - return; + if (!disk) return; - err_global_get() = kErrorSuccess; + err_global_get() = kErrorSuccess; - drv_std_input_output_ahci(disk->fPacket.fPacketLba, (UInt8*)disk->fPacket.fPacketContent, kAHCISectorSize, disk->fPacket.fPacketSize); - } - } // namespace Detail + drv_std_input_output_ahci(disk->fPacket.fPacketLba, + (UInt8*) disk->fPacket.fPacketContent, kAHCISectorSize, + disk->fPacket.fPacketSize); + } +} // namespace Detail - /// @brief Acquires a new AHCI device with drv_index in mind. - /// @param drv_index The drive index to assign. - /// @return A wrapped device interface if successful, or error code. - ErrorOr sk_acquire_ahci_device(Int32 drv_index) - { - if (!drv_std_detected_ahci()) - return ErrorOr(kErrorDisk); +/// @brief Acquires a new AHCI device with drv_index in mind. +/// @param drv_index The drive index to assign. +/// @return A wrapped device interface if successful, or error code. +ErrorOr sk_acquire_ahci_device(Int32 drv_index) { + if (!drv_std_detected_ahci()) return ErrorOr(kErrorDisk); - AHCIDeviceInterface device(Detail::sk_io_read_ahci, - Detail::sk_io_write_ahci); + AHCIDeviceInterface device(Detail::sk_io_read_ahci, Detail::sk_io_write_ahci); - device.SetPortsImplemented(kSATAPortsImplemented); - device.SetIndex(drv_index); + device.SetPortsImplemented(kSATAPortsImplemented); + device.SetIndex(drv_index); - return ErrorOr(device); - } -} // namespace Kernel + return ErrorOr(device); +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/AMD64/Storage/DMA+Generic.cc b/dev/kernel/HALKit/AMD64/Storage/DMA+Generic.cc index f04d25eb..a7361778 100644 --- a/dev/kernel/HALKit/AMD64/Storage/DMA+Generic.cc +++ b/dev/kernel/HALKit/AMD64/Storage/DMA+Generic.cc @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -15,9 +15,9 @@ * */ -#include #include #include +#include #if defined(__ATA_DMA__) @@ -28,185 +28,165 @@ using namespace Kernel::HAL; /// BUGS: 0 -STATIC Boolean kATADetected = false; -STATIC Int32 kATADeviceType = kATADeviceCount; +STATIC Boolean kATADetected = false; +STATIC Int32 kATADeviceType = kATADeviceCount; STATIC UInt16 kATAIdentifyData[kATADataLen] = {0}; STATIC Kernel::PCI::Device kATADevice; -STATIC Char kATADiskModel[50] = {"GENERIC DMA"}; +STATIC Char kATADiskModel[50] = {"GENERIC DMA"}; -Boolean drv_std_wait_io(UInt16 IO) -{ - for (int i = 0; i < 400; i++) - rt_in8(IO + ATA_REG_STATUS); +Boolean drv_std_wait_io(UInt16 IO) { + for (int i = 0; i < 400; i++) rt_in8(IO + ATA_REG_STATUS); ATAWaitForIO_Retry: - auto status_rdy = rt_in8(IO + ATA_REG_STATUS); + auto status_rdy = rt_in8(IO + ATA_REG_STATUS); - if ((status_rdy & ATA_SR_BSY)) - goto ATAWaitForIO_Retry; + if ((status_rdy & ATA_SR_BSY)) goto ATAWaitForIO_Retry; ATAWaitForIO_Retry2: - status_rdy = rt_in8(IO + ATA_REG_STATUS); + status_rdy = rt_in8(IO + ATA_REG_STATUS); - if (status_rdy & ATA_SR_ERR) - return false; + if (status_rdy & ATA_SR_ERR) return false; - if (!(status_rdy & ATA_SR_DRDY)) - goto ATAWaitForIO_Retry2; + if (!(status_rdy & ATA_SR_DRDY)) goto ATAWaitForIO_Retry2; - return true; + return true; } -Void drv_std_select(UInt16 Bus) -{ - if (Bus == ATA_PRIMARY_IO) - rt_out8(Bus + ATA_REG_HDDEVSEL, ATA_PRIMARY_SEL); - else - rt_out8(Bus + ATA_REG_HDDEVSEL, ATA_SECONDARY_SEL); +Void drv_std_select(UInt16 Bus) { + if (Bus == ATA_PRIMARY_IO) + rt_out8(Bus + ATA_REG_HDDEVSEL, ATA_PRIMARY_SEL); + else + rt_out8(Bus + ATA_REG_HDDEVSEL, ATA_SECONDARY_SEL); } -Boolean drv_std_init(UInt16 Bus, UInt8 Drive, UInt16& OutBus, UInt8& OutMaster) -{ - PCI::Iterator iterator(Types::PciDeviceKind::MassStorageController); - - for (SizeT device_index = 0; device_index < NE_BUS_COUNT; ++device_index) - { - kATADevice = iterator[device_index].Leak(); // And then leak the reference. +Boolean drv_std_init(UInt16 Bus, UInt8 Drive, UInt16& OutBus, UInt8& OutMaster) { + PCI::Iterator iterator(Types::PciDeviceKind::MassStorageController); - /// IDE interface - if (kATADevice.Subclass() == 0x01) - { + for (SizeT device_index = 0; device_index < NE_BUS_COUNT; ++device_index) { + kATADevice = iterator[device_index].Leak(); // And then leak the reference. - break; - } - } + /// IDE interface + if (kATADevice.Subclass() == 0x01) { + break; + } + } - return NO; + return NO; } -namespace Kernel::Detail -{ - struct PRDEntry final - { - UInt32 mAddress; - UInt16 mByteCount; - UInt16 mFlags; /// @param PRD flags, set to 0x8000 to indicate end of prd. - }; -} // namespace Kernel::Detail +namespace Kernel::Detail { +struct PRDEntry final { + UInt32 mAddress; + UInt16 mByteCount; + UInt16 mFlags; /// @param PRD flags, set to 0x8000 to indicate end of prd. +}; +} // namespace Kernel::Detail static UIntPtr kReadAddr = mib_cast(2); static UIntPtr kWriteAddr = mib_cast(2) + kib_cast(64); -Void drv_std_read(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) -{ - Lba /= SectorSz; +Void drv_std_read(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) { + Lba /= SectorSz; - if (Size > kib_cast(64)) - return; + if (Size > kib_cast(64)) return; - UInt8 Command = ((!Master) ? 0xE0 : 0xF0); + UInt8 Command = ((!Master) ? 0xE0 : 0xF0); - rt_copy_memory((VoidPtr)Buf, (VoidPtr)kReadAddr, Size); + rt_copy_memory((VoidPtr) Buf, (VoidPtr) kReadAddr, Size); - drv_std_select(IO); + drv_std_select(IO); - rt_out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); + rt_out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); - rt_out8(IO + ATA_REG_SEC_COUNT0, ((Size + SectorSz - 1) / SectorSz)); + rt_out8(IO + ATA_REG_SEC_COUNT0, ((Size + SectorSz - 1) / SectorSz)); - rt_out8(IO + ATA_REG_LBA0, (Lba)&0xFF); - rt_out8(IO + ATA_REG_LBA1, (Lba) >> 8); - rt_out8(IO + ATA_REG_LBA2, (Lba) >> 16); - rt_out8(IO + ATA_REG_LBA3, (Lba) >> 24); + rt_out8(IO + ATA_REG_LBA0, (Lba) & 0xFF); + rt_out8(IO + ATA_REG_LBA1, (Lba) >> 8); + rt_out8(IO + ATA_REG_LBA2, (Lba) >> 16); + rt_out8(IO + ATA_REG_LBA3, (Lba) >> 24); - Kernel::Detail::PRDEntry* prd = (Kernel::Detail::PRDEntry*)(kATADevice.Bar(0x20) + 4); // The PRDEntry is not correct. + Kernel::Detail::PRDEntry* prd = + (Kernel::Detail::PRDEntry*) (kATADevice.Bar(0x20) + 4); // The PRDEntry is not correct. - prd->mAddress = (UInt32)(UIntPtr)kReadAddr; - prd->mByteCount = Size - 1; - prd->mFlags = 0x8000; // indicate the end of prd. + prd->mAddress = (UInt32) (UIntPtr) kReadAddr; + prd->mByteCount = Size - 1; + prd->mFlags = 0x8000; // indicate the end of prd. - rt_out32(kATADevice.Bar(0x20) + 0x04, (UInt32)(UIntPtr)prd); + rt_out32(kATADevice.Bar(0x20) + 0x04, (UInt32) (UIntPtr) prd); - rt_out8(kATADevice.Bar(0x20) + ATA_REG_COMMAND, ATA_CMD_READ_DMA); + rt_out8(kATADevice.Bar(0x20) + ATA_REG_COMMAND, ATA_CMD_READ_DMA); - rt_out8(kATADevice.Bar(0x20) + 0x00, 0x09); // Start DMA engine + rt_out8(kATADevice.Bar(0x20) + 0x00, 0x09); // Start DMA engine - while (rt_in8(kATADevice.Bar(0x20) + ATA_REG_STATUS) & 0x01) - ; + while (rt_in8(kATADevice.Bar(0x20) + ATA_REG_STATUS) & 0x01); - rt_out8(kATADevice.Bar(0x20) + 0x00, 0x00); // Stop DMA engine + rt_out8(kATADevice.Bar(0x20) + 0x00, 0x00); // Stop DMA engine - rt_copy_memory((VoidPtr)kReadAddr, (VoidPtr)Buf, Size); + rt_copy_memory((VoidPtr) kReadAddr, (VoidPtr) Buf, Size); - delete prd; - prd = nullptr; + delete prd; + prd = nullptr; } -Void drv_std_write(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) -{ - Lba /= SectorSz; +Void drv_std_write(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) { + Lba /= SectorSz; - if (Size > kib_cast(64)) - return; + if (Size > kib_cast(64)) return; - UInt8 Command = ((!Master) ? 0xE0 : 0xF0); + UInt8 Command = ((!Master) ? 0xE0 : 0xF0); - rt_copy_memory((VoidPtr)Buf, (VoidPtr)kWriteAddr, Size); + rt_copy_memory((VoidPtr) Buf, (VoidPtr) kWriteAddr, Size); - rt_out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); + rt_out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); - rt_out8(IO + ATA_REG_SEC_COUNT0, ((Size + (SectorSz - 1)) / SectorSz)); + rt_out8(IO + ATA_REG_SEC_COUNT0, ((Size + (SectorSz - 1)) / SectorSz)); - rt_out8(IO + ATA_REG_LBA0, (Lba)&0xFF); - rt_out8(IO + ATA_REG_LBA1, (Lba) >> 8); - rt_out8(IO + ATA_REG_LBA2, (Lba) >> 16); - rt_out8(IO + ATA_REG_LBA3, (Lba) >> 24); + rt_out8(IO + ATA_REG_LBA0, (Lba) & 0xFF); + rt_out8(IO + ATA_REG_LBA1, (Lba) >> 8); + rt_out8(IO + ATA_REG_LBA2, (Lba) >> 16); + rt_out8(IO + ATA_REG_LBA3, (Lba) >> 24); - Kernel::Detail::PRDEntry* prd = (Kernel::Detail::PRDEntry*)(kATADevice.Bar(0x20) + 4); + Kernel::Detail::PRDEntry* prd = (Kernel::Detail::PRDEntry*) (kATADevice.Bar(0x20) + 4); - prd->mAddress = (UInt32)(UIntPtr)kWriteAddr; - prd->mByteCount = Size - 1; - prd->mFlags = 0x8000; + prd->mAddress = (UInt32) (UIntPtr) kWriteAddr; + prd->mByteCount = Size - 1; + prd->mFlags = 0x8000; - rt_out32(kATADevice.Bar(0x20) + 0x04, (UInt32)(UIntPtr)prd); - rt_out8(kATADevice.Bar(0x20) + ATA_REG_COMMAND, ATA_CMD_WRITE_DMA); + rt_out32(kATADevice.Bar(0x20) + 0x04, (UInt32) (UIntPtr) prd); + rt_out8(kATADevice.Bar(0x20) + ATA_REG_COMMAND, ATA_CMD_WRITE_DMA); - rt_out8(IO + 0x00, 0x09); // Start DMA engine + rt_out8(IO + 0x00, 0x09); // Start DMA engine - while (rt_in8(kATADevice.Bar(0x20) + ATA_REG_STATUS) & 0x01) - ; + while (rt_in8(kATADevice.Bar(0x20) + ATA_REG_STATUS) & 0x01); - rt_out8(kATADevice.Bar(0x20) + 0x00, 0x00); // Stop DMA engine + rt_out8(kATADevice.Bar(0x20) + 0x00, 0x00); // Stop DMA engine - delete prd; - prd = nullptr; + delete prd; + prd = nullptr; } /***********************************************************************************/ /// @brief Is ATA detected? /***********************************************************************************/ -Boolean drv_std_detected(Void) -{ - return kATADetected; +Boolean drv_std_detected(Void) { + return kATADetected; } /***********************************************************************************/ /*** - @brief Gets the number of sectors inside the drive. - @return Number of sectors, or zero. + @brief Gets the number of sectors inside the drive. + @return Number of sectors, or zero. */ /***********************************************************************************/ -Kernel::SizeT drv_get_sector_count() -{ - return (kATAIdentifyData[61] << 16) | kATAIdentifyData[60]; +Kernel::SizeT drv_get_sector_count() { + return (kATAIdentifyData[61] << 16) | kATAIdentifyData[60]; } /***********************************************************************************/ /// @brief Get the size of the current drive. /***********************************************************************************/ -Kernel::SizeT drv_get_size() -{ - return (drv_get_sector_count()) * kATASectorSize; +Kernel::SizeT drv_get_size() { + return (drv_get_sector_count()) * kATASectorSize; } #endif /* ifdef __ATA_DMA__ */ diff --git a/dev/kernel/HALKit/AMD64/Storage/PIO+Generic.cc b/dev/kernel/HALKit/AMD64/Storage/PIO+Generic.cc index cd25ab7f..6fb1d8a3 100644 --- a/dev/kernel/HALKit/AMD64/Storage/PIO+Generic.cc +++ b/dev/kernel/HALKit/AMD64/Storage/PIO+Generic.cc @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -15,10 +15,10 @@ * */ -#include #include #include #include +#include using namespace Kernel; using namespace Kernel::HAL; @@ -27,264 +27,234 @@ using namespace Kernel::HAL; #define kATADataLen 256 -STATIC Boolean kATADetected = false; +STATIC Boolean kATADetected = false; STATIC UInt16 kATAIdentifyData[kATADataLen] = {0}; -STATIC Char kATADiskModel[50] = {"GENERIC PIO"}; +STATIC Char kATADiskModel[50] = {"GENERIC PIO"}; -static Boolean drv_pio_std_wait_io(UInt16 IO) -{ - for (int i = 0; i < 400; i++) - rt_in8(IO + ATA_REG_STATUS); +static Boolean drv_pio_std_wait_io(UInt16 IO) { + for (int i = 0; i < 400; i++) rt_in8(IO + ATA_REG_STATUS); ATAWaitForIO_Retry: - auto stat_rdy = rt_in8(IO + ATA_REG_STATUS); + auto stat_rdy = rt_in8(IO + ATA_REG_STATUS); - if ((stat_rdy & ATA_SR_BSY)) - goto ATAWaitForIO_Retry; + if ((stat_rdy & ATA_SR_BSY)) goto ATAWaitForIO_Retry; ATAWaitForIO_Retry2: - stat_rdy = rt_in8(IO + ATA_REG_STATUS); + stat_rdy = rt_in8(IO + ATA_REG_STATUS); - if (stat_rdy & ATA_SR_ERR) - return false; + if (stat_rdy & ATA_SR_ERR) return false; - if (!(stat_rdy & ATA_SR_DRDY)) - goto ATAWaitForIO_Retry2; + if (!(stat_rdy & ATA_SR_DRDY)) goto ATAWaitForIO_Retry2; - return true; + return true; } -static Void drv_pio_std_select(UInt16 Bus) -{ - if (Bus == ATA_PRIMARY_IO) - rt_out8(Bus + ATA_REG_HDDEVSEL, ATA_PRIMARY_SEL); - else - rt_out8(Bus + ATA_REG_HDDEVSEL, ATA_SECONDARY_SEL); +static Void drv_pio_std_select(UInt16 Bus) { + if (Bus == ATA_PRIMARY_IO) + rt_out8(Bus + ATA_REG_HDDEVSEL, ATA_PRIMARY_SEL); + else + rt_out8(Bus + ATA_REG_HDDEVSEL, ATA_SECONDARY_SEL); } -Boolean drv_pio_std_init(UInt16 Bus, UInt8 Drive, UInt16& OutBus, UInt8& OutMaster) -{ - UInt16 IO = Bus; +Boolean drv_pio_std_init(UInt16 Bus, UInt8 Drive, UInt16& OutBus, UInt8& OutMaster) { + UInt16 IO = Bus; - NE_UNUSED(Drive); + NE_UNUSED(Drive); - drv_pio_std_select(IO); + drv_pio_std_select(IO); - // Bus init, NEIN bit. - rt_out8(IO + ATA_REG_NEIN, 1); + // Bus init, NEIN bit. + rt_out8(IO + ATA_REG_NEIN, 1); - // identify until it's good. + // identify until it's good. ATAInit_Retry: - auto stat_rdy = rt_in8(IO + ATA_REG_STATUS); + auto stat_rdy = rt_in8(IO + ATA_REG_STATUS); - if (stat_rdy & ATA_SR_ERR) - { - return false; - } + if (stat_rdy & ATA_SR_ERR) { + return false; + } - if ((stat_rdy & ATA_SR_BSY)) - goto ATAInit_Retry; + if ((stat_rdy & ATA_SR_BSY)) goto ATAInit_Retry; - OutBus = (Bus == ATA_PRIMARY_IO) ? ATA_PRIMARY_IO : ATA_SECONDARY_IO; - OutMaster = (Bus == ATA_PRIMARY_IO) ? ATA_MASTER : ATA_SLAVE; + OutBus = (Bus == ATA_PRIMARY_IO) ? ATA_PRIMARY_IO : ATA_SECONDARY_IO; + OutMaster = (Bus == ATA_PRIMARY_IO) ? ATA_MASTER : ATA_SLAVE; - rt_out8(OutBus + ATA_REG_COMMAND, ATA_CMD_IDENTIFY); + rt_out8(OutBus + ATA_REG_COMMAND, ATA_CMD_IDENTIFY); - drv_pio_std_wait_io(IO); + drv_pio_std_wait_io(IO); - /// fetch serial info - /// model, speed, number of sectors... + /// fetch serial info + /// model, speed, number of sectors... - for (SizeT i = 0ul; i < kATADataLen; ++i) - { - kATAIdentifyData[i] = HAL::rt_in16(OutBus + ATA_REG_DATA); - } + for (SizeT i = 0ul; i < kATADataLen; ++i) { + kATAIdentifyData[i] = HAL::rt_in16(OutBus + ATA_REG_DATA); + } - for (Int32 i = 0; i < 20; i++) - { - kATADiskModel[i * 2] = (kATAIdentifyData[27 + i] >> 8) & 0xFF; - kATADiskModel[i * 2 + 1] = kATAIdentifyData[27 + i] & 0xFF; - } + for (Int32 i = 0; i < 20; i++) { + kATADiskModel[i * 2] = (kATAIdentifyData[27 + i] >> 8) & 0xFF; + kATADiskModel[i * 2 + 1] = kATAIdentifyData[27 + i] & 0xFF; + } - kATADiskModel[40] = '\0'; + kATADiskModel[40] = '\0'; - (Void)(kout << "Drive Model: " << kATADiskModel << kendl); + (Void)(kout << "Drive Model: " << kATADiskModel << kendl); - return true; + return true; } -Void drv_pio_std_read(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) -{ - Lba /= SectorSz; +Void drv_pio_std_read(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) { + Lba /= SectorSz; - UInt8 Command = ((!Master) ? 0xE0 : 0xF0); + UInt8 Command = ((!Master) ? 0xE0 : 0xF0); - drv_pio_std_wait_io(IO); - drv_pio_std_select(IO); + drv_pio_std_wait_io(IO); + drv_pio_std_select(IO); - rt_out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); + rt_out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); - rt_out8(IO + ATA_REG_SEC_COUNT0, ((Size + SectorSz) / SectorSz)); + rt_out8(IO + ATA_REG_SEC_COUNT0, ((Size + SectorSz) / SectorSz)); - rt_out8(IO + ATA_REG_LBA0, (Lba)&0xFF); - rt_out8(IO + ATA_REG_LBA1, (Lba) >> 8); - rt_out8(IO + ATA_REG_LBA2, (Lba) >> 16); - rt_out8(IO + ATA_REG_LBA3, (Lba) >> 24); + rt_out8(IO + ATA_REG_LBA0, (Lba) & 0xFF); + rt_out8(IO + ATA_REG_LBA1, (Lba) >> 8); + rt_out8(IO + ATA_REG_LBA2, (Lba) >> 16); + rt_out8(IO + ATA_REG_LBA3, (Lba) >> 24); - rt_out8(IO + ATA_REG_COMMAND, ATA_CMD_READ_PIO); + rt_out8(IO + ATA_REG_COMMAND, ATA_CMD_READ_PIO); - for (SizeT IndexOff = 0; IndexOff < Size; ++IndexOff) - { - drv_pio_std_wait_io(IO); - Buf[IndexOff] = HAL::rt_in16(IO + ATA_REG_DATA); - } + for (SizeT IndexOff = 0; IndexOff < Size; ++IndexOff) { + drv_pio_std_wait_io(IO); + Buf[IndexOff] = HAL::rt_in16(IO + ATA_REG_DATA); + } } -Void drv_pio_std_write(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) -{ - Lba /= SectorSz; +Void drv_pio_std_write(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) { + Lba /= SectorSz; - UInt8 Command = ((!Master) ? 0xE0 : 0xF0); + UInt8 Command = ((!Master) ? 0xE0 : 0xF0); - drv_pio_std_wait_io(IO); - drv_pio_std_select(IO); + drv_pio_std_wait_io(IO); + drv_pio_std_select(IO); - rt_out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); + rt_out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); - rt_out8(IO + ATA_REG_SEC_COUNT0, ((Size + (SectorSz)) / SectorSz)); + rt_out8(IO + ATA_REG_SEC_COUNT0, ((Size + (SectorSz)) / SectorSz)); - rt_out8(IO + ATA_REG_LBA0, (Lba)&0xFF); - rt_out8(IO + ATA_REG_LBA1, (Lba) >> 8); - rt_out8(IO + ATA_REG_LBA2, (Lba) >> 16); - rt_out8(IO + ATA_REG_LBA3, (Lba) >> 24); + rt_out8(IO + ATA_REG_LBA0, (Lba) & 0xFF); + rt_out8(IO + ATA_REG_LBA1, (Lba) >> 8); + rt_out8(IO + ATA_REG_LBA2, (Lba) >> 16); + rt_out8(IO + ATA_REG_LBA3, (Lba) >> 24); - rt_out8(IO + ATA_REG_COMMAND, ATA_CMD_WRITE_PIO); + rt_out8(IO + ATA_REG_COMMAND, ATA_CMD_WRITE_PIO); - for (SizeT IndexOff = 0; IndexOff < Size; ++IndexOff) - { - drv_pio_std_wait_io(IO); - rt_out16(IO + ATA_REG_DATA, Buf[IndexOff]); - } + for (SizeT IndexOff = 0; IndexOff < Size; ++IndexOff) { + drv_pio_std_wait_io(IO); + rt_out16(IO + ATA_REG_DATA, Buf[IndexOff]); + } } /// @brief is ATA detected? -Boolean drv_pio_std_detected(Void) -{ - return kATADetected; +Boolean drv_pio_std_detected(Void) { + return kATADetected; } /*** - @brief Getter, gets the number of sectors inside the drive. + @brief Getter, gets the number of sectors inside the drive. */ -SizeT drv_pio_get_sector_count() -{ - return (kATAIdentifyData[61] << 16) | kATAIdentifyData[60]; +SizeT drv_pio_get_sector_count() { + return (kATAIdentifyData[61] << 16) | kATAIdentifyData[60]; } /// @brief Get the drive size. -SizeT drv_pio_get_size() -{ - return (drv_pio_get_sector_count()) * kATASectorSize; +SizeT drv_pio_get_size() { + return (drv_pio_get_sector_count()) * kATASectorSize; } -namespace Kernel -{ - /// @brief Initialize an PIO device (StorageKit function) - /// @param is_master is the current PIO master? - /// @return [io:master] for PIO device. - BOOL sk_init_pio_device(BOOL is_master, UInt16& io, UInt8& master) - { - return drv_pio_std_init(ATA_SECONDARY_IO, is_master, io, master); - } +namespace Kernel { +/// @brief Initialize an PIO device (StorageKit function) +/// @param is_master is the current PIO master? +/// @return [io:master] for PIO device. +BOOL sk_init_pio_device(BOOL is_master, UInt16& io, UInt8& master) { + return drv_pio_std_init(ATA_SECONDARY_IO, is_master, io, master); +} - /// @brief Implementation details namespace. - namespace Detail - { - /// @brief Read PIO device. - /// @param self device - /// @param mnt mounted disk. - STATIC Void sk_io_read_pio(IDeviceObject* self, MountpointInterface* mnt) - { - ATADeviceInterface* dev = (ATADeviceInterface*)self; +/// @brief Implementation details namespace. +namespace Detail { + /// @brief Read PIO device. + /// @param self device + /// @param mnt mounted disk. + STATIC Void sk_io_read_pio(IDeviceObject* self, MountpointInterface* mnt) { + ATADeviceInterface* dev = (ATADeviceInterface*) self; - err_global_get() = kErrorDisk; + err_global_get() = kErrorDisk; - if (!dev) - return; + if (!dev) return; - auto disk = mnt->GetAddressOf(dev->GetIndex()); + auto disk = mnt->GetAddressOf(dev->GetIndex()); - if (!disk) - return; + if (!disk) return; - err_global_get() = kErrorSuccess; + err_global_get() = kErrorSuccess; - drv_pio_std_read(disk->fPacket.fPacketLba, dev->GetIO(), dev->GetMaster(), (Char*)disk->fPacket.fPacketContent, kATASectorSize, disk->fPacket.fPacketSize); - } + drv_pio_std_read(disk->fPacket.fPacketLba, dev->GetIO(), dev->GetMaster(), + (Char*) disk->fPacket.fPacketContent, kATASectorSize, + disk->fPacket.fPacketSize); + } - /// @brief Write PIO device. - /// @param self device - /// @param mnt mounted disk. - STATIC Void sk_io_write_pio(IDeviceObject* self, MountpointInterface* mnt) - { - ATADeviceInterface* dev = (ATADeviceInterface*)self; + /// @brief Write PIO device. + /// @param self device + /// @param mnt mounted disk. + STATIC Void sk_io_write_pio(IDeviceObject* self, MountpointInterface* mnt) { + ATADeviceInterface* dev = (ATADeviceInterface*) self; - err_global_get() = kErrorDisk; + err_global_get() = kErrorDisk; - if (!dev) - return; + if (!dev) return; - auto disk = mnt->GetAddressOf(dev->GetIndex()); + auto disk = mnt->GetAddressOf(dev->GetIndex()); - if (!disk) - return; + if (!disk) return; - err_global_get() = kErrorSuccess; + err_global_get() = kErrorSuccess; - drv_pio_std_write(disk->fPacket.fPacketLba, dev->GetIO(), dev->GetMaster(), (Char*)disk->fPacket.fPacketContent, kATASectorSize, disk->fPacket.fPacketSize); - } - } // namespace Detail + drv_pio_std_write(disk->fPacket.fPacketLba, dev->GetIO(), dev->GetMaster(), + (Char*) disk->fPacket.fPacketContent, kATASectorSize, + disk->fPacket.fPacketSize); + } +} // namespace Detail - /// @brief Acquires a new PIO device with drv_index in mind. - /// @param drv_index The drive index to assign. - /// @return A wrapped device interface if successful, or error code. - ErrorOr sk_acquire_pio_device(Int32 drv_index) - { - /// here we don't check if we probed ATA, since we'd need to grab IO after that. - ATADeviceInterface device(Detail::sk_io_read_pio, - Detail::sk_io_write_pio); +/// @brief Acquires a new PIO device with drv_index in mind. +/// @param drv_index The drive index to assign. +/// @return A wrapped device interface if successful, or error code. +ErrorOr sk_acquire_pio_device(Int32 drv_index) { + /// here we don't check if we probed ATA, since we'd need to grab IO after that. + ATADeviceInterface device(Detail::sk_io_read_pio, Detail::sk_io_write_pio); - device.SetIndex(drv_index); + device.SetIndex(drv_index); - return ErrorOr(device); - } -} // namespace Kernel + return ErrorOr(device); +} +} // namespace Kernel #ifdef __ATA_PIO__ -Void drv_std_read(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) -{ - drv_pio_std_read(Lba, IO, Master, Buf, SectorSz, Size); +Void drv_std_read(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) { + drv_pio_std_read(Lba, IO, Master, Buf, SectorSz, Size); } -Void drv_std_write(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) -{ - drv_pio_std_write(Lba, IO, Master, Buf, SectorSz, Size); +Void drv_std_write(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) { + drv_pio_std_write(Lba, IO, Master, Buf, SectorSz, Size); } -SizeT drv_get_size() -{ - return drv_pio_get_size(); +SizeT drv_get_size() { + return drv_pio_get_size(); } -SizeT drv_get_sector_count() -{ - return drv_pio_get_sector_count(); +SizeT drv_get_sector_count() { + return drv_pio_get_sector_count(); } -Boolean drv_std_init(UInt16 Bus, UInt8 Drive, UInt16& OutBus, UInt8& OutMaster) -{ - return drv_pio_std_init(Bus, Drive, OutBus, OutMaster); +Boolean drv_std_init(UInt16 Bus, UInt8 Drive, UInt16& OutBus, UInt8& OutMaster) { + return drv_pio_std_init(Bus, Drive, OutBus, OutMaster); } #endif \ No newline at end of file diff --git a/dev/kernel/HALKit/AMD64/Storage/SCSI+Generic.cc b/dev/kernel/HALKit/AMD64/Storage/SCSI+Generic.cc index cb387e73..1cc97cba 100644 --- a/dev/kernel/HALKit/AMD64/Storage/SCSI+Generic.cc +++ b/dev/kernel/HALKit/AMD64/Storage/SCSI+Generic.cc @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -9,5 +9,5 @@ using namespace Kernel; ///! @brief ATAPI SCSI packet. -const ATTRIBUTE(unused) scsi_packet_type_12 kCDRomPacketTemplate = {0x43, 0, 1, 0, 0, 0, - 0, 12, 0x40, 0, 0}; +const ATTRIBUTE(unused) scsi_packet_type_12 kCDRomPacketTemplate = {0x43, 0, 1, 0, 0, 0, + 0, 12, 0x40, 0, 0}; diff --git a/dev/kernel/HALKit/ARM64/APM/APM+IO.cc b/dev/kernel/HALKit/ARM64/APM/APM+IO.cc index fc53e4e0..3df8a407 100644 --- a/dev/kernel/HALKit/ARM64/APM/APM+IO.cc +++ b/dev/kernel/HALKit/ARM64/APM/APM+IO.cc @@ -1,11 +1,11 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ -#include #include +#include using namespace Kernel; @@ -13,25 +13,23 @@ using namespace Kernel; /// @param base_dma the IO base port. /// @param cmd the command. /// @return status code. -EXTERN_C Int32 apm_send_io_command(UInt16 cmd, APMPowerCmd value) -{ - switch (cmd) - { - case kAPMPowerCommandReboot: { - asm volatile( - "ldr x0, =0x84000004\n" - "svc #0\n"); +EXTERN_C Int32 apm_send_io_command(UInt16 cmd, APMPowerCmd value) { + switch (cmd) { + case kAPMPowerCommandReboot: { + asm volatile( + "ldr x0, =0x84000004\n" + "svc #0\n"); - return kErrorSuccess; - } - case kAPMPowerCommandShutdown: { - asm volatile( - "ldr x0, =0x84000008\n" - "svc #0\n"); + return kErrorSuccess; + } + case kAPMPowerCommandShutdown: { + asm volatile( + "ldr x0, =0x84000008\n" + "svc #0\n"); - return kErrorSuccess; - } - default: - return kErrorInvalidData; - } + return kErrorSuccess; + } + default: + return kErrorInvalidData; + } } diff --git a/dev/kernel/HALKit/ARM64/ApplicationProcessor.h b/dev/kernel/HALKit/ARM64/ApplicationProcessor.h index 6068d503..f48c1483 100644 --- a/dev/kernel/HALKit/ARM64/ApplicationProcessor.h +++ b/dev/kernel/HALKit/ARM64/ApplicationProcessor.h @@ -1,19 +1,18 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #pragma once -#include #include +#include /************************************************** */ /* INITIALIZE THE GIC ON CPU. */ /************************************************** */ -namespace Kernel -{ - BOOL mp_initialize_gic(Kernel::Void); +namespace Kernel { +BOOL mp_initialize_gic(Kernel::Void); } \ No newline at end of file diff --git a/dev/kernel/HALKit/ARM64/HalACPIFactoryInterface.cc b/dev/kernel/HALKit/ARM64/HalACPIFactoryInterface.cc index 27ea0977..31f5a4f2 100644 --- a/dev/kernel/HALKit/ARM64/HalACPIFactoryInterface.cc +++ b/dev/kernel/HALKit/ARM64/HalACPIFactoryInterface.cc @@ -1,32 +1,26 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ -#include -#include #include #include +#include +#include #include -namespace Kernel -{ - ACPIFactoryInterface::ACPIFactoryInterface(VoidPtr rsp_ptr) - : fRsdp(rsp_ptr), fEntries(0) - { - } +namespace Kernel { +ACPIFactoryInterface::ACPIFactoryInterface(VoidPtr rsp_ptr) : fRsdp(rsp_ptr), fEntries(0) {} - BOOL ACPIFactoryInterface::Shutdown() - { - apm_send_io_command(kAPMPowerCommandShutdown, 0); - return NO; - } +BOOL ACPIFactoryInterface::Shutdown() { + apm_send_io_command(kAPMPowerCommandShutdown, 0); + return NO; +} - /// @brief Reboot machine in either ACPI or by triple faulting. - /// @return nothing it's a reboot. - Void ACPIFactoryInterface::Reboot() - { - apm_send_io_command(kAPMPowerCommandReboot, 0); - } -} // namespace Kernel +/// @brief Reboot machine in either ACPI or by triple faulting. +/// @return nothing it's a reboot. +Void ACPIFactoryInterface::Reboot() { + apm_send_io_command(kAPMPowerCommandReboot, 0); +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/ARM64/HalApplicationProcessor.cc b/dev/kernel/HALKit/ARM64/HalApplicationProcessor.cc index 7d985a44..14af1a16 100644 --- a/dev/kernel/HALKit/ARM64/HalApplicationProcessor.cc +++ b/dev/kernel/HALKit/ARM64/HalApplicationProcessor.cc @@ -1,145 +1,132 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ +#include #include #include -#include #include -#define GICD_BASE 0x08000000 // Distributor base address -#define GICC_BASE 0x08010000 // CPU interface base address +#define GICD_BASE 0x08000000 // Distributor base address +#define GICC_BASE 0x08010000 // CPU interface base address -#define GICD_CTLR 0x000 // Distributor Control Register -#define GICD_ISENABLER 0x100 // Interrupt Set-Enable Registers -#define GICD_ICENABLER 0x180 // Interrupt Clear-Enable Registers -#define GICD_ISPENDR 0x200 // Interrupt Set-Pending Registers -#define GICD_ICPENDR 0x280 // Interrupt Clear-Pending Registers -#define GICD_IPRIORITYR 0x400 // Interrupt Priority Registers -#define GICD_ITARGETSR 0x800 // Interrupt Processor Targets Registers -#define GICD_ICFGR 0xC00 // Interrupt Configuration Registers +#define GICD_CTLR 0x000 // Distributor Control Register +#define GICD_ISENABLER 0x100 // Interrupt Set-Enable Registers +#define GICD_ICENABLER 0x180 // Interrupt Clear-Enable Registers +#define GICD_ISPENDR 0x200 // Interrupt Set-Pending Registers +#define GICD_ICPENDR 0x280 // Interrupt Clear-Pending Registers +#define GICD_IPRIORITYR 0x400 // Interrupt Priority Registers +#define GICD_ITARGETSR 0x800 // Interrupt Processor Targets Registers +#define GICD_ICFGR 0xC00 // Interrupt Configuration Registers -#define GICC_CTLR 0x000 // CPU Interface Control Register -#define GICC_PMR 0x004 // Interrupt Priority Mask Register -#define GICC_IAR 0x00C // Interrupt Acknowledge Register -#define GICC_EOIR 0x010 // End of Interrupt Register +#define GICC_CTLR 0x000 // CPU Interface Control Register +#define GICC_PMR 0x004 // Interrupt Priority Mask Register +#define GICC_IAR 0x00C // Interrupt Acknowledge Register +#define GICC_EOIR 0x010 // End of Interrupt Register // ================================================================= // -namespace Kernel -{ - struct PROCESS_CONTROL_BLOCK final - { - HAL::StackFramePtr mFrame; - }; +namespace Kernel { +struct PROCESS_CONTROL_BLOCK final { + HAL::StackFramePtr mFrame; +}; - STATIC PROCESS_CONTROL_BLOCK kProcessBlocks[kSchedProcessLimitPerTeam] = {0}; +STATIC PROCESS_CONTROL_BLOCK kProcessBlocks[kSchedProcessLimitPerTeam] = {0}; - namespace Detail - { - STATIC BOOL kGICEnabled = NO; +namespace Detail { + STATIC BOOL kGICEnabled = NO; - STATIC void mp_hang_fn(void) - { - while (YES) - ; + STATIC void mp_hang_fn(void) { + while (YES); - dbg_break_point(); - } + dbg_break_point(); + } - Void mp_setup_gic_el0(Void) - { - // enable distributor. - ke_dma_write(GICD_BASE, GICD_CTLR, YES); + Void mp_setup_gic_el0(Void) { + // enable distributor. + ke_dma_write(GICD_BASE, GICD_CTLR, YES); - UInt32 gicc_ctlr = ke_dma_read(GICC_BASE, GICC_CTLR); + UInt32 gicc_ctlr = ke_dma_read(GICC_BASE, GICC_CTLR); - const auto kEnableSignalInt = YES; + const auto kEnableSignalInt = YES; - gicc_ctlr |= kEnableSignalInt; // Enable signaling of interrupts - gicc_ctlr |= (kEnableSignalInt << 1); // Allow Group 1 interrupts in EL0 + gicc_ctlr |= kEnableSignalInt; // Enable signaling of interrupts + gicc_ctlr |= (kEnableSignalInt << 1); // Allow Group 1 interrupts in EL0 - ke_dma_write(GICC_BASE, GICC_CTLR, gicc_ctlr); + ke_dma_write(GICC_BASE, GICC_CTLR, gicc_ctlr); - // Set priority mask (accept all priorities) - ke_dma_write(GICC_BASE, GICC_PMR, 0xFF); + // Set priority mask (accept all priorities) + ke_dma_write(GICC_BASE, GICC_PMR, 0xFF); - UInt32 icfgr = ke_dma_read(GICD_BASE, GICD_ICFGR + (0x20 / 0x10) * 4); + UInt32 icfgr = ke_dma_read(GICD_BASE, GICD_ICFGR + (0x20 / 0x10) * 4); - icfgr |= (0x2 << ((32 % 16) * 2)); // Edge-triggered - ke_dma_write(GICD_BASE, GICD_ICFGR + (0x20 / 0x10) * 4, icfgr); + icfgr |= (0x2 << ((32 % 16) * 2)); // Edge-triggered + ke_dma_write(GICD_BASE, GICD_ICFGR + (0x20 / 0x10) * 4, icfgr); - // Target interrupt 32 to CPU 1 - ke_dma_write(GICD_BASE, GICD_ITARGETSR + (0x20 / 0x04) * 4, 0x2 << ((32 % 4) * 8)); + // Target interrupt 32 to CPU 1 + ke_dma_write(GICD_BASE, GICD_ITARGETSR + (0x20 / 0x04) * 4, 0x2 << ((32 % 4) * 8)); - // Set interrupt 32 priority to lowest (0xFF) - ke_dma_write(GICD_BASE, GICD_IPRIORITYR + (0x20 / 0x04) * 4, 0xFF << ((32 % 4) * 8)); + // Set interrupt 32 priority to lowest (0xFF) + ke_dma_write(GICD_BASE, GICD_IPRIORITYR + (0x20 / 0x04) * 4, 0xFF << ((32 % 4) * 8)); - // Enable interrupt 32 for AP. - ke_dma_write(GICD_BASE, GICD_ISENABLER + 4, 0x01); - } + // Enable interrupt 32 for AP. + ke_dma_write(GICD_BASE, GICD_ISENABLER + 4, 0x01); + } - BOOL mp_handle_gic_interrupt_el0(Void) - { - // Read the interrupt ID - UInt32 interrupt_id = ke_dma_read(GICC_BASE, GICC_IAR); + BOOL mp_handle_gic_interrupt_el0(Void) { + // Read the interrupt ID + UInt32 interrupt_id = ke_dma_read(GICC_BASE, GICC_IAR); - // Check if it's a valid interrupt (not spurious) - if ((interrupt_id & 0x3FF) < 1020) - { - auto interrupt = interrupt_id & 0x3FF; + // Check if it's a valid interrupt (not spurious) + if ((interrupt_id & 0x3FF) < 1020) { + auto interrupt = interrupt_id & 0x3FF; - const UInt16 kInterruptScheduler = 0x20; + const UInt16 kInterruptScheduler = 0x20; - (Void)(kout << "Handling interrupt for AP: " << interrupt << kendl); + (Void)(kout << "Handling interrupt for AP: " << interrupt << kendl); - switch (interrupt) - { - case kInterruptScheduler: { - ke_dma_write(GICC_BASE, GICC_EOIR, interrupt_id); - UserProcessHelper::StartScheduling(); - break; - } - default: { - ke_dma_write(GICC_BASE, GICC_EOIR, interrupt_id); - break; - } - } + switch (interrupt) { + case kInterruptScheduler: { + ke_dma_write(GICC_BASE, GICC_EOIR, interrupt_id); + UserProcessHelper::StartScheduling(); + break; + } + default: { + ke_dma_write(GICC_BASE, GICC_EOIR, interrupt_id); + break; + } + } - return YES; - } + return YES; + } - // spurious interrupt - return NO; - } - } // namespace Detail + // spurious interrupt + return NO; + } +} // namespace Detail - EXTERN_C HAL::StackFramePtr mp_get_current_context(ProcessID pid) - { - return kProcessBlocks[pid % kSchedProcessLimitPerTeam].mFrame; - } +EXTERN_C HAL::StackFramePtr mp_get_current_context(ProcessID pid) { + return kProcessBlocks[pid % kSchedProcessLimitPerTeam].mFrame; +} - EXTERN_C Bool mp_register_process(HAL::StackFramePtr stack_frame, ProcessID pid) - { - MUST_PASS(stack_frame); +EXTERN_C Bool mp_register_process(HAL::StackFramePtr stack_frame, ProcessID pid) { + MUST_PASS(stack_frame); - const auto process_index = pid % kSchedProcessLimitPerTeam; + const auto process_index = pid % kSchedProcessLimitPerTeam; - kProcessBlocks[process_index].mFrame = stack_frame; + kProcessBlocks[process_index].mFrame = stack_frame; - return YES; - } + return YES; +} - BOOL mp_initialize_gic(Void) - { - if (!Detail::kGICEnabled) - { - Detail::kGICEnabled = YES; - Detail::mp_setup_gic_el0(); - } +BOOL mp_initialize_gic(Void) { + if (!Detail::kGICEnabled) { + Detail::kGICEnabled = YES; + Detail::mp_setup_gic_el0(); + } - return Detail::kGICEnabled; - } -} // namespace Kernel \ No newline at end of file + return Detail::kGICEnabled; +} +} // namespace Kernel \ No newline at end of file diff --git a/dev/kernel/HALKit/ARM64/HalDebugOutput.cc b/dev/kernel/HALKit/ARM64/HalDebugOutput.cc index 7f9c73be..7ec90c6e 100644 --- a/dev/kernel/HALKit/ARM64/HalDebugOutput.cc +++ b/dev/kernel/HALKit/ARM64/HalDebugOutput.cc @@ -1,83 +1,71 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #include #include -#include #include +#include -namespace Kernel -{ - EXTERN_C void ke_io_write(IDeviceObject* self, const Char* bytes) - { +namespace Kernel { +EXTERN_C void ke_io_write(IDeviceObject* self, const Char* bytes) { #ifdef __DEBUG__ - if (*bytes == 0) - return; + if (*bytes == 0) return; - SizeT index = 0; - SizeT len = 0; + SizeT index = 0; + SizeT len = 0; - index = 0; - len = rt_string_len(bytes, 256U); + index = 0; + len = rt_string_len(bytes, 256U); - volatile UInt8* uart_ptr = (UInt8*)0x09000000; + volatile UInt8* uart_ptr = (UInt8*) 0x09000000; - while (index < len) - { - if (bytes[index] == '\r') - *uart_ptr = '\r'; + while (index < len) { + if (bytes[index] == '\r') *uart_ptr = '\r'; - *uart_ptr = bytes[index] == '\r' ? '\n' : bytes[index]; - ++index; - } -#endif // __DEBUG__ - } + *uart_ptr = bytes[index] == '\r' ? '\n' : bytes[index]; + ++index; + } +#endif // __DEBUG__ +} - TerminalDevice::~TerminalDevice() = default; +TerminalDevice::~TerminalDevice() = default; - EXTERN_C void ke_io_read(IDeviceObject* self, const Char* bytes) - { +EXTERN_C void ke_io_read(IDeviceObject* self, const Char* bytes) { #ifdef __DEBUG__ - SizeT index = 0; - - volatile UInt8* uart_ptr = (UInt8*)0x09000000; - - ///! TODO: Look on how to wait for the UART to complete. - while (Yes) - { - auto in = *uart_ptr; - - ///! If enter pressed then break. - if (in == 0xD) - { - break; - } - - if (in < '0' || in < 'A' || in < 'a') - { - if (in != '@' || in != '!' || in != '?' || in != '.' || in != '/' || - in != ':') - { - continue; - } - } - - ((char*)bytes)[index] = in; - - ++index; - } - - ((char*)bytes)[index] = 0; -#endif // __DEBUG__ - } - - TerminalDevice TerminalDevice::The() noexcept - { - TerminalDevice out(Kernel::ke_io_write, Kernel::ke_io_read); - return out; - } - -} // namespace Kernel + SizeT index = 0; + + volatile UInt8* uart_ptr = (UInt8*) 0x09000000; + + ///! TODO: Look on how to wait for the UART to complete. + while (Yes) { + auto in = *uart_ptr; + + ///! If enter pressed then break. + if (in == 0xD) { + break; + } + + if (in < '0' || in < 'A' || in < 'a') { + if (in != '@' || in != '!' || in != '?' || in != '.' || in != '/' || in != ':') { + continue; + } + } + + ((char*) bytes)[index] = in; + + ++index; + } + + ((char*) bytes)[index] = 0; +#endif // __DEBUG__ +} + +TerminalDevice TerminalDevice::The() noexcept { + TerminalDevice out(Kernel::ke_io_write, Kernel::ke_io_read); + return out; +} + +} // namespace Kernel diff --git a/dev/kernel/HALKit/ARM64/HalKernelMain.cc b/dev/kernel/HALKit/ARM64/HalKernelMain.cc index 3498d477..3e6701ea 100644 --- a/dev/kernel/HALKit/ARM64/HalKernelMain.cc +++ b/dev/kernel/HALKit/ARM64/HalKernelMain.cc @@ -1,77 +1,71 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #include -#include +#include #include +#include +#include #include #include #include #include +#include #include -#include #include -#include -#include -#include +#include #include -EXTERN_C void hal_init_platform( - Kernel::HEL::BootInfoHeader* handover_hdr) -{ - - /************************************************** */ - /* INITIALIZE AND VALIDATE HEADER. */ - /************************************************** */ +EXTERN_C void hal_init_platform(Kernel::HEL::BootInfoHeader* handover_hdr) { + /************************************************** */ + /* INITIALIZE AND VALIDATE HEADER. */ + /************************************************** */ - kHandoverHeader = handover_hdr; + kHandoverHeader = handover_hdr; - if (kHandoverHeader->f_Magic != kHandoverMagic && - kHandoverHeader->f_Version != kHandoverVersion) - { - return; - } + if (kHandoverHeader->f_Magic != kHandoverMagic && + kHandoverHeader->f_Version != kHandoverVersion) { + return; + } - /************************************** */ - /* INITIALIZE BIT MAP. */ - /************************************** */ + /************************************** */ + /* INITIALIZE BIT MAP. */ + /************************************** */ - kKernelBitMpSize = kHandoverHeader->f_BitMapSize; - kKernelBitMpStart = reinterpret_cast( - reinterpret_cast(kHandoverHeader->f_BitMapStart)); + kKernelBitMpSize = kHandoverHeader->f_BitMapSize; + kKernelBitMpStart = reinterpret_cast( + reinterpret_cast(kHandoverHeader->f_BitMapStart)); - /// @note do initialize the interrupts after it. + /// @note do initialize the interrupts after it. - Kernel::mp_initialize_gic(); + Kernel::mp_initialize_gic(); - /// after the scheduler runs, we must look over teams, every 5000s in order to schedule every process according to their affinity fairly. + /// after the scheduler runs, we must look over teams, every 5000s in order to schedule every + /// process according to their affinity fairly. - auto constexpr kSchedTeamSwitchMS = 5U; /// @brief Team switch time in milliseconds. + auto constexpr kSchedTeamSwitchMS = 5U; /// @brief Team switch time in milliseconds. - Kernel::HardwareTimer timer(rtl_milliseconds(kSchedTeamSwitchMS)); + Kernel::HardwareTimer timer(rtl_milliseconds(kSchedTeamSwitchMS)); - STATIC Kernel::Array kTeams; + STATIC Kernel::Array kTeams; - SizeT team_index = 0U; + SizeT team_index = 0U; - /// @brief This just loops over the teams and switches between them. - /// @details Not even round-robin, just a simple loop in this boot core we're at. - while (YES) - { - if (team_index > (kSchedTeamCount - 1)) - { - team_index = 0U; - } + /// @brief This just loops over the teams and switches between them. + /// @details Not even round-robin, just a simple loop in this boot core we're at. + while (YES) { + if (team_index > (kSchedTeamCount - 1)) { + team_index = 0U; + } - while (!UserProcessScheduler::The().SwitchTeam(kTeams[team_index])) - ; + while (!UserProcessScheduler::The().SwitchTeam(kTeams[team_index])); - timer.Wait(); + timer.Wait(); - ++team_index; - } + ++team_index; + } } diff --git a/dev/kernel/HALKit/ARM64/HalKernelPanic.cc b/dev/kernel/HALKit/ARM64/HalKernelPanic.cc index ad966991..5680041c 100644 --- a/dev/kernel/HALKit/ARM64/HalKernelPanic.cc +++ b/dev/kernel/HALKit/ARM64/HalKernelPanic.cc @@ -1,80 +1,74 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ -#include #include -#include -#include -#include #include +#include #include +#include +#include +#include +#include #include #include -#include /* Each error code is attributed with an ID, which will prompt a string onto the * screen. Wait for debugger... */ -namespace Kernel -{ - /// @brief Dumping factory class. - class RecoveryFactory final - { - public: - STATIC Void Recover() noexcept; - }; +namespace Kernel { +/// @brief Dumping factory class. +class RecoveryFactory final { + public: + STATIC Void Recover() noexcept; +}; - /***********************************************************************************/ - /// @brief Stops execution of the kernel. - /// @param id kernel stop ID. - /***********************************************************************************/ - Void ke_panic(const Kernel::Int32& id, const Char* message) - { - fb_init(); +/***********************************************************************************/ +/// @brief Stops execution of the kernel. +/// @param id kernel stop ID. +/***********************************************************************************/ +Void ke_panic(const Kernel::Int32& id, const Char* message) { + fb_init(); - auto panic_text = RGB(0xff, 0xff, 0xff); + auto panic_text = RGB(0xff, 0xff, 0xff); - auto y = 10; - auto x = 10; + auto y = 10; + auto x = 10; - Char* message_apicid = new Char[128]; - rt_set_memory(message_apicid, 0, 128); + Char* message_apicid = new Char[128]; + rt_set_memory(message_apicid, 0, 128); - rt_copy_memory((VoidPtr) "panic id: ", message_apicid, rt_string_len("panic id: ")); - rt_to_string(message_apicid + rt_string_len("panic id: "), (UIntPtr)id, 10); + rt_copy_memory((VoidPtr) "panic id: ", message_apicid, rt_string_len("panic id: ")); + rt_to_string(message_apicid + rt_string_len("panic id: "), (UIntPtr) id, 10); - fb_render_string(message_apicid, y, x, panic_text); + fb_render_string(message_apicid, y, x, panic_text); - y += 10; + y += 10; - fb_render_string((message ? message : "message: panic raised, going nowhere after this!"), y, x, panic_text); + fb_render_string((message ? message : "message: panic raised, going nowhere after this!"), y, x, + panic_text); - y += 10; + y += 10; - fb_clear(); + fb_clear(); - RecoveryFactory::Recover(); - } + RecoveryFactory::Recover(); +} - Void RecoveryFactory::Recover() noexcept - { - while (YES) - { - HAL::rt_halt(); - } - } +Void RecoveryFactory::Recover() noexcept { + while (YES) { + HAL::rt_halt(); + } +} - void ke_runtime_check(bool expr, const Char* file, const Char* line) - { - if (!expr) - { - (Void)(kout << "FAILED: FILE: " << file << kendl); - (Void)(kout << "FAILED: LINE: " << line << kendl); +void ke_runtime_check(bool expr, const Char* file, const Char* line) { + if (!expr) { + (Void)(kout << "FAILED: FILE: " << file << kendl); + (Void)(kout << "FAILED: LINE: " << line << kendl); - ke_panic(RUNTIME_CHECK_FAILED, file); // Runtime Check failed - } - } -} // namespace Kernel + ke_panic(RUNTIME_CHECK_FAILED, file); // Runtime Check failed + } +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/ARM64/HalPagingMgrARM64.cc b/dev/kernel/HALKit/ARM64/HalPagingMgrARM64.cc index 08dd6180..e8c6875d 100644 --- a/dev/kernel/HALKit/ARM64/HalPagingMgrARM64.cc +++ b/dev/kernel/HALKit/ARM64/HalPagingMgrARM64.cc @@ -1,86 +1,75 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: HalPagingMgr.cc - Purpose: Platform Paging Manager. + File: HalPagingMgr.cc + Purpose: Platform Paging Manager. ------------------------------------------- */ #include #include -namespace Kernel::HAL -{ - typedef UInt32 PageTableIndex; - - /// \brief Page store type. - struct NE_PAGE_STORE final - { - struct - { - PDE* fPde{nullptr}; - PTE* fPte{nullptr}; - VoidPtr fVAddr{nullptr}; - } fInternalStore; - - Bool fStoreOp{No}; // Store operation in progress. - - static NE_PAGE_STORE& The() - { - static NE_PAGE_STORE the; - return the; - } - }; - - /// \brief Retrieve the page status of a PTE. - STATIC Void mmi_page_status(PTE* pte) - { - } - - STATIC Int32 mmi_map_page_table_entry(VoidPtr virtual_address, UInt32 flags, PTE* pt_entry); - - /// @brief Maps or allocates a page from virtual_address. - /// @param virtual_address a valid virtual address. - /// @param phys_addr point to physical address. - /// @param flags the flags to put on the page. - /// @return Status code of page manipulation process. - EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags) - { - if (!virtual_address || - !flags) - return 0; - - NE_PAGE_STORE& page_store = NE_PAGE_STORE::The(); - - while (page_store.fStoreOp) - ; - - page_store.fStoreOp = Yes; - - if (page_store.fInternalStore.fVAddr == virtual_address) - { - page_store.fStoreOp = No; - return mmi_map_page_table_entry(page_store.fInternalStore.fVAddr, flags, page_store.fInternalStore.fPte); - } - - return 1; - } - - /// @brief Maps flags for a specific pte. - /// @internal Internal function. - STATIC Int32 mmi_map_page_table_entry(VoidPtr virtual_address, UInt32 flags, PTE* pt_entry) - { - NE_PAGE_STORE& page_store = NE_PAGE_STORE::The(); - - // Update internal store. - - page_store.fInternalStore.fPde = nullptr; - page_store.fInternalStore.fPte = pt_entry; - page_store.fInternalStore.fVAddr = virtual_address; - - page_store.fStoreOp = No; - - return 0; - } -} // namespace Kernel::HAL +namespace Kernel::HAL { +typedef UInt32 PageTableIndex; + +/// \brief Page store type. +struct NE_PAGE_STORE final { + struct { + PDE* fPde{nullptr}; + PTE* fPte{nullptr}; + VoidPtr fVAddr{nullptr}; + } fInternalStore; + + Bool fStoreOp{No}; // Store operation in progress. + + static NE_PAGE_STORE& The() { + static NE_PAGE_STORE the; + return the; + } +}; + +/// \brief Retrieve the page status of a PTE. +STATIC Void mmi_page_status(PTE* pte) {} + +STATIC Int32 mmi_map_page_table_entry(VoidPtr virtual_address, UInt32 flags, PTE* pt_entry); + +/// @brief Maps or allocates a page from virtual_address. +/// @param virtual_address a valid virtual address. +/// @param phys_addr point to physical address. +/// @param flags the flags to put on the page. +/// @return Status code of page manipulation process. +EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags) { + if (!virtual_address || !flags) return 0; + + NE_PAGE_STORE& page_store = NE_PAGE_STORE::The(); + + while (page_store.fStoreOp); + + page_store.fStoreOp = Yes; + + if (page_store.fInternalStore.fVAddr == virtual_address) { + page_store.fStoreOp = No; + return mmi_map_page_table_entry(page_store.fInternalStore.fVAddr, flags, + page_store.fInternalStore.fPte); + } + + return 1; +} + +/// @brief Maps flags for a specific pte. +/// @internal Internal function. +STATIC Int32 mmi_map_page_table_entry(VoidPtr virtual_address, UInt32 flags, PTE* pt_entry) { + NE_PAGE_STORE& page_store = NE_PAGE_STORE::The(); + + // Update internal store. + + page_store.fInternalStore.fPde = nullptr; + page_store.fInternalStore.fPte = pt_entry; + page_store.fInternalStore.fVAddr = virtual_address; + + page_store.fStoreOp = No; + + return 0; +} +} // namespace Kernel::HAL diff --git a/dev/kernel/HALKit/ARM64/HalSchedulerCoreARM64.cc b/dev/kernel/HALKit/ARM64/HalSchedulerCoreARM64.cc index 538124a6..b3f1b62a 100644 --- a/dev/kernel/HALKit/ARM64/HalSchedulerCoreARM64.cc +++ b/dev/kernel/HALKit/ARM64/HalSchedulerCoreARM64.cc @@ -1,24 +1,21 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #include -namespace Kernel -{ - /// @brief Wakes up thread. - /// Wakes up thread from the hang state. - Void mp_wakeup_thread(HAL::StackFrame* stack) - { - NE_UNUSED(stack); - } +namespace Kernel { +/// @brief Wakes up thread. +/// Wakes up thread from the hang state. +Void mp_wakeup_thread(HAL::StackFrame* stack) { + NE_UNUSED(stack); +} - /// @brief makes the thread sleep on a loop. - /// hooks and hangs thread to prevent code from executing. - Void mp_hang_thread(HAL::StackFrame* stack) - { - NE_UNUSED(stack); - } -} // namespace Kernel +/// @brief makes the thread sleep on a loop. +/// hooks and hangs thread to prevent code from executing. +Void mp_hang_thread(HAL::StackFrame* stack) { + NE_UNUSED(stack); +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/ARM64/HalSchedulerCorePrimitivesARM64.cc b/dev/kernel/HALKit/ARM64/HalSchedulerCorePrimitivesARM64.cc index 84aae986..a8f0b1e1 100644 --- a/dev/kernel/HALKit/ARM64/HalSchedulerCorePrimitivesARM64.cc +++ b/dev/kernel/HALKit/ARM64/HalSchedulerCorePrimitivesARM64.cc @@ -1,35 +1,30 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #include #include -namespace Kernel -{ - /***********************************************************************************/ - /// @brief Unimplemented function (crashes by default) - /// @param void - /***********************************************************************************/ - - EXTERN_C Void __zka_pure_call(USER_PROCESS* process) - { - if (process) - process->Crash(); - } - - /***********************************************************************************/ - /// @brief Validate user stack. - /// @param stack_ptr the frame pointer. - /***********************************************************************************/ - - EXTERN_C Bool hal_check_stack(HAL::StackFramePtr stack_ptr) - { - if (!stack_ptr) - return No; - - return stack_ptr->SP != 0 && stack_ptr->BP != 0; - } -} // namespace Kernel +namespace Kernel { +/***********************************************************************************/ +/// @brief Unimplemented function (crashes by default) +/// @param void +/***********************************************************************************/ + +EXTERN_C Void __zka_pure_call(USER_PROCESS* process) { + if (process) process->Crash(); +} + +/***********************************************************************************/ +/// @brief Validate user stack. +/// @param stack_ptr the frame pointer. +/***********************************************************************************/ + +EXTERN_C Bool hal_check_stack(HAL::StackFramePtr stack_ptr) { + if (!stack_ptr) return No; + + return stack_ptr->SP != 0 && stack_ptr->BP != 0; +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/ARM64/HalTimerARM64.cc b/dev/kernel/HALKit/ARM64/HalTimerARM64.cc index c9fb1617..32f64aec 100644 --- a/dev/kernel/HALKit/ARM64/HalTimerARM64.cc +++ b/dev/kernel/HALKit/ARM64/HalTimerARM64.cc @@ -1,13 +1,13 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: HalTimer.cc - Purpose: HAL timer + File: HalTimer.cc + Purpose: HAL timer - Revision History: + Revision History: - 07/07/24: Added file (amlel) + 07/07/24: Added file (amlel) ------------------------------------------- */ diff --git a/dev/kernel/HALKit/ARM64/Paging.h b/dev/kernel/HALKit/ARM64/Paging.h index 26c277db..e23c0538 100644 --- a/dev/kernel/HALKit/ARM64/Paging.h +++ b/dev/kernel/HALKit/ARM64/Paging.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -8,7 +8,7 @@ /** --------------------------------------------------- - * THIS FILE CONTAINS CODE FOR ARMV8 PAGING. + * THIS FILE CONTAINS CODE FOR ARMV8 PAGING. ------------------------------------------------------- */ @@ -16,105 +16,90 @@ #ifndef kPageMax #define kPageMax (0x200) -#endif //! kPageMax +#endif //! kPageMax #ifndef kPageAlign #define kPageAlign (0x1000) -#endif //! kPageAlign +#endif //! kPageAlign #ifndef kPageSize #define kPageSize (0x1000) -#endif // !kPageSize +#endif // !kPageSize //! short format address range #define c16KBPage 0b000 -#define c8KBPage 0b001 -#define c4KBPage 0b010 -#define c2KBPage 0b011 -#define c1KBPage 0b100 +#define c8KBPage 0b001 +#define c4KBPage 0b010 +#define c2KBPage 0b011 +#define c1KBPage 0b100 #define c512BPage 0b101 #define c256BPage 0b110 #define c128BPage 0b111 /// Long format address range -#define cPageMAll \ - { \ - 0b000, 0b000 \ - } +#define cPageMAll \ + { 0b000, 0b000 } #define cPageMToMax(M) \ - { \ - M, 0b000 \ - } + { M, 0b000 } #define cPageMaxToM(M) \ - { \ - 0b000, M \ - } + { 0b000, M } #define cPageMToN(M, N) \ - { \ - M, N \ - } - -namespace Kernel::HAL -{ - struct PACKED PTE_4KB final - { - UInt64 Valid : 1; - UInt64 Table : 1; - UInt64 AttrIndex : 3; - UInt64 NS : 1; - UInt64 AP : 2; - UInt64 SH : 2; - UInt64 AF : 1; - UInt64 NG : 1; - UInt64 Reserved1 : 1; - UInt64 Contiguous : 1; - UInt64 Dirty : 1; - UInt64 Reserved : 2; - UInt64 PhysicalAddress : 36; - UInt64 Reserved3 : 4; - UInt64 PXN : 1; - UInt64 XN : 1; - UInt64 Reserved4 : 9; - }; - - namespace Detail - { - enum class ControlRegisterBits - { - ProtectedModeEnable = 0, - MonitorCoProcessor = 1, - Emulation = 2, - TaskSwitched = 3, - ExtensionType = 4, - NumericError = 5, - WriteProtect = 16, - AlignementMask = 18, - NotWriteThrough = 29, - CacheDisable = 30, - PageEnable = 31, - }; - - inline UInt8 control_register_cast(ControlRegisterBits reg) - { - return static_cast(reg); - } - } // namespace Detail - - struct PDE_4KB final - { - PTE_4KB ALIGN(kPageAlign) fEntries[kPageMax]; - }; - - auto mm_alloc_bitmap(Boolean wr, Boolean user, SizeT size, Bool is_page) -> VoidPtr; - auto mm_free_bitmap(VoidPtr page_ptr) -> Bool; -} // namespace Kernel::HAL - -namespace Kernel -{ - typedef HAL::PTE_4KB PTE; - typedef HAL::PDE_4KB PDE; -} // namespace Kernel + { M, N } + +namespace Kernel::HAL { +struct PACKED PTE_4KB final { + UInt64 Valid : 1; + UInt64 Table : 1; + UInt64 AttrIndex : 3; + UInt64 NS : 1; + UInt64 AP : 2; + UInt64 SH : 2; + UInt64 AF : 1; + UInt64 NG : 1; + UInt64 Reserved1 : 1; + UInt64 Contiguous : 1; + UInt64 Dirty : 1; + UInt64 Reserved : 2; + UInt64 PhysicalAddress : 36; + UInt64 Reserved3 : 4; + UInt64 PXN : 1; + UInt64 XN : 1; + UInt64 Reserved4 : 9; +}; + +namespace Detail { + enum class ControlRegisterBits { + ProtectedModeEnable = 0, + MonitorCoProcessor = 1, + Emulation = 2, + TaskSwitched = 3, + ExtensionType = 4, + NumericError = 5, + WriteProtect = 16, + AlignementMask = 18, + NotWriteThrough = 29, + CacheDisable = 30, + PageEnable = 31, + }; + + inline UInt8 control_register_cast(ControlRegisterBits reg) { + return static_cast(reg); + } +} // namespace Detail + +struct PDE_4KB final { + PTE_4KB ALIGN(kPageAlign) fEntries[kPageMax]; +}; + +auto mm_alloc_bitmap(Boolean wr, Boolean user, SizeT size, Bool is_page) -> VoidPtr; +auto mm_free_bitmap(VoidPtr page_ptr) -> Bool; +} // namespace Kernel::HAL + +namespace Kernel { +typedef HAL::PTE_4KB PTE; +typedef HAL::PDE_4KB PDE; +} // namespace Kernel EXTERN_C void hal_flush_tlb(); diff --git a/dev/kernel/HALKit/ARM64/Processor.h b/dev/kernel/HALKit/ARM64/Processor.h index 3a04bed1..38902627 100644 --- a/dev/kernel/HALKit/ARM64/Processor.h +++ b/dev/kernel/HALKit/ARM64/Processor.h @@ -1,93 +1,84 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #pragma once +#include #include #include #include -#include #define kCPUBackendName "ARMv8" -namespace Kernel::HAL -{ - struct PACKED Register64 final - { - UShort Limit; - UIntPtr Base; - }; - - /// @brief Memory Manager mapping flags. - enum - { - kMMFlagsPresent = 1 << 0, - kMMFlagsWr = 1 << 1, - kMMFlagsUser = 1 << 2, - kMMFlagsNX = 1 << 3, - kMMFlagsPCD = 1 << 4, - kMMFlagsCount = 4, - }; - - /// @brief Set a PTE from pd_base. - /// @param virt_addr a valid virtual address. - /// @param phys_addr point to physical address. - /// @param flags the flags to put on the page. - /// @return Status code of page manip. - EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags); - - EXTERN_C UIntPtr hal_get_phys_address(VoidPtr virtual_address); - - typedef UIntPtr Reg; - typedef Register64 Register; - - /// @note let's keep the same name as AMD64 HAL. - struct PACKED StackFrame final - { - Reg R8{0}; - Reg R9{0}; - Reg R10{0}; - Reg R11{0}; - Reg R12{0}; - Reg R13{0}; - Reg R14{0}; - Reg R15{0}; - Reg SP{0}; - Reg BP{0}; - }; - - typedef StackFrame* StackFramePtr; - - inline Void rt_halt() noexcept - { - while (Yes) - { - } - } - - template - inline void hal_dma_write(UIntPtr address, DataKind value) - { - *reinterpret_cast(address) = value; - } - - template - inline DataKind hal_dma_read(UIntPtr address) - { - return *reinterpret_cast(address); - } - - inline Void hal_wfi(Void) - { - asm volatile("wfi"); - } -} // namespace Kernel::HAL +namespace Kernel::HAL { +struct PACKED Register64 final { + UShort Limit; + UIntPtr Base; +}; + +/// @brief Memory Manager mapping flags. +enum { + kMMFlagsPresent = 1 << 0, + kMMFlagsWr = 1 << 1, + kMMFlagsUser = 1 << 2, + kMMFlagsNX = 1 << 3, + kMMFlagsPCD = 1 << 4, + kMMFlagsCount = 4, +}; + +/// @brief Set a PTE from pd_base. +/// @param virt_addr a valid virtual address. +/// @param phys_addr point to physical address. +/// @param flags the flags to put on the page. +/// @return Status code of page manip. +EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags); + +EXTERN_C UIntPtr hal_get_phys_address(VoidPtr virtual_address); + +typedef UIntPtr Reg; +typedef Register64 Register; + +/// @note let's keep the same name as AMD64 HAL. +struct PACKED StackFrame final { + Reg R8{0}; + Reg R9{0}; + Reg R10{0}; + Reg R11{0}; + Reg R12{0}; + Reg R13{0}; + Reg R14{0}; + Reg R15{0}; + Reg SP{0}; + Reg BP{0}; +}; + +typedef StackFrame* StackFramePtr; + +inline Void rt_halt() noexcept { + while (Yes) { + } +} + +template +inline void hal_dma_write(UIntPtr address, DataKind value) { + *reinterpret_cast(address) = value; +} + +template +inline DataKind hal_dma_read(UIntPtr address) { + return *reinterpret_cast(address); +} + +inline Void hal_wfi(Void) { + asm volatile("wfi"); +} +} // namespace Kernel::HAL inline Kernel::VoidPtr kKernelBitMpStart = nullptr; -inline Kernel::UIntPtr kKernelBitMpSize = 0UL; +inline Kernel::UIntPtr kKernelBitMpSize = 0UL; inline Kernel::VoidPtr kKernelPhysicalStart = nullptr; diff --git a/dev/kernel/HALKit/ARM64/Storage/SCSI+Generic.cc b/dev/kernel/HALKit/ARM64/Storage/SCSI+Generic.cc index cb387e73..1cc97cba 100644 --- a/dev/kernel/HALKit/ARM64/Storage/SCSI+Generic.cc +++ b/dev/kernel/HALKit/ARM64/Storage/SCSI+Generic.cc @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -9,5 +9,5 @@ using namespace Kernel; ///! @brief ATAPI SCSI packet. -const ATTRIBUTE(unused) scsi_packet_type_12 kCDRomPacketTemplate = {0x43, 0, 1, 0, 0, 0, - 0, 12, 0x40, 0, 0}; +const ATTRIBUTE(unused) scsi_packet_type_12 kCDRomPacketTemplate = {0x43, 0, 1, 0, 0, 0, + 0, 12, 0x40, 0, 0}; diff --git a/dev/kernel/HALKit/ARM64/Storage/UFS+Generic.cc b/dev/kernel/HALKit/ARM64/Storage/UFS+Generic.cc index 1529e158..e5ef7b91 100644 --- a/dev/kernel/HALKit/ARM64/Storage/UFS+Generic.cc +++ b/dev/kernel/HALKit/ARM64/Storage/UFS+Generic.cc @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ diff --git a/dev/kernel/HALKit/POWER/AP.h b/dev/kernel/HALKit/POWER/AP.h index 4558804b..f938d6a1 100644 --- a/dev/kernel/HALKit/POWER/AP.h +++ b/dev/kernel/HALKit/POWER/AP.h @@ -1,13 +1,13 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: AP.h - Purpose: POWER hardware threads. + File: AP.h + Purpose: POWER hardware threads. - Revision History: + Revision History: - 14/04/24: Added file (amlel) + 14/04/24: Added file (amlel) ------------------------------------------- */ @@ -15,27 +15,25 @@ #include -namespace Kernel -{ - struct HAL_HARDWARE_THREAD; - - /// @brief hardware thread indentification type. - typedef Kernel::Int32 hal_ap_kind; - - /// @brief Hardware thread information structure. - typedef struct HAL_HARDWARE_THREAD - { - Kernel::UIntPtr fStartAddress; - Kernel::UIntPtr fStackPtr; - Kernel::UIntPtr fFramePtr; - Kernel::UInt8 fPrivileged : 1; - Kernel::UInt32 fPageMemoryFlags; - hal_ap_kind fIdentNumber; - } HAL_HARDWARE_THREAD; - - /// @brief Set PC to specific hart. - /// @param hart the hart - /// @param epc the pc. - /// @return - EXTERN_C Kernel::Void hal_set_pc_to_hart(HAL_HARDWARE_THREAD* hart, Kernel::VoidPtr epc); -} // namespace Kernel +namespace Kernel { +struct HAL_HARDWARE_THREAD; + +/// @brief hardware thread indentification type. +typedef Kernel::Int32 hal_ap_kind; + +/// @brief Hardware thread information structure. +typedef struct HAL_HARDWARE_THREAD { + Kernel::UIntPtr fStartAddress; + Kernel::UIntPtr fStackPtr; + Kernel::UIntPtr fFramePtr; + Kernel::UInt8 fPrivileged : 1; + Kernel::UInt32 fPageMemoryFlags; + hal_ap_kind fIdentNumber; +} HAL_HARDWARE_THREAD; + +/// @brief Set PC to specific hart. +/// @param hart the hart +/// @param epc the pc. +/// @return +EXTERN_C Kernel::Void hal_set_pc_to_hart(HAL_HARDWARE_THREAD* hart, Kernel::VoidPtr epc); +} // namespace Kernel diff --git a/dev/kernel/HALKit/POWER/HalApplicationProcessor.cc b/dev/kernel/HALKit/POWER/HalApplicationProcessor.cc index ca2153e3..eb44b72b 100644 --- a/dev/kernel/HALKit/POWER/HalApplicationProcessor.cc +++ b/dev/kernel/HALKit/POWER/HalApplicationProcessor.cc @@ -1,41 +1,35 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ +#include #include #include -#include -namespace Kernel::Detail -{ - STATIC void mp_hang_fn(void) - { - while (YES) - ; - } -} // namespace Kernel::Detail - -namespace Kernel -{ - /// @brief wakes up thread. - /// wakes up thread from hang. - void mp_wakeup_thread(HAL::StackFramePtr stack) - { - if (!stack) - return; - - hal_set_pc_to_hart(reinterpret_cast(stack->R15), reinterpret_cast(stack->BP)); - } - - /// @brief makes thread sleep. - /// hooks and hangs thread to prevent code from executing. - void mp_hang_thread(HAL::StackFramePtr stack) - { - if (!stack) - return; - - hal_set_pc_to_hart(reinterpret_cast(stack->R15), reinterpret_cast(Kernel::Detail::mp_hang_fn)); - } -} // namespace Kernel \ No newline at end of file +namespace Kernel::Detail { +STATIC void mp_hang_fn(void) { + while (YES); +} +} // namespace Kernel::Detail + +namespace Kernel { +/// @brief wakes up thread. +/// wakes up thread from hang. +void mp_wakeup_thread(HAL::StackFramePtr stack) { + if (!stack) return; + + hal_set_pc_to_hart(reinterpret_cast(stack->R15), + reinterpret_cast(stack->BP)); +} + +/// @brief makes thread sleep. +/// hooks and hangs thread to prevent code from executing. +void mp_hang_thread(HAL::StackFramePtr stack) { + if (!stack) return; + + hal_set_pc_to_hart(reinterpret_cast(stack->R15), + reinterpret_cast(Kernel::Detail::mp_hang_fn)); +} +} // namespace Kernel \ No newline at end of file diff --git a/dev/kernel/HALKit/POWER/HalDebugOutput.cc b/dev/kernel/HALKit/POWER/HalDebugOutput.cc index 8142364c..bcc6922c 100644 --- a/dev/kernel/HALKit/POWER/HalDebugOutput.cc +++ b/dev/kernel/HALKit/POWER/HalDebugOutput.cc @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -11,17 +11,14 @@ using namespace Kernel; /// @brief Writes to COM1. /// @param bytes -void ke_io_write(const Char* bytes) -{ - if (!bytes) - return; +void ke_io_write(const Char* bytes) { + if (!bytes) return; - SizeT index = 0; - SizeT len = rt_string_len(bytes, 256U); + SizeT index = 0; + SizeT len = rt_string_len(bytes, 256U); - while (index < len) - { - // TODO - ++index; - } + while (index < len) { + // TODO + ++index; + } } diff --git a/dev/kernel/HALKit/POWER/HalHardwareThread.cc b/dev/kernel/HALKit/POWER/HalHardwareThread.cc index 40bb7d8a..2c7c69ba 100644 --- a/dev/kernel/HALKit/POWER/HalHardwareThread.cc +++ b/dev/kernel/HALKit/POWER/HalHardwareThread.cc @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ diff --git a/dev/kernel/HALKit/POWER/HalVirtualMemory.cc b/dev/kernel/HALKit/POWER/HalVirtualMemory.cc index 5c20458e..07c40134 100644 --- a/dev/kernel/HALKit/POWER/HalVirtualMemory.cc +++ b/dev/kernel/HALKit/POWER/HalVirtualMemory.cc @@ -1,49 +1,46 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ +#include #include #include -#include /// @note Refer to SoC documentation. using namespace Kernel; -EXTERN_C Void hal_write_tlb(UInt32 mas0, UInt32 mas1, UInt32 mas2, UInt32 mas3, UInt32 mas7) -{ - hal_mtspr(MAS0, mas0); - hal_mtspr(MAS1, mas1); - hal_mtspr(MAS2, mas2); - hal_mtspr(MAS3, mas3); - hal_mtspr(MAS7, mas7); +EXTERN_C Void hal_write_tlb(UInt32 mas0, UInt32 mas1, UInt32 mas2, UInt32 mas3, UInt32 mas7) { + hal_mtspr(MAS0, mas0); + hal_mtspr(MAS1, mas1); + hal_mtspr(MAS2, mas2); + hal_mtspr(MAS3, mas3); + hal_mtspr(MAS7, mas7); - hal_flush_tlb(); + hal_flush_tlb(); } -EXTERN_C Bool hal_set_tlb(UInt8 tlb, UInt32 epn, UInt64 rpn, UInt8 perms, UInt8 wimge, UInt8 ts, UInt8 esel, UInt8 tsize, UInt8 iprot) -{ - if ((hal_mfspr(SPRN_MMUCFG) & MMUCFG_MAVN) == MMUCFG_MAVN_V1 && (tsize & 1)) - { - // this MMU does not allow odd tsize values - return false; - } +EXTERN_C Bool hal_set_tlb(UInt8 tlb, UInt32 epn, UInt64 rpn, UInt8 perms, UInt8 wimge, UInt8 ts, + UInt8 esel, UInt8 tsize, UInt8 iprot) { + if ((hal_mfspr(SPRN_MMUCFG) & MMUCFG_MAVN) == MMUCFG_MAVN_V1 && (tsize & 1)) { + // this MMU does not allow odd tsize values + return false; + } - UInt32 mas0 = FSL_BOOKE_MAS0(tlb, esel, 0); - UInt32 mas1 = FSL_BOOKE_MAS1(1, iprot, 0, ts, tsize); - UInt32 mas2 = FSL_BOOKE_MAS2(epn, wimge); - UInt32 mas3 = FSL_BOOKE_MAS3(rpn, 0, perms); - UInt32 mas7 = FSL_BOOKE_MAS7(rpn); + UInt32 mas0 = FSL_BOOKE_MAS0(tlb, esel, 0); + UInt32 mas1 = FSL_BOOKE_MAS1(1, iprot, 0, ts, tsize); + UInt32 mas2 = FSL_BOOKE_MAS2(epn, wimge); + UInt32 mas3 = FSL_BOOKE_MAS3(rpn, 0, perms); + UInt32 mas7 = FSL_BOOKE_MAS7(rpn); - hal_write_tlb(mas0, mas1, mas2, mas3, mas7); + hal_write_tlb(mas0, mas1, mas2, mas3, mas7); - return true; + return true; } /// @brief Flush TLB -EXTERN_C void hal_flush_tlb() -{ - asm volatile("isync;tlbwe;msync;isync"); +EXTERN_C void hal_flush_tlb() { + asm volatile("isync;tlbwe;msync;isync"); } diff --git a/dev/kernel/HALKit/POWER/Processor.h b/dev/kernel/HALKit/POWER/Processor.h index 507805c7..850b636d 100644 --- a/dev/kernel/HALKit/POWER/Processor.h +++ b/dev/kernel/HALKit/POWER/Processor.h @@ -1,8 +1,8 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - Purpose: POWER processor header. + Purpose: POWER processor header. ------------------------------------------- */ @@ -11,52 +11,50 @@ #include #include -#define rtl_nop_op() asm volatile("mr 0, 0") +#define rtl_nop_op() asm volatile("mr 0, 0") #define kHalPPCAlignment __attribute__((aligned(4))) -namespace Kernel::HAL -{ - typedef UIntPtr Reg; - - /// @brief Stack frame (as retrieved from assembly.) - struct PACKED StackFrame final - { - Reg R8{0}; - Reg R9{0}; - Reg R10{0}; - Reg R11{0}; - Reg R12{0}; - Reg R13{0}; - Reg R14{0}; - Reg R15{0}; - Reg SP{0}; - Reg BP{0}; - }; - - typedef StackFrame* StackFramePtr; - - inline void rt_halt() - { - while (true) - { - NoOp(); // no oop. - } - } - - inline void rt_cli() - { - NoOp(); // no oop - } -} // namespace Kernel::HAL +namespace Kernel::HAL { +typedef UIntPtr Reg; + +/// @brief Stack frame (as retrieved from assembly.) +struct PACKED StackFrame final { + Reg R8{0}; + Reg R9{0}; + Reg R10{0}; + Reg R11{0}; + Reg R12{0}; + Reg R13{0}; + Reg R14{0}; + Reg R15{0}; + Reg SP{0}; + Reg BP{0}; +}; + +typedef StackFrame* StackFramePtr; + +inline void rt_halt() { + while (true) { + NoOp(); // no oop. + } +} + +inline void rt_cli() { + NoOp(); // no oop +} +} // namespace Kernel::HAL EXTERN_C Kernel::Void int_handle_math(Kernel::UIntPtr sp); EXTERN_C Kernel::Void int_handle_pf(Kernel::UIntPtr sp); /// @brief Set TLB. -Kernel::Bool hal_set_tlb(Kernel::UInt8 tlb, Kernel::UInt32 epn, Kernel::UInt64 rpn, Kernel::UInt8 perms, Kernel::UInt8 wimge, Kernel::UInt8 ts, Kernel::UInt8 esel, Kernel::UInt8 tsize, Kernel::UInt8 iprot); +Kernel::Bool hal_set_tlb(Kernel::UInt8 tlb, Kernel::UInt32 epn, Kernel::UInt64 rpn, + Kernel::UInt8 perms, Kernel::UInt8 wimge, Kernel::UInt8 ts, + Kernel::UInt8 esel, Kernel::UInt8 tsize, Kernel::UInt8 iprot); /// @brief Write TLB. -Kernel::Void hal_write_tlb(Kernel::UInt32 mas0, Kernel::UInt32 mas1, Kernel::UInt32 mas2, Kernel::UInt32 mas3, Kernel::UInt32 mas7); +Kernel::Void hal_write_tlb(Kernel::UInt32 mas0, Kernel::UInt32 mas1, Kernel::UInt32 mas2, + Kernel::UInt32 mas3, Kernel::UInt32 mas7); /// @brief Flush TLB. EXTERN_C Kernel::Void hal_flush_tlb(); diff --git a/dev/kernel/HALKit/RISCV/AP.h b/dev/kernel/HALKit/RISCV/AP.h index e55e3462..0e94fd97 100644 --- a/dev/kernel/HALKit/RISCV/AP.h +++ b/dev/kernel/HALKit/RISCV/AP.h @@ -1,13 +1,13 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: AP.h - Purpose: RISC-V hardware threads. + File: AP.h + Purpose: RISC-V hardware threads. - Revision History: + Revision History: - 30/01/24: Added file (amlel) + 30/01/24: Added file (amlel) ------------------------------------------- */ @@ -15,23 +15,21 @@ #include -namespace Kernel -{ - typedef Int64 hal_ap_kind; - - typedef struct HAL_HARDWARE_THREAD - { - Kernel::UIntPtr fStartAddress; - Kernel::UIntPtr fStackPtr; - Kernel::UIntPtr fFramePtr; - Kernel::UInt8 fPrivileged : 1; - Kernel::UInt32 fPageMemoryFlags; - hal_ap_kind fIdentNumber; - } HAL_HARDWARE_THREAD; - - /// @brief Set PC to specific hart. - /// @param hart the hart - /// @param epc the pc. - /// @return - EXTERN_C Kernel::Void hal_set_pc_to_hart(HAL_HARDWARE_THREAD* hart, Kernel::VoidPtr epc); -} // namespace Kernel +namespace Kernel { +typedef Int64 hal_ap_kind; + +typedef struct HAL_HARDWARE_THREAD { + Kernel::UIntPtr fStartAddress; + Kernel::UIntPtr fStackPtr; + Kernel::UIntPtr fFramePtr; + Kernel::UInt8 fPrivileged : 1; + Kernel::UInt32 fPageMemoryFlags; + hal_ap_kind fIdentNumber; +} HAL_HARDWARE_THREAD; + +/// @brief Set PC to specific hart. +/// @param hart the hart +/// @param epc the pc. +/// @return +EXTERN_C Kernel::Void hal_set_pc_to_hart(HAL_HARDWARE_THREAD* hart, Kernel::VoidPtr epc); +} // namespace Kernel diff --git a/dev/kernel/HALKit/RISCV/HalApplicationProcessor.cc b/dev/kernel/HALKit/RISCV/HalApplicationProcessor.cc index 1967a649..548167a4 100644 --- a/dev/kernel/HALKit/RISCV/HalApplicationProcessor.cc +++ b/dev/kernel/HALKit/RISCV/HalApplicationProcessor.cc @@ -1,45 +1,39 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ +#include #include #include -#include using namespace Kernel; -namespace Kernel -{ - namespace Detail - { - STATIC void mp_hang_fn(void) - { - while (YES) - ; - } - - } // namespace Detail - - /// @brief wakes up thread. - /// wakes up thread from hang. - void mp_wakeup_thread(HAL::StackFramePtr stack) - { - if (!stack) - return; - - hal_set_pc_to_hart(reinterpret_cast(stack->R15), reinterpret_cast(stack->BP)); - } - - /// @brief makes thread sleep. - /// hooks and hangs thread to prevent code from executing. - void mp_hang_thread(HAL::StackFramePtr stack) - { - if (!stack) - return; - - hal_set_pc_to_hart(reinterpret_cast(stack->R15), reinterpret_cast(Kernel::Detail::mp_hang_fn)); - } - -} // namespace Kernel +namespace Kernel { +namespace Detail { + STATIC void mp_hang_fn(void) { + while (YES); + } + +} // namespace Detail + +/// @brief wakes up thread. +/// wakes up thread from hang. +void mp_wakeup_thread(HAL::StackFramePtr stack) { + if (!stack) return; + + hal_set_pc_to_hart(reinterpret_cast(stack->R15), + reinterpret_cast(stack->BP)); +} + +/// @brief makes thread sleep. +/// hooks and hangs thread to prevent code from executing. +void mp_hang_thread(HAL::StackFramePtr stack) { + if (!stack) return; + + hal_set_pc_to_hart(reinterpret_cast(stack->R15), + reinterpret_cast(Kernel::Detail::mp_hang_fn)); +} + +} // namespace Kernel -- cgit v1.2.3