From d48cbe75ef29a9c67c9d176bf58e56ea6448fb9e Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Mon, 21 Oct 2024 20:23:36 +0200 Subject: IMP: Major refactor of header and source files extensions. Signed-off-by: Amlal El Mahrouss --- dev/zka/ArchKit/ArchKit.h | 85 ++ dev/zka/ArchKit/ArchKit.hxx | 85 -- dev/zka/CFKit/GUIDWizard.h | 22 + dev/zka/CFKit/GUIDWizard.hxx | 22 - dev/zka/CFKit/GUIDWrapper.h | 58 ++ dev/zka/CFKit/GUIDWrapper.hxx | 58 -- dev/zka/CFKit/LoaderUtils.h | 53 + dev/zka/CFKit/LoaderUtils.hxx | 53 - dev/zka/CFKit/Property.h | 47 + dev/zka/CFKit/Property.hxx | 47 - dev/zka/CompilerKit/CompilerKit.h | 13 + dev/zka/CompilerKit/CompilerKit.hxx | 13 - dev/zka/CompilerKit/Detail.h | 27 + dev/zka/CompilerKit/Detail.hxx | 27 - dev/zka/CompilerKit/Version.h | 7 + dev/zka/CompilerKit/Version.hxx | 7 - dev/zka/CompressKit/GZip.h | 18 + dev/zka/CompressKit/GZip.hxx | 18 - dev/zka/CompressKit/RLE.h | 18 + dev/zka/CompressKit/RLE.hxx | 18 - dev/zka/FSKit/Defines.h | 11 + dev/zka/FSKit/Defines.hxx | 11 - dev/zka/FSKit/HPFS.h | 24 + dev/zka/FSKit/HPFS.hxx | 24 - dev/zka/FSKit/IndexableProperty.h | 63 ++ dev/zka/FSKit/IndexableProperty.hxx | 63 -- dev/zka/FSKit/NeFS.h | 331 ++++++ dev/zka/FSKit/NeFS.hxx | 331 ------ dev/zka/FirmwareKit/EFI.h | 11 + dev/zka/FirmwareKit/EFI.hxx | 11 - dev/zka/FirmwareKit/EFI/API.h | 114 +++ dev/zka/FirmwareKit/EFI/API.hxx | 114 --- dev/zka/FirmwareKit/EFI/EFI.h | 883 ++++++++++++++++ dev/zka/FirmwareKit/EFI/EFI.hxx | 883 ---------------- dev/zka/FirmwareKit/EPM.h | 122 +++ dev/zka/FirmwareKit/EPM.hxx | 122 --- dev/zka/FirmwareKit/Handover.h | 116 +++ dev/zka/FirmwareKit/Handover.hxx | 116 --- dev/zka/HALKit/64x0/HalVirtualMemory.cc | 17 + dev/zka/HALKit/64x0/HalVirtualMemory.cxx | 17 - dev/zka/HALKit/AMD64/CPUID.h | 83 ++ dev/zka/HALKit/AMD64/CPUID.hxx | 83 -- dev/zka/HALKit/AMD64/HalACPIFactoryInterface.cc | 126 +++ dev/zka/HALKit/AMD64/HalACPIFactoryInterface.cxx | 126 --- dev/zka/HALKit/AMD64/HalAPICController.cc | 39 + dev/zka/HALKit/AMD64/HalAPICController.cxx | 39 - dev/zka/HALKit/AMD64/HalCPU.cc | 101 ++ dev/zka/HALKit/AMD64/HalCPU.cxx | 101 -- .../HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc | 113 +++ .../HALKit/AMD64/HalCoreInterruptHandlerAMD64.cxx | 113 --- dev/zka/HALKit/AMD64/HalCoreMPScheduler.cc | 229 +++++ dev/zka/HALKit/AMD64/HalCoreMPScheduler.cxx | 229 ----- dev/zka/HALKit/AMD64/HalDebugOutput.cc | 144 +++ dev/zka/HALKit/AMD64/HalDebugOutput.cxx | 144 --- dev/zka/HALKit/AMD64/HalDebugPort.cc | 40 + dev/zka/HALKit/AMD64/HalDebugPort.cxx | 40 - dev/zka/HALKit/AMD64/HalDescriptorLoader.cc | 120 +++ dev/zka/HALKit/AMD64/HalDescriptorLoader.cxx | 120 --- dev/zka/HALKit/AMD64/HalKernelMain.cc | 108 ++ dev/zka/HALKit/AMD64/HalKernelMain.cxx | 108 -- dev/zka/HALKit/AMD64/HalPagingMgr.cc | 162 +++ dev/zka/HALKit/AMD64/HalPagingMgr.cxx | 162 --- dev/zka/HALKit/AMD64/HalSchedulerCore.cc | 56 ++ dev/zka/HALKit/AMD64/HalSchedulerCore.cxx | 56 -- dev/zka/HALKit/AMD64/HalTimer.cc | 86 ++ dev/zka/HALKit/AMD64/HalTimer.cxx | 86 -- dev/zka/HALKit/AMD64/Hypervisor.h | 25 + dev/zka/HALKit/AMD64/Hypervisor.hxx | 25 - dev/zka/HALKit/AMD64/PCI/DMA.cc | 82 ++ dev/zka/HALKit/AMD64/PCI/DMA.cxx | 82 -- dev/zka/HALKit/AMD64/PCI/Database.cc | 11 + dev/zka/HALKit/AMD64/PCI/Database.cxx | 11 - dev/zka/HALKit/AMD64/PCI/Device.cc | 139 +++ dev/zka/HALKit/AMD64/PCI/Device.cxx | 139 --- dev/zka/HALKit/AMD64/PCI/Express.cc | 11 + dev/zka/HALKit/AMD64/PCI/Express.cxx | 11 - dev/zka/HALKit/AMD64/PCI/IO.cc | 7 + dev/zka/HALKit/AMD64/PCI/IO.cxx | 7 - dev/zka/HALKit/AMD64/PCI/Iterator.cc | 41 + dev/zka/HALKit/AMD64/PCI/Iterator.cxx | 41 - dev/zka/HALKit/AMD64/PCI/PCI.cc | 7 + dev/zka/HALKit/AMD64/PCI/PCI.cxx | 7 - dev/zka/HALKit/AMD64/Paging.h | 99 ++ dev/zka/HALKit/AMD64/Paging.hxx | 99 -- dev/zka/HALKit/AMD64/Processor.h | 312 ++++++ dev/zka/HALKit/AMD64/Processor.hxx | 312 ------ dev/zka/HALKit/AMD64/Storage/AHCI.cc | 203 ++++ dev/zka/HALKit/AMD64/Storage/AHCI.cxx | 202 ---- dev/zka/HALKit/AMD64/Storage/ATA-DMA.cc | 38 + dev/zka/HALKit/AMD64/Storage/ATA-DMA.cxx | 38 - dev/zka/HALKit/AMD64/Storage/ATA-PIO.cc | 197 ++++ dev/zka/HALKit/AMD64/Storage/ATA-PIO.cxx | 197 ---- dev/zka/HALKit/ARM64/APM/APM.cc | 37 + dev/zka/HALKit/ARM64/APM/APM.cxx | 37 - dev/zka/HALKit/ARM64/HalACPIFactoryInterface.cc | 31 + dev/zka/HALKit/ARM64/HalACPIFactoryInterface.cxx | 31 - dev/zka/HALKit/ARM64/HalCoreMPScheduler.cc | 19 + dev/zka/HALKit/ARM64/HalCoreMPScheduler.cxx | 19 - dev/zka/HALKit/ARM64/HalDebugOutput.cc | 81 ++ dev/zka/HALKit/ARM64/HalDebugOutput.cxx | 81 -- dev/zka/HALKit/ARM64/HalKernelMain.cc | 46 + dev/zka/HALKit/ARM64/HalKernelMain.cxx | 46 - dev/zka/HALKit/ARM64/HalPagingMgr.cc | 86 ++ dev/zka/HALKit/ARM64/HalPagingMgr.cxx | 86 -- dev/zka/HALKit/ARM64/HalSchedulerCore.cc | 50 + dev/zka/HALKit/ARM64/HalSchedulerCore.cxx | 50 - dev/zka/HALKit/ARM64/HalTimer.cc | 14 + dev/zka/HALKit/ARM64/HalTimer.cxx | 14 - dev/zka/HALKit/ARM64/Paging.h | 120 +++ dev/zka/HALKit/ARM64/Paging.hxx | 120 --- dev/zka/HALKit/ARM64/Processor.h | 75 ++ dev/zka/HALKit/ARM64/Processor.hxx | 75 -- dev/zka/HALKit/ARM64/Storage/HalFlash.cc | 66 ++ dev/zka/HALKit/ARM64/Storage/HalFlash.cxx | 66 -- dev/zka/HALKit/AXP/CoreSyscallHandlerDEC.cpp | 4 +- dev/zka/HALKit/AXP/Processor.h | 7 + dev/zka/HALKit/AXP/Processor.hxx | 7 - dev/zka/HALKit/POWER/HalHart.cc | 25 + dev/zka/HALKit/POWER/HalHart.cxx | 25 - dev/zka/HALKit/POWER/HalSerialPort.cc | 27 + dev/zka/HALKit/POWER/HalSerialPort.cxx | 27 - dev/zka/HALKit/POWER/HalThread.cc | 8 + dev/zka/HALKit/POWER/HalThread.cxx | 8 - dev/zka/HALKit/POWER/HalVirtualMemory.cc | 51 + dev/zka/HALKit/POWER/HalVirtualMemory.cxx | 51 - dev/zka/HALKit/POWER/Hart.h | 36 + dev/zka/HALKit/POWER/Hart.hxx | 36 - dev/zka/HALKit/POWER/MBCI/HalMBCIHost.cc | 8 + dev/zka/HALKit/POWER/MBCI/HalMBCIHost.cxx | 8 - dev/zka/HALKit/POWER/Processor.h | 60 ++ dev/zka/HALKit/POWER/Processor.hxx | 60 -- dev/zka/HALKit/RISCV/Hart.h | 24 + dev/zka/HALKit/RISCV/Hart.hxx | 24 - dev/zka/HintKit/CompilerHint.h | 23 + dev/zka/HintKit/CompilerHint.hxx | 23 - dev/zka/KernelKit/CodeMgr.h | 31 + dev/zka/KernelKit/CodeMgr.hxx | 31 - dev/zka/KernelKit/DebugOutput.h | 197 ++++ dev/zka/KernelKit/DebugOutput.hxx | 197 ---- dev/zka/KernelKit/Defines.h | 11 + dev/zka/KernelKit/Defines.hxx | 11 - dev/zka/KernelKit/DeviceMgr.h | 132 +++ dev/zka/KernelKit/DeviceMgr.hxx | 132 --- dev/zka/KernelKit/DriveMgr.h | 155 +++ dev/zka/KernelKit/DriveMgr.hxx | 155 --- dev/zka/KernelKit/FileMgr.h | 420 ++++++++ dev/zka/KernelKit/FileMgr.hxx | 420 -------- dev/zka/KernelKit/HardwareThreadScheduler.h | 149 +++ dev/zka/KernelKit/HardwareThreadScheduler.hxx | 149 --- dev/zka/KernelKit/Heap.h | 74 ++ dev/zka/KernelKit/Heap.hxx | 74 -- dev/zka/KernelKit/IDLLObject.h | 45 + dev/zka/KernelKit/IDLLObject.hxx | 45 - dev/zka/KernelKit/IPEFDLLObject.h | 106 ++ dev/zka/KernelKit/IPEFDLLObject.hxx | 106 -- dev/zka/KernelKit/LPC.h | 61 ++ dev/zka/KernelKit/LPC.hxx | 61 -- dev/zka/KernelKit/LoaderInterface.h | 33 + dev/zka/KernelKit/LoaderInterface.hxx | 33 - dev/zka/KernelKit/LockDelegate.h | 67 ++ dev/zka/KernelKit/LockDelegate.hxx | 67 -- dev/zka/KernelKit/MSDOS.h | 52 + dev/zka/KernelKit/MSDOS.hxx | 52 - dev/zka/KernelKit/PCI/DMA.h | 81 ++ dev/zka/KernelKit/PCI/DMA.hxx | 81 -- dev/zka/KernelKit/PCI/Database.h | 38 + dev/zka/KernelKit/PCI/Database.hxx | 38 - dev/zka/KernelKit/PCI/Device.h | 80 ++ dev/zka/KernelKit/PCI/Device.hxx | 80 -- dev/zka/KernelKit/PCI/Express.h | 11 + dev/zka/KernelKit/PCI/Express.hxx | 11 - dev/zka/KernelKit/PCI/IO.h | 59 ++ dev/zka/KernelKit/PCI/IO.hxx | 59 -- dev/zka/KernelKit/PCI/Iterator.h | 43 + dev/zka/KernelKit/PCI/Iterator.hxx | 43 - dev/zka/KernelKit/PCI/PCI.h | 59 ++ dev/zka/KernelKit/PCI/PCI.hxx | 59 -- dev/zka/KernelKit/PE.h | 143 +++ dev/zka/KernelKit/PE.hxx | 143 --- dev/zka/KernelKit/PECodeMgr.h | 24 + dev/zka/KernelKit/PECodeMgr.hxx | 24 - dev/zka/KernelKit/PEF.h | 116 +++ dev/zka/KernelKit/PEF.hxx | 116 --- dev/zka/KernelKit/PEFCodeMgr.h | 67 ++ dev/zka/KernelKit/PEFCodeMgr.hxx | 67 -- dev/zka/KernelKit/Semaphore.h | 43 + dev/zka/KernelKit/Semaphore.hxx | 43 - dev/zka/KernelKit/ThreadLocalStorage.h | 54 + dev/zka/KernelKit/ThreadLocalStorage.hxx | 54 - dev/zka/KernelKit/ThreadLocalStorage.inl | 2 +- dev/zka/KernelKit/Timer.h | 82 ++ dev/zka/KernelKit/Timer.hxx | 82 -- dev/zka/KernelKit/User.h | 75 ++ dev/zka/KernelKit/User.hxx | 75 -- dev/zka/KernelKit/UserProcessScheduler.h | 322 ++++++ dev/zka/KernelKit/UserProcessScheduler.hxx | 322 ------ dev/zka/KernelKit/XCOFF.h | 51 + dev/zka/KernelKit/XCOFF.hxx | 51 - dev/zka/KernelRsrc.rsrc | 2 +- dev/zka/NetworkKit/IP.h | 83 ++ dev/zka/NetworkKit/IP.hxx | 83 -- dev/zka/NetworkKit/IPC.h | 91 ++ dev/zka/NetworkKit/IPC.hxx | 91 -- dev/zka/NetworkKit/LTE.h | 16 + dev/zka/NetworkKit/LTE.hxx | 16 - dev/zka/NetworkKit/MAC.h | 29 + dev/zka/NetworkKit/MAC.hxx | 29 - dev/zka/NetworkKit/NetworkDevice.h | 80 ++ dev/zka/NetworkKit/NetworkDevice.hxx | 80 -- dev/zka/NewKit/Array.h | 74 ++ dev/zka/NewKit/Array.hxx | 74 -- dev/zka/NewKit/ArrayList.h | 58 ++ dev/zka/NewKit/ArrayList.hxx | 58 -- dev/zka/NewKit/Atom.h | 46 + dev/zka/NewKit/Atom.hxx | 46 - dev/zka/NewKit/Crc32.h | 23 + dev/zka/NewKit/Crc32.hxx | 23 - dev/zka/NewKit/CxxAbi.h | 28 + dev/zka/NewKit/CxxAbi.hxx | 28 - dev/zka/NewKit/Defines.h | 194 ++++ dev/zka/NewKit/Defines.hxx | 194 ---- dev/zka/NewKit/ErrorOr.h | 72 ++ dev/zka/NewKit/ErrorOr.hxx | 72 -- dev/zka/NewKit/Function.h | 53 + dev/zka/NewKit/Function.hxx | 53 - dev/zka/NewKit/Json.h | 151 +++ dev/zka/NewKit/Json.hxx | 151 --- dev/zka/NewKit/Macros.h | 133 +++ dev/zka/NewKit/Macros.hxx | 133 --- dev/zka/NewKit/MutableArray.h | 239 +++++ dev/zka/NewKit/MutableArray.hxx | 239 ----- dev/zka/NewKit/New.h | 18 + dev/zka/NewKit/New.hxx | 18 - dev/zka/NewKit/NewKit.h | 20 + dev/zka/NewKit/NewKit.hxx | 20 - dev/zka/NewKit/OwnPtr.h | 94 ++ dev/zka/NewKit/OwnPtr.hxx | 94 -- dev/zka/NewKit/PageMgr.h | 81 ++ dev/zka/NewKit/PageMgr.hxx | 81 -- dev/zka/NewKit/Pair.h | 14 + dev/zka/NewKit/Pair.hxx | 14 - dev/zka/NewKit/Pmm.h | 44 + dev/zka/NewKit/Pmm.hxx | 44 - dev/zka/NewKit/Ref.h | 103 ++ dev/zka/NewKit/Ref.hxx | 103 -- dev/zka/NewKit/Stop.h | 71 ++ dev/zka/NewKit/Stop.hxx | 71 -- dev/zka/NewKit/Stream.h | 58 ++ dev/zka/NewKit/Stream.hxx | 58 -- dev/zka/NewKit/String.h | 91 ++ dev/zka/NewKit/String.hxx | 91 -- dev/zka/NewKit/Utils.h | 29 + dev/zka/NewKit/Utils.hxx | 29 - dev/zka/NewKit/Variant.h | 70 ++ dev/zka/NewKit/Variant.hxx | 70 -- dev/zka/StorageKit/AHCI.h | 33 + dev/zka/StorageKit/AHCI.hxx | 33 - dev/zka/StorageKit/ATA.h | 39 + dev/zka/StorageKit/ATA.hxx | 39 - dev/zka/StorageKit/NVME.h | 36 + dev/zka/StorageKit/NVME.hxx | 36 - dev/zka/StorageKit/PRDT.h | 36 + dev/zka/StorageKit/PRDT.hxx | 36 - dev/zka/StorageKit/SCSI.h | 11 + dev/zka/StorageKit/SCSI.hxx | 11 - dev/zka/StorageKit/Storage.h | 22 + dev/zka/StorageKit/Storage.hxx | 22 - dev/zka/amd64-efi.make | 8 +- dev/zka/arm64-efi.make | 10 +- dev/zka/src/ACPIFactoryInterface.cc | 95 ++ dev/zka/src/ACPIFactoryInterface.cxx | 95 -- dev/zka/src/Array.cc | 7 + dev/zka/src/Array.cxx | 7 - dev/zka/src/ArrayList.cc | 7 + dev/zka/src/ArrayList.cxx | 7 - dev/zka/src/Atom.cc | 10 + dev/zka/src/Atom.cxx | 10 - dev/zka/src/BitMapMgr.cc | 203 ++++ dev/zka/src/BitMapMgr.cxx | 203 ---- dev/zka/src/CRuntime.cc | 69 ++ dev/zka/src/CRuntime.cxx | 69 -- dev/zka/src/CodeMgr.cc | 33 + dev/zka/src/CodeMgr.cxx | 33 - dev/zka/src/Crc32.cc | 83 ++ dev/zka/src/Crc32.cxx | 83 -- dev/zka/src/CxxAbi-AMD64.cc | 90 ++ dev/zka/src/CxxAbi-AMD64.cxx | 90 -- dev/zka/src/CxxAbi-ARM64.cc | 90 ++ dev/zka/src/CxxAbi-ARM64.cxx | 90 -- dev/zka/src/Defines.cc | 7 + dev/zka/src/Defines.cxx | 7 - dev/zka/src/DeviceMgr.cc | 7 + dev/zka/src/DeviceMgr.cxx | 7 - dev/zka/src/DriveMgr.cc | 167 ++++ dev/zka/src/DriveMgr.cxx | 167 ---- dev/zka/src/ErrorOr.cc | 12 + dev/zka/src/ErrorOr.cxx | 12 - dev/zka/src/FS/HPFS.cc | 12 + dev/zka/src/FS/HPFS.cxx | 12 - dev/zka/src/FS/NeFS.cc | 1057 ++++++++++++++++++++ dev/zka/src/FS/NeFS.cxx | 1057 -------------------- dev/zka/src/FileMgr.cc | 52 + dev/zka/src/FileMgr.cxx | 52 - dev/zka/src/GUIDWizard.cc | 72 ++ dev/zka/src/GUIDWizard.cxx | 72 -- dev/zka/src/GUIDWrapper.cc | 11 + dev/zka/src/GUIDWrapper.cxx | 11 - dev/zka/src/HardwareThreadScheduler.cc | 193 ++++ dev/zka/src/HardwareThreadScheduler.cxx | 193 ---- dev/zka/src/Heap.cc | 265 +++++ dev/zka/src/Heap.cxx | 265 ----- dev/zka/src/IDLLObject.cc | 15 + dev/zka/src/IDLLObject.cxx | 15 - dev/zka/src/IPEFDLLObject.cc | 102 ++ dev/zka/src/IPEFDLLObject.cxx | 102 -- dev/zka/src/IndexableProperty.cc | 57 ++ dev/zka/src/IndexableProperty.cxx | 57 -- dev/zka/src/Json.cc | 12 + dev/zka/src/Json.cxx | 12 - dev/zka/src/LPC.cc | 34 + dev/zka/src/LPC.cxx | 34 - dev/zka/src/LockDelegate.cc | 12 + dev/zka/src/LockDelegate.cxx | 12 - dev/zka/src/MutableArray.cc | 7 + dev/zka/src/MutableArray.cxx | 7 - dev/zka/src/NeFS+FileMgr.cc | 248 +++++ dev/zka/src/NeFS+FileMgr.cxx | 248 ----- dev/zka/src/NeFS+IO.cc | 101 ++ dev/zka/src/NeFS+IO.cxx | 101 -- dev/zka/src/Network/IP.cc | 126 +++ dev/zka/src/Network/IP.cxx | 126 --- dev/zka/src/Network/IPC.cc | 114 +++ dev/zka/src/Network/IPC.cxx | 114 --- dev/zka/src/Network/NetworkDevice.cc | 35 + dev/zka/src/Network/NetworkDevice.cxx | 35 - dev/zka/src/New+Delete.cc | 50 + dev/zka/src/New+Delete.cxx | 50 - dev/zka/src/OwnPtr.cc | 7 + dev/zka/src/OwnPtr.cxx | 7 - dev/zka/src/PEFCodeMgr.cc | 262 +++++ dev/zka/src/PEFCodeMgr.cxx | 262 ----- dev/zka/src/PRDT.cc | 22 + dev/zka/src/PRDT.cxx | 22 - dev/zka/src/PageMgr.cc | 110 ++ dev/zka/src/PageMgr.cxx | 110 -- dev/zka/src/Pmm.cc | 94 ++ dev/zka/src/Pmm.cxx | 94 -- dev/zka/src/Property.cc | 27 + dev/zka/src/Property.cxx | 27 - dev/zka/src/Ref.cc | 7 + dev/zka/src/Ref.cxx | 7 - dev/zka/src/Semaphore.cc | 62 ++ dev/zka/src/Semaphore.cxx | 62 -- dev/zka/src/Stop.cc | 126 +++ dev/zka/src/Stop.cxx | 126 --- dev/zka/src/Storage/AHCIDeviceInterface.cc | 35 + dev/zka/src/Storage/AHCIDeviceInterface.cxx | 35 - dev/zka/src/Storage/ATADeviceInterface.cc | 88 ++ dev/zka/src/Storage/ATADeviceInterface.cxx | 88 -- dev/zka/src/Storage/NVMEDeviceInterface.cc | 28 + dev/zka/src/Storage/NVMEDeviceInterface.cxx | 28 - dev/zka/src/Storage/SCSIDeviceInterface.cc | 11 + dev/zka/src/Storage/SCSIDeviceInterface.cxx | 11 - dev/zka/src/Stream.cc | 12 + dev/zka/src/Stream.cxx | 12 - dev/zka/src/String.cc | 215 ++++ dev/zka/src/String.cxx | 215 ---- dev/zka/src/ThreadLocalStorage.cc | 67 ++ dev/zka/src/ThreadLocalStorage.cxx | 67 -- dev/zka/src/Timer.cc | 47 + dev/zka/src/Timer.cxx | 47 - dev/zka/src/User.cc | 138 +++ dev/zka/src/User.cxx | 138 --- dev/zka/src/UserProcessScheduler.cc | 592 +++++++++++ dev/zka/src/UserProcessScheduler.cxx | 592 ----------- dev/zka/src/UserProcessTeam.cc | 47 + dev/zka/src/UserProcessTeam.cxx | 47 - dev/zka/src/Utils.cc | 212 ++++ dev/zka/src/Utils.cxx | 212 ---- dev/zka/src/Variant.cc | 33 + dev/zka/src/Variant.cxx | 33 - 381 files changed, 16344 insertions(+), 16343 deletions(-) create mode 100644 dev/zka/ArchKit/ArchKit.h delete mode 100644 dev/zka/ArchKit/ArchKit.hxx create mode 100644 dev/zka/CFKit/GUIDWizard.h delete mode 100644 dev/zka/CFKit/GUIDWizard.hxx create mode 100644 dev/zka/CFKit/GUIDWrapper.h delete mode 100644 dev/zka/CFKit/GUIDWrapper.hxx create mode 100644 dev/zka/CFKit/LoaderUtils.h delete mode 100644 dev/zka/CFKit/LoaderUtils.hxx create mode 100644 dev/zka/CFKit/Property.h delete mode 100644 dev/zka/CFKit/Property.hxx create mode 100644 dev/zka/CompilerKit/CompilerKit.h delete mode 100644 dev/zka/CompilerKit/CompilerKit.hxx create mode 100644 dev/zka/CompilerKit/Detail.h delete mode 100644 dev/zka/CompilerKit/Detail.hxx create mode 100644 dev/zka/CompilerKit/Version.h delete mode 100644 dev/zka/CompilerKit/Version.hxx create mode 100644 dev/zka/CompressKit/GZip.h delete mode 100644 dev/zka/CompressKit/GZip.hxx create mode 100644 dev/zka/CompressKit/RLE.h delete mode 100644 dev/zka/CompressKit/RLE.hxx create mode 100644 dev/zka/FSKit/Defines.h delete mode 100644 dev/zka/FSKit/Defines.hxx create mode 100644 dev/zka/FSKit/HPFS.h delete mode 100644 dev/zka/FSKit/HPFS.hxx create mode 100644 dev/zka/FSKit/IndexableProperty.h delete mode 100644 dev/zka/FSKit/IndexableProperty.hxx create mode 100644 dev/zka/FSKit/NeFS.h delete mode 100644 dev/zka/FSKit/NeFS.hxx create mode 100644 dev/zka/FirmwareKit/EFI.h delete mode 100644 dev/zka/FirmwareKit/EFI.hxx create mode 100644 dev/zka/FirmwareKit/EFI/API.h delete mode 100644 dev/zka/FirmwareKit/EFI/API.hxx create mode 100644 dev/zka/FirmwareKit/EFI/EFI.h delete mode 100644 dev/zka/FirmwareKit/EFI/EFI.hxx create mode 100644 dev/zka/FirmwareKit/EPM.h delete mode 100644 dev/zka/FirmwareKit/EPM.hxx create mode 100644 dev/zka/FirmwareKit/Handover.h delete mode 100644 dev/zka/FirmwareKit/Handover.hxx create mode 100644 dev/zka/HALKit/64x0/HalVirtualMemory.cc delete mode 100644 dev/zka/HALKit/64x0/HalVirtualMemory.cxx create mode 100644 dev/zka/HALKit/AMD64/CPUID.h delete mode 100644 dev/zka/HALKit/AMD64/CPUID.hxx create mode 100644 dev/zka/HALKit/AMD64/HalACPIFactoryInterface.cc delete mode 100644 dev/zka/HALKit/AMD64/HalACPIFactoryInterface.cxx create mode 100644 dev/zka/HALKit/AMD64/HalAPICController.cc delete mode 100644 dev/zka/HALKit/AMD64/HalAPICController.cxx create mode 100644 dev/zka/HALKit/AMD64/HalCPU.cc delete mode 100644 dev/zka/HALKit/AMD64/HalCPU.cxx create mode 100644 dev/zka/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc delete mode 100644 dev/zka/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cxx create mode 100644 dev/zka/HALKit/AMD64/HalCoreMPScheduler.cc delete mode 100644 dev/zka/HALKit/AMD64/HalCoreMPScheduler.cxx create mode 100644 dev/zka/HALKit/AMD64/HalDebugOutput.cc delete mode 100644 dev/zka/HALKit/AMD64/HalDebugOutput.cxx create mode 100644 dev/zka/HALKit/AMD64/HalDebugPort.cc delete mode 100644 dev/zka/HALKit/AMD64/HalDebugPort.cxx create mode 100644 dev/zka/HALKit/AMD64/HalDescriptorLoader.cc delete mode 100644 dev/zka/HALKit/AMD64/HalDescriptorLoader.cxx create mode 100644 dev/zka/HALKit/AMD64/HalKernelMain.cc delete mode 100644 dev/zka/HALKit/AMD64/HalKernelMain.cxx create mode 100644 dev/zka/HALKit/AMD64/HalPagingMgr.cc delete mode 100644 dev/zka/HALKit/AMD64/HalPagingMgr.cxx create mode 100644 dev/zka/HALKit/AMD64/HalSchedulerCore.cc delete mode 100644 dev/zka/HALKit/AMD64/HalSchedulerCore.cxx create mode 100644 dev/zka/HALKit/AMD64/HalTimer.cc delete mode 100644 dev/zka/HALKit/AMD64/HalTimer.cxx create mode 100644 dev/zka/HALKit/AMD64/Hypervisor.h delete mode 100644 dev/zka/HALKit/AMD64/Hypervisor.hxx create mode 100644 dev/zka/HALKit/AMD64/PCI/DMA.cc delete mode 100644 dev/zka/HALKit/AMD64/PCI/DMA.cxx create mode 100644 dev/zka/HALKit/AMD64/PCI/Database.cc delete mode 100644 dev/zka/HALKit/AMD64/PCI/Database.cxx create mode 100644 dev/zka/HALKit/AMD64/PCI/Device.cc delete mode 100644 dev/zka/HALKit/AMD64/PCI/Device.cxx create mode 100644 dev/zka/HALKit/AMD64/PCI/Express.cc delete mode 100644 dev/zka/HALKit/AMD64/PCI/Express.cxx create mode 100644 dev/zka/HALKit/AMD64/PCI/IO.cc delete mode 100644 dev/zka/HALKit/AMD64/PCI/IO.cxx create mode 100644 dev/zka/HALKit/AMD64/PCI/Iterator.cc delete mode 100644 dev/zka/HALKit/AMD64/PCI/Iterator.cxx create mode 100644 dev/zka/HALKit/AMD64/PCI/PCI.cc delete mode 100644 dev/zka/HALKit/AMD64/PCI/PCI.cxx create mode 100644 dev/zka/HALKit/AMD64/Paging.h delete mode 100644 dev/zka/HALKit/AMD64/Paging.hxx create mode 100644 dev/zka/HALKit/AMD64/Processor.h delete mode 100644 dev/zka/HALKit/AMD64/Processor.hxx create mode 100644 dev/zka/HALKit/AMD64/Storage/AHCI.cc delete mode 100644 dev/zka/HALKit/AMD64/Storage/AHCI.cxx create mode 100644 dev/zka/HALKit/AMD64/Storage/ATA-DMA.cc delete mode 100644 dev/zka/HALKit/AMD64/Storage/ATA-DMA.cxx create mode 100644 dev/zka/HALKit/AMD64/Storage/ATA-PIO.cc delete mode 100644 dev/zka/HALKit/AMD64/Storage/ATA-PIO.cxx create mode 100644 dev/zka/HALKit/ARM64/APM/APM.cc delete mode 100644 dev/zka/HALKit/ARM64/APM/APM.cxx create mode 100644 dev/zka/HALKit/ARM64/HalACPIFactoryInterface.cc delete mode 100644 dev/zka/HALKit/ARM64/HalACPIFactoryInterface.cxx create mode 100644 dev/zka/HALKit/ARM64/HalCoreMPScheduler.cc delete mode 100644 dev/zka/HALKit/ARM64/HalCoreMPScheduler.cxx create mode 100644 dev/zka/HALKit/ARM64/HalDebugOutput.cc delete mode 100644 dev/zka/HALKit/ARM64/HalDebugOutput.cxx create mode 100644 dev/zka/HALKit/ARM64/HalKernelMain.cc delete mode 100644 dev/zka/HALKit/ARM64/HalKernelMain.cxx create mode 100644 dev/zka/HALKit/ARM64/HalPagingMgr.cc delete mode 100644 dev/zka/HALKit/ARM64/HalPagingMgr.cxx create mode 100644 dev/zka/HALKit/ARM64/HalSchedulerCore.cc delete mode 100644 dev/zka/HALKit/ARM64/HalSchedulerCore.cxx create mode 100644 dev/zka/HALKit/ARM64/HalTimer.cc delete mode 100644 dev/zka/HALKit/ARM64/HalTimer.cxx create mode 100644 dev/zka/HALKit/ARM64/Paging.h delete mode 100644 dev/zka/HALKit/ARM64/Paging.hxx create mode 100644 dev/zka/HALKit/ARM64/Processor.h delete mode 100644 dev/zka/HALKit/ARM64/Processor.hxx create mode 100644 dev/zka/HALKit/ARM64/Storage/HalFlash.cc delete mode 100644 dev/zka/HALKit/ARM64/Storage/HalFlash.cxx create mode 100644 dev/zka/HALKit/AXP/Processor.h delete mode 100644 dev/zka/HALKit/AXP/Processor.hxx create mode 100644 dev/zka/HALKit/POWER/HalHart.cc delete mode 100644 dev/zka/HALKit/POWER/HalHart.cxx create mode 100644 dev/zka/HALKit/POWER/HalSerialPort.cc delete mode 100644 dev/zka/HALKit/POWER/HalSerialPort.cxx create mode 100644 dev/zka/HALKit/POWER/HalThread.cc delete mode 100644 dev/zka/HALKit/POWER/HalThread.cxx create mode 100644 dev/zka/HALKit/POWER/HalVirtualMemory.cc delete mode 100644 dev/zka/HALKit/POWER/HalVirtualMemory.cxx create mode 100644 dev/zka/HALKit/POWER/Hart.h delete mode 100644 dev/zka/HALKit/POWER/Hart.hxx create mode 100644 dev/zka/HALKit/POWER/MBCI/HalMBCIHost.cc delete mode 100644 dev/zka/HALKit/POWER/MBCI/HalMBCIHost.cxx create mode 100644 dev/zka/HALKit/POWER/Processor.h delete mode 100644 dev/zka/HALKit/POWER/Processor.hxx create mode 100644 dev/zka/HALKit/RISCV/Hart.h delete mode 100644 dev/zka/HALKit/RISCV/Hart.hxx create mode 100644 dev/zka/HintKit/CompilerHint.h delete mode 100644 dev/zka/HintKit/CompilerHint.hxx create mode 100644 dev/zka/KernelKit/CodeMgr.h delete mode 100644 dev/zka/KernelKit/CodeMgr.hxx create mode 100644 dev/zka/KernelKit/DebugOutput.h delete mode 100644 dev/zka/KernelKit/DebugOutput.hxx create mode 100644 dev/zka/KernelKit/Defines.h delete mode 100644 dev/zka/KernelKit/Defines.hxx create mode 100644 dev/zka/KernelKit/DeviceMgr.h delete mode 100644 dev/zka/KernelKit/DeviceMgr.hxx create mode 100644 dev/zka/KernelKit/DriveMgr.h delete mode 100644 dev/zka/KernelKit/DriveMgr.hxx create mode 100644 dev/zka/KernelKit/FileMgr.h delete mode 100644 dev/zka/KernelKit/FileMgr.hxx create mode 100644 dev/zka/KernelKit/HardwareThreadScheduler.h delete mode 100644 dev/zka/KernelKit/HardwareThreadScheduler.hxx create mode 100644 dev/zka/KernelKit/Heap.h delete mode 100644 dev/zka/KernelKit/Heap.hxx create mode 100644 dev/zka/KernelKit/IDLLObject.h delete mode 100644 dev/zka/KernelKit/IDLLObject.hxx create mode 100644 dev/zka/KernelKit/IPEFDLLObject.h delete mode 100644 dev/zka/KernelKit/IPEFDLLObject.hxx create mode 100644 dev/zka/KernelKit/LPC.h delete mode 100644 dev/zka/KernelKit/LPC.hxx create mode 100644 dev/zka/KernelKit/LoaderInterface.h delete mode 100644 dev/zka/KernelKit/LoaderInterface.hxx create mode 100644 dev/zka/KernelKit/LockDelegate.h delete mode 100644 dev/zka/KernelKit/LockDelegate.hxx create mode 100644 dev/zka/KernelKit/MSDOS.h delete mode 100644 dev/zka/KernelKit/MSDOS.hxx create mode 100644 dev/zka/KernelKit/PCI/DMA.h delete mode 100644 dev/zka/KernelKit/PCI/DMA.hxx create mode 100644 dev/zka/KernelKit/PCI/Database.h delete mode 100644 dev/zka/KernelKit/PCI/Database.hxx create mode 100644 dev/zka/KernelKit/PCI/Device.h delete mode 100644 dev/zka/KernelKit/PCI/Device.hxx create mode 100644 dev/zka/KernelKit/PCI/Express.h delete mode 100644 dev/zka/KernelKit/PCI/Express.hxx create mode 100644 dev/zka/KernelKit/PCI/IO.h delete mode 100644 dev/zka/KernelKit/PCI/IO.hxx create mode 100644 dev/zka/KernelKit/PCI/Iterator.h delete mode 100644 dev/zka/KernelKit/PCI/Iterator.hxx create mode 100644 dev/zka/KernelKit/PCI/PCI.h delete mode 100644 dev/zka/KernelKit/PCI/PCI.hxx create mode 100644 dev/zka/KernelKit/PE.h delete mode 100644 dev/zka/KernelKit/PE.hxx create mode 100644 dev/zka/KernelKit/PECodeMgr.h delete mode 100644 dev/zka/KernelKit/PECodeMgr.hxx create mode 100644 dev/zka/KernelKit/PEF.h delete mode 100644 dev/zka/KernelKit/PEF.hxx create mode 100644 dev/zka/KernelKit/PEFCodeMgr.h delete mode 100644 dev/zka/KernelKit/PEFCodeMgr.hxx create mode 100644 dev/zka/KernelKit/Semaphore.h delete mode 100644 dev/zka/KernelKit/Semaphore.hxx create mode 100644 dev/zka/KernelKit/ThreadLocalStorage.h delete mode 100644 dev/zka/KernelKit/ThreadLocalStorage.hxx create mode 100644 dev/zka/KernelKit/Timer.h delete mode 100644 dev/zka/KernelKit/Timer.hxx create mode 100644 dev/zka/KernelKit/User.h delete mode 100644 dev/zka/KernelKit/User.hxx create mode 100644 dev/zka/KernelKit/UserProcessScheduler.h delete mode 100644 dev/zka/KernelKit/UserProcessScheduler.hxx create mode 100644 dev/zka/KernelKit/XCOFF.h delete mode 100644 dev/zka/KernelKit/XCOFF.hxx create mode 100644 dev/zka/NetworkKit/IP.h delete mode 100644 dev/zka/NetworkKit/IP.hxx create mode 100644 dev/zka/NetworkKit/IPC.h delete mode 100644 dev/zka/NetworkKit/IPC.hxx create mode 100644 dev/zka/NetworkKit/LTE.h delete mode 100644 dev/zka/NetworkKit/LTE.hxx create mode 100644 dev/zka/NetworkKit/MAC.h delete mode 100644 dev/zka/NetworkKit/MAC.hxx create mode 100644 dev/zka/NetworkKit/NetworkDevice.h delete mode 100644 dev/zka/NetworkKit/NetworkDevice.hxx create mode 100644 dev/zka/NewKit/Array.h delete mode 100644 dev/zka/NewKit/Array.hxx create mode 100644 dev/zka/NewKit/ArrayList.h delete mode 100644 dev/zka/NewKit/ArrayList.hxx create mode 100644 dev/zka/NewKit/Atom.h delete mode 100644 dev/zka/NewKit/Atom.hxx create mode 100644 dev/zka/NewKit/Crc32.h delete mode 100644 dev/zka/NewKit/Crc32.hxx create mode 100644 dev/zka/NewKit/CxxAbi.h delete mode 100644 dev/zka/NewKit/CxxAbi.hxx create mode 100644 dev/zka/NewKit/Defines.h delete mode 100644 dev/zka/NewKit/Defines.hxx create mode 100644 dev/zka/NewKit/ErrorOr.h delete mode 100644 dev/zka/NewKit/ErrorOr.hxx create mode 100644 dev/zka/NewKit/Function.h delete mode 100644 dev/zka/NewKit/Function.hxx create mode 100644 dev/zka/NewKit/Json.h delete mode 100644 dev/zka/NewKit/Json.hxx create mode 100644 dev/zka/NewKit/Macros.h delete mode 100644 dev/zka/NewKit/Macros.hxx create mode 100644 dev/zka/NewKit/MutableArray.h delete mode 100644 dev/zka/NewKit/MutableArray.hxx create mode 100644 dev/zka/NewKit/New.h delete mode 100644 dev/zka/NewKit/New.hxx create mode 100644 dev/zka/NewKit/NewKit.h delete mode 100644 dev/zka/NewKit/NewKit.hxx create mode 100644 dev/zka/NewKit/OwnPtr.h delete mode 100644 dev/zka/NewKit/OwnPtr.hxx create mode 100644 dev/zka/NewKit/PageMgr.h delete mode 100644 dev/zka/NewKit/PageMgr.hxx create mode 100644 dev/zka/NewKit/Pair.h delete mode 100644 dev/zka/NewKit/Pair.hxx create mode 100644 dev/zka/NewKit/Pmm.h delete mode 100644 dev/zka/NewKit/Pmm.hxx create mode 100644 dev/zka/NewKit/Ref.h delete mode 100644 dev/zka/NewKit/Ref.hxx create mode 100644 dev/zka/NewKit/Stop.h delete mode 100644 dev/zka/NewKit/Stop.hxx create mode 100644 dev/zka/NewKit/Stream.h delete mode 100644 dev/zka/NewKit/Stream.hxx create mode 100644 dev/zka/NewKit/String.h delete mode 100644 dev/zka/NewKit/String.hxx create mode 100644 dev/zka/NewKit/Utils.h delete mode 100644 dev/zka/NewKit/Utils.hxx create mode 100644 dev/zka/NewKit/Variant.h delete mode 100644 dev/zka/NewKit/Variant.hxx create mode 100644 dev/zka/StorageKit/AHCI.h delete mode 100644 dev/zka/StorageKit/AHCI.hxx create mode 100644 dev/zka/StorageKit/ATA.h delete mode 100644 dev/zka/StorageKit/ATA.hxx create mode 100644 dev/zka/StorageKit/NVME.h delete mode 100644 dev/zka/StorageKit/NVME.hxx create mode 100644 dev/zka/StorageKit/PRDT.h delete mode 100644 dev/zka/StorageKit/PRDT.hxx create mode 100644 dev/zka/StorageKit/SCSI.h delete mode 100644 dev/zka/StorageKit/SCSI.hxx create mode 100644 dev/zka/StorageKit/Storage.h delete mode 100644 dev/zka/StorageKit/Storage.hxx create mode 100644 dev/zka/src/ACPIFactoryInterface.cc delete mode 100644 dev/zka/src/ACPIFactoryInterface.cxx create mode 100644 dev/zka/src/Array.cc delete mode 100644 dev/zka/src/Array.cxx create mode 100644 dev/zka/src/ArrayList.cc delete mode 100644 dev/zka/src/ArrayList.cxx create mode 100644 dev/zka/src/Atom.cc delete mode 100644 dev/zka/src/Atom.cxx create mode 100644 dev/zka/src/BitMapMgr.cc delete mode 100644 dev/zka/src/BitMapMgr.cxx create mode 100644 dev/zka/src/CRuntime.cc delete mode 100644 dev/zka/src/CRuntime.cxx create mode 100644 dev/zka/src/CodeMgr.cc delete mode 100644 dev/zka/src/CodeMgr.cxx create mode 100644 dev/zka/src/Crc32.cc delete mode 100644 dev/zka/src/Crc32.cxx create mode 100644 dev/zka/src/CxxAbi-AMD64.cc delete mode 100644 dev/zka/src/CxxAbi-AMD64.cxx create mode 100644 dev/zka/src/CxxAbi-ARM64.cc delete mode 100644 dev/zka/src/CxxAbi-ARM64.cxx create mode 100644 dev/zka/src/Defines.cc delete mode 100644 dev/zka/src/Defines.cxx create mode 100644 dev/zka/src/DeviceMgr.cc delete mode 100644 dev/zka/src/DeviceMgr.cxx create mode 100644 dev/zka/src/DriveMgr.cc delete mode 100644 dev/zka/src/DriveMgr.cxx create mode 100644 dev/zka/src/ErrorOr.cc delete mode 100644 dev/zka/src/ErrorOr.cxx create mode 100644 dev/zka/src/FS/HPFS.cc delete mode 100644 dev/zka/src/FS/HPFS.cxx create mode 100644 dev/zka/src/FS/NeFS.cc delete mode 100644 dev/zka/src/FS/NeFS.cxx create mode 100644 dev/zka/src/FileMgr.cc delete mode 100644 dev/zka/src/FileMgr.cxx create mode 100644 dev/zka/src/GUIDWizard.cc delete mode 100644 dev/zka/src/GUIDWizard.cxx create mode 100644 dev/zka/src/GUIDWrapper.cc delete mode 100644 dev/zka/src/GUIDWrapper.cxx create mode 100644 dev/zka/src/HardwareThreadScheduler.cc delete mode 100644 dev/zka/src/HardwareThreadScheduler.cxx create mode 100644 dev/zka/src/Heap.cc delete mode 100644 dev/zka/src/Heap.cxx create mode 100644 dev/zka/src/IDLLObject.cc delete mode 100644 dev/zka/src/IDLLObject.cxx create mode 100644 dev/zka/src/IPEFDLLObject.cc delete mode 100644 dev/zka/src/IPEFDLLObject.cxx create mode 100644 dev/zka/src/IndexableProperty.cc delete mode 100644 dev/zka/src/IndexableProperty.cxx create mode 100644 dev/zka/src/Json.cc delete mode 100644 dev/zka/src/Json.cxx create mode 100644 dev/zka/src/LPC.cc delete mode 100644 dev/zka/src/LPC.cxx create mode 100644 dev/zka/src/LockDelegate.cc delete mode 100644 dev/zka/src/LockDelegate.cxx create mode 100644 dev/zka/src/MutableArray.cc delete mode 100644 dev/zka/src/MutableArray.cxx create mode 100644 dev/zka/src/NeFS+FileMgr.cc delete mode 100644 dev/zka/src/NeFS+FileMgr.cxx create mode 100644 dev/zka/src/NeFS+IO.cc delete mode 100644 dev/zka/src/NeFS+IO.cxx create mode 100644 dev/zka/src/Network/IP.cc delete mode 100644 dev/zka/src/Network/IP.cxx create mode 100644 dev/zka/src/Network/IPC.cc delete mode 100644 dev/zka/src/Network/IPC.cxx create mode 100644 dev/zka/src/Network/NetworkDevice.cc delete mode 100644 dev/zka/src/Network/NetworkDevice.cxx create mode 100644 dev/zka/src/New+Delete.cc delete mode 100644 dev/zka/src/New+Delete.cxx create mode 100644 dev/zka/src/OwnPtr.cc delete mode 100644 dev/zka/src/OwnPtr.cxx create mode 100644 dev/zka/src/PEFCodeMgr.cc delete mode 100644 dev/zka/src/PEFCodeMgr.cxx create mode 100644 dev/zka/src/PRDT.cc delete mode 100644 dev/zka/src/PRDT.cxx create mode 100644 dev/zka/src/PageMgr.cc delete mode 100644 dev/zka/src/PageMgr.cxx create mode 100644 dev/zka/src/Pmm.cc delete mode 100644 dev/zka/src/Pmm.cxx create mode 100644 dev/zka/src/Property.cc delete mode 100644 dev/zka/src/Property.cxx create mode 100644 dev/zka/src/Ref.cc delete mode 100644 dev/zka/src/Ref.cxx create mode 100644 dev/zka/src/Semaphore.cc delete mode 100644 dev/zka/src/Semaphore.cxx create mode 100644 dev/zka/src/Stop.cc delete mode 100644 dev/zka/src/Stop.cxx create mode 100644 dev/zka/src/Storage/AHCIDeviceInterface.cc delete mode 100644 dev/zka/src/Storage/AHCIDeviceInterface.cxx create mode 100644 dev/zka/src/Storage/ATADeviceInterface.cc delete mode 100644 dev/zka/src/Storage/ATADeviceInterface.cxx create mode 100644 dev/zka/src/Storage/NVMEDeviceInterface.cc delete mode 100644 dev/zka/src/Storage/NVMEDeviceInterface.cxx create mode 100644 dev/zka/src/Storage/SCSIDeviceInterface.cc delete mode 100644 dev/zka/src/Storage/SCSIDeviceInterface.cxx create mode 100644 dev/zka/src/Stream.cc delete mode 100644 dev/zka/src/Stream.cxx create mode 100644 dev/zka/src/String.cc delete mode 100644 dev/zka/src/String.cxx create mode 100644 dev/zka/src/ThreadLocalStorage.cc delete mode 100644 dev/zka/src/ThreadLocalStorage.cxx create mode 100644 dev/zka/src/Timer.cc delete mode 100644 dev/zka/src/Timer.cxx create mode 100644 dev/zka/src/User.cc delete mode 100644 dev/zka/src/User.cxx create mode 100644 dev/zka/src/UserProcessScheduler.cc delete mode 100644 dev/zka/src/UserProcessScheduler.cxx create mode 100644 dev/zka/src/UserProcessTeam.cc delete mode 100644 dev/zka/src/UserProcessTeam.cxx create mode 100644 dev/zka/src/Utils.cc delete mode 100644 dev/zka/src/Utils.cxx create mode 100644 dev/zka/src/Variant.cc delete mode 100644 dev/zka/src/Variant.cxx (limited to 'dev/zka') diff --git a/dev/zka/ArchKit/ArchKit.h b/dev/zka/ArchKit/ArchKit.h new file mode 100644 index 00000000..681dbab1 --- /dev/null +++ b/dev/zka/ArchKit/ArchKit.h @@ -0,0 +1,85 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +#include + +#ifdef __ZKA_AMD64__ +#include +#include +#include +#elif defined(__ZKA_POWER64__) +#include +#elif defined(__ZKA_ARM64__) +#include +#else +#error !!! unknown architecture !!! +#endif + +namespace Kernel +{ + inline SSizeT rt_hash_seed(const Char* seed, int mul) + { + SSizeT hash = 0; + + for (SSizeT idx = 0; seed[idx] != 0; ++idx) + { + hash += seed[idx]; + hash ^= mul; + } + + return hash; + } + + /// @brief write to mapped memory register + /// @param base the base address. + /// @param reg the register. + /// @param value the write to write on it. + inline Void ke_dma_write(UInt32 base, UInt32 reg, UInt32 value) noexcept + { + *(volatile UInt32*)((UInt64)base + reg) = value; + } + + /// @brief read from mapped memory register. + /// @param base base address + /// @param reg the register. + /// @return the value inside the register. + inline UInt32 ke_dma_read(UInt32 base, UInt32 reg) noexcept + { + return *(volatile UInt32*)((UInt64)base + reg); + } +} // namespace Kernel + +#define kKernelMaxSystemCalls (256) + +typedef Kernel::Void (*rt_syscall_proc)(Kernel::VoidPtr); + +struct HAL_SYSCALL_RECORD final +{ + Kernel::Int64 fHash; + Kernel::Bool fHooked; + rt_syscall_proc fProc; + + operator bool() + { + return fHooked; + } +}; + +inline Kernel::Array + kSyscalls; + +inline Kernel::Array + kKerncalls; + +EXTERN_C Kernel::HAL::StackFramePtr mp_get_current_context(); diff --git a/dev/zka/ArchKit/ArchKit.hxx b/dev/zka/ArchKit/ArchKit.hxx deleted file mode 100644 index 0ac0edd6..00000000 --- a/dev/zka/ArchKit/ArchKit.hxx +++ /dev/null @@ -1,85 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -#include - -#ifdef __ZKA_AMD64__ -#include -#include -#include -#elif defined(__ZKA_POWER64__) -#include -#elif defined(__ZKA_ARM64__) -#include -#else -#error !!! unknown architecture !!! -#endif - -namespace Kernel -{ - inline SSizeT rt_hash_seed(const Char* seed, int mul) - { - SSizeT hash = 0; - - for (SSizeT idx = 0; seed[idx] != 0; ++idx) - { - hash += seed[idx]; - hash ^= mul; - } - - return hash; - } - - /// @brief write to mapped memory register - /// @param base the base address. - /// @param reg the register. - /// @param value the write to write on it. - inline Void ke_dma_write(UInt32 base, UInt32 reg, UInt32 value) noexcept - { - *(volatile UInt32*)((UInt64)base + reg) = value; - } - - /// @brief read from mapped memory register. - /// @param base base address - /// @param reg the register. - /// @return the value inside the register. - inline UInt32 ke_dma_read(UInt32 base, UInt32 reg) noexcept - { - return *(volatile UInt32*)((UInt64)base + reg); - } -} // namespace Kernel - -#define kKernelMaxSystemCalls (256) - -typedef Kernel::Void (*rt_syscall_proc)(Kernel::VoidPtr); - -struct HAL_SYSCALL_RECORD final -{ - Kernel::Int64 fHash; - Kernel::Bool fHooked; - rt_syscall_proc fProc; - - operator bool() - { - return fHooked; - } -}; - -inline Kernel::Array - kSyscalls; - -inline Kernel::Array - kKerncalls; - -EXTERN_C Kernel::HAL::StackFramePtr mp_get_current_context(); diff --git a/dev/zka/CFKit/GUIDWizard.h b/dev/zka/CFKit/GUIDWizard.h new file mode 100644 index 00000000..74dab72b --- /dev/null +++ b/dev/zka/CFKit/GUIDWizard.h @@ -0,0 +1,22 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Kernel::XRN::Version1 +{ + Ref cf_make_sequence(const ArrayList& seq); + ErrorOr> cf_try_guid_to_string(Ref& guid); +} // namespace Kernel::XRN::Version1 diff --git a/dev/zka/CFKit/GUIDWizard.hxx b/dev/zka/CFKit/GUIDWizard.hxx deleted file mode 100644 index bd390bd4..00000000 --- a/dev/zka/CFKit/GUIDWizard.hxx +++ /dev/null @@ -1,22 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Kernel::XRN::Version1 -{ - Ref cf_make_sequence(const ArrayList& seq); - ErrorOr> cf_try_guid_to_string(Ref& guid); -} // namespace Kernel::XRN::Version1 diff --git a/dev/zka/CFKit/GUIDWrapper.h b/dev/zka/CFKit/GUIDWrapper.h new file mode 100644 index 00000000..ee51e065 --- /dev/null +++ b/dev/zka/CFKit/GUIDWrapper.h @@ -0,0 +1,58 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +/* GUID for C++ Components */ + +#define kXRNNil "@{........-....-M...-N...-............}" + +// eXtensible Resource Information +namespace Kernel::XRN +{ + union GUIDSequence { + alignas(8) UShort u8[16]; + alignas(8) UShort u16[8]; + alignas(8) UInt u32[4]; + alignas(8) ULong u64[2]; + + struct + { + alignas(8) UInt fMs1; + UShort fMs2; + UShort fMs3; + UChar fMs4[8]; + }; + }; + + class GUID final + { + public: + explicit GUID() = default; + ~GUID() = default; + + public: + GUID& operator=(const GUID&) = default; + GUID(const GUID&) = default; + + public: + GUIDSequence& operator->() noexcept + { + return fUUID; + } + GUIDSequence& Leak() noexcept + { + return fUUID; + } + + private: + GUIDSequence fUUID; + }; +} // namespace Kernel::XRN diff --git a/dev/zka/CFKit/GUIDWrapper.hxx b/dev/zka/CFKit/GUIDWrapper.hxx deleted file mode 100644 index 48977a7c..00000000 --- a/dev/zka/CFKit/GUIDWrapper.hxx +++ /dev/null @@ -1,58 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -/* GUID for C++ Components */ - -#define kXRNNil "@{........-....-M...-N...-............}" - -// eXtensible Resource Information -namespace Kernel::XRN -{ - union GUIDSequence { - alignas(8) UShort u8[16]; - alignas(8) UShort u16[8]; - alignas(8) UInt u32[4]; - alignas(8) ULong u64[2]; - - struct - { - alignas(8) UInt fMs1; - UShort fMs2; - UShort fMs3; - UChar fMs4[8]; - }; - }; - - class GUID final - { - public: - explicit GUID() = default; - ~GUID() = default; - - public: - GUID& operator=(const GUID&) = default; - GUID(const GUID&) = default; - - public: - GUIDSequence& operator->() noexcept - { - return fUUID; - } - GUIDSequence& Leak() noexcept - { - return fUUID; - } - - private: - GUIDSequence fUUID; - }; -} // namespace Kernel::XRN diff --git a/dev/zka/CFKit/LoaderUtils.h b/dev/zka/CFKit/LoaderUtils.h new file mode 100644 index 00000000..4a30ec84 --- /dev/null +++ b/dev/zka/CFKit/LoaderUtils.h @@ -0,0 +1,53 @@ +#ifndef __CFKIT_LOADER_UTILS_HXX__ +#define __CFKIT_LOADER_UTILS_HXX__ + +#include +#include + +namespace Kernel +{ + /// @brief Find the PE header inside the blob. + inline auto ldr_find_exec_header(DosHeaderPtr ptrDos) -> LDR_EXEC_HEADER_PTR + { + if (!ptrDos) + return nullptr; + + if (ptrDos->eMagic[0] != kMagMz0) + return nullptr; + + if (ptrDos->eMagic[1] != kMagMz1) + return nullptr; + + return (LDR_EXEC_HEADER_PTR)(VoidPtr)(&ptrDos->eLfanew + 1); + } + + /// @brief Find the PE optional header inside the blob. + inline auto ldr_find_opt_exec_header(DosHeaderPtr ptrDos) -> LDR_OPTIONAL_HEADER_PTR + { + if (!ptrDos) + return nullptr; + + auto exec = ldr_find_exec_header(ptrDos); + + if (!exec) + return nullptr; + + return (LDR_OPTIONAL_HEADER_PTR)(VoidPtr)(&exec->mCharacteristics + 1); + } + + /// @brief Find the PE header inside the blob. + /// @note overloaded function. + inline auto ldr_find_exec_header(const Char* ptrDos) -> LDR_EXEC_HEADER_PTR + { + return ldr_find_exec_header((DosHeaderPtr)ptrDos); + } + + /// @brief Find the PE header inside the blob. + /// @note overloaded function. + inline auto ldr_find_opt_exec_header(const Char* ptrDos) -> LDR_OPTIONAL_HEADER_PTR + { + return ldr_find_opt_exec_header((DosHeaderPtr)ptrDos); + } +} // namespace Kernel + +#endif // ifndef __CFKIT_LOADER_UTILS_HXX__ diff --git a/dev/zka/CFKit/LoaderUtils.hxx b/dev/zka/CFKit/LoaderUtils.hxx deleted file mode 100644 index 7385fc2e..00000000 --- a/dev/zka/CFKit/LoaderUtils.hxx +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef __CFKIT_LOADER_UTILS_HXX__ -#define __CFKIT_LOADER_UTILS_HXX__ - -#include -#include - -namespace Kernel -{ - /// @brief Find the PE header inside the blob. - inline auto ldr_find_exec_header(DosHeaderPtr ptrDos) -> LDR_EXEC_HEADER_PTR - { - if (!ptrDos) - return nullptr; - - if (ptrDos->eMagic[0] != kMagMz0) - return nullptr; - - if (ptrDos->eMagic[1] != kMagMz1) - return nullptr; - - return (LDR_EXEC_HEADER_PTR)(VoidPtr)(&ptrDos->eLfanew + 1); - } - - /// @brief Find the PE optional header inside the blob. - inline auto ldr_find_opt_exec_header(DosHeaderPtr ptrDos) -> LDR_OPTIONAL_HEADER_PTR - { - if (!ptrDos) - return nullptr; - - auto exec = ldr_find_exec_header(ptrDos); - - if (!exec) - return nullptr; - - return (LDR_OPTIONAL_HEADER_PTR)(VoidPtr)(&exec->mCharacteristics + 1); - } - - /// @brief Find the PE header inside the blob. - /// @note overloaded function. - inline auto ldr_find_exec_header(const Char* ptrDos) -> LDR_EXEC_HEADER_PTR - { - return ldr_find_exec_header((DosHeaderPtr)ptrDos); - } - - /// @brief Find the PE header inside the blob. - /// @note overloaded function. - inline auto ldr_find_opt_exec_header(const Char* ptrDos) -> LDR_OPTIONAL_HEADER_PTR - { - return ldr_find_opt_exec_header((DosHeaderPtr)ptrDos); - } -} // namespace Kernel - -#endif // ifndef __CFKIT_LOADER_UTILS_HXX__ diff --git a/dev/zka/CFKit/Property.h b/dev/zka/CFKit/Property.h new file mode 100644 index 00000000..56829165 --- /dev/null +++ b/dev/zka/CFKit/Property.h @@ -0,0 +1,47 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef __INC_PROPS_HPP__ +#define __INC_PROPS_HPP__ + +#include +#include +#include +#include + +#define cMaxPropLen 4096 + +namespace Kernel +{ + /// @brief handle to anything (number, ptr, string...) + using PropertyId = UIntPtr; + + /// @brief Kernel property class. + /// @example \Properties\SmpCores or \Properties\KernelVersion + class Property + { + public: + Property() = default; + virtual ~Property(); + + public: + Property& operator=(const Property&) = default; + Property(const Property&) = default; + + bool StringEquals(StringView& name); + PropertyId& GetValue(); + StringView& GetKey(); + + private: + StringView fName{cMaxPropLen}; + PropertyId fAction{No}; + }; + + template + using PropertyArray = Array; +} // namespace Kernel + +#endif // !__INC_PROPS_HPP__ diff --git a/dev/zka/CFKit/Property.hxx b/dev/zka/CFKit/Property.hxx deleted file mode 100644 index 7f1aed64..00000000 --- a/dev/zka/CFKit/Property.hxx +++ /dev/null @@ -1,47 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef __INC_PROPS_HPP__ -#define __INC_PROPS_HPP__ - -#include -#include -#include -#include - -#define cMaxPropLen 4096 - -namespace Kernel -{ - /// @brief handle to anything (number, ptr, string...) - using PropertyId = UIntPtr; - - /// @brief Kernel property class. - /// @example \Properties\SmpCores or \Properties\KernelVersion - class Property - { - public: - Property() = default; - virtual ~Property(); - - public: - Property& operator=(const Property&) = default; - Property(const Property&) = default; - - bool StringEquals(StringView& name); - PropertyId& GetValue(); - StringView& GetKey(); - - private: - StringView fName{cMaxPropLen}; - PropertyId fAction{No}; - }; - - template - using PropertyArray = Array; -} // namespace Kernel - -#endif // !__INC_PROPS_HPP__ diff --git a/dev/zka/CompilerKit/CompilerKit.h b/dev/zka/CompilerKit/CompilerKit.h new file mode 100644 index 00000000..6aa7d04f --- /dev/null +++ b/dev/zka/CompilerKit/CompilerKit.h @@ -0,0 +1,13 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef _INC_CL_HPP +#define _INC_CL_HPP + +#include +#include + +#endif /* ifndef _INC_CL_HPP */ diff --git a/dev/zka/CompilerKit/CompilerKit.hxx b/dev/zka/CompilerKit/CompilerKit.hxx deleted file mode 100644 index 01661827..00000000 --- a/dev/zka/CompilerKit/CompilerKit.hxx +++ /dev/null @@ -1,13 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef _INC_CL_HPP -#define _INC_CL_HPP - -#include -#include - -#endif /* ifndef _INC_CL_HPP */ diff --git a/dev/zka/CompilerKit/Detail.h b/dev/zka/CompilerKit/Detail.h new file mode 100644 index 00000000..203175ce --- /dev/null +++ b/dev/zka/CompilerKit/Detail.h @@ -0,0 +1,27 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#ifdef __NEWOSKRNL__ +#include +#endif // ifdef __NEWOSKRNL__ + +#define ZKA_COPY_DELETE(KLASS) \ + KLASS& operator=(const KLASS&) = delete; \ + KLASS(const KLASS&) = delete; + +#define ZKA_COPY_DEFAULT(KLASS) \ + KLASS& operator=(const KLASS&) = default; \ + KLASS(const KLASS&) = default; + +#define ZKA_MOVE_DELETE(KLASS) \ + KLASS& operator=(KLASS&&) = delete; \ + KLASS(KLASS&&) = delete; + +#define ZKA_MOVE_DEFAULT(KLASS) \ + KLASS& operator=(KLASS&&) = default; \ + KLASS(KLASS&&) = default; diff --git a/dev/zka/CompilerKit/Detail.hxx b/dev/zka/CompilerKit/Detail.hxx deleted file mode 100644 index 827cebe6..00000000 --- a/dev/zka/CompilerKit/Detail.hxx +++ /dev/null @@ -1,27 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#ifdef __NEWOSKRNL__ -#include -#endif // ifdef __NEWOSKRNL__ - -#define ZKA_COPY_DELETE(KLASS) \ - KLASS& operator=(const KLASS&) = delete; \ - KLASS(const KLASS&) = delete; - -#define ZKA_COPY_DEFAULT(KLASS) \ - KLASS& operator=(const KLASS&) = default; \ - KLASS(const KLASS&) = default; - -#define ZKA_MOVE_DELETE(KLASS) \ - KLASS& operator=(KLASS&&) = delete; \ - KLASS(KLASS&&) = delete; - -#define ZKA_MOVE_DEFAULT(KLASS) \ - KLASS& operator=(KLASS&&) = default; \ - KLASS(KLASS&&) = default; diff --git a/dev/zka/CompilerKit/Version.h b/dev/zka/CompilerKit/Version.h new file mode 100644 index 00000000..460fe2ee --- /dev/null +++ b/dev/zka/CompilerKit/Version.h @@ -0,0 +1,7 @@ +// (C) ZKA Web Services Co + +#pragma once + +/// .. +#define BOOTLOADER_VERSION "930.2024.1" +#define KERNEL_VERSION "930.2024.1" diff --git a/dev/zka/CompilerKit/Version.hxx b/dev/zka/CompilerKit/Version.hxx deleted file mode 100644 index 460fe2ee..00000000 --- a/dev/zka/CompilerKit/Version.hxx +++ /dev/null @@ -1,7 +0,0 @@ -// (C) ZKA Web Services Co - -#pragma once - -/// .. -#define BOOTLOADER_VERSION "930.2024.1" -#define KERNEL_VERSION "930.2024.1" diff --git a/dev/zka/CompressKit/GZip.h b/dev/zka/CompressKit/GZip.h new file mode 100644 index 00000000..cd1b9744 --- /dev/null +++ b/dev/zka/CompressKit/GZip.h @@ -0,0 +1,18 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef __KERNELKIT_GZIP_HXX__ +#define __KERNELKIT_GZIP_HXX__ + +#include + +namespace Kernel::GZip +{ + class IGZipObject; + class IGZipProxy; +} // namespace Kernel::GZip + +#endif // !__KERNELKIT_GZIP_HXX__ diff --git a/dev/zka/CompressKit/GZip.hxx b/dev/zka/CompressKit/GZip.hxx deleted file mode 100644 index 9f3e23b6..00000000 --- a/dev/zka/CompressKit/GZip.hxx +++ /dev/null @@ -1,18 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef __KERNELKIT_GZIP_HXX__ -#define __KERNELKIT_GZIP_HXX__ - -#include - -namespace Kernel::GZip -{ - class IGZipObject; - class IGZipProxy; -} // namespace Kernel::GZip - -#endif // !__KERNELKIT_GZIP_HXX__ diff --git a/dev/zka/CompressKit/RLE.h b/dev/zka/CompressKit/RLE.h new file mode 100644 index 00000000..64cd53ca --- /dev/null +++ b/dev/zka/CompressKit/RLE.h @@ -0,0 +1,18 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef __KERNELKIT_RLE_HXX__ +#define __KERNELKIT_RLE_HXX__ + +#include + +namespace Kernel +{ + class IRleObject; + class IRleProxy; +} // namespace Kernel + +#endif // !ifndef __KERNELKIT_RLE_HXX__ diff --git a/dev/zka/CompressKit/RLE.hxx b/dev/zka/CompressKit/RLE.hxx deleted file mode 100644 index 6bc19292..00000000 --- a/dev/zka/CompressKit/RLE.hxx +++ /dev/null @@ -1,18 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef __KERNELKIT_RLE_HXX__ -#define __KERNELKIT_RLE_HXX__ - -#include - -namespace Kernel -{ - class IRleObject; - class IRleProxy; -} // namespace Kernel - -#endif // !ifndef __KERNELKIT_RLE_HXX__ diff --git a/dev/zka/FSKit/Defines.h b/dev/zka/FSKit/Defines.h new file mode 100644 index 00000000..e7eac935 --- /dev/null +++ b/dev/zka/FSKit/Defines.h @@ -0,0 +1,11 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +#define FSKIT_VERSION "1.00" diff --git a/dev/zka/FSKit/Defines.hxx b/dev/zka/FSKit/Defines.hxx deleted file mode 100644 index b0107c13..00000000 --- a/dev/zka/FSKit/Defines.hxx +++ /dev/null @@ -1,11 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -#define FSKIT_VERSION "1.00" diff --git a/dev/zka/FSKit/HPFS.h b/dev/zka/FSKit/HPFS.h new file mode 100644 index 00000000..0c778f30 --- /dev/null +++ b/dev/zka/FSKit/HPFS.h @@ -0,0 +1,24 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +/// @file HPFS.h +/// @brief HPFS filesystem support. + +#define kHPFSVersion 0x01000 +#define kHPFSMagic " HPFS" +#define kHPFSMagicLen 8 + +#define kHPFSMinimumDiskSize (gib_cast(64)) + +struct HPFS_EXPLICIT_BOOT_SECTOR; + +struct HPFS_EXPLICIT_BOOT_SECTOR final +{ +}; diff --git a/dev/zka/FSKit/HPFS.hxx b/dev/zka/FSKit/HPFS.hxx deleted file mode 100644 index 12a9d81f..00000000 --- a/dev/zka/FSKit/HPFS.hxx +++ /dev/null @@ -1,24 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -/// @file HPFS.hxx -/// @brief HPFS filesystem support. - -#define kHPFSVersion 0x01000 -#define kHPFSMagic " HPFS" -#define kHPFSMagicLen 8 - -#define kHPFSMinimumDiskSize (gib_cast(64)) - -struct HPFS_EXPLICIT_BOOT_SECTOR; - -struct HPFS_EXPLICIT_BOOT_SECTOR final -{ -}; diff --git a/dev/zka/FSKit/IndexableProperty.h b/dev/zka/FSKit/IndexableProperty.h new file mode 100644 index 00000000..fd7082f8 --- /dev/null +++ b/dev/zka/FSKit/IndexableProperty.h @@ -0,0 +1,63 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +#define kIndexerNodeNameLength 255 +#define kIndexerClaimed 0xCF + +namespace Kernel +{ + namespace Indexer + { + struct IndexProperty final + { + public: + Char Drive[kDriveNameLen]; + Char Path[kIndexerNodeNameLength]; + }; + + class IndexableProperty final : public Property + { + public: + explicit IndexableProperty() + : Property() + { + Kernel::StringView strProp(cMaxPropLen); + strProp += "\\Properties\\Indexable"; + + this->GetKey() = strProp; + } + + ~IndexableProperty() override = default; + + ZKA_COPY_DEFAULT(IndexableProperty); + + public: + IndexProperty& Leak() noexcept; + + public: + void AddFlag(Int16 flag); + void RemoveFlag(Int16 flag); + Int16 HasFlag(Int16 flag); + + private: + IndexProperty fIndex; + UInt32 fFlags; + }; + + /// @brief Index a file into the indexer instance. + /// @param filename path + /// @param filenameLen used bytes in path. + /// @param indexer the filesystem indexer. + /// @return none. + Void fs_index_file(const Char* filename, SizeT filenameLen, IndexableProperty& indexer); + } // namespace Indexer +} // namespace Kernel diff --git a/dev/zka/FSKit/IndexableProperty.hxx b/dev/zka/FSKit/IndexableProperty.hxx deleted file mode 100644 index ca0fa0d1..00000000 --- a/dev/zka/FSKit/IndexableProperty.hxx +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -#define kIndexerNodeNameLength 255 -#define kIndexerClaimed 0xCF - -namespace Kernel -{ - namespace Indexer - { - struct IndexProperty final - { - public: - Char Drive[kDriveNameLen]; - Char Path[kIndexerNodeNameLength]; - }; - - class IndexableProperty final : public Property - { - public: - explicit IndexableProperty() - : Property() - { - Kernel::StringView strProp(cMaxPropLen); - strProp += "\\Properties\\Indexable"; - - this->GetKey() = strProp; - } - - ~IndexableProperty() override = default; - - ZKA_COPY_DEFAULT(IndexableProperty); - - public: - IndexProperty& Leak() noexcept; - - public: - void AddFlag(Int16 flag); - void RemoveFlag(Int16 flag); - Int16 HasFlag(Int16 flag); - - private: - IndexProperty fIndex; - UInt32 fFlags; - }; - - /// @brief Index a file into the indexer instance. - /// @param filename path - /// @param filenameLen used bytes in path. - /// @param indexer the filesystem indexer. - /// @return none. - Void fs_index_file(const Char* filename, SizeT filenameLen, IndexableProperty& indexer); - } // namespace Indexer -} // namespace Kernel diff --git a/dev/zka/FSKit/NeFS.h b/dev/zka/FSKit/NeFS.h new file mode 100644 index 00000000..08771032 --- /dev/null +++ b/dev/zka/FSKit/NeFS.h @@ -0,0 +1,331 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + FILE: NeFS.h + PURPOSE: NeFS (New FileSystem) support, can be used with kernel, HPFS is preferred. + + Revision History: + + ?/?/?: Added file (amlel) + 12/02/24: Add UUID macro for EPM and GPT partition schemes. + 3/16/24: Add mandatory sector size, kNeFSSectorSz is set to 2048 by +default. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include +#include + +/** + @brief New File System specification. + @author Amlal EL Mahrouss +*/ + +#define kNeFSInvalidFork (-1) +#define kNeFSInvalidCatalog (-1) +#define kNeFSNodeNameLen (256) + +#define kNeFSMinimumDiskSize (gib_cast(4)) + +#define kNeFSSectorSz (512) +#define kNeFSForkDataSz (mib_cast(16)) + +#define kNeFSIdentLen (8) +#define kNeFSIdent " NeFS" +#define kNeFSPadLen (392) + +#define kNeFSMetaFilePrefix '$' + +#define kNeFSVersionInteger (0x0128) +#define kNeFSVerionString "1.28" + +/// @brief Standard fork types. +#define kNeFSDataFork "main_data" +#define kNeFSResourceFork "main_rsrc" + +#define kNeFSForkSize (sizeof(NFS_FORK_STRUCT)) + +#define kNeFSPartitionTypeStandard (7) +#define kNeFSPartitionTypePage (8) +#define kNeFSPartitionTypeBoot (9) + +#define kNeFSCatalogKindFile (1) +#define kNeFSCatalogKindDir (2) +#define kNeFSCatalogKindAlias (3) + +//! Shared between network and/or partitions. Export forks as .zip when copying. +#define kNeFSCatalogKindShared (4) + +#define kNeFSCatalogKindResource (5) +#define kNeFSCatalogKindExecutable (6) + +#define kNeFSCatalogKindPage (8) + +#define kNeFSCatalogKindDevice (9) +#define kNeFSCatalogKindLock (10) + +#define kNeFSCatalogKindRLE (11) +#define kNeFSCatalogKindMetaFile (12) + +#define kNeFSCatalogKindTTF (13) +#define kNeFSCatalogKindRIFF (14) + +#define kNeFSSeparator '\\' +#define kNeFSSeparatorAlt '/' + +#define kNeFSUpDir ".." +#define kNeFSRoot "\\" +#define kNeFSRootAlt "/" + +#define kNeFSLF '\r' +#define kNeFSEOF (-1) + +#define kNeFSBitWidth (sizeof(Kernel::Char)) +#define kNeFSLbaType (Kernel::Lba) + +/// @note Start after the partition map header. (Virtual addressing) +#define kNeFSRootCatalogStartAddress (1024) +#define kNeFSCatalogStartAddress ((2048) + sizeof(NFS_ROOT_PARTITION_BLOCK)) + +#define kResourceTypeDialog (10) +#define kResourceTypeString (11) +#define kResourceTypeMenu (12) +#define kResourceTypeSound (13) +#define kResourceTypeFont (14) + +#define kConfigLen (64) +#define kPartLen (32) + +#define kNeFSFlagDeleted (70) +#define kNeFSFlagUnallocated (0) +#define kNeFSFlagCreated (71) + +#define kNeFSMimeNameLen (200) + +#define kNeFSForkNameLen (200U) + +struct NFS_CATALOG_STRUCT; +struct NFS_FORK_STRUCT; +struct NFS_ROOT_PARTITION_BLOCK; + +enum +{ + kNeFSHardDrive = 0xC0, // Hard Drive + kNeFSSolidStateDrive = 0xC1, // Solid State Drive + kNeFSOpticalDrive = 0x0C, // Blu-Ray/DVD + kNeFSMassStorageDevice = 0xCC, // USB + kNeFSScsiDrive = 0xC4, // SCSI Hard Drive + kNeFSFlashDrive = 0xC6, + kNeFSUnknown = 0xFF, // Unknown device. + kNeFSDriveCount = 7, +}; + +/// @brief Catalog type. +struct PACKED NFS_CATALOG_STRUCT final +{ + Kernel::Char Name[kNeFSNodeNameLen]; + Kernel::Char Mime[kNeFSMimeNameLen]; + + /// Catalog status flag. + Kernel::UInt16 Flags; + /// Custom catalog flags. + Kernel::UInt16 FileFlags; + /// Catalog kind. + Kernel::Int32 Kind; + + /// Size of the data fork. + Kernel::Lba DataForkSize; + + /// Size of all resource forks. + Kernel::Lba ResourceForkSize; + + Kernel::Lba DataFork; + Kernel::Lba ResourceFork; + + Kernel::Lba NextSibling; + Kernel::Lba PrevSibling; +}; + +/// @brief Fork type, contains a data page. +/// @note The way we store is way different than how other filesystems do, specific chunk of code are +/// written into either the data fork or resource fork, the resource fork is reserved for file metadata. +/// whereas the data fork is reserved for file data. +struct PACKED NFS_FORK_STRUCT final +{ + Kernel::Char ForkName[kNeFSForkNameLen]; + Kernel::Char CatalogName[kNeFSNodeNameLen]; + + Kernel::Int32 Flags; + Kernel::Int32 Kind; + + Kernel::Int64 ResourceId; + Kernel::Int32 ResourceKind; + Kernel::Int32 ResourceFlags; + + Kernel::Lba DataOffset; // 8 Where to look for this data? + Kernel::SizeT DataSize; /// Data size according using sector count. + + Kernel::Lba NextSibling; + Kernel::Lba PreviousSibling; +}; + +/// @brief Partition block type +struct PACKED NFS_ROOT_PARTITION_BLOCK final +{ + Kernel::Char Ident[kNeFSIdentLen]; + Kernel::Char PartitionName[kPartLen]; + + Kernel::Int32 Flags; + Kernel::Int32 Kind; + + Kernel::Lba StartCatalog; + Kernel::SizeT CatalogCount; + + Kernel::SizeT DiskSize; + + Kernel::SizeT FreeCatalog; + Kernel::SizeT FreeSectors; + + Kernel::SizeT SectorCount; + Kernel::SizeT SectorSize; + + Kernel::UInt64 Version; + + Kernel::Lba EpmBlock; + + Kernel::Char Pad[kNeFSPadLen]; +}; + +namespace Kernel +{ + enum + { + kNeFSSubDriveA, + kNeFSSubDriveB, + kNeFSSubDriveC, + kNeFSSubDriveD, + kNeFSSubDriveInvalid, + kNeFSSubDriveCount, + }; + + /// \brief Resource fork kind. + enum + { + kNeFSRsrcForkKind = 0, + kNeFSDataForkKind = 1 + }; + + /// + /// \name NeFSParser + /// \brief NeFS parser class. (catalog creation, remove removal, root, + /// forks...) Designed like the DOM, detects the filesystem automatically. + /// + class NeFSParser final + { + public: + explicit NeFSParser() = default; + ~NeFSParser() = default; + + public: + ZKA_COPY_DEFAULT(NeFSParser); + + public: + /// @brief Creates a new fork inside the New filesystem partition. + /// @param catalog it's catalog + /// @param theFork the fork itself. + /// @return the fork + _Output NFS_FORK_STRUCT* CreateFork(_Input NFS_CATALOG_STRUCT* catalog, + _Input NFS_FORK_STRUCT& theFork); + + /// @brief Find fork inside New filesystem. + /// @param catalog the catalog. + /// @param name the fork name. + /// @return the fork. + _Output NFS_FORK_STRUCT* FindFork(_Input NFS_CATALOG_STRUCT* catalog, + _Input const Char* name, + Boolean dataOrRsrc); + + _Output Void RemoveFork(_Input NFS_FORK_STRUCT* fork); + + _Output Void CloseFork(_Input NFS_FORK_STRUCT* fork); + + _Output NFS_CATALOG_STRUCT* FindCatalog(_Input const Char* catalogName, Lba& outLba); + + _Output NFS_CATALOG_STRUCT* GetCatalog(_Input const Char* name); + + _Output NFS_CATALOG_STRUCT* CreateCatalog(_Input const Char* name, + _Input const Int32& flags, + _Input const Int32& kind); + + _Output NFS_CATALOG_STRUCT* CreateCatalog(_Input const Char* name); + + Bool WriteCatalog(_Input _Output NFS_CATALOG_STRUCT* catalog, + _Input Bool isRsrcFork, + _Input VoidPtr data, + _Input SizeT sizeOfData, + _Input const Char* forkName); + + VoidPtr ReadCatalog(_Input _Output NFS_CATALOG_STRUCT* catalog, + _Input Bool isRsrcFork, + _Input SizeT dataSz, + _Input const Char* forkName); + + bool Seek(_Input _Output NFS_CATALOG_STRUCT* catalog, SizeT off); + + SizeT Tell(_Input _Output NFS_CATALOG_STRUCT* catalog); + + bool RemoveCatalog(_Input const Char* catalog); + + bool CloseCatalog(_InOut NFS_CATALOG_STRUCT* catalog); + + /// @brief Make a EPM+NeFS drive out of the disk. + /// @param drive The drive to write on. + /// @return If it was sucessful, see ErrLocal(). + bool Format(_Input _Output DriveTrait* drive, _Input const Lba endLba, _Input const Int32 flags, const Char* part_name); + + public: + Int32 fDriveIndex{kNeFSSubDriveA}; + }; + + /// + /// \name NeFileSystemHelper + /// \brief Filesystem helper and utils. + /// + + class NeFileSystemHelper final + { + public: + STATIC const Char* Root(); + STATIC const Char* UpDir(); + STATIC const Char Separator(); + STATIC const Char MetaFile(); + }; + + namespace Detail + { + Boolean fs_init_newfs(Void) noexcept; + } // namespace Detail +} // namespace Kernel + +/// @brief Write to newfs disk. +/// @param Mnt mounted interface. +/// @param DrvTrait drive info +/// @param DrvIndex drive index. +/// @return +Kernel::Int32 fs_newfs_write(Kernel::MountpointInterface* Mnt, + Kernel::DriveTrait& DrvTrait, + Kernel::Int32 DrvIndex); + +/// @brief Read from newfs disk. +/// @param Mnt mounted interface. +/// @param DrvTrait drive info +/// @param DrvIndex drive index. +/// @return +Kernel::Int32 fs_newfs_read(Kernel::MountpointInterface* Mnt, + Kernel::DriveTrait& DrvTrait, + Kernel::Int32 DrvIndex); diff --git a/dev/zka/FSKit/NeFS.hxx b/dev/zka/FSKit/NeFS.hxx deleted file mode 100644 index 4696df57..00000000 --- a/dev/zka/FSKit/NeFS.hxx +++ /dev/null @@ -1,331 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - FILE: NeFS.hxx - PURPOSE: NeFS (New FileSystem) support, can be used with kernel, HPFS is preferred. - - Revision History: - - ?/?/?: Added file (amlel) - 12/02/24: Add UUID macro for EPM and GPT partition schemes. - 3/16/24: Add mandatory sector size, kNeFSSectorSz is set to 2048 by -default. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include -#include - -/** - @brief New File System specification. - @author Amlal EL Mahrouss -*/ - -#define kNeFSInvalidFork (-1) -#define kNeFSInvalidCatalog (-1) -#define kNeFSNodeNameLen (256) - -#define kNeFSMinimumDiskSize (gib_cast(4)) - -#define kNeFSSectorSz (512) -#define kNeFSForkDataSz (mib_cast(16)) - -#define kNeFSIdentLen (8) -#define kNeFSIdent " NeFS" -#define kNeFSPadLen (392) - -#define kNeFSMetaFilePrefix '$' - -#define kNeFSVersionInteger (0x0128) -#define kNeFSVerionString "1.28" - -/// @brief Standard fork types. -#define kNeFSDataFork "main_data" -#define kNeFSResourceFork "main_rsrc" - -#define kNeFSForkSize (sizeof(NFS_FORK_STRUCT)) - -#define kNeFSPartitionTypeStandard (7) -#define kNeFSPartitionTypePage (8) -#define kNeFSPartitionTypeBoot (9) - -#define kNeFSCatalogKindFile (1) -#define kNeFSCatalogKindDir (2) -#define kNeFSCatalogKindAlias (3) - -//! Shared between network and/or partitions. Export forks as .zip when copying. -#define kNeFSCatalogKindShared (4) - -#define kNeFSCatalogKindResource (5) -#define kNeFSCatalogKindExecutable (6) - -#define kNeFSCatalogKindPage (8) - -#define kNeFSCatalogKindDevice (9) -#define kNeFSCatalogKindLock (10) - -#define kNeFSCatalogKindRLE (11) -#define kNeFSCatalogKindMetaFile (12) - -#define kNeFSCatalogKindTTF (13) -#define kNeFSCatalogKindRIFF (14) - -#define kNeFSSeparator '\\' -#define kNeFSSeparatorAlt '/' - -#define kNeFSUpDir ".." -#define kNeFSRoot "\\" -#define kNeFSRootAlt "/" - -#define kNeFSLF '\r' -#define kNeFSEOF (-1) - -#define kNeFSBitWidth (sizeof(Kernel::Char)) -#define kNeFSLbaType (Kernel::Lba) - -/// @note Start after the partition map header. (Virtual addressing) -#define kNeFSRootCatalogStartAddress (1024) -#define kNeFSCatalogStartAddress ((2048) + sizeof(NFS_ROOT_PARTITION_BLOCK)) - -#define kResourceTypeDialog (10) -#define kResourceTypeString (11) -#define kResourceTypeMenu (12) -#define kResourceTypeSound (13) -#define kResourceTypeFont (14) - -#define kConfigLen (64) -#define kPartLen (32) - -#define kNeFSFlagDeleted (70) -#define kNeFSFlagUnallocated (0) -#define kNeFSFlagCreated (71) - -#define kNeFSMimeNameLen (200) - -#define kNeFSForkNameLen (200U) - -struct NFS_CATALOG_STRUCT; -struct NFS_FORK_STRUCT; -struct NFS_ROOT_PARTITION_BLOCK; - -enum -{ - kNeFSHardDrive = 0xC0, // Hard Drive - kNeFSSolidStateDrive = 0xC1, // Solid State Drive - kNeFSOpticalDrive = 0x0C, // Blu-Ray/DVD - kNeFSMassStorageDevice = 0xCC, // USB - kNeFSScsiDrive = 0xC4, // SCSI Hard Drive - kNeFSFlashDrive = 0xC6, - kNeFSUnknown = 0xFF, // Unknown device. - kNeFSDriveCount = 7, -}; - -/// @brief Catalog type. -struct PACKED NFS_CATALOG_STRUCT final -{ - Kernel::Char Name[kNeFSNodeNameLen]; - Kernel::Char Mime[kNeFSMimeNameLen]; - - /// Catalog status flag. - Kernel::UInt16 Flags; - /// Custom catalog flags. - Kernel::UInt16 FileFlags; - /// Catalog kind. - Kernel::Int32 Kind; - - /// Size of the data fork. - Kernel::Lba DataForkSize; - - /// Size of all resource forks. - Kernel::Lba ResourceForkSize; - - Kernel::Lba DataFork; - Kernel::Lba ResourceFork; - - Kernel::Lba NextSibling; - Kernel::Lba PrevSibling; -}; - -/// @brief Fork type, contains a data page. -/// @note The way we store is way different than how other filesystems do, specific chunk of code are -/// written into either the data fork or resource fork, the resource fork is reserved for file metadata. -/// whereas the data fork is reserved for file data. -struct PACKED NFS_FORK_STRUCT final -{ - Kernel::Char ForkName[kNeFSForkNameLen]; - Kernel::Char CatalogName[kNeFSNodeNameLen]; - - Kernel::Int32 Flags; - Kernel::Int32 Kind; - - Kernel::Int64 ResourceId; - Kernel::Int32 ResourceKind; - Kernel::Int32 ResourceFlags; - - Kernel::Lba DataOffset; // 8 Where to look for this data? - Kernel::SizeT DataSize; /// Data size according using sector count. - - Kernel::Lba NextSibling; - Kernel::Lba PreviousSibling; -}; - -/// @brief Partition block type -struct PACKED NFS_ROOT_PARTITION_BLOCK final -{ - Kernel::Char Ident[kNeFSIdentLen]; - Kernel::Char PartitionName[kPartLen]; - - Kernel::Int32 Flags; - Kernel::Int32 Kind; - - Kernel::Lba StartCatalog; - Kernel::SizeT CatalogCount; - - Kernel::SizeT DiskSize; - - Kernel::SizeT FreeCatalog; - Kernel::SizeT FreeSectors; - - Kernel::SizeT SectorCount; - Kernel::SizeT SectorSize; - - Kernel::UInt64 Version; - - Kernel::Lba EpmBlock; - - Kernel::Char Pad[kNeFSPadLen]; -}; - -namespace Kernel -{ - enum - { - kNeFSSubDriveA, - kNeFSSubDriveB, - kNeFSSubDriveC, - kNeFSSubDriveD, - kNeFSSubDriveInvalid, - kNeFSSubDriveCount, - }; - - /// \brief Resource fork kind. - enum - { - kNeFSRsrcForkKind = 0, - kNeFSDataForkKind = 1 - }; - - /// - /// \name NeFSParser - /// \brief NeFS parser class. (catalog creation, remove removal, root, - /// forks...) Designed like the DOM, detects the filesystem automatically. - /// - class NeFSParser final - { - public: - explicit NeFSParser() = default; - ~NeFSParser() = default; - - public: - ZKA_COPY_DEFAULT(NeFSParser); - - public: - /// @brief Creates a new fork inside the New filesystem partition. - /// @param catalog it's catalog - /// @param theFork the fork itself. - /// @return the fork - _Output NFS_FORK_STRUCT* CreateFork(_Input NFS_CATALOG_STRUCT* catalog, - _Input NFS_FORK_STRUCT& theFork); - - /// @brief Find fork inside New filesystem. - /// @param catalog the catalog. - /// @param name the fork name. - /// @return the fork. - _Output NFS_FORK_STRUCT* FindFork(_Input NFS_CATALOG_STRUCT* catalog, - _Input const Char* name, - Boolean dataOrRsrc); - - _Output Void RemoveFork(_Input NFS_FORK_STRUCT* fork); - - _Output Void CloseFork(_Input NFS_FORK_STRUCT* fork); - - _Output NFS_CATALOG_STRUCT* FindCatalog(_Input const Char* catalogName, Lba& outLba); - - _Output NFS_CATALOG_STRUCT* GetCatalog(_Input const Char* name); - - _Output NFS_CATALOG_STRUCT* CreateCatalog(_Input const Char* name, - _Input const Int32& flags, - _Input const Int32& kind); - - _Output NFS_CATALOG_STRUCT* CreateCatalog(_Input const Char* name); - - Bool WriteCatalog(_Input _Output NFS_CATALOG_STRUCT* catalog, - _Input Bool isRsrcFork, - _Input VoidPtr data, - _Input SizeT sizeOfData, - _Input const Char* forkName); - - VoidPtr ReadCatalog(_Input _Output NFS_CATALOG_STRUCT* catalog, - _Input Bool isRsrcFork, - _Input SizeT dataSz, - _Input const Char* forkName); - - bool Seek(_Input _Output NFS_CATALOG_STRUCT* catalog, SizeT off); - - SizeT Tell(_Input _Output NFS_CATALOG_STRUCT* catalog); - - bool RemoveCatalog(_Input const Char* catalog); - - bool CloseCatalog(_InOut NFS_CATALOG_STRUCT* catalog); - - /// @brief Make a EPM+NeFS drive out of the disk. - /// @param drive The drive to write on. - /// @return If it was sucessful, see ErrLocal(). - bool Format(_Input _Output DriveTrait* drive, _Input const Lba endLba, _Input const Int32 flags, const Char* part_name); - - public: - Int32 fDriveIndex{kNeFSSubDriveA}; - }; - - /// - /// \name NeFileSystemHelper - /// \brief Filesystem helper and utils. - /// - - class NeFileSystemHelper final - { - public: - STATIC const Char* Root(); - STATIC const Char* UpDir(); - STATIC const Char Separator(); - STATIC const Char MetaFile(); - }; - - namespace Detail - { - Boolean fs_init_newfs(Void) noexcept; - } // namespace Detail -} // namespace Kernel - -/// @brief Write to newfs disk. -/// @param Mnt mounted interface. -/// @param DrvTrait drive info -/// @param DrvIndex drive index. -/// @return -Kernel::Int32 fs_newfs_write(Kernel::MountpointInterface* Mnt, - Kernel::DriveTrait& DrvTrait, - Kernel::Int32 DrvIndex); - -/// @brief Read from newfs disk. -/// @param Mnt mounted interface. -/// @param DrvTrait drive info -/// @param DrvIndex drive index. -/// @return -Kernel::Int32 fs_newfs_read(Kernel::MountpointInterface* Mnt, - Kernel::DriveTrait& DrvTrait, - Kernel::Int32 DrvIndex); diff --git a/dev/zka/FirmwareKit/EFI.h b/dev/zka/FirmwareKit/EFI.h new file mode 100644 index 00000000..3097c7b6 --- /dev/null +++ b/dev/zka/FirmwareKit/EFI.h @@ -0,0 +1,11 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +/// @note this header is used to reference the EFI/EFI.h diff --git a/dev/zka/FirmwareKit/EFI.hxx b/dev/zka/FirmwareKit/EFI.hxx deleted file mode 100644 index f099958e..00000000 --- a/dev/zka/FirmwareKit/EFI.hxx +++ /dev/null @@ -1,11 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -/// @note this header is used to reference the EFI/EFI.hxx diff --git a/dev/zka/FirmwareKit/EFI/API.h b/dev/zka/FirmwareKit/EFI/API.h new file mode 100644 index 00000000..12f69033 --- /dev/null +++ b/dev/zka/FirmwareKit/EFI/API.h @@ -0,0 +1,114 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef __EFI_API__ +#define __EFI_API__ + +#include +#include +#include +#include + +#define kZKASubsystem 17 + +#ifdef __NEWOSLDR__ +// forward decl. +class BTextWriter; + +#define __BOOTKIT_NO_INCLUDE__ 1 + +#include +#include +#endif // ifdef __NEWOSLDR__ + +inline EfiSystemTable* ST = nullptr; +inline EfiBootServices* BS = nullptr; + +EXTERN_C void rt_cli(); +EXTERN_C void rt_hlt(); + +namespace EFI +{ + /// @brief Halt and clear interrupts. + /// @return + inline Void Stop() noexcept + { + while (1) + { + rt_hlt(); + rt_cli(); + } + } + + /** +@brief Exit EFI API to let the OS load correctly. +Bascially frees everything we have in the EFI side. +*/ + inline void ExitBootServices(UInt64 MapKey, EfiHandlePtr ImageHandle) noexcept + { + if (!ST) + return; + + ST->BootServices->ExitBootServices(ImageHandle, MapKey); + } + + enum + { + kPartEPM, + kPartGPT, + kPartMBR, + kPartCnt, + }; + + inline UInt32 Platform() noexcept + { + return kPeMachineAMD64; + } + + /*** + * @brief Throw an error, stop execution as well. + * @param ErrorCode error code to be print. + * @param Reason reason to be print. + */ + inline void ThrowError(const EfiCharType* ErrorCode, + const EfiCharType* Reason) noexcept + { + ST->ConOut->OutputString(ST->ConOut, L"\r*** STOP ***\r"); + + ST->ConOut->OutputString(ST->ConOut, L"*** Error: "); + ST->ConOut->OutputString(ST->ConOut, ErrorCode); + + ST->ConOut->OutputString(ST->ConOut, L", Reason: "); + ST->ConOut->OutputString(ST->ConOut, Reason); + + ST->ConOut->OutputString(ST->ConOut, L" ***\r"); + + EFI::Stop(); + } +} // namespace EFI + +inline void InitEFI(EfiSystemTable* SystemTable) noexcept +{ + if (!SystemTable) + return; + + ST = SystemTable; + BS = ST->BootServices; + + ST->ConOut->ClearScreen(SystemTable->ConOut); + ST->ConOut->SetAttribute(SystemTable->ConOut, kEFIYellow); + + ST->BootServices->SetWatchdogTimer(0, 0, 0, nullptr); + ST->ConOut->EnableCursor(ST->ConOut, false); +} + +#ifdef __NEWOSLDR__ + +#include + +#endif // ifdef __NEWOSLDR__ + +#endif /* ifndef __EFI_API__ */ diff --git a/dev/zka/FirmwareKit/EFI/API.hxx b/dev/zka/FirmwareKit/EFI/API.hxx deleted file mode 100644 index 42df38d6..00000000 --- a/dev/zka/FirmwareKit/EFI/API.hxx +++ /dev/null @@ -1,114 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef __EFI_API__ -#define __EFI_API__ - -#include -#include -#include -#include - -#define kZKASubsystem 17 - -#ifdef __NEWOSLDR__ -// forward decl. -class BTextWriter; - -#define __BOOTKIT_NO_INCLUDE__ 1 - -#include -#include -#endif // ifdef __NEWOSLDR__ - -inline EfiSystemTable* ST = nullptr; -inline EfiBootServices* BS = nullptr; - -EXTERN_C void rt_cli(); -EXTERN_C void rt_hlt(); - -namespace EFI -{ - /// @brief Halt and clear interrupts. - /// @return - inline Void Stop() noexcept - { - while (1) - { - rt_hlt(); - rt_cli(); - } - } - - /** -@brief Exit EFI API to let the OS load correctly. -Bascially frees everything we have in the EFI side. -*/ - inline void ExitBootServices(UInt64 MapKey, EfiHandlePtr ImageHandle) noexcept - { - if (!ST) - return; - - ST->BootServices->ExitBootServices(ImageHandle, MapKey); - } - - enum - { - kPartEPM, - kPartGPT, - kPartMBR, - kPartCnt, - }; - - inline UInt32 Platform() noexcept - { - return kPeMachineAMD64; - } - - /*** - * @brief Throw an error, stop execution as well. - * @param ErrorCode error code to be print. - * @param Reason reason to be print. - */ - inline void ThrowError(const EfiCharType* ErrorCode, - const EfiCharType* Reason) noexcept - { - ST->ConOut->OutputString(ST->ConOut, L"\r*** STOP ***\r"); - - ST->ConOut->OutputString(ST->ConOut, L"*** Error: "); - ST->ConOut->OutputString(ST->ConOut, ErrorCode); - - ST->ConOut->OutputString(ST->ConOut, L", Reason: "); - ST->ConOut->OutputString(ST->ConOut, Reason); - - ST->ConOut->OutputString(ST->ConOut, L" ***\r"); - - EFI::Stop(); - } -} // namespace EFI - -inline void InitEFI(EfiSystemTable* SystemTable) noexcept -{ - if (!SystemTable) - return; - - ST = SystemTable; - BS = ST->BootServices; - - ST->ConOut->ClearScreen(SystemTable->ConOut); - ST->ConOut->SetAttribute(SystemTable->ConOut, kEFIYellow); - - ST->BootServices->SetWatchdogTimer(0, 0, 0, nullptr); - ST->ConOut->EnableCursor(ST->ConOut, false); -} - -#ifdef __NEWOSLDR__ - -#include - -#endif // ifdef __NEWOSLDR__ - -#endif /* ifndef __EFI_API__ */ diff --git a/dev/zka/FirmwareKit/EFI/EFI.h b/dev/zka/FirmwareKit/EFI/EFI.h new file mode 100644 index 00000000..46d3083e --- /dev/null +++ b/dev/zka/FirmwareKit/EFI/EFI.h @@ -0,0 +1,883 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef __EFI__ +#define __EFI__ + +/** +@brief Kernel Implementation of EFI. +@note This API is in WiP, so it's not 'pretty', just deal with it. We'll be +improving that later. +@author Amlal El Mahrouss +*/ + +#include + +using namespace Kernel; + +/* we always use stdcall in EFI, the pascal way of calling functions. */ + +#ifndef EPI_API +#define EFI_API __attribute__((ms_abi)) +#endif // ifndef EPI_API + +#define IN +#define OUT +#define OPTIONAL + +// Forward decls + +struct EfiTableHeader; +struct EfiLoadFileProtocol; +struct EfiSimpleTextOutputProtocol; +struct EfiDevicePathProtocol; +struct EfiBootServices; +struct EfiMemoryDescriptor; +struct EfiSystemTable; +struct EfiGUID; +struct EfiFileDevicePathProtocol; +struct EfiHandle; +struct EfiGraphicsOutputProtocol; +struct EfiBitmask; +struct EfiFileProtocol; + +typedef UInt64 EfiStatusType; + +/// @brief Core Handle Kind +/// This is like NT's Win32 HANDLE type. +typedef struct EfiHandle +{ +} * EfiHandlePtr; + +/* UEFI uses wide characters by default. */ +typedef WideChar EfiCharType; + +typedef UInt64 EfiPhysicalAddress; +typedef UIntPtr EfiVirtualAddress; + +/// What's BootBolicy? +/// If TRUE, indicates that the request originates from the boot manager, and +/// that the boot manager is attempting to load FilePath as a boot selection. If +/// FALSE, then FilePath must match an exact file to be loaded. + +typedef UInt64(EFI_API* EfiTextString)(struct EfiSimpleTextOutputProtocol* This, + const WideChar* OutputString); + +typedef UInt64(EFI_API* EfiTextAttrib)(struct EfiSimpleTextOutputProtocol* This, + const WideChar Attribute); + +typedef UInt64(EFI_API* EfiTextClear)(struct EfiSimpleTextOutputProtocol* This); + +typedef UInt64(EFI_API* EfiLoadFile)(EfiLoadFileProtocol* This, + EfiFileDevicePathProtocol* FilePath, + Boolean BootPolicy, + UInt32* BufferSize, + VoidPtr Buffer); + +typedef UInt64(EFI_API* EfiCopyMem)(VoidPtr DstBuf, VoidPtr SrcBuf, SizeT Length); +typedef UInt64(EFI_API* EfiSetMem)(VoidPtr DstBuf, Char Byte, SizeT Length); + +typedef UInt64(EFI_API* EfiHandleProtocol)(EfiHandlePtr Handle, EfiGUID* Guid, VoidPtr* Device); + +typedef UInt64(EFI_API* EfiLocateDevicePath)(EfiGUID* Protocol, + EfiDevicePathProtocol** DevicePath, + EfiHandlePtr Device); + +typedef UInt64(EFI_API* EfiStartImage)(EfiHandlePtr Handle, VoidPtr ArgsSize, VoidPtr ArgsPtr); + +typedef UInt64(EFI_API* EfiLoadImage)(Boolean BootPolicy, + EfiHandlePtr ParentHandle, + EfiFileDevicePathProtocol* DeviceFile, + VoidPtr buffer, + SizeT size, + EfiHandlePtr* ppHandle); + +/// EFI pool helpers, taken from iPXE. + +typedef enum EfiMemoryType +{ + /// + /// Not used. + /// + EfiReservedMemoryType, + /// + /// The code portions of a loaded application. + /// (Note that UEFI OS loaders are UEFI applications.) + /// + EfiLoaderCode, + /// + /// The data portions of a loaded application and the default data allocation + /// type used by an application to allocate pool memory. + /// + EfiLoaderData, + /// + /// The code portions of a loaded Boot Services Driver. + /// + EfiBootServicesCode, + /// + /// The data portions of a loaded Boot Serves Driver, and the default data + /// allocation type used by a Boot Services Driver to allocate pool memory. + /// + EfiBootServicesData, + /// + /// The code portions of a loaded Runtime Services Driver. + /// + EfiRuntimeServicesCode, + /// + /// The data portions of a loaded Runtime Services Driver and the default + /// data allocation type used by a Runtime Services Driver to allocate pool + /// memory. + /// + EfiRuntimeServicesData, + /// + /// Free (unallocated) memory. + /// + EfiConventionalMemory, + /// + /// Memory in which errors have been detected. + /// + EfiUnusableMemory, + /// + /// Memory that holds the ACPI tables. + /// + EfiACPIReclaimMemory, + /// + /// Address space reserved for use by the firmware. + /// + EfiACPIMemoryNVS, + /// + /// Used by system firmware to request that a memory-mapped IO region + /// be mapped by the OS to a virtual address so it can be accessed by EFI + /// runtime services. + /// + EfiMemoryMappedIO, + /// + /// System memory-mapped IO region that is used to translate memory + /// cycles to IO cycles by the processor. + /// + EfiMemoryMappedIOPortSpace, + /// + /// Address space reserved by the firmware for code that is part of the + /// processor. + /// + EfiPalCode, + /// + /// A memory region that operates as EfiConventionalMemory, + /// however it happens to also support byte-addressable non-volatility. + /// + EfiPersistentMemory, + /// + /// A memory region that describes system memory that has not been accepted + /// by a corresponding call to the underlying isolation architecture. + /// + EfiUnacceptedMemoryType, + /// + /// The last type of memory. + /// Not a real type. + /// + EfiMaxMemoryType, +} EfiMemoryType; + +typedef enum EfiAllocateType +{ + /// Anything that satisfy the request. + AllocateAnyPages, + AllocateMaxAddress, + /// + /// Allocate pages at a specified address. + /// + AllocateAddress, + /// + /// Maximum enumeration value that may be used for bounds checking. + /// + MaxAllocateType +} EfiAllocateType; + +typedef struct EfiMemoryDescriptor +{ + /// + /// Kind of the memory region. + /// Kind EFI_MEMORY_TYPE is defined in the + /// AllocatePages() function description. + /// + UInt32 Kind; + /// + /// Physical address of the first byte in the memory region. PhysicalStart + /// must be aligned on a 4 KiB boundary, and must not be above + /// 0xfffffffffffff000. Kind EFI_PHYSICAL_ADDRESS is defined in the + /// AllocatePages() function description + /// + EfiPhysicalAddress PhysicalStart; + /// + /// Virtual address of the first byte in the memory region. + /// VirtualStart must be aligned on a 4 KiB boundary, + /// and must not be above 0xfffffffffffff000. + /// + EfiVirtualAddress VirtualStart; + /// + /// NumberOfPagesNumber of 4 KiB pages in the memory region. + /// NumberOfPages must not be 0, and must not be any value + /// that would represent a memory page with a start address, + /// either physical or virtual, above 0xfffffffffffff000. + /// + UInt64 NumberOfPages; + /// + /// Attributes of the memory region that describe the bit mask of capabilities + /// for that memory region, and not necessarily the current settings for that + /// memory region. + /// + UInt64 Attribute; +} EfiMemoryDescriptor; + +typedef UInt64(EFI_API* EfiAllocatePool)(EfiMemoryType PoolType, UInt32 Size, VoidPtr* Buffer); + +typedef UInt64(EFI_API* EfiFreePool)(VoidPtr Buffer); + +typedef UInt64(EFI_API* EfiCalculateCrc32)(VoidPtr Data, UInt32 DataSize, UInt32* CrcOut); + +/** +@brief Present in every header, used to identify a UEFI structure. +*/ +typedef struct EfiTableHeader +{ + UInt64 Signature; + UInt32 Revision; + UInt32 HeaderSize; + UInt32 Crc32; + UInt32 Reserved; +} EfiTableHeader; + +#define EFI_ACPI_TABLE_PROTOCOL_GUID \ + { \ + 0xffe06bdd, 0x6107, 0x46a6, \ + { \ + 0x7b, 0xb2, 0x5a, 0x9c, 0x7e, 0xc5, 0x27, 0x5c \ + } \ + } + +#define EFI_LOAD_FILE_PROTOCOL_GUID \ + { \ + 0x56EC3091, 0x954C, 0x11d2, \ + { \ + 0x8e, 0x3f, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b \ + } \ + } + +#define EFI_LOAD_FILE2_PROTOCOL_GUID \ + { \ + 0x4006c0c1, 0xfcb3, 0x403e, \ + { \ + 0x99, 0x6d, 0x4a, 0x6c, 0x87, 0x24, 0xe0, 0x6d \ + } \ + } + +#define EFI_LOADED_IMAGE_PROTOCOL_GUID \ + { \ + 0x5B1B31A1, 0x9562, 0x11d2, \ + { \ + 0x8E, 0x3F, 0x00, 0xA0, 0xC9, 0x69, 0x72, 0x3B \ + } \ + } + +#define EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID \ + { \ + 0x9042a9de, 0x23dc, 0x4a38, \ + { \ + 0x96, 0xfb, 0x7a, 0xde, 0xd0, 0x80, 0x51, 0x6a \ + } \ + } + +#define EFI_LOADED_IMAGE_PROTOCOL_REVISION 0x1000 + +#define EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID \ + { \ + 0x0964e5b22, 0x6459, 0x11d2, \ + { \ + 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b \ + } \ + } + +#define EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID \ + { \ + 0xbc62157e, 0x3e33, 0x4fec, \ + { \ + 0x99, 0x20, 0x2d, 0x3b, 0x36, 0xd7, 0x50, 0xdf \ + } \ + } + +#define EFI_DEVICE_PATH_PROTOCOL_GUID \ + { \ + 0x9576e91, 0x6d3f, 0x11d2, \ + { \ + 0x8e, 0x39, 0x0, 0xa0, 0xc9, 0x69, 0x72, 0x3b \ + } \ + } + +#define EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID \ + { \ + 0x0964e5b22, 0x6459, 0x11d2, \ + { \ + 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b \ + } \ + } + +typedef UInt64(EfiImageUnload)(EfiHandlePtr ImageHandle); + +enum +{ + kPixelRedGreenBlueReserved8BitPerColor, + kPixelBlueGreenRedReserved8BitPerColor, + kPixelBitMask, + kPixelBltOnly, + kPixelFormatMax +}; + +typedef struct EfiBitmask +{ + UInt32 RedMask; + UInt32 GreenMask; + UInt32 BlueMask; + UInt32 ReservedMask; +} EfiBitmask; + +typedef struct +{ + UInt8 Blue; + UInt8 Green; + UInt8 Red; + UInt8 Reserved; +} EfiGraphicsOutputBltPixel; + +typedef enum EfiGraphicsOutputProtocolBltOperation +{ + EfiBltVideoFill, + EfiBltVideoToBltBuffer, + EfiBltBufferToVideo, + EfiBltVideoToVideo, + EfiGraphicsOutputBltOperationMax +} EfiGraphicsOutputProtocolBltOperation; + +typedef struct EfiGraphicsOutputProtocolModeInformation +{ + UInt32 Version; + UInt32 HorizontalResolution; + UInt32 VerticalResolution; + UInt32 PixelFormat; + EfiBitmask PixelInformation; + UInt32 PixelsPerScanLine; +} EfiGraphicsOutputProtocolModeInformation; + +typedef UInt64(EFI_API* EfiGraphicsOutputProtocolQueryMode)( + EfiGraphicsOutputProtocol* This, UInt32 ModeNumber, UInt32* SizeOfInfo, EfiGraphicsOutputProtocolModeInformation** Info); + +typedef UInt64(EFI_API* EfiGraphicsOutputProtocolSetMode)( + EfiGraphicsOutputProtocol* This, UInt32 ModeNumber); + +typedef UInt64(EFI_API* EfiGraphicsOutputProtocolBlt)( + EfiGraphicsOutputProtocol* This, EfiGraphicsOutputBltPixel* BltBuffer, EfiGraphicsOutputProtocolBltOperation BltOperation, UInt32 SourceX, UInt32 SourceY, UInt32 DestinationX, UInt32 DestinationY, UInt32 Width, UInt32 Height, UInt32 Delta); + +typedef struct +{ + UInt32 MaxMode; + UInt32 Mode; + EfiGraphicsOutputProtocolModeInformation* Info; + UInt32 SizeOfInfo; + UIntPtr FrameBufferBase; + UInt32 FrameBufferSize; +} EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE; + +typedef struct EfiGraphicsOutputProtocol +{ + EfiGraphicsOutputProtocolQueryMode QueryMode; + EfiGraphicsOutputProtocolSetMode SetMode; + EfiGraphicsOutputProtocolBlt Blt; + EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE* Mode; +} EfiGraphicsOutputProtocol; + +typedef struct EfiLoadImageProtocol +{ + UInt32 Revision; + EfiHandlePtr ParentHandle; + EfiSystemTable* SystemTable; + + // Source location of the image + EfiHandlePtr DeviceHandle; + EfiDevicePathProtocol* FilePath; + Void* Reserved; + + // Image’s load options + UInt32 LoadOptionsSize; + Void* LoadOptions; + + // Location where image was loaded + Void* ImageBase; + UInt64 ImageSize; + EfiMemoryType ImageCodeType; + EfiMemoryType ImageDataType; + EfiImageUnload Unload; +} EfiLoadImageProtocol; + +typedef struct EfiLoadFileProtocol +{ + EfiLoadFile LoadFile; +} EfiLoadFileProtocol; + +typedef struct EfiDevicePathProtocol +{ + UInt8 Kind; + UInt8 SubType; + UInt8 Length[2]; +} EfiDevicePathProtocol; + +typedef struct EfiFileDevicePathProtocol +{ + EfiDevicePathProtocol Proto; + + /// + /// File Path of this struct + /// + WideChar Path[kPathLen]; +} EfiFileDevicePathProtocol; + +typedef UInt64(EFI_API* EfiExitBootServices)(VoidPtr ImageHandle, + UInt32 MapKey); + +typedef UInt64(EFI_API* EfiAllocatePages)(EfiAllocateType AllocType, + EfiMemoryType MemType, + UInt32 Count, + EfiPhysicalAddress* Memory); + +typedef UInt64(EFI_API* EfiFreePages)(EfiPhysicalAddress* Memory, UInt32 Pages); + +typedef UInt64(EFI_API* EfiGetMemoryMap)(UInt32* MapSize, + EfiMemoryDescriptor* DescPtr, + UInt32* MapKey, + UInt32* DescSize, + UInt32* DescVersion); + +/** + * @brief GUID type, something you can also find in CFKit. + */ +typedef struct EfiGUID final +{ + UInt32 Data1; + UInt16 Data2; + UInt16 Data3; + UInt8 Data4[8]; +} EfiGUID; + +/*** + * Protocol stuff... + */ + +/** some helpers */ +#define EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL 0x00000001 +#define EFI_OPEN_PROTOCOL_GET_PROTOCOL 0x00000002 +#define EFI_OPEN_PROTOCOL_TEST_PROTOCOL 0x00000004 +#define EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER 0x00000008 +#define EFI_OPEN_PROTOCOL_BY_DRIVER 0x00000010 +#define EFI_OPEN_PROTOCOL_EXCLUSIVE 0x00000020 + +typedef UInt64(EFI_API* EfiLocateProtocol)(EfiGUID* Protocol, + VoidPtr Registration, + VoidPtr* Interface); + +typedef UInt64(EFI_API* EfiOpenProtocol)(EfiHandlePtr Handle, EfiGUID* Guid, VoidPtr* Interface, EfiHandlePtr AgentHandle, EfiHandlePtr ControllerHandle, UInt32 Attributes); + +typedef UInt64(EFI_API* EfiEnableCursor)(EfiSimpleTextOutputProtocol* This, Boolean Visible); + +/** +@name EfiBootServices +@brief UEFI Boot Services record, it contains functions necessary to a +firmware level application. +*/ +typedef struct EfiBootServices +{ + EfiTableHeader SystemTable; + VoidPtr RaiseTPL; + VoidPtr RestoreTPL; + EfiAllocatePages AllocatePages; + EfiFreePages FreePages; + EfiGetMemoryMap GetMemoryMap; + EfiAllocatePool AllocatePool; + EfiFreePool FreePool; + VoidPtr CreateEvent; + VoidPtr SetTimer; + VoidPtr WaitForEvent; + VoidPtr SignalEvent; + VoidPtr CloseEvent; + VoidPtr CheckEvent; + VoidPtr InstallProtocolInterface; + VoidPtr ReinstallProtocolInterface; + VoidPtr UninstallProtocolInterface; + EfiHandleProtocol HandleProtocol; + VoidPtr Reserved; + VoidPtr RegisterProtocolNotify; + VoidPtr LocateHandle; + EfiLocateDevicePath LocateDevicePath; + VoidPtr InstallConfigurationTable; + EfiLoadImage LoadImage; + EfiStartImage StartImage; + VoidPtr Exit; + VoidPtr UnloadImage; + EfiExitBootServices ExitBootServices; + VoidPtr GetNextMonotonicCount; + VoidPtr Stall; + EfiStatusType(EFI_API* SetWatchdogTimer)(UInt32 Timeout, UInt64 WatchdogCode, UInt32 DataSize, EfiCharType* Data); + VoidPtr ConnectController; + VoidPtr DisconnectController; + EfiOpenProtocol OpenProtocol; + VoidPtr CloseProtocol; + VoidPtr OpenProtocolInformation; + VoidPtr ProtocolsPerHandle; + VoidPtr LocateHandleBuffer; + EfiLocateProtocol LocateProtocol; + VoidPtr InstallMultipleProtocolInterfaces; + VoidPtr UninstallMultipleProtocolInterfaces; + EfiCalculateCrc32 CalculateCrc32; + EfiCopyMem CopyMem; + EfiSetMem SetMem; + VoidPtr CreateEventEx; +} EfiBootServices; + +#define kEntireDevPath 0xFF +#define kThisInstancePath 0x01 + +/** +@brief PrintF like protocol. +*/ +typedef struct EfiSimpleTextOutputProtocol +{ + VoidPtr Reset; + EfiTextString OutputString; + VoidPtr TestString; + VoidPtr QueryMode; + VoidPtr SetMode; + EfiTextAttrib SetAttribute; + EfiTextClear ClearScreen; + VoidPtr SetCursorPosition; + EfiEnableCursor EnableCursor; + VoidPtr Mode; +} EfiSimpleTextOutputProtocol; + +typedef UInt64(EFI_API* EfiOpenVolume)(struct EfiSimpleFilesystemProtocol*, + struct EfiFileProtocol**); + +struct EfiSimpleFilesystemProtocol +{ + UInt64 Revision; + EfiOpenVolume OpenVolume; +}; + +/** +@brief The Structure that they give you when booting. +*/ +typedef struct EfiSystemTable +{ + EfiTableHeader SystemHeader; + WideChar* FirmwareVendor; + UInt32 FirmwareRevision; + EfiHandlePtr ConsoleInHandle; + VoidPtr ConIn; + EfiHandlePtr ConsoleOutHandle; + EfiSimpleTextOutputProtocol* ConOut; + EfiHandlePtr StandardErrorHandle; + VoidPtr StdErr; + VoidPtr RuntimeServices; + EfiBootServices* BootServices; + UInt64 NumberOfTableEntries; + struct + { + EfiGUID VendorGUID; + VoidPtr VendorTable; + } * ConfigurationTable; +} EfiSystemTable; + +#define kEfiOk 0 +#define kEfiFail -1 +#define kBufferTooSmall 5 + +#define EFI_EXTERN_C extern "C" + +typedef struct EfiIPV4 +{ + UInt8 Addr[4]; +} EfiIPV4; + +/// +/// 16-byte buffer. An IPv6 internet protocol address. +/// +typedef struct EfiIPV6 +{ + UInt8 Addr[16]; +} EfiIPV6; + +#define kEFIYellow (0x01 | 0x02 | 0x04 | 0x08) + +#ifdef __x86_64 +#define __EFI_x86_64__ 1 +#endif // __x86_64 + +enum +{ + kEFIHwDevicePath = 0x01, + kEFIAcpiDevicePath = 0x02, + kEFIMessaingDevicePath = 0x03, + kEFIMediaDevicePath = 0x04, + kEFIBiosBootPath = 0x05, + kEFIEndOfPath = 0x06, + kEFICount = 6, +}; + +#define END_DEVICE_PATH_TYPE 0x7f +#define END_ENTIRE_DEVICE_PATH_SUBTYPE 0xFF +#define END_INSTANCE_DEVICE_PATH_SUBTYPE 0x01 + +#define kEfiOffsetOf(T, F) __builtin_offsetof(T, F) + +/// File I/O macros + +#define kEFIFileRead 0x0000000000000001 +#define kEFIFileWrite 0x0000000000000002 +#define kEFIFileCreate 0x0000000000000000 + +#define kEFIReadOnly 0x01 +#define kEFIHidden 0x02 +#define kEFISystem 0x04 +#define kEFIReserved 0x08 +#define kEFIDirectory 0x10 +#define kEFIArchive 0x20 + +typedef struct EfiIOToken +{ + // + // If Event is NULL, then blocking I/O is performed. + // If Event is not NULL and non-blocking I/O is supported, then non-blocking + // I/O is performed, and Event will be signaled when the read request is + // completed. The caller must be prepared to handle the case where the + // callback associated with Event occurs before the original asynchronous I/O + // request call returns. + // + UInt64 Event; + + // + // Defines whether or not the signaled event encountered an error. + // + UInt64 Status; + + // + // For OpenEx(): Not Used, ignored. + // For ReadEx(): On input, the size of the Buffer. On output, the amount of + // data returned in Buffer. + // In both cases, the size is measured in bytes. + // For WriteEx(): On input, the size of the Buffer. On output, the amount of + // data actually written. + // In both cases, the size is measured in bytes. + // For FlushEx(): Not used, ignored. + // + UInt32 BufferSize; + + // + // For OpenEx(): Not Used, ignored. + // For ReadEx(): The buffer into which the data is read. + // For WriteEx(): The buffer of data to write. + // For FlushEx(): Not Used, ignored. + // + Void* Buffer; +} EfiIOToken; + +typedef struct EfiFileProtocol +{ + UInt64 Revision; + + EfiStatusType(EFI_API* Open)(struct EfiFileProtocol* This, + struct EfiFileProtocol** Out, + EfiCharType* CharType, + UInt64 OpenMode, + UInt64 Attrib); + + EfiStatusType(EFI_API* Close)(struct EfiFileProtocol* This); + + EfiStatusType(EFI_API* Delete)(struct EfiFileProtocol* This); + + EfiStatusType(EFI_API* Read)(struct EfiFileProtocol* This, UInt64* BufSize, VoidPtr BufOut); + + EfiStatusType(EFI_API* Write)(struct EfiFileProtocol* This, UInt64* BufSize, VoidPtr BufOut); + + EfiStatusType(EFI_API* GetPosition)(EfiFileProtocol* This, UInt64* Position); + + EfiStatusType(EFI_API* SetPosition)(EfiFileProtocol* This, UInt64* Position); + + EfiStatusType(EFI_API* GetInfo)(struct EfiFileProtocol*, struct EfiGUID*, UInt32*, void*); + + EfiStatusType(EFI_API* SetInfo)(struct EfiFileProtocol*, struct EfiGUID*, UInt32*, void*); + + EfiStatusType(EFI_API* Flush)(EfiFileProtocol*); + + EfiStatusType(EFI_API* OpenEx)(EfiFileProtocol* This, + EfiFileProtocol** OutHandle, + EfiCharType* Path, + UInt64 Mode, + UInt64 Attrib, + struct EfiIOToken* Token); + + EfiStatusType(EFI_API* ReadEx)(EfiFileProtocol* This, + struct EfiIOToken* Token); + + EfiStatusType(EFI_API* WriteEx)(EfiFileProtocol* This, + struct EfiIOToken* Token); + + EfiStatusType(EFI_API* FlushEx)(EfiFileProtocol* This, + struct EfiIOToken* Token); +} EfiFileProtocol, *EfiFileProtocolPtr; + +typedef UInt64 EfiCursorType; + +typedef struct EfiTime +{ + UInt16 Year; + UInt8 Month; + UInt8 Day; + UInt8 Hour; + UInt8 Minute; + UInt8 Second; + UInt8 Pad1; + UInt32 Nanosecond; + Int16 TimeZone; + UInt8 Daylight; + UInt8 Pad2; +} EfiTime; + +#define EFI_FILE_INFO_GUID \ + { \ + 0x09576e92, 0x6d3f, 0x11d2, \ + { \ + 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b \ + } \ + } + +struct EfiFileInfo final +{ + /// @brief Structure size. + UInt64 Size; + /// @brief File size. + UInt64 FileSize; + /// @brief Physical size on disk. + UInt64 PhysicalSize; + /// @brief Create time. + EfiTime CreateTime; + /// @brief Last access time. + EfiTime LastAccessTime; + /// @brief Edit time. + EfiTime EditTime; + /// @brief Attributes. + UInt64 Attribute; + /// @brief VLA file name. + WideChar FileName[1]; +}; + +#define EFI_FILE_PROTOCOL_REVISION 0x00010000 +#define EFI_FILE_PROTOCOL_REVISION2 0x00020000 +#define EFI_FILE_PROTOCOL_LATEST_REVISION EFI_FILE_PROTOCOL_REVISION2 + +#define EFI_EXTRA_DESCRIPTOR_SIZE 8 + +#define EFI_MP_SERVICES_PROTOCOL_GUID \ + { \ + 0x3fdda605, 0xa76e, 0x4f46, \ + { \ + 0xad, 0x29, 0x12, 0xf4, \ + 0x53, 0x1b, 0x3d, 0x08 \ + } \ + } + +//******************************************************* +// EFI_CPU_PHYSICAL_LOCATION +// @note As in the EFI specs. +//******************************************************* +typedef struct _EfiCPUPhyiscalLocation +{ + UInt32 Package; + UInt32 Core; + UInt32 Thread; +} EfiCPUPhyiscalLocation; + +typedef union _EfiExtendedProcessorInformation { + EfiCPUPhyiscalLocation Location2; +} EfiExtendedProcessorInformation; + +typedef struct _EfiProcessorInformation +{ + UInt64 ProcessorId; + UInt32 StatusFlag; + EfiCPUPhyiscalLocation Location; + EfiExtendedProcessorInformation ExtendedInformation; +} EfiProcessorInformation; + +#define PROCESSOR_AS_BSP_BIT 0x00000001 +#define PROCESSOR_ENABLED_BIT 0x00000002 +#define PROCESSOR_HEALTH_STATUS_BIT 0x00000004 + +typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_GET_NUMBER_OF_PROCESSORS)( + IN struct _EfiMpServicesProtocol* Self, + OUT UInt32* NumberOfProcessors, + OUT UInt32* NumberOfEnabledProcessors); + +typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_GET_PROCESSOR_INFO)( + IN struct _EfiMpServicesProtocol* Self, + IN UInt32* ProcessorNumber, + OUT struct _EfiProcessorInformation* NumberOfEnabledProcessors); + +#define END_OF_CPU_LIST 0xffffffff + +typedef void EFI_API (*EFI_AP_PROCEDURE)( + IN VoidPtr ProcedureArgument); + +typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_STARTUP_ALL_APS)( + IN struct _EfiMpServicesProtocol* This, + IN EFI_AP_PROCEDURE Procedure, + IN Boolean SingleThread, + IN VoidPtr WaitEvent OPTIONAL, // EFI_EVENT first, but unused here. + IN UInt32 TimeoutInMicroSeconds, + IN Void* ProcedureArgument OPTIONAL, + OUT UInt32** FailedCpuList OPTIONAL); + +typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_SWITCH_BSP)( + IN struct _EfiMpServicesProtocol* This, + IN UInt32 ProcessorNumber, + IN Boolean EnableOldBSP); + +typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_STARTUP_THIS_AP)( + IN struct _EfiMpServicesProtocol* This, + IN EFI_AP_PROCEDURE Procedure, + IN UInt32 ProcessorNumber, + IN VoidPtr WaitEvent OPTIONAL, + IN UInt32 TimeoutInMicroseconds, + IN Void* ProcedureArgument OPTIONAL, + OUT Boolean* Finished OPTIONAL); + +typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_ENABLEDISABLEAP)( + IN struct _EfiMpServicesProtocol* This, + IN UInt32 ProcessorNumber, + IN Boolean EnableAP, + IN UInt32* HealthFlag OPTIONAL); + +typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_WHOAMI)( + IN struct _EfiMpServicesProtocol* This, + OUT UInt32* ProcessorNumber); + +typedef struct _EfiMpServicesProtocol +{ + EFI_MP_SERVICES_GET_NUMBER_OF_PROCESSORS GetNumberOfProcessors; + EFI_MP_SERVICES_GET_PROCESSOR_INFO GetProcessorInfo; + EFI_MP_SERVICES_STARTUP_ALL_APS StartupAllAPs; + EFI_MP_SERVICES_STARTUP_THIS_AP StartupThisAP; + EFI_MP_SERVICES_SWITCH_BSP SwitchBSP; + EFI_MP_SERVICES_ENABLEDISABLEAP EnableDisableAP; + EFI_MP_SERVICES_WHOAMI WhoAmI; +} EfiMpServicesProtocol; + +#endif // ifndef __EFI__ diff --git a/dev/zka/FirmwareKit/EFI/EFI.hxx b/dev/zka/FirmwareKit/EFI/EFI.hxx deleted file mode 100644 index 75438014..00000000 --- a/dev/zka/FirmwareKit/EFI/EFI.hxx +++ /dev/null @@ -1,883 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef __EFI__ -#define __EFI__ - -/** -@brief Kernel Implementation of EFI. -@note This API is in WiP, so it's not 'pretty', just deal with it. We'll be -improving that later. -@author Amlal El Mahrouss -*/ - -#include - -using namespace Kernel; - -/* we always use stdcall in EFI, the pascal way of calling functions. */ - -#ifndef EPI_API -#define EFI_API __attribute__((ms_abi)) -#endif // ifndef EPI_API - -#define IN -#define OUT -#define OPTIONAL - -// Forward decls - -struct EfiTableHeader; -struct EfiLoadFileProtocol; -struct EfiSimpleTextOutputProtocol; -struct EfiDevicePathProtocol; -struct EfiBootServices; -struct EfiMemoryDescriptor; -struct EfiSystemTable; -struct EfiGUID; -struct EfiFileDevicePathProtocol; -struct EfiHandle; -struct EfiGraphicsOutputProtocol; -struct EfiBitmask; -struct EfiFileProtocol; - -typedef UInt64 EfiStatusType; - -/// @brief Core Handle Kind -/// This is like NT's Win32 HANDLE type. -typedef struct EfiHandle -{ -} * EfiHandlePtr; - -/* UEFI uses wide characters by default. */ -typedef WideChar EfiCharType; - -typedef UInt64 EfiPhysicalAddress; -typedef UIntPtr EfiVirtualAddress; - -/// What's BootBolicy? -/// If TRUE, indicates that the request originates from the boot manager, and -/// that the boot manager is attempting to load FilePath as a boot selection. If -/// FALSE, then FilePath must match an exact file to be loaded. - -typedef UInt64(EFI_API* EfiTextString)(struct EfiSimpleTextOutputProtocol* This, - const WideChar* OutputString); - -typedef UInt64(EFI_API* EfiTextAttrib)(struct EfiSimpleTextOutputProtocol* This, - const WideChar Attribute); - -typedef UInt64(EFI_API* EfiTextClear)(struct EfiSimpleTextOutputProtocol* This); - -typedef UInt64(EFI_API* EfiLoadFile)(EfiLoadFileProtocol* This, - EfiFileDevicePathProtocol* FilePath, - Boolean BootPolicy, - UInt32* BufferSize, - VoidPtr Buffer); - -typedef UInt64(EFI_API* EfiCopyMem)(VoidPtr DstBuf, VoidPtr SrcBuf, SizeT Length); -typedef UInt64(EFI_API* EfiSetMem)(VoidPtr DstBuf, Char Byte, SizeT Length); - -typedef UInt64(EFI_API* EfiHandleProtocol)(EfiHandlePtr Handle, EfiGUID* Guid, VoidPtr* Device); - -typedef UInt64(EFI_API* EfiLocateDevicePath)(EfiGUID* Protocol, - EfiDevicePathProtocol** DevicePath, - EfiHandlePtr Device); - -typedef UInt64(EFI_API* EfiStartImage)(EfiHandlePtr Handle, VoidPtr ArgsSize, VoidPtr ArgsPtr); - -typedef UInt64(EFI_API* EfiLoadImage)(Boolean BootPolicy, - EfiHandlePtr ParentHandle, - EfiFileDevicePathProtocol* DeviceFile, - VoidPtr buffer, - SizeT size, - EfiHandlePtr* ppHandle); - -/// EFI pool helpers, taken from iPXE. - -typedef enum EfiMemoryType -{ - /// - /// Not used. - /// - EfiReservedMemoryType, - /// - /// The code portions of a loaded application. - /// (Note that UEFI OS loaders are UEFI applications.) - /// - EfiLoaderCode, - /// - /// The data portions of a loaded application and the default data allocation - /// type used by an application to allocate pool memory. - /// - EfiLoaderData, - /// - /// The code portions of a loaded Boot Services Driver. - /// - EfiBootServicesCode, - /// - /// The data portions of a loaded Boot Serves Driver, and the default data - /// allocation type used by a Boot Services Driver to allocate pool memory. - /// - EfiBootServicesData, - /// - /// The code portions of a loaded Runtime Services Driver. - /// - EfiRuntimeServicesCode, - /// - /// The data portions of a loaded Runtime Services Driver and the default - /// data allocation type used by a Runtime Services Driver to allocate pool - /// memory. - /// - EfiRuntimeServicesData, - /// - /// Free (unallocated) memory. - /// - EfiConventionalMemory, - /// - /// Memory in which errors have been detected. - /// - EfiUnusableMemory, - /// - /// Memory that holds the ACPI tables. - /// - EfiACPIReclaimMemory, - /// - /// Address space reserved for use by the firmware. - /// - EfiACPIMemoryNVS, - /// - /// Used by system firmware to request that a memory-mapped IO region - /// be mapped by the OS to a virtual address so it can be accessed by EFI - /// runtime services. - /// - EfiMemoryMappedIO, - /// - /// System memory-mapped IO region that is used to translate memory - /// cycles to IO cycles by the processor. - /// - EfiMemoryMappedIOPortSpace, - /// - /// Address space reserved by the firmware for code that is part of the - /// processor. - /// - EfiPalCode, - /// - /// A memory region that operates as EfiConventionalMemory, - /// however it happens to also support byte-addressable non-volatility. - /// - EfiPersistentMemory, - /// - /// A memory region that describes system memory that has not been accepted - /// by a corresponding call to the underlying isolation architecture. - /// - EfiUnacceptedMemoryType, - /// - /// The last type of memory. - /// Not a real type. - /// - EfiMaxMemoryType, -} EfiMemoryType; - -typedef enum EfiAllocateType -{ - /// Anything that satisfy the request. - AllocateAnyPages, - AllocateMaxAddress, - /// - /// Allocate pages at a specified address. - /// - AllocateAddress, - /// - /// Maximum enumeration value that may be used for bounds checking. - /// - MaxAllocateType -} EfiAllocateType; - -typedef struct EfiMemoryDescriptor -{ - /// - /// Kind of the memory region. - /// Kind EFI_MEMORY_TYPE is defined in the - /// AllocatePages() function description. - /// - UInt32 Kind; - /// - /// Physical address of the first byte in the memory region. PhysicalStart - /// must be aligned on a 4 KiB boundary, and must not be above - /// 0xfffffffffffff000. Kind EFI_PHYSICAL_ADDRESS is defined in the - /// AllocatePages() function description - /// - EfiPhysicalAddress PhysicalStart; - /// - /// Virtual address of the first byte in the memory region. - /// VirtualStart must be aligned on a 4 KiB boundary, - /// and must not be above 0xfffffffffffff000. - /// - EfiVirtualAddress VirtualStart; - /// - /// NumberOfPagesNumber of 4 KiB pages in the memory region. - /// NumberOfPages must not be 0, and must not be any value - /// that would represent a memory page with a start address, - /// either physical or virtual, above 0xfffffffffffff000. - /// - UInt64 NumberOfPages; - /// - /// Attributes of the memory region that describe the bit mask of capabilities - /// for that memory region, and not necessarily the current settings for that - /// memory region. - /// - UInt64 Attribute; -} EfiMemoryDescriptor; - -typedef UInt64(EFI_API* EfiAllocatePool)(EfiMemoryType PoolType, UInt32 Size, VoidPtr* Buffer); - -typedef UInt64(EFI_API* EfiFreePool)(VoidPtr Buffer); - -typedef UInt64(EFI_API* EfiCalculateCrc32)(VoidPtr Data, UInt32 DataSize, UInt32* CrcOut); - -/** -@brief Present in every header, used to identify a UEFI structure. -*/ -typedef struct EfiTableHeader -{ - UInt64 Signature; - UInt32 Revision; - UInt32 HeaderSize; - UInt32 Crc32; - UInt32 Reserved; -} EfiTableHeader; - -#define EFI_ACPI_TABLE_PROTOCOL_GUID \ - { \ - 0xffe06bdd, 0x6107, 0x46a6, \ - { \ - 0x7b, 0xb2, 0x5a, 0x9c, 0x7e, 0xc5, 0x27, 0x5c \ - } \ - } - -#define EFI_LOAD_FILE_PROTOCOL_GUID \ - { \ - 0x56EC3091, 0x954C, 0x11d2, \ - { \ - 0x8e, 0x3f, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b \ - } \ - } - -#define EFI_LOAD_FILE2_PROTOCOL_GUID \ - { \ - 0x4006c0c1, 0xfcb3, 0x403e, \ - { \ - 0x99, 0x6d, 0x4a, 0x6c, 0x87, 0x24, 0xe0, 0x6d \ - } \ - } - -#define EFI_LOADED_IMAGE_PROTOCOL_GUID \ - { \ - 0x5B1B31A1, 0x9562, 0x11d2, \ - { \ - 0x8E, 0x3F, 0x00, 0xA0, 0xC9, 0x69, 0x72, 0x3B \ - } \ - } - -#define EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID \ - { \ - 0x9042a9de, 0x23dc, 0x4a38, \ - { \ - 0x96, 0xfb, 0x7a, 0xde, 0xd0, 0x80, 0x51, 0x6a \ - } \ - } - -#define EFI_LOADED_IMAGE_PROTOCOL_REVISION 0x1000 - -#define EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID \ - { \ - 0x0964e5b22, 0x6459, 0x11d2, \ - { \ - 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b \ - } \ - } - -#define EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID \ - { \ - 0xbc62157e, 0x3e33, 0x4fec, \ - { \ - 0x99, 0x20, 0x2d, 0x3b, 0x36, 0xd7, 0x50, 0xdf \ - } \ - } - -#define EFI_DEVICE_PATH_PROTOCOL_GUID \ - { \ - 0x9576e91, 0x6d3f, 0x11d2, \ - { \ - 0x8e, 0x39, 0x0, 0xa0, 0xc9, 0x69, 0x72, 0x3b \ - } \ - } - -#define EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID \ - { \ - 0x0964e5b22, 0x6459, 0x11d2, \ - { \ - 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b \ - } \ - } - -typedef UInt64(EfiImageUnload)(EfiHandlePtr ImageHandle); - -enum -{ - kPixelRedGreenBlueReserved8BitPerColor, - kPixelBlueGreenRedReserved8BitPerColor, - kPixelBitMask, - kPixelBltOnly, - kPixelFormatMax -}; - -typedef struct EfiBitmask -{ - UInt32 RedMask; - UInt32 GreenMask; - UInt32 BlueMask; - UInt32 ReservedMask; -} EfiBitmask; - -typedef struct -{ - UInt8 Blue; - UInt8 Green; - UInt8 Red; - UInt8 Reserved; -} EfiGraphicsOutputBltPixel; - -typedef enum EfiGraphicsOutputProtocolBltOperation -{ - EfiBltVideoFill, - EfiBltVideoToBltBuffer, - EfiBltBufferToVideo, - EfiBltVideoToVideo, - EfiGraphicsOutputBltOperationMax -} EfiGraphicsOutputProtocolBltOperation; - -typedef struct EfiGraphicsOutputProtocolModeInformation -{ - UInt32 Version; - UInt32 HorizontalResolution; - UInt32 VerticalResolution; - UInt32 PixelFormat; - EfiBitmask PixelInformation; - UInt32 PixelsPerScanLine; -} EfiGraphicsOutputProtocolModeInformation; - -typedef UInt64(EFI_API* EfiGraphicsOutputProtocolQueryMode)( - EfiGraphicsOutputProtocol* This, UInt32 ModeNumber, UInt32* SizeOfInfo, EfiGraphicsOutputProtocolModeInformation** Info); - -typedef UInt64(EFI_API* EfiGraphicsOutputProtocolSetMode)( - EfiGraphicsOutputProtocol* This, UInt32 ModeNumber); - -typedef UInt64(EFI_API* EfiGraphicsOutputProtocolBlt)( - EfiGraphicsOutputProtocol* This, EfiGraphicsOutputBltPixel* BltBuffer, EfiGraphicsOutputProtocolBltOperation BltOperation, UInt32 SourceX, UInt32 SourceY, UInt32 DestinationX, UInt32 DestinationY, UInt32 Width, UInt32 Height, UInt32 Delta); - -typedef struct -{ - UInt32 MaxMode; - UInt32 Mode; - EfiGraphicsOutputProtocolModeInformation* Info; - UInt32 SizeOfInfo; - UIntPtr FrameBufferBase; - UInt32 FrameBufferSize; -} EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE; - -typedef struct EfiGraphicsOutputProtocol -{ - EfiGraphicsOutputProtocolQueryMode QueryMode; - EfiGraphicsOutputProtocolSetMode SetMode; - EfiGraphicsOutputProtocolBlt Blt; - EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE* Mode; -} EfiGraphicsOutputProtocol; - -typedef struct EfiLoadImageProtocol -{ - UInt32 Revision; - EfiHandlePtr ParentHandle; - EfiSystemTable* SystemTable; - - // Source location of the image - EfiHandlePtr DeviceHandle; - EfiDevicePathProtocol* FilePath; - Void* Reserved; - - // Image’s load options - UInt32 LoadOptionsSize; - Void* LoadOptions; - - // Location where image was loaded - Void* ImageBase; - UInt64 ImageSize; - EfiMemoryType ImageCodeType; - EfiMemoryType ImageDataType; - EfiImageUnload Unload; -} EfiLoadImageProtocol; - -typedef struct EfiLoadFileProtocol -{ - EfiLoadFile LoadFile; -} EfiLoadFileProtocol; - -typedef struct EfiDevicePathProtocol -{ - UInt8 Kind; - UInt8 SubType; - UInt8 Length[2]; -} EfiDevicePathProtocol; - -typedef struct EfiFileDevicePathProtocol -{ - EfiDevicePathProtocol Proto; - - /// - /// File Path of this struct - /// - WideChar Path[kPathLen]; -} EfiFileDevicePathProtocol; - -typedef UInt64(EFI_API* EfiExitBootServices)(VoidPtr ImageHandle, - UInt32 MapKey); - -typedef UInt64(EFI_API* EfiAllocatePages)(EfiAllocateType AllocType, - EfiMemoryType MemType, - UInt32 Count, - EfiPhysicalAddress* Memory); - -typedef UInt64(EFI_API* EfiFreePages)(EfiPhysicalAddress* Memory, UInt32 Pages); - -typedef UInt64(EFI_API* EfiGetMemoryMap)(UInt32* MapSize, - EfiMemoryDescriptor* DescPtr, - UInt32* MapKey, - UInt32* DescSize, - UInt32* DescVersion); - -/** - * @brief GUID type, something you can also find in CFKit. - */ -typedef struct EfiGUID final -{ - UInt32 Data1; - UInt16 Data2; - UInt16 Data3; - UInt8 Data4[8]; -} EfiGUID; - -/*** - * Protocol stuff... - */ - -/** some helpers */ -#define EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL 0x00000001 -#define EFI_OPEN_PROTOCOL_GET_PROTOCOL 0x00000002 -#define EFI_OPEN_PROTOCOL_TEST_PROTOCOL 0x00000004 -#define EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER 0x00000008 -#define EFI_OPEN_PROTOCOL_BY_DRIVER 0x00000010 -#define EFI_OPEN_PROTOCOL_EXCLUSIVE 0x00000020 - -typedef UInt64(EFI_API* EfiLocateProtocol)(EfiGUID* Protocol, - VoidPtr Registration, - VoidPtr* Interface); - -typedef UInt64(EFI_API* EfiOpenProtocol)(EfiHandlePtr Handle, EfiGUID* Guid, VoidPtr* Interface, EfiHandlePtr AgentHandle, EfiHandlePtr ControllerHandle, UInt32 Attributes); - -typedef UInt64(EFI_API* EfiEnableCursor)(EfiSimpleTextOutputProtocol* This, Boolean Visible); - -/** -@name EfiBootServices -@brief UEFI Boot Services record, it contains functions necessary to a -firmware level application. -*/ -typedef struct EfiBootServices -{ - EfiTableHeader SystemTable; - VoidPtr RaiseTPL; - VoidPtr RestoreTPL; - EfiAllocatePages AllocatePages; - EfiFreePages FreePages; - EfiGetMemoryMap GetMemoryMap; - EfiAllocatePool AllocatePool; - EfiFreePool FreePool; - VoidPtr CreateEvent; - VoidPtr SetTimer; - VoidPtr WaitForEvent; - VoidPtr SignalEvent; - VoidPtr CloseEvent; - VoidPtr CheckEvent; - VoidPtr InstallProtocolInterface; - VoidPtr ReinstallProtocolInterface; - VoidPtr UninstallProtocolInterface; - EfiHandleProtocol HandleProtocol; - VoidPtr Reserved; - VoidPtr RegisterProtocolNotify; - VoidPtr LocateHandle; - EfiLocateDevicePath LocateDevicePath; - VoidPtr InstallConfigurationTable; - EfiLoadImage LoadImage; - EfiStartImage StartImage; - VoidPtr Exit; - VoidPtr UnloadImage; - EfiExitBootServices ExitBootServices; - VoidPtr GetNextMonotonicCount; - VoidPtr Stall; - EfiStatusType(EFI_API* SetWatchdogTimer)(UInt32 Timeout, UInt64 WatchdogCode, UInt32 DataSize, EfiCharType* Data); - VoidPtr ConnectController; - VoidPtr DisconnectController; - EfiOpenProtocol OpenProtocol; - VoidPtr CloseProtocol; - VoidPtr OpenProtocolInformation; - VoidPtr ProtocolsPerHandle; - VoidPtr LocateHandleBuffer; - EfiLocateProtocol LocateProtocol; - VoidPtr InstallMultipleProtocolInterfaces; - VoidPtr UninstallMultipleProtocolInterfaces; - EfiCalculateCrc32 CalculateCrc32; - EfiCopyMem CopyMem; - EfiSetMem SetMem; - VoidPtr CreateEventEx; -} EfiBootServices; - -#define kEntireDevPath 0xFF -#define kThisInstancePath 0x01 - -/** -@brief PrintF like protocol. -*/ -typedef struct EfiSimpleTextOutputProtocol -{ - VoidPtr Reset; - EfiTextString OutputString; - VoidPtr TestString; - VoidPtr QueryMode; - VoidPtr SetMode; - EfiTextAttrib SetAttribute; - EfiTextClear ClearScreen; - VoidPtr SetCursorPosition; - EfiEnableCursor EnableCursor; - VoidPtr Mode; -} EfiSimpleTextOutputProtocol; - -typedef UInt64(EFI_API* EfiOpenVolume)(struct EfiSimpleFilesystemProtocol*, - struct EfiFileProtocol**); - -struct EfiSimpleFilesystemProtocol -{ - UInt64 Revision; - EfiOpenVolume OpenVolume; -}; - -/** -@brief The Structure that they give you when booting. -*/ -typedef struct EfiSystemTable -{ - EfiTableHeader SystemHeader; - WideChar* FirmwareVendor; - UInt32 FirmwareRevision; - EfiHandlePtr ConsoleInHandle; - VoidPtr ConIn; - EfiHandlePtr ConsoleOutHandle; - EfiSimpleTextOutputProtocol* ConOut; - EfiHandlePtr StandardErrorHandle; - VoidPtr StdErr; - VoidPtr RuntimeServices; - EfiBootServices* BootServices; - UInt64 NumberOfTableEntries; - struct - { - EfiGUID VendorGUID; - VoidPtr VendorTable; - } * ConfigurationTable; -} EfiSystemTable; - -#define kEfiOk 0 -#define kEfiFail -1 -#define kBufferTooSmall 5 - -#define EFI_EXTERN_C extern "C" - -typedef struct EfiIPV4 -{ - UInt8 Addr[4]; -} EfiIPV4; - -/// -/// 16-byte buffer. An IPv6 internet protocol address. -/// -typedef struct EfiIPV6 -{ - UInt8 Addr[16]; -} EfiIPV6; - -#define kEFIYellow (0x01 | 0x02 | 0x04 | 0x08) - -#ifdef __x86_64 -#define __EFI_x86_64__ 1 -#endif // __x86_64 - -enum -{ - kEFIHwDevicePath = 0x01, - kEFIAcpiDevicePath = 0x02, - kEFIMessaingDevicePath = 0x03, - kEFIMediaDevicePath = 0x04, - kEFIBiosBootPath = 0x05, - kEFIEndOfPath = 0x06, - kEFICount = 6, -}; - -#define END_DEVICE_PATH_TYPE 0x7f -#define END_ENTIRE_DEVICE_PATH_SUBTYPE 0xFF -#define END_INSTANCE_DEVICE_PATH_SUBTYPE 0x01 - -#define kEfiOffsetOf(T, F) __builtin_offsetof(T, F) - -/// File I/O macros - -#define kEFIFileRead 0x0000000000000001 -#define kEFIFileWrite 0x0000000000000002 -#define kEFIFileCreate 0x0000000000000000 - -#define kEFIReadOnly 0x01 -#define kEFIHidden 0x02 -#define kEFISystem 0x04 -#define kEFIReserved 0x08 -#define kEFIDirectory 0x10 -#define kEFIArchive 0x20 - -typedef struct EfiIOToken -{ - // - // If Event is NULL, then blocking I/O is performed. - // If Event is not NULL and non-blocking I/O is supported, then non-blocking - // I/O is performed, and Event will be signaled when the read request is - // completed. The caller must be prepared to handle the case where the - // callback associated with Event occurs before the original asynchronous I/O - // request call returns. - // - UInt64 Event; - - // - // Defines whether or not the signaled event encountered an error. - // - UInt64 Status; - - // - // For OpenEx(): Not Used, ignored. - // For ReadEx(): On input, the size of the Buffer. On output, the amount of - // data returned in Buffer. - // In both cases, the size is measured in bytes. - // For WriteEx(): On input, the size of the Buffer. On output, the amount of - // data actually written. - // In both cases, the size is measured in bytes. - // For FlushEx(): Not used, ignored. - // - UInt32 BufferSize; - - // - // For OpenEx(): Not Used, ignored. - // For ReadEx(): The buffer into which the data is read. - // For WriteEx(): The buffer of data to write. - // For FlushEx(): Not Used, ignored. - // - Void* Buffer; -} EfiIOToken; - -typedef struct EfiFileProtocol -{ - UInt64 Revision; - - EfiStatusType(EFI_API* Open)(struct EfiFileProtocol* This, - struct EfiFileProtocol** Out, - EfiCharType* CharType, - UInt64 OpenMode, - UInt64 Attrib); - - EfiStatusType(EFI_API* Close)(struct EfiFileProtocol* This); - - EfiStatusType(EFI_API* Delete)(struct EfiFileProtocol* This); - - EfiStatusType(EFI_API* Read)(struct EfiFileProtocol* This, UInt64* BufSize, VoidPtr BufOut); - - EfiStatusType(EFI_API* Write)(struct EfiFileProtocol* This, UInt64* BufSize, VoidPtr BufOut); - - EfiStatusType(EFI_API* GetPosition)(EfiFileProtocol* This, UInt64* Position); - - EfiStatusType(EFI_API* SetPosition)(EfiFileProtocol* This, UInt64* Position); - - EfiStatusType(EFI_API* GetInfo)(struct EfiFileProtocol*, struct EfiGUID*, UInt32*, void*); - - EfiStatusType(EFI_API* SetInfo)(struct EfiFileProtocol*, struct EfiGUID*, UInt32*, void*); - - EfiStatusType(EFI_API* Flush)(EfiFileProtocol*); - - EfiStatusType(EFI_API* OpenEx)(EfiFileProtocol* This, - EfiFileProtocol** OutHandle, - EfiCharType* Path, - UInt64 Mode, - UInt64 Attrib, - struct EfiIOToken* Token); - - EfiStatusType(EFI_API* ReadEx)(EfiFileProtocol* This, - struct EfiIOToken* Token); - - EfiStatusType(EFI_API* WriteEx)(EfiFileProtocol* This, - struct EfiIOToken* Token); - - EfiStatusType(EFI_API* FlushEx)(EfiFileProtocol* This, - struct EfiIOToken* Token); -} EfiFileProtocol, *EfiFileProtocolPtr; - -typedef UInt64 EfiCursorType; - -typedef struct EfiTime -{ - UInt16 Year; - UInt8 Month; - UInt8 Day; - UInt8 Hour; - UInt8 Minute; - UInt8 Second; - UInt8 Pad1; - UInt32 Nanosecond; - Int16 TimeZone; - UInt8 Daylight; - UInt8 Pad2; -} EfiTime; - -#define EFI_FILE_INFO_GUID \ - { \ - 0x09576e92, 0x6d3f, 0x11d2, \ - { \ - 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b \ - } \ - } - -struct EfiFileInfo final -{ - /// @brief Structure size. - UInt64 Size; - /// @brief File size. - UInt64 FileSize; - /// @brief Physical size on disk. - UInt64 PhysicalSize; - /// @brief Create time. - EfiTime CreateTime; - /// @brief Last access time. - EfiTime LastAccessTime; - /// @brief Edit time. - EfiTime EditTime; - /// @brief Attributes. - UInt64 Attribute; - /// @brief VLA file name. - WideChar FileName[1]; -}; - -#define EFI_FILE_PROTOCOL_REVISION 0x00010000 -#define EFI_FILE_PROTOCOL_REVISION2 0x00020000 -#define EFI_FILE_PROTOCOL_LATEST_REVISION EFI_FILE_PROTOCOL_REVISION2 - -#define EFI_EXTRA_DESCRIPTOR_SIZE 8 - -#define EFI_MP_SERVICES_PROTOCOL_GUID \ - { \ - 0x3fdda605, 0xa76e, 0x4f46, \ - { \ - 0xad, 0x29, 0x12, 0xf4, \ - 0x53, 0x1b, 0x3d, 0x08 \ - } \ - } - -//******************************************************* -// EFI_CPU_PHYSICAL_LOCATION -// @note As in the EFI specs. -//******************************************************* -typedef struct _EfiCPUPhyiscalLocation -{ - UInt32 Package; - UInt32 Core; - UInt32 Thread; -} EfiCPUPhyiscalLocation; - -typedef union _EfiExtendedProcessorInformation { - EfiCPUPhyiscalLocation Location2; -} EfiExtendedProcessorInformation; - -typedef struct _EfiProcessorInformation -{ - UInt64 ProcessorId; - UInt32 StatusFlag; - EfiCPUPhyiscalLocation Location; - EfiExtendedProcessorInformation ExtendedInformation; -} EfiProcessorInformation; - -#define PROCESSOR_AS_BSP_BIT 0x00000001 -#define PROCESSOR_ENABLED_BIT 0x00000002 -#define PROCESSOR_HEALTH_STATUS_BIT 0x00000004 - -typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_GET_NUMBER_OF_PROCESSORS)( - IN struct _EfiMpServicesProtocol* Self, - OUT UInt32* NumberOfProcessors, - OUT UInt32* NumberOfEnabledProcessors); - -typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_GET_PROCESSOR_INFO)( - IN struct _EfiMpServicesProtocol* Self, - IN UInt32* ProcessorNumber, - OUT struct _EfiProcessorInformation* NumberOfEnabledProcessors); - -#define END_OF_CPU_LIST 0xffffffff - -typedef void EFI_API (*EFI_AP_PROCEDURE)( - IN VoidPtr ProcedureArgument); - -typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_STARTUP_ALL_APS)( - IN struct _EfiMpServicesProtocol* This, - IN EFI_AP_PROCEDURE Procedure, - IN Boolean SingleThread, - IN VoidPtr WaitEvent OPTIONAL, // EFI_EVENT first, but unused here. - IN UInt32 TimeoutInMicroSeconds, - IN Void* ProcedureArgument OPTIONAL, - OUT UInt32** FailedCpuList OPTIONAL); - -typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_SWITCH_BSP)( - IN struct _EfiMpServicesProtocol* This, - IN UInt32 ProcessorNumber, - IN Boolean EnableOldBSP); - -typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_STARTUP_THIS_AP)( - IN struct _EfiMpServicesProtocol* This, - IN EFI_AP_PROCEDURE Procedure, - IN UInt32 ProcessorNumber, - IN VoidPtr WaitEvent OPTIONAL, - IN UInt32 TimeoutInMicroseconds, - IN Void* ProcedureArgument OPTIONAL, - OUT Boolean* Finished OPTIONAL); - -typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_ENABLEDISABLEAP)( - IN struct _EfiMpServicesProtocol* This, - IN UInt32 ProcessorNumber, - IN Boolean EnableAP, - IN UInt32* HealthFlag OPTIONAL); - -typedef EfiStatusType EFI_API (*EFI_MP_SERVICES_WHOAMI)( - IN struct _EfiMpServicesProtocol* This, - OUT UInt32* ProcessorNumber); - -typedef struct _EfiMpServicesProtocol -{ - EFI_MP_SERVICES_GET_NUMBER_OF_PROCESSORS GetNumberOfProcessors; - EFI_MP_SERVICES_GET_PROCESSOR_INFO GetProcessorInfo; - EFI_MP_SERVICES_STARTUP_ALL_APS StartupAllAPs; - EFI_MP_SERVICES_STARTUP_THIS_AP StartupThisAP; - EFI_MP_SERVICES_SWITCH_BSP SwitchBSP; - EFI_MP_SERVICES_ENABLEDISABLEAP EnableDisableAP; - EFI_MP_SERVICES_WHOAMI WhoAmI; -} EfiMpServicesProtocol; - -#endif // ifndef __EFI__ diff --git a/dev/zka/FirmwareKit/EPM.h b/dev/zka/FirmwareKit/EPM.h new file mode 100644 index 00000000..7ff976a0 --- /dev/null +++ b/dev/zka/FirmwareKit/EPM.h @@ -0,0 +1,122 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +/** + @brief The Explicit Partition Map scheme. +*/ + +#ifndef __FIRMWARE_EPM_HXX__ +#define __FIRMWARE_EPM_HXX__ + +#include + +#define kEPMNameLength (32) +#define kEPMFilesystemLength (16) +#define kEPMMagicLength (5) + +/* @brief AMD64 magic for EPM */ +#define kEPMMagic86 "EPMAM" + +/* @brief RISC-V magic for EPM */ +#define kEPMMagicRISCV "EPMRV" + +/* @brief ARM magic for EPM */ +#define kEPMMagicARM "EPMAR" + +/* @brief 64x0 magic for EPM */ +#define kEPMMagic64k "EPM64" + +/* @brief 32x0 magic for EPM */ + +#define kEPMMagic32k "EPM32" + +/* @brief POWER magic for EPM */ + +#define kEPMMagicPPC "EPMPC" + +/* @brief UEFI magic for EPM */ + +#define kEPMMagicUEFI "EPMUE" + +/* @brief CoreBoot magic for EPM */ + +#define kEPMMagicCoreBoot "EPMCB" + +/* @brief Invalid magic for EPM */ + +#define kEPMMagicError "EPM??" + +#ifdef __ZKA_AMD64__ +#define kEPMMagic kEPMMagic86 +#else +#ifdef __ZKA_ARM64__ +#define kEPMMagic kEPMMagicARM +#else +#define kEPMMagic kEPMMagicError +#endif +#endif + +///! @brief partition must start at this address. +///! Anything below is reserved for Data backup by the Main OS. +#define kEPMStartPartitionBlk (sizeof(_BOOT_BLOCK_STRUCT)) + +///! @brief Current EPM revision. +#define kEPMRevision (0xAD) + +///! @brief Current EPM revision. +#define kEPMRevisionUEFI (0xAF) + +/// !@brief EPM base address. +#define kEpmBase (0U) + +struct _BLOCK_GUID_STRUCT; +struct _BOOT_BLOCK_STRUCT; + +/* The first 0 > 128 addresses of a disk contains these headers. */ + +/// @brief EPM GUID structure. +typedef struct _BLOCK_GUID_STRUCT +{ + Kernel::UInt32 Data1; + Kernel::UInt16 Data2; + Kernel::UInt16 Data3; + Kernel::UInt8 Data4[8]; +} BLOCK_GUID_STRUCT; + +/** + * @brief The EPM boot block. + * @note NumBlock and LbaStart are ignored on some platforms. + */ +struct PACKED _BOOT_BLOCK_STRUCT +{ + Kernel::Char Magic[kEPMMagicLength]; + Kernel::Char Name[kEPMNameLength]; + BLOCK_GUID_STRUCT Uuid; + Kernel::Int32 Version; + Kernel::Int64 NumBlocks; + Kernel::Int64 SectorSz; + Kernel::Int64 LbaStart; // base offset + Kernel::Int64 LbaEnd; // addition of lba_start to get the end of partition. + Kernel::Int16 Kind; + Kernel::Int32 FsVersion; + Kernel::Char Fs[kEPMFilesystemLength]; /* NeFS, ffs2... */ + Kernel::Char Reserved[401]; // to fill a full sector. +}; + +///! @brief Version kind enum. +///! @brief Use in boot block version field. + +enum +{ + kEPMEmbeddedOS = 0xcf, // Embedded OS + kEPMLinux = 0x8f, // Linux on EPM + kEPMBSD = 0x9f, // Berkeley Soft. Distribution + kEPMNewOS = 0x1f, // This OS. +}; + +typedef struct _BOOT_BLOCK_STRUCT BOOT_BLOCK_STRUCT; + +#endif // ifndef __FIRMWARE_EPM_HXX__ diff --git a/dev/zka/FirmwareKit/EPM.hxx b/dev/zka/FirmwareKit/EPM.hxx deleted file mode 100644 index 29392a8f..00000000 --- a/dev/zka/FirmwareKit/EPM.hxx +++ /dev/null @@ -1,122 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -/** - @brief The Explicit Partition Map scheme. -*/ - -#ifndef __FIRMWARE_EPM_HXX__ -#define __FIRMWARE_EPM_HXX__ - -#include - -#define kEPMNameLength (32) -#define kEPMFilesystemLength (16) -#define kEPMMagicLength (5) - -/* @brief AMD64 magic for EPM */ -#define kEPMMagic86 "EPMAM" - -/* @brief RISC-V magic for EPM */ -#define kEPMMagicRISCV "EPMRV" - -/* @brief ARM magic for EPM */ -#define kEPMMagicARM "EPMAR" - -/* @brief 64x0 magic for EPM */ -#define kEPMMagic64k "EPM64" - -/* @brief 32x0 magic for EPM */ - -#define kEPMMagic32k "EPM32" - -/* @brief POWER magic for EPM */ - -#define kEPMMagicPPC "EPMPC" - -/* @brief UEFI magic for EPM */ - -#define kEPMMagicUEFI "EPMUE" - -/* @brief CoreBoot magic for EPM */ - -#define kEPMMagicCoreBoot "EPMCB" - -/* @brief Invalid magic for EPM */ - -#define kEPMMagicError "EPM??" - -#ifdef __ZKA_AMD64__ -#define kEPMMagic kEPMMagic86 -#else -#ifdef __ZKA_ARM64__ -#define kEPMMagic kEPMMagicARM -#else -#define kEPMMagic kEPMMagicError -#endif -#endif - -///! @brief partition must start at this address. -///! Anything below is reserved for Data backup by the Main OS. -#define kEPMStartPartitionBlk (sizeof(_BOOT_BLOCK_STRUCT)) - -///! @brief Current EPM revision. -#define kEPMRevision (0xAD) - -///! @brief Current EPM revision. -#define kEPMRevisionUEFI (0xAF) - -/// !@brief EPM base address. -#define kEpmBase (0U) - -struct _BLOCK_GUID_STRUCT; -struct _BOOT_BLOCK_STRUCT; - -/* The first 0 > 128 addresses of a disk contains these headers. */ - -/// @brief EPM GUID structure. -typedef struct _BLOCK_GUID_STRUCT -{ - Kernel::UInt32 Data1; - Kernel::UInt16 Data2; - Kernel::UInt16 Data3; - Kernel::UInt8 Data4[8]; -} BLOCK_GUID_STRUCT; - -/** - * @brief The EPM boot block. - * @note NumBlock and LbaStart are ignored on some platforms. - */ -struct PACKED _BOOT_BLOCK_STRUCT -{ - Kernel::Char Magic[kEPMMagicLength]; - Kernel::Char Name[kEPMNameLength]; - BLOCK_GUID_STRUCT Uuid; - Kernel::Int32 Version; - Kernel::Int64 NumBlocks; - Kernel::Int64 SectorSz; - Kernel::Int64 LbaStart; // base offset - Kernel::Int64 LbaEnd; // addition of lba_start to get the end of partition. - Kernel::Int16 Kind; - Kernel::Int32 FsVersion; - Kernel::Char Fs[kEPMFilesystemLength]; /* NeFS, ffs2... */ - Kernel::Char Reserved[401]; // to fill a full sector. -}; - -///! @brief Version kind enum. -///! @brief Use in boot block version field. - -enum -{ - kEPMEmbeddedOS = 0xcf, // Embedded OS - kEPMLinux = 0x8f, // Linux on EPM - kEPMBSD = 0x9f, // Berkeley Soft. Distribution - kEPMNewOS = 0x1f, // This OS. -}; - -typedef struct _BOOT_BLOCK_STRUCT BOOT_BLOCK_STRUCT; - -#endif // ifndef __FIRMWARE_EPM_HXX__ diff --git a/dev/zka/FirmwareKit/Handover.h b/dev/zka/FirmwareKit/Handover.h new file mode 100644 index 00000000..d753cb10 --- /dev/null +++ b/dev/zka/FirmwareKit/Handover.h @@ -0,0 +1,116 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +/** + * @file Handover.h + * @author Amlal El Mahrouss (amlalelmahrouss@icloud.com) + * @brief The handover boot protocol. + * @version 1.15 + * @date 2024-02-23 + * + * @copyright Copyright (c) 2024, ZKA Web Services Co + * + */ + +#pragma once + +#include + +#define kHandoverMagic 0xBADCC +#define kHandoverVersion 0x0117 + +/* Initial bitmap pointer location and size. */ +#define kHandoverBitMapSz (gib_cast(4)) + +/* Executable base */ +#define kHandoverExecBase (0x4000000) + +#define kHandoverStructSz sizeof(HEL::HANDOVER_INFO_HEADER) + +namespace Kernel::HEL +{ + /** + @brief The executable type enum. + */ + enum + { + kTypeKernel = 100, + kTypeKernelDriver = 101, + kTypeRsrc = 102, + kTypeInvalid = 103, + kTypeCount = 4, + }; + + /** + @brief The executable architecture enum. + */ + + enum + { + kArchAMD64 = 122, + kArchARM64 = 123, + kArchRISCV = 124, + kArchCount = 3, + }; + + struct HANDOVER_INFO_HEADER final + { + UInt64 f_Magic; + UInt64 f_Version; + + VoidPtr f_BitMapStart; + SizeT f_BitMapSize; + + VoidPtr f_PageStart; + + VoidPtr f_KernelImage; + SizeT f_KernelSz; + VoidPtr f_StartupChime; + SizeT f_ChimeSz; + VoidPtr f_StartupImage; + SizeT f_StartupSz; + VoidPtr f_TTFallbackFont; + SizeT f_FontSz; + + WideChar f_FirmwareVendorName[32]; + SizeT f_FirmwareVendorLen; + + VoidPtr f_FirmwareCustomTables[2]; // On EFI 0: BS 1: ST + + struct + { + VoidPtr f_SmBios; + VoidPtr f_VendorPtr; + VoidPtr f_MpPtr; + Bool f_MultiProcessingEnabled; + } f_HardwareTables; + + struct + { + UIntPtr f_The; + SizeT f_Size; + UInt32 f_Width; + UInt32 f_Height; + UInt32 f_PixelFormat; + UInt32 f_PixelPerLine; + } f_GOP; + + UInt64 f_FirmwareSpecific[8]; + }; + + enum + { + kHandoverSpecificKind, + kHandoverSpecificAttrib, + kHandoverSpecificMemoryEfi, + }; + + /// @brief Alias of bootloader main type. + typedef void (*HandoverProc)(HANDOVER_INFO_HEADER* handoverInfo); +} // namespace Kernel::HEL + +/// @brief Bootloader global header. +inline Kernel::HEL::HANDOVER_INFO_HEADER* kHandoverHeader = nullptr; diff --git a/dev/zka/FirmwareKit/Handover.hxx b/dev/zka/FirmwareKit/Handover.hxx deleted file mode 100644 index 4d7130cf..00000000 --- a/dev/zka/FirmwareKit/Handover.hxx +++ /dev/null @@ -1,116 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -/** - * @file Handover.hxx - * @author Amlal El Mahrouss (amlalelmahrouss@icloud.com) - * @brief The handover boot protocol. - * @version 1.15 - * @date 2024-02-23 - * - * @copyright Copyright (c) 2024, ZKA Web Services Co - * - */ - -#pragma once - -#include - -#define kHandoverMagic 0xBADCC -#define kHandoverVersion 0x0117 - -/* Initial bitmap pointer location and size. */ -#define kHandoverBitMapSz (gib_cast(4)) - -/* Executable base */ -#define kHandoverExecBase (0x4000000) - -#define kHandoverStructSz sizeof(HEL::HANDOVER_INFO_HEADER) - -namespace Kernel::HEL -{ - /** - @brief The executable type enum. - */ - enum - { - kTypeKernel = 100, - kTypeKernelDriver = 101, - kTypeRsrc = 102, - kTypeInvalid = 103, - kTypeCount = 4, - }; - - /** - @brief The executable architecture enum. - */ - - enum - { - kArchAMD64 = 122, - kArchARM64 = 123, - kArchRISCV = 124, - kArchCount = 3, - }; - - struct HANDOVER_INFO_HEADER final - { - UInt64 f_Magic; - UInt64 f_Version; - - VoidPtr f_BitMapStart; - SizeT f_BitMapSize; - - VoidPtr f_PageStart; - - VoidPtr f_KernelImage; - SizeT f_KernelSz; - VoidPtr f_StartupChime; - SizeT f_ChimeSz; - VoidPtr f_StartupImage; - SizeT f_StartupSz; - VoidPtr f_TTFallbackFont; - SizeT f_FontSz; - - WideChar f_FirmwareVendorName[32]; - SizeT f_FirmwareVendorLen; - - VoidPtr f_FirmwareCustomTables[2]; // On EFI 0: BS 1: ST - - struct - { - VoidPtr f_SmBios; - VoidPtr f_VendorPtr; - VoidPtr f_MpPtr; - Bool f_MultiProcessingEnabled; - } f_HardwareTables; - - struct - { - UIntPtr f_The; - SizeT f_Size; - UInt32 f_Width; - UInt32 f_Height; - UInt32 f_PixelFormat; - UInt32 f_PixelPerLine; - } f_GOP; - - UInt64 f_FirmwareSpecific[8]; - }; - - enum - { - kHandoverSpecificKind, - kHandoverSpecificAttrib, - kHandoverSpecificMemoryEfi, - }; - - /// @brief Alias of bootloader main type. - typedef void (*HandoverProc)(HANDOVER_INFO_HEADER* handoverInfo); -} // namespace Kernel::HEL - -/// @brief Bootloader global header. -inline Kernel::HEL::HANDOVER_INFO_HEADER* kHandoverHeader = nullptr; diff --git a/dev/zka/HALKit/64x0/HalVirtualMemory.cc b/dev/zka/HALKit/64x0/HalVirtualMemory.cc new file mode 100644 index 00000000..ae7faa0b --- /dev/null +++ b/dev/zka/HALKit/64x0/HalVirtualMemory.cc @@ -0,0 +1,17 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +using namespace Kernel; + +/// @brief Flush system TLB, looks like the POWER version, as it acts the same, no specific instruction for that. +/// @note The 88K MMU should be present as well. +EXTERN_C void hal_flush_tlb() +{ + asm volatile("invltlb"); +} diff --git a/dev/zka/HALKit/64x0/HalVirtualMemory.cxx b/dev/zka/HALKit/64x0/HalVirtualMemory.cxx deleted file mode 100644 index 30ab87af..00000000 --- a/dev/zka/HALKit/64x0/HalVirtualMemory.cxx +++ /dev/null @@ -1,17 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -using namespace Kernel; - -/// @brief Flush system TLB, looks like the POWER version, as it acts the same, no specific instruction for that. -/// @note The 88K MMU should be present as well. -EXTERN_C void hal_flush_tlb() -{ - asm volatile("invltlb"); -} diff --git a/dev/zka/HALKit/AMD64/CPUID.h b/dev/zka/HALKit/AMD64/CPUID.h new file mode 100644 index 00000000..6eda5736 --- /dev/null +++ b/dev/zka/HALKit/AMD64/CPUID.h @@ -0,0 +1,83 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: CPUID.h + Purpose: CPUID flags. + + Revision History: + + 30/01/24: Added file (amlel) + +------------------------------------------- */ + +#pragma once + +#include + +enum +{ + eCPUFeatureSSE3 = 1 << 0, + eCPUFeaturePCLMUL = 1 << 1, + eCPUFeatureDTES64 = 1 << 2, + eCPUFeatureMONITOR = 1 << 3, + eCPUFeatureDS_CPL = 1 << 4, + eCPUFeatureVMX = 1 << 5, + eCPUFeatureSMX = 1 << 6, + eCPUFeatureEST = 1 << 7, + eCPUFeatureTM2 = 1 << 8, + eCPUFeatureSSSE3 = 1 << 9, + eCPUFeatureCID = 1 << 10, + eCPUFeatureSDBG = 1 << 11, + eCPUFeatureFMA = 1 << 12, + eCPUFeatureCX16 = 1 << 13, + eCPUFeatureXTPR = 1 << 14, + eCPUFeaturePDCM = 1 << 15, + eCPUFeaturePCID = 1 << 17, + eCPUFeatureDCA = 1 << 18, + eCPUFeatureSSE4_1 = 1 << 19, + eCPUFeatureSSE4_2 = 1 << 20, + eCPUFeatureX2APIC = 1 << 21, + eCPUFeatureMOVBE = 1 << 22, + eCPUFeaturePOP3C = 1 << 23, + eCPUFeatureECXTSC = 1 << 24, + eCPUFeatureAES = 1 << 25, + eCPUFeatureXSAVE = 1 << 26, + eCPUFeatureOSXSAVE = 1 << 27, + eCPUFeatureAVX = 1 << 28, + eCPUFeatureF16C = 1 << 29, + eCPUFeatureRDRAND = 1 << 30, + eCPUFeatureHYPERVISOR = 1 << 31, + eCPUFeatureFPU = 1 << 0, + eCPUFeatureVME = 1 << 1, + eCPUFeatureDE = 1 << 2, + eCPUFeaturePSE = 1 << 3, + eCPUFeatureEDXTSC = 1 << 4, + eCPUFeatureMSR = 1 << 5, + eCPUFeaturePAE = 1 << 6, + eCPUFeatureMCE = 1 << 7, + eCPUFeatureCX8 = 1 << 8, + eCPUFeatureAPIC = 1 << 9, + eCPUFeatureSEP = 1 << 11, + eCPUFeatureMTRR = 1 << 12, + eCPUFeaturePGE = 1 << 13, + eCPUFeatureMCA = 1 << 14, + eCPUFeatureCMOV = 1 << 15, + eCPUFeaturePAT = 1 << 16, + eCPUFeaturePSE36 = 1 << 17, + eCPUFeaturePSN = 1 << 18, + eCPUFeatureCLFLUSH = 1 << 19, + eCPUFeatureDS = 1 << 21, + eCPUFeatureACPI = 1 << 22, + eCPUFeatureMMX = 1 << 23, + eCPUFeatureFXSR = 1 << 24, + eCPUFeatureSSE = 1 << 25, + eCPUFeatureSSE2 = 1 << 26, + eCPUFeatureSS = 1 << 27, + eCPUFeatureHTT = 1 << 28, + eCPUFeatureTM = 1 << 29, + eCPUFeatureIA64 = 1 << 30, + eCPUFeaturePBE = 1 << 31 +}; + +typedef Kernel::Int64 hal_cpu_feature_type; diff --git a/dev/zka/HALKit/AMD64/CPUID.hxx b/dev/zka/HALKit/AMD64/CPUID.hxx deleted file mode 100644 index 49421586..00000000 --- a/dev/zka/HALKit/AMD64/CPUID.hxx +++ /dev/null @@ -1,83 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: CPUID.hxx - Purpose: CPUID flags. - - Revision History: - - 30/01/24: Added file (amlel) - -------------------------------------------- */ - -#pragma once - -#include - -enum -{ - eCPUFeatureSSE3 = 1 << 0, - eCPUFeaturePCLMUL = 1 << 1, - eCPUFeatureDTES64 = 1 << 2, - eCPUFeatureMONITOR = 1 << 3, - eCPUFeatureDS_CPL = 1 << 4, - eCPUFeatureVMX = 1 << 5, - eCPUFeatureSMX = 1 << 6, - eCPUFeatureEST = 1 << 7, - eCPUFeatureTM2 = 1 << 8, - eCPUFeatureSSSE3 = 1 << 9, - eCPUFeatureCID = 1 << 10, - eCPUFeatureSDBG = 1 << 11, - eCPUFeatureFMA = 1 << 12, - eCPUFeatureCX16 = 1 << 13, - eCPUFeatureXTPR = 1 << 14, - eCPUFeaturePDCM = 1 << 15, - eCPUFeaturePCID = 1 << 17, - eCPUFeatureDCA = 1 << 18, - eCPUFeatureSSE4_1 = 1 << 19, - eCPUFeatureSSE4_2 = 1 << 20, - eCPUFeatureX2APIC = 1 << 21, - eCPUFeatureMOVBE = 1 << 22, - eCPUFeaturePOP3C = 1 << 23, - eCPUFeatureECXTSC = 1 << 24, - eCPUFeatureAES = 1 << 25, - eCPUFeatureXSAVE = 1 << 26, - eCPUFeatureOSXSAVE = 1 << 27, - eCPUFeatureAVX = 1 << 28, - eCPUFeatureF16C = 1 << 29, - eCPUFeatureRDRAND = 1 << 30, - eCPUFeatureHYPERVISOR = 1 << 31, - eCPUFeatureFPU = 1 << 0, - eCPUFeatureVME = 1 << 1, - eCPUFeatureDE = 1 << 2, - eCPUFeaturePSE = 1 << 3, - eCPUFeatureEDXTSC = 1 << 4, - eCPUFeatureMSR = 1 << 5, - eCPUFeaturePAE = 1 << 6, - eCPUFeatureMCE = 1 << 7, - eCPUFeatureCX8 = 1 << 8, - eCPUFeatureAPIC = 1 << 9, - eCPUFeatureSEP = 1 << 11, - eCPUFeatureMTRR = 1 << 12, - eCPUFeaturePGE = 1 << 13, - eCPUFeatureMCA = 1 << 14, - eCPUFeatureCMOV = 1 << 15, - eCPUFeaturePAT = 1 << 16, - eCPUFeaturePSE36 = 1 << 17, - eCPUFeaturePSN = 1 << 18, - eCPUFeatureCLFLUSH = 1 << 19, - eCPUFeatureDS = 1 << 21, - eCPUFeatureACPI = 1 << 22, - eCPUFeatureMMX = 1 << 23, - eCPUFeatureFXSR = 1 << 24, - eCPUFeatureSSE = 1 << 25, - eCPUFeatureSSE2 = 1 << 26, - eCPUFeatureSS = 1 << 27, - eCPUFeatureHTT = 1 << 28, - eCPUFeatureTM = 1 << 29, - eCPUFeatureIA64 = 1 << 30, - eCPUFeaturePBE = 1 << 31 -}; - -typedef Kernel::Int64 hal_cpu_feature_type; diff --git a/dev/zka/HALKit/AMD64/HalACPIFactoryInterface.cc b/dev/zka/HALKit/AMD64/HalACPIFactoryInterface.cc new file mode 100644 index 00000000..2ed013ef --- /dev/null +++ b/dev/zka/HALKit/AMD64/HalACPIFactoryInterface.cc @@ -0,0 +1,126 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include +#include +#include + +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; + + 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 BootArchitectureFlags; + + UInt8 Reserved2; + UInt32 Flags; + + // 12 byte structure; see below for details + ACPI_ADDRESS ResetReg; + + UInt8 ResetValue; + UInt8 Reserved3[3]; + + // 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 + + ACPIFactoryInterface::ACPIFactoryInterface(VoidPtr rsp_ptr) + : fRsdp(rsp_ptr), fEntries(0) + { + } + + Void ACPIFactoryInterface::Shutdown() + { + failed_to_shutdown: + // in case no acpi mode, or it's not available. + while (Yes) + { + asm volatile("cli; hlt"); + } + } + + /// @brief Reboot machine in either ACPI or by triple faulting. + /// @return nothing it's a reboot. + Void ACPIFactoryInterface::Reboot() + { + failed_to_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/zka/HALKit/AMD64/HalACPIFactoryInterface.cxx b/dev/zka/HALKit/AMD64/HalACPIFactoryInterface.cxx deleted file mode 100644 index 443d6a5d..00000000 --- a/dev/zka/HALKit/AMD64/HalACPIFactoryInterface.cxx +++ /dev/null @@ -1,126 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include -#include -#include - -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; - - 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 BootArchitectureFlags; - - UInt8 Reserved2; - UInt32 Flags; - - // 12 byte structure; see below for details - ACPI_ADDRESS ResetReg; - - UInt8 ResetValue; - UInt8 Reserved3[3]; - - // 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 - - ACPIFactoryInterface::ACPIFactoryInterface(VoidPtr rsp_ptr) - : fRsdp(rsp_ptr), fEntries(0) - { - } - - Void ACPIFactoryInterface::Shutdown() - { - failed_to_shutdown: - // in case no acpi mode, or it's not available. - while (Yes) - { - asm volatile("cli; hlt"); - } - } - - /// @brief Reboot machine in either ACPI or by triple faulting. - /// @return nothing it's a reboot. - Void ACPIFactoryInterface::Reboot() - { - failed_to_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/zka/HALKit/AMD64/HalAPICController.cc b/dev/zka/HALKit/AMD64/HalAPICController.cc new file mode 100644 index 00000000..3a8bc23d --- /dev/null +++ b/dev/zka/HALKit/AMD64/HalAPICController.cc @@ -0,0 +1,39 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +#define cIOAPICRegVal (4) +#define cIOAPICRegReg (0) + +namespace Kernel::HAL +{ + /// @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/zka/HALKit/AMD64/HalAPICController.cxx b/dev/zka/HALKit/AMD64/HalAPICController.cxx deleted file mode 100644 index 47c55657..00000000 --- a/dev/zka/HALKit/AMD64/HalAPICController.cxx +++ /dev/null @@ -1,39 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -#define cIOAPICRegVal (4) -#define cIOAPICRegReg (0) - -namespace Kernel::HAL -{ - /// @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/zka/HALKit/AMD64/HalCPU.cc b/dev/zka/HALKit/AMD64/HalCPU.cc new file mode 100644 index 00000000..80729346 --- /dev/null +++ b/dev/zka/HALKit/AMD64/HalCPU.cc @@ -0,0 +1,101 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: HalCPU.cxx + Purpose: Platform processor routines. + +------------------------------------------- */ + +#include +#include + +/** + * @file HalCPU.cxx + * @brief Common CPU API. + */ + +namespace Kernel::HAL +{ + Void Out8(UInt16 port, UInt8 value) + { + asm volatile("outb %%al, %1" + : + : "a"(value), "Nd"(port) + : "memory"); + } + + Void Out16(UInt16 port, UInt16 value) + { + asm volatile("outw %%ax, %1" + : + : "a"(value), "Nd"(port) + : "memory"); + } + + Void Out32(UInt16 port, UInt32 value) + { + asm volatile("outl %%eax, %1" + : + : "a"(value), "Nd"(port) + : "memory"); + } + + UInt8 In8(UInt16 port) + { + UInt8 value = 0UL; + asm volatile("inb %1, %%al" + : "=a"(value) + : "Nd"(port) + : "memory"); + + return value; + } + + UInt16 In16(UInt16 port) + { + UInt16 value = 0UL; + asm volatile("inw %1, %%ax" + : "=a"(value) + : "Nd"(port) + : "memory"); + + return value; + } + + UInt32 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/zka/HALKit/AMD64/HalCPU.cxx b/dev/zka/HALKit/AMD64/HalCPU.cxx deleted file mode 100644 index a96ceb34..00000000 --- a/dev/zka/HALKit/AMD64/HalCPU.cxx +++ /dev/null @@ -1,101 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: HalCPU.cxx - Purpose: Platform processor routines. - -------------------------------------------- */ - -#include -#include - -/** - * @file HalCPU.cxx - * @brief Common CPU API. - */ - -namespace Kernel::HAL -{ - Void Out8(UInt16 port, UInt8 value) - { - asm volatile("outb %%al, %1" - : - : "a"(value), "Nd"(port) - : "memory"); - } - - Void Out16(UInt16 port, UInt16 value) - { - asm volatile("outw %%ax, %1" - : - : "a"(value), "Nd"(port) - : "memory"); - } - - Void Out32(UInt16 port, UInt32 value) - { - asm volatile("outl %%eax, %1" - : - : "a"(value), "Nd"(port) - : "memory"); - } - - UInt8 In8(UInt16 port) - { - UInt8 value = 0UL; - asm volatile("inb %1, %%al" - : "=a"(value) - : "Nd"(port) - : "memory"); - - return value; - } - - UInt16 In16(UInt16 port) - { - UInt16 value = 0UL; - asm volatile("inw %1, %%ax" - : "=a"(value) - : "Nd"(port) - : "memory"); - - return value; - } - - UInt32 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/zka/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc b/dev/zka/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc new file mode 100644 index 00000000..7dd0b68e --- /dev/null +++ b/dev/zka/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc @@ -0,0 +1,113 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include + +namespace Kernel +{ + EXTERN UserProcessScheduler* kProcessScheduler; +} + +/// @brief Handle GPF fault. +/// @param rsp +EXTERN_C void idt_handle_gpf(Kernel::UIntPtr rsp) +{ + Kernel::UserProcessScheduler::The().CurrentProcess().Leak().Crash(); +} + +/// @brief Handle page fault. +/// @param rsp +EXTERN_C void idt_handle_pf(Kernel::UIntPtr rsp) +{ + Kernel::UserProcessScheduler::The().CurrentProcess().Leak().Crash(); +} + +/// @brief Handle scheduler interrupt. +EXTERN_C void idt_handle_scheduler(Kernel::UIntPtr rsp) +{ + Kernel::UserProcessHelper::StartScheduling(); +} + +/// @brief Handle math fault. +/// @param rsp +EXTERN_C void idt_handle_math(Kernel::UIntPtr rsp) +{ + Kernel::UserProcessScheduler::The().CurrentProcess().Leak().Crash(); +} + +/// @brief Handle any generic fault. +/// @param rsp +EXTERN_C void idt_handle_generic(Kernel::UIntPtr rsp) +{ + Kernel::UserProcessScheduler::The().CurrentProcess().Leak().Crash(); +} + +/// @brief Handle #UD fault. +/// @param rsp +EXTERN_C void idt_handle_ud(Kernel::UIntPtr rsp) +{ + Kernel::UserProcessScheduler::The().CurrentProcess().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()) + { + kcout << "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 + { + kcout << "syscall: syscall isn't valid at all! (is nullptr)\r"; + } + } + else + { + kcout << "syscall: syscall isn't hooked at all! (is set to false)\r"; + } + + kcout << "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()) + { + kcout << "kerncall: Enter Kcall.\r"; + + if (kKerncalls[rcx_kerncall_index].fHooked) + { + if (kKerncalls[rcx_kerncall_index].fProc) + { + (kKerncalls[rcx_kerncall_index].fProc)((Kernel::VoidPtr)rdx_kerncall_struct); + } + else + { + kcout << "kerncall: syscall isn't valid at all! (is nullptr)\r"; + } + } + else + { + kcout << "kerncall: syscall isn't hooked at all! (is set to false)\r"; + } + + kcout << "kerncall: Exit Kcall.\r"; + } +} diff --git a/dev/zka/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cxx b/dev/zka/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cxx deleted file mode 100644 index 4ff168cd..00000000 --- a/dev/zka/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cxx +++ /dev/null @@ -1,113 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include - -namespace Kernel -{ - EXTERN UserProcessScheduler* kProcessScheduler; -} - -/// @brief Handle GPF fault. -/// @param rsp -EXTERN_C void idt_handle_gpf(Kernel::UIntPtr rsp) -{ - Kernel::UserProcessScheduler::The().CurrentProcess().Leak().Crash(); -} - -/// @brief Handle page fault. -/// @param rsp -EXTERN_C void idt_handle_pf(Kernel::UIntPtr rsp) -{ - Kernel::UserProcessScheduler::The().CurrentProcess().Leak().Crash(); -} - -/// @brief Handle scheduler interrupt. -EXTERN_C void idt_handle_scheduler(Kernel::UIntPtr rsp) -{ - Kernel::UserProcessHelper::StartScheduling(); -} - -/// @brief Handle math fault. -/// @param rsp -EXTERN_C void idt_handle_math(Kernel::UIntPtr rsp) -{ - Kernel::UserProcessScheduler::The().CurrentProcess().Leak().Crash(); -} - -/// @brief Handle any generic fault. -/// @param rsp -EXTERN_C void idt_handle_generic(Kernel::UIntPtr rsp) -{ - Kernel::UserProcessScheduler::The().CurrentProcess().Leak().Crash(); -} - -/// @brief Handle #UD fault. -/// @param rsp -EXTERN_C void idt_handle_ud(Kernel::UIntPtr rsp) -{ - Kernel::UserProcessScheduler::The().CurrentProcess().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()) - { - kcout << "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 - { - kcout << "syscall: syscall isn't valid at all! (is nullptr)\r"; - } - } - else - { - kcout << "syscall: syscall isn't hooked at all! (is set to false)\r"; - } - - kcout << "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()) - { - kcout << "kerncall: Enter Kcall.\r"; - - if (kKerncalls[rcx_kerncall_index].fHooked) - { - if (kKerncalls[rcx_kerncall_index].fProc) - { - (kKerncalls[rcx_kerncall_index].fProc)((Kernel::VoidPtr)rdx_kerncall_struct); - } - else - { - kcout << "kerncall: syscall isn't valid at all! (is nullptr)\r"; - } - } - else - { - kcout << "kerncall: syscall isn't hooked at all! (is set to false)\r"; - } - - kcout << "kerncall: Exit Kcall.\r"; - } -} diff --git a/dev/zka/HALKit/AMD64/HalCoreMPScheduler.cc b/dev/zka/HALKit/AMD64/HalCoreMPScheduler.cc new file mode 100644 index 00000000..9feddbfb --- /dev/null +++ b/dev/zka/HALKit/AMD64/HalCoreMPScheduler.cc @@ -0,0 +1,229 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Needed for SMP. // +#include +#include + +#define kApicSignature "APIC" + +#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_ENABLE 0x800 + +#define cSMPMax (32U) + +/// @note: _hal_switch_context is internal + +/////////////////////////////////////////////////////////////////////////////////////// + +//! NOTE: fGSI stands 'Field Global System Interrupt' + +/////////////////////////////////////////////////////////////////////////////////////// + +namespace Kernel::HAL +{ + struct MADT_TABLE; + + EXTERN_C Void _hal_spin_core(Void); + + STATIC struct MADT_TABLE* kMADTBlock = nullptr; + STATIC Bool kSMPAware = false; + STATIC Int64 kSMPCount = 0; + + STATIC Int32 cSMPInterrupt = 0; + STATIC UInt64 cSMPCores[cSMPMax] = {0}; + STATIC VoidPtr kRawMADT = nullptr; + + /// @brief Multiple APIC Descriptor Table. + struct MADT_TABLE final : public SDT + { + UInt32 Address; // Madt address + UInt8 Flags; // Madt flags + + struct + { + UInt8 Type; + UInt8 Len; + + union { + struct + { + UInt8 IoID; + UInt8 Resv; + UInt32 IoAddress; + UInt32 GISBase; + } IOAPIC; + + struct + { + UInt8 Source; + UInt8 IRQSource; + UInt32 GSI; + UInt16 Flags; + } IOAPIC_NMI; + + struct + { + UInt8 ProcessorID; + UInt16 Flags; + UInt8 LINT; + } LAPIC; + + struct + { + UInt16 Reserved; + UInt64 Address; + } LAPIC_ADDRESS_OVERRIDE; + + struct + { + UInt16 Reserved; + UInt32 x2APICID; + UInt32 Flags; + UInt32 AcpiID; + } LAPIC_ADDRESS; + }; + } List[]; // Records List + }; + + /////////////////////////////////////////////////////////////////////////////////////// + + /***********************************************************************************/ + /// @brief Send start IPI for CPU. + /// @param apicId + /// @param vector + /// @param targetAddress + /// @return + /***********************************************************************************/ + + Void hal_send_start_ipi(UInt32 apicId, UInt8 vector, UInt32 targetAddress) + { + Kernel::ke_dma_write(targetAddress, kAPIC_ICR_High, (apicId << 24)); + Kernel::ke_dma_write(targetAddress, kAPIC_ICR_Low, kAPIC_SIPI_Vector | vector); + } + + /***********************************************************************************/ + /// @brief Send end IPI for CPU. + /// @param apicId + /// @param vector + /// @param targetAddress + /// @return + /***********************************************************************************/ + Void hal_send_end_ipi(UInt32 apicId, UInt8 vector, UInt32 targetAddress) + { + Kernel::ke_dma_write(targetAddress, kAPIC_ICR_High, (apicId << 24)); + Kernel::ke_dma_write(targetAddress, kAPIC_ICR_Low, kAPIC_EIPI_Vector | vector); + } + + EXTERN_C Bool mp_register_process(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr stack_frame); + + struct PROCESS_CONTROL_BLOCK final + { + HAL::StackFramePtr f_Frame; + UInt8* f_Stack; + VoidPtr f_Image; + } fBlocks[kSchedProcessLimitPerTeam] = {0}; + + EXTERN_C HAL::StackFramePtr mp_get_current_context(Void) + { + return fBlocks[UserProcessScheduler::The().CurrentProcess().Leak().ProcessId % kSchedProcessLimitPerTeam].f_Frame; + } + + EXTERN_C Void mp_do_task_switch(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr stack_frame); + + EXTERN_C Bool mp_register_process(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr stack_frame) + { + fBlocks[UserProcessScheduler::The().CurrentProcess().Leak().ProcessId % kSchedProcessLimitPerTeam].f_Frame = stack_frame; + fBlocks[UserProcessScheduler::The().CurrentProcess().Leak().ProcessId % kSchedProcessLimitPerTeam].f_Stack = stack_ptr; + fBlocks[UserProcessScheduler::The().CurrentProcess().Leak().ProcessId % kSchedProcessLimitPerTeam].f_Image = image; + + mp_do_task_switch(image, stack_ptr, stack_frame); + + return Yes; + } + + /***********************************************************************************/ + /// @brief Fetch and enable cores inside main CPU. + /// @param vendor_ptr RSD PTR structure. + /***********************************************************************************/ + Void mp_get_cores(VoidPtr vendor_ptr) noexcept + { + if (!vendor_ptr) + return; + + auto hw_and_pow_int = PowerFactoryInterface(vendor_ptr); + kRawMADT = hw_and_pow_int.Find(kApicSignature).Leak().Leak(); + + kMADTBlock = reinterpret_cast(kRawMADT); + + kSMPAware = false; + + if (kMADTBlock) + { + SizeT index = 0; + + // reset values. + + cSMPInterrupt = 0; + kSMPCount = 0; + + kcout << "Probing MADT cores...\r"; + + UIntPtr madt_address = kMADTBlock->Address; + + while (Yes) + { + if (kMADTBlock->List[index].Type > 9 || + kSMPCount > cSMPMax) + break; + + switch (kMADTBlock->List[index].Type) + { + case 0x00: { + cSMPCores[index] = kMADTBlock->List[index].LAPIC.ProcessorID; + kcout << "Core ID: " << number(cSMPCores[index]) << endl; + ++kSMPCount; + break; + } + case 0x05: { + madt_address = kMADTBlock->List[index].LAPIC_ADDRESS_OVERRIDE.Address; + kcout << "Address: " << number(madt_address) << endl; + break; + } + } + + ++index; + } + + kcout << "# of cores: " << number(kSMPCount) << endl; + + // Kernel is now SMP aware. + // That means that the scheduler is now available (on MP Kernels) + + kSMPAware = true; + + /// TODO: Notify Boot AP that it must start. + } + } +} // namespace Kernel::HAL + +/////////////////////////////////////////////////////////////////////////////////////// diff --git a/dev/zka/HALKit/AMD64/HalCoreMPScheduler.cxx b/dev/zka/HALKit/AMD64/HalCoreMPScheduler.cxx deleted file mode 100644 index e763475a..00000000 --- a/dev/zka/HALKit/AMD64/HalCoreMPScheduler.cxx +++ /dev/null @@ -1,229 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Needed for SMP. // -#include -#include - -#define kApicSignature "APIC" - -#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_ENABLE 0x800 - -#define cSMPMax (32U) - -/// @note: _hal_switch_context is internal - -/////////////////////////////////////////////////////////////////////////////////////// - -//! NOTE: fGSI stands 'Field Global System Interrupt' - -/////////////////////////////////////////////////////////////////////////////////////// - -namespace Kernel::HAL -{ - struct MADT_TABLE; - - EXTERN_C Void _hal_spin_core(Void); - - STATIC struct MADT_TABLE* kMADTBlock = nullptr; - STATIC Bool kSMPAware = false; - STATIC Int64 kSMPCount = 0; - - STATIC Int32 cSMPInterrupt = 0; - STATIC UInt64 cSMPCores[cSMPMax] = {0}; - STATIC VoidPtr kRawMADT = nullptr; - - /// @brief Multiple APIC Descriptor Table. - struct MADT_TABLE final : public SDT - { - UInt32 Address; // Madt address - UInt8 Flags; // Madt flags - - struct - { - UInt8 Type; - UInt8 Len; - - union { - struct - { - UInt8 IoID; - UInt8 Resv; - UInt32 IoAddress; - UInt32 GISBase; - } IOAPIC; - - struct - { - UInt8 Source; - UInt8 IRQSource; - UInt32 GSI; - UInt16 Flags; - } IOAPIC_NMI; - - struct - { - UInt8 ProcessorID; - UInt16 Flags; - UInt8 LINT; - } LAPIC; - - struct - { - UInt16 Reserved; - UInt64 Address; - } LAPIC_ADDRESS_OVERRIDE; - - struct - { - UInt16 Reserved; - UInt32 x2APICID; - UInt32 Flags; - UInt32 AcpiID; - } LAPIC_ADDRESS; - }; - } List[]; // Records List - }; - - /////////////////////////////////////////////////////////////////////////////////////// - - /***********************************************************************************/ - /// @brief Send start IPI for CPU. - /// @param apicId - /// @param vector - /// @param targetAddress - /// @return - /***********************************************************************************/ - - Void hal_send_start_ipi(UInt32 apicId, UInt8 vector, UInt32 targetAddress) - { - Kernel::ke_dma_write(targetAddress, kAPIC_ICR_High, (apicId << 24)); - Kernel::ke_dma_write(targetAddress, kAPIC_ICR_Low, kAPIC_SIPI_Vector | vector); - } - - /***********************************************************************************/ - /// @brief Send end IPI for CPU. - /// @param apicId - /// @param vector - /// @param targetAddress - /// @return - /***********************************************************************************/ - Void hal_send_end_ipi(UInt32 apicId, UInt8 vector, UInt32 targetAddress) - { - Kernel::ke_dma_write(targetAddress, kAPIC_ICR_High, (apicId << 24)); - Kernel::ke_dma_write(targetAddress, kAPIC_ICR_Low, kAPIC_EIPI_Vector | vector); - } - - EXTERN_C Bool mp_register_process(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr stack_frame); - - struct PROCESS_CONTROL_BLOCK final - { - HAL::StackFramePtr f_Frame; - UInt8* f_Stack; - VoidPtr f_Image; - } fBlocks[kSchedProcessLimitPerTeam] = {0}; - - EXTERN_C HAL::StackFramePtr mp_get_current_context(Void) - { - return fBlocks[UserProcessScheduler::The().CurrentProcess().Leak().ProcessId % kSchedProcessLimitPerTeam].f_Frame; - } - - EXTERN_C Void mp_do_task_switch(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr stack_frame); - - EXTERN_C Bool mp_register_process(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr stack_frame) - { - fBlocks[UserProcessScheduler::The().CurrentProcess().Leak().ProcessId % kSchedProcessLimitPerTeam].f_Frame = stack_frame; - fBlocks[UserProcessScheduler::The().CurrentProcess().Leak().ProcessId % kSchedProcessLimitPerTeam].f_Stack = stack_ptr; - fBlocks[UserProcessScheduler::The().CurrentProcess().Leak().ProcessId % kSchedProcessLimitPerTeam].f_Image = image; - - mp_do_task_switch(image, stack_ptr, stack_frame); - - return Yes; - } - - /***********************************************************************************/ - /// @brief Fetch and enable cores inside main CPU. - /// @param vendor_ptr RSD PTR structure. - /***********************************************************************************/ - Void mp_get_cores(VoidPtr vendor_ptr) noexcept - { - if (!vendor_ptr) - return; - - auto hw_and_pow_int = PowerFactoryInterface(vendor_ptr); - kRawMADT = hw_and_pow_int.Find(kApicSignature).Leak().Leak(); - - kMADTBlock = reinterpret_cast(kRawMADT); - - kSMPAware = false; - - if (kMADTBlock) - { - SizeT index = 0; - - // reset values. - - cSMPInterrupt = 0; - kSMPCount = 0; - - kcout << "Probing MADT cores...\r"; - - UIntPtr madt_address = kMADTBlock->Address; - - while (Yes) - { - if (kMADTBlock->List[index].Type > 9 || - kSMPCount > cSMPMax) - break; - - switch (kMADTBlock->List[index].Type) - { - case 0x00: { - cSMPCores[index] = kMADTBlock->List[index].LAPIC.ProcessorID; - kcout << "Core ID: " << number(cSMPCores[index]) << endl; - ++kSMPCount; - break; - } - case 0x05: { - madt_address = kMADTBlock->List[index].LAPIC_ADDRESS_OVERRIDE.Address; - kcout << "Address: " << number(madt_address) << endl; - break; - } - } - - ++index; - } - - kcout << "# of cores: " << number(kSMPCount) << endl; - - // Kernel is now SMP aware. - // That means that the scheduler is now available (on MP Kernels) - - kSMPAware = true; - - /// TODO: Notify Boot AP that it must start. - } - } -} // namespace Kernel::HAL - -/////////////////////////////////////////////////////////////////////////////////////// diff --git a/dev/zka/HALKit/AMD64/HalDebugOutput.cc b/dev/zka/HALKit/AMD64/HalDebugOutput.cc new file mode 100644 index 00000000..49cdc964 --- /dev/null +++ b/dev/zka/HALKit/AMD64/HalDebugOutput.cc @@ -0,0 +1,144 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include +#include + +namespace Kernel +{ + enum CommStatus + { + kStateInvalid, + kStateReady = 0xCF, + kStateTransmit = 0xFC, + kStateCnt = 3 + }; + + namespace Detail + { + constexpr short PORT = 0x3F8; + + static int kState = kStateInvalid; + + /// @brief Init COM1. + /// @return + bool hal_serial_init() noexcept + { +#ifdef __DEBUG__ + if (kState == kStateReady || kState == kStateTransmit) + return true; + + HAL::Out8(PORT + 1, 0x00); // Disable all interrupts + HAL::Out8(PORT + 3, 0x80); // Enable DLAB (set baud rate divisor) + HAL::Out8(PORT + 0, 0x03); // Set divisor to 3 (lo byte) 38400 baud + HAL::Out8(PORT + 1, 0x00); // (hi byte) + HAL::Out8(PORT + 3, 0x03); // 8 bits, no parity, one stop bit + HAL::Out8(PORT + 2, 0xC7); // Enable FIFO, clear them, with 14-byte threshold + HAL::Out8(PORT + 4, 0x0B); // IRQs enabled, RTS/DSR set + HAL::Out8(PORT + 4, 0x1E); // Set in loopback mode, test the serial chip + HAL::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::In8(PORT) != 0xAE) + { + ke_stop(RUNTIME_CHECK_HANDSHAKE); + } + + 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::Out8(Detail::PORT + 4, 0x0F); +#endif // __DEBUG__ + + return true; + } + } // namespace Detail + + EXTERN_C void ke_io_write(const Char* bytes) + { +#ifdef __DEBUG__ + Detail::hal_serial_init(); + + if (!bytes || Detail::kState != kStateReady) + return; + if (*bytes == 0) + return; + + Detail::kState = kStateTransmit; + + SizeT index = 0; + SizeT len = 0; + + index = 0; + len = rt_string_len(bytes, 255); + + while (index < len) + { + if (bytes[index] == '\r') + HAL::Out8(Detail::PORT, '\r'); + + HAL::Out8(Detail::PORT, bytes[index] == '\r' ? '\n' : bytes[index]); + ++index; + } + + Detail::kState = kStateReady; +#endif // __DEBUG__ + } + + EXTERN_C void ke_io_read(const Char* bytes) + { +#ifdef __DEBUG__ + Detail::hal_serial_init(); + + if (!bytes || Detail::kState != kStateReady) + return; + + Detail::kState = kStateTransmit; + + SizeT index = 0; + + ///! TODO: Look on how to wait for the UART to complete. + while (true) + { + auto in = HAL::In8(Detail::PORT); + + ///! 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; + + Detail::kState = kStateReady; +#endif // __DEBUG__ + } + + TerminalDevice TerminalDevice::The() noexcept + { + TerminalDevice out(Kernel::ke_io_write, Kernel::ke_io_read); + return out; + } + +} // namespace Kernel diff --git a/dev/zka/HALKit/AMD64/HalDebugOutput.cxx b/dev/zka/HALKit/AMD64/HalDebugOutput.cxx deleted file mode 100644 index e6f4148b..00000000 --- a/dev/zka/HALKit/AMD64/HalDebugOutput.cxx +++ /dev/null @@ -1,144 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include -#include - -namespace Kernel -{ - enum CommStatus - { - kStateInvalid, - kStateReady = 0xCF, - kStateTransmit = 0xFC, - kStateCnt = 3 - }; - - namespace Detail - { - constexpr short PORT = 0x3F8; - - static int kState = kStateInvalid; - - /// @brief Init COM1. - /// @return - bool hal_serial_init() noexcept - { -#ifdef __DEBUG__ - if (kState == kStateReady || kState == kStateTransmit) - return true; - - HAL::Out8(PORT + 1, 0x00); // Disable all interrupts - HAL::Out8(PORT + 3, 0x80); // Enable DLAB (set baud rate divisor) - HAL::Out8(PORT + 0, 0x03); // Set divisor to 3 (lo byte) 38400 baud - HAL::Out8(PORT + 1, 0x00); // (hi byte) - HAL::Out8(PORT + 3, 0x03); // 8 bits, no parity, one stop bit - HAL::Out8(PORT + 2, 0xC7); // Enable FIFO, clear them, with 14-byte threshold - HAL::Out8(PORT + 4, 0x0B); // IRQs enabled, RTS/DSR set - HAL::Out8(PORT + 4, 0x1E); // Set in loopback mode, test the serial chip - HAL::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::In8(PORT) != 0xAE) - { - ke_stop(RUNTIME_CHECK_HANDSHAKE); - } - - 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::Out8(Detail::PORT + 4, 0x0F); -#endif // __DEBUG__ - - return true; - } - } // namespace Detail - - EXTERN_C void ke_io_write(const Char* bytes) - { -#ifdef __DEBUG__ - Detail::hal_serial_init(); - - if (!bytes || Detail::kState != kStateReady) - return; - if (*bytes == 0) - return; - - Detail::kState = kStateTransmit; - - SizeT index = 0; - SizeT len = 0; - - index = 0; - len = rt_string_len(bytes, 255); - - while (index < len) - { - if (bytes[index] == '\r') - HAL::Out8(Detail::PORT, '\r'); - - HAL::Out8(Detail::PORT, bytes[index] == '\r' ? '\n' : bytes[index]); - ++index; - } - - Detail::kState = kStateReady; -#endif // __DEBUG__ - } - - EXTERN_C void ke_io_read(const Char* bytes) - { -#ifdef __DEBUG__ - Detail::hal_serial_init(); - - if (!bytes || Detail::kState != kStateReady) - return; - - Detail::kState = kStateTransmit; - - SizeT index = 0; - - ///! TODO: Look on how to wait for the UART to complete. - while (true) - { - auto in = HAL::In8(Detail::PORT); - - ///! 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; - - Detail::kState = kStateReady; -#endif // __DEBUG__ - } - - TerminalDevice TerminalDevice::The() noexcept - { - TerminalDevice out(Kernel::ke_io_write, Kernel::ke_io_read); - return out; - } - -} // namespace Kernel diff --git a/dev/zka/HALKit/AMD64/HalDebugPort.cc b/dev/zka/HALKit/AMD64/HalDebugPort.cc new file mode 100644 index 00000000..6c8ebf2b --- /dev/null +++ b/dev/zka/HALKit/AMD64/HalDebugPort.cc @@ -0,0 +1,40 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +//! @file DebuggerPort.cxx +//! @brief UART debug via packets. + +#include +#include + +// after that we have start of additional data. + +namespace Kernel +{ + void rt_debug_listen(DebuggerPortHeader* theHook) noexcept + { + if (theHook == nullptr) + return; + + for (UInt32 i = 0U; i < kDebugMaxPorts; ++i) + { + HAL::Out16(theHook->fPort[i], kDebugMag0); + HAL::rt_wait_400ns(); + + HAL::Out16(theHook->fPort[i], kDebugMag1); + HAL::rt_wait_400ns(); + + HAL::Out16(theHook->fPort[i], kDebugMag2); + HAL::rt_wait_400ns(); + + HAL::Out16(theHook->fPort[i], kDebugMag3); + HAL::rt_wait_400ns(); + + if (HAL::In16(theHook->fPort[i] != kDebugUnboundPort)) + theHook->fBoundCnt++; + } + } +} // namespace Kernel diff --git a/dev/zka/HALKit/AMD64/HalDebugPort.cxx b/dev/zka/HALKit/AMD64/HalDebugPort.cxx deleted file mode 100644 index 4e28f637..00000000 --- a/dev/zka/HALKit/AMD64/HalDebugPort.cxx +++ /dev/null @@ -1,40 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -//! @file DebuggerPort.cxx -//! @brief UART debug via packets. - -#include -#include - -// after that we have start of additional data. - -namespace Kernel -{ - void rt_debug_listen(DebuggerPortHeader* theHook) noexcept - { - if (theHook == nullptr) - return; - - for (UInt32 i = 0U; i < kDebugMaxPorts; ++i) - { - HAL::Out16(theHook->fPort[i], kDebugMag0); - HAL::rt_wait_400ns(); - - HAL::Out16(theHook->fPort[i], kDebugMag1); - HAL::rt_wait_400ns(); - - HAL::Out16(theHook->fPort[i], kDebugMag2); - HAL::rt_wait_400ns(); - - HAL::Out16(theHook->fPort[i], kDebugMag3); - HAL::rt_wait_400ns(); - - if (HAL::In16(theHook->fPort[i] != kDebugUnboundPort)) - theHook->fBoundCnt++; - } - } -} // namespace Kernel diff --git a/dev/zka/HALKit/AMD64/HalDescriptorLoader.cc b/dev/zka/HALKit/AMD64/HalDescriptorLoader.cc new file mode 100644 index 00000000..f0eff4e1 --- /dev/null +++ b/dev/zka/HALKit/AMD64/HalDescriptorLoader.cc @@ -0,0 +1,120 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +namespace Kernel::HAL +{ + namespace Detail + { + STATIC ::Kernel::Detail::AMD64::InterruptDescriptorAMD64 + kInterruptVectorTable[kKernelIdtSize]; + + STATIC void hal_set_irq_mask(UInt8 irql); + STATIC void hal_clear_irq_mask(UInt8 irql); + + STATIC Void hal_enable_pit(UInt16 ticks) noexcept + { + if (ticks == 0) + ticks = 1000; + + // Configure PIT to receieve scheduler interrupts. + + UInt16 cCommonDivisor = kPITFrequency / ticks; // 100 Hz. + + HAL::Out8(kPITControlPort, 0x36); // Command to PIT + HAL::Out8(kPITChannel0Port, cCommonDivisor & 0xFF); // Send low byte + HAL::Out8(kPITChannel0Port, (cCommonDivisor >> 8) & 0xFF); // Send high byte + + hal_clear_irq_mask(32); + } + + STATIC void hal_set_irq_mask(UInt8 irql) + { + UInt16 port; + UInt8 value; + + if (irql < 8) + { + port = kPICData; + } + else + { + port = kPIC2Data; + irql -= 8; + } + + value = In8(port) | (1 << irql); + Out8(port, value); + } + + STATIC void hal_clear_irq_mask(UInt8 irql) + { + UInt16 port; + UInt8 value; + + if (irql < 8) + { + port = kPICData; + } + else + { + port = kPIC2Data; + irql -= 8; + } + + value = In8(port) & ~(1 << irql); + Out8(port, value); + } + } // namespace Detail + + /// @brief Loads the provided Global Descriptor Table. + /// @param gdt + /// @return + Void GDTLoader::Load(RegisterGDT& gdt) + { + hal_load_gdt(gdt); + } + + Void IDTLoader::Load(Register64& idt) + { + const auto kPITTickForScheduler = 100; + + volatile ::Kernel::UIntPtr** ptr_ivt = (volatile ::Kernel::UIntPtr**)idt.Base; + + for (UInt16 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)-1; + + hal_load_idt(idt); + + Detail::hal_enable_pit(kPITTickForScheduler); + } + + void GDTLoader::Load(Ref& gdt) + { + GDTLoader::Load(gdt.Leak()); + } + + void IDTLoader::Load(Ref& idt) + { + IDTLoader::Load(idt.Leak()); + } +} // namespace Kernel::HAL diff --git a/dev/zka/HALKit/AMD64/HalDescriptorLoader.cxx b/dev/zka/HALKit/AMD64/HalDescriptorLoader.cxx deleted file mode 100644 index 822d7dac..00000000 --- a/dev/zka/HALKit/AMD64/HalDescriptorLoader.cxx +++ /dev/null @@ -1,120 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -namespace Kernel::HAL -{ - namespace Detail - { - STATIC ::Kernel::Detail::AMD64::InterruptDescriptorAMD64 - kInterruptVectorTable[kKernelIdtSize]; - - STATIC void hal_set_irq_mask(UInt8 irql); - STATIC void hal_clear_irq_mask(UInt8 irql); - - STATIC Void hal_enable_pit(UInt16 ticks) noexcept - { - if (ticks == 0) - ticks = 1000; - - // Configure PIT to receieve scheduler interrupts. - - UInt16 cCommonDivisor = kPITFrequency / ticks; // 100 Hz. - - HAL::Out8(kPITControlPort, 0x36); // Command to PIT - HAL::Out8(kPITChannel0Port, cCommonDivisor & 0xFF); // Send low byte - HAL::Out8(kPITChannel0Port, (cCommonDivisor >> 8) & 0xFF); // Send high byte - - hal_clear_irq_mask(32); - } - - STATIC void hal_set_irq_mask(UInt8 irql) - { - UInt16 port; - UInt8 value; - - if (irql < 8) - { - port = kPICData; - } - else - { - port = kPIC2Data; - irql -= 8; - } - - value = In8(port) | (1 << irql); - Out8(port, value); - } - - STATIC void hal_clear_irq_mask(UInt8 irql) - { - UInt16 port; - UInt8 value; - - if (irql < 8) - { - port = kPICData; - } - else - { - port = kPIC2Data; - irql -= 8; - } - - value = In8(port) & ~(1 << irql); - Out8(port, value); - } - } // namespace Detail - - /// @brief Loads the provided Global Descriptor Table. - /// @param gdt - /// @return - Void GDTLoader::Load(RegisterGDT& gdt) - { - hal_load_gdt(gdt); - } - - Void IDTLoader::Load(Register64& idt) - { - const auto kPITTickForScheduler = 100; - - volatile ::Kernel::UIntPtr** ptr_ivt = (volatile ::Kernel::UIntPtr**)idt.Base; - - for (UInt16 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)-1; - - hal_load_idt(idt); - - Detail::hal_enable_pit(kPITTickForScheduler); - } - - void GDTLoader::Load(Ref& gdt) - { - GDTLoader::Load(gdt.Leak()); - } - - void IDTLoader::Load(Ref& idt) - { - IDTLoader::Load(idt.Leak()); - } -} // namespace Kernel::HAL diff --git a/dev/zka/HALKit/AMD64/HalKernelMain.cc b/dev/zka/HALKit/AMD64/HalKernelMain.cc new file mode 100644 index 00000000..08d91062 --- /dev/null +++ b/dev/zka/HALKit/AMD64/HalKernelMain.cc @@ -0,0 +1,108 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Kernel::HAL +{ + /// @brief Gets the system cores using the MADT. + /// @param rsp_ptr The 'RSD PTR' data structure. + EXTERN void mp_get_cores(Kernel::voidPtr rsp_ptr) noexcept; +} // namespace Kernel::HAL + +namespace Kernel +{ + EXTERN UserProcessScheduler* kProcessScheduler; + EXTERN HardwareThreadScheduler* kHardwareThreadScheduler; +} // namespace Kernel + +EXTERN_C Kernel::VoidPtr kInterruptVectorTable[]; +EXTERN_C Kernel::VoidPtr mp_user_switch_proc; +EXTERN_C Kernel::Char mp_user_switch_proc_stack_begin[]; + +/// @brief Kernel init procedure. +EXTERN_C void hal_init_platform( + Kernel::HEL::HANDOVER_INFO_HEADER* HandoverHeader) +{ + kHandoverHeader = HandoverHeader; + + Kernel::kProcessScheduler = nullptr; + Kernel::kHardwareThreadScheduler = nullptr; + + if (kHandoverHeader->f_Magic != kHandoverMagic && + kHandoverHeader->f_Version != kHandoverVersion) + { + return; + } + + /************************************** */ + /* INITIALIZE BIT MAP. */ + /************************************** */ + + kKernelBitMpSize = kHandoverHeader->f_BitMapSize; + kKernelBitMpStart = reinterpret_cast( + reinterpret_cast(kHandoverHeader->f_BitMapStart)); + + /************************************** */ + /* INITIALIZE GDT AND SEGMENTS. */ + /************************************** */ + + STATIC CONST auto cEntriesCount = 6; + + /* GDT, mostly descriptors for user and kernel segments. */ + STATIC Kernel::HAL::Detail::ZKA_GDT_ENTRY ALIGN(0x08) cGdt[cEntriesCount] = { + {.fLimitLow = 0, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0x00, .fFlags = 0x00, .fBaseHigh = 0}, // Null entry + {.fLimitLow = 0xFFFF, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0x9A, .fFlags = 0xAF, .fBaseHigh = 0}, // Kernel code + {.fLimitLow = 0xFFFF, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0x92, .fFlags = 0xCF, .fBaseHigh = 0}, // Kernel data + {.fLimitLow = 0xFFFF, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0xF2, .fFlags = 0xCF, .fBaseHigh = 0}, // User data + {.fLimitLow = 0xFFFF, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0xFA, .fFlags = 0xAF, .fBaseHigh = 0}, // User code + }; + + // Load memory descriptors. + Kernel::HAL::RegisterGDT gdt_reg; + + gdt_reg.Base = reinterpret_cast(cGdt); + gdt_reg.Limit = (sizeof(Kernel::HAL::Detail::ZKA_GDT_ENTRY) * cEntriesCount) - 1; + + //! GDT will load hal_read_init after it successfully loads the segments. + Kernel::HAL::GDTLoader gdt_loader; + gdt_loader.Load(gdt_reg); + + Kernel::ke_stop(RUNTIME_CHECK_BOOTSTRAP); +} + +EXTERN_C Kernel::Void hal_real_init(Kernel::Void) noexcept +{ + /* Initialize filesystem. */ + Kernel::NeFileSystemMgr* mgr = Kernel::mm_new_class(); + Kernel::NeFileSystemMgr::Mount(mgr); + + /* Initialize scheduler. */ + Kernel::UserProcessHelper::InitializeScheduler(); + + /* Start any cores. */ + if (kHandoverHeader->f_HardwareTables.f_MultiProcessingEnabled) + Kernel::HAL::mp_get_cores(kHandoverHeader->f_HardwareTables.f_VendorPtr); + + /* Load OSLdr.exe here (TODO) */ + + Kernel::HAL::Register64 idt_reg; + idt_reg.Base = (Kernel::UIntPtr)kInterruptVectorTable; + + /* Load interrupts. */ + Kernel::HAL::IDTLoader idt_loader; + idt_loader.Load(idt_reg); + + while (Yes) + ; +} diff --git a/dev/zka/HALKit/AMD64/HalKernelMain.cxx b/dev/zka/HALKit/AMD64/HalKernelMain.cxx deleted file mode 100644 index 1a4fc830..00000000 --- a/dev/zka/HALKit/AMD64/HalKernelMain.cxx +++ /dev/null @@ -1,108 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Kernel::HAL -{ - /// @brief Gets the system cores using the MADT. - /// @param rsp_ptr The 'RSD PTR' data structure. - EXTERN void mp_get_cores(Kernel::voidPtr rsp_ptr) noexcept; -} // namespace Kernel::HAL - -namespace Kernel -{ - EXTERN UserProcessScheduler* kProcessScheduler; - EXTERN HardwareThreadScheduler* kHardwareThreadScheduler; -} // namespace Kernel - -EXTERN_C Kernel::VoidPtr kInterruptVectorTable[]; -EXTERN_C Kernel::VoidPtr mp_user_switch_proc; -EXTERN_C Kernel::Char mp_user_switch_proc_stack_begin[]; - -/// @brief Kernel init procedure. -EXTERN_C void hal_init_platform( - Kernel::HEL::HANDOVER_INFO_HEADER* HandoverHeader) -{ - kHandoverHeader = HandoverHeader; - - Kernel::kProcessScheduler = nullptr; - Kernel::kHardwareThreadScheduler = nullptr; - - if (kHandoverHeader->f_Magic != kHandoverMagic && - kHandoverHeader->f_Version != kHandoverVersion) - { - return; - } - - /************************************** */ - /* INITIALIZE BIT MAP. */ - /************************************** */ - - kKernelBitMpSize = kHandoverHeader->f_BitMapSize; - kKernelBitMpStart = reinterpret_cast( - reinterpret_cast(kHandoverHeader->f_BitMapStart)); - - /************************************** */ - /* INITIALIZE GDT AND SEGMENTS. */ - /************************************** */ - - STATIC CONST auto cEntriesCount = 6; - - /* GDT, mostly descriptors for user and kernel segments. */ - STATIC Kernel::HAL::Detail::ZKA_GDT_ENTRY ALIGN(0x08) cGdt[cEntriesCount] = { - {.fLimitLow = 0, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0x00, .fFlags = 0x00, .fBaseHigh = 0}, // Null entry - {.fLimitLow = 0xFFFF, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0x9A, .fFlags = 0xAF, .fBaseHigh = 0}, // Kernel code - {.fLimitLow = 0xFFFF, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0x92, .fFlags = 0xCF, .fBaseHigh = 0}, // Kernel data - {.fLimitLow = 0xFFFF, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0xF2, .fFlags = 0xCF, .fBaseHigh = 0}, // User data - {.fLimitLow = 0xFFFF, .fBaseLow = 0, .fBaseMid = 0, .fAccessByte = 0xFA, .fFlags = 0xAF, .fBaseHigh = 0}, // User code - }; - - // Load memory descriptors. - Kernel::HAL::RegisterGDT gdt_reg; - - gdt_reg.Base = reinterpret_cast(cGdt); - gdt_reg.Limit = (sizeof(Kernel::HAL::Detail::ZKA_GDT_ENTRY) * cEntriesCount) - 1; - - //! GDT will load hal_read_init after it successfully loads the segments. - Kernel::HAL::GDTLoader gdt_loader; - gdt_loader.Load(gdt_reg); - - Kernel::ke_stop(RUNTIME_CHECK_BOOTSTRAP); -} - -EXTERN_C Kernel::Void hal_real_init(Kernel::Void) noexcept -{ - /* Initialize filesystem. */ - Kernel::NeFileSystemMgr* mgr = Kernel::mm_new_class(); - Kernel::NeFileSystemMgr::Mount(mgr); - - /* Initialize scheduler. */ - Kernel::UserProcessHelper::InitializeScheduler(); - - /* Start any cores. */ - if (kHandoverHeader->f_HardwareTables.f_MultiProcessingEnabled) - Kernel::HAL::mp_get_cores(kHandoverHeader->f_HardwareTables.f_VendorPtr); - - /* Load OSLdr.exe here (TODO) */ - - Kernel::HAL::Register64 idt_reg; - idt_reg.Base = (Kernel::UIntPtr)kInterruptVectorTable; - - /* Load interrupts. */ - Kernel::HAL::IDTLoader idt_loader; - idt_loader.Load(idt_reg); - - while (Yes) - ; -} diff --git a/dev/zka/HALKit/AMD64/HalPagingMgr.cc b/dev/zka/HALKit/AMD64/HalPagingMgr.cc new file mode 100644 index 00000000..afc86eeb --- /dev/null +++ b/dev/zka/HALKit/AMD64/HalPagingMgr.cc @@ -0,0 +1,162 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: HalPagingMgr.cxx + Purpose: Platform Paging Manager.. + +------------------------------------------- */ + +#include +#include + +namespace Kernel::HAL +{ + typedef UInt32 PageTableIndex; + + /// \brief Page store type. + struct ZKA_PAGE_STORE final + { + struct + { + PDE* fPde{nullptr}; + PTE* fPte{nullptr}; + VoidPtr fVAddr{nullptr}; + } fInternalStore; + + Bool fStoreOp{No}; // Store operation in progress. + + bool IsValidPage(PTE* pte) + { + return pte && pte->Present; + } + + bool IsWRPage(PTE* pte) + { + return pte && pte->Wr; + } + + bool IsUserPage(PTE* pte) + { + return pte && pte->User; + } + + static ZKA_PAGE_STORE& The() + { + static ZKA_PAGE_STORE the; + return the; + } + }; + + /// \brief Retrieve the page status of a PTE. + STATIC Void mmi_page_status(PTE* pte) + { + kcout << (pte->Present ? "Present" : "Not Present") << endl; + kcout << (pte->Wr ? "W/R" : "Not W/R") << endl; + kcout << (pte->ExecDisable ? "NX" : "Not NX") << endl; + kcout << (pte->User ? "User" : "Not User") << endl; + } + + 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, UInt32 flags) + { + if (!virtual_address || + !flags) + return 0; + + // Constants for table index bits + const UInt64 cPmlIndexMask = 0x1FFULL; // Mask for PML4, PDPT, PD, PT index (9 bits) + const UInt64 cPtIndexMask = 0xFFFULL; // Mask for page table index (12 bits) + + UInt64 cr3 = (UInt64)hal_read_cr3(); + + ZKA_PAGE_STORE& page_store = ZKA_PAGE_STORE::The(); + + // Extract the indices from the virtual address + UInt64 pml4_index = ((UIntPtr)virtual_address >> 39) & cPmlIndexMask; + UInt64 pdpt_index = ((UIntPtr)virtual_address >> 30) & cPmlIndexMask; + UInt64 pd_index = ((UIntPtr)virtual_address >> 21) & cPmlIndexMask; + UInt64 pt_index = ((UIntPtr)virtual_address >> 12) & cPmlIndexMask; + + 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); + } + + const auto cPmlEntrySize = 8; + + // Read the PML4 entry from memory + UInt64 pml4_base = cr3 & ~cPtIndexMask; // CR3 points to the PML4 table base, mask off lower bits + UInt64 pml4_entry = (pml4_base + pml4_index * cPmlEntrySize); // Each entry is 8 bytes + + // Read the PDPT entry + UInt64 pdpt_base = pml4_entry & ~cPtIndexMask; // Get the PDPT base physical address + UInt64 pdpt_entry = (pdpt_base + pdpt_index * cPmlEntrySize); + + // Read the PD entry + UInt64 pd_base = pdpt_entry & ~cPtIndexMask; // Get the Page Directory base physical address + UInt64 pd_entry = (pd_base + pd_index * cPmlEntrySize); + + // Read the PT entry + UInt64 pt_base = pd_entry & ~cPtIndexMask; // Get the Page Table base physical address + UInt64 pt_entry = (pt_base + pt_index * cPmlEntrySize); + + // Lastly, grab the pte entry. + ZKA_PDE* pte_struct = reinterpret_cast(pt_base); + + return mmi_map_page_table_entry(virtual_address, flags, pte_struct->fEntries[pt_entry]); + } + + /// @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) + { + if (flags & ~eFlagsPresent) + pt_entry->Present = false; + else if (flags & eFlagsPresent) + pt_entry->Present = true; + + if (flags & eFlagsWr) + pt_entry->Wr = true; + else if (flags & ~eFlagsWr) + pt_entry->Wr = false; + + if (flags & eFlagsNX) + pt_entry->ExecDisable = true; + else if (flags & ~eFlagsNX) + pt_entry->ExecDisable = false; + + if (flags & eFlagsUser) + pt_entry->User = true; + else if (flags & ~eFlagsUser) + pt_entry->User = false; + + hal_invl_tlb(reinterpret_cast(pt_entry)); + + mmi_page_status(pt_entry); + + ZKA_PAGE_STORE& page_store = ZKA_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/zka/HALKit/AMD64/HalPagingMgr.cxx b/dev/zka/HALKit/AMD64/HalPagingMgr.cxx deleted file mode 100644 index fe6aea0f..00000000 --- a/dev/zka/HALKit/AMD64/HalPagingMgr.cxx +++ /dev/null @@ -1,162 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: HalPagingMgr.cxx - Purpose: Platform Paging Manager.. - -------------------------------------------- */ - -#include -#include - -namespace Kernel::HAL -{ - typedef UInt32 PageTableIndex; - - /// \brief Page store type. - struct ZKA_PAGE_STORE final - { - struct - { - PDE* fPde{nullptr}; - PTE* fPte{nullptr}; - VoidPtr fVAddr{nullptr}; - } fInternalStore; - - Bool fStoreOp{No}; // Store operation in progress. - - bool IsValidPage(PTE* pte) - { - return pte && pte->Present; - } - - bool IsWRPage(PTE* pte) - { - return pte && pte->Wr; - } - - bool IsUserPage(PTE* pte) - { - return pte && pte->User; - } - - static ZKA_PAGE_STORE& The() - { - static ZKA_PAGE_STORE the; - return the; - } - }; - - /// \brief Retrieve the page status of a PTE. - STATIC Void mmi_page_status(PTE* pte) - { - kcout << (pte->Present ? "Present" : "Not Present") << endl; - kcout << (pte->Wr ? "W/R" : "Not W/R") << endl; - kcout << (pte->ExecDisable ? "NX" : "Not NX") << endl; - kcout << (pte->User ? "User" : "Not User") << endl; - } - - 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, UInt32 flags) - { - if (!virtual_address || - !flags) - return 0; - - // Constants for table index bits - const UInt64 cPmlIndexMask = 0x1FFULL; // Mask for PML4, PDPT, PD, PT index (9 bits) - const UInt64 cPtIndexMask = 0xFFFULL; // Mask for page table index (12 bits) - - UInt64 cr3 = (UInt64)hal_read_cr3(); - - ZKA_PAGE_STORE& page_store = ZKA_PAGE_STORE::The(); - - // Extract the indices from the virtual address - UInt64 pml4_index = ((UIntPtr)virtual_address >> 39) & cPmlIndexMask; - UInt64 pdpt_index = ((UIntPtr)virtual_address >> 30) & cPmlIndexMask; - UInt64 pd_index = ((UIntPtr)virtual_address >> 21) & cPmlIndexMask; - UInt64 pt_index = ((UIntPtr)virtual_address >> 12) & cPmlIndexMask; - - 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); - } - - const auto cPmlEntrySize = 8; - - // Read the PML4 entry from memory - UInt64 pml4_base = cr3 & ~cPtIndexMask; // CR3 points to the PML4 table base, mask off lower bits - UInt64 pml4_entry = (pml4_base + pml4_index * cPmlEntrySize); // Each entry is 8 bytes - - // Read the PDPT entry - UInt64 pdpt_base = pml4_entry & ~cPtIndexMask; // Get the PDPT base physical address - UInt64 pdpt_entry = (pdpt_base + pdpt_index * cPmlEntrySize); - - // Read the PD entry - UInt64 pd_base = pdpt_entry & ~cPtIndexMask; // Get the Page Directory base physical address - UInt64 pd_entry = (pd_base + pd_index * cPmlEntrySize); - - // Read the PT entry - UInt64 pt_base = pd_entry & ~cPtIndexMask; // Get the Page Table base physical address - UInt64 pt_entry = (pt_base + pt_index * cPmlEntrySize); - - // Lastly, grab the pte entry. - ZKA_PDE* pte_struct = reinterpret_cast(pt_base); - - return mmi_map_page_table_entry(virtual_address, flags, pte_struct->fEntries[pt_entry]); - } - - /// @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) - { - if (flags & ~eFlagsPresent) - pt_entry->Present = false; - else if (flags & eFlagsPresent) - pt_entry->Present = true; - - if (flags & eFlagsWr) - pt_entry->Wr = true; - else if (flags & ~eFlagsWr) - pt_entry->Wr = false; - - if (flags & eFlagsNX) - pt_entry->ExecDisable = true; - else if (flags & ~eFlagsNX) - pt_entry->ExecDisable = false; - - if (flags & eFlagsUser) - pt_entry->User = true; - else if (flags & ~eFlagsUser) - pt_entry->User = false; - - hal_invl_tlb(reinterpret_cast(pt_entry)); - - mmi_page_status(pt_entry); - - ZKA_PAGE_STORE& page_store = ZKA_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/zka/HALKit/AMD64/HalSchedulerCore.cc b/dev/zka/HALKit/AMD64/HalSchedulerCore.cc new file mode 100644 index 00000000..214b889b --- /dev/null +++ b/dev/zka/HALKit/AMD64/HalSchedulerCore.cc @@ -0,0 +1,56 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +using namespace Kernel; + +Void UserProcess::SetImageStart(VoidPtr imageStart) noexcept +{ + if (imageStart == nullptr) + this->Crash(); + + this->Image = imageStart; +} + +namespace Kernel +{ + /***********************************************************************************/ + /// @brief Unimplemented function (crashes by default) + /// @param + /***********************************************************************************/ + + EXTERN_C Void __zka_pure_call(void) + { + UserProcessScheduler::The().CurrentProcess().Leak().Crash(); + } + + Bool hal_check_stack(HAL::StackFramePtr stack_ptr) + { + if (!stack_ptr) + return false; + + return true; + } + + /// @brief Wakes up thread. + /// Wakes up thread from the hang state. + Void mp_wakeup_thread(HAL::StackFrame* 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) + { + while (Yes) + { + /* Nothing to do, code is spinning */ + } + } +} // namespace Kernel diff --git a/dev/zka/HALKit/AMD64/HalSchedulerCore.cxx b/dev/zka/HALKit/AMD64/HalSchedulerCore.cxx deleted file mode 100644 index e5396c92..00000000 --- a/dev/zka/HALKit/AMD64/HalSchedulerCore.cxx +++ /dev/null @@ -1,56 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -using namespace Kernel; - -Void UserProcess::SetImageStart(VoidPtr imageStart) noexcept -{ - if (imageStart == nullptr) - this->Crash(); - - this->Image = imageStart; -} - -namespace Kernel -{ - /***********************************************************************************/ - /// @brief Unimplemented function (crashes by default) - /// @param - /***********************************************************************************/ - - EXTERN_C Void __zka_pure_call(void) - { - UserProcessScheduler::The().CurrentProcess().Leak().Crash(); - } - - Bool hal_check_stack(HAL::StackFramePtr stack_ptr) - { - if (!stack_ptr) - return false; - - return true; - } - - /// @brief Wakes up thread. - /// Wakes up thread from the hang state. - Void mp_wakeup_thread(HAL::StackFrame* 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) - { - while (Yes) - { - /* Nothing to do, code is spinning */ - } - } -} // namespace Kernel diff --git a/dev/zka/HALKit/AMD64/HalTimer.cc b/dev/zka/HALKit/AMD64/HalTimer.cc new file mode 100644 index 00000000..6d552a09 --- /dev/null +++ b/dev/zka/HALKit/AMD64/HalTimer.cc @@ -0,0 +1,86 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: HalTimer.cxx + Purpose: HAL timer + + Revision History: + + 07/07/24: Added file (amlel) + +------------------------------------------- */ + +#include +#include +#include + +// timer slot 0 + +#define cHPETCounterRegValue (0x00) +#define cHPETConfigRegValue (0x20) +#define cHPETCompRegValue (0x24) +#define cHPETInterruptRegValue (0x2C) + +///! BUGS: 0 +///! @file HalTimer.cxx +///! @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 + +using namespace Kernel; + +HardwareTimer::HardwareTimer(Int64 ms) + : fWaitFor(ms) +{ + auto power = PowerFactoryInterface(kHandoverHeader->f_HardwareTables.f_VendorPtr); + + auto hpet = (Detail::HPET_BLOCK*)power.Find("HPET").Leak().Leak(); + MUST_PASS(hpet); + + fDigitalTimer = (IntPtr*)hpet->address.Address; +} + +HardwareTimer::~HardwareTimer() +{ + fDigitalTimer = nullptr; + fWaitFor = 0; +} + +Int32 HardwareTimer::Wait() noexcept +{ + if (fWaitFor < 1) + return -1; + + // if not enabled yet. + if (!(*(fDigitalTimer + cHPETConfigRegValue) & (1 << 0))) + { + *(fDigitalTimer + cHPETConfigRegValue) |= (1 << 0); // enable it + *(fDigitalTimer + cHPETConfigRegValue) |= (1 << 3); // one shot conf + } + + UInt64 ticks = fWaitFor / ((*(fDigitalTimer) >> 32) & __UINT32_MAX__); + UInt64 prev = *(fDigitalTimer + cHPETCounterRegValue); + + prev += ticks; + + while (*(fDigitalTimer + cHPETCounterRegValue) < (ticks)) + ; + + return 0; +} diff --git a/dev/zka/HALKit/AMD64/HalTimer.cxx b/dev/zka/HALKit/AMD64/HalTimer.cxx deleted file mode 100644 index 75102c15..00000000 --- a/dev/zka/HALKit/AMD64/HalTimer.cxx +++ /dev/null @@ -1,86 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: HalTimer.cxx - Purpose: HAL timer - - Revision History: - - 07/07/24: Added file (amlel) - -------------------------------------------- */ - -#include -#include -#include - -// timer slot 0 - -#define cHPETCounterRegValue (0x00) -#define cHPETConfigRegValue (0x20) -#define cHPETCompRegValue (0x24) -#define cHPETInterruptRegValue (0x2C) - -///! BUGS: 0 -///! @file HalTimer.cxx -///! @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 - -using namespace Kernel; - -HardwareTimer::HardwareTimer(Int64 ms) - : fWaitFor(ms) -{ - auto power = PowerFactoryInterface(kHandoverHeader->f_HardwareTables.f_VendorPtr); - - auto hpet = (Detail::HPET_BLOCK*)power.Find("HPET").Leak().Leak(); - MUST_PASS(hpet); - - fDigitalTimer = (IntPtr*)hpet->address.Address; -} - -HardwareTimer::~HardwareTimer() -{ - fDigitalTimer = nullptr; - fWaitFor = 0; -} - -Int32 HardwareTimer::Wait() noexcept -{ - if (fWaitFor < 1) - return -1; - - // if not enabled yet. - if (!(*(fDigitalTimer + cHPETConfigRegValue) & (1 << 0))) - { - *(fDigitalTimer + cHPETConfigRegValue) |= (1 << 0); // enable it - *(fDigitalTimer + cHPETConfigRegValue) |= (1 << 3); // one shot conf - } - - UInt64 ticks = fWaitFor / ((*(fDigitalTimer) >> 32) & __UINT32_MAX__); - UInt64 prev = *(fDigitalTimer + cHPETCounterRegValue); - - prev += ticks; - - while (*(fDigitalTimer + cHPETCounterRegValue) < (ticks)) - ; - - return 0; -} diff --git a/dev/zka/HALKit/AMD64/Hypervisor.h b/dev/zka/HALKit/AMD64/Hypervisor.h new file mode 100644 index 00000000..5a0a9aeb --- /dev/null +++ b/dev/zka/HALKit/AMD64/Hypervisor.h @@ -0,0 +1,25 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#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 diff --git a/dev/zka/HALKit/AMD64/Hypervisor.hxx b/dev/zka/HALKit/AMD64/Hypervisor.hxx deleted file mode 100644 index f4c0c5ac..00000000 --- a/dev/zka/HALKit/AMD64/Hypervisor.hxx +++ /dev/null @@ -1,25 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#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 diff --git a/dev/zka/HALKit/AMD64/PCI/DMA.cc b/dev/zka/HALKit/AMD64/PCI/DMA.cc new file mode 100644 index 00000000..056cdf19 --- /dev/null +++ b/dev/zka/HALKit/AMD64/PCI/DMA.cc @@ -0,0 +1,82 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +namespace Kernel +{ + DMAWrapper::operator bool() + { + return fAddress; + } + + bool DMAWrapper::operator!() + { + return !fAddress; + } + + Boolean DMAWrapper::Check(UIntPtr offset) const + { + if (!fAddress) + return false; + if (offset == 0) + return true; + + kcout << "[DMAWrapper::IsIn] Checking offset..\n"; + return reinterpret_cast(fAddress) >= offset; + } + + bool DMAWrapper::Write(const UIntPtr& bit, const UIntPtr& offset) + { + if (!fAddress) + return false; + + kcout << "[DMAWrapper::Write] Writing at address..\n"; + + auto addr = + (volatile UIntPtr*)(reinterpret_cast(fAddress) + offset); + *addr = bit; + + return true; + } + + UIntPtr DMAWrapper::Read(const UIntPtr& offset) + { + kcout << "[DMAWrapper::Read] checking fAddress..\n"; + if (!fAddress) + return 0; + + kcout << "[DMAWrapper::Read] Reading fAddress..\n"; + return *(volatile UIntPtr*)(reinterpret_cast(fAddress) + offset); + ; + } + + UIntPtr DMAWrapper::operator[](const UIntPtr& offset) + { + return this->Read(offset); + } + + OwnPtr> DMAFactory::Construct(OwnPtr& dma) + { + if (!dma) + return {}; + + OwnPtr> dmaOwnPtr = + make_ptr, char*>(reinterpret_cast(dma->fAddress)); + + if (!dmaOwnPtr) + return {}; + + kcout << "Returning the new OwnPtr>!\r"; + return dmaOwnPtr; + } + + DMAWrapper& DMAWrapper::operator=(voidPtr Ptr) + { + fAddress = Ptr; + return *this; + } +} // namespace Kernel diff --git a/dev/zka/HALKit/AMD64/PCI/DMA.cxx b/dev/zka/HALKit/AMD64/PCI/DMA.cxx deleted file mode 100644 index 3670b7e4..00000000 --- a/dev/zka/HALKit/AMD64/PCI/DMA.cxx +++ /dev/null @@ -1,82 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -namespace Kernel -{ - DMAWrapper::operator bool() - { - return fAddress; - } - - bool DMAWrapper::operator!() - { - return !fAddress; - } - - Boolean DMAWrapper::Check(UIntPtr offset) const - { - if (!fAddress) - return false; - if (offset == 0) - return true; - - kcout << "[DMAWrapper::IsIn] Checking offset..\n"; - return reinterpret_cast(fAddress) >= offset; - } - - bool DMAWrapper::Write(const UIntPtr& bit, const UIntPtr& offset) - { - if (!fAddress) - return false; - - kcout << "[DMAWrapper::Write] Writing at address..\n"; - - auto addr = - (volatile UIntPtr*)(reinterpret_cast(fAddress) + offset); - *addr = bit; - - return true; - } - - UIntPtr DMAWrapper::Read(const UIntPtr& offset) - { - kcout << "[DMAWrapper::Read] checking fAddress..\n"; - if (!fAddress) - return 0; - - kcout << "[DMAWrapper::Read] Reading fAddress..\n"; - return *(volatile UIntPtr*)(reinterpret_cast(fAddress) + offset); - ; - } - - UIntPtr DMAWrapper::operator[](const UIntPtr& offset) - { - return this->Read(offset); - } - - OwnPtr> DMAFactory::Construct(OwnPtr& dma) - { - if (!dma) - return {}; - - OwnPtr> dmaOwnPtr = - make_ptr, char*>(reinterpret_cast(dma->fAddress)); - - if (!dmaOwnPtr) - return {}; - - kcout << "Returning the new OwnPtr>!\r"; - return dmaOwnPtr; - } - - DMAWrapper& DMAWrapper::operator=(voidPtr Ptr) - { - fAddress = Ptr; - return *this; - } -} // namespace Kernel diff --git a/dev/zka/HALKit/AMD64/PCI/Database.cc b/dev/zka/HALKit/AMD64/PCI/Database.cc new file mode 100644 index 00000000..897c51f4 --- /dev/null +++ b/dev/zka/HALKit/AMD64/PCI/Database.cc @@ -0,0 +1,11 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +namespace Kernel +{ +} diff --git a/dev/zka/HALKit/AMD64/PCI/Database.cxx b/dev/zka/HALKit/AMD64/PCI/Database.cxx deleted file mode 100644 index 5441397c..00000000 --- a/dev/zka/HALKit/AMD64/PCI/Database.cxx +++ /dev/null @@ -1,11 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -namespace Kernel -{ -} diff --git a/dev/zka/HALKit/AMD64/PCI/Device.cc b/dev/zka/HALKit/AMD64/PCI/Device.cc new file mode 100644 index 00000000..19b0886c --- /dev/null +++ b/dev/zka/HALKit/AMD64/PCI/Device.cc @@ -0,0 +1,139 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +Kernel::UInt ZKA_PCIReadRaw(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::Out32((Kernel::UShort)Kernel::PCI::PciConfigKind::ConfigAddress, + target); + + return Kernel::HAL::In32((Kernel::UShort)Kernel::PCI::PciConfigKind::ConfigData); +} + +void ZKA_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 & ~3); + + Kernel::HAL::Out32((Kernel::UShort)Kernel::PCI::PciConfigKind::ConfigAddress, + target); +} + +#define PCI_BAR_IO 0x01 +#define PCI_BAR_LOWMEM 0x02 +#define PCI_BAR_64 0x04 +#define PCI_BAR_PREFETCH 0x08 + +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) + { + ZKA_PCISetCfgTarget(bar, fBus, fDevice, fFunction); + + if (sz == 4) + return HAL::In32((UShort)PciConfigKind::ConfigData + (bar & 3)); + if (sz == 2) + return HAL::In16((UShort)PciConfigKind::ConfigData + (bar & 3)); + if (sz == 1) + return HAL::In8((UShort)PciConfigKind::ConfigData + (bar & 3)); + + return 0xFFFF; + } + + void Device::Write(UInt bar, UIntPtr data, Size sz) + { + ZKA_PCISetCfgTarget(bar, fBus, fDevice, fFunction); + + if (sz == 4) + HAL::Out32((UShort)PciConfigKind::ConfigData + (fBar & 3), (UInt)data); + if (sz == 2) + HAL::Out16((UShort)PciConfigKind::ConfigData + (fBar & 3), (UShort)data); + if (sz == 1) + HAL::Out8((UShort)PciConfigKind::ConfigData + (fBar & 3), (UChar)data); + } + + UShort Device::DeviceId() + { + return (UShort)(ZKA_PCIReadRaw(0x0 >> 16, fBus, fDevice, fFunction)); + } + + UShort Device::VendorId() + { + return (UShort)(ZKA_PCIReadRaw(0x0, fBus, fDevice, fFunction) >> 16); + } + + UShort Device::InterfaceId() + { + return (UShort)(ZKA_PCIReadRaw(0x0, fBus, fDevice, fFunction) >> 16); + } + + UChar Device::Class() + { + return (UChar)(ZKA_PCIReadRaw(0x08, fBus, fDevice, fFunction) >> 24); + } + + UChar Device::Subclass() + { + return (UChar)(ZKA_PCIReadRaw(0x08, fBus, fDevice, fFunction) >> 16); + } + + UChar Device::ProgIf() + { + return (UChar)(ZKA_PCIReadRaw(0x08, fBus, fDevice, fFunction) >> 8); + } + + UChar Device::HeaderType() + { + return (UChar)(ZKA_PCIReadRaw(0xC, fBus, fDevice, fFunction) >> 16); + } + + void Device::EnableMmio(UInt32 bar_in) + { + bool enable = Read(bar_in, sizeof(UChar)) | (1 << 1); + Write(bar_in, enable, sizeof(UShort)); + } + + void Device::BecomeBusMaster(UInt32 bar_in) + { + bool enable = Read(bar_in, sizeof(UShort)) | (1 << 2); + Write(bar_in, enable, sizeof(UShort)); + } + + UInt32 Device::Bar(UInt32 bar_in) + { + UInt32 bar = ZKA_PCIReadRaw(bar_in, fBus, fDevice, fFunction); + return bar; + } + + UShort Device::Vendor() + { + UShort vendor = VendorId(); + + if (vendor != (UShort)PciConfigKind::Invalid) + fDevice = (UShort)Read(0x0, sizeof(UShort)); + + return fDevice; + } + + Device::operator bool() + { + return VendorId() != (UShort)PciConfigKind::Invalid; + } +} // namespace Kernel::PCI diff --git a/dev/zka/HALKit/AMD64/PCI/Device.cxx b/dev/zka/HALKit/AMD64/PCI/Device.cxx deleted file mode 100644 index d55683d5..00000000 --- a/dev/zka/HALKit/AMD64/PCI/Device.cxx +++ /dev/null @@ -1,139 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -Kernel::UInt ZKA_PCIReadRaw(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::Out32((Kernel::UShort)Kernel::PCI::PciConfigKind::ConfigAddress, - target); - - return Kernel::HAL::In32((Kernel::UShort)Kernel::PCI::PciConfigKind::ConfigData); -} - -void ZKA_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 & ~3); - - Kernel::HAL::Out32((Kernel::UShort)Kernel::PCI::PciConfigKind::ConfigAddress, - target); -} - -#define PCI_BAR_IO 0x01 -#define PCI_BAR_LOWMEM 0x02 -#define PCI_BAR_64 0x04 -#define PCI_BAR_PREFETCH 0x08 - -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) - { - ZKA_PCISetCfgTarget(bar, fBus, fDevice, fFunction); - - if (sz == 4) - return HAL::In32((UShort)PciConfigKind::ConfigData + (bar & 3)); - if (sz == 2) - return HAL::In16((UShort)PciConfigKind::ConfigData + (bar & 3)); - if (sz == 1) - return HAL::In8((UShort)PciConfigKind::ConfigData + (bar & 3)); - - return 0xFFFF; - } - - void Device::Write(UInt bar, UIntPtr data, Size sz) - { - ZKA_PCISetCfgTarget(bar, fBus, fDevice, fFunction); - - if (sz == 4) - HAL::Out32((UShort)PciConfigKind::ConfigData + (fBar & 3), (UInt)data); - if (sz == 2) - HAL::Out16((UShort)PciConfigKind::ConfigData + (fBar & 3), (UShort)data); - if (sz == 1) - HAL::Out8((UShort)PciConfigKind::ConfigData + (fBar & 3), (UChar)data); - } - - UShort Device::DeviceId() - { - return (UShort)(ZKA_PCIReadRaw(0x0 >> 16, fBus, fDevice, fFunction)); - } - - UShort Device::VendorId() - { - return (UShort)(ZKA_PCIReadRaw(0x0, fBus, fDevice, fFunction) >> 16); - } - - UShort Device::InterfaceId() - { - return (UShort)(ZKA_PCIReadRaw(0x0, fBus, fDevice, fFunction) >> 16); - } - - UChar Device::Class() - { - return (UChar)(ZKA_PCIReadRaw(0x08, fBus, fDevice, fFunction) >> 24); - } - - UChar Device::Subclass() - { - return (UChar)(ZKA_PCIReadRaw(0x08, fBus, fDevice, fFunction) >> 16); - } - - UChar Device::ProgIf() - { - return (UChar)(ZKA_PCIReadRaw(0x08, fBus, fDevice, fFunction) >> 8); - } - - UChar Device::HeaderType() - { - return (UChar)(ZKA_PCIReadRaw(0xC, fBus, fDevice, fFunction) >> 16); - } - - void Device::EnableMmio(UInt32 bar_in) - { - bool enable = Read(bar_in, sizeof(UChar)) | (1 << 1); - Write(bar_in, enable, sizeof(UShort)); - } - - void Device::BecomeBusMaster(UInt32 bar_in) - { - bool enable = Read(bar_in, sizeof(UShort)) | (1 << 2); - Write(bar_in, enable, sizeof(UShort)); - } - - UInt32 Device::Bar(UInt32 bar_in) - { - UInt32 bar = ZKA_PCIReadRaw(bar_in, fBus, fDevice, fFunction); - return bar; - } - - UShort Device::Vendor() - { - UShort vendor = VendorId(); - - if (vendor != (UShort)PciConfigKind::Invalid) - fDevice = (UShort)Read(0x0, sizeof(UShort)); - - return fDevice; - } - - Device::operator bool() - { - return VendorId() != (UShort)PciConfigKind::Invalid; - } -} // namespace Kernel::PCI diff --git a/dev/zka/HALKit/AMD64/PCI/Express.cc b/dev/zka/HALKit/AMD64/PCI/Express.cc new file mode 100644 index 00000000..c1481616 --- /dev/null +++ b/dev/zka/HALKit/AMD64/PCI/Express.cc @@ -0,0 +1,11 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +namespace Kernel +{ +} diff --git a/dev/zka/HALKit/AMD64/PCI/Express.cxx b/dev/zka/HALKit/AMD64/PCI/Express.cxx deleted file mode 100644 index b1f69a6e..00000000 --- a/dev/zka/HALKit/AMD64/PCI/Express.cxx +++ /dev/null @@ -1,11 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -namespace Kernel -{ -} diff --git a/dev/zka/HALKit/AMD64/PCI/IO.cc b/dev/zka/HALKit/AMD64/PCI/IO.cc new file mode 100644 index 00000000..c8535c54 --- /dev/null +++ b/dev/zka/HALKit/AMD64/PCI/IO.cc @@ -0,0 +1,7 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include diff --git a/dev/zka/HALKit/AMD64/PCI/IO.cxx b/dev/zka/HALKit/AMD64/PCI/IO.cxx deleted file mode 100644 index 43970e2a..00000000 --- a/dev/zka/HALKit/AMD64/PCI/IO.cxx +++ /dev/null @@ -1,7 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include diff --git a/dev/zka/HALKit/AMD64/PCI/Iterator.cc b/dev/zka/HALKit/AMD64/PCI/Iterator.cc new file mode 100644 index 00000000..edafe07b --- /dev/null +++ b/dev/zka/HALKit/AMD64/PCI/Iterator.cc @@ -0,0 +1,41 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +namespace Kernel::PCI +{ + Iterator::Iterator(const Types::PciDeviceKind& type) + { + // probe devices. + for (int bus = 0; bus < ZKA_BUS_COUNT; ++bus) + { + for (int device = 0; device < ZKA_DEVICE_COUNT; ++device) + { + for (int function = 0; function < ZKA_FUNCTION_COUNT; ++function) + { + auto bar = 0x00; + + Device dev(bus, device, function, bar); + + if (dev.Class() == (UChar)type) + { + fDevices[bus] = dev; + } + } + } + } + } + + Iterator::~Iterator() + { + } + + Ref Iterator::operator[](const Size& at) + { + return fDevices[at]; + } +} // namespace Kernel::PCI diff --git a/dev/zka/HALKit/AMD64/PCI/Iterator.cxx b/dev/zka/HALKit/AMD64/PCI/Iterator.cxx deleted file mode 100644 index f0d52c5d..00000000 --- a/dev/zka/HALKit/AMD64/PCI/Iterator.cxx +++ /dev/null @@ -1,41 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -namespace Kernel::PCI -{ - Iterator::Iterator(const Types::PciDeviceKind& type) - { - // probe devices. - for (int bus = 0; bus < ZKA_BUS_COUNT; ++bus) - { - for (int device = 0; device < ZKA_DEVICE_COUNT; ++device) - { - for (int function = 0; function < ZKA_FUNCTION_COUNT; ++function) - { - auto bar = 0x00; - - Device dev(bus, device, function, bar); - - if (dev.Class() == (UChar)type) - { - fDevices[bus] = dev; - } - } - } - } - } - - Iterator::~Iterator() - { - } - - Ref Iterator::operator[](const Size& at) - { - return fDevices[at]; - } -} // namespace Kernel::PCI diff --git a/dev/zka/HALKit/AMD64/PCI/PCI.cc b/dev/zka/HALKit/AMD64/PCI/PCI.cc new file mode 100644 index 00000000..7e056bf9 --- /dev/null +++ b/dev/zka/HALKit/AMD64/PCI/PCI.cc @@ -0,0 +1,7 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include diff --git a/dev/zka/HALKit/AMD64/PCI/PCI.cxx b/dev/zka/HALKit/AMD64/PCI/PCI.cxx deleted file mode 100644 index 02ba1e73..00000000 --- a/dev/zka/HALKit/AMD64/PCI/PCI.cxx +++ /dev/null @@ -1,7 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include diff --git a/dev/zka/HALKit/AMD64/Paging.h b/dev/zka/HALKit/AMD64/Paging.h new file mode 100644 index 00000000..0d109bb0 --- /dev/null +++ b/dev/zka/HALKit/AMD64/Paging.h @@ -0,0 +1,99 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +/** --------------------------------------------------- + + * THIS FILE CONTAINS CODE FOR X86_64 PAGING. + +------------------------------------------------------- */ + +#include + +#ifndef kPageMax +#define kPageMax (0x200) +#endif //! kPageMax + +#ifndef kPageAlign +#define kPageAlign (0x08) +#endif //! kPageAlign + +#ifndef kPageSize +#define kPageSize (0x100) +#endif // !kPageSize + +#ifndef kAlign +#define kAlign __BIGGEST_ALIGNMENT__ +#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 +{ + /// @brief Final page entry (Not PML, PDPT) + struct PACKED ZKA_PTE final + { + UInt64 Present : 1; + UInt64 Wr : 1; + UInt64 User : 1; + UInt64 Wt : 1; + UInt64 Cache : 1; + UInt64 Accessed : 1; + UInt64 Dirty : 1; + UInt64 MemoryType : 1; + UInt64 Global : 1; + UInt64 Resvered1 : 3; + UInt64 PhysicalAddress : 36; + UInt64 Reserved2 : 10; + UInt64 ProtectionKey : 5; + UInt64 ExecDisable : 1; + }; + + 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 ZKA_PDE final + { + ZKA_PTE* 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::ZKA_PTE PTE; + typedef HAL::ZKA_PDE PDE; +} // namespace Kernel diff --git a/dev/zka/HALKit/AMD64/Paging.hxx b/dev/zka/HALKit/AMD64/Paging.hxx deleted file mode 100644 index 2720bbf9..00000000 --- a/dev/zka/HALKit/AMD64/Paging.hxx +++ /dev/null @@ -1,99 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -/** --------------------------------------------------- - - * THIS FILE CONTAINS CODE FOR X86_64 PAGING. - -------------------------------------------------------- */ - -#include - -#ifndef kPageMax -#define kPageMax (0x200) -#endif //! kPageMax - -#ifndef kPageAlign -#define kPageAlign (0x08) -#endif //! kPageAlign - -#ifndef kPageSize -#define kPageSize (0x100) -#endif // !kPageSize - -#ifndef kAlign -#define kAlign __BIGGEST_ALIGNMENT__ -#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 -{ - /// @brief Final page entry (Not PML, PDPT) - struct PACKED ZKA_PTE final - { - UInt64 Present : 1; - UInt64 Wr : 1; - UInt64 User : 1; - UInt64 Wt : 1; - UInt64 Cache : 1; - UInt64 Accessed : 1; - UInt64 Dirty : 1; - UInt64 MemoryType : 1; - UInt64 Global : 1; - UInt64 Resvered1 : 3; - UInt64 PhysicalAddress : 36; - UInt64 Reserved2 : 10; - UInt64 ProtectionKey : 5; - UInt64 ExecDisable : 1; - }; - - 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 ZKA_PDE final - { - ZKA_PTE* 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::ZKA_PTE PTE; - typedef HAL::ZKA_PDE PDE; -} // namespace Kernel diff --git a/dev/zka/HALKit/AMD64/Processor.h b/dev/zka/HALKit/AMD64/Processor.h new file mode 100644 index 00000000..8dbac715 --- /dev/null +++ b/dev/zka/HALKit/AMD64/Processor.h @@ -0,0 +1,312 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: Prcoessor.h + Purpose: AMD64 processor abstraction. + + Revision History: + + 30/01/24: Added file (amlel) + +------------------------------------------- */ + +#pragma once + +#include +#include +#include +#include +#include + +#define kPITControlPort 0x43 +#define kPITChannel0Port 0x40 +#define kPITFrequency 1193180 + +#define kPICCommand 0x20 +#define kPICData 0x21 +#define kPIC2Command 0xA0 +#define kPIC2Data 0xA1 + +EXTERN_C +{ +#include +} + +#include + +/// @brief Maximum entries of the interrupt descriptor table. +#define kKernelIdtSize (0x100) + +/// @brief interrupt for system call. +#define kKernelInterruptId (0x32) + +#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 + { + eFlagsPresent = 1 << 0, + eFlagsWr = 1 << 1, + eFlagsUser = 1 << 2, + eFlagsNX = 1 << 3, + eFlagsCount = 3, + }; + + struct PACKED Register64 final + { + UShort Limit; + UIntPtr Base; + }; + + struct PACKED RegisterGDT 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(RegisterGDT& gdt); + static Void Load(Ref& gdt); + }; + + class IDTLoader final + { + public: + static Void Load(Register64& idt); + static Void Load(Ref& idt); + }; + + Void mp_get_cores(VoidPtr rsp_ptr) noexcept; + Void hal_send_start_ipi(UInt32 apicId, UInt8 vector, UInt32 targetAddress); + Void hal_send_end_ipi(UInt32 apicId, UInt8 vector, UInt32 targetAddress); + + /// @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); + } + + /// @brief Get Model-specific register. + /// @param msr MSR + /// @param lo low byte + /// @param hi high byte + inline Void hal_get_msr(UInt32 msr, UInt32* lo, UInt32* hi) noexcept + { + if (!lo || !hi) + return; + + asm volatile("rdmsr" + : "=a"(*lo), "=d"(*hi) + : "c"(msr)); + } + + /// @brief Set Model-specific register. + /// @param msr MSR + /// @param lo low byte + /// @param hi high byte + inline Void hal_set_msr(UInt32 msr, UInt32 lo, UInt32 hi) noexcept + { + asm volatile("wrmsr" + : + : "a"(lo), "d"(hi), "c"(msr)); + } + + /// @brief Processor specific namespace. + namespace Detail + { + /* @brief TSS struct. */ + struct ZKA_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 ZKA_GDT_ENTRY final + { + UInt16 fLimitLow; + UInt16 fBaseLow; + UInt8 fBaseMid; + UInt8 fAccessByte; + UInt8 fFlags; + UInt8 fBaseHigh; + }; + } // namespace Detail + + class APICController + { + public: + explicit APICController(VoidPtr base) + : fApic(base) + { + } + + ~APICController() = default; + + ZKA_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 virt_addr, UInt32 flags); + + EXTERN_C UChar In8(UInt16 port); + EXTERN_C UShort In16(UInt16 port); + EXTERN_C UInt In32(UInt16 port); + + EXTERN_C void Out16(UShort port, UShort byte); + EXTERN_C void Out8(UShort port, UChar byte); + EXTERN_C void 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); +EXTERN_C Kernel::Void idt_handle_math(Kernel::UIntPtr rsp); +EXTERN_C Kernel::Void idt_handle_pf(Kernel::UIntPtr rsp); + +EXTERN_C Kernel::Void hal_load_idt(Kernel::HAL::Register64 ptr); +EXTERN_C Kernel::Void hal_load_gdt(Kernel::HAL::RegisterGDT ptr); + +inline Kernel::VoidPtr kKernelBitMpStart = nullptr; +inline Kernel::UIntPtr kKernelBitMpSize = 0UL; diff --git a/dev/zka/HALKit/AMD64/Processor.hxx b/dev/zka/HALKit/AMD64/Processor.hxx deleted file mode 100644 index 2fd62820..00000000 --- a/dev/zka/HALKit/AMD64/Processor.hxx +++ /dev/null @@ -1,312 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: Prcoessor.hxx - Purpose: AMD64 processor abstraction. - - Revision History: - - 30/01/24: Added file (amlel) - -------------------------------------------- */ - -#pragma once - -#include -#include -#include -#include -#include - -#define kPITControlPort 0x43 -#define kPITChannel0Port 0x40 -#define kPITFrequency 1193180 - -#define kPICCommand 0x20 -#define kPICData 0x21 -#define kPIC2Command 0xA0 -#define kPIC2Data 0xA1 - -EXTERN_C -{ -#include -} - -#include - -/// @brief Maximum entries of the interrupt descriptor table. -#define kKernelIdtSize (0x100) - -/// @brief interrupt for system call. -#define kKernelInterruptId (0x32) - -#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 - { - eFlagsPresent = 1 << 0, - eFlagsWr = 1 << 1, - eFlagsUser = 1 << 2, - eFlagsNX = 1 << 3, - eFlagsCount = 3, - }; - - struct PACKED Register64 final - { - UShort Limit; - UIntPtr Base; - }; - - struct PACKED RegisterGDT 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(RegisterGDT& gdt); - static Void Load(Ref& gdt); - }; - - class IDTLoader final - { - public: - static Void Load(Register64& idt); - static Void Load(Ref& idt); - }; - - Void mp_get_cores(VoidPtr rsp_ptr) noexcept; - Void hal_send_start_ipi(UInt32 apicId, UInt8 vector, UInt32 targetAddress); - Void hal_send_end_ipi(UInt32 apicId, UInt8 vector, UInt32 targetAddress); - - /// @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); - } - - /// @brief Get Model-specific register. - /// @param msr MSR - /// @param lo low byte - /// @param hi high byte - inline Void hal_get_msr(UInt32 msr, UInt32* lo, UInt32* hi) noexcept - { - if (!lo || !hi) - return; - - asm volatile("rdmsr" - : "=a"(*lo), "=d"(*hi) - : "c"(msr)); - } - - /// @brief Set Model-specific register. - /// @param msr MSR - /// @param lo low byte - /// @param hi high byte - inline Void hal_set_msr(UInt32 msr, UInt32 lo, UInt32 hi) noexcept - { - asm volatile("wrmsr" - : - : "a"(lo), "d"(hi), "c"(msr)); - } - - /// @brief Processor specific namespace. - namespace Detail - { - /* @brief TSS struct. */ - struct ZKA_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 ZKA_GDT_ENTRY final - { - UInt16 fLimitLow; - UInt16 fBaseLow; - UInt8 fBaseMid; - UInt8 fAccessByte; - UInt8 fFlags; - UInt8 fBaseHigh; - }; - } // namespace Detail - - class APICController - { - public: - explicit APICController(VoidPtr base) - : fApic(base) - { - } - - ~APICController() = default; - - ZKA_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 virt_addr, UInt32 flags); - - EXTERN_C UChar In8(UInt16 port); - EXTERN_C UShort In16(UInt16 port); - EXTERN_C UInt In32(UInt16 port); - - EXTERN_C void Out16(UShort port, UShort byte); - EXTERN_C void Out8(UShort port, UChar byte); - EXTERN_C void 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); -EXTERN_C Kernel::Void idt_handle_math(Kernel::UIntPtr rsp); -EXTERN_C Kernel::Void idt_handle_pf(Kernel::UIntPtr rsp); - -EXTERN_C Kernel::Void hal_load_idt(Kernel::HAL::Register64 ptr); -EXTERN_C Kernel::Void hal_load_gdt(Kernel::HAL::RegisterGDT ptr); - -inline Kernel::VoidPtr kKernelBitMpStart = nullptr; -inline Kernel::UIntPtr kKernelBitMpSize = 0UL; diff --git a/dev/zka/HALKit/AMD64/Storage/AHCI.cc b/dev/zka/HALKit/AMD64/Storage/AHCI.cc new file mode 100644 index 00000000..abc4603c --- /dev/null +++ b/dev/zka/HALKit/AMD64/Storage/AHCI.cc @@ -0,0 +1,203 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +/** + * @file AHCI.cxx + * @author Amlal El Mahrouss (amlalelmahrouss@icloud.com) + * @brief AHCI driver. + * @version 0.1 + * @date 2024-02-02 + * + * @copyright ZKA Web Services Co. + * + */ + +#include +#include +#include + +#ifdef __AHCI__ +enum +{ + kSATAProgIfAHCI = 0x01, + kSATASubClass = 0x06, + kSATABar5 = 0x24, +}; + +STATIC Kernel::PCI::Device kAhciDevice; +STATIC HbaPort* kAhciPort = nullptr; + +/// @brief Initializes an AHCI disk. +/// @param PortsImplemented the amount of kAhciPort that have been detected. +/// @return +Kernel::Boolean drv_std_init(Kernel::UInt16& PortsImplemented) +{ + using namespace Kernel; + + PCI::Iterator iterator(Types::PciDeviceKind::MassStorageController); + + for (SizeT devIndex = 0; devIndex < ZKA_BUS_COUNT; ++devIndex) + { + if (iterator[devIndex].Leak().Subclass() == kSATASubClass && + iterator[devIndex].Leak().ProgIf() == kSATAProgIfAHCI) + { + iterator[devIndex].Leak().EnableMmio(0x24); /// enable the memory index_byte/o for this ahci device. + iterator[devIndex].Leak().BecomeBusMaster(0x24); /// become bus master for this ahci device, so that we can control it. + + kAhciDevice = iterator[devIndex].Leak(); /// and then leak the reference. + + HbaMem* mem_ahci = (HbaMem*)kAhciDevice.Bar(0x24); + + Kernel::UInt32 ports_implemented = mem_ahci->Pi; + Int32 ahci_index = 0; + + const auto cMaxAhciDevices = 32; + const auto cAhciSig = 0x00000101; + const auto cAhciPresent = 0x03; + const auto cAhciIPMActive = 0x01; + + auto detected = false; + + while (ahci_index < cMaxAhciDevices) + { + if (ports_implemented) + { + kcout << "Port is implemented by host.\r"; + + Kernel::UInt8 ipm = (mem_ahci->Ports[ahci_index].Ssts >> 8) & 0x0F; + Kernel::UInt8 det = mem_ahci->Ports[ahci_index].Ssts & 0x0F; + + if (mem_ahci->Ports[ahci_index].Sig == cAhciSig) + { + kcout << "Found AHCI controller.\r"; + kcout << "Device is of SATA type.\r"; + + detected = true; + + mem_ahci->Ghc |= (1 << kAhciGHC_AE); + + kAhciPort = &mem_ahci->Ports[ahci_index]; + + break; + } + } + + ports_implemented >>= 1; + ++ahci_index; + } + + return detected; + } + } + + return false; +} + +Kernel::Boolean drv_std_detected(Kernel::Void) +{ + return kAhciDevice.DeviceId() != 0xFFFF; +} + +Kernel::Void drv_std_read(Kernel::UInt64 Lba, Kernel::Char* Buf, Kernel::SizeT SectorSz, Kernel::SizeT Size) +{ + STATIC Kernel::Boolean kSlotIsUsed = No; + + while (kSlotIsUsed) + ; + + kSlotIsUsed = Yes; + + Kernel::Int64 free_slot = 0; + + // Prepare command header. + + HbaCmdHeader* cmd_header = (HbaCmdHeader*)kAhciPort->Clb; + cmd_header += free_slot; + + // Read operation/set entries count. + + cmd_header->Write = No; + cmd_header->Prdtl = (Kernel::UInt16)((Size - 1) >> 4) + 1; // PRDT entries count + + // Prepare command table. + + HbaCmdTbl* cmd_tbl = (HbaCmdTbl*)cmd_header->Ctba; + Kernel::rt_set_memory(cmd_tbl, 0, sizeof(HbaCmdTbl)); + + Kernel::UInt64 size = Size * kAHCISectorSize; + Kernel::Int64 index_byte = 0L; + + for (index_byte = 0; index_byte < cmd_header->Prdtl - 1; index_byte++) + { + cmd_tbl->prdtEntries[index_byte].Dba = (Kernel::UInt32)(Kernel::UIntPtr)Buf; + cmd_tbl->prdtEntries[index_byte].Dbc = (8 * 1024) - 1; // 8KB Buf size + cmd_tbl->prdtEntries[index_byte].InterruptBit = 1; // Interrupt on completion + + Size -= 8 * 1024; + Buf += 4 * 1024; // Move the Buf pointer forward + } + + // Last PRDT entry + cmd_tbl->prdtEntries[index_byte].Dba = (Kernel::UInt32)(Kernel::UIntPtr)Buf; + cmd_tbl->prdtEntries[index_byte].Dbc = Size - 1; // Byte count left + cmd_tbl->prdtEntries[index_byte].InterruptBit = 1; + + // 5. Prepare the command FIS (Frame Information Structure) + FisRegH2D* cmd_fis = (FisRegH2D*)(&cmd_tbl->Cfis); + Kernel::rt_set_memory(cmd_fis, 0, sizeof(FisRegH2D)); + + cmd_fis->FisType = kFISTypeRegH2D; + cmd_fis->CmdOrCtrl = 1; // Command + cmd_fis->Command = kAHCICmdReadDmaEx; + + cmd_fis->Lba0 = (Kernel::UInt8)Lba; + cmd_fis->Lba1 = (Kernel::UInt8)(Lba >> 8); + cmd_fis->Lba2 = (Kernel::UInt8)(Lba >> 16); + cmd_fis->Device = 1 << 6; // LBA mode + + cmd_fis->Lba3 = (Kernel::UInt8)(Lba >> 24); + cmd_fis->Lba4 = (Kernel::UInt8)(Lba >> 32); + cmd_fis->Lba5 = (Kernel::UInt8)(Lba >> 40); + + cmd_fis->CountLow = Size & 0xFF; + cmd_fis->CountHigh = (Size >> 8) & 0xFF; + + // 6. Issue the command by writing to the kAhciPort's command issue register (CI) + kAhciPort->Ci = 1 << free_slot; + + // 7. Wait for the command to complete (simple spinlock, no need for an object here) + while (Yes) + { + if (!(kAhciPort->Ci & (1 << free_slot))) + { + break; // Command has completed + } + if (kAhciPort->Is & (1 << 30)) + { + return; // Error in task file + } + } + + kSlotIsUsed = No; +} + +Kernel::Void drv_std_write(Kernel::UInt64 Lba, Kernel::Char* Buf, Kernel::SizeT SectorSz, Kernel::SizeT Size) +{ +} +/*** + @brief Getter, gets the number of sectors inside the drive. +*/ +Kernel::SizeT drv_get_sector_count() +{ + return 0; +} + +/// @brief Get the drive size. +Kernel::SizeT drv_get_size() +{ + return 0; +} +#endif // __AHCI__ diff --git a/dev/zka/HALKit/AMD64/Storage/AHCI.cxx b/dev/zka/HALKit/AMD64/Storage/AHCI.cxx deleted file mode 100644 index 0a318d6d..00000000 --- a/dev/zka/HALKit/AMD64/Storage/AHCI.cxx +++ /dev/null @@ -1,202 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -/** - * @file AHCI.cxx - * @author Amlal El Mahrouss (amlalelmahrouss@icloud.com) - * @brief AHCI driver. - * @version 0.1 - * @date 2024-02-02 - * - * @copyright ZKA Web Services Co. - * - */ - -#include -#include -#include - -#ifdef __AHCI__ -enum -{ - kSATAProgIfAHCI = 0x01, - kSATASubClass = 0x06 -}; - -STATIC Kernel::PCI::Device kAhciDevice; -STATIC HbaPort* kAhciPort = nullptr; - -/// @brief Initializes an AHCI disk. -/// @param PortsImplemented the amount of kAhciPort that have been detected. -/// @return -Kernel::Boolean drv_std_init(Kernel::UInt16& PortsImplemented) -{ - using namespace Kernel; - - PCI::Iterator iterator(Types::PciDeviceKind::MassStorageController); - - for (SizeT devIndex = 0; devIndex < ZKA_BUS_COUNT; ++devIndex) - { - if (iterator[devIndex].Leak().Subclass() == kSATASubClass && - iterator[devIndex].Leak().ProgIf() == kSATAProgIfAHCI) - { - iterator[devIndex].Leak().EnableMmio(0x24); /// enable the memory index_byte/o for this ahci device. - iterator[devIndex].Leak().BecomeBusMaster(0x24); /// become bus master for this ahci device, so that we can control it. - - kAhciDevice = iterator[devIndex].Leak(); /// and then leak the reference. - - HbaMem* mem_ahci = (HbaMem*)kAhciDevice.Bar(0x24); - - Kernel::UInt32 ports_implemented = mem_ahci->Pi; - Int32 ahci_index = 0; - - const auto cMaxAhciDevices = 32; - const auto cAhciSig = 0x00000101; - const auto cAhciPresent = 0x03; - const auto cAhciIPMActive = 0x01; - - auto detected = false; - - while (ahci_index < cMaxAhciDevices) - { - if (ports_implemented) - { - kcout << "Port is implemented by host.\r"; - - Kernel::UInt8 ipm = (mem_ahci->Ports[ahci_index].Ssts >> 8) & 0x0F; - Kernel::UInt8 det = mem_ahci->Ports[ahci_index].Ssts & 0x0F; - - if (mem_ahci->Ports[ahci_index].Sig == cAhciSig) - { - kcout << "Found AHCI controller.\r"; - kcout << "Device is of SATA type.\r"; - - detected = true; - - mem_ahci->Ghc |= (1 << kAhciGHC_AE); - - kAhciPort = &mem_ahci->Ports[ahci_index]; - - break; - } - } - - ports_implemented >>= 1; - ++ahci_index; - } - - return detected; - } - } - - return false; -} - -Kernel::Boolean drv_std_detected(Kernel::Void) -{ - return kAhciDevice.DeviceId() != 0xFFFF; -} - -Kernel::Void drv_std_read(Kernel::UInt64 Lba, Kernel::Char* Buf, Kernel::SizeT SectorSz, Kernel::SizeT Size) -{ - STATIC Kernel::Boolean kSlotIsUsed = No; - - while (kSlotIsUsed) - ; - - kSlotIsUsed = Yes; - - Kernel::Int64 free_slot = 0; - - // Prepare command header. - - HbaCmdHeader* cmd_header = (HbaCmdHeader*)kAhciPort->Clb; - cmd_header += free_slot; - - // Read operation/set entries count. - - cmd_header->Write = No; - cmd_header->Prdtl = (Kernel::UInt16)((Size - 1) >> 4) + 1; // PRDT entries count - - // Prepare command table. - - HbaCmdTbl* cmd_tbl = (HbaCmdTbl*)cmd_header->Ctba; - Kernel::rt_set_memory(cmd_tbl, 0, sizeof(HbaCmdTbl)); - - Kernel::UInt64 size = Size * kAHCISectorSize; - Kernel::Int64 index_byte = 0L; - - for (index_byte = 0; index_byte < cmd_header->Prdtl - 1; index_byte++) - { - cmd_tbl->prdtEntries[index_byte].Dba = (Kernel::UInt32)(Kernel::UIntPtr)Buf; - cmd_tbl->prdtEntries[index_byte].Dbc = (8 * 1024) - 1; // 8KB Buf size - cmd_tbl->prdtEntries[index_byte].InterruptBit = 1; // Interrupt on completion - - Size -= 8 * 1024; - Buf += 4 * 1024; // Move the Buf pointer forward - } - - // Last PRDT entry - cmd_tbl->prdtEntries[index_byte].Dba = (Kernel::UInt32)(Kernel::UIntPtr)Buf; - cmd_tbl->prdtEntries[index_byte].Dbc = Size - 1; // Byte count left - cmd_tbl->prdtEntries[index_byte].InterruptBit = 1; - - // 5. Prepare the command FIS (Frame Information Structure) - FisRegH2D* cmd_fis = (FisRegH2D*)(&cmd_tbl->Cfis); - Kernel::rt_set_memory(cmd_fis, 0, sizeof(FisRegH2D)); - - cmd_fis->FisType = kFISTypeRegH2D; - cmd_fis->CmdOrCtrl = 1; // Command - cmd_fis->Command = kAHCICmdReadDmaEx; - - cmd_fis->Lba0 = (Kernel::UInt8)Lba; - cmd_fis->Lba1 = (Kernel::UInt8)(Lba >> 8); - cmd_fis->Lba2 = (Kernel::UInt8)(Lba >> 16); - cmd_fis->Device = 1 << 6; // LBA mode - - cmd_fis->Lba3 = (Kernel::UInt8)(Lba >> 24); - cmd_fis->Lba4 = (Kernel::UInt8)(Lba >> 32); - cmd_fis->Lba5 = (Kernel::UInt8)(Lba >> 40); - - cmd_fis->CountLow = Size & 0xFF; - cmd_fis->CountHigh = (Size >> 8) & 0xFF; - - // 6. Issue the command by writing to the kAhciPort's command issue register (CI) - kAhciPort->Ci = 1 << free_slot; - - // 7. Wait for the command to complete (simple spinlock, no need for an object here) - while (Yes) - { - if (!(kAhciPort->Ci & (1 << free_slot))) - { - break; // Command has completed - } - if (kAhciPort->Is & (1 << 30)) - { - return; // Error in task file - } - } - - kSlotIsUsed = No; -} - -Kernel::Void drv_std_write(Kernel::UInt64 Lba, Kernel::Char* Buf, Kernel::SizeT SectorSz, Kernel::SizeT Size) -{ -} -/*** - @brief Getter, gets the number of sectors inside the drive. -*/ -Kernel::SizeT drv_get_sector_count() -{ - return 0; -} - -/// @brief Get the drive size. -Kernel::SizeT drv_get_size() -{ - return 0; -} -#endif // __AHCI__ diff --git a/dev/zka/HALKit/AMD64/Storage/ATA-DMA.cc b/dev/zka/HALKit/AMD64/Storage/ATA-DMA.cc new file mode 100644 index 00000000..ddf08501 --- /dev/null +++ b/dev/zka/HALKit/AMD64/Storage/ATA-DMA.cc @@ -0,0 +1,38 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +/** + * @file ATA-DMA.cxx + * @author Amlal El Mahrouss (amlalelmahrouss@icloud.com) + * @brief ATA driver (DMA mode). + * @version 0.1 + * @date 2024-02-02 + * + * @copyright Copyright (c) ZKA Web Services Co + * + */ + +#include + +#include +#include + +using namespace Kernel; + +EXTERN_C Int32 kPRDTTransferStatus; +STATIC PRDT kPRDT; + +#ifdef __ATA_DMA__ + +#ifdef __ATA_PIO__ +#error !!! You cant have both PIO and DMA enabled! !!! +#endif /* ifdef __ATA_PIO__ */ + +#ifdef __AHCI__ +#error !!! You cant have both ATA and AHCI enabled! !!! +#endif /* ifdef __AHCI__ */ + +#endif /* ifdef __ATA_DMA__ */ diff --git a/dev/zka/HALKit/AMD64/Storage/ATA-DMA.cxx b/dev/zka/HALKit/AMD64/Storage/ATA-DMA.cxx deleted file mode 100644 index cc74d1ac..00000000 --- a/dev/zka/HALKit/AMD64/Storage/ATA-DMA.cxx +++ /dev/null @@ -1,38 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -/** - * @file ATA-DMA.cxx - * @author Amlal El Mahrouss (amlalelmahrouss@icloud.com) - * @brief ATA driver (DMA mode). - * @version 0.1 - * @date 2024-02-02 - * - * @copyright Copyright (c) ZKA Web Services Co - * - */ - -#include - -#include -#include - -using namespace Kernel; - -EXTERN_C Int32 kPRDTTransferStatus; -STATIC PRDT kPRDT; - -#ifdef __ATA_DMA__ - -#ifdef __ATA_PIO__ -#error !!! You cant have both PIO and DMA enabled! !!! -#endif /* ifdef __ATA_PIO__ */ - -#ifdef __AHCI__ -#error !!! You cant have both ATA and AHCI enabled! !!! -#endif /* ifdef __AHCI__ */ - -#endif /* ifdef __ATA_DMA__ */ diff --git a/dev/zka/HALKit/AMD64/Storage/ATA-PIO.cc b/dev/zka/HALKit/AMD64/Storage/ATA-PIO.cc new file mode 100644 index 00000000..96e7eb35 --- /dev/null +++ b/dev/zka/HALKit/AMD64/Storage/ATA-PIO.cc @@ -0,0 +1,197 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +/** + * @file ATA-PIO.cxx + * @author Amlal El Mahrouss (amlalelmahrouss@icloud.com) + * @brief ATA driver (PIO mode). + * @version 0.1 + * @date 2024-02-02 + * + * @copyright Copyright (c) ZKA Web Services Co + * + */ + +#include +#include + +#ifdef __ATA_PIO__ + +using namespace Kernel; +using namespace Kernel::HAL; + +/// bugs: 0 + +#define kATADataLen 256 + +STATIC Boolean kATADetected = false; +STATIC Int32 kATADeviceType = kATADeviceCount; +STATIC Char kATAData[kATADataLen] = {0}; + +Boolean drv_std_wait_io(UInt16 IO) +{ + for (int i = 0; i < 400; i++) + In8(IO + ATA_REG_STATUS); + +ATAWaitForIO_Retry: + auto statRdy = In8(IO + ATA_REG_STATUS); + + if ((statRdy & ATA_SR_BSY)) + goto ATAWaitForIO_Retry; + +ATAWaitForIO_Retry2: + statRdy = In8(IO + ATA_REG_STATUS); + + if (statRdy & ATA_SR_ERR) + return false; + + if (!(statRdy & ATA_SR_DRDY)) + goto ATAWaitForIO_Retry2; + + return true; +} + +Void drv_std_select(UInt16 Bus) +{ + if (Bus == ATA_PRIMARY_IO) + Out8(Bus + ATA_REG_HDDEVSEL, ATA_PRIMARY_SEL); + else + Out8(Bus + ATA_REG_HDDEVSEL, ATA_SECONDARY_SEL); +} + +Boolean drv_std_init(UInt16 Bus, UInt8 Drive, UInt16& OutBus, UInt8& OutMaster) +{ + UInt16 IO = Bus; + + drv_std_select(IO); + +ATAInit_Retry: + // Bus init, NEIN bit. + Out8(IO + ATA_REG_NEIN, 1); + + // identify until it's good + + auto statRdy = In8(IO + ATA_REG_STATUS); + + if (statRdy & ATA_SR_ERR) + { + kcout << "ERROR: ATA DRIVE RETURNED ERROR BIT! ABORTING...\r"; + + return false; + } + + if ((statRdy & ATA_SR_BSY)) + { + kcout << "Retrying..."; + goto ATAInit_Retry; + } + + Out8(IO + ATA_REG_COMMAND, ATA_CMD_IDENTIFY); + + /// fetch serial info + /// model, speed, number of sectors... + + drv_std_wait_io(IO); + + for (SizeT indexData = 0ul; indexData < kATADataLen; ++indexData) + { + kATAData[indexData] = In16(IO + ATA_REG_DATA); + } + + OutBus = (Bus == ATA_PRIMARY_IO) ? ATA_PRIMARY_IO : ATA_SECONDARY_IO; + + OutMaster = (Bus == ATA_PRIMARY_IO) ? ATA_MASTER : ATA_SLAVE; + + kcout << "INFO: INITIALIZED ATA DRIVE!\r"; + + return true; +} + +Void drv_std_read(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) +{ + Lba /= SectorSz; + + UInt8 Command = ((!Master) ? 0xE0 : 0xF0); + + drv_std_wait_io(IO); + drv_std_select(IO); + + Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); + + Out8(IO + ATA_REG_SEC_COUNT0, ((Size + SectorSz) / SectorSz)); + + Out8(IO + ATA_REG_LBA0, (Lba)&0xFF); + Out8(IO + ATA_REG_LBA1, (Lba) >> 8); + Out8(IO + ATA_REG_LBA2, (Lba) >> 16); + Out8(IO + ATA_REG_LBA3, (Lba) >> 24); + + Out8(IO + ATA_REG_COMMAND, ATA_CMD_READ_PIO); + + drv_std_wait_io(IO); + + for (SizeT IndexOff = 0; IndexOff < Size; ++IndexOff) + { + drv_std_wait_io(IO); + Buf[IndexOff] = In16(IO + ATA_REG_DATA); + drv_std_wait_io(IO); + } + + drv_std_wait_io(IO); +} + +Void drv_std_write(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) +{ + Lba /= SectorSz; + + UInt8 Command = ((!Master) ? 0xE0 : 0xF0); + + drv_std_wait_io(IO); + drv_std_select(IO); + + Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); + + Out8(IO + ATA_REG_SEC_COUNT0, ((Size + (SectorSz)) / SectorSz)); + + Out8(IO + ATA_REG_LBA0, (Lba)&0xFF); + Out8(IO + ATA_REG_LBA1, (Lba) >> 8); + Out8(IO + ATA_REG_LBA2, (Lba) >> 16); + Out8(IO + ATA_REG_LBA3, (Lba) >> 24); + + Out8(IO + ATA_REG_COMMAND, ATA_CMD_WRITE_PIO); + + drv_std_wait_io(IO); + + for (SizeT IndexOff = 0; IndexOff < Size; ++IndexOff) + { + drv_std_wait_io(IO); + Out16(IO + ATA_REG_DATA, Buf[IndexOff]); + drv_std_wait_io(IO); + } + + drv_std_wait_io(IO); +} + +/// @brief is ATA detected? +Boolean drv_std_detected(Void) +{ + return kATADetected; +} + +/*** + @brief Getter, gets the number of sectors inside the drive. +*/ +Kernel::SizeT drv_get_sector_count() +{ + return (kATAData[61] << 16) | kATAData[60]; +} + +/// @brief Get the drive size. +Kernel::SizeT drv_get_size() +{ + return drv_get_sector_count() * kATASectorSize; +} + +#endif /* ifdef __ATA_PIO__ */ diff --git a/dev/zka/HALKit/AMD64/Storage/ATA-PIO.cxx b/dev/zka/HALKit/AMD64/Storage/ATA-PIO.cxx deleted file mode 100644 index d0a1cf45..00000000 --- a/dev/zka/HALKit/AMD64/Storage/ATA-PIO.cxx +++ /dev/null @@ -1,197 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -/** - * @file ATA-PIO.cxx - * @author Amlal El Mahrouss (amlalelmahrouss@icloud.com) - * @brief ATA driver (PIO mode). - * @version 0.1 - * @date 2024-02-02 - * - * @copyright Copyright (c) ZKA Web Services Co - * - */ - -#include -#include - -#ifdef __ATA_PIO__ - -using namespace Kernel; -using namespace Kernel::HAL; - -/// bugs: 0 - -#define kATADataLen 256 - -STATIC Boolean kATADetected = false; -STATIC Int32 kATADeviceType = kATADeviceCount; -STATIC Char kATAData[kATADataLen] = {0}; - -Boolean drv_std_wait_io(UInt16 IO) -{ - for (int i = 0; i < 400; i++) - In8(IO + ATA_REG_STATUS); - -ATAWaitForIO_Retry: - auto statRdy = In8(IO + ATA_REG_STATUS); - - if ((statRdy & ATA_SR_BSY)) - goto ATAWaitForIO_Retry; - -ATAWaitForIO_Retry2: - statRdy = In8(IO + ATA_REG_STATUS); - - if (statRdy & ATA_SR_ERR) - return false; - - if (!(statRdy & ATA_SR_DRDY)) - goto ATAWaitForIO_Retry2; - - return true; -} - -Void drv_std_select(UInt16 Bus) -{ - if (Bus == ATA_PRIMARY_IO) - Out8(Bus + ATA_REG_HDDEVSEL, ATA_PRIMARY_SEL); - else - Out8(Bus + ATA_REG_HDDEVSEL, ATA_SECONDARY_SEL); -} - -Boolean drv_std_init(UInt16 Bus, UInt8 Drive, UInt16& OutBus, UInt8& OutMaster) -{ - UInt16 IO = Bus; - - drv_std_select(IO); - -ATAInit_Retry: - // Bus init, NEIN bit. - Out8(IO + ATA_REG_NEIN, 1); - - // identify until it's good - - auto statRdy = In8(IO + ATA_REG_STATUS); - - if (statRdy & ATA_SR_ERR) - { - kcout << "ERROR: ATA DRIVE RETURNED ERROR BIT! ABORTING...\r"; - - return false; - } - - if ((statRdy & ATA_SR_BSY)) - { - kcout << "Retrying..."; - goto ATAInit_Retry; - } - - Out8(IO + ATA_REG_COMMAND, ATA_CMD_IDENTIFY); - - /// fetch serial info - /// model, speed, number of sectors... - - drv_std_wait_io(IO); - - for (SizeT indexData = 0ul; indexData < kATADataLen; ++indexData) - { - kATAData[indexData] = In16(IO + ATA_REG_DATA); - } - - OutBus = (Bus == ATA_PRIMARY_IO) ? ATA_PRIMARY_IO : ATA_SECONDARY_IO; - - OutMaster = (Bus == ATA_PRIMARY_IO) ? ATA_MASTER : ATA_SLAVE; - - kcout << "INFO: INITIALIZED ATA DRIVE!\r"; - - return true; -} - -Void drv_std_read(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) -{ - Lba /= SectorSz; - - UInt8 Command = ((!Master) ? 0xE0 : 0xF0); - - drv_std_wait_io(IO); - drv_std_select(IO); - - Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); - - Out8(IO + ATA_REG_SEC_COUNT0, ((Size + SectorSz) / SectorSz)); - - Out8(IO + ATA_REG_LBA0, (Lba)&0xFF); - Out8(IO + ATA_REG_LBA1, (Lba) >> 8); - Out8(IO + ATA_REG_LBA2, (Lba) >> 16); - Out8(IO + ATA_REG_LBA3, (Lba) >> 24); - - Out8(IO + ATA_REG_COMMAND, ATA_CMD_READ_PIO); - - drv_std_wait_io(IO); - - for (SizeT IndexOff = 0; IndexOff < Size; ++IndexOff) - { - drv_std_wait_io(IO); - Buf[IndexOff] = In16(IO + ATA_REG_DATA); - drv_std_wait_io(IO); - } - - drv_std_wait_io(IO); -} - -Void drv_std_write(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) -{ - Lba /= SectorSz; - - UInt8 Command = ((!Master) ? 0xE0 : 0xF0); - - drv_std_wait_io(IO); - drv_std_select(IO); - - Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); - - Out8(IO + ATA_REG_SEC_COUNT0, ((Size + (SectorSz)) / SectorSz)); - - Out8(IO + ATA_REG_LBA0, (Lba)&0xFF); - Out8(IO + ATA_REG_LBA1, (Lba) >> 8); - Out8(IO + ATA_REG_LBA2, (Lba) >> 16); - Out8(IO + ATA_REG_LBA3, (Lba) >> 24); - - Out8(IO + ATA_REG_COMMAND, ATA_CMD_WRITE_PIO); - - drv_std_wait_io(IO); - - for (SizeT IndexOff = 0; IndexOff < Size; ++IndexOff) - { - drv_std_wait_io(IO); - Out16(IO + ATA_REG_DATA, Buf[IndexOff]); - drv_std_wait_io(IO); - } - - drv_std_wait_io(IO); -} - -/// @brief is ATA detected? -Boolean drv_std_detected(Void) -{ - return kATADetected; -} - -/*** - @brief Getter, gets the number of sectors inside the drive. -*/ -Kernel::SizeT drv_get_sector_count() -{ - return (kATAData[61] << 16) | kATAData[60]; -} - -/// @brief Get the drive size. -Kernel::SizeT drv_get_size() -{ - return drv_get_sector_count() * kATASectorSize; -} - -#endif /* ifdef __ATA_PIO__ */ diff --git a/dev/zka/HALKit/ARM64/APM/APM.cc b/dev/zka/HALKit/ARM64/APM/APM.cc new file mode 100644 index 00000000..ff193765 --- /dev/null +++ b/dev/zka/HALKit/ARM64/APM/APM.cc @@ -0,0 +1,37 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +using namespace Kernel; + +/// @brief Send a APM command into it's own IO space. +/// @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, =0x84000009\n" + "hvc #0\n"); + + return kErrorSuccess; + } + case kAPMPowerCommandShutdown: { + asm volatile( + "ldr x0, =0x84000008\n" + "hvc #0\n"); + + return kErrorSuccess; + } + default: + return kErrorInvalidData; + } +} diff --git a/dev/zka/HALKit/ARM64/APM/APM.cxx b/dev/zka/HALKit/ARM64/APM/APM.cxx deleted file mode 100644 index 164f3aab..00000000 --- a/dev/zka/HALKit/ARM64/APM/APM.cxx +++ /dev/null @@ -1,37 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -using namespace Kernel; - -/// @brief Send a APM command into it's own IO space. -/// @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, =0x84000009\n" - "hvc #0\n"); - - return kErrorSuccess; - } - case kAPMPowerCommandShutdown: { - asm volatile( - "ldr x0, =0x84000008\n" - "hvc #0\n"); - - return kErrorSuccess; - } - default: - return kErrorInvalidData; - } -} diff --git a/dev/zka/HALKit/ARM64/HalACPIFactoryInterface.cc b/dev/zka/HALKit/ARM64/HalACPIFactoryInterface.cc new file mode 100644 index 00000000..c093e83e --- /dev/null +++ b/dev/zka/HALKit/ARM64/HalACPIFactoryInterface.cc @@ -0,0 +1,31 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include +#include +#include + +namespace Kernel +{ + ACPIFactoryInterface::ACPIFactoryInterface(VoidPtr rsp_ptr) + : fRsdp(rsp_ptr), fEntries(0) + { + } + + Void ACPIFactoryInterface::Shutdown() + { + apm_send_io_command(kAPMPowerCommandShutdown, 0); + } + + /// @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/zka/HALKit/ARM64/HalACPIFactoryInterface.cxx b/dev/zka/HALKit/ARM64/HalACPIFactoryInterface.cxx deleted file mode 100644 index 8221b734..00000000 --- a/dev/zka/HALKit/ARM64/HalACPIFactoryInterface.cxx +++ /dev/null @@ -1,31 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include -#include -#include - -namespace Kernel -{ - ACPIFactoryInterface::ACPIFactoryInterface(VoidPtr rsp_ptr) - : fRsdp(rsp_ptr), fEntries(0) - { - } - - Void ACPIFactoryInterface::Shutdown() - { - apm_send_io_command(kAPMPowerCommandShutdown, 0); - } - - /// @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/zka/HALKit/ARM64/HalCoreMPScheduler.cc b/dev/zka/HALKit/ARM64/HalCoreMPScheduler.cc new file mode 100644 index 00000000..d808ebeb --- /dev/null +++ b/dev/zka/HALKit/ARM64/HalCoreMPScheduler.cc @@ -0,0 +1,19 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +using namespace Kernel; + +EXTERN_C Void mp_do_task_switch(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr stack_frame); + +EXTERN_C Bool mp_register_process(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr stack_frame) +{ + mp_do_task_switch(image, stack_ptr, stack_frame); + + return Yes; +} diff --git a/dev/zka/HALKit/ARM64/HalCoreMPScheduler.cxx b/dev/zka/HALKit/ARM64/HalCoreMPScheduler.cxx deleted file mode 100644 index 76456318..00000000 --- a/dev/zka/HALKit/ARM64/HalCoreMPScheduler.cxx +++ /dev/null @@ -1,19 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -using namespace Kernel; - -EXTERN_C Void mp_do_task_switch(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr stack_frame); - -EXTERN_C Bool mp_register_process(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr stack_frame) -{ - mp_do_task_switch(image, stack_ptr, stack_frame); - - return Yes; -} diff --git a/dev/zka/HALKit/ARM64/HalDebugOutput.cc b/dev/zka/HALKit/ARM64/HalDebugOutput.cc new file mode 100644 index 00000000..c98d87a5 --- /dev/null +++ b/dev/zka/HALKit/ARM64/HalDebugOutput.cc @@ -0,0 +1,81 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include +#include + +namespace Kernel +{ + EXTERN_C void ke_io_write(const Char* bytes) + { +#ifdef __DEBUG__ + if (*bytes == 0) + return; + + SizeT index = 0; + SizeT len = 0; + + index = 0; + len = rt_string_len(bytes, 255); + + volatile UInt8* uart_ptr = (UInt8*)0x09000000; + + while (index < len) + { + if (bytes[index] == '\r') + *uart_ptr = '\r'; + + *uart_ptr = bytes[index] == '\r' ? '\n' : bytes[index]; + ++index; + } +#endif // __DEBUG__ + } + + EXTERN_C void ke_io_read(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 diff --git a/dev/zka/HALKit/ARM64/HalDebugOutput.cxx b/dev/zka/HALKit/ARM64/HalDebugOutput.cxx deleted file mode 100644 index 2710b099..00000000 --- a/dev/zka/HALKit/ARM64/HalDebugOutput.cxx +++ /dev/null @@ -1,81 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include -#include - -namespace Kernel -{ - EXTERN_C void ke_io_write(const Char* bytes) - { -#ifdef __DEBUG__ - if (*bytes == 0) - return; - - SizeT index = 0; - SizeT len = 0; - - index = 0; - len = rt_string_len(bytes, 255); - - volatile UInt8* uart_ptr = (UInt8*)0x09000000; - - while (index < len) - { - if (bytes[index] == '\r') - *uart_ptr = '\r'; - - *uart_ptr = bytes[index] == '\r' ? '\n' : bytes[index]; - ++index; - } -#endif // __DEBUG__ - } - - EXTERN_C void ke_io_read(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 diff --git a/dev/zka/HALKit/ARM64/HalKernelMain.cc b/dev/zka/HALKit/ARM64/HalKernelMain.cc new file mode 100644 index 00000000..16460bb5 --- /dev/null +++ b/dev/zka/HALKit/ARM64/HalKernelMain.cc @@ -0,0 +1,46 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +Kernel::Void hal_real_init(Kernel::Void) noexcept; +EXTERN_C Kernel::Void ke_dll_entrypoint(Kernel::Void); + +EXTERN_C void hal_init_platform( + Kernel::HEL::HANDOVER_INFO_HEADER* HandoverHeader) +{ + + /************************************************** */ + /* INITIALIZE AND VALIDATE HEADER. */ + /************************************************** */ + + kHandoverHeader = HandoverHeader; + + if (kHandoverHeader->f_Magic != kHandoverMagic && + kHandoverHeader->f_Version != kHandoverVersion) + { + return; + } + + /************************************** */ + /* INITIALIZE BIT MAP. */ + /************************************** */ + + while (Yes) + { + } +} diff --git a/dev/zka/HALKit/ARM64/HalKernelMain.cxx b/dev/zka/HALKit/ARM64/HalKernelMain.cxx deleted file mode 100644 index 52096158..00000000 --- a/dev/zka/HALKit/ARM64/HalKernelMain.cxx +++ /dev/null @@ -1,46 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -Kernel::Void hal_real_init(Kernel::Void) noexcept; -EXTERN_C Kernel::Void ke_dll_entrypoint(Kernel::Void); - -EXTERN_C void hal_init_platform( - Kernel::HEL::HANDOVER_INFO_HEADER* HandoverHeader) -{ - - /************************************************** */ - /* INITIALIZE AND VALIDATE HEADER. */ - /************************************************** */ - - kHandoverHeader = HandoverHeader; - - if (kHandoverHeader->f_Magic != kHandoverMagic && - kHandoverHeader->f_Version != kHandoverVersion) - { - return; - } - - /************************************** */ - /* INITIALIZE BIT MAP. */ - /************************************** */ - - while (Yes) - { - } -} diff --git a/dev/zka/HALKit/ARM64/HalPagingMgr.cc b/dev/zka/HALKit/ARM64/HalPagingMgr.cc new file mode 100644 index 00000000..0182c315 --- /dev/null +++ b/dev/zka/HALKit/ARM64/HalPagingMgr.cc @@ -0,0 +1,86 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: HalPagingMgr.cxx + Purpose: Platform Paging Manager.. + +------------------------------------------- */ + +#include +#include + +namespace Kernel::HAL +{ + typedef UInt32 PageTableIndex; + + /// \brief Page store type. + struct ZKA_PAGE_STORE final + { + struct + { + PDE* fPde{nullptr}; + PTE* fPte{nullptr}; + VoidPtr fVAddr{nullptr}; + } fInternalStore; + + Bool fStoreOp{No}; // Store operation in progress. + + static ZKA_PAGE_STORE& The() + { + static ZKA_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, UInt32 flags) + { + if (!virtual_address || + !flags) + return 0; + + ZKA_PAGE_STORE& page_store = ZKA_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) + { + ZKA_PAGE_STORE& page_store = ZKA_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/zka/HALKit/ARM64/HalPagingMgr.cxx b/dev/zka/HALKit/ARM64/HalPagingMgr.cxx deleted file mode 100644 index ae060af9..00000000 --- a/dev/zka/HALKit/ARM64/HalPagingMgr.cxx +++ /dev/null @@ -1,86 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: HalPagingMgr.cxx - Purpose: Platform Paging Manager.. - -------------------------------------------- */ - -#include -#include - -namespace Kernel::HAL -{ - typedef UInt32 PageTableIndex; - - /// \brief Page store type. - struct ZKA_PAGE_STORE final - { - struct - { - PDE* fPde{nullptr}; - PTE* fPte{nullptr}; - VoidPtr fVAddr{nullptr}; - } fInternalStore; - - Bool fStoreOp{No}; // Store operation in progress. - - static ZKA_PAGE_STORE& The() - { - static ZKA_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, UInt32 flags) - { - if (!virtual_address || - !flags) - return 0; - - ZKA_PAGE_STORE& page_store = ZKA_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) - { - ZKA_PAGE_STORE& page_store = ZKA_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/zka/HALKit/ARM64/HalSchedulerCore.cc b/dev/zka/HALKit/ARM64/HalSchedulerCore.cc new file mode 100644 index 00000000..a384db22 --- /dev/null +++ b/dev/zka/HALKit/ARM64/HalSchedulerCore.cc @@ -0,0 +1,50 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +namespace Kernel +{ + EXTERN_C Void __zka_pure_call(void) + { + UserProcessScheduler::The().CurrentProcess().Leak().Crash(); + } + + Void UserProcess::SetImageStart(VoidPtr image_start) noexcept + { + if (image_start == 0) + this->Crash(); + + this->Image = image_start; + } + + bool hal_check_stack(HAL::StackFramePtr stackPtr) + { + if (!stackPtr) + return false; + if (stackPtr->BP == 0 || stackPtr->SP == 0) + return false; + + return true; + } + + /// @brief Wakes up thread. + /// Wakes up thread from the hang state. + Void mp_wakeup_thread(HAL::StackFrame* stack) + { + ZKA_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) + { + while (Yes) + { + /* Nothing to do, code is spinning */ + } + } +} // namespace Kernel diff --git a/dev/zka/HALKit/ARM64/HalSchedulerCore.cxx b/dev/zka/HALKit/ARM64/HalSchedulerCore.cxx deleted file mode 100644 index e231e0fc..00000000 --- a/dev/zka/HALKit/ARM64/HalSchedulerCore.cxx +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -namespace Kernel -{ - EXTERN_C Void __zka_pure_call(void) - { - UserProcessScheduler::The().CurrentProcess().Leak().Crash(); - } - - Void UserProcess::SetImageStart(VoidPtr image_start) noexcept - { - if (image_start == 0) - this->Crash(); - - this->Image = image_start; - } - - bool hal_check_stack(HAL::StackFramePtr stackPtr) - { - if (!stackPtr) - return false; - if (stackPtr->BP == 0 || stackPtr->SP == 0) - return false; - - return true; - } - - /// @brief Wakes up thread. - /// Wakes up thread from the hang state. - Void mp_wakeup_thread(HAL::StackFrame* stack) - { - ZKA_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) - { - while (Yes) - { - /* Nothing to do, code is spinning */ - } - } -} // namespace Kernel diff --git a/dev/zka/HALKit/ARM64/HalTimer.cc b/dev/zka/HALKit/ARM64/HalTimer.cc new file mode 100644 index 00000000..d3f8c457 --- /dev/null +++ b/dev/zka/HALKit/ARM64/HalTimer.cc @@ -0,0 +1,14 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: HalTimer.cxx + Purpose: HAL timer + + Revision History: + + 07/07/24: Added file (amlel) + +------------------------------------------- */ + +#include diff --git a/dev/zka/HALKit/ARM64/HalTimer.cxx b/dev/zka/HALKit/ARM64/HalTimer.cxx deleted file mode 100644 index 7183fd10..00000000 --- a/dev/zka/HALKit/ARM64/HalTimer.cxx +++ /dev/null @@ -1,14 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: HalTimer.cxx - Purpose: HAL timer - - Revision History: - - 07/07/24: Added file (amlel) - -------------------------------------------- */ - -#include diff --git a/dev/zka/HALKit/ARM64/Paging.h b/dev/zka/HALKit/ARM64/Paging.h new file mode 100644 index 00000000..74b4bab0 --- /dev/null +++ b/dev/zka/HALKit/ARM64/Paging.h @@ -0,0 +1,120 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +/** --------------------------------------------------- + + * THIS FILE CONTAINS CODE FOR ARMV8 PAGING. + +------------------------------------------------------- */ + +#include + +#ifndef kPageMax +#define kPageMax (0x200) +#endif //! kPageMax + +#ifndef kPageAlign +#define kPageAlign (0x1000) +#endif //! kPageAlign + +#ifndef kPageSize +#define kPageSize (0x1000) +#endif // !kPageSize + +//! short format address range + +#define c16KBPage 0b000 +#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 cPageMToMax(M) \ + { \ + M, 0b000 \ + } +#define cPageMaxToM(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 + +EXTERN_C void hal_flush_tlb(); diff --git a/dev/zka/HALKit/ARM64/Paging.hxx b/dev/zka/HALKit/ARM64/Paging.hxx deleted file mode 100644 index 276433c7..00000000 --- a/dev/zka/HALKit/ARM64/Paging.hxx +++ /dev/null @@ -1,120 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -/** --------------------------------------------------- - - * THIS FILE CONTAINS CODE FOR ARMV8 PAGING. - -------------------------------------------------------- */ - -#include - -#ifndef kPageMax -#define kPageMax (0x200) -#endif //! kPageMax - -#ifndef kPageAlign -#define kPageAlign (0x1000) -#endif //! kPageAlign - -#ifndef kPageSize -#define kPageSize (0x1000) -#endif // !kPageSize - -//! short format address range - -#define c16KBPage 0b000 -#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 cPageMToMax(M) \ - { \ - M, 0b000 \ - } -#define cPageMaxToM(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 - -EXTERN_C void hal_flush_tlb(); diff --git a/dev/zka/HALKit/ARM64/Processor.h b/dev/zka/HALKit/ARM64/Processor.h new file mode 100644 index 00000000..5f00e345 --- /dev/null +++ b/dev/zka/HALKit/ARM64/Processor.h @@ -0,0 +1,75 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include +#include + +#define kCPUBackendName "ARMv8" + +namespace Kernel::HAL +{ + struct PACKED Register64 final + { + UShort Limit; + UIntPtr Base; + }; + + /// @brief Memory Manager mapping flags. + enum + { + eFlagsPresent = 1 << 0, + eFlagsWr = 1 << 1, + eFlagsUser = 1 << 2, + eFlagsNX = 1 << 3, + eFlagsCount = 3, + }; + + /// @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 virt_addr, UInt32 flags); + + 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() + { + while (Yes) + { + } + } + +} // namespace Kernel::HAL + +inline Kernel::VoidPtr kKernelBitMpStart = nullptr; +inline Kernel::UIntPtr kKernelBitMpSize = 0UL; + +inline Kernel::VoidPtr kKernelPhysicalStart = nullptr; + +#include diff --git a/dev/zka/HALKit/ARM64/Processor.hxx b/dev/zka/HALKit/ARM64/Processor.hxx deleted file mode 100644 index 93a9141a..00000000 --- a/dev/zka/HALKit/ARM64/Processor.hxx +++ /dev/null @@ -1,75 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include -#include - -#define kCPUBackendName "ARMv8" - -namespace Kernel::HAL -{ - struct PACKED Register64 final - { - UShort Limit; - UIntPtr Base; - }; - - /// @brief Memory Manager mapping flags. - enum - { - eFlagsPresent = 1 << 0, - eFlagsWr = 1 << 1, - eFlagsUser = 1 << 2, - eFlagsNX = 1 << 3, - eFlagsCount = 3, - }; - - /// @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 virt_addr, UInt32 flags); - - 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() - { - while (Yes) - { - } - } - -} // namespace Kernel::HAL - -inline Kernel::VoidPtr kKernelBitMpStart = nullptr; -inline Kernel::UIntPtr kKernelBitMpSize = 0UL; - -inline Kernel::VoidPtr kKernelPhysicalStart = nullptr; - -#include diff --git a/dev/zka/HALKit/ARM64/Storage/HalFlash.cc b/dev/zka/HALKit/ARM64/Storage/HalFlash.cc new file mode 100644 index 00000000..d64d9d82 --- /dev/null +++ b/dev/zka/HALKit/ARM64/Storage/HalFlash.cc @@ -0,0 +1,66 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +/// @file Flash.cxx +/// @brief Flash memory builtin. + +#ifdef __USE_MBCI_FLASH__ + +#define cMaxFlash (4U) + +namespace Kernel +{ + /// /:\\BRIDGE\\FLSH\\1 + constexpr auto cFlashBridgeMagic = "FLSH"; + constexpr auto cFlashBridgeRevision = 1; + + STATIC const Boolean kFlashEnabled = No; + STATIC SizeT kFlashSize[cMaxFlash] = {}; + STATIC SizeT kFlashSectorSz[cMaxFlash] = {}; + + /// @brief Enable flash memory builtin. + STATIC Void drv_enable_flash(Int32 slot); + + /// @brief Disable flash memory builtin. + STATIC Void drv_disable_flash(Int32 slot); + + /// @brief get sector count. + /// @return drive sector count. + SizeT drv_get_sector_count(Int32 slot) + { + if (slot > cMaxFlash) + return 0; + + return kFlashSectorSz[slot]; + } + + /// @brief get device size. + /// @return drive size + SizeT drv_get_size(Int32 slot) + { + if (slot > cMaxFlash) + return 0; + + return kFlashSize[slot]; + } + + /// @brief Enable flash memory at slot. + STATIC Void drv_enable_flash(Int32 arg) + { + kcout << "Enabled FLSH hardware.\r"; + } + + /// @brief Disable flash memory at slot. + STATIC Void drv_disable_flash(Int32 arg) + { + kcout << "Disabled FLSH hardware.\r"; + } +} // namespace Kernel + +#endif // if __USE_MBCI_FLASH__ (Bridge) diff --git a/dev/zka/HALKit/ARM64/Storage/HalFlash.cxx b/dev/zka/HALKit/ARM64/Storage/HalFlash.cxx deleted file mode 100644 index 70e025f7..00000000 --- a/dev/zka/HALKit/ARM64/Storage/HalFlash.cxx +++ /dev/null @@ -1,66 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -/// @file Flash.cxx -/// @brief Flash memory builtin. - -#ifdef __USE_MBCI_FLASH__ - -#define cMaxFlash (4U) - -namespace Kernel -{ - /// /:\\BRIDGE\\FLSH\\1 - constexpr auto cFlashBridgeMagic = "FLSH"; - constexpr auto cFlashBridgeRevision = 1; - - STATIC const Boolean kFlashEnabled = No; - STATIC SizeT kFlashSize[cMaxFlash] = {}; - STATIC SizeT kFlashSectorSz[cMaxFlash] = {}; - - /// @brief Enable flash memory builtin. - STATIC Void drv_enable_flash(Int32 slot); - - /// @brief Disable flash memory builtin. - STATIC Void drv_disable_flash(Int32 slot); - - /// @brief get sector count. - /// @return drive sector count. - SizeT drv_get_sector_count(Int32 slot) - { - if (slot > cMaxFlash) - return 0; - - return kFlashSectorSz[slot]; - } - - /// @brief get device size. - /// @return drive size - SizeT drv_get_size(Int32 slot) - { - if (slot > cMaxFlash) - return 0; - - return kFlashSize[slot]; - } - - /// @brief Enable flash memory at slot. - STATIC Void drv_enable_flash(Int32 arg) - { - kcout << "Enabled FLSH hardware.\r"; - } - - /// @brief Disable flash memory at slot. - STATIC Void drv_disable_flash(Int32 arg) - { - kcout << "Disabled FLSH hardware.\r"; - } -} // namespace Kernel - -#endif // if __USE_MBCI_FLASH__ (Bridge) diff --git a/dev/zka/HALKit/AXP/CoreSyscallHandlerDEC.cpp b/dev/zka/HALKit/AXP/CoreSyscallHandlerDEC.cpp index 7fe901a5..c164dce0 100644 --- a/dev/zka/HALKit/AXP/CoreSyscallHandlerDEC.cpp +++ b/dev/zka/HALKit/AXP/CoreSyscallHandlerDEC.cpp @@ -4,8 +4,8 @@ ------------------------------------------- */ -#include -#include +#include +#include /// @brief Internal call for syscall, to work with C++. /// @param stack diff --git a/dev/zka/HALKit/AXP/Processor.h b/dev/zka/HALKit/AXP/Processor.h new file mode 100644 index 00000000..cdb39054 --- /dev/null +++ b/dev/zka/HALKit/AXP/Processor.h @@ -0,0 +1,7 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once diff --git a/dev/zka/HALKit/AXP/Processor.hxx b/dev/zka/HALKit/AXP/Processor.hxx deleted file mode 100644 index cdb39054..00000000 --- a/dev/zka/HALKit/AXP/Processor.hxx +++ /dev/null @@ -1,7 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once diff --git a/dev/zka/HALKit/POWER/HalHart.cc b/dev/zka/HALKit/POWER/HalHart.cc new file mode 100644 index 00000000..ff5025d5 --- /dev/null +++ b/dev/zka/HALKit/POWER/HalHart.cc @@ -0,0 +1,25 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include + +using namespace Kernel; + +/// @brief wakes up thread. +/// wakes up thread from hang. +void mp_wakeup_thread(HAL::StackFramePtr stack) +{ + ZKA_UNUSED(stack); +} + +/// @brief makes thread sleep. +/// hooks and hangs thread to prevent code from executing. +void mp_hang_thread(HAL::StackFramePtr stack) +{ + ZKA_UNUSED(stack); +} diff --git a/dev/zka/HALKit/POWER/HalHart.cxx b/dev/zka/HALKit/POWER/HalHart.cxx deleted file mode 100644 index 185d835a..00000000 --- a/dev/zka/HALKit/POWER/HalHart.cxx +++ /dev/null @@ -1,25 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include - -using namespace Kernel; - -/// @brief wakes up thread. -/// wakes up thread from hang. -void mp_wakeup_thread(HAL::StackFramePtr stack) -{ - ZKA_UNUSED(stack); -} - -/// @brief makes thread sleep. -/// hooks and hangs thread to prevent code from executing. -void mp_hang_thread(HAL::StackFramePtr stack) -{ - ZKA_UNUSED(stack); -} diff --git a/dev/zka/HALKit/POWER/HalSerialPort.cc b/dev/zka/HALKit/POWER/HalSerialPort.cc new file mode 100644 index 00000000..29bc8fa5 --- /dev/null +++ b/dev/zka/HALKit/POWER/HalSerialPort.cc @@ -0,0 +1,27 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +using namespace Kernel; + +/// @brief Writes to COM1. +/// @param bytes +void ke_io_write(const Char* bytes) +{ + if (!bytes) + return; + + SizeT index = 0; + SizeT len = rt_string_len(bytes, 255); + + while (index < len) + { + // TODO + ++index; + } +} diff --git a/dev/zka/HALKit/POWER/HalSerialPort.cxx b/dev/zka/HALKit/POWER/HalSerialPort.cxx deleted file mode 100644 index 0c4eb230..00000000 --- a/dev/zka/HALKit/POWER/HalSerialPort.cxx +++ /dev/null @@ -1,27 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -using namespace Kernel; - -/// @brief Writes to COM1. -/// @param bytes -void ke_io_write(const Char* bytes) -{ - if (!bytes) - return; - - SizeT index = 0; - SizeT len = rt_string_len(bytes, 255); - - while (index < len) - { - // TODO - ++index; - } -} diff --git a/dev/zka/HALKit/POWER/HalThread.cc b/dev/zka/HALKit/POWER/HalThread.cc new file mode 100644 index 00000000..7a0d5ccb --- /dev/null +++ b/dev/zka/HALKit/POWER/HalThread.cc @@ -0,0 +1,8 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include diff --git a/dev/zka/HALKit/POWER/HalThread.cxx b/dev/zka/HALKit/POWER/HalThread.cxx deleted file mode 100644 index da8f4e2d..00000000 --- a/dev/zka/HALKit/POWER/HalThread.cxx +++ /dev/null @@ -1,8 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include diff --git a/dev/zka/HALKit/POWER/HalVirtualMemory.cc b/dev/zka/HALKit/POWER/HalVirtualMemory.cc new file mode 100644 index 00000000..8d8db849 --- /dev/null +++ b/dev/zka/HALKit/POWER/HalVirtualMemory.cc @@ -0,0 +1,51 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +#include +#include + +/// @note refer to the SoC documentation. + +using namespace Kernel; + +Void hal_write_tlb(UInt32 mas0, UInt32 mas1, UInt32 mas2, UInt32 mas3, UInt32 mas7) +{ + mtspr(MAS0, mas0); + mtspr(MAS1, mas1); + mtspr(MAS2, mas2); + mtspr(MAS3, mas3); + mtspr(MAS7, mas7); + + hal_flush_tlb(); +} + +Bool hal_set_tlb(UInt8 tlb, UInt32 epn, UInt64 rpn, UInt8 perms, UInt8 wimge, UInt8 ts, UInt8 esel, UInt8 tsize, UInt8 iprot) +{ + if ((mfspr(SPRN_MMUCFG) & MMUCFG_MAVN) == MMUCFG_MAVN_V1 && (tsize & 1)) + { + // this mmu-version 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); + + hal_write_tlb(mas0, mas1, mas2, mas3, mas7); + + return true; +} + +/// @brief Flush TLB +EXTERN_C void hal_flush_tlb() +{ + asm volatile("isync;tlbwe;msync;isync"); +} diff --git a/dev/zka/HALKit/POWER/HalVirtualMemory.cxx b/dev/zka/HALKit/POWER/HalVirtualMemory.cxx deleted file mode 100644 index 9e4529a2..00000000 --- a/dev/zka/HALKit/POWER/HalVirtualMemory.cxx +++ /dev/null @@ -1,51 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -#include -#include - -/// @note refer to the SoC documentation. - -using namespace Kernel; - -Void hal_write_tlb(UInt32 mas0, UInt32 mas1, UInt32 mas2, UInt32 mas3, UInt32 mas7) -{ - mtspr(MAS0, mas0); - mtspr(MAS1, mas1); - mtspr(MAS2, mas2); - mtspr(MAS3, mas3); - mtspr(MAS7, mas7); - - hal_flush_tlb(); -} - -Bool hal_set_tlb(UInt8 tlb, UInt32 epn, UInt64 rpn, UInt8 perms, UInt8 wimge, UInt8 ts, UInt8 esel, UInt8 tsize, UInt8 iprot) -{ - if ((mfspr(SPRN_MMUCFG) & MMUCFG_MAVN) == MMUCFG_MAVN_V1 && (tsize & 1)) - { - // this mmu-version 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); - - hal_write_tlb(mas0, mas1, mas2, mas3, mas7); - - return true; -} - -/// @brief Flush TLB -EXTERN_C void hal_flush_tlb() -{ - asm volatile("isync;tlbwe;msync;isync"); -} diff --git a/dev/zka/HALKit/POWER/Hart.h b/dev/zka/HALKit/POWER/Hart.h new file mode 100644 index 00000000..eaf00493 --- /dev/null +++ b/dev/zka/HALKit/POWER/Hart.h @@ -0,0 +1,36 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: Hart.h + Purpose: POWER hardware threads. + + Revision History: + + 14/04/24: Added file (amlel) + +------------------------------------------- */ + +#pragma once + +#include + +struct HAL_HARDWARE_THREAD; + +/// @brief hardware thread indentification type. +typedef Kernel::Int32 PPCHartType; + +/// @brief Hardware thread information structure. +typedef struct HAL_HARDWARE_THREAD +{ + Kernel::UIntPtr fStartAddress; + Kernel::UInt8 fPrivleged : 1; + Kernel::UInt32 fPageFlags; + PPCHartType 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); diff --git a/dev/zka/HALKit/POWER/Hart.hxx b/dev/zka/HALKit/POWER/Hart.hxx deleted file mode 100644 index aceed5db..00000000 --- a/dev/zka/HALKit/POWER/Hart.hxx +++ /dev/null @@ -1,36 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: Hart.hxx - Purpose: POWER hardware threads. - - Revision History: - - 14/04/24: Added file (amlel) - -------------------------------------------- */ - -#pragma once - -#include - -struct HAL_HARDWARE_THREAD; - -/// @brief hardware thread indentification type. -typedef Kernel::Int32 PPCHartType; - -/// @brief Hardware thread information structure. -typedef struct HAL_HARDWARE_THREAD -{ - Kernel::UIntPtr fStartAddress; - Kernel::UInt8 fPrivleged : 1; - Kernel::UInt32 fPageFlags; - PPCHartType 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); diff --git a/dev/zka/HALKit/POWER/MBCI/HalMBCIHost.cc b/dev/zka/HALKit/POWER/MBCI/HalMBCIHost.cc new file mode 100644 index 00000000..7a0d5ccb --- /dev/null +++ b/dev/zka/HALKit/POWER/MBCI/HalMBCIHost.cc @@ -0,0 +1,8 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include diff --git a/dev/zka/HALKit/POWER/MBCI/HalMBCIHost.cxx b/dev/zka/HALKit/POWER/MBCI/HalMBCIHost.cxx deleted file mode 100644 index da8f4e2d..00000000 --- a/dev/zka/HALKit/POWER/MBCI/HalMBCIHost.cxx +++ /dev/null @@ -1,8 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include diff --git a/dev/zka/HALKit/POWER/Processor.h b/dev/zka/HALKit/POWER/Processor.h new file mode 100644 index 00000000..95c1f1c6 --- /dev/null +++ b/dev/zka/HALKit/POWER/Processor.h @@ -0,0 +1,60 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + Purpose: POWER processor header. + +------------------------------------------- */ + +#pragma once + +#include +#include + +#define NoOp() 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}; + }; + + 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); + +/// @brief Write TLB. +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/zka/HALKit/POWER/Processor.hxx b/dev/zka/HALKit/POWER/Processor.hxx deleted file mode 100644 index de34e1d2..00000000 --- a/dev/zka/HALKit/POWER/Processor.hxx +++ /dev/null @@ -1,60 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - Purpose: POWER processor header. - -------------------------------------------- */ - -#pragma once - -#include -#include - -#define NoOp() 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}; - }; - - 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); - -/// @brief Write TLB. -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/zka/HALKit/RISCV/Hart.h b/dev/zka/HALKit/RISCV/Hart.h new file mode 100644 index 00000000..b5e842c0 --- /dev/null +++ b/dev/zka/HALKit/RISCV/Hart.h @@ -0,0 +1,24 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: Hart.h + Purpose: RISC-V hardware threads. + + Revision History: + + 30/01/24: Added file (amlel) + +------------------------------------------- */ + +#pragma once + +#include + +typedef Kernel::Int32 Rv64HartType; + +/// @brief Set PC to specific hart. +/// @param hart the hart +/// @param epc the pc. +/// @return +EXTERN_C Kernel::Void hal_set_pc_to_hart(Rv64HartType hart, Kernel::VoidPtr epc); diff --git a/dev/zka/HALKit/RISCV/Hart.hxx b/dev/zka/HALKit/RISCV/Hart.hxx deleted file mode 100644 index c25816be..00000000 --- a/dev/zka/HALKit/RISCV/Hart.hxx +++ /dev/null @@ -1,24 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: Hart.hxx - Purpose: RISC-V hardware threads. - - Revision History: - - 30/01/24: Added file (amlel) - -------------------------------------------- */ - -#pragma once - -#include - -typedef Kernel::Int32 Rv64HartType; - -/// @brief Set PC to specific hart. -/// @param hart the hart -/// @param epc the pc. -/// @return -EXTERN_C Kernel::Void hal_set_pc_to_hart(Rv64HartType hart, Kernel::VoidPtr epc); diff --git a/dev/zka/HintKit/CompilerHint.h b/dev/zka/HintKit/CompilerHint.h new file mode 100644 index 00000000..da670509 --- /dev/null +++ b/dev/zka/HintKit/CompilerHint.h @@ -0,0 +1,23 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef __HINTKIT_COMPILER_HINT_HXX__ +#define __HINTKIT_COMPILER_HINT_HXX__ + +#pragma compiler(hint_manifest) + +#define _Input +#define _Output + +#define _Optional + +#define _StrictCheckInput +#define _StrictCheckOutput + +#define _InOut +#define _StrictInOut + +#endif // ifndef __HINTKIT_COMPILER_HINT_HXX__ diff --git a/dev/zka/HintKit/CompilerHint.hxx b/dev/zka/HintKit/CompilerHint.hxx deleted file mode 100644 index da670509..00000000 --- a/dev/zka/HintKit/CompilerHint.hxx +++ /dev/null @@ -1,23 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef __HINTKIT_COMPILER_HINT_HXX__ -#define __HINTKIT_COMPILER_HINT_HXX__ - -#pragma compiler(hint_manifest) - -#define _Input -#define _Output - -#define _Optional - -#define _StrictCheckInput -#define _StrictCheckOutput - -#define _InOut -#define _StrictInOut - -#endif // ifndef __HINTKIT_COMPILER_HINT_HXX__ diff --git a/dev/zka/KernelKit/CodeMgr.h b/dev/zka/KernelKit/CodeMgr.h new file mode 100644 index 00000000..41a90ec5 --- /dev/null +++ b/dev/zka/KernelKit/CodeMgr.h @@ -0,0 +1,31 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: CodeMgr.hpp + Purpose: Code Mgr and DLL mgr. + + Revision History: + + 30/01/24: Added file (amlel) + 3/8/24: Add UPP struct. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +namespace Kernel +{ + /// @brief Main process entrypoint. + typedef void (*MainKind)(void); + + /// @brief Executes a new process from a function. Kernel code only. + /// @note This sets up a new stack, anything on the main function that calls the Kernel will not be accessible. + /// @param main the start of the process. + /// @return if the process was started or not. + bool sched_execute_thread(MainKind main, const Char* process_name) noexcept; +} // namespace Kernel diff --git a/dev/zka/KernelKit/CodeMgr.hxx b/dev/zka/KernelKit/CodeMgr.hxx deleted file mode 100644 index 127f3b7b..00000000 --- a/dev/zka/KernelKit/CodeMgr.hxx +++ /dev/null @@ -1,31 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: CodeMgr.hpp - Purpose: Code Mgr and DLL mgr. - - Revision History: - - 30/01/24: Added file (amlel) - 3/8/24: Add UPP struct. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -namespace Kernel -{ - /// @brief Main process entrypoint. - typedef void (*MainKind)(void); - - /// @brief Executes a new process from a function. Kernel code only. - /// @note This sets up a new stack, anything on the main function that calls the Kernel will not be accessible. - /// @param main the start of the process. - /// @return if the process was started or not. - bool sched_execute_thread(MainKind main, const Char* process_name) noexcept; -} // namespace Kernel diff --git a/dev/zka/KernelKit/DebugOutput.h b/dev/zka/KernelKit/DebugOutput.h new file mode 100644 index 00000000..e7e466e3 --- /dev/null +++ b/dev/zka/KernelKit/DebugOutput.h @@ -0,0 +1,197 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include +#include + +#define kDebugMaxPorts 16 + +#define kDebugUnboundPort 0x0FEED + +#define kDebugMag0 'N' +#define kDebugMag1 'D' +#define kDebugMag2 'B' +#define kDebugMag3 'G' + +#define kDebugSourceFile 0 +#define kDebugLine 33 +#define kDebugTeam 43 +#define kDebugEOP 49 + +namespace Kernel +{ + class TerminalDevice; + + inline TerminalDevice end_line(); + inline TerminalDevice number(const Long& x); + inline TerminalDevice hex_number(const Long& x); + + // @brief Emulates a VT100 terminal. + class TerminalDevice final : public DeviceInterface + { + public: + TerminalDevice(void (*print)(const Char*), void (*get)(const Char*)) + : DeviceInterface(print, get) + { + } + + virtual ~TerminalDevice() = default; + + /// @brief returns device name (terminal name) + /// @return string type (const Char*) + virtual const Char* Name() const override + { + return ("TerminalDevice"); + } + + ZKA_COPY_DEFAULT(TerminalDevice); + + STATIC TerminalDevice The() noexcept; + }; + + inline TerminalDevice end_line() + { + TerminalDevice selfTerm = TerminalDevice::The(); + + selfTerm.operator<<("\r"); + return selfTerm; + } + + inline TerminalDevice carriage_return() + { + TerminalDevice selfTerm = TerminalDevice::The(); + + selfTerm.operator<<("\r"); + return selfTerm; + } + + inline TerminalDevice tabulate() + { + TerminalDevice selfTerm = TerminalDevice::The(); + + selfTerm.operator<<("\t"); + return selfTerm; + } + + /// @brief emulate a terminal bell, like the VT100 does. + inline TerminalDevice bell() + { + TerminalDevice selfTerm = TerminalDevice::The(); + + selfTerm.operator<<("\a"); + return selfTerm; + } + + namespace Detail + { + inline TerminalDevice _write_number(const Long& x, TerminalDevice& term) + { + UInt64 y = (x > 0 ? x : -x) / 10; + UInt64 h = (x > 0 ? x : -x) % 10; + + if (y) + _write_number(y, term); + + /* fail if the number is not base-10 */ + if (h > 10) + { + _write_number('?', term); + return term; + } + + if (y < 0) + y = -y; + + const Char cNumbers[11] = "0123456789"; + + Char buf[2]; + buf[0] = cNumbers[h]; + buf[1] = 0; + + term.operator<<(buf); + return term; + } + + inline TerminalDevice _write_number_hex(const Long& x, TerminalDevice& term) + { + UInt64 y = (x > 0 ? x : -x) / 16; + UInt64 h = (x > 0 ? x : -x) % 16; + + if (y) + _write_number_hex(y, term); + + /* fail if the hex number is not base-16 */ + if (h > 15) + { + _write_number_hex('?', term); + return term; + } + + if (y < 0) + y = -y; + + const Char cNumbers[17] = "0123456789ABCDEF"; + + Char buf[2]; + buf[0] = cNumbers[h]; + buf[1] = 0; + + term.operator<<(buf); + return term; + } + } // namespace Detail + + inline TerminalDevice hex_number(const Long& x) + { + TerminalDevice selfTerm = TerminalDevice::The(); + + Detail::_write_number_hex(x, selfTerm); + selfTerm.operator<<("h"); + + return selfTerm; + } + + inline TerminalDevice number(const Long& x) + { + TerminalDevice selfTerm = TerminalDevice::The(); + + Detail::_write_number(x, selfTerm); + + return selfTerm; + } + + inline TerminalDevice get_console_in(Char* buf) + { + TerminalDevice selfTerm = TerminalDevice::The(); + + selfTerm >> buf; + + return selfTerm; + } + + typedef Char rt_debug_type[255]; + + class DebuggerPortHeader final + { + public: + Int16 fPort[kDebugMaxPorts]; + Int16 fBoundCnt; + }; +} // namespace Kernel + +#ifdef kcout +#undef kcout +#endif // ifdef kcout + +#define kcout \ + (Kernel::TerminalDevice::The() << "\e[0;31m [ " << __FILE__ << ": LINE: " << Kernel::number(__LINE__)); \ + (Kernel::TerminalDevice::The() << " ] \e[0m" \ + << ": ") +#define endl Kernel::TerminalDevice::The() << Kernel::end_line() diff --git a/dev/zka/KernelKit/DebugOutput.hxx b/dev/zka/KernelKit/DebugOutput.hxx deleted file mode 100644 index 142debc7..00000000 --- a/dev/zka/KernelKit/DebugOutput.hxx +++ /dev/null @@ -1,197 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include -#include - -#define kDebugMaxPorts 16 - -#define kDebugUnboundPort 0x0FEED - -#define kDebugMag0 'N' -#define kDebugMag1 'D' -#define kDebugMag2 'B' -#define kDebugMag3 'G' - -#define kDebugSourceFile 0 -#define kDebugLine 33 -#define kDebugTeam 43 -#define kDebugEOP 49 - -namespace Kernel -{ - class TerminalDevice; - - inline TerminalDevice end_line(); - inline TerminalDevice number(const Long& x); - inline TerminalDevice hex_number(const Long& x); - - // @brief Emulates a VT100 terminal. - class TerminalDevice final : public DeviceInterface - { - public: - TerminalDevice(void (*print)(const Char*), void (*get)(const Char*)) - : DeviceInterface(print, get) - { - } - - virtual ~TerminalDevice() = default; - - /// @brief returns device name (terminal name) - /// @return string type (const Char*) - virtual const Char* Name() const override - { - return ("TerminalDevice"); - } - - ZKA_COPY_DEFAULT(TerminalDevice); - - STATIC TerminalDevice The() noexcept; - }; - - inline TerminalDevice end_line() - { - TerminalDevice selfTerm = TerminalDevice::The(); - - selfTerm.operator<<("\r"); - return selfTerm; - } - - inline TerminalDevice carriage_return() - { - TerminalDevice selfTerm = TerminalDevice::The(); - - selfTerm.operator<<("\r"); - return selfTerm; - } - - inline TerminalDevice tabulate() - { - TerminalDevice selfTerm = TerminalDevice::The(); - - selfTerm.operator<<("\t"); - return selfTerm; - } - - /// @brief emulate a terminal bell, like the VT100 does. - inline TerminalDevice bell() - { - TerminalDevice selfTerm = TerminalDevice::The(); - - selfTerm.operator<<("\a"); - return selfTerm; - } - - namespace Detail - { - inline TerminalDevice _write_number(const Long& x, TerminalDevice& term) - { - UInt64 y = (x > 0 ? x : -x) / 10; - UInt64 h = (x > 0 ? x : -x) % 10; - - if (y) - _write_number(y, term); - - /* fail if the number is not base-10 */ - if (h > 10) - { - _write_number('?', term); - return term; - } - - if (y < 0) - y = -y; - - const Char cNumbers[11] = "0123456789"; - - Char buf[2]; - buf[0] = cNumbers[h]; - buf[1] = 0; - - term.operator<<(buf); - return term; - } - - inline TerminalDevice _write_number_hex(const Long& x, TerminalDevice& term) - { - UInt64 y = (x > 0 ? x : -x) / 16; - UInt64 h = (x > 0 ? x : -x) % 16; - - if (y) - _write_number_hex(y, term); - - /* fail if the hex number is not base-16 */ - if (h > 15) - { - _write_number_hex('?', term); - return term; - } - - if (y < 0) - y = -y; - - const Char cNumbers[17] = "0123456789ABCDEF"; - - Char buf[2]; - buf[0] = cNumbers[h]; - buf[1] = 0; - - term.operator<<(buf); - return term; - } - } // namespace Detail - - inline TerminalDevice hex_number(const Long& x) - { - TerminalDevice selfTerm = TerminalDevice::The(); - - Detail::_write_number_hex(x, selfTerm); - selfTerm.operator<<("h"); - - return selfTerm; - } - - inline TerminalDevice number(const Long& x) - { - TerminalDevice selfTerm = TerminalDevice::The(); - - Detail::_write_number(x, selfTerm); - - return selfTerm; - } - - inline TerminalDevice get_console_in(Char* buf) - { - TerminalDevice selfTerm = TerminalDevice::The(); - - selfTerm >> buf; - - return selfTerm; - } - - typedef Char rt_debug_type[255]; - - class DebuggerPortHeader final - { - public: - Int16 fPort[kDebugMaxPorts]; - Int16 fBoundCnt; - }; -} // namespace Kernel - -#ifdef kcout -#undef kcout -#endif // ifdef kcout - -#define kcout \ - (Kernel::TerminalDevice::The() << "\e[0;31m [ " << __FILE__ << ": LINE: " << Kernel::number(__LINE__)); \ - (Kernel::TerminalDevice::The() << " ] \e[0m" \ - << ": ") -#define endl Kernel::TerminalDevice::The() << Kernel::end_line() diff --git a/dev/zka/KernelKit/Defines.h b/dev/zka/KernelKit/Defines.h new file mode 100644 index 00000000..48befc8e --- /dev/null +++ b/dev/zka/KernelKit/Defines.h @@ -0,0 +1,11 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +#define KERNELKIT_VERSION "1.02" diff --git a/dev/zka/KernelKit/Defines.hxx b/dev/zka/KernelKit/Defines.hxx deleted file mode 100644 index 3e59716f..00000000 --- a/dev/zka/KernelKit/Defines.hxx +++ /dev/null @@ -1,11 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -#define KERNELKIT_VERSION "1.02" diff --git a/dev/zka/KernelKit/DeviceMgr.h b/dev/zka/KernelKit/DeviceMgr.h new file mode 100644 index 00000000..1f767aa6 --- /dev/null +++ b/dev/zka/KernelKit/DeviceMgr.h @@ -0,0 +1,132 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +/* ------------------------------------------- + + Revision History: + + 31/01/24: Add kDeviceCnt (amlel) + + ------------------------------------------- */ + +#pragma once + +/* Device manager. */ +/* @file KernelKit/DeviceMgr.hpp */ +/* @brief Device abstraction and I/O buffer. */ + +#include +#include + +#define cDevicePath "\\Mount\\" + +// Last Rev +// Wed, Apr 3, 2024 9:09:41 AM + +namespace Kernel +{ + template + class DeviceInterface; + + template + class DeviceInterface + { + public: + explicit DeviceInterface(void (*Out)(T), void (*In)(T)) + : fOut(Out), fIn(In) + { + } + + virtual ~DeviceInterface() = default; + + public: + DeviceInterface& operator=(const DeviceInterface&) = default; + DeviceInterface(const DeviceInterface&) = default; + + public: + virtual DeviceInterface& operator<<(T Data) + { + fOut(Data); + return *this; + } + + virtual DeviceInterface& operator>>(T Data) + { + fIn(Data); + return *this; + } + + virtual const char* Name() const + { + return "DeviceInterface"; + } + + operator bool() + { + return fOut && fIn; + } + + Bool operator!() + { + return !fOut || !fIn; + } + + private: + Void (*fOut)(T Data) = {nullptr}; + Void (*fIn)(T Data) = {nullptr}; + }; + + /// + /// @brief Input Output Buffer + /// Used mainly to communicate between hardware. + /// + template + class IOBuf final + { + public: + explicit IOBuf(T Dat) + : fData(Dat) + { + // at least pass something valid when instancating this struct. + MUST_PASS(Dat); + } + + IOBuf& operator=(const IOBuf&) = default; + IOBuf(const IOBuf&) = default; + + ~IOBuf() = default; + + public: + template + R operator->() const + { + return fData; + } + + template + R& operator[](Size index) const + { + return fData[index]; + } + + private: + T fData; + }; + + ///! @brief Device enum types. + enum + { + kDeviceTypeIDE, + kDeviceTypeEthernet, + kDeviceTypeWiFi, + kDeviceTypeRS232, + kDeviceTypeSCSI, + kDeviceTypeSHCI, + kDeviceTypeUSB, + kDeviceTypeMedia, + kDeviceTypeCount, + }; +} // namespace Kernel diff --git a/dev/zka/KernelKit/DeviceMgr.hxx b/dev/zka/KernelKit/DeviceMgr.hxx deleted file mode 100644 index 5788d1b0..00000000 --- a/dev/zka/KernelKit/DeviceMgr.hxx +++ /dev/null @@ -1,132 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -/* ------------------------------------------- - - Revision History: - - 31/01/24: Add kDeviceCnt (amlel) - - ------------------------------------------- */ - -#pragma once - -/* Device manager. */ -/* @file KernelKit/DeviceMgr.hpp */ -/* @brief Device abstraction and I/O buffer. */ - -#include -#include - -#define cDevicePath "\\Mount\\" - -// Last Rev -// Wed, Apr 3, 2024 9:09:41 AM - -namespace Kernel -{ - template - class DeviceInterface; - - template - class DeviceInterface - { - public: - explicit DeviceInterface(void (*Out)(T), void (*In)(T)) - : fOut(Out), fIn(In) - { - } - - virtual ~DeviceInterface() = default; - - public: - DeviceInterface& operator=(const DeviceInterface&) = default; - DeviceInterface(const DeviceInterface&) = default; - - public: - virtual DeviceInterface& operator<<(T Data) - { - fOut(Data); - return *this; - } - - virtual DeviceInterface& operator>>(T Data) - { - fIn(Data); - return *this; - } - - virtual const char* Name() const - { - return "DeviceInterface"; - } - - operator bool() - { - return fOut && fIn; - } - - Bool operator!() - { - return !fOut || !fIn; - } - - private: - Void (*fOut)(T Data) = {nullptr}; - Void (*fIn)(T Data) = {nullptr}; - }; - - /// - /// @brief Input Output Buffer - /// Used mainly to communicate between hardware. - /// - template - class IOBuf final - { - public: - explicit IOBuf(T Dat) - : fData(Dat) - { - // at least pass something valid when instancating this struct. - MUST_PASS(Dat); - } - - IOBuf& operator=(const IOBuf&) = default; - IOBuf(const IOBuf&) = default; - - ~IOBuf() = default; - - public: - template - R operator->() const - { - return fData; - } - - template - R& operator[](Size index) const - { - return fData[index]; - } - - private: - T fData; - }; - - ///! @brief Device enum types. - enum - { - kDeviceTypeIDE, - kDeviceTypeEthernet, - kDeviceTypeWiFi, - kDeviceTypeRS232, - kDeviceTypeSCSI, - kDeviceTypeSHCI, - kDeviceTypeUSB, - kDeviceTypeMedia, - kDeviceTypeCount, - }; -} // namespace Kernel diff --git a/dev/zka/KernelKit/DriveMgr.h b/dev/zka/KernelKit/DriveMgr.h new file mode 100644 index 00000000..850217cb --- /dev/null +++ b/dev/zka/KernelKit/DriveMgr.h @@ -0,0 +1,155 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef __INC_DRIVE_MANAGER_HXX__ +#define __INC_DRIVE_MANAGER_HXX__ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define kMaxDriveCountPerMountpoint (4U) + +#define kDriveInvalidID (-1) +#define kDriveNameLen (32) + +#define DrvSectorCnt(SIZE, SECTOR_SZ) (((SIZE) + (SECTOR_SZ)) / (SECTOR_SZ)) + +namespace Kernel +{ + enum + { + /// Storage type. + kInvalidStorage = -1, + kBlockDevice = 0xAD, + kMassStorage = 0xDA, + kFloppyDisc = 0xCD, + kOpticalDisc = 0xDC, // CD-ROM/DVD-ROM/Blu-Ray + /// Storage flags, combine with below. + kReadOnly = 0x10, // Read only drive + kEPMDrive = 0x11, // Explicit Partition Map. + kEPTDrive = 0x12, // ESP w/ EPM partition. + kMBRDrive = 0x13, // PC classic partition scheme + kGPTDrive = 0x14, // PC new partition scheme + kStorageCount = 9, + }; + + typedef Int64 rt_drive_id_type; + + /// @brief Media drive trait type. + struct DriveTrait final + { + Char fName[kDriveNameLen]; // /System, /Boot, //./Devices/USB... + Int32 fKind; // fMassStorage, fFloppy, fOpticalDisc. + rt_drive_id_type fId; // Drive id. + Int32 fFlags; // fReadOnly, fXPMDrive, fXPTDrive + + /// @brief Packet drive (StorageKit compilant.) + struct DrivePacket final + { + Ref fPacketContent; //! packet body. + Char fPacketMime[kDriveNameLen]; //! identify what we're sending. + SizeT fPacketSize; //! packet size + UInt32 fPacketCRC32; //! sanity crc, in case if good is set to false + Boolean fPacketGood; + Lba fLba; + } fPacket; + + Void (*fInput)(DrivePacket* packetPtr); + Void (*fOutput)(DrivePacket* packetPtr); + Void (*fVerify)(DrivePacket* packetPtr); + Void (*fInit)(DrivePacket* packetPtr); + const Char* (*fDriveKind)(Void); + }; + + ///! drive as a device. + typedef DriveTrait* DriveTraitPtr; + + /** + * @brief Mounted drives interface. + * @note This class has all of it's drive set to nullptr, allocate them using + * GetAddressOf(index). + */ + class MountpointInterface final + { + public: + explicit MountpointInterface() = default; + ~MountpointInterface() = default; + + ZKA_COPY_DEFAULT(MountpointInterface); + + public: + DriveTrait& A() + { + return mA; + } + DriveTrait& B() + { + return mB; + } + DriveTrait& C() + { + return mC; + } + DriveTrait& D() + { + return mD; + } + + DriveTraitPtr GetAddressOf(Int32 index) + { + ErrLocal() = kErrorSuccess; + + switch (index) + { + case 0: + return &mA; + case 1: + return &mB; + case 2: + return &mC; + case 3: + return &mD; + default: { + ErrLocal() = kErrorNoSuchDisk; + kcout << "No such disk.\n"; + + break; + } + } + + return nullptr; + } + + private: + DriveTrait mA, mB, mC, mD; + }; + + /// @brief Unimplemented drive. + /// @param pckt + /// @return + Void io_drv_unimplemented(DriveTrait::DrivePacket* pckt); + + /// @brief Gets the drive kind (ATA, SCSI, AHCI...) + /// @param + /// @return the drive kind (ATA, Flash, NVM) + const Char* io_drv_kind(Void); + + /// @brief Makes a new drive. + /// @return the new drive as a trait. + DriveTrait io_construct_drive(void) noexcept; + + /// @brief Fetches the main drive. + /// @return the new drive as a trait. + DriveTrait io_construct_main_drive(void) noexcept; +} // namespace Kernel + +#endif /* ifndef __INC_DRIVE_MANAGER_HXX__ */ diff --git a/dev/zka/KernelKit/DriveMgr.hxx b/dev/zka/KernelKit/DriveMgr.hxx deleted file mode 100644 index ddff013b..00000000 --- a/dev/zka/KernelKit/DriveMgr.hxx +++ /dev/null @@ -1,155 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef __INC_DRIVE_MANAGER_HXX__ -#define __INC_DRIVE_MANAGER_HXX__ - -#include -#include -#include -#include -#include -#include -#include -#include - -#define kMaxDriveCountPerMountpoint (4U) - -#define kDriveInvalidID (-1) -#define kDriveNameLen (32) - -#define DrvSectorCnt(SIZE, SECTOR_SZ) (((SIZE) + (SECTOR_SZ)) / (SECTOR_SZ)) - -namespace Kernel -{ - enum - { - /// Storage type. - kInvalidStorage = -1, - kBlockDevice = 0xAD, - kMassStorage = 0xDA, - kFloppyDisc = 0xCD, - kOpticalDisc = 0xDC, // CD-ROM/DVD-ROM/Blu-Ray - /// Storage flags, combine with below. - kReadOnly = 0x10, // Read only drive - kEPMDrive = 0x11, // Explicit Partition Map. - kEPTDrive = 0x12, // ESP w/ EPM partition. - kMBRDrive = 0x13, // PC classic partition scheme - kGPTDrive = 0x14, // PC new partition scheme - kStorageCount = 9, - }; - - typedef Int64 rt_drive_id_type; - - /// @brief Media drive trait type. - struct DriveTrait final - { - Char fName[kDriveNameLen]; // /System, /Boot, //./Devices/USB... - Int32 fKind; // fMassStorage, fFloppy, fOpticalDisc. - rt_drive_id_type fId; // Drive id. - Int32 fFlags; // fReadOnly, fXPMDrive, fXPTDrive - - /// @brief Packet drive (StorageKit compilant.) - struct DrivePacket final - { - Ref fPacketContent; //! packet body. - Char fPacketMime[kDriveNameLen]; //! identify what we're sending. - SizeT fPacketSize; //! packet size - UInt32 fPacketCRC32; //! sanity crc, in case if good is set to false - Boolean fPacketGood; - Lba fLba; - } fPacket; - - Void (*fInput)(DrivePacket* packetPtr); - Void (*fOutput)(DrivePacket* packetPtr); - Void (*fVerify)(DrivePacket* packetPtr); - Void (*fInit)(DrivePacket* packetPtr); - const Char* (*fDriveKind)(Void); - }; - - ///! drive as a device. - typedef DriveTrait* DriveTraitPtr; - - /** - * @brief Mounted drives interface. - * @note This class has all of it's drive set to nullptr, allocate them using - * GetAddressOf(index). - */ - class MountpointInterface final - { - public: - explicit MountpointInterface() = default; - ~MountpointInterface() = default; - - ZKA_COPY_DEFAULT(MountpointInterface); - - public: - DriveTrait& A() - { - return mA; - } - DriveTrait& B() - { - return mB; - } - DriveTrait& C() - { - return mC; - } - DriveTrait& D() - { - return mD; - } - - DriveTraitPtr GetAddressOf(Int32 index) - { - ErrLocal() = kErrorSuccess; - - switch (index) - { - case 0: - return &mA; - case 1: - return &mB; - case 2: - return &mC; - case 3: - return &mD; - default: { - ErrLocal() = kErrorNoSuchDisk; - kcout << "No such disk.\n"; - - break; - } - } - - return nullptr; - } - - private: - DriveTrait mA, mB, mC, mD; - }; - - /// @brief Unimplemented drive. - /// @param pckt - /// @return - Void io_drv_unimplemented(DriveTrait::DrivePacket* pckt); - - /// @brief Gets the drive kind (ATA, SCSI, AHCI...) - /// @param - /// @return the drive kind (ATA, Flash, NVM) - const Char* io_drv_kind(Void); - - /// @brief Makes a new drive. - /// @return the new drive as a trait. - DriveTrait io_construct_drive(void) noexcept; - - /// @brief Fetches the main drive. - /// @return the new drive as a trait. - DriveTrait io_construct_main_drive(void) noexcept; -} // namespace Kernel - -#endif /* ifndef __INC_DRIVE_MANAGER_HXX__ */ diff --git a/dev/zka/KernelKit/FileMgr.h b/dev/zka/KernelKit/FileMgr.h new file mode 100644 index 00000000..cdda89e7 --- /dev/null +++ b/dev/zka/KernelKit/FileMgr.h @@ -0,0 +1,420 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: FileMgr.h + Purpose: Kernel file manager. + +------------------------------------------- */ + +/* ------------------------------------------- + + Revision History: + + 31/01/24: Update documentation (amlel) + 05/07/24: NeFS support, and fork support, updated constants and specs + as well. + + ------------------------------------------- */ + +#pragma once + +#ifdef __FSKIT_USE_NEFS__ +#include +#endif // __FSKIT_USE_NEFS__ + +#include +#include +#include +#include +#include +#include +#include +#include + +/// @brief Filesystem manager, abstraction over mounted filesystem. +/// Works like the VFS or IFS. + +#define cRestrictR "r" +#define cRestrictRB "rb" +#define cRestrictW "w" +#define cRestrictWB "rw" +#define cRestrictRWB "rwb" + +#define cRestrictMax 5 + +#define node_cast(PTR) reinterpret_cast(PTR) + +/** + @note Refer to first enum. +*/ +#define cFileOpsCount 4 +#define cFileMimeGeneric "n-application-kind/all" + +/** @brief invalid position. (n-pos) */ +#define kNPos (SizeT)(-1); + +namespace Kernel +{ + enum + { + cFileWriteAll = 100, + cFileReadAll = 101, + cFileReadChunk = 102, + cFileWriteChunk = 103, + cFileIOCnt = (cFileWriteChunk - cFileWriteAll) + 1, + // file flags + cFileFlagRsrc = 104, + cFileFlagData = 105, + }; + + typedef VoidPtr NodePtr; + + /** + @brief Filesystem Mgr Interface class + @brief Used to provide common I/O for a specific filesystem. +*/ + class IFilesystemMgr + { + public: + explicit IFilesystemMgr() = default; + virtual ~IFilesystemMgr() = default; + + public: + ZKA_COPY_DEFAULT(IFilesystemMgr); + + public: + /// @brief Mounts a new filesystem into an active state. + /// @param interface the filesystem interface + /// @return + static bool Mount(IFilesystemMgr* interface); + + /// @brief Unmounts the active filesystem + /// @return + static IFilesystemMgr* Unmount(); + + /// @brief Getter, gets the active filesystem. + /// @return + static IFilesystemMgr* GetMounted(); + + public: + virtual NodePtr Create(_Input const Char* path) = 0; + virtual NodePtr CreateAlias(_Input const Char* path) = 0; + virtual NodePtr CreateDirectory(_Input const Char* path) = 0; + virtual NodePtr CreateSwapFile(const Char* path) = 0; + + public: + virtual bool Remove(_Input const Char* path) = 0; + + public: + virtual NodePtr Open(_Input const Char* path, _Input const Char* r) = 0; + + public: + virtual Void Write(_Input NodePtr node, _Input VoidPtr data, _Input Int32 flags, _Input SizeT size) = 0; + + virtual _Output VoidPtr Read(_Input NodePtr node, + _Input Int32 flags, + _Input SizeT sz) = 0; + + virtual Void Write(_Input const Char* name, + _Input NodePtr node, + _Input VoidPtr data, + _Input Int32 flags, + _Input SizeT size) = 0; + + virtual _Output VoidPtr Read(_Input const Char* name, + _Input NodePtr node, + _Input Int32 flags, + _Input SizeT sz) = 0; + + public: + virtual bool Seek(_Input NodePtr node, _Input SizeT off) = 0; + + public: + virtual SizeT Tell(_Input NodePtr node) = 0; + virtual bool Rewind(_Input NodePtr node) = 0; + }; + +#ifdef __FSKIT_USE_NEFS__ + /** + * @brief Based of IFilesystemMgr, takes care of managing NeFS + * disks. + */ + class NeFileSystemMgr final : public IFilesystemMgr + { + public: + explicit NeFileSystemMgr(); + ~NeFileSystemMgr() override; + + public: + ZKA_COPY_DEFAULT(NeFileSystemMgr); + + public: + NodePtr Create(const Char* path) override; + NodePtr CreateAlias(const Char* path) override; + NodePtr CreateDirectory(const Char* path) override; + NodePtr CreateSwapFile(const Char* path) override; + + public: + bool Remove(_Input const Char* path) override; + NodePtr Open(_Input const Char* path, _Input const Char* r) override; + Void Write(_Input NodePtr node, _Input VoidPtr data, _Input Int32 flags, _Input SizeT sz) override; + VoidPtr Read(_Input NodePtr node, _Input Int32 flags, _Input SizeT sz) override; + bool Seek(_Input NodePtr node, _Input SizeT off) override; + SizeT Tell(_Input NodePtr node) override; + bool Rewind(_Input NodePtr node) override; + + Void Write(_Input const Char* name, + _Input NodePtr node, + _Input VoidPtr data, + _Input Int32 flags, + _Input SizeT size) override; + + _Output VoidPtr Read(_Input const Char* name, + _Input NodePtr node, + _Input Int32 flags, + _Input SizeT sz) override; + + public: + /// @brief Get NeFS parser class. + /// @return The filesystem parser class. + NeFSParser* GetParser() noexcept; + + private: + NeFSParser* fImpl{nullptr}; + }; + +#endif // ifdef __FSKIT_USE_NEFS__ + + /** + * Usable FileStream + * @tparam Encoding file encoding (char, wchar_t...) + * @tparam FSClass Filesystem contract who takes care of it. + */ + template + class FileStream final + { + public: + explicit FileStream(const Encoding* path, const Encoding* restrict_type); + ~FileStream(); + + public: + FileStream& operator=(const FileStream&); + FileStream(const FileStream&); + + public: + ErrorOr WriteAll(const VoidPtr data) noexcept + { + if (this->fFileRestrict != eRestrictReadWrite && + this->fFileRestrict != eRestrictReadWriteBinary && + this->fFileRestrict != eRestrictWrite && + this->fFileRestrict != eRestrictWriteBinary) + return ErrorOr(kErrorInvalidData); + + if (data == nullptr) + return ErrorOr(kErrorInvalidData); + + auto man = FSClass::GetMounted(); + + if (man) + { + man->Write(fFile, data, cFileWriteAll); + return ErrorOr(0); + } + + return ErrorOr(kErrorInvalidData); + } + + VoidPtr ReadAll() noexcept + { + if (this->fFileRestrict != eRestrictReadWrite && + this->fFileRestrict != eRestrictReadWriteBinary && + this->fFileRestrict != eRestrictRead && + this->fFileRestrict != eRestrictReadBinary) + return nullptr; + + auto man = FSClass::GetMounted(); + + if (man) + { + VoidPtr ret = man->Read(fFile, cFileReadAll, 0); + return ret; + } + + return nullptr; + } + + ErrorOr WriteAll(const Char* fName, const VoidPtr data) noexcept + { + if (this->fFileRestrict != eRestrictReadWrite && + this->fFileRestrict != eRestrictReadWriteBinary && + this->fFileRestrict != eRestrictWrite && + this->fFileRestrict != eRestrictWriteBinary) + return ErrorOr(kErrorInvalidData); + + if (data == nullptr) + return ErrorOr(kErrorInvalidData); + + auto man = FSClass::GetMounted(); + + if (man) + { + man->Write(fName, fFile, data, cFileWriteAll); + return ErrorOr(0); + } + + return ErrorOr(kErrorInvalidData); + } + + VoidPtr Read(const Char* fName) noexcept + { + if (this->fFileRestrict != eRestrictReadWrite && + this->fFileRestrict != eRestrictReadWriteBinary && + this->fFileRestrict != eRestrictRead && + this->fFileRestrict != eRestrictReadBinary) + return nullptr; + + auto man = FSClass::GetMounted(); + + if (man) + { + VoidPtr ret = man->Read(fName, fFile, cFileReadAll, 0); + return ret; + } + + return nullptr; + } + + VoidPtr Read(SizeT offset, SizeT sz) + { + if (this->fFileRestrict != eRestrictReadWrite && + this->fFileRestrict != eRestrictReadWriteBinary && + this->fFileRestrict != eRestrictRead && + this->fFileRestrict != eRestrictReadBinary) + return nullptr; + + auto man = FSClass::GetMounted(); + + if (man) + { + man->Seek(fFile, offset); + auto ret = man->Read(fFile, cFileReadChunk, sz); + + return ret; + } + + return nullptr; + } + + Void Write(SizeT offset, voidPtr data, SizeT sz) + { + if (this->fFileRestrict != eRestrictReadWrite && + this->fFileRestrict != eRestrictReadWriteBinary && + this->fFileRestrict != eRestrictWrite && + this->fFileRestrict != eRestrictWriteBinary) + return; + + auto man = FSClass::GetMounted(); + + if (man) + { + man->Seek(fFile, offset); + man->Write(fFile, data, sz, cFileReadChunk); + } + } + + public: + /// @brief Leak node pointer. + /// @return The node pointer. + NodePtr Leak() + { + return fFile; + } + + /// @brief Leak MIME. + /// @return The MIME. + Char* MIME() noexcept + { + return const_cast(fMime); + } + + enum + { + eRestrictRead, + eRestrictReadBinary, + eRestrictWrite, + eRestrictWriteBinary, + eRestrictReadWrite, + eRestrictReadWriteBinary, + }; + + private: + NodePtr fFile{nullptr}; + Int32 fFileRestrict{}; + const Char* fMime{cFileMimeGeneric}; + }; + + using FileStreamUTF8 = FileStream; + using FileStreamUTF16 = FileStream; + + typedef UInt64 CursorType; + + /// @brief constructor + template + FileStream::FileStream(const Encoding* path, + const Encoding* restrict_type) + : fFile(Class::GetMounted()->Open(path, restrict_type)) + { + static const auto cLength = 255; + + /// @brief restrict information about the file descriptor. + struct RESTRICT_MAP final + { + Char fRestrict[cLength]; + Int32 fMappedTo; + }; + + const SizeT cRestrictCount = cRestrictMax; + const RESTRICT_MAP cRestrictList[] = { + { + .fRestrict = cRestrictR, + .fMappedTo = eRestrictRead, + }, + { + .fRestrict = cRestrictRB, + .fMappedTo = eRestrictReadBinary, + }, + { + .fRestrict = cRestrictRWB, + .fMappedTo = eRestrictReadWriteBinary, + }, + { + .fRestrict = cRestrictW, + .fMappedTo = eRestrictWrite, + }, + { + .fRestrict = cRestrictWB, + .fMappedTo = eRestrictReadWrite, + }}; + + for (SizeT index = 0; index < cRestrictCount; ++index) + { + if (rt_string_cmp(restrict_type, cRestrictList[index].fRestrict, + rt_string_len(cRestrictList[index].fRestrict)) == 0) + { + fFileRestrict = cRestrictList[index].fMappedTo; + break; + } + } + + kcout << "new file: " << path << ".\r"; + } + + /// @brief destructor + template + FileStream::~FileStream() + { + mm_delete_heap(fFile); + } +} // namespace Kernel diff --git a/dev/zka/KernelKit/FileMgr.hxx b/dev/zka/KernelKit/FileMgr.hxx deleted file mode 100644 index fc6e6fc1..00000000 --- a/dev/zka/KernelKit/FileMgr.hxx +++ /dev/null @@ -1,420 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: FileMgr.hxx - Purpose: Kernel file manager. - -------------------------------------------- */ - -/* ------------------------------------------- - - Revision History: - - 31/01/24: Update documentation (amlel) - 05/07/24: NeFS support, and fork support, updated constants and specs - as well. - - ------------------------------------------- */ - -#pragma once - -#ifdef __FSKIT_USE_NEFS__ -#include -#endif // __FSKIT_USE_NEFS__ - -#include -#include -#include -#include -#include -#include -#include -#include - -/// @brief Filesystem manager, abstraction over mounted filesystem. -/// Works like the VFS or IFS. - -#define cRestrictR "r" -#define cRestrictRB "rb" -#define cRestrictW "w" -#define cRestrictWB "rw" -#define cRestrictRWB "rwb" - -#define cRestrictMax 5 - -#define node_cast(PTR) reinterpret_cast(PTR) - -/** - @note Refer to first enum. -*/ -#define cFileOpsCount 4 -#define cFileMimeGeneric "n-application-kind/all" - -/** @brief invalid position. (n-pos) */ -#define kNPos (SizeT)(-1); - -namespace Kernel -{ - enum - { - cFileWriteAll = 100, - cFileReadAll = 101, - cFileReadChunk = 102, - cFileWriteChunk = 103, - cFileIOCnt = (cFileWriteChunk - cFileWriteAll) + 1, - // file flags - cFileFlagRsrc = 104, - cFileFlagData = 105, - }; - - typedef VoidPtr NodePtr; - - /** - @brief Filesystem Mgr Interface class - @brief Used to provide common I/O for a specific filesystem. -*/ - class IFilesystemMgr - { - public: - explicit IFilesystemMgr() = default; - virtual ~IFilesystemMgr() = default; - - public: - ZKA_COPY_DEFAULT(IFilesystemMgr); - - public: - /// @brief Mounts a new filesystem into an active state. - /// @param interface the filesystem interface - /// @return - static bool Mount(IFilesystemMgr* interface); - - /// @brief Unmounts the active filesystem - /// @return - static IFilesystemMgr* Unmount(); - - /// @brief Getter, gets the active filesystem. - /// @return - static IFilesystemMgr* GetMounted(); - - public: - virtual NodePtr Create(_Input const Char* path) = 0; - virtual NodePtr CreateAlias(_Input const Char* path) = 0; - virtual NodePtr CreateDirectory(_Input const Char* path) = 0; - virtual NodePtr CreateSwapFile(const Char* path) = 0; - - public: - virtual bool Remove(_Input const Char* path) = 0; - - public: - virtual NodePtr Open(_Input const Char* path, _Input const Char* r) = 0; - - public: - virtual Void Write(_Input NodePtr node, _Input VoidPtr data, _Input Int32 flags, _Input SizeT size) = 0; - - virtual _Output VoidPtr Read(_Input NodePtr node, - _Input Int32 flags, - _Input SizeT sz) = 0; - - virtual Void Write(_Input const Char* name, - _Input NodePtr node, - _Input VoidPtr data, - _Input Int32 flags, - _Input SizeT size) = 0; - - virtual _Output VoidPtr Read(_Input const Char* name, - _Input NodePtr node, - _Input Int32 flags, - _Input SizeT sz) = 0; - - public: - virtual bool Seek(_Input NodePtr node, _Input SizeT off) = 0; - - public: - virtual SizeT Tell(_Input NodePtr node) = 0; - virtual bool Rewind(_Input NodePtr node) = 0; - }; - -#ifdef __FSKIT_USE_NEFS__ - /** - * @brief Based of IFilesystemMgr, takes care of managing NeFS - * disks. - */ - class NeFileSystemMgr final : public IFilesystemMgr - { - public: - explicit NeFileSystemMgr(); - ~NeFileSystemMgr() override; - - public: - ZKA_COPY_DEFAULT(NeFileSystemMgr); - - public: - NodePtr Create(const Char* path) override; - NodePtr CreateAlias(const Char* path) override; - NodePtr CreateDirectory(const Char* path) override; - NodePtr CreateSwapFile(const Char* path) override; - - public: - bool Remove(_Input const Char* path) override; - NodePtr Open(_Input const Char* path, _Input const Char* r) override; - Void Write(_Input NodePtr node, _Input VoidPtr data, _Input Int32 flags, _Input SizeT sz) override; - VoidPtr Read(_Input NodePtr node, _Input Int32 flags, _Input SizeT sz) override; - bool Seek(_Input NodePtr node, _Input SizeT off) override; - SizeT Tell(_Input NodePtr node) override; - bool Rewind(_Input NodePtr node) override; - - Void Write(_Input const Char* name, - _Input NodePtr node, - _Input VoidPtr data, - _Input Int32 flags, - _Input SizeT size) override; - - _Output VoidPtr Read(_Input const Char* name, - _Input NodePtr node, - _Input Int32 flags, - _Input SizeT sz) override; - - public: - /// @brief Get NeFS parser class. - /// @return The filesystem parser class. - NeFSParser* GetParser() noexcept; - - private: - NeFSParser* fImpl{nullptr}; - }; - -#endif // ifdef __FSKIT_USE_NEFS__ - - /** - * Usable FileStream - * @tparam Encoding file encoding (char, wchar_t...) - * @tparam FSClass Filesystem contract who takes care of it. - */ - template - class FileStream final - { - public: - explicit FileStream(const Encoding* path, const Encoding* restrict_type); - ~FileStream(); - - public: - FileStream& operator=(const FileStream&); - FileStream(const FileStream&); - - public: - ErrorOr WriteAll(const VoidPtr data) noexcept - { - if (this->fFileRestrict != eRestrictReadWrite && - this->fFileRestrict != eRestrictReadWriteBinary && - this->fFileRestrict != eRestrictWrite && - this->fFileRestrict != eRestrictWriteBinary) - return ErrorOr(kErrorInvalidData); - - if (data == nullptr) - return ErrorOr(kErrorInvalidData); - - auto man = FSClass::GetMounted(); - - if (man) - { - man->Write(fFile, data, cFileWriteAll); - return ErrorOr(0); - } - - return ErrorOr(kErrorInvalidData); - } - - VoidPtr ReadAll() noexcept - { - if (this->fFileRestrict != eRestrictReadWrite && - this->fFileRestrict != eRestrictReadWriteBinary && - this->fFileRestrict != eRestrictRead && - this->fFileRestrict != eRestrictReadBinary) - return nullptr; - - auto man = FSClass::GetMounted(); - - if (man) - { - VoidPtr ret = man->Read(fFile, cFileReadAll, 0); - return ret; - } - - return nullptr; - } - - ErrorOr WriteAll(const Char* fName, const VoidPtr data) noexcept - { - if (this->fFileRestrict != eRestrictReadWrite && - this->fFileRestrict != eRestrictReadWriteBinary && - this->fFileRestrict != eRestrictWrite && - this->fFileRestrict != eRestrictWriteBinary) - return ErrorOr(kErrorInvalidData); - - if (data == nullptr) - return ErrorOr(kErrorInvalidData); - - auto man = FSClass::GetMounted(); - - if (man) - { - man->Write(fName, fFile, data, cFileWriteAll); - return ErrorOr(0); - } - - return ErrorOr(kErrorInvalidData); - } - - VoidPtr Read(const Char* fName) noexcept - { - if (this->fFileRestrict != eRestrictReadWrite && - this->fFileRestrict != eRestrictReadWriteBinary && - this->fFileRestrict != eRestrictRead && - this->fFileRestrict != eRestrictReadBinary) - return nullptr; - - auto man = FSClass::GetMounted(); - - if (man) - { - VoidPtr ret = man->Read(fName, fFile, cFileReadAll, 0); - return ret; - } - - return nullptr; - } - - VoidPtr Read(SizeT offset, SizeT sz) - { - if (this->fFileRestrict != eRestrictReadWrite && - this->fFileRestrict != eRestrictReadWriteBinary && - this->fFileRestrict != eRestrictRead && - this->fFileRestrict != eRestrictReadBinary) - return nullptr; - - auto man = FSClass::GetMounted(); - - if (man) - { - man->Seek(fFile, offset); - auto ret = man->Read(fFile, cFileReadChunk, sz); - - return ret; - } - - return nullptr; - } - - Void Write(SizeT offset, voidPtr data, SizeT sz) - { - if (this->fFileRestrict != eRestrictReadWrite && - this->fFileRestrict != eRestrictReadWriteBinary && - this->fFileRestrict != eRestrictWrite && - this->fFileRestrict != eRestrictWriteBinary) - return; - - auto man = FSClass::GetMounted(); - - if (man) - { - man->Seek(fFile, offset); - man->Write(fFile, data, sz, cFileReadChunk); - } - } - - public: - /// @brief Leak node pointer. - /// @return The node pointer. - NodePtr Leak() - { - return fFile; - } - - /// @brief Leak MIME. - /// @return The MIME. - Char* MIME() noexcept - { - return const_cast(fMime); - } - - enum - { - eRestrictRead, - eRestrictReadBinary, - eRestrictWrite, - eRestrictWriteBinary, - eRestrictReadWrite, - eRestrictReadWriteBinary, - }; - - private: - NodePtr fFile{nullptr}; - Int32 fFileRestrict{}; - const Char* fMime{cFileMimeGeneric}; - }; - - using FileStreamUTF8 = FileStream; - using FileStreamUTF16 = FileStream; - - typedef UInt64 CursorType; - - /// @brief constructor - template - FileStream::FileStream(const Encoding* path, - const Encoding* restrict_type) - : fFile(Class::GetMounted()->Open(path, restrict_type)) - { - static const auto cLength = 255; - - /// @brief restrict information about the file descriptor. - struct RESTRICT_MAP final - { - Char fRestrict[cLength]; - Int32 fMappedTo; - }; - - const SizeT cRestrictCount = cRestrictMax; - const RESTRICT_MAP cRestrictList[] = { - { - .fRestrict = cRestrictR, - .fMappedTo = eRestrictRead, - }, - { - .fRestrict = cRestrictRB, - .fMappedTo = eRestrictReadBinary, - }, - { - .fRestrict = cRestrictRWB, - .fMappedTo = eRestrictReadWriteBinary, - }, - { - .fRestrict = cRestrictW, - .fMappedTo = eRestrictWrite, - }, - { - .fRestrict = cRestrictWB, - .fMappedTo = eRestrictReadWrite, - }}; - - for (SizeT index = 0; index < cRestrictCount; ++index) - { - if (rt_string_cmp(restrict_type, cRestrictList[index].fRestrict, - rt_string_len(cRestrictList[index].fRestrict)) == 0) - { - fFileRestrict = cRestrictList[index].fMappedTo; - break; - } - } - - kcout << "new file: " << path << ".\r"; - } - - /// @brief destructor - template - FileStream::~FileStream() - { - mm_delete_heap(fFile); - } -} // namespace Kernel diff --git a/dev/zka/KernelKit/HardwareThreadScheduler.h b/dev/zka/KernelKit/HardwareThreadScheduler.h new file mode 100644 index 00000000..15848d97 --- /dev/null +++ b/dev/zka/KernelKit/HardwareThreadScheduler.h @@ -0,0 +1,149 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef __INC_MP_MANAGER_HPP__ +#define __INC_MP_MANAGER_HPP__ + +#include +#include +#include + +/// @note Last Rev Sun 28 Jul CET 2024 +/// @note Last Rev Thu, Aug 1, 2024 9:07:38 AM + +#define cMaxHartInsideSched (8U) + +namespace Kernel +{ + class HardwareThread; + class HardwareThreadScheduler; + + using ThreadID = UInt32; + + enum ThreadKind + { + kHartSystemReserved, // System reserved thread, well user can't use it + kHartStandard, // user thread, cannot be used by Kernel + kHartFallback, // fallback thread, cannot be used by user if not clear or + // used by Kernel. + kHartBoot, // The core we booted from, the mama. + kInvalidHart, + kHartCount, + }; + + typedef enum ThreadKind ThreadKind; + typedef ThreadID ThreadID; + + /***********************************************************************************/ + /// + /// \name HardwareThread + /// \brief Abstraction over the CPU's core, used to run processes or threads. + /// + /***********************************************************************************/ + + class HardwareThread final + { + public: + explicit HardwareThread(); + ~HardwareThread(); + + public: + ZKA_COPY_DEFAULT(HardwareThread) + + public: + operator bool(); + + public: + void Wake(const bool wakeup = false) noexcept; + void Busy(const bool busy = false) noexcept; + + public: + bool Switch(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr frame); + bool IsWakeup() noexcept; + + public: + HAL::StackFramePtr StackFrame() noexcept; + const ThreadKind& Kind() noexcept; + bool IsBusy() noexcept; + const ThreadID& ID() noexcept; + + private: + HAL::StackFramePtr fStack{nullptr}; + ThreadKind fKind{ThreadKind::kHartStandard}; + ThreadID fID{0}; + ProcessID fSourcePID{-1}; + Bool fWakeup{false}; + Bool fBusy{false}; + UInt64 fPTime{0}; + + private: + friend class HardwareThreadScheduler; + friend class UserProcessHelper; + }; + + /// + /// \name HardwareThreadScheduler + /// \brief Class to manage the thread scheduling. + /// + + class HardwareThreadScheduler final : public ISchedulerObject + { + private: + friend class UserProcessHelper; + + public: + explicit HardwareThreadScheduler(); + ~HardwareThreadScheduler(); + ZKA_COPY_DEFAULT(HardwareThreadScheduler); + + public: + HAL::StackFramePtr Leak() noexcept; + + public: + Ref operator[](const SizeT& idx); + bool operator!() noexcept; + operator bool() noexcept; + + const Bool IsUser() override + { + return Yes; + } + + const Bool IsKernel() override + { + return No; + } + + const Bool HasMP() override + { + return kHandoverHeader->f_HardwareTables.f_MultiProcessingEnabled; + } + + public: + /// @brief Shared instance of the MP Mgr. + /// @return the reference to the mp manager class. + STATIC HardwareThreadScheduler& The(); + + public: + /// @brief Returns the amount of threads present in the system. + /// @returns SizeT the amount of cores present. + SizeT Count() noexcept; + + private: + Array fThreadList; + ThreadID fCurrentThread{0}; + }; + + /// @brief wakes up thread. + /// wakes up thread from hang. + Void mp_wakeup_thread(HAL::StackFramePtr stack); + + /// @brief makes thread sleep. + /// hooks and hangs thread to prevent code from executing. + Void mp_hang_thread(HAL::StackFramePtr stack); +} // namespace Kernel + +#endif // !__INC_MP_MANAGER_HPP__ diff --git a/dev/zka/KernelKit/HardwareThreadScheduler.hxx b/dev/zka/KernelKit/HardwareThreadScheduler.hxx deleted file mode 100644 index c026f6ac..00000000 --- a/dev/zka/KernelKit/HardwareThreadScheduler.hxx +++ /dev/null @@ -1,149 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef __INC_MP_MANAGER_HPP__ -#define __INC_MP_MANAGER_HPP__ - -#include -#include -#include - -/// @note Last Rev Sun 28 Jul CET 2024 -/// @note Last Rev Thu, Aug 1, 2024 9:07:38 AM - -#define cMaxHartInsideSched (8U) - -namespace Kernel -{ - class HardwareThread; - class HardwareThreadScheduler; - - using ThreadID = UInt32; - - enum ThreadKind - { - kHartSystemReserved, // System reserved thread, well user can't use it - kHartStandard, // user thread, cannot be used by Kernel - kHartFallback, // fallback thread, cannot be used by user if not clear or - // used by Kernel. - kHartBoot, // The core we booted from, the mama. - kInvalidHart, - kHartCount, - }; - - typedef enum ThreadKind ThreadKind; - typedef ThreadID ThreadID; - - /***********************************************************************************/ - /// - /// \name HardwareThread - /// \brief Abstraction over the CPU's core, used to run processes or threads. - /// - /***********************************************************************************/ - - class HardwareThread final - { - public: - explicit HardwareThread(); - ~HardwareThread(); - - public: - ZKA_COPY_DEFAULT(HardwareThread) - - public: - operator bool(); - - public: - void Wake(const bool wakeup = false) noexcept; - void Busy(const bool busy = false) noexcept; - - public: - bool Switch(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr frame); - bool IsWakeup() noexcept; - - public: - HAL::StackFramePtr StackFrame() noexcept; - const ThreadKind& Kind() noexcept; - bool IsBusy() noexcept; - const ThreadID& ID() noexcept; - - private: - HAL::StackFramePtr fStack{nullptr}; - ThreadKind fKind{ThreadKind::kHartStandard}; - ThreadID fID{0}; - ProcessID fSourcePID{-1}; - Bool fWakeup{false}; - Bool fBusy{false}; - UInt64 fPTime{0}; - - private: - friend class HardwareThreadScheduler; - friend class UserProcessHelper; - }; - - /// - /// \name HardwareThreadScheduler - /// \brief Class to manage the thread scheduling. - /// - - class HardwareThreadScheduler final : public ISchedulerObject - { - private: - friend class UserProcessHelper; - - public: - explicit HardwareThreadScheduler(); - ~HardwareThreadScheduler(); - ZKA_COPY_DEFAULT(HardwareThreadScheduler); - - public: - HAL::StackFramePtr Leak() noexcept; - - public: - Ref operator[](const SizeT& idx); - bool operator!() noexcept; - operator bool() noexcept; - - const Bool IsUser() override - { - return Yes; - } - - const Bool IsKernel() override - { - return No; - } - - const Bool HasMP() override - { - return kHandoverHeader->f_HardwareTables.f_MultiProcessingEnabled; - } - - public: - /// @brief Shared instance of the MP Mgr. - /// @return the reference to the mp manager class. - STATIC HardwareThreadScheduler& The(); - - public: - /// @brief Returns the amount of threads present in the system. - /// @returns SizeT the amount of cores present. - SizeT Count() noexcept; - - private: - Array fThreadList; - ThreadID fCurrentThread{0}; - }; - - /// @brief wakes up thread. - /// wakes up thread from hang. - Void mp_wakeup_thread(HAL::StackFramePtr stack); - - /// @brief makes thread sleep. - /// hooks and hangs thread to prevent code from executing. - Void mp_hang_thread(HAL::StackFramePtr stack); -} // namespace Kernel - -#endif // !__INC_MP_MANAGER_HPP__ diff --git a/dev/zka/KernelKit/Heap.h b/dev/zka/KernelKit/Heap.h new file mode 100644 index 00000000..a136b42f --- /dev/null +++ b/dev/zka/KernelKit/Heap.h @@ -0,0 +1,74 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef INC_KERNEL_HEAP_HXX +#define INC_KERNEL_HEAP_HXX + +// last-rev 30/01/24 +// file: Heap.h +// description: heap allocation for the Kernel. + +#include +#include + +namespace Kernel +{ + /// @brief Declare pointer as free. + /// @param heap_ptr the pointer. + /// @return a status code regarding the deallocation. + Int32 mm_delete_heap(VoidPtr heap_ptr); + + /// @brief Declare a new size for heap_ptr. + /// @param heap_ptr the pointer. + /// @return unsupported always returns nullptr. + VoidPtr mm_realloc_heap(VoidPtr heap_ptr, SizeT new_sz); + + /// @brief Check if pointer is a valid Kernel pointer. + /// @param heap_ptr the pointer + /// @return if it exists it returns true. + Boolean mm_is_valid_heap(VoidPtr heap_ptr); + + /// @brief Allocate chunk of memory. + /// @param sz Size of pointer + /// @param wr Read Write bit. + /// @param user User enable bit. + /// @return The newly allocated pointer, or nullptr. + VoidPtr mm_new_heap(const SizeT sz, const Bool wr, const Bool user); + + /// @brief Protect the heap with a CRC value. + /// @param heap_ptr pointer. + /// @return if it valid: point has crc now., otherwise fail. + Boolean mm_protect_heap(VoidPtr heap_ptr); + + /// @brief Makes a Kernel page. + /// @param heap_ptr the page pointer. + /// @return status code + Int32 mm_make_ke_page(VoidPtr heap_ptr); + + /// @brief Allocate C++ class. + template + inline T* mm_new_class(Args&&... args) + { + T* cls = new T(move(args)...); + + if (cls == nullptr) + { + ke_stop(RUNTIME_CHECK_POINTER); + } + + return cls; + } + + /// @brief Free C++ class. + template + inline Void mm_delete_class(T* cls) + { + delete cls; + cls = nullptr; + } +} // namespace Kernel + +#endif // !INC_KERNEL_HEAP_HXX diff --git a/dev/zka/KernelKit/Heap.hxx b/dev/zka/KernelKit/Heap.hxx deleted file mode 100644 index cfa3fc94..00000000 --- a/dev/zka/KernelKit/Heap.hxx +++ /dev/null @@ -1,74 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef INC_KERNEL_HEAP_HXX -#define INC_KERNEL_HEAP_HXX - -// last-rev 30/01/24 -// file: Heap.hxx -// description: heap allocation for the Kernel. - -#include -#include - -namespace Kernel -{ - /// @brief Declare pointer as free. - /// @param heap_ptr the pointer. - /// @return a status code regarding the deallocation. - Int32 mm_delete_heap(VoidPtr heap_ptr); - - /// @brief Declare a new size for heap_ptr. - /// @param heap_ptr the pointer. - /// @return unsupported always returns nullptr. - VoidPtr mm_realloc_heap(VoidPtr heap_ptr, SizeT new_sz); - - /// @brief Check if pointer is a valid Kernel pointer. - /// @param heap_ptr the pointer - /// @return if it exists it returns true. - Boolean mm_is_valid_heap(VoidPtr heap_ptr); - - /// @brief Allocate chunk of memory. - /// @param sz Size of pointer - /// @param wr Read Write bit. - /// @param user User enable bit. - /// @return The newly allocated pointer, or nullptr. - VoidPtr mm_new_heap(const SizeT sz, const Bool wr, const Bool user); - - /// @brief Protect the heap with a CRC value. - /// @param heap_ptr pointer. - /// @return if it valid: point has crc now., otherwise fail. - Boolean mm_protect_heap(VoidPtr heap_ptr); - - /// @brief Makes a Kernel page. - /// @param heap_ptr the page pointer. - /// @return status code - Int32 mm_make_ke_page(VoidPtr heap_ptr); - - /// @brief Allocate C++ class. - template - inline T* mm_new_class(Args&&... args) - { - T* cls = new T(move(args)...); - - if (cls == nullptr) - { - ke_stop(RUNTIME_CHECK_POINTER); - } - - return cls; - } - - /// @brief Free C++ class. - template - inline Void mm_delete_class(T* cls) - { - delete cls; - cls = nullptr; - } -} // namespace Kernel - -#endif // !INC_KERNEL_HEAP_HXX diff --git a/dev/zka/KernelKit/IDLLObject.h b/dev/zka/KernelKit/IDLLObject.h new file mode 100644 index 00000000..e3b09ccc --- /dev/null +++ b/dev/zka/KernelKit/IDLLObject.h @@ -0,0 +1,45 @@ +/* + * ======================================================== + * + * Kernel + * Copyright ZKA Web Services Co., all rights reserved. + * + * ======================================================== + */ + +#pragma once + +#include +#include + +namespace Kernel +{ + class IDLLObject + { + public: + explicit IDLLObject() = default; + virtual ~IDLLObject() = default; + + struct DLL_TRAITS final + { + VoidPtr fImageObject{nullptr}; + VoidPtr fImageEntrypointOffset{nullptr}; + + Bool IsValid() + { + return fImageObject && fImageEntrypointOffset; + } + }; + + ZKA_COPY_DEFAULT(IDLLObject); + + virtual DLL_TRAITS** GetAddressOf() = 0; + virtual DLL_TRAITS* Get() = 0; + + virtual Void Mount(DLL_TRAITS* to_mount) = 0; + virtual Void Unmount() = 0; + }; + + /// @brief Pure implementation, missing method/function handler. + EXTERN_C void __zka_pure_call(void); +} // namespace Kernel diff --git a/dev/zka/KernelKit/IDLLObject.hxx b/dev/zka/KernelKit/IDLLObject.hxx deleted file mode 100644 index 1755b403..00000000 --- a/dev/zka/KernelKit/IDLLObject.hxx +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ======================================================== - * - * Kernel - * Copyright ZKA Web Services Co., all rights reserved. - * - * ======================================================== - */ - -#pragma once - -#include -#include - -namespace Kernel -{ - class IDLLObject - { - public: - explicit IDLLObject() = default; - virtual ~IDLLObject() = default; - - struct DLL_TRAITS final - { - VoidPtr fImageObject{nullptr}; - VoidPtr fImageEntrypointOffset{nullptr}; - - Bool IsValid() - { - return fImageObject && fImageEntrypointOffset; - } - }; - - ZKA_COPY_DEFAULT(IDLLObject); - - virtual DLL_TRAITS** GetAddressOf() = 0; - virtual DLL_TRAITS* Get() = 0; - - virtual Void Mount(DLL_TRAITS* to_mount) = 0; - virtual Void Unmount() = 0; - }; - - /// @brief Pure implementation, missing method/function handler. - EXTERN_C void __zka_pure_call(void); -} // namespace Kernel diff --git a/dev/zka/KernelKit/IPEFDLLObject.h b/dev/zka/KernelKit/IPEFDLLObject.h new file mode 100644 index 00000000..8c0703ed --- /dev/null +++ b/dev/zka/KernelKit/IPEFDLLObject.h @@ -0,0 +1,106 @@ +/* + * ======================================================== + * + * Kernel + * Copyright ZKA Web Services Co., all rights reserved. + * + * ======================================================== + */ + +#ifndef __KERNELKIT_SHARED_OBJECT_HXX__ +#define __KERNELKIT_SHARED_OBJECT_HXX__ + +#include +#include +#include +#include +#include + +namespace Kernel +{ + /** + * @brief Shared Library class + * Load library from this class + */ + class IPEFDLLObject final : public IDLLObject + { + public: + explicit IPEFDLLObject() = default; + ~IPEFDLLObject() = default; + + public: + ZKA_COPY_DEFAULT(IPEFDLLObject); + + private: + DLL_TRAITS* fMounted{nullptr}; + + public: + DLL_TRAITS** GetAddressOf() + { + return &fMounted; + } + + DLL_TRAITS* Get() + { + return fMounted; + } + + public: + void Mount(DLL_TRAITS* to_mount) + { + if (!to_mount || !to_mount->fImageObject) + return; + + fMounted = to_mount; + + if (fLoader && to_mount) + { + delete fLoader; + fLoader = nullptr; + } + + if (!fLoader) + { + fLoader = new PEFLoader(fMounted->fImageObject); + } + } + + void Unmount() + { + if (fMounted) + fMounted = nullptr; + }; + + template + SymbolType Load(const Char* symbol_name, SizeT len, Int32 kind) + { + if (symbol_name == nullptr || *symbol_name == 0) + return nullptr; + if (len > kPathLen || len < 1) + return nullptr; + + auto ret = + reinterpret_cast(fLoader->FindSymbol(symbol_name, kind)); + + if (!ret) + { + if (kind == kPefCode) + return (VoidPtr)&__zka_pure_call; + + return nullptr; + } + + return ret; + } + + private: + PEFLoader* fLoader{nullptr}; + }; + + typedef IPEFDLLObject* IDLL; + + EXTERN_C IDLL rtl_init_dll(UserProcess* header); + EXTERN_C Void rtl_fini_dll(UserProcess* header, IDLL lib, Bool* successful); +} // namespace Kernel + +#endif /* ifndef __KERNELKIT_SHARED_OBJECT_HXX__ */ diff --git a/dev/zka/KernelKit/IPEFDLLObject.hxx b/dev/zka/KernelKit/IPEFDLLObject.hxx deleted file mode 100644 index 7852381d..00000000 --- a/dev/zka/KernelKit/IPEFDLLObject.hxx +++ /dev/null @@ -1,106 +0,0 @@ -/* - * ======================================================== - * - * Kernel - * Copyright ZKA Web Services Co., all rights reserved. - * - * ======================================================== - */ - -#ifndef __KERNELKIT_SHARED_OBJECT_HXX__ -#define __KERNELKIT_SHARED_OBJECT_HXX__ - -#include -#include -#include -#include -#include - -namespace Kernel -{ - /** - * @brief Shared Library class - * Load library from this class - */ - class IPEFDLLObject final : public IDLLObject - { - public: - explicit IPEFDLLObject() = default; - ~IPEFDLLObject() = default; - - public: - ZKA_COPY_DEFAULT(IPEFDLLObject); - - private: - DLL_TRAITS* fMounted{nullptr}; - - public: - DLL_TRAITS** GetAddressOf() - { - return &fMounted; - } - - DLL_TRAITS* Get() - { - return fMounted; - } - - public: - void Mount(DLL_TRAITS* to_mount) - { - if (!to_mount || !to_mount->fImageObject) - return; - - fMounted = to_mount; - - if (fLoader && to_mount) - { - delete fLoader; - fLoader = nullptr; - } - - if (!fLoader) - { - fLoader = new PEFLoader(fMounted->fImageObject); - } - } - - void Unmount() - { - if (fMounted) - fMounted = nullptr; - }; - - template - SymbolType Load(const Char* symbol_name, SizeT len, Int32 kind) - { - if (symbol_name == nullptr || *symbol_name == 0) - return nullptr; - if (len > kPathLen || len < 1) - return nullptr; - - auto ret = - reinterpret_cast(fLoader->FindSymbol(symbol_name, kind)); - - if (!ret) - { - if (kind == kPefCode) - return (VoidPtr)&__zka_pure_call; - - return nullptr; - } - - return ret; - } - - private: - PEFLoader* fLoader{nullptr}; - }; - - typedef IPEFDLLObject* IDLL; - - EXTERN_C IDLL rtl_init_dll(UserProcess* header); - EXTERN_C Void rtl_fini_dll(UserProcess* header, IDLL lib, Bool* successful); -} // namespace Kernel - -#endif /* ifndef __KERNELKIT_SHARED_OBJECT_HXX__ */ diff --git a/dev/zka/KernelKit/LPC.h b/dev/zka/KernelKit/LPC.h new file mode 100644 index 00000000..b0b0fae8 --- /dev/null +++ b/dev/zka/KernelKit/LPC.h @@ -0,0 +1,61 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +/// @file LPC.h +/// @brief Local Process Codes. + +#define ErrLocalIsOk() (Kernel::UserProcessScheduler::The().CurrentProcess().Leak().GetLocalCode() == Kernel::kErrorSuccess) +#define ErrLocalFailed() (Kernel::UserProcessScheduler::The().CurrentProcess().Leak().GetLocalCode() != Kernel::kErrorSuccess) +#define ErrLocal() Kernel::UserProcessScheduler::The().CurrentProcess().Leak().GetLocalCode() + +namespace Kernel +{ + typedef Int32 HError; + + inline constexpr HError kErrorSuccess = 0; + inline constexpr HError kErrorExecutable = 33; + inline constexpr HError kErrorExecutableLib = 34; + inline constexpr HError kErrorFileNotFound = 35; + inline constexpr HError kErrorDirectoryNotFound = 36; + inline constexpr HError kErrorDiskReadOnly = 37; + inline constexpr HError kErrorDiskIsFull = 38; + inline constexpr HError kErrorProcessFault = 39; + inline constexpr HError kErrorSocketHangUp = 40; + inline constexpr HError kErrorThreadLocalStorage = 41; + inline constexpr HError kErrorMath = 42; + inline constexpr HError kErrorNoNetwork = 43; + inline constexpr HError kErrorHeapOutOfMemory = 44; + inline constexpr HError kErrorNoSuchDisk = 45; + inline constexpr HError kErrorFileExists = 46; + inline constexpr HError kErrorFormatFailed = 47; + inline constexpr HError kErrorNetworkTimeout = 48; + inline constexpr HError kErrorInternal = 49; + inline constexpr HError kErrorForkAlreadyExists = 50; + inline constexpr HError kErrorOutOfTeamSlot = 51; + inline constexpr HError kErrorHeapNotPresent = 52; + inline constexpr HError kErrorNoEntrypoint = 53; + inline constexpr HError kErrorDiskIsCorrupted = 54; + inline constexpr HError kErrorDisk = 55; + inline constexpr HError kErrorInvalidData = 56; + inline constexpr HError kErrorAsync = 57; + inline constexpr HError kErrorNonBlocking = 58; + inline constexpr HError kErrorIPC = 59; + inline constexpr HError kErrorSign = 60; + inline constexpr HError kErrorInvalidCreds = 61; + inline constexpr HError kErrorUnimplemented = 0; + + /// @brief Reports a bug to system check. + Void err_bug_check_raise(void) noexcept; + + /// @brief Does a system wide bug check. + /// @param void no params. + /// @return if error-free: false, otherwise true. + Boolean err_bug_check(void) noexcept; +} // namespace Kernel diff --git a/dev/zka/KernelKit/LPC.hxx b/dev/zka/KernelKit/LPC.hxx deleted file mode 100644 index 57c38390..00000000 --- a/dev/zka/KernelKit/LPC.hxx +++ /dev/null @@ -1,61 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -/// @file LPC.hxx -/// @brief Local Process Codes. - -#define ErrLocalIsOk() (Kernel::UserProcessScheduler::The().CurrentProcess().Leak().GetLocalCode() == Kernel::kErrorSuccess) -#define ErrLocalFailed() (Kernel::UserProcessScheduler::The().CurrentProcess().Leak().GetLocalCode() != Kernel::kErrorSuccess) -#define ErrLocal() Kernel::UserProcessScheduler::The().CurrentProcess().Leak().GetLocalCode() - -namespace Kernel -{ - typedef Int32 HError; - - inline constexpr HError kErrorSuccess = 0; - inline constexpr HError kErrorExecutable = 33; - inline constexpr HError kErrorExecutableLib = 34; - inline constexpr HError kErrorFileNotFound = 35; - inline constexpr HError kErrorDirectoryNotFound = 36; - inline constexpr HError kErrorDiskReadOnly = 37; - inline constexpr HError kErrorDiskIsFull = 38; - inline constexpr HError kErrorProcessFault = 39; - inline constexpr HError kErrorSocketHangUp = 40; - inline constexpr HError kErrorThreadLocalStorage = 41; - inline constexpr HError kErrorMath = 42; - inline constexpr HError kErrorNoNetwork = 43; - inline constexpr HError kErrorHeapOutOfMemory = 44; - inline constexpr HError kErrorNoSuchDisk = 45; - inline constexpr HError kErrorFileExists = 46; - inline constexpr HError kErrorFormatFailed = 47; - inline constexpr HError kErrorNetworkTimeout = 48; - inline constexpr HError kErrorInternal = 49; - inline constexpr HError kErrorForkAlreadyExists = 50; - inline constexpr HError kErrorOutOfTeamSlot = 51; - inline constexpr HError kErrorHeapNotPresent = 52; - inline constexpr HError kErrorNoEntrypoint = 53; - inline constexpr HError kErrorDiskIsCorrupted = 54; - inline constexpr HError kErrorDisk = 55; - inline constexpr HError kErrorInvalidData = 56; - inline constexpr HError kErrorAsync = 57; - inline constexpr HError kErrorNonBlocking = 58; - inline constexpr HError kErrorIPC = 59; - inline constexpr HError kErrorSign = 60; - inline constexpr HError kErrorInvalidCreds = 61; - inline constexpr HError kErrorUnimplemented = 0; - - /// @brief Reports a bug to system check. - Void err_bug_check_raise(void) noexcept; - - /// @brief Does a system wide bug check. - /// @param void no params. - /// @return if error-free: false, otherwise true. - Boolean err_bug_check(void) noexcept; -} // namespace Kernel diff --git a/dev/zka/KernelKit/LoaderInterface.h b/dev/zka/KernelKit/LoaderInterface.h new file mode 100644 index 00000000..843b42d8 --- /dev/null +++ b/dev/zka/KernelKit/LoaderInterface.h @@ -0,0 +1,33 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include +#include + +namespace Kernel +{ + /// @brief This interface is used to make loader contracts (MSCOFF, PEF). + /// @author @Amlal-El-Mahrouss + class LoaderInterface + { + public: + explicit LoaderInterface() = default; + virtual ~LoaderInterface() = default; + + ZKA_COPY_DEFAULT(LoaderInterface); + + public: + virtual _Output const Char* AsString() = 0; + virtual _Output const Char* MIME() = 0; + virtual _Output const Char* Path() = 0; + virtual _Output ErrorOr FindStart() = 0; + virtual _Output VoidPtr FindSymbol(_Input const Char* name, _Input Int32 kind) = 0; + }; +} // namespace Kernel diff --git a/dev/zka/KernelKit/LoaderInterface.hxx b/dev/zka/KernelKit/LoaderInterface.hxx deleted file mode 100644 index 246978dd..00000000 --- a/dev/zka/KernelKit/LoaderInterface.hxx +++ /dev/null @@ -1,33 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include -#include - -namespace Kernel -{ - /// @brief This interface is used to make loader contracts (MSCOFF, PEF). - /// @author @Amlal-El-Mahrouss - class LoaderInterface - { - public: - explicit LoaderInterface() = default; - virtual ~LoaderInterface() = default; - - ZKA_COPY_DEFAULT(LoaderInterface); - - public: - virtual _Output const Char* AsString() = 0; - virtual _Output const Char* MIME() = 0; - virtual _Output const Char* Path() = 0; - virtual _Output ErrorOr FindStart() = 0; - virtual _Output VoidPtr FindSymbol(_Input const Char* name, _Input Int32 kind) = 0; - }; -} // namespace Kernel diff --git a/dev/zka/KernelKit/LockDelegate.h b/dev/zka/KernelKit/LockDelegate.h new file mode 100644 index 00000000..8f7e9a42 --- /dev/null +++ b/dev/zka/KernelKit/LockDelegate.h @@ -0,0 +1,67 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include + +namespace Kernel +{ + enum + { + kLockDone = 200, + kLockTimedOut, + }; + + /// @brief Lock condition pointer. + typedef Boolean* LockPtr; + + /// @brief Locking delegate class, hangs until limit. + /// @tparam N the amount of cycles to wait. + template + class LockDelegate final + { + public: + LockDelegate() = delete; + + public: + explicit LockDelegate(LockPtr expr) + { + auto spin = 0U; + + while (spin != N) + { + if (*expr) + { + fLockStatus | kLockDone; + break; + } + } + + if (spin == N) + fLockStatus | kLockTimedOut; + } + + ~LockDelegate() = default; + + LockDelegate& operator=(const LockDelegate&) = delete; + LockDelegate(const LockDelegate&) = delete; + + bool Done() + { + return fLockStatus[kLockDone] == kLockDone; + } + + bool HasTimedOut() + { + return fLockStatus[kLockTimedOut] != kLockTimedOut; + } + + private: + Atom fLockStatus; + }; +} // namespace Kernel diff --git a/dev/zka/KernelKit/LockDelegate.hxx b/dev/zka/KernelKit/LockDelegate.hxx deleted file mode 100644 index 0181fc9b..00000000 --- a/dev/zka/KernelKit/LockDelegate.hxx +++ /dev/null @@ -1,67 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include - -namespace Kernel -{ - enum - { - kLockDone = 200, - kLockTimedOut, - }; - - /// @brief Lock condition pointer. - typedef Boolean* LockPtr; - - /// @brief Locking delegate class, hangs until limit. - /// @tparam N the amount of cycles to wait. - template - class LockDelegate final - { - public: - LockDelegate() = delete; - - public: - explicit LockDelegate(LockPtr expr) - { - auto spin = 0U; - - while (spin != N) - { - if (*expr) - { - fLockStatus | kLockDone; - break; - } - } - - if (spin == N) - fLockStatus | kLockTimedOut; - } - - ~LockDelegate() = default; - - LockDelegate& operator=(const LockDelegate&) = delete; - LockDelegate(const LockDelegate&) = delete; - - bool Done() - { - return fLockStatus[kLockDone] == kLockDone; - } - - bool HasTimedOut() - { - return fLockStatus[kLockTimedOut] != kLockTimedOut; - } - - private: - Atom fLockStatus; - }; -} // namespace Kernel diff --git a/dev/zka/KernelKit/MSDOS.h b/dev/zka/KernelKit/MSDOS.h new file mode 100644 index 00000000..b9f8f13c --- /dev/null +++ b/dev/zka/KernelKit/MSDOS.h @@ -0,0 +1,52 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: MSDOS.hpp + Purpose: MS-DOS header for Kernel. + + Revision History: + + 30/01/24: Added file (amlel) + +------------------------------------------- */ + +#ifndef __MSDOS_EXEC__ +#define __MSDOS_EXEC__ + +#include +#include + +// Last Rev +// Sat Feb 24 CET 2024 + +#define kMagMz0 'M' +#define kMagMz1 'Z' + +typedef Kernel::UInt32 DosWord; +typedef Kernel::Long DosLong; + +typedef struct _DosHeader +{ + Kernel::UInt8 eMagic[2]; + DosWord eMagLen; + DosWord ePagesCount; + DosWord eCrlc; + DosWord eCParHdr; + DosWord eMinAlloc; + DosWord eMaxAlloc; + DosWord eStackSeg; + DosWord eStackPtr; + DosWord eChksum; + DosWord eIp; + DosWord eCs; + DosWord eLfarlc; + DosWord eOvno; + DosWord eRes[4]; + DosWord eOemid; + DosWord eOeminfo; + DosWord eRes2[10]; + DosLong eLfanew; +} DosHeader, *DosHeaderPtr; + +#endif /* ifndef __MSDOS_EXEC__ */ diff --git a/dev/zka/KernelKit/MSDOS.hxx b/dev/zka/KernelKit/MSDOS.hxx deleted file mode 100644 index 1a0698b3..00000000 --- a/dev/zka/KernelKit/MSDOS.hxx +++ /dev/null @@ -1,52 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: MSDOS.hpp - Purpose: MS-DOS header for Kernel. - - Revision History: - - 30/01/24: Added file (amlel) - -------------------------------------------- */ - -#ifndef __MSDOS_EXEC__ -#define __MSDOS_EXEC__ - -#include -#include - -// Last Rev -// Sat Feb 24 CET 2024 - -#define kMagMz0 'M' -#define kMagMz1 'Z' - -typedef Kernel::UInt32 DosWord; -typedef Kernel::Long DosLong; - -typedef struct _DosHeader -{ - Kernel::UInt8 eMagic[2]; - DosWord eMagLen; - DosWord ePagesCount; - DosWord eCrlc; - DosWord eCParHdr; - DosWord eMinAlloc; - DosWord eMaxAlloc; - DosWord eStackSeg; - DosWord eStackPtr; - DosWord eChksum; - DosWord eIp; - DosWord eCs; - DosWord eLfarlc; - DosWord eOvno; - DosWord eRes[4]; - DosWord eOemid; - DosWord eOeminfo; - DosWord eRes2[10]; - DosLong eLfanew; -} DosHeader, *DosHeaderPtr; - -#endif /* ifndef __MSDOS_EXEC__ */ diff --git a/dev/zka/KernelKit/PCI/DMA.h b/dev/zka/KernelKit/PCI/DMA.h new file mode 100644 index 00000000..d13f2c05 --- /dev/null +++ b/dev/zka/KernelKit/PCI/DMA.h @@ -0,0 +1,81 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace Kernel +{ + enum class DmaKind + { + PCI, // Bus mastering is required to be turned on. Basiaclly a request + // control system. 64-Bit access depends on the PAE bit and the device + // (if Double Address Cycle is available) + ISA, // Four DMA channels 0-3; 8 bit transfers and only a megabyte of RAM. + Invalid, + }; + + class DMAWrapper final + { + public: + explicit DMAWrapper() = delete; + + public: + explicit DMAWrapper(nullPtr) = delete; + explicit DMAWrapper(voidPtr Ptr, DmaKind Kind = DmaKind::PCI) + : fAddress(Ptr), fKind(Kind) + { + } + + public: + DMAWrapper& operator=(voidPtr Ptr); + + public: + DMAWrapper& operator=(const DMAWrapper&) = default; + DMAWrapper(const DMAWrapper&) = default; + + public: + ~DMAWrapper() = default; + + template + T* operator->(); + + template + T* Get(const UIntPtr off = 0); + + public: + operator bool(); + bool operator!(); + + public: + bool Write(const UIntPtr& bit, const UIntPtr& offset); + UIntPtr Read(const UIntPtr& offset); + Boolean Check(UIntPtr offset) const; + + public: + UIntPtr operator[](const UIntPtr& offset); + + private: + voidPtr fAddress{nullptr}; + DmaKind fKind{DmaKind::Invalid}; + + private: + friend class DMAFactory; + }; + + class DMAFactory final + { + public: + static OwnPtr> Construct(OwnPtr& dma); + }; +} // namespace Kernel + +#include diff --git a/dev/zka/KernelKit/PCI/DMA.hxx b/dev/zka/KernelKit/PCI/DMA.hxx deleted file mode 100644 index 94dd5ad5..00000000 --- a/dev/zka/KernelKit/PCI/DMA.hxx +++ /dev/null @@ -1,81 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace Kernel -{ - enum class DmaKind - { - PCI, // Bus mastering is required to be turned on. Basiaclly a request - // control system. 64-Bit access depends on the PAE bit and the device - // (if Double Address Cycle is available) - ISA, // Four DMA channels 0-3; 8 bit transfers and only a megabyte of RAM. - Invalid, - }; - - class DMAWrapper final - { - public: - explicit DMAWrapper() = delete; - - public: - explicit DMAWrapper(nullPtr) = delete; - explicit DMAWrapper(voidPtr Ptr, DmaKind Kind = DmaKind::PCI) - : fAddress(Ptr), fKind(Kind) - { - } - - public: - DMAWrapper& operator=(voidPtr Ptr); - - public: - DMAWrapper& operator=(const DMAWrapper&) = default; - DMAWrapper(const DMAWrapper&) = default; - - public: - ~DMAWrapper() = default; - - template - T* operator->(); - - template - T* Get(const UIntPtr off = 0); - - public: - operator bool(); - bool operator!(); - - public: - bool Write(const UIntPtr& bit, const UIntPtr& offset); - UIntPtr Read(const UIntPtr& offset); - Boolean Check(UIntPtr offset) const; - - public: - UIntPtr operator[](const UIntPtr& offset); - - private: - voidPtr fAddress{nullptr}; - DmaKind fKind{DmaKind::Invalid}; - - private: - friend class DMAFactory; - }; - - class DMAFactory final - { - public: - static OwnPtr> Construct(OwnPtr& dma); - }; -} // namespace Kernel - -#include diff --git a/dev/zka/KernelKit/PCI/Database.h b/dev/zka/KernelKit/PCI/Database.h new file mode 100644 index 00000000..4985049a --- /dev/null +++ b/dev/zka/KernelKit/PCI/Database.h @@ -0,0 +1,38 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ +#pragma once + +#include +#include + +namespace Kernel +{ + namespace Types + { + // https://wiki.osdev.org/PCI + enum class PciDeviceKind : UChar + { + MassStorageController = 0x1, + NetworkController = 0x2, + DisplayController = 0x3, + MultimediaController = 0x4, + MemoryController = 0x5, + Bridge = 0x6, + CommunicationController = 0x7, + GenericSystemPeripheral = 0x8, + InputDeviceController = 0x9, + DockingStation = 0xa, + Processor = 0xb, + SerialBusController = 0xc, + WirelessController = 0xd, + IntelligentController = 0xe, + SatelliteCommunicationsController = 0xf, + CoProcessor = 0x40, + Unassgined = 0xf, + Invalid = Unassgined, + }; + } // namespace Types +} // namespace Kernel diff --git a/dev/zka/KernelKit/PCI/Database.hxx b/dev/zka/KernelKit/PCI/Database.hxx deleted file mode 100644 index 16b5c787..00000000 --- a/dev/zka/KernelKit/PCI/Database.hxx +++ /dev/null @@ -1,38 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ -#pragma once - -#include -#include - -namespace Kernel -{ - namespace Types - { - // https://wiki.osdev.org/PCI - enum class PciDeviceKind : UChar - { - MassStorageController = 0x1, - NetworkController = 0x2, - DisplayController = 0x3, - MultimediaController = 0x4, - MemoryController = 0x5, - Bridge = 0x6, - CommunicationController = 0x7, - GenericSystemPeripheral = 0x8, - InputDeviceController = 0x9, - DockingStation = 0xa, - Processor = 0xb, - SerialBusController = 0xc, - WirelessController = 0xd, - IntelligentController = 0xe, - SatelliteCommunicationsController = 0xf, - CoProcessor = 0x40, - Unassgined = 0xf, - Invalid = Unassgined, - }; - } // namespace Types -} // namespace Kernel diff --git a/dev/zka/KernelKit/PCI/Device.h b/dev/zka/KernelKit/PCI/Device.h new file mode 100644 index 00000000..cdedb92b --- /dev/null +++ b/dev/zka/KernelKit/PCI/Device.h @@ -0,0 +1,80 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ +#pragma once + +#include + +namespace Kernel::PCI +{ + enum class PciConfigKind : UShort + { + ConfigAddress = 0xCF8, + ConfigData = 0xCFC, + Invalid = 0xFFF + }; + + class Device final + { + public: + Device() = default; + + public: + explicit Device(UShort bus, UShort device, UShort function, UInt32 bar); + + Device& operator=(const Device&) = default; + + Device(const Device&) = default; + + ~Device(); + + public: + UInt Read(UInt bar, Size szData); + void Write(UInt bar, UIntPtr data, Size szData); + + public: + operator bool(); + + public: + template + UInt Read(UInt bar) + { + static_assert(sizeof(T) <= 4, "64-bit PCI addressing is unsupported"); + return Read(bar, sizeof(T)); + } + + template + void Write(UInt bar, UIntPtr data) + { + static_assert(sizeof(T) <= 4, "64-bit PCI addressing is unsupported"); + Write(bar, data, sizeof(T)); + } + + public: + UShort DeviceId(); + UShort VendorId(); + UShort InterfaceId(); + UChar Class(); + UChar Subclass(); + UChar ProgIf(); + UChar HeaderType(); + UInt32 Bar(UInt32 bar_in); + + public: + void EnableMmio(UInt32 bar_in); + void BecomeBusMaster(UInt32 bar_in); // for PCI-DMA, PC-DMA does not need that. + + UShort Vendor(); + + private: + UShort fBus; + UShort fDevice; + UShort fFunction; + UInt32 fBar; + }; +} // namespace Kernel::PCI + +EXTERN_C void NewOSPCISetCfgTarget(Kernel::UInt bar); +EXTERN_C Kernel::UInt NewOSPCIReadRaw(Kernel::UInt bar); diff --git a/dev/zka/KernelKit/PCI/Device.hxx b/dev/zka/KernelKit/PCI/Device.hxx deleted file mode 100644 index bc1b4eb7..00000000 --- a/dev/zka/KernelKit/PCI/Device.hxx +++ /dev/null @@ -1,80 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ -#pragma once - -#include - -namespace Kernel::PCI -{ - enum class PciConfigKind : UShort - { - ConfigAddress = 0xCF8, - ConfigData = 0xCFC, - Invalid = 0xFFF - }; - - class Device final - { - public: - Device() = default; - - public: - explicit Device(UShort bus, UShort device, UShort function, UInt32 bar); - - Device& operator=(const Device&) = default; - - Device(const Device&) = default; - - ~Device(); - - public: - UInt Read(UInt bar, Size szData); - void Write(UInt bar, UIntPtr data, Size szData); - - public: - operator bool(); - - public: - template - UInt Read(UInt bar) - { - static_assert(sizeof(T) <= 4, "64-bit PCI addressing is unsupported"); - return Read(bar, sizeof(T)); - } - - template - void Write(UInt bar, UIntPtr data) - { - static_assert(sizeof(T) <= 4, "64-bit PCI addressing is unsupported"); - Write(bar, data, sizeof(T)); - } - - public: - UShort DeviceId(); - UShort VendorId(); - UShort InterfaceId(); - UChar Class(); - UChar Subclass(); - UChar ProgIf(); - UChar HeaderType(); - UInt32 Bar(UInt32 bar_in); - - public: - void EnableMmio(UInt32 bar_in); - void BecomeBusMaster(UInt32 bar_in); // for PCI-DMA, PC-DMA does not need that. - - UShort Vendor(); - - private: - UShort fBus; - UShort fDevice; - UShort fFunction; - UInt32 fBar; - }; -} // namespace Kernel::PCI - -EXTERN_C void NewOSPCISetCfgTarget(Kernel::UInt bar); -EXTERN_C Kernel::UInt NewOSPCIReadRaw(Kernel::UInt bar); diff --git a/dev/zka/KernelKit/PCI/Express.h b/dev/zka/KernelKit/PCI/Express.h new file mode 100644 index 00000000..57962631 --- /dev/null +++ b/dev/zka/KernelKit/PCI/Express.h @@ -0,0 +1,11 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +#define PCI_EXPRESS_BUS_COUNT (4096) diff --git a/dev/zka/KernelKit/PCI/Express.hxx b/dev/zka/KernelKit/PCI/Express.hxx deleted file mode 100644 index 1e7ce5bc..00000000 --- a/dev/zka/KernelKit/PCI/Express.hxx +++ /dev/null @@ -1,11 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -#define PCI_EXPRESS_BUS_COUNT (4096) diff --git a/dev/zka/KernelKit/PCI/IO.h b/dev/zka/KernelKit/PCI/IO.h new file mode 100644 index 00000000..d42119f2 --- /dev/null +++ b/dev/zka/KernelKit/PCI/IO.h @@ -0,0 +1,59 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include +#include + +namespace Kernel +{ + template + class IOArray final + { + public: + IOArray() = delete; + + IOArray(nullPtr) = delete; + + explicit IOArray(Array& ports) + : fPorts(ports) + { + } + ~IOArray() + { + } + + IOArray& operator=(const IOArray&) = default; + + IOArray(const IOArray&) = default; + + operator bool() + { + return !fPorts.Empty(); + } + + public: + template + T In(SizeT index); + + template + void Out(SizeT index, T value); + + private: + Array fPorts; + }; + + using IOArray16 = IOArray<16>; +} // namespace Kernel + +#ifdef __x86_64__ +#include +#else +#error Please provide platform specific code for the I/O +#endif // ifdef __x86_64__ diff --git a/dev/zka/KernelKit/PCI/IO.hxx b/dev/zka/KernelKit/PCI/IO.hxx deleted file mode 100644 index 58287a9b..00000000 --- a/dev/zka/KernelKit/PCI/IO.hxx +++ /dev/null @@ -1,59 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include -#include - -namespace Kernel -{ - template - class IOArray final - { - public: - IOArray() = delete; - - IOArray(nullPtr) = delete; - - explicit IOArray(Array& ports) - : fPorts(ports) - { - } - ~IOArray() - { - } - - IOArray& operator=(const IOArray&) = default; - - IOArray(const IOArray&) = default; - - operator bool() - { - return !fPorts.Empty(); - } - - public: - template - T In(SizeT index); - - template - void Out(SizeT index, T value); - - private: - Array fPorts; - }; - - using IOArray16 = IOArray<16>; -} // namespace Kernel - -#ifdef __x86_64__ -#include -#else -#error Please provide platform specific code for the I/O -#endif // ifdef __x86_64__ diff --git a/dev/zka/KernelKit/PCI/Iterator.h b/dev/zka/KernelKit/PCI/Iterator.h new file mode 100644 index 00000000..232a4671 --- /dev/null +++ b/dev/zka/KernelKit/PCI/Iterator.h @@ -0,0 +1,43 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef __PCI_ITERATOR_HPP__ +#define __PCI_ITERATOR_HPP__ + +#include +#include +#include +#include +#include + +#define ZKA_BUS_COUNT (256) +#define ZKA_DEVICE_COUNT (33) +#define ZKA_FUNCTION_COUNT (8) + +namespace Kernel::PCI +{ + class Iterator final + { + public: + Iterator() = delete; + + public: + explicit Iterator(const Types::PciDeviceKind& deviceType); + + Iterator& operator=(const Iterator&) = default; + Iterator(const Iterator&) = default; + + ~Iterator(); + + public: + Ref operator[](const Size& sz); + + private: + Array fDevices; + }; +} // namespace Kernel::PCI + +#endif // __PCI_ITERATOR_HPP__ diff --git a/dev/zka/KernelKit/PCI/Iterator.hxx b/dev/zka/KernelKit/PCI/Iterator.hxx deleted file mode 100644 index a065f9de..00000000 --- a/dev/zka/KernelKit/PCI/Iterator.hxx +++ /dev/null @@ -1,43 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef __PCI_ITERATOR_HPP__ -#define __PCI_ITERATOR_HPP__ - -#include -#include -#include -#include -#include - -#define ZKA_BUS_COUNT (256) -#define ZKA_DEVICE_COUNT (33) -#define ZKA_FUNCTION_COUNT (8) - -namespace Kernel::PCI -{ - class Iterator final - { - public: - Iterator() = delete; - - public: - explicit Iterator(const Types::PciDeviceKind& deviceType); - - Iterator& operator=(const Iterator&) = default; - Iterator(const Iterator&) = default; - - ~Iterator(); - - public: - Ref operator[](const Size& sz); - - private: - Array fDevices; - }; -} // namespace Kernel::PCI - -#endif // __PCI_ITERATOR_HPP__ diff --git a/dev/zka/KernelKit/PCI/PCI.h b/dev/zka/KernelKit/PCI/PCI.h new file mode 100644 index 00000000..b445074f --- /dev/null +++ b/dev/zka/KernelKit/PCI/PCI.h @@ -0,0 +1,59 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +#define cPCIConfigAddressPort (0xCF8) +#define cPCIConfigDataPort (0xCFC) + +#define cPCIDeviceCount (32) +#define cPCIFuncCount (8) +#define cPCIBusCount (255) + +namespace Kernel::PCI +{ + // model + struct DeviceHeader + { + UInt16 VendorId; + UInt16 DeviceId; + UInt8 Command; + UInt8 Status; + UInt8 RevisionId; + UInt8 ProgIf; + UInt8 SubClass; + UInt8 Class; + UInt8 CacheLineSz; + UInt8 LatencyTimer; + UInt8 HeaderType; + UInt8 Bist; + UInt8 Bus; + UInt8 Device; + UInt8 Function; + }; + + namespace Detail + { + class BAR + { + public: + UIntPtr BAR; + SizeT Size; + }; + } // namespace Detail + + class BAR + { + public: + Detail::BAR BAR1; + Detail::BAR BAR2; + Detail::BAR BAR3; + Detail::BAR BAR4; + Detail::BAR BAR5; + }; +} // namespace Kernel::PCI diff --git a/dev/zka/KernelKit/PCI/PCI.hxx b/dev/zka/KernelKit/PCI/PCI.hxx deleted file mode 100644 index 2433be43..00000000 --- a/dev/zka/KernelKit/PCI/PCI.hxx +++ /dev/null @@ -1,59 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -#define cPCIConfigAddressPort (0xCF8) -#define cPCIConfigDataPort (0xCFC) - -#define cPCIDeviceCount (32) -#define cPCIFuncCount (8) -#define cPCIBusCount (255) - -namespace Kernel::PCI -{ - // model - struct DeviceHeader - { - UInt16 VendorId; - UInt16 DeviceId; - UInt8 Command; - UInt8 Status; - UInt8 RevisionId; - UInt8 ProgIf; - UInt8 SubClass; - UInt8 Class; - UInt8 CacheLineSz; - UInt8 LatencyTimer; - UInt8 HeaderType; - UInt8 Bist; - UInt8 Bus; - UInt8 Device; - UInt8 Function; - }; - - namespace Detail - { - class BAR - { - public: - UIntPtr BAR; - SizeT Size; - }; - } // namespace Detail - - class BAR - { - public: - Detail::BAR BAR1; - Detail::BAR BAR2; - Detail::BAR BAR3; - Detail::BAR BAR4; - Detail::BAR BAR5; - }; -} // namespace Kernel::PCI diff --git a/dev/zka/KernelKit/PE.h b/dev/zka/KernelKit/PE.h new file mode 100644 index 00000000..b077f251 --- /dev/null +++ b/dev/zka/KernelKit/PE.h @@ -0,0 +1,143 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: PE.h + Purpose: Portable Executable for Kernel. + + Revision History: + + 30/01/24: Added file (amlel) + +------------------------------------------- */ + +#ifndef __KERNELKIT_INC_PE_HXX__ +#define __KERNELKIT_INC_PE_HXX__ + +#include + +#define kPeSignature 0x00004550 + +#define kPeDLLBase 0x4000000 +#define kPeEXEBase 0x1000000 + +#define kPeMagic32 0x010b +#define kPeMagic64 0x020b + +#define kPeMachineAMD64 0x8664 +#define kPeMachineARM64 0xaa64 + +typedef struct LDR_EXEC_HEADER final +{ + Kernel::UInt32 mSignature; + Kernel::UInt16 mMachine; + Kernel::UInt16 mNumberOfSections; + Kernel::UInt32 mTimeDateStamp; + Kernel::UInt32 mPointerToSymbolTable; + Kernel::UInt32 mNumberOfSymbols; + Kernel::UInt16 mSizeOfOptionalHeader; + Kernel::UInt16 mCharacteristics; +} LDR_EXEC_HEADER, *LDR_EXEC_HEADER_PTR; + +typedef struct LDR_OPTIONAL_HEADER final +{ + Kernel::UInt16 mMagic; // 0x010b - PE32, 0x020b - PE32+ (64 bit) + Kernel::UInt8 mMajorLinkerVersion; + Kernel::UInt8 mMinorLinkerVersion; + Kernel::UInt32 mSizeOfCode; + Kernel::UInt32 mSizeOfInitializedData; + Kernel::UInt32 mSizeOfUninitializedData; + Kernel::UInt32 mAddressOfEntryPoint; + Kernel::UInt32 mBaseOfCode; + Kernel::UInt32 mBaseOfData; + Kernel::UInt32 mImageBase; + Kernel::UInt32 mSectionAlignment; + Kernel::UInt32 mFileAlignment; + Kernel::UInt16 mMajorOperatingSystemVersion; + Kernel::UInt16 mMinorOperatingSystemVersion; + Kernel::UInt16 mMajorImageVersion; + Kernel::UInt16 mMinorImageVersion; + Kernel::UInt16 mMajorSubsystemVersion; + Kernel::UInt16 mMinorSubsystemVersion; + Kernel::UInt32 mWin32VersionValue; + Kernel::UInt32 mSizeOfImage; + Kernel::UInt32 mSizeOfHeaders; + Kernel::UInt32 mCheckSum; + Kernel::UInt16 mSubsystem; + Kernel::UInt16 mDllCharacteristics; + Kernel::UInt32 mSizeOfStackReserve; + Kernel::UInt32 mSizeOfStackCommit; + Kernel::UInt32 mSizeOfHeapReserve; + Kernel::UInt32 mSizeOfHeapCommit; + Kernel::UInt32 mLoaderFlags; + Kernel::UInt32 mNumberOfRvaAndSizes; +} LDR_OPTIONAL_HEADER, *LDR_OPTIONAL_HEADER_PTR; + +typedef struct LDR_SECTION_HEADER final +{ + Kernel::Char mName[8]; + Kernel::UInt32 mVirtualSize; + Kernel::UInt32 mVirtualAddress; + Kernel::UInt32 mSizeOfRawData; + Kernel::UInt32 mPointerToRawData; + Kernel::UInt32 mPointerToRelocations; + Kernel::UInt32 mPointerToLineNumbers; + Kernel::UInt16 mNumberOfRelocations; + Kernel::UInt16 mNumberOfLinenumbers; + Kernel::UInt32 mCharacteristics; +} LDR_SECTION_HEADER, *LDR_SECTION_HEADER_PTR; + +enum kExecDataDirParams +{ + kExecExport, + kExecImport, + kExecInvalid, + kExecCount, +}; + +typedef struct LDR_EXPORT_DIRECTORY +{ + Kernel::UInt32 mCharacteristics; + Kernel::UInt32 mTimeDateStamp; + Kernel::UInt16 mMajorVersion; + Kernel::UInt16 mMinorVersion; + Kernel::UInt32 mName; + Kernel::UInt32 mBase; + Kernel::UInt32 mNumberOfFunctions; + Kernel::UInt32 mNumberOfNames; + Kernel::UInt32 mAddressOfFunctions; // export table rva + Kernel::UInt32 mAddressOfNames; + Kernel::UInt32 mAddressOfNameOrdinal; // ordinal table rva +} LDR_EXPORT_DIRECTORY, *LDR_EXPORT_DIRECTORY_PTR; + +typedef struct LDR_IMPORT_DIRECTORY +{ + union { + Kernel::UInt32 mCharacteristics; + Kernel::UInt32 mOriginalFirstThunk; + }; + Kernel::UInt32 mTimeDateStamp; + Kernel::UInt32 mForwarderChain; + Kernel::UInt32 mNameRva; + Kernel::UInt32 mThunkTableRva; +} LDR_IMPORT_DIRECTORY, *LDR_IMPORT_DIRECTORY_PTR; + +typedef struct LDR_DATA_DIRECTORY +{ + Kernel::UInt32 VirtualAddress; + Kernel::UInt32 Size; +} LDR_DATA_DIRECTORY, *LDR_DATA_DIRECTORY_PTR; + +typedef struct LDR_IMAGE_HEADER +{ + LDR_EXEC_HEADER mHeader; + LDR_OPTIONAL_HEADER mOptHdr; +} LDR_IMAGE_HEADER, *LDR_IMAGE_HEADER_PTR; + +enum +{ + eUserSection = 0x00000020, + cPEResourceId = 0xFFaadd00, +}; + +#endif /* ifndef __KERNELKIT_INC_PE_HXX__ */ diff --git a/dev/zka/KernelKit/PE.hxx b/dev/zka/KernelKit/PE.hxx deleted file mode 100644 index 54b1b12e..00000000 --- a/dev/zka/KernelKit/PE.hxx +++ /dev/null @@ -1,143 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: PE.hxx - Purpose: Portable Executable for Kernel. - - Revision History: - - 30/01/24: Added file (amlel) - -------------------------------------------- */ - -#ifndef __KERNELKIT_INC_PE_HXX__ -#define __KERNELKIT_INC_PE_HXX__ - -#include - -#define kPeSignature 0x00004550 - -#define kPeDLLBase 0x4000000 -#define kPeEXEBase 0x1000000 - -#define kPeMagic32 0x010b -#define kPeMagic64 0x020b - -#define kPeMachineAMD64 0x8664 -#define kPeMachineARM64 0xaa64 - -typedef struct LDR_EXEC_HEADER final -{ - Kernel::UInt32 mSignature; - Kernel::UInt16 mMachine; - Kernel::UInt16 mNumberOfSections; - Kernel::UInt32 mTimeDateStamp; - Kernel::UInt32 mPointerToSymbolTable; - Kernel::UInt32 mNumberOfSymbols; - Kernel::UInt16 mSizeOfOptionalHeader; - Kernel::UInt16 mCharacteristics; -} LDR_EXEC_HEADER, *LDR_EXEC_HEADER_PTR; - -typedef struct LDR_OPTIONAL_HEADER final -{ - Kernel::UInt16 mMagic; // 0x010b - PE32, 0x020b - PE32+ (64 bit) - Kernel::UInt8 mMajorLinkerVersion; - Kernel::UInt8 mMinorLinkerVersion; - Kernel::UInt32 mSizeOfCode; - Kernel::UInt32 mSizeOfInitializedData; - Kernel::UInt32 mSizeOfUninitializedData; - Kernel::UInt32 mAddressOfEntryPoint; - Kernel::UInt32 mBaseOfCode; - Kernel::UInt32 mBaseOfData; - Kernel::UInt32 mImageBase; - Kernel::UInt32 mSectionAlignment; - Kernel::UInt32 mFileAlignment; - Kernel::UInt16 mMajorOperatingSystemVersion; - Kernel::UInt16 mMinorOperatingSystemVersion; - Kernel::UInt16 mMajorImageVersion; - Kernel::UInt16 mMinorImageVersion; - Kernel::UInt16 mMajorSubsystemVersion; - Kernel::UInt16 mMinorSubsystemVersion; - Kernel::UInt32 mWin32VersionValue; - Kernel::UInt32 mSizeOfImage; - Kernel::UInt32 mSizeOfHeaders; - Kernel::UInt32 mCheckSum; - Kernel::UInt16 mSubsystem; - Kernel::UInt16 mDllCharacteristics; - Kernel::UInt32 mSizeOfStackReserve; - Kernel::UInt32 mSizeOfStackCommit; - Kernel::UInt32 mSizeOfHeapReserve; - Kernel::UInt32 mSizeOfHeapCommit; - Kernel::UInt32 mLoaderFlags; - Kernel::UInt32 mNumberOfRvaAndSizes; -} LDR_OPTIONAL_HEADER, *LDR_OPTIONAL_HEADER_PTR; - -typedef struct LDR_SECTION_HEADER final -{ - Kernel::Char mName[8]; - Kernel::UInt32 mVirtualSize; - Kernel::UInt32 mVirtualAddress; - Kernel::UInt32 mSizeOfRawData; - Kernel::UInt32 mPointerToRawData; - Kernel::UInt32 mPointerToRelocations; - Kernel::UInt32 mPointerToLineNumbers; - Kernel::UInt16 mNumberOfRelocations; - Kernel::UInt16 mNumberOfLinenumbers; - Kernel::UInt32 mCharacteristics; -} LDR_SECTION_HEADER, *LDR_SECTION_HEADER_PTR; - -enum kExecDataDirParams -{ - kExecExport, - kExecImport, - kExecInvalid, - kExecCount, -}; - -typedef struct LDR_EXPORT_DIRECTORY -{ - Kernel::UInt32 mCharacteristics; - Kernel::UInt32 mTimeDateStamp; - Kernel::UInt16 mMajorVersion; - Kernel::UInt16 mMinorVersion; - Kernel::UInt32 mName; - Kernel::UInt32 mBase; - Kernel::UInt32 mNumberOfFunctions; - Kernel::UInt32 mNumberOfNames; - Kernel::UInt32 mAddressOfFunctions; // export table rva - Kernel::UInt32 mAddressOfNames; - Kernel::UInt32 mAddressOfNameOrdinal; // ordinal table rva -} LDR_EXPORT_DIRECTORY, *LDR_EXPORT_DIRECTORY_PTR; - -typedef struct LDR_IMPORT_DIRECTORY -{ - union { - Kernel::UInt32 mCharacteristics; - Kernel::UInt32 mOriginalFirstThunk; - }; - Kernel::UInt32 mTimeDateStamp; - Kernel::UInt32 mForwarderChain; - Kernel::UInt32 mNameRva; - Kernel::UInt32 mThunkTableRva; -} LDR_IMPORT_DIRECTORY, *LDR_IMPORT_DIRECTORY_PTR; - -typedef struct LDR_DATA_DIRECTORY -{ - Kernel::UInt32 VirtualAddress; - Kernel::UInt32 Size; -} LDR_DATA_DIRECTORY, *LDR_DATA_DIRECTORY_PTR; - -typedef struct LDR_IMAGE_HEADER -{ - LDR_EXEC_HEADER mHeader; - LDR_OPTIONAL_HEADER mOptHdr; -} LDR_IMAGE_HEADER, *LDR_IMAGE_HEADER_PTR; - -enum -{ - eUserSection = 0x00000020, - cPEResourceId = 0xFFaadd00, -}; - -#endif /* ifndef __KERNELKIT_INC_PE_HXX__ */ diff --git a/dev/zka/KernelKit/PECodeMgr.h b/dev/zka/KernelKit/PECodeMgr.h new file mode 100644 index 00000000..14dd8c1a --- /dev/null +++ b/dev/zka/KernelKit/PECodeMgr.h @@ -0,0 +1,24 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: PECodeMgr.h + Purpose: PE32+ Code Mgr and DLL mgr. + + Revision History: + + 12/02/24: Added file (amlel) + +------------------------------------------- */ + +#pragma once + +//////////////////////////////////////////////////// + +// LAST REV: Mon Feb 12 13:52:01 CET 2024 + +//////////////////////////////////////////////////// + +#include +#include +#include diff --git a/dev/zka/KernelKit/PECodeMgr.hxx b/dev/zka/KernelKit/PECodeMgr.hxx deleted file mode 100644 index 39551909..00000000 --- a/dev/zka/KernelKit/PECodeMgr.hxx +++ /dev/null @@ -1,24 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: PECodeMgr.hxx - Purpose: PE32+ Code Mgr and DLL mgr. - - Revision History: - - 12/02/24: Added file (amlel) - -------------------------------------------- */ - -#pragma once - -//////////////////////////////////////////////////// - -// LAST REV: Mon Feb 12 13:52:01 CET 2024 - -//////////////////////////////////////////////////// - -#include -#include -#include diff --git a/dev/zka/KernelKit/PEF.h b/dev/zka/KernelKit/PEF.h new file mode 100644 index 00000000..15f9c5e2 --- /dev/null +++ b/dev/zka/KernelKit/PEF.h @@ -0,0 +1,116 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: PEF.h + Purpose: Preferred Executable Format for Kernel. + + Revision History: + + ?/?/23: Added file (amlel) + +------------------------------------------- */ + +#ifndef __KERNELKIT_INC_PEF_HXX__ +#define __KERNELKIT_INC_PEF_HXX__ + +#include +#include +#include + +#define kPefMagic "Joy!" +#define kPefMagicFat "yoJ!" + +#define kPefMagicLen 5 + +#define kPefVersion 3 +#define kPefNameLen 255 + +namespace Kernel +{ + enum + { + kPefArchIntel86S, + kPefArchAMD64, + kPefArchRISCV, + kPefArch64x0, /* 64x0. ISA */ + kPefArch32x0, /* 32x0. ISA */ + kPefArchPowerPC, + kPefArchARM64, + kPefArchCount = (kPefArchPowerPC - kPefArchIntel86S) + 1, + kPefArchInvalid = 0xFF, + }; + + enum + { + kPefSubArchAMD, + kPefSubArchIntel, + kPefSubArchGeneric, + kPefSubArchIBM, + }; + + enum + { + kPefKindExec = 1, /* .exe */ + kPefKindSharedObject = 2, /* .lib */ + kPefKindObject = 4, /* .obj */ + kPefKindDebug = 5, /* .dbg */ + kPefKindDriver = 6, + kPefKindCount, + }; + + typedef struct PEFContainer final + { + Char Magic[kPefMagicLen]; + UInt32 Linker; + UInt32 Version; + UInt32 Kind; + UInt32 Abi; + UInt32 Cpu; + UInt32 SubCpu; /* Cpu specific information */ + UIntPtr Start; + SizeT HdrSz; /* Size of header */ + SizeT Count; /* container header count */ + } PACKED PEFContainer; + + /* First PEFCommandHeader starts after PEFContainer */ + + typedef struct PEFCommandHeader final + { + Char Name[kPefNameLen]; /* container name */ + UInt32 Cpu; /* container cpu */ + UInt32 SubCpu; /* container sub-cpu */ + UInt32 Flags; /* container flags */ + UInt16 Kind; /* container kind */ + UIntPtr Offset; /* content offset */ + SizeT Size; /* content Size */ + } PACKED PEFCommandHeader; + + enum + { + kPefCode = 0xC, + kPefData = 0xD, + kPefZero = 0xE, + kPefLinkerID = 0x1, + }; +} // namespace Kernel + +/* not mandatory, only for non fork based filesystems */ +#define kPefExt ".exe" +#define kPefDylibExt ".dll" +#define kPefLibExt ".lib" +#define kPefObjectExt ".obj" +#define kPefDebugExt ".dbg" +#define kPefDriverExt ".sys" + +// Kernel System Binary Interface. +#define kPefAbi (0x5046) + +#define kPefBaseOrigin (0x40000000) + +#define kPefStart "__ImageStart" + +#define kPefForkKind kPefMagic +#define kPefForkKindFAT kPefMagicFat + +#endif /* ifndef __KERNELKIT_INC_PEF_HXX__ */ diff --git a/dev/zka/KernelKit/PEF.hxx b/dev/zka/KernelKit/PEF.hxx deleted file mode 100644 index 98287693..00000000 --- a/dev/zka/KernelKit/PEF.hxx +++ /dev/null @@ -1,116 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: PEF.hxx - Purpose: Preferred Executable Format for Kernel. - - Revision History: - - ?/?/23: Added file (amlel) - -------------------------------------------- */ - -#ifndef __KERNELKIT_INC_PEF_HXX__ -#define __KERNELKIT_INC_PEF_HXX__ - -#include -#include -#include - -#define kPefMagic "Joy!" -#define kPefMagicFat "yoJ!" - -#define kPefMagicLen 5 - -#define kPefVersion 3 -#define kPefNameLen 255 - -namespace Kernel -{ - enum - { - kPefArchIntel86S, - kPefArchAMD64, - kPefArchRISCV, - kPefArch64x0, /* 64x0. ISA */ - kPefArch32x0, /* 32x0. ISA */ - kPefArchPowerPC, - kPefArchARM64, - kPefArchCount = (kPefArchPowerPC - kPefArchIntel86S) + 1, - kPefArchInvalid = 0xFF, - }; - - enum - { - kPefSubArchAMD, - kPefSubArchIntel, - kPefSubArchGeneric, - kPefSubArchIBM, - }; - - enum - { - kPefKindExec = 1, /* .exe */ - kPefKindSharedObject = 2, /* .lib */ - kPefKindObject = 4, /* .obj */ - kPefKindDebug = 5, /* .dbg */ - kPefKindDriver = 6, - kPefKindCount, - }; - - typedef struct PEFContainer final - { - Char Magic[kPefMagicLen]; - UInt32 Linker; - UInt32 Version; - UInt32 Kind; - UInt32 Abi; - UInt32 Cpu; - UInt32 SubCpu; /* Cpu specific information */ - UIntPtr Start; - SizeT HdrSz; /* Size of header */ - SizeT Count; /* container header count */ - } PACKED PEFContainer; - - /* First PEFCommandHeader starts after PEFContainer */ - - typedef struct PEFCommandHeader final - { - Char Name[kPefNameLen]; /* container name */ - UInt32 Cpu; /* container cpu */ - UInt32 SubCpu; /* container sub-cpu */ - UInt32 Flags; /* container flags */ - UInt16 Kind; /* container kind */ - UIntPtr Offset; /* content offset */ - SizeT Size; /* content Size */ - } PACKED PEFCommandHeader; - - enum - { - kPefCode = 0xC, - kPefData = 0xD, - kPefZero = 0xE, - kPefLinkerID = 0x1, - }; -} // namespace Kernel - -/* not mandatory, only for non fork based filesystems */ -#define kPefExt ".exe" -#define kPefDylibExt ".dll" -#define kPefLibExt ".lib" -#define kPefObjectExt ".obj" -#define kPefDebugExt ".dbg" -#define kPefDriverExt ".sys" - -// Kernel System Binary Interface. -#define kPefAbi (0x5046) - -#define kPefBaseOrigin (0x40000000) - -#define kPefStart "__ImageStart" - -#define kPefForkKind kPefMagic -#define kPefForkKindFAT kPefMagicFat - -#endif /* ifndef __KERNELKIT_INC_PEF_HXX__ */ diff --git a/dev/zka/KernelKit/PEFCodeMgr.h b/dev/zka/KernelKit/PEFCodeMgr.h new file mode 100644 index 00000000..8ad9eb01 --- /dev/null +++ b/dev/zka/KernelKit/PEFCodeMgr.h @@ -0,0 +1,67 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef _INC_CODE_MANAGER_PEF_HXX_ +#define _INC_CODE_MANAGER_PEF_HXX_ + +#include +#include +#include +#include + +#define kPefApplicationMime "application/vnd-zka-executable" + +namespace Kernel +{ + /// + /// \name PEFLoader + /// \brief PEF loader class. + /// + class PEFLoader : public LoaderInterface + { + private: + explicit PEFLoader() = delete; + + public: + explicit PEFLoader(const VoidPtr blob); + explicit PEFLoader(const Char* path); + ~PEFLoader() override; + + public: + ZKA_COPY_DEFAULT(PEFLoader); + + public: + const Char* Path() override; + const Char* AsString() override; + const Char* MIME() override; + + public: + ErrorOr FindStart() override; + VoidPtr FindSymbol(const Char* name, Int32 kind) override; + + public: + bool IsLoaded() noexcept; + + private: +#ifdef __FSKIT_USE_NEFS__ + OwnPtr> fFile; +#else + OwnPtr> fFile; +#endif // __FSKIT_USE_NEFS__ + + Ref fPath; + VoidPtr fCachedBlob; + bool fFatBinary; + bool fBad; + }; + + namespace Utils + { + bool execute_from_image(PEFLoader& exec, const Int32& procKind) noexcept; + } // namespace Utils +} // namespace Kernel + +#endif // ifndef _INC_CODE_MANAGER_PEF_HXX_ diff --git a/dev/zka/KernelKit/PEFCodeMgr.hxx b/dev/zka/KernelKit/PEFCodeMgr.hxx deleted file mode 100644 index 006fa6e6..00000000 --- a/dev/zka/KernelKit/PEFCodeMgr.hxx +++ /dev/null @@ -1,67 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef _INC_CODE_MANAGER_PEF_HXX_ -#define _INC_CODE_MANAGER_PEF_HXX_ - -#include -#include -#include -#include - -#define kPefApplicationMime "application/vnd-zka-executable" - -namespace Kernel -{ - /// - /// \name PEFLoader - /// \brief PEF loader class. - /// - class PEFLoader : public LoaderInterface - { - private: - explicit PEFLoader() = delete; - - public: - explicit PEFLoader(const VoidPtr blob); - explicit PEFLoader(const Char* path); - ~PEFLoader() override; - - public: - ZKA_COPY_DEFAULT(PEFLoader); - - public: - const Char* Path() override; - const Char* AsString() override; - const Char* MIME() override; - - public: - ErrorOr FindStart() override; - VoidPtr FindSymbol(const Char* name, Int32 kind) override; - - public: - bool IsLoaded() noexcept; - - private: -#ifdef __FSKIT_USE_NEFS__ - OwnPtr> fFile; -#else - OwnPtr> fFile; -#endif // __FSKIT_USE_NEFS__ - - Ref fPath; - VoidPtr fCachedBlob; - bool fFatBinary; - bool fBad; - }; - - namespace Utils - { - bool execute_from_image(PEFLoader& exec, const Int32& procKind) noexcept; - } // namespace Utils -} // namespace Kernel - -#endif // ifndef _INC_CODE_MANAGER_PEF_HXX_ diff --git a/dev/zka/KernelKit/Semaphore.h b/dev/zka/KernelKit/Semaphore.h new file mode 100644 index 00000000..0ce17e9d --- /dev/null +++ b/dev/zka/KernelKit/Semaphore.h @@ -0,0 +1,43 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +namespace Kernel +{ + class UserProcess; + + typedef UserProcess* UserProcessPtr; + + /// @brief Access control class, which locks a task until one is done. + class Semaphore final + { + public: + explicit Semaphore() = default; + ~Semaphore() = default; + + public: + bool IsLocked() const; + bool Unlock() noexcept; + + public: + void WaitForProcess() noexcept; + + public: + bool Lock(UserProcess* process); + bool LockOrWait(UserProcess* process, TimerInterface* timer); + + public: + ZKA_COPY_DEFAULT(Semaphore); + + private: + UserProcessPtr fLockingProcess{nullptr}; + }; +} // namespace Kernel diff --git a/dev/zka/KernelKit/Semaphore.hxx b/dev/zka/KernelKit/Semaphore.hxx deleted file mode 100644 index 535a683b..00000000 --- a/dev/zka/KernelKit/Semaphore.hxx +++ /dev/null @@ -1,43 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -namespace Kernel -{ - class UserProcess; - - typedef UserProcess* UserProcessPtr; - - /// @brief Access control class, which locks a task until one is done. - class Semaphore final - { - public: - explicit Semaphore() = default; - ~Semaphore() = default; - - public: - bool IsLocked() const; - bool Unlock() noexcept; - - public: - void WaitForProcess() noexcept; - - public: - bool Lock(UserProcess* process); - bool LockOrWait(UserProcess* process, TimerInterface* timer); - - public: - ZKA_COPY_DEFAULT(Semaphore); - - private: - UserProcessPtr fLockingProcess{nullptr}; - }; -} // namespace Kernel diff --git a/dev/zka/KernelKit/ThreadLocalStorage.h b/dev/zka/KernelKit/ThreadLocalStorage.h new file mode 100644 index 00000000..1e6df991 --- /dev/null +++ b/dev/zka/KernelKit/ThreadLocalStorage.h @@ -0,0 +1,54 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef _KERNELKIT_TLS_HPP +#define _KERNELKIT_TLS_HPP + +#include + +///! @brief Thread Local Storage for minoskrnl. + +#define kCookieMag0 'Z' +#define kCookieMag1 'K' +#define kCookieMag2 'A' + +#define kTLSCookieLen (3U) + +struct THREAD_INFORMATION_BLOCK; + +/// @brief Thread Information Block. +/// Located in GS on AMD64, other architectures have their own stuff. (64x0, 32x0, ARM64) +struct PACKED THREAD_INFORMATION_BLOCK final +{ + Kernel::Char f_Cookie[kTLSCookieLen]{0}; //! Thread magic number. + Kernel::VoidPtr f_ThreadRecord{nullptr}; //! Thread information record. +}; + +///! @brief Cookie Sanity check. +Kernel::Boolean tls_check_tib(THREAD_INFORMATION_BLOCK* the_tib); + +///! @brief new ptr syscall. +template +T* tls_new_ptr(void) noexcept; + +///! @brief delete ptr syscall. +template +Kernel::Boolean tls_delete_ptr(T* ptr) noexcept; + +template +T* tls_new_class(Args&&... args); + +/// @brief TLS install TIB and PIB. (syscall) +EXTERN_C Kernel::Void rt_install_tib(THREAD_INFORMATION_BLOCK* TIB, THREAD_INFORMATION_BLOCK* PIB); + +/// @brief TLS check (syscall) +EXTERN_C Kernel::Bool tls_check_syscall_impl(Kernel::VoidPtr TIB) noexcept; + +#include + +// last rev 7/7/24 + +#endif /* ifndef _KERNELKIT_TLS_HPP */ diff --git a/dev/zka/KernelKit/ThreadLocalStorage.hxx b/dev/zka/KernelKit/ThreadLocalStorage.hxx deleted file mode 100644 index 55bb2b5f..00000000 --- a/dev/zka/KernelKit/ThreadLocalStorage.hxx +++ /dev/null @@ -1,54 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef _KERNELKIT_TLS_HPP -#define _KERNELKIT_TLS_HPP - -#include - -///! @brief Thread Local Storage for minoskrnl. - -#define kCookieMag0 'Z' -#define kCookieMag1 'K' -#define kCookieMag2 'A' - -#define kTLSCookieLen (3U) - -struct THREAD_INFORMATION_BLOCK; - -/// @brief Thread Information Block. -/// Located in GS on AMD64, other architectures have their own stuff. (64x0, 32x0, ARM64) -struct PACKED THREAD_INFORMATION_BLOCK final -{ - Kernel::Char f_Cookie[kTLSCookieLen]{0}; //! Thread magic number. - Kernel::VoidPtr f_ThreadRecord{nullptr}; //! Thread information record. -}; - -///! @brief Cookie Sanity check. -Kernel::Boolean tls_check_tib(THREAD_INFORMATION_BLOCK* the_tib); - -///! @brief new ptr syscall. -template -T* tls_new_ptr(void) noexcept; - -///! @brief delete ptr syscall. -template -Kernel::Boolean tls_delete_ptr(T* ptr) noexcept; - -template -T* tls_new_class(Args&&... args); - -/// @brief TLS install TIB and PIB. (syscall) -EXTERN_C Kernel::Void rt_install_tib(THREAD_INFORMATION_BLOCK* TIB, THREAD_INFORMATION_BLOCK* PIB); - -/// @brief TLS check (syscall) -EXTERN_C Kernel::Bool tls_check_syscall_impl(Kernel::VoidPtr TIB) noexcept; - -#include - -// last rev 7/7/24 - -#endif /* ifndef _KERNELKIT_TLS_HPP */ diff --git a/dev/zka/KernelKit/ThreadLocalStorage.inl b/dev/zka/KernelKit/ThreadLocalStorage.inl index 2f0fe553..305d3966 100644 --- a/dev/zka/KernelKit/ThreadLocalStorage.inl +++ b/dev/zka/KernelKit/ThreadLocalStorage.inl @@ -8,7 +8,7 @@ //! @brief Allocate resources from the process's heap storage. #ifndef INC_PROCESS_SCHEDULER_HXX -#include +#include #endif template diff --git a/dev/zka/KernelKit/Timer.h b/dev/zka/KernelKit/Timer.h new file mode 100644 index 00000000..cd0b6c4c --- /dev/null +++ b/dev/zka/KernelKit/Timer.h @@ -0,0 +1,82 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +namespace Kernel +{ + class SoftwareTimer; + class TimerInterface; + + class TimerInterface + { + public: + /// @brief Default constructor + explicit TimerInterface() = default; + virtual ~TimerInterface() = default; + + public: + ZKA_COPY_DEFAULT(TimerInterface); + + public: + virtual Int32 Wait() noexcept; + }; + + class SoftwareTimer final : public TimerInterface + { + public: + explicit SoftwareTimer(Int64 seconds); + ~SoftwareTimer() override; + + public: + ZKA_COPY_DEFAULT(SoftwareTimer); + + public: + Int32 Wait() noexcept override; + + private: + IntPtr* fDigitalTimer{nullptr}; + Int64 fWaitFor{0}; + }; + + class HardwareTimer final : public TimerInterface + { + public: + explicit HardwareTimer(Int64 seconds); + ~HardwareTimer() override; + + public: + ZKA_COPY_DEFAULT(HardwareTimer); + + public: + Int32 Wait() noexcept override; + + private: + IntPtr* fDigitalTimer{nullptr}; + Int64 fWaitFor{0}; + }; + + inline Int64 Milliseconds(Int64 time) + { + if (time < 0) + return 0; + + // TODO: nanoseconds maybe? + return 1000 * 1000 * time; + } + + inline Int64 Seconds(Int64 time) + { + if (time < 0) + return 0; + + return 1000 * Milliseconds(time); + } +} // namespace Kernel diff --git a/dev/zka/KernelKit/Timer.hxx b/dev/zka/KernelKit/Timer.hxx deleted file mode 100644 index 345f59ca..00000000 --- a/dev/zka/KernelKit/Timer.hxx +++ /dev/null @@ -1,82 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -namespace Kernel -{ - class SoftwareTimer; - class TimerInterface; - - class TimerInterface - { - public: - /// @brief Default constructor - explicit TimerInterface() = default; - virtual ~TimerInterface() = default; - - public: - ZKA_COPY_DEFAULT(TimerInterface); - - public: - virtual Int32 Wait() noexcept; - }; - - class SoftwareTimer final : public TimerInterface - { - public: - explicit SoftwareTimer(Int64 seconds); - ~SoftwareTimer() override; - - public: - ZKA_COPY_DEFAULT(SoftwareTimer); - - public: - Int32 Wait() noexcept override; - - private: - IntPtr* fDigitalTimer{nullptr}; - Int64 fWaitFor{0}; - }; - - class HardwareTimer final : public TimerInterface - { - public: - explicit HardwareTimer(Int64 seconds); - ~HardwareTimer() override; - - public: - ZKA_COPY_DEFAULT(HardwareTimer); - - public: - Int32 Wait() noexcept override; - - private: - IntPtr* fDigitalTimer{nullptr}; - Int64 fWaitFor{0}; - }; - - inline Int64 Milliseconds(Int64 time) - { - if (time < 0) - return 0; - - // TODO: nanoseconds maybe? - return 1000 * 1000 * time; - } - - inline Int64 Seconds(Int64 time) - { - if (time < 0) - return 0; - - return 1000 * Milliseconds(time); - } -} // namespace Kernel diff --git a/dev/zka/KernelKit/User.h b/dev/zka/KernelKit/User.h new file mode 100644 index 00000000..10697f28 --- /dev/null +++ b/dev/zka/KernelKit/User.h @@ -0,0 +1,75 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef INC_USER_HXX +#define INC_USER_HXX + +#include +#include +#include +#include + +// user mode users. +#define kSuperUser "ZKA AUTHORITY\\SUPER" +#define kGuestUser "ZKA AUTHORITY\\GUEST" + +#define kUsersDir "\\Users\\" + +#define kMaxUserNameLen (255) +#define kMaxUserTokenLen (255) + +namespace Kernel +{ + class User; + + enum class RingKind + { + kRingStdUser = 1, + kRingSuperUser = 2, + kRingGuestUser = 5, + kRingCount = 3, + }; + + class User final + { + public: + explicit User() = delete; + + User(const Int32& sel, const Char* userName); + User(const RingKind& kind, const Char* userName); + + ~User(); + + public: + ZKA_COPY_DEFAULT(User) + + public: + bool operator==(const User& lhs); + bool operator!=(const User& lhs); + + public: + /// @brief Get software ring + const RingKind& Ring() noexcept; + + /// @brief Get user name + Char* Name() noexcept; + + /// @brief Is he a standard user? + Bool IsStdUser() noexcept; + + /// @brief Is she a super user? + Bool IsSuperUser() noexcept; + + Bool TrySave(const Char* password) noexcept; + + private: + RingKind fRing{RingKind::kRingStdUser}; + Char fUserName[kMaxUserNameLen] = {0}; + Char fUserToken[kMaxUserTokenLen] = {0}; + }; +} // namespace Kernel + +#endif /* ifndef INC_USER_HXX */ diff --git a/dev/zka/KernelKit/User.hxx b/dev/zka/KernelKit/User.hxx deleted file mode 100644 index d082bf93..00000000 --- a/dev/zka/KernelKit/User.hxx +++ /dev/null @@ -1,75 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef INC_USER_HXX -#define INC_USER_HXX - -#include -#include -#include -#include - -// user mode users. -#define kSuperUser "ZKA AUTHORITY\\SUPER" -#define kGuestUser "ZKA AUTHORITY\\GUEST" - -#define kUsersDir "\\Users\\" - -#define kMaxUserNameLen (255) -#define kMaxUserTokenLen (255) - -namespace Kernel -{ - class User; - - enum class RingKind - { - kRingStdUser = 1, - kRingSuperUser = 2, - kRingGuestUser = 5, - kRingCount = 3, - }; - - class User final - { - public: - explicit User() = delete; - - User(const Int32& sel, const Char* userName); - User(const RingKind& kind, const Char* userName); - - ~User(); - - public: - ZKA_COPY_DEFAULT(User) - - public: - bool operator==(const User& lhs); - bool operator!=(const User& lhs); - - public: - /// @brief Get software ring - const RingKind& Ring() noexcept; - - /// @brief Get user name - Char* Name() noexcept; - - /// @brief Is he a standard user? - Bool IsStdUser() noexcept; - - /// @brief Is she a super user? - Bool IsSuperUser() noexcept; - - Bool TrySave(const Char* password) noexcept; - - private: - RingKind fRing{RingKind::kRingStdUser}; - Char fUserName[kMaxUserNameLen] = {0}; - Char fUserToken[kMaxUserTokenLen] = {0}; - }; -} // namespace Kernel - -#endif /* ifndef INC_USER_HXX */ diff --git a/dev/zka/KernelKit/UserProcessScheduler.h b/dev/zka/KernelKit/UserProcessScheduler.h new file mode 100644 index 00000000..637f41b4 --- /dev/null +++ b/dev/zka/KernelKit/UserProcessScheduler.h @@ -0,0 +1,322 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef INC_PROCESS_SCHEDULER_HXX +#define INC_PROCESS_SCHEDULER_HXX + +#include +#include +#include +#include + +#define kSchedMinMicroTime (AffinityKind::kStandard) +#define kSchedInvalidPID (-1) +#define kSchedProcessLimitPerTeam (16U) + +#define kSchedMaxMemoryLimit gib_cast(128) +#define kSchedMaxStackSz mib_cast(8) + +//////////////////////////////////////////////////// + +// LAST REV: Mon Feb 12 13:52:01 CET 2024 + +//////////////////////////////////////////////////// + +namespace Kernel +{ + //! @note Forward declarations. + + class UserProcess; + class IPEFDLLObject; + class UserProcessTeam; + class UserProcessScheduler; + class UserProcessHelper; + + //! @brief UserProcess identifier. + typedef Int64 ProcessID; + + //! @brief UserProcess name length. + inline constexpr SizeT kProcessLen = 256U; + + //! @brief UserProcess status enum. + enum class ProcessStatusKind : Int32 + { + kStarting, + kRunning, + kKilled, + kFrozen, + kDead + }; + + //! @brief Affinity is the amount of nano-seconds this process is going + //! to run. + enum class AffinityKind : Int32 + { + kRealTime = 500, + kVeryHigh = 250, + kHigh = 200, + kStandard = 1000, + kLowUsage = 1500, + kVeryLowUsage = 2000, + }; + + // operator overloading. + + inline bool operator<(AffinityKind lhs, AffinityKind rhs) + { + Int32 lhs_int = static_cast(lhs); + Int32 rhs_int = static_cast(rhs); + + return lhs_int < rhs_int; + } + + inline bool operator>(AffinityKind lhs, AffinityKind rhs) + { + Int32 lhs_int = static_cast(lhs); + Int32 rhs_int = static_cast(rhs); + + return lhs_int > rhs_int; + } + + inline bool operator<=(AffinityKind lhs, AffinityKind rhs) + { + Int32 lhs_int = static_cast(lhs); + Int32 rhs_int = static_cast(rhs); + + return lhs_int <= rhs_int; + } + + inline bool operator>=(AffinityKind lhs, AffinityKind rhs) + { + Int32 lhs_int = static_cast(lhs); + Int32 rhs_int = static_cast(rhs); + + return lhs_int >= rhs_int; + } + + // end of operator overloading. + + enum ProcessSubsystemEnum : Int32 + { + kProcessSubsystemSecurity = 100, + kProcessSubsystemApplication, + kProcessSubsystemService, + kProcessSubsystemDriver, + kProcessSubsystemInvalid = 255, + kProcessSubsystemCount = 4, + }; + + using ProcessSubsystem = ProcessSubsystemEnum; + using ProcessTime = UInt64; + using PID = Int64; + + // for permission manager, tells where we run the code. + enum class ProcessLevelRing : Int32 + { + kRingStdUser = 1, + kRingSuperUser = 2, + kRingGuestUser = 5, + kRingCount = 5, + }; + + // Helper types. + using ImagePtr = VoidPtr; + using HeapPtrKind = VoidPtr; + + /// @name UserProcess + /// @brief User process block. + /// Holds information about the running process/thread. + struct UserProcess final + { + public: + explicit UserProcess(VoidPtr startImage = nullptr) + : Image(startImage) + { + } + + ~UserProcess() = default; + + ZKA_COPY_DEFAULT(UserProcess) + + public: + Void SetImageStart(VoidPtr imageStart) noexcept; + const UInt32& GetExitCode() noexcept; + + public: + Char Name[kProcessLen] = {"ZKA Process"}; + ProcessSubsystem SubSystem{ProcessSubsystem::kProcessSubsystemInvalid}; + User* Owner{nullptr}; + HAL::StackFramePtr StackFrame{nullptr}; + AffinityKind Affinity{AffinityKind::kStandard}; + ProcessStatusKind Status{ProcessStatusKind::kDead}; + UInt8* StackReserve{nullptr}; + + //! @brief Code Image. + ImagePtr Image{nullptr}; + + SizeT StackSize{kSchedMaxStackSz}; + + //! @brief Shared library handle, reserved for kExectuableDLLKind types of executables only. + IPEFDLLObject* PefDLLDelegate{nullptr}; + + // Memory usage. + SizeT MemoryCursor{0}; + SizeT MemoryLimit{kSchedMaxMemoryLimit}; + + struct PROCESS_MEMORY_ENTRY final + { + VoidPtr MemoryEntry; + + struct PROCESS_MEMORY_ENTRY* MemoryPrev; + struct PROCESS_MEMORY_ENTRY* MemoryNext; + }; + + PROCESS_MEMORY_ENTRY* MemoryEntryList{nullptr}; + + UIntPtr MemoryPD{0UL}; + + enum + { + kExectuableKind, + kExectuableDLLKind, + kExectuableKindCount, + }; + + ProcessTime PTime{0}; //! @brief Process allocated tine. + + PID ProcessId{kSchedInvalidPID}; + Int32 Kind{kExectuableKind}; + + public: + //! @brief boolean operator, check status. + operator bool(); + + ///! @brief Crashes the app, exits with code ~0. + Void Crash(); + + ///! @brief Exits the app. + Void Exit(const Int32& exit_code = 0); + + ///! @brief TLS allocate. + ///! @param sz size of new ptr. + VoidPtr New(const SizeT& sz); + + ///! @brief TLS free. + ///! @param ptr the pointer to free. + ///! @param sz the size of it. + Boolean Delete(VoidPtr ptr, const SizeT& sz); + + ///! @brief Wakes up threads. + Void Wake(const bool wakeup = false); + + // UserProcess getters. + public: + ///! @brief Get the process's name + ///! @example 'C Runtime Library' + const Char* GetProcessName() noexcept; + + //! @brief return local error code of process. + //! @return Int32 local error code. + Int32& GetLocalCode() noexcept; + + const User* GetOwner() noexcept; + const ProcessStatusKind& GetStatus() noexcept; + const AffinityKind& GetAffinity() noexcept; + + private: + UInt32 fLastExitCode{0}; + Int32 fLocalCode{0}; + + friend UserProcessScheduler; + friend UserProcessHelper; + }; + + /// \brief Processs Team (contains multiple processes inside it.) + /// Equivalent to a process batch + class UserProcessTeam final + { + public: + explicit UserProcessTeam() = default; + ~UserProcessTeam() = default; + + ZKA_COPY_DEFAULT(UserProcessTeam); + + Array& AsArray(); + Ref& AsRef(); + ProcessID& Id() noexcept; + + public: + Array mProcessList; + Ref mCurrentProcess; + SizeT mProcessAmount{0}; + ProcessID mTeamId{0}; + }; + + using UserProcessPtr = UserProcess*; + + /// @brief UserProcess scheduler class. + /// The main class which you call to schedule processes. + class UserProcessScheduler final : public ISchedulerObject + { + friend class UserProcessHelper; + + public: + explicit UserProcessScheduler() = default; + ~UserProcessScheduler() override = default; + + ZKA_COPY_DEFAULT(UserProcessScheduler) + + operator bool(); + bool operator!(); + + public: + UserProcessTeam& CurrentTeam(); + + public: + SizeT Add(UserProcess process); + Bool Remove(ProcessID process_id); + + const Bool IsUser() override; + const Bool IsKernel() override; + const Bool HasMP() override; + + public: + Ref& CurrentProcess(); + SizeT Run() noexcept; + + public: + STATIC UserProcessScheduler& The(); + + private: + UserProcessTeam mTeam; + }; + + /* + * \brief UserProcess helper class, which contains needed utilities for the scheduler. + */ + + class UserProcessHelper final + { + public: + STATIC bool Switch(VoidPtr image_ptr, UInt8* stack_ptr, HAL::StackFramePtr frame_ptr, const PID& new_pid); + STATIC bool CanBeScheduled(const UserProcess& process); + STATIC PID& TheCurrentPID(); + STATIC SizeT StartScheduling(); + STATIC Bool InitializeScheduler(); + }; + + const UInt32& sched_get_exit_code(void) noexcept; +} // namespace Kernel + +#include + +//////////////////////////////////////////////////// + +// END + +//////////////////////////////////////////////////// + +#endif /* ifndef INC_PROCESS_SCHEDULER_HXX */ diff --git a/dev/zka/KernelKit/UserProcessScheduler.hxx b/dev/zka/KernelKit/UserProcessScheduler.hxx deleted file mode 100644 index bc246683..00000000 --- a/dev/zka/KernelKit/UserProcessScheduler.hxx +++ /dev/null @@ -1,322 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef INC_PROCESS_SCHEDULER_HXX -#define INC_PROCESS_SCHEDULER_HXX - -#include -#include -#include -#include - -#define kSchedMinMicroTime (AffinityKind::kStandard) -#define kSchedInvalidPID (-1) -#define kSchedProcessLimitPerTeam (16U) - -#define kSchedMaxMemoryLimit gib_cast(128) -#define kSchedMaxStackSz mib_cast(8) - -//////////////////////////////////////////////////// - -// LAST REV: Mon Feb 12 13:52:01 CET 2024 - -//////////////////////////////////////////////////// - -namespace Kernel -{ - //! @note Forward declarations. - - class UserProcess; - class IPEFDLLObject; - class UserProcessTeam; - class UserProcessScheduler; - class UserProcessHelper; - - //! @brief UserProcess identifier. - typedef Int64 ProcessID; - - //! @brief UserProcess name length. - inline constexpr SizeT kProcessLen = 256U; - - //! @brief UserProcess status enum. - enum class ProcessStatusKind : Int32 - { - kStarting, - kRunning, - kKilled, - kFrozen, - kDead - }; - - //! @brief Affinity is the amount of nano-seconds this process is going - //! to run. - enum class AffinityKind : Int32 - { - kRealTime = 500, - kVeryHigh = 250, - kHigh = 200, - kStandard = 1000, - kLowUsage = 1500, - kVeryLowUsage = 2000, - }; - - // operator overloading. - - inline bool operator<(AffinityKind lhs, AffinityKind rhs) - { - Int32 lhs_int = static_cast(lhs); - Int32 rhs_int = static_cast(rhs); - - return lhs_int < rhs_int; - } - - inline bool operator>(AffinityKind lhs, AffinityKind rhs) - { - Int32 lhs_int = static_cast(lhs); - Int32 rhs_int = static_cast(rhs); - - return lhs_int > rhs_int; - } - - inline bool operator<=(AffinityKind lhs, AffinityKind rhs) - { - Int32 lhs_int = static_cast(lhs); - Int32 rhs_int = static_cast(rhs); - - return lhs_int <= rhs_int; - } - - inline bool operator>=(AffinityKind lhs, AffinityKind rhs) - { - Int32 lhs_int = static_cast(lhs); - Int32 rhs_int = static_cast(rhs); - - return lhs_int >= rhs_int; - } - - // end of operator overloading. - - enum ProcessSubsystemEnum : Int32 - { - kProcessSubsystemSecurity = 100, - kProcessSubsystemApplication, - kProcessSubsystemService, - kProcessSubsystemDriver, - kProcessSubsystemInvalid = 255, - kProcessSubsystemCount = 4, - }; - - using ProcessSubsystem = ProcessSubsystemEnum; - using ProcessTime = UInt64; - using PID = Int64; - - // for permission manager, tells where we run the code. - enum class ProcessLevelRing : Int32 - { - kRingStdUser = 1, - kRingSuperUser = 2, - kRingGuestUser = 5, - kRingCount = 5, - }; - - // Helper types. - using ImagePtr = VoidPtr; - using HeapPtrKind = VoidPtr; - - /// @name UserProcess - /// @brief User process block. - /// Holds information about the running process/thread. - struct UserProcess final - { - public: - explicit UserProcess(VoidPtr startImage = nullptr) - : Image(startImage) - { - } - - ~UserProcess() = default; - - ZKA_COPY_DEFAULT(UserProcess) - - public: - Void SetImageStart(VoidPtr imageStart) noexcept; - const UInt32& GetExitCode() noexcept; - - public: - Char Name[kProcessLen] = {"ZKA Process"}; - ProcessSubsystem SubSystem{ProcessSubsystem::kProcessSubsystemInvalid}; - User* Owner{nullptr}; - HAL::StackFramePtr StackFrame{nullptr}; - AffinityKind Affinity{AffinityKind::kStandard}; - ProcessStatusKind Status{ProcessStatusKind::kDead}; - UInt8* StackReserve{nullptr}; - - //! @brief Code Image. - ImagePtr Image{nullptr}; - - SizeT StackSize{kSchedMaxStackSz}; - - //! @brief Shared library handle, reserved for kExectuableDLLKind types of executables only. - IPEFDLLObject* PefDLLDelegate{nullptr}; - - // Memory usage. - SizeT MemoryCursor{0}; - SizeT MemoryLimit{kSchedMaxMemoryLimit}; - - struct PROCESS_MEMORY_ENTRY final - { - VoidPtr MemoryEntry; - - struct PROCESS_MEMORY_ENTRY* MemoryPrev; - struct PROCESS_MEMORY_ENTRY* MemoryNext; - }; - - PROCESS_MEMORY_ENTRY* MemoryEntryList{nullptr}; - - UIntPtr MemoryPD{0UL}; - - enum - { - kExectuableKind, - kExectuableDLLKind, - kExectuableKindCount, - }; - - ProcessTime PTime{0}; //! @brief Process allocated tine. - - PID ProcessId{kSchedInvalidPID}; - Int32 Kind{kExectuableKind}; - - public: - //! @brief boolean operator, check status. - operator bool(); - - ///! @brief Crashes the app, exits with code ~0. - Void Crash(); - - ///! @brief Exits the app. - Void Exit(const Int32& exit_code = 0); - - ///! @brief TLS allocate. - ///! @param sz size of new ptr. - VoidPtr New(const SizeT& sz); - - ///! @brief TLS free. - ///! @param ptr the pointer to free. - ///! @param sz the size of it. - Boolean Delete(VoidPtr ptr, const SizeT& sz); - - ///! @brief Wakes up threads. - Void Wake(const bool wakeup = false); - - // UserProcess getters. - public: - ///! @brief Get the process's name - ///! @example 'C Runtime Library' - const Char* GetProcessName() noexcept; - - //! @brief return local error code of process. - //! @return Int32 local error code. - Int32& GetLocalCode() noexcept; - - const User* GetOwner() noexcept; - const ProcessStatusKind& GetStatus() noexcept; - const AffinityKind& GetAffinity() noexcept; - - private: - UInt32 fLastExitCode{0}; - Int32 fLocalCode{0}; - - friend UserProcessScheduler; - friend UserProcessHelper; - }; - - /// \brief Processs Team (contains multiple processes inside it.) - /// Equivalent to a process batch - class UserProcessTeam final - { - public: - explicit UserProcessTeam() = default; - ~UserProcessTeam() = default; - - ZKA_COPY_DEFAULT(UserProcessTeam); - - Array& AsArray(); - Ref& AsRef(); - ProcessID& Id() noexcept; - - public: - Array mProcessList; - Ref mCurrentProcess; - SizeT mProcessAmount{0}; - ProcessID mTeamId{0}; - }; - - using UserProcessPtr = UserProcess*; - - /// @brief UserProcess scheduler class. - /// The main class which you call to schedule processes. - class UserProcessScheduler final : public ISchedulerObject - { - friend class UserProcessHelper; - - public: - explicit UserProcessScheduler() = default; - ~UserProcessScheduler() override = default; - - ZKA_COPY_DEFAULT(UserProcessScheduler) - - operator bool(); - bool operator!(); - - public: - UserProcessTeam& CurrentTeam(); - - public: - SizeT Add(UserProcess process); - Bool Remove(ProcessID process_id); - - const Bool IsUser() override; - const Bool IsKernel() override; - const Bool HasMP() override; - - public: - Ref& CurrentProcess(); - SizeT Run() noexcept; - - public: - STATIC UserProcessScheduler& The(); - - private: - UserProcessTeam mTeam; - }; - - /* - * \brief UserProcess helper class, which contains needed utilities for the scheduler. - */ - - class UserProcessHelper final - { - public: - STATIC bool Switch(VoidPtr image_ptr, UInt8* stack_ptr, HAL::StackFramePtr frame_ptr, const PID& new_pid); - STATIC bool CanBeScheduled(const UserProcess& process); - STATIC PID& TheCurrentPID(); - STATIC SizeT StartScheduling(); - STATIC Bool InitializeScheduler(); - }; - - const UInt32& sched_get_exit_code(void) noexcept; -} // namespace Kernel - -#include - -//////////////////////////////////////////////////// - -// END - -//////////////////////////////////////////////////// - -#endif /* ifndef INC_PROCESS_SCHEDULER_HXX */ diff --git a/dev/zka/KernelKit/XCOFF.h b/dev/zka/KernelKit/XCOFF.h new file mode 100644 index 00000000..a7cf3aff --- /dev/null +++ b/dev/zka/KernelKit/XCOFF.h @@ -0,0 +1,51 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: XCOFF.hpp + Purpose: XCOFF for Kernel. + + Revision History: + + 04/07/24: Added file (amlel) + +------------------------------------------- */ + +#ifndef __INC_XCOFF_HXX__ +#define __INC_XCOFF_HXX__ + +#include + +#define cXCOFF64Magic (0x01F7) + +#define cXCOFFRelFlg (0x0001) +#define cXCOFFExecutable (0x0002) +#define cXCOFFLnno (0x0004) +#define cXCOFFLSyms (0x0008) + +struct XCoffFileHeader; +struct XCoffForkHeader; + +/// @brief XCoff file header, meant for POWER apps. +typedef struct XCoffFileHeader +{ + Kernel::UInt16 fMagic; + Kernel::UInt16 fTarget; + Kernel::UInt16 fNumSecs; + Kernel::UInt32 fTimeDat; + Kernel::UIntPtr fSymPtr; + Kernel::UInt32 fNumSyms; + Kernel::UInt16 fOptHdr; // ?: Number of bytes in optional header +} XCoffFileHeader64; + +#define cForkNameLen (255) + +/// @brief This the executable manifest fork. +typedef struct XCoffForkHeader +{ + Kernel::Char fPropertiesXMLFork[cForkNameLen]; + Kernel::Char fDynamicLoaderFork[cForkNameLen]; + Kernel::Char fCodeSignFork[cForkNameLen]; +} XCoffForkHeader; + +#endif // ifndef __INC_XCOFF_HXX__ diff --git a/dev/zka/KernelKit/XCOFF.hxx b/dev/zka/KernelKit/XCOFF.hxx deleted file mode 100644 index 9a09a617..00000000 --- a/dev/zka/KernelKit/XCOFF.hxx +++ /dev/null @@ -1,51 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: XCOFF.hpp - Purpose: XCOFF for Kernel. - - Revision History: - - 04/07/24: Added file (amlel) - -------------------------------------------- */ - -#ifndef __INC_XCOFF_HXX__ -#define __INC_XCOFF_HXX__ - -#include - -#define cXCOFF64Magic (0x01F7) - -#define cXCOFFRelFlg (0x0001) -#define cXCOFFExecutable (0x0002) -#define cXCOFFLnno (0x0004) -#define cXCOFFLSyms (0x0008) - -struct XCoffFileHeader; -struct XCoffForkHeader; - -/// @brief XCoff file header, meant for POWER apps. -typedef struct XCoffFileHeader -{ - Kernel::UInt16 fMagic; - Kernel::UInt16 fTarget; - Kernel::UInt16 fNumSecs; - Kernel::UInt32 fTimeDat; - Kernel::UIntPtr fSymPtr; - Kernel::UInt32 fNumSyms; - Kernel::UInt16 fOptHdr; // ?: Number of bytes in optional header -} XCoffFileHeader64; - -#define cForkNameLen (255) - -/// @brief This the executable manifest fork. -typedef struct XCoffForkHeader -{ - Kernel::Char fPropertiesXMLFork[cForkNameLen]; - Kernel::Char fDynamicLoaderFork[cForkNameLen]; - Kernel::Char fCodeSignFork[cForkNameLen]; -} XCoffForkHeader; - -#endif // ifndef __INC_XCOFF_HXX__ diff --git a/dev/zka/KernelRsrc.rsrc b/dev/zka/KernelRsrc.rsrc index 8c424ebf..3429a3a2 100644 --- a/dev/zka/KernelRsrc.rsrc +++ b/dev/zka/KernelRsrc.rsrc @@ -1,4 +1,4 @@ -#include "CompilerKit/Version.hxx" +#include "CompilerKit/Version.h" 1 VERSIONINFO FILEVERSION 1,0,0,0 diff --git a/dev/zka/NetworkKit/IP.h b/dev/zka/NetworkKit/IP.h new file mode 100644 index 00000000..6853ad6a --- /dev/null +++ b/dev/zka/NetworkKit/IP.h @@ -0,0 +1,83 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include +#include + +namespace Kernel +{ + class RawIPAddress6; + class RawIPAddress; + class IPFactory; + + class RawIPAddress final + { + private: + explicit RawIPAddress(char bytes[4]); + ~RawIPAddress() = default; + + RawIPAddress& operator=(const RawIPAddress&) = delete; + RawIPAddress(const RawIPAddress&) = default; + + public: + char* Address(); + + char& operator[](const Size& index); + + bool operator==(const RawIPAddress& ipv6); + bool operator!=(const RawIPAddress& ipv6); + + private: + char fAddr[4]; + + friend IPFactory; // it is the one creating these addresses, thus this + // is why the constructors are private. + }; + + /** + * @brief IPv6 address. + */ + class RawIPAddress6 final + { + private: + explicit RawIPAddress6(char Bytes[8]); + ~RawIPAddress6() = default; + + RawIPAddress6& operator=(const RawIPAddress6&) = delete; + RawIPAddress6(const RawIPAddress6&) = default; + + public: + char* Address() + { + return fAddr; + } + + char& operator[](const Size& index); + + bool operator==(const RawIPAddress6& ipv6); + bool operator!=(const RawIPAddress6& ipv6); + + private: + char fAddr[8]; + + friend IPFactory; + }; + + /** + * @brief IP Creation helpers + */ + class IPFactory final + { + public: + static ErrorOr ToStringView(Ref& ipv6); + static ErrorOr ToStringView(Ref& ipv4); + static bool IpCheckVersion4(const Char* ip); + }; +} // namespace Kernel diff --git a/dev/zka/NetworkKit/IP.hxx b/dev/zka/NetworkKit/IP.hxx deleted file mode 100644 index 77848d76..00000000 --- a/dev/zka/NetworkKit/IP.hxx +++ /dev/null @@ -1,83 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include -#include - -namespace Kernel -{ - class RawIPAddress6; - class RawIPAddress; - class IPFactory; - - class RawIPAddress final - { - private: - explicit RawIPAddress(char bytes[4]); - ~RawIPAddress() = default; - - RawIPAddress& operator=(const RawIPAddress&) = delete; - RawIPAddress(const RawIPAddress&) = default; - - public: - char* Address(); - - char& operator[](const Size& index); - - bool operator==(const RawIPAddress& ipv6); - bool operator!=(const RawIPAddress& ipv6); - - private: - char fAddr[4]; - - friend IPFactory; // it is the one creating these addresses, thus this - // is why the constructors are private. - }; - - /** - * @brief IPv6 address. - */ - class RawIPAddress6 final - { - private: - explicit RawIPAddress6(char Bytes[8]); - ~RawIPAddress6() = default; - - RawIPAddress6& operator=(const RawIPAddress6&) = delete; - RawIPAddress6(const RawIPAddress6&) = default; - - public: - char* Address() - { - return fAddr; - } - - char& operator[](const Size& index); - - bool operator==(const RawIPAddress6& ipv6); - bool operator!=(const RawIPAddress6& ipv6); - - private: - char fAddr[8]; - - friend IPFactory; - }; - - /** - * @brief IP Creation helpers - */ - class IPFactory final - { - public: - static ErrorOr ToStringView(Ref& ipv6); - static ErrorOr ToStringView(Ref& ipv4); - static bool IpCheckVersion4(const Char* ip); - }; -} // namespace Kernel diff --git a/dev/zka/NetworkKit/IPC.h b/dev/zka/NetworkKit/IPC.h new file mode 100644 index 00000000..25ececea --- /dev/null +++ b/dev/zka/NetworkKit/IPC.h @@ -0,0 +1,91 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co.. + + File: IPC.h. + Purpose: IPC protocol. + +------------------------------------------- */ + +#ifndef _INC_IPC_ENDPOINT_HXX_ +#define _INC_IPC_ENDPOINT_HXX_ + +#include +#include +#include +#include + +/// @file IPC.h +/// @brief IPC EP protocol. + +/// IA separator. +#define cXPCOMRemoteSeparator ":" + +/// Interchange address, consists of PID:TEAM. +#define cXPCOMRemoteInvalid "00:00" + +#define cXPCOMHeaderMagic (0x4950434) + +namespace Kernel +{ + struct IPC_ADDRESS_STRUCT; + struct IPC_MESSAGE_STRUCT; + + /// @brief 128-bit IPC address. + struct PACKED IPC_ADDRESS_STRUCT final + { + UInt64 UserProcessID; + UInt64 UserProcessTeam; + + //////////////////////////////////// + // some operators. + //////////////////////////////////// + + bool operator==(const IPC_ADDRESS_STRUCT& addr) noexcept + { + return addr.UserProcessID == this->UserProcessID && addr.UserProcessTeam == this->UserProcessTeam; + } + + bool operator==(IPC_ADDRESS_STRUCT& addr) noexcept + { + return addr.UserProcessID == this->UserProcessID && addr.UserProcessTeam == this->UserProcessTeam; + } + }; + + typedef struct IPC_ADDRESS_STRUCT IPCEPAddressKind; + + enum + { + eIPCEPLittleEndian = 0, + eIPCEPBigEndian = 1, + eIPCEPMixedEndian = 2, + }; + + constexpr auto cXPCOMMsgSize = 6094U; + + /// @brief IPC connection header, message cannot be greater than 6K. + typedef struct IPC_MESSAGE_STRUCT final + { + UInt32 IpcHeaderMagic; // cRemoteHeaderMagic + UInt8 IpcEndianess; // 0 : LE, 1 : BE + SizeT IpcPacketSize; + IPCEPAddressKind IpcFrom; + IPCEPAddressKind IpcTo; + UInt32 IpcCRC32; + UInt32 IpcMsg; + UInt32 IpcMsgSz; + UInt8 IpcData[cXPCOMMsgSize]; + } PACKED IPC_MESSAGE_STRUCT; + + /// @brief Sanitize packet function + /// @retval true packet is correct. + /// @retval false packet is incorrect and process has crashed. + Bool ipc_sanitize_packet(_Input IPC_MESSAGE_STRUCT* pckt_in); + + /// @brief Construct packet function + /// @retval true packet is correct. + /// @retval false packet is incorrect and process has crashed. + Bool ipc_construct_packet(_Output IPC_MESSAGE_STRUCT** pckt_in); +} // namespace Kernel + +#endif // _INC_IPC_ENDPOINT_HXX_ diff --git a/dev/zka/NetworkKit/IPC.hxx b/dev/zka/NetworkKit/IPC.hxx deleted file mode 100644 index 11b04990..00000000 --- a/dev/zka/NetworkKit/IPC.hxx +++ /dev/null @@ -1,91 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co.. - - File: IPC.hxx. - Purpose: IPC protocol. - -------------------------------------------- */ - -#ifndef _INC_IPC_ENDPOINT_HXX_ -#define _INC_IPC_ENDPOINT_HXX_ - -#include -#include -#include -#include - -/// @file IPC.hxx -/// @brief IPC EP protocol. - -/// IA separator. -#define cXPCOMRemoteSeparator ":" - -/// Interchange address, consists of PID:TEAM. -#define cXPCOMRemoteInvalid "00:00" - -#define cXPCOMHeaderMagic (0x4950434) - -namespace Kernel -{ - struct IPC_ADDRESS_STRUCT; - struct IPC_MESSAGE_STRUCT; - - /// @brief 128-bit IPC address. - struct PACKED IPC_ADDRESS_STRUCT final - { - UInt64 UserProcessID; - UInt64 UserProcessTeam; - - //////////////////////////////////// - // some operators. - //////////////////////////////////// - - bool operator==(const IPC_ADDRESS_STRUCT& addr) noexcept - { - return addr.UserProcessID == this->UserProcessID && addr.UserProcessTeam == this->UserProcessTeam; - } - - bool operator==(IPC_ADDRESS_STRUCT& addr) noexcept - { - return addr.UserProcessID == this->UserProcessID && addr.UserProcessTeam == this->UserProcessTeam; - } - }; - - typedef struct IPC_ADDRESS_STRUCT IPCEPAddressKind; - - enum - { - eIPCEPLittleEndian = 0, - eIPCEPBigEndian = 1, - eIPCEPMixedEndian = 2, - }; - - constexpr auto cXPCOMMsgSize = 6094U; - - /// @brief IPC connection header, message cannot be greater than 6K. - typedef struct IPC_MESSAGE_STRUCT final - { - UInt32 IpcHeaderMagic; // cRemoteHeaderMagic - UInt8 IpcEndianess; // 0 : LE, 1 : BE - SizeT IpcPacketSize; - IPCEPAddressKind IpcFrom; - IPCEPAddressKind IpcTo; - UInt32 IpcCRC32; - UInt32 IpcMsg; - UInt32 IpcMsgSz; - UInt8 IpcData[cXPCOMMsgSize]; - } PACKED IPC_MESSAGE_STRUCT; - - /// @brief Sanitize packet function - /// @retval true packet is correct. - /// @retval false packet is incorrect and process has crashed. - Bool ipc_sanitize_packet(_Input IPC_MESSAGE_STRUCT* pckt_in); - - /// @brief Construct packet function - /// @retval true packet is correct. - /// @retval false packet is incorrect and process has crashed. - Bool ipc_construct_packet(_Output IPC_MESSAGE_STRUCT** pckt_in); -} // namespace Kernel - -#endif // _INC_IPC_ENDPOINT_HXX_ diff --git a/dev/zka/NetworkKit/LTE.h b/dev/zka/NetworkKit/LTE.h new file mode 100644 index 00000000..1d356acc --- /dev/null +++ b/dev/zka/NetworkKit/LTE.h @@ -0,0 +1,16 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co.. + + File: LTE.h. + Purpose: LTE protocol classes. + +------------------------------------------- */ + +#ifndef _INC_NETWORK_LTE_HXX_ +#define _INC_NETWORK_LTE_HXX_ + +#include +#include + +#endif // ifndef _INC_NETWORK_LTE_HXX_ diff --git a/dev/zka/NetworkKit/LTE.hxx b/dev/zka/NetworkKit/LTE.hxx deleted file mode 100644 index 36f76324..00000000 --- a/dev/zka/NetworkKit/LTE.hxx +++ /dev/null @@ -1,16 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co.. - - File: LTE.hxx. - Purpose: LTE protocol classes. - -------------------------------------------- */ - -#ifndef _INC_NETWORK_LTE_HXX_ -#define _INC_NETWORK_LTE_HXX_ - -#include -#include - -#endif // ifndef _INC_NETWORK_LTE_HXX_ diff --git a/dev/zka/NetworkKit/MAC.h b/dev/zka/NetworkKit/MAC.h new file mode 100644 index 00000000..8794c068 --- /dev/null +++ b/dev/zka/NetworkKit/MAC.h @@ -0,0 +1,29 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +namespace Kernel +{ + class MacAddressGetter; + + /// \brief This retrieves the MAC address of the device. + /// \note Listens for the current NIC. + class MacAddressGetter final + { + public: + explicit MacAddressGetter() = default; + + public: + StringView& AsString(); + Array& AsBytes(); + }; + +} // namespace Kernel diff --git a/dev/zka/NetworkKit/MAC.hxx b/dev/zka/NetworkKit/MAC.hxx deleted file mode 100644 index bd4c0014..00000000 --- a/dev/zka/NetworkKit/MAC.hxx +++ /dev/null @@ -1,29 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -namespace Kernel -{ - class MacAddressGetter; - - /// \brief This retrieves the MAC address of the device. - /// \note Listens for the current NIC. - class MacAddressGetter final - { - public: - explicit MacAddressGetter() = default; - - public: - StringView& AsString(); - Array& AsBytes(); - }; - -} // namespace Kernel diff --git a/dev/zka/NetworkKit/NetworkDevice.h b/dev/zka/NetworkKit/NetworkDevice.h new file mode 100644 index 00000000..2692b14e --- /dev/null +++ b/dev/zka/NetworkKit/NetworkDevice.h @@ -0,0 +1,80 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef __INC_NETWORK_DEVICE_HPP__ +#define __INC_NETWORK_DEVICE_HPP__ + +#include +#include + +/// @note Can either work with: Ethernet, GPRS, WiFi + +namespace Kernel +{ + struct NetworkDeviceCommand; + class NetworkDevice; + + /** + * \brief Network device interface, establishes a connection to the NIC. + */ + class NetworkDevice final : public DeviceInterface + { + public: + NetworkDevice(void (*out)(NetworkDeviceCommand), + void (*in)(NetworkDeviceCommand), + void (*onCleanup)(void) = nullptr); + + ~NetworkDevice() override; + + public: + NetworkDevice& operator=(const NetworkDevice&) = default; + NetworkDevice(const NetworkDevice&) = default; + + public: + const Char* Name() const override; + Boolean Name(const Char* strView); + + private: + static constexpr auto cNetworkNameLen = 512; + + Void (*fCleanup)(void); + Char fNetworkName[cNetworkNameLen]; + }; + + struct NetworkDeviceCommand final + { + UInt32 CommandName; + UInt32 CommandType; + UInt32 CommandFlags; + VoidPtr CommandBuffer; + SizeT CommandSizeBuffer; + }; + + /// @brief TCP device. + using TCPNetworkDevice = NetworkDevice; + + /// @brief UDP device. + using UDPNetworkDevice = NetworkDevice; + + /// @brief PPP device. + using PPPNetworkDevice = NetworkDevice; + + /// @brief IPC device. + using IPCEPNetworkDevice = NetworkDevice; + + /// @brief GRPS device. + using GPRSNetworkDevice = NetworkDevice; + + /// @brief GSM device. + using GSMNetworkDevice = NetworkDevice; + + /// @brief LTE device. + using LTENetworkDevice = NetworkDevice; +} // namespace Kernel + +#include + +#endif // !__INC_NETWORK_DEVICE_HPP__ diff --git a/dev/zka/NetworkKit/NetworkDevice.hxx b/dev/zka/NetworkKit/NetworkDevice.hxx deleted file mode 100644 index 4f05d4b2..00000000 --- a/dev/zka/NetworkKit/NetworkDevice.hxx +++ /dev/null @@ -1,80 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef __INC_NETWORK_DEVICE_HPP__ -#define __INC_NETWORK_DEVICE_HPP__ - -#include -#include - -/// @note Can either work with: Ethernet, GPRS, WiFi - -namespace Kernel -{ - struct NetworkDeviceCommand; - class NetworkDevice; - - /** - * \brief Network device interface, establishes a connection to the NIC. - */ - class NetworkDevice final : public DeviceInterface - { - public: - NetworkDevice(void (*out)(NetworkDeviceCommand), - void (*in)(NetworkDeviceCommand), - void (*onCleanup)(void) = nullptr); - - ~NetworkDevice() override; - - public: - NetworkDevice& operator=(const NetworkDevice&) = default; - NetworkDevice(const NetworkDevice&) = default; - - public: - const Char* Name() const override; - Boolean Name(const Char* strView); - - private: - static constexpr auto cNetworkNameLen = 512; - - Void (*fCleanup)(void); - Char fNetworkName[cNetworkNameLen]; - }; - - struct NetworkDeviceCommand final - { - UInt32 CommandName; - UInt32 CommandType; - UInt32 CommandFlags; - VoidPtr CommandBuffer; - SizeT CommandSizeBuffer; - }; - - /// @brief TCP device. - using TCPNetworkDevice = NetworkDevice; - - /// @brief UDP device. - using UDPNetworkDevice = NetworkDevice; - - /// @brief PPP device. - using PPPNetworkDevice = NetworkDevice; - - /// @brief IPC device. - using IPCEPNetworkDevice = NetworkDevice; - - /// @brief GRPS device. - using GPRSNetworkDevice = NetworkDevice; - - /// @brief GSM device. - using GSMNetworkDevice = NetworkDevice; - - /// @brief LTE device. - using LTENetworkDevice = NetworkDevice; -} // namespace Kernel - -#include - -#endif // !__INC_NETWORK_DEVICE_HPP__ diff --git a/dev/zka/NewKit/Array.h b/dev/zka/NewKit/Array.h new file mode 100644 index 00000000..31a6a6d0 --- /dev/null +++ b/dev/zka/NewKit/Array.h @@ -0,0 +1,74 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +namespace Kernel +{ + template + class Array final + { + public: + explicit Array() + { + for (SizeT i = 0; i < N; i++) + { + if (!fArray[i]) + fArray[i] = T(); + } + } + + ~Array() = default; + + Array& operator=(const Array&) = default; + Array(const Array&) = default; + + T& operator[](const SizeT& At) + { + return fArray[At]; + } + + Boolean Empty() const + { + return No; + } + + const SizeT Capacity() + { + return N; + } + + const SizeT Count() + { + SizeT count = 0; + + for (SizeT i = 0; i < N; i++) + { + if (fArray[i]) + ++count; + } + + return count; + } + + const T* CData() + { + return fArray; + } + + operator bool() + { + return !Empty(); + } + + private: + T fArray[N]; + }; +} // namespace Kernel diff --git a/dev/zka/NewKit/Array.hxx b/dev/zka/NewKit/Array.hxx deleted file mode 100644 index 31778e1b..00000000 --- a/dev/zka/NewKit/Array.hxx +++ /dev/null @@ -1,74 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -namespace Kernel -{ - template - class Array final - { - public: - explicit Array() - { - for (SizeT i = 0; i < N; i++) - { - if (!fArray[i]) - fArray[i] = T(); - } - } - - ~Array() = default; - - Array& operator=(const Array&) = default; - Array(const Array&) = default; - - T& operator[](const SizeT& At) - { - return fArray[At]; - } - - Boolean Empty() const - { - return No; - } - - const SizeT Capacity() - { - return N; - } - - const SizeT Count() - { - SizeT count = 0; - - for (SizeT i = 0; i < N; i++) - { - if (fArray[i]) - ++count; - } - - return count; - } - - const T* CData() - { - return fArray; - } - - operator bool() - { - return !Empty(); - } - - private: - T fArray[N]; - }; -} // namespace Kernel diff --git a/dev/zka/NewKit/ArrayList.h b/dev/zka/NewKit/ArrayList.h new file mode 100644 index 00000000..12949b64 --- /dev/null +++ b/dev/zka/NewKit/ArrayList.h @@ -0,0 +1,58 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +namespace Kernel +{ + template + class ArrayList final + { + public: + explicit ArrayList(T* list) + : fList(reinterpret_cast(list)) + { + } + + ~ArrayList() = default; + + ArrayList& operator=(const ArrayList&) = default; + ArrayList(const ArrayList&) = default; + + T* Data() + { + return fList; + } + + const T* CData() + { + return fList; + } + + T& operator[](int index) const + { + return fList[index]; + } + + operator bool() + { + return fList; + } + + private: + T* fList; + + friend class InitHelpers; + }; + + template + ArrayList make_list(ValueType val) + { + return ArrayList{val}; + } +} // namespace Kernel diff --git a/dev/zka/NewKit/ArrayList.hxx b/dev/zka/NewKit/ArrayList.hxx deleted file mode 100644 index f4402cf3..00000000 --- a/dev/zka/NewKit/ArrayList.hxx +++ /dev/null @@ -1,58 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -namespace Kernel -{ - template - class ArrayList final - { - public: - explicit ArrayList(T* list) - : fList(reinterpret_cast(list)) - { - } - - ~ArrayList() = default; - - ArrayList& operator=(const ArrayList&) = default; - ArrayList(const ArrayList&) = default; - - T* Data() - { - return fList; - } - - const T* CData() - { - return fList; - } - - T& operator[](int index) const - { - return fList[index]; - } - - operator bool() - { - return fList; - } - - private: - T* fList; - - friend class InitHelpers; - }; - - template - ArrayList make_list(ValueType val) - { - return ArrayList{val}; - } -} // namespace Kernel diff --git a/dev/zka/NewKit/Atom.h b/dev/zka/NewKit/Atom.h new file mode 100644 index 00000000..955d40fb --- /dev/null +++ b/dev/zka/NewKit/Atom.h @@ -0,0 +1,46 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ +#pragma once + +#include + +namespace Kernel +{ + template + class Atom final + { + public: + explicit Atom() = default; + ~Atom() = default; + + public: + Atom& operator=(const Atom&) = delete; + Atom(const Atom&) = delete; + + public: + T operator[](Size sz) + { + return (fArrayOfAtoms & sz); + } + void operator|(Size sz) + { + fArrayOfAtoms |= sz; + } + + friend Boolean operator==(Atom& atomic, const T& idx) + { + return atomic[idx] == idx; + } + + friend Boolean operator!=(Atom& atomic, const T& idx) + { + return atomic[idx] == idx; + } + + private: + T fArrayOfAtoms; + }; +} // namespace Kernel diff --git a/dev/zka/NewKit/Atom.hxx b/dev/zka/NewKit/Atom.hxx deleted file mode 100644 index 43948765..00000000 --- a/dev/zka/NewKit/Atom.hxx +++ /dev/null @@ -1,46 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ -#pragma once - -#include - -namespace Kernel -{ - template - class Atom final - { - public: - explicit Atom() = default; - ~Atom() = default; - - public: - Atom& operator=(const Atom&) = delete; - Atom(const Atom&) = delete; - - public: - T operator[](Size sz) - { - return (fArrayOfAtoms & sz); - } - void operator|(Size sz) - { - fArrayOfAtoms |= sz; - } - - friend Boolean operator==(Atom& atomic, const T& idx) - { - return atomic[idx] == idx; - } - - friend Boolean operator!=(Atom& atomic, const T& idx) - { - return atomic[idx] == idx; - } - - private: - T fArrayOfAtoms; - }; -} // namespace Kernel diff --git a/dev/zka/NewKit/Crc32.h b/dev/zka/NewKit/Crc32.h new file mode 100644 index 00000000..cacb4105 --- /dev/null +++ b/dev/zka/NewKit/Crc32.h @@ -0,0 +1,23 @@ +/* + * ======================================================== + * + * ZKA + * Date Added: 13/02/2023 + * Copyright ZKA Web Services Co., all rights reserved. + * + * ======================================================== + */ + +#ifndef __CRC32_H__ +#define __CRC32_H__ + +#include + +#define kCrcCnt (256) + +namespace Kernel +{ + UInt ke_calculate_crc32(const Char* crc, UInt len) noexcept; +} // namespace Kernel + +#endif // !__CRC32_H__ diff --git a/dev/zka/NewKit/Crc32.hxx b/dev/zka/NewKit/Crc32.hxx deleted file mode 100644 index 0b828479..00000000 --- a/dev/zka/NewKit/Crc32.hxx +++ /dev/null @@ -1,23 +0,0 @@ -/* - * ======================================================== - * - * ZKA - * Date Added: 13/02/2023 - * Copyright ZKA Web Services Co., all rights reserved. - * - * ======================================================== - */ - -#ifndef __CRC32_H__ -#define __CRC32_H__ - -#include - -#define kCrcCnt (256) - -namespace Kernel -{ - UInt ke_calculate_crc32(const Char* crc, UInt len) noexcept; -} // namespace Kernel - -#endif // !__CRC32_H__ diff --git a/dev/zka/NewKit/CxxAbi.h b/dev/zka/NewKit/CxxAbi.h new file mode 100644 index 00000000..36dcf0b3 --- /dev/null +++ b/dev/zka/NewKit/CxxAbi.h @@ -0,0 +1,28 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ +#pragma once + +#include + +#ifndef __NDK__ + +#define kDSOMaxObjects (128) + +struct atexit_func_entry_t +{ + void (*destructor_func)(void*); + void* obj_ptr; + void* dso_handle; +}; + +typedef unsigned uarch_t; + +namespace cxxabiv1 +{ + typedef void* __guard; +} + +#endif // __GNUC__ diff --git a/dev/zka/NewKit/CxxAbi.hxx b/dev/zka/NewKit/CxxAbi.hxx deleted file mode 100644 index 3f14d357..00000000 --- a/dev/zka/NewKit/CxxAbi.hxx +++ /dev/null @@ -1,28 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ -#pragma once - -#include - -#ifndef __NDK__ - -#define kDSOMaxObjects (128) - -struct atexit_func_entry_t -{ - void (*destructor_func)(void*); - void* obj_ptr; - void* dso_handle; -}; - -typedef unsigned uarch_t; - -namespace cxxabiv1 -{ - typedef void* __guard; -} - -#endif // __GNUC__ diff --git a/dev/zka/NewKit/Defines.h b/dev/zka/NewKit/Defines.h new file mode 100644 index 00000000..f1a82e99 --- /dev/null +++ b/dev/zka/NewKit/Defines.h @@ -0,0 +1,194 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +#define NEWKIT_VERSION "1.01" +#define NEWKIT_VERSION_CB 0x0101 + +#if !defined(_INC_NO_STDC_HEADERS) && defined(__GNUC__) +#include +#endif + +#ifdef __has_feature +#if !__has_feature(cxx_nullptr) +#if !__has_nullptr +#error !!! You must at least have nullptr featured on your C++ compiler. !!! +#endif +#endif +#endif + +/// @brief The **Kernel** namespace where it's API resides. +namespace Kernel +{ + using voidPtr = void*; + using VoidPtr = void*; + using nullPtr = decltype(nullptr); + using NullPtr = decltype(nullptr); + + using Int = int; + using Int32 = int; + using UShort = unsigned short; + using UInt16 = unsigned short; + using Short = short; + using Int16 = short; + using UInt = unsigned int; + using UInt32 = unsigned int; + using Long = __INT64_TYPE__; + using Int64 = __INT64_TYPE__; + using ULong = __UINT64_TYPE__; + using UInt64 = __UINT64_TYPE__; + using Boolean = bool; + using Bool = bool; + using Char = char; + using UChar = unsigned char; + using UInt8 = unsigned char; + + using SSize = Int64; + using SSizeT = Int64; + using Size = __SIZE_TYPE__; + using SizeT = __SIZE_TYPE__; + using IntPtr = __INTPTR_TYPE__; + using UIntPtr = __UINTPTR_TYPE__; + using IntFast = __INT_FAST32_TYPE__; + using IntFast64 = __INT_FAST64_TYPE__; + using PtrDiff = __PTRDIFF_TYPE__; + + using SInt16 = Int16; + using SInt32 = Int32; + using SInt64 = Int64; + + typedef UIntPtr* Ptr64; + typedef UInt32* Ptr32; + + using Utf8Char = char8_t; + using Utf16Char = char16_t; + using WideChar = wchar_t; + using Utf32Char = char32_t; + + typedef UInt32 PhysicalAddressKind; + typedef UIntPtr VirtualAddressKind; + + using Void = void; + + using Lba = UInt64; + + enum class Endian : UInt8 + { + kEndianInvalid, + kEndianBig, + kEndianLittle, + kEndianMixed, + kCount + }; + + /// @brief Forward object. + /// @tparam Args the object type. + /// @param arg the object. + /// @return object's rvalue + template + inline Args&& forward(Args& arg) + { + return static_cast(arg); + } + + /// @brief Move object. + /// @tparam Args the object type. + /// @param arg the object. + /// @return object's rvalue + template + inline Args&& move(Args&& arg) + { + return static_cast(arg); + } + + /// @brief Encoding interface, used as a proxy to convert T to Char* + /// Used to cast A to B or B to A. + class IEncoderObject + { + public: + explicit IEncoderObject() = default; + virtual ~IEncoderObject() = default; + + IEncoderObject& operator=(const IEncoderObject&) = default; + IEncoderObject(const IEncoderObject&) = default; + + public: + /// @brief Convert type to bytes. + /// @tparam T the type. + /// @param type (a1) the data. + /// @return a1 as Char* + template + Char* AsBytes(T type) noexcept + { + return nullptr; + } + + /// @brief Convert T class to Y class. + /// @tparam T the class type of type. + /// @tparam Y the result class. + /// @param type the class to cast. + /// @return the class as Y. + template + Y As(T type) noexcept + { + if (type.IsSerializable()) + { + return reinterpret_cast(type); + } + + return type.template As(); + } + }; + + /// \brief Scheduler interface, represents a scheduler object. + /// @note This is used to schedule tasks, such as threads, drivers, user threads, etc. + class ISchedulerObject + { + public: + explicit ISchedulerObject() = default; + virtual ~ISchedulerObject() = default; + + ISchedulerObject& operator=(const ISchedulerObject&) = default; + ISchedulerObject(const ISchedulerObject&) = default; + + /// @brief Is this object only accepting user tasks? + virtual const Bool IsUser() + { + return false; + } + + /// @brief Is this object only accepting kernel tasks? + virtual const Bool IsKernel() + { + return false; + } + + /// @brief Is this object offloading to another CPU? + virtual const Bool HasMP() + { + return false; + } + }; +} // namespace Kernel + +#define cDeduceEndian(address, value) \ + (((reinterpret_cast(address)[0]) == (value)) \ + ? (Kernel::Endian::kEndianBig) \ + : (Kernel::Endian::kEndianLittle)) + +#define Yes true +#define No false + +#define VoidStar Kernel::VoidPtr + +#ifdef cInitObject +#undef cInitObject +#endif // ifdef cInitObject + +#define cInitObject(OBJ, TYPE, ...) TYPE OBJ = TYPE(__VA_ARGS__) diff --git a/dev/zka/NewKit/Defines.hxx b/dev/zka/NewKit/Defines.hxx deleted file mode 100644 index b9064280..00000000 --- a/dev/zka/NewKit/Defines.hxx +++ /dev/null @@ -1,194 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -#define NEWKIT_VERSION "1.01" -#define NEWKIT_VERSION_CB 0x0101 - -#if !defined(_INC_NO_STDC_HEADERS) && defined(__GNUC__) -#include -#endif - -#ifdef __has_feature -#if !__has_feature(cxx_nullptr) -#if !__has_nullptr -#error !!! You must at least have nullptr featured on your C++ compiler. !!! -#endif -#endif -#endif - -/// @brief The **Kernel** namespace where it's API resides. -namespace Kernel -{ - using voidPtr = void*; - using VoidPtr = void*; - using nullPtr = decltype(nullptr); - using NullPtr = decltype(nullptr); - - using Int = int; - using Int32 = int; - using UShort = unsigned short; - using UInt16 = unsigned short; - using Short = short; - using Int16 = short; - using UInt = unsigned int; - using UInt32 = unsigned int; - using Long = __INT64_TYPE__; - using Int64 = __INT64_TYPE__; - using ULong = __UINT64_TYPE__; - using UInt64 = __UINT64_TYPE__; - using Boolean = bool; - using Bool = bool; - using Char = char; - using UChar = unsigned char; - using UInt8 = unsigned char; - - using SSize = Int64; - using SSizeT = Int64; - using Size = __SIZE_TYPE__; - using SizeT = __SIZE_TYPE__; - using IntPtr = __INTPTR_TYPE__; - using UIntPtr = __UINTPTR_TYPE__; - using IntFast = __INT_FAST32_TYPE__; - using IntFast64 = __INT_FAST64_TYPE__; - using PtrDiff = __PTRDIFF_TYPE__; - - using SInt16 = Int16; - using SInt32 = Int32; - using SInt64 = Int64; - - typedef UIntPtr* Ptr64; - typedef UInt32* Ptr32; - - using Utf8Char = char8_t; - using Utf16Char = char16_t; - using WideChar = wchar_t; - using Utf32Char = char32_t; - - typedef UInt32 PhysicalAddressKind; - typedef UIntPtr VirtualAddressKind; - - using Void = void; - - using Lba = UInt64; - - enum class Endian : UInt8 - { - kEndianInvalid, - kEndianBig, - kEndianLittle, - kEndianMixed, - kCount - }; - - /// @brief Forward object. - /// @tparam Args the object type. - /// @param arg the object. - /// @return object's rvalue - template - inline Args&& forward(Args& arg) - { - return static_cast(arg); - } - - /// @brief Move object. - /// @tparam Args the object type. - /// @param arg the object. - /// @return object's rvalue - template - inline Args&& move(Args&& arg) - { - return static_cast(arg); - } - - /// @brief Encoding interface, used as a proxy to convert T to Char* - /// Used to cast A to B or B to A. - class IEncoderObject - { - public: - explicit IEncoderObject() = default; - virtual ~IEncoderObject() = default; - - IEncoderObject& operator=(const IEncoderObject&) = default; - IEncoderObject(const IEncoderObject&) = default; - - public: - /// @brief Convert type to bytes. - /// @tparam T the type. - /// @param type (a1) the data. - /// @return a1 as Char* - template - Char* AsBytes(T type) noexcept - { - return nullptr; - } - - /// @brief Convert T class to Y class. - /// @tparam T the class type of type. - /// @tparam Y the result class. - /// @param type the class to cast. - /// @return the class as Y. - template - Y As(T type) noexcept - { - if (type.IsSerializable()) - { - return reinterpret_cast(type); - } - - return type.template As(); - } - }; - - /// \brief Scheduler interface, represents a scheduler object. - /// @note This is used to schedule tasks, such as threads, drivers, user threads, etc. - class ISchedulerObject - { - public: - explicit ISchedulerObject() = default; - virtual ~ISchedulerObject() = default; - - ISchedulerObject& operator=(const ISchedulerObject&) = default; - ISchedulerObject(const ISchedulerObject&) = default; - - /// @brief Is this object only accepting user tasks? - virtual const Bool IsUser() - { - return false; - } - - /// @brief Is this object only accepting kernel tasks? - virtual const Bool IsKernel() - { - return false; - } - - /// @brief Is this object offloading to another CPU? - virtual const Bool HasMP() - { - return false; - } - }; -} // namespace Kernel - -#define cDeduceEndian(address, value) \ - (((reinterpret_cast(address)[0]) == (value)) \ - ? (Kernel::Endian::kEndianBig) \ - : (Kernel::Endian::kEndianLittle)) - -#define Yes true -#define No false - -#define VoidStar Kernel::VoidPtr - -#ifdef cInitObject -#undef cInitObject -#endif // ifdef cInitObject - -#define cInitObject(OBJ, TYPE, ...) TYPE OBJ = TYPE(__VA_ARGS__) diff --git a/dev/zka/NewKit/ErrorOr.h b/dev/zka/NewKit/ErrorOr.h new file mode 100644 index 00000000..eae5bcd1 --- /dev/null +++ b/dev/zka/NewKit/ErrorOr.h @@ -0,0 +1,72 @@ +/* + * ======================================================== + * + * ZKA + * Copyright ZKA Web Services Co., all rights reserved. + * + * ======================================================== + */ + +#pragma once + +#include +#include + +namespace Kernel +{ + using ErrorT = UInt; + + template + class ErrorOr final + { + public: + ErrorOr() = default; + ~ErrorOr() = default; + + public: + explicit ErrorOr(Int32 err) + : mId(err) + { + } + + explicit ErrorOr(nullPtr Null) + { + } + + explicit ErrorOr(T Class) + : mRef(Class) + { + } + + ErrorOr& operator=(const ErrorOr&) = default; + ErrorOr(const ErrorOr&) = default; + + ErrorOr& operator=(const Ref& refErr) + { + mRef = refErr; + return *this; + } + + Ref& Leak() + { + return mRef; + } + + Int32 Error() + { + return mId; + } + + operator bool() + { + return mRef; + } + + private: + Ref mRef; + Int32 mId{0}; + }; + + using ErrorOrAny = ErrorOr; + +} // namespace Kernel diff --git a/dev/zka/NewKit/ErrorOr.hxx b/dev/zka/NewKit/ErrorOr.hxx deleted file mode 100644 index c1346a08..00000000 --- a/dev/zka/NewKit/ErrorOr.hxx +++ /dev/null @@ -1,72 +0,0 @@ -/* - * ======================================================== - * - * ZKA - * Copyright ZKA Web Services Co., all rights reserved. - * - * ======================================================== - */ - -#pragma once - -#include -#include - -namespace Kernel -{ - using ErrorT = UInt; - - template - class ErrorOr final - { - public: - ErrorOr() = default; - ~ErrorOr() = default; - - public: - explicit ErrorOr(Int32 err) - : mId(err) - { - } - - explicit ErrorOr(nullPtr Null) - { - } - - explicit ErrorOr(T Class) - : mRef(Class) - { - } - - ErrorOr& operator=(const ErrorOr&) = default; - ErrorOr(const ErrorOr&) = default; - - ErrorOr& operator=(const Ref& refErr) - { - mRef = refErr; - return *this; - } - - Ref& Leak() - { - return mRef; - } - - Int32 Error() - { - return mId; - } - - operator bool() - { - return mRef; - } - - private: - Ref mRef; - Int32 mId{0}; - }; - - using ErrorOrAny = ErrorOr; - -} // namespace Kernel diff --git a/dev/zka/NewKit/Function.h b/dev/zka/NewKit/Function.h new file mode 100644 index 00000000..ae298db5 --- /dev/null +++ b/dev/zka/NewKit/Function.h @@ -0,0 +1,53 @@ +#ifndef _INC_FUNCTION_HPP__ +#define _INC_FUNCTION_HPP__ + +#include + +namespace Kernel +{ + template + class Function final + { + public: + Function() = default; + + public: + explicit Function(T (*Fn)(Args... args)) + : fFn(Fn) + { + } + + ~Function() = default; + + Function& operator=(const Function&) = default; + Function(const Function&) = default; + + template + T operator()(Args... args) + { + return fFn(args...); + } + + template + T Call(Args... args) + { + return fFn(args...); + } + + operator bool() + { + return fFn; + } + + bool operator!() + { + return !fFn; + } + + private: + T(*fFn) + (Args... args); + }; +} // namespace Kernel + +#endif // !_INC_FUNCTION_HPP__ diff --git a/dev/zka/NewKit/Function.hxx b/dev/zka/NewKit/Function.hxx deleted file mode 100644 index e54ff456..00000000 --- a/dev/zka/NewKit/Function.hxx +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef _INC_FUNCTION_HPP__ -#define _INC_FUNCTION_HPP__ - -#include - -namespace Kernel -{ - template - class Function final - { - public: - Function() = default; - - public: - explicit Function(T (*Fn)(Args... args)) - : fFn(Fn) - { - } - - ~Function() = default; - - Function& operator=(const Function&) = default; - Function(const Function&) = default; - - template - T operator()(Args... args) - { - return fFn(args...); - } - - template - T Call(Args... args) - { - return fFn(args...); - } - - operator bool() - { - return fFn; - } - - bool operator!() - { - return !fFn; - } - - private: - T(*fFn) - (Args... args); - }; -} // namespace Kernel - -#endif // !_INC_FUNCTION_HPP__ diff --git a/dev/zka/NewKit/Json.h b/dev/zka/NewKit/Json.h new file mode 100644 index 00000000..68210e00 --- /dev/null +++ b/dev/zka/NewKit/Json.h @@ -0,0 +1,151 @@ + +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +// last-rev: 30/01/24 + +#include +#include +#include +#include +#include + +#define cMaxJsonPath 4096 +#define cJSONLen 32 +#define cJSONNull "null" + +namespace Kernel +{ + /// @brief Json class + class JSON final + { + public: + explicit JSON() + { + auto len = cJSONLen; + StringView key = StringView(len); + key += cJSONNull; + + this->AsKey() = key; + this->AsValue() = key; + } + + explicit JSON(SizeT lhsLen, SizeT rhsLen) + : fKey(lhsLen), fValue(rhsLen) + { + } + + ~JSON() = default; + + ZKA_COPY_DEFAULT(JSON); + + const Bool& IsUndefined() + { + return fUndefined; + } + + private: + Bool fUndefined; // is this instance undefined? + StringView fKey; + StringView fValue; + + public: + /// @brief returns the key of the json + /// @return the key as string view. + StringView& AsKey() + { + return fKey; + } + + /// @brief returns the value of the json. + /// @return the key as string view. + StringView& AsValue() + { + return fValue; + } + + static JSON kNull; + }; + + /// @brief Json stream reader helper. + struct JsonStreamReader final + { + STATIC JSON In(const Char* full_array) + { + auto start_val = '{'; + auto end_val = '}'; + Boolean probe_value = false; + + if (full_array[0] != start_val) + { + if (full_array[0] != '[') + return JSON::kNull; + + start_val = '['; + end_val = ']'; + + probe_value = true; + } + + SizeT len = rt_string_len(full_array); + + SizeT key_len = 0; + SizeT value_len = 0; + + JSON type(cMaxJsonPath, cMaxJsonPath); + + for (SizeT i = 1; i < len; ++i) + { + if (full_array[i] == '\r' || + full_array[i] == '\n') + continue; + + if (probe_value) + { + if (full_array[i] == end_val || + full_array[i] == ',') + { + probe_value = false; + + ++value_len; + } + else + { + type.AsValue().Data()[value_len] = full_array[i]; + + ++value_len; + } + } + else + { + if (start_val == '[') + continue; + + if (full_array[i] == ':') + { + probe_value = true; + type.AsKey().Data()[key_len] = 0; + ++key_len; + } + else + { + type.AsKey().Data()[key_len] = full_array[i]; + + ++key_len; + } + } + } + + type.AsValue().Data()[value_len] = 0; + + return type; + } + }; + + using JsonStream = Stream; +} // namespace Kernel diff --git a/dev/zka/NewKit/Json.hxx b/dev/zka/NewKit/Json.hxx deleted file mode 100644 index bdba9391..00000000 --- a/dev/zka/NewKit/Json.hxx +++ /dev/null @@ -1,151 +0,0 @@ - -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -// last-rev: 30/01/24 - -#include -#include -#include -#include -#include - -#define cMaxJsonPath 4096 -#define cJSONLen 32 -#define cJSONNull "null" - -namespace Kernel -{ - /// @brief Json class - class JSON final - { - public: - explicit JSON() - { - auto len = cJSONLen; - StringView key = StringView(len); - key += cJSONNull; - - this->AsKey() = key; - this->AsValue() = key; - } - - explicit JSON(SizeT lhsLen, SizeT rhsLen) - : fKey(lhsLen), fValue(rhsLen) - { - } - - ~JSON() = default; - - ZKA_COPY_DEFAULT(JSON); - - const Bool& IsUndefined() - { - return fUndefined; - } - - private: - Bool fUndefined; // is this instance undefined? - StringView fKey; - StringView fValue; - - public: - /// @brief returns the key of the json - /// @return the key as string view. - StringView& AsKey() - { - return fKey; - } - - /// @brief returns the value of the json. - /// @return the key as string view. - StringView& AsValue() - { - return fValue; - } - - static JSON kNull; - }; - - /// @brief Json stream reader helper. - struct JsonStreamReader final - { - STATIC JSON In(const Char* full_array) - { - auto start_val = '{'; - auto end_val = '}'; - Boolean probe_value = false; - - if (full_array[0] != start_val) - { - if (full_array[0] != '[') - return JSON::kNull; - - start_val = '['; - end_val = ']'; - - probe_value = true; - } - - SizeT len = rt_string_len(full_array); - - SizeT key_len = 0; - SizeT value_len = 0; - - JSON type(cMaxJsonPath, cMaxJsonPath); - - for (SizeT i = 1; i < len; ++i) - { - if (full_array[i] == '\r' || - full_array[i] == '\n') - continue; - - if (probe_value) - { - if (full_array[i] == end_val || - full_array[i] == ',') - { - probe_value = false; - - ++value_len; - } - else - { - type.AsValue().Data()[value_len] = full_array[i]; - - ++value_len; - } - } - else - { - if (start_val == '[') - continue; - - if (full_array[i] == ':') - { - probe_value = true; - type.AsKey().Data()[key_len] = 0; - ++key_len; - } - else - { - type.AsKey().Data()[key_len] = full_array[i]; - - ++key_len; - } - } - } - - type.AsValue().Data()[value_len] = 0; - - return type; - } - }; - - using JsonStream = Stream; -} // namespace Kernel diff --git a/dev/zka/NewKit/Macros.h b/dev/zka/NewKit/Macros.h new file mode 100644 index 00000000..2ab04efe --- /dev/null +++ b/dev/zka/NewKit/Macros.h @@ -0,0 +1,133 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#ifndef KIB +#define KIB(X) (Kernel::UInt64)((X) / 1024) +#endif + +#ifndef kib_cast +#define kib_cast(X) (Kernel::UInt64)((X)*1024) +#endif + +#ifndef MIB +#define MIB(X) (Kernel::UInt64)((Kernel::UInt64)KIB(X) / 1024) +#endif + +#ifndef mib_cast +#define mib_cast(X) (Kernel::UInt64)((Kernel::UInt64)kib_cast(X) * 1024) +#endif + +#ifndef GIB +#define GIB(X) (Kernel::UInt64)((Kernel::UInt64)MIB(X) / 1024) +#endif + +#ifndef gib_cast +#define gib_cast(X) (Kernel::UInt64)((Kernel::UInt64)mib_cast(X) * 1024) +#endif + +#ifndef TIB +#define TIB(X) (Kernel::UInt64)((Kernel::UInt64)GIB(X) / 1024) +#endif + +#ifndef tib_cast +#define tib_cast(X) ((Kernel::UInt64)gib_cast(X) * 1024) +#endif + +#ifndef ARRAY_SIZE +#define ARRAY_SIZE(a) \ + (((sizeof(a) / sizeof(*(a))) / \ + (static_cast(!(sizeof(a) % sizeof(*(a))))))) +#endif + +#ifndef ALIGN +#define ALIGN(X) __attribute__((aligned(X))) +#endif // #ifndef ALIGN + +#ifndef ATTRIBUTE +#define ATTRIBUTE(X) __attribute__((X)) +#endif // #ifndef ATTRIBUTE + +#ifndef __ZKA_VER__ +#define __ZKA_VER__ (2024) +#endif // !__ZKA_VER__ + +#ifndef EXTERN_C +#define EXTERN_C extern "C" +#endif + +#ifndef MAKE_ENUM +#define MAKE_ENUM(NAME) \ + enum NAME \ + { +#endif + +#ifndef END_ENUM +#define END_ENUM() \ + } \ + ; +#endif + +#ifndef MAKE_STRING_ENUM +#define MAKE_STRING_ENUM(NAME) \ + namespace NAME \ + { +#endif + +#ifndef ENUM_STRING +#define ENUM_STRING(NAME, VAL) inline constexpr const char* e##NAME = VAL +#endif + +#ifndef END_STRING_ENUM +#define END_STRING_ENUM() } +#endif + +#ifndef cAlloca +#define cAlloca(Sz) __builtin_alloca(Sz) +#endif // #ifndef cAlloca + +#ifndef CANT_REACH +#define CANT_REACH() __builtin_unreachable() +#endif + +#define kInvalidAddress 0xFBFBFBFBFBFBFBFB +#define kBadAddress 0x0000000000000000 +#define kMaxAddr 0xFFFFFFFFFFFFFFFF +#define kPathLen 0x100 + +#define PACKED ATTRIBUTE(packed) +#define NO_EXEC ATTRIBUTE(noexec) + +#define EXTERN extern +#define STATIC static + +#define CONST const + +#define STRINGIFY(X) #X +#define ZKA_UNUSED(X) ((Kernel::Void)X) + +#ifndef RGB +#define RGB(R, G, B) (Kernel::UInt32)(R | G << 0x8 | B << 0x10) +#endif // !RGB + +/// @brief The system page file. +#define kPageSys "\\System\\syspage.sys" + +/// @brief The main system driver. +#define kStartupSys "\\Boot\\startup.sys" + +/// @brief The main font file. +#define kUrbanistTTF "\\Fonts\\urbanist.ttf" + +/// @brief License file +#define kEulaTxt "\\Misc\\EULA.txt" + +/// @brief The main kernel file. +#define kStartupWav "\\Rsrc\\startup.wav" + +/// @brief The main system loader. +#define kUserName "ZKA AUTHORITY\\KERNEL" diff --git a/dev/zka/NewKit/Macros.hxx b/dev/zka/NewKit/Macros.hxx deleted file mode 100644 index 2ab04efe..00000000 --- a/dev/zka/NewKit/Macros.hxx +++ /dev/null @@ -1,133 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#ifndef KIB -#define KIB(X) (Kernel::UInt64)((X) / 1024) -#endif - -#ifndef kib_cast -#define kib_cast(X) (Kernel::UInt64)((X)*1024) -#endif - -#ifndef MIB -#define MIB(X) (Kernel::UInt64)((Kernel::UInt64)KIB(X) / 1024) -#endif - -#ifndef mib_cast -#define mib_cast(X) (Kernel::UInt64)((Kernel::UInt64)kib_cast(X) * 1024) -#endif - -#ifndef GIB -#define GIB(X) (Kernel::UInt64)((Kernel::UInt64)MIB(X) / 1024) -#endif - -#ifndef gib_cast -#define gib_cast(X) (Kernel::UInt64)((Kernel::UInt64)mib_cast(X) * 1024) -#endif - -#ifndef TIB -#define TIB(X) (Kernel::UInt64)((Kernel::UInt64)GIB(X) / 1024) -#endif - -#ifndef tib_cast -#define tib_cast(X) ((Kernel::UInt64)gib_cast(X) * 1024) -#endif - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(a) \ - (((sizeof(a) / sizeof(*(a))) / \ - (static_cast(!(sizeof(a) % sizeof(*(a))))))) -#endif - -#ifndef ALIGN -#define ALIGN(X) __attribute__((aligned(X))) -#endif // #ifndef ALIGN - -#ifndef ATTRIBUTE -#define ATTRIBUTE(X) __attribute__((X)) -#endif // #ifndef ATTRIBUTE - -#ifndef __ZKA_VER__ -#define __ZKA_VER__ (2024) -#endif // !__ZKA_VER__ - -#ifndef EXTERN_C -#define EXTERN_C extern "C" -#endif - -#ifndef MAKE_ENUM -#define MAKE_ENUM(NAME) \ - enum NAME \ - { -#endif - -#ifndef END_ENUM -#define END_ENUM() \ - } \ - ; -#endif - -#ifndef MAKE_STRING_ENUM -#define MAKE_STRING_ENUM(NAME) \ - namespace NAME \ - { -#endif - -#ifndef ENUM_STRING -#define ENUM_STRING(NAME, VAL) inline constexpr const char* e##NAME = VAL -#endif - -#ifndef END_STRING_ENUM -#define END_STRING_ENUM() } -#endif - -#ifndef cAlloca -#define cAlloca(Sz) __builtin_alloca(Sz) -#endif // #ifndef cAlloca - -#ifndef CANT_REACH -#define CANT_REACH() __builtin_unreachable() -#endif - -#define kInvalidAddress 0xFBFBFBFBFBFBFBFB -#define kBadAddress 0x0000000000000000 -#define kMaxAddr 0xFFFFFFFFFFFFFFFF -#define kPathLen 0x100 - -#define PACKED ATTRIBUTE(packed) -#define NO_EXEC ATTRIBUTE(noexec) - -#define EXTERN extern -#define STATIC static - -#define CONST const - -#define STRINGIFY(X) #X -#define ZKA_UNUSED(X) ((Kernel::Void)X) - -#ifndef RGB -#define RGB(R, G, B) (Kernel::UInt32)(R | G << 0x8 | B << 0x10) -#endif // !RGB - -/// @brief The system page file. -#define kPageSys "\\System\\syspage.sys" - -/// @brief The main system driver. -#define kStartupSys "\\Boot\\startup.sys" - -/// @brief The main font file. -#define kUrbanistTTF "\\Fonts\\urbanist.ttf" - -/// @brief License file -#define kEulaTxt "\\Misc\\EULA.txt" - -/// @brief The main kernel file. -#define kStartupWav "\\Rsrc\\startup.wav" - -/// @brief The main system loader. -#define kUserName "ZKA AUTHORITY\\KERNEL" diff --git a/dev/zka/NewKit/MutableArray.h b/dev/zka/NewKit/MutableArray.h new file mode 100644 index 00000000..61b547e2 --- /dev/null +++ b/dev/zka/NewKit/MutableArray.h @@ -0,0 +1,239 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ +#pragma once + +#include +#include +#include + +#define TRY_FIND_NODE(NAME, NODE) \ + auto* NAME = NODE; \ + while (NAME) \ + { \ + if (NAME->fIndex == Index) \ + return NAME->fVal; \ + NAME = NAME->fNext; \ + } + +#define TRY_FIND_NODE2(NAME, NODE) \ + auto* NAME = NODE; \ + while (NAME) \ + { \ + if (NAME->fIndex == Index) \ + return Ref{NAME->fVal}; \ + NAME = NAME->fNext; \ + } + +#define TRY_REMOVE_NODE(NODE) \ + if (NODE && NODE->fIndex == Index) \ + { \ + NODE->fUsed = false; \ + NODE->fIndex = 0; \ + \ + return true; \ + } + +// FIXME: this is a shitty algorithm, which is consumer hungry. +// Remove and occurences of that, and remove that class. +namespace Kernel +{ + template + class MutableArray; + + template + class NullableMutableArray; + + template + class MutableLinkedList + { + public: + T fVal; + SizeT fIndex{0}; + Boolean fUsed{false}; + + MutableLinkedList* fPrev{nullptr}; + MutableLinkedList* fNext{nullptr}; + }; + + template + class NullableMutableArray + { + public: + // explicit this. + explicit NullableMutableArray() + : fFirstNode(new MutableLinkedList()) + { + } + + /* + * We free all the nodes allocated by the array + * and store the next one inside "NextIt" + */ + + virtual ~NullableMutableArray() + { + auto* It = fFirstNode; + MutableLinkedList* NextIt = nullptr; + + while (It) + { + NextIt = It->fNext; + delete It; + + It = NextIt; + } + } + + NullableMutableArray& operator=(const NullableMutableArray&) = default; + NullableMutableArray(const NullableMutableArray&) = default; + + operator bool() + { + return Count() > 1; + } + + public: + T operator[](const SizeT& Index) const + { + TRY_FIND_NODE(first, fFirstNode); + TRY_FIND_NODE(last, fLastNode); + + return _PlaceHolderValue; + } + + SizeT Count() const + { + return fNodeCount; + } + + public: + Boolean Remove(const SizeT& Index) + { + TRY_REMOVE_NODE(fFirstNode); + TRY_REMOVE_NODE(fLastNode); + + return false; + } + + Boolean Add(const T val) + { + auto* iterationNode = fFirstNode; + MUST_PASS(iterationNode); + + while (iterationNode) + { + if (!iterationNode->fUsed) + { + iterationNode->fVal = val; + iterationNode->fIndex = 0; + + iterationNode->fUsed = true; + + ++fNodeCount; + + return true; + } + + iterationNode = iterationNode->fNext; + } + + return false; + } + + private: + /* Avoid useless lookups */ + MutableLinkedList* fLastNode{nullptr}; + MutableLinkedList* fFirstNode{nullptr}; + + /* Number of nodes inside of this dynamic array. */ + Kernel::SizeT fNodeCount{0}; + + private: + // don't remove that + friend MutableArray; + }; + + template + class MutableArray : public NullableMutableArray + { + public: + // explicit this. + explicit MutableArray() = default; + virtual ~MutableArray() = default; + + ZKA_COPY_DEFAULT(MutableArray) + + public: + Boolean Add(const T val) + { + auto* iterationNode = fFirstNode; + + if (!iterationNode) + { + fFirstNode = new MutableLinkedList(); + iterationNode = fFirstNode; + } + + MUST_PASS(iterationNode); + + while (iterationNode) + { + if (!iterationNode->fUsed) + { + iterationNode->fVal = val; + iterationNode->fIndex = 0; + + iterationNode->fUsed = true; + + ++fNodeCount; + + return true; + } + + iterationNode = iterationNode->fNext; + } + + return false; + } + + public: + Ref operator[](const SizeT& Index) const + { + TRY_FIND_NODE2(first, fFirstNode); + TRY_FIND_NODE2(last, fLastNode); + + return {}; + } + + SizeT Count() const + { + return fNodeCount; + } + + bool Contains(T& value) noexcept + { + MutableLinkedList* first = fFirstNode; + + while (first) + { + if (first->fVal == value && first->fUsed) + return true; + + first = first->fNext; + } + + return false; + } + + private: + /* Avoid useless lookups */ + MutableLinkedList* fLastNode{nullptr}; + MutableLinkedList* fFirstNode{nullptr}; + + /* Number of nodes inside of this dynamic array. */ + Kernel::SizeT fNodeCount{0}; + }; +} // namespace Kernel diff --git a/dev/zka/NewKit/MutableArray.hxx b/dev/zka/NewKit/MutableArray.hxx deleted file mode 100644 index 1fb8dc55..00000000 --- a/dev/zka/NewKit/MutableArray.hxx +++ /dev/null @@ -1,239 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ -#pragma once - -#include -#include -#include - -#define TRY_FIND_NODE(NAME, NODE) \ - auto* NAME = NODE; \ - while (NAME) \ - { \ - if (NAME->fIndex == Index) \ - return NAME->fVal; \ - NAME = NAME->fNext; \ - } - -#define TRY_FIND_NODE2(NAME, NODE) \ - auto* NAME = NODE; \ - while (NAME) \ - { \ - if (NAME->fIndex == Index) \ - return Ref{NAME->fVal}; \ - NAME = NAME->fNext; \ - } - -#define TRY_REMOVE_NODE(NODE) \ - if (NODE && NODE->fIndex == Index) \ - { \ - NODE->fUsed = false; \ - NODE->fIndex = 0; \ - \ - return true; \ - } - -// FIXME: this is a shitty algorithm, which is consumer hungry. -// Remove and occurences of that, and remove that class. -namespace Kernel -{ - template - class MutableArray; - - template - class NullableMutableArray; - - template - class MutableLinkedList - { - public: - T fVal; - SizeT fIndex{0}; - Boolean fUsed{false}; - - MutableLinkedList* fPrev{nullptr}; - MutableLinkedList* fNext{nullptr}; - }; - - template - class NullableMutableArray - { - public: - // explicit this. - explicit NullableMutableArray() - : fFirstNode(new MutableLinkedList()) - { - } - - /* - * We free all the nodes allocated by the array - * and store the next one inside "NextIt" - */ - - virtual ~NullableMutableArray() - { - auto* It = fFirstNode; - MutableLinkedList* NextIt = nullptr; - - while (It) - { - NextIt = It->fNext; - delete It; - - It = NextIt; - } - } - - NullableMutableArray& operator=(const NullableMutableArray&) = default; - NullableMutableArray(const NullableMutableArray&) = default; - - operator bool() - { - return Count() > 1; - } - - public: - T operator[](const SizeT& Index) const - { - TRY_FIND_NODE(first, fFirstNode); - TRY_FIND_NODE(last, fLastNode); - - return _PlaceHolderValue; - } - - SizeT Count() const - { - return fNodeCount; - } - - public: - Boolean Remove(const SizeT& Index) - { - TRY_REMOVE_NODE(fFirstNode); - TRY_REMOVE_NODE(fLastNode); - - return false; - } - - Boolean Add(const T val) - { - auto* iterationNode = fFirstNode; - MUST_PASS(iterationNode); - - while (iterationNode) - { - if (!iterationNode->fUsed) - { - iterationNode->fVal = val; - iterationNode->fIndex = 0; - - iterationNode->fUsed = true; - - ++fNodeCount; - - return true; - } - - iterationNode = iterationNode->fNext; - } - - return false; - } - - private: - /* Avoid useless lookups */ - MutableLinkedList* fLastNode{nullptr}; - MutableLinkedList* fFirstNode{nullptr}; - - /* Number of nodes inside of this dynamic array. */ - Kernel::SizeT fNodeCount{0}; - - private: - // don't remove that - friend MutableArray; - }; - - template - class MutableArray : public NullableMutableArray - { - public: - // explicit this. - explicit MutableArray() = default; - virtual ~MutableArray() = default; - - ZKA_COPY_DEFAULT(MutableArray) - - public: - Boolean Add(const T val) - { - auto* iterationNode = fFirstNode; - - if (!iterationNode) - { - fFirstNode = new MutableLinkedList(); - iterationNode = fFirstNode; - } - - MUST_PASS(iterationNode); - - while (iterationNode) - { - if (!iterationNode->fUsed) - { - iterationNode->fVal = val; - iterationNode->fIndex = 0; - - iterationNode->fUsed = true; - - ++fNodeCount; - - return true; - } - - iterationNode = iterationNode->fNext; - } - - return false; - } - - public: - Ref operator[](const SizeT& Index) const - { - TRY_FIND_NODE2(first, fFirstNode); - TRY_FIND_NODE2(last, fLastNode); - - return {}; - } - - SizeT Count() const - { - return fNodeCount; - } - - bool Contains(T& value) noexcept - { - MutableLinkedList* first = fFirstNode; - - while (first) - { - if (first->fVal == value && first->fUsed) - return true; - - first = first->fNext; - } - - return false; - } - - private: - /* Avoid useless lookups */ - MutableLinkedList* fLastNode{nullptr}; - MutableLinkedList* fFirstNode{nullptr}; - - /* Number of nodes inside of this dynamic array. */ - Kernel::SizeT fNodeCount{0}; - }; -} // namespace Kernel diff --git a/dev/zka/NewKit/New.h b/dev/zka/NewKit/New.h new file mode 100644 index 00000000..33bf3b24 --- /dev/null +++ b/dev/zka/NewKit/New.h @@ -0,0 +1,18 @@ + +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ +#pragma once + +#include + +typedef __SIZE_TYPE__ size_t; // gcc will complain about that + +void* operator new(size_t ptr); +void* operator new[](size_t ptr); + +void operator delete(void* ptr); +void operator delete(void* ptr, unsigned long); +void operator delete[](void* ptr); diff --git a/dev/zka/NewKit/New.hxx b/dev/zka/NewKit/New.hxx deleted file mode 100644 index e479e85f..00000000 --- a/dev/zka/NewKit/New.hxx +++ /dev/null @@ -1,18 +0,0 @@ - -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ -#pragma once - -#include - -typedef __SIZE_TYPE__ size_t; // gcc will complain about that - -void* operator new(size_t ptr); -void* operator new[](size_t ptr); - -void operator delete(void* ptr); -void operator delete(void* ptr, unsigned long); -void operator delete[](void* ptr); diff --git a/dev/zka/NewKit/NewKit.h b/dev/zka/NewKit/NewKit.h new file mode 100644 index 00000000..f5bab516 --- /dev/null +++ b/dev/zka/NewKit/NewKit.h @@ -0,0 +1,20 @@ + +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/dev/zka/NewKit/NewKit.hxx b/dev/zka/NewKit/NewKit.hxx deleted file mode 100644 index 6609a9a2..00000000 --- a/dev/zka/NewKit/NewKit.hxx +++ /dev/null @@ -1,20 +0,0 @@ - -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include diff --git a/dev/zka/NewKit/OwnPtr.h b/dev/zka/NewKit/OwnPtr.h new file mode 100644 index 00000000..b8f78ac1 --- /dev/null +++ b/dev/zka/NewKit/OwnPtr.h @@ -0,0 +1,94 @@ + +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +namespace Kernel +{ + template + class OwnPtr; + + template + class NonNullRefPtr; + + template + class OwnPtr final + { + public: + OwnPtr() + { + } + ~OwnPtr() + { + this->Delete(); + } + + OwnPtr& operator=(const OwnPtr&) = default; + OwnPtr(const OwnPtr&) = default; + + public: + template + bool New(Args&&... arg) + { + if (fCls) + { + return false; + } + + fCls = new T(arg...); + return fCls; + } + + void Delete() + { + if (fCls) + delete fCls; + + fCls = nullptr; + } + + T* operator->() const + { + return fCls; + }; + T* Raw() + { + return fCls; + } + + Ref AsRef() + { + return Ref(fCls); + } + + operator bool() + { + return fCls; + } + bool operator!() + { + return !fCls; + } + + private: + T* fCls; + }; + + template + OwnPtr make_ptr(Args... args) + { + OwnPtr ret; + ret.template New(forward(args)...); + MUST_PASS(ret); + + return ret; + } +} // namespace Kernel diff --git a/dev/zka/NewKit/OwnPtr.hxx b/dev/zka/NewKit/OwnPtr.hxx deleted file mode 100644 index b16c3cf5..00000000 --- a/dev/zka/NewKit/OwnPtr.hxx +++ /dev/null @@ -1,94 +0,0 @@ - -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -namespace Kernel -{ - template - class OwnPtr; - - template - class NonNullRefPtr; - - template - class OwnPtr final - { - public: - OwnPtr() - { - } - ~OwnPtr() - { - this->Delete(); - } - - OwnPtr& operator=(const OwnPtr&) = default; - OwnPtr(const OwnPtr&) = default; - - public: - template - bool New(Args&&... arg) - { - if (fCls) - { - return false; - } - - fCls = new T(arg...); - return fCls; - } - - void Delete() - { - if (fCls) - delete fCls; - - fCls = nullptr; - } - - T* operator->() const - { - return fCls; - }; - T* Raw() - { - return fCls; - } - - Ref AsRef() - { - return Ref(fCls); - } - - operator bool() - { - return fCls; - } - bool operator!() - { - return !fCls; - } - - private: - T* fCls; - }; - - template - OwnPtr make_ptr(Args... args) - { - OwnPtr ret; - ret.template New(forward(args)...); - MUST_PASS(ret); - - return ret; - } -} // namespace Kernel diff --git a/dev/zka/NewKit/PageMgr.h b/dev/zka/NewKit/PageMgr.h new file mode 100644 index 00000000..702139f6 --- /dev/null +++ b/dev/zka/NewKit/PageMgr.h @@ -0,0 +1,81 @@ +// a way to create and find our pages. +// I'm thinking about a separate way of getting a paged area. + +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include + +namespace Kernel +{ + class PageMgr; + + class PTEWrapper final + { + public: + explicit PTEWrapper(Boolean Rw = false, Boolean User = false, Boolean ExecDisable = false, UIntPtr Address = 0); + + ~PTEWrapper(); + + PTEWrapper& operator=(const PTEWrapper&) = default; + PTEWrapper(const PTEWrapper&) = default; + + public: + const UIntPtr VirtualAddress(); + + void NoExecute(const bool enable = false); + const Bool& NoExecute(); + + operator bool() + { + return fVirtAddr; + } + + bool Reclaim(); + bool Shareable(); + bool Present(); + bool Access(); + + private: + Boolean fRw; + Boolean fUser; + Boolean fExecDisable; + UIntPtr fVirtAddr; + Boolean fCache; + Boolean fShareable; + Boolean fWt; + Boolean fPresent; + Boolean fAccessed; + + private: + friend class PageMgr; + friend class Pmm; + }; + + struct PageMgr final + { + public: + PageMgr() = default; + ~PageMgr() = default; + + PageMgr& operator=(const PageMgr&) = default; + PageMgr(const PageMgr&) = default; + + public: + PTEWrapper Request(Boolean Rw, Boolean User, Boolean ExecDisable, SizeT Sz); + bool Free(Ref& wrapper); + + private: + void FlushTLB(); + + private: + friend PTEWrapper; + friend class Pmm; + }; +} // namespace Kernel diff --git a/dev/zka/NewKit/PageMgr.hxx b/dev/zka/NewKit/PageMgr.hxx deleted file mode 100644 index fcbd1955..00000000 --- a/dev/zka/NewKit/PageMgr.hxx +++ /dev/null @@ -1,81 +0,0 @@ -// a way to create and find our pages. -// I'm thinking about a separate way of getting a paged area. - -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include - -namespace Kernel -{ - class PageMgr; - - class PTEWrapper final - { - public: - explicit PTEWrapper(Boolean Rw = false, Boolean User = false, Boolean ExecDisable = false, UIntPtr Address = 0); - - ~PTEWrapper(); - - PTEWrapper& operator=(const PTEWrapper&) = default; - PTEWrapper(const PTEWrapper&) = default; - - public: - const UIntPtr VirtualAddress(); - - void NoExecute(const bool enable = false); - const Bool& NoExecute(); - - operator bool() - { - return fVirtAddr; - } - - bool Reclaim(); - bool Shareable(); - bool Present(); - bool Access(); - - private: - Boolean fRw; - Boolean fUser; - Boolean fExecDisable; - UIntPtr fVirtAddr; - Boolean fCache; - Boolean fShareable; - Boolean fWt; - Boolean fPresent; - Boolean fAccessed; - - private: - friend class PageMgr; - friend class Pmm; - }; - - struct PageMgr final - { - public: - PageMgr() = default; - ~PageMgr() = default; - - PageMgr& operator=(const PageMgr&) = default; - PageMgr(const PageMgr&) = default; - - public: - PTEWrapper Request(Boolean Rw, Boolean User, Boolean ExecDisable, SizeT Sz); - bool Free(Ref& wrapper); - - private: - void FlushTLB(); - - private: - friend PTEWrapper; - friend class Pmm; - }; -} // namespace Kernel diff --git a/dev/zka/NewKit/Pair.h b/dev/zka/NewKit/Pair.h new file mode 100644 index 00000000..aabc66ff --- /dev/null +++ b/dev/zka/NewKit/Pair.h @@ -0,0 +1,14 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +namespace Kernel +{ + +} // namespace Kernel diff --git a/dev/zka/NewKit/Pair.hxx b/dev/zka/NewKit/Pair.hxx deleted file mode 100644 index cb0bfbaa..00000000 --- a/dev/zka/NewKit/Pair.hxx +++ /dev/null @@ -1,14 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -namespace Kernel -{ - -} // namespace Kernel diff --git a/dev/zka/NewKit/Pmm.h b/dev/zka/NewKit/Pmm.h new file mode 100644 index 00000000..da347b53 --- /dev/null +++ b/dev/zka/NewKit/Pmm.h @@ -0,0 +1,44 @@ + +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include + +namespace Kernel +{ + class Pmm; + class PTEWrapper; + + class Pmm final + { + public: + explicit Pmm(); + ~Pmm(); + + Pmm& operator=(const Pmm&) = delete; + Pmm(const Pmm&) = default; + + Ref RequestPage(Boolean user = false, Boolean readWrite = false); + Boolean FreePage(Ref refPage); + + Boolean ToggleRw(Ref refPage, Boolean enable = true); + Boolean TogglePresent(Ref refPage, Boolean enable = true); + Boolean ToggleUser(Ref refPage, Boolean enable = true); + Boolean ToggleShare(Ref refPage, Boolean enable = true); + + /// @brief Get the page manager of this. + Ref& Leak() + { + return fPageMgr; + } + + private: + Ref fPageMgr; + }; +} // namespace Kernel diff --git a/dev/zka/NewKit/Pmm.hxx b/dev/zka/NewKit/Pmm.hxx deleted file mode 100644 index f7c4c885..00000000 --- a/dev/zka/NewKit/Pmm.hxx +++ /dev/null @@ -1,44 +0,0 @@ - -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include - -namespace Kernel -{ - class Pmm; - class PTEWrapper; - - class Pmm final - { - public: - explicit Pmm(); - ~Pmm(); - - Pmm& operator=(const Pmm&) = delete; - Pmm(const Pmm&) = default; - - Ref RequestPage(Boolean user = false, Boolean readWrite = false); - Boolean FreePage(Ref refPage); - - Boolean ToggleRw(Ref refPage, Boolean enable = true); - Boolean TogglePresent(Ref refPage, Boolean enable = true); - Boolean ToggleUser(Ref refPage, Boolean enable = true); - Boolean ToggleShare(Ref refPage, Boolean enable = true); - - /// @brief Get the page manager of this. - Ref& Leak() - { - return fPageMgr; - } - - private: - Ref fPageMgr; - }; -} // namespace Kernel diff --git a/dev/zka/NewKit/Ref.h b/dev/zka/NewKit/Ref.h new file mode 100644 index 00000000..cc6821c0 --- /dev/null +++ b/dev/zka/NewKit/Ref.h @@ -0,0 +1,103 @@ + +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifndef _NEWKIT_REF_HPP_ +#define _NEWKIT_REF_HPP_ + +#include +#include +#include + +namespace Kernel +{ + template + class Ref final + { + public: + Ref() = default; + + ~Ref() + { + if (mm_is_valid_heap(fClass)) + delete fClass; + } + + public: + Ref(T cls) + : fClass(&cls) + { + } + + Ref& operator=(T ref) + { + if (!fClass) + return *this; + + fClass = &ref; + return *this; + } + + public: + T operator->() const + { + MUST_PASS(*fClass); + return *fClass; + } + + T& Leak() noexcept + { + return *fClass; + } + + T& TryLeak() const noexcept + { + MUST_PASS(*fClass); + return *fClass; + } + + T operator*() + { + return *fClass; + } + + operator bool() noexcept + { + return fClass; + } + + private: + T* fClass{nullptr}; + }; + + template + class NonNullRef final + { + public: + NonNullRef() = delete; + NonNullRef(nullPtr) = delete; + + NonNullRef(T* ref) + : fRef(ref) + { + MUST_PASS(ref); + } + + Ref& operator->() + { + MUST_PASS(fRef); + return fRef; + } + + NonNullRef& operator=(const NonNullRef& ref) = delete; + NonNullRef(const NonNullRef& ref) = default; + + private: + Ref fRef{nullptr}; + }; +} // namespace Kernel + +#endif // ifndef _NEWKIT_REF_HPP_ diff --git a/dev/zka/NewKit/Ref.hxx b/dev/zka/NewKit/Ref.hxx deleted file mode 100644 index cf672886..00000000 --- a/dev/zka/NewKit/Ref.hxx +++ /dev/null @@ -1,103 +0,0 @@ - -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifndef _NEWKIT_REF_HPP_ -#define _NEWKIT_REF_HPP_ - -#include -#include -#include - -namespace Kernel -{ - template - class Ref final - { - public: - Ref() = default; - - ~Ref() - { - if (mm_is_valid_heap(fClass)) - delete fClass; - } - - public: - Ref(T cls) - : fClass(&cls) - { - } - - Ref& operator=(T ref) - { - if (!fClass) - return *this; - - fClass = &ref; - return *this; - } - - public: - T operator->() const - { - MUST_PASS(*fClass); - return *fClass; - } - - T& Leak() noexcept - { - return *fClass; - } - - T& TryLeak() const noexcept - { - MUST_PASS(*fClass); - return *fClass; - } - - T operator*() - { - return *fClass; - } - - operator bool() noexcept - { - return fClass; - } - - private: - T* fClass{nullptr}; - }; - - template - class NonNullRef final - { - public: - NonNullRef() = delete; - NonNullRef(nullPtr) = delete; - - NonNullRef(T* ref) - : fRef(ref) - { - MUST_PASS(ref); - } - - Ref& operator->() - { - MUST_PASS(fRef); - return fRef; - } - - NonNullRef& operator=(const NonNullRef& ref) = delete; - NonNullRef(const NonNullRef& ref) = default; - - private: - Ref fRef{nullptr}; - }; -} // namespace Kernel - -#endif // ifndef _NEWKIT_REF_HPP_ diff --git a/dev/zka/NewKit/Stop.h b/dev/zka/NewKit/Stop.h new file mode 100644 index 00000000..4f9e5795 --- /dev/null +++ b/dev/zka/NewKit/Stop.h @@ -0,0 +1,71 @@ + +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +namespace Kernel +{ + void ke_runtime_check(bool bExpression, const Char* file, const Char* line); +} + +#define MUST_PASS_COMPILER(EXPR, MSG) static_assert(EXPR, MSG) + +#define __MUST_PASS(EXPR, FILE, LINE) \ + Kernel::ke_runtime_check(EXPR, FILE, STRINGIFY(LINE)) + +#ifdef __DEBUG__ +#define MUST_PASS(EXPR) __MUST_PASS((EXPR), __FILE__, __LINE__) +#define assert(EXPR) MUST_PASS(EXPR, RUNTIME_CHECK_EXPRESSION) +#else +#define MUST_PASS(EXPR) (Kernel::Void)(EXPR) +#define assert(EXPR) (Kernel::Void)(EXPR) +#endif + +enum RUNTIME_CHECK +{ + RUNTIME_CHECK_FAILED = -1, + RUNTIME_CHECK_POINTER = 0, + RUNTIME_CHECK_EXPRESSION, + RUNTIME_CHECK_FILE, + RUNTIME_CHECK_IPC, + RUNTIME_CHECK_TLS, + RUNTIME_CHECK_HANDSHAKE, + RUNTIME_CHECK_ACPI, + RUNTIME_CHECK_INVALID_PRIVILEGE, + RUNTIME_CHECK_PROCESS, + RUNTIME_CHECK_BAD_BEHAVIOR, + RUNTIME_CHECK_BOOTSTRAP, + RUNTIME_CHECK_UNEXCPECTED, + RUNTIME_CHECK_FILESYSTEM, + RUNTIME_CHECK_VIRTUAL_OUT_OF_MEM, + RUNTIME_CHECK_PAGE, + RUNTIME_CHECK_COUNT, +}; + +namespace Kernel +{ + /// @brief Dumping factory class. + class RecoveryFactory final + { + public: + STATIC Void Recover() noexcept; + }; + + void ke_stop(const Int& id); +} // namespace Kernel + +#ifdef TRY +#undef TRY +#endif + +#define TRY(FN) \ + if (!FN()) \ + { \ + MUST_PASS(false); \ + } diff --git a/dev/zka/NewKit/Stop.hxx b/dev/zka/NewKit/Stop.hxx deleted file mode 100644 index e3188743..00000000 --- a/dev/zka/NewKit/Stop.hxx +++ /dev/null @@ -1,71 +0,0 @@ - -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -namespace Kernel -{ - void ke_runtime_check(bool bExpression, const Char* file, const Char* line); -} - -#define MUST_PASS_COMPILER(EXPR, MSG) static_assert(EXPR, MSG) - -#define __MUST_PASS(EXPR, FILE, LINE) \ - Kernel::ke_runtime_check(EXPR, FILE, STRINGIFY(LINE)) - -#ifdef __DEBUG__ -#define MUST_PASS(EXPR) __MUST_PASS((EXPR), __FILE__, __LINE__) -#define assert(EXPR) MUST_PASS(EXPR, RUNTIME_CHECK_EXPRESSION) -#else -#define MUST_PASS(EXPR) (Kernel::Void)(EXPR) -#define assert(EXPR) (Kernel::Void)(EXPR) -#endif - -enum RUNTIME_CHECK -{ - RUNTIME_CHECK_FAILED = -1, - RUNTIME_CHECK_POINTER = 0, - RUNTIME_CHECK_EXPRESSION, - RUNTIME_CHECK_FILE, - RUNTIME_CHECK_IPC, - RUNTIME_CHECK_TLS, - RUNTIME_CHECK_HANDSHAKE, - RUNTIME_CHECK_ACPI, - RUNTIME_CHECK_INVALID_PRIVILEGE, - RUNTIME_CHECK_PROCESS, - RUNTIME_CHECK_BAD_BEHAVIOR, - RUNTIME_CHECK_BOOTSTRAP, - RUNTIME_CHECK_UNEXCPECTED, - RUNTIME_CHECK_FILESYSTEM, - RUNTIME_CHECK_VIRTUAL_OUT_OF_MEM, - RUNTIME_CHECK_PAGE, - RUNTIME_CHECK_COUNT, -}; - -namespace Kernel -{ - /// @brief Dumping factory class. - class RecoveryFactory final - { - public: - STATIC Void Recover() noexcept; - }; - - void ke_stop(const Int& id); -} // namespace Kernel - -#ifdef TRY -#undef TRY -#endif - -#define TRY(FN) \ - if (!FN()) \ - { \ - MUST_PASS(false); \ - } diff --git a/dev/zka/NewKit/Stream.h b/dev/zka/NewKit/Stream.h new file mode 100644 index 00000000..ad0edf28 --- /dev/null +++ b/dev/zka/NewKit/Stream.h @@ -0,0 +1,58 @@ + +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include + +namespace Kernel +{ + template + class Stream final + { + public: + explicit Stream(Ref ref) + : fStream(ref) + { + } + + ~Stream() = default; + + Stream& operator=(const Stream&) = default; + Stream(const Stream&) = default; + + template + friend Stream& operator>>(Stream& Ks, Ref& Buf) + { + Ks.fKind = Ks.fStream->In(Buf); + return *Ks; + } + + template + friend Stream& operator<<(Stream& Ks, Ref& Buf) + { + Ks.fKind = Buf; + Ks.fStream->Out(Buf.Leak()); + return *Ks; + } + + Ref& AsStreamTrait() + { + return fStream; + } + + Ref& AsType() + { + return fKind; + } + + private: + Ref fStream; + Ref fKind; + }; +} // namespace Kernel diff --git a/dev/zka/NewKit/Stream.hxx b/dev/zka/NewKit/Stream.hxx deleted file mode 100644 index eb2f07f5..00000000 --- a/dev/zka/NewKit/Stream.hxx +++ /dev/null @@ -1,58 +0,0 @@ - -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include - -namespace Kernel -{ - template - class Stream final - { - public: - explicit Stream(Ref ref) - : fStream(ref) - { - } - - ~Stream() = default; - - Stream& operator=(const Stream&) = default; - Stream(const Stream&) = default; - - template - friend Stream& operator>>(Stream& Ks, Ref& Buf) - { - Ks.fKind = Ks.fStream->In(Buf); - return *Ks; - } - - template - friend Stream& operator<<(Stream& Ks, Ref& Buf) - { - Ks.fKind = Buf; - Ks.fStream->Out(Buf.Leak()); - return *Ks; - } - - Ref& AsStreamTrait() - { - return fStream; - } - - Ref& AsType() - { - return fKind; - } - - private: - Ref fStream; - Ref fKind; - }; -} // namespace Kernel diff --git a/dev/zka/NewKit/String.h b/dev/zka/NewKit/String.h new file mode 100644 index 00000000..8e77b61b --- /dev/null +++ b/dev/zka/NewKit/String.h @@ -0,0 +1,91 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include +#include +#include + +#define cMinimumStringSize 8196 + +namespace Kernel +{ + /// @brief StringView class, using dynamic or static memory. + class StringView final + { + public: + explicit StringView() + { + fDataSz = cMinimumStringSize; + + fData = new Char[fDataSz]; + MUST_PASS(fData); + + rt_set_memory(fData, 0, fDataSz); + } + + explicit StringView(const SizeT& Sz) + : fDataSz(Sz) + { + MUST_PASS(Sz > 1); + + fData = new Char[Sz]; + MUST_PASS(fData); + + rt_set_memory(fData, 0, Sz); + } + + ~StringView() + { + if (fData) + delete[] fData; + } + + ZKA_COPY_DEFAULT(StringView); + + Char* Data(); + const Char* CData() const; + Size Length() const; + + bool operator==(const Char* rhs) const; + bool operator!=(const Char* rhs) const; + + bool operator==(const StringView& rhs) const; + bool operator!=(const StringView& rhs) const; + + StringView& operator+=(const Char* rhs); + StringView& operator+=(const StringView& rhs); + + operator bool() + { + return fData; + } + + bool operator!() + { + return fData; + } + + private: + Char* fData{nullptr}; + Size fDataSz{0}; + Size fCur{0}; + + friend class StringBuilder; + }; + + struct StringBuilder final + { + static ErrorOr Construct(const Char* data); + static const Char* FromBool(const Char* fmt, bool n); + static const Char* Format(const Char* fmt, const Char* from); + static bool Equals(const Char* lhs, const Char* rhs); + static bool Equals(const WideChar* lhs, const WideChar* rhs); + }; +} // namespace Kernel diff --git a/dev/zka/NewKit/String.hxx b/dev/zka/NewKit/String.hxx deleted file mode 100644 index dc963e9f..00000000 --- a/dev/zka/NewKit/String.hxx +++ /dev/null @@ -1,91 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include -#include -#include - -#define cMinimumStringSize 8196 - -namespace Kernel -{ - /// @brief StringView class, using dynamic or static memory. - class StringView final - { - public: - explicit StringView() - { - fDataSz = cMinimumStringSize; - - fData = new Char[fDataSz]; - MUST_PASS(fData); - - rt_set_memory(fData, 0, fDataSz); - } - - explicit StringView(const SizeT& Sz) - : fDataSz(Sz) - { - MUST_PASS(Sz > 1); - - fData = new Char[Sz]; - MUST_PASS(fData); - - rt_set_memory(fData, 0, Sz); - } - - ~StringView() - { - if (fData) - delete[] fData; - } - - ZKA_COPY_DEFAULT(StringView); - - Char* Data(); - const Char* CData() const; - Size Length() const; - - bool operator==(const Char* rhs) const; - bool operator!=(const Char* rhs) const; - - bool operator==(const StringView& rhs) const; - bool operator!=(const StringView& rhs) const; - - StringView& operator+=(const Char* rhs); - StringView& operator+=(const StringView& rhs); - - operator bool() - { - return fData; - } - - bool operator!() - { - return fData; - } - - private: - Char* fData{nullptr}; - Size fDataSz{0}; - Size fCur{0}; - - friend class StringBuilder; - }; - - struct StringBuilder final - { - static ErrorOr Construct(const Char* data); - static const Char* FromBool(const Char* fmt, bool n); - static const Char* Format(const Char* fmt, const Char* from); - static bool Equals(const Char* lhs, const Char* rhs); - static bool Equals(const WideChar* lhs, const WideChar* rhs); - }; -} // namespace Kernel diff --git a/dev/zka/NewKit/Utils.h b/dev/zka/NewKit/Utils.h new file mode 100644 index 00000000..a689cf51 --- /dev/null +++ b/dev/zka/NewKit/Utils.h @@ -0,0 +1,29 @@ + +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +namespace Kernel +{ + Int rt_copy_memory(const voidPtr src, voidPtr dst, Size len); + Int rt_move_memory(const voidPtr src, voidPtr dst, Size len); + voidPtr rt_set_memory(voidPtr dst, UInt32 val, Size len); + void rt_zero_memory(voidPtr pointer, Size len); + Int rt_string_cmp(const Char* src, const Char* cmp, Size len); + const Char* alloc_string(const Char* text); + Size rt_string_len(const Char* str); + Size rt_string_len(const Char* str, SizeT _len); + Boolean rt_to_string(Char* buf, Int limit, Int base); + Boolean is_newln(Char chr); + Boolean is_space(Char chr); + Int rt_to_uppercase(Int c); + Int rt_to_lower(Int c); + voidPtr rt_string_in_string(const Char* in, const Char* needle); + char* rt_string_has_char(Char* str, const Char chr); +} // namespace Kernel diff --git a/dev/zka/NewKit/Utils.hxx b/dev/zka/NewKit/Utils.hxx deleted file mode 100644 index 9f2f93a6..00000000 --- a/dev/zka/NewKit/Utils.hxx +++ /dev/null @@ -1,29 +0,0 @@ - -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -namespace Kernel -{ - Int rt_copy_memory(const voidPtr src, voidPtr dst, Size len); - Int rt_move_memory(const voidPtr src, voidPtr dst, Size len); - voidPtr rt_set_memory(voidPtr dst, UInt32 val, Size len); - void rt_zero_memory(voidPtr pointer, Size len); - Int rt_string_cmp(const Char* src, const Char* cmp, Size len); - const Char* alloc_string(const Char* text); - Size rt_string_len(const Char* str); - Size rt_string_len(const Char* str, SizeT _len); - Boolean rt_to_string(Char* buf, Int limit, Int base); - Boolean is_newln(Char chr); - Boolean is_space(Char chr); - Int rt_to_uppercase(Int c); - Int rt_to_lower(Int c); - voidPtr rt_string_in_string(const Char* in, const Char* needle); - char* rt_string_has_char(Char* str, const Char chr); -} // namespace Kernel diff --git a/dev/zka/NewKit/Variant.h b/dev/zka/NewKit/Variant.h new file mode 100644 index 00000000..92eee500 --- /dev/null +++ b/dev/zka/NewKit/Variant.h @@ -0,0 +1,70 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +namespace Kernel +{ + class Variant final + { + public: + enum class VariantKind + { + kString, + kBlob, + kNull, + kJson, + kXML, + }; + + public: + explicit Variant() = delete; + + public: + ZKA_COPY_DEFAULT(Variant); + + ~Variant() = default; + + public: + explicit Variant(StringView* stringView) + : fPtr((VoidPtr)stringView), fKind(VariantKind::kString) + { + } + + explicit Variant(JSON* json) + : fPtr((VoidPtr)json), fKind(VariantKind::kJson) + { + } + + explicit Variant(nullPtr) + : fPtr(nullptr), fKind(VariantKind::kNull) + { + } + + explicit Variant(VoidPtr ptr) + : fPtr(ptr), fKind(VariantKind::kBlob) + { + } + + public: + const Char* ToString(); + VoidPtr Leak(); + + template + T* As() + { + return reinterpret_cast(fPtr); + } + + private: + voidPtr fPtr{nullptr}; + VariantKind fKind{VariantKind::kNull}; + }; +} // namespace Kernel diff --git a/dev/zka/NewKit/Variant.hxx b/dev/zka/NewKit/Variant.hxx deleted file mode 100644 index 7d178b4c..00000000 --- a/dev/zka/NewKit/Variant.hxx +++ /dev/null @@ -1,70 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -namespace Kernel -{ - class Variant final - { - public: - enum class VariantKind - { - kString, - kBlob, - kNull, - kJson, - kXML, - }; - - public: - explicit Variant() = delete; - - public: - ZKA_COPY_DEFAULT(Variant); - - ~Variant() = default; - - public: - explicit Variant(StringView* stringView) - : fPtr((VoidPtr)stringView), fKind(VariantKind::kString) - { - } - - explicit Variant(JSON* json) - : fPtr((VoidPtr)json), fKind(VariantKind::kJson) - { - } - - explicit Variant(nullPtr) - : fPtr(nullptr), fKind(VariantKind::kNull) - { - } - - explicit Variant(VoidPtr ptr) - : fPtr(ptr), fKind(VariantKind::kBlob) - { - } - - public: - const Char* ToString(); - VoidPtr Leak(); - - template - T* As() - { - return reinterpret_cast(fPtr); - } - - private: - voidPtr fPtr{nullptr}; - VariantKind fKind{VariantKind::kNull}; - }; -} // namespace Kernel diff --git a/dev/zka/StorageKit/AHCI.h b/dev/zka/StorageKit/AHCI.h new file mode 100644 index 00000000..e89f5654 --- /dev/null +++ b/dev/zka/StorageKit/AHCI.h @@ -0,0 +1,33 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +namespace Kernel +{ + class AHCIDeviceInterface : public DeviceInterface + { + public: + explicit AHCIDeviceInterface(void (*Out)(MountpointInterface* outpacket), + void (*In)(MountpointInterface* inpacket), + void (*Cleanup)(void)); + + virtual ~AHCIDeviceInterface(); + + public: + AHCIDeviceInterface& operator=(const AHCIDeviceInterface&) = default; + AHCIDeviceInterface(const AHCIDeviceInterface&) = default; + + const Char* Name() const override; + + private: + void (*fCleanup)(void) = {nullptr}; + }; +} // namespace Kernel diff --git a/dev/zka/StorageKit/AHCI.hxx b/dev/zka/StorageKit/AHCI.hxx deleted file mode 100644 index 67948033..00000000 --- a/dev/zka/StorageKit/AHCI.hxx +++ /dev/null @@ -1,33 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -namespace Kernel -{ - class AHCIDeviceInterface : public DeviceInterface - { - public: - explicit AHCIDeviceInterface(void (*Out)(MountpointInterface* outpacket), - void (*In)(MountpointInterface* inpacket), - void (*Cleanup)(void)); - - virtual ~AHCIDeviceInterface(); - - public: - AHCIDeviceInterface& operator=(const AHCIDeviceInterface&) = default; - AHCIDeviceInterface(const AHCIDeviceInterface&) = default; - - const Char* Name() const override; - - private: - void (*fCleanup)(void) = {nullptr}; - }; -} // namespace Kernel diff --git a/dev/zka/StorageKit/ATA.h b/dev/zka/StorageKit/ATA.h new file mode 100644 index 00000000..d4efd15c --- /dev/null +++ b/dev/zka/StorageKit/ATA.h @@ -0,0 +1,39 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include +#include + +namespace Kernel +{ + /// @brief ATA device interface type. + class ATADeviceInterface : public DeviceInterface + { + public: + explicit ATADeviceInterface(void (*Out)(MountpointInterface* outpacket), + void (*In)(MountpointInterface* inpacket), + void (*Cleanup)(void)); + + virtual ~ATADeviceInterface(); + + public: + ATADeviceInterface& operator<<(MountpointInterface* Data) override; + ATADeviceInterface& operator>>(MountpointInterface* Data) override; + + public: + ATADeviceInterface& operator=(const ATADeviceInterface&) = default; + ATADeviceInterface(const ATADeviceInterface&) = default; + + const Char* Name() const override; + + private: + void (*fCleanup)(void) = {nullptr}; + }; +} // namespace Kernel diff --git a/dev/zka/StorageKit/ATA.hxx b/dev/zka/StorageKit/ATA.hxx deleted file mode 100644 index 11a0d546..00000000 --- a/dev/zka/StorageKit/ATA.hxx +++ /dev/null @@ -1,39 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include -#include - -namespace Kernel -{ - /// @brief ATA device interface type. - class ATADeviceInterface : public DeviceInterface - { - public: - explicit ATADeviceInterface(void (*Out)(MountpointInterface* outpacket), - void (*In)(MountpointInterface* inpacket), - void (*Cleanup)(void)); - - virtual ~ATADeviceInterface(); - - public: - ATADeviceInterface& operator<<(MountpointInterface* Data) override; - ATADeviceInterface& operator>>(MountpointInterface* Data) override; - - public: - ATADeviceInterface& operator=(const ATADeviceInterface&) = default; - ATADeviceInterface(const ATADeviceInterface&) = default; - - const Char* Name() const override; - - private: - void (*fCleanup)(void) = {nullptr}; - }; -} // namespace Kernel diff --git a/dev/zka/StorageKit/NVME.h b/dev/zka/StorageKit/NVME.h new file mode 100644 index 00000000..04b3df7f --- /dev/null +++ b/dev/zka/StorageKit/NVME.h @@ -0,0 +1,36 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +namespace Kernel +{ + class NVMEDeviceInterface final : public DeviceInterface + { + public: + explicit NVMEDeviceInterface(void (*Out)(MountpointInterface* outpacket), + void (*In)(MountpointInterface* inpacket), + void (*Cleanup)(void)); + + ~NVMEDeviceInterface() override; + + public: + NVMEDeviceInterface& operator=(const NVMEDeviceInterface&) = default; + NVMEDeviceInterface(const NVMEDeviceInterface&) = default; + + const Char* Name() const override; + + public: + OwnPtr operator()(UInt32 dmaLow, UInt32 dmaHigh, SizeT sz); + + private: + void (*fCleanup)(void) = {nullptr}; + }; +} // namespace Kernel diff --git a/dev/zka/StorageKit/NVME.hxx b/dev/zka/StorageKit/NVME.hxx deleted file mode 100644 index e909b783..00000000 --- a/dev/zka/StorageKit/NVME.hxx +++ /dev/null @@ -1,36 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -namespace Kernel -{ - class NVMEDeviceInterface final : public DeviceInterface - { - public: - explicit NVMEDeviceInterface(void (*Out)(MountpointInterface* outpacket), - void (*In)(MountpointInterface* inpacket), - void (*Cleanup)(void)); - - ~NVMEDeviceInterface() override; - - public: - NVMEDeviceInterface& operator=(const NVMEDeviceInterface&) = default; - NVMEDeviceInterface(const NVMEDeviceInterface&) = default; - - const Char* Name() const override; - - public: - OwnPtr operator()(UInt32 dmaLow, UInt32 dmaHigh, SizeT sz); - - private: - void (*fCleanup)(void) = {nullptr}; - }; -} // namespace Kernel diff --git a/dev/zka/StorageKit/PRDT.h b/dev/zka/StorageKit/PRDT.h new file mode 100644 index 00000000..993782bf --- /dev/null +++ b/dev/zka/StorageKit/PRDT.h @@ -0,0 +1,36 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include +#include +#include + +#define kPrdtTransferSize (sizeof(Kernel::UShort)) + +namespace Kernel +{ + /// @brief Tranfer information about PRD. + enum kPRDTTransfer + { + kPRDTTransferInProgress, + kPRDTTransferIsDone, + kPRDTTransferCount, + }; + + /// @brief Physical Region Descriptor Table. + struct PRDT + { + UInt32 fPhysAddress; + UInt32 fSectorCount; + UInt8 fEndBit; + }; + + void construct_prdt(Ref& prd); + + EXTERN_C Int32 kPRDTTransferStatus; +} // namespace Kernel diff --git a/dev/zka/StorageKit/PRDT.hxx b/dev/zka/StorageKit/PRDT.hxx deleted file mode 100644 index df9f3cc1..00000000 --- a/dev/zka/StorageKit/PRDT.hxx +++ /dev/null @@ -1,36 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include -#include -#include - -#define kPrdtTransferSize (sizeof(Kernel::UShort)) - -namespace Kernel -{ - /// @brief Tranfer information about PRD. - enum kPRDTTransfer - { - kPRDTTransferInProgress, - kPRDTTransferIsDone, - kPRDTTransferCount, - }; - - /// @brief Physical Region Descriptor Table. - struct PRDT - { - UInt32 fPhysAddress; - UInt32 fSectorCount; - UInt8 fEndBit; - }; - - void construct_prdt(Ref& prd); - - EXTERN_C Int32 kPRDTTransferStatus; -} // namespace Kernel diff --git a/dev/zka/StorageKit/SCSI.h b/dev/zka/StorageKit/SCSI.h new file mode 100644 index 00000000..7c2f7c48 --- /dev/null +++ b/dev/zka/StorageKit/SCSI.h @@ -0,0 +1,11 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#include + +extern const scsi_packet_type<12> kCDRomPacketTemplate; diff --git a/dev/zka/StorageKit/SCSI.hxx b/dev/zka/StorageKit/SCSI.hxx deleted file mode 100644 index 1d8470ec..00000000 --- a/dev/zka/StorageKit/SCSI.hxx +++ /dev/null @@ -1,11 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#include - -extern const scsi_packet_type<12> kCDRomPacketTemplate; diff --git a/dev/zka/StorageKit/Storage.h b/dev/zka/StorageKit/Storage.h new file mode 100644 index 00000000..5d388c7e --- /dev/null +++ b/dev/zka/StorageKit/Storage.h @@ -0,0 +1,22 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#pragma once + +#define kDriveSectorSizeHDD (512U) +#define kDriveSectorSizeSSD (512U) +#define kDriveSectorSizeOptical (2048) + +namespace Kernel +{ + template + class DeviceInterface; + + class NVMEDeviceInterface; + class AHCIDeviceInterface; + class ATADeviceInterface; + class SCSIDeviceInterface; +} // namespace Kernel diff --git a/dev/zka/StorageKit/Storage.hxx b/dev/zka/StorageKit/Storage.hxx deleted file mode 100644 index 5d388c7e..00000000 --- a/dev/zka/StorageKit/Storage.hxx +++ /dev/null @@ -1,22 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#pragma once - -#define kDriveSectorSizeHDD (512U) -#define kDriveSectorSizeSSD (512U) -#define kDriveSectorSizeOptical (2048) - -namespace Kernel -{ - template - class DeviceInterface; - - class NVMEDeviceInterface; - class AHCIDeviceInterface; - class ATADeviceInterface; - class SCSIDeviceInterface; -} // namespace Kernel diff --git a/dev/zka/amd64-efi.make b/dev/zka/amd64-efi.make index 18c493fc..8d9d1311 100644 --- a/dev/zka/amd64-efi.make +++ b/dev/zka/amd64-efi.make @@ -52,10 +52,10 @@ WINDRES=x86_64-w64-mingw32-windres .PHONY: newos-amd64-epm newos-amd64-epm: clean $(WINDRES) KernelRsrc.rsrc -O coff -o KernelRsrc.obj - $(CC) $(CCFLAGS) $(DISK_DRV) $(DEBUG_MACRO) $(wildcard src/*.cxx) \ - $(wildcard src/FS/*.cxx) $(wildcard HALKit/AMD64/Storage/*.cxx) \ - $(wildcard HALKit/AMD64/PCI/*.cxx) $(wildcard src/Network/*.cxx) $(wildcard src/Storage/*.cxx) \ - $(wildcard HALKit/AMD64/*.cxx) $(wildcard HALKit/AMD64/*.cpp) \ + $(CC) $(CCFLAGS) $(DISK_DRV) $(DEBUG_MACRO) $(wildcard src/*.cc) \ + $(wildcard src/FS/*.cc) $(wildcard HALKit/AMD64/Storage/*.cc) \ + $(wildcard HALKit/AMD64/PCI/*.cc) $(wildcard src/Network/*.cc) $(wildcard src/Storage/*.cc) \ + $(wildcard HALKit/AMD64/*.cc) $(wildcard HALKit/AMD64/*.cpp) \ $(wildcard HALKit/AMD64/*.s) $(ASM) $(ASMFLAGS) HALKit/AMD64/HalInterruptAPI.asm $(ASM) $(ASMFLAGS) HALKit/AMD64/HalMPContextSwitch.asm diff --git a/dev/zka/arm64-efi.make b/dev/zka/arm64-efi.make index b164341d..1ddd2f8b 100644 --- a/dev/zka/arm64-efi.make +++ b/dev/zka/arm64-efi.make @@ -34,11 +34,11 @@ MOVEALL=./MoveAll.ARM64.sh .PHONY: newos-arm64-epm newos-arm64-epm: clean - $(CC) $(CCFLAGS) $(DISKDRIVER) $(DEBUG) $(wildcard src/*.cxx) \ - $(wildcard src/FS/*.cxx) $(wildcard HALKit/ARM64/Storage/*.cxx) \ - $(wildcard HALKit/ARM64/PCI/*.cxx) $(wildcard src/Network/*.cxx) $(wildcard src/Storage/*.cxx) \ - $(wildcard HALKit/ARM64/*.cxx) $(wildcard HALKit/ARM64/*.cpp) \ - $(wildcard HALKit/ARM64/*.s) $(wildcard HALKit/ARM64/APM/*.cxx) + $(CC) $(CCFLAGS) $(DISKDRIVER) $(DEBUG) $(wildcard src/*.cc) \ + $(wildcard src/FS/*.cc) $(wildcard HALKit/ARM64/Storage/*.cc) \ + $(wildcard HALKit/ARM64/PCI/*.cc) $(wildcard src/Network/*.cc) $(wildcard src/Storage/*.cc) \ + $(wildcard HALKit/ARM64/*.cc) $(wildcard HALKit/ARM64/*.cpp) \ + $(wildcard HALKit/ARM64/*.s) $(wildcard HALKit/ARM64/APM/*.cc) $(MOVEALL) diff --git a/dev/zka/src/ACPIFactoryInterface.cc b/dev/zka/src/ACPIFactoryInterface.cc new file mode 100644 index 00000000..c7d2914f --- /dev/null +++ b/dev/zka/src/ACPIFactoryInterface.cc @@ -0,0 +1,95 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include +#include + +namespace Kernel +{ + /// @brief Finds a descriptor table inside ACPI XSDT. + ErrorOr ACPIFactoryInterface::Find(const Char* signature) + { + MUST_PASS(fRsdp); + + if (!signature) + return ErrorOr{-1}; + + if (*signature == 0) + return ErrorOr{-1}; + + RSDP* rsp_ptr = reinterpret_cast(this->fRsdp); + + if (rsp_ptr->Revision <= 1) + return ErrorOr{-1}; + + RSDT* xsdt = reinterpret_cast(rsp_ptr->RsdtAddress); + + Int64 num = (xsdt->Length - sizeof(SDT)) / sizeof(UInt32); + + /*** + crucial to avoid - overflows. + */ + if (num < 1) + { + /// stop here, we should have entries... + ke_stop(RUNTIME_CHECK_ACPI); + return ErrorOr{-1}; + } + + this->fEntries = num; + + kcout << "ACPI: Number of entries: " << number(this->fEntries) << endl; + kcout << "ACPI: Revision: " << number(xsdt->Revision) << endl; + kcout << "ACPI: Signature: " << xsdt->Signature << endl; + kcout << "ACPI: Address of XSDT: " << hex_number((UIntPtr)xsdt) << endl; + + const short cAcpiSignatureLength = 4; + + for (Size index = 0; index < this->fEntries; ++index) + { + SDT* sdt = reinterpret_cast(xsdt->AddressArr[index]); + + kcout << "ACPI: Checksum: " << number(sdt->Checksum) << endl; + kcout << "ACPI: Revision: " << number(sdt->Revision) << endl; + + for (short signature_index = 0; signature_index < cAcpiSignatureLength; ++signature_index) + { + if (sdt->Signature[signature_index] != signature[signature_index]) + break; + + if (signature_index == (cAcpiSignatureLength - 1)) + { + kcout << "ACPI: Found the SDT" << endl; + return ErrorOr(reinterpret_cast(xsdt->AddressArr[index])); + } + } + } + + return ErrorOr{-1}; + } + + /*** + @brief check SDT header + @param checksum the header to checksum + @param len the length of it. +*/ + bool ACPIFactoryInterface::Checksum(const Char* checksum, SSizeT len) + { + if (len == 0) + return -1; + + char chr = 0; + + for (int index = 0; index < len; ++index) + { + chr += checksum[index]; + } + + return chr == 0; + } +} // namespace Kernel diff --git a/dev/zka/src/ACPIFactoryInterface.cxx b/dev/zka/src/ACPIFactoryInterface.cxx deleted file mode 100644 index 4a04d7b9..00000000 --- a/dev/zka/src/ACPIFactoryInterface.cxx +++ /dev/null @@ -1,95 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include -#include - -namespace Kernel -{ - /// @brief Finds a descriptor table inside ACPI XSDT. - ErrorOr ACPIFactoryInterface::Find(const Char* signature) - { - MUST_PASS(fRsdp); - - if (!signature) - return ErrorOr{-1}; - - if (*signature == 0) - return ErrorOr{-1}; - - RSDP* rsp_ptr = reinterpret_cast(this->fRsdp); - - if (rsp_ptr->Revision <= 1) - return ErrorOr{-1}; - - RSDT* xsdt = reinterpret_cast(rsp_ptr->RsdtAddress); - - Int64 num = (xsdt->Length - sizeof(SDT)) / sizeof(UInt32); - - /*** - crucial to avoid - overflows. - */ - if (num < 1) - { - /// stop here, we should have entries... - ke_stop(RUNTIME_CHECK_ACPI); - return ErrorOr{-1}; - } - - this->fEntries = num; - - kcout << "ACPI: Number of entries: " << number(this->fEntries) << endl; - kcout << "ACPI: Revision: " << number(xsdt->Revision) << endl; - kcout << "ACPI: Signature: " << xsdt->Signature << endl; - kcout << "ACPI: Address of XSDT: " << hex_number((UIntPtr)xsdt) << endl; - - const short cAcpiSignatureLength = 4; - - for (Size index = 0; index < this->fEntries; ++index) - { - SDT* sdt = reinterpret_cast(xsdt->AddressArr[index]); - - kcout << "ACPI: Checksum: " << number(sdt->Checksum) << endl; - kcout << "ACPI: Revision: " << number(sdt->Revision) << endl; - - for (short signature_index = 0; signature_index < cAcpiSignatureLength; ++signature_index) - { - if (sdt->Signature[signature_index] != signature[signature_index]) - break; - - if (signature_index == (cAcpiSignatureLength - 1)) - { - kcout << "ACPI: Found the SDT" << endl; - return ErrorOr(reinterpret_cast(xsdt->AddressArr[index])); - } - } - } - - return ErrorOr{-1}; - } - - /*** - @brief check SDT header - @param checksum the header to checksum - @param len the length of it. -*/ - bool ACPIFactoryInterface::Checksum(const Char* checksum, SSizeT len) - { - if (len == 0) - return -1; - - char chr = 0; - - for (int index = 0; index < len; ++index) - { - chr += checksum[index]; - } - - return chr == 0; - } -} // namespace Kernel diff --git a/dev/zka/src/Array.cc b/dev/zka/src/Array.cc new file mode 100644 index 00000000..0bf62d59 --- /dev/null +++ b/dev/zka/src/Array.cc @@ -0,0 +1,7 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include diff --git a/dev/zka/src/Array.cxx b/dev/zka/src/Array.cxx deleted file mode 100644 index 437cb11b..00000000 --- a/dev/zka/src/Array.cxx +++ /dev/null @@ -1,7 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include diff --git a/dev/zka/src/ArrayList.cc b/dev/zka/src/ArrayList.cc new file mode 100644 index 00000000..6de794be --- /dev/null +++ b/dev/zka/src/ArrayList.cc @@ -0,0 +1,7 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include diff --git a/dev/zka/src/ArrayList.cxx b/dev/zka/src/ArrayList.cxx deleted file mode 100644 index 27fae68c..00000000 --- a/dev/zka/src/ArrayList.cxx +++ /dev/null @@ -1,7 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include diff --git a/dev/zka/src/Atom.cc b/dev/zka/src/Atom.cc new file mode 100644 index 00000000..20114b7c --- /dev/null +++ b/dev/zka/src/Atom.cc @@ -0,0 +1,10 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +// @file Atom.cpp +// @brief Atomic primitives diff --git a/dev/zka/src/Atom.cxx b/dev/zka/src/Atom.cxx deleted file mode 100644 index bfacfe83..00000000 --- a/dev/zka/src/Atom.cxx +++ /dev/null @@ -1,10 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -// @file Atom.cpp -// @brief Atomic primitives diff --git a/dev/zka/src/BitMapMgr.cc b/dev/zka/src/BitMapMgr.cc new file mode 100644 index 00000000..e97c9bfa --- /dev/null +++ b/dev/zka/src/BitMapMgr.cc @@ -0,0 +1,203 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +#define kBitMapMagic (0x10210) + +#ifdef __ZKA_AMD64__ +#include +#elif defined(__ZKA_ARM64__) +#include +#endif + +#include +#include + +#define cBitMapMagIdx (0) +#define cBitMapSizeIdx (1) +#define cBitMapUsedIdx (2) + +namespace Kernel +{ + namespace HAL + { + namespace Detail + { + /// \brief Proxy Interface to allocate a bitmap. + class IBitMapAllocator final + { + public: + explicit IBitMapAllocator() = default; + ~IBitMapAllocator() = default; + + ZKA_COPY_DELETE(IBitMapAllocator); + + auto IsBitMap(VoidPtr page_ptr) -> Bool + { + if (!page_ptr) + return No; + + UIntPtr* ptr_bit_set = reinterpret_cast(page_ptr); + + if (!ptr_bit_set[cBitMapMagIdx] || + ptr_bit_set[cBitMapMagIdx] != kBitMapMagic) + return No; + + return Yes; + } + + auto FreeBitMap(VoidPtr page_ptr) -> Bool + { + if (this->IsBitMap(page_ptr) == No) + return No; + + UIntPtr* ptr_bit_set = reinterpret_cast(page_ptr); + + ptr_bit_set[cBitMapMagIdx] = kBitMapMagic; + ptr_bit_set[cBitMapUsedIdx] = No; + + this->GetBitMapStatus(ptr_bit_set); + + mm_map_page(ptr_bit_set, ~eFlagsPresent); + mm_map_page(ptr_bit_set, ~eFlagsWr); + mm_map_page(ptr_bit_set, ~eFlagsUser); + + return Yes; + } + + UInt32 MakeFlags(Bool wr, Bool user) + { + + UInt32 flags = eFlagsPresent; + + if (wr) + flags |= eFlagsWr; + + if (user) + flags |= eFlagsUser; + + return flags; + } + + /// @brief Iterate over availables pages for a free one. + /// @return The new address which was found. + auto FindBitMap(VoidPtr base_ptr, SizeT size, Bool wr, Bool user) -> VoidPtr + { + VoidPtr base = reinterpret_cast(((UIntPtr)base_ptr) + kPageSize); + + while (base && size) + { + UIntPtr* ptr_bit_set = reinterpret_cast(base); + + if (ptr_bit_set[cBitMapMagIdx] == kBitMapMagic && + ptr_bit_set[cBitMapSizeIdx] <= size) + { + if (ptr_bit_set[cBitMapUsedIdx] == No) + { + ptr_bit_set[cBitMapSizeIdx] = size; + ptr_bit_set[cBitMapUsedIdx] = Yes; + + this->GetBitMapStatus(ptr_bit_set); + + UInt32 flags = this->MakeFlags(wr, user); + mm_map_page(ptr_bit_set, flags); + + return (VoidPtr)ptr_bit_set; + } + } + else if (ptr_bit_set[cBitMapMagIdx] != kBitMapMagic) + { + UIntPtr* ptr_bit_set = reinterpret_cast(base_ptr); + + ptr_bit_set[cBitMapMagIdx] = kBitMapMagic; + ptr_bit_set[cBitMapSizeIdx] = size; + ptr_bit_set[cBitMapUsedIdx] = Yes; + + this->GetBitMapStatus(ptr_bit_set); + + UInt32 flags = this->MakeFlags(wr, user); + mm_map_page(ptr_bit_set, flags); + + return (VoidPtr)ptr_bit_set; + } + + base = reinterpret_cast(reinterpret_cast(base_ptr) + (ptr_bit_set[0] != kBitMapMagic ? size : ptr_bit_set[1])); + + if ((UIntPtr)base_ptr < (reinterpret_cast(base) + kHandoverHeader->f_BitMapSize)) + return nullptr; + } + + return nullptr; + } + + /// @brief Print Bitmap status + auto GetBitMapStatus(UIntPtr* ptr_bit_set) -> Void + { + if (!this->IsBitMap(ptr_bit_set)) + { + kcout << "Not a BitMap: " << hex_number((UIntPtr)ptr_bit_set) << endl; + return; + } + + kcout << "Magic Number: " << hex_number(ptr_bit_set[cBitMapMagIdx]) << endl; + kcout << "Is Allocated: " << (ptr_bit_set[cBitMapUsedIdx] ? "Yes" : "No") << endl; + kcout << "Size of BitMap (B): " << number(ptr_bit_set[cBitMapSizeIdx]) << endl; + kcout << "Size of BitMap (KIB): " << number(KIB(ptr_bit_set[cBitMapSizeIdx])) << endl; + kcout << "Size of BitMap (MIB): " << number(MIB(ptr_bit_set[cBitMapSizeIdx])) << endl; + kcout << "Size of BitMap (GIB): " << number(GIB(ptr_bit_set[cBitMapSizeIdx])) << endl; + kcout << "Size of BitMap (TIB): " << number(TIB(ptr_bit_set[cBitMapSizeIdx])) << endl; + kcout << "Address Of BitMap: " << hex_number((UIntPtr)ptr_bit_set) << endl; + } + }; + } // namespace Detail + + /// @brief Allocate a new page to be used by the OS. + /// @param wr read/write bit. + /// @param user user bit. + /// @return a new bitmap allocated pointer. + auto mm_alloc_bitmap(Boolean wr, Boolean user, SizeT size, Bool is_page) -> VoidPtr + { + VoidPtr ptr_new = nullptr; + Detail::IBitMapAllocator traits; + + ptr_new = traits.FindBitMap(kKernelBitMpStart, size, wr, user); + + if (!ptr_new) + { + return nullptr; + } + + if (wr) + mm_map_page(ptr_new, eFlagsWr | eFlagsPresent); + else if (user && wr) + mm_map_page(ptr_new, eFlagsUser | eFlagsWr | eFlagsPresent); + else if (user) + mm_map_page(ptr_new, eFlagsUser | eFlagsPresent); + else + mm_map_page(ptr_new, eFlagsPresent); + + return (UIntPtr*)ptr_new; + } + + /// @brief Free Bitmap, and mark it a absent in page terms. + auto mm_free_bitmap(VoidPtr page_ptr) -> Bool + { + if (!page_ptr) + return No; + + Detail::IBitMapAllocator traits; + Bool ret = traits.FreeBitMap(page_ptr); + + if (ret) + { + mm_map_page(page_ptr, ~eFlagsPresent); + } + + return ret; + } + } // namespace HAL +} // namespace Kernel diff --git a/dev/zka/src/BitMapMgr.cxx b/dev/zka/src/BitMapMgr.cxx deleted file mode 100644 index 1f4b4860..00000000 --- a/dev/zka/src/BitMapMgr.cxx +++ /dev/null @@ -1,203 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -#define kBitMapMagic (0x10210) - -#ifdef __ZKA_AMD64__ -#include -#elif defined(__ZKA_ARM64__) -#include -#endif - -#include -#include - -#define cBitMapMagIdx (0) -#define cBitMapSizeIdx (1) -#define cBitMapUsedIdx (2) - -namespace Kernel -{ - namespace HAL - { - namespace Detail - { - /// \brief Proxy Interface to allocate a bitmap. - class IBitMapAllocator final - { - public: - explicit IBitMapAllocator() = default; - ~IBitMapAllocator() = default; - - ZKA_COPY_DELETE(IBitMapAllocator); - - auto IsBitMap(VoidPtr page_ptr) -> Bool - { - if (!page_ptr) - return No; - - UIntPtr* ptr_bit_set = reinterpret_cast(page_ptr); - - if (!ptr_bit_set[cBitMapMagIdx] || - ptr_bit_set[cBitMapMagIdx] != kBitMapMagic) - return No; - - return Yes; - } - - auto FreeBitMap(VoidPtr page_ptr) -> Bool - { - if (this->IsBitMap(page_ptr) == No) - return No; - - UIntPtr* ptr_bit_set = reinterpret_cast(page_ptr); - - ptr_bit_set[cBitMapMagIdx] = kBitMapMagic; - ptr_bit_set[cBitMapUsedIdx] = No; - - this->GetBitMapStatus(ptr_bit_set); - - mm_map_page(ptr_bit_set, ~eFlagsPresent); - mm_map_page(ptr_bit_set, ~eFlagsWr); - mm_map_page(ptr_bit_set, ~eFlagsUser); - - return Yes; - } - - UInt32 MakeFlags(Bool wr, Bool user) - { - - UInt32 flags = eFlagsPresent; - - if (wr) - flags |= eFlagsWr; - - if (user) - flags |= eFlagsUser; - - return flags; - } - - /// @brief Iterate over availables pages for a free one. - /// @return The new address which was found. - auto FindBitMap(VoidPtr base_ptr, SizeT size, Bool wr, Bool user) -> VoidPtr - { - VoidPtr base = reinterpret_cast(((UIntPtr)base_ptr) + kPageSize); - - while (base && size) - { - UIntPtr* ptr_bit_set = reinterpret_cast(base); - - if (ptr_bit_set[cBitMapMagIdx] == kBitMapMagic && - ptr_bit_set[cBitMapSizeIdx] <= size) - { - if (ptr_bit_set[cBitMapUsedIdx] == No) - { - ptr_bit_set[cBitMapSizeIdx] = size; - ptr_bit_set[cBitMapUsedIdx] = Yes; - - this->GetBitMapStatus(ptr_bit_set); - - UInt32 flags = this->MakeFlags(wr, user); - mm_map_page(ptr_bit_set, flags); - - return (VoidPtr)ptr_bit_set; - } - } - else if (ptr_bit_set[cBitMapMagIdx] != kBitMapMagic) - { - UIntPtr* ptr_bit_set = reinterpret_cast(base_ptr); - - ptr_bit_set[cBitMapMagIdx] = kBitMapMagic; - ptr_bit_set[cBitMapSizeIdx] = size; - ptr_bit_set[cBitMapUsedIdx] = Yes; - - this->GetBitMapStatus(ptr_bit_set); - - UInt32 flags = this->MakeFlags(wr, user); - mm_map_page(ptr_bit_set, flags); - - return (VoidPtr)ptr_bit_set; - } - - base = reinterpret_cast(reinterpret_cast(base_ptr) + (ptr_bit_set[0] != kBitMapMagic ? size : ptr_bit_set[1])); - - if ((UIntPtr)base_ptr < (reinterpret_cast(base) + kHandoverHeader->f_BitMapSize)) - return nullptr; - } - - return nullptr; - } - - /// @brief Print Bitmap status - auto GetBitMapStatus(UIntPtr* ptr_bit_set) -> Void - { - if (!this->IsBitMap(ptr_bit_set)) - { - kcout << "Not a BitMap: " << hex_number((UIntPtr)ptr_bit_set) << endl; - return; - } - - kcout << "Magic Number: " << hex_number(ptr_bit_set[cBitMapMagIdx]) << endl; - kcout << "Is Allocated: " << (ptr_bit_set[cBitMapUsedIdx] ? "Yes" : "No") << endl; - kcout << "Size of BitMap (B): " << number(ptr_bit_set[cBitMapSizeIdx]) << endl; - kcout << "Size of BitMap (KIB): " << number(KIB(ptr_bit_set[cBitMapSizeIdx])) << endl; - kcout << "Size of BitMap (MIB): " << number(MIB(ptr_bit_set[cBitMapSizeIdx])) << endl; - kcout << "Size of BitMap (GIB): " << number(GIB(ptr_bit_set[cBitMapSizeIdx])) << endl; - kcout << "Size of BitMap (TIB): " << number(TIB(ptr_bit_set[cBitMapSizeIdx])) << endl; - kcout << "Address Of BitMap: " << hex_number((UIntPtr)ptr_bit_set) << endl; - } - }; - } // namespace Detail - - /// @brief Allocate a new page to be used by the OS. - /// @param wr read/write bit. - /// @param user user bit. - /// @return a new bitmap allocated pointer. - auto mm_alloc_bitmap(Boolean wr, Boolean user, SizeT size, Bool is_page) -> VoidPtr - { - VoidPtr ptr_new = nullptr; - Detail::IBitMapAllocator traits; - - ptr_new = traits.FindBitMap(kKernelBitMpStart, size, wr, user); - - if (!ptr_new) - { - return nullptr; - } - - if (wr) - mm_map_page(ptr_new, eFlagsWr | eFlagsPresent); - else if (user && wr) - mm_map_page(ptr_new, eFlagsUser | eFlagsWr | eFlagsPresent); - else if (user) - mm_map_page(ptr_new, eFlagsUser | eFlagsPresent); - else - mm_map_page(ptr_new, eFlagsPresent); - - return (UIntPtr*)ptr_new; - } - - /// @brief Free Bitmap, and mark it a absent in page terms. - auto mm_free_bitmap(VoidPtr page_ptr) -> Bool - { - if (!page_ptr) - return No; - - Detail::IBitMapAllocator traits; - Bool ret = traits.FreeBitMap(page_ptr); - - if (ret) - { - mm_map_page(page_ptr, ~eFlagsPresent); - } - - return ret; - } - } // namespace HAL -} // namespace Kernel diff --git a/dev/zka/src/CRuntime.cc b/dev/zka/src/CRuntime.cc new file mode 100644 index 00000000..4a1de1d7 --- /dev/null +++ b/dev/zka/src/CRuntime.cc @@ -0,0 +1,69 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +using namespace Kernel; + +/// @brief memset definition in C++. +/// @param dst destination pointer. +/// @param byte value to fill in. +/// @param len length of of src. +EXTERN_C VoidPtr memset(void* dst, int byte, long long unsigned int len) +{ + for (size_t i = 0UL; i < len; ++i) + { + ((int*)dst)[i] = byte; + } + + return dst; +} + +/// @brief memcpy definition in C++. +/// @param dst destination pointer. +/// @param src source pointer. +/// @param len length of of src. +EXTERN_C VoidPtr memcpy(void* dst, const void* src, long long unsigned int len) +{ + for (size_t i = 0UL; i < len; ++i) + { + ((int*)dst)[i] = ((int*)src)[i]; + } + + return dst; +} + +/// @brief strlen definition in C++. +EXTERN_C size_t strlen(const char* whatToCheck) +{ + SizeT len = 0; + + while (whatToCheck[len] != 0) + { + ++len; + } + + return len; +} + +/// @brief strcmp definition in C++. +EXTERN_C int strcmp(const char* whatToCheck, const char* whatToCheckRight) +{ + if (!whatToCheck || *whatToCheck == 0) + return 0; + + SizeT len = 0; + + while (whatToCheck[len] == whatToCheckRight[len]) + { + if (whatToCheck[len] == 0) + return 0; + + ++len; + } + + return len; +} diff --git a/dev/zka/src/CRuntime.cxx b/dev/zka/src/CRuntime.cxx deleted file mode 100644 index 75646bbe..00000000 --- a/dev/zka/src/CRuntime.cxx +++ /dev/null @@ -1,69 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -using namespace Kernel; - -/// @brief memset definition in C++. -/// @param dst destination pointer. -/// @param byte value to fill in. -/// @param len length of of src. -EXTERN_C VoidPtr memset(void* dst, int byte, long long unsigned int len) -{ - for (size_t i = 0UL; i < len; ++i) - { - ((int*)dst)[i] = byte; - } - - return dst; -} - -/// @brief memcpy definition in C++. -/// @param dst destination pointer. -/// @param src source pointer. -/// @param len length of of src. -EXTERN_C VoidPtr memcpy(void* dst, const void* src, long long unsigned int len) -{ - for (size_t i = 0UL; i < len; ++i) - { - ((int*)dst)[i] = ((int*)src)[i]; - } - - return dst; -} - -/// @brief strlen definition in C++. -EXTERN_C size_t strlen(const char* whatToCheck) -{ - SizeT len = 0; - - while (whatToCheck[len] != 0) - { - ++len; - } - - return len; -} - -/// @brief strcmp definition in C++. -EXTERN_C int strcmp(const char* whatToCheck, const char* whatToCheckRight) -{ - if (!whatToCheck || *whatToCheck == 0) - return 0; - - SizeT len = 0; - - while (whatToCheck[len] == whatToCheckRight[len]) - { - if (whatToCheck[len] == 0) - return 0; - - ++len; - } - - return len; -} diff --git a/dev/zka/src/CodeMgr.cc b/dev/zka/src/CodeMgr.cc new file mode 100644 index 00000000..130f8cfe --- /dev/null +++ b/dev/zka/src/CodeMgr.cc @@ -0,0 +1,33 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include + +namespace Kernel +{ + /// @brief Executes a new process from a function. Kernel code only. + /// @note This sets up a new stack, anything on the main function that calls the Kernel will not be accessible. + /// @param main the start of the process. + /// @return if the process was started or not. + Bool sched_execute_thread(MainKind main, const Char* process_name) noexcept + { + if (!main) + return No; + + UserProcess proc; + proc.SetImageStart(reinterpret_cast(main)); + + proc.Kind = UserProcess::kExectuableKind; + proc.StackSize = kib_cast(32); + + rt_set_memory(proc.Name, 0, kProcessLen); + rt_copy_memory((VoidPtr)process_name, proc.Name, rt_string_len(process_name)); + + return UserProcessScheduler::The().Add(proc) > 0; + } +} // namespace Kernel diff --git a/dev/zka/src/CodeMgr.cxx b/dev/zka/src/CodeMgr.cxx deleted file mode 100644 index 2e0308f3..00000000 --- a/dev/zka/src/CodeMgr.cxx +++ /dev/null @@ -1,33 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include - -namespace Kernel -{ - /// @brief Executes a new process from a function. Kernel code only. - /// @note This sets up a new stack, anything on the main function that calls the Kernel will not be accessible. - /// @param main the start of the process. - /// @return if the process was started or not. - Bool sched_execute_thread(MainKind main, const Char* process_name) noexcept - { - if (!main) - return No; - - UserProcess proc; - proc.SetImageStart(reinterpret_cast(main)); - - proc.Kind = UserProcess::kExectuableKind; - proc.StackSize = kib_cast(32); - - rt_set_memory(proc.Name, 0, kProcessLen); - rt_copy_memory((VoidPtr)process_name, proc.Name, rt_string_len(process_name)); - - return UserProcessScheduler::The().Add(proc) > 0; - } -} // namespace Kernel diff --git a/dev/zka/src/Crc32.cc b/dev/zka/src/Crc32.cc new file mode 100644 index 00000000..bcf04c03 --- /dev/null +++ b/dev/zka/src/Crc32.cc @@ -0,0 +1,83 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +// @file CRC32.cpp +// @brief Check sequence implementation. + +namespace Kernel +{ + /// @brief The CRC32 seed table. + UInt32 kCrcTbl[kCrcCnt] = { + 0x00000000L, 0xF26B8303L, 0xE13B70F7L, 0x1350F3F4L, 0xC79A971FL, + 0x35F1141CL, 0x26A1E7E8L, 0xD4CA64EBL, 0x8AD958CFL, 0x78B2DBCCL, + 0x6BE22838L, 0x9989AB3BL, 0x4D43CFD0L, 0xBF284CD3L, 0xAC78BF27L, + 0x5E133C24L, 0x105EC76FL, 0xE235446CL, 0xF165B798L, 0x030E349BL, + 0xD7C45070L, 0x25AFD373L, 0x36FF2087L, 0xC494A384L, 0x9A879FA0L, + 0x68EC1CA3L, 0x7BBCEF57L, 0x89D76C54L, 0x5D1D08BFL, 0xAF768BBCL, + 0xBC267848L, 0x4E4DFB4BL, 0x20BD8EDEL, 0xD2D60DDDL, 0xC186FE29L, + 0x33ED7D2AL, 0xE72719C1L, 0x154C9AC2L, 0x061C6936L, 0xF477EA35L, + 0xAA64D611L, 0x580F5512L, 0x4B5FA6E6L, 0xB93425E5L, 0x6DFE410EL, + 0x9F95C20DL, 0x8CC531F9L, 0x7EAEB2FAL, 0x30E349B1L, 0xC288CAB2L, + 0xD1D83946L, 0x23B3BA45L, 0xF779DEAEL, 0x05125DADL, 0x1642AE59L, + 0xE4292D5AL, 0xBA3A117EL, 0x4851927DL, 0x5B016189L, 0xA96AE28AL, + 0x7DA08661L, 0x8FCB0562L, 0x9C9BF696L, 0x6EF07595L, 0x417B1DBCL, + 0xB3109EBFL, 0xA0406D4BL, 0x522BEE48L, 0x86E18AA3L, 0x748A09A0L, + 0x67DAFA54L, 0x95B17957L, 0xCBA24573L, 0x39C9C670L, 0x2A993584L, + 0xD8F2B687L, 0x0C38D26CL, 0xFE53516FL, 0xED03A29BL, 0x1F682198L, + 0x5125DAD3L, 0xA34E59D0L, 0xB01EAA24L, 0x42752927L, 0x96BF4DCCL, + 0x64D4CECFL, 0x77843D3BL, 0x85EFBE38L, 0xDBFC821CL, 0x2997011FL, + 0x3AC7F2EBL, 0xC8AC71E8L, 0x1C661503L, 0xEE0D9600L, 0xFD5D65F4L, + 0x0F36E6F7L, 0x61C69362L, 0x93AD1061L, 0x80FDE395L, 0x72966096L, + 0xA65C047DL, 0x5437877EL, 0x4767748AL, 0xB50CF789L, 0xEB1FCBADL, + 0x197448AEL, 0x0A24BB5AL, 0xF84F3859L, 0x2C855CB2L, 0xDEEEDFB1L, + 0xCDBE2C45L, 0x3FD5AF46L, 0x7198540DL, 0x83F3D70EL, 0x90A324FAL, + 0x62C8A7F9L, 0xB602C312L, 0x44694011L, 0x5739B3E5L, 0xA55230E6L, + 0xFB410CC2L, 0x092A8FC1L, 0x1A7A7C35L, 0xE811FF36L, 0x3CDB9BDDL, + 0xCEB018DEL, 0xDDE0EB2AL, 0x2F8B6829L, 0x82F63B78L, 0x709DB87BL, + 0x63CD4B8FL, 0x91A6C88CL, 0x456CAC67L, 0xB7072F64L, 0xA457DC90L, + 0x563C5F93L, 0x082F63B7L, 0xFA44E0B4L, 0xE9141340L, 0x1B7F9043L, + 0xCFB5F4A8L, 0x3DDE77ABL, 0x2E8E845FL, 0xDCE5075CL, 0x92A8FC17L, + 0x60C37F14L, 0x73938CE0L, 0x81F80FE3L, 0x55326B08L, 0xA759E80BL, + 0xB4091BFFL, 0x466298FCL, 0x1871A4D8L, 0xEA1A27DBL, 0xF94AD42FL, + 0x0B21572CL, 0xDFEB33C7L, 0x2D80B0C4L, 0x3ED04330L, 0xCCBBC033L, + 0xA24BB5A6L, 0x502036A5L, 0x4370C551L, 0xB11B4652L, 0x65D122B9L, + 0x97BAA1BAL, 0x84EA524EL, 0x7681D14DL, 0x2892ED69L, 0xDAF96E6AL, + 0xC9A99D9EL, 0x3BC21E9DL, 0xEF087A76L, 0x1D63F975L, 0x0E330A81L, + 0xFC588982L, 0xB21572C9L, 0x407EF1CAL, 0x532E023EL, 0xA145813DL, + 0x758FE5D6L, 0x87E466D5L, 0x94B49521L, 0x66DF1622L, 0x38CC2A06L, + 0xCAA7A905L, 0xD9F75AF1L, 0x2B9CD9F2L, 0xFF56BD19L, 0x0D3D3E1AL, + 0x1E6DCDEEL, 0xEC064EEDL, 0xC38D26C4L, 0x31E6A5C7L, 0x22B65633L, + 0xD0DDD530L, 0x0417B1DBL, 0xF67C32D8L, 0xE52CC12CL, 0x1747422FL, + 0x49547E0BL, 0xBB3FFD08L, 0xA86F0EFCL, 0x5A048DFFL, 0x8ECEE914L, + 0x7CA56A17L, 0x6FF599E3L, 0x9D9E1AE0L, 0xD3D3E1ABL, 0x21B862A8L, + 0x32E8915CL, 0xC083125FL, 0x144976B4L, 0xE622F5B7L, 0xF5720643L, + 0x07198540L, 0x590AB964L, 0xAB613A67L, 0xB831C993L, 0x4A5A4A90L, + 0x9E902E7BL, 0x6CFBAD78L, 0x7FAB5E8CL, 0x8DC0DD8FL, 0xE330A81AL, + 0x115B2B19L, 0x020BD8EDL, 0xF0605BEEL, 0x24AA3F05L, 0xD6C1BC06L, + 0xC5914FF2L, 0x37FACCF1L, 0x69E9F0D5L, 0x9B8273D6L, 0x88D28022L, + 0x7AB90321L, 0xAE7367CAL, 0x5C18E4C9L, 0x4F48173DL, 0xBD23943EL, + 0xF36E6F75L, 0x0105EC76L, 0x12551F82L, 0xE03E9C81L, 0x34F4F86AL, + 0xC69F7B69L, 0xD5CF889DL, 0x27A40B9EL, 0x79B737BAL, 0x8BDCB4B9L, + 0x988C474DL, 0x6AE7C44EL, 0xBE2DA0A5L, 0x4C4623A6L, 0x5F16D052L, + 0xAD7D5351L}; + + /// @brief Calculate CRC32 of p + /// @param p the data to compute. + /// @param len the length of the data. + /// @return the CRC32. + UInt ke_calculate_crc32(const Char* p, UInt len) noexcept + { + UInt crc = 0xffffffff; + + while (len-- != 0) + crc = kCrcTbl[((UInt8)crc ^ *(p++))] ^ (crc >> 8); + + // return (~crc); also works, does the same thing. + return (crc ^ 0xffffffff); + } +} // namespace Kernel diff --git a/dev/zka/src/Crc32.cxx b/dev/zka/src/Crc32.cxx deleted file mode 100644 index 4faa78f9..00000000 --- a/dev/zka/src/Crc32.cxx +++ /dev/null @@ -1,83 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -// @file CRC32.cpp -// @brief Check sequence implementation. - -namespace Kernel -{ - /// @brief The CRC32 seed table. - UInt32 kCrcTbl[kCrcCnt] = { - 0x00000000L, 0xF26B8303L, 0xE13B70F7L, 0x1350F3F4L, 0xC79A971FL, - 0x35F1141CL, 0x26A1E7E8L, 0xD4CA64EBL, 0x8AD958CFL, 0x78B2DBCCL, - 0x6BE22838L, 0x9989AB3BL, 0x4D43CFD0L, 0xBF284CD3L, 0xAC78BF27L, - 0x5E133C24L, 0x105EC76FL, 0xE235446CL, 0xF165B798L, 0x030E349BL, - 0xD7C45070L, 0x25AFD373L, 0x36FF2087L, 0xC494A384L, 0x9A879FA0L, - 0x68EC1CA3L, 0x7BBCEF57L, 0x89D76C54L, 0x5D1D08BFL, 0xAF768BBCL, - 0xBC267848L, 0x4E4DFB4BL, 0x20BD8EDEL, 0xD2D60DDDL, 0xC186FE29L, - 0x33ED7D2AL, 0xE72719C1L, 0x154C9AC2L, 0x061C6936L, 0xF477EA35L, - 0xAA64D611L, 0x580F5512L, 0x4B5FA6E6L, 0xB93425E5L, 0x6DFE410EL, - 0x9F95C20DL, 0x8CC531F9L, 0x7EAEB2FAL, 0x30E349B1L, 0xC288CAB2L, - 0xD1D83946L, 0x23B3BA45L, 0xF779DEAEL, 0x05125DADL, 0x1642AE59L, - 0xE4292D5AL, 0xBA3A117EL, 0x4851927DL, 0x5B016189L, 0xA96AE28AL, - 0x7DA08661L, 0x8FCB0562L, 0x9C9BF696L, 0x6EF07595L, 0x417B1DBCL, - 0xB3109EBFL, 0xA0406D4BL, 0x522BEE48L, 0x86E18AA3L, 0x748A09A0L, - 0x67DAFA54L, 0x95B17957L, 0xCBA24573L, 0x39C9C670L, 0x2A993584L, - 0xD8F2B687L, 0x0C38D26CL, 0xFE53516FL, 0xED03A29BL, 0x1F682198L, - 0x5125DAD3L, 0xA34E59D0L, 0xB01EAA24L, 0x42752927L, 0x96BF4DCCL, - 0x64D4CECFL, 0x77843D3BL, 0x85EFBE38L, 0xDBFC821CL, 0x2997011FL, - 0x3AC7F2EBL, 0xC8AC71E8L, 0x1C661503L, 0xEE0D9600L, 0xFD5D65F4L, - 0x0F36E6F7L, 0x61C69362L, 0x93AD1061L, 0x80FDE395L, 0x72966096L, - 0xA65C047DL, 0x5437877EL, 0x4767748AL, 0xB50CF789L, 0xEB1FCBADL, - 0x197448AEL, 0x0A24BB5AL, 0xF84F3859L, 0x2C855CB2L, 0xDEEEDFB1L, - 0xCDBE2C45L, 0x3FD5AF46L, 0x7198540DL, 0x83F3D70EL, 0x90A324FAL, - 0x62C8A7F9L, 0xB602C312L, 0x44694011L, 0x5739B3E5L, 0xA55230E6L, - 0xFB410CC2L, 0x092A8FC1L, 0x1A7A7C35L, 0xE811FF36L, 0x3CDB9BDDL, - 0xCEB018DEL, 0xDDE0EB2AL, 0x2F8B6829L, 0x82F63B78L, 0x709DB87BL, - 0x63CD4B8FL, 0x91A6C88CL, 0x456CAC67L, 0xB7072F64L, 0xA457DC90L, - 0x563C5F93L, 0x082F63B7L, 0xFA44E0B4L, 0xE9141340L, 0x1B7F9043L, - 0xCFB5F4A8L, 0x3DDE77ABL, 0x2E8E845FL, 0xDCE5075CL, 0x92A8FC17L, - 0x60C37F14L, 0x73938CE0L, 0x81F80FE3L, 0x55326B08L, 0xA759E80BL, - 0xB4091BFFL, 0x466298FCL, 0x1871A4D8L, 0xEA1A27DBL, 0xF94AD42FL, - 0x0B21572CL, 0xDFEB33C7L, 0x2D80B0C4L, 0x3ED04330L, 0xCCBBC033L, - 0xA24BB5A6L, 0x502036A5L, 0x4370C551L, 0xB11B4652L, 0x65D122B9L, - 0x97BAA1BAL, 0x84EA524EL, 0x7681D14DL, 0x2892ED69L, 0xDAF96E6AL, - 0xC9A99D9EL, 0x3BC21E9DL, 0xEF087A76L, 0x1D63F975L, 0x0E330A81L, - 0xFC588982L, 0xB21572C9L, 0x407EF1CAL, 0x532E023EL, 0xA145813DL, - 0x758FE5D6L, 0x87E466D5L, 0x94B49521L, 0x66DF1622L, 0x38CC2A06L, - 0xCAA7A905L, 0xD9F75AF1L, 0x2B9CD9F2L, 0xFF56BD19L, 0x0D3D3E1AL, - 0x1E6DCDEEL, 0xEC064EEDL, 0xC38D26C4L, 0x31E6A5C7L, 0x22B65633L, - 0xD0DDD530L, 0x0417B1DBL, 0xF67C32D8L, 0xE52CC12CL, 0x1747422FL, - 0x49547E0BL, 0xBB3FFD08L, 0xA86F0EFCL, 0x5A048DFFL, 0x8ECEE914L, - 0x7CA56A17L, 0x6FF599E3L, 0x9D9E1AE0L, 0xD3D3E1ABL, 0x21B862A8L, - 0x32E8915CL, 0xC083125FL, 0x144976B4L, 0xE622F5B7L, 0xF5720643L, - 0x07198540L, 0x590AB964L, 0xAB613A67L, 0xB831C993L, 0x4A5A4A90L, - 0x9E902E7BL, 0x6CFBAD78L, 0x7FAB5E8CL, 0x8DC0DD8FL, 0xE330A81AL, - 0x115B2B19L, 0x020BD8EDL, 0xF0605BEEL, 0x24AA3F05L, 0xD6C1BC06L, - 0xC5914FF2L, 0x37FACCF1L, 0x69E9F0D5L, 0x9B8273D6L, 0x88D28022L, - 0x7AB90321L, 0xAE7367CAL, 0x5C18E4C9L, 0x4F48173DL, 0xBD23943EL, - 0xF36E6F75L, 0x0105EC76L, 0x12551F82L, 0xE03E9C81L, 0x34F4F86AL, - 0xC69F7B69L, 0xD5CF889DL, 0x27A40B9EL, 0x79B737BAL, 0x8BDCB4B9L, - 0x988C474DL, 0x6AE7C44EL, 0xBE2DA0A5L, 0x4C4623A6L, 0x5F16D052L, - 0xAD7D5351L}; - - /// @brief Calculate CRC32 of p - /// @param p the data to compute. - /// @param len the length of the data. - /// @return the CRC32. - UInt ke_calculate_crc32(const Char* p, UInt len) noexcept - { - UInt crc = 0xffffffff; - - while (len-- != 0) - crc = kCrcTbl[((UInt8)crc ^ *(p++))] ^ (crc >> 8); - - // return (~crc); also works, does the same thing. - return (crc ^ 0xffffffff); - } -} // namespace Kernel diff --git a/dev/zka/src/CxxAbi-AMD64.cc b/dev/zka/src/CxxAbi-AMD64.cc new file mode 100644 index 00000000..9d439d6b --- /dev/null +++ b/dev/zka/src/CxxAbi-AMD64.cc @@ -0,0 +1,90 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifdef __ZKA_AMD64__ + +#include +#include +#include + +atexit_func_entry_t __atexit_funcs[kDSOMaxObjects]; + +uarch_t __atexit_func_count; + +/// @brief Dynamic Shared Object Handle. +Kernel::UIntPtr __dso_handle; + +EXTERN_C Kernel::Void __cxa_pure_virtual(void* self) +{ + kcout << "object: " << Kernel::number(reinterpret_cast(self)); + kcout << ", has unimplemented virtual functions.\r"; +} + +EXTERN_C void ___chkstk_ms(void) +{ +} + +EXTERN_C int atexit(void (*f)(void*), void* arg, void* dso) +{ + if (__atexit_func_count >= kDSOMaxObjects) + return -1; + + __atexit_funcs[__atexit_func_count].destructor_func = f; + __atexit_funcs[__atexit_func_count].obj_ptr = arg; + __atexit_funcs[__atexit_func_count].dso_handle = dso; + + __atexit_func_count++; + + return 0; +} + +EXTERN_C void __cxa_finalize(void* f) +{ + uarch_t i = __atexit_func_count; + if (!f) + { + while (i--) + { + if (__atexit_funcs[i].destructor_func) + { + (*__atexit_funcs[i].destructor_func)(__atexit_funcs[i].obj_ptr); + }; + } + + return; + } + + while (i--) + { + if (__atexit_funcs[i].destructor_func) + { + (*__atexit_funcs[i].destructor_func)(__atexit_funcs[i].obj_ptr); + __atexit_funcs[i].destructor_func = 0; + }; + } +} + +namespace cxxabiv1 +{ + EXTERN_C int __cxa_guard_acquire(__guard* g) + { + (void)g; + return 0; + } + + EXTERN_C int __cxa_guard_release(__guard* g) + { + *(char*)g = 1; + return 0; + } + + EXTERN_C void __cxa_guard_abort(__guard* g) + { + (void)g; + } +} // namespace cxxabiv1 + +#endif // ifdef __ZKA_AMD64__ diff --git a/dev/zka/src/CxxAbi-AMD64.cxx b/dev/zka/src/CxxAbi-AMD64.cxx deleted file mode 100644 index 32e3ff37..00000000 --- a/dev/zka/src/CxxAbi-AMD64.cxx +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifdef __ZKA_AMD64__ - -#include -#include -#include - -atexit_func_entry_t __atexit_funcs[kDSOMaxObjects]; - -uarch_t __atexit_func_count; - -/// @brief Dynamic Shared Object Handle. -Kernel::UIntPtr __dso_handle; - -EXTERN_C Kernel::Void __cxa_pure_virtual(void* self) -{ - kcout << "object: " << Kernel::number(reinterpret_cast(self)); - kcout << ", has unimplemented virtual functions.\r"; -} - -EXTERN_C void ___chkstk_ms(void) -{ -} - -EXTERN_C int atexit(void (*f)(void*), void* arg, void* dso) -{ - if (__atexit_func_count >= kDSOMaxObjects) - return -1; - - __atexit_funcs[__atexit_func_count].destructor_func = f; - __atexit_funcs[__atexit_func_count].obj_ptr = arg; - __atexit_funcs[__atexit_func_count].dso_handle = dso; - - __atexit_func_count++; - - return 0; -} - -EXTERN_C void __cxa_finalize(void* f) -{ - uarch_t i = __atexit_func_count; - if (!f) - { - while (i--) - { - if (__atexit_funcs[i].destructor_func) - { - (*__atexit_funcs[i].destructor_func)(__atexit_funcs[i].obj_ptr); - }; - } - - return; - } - - while (i--) - { - if (__atexit_funcs[i].destructor_func) - { - (*__atexit_funcs[i].destructor_func)(__atexit_funcs[i].obj_ptr); - __atexit_funcs[i].destructor_func = 0; - }; - } -} - -namespace cxxabiv1 -{ - EXTERN_C int __cxa_guard_acquire(__guard* g) - { - (void)g; - return 0; - } - - EXTERN_C int __cxa_guard_release(__guard* g) - { - *(char*)g = 1; - return 0; - } - - EXTERN_C void __cxa_guard_abort(__guard* g) - { - (void)g; - } -} // namespace cxxabiv1 - -#endif // ifdef __ZKA_AMD64__ diff --git a/dev/zka/src/CxxAbi-ARM64.cc b/dev/zka/src/CxxAbi-ARM64.cc new file mode 100644 index 00000000..f603f863 --- /dev/null +++ b/dev/zka/src/CxxAbi-ARM64.cc @@ -0,0 +1,90 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifdef __ZKA_ARM64__ + +#include +#include +#include + +atexit_func_entry_t __atexit_funcs[kDSOMaxObjects]; + +uarch_t __atexit_func_count; + +/// @brief Dynamic Shared Object Handle. +Kernel::UIntPtr __dso_handle; + +EXTERN_C void __chkstk(void) +{ +} + +EXTERN_C int atexit(void (*f)(void*), void* arg, void* dso) +{ + if (__atexit_func_count >= kDSOMaxObjects) + return -1; + + __atexit_funcs[__atexit_func_count].destructor_func = f; + __atexit_funcs[__atexit_func_count].obj_ptr = arg; + __atexit_funcs[__atexit_func_count].dso_handle = dso; + + __atexit_func_count++; + + return 0; +} + +EXTERN_C void __cxa_finalize(void* f) +{ + uarch_t i = __atexit_func_count; + if (!f) + { + while (i--) + { + if (__atexit_funcs[i].destructor_func) + { + (*__atexit_funcs[i].destructor_func)(__atexit_funcs[i].obj_ptr); + }; + } + + return; + } + + while (i--) + { + if (__atexit_funcs[i].destructor_func) + { + (*__atexit_funcs[i].destructor_func)(__atexit_funcs[i].obj_ptr); + __atexit_funcs[i].destructor_func = 0; + }; + } +} + +namespace cxxabiv1 +{ + EXTERN_C int __cxa_guard_acquire(__guard* g) + { + (void)g; + return 0; + } + + EXTERN_C int __cxa_guard_release(__guard* g) + { + *(char*)g = 1; + return 0; + } + + EXTERN_C void __cxa_guard_abort(__guard* g) + { + (void)g; + } +} // namespace cxxabiv1 + +EXTERN_C Kernel::Void _purecall(void* self) +{ + kcout << "object: " << Kernel::number(reinterpret_cast(self)); + kcout << ", has unimplemented virtual functions.\r"; +} + +#endif // ifdef __ZKA_ARM64__ diff --git a/dev/zka/src/CxxAbi-ARM64.cxx b/dev/zka/src/CxxAbi-ARM64.cxx deleted file mode 100644 index 759c2a7f..00000000 --- a/dev/zka/src/CxxAbi-ARM64.cxx +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifdef __ZKA_ARM64__ - -#include -#include -#include - -atexit_func_entry_t __atexit_funcs[kDSOMaxObjects]; - -uarch_t __atexit_func_count; - -/// @brief Dynamic Shared Object Handle. -Kernel::UIntPtr __dso_handle; - -EXTERN_C void __chkstk(void) -{ -} - -EXTERN_C int atexit(void (*f)(void*), void* arg, void* dso) -{ - if (__atexit_func_count >= kDSOMaxObjects) - return -1; - - __atexit_funcs[__atexit_func_count].destructor_func = f; - __atexit_funcs[__atexit_func_count].obj_ptr = arg; - __atexit_funcs[__atexit_func_count].dso_handle = dso; - - __atexit_func_count++; - - return 0; -} - -EXTERN_C void __cxa_finalize(void* f) -{ - uarch_t i = __atexit_func_count; - if (!f) - { - while (i--) - { - if (__atexit_funcs[i].destructor_func) - { - (*__atexit_funcs[i].destructor_func)(__atexit_funcs[i].obj_ptr); - }; - } - - return; - } - - while (i--) - { - if (__atexit_funcs[i].destructor_func) - { - (*__atexit_funcs[i].destructor_func)(__atexit_funcs[i].obj_ptr); - __atexit_funcs[i].destructor_func = 0; - }; - } -} - -namespace cxxabiv1 -{ - EXTERN_C int __cxa_guard_acquire(__guard* g) - { - (void)g; - return 0; - } - - EXTERN_C int __cxa_guard_release(__guard* g) - { - *(char*)g = 1; - return 0; - } - - EXTERN_C void __cxa_guard_abort(__guard* g) - { - (void)g; - } -} // namespace cxxabiv1 - -EXTERN_C Kernel::Void _purecall(void* self) -{ - kcout << "object: " << Kernel::number(reinterpret_cast(self)); - kcout << ", has unimplemented virtual functions.\r"; -} - -#endif // ifdef __ZKA_ARM64__ diff --git a/dev/zka/src/Defines.cc b/dev/zka/src/Defines.cc new file mode 100644 index 00000000..d5ce58ce --- /dev/null +++ b/dev/zka/src/Defines.cc @@ -0,0 +1,7 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include diff --git a/dev/zka/src/Defines.cxx b/dev/zka/src/Defines.cxx deleted file mode 100644 index fc7d41b5..00000000 --- a/dev/zka/src/Defines.cxx +++ /dev/null @@ -1,7 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include diff --git a/dev/zka/src/DeviceMgr.cc b/dev/zka/src/DeviceMgr.cc new file mode 100644 index 00000000..78058a17 --- /dev/null +++ b/dev/zka/src/DeviceMgr.cc @@ -0,0 +1,7 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include diff --git a/dev/zka/src/DeviceMgr.cxx b/dev/zka/src/DeviceMgr.cxx deleted file mode 100644 index 1bd775ab..00000000 --- a/dev/zka/src/DeviceMgr.cxx +++ /dev/null @@ -1,7 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include diff --git a/dev/zka/src/DriveMgr.cc b/dev/zka/src/DriveMgr.cc new file mode 100644 index 00000000..9f5201d9 --- /dev/null +++ b/dev/zka/src/DriveMgr.cc @@ -0,0 +1,167 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include + +#include +#include +#include + +/***********************************************************************************/ +/// @file DriveMgr.cxx +/// @brief Drive Manager API. +/***********************************************************************************/ + +namespace Kernel +{ + STATIC UInt16 kATAIO = 0U; + STATIC UInt8 kATAMaster = 0U; + + /// @brief reads from an ATA drive. + /// @param pckt Packet structure (fPacketContent must be non null) + /// @return + Void io_drv_input(DriveTrait::DrivePacket* pckt) + { + if (!pckt) + { + return; + } + +#ifdef __AHCI__ + drv_std_read(pckt->fLba, (Char*)pckt->fPacketContent.Leak(), kAHCISectorSize, pckt->fPacketSize); +#elif defined(__ATA_PIO__) || defined(__ATA_DMA__) + drv_std_read(pckt->fLba, kATAIO, kATAMaster, (Char*)pckt->fPacketContent.Leak(), kATASectorSize, pckt->fPacketSize); +#endif + } + + /// @brief Writes to an ATA drive. + /// @param pckt the packet to write. + /// @return + Void io_drv_output(DriveTrait::DrivePacket* pckt) + { + if (!pckt) + { + return; + } + +#ifdef __AHCI__ + drv_std_write(pckt->fLba, (Char*)pckt->fPacketContent.Leak(), kAHCISectorSize, pckt->fPacketSize); +#elif defined(__ATA_PIO__) || defined(__ATA_DMA__) + drv_std_write(pckt->fLba, kATAIO, kATAMaster, (Char*)pckt->fPacketContent.Leak(), kATASectorSize, pckt->fPacketSize); +#endif + } + + /// @brief Executes a disk check on the ATA drive. + /// @param pckt the packet to read. + /// @return + Void io_drv_init(DriveTrait::DrivePacket* pckt) + { + if (!pckt) + { + return; + } + + pckt->fPacketGood = false; + +#if defined(__ATA_PIO__) || defined(__ATA_DMA__) + kATAMaster = true; + kATAIO = ATA_PRIMARY_IO; + + if (!drv_std_init(kATAIO, kATAMaster, kATAIO, kATAMaster)) + return; + +#elif defined(__AHCI__) + UInt16 pi = 0; + + if (!drv_std_init(pi)) + return; +#endif // if defined(__ATA_PIO__) || defined (__ATA_DMA__) + + pckt->fPacketGood = true; + } + +/// @brief Gets the drive kind (ATA, SCSI, AHCI...) +/// @param no arguments. +/// @return no arguments. +#ifdef __ATA_PIO__ + const Char* io_drv_kind(Void) + { + return "ATA-PIO"; + } +#endif +#ifdef __ATA_DMA__ + const Char* io_drv_kind(Void) + { + return "ATA-DMA"; + } +#endif +#ifdef __AHCI__ + const Char* io_drv_kind(Void) + { + return "AHCI"; + } +#endif +#ifdef __ZKA_MINIMAL_OS__ + const Char* io_drv_kind(Void) + { + return "Not Loaded"; + } +#endif +#ifdef __ZKA_ED__ + const Char* io_drv_kind(Void) + { + return "C++ Code Editor"; + } +#endif + + /// @brief Unimplemented drive function. + /// @param pckt the packet to read. + /// @return + Void io_drv_unimplemented(DriveTrait::DrivePacket* pckt) + { + ZKA_UNUSED(pckt); + } + + /// @brief Makes a new drive. + /// @return the new blank drive. + DriveTrait io_construct_drive() noexcept + { + DriveTrait trait; + + rt_copy_memory((VoidPtr) "\\Mount\\NUL:", trait.fName, rt_string_len("\\Mount\\NUL:")); + trait.fKind = kInvalidStorage; + + trait.fInput = io_drv_unimplemented; + trait.fOutput = io_drv_unimplemented; + trait.fVerify = io_drv_unimplemented; + trait.fInit = io_drv_unimplemented; + trait.fDriveKind = io_drv_kind; + + return trait; + } + + /// @brief Fetches the main drive. + /// @return the new drive. + DriveTrait io_construct_main_drive() noexcept + { + DriveTrait trait; + + rt_copy_memory((VoidPtr) "\\Mount\\MainDisk:", trait.fName, rt_string_len("\\Mount\\MainDisk:")); + trait.fKind = kMassStorage | kEPMDrive; + + trait.fVerify = io_drv_unimplemented; + trait.fOutput = io_drv_output; + trait.fInput = io_drv_input; + trait.fInit = io_drv_init; + trait.fDriveKind = io_drv_kind; + + kcout << "Constructed drive successfully.\r"; + + return trait; + } +} // namespace Kernel diff --git a/dev/zka/src/DriveMgr.cxx b/dev/zka/src/DriveMgr.cxx deleted file mode 100644 index 4164674b..00000000 --- a/dev/zka/src/DriveMgr.cxx +++ /dev/null @@ -1,167 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include - -#include -#include -#include - -/***********************************************************************************/ -/// @file DriveMgr.cxx -/// @brief Drive Manager API. -/***********************************************************************************/ - -namespace Kernel -{ - STATIC UInt16 kATAIO = 0U; - STATIC UInt8 kATAMaster = 0U; - - /// @brief reads from an ATA drive. - /// @param pckt Packet structure (fPacketContent must be non null) - /// @return - Void io_drv_input(DriveTrait::DrivePacket* pckt) - { - if (!pckt) - { - return; - } - -#ifdef __AHCI__ - drv_std_read(pckt->fLba, (Char*)pckt->fPacketContent.Leak(), kAHCISectorSize, pckt->fPacketSize); -#elif defined(__ATA_PIO__) || defined(__ATA_DMA__) - drv_std_read(pckt->fLba, kATAIO, kATAMaster, (Char*)pckt->fPacketContent.Leak(), kATASectorSize, pckt->fPacketSize); -#endif - } - - /// @brief Writes to an ATA drive. - /// @param pckt the packet to write. - /// @return - Void io_drv_output(DriveTrait::DrivePacket* pckt) - { - if (!pckt) - { - return; - } - -#ifdef __AHCI__ - drv_std_write(pckt->fLba, (Char*)pckt->fPacketContent.Leak(), kAHCISectorSize, pckt->fPacketSize); -#elif defined(__ATA_PIO__) || defined(__ATA_DMA__) - drv_std_write(pckt->fLba, kATAIO, kATAMaster, (Char*)pckt->fPacketContent.Leak(), kATASectorSize, pckt->fPacketSize); -#endif - } - - /// @brief Executes a disk check on the ATA drive. - /// @param pckt the packet to read. - /// @return - Void io_drv_init(DriveTrait::DrivePacket* pckt) - { - if (!pckt) - { - return; - } - - pckt->fPacketGood = false; - -#if defined(__ATA_PIO__) || defined(__ATA_DMA__) - kATAMaster = true; - kATAIO = ATA_PRIMARY_IO; - - if (!drv_std_init(kATAIO, kATAMaster, kATAIO, kATAMaster)) - return; - -#elif defined(__AHCI__) - UInt16 pi = 0; - - if (!drv_std_init(pi)) - return; -#endif // if defined(__ATA_PIO__) || defined (__ATA_DMA__) - - pckt->fPacketGood = true; - } - -/// @brief Gets the drive kind (ATA, SCSI, AHCI...) -/// @param no arguments. -/// @return no arguments. -#ifdef __ATA_PIO__ - const Char* io_drv_kind(Void) - { - return "ATA-PIO"; - } -#endif -#ifdef __ATA_DMA__ - const Char* io_drv_kind(Void) - { - return "ATA-DMA"; - } -#endif -#ifdef __AHCI__ - const Char* io_drv_kind(Void) - { - return "AHCI"; - } -#endif -#ifdef __ZKA_MINIMAL_OS__ - const Char* io_drv_kind(Void) - { - return "Not Loaded"; - } -#endif -#ifdef __ZKA_ED__ - const Char* io_drv_kind(Void) - { - return "C++ Code Editor"; - } -#endif - - /// @brief Unimplemented drive function. - /// @param pckt the packet to read. - /// @return - Void io_drv_unimplemented(DriveTrait::DrivePacket* pckt) - { - ZKA_UNUSED(pckt); - } - - /// @brief Makes a new drive. - /// @return the new blank drive. - DriveTrait io_construct_drive() noexcept - { - DriveTrait trait; - - rt_copy_memory((VoidPtr) "\\Mount\\NUL:", trait.fName, rt_string_len("\\Mount\\NUL:")); - trait.fKind = kInvalidStorage; - - trait.fInput = io_drv_unimplemented; - trait.fOutput = io_drv_unimplemented; - trait.fVerify = io_drv_unimplemented; - trait.fInit = io_drv_unimplemented; - trait.fDriveKind = io_drv_kind; - - return trait; - } - - /// @brief Fetches the main drive. - /// @return the new drive. - DriveTrait io_construct_main_drive() noexcept - { - DriveTrait trait; - - rt_copy_memory((VoidPtr) "\\Mount\\MainDisk:", trait.fName, rt_string_len("\\Mount\\MainDisk:")); - trait.fKind = kMassStorage | kEPMDrive; - - trait.fVerify = io_drv_unimplemented; - trait.fOutput = io_drv_output; - trait.fInput = io_drv_input; - trait.fInit = io_drv_init; - trait.fDriveKind = io_drv_kind; - - kcout << "Constructed drive successfully.\r"; - - return trait; - } -} // namespace Kernel diff --git a/dev/zka/src/ErrorOr.cc b/dev/zka/src/ErrorOr.cc new file mode 100644 index 00000000..9c10745e --- /dev/null +++ b/dev/zka/src/ErrorOr.cc @@ -0,0 +1,12 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +/***********************************************************************************/ +/// @file ErrorOr.cxx /// +/// @brief ErrorOr container class. /// +/***********************************************************************************/ diff --git a/dev/zka/src/ErrorOr.cxx b/dev/zka/src/ErrorOr.cxx deleted file mode 100644 index 53d60a3d..00000000 --- a/dev/zka/src/ErrorOr.cxx +++ /dev/null @@ -1,12 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -/***********************************************************************************/ -/// @file ErrorOr.cxx /// -/// @brief ErrorOr container class. /// -/***********************************************************************************/ diff --git a/dev/zka/src/FS/HPFS.cc b/dev/zka/src/FS/HPFS.cc new file mode 100644 index 00000000..0fb80079 --- /dev/null +++ b/dev/zka/src/FS/HPFS.cc @@ -0,0 +1,12 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifdef __FSKIT_INCLUDES_HPFS__ + +#include +#include + +#endif // ifdef __FSKIT_INCLUDES_HPFS__ diff --git a/dev/zka/src/FS/HPFS.cxx b/dev/zka/src/FS/HPFS.cxx deleted file mode 100644 index 56760972..00000000 --- a/dev/zka/src/FS/HPFS.cxx +++ /dev/null @@ -1,12 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifdef __FSKIT_INCLUDES_HPFS__ - -#include -#include - -#endif // ifdef __FSKIT_INCLUDES_HPFS__ diff --git a/dev/zka/src/FS/NeFS.cc b/dev/zka/src/FS/NeFS.cc new file mode 100644 index 00000000..6fcbb786 --- /dev/null +++ b/dev/zka/src/FS/NeFS.cc @@ -0,0 +1,1057 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#ifdef __FSKIT_USE_NEFS__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef __ZKA_MINIMAL_OS__ +using namespace Kernel; + +#ifdef __ZKA_NO_BUILTIN__ +/***********************************************************************************/ +/** + Define those external symbols, to make the editor shutup +*/ +/***********************************************************************************/ + +/***********************************************************************************/ +/// @brief get sector count. +/***********************************************************************************/ +Kernel::SizeT drv_get_sector_count(); + +/***********************************************************************************/ +/// @brief get device size. +/***********************************************************************************/ +Kernel::SizeT drv_get_size(); + +#endif + +///! BUGS: 0 + +/***********************************************************************************/ +/// This file implements the New File System. +/// New File System implements a B-Tree based algortihm. +/// \\ +/// \\Path1\\ \\ath2\\ +/// \\readme.rtf \\ListContents.pef \\readme.lnk <-- symlink. +/// \\Path1\\readme.rtf +/***********************************************************************************/ + +STATIC MountpointInterface sMountpointInterface; + +/***********************************************************************************/ +/// @brief Creates a new fork inside the New filesystem partition. +/// @param catalog it's catalog +/// @param the_fork the fork itself. +/// @return the fork +/***********************************************************************************/ +_Output NFS_FORK_STRUCT* NeFSParser::CreateFork(_Input NFS_CATALOG_STRUCT* catalog, + _Input NFS_FORK_STRUCT& the_fork) +{ + if (catalog && the_fork.ForkName[0] != 0 && + the_fork.DataSize <= kNeFSForkDataSz) + { + Lba lba = (the_fork.Kind == kNeFSDataForkKind) ? catalog->DataFork + : catalog->ResourceFork; + + kcout << "fork lba: " << hex_number(lba) << endl; + + if (lba <= kNeFSCatalogStartAddress) + return nullptr; + + auto drv = sMountpointInterface.A(); + + /// special treatment. + rt_copy_memory((VoidPtr) "fs/nefs-packet", drv.fPacket.fPacketMime, + rt_string_len("fs/nefs-packet")); + + NFS_FORK_STRUCT curFork{0}; + NFS_FORK_STRUCT prevFork{0}; + Lba lbaOfPreviousFork = lba; + + /// do not check for anything. Loop until we get what we want, that is a free fork zone. + while (true) + { + if (lba <= kNeFSCatalogStartAddress) + break; + + drv.fPacket.fLba = lba; + drv.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); + drv.fPacket.fPacketContent = &curFork; + + drv.fInput(&drv.fPacket); + + if (curFork.NextSibling > kBadAddress) + { + kcout << "bad fork: " << hex_number(curFork.NextSibling) << endl; + break; + } + + kcout << "next fork: " << hex_number(curFork.NextSibling) << endl; + + if (curFork.Flags & kNeFSFlagCreated) + { + kcout << "fork already exists.\r"; + + /// sanity check. + if (StringBuilder::Equals(curFork.ForkName, the_fork.ForkName) && + StringBuilder::Equals(curFork.CatalogName, catalog->Name)) + return nullptr; + + kcout << "next fork: " << hex_number(curFork.NextSibling) << endl; + + lbaOfPreviousFork = lba; + lba = curFork.NextSibling; + + prevFork = curFork; + } + else + { + /// This is a check that we have, in order to link the previous fork + /// entry. + if (lba >= kNeFSCatalogStartAddress) + { + drv.fPacket.fLba = lbaOfPreviousFork; + drv.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); + drv.fPacket.fPacketContent = &prevFork; + + prevFork.NextSibling = lba; + + /// write to disk. + drv.fOutput(&drv.fPacket); + } + + break; + } + } + + constexpr auto cForkPadding = + 4; /// this value gives us space for the data offset. + + the_fork.Flags |= kNeFSFlagCreated; + the_fork.DataOffset = lba - sizeof(NFS_FORK_STRUCT); + the_fork.PreviousSibling = lbaOfPreviousFork; + the_fork.NextSibling = the_fork.DataOffset - the_fork.DataSize - sizeof(NFS_FORK_STRUCT); + + drv.fPacket.fLba = lba; + drv.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); + drv.fPacket.fPacketContent = &the_fork; + + drv.fOutput(&drv.fPacket); + + /// log what we have now. + kcout << "Wrote fork data at: " << hex_number(the_fork.DataOffset) + << endl; + + kcout << "Wrote fork at: " << hex_number(lba) << endl; + + return &the_fork; + } + + return nullptr; +} + +/***********************************************************************************/ +/// @brief Find fork inside New filesystem. +/// @param catalog the catalog. +/// @param name the fork name. +/// @return the fork. +/***********************************************************************************/ +_Output NFS_FORK_STRUCT* NeFSParser::FindFork(_Input NFS_CATALOG_STRUCT* catalog, + _Input const Char* name, + Boolean isDataFork) +{ + auto drv = sMountpointInterface.A(); + NFS_FORK_STRUCT* the_fork = nullptr; + + Lba lba = isDataFork ? catalog->DataFork : catalog->ResourceFork; + + while (lba != 0) + { + drv.fPacket.fLba = lba; + drv.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); + drv.fPacket.fPacketContent = (VoidPtr)the_fork; + + rt_copy_memory((VoidPtr) "fs/nefs-packet", drv.fPacket.fPacketMime, 16); + + if (auto res = + fs_newfs_read(&sMountpointInterface, drv, this->fDriveIndex); + res) + { + switch (res) + { + case 1: + ErrLocal() = kErrorDiskReadOnly; + break; + case 2: + ErrLocal() = kErrorDiskIsFull; + break; + ErrLocal() = kErrorNoSuchDisk; + break; + + default: + break; + } + return nullptr; + } + + if (StringBuilder::Equals(the_fork->ForkName, name)) + { + break; + } + + lba = the_fork->NextSibling; + } + + return the_fork; +} + +/***********************************************************************************/ +/// @brief Simpler factory to create a catalog (assumes you want to create a +/// file.) +/// @param name +/// @return catalog pointer. +/***********************************************************************************/ +_Output NFS_CATALOG_STRUCT* NeFSParser::CreateCatalog(_Input const Char* name) +{ + return this->CreateCatalog(name, 0, kNeFSCatalogKindFile); +} + +/***********************************************************************************/ +/// @brief Creates a new catalog into the disk. +/// @param name the catalog name. +/// @param flags the flags of the catalog. +/// @param kind the catalog kind. +/// @return catalog pointer. +/***********************************************************************************/ +_Output NFS_CATALOG_STRUCT* NeFSParser::CreateCatalog(_Input const Char* name, + _Input const Int32& flags, + _Input const Int32& kind) +{ + kcout << "CreateCatalog(...)\r"; + + Lba out_lba = 0UL; + + kcout << "Checking for extension...\r"; + + /// a directory should have a slash in the end. + if (kind == kNeFSCatalogKindDir && + name[rt_string_len(name) - 1] != NeFileSystemHelper::Separator()) + return nullptr; + + /// a file shouldn't have a slash in the end. + if (kind != kNeFSCatalogKindDir && + name[rt_string_len(name) - 1] == NeFileSystemHelper::Separator()) + return nullptr; + + NFS_CATALOG_STRUCT* catalog_copy = this->FindCatalog(name, out_lba); + + if (catalog_copy) + { + kcout << "Catalog already exists: " << name << ".\r"; + ErrLocal() = kErrorFileExists; + + return catalog_copy; + } + + Char parentName[kNeFSNodeNameLen] = {0}; + + for (SizeT indexName = 0UL; indexName < rt_string_len(name); ++indexName) + { + parentName[indexName] = name[indexName]; + } + + if (*parentName == 0) + { + kcout << "Parent name is NUL.\r"; + ErrLocal() = kErrorFileNotFound; + return nullptr; + } + + /// Locate parent catalog, to then allocate right after it. + + for (SizeT indexFill = 0; indexFill < rt_string_len(name); ++indexFill) + { + parentName[indexFill] = name[indexFill]; + } + + SizeT indexReverseCopy = rt_string_len(parentName); + + // zero character it. + parentName[--indexReverseCopy] = 0; + + // mandatory / character, zero it. + parentName[--indexReverseCopy] = 0; + + while (parentName[indexReverseCopy] != NeFileSystemHelper::Separator()) + { + parentName[indexReverseCopy] = 0; + --indexReverseCopy; + } + + NFS_CATALOG_STRUCT* catalog = this->FindCatalog(parentName, out_lba); + + auto drive = sMountpointInterface.A(); + + if (catalog && catalog->Kind == kNeFSCatalogKindFile) + { + kcout << "Parent name is file.\r"; + delete catalog; + return nullptr; + } + else if (!catalog) + { + Char sectorBufPartBlock[kNeFSSectorSz] = {0}; + + drive.fPacket.fPacketContent = sectorBufPartBlock; + drive.fPacket.fPacketSize = kNeFSSectorSz; + drive.fPacket.fLba = kNeFSRootCatalogStartAddress; + + drive.fInput(&drive.fPacket); + + constexpr auto cNeFSCatalogPadding = 4; + + NFS_ROOT_PARTITION_BLOCK* part_block = (NFS_ROOT_PARTITION_BLOCK*)sectorBufPartBlock; + out_lba = part_block->StartCatalog; + } + + constexpr SizeT cDefaultForkSize = kNeFSForkSize; + + NFS_CATALOG_STRUCT* child_catalog = new NFS_CATALOG_STRUCT(); + + Int32 flagsList = flags; + + child_catalog->ResourceForkSize = cDefaultForkSize; + child_catalog->DataForkSize = cDefaultForkSize; + + child_catalog->NextSibling = out_lba; + child_catalog->PrevSibling = out_lba; + child_catalog->Kind = kind; + child_catalog->Flags = kNeFSFlagCreated | flagsList; + + rt_copy_memory((VoidPtr)name, (VoidPtr)child_catalog->Name, + rt_string_len(name)); + + NFS_CATALOG_STRUCT temporary_catalog; + + Lba start_free = out_lba; + + rt_copy_memory((VoidPtr) "fs/nefs-packet", drive.fPacket.fPacketMime, + rt_string_len("fs/nefs-packet")); + + drive.fPacket.fPacketContent = &temporary_catalog; + drive.fPacket.fPacketSize = kNeFSSectorSz; + drive.fPacket.fLba = start_free; + + drive.fInput(&drive.fPacket); + + NFS_CATALOG_STRUCT* next_sibling = reinterpret_cast(&temporary_catalog); + + start_free = next_sibling->NextSibling; + + child_catalog->PrevSibling = out_lba; + + drive.fPacket.fLba = start_free; + drive.fInput(&drive.fPacket); + + while (drive.fPacket.fPacketGood) + { + next_sibling = reinterpret_cast(&temporary_catalog); + + if (start_free <= kNeFSRootCatalogStartAddress) + { + delete child_catalog; + delete catalog; + + return nullptr; + } + + // ========================== // + // Allocate catalog now... + // ========================== // + if ((next_sibling->Flags & kNeFSFlagCreated) == 0) + { + Char sectorBufPartBlock[kNeFSSectorSz] = {0}; + + drive.fPacket.fPacketContent = sectorBufPartBlock; + drive.fPacket.fPacketSize = kNeFSSectorSz; + drive.fPacket.fLba = kNeFSRootCatalogStartAddress; + + drive.fInput(&drive.fPacket); + + constexpr auto cNeFSCatalogPadding = 4; + + NFS_ROOT_PARTITION_BLOCK* part_block = (NFS_ROOT_PARTITION_BLOCK*)sectorBufPartBlock; + + if (part_block->FreeCatalog < 1) + { + delete child_catalog; + return nullptr; + } + + child_catalog->DataFork = part_block->DiskSize - start_free; + child_catalog->ResourceFork = child_catalog->DataFork; + + // Write the new catalog next sibling, if we don't know this parent. // + // This is necessary, so that we don't have to get another lba to allocate. // + if (!StringBuilder::Equals(parentName, next_sibling->Name)) + { + child_catalog->NextSibling = + start_free + (sizeof(NFS_CATALOG_STRUCT) * cNeFSCatalogPadding); + } + + drive.fPacket.fPacketContent = child_catalog; + drive.fPacket.fPacketSize = sizeof(NFS_CATALOG_STRUCT); + drive.fPacket.fLba = start_free; + + drive.fOutput(&drive.fPacket); + + // Get NeFS partition's block. + + drive.fPacket.fPacketContent = sectorBufPartBlock; + drive.fPacket.fPacketSize = kNeFSSectorSz; + drive.fPacket.fLba = kNeFSRootCatalogStartAddress; + + drive.fInput(&drive.fPacket); + + part_block->FreeSectors -= 1; + part_block->CatalogCount += 1; + part_block->FreeCatalog -= 1; + + drive.fOutput(&drive.fPacket); + + kcout << "Create new catalog, status: " + << hex_number(child_catalog->Flags) << endl; + kcout << "Create new catalog, name: " << child_catalog->Name + << endl; + + delete catalog; + return child_catalog; + } + else if ((next_sibling->Flags & kNeFSFlagCreated) && + StringBuilder::Equals(next_sibling->Name, name)) + { + return next_sibling; + } + + constexpr auto cNeFSCatalogPadding = 4; + + //// @note that's how we find the next catalog in the partition block. + start_free = start_free + (sizeof(NFS_CATALOG_STRUCT) * cNeFSCatalogPadding); + + drive.fPacket.fPacketContent = &temporary_catalog; + drive.fPacket.fPacketSize = kNeFSSectorSz; + drive.fPacket.fLba = start_free; + + drive.fInput(&drive.fPacket); + } + + delete catalog; + return nullptr; +} + +/// @brief Make a EPM+NeFS drive out of the disk. +/// @param drive The drive to write on. +/// @return If it was sucessful, see ErrLocal(). +bool NeFSParser::Format(_Input _Output DriveTrait* drive, _Input const Lba endLba, _Input const Int32 flags, const Char* part_name) +{ + if (*part_name == 0 || + endLba == 0) + return false; + + // verify disk. + drive->fVerify(&drive->fPacket); + + rt_copy_memory((VoidPtr) "fs/nefs-packet", drive->fPacket.fPacketMime, + rt_string_len("fs/nefs-packet")); + + // if disk isn't good, then error out. + if (false == drive->fPacket.fPacketGood) + { + ErrLocal() = kErrorDiskIsCorrupted; + return false; + } + + Char fs_buf[kNeFSSectorSz] = {0}; + + Lba start = kNeFSRootCatalogStartAddress; + + drive->fPacket.fPacketContent = fs_buf; + drive->fPacket.fPacketSize = kNeFSSectorSz; + drive->fPacket.fLba = start; + + drive->fInput(&drive->fPacket); + + if (flags & kNeFSPartitionTypeBoot) + { + // make it bootable when needed. + Char bufEpmHdr[kNeFSSectorSz] = {0}; + + BOOT_BLOCK_STRUCT* epmBoot = (BOOT_BLOCK_STRUCT*)bufEpmHdr; + + // EPM header. + + constexpr auto cFsName = "NeFS"; + constexpr auto cBlockName = "ZKA:"; + + rt_copy_memory(reinterpret_cast(const_cast(cFsName)), epmBoot->Fs, rt_string_len(cFsName)); + + epmBoot->FsVersion = kNeFSVersionInteger; + epmBoot->LbaStart = start; + epmBoot->SectorSz = kNeFSSectorSz; + + rt_copy_memory(reinterpret_cast(const_cast(cBlockName)), epmBoot->Name, rt_string_len(cBlockName)); + rt_copy_memory(reinterpret_cast(const_cast(kEPMMagic)), epmBoot->Magic, rt_string_len(kEPMMagic)); + + Lba outEpmLba = kEpmBase; + + Char buf[kNeFSSectorSz]; + + Lba prevStart = 0; + SizeT cnt = 0; + + while (drive->fPacket.fPacketGood) + { + drive->fPacket.fPacketContent = buf; + drive->fPacket.fPacketSize = kNeFSSectorSz; + drive->fPacket.fLba = outEpmLba; + + drive->fInput(&drive->fPacket); + + if (buf[0] == 0) + { + epmBoot->LbaStart = prevStart; + + if (epmBoot->LbaStart) + epmBoot->LbaStart = outEpmLba; + + epmBoot->LbaEnd = endLba; + epmBoot->NumBlocks = cnt; + + drive->fPacket.fPacketContent = bufEpmHdr; + drive->fPacket.fPacketSize = kNeFSSectorSz; + drive->fPacket.fLba = outEpmLba; + + drive->fOutput(&drive->fPacket); + + break; + } + else + { + prevStart = ((BOOT_BLOCK_STRUCT*)buf)->LbaStart + ((BOOT_BLOCK_STRUCT*)buf)->LbaEnd; + } + + outEpmLba += sizeof(BOOT_BLOCK_STRUCT); + ++cnt; + } + } + + // disk isnt faulty and data has been fetched. + while (drive->fPacket.fPacketGood) + { + NFS_ROOT_PARTITION_BLOCK* part_block = (NFS_ROOT_PARTITION_BLOCK*)fs_buf; + + // check for an empty partition here. + if (part_block->PartitionName[0] == 0 && + rt_string_cmp(part_block->Ident, kNeFSIdent, kNeFSIdentLen)) + { + // partition is free and valid. + + part_block->Version = kNeFSVersionInteger; + + const auto cUntitledHD = part_name; + + rt_copy_memory((VoidPtr)kNeFSIdent, (VoidPtr)part_block->Ident, + kNeFSIdentLen); + + rt_copy_memory((VoidPtr)cUntitledHD, (VoidPtr)part_block->PartitionName, + rt_string_len(cUntitledHD)); + + SizeT catalogCount = 0UL; + + SizeT sectorCount = drv_get_sector_count(); + SizeT diskSize = drv_get_size(); + + part_block->Kind = kNeFSPartitionTypeStandard; + part_block->StartCatalog = kNeFSCatalogStartAddress; + part_block->Flags = kNeFSPartitionTypeStandard; + part_block->CatalogCount = sectorCount / sizeof(NFS_CATALOG_STRUCT); + part_block->SectorCount = sectorCount; + part_block->DiskSize = diskSize; + part_block->FreeCatalog = sectorCount / sizeof(NFS_CATALOG_STRUCT); + + drive->fPacket.fPacketContent = fs_buf; + drive->fPacket.fPacketSize = kNeFSSectorSz; + drive->fPacket.fLba = kNeFSRootCatalogStartAddress; + + drive->fOutput(&drive->fPacket); + + kcout << "drive kind: " << drive->fDriveKind() << endl; + + kcout << "partition name: " << part_block->PartitionName << endl; + kcout << "start: " << hex_number(part_block->StartCatalog) << endl; + kcout << "number of catalogs: " << hex_number(part_block->CatalogCount) << endl; + kcout << "free catalog: " << hex_number(part_block->FreeCatalog) << endl; + kcout << "free sectors: " << hex_number(part_block->FreeSectors) << endl; + kcout << "sector size: " << hex_number(part_block->SectorSize) << endl; + + // write the root catalog. + this->CreateCatalog(kNeFSRoot, 0, kNeFSCatalogKindDir); + + return true; + } + + kcout << "partition block already exists.\r"; + + start += part_block->DiskSize; + + drive->fPacket.fPacketContent = fs_buf; + drive->fPacket.fPacketSize = kNeFSSectorSz; + drive->fPacket.fLba = start; + + drive->fInput(&drive->fPacket); + } + + return false; +} + +/// @brief Writes the data fork into a specific catalog. +/// @param catalog the catalog itself +/// @param data the data. +/// @return if the catalog w rote the contents successfully. +bool NeFSParser::WriteCatalog(_Input _Output NFS_CATALOG_STRUCT* catalog, Bool is_rsrc_fork, _Input VoidPtr data, _Input SizeT size_of_data, _Input const Char* forkName) +{ + if (size_of_data > kNeFSForkDataSz || + size_of_data == 0) + return No; + + auto buf = new UInt8[kNeFSForkDataSz]; + rt_set_memory(buf, 0, kNeFSForkDataSz); + + rt_copy_memory(data, buf, size_of_data); + + auto drive = sMountpointInterface.A(); + + rt_copy_memory((VoidPtr) "fs/nefs-packet", drive.fPacket.fPacketMime, + rt_string_len("fs/nefs-packet")); + + auto startFork = (!is_rsrc_fork) ? catalog->DataFork + : catalog->ResourceFork; + + NFS_FORK_STRUCT* fork_data_input = new NFS_FORK_STRUCT(); + NFS_FORK_STRUCT prevFork{}; + + // sanity check of the fork position as the condition to run the loop. + while (startFork >= kNeFSCatalogStartAddress) + { + drive.fPacket.fPacketContent = fork_data_input; + drive.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); + drive.fPacket.fLba = startFork; + + drive.fInput(&drive.fPacket); + + // check the fork, if it's position is valid. + if (fork_data_input->DataOffset <= kNeFSCatalogStartAddress) + { + ErrLocal() = kErrorDiskIsCorrupted; + + kcout << "Invalid fork offset.\r"; + + return false; + } + + if (fork_data_input->Flags != kNeFSFlagUnallocated && + fork_data_input->Flags != kNeFSFlagDeleted && + StringBuilder::Equals(fork_data_input->ForkName, forkName) && + StringBuilder::Equals(fork_data_input->CatalogName, catalog->Name) && + fork_data_input->DataSize == size_of_data) + { + // ===================================================== // + // Store the blob now. + // ===================================================== // + + fork_data_input->Flags |= kNeFSFlagCreated; + + drive.fPacket.fPacketContent = buf; + drive.fPacket.fPacketSize = kNeFSForkDataSz; + drive.fPacket.fLba = fork_data_input->DataOffset; + + kcout << "data offset: " << hex_number(fork_data_input->DataOffset) << endl; + + drive.fOutput(&drive.fPacket); + + drive.fPacket.fPacketContent = fork_data_input; + drive.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); + drive.fPacket.fLba = startFork - sizeof(NFS_FORK_STRUCT); + + drive.fOutput(&drive.fPacket); + + kcout << "wrote fork at offset: " << hex_number(fork_data_input->DataOffset) << endl; + kcout << "wrote fork at offset: " << hex_number(startFork - sizeof(NFS_FORK_STRUCT)) << endl; + + delete catalog; + + return true; + } + + // stumble upon a fork, store it. + + prevFork = *fork_data_input; + + startFork = fork_data_input->NextSibling; + } + + return false; +} + +/// @brief +/// @param catalogName the catalog name. +/// @return the newly found catalog. +_Output NFS_CATALOG_STRUCT* NeFSParser::FindCatalog(_Input const Char* catalogName, + Lba& out_lba) +{ + kcout << "Start finding catalog...\r"; + + NFS_ROOT_PARTITION_BLOCK fs_buf{0}; + auto drive = sMountpointInterface.A(); + + rt_copy_memory((VoidPtr) "fs/nefs-packet", drive.fPacket.fPacketMime, + rt_string_len("fs/nefs-packet")); + + drive.fPacket.fPacketContent = &fs_buf; + drive.fPacket.fPacketSize = sizeof(NFS_ROOT_PARTITION_BLOCK); + drive.fPacket.fLba = kNeFSRootCatalogStartAddress; + + drive.fInput(&drive.fPacket); + + NFS_ROOT_PARTITION_BLOCK* part = (NFS_ROOT_PARTITION_BLOCK*)&fs_buf; + + auto startCatalogList = part->StartCatalog; + const auto cCtartCatalogList = startCatalogList; + + auto localSearchFirst = false; + + NFS_CATALOG_STRUCT temporary_catalog{0}; + + drive.fPacket.fLba = startCatalogList; + drive.fPacket.fPacketContent = &temporary_catalog; + drive.fPacket.fPacketSize = sizeof(NFS_CATALOG_STRUCT); + + drive.fInput(&drive.fPacket); + + if (!StringBuilder::Equals(catalogName, NeFileSystemHelper::Root())) + { + Char parentName[kNeFSNodeNameLen] = {0}; + + for (SizeT indexFill = 0; indexFill < rt_string_len(catalogName); ++indexFill) + { + parentName[indexFill] = catalogName[indexFill]; + } + + SizeT indexReverseCopy = rt_string_len(parentName); + + // zero character. + parentName[--indexReverseCopy] = 0; + + // mandatory '/' character. + parentName[--indexReverseCopy] = 0; + + while (parentName[indexReverseCopy] != NeFileSystemHelper::Separator()) + { + parentName[indexReverseCopy] = 0; + --indexReverseCopy; + } + + NFS_CATALOG_STRUCT* parentCatalog = this->FindCatalog(parentName, out_lba); + + if (parentCatalog && + !StringBuilder::Equals(parentName, NeFileSystemHelper::Root())) + { + startCatalogList = parentCatalog->NextSibling; + delete parentCatalog; + + localSearchFirst = true; + } + else if (parentCatalog) + { + delete parentCatalog; + } + else + { + return nullptr; + } + } + + kcout << "Fetching catalog...\r"; + +NeFSSearchThroughCatalogList: + while (drive.fPacket.fPacketGood) + { + drive.fPacket.fLba = startCatalogList; + drive.fPacket.fPacketContent = &temporary_catalog; + drive.fPacket.fPacketSize = sizeof(NFS_CATALOG_STRUCT); + + drive.fInput(&drive.fPacket); + + NFS_CATALOG_STRUCT* catalog = (NFS_CATALOG_STRUCT*)&temporary_catalog; + + if (StringBuilder::Equals(catalogName, catalog->Name)) + { + /// ignore unallocated catalog, break + if (!(catalog->Flags & kNeFSFlagCreated)) + { + goto NeFSContinueSearch; + } + + NFS_CATALOG_STRUCT* catalogPtr = new NFS_CATALOG_STRUCT(); + rt_copy_memory(catalog, catalogPtr, sizeof(NFS_CATALOG_STRUCT)); + + kcout << "Found catalog at: " << hex_number(startCatalogList) << endl; + kcout << "Found catalog at: " << catalog->Name << endl; + + out_lba = startCatalogList; + return catalogPtr; + } + + NeFSContinueSearch: + startCatalogList = catalog->NextSibling; + + if (startCatalogList <= kNeFSRootCatalogStartAddress) + break; + } + + if (localSearchFirst) + { + localSearchFirst = false; + startCatalogList = cCtartCatalogList; + + goto NeFSSearchThroughCatalogList; + } + + out_lba = 0UL; + return nullptr; +} + +/// @brief Get catalog from filesystem. +/// @param name the catalog's name/ +/// @return +_Output NFS_CATALOG_STRUCT* NeFSParser::GetCatalog(_Input const Char* name) +{ + Lba unused = 0; + return this->FindCatalog(name, unused); +} + +/// @brief Closes a catalog, (frees it). +/// @param catalog the catalog to close. +/// @return +Boolean NeFSParser::CloseCatalog(_Input _Output NFS_CATALOG_STRUCT* catalog) +{ + if (!catalog) + return false; + + delete catalog; + catalog = nullptr; + + return true; +} + +/// @brief Mark catalog as removed. +/// @param catalog The catalog structure. +/// @return if the catalog was removed or not. +Boolean NeFSParser::RemoveCatalog(_Input const Char* catalogName) +{ + if (!catalogName || + StringBuilder::Equals(catalogName, NeFileSystemHelper::Root())) + { + ErrLocal() = kErrorInternal; + return false; + } + + Lba out_lba = 0; + auto catalog = this->FindCatalog(catalogName, out_lba); + + if (out_lba >= kNeFSCatalogStartAddress || + catalog->Flags & kNeFSFlagCreated) + { + catalog->Flags |= kNeFSFlagDeleted; + + auto drive = sMountpointInterface.A(); + + rt_copy_memory((VoidPtr) "fs/nefs-packet", drive.fPacket.fPacketMime, + rt_string_len("fs/nefs-packet")); + + drive.fPacket.fLba = out_lba; // the catalog position. + drive.fPacket.fPacketSize = + sizeof(NFS_CATALOG_STRUCT); // size of catalog. roughly the sector size. + drive.fPacket.fPacketContent = catalog; // the catalog itself. + + drive.fOutput(&drive.fPacket); // send packet. + + Char partitionBlockBuf[sizeof(NFS_ROOT_PARTITION_BLOCK)] = {0}; + + drive.fPacket.fLba = kNeFSRootCatalogStartAddress; + drive.fPacket.fPacketContent = partitionBlockBuf; + drive.fPacket.fPacketSize = sizeof(NFS_ROOT_PARTITION_BLOCK); + + drive.fInput(&drive.fPacket); + + NFS_ROOT_PARTITION_BLOCK* part_block = + reinterpret_cast(partitionBlockBuf); + + --part_block->CatalogCount; + ++part_block->FreeSectors; + + drive.fOutput(&drive.fPacket); + + return true; + } + + delete catalog; + return false; +} + +/// ***************************************************************** /// +/// Reading,Seek,Tell are unimplemented on catalogs, refer to forks I/O instead. +/// ***************************************************************** /// + +/***********************************************************************************/ +/// @brief Read the catalog data fork. +/// @param catalog +/// @param dataSz +/// @return +/***********************************************************************************/ + +VoidPtr NeFSParser::ReadCatalog(_Input _Output NFS_CATALOG_STRUCT* catalog, + _Input Bool is_rsrc_fork, + _Input SizeT dataSz, + _Input const Char* forkName) +{ + if (!catalog) + { + ErrLocal() = kErrorFileNotFound; + return nullptr; + } + + constexpr auto cNeFSCatalogPadding = 4; + + Lba dataForkLba = (!is_rsrc_fork) ? catalog->DataFork : catalog->ResourceFork; + Size dataForkSize = (!is_rsrc_fork) ? catalog->DataForkSize : catalog->ResourceForkSize; + + kcout << "catalog " << catalog->Name + << ", fork: " << hex_number(dataForkLba) << endl; + + NFS_FORK_STRUCT* fs_buf = new NFS_FORK_STRUCT(); + auto drive = sMountpointInterface.A(); + + rt_copy_memory((VoidPtr) "fs/nefs-packet", drive.fPacket.fPacketMime, + rt_string_len("fs/nefs-packet")); + + NFS_FORK_STRUCT* fs_fork_data = nullptr; + + while (dataForkLba > kNeFSCatalogStartAddress) + { + drive.fPacket.fLba = dataForkLba; + drive.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); + drive.fPacket.fPacketContent = fs_buf; + + drive.fInput(&drive.fPacket); + + fs_fork_data = fs_buf; + + kcout << "ForkName: " << fs_fork_data->ForkName << endl; + kcout << "CatalogName: " << fs_fork_data->CatalogName << endl; + + if (StringBuilder::Equals(forkName, fs_fork_data->ForkName) && + StringBuilder::Equals(catalog->Name, fs_fork_data->CatalogName)) + break; + + dataForkLba = fs_fork_data->NextSibling; + } + + if (dataForkLba < kNeFSCatalogStartAddress) + { + delete fs_buf; + return nullptr; + } + + return fs_fork_data; +} + +/***********************************************************************************/ +/// @brief Seek in the data fork. +/// @param catalog the catalog offset. +/// @param off where to seek. +/// @return if the seeking was successful. +/***********************************************************************************/ + +bool NeFSParser::Seek(_Input _Output NFS_CATALOG_STRUCT* catalog, SizeT off) +{ + if (!catalog) + { + ErrLocal() = kErrorFileNotFound; + return false; + } + + ErrLocal() = kErrorUnimplemented; + return false; +} + +/***********************************************************************************/ +/// @brief Tell where we are inside the data fork. +/// @param catalog +/// @return The position on the file. +/***********************************************************************************/ + +SizeT NeFSParser::Tell(_Input _Output NFS_CATALOG_STRUCT* catalog) +{ + if (!catalog) + { + ErrLocal() = kErrorFileNotFound; + return 0; + } + + ErrLocal() = kErrorUnimplemented; + return 0; +} + +namespace Kernel::Detail +{ + /***********************************************************************************/ + /// @brief Construct NeFS drives. + /***********************************************************************************/ + Boolean fs_init_newfs(Void) noexcept + { + kcout << "Creating drives...\r"; + + sMountpointInterface.A() = io_construct_main_drive(); + sMountpointInterface.B() = io_construct_drive(); + sMountpointInterface.C() = io_construct_drive(); + sMountpointInterface.D() = io_construct_drive(); + + kcout << "Constructing A:\r"; + + sMountpointInterface.A().fInit(&sMountpointInterface.A().fPacket); + + kcout << "Constructing A: [ OK ]\r"; + + return true; + } +} // namespace Kernel::Detail +#endif // !__ZKA_MINIMAL_OS__ + +#endif // ifdef __FSKIT_USE_NEFS__ diff --git a/dev/zka/src/FS/NeFS.cxx b/dev/zka/src/FS/NeFS.cxx deleted file mode 100644 index 48bd441f..00000000 --- a/dev/zka/src/FS/NeFS.cxx +++ /dev/null @@ -1,1057 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#ifdef __FSKIT_USE_NEFS__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef __ZKA_MINIMAL_OS__ -using namespace Kernel; - -#ifdef __ZKA_NO_BUILTIN__ -/***********************************************************************************/ -/** - Define those external symbols, to make the editor shutup -*/ -/***********************************************************************************/ - -/***********************************************************************************/ -/// @brief get sector count. -/***********************************************************************************/ -Kernel::SizeT drv_get_sector_count(); - -/***********************************************************************************/ -/// @brief get device size. -/***********************************************************************************/ -Kernel::SizeT drv_get_size(); - -#endif - -///! BUGS: 0 - -/***********************************************************************************/ -/// This file implements the New File System. -/// New File System implements a B-Tree based algortihm. -/// \\ -/// \\Path1\\ \\ath2\\ -/// \\readme.rtf \\ListContents.pef \\readme.lnk <-- symlink. -/// \\Path1\\readme.rtf -/***********************************************************************************/ - -STATIC MountpointInterface sMountpointInterface; - -/***********************************************************************************/ -/// @brief Creates a new fork inside the New filesystem partition. -/// @param catalog it's catalog -/// @param the_fork the fork itself. -/// @return the fork -/***********************************************************************************/ -_Output NFS_FORK_STRUCT* NeFSParser::CreateFork(_Input NFS_CATALOG_STRUCT* catalog, - _Input NFS_FORK_STRUCT& the_fork) -{ - if (catalog && the_fork.ForkName[0] != 0 && - the_fork.DataSize <= kNeFSForkDataSz) - { - Lba lba = (the_fork.Kind == kNeFSDataForkKind) ? catalog->DataFork - : catalog->ResourceFork; - - kcout << "fork lba: " << hex_number(lba) << endl; - - if (lba <= kNeFSCatalogStartAddress) - return nullptr; - - auto drv = sMountpointInterface.A(); - - /// special treatment. - rt_copy_memory((VoidPtr) "fs/nefs-packet", drv.fPacket.fPacketMime, - rt_string_len("fs/nefs-packet")); - - NFS_FORK_STRUCT curFork{0}; - NFS_FORK_STRUCT prevFork{0}; - Lba lbaOfPreviousFork = lba; - - /// do not check for anything. Loop until we get what we want, that is a free fork zone. - while (true) - { - if (lba <= kNeFSCatalogStartAddress) - break; - - drv.fPacket.fLba = lba; - drv.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); - drv.fPacket.fPacketContent = &curFork; - - drv.fInput(&drv.fPacket); - - if (curFork.NextSibling > kBadAddress) - { - kcout << "bad fork: " << hex_number(curFork.NextSibling) << endl; - break; - } - - kcout << "next fork: " << hex_number(curFork.NextSibling) << endl; - - if (curFork.Flags & kNeFSFlagCreated) - { - kcout << "fork already exists.\r"; - - /// sanity check. - if (StringBuilder::Equals(curFork.ForkName, the_fork.ForkName) && - StringBuilder::Equals(curFork.CatalogName, catalog->Name)) - return nullptr; - - kcout << "next fork: " << hex_number(curFork.NextSibling) << endl; - - lbaOfPreviousFork = lba; - lba = curFork.NextSibling; - - prevFork = curFork; - } - else - { - /// This is a check that we have, in order to link the previous fork - /// entry. - if (lba >= kNeFSCatalogStartAddress) - { - drv.fPacket.fLba = lbaOfPreviousFork; - drv.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); - drv.fPacket.fPacketContent = &prevFork; - - prevFork.NextSibling = lba; - - /// write to disk. - drv.fOutput(&drv.fPacket); - } - - break; - } - } - - constexpr auto cForkPadding = - 4; /// this value gives us space for the data offset. - - the_fork.Flags |= kNeFSFlagCreated; - the_fork.DataOffset = lba - sizeof(NFS_FORK_STRUCT); - the_fork.PreviousSibling = lbaOfPreviousFork; - the_fork.NextSibling = the_fork.DataOffset - the_fork.DataSize - sizeof(NFS_FORK_STRUCT); - - drv.fPacket.fLba = lba; - drv.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); - drv.fPacket.fPacketContent = &the_fork; - - drv.fOutput(&drv.fPacket); - - /// log what we have now. - kcout << "Wrote fork data at: " << hex_number(the_fork.DataOffset) - << endl; - - kcout << "Wrote fork at: " << hex_number(lba) << endl; - - return &the_fork; - } - - return nullptr; -} - -/***********************************************************************************/ -/// @brief Find fork inside New filesystem. -/// @param catalog the catalog. -/// @param name the fork name. -/// @return the fork. -/***********************************************************************************/ -_Output NFS_FORK_STRUCT* NeFSParser::FindFork(_Input NFS_CATALOG_STRUCT* catalog, - _Input const Char* name, - Boolean isDataFork) -{ - auto drv = sMountpointInterface.A(); - NFS_FORK_STRUCT* the_fork = nullptr; - - Lba lba = isDataFork ? catalog->DataFork : catalog->ResourceFork; - - while (lba != 0) - { - drv.fPacket.fLba = lba; - drv.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); - drv.fPacket.fPacketContent = (VoidPtr)the_fork; - - rt_copy_memory((VoidPtr) "fs/nefs-packet", drv.fPacket.fPacketMime, 16); - - if (auto res = - fs_newfs_read(&sMountpointInterface, drv, this->fDriveIndex); - res) - { - switch (res) - { - case 1: - ErrLocal() = kErrorDiskReadOnly; - break; - case 2: - ErrLocal() = kErrorDiskIsFull; - break; - ErrLocal() = kErrorNoSuchDisk; - break; - - default: - break; - } - return nullptr; - } - - if (StringBuilder::Equals(the_fork->ForkName, name)) - { - break; - } - - lba = the_fork->NextSibling; - } - - return the_fork; -} - -/***********************************************************************************/ -/// @brief Simpler factory to create a catalog (assumes you want to create a -/// file.) -/// @param name -/// @return catalog pointer. -/***********************************************************************************/ -_Output NFS_CATALOG_STRUCT* NeFSParser::CreateCatalog(_Input const Char* name) -{ - return this->CreateCatalog(name, 0, kNeFSCatalogKindFile); -} - -/***********************************************************************************/ -/// @brief Creates a new catalog into the disk. -/// @param name the catalog name. -/// @param flags the flags of the catalog. -/// @param kind the catalog kind. -/// @return catalog pointer. -/***********************************************************************************/ -_Output NFS_CATALOG_STRUCT* NeFSParser::CreateCatalog(_Input const Char* name, - _Input const Int32& flags, - _Input const Int32& kind) -{ - kcout << "CreateCatalog(...)\r"; - - Lba out_lba = 0UL; - - kcout << "Checking for extension...\r"; - - /// a directory should have a slash in the end. - if (kind == kNeFSCatalogKindDir && - name[rt_string_len(name) - 1] != NeFileSystemHelper::Separator()) - return nullptr; - - /// a file shouldn't have a slash in the end. - if (kind != kNeFSCatalogKindDir && - name[rt_string_len(name) - 1] == NeFileSystemHelper::Separator()) - return nullptr; - - NFS_CATALOG_STRUCT* catalog_copy = this->FindCatalog(name, out_lba); - - if (catalog_copy) - { - kcout << "Catalog already exists: " << name << ".\r"; - ErrLocal() = kErrorFileExists; - - return catalog_copy; - } - - Char parentName[kNeFSNodeNameLen] = {0}; - - for (SizeT indexName = 0UL; indexName < rt_string_len(name); ++indexName) - { - parentName[indexName] = name[indexName]; - } - - if (*parentName == 0) - { - kcout << "Parent name is NUL.\r"; - ErrLocal() = kErrorFileNotFound; - return nullptr; - } - - /// Locate parent catalog, to then allocate right after it. - - for (SizeT indexFill = 0; indexFill < rt_string_len(name); ++indexFill) - { - parentName[indexFill] = name[indexFill]; - } - - SizeT indexReverseCopy = rt_string_len(parentName); - - // zero character it. - parentName[--indexReverseCopy] = 0; - - // mandatory / character, zero it. - parentName[--indexReverseCopy] = 0; - - while (parentName[indexReverseCopy] != NeFileSystemHelper::Separator()) - { - parentName[indexReverseCopy] = 0; - --indexReverseCopy; - } - - NFS_CATALOG_STRUCT* catalog = this->FindCatalog(parentName, out_lba); - - auto drive = sMountpointInterface.A(); - - if (catalog && catalog->Kind == kNeFSCatalogKindFile) - { - kcout << "Parent name is file.\r"; - delete catalog; - return nullptr; - } - else if (!catalog) - { - Char sectorBufPartBlock[kNeFSSectorSz] = {0}; - - drive.fPacket.fPacketContent = sectorBufPartBlock; - drive.fPacket.fPacketSize = kNeFSSectorSz; - drive.fPacket.fLba = kNeFSRootCatalogStartAddress; - - drive.fInput(&drive.fPacket); - - constexpr auto cNeFSCatalogPadding = 4; - - NFS_ROOT_PARTITION_BLOCK* part_block = (NFS_ROOT_PARTITION_BLOCK*)sectorBufPartBlock; - out_lba = part_block->StartCatalog; - } - - constexpr SizeT cDefaultForkSize = kNeFSForkSize; - - NFS_CATALOG_STRUCT* child_catalog = new NFS_CATALOG_STRUCT(); - - Int32 flagsList = flags; - - child_catalog->ResourceForkSize = cDefaultForkSize; - child_catalog->DataForkSize = cDefaultForkSize; - - child_catalog->NextSibling = out_lba; - child_catalog->PrevSibling = out_lba; - child_catalog->Kind = kind; - child_catalog->Flags = kNeFSFlagCreated | flagsList; - - rt_copy_memory((VoidPtr)name, (VoidPtr)child_catalog->Name, - rt_string_len(name)); - - NFS_CATALOG_STRUCT temporary_catalog; - - Lba start_free = out_lba; - - rt_copy_memory((VoidPtr) "fs/nefs-packet", drive.fPacket.fPacketMime, - rt_string_len("fs/nefs-packet")); - - drive.fPacket.fPacketContent = &temporary_catalog; - drive.fPacket.fPacketSize = kNeFSSectorSz; - drive.fPacket.fLba = start_free; - - drive.fInput(&drive.fPacket); - - NFS_CATALOG_STRUCT* next_sibling = reinterpret_cast(&temporary_catalog); - - start_free = next_sibling->NextSibling; - - child_catalog->PrevSibling = out_lba; - - drive.fPacket.fLba = start_free; - drive.fInput(&drive.fPacket); - - while (drive.fPacket.fPacketGood) - { - next_sibling = reinterpret_cast(&temporary_catalog); - - if (start_free <= kNeFSRootCatalogStartAddress) - { - delete child_catalog; - delete catalog; - - return nullptr; - } - - // ========================== // - // Allocate catalog now... - // ========================== // - if ((next_sibling->Flags & kNeFSFlagCreated) == 0) - { - Char sectorBufPartBlock[kNeFSSectorSz] = {0}; - - drive.fPacket.fPacketContent = sectorBufPartBlock; - drive.fPacket.fPacketSize = kNeFSSectorSz; - drive.fPacket.fLba = kNeFSRootCatalogStartAddress; - - drive.fInput(&drive.fPacket); - - constexpr auto cNeFSCatalogPadding = 4; - - NFS_ROOT_PARTITION_BLOCK* part_block = (NFS_ROOT_PARTITION_BLOCK*)sectorBufPartBlock; - - if (part_block->FreeCatalog < 1) - { - delete child_catalog; - return nullptr; - } - - child_catalog->DataFork = part_block->DiskSize - start_free; - child_catalog->ResourceFork = child_catalog->DataFork; - - // Write the new catalog next sibling, if we don't know this parent. // - // This is necessary, so that we don't have to get another lba to allocate. // - if (!StringBuilder::Equals(parentName, next_sibling->Name)) - { - child_catalog->NextSibling = - start_free + (sizeof(NFS_CATALOG_STRUCT) * cNeFSCatalogPadding); - } - - drive.fPacket.fPacketContent = child_catalog; - drive.fPacket.fPacketSize = sizeof(NFS_CATALOG_STRUCT); - drive.fPacket.fLba = start_free; - - drive.fOutput(&drive.fPacket); - - // Get NeFS partition's block. - - drive.fPacket.fPacketContent = sectorBufPartBlock; - drive.fPacket.fPacketSize = kNeFSSectorSz; - drive.fPacket.fLba = kNeFSRootCatalogStartAddress; - - drive.fInput(&drive.fPacket); - - part_block->FreeSectors -= 1; - part_block->CatalogCount += 1; - part_block->FreeCatalog -= 1; - - drive.fOutput(&drive.fPacket); - - kcout << "Create new catalog, status: " - << hex_number(child_catalog->Flags) << endl; - kcout << "Create new catalog, name: " << child_catalog->Name - << endl; - - delete catalog; - return child_catalog; - } - else if ((next_sibling->Flags & kNeFSFlagCreated) && - StringBuilder::Equals(next_sibling->Name, name)) - { - return next_sibling; - } - - constexpr auto cNeFSCatalogPadding = 4; - - //// @note that's how we find the next catalog in the partition block. - start_free = start_free + (sizeof(NFS_CATALOG_STRUCT) * cNeFSCatalogPadding); - - drive.fPacket.fPacketContent = &temporary_catalog; - drive.fPacket.fPacketSize = kNeFSSectorSz; - drive.fPacket.fLba = start_free; - - drive.fInput(&drive.fPacket); - } - - delete catalog; - return nullptr; -} - -/// @brief Make a EPM+NeFS drive out of the disk. -/// @param drive The drive to write on. -/// @return If it was sucessful, see ErrLocal(). -bool NeFSParser::Format(_Input _Output DriveTrait* drive, _Input const Lba endLba, _Input const Int32 flags, const Char* part_name) -{ - if (*part_name == 0 || - endLba == 0) - return false; - - // verify disk. - drive->fVerify(&drive->fPacket); - - rt_copy_memory((VoidPtr) "fs/nefs-packet", drive->fPacket.fPacketMime, - rt_string_len("fs/nefs-packet")); - - // if disk isn't good, then error out. - if (false == drive->fPacket.fPacketGood) - { - ErrLocal() = kErrorDiskIsCorrupted; - return false; - } - - Char fs_buf[kNeFSSectorSz] = {0}; - - Lba start = kNeFSRootCatalogStartAddress; - - drive->fPacket.fPacketContent = fs_buf; - drive->fPacket.fPacketSize = kNeFSSectorSz; - drive->fPacket.fLba = start; - - drive->fInput(&drive->fPacket); - - if (flags & kNeFSPartitionTypeBoot) - { - // make it bootable when needed. - Char bufEpmHdr[kNeFSSectorSz] = {0}; - - BOOT_BLOCK_STRUCT* epmBoot = (BOOT_BLOCK_STRUCT*)bufEpmHdr; - - // EPM header. - - constexpr auto cFsName = "NeFS"; - constexpr auto cBlockName = "ZKA:"; - - rt_copy_memory(reinterpret_cast(const_cast(cFsName)), epmBoot->Fs, rt_string_len(cFsName)); - - epmBoot->FsVersion = kNeFSVersionInteger; - epmBoot->LbaStart = start; - epmBoot->SectorSz = kNeFSSectorSz; - - rt_copy_memory(reinterpret_cast(const_cast(cBlockName)), epmBoot->Name, rt_string_len(cBlockName)); - rt_copy_memory(reinterpret_cast(const_cast(kEPMMagic)), epmBoot->Magic, rt_string_len(kEPMMagic)); - - Lba outEpmLba = kEpmBase; - - Char buf[kNeFSSectorSz]; - - Lba prevStart = 0; - SizeT cnt = 0; - - while (drive->fPacket.fPacketGood) - { - drive->fPacket.fPacketContent = buf; - drive->fPacket.fPacketSize = kNeFSSectorSz; - drive->fPacket.fLba = outEpmLba; - - drive->fInput(&drive->fPacket); - - if (buf[0] == 0) - { - epmBoot->LbaStart = prevStart; - - if (epmBoot->LbaStart) - epmBoot->LbaStart = outEpmLba; - - epmBoot->LbaEnd = endLba; - epmBoot->NumBlocks = cnt; - - drive->fPacket.fPacketContent = bufEpmHdr; - drive->fPacket.fPacketSize = kNeFSSectorSz; - drive->fPacket.fLba = outEpmLba; - - drive->fOutput(&drive->fPacket); - - break; - } - else - { - prevStart = ((BOOT_BLOCK_STRUCT*)buf)->LbaStart + ((BOOT_BLOCK_STRUCT*)buf)->LbaEnd; - } - - outEpmLba += sizeof(BOOT_BLOCK_STRUCT); - ++cnt; - } - } - - // disk isnt faulty and data has been fetched. - while (drive->fPacket.fPacketGood) - { - NFS_ROOT_PARTITION_BLOCK* part_block = (NFS_ROOT_PARTITION_BLOCK*)fs_buf; - - // check for an empty partition here. - if (part_block->PartitionName[0] == 0 && - rt_string_cmp(part_block->Ident, kNeFSIdent, kNeFSIdentLen)) - { - // partition is free and valid. - - part_block->Version = kNeFSVersionInteger; - - const auto cUntitledHD = part_name; - - rt_copy_memory((VoidPtr)kNeFSIdent, (VoidPtr)part_block->Ident, - kNeFSIdentLen); - - rt_copy_memory((VoidPtr)cUntitledHD, (VoidPtr)part_block->PartitionName, - rt_string_len(cUntitledHD)); - - SizeT catalogCount = 0UL; - - SizeT sectorCount = drv_get_sector_count(); - SizeT diskSize = drv_get_size(); - - part_block->Kind = kNeFSPartitionTypeStandard; - part_block->StartCatalog = kNeFSCatalogStartAddress; - part_block->Flags = kNeFSPartitionTypeStandard; - part_block->CatalogCount = sectorCount / sizeof(NFS_CATALOG_STRUCT); - part_block->SectorCount = sectorCount; - part_block->DiskSize = diskSize; - part_block->FreeCatalog = sectorCount / sizeof(NFS_CATALOG_STRUCT); - - drive->fPacket.fPacketContent = fs_buf; - drive->fPacket.fPacketSize = kNeFSSectorSz; - drive->fPacket.fLba = kNeFSRootCatalogStartAddress; - - drive->fOutput(&drive->fPacket); - - kcout << "drive kind: " << drive->fDriveKind() << endl; - - kcout << "partition name: " << part_block->PartitionName << endl; - kcout << "start: " << hex_number(part_block->StartCatalog) << endl; - kcout << "number of catalogs: " << hex_number(part_block->CatalogCount) << endl; - kcout << "free catalog: " << hex_number(part_block->FreeCatalog) << endl; - kcout << "free sectors: " << hex_number(part_block->FreeSectors) << endl; - kcout << "sector size: " << hex_number(part_block->SectorSize) << endl; - - // write the root catalog. - this->CreateCatalog(kNeFSRoot, 0, kNeFSCatalogKindDir); - - return true; - } - - kcout << "partition block already exists.\r"; - - start += part_block->DiskSize; - - drive->fPacket.fPacketContent = fs_buf; - drive->fPacket.fPacketSize = kNeFSSectorSz; - drive->fPacket.fLba = start; - - drive->fInput(&drive->fPacket); - } - - return false; -} - -/// @brief Writes the data fork into a specific catalog. -/// @param catalog the catalog itself -/// @param data the data. -/// @return if the catalog w rote the contents successfully. -bool NeFSParser::WriteCatalog(_Input _Output NFS_CATALOG_STRUCT* catalog, Bool is_rsrc_fork, _Input VoidPtr data, _Input SizeT size_of_data, _Input const Char* forkName) -{ - if (size_of_data > kNeFSForkDataSz || - size_of_data == 0) - return No; - - auto buf = new UInt8[kNeFSForkDataSz]; - rt_set_memory(buf, 0, kNeFSForkDataSz); - - rt_copy_memory(data, buf, size_of_data); - - auto drive = sMountpointInterface.A(); - - rt_copy_memory((VoidPtr) "fs/nefs-packet", drive.fPacket.fPacketMime, - rt_string_len("fs/nefs-packet")); - - auto startFork = (!is_rsrc_fork) ? catalog->DataFork - : catalog->ResourceFork; - - NFS_FORK_STRUCT* fork_data_input = new NFS_FORK_STRUCT(); - NFS_FORK_STRUCT prevFork{}; - - // sanity check of the fork position as the condition to run the loop. - while (startFork >= kNeFSCatalogStartAddress) - { - drive.fPacket.fPacketContent = fork_data_input; - drive.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); - drive.fPacket.fLba = startFork; - - drive.fInput(&drive.fPacket); - - // check the fork, if it's position is valid. - if (fork_data_input->DataOffset <= kNeFSCatalogStartAddress) - { - ErrLocal() = kErrorDiskIsCorrupted; - - kcout << "Invalid fork offset.\r"; - - return false; - } - - if (fork_data_input->Flags != kNeFSFlagUnallocated && - fork_data_input->Flags != kNeFSFlagDeleted && - StringBuilder::Equals(fork_data_input->ForkName, forkName) && - StringBuilder::Equals(fork_data_input->CatalogName, catalog->Name) && - fork_data_input->DataSize == size_of_data) - { - // ===================================================== // - // Store the blob now. - // ===================================================== // - - fork_data_input->Flags |= kNeFSFlagCreated; - - drive.fPacket.fPacketContent = buf; - drive.fPacket.fPacketSize = kNeFSForkDataSz; - drive.fPacket.fLba = fork_data_input->DataOffset; - - kcout << "data offset: " << hex_number(fork_data_input->DataOffset) << endl; - - drive.fOutput(&drive.fPacket); - - drive.fPacket.fPacketContent = fork_data_input; - drive.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); - drive.fPacket.fLba = startFork - sizeof(NFS_FORK_STRUCT); - - drive.fOutput(&drive.fPacket); - - kcout << "wrote fork at offset: " << hex_number(fork_data_input->DataOffset) << endl; - kcout << "wrote fork at offset: " << hex_number(startFork - sizeof(NFS_FORK_STRUCT)) << endl; - - delete catalog; - - return true; - } - - // stumble upon a fork, store it. - - prevFork = *fork_data_input; - - startFork = fork_data_input->NextSibling; - } - - return false; -} - -/// @brief -/// @param catalogName the catalog name. -/// @return the newly found catalog. -_Output NFS_CATALOG_STRUCT* NeFSParser::FindCatalog(_Input const Char* catalogName, - Lba& out_lba) -{ - kcout << "Start finding catalog...\r"; - - NFS_ROOT_PARTITION_BLOCK fs_buf{0}; - auto drive = sMountpointInterface.A(); - - rt_copy_memory((VoidPtr) "fs/nefs-packet", drive.fPacket.fPacketMime, - rt_string_len("fs/nefs-packet")); - - drive.fPacket.fPacketContent = &fs_buf; - drive.fPacket.fPacketSize = sizeof(NFS_ROOT_PARTITION_BLOCK); - drive.fPacket.fLba = kNeFSRootCatalogStartAddress; - - drive.fInput(&drive.fPacket); - - NFS_ROOT_PARTITION_BLOCK* part = (NFS_ROOT_PARTITION_BLOCK*)&fs_buf; - - auto startCatalogList = part->StartCatalog; - const auto cCtartCatalogList = startCatalogList; - - auto localSearchFirst = false; - - NFS_CATALOG_STRUCT temporary_catalog{0}; - - drive.fPacket.fLba = startCatalogList; - drive.fPacket.fPacketContent = &temporary_catalog; - drive.fPacket.fPacketSize = sizeof(NFS_CATALOG_STRUCT); - - drive.fInput(&drive.fPacket); - - if (!StringBuilder::Equals(catalogName, NeFileSystemHelper::Root())) - { - Char parentName[kNeFSNodeNameLen] = {0}; - - for (SizeT indexFill = 0; indexFill < rt_string_len(catalogName); ++indexFill) - { - parentName[indexFill] = catalogName[indexFill]; - } - - SizeT indexReverseCopy = rt_string_len(parentName); - - // zero character. - parentName[--indexReverseCopy] = 0; - - // mandatory '/' character. - parentName[--indexReverseCopy] = 0; - - while (parentName[indexReverseCopy] != NeFileSystemHelper::Separator()) - { - parentName[indexReverseCopy] = 0; - --indexReverseCopy; - } - - NFS_CATALOG_STRUCT* parentCatalog = this->FindCatalog(parentName, out_lba); - - if (parentCatalog && - !StringBuilder::Equals(parentName, NeFileSystemHelper::Root())) - { - startCatalogList = parentCatalog->NextSibling; - delete parentCatalog; - - localSearchFirst = true; - } - else if (parentCatalog) - { - delete parentCatalog; - } - else - { - return nullptr; - } - } - - kcout << "Fetching catalog...\r"; - -NeFSSearchThroughCatalogList: - while (drive.fPacket.fPacketGood) - { - drive.fPacket.fLba = startCatalogList; - drive.fPacket.fPacketContent = &temporary_catalog; - drive.fPacket.fPacketSize = sizeof(NFS_CATALOG_STRUCT); - - drive.fInput(&drive.fPacket); - - NFS_CATALOG_STRUCT* catalog = (NFS_CATALOG_STRUCT*)&temporary_catalog; - - if (StringBuilder::Equals(catalogName, catalog->Name)) - { - /// ignore unallocated catalog, break - if (!(catalog->Flags & kNeFSFlagCreated)) - { - goto NeFSContinueSearch; - } - - NFS_CATALOG_STRUCT* catalogPtr = new NFS_CATALOG_STRUCT(); - rt_copy_memory(catalog, catalogPtr, sizeof(NFS_CATALOG_STRUCT)); - - kcout << "Found catalog at: " << hex_number(startCatalogList) << endl; - kcout << "Found catalog at: " << catalog->Name << endl; - - out_lba = startCatalogList; - return catalogPtr; - } - - NeFSContinueSearch: - startCatalogList = catalog->NextSibling; - - if (startCatalogList <= kNeFSRootCatalogStartAddress) - break; - } - - if (localSearchFirst) - { - localSearchFirst = false; - startCatalogList = cCtartCatalogList; - - goto NeFSSearchThroughCatalogList; - } - - out_lba = 0UL; - return nullptr; -} - -/// @brief Get catalog from filesystem. -/// @param name the catalog's name/ -/// @return -_Output NFS_CATALOG_STRUCT* NeFSParser::GetCatalog(_Input const Char* name) -{ - Lba unused = 0; - return this->FindCatalog(name, unused); -} - -/// @brief Closes a catalog, (frees it). -/// @param catalog the catalog to close. -/// @return -Boolean NeFSParser::CloseCatalog(_Input _Output NFS_CATALOG_STRUCT* catalog) -{ - if (!catalog) - return false; - - delete catalog; - catalog = nullptr; - - return true; -} - -/// @brief Mark catalog as removed. -/// @param catalog The catalog structure. -/// @return if the catalog was removed or not. -Boolean NeFSParser::RemoveCatalog(_Input const Char* catalogName) -{ - if (!catalogName || - StringBuilder::Equals(catalogName, NeFileSystemHelper::Root())) - { - ErrLocal() = kErrorInternal; - return false; - } - - Lba out_lba = 0; - auto catalog = this->FindCatalog(catalogName, out_lba); - - if (out_lba >= kNeFSCatalogStartAddress || - catalog->Flags & kNeFSFlagCreated) - { - catalog->Flags |= kNeFSFlagDeleted; - - auto drive = sMountpointInterface.A(); - - rt_copy_memory((VoidPtr) "fs/nefs-packet", drive.fPacket.fPacketMime, - rt_string_len("fs/nefs-packet")); - - drive.fPacket.fLba = out_lba; // the catalog position. - drive.fPacket.fPacketSize = - sizeof(NFS_CATALOG_STRUCT); // size of catalog. roughly the sector size. - drive.fPacket.fPacketContent = catalog; // the catalog itself. - - drive.fOutput(&drive.fPacket); // send packet. - - Char partitionBlockBuf[sizeof(NFS_ROOT_PARTITION_BLOCK)] = {0}; - - drive.fPacket.fLba = kNeFSRootCatalogStartAddress; - drive.fPacket.fPacketContent = partitionBlockBuf; - drive.fPacket.fPacketSize = sizeof(NFS_ROOT_PARTITION_BLOCK); - - drive.fInput(&drive.fPacket); - - NFS_ROOT_PARTITION_BLOCK* part_block = - reinterpret_cast(partitionBlockBuf); - - --part_block->CatalogCount; - ++part_block->FreeSectors; - - drive.fOutput(&drive.fPacket); - - return true; - } - - delete catalog; - return false; -} - -/// ***************************************************************** /// -/// Reading,Seek,Tell are unimplemented on catalogs, refer to forks I/O instead. -/// ***************************************************************** /// - -/***********************************************************************************/ -/// @brief Read the catalog data fork. -/// @param catalog -/// @param dataSz -/// @return -/***********************************************************************************/ - -VoidPtr NeFSParser::ReadCatalog(_Input _Output NFS_CATALOG_STRUCT* catalog, - _Input Bool is_rsrc_fork, - _Input SizeT dataSz, - _Input const Char* forkName) -{ - if (!catalog) - { - ErrLocal() = kErrorFileNotFound; - return nullptr; - } - - constexpr auto cNeFSCatalogPadding = 4; - - Lba dataForkLba = (!is_rsrc_fork) ? catalog->DataFork : catalog->ResourceFork; - Size dataForkSize = (!is_rsrc_fork) ? catalog->DataForkSize : catalog->ResourceForkSize; - - kcout << "catalog " << catalog->Name - << ", fork: " << hex_number(dataForkLba) << endl; - - NFS_FORK_STRUCT* fs_buf = new NFS_FORK_STRUCT(); - auto drive = sMountpointInterface.A(); - - rt_copy_memory((VoidPtr) "fs/nefs-packet", drive.fPacket.fPacketMime, - rt_string_len("fs/nefs-packet")); - - NFS_FORK_STRUCT* fs_fork_data = nullptr; - - while (dataForkLba > kNeFSCatalogStartAddress) - { - drive.fPacket.fLba = dataForkLba; - drive.fPacket.fPacketSize = sizeof(NFS_FORK_STRUCT); - drive.fPacket.fPacketContent = fs_buf; - - drive.fInput(&drive.fPacket); - - fs_fork_data = fs_buf; - - kcout << "ForkName: " << fs_fork_data->ForkName << endl; - kcout << "CatalogName: " << fs_fork_data->CatalogName << endl; - - if (StringBuilder::Equals(forkName, fs_fork_data->ForkName) && - StringBuilder::Equals(catalog->Name, fs_fork_data->CatalogName)) - break; - - dataForkLba = fs_fork_data->NextSibling; - } - - if (dataForkLba < kNeFSCatalogStartAddress) - { - delete fs_buf; - return nullptr; - } - - return fs_fork_data; -} - -/***********************************************************************************/ -/// @brief Seek in the data fork. -/// @param catalog the catalog offset. -/// @param off where to seek. -/// @return if the seeking was successful. -/***********************************************************************************/ - -bool NeFSParser::Seek(_Input _Output NFS_CATALOG_STRUCT* catalog, SizeT off) -{ - if (!catalog) - { - ErrLocal() = kErrorFileNotFound; - return false; - } - - ErrLocal() = kErrorUnimplemented; - return false; -} - -/***********************************************************************************/ -/// @brief Tell where we are inside the data fork. -/// @param catalog -/// @return The position on the file. -/***********************************************************************************/ - -SizeT NeFSParser::Tell(_Input _Output NFS_CATALOG_STRUCT* catalog) -{ - if (!catalog) - { - ErrLocal() = kErrorFileNotFound; - return 0; - } - - ErrLocal() = kErrorUnimplemented; - return 0; -} - -namespace Kernel::Detail -{ - /***********************************************************************************/ - /// @brief Construct NeFS drives. - /***********************************************************************************/ - Boolean fs_init_newfs(Void) noexcept - { - kcout << "Creating drives...\r"; - - sMountpointInterface.A() = io_construct_main_drive(); - sMountpointInterface.B() = io_construct_drive(); - sMountpointInterface.C() = io_construct_drive(); - sMountpointInterface.D() = io_construct_drive(); - - kcout << "Constructing A:\r"; - - sMountpointInterface.A().fInit(&sMountpointInterface.A().fPacket); - - kcout << "Constructing A: [ OK ]\r"; - - return true; - } -} // namespace Kernel::Detail -#endif // !__ZKA_MINIMAL_OS__ - -#endif // ifdef __FSKIT_USE_NEFS__ diff --git a/dev/zka/src/FileMgr.cc b/dev/zka/src/FileMgr.cc new file mode 100644 index 00000000..c9591bf0 --- /dev/null +++ b/dev/zka/src/FileMgr.cc @@ -0,0 +1,52 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +/// BUGS: 0 +//! @brief File System Manager API. + +namespace Kernel +{ + STATIC IFilesystemMgr* kMountedFilesystem = nullptr; + + /// @brief FilesystemMgr getter. + /// @return The mounted filesystem. + _Output IFilesystemMgr* IFilesystemMgr::GetMounted() + { + return kMountedFilesystem; + } + + /// @brief Unmount filesystem. + /// @return The unmounted filesystem. + _Output IFilesystemMgr* IFilesystemMgr::Unmount() + { + if (kMountedFilesystem) + { + auto mount = kMountedFilesystem; + kMountedFilesystem = nullptr; + + return mount; + } + + return nullptr; + } + + /// @brief Mount filesystem. + /// @param mount_ptr The filesystem to mount. + /// @return if it succeeded true, otherwise false. + bool IFilesystemMgr::Mount(_Input IFilesystemMgr* mount_ptr) + { + if (mount_ptr != nullptr) + { + kMountedFilesystem = mount_ptr; + return true; + } + + return false; + } +} // namespace Kernel diff --git a/dev/zka/src/FileMgr.cxx b/dev/zka/src/FileMgr.cxx deleted file mode 100644 index fc51683f..00000000 --- a/dev/zka/src/FileMgr.cxx +++ /dev/null @@ -1,52 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -/// BUGS: 0 -//! @brief File System Manager API. - -namespace Kernel -{ - STATIC IFilesystemMgr* kMountedFilesystem = nullptr; - - /// @brief FilesystemMgr getter. - /// @return The mounted filesystem. - _Output IFilesystemMgr* IFilesystemMgr::GetMounted() - { - return kMountedFilesystem; - } - - /// @brief Unmount filesystem. - /// @return The unmounted filesystem. - _Output IFilesystemMgr* IFilesystemMgr::Unmount() - { - if (kMountedFilesystem) - { - auto mount = kMountedFilesystem; - kMountedFilesystem = nullptr; - - return mount; - } - - return nullptr; - } - - /// @brief Mount filesystem. - /// @param mount_ptr The filesystem to mount. - /// @return if it succeeded true, otherwise false. - bool IFilesystemMgr::Mount(_Input IFilesystemMgr* mount_ptr) - { - if (mount_ptr != nullptr) - { - kMountedFilesystem = mount_ptr; - return true; - } - - return false; - } -} // namespace Kernel diff --git a/dev/zka/src/GUIDWizard.cc b/dev/zka/src/GUIDWizard.cc new file mode 100644 index 00000000..77635979 --- /dev/null +++ b/dev/zka/src/GUIDWizard.cc @@ -0,0 +1,72 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: GUIDWizard.cxx + Purpose: GUID helper code + + Revision History: + +------------------------------------------- */ + +#include +#include + +// begin of ascii 'readable' characters. (A, C, C, 1, 2) +#define kAsciiBegin 47 +// @brief Size of UUID. +#define kUUIDSize 37 + +namespace Kernel::XRN::Version1 +{ + auto cf_make_sequence(const ArrayList& uuidSeq) -> Ref + { + GUIDSequence* seq = new GUIDSequence(); + MUST_PASS(seq); + + Ref seq_ref{*seq}; + + seq_ref.Leak().fMs1 = uuidSeq[0]; + seq_ref.Leak().fMs2 = uuidSeq[1]; + seq_ref.Leak().fMs3 = uuidSeq[2]; + seq_ref.Leak().fMs4[0] = uuidSeq[3]; + seq_ref.Leak().fMs4[1] = uuidSeq[4]; + seq_ref.Leak().fMs4[2] = uuidSeq[5]; + seq_ref.Leak().fMs4[3] = uuidSeq[6]; + seq_ref.Leak().fMs4[4] = uuidSeq[7]; + seq_ref.Leak().fMs4[5] = uuidSeq[8]; + seq_ref.Leak().fMs4[6] = uuidSeq[9]; + seq_ref.Leak().fMs4[7] = uuidSeq[10]; + + return seq_ref; + } + + // @brief Tries to make a guid out of a string. + // This function is not complete for now + auto cf_try_guid_to_string(Ref& seq) -> ErrorOr> + { + Char buf[kUUIDSize]; + + for (SizeT index = 0; index < 16; ++index) + { + buf[index] = seq.Leak().u8[index] + kAsciiBegin; + } + + for (SizeT index = 16; index < 24; ++index) + { + buf[index] = seq.Leak().u16[index] + kAsciiBegin; + } + + for (SizeT index = 24; index < 28; ++index) + { + buf[index] = seq.Leak().u32[index] + kAsciiBegin; + } + + auto view = StringBuilder::Construct(buf); + + if (view) + return ErrorOr>{view.Leak()}; + + return ErrorOr>{-1}; + } +} // namespace Kernel::XRN::Version1 diff --git a/dev/zka/src/GUIDWizard.cxx b/dev/zka/src/GUIDWizard.cxx deleted file mode 100644 index a9094215..00000000 --- a/dev/zka/src/GUIDWizard.cxx +++ /dev/null @@ -1,72 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: GUIDWizard.cxx - Purpose: GUID helper code - - Revision History: - -------------------------------------------- */ - -#include -#include - -// begin of ascii 'readable' characters. (A, C, C, 1, 2) -#define kAsciiBegin 47 -// @brief Size of UUID. -#define kUUIDSize 37 - -namespace Kernel::XRN::Version1 -{ - auto cf_make_sequence(const ArrayList& uuidSeq) -> Ref - { - GUIDSequence* seq = new GUIDSequence(); - MUST_PASS(seq); - - Ref seq_ref{*seq}; - - seq_ref.Leak().fMs1 = uuidSeq[0]; - seq_ref.Leak().fMs2 = uuidSeq[1]; - seq_ref.Leak().fMs3 = uuidSeq[2]; - seq_ref.Leak().fMs4[0] = uuidSeq[3]; - seq_ref.Leak().fMs4[1] = uuidSeq[4]; - seq_ref.Leak().fMs4[2] = uuidSeq[5]; - seq_ref.Leak().fMs4[3] = uuidSeq[6]; - seq_ref.Leak().fMs4[4] = uuidSeq[7]; - seq_ref.Leak().fMs4[5] = uuidSeq[8]; - seq_ref.Leak().fMs4[6] = uuidSeq[9]; - seq_ref.Leak().fMs4[7] = uuidSeq[10]; - - return seq_ref; - } - - // @brief Tries to make a guid out of a string. - // This function is not complete for now - auto cf_try_guid_to_string(Ref& seq) -> ErrorOr> - { - Char buf[kUUIDSize]; - - for (SizeT index = 0; index < 16; ++index) - { - buf[index] = seq.Leak().u8[index] + kAsciiBegin; - } - - for (SizeT index = 16; index < 24; ++index) - { - buf[index] = seq.Leak().u16[index] + kAsciiBegin; - } - - for (SizeT index = 24; index < 28; ++index) - { - buf[index] = seq.Leak().u32[index] + kAsciiBegin; - } - - auto view = StringBuilder::Construct(buf); - - if (view) - return ErrorOr>{view.Leak()}; - - return ErrorOr>{-1}; - } -} // namespace Kernel::XRN::Version1 diff --git a/dev/zka/src/GUIDWrapper.cc b/dev/zka/src/GUIDWrapper.cc new file mode 100644 index 00000000..53d983a1 --- /dev/null +++ b/dev/zka/src/GUIDWrapper.cc @@ -0,0 +1,11 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +namespace Kernel::XRN +{ +} diff --git a/dev/zka/src/GUIDWrapper.cxx b/dev/zka/src/GUIDWrapper.cxx deleted file mode 100644 index 1c0eb5ef..00000000 --- a/dev/zka/src/GUIDWrapper.cxx +++ /dev/null @@ -1,11 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -namespace Kernel::XRN -{ -} diff --git a/dev/zka/src/HardwareThreadScheduler.cc b/dev/zka/src/HardwareThreadScheduler.cc new file mode 100644 index 00000000..37d81f04 --- /dev/null +++ b/dev/zka/src/HardwareThreadScheduler.cc @@ -0,0 +1,193 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include +#include + +///! BUGS: 0 + +///! @file MP.cxx +///! @brief This file handles multi processing in the Kernel. +///! @brief Multi processing is needed for multi-tasking operations. + +namespace Kernel +{ + HardwareThreadScheduler* kHardwareThreadScheduler = nullptr; + + ///! A HardwareThread class takes care of it's owned hardware thread. + ///! It has a stack for it's core. + + ///! @brief C++ constructor. + HardwareThread::HardwareThread() = default; + + ///! @brief C++ destructor. + HardwareThread::~HardwareThread() = default; + + //! @brief returns the id of the thread. + const ThreadID& HardwareThread::ID() noexcept + { + return fID; + } + + //! @brief returns the kind of thread we have. + const ThreadKind& HardwareThread::Kind() noexcept + { + return fKind; + } + + //! @brief is the thread busy? + Bool HardwareThread::IsBusy() noexcept + { + STATIC Int64 busy_timer = 0U; + + if (busy_timer > this->fPTime) + { + busy_timer = 0U; + fBusy = No; + } + + return fBusy; + } + + /// @brief Get processor stack frame. + + HAL::StackFramePtr HardwareThread::StackFrame() noexcept + { + MUST_PASS(fStack); + return fStack; + } + + Void HardwareThread::Busy(const Bool busy) noexcept + { + fBusy = busy; + } + + HardwareThread::operator bool() + { + return fStack; + } + + /// @brief Wakeup the processor. + + Void HardwareThread::Wake(const bool wakeup) noexcept + { + fWakeup = wakeup; + + if (!fWakeup) + mp_hang_thread(fStack); + else + mp_wakeup_thread(fStack); + } + + /// @note Those symbols are needed in order to switch and validate the stack. + + EXTERN Bool hal_check_stack(HAL::StackFramePtr stackPtr); + EXTERN_C Bool mp_register_process(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr frame_ptr); + + /// @brief Switch to hardware thread. + /// @param stack the new hardware thread. + /// @retval true stack was changed, code is running. + /// @retval false stack is invalid, previous code is running. + Bool HardwareThread::Switch(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr frame) + { + if (!frame || + !image || + !stack_ptr) + return No; + + if (!this->IsWakeup()) + return No; + + if (this->IsBusy()) + return No; + + fStack = frame; + + Bool ret = mp_register_process(image, stack_ptr, fStack); + + if (ret) + this->Busy(true); + + return ret; + } + + ///! @brief Tells if processor is waked up. + bool HardwareThread::IsWakeup() noexcept + { + return fWakeup; + } + + ///! @brief Constructor and destructors. + + ///! @brief Default constructor. + HardwareThreadScheduler::HardwareThreadScheduler() = default; + + ///! @brief Default destructor. + HardwareThreadScheduler::~HardwareThreadScheduler() = default; + + /// @brief Shared singleton function + HardwareThreadScheduler& HardwareThreadScheduler::The() + { + MUST_PASS(kHardwareThreadScheduler); + return *kHardwareThreadScheduler; + } + + /// @brief Get Stack Frame of Core + HAL::StackFramePtr HardwareThreadScheduler::Leak() noexcept + { + return fThreadList[fCurrentThread].fStack; + } + + /** + * Get Hardware thread at index. + * @param idx the index + * @return the reference to the hardware thread. + */ + Ref HardwareThreadScheduler::operator[](const SizeT& idx) + { + if (idx == 0) + { + if (fThreadList[idx].Kind() != kHartSystemReserved) + { + fThreadList[idx].fKind = kHartBoot; + } + } + else if (idx >= cMaxHartInsideSched) + { + static HardwareThread* fakeThread = nullptr; + return {fakeThread}; + } + + return &fThreadList[idx]; + } + + /** + * Check if thread pool isn't empty. + * @return + */ + HardwareThreadScheduler::operator bool() noexcept + { + return !fThreadList.Empty(); + } + + /** + * Reverse operator bool + * @return + */ + bool HardwareThreadScheduler::operator!() noexcept + { + return fThreadList.Empty(); + } + + /// @brief Returns the amount of core present. + /// @return the number of cores. + SizeT HardwareThreadScheduler::Count() noexcept + { + return fThreadList.Capacity(); + } +} // namespace Kernel diff --git a/dev/zka/src/HardwareThreadScheduler.cxx b/dev/zka/src/HardwareThreadScheduler.cxx deleted file mode 100644 index 50a153f1..00000000 --- a/dev/zka/src/HardwareThreadScheduler.cxx +++ /dev/null @@ -1,193 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include -#include - -///! BUGS: 0 - -///! @file MP.cxx -///! @brief This file handles multi processing in the Kernel. -///! @brief Multi processing is needed for multi-tasking operations. - -namespace Kernel -{ - HardwareThreadScheduler* kHardwareThreadScheduler = nullptr; - - ///! A HardwareThread class takes care of it's owned hardware thread. - ///! It has a stack for it's core. - - ///! @brief C++ constructor. - HardwareThread::HardwareThread() = default; - - ///! @brief C++ destructor. - HardwareThread::~HardwareThread() = default; - - //! @brief returns the id of the thread. - const ThreadID& HardwareThread::ID() noexcept - { - return fID; - } - - //! @brief returns the kind of thread we have. - const ThreadKind& HardwareThread::Kind() noexcept - { - return fKind; - } - - //! @brief is the thread busy? - Bool HardwareThread::IsBusy() noexcept - { - STATIC Int64 busy_timer = 0U; - - if (busy_timer > this->fPTime) - { - busy_timer = 0U; - fBusy = No; - } - - return fBusy; - } - - /// @brief Get processor stack frame. - - HAL::StackFramePtr HardwareThread::StackFrame() noexcept - { - MUST_PASS(fStack); - return fStack; - } - - Void HardwareThread::Busy(const Bool busy) noexcept - { - fBusy = busy; - } - - HardwareThread::operator bool() - { - return fStack; - } - - /// @brief Wakeup the processor. - - Void HardwareThread::Wake(const bool wakeup) noexcept - { - fWakeup = wakeup; - - if (!fWakeup) - mp_hang_thread(fStack); - else - mp_wakeup_thread(fStack); - } - - /// @note Those symbols are needed in order to switch and validate the stack. - - EXTERN Bool hal_check_stack(HAL::StackFramePtr stackPtr); - EXTERN_C Bool mp_register_process(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr frame_ptr); - - /// @brief Switch to hardware thread. - /// @param stack the new hardware thread. - /// @retval true stack was changed, code is running. - /// @retval false stack is invalid, previous code is running. - Bool HardwareThread::Switch(VoidPtr image, UInt8* stack_ptr, HAL::StackFramePtr frame) - { - if (!frame || - !image || - !stack_ptr) - return No; - - if (!this->IsWakeup()) - return No; - - if (this->IsBusy()) - return No; - - fStack = frame; - - Bool ret = mp_register_process(image, stack_ptr, fStack); - - if (ret) - this->Busy(true); - - return ret; - } - - ///! @brief Tells if processor is waked up. - bool HardwareThread::IsWakeup() noexcept - { - return fWakeup; - } - - ///! @brief Constructor and destructors. - - ///! @brief Default constructor. - HardwareThreadScheduler::HardwareThreadScheduler() = default; - - ///! @brief Default destructor. - HardwareThreadScheduler::~HardwareThreadScheduler() = default; - - /// @brief Shared singleton function - HardwareThreadScheduler& HardwareThreadScheduler::The() - { - MUST_PASS(kHardwareThreadScheduler); - return *kHardwareThreadScheduler; - } - - /// @brief Get Stack Frame of Core - HAL::StackFramePtr HardwareThreadScheduler::Leak() noexcept - { - return fThreadList[fCurrentThread].fStack; - } - - /** - * Get Hardware thread at index. - * @param idx the index - * @return the reference to the hardware thread. - */ - Ref HardwareThreadScheduler::operator[](const SizeT& idx) - { - if (idx == 0) - { - if (fThreadList[idx].Kind() != kHartSystemReserved) - { - fThreadList[idx].fKind = kHartBoot; - } - } - else if (idx >= cMaxHartInsideSched) - { - static HardwareThread* fakeThread = nullptr; - return {fakeThread}; - } - - return &fThreadList[idx]; - } - - /** - * Check if thread pool isn't empty. - * @return - */ - HardwareThreadScheduler::operator bool() noexcept - { - return !fThreadList.Empty(); - } - - /** - * Reverse operator bool - * @return - */ - bool HardwareThreadScheduler::operator!() noexcept - { - return fThreadList.Empty(); - } - - /// @brief Returns the amount of core present. - /// @return the number of cores. - SizeT HardwareThreadScheduler::Count() noexcept - { - return fThreadList.Capacity(); - } -} // namespace Kernel diff --git a/dev/zka/src/Heap.cc b/dev/zka/src/Heap.cc new file mode 100644 index 00000000..45b7aa73 --- /dev/null +++ b/dev/zka/src/Heap.cc @@ -0,0 +1,265 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include +#include +#include +#include + +/* ------------------------------------------- + + Revision History: + 10/8/24: FIX: Fix useless long name, alongside a new WR (WriteRead) field. + 20/10/24: Fix mm_new_ and mm_delete_ APIs inside Heap.h header. (amlal) + + ------------------------------------------- */ + +//! @file Heap.cxx +//! @brief Kernel's heap manager, serves as the main memory manager. + +#define kKernelHeapMagic (0xD4D7D5) +#define kKernelAlignSz (__BIGGEST_ALIGNMENT__) + +namespace Kernel +{ + /// @brief Contains data structures and algorithms for the heap. + namespace Detail + { + struct PACKED HEAP_INFORMATION_BLOCK; + + /// @brief Kernel heap information block. + /// Located before the address bytes. + /// | HIB | CLASS/STRUCT/DATA TYPES... | + struct PACKED HEAP_INFORMATION_BLOCK final + { + ///! @brief 32-bit value which contains the magic number of the heap. + UInt32 fMagic : 24; + + ///! @brief Boolean value which tells if the heap is allocated. + Boolean fPresent : 1; + + /// @brief Is this valued owned by the user? + Boolean fWr : 1; + + /// @brief Is this valued owned by the user? + Boolean fUser : 1; + + /// @brief Is this a page pointer? + Boolean fPage : 1; + + ///! @brief 32-bit CRC checksum. + UInt32 fCRC32; + + /// @brief 64-bit pointer size. + SizeT fHeapSize; + + /// @brief 64-bit target pointer. + UIntPtr fHeapPtr; + + /// @brief Padding bytes for header. + UInt8 fPadding[kKernelAlignSz]; + }; + + /// @brief Check for heap address validity. + /// @param heap_ptr The address_ptr to check. + /// @return Bool if the pointer is valid or not. + auto mm_check_heap_address(VoidPtr heap_ptr) -> Bool + { + if (!heap_ptr) + return false; + + /// Add that check in case we're having an integer underflow. /// + + auto base_heap = (IntPtr)(heap_ptr) - sizeof(Detail::HEAP_INFORMATION_BLOCK); + + if (base_heap < 0) + { + return false; + } + + return true; + } + + typedef HEAP_INFORMATION_BLOCK* HEAP_INFORMATION_BLOCK_PTR; + } // namespace Detail + + Detail::HEAP_INFORMATION_BLOCK_PTR kLatestAllocation = nullptr; + + /// @brief Declare a new size for ptr_heap. + /// @param ptr_heap the pointer. + /// @return Newly allocated heap header. + VoidPtr mm_realloc_heap(VoidPtr ptr_heap, SizeT new_sz) + { + if (Detail::mm_check_heap_address(ptr_heap) == No) + return nullptr; + + if (!ptr_heap || new_sz < 1) + return nullptr; + + kcout << "This function is not implemented in the kernel, please refrain from using that.\r"; + ke_stop(RUNTIME_CHECK_PROCESS); + + return nullptr; + } + + /// @brief Allocate chunk of memory. + /// @param sz Size of pointer + /// @param wr Read Write bit. + /// @param user User enable bit. + /// @return The newly allocated pointer. + VoidPtr mm_new_heap(const SizeT sz, const bool wr, const bool user) + { + auto sz_fix = sz; + + if (sz_fix == 0) + return nullptr; + + sz_fix += sizeof(Detail::HEAP_INFORMATION_BLOCK); + + PageMgr heap_mgr; + auto wrapper = heap_mgr.Request(wr, user, No, sz_fix); + + Detail::HEAP_INFORMATION_BLOCK_PTR heap_info_ptr = + reinterpret_cast( + wrapper.VirtualAddress() + sizeof(Detail::HEAP_INFORMATION_BLOCK)); + + heap_info_ptr->fHeapSize = sz_fix; + heap_info_ptr->fMagic = kKernelHeapMagic; + heap_info_ptr->fCRC32 = No; // dont fill it for now. + heap_info_ptr->fHeapPtr = reinterpret_cast(heap_info_ptr) + sizeof(Detail::HEAP_INFORMATION_BLOCK); + heap_info_ptr->fPage = No; + heap_info_ptr->fWr = wr; + heap_info_ptr->fUser = user; + heap_info_ptr->fPresent = Yes; + + rt_set_memory(heap_info_ptr->fPadding, 0, kKernelAlignSz); + + auto result = reinterpret_cast(heap_info_ptr->fHeapPtr); + + kLatestAllocation = heap_info_ptr; + + return result; + } + + /// @brief Makes a page heap. + /// @param heap_ptr the pointer to make a page heap. + /// @return kErrorSuccess if successful, otherwise an error code. + Int32 mm_make_ke_page(VoidPtr heap_ptr) + { + if (Detail::mm_check_heap_address(heap_ptr) == No) + return -kErrorHeapNotPresent; + + Detail::HEAP_INFORMATION_BLOCK_PTR heap_blk = + reinterpret_cast( + (UIntPtr)heap_ptr - sizeof(Detail::HEAP_INFORMATION_BLOCK)); + + if (!heap_ptr) + return -kErrorHeapNotPresent; + + heap_blk->fPage = true; + + return kErrorSuccess; + } + + /// @brief Declare pointer as free. + /// @param heap_ptr the pointer. + /// @return + Int32 mm_delete_heap(VoidPtr heap_ptr) + { + if (Detail::mm_check_heap_address(heap_ptr) == No) + return -kErrorHeapNotPresent; + + Detail::HEAP_INFORMATION_BLOCK_PTR heap_blk = + reinterpret_cast( + (UIntPtr)(heap_ptr) - sizeof(Detail::HEAP_INFORMATION_BLOCK)); + + if (heap_blk && heap_blk->fMagic == kKernelHeapMagic) + { + if (!heap_blk->fPresent) + { + return -kErrorHeapNotPresent; + } + + if (heap_blk->fCRC32 != 0) + { + if (heap_blk->fCRC32 != + ke_calculate_crc32((Char*)heap_blk->fHeapPtr, + heap_blk->fHeapSize)) + { + if (!heap_blk->fUser) + { + ke_stop(RUNTIME_CHECK_POINTER); + } + } + } + + heap_blk->fHeapSize = 0UL; + heap_blk->fPresent = No; + heap_blk->fHeapPtr = 0; + heap_blk->fCRC32 = 0; + heap_blk->fWr = No; + heap_blk->fUser = No; + heap_blk->fMagic = 0; + + PTEWrapper pageWrapper(No, No, No, reinterpret_cast(heap_blk) - sizeof(Detail::HEAP_INFORMATION_BLOCK)); + Ref pteAddress{pageWrapper}; + + kcout << "Freeing pointer address: " << hex_number(reinterpret_cast(heap_blk) - sizeof(Detail::HEAP_INFORMATION_BLOCK)) << endl; + + PageMgr heap_mgr; + heap_mgr.Free(pteAddress); + + return kErrorSuccess; + } + + return -kErrorInternal; + } + + /// @brief Check if pointer is a valid Kernel pointer. + /// @param heap_ptr the pointer + /// @return if it exists. + Boolean mm_is_valid_heap(VoidPtr heap_ptr) + { + if (heap_ptr) + { + Detail::HEAP_INFORMATION_BLOCK_PTR heap_blk = + reinterpret_cast( + (UIntPtr)(heap_ptr) - sizeof(Detail::HEAP_INFORMATION_BLOCK)); + + if (heap_blk && heap_blk->fPresent && heap_blk->fMagic == kKernelHeapMagic) + { + return Yes; + } + } + + return No; + } + + /// @brief Protect the heap with a CRC value. + /// @param heap_ptr HIB pointer. + /// @return if it valid: point has crc now., otherwise fail. + Boolean mm_protect_heap(VoidPtr heap_ptr) + { + if (heap_ptr) + { + Detail::HEAP_INFORMATION_BLOCK_PTR heap_blk = + reinterpret_cast( + (UIntPtr)heap_ptr - sizeof(Detail::HEAP_INFORMATION_BLOCK)); + + if (heap_ptr && heap_blk->fPresent && kKernelHeapMagic == heap_blk->fMagic) + { + heap_blk->fCRC32 = + ke_calculate_crc32((Char*)heap_blk->fHeapPtr, heap_blk->fHeapSize); + + return Yes; + } + } + + return No; + } +} // namespace Kernel diff --git a/dev/zka/src/Heap.cxx b/dev/zka/src/Heap.cxx deleted file mode 100644 index 63e9286a..00000000 --- a/dev/zka/src/Heap.cxx +++ /dev/null @@ -1,265 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include -#include -#include -#include - -/* ------------------------------------------- - - Revision History: - 10/8/24: FIX: Fix useless long name, alongside a new WR (WriteRead) field. - 20/10/24: Fix mm_new_ and mm_delete_ APIs inside Heap.hxx header. (amlal) - - ------------------------------------------- */ - -//! @file Heap.cxx -//! @brief Kernel's heap manager, serves as the main memory manager. - -#define kKernelHeapMagic (0xD4D7D5) -#define kKernelAlignSz (__BIGGEST_ALIGNMENT__) - -namespace Kernel -{ - /// @brief Contains data structures and algorithms for the heap. - namespace Detail - { - struct PACKED HEAP_INFORMATION_BLOCK; - - /// @brief Kernel heap information block. - /// Located before the address bytes. - /// | HIB | CLASS/STRUCT/DATA TYPES... | - struct PACKED HEAP_INFORMATION_BLOCK final - { - ///! @brief 32-bit value which contains the magic number of the heap. - UInt32 fMagic : 24; - - ///! @brief Boolean value which tells if the heap is allocated. - Boolean fPresent : 1; - - /// @brief Is this valued owned by the user? - Boolean fWr : 1; - - /// @brief Is this valued owned by the user? - Boolean fUser : 1; - - /// @brief Is this a page pointer? - Boolean fPage : 1; - - ///! @brief 32-bit CRC checksum. - UInt32 fCRC32; - - /// @brief 64-bit pointer size. - SizeT fHeapSize; - - /// @brief 64-bit target pointer. - UIntPtr fHeapPtr; - - /// @brief Padding bytes for header. - UInt8 fPadding[kKernelAlignSz]; - }; - - /// @brief Check for heap address validity. - /// @param heap_ptr The address_ptr to check. - /// @return Bool if the pointer is valid or not. - auto mm_check_heap_address(VoidPtr heap_ptr) -> Bool - { - if (!heap_ptr) - return false; - - /// Add that check in case we're having an integer underflow. /// - - auto base_heap = (IntPtr)(heap_ptr) - sizeof(Detail::HEAP_INFORMATION_BLOCK); - - if (base_heap < 0) - { - return false; - } - - return true; - } - - typedef HEAP_INFORMATION_BLOCK* HEAP_INFORMATION_BLOCK_PTR; - } // namespace Detail - - Detail::HEAP_INFORMATION_BLOCK_PTR kLatestAllocation = nullptr; - - /// @brief Declare a new size for ptr_heap. - /// @param ptr_heap the pointer. - /// @return Newly allocated heap header. - VoidPtr mm_realloc_heap(VoidPtr ptr_heap, SizeT new_sz) - { - if (Detail::mm_check_heap_address(ptr_heap) == No) - return nullptr; - - if (!ptr_heap || new_sz < 1) - return nullptr; - - kcout << "This function is not implemented in the kernel, please refrain from using that.\r"; - ke_stop(RUNTIME_CHECK_PROCESS); - - return nullptr; - } - - /// @brief Allocate chunk of memory. - /// @param sz Size of pointer - /// @param wr Read Write bit. - /// @param user User enable bit. - /// @return The newly allocated pointer. - VoidPtr mm_new_heap(const SizeT sz, const bool wr, const bool user) - { - auto sz_fix = sz; - - if (sz_fix == 0) - return nullptr; - - sz_fix += sizeof(Detail::HEAP_INFORMATION_BLOCK); - - PageMgr heap_mgr; - auto wrapper = heap_mgr.Request(wr, user, No, sz_fix); - - Detail::HEAP_INFORMATION_BLOCK_PTR heap_info_ptr = - reinterpret_cast( - wrapper.VirtualAddress() + sizeof(Detail::HEAP_INFORMATION_BLOCK)); - - heap_info_ptr->fHeapSize = sz_fix; - heap_info_ptr->fMagic = kKernelHeapMagic; - heap_info_ptr->fCRC32 = No; // dont fill it for now. - heap_info_ptr->fHeapPtr = reinterpret_cast(heap_info_ptr) + sizeof(Detail::HEAP_INFORMATION_BLOCK); - heap_info_ptr->fPage = No; - heap_info_ptr->fWr = wr; - heap_info_ptr->fUser = user; - heap_info_ptr->fPresent = Yes; - - rt_set_memory(heap_info_ptr->fPadding, 0, kKernelAlignSz); - - auto result = reinterpret_cast(heap_info_ptr->fHeapPtr); - - kLatestAllocation = heap_info_ptr; - - return result; - } - - /// @brief Makes a page heap. - /// @param heap_ptr the pointer to make a page heap. - /// @return kErrorSuccess if successful, otherwise an error code. - Int32 mm_make_ke_page(VoidPtr heap_ptr) - { - if (Detail::mm_check_heap_address(heap_ptr) == No) - return -kErrorHeapNotPresent; - - Detail::HEAP_INFORMATION_BLOCK_PTR heap_blk = - reinterpret_cast( - (UIntPtr)heap_ptr - sizeof(Detail::HEAP_INFORMATION_BLOCK)); - - if (!heap_ptr) - return -kErrorHeapNotPresent; - - heap_blk->fPage = true; - - return kErrorSuccess; - } - - /// @brief Declare pointer as free. - /// @param heap_ptr the pointer. - /// @return - Int32 mm_delete_heap(VoidPtr heap_ptr) - { - if (Detail::mm_check_heap_address(heap_ptr) == No) - return -kErrorHeapNotPresent; - - Detail::HEAP_INFORMATION_BLOCK_PTR heap_blk = - reinterpret_cast( - (UIntPtr)(heap_ptr) - sizeof(Detail::HEAP_INFORMATION_BLOCK)); - - if (heap_blk && heap_blk->fMagic == kKernelHeapMagic) - { - if (!heap_blk->fPresent) - { - return -kErrorHeapNotPresent; - } - - if (heap_blk->fCRC32 != 0) - { - if (heap_blk->fCRC32 != - ke_calculate_crc32((Char*)heap_blk->fHeapPtr, - heap_blk->fHeapSize)) - { - if (!heap_blk->fUser) - { - ke_stop(RUNTIME_CHECK_POINTER); - } - } - } - - heap_blk->fHeapSize = 0UL; - heap_blk->fPresent = No; - heap_blk->fHeapPtr = 0; - heap_blk->fCRC32 = 0; - heap_blk->fWr = No; - heap_blk->fUser = No; - heap_blk->fMagic = 0; - - PTEWrapper pageWrapper(No, No, No, reinterpret_cast(heap_blk) - sizeof(Detail::HEAP_INFORMATION_BLOCK)); - Ref pteAddress{pageWrapper}; - - kcout << "Freeing pointer address: " << hex_number(reinterpret_cast(heap_blk) - sizeof(Detail::HEAP_INFORMATION_BLOCK)) << endl; - - PageMgr heap_mgr; - heap_mgr.Free(pteAddress); - - return kErrorSuccess; - } - - return -kErrorInternal; - } - - /// @brief Check if pointer is a valid Kernel pointer. - /// @param heap_ptr the pointer - /// @return if it exists. - Boolean mm_is_valid_heap(VoidPtr heap_ptr) - { - if (heap_ptr) - { - Detail::HEAP_INFORMATION_BLOCK_PTR heap_blk = - reinterpret_cast( - (UIntPtr)(heap_ptr) - sizeof(Detail::HEAP_INFORMATION_BLOCK)); - - if (heap_blk && heap_blk->fPresent && heap_blk->fMagic == kKernelHeapMagic) - { - return Yes; - } - } - - return No; - } - - /// @brief Protect the heap with a CRC value. - /// @param heap_ptr HIB pointer. - /// @return if it valid: point has crc now., otherwise fail. - Boolean mm_protect_heap(VoidPtr heap_ptr) - { - if (heap_ptr) - { - Detail::HEAP_INFORMATION_BLOCK_PTR heap_blk = - reinterpret_cast( - (UIntPtr)heap_ptr - sizeof(Detail::HEAP_INFORMATION_BLOCK)); - - if (heap_ptr && heap_blk->fPresent && kKernelHeapMagic == heap_blk->fMagic) - { - heap_blk->fCRC32 = - ke_calculate_crc32((Char*)heap_blk->fHeapPtr, heap_blk->fHeapSize); - - return Yes; - } - } - - return No; - } -} // namespace Kernel diff --git a/dev/zka/src/IDLLObject.cc b/dev/zka/src/IDLLObject.cc new file mode 100644 index 00000000..4e5f7aa2 --- /dev/null +++ b/dev/zka/src/IDLLObject.cc @@ -0,0 +1,15 @@ +/* + * ======================================================== + * + * minoskrnl + * Copyright ZKA Web Services Co., all rights reserved. + * + * ======================================================== + */ + +#include +#include + +#include + +using namespace Kernel; diff --git a/dev/zka/src/IDLLObject.cxx b/dev/zka/src/IDLLObject.cxx deleted file mode 100644 index a9ab9542..00000000 --- a/dev/zka/src/IDLLObject.cxx +++ /dev/null @@ -1,15 +0,0 @@ -/* - * ======================================================== - * - * minoskrnl - * Copyright ZKA Web Services Co., all rights reserved. - * - * ======================================================== - */ - -#include -#include - -#include - -using namespace Kernel; diff --git a/dev/zka/src/IPEFDLLObject.cc b/dev/zka/src/IPEFDLLObject.cc new file mode 100644 index 00000000..d7fe2948 --- /dev/null +++ b/dev/zka/src/IPEFDLLObject.cc @@ -0,0 +1,102 @@ +/* + * ======================================================== + * + * minoskrnl + * Copyright ZKA Web Services Co., all rights reserved. + * + * ======================================================== + */ + +#include +#include +#include +#include +#include +#include + +/* ------------------------------------------- + + Revision History: + + 01/02/24: Reworked dll ABI, expect a rtl_init_dll and + rtl_fini_dll (amlel) 15/02/24: Breaking changes, changed the name of the + routines. (amlel) + + 07/28/24: Replace rt_library_free with rtl_fini_dll + + 10/8/24: FIX: Fix log comment. + + ------------------------------------------- */ + +using namespace Kernel; + +/***********************************************************************************/ +/// @file PEFSharedObjectRT.cxx +/// @brief PEF's shared object runtime. +/***********************************************************************************/ + +/***********************************************************************************/ +/** @brief Library initializer. */ +/***********************************************************************************/ + +EXTERN_C IDLL rtl_init_dll(UserProcess* header) +{ + IDLL dll_obj = tls_new_class(); + + if (!dll_obj) + { + header->Crash(); + + return nullptr; + } + + dll_obj->Mount(tls_new_class()); + + if (!dll_obj->Get()) + { + header->Crash(); + + return nullptr; + } + + dll_obj->Get()->fImageObject = + header->Image; + + if (!dll_obj->Get()->fImageObject) + { + header->Crash(); + + return nullptr; + } + + dll_obj->Get()->fImageEntrypointOffset = + dll_obj->Load(kPefStart, rt_string_len(kPefStart, 0), kPefCode); + + return dll_obj; +} + +/***********************************************************************************/ +/** @brief Frees the dll_obj. */ +/** @note Please check if the dll_obj got freed! */ +/** @param dll_obj The dll_obj to free. */ +/** @param successful Reports if successful or not. */ +/***********************************************************************************/ + +EXTERN_C Void rtl_fini_dll(UserProcess* header, IDLL dll_obj, Bool* successful) +{ + MUST_PASS(successful); + + // sanity check (will also trigger a bug check if this fails) + if (dll_obj == nullptr) + { + *successful = false; + header->Crash(); + } + + delete dll_obj->Get(); + delete dll_obj; + + dll_obj = nullptr; + + *successful = true; +} diff --git a/dev/zka/src/IPEFDLLObject.cxx b/dev/zka/src/IPEFDLLObject.cxx deleted file mode 100644 index e2e85dcc..00000000 --- a/dev/zka/src/IPEFDLLObject.cxx +++ /dev/null @@ -1,102 +0,0 @@ -/* - * ======================================================== - * - * minoskrnl - * Copyright ZKA Web Services Co., all rights reserved. - * - * ======================================================== - */ - -#include -#include -#include -#include -#include -#include - -/* ------------------------------------------- - - Revision History: - - 01/02/24: Reworked dll ABI, expect a rtl_init_dll and - rtl_fini_dll (amlel) 15/02/24: Breaking changes, changed the name of the - routines. (amlel) - - 07/28/24: Replace rt_library_free with rtl_fini_dll - - 10/8/24: FIX: Fix log comment. - - ------------------------------------------- */ - -using namespace Kernel; - -/***********************************************************************************/ -/// @file PEFSharedObjectRT.cxx -/// @brief PEF's shared object runtime. -/***********************************************************************************/ - -/***********************************************************************************/ -/** @brief Library initializer. */ -/***********************************************************************************/ - -EXTERN_C IDLL rtl_init_dll(UserProcess* header) -{ - IDLL dll_obj = tls_new_class(); - - if (!dll_obj) - { - header->Crash(); - - return nullptr; - } - - dll_obj->Mount(tls_new_class()); - - if (!dll_obj->Get()) - { - header->Crash(); - - return nullptr; - } - - dll_obj->Get()->fImageObject = - header->Image; - - if (!dll_obj->Get()->fImageObject) - { - header->Crash(); - - return nullptr; - } - - dll_obj->Get()->fImageEntrypointOffset = - dll_obj->Load(kPefStart, rt_string_len(kPefStart, 0), kPefCode); - - return dll_obj; -} - -/***********************************************************************************/ -/** @brief Frees the dll_obj. */ -/** @note Please check if the dll_obj got freed! */ -/** @param dll_obj The dll_obj to free. */ -/** @param successful Reports if successful or not. */ -/***********************************************************************************/ - -EXTERN_C Void rtl_fini_dll(UserProcess* header, IDLL dll_obj, Bool* successful) -{ - MUST_PASS(successful); - - // sanity check (will also trigger a bug check if this fails) - if (dll_obj == nullptr) - { - *successful = false; - header->Crash(); - } - - delete dll_obj->Get(); - delete dll_obj; - - dll_obj = nullptr; - - *successful = true; -} diff --git a/dev/zka/src/IndexableProperty.cc b/dev/zka/src/IndexableProperty.cc new file mode 100644 index 00000000..05438467 --- /dev/null +++ b/dev/zka/src/IndexableProperty.cc @@ -0,0 +1,57 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include +#include + +/// @brief File indexer API for fast path access. +/// BUGS: 0 + +#define kMaxLenIndexer (256U) + +namespace Kernel +{ + namespace Indexer + { + IndexProperty& IndexableProperty::Leak() noexcept + { + return fIndex; + } + + Void IndexableProperty::AddFlag(Int16 flag) + { + fFlags |= flag; + } + + Void IndexableProperty::RemoveFlag(Int16 flag) + { + fFlags &= flag; + } + + Int16 IndexableProperty::HasFlag(Int16 flag) + { + return fFlags & flag; + } + + /// @brief Index a file into the indexer instance. + /// @param filename filesystem path to access. + /// @param filenameLen used bytes in path. + /// @param indexer the filesystem indexer. + /// @return none, check before if indexer can be claimed (using indexer.HasFlag(kIndexerClaimed)). + Void fs_index_file(const Char* filename, SizeT filenameLen, IndexableProperty& indexer) + { + if (!indexer.HasFlag(kIndexerClaimed)) + { + indexer.AddFlag(kIndexerClaimed); + rt_copy_memory((VoidPtr)indexer.Leak().Path, (VoidPtr)filename, filenameLen); + + kcout << "FSKit: Indexed new file: " << filename << endl; + } + } + } // namespace Indexer +} // namespace Kernel diff --git a/dev/zka/src/IndexableProperty.cxx b/dev/zka/src/IndexableProperty.cxx deleted file mode 100644 index 7595291c..00000000 --- a/dev/zka/src/IndexableProperty.cxx +++ /dev/null @@ -1,57 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include -#include - -/// @brief File indexer API for fast path access. -/// BUGS: 0 - -#define kMaxLenIndexer (256U) - -namespace Kernel -{ - namespace Indexer - { - IndexProperty& IndexableProperty::Leak() noexcept - { - return fIndex; - } - - Void IndexableProperty::AddFlag(Int16 flag) - { - fFlags |= flag; - } - - Void IndexableProperty::RemoveFlag(Int16 flag) - { - fFlags &= flag; - } - - Int16 IndexableProperty::HasFlag(Int16 flag) - { - return fFlags & flag; - } - - /// @brief Index a file into the indexer instance. - /// @param filename filesystem path to access. - /// @param filenameLen used bytes in path. - /// @param indexer the filesystem indexer. - /// @return none, check before if indexer can be claimed (using indexer.HasFlag(kIndexerClaimed)). - Void fs_index_file(const Char* filename, SizeT filenameLen, IndexableProperty& indexer) - { - if (!indexer.HasFlag(kIndexerClaimed)) - { - indexer.AddFlag(kIndexerClaimed); - rt_copy_memory((VoidPtr)indexer.Leak().Path, (VoidPtr)filename, filenameLen); - - kcout << "FSKit: Indexed new file: " << filename << endl; - } - } - } // namespace Indexer -} // namespace Kernel diff --git a/dev/zka/src/Json.cc b/dev/zka/src/Json.cc new file mode 100644 index 00000000..4c3f07dc --- /dev/null +++ b/dev/zka/src/Json.cc @@ -0,0 +1,12 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +using namespace Kernel; + +/// @brief Undefined object, is null in length. +cInitObject(Kernel::JSON::kNull, Kernel::JSON); diff --git a/dev/zka/src/Json.cxx b/dev/zka/src/Json.cxx deleted file mode 100644 index acf46f8a..00000000 --- a/dev/zka/src/Json.cxx +++ /dev/null @@ -1,12 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -using namespace Kernel; - -/// @brief Undefined object, is null in length. -cInitObject(Kernel::JSON::kNull, Kernel::JSON); diff --git a/dev/zka/src/LPC.cc b/dev/zka/src/LPC.cc new file mode 100644 index 00000000..a39b0857 --- /dev/null +++ b/dev/zka/src/LPC.cc @@ -0,0 +1,34 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +namespace Kernel +{ + STATIC Bool kRaiseOnBugCheck = false; + + /// @brief Does a system wide bug check. + /// @param void no params. + /// @return if error-free: false, otherwise true. + Boolean err_bug_check(void) noexcept + { + if (kRaiseOnBugCheck) + { + ke_stop(RUNTIME_CHECK_BAD_BEHAVIOR); + } + + return No; + } + + /// @brief Tells if we should raise a bug check not. + /// @param void + /// @return void + Void err_bug_check_raise(Void) noexcept + { + kRaiseOnBugCheck = true; + } +} // namespace Kernel diff --git a/dev/zka/src/LPC.cxx b/dev/zka/src/LPC.cxx deleted file mode 100644 index 5cf64e26..00000000 --- a/dev/zka/src/LPC.cxx +++ /dev/null @@ -1,34 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -namespace Kernel -{ - STATIC Bool kRaiseOnBugCheck = false; - - /// @brief Does a system wide bug check. - /// @param void no params. - /// @return if error-free: false, otherwise true. - Boolean err_bug_check(void) noexcept - { - if (kRaiseOnBugCheck) - { - ke_stop(RUNTIME_CHECK_BAD_BEHAVIOR); - } - - return No; - } - - /// @brief Tells if we should raise a bug check not. - /// @param void - /// @return void - Void err_bug_check_raise(Void) noexcept - { - kRaiseOnBugCheck = true; - } -} // namespace Kernel diff --git a/dev/zka/src/LockDelegate.cc b/dev/zka/src/LockDelegate.cc new file mode 100644 index 00000000..cc2a36b8 --- /dev/null +++ b/dev/zka/src/LockDelegate.cc @@ -0,0 +1,12 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +namespace Kernel +{ + /// @note Leave it empty for now. +} // namespace Kernel diff --git a/dev/zka/src/LockDelegate.cxx b/dev/zka/src/LockDelegate.cxx deleted file mode 100644 index d101615c..00000000 --- a/dev/zka/src/LockDelegate.cxx +++ /dev/null @@ -1,12 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -namespace Kernel -{ - /// @note Leave it empty for now. -} // namespace Kernel diff --git a/dev/zka/src/MutableArray.cc b/dev/zka/src/MutableArray.cc new file mode 100644 index 00000000..de0523e1 --- /dev/null +++ b/dev/zka/src/MutableArray.cc @@ -0,0 +1,7 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include diff --git a/dev/zka/src/MutableArray.cxx b/dev/zka/src/MutableArray.cxx deleted file mode 100644 index 48b9c787..00000000 --- a/dev/zka/src/MutableArray.cxx +++ /dev/null @@ -1,7 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include diff --git a/dev/zka/src/NeFS+FileMgr.cc b/dev/zka/src/NeFS+FileMgr.cc new file mode 100644 index 00000000..3cc5400b --- /dev/null +++ b/dev/zka/src/NeFS+FileMgr.cc @@ -0,0 +1,248 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +#ifndef __ZKA_MINIMAL_OS__ +#ifdef __FSKIT_USE_NEFS__ + +/// @brief NeFS File manager. +/// BUGS: 0 + +namespace Kernel +{ + /// @brief C++ constructor + NeFileSystemMgr::NeFileSystemMgr() + { + MUST_PASS(Detail::fs_init_newfs()); + fImpl = mm_new_class(); + MUST_PASS(fImpl); + + kcout << "We are done here... (NeFileSystemMgr).\r"; + } + + NeFileSystemMgr::~NeFileSystemMgr() + { + if (fImpl) + { + kcout << "Destroying FS class (NeFS)...\r"; + + delete fImpl; + fImpl = nullptr; + } + } + + /// @brief Removes a node from the filesystem. + /// @param fileName The filename + /// @return If it was deleted or not. + bool NeFileSystemMgr::Remove(const Char* fileName) + { + if (fileName == nullptr || *fileName == 0) + return false; + + return fImpl->RemoveCatalog(fileName); + } + + /// @brief Creates a node with the specified. + /// @param path The filename path. + /// @return The Node pointer. + NodePtr NeFileSystemMgr::Create(const Char* path) + { + return node_cast(fImpl->CreateCatalog(path)); + } + + /// @brief Creates a node with is a directory. + /// @param path The filename path. + /// @return The Node pointer. + NodePtr NeFileSystemMgr::CreateDirectory(const Char* path) + { + return node_cast(fImpl->CreateCatalog(path, 0, kNeFSCatalogKindDir)); + } + + /// @brief Creates a node with is a alias. + /// @param path The filename path. + /// @return The Node pointer. + NodePtr NeFileSystemMgr::CreateAlias(const Char* path) + { + return node_cast(fImpl->CreateCatalog(path, 0, kNeFSCatalogKindAlias)); + } + + /// @brief Creates a node with is a page file. + /// @param path The filename path. + /// @return The Node pointer. + NodePtr NeFileSystemMgr::CreateSwapFile(const Char* path) + { + return node_cast(fImpl->CreateCatalog(path, 0, kNeFSCatalogKindPage)); + } + + /// @brief Gets the root directory. + /// @return + const Char* NeFileSystemHelper::Root() + { + return kNeFSRoot; + } + + /// @brief Gets the up-dir directory. + /// @return + const Char* NeFileSystemHelper::UpDir() + { + return kNeFSUpDir; + } + + /// @brief Gets the separator character. + /// @return + const Char NeFileSystemHelper::Separator() + { + return kNeFSSeparator; + } + + /// @brief Gets the metafile character. + /// @return + const Char NeFileSystemHelper::MetaFile() + { + return kNeFSMetaFilePrefix; + } + + /// @brief Opens a new file. + /// @param path + /// @param r + /// @return + _Output NodePtr NeFileSystemMgr::Open(_Input const Char* path, _Input const Char* r) + { + if (!path || *path == 0) + return nullptr; + + if (!r || *r == 0) + return nullptr; + + auto catalog = fImpl->GetCatalog(path); + + return node_cast(catalog); + } + + /// @brief Writes to a catalog's fork. + /// @param node the node ptr. + /// @param data the data. + /// @param flags the size. + /// @return + Void NeFileSystemMgr::Write(_Input NodePtr node, _Input VoidPtr data, _Input Int32 flags, _Input SizeT size) + { + if (!node) + return; + if (!size) + return; + + constexpr auto cDataForkName = kNeFSDataFork; + this->Write(cDataForkName, node, data, flags, size); + } + + /// @brief Read from filesystem fork. + /// @param node the catalog node. + /// @param flags the flags with it. + /// @param sz the size to read. + /// @return + _Output VoidPtr NeFileSystemMgr::Read(_Input NodePtr node, _Input Int32 flags, _Input SizeT size) + { + if (!node) + return nullptr; + if (!size) + return nullptr; + + constexpr auto cDataForkName = kNeFSDataFork; + return this->Read(cDataForkName, node, flags, size); + } + + Void NeFileSystemMgr::Write(_Input const Char* name, + _Input NodePtr node, + _Input VoidPtr data, + _Input Int32 flags, + _Input SizeT size) + { + if (!size || + size > kNeFSForkSize) + return; + + if (!data) + return; + + ZKA_UNUSED(flags); + + if ((reinterpret_cast(node))->Kind == kNeFSCatalogKindFile) + fImpl->WriteCatalog(reinterpret_cast(node), (flags & cFileFlagRsrc ? true : false), data, size, + name); + } + + _Output VoidPtr NeFileSystemMgr::Read(_Input const Char* name, + _Input NodePtr node, + _Input Int32 flags, + _Input SizeT sz) + { + if (sz > kNeFSForkSize) + return nullptr; + + if (!sz) + return nullptr; + + ZKA_UNUSED(flags); + + if ((reinterpret_cast(node))->Kind == kNeFSCatalogKindFile) + return fImpl->ReadCatalog(reinterpret_cast(node), (flags & cFileFlagRsrc ? true : false), sz, + name); + + return nullptr; + } + + /// @brief Seek from Catalog. + /// @param node + /// @param off + /// @retval true always returns false, this is unimplemented. + /// @retval false always returns this, it is unimplemented. + + _Output Bool NeFileSystemMgr::Seek(NodePtr node, SizeT off) + { + if (!node || off == 0) + return false; + + return fImpl->Seek(reinterpret_cast(node), off); + } + + /// @brief Tell where the catalog is. + /// @param node + /// @retval true always returns false, this is unimplemented. + /// @retval false always returns this, it is unimplemented. + + _Output SizeT NeFileSystemMgr::Tell(NodePtr node) + { + if (!node) + return kNPos; + + return fImpl->Tell(reinterpret_cast(node)); + } + + /// @brief Rewinds the catalog. + /// @param node + /// @retval true always returns false, this is unimplemented. + /// @retval false always returns this, it is unimplemented. + + _Output Bool NeFileSystemMgr::Rewind(NodePtr node) + { + if (!node) + return false; + + return this->Seek(node, 0); + } + + /// @brief Returns the filesystem parser. + /// @return the Filesystem parser class. + _Output NeFSParser* NeFileSystemMgr::GetParser() noexcept + { + return fImpl; + } +} // namespace Kernel + +#endif // ifdef __FSKIT_USE_NEFS__ +#endif // ifndef __ZKA_MINIMAL_OS__ diff --git a/dev/zka/src/NeFS+FileMgr.cxx b/dev/zka/src/NeFS+FileMgr.cxx deleted file mode 100644 index da5a1285..00000000 --- a/dev/zka/src/NeFS+FileMgr.cxx +++ /dev/null @@ -1,248 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -#ifndef __ZKA_MINIMAL_OS__ -#ifdef __FSKIT_USE_NEFS__ - -/// @brief NeFS File manager. -/// BUGS: 0 - -namespace Kernel -{ - /// @brief C++ constructor - NeFileSystemMgr::NeFileSystemMgr() - { - MUST_PASS(Detail::fs_init_newfs()); - fImpl = mm_new_class(); - MUST_PASS(fImpl); - - kcout << "We are done here... (NeFileSystemMgr).\r"; - } - - NeFileSystemMgr::~NeFileSystemMgr() - { - if (fImpl) - { - kcout << "Destroying FS class (NeFS)...\r"; - - delete fImpl; - fImpl = nullptr; - } - } - - /// @brief Removes a node from the filesystem. - /// @param fileName The filename - /// @return If it was deleted or not. - bool NeFileSystemMgr::Remove(const Char* fileName) - { - if (fileName == nullptr || *fileName == 0) - return false; - - return fImpl->RemoveCatalog(fileName); - } - - /// @brief Creates a node with the specified. - /// @param path The filename path. - /// @return The Node pointer. - NodePtr NeFileSystemMgr::Create(const Char* path) - { - return node_cast(fImpl->CreateCatalog(path)); - } - - /// @brief Creates a node with is a directory. - /// @param path The filename path. - /// @return The Node pointer. - NodePtr NeFileSystemMgr::CreateDirectory(const Char* path) - { - return node_cast(fImpl->CreateCatalog(path, 0, kNeFSCatalogKindDir)); - } - - /// @brief Creates a node with is a alias. - /// @param path The filename path. - /// @return The Node pointer. - NodePtr NeFileSystemMgr::CreateAlias(const Char* path) - { - return node_cast(fImpl->CreateCatalog(path, 0, kNeFSCatalogKindAlias)); - } - - /// @brief Creates a node with is a page file. - /// @param path The filename path. - /// @return The Node pointer. - NodePtr NeFileSystemMgr::CreateSwapFile(const Char* path) - { - return node_cast(fImpl->CreateCatalog(path, 0, kNeFSCatalogKindPage)); - } - - /// @brief Gets the root directory. - /// @return - const Char* NeFileSystemHelper::Root() - { - return kNeFSRoot; - } - - /// @brief Gets the up-dir directory. - /// @return - const Char* NeFileSystemHelper::UpDir() - { - return kNeFSUpDir; - } - - /// @brief Gets the separator character. - /// @return - const Char NeFileSystemHelper::Separator() - { - return kNeFSSeparator; - } - - /// @brief Gets the metafile character. - /// @return - const Char NeFileSystemHelper::MetaFile() - { - return kNeFSMetaFilePrefix; - } - - /// @brief Opens a new file. - /// @param path - /// @param r - /// @return - _Output NodePtr NeFileSystemMgr::Open(_Input const Char* path, _Input const Char* r) - { - if (!path || *path == 0) - return nullptr; - - if (!r || *r == 0) - return nullptr; - - auto catalog = fImpl->GetCatalog(path); - - return node_cast(catalog); - } - - /// @brief Writes to a catalog's fork. - /// @param node the node ptr. - /// @param data the data. - /// @param flags the size. - /// @return - Void NeFileSystemMgr::Write(_Input NodePtr node, _Input VoidPtr data, _Input Int32 flags, _Input SizeT size) - { - if (!node) - return; - if (!size) - return; - - constexpr auto cDataForkName = kNeFSDataFork; - this->Write(cDataForkName, node, data, flags, size); - } - - /// @brief Read from filesystem fork. - /// @param node the catalog node. - /// @param flags the flags with it. - /// @param sz the size to read. - /// @return - _Output VoidPtr NeFileSystemMgr::Read(_Input NodePtr node, _Input Int32 flags, _Input SizeT size) - { - if (!node) - return nullptr; - if (!size) - return nullptr; - - constexpr auto cDataForkName = kNeFSDataFork; - return this->Read(cDataForkName, node, flags, size); - } - - Void NeFileSystemMgr::Write(_Input const Char* name, - _Input NodePtr node, - _Input VoidPtr data, - _Input Int32 flags, - _Input SizeT size) - { - if (!size || - size > kNeFSForkSize) - return; - - if (!data) - return; - - ZKA_UNUSED(flags); - - if ((reinterpret_cast(node))->Kind == kNeFSCatalogKindFile) - fImpl->WriteCatalog(reinterpret_cast(node), (flags & cFileFlagRsrc ? true : false), data, size, - name); - } - - _Output VoidPtr NeFileSystemMgr::Read(_Input const Char* name, - _Input NodePtr node, - _Input Int32 flags, - _Input SizeT sz) - { - if (sz > kNeFSForkSize) - return nullptr; - - if (!sz) - return nullptr; - - ZKA_UNUSED(flags); - - if ((reinterpret_cast(node))->Kind == kNeFSCatalogKindFile) - return fImpl->ReadCatalog(reinterpret_cast(node), (flags & cFileFlagRsrc ? true : false), sz, - name); - - return nullptr; - } - - /// @brief Seek from Catalog. - /// @param node - /// @param off - /// @retval true always returns false, this is unimplemented. - /// @retval false always returns this, it is unimplemented. - - _Output Bool NeFileSystemMgr::Seek(NodePtr node, SizeT off) - { - if (!node || off == 0) - return false; - - return fImpl->Seek(reinterpret_cast(node), off); - } - - /// @brief Tell where the catalog is. - /// @param node - /// @retval true always returns false, this is unimplemented. - /// @retval false always returns this, it is unimplemented. - - _Output SizeT NeFileSystemMgr::Tell(NodePtr node) - { - if (!node) - return kNPos; - - return fImpl->Tell(reinterpret_cast(node)); - } - - /// @brief Rewinds the catalog. - /// @param node - /// @retval true always returns false, this is unimplemented. - /// @retval false always returns this, it is unimplemented. - - _Output Bool NeFileSystemMgr::Rewind(NodePtr node) - { - if (!node) - return false; - - return this->Seek(node, 0); - } - - /// @brief Returns the filesystem parser. - /// @return the Filesystem parser class. - _Output NeFSParser* NeFileSystemMgr::GetParser() noexcept - { - return fImpl; - } -} // namespace Kernel - -#endif // ifdef __FSKIT_USE_NEFS__ -#endif // ifndef __ZKA_MINIMAL_OS__ diff --git a/dev/zka/src/NeFS+IO.cc b/dev/zka/src/NeFS+IO.cc new file mode 100644 index 00000000..010ec3f2 --- /dev/null +++ b/dev/zka/src/NeFS+IO.cc @@ -0,0 +1,101 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +/************************************************************* + * + * File: NeFS+IO.cxx + * Purpose: Filesystem to mountpoint interface. + * Date: 3/26/24 + * + * Copyright ZKA Web Services Co., all rights reserved. + * + *************************************************************/ + +#ifdef __FSKIT_USE_NEFS__ + +#include + +/// Useful macros. + +#define NEFS_WRITE(DRV, TRAITS, MP) (MP->DRV()).fOutput(&TRAITS) +#define NEFS_READ(DRV, TRAITS, MP) (MP->DRV()).fInput(&TRAITS) + +using namespace Kernel; + +/// @brief Read from newfs disk. +/// @param Mnt mounted interface. +/// @param DrvTrait drive info +/// @param DrvIndex drive index. +/// @return +Int32 fs_newfs_read(MountpointInterface* Mnt, DriveTrait& DrvTrait, Int32 DrvIndex) +{ + if (!Mnt) + return -1; + + DrvTrait.fPacket.fPacketGood = false; + + switch (DrvIndex) + { + case kNeFSSubDriveA: { + NEFS_READ(A, DrvTrait.fPacket, Mnt); + break; + } + case kNeFSSubDriveB: { + NEFS_READ(B, DrvTrait.fPacket, Mnt); + break; + } + case kNeFSSubDriveC: { + NEFS_READ(C, DrvTrait.fPacket, Mnt); + break; + } + case kNeFSSubDriveD: { + NEFS_READ(D, DrvTrait.fPacket, Mnt); + break; + } + } + + return DrvTrait.fPacket.fPacketGood; +} + +/// @brief Write to newfs disk. +/// @param Mnt mounted interface. +/// @param DrvTrait drive info +/// @param DrvIndex drive index. +/// @return +Int32 fs_newfs_write(MountpointInterface* Mnt, DriveTrait& DrvTrait, Int32 DrvIndex) +{ + if (!Mnt) + return -1; + + DrvTrait.fPacket.fPacketGood = false; + + switch (DrvIndex) + { + case kNeFSSubDriveA: { + NEFS_WRITE(A, DrvTrait.fPacket, Mnt); + break; + } + case kNeFSSubDriveB: { + NEFS_WRITE(B, DrvTrait.fPacket, Mnt); + break; + } + case kNeFSSubDriveC: { + NEFS_WRITE(C, DrvTrait.fPacket, Mnt); + break; + } + case kNeFSSubDriveD: { + NEFS_WRITE(D, DrvTrait.fPacket, Mnt); + break; + } + } + + return DrvTrait.fPacket.fPacketGood; +} + +#endif // ifdef __FSKIT_USE_NEFS__ diff --git a/dev/zka/src/NeFS+IO.cxx b/dev/zka/src/NeFS+IO.cxx deleted file mode 100644 index c95d48ce..00000000 --- a/dev/zka/src/NeFS+IO.cxx +++ /dev/null @@ -1,101 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -/************************************************************* - * - * File: NeFS+IO.cxx - * Purpose: Filesystem to mountpoint interface. - * Date: 3/26/24 - * - * Copyright ZKA Web Services Co., all rights reserved. - * - *************************************************************/ - -#ifdef __FSKIT_USE_NEFS__ - -#include - -/// Useful macros. - -#define NEFS_WRITE(DRV, TRAITS, MP) (MP->DRV()).fOutput(&TRAITS) -#define NEFS_READ(DRV, TRAITS, MP) (MP->DRV()).fInput(&TRAITS) - -using namespace Kernel; - -/// @brief Read from newfs disk. -/// @param Mnt mounted interface. -/// @param DrvTrait drive info -/// @param DrvIndex drive index. -/// @return -Int32 fs_newfs_read(MountpointInterface* Mnt, DriveTrait& DrvTrait, Int32 DrvIndex) -{ - if (!Mnt) - return -1; - - DrvTrait.fPacket.fPacketGood = false; - - switch (DrvIndex) - { - case kNeFSSubDriveA: { - NEFS_READ(A, DrvTrait.fPacket, Mnt); - break; - } - case kNeFSSubDriveB: { - NEFS_READ(B, DrvTrait.fPacket, Mnt); - break; - } - case kNeFSSubDriveC: { - NEFS_READ(C, DrvTrait.fPacket, Mnt); - break; - } - case kNeFSSubDriveD: { - NEFS_READ(D, DrvTrait.fPacket, Mnt); - break; - } - } - - return DrvTrait.fPacket.fPacketGood; -} - -/// @brief Write to newfs disk. -/// @param Mnt mounted interface. -/// @param DrvTrait drive info -/// @param DrvIndex drive index. -/// @return -Int32 fs_newfs_write(MountpointInterface* Mnt, DriveTrait& DrvTrait, Int32 DrvIndex) -{ - if (!Mnt) - return -1; - - DrvTrait.fPacket.fPacketGood = false; - - switch (DrvIndex) - { - case kNeFSSubDriveA: { - NEFS_WRITE(A, DrvTrait.fPacket, Mnt); - break; - } - case kNeFSSubDriveB: { - NEFS_WRITE(B, DrvTrait.fPacket, Mnt); - break; - } - case kNeFSSubDriveC: { - NEFS_WRITE(C, DrvTrait.fPacket, Mnt); - break; - } - case kNeFSSubDriveD: { - NEFS_WRITE(D, DrvTrait.fPacket, Mnt); - break; - } - } - - return DrvTrait.fPacket.fPacketGood; -} - -#endif // ifdef __FSKIT_USE_NEFS__ diff --git a/dev/zka/src/Network/IP.cc b/dev/zka/src/Network/IP.cc new file mode 100644 index 00000000..b78009dc --- /dev/null +++ b/dev/zka/src/Network/IP.cc @@ -0,0 +1,126 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +namespace Kernel +{ + char* RawIPAddress::Address() + { + return fAddr; + } + + RawIPAddress::RawIPAddress(char bytes[4]) + { + rt_copy_memory(bytes, fAddr, 4); + } + + bool RawIPAddress::operator==(const RawIPAddress& ipv4) + { + for (Size index = 0; index < 4; ++index) + { + if (ipv4.fAddr[index] != fAddr[index]) + return false; + } + + return true; + } + + bool RawIPAddress::operator!=(const RawIPAddress& ipv4) + { + for (Size index = 0; index < 4; ++index) + { + if (ipv4.fAddr[index] == fAddr[index]) + return false; + } + + return true; + } + + char& RawIPAddress::operator[](const Size& index) + { + kcout << "[RawIPAddress::operator[]] Fetching Index...\r"; + + static char IP_PLACEHOLDER = '0'; + if (index > 4) + return IP_PLACEHOLDER; + + return fAddr[index]; + } + + RawIPAddress6::RawIPAddress6(char bytes[8]) + { + rt_copy_memory(bytes, fAddr, 8); + } + + char& RawIPAddress6::operator[](const Size& index) + { + kcout << "[RawIPAddress6::operator[]] Fetching Index...\r"; + + static char IP_PLACEHOLDER = '0'; + if (index > 8) + return IP_PLACEHOLDER; + + return fAddr[index]; + } + + bool RawIPAddress6::operator==(const RawIPAddress6& ipv6) + { + for (SizeT index = 0; index < 8; ++index) + { + if (ipv6.fAddr[index] != fAddr[index]) + return false; + } + + return true; + } + + bool RawIPAddress6::operator!=(const RawIPAddress6& ipv6) + { + for (SizeT index = 0; index < 8; ++index) + { + if (ipv6.fAddr[index] == fAddr[index]) + return false; + } + + return true; + } + + ErrorOr IPFactory::ToStringView(Ref& ipv6) + { + auto str = StringBuilder::Construct(ipv6.Leak().Address()); + return str; + } + + ErrorOr IPFactory::ToStringView(Ref& ipv4) + { + auto str = StringBuilder::Construct(ipv4.Leak().Address()); + return str; + } + + bool IPFactory::IpCheckVersion4(const Char* ip) + { + int cnter = 0; + + for (Size base = 0; base < rt_string_len(ip); ++base) + { + if (ip[base] == '.') + { + cnter = 0; + } + else + { + if (cnter == 3) + return false; + + ++cnter; + } + } + + return true; + } +} // namespace Kernel diff --git a/dev/zka/src/Network/IP.cxx b/dev/zka/src/Network/IP.cxx deleted file mode 100644 index d7676592..00000000 --- a/dev/zka/src/Network/IP.cxx +++ /dev/null @@ -1,126 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -namespace Kernel -{ - char* RawIPAddress::Address() - { - return fAddr; - } - - RawIPAddress::RawIPAddress(char bytes[4]) - { - rt_copy_memory(bytes, fAddr, 4); - } - - bool RawIPAddress::operator==(const RawIPAddress& ipv4) - { - for (Size index = 0; index < 4; ++index) - { - if (ipv4.fAddr[index] != fAddr[index]) - return false; - } - - return true; - } - - bool RawIPAddress::operator!=(const RawIPAddress& ipv4) - { - for (Size index = 0; index < 4; ++index) - { - if (ipv4.fAddr[index] == fAddr[index]) - return false; - } - - return true; - } - - char& RawIPAddress::operator[](const Size& index) - { - kcout << "[RawIPAddress::operator[]] Fetching Index...\r"; - - static char IP_PLACEHOLDER = '0'; - if (index > 4) - return IP_PLACEHOLDER; - - return fAddr[index]; - } - - RawIPAddress6::RawIPAddress6(char bytes[8]) - { - rt_copy_memory(bytes, fAddr, 8); - } - - char& RawIPAddress6::operator[](const Size& index) - { - kcout << "[RawIPAddress6::operator[]] Fetching Index...\r"; - - static char IP_PLACEHOLDER = '0'; - if (index > 8) - return IP_PLACEHOLDER; - - return fAddr[index]; - } - - bool RawIPAddress6::operator==(const RawIPAddress6& ipv6) - { - for (SizeT index = 0; index < 8; ++index) - { - if (ipv6.fAddr[index] != fAddr[index]) - return false; - } - - return true; - } - - bool RawIPAddress6::operator!=(const RawIPAddress6& ipv6) - { - for (SizeT index = 0; index < 8; ++index) - { - if (ipv6.fAddr[index] == fAddr[index]) - return false; - } - - return true; - } - - ErrorOr IPFactory::ToStringView(Ref& ipv6) - { - auto str = StringBuilder::Construct(ipv6.Leak().Address()); - return str; - } - - ErrorOr IPFactory::ToStringView(Ref& ipv4) - { - auto str = StringBuilder::Construct(ipv4.Leak().Address()); - return str; - } - - bool IPFactory::IpCheckVersion4(const Char* ip) - { - int cnter = 0; - - for (Size base = 0; base < rt_string_len(ip); ++base) - { - if (ip[base] == '.') - { - cnter = 0; - } - else - { - if (cnter == 3) - return false; - - ++cnter; - } - } - - return true; - } -} // namespace Kernel diff --git a/dev/zka/src/Network/IPC.cc b/dev/zka/src/Network/IPC.cc new file mode 100644 index 00000000..3f69bc3c --- /dev/null +++ b/dev/zka/src/Network/IPC.cc @@ -0,0 +1,114 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include + +using namespace Kernel; + +/// @internal +/// @brief The internal sanitize function. +Bool ipc_int_sanitize_packet(IPC_MESSAGE_STRUCT* pckt) +{ + auto endian = cDeduceEndian(pckt, ((Char*)pckt)[0]); + + switch (endian) + { + case Endian::kEndianBig: { + if (pckt->IpcEndianess == eIPCEPLittleEndian) + goto ipc_check_failed; + + break; + } + case Endian::kEndianLittle: { + if (pckt->IpcEndianess == eIPCEPBigEndian) + goto ipc_check_failed; + + break; + } + case Endian::kEndianMixed: { + if (pckt->IpcEndianess == eIPCEPMixedEndian) + goto ipc_check_failed; + + break; + } + default: + goto ipc_check_failed; + } + + if (pckt->IpcFrom == pckt->IpcTo || + pckt->IpcPacketSize > cXPCOMMsgSize) + { + goto ipc_check_failed; + } + + return pckt->IpcPacketSize > 1 && pckt->IpcHeaderMagic == cXPCOMHeaderMagic; + +ipc_check_failed: + ErrLocal() = kErrorIPC; + return false; +} + +namespace Kernel +{ + /// @brief Sanitize packet function + /// @retval true packet is correct. + /// @retval false packet is incorrect and process has crashed. + Bool ipc_sanitize_packet(IPC_MESSAGE_STRUCT* pckt) + { + if (!pckt || + !ipc_int_sanitize_packet(pckt)) + { + UserProcessScheduler::The().CurrentProcess().Leak().Crash(); + return false; + } + + return true; + } + + /// @brief Construct packet function + /// @retval true packet is correct. + /// @retval false packet is incorrect and process has crashed. + Bool ipc_construct_packet(_Output IPC_MESSAGE_STRUCT** pckt_in) + { + // don't do anything if it's valid already. + if (*pckt_in) + return true; + + // crash process if the packet pointer of pointer is NULL. + if (!pckt_in) + { + UserProcessScheduler::The().CurrentProcess().Leak().Crash(); + return false; + } + + *pckt_in = new IPC_MESSAGE_STRUCT(); + + MUST_PASS((*pckt_in)); + + if (*pckt_in) + { + auto endian = cDeduceEndian((*pckt_in), ((Char*)(*pckt_in))[0]); + + (*pckt_in)->IpcHeaderMagic = cXPCOMHeaderMagic; + + (*pckt_in)->IpcEndianess = static_cast(endian); + (*pckt_in)->IpcPacketSize = sizeof(IPC_MESSAGE_STRUCT); + + (*pckt_in)->IpcTo.UserProcessID = 0; + (*pckt_in)->IpcTo.UserProcessTeam = 0; + + (*pckt_in)->IpcFrom.UserProcessID = Kernel::UserProcessScheduler::The().CurrentProcess().Leak().ProcessId; + (*pckt_in)->IpcFrom.UserProcessTeam = Kernel::UserProcessScheduler::The().CurrentTeam().mTeamId; + + return true; + } + + UserProcessScheduler::The().CurrentProcess().Leak().Crash(); + return false; + } +} // namespace Kernel diff --git a/dev/zka/src/Network/IPC.cxx b/dev/zka/src/Network/IPC.cxx deleted file mode 100644 index feb7822f..00000000 --- a/dev/zka/src/Network/IPC.cxx +++ /dev/null @@ -1,114 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include - -using namespace Kernel; - -/// @internal -/// @brief The internal sanitize function. -Bool ipc_int_sanitize_packet(IPC_MESSAGE_STRUCT* pckt) -{ - auto endian = cDeduceEndian(pckt, ((Char*)pckt)[0]); - - switch (endian) - { - case Endian::kEndianBig: { - if (pckt->IpcEndianess == eIPCEPLittleEndian) - goto ipc_check_failed; - - break; - } - case Endian::kEndianLittle: { - if (pckt->IpcEndianess == eIPCEPBigEndian) - goto ipc_check_failed; - - break; - } - case Endian::kEndianMixed: { - if (pckt->IpcEndianess == eIPCEPMixedEndian) - goto ipc_check_failed; - - break; - } - default: - goto ipc_check_failed; - } - - if (pckt->IpcFrom == pckt->IpcTo || - pckt->IpcPacketSize > cXPCOMMsgSize) - { - goto ipc_check_failed; - } - - return pckt->IpcPacketSize > 1 && pckt->IpcHeaderMagic == cXPCOMHeaderMagic; - -ipc_check_failed: - ErrLocal() = kErrorIPC; - return false; -} - -namespace Kernel -{ - /// @brief Sanitize packet function - /// @retval true packet is correct. - /// @retval false packet is incorrect and process has crashed. - Bool ipc_sanitize_packet(IPC_MESSAGE_STRUCT* pckt) - { - if (!pckt || - !ipc_int_sanitize_packet(pckt)) - { - UserProcessScheduler::The().CurrentProcess().Leak().Crash(); - return false; - } - - return true; - } - - /// @brief Construct packet function - /// @retval true packet is correct. - /// @retval false packet is incorrect and process has crashed. - Bool ipc_construct_packet(_Output IPC_MESSAGE_STRUCT** pckt_in) - { - // don't do anything if it's valid already. - if (*pckt_in) - return true; - - // crash process if the packet pointer of pointer is NULL. - if (!pckt_in) - { - UserProcessScheduler::The().CurrentProcess().Leak().Crash(); - return false; - } - - *pckt_in = new IPC_MESSAGE_STRUCT(); - - MUST_PASS((*pckt_in)); - - if (*pckt_in) - { - auto endian = cDeduceEndian((*pckt_in), ((Char*)(*pckt_in))[0]); - - (*pckt_in)->IpcHeaderMagic = cXPCOMHeaderMagic; - - (*pckt_in)->IpcEndianess = static_cast(endian); - (*pckt_in)->IpcPacketSize = sizeof(IPC_MESSAGE_STRUCT); - - (*pckt_in)->IpcTo.UserProcessID = 0; - (*pckt_in)->IpcTo.UserProcessTeam = 0; - - (*pckt_in)->IpcFrom.UserProcessID = Kernel::UserProcessScheduler::The().CurrentProcess().Leak().ProcessId; - (*pckt_in)->IpcFrom.UserProcessTeam = Kernel::UserProcessScheduler::The().CurrentTeam().mTeamId; - - return true; - } - - UserProcessScheduler::The().CurrentProcess().Leak().Crash(); - return false; - } -} // namespace Kernel diff --git a/dev/zka/src/Network/NetworkDevice.cc b/dev/zka/src/Network/NetworkDevice.cc new file mode 100644 index 00000000..b2fba74d --- /dev/null +++ b/dev/zka/src/Network/NetworkDevice.cc @@ -0,0 +1,35 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +namespace Kernel +{ + /// \brief Getter for fNetworkName. + const Char* NetworkDevice::Name() const + { + return this->fNetworkName; + } + + /// \brief Setter for fNetworkName. + Boolean NetworkDevice::Name(const Char* strView) + { + if (strView == nullptr) + return false; + + if (*strView == 0) + return false; + + if (rt_string_len(strView) > cNetworkNameLen) + return false; + + rt_copy_memory((VoidPtr)strView, + (VoidPtr)this->fNetworkName, rt_string_len(strView)); + + return true; + } +} // namespace Kernel diff --git a/dev/zka/src/Network/NetworkDevice.cxx b/dev/zka/src/Network/NetworkDevice.cxx deleted file mode 100644 index 8f968612..00000000 --- a/dev/zka/src/Network/NetworkDevice.cxx +++ /dev/null @@ -1,35 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -namespace Kernel -{ - /// \brief Getter for fNetworkName. - const Char* NetworkDevice::Name() const - { - return this->fNetworkName; - } - - /// \brief Setter for fNetworkName. - Boolean NetworkDevice::Name(const Char* strView) - { - if (strView == nullptr) - return false; - - if (*strView == 0) - return false; - - if (rt_string_len(strView) > cNetworkNameLen) - return false; - - rt_copy_memory((VoidPtr)strView, - (VoidPtr)this->fNetworkName, rt_string_len(strView)); - - return true; - } -} // namespace Kernel diff --git a/dev/zka/src/New+Delete.cc b/dev/zka/src/New+Delete.cc new file mode 100644 index 00000000..89696ed8 --- /dev/null +++ b/dev/zka/src/New+Delete.cc @@ -0,0 +1,50 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +void* operator new[](size_t sz) +{ + if (sz == 0) + ++sz; + + return Kernel::mm_new_heap(sz, true, false); +} + +void* operator new(size_t sz) +{ + if (sz == 0) + ++sz; + + return Kernel::mm_new_heap(sz, true, false); +} + +void operator delete[](void* ptr) +{ + if (ptr == nullptr) + return; + + Kernel::mm_delete_heap(ptr); +} + +void operator delete(void* ptr) +{ + if (ptr == nullptr) + return; + + Kernel::mm_delete_heap(ptr); +} + +void operator delete(void* ptr, size_t sz) +{ + if (ptr == nullptr) + return; + + ZKA_UNUSED(sz); + + Kernel::mm_delete_heap(ptr); +} diff --git a/dev/zka/src/New+Delete.cxx b/dev/zka/src/New+Delete.cxx deleted file mode 100644 index f63b79ed..00000000 --- a/dev/zka/src/New+Delete.cxx +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -void* operator new[](size_t sz) -{ - if (sz == 0) - ++sz; - - return Kernel::mm_new_heap(sz, true, false); -} - -void* operator new(size_t sz) -{ - if (sz == 0) - ++sz; - - return Kernel::mm_new_heap(sz, true, false); -} - -void operator delete[](void* ptr) -{ - if (ptr == nullptr) - return; - - Kernel::mm_delete_heap(ptr); -} - -void operator delete(void* ptr) -{ - if (ptr == nullptr) - return; - - Kernel::mm_delete_heap(ptr); -} - -void operator delete(void* ptr, size_t sz) -{ - if (ptr == nullptr) - return; - - ZKA_UNUSED(sz); - - Kernel::mm_delete_heap(ptr); -} diff --git a/dev/zka/src/OwnPtr.cc b/dev/zka/src/OwnPtr.cc new file mode 100644 index 00000000..67a4235b --- /dev/null +++ b/dev/zka/src/OwnPtr.cc @@ -0,0 +1,7 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include diff --git a/dev/zka/src/OwnPtr.cxx b/dev/zka/src/OwnPtr.cxx deleted file mode 100644 index 128f1b45..00000000 --- a/dev/zka/src/OwnPtr.cxx +++ /dev/null @@ -1,7 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include diff --git a/dev/zka/src/PEFCodeMgr.cc b/dev/zka/src/PEFCodeMgr.cc new file mode 100644 index 00000000..593910be --- /dev/null +++ b/dev/zka/src/PEFCodeMgr.cc @@ -0,0 +1,262 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/// @brief PEF stack size symbol. +#define cPefStackSizeSymbol "SizeOfReserveStack" +#define cPefHeapSizeSymbol "SizeOfReserveHeap" +#define cPefNameSymbol "ProgramName" + +namespace Kernel +{ + namespace Detail + { + /// @brief Get the PEF platform signature according to the compiled backebnd + UInt32 ldr_get_platform(void) noexcept + { +#if defined(__ZKA_32X0__) + return kPefArch32x0; +#elif defined(__ZKA_64X0__) + return kPefArch64x0; +#elif defined(__ZKA_AMD64__) + return kPefArchAMD64; +#elif defined(__ZKA_PPC64__) + return kPefArchPowerPC; +#elif defined(__ZKA_ARM64__) + return kPefArchARM64; +#else + return kPefArchInvalid; +#endif // __32x0__ || __64x0__ || __x86_64__ + } + } // namespace Detail + + /// @brief PEF loader constructor w/ blob. + /// @param blob + PEFLoader::PEFLoader(const VoidPtr blob) + : fCachedBlob(blob) + { + MUST_PASS(fCachedBlob); + fBad = false; + } + + /// @brief PEF loader constructor. + /// @param path the filesystem path. + PEFLoader::PEFLoader(const Char* path) + : fCachedBlob(nullptr), fBad(false), fFatBinary(false) + { + fFile.New(const_cast(path), cRestrictRB); + fPath = StringBuilder::Construct(path).Leak(); + + auto cPefHeader = "PEF_CONTAINER"; + + fCachedBlob = fFile->Read(cPefHeader); + + PEFContainer* container = reinterpret_cast(fCachedBlob); + + if (container->Cpu == Detail::ldr_get_platform() && + container->Magic[0] == kPefMagic[0] && + container->Magic[1] == kPefMagic[1] && + container->Magic[2] == kPefMagic[2] && + container->Magic[3] == kPefMagic[3] && + container->Magic[4] == kPefMagic[4] && container->Abi == kPefAbi) + { + return; + } + else if (container->Magic[4] == kPefMagic[0] && + container->Magic[3] == kPefMagic[1] && + container->Magic[2] == kPefMagic[2] && + container->Magic[1] == kPefMagic[3] && + container->Magic[0] == kPefMagic[4] && container->Abi == kPefAbi) + { + /// This is a fat binary. + this->fFatBinary = true; + return; + } + + fBad = true; + + if (fCachedBlob) + mm_delete_heap(fCachedBlob); + + kcout << "PEFLoader: warn: Executable format error!\r"; + + fCachedBlob = nullptr; + } + + /// @brief PEF destructor. + PEFLoader::~PEFLoader() + { + if (fCachedBlob) + mm_delete_heap(fCachedBlob); + + fFile.Delete(); + } + + VoidPtr PEFLoader::FindSymbol(const Char* name, Int32 kind) + { + if (!fCachedBlob || fBad || !name) + return nullptr; + + PEFContainer* container = reinterpret_cast(fCachedBlob); + + auto blob = fFile->Read(name); + + PEFCommandHeader* container_header = reinterpret_cast(blob); + + constexpr auto cMangleCharacter = '$'; + const Char* cContainerKinds[] = {".code64", ".data64", ".zero64", nullptr}; + + ErrorOr error_or_symbol; + + switch (kind) + { + case kPefCode: { + error_or_symbol = StringBuilder::Construct(cContainerKinds[0]); // code symbol. + break; + } + case kPefData: { + error_or_symbol = StringBuilder::Construct(cContainerKinds[1]); // data symbol. + break; + } + case kPefZero: { + error_or_symbol = StringBuilder::Construct(cContainerKinds[2]); // block starting symbol. + break; + } + default: + return nullptr; // prevent that from the kernel's mode perspective, let that happen if it were + // a user process. + } + + Char* unconst_symbol = const_cast(name); + + for (SizeT i = 0UL; i < rt_string_len(unconst_symbol, kPefNameLen); ++i) + { + if (unconst_symbol[i] == ' ') + { + unconst_symbol[i] = cMangleCharacter; + } + } + + error_or_symbol.Leak().Leak() += name; + + for (SizeT index = 0; index < container->Count; ++index) + { + if (StringBuilder::Equals(container_header->Name, + error_or_symbol.Leak().Leak().CData())) + { + if (container_header->Kind == kind) + { + if (container_header->Cpu != Detail::ldr_get_platform()) + { + if (!this->fFatBinary) + { + mm_delete_heap(blob); + return nullptr; + } + } + + Char* container_blob_value = new Char[container_header->Size]; + + rt_copy_memory((VoidPtr)((Char*)blob + sizeof(PEFCommandHeader)), container_blob_value, container_header->Size); + mm_delete_heap(blob); + + kcout << "PEFLoader: INFO: Load stub: " << container_header->Name << "!\r"; + + return container_blob_value; + } + } + } + + mm_delete_heap(blob); + return nullptr; + } + + /// @brief Finds the executable entrypoint. + /// @return + ErrorOr PEFLoader::FindStart() + { + if (auto sym = this->FindSymbol(kPefStart, kPefCode); sym) + return ErrorOr(sym); + + return ErrorOr(kErrorExecutable); + } + + /// @brief Tells if the executable is loaded or not. + /// @return + bool PEFLoader::IsLoaded() noexcept + { + return !fBad && fCachedBlob; + } + + namespace Utils + { + Bool execute_from_image(PEFLoader& exec, const Int32& procKind) noexcept + { + auto errOrStart = exec.FindStart(); + + if (errOrStart.Error() != kErrorSuccess) + return false; + + UserProcess proc; + + proc.SetImageStart(errOrStart.Leak().Leak()); + proc.Kind = procKind; + proc.StackSize = *(UIntPtr*)exec.FindSymbol(cPefStackSizeSymbol, kPefData); + proc.MemoryLimit = *(UIntPtr*)exec.FindSymbol(cPefHeapSizeSymbol, kPefData); + + rt_set_memory(proc.Name, 0, kProcessLen); + + if (exec.FindSymbol(cPefNameSymbol, kPefData)) + rt_copy_memory((VoidPtr)exec.FindSymbol(cPefNameSymbol, kPefData), proc.Name, rt_string_len((Char*)exec.FindSymbol(cPefNameSymbol, kPefData))); + else + rt_copy_memory((VoidPtr) "UNNAMED PROCESS.", proc.Name, rt_string_len("UNNAMED PROCESS.")); + + if (!proc.StackSize) + { + const auto cDefaultStackSizeMib = 8; + + proc.StackSize = mib_cast(cDefaultStackSizeMib); + } + + return UserProcessScheduler::The().Add(proc) > 0; + } + } // namespace Utils + + const Char* PEFLoader::Path() + { + return fPath.Leak().CData(); + } + + const Char* PEFLoader::AsString() + { +#ifdef __32x0__ + return "32x0 PEF executable."; +#elif defined(__64x0__) + return "64x0 PEF executable."; +#elif defined(__x86_64__) + return "x86_64 PEF executable."; +#elif defined(__aarch64__) + return "aarch64 PEF executable."; +#elif defined(__powerpc64__) + return "POWER64 PEF executable."; +#else + return "???? PEF executable."; +#endif // __32x0__ || __64x0__ || __x86_64__ || __powerpc64__ + } + + const Char* PEFLoader::MIME() + { + return kPefApplicationMime; + } +} // namespace Kernel diff --git a/dev/zka/src/PEFCodeMgr.cxx b/dev/zka/src/PEFCodeMgr.cxx deleted file mode 100644 index edea684e..00000000 --- a/dev/zka/src/PEFCodeMgr.cxx +++ /dev/null @@ -1,262 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include -#include -#include -#include -#include -#include - -/// @brief PEF stack size symbol. -#define cPefStackSizeSymbol "SizeOfReserveStack" -#define cPefHeapSizeSymbol "SizeOfReserveHeap" -#define cPefNameSymbol "ProgramName" - -namespace Kernel -{ - namespace Detail - { - /// @brief Get the PEF platform signature according to the compiled backebnd - UInt32 ldr_get_platform(void) noexcept - { -#if defined(__ZKA_32X0__) - return kPefArch32x0; -#elif defined(__ZKA_64X0__) - return kPefArch64x0; -#elif defined(__ZKA_AMD64__) - return kPefArchAMD64; -#elif defined(__ZKA_PPC64__) - return kPefArchPowerPC; -#elif defined(__ZKA_ARM64__) - return kPefArchARM64; -#else - return kPefArchInvalid; -#endif // __32x0__ || __64x0__ || __x86_64__ - } - } // namespace Detail - - /// @brief PEF loader constructor w/ blob. - /// @param blob - PEFLoader::PEFLoader(const VoidPtr blob) - : fCachedBlob(blob) - { - MUST_PASS(fCachedBlob); - fBad = false; - } - - /// @brief PEF loader constructor. - /// @param path the filesystem path. - PEFLoader::PEFLoader(const Char* path) - : fCachedBlob(nullptr), fBad(false), fFatBinary(false) - { - fFile.New(const_cast(path), cRestrictRB); - fPath = StringBuilder::Construct(path).Leak(); - - auto cPefHeader = "PEF_CONTAINER"; - - fCachedBlob = fFile->Read(cPefHeader); - - PEFContainer* container = reinterpret_cast(fCachedBlob); - - if (container->Cpu == Detail::ldr_get_platform() && - container->Magic[0] == kPefMagic[0] && - container->Magic[1] == kPefMagic[1] && - container->Magic[2] == kPefMagic[2] && - container->Magic[3] == kPefMagic[3] && - container->Magic[4] == kPefMagic[4] && container->Abi == kPefAbi) - { - return; - } - else if (container->Magic[4] == kPefMagic[0] && - container->Magic[3] == kPefMagic[1] && - container->Magic[2] == kPefMagic[2] && - container->Magic[1] == kPefMagic[3] && - container->Magic[0] == kPefMagic[4] && container->Abi == kPefAbi) - { - /// This is a fat binary. - this->fFatBinary = true; - return; - } - - fBad = true; - - if (fCachedBlob) - mm_delete_heap(fCachedBlob); - - kcout << "PEFLoader: warn: Executable format error!\r"; - - fCachedBlob = nullptr; - } - - /// @brief PEF destructor. - PEFLoader::~PEFLoader() - { - if (fCachedBlob) - mm_delete_heap(fCachedBlob); - - fFile.Delete(); - } - - VoidPtr PEFLoader::FindSymbol(const Char* name, Int32 kind) - { - if (!fCachedBlob || fBad || !name) - return nullptr; - - PEFContainer* container = reinterpret_cast(fCachedBlob); - - auto blob = fFile->Read(name); - - PEFCommandHeader* container_header = reinterpret_cast(blob); - - constexpr auto cMangleCharacter = '$'; - const Char* cContainerKinds[] = {".code64", ".data64", ".zero64", nullptr}; - - ErrorOr error_or_symbol; - - switch (kind) - { - case kPefCode: { - error_or_symbol = StringBuilder::Construct(cContainerKinds[0]); // code symbol. - break; - } - case kPefData: { - error_or_symbol = StringBuilder::Construct(cContainerKinds[1]); // data symbol. - break; - } - case kPefZero: { - error_or_symbol = StringBuilder::Construct(cContainerKinds[2]); // block starting symbol. - break; - } - default: - return nullptr; // prevent that from the kernel's mode perspective, let that happen if it were - // a user process. - } - - Char* unconst_symbol = const_cast(name); - - for (SizeT i = 0UL; i < rt_string_len(unconst_symbol, kPefNameLen); ++i) - { - if (unconst_symbol[i] == ' ') - { - unconst_symbol[i] = cMangleCharacter; - } - } - - error_or_symbol.Leak().Leak() += name; - - for (SizeT index = 0; index < container->Count; ++index) - { - if (StringBuilder::Equals(container_header->Name, - error_or_symbol.Leak().Leak().CData())) - { - if (container_header->Kind == kind) - { - if (container_header->Cpu != Detail::ldr_get_platform()) - { - if (!this->fFatBinary) - { - mm_delete_heap(blob); - return nullptr; - } - } - - Char* container_blob_value = new Char[container_header->Size]; - - rt_copy_memory((VoidPtr)((Char*)blob + sizeof(PEFCommandHeader)), container_blob_value, container_header->Size); - mm_delete_heap(blob); - - kcout << "PEFLoader: INFO: Load stub: " << container_header->Name << "!\r"; - - return container_blob_value; - } - } - } - - mm_delete_heap(blob); - return nullptr; - } - - /// @brief Finds the executable entrypoint. - /// @return - ErrorOr PEFLoader::FindStart() - { - if (auto sym = this->FindSymbol(kPefStart, kPefCode); sym) - return ErrorOr(sym); - - return ErrorOr(kErrorExecutable); - } - - /// @brief Tells if the executable is loaded or not. - /// @return - bool PEFLoader::IsLoaded() noexcept - { - return !fBad && fCachedBlob; - } - - namespace Utils - { - Bool execute_from_image(PEFLoader& exec, const Int32& procKind) noexcept - { - auto errOrStart = exec.FindStart(); - - if (errOrStart.Error() != kErrorSuccess) - return false; - - UserProcess proc; - - proc.SetImageStart(errOrStart.Leak().Leak()); - proc.Kind = procKind; - proc.StackSize = *(UIntPtr*)exec.FindSymbol(cPefStackSizeSymbol, kPefData); - proc.MemoryLimit = *(UIntPtr*)exec.FindSymbol(cPefHeapSizeSymbol, kPefData); - - rt_set_memory(proc.Name, 0, kProcessLen); - - if (exec.FindSymbol(cPefNameSymbol, kPefData)) - rt_copy_memory((VoidPtr)exec.FindSymbol(cPefNameSymbol, kPefData), proc.Name, rt_string_len((Char*)exec.FindSymbol(cPefNameSymbol, kPefData))); - else - rt_copy_memory((VoidPtr) "UNNAMED PROCESS.", proc.Name, rt_string_len("UNNAMED PROCESS.")); - - if (!proc.StackSize) - { - const auto cDefaultStackSizeMib = 8; - - proc.StackSize = mib_cast(cDefaultStackSizeMib); - } - - return UserProcessScheduler::The().Add(proc) > 0; - } - } // namespace Utils - - const Char* PEFLoader::Path() - { - return fPath.Leak().CData(); - } - - const Char* PEFLoader::AsString() - { -#ifdef __32x0__ - return "32x0 PEF executable."; -#elif defined(__64x0__) - return "64x0 PEF executable."; -#elif defined(__x86_64__) - return "x86_64 PEF executable."; -#elif defined(__aarch64__) - return "aarch64 PEF executable."; -#elif defined(__powerpc64__) - return "POWER64 PEF executable."; -#else - return "???? PEF executable."; -#endif // __32x0__ || __64x0__ || __x86_64__ || __powerpc64__ - } - - const Char* PEFLoader::MIME() - { - return kPefApplicationMime; - } -} // namespace Kernel diff --git a/dev/zka/src/PRDT.cc b/dev/zka/src/PRDT.cc new file mode 100644 index 00000000..741e932b --- /dev/null +++ b/dev/zka/src/PRDT.cc @@ -0,0 +1,22 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include + +namespace Kernel +{ + /// @brief constructs a new PRD. + /// @param prd PRD reference. + /// @note This doesnt construct a valid, please fill it by yourself. + void construct_prdt(Ref& prd) + { + prd.Leak().fPhysAddress = 0x0; + prd.Leak().fSectorCount = 0x0; + prd.Leak().fEndBit = 0x0; + } +} // namespace Kernel diff --git a/dev/zka/src/PRDT.cxx b/dev/zka/src/PRDT.cxx deleted file mode 100644 index c12a4159..00000000 --- a/dev/zka/src/PRDT.cxx +++ /dev/null @@ -1,22 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include - -namespace Kernel -{ - /// @brief constructs a new PRD. - /// @param prd PRD reference. - /// @note This doesnt construct a valid, please fill it by yourself. - void construct_prdt(Ref& prd) - { - prd.Leak().fPhysAddress = 0x0; - prd.Leak().fSectorCount = 0x0; - prd.Leak().fEndBit = 0x0; - } -} // namespace Kernel diff --git a/dev/zka/src/PageMgr.cc b/dev/zka/src/PageMgr.cc new file mode 100644 index 00000000..18b65dc6 --- /dev/null +++ b/dev/zka/src/PageMgr.cc @@ -0,0 +1,110 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +#ifdef __ZKA_AMD64__ +#include +#elif defined(__ZKA_ARM64__) +#include +#endif // ifdef __ZKA_AMD64__ || defined(__ZKA_ARM64__) + +namespace Kernel +{ + PTEWrapper::PTEWrapper(Boolean Rw, Boolean User, Boolean ExecDisable, UIntPtr VirtAddr) + : fRw(Rw), + fUser(User), + fExecDisable(ExecDisable), + fVirtAddr(VirtAddr), + fCache(false), + fShareable(false), + fWt(false), + fPresent(true), + fAccessed(false) + { + } + + PTEWrapper::~PTEWrapper() = default; + + /// @brief Flush virtual address. + /// @param VirtAddr + Void PageMgr::FlushTLB() + { +#ifndef __ZKA_MINIMAL_OS__ + hal_flush_tlb(); +#endif // !__ZKA_MINIMAL_OS__ + } + + /// @brief Reclaim freed page. + /// @return + Bool PTEWrapper::Reclaim() + { + if (!this->fPresent) + { + this->fPresent = true; + return true; + } + + return false; + } + + /// @brief Request a PTE. + /// @param Rw r/w? + /// @param User user mode? + /// @param ExecDisable disable execution on page? + /// @return + PTEWrapper PageMgr::Request(Boolean Rw, Boolean User, Boolean ExecDisable, SizeT Sz) + { + // Store PTE wrapper right after PTE. + VoidPtr ptr = Kernel::HAL::mm_alloc_bitmap(Rw, User, Sz, false); + + return PTEWrapper{Rw, User, ExecDisable, reinterpret_cast(ptr)}; + } + + /// @brief Disable BitMap. + /// @param wrapper the wrapper. + /// @return If the page bitmap was cleared or not. + Bool PageMgr::Free(Ref& wrapper) + { + if (!Kernel::HAL::mm_free_bitmap((VoidPtr)wrapper.Leak().VirtualAddress())) + return false; + + return true; + } + + /// @brief Virtual PTE address. + /// @return The virtual address of the page. + const UIntPtr PTEWrapper::VirtualAddress() + { + return (fVirtAddr); + } + + bool PTEWrapper::Shareable() + { + return fShareable; + } + + bool PTEWrapper::Present() + { + return fPresent; + } + + bool PTEWrapper::Access() + { + return fAccessed; + } + + void PTEWrapper::NoExecute(const bool enable) + { + this->fExecDisable = enable; + } + + const bool& PTEWrapper::NoExecute() + { + return this->fExecDisable; + } +} // namespace Kernel diff --git a/dev/zka/src/PageMgr.cxx b/dev/zka/src/PageMgr.cxx deleted file mode 100644 index 6d9f4cc6..00000000 --- a/dev/zka/src/PageMgr.cxx +++ /dev/null @@ -1,110 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -#ifdef __ZKA_AMD64__ -#include -#elif defined(__ZKA_ARM64__) -#include -#endif // ifdef __ZKA_AMD64__ || defined(__ZKA_ARM64__) - -namespace Kernel -{ - PTEWrapper::PTEWrapper(Boolean Rw, Boolean User, Boolean ExecDisable, UIntPtr VirtAddr) - : fRw(Rw), - fUser(User), - fExecDisable(ExecDisable), - fVirtAddr(VirtAddr), - fCache(false), - fShareable(false), - fWt(false), - fPresent(true), - fAccessed(false) - { - } - - PTEWrapper::~PTEWrapper() = default; - - /// @brief Flush virtual address. - /// @param VirtAddr - Void PageMgr::FlushTLB() - { -#ifndef __ZKA_MINIMAL_OS__ - hal_flush_tlb(); -#endif // !__ZKA_MINIMAL_OS__ - } - - /// @brief Reclaim freed page. - /// @return - Bool PTEWrapper::Reclaim() - { - if (!this->fPresent) - { - this->fPresent = true; - return true; - } - - return false; - } - - /// @brief Request a PTE. - /// @param Rw r/w? - /// @param User user mode? - /// @param ExecDisable disable execution on page? - /// @return - PTEWrapper PageMgr::Request(Boolean Rw, Boolean User, Boolean ExecDisable, SizeT Sz) - { - // Store PTE wrapper right after PTE. - VoidPtr ptr = Kernel::HAL::mm_alloc_bitmap(Rw, User, Sz, false); - - return PTEWrapper{Rw, User, ExecDisable, reinterpret_cast(ptr)}; - } - - /// @brief Disable BitMap. - /// @param wrapper the wrapper. - /// @return If the page bitmap was cleared or not. - Bool PageMgr::Free(Ref& wrapper) - { - if (!Kernel::HAL::mm_free_bitmap((VoidPtr)wrapper.Leak().VirtualAddress())) - return false; - - return true; - } - - /// @brief Virtual PTE address. - /// @return The virtual address of the page. - const UIntPtr PTEWrapper::VirtualAddress() - { - return (fVirtAddr); - } - - bool PTEWrapper::Shareable() - { - return fShareable; - } - - bool PTEWrapper::Present() - { - return fPresent; - } - - bool PTEWrapper::Access() - { - return fAccessed; - } - - void PTEWrapper::NoExecute(const bool enable) - { - this->fExecDisable = enable; - } - - const bool& PTEWrapper::NoExecute() - { - return this->fExecDisable; - } -} // namespace Kernel diff --git a/dev/zka/src/Pmm.cc b/dev/zka/src/Pmm.cc new file mode 100644 index 00000000..4af7d909 --- /dev/null +++ b/dev/zka/src/Pmm.cc @@ -0,0 +1,94 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +#if defined(__ZKA_ARM64__) +#include +#endif // defined(__ZKA_ARM64__) + +#if defined(__ZKA_AMD64__) +#include +#endif // defined(__ZKA_AMD64__) + +namespace Kernel +{ + /// @brief Pmm constructor. + Pmm::Pmm() + : fPageMgr() + { + kcout << "[PMM] Allocate PageMemoryMgr"; + } + + Pmm::~Pmm() = default; + + /* If this returns Null pointer, enter emergency mode */ + /// @param user is this a user page? + /// @param readWrite is it r/w? + Ref Pmm::RequestPage(Boolean user, Boolean readWrite) + { + PTEWrapper pt = fPageMgr.Leak().Request(user, readWrite, false, kPageSize); + + if (pt.fPresent) + { + kcout << "[PMM]: Allocation failed.\r"; + return {}; + } + + return Ref(pt); + } + + Boolean Pmm::FreePage(Ref PageRef) + { + if (!PageRef) + return false; + + PageRef.Leak().fPresent = false; + + return true; + } + + Boolean Pmm::TogglePresent(Ref PageRef, Boolean Enable) + { + if (!PageRef) + return false; + + PageRef.Leak().fPresent = Enable; + + return true; + } + + Boolean Pmm::ToggleUser(Ref PageRef, Boolean Enable) + { + if (!PageRef) + return false; + + PageRef.Leak().fRw = Enable; + + return true; + } + + Boolean Pmm::ToggleRw(Ref PageRef, Boolean Enable) + { + if (!PageRef) + return false; + + PageRef.Leak().fRw = Enable; + + return true; + } + + Boolean Pmm::ToggleShare(Ref PageRef, Boolean Enable) + { + if (!PageRef) + return false; + + PageRef.Leak().fShareable = Enable; + + return true; + } +} // namespace Kernel diff --git a/dev/zka/src/Pmm.cxx b/dev/zka/src/Pmm.cxx deleted file mode 100644 index cf39714f..00000000 --- a/dev/zka/src/Pmm.cxx +++ /dev/null @@ -1,94 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -#if defined(__ZKA_ARM64__) -#include -#endif // defined(__ZKA_ARM64__) - -#if defined(__ZKA_AMD64__) -#include -#endif // defined(__ZKA_AMD64__) - -namespace Kernel -{ - /// @brief Pmm constructor. - Pmm::Pmm() - : fPageMgr() - { - kcout << "[PMM] Allocate PageMemoryMgr"; - } - - Pmm::~Pmm() = default; - - /* If this returns Null pointer, enter emergency mode */ - /// @param user is this a user page? - /// @param readWrite is it r/w? - Ref Pmm::RequestPage(Boolean user, Boolean readWrite) - { - PTEWrapper pt = fPageMgr.Leak().Request(user, readWrite, false, kPageSize); - - if (pt.fPresent) - { - kcout << "[PMM]: Allocation failed.\r"; - return {}; - } - - return Ref(pt); - } - - Boolean Pmm::FreePage(Ref PageRef) - { - if (!PageRef) - return false; - - PageRef.Leak().fPresent = false; - - return true; - } - - Boolean Pmm::TogglePresent(Ref PageRef, Boolean Enable) - { - if (!PageRef) - return false; - - PageRef.Leak().fPresent = Enable; - - return true; - } - - Boolean Pmm::ToggleUser(Ref PageRef, Boolean Enable) - { - if (!PageRef) - return false; - - PageRef.Leak().fRw = Enable; - - return true; - } - - Boolean Pmm::ToggleRw(Ref PageRef, Boolean Enable) - { - if (!PageRef) - return false; - - PageRef.Leak().fRw = Enable; - - return true; - } - - Boolean Pmm::ToggleShare(Ref PageRef, Boolean Enable) - { - if (!PageRef) - return false; - - PageRef.Leak().fShareable = Enable; - - return true; - } -} // namespace Kernel diff --git a/dev/zka/src/Property.cc b/dev/zka/src/Property.cc new file mode 100644 index 00000000..084616a4 --- /dev/null +++ b/dev/zka/src/Property.cc @@ -0,0 +1,27 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +namespace Kernel +{ + Property::~Property() = default; + + Bool Property::StringEquals(StringView& name) + { + return this->fName && this->fName == name; + } + + StringView& Property::GetKey() + { + return this->fName; + } + + PropertyId& Property::GetValue() + { + return fAction; + } +} // namespace Kernel diff --git a/dev/zka/src/Property.cxx b/dev/zka/src/Property.cxx deleted file mode 100644 index 7cc78966..00000000 --- a/dev/zka/src/Property.cxx +++ /dev/null @@ -1,27 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -namespace Kernel -{ - Property::~Property() = default; - - Bool Property::StringEquals(StringView& name) - { - return this->fName && this->fName == name; - } - - StringView& Property::GetKey() - { - return this->fName; - } - - PropertyId& Property::GetValue() - { - return fAction; - } -} // namespace Kernel diff --git a/dev/zka/src/Ref.cc b/dev/zka/src/Ref.cc new file mode 100644 index 00000000..2ac42395 --- /dev/null +++ b/dev/zka/src/Ref.cc @@ -0,0 +1,7 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include diff --git a/dev/zka/src/Ref.cxx b/dev/zka/src/Ref.cxx deleted file mode 100644 index bdb60236..00000000 --- a/dev/zka/src/Ref.cxx +++ /dev/null @@ -1,7 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include diff --git a/dev/zka/src/Semaphore.cc b/dev/zka/src/Semaphore.cc new file mode 100644 index 00000000..08f33cf1 --- /dev/null +++ b/dev/zka/src/Semaphore.cc @@ -0,0 +1,62 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +namespace Kernel +{ + Bool Semaphore::Unlock() noexcept + { + if (fLockingProcess) + fLockingProcess = nullptr; + + return fLockingProcess == nullptr; + } + + Bool Semaphore::Lock(UserProcess* process) + { + if (!process || fLockingProcess) + return false; + + fLockingProcess = process; + + return true; + } + + Bool Semaphore::IsLocked() const + { + return fLockingProcess; + } + + Bool Semaphore::LockOrWait(UserProcess* process, TimerInterface* timer) + { + if (process == nullptr) + return false; + + if (timer == nullptr) + return false; + + this->Lock(process); + + timer->Wait(); + + return this->Lock(process); + } + + /// @brief Wait with process, either wait for it to be being invalid, or not being run. + Void Semaphore::WaitForProcess() noexcept + { + while (fLockingProcess) + { + if (fLockingProcess->GetStatus() != ProcessStatusKind::kRunning) + { + this->Unlock(); + break; + } + } + } +} // namespace Kernel diff --git a/dev/zka/src/Semaphore.cxx b/dev/zka/src/Semaphore.cxx deleted file mode 100644 index 5a598001..00000000 --- a/dev/zka/src/Semaphore.cxx +++ /dev/null @@ -1,62 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -namespace Kernel -{ - Bool Semaphore::Unlock() noexcept - { - if (fLockingProcess) - fLockingProcess = nullptr; - - return fLockingProcess == nullptr; - } - - Bool Semaphore::Lock(UserProcess* process) - { - if (!process || fLockingProcess) - return false; - - fLockingProcess = process; - - return true; - } - - Bool Semaphore::IsLocked() const - { - return fLockingProcess; - } - - Bool Semaphore::LockOrWait(UserProcess* process, TimerInterface* timer) - { - if (process == nullptr) - return false; - - if (timer == nullptr) - return false; - - this->Lock(process); - - timer->Wait(); - - return this->Lock(process); - } - - /// @brief Wait with process, either wait for it to be being invalid, or not being run. - Void Semaphore::WaitForProcess() noexcept - { - while (fLockingProcess) - { - if (fLockingProcess->GetStatus() != ProcessStatusKind::kRunning) - { - this->Unlock(); - break; - } - } - } -} // namespace Kernel diff --git a/dev/zka/src/Stop.cc b/dev/zka/src/Stop.cc new file mode 100644 index 00000000..3ec67249 --- /dev/null +++ b/dev/zka/src/Stop.cc @@ -0,0 +1,126 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#define cWebsiteMacro "https://help.zws.com/" + +/* Each error code is attributed with an ID, which will prompt a string onto the + * screen. Wait for debugger... */ + +namespace Kernel +{ + void ke_stop(const Kernel::Int& id) + { + CGInit(); + + auto panic_text = RGB(0xff, 0xff, 0xff); + + auto start_y = 10; + auto x = 10; + + CGDrawString("minoskrnl.exe stopped working properly so it had to stop.", start_y, x, panic_text); + start_y += 10; + + // simply offset from previous string and then write the website. + CGDrawString("Please visit: ", start_y, x, panic_text); + CGDrawString(cWebsiteMacro, start_y, x + (FONT_SIZE_X * rt_string_len("Please visit: ")), panic_text); + + CGFini(); + + start_y += 10; + + // show text according to error id. + + switch (id) + { + case RUNTIME_CHECK_PROCESS: { + CGDrawString("0x00000008 Multi-Task error.", start_y, x, panic_text); + break; + } + case RUNTIME_CHECK_ACPI: { + CGDrawString("0x00000006 ACPI configuration error.", start_y, x, panic_text); + break; + } + case RUNTIME_CHECK_PAGE: { + CGDrawString("0x0000000B Write/Read in non paged area.", start_y, x, panic_text); + break; + } + case RUNTIME_CHECK_FILESYSTEM: { + CGDrawString("0x0000000A Filesystem error.", start_y, x, panic_text); + break; + } + case RUNTIME_CHECK_POINTER: { + CGDrawString("0x00000000 Heap is corrupted.", start_y, x, panic_text); + break; + } + case RUNTIME_CHECK_BAD_BEHAVIOR: { + CGDrawString("0x00000009 Bad Behavior.", start_y, x, panic_text); + break; + } + case RUNTIME_CHECK_BOOTSTRAP: { + CGDrawString("0x0000000A Boot code has finished executing, waiting for scheduler and other cores.", start_y, x, panic_text); + return; + } + case RUNTIME_CHECK_HANDSHAKE: { + CGDrawString("0x00000005 Handshake fault.", start_y, x, panic_text); + break; + } + case RUNTIME_CHECK_IPC: { + CGDrawString("0x00000003 Bad IPC/XPCOM message.", start_y, x, panic_text); + break; + } + case RUNTIME_CHECK_INVALID_PRIVILEGE: { + CGDrawString("0x00000007 Privilege access violation.", start_y, x, panic_text); + break; + case RUNTIME_CHECK_UNEXCPECTED: { + CGDrawString("0x0000000B Unexpected violation.", start_y, x, panic_text); + break; + } + case RUNTIME_CHECK_VIRTUAL_OUT_OF_MEM: { + CGDrawString("0x10000001 Out of virtual memory.", start_y, x, panic_text); + + break; + } + case RUNTIME_CHECK_FAILED: { + CGDrawString("0x10000001 Kernel Bug check appears to have failed, a dump has been written to the storage.", start_y, x, panic_text); + break; + } + default: { + CGDrawString("0xFFFFFFFC Unknown Kernel Error.", start_y, x, panic_text); + break; + } + } + }; + + RecoveryFactory::Recover(); + } + + Void RecoveryFactory::Recover() noexcept + { + HAL::rt_halt(); + } + + void ke_runtime_check(bool expr, const Char* file, const Char* line) + { + if (!expr) + { + kcout << "FAILED: FILE: " << file << endl; + kcout << "FAILED: LINE: " << line << endl; + + ke_stop(RUNTIME_CHECK_FAILED); // Runtime Check failed + } + } +} // namespace Kernel diff --git a/dev/zka/src/Stop.cxx b/dev/zka/src/Stop.cxx deleted file mode 100644 index 39e57070..00000000 --- a/dev/zka/src/Stop.cxx +++ /dev/null @@ -1,126 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#define cWebsiteMacro "https://help.zws.com/" - -/* Each error code is attributed with an ID, which will prompt a string onto the - * screen. Wait for debugger... */ - -namespace Kernel -{ - void ke_stop(const Kernel::Int& id) - { - CGInit(); - - auto panic_text = RGB(0xff, 0xff, 0xff); - - auto start_y = 10; - auto x = 10; - - CGDrawString("minoskrnl.exe stopped working properly so it had to stop.", start_y, x, panic_text); - start_y += 10; - - // simply offset from previous string and then write the website. - CGDrawString("Please visit: ", start_y, x, panic_text); - CGDrawString(cWebsiteMacro, start_y, x + (FONT_SIZE_X * rt_string_len("Please visit: ")), panic_text); - - CGFini(); - - start_y += 10; - - // show text according to error id. - - switch (id) - { - case RUNTIME_CHECK_PROCESS: { - CGDrawString("0x00000008 Multi-Task error.", start_y, x, panic_text); - break; - } - case RUNTIME_CHECK_ACPI: { - CGDrawString("0x00000006 ACPI configuration error.", start_y, x, panic_text); - break; - } - case RUNTIME_CHECK_PAGE: { - CGDrawString("0x0000000B Write/Read in non paged area.", start_y, x, panic_text); - break; - } - case RUNTIME_CHECK_FILESYSTEM: { - CGDrawString("0x0000000A Filesystem error.", start_y, x, panic_text); - break; - } - case RUNTIME_CHECK_POINTER: { - CGDrawString("0x00000000 Heap is corrupted.", start_y, x, panic_text); - break; - } - case RUNTIME_CHECK_BAD_BEHAVIOR: { - CGDrawString("0x00000009 Bad Behavior.", start_y, x, panic_text); - break; - } - case RUNTIME_CHECK_BOOTSTRAP: { - CGDrawString("0x0000000A Boot code has finished executing, waiting for scheduler and other cores.", start_y, x, panic_text); - return; - } - case RUNTIME_CHECK_HANDSHAKE: { - CGDrawString("0x00000005 Handshake fault.", start_y, x, panic_text); - break; - } - case RUNTIME_CHECK_IPC: { - CGDrawString("0x00000003 Bad IPC/XPCOM message.", start_y, x, panic_text); - break; - } - case RUNTIME_CHECK_INVALID_PRIVILEGE: { - CGDrawString("0x00000007 Privilege access violation.", start_y, x, panic_text); - break; - case RUNTIME_CHECK_UNEXCPECTED: { - CGDrawString("0x0000000B Unexpected violation.", start_y, x, panic_text); - break; - } - case RUNTIME_CHECK_VIRTUAL_OUT_OF_MEM: { - CGDrawString("0x10000001 Out of virtual memory.", start_y, x, panic_text); - - break; - } - case RUNTIME_CHECK_FAILED: { - CGDrawString("0x10000001 Kernel Bug check appears to have failed, a dump has been written to the storage.", start_y, x, panic_text); - break; - } - default: { - CGDrawString("0xFFFFFFFC Unknown Kernel Error.", start_y, x, panic_text); - break; - } - } - }; - - RecoveryFactory::Recover(); - } - - Void RecoveryFactory::Recover() noexcept - { - HAL::rt_halt(); - } - - void ke_runtime_check(bool expr, const Char* file, const Char* line) - { - if (!expr) - { - kcout << "FAILED: FILE: " << file << endl; - kcout << "FAILED: LINE: " << line << endl; - - ke_stop(RUNTIME_CHECK_FAILED); // Runtime Check failed - } - } -} // namespace Kernel diff --git a/dev/zka/src/Storage/AHCIDeviceInterface.cc b/dev/zka/src/Storage/AHCIDeviceInterface.cc new file mode 100644 index 00000000..a790236d --- /dev/null +++ b/dev/zka/src/Storage/AHCIDeviceInterface.cc @@ -0,0 +1,35 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +using namespace Kernel; + +/// @brief Class constructor +/// @param Out Drive output +/// @param In Drive input +/// @param Cleanup Drive cleanup. +AHCIDeviceInterface::AHCIDeviceInterface(void (*Out)(MountpointInterface* outpacket), + void (*In)(MountpointInterface* inpacket), + void (*Cleanup)(void)) + : DeviceInterface(Out, In), fCleanup(Cleanup) +{ +} + +/// @brief Class desctructor +AHCIDeviceInterface::~AHCIDeviceInterface() +{ + MUST_PASS(fCleanup); + if (fCleanup) + fCleanup(); +} + +/// @brief Returns the name of the device interface. +/// @return it's name as a string. +const Char* AHCIDeviceInterface::Name() const +{ + return "AHCIDeviceInterface"; +} diff --git a/dev/zka/src/Storage/AHCIDeviceInterface.cxx b/dev/zka/src/Storage/AHCIDeviceInterface.cxx deleted file mode 100644 index 9165ea32..00000000 --- a/dev/zka/src/Storage/AHCIDeviceInterface.cxx +++ /dev/null @@ -1,35 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -using namespace Kernel; - -/// @brief Class constructor -/// @param Out Drive output -/// @param In Drive input -/// @param Cleanup Drive cleanup. -AHCIDeviceInterface::AHCIDeviceInterface(void (*Out)(MountpointInterface* outpacket), - void (*In)(MountpointInterface* inpacket), - void (*Cleanup)(void)) - : DeviceInterface(Out, In), fCleanup(Cleanup) -{ -} - -/// @brief Class desctructor -AHCIDeviceInterface::~AHCIDeviceInterface() -{ - MUST_PASS(fCleanup); - if (fCleanup) - fCleanup(); -} - -/// @brief Returns the name of the device interface. -/// @return it's name as a string. -const Char* AHCIDeviceInterface::Name() const -{ - return "AHCIDeviceInterface"; -} diff --git a/dev/zka/src/Storage/ATADeviceInterface.cc b/dev/zka/src/Storage/ATADeviceInterface.cc new file mode 100644 index 00000000..2c027351 --- /dev/null +++ b/dev/zka/src/Storage/ATADeviceInterface.cc @@ -0,0 +1,88 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +using namespace Kernel; + +/// @brief Class constructor +/// @param Out Drive output +/// @param In Drive input +/// @param Cleanup Drive cleanup. +ATADeviceInterface::ATADeviceInterface( + void (*Out)(MountpointInterface* outpacket), + void (*In)(MountpointInterface* inpacket), + void (*Cleanup)(void)) + : DeviceInterface(Out, In), fCleanup(Cleanup) +{ +} + +/// @brief Class desctructor +ATADeviceInterface::~ATADeviceInterface() +{ + MUST_PASS(fCleanup); + if (fCleanup) + fCleanup(); +} + +/// @brief Returns the name of the device interface. +/// @return it's name as a string. +const Char* ATADeviceInterface::Name() const +{ + return "ATADeviceInterface"; +} + +/// @brief Output operator. +/// @param Data +/// @return +ATADeviceInterface& ATADeviceInterface::operator<<(MountpointInterface* Data) +{ + if (!Data) + return *this; + + for (SizeT driveCount = 0; driveCount < kMaxDriveCountPerMountpoint; ++driveCount) + { + auto interface = Data->GetAddressOf(driveCount); + if ((interface) && rt_string_cmp((interface)->fDriveKind(), "ATA-", 5) == 0) + { + continue; + } + else if ((interface) && + rt_string_cmp((interface)->fDriveKind(), "ATA-", 5) != 0) + { + return *this; + } + } + + return (ATADeviceInterface&)DeviceInterface::operator<<( + Data); +} + +/// @brief Input operator. +/// @param Data +/// @return +ATADeviceInterface& ATADeviceInterface::operator>>(MountpointInterface* Data) +{ + if (!Data) + return *this; + + for (SizeT driveCount = 0; driveCount < kMaxDriveCountPerMountpoint; ++driveCount) + { + auto interface = Data->GetAddressOf(driveCount); + if ((interface) && rt_string_cmp((interface)->fDriveKind(), "ATA-", 5) == 0) + { + continue; + } + else if ((interface) && + rt_string_cmp((interface)->fDriveKind(), "ATA-", 5) != 0) + { + return *this; + } + } + + return (ATADeviceInterface&)DeviceInterface::operator>>( + Data); +} diff --git a/dev/zka/src/Storage/ATADeviceInterface.cxx b/dev/zka/src/Storage/ATADeviceInterface.cxx deleted file mode 100644 index 8eae0262..00000000 --- a/dev/zka/src/Storage/ATADeviceInterface.cxx +++ /dev/null @@ -1,88 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -using namespace Kernel; - -/// @brief Class constructor -/// @param Out Drive output -/// @param In Drive input -/// @param Cleanup Drive cleanup. -ATADeviceInterface::ATADeviceInterface( - void (*Out)(MountpointInterface* outpacket), - void (*In)(MountpointInterface* inpacket), - void (*Cleanup)(void)) - : DeviceInterface(Out, In), fCleanup(Cleanup) -{ -} - -/// @brief Class desctructor -ATADeviceInterface::~ATADeviceInterface() -{ - MUST_PASS(fCleanup); - if (fCleanup) - fCleanup(); -} - -/// @brief Returns the name of the device interface. -/// @return it's name as a string. -const Char* ATADeviceInterface::Name() const -{ - return "ATADeviceInterface"; -} - -/// @brief Output operator. -/// @param Data -/// @return -ATADeviceInterface& ATADeviceInterface::operator<<(MountpointInterface* Data) -{ - if (!Data) - return *this; - - for (SizeT driveCount = 0; driveCount < kMaxDriveCountPerMountpoint; ++driveCount) - { - auto interface = Data->GetAddressOf(driveCount); - if ((interface) && rt_string_cmp((interface)->fDriveKind(), "ATA-", 5) == 0) - { - continue; - } - else if ((interface) && - rt_string_cmp((interface)->fDriveKind(), "ATA-", 5) != 0) - { - return *this; - } - } - - return (ATADeviceInterface&)DeviceInterface::operator<<( - Data); -} - -/// @brief Input operator. -/// @param Data -/// @return -ATADeviceInterface& ATADeviceInterface::operator>>(MountpointInterface* Data) -{ - if (!Data) - return *this; - - for (SizeT driveCount = 0; driveCount < kMaxDriveCountPerMountpoint; ++driveCount) - { - auto interface = Data->GetAddressOf(driveCount); - if ((interface) && rt_string_cmp((interface)->fDriveKind(), "ATA-", 5) == 0) - { - continue; - } - else if ((interface) && - rt_string_cmp((interface)->fDriveKind(), "ATA-", 5) != 0) - { - return *this; - } - } - - return (ATADeviceInterface&)DeviceInterface::operator>>( - Data); -} diff --git a/dev/zka/src/Storage/NVMEDeviceInterface.cc b/dev/zka/src/Storage/NVMEDeviceInterface.cc new file mode 100644 index 00000000..c2bd701f --- /dev/null +++ b/dev/zka/src/Storage/NVMEDeviceInterface.cc @@ -0,0 +1,28 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +namespace Kernel +{ + NVMEDeviceInterface::NVMEDeviceInterface(void (*Out)(MountpointInterface* outpacket), + void (*In)(MountpointInterface* inpacket), + void (*Cleanup)(void)) + : DeviceInterface(Out, In), fCleanup(Cleanup) + { + } + + NVMEDeviceInterface::~NVMEDeviceInterface() + { + if (fCleanup) + fCleanup(); + } + + const Char* NVMEDeviceInterface::Name() const + { + return ("NVMEDeviceInterface"); + } +} // namespace Kernel diff --git a/dev/zka/src/Storage/NVMEDeviceInterface.cxx b/dev/zka/src/Storage/NVMEDeviceInterface.cxx deleted file mode 100644 index c762affe..00000000 --- a/dev/zka/src/Storage/NVMEDeviceInterface.cxx +++ /dev/null @@ -1,28 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -namespace Kernel -{ - NVMEDeviceInterface::NVMEDeviceInterface(void (*Out)(MountpointInterface* outpacket), - void (*In)(MountpointInterface* inpacket), - void (*Cleanup)(void)) - : DeviceInterface(Out, In), fCleanup(Cleanup) - { - } - - NVMEDeviceInterface::~NVMEDeviceInterface() - { - if (fCleanup) - fCleanup(); - } - - const Char* NVMEDeviceInterface::Name() const - { - return ("NVMEDeviceInterface"); - } -} // namespace Kernel diff --git a/dev/zka/src/Storage/SCSIDeviceInterface.cc b/dev/zka/src/Storage/SCSIDeviceInterface.cc new file mode 100644 index 00000000..2cb397e7 --- /dev/null +++ b/dev/zka/src/Storage/SCSIDeviceInterface.cc @@ -0,0 +1,11 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +///! @brief ATAPI SCSI packet. +const scsi_packet_type<12> kCDRomPacketTemplate = {0x43, 0, 1, 0, 0, 0, + 0, 12, 0x40, 0, 0}; diff --git a/dev/zka/src/Storage/SCSIDeviceInterface.cxx b/dev/zka/src/Storage/SCSIDeviceInterface.cxx deleted file mode 100644 index bda16961..00000000 --- a/dev/zka/src/Storage/SCSIDeviceInterface.cxx +++ /dev/null @@ -1,11 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -///! @brief ATAPI SCSI packet. -const scsi_packet_type<12> kCDRomPacketTemplate = {0x43, 0, 1, 0, 0, 0, - 0, 12, 0x40, 0, 0}; diff --git a/dev/zka/src/Stream.cc b/dev/zka/src/Stream.cc new file mode 100644 index 00000000..cf5cb4a4 --- /dev/null +++ b/dev/zka/src/Stream.cc @@ -0,0 +1,12 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + File: Stream.cxx + Purpose: Stream object + + Revision History: + +------------------------------------------- */ + +#include diff --git a/dev/zka/src/Stream.cxx b/dev/zka/src/Stream.cxx deleted file mode 100644 index 6d975ca2..00000000 --- a/dev/zka/src/Stream.cxx +++ /dev/null @@ -1,12 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - File: Stream.cxx - Purpose: Stream object - - Revision History: - -------------------------------------------- */ - -#include diff --git a/dev/zka/src/String.cc b/dev/zka/src/String.cc new file mode 100644 index 00000000..824e7b91 --- /dev/null +++ b/dev/zka/src/String.cc @@ -0,0 +1,215 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include +#include + +namespace Kernel +{ + Char* StringView::Data() + { + return fData; + } + + const Char* StringView::CData() const + { + return fData; + } + + Size StringView::Length() const + { + return fDataSz; + } + + bool StringView::operator==(const StringView& rhs) const + { + if (rhs.Length() != this->Length()) + return false; + + for (Size index = 0; index < this->Length(); ++index) + { + if (rhs.fData[index] != fData[index]) + return false; + } + + return true; + } + + bool StringView::operator==(const Char* rhs) const + { + if (rt_string_len(rhs) != this->Length()) + return false; + + for (Size index = 0; index < rt_string_len(rhs); ++index) + { + if (rhs[index] != fData[index]) + return false; + } + + return true; + } + + bool StringView::operator!=(const StringView& rhs) const + { + if (rhs.Length() != this->Length()) + return false; + + for (Size index = 0; index < rhs.Length(); ++index) + { + if (rhs.fData[index] == fData[index]) + return false; + } + + return true; + } + + bool StringView::operator!=(const Char* rhs) const + { + if (rt_string_len(rhs) != this->Length()) + return false; + + for (Size index = 0; index < rt_string_len(rhs); ++index) + { + if (rhs[index] == fData[index]) + return false; + } + + return true; + } + + ErrorOr StringBuilder::Construct(const Char* data) + { + if (!data || *data == 0) + return {}; + + StringView* view = new StringView(rt_string_len(data)); + (*view) += data; + + return ErrorOr(*view); + } + + const Char* StringBuilder::FromBool(const Char* fmt, bool i) + { + if (!fmt) + return ("?"); + + const Char* boolean_expr = i ? "True" : "False"; + char* ret = (char*)cAlloca((sizeof(char) * i) ? 4 : 5 + rt_string_len(fmt)); + + if (!ret) + return ("?"); + + const auto fmt_len = rt_string_len(fmt); + const auto res_len = rt_string_len(boolean_expr); + + for (Size idx = 0; idx < fmt_len; ++idx) + { + if (fmt[idx] == '%') + { + SizeT result_cnt = idx; + + for (auto y_idx = idx; y_idx < res_len; ++y_idx) + { + ret[result_cnt] = boolean_expr[y_idx]; + ++result_cnt; + } + + break; + } + + ret[idx] = fmt[idx]; + } + + return ret; + } + + bool StringBuilder::Equals(const Char* lhs, const Char* rhs) + { + if (rt_string_len(rhs) != rt_string_len(lhs)) + return false; + + for (Size index = 0; index < rt_string_len(rhs); ++index) + { + if (rhs[index] != lhs[index]) + return false; + } + + return true; + } + + bool StringBuilder::Equals(const WideChar* lhs, const WideChar* rhs) + { + for (Size index = 0; rhs[index] != 0; ++index) + { + if (rhs[index] != lhs[index]) + return false; + } + + return true; + } + + const Char* StringBuilder::Format(const Char* fmt, const Char* fmt2) + { + if (!fmt || !fmt2) + return ("?"); + + char* ret = + (char*)cAlloca(sizeof(char) * rt_string_len(fmt2) + rt_string_len(fmt)); + + if (!ret) + return ("?"); + + for (Size idx = 0; idx < rt_string_len(fmt); ++idx) + { + if (fmt[idx] == '%') + { + Size result_cnt = idx; + for (Size y_idx = 0; y_idx < rt_string_len(fmt2); ++y_idx) + { + ret[result_cnt] = fmt2[y_idx]; + ++result_cnt; + } + + break; + } + + ret[idx] = fmt[idx]; + } + + return ret; + } + + STATIC void rt_string_append(Char* lhs, const Char* rhs, Int32 cur) + { + SizeT sz_rhs = rt_string_len(rhs); + SizeT rhs_i = 0; + + for (; rhs_i < sz_rhs; ++rhs_i) + { + lhs[rhs_i + cur] = rhs[rhs_i]; + } + } + + StringView& StringView::operator+=(const Char* rhs) + { + rt_string_append(this->fData, rhs, this->fCur); + this->fCur += rt_string_len(rhs); + + return *this; + } + + StringView& StringView::operator+=(const StringView& rhs) + { + if (rt_string_len(rhs.fData) > this->Length()) + return *this; + + rt_string_append(this->fData, const_cast(rhs.fData), this->fCur); + this->fCur += rt_string_len(const_cast(rhs.fData)); + + return *this; + } +} // namespace Kernel diff --git a/dev/zka/src/String.cxx b/dev/zka/src/String.cxx deleted file mode 100644 index c596db77..00000000 --- a/dev/zka/src/String.cxx +++ /dev/null @@ -1,215 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include -#include - -namespace Kernel -{ - Char* StringView::Data() - { - return fData; - } - - const Char* StringView::CData() const - { - return fData; - } - - Size StringView::Length() const - { - return fDataSz; - } - - bool StringView::operator==(const StringView& rhs) const - { - if (rhs.Length() != this->Length()) - return false; - - for (Size index = 0; index < this->Length(); ++index) - { - if (rhs.fData[index] != fData[index]) - return false; - } - - return true; - } - - bool StringView::operator==(const Char* rhs) const - { - if (rt_string_len(rhs) != this->Length()) - return false; - - for (Size index = 0; index < rt_string_len(rhs); ++index) - { - if (rhs[index] != fData[index]) - return false; - } - - return true; - } - - bool StringView::operator!=(const StringView& rhs) const - { - if (rhs.Length() != this->Length()) - return false; - - for (Size index = 0; index < rhs.Length(); ++index) - { - if (rhs.fData[index] == fData[index]) - return false; - } - - return true; - } - - bool StringView::operator!=(const Char* rhs) const - { - if (rt_string_len(rhs) != this->Length()) - return false; - - for (Size index = 0; index < rt_string_len(rhs); ++index) - { - if (rhs[index] == fData[index]) - return false; - } - - return true; - } - - ErrorOr StringBuilder::Construct(const Char* data) - { - if (!data || *data == 0) - return {}; - - StringView* view = new StringView(rt_string_len(data)); - (*view) += data; - - return ErrorOr(*view); - } - - const Char* StringBuilder::FromBool(const Char* fmt, bool i) - { - if (!fmt) - return ("?"); - - const Char* boolean_expr = i ? "True" : "False"; - char* ret = (char*)cAlloca((sizeof(char) * i) ? 4 : 5 + rt_string_len(fmt)); - - if (!ret) - return ("?"); - - const auto fmt_len = rt_string_len(fmt); - const auto res_len = rt_string_len(boolean_expr); - - for (Size idx = 0; idx < fmt_len; ++idx) - { - if (fmt[idx] == '%') - { - SizeT result_cnt = idx; - - for (auto y_idx = idx; y_idx < res_len; ++y_idx) - { - ret[result_cnt] = boolean_expr[y_idx]; - ++result_cnt; - } - - break; - } - - ret[idx] = fmt[idx]; - } - - return ret; - } - - bool StringBuilder::Equals(const Char* lhs, const Char* rhs) - { - if (rt_string_len(rhs) != rt_string_len(lhs)) - return false; - - for (Size index = 0; index < rt_string_len(rhs); ++index) - { - if (rhs[index] != lhs[index]) - return false; - } - - return true; - } - - bool StringBuilder::Equals(const WideChar* lhs, const WideChar* rhs) - { - for (Size index = 0; rhs[index] != 0; ++index) - { - if (rhs[index] != lhs[index]) - return false; - } - - return true; - } - - const Char* StringBuilder::Format(const Char* fmt, const Char* fmt2) - { - if (!fmt || !fmt2) - return ("?"); - - char* ret = - (char*)cAlloca(sizeof(char) * rt_string_len(fmt2) + rt_string_len(fmt)); - - if (!ret) - return ("?"); - - for (Size idx = 0; idx < rt_string_len(fmt); ++idx) - { - if (fmt[idx] == '%') - { - Size result_cnt = idx; - for (Size y_idx = 0; y_idx < rt_string_len(fmt2); ++y_idx) - { - ret[result_cnt] = fmt2[y_idx]; - ++result_cnt; - } - - break; - } - - ret[idx] = fmt[idx]; - } - - return ret; - } - - STATIC void rt_string_append(Char* lhs, const Char* rhs, Int32 cur) - { - SizeT sz_rhs = rt_string_len(rhs); - SizeT rhs_i = 0; - - for (; rhs_i < sz_rhs; ++rhs_i) - { - lhs[rhs_i + cur] = rhs[rhs_i]; - } - } - - StringView& StringView::operator+=(const Char* rhs) - { - rt_string_append(this->fData, rhs, this->fCur); - this->fCur += rt_string_len(rhs); - - return *this; - } - - StringView& StringView::operator+=(const StringView& rhs) - { - if (rt_string_len(rhs.fData) > this->Length()) - return *this; - - rt_string_append(this->fData, const_cast(rhs.fData), this->fCur); - this->fCur += rt_string_len(const_cast(rhs.fData)); - - return *this; - } -} // namespace Kernel diff --git a/dev/zka/src/ThreadLocalStorage.cc b/dev/zka/src/ThreadLocalStorage.cc new file mode 100644 index 00000000..ef8aba6c --- /dev/null +++ b/dev/zka/src/ThreadLocalStorage.cc @@ -0,0 +1,67 @@ +/* + * ======================================================== + * + * minoskrnl + * Copyright ZKA Web Services Co., all rights reserved. + * + * ======================================================== + */ + +#include +#include +#include +#include + +/***********************************************************************************/ +/// @bugs: 0 +/// @file ThreadLocalStorage.cxx +/// @brief Process Thread Local Storage. +/***********************************************************************************/ + +using namespace Kernel; + +/** + * @brief Checks for cookie inside the TIB. + * @param tib_ptr the TIB to check. + * @return if the cookie is enabled, true; false otherwise + */ + +Boolean tls_check_tib(THREAD_INFORMATION_BLOCK* tib_ptr) +{ + if (!tib_ptr || + !tib_ptr->f_ThreadRecord) + return false; + + IEncoderObject encoder; + const char* tib_as_bytes = encoder.AsBytes(tib_ptr); + + kcout << "Checking for a valid cookie inside the TIB...\r"; + + return tib_as_bytes[0] == kCookieMag0 && tib_as_bytes[1] == kCookieMag1 && + tib_as_bytes[2] == kCookieMag2; +} + +/** + * @brief System call implementation of the TLS check. + * @param tib_ptr The TIB record. + * @return + */ +EXTERN_C Bool tls_check_syscall_impl(Kernel::VoidPtr tib_ptr) noexcept +{ + if (!tib_ptr) + { + kcout << "Failing because of an invalid TIB...\r"; + return false; + } + + THREAD_INFORMATION_BLOCK* tib = (THREAD_INFORMATION_BLOCK*)tib_ptr; + + if (!tls_check_tib(tib)) + { + kcout << "Crashing because of an invalid TIB...\r"; + return false; + } + + kcout << "Verification succeeded! staying alive...\r"; + return true; +} diff --git a/dev/zka/src/ThreadLocalStorage.cxx b/dev/zka/src/ThreadLocalStorage.cxx deleted file mode 100644 index 0468d628..00000000 --- a/dev/zka/src/ThreadLocalStorage.cxx +++ /dev/null @@ -1,67 +0,0 @@ -/* - * ======================================================== - * - * minoskrnl - * Copyright ZKA Web Services Co., all rights reserved. - * - * ======================================================== - */ - -#include -#include -#include -#include - -/***********************************************************************************/ -/// @bugs: 0 -/// @file ThreadLocalStorage.cxx -/// @brief Process Thread Local Storage. -/***********************************************************************************/ - -using namespace Kernel; - -/** - * @brief Checks for cookie inside the TIB. - * @param tib_ptr the TIB to check. - * @return if the cookie is enabled, true; false otherwise - */ - -Boolean tls_check_tib(THREAD_INFORMATION_BLOCK* tib_ptr) -{ - if (!tib_ptr || - !tib_ptr->f_ThreadRecord) - return false; - - IEncoderObject encoder; - const char* tib_as_bytes = encoder.AsBytes(tib_ptr); - - kcout << "Checking for a valid cookie inside the TIB...\r"; - - return tib_as_bytes[0] == kCookieMag0 && tib_as_bytes[1] == kCookieMag1 && - tib_as_bytes[2] == kCookieMag2; -} - -/** - * @brief System call implementation of the TLS check. - * @param tib_ptr The TIB record. - * @return - */ -EXTERN_C Bool tls_check_syscall_impl(Kernel::VoidPtr tib_ptr) noexcept -{ - if (!tib_ptr) - { - kcout << "Failing because of an invalid TIB...\r"; - return false; - } - - THREAD_INFORMATION_BLOCK* tib = (THREAD_INFORMATION_BLOCK*)tib_ptr; - - if (!tls_check_tib(tib)) - { - kcout << "Crashing because of an invalid TIB...\r"; - return false; - } - - kcout << "Verification succeeded! staying alive...\r"; - return true; -} diff --git a/dev/zka/src/Timer.cc b/dev/zka/src/Timer.cc new file mode 100644 index 00000000..e7ad488a --- /dev/null +++ b/dev/zka/src/Timer.cc @@ -0,0 +1,47 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +///! BUGS: 0 +///! @file Timer.cxx +///! @brief Software Timer implementation + +using namespace Kernel; + +/// @brief Unimplemented as it is an interface. +Int32 TimerInterface::Wait() noexcept +{ + return kErrorUnimplemented; +} + +/// @brief SoftwareTimer class, meant to be generic. + +SoftwareTimer::SoftwareTimer(Int64 seconds) + : fWaitFor(seconds) +{ + fDigitalTimer = new IntPtr(); + MUST_PASS(fDigitalTimer); +} + +SoftwareTimer::~SoftwareTimer() +{ + delete fDigitalTimer; + fWaitFor = 0; +} + +Int32 SoftwareTimer::Wait() noexcept +{ + if (fWaitFor < 1) + return -1; + + while (*fDigitalTimer < (*fDigitalTimer + fWaitFor)) + { + ++(*fDigitalTimer); + } + + return 0; +} diff --git a/dev/zka/src/Timer.cxx b/dev/zka/src/Timer.cxx deleted file mode 100644 index f1d8c469..00000000 --- a/dev/zka/src/Timer.cxx +++ /dev/null @@ -1,47 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -///! BUGS: 0 -///! @file Timer.cxx -///! @brief Software Timer implementation - -using namespace Kernel; - -/// @brief Unimplemented as it is an interface. -Int32 TimerInterface::Wait() noexcept -{ - return kErrorUnimplemented; -} - -/// @brief SoftwareTimer class, meant to be generic. - -SoftwareTimer::SoftwareTimer(Int64 seconds) - : fWaitFor(seconds) -{ - fDigitalTimer = new IntPtr(); - MUST_PASS(fDigitalTimer); -} - -SoftwareTimer::~SoftwareTimer() -{ - delete fDigitalTimer; - fWaitFor = 0; -} - -Int32 SoftwareTimer::Wait() noexcept -{ - if (fWaitFor < 1) - return -1; - - while (*fDigitalTimer < (*fDigitalTimer + fWaitFor)) - { - ++(*fDigitalTimer); - } - - return 0; -} diff --git a/dev/zka/src/User.cc b/dev/zka/src/User.cc new file mode 100644 index 00000000..9037d729 --- /dev/null +++ b/dev/zka/src/User.cc @@ -0,0 +1,138 @@ +/* + * ======================================================== + * + * ZKA + * Copyright ZKA Web Services Co., all rights reserved. + * + * File: User.cxx + * Purpose: User class, used to provide authentication and security. + * + * ======================================================== + */ + +#include + +#include +#include +#include +#include +#include + +#define cStdUser (0xCEEF) +#define cSuperUser (0xECCF) + +/// BUGS: 0 + +namespace Kernel +{ + namespace Detail + { + /// \brief Constructs a password by hashing the password. + /// \param password password to hash. + /// \return the hashed password + const Int32 cred_construct_token(Char* password, const Char* in_password, User* user, SizeT length) + { + if (!password || !user) + return -1; + + kcout << "Constructing password...\r"; + + for (Size i_pass = 0; i_pass < length; ++i_pass) + { + Char cur_chr = in_password[i_pass]; + + if (cur_chr == 0) + break; + + password[i_pass] = cur_chr + (user->IsStdUser() ? cStdUser : cSuperUser); + } + + kcout << "Done constructing password...\r"; + + return 0; + } + } // namespace Detail + + User::User(const Int32& sel, const Char* userName) + : fRing((RingKind)sel) + { + MUST_PASS(sel >= 0); + rt_copy_memory((VoidPtr)userName, this->fUserName, rt_string_len(userName)); + } + + User::User(const RingKind& ringKind, const Char* userName) + : fRing(ringKind) + { + rt_copy_memory((VoidPtr)userName, this->fUserName, rt_string_len(userName)); + } + + User::~User() = default; + + Bool User::TrySave(const Char* password_to_fill) noexcept + { + if (!password_to_fill || + *password_to_fill == 0) + return No; + + SizeT len = rt_string_len(password_to_fill); + + Char* password = new Char[len]; + MUST_PASS(password); + + // fill data first, generate hash. + // return false on error. + + rt_copy_memory((VoidPtr)password_to_fill, password, len); + + if (!Detail::cred_construct_token(password, password_to_fill, this, len)) + { + delete[] password; + password = nullptr; + + return No; + } + + // then store password. + + rt_copy_memory(password, this->fUserToken, rt_string_len(password_to_fill)); + + delete[] password; + password = nullptr; + + kcout << "Saved password successfully...\r"; + + return Yes; + } + + Bool User::operator==(const User& lhs) + { + return lhs.fRing == this->fRing; + } + + Bool User::operator!=(const User& lhs) + { + return lhs.fRing != this->fRing; + } + + Char* User::Name() noexcept + { + return this->fUserName; + } + + /// @brief Returns the user's ring. + /// @return The king of ring the user is attached to. + const RingKind& User::Ring() noexcept + { + return this->fRing; + } + + Bool User::IsStdUser() noexcept + { + return this->Ring() == RingKind::kRingStdUser; + } + + Bool User::IsSuperUser() noexcept + { + return this->Ring() == RingKind::kRingSuperUser; + } +} // namespace Kernel diff --git a/dev/zka/src/User.cxx b/dev/zka/src/User.cxx deleted file mode 100644 index f8800e9b..00000000 --- a/dev/zka/src/User.cxx +++ /dev/null @@ -1,138 +0,0 @@ -/* - * ======================================================== - * - * ZKA - * Copyright ZKA Web Services Co., all rights reserved. - * - * File: User.cxx - * Purpose: User class, used to provide authentication and security. - * - * ======================================================== - */ - -#include - -#include -#include -#include -#include -#include - -#define cStdUser (0xCEEF) -#define cSuperUser (0xECCF) - -/// BUGS: 0 - -namespace Kernel -{ - namespace Detail - { - /// \brief Constructs a password by hashing the password. - /// \param password password to hash. - /// \return the hashed password - const Int32 cred_construct_token(Char* password, const Char* in_password, User* user, SizeT length) - { - if (!password || !user) - return -1; - - kcout << "Constructing password...\r"; - - for (Size i_pass = 0; i_pass < length; ++i_pass) - { - Char cur_chr = in_password[i_pass]; - - if (cur_chr == 0) - break; - - password[i_pass] = cur_chr + (user->IsStdUser() ? cStdUser : cSuperUser); - } - - kcout << "Done constructing password...\r"; - - return 0; - } - } // namespace Detail - - User::User(const Int32& sel, const Char* userName) - : fRing((RingKind)sel) - { - MUST_PASS(sel >= 0); - rt_copy_memory((VoidPtr)userName, this->fUserName, rt_string_len(userName)); - } - - User::User(const RingKind& ringKind, const Char* userName) - : fRing(ringKind) - { - rt_copy_memory((VoidPtr)userName, this->fUserName, rt_string_len(userName)); - } - - User::~User() = default; - - Bool User::TrySave(const Char* password_to_fill) noexcept - { - if (!password_to_fill || - *password_to_fill == 0) - return No; - - SizeT len = rt_string_len(password_to_fill); - - Char* password = new Char[len]; - MUST_PASS(password); - - // fill data first, generate hash. - // return false on error. - - rt_copy_memory((VoidPtr)password_to_fill, password, len); - - if (!Detail::cred_construct_token(password, password_to_fill, this, len)) - { - delete[] password; - password = nullptr; - - return No; - } - - // then store password. - - rt_copy_memory(password, this->fUserToken, rt_string_len(password_to_fill)); - - delete[] password; - password = nullptr; - - kcout << "Saved password successfully...\r"; - - return Yes; - } - - Bool User::operator==(const User& lhs) - { - return lhs.fRing == this->fRing; - } - - Bool User::operator!=(const User& lhs) - { - return lhs.fRing != this->fRing; - } - - Char* User::Name() noexcept - { - return this->fUserName; - } - - /// @brief Returns the user's ring. - /// @return The king of ring the user is attached to. - const RingKind& User::Ring() noexcept - { - return this->fRing; - } - - Bool User::IsStdUser() noexcept - { - return this->Ring() == RingKind::kRingStdUser; - } - - Bool User::IsSuperUser() noexcept - { - return this->Ring() == RingKind::kRingSuperUser; - } -} // namespace Kernel diff --git a/dev/zka/src/UserProcessScheduler.cc b/dev/zka/src/UserProcessScheduler.cc new file mode 100644 index 00000000..7dd213b5 --- /dev/null +++ b/dev/zka/src/UserProcessScheduler.cc @@ -0,0 +1,592 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + + FILE: UserProcessScheduler.cxx + PURPOSE: EL0/Ring-3 Process scheduler. + +------------------------------------------- */ + +/***********************************************************************************/ +/// @file UserProcessScheduler.cxx +/// @brief User process scheduler. +/***********************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +///! BUGS: 0 + +/***********************************************************************************/ +/** TODO: Document the Kernel, SDK and kits. */ +/***********************************************************************************/ + +namespace Kernel +{ + /***********************************************************************************/ + /// @brief Exit Code global variable. + /***********************************************************************************/ + + STATIC UInt32 cLastExitCode = 0U; + + /***********************************************************************************/ + /// @brief User Process scheduler global and external reference of thread scheduler. + /***********************************************************************************/ + + UserProcessScheduler* kProcessScheduler = nullptr; + EXTERN HardwareThreadScheduler* kHardwareThreadScheduler; + + /// @brief Gets the last exit code. + /// @note Not thread-safe. + /// @return Int32 the last exit code. + const UInt32& sched_get_exit_code(void) noexcept + { + return cLastExitCode; + } + + /***********************************************************************************/ + /// @brief crash current process. + /***********************************************************************************/ + + Void UserProcess::Crash() + { + if (this->Status != ProcessStatusKind::kRunning) + return; + + if (*this->Name != 0) + { + kcout << this->Name << ": crashed, error id: " << number(kErrorProcessFault) << endl; + } + + this->Exit(kErrorProcessFault); + } + + /***********************************************************************************/ + //! @brief boolean operator, check status. + /***********************************************************************************/ + + UserProcess::operator bool() + { + return this->Status != ProcessStatusKind::kDead; + } + + /***********************************************************************************/ + /// @brief Gets the local last exit code. + /// @note Not thread-safe. + /// @return Int32 the last exit code. + /***********************************************************************************/ + + const UInt32& UserProcess::GetExitCode() noexcept + { + return this->fLastExitCode; + } + + /***********************************************************************************/ + /// @brief Error code variable getter. + /***********************************************************************************/ + + Int32& UserProcess::GetLocalCode() noexcept + { + return fLocalCode; + } + + /***********************************************************************************/ + /// @brief Wake process. + /***********************************************************************************/ + + void UserProcess::Wake(const bool should_wakeup) + { + this->Status = + should_wakeup ? ProcessStatusKind::kRunning : ProcessStatusKind::kFrozen; + } + + /***********************************************************************************/ + /** @brief Add pointer to entry. */ + /***********************************************************************************/ + + VoidPtr UserProcess::New(const SizeT& sz) + { +#ifdef __ZKA_AMD64__ + auto pd = hal_read_cr3(); + hal_write_cr3(reinterpret_cast(this->MemoryPD)); + + auto ptr = mm_new_heap(sz, Yes, Yes); + + hal_write_cr3(reinterpret_cast(pd)); +#else + auto ptr = mm_new_heap(sz, Yes, Yes); +#endif + + if (!this->MemoryEntryList) + { + this->MemoryEntryList = new UserProcess::PROCESS_MEMORY_ENTRY(); + this->MemoryEntryList->MemoryEntry = ptr; + + this->MemoryEntryList->MemoryPrev = nullptr; + this->MemoryEntryList->MemoryNext = nullptr; + + return ptr; + } + else + { + PROCESS_MEMORY_ENTRY* entry = this->MemoryEntryList; + PROCESS_MEMORY_ENTRY* prev_entry = nullptr; + + while (!entry) + { + if (entry->MemoryEntry == nullptr) + break; // chose to break here, when we get an already allocated memory entry for our needs. + + prev_entry = entry; + entry = entry->MemoryNext; + } + + entry->MemoryNext = new PROCESS_MEMORY_ENTRY(); + entry->MemoryNext->MemoryEntry = ptr; + + entry->MemoryNext->MemoryPrev = entry; + entry->MemoryNext->MemoryNext = nullptr; + } + + return nullptr; + } + + /***********************************************************************************/ + /** @brief Free pointer from usage. */ + /***********************************************************************************/ + + Boolean UserProcess::Delete(VoidPtr ptr, const SizeT& sz) + { + if (!ptr || + sz == 0) + return No; + + PROCESS_MEMORY_ENTRY* entry = this->MemoryEntryList; + + while (entry != nullptr) + { + if (entry->MemoryEntry == ptr) + { +#ifdef __ZKA_AMD64__ + auto pd = hal_read_cr3(); + hal_write_cr3(reinterpret_cast(this->MemoryPD)); + + auto ret = mm_delete_heap(entry->MemoryEntry); + + hal_write_cr3(pd); + + return ret; +#else + Bool ret = mm_delete_heap(ptr); + return ret; +#endif + } + + entry = entry->MemoryNext; + } + + return No; + } + + /***********************************************************************************/ + /// @brief Gets the name of the current process. + /***********************************************************************************/ + + const Char* UserProcess::GetProcessName() noexcept + { + return this->Name; + } + + /***********************************************************************************/ + /// @brief Gets the owner of the process. + /***********************************************************************************/ + + const User* UserProcess::GetOwner() noexcept + { + return this->Owner; + } + + /// @brief UserProcess status getter. + const ProcessStatusKind& UserProcess::GetStatus() noexcept + { + return this->Status; + } + + /***********************************************************************************/ + /** + @brief Affinity is the time slot allowed for the process. + */ + /***********************************************************************************/ + + const AffinityKind& UserProcess::GetAffinity() noexcept + { + return this->Affinity; + } + + /***********************************************************************************/ + /** + @brief Process exit method. + */ + /***********************************************************************************/ + + void UserProcess::Exit(const Int32& exit_code) + { + this->Status = ProcessStatusKind::kDead; + + fLastExitCode = exit_code; + cLastExitCode = exit_code; + + auto memory_list = this->MemoryEntryList; + + // Deleting memory lists. Make sure to free all of them. + while (memory_list) + { + if (memory_list->MemoryEntry) + { +#ifdef __ZKA_AMD64__ + auto pd = hal_read_cr3(); + hal_write_cr3(reinterpret_cast(this->MemoryPD)); +#endif + + MUST_PASS(mm_delete_heap(memory_list->MemoryEntry)); + +#ifdef __ZKA_AMD64__ + hal_write_cr3(pd); +#endif + } + + auto next = memory_list->MemoryNext; + + mm_delete_heap(memory_list); + memory_list = nullptr; + + memory_list = next; + } + + //! Free the memory's page directory. + HAL::mm_free_bitmap(reinterpret_cast(this->MemoryPD)); + + //! Delete image if not done already. + if (this->Image && mm_is_valid_heap(this->Image)) + mm_delete_heap(this->Image); + + if (this->StackFrame && mm_is_valid_heap(this->StackFrame)) + mm_delete_heap((VoidPtr)this->StackFrame); + + this->Image = nullptr; + this->StackFrame = nullptr; + + if (this->Kind == kExectuableDLLKind) + { + Bool success = false; + rtl_fini_dll(this, this->PefDLLDelegate, &success); + + if (success) + { + this->PefDLLDelegate = nullptr; + } + } + + if (this->StackReserve) + delete[] this->StackReserve; + + this->ProcessId = 0; + + if (this->ProcessId > 0) + UserProcessScheduler::The().Remove(this->ProcessId); + } + + /***********************************************************************************/ + /// @brief Add process to list. + /// @param process the process *Ref* class. + /// @return the process index inside the team. + /***********************************************************************************/ + + SizeT UserProcessScheduler::Add(UserProcess process) + { + if (mTeam.mProcessAmount > kSchedProcessLimitPerTeam) + return 0; + +#ifdef __ZKA_AMD64__ + process.MemoryPD = reinterpret_cast(HAL::mm_alloc_bitmap(Yes, Yes, sizeof(PDE), Yes)); +#endif // __ZKA_AMD64__ + + process.Status = ProcessStatusKind::kStarting; + + process.StackFrame = (HAL::StackFramePtr)mm_new_heap(sizeof(HAL::StackFrame), Yes, Yes); + + if (!process.StackFrame) + { + process.Crash(); + return -kErrorProcessFault; + } + + // Create heap according to type of process. + if (process.Kind == UserProcess::kExectuableDLLKind) + { + process.PefDLLDelegate = rtl_init_dll(&process); + } + + if (!process.Image) + { + if (process.Kind != UserProcess::kExectuableDLLKind) + { + process.Crash(); + return -kErrorProcessFault; + } + } + + // get preferred stack size by app. + const auto cMaxStackSize = process.StackSize; + process.StackReserve = (UInt8*)mm_new_heap(sizeof(UInt8) * cMaxStackSize, Yes, Yes); + + if (!process.StackReserve) + { + mm_delete_heap(process.StackFrame); + process.StackFrame = nullptr; + return -kErrorProcessFault; + } + + ++mTeam.mProcessAmount; + + process.ProcessId = mTeam.mProcessAmount; + process.Status = ProcessStatusKind::kRunning; + + // avoid the pitfalls of moving process. + auto ret_pid = process.ProcessId; + + mTeam.AsArray()[process.ProcessId] = move(process); + + return ret_pid; + } + + /***********************************************************************************/ + /// @brief Retrieves the singleton of the process scheduler. + /***********************************************************************************/ + + UserProcessScheduler& UserProcessScheduler::The() + { + MUST_PASS(kProcessScheduler); + return *kProcessScheduler; + } + + /***********************************************************************************/ + + /// @brief Remove process from list. + /// @param process_id process slot inside team. + /// @retval true process was removed. + /// @retval false process doesn't exist in team. + + /***********************************************************************************/ + + Bool UserProcessScheduler::Remove(ProcessID process_id) + { + // check if process is within range. + if (process_id > mTeam.AsArray().Count()) + return No; + + mTeam.AsArray()[process_id].Status = ProcessStatusKind::kDead; + --mTeam.mProcessAmount; + + return Yes; + } + + const Bool UserProcessScheduler::IsUser() + { + return Yes; + } + + const Bool UserProcessScheduler::IsKernel() + { + return No; + } + + const Bool UserProcessScheduler::HasMP() + { + return kHandoverHeader->f_HardwareTables.f_MultiProcessingEnabled; + } + + /***********************************************************************************/ + + /// @brief Run User scheduler object. + /// @return Process executed within team. + + /***********************************************************************************/ + + SizeT UserProcessScheduler::Run() noexcept + { + SizeT process_index = 0; //! we store this guy to tell the scheduler how many + //! things we have scheduled. + + for (; process_index < mTeam.AsArray().Capacity(); ++process_index) + { + auto& process = mTeam.AsArray()[process_index]; + + //! check if process needs to be scheduled. + if (UserProcessHelper::CanBeScheduled(process)) + { + // Set current process header. + this->CurrentProcess() = process; + + process.PTime = static_cast(process.Affinity); + + UserProcessScheduler::The().CurrentProcess().Leak().Status = ProcessStatusKind::kFrozen; + UserProcessScheduler::The().CurrentProcess() = process; + + kcout << "Switch to '" << process.Name << "'.\r"; + + // tell helper to find a core to schedule on. + if (!UserProcessHelper::Switch(process.Image, &process.StackReserve[process.StackSize - 1], process.StackFrame, + process.ProcessId)) + { + process.Crash(); + continue; + } + } + else + { + if (process.Status == ProcessStatusKind::kRunning) + --process.PTime; + } + } + + kcout << "Scheduled Process Count: " << number(process_index) << endl; + + return process_index; + } + + /// @brief Gets the current scheduled team. + /// @return + UserProcessTeam& UserProcessScheduler::CurrentTeam() + { + return mTeam; + } + + /// @internal + + /// @brief Gets current running process. + /// @return + Ref& UserProcessScheduler::CurrentProcess() + { + return mTeam.AsRef(); + } + + /// @brief Current proccess id getter. + /// @return UserProcess ID integer. + PID& UserProcessHelper::TheCurrentPID() + { + kcout << "UserProcessHelper::TheCurrentPID: Leaking ProcessId...\r"; + return kProcessScheduler->CurrentProcess().Leak().ProcessId; + } + + /// @brief Check if process can be schedulded. + /// @param process the process reference. + /// @retval true can be schedulded. + /// @retval false cannot be schedulded. + Bool UserProcessHelper::CanBeScheduled(const UserProcess& process) + { + if (process.Status == ProcessStatusKind::kKilled || + process.Status == ProcessStatusKind::kDead) + return No; + + if (!process.Image && + process.Kind == UserProcess::kExectuableKind) + return No; + + return process.PTime < 1 && process.Status == ProcessStatusKind::kRunning; + } + + /***********************************************************************************/ + /** + * @brief Allocate a scheduler. + */ + /***********************************************************************************/ + + Bool UserProcessHelper::InitializeScheduler() + { + if (!kProcessScheduler) + { + kProcessScheduler = new UserProcessScheduler(); + } + + if (!kHardwareThreadScheduler) + { + kHardwareThreadScheduler = new HardwareThreadScheduler(); + } + + return Yes; + } + + /***********************************************************************************/ + /** + * @brief Start scheduling current AP/Hart/Core. + */ + /***********************************************************************************/ + SizeT UserProcessHelper::StartScheduling() + { + if (!kProcessScheduler) + return 0; + + return kProcessScheduler->Run(); + } + + /***********************************************************************************/ + /** + * \brief Does a context switch in a CPU. + * \param the_stack the stackframe of the running app. + * \param new_pid the process's PID. + */ + /***********************************************************************************/ + + Bool UserProcessHelper::Switch(VoidPtr image_ptr, UInt8* stack, HAL::StackFramePtr frame_ptr, const PID& new_pid) + { + if (!stack || !frame_ptr || !image_ptr || new_pid < 0) + return No; + + for (SizeT index = 0UL; index < HardwareThreadScheduler::The().Count(); ++index) + { + if (HardwareThreadScheduler::The()[index].Leak()->Kind() == kInvalidHart) + continue; + + if (HardwareThreadScheduler::The()[index].Leak()->Kind() != + ThreadKind::kHartBoot && + HardwareThreadScheduler::The()[index].Leak()->Kind() != + ThreadKind::kHartSystemReserved) + { + PID prev_pid = UserProcessHelper::TheCurrentPID(); + UserProcessHelper::TheCurrentPID() = new_pid; + + auto prev_ptime = HardwareThreadScheduler::The()[index].Leak()->fPTime; + HardwareThreadScheduler::The()[index].Leak()->fPTime = UserProcessScheduler::The().CurrentTeam().AsArray()[new_pid].ProcessId; + Bool ret = HardwareThreadScheduler::The()[index].Leak()->Switch(image_ptr, stack, frame_ptr); + + if (!ret) + { + HardwareThreadScheduler::The()[index].Leak()->fPTime = prev_ptime; + UserProcessHelper::TheCurrentPID() = prev_pid; + + continue; + } + } + } + + return false; + } + + /// @brief this checks if any process is on the team. + UserProcessScheduler::operator bool() + { + return mTeam.AsArray().Count() > 0; + } + + /// @brief this checks if no process is on the team. + bool UserProcessScheduler::operator!() + { + return mTeam.AsArray().Count() == 0; + } +} // namespace Kernel diff --git a/dev/zka/src/UserProcessScheduler.cxx b/dev/zka/src/UserProcessScheduler.cxx deleted file mode 100644 index 6802f59d..00000000 --- a/dev/zka/src/UserProcessScheduler.cxx +++ /dev/null @@ -1,592 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - - FILE: UserProcessScheduler.cxx - PURPOSE: EL0/Ring-3 Process scheduler. - -------------------------------------------- */ - -/***********************************************************************************/ -/// @file UserProcessScheduler.cxx -/// @brief User process scheduler. -/***********************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include - -///! BUGS: 0 - -/***********************************************************************************/ -/** TODO: Document the Kernel, SDK and kits. */ -/***********************************************************************************/ - -namespace Kernel -{ - /***********************************************************************************/ - /// @brief Exit Code global variable. - /***********************************************************************************/ - - STATIC UInt32 cLastExitCode = 0U; - - /***********************************************************************************/ - /// @brief User Process scheduler global and external reference of thread scheduler. - /***********************************************************************************/ - - UserProcessScheduler* kProcessScheduler = nullptr; - EXTERN HardwareThreadScheduler* kHardwareThreadScheduler; - - /// @brief Gets the last exit code. - /// @note Not thread-safe. - /// @return Int32 the last exit code. - const UInt32& sched_get_exit_code(void) noexcept - { - return cLastExitCode; - } - - /***********************************************************************************/ - /// @brief crash current process. - /***********************************************************************************/ - - Void UserProcess::Crash() - { - if (this->Status != ProcessStatusKind::kRunning) - return; - - if (*this->Name != 0) - { - kcout << this->Name << ": crashed, error id: " << number(kErrorProcessFault) << endl; - } - - this->Exit(kErrorProcessFault); - } - - /***********************************************************************************/ - //! @brief boolean operator, check status. - /***********************************************************************************/ - - UserProcess::operator bool() - { - return this->Status != ProcessStatusKind::kDead; - } - - /***********************************************************************************/ - /// @brief Gets the local last exit code. - /// @note Not thread-safe. - /// @return Int32 the last exit code. - /***********************************************************************************/ - - const UInt32& UserProcess::GetExitCode() noexcept - { - return this->fLastExitCode; - } - - /***********************************************************************************/ - /// @brief Error code variable getter. - /***********************************************************************************/ - - Int32& UserProcess::GetLocalCode() noexcept - { - return fLocalCode; - } - - /***********************************************************************************/ - /// @brief Wake process. - /***********************************************************************************/ - - void UserProcess::Wake(const bool should_wakeup) - { - this->Status = - should_wakeup ? ProcessStatusKind::kRunning : ProcessStatusKind::kFrozen; - } - - /***********************************************************************************/ - /** @brief Add pointer to entry. */ - /***********************************************************************************/ - - VoidPtr UserProcess::New(const SizeT& sz) - { -#ifdef __ZKA_AMD64__ - auto pd = hal_read_cr3(); - hal_write_cr3(reinterpret_cast(this->MemoryPD)); - - auto ptr = mm_new_heap(sz, Yes, Yes); - - hal_write_cr3(reinterpret_cast(pd)); -#else - auto ptr = mm_new_heap(sz, Yes, Yes); -#endif - - if (!this->MemoryEntryList) - { - this->MemoryEntryList = new UserProcess::PROCESS_MEMORY_ENTRY(); - this->MemoryEntryList->MemoryEntry = ptr; - - this->MemoryEntryList->MemoryPrev = nullptr; - this->MemoryEntryList->MemoryNext = nullptr; - - return ptr; - } - else - { - PROCESS_MEMORY_ENTRY* entry = this->MemoryEntryList; - PROCESS_MEMORY_ENTRY* prev_entry = nullptr; - - while (!entry) - { - if (entry->MemoryEntry == nullptr) - break; // chose to break here, when we get an already allocated memory entry for our needs. - - prev_entry = entry; - entry = entry->MemoryNext; - } - - entry->MemoryNext = new PROCESS_MEMORY_ENTRY(); - entry->MemoryNext->MemoryEntry = ptr; - - entry->MemoryNext->MemoryPrev = entry; - entry->MemoryNext->MemoryNext = nullptr; - } - - return nullptr; - } - - /***********************************************************************************/ - /** @brief Free pointer from usage. */ - /***********************************************************************************/ - - Boolean UserProcess::Delete(VoidPtr ptr, const SizeT& sz) - { - if (!ptr || - sz == 0) - return No; - - PROCESS_MEMORY_ENTRY* entry = this->MemoryEntryList; - - while (entry != nullptr) - { - if (entry->MemoryEntry == ptr) - { -#ifdef __ZKA_AMD64__ - auto pd = hal_read_cr3(); - hal_write_cr3(reinterpret_cast(this->MemoryPD)); - - auto ret = mm_delete_heap(entry->MemoryEntry); - - hal_write_cr3(pd); - - return ret; -#else - Bool ret = mm_delete_heap(ptr); - return ret; -#endif - } - - entry = entry->MemoryNext; - } - - return No; - } - - /***********************************************************************************/ - /// @brief Gets the name of the current process. - /***********************************************************************************/ - - const Char* UserProcess::GetProcessName() noexcept - { - return this->Name; - } - - /***********************************************************************************/ - /// @brief Gets the owner of the process. - /***********************************************************************************/ - - const User* UserProcess::GetOwner() noexcept - { - return this->Owner; - } - - /// @brief UserProcess status getter. - const ProcessStatusKind& UserProcess::GetStatus() noexcept - { - return this->Status; - } - - /***********************************************************************************/ - /** - @brief Affinity is the time slot allowed for the process. - */ - /***********************************************************************************/ - - const AffinityKind& UserProcess::GetAffinity() noexcept - { - return this->Affinity; - } - - /***********************************************************************************/ - /** - @brief Process exit method. - */ - /***********************************************************************************/ - - void UserProcess::Exit(const Int32& exit_code) - { - this->Status = ProcessStatusKind::kDead; - - fLastExitCode = exit_code; - cLastExitCode = exit_code; - - auto memory_list = this->MemoryEntryList; - - // Deleting memory lists. Make sure to free all of them. - while (memory_list) - { - if (memory_list->MemoryEntry) - { -#ifdef __ZKA_AMD64__ - auto pd = hal_read_cr3(); - hal_write_cr3(reinterpret_cast(this->MemoryPD)); -#endif - - MUST_PASS(mm_delete_heap(memory_list->MemoryEntry)); - -#ifdef __ZKA_AMD64__ - hal_write_cr3(pd); -#endif - } - - auto next = memory_list->MemoryNext; - - mm_delete_heap(memory_list); - memory_list = nullptr; - - memory_list = next; - } - - //! Free the memory's page directory. - HAL::mm_free_bitmap(reinterpret_cast(this->MemoryPD)); - - //! Delete image if not done already. - if (this->Image && mm_is_valid_heap(this->Image)) - mm_delete_heap(this->Image); - - if (this->StackFrame && mm_is_valid_heap(this->StackFrame)) - mm_delete_heap((VoidPtr)this->StackFrame); - - this->Image = nullptr; - this->StackFrame = nullptr; - - if (this->Kind == kExectuableDLLKind) - { - Bool success = false; - rtl_fini_dll(this, this->PefDLLDelegate, &success); - - if (success) - { - this->PefDLLDelegate = nullptr; - } - } - - if (this->StackReserve) - delete[] this->StackReserve; - - this->ProcessId = 0; - - if (this->ProcessId > 0) - UserProcessScheduler::The().Remove(this->ProcessId); - } - - /***********************************************************************************/ - /// @brief Add process to list. - /// @param process the process *Ref* class. - /// @return the process index inside the team. - /***********************************************************************************/ - - SizeT UserProcessScheduler::Add(UserProcess process) - { - if (mTeam.mProcessAmount > kSchedProcessLimitPerTeam) - return 0; - -#ifdef __ZKA_AMD64__ - process.MemoryPD = reinterpret_cast(HAL::mm_alloc_bitmap(Yes, Yes, sizeof(PDE), Yes)); -#endif // __ZKA_AMD64__ - - process.Status = ProcessStatusKind::kStarting; - - process.StackFrame = (HAL::StackFramePtr)mm_new_heap(sizeof(HAL::StackFrame), Yes, Yes); - - if (!process.StackFrame) - { - process.Crash(); - return -kErrorProcessFault; - } - - // Create heap according to type of process. - if (process.Kind == UserProcess::kExectuableDLLKind) - { - process.PefDLLDelegate = rtl_init_dll(&process); - } - - if (!process.Image) - { - if (process.Kind != UserProcess::kExectuableDLLKind) - { - process.Crash(); - return -kErrorProcessFault; - } - } - - // get preferred stack size by app. - const auto cMaxStackSize = process.StackSize; - process.StackReserve = (UInt8*)mm_new_heap(sizeof(UInt8) * cMaxStackSize, Yes, Yes); - - if (!process.StackReserve) - { - mm_delete_heap(process.StackFrame); - process.StackFrame = nullptr; - return -kErrorProcessFault; - } - - ++mTeam.mProcessAmount; - - process.ProcessId = mTeam.mProcessAmount; - process.Status = ProcessStatusKind::kRunning; - - // avoid the pitfalls of moving process. - auto ret_pid = process.ProcessId; - - mTeam.AsArray()[process.ProcessId] = move(process); - - return ret_pid; - } - - /***********************************************************************************/ - /// @brief Retrieves the singleton of the process scheduler. - /***********************************************************************************/ - - UserProcessScheduler& UserProcessScheduler::The() - { - MUST_PASS(kProcessScheduler); - return *kProcessScheduler; - } - - /***********************************************************************************/ - - /// @brief Remove process from list. - /// @param process_id process slot inside team. - /// @retval true process was removed. - /// @retval false process doesn't exist in team. - - /***********************************************************************************/ - - Bool UserProcessScheduler::Remove(ProcessID process_id) - { - // check if process is within range. - if (process_id > mTeam.AsArray().Count()) - return No; - - mTeam.AsArray()[process_id].Status = ProcessStatusKind::kDead; - --mTeam.mProcessAmount; - - return Yes; - } - - const Bool UserProcessScheduler::IsUser() - { - return Yes; - } - - const Bool UserProcessScheduler::IsKernel() - { - return No; - } - - const Bool UserProcessScheduler::HasMP() - { - return kHandoverHeader->f_HardwareTables.f_MultiProcessingEnabled; - } - - /***********************************************************************************/ - - /// @brief Run User scheduler object. - /// @return Process executed within team. - - /***********************************************************************************/ - - SizeT UserProcessScheduler::Run() noexcept - { - SizeT process_index = 0; //! we store this guy to tell the scheduler how many - //! things we have scheduled. - - for (; process_index < mTeam.AsArray().Capacity(); ++process_index) - { - auto& process = mTeam.AsArray()[process_index]; - - //! check if process needs to be scheduled. - if (UserProcessHelper::CanBeScheduled(process)) - { - // Set current process header. - this->CurrentProcess() = process; - - process.PTime = static_cast(process.Affinity); - - UserProcessScheduler::The().CurrentProcess().Leak().Status = ProcessStatusKind::kFrozen; - UserProcessScheduler::The().CurrentProcess() = process; - - kcout << "Switch to '" << process.Name << "'.\r"; - - // tell helper to find a core to schedule on. - if (!UserProcessHelper::Switch(process.Image, &process.StackReserve[process.StackSize - 1], process.StackFrame, - process.ProcessId)) - { - process.Crash(); - continue; - } - } - else - { - if (process.Status == ProcessStatusKind::kRunning) - --process.PTime; - } - } - - kcout << "Scheduled Process Count: " << number(process_index) << endl; - - return process_index; - } - - /// @brief Gets the current scheduled team. - /// @return - UserProcessTeam& UserProcessScheduler::CurrentTeam() - { - return mTeam; - } - - /// @internal - - /// @brief Gets current running process. - /// @return - Ref& UserProcessScheduler::CurrentProcess() - { - return mTeam.AsRef(); - } - - /// @brief Current proccess id getter. - /// @return UserProcess ID integer. - PID& UserProcessHelper::TheCurrentPID() - { - kcout << "UserProcessHelper::TheCurrentPID: Leaking ProcessId...\r"; - return kProcessScheduler->CurrentProcess().Leak().ProcessId; - } - - /// @brief Check if process can be schedulded. - /// @param process the process reference. - /// @retval true can be schedulded. - /// @retval false cannot be schedulded. - Bool UserProcessHelper::CanBeScheduled(const UserProcess& process) - { - if (process.Status == ProcessStatusKind::kKilled || - process.Status == ProcessStatusKind::kDead) - return No; - - if (!process.Image && - process.Kind == UserProcess::kExectuableKind) - return No; - - return process.PTime < 1 && process.Status == ProcessStatusKind::kRunning; - } - - /***********************************************************************************/ - /** - * @brief Allocate a scheduler. - */ - /***********************************************************************************/ - - Bool UserProcessHelper::InitializeScheduler() - { - if (!kProcessScheduler) - { - kProcessScheduler = new UserProcessScheduler(); - } - - if (!kHardwareThreadScheduler) - { - kHardwareThreadScheduler = new HardwareThreadScheduler(); - } - - return Yes; - } - - /***********************************************************************************/ - /** - * @brief Start scheduling current AP/Hart/Core. - */ - /***********************************************************************************/ - SizeT UserProcessHelper::StartScheduling() - { - if (!kProcessScheduler) - return 0; - - return kProcessScheduler->Run(); - } - - /***********************************************************************************/ - /** - * \brief Does a context switch in a CPU. - * \param the_stack the stackframe of the running app. - * \param new_pid the process's PID. - */ - /***********************************************************************************/ - - Bool UserProcessHelper::Switch(VoidPtr image_ptr, UInt8* stack, HAL::StackFramePtr frame_ptr, const PID& new_pid) - { - if (!stack || !frame_ptr || !image_ptr || new_pid < 0) - return No; - - for (SizeT index = 0UL; index < HardwareThreadScheduler::The().Count(); ++index) - { - if (HardwareThreadScheduler::The()[index].Leak()->Kind() == kInvalidHart) - continue; - - if (HardwareThreadScheduler::The()[index].Leak()->Kind() != - ThreadKind::kHartBoot && - HardwareThreadScheduler::The()[index].Leak()->Kind() != - ThreadKind::kHartSystemReserved) - { - PID prev_pid = UserProcessHelper::TheCurrentPID(); - UserProcessHelper::TheCurrentPID() = new_pid; - - auto prev_ptime = HardwareThreadScheduler::The()[index].Leak()->fPTime; - HardwareThreadScheduler::The()[index].Leak()->fPTime = UserProcessScheduler::The().CurrentTeam().AsArray()[new_pid].ProcessId; - Bool ret = HardwareThreadScheduler::The()[index].Leak()->Switch(image_ptr, stack, frame_ptr); - - if (!ret) - { - HardwareThreadScheduler::The()[index].Leak()->fPTime = prev_ptime; - UserProcessHelper::TheCurrentPID() = prev_pid; - - continue; - } - } - } - - return false; - } - - /// @brief this checks if any process is on the team. - UserProcessScheduler::operator bool() - { - return mTeam.AsArray().Count() > 0; - } - - /// @brief this checks if no process is on the team. - bool UserProcessScheduler::operator!() - { - return mTeam.AsArray().Count() == 0; - } -} // namespace Kernel diff --git a/dev/zka/src/UserProcessTeam.cc b/dev/zka/src/UserProcessTeam.cc new file mode 100644 index 00000000..22b158b9 --- /dev/null +++ b/dev/zka/src/UserProcessTeam.cc @@ -0,0 +1,47 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +/***********************************************************************************/ +/// @file UserProcessTeam.cxx +/// @brief UserProcess teams implementation. +/***********************************************************************************/ + +#include + +namespace Kernel +{ + /***********************************************************************************/ + /// @brief UserProcess list array getter. + /// @return The list of process to schedule. + /***********************************************************************************/ + + Array& UserProcessTeam::AsArray() + { + return mProcessList; + } + + /***********************************************************************************/ + /// @brief Get team ID. + /// @return The team's ID. + /***********************************************************************************/ + + ProcessID& UserProcessTeam::Id() noexcept + { + return mTeamId; + } + + /***********************************************************************************/ + /// @brief Get current process getter as Ref. + /// @return The current process header. + /***********************************************************************************/ + + Ref& UserProcessTeam::AsRef() + { + return mCurrentProcess; + } +} // namespace Kernel + +// last rev 05-03-24 diff --git a/dev/zka/src/UserProcessTeam.cxx b/dev/zka/src/UserProcessTeam.cxx deleted file mode 100644 index 6d3fa2db..00000000 --- a/dev/zka/src/UserProcessTeam.cxx +++ /dev/null @@ -1,47 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -/***********************************************************************************/ -/// @file UserProcessTeam.cxx -/// @brief UserProcess teams implementation. -/***********************************************************************************/ - -#include - -namespace Kernel -{ - /***********************************************************************************/ - /// @brief UserProcess list array getter. - /// @return The list of process to schedule. - /***********************************************************************************/ - - Array& UserProcessTeam::AsArray() - { - return mProcessList; - } - - /***********************************************************************************/ - /// @brief Get team ID. - /// @return The team's ID. - /***********************************************************************************/ - - ProcessID& UserProcessTeam::Id() noexcept - { - return mTeamId; - } - - /***********************************************************************************/ - /// @brief Get current process getter as Ref. - /// @return The current process header. - /***********************************************************************************/ - - Ref& UserProcessTeam::AsRef() - { - return mCurrentProcess; - } -} // namespace Kernel - -// last rev 05-03-24 diff --git a/dev/zka/src/Utils.cc b/dev/zka/src/Utils.cc new file mode 100644 index 00000000..7427fe34 --- /dev/null +++ b/dev/zka/src/Utils.cc @@ -0,0 +1,212 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include +#include + +namespace Kernel +{ + Int rt_string_cmp(const Char* src, const Char* cmp, Size size) + { + if (!cmp || + !src) + return 1; + + Int32 counter = 0; + + for (Size index = 0; index < size; ++index) + { + if (src[index] != cmp[index]) + ++counter; + } + + return counter; + } + + void rt_zero_memory(voidPtr pointer, Size len) + { + rt_set_memory(pointer, 0, len); + } + + Size rt_string_len(const Char* str, SizeT _len) + { + Size len{0}; + while (str[len] != '\0') + { + if (len > _len) + { + return 0; + } + + len++; + } + + return len; + } + + Size rt_string_len(const Char* ptr) + { + if (*ptr == 0) + return 0; + + SizeT cnt = 0; + + while (ptr[cnt] != (Char)0) + { + cnt++; + } + + return cnt; + } + + voidPtr rt_set_memory(voidPtr src, UInt32 value, Size len) + { + if (!src || len < 1) + return nullptr; + + UInt32* start = reinterpret_cast(src); + + while (len) + { + *start = value; + ++start; + --len; + } + + return (voidPtr)start; + } + + Int rt_move_memory(const voidPtr src, voidPtr dst, Size len) + { + if (len < 1) + return -2; + if (!src || !dst) + return -1; + + char* srcChr = reinterpret_cast(src); + char* dstChar = reinterpret_cast(dst); + Size index = 0; + + while (index < len) + { + dstChar[index] = srcChr[index]; + srcChr[index] = 0; + + ++index; + } + + return 0; + } + + Int rt_copy_memory(const voidPtr src, voidPtr dst, Size len) + { + if (len < 1) + return -2; + + char* srcChr = reinterpret_cast(src); + char* dstChar = reinterpret_cast(dst); + Size index = 0; + + while (index < len) + { + dstChar[index] = srcChr[index]; + ++index; + } + + return index; + } + + const Char* alloc_string(const Char* text) + { + if (!text) + return nullptr; + + const Char* string = new Char[rt_string_len(text)]; + if (!string) + return nullptr; + + voidPtr vText = reinterpret_cast(const_cast(text)); + voidPtr vStr = reinterpret_cast(const_cast(string)); + rt_copy_memory(vText, vStr, rt_string_len(text)); + + return string; + } + + Int rt_to_uppercase(Int character) + { + if (character >= 'a' && character <= 'z') + return character - 0x20; + + return character; + } + + Int rt_to_lower(Int character) + { + if (character >= 'A' && character <= 'Z') + return character + 0x20; + + return character; + } + + bool rt_to_string(Char* str, Int limit, Int base) + { + if (limit == 0) + return false; + + Int copy_limit = limit; + Int cnt = 0; + Int ret = base; + + while (limit != 1) + { + ret = ret % 10; + str[cnt] = ret; + + ++cnt; + --limit; + --ret; + } + + str[copy_limit] = '\0'; + return true; + } + + Boolean is_space(Char chr) + { + return chr == ' '; + } + + Boolean is_newln(Char chr) + { + return chr == '\n'; + } + + voidPtr rt_string_in_string(const Char* in, const Char* needle) + { + for (SizeT i = 0; i < rt_string_len(in); ++i) + { + if (rt_string_cmp(in + i, needle, rt_string_len(needle)) == 0) + return reinterpret_cast(const_cast(in + i)); + } + + return nullptr; + } + + // @brief Checks for a string start at the character. + + char* rt_string_has_char(char* str, const Char chr) + { + while (*str != chr) + { + ++str; + + if (*str == 0) + return nullptr; + } + + return str; + } +} // namespace Kernel diff --git a/dev/zka/src/Utils.cxx b/dev/zka/src/Utils.cxx deleted file mode 100644 index fe0d7ed4..00000000 --- a/dev/zka/src/Utils.cxx +++ /dev/null @@ -1,212 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include -#include - -namespace Kernel -{ - Int rt_string_cmp(const Char* src, const Char* cmp, Size size) - { - if (!cmp || - !src) - return 1; - - Int32 counter = 0; - - for (Size index = 0; index < size; ++index) - { - if (src[index] != cmp[index]) - ++counter; - } - - return counter; - } - - void rt_zero_memory(voidPtr pointer, Size len) - { - rt_set_memory(pointer, 0, len); - } - - Size rt_string_len(const Char* str, SizeT _len) - { - Size len{0}; - while (str[len] != '\0') - { - if (len > _len) - { - return 0; - } - - len++; - } - - return len; - } - - Size rt_string_len(const Char* ptr) - { - if (*ptr == 0) - return 0; - - SizeT cnt = 0; - - while (ptr[cnt] != (Char)0) - { - cnt++; - } - - return cnt; - } - - voidPtr rt_set_memory(voidPtr src, UInt32 value, Size len) - { - if (!src || len < 1) - return nullptr; - - UInt32* start = reinterpret_cast(src); - - while (len) - { - *start = value; - ++start; - --len; - } - - return (voidPtr)start; - } - - Int rt_move_memory(const voidPtr src, voidPtr dst, Size len) - { - if (len < 1) - return -2; - if (!src || !dst) - return -1; - - char* srcChr = reinterpret_cast(src); - char* dstChar = reinterpret_cast(dst); - Size index = 0; - - while (index < len) - { - dstChar[index] = srcChr[index]; - srcChr[index] = 0; - - ++index; - } - - return 0; - } - - Int rt_copy_memory(const voidPtr src, voidPtr dst, Size len) - { - if (len < 1) - return -2; - - char* srcChr = reinterpret_cast(src); - char* dstChar = reinterpret_cast(dst); - Size index = 0; - - while (index < len) - { - dstChar[index] = srcChr[index]; - ++index; - } - - return index; - } - - const Char* alloc_string(const Char* text) - { - if (!text) - return nullptr; - - const Char* string = new Char[rt_string_len(text)]; - if (!string) - return nullptr; - - voidPtr vText = reinterpret_cast(const_cast(text)); - voidPtr vStr = reinterpret_cast(const_cast(string)); - rt_copy_memory(vText, vStr, rt_string_len(text)); - - return string; - } - - Int rt_to_uppercase(Int character) - { - if (character >= 'a' && character <= 'z') - return character - 0x20; - - return character; - } - - Int rt_to_lower(Int character) - { - if (character >= 'A' && character <= 'Z') - return character + 0x20; - - return character; - } - - bool rt_to_string(Char* str, Int limit, Int base) - { - if (limit == 0) - return false; - - Int copy_limit = limit; - Int cnt = 0; - Int ret = base; - - while (limit != 1) - { - ret = ret % 10; - str[cnt] = ret; - - ++cnt; - --limit; - --ret; - } - - str[copy_limit] = '\0'; - return true; - } - - Boolean is_space(Char chr) - { - return chr == ' '; - } - - Boolean is_newln(Char chr) - { - return chr == '\n'; - } - - voidPtr rt_string_in_string(const Char* in, const Char* needle) - { - for (SizeT i = 0; i < rt_string_len(in); ++i) - { - if (rt_string_cmp(in + i, needle, rt_string_len(needle)) == 0) - return reinterpret_cast(const_cast(in + i)); - } - - return nullptr; - } - - // @brief Checks for a string start at the character. - - char* rt_string_has_char(char* str, const Char chr) - { - while (*str != chr) - { - ++str; - - if (*str == 0) - return nullptr; - } - - return str; - } -} // namespace Kernel diff --git a/dev/zka/src/Variant.cc b/dev/zka/src/Variant.cc new file mode 100644 index 00000000..76ff2f04 --- /dev/null +++ b/dev/zka/src/Variant.cc @@ -0,0 +1,33 @@ +/* ------------------------------------------- + + Copyright ZKA Web Services Co. + +------------------------------------------- */ + +#include + +namespace Kernel +{ + const Char* Variant::ToString() + { + switch (fKind) + { + case VariantKind::kXML: + return ("Class:{XML}"); + case VariantKind::kJson: + return ("Class:{Json}"); + case VariantKind::kString: + return ("Class:{String}"); + case VariantKind::kBlob: + return ("Class:{Blob}"); + default: + return ("Class:{Null}"); + } + } + + /// @brief Leak variant's instance. + VoidPtr Variant::Leak() + { + return fPtr; + } +} // namespace Kernel diff --git a/dev/zka/src/Variant.cxx b/dev/zka/src/Variant.cxx deleted file mode 100644 index 6314ed9e..00000000 --- a/dev/zka/src/Variant.cxx +++ /dev/null @@ -1,33 +0,0 @@ -/* ------------------------------------------- - - Copyright ZKA Web Services Co. - -------------------------------------------- */ - -#include - -namespace Kernel -{ - const Char* Variant::ToString() - { - switch (fKind) - { - case VariantKind::kXML: - return ("Class:{XML}"); - case VariantKind::kJson: - return ("Class:{Json}"); - case VariantKind::kString: - return ("Class:{String}"); - case VariantKind::kBlob: - return ("Class:{Blob}"); - default: - return ("Class:{Null}"); - } - } - - /// @brief Leak variant's instance. - VoidPtr Variant::Leak() - { - return fPtr; - } -} // namespace Kernel -- cgit v1.2.3