diff --git a/.editorconfig b/.editorconfig index a56d06f..f0406f5 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,14 +6,14 @@ end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true -max_line_length = 120 +max_line_length = 160 [*.md] trim_trailing_whitespace = false [*.d] dfmt_brace_style = otbs -dfmt_soft_max_line_length = 80 +dfmt_soft_max_line_length = 120 dfmt_align_switch_statements = true dfmt_outdent_attributes = true dfmt_split_operator_at_line_end = false diff --git a/.gitignore b/.gitignore index 232c57c..553da73 100644 --- a/.gitignore +++ b/.gitignore @@ -1,25 +1,9 @@ -.wild-cache -build.dot -PowerNex.krl -PowerNex.map -PowerNex.dsk -wild -obj/ -PowerNex.iso +powernex.iso bochsout.txt bx_enh_dbg.ini /cc COM1.log -Utils/GenerateSymbols -Utils/MakeInitrd .vscode -*.psf -*.o -.dub -Initrd/Binary -*.a -*.krl -*.di *~ *.ninja* *.reggae diff --git a/build b/build deleted file mode 100755 index 1831a7a..0000000 --- a/build +++ /dev/null @@ -1,204 +0,0 @@ -#!./wild -{ - "variables": { - }, - "processors": { - "dc": { - "command": "cc/bin/powernex-dmd", - "arguments": "-m64 -fPIC -debug -c -g -IKernel/src -JKernel/src -defaultlib= -debuglib= -version=bare_metal -debug=allocations -of$out $in" - }, - "dc-header": { - "command": "cc/bin/powernex-dmd", - "arguments": "-m64 -fPIC -debug -c -g -IKernel/src -JKernel/src -defaultlib= -debuglib= -version=bare_metal -debug=allocations -o- -Hf$out $in" - }, - "ac": { - "command": "cc/bin/x86_64-powernex-as", - "arguments": "--64 -o $out $in" - }, - "ld": { - "command": "cc/bin/x86_64-powernex-ld", - "arguments": "-o $out -z max-page-size=0x1000 $in -T Kernel/src/Kernel.ld" - }, - "iso": { - "command": "grub-mkrescue", - "arguments": "-d /usr/lib/grub/i386-pc -o $out $in" - }, - "ndc": { - "command": "dmd", - "arguments": "-of$out -odUtils/obj $in" - }, - "copy": { - "command": "cp", - "arguments": "-f $in $out" - }, - "gzip-d": { - "command": "gzip", - "arguments": "-d -f $in" - }, - "GenerateSymbols" : { - "command": "Utils/GenerateSymbols", - "arguments": "$in $out" - }, - "MakeInitrd" : { - "command": "Utils/MakeInitrd", - "arguments": "$in $out" - }, - - "RemoveImports" : { - "command": "sed", - "arguments": "-e 's/^import .*//g' -e 's/enum/import PowerNex.Data.Address;\\nenum/' $in > $out" - }, - - "user-dc": { - "command": "cc/bin/powernex-dmd", - "arguments": "-m64 -debug -c -g -IUserspace/libRT/src -IUserspace/libPowerNex/src -defaultlib= -debuglib= -version=bare_metal -debug=allocations -of$out $in" - }, - "user-ac": { - "command": "cc/bin/x86_64-powernex-as", - "arguments": "--64 -o $out $in" - }, - "user-ar": { - "command": "cc/bin/x86_64-powernex-ar", - "arguments": "rcs $out $in" - }, - "user-ld": { - "command": "cc/bin/x86_64-powernex-ld", - "arguments": "-o $out $in Userspace/lib/libRT.a Userspace/lib/libPowerNex.a" - } - }, - "phonies": { - "Userspace/Syscall.di" : { - "processor": "dc-header", - "input": "Kernel/src/System/Syscall.d" - } - }, - "missing": { - "Utils/GenerateSymbols": { - "processor": "ndc", - "input": "Utils/GenerateSymbols.d" - }, - "Utils/MakeInitrd": { - "processor": "ndc", - "input": "Utils/MakeInitrd.d" - }, - "Kernel/src/Bin/ConsoleFont.psf.gz": { - "processor": "copy", - "input": "/usr/share/kbd/consolefonts/lat9w-16.psfu.gz" - } - }, - "rules": { - "Userspace/libRT/obj/DCode.o": { - "processor": "user-dc", - "input": "Userspace/libRT/src/*.d" - }, - "Userspace/lib/libRT.a": { - "processor": "user-ar", - "input": "Userspace/libRT/obj/*.o" - }, - - - "Userspace/libPowerNex/src/PowerNex/Internal/Syscall.di": { - "processor": "RemoveImports", - "input": "Userspace/Syscall.di" - }, - "Userspace/libPowerNex/obj/DCode.o": { - "processor": "user-dc", - "input": "Userspace/libPowerNex/src/*.d" - }, - "Userspace/lib/libPowerNex.a": { - "processor": "user-ar", - "input": "Userspace/libPowerNex/obj/*.o" - }, - - - "Userspace/Init/obj/DCode.o": { - "processor": "user-dc", - "input": "Userspace/Init/src/*.d" - }, - "Initrd/Binary/Init": { - "processor": "user-ld", - "input": "Userspace/Init/obj/*.o" - }, - - "Userspace/Shell/obj/DCode.o": { - "processor": "user-dc", - "input": "Userspace/Shell/src/*.d" - }, - "Initrd/Binary/Shell": { - "processor": "user-ld", - "input": "Userspace/Shell/obj/*.o" - }, - - - "Userspace/HelloWorld/obj/DCode.o": { - "processor": "user-dc", - "input": "Userspace/HelloWorld/src/*.d" - }, - "Initrd/Binary/HelloWorld": { - "processor": "user-ld", - "input": "Userspace/HelloWorld/obj/*.o" - }, - - "Userspace/Cat/obj/DCode.o": { - "processor": "user-dc", - "input": "Userspace/Cat/src/*.d" - }, - "Initrd/Binary/Cat": { - "processor": "user-ld", - "input": "Userspace/Cat/obj/*.o" - }, - - "Userspace/DLogo/obj/DCode.o": { - "processor": "user-dc", - "input": "Userspace/DLogo/src/*.d" - }, - "Initrd/Binary/DLogo": { - "processor": "user-ld", - "input": "Userspace/DLogo/obj/*.o" - }, - - "Kernel/obj/DCode.o": { - "processor": "dc", - "input": "Kernel/src/*.d" - }, - "Kernel/obj/asm/*.o": { - "processor": "ac", - "input": "Kernel/src/*.S" - }, - "Disk/boot/PowerNex.krl": { - "processor": "ld", - "input": "Kernel/obj/*.o" - }, - "Initrd/Data/PowerNex.map": { - "processor": "GenerateSymbols", - "input": "Disk/boot/PowerNex.krl" - }, - "Kernel/src/Bin/ConsoleFont.psf": { - "processor": "gzip-d", - "input": "Kernel/src/Bin/ConsoleFont.psf.gz" - }, - "Disk/boot/PowerNex.dsk": { - "processor": "MakeInitrd", - "input": "Initrd" - }, - "PowerNex.iso": { - "processor": "iso", - "input": "Disk" - } - }, - "targets": [ - "Kernel/src/Bin/ConsoleFont.psf", - "Disk/boot/PowerNex.krl", - "Initrd/Data/PowerNex.map", - "Userspace/libPowerNex/src/PowerNex/Internal/Syscall.di", - "Userspace/lib/libRT.a", - "Userspace/lib/libPowerNex.a", - "Initrd/Binary/Init", - "Initrd/Binary/Shell", - "Initrd/Binary/HelloWorld", - "Initrd/Binary/Cat", - "Initrd/Binary/DLogo", - "Disk/boot/PowerNex.dsk", - "PowerNex.iso" - ] -} diff --git a/env.sh b/env.sh index 4d96ce2..e7d99b2 100644 --- a/env.sh +++ b/env.sh @@ -4,7 +4,7 @@ function initPowerNex() { dub run reggae -- -b ninja . fi } -function c() {rm -rf objs && echo "Clean successful" || echo "Clean failed"} +function c() {rm -rf objs powernex.iso && echo "Clean successful" || echo "Clean failed"} function v() {initPowerNex && ninja} -function b() {v && qemu-system-x86_64 -cdrom PowerNex.iso -m 2048 -monitor stdio -serial file:COM1.log -no-reboot 2>/dev/null} -function a() {addr2line -e Disk/boot/PowerNex.krl $1} +function b() {v && qemu-system-x86_64 -cdrom powernex.iso -m 2048 -monitor stdio -serial file:COM1.log -no-reboot 2>/dev/null} +function a() {addr2line -e disk/boot/powernex.krl $1} diff --git a/kernel/src/acpi/rsdp.d b/kernel/src/acpi/rsdp.d index 9c64c56..64d74ae 100644 --- a/kernel/src/acpi/rsdp.d +++ b/kernel/src/acpi/rsdp.d @@ -1,52 +1,52 @@ -module ACPI.RSDP; +module acpi.rsdp; -import Data.Address; -import Data.TextBuffer : scr = GetBootTTY; -import IO.Port; +import data.address; +import data.textbuffer : scr = getBootTTY; +import io.port; struct RSDPDescriptor { align(1): - char[8] Signature; - ubyte Checksum; - char[6] OEMID; - ubyte Revision; - PhysAddress32 RSDTAddress; + char[8] signature; + ubyte checksum; + char[6] oemID; + ubyte revision; + PhysAddress32 rsdtAddress; } struct RSDPDescriptor20 { align(1): RSDPDescriptor firstPart; - uint Length; - PhysAddress XSDTAddress; - ubyte ExtendedChecksum; + uint length; + PhysAddress xsdtAddress; + ubyte extendedChecksum; ubyte[3] reserved; } struct ACPISDTHeader { align(1): - char[4] Signature; - uint Length; - ubyte Revision; - ubyte Checksum; - char[6] OEMID; - char[8] OEMTableID; - uint OEMRevision; - uint CreatorID; - uint CreatorRevision; + char[4] signature; + uint length; + ubyte revision; + ubyte checksum; + char[6] oemID; + char[8] oemTableID; + uint oemRevision; + uint creatorID; + uint creatorRevision; } struct RSDT { ACPISDTHeader h; - PhysAddress32[] PointerToOtherSDT() { + PhysAddress32[] pointerToOtherSDT() { auto ptr = VirtAddress(&h) + h.sizeof; - return ptr.Ptr!PhysAddress32[0 .. (h.Length - h.sizeof) / 4]; + return ptr.ptr!PhysAddress32[0 .. (h.length - h.sizeof) / 4]; } - T* GetSDT(T)(char[4] sig) { - foreach (PhysAddress32 addr; PointerToOtherSDT) { - ACPISDTHeader* hdr = addr.Virtual.Ptr!ACPISDTHeader; - if (hdr && hdr.Signature == sig) + T* getSDT(T)(char[4] sig) { + foreach (PhysAddress32 addr; pointerToOtherSDT) { + ACPISDTHeader* hdr = addr.virtual.ptr!ACPISDTHeader; + if (hdr && hdr.signature == sig) return cast(T*)hdr; } @@ -57,123 +57,123 @@ struct RSDT { struct FADT { align(1): ACPISDTHeader h; - uint FirmwareCtrl; - uint Dsdt; - - ubyte Reserved; - - ubyte PreferredPowerManagementProfile; - ushort SCI_Interrupt; - uint SMI_CommandPort; - ubyte AcpiEnable; - ubyte AcpiDisable; - ubyte S4BIOS_REQ; - ubyte PSTATE_Control; - uint PM1aEventBlock; - uint PM1bEventBlock; - uint PM1aControlBlock; - uint PM1bControlBlock; - uint PM2ControlBlock; - uint PMTimerBlock; - uint GPE0Block; - uint GPE1Block; - ubyte PM1EventLength; - ubyte PM1ControlLength; - ubyte PM2ControlLength; - ubyte PMTimerLength; - ubyte GPE0Length; - ubyte GPE1Length; - ubyte GPE1Base; - ubyte CStateControl; - ushort WorstC2Latency; - ushort WorstC3Latency; - ushort FlushSize; - ushort FlushStride; - ubyte DutyOffset; - ubyte DutyWidth; - ubyte DayAlarm; - ubyte MonthAlarm; - ubyte Century; - - ushort BootArchitectureFlags; - - ubyte Reserved2; - uint Flags; - - GenericAddressStructure ResetReg; - - ubyte ResetValue; - ubyte[2] ARMBootArch; - ubyte MinorVersion; + uint firmwareCtrl; + uint dsdt; + + ubyte reserved; + + ubyte preferredPowerManagementProfile; + ushort sciInterrupt; + uint smiCommandPort; + ubyte acpiEnable; + ubyte acpiDisable; + ubyte s4biosREQ; + ubyte pstateControl; + uint pm1aEventBlock; + uint pm1bEventBlock; + uint pm1aControlBlock; + uint pm1bControlBlock; + uint pm2ControlBlock; + uint pmTimerBlock; + uint gpe0Block; + uint gpe1Block; + ubyte pm1EventLength; + ubyte pm1ControlLength; + ubyte pm2ControlLength; + ubyte pmTimerLength; + ubyte gpe0Length; + ubyte gpe1Length; + ubyte gpe1Base; + ubyte cstateControl; + ushort worstC2Latency; + ushort worstC3Latency; + ushort flushSize; + ushort flushStride; + ubyte dutyOffset; + ubyte dutyWidth; + ubyte dayAlarm; + ubyte monthAlarm; + ubyte century; + + ushort bootArchitectureFlags; + + ubyte reserved2; + uint flags; + + GenericAddressStructure resetReg; + + ubyte resetValue; + ubyte[2] armBootArch; + ubyte minorVersion; } struct GenericAddressStructure { align(1): - ubyte AddressSpace; - ubyte BitWidth; - ubyte BitOffset; - ubyte AccessSize; - ulong Address; + ubyte addressSpace; + ubyte bitWidth; + ubyte bitOffset; + ubyte accessSize; + ulong address; } struct RSDP { - void Init() { - VirtAddress addr = getAddress(); - if (!addr.Int) - return scr.Writeln("RSDP: Can't find!"); + void init() { + VirtAddress addr = _getAddress(); + if (!addr.num) + return scr.writeln("RSDP: Can't find!"); - RSDPDescriptor* rsdp = addr.Ptr!RSDPDescriptor; - if (!rsdp || !checksum(rsdp)) - return scr.Writeln("RSDPDescriptor: Invalid checksum"); + RSDPDescriptor* rsdp = addr.ptr!RSDPDescriptor; + if (!rsdp || !_checksum(rsdp)) + return scr.writeln("RSDPDescriptor: Invalid checksum"); - rsdt = rsdp.RSDTAddress.Virtual.Ptr!RSDT; + rsdt = rsdp.rsdtAddress.virtual.ptr!RSDT; if (!rsdt) - return scr.Writeln("RSDTDesciptor: invalid"); + return scr.writeln("RSDTDesciptor: invalid"); - fadt = rsdt.GetSDT!FADT("FACP"); - if (!fadt || !checksum(fadt, fadt.h.Length)) - return scr.Writeln("FADT: Invalid checksum"); + fadt = rsdt.getSDT!FADT("FACP"); + if (!fadt || !_checksum(fadt, fadt.h.length)) + return scr.writeln("FADT: Invalid checksum"); - scr.Writeln("ACPI Version: ", cast(int)fadt.h.Revision, ".", cast(int)fadt.MinorVersion); + scr.writeln("ACPI Version: ", cast(int)fadt.h.revision, ".", cast(int)fadt.minorVersion); - bool shouldEnable = !(fadt.SMI_CommandPort == 0 && fadt.AcpiEnable == 0 && fadt.AcpiDisable == 0 && fadt.PM1aControlBlock & 0x1); + bool shouldEnable = !(fadt.smiCommandPort == 0 && fadt.acpiEnable == 0 && fadt.acpiDisable == 0 && fadt.pm1aControlBlock & 0x1); if (shouldEnable) { - Out!ubyte(cast(ushort)fadt.SMI_CommandPort, fadt.AcpiEnable); - while ((In!ushort(cast(ushort)fadt.PM1aControlBlock) & 1) == 0) { + outp!ubyte(cast(ushort)fadt.smiCommandPort, fadt.acpiEnable); + while ((inp!ushort(cast(ushort)fadt.pm1aControlBlock) & 1) == 0) { } } - ACPISDTHeader* dsdt = PhysAddress32(fadt.Dsdt).Virtual.Ptr!ACPISDTHeader; - if (!dsdt || dsdt.Signature != "DSDT" || !checksum(dsdt, dsdt.Length)) - return scr.Writeln("DSDT: Invalid checksum"); + ACPISDTHeader* dsdt = PhysAddress32(fadt.dsdt).virtual.ptr!ACPISDTHeader; + if (!dsdt || dsdt.signature != "DSDT" || !_checksum(dsdt, dsdt.length)) + return scr.writeln("DSDT: Invalid checksum"); - ACPISDTHeader* ssdt = rsdt.GetSDT!ACPISDTHeader("SSDT"); + ACPISDTHeader* ssdt = rsdt.getSDT!ACPISDTHeader("SSDT"); - if (!ssdt || !checksum(ssdt, ssdt.Length)) - return scr.Writeln("SSDT: Invalid checksum"); + if (!ssdt || !_checksum(ssdt, ssdt.length)) + return scr.writeln("SSDT: Invalid checksum"); - ubyte* s5Addr = (VirtAddress(dsdt) + ACPISDTHeader.sizeof).Ptr!ubyte; - size_t len = dsdt.Length - dsdt.sizeof; + ubyte* s5Addr = (VirtAddress(dsdt) + ACPISDTHeader.sizeof).ptr!ubyte; + size_t len = dsdt.length - dsdt.sizeof; size_t i; for (i = 0; i < len; i++) { if (s5Addr[0 .. 4] == "_S5_") { - scr.Writeln("FOUND IT!"); + scr.writeln("FOUND IT!"); break; } s5Addr++; } if (i == len) - return scr.Writeln("DSDT: Can't find _S5_"); + return scr.writeln("DSDT: Can't find _S5_"); - scr.Writeln("_S5_ Bytes -2 to 4: ", cast(void*)s5Addr[-2], ", ", cast(void*)s5Addr[-1], ", ", + scr.writeln("_S5_ Bytes -2 to 4: ", cast(void*)s5Addr[-2], ", ", cast(void*)s5Addr[-1], ", ", cast(void*)s5Addr[0], ", ", cast(void*)s5Addr[1], ", ", cast(void*)s5Addr[2], ", ", cast(void*)s5Addr[3], ", ", cast(void*)s5Addr[4]); if (!((s5Addr[-1] == 0x08 || (s5Addr[-2] == 0x08 && s5Addr[-1] == '\\')) && s5Addr[4] == 0x12)) - return scr.Writeln("_S5_: Parse error"); + return scr.writeln("_S5_: Parse error"); s5Addr += 5; s5Addr += ((*s5Addr & 0xC0) >> 6) + 2; // calculate PkgLength size @@ -191,12 +191,12 @@ struct RSDP { sciEn = 1; valid = true; - scr.Writeln("#########RSDP VALID!########"); + scr.writeln("#########RSDP VALID!########"); } - void Shutdown() { + void shutdown() { if (!slpTypA) { - Out!ushort(0xB004, 0x0 | 0x2000); + outp!ushort(0xB004, 0x0 | 0x2000); asm { mov RAX, 0x1000; // Because page zero is not mapped @@ -208,16 +208,16 @@ struct RSDP { } } - Out!ushort(cast(ushort)fadt.PM1aControlBlock, slpTypA | slpEn); - if (fadt.PM1bControlBlock != 0) - Out!ushort(cast(ushort)fadt.PM1bControlBlock, slpTypB | slpEn); + outp!ushort(cast(ushort)fadt.pm1aControlBlock, slpTypA | slpEn); + if (fadt.pm1bControlBlock != 0) + outp!ushort(cast(ushort)fadt.pm1bControlBlock, slpTypB | slpEn); } - @property RSDT* RSDTInstance() { + @property RSDT* rsdtInstance() { return rsdt; } - @property FADT* FADTInstance() { + @property FADT* fadtInstance() { return fadt; } @@ -231,16 +231,16 @@ private: ushort slpEn; ushort sciEn; - VirtAddress getAddress() { + VirtAddress _getAddress() { VirtAddress ptr; for (ptr = VirtAddress(0xFFFF_FFFF_800E_0000); ptr < 0xFFFF_FFFF_800F_FFFF; ptr += 16) - if (ptr.Ptr!char[0 .. 8] == "RSD PTR ") + if (ptr.ptr!char[0 .. 8] == "RSD PTR ") return ptr; return VirtAddress(null); } - bool checksum(T)(T* obj, size_t size = T.sizeof) { + bool _checksum(T)(T* obj, size_t size = T.sizeof) { if (!obj) return false; ubyte* ptr = cast(ubyte*)obj; diff --git a/kernel/src/bin/consolefont.d b/kernel/src/bin/consolefont.d index 957f02d..9a2a6e7 100644 --- a/kernel/src/bin/consolefont.d +++ b/kernel/src/bin/consolefont.d @@ -1,17 +1,17 @@ -module Bin.ConsoleFont; +module bin.consolefont; -import Data.Font; -import Data.PSF; +import data.font; +import data.psf; -private __gshared ubyte[] ConsoleFont_PSF = cast(ubyte[])import("Bin/ConsoleFont.psf"); +private __gshared ubyte[] _consoleFont_PSF = cast(ubyte[])import("bin/consoleFont.psf"); -PSF GetConsoleFont() { - import Data.Util : InplaceClass; +PSF getConsoleFont() { + import data.util : inplaceClass; __gshared ubyte[__traits(classInstanceSize, PSF)] data; __gshared PSF consoleFont; if (!consoleFont) - consoleFont = InplaceClass!PSF(data, ConsoleFont_PSF); + consoleFont = inplaceClass!PSF(data, _consoleFont_PSF); return consoleFont; } diff --git a/kernel/src/boot.S b/kernel/src/boot.S new file mode 100644 index 0000000..19c0798 --- /dev/null +++ b/kernel/src/boot.S @@ -0,0 +1,426 @@ +.extern KERNEL_LMA +.SET KERNEL_VMA, 0xFFFFFFFF80000000 + +#8*0x1000 = 32KiB +.SET KERNEL_STACK_SIZE, 8 +.extern KERNEL_MODULES_START +.extern KERNEL_MODULES_END +.extern KERNEL_SYMBOLS_START +.extern KERNEL_SYMBOLS_END +.extern KERNEL_BSS_START +.extern KERNEL_END + +.set MULTIBOOT2_HEADER_MAGIC, 0xe85250d6 +.set MULTIBOOT_ARCHITECTURE_I386, 0 +.set MULTIBOOT_HEADER_TAG_ADDRESS, 2 +.set MULTIBOOT_HEADER_TAG_ENTRY_ADDRESS, 3 +.set MULTIBOOT_HEADER_TAG_END, 0 + +.section .multiboot +.align 8 +multiboot2_header: + .int MULTIBOOT2_HEADER_MAGIC + .int MULTIBOOT_ARCHITECTURE_I386 + .int (multiboot2_header_end - multiboot2_header) + .int -(MULTIBOOT2_HEADER_MAGIC + MULTIBOOT_ARCHITECTURE_I386 + (multiboot2_header_end - multiboot2_header)) + + .short MULTIBOOT_HEADER_TAG_ADDRESS + .short 0 + .int 24 + .int multiboot2_header + .int KERNEL_LMA + .int (KERNEL_BSS_START - KERNEL_VMA) + .int (KERNEL_END - KERNEL_VMA) + + .short MULTIBOOT_HEADER_TAG_ENTRY_ADDRESS + .short 0 + .int 12 + .int start - KERNEL_VMA + + .short MULTIBOOT_HEADER_TAG_END + .short 0 + .int 0 +multiboot2_header_end: + +.text +.code32 + +.extern start64 +.global start +start: + cli + + movl %eax, (multiboot_magic - KERNEL_VMA) + movl %ebx, (multiboot_ptr - KERNEL_VMA) + + # Check to check if we can check if x64 is supported + mov $0x80000000, %eax + cpuid + cmp $0x80000001, %eax + jb notx64Capable + + # Check so that x64 is supported + mov $0x80000001, %eax + cpuid + test $(1 << 29), %edx + jz notx64Capable + + # Enable PAE + mov %cr4, %eax + bts $5, %eax # physical address extension + mov %eax, %cr4 + + # Set long mode bit in EFER MSR + mov $0xC0000080, %ecx # Refers to EFER MSR + rdmsr + bts $11, %eax # No execute enable + bts $0, %eax # SYSCALL/SYSRET + bts $8, %eax # Long mode enable + wrmsr + + mov $(PML4 - KERNEL_VMA), %eax + mov %eax, %cr3 + + # Enable paging and write protected + mov %cr0, %eax + bts $1, %eax # monitor co-processor + btr $2, %eax # clear coprocessor emulation + bts $16, %eax # write protect + bts $31, %eax # paging + mov %eax, %cr0 + + mov %cr4, %eax + bts $9, %eax # fxsave and fxrstor instructions + bts $10, %eax # unmasked simd floating point exceptions + mov %eax, %cr4 + +remapIRQ: +.SET MasterControl, 0x20 +.SET MasterData, 0x21 +.SET SlaveControl, 0xA0 +.SET SlaveData, 0xA1 + mov $0x11, %al + out %al, $MasterControl # Starts setup of controllers + out %al, $SlaveControl + + mov $0x20, %al + out %al, $MasterData # Master PIC interrupt id + mov $0x28, %al + out %al, $SlaveData # Slave PIC interrupt id + + mov $0x04, %al + out %al, $MasterData # Tells master that it has a slave at IRQ2 (0000 0100) + mov $0x02, %al + out %al, $SlaveData # Tells the slave that it's a slave (0000 0010) + + mov $0x01, %al + out %al, $MasterData # 8086/88 (MCS-80/85) mode + out %al, $SlaveData + + mov $0x0, %al + out %al, $MasterData # Sets the masks to 0 + out %al, $SlaveData + +jumpToX64: + # Load x64 GDT + lgdt (gdtPointer - KERNEL_VMA) + # Jump into x64 + ljmp $0x8, $(start64 - KERNEL_VMA) + +notx64Capable: + mov $0x4A, %ah + mov $0xB8000, %edi + mov $(x64NotSupported_msg - KERNEL_VMA), %esi + +writeString: + lodsb + test %al, %al + jz hidecursor + stosw + jmp writeString + +hidecursor: + mov $0x0F, %al + mov $0x3D4, %dx + out %al, %dx + + mov $0xFF, %al + mov $0x3D5, %dx + out %al, %dx + + mov $0x0E, %al + mov $0x3D4, %dx + out %al, %dx + + mov $0xFF, %al + mov $0x3D5, %dx + out %al, %dx + +hlt: + cli + hlt + jmp hlt + +.section .data +.global multiboot_magic +multiboot_magic: + .int 0 +.global multiboot_ptr +multiboot_ptr: + .int 0 + +x64NotSupported_msg: + .ascii " " + .ascii " _____ _ _ " + .ascii " | __ \\ | \\ | | " + .ascii " | |__) |____ _____ _ __| \\| | _____ __ " + .ascii " | ___/ _ \\ \\ /\\ / / _ \\ '__| . ` |/ _ \\ \\/ / " + .ascii " | | | (_) \\ V V / __/ | | |\\ | __/> < " + .ascii " |_| \\___/ \\_/\\_/ \\___|_| |_| \\_|\\___/_/\\_\\ " + .ascii " " + .ascii " " + .ascii " *The current setup can not run 64-bit code* " + .ascii " " + .ascii " " + .ascii " Please run PowerNex in a VM which supports it " + .ascii " Examples of VM that are supported are: " + .ascii " " + .ascii " " + .ascii " * QEMU - qemu.org " + .ascii " * VirtualBox - virtualbox.org " + .ascii " " + .ascii " " + .ascii " If you believe that you should see this " + .ascii " message because of an error. " + .ascii " Please report it to: vild.io/powernex " + .ascii " or: powernex@vild.io " + .ascii " " + .byte 0 + +.section .padata +.align 0x1000 +.SET PRESENT, 0x1 +.SET WRITEABLE, 0x2 +.SET USER, 0x4 +.SET MAP4M, 0x80 +.SET MAP_MODE, PRESENT + WRITEABLE +.SET ATTR, (- KERNEL_VMA + MAP_MODE) +.SET ATTR_MAP, (MAP_MODE + MAP4M) +.SET STACK_ATTR, (- KERNEL_VMA + MAP_MODE) + +.macro mapPage from, to + .int \from + MAP_MODE, 0 + .if \to-\from + mapPage "(\from+0x1000)", \to + .endif +.endm + +# Kinda stole this from https://github.com/Bloodmanovski/Trinix/blob/master/KernelLand/Kernel/Architectures/x86_64/Boot/Boot.s + + .global PML4 +PML4: + .int PDP + ATTR, 0 # Identity map for low 4MB + .space (255) * 8 + .int PDP_MAP + ATTR, 0 + .space (254) * 8 + .int PDP_HIGH + ATTR, 0 # Map low 4MB to kernel base + +PDP: + .int PD + ATTR, 0 + .space 511 * 8 + +PDP_MAP: + .int PD_MAP0 + ATTR, 0 + .int PD_MAP1 + ATTR, 0 + .int PD_MAP2 + ATTR, 0 + .int PD_MAP3 + ATTR, 0 + .space 508 * 8 + +PDP_HIGH: + .space 510*8 + .int PD + ATTR, 0 + .quad 0 + +PD: + .int PT_1 + ATTR, 0 + .int PT_2 + ATTR, 0 + .int PT_3 + ATTR, 0 + .int PT_4 + ATTR, 0 + .int PT_5 + ATTR, 0 + .int PT_6 + ATTR, 0 + .int PT_7 + ATTR, 0 + .int PT_8 + ATTR, 0 + .int PT_9 + ATTR, 0 + .int PT_10 + ATTR, 0 + .int PT_11 + ATTR, 0 + .int PT_12 + ATTR, 0 + .int PT_13 + ATTR, 0 + .int PT_14 + ATTR, 0 + .int PT_15 + ATTR, 0 + .int PT_16 + ATTR, 0 + .int PT_17 + ATTR, 0 + .int PT_18 + ATTR, 0 + .int PT_19 + ATTR, 0 + .int PT_20 + ATTR, 0 + .int PT_21 + ATTR, 0 + .int PT_22 + ATTR, 0 + .int PT_23 + ATTR, 0 + .int PT_24 + ATTR, 0 + .int PT_25 + ATTR, 0 + .int PT_26 + ATTR, 0 + .int PT_27 + ATTR, 0 + .int PT_28 + ATTR, 0 + .int PT_29 + ATTR, 0 + .int PT_30 + ATTR, 0 + .int PT_31 + ATTR, 0 + .int PT_32 + ATTR, 0 + .space (512 - 32) * 8 + +.macro mapPDMap from, to + .int \from + ATTR_MAP, 0 + .if \to-\from + mapPDMap "(\from+0x200000)", \to + .endif +.endm +.macro map4MB offset + mapPDMap (0x200000 * (0 + \offset)), (0x200000 * (64 + \offset)) + mapPDMap (0x200000 * (65 + \offset)), (0x200000 * (128 + \offset)) + mapPDMap (0x200000 * (129 + \offset)), (0x200000 * (192 + \offset)) + mapPDMap (0x200000 * (193 + \offset)), (0x200000 * (256 + \offset)) + mapPDMap (0x200000 * (257 + \offset)), (0x200000 * (320 + \offset)) + mapPDMap (0x200000 * (321 + \offset)), (0x200000 * (384 + \offset)) + mapPDMap (0x200000 * (385 + \offset)), (0x200000 * (448 + \offset)) + mapPDMap (0x200000 * (449 + \offset)), (0x200000 * (511 + \offset)) +.endm + +PD_MAP0: + map4MB 512*0 +PD_MAP1: + map4MB 512*1 +PD_MAP2: + map4MB 512*2 +PD_MAP3: + map4MB 512*3 + +.macro map2MB offset + mapPage (0x1000 * (0 + \offset)), (0x1000 * (64 + \offset)) + mapPage (0x1000 * (65 + \offset)), (0x1000 * (128 + \offset)) + mapPage (0x1000 * (129 + \offset)), (0x1000 * (192 + \offset)) + mapPage (0x1000 * (193 + \offset)), (0x1000 * (256 + \offset)) + mapPage (0x1000 * (257 + \offset)), (0x1000 * (320 + \offset)) + mapPage (0x1000 * (321 + \offset)), (0x1000 * (384 + \offset)) + mapPage (0x1000 * (385 + \offset)), (0x1000 * (448 + \offset)) + mapPage (0x1000 * (449 + \offset)), (0x1000 * (511 + \offset)) +.endm + +PT_1: + .int 0, 0 + mapPage (0x1000 * 1 ), (0x1000 * 64 ) + mapPage (0x1000 * 65 ), (0x1000 * 128) + mapPage (0x1000 * 129), (0x1000 * 192) + mapPage (0x1000 * 193), (0x1000 * 256) + mapPage (0x1000 * 257), (0x1000 * 320) + mapPage (0x1000 * 321), (0x1000 * 384) + mapPage (0x1000 * 385), (0x1000 * 448) + mapPage (0x1000 * 449), (0x1000 * 511) + +PT_2: + map2MB 512*1 +PT_3: + map2MB 512*2 +PT_4: + map2MB 512*3 +PT_5: + map2MB 512*4 +PT_6: + map2MB 512*5 +PT_7: + map2MB 512*6 +PT_8: + map2MB 512*7 + +PT_9: + map2MB 512*8 +PT_10: + map2MB 512*9 +PT_11: + map2MB 512*10 +PT_12: + map2MB 512*11 +PT_13: + map2MB 512*12 +PT_14: + map2MB 512*13 +PT_15: + map2MB 512*14 +PT_16: + map2MB 512*15 + +PT_17: + map2MB 512*16 +PT_18: + map2MB 512*17 +PT_19: + map2MB 512*18 +PT_20: + map2MB 512*19 +PT_21: + map2MB 512*20 +PT_22: + map2MB 512*21 +PT_23: + map2MB 512*22 +PT_24: + map2MB 512*23 + +PT_25: + map2MB 512*24 +PT_26: + map2MB 512*25 +PT_27: + map2MB 512*26 +PT_28: + map2MB 512*27 +PT_29: + map2MB 512*28 +PT_30: + map2MB 512*29 +PT_31: + map2MB 512*30 +PT_32: + map2MB 512*31 + + + + +.section .padata +.global KERNEL_STACK +.global KERNEL_STACK_START +KERNEL_STACK: + .space 0x1000 * (KERNEL_STACK_SIZE - 1) +KERNEL_STACK_START: + + +# TODO: Define name the constants +.global gdt +.align 16 +gdt: + .quad 0 + + gdtCode64: + .int 0x0000FFFF + .int 0x000F0000 + 0xA09A00 + gdtData64: + .int 0x0000FFFF + .int 0x000F0000 + 0xA09200 + + gdtCode32: + .int 0x0000FFFF + .int 0x000F0000 + 0xC09A00 + gdtData32: + .int 0x0000FFFF + .int 0x000F0000 + 0xC09200 + +gdtPointer: + .word . - gdt - 1 + .int gdt - KERNEL_VMA, 0 diff --git a/kernel/src/bootx64.S b/kernel/src/bootx64.S new file mode 100644 index 0000000..96e5e28 --- /dev/null +++ b/kernel/src/bootx64.S @@ -0,0 +1,39 @@ +.text +.code64 + +.SET KERNEL_VMA, 0xFFFFFFFF80000000 +.SET KERNEL_STACK_SIZE, 8 +.extern multiboot_magic +.extern multiboot_ptr +.extern KERNEL_STACK_START +.global start64 +.type start64, %function +start64: + cli + mov $0x10, %ax + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + mov %ax, %ss + + mov $1f, %rax + jmp *%rax + +1: + xor %rax, %rax + mov %rax, %dr0 + + mov $KERNEL_STACK_START, %rsp + + mov (multiboot_magic - KERNEL_VMA), %edi + mov (multiboot_ptr - KERNEL_VMA), %esi + + call _Dkmain_entry + cli + +1: + hlt + jmp 1b + +.size start64, .-start64 diff --git a/kernel/src/cpu/gdt.d b/kernel/src/cpu/gdt.d index 4750755..13869f4 100644 --- a/kernel/src/cpu/gdt.d +++ b/kernel/src/cpu/gdt.d @@ -1,82 +1,82 @@ -module CPU.GDT; -import Data.BitField; -import CPU.TSS; +module cpu.gdt; +import data.bitfield; +import cpu.tss; align(1) struct GDTBase { align(1): - ushort Limit; - ulong Base; + ushort limit; + ulong base; } struct GDTCodeDescriptor { align(1): - ushort Limit = 0xFFFF; - ushort Base = 0x0000; - ubyte BaseMiddle = 0x00; + ushort limit = 0xFFFF; + ushort base = 0x0000; + ubyte baseMiddle = 0x00; private ubyte flags1 = 0b11111101; private ubyte flags2 = 0b00000000; - ubyte BaseHigh = 0x00; + ubyte baseHigh = 0x00; - mixin(Bitfield!(flags1, "zero3", 2, "c", 1, "ones0", 2, "dpl", 2, "p", 1)); - mixin(Bitfield!(flags2, "zero4", 5, "l", 1, "d", 1, "Granularity", 1)); + mixin(bitfield!(flags1, "zero3", 2, "c", 1, "ones0", 2, "dpl", 2, "p", 1)); + mixin(bitfield!(flags2, "zero4", 5, "l", 1, "d", 1, "granularity", 1)); } struct GDTDataDescriptor { align(1): - ushort Limit = 0xFFFF; - ushort Base = 0x0000; - ubyte BaseMiddle = 0x00; + ushort limit = 0xFFFF; + ushort base = 0x0000; + ubyte baseMiddle = 0x00; private ubyte flags1 = 0b11110011; private ubyte flags2 = 0b11001111; - ubyte BaseHigh = 0x00; + ubyte baseHigh = 0x00; - mixin(Bitfield!(flags1, "zero4", 5, "dpl", 2, "p", 1)); + mixin(bitfield!(flags1, "zero4", 5, "dpl", 2, "p", 1)); } struct GDTSystemDescriptor { align(1): - ushort LimitLow; - ushort BaseLow; - ubyte BaseMiddleLow; + ushort limitLow; + ushort baseLow; + ubyte baseMiddleLow; private ubyte flags1; private ubyte flags2; - ubyte BaseMiddleHigh; + ubyte baseMiddleHigh; - mixin(Bitfield!(flags1, "Type", 4, "Zero0", 1, "dpl", 2, "p", 1)); - mixin(Bitfield!(flags2, "LimitHigh", 4, "avl", 1, "Zero1", 2, "g", 1)); + mixin(bitfield!(flags1, "type", 4, "zero0", 1, "dpl", 2, "p", 1)); + mixin(bitfield!(flags2, "limitHigh", 4, "avl", 1, "zero1", 2, "g", 1)); } struct GDTSystemExtension { align(1): - uint BaseHigh; + uint baseHigh; private uint reserved; } union GDTDescriptor { align(1): - GDTDataDescriptor Data; - GDTCodeDescriptor Code; - GDTSystemDescriptor SystemLow; - GDTSystemExtension SystemHigh; + GDTDataDescriptor data; + GDTCodeDescriptor code; + GDTSystemDescriptor systemLow; + GDTSystemExtension systemHigh; - TSSDescriptor1 TSS1; - TSSDescriptor2 TSS2; + TSSDescriptor1 tss1; + TSSDescriptor2 tss2; - ulong Value; + ulong value; } static assert(GDTDescriptor.sizeof == ulong.sizeof); enum GDTSystemType : ubyte { - LocalDescriptorTable = 0b0010, - AvailableTSS = 0b1001, - BusyTSS = 0b1011, - CallGate = 0b1100, - InterruptGate = 0b1110, - TrapGate = 0b1111 + localDescriptorTable = 0b0010, + availableTSS = 0b1001, + busyTSS = 0b1011, + callGate = 0b1100, + interruptGate = 0b1110, + trapGate = 0b1111 } -private extern (C) void CPU_refresh_iretq(); +private extern (C) void cpuRefreshIREQ(); static struct GDT { public: @@ -85,89 +85,89 @@ public: __gshared TSS tss; __gshared ushort tssID; - static void Init() { - base.Limit = cast(ushort)(setupTable() * GDTDescriptor.sizeof - 1); - base.Base = cast(ulong)descriptors.ptr; + static void init() { + base.limit = cast(ushort)(_setupTable() * GDTDescriptor.sizeof - 1); + base.base = cast(ulong)descriptors.ptr; - Flush(); + flush(); } - static void Flush() { + static void flush() { void* baseAddr = cast(void*)(&base); ushort id = cast(ushort)(tssID * GDTDescriptor.sizeof); asm { mov RAX, baseAddr; lgdt [RAX]; - call CPU_refresh_iretq; + call cpuRefreshIREQ; ltr id; } } - static void SetNull(size_t index) { - descriptors[index].Value = 0; + static void setNull(size_t index) { + descriptors[index].value = 0; } - static void SetCode(size_t index, bool conforming, ubyte DPL, bool present) { - descriptors[index].Code = GDTCodeDescriptor.init; - with (descriptors[index].Code) { + static void setCode(size_t index, bool conforming, ubyte dpl_, bool present) { + descriptors[index].code = GDTCodeDescriptor.init; + with (descriptors[index].code) { c = conforming; - dpl = DPL; + dpl = dpl_; p = present; l = true; d = false; } } - static void SetData(uint index, bool present, ubyte DPL) { - descriptors[index].Data = GDTDataDescriptor.init; - with (descriptors[index].Data) { + static void setData(uint index, bool present, ubyte dpl_) { + descriptors[index].data = GDTDataDescriptor.init; + with (descriptors[index].data) { p = present; - dpl = DPL; + dpl = dpl_; } } - static void SetTSS(uint index, ref TSS tss) { - descriptors[index].TSS1 = TSSDescriptor1(tss); - descriptors[index + 1].TSS2 = TSSDescriptor2(tss); + static void setTSS(uint index, ref TSS tss) { + descriptors[index].tss1 = TSSDescriptor1(tss); + descriptors[index + 1].tss2 = TSSDescriptor2(tss); } - void SetSystem(uint index, uint limit, ulong base, GDTSystemType segType, ubyte DPL, bool present, bool avail, bool granularity) { - descriptors[index].SystemLow = GDTSystemDescriptor.init; - descriptors[index + 1].SystemHigh = GDTSystemExtension.init; + void setSystem(uint index, uint limit, ulong base, GDTSystemType segType, ubyte dpl_, bool present, bool avail, bool granularity) { + descriptors[index].systemLow = GDTSystemDescriptor.init; + descriptors[index + 1].systemHigh = GDTSystemExtension.init; - with (descriptors[index].SystemLow) { - BaseLow = (base & 0xFFFF); - BaseMiddleLow = (base >> 16) & 0xFF; - BaseMiddleHigh = (base >> 24) & 0xFF; + with (descriptors[index].systemLow) { + baseLow = (base & 0xFFFF); + baseMiddleLow = (base >> 16) & 0xFF; + baseMiddleHigh = (base >> 24) & 0xFF; - LimitLow = limit & 0xFFFF; - LimitHigh = (limit >> 16) & 0xF; + limitLow = limit & 0xFFFF; + limitHigh = (limit >> 16) & 0xF; - Type = segType; - dpl = DPL; + type = segType; + dpl = dpl_; p = present; avl = avail; g = granularity; } - descriptors[index + 1].SystemHigh.BaseHigh = (base >> 32) & 0xFFFFFFFF; + descriptors[index + 1].systemHigh.baseHigh = (base >> 32) & 0xFFFFFFFF; } private: - static uint setupTable() { - uint idx = 0; - SetNull(idx++); + static ushort _setupTable() { + ushort idx = 0; + setNull(idx++); // Kernel - SetCode(idx++, false, 0, true); - SetData(idx++, true, 0); + setCode(idx++, false, 0, true); + setData(idx++, true, 0); // User - SetCode(idx++, true, 3, true); - SetData(idx++, true, 3); - SetCode(idx++, true, 3, true); // This is need because (MSR_STAR.SYSRET_CS + 16) is the CS when returning to 64bit mode. + setCode(idx++, true, 3, true); + setData(idx++, true, 3); + setCode(idx++, true, 3, true); // This is need because (MSR_STAR.SYSRET_CS + 16) is the CS when returning to 64bit mode. - tssID = cast(ushort)idx; - SetTSS(idx, tss); // Uses 2 entries + tssID = idx; + setTSS(idx, tss); // Uses 2 entries idx += 2; return idx; } diff --git a/kernel/src/cpu/idt.d b/kernel/src/cpu/idt.d index 097f87c..4d38cca 100644 --- a/kernel/src/cpu/idt.d +++ b/kernel/src/cpu/idt.d @@ -1,79 +1,79 @@ -module CPU.IDT; +module cpu.idt; -import Data.Register; -import Data.BitField; -import IO.Port; +import data.register; +import data.bitfield; +import io.port; align(1) struct IDTBase { align(1): - ushort Limit; - ulong Offset; + ushort limit; + ulong offset; } static assert(IDTBase.sizeof == 10); struct IDTDescriptor { align(1): - ushort TargetLow; - ushort Segment; + ushort targetLow; + ushort segment; private ushort _flags; - ushort TargetMiddle; - uint TargetHigh; + ushort targetMiddle; + uint targetHigh; private uint _reserved; - mixin(Bitfield!(_flags, "ist", 3, "Zero0", 5, "Type", 4, "Zero1", 1, "dpl", 2, "p", 1)); + mixin(bitfield!(_flags, "ist", 3, "zero0", 5, "type", 4, "zero1", 1, "dpl", 2, "p", 1)); } static assert(IDTDescriptor.sizeof == 16); enum IDTFlags : ubyte { - Interupt = 0xE, - Present = 0x80, - PrivilegeLevel3 = 0x60 + interupt = 0xE, + present = 0x80, + privilegeLevel3 = 0x60 } enum InterruptType : ubyte { - DivisionByZero = 0, - Debugger = 0x1, - NMI = 0x2, - Breakpoint = 0x3, - Overflow = 0x4, - Bounds = 0x5, - InvalidOpcode = 0x6, - CoprocessorNotAvailable = 0x7, - DoubleFault = 0x8, - CoprocessorSegmentOverrun = 0x9, // (386 or earlier only) - InvalidTaskStateSegment = 0xA, - SegmentNotPresent = 0xB, - StackFault = 0xC, - GeneralProtectionFault = 0xD, - PageFault = 0xE, - Reserved = 0xF, - MathFault = 0x10, - AlignmentCheck = 0x11, - MachineCheck = 0x12, - SIMDFloatingPointException = 0x13 + divisionByZero = 0, + debugger = 0x1, + nmi = 0x2, + breakpoint = 0x3, + overflow = 0x4, + bounds = 0x5, + invalidOpcode = 0x6, + coprocessorNotAvailable = 0x7, + doubleFault = 0x8, + coprocessorSegmentOverrun = 0x9, // (386 or earlier only) + invalidTaskStateSegment = 0xA, + segmentNotPresent = 0xB, + stackFault = 0xC, + generalProtectionFault = 0xD, + pageFault = 0xE, + reserved = 0xF, + mathFault = 0x10, + alignmentCheck = 0x11, + machineCheck = 0x12, + simdFloatingPointException = 0x13 } enum SystemSegmentType : ubyte { - LocalDescriptorTable = 0b0010, - AvailableTSS = 0b1001, - BusyTSS = 0b1011, - CallGate = 0b1100, - InterruptGate = 0b1110, - TrapGate = 0b1111 + localDescriptorTable = 0b0010, + availableTSS = 0b1001, + busyTSS = 0b1011, + callGate = 0b1100, + interruptGate = 0b1110, + trapGate = 0b1111 } enum InterruptStackType : ushort { - RegisterStack, - StackFault, - DoubleFault, - NMI, - Debug, - MCE + registerStack, + stackFault, + doubleFault, + nmi, + debug_, + mce } -alias IRQ = (x) => 32 + x; +alias irq = (x) => 32 + x; static struct IDT { public: @@ -82,14 +82,14 @@ public: __gshared IDTDescriptor[256] desc; __gshared InterruptCallback[256] handlers; - static void Init() { - base.Limit = (IDTDescriptor.sizeof * desc.length) - 1; - base.Offset = cast(ulong)desc.ptr; + static void init() { + base.limit = (IDTDescriptor.sizeof * desc.length) - 1; + base.offset = cast(ulong)desc.ptr; - addAllJumps(); + _addAllJumps(); } - static void Flush() { + static void flush() { void* baseAddr = cast(void*)(&base); asm { mov RAX, baseAddr; @@ -97,40 +97,40 @@ public: } } - static void Register(uint id, InterruptCallback cb) { + static void register(uint id, InterruptCallback cb) { handlers[id] = cb; } private: - static void add(uint id, SystemSegmentType gateType, ulong func, ubyte dplFlags, ubyte istFlags) { + static void _add(uint id, SystemSegmentType gateType, ulong func, ubyte dplFlags, ubyte istFlags) { with (desc[id]) { - TargetLow = func & 0xFFFF; - Segment = 0x08; + targetLow = func & 0xFFFF; + segment = 0x08; ist = istFlags; p = true; dpl = dplFlags; - Type = cast(uint)gateType; - TargetMiddle = (func >> 16) & 0xFFFF; - TargetHigh = (func >> 32) & 0xFFFF_FFFF; + type = cast(uint)gateType; + targetMiddle = (func >> 16) & 0xFFFF; + targetHigh = (func >> 32) & 0xFFFF_FFFF; } } - static void addAllJumps() { - mixin(addJumps!(0, 255)); - add(3, SystemSegmentType.InterruptGate, cast(ulong)&isr3, 3, InterruptStackType.Debug); - add(8, SystemSegmentType.InterruptGate, cast(ulong)&isrIgnore, 0, InterruptStackType.RegisterStack); - add(0x80, SystemSegmentType.InterruptGate, cast(ulong)&isr128, 3, InterruptStackType.RegisterStack); + static void _addAllJumps() { + mixin(_addJumps!(0, 255)); + _add(3, SystemSegmentType.interruptGate, cast(ulong)&isr3, 3, InterruptStackType.debug_); + _add(8, SystemSegmentType.interruptGate, cast(ulong)&isrIgnore, 0, InterruptStackType.registerStack); + _add(0x80, SystemSegmentType.interruptGate, cast(ulong)&isr128, 3, InterruptStackType.registerStack); - Flush(); + flush(); } - static template generateJump(ulong id, bool hasError = false) { - const char[] generateJump = ` + static template _generateJump(ulong id, bool hasError = false) { + const char[] _generateJump = ` static void isr` ~ id.stringof[0 .. $ - 2] ~ `() { asm { naked; - ` ~ (hasError ? "" : "push 0UL;") - ~ ` + ` ~ (hasError ? "" + : "push 0UL;") ~ ` push ` ~ id.stringof ~ `; jmp isrCommon; @@ -139,31 +139,31 @@ private: `; } - static template generateJumps(ulong from, ulong to, bool hasError = false) { + static template _generateJumps(ulong from, ulong to, bool hasError = false) { static if (from <= to) - const char[] generateJumps = generateJump!(from, hasError) ~ generateJumps!(from + 1, to, hasError); + const char[] _generateJumps = _generateJump!(from, hasError) ~ _generateJumps!(from + 1, to, hasError); else - const char[] generateJumps = ""; + const char[] _generateJumps = ""; } - static template addJump(ulong id) { - const char[] addJump = ` - add(` ~ id.stringof[0 .. $ - 2] ~ `, SystemSegmentType.InterruptGate, cast(ulong)&isr` - ~ id.stringof[0 .. $ - 2] ~ `, 0, InterruptStackType.RegisterStack);`; + static template _addJump(ulong id) { + const char[] _addJump = ` + _add(` ~ id.stringof[0 .. $ - 2] ~ `, SystemSegmentType.interruptGate, cast(ulong)&isr` + ~ id.stringof[0 .. $ - 2] ~ `, 0, InterruptStackType.registerStack);`; } - static template addJumps(ulong from, ulong to) { + static template _addJumps(ulong from, ulong to) { static if (from <= to) - const char[] addJumps = addJump!from ~ addJumps!(from + 1, to); + const char[] _addJumps = _addJump!from ~ _addJumps!(from + 1, to); else - const char[] addJumps = ""; + const char[] _addJumps = ""; } - mixin(generateJumps!(0, 7)); - mixin(generateJump!(8, true)); - mixin(generateJump!(9)); - mixin(generateJumps!(10, 14, true)); - mixin(generateJumps!(15, 255)); + mixin(_generateJumps!(0, 7)); + mixin(_generateJump!(8, true)); + mixin(_generateJump!(9)); + mixin(_generateJumps!(10, 14, true)); + mixin(_generateJumps!(15, 255)); static void isrIgnore() { asm { @@ -222,47 +222,47 @@ private: } extern (C) static void isrHandler(Registers* regs) { - import Data.TextBuffer : scr = GetBootTTY; - import IO.Log; - - regs.IntNumber &= 0xFF; - if (32 <= regs.IntNumber && regs.IntNumber <= 48) { - if (regs.IntNumber >= 40) - Out!ubyte(0xA0, 0x20); - Out!ubyte(0x20, 0x20); + import data.textbuffer : scr = getBootTTY; + import io.log; + + regs.intNumber &= 0xFF; + if (32 <= regs.intNumber && regs.intNumber <= 48) { + if (regs.intNumber >= 40) + outp!ubyte(0xA0, 0x20); + outp!ubyte(0x20, 0x20); } - if (auto handler = handlers[regs.IntNumber]) + if (auto handler = handlers[regs.intNumber]) handler(regs); else with (regs) { - import Data.Color; - - scr.Foreground = Color(255, 0, 0); - scr.Writeln("===> UNCAUGHT INTERRUPT"); - scr.Writeln("IRQ = ", cast(InterruptType)IntNumber, " | RIP = ", cast(void*)RIP); - scr.Writeln("RAX = ", cast(void*)RAX, " | RBX = ", cast(void*)RBX); - scr.Writeln("RCX = ", cast(void*)RCX, " | RDX = ", cast(void*)RDX); - scr.Writeln("RDI = ", cast(void*)RDI, " | RSI = ", cast(void*)RSI); - scr.Writeln("RSP = ", cast(void*)RSP, " | RBP = ", cast(void*)RBP); - scr.Writeln(" R8 = ", cast(void*)R8, " | R9 = ", cast(void*)R9); - scr.Writeln("R10 = ", cast(void*)R10, " | R11 = ", cast(void*)R11); - scr.Writeln("R12 = ", cast(void*)R12, " | R13 = ", cast(void*)R13); - scr.Writeln("R14 = ", cast(void*)R14, " | R15 = ", cast(void*)R15); - scr.Writeln(" CS = ", cast(void*)CS, " | SS = ", cast(void*)SS); - scr.Writeln(" CR2 = ", cast(void*)CR2); - scr.Writeln("Flags: ", cast(void*)Flags); - scr.Writeln("Errorcode: ", cast(void*)ErrorCode); - - log.Fatal("===> UNCAUGHT INTERRUPT", "\n", "IRQ = ", cast(InterruptType)IntNumber, " | RIP = ", - cast(void*)RIP, "\n", "RAX = ", cast(void*)RAX, " | RBX = ", cast(void*)RBX, "\n", "RCX = ", - cast(void*)RCX, " | RDX = ", cast(void*)RDX, "\n", "RDI = ", cast(void*)RDI, " | RSI = ", - cast(void*)RSI, "\n", "RSP = ", cast(void*)RSP, " | RBP = ", cast(void*)RBP, "\n", " R8 = ", - cast(void*)R8, " | R9 = ", cast(void*)R9, "\n", "R10 = ", cast(void*)R10, " | R11 = ", - cast(void*)R11, "\n", "R12 = ", cast(void*)R12, " | R13 = ", cast(void*)R13, "\n", "R14 = ", - cast(void*)R14, " | R15 = ", cast(void*)R15, "\n", " CS = ", cast(void*)CS, " | SS = ", - cast(void*)SS, "\n", " CR2 = ", cast(void*)CR2, "\n", "Flags: ", cast(void*)Flags, "\n", - "Errorcode: ", cast(void*)ErrorCode); + import data.color; + + scr.foreground = Color(255, 0, 0); + scr.writeln("===> UNCAUGHT INTERRUPT"); + scr.writeln("IRQ = ", cast(InterruptType)intNumber, " | RIP = ", cast(void*)rip); + scr.writeln("RAX = ", cast(void*)rax, " | RBX = ", cast(void*)rbx); + scr.writeln("RCX = ", cast(void*)rcx, " | RDX = ", cast(void*)rdx); + scr.writeln("RDI = ", cast(void*)rdi, " | RSI = ", cast(void*)rsi); + scr.writeln("RSP = ", cast(void*)rsp, " | RBP = ", cast(void*)rbp); + scr.writeln(" R8 = ", cast(void*)r8, " | R9 = ", cast(void*)r9); + scr.writeln("R10 = ", cast(void*)r10, " | R11 = ", cast(void*)r11); + scr.writeln("R12 = ", cast(void*)r12, " | R13 = ", cast(void*)r13); + scr.writeln("R14 = ", cast(void*)r14, " | R15 = ", cast(void*)r15); + scr.writeln(" CS = ", cast(void*)cs, " | SS = ", cast(void*)ss); + scr.writeln(" CR2 = ", cast(void*)cr2); + scr.writeln("Flags: ", cast(void*)flags); + scr.writeln("Errorcode: ", cast(void*)errorCode); + + log.fatal("===> UNCAUGHT INTERRUPT", "\n", "IRQ = ", cast(InterruptType)intNumber, " | RIP = ", + cast(void*)rip, "\n", "RAX = ", cast(void*)rax, " | RBX = ", cast(void*)rbx, "\n", "RCX = ", + cast(void*)rcx, " | RDX = ", cast(void*)rdx, "\n", "RDI = ", cast(void*)rdi, " | RSI = ", + cast(void*)rsi, "\n", "RSP = ", cast(void*)rsp, " | RBP = ", cast(void*)rbp, "\n", " R8 = ", + cast(void*)r8, " | R9 = ", cast(void*)r9, "\n", "R10 = ", cast(void*)r10, " | R11 = ", + cast(void*)r11, "\n", "R12 = ", cast(void*)r12, " | R13 = ", cast(void*)r13, "\n", "R14 = ", + cast(void*)r14, " | R15 = ", cast(void*)r15, "\n", " CS = ", cast(void*)cs, " | SS = ", + cast(void*)ss, "\n", " CR2 = ", cast(void*)cr2, "\n", "Flags: ", cast(void*)flags, "\n", + "Errorcode: ", cast(void*)errorCode); } } } diff --git a/kernel/src/cpu/msr.d b/kernel/src/cpu/msr.d index 209b327..4d499fe 100644 --- a/kernel/src/cpu/msr.d +++ b/kernel/src/cpu/msr.d @@ -1,17 +1,17 @@ -module CPU.MSR; +module cpu.msr; enum MSRIdentifiers : uint { - EFER = 0xC0000080, - Star = 0xC0000081, - LStar = 0xC0000082, - CStar = 0xC0000083, - SFMask = 0xC0000084, - FSBase = 0xC0000100, - GSBase = 0xC0000101 + efer = 0xC0000080, + star = 0xC0000081, + lStar = 0xC0000082, + cStar = 0xC0000083, + sfMask = 0xC0000084, + fsBase = 0xC0000100, + gsBase = 0xC0000101 } struct MSR { - static void Write(MSRIdentifiers ident, ulong value) { + static void write(MSRIdentifiers ident, ulong value) { uint low = cast(uint)value; uint high = cast(uint)(value >> 32); asm { @@ -22,7 +22,7 @@ struct MSR { } } - static ulong Read(MSRIdentifiers ident) { + static ulong read(MSRIdentifiers ident) { uint low, high; asm { mov ECX, ident; @@ -33,21 +33,21 @@ struct MSR { return cast(ulong)high << 32UL | low; } - mixin(generateGetterSetter()); + mixin(_generateGetterSetter()); private: - static string generateGetterSetter() { + static string _generateGetterSetter() { if (!__ctfe) return ""; - template generateGetterSetterEntry(alias item) { - enum generateGetterSetterEntry = `@property static ulong ` ~ item ~ `() { return Read(MSRIdentifiers.` ~ item - ~ `); } -@property static ulong ` ~ item ~ `(ulong val) { Write(MSRIdentifiers.` ~ item ~ `, val); return val; }`; + template _generateGetterSetterEntry(alias item) { + enum _generateGetterSetterEntry = `@property static ulong ` ~ item ~ `() { return read(MSRIdentifiers.` + ~ item ~ `); } +@property static ulong ` ~ item ~ `(ulong val) { write(MSRIdentifiers.` ~ item ~ `, val); return val; }`; } string output; foreach (item; __traits(allMembers, MSRIdentifiers)) - output ~= generateGetterSetterEntry!item; + output ~= _generateGetterSetterEntry!item; return output; } diff --git a/kernel/src/cpu/pit.d b/kernel/src/cpu/pit.d index a87b99f..9a43d89 100644 --- a/kernel/src/cpu/pit.d +++ b/kernel/src/cpu/pit.d @@ -1,53 +1,53 @@ -module CPU.PIT; +module cpu.pit; -import CPU.IDT; -import IO.Port; -import IO.Log; -import Data.Register; -import Task.Process; -import Task.Scheduler; +import cpu.idt; +import io.port; +import io.log; +import data.register; +import task.process; +import task.scheduler; struct PIT { public: - static void Init(uint hz = 1000) { - IDT.Register(IRQ(0), &onTick); - this.hz = hz; + static void init(uint hz = 1000) { + IDT.register(irq(0), &_onTick); + _hz = hz; uint divisor = 1193180 / hz; - Out!ubyte(0x43, 0x36); + outp!ubyte(0x43, 0x36); ubyte l = cast(ubyte)(divisor & 0xFF); ubyte h = cast(ubyte)((divisor >> 8) & 0xFF); - Out!ubyte(0x40, l); - Out!ubyte(0x40, h); + outp!ubyte(0x40, l); + outp!ubyte(0x40, h); } - static @property ulong Seconds() { - if (hz) - return counter / hz; + static @property ulong seconds() { + if (_hz) + return _counter / _hz; return 0; } - static void Clear() { - counter = 0; + static void clear() { + _counter = 0; } private: - __gshared bool enabled; - __gshared uint hz; - __gshared ulong counter; - static void onTick(Registers* regs) { - import Memory.FrameAllocator; - import Task.Scheduler : GetScheduler; - import Data.TextBuffer : scr = GetBootTTY; - - counter++; - - GetScheduler.WakeUp(WaitReason.Timer, &wakeUpTimedSleep); - GetScheduler.SwitchProcess(true); + __gshared bool _enabled; + __gshared uint _hz; + __gshared ulong _counter; + static void _onTick(Registers* regs) { + import memory.frameallocator; + import task.scheduler : getScheduler; + import data.textbuffer : scr = getBootTTY; + + _counter++; + + getScheduler.wakeUp(WaitReason.timer, &_wakeUpTimedSleep); + getScheduler.switchProcess(true); } - static bool wakeUpTimedSleep(Process* p, void* data) { + static bool _wakeUpTimedSleep(Process* p, void* data) { p.waitData--; if (p.waitData == 0) return true; diff --git a/kernel/src/cpu/tss.d b/kernel/src/cpu/tss.d index fc9bba9..5465705 100644 --- a/kernel/src/cpu/tss.d +++ b/kernel/src/cpu/tss.d @@ -1,7 +1,7 @@ -module CPU.TSS; +module cpu.tss; -import Data.BitField; -import Data.Address; +import data.bitfield; +import data.address; struct TSS { align(1): @@ -15,13 +15,9 @@ align(1): align(4096) ubyte[1 << 16] ioBitmap; ubyte stopper = 0xFF; - @property ref VirtAddress RSP0() return { + @property ref VirtAddress rsp0() return { return rsp[0]; } - - @property VirtAddress IOBitmap() { - return VirtAddress(&ioBitmap); - } } struct TSSDescriptor1 { @@ -48,10 +44,10 @@ align(1): ubyte base16; private ubyte data1; - mixin(Bitfield!(data1, "type", 4, "res0", 1, "dpl", 2, "present", 1)); + mixin(bitfield!(data1, "type", 4, "res0", 1, "dpl", 2, "present", 1)); private ubyte data2; - mixin(Bitfield!(data2, "limit16", 4, "available", 1, "res1", 2, "granularity", 1)); + mixin(bitfield!(data2, "limit16", 4, "available", 1, "res1", 2, "granularity", 1)); ubyte base24; } diff --git a/kernel/src/data/address.d b/kernel/src/data/address.d index 3631a0a..32385dd 100644 --- a/kernel/src/data/address.d +++ b/kernel/src/data/address.d @@ -1,6 +1,6 @@ -module Data.Address; +module data.address; -private mixin template AddressBase(Type = ulong) { +private mixin template AddressBase(Type = size_t) { alias Func = void function(); Type addr; @@ -31,7 +31,7 @@ private mixin template AddressBase(Type = ulong) { } typeof(this) opBinary(string op)(typeof(this) other) const { - return opBinary!op(other.Ptr); + return opBinary!op(other.ptr); } typeof(this) opOpAssign(string op)(void* other) { @@ -43,61 +43,61 @@ private mixin template AddressBase(Type = ulong) { } typeof(this) opOpAssign(string op)(typeof(this) other) { - return opOpAssign!op(other.Ptr); + return opOpAssign!op(other.ptr); } int opCmp(typeof(this) other) const { - if (Int < other.Int) + if (num < other.num) return -1; - else if (Int > other.Int) + else if (num > other.num) return 1; else return 0; } int opCmp(Type other) const { - if (Int < other) + if (num < other) return -1; - else if (Int > other) + else if (num > other) return 1; else return 0; } - @property T* Ptr(T = void)() { + @property T* ptr(T = void)() { return cast(T*)addr; } - @property T* Ptr(T = void)(T addr) { + @property T* ptr(T = void)(T addr) { this.addr = cast(Type)addr; return cast(T*)addr; } - @property Type Int() const { + @property Type num() const { return addr; } - @property Type Int(Type addr) { + @property Type num(Type addr) { this.addr = addr; return addr; } - @property Func Function() const { + @property Func func() const { return cast(Func)addr; } - @property Func Function(Func func) { + @property Func func(Func func) { this.addr = cast(Type)func; return cast(Func)addr; } - T Array(T : X[], X)(size_t length) const { + T array(T : X[], X)(size_t length) const { return (cast(X*)addr)[0 .. length]; } - @property T Array(T)(T array) { - this.addr = cast(Type)array.ptr; - return array; + @property T array(T)(T array_) { + this.addr = cast(Type)array_.ptr; + return array_; } } @@ -108,16 +108,16 @@ struct VirtAddress { struct PhysAddress { mixin AddressBase; - @property VirtAddress Virtual() const { - return VirtAddress(Int + 0xFFFF_8000_0000_0000); + @property VirtAddress virtual() const { + return VirtAddress(addr + 0xFFFF_8000_0000_0000); } } struct PhysAddress32 { mixin AddressBase!uint; - @property VirtAddress Virtual() const { - return VirtAddress(Int + 0xFFFF_8000_0000_0000); + @property VirtAddress virtual() const { + return VirtAddress(addr + 0xFFFF_8000_0000_0000); } } diff --git a/kernel/src/data/bitfield.d b/kernel/src/data/bitfield.d index 30a922d..dbc7799 100644 --- a/kernel/src/data/bitfield.d +++ b/kernel/src/data/bitfield.d @@ -1,63 +1,63 @@ -module Data.BitField; +module data.bitfield; -template Bitfield(alias data, Args...) { - const char[] Bitfield = BitfieldShim!((typeof(data)).stringof, data, Args).Ret; +template bitfield(alias data, args...) { + const char[] bitfield = bitfieldShim!((typeof(data)).stringof, data, args).ret; } -template BitfieldShim(const char[] typeStr, alias data, Args...) { - const char[] Name = data.stringof; - const char[] Ret = BitfieldImpl!(typeStr, Name, 0, Args).Ret; +template bitfieldShim(const char[] typeStr, alias data, args...) { + const char[] name = data.stringof; + const char[] ret = bitfieldImpl!(typeStr, name, 0, args).ret; } -template BitfieldImpl(const char[] typeStr, const char[] nameStr, int offset, Args...) { - static if (!Args.length) - const char[] Ret = ""; +template bitfieldImpl(const char[] typeStr, const char[] nameStr, int offset, args...) { + static if (!args.length) + const char[] ret = ""; else { - const Name = Args[0]; - const Size = Args[1]; - const Mask = Bitmask!Size; - const Type = TargetType!Size; + const name = args[0]; + const size = args[1]; + const mask = bitmask!size; + const type = targetType!size; - const char[] Getter = "@property " ~ Type ~ " " ~ Name ~ "() { return cast(" ~ Type ~ ")((" ~ nameStr ~ " >> " ~ Itoh!( - offset) ~ ") & " ~ Itoh!(Mask) ~ "); } \n"; + const char[] getter = "@property " ~ type ~ " " ~ name ~ "() { return cast(" ~ type ~ ")((" ~ nameStr ~ " >> " ~ itoh!( + offset) ~ ") & " ~ itoh!(mask) ~ "); } \n"; - const char[] Setter = "@property void " ~ Name ~ "(" ~ Type ~ " val) { " ~ nameStr ~ " = (" ~ nameStr ~ " & " ~ Itoh!( - ~(Mask << offset)) ~ ") | ((val & " ~ Itoh!(Mask) ~ ") << " ~ Itoh!(offset) ~ "); } \n"; + const char[] setter = "@property void " ~ name ~ "(" ~ type ~ " val) { " ~ nameStr ~ " = (" ~ nameStr ~ " & " ~ itoh!( + ~(mask << offset)) ~ ") | ((val & " ~ itoh!(mask) ~ ") << " ~ itoh!(offset) ~ "); } \n"; - const char[] Ret = Getter ~ Setter ~ BitfieldImpl!(typeStr, nameStr, offset + Size, Args[2 .. $]).Ret; + const char[] ret = getter ~ setter ~ bitfieldImpl!(typeStr, nameStr, offset + size, args[2 .. $]).ret; } } -template Bitmask(long size) { - const long Bitmask = (1UL << size) - 1; +template bitmask(long size) { + const long bitmask = (1UL << size) - 1; } -template TargetType(long size) { +template targetType(long size) { static if (size == 1) - const TargetType = "bool"; + const targetType = "bool"; else static if (size <= 8) - const TargetType = "ubyte"; + const targetType = "ubyte"; else static if (size <= 16) - const TargetType = "ushort"; + const targetType = "ushort"; else static if (size <= 32) - const TargetType = "uint"; + const targetType = "uint"; else static if (size <= 64) - const TargetType = "ulong"; + const targetType = "ulong"; else static assert(0); } -template Itoh(long i) { - const char[] Itoh = "0x" ~ IntToStr!(i, 16) ~ "UL"; +template itoh(long i) { + const char[] itoh = "0x" ~ intToStr!(i, 16) ~ "UL"; } -template Digits(long i) { - const char[] Digits = "0123456789abcdefghijklmnopqrstuvwxyz"[0 .. i]; +template digits(long i) { + const char[] digits = "0123456789abcdefghijklmnopqrstuvwxyz"[0 .. i]; } -template IntToStr(ulong i, int base) { +template intToStr(ulong i, int base) { static if (i >= base) - const char[] IntToStr = IntToStr!(i / base, base) ~ Digits!base[i % base]; + const char[] intToStr = intToStr!(i / base, base) ~ digits!base[i % base]; else - const char[] IntToStr = "" ~ Digits!base[i % base]; + const char[] intToStr = "" ~ digits!base[i % base]; } diff --git a/kernel/src/data/bmpimage.d b/kernel/src/data/bmpimage.d index 1ae1356..1bc9ac6 100644 --- a/kernel/src/data/bmpimage.d +++ b/kernel/src/data/bmpimage.d @@ -1,90 +1,89 @@ -module Data.BMPImage; +module data.bmpimage; -import IO.FS.FileNode; -import Data.Color; +import io.fs.filenode; +import data.color; +import io.log; private align(1) struct FileHeader { align(1): - char[2] filetype; /* magic - always 'B' 'M' */ - uint filesize; + char[2] fileType; /* magic - always 'B' 'M' */ + uint fileSize; short reserved1; short reserved2; - uint dataoffset; /* offset in bytes to actual bitmap data */ + uint dataOffset; /* offset in bytes to actual bitmap data */ } private align(1) struct BitmapHeader { align(1): - FileHeader fileheader; - uint headersize; + FileHeader fileHeader; + uint headerSize; int width; int height; short planes; - short bitsperpixel; + short bitsPerPixel; uint compression; - uint bitmapsize; - int horizontalres; - int verticalres; - uint numcolors; - uint importantcolors; - uint redmask; - uint greenmask; - uint bluemask; - uint alphamask; + uint bitmapSize; + int horizontalRes; + int verticalRes; + uint numColors; + uint importantColors; + uint redMask; + uint greenMask; + uint blueMask; + uint alphaMask; } -import IO.Log; - class BMPImage { public: this(FileNode file) { - file.Read((cast(ubyte*)&bitmap)[0 .. BitmapHeader.sizeof], 0); - data = new Color[bitmap.width * bitmap.height]; - size_t offset = bitmap.fileheader.dataoffset; - int pad = bitmap.width % 4; + file.read((cast(ubyte*)&_bitmap)[0 .. BitmapHeader.sizeof], 0); + _data = new Color[_bitmap.width * _bitmap.height]; + size_t offset = _bitmap.fileHeader.dataOffset; + int pad = _bitmap.width % 4; - switch (bitmap.bitsperpixel) { + switch (_bitmap.bitsPerPixel) { case 32: - readData!32(file, offset, pad); + _readData!32(file, offset, pad); break; case 24: - readData!24(file, offset, pad); + _readData!24(file, offset, pad); break; default: - log.Error("Can't handle bpp = ", bitmap.bitsperpixel); + log.error("Can't handle bpp = ", _bitmap.bitsPerPixel); return; } } this(BMPImage other) { - bitmap = other.bitmap; - data = other.Data.dup; + _bitmap = other._bitmap; + _data = other._data.dup; } ~this() { - data.destroy; + _data.destroy; } - @property BitmapHeader Header() { - return bitmap; + @property BitmapHeader header() { + return _bitmap; } - @property Color[] Data() { - return data; + @property Color[] data() { + return _data; } - @property int Width() { - return bitmap.width; + @property int width() { + return _bitmap.width; } - @property int Height() { - return bitmap.height; + @property int height() { + return _bitmap.height; } private: - BitmapHeader bitmap; - Color[] data; + BitmapHeader _bitmap; + Color[] _data; - void readData(int bpp)(FileNode file, size_t offset, int pad) if (bpp == 24 || bpp == 32) { + void _readData(int bpp)(FileNode file, size_t offset, int pad) if (bpp == 24 || bpp == 32) { enum bytesPerPixel = bpp / 8; ubyte toIdx(int bitmask) { @@ -92,19 +91,19 @@ private: : (bitmask & 0x00_00_00_01) ? 0 : ubyte.max; } - import IO.FS.Initrd.FileNode : InitrdFileNode; + import io.fs.initrd.filenode : InitrdFileNode; - immutable ubyte rid = toIdx(bitmap.redmask); - immutable ubyte gid = toIdx(bitmap.greenmask); - immutable ubyte bid = toIdx(bitmap.bluemask); - immutable ubyte aid = toIdx(bitmap.alphamask); + immutable ubyte rid = toIdx(_bitmap.redMask); + immutable ubyte gid = toIdx(_bitmap.greenMask); + immutable ubyte bid = toIdx(_bitmap.blueMask); + immutable ubyte aid = toIdx(_bitmap.alphaMask); - log.Debug("rid: ", cast(int)rid, " gid: ", cast(int)gid, " bid: ", cast(int)bid, " aid: ", cast(int)aid); + log.debug_("rid: ", cast(int)rid, " gid: ", cast(int)gid, " bid: ", cast(int)bid, " aid: ", cast(int)aid); ubyte[bytesPerPixel] buf = void; - for (int y = bitmap.height - 1; y >= 0; y--) { - for (int x = 0; x < bitmap.width; x++) { - file.Read(buf, offset); + for (int y = _bitmap.height - 1; y >= 0; y--) { + for (int x = 0; x < _bitmap.width; x++) { + file.read(buf, offset); offset += bytesPerPixel; immutable ubyte r = rid != ubyte.max ? buf[rid] : 0; @@ -116,7 +115,7 @@ private: else immutable ubyte a = 0; - data[y * bitmap.width + x] = Color(r, g, b, a); + _data[y * _bitmap.width + x] = Color(r, g, b, a); } if (pad) @@ -124,28 +123,3 @@ private: } } } - -/* -if (auto f = cast(InitrdFileNode)file) { - ubyte[] d = f.RawAccess; - for (int y = bitmap.height - 1; y >= 0; y--) { - for (int x = 0; x < bitmap.width; x++, offset += bytesPerPixel) { - data[y * bitmap.width + x] = Color(d[offset + 0], d[offset + 1], d[offset + 2], d[offset + 3]); - } - - if (pad) - offset = (offset + 4) & ~0b11; - } - return; - } - - for (int y = bitmap.height - 1; y >= 0; y--) { - for (int x = 0; x < bitmap.width; x++) { - ubyte[4] abgr; - file.Read(abgr, offset += 4); - data[y * bitmap.width + x] = Color(abgr[0], abgr[1], abgr[2], abgr[3]); //Color(r, g, b, a); - } - if (pad) - offset = (offset + 4) & ~0b11; - } -*/ diff --git a/kernel/src/data/color.d b/kernel/src/data/color.d index eb22ea0..d84a018 100644 --- a/kernel/src/data/color.d +++ b/kernel/src/data/color.d @@ -1,4 +1,4 @@ -module Data.Color; +module data.color; struct Color { align(1): diff --git a/kernel/src/data/elf.d b/kernel/src/data/elf.d index 489efed..74c1881 100644 --- a/kernel/src/data/elf.d +++ b/kernel/src/data/elf.d @@ -1,20 +1,20 @@ -module Data.ELF; +module data.elf; -import Data.BitField; -import Data.Address; -import Data.String; -import IO.FS.FileNode; -import IO.Log; -import Data.TextBuffer : scr = GetBootTTY; -import Task.Process; -import Memory.Heap; +import data.bitfield; +import data.address; +import data.string_; +import io.fs.filenode; +import io.log; +import data.textbuffer : scr = getBootTTY; +import task.process; +import memory.heap; struct ELF64Header { struct Identification { char[4] magic; enum Class : ubyte { - None, + none, _32, _64 } @@ -22,29 +22,29 @@ struct ELF64Header { Class class_; enum Data : ubyte { - None, - LeastSignificantBit, - MostSignificantBit + none, + leastSignificantBit, + mostSignificantBit } Data data; enum ELFVersion : ubyte { - None, - Current + none, + current } ELFVersion elfVersion; enum OSABI : ubyte { - None, - PowerNex = 16 + none, + powerNex = 16 } OSABI osABI; enum ABIVersion : ubyte { - Current = 0 + current = 0 } ABIVersion abiVersion; @@ -56,19 +56,19 @@ struct ELF64Header { Identification identification; enum ObjectType : ushort { - None, - Relocatable, - Executable, - Shared, - Core + none, + relocatable, + executable, + shared_, + core } ObjectType type; enum Machine : ushort { - None, - I386 = 3, - AMD64 = 0x3E + none, + i386 = 3, + amd64 = 0x3E } Machine machine; @@ -85,35 +85,35 @@ struct ELF64Header { ushort sectionHeaderCount; ushort sectionHeaderStringTableIndex; - @property bool Valid() { - immutable char[4] ELF64Magic = [0x7F, 'E', 'L', 'F']; - return identification.magic == ELF64Magic && programHeaderEntrySize == ELF64ProgramHeader.sizeof + @property bool valid() { + immutable char[4] elf64Magic = [0x7F, 'E', 'L', 'F']; + return identification.magic == elf64Magic && programHeaderEntrySize == ELF64ProgramHeader.sizeof && ELF64SectionHeader.sizeof == sectionHeaderEntrySize; } } struct ELF64ProgramHeader { enum Type : uint { - Null, - Load, - Dynamic, - Interpreter, - Note, - SHLIB, // Not use, Not allowed - ProgramHeader, - ThreadLocalStorage, - - GNUEHFrameHeader = 0x6474E550, - GNUStack = 0x6474E551, + null_, + load, + dynamic, + interpreter, + note, + shlib, // Not use, Not allowed + programHeader, + threadLocalStorage, + + gnuEHFrameHeader = 0x6474E550, + gnuStack = 0x6474E551, } Type type; enum Flags : uint { - None, - X = 1 << 0, - W = 1 << 1, - R = 1 << 2 + none, + x = 1 << 0, + w = 1 << 1, + r = 1 << 2 } Flags flags; @@ -129,46 +129,46 @@ struct ELF64SectionHeader { uint nameIdx; enum Type : uint { - Null, - ProgramBits, - SymbolTable, - StringTable, - RelocationEntries, - SymbolHashTable, - DynamicLinking, - Note, - NoBits, - RelocationOffsets, - SHLIB, // Not used, not allowed - DynamicLinkingSymbols, - ConstructorArray = 14, - DestructorArray, - PreConstructorArray, - GNUHashTable = 0x6FFFFFF6, - GNUVersionNeeds = 0x6FFFFFFE, - GNUVersionSymbolTable = 0x6FFFFFFF, + null_, + programBits, + symbolTable, + stringTable, + relocationEntries, + symbolHashTable, + dynamicLinking, + note, + noBits, + relocationOffsets, + shlib, // Not used, not allowed + dynamicLinkingSymbols, + constructorArray = 14, + destructorArray, + preConstructorArray, + gnuHashTable = 0x6FFFFFF6, + gnuVersionNeeds = 0x6FFFFFFE, + gnuVersionSymbolTable = 0x6FFFFFFF, } Type type; enum Flags : ulong { - Null, - Write = 1 << 0, - Allocate = 1 << 1, - ExecutableInstructions = 1 << 2, - Merge = 1 << 4, - Strings = 1 << 5, - InfoLink = 1 << 6, - LinkOrder = 1 << 7, - Group = 1 << 9, - ThreadLocalData = 1 << 10, - Compressed = 1 << 11, - - Allocate_Write = Allocate | Write, - ExecutableInstructions_Allocate = ExecutableInstructions | Allocate, - Strings_Merge = Strings | Merge, - InfoLink_Allocate = InfoLink | Allocate, - ThreadLocalData_Allocate_Write = ThreadLocalData | Allocate | Write + null_, + write = 1 << 0, + allocate = 1 << 1, + executableInstructions = 1 << 2, + merge = 1 << 4, + strings = 1 << 5, + infoLink = 1 << 6, + linkOrder = 1 << 7, + group = 1 << 9, + threadLocalData = 1 << 10, + compressed = 1 << 11, + + allocateWrite = allocate | write, + executableInstructionsAllocate = executableInstructions | allocate, + stringsMerge = strings | merge, + infoLinkAllocate = infoLink | allocate, + threadLocalDataAllocateWrite = threadLocalData | allocate | write } Flags flags; @@ -185,36 +185,36 @@ struct ELF64Symbol { uint name; struct Info { enum InfoType : ubyte { - NoType, - Object, - Function, - Section, - File, - Common, - TLS + noType, + object, + function_, + section, + file, + common, + tls } enum InfoBinding : ubyte { - Local, - Global, - Weak + local, + global, + weak } private ubyte data; - @property InfoType Type() { + @property InfoType type() { return cast(InfoType)(data & 0xF); } - @property InfoType Type(InfoType type) { + @property InfoType type(InfoType type) { data = data & 0xF0 | type & 0xF; return type; } - @property InfoBinding Binding() { + @property InfoBinding binding() { return cast(InfoBinding)((data & 0xF0 >> 4) & 0x2); } - @property InfoBinding Binding(InfoBinding binding) { + @property InfoBinding binding(InfoBinding binding) { data = (binding << 4) & 0xF0 | data & 0xF; return binding; } @@ -222,10 +222,10 @@ struct ELF64Symbol { Info info; enum Other : ubyte { - Default, - Internal, - Hidden, - Protected + default_, + internal, + hidden, + protected_ } Other other; @@ -257,32 +257,32 @@ struct ELF64RelocationAddend { struct ELF64Dynamic { enum Tag : long { - Null, - Needed, - PLTRelocationEntries, - PLTGOT, - HashTable, - StringTable, - SymbolTable, - RelocationAddendTable, - RelocationAddendTableSize, - RelocationAddendTableEntrySize, - StringTableSize, - SymbolTableEntrySize, - Init, - Fini, - SOName, - RPath, - Symbolic, - RelocationTable, - RelocationTableSize, - RelocationTableEntrySize, - PLTRel, - Debug, - TextRel, - JumpRel, - BindNow, - RunPath + null_, + needed, + pltRelocationEntries, + pltgot, + hashTable, + stringTable, + symbolTable, + relocationAddendTable, + relocationAddendTableSize, + relocationAddendTableEntrySize, + stringTableSize, + symbolTableEntrySize, + init, + fini, + sOName, + rPath, + symbolic, + relocationTable, + relocationTableSize, + relocationTableEntrySize, + pLTRel, + debug_, + textRel, + jumpRel, + bindNow, + runPath } Tag tag; @@ -292,29 +292,29 @@ struct ELF64Dynamic { class ELF { public: this(FileNode file) { - this.file = file; + this._file = file; - if (file.Size <= ELF64Header.sizeof) + if (_file.size <= ELF64Header.sizeof) return; - file.Read((cast(ubyte*)&header)[0 .. ELF64Header.sizeof], 0); - valid = header.Valid; + _file.read((cast(ubyte*)&_header)[0 .. ELF64Header.sizeof], 0); + _valid = _header.valid; - foreach (idx; 0 .. header.sectionHeaderCount) { - ELF64SectionHeader sectionHdr = GetSectionHeader(idx); - if (sectionHdr.type == ELF64SectionHeader.Type.SymbolTable) - symtabIdx = idx; - else if (sectionHdr.type == ELF64SectionHeader.Type.StringTable) - strtabIdx = idx; + foreach (idx; 0 .. _header.sectionHeaderCount) { + ELF64SectionHeader sectionHdr = getSectionHeader(idx); + if (sectionHdr.type == ELF64SectionHeader.type.symbolTable) + _symtabIdx = idx; + else if (sectionHdr.type == ELF64SectionHeader.type.stringTable) + _strtabIdx = idx; } } - void MapAndRun(string[] args) { - import Memory.Paging; - import Task.Scheduler; + void mapAndRun(string[] args) { + import memory.paging; + import task.scheduler; - Scheduler scheduler = GetScheduler; - Process* process = scheduler.CurrentProcess; + Scheduler scheduler = getScheduler; + Process* process = scheduler.currentProcess; Paging paging = process.threadState.paging; string[] tmpArgs; @@ -322,52 +322,52 @@ public: foreach (idx, arg; args) tmpArgs[idx] = arg.dup; - if (process.heap && !(--process.heap.RefCounter)) + if (process.heap && !(--process.heap.refCounter)) process.heap.destroy; - paging.RemoveUserspace(true); + paging.removeUserspace(true); VirtAddress startHeap; foreach (idx; 0 .. header.programHeaderCount) { - ELF64ProgramHeader program = GetProgramHeader(idx); - if (program.type == ELF64ProgramHeader.Type.Load) { - - MapMode mode = MapMode.User; - if (!(program.flags & ELF64ProgramHeader.Flags.X)) - mode |= MapMode.NoExecute; - if (program.flags & ELF64ProgramHeader.Flags.W) - mode |= MapMode.Writable; + ELF64ProgramHeader program = getProgramHeader(idx); + if (program.type == ELF64ProgramHeader.type.load) { + + MapMode mode = MapMode.user; + if (!(program.flags & ELF64ProgramHeader.Flags.x)) + mode |= MapMode.noExecute; + if (program.flags & ELF64ProgramHeader.Flags.w) + mode |= MapMode.writable; // Page will always be readable VirtAddress start = program.virtAddress & ~0xFFF; VirtAddress end = program.virtAddress + program.memorySize; VirtAddress cur = start; while (cur < end) { - paging.MapFreeMemory(cur, MapMode.DefaultKernel); + paging.mapFreeMemory(cur, MapMode.defaultKernel); cur += 0x1000; } - log.Debug("Start: ", start, " End: ", end, " cur: ", cur, " Mode: R", (mode & MapMode.Writable) ? "W" - : "", (mode & MapMode.NoExecute) ? "" : "X", (mode & MapMode.User) ? "-User" : ""); + log.debug_("Start: ", start, " End: ", end, " cur: ", cur, " Mode: R", (mode & MapMode.writable) ? "W" + : "", (mode & MapMode.noExecute) ? "" : "X", (mode & MapMode.user) ? "-User" : ""); - memset(start.Ptr, 0, (program.virtAddress - start).Int); + memset(start.ptr, 0, (program.virtAddress - start).num); cur = (program.virtAddress + program.fileSize); - memset(cur.Ptr, 0, (end - cur).Int); - file.Read(program.virtAddress.Ptr!ubyte[0 .. program.fileSize], program.offset.Int); + memset(cur.ptr, 0, (end - cur).num); + _file.read(program.virtAddress.ptr!ubyte[0 .. program.fileSize], program.offset.num); cur = start; while (cur < end) { - auto page = paging.GetPage(cur); - page.Mode = mode; - paging.FlushPage(cur); + auto page = paging.getPage(cur); + page.mode = mode; + paging.flushPage(cur); cur += 0x1000; } if (end > startHeap) startHeap = end; - } else if (program.type == ELF64ProgramHeader.Type.ThreadLocalStorage) - process.image.defaultTLS = program.virtAddress.Ptr!ubyte[0 .. program.memorySize]; + } else if (program.type == ELF64ProgramHeader.Type.threadLocalStorage) + process.image.defaultTLS = program.virtAddress.ptr!ubyte[0 .. program.memorySize]; } // Setup stack, setup heap @@ -376,14 +376,14 @@ public: cli; } - startHeap = (startHeap.Int + 0xFFF) & ~0xFFF; + startHeap = (startHeap.num + 0xFFF) & ~0xFFF; - process.heap = new Heap(process.threadState.paging, MapMode.DefaultUser, startHeap, VirtAddress(0xFFFF_FFFF_0000_0000)); + process.heap = new Heap(process.threadState.paging, MapMode.defaultUser, startHeap, VirtAddress(0xFFFF_FFFF_0000_0000)); - enum StackSize = 0x1000; - VirtAddress userStack = VirtAddress(process.heap.Alloc(StackSize)) + StackSize; + enum stackSize = 0x1000; + VirtAddress userStack = VirtAddress(process.heap.alloc(stackSize)) + stackSize; process.image.userStack = userStack; - process.threadState.tls = TLS.Init(process, false); + process.threadState.tls = TLS.init(process, false); { ubyte length = 0; @@ -393,13 +393,13 @@ public: const ulong endOfArgs = length; length += ulong.sizeof * (tmpArgs.length + 1); - VirtAddress elfArgs = process.heap.Alloc(length).VirtAddress; + VirtAddress elfArgs = process.heap.alloc(length).VirtAddress; VirtAddress cur = elfArgs; - char*[] entries = (elfArgs + endOfArgs).Ptr!(char*)[0 .. tmpArgs.length + 1]; + char*[] entries = (elfArgs + endOfArgs).ptr!(char*)[0 .. tmpArgs.length + 1]; foreach (idx, arg; tmpArgs) { - entries[idx] = cur.Ptr!char; - cur.Ptr!char[0 .. arg.length] = arg[]; - cur.Ptr!ubyte[arg.length] = 0; + entries[idx] = cur.ptr!char; + cur.ptr!char[0 .. arg.length] = arg[]; + cur.ptr!ubyte[arg.length] = 0; cur += arg.length + 1; } entries[$ - 1] = null; @@ -407,73 +407,73 @@ public: process.image.arguments = cast(char*[])entries; } - process.name = file.Name.dup; - process.image.file = file; + process.name = _file.name.dup; + process.image.file = _file; process.image.elf = this; foreach (arg; tmpArgs) arg.destroy; tmpArgs.destroy; - switchToUserMode(header.entry.Int, userStack.Int); + switchToUserMode(header.entry.num, userStack.num); } - ELF64ProgramHeader GetProgramHeader(size_t idx) { + ELF64ProgramHeader getProgramHeader(size_t idx) { assert(idx < header.programHeaderCount); ELF64ProgramHeader programHdr; - file.Read(&programHdr, header.programHeaderOffset + header.programHeaderEntrySize * idx); + _file.read(&programHdr, header.programHeaderOffset + header.programHeaderEntrySize * idx); return programHdr; } - ELF64SectionHeader GetSectionHeader(size_t idx) { + ELF64SectionHeader getSectionHeader(size_t idx) { assert(idx < header.sectionHeaderCount); ELF64SectionHeader sectionHdr; - file.Read(§ionHdr, header.sectionHeaderOffset + header.sectionHeaderEntrySize * idx); + _file.read(§ionHdr, header.sectionHeaderOffset + header.sectionHeaderEntrySize * idx); return sectionHdr; } - ELF64Symbol GetSymbol(size_t idx) { - assert(symtabIdx != ulong.max); - ELF64SectionHeader symtab = GetSectionHeader(symtabIdx); + ELF64Symbol getSymbol(size_t idx) { + assert(_symtabIdx != ulong.max); + ELF64SectionHeader symtab = getSectionHeader(_symtabIdx); ELF64Symbol symbol; - file.Read(&symbol, symtab.offset + ELF64Symbol.sizeof * idx); + _file.read(&symbol, symtab.offset + ELF64Symbol.sizeof * idx); return symbol; } - /// Note that the output will only be valid until GetSectionName is called again - char[] GetSectionName(uint nameIdx) { + /// Note that the output will only be valid until getSectionName is called again + char[] getSectionName(uint nameIdx) { __gshared char[255] buf; if (!header.sectionHeaderStringTableIndex) return cast(char[])"UNKNOWN"; - file.Read(buf, GetSectionHeader(header.sectionHeaderStringTableIndex).offset + nameIdx); + _file.read(buf, getSectionHeader(header.sectionHeaderStringTableIndex).offset + nameIdx); return buf[0 .. strlen(buf)]; } - /// Note that the output will only be valid until GetSymbolName is called again - char[] GetSymbolName(uint idx) { + /// Note that the output will only be valid until getSymbolName is called again + char[] getSymbolName(uint idx) { __gshared char[255] buf; - if (!strtabIdx) + if (!_strtabIdx) return cast(char[])"UNKNOWN"; - file.Read(buf, GetSectionHeader(strtabIdx).offset + idx); + _file.read(buf, getSectionHeader(_strtabIdx).offset + idx); return buf[0 .. strlen(buf)]; } - @property bool Valid() { - return valid; + @property bool valid() { + return _valid; } - @property ELF64Header Header() { - return header; + @property ELF64Header header() { + return _header; } private: - FileNode file; - bool valid; - ELF64Header header; - ulong strtabIdx = ulong.max; - ulong symtabIdx = ulong.max; + FileNode _file; + bool _valid; + ELF64Header _header; + ulong _strtabIdx = ulong.max; + ulong _symtabIdx = ulong.max; } diff --git a/kernel/src/data/font.d b/kernel/src/data/font.d index 8ce61f3..d203d18 100644 --- a/kernel/src/data/font.d +++ b/kernel/src/data/font.d @@ -1,8 +1,8 @@ -module Data.Font; +module data.font; interface Font { - @property size_t BufferSize(); - ref ulong[] GetChar(dchar ch, ref return ulong[] buffer); - @property uint Width(); - @property uint Height(); + @property size_t bufferSize(); + ref ulong[] getChar(dchar ch, ref return ulong[] buffer); + @property uint width(); + @property uint height(); } diff --git a/kernel/src/data/linkedlist.d b/kernel/src/data/linkedlist.d index c69674a..dca8373 100644 --- a/kernel/src/data/linkedlist.d +++ b/kernel/src/data/linkedlist.d @@ -1,8 +1,8 @@ -module Data.LinkedList; +module data.linkedlist; class LinkedList(T) { public: - void Add(T* obj) { + void add(T* obj) { Node n = new Node(obj, null); if (last) last.next = n; @@ -12,7 +12,7 @@ public: len++; } - T* Remove(T* obj) { + T* remove(T* obj) { Node prev; Node cur = first; while (cur && cur.data != obj) { @@ -35,7 +35,7 @@ public: return obj; } - T* Remove(size_t idx) { + T* remove(size_t idx) { if (idx >= len) return null; @@ -62,7 +62,7 @@ public: return data; } - T* Get(size_t idx) { + T* get(size_t idx) { if (idx >= len) return null; @@ -75,12 +75,12 @@ public: return cur.data; } - @property size_t Length() { + @property size_t length() { return len; } T* opIndex(size_t i) { - return Get(i); + return get(i); } size_t opDollar() { diff --git a/kernel/src/data/linker.d b/kernel/src/data/linker.d index 6181c1c..f8b9ee1 100644 --- a/kernel/src/data/linker.d +++ b/kernel/src/data/linker.d @@ -1,6 +1,6 @@ -module Data.Linker; +module data.linker; -import Data.Address; +import data.address; /* You have to do it like this because the linker will put the variable at the address. @@ -18,31 +18,31 @@ private extern (C) extern __gshared { static struct Linker { public: - @property static PhysAddress KernelPhysStart() { + @property static PhysAddress kernelPhysStart() { return PhysAddress(&KERNEL_LMA); } - @property static VirtAddress KernelStart() { + @property static VirtAddress kernelStart() { return VirtAddress(&KERNEL_VMA); } - @property static VirtAddress KernelEnd() { + @property static VirtAddress kernelEnd() { return VirtAddress(&KERNEL_END); } - @property static VirtAddress KernelSymbolsStart() { + @property static VirtAddress kernelSymbolsStart() { return VirtAddress(&KERNEL_SYMBOLS_START); } - @property static VirtAddress KernelSymbolsEnd() { + @property static VirtAddress kernelSymbolsEnd() { return VirtAddress(&KERNEL_SYMBOLS_END); } - @property static VirtAddress KernelModulesStart() { + @property static VirtAddress kernelModulesStart() { return VirtAddress(&KERNEL_MODULES_START); } - @property static VirtAddress KernelModulesEnd() { + @property static VirtAddress kernelModulesEnd() { return VirtAddress(&KERNEL_MODULES_END); } } diff --git a/kernel/src/data/multiboot.d b/kernel/src/data/multiboot.d index 9de40f1..5d78061 100644 --- a/kernel/src/data/multiboot.d +++ b/kernel/src/data/multiboot.d @@ -1,182 +1,181 @@ -module Data.Multiboot; +module data.multiboot; -import Data.Linker; -import Data.TextBuffer : scr = GetBootTTY; -import IO.Log; -import Data.Address; +import data.linker; +import data.textbuffer : scr = getBootTTY; +import io.log; +import data.address; enum MultibootTagType { - Align = 8, - End = 0, - CmdLine, - BootLoaderName, - Module, - BasicMemInfo, - BootDev, - MemoryMap, - VBE, - FrameBuffer, - ElfSections, - APM, - EFI32, - EFI64, - SMBIOS, - ACPIOld, - ACPINew, - Network, - EFIMemoryMap, - EFIBS + align_ = 8, + end = 0, + cmdLine, + bootLoaderName, + module_, + basicMemInfo, + bootDev, + memoryMap, + vbe, + frameBuffer, + elfSections, + apm, + efi32, + efi64, + smbios, + acpiOld, + acpiNew, + network, + efiMemoryMap, + efibs } enum MultibootFramebufferType { - Indexed, - RGB, - EGAText + indexed, + rgd, + egaText } enum MultibootMemoryType { - Available = 1, - Reserved, - ACPIReclaimable, - NVS, - BadRAM + available = 1, + reserved, + acpiReclaimable, + nvs, + badRAM } struct MultibootColor { align(1): - ubyte Red; - ubyte Green; - ubyte Blue; + ubyte red; + ubyte green; + ubyte blue; } struct MultibootMemoryMap { align(1): - ulong Address; - ulong Length; - uint Type; - private uint m_zero; + ulong address; + ulong length; + uint type; + private uint _zero; } struct MultibootTag { align(1): - uint Type; - uint Size; + uint type; + uint size; } struct MultibootTagString { align(1): - uint Type; - uint Size; - char String; + uint type; + uint size; + char string_; } struct MultibootTagModule { align(1): - uint Type; - uint Size; - uint ModStart; - uint ModEnd; - char String; + uint type; + uint size; + uint modStart; + uint modEnd; + char string_; } struct MultibootTagBasicMemInfo { align(1): - uint Type; - uint Size; - uint Lower; - uint Upper; + uint type; + uint size; + uint lower; + uint upper; } struct MultibootTagBootDev { align(1): - uint Type; - uint Size; - uint BiosDev; - uint Slice; - uint Part; + uint type; + uint size; + uint biosDev; + uint slice; + uint part; } struct MultibootTagMemoryMap { align(1): - uint Type; - uint Size; - uint EntrySize; - uint EntryVersion; - MultibootMemoryMap Entry; + uint type; + uint size; + uint entrySize; + uint entryVersion; + MultibootMemoryMap entry; } struct MultibootTagFramebufferCommon { align(1): - uint Type; - uint Size; - - ulong Address; - uint Pitch; - uint Width; - uint Height; - ubyte Bpp; - ubyte FramebufferType; - private ushort m_reserved; + uint type; + uint size; + + ulong address; + uint pitch; + uint width; + uint geight; + ubyte bpp; + ubyte framebufferType; + private ushort _reserved; } struct MultibootTagFramebuffer { align(1): - MultibootTagFramebufferCommon Common; + MultibootTagFramebufferCommon common; union { struct { - ushort PaletteNumColors; - MultibootColor Palette; + ushort paletteNumColors; + MultibootColor palette; } struct { - ubyte RedFieldPos; - ubyte RedMaskSize; - ubyte GreenFieldPos; - ubyte GreenMaskSize; - ubyte BlueFieldPos; - ubyte BlueMaskSize; + ubyte redFieldPos; + ubyte redMaskSize; + ubyte greenFieldPos; + ubyte greenMaskSize; + ubyte blueFieldPos; + ubyte blueMaskSize; } } } struct Multiboot { private enum { - HEADER_MAGIC = 0xE85250D6, - BOOTLOADER_MAGIC = 0x36D76289 + headerMagic = 0xE85250D6, + bootloaderMagic = 0x36D76289 } - __gshared MultibootTagModule*[256] Modules; - __gshared MultibootMemoryMap*[256] MemoryMap; - __gshared int ModulesCount; - __gshared int MemoryMapCount; - __gshared ulong MemorySize; + __gshared MultibootTagModule*[256] modules; + __gshared MultibootMemoryMap*[256] memoryMap; + __gshared int modulesCount; + __gshared int memoryMapCount; + __gshared ulong memorySize; - __gshared string[256] cmd_key; - __gshared string[256] cmd_value; - __gshared size_t cmd_length; + __gshared string[256] cmdKey; + __gshared string[256] cmdValue; + __gshared size_t cmdLength; - static void ParseHeader(uint magic, ulong info) { - if (magic != BOOTLOADER_MAGIC) { - scr.Writeln("Error: Bad multiboot 2 magic: %d", magic); + static void parseHeader(uint magic, ulong info) { + if (magic != bootloaderMagic) { + scr.writeln("Error: Bad multiboot 2 magic: %d", magic); while (true) { } } if (info & 7) { - scr.Writeln("Error: Unaligned MBI"); + scr.writeln("Error: Unaligned MBI"); while (true) { } } - //log.Info("Size: ", cast(ulong*)info); - MultibootTag* mbt = cast(MultibootTag*)(info + Linker.KernelStart + 8); - for (; mbt.Type != MultibootTagType.End; mbt = cast(MultibootTag*)(cast(ulong)mbt + ((mbt.Size + 7UL) & ~7UL))) { - switch (mbt.Type) { - case MultibootTagType.CmdLine: + MultibootTag* mbt = cast(MultibootTag*)(info + Linker.kernelStart + 8); + for (; mbt.type != MultibootTagType.end; mbt = cast(MultibootTag*)(cast(ulong)mbt + ((mbt.size + 7UL) & ~7UL))) { + switch (mbt.type) { + case MultibootTagType.cmdLine: auto tmp = cast(MultibootTagString*)mbt; - string str = cast(string)(&tmp.String)[0 .. tmp.Size - 9]; - log.Debug("CmdLine: ", str); + string str = cast(string)(&tmp.string_)[0 .. tmp.size - 9]; + log.debug_("CmdLine: ", str); if (!str.length) break; @@ -185,150 +184,106 @@ struct Multiboot { size_t cur; while (cur < str.length) { if (str[cur] == ' ') { - cmd_key[cmd_length] = (start == divider) ? null : str[start .. (start < divider) ? divider : cur]; - cmd_value[cmd_length] = (start > divider) ? null : str[divider + 1 .. cur]; - log.Debug("\tKey: '", cmd_key[cmd_length], "' Value: '", cmd_value[cmd_length], "'"); - cmd_length++; + cmdKey[cmdLength] = (start == divider) ? null : str[start .. (start < divider) ? divider : cur]; + cmdValue[cmdLength] = (start > divider) ? null : str[divider + 1 .. cur]; + log.debug_("\tKey: '", cmdKey[cmdLength], "' Value: '", cmdValue[cmdLength], "'"); + cmdLength++; start = cur + 1; } else if (str[cur] == '=') divider = cur; cur++; } - cmd_key[cmd_length] = (start == divider) ? null : str[start .. (start < divider) ? divider : cur]; - cmd_value[cmd_length] = (start > divider) ? null : str[divider + 1 .. cur]; - log.Debug("\tKey: '", cmd_key[cmd_length], "' Value: '", cmd_value[cmd_length], "'"); - cmd_length++; - + cmdKey[cmdLength] = (start == divider) ? null : str[start .. (start < divider) ? divider : cur]; + cmdValue[cmdLength] = (start > divider) ? null : str[divider + 1 .. cur]; + log.debug_("\tKey: '", cmdKey[cmdLength], "' Value: '", cmdValue[cmdLength], "'"); + cmdLength++; break; - case MultibootTagType.BootLoaderName: - auto tmp = cast(MultibootTagString*)mbt; - char* str = &tmp.String; - - //log.Info("Name: BootLoaderName, Value: ", cast(string)str[0 .. tmp.Size - 9]); + case MultibootTagType.bootLoaderName: break; - case MultibootTagType.Module: + case MultibootTagType.module_: auto tmp = cast(MultibootTagModule*)mbt; - char* str = &tmp.String; - Modules[ModulesCount++] = tmp; + char* str = &tmp.string_; + modules[modulesCount++] = tmp; - log.Info("Name: Module, Start: ", cast(void*)tmp.ModStart, ", End: ", cast(void*)tmp.ModEnd, - ", CMD: ", cast(string)str[0 .. tmp.Size - 17]); + log.info("Name: Module, Start: ", cast(void*)tmp.modStart, ", End: ", cast(void*)tmp.modEnd, + ", CMD: ", cast(string)str[0 .. tmp.size - 17]); break; - case MultibootTagType.BasicMemInfo: + case MultibootTagType.basicMemInfo: auto tmp = cast(MultibootTagBasicMemInfo*)mbt; - - //log.Info("Memory is: ", (tmp.Lower + tmp.Upper) / 1024, " MiB"); - //log.Info("Name: BasicMemInfo, Lower: ", tmp.Lower, ", Upper: ", tmp.Upper); - MemorySize = tmp.Lower + tmp.Upper; + memorySize = tmp.lower + tmp.upper; break; - case MultibootTagType.BootDev: - auto tmp = cast(MultibootTagBootDev*)mbt; - //log.Info("Name: BootDev, Device: ", tmp.BiosDev, ", Slice: ", tmp.Slice, ", Part: ", tmp.Part); + case MultibootTagType.bootDev: break; - case MultibootTagType.MemoryMap: - //log.Info("MemoryMap ---->"); - for (auto tmp = &(cast(MultibootTagMemoryMap*)mbt).Entry; cast(void*)tmp < (cast(void*)mbt + mbt.Size); tmp = cast( - MultibootMemoryMap*)(cast(ulong)tmp + (cast(MultibootTagMemoryMap*)mbt).EntrySize)) { - MemoryMap[MemoryMapCount++] = tmp; - log.Info("BaseAddr: ", cast(void*)tmp.Address, ", Length: ", cast(void*)tmp.Length, ", Type: ", tmp.Type); + case MultibootTagType.memoryMap: + for (auto tmp = &(cast(MultibootTagMemoryMap*)mbt).entry; cast(void*)tmp < (cast(void*)mbt + mbt.size); tmp = cast( + MultibootMemoryMap*)(cast(ulong)tmp + (cast(MultibootTagMemoryMap*)mbt).entrySize)) { + memoryMap[memoryMapCount++] = tmp; + log.info("BaseAddr: ", cast(void*)tmp.address, ", Length: ", cast(void*)tmp.length, ", Type: ", tmp.type); } break; - case MultibootTagType.VBE: + case MultibootTagType.vbe: break; - case MultibootTagType.FrameBuffer: - uint color; - auto tmp = cast(MultibootTagFramebuffer*)mbt; - - switch (tmp.Common.FramebufferType) { - case MultibootFramebufferType.Indexed: - uint distance; - uint bestDistance = 4 * 256 * 256; - auto palette = &tmp.Palette; - - for (int i = 0; i < tmp.PaletteNumColors; i++) { - distance = (0xFF - palette[i].Blue) * (0xFF - palette[i].Blue) + palette[i].Red * palette[i].Red - + palette[i].Green * palette[i].Green; - - if (distance < bestDistance) { - color = i; - bestDistance = distance; - } - } - break; - - case MultibootFramebufferType.RGB: - color = ((1 << tmp.BlueMaskSize) - 1) << tmp.BlueFieldPos; - break; - - case MultibootFramebufferType.EGAText: - color = '\\' | 0x0100; - break; - - default: - color = 0xFFFFFFFF; - break; - } - + case MultibootTagType.frameBuffer: break; - case MultibootTagType.ElfSections: + case MultibootTagType.elfSections: break; - case MultibootTagType.APM: + case MultibootTagType.apm: break; - case MultibootTagType.EFI32: + case MultibootTagType.efi32: break; - case MultibootTagType.EFI64: + case MultibootTagType.efi64: break; - case MultibootTagType.SMBIOS: + case MultibootTagType.smbios: break; - case MultibootTagType.ACPIOld: + case MultibootTagType.acpiOld: break; - case MultibootTagType.ACPINew: + case MultibootTagType.acpiNew: break; - case MultibootTagType.Network: + case MultibootTagType.network: break; - case MultibootTagType.EFIMemoryMap: + case MultibootTagType.efiMemoryMap: break; - case MultibootTagType.EFIBS: + case MultibootTagType.efibs: break; default: - scr.Writeln("Multiboot2 Error tag type"); + scr.writeln("Multiboot2 Error tag type"); break; } } } - static VirtAddress[2] GetModule(string name) { - foreach (mod; Modules[0 .. ModulesCount]) { - char* str = &mod.String; - if (str[0 .. mod.Size - 17] == name) - return [PhysAddress(mod.ModStart).Virtual, PhysAddress(mod.ModEnd).Virtual]; + static VirtAddress[2] getModule(string name) { + foreach (mod; modules[0 .. modulesCount]) { + char* str = &mod.string_; + if (str[0 .. mod.size - 17] == name) + return [PhysAddress(mod.modStart).virtual, PhysAddress(mod.modEnd).virtual]; } return [VirtAddress(), VirtAddress()]; } - static string* GetArgument(string key) { - foreach (idx, k; cmd_key[0 .. cmd_length]) + static string* getArgument(string key) { + foreach (idx, k; cmdKey[0 .. cmdLength]) if (k == key) - return &cmd_value[idx]; + return &cmdValue[idx]; return null; } } diff --git a/kernel/src/data/parameters.d b/kernel/src/data/parameters.d index c74f969..bf87753 100644 --- a/kernel/src/data/parameters.d +++ b/kernel/src/data/parameters.d @@ -1,9 +1,9 @@ -module Data.Parameters; +module data.parameters; -template Parameters(func...) { +template parameters(func...) { static if (is(typeof(&func[0]) Fsym : Fsym*) && is(Fsym == function)) static if (is(Fsym P == function)) - alias Parameters = P; + alias parameters = P; else static assert(0, "argument has no parameters"); } diff --git a/kernel/src/data/psf.d b/kernel/src/data/psf.d index b2886d5..0852d1b 100644 --- a/kernel/src/data/psf.d +++ b/kernel/src/data/psf.d @@ -1,24 +1,24 @@ -module Data.PSF; +module data.psf; -import Data.Font; -import Data.UTF; -import IO.FS.FileNode; +import data.font; +import data.utf; +import io.fs.filenode; private enum { - PSF2_MAGIC0 = 0x72, - PSF2_MAGIC1 = 0xb5, - PSF2_MAGIC2 = 0x4a, - PSF2_MAGIC3 = 0x86, + psf2Magic0 = 0x72, + psf2Magic1 = 0xb5, + psf2Magic2 = 0x4a, + psf2Magic3 = 0x86, /* bits used in flags */ - PSF2_HAS_UNICODE_TABLE = 0x01, + psf2HasUnicodeTable = 0x01, /* max version recognized so far */ - PSF2_MAXVERSION = 0, + psf2MaxVersion = 0, /* UTF8 separators */ - PSF2_SEPARATOR = 0xFF, - PSF2_STARTSEQ = 0xFE, + psf2Separator = 0xFF, + psf2Startseq = 0xFE } private struct psf2_header { @@ -35,78 +35,78 @@ private struct psf2_header { class PSF : Font { public: this(FileNode file) { - valid = read(file, hdr); - if (!valid) + _valid = file.read(_hdr, 0) == _hdr.sizeof; + if (!_valid) return; - valid = (hdr.magic[0] == PSF2_MAGIC0 && hdr.magic[1] == PSF2_MAGIC1 && hdr.magic[2] == PSF2_MAGIC2 && hdr.magic[3] == PSF2_MAGIC3); - if (!valid) + _valid = (_hdr.magic[0] == psf2Magic0 && _hdr.magic[1] == psf2Magic1 && _hdr.magic[2] == psf2Magic2 && _hdr.magic[3] == psf2Magic3); + if (!_valid) return; - fontData = new ubyte[hdr.charsize * hdr.length]; - valid = file.Read(fontData, hdr.headersize) == fontData.length; - if (!valid) + _fontData = new ubyte[_hdr.charsize * _hdr.length]; + _valid = file.read(_fontData, _hdr.headersize) == _fontData.length; + if (!_valid) return; - unicodeTable = new ubyte[file.Size - hdr.headersize - fontData.length]; - valid = file.Read(unicodeTable, hdr.headersize + fontData.length) == unicodeTable.length; - if (!valid) + _unicodeTable = new ubyte[file.size - _hdr.headersize - _fontData.length]; + _valid = file.read(_unicodeTable, _hdr.headersize + _fontData.length) == _unicodeTable.length; + if (!_valid) return; - parseUnicode(); + _parseUnicode(); } this(ubyte[] file) { if (file.length < psf2_header.sizeof) return; - hdr = *cast(psf2_header*)file.ptr; + _hdr = *cast(psf2_header*)file.ptr; - valid = (hdr.magic[0] == PSF2_MAGIC0 && hdr.magic[1] == PSF2_MAGIC1 && hdr.magic[2] == PSF2_MAGIC2 && hdr.magic[3] == PSF2_MAGIC3); - if (!valid) + _valid = (_hdr.magic[0] == psf2Magic0 && _hdr.magic[1] == psf2Magic1 && _hdr.magic[2] == psf2Magic2 && _hdr.magic[3] == psf2Magic3); + if (!_valid) return; - if (hdr.charsize * hdr.length + hdr.headersize > file.length) + if (_hdr.charsize * _hdr.length + _hdr.headersize > file.length) return; - fontData = file[hdr.headersize .. hdr.headersize + hdr.charsize * hdr.length]; - unicodeTable = file[hdr.headersize + hdr.charsize * hdr.length .. $]; + _fontData = file[_hdr.headersize .. _hdr.headersize + _hdr.charsize * _hdr.length]; + _unicodeTable = file[_hdr.headersize + _hdr.charsize * _hdr.length .. $]; - valid = true; - parseUnicode(); + _valid = true; + _parseUnicode(); } - bool Valid() { - return valid; + bool valid() { + return _valid; } - ref ulong[] GetChar(dchar ch, ref return ulong[] buffer) { - import IO.Log; + ref ulong[] getChar(dchar ch, ref return ulong[] buffer) { + import io.log; foreach (ref row; buffer) row = 0; - if (buffer.length < hdr.height) + if (buffer.length < _hdr.height) return buffer; - if (ch >= MAX_CHARS || ch == dchar.init) + if (ch >= _maxChars || ch == dchar.init) ch = 0; - dchar[MAX_RENDERER_PART] parts; - if (auto id = charJumpTable[ch]) - parts = renderer[id]; + dchar[_maxRendererPart] parts; + if (auto id = _charJumpTable[ch]) + parts = _renderer[id]; else parts[0] = ch; - size_t widthBytes = (hdr.width + 7) / 8; + size_t widthBytes = (_hdr.width + 7) / 8; foreach (partId; parts) { if (partId == dchar.init) break; - size_t partOffset = partId * hdr.charsize; - if (partOffset + widthBytes * hdr.height >= fontData.length) + size_t partOffset = partId * _hdr.charsize; + if (partOffset + widthBytes * _hdr.height >= _fontData.length) continue; - foreach (row; 0 .. hdr.height) { + foreach (row; 0 .. _hdr.height) { ulong bitmapRow; for (size_t partByte = 0; partByte < widthBytes; partByte++) - bitmapRow = bitmapRow << 8 | fontData[partOffset + row * widthBytes + partByte]; + bitmapRow = bitmapRow << 8 | _fontData[partOffset + row * widthBytes + partByte]; buffer[row] |= bitmapRow; } @@ -115,74 +115,70 @@ public: return buffer; } - @property size_t BufferSize() { - return hdr.height; + @property size_t bufferSize() { + return _hdr.height; } - @property uint Width() { - return hdr.width; //TODO: Hack space between font here later? + @property uint width() { + return _hdr.width; //TODO: Hack space between font here later? } - @property uint Height() { - return hdr.height; + @property uint height() { + return _hdr.height; } private: - bool valid; - psf2_header hdr; - ubyte[] fontData; - ubyte[] unicodeTable; - - enum MAX_CHARS = 0x10000; - enum MAX_RENDERER = MAX_CHARS; - enum MAX_RENDERER_PART = 4; - dchar[MAX_RENDERER_PART][MAX_RENDERER] renderer; // How to render a char - ushort[MAX_CHARS] charJumpTable; // Which renderer should be used to render the char - ushort rendererCount; - - bool read(T)(FileNode file, ref T t, ulong offset = 0) { - return file.Read((cast(ubyte*)(&t))[0 .. T.sizeof], offset) == T.sizeof; - } - - void parseUnicode() { + bool _valid; + psf2_header _hdr; + ubyte[] _fontData; + ubyte[] _unicodeTable; + + enum _maxChars = 0x10000; + enum _maxRenderer = _maxChars; + enum _maxRendererPart = 4; + dchar[_maxRendererPart][_maxRenderer] _renderer; // How to render a char + ushort[_maxChars] _charJumpTable; // Which renderer should be used to render the char + ushort _rendererCount; + + void _parseUnicode() { size_t idx; // TODO: Fix. Totally wrong! - if (false && hdr.flags & PSF2_HAS_UNICODE_TABLE && unicodeTable.length) { - while (unicodeTable.length) { - import IO.Log; + if (false && _hdr.flags & psf2HasUnicodeTable && _unicodeTable.length) { + while (_unicodeTable.length) { + import io.log; - while (unicodeTable.length && unicodeTable[0] != PSF2_STARTSEQ) { - if (unicodeTable[0] == PSF2_SEPARATOR) + while (_unicodeTable.length && _unicodeTable[0] != psf2Startseq) { + if (_unicodeTable[0] == psf2Separator) break; size_t bytesUsed; - auto ch = ParseUTF8(unicodeTable, bytesUsed); - if (ch < MAX_CHARS) - charJumpTable[ch] = rendererCount; - unicodeTable = unicodeTable[bytesUsed .. $]; + auto ch = parseUTF8(_unicodeTable, bytesUsed); + if (ch < _maxChars) + _charJumpTable[ch] = _rendererCount; + _unicodeTable = _unicodeTable[bytesUsed .. $]; idx += bytesUsed; } - if (unicodeTable.length) - unicodeTable = unicodeTable[1 .. $]; + if (_unicodeTable.length) + _unicodeTable = _unicodeTable[1 .. $]; size_t rendererPart; - while (unicodeTable.length && unicodeTable[0] != PSF2_SEPARATOR) { - if (rendererPart == MAX_RENDERER_PART) { - while (unicodeTable.length && unicodeTable[0] != PSF2_SEPARATOR) - unicodeTable = unicodeTable[1 .. $]; + while (_unicodeTable.length && _unicodeTable[0] != psf2Separator) { + if (rendererPart == _maxRendererPart) { + while (_unicodeTable.length && _unicodeTable[0] != psf2Separator) + _unicodeTable = _unicodeTable[1 .. $]; break; } size_t bytesUsed; - renderer[rendererCount][rendererPart++] = ParseUTF8(unicodeTable, bytesUsed); - unicodeTable = unicodeTable[bytesUsed .. $]; + _renderer[_rendererCount][rendererPart++] = parseUTF8(_unicodeTable, bytesUsed); + _unicodeTable = _unicodeTable[bytesUsed .. $]; idx += bytesUsed; } - rendererCount++; - if (unicodeTable.length) - unicodeTable = unicodeTable[1 .. $]; + _rendererCount++; + if (_unicodeTable.length) + _unicodeTable = _unicodeTable[1 .. $]; } } } diff --git a/kernel/src/data/register.d b/kernel/src/data/register.d index b41892e..172f762 100644 --- a/kernel/src/data/register.d +++ b/kernel/src/data/register.d @@ -1,17 +1,17 @@ -module Data.Register; +module data.register; -import Data.Address; +import data.address; -private extern (C) VirtAddress CPU_ret_cr2(); +private extern (C) VirtAddress cpuRetCR2(); struct Registers { align(1): - VirtAddress R15, R14, R13, R12, R11, R10, R9, R8; - VirtAddress RBP, RDI, RSI, RDX, RCX, RBX, RAX; - VirtAddress IntNumber, ErrorCode; - VirtAddress RIP, CS, Flags, RSP, SS; + VirtAddress r15, r14, r13, r12, r11, r10, r9, r8; + VirtAddress rbp, rdi, rsi, rdx, rcx, rbx, rax; + VirtAddress intNumber, errorCode; + VirtAddress rip, cs, flags, rsp, ss; - @property VirtAddress CR2() const { - return CPU_ret_cr2(); + @property VirtAddress cr2() const { + return cpuRetCR2(); } } diff --git a/kernel/src/data/screen.d b/kernel/src/data/screen.d index 568abf1..c17d5f4 100644 --- a/kernel/src/data/screen.d +++ b/kernel/src/data/screen.d @@ -1,9 +1,9 @@ -module Data.Screen; +module data.screen; -import Data.Color; +import data.color; interface Screen { - @property long Width(); - @property long Height(); - @property Color[] PixelData(); + @property long width(); + @property long height(); + @property Color[] pixelData(); } diff --git a/kernel/src/data/string_.d b/kernel/src/data/string_.d index 6a0a1f4..04177cd 100644 --- a/kernel/src/data/string_.d +++ b/kernel/src/data/string_.d @@ -1,7 +1,7 @@ -module Data.String; +module data.string_; -import Data.Util; -import Memory.Heap; +import data.util; +import memory.heap; nothrow pure size_t strlen(const(char)* str) { if (!str) @@ -61,7 +61,7 @@ string itoa(S)(S v, char[] buf, uint base = 10) if (isNumber!S) { size_t itoa(S)(S v, char* buf, ulong len, uint base = 10) if (isNumber!S) { assert(1 < base && base <= 16); Unqual!S value = v; - immutable char[] BASE_CHARS = cast(immutable char[])"0123456789ABCDEF"; + immutable char[] baseChars = cast(immutable char[])"0123456789ABCDEF"; size_t pos = len; bool sign = false; @@ -71,7 +71,7 @@ size_t itoa(S)(S v, char* buf, ulong len, uint base = 10) if (isNumber!S) { } do { - buf[--pos] = BASE_CHARS[value % base]; + buf[--pos] = baseChars[value % base]; value /= base; } while (value); @@ -84,12 +84,12 @@ size_t itoa(S)(S v, char* buf, ulong len, uint base = 10) if (isNumber!S) { long atoi(string str, uint base = 10) { long result; - immutable char[] BASE_CHARS = cast(immutable char[])"0123456789ABCDEF"; + immutable char[] baseChars = cast(immutable char[])"0123456789ABCDEF"; foreach (ch; str) { long value; for (value = 0; value <= base; value++) - if (BASE_CHARS[value] == ch) + if (baseChars[value] == ch) break; if (value > base) return result; @@ -105,7 +105,7 @@ string dtoa(double v, char[] buf, uint base = 10) { } bool isNan(double value) { - enum ulong NANMASK = 0x7FFUL; + enum ulong nanMask = 0x7FFUL; union storage { double v; ulong i; @@ -114,7 +114,7 @@ bool isNan(double value) { storage s; s.v = value; - return ((s.i >> 51UL) & NANMASK) == NANMASK; + return ((s.i >> 51UL) & nanMask) == nanMask; } size_t dtoa(double value, char* buf, ulong len, uint base = 10) { @@ -147,14 +147,14 @@ size_t dtoa(double value, char* buf, ulong len, uint base = 10) { ulong exponent = cast(ulong)value; double fraction = value - exponent; - immutable char[] BASE_CHARS = cast(immutable char[])"0123456789ABCDEF"; + immutable char[] baseChars = cast(immutable char[])"0123456789ABCDEF"; // Fraction char[16] fracTmp; int fracPos; fraction *= base; do { - fracTmp[fracPos++] = BASE_CHARS[cast(ulong)fraction % base]; + fracTmp[fracPos++] = baseChars[cast(ulong)fraction % base]; fraction *= base; } while (fraction && fracPos < fracTmp.length); @@ -166,7 +166,7 @@ size_t dtoa(double value, char* buf, ulong len, uint base = 10) { buf[--pos] = '.'; // Exponent do { - buf[--pos] = BASE_CHARS[exponent % base]; + buf[--pos] = baseChars[exponent % base]; exponent /= base; } while (exponent); diff --git a/kernel/src/data/textbuffer.d b/kernel/src/data/textbuffer.d index 9dd6155..80e2f74 100644 --- a/kernel/src/data/textbuffer.d +++ b/kernel/src/data/textbuffer.d @@ -1,18 +1,18 @@ -module Data.TextBuffer; +module data.textbuffer; -import Data.Color; -import Data.String; -import Data.Util; +import data.color; +import data.string_; +import data.util; enum SlotFlags : ushort { - Nothing, - Blinking = 1 << 0, - //Underline = 1 << 1, - //Bold = 1 << 2, - Shadow = 1 << 3, - InvertedColors = 1 << 4, - FlipX = 1 << 5, - FlipY = 1 << 6, + nothing, + blinking = 1 << 0, + //underline = 1 << 1, + //bold = 1 << 2, + shadow = 1 << 3, + invertedColors = 1 << 4, + flipX = 1 << 5, + flipY = 1 << 6, unknown = 1 << 15, } @@ -32,195 +32,195 @@ public: alias OnChangedCallbackType = void function(size_t start, size_t end); this(Slot[] buffer) { - this.buffer = buffer; - otherBuffer = true; + _buffer = buffer; + _otherBuffer = true; - defaultFG = Color(0, 255, 255); - defaultBG = Color(0, 0x22, 0x22); + _defaultFG = Color(0, 255, 255); + _defaultBG = Color(0, 0x22, 0x22); } this(size_t size) { - buffer = new Slot[size]; - otherBuffer = false; + _buffer = new Slot[size]; + _otherBuffer = false; - defaultFG = Color(0, 255, 255); - defaultBG = Color(0, 0x22, 0x22); + _defaultFG = Color(0, 255, 255); + _defaultBG = Color(0, 0x22, 0x22); } ~this() { - if (!otherBuffer) - buffer.destroy; + if (!_otherBuffer) + _buffer.destroy; } - void Write(Args...)(Args args) { - import Data.Address; + void write(Args...)(Args args) { + import data.address; - size_t startPos = count; - Color fg = defaultFG; - Color bg = defaultBG; - SlotFlags flags = defaultFlags; + size_t startPos = _count; + Color fg = _defaultFG; + Color bg = _defaultBG; + SlotFlags flags = _defaultFlags; foreach (arg; args) { alias T = Unqual!(typeof(arg)); static if (is(T : const char[])) - write(arg, fg, bg, flags); + _write(arg, fg, bg, flags); else static if (is(T == BinaryInt)) { - write("0b", fg, bg, flags); - writeNumber(arg.Int, 2, fg, bg, flags); + _write("0b", fg, bg, flags); + _writeNumber(arg.num, 2, fg, bg, flags); } else static if (is(T : V*, V)) { - write("0x", fg, bg, flags); - writeNumber(cast(ulong)arg, 16, fg, bg, flags); + _write("0x", fg, bg, flags); + _writeNumber(cast(ulong)arg, 16, fg, bg, flags); } else static if (is(T == VirtAddress) || is(T == PhysAddress) || is(T == PhysAddress32)) { - write("0x", fg, bg, flags); - writeNumber(cast(ulong)arg.Int, 16, fg, bg, flags); + _write("0x", fg, bg, flags); + _writeNumber(cast(ulong)arg.num, 16, fg, bg, flags); } else static if (is(T == enum)) - writeEnum(arg, fg, bg, flags); + _writeEnum(arg, fg, bg, flags); else static if (is(T == bool)) - write((arg) ? "true" : "false", fg, bg, flags); + _write((arg) ? "true" : "false", fg, bg, flags); else static if (is(T : char)) - write(arg, fg, bg, flags); + _write(arg, fg, bg, flags); else static if (isNumber!T) - writeNumber(arg, 10, fg, bg, flags); + _writeNumber(arg, 10, fg, bg, flags); else static if (isFloating!T) - writeFloating(cast(double)arg, 10, fg, bg, flags); + _writeFloating(cast(double)arg, 10, fg, bg, flags); else - write(arg.toString, fg, bg, flags); + _write(arg.toString, fg, bg, flags); } - if (onChanged) - onChanged(startPos, count); + if (_onChanged) + _onChanged(startPos, _count); } - void Writeln(Args...)(Args args) { - Write(args, '\n'); + void writeln(Args...)(Args args) { + write(args, '\n'); } - void Writef(Args...)(wstring format, Args args) { - size_t startPos = count; + void writef(Args...)(wstring format, Args args) { + size_t startPos = _count; static assert(0); - if (onChanged) - onChanged(startPos, count); + if (_onChanged) + _onChanged(startPos, _count); } - void Writefln(Args...)(wstring format, Args args) { - size_t startPos = count; - OnChangedCallback cb = onChanged; //Hack to make it only update once. - onChanged = null; + void writefln(Args...)(wstring format, Args args) { + size_t startPos = _count; + OnChangedCallback cb = _onChanged; //Hack to make it only update once. + _onChanged = null; - Writef(args); - write('\n'); + writef(format, args); + _write('\n'); - onChanged = cb; - if (onChanged) - onChanged(startPos, count); + _onChanged = cb; + if (_onChanged) + _onChanged(startPos, _count); } - void Clear() { - if (onChanged) - onChanged(-1, -1); + void clear() { + if (_onChanged) + _onChanged(-1, -1); } - @property Slot[] Buffer() { - return buffer; + @property Slot[] buffer() { + return _buffer; } - @property size_t Count() { - return count; + @property size_t count() { + return _count; } - @property ref Color Foreground() { - return defaultFG; + @property ref Color foreground() { + return _defaultFG; } - @property ref Color Background() { - return defaultBG; + @property ref Color background() { + return _defaultBG; } - @property ref SlotFlags Flags() { - return defaultFlags; + @property ref SlotFlags flags() { + return _defaultFlags; } - @property ref OnChangedCallbackType OnChangedCallback() { - return onChanged; + @property ref OnChangedCallbackType onChangedCallback() { + return _onChanged; } private: - enum IncreaseSize = 0x1000; + enum increaseSize = 0x1000; - bool otherBuffer; - Slot[] buffer; - size_t count; + bool _otherBuffer; + Slot[] _buffer; + size_t _count; - Color defaultFG; - Color defaultBG; - SlotFlags defaultFlags; + Color _defaultFG; + Color _defaultBG; + SlotFlags _defaultFlags; - OnChangedCallbackType onChanged; + OnChangedCallbackType _onChanged; - void resize() { - if (otherBuffer) { - Slot[] newBuffer = new Slot[buffer.length + IncreaseSize]; + void _resize() { + if (_otherBuffer) { + Slot[] newBuffer = new Slot[_buffer.length + increaseSize]; foreach (idx, slot; buffer) newBuffer[idx] = slot; - buffer = newBuffer; - otherBuffer = false; + _buffer = newBuffer; + _otherBuffer = false; } else - buffer.length += IncreaseSize; + _buffer.length += increaseSize; } - void write(wchar ch, Color fg, Color bg, SlotFlags flags) { - if (buffer.length == count) - resize(); - buffer[count++] = Slot(ch, fg, bg, flags); + void _write(wchar ch, Color fg, Color bg, SlotFlags flags) { + if (_buffer.length == _count) + _resize(); + _buffer[_count++] = Slot(ch, fg, bg, flags); } - void write(in char[] str, Color fg, Color bg, SlotFlags flags) { + void _write(in char[] str, Color fg, Color bg, SlotFlags flags) { foreach (char ch; str) - write(ch, fg, bg, flags); + _write(ch, fg, bg, flags); } - void write(in wchar[] str, Color fg, Color bg, SlotFlags flags) { + void _write(in wchar[] str, Color fg, Color bg, SlotFlags flags) { foreach (wchar ch; str) - write(ch, fg, bg, flags); + _write(ch, fg, bg, flags); } - void write(char* str, Color fg, Color bg, SlotFlags flags) { + void _write(char* str, Color fg, Color bg, SlotFlags flags) { while (*str) - write(*(str++), fg, bg, flags); + _write(*(str++), fg, bg, flags); } - void writeNumber(S = long)(S value, uint base, Color fg, Color bg, SlotFlags flags) if (isNumber!S) { + void _writeNumber(S = long)(S value, uint base, Color fg, Color bg, SlotFlags flags) if (isNumber!S) { char[S.sizeof * 8] buf; - write(itoa(value, buf, base), fg, bg, flags); + _write(itoa(value, buf, base), fg, bg, flags); } - void writeFloating(double value, uint base, Color fg, Color bg, SlotFlags flags) { + void _writeFloating(double value, uint base, Color fg, Color bg, SlotFlags flags) { char[double.sizeof * 8] buf; - write(dtoa(value, buf, base), fg, bg, flags); + _write(dtoa(value, buf, base), fg, bg, flags); } - void writeEnum(T)(T value, Color fg, Color bg, SlotFlags flags) if (is(T == enum)) { - foreach (i, e; EnumMembers!T) + void _writeEnum(T)(T value, Color fg, Color bg, SlotFlags flags) if (is(T == enum)) { + foreach (i, e; enumMembers!T) if (value == e) { - write(__traits(allMembers, T)[i], fg, bg, flags); + _write(__traits(allMembers, T)[i], fg, bg, flags); return; } - write("cast(", fg, bg, flags); - write(T.stringof, fg, bg, flags); - write(")", fg, bg, flags); - writeNumber(cast(int)value, 10, fg, bg, flags); + _write("cast(", fg, bg, flags); + _write(T.stringof, fg, bg, flags); + _write(")", fg, bg, flags); + _writeNumber(cast(int)value, 10, fg, bg, flags); } } -TextBuffer GetBootTTY() { - import Data.Util : InplaceClass; +TextBuffer getBootTTY() { + import data.util : inplaceClass; __gshared TextBuffer textBuffer; __gshared ubyte[__traits(classInstanceSize, TextBuffer)] buf; __gshared Slot[0x1000] slotBuffer; if (!textBuffer) - textBuffer = InplaceClass!TextBuffer(buf, slotBuffer); + textBuffer = inplaceClass!TextBuffer(buf, slotBuffer); return textBuffer; } diff --git a/kernel/src/data/utf.d b/kernel/src/data/utf.d index 4067edc..bcc67be 100644 --- a/kernel/src/data/utf.d +++ b/kernel/src/data/utf.d @@ -1,9 +1,9 @@ -module Data.UTF; +module data.utf; -import IO.Log; +import io.log; -dchar ParseUTF8(ubyte[] data, ref size_t bytesUsed) { - __gshared immutable ubyte[] MASK_NEEDED = [0b0111_1111, 0b0011_1111, 0b0001_1111, 0b0000_1111, 0b0000_0111]; +dchar parseUTF8(ubyte[] data, ref size_t bytesUsed) { + __gshared immutable ubyte[] maskNeeded = [0b0111_1111, 0b0011_1111, 0b0001_1111, 0b0000_1111, 0b0000_0111]; uint ch; if (!data.length) { bytesUsed = 0; @@ -18,8 +18,8 @@ dchar ParseUTF8(ubyte[] data, ref size_t bytesUsed) { break; if (expectedCharSize > 3) { // Invalid, char cannot have more than 4 bytes - log.Debug("Invalid, cannot have more than 4 bytes"); - log.Warning("\t Error byte: ", cast(void*)data[0]); + log.debug_("Invalid, cannot have more than 4 bytes"); + log.warning("\t Error byte: ", cast(void*)data[0]); goto error; } else if (expectedCharSize == 0) { // Doesn't require another bytes bytesUsed = 1; @@ -27,22 +27,22 @@ dchar ParseUTF8(ubyte[] data, ref size_t bytesUsed) { } else if (expectedCharSize == 1) { // If expectedCharSize is 1, it is a 'extra' char // expectedCharSize can only be 0 (Means 1), 2, 3 - log.Debug("Invalid byte"); - log.Warning("\t Error byte: ", cast(void*)data[0]); + log.debug_("Invalid byte"); + log.warning("\t Error byte: ", cast(void*)data[0]); goto error; } if (data.length < expectedCharSize) { - log.Debug("Data array is too small! needed size: ", expectedCharSize, " is: ", data.length); + log.debug_("Data array is too small! needed size: ", expectedCharSize, " is: ", data.length); goto error; } - ch = data[0] & MASK_NEEDED[expectedCharSize]; + ch = data[0] & maskNeeded[expectedCharSize]; for (size_t i = 1; i < expectedCharSize; i++) { if ((data[i] & 0b1100_0000) != 0b1000_0000) { - log.Debug("Expected a 'extra' char, found a data char instead"); - log.Warning("\t Error byte: ", cast(void*)data[i], " idx: ", i); + log.debug_("Expected a 'extra' char, found a data char instead"); + log.warning("\t Error byte: ", cast(void*)data[i], " idx: ", i); goto error; } @@ -58,7 +58,7 @@ error: return dchar.init; } -ubyte[4] ToUTF8(dchar ch, ref size_t bytesUsed) { +ubyte[4] toUTF8(dchar ch, ref size_t bytesUsed) { ubyte[4] ret; uint ich = cast(uint)ch; if (ich <= 0x7F) { @@ -80,7 +80,7 @@ ubyte[4] ToUTF8(dchar ch, ref size_t bytesUsed) { ret[3] = cast(ubyte)(ch >> (3 + 6 + 6)) | /* Clear second top bit */ 0x40 | /* Set top bit */ 0x80; bytesUsed = 4; } else // invalid size - return ToUTF8(dchar.init, bytesUsed); + return toUTF8(dchar.init, bytesUsed); return ret; } @@ -92,7 +92,7 @@ struct UTF8Range { this(ubyte[] str) { this.str = str; - this.current = ParseUTF8(str, bytesUsed); + this.current = parseUTF8(str, bytesUsed); } @property dchar front() const { @@ -102,7 +102,7 @@ struct UTF8Range { void popFront() { str = str[bytesUsed .. $]; if (str.length) - current = ParseUTF8(str, bytesUsed); + current = parseUTF8(str, bytesUsed); else current = dchar.init; } @@ -117,7 +117,7 @@ struct UTF8Range { size_t bytesUsed; dchar ch; while (str.length && index--) { - ch = ParseUTF8(str, bytesUsed); + ch = parseUTF8(str, bytesUsed); str = str[bytesUsed .. $]; } if (index) @@ -134,7 +134,7 @@ struct UTF8Range { size_t bytesUsed; size_t count; while (str.length) { - ParseUTF8(str, bytesUsed); + parseUTF8(str, bytesUsed); str = str[bytesUsed .. $]; count++; } diff --git a/kernel/src/data/util.d b/kernel/src/data/util.d index c1766ca..2900105 100644 --- a/kernel/src/data/util.d +++ b/kernel/src/data/util.d @@ -1,4 +1,4 @@ -module Data.Util; +module data.util; template Unqual(T) { static if (is(T U == shared(const U))) @@ -28,8 +28,8 @@ template TypeTuple(T...) { alias TypeTuple = T; } -template EnumMembers(E) if (is(E == enum)) { - template WithIdentifier(string ident) { +template enumMembers(E) if (is(E == enum)) { + template withIdentifier(string ident) { static if (ident == "Symbolize") { template Symbolize(alias value) { enum Symbolize = value; @@ -39,19 +39,19 @@ template EnumMembers(E) if (is(E == enum)) { } } - template EnumSpecificMembers(names...) { + template enumSpecificMembers(names...) { static if (names.length > 0) { - alias EnumSpecificMembers = TypeTuple!(WithIdentifier!(names[0]).Symbolize!(__traits(getMember, E, - names[0])), EnumSpecificMembers!(names[1 .. $])); + alias enumSpecificMembers = TypeTuple!(withIdentifier!(names[0]).Symbolize!(__traits(getMember, E, + names[0])), enumSpecificMembers!(names[1 .. $])); } else { - alias EnumSpecificMembers = TypeTuple!(); + alias enumSpecificMembers = TypeTuple!(); } } - alias EnumMembers = EnumSpecificMembers!(__traits(allMembers, E)); + alias enumMembers = enumSpecificMembers!(__traits(allMembers, E)); } -T InplaceClass(T, Args...)(void[] chunk, auto ref Args args) if (is(T == class)) { +T inplaceClass(T, Args...)(void[] chunk, auto ref Args args) if (is(T == class)) { static assert(!__traits(isAbstractClass, T), T.stringof ~ " is abstract and it can't be emplaced"); enum classSize = __traits(classInstanceSize, T); @@ -73,7 +73,7 @@ struct BinaryInt { ulong Int; } -void Swap(T)(ref T t1, ref T t2) { +void swap(T)(ref T t1, ref T t2) { T tmp = t1; t1 = t2; t2 = tmp; diff --git a/kernel/src/extra.S b/kernel/src/extra.S new file mode 100644 index 0000000..a3e45b7 --- /dev/null +++ b/kernel/src/extra.S @@ -0,0 +1,45 @@ +.text +.code64 + +.global cpuRefreshIREQ +.type cpuRefreshIREQ, %function +cpuRefreshIREQ: + mov $0x10, %RAX + mov %AX, %DS + mov %AX, %ES + mov %AX, %SS + + mov %RSP, %RDX + push %RAX + push %RDX + pushfq + push $0x08 + + mov $1f, %RAX + push %RAX + iretq + + 1: + ret +.size cpuRefreshIREQ, .-cpuRefreshIREQ + +.global cpuInstallCR3 +.type cpuInstallCR3, %function +cpuInstallCR3: + mov %RDI, %CR3 + ret +.size cpuInstallCR3, .-cpuInstallCR3 + +.global cpuRetCR2 +.type cpuRetCR2, %function +cpuRetCR2: + mov %CR2, %RAX + ret +.size cpuRetCR2, .-cpuRetCR2 + +.global cpuFlushPage +.type cpuFlushPage, %function +cpuFlushPage: + invlpg (%rdi) + ret +.size cpuFlushPage, .-cpuFlushPage diff --git a/kernel/src/hw/cmos/cmos.d b/kernel/src/hw/cmos/cmos.d index 93035e8..7b4b577 100644 --- a/kernel/src/hw/cmos/cmos.d +++ b/kernel/src/hw/cmos/cmos.d @@ -1,89 +1,86 @@ -module HW.CMOS.CMOS; +module hw.cmos.cmos; -import IO.Port; +import io.port; +import cpu.pit; private enum { - CMOS_ADDRESS = 0x70, - CMOS_DATA = 0x71, - - CMOS_SECOND = 0, - CMOS_MINUTE = 2, - CMOS_HOUR = 4, - CMOS_DAY = 7, - CMOS_MONTH = 8, - CMOS_YEAR = 9, - - CMOS_REGA = 0x0A, - CMOS_REGB = 0x0B + cmosAddress = 0x70, + cmosData = 0x71, + + cmosSecond = 0, + cmosMinute = 2, + cmosHour = 4, + cmosDay = 7, + cmosMonth = 8, + cmosYear = 9, + + cmosRega = 0x0A, + cmosRegb = 0x0B } class CMOS { public: this(ubyte centuryReg) { - this.centuryReg = centuryReg; - RetrieveTime(); + _centuryReg = centuryReg; + retrieveTime(); } - void RetrieveTime() { - import CPU.PIT; - + void retrieveTime() { ushort[128] last; - ushort[128] data; - dump(data); + ushort[128] rawData; + dump(rawData); do { - foreach (idx, val; data) + foreach (idx, val; rawData) last[idx] = val; - dump(data); + dump(rawData); } - while (last[CMOS_SECOND] != data[CMOS_SECOND] || last[CMOS_MINUTE] != data[CMOS_MINUTE] - || last[CMOS_HOUR] != data[CMOS_HOUR] || last[CMOS_DAY] != data[CMOS_DAY] - || last[CMOS_MONTH] != data[CMOS_MONTH] || last[CMOS_YEAR] != data[CMOS_YEAR] - || last[CMOS_YEAR] != data[CMOS_YEAR] || (centuryReg && last[centuryReg] != data[centuryReg])); - - PIT.Clear(); - - if (!(data[CMOS_REGB] & 0x04)) { // If data is BCD - data[CMOS_SECOND] = fromBCD(data[CMOS_SECOND]); - data[CMOS_MINUTE] = fromBCD(data[CMOS_MINUTE]); - data[CMOS_HOUR] = ((data[CMOS_HOUR] & 0x0F) + (((data[CMOS_HOUR] & 0x70) / 16) * 10)) | (data[CMOS_HOUR] & 0x80); - data[CMOS_DAY] = fromBCD(data[CMOS_DAY]); - data[CMOS_MONTH] = fromBCD(data[CMOS_MONTH]); - data[CMOS_YEAR] = fromBCD(data[CMOS_YEAR]); - if (centuryReg) - data[centuryReg] = fromBCD(data[centuryReg]); + while (last[cmosSecond] != rawData[cmosSecond] || last[cmosMinute] != rawData[cmosMinute] + || last[cmosHour] != rawData[cmosHour] || last[cmosDay] != rawData[cmosDay] + || last[cmosMonth] != rawData[cmosMonth] || last[cmosYear] != rawData[cmosYear] + || last[cmosYear] != rawData[cmosYear] || (_centuryReg && last[_centuryReg] != rawData[_centuryReg])); + + PIT.clear(); + + if (!(rawData[cmosRegb] & 0x04)) { // If rawData is BCD + rawData[cmosSecond] = fromBCD(rawData[cmosSecond]); + rawData[cmosMinute] = fromBCD(rawData[cmosMinute]); + rawData[cmosHour] = ((rawData[cmosHour] & 0x0F) + (((rawData[cmosHour] & 0x70) / 16) * 10)) | (rawData[cmosHour] & 0x80); + rawData[cmosDay] = fromBCD(rawData[cmosDay]); + rawData[cmosMonth] = fromBCD(rawData[cmosMonth]); + rawData[cmosYear] = fromBCD(rawData[cmosYear]); + if (_centuryReg) + rawData[_centuryReg] = fromBCD(rawData[_centuryReg]); } - if (!(data[CMOS_REGB] & 0x02) && (data[CMOS_HOUR] & 0x80)) // am/pm -> 24 hours - data[CMOS_HOUR] = ((data[CMOS_HOUR] & 0x7F) + 12) % 24; + if (!(rawData[cmosRegb] & 0x02) && (rawData[cmosHour] & 0x80)) // am/pm -> 24 hours + rawData[cmosHour] = ((rawData[cmosHour] & 0x7F) + 12) % 24; - if (centuryReg) - data[CMOS_YEAR] += data[centuryReg] * 100; + if (_centuryReg) + rawData[cmosYear] += rawData[_centuryReg] * 100; else { - import Data.String; + import data.string_; string year = __DATE__[$ - 4 .. $]; ushort currentYear = cast(ushort)atoi(year); - data[CMOS_YEAR] += (currentYear / 100) * 100; - if (data[CMOS_YEAR] < currentYear) - data[CMOS_YEAR] += 100; + rawData[cmosYear] += (currentYear / 100) * 100; + if (rawData[cmosYear] < currentYear) + rawData[cmosYear] += 100; } - timestamp = secondsOfYear(cast(ushort)(data[CMOS_YEAR] - 1)) + secondsOfMonth(data[CMOS_MONTH] - 1, - data[CMOS_YEAR]) + (data[CMOS_DAY] - 1) * 86400 + (data[CMOS_HOUR]) * 3600 + (data[CMOS_MINUTE]) * 60 + data[CMOS_SECOND] - + 0; + _timestamp = secondsOfYear(cast(ushort)(rawData[cmosYear] - 1)) + secondsOfMonth(rawData[cmosMonth] - 1, + rawData[cmosYear]) + (rawData[cmosDay] - 1) * 86400 + (rawData[cmosHour]) * 3600 + ( + rawData[cmosMinute]) * 60 + rawData[cmosSecond] + 0; } - @property ulong TimeStamp() { - import CPU.PIT; - - return timestamp + PIT.Seconds; + @property ulong timeStamp() { + return _timestamp + PIT.seconds; } private: - ulong timestamp; - ubyte centuryReg; + ulong _timestamp; + ubyte _centuryReg; void dump(ref ushort[128] rawData) { while (updateInProgress) { @@ -93,13 +90,13 @@ private: } ubyte read(ubyte reg) { - Out!ubyte(CMOS_ADDRESS, reg); //(NMI_disable_bit << 7) | - return In!ubyte(CMOS_DATA); + outp!ubyte(cmosAddress, reg); //(NMI_disable_bit << 7) | + return inp!ubyte(cmosData); } void write(ubyte reg, ubyte data) { - Out!ubyte(CMOS_ADDRESS, reg); //(NMI_disable_bit << 7) | - return Out!ubyte(CMOS_DATA, data); + outp!ubyte(cmosAddress, reg); //(NMI_disable_bit << 7) | + return outp!ubyte(cmosData, data); } ushort fromBCD(ushort bcd) { @@ -162,16 +159,16 @@ private: } } -CMOS GetCMOS() { - import Data.Util : InplaceClass; +CMOS getCMOS() { + import data.util : inplaceClass; __gshared ubyte[__traits(classInstanceSize, CMOS)] data; __gshared CMOS cmos; if (!cmos) { - import ACPI.RSDP : rsdp; + import acpi.rsdp : rsdp; - cmos = InplaceClass!CMOS(data, rsdp.FADTInstance.Century); + cmos = inplaceClass!CMOS(data, rsdp.fadtInstance.century); } return cmos; } diff --git a/kernel/src/hw/pci/pci.d b/kernel/src/hw/pci/pci.d index 514be1e..9976bff 100644 --- a/kernel/src/hw/pci/pci.d +++ b/kernel/src/hw/pci/pci.d @@ -1,20 +1,20 @@ -module HW.PCI.PCI; +module hw.pci.pci; -import Data.Address; -import IO.Port; -import IO.Log; -import Data.TextBuffer : scr = GetBootTTY; +import data.address; +import io.port; +import io.log; +import data.textbuffer : scr = getBootTTY; private enum { - CONFIG_ADDRESS = 0xCF8, - CONFIG_DATA = 0xCFC + configAddress = 0xCF8, + configData = 0xCFC } struct PCIDevice { this(PCI pci, ubyte bus, ubyte slot) { ushort[] raw = (&deviceID)[0 .. PCIDevice.sizeof / ushort.sizeof]; foreach (idx, ref word; raw) - word = pci.ReadData(bus, slot, 0, cast(ubyte)(idx * ushort.sizeof)); + word = pci.readData(bus, slot, 0, cast(ubyte)(idx * ushort.sizeof)); } align(1): @@ -42,67 +42,67 @@ static assert(PCIDevice.sizeof == 64); class PCI { public: this() { - devices.length = 16; - scanForDevices(); + _devices.length = 16; + _scanForDevices(); } - ushort ReadData(ubyte bus, ubyte slot, ubyte func, ubyte offset) { + ushort readData(ubyte bus, ubyte slot, ubyte func, ubyte offset) { uint address = cast(uint)((bus << 16) | (slot << 11) | (func << 8) | (offset & 0xfc) | (cast(uint)0x80000000)); - Out!uint(CONFIG_ADDRESS, address); - return cast(ushort)(In!uint(CONFIG_DATA) >> ((offset & 2) * 8)); + outp!uint(configAddress, address); + return cast(ushort)(inp!uint(configData) >> ((offset & 2) * 8)); } - PCIDevice* GetDevice(ushort deviceID, ushort vendorID) { - foreach (ref device; devices[0 .. deviceCount]) + PCIDevice* getDevice(ushort deviceID, ushort vendorID) { + foreach (ref device; _devices[0 .. _deviceCount]) if (device.deviceID == deviceID && device.vendorID == vendorID) return &device; return null; } private: - PCIDevice[] devices; - size_t deviceCount; - void scanForDevices() { + PCIDevice[] _devices; + size_t _deviceCount; + void _scanForDevices() { for (ubyte bus = 0; bus < 255; bus++) for (ubyte slot = 0; slot < 32; slot++) { - if (!deviceExist(bus, slot)) + if (!_deviceExist(bus, slot)) continue; - if ((ReadData(bus, slot, 0, 0x0C) & 0xFF) == 0xFF) + if ((readData(bus, slot, 0, 0x0C) & 0xFF) == 0xFF) continue; - if (deviceCount == devices.length) - devices.length += 16; + if (_deviceCount == _devices.length) + _devices.length += 16; - PCIDevice* device = &devices[deviceCount]; + PCIDevice* device = &_devices[_deviceCount]; *device = PCIDevice(this, bus, slot); - log.Info("Found device at ", cast(void*)bus, ":", cast(void*)slot); - log.Info("\tdeviceID: ", cast(void*)device.deviceID, " vendorID: ", cast(void*)device.vendorID, + log.info("Found device at ", cast(void*)bus, ":", cast(void*)slot); + log.info("\tdeviceID: ", cast(void*)device.deviceID, " vendorID: ", cast(void*)device.vendorID, " type: ", device.headerType & 0x7E, " mf?: ", !!device.headerType & 0x80); - scr.Writeln("Found device at ", cast(void*)bus, ":", cast(void*)slot); - scr.Writeln("\tdeviceID: ", cast(void*)device.deviceID, " vendorID: ", cast(void*)device.vendorID, + scr.writeln("Found device at ", cast(void*)bus, ":", cast(void*)slot); + scr.writeln("\tdeviceID: ", cast(void*)device.deviceID, " vendorID: ", cast(void*)device.vendorID, " type: ", device.headerType & 0x7E, " mf?: ", !!device.headerType & 0x80); - deviceCount++; + _deviceCount++; } } - ushort deviceExist(ubyte bus, ubyte slot, ubyte func = 0) { - return ReadData(bus, slot, func, 0) != ushort.max; + ushort _deviceExist(ubyte bus, ubyte slot, ubyte func = 0) { + return readData(bus, slot, func, 0) != ushort.max; } } -PCI GetPCI() { - import Data.Util : InplaceClass; +PCI getPCI() { + import data.util : inplaceClass; __gshared ubyte[__traits(classInstanceSize, PCI)] data; __gshared PCI pci; if (!pci) - pci = InplaceClass!PCI(data); + pci = inplaceClass!PCI(data); return pci; } diff --git a/kernel/src/hw/ps2/kbset.d b/kernel/src/hw/ps2/kbset.d index 1c1e5b6..338efef 100644 --- a/kernel/src/hw/ps2/kbset.d +++ b/kernel/src/hw/ps2/kbset.d @@ -1,40 +1,40 @@ -module HW.PS2.KBSet; +module hw.ps2.kbset; // Uses the HID Usage Table for Keyboards // 10. Table 12, http://www.usb.org/developers/hidpage/Hut1_12v2.pdf enum KeyCode : ubyte { - None, - ErrorRollover, - PostFail, - ErrorUndefined, + none, + errorRollover, + postFail, + errorUndefined, /* 0x04 / 4 */ - A, - B, - C, - D, - E, - F, - G, - H, - I, - J, - K, - L, - M, - N, - O, - P, - Q, - R, - S, - T, - U, - V, - W, - X, - Y, - Z, + a, + b, + c, + d, + e, + f, + g, + h, + i, + j, + k, + l, + m, + n, + o, + p, + q, + r, + s, + t, + u, + v, + w, + x, + y, + z, /* 0x1E / 30 */ _1, @@ -48,297 +48,297 @@ enum KeyCode : ubyte { _9, _0, - Return, - Escape, - Backspace, - Tab, - Space, - Minus, - Equals, - SquareOpen, - SquareClose, - Backslash, - NonUSHashTilde, - Semicolon, - Quote, - GraveTilde, - Comma, - Dot, - Slash, - CapsLock, - F1, - F2, - F3, - F4, - F5, - F6, - F7, - F8, - F9, - F10, - F11, - F12, - PrintScreen, - ScrollLock, - Pause, - Insert, - Home, - PageUp, - Delete, - End, - PageDown, - RightArrow, - LeftArrow, - DownArrow, - UpArrow, - - NumLock, - KPSlash, - KPStar, - KPMinus, - KPPlus, - KPReturn, - KP1, - KP2, - KP3, - KP4, - KP5, - KP6, - KP7, - KP8, - KP9, - KP0, - KPPeriod, - - NonUSBackslash, - Application, - Power, - KPEquals, - - F13, - F14, - F15, - F16, - F17, - F18, - F19, - F20, - F21, - F22, - F23, - F24, - Execute, - Help, - Menu, - Select, - Stop, - Again, - Undo, - Cut, - Copy, - Paste, - Find, - Mute, - VolumeUp, - VolumeDown, - LockingCaps, /* Physically toggles */ - LockingNum, - LockingScroll, - KPComma, - KPEqualSign, - International1, - International2, - International3, - International4, - International5, - International6, - International7, - International8, - International9, - - Lang1, - Lang2, - Lang3, - Lang4, - Lang5, - Lang6, - Lang7, - Lang8, - Lang9, - - AltErase, - SysReq, - Cancle, - Clear, - Prior, - Return2, - Separator, - Out, - Oper, - - LeftCtrl = 0xE0, - LeftShift, - LeftAlt, - LeftGUI, - RightCtrl, - RightShift, - RightAlt, - RightGUI, - - MaxValue = 0xFF + return_, + escape, + backspace, + tab, + space, + minus, + equals, + squareOpen, + squareClose, + backslash, + nonUsHashTilde, + semicolon, + quote, + graveTilde, + comma, + dot, + slash, + capsLock, + f1, + f2, + f3, + f4, + f5, + f6, + f7, + f8, + f9, + f10, + f11, + f12, + printScreen, + scrollLock, + pause, + insert, + home, + pageUp, + delete_, + end, + pageDown, + rightArrow, + leftArrow, + downArrow, + upArrow, + + numLock, + kpSlash, + kpStar, + kpMinus, + kpPlus, + kpReturn, + kp1, + kp2, + kp3, + kp4, + kp5, + kp6, + kp7, + kp8, + kp9, + kp0, + kpPeriod, + + nonUsBackslash, + application, + power, + kpEquals, + + f13, + f14, + f15, + f16, + f17, + f18, + f19, + f20, + f21, + f22, + f23, + f24, + execute, + help, + menu, + select, + stop, + again, + undo, + cut, + copy, + paste, + find, + mute, + volumeUp, + volumeDown, + lockingCaps, /* Physically toggles */ + lockingNum, + lockingScroll, + kpComma, + kpEqualSign, + international1, + international2, + international3, + international4, + international5, + international6, + international7, + international8, + international9, + + lang1, + lang2, + lang3, + lang4, + lang5, + lang6, + lang7, + lang8, + lang9, + + altErase, + sysReq, + cancle, + clear, + prior, + return2, + separator, + out_, + oper, + + leftCtrl = 0xE0, + leftShift, + leftAlt, + leftGui, + rightCtrl, + rightShift, + rightAlt, + rightGui, + + maxValue = 0xFF } -private alias PS2Layout = PS2LayoutEN_US; -private alias ShiftedCharTranslation = ShiftedCharTranslationEN_US; -private alias ShiftedEtcTranslation = ShiftedEtcTranslationEN_US; -private alias KeypadTranslation = KeypadTranslationEN_US; -private alias NormalTranslation = NormalTranslationEN_US; +private alias _ps2Layout = _ps2LayoutEN_US; +private alias _shiftedCharTranslation = _shiftedCharTranslationEN_US; +private alias _shiftedEtcTranslation = _shiftedEtcTranslationEN_US; +private alias _keypadTranslation = _keypadTranslationEN_US; +private alias _normalTranslation = _normalTranslationEN_US; -KeyCode FindKeycode(ushort id) { - return PS2Layout[id]; +KeyCode findKeycode(ushort id) { + return _ps2Layout[id]; } -dchar FindShiftedCharTranslate(KeyCode key) { - return ShiftedCharTranslation[key]; +dchar findShiftedCharTranslate(KeyCode key) { + return _shiftedCharTranslation[key]; } -dchar FindShiftedEtcTranslate(KeyCode key) { - return ShiftedEtcTranslation[key]; +dchar findShiftedEtcTranslate(KeyCode key) { + return _shiftedEtcTranslation[key]; } -dchar FindKeypadTranslate(KeyCode key) { - return KeypadTranslation[key]; +dchar findKeypadTranslate(KeyCode key) { + return _keypadTranslation[key]; } -dchar FindNormalTranslate(KeyCode key) { - return NormalTranslation[key]; +dchar findNormalTranslate(KeyCode key) { + return _normalTranslation[key]; } -enum E0Bit = 0x80; -enum E1Bit = 0x100; +enum e0Bit = 0x80; +enum e1Bit = 0x100; // dfmt off -private __gshared KeyCode[512] PS2LayoutEN_US = [ - 0x0e: KeyCode.GraveTilde, - 0x16: KeyCode._1, - 0x1e: KeyCode._2, - 0x26: KeyCode._3, - 0x25: KeyCode._4, - 0x2e: KeyCode._5, - 0x36: KeyCode._6, - 0x3d: KeyCode._7, - 0x3e: KeyCode._8, - 0x46: KeyCode._9, - 0x45: KeyCode._0, - 0x4e: KeyCode.Minus, - 0x55: KeyCode.Equals, - 0x66: KeyCode.Backspace, - - 0x0d: KeyCode.Tab, - 0x15: KeyCode.Q, - 0x1d: KeyCode.W, - 0x24: KeyCode.E, - 0x2d: KeyCode.R, - 0x2c: KeyCode.T, - 0x35: KeyCode.Y, - 0x3c: KeyCode.U, - 0x43: KeyCode.I, - 0x44: KeyCode.O, - 0x4d: KeyCode.P, - 0x54: KeyCode.SquareOpen, - 0x5b: KeyCode.SquareClose, - 0x5d: KeyCode.Backslash, - - 0x58: KeyCode.CapsLock, - 0x1c: KeyCode.A, - 0x1b: KeyCode.S, - 0x23: KeyCode.D, - 0x2b: KeyCode.F, - 0x34: KeyCode.G, - 0x33: KeyCode.H, - 0x3b: KeyCode.J, - 0x42: KeyCode.K, - 0x4b: KeyCode.L, - 0x4c: KeyCode.Semicolon, - 0x52: KeyCode.Quote, - 0x5a: KeyCode.Return, - - 0x12: KeyCode.LeftShift, - 0x1a: KeyCode.Z, - 0x22: KeyCode.X, - 0x21: KeyCode.C, - 0x2a: KeyCode.V, - 0x32: KeyCode.B, - 0x31: KeyCode.N, - 0x3a: KeyCode.M, - 0x41: KeyCode.Comma, - 0x49: KeyCode.Dot, - 0x4a: KeyCode.Slash, - 0x59: KeyCode.RightShift, - - 0x14: KeyCode.LeftCtrl, - 0x11: KeyCode.LeftAlt, - 0x29: KeyCode.Space, - E0Bit | 0x11: KeyCode.RightAlt, - E0Bit | 0x14: KeyCode.RightCtrl, - - E0Bit | 0x70: KeyCode.Insert, - E0Bit | 0x71: KeyCode.Delete, - E0Bit | 0x6c: KeyCode.Home, - E0Bit | 0x69: KeyCode.End, - E0Bit | 0x7d: KeyCode.PageUp, - E0Bit | 0x7a: KeyCode.PageDown, - - E0Bit | 0x6b: KeyCode.LeftArrow, - E0Bit | 0x75: KeyCode.UpArrow, - E0Bit | 0x72: KeyCode.DownArrow, - E0Bit | 0x74: KeyCode.RightArrow, - - 0x77: KeyCode.NumLock, - 0x6c: KeyCode.KP7, - 0x6b: KeyCode.KP4, - 0x69: KeyCode.KP1, - E0Bit | 0x4a: KeyCode.KPSlash, - 0x75: KeyCode.KP8, - 0x73: KeyCode.KP5, - 0x72: KeyCode.KP2, - 0x70: KeyCode.KP0, - 0x7c: KeyCode.KPStar, - 0x7d: KeyCode.KP9, - 0x74: KeyCode.KP6, - 0x7a: KeyCode.KP3, - 0x71: KeyCode.KPPeriod, - 0x7b: KeyCode.KPMinus, - 0x79: KeyCode.KPPlus, - E0Bit | 0x5a: KeyCode.KPReturn, - - 0x76: KeyCode.Escape, - 0x05: KeyCode.F1, - 0x06: KeyCode.F2, - 0x04: KeyCode.F3, - 0x0c: KeyCode.F4, - 0x03: KeyCode.F5, - 0x0b: KeyCode.F6, - 0x83: KeyCode.F7, - 0x0a: KeyCode.F8, - 0x01: KeyCode.F9, - 0x09: KeyCode.F10, - 0x78: KeyCode.F11, - 0x07: KeyCode.F12, - - E0Bit | 0x7c: KeyCode.PrintScreen, - 0x84: KeyCode.SysReq, - 0x7e: KeyCode.ScrollLock, - E1Bit | 0x77: KeyCode.Pause, - - E0Bit | 0x1f: KeyCode.LeftGUI, - E0Bit | 0x27: KeyCode.RightGUI, - E0Bit | 0x2f: KeyCode.Menu, +private __gshared KeyCode[512] _ps2LayoutEN_US = [ + 0x0e: KeyCode.graveTilde, + 0x16: KeyCode._1, + 0x1e: KeyCode._2, + 0x26: KeyCode._3, + 0x25: KeyCode._4, + 0x2e: KeyCode._5, + 0x36: KeyCode._6, + 0x3d: KeyCode._7, + 0x3e: KeyCode._8, + 0x46: KeyCode._9, + 0x45: KeyCode._0, + 0x4e: KeyCode.minus, + 0x55: KeyCode.equals, + 0x66: KeyCode.backspace, + + 0x0d: KeyCode.tab, + 0x15: KeyCode.q, + 0x1d: KeyCode.w, + 0x24: KeyCode.e, + 0x2d: KeyCode.r, + 0x2c: KeyCode.t, + 0x35: KeyCode.y, + 0x3c: KeyCode.u, + 0x43: KeyCode.i, + 0x44: KeyCode.o, + 0x4d: KeyCode.p, + 0x54: KeyCode.squareOpen, + 0x5b: KeyCode.squareClose, + 0x5d: KeyCode.backslash, + + 0x58: KeyCode.capsLock, + 0x1c: KeyCode.a, + 0x1b: KeyCode.s, + 0x23: KeyCode.d, + 0x2b: KeyCode.f, + 0x34: KeyCode.g, + 0x33: KeyCode.h, + 0x3b: KeyCode.j, + 0x42: KeyCode.k, + 0x4b: KeyCode.l, + 0x4c: KeyCode.semicolon, + 0x52: KeyCode.quote, + 0x5a: KeyCode.return_, + + 0x12: KeyCode.leftShift, + 0x1a: KeyCode.z, + 0x22: KeyCode.x, + 0x21: KeyCode.c, + 0x2a: KeyCode.v, + 0x32: KeyCode.b, + 0x31: KeyCode.n, + 0x3a: KeyCode.m, + 0x41: KeyCode.comma, + 0x49: KeyCode.dot, + 0x4a: KeyCode.slash, + 0x59: KeyCode.rightShift, + + 0x14: KeyCode.leftCtrl, + 0x11: KeyCode.leftAlt, + 0x29: KeyCode.space, + e0Bit | 0x11: KeyCode.rightAlt, + e0Bit | 0x14: KeyCode.rightCtrl, + + e0Bit | 0x70: KeyCode.insert, + e0Bit | 0x71: KeyCode.delete_, + e0Bit | 0x6c: KeyCode.home, + e0Bit | 0x69: KeyCode.end, + e0Bit | 0x7d: KeyCode.pageUp, + e0Bit | 0x7a: KeyCode.pageDown, + + e0Bit | 0x6b: KeyCode.leftArrow, + e0Bit | 0x75: KeyCode.upArrow, + e0Bit | 0x72: KeyCode.downArrow, + e0Bit | 0x74: KeyCode.rightArrow, + + 0x77: KeyCode.numLock, + 0x6c: KeyCode.kp7, + 0x6b: KeyCode.kp4, + 0x69: KeyCode.kp1, + e0Bit | 0x4a: KeyCode.kpSlash, + 0x75: KeyCode.kp8, + 0x73: KeyCode.kp5, + 0x72: KeyCode.kp2, + 0x70: KeyCode.kp0, + 0x7c: KeyCode.kpStar, + 0x7d: KeyCode.kp9, + 0x74: KeyCode.kp6, + 0x7a: KeyCode.kp3, + 0x71: KeyCode.kpPeriod, + 0x7b: KeyCode.kpMinus, + 0x79: KeyCode.kpPlus, + e0Bit | 0x5a: KeyCode.kpReturn, + + 0x76: KeyCode.escape, + 0x05: KeyCode.f1, + 0x06: KeyCode.f2, + 0x04: KeyCode.f3, + 0x0c: KeyCode.f4, + 0x03: KeyCode.f5, + 0x0b: KeyCode.f6, + 0x83: KeyCode.f7, + 0x0a: KeyCode.f8, + 0x01: KeyCode.f9, + 0x09: KeyCode.f10, + 0x78: KeyCode.f11, + 0x07: KeyCode.f12, + + e0Bit | 0x7c: KeyCode.printScreen, + 0x84: KeyCode.sysReq, + 0x7e: KeyCode.scrollLock, + e1Bit | 0x77: KeyCode.pause, + + e0Bit | 0x1f: KeyCode.leftGui, + e0Bit | 0x27: KeyCode.rightGui, + e0Bit | 0x2f: KeyCode.menu, ]; -private __gshared dchar[KeyCode.max] NormalTranslationEN_US = [ - KeyCode.Escape: 27, - KeyCode.GraveTilde: '`', +private __gshared dchar[KeyCode.max] _normalTranslationEN_US = [ + KeyCode.escape: 27, + KeyCode.graveTilde: '`', KeyCode._1: '1', KeyCode._2: '2', KeyCode._3: '3', @@ -349,69 +349,69 @@ private __gshared dchar[KeyCode.max] NormalTranslationEN_US = [ KeyCode._8: '8', KeyCode._9: '9', KeyCode._0: '0', - KeyCode.Minus: '-', - KeyCode.Equals: '=', - KeyCode.Backspace: '\b', - KeyCode.Tab: '\t', - KeyCode.Q: 'q', - KeyCode.W: 'w', - KeyCode.E: 'e', - KeyCode.R: 'r', - KeyCode.T: 't', - KeyCode.Y: 'y', - KeyCode.U: 'u', - KeyCode.I: 'i', - KeyCode.O: 'o', - KeyCode.P: 'p', - KeyCode.SquareOpen: '[', - KeyCode.SquareClose: ']', - KeyCode.Backslash: '\\', - KeyCode.A: 'a', - KeyCode.S: 's', - KeyCode.D: 'd', - KeyCode.F: 'f', - KeyCode.G: 'g', - KeyCode.H: 'h', - KeyCode.J: 'j', - KeyCode.K: 'k', - KeyCode.L: 'l', - KeyCode.Semicolon: ';', - KeyCode.Quote: '\'', - KeyCode.Return: '\n', - KeyCode.Z: 'z', - KeyCode.X: 'x', - KeyCode.C: 'c', - KeyCode.V: 'v', - KeyCode.B: 'b', - KeyCode.N: 'n', - KeyCode.M: 'm', - KeyCode.Comma: ',', - KeyCode.Dot: '.', - KeyCode.Slash: '/', - KeyCode.Space: ' ' + KeyCode.minus: '-', + KeyCode.equals: '=', + KeyCode.backspace: '\b', + KeyCode.tab: '\t', + KeyCode.q: 'q', + KeyCode.w: 'w', + KeyCode.e: 'e', + KeyCode.r: 'r', + KeyCode.t: 't', + KeyCode.y: 'y', + KeyCode.u: 'u', + KeyCode.i: 'i', + KeyCode.o: 'o', + KeyCode.p: 'p', + KeyCode.squareOpen: '[', + KeyCode.squareClose: ']', + KeyCode.backslash: '\\', + KeyCode.a: 'a', + KeyCode.s: 's', + KeyCode.d: 'd', + KeyCode.f: 'f', + KeyCode.g: 'g', + KeyCode.h: 'h', + KeyCode.j: 'j', + KeyCode.k: 'k', + KeyCode.l: 'l', + KeyCode.semicolon: ';', + KeyCode.quote: '\'', + KeyCode.return_: '\n', + KeyCode.z: 'z', + KeyCode.x: 'x', + KeyCode.c: 'c', + KeyCode.v: 'v', + KeyCode.b: 'b', + KeyCode.n: 'n', + KeyCode.m: 'm', + KeyCode.comma: ',', + KeyCode.dot: '.', + KeyCode.slash: '/', + KeyCode.space: ' ' ]; -private __gshared dchar[KeyCode.max] KeypadTranslationEN_US = [ - KeyCode.KP7: '7', - KeyCode.KP4: '4', - KeyCode.KP1: '1', - KeyCode.KP8: '8', - KeyCode.KP5: '5', - KeyCode.KP2: '2', - KeyCode.KP0: '0', - KeyCode.KP9: '9', - KeyCode.KP6: '6', - KeyCode.KP3: '3', - KeyCode.KPPeriod: ',', - KeyCode.KPSlash: '/', - KeyCode.KPStar: '*', - KeyCode.KPMinus: '-', - KeyCode.KPPlus: '+', - KeyCode.KPReturn: '\n' +private __gshared dchar[KeyCode.max] _keypadTranslationEN_US = [ + KeyCode.kp7: '7', + KeyCode.kp4: '4', + KeyCode.kp1: '1', + KeyCode.kp8: '8', + KeyCode.kp5: '5', + KeyCode.kp2: '2', + KeyCode.kp0: '0', + KeyCode.kp9: '9', + KeyCode.kp6: '6', + KeyCode.kp3: '3', + KeyCode.kpPeriod: ',', + KeyCode.kpSlash: '/', + KeyCode.kpStar: '*', + KeyCode.kpMinus: '-', + KeyCode.kpPlus: '+', + KeyCode.kpReturn: '\n' ]; -private __gshared dchar[KeyCode.max] ShiftedEtcTranslationEN_US = [ - KeyCode.GraveTilde: '~', +private __gshared dchar[KeyCode.max] _shiftedEtcTranslationEN_US = [ + KeyCode.graveTilde: '~', KeyCode._1: '!', KeyCode._2: '@', KeyCode._3: '#', @@ -422,44 +422,44 @@ private __gshared dchar[KeyCode.max] ShiftedEtcTranslationEN_US = [ KeyCode._8: '*', KeyCode._9: '(', KeyCode._0: ')', - KeyCode.Minus: '_', - KeyCode.Equals: '+', - KeyCode.SquareOpen: '{', - KeyCode.SquareClose: '}', - KeyCode.Backslash: '|', - KeyCode.Semicolon: ':', - KeyCode.Quote: '"', - KeyCode.Comma: '<', - KeyCode.Dot: '>', - KeyCode.Slash: '?', + KeyCode.minus: '_', + KeyCode.equals: '+', + KeyCode.squareOpen: '{', + KeyCode.squareClose: '}', + KeyCode.backslash: '|', + KeyCode.semicolon: ':', + KeyCode.quote: '"', + KeyCode.comma: '<', + KeyCode.dot: '>', + KeyCode.slash: '?', ]; -private __gshared dchar[KeyCode.max] ShiftedCharTranslationEN_US = [ - KeyCode.Q: 'Q', - KeyCode.W: 'W', - KeyCode.E: 'E', - KeyCode.R: 'R', - KeyCode.T: 'T', - KeyCode.Y: 'Y', - KeyCode.U: 'U', - KeyCode.I: 'I', - KeyCode.O: 'O', - KeyCode.P: 'P', - KeyCode.A: 'A', - KeyCode.S: 'S', - KeyCode.D: 'D', - KeyCode.F: 'F', - KeyCode.G: 'G', - KeyCode.H: 'H', - KeyCode.J: 'J', - KeyCode.K: 'K', - KeyCode.L: 'L', - KeyCode.Z: 'Z', - KeyCode.X: 'X', - KeyCode.C: 'C', - KeyCode.V: 'V', - KeyCode.B: 'B', - KeyCode.N: 'N', - KeyCode.M: 'M', +private __gshared dchar[KeyCode.max] _shiftedCharTranslationEN_US = [ + KeyCode.q: 'Q', + KeyCode.w: 'W', + KeyCode.e: 'E', + KeyCode.r: 'R', + KeyCode.t: 'T', + KeyCode.y: 'Y', + KeyCode.u: 'U', + KeyCode.i: 'I', + KeyCode.o: 'O', + KeyCode.p: 'P', + KeyCode.a: 'A', + KeyCode.s: 'S', + KeyCode.d: 'D', + KeyCode.f: 'F', + KeyCode.g: 'G', + KeyCode.h: 'H', + KeyCode.j: 'J', + KeyCode.k: 'K', + KeyCode.l: 'L', + KeyCode.z: 'Z', + KeyCode.x: 'X', + KeyCode.c: 'C', + KeyCode.v: 'V', + KeyCode.b: 'B', + KeyCode.n: 'N', + KeyCode.m: 'M', ]; // dfmt on diff --git a/kernel/src/hw/ps2/keyboard.d b/kernel/src/hw/ps2/keyboard.d index 079c0ce..420d20b 100644 --- a/kernel/src/hw/ps2/keyboard.d +++ b/kernel/src/hw/ps2/keyboard.d @@ -1,46 +1,45 @@ -module HW.PS2.Keyboard; +module hw.ps2.keyboard; -import CPU.IDT; -import Data.Register; -import Data.BitField; -import IO.Log; -import IO.Port; -import IO.Keyboard; -import HW.PS2.KBSet; +import cpu.idt; +import data.register; +import data.bitfield; +import io.log; +import io.port; +import hw.ps2.kbset; /// This is a class for controlling the 8042 PS/2 controller struct PS2Keyboard { public: - static void Init() { + static void init() { ubyte result; - IDT.Register(IRQ(1), &onIRQ); - IDT.Register(IRQ(2), &ignore); + IDT.register(irq(1), &_onIRQ); + IDT.register(irq(2), &_ignore); - sendCtlCmd(0xAD /* Disable port 1 */ ); - sendCtlCmd(0xA7 /* Disable port 2 */ ); + _sendCtlCmd(0xAD /* Disable port 1 */ ); + _sendCtlCmd(0xA7 /* Disable port 2 */ ); - while (getStatus.OutputFull) - get(false); - sendCtlCmd(0x20 /* Read configuration */ ); - result = get(); + while (_getStatus.OutputFull) + _get(false); + _sendCtlCmd(0x20 /* Read configuration */ ); + result = _get(); result &= ~0b100_0010; // Clear Translation bit (aka enable scancode set 2) and IRQ flags - sendCtlCmd(0x60 /* Write configuration */ ); - sendCmd(result); - sendCtlCmd(0xAE /* Enable port 1 */ ); - sendCmd(0xFF /* Reset */ ); + _sendCtlCmd(0x60 /* Write configuration */ ); + _sendCmd(result); + _sendCtlCmd(0xAE /* Enable port 1 */ ); + _sendCmd(0xFF /* Reset */ ); while (result != 0xAA) - result = get(); - setLED(); - enabled = true; + result = _get(); + _setLED(); + _enabled = true; } private: - struct keyboardStatus { - private ubyte value; + struct KeyboardStatus { + private ubyte _value; //dfmt off - mixin(Bitfield!(value, + mixin(bitfield!(_value, "OutputFull", 1, "InputFull", 1, "SelfTestSucceeded", 1, @@ -52,192 +51,192 @@ private: //dfmt on } - struct keyState { + struct KeyState { ulong[4] bitmaps; - private enum countPerInt = ulong.sizeof * 8; - private enum length = bitmaps.length * countPerInt; + private enum _countPerInt = ulong.sizeof * 8; + private enum _length = bitmaps.length * _countPerInt; - void Set(KeyCode key) { + void set(KeyCode key) { ubyte bit = cast(ubyte)key; - bitmaps[bit / countPerInt] |= 1 << (bit % countPerInt); + bitmaps[bit / _countPerInt] |= 1 << (bit % _countPerInt); } - bool IsSet(KeyCode key) { + bool isSet(KeyCode key) { ubyte bit = cast(ubyte)key; - return !!(bitmaps[bit / countPerInt] & 1 << (bit % countPerInt)); + return !!(bitmaps[bit / _countPerInt] & 1 << (bit % _countPerInt)); } - void Clear(KeyCode key) { + void clear(KeyCode key) { ubyte bit = cast(ubyte)key; - bitmaps[bit / countPerInt] &= ~(1 << (bit % countPerInt)); + bitmaps[bit / _countPerInt] &= ~(1 << (bit % _countPerInt)); } - void Toggle(KeyCode key) { - if (IsSet(key)) - Clear(key); + void toggle(KeyCode key) { + if (isSet(key)) + clear(key); else - Set(key); + set(key); } } - struct modifierState { - private ubyte data; + struct ModifierState { + private ubyte _data; - mixin(Bitfield!(data, "NumLock", 1, "CapsLock", 1, "ScrollLock", 1)); + mixin(bitfield!(_data, "numLock", 1, "capsLock", 1, "scrollLock", 1)); } - enum ushort DataPort = 0x60; - enum ushort ControllerPort = 0x64; // Read -> Status Register / Write -> Command Register + enum ushort _dataPort = 0x60; + enum ushort _controllerPort = 0x64; // Read -> Status Register / Write -> Command Register - __gshared bool enabled; - __gshared keyState state; - __gshared modifierState modifiers; + __gshared bool _enabled; + __gshared KeyState _state; + __gshared ModifierState _modifiers; - static KeyCode combineKeyData(ubyte ch) { + static KeyCode _combineKeyData(ubyte ch) { enum VBoxHack { // XXX: Fixed VBox scancode set 2 problems - None, - NumLock, - CapsLock, + none, + numLock, + capsLock, } - __gshared VBoxHack vboxHackState = VBoxHack.None; + __gshared VBoxHack vboxHackState = VBoxHack.none; __gshared bool nextUnpress = false; __gshared bool nextExtended = false; __gshared int nextSpecial = 0; - KeyCode key = KeyCode.None; + KeyCode key = KeyCode.none; if (ch == 0xF0) { nextUnpress = true; - return KeyCode.None; + return KeyCode.none; } else if (nextSpecial == 2) { nextSpecial--; // Should maybe save ch? - return KeyCode.None; + return KeyCode.none; } else if (ch == 0xE0) { nextExtended = true; - return KeyCode.None; + return KeyCode.none; } else if (ch == 0xE1) { nextSpecial = 2; - return KeyCode.None; + return KeyCode.none; } if (nextExtended) - key = FindKeycode(E0Bit | (ch & 0x7F)); + key = findKeycode(e0Bit | (ch & 0x7F)); else if (nextSpecial == 1) - key = FindKeycode(E1Bit | (ch & 0x7F)); + key = findKeycode(e1Bit | (ch & 0x7F)); else - key = FindKeycode(ch); + key = findKeycode(ch); if (nextUnpress) { - state.Clear(key); + _state.clear(key); - vboxHackState = VBoxHack.None; + vboxHackState = VBoxHack.none; nextUnpress = false; nextExtended = false; nextSpecial = 0; - return KeyCode.None; + return KeyCode.none; } - state.Set(key); - - if (key == KeyCode.CapsLock && vboxHackState != VBoxHack.CapsLock) { - modifiers.CapsLock = !modifiers.CapsLock; - setLED(); - vboxHackState = VBoxHack.CapsLock; - } else if (vboxHackState != VBoxHack.NumLock && key == KeyCode.NumLock) { - modifiers.NumLock = !modifiers.NumLock; - setLED(); - vboxHackState = VBoxHack.NumLock; - } else if (key == KeyCode.ScrollLock) { - modifiers.ScrollLock = !modifiers.ScrollLock; - setLED(); + _state.set(key); + + if (key == KeyCode.capsLock && vboxHackState != VBoxHack.capsLock) { + _modifiers.capsLock = !_modifiers.capsLock; + _setLED(); + vboxHackState = VBoxHack.capsLock; + } else if (vboxHackState != VBoxHack.numLock && key == KeyCode.numLock) { + _modifiers.numLock = !_modifiers.numLock; + _setLED(); + vboxHackState = VBoxHack.numLock; + } else if (key == KeyCode.scrollLock) { + _modifiers.scrollLock = !_modifiers.scrollLock; + _setLED(); } else - vboxHackState = VBoxHack.None; + vboxHackState = VBoxHack.none; return key; } - static void waitGet() { - while (!getStatus.OutputFull) { + static void _waitGet() { + while (!_getStatus.OutputFull) { } } - static void waitSend() { - while (getStatus.InputFull) { + static void _waitSend() { + while (_getStatus.InputFull) { } } - static ubyte get(bool wait = true) { + static ubyte _get(bool wait = true) { if (wait) - waitGet(); - return In!ubyte(DataPort); + _waitGet(); + return inp!ubyte(_dataPort); } - static keyboardStatus getStatus() { - return keyboardStatus(In!ubyte(ControllerPort)); + static KeyboardStatus _getStatus() { + return KeyboardStatus(inp!ubyte(_controllerPort)); } - static void sendCmd(ubyte cmd) { - waitSend(); - Out!ubyte(DataPort, cmd); + static void _sendCmd(ubyte cmd) { + _waitSend(); + outp!ubyte(_dataPort, cmd); } - static void sendCtlCmd(ubyte cmd) { - waitSend(); - Out!ubyte(ControllerPort, cmd); + static void _sendCtlCmd(ubyte cmd) { + _waitSend(); + outp!ubyte(_controllerPort, cmd); } - static void setLED() { - enabled = false; - sendCmd(0xED); - while (get() != 0xFA) { + static void _setLED() { + _enabled = false; + _sendCmd(0xED); + while (_get() != 0xFA) { } - sendCmd(modifiers.CapsLock << 2 | modifiers.NumLock << 1 | modifiers.ScrollLock); - while (get() != 0xFA) { + _sendCmd(_modifiers.capsLock << 2 | _modifiers.numLock << 1 | _modifiers.scrollLock); + while (_get() != 0xFA) { } - enabled = true; + _enabled = true; } - static void onIRQ(Registers* regs) { - import IO.ConsoleManager; + static void _onIRQ(Registers* regs) { + import io.consolemanager; - ubyte data = get(false); - if (!enabled) + ubyte data = _get(false); + if (!_enabled) return; //if (data == 0x00 || data == 0xAA || data == 0xEE || data == 0xFA || data == 0xFC || data == 0xFD || data == 0xFE || data == 0xFF) //acontinue; - KeyCode key = combineKeyData(data); - if (key != KeyCode.None) { + KeyCode key = _combineKeyData(data); + if (key != KeyCode.none) { dchar ch; - const bool shift = state.IsSet(KeyCode.LeftShift) || state.IsSet(KeyCode.RightShift); - const bool caps = modifiers.CapsLock; - const bool num = modifiers.NumLock; + const bool shift = _state.isSet(KeyCode.leftShift) || _state.isSet(KeyCode.rightShift); + const bool caps = _modifiers.capsLock; + const bool num = _modifiers.numLock; if (ch == dchar.init && caps != shift) - ch = FindShiftedCharTranslate(key); + ch = findShiftedCharTranslate(key); if (ch == dchar.init && shift) - ch = FindShiftedEtcTranslate(key); + ch = findShiftedEtcTranslate(key); if (ch == dchar.init && num) - ch = FindKeypadTranslate(key); + ch = findKeypadTranslate(key); if (ch == dchar.init) - ch = FindNormalTranslate(key); + ch = findNormalTranslate(key); if (ch != dchar.init) { - const bool ctrl = state.IsSet(KeyCode.LeftCtrl) || state.IsSet(KeyCode.RightCtrl); - const bool alt = state.IsSet(KeyCode.LeftAlt) || state.IsSet(KeyCode.RightAlt); - GetConsoleManager.AddKeyboardInput(ch, ctrl, alt, shift); + const bool ctrl = _state.isSet(KeyCode.leftCtrl) || _state.isSet(KeyCode.rightCtrl); + const bool alt = _state.isSet(KeyCode.leftAlt) || _state.isSet(KeyCode.rightAlt); + getConsoleManager.addKeyboardInput(ch, ctrl, alt, shift); //Keyboard.Push(ch); } } } - static void ignore(Registers*) { + static void _ignore(Registers*) { } } diff --git a/kernel/src/io/com.d b/kernel/src/io/com.d index b8c0458..6e517e1 100644 --- a/kernel/src/io/com.d +++ b/kernel/src/io/com.d @@ -1,61 +1,61 @@ -module IO.COM; +module io.com; -import IO.Port; -import CPU.IDT; -import Data.Register; +import io.port; +import cpu.idt; +import data.register; -ref COM COM1() { - return COMPorts[0]; +ref COM com1() { + return comPorts[0]; } -ref COM COM2() { - return COMPorts[1]; +ref COM com2() { + return comPorts[1]; } -ref COM COM3() { - return COMPorts[2]; +ref COM com3() { + return comPorts[2]; } -ref COM COM4() { - return COMPorts[3]; +ref COM com4() { + return comPorts[3]; } -__gshared COM[] COMPorts = [COM(0x3F8), COM(0x2F8), COM(0x3E8), COM(0x2E8)]; +__gshared COM[] comPorts = [COM(0x3F8), COM(0x2F8), COM(0x3E8), COM(0x2E8)]; enum Mode { - EightByteNoParityOneStopBit = 0x03, - DivisorLatch = 0x80, + eightByteNoParityOneStopBit = 0x03, + divisorLatch = 0x80, } enum PortNumber : ushort { - Transmit = 0, // w - Recieve = 0, // r - DivisorLow = 0, // rw latch - InterruptEnable = 1, // rw - DivisorHigh = 1, // rw latch - InterruptIdentifier = 2, // r - FIFOControl = 2, // w - LineControl = 3, // rw - ModemControl = 4, // rw - LineStatus = 5, // r - ModemStatus = 6, // r - Scratch = 7, // rw + transmit = 0, // w + recieve = 0, // r + divisorLow = 0, // rw latch + interruptEnable = 1, // rw + divisorHigh = 1, // rw latch + interruptIdentifier = 2, // r + fifoControl = 2, // w + lineControl = 3, // rw + modemControl = 4, // rw + lineStatus = 5, // r + modemStatus = 6, // r + scratch = 7, // rw } enum InterruptSettings : ubyte { - EnableTransmit = 1 << 1, - EnableRecieve = 1 << 0, + enableTransmit = 1 << 1, + enableRecieve = 1 << 0, } enum StatusInfo : ubyte { - Interrupt = 1 << 0, - Reason = 0b1110, - - ReasonStatus = 0b0110, - ReasonReceiver = 0b0100, - ReasonFIFO = 0b1100, - ReasonTransmission = 0b0010, - ReasonModem = 0b0000, + interrupt = 1 << 0, + reason = 0b1110, + + reasonStatus = 0b0110, + reasonReceiver = 0b0100, + reasonFifo = 0b1100, + reasonTransmission = 0b0010, + reasonModem = 0b0000, } struct COM { @@ -63,101 +63,102 @@ struct COM { char[0x1000] buf; ushort start, end; - static void Init() { - enum Divisor = 115200; - ushort speed = Divisor / 9600; + static void init() { + enum divisor = 115200; + ushort speed = divisor / 9600; - IDT.Register(IRQ(4), &handleIRQ4); - IDT.Register(IRQ(3), &handleIRQ3); + IDT.register(irq(4), &_handleIRQ4); + IDT.register(irq(3), &_handleIRQ3); - foreach (com; COMPorts) { - Out!ubyte(cast(ushort)(com.port + PortNumber.InterruptEnable), 0); + foreach (com; comPorts) { + outp!ubyte(cast(ushort)(com.port + PortNumber.interruptEnable), 0); - Out!ubyte(cast(ushort)(com.port + PortNumber.LineControl), Mode.DivisorLatch | Mode.EightByteNoParityOneStopBit); - Out!ubyte(cast(ushort)(com.port + PortNumber.DivisorHigh), cast(ubyte)(speed >> 8)); - Out!ubyte(cast(ushort)(com.port + PortNumber.DivisorLow), cast(ubyte)speed); + outp!ubyte(cast(ushort)(com.port + PortNumber.lineControl), Mode.divisorLatch | Mode.eightByteNoParityOneStopBit); + outp!ubyte(cast(ushort)(com.port + PortNumber.divisorHigh), cast(ubyte)(speed >> 8)); + outp!ubyte(cast(ushort)(com.port + PortNumber.divisorLow), cast(ubyte)speed); - Out!ubyte(cast(ushort)(com.port + PortNumber.LineControl), Mode.EightByteNoParityOneStopBit); + outp!ubyte(cast(ushort)(com.port + PortNumber.lineControl), Mode.eightByteNoParityOneStopBit); - Out!ubyte(cast(ushort)(com.port + PortNumber.FIFOControl), 0xC7); // Enable FIFO, clear them, with 14-byte threshold + outp!ubyte(cast(ushort)(com.port + PortNumber.fifoControl), 0xC7); // Enable FIFO, clear them, with 14-byte threshold - Out!ubyte(cast(ushort)(com.port + PortNumber.InterruptEnable), InterruptSettings.EnableRecieve); + outp!ubyte(cast(ushort)(com.port + PortNumber.interruptEnable), InterruptSettings.enableRecieve); } } - bool CanRead() { + bool canRead() { return (start != end); } - ubyte Read() { - while (!CanRead()) { //XXX: + ubyte read() { + while (!canRead()) { //XXX: } return buf[(++start % 0x1000)]; } - bool CanSend() { - return !!(In(cast(ushort)(port + 5)) & 0x20); + bool canSend() { + return !!(inp!ubyte(cast(ushort)(port + 5)) & 0x20); } - void Write(ubyte d) { - while (!CanSend()) { //XXX: fix deadlock + void write(ubyte d) { + while (!canSend()) { //XXX: fix deadlock } - Out!ubyte(cast(ushort)port, d); + outp!ubyte(cast(ushort)port, d); } - void Write(T : ubyte)(T[] data) { + void write(T : ubyte)(T[] data) { foreach (d; data) - Write(d); + write(d); } - void Write(Args...)(Args args) { + void write(Args...)(Args args) { foreach (arg; args) - Write(arg); + write(arg); } - static void handleIRQ3(Registers*) { - handleIRQ!COM2(); - handleIRQ!COM4(); +private: + static void _handleIRQ3(Registers*) { + _handleIRQ!com2(); + _handleIRQ!com4(); } - static void handleIRQ4(Registers*) { - handleIRQ!COM1(); - handleIRQ!COM3(); + static void _handleIRQ4(Registers*) { + _handleIRQ!com1(); + _handleIRQ!com3(); } - static void handleIRQ(alias com)() { - import Data.TextBuffer : scr = GetBootTTY; - import Data.Util : BinaryInt; + static void _handleIRQ(alias com)() { + import data.textbuffer : scr = getBootTTY; + import data.util : BinaryInt; - StatusInfo status = cast(StatusInfo)In!ubyte(cast(ushort)(com.port + PortNumber.InterruptIdentifier)); - while (!(status & StatusInfo.Interrupt)) { - status &= StatusInfo.Reason; + StatusInfo status = cast(StatusInfo)inp!ubyte(cast(ushort)(com.port + PortNumber.interruptIdentifier)); + while (!(status & StatusInfo.interrupt)) { + status &= StatusInfo.reason; switch (status) with (StatusInfo) { - case ReasonStatus: - ubyte line = In(cast(ushort)(com.port + PortNumber.LineStatus)); + case reasonStatus: + ubyte line = inp!ubyte(cast(ushort)(com.port + PortNumber.lineStatus)); //TODO: Check line status? break; - case ReasonReceiver: - case ReasonFIFO: //TODO: Check if ReasonFIFO should be it's own case - while (In(cast(ushort)(com.port + PortNumber.LineStatus)) & 0x1) { - ubyte tmp = In(com.port); + case reasonReceiver: + case reasonFifo: //TODO: Check if ReasonFIFO should be it's own case + while (inp!ubyte(cast(ushort)(com.port + PortNumber.lineStatus)) & 0x1) { + ubyte tmp = inp!ubyte(com.port); //scr.Writeln("Char: ", tmp); if ((com.end + 1 % 0x1000) != com.start) com.buf[(++com.end % 0x1000)] = tmp; } break; - case ReasonTransmission: - //TODO: Transmit stuff here + case reasonTransmission: + //TODO: transmit stuff here break; - case ReasonModem: - ubyte modem = In(cast(ushort)(com.port + PortNumber.ModemStatus)); + case reasonModem: + ubyte modem = inp!ubyte(cast(ushort)(com.port + PortNumber.modemStatus)); //TODO: Check modem status? break; default: // Will never happen! assert(0); break; } - status = cast(StatusInfo)In!ubyte(cast(ushort)(com.port + PortNumber.InterruptIdentifier)); + status = cast(StatusInfo)inp!ubyte(cast(ushort)(com.port + PortNumber.interruptIdentifier)); } } } diff --git a/kernel/src/io/consolemanager.d b/kernel/src/io/consolemanager.d index dff6c0a..738ba36 100644 --- a/kernel/src/io/consolemanager.d +++ b/kernel/src/io/consolemanager.d @@ -1,60 +1,60 @@ -module IO.ConsoleManager; +module io.consolemanager; -import IO.FS.IO.Console; +import io.fs.io.console; class ConsoleManager { public: - void Init() { - import KMain : rootFS; - import IO.FS; - import IO.Log; + void init() { + import kmain : rootFS; + import io.fs; + import io.log; - DirectoryNode csDir = cast(DirectoryNode)rootFS.Root.FindNode("/IO/Console"); + DirectoryNode csDir = cast(DirectoryNode)rootFS.root.findNode("/io/console"); if (!csDir) - log.Error("/IO/Console/ missing"); + log.error("/io/console/ missing"); - auto nodes = csDir.Nodes; - vcs = new VirtualConsole[4]; //XXX: + auto nodes = csDir.nodes; + _vcs = new VirtualConsole[4]; //XXX: size_t idx = 0; foreach (node; nodes) { if (auto _ = cast(VirtualConsole)node) - vcs[idx++] = _; + _vcs[idx++] = _; } - vcs[active].Active = true; + _vcs[_active].active = true; } - void AddKeyboardInput(dchar ch, bool ctrl, bool alt, bool shift) { - if (!vcs.length) + void addKeyboardInput(dchar ch, bool ctrl, bool alt, bool shift) { + if (!_vcs.length) return; if ((ch >= '1' || ch <= '9') && alt) { size_t want = ch - '1'; - if (want < vcs.length && want != active) { - vcs[active].Active = false; - active = want; - vcs[active].Active = true; + if (want < _vcs.length && want != _active) { + _vcs[_active].active = false; + _active = want; + _vcs[_active].active = true; } } else - vcs[active].AddKeyboardInput(ch); + _vcs[_active].addKeyboardInput(ch); } - @property VirtualConsole[] VirtualConsoles() { - return vcs; + @property VirtualConsole[] virtualConsoles() { + return _vcs; } private: - size_t active; - VirtualConsole[] vcs; + size_t _active; + VirtualConsole[] _vcs; } -ConsoleManager GetConsoleManager() { - import Data.Util : InplaceClass; +ConsoleManager getConsoleManager() { + import data.util : inplaceClass; __gshared ubyte[__traits(classInstanceSize, ConsoleManager)] data; __gshared ConsoleManager cm; if (!cm) - cm = InplaceClass!ConsoleManager(data); + cm = inplaceClass!ConsoleManager(data); return cm; } diff --git a/kernel/src/io/fs/directorynode.d b/kernel/src/io/fs/directorynode.d index 8e2f6eb..e350ae6 100644 --- a/kernel/src/io/fs/directorynode.d +++ b/kernel/src/io/fs/directorynode.d @@ -1,7 +1,7 @@ -module IO.FS.DirectoryNode; +module io.fs.directorynode; -import IO.FS; -import IO.Log; +import io.fs; +import io.log; class DirectoryNode : Node { public: @@ -9,73 +9,72 @@ public: super(permission); } - Node FindNode(string path) { - return FindNode(path, true); + Node findNode(string path) { + return findNode(path, true); } - MountPointNode Mount(DirectoryNode node, FSRoot fs) { - if (node.Parent != this) { - log.Error("Tried to run Mount on ", node.Name, " but it doesn't belong to ", name, "! Redirecting"); - node.Parent.Mount(node, fs); + MountPointNode mount(DirectoryNode node, FSRoot fs) { + if (node.parent != this) { + log.error("Tried to run Mount on ", node.name, " but it doesn't belong to ", name, "! Redirecting"); + node.parent.mount(node, fs); } MountPointNode mount = new MountPointNode(node, fs); - node.Parent = null; - node.Root = null; - mount.Root = root; - mount.Parent = this; - mount.RootMount.Parent = this; + node.parent = null; + node.root = null; + mount.root = _root; + mount.parent = this; + mount.rootMount.parent = this; return mount; } - DirectoryNode Unmount(MountPointNode node) { - if (node.Parent != this) { - log.Error("Tried to run Unmount on ", node.Name, " but it doesn't belong to ", name, "! Redirecting"); - node.Parent.Unmount(node); + DirectoryNode unmount(MountPointNode node) { + if (node.parent != this) { + log.error("Tried to run Unmount on ", node.name, " but it doesn't belong to ", name, "! Redirecting"); + node.parent.unmount(node); } - node.RootMount.Parent = null; - node.Parent = null; - node.Root = null; - DirectoryNode dir = node.OldNode; - dir.root = root; - dir.Parent = this; + node.rootMount.parent = null; + node.parent = null; + node.root = null; + DirectoryNode dir = node.oldNode; + dir.root = _root; + dir.parent = this; node.destroy; return dir; } - @property Node[] Nodes() { - return nodes[0 .. nodeCount]; + @property Node[] nodes() { + return _nodes[0 .. _nodeCount]; } - DirectoryNode SetParentNoUpdate(DirectoryNode node) { + DirectoryNode setParentNoUpdate(DirectoryNode node) { if (!node) - parent = oldParent; + _parent = _oldParent; else { - oldParent = parent; - parent = node; + _oldParent = _parent; + _parent = node; } - return parent; + return _parent; } package: - - Node Add(Node node) { - return add(node); + Node add(Node node) { + return _add(node); } - Node Remove(Node node) { - return remove(node); + Node remove(Node node) { + return _remove(node); } - Node FindNode(string path, bool firstTime) { - import KMain : rootFS; + Node findNode(string path, bool firstTime) { + import kmain : rootFS; - log.Info("CUR: ", Name, " FindNode: ", path, " firstTime: ", firstTime); + log.info("CUR: ", name, " FindNode: ", path, " firstTime: ", firstTime); if (!path.length) return this; if (path[0] == '/') { if (firstTime) - return rootFS.Root.FindNode(path[1 .. $], false); //root.Root.FindNode(path[1 .. $], false); + return rootFS.root.findNode(path[1 .. $], false); //root.root.findNode(path[1 .. $], false); while (path.length && path[0] == '/') path = path[1 .. $]; @@ -86,8 +85,8 @@ package: if (path.length > 1 && path[0 .. 2] == "..") { DirectoryNode p = parent; if (!p) - p = root.Root; - return p.FindNode(path[2 .. $], false); + p = root.root; + return p.findNode(path[2 .. $], false); } else if (path.length > 1 && path[0 .. 2] == "./") path = path[2 .. $]; @@ -99,15 +98,15 @@ package: while (end < path.length && path[end] != '/') end++; - foreach (node; nodes[0 .. nodeCount]) { - log.Info("\t cur Name: ", node.Name); - if (node.Name == path[0 .. end]) { + foreach (node; _nodes[0 .. _nodeCount]) { + log.info("\t cur Name: ", node.name); + if (node.name == path[0 .. end]) { auto n = node; while (true) { if (auto hardlink = cast(HardLinkNode)n) - n = hardlink.Target; + n = hardlink.target; else if (auto softlink = cast(SoftLinkNode)n) - n = softlink.Target; + n = softlink.target; else break; } @@ -116,9 +115,9 @@ package: return n; if (auto mp = cast(MountPointNode)node) - return mp.RootMount.Root.FindNode(path[end + 1 .. $], false); + return mp.rootMount.root.findNode(path[end + 1 .. $], false); if (auto dir = cast(DirectoryNode)node) - return dir.FindNode(path[end + 1 .. $], false); + return dir.findNode(path[end + 1 .. $], false); return null; } @@ -128,37 +127,37 @@ package: } protected: - DirectoryNode oldParent; - Node[] nodes; - ulong nodeCount; + DirectoryNode _oldParent; + Node[] _nodes; + ulong _nodeCount; - Node add(Node node) { - if (node.Parent == this) + Node _add(Node node) { + if (node.parent == this) return node; - log.Info("DirectoryNode ", ID, " Add: ", node.ID, "(", cast(void*)node, ")"); - if (nodes.length == nodeCount) { - nodes.length += 8; - for (ulong i = nodeCount; i < nodes.length; i++) - nodes[i] = null; + log.info("DirectoryNode ", id, " Add: ", node.id, "(", cast(void*)node, ")"); + if (_nodes.length == _nodeCount) { + _nodes.length += 8; + for (ulong i = _nodeCount; i < _nodes.length; i++) + _nodes[i] = null; } - nodes[nodeCount++] = node; + _nodes[_nodeCount++] = node; return node; } - Node remove(Node node) { - if (node.Parent != this) + Node _remove(Node node) { + if (node.parent != this) return node; - log.Info("DirectoryNode ", ID, " Remove: ", node.ID, "(", cast(void*)node, ")"); + log.info("DirectoryNode ", id, " Remove: ", node.id, "(", cast(void*)node, ")"); ulong i = 0; - while (i < nodeCount && nodes[i] != node) + while (i < _nodeCount && _nodes[i] != node) i++; - if (i >= nodeCount) + if (i >= _nodeCount) return node; - for (; i < nodeCount; i++) - nodes[i] = nodes[i + 1]; - nodeCount--; + for (; i < _nodeCount; i++) + _nodes[i] = _nodes[i + 1]; + _nodeCount--; return node; } } diff --git a/kernel/src/io/fs/filenode.d b/kernel/src/io/fs/filenode.d index cdddc6e..285ec49 100644 --- a/kernel/src/io/fs/filenode.d +++ b/kernel/src/io/fs/filenode.d @@ -1,46 +1,54 @@ -module IO.FS.FileNode; +module io.fs.filenode; -import IO.FS; -import IO.Log; +import io.fs; +import io.log; abstract class FileNode : Node { public: this(NodePermissions permission, ulong size) { super(permission); - this.size = size; + _size = size; } - abstract bool Open(); - abstract void Close(); - abstract ulong Read(ubyte[] buffer, ulong offset); - abstract ulong Write(ubyte[] buffer, ulong offset); + abstract bool open(); + abstract void close(); + abstract ulong read(ubyte[] buffer, ulong offset); + abstract ulong write(ubyte[] buffer, ulong offset); - ulong Read(T)(T[] arr, ulong offset) { - ulong result = Read((cast(ubyte*)arr.ptr)[0 .. T.sizeof * arr.length], offset); + ulong read(T)(T[] arr, ulong offset) { + ulong result = read((cast(ubyte*)arr.ptr)[0 .. T.sizeof * arr.length], offset); return result; } - ulong Write(T)(T[] obj, ulong offset) { - ulong result = Write((cast(ubyte*)arr.ptr)[0 .. T.sizeof * arr.length], offset); + ulong write(T)(T[] obj, ulong offset) { + ulong result = write((cast(ubyte*)arr.ptr)[0 .. T.sizeof * arr.length], offset); return result; } - ulong Read(T)(T* obj, ulong offset) { - ulong result = Read((cast(ubyte*)obj)[0 .. T.sizeof], offset); + ulong read(T)(T* obj, ulong offset) { + ulong result = read((cast(ubyte*)obj)[0 .. T.sizeof], offset); assert(result == T.sizeof); return result; } - ulong Write(T)(T* obj, ulong offset) { - ulong result = Write((cast(ubyte*)obj)[0 .. T.sizeof], offset); + ulong write(T)(T* obj, ulong offset) { + ulong result = write((cast(ubyte*)obj)[0 .. T.sizeof], offset); assert(result == T.sizeof); return result; } - @property ulong Size() { - return size; + ulong read(T)(ref T obj, ulong offset) { + return read(&obj, offset); + } + + ulong write(T)(ref T obj, ulong offset) { + return write(&obj, offset); + } + + @property ulong size() { + return _size; } private: - ulong size; + ulong _size; } diff --git a/kernel/src/io/fs/fsroot.d b/kernel/src/io/fs/fsroot.d index a9aadce..78aae05 100644 --- a/kernel/src/io/fs/fsroot.d +++ b/kernel/src/io/fs/fsroot.d @@ -1,80 +1,80 @@ -module IO.FS.FSRoot; -import IO.FS; -import IO.Log; +module io.fs.fsroot; +import io.fs; +import io.log; abstract class FSRoot { public: this(DirectoryNode root) { - this.root = root; - root.Root = this; + _root = root; + _root.root = this; } - Node[] Nodes() { - return nodes[0 .. nodeCount]; + Node[] nodes() { + return _nodes[0 .. _nodeCount]; } - Node GetNode(ulong id) { - foreach (node; nodes[0 .. nodeCount]) - if (node.ID == id) + Node getNode(ulong id) { + foreach (node; _nodes[0 .. _nodeCount]) + if (node.id == id) return node; return null; } - @property ref DirectoryNode Root() { - return root; + @property ref DirectoryNode root() { + return _root; } - @property DirectoryNode Parent() { - return root.Parent; + @property DirectoryNode parent() { + return _root.parent; } - @property DirectoryNode Parent(DirectoryNode parent) { - return root.SetParentNoUpdate(parent); + @property DirectoryNode parent(DirectoryNode parent) { + return _root.setParentNoUpdate(parent); } package: - Node Add(Node node) { - if (node.Root == this) + Node add(Node node) { + if (node.root == this) return node; - if (nodes.length == nodeCount) - nodes.length += 8; + if (_nodes.length == _nodeCount) + _nodes.length += 8; - nodes[nodeCount++] = node; - node.ID = idCounter++; - log.Info("FSRoot Add: ", node.ID, "(", cast(void*)node, ")"); + _nodes[_nodeCount++] = node; + node.id = _idCounter++; + log.info("FSRoot Add: ", node.id, "(", cast(void*)node, ")"); return node; } - Node Remove(Node node) { - if (node.Root != this) + Node remove(Node node) { + if (node.root != this) return node; - log.Info("FSRoot Remove: ", node.ID, "(", cast(void*)node, ")"); + log.info("FSRoot Remove: ", node.id, "(", cast(void*)node, ")"); ulong i = 0; - while (i < nodeCount && nodes[i] != node) + while (i < _nodeCount && _nodes[i] != node) i++; - if (i >= nodeCount) + if (i >= _nodeCount) return node; - for (; i < nodeCount - 1; i++) - nodes[i] = nodes[i + 1]; - nodeCount--; + for (; i < _nodeCount - 1; i++) + _nodes[i] = _nodes[i + 1]; + _nodeCount--; return node; } protected: - DirectoryNode root; - Node[] nodes; - ulong nodeCount; - ulong idCounter; + DirectoryNode _root; + Node[] _nodes; + ulong _nodeCount; + ulong _idCounter; DirectoryNode getOrAdd(DirectoryNode cur, string dir) { - if (auto node = cur.FindNode(dir)) + if (auto node = cur.findNode(dir)) return cast(DirectoryNode)node; - auto node = new DirectoryNode(NodePermissions.DefaultPermissions); - node.Name = dir; - node.Root = this; - node.Parent = cur; + auto node = new DirectoryNode(NodePermissions.defaultPermissions); + node.name = dir; + node.root = this; + node.parent = cur; return node; } @@ -83,7 +83,7 @@ protected: return null; ulong start = 1; ulong end = 1; - DirectoryNode parent = Root; + DirectoryNode parent = root; while (end < path.length) { while (end < path.length && path[end] != '/') end++; @@ -98,9 +98,9 @@ protected: end++; } - node.Name = path[start .. $]; - node.Root = this; - node.Parent = parent; + node.name = path[start .. $]; + node.root = this; + node.parent = parent; return node; } } diff --git a/kernel/src/io/fs/hardlinknode.d b/kernel/src/io/fs/hardlinknode.d index 2d37514..22bb4b6 100644 --- a/kernel/src/io/fs/hardlinknode.d +++ b/kernel/src/io/fs/hardlinknode.d @@ -1,31 +1,31 @@ -module IO.FS.HardLinkNode; +module io.fs.hardlinknode; -import IO.FS; +import io.fs; class HardLinkNode : Node { public: this(NodePermissions permission, ulong target) { super(permission); - this.target = target; + _target = target; } - @property ref ulong TargetID() { - return target; + @property ref ulong targetID() { + return _target; } - @property Node Target() { - return root.GetNode(target); + @property Node target() { + return root.getNode(_target); } - @property Node Target(Node node) { + @property Node target(Node node) { if (node) - target = node.ID; + _target = node.id; else - target = ulong.max; + _target = ulong.max; return node; } private: - ulong target; + ulong _target; } diff --git a/kernel/src/io/fs/initrd/filenode.d b/kernel/src/io/fs/initrd/filenode.d index c0eade6..409460b 100644 --- a/kernel/src/io/fs/initrd/filenode.d +++ b/kernel/src/io/fs/initrd/filenode.d @@ -1,47 +1,47 @@ -module IO.FS.Initrd.FileNode; +module io.fs.initrd.filenode; -import IO.FS.Initrd; -import IO.FS; +import io.fs.initrd; +import io.fs; final class InitrdFileNode : FileNode { public: this(ubyte* offset, ulong size) { - this.root = root; - this.data = offset[0 .. size]; - super(NodePermissions.DefaultPermissions, size); + root = root; + _data = offset[0 .. size]; + super(NodePermissions.defaultPermissions, size); } - override ulong Read(ubyte[] buffer, ulong offset) { - if (offset >= data.length) + override ulong read(ubyte[] buffer, ulong offset) { + if (offset >= _data.length) return 0; ulong size = buffer.length; ulong end = size + offset; - if (end > data.length) { - end = data.length; + if (end > _data.length) { + end = _data.length; long tmp = end - offset; size = (tmp < 0) ? 0 : tmp; } - memcpy(buffer.ptr, &data[offset], size); + memcpy(buffer.ptr, &_data[offset], size); return size; } - override ulong Write(ubyte[] buffer, ulong offset) { + override ulong write(ubyte[] buffer, ulong offset) { return -1; } - override bool Open() { + override bool open() { return true; } - override void Close() { + override void close() { } - @property ubyte[] RawAccess() { - return data; + @property ubyte[] rawAccess() { + return _data; } private: - ubyte[] data; + ubyte[] _data; } diff --git a/kernel/src/io/fs/initrd/fsroot.d b/kernel/src/io/fs/initrd/fsroot.d index ed2a302..c8e2410 100644 --- a/kernel/src/io/fs/initrd/fsroot.d +++ b/kernel/src/io/fs/initrd/fsroot.d @@ -1,42 +1,42 @@ -module IO.FS.Initrd.FSRoot; +module io.fs.initrd.fsroot; -import IO.FS.Initrd; -import IO.FS; -import IO.Log; +import io.fs.initrd; +import io.fs; +import io.log; -import Data.Address; -import Data.String; +import data.address; +import data.string_; class InitrdFSRoot : FSRoot { public: this(VirtAddress initrdAddr) { - auto root = new DirectoryNode(NodePermissions.DefaultPermissions); - root.Name = "Initrd"; - root.ID = idCounter++; + auto root = new DirectoryNode(NodePermissions.defaultPermissions); + root.name = "Initrd"; + root.id = _idCounter++; super(root); - initrd = cast(Initrd*)initrdAddr.Ptr; - if (initrd.Magic != MAGIC) + _initrd = cast(Initrd*)initrdAddr.ptr; + if (_initrd.magic != _magic) return; - initrdEntries = (initrdAddr + Initrd.sizeof).Ptr!InitrdEntry[0 .. initrd.Count]; + _initrdEntries = (initrdAddr + Initrd.sizeof).ptr!InitrdEntry[0 .. _initrd.count]; makeNodes(); } - @property InitrdEntry[] InitrdEntries() { - return initrdEntries; + @property InitrdEntry[] initrdEntries() { + return _initrdEntries; } private: - enum MAGIC = ['D', 'S', 'K', '0']; + enum _magic = ['D', 'S', 'K', '0']; enum Type : ulong { - File, - Folder + file, + folder } struct Initrd { align(1): - char[4] Magic; - ulong Count; + char[4] magic; + ulong count; } struct InitrdEntry { @@ -48,31 +48,31 @@ private: ulong parent; } - Initrd* initrd; - InitrdEntry[] initrdEntries; + Initrd* _initrd; + InitrdEntry[] _initrdEntries; void makeNodes() { ulong[] lookup; - lookup.length = initrdEntries.length; - foreach (idx, entry; initrdEntries) { - ubyte* offset = (VirtAddress(initrd) + entry.offset).Ptr!ubyte; + lookup.length = _initrdEntries.length; + foreach (idx, entry; _initrdEntries) { + ubyte* offset = (VirtAddress(_initrd) + entry.offset).ptr!ubyte; - auto parent = entry.parent == ulong.max ? root : cast(DirectoryNode)GetNode(lookup[entry.parent]); + auto parent = entry.parent == ulong.max ? root : cast(DirectoryNode)getNode(lookup[entry.parent]); Node node; - if (entry.type == Type.File) + if (entry.type == Type.file) node = new InitrdFileNode(offset, entry.size); - else if (entry.type == Type.Folder) - node = new DirectoryNode(NodePermissions.DefaultPermissions); + else if (entry.type == Type.folder) + node = new DirectoryNode(NodePermissions.defaultPermissions); else { - log.Error("Unknown file type! ", entry.type); + log.error("Unknown file type! ", entry.type); continue; } - node.Name = entry.name.fromStringz().dup; - node.Root = this; - node.Parent = parent; - lookup[idx] = node.ID; + node.name = entry.name.fromStringz().dup; + node.root = this; + node.parent = parent; + lookup[idx] = node.id; } lookup.destroy; } diff --git a/kernel/src/io/fs/initrd/package.d b/kernel/src/io/fs/initrd/package.d index 240a560..15071d0 100644 --- a/kernel/src/io/fs/initrd/package.d +++ b/kernel/src/io/fs/initrd/package.d @@ -1,6 +1,6 @@ -module IO.FS.Initrd; +module io.fs.initrd; public { - import IO.FS.Initrd.FSRoot; - import IO.FS.Initrd.FileNode; + import io.fs.initrd.fsroot; + import io.fs.initrd.filenode; } diff --git a/kernel/src/io/fs/io/boolnode.d b/kernel/src/io/fs/io/boolnode.d index 9083f4b..3340b3b 100644 --- a/kernel/src/io/fs/io/boolnode.d +++ b/kernel/src/io/fs/io/boolnode.d @@ -1,33 +1,33 @@ -module IO.FS.IO.BoolNode; +module io.fs.io.boolnode; -import IO.FS; -import IO.FS.IO; +import io.fs; +import io.fs.io; class BoolNode : FileNode { public: this(bool val) { - super(NodePermissions.DefaultPermissions, 0); - this.val = val; + super(NodePermissions.defaultPermissions, 0); + this._val = _val; } - override ulong Read(ubyte[] buffer, ulong offset) { + override ulong read(ubyte[] buffer, ulong offset) { if (buffer.length == 0) return 0; - buffer[1] = val; + buffer[1] = _val; return 1; } - override ulong Write(ubyte[] buffer, ulong offset) { + override ulong write(ubyte[] buffer, ulong offset) { return -1; } - override bool Open() { + override bool open() { return true; } - override void Close() { + override void close() { } private: - bool val; + bool _val; } diff --git a/kernel/src/io/fs/io/console/console.d b/kernel/src/io/fs/io/console/console.d index cb7d5c5..447da79 100644 --- a/kernel/src/io/fs/io/console/console.d +++ b/kernel/src/io/fs/io/console/console.d @@ -1,11 +1,11 @@ -module IO.FS.IO.Console.Console; +module io.fs.io.console.console; -import IO.FS; -import IO.FS.IO.Console; +import io.fs; +import io.fs.io.console; abstract class Console : FileNode { public: this() { - super(NodePermissions.DefaultPermissions, 0); + super(NodePermissions.defaultPermissions, 0); } } diff --git a/kernel/src/io/fs/io/console/package.d b/kernel/src/io/fs/io/console/package.d index 53c39e9..13044b9 100644 --- a/kernel/src/io/fs/io/console/package.d +++ b/kernel/src/io/fs/io/console/package.d @@ -1,8 +1,8 @@ -module IO.FS.IO.Console; +module io.fs.io.console; public { - import IO.FS.IO.Console.Console; - import IO.FS.IO.Console.SerialConsole; - import IO.FS.IO.Console.VirtualConsole; - import IO.FS.IO.Console.Screen; + import io.fs.io.console.console; + import io.fs.io.console.serialconsole; + import io.fs.io.console.virtualconsole; + import io.fs.io.console.screen; } diff --git a/kernel/src/io/fs/io/console/screen/formattedchar.d b/kernel/src/io/fs/io/console/screen/formattedchar.d index d3be697..aa1e954 100644 --- a/kernel/src/io/fs/io/console/screen/formattedchar.d +++ b/kernel/src/io/fs/io/console/screen/formattedchar.d @@ -1,13 +1,13 @@ -module IO.FS.IO.Console.Screen.FormattedChar; +module io.fs.io.console.screen.formattedchar; -import Data.Color; +import data.color; enum CharStyle { - None, - Bold = 1 << 0, - Underline = 1 << 1, - Italic = 1 << 2, - Strikethru = 1 << 3 + none, + bold = 1 << 0, + underline = 1 << 1, + italic = 1 << 2, + strikethru = 1 << 3 } struct FormattedChar { diff --git a/kernel/src/io/fs/io/console/screen/package.d b/kernel/src/io/fs/io/console/screen/package.d index 0bc7dea..07af965 100644 --- a/kernel/src/io/fs/io/console/screen/package.d +++ b/kernel/src/io/fs/io/console/screen/package.d @@ -1,8 +1,8 @@ -module IO.FS.IO.Console.Screen; +module io.fs.io.console.screen; public { - import IO.FS.IO.Console.Screen.VirtualConsoleScreen; - import IO.FS.IO.Console.Screen.FormattedChar; - import IO.FS.IO.Console.Screen.VirtualConsoleScreenTextMode; - import IO.FS.IO.Console.Screen.VirtualConsoleScreenFramebuffer; + import io.fs.io.console.screen.virtualconsolescreen; + import io.fs.io.console.screen.formattedchar; + import io.fs.io.console.screen.virtualconsolescreentextmode; + import io.fs.io.console.screen.virtualconsolescreenframebuffer; } diff --git a/kernel/src/io/fs/io/console/screen/virtualconsolescreen.d b/kernel/src/io/fs/io/console/screen/virtualconsolescreen.d index 29e1359..0cbd143 100644 --- a/kernel/src/io/fs/io/console/screen/virtualconsolescreen.d +++ b/kernel/src/io/fs/io/console/screen/virtualconsolescreen.d @@ -1,45 +1,45 @@ -module IO.FS.IO.Console.Screen.VirtualConsoleScreen; +module io.fs.io.console.screen.virtualconsolescreen; -import IO.FS; -import IO.FS.IO.Console.Screen; -import Data.Address; -import Data.Color; -import Data.UTF; +import io.fs; +import io.fs.io.console.screen; +import data.address; +import data.color; +import data.utf; abstract class VirtualConsoleScreen : FileNode { public: this(size_t width, size_t height, FormattedChar clearChar) { - super(NodePermissions.DefaultPermissions, 0); - this.width = width; - this.height = height; - this.clearChar = clearChar; - this.screen = new FormattedChar[width * height]; - for (size_t i = 0; i < screen.length; i++) - screen[i] = clearChar; - - this.lineStarts = new size_t[height]; + super(NodePermissions.defaultPermissions, 0); + _width = width; + _height = height; + _clearChar = clearChar; + _screen = new FormattedChar[width * height]; + for (size_t i = 0; i < _screen.length; i++) + _screen[i] = _clearChar; + + _lineStarts = new size_t[height]; } ~this() { - screen.destroy; + _screen.destroy; } - override bool Open() { - if (inUse) + override bool open() { + if (_inUse) return false; - return inUse = true; + return _inUse = true; } - override void Close() { - inUse = false; + override void close() { + _inUse = false; } /++ TODO: Change how this works! XXX: Casting FormattedChar to a ubyte array is crazy! +/ - override ulong Read(ubyte[] buffer, ulong offset) { - ubyte[] scr_b = cast(ubyte[])screen; + override ulong read(ubyte[] buffer, ulong offset) { + ubyte[] scr_b = cast(ubyte[])_screen; size_t maxBytes = (buffer.length < scr_b.length) ? buffer.length : scr_b.length; @@ -49,100 +49,100 @@ public: return maxBytes; } - override ulong Write(ubyte[] buffer, ulong offset) { + override ulong write(ubyte[] buffer, ulong offset) { UTF8Range str = UTF8Range(buffer); if (active) - UpdateChar(curX, curY); // Remove cursor rendering + updateChar(_curX, _curY); // Remove cursor rendering - foreach (dchar ch; prepareData(str)) { + foreach (dchar ch; _prepareData(str)) { switch (ch) { case '\n': - curY++; - curX = 0; + _curY++; + _curX = 0; break; case '\r': - curX = 0; + _curX = 0; break; case '\b': - if (curX) - curX--; + if (_curX) + _curX--; break; case '\t': - size_t goal = (curX + 8) & ~7; - if (goal > width) - goal = width; - for (; curX < goal; curX++) { - screen[curY * width + curX] = clearChar; + size_t goal = (_curX + 8) & ~7; + if (goal > _width) + goal = _width; + for (; _curX < goal; _curX++) { + _screen[_curY * _width + _curX] = _clearChar; if (active) - UpdateChar(curX, curY); - curX++; + updateChar(_curX, _curY); + _curX++; } - if (curX >= width) { - curY++; - curX = 0; + if (_curX >= _width) { + _curY++; + _curX = 0; } break; default: - screen[curY * width + curX] = FormattedChar(ch, Color(255, 255, 0), Color(0, 0, 0), CharStyle.None); + _screen[_curY * _width + _curX] = FormattedChar(ch, Color(255, 255, 0), Color(0, 0, 0), CharStyle.none); if (active) - UpdateChar(curX, curY); - curX++; - if (curX >= width) { - curY++; - curX = 0; + updateChar(_curX, _curY); + _curX++; + if (_curX >= _width) { + _curY++; + _curX = 0; } break; } } if (active) - UpdateCursor(); + updateCursor(); return buffer.length; } - void Clear() { //TODO:REMOVE - clear(); + void clear() { //TODO:REMOVE + _clear(); } - @property bool Active() { - return active; + @property bool active() { + return _active; } - @property bool Active(bool active) { - if (active && !this.active) { - for (size_t h = 0; h < height; h++) - for (size_t w = 0; w < width; w++) - UpdateChar(w, h); - UpdateCursor(); + @property bool active(bool active) { + if (active && !_active) { + for (size_t h = 0; h < _height; h++) + for (size_t w = 0; w < _width; w++) + updateChar(w, h); + updateCursor(); } - this.active = active; - return active; + _active = active; + return _active; } protected: - FormattedChar[] screen; - FormattedChar clearChar; - size_t width; - size_t height; - size_t curX; - size_t curY; - - // abstract void OnNewText(size_t startIdx, size_t length); //TODO: Use this instead of UpdateChar? - abstract void OnScroll(size_t lineCount); - abstract void UpdateCursor(); - abstract void UpdateChar(size_t x, size_t y); + FormattedChar[] _screen; + FormattedChar _clearChar; + size_t _width; + size_t _height; + size_t _curX; + size_t _curY; + + // abstract void OnNewText(size_t startIdx, size_t length); //TODO: Use this instead of updateChar? + abstract void onScroll(size_t lineCount); + abstract void updateCursor(); + abstract void updateChar(size_t x, size_t y); private: - bool inUse; - bool active; + bool _inUse; + bool _active; - size_t[] lineStarts; + size_t[] _lineStarts; - ref UTF8Range prepareData(ref return UTF8Range str) { - size_t charCount = curX; + ref UTF8Range _prepareData(ref return UTF8Range str) { + size_t charCount = _curX; size_t lines; - //size_t[] lineStarts = new size_t[height]; + //size_t[] _lineStarts = new size_t[_height]; size_t lsIdx; // Calc the number line @@ -162,8 +162,8 @@ private: case 'J': if (escapeValue == '2') { str.popFrontN(idx + 1); - clear(); - return prepareData(str); + _clear(); + return _prepareData(str); } break; default: @@ -181,76 +181,76 @@ private: } else if (ch == '\n') { lines++; charCount = 0; - lsIdx = (lsIdx + 1) % height; - lineStarts[lsIdx] = idx + 1; // Next char is the start of *new* the line + lsIdx = (lsIdx + 1) % _height; + _lineStarts[lsIdx] = idx + 1; // Next char is the start of *new* the line } else if (ch == '\r') { charCount = 0; - lineStarts[lsIdx] = idx + 1; // Update the lineStart on the current one + _lineStarts[lsIdx] = idx + 1; // Update the lineStart on the current one } else if (ch == '\b') { if (charCount) charCount--; } else if (ch == '\t') { charCount = (charCount + 8) & ~7; - if (charCount > width) - charCount = width; + if (charCount > _width) + charCount = _width; } else charCount++; - while (charCount >= width) { + while (charCount >= _width) { lines++; - charCount -= width; - lsIdx = (lsIdx + 1) % height; - lineStarts[lsIdx] = idx + 1; // The current char is the start of *new* the line + charCount -= _width; + lsIdx = (lsIdx + 1) % _height; + _lineStarts[lsIdx] = idx + 1; // The current char is the start of *new* the line } idx++; } - if (curY + lines >= height) { - scroll(curY + lines - height + 1); + if (_curY + lines >= _height) { + _scroll(_curY + lines - _height + 1); - // Skip the beginning of the data, that would never be shown on the screen. - if (lines >= height) { - if (lineStarts[(lsIdx + 1) % height] < str.length) { + // Skip the beginning of the data, that would never be shown on the _screen. + if (lines >= _height) { + if (_lineStarts[(lsIdx + 1) % _height] < str.length) { //XXX: Fix hack - str.popFrontN(lineStarts[(lsIdx + 1) % height] + 1); - //str = str[lineStarts[(lsIdx + 1) % height] + 1 .. $]; + str.popFrontN(_lineStarts[(lsIdx + 1) % _height] + 1); + //str = str[_lineStarts[(lsIdx + 1) % _height] + 1 .. $]; } else str = UTF8Range([]); } } - //lineStarts.destroy; + //_lineStarts.destroy; return str; } - void scroll(size_t lineCount) { - if (lineCount > height) - lineCount = height; + void _scroll(size_t lineCount) { + if (lineCount > _height) + lineCount = _height; if (active) - UpdateChar(curX, curY); // Remove cursor rendering + updateChar(_curX, _curY); // Remove cursor rendering if (active) - OnScroll(lineCount); + onScroll(lineCount); - size_t offset = FormattedChar.sizeof * lineCount * width; - memmove(screen.ptr, (screen.VirtAddress + offset).Ptr, screen.length * FormattedChar.sizeof - offset); - for (size_t i = screen.length - (lineCount * width); i < screen.length; i++) - screen[i] = clearChar; + size_t offset = FormattedChar.sizeof * lineCount * _width; + memmove(_screen.ptr, (_screen.VirtAddress + offset).ptr, _screen.length * FormattedChar.sizeof - offset); + for (size_t i = _screen.length - (lineCount * _width); i < _screen.length; i++) + _screen[i] = _clearChar; - ssize_t tmp = curY - lineCount; + ssize_t tmp = _curY - lineCount; if (tmp < 0) - curY = curX = 0; + _curY = _curX = 0; else - curY = tmp; + _curY = tmp; } - void clear() { - scroll(height); - curX = curY = 0; + void _clear() { + _scroll(_height); + _curX = _curY = 0; if (active) - UpdateCursor(); + updateCursor(); } } diff --git a/kernel/src/io/fs/io/console/screen/virtualconsolescreenframebuffer.d b/kernel/src/io/fs/io/console/screen/virtualconsolescreenframebuffer.d index 5e048b5..a05c40f 100644 --- a/kernel/src/io/fs/io/console/screen/virtualconsolescreenframebuffer.d +++ b/kernel/src/io/fs/io/console/screen/virtualconsolescreenframebuffer.d @@ -1,56 +1,56 @@ -module IO.FS.IO.Console.Screen.VirtualConsoleScreenFramebuffer; +module io.fs.io.console.screen.virtualconsolescreenframebuffer; -import IO.FS; -import IO.FS.IO.Console.Screen; -import IO.FS.IO.Framebuffer; +import io.fs; +import io.fs.io.console.screen; +import io.fs.io.framebuffer; -import Data.Color; -import Data.Font; +import data.color; +import data.font; final class VirtualConsoleScreenFramebuffer : VirtualConsoleScreen { public: this(Framebuffer fb, Font font) { - super(fb.Width / font.Width, fb.Height / font.Height, FormattedChar(' ', Color(0xFF, 0xFF, 0xFF), Color(0x00, - 0x00, 0x00), CharStyle.None)); - this.fb = fb; - this.font = font; + super(fb.width / font.width, fb.height / font.height, FormattedChar(' ', Color(0xFF, 0xFF, 0xFF), Color(0x00, + 0x00, 0x00), CharStyle.none)); + _fb = fb; + _font = font; } protected: - override void OnScroll(size_t lineCount) { - size_t startRow = font.Height * lineCount; - size_t rows = font.Height * height - startRow; + override void onScroll(size_t lineCount) { + size_t startRow = _font.height * lineCount; + size_t rows = _font.height * _height - startRow; - fb.MoveRegion(0, 0, 0, startRow, fb.Width, rows); - fb.RenderRect(0, rows, fb.Width, startRow, clearChar.bg); + _fb.moveRegion(0, 0, 0, startRow, _fb.width, rows); + _fb.renderRect(0, rows, _fb.width, startRow, _clearChar.bg); } - override void UpdateCursor() { - FormattedChar ch = screen[curY * width + curX]; + override void updateCursor() { + FormattedChar ch = _screen[_curY * _width + _curX]; Color tmp = ch.fg; ch.fg = ch.bg; ch.bg = tmp; - fb.RenderChar(font, ch.ch, curX * font.Width, curY * font.Height, ch.fg, ch.bg); + _fb.renderChar(_font, ch.ch, _curX * _font.width, _curY * _font.height, ch.fg, ch.bg); } - override void UpdateChar(size_t x, size_t y) { - auto ch = screen[y * width + x]; - fb.RenderChar(font, ch.ch, x * font.Width, y * font.Height, ch.fg, ch.bg); + override void updateChar(size_t x, size_t y) { + auto ch = _screen[y * _width + x]; + _fb.renderChar(_font, ch.ch, x * _font.width, y * _font.height, ch.fg, ch.bg); } - @property override bool Active(bool active) { - fb.Active = active; - return super.Active(active); + @property override bool active(bool active) { + _fb.active = active; + return super.active(active); } private: - Framebuffer fb; - Font font; + Framebuffer _fb; + Font _font; - void rerender() { - foreach (idx, ch; screen) - fb.RenderChar(font, ch.ch, idx % font.Width, idx / font.Height, ch.fg, ch.bg); - UpdateCursor(); + void _rerender() { + foreach (idx, ch; _screen) + _fb.renderChar(_font, ch.ch, idx % _font.width, idx / _font.height, ch.fg, ch.bg); + updateCursor(); } } diff --git a/kernel/src/io/fs/io/console/screen/virtualconsolescreentextmode.d b/kernel/src/io/fs/io/console/screen/virtualconsolescreentextmode.d index 0ac0056..d764ba8 100644 --- a/kernel/src/io/fs/io/console/screen/virtualconsolescreentextmode.d +++ b/kernel/src/io/fs/io/console/screen/virtualconsolescreentextmode.d @@ -1,40 +1,40 @@ -module IO.FS.IO.Console.Screen.VirtualConsoleScreenTextMode; +module io.fs.io.console.screen.virtualconsolescreentextmode; -import IO.FS; -import IO.FS.IO.Console.Screen; +import io.fs; +import io.fs.io.console.screen; -import Data.Color; +import data.color; -import Data.Address; +import data.address; final class VirtualConsoleScreenTextMode : VirtualConsoleScreen { public: this() { - super(80, 25, FormattedChar(' ', Color(0xFF, 0xFF, 0xFF), Color(0x00, 0x00, 0x00), CharStyle.None)); - slots = VirtAddress(0xFFFF_FFFF_800B_8000).Ptr!Slot[0 .. width * height]; + super(80, 25, FormattedChar(' ', Color(0xFF, 0xFF, 0xFF), Color(0x00, 0x00, 0x00), CharStyle.none)); + _slots = VirtAddress(0xFFFF_FFFF_800B_8000).ptr!Slot[0 .. _width * _height]; } protected: - override void OnScroll(size_t lineCount) { - size_t offset = Slot.sizeof * lineCount * width; - memmove(slots.ptr, (slots.VirtAddress + offset).Ptr, slots.length * Slot.sizeof - offset); - for (size_t i = slots.length - (lineCount * width); i < slots.length; i++) - slots[i] = toSlot(clearChar); + override void onScroll(size_t lineCount) { + size_t offset = Slot.sizeof * lineCount * _width; + memmove(_slots.ptr, (_slots.VirtAddress + offset).ptr, _slots.length * Slot.sizeof - offset); + for (size_t i = _slots.length - (lineCount * _width); i < _slots.length; i++) + _slots[i] = _toSlot(_clearChar); } - override void UpdateCursor() { - import IO.Port; + override void updateCursor() { + import io.port; - ushort pos = cast(ushort)(curY * width + curX); - Out!ubyte(0x3D4, 14); - Out!ubyte(0x3D5, pos >> 8); - Out!ubyte(0x3D4, 15); - Out!ubyte(0x3D5, cast(ubyte)pos); + ushort pos = cast(ushort)(_curY * _width + _curX); + outp!ubyte(0x3D4, 14); + outp!ubyte(0x3D5, pos >> 8); + outp!ubyte(0x3D4, 15); + outp!ubyte(0x3D5, cast(ubyte)pos); } - override void UpdateChar(size_t x, size_t y) { - FormattedChar fc = screen[y * width + x]; - slots[y * width + x] = toSlot(fc); + override void updateChar(size_t x, size_t y) { + FormattedChar fc = _screen[y * _width + x]; + _slots[y * _width + x] = _toSlot(fc); } private: @@ -43,9 +43,9 @@ private: CharColor color; } - Slot[] slots; + Slot[] _slots; - TMColor findNearest(Color c) { + TMColor _findNearest(Color c) { TMColor tc; ulong dif = ulong.max; @@ -60,75 +60,75 @@ private: return tc; } - Slot toSlot(FormattedChar fc) { - return Slot(cast(char)fc.ch, CharColor(findNearest(fc.fg), findNearest(fc.bg))); + Slot _toSlot(FormattedChar fc) { + return Slot(cast(char)fc.ch, CharColor(_findNearest(fc.fg), _findNearest(fc.bg))); } } private { enum TMColor : ubyte { - Black = 0, - Blue = 1, - Green = 2, - Cyan = 3, - Red = 4, - Magenta = 5, - Brown = 6, - LightGray = 7, - DarkGray = 8, - LightBlue = 9, - LightGreen = 10, - LightCyan = 11, - LightRed = 12, - LightMagenta = 13, - Yellow = 14, - White = 15 + black = 0, + blue = 1, + green = 2, + cyan = 3, + red = 4, + magenta = 5, + brown = 6, + lightGray = 7, + darkGray = 8, + lightBlue = 9, + lightGreen = 10, + lightCyan = 11, + lightRed = 12, + lightMagenta = 13, + yellow = 14, + white = 15 } //dfmt off immutable Color[/*TMColor*/] TMColorPalette = [ - /*TMColor.Black: */Color(0, 0, 0), - /*TMColor.Blue: */Color(0, 0, 170), - /*TMColor.Green: */Color(0, 170, 0), - /*TMColor.Cyan: */Color(0, 170, 170), - /*TMColor.Red: */Color(170, 0, 0), - /*TMColor.Magenta: */Color(170, 0, 170), - /*TMColor.Brown: */Color(170, 85, 0), - /*TMColor.LightGray: */Color(170, 170, 170), - /*TMColor.DarkGray: */Color(85, 85, 85), - /*TMColor.LightBlue: */Color(85, 85, 255), - /*TMColor.LightGreen: */Color(85, 255, 85), - /*TMColor.LightCyan: */Color(85, 255, 255), - /*TMColor.LightRed: */Color(255, 85, 85), - /*TMColor.LightMagenta: */Color(255, 85, 255), - /*TMColor.Yellow: */Color(255, 255, 85), - /*TMColor.White: */Color(255, 255, 255) + /*TMColor.black: */Color(0, 0, 0), + /*TMColor.blue: */Color(0, 0, 170), + /*TMColor.green: */Color(0, 170, 0), + /*TMColor.cyan: */Color(0, 170, 170), + /*TMColor.red: */Color(170, 0, 0), + /*TMColor.magenta: */Color(170, 0, 170), + /*TMColor.brown: */Color(170, 85, 0), + /*TMColor.lightGray: */Color(170, 170, 170), + /*TMColor.darkGray: */Color(85, 85, 85), + /*TMColor.lightBlue: */Color(85, 85, 255), + /*TMColor.lightGreen: */Color(85, 255, 85), + /*TMColor.lightCyan: */Color(85, 255, 255), + /*TMColor.lightRed: */Color(255, 85, 85), + /*TMColor.lightMagenta: */Color(255, 85, 255), + /*TMColor.yellow: */Color(255, 255, 85), + /*TMColor.white: */Color(255, 255, 255) ]; //dfmt on struct CharColor { - private ubyte color; + private ubyte _color; this(TMColor fg, TMColor bg) { - color = ((bg & 0xF) << 4) | (fg & 0xF); + _color = ((bg & 0xF) << 4) | (fg & 0xF); } - @property TMColor Foreground() { - return cast(TMColor)(color & 0xF); + @property TMColor foreground() { + return cast(TMColor)(_color & 0xF); } - @property TMColor Foreground(TMColor c) { - color = (color & 0xF0) | (c & 0xF); - return cast(TMColor)(color & 0xF); + @property TMColor foreground(TMColor c) { + _color = (_color & 0xF0) | (c & 0xF); + return cast(TMColor)(_color & 0xF); } - @property TMColor Background() { - return cast(TMColor)((color >> 4) & 0xF); + @property TMColor background() { + return cast(TMColor)((_color >> 4) & 0xF); } - @property TMColor Background(TMColor c) { - color = ((c & 0xF) << 4) | (color & 0xF); - return cast(TMColor)((color >> 4) & 0xF); + @property TMColor background(TMColor c) { + _color = ((c & 0xF) << 4) | (_color & 0xF); + return cast(TMColor)((_color >> 4) & 0xF); } } } diff --git a/kernel/src/io/fs/io/console/serialconsole.d b/kernel/src/io/fs/io/console/serialconsole.d index 3d4f3db..34a05ee 100644 --- a/kernel/src/io/fs/io/console/serialconsole.d +++ b/kernel/src/io/fs/io/console/serialconsole.d @@ -1,43 +1,43 @@ -module IO.FS.IO.Console.SerialConsole; +module io.fs.io.console.serialconsole; -import IO.FS; -import IO.FS.IO.Console; +import io.fs; +import io.fs.io.console; -import IO.COM; -import CPU.IDT; +import io.com; +import cpu.idt; class SerialConsole : Console { public: this(ref COM com) { - this.com = &com; + _com = &com; } - override bool Open() { - if (inUse) + override bool open() { + if (_inUse) return false; - return inUse = true; + return _inUse = true; } - override void Close() { - inUse = false; + override void close() { + _inUse = false; } - override ulong Read(ubyte[] buffer, ulong offset) { + override ulong read(ubyte[] buffer, ulong offset) { size_t read; - while (read < buffer.length && com.CanRead) - buffer[read++] = com.Read(); + while (read < buffer.length && _com.canRead) + buffer[read++] = _com.read(); return read; } - override ulong Write(ubyte[] buffer, ulong offset) { + override ulong write(ubyte[] buffer, ulong offset) { foreach (ubyte b; buffer) - com.Write(b); + _com.write(b); return buffer.length; } private: - bool inUse; - COM* com; + bool _inUse; + COM* _com; } diff --git a/kernel/src/io/fs/io/console/virtualconsole.d b/kernel/src/io/fs/io/console/virtualconsole.d index 2f18165..c6bbc9a 100644 --- a/kernel/src/io/fs/io/console/virtualconsole.d +++ b/kernel/src/io/fs/io/console/virtualconsole.d @@ -1,76 +1,77 @@ -module IO.FS.IO.Console.VirtualConsole; -import IO.FS; -import IO.FS.IO.Console; -import Task.Scheduler; -import Task.Process; +module io.fs.io.console.virtualconsole; +import io.fs; +import io.fs.io.console; +import task.scheduler; +import task.process; class VirtualConsole : Console { public: - this(VirtualConsoleScreen vcs) { + this(VirtualConsoleScreen _vcs) { super(); - this.vcs = vcs; + this._vcs = _vcs; } - override bool Open() { - if (inUse) + override bool open() { + if (_inUse) return false; - return inUse = true; + return _inUse = true; } - override void Close() { - inUse = false; + override void close() { + _inUse = false; } - override ulong Read(ubyte[] buffer, ulong offset) { + override ulong read(ubyte[] buffer, ulong offset) { size_t read; - if (kbStart == kbEnd) - GetScheduler.WaitFor(WaitReason.Keyboard, cast(ulong)kbBuffer.ptr); + if (_kbStart == _kbEnd) + getScheduler.waitFor(WaitReason.keyboard, cast(ulong)_kbBuffer.ptr); - while (read < buffer.length && kbStart != kbEnd) - buffer[read++] = kbBuffer[kbStart++]; + while (read < buffer.length && _kbStart != _kbEnd) + buffer[read++] = _kbBuffer[_kbStart++]; return read; } - override ulong Write(ubyte[] buffer, ulong offset) { - return vcs.Write(buffer, offset); + override ulong write(ubyte[] buffer, ulong offset) { + return _vcs.write(buffer, offset); } - bool AddKeyboardInput(dchar ch) { - import Data.UTF; + bool addKeyboardInput(dchar ch) { + import data.utf; - if (kbEnd + 1 == kbStart) + if (_kbEnd + 1 == _kbStart) return false; size_t bytesUsed; - ubyte[4] utf8 = ToUTF8(ch, bytesUsed); + ubyte[4] utf8 = toUTF8(ch, bytesUsed); //XXX: Make this prettier - if ((bytesUsed > 1 && kbEnd + 2 == kbStart) || (bytesUsed > 2 && kbEnd + 3 == kbStart) || (bytesUsed > 3 && kbEnd + 4 == kbStart)) + if ((bytesUsed > 1 && _kbEnd + 2 == _kbStart) || (bytesUsed > 2 && _kbEnd + 3 == _kbStart) || (bytesUsed > 3 && _kbEnd + + 4 == _kbStart)) return false; foreach (b; utf8[0 .. bytesUsed]) - kbBuffer[kbEnd++] = b; + _kbBuffer[_kbEnd++] = b; - GetScheduler.WakeUp(WaitReason.Keyboard, &wakeUpKeyboard, cast(void*)kbBuffer.ptr); + getScheduler.wakeUp(WaitReason.keyboard, &_wakeUpKeyboard, cast(void*)_kbBuffer.ptr); return true; } - @property bool Active() { - return vcs.Active; + @property bool active() { + return _vcs.active; } - @property bool Active(bool active) { - return vcs.Active = active; + @property bool active(bool active) { + return _vcs.active = active; } private: - bool inUse; - VirtualConsoleScreen vcs; - size_t kbStart; - size_t kbEnd; - ubyte[0x1000] kbBuffer; - static bool wakeUpKeyboard(Process* p, void* data) { + bool _inUse; + VirtualConsoleScreen _vcs; + size_t _kbStart; + size_t _kbEnd; + ubyte[0x1000] _kbBuffer; + static bool _wakeUpKeyboard(Process* p, void* data) { return p.waitData == cast(ulong)data; } } diff --git a/kernel/src/io/fs/io/framebuffer/bgaframebuffer.d b/kernel/src/io/fs/io/framebuffer/bgaframebuffer.d index c498f64..ac1f7d0 100644 --- a/kernel/src/io/fs/io/framebuffer/bgaframebuffer.d +++ b/kernel/src/io/fs/io/framebuffer/bgaframebuffer.d @@ -1,112 +1,112 @@ -module IO.FS.IO.Framebuffer.BGAFramebuffer; +module io.fs.io.framebuffer.bgaframebuffer; -import IO.FS; -import IO.FS.IO.Framebuffer; -import Data.Address; -import IO.Log; -import IO.Port; +import io.fs; +import io.fs.io.framebuffer; +import data.address; +import io.log; +import io.port; -import HW.PCI.PCI; +import hw.pci.pci; private enum : ushort { - VBE_DISPI_TOTAL_VIDEO_MEMORY_MB = 16, - VBE_DISPI_4BPP_PLANE_SHIFT = 22, - VBE_DISPI_BANK_SIZE_KB = 64, - VBE_DISPI_MAX_XRES = 2560, - VBE_DISPI_MAX_YRES = 1600, - VBE_DISPI_MAX_BPP = 32, - VBE_DISPI_IOPORT_INDEX = 0x01CE, - VBE_DISPI_IOPORT_DATA = 0x01CF, - VBE_DISPI_INDEX_ID = 0x0, - VBE_DISPI_INDEX_XRES = 0x1, - VBE_DISPI_INDEX_YRES = 0x2, - VBE_DISPI_INDEX_BPP = 0x3, - VBE_DISPI_INDEX_ENABLE = 0x4, - VBE_DISPI_INDEX_BANK = 0x5, - VBE_DISPI_INDEX_VIRT_WIDTH = 0x6, - VBE_DISPI_INDEX_VIRT_HEIGHT = 0x7, - VBE_DISPI_INDEX_X_OFFSET = 0x8, - VBE_DISPI_INDEX_Y_OFFSET = 0x9, - VBE_DISPI_INDEX_VIDEO_MEMORY_64K = 0xa, - VBE_DISPI_ID0 = 0xB0C0, - VBE_DISPI_ID1 = 0xB0C1, - VBE_DISPI_ID2 = 0xB0C2, - VBE_DISPI_ID3 = 0xB0C3, - VBE_DISPI_ID4 = 0xB0C4, - VBE_DISPI_ID5 = 0xB0C5, - VBE_DISPI_BPP_4 = 0x04, - VBE_DISPI_BPP_8 = 0x08, - VBE_DISPI_BPP_15 = 0x0F, - VBE_DISPI_BPP_16 = 0x10, - VBE_DISPI_BPP_24 = 0x18, - VBE_DISPI_BPP_32 = 0x20, - VBE_DISPI_DISABLED = 0x00, - VBE_DISPI_ENABLED = 0x01, - VBE_DISPI_GETCAPS = 0x02, - VBE_DISPI_8BIT_DAC = 0x20, - VBE_DISPI_LFB_ENABLED = 0x40, - VBE_DISPI_NOCLEARMEM = 0x80, + vbeDispiTotalVideoMemoryMb = 16, + vbeDispi_4BppPlaneShift = 22, + vbeDispiBankSizeKb = 64, + vbeDispiMaxXres = 2560, + vbeDispiMaxYres = 1600, + vbeDispiMaxBpp = 32, + vbeDispiIoportIndex = 0x01CE, + vbeDispiIoportData = 0x01CF, + vbeDispiIndexId = 0x0, + vbeDispiIndexXres = 0x1, + vbeDispiIndexYres = 0x2, + vbeDispiIndexBpp = 0x3, + vbeDispiIndexEnable = 0x4, + vbeDispiIndexBank = 0x5, + vbeDispiIndexVirtWidth = 0x6, + vbeDispiIndexVirtHeight = 0x7, + vbeDispiIndexXOffset = 0x8, + vbeDispiIndexYOffset = 0x9, + vbeDispiIndexVideoMemory_64K = 0xa, + vbeDispiId0 = 0xB0C0, + vbeDispiId1 = 0xB0C1, + vbeDispiId2 = 0xB0C2, + vbeDispiId3 = 0xB0C3, + vbeDispiId4 = 0xB0C4, + vbeDispiId5 = 0xB0C5, + vbeDispiBpp_4 = 0x04, + vbeDispiBpp_8 = 0x08, + vbeDispiBpp_15 = 0x0F, + vbeDispiBpp_16 = 0x10, + vbeDispiBpp_24 = 0x18, + vbeDispiBpp_32 = 0x20, + vbeDispiDisabled = 0x00, + vbeDispiEnabled = 0x01, + vbeDispiGetcaps = 0x02, + vbeDispi8BitDac = 0x20, + vbeDispiLfbEnabled = 0x40, + vbeDispiNoclearmem = 0x80, } enum : ushort { - BGA_VENDOR = 0x1234, - BGA_DEVICE = 0x1111, - VBOX_VENDOR = 0x80EE, - VBOX_DEVICE = 0xBEEF, - VBOX_OLDDEVICE = 0x7145, + bgaVendor = 0x1234, + bgaDevice = 0x1111, + vboxVendor = 0x80EE, + vboxDevice = 0xBEEF, + vboxOlddevice = 0x7145, } enum { - VBOX_ADDR = 0xE000_0000, + vboxAddr = 0xE000_0000, } class BGAFramebuffer : Framebuffer { public: this(size_t width, size_t height) { PhysAddress physAddress; - PCIDevice* bgaDevice = GetPCI.GetDevice(BGA_VENDOR, BGA_DEVICE); + PCIDevice* bgaDevice = getPCI.getDevice(bgaVendor, bgaDevice); if (bgaDevice) physAddress = PhysAddress(bgaDevice.bar0 & ~0b1111UL); else { - bgaDevice = GetPCI.GetDevice(VBOX_VENDOR, VBOX_DEVICE); + bgaDevice = getPCI.getDevice(vboxVendor, vboxDevice); if (!bgaDevice) - bgaDevice = GetPCI.GetDevice(VBOX_VENDOR, VBOX_OLDDEVICE); + bgaDevice = getPCI.getDevice(vboxVendor, vboxOlddevice); if (!bgaDevice) - log.Fatal("BGA device not found!"); - physAddress = PhysAddress(VBOX_ADDR); + log.fatal("BGA device not found!"); + physAddress = PhysAddress(vboxAddr); } super(physAddress, width, height); } protected: - override void OnActivate() { - ushort bitDepth = VBE_DISPI_BPP_32; + override void onActivate() { + ushort bitDepth = vbeDispiBpp_32; bool useLinearFrameBuffer = true; bool clearVideoMemory = true; - writeRegister(VBE_DISPI_INDEX_ENABLE, VBE_DISPI_DISABLED); - writeRegister(VBE_DISPI_INDEX_XRES, cast(ushort)width); - writeRegister(VBE_DISPI_INDEX_YRES, cast(ushort)height); - writeRegister(VBE_DISPI_INDEX_BPP, bitDepth); - writeRegister(VBE_DISPI_INDEX_VIRT_WIDTH, cast(ushort)width); - writeRegister(VBE_DISPI_INDEX_VIRT_HEIGHT, cast(ushort)height); - writeRegister(VBE_DISPI_INDEX_X_OFFSET, 0); - writeRegister(VBE_DISPI_INDEX_Y_OFFSET, 0); - writeRegister(VBE_DISPI_INDEX_ENABLE, VBE_DISPI_ENABLED | (useLinearFrameBuffer ? VBE_DISPI_LFB_ENABLED - : 0) | (clearVideoMemory ? 0 : VBE_DISPI_NOCLEARMEM)); + _writeRegister(vbeDispiIndexEnable, vbeDispiDisabled); + _writeRegister(vbeDispiIndexXres, cast(ushort)width); + _writeRegister(vbeDispiIndexYres, cast(ushort)height); + _writeRegister(vbeDispiIndexBpp, bitDepth); + _writeRegister(vbeDispiIndexVirtWidth, cast(ushort)width); + _writeRegister(vbeDispiIndexVirtHeight, cast(ushort)height); + _writeRegister(vbeDispiIndexXOffset, 0); + _writeRegister(vbeDispiIndexYOffset, 0); + _writeRegister(vbeDispiIndexEnable, vbeDispiEnabled | (useLinearFrameBuffer ? vbeDispiLfbEnabled + : 0) | (clearVideoMemory ? 0 : vbeDispiNoclearmem)); } - override void OnDisable() { - writeRegister(VBE_DISPI_INDEX_ENABLE, VBE_DISPI_DISABLED); + override void onDisable() { + _writeRegister(vbeDispiIndexEnable, vbeDispiDisabled); } private: - void writeRegister(ushort indexValue, ushort dataValue) { - Out!ushort(VBE_DISPI_IOPORT_INDEX, indexValue); - Out!ushort(VBE_DISPI_IOPORT_DATA, dataValue); + void _writeRegister(ushort indexValue, ushort dataValue) { + outp!ushort(vbeDispiIoportIndex, indexValue); + outp!ushort(vbeDispiIoportData, dataValue); } - ushort readRegister(ushort indexValue) { - Out!ushort(VBE_DISPI_IOPORT_INDEX, indexValue); - return In!ushort(VBE_DISPI_IOPORT_DATA); + ushort _readRegister(ushort indexValue) { + outp!ushort(vbeDispiIoportIndex, indexValue); + return inp!ushort(vbeDispiIoportData); } } diff --git a/kernel/src/io/fs/io/framebuffer/framebuffer.d b/kernel/src/io/fs/io/framebuffer/framebuffer.d index 204c79c..c9d85f1 100644 --- a/kernel/src/io/fs/io/framebuffer/framebuffer.d +++ b/kernel/src/io/fs/io/framebuffer/framebuffer.d @@ -1,39 +1,39 @@ -module IO.FS.IO.Framebuffer.Framebuffer; +module io.fs.io.framebuffer.framebuffer; -import IO.FS; -import IO.FS.IO.Framebuffer; +import io.fs; +import io.fs.io.framebuffer; -import Data.Address; -import Data.Color; -import Data.Font; -import Memory.Paging; +import data.address; +import data.color; +import data.font; +import memory.paging; abstract class Framebuffer : FileNode { public: this(PhysAddress physAddress, size_t width, size_t height) { - super(NodePermissions.DefaultPermissions, 0); + super(NodePermissions.defaultPermissions, 0); - this.width = width; - this.height = height; + _width = width; + _height = height; //TODO: Map physAddress - pixels = physAddress.Virtual; + _pixels = physAddress.virtual; } - override bool Open() { - if (inUse) + override bool open() { + if (_inUse) return false; - return inUse = true; + return _inUse = true; } - override void Close() { - inUse = false; + override void close() { + _inUse = false; } - override ulong Read(ubyte[] buffer, ulong offset) { - if (!active) + override ulong read(ubyte[] buffer, ulong offset) { + if (!_active) return 0; - size_t length = width * height * Color.sizeof + size_t.sizeof * 2; + size_t length = _width * _height * Color.sizeof + size_t.sizeof * 2; if (offset >= length) return 0; ulong size = buffer.length; @@ -44,142 +44,142 @@ public: size = (tmp < 0) ? 0 : tmp; } - size_t[] header = [width, height]; + size_t[] header = [_width, _height]; if (offset < 16) { auto wroteHeader = ((size < 16) ? size : 16) - offset; memcpy(buffer.ptr, &header[offset], wroteHeader); if (buffer.length > size) - memcpy(&buffer[wroteHeader], pixels.Ptr, size - wroteHeader); + memcpy(&buffer[wroteHeader], _pixels.ptr, size - wroteHeader); } else - memcpy(buffer.ptr, &pixels.Ptr[offset - 16], size); + memcpy(buffer.ptr, &_pixels.ptr[offset - 16], size); return size; } - override ulong Write(ubyte[] buffer, ulong offset) { - if (!active) + override ulong write(ubyte[] buffer, ulong offset) { + if (!_active) return 0; - size_t pixelLength = width * height * Color.sizeof; + size_t pixelLength = _width * _height * Color.sizeof; if (offset > pixelLength) return 0; size_t size = buffer.length; if (size + offset > pixelLength) size = pixelLength - offset; - memcpy(&pixels.Ptr[offset], buffer.ptr, size); + memcpy(&_pixels.ptr[offset], buffer.ptr, size); return buffer.length; } - void RenderPixel(ssize_t x, ssize_t y, Color c) { - if (!active) + void renderPixel(ssize_t x, ssize_t y, Color c) { + if (!_active) return; putPixel(x, y, c); } - void RenderText(Font font, string str, ssize_t x, ssize_t y, Color fg, Color bg) { - if (!active) + void renderText(Font font, string str, ssize_t x, ssize_t y, Color fg, Color bg) { + if (!_active) return; - renderText(font, str, x, y, fg, bg); + _renderText(font, str, x, y, fg, bg); } - void RenderChar(Font font, dchar str, ssize_t x, ssize_t y, Color fg, Color bg) { - if (!active) + void renderChar(Font font, dchar str, ssize_t x, ssize_t y, Color fg, Color bg) { + if (!_active) return; - renderChar(font, str, x, y, fg, bg); + _renderChar(font, str, x, y, fg, bg); } - void RenderRect(ssize_t x, ssize_t y, size_t width, size_t height, Color color) { - if (!active) + void renderRect(ssize_t x, ssize_t y, size_t _width, size_t _height, Color color) { + if (!_active) return; - renderRect(x, y, width, height, color); + _renderRect(x, y, _width, _height, color); } - void RenderLine(ssize_t x0, ssize_t y0, ssize_t x1, ssize_t y1, Color c) { - if (!active) + void renderLine(ssize_t x0, ssize_t y0, ssize_t x1, ssize_t y1, Color c) { + if (!_active) return; - renderLine(x0, y0, x1, y1, c); + _renderLine(x0, y0, x1, y1, c); } - void RenderCircle(ssize_t x0, ssize_t y0, ssize_t radius, Color color) { - if (!active) + void renderCircle(ssize_t x0, ssize_t y0, ssize_t radius, Color color) { + if (!_active) return; - renderCircle(x0, y0, radius, color); + _renderCircle(x0, y0, radius, color); } - void MoveRegion(ssize_t toX, ssize_t toY, ssize_t fromX, ssize_t fromY, size_t width, size_t height) { - if (!active) + void moveRegion(ssize_t toX, ssize_t toY, ssize_t fromX, ssize_t fromY, size_t _width, size_t _height) { + if (!_active) return; - moveRegion(toX, toY, fromX, fromY, width, height); + _moveRegion(toX, toY, fromX, fromY, _width, _height); } - @property size_t Width() { - return width; + @property size_t width() { + return _width; } - @property size_t Height() { - return height; + @property size_t height() { + return _height; } - @property bool Active() { - return active; + @property bool active() { + return _active; } - @property bool Active(bool active) { - if (active && !this.active) - OnActivate(); - else if (!active && this.active) - OnDisable(); + @property bool active(bool active) { + if (active && !_active) + onActivate(); + else if (!active && _active) + onDisable(); - this.active = active; - return active; + _active = active; + return _active; } protected: - size_t width; - size_t height; + size_t _width; + size_t _height; /// Activate the Framebuffer. /// This should set the needed mode and rerender everything. - abstract void OnActivate(); - abstract void OnDisable(); + abstract void onActivate(); + abstract void onDisable(); private: - bool inUse; - VirtAddress pixels; - bool active; + bool _inUse; + VirtAddress _pixels; + bool _active; pragma(inline, true) void putPixel(ssize_t x, ssize_t y, Color color) { if (x < 0 && y < 0) return; - *(pixels + (y * width + x) * Color.sizeof).Ptr!Color = color; + *(_pixels + (y * _width + x) * Color.sizeof).ptr!Color = color; } - void renderText(Font font, string str, ssize_t x, ssize_t y, Color fg, Color bg) { + void _renderText(Font font, string str, ssize_t x, ssize_t y, Color fg, Color bg) { foreach (ch; str) - RenderChar(font, ch, x += font.Width, y, fg, bg); + _renderChar(font, ch, x += font.width, y, fg, bg); } - void renderChar(Font font, dchar ch, ssize_t x, ssize_t y, Color fg, Color bg) { - ulong[] charData = new ulong[font.BufferSize]; - foreach (idxRow, ulong row; font.GetChar(ch, charData)) - foreach (column; 0 .. font.Width) - putPixel(x + column, y + idxRow, (row & (1 << (font.Width - 1 - column))) ? fg : bg); + void _renderChar(Font font, dchar ch, ssize_t x, ssize_t y, Color fg, Color bg) { + ulong[] charData = new ulong[font.bufferSize]; + foreach (idxRow, ulong row; font.getChar(ch, charData)) + foreach (column; 0 .. font.width) + putPixel(x + column, y + idxRow, (row & (1 << (font.width - 1 - column))) ? fg : bg); charData.destroy; } - void renderRect(ssize_t x, ssize_t y, size_t width, size_t height, Color color) { - for (ssize_t yy = y; yy < y + height; yy++) - for (ssize_t xx = x; xx < x + width; xx++) + void _renderRect(ssize_t x, ssize_t y, size_t _width, size_t _height, Color color) { + for (ssize_t yy = y; yy < y + _height; yy++) + for (ssize_t xx = x; xx < x + _width; xx++) putPixel(xx, yy, color); } - void renderLine(ssize_t x0, ssize_t y0, ssize_t x1, ssize_t y1, Color c) { - import Data.Util : abs; + void _renderLine(ssize_t x0, ssize_t y0, ssize_t x1, ssize_t y1, Color c) { + import data.util : abs; //Bresenham's line algorithm const ssize_t steep = abs(y1 - y0) > abs(x1 - x0); @@ -229,7 +229,7 @@ private: } } - void renderCircle(ssize_t x0, ssize_t y0, ssize_t radius, Color color) { + void _renderCircle(ssize_t x0, ssize_t y0, ssize_t radius, Color color) { //Midpoint circle algorithm ssize_t x = radius; ssize_t y = 0; @@ -254,14 +254,14 @@ private: } } - void moveRegion(ssize_t toX, ssize_t toY, ssize_t fromX, ssize_t fromY, size_t width, size_t height) { + void _moveRegion(ssize_t toX, ssize_t toY, ssize_t fromX, ssize_t fromY, size_t _width, size_t _height) { if (fromY >= toY) - foreach (row; 0 .. height) - memmove((pixels + ((toY + row) * this.width + toX) * Color.sizeof).Ptr, - (pixels + ((fromY + row) * this.width + fromX) * Color.sizeof).Ptr, width * Color.sizeof); + foreach (row; 0 .. _height) + memmove((_pixels + ((toY + row) * this._width + toX) * Color.sizeof).ptr, + (_pixels + ((fromY + row) * this._width + fromX) * Color.sizeof).ptr, _width * Color.sizeof); else - foreach_reverse (row; 0 .. height) - memmove((pixels + ((toY + row) * this.width + toX) * Color.sizeof).Ptr, - (pixels + ((fromY + row) * this.width + fromX) * Color.sizeof).Ptr, width * Color.sizeof); + foreach_reverse (row; 0 .. _height) + memmove((_pixels + ((toY + row) * this._width + toX) * Color.sizeof).ptr, + (_pixels + ((fromY + row) * this._width + fromX) * Color.sizeof).ptr, _width * Color.sizeof); } } diff --git a/kernel/src/io/fs/io/framebuffer/package.d b/kernel/src/io/fs/io/framebuffer/package.d index c28b120..43c8194 100644 --- a/kernel/src/io/fs/io/framebuffer/package.d +++ b/kernel/src/io/fs/io/framebuffer/package.d @@ -1,6 +1,6 @@ -module IO.FS.IO.Framebuffer; +module io.fs.io.framebuffer; public { - import IO.FS.IO.Framebuffer.Framebuffer; - import IO.FS.IO.Framebuffer.BGAFramebuffer; + import io.fs.io.framebuffer.framebuffer; + import io.fs.io.framebuffer.bgaframebuffer; } diff --git a/kernel/src/io/fs/io/fsroot.d b/kernel/src/io/fs/io/fsroot.d index b3f834c..ec6bded 100644 --- a/kernel/src/io/fs/io/fsroot.d +++ b/kernel/src/io/fs/io/fsroot.d @@ -1,57 +1,56 @@ -module IO.FS.IO.FSRoot; +module io.fs.io.fsroot; -import IO.FS; -import IO.FS.IO; +import io.fs; +import io.fs.io; -import IO.FS.IO.Console; -import IO.FS.IO.Framebuffer; +import io.fs.io.console; +import io.fs.io.framebuffer; class IOFSRoot : FSRoot { public: this() { - auto root = new DirectoryNode(NodePermissions.DefaultPermissions); - root.Name = "IO"; - root.ID = idCounter++; + auto root = new DirectoryNode(NodePermissions.defaultPermissions); + root.name = "io"; + root.id = _idCounter++; super(root); - addAt("/Zero", new ZeroNode()); - addAt("/True", new BoolNode(true)); - addAt("/False", new BoolNode(false)); + addAt("/zero", new ZeroNode()); + addAt("/true", new BoolNode(true)); + addAt("/false", new BoolNode(false)); Framebuffer[4] fbs; VirtualConsoleScreen[4] vcss; { - addAt("/Framebuffer/Framebuffer1", fbs[0] = new BGAFramebuffer(1280, 720)); - addAt("/Framebuffer/Framebuffer2", fbs[1] = new BGAFramebuffer(1280, 720)); - addAt("/Framebuffer/Framebuffer3", fbs[2] = new BGAFramebuffer(1280, 720)); - addAt("/Framebuffer/Framebuffer4", fbs[3] = new BGAFramebuffer(1280, 720)); + addAt("/framebuffer/framebuffer1", fbs[0] = new BGAFramebuffer(1280, 720)); + addAt("/framebuffer/framebuffer2", fbs[1] = new BGAFramebuffer(1280, 720)); + addAt("/framebuffer/framebuffer3", fbs[2] = new BGAFramebuffer(1280, 720)); + addAt("/framebuffer/framebuffer4", fbs[3] = new BGAFramebuffer(1280, 720)); } { - import Bin.ConsoleFont; + import bin.consolefont; - addAt("/ConsoleScreen/VirtualConsoleScreen1", vcss[0] = new VirtualConsoleScreenFramebuffer(fbs[0], GetConsoleFont())); - addAt("/ConsoleScreen/VirtualConsoleScreen2", vcss[1] = new VirtualConsoleScreenFramebuffer(fbs[1], GetConsoleFont())); - addAt("/ConsoleScreen/VirtualConsoleScreen3", vcss[2] = new VirtualConsoleScreenFramebuffer(fbs[2], GetConsoleFont())); - addAt("/ConsoleScreen/VirtualConsoleScreen4", vcss[3] = new VirtualConsoleScreenFramebuffer(fbs[3], GetConsoleFont())); + addAt("/consolescreen/virtualconsolescreen1", vcss[0] = new VirtualConsoleScreenFramebuffer(fbs[0], getConsoleFont())); + addAt("/consolescreen/virtualconsolescreen2", vcss[1] = new VirtualConsoleScreenFramebuffer(fbs[1], getConsoleFont())); + addAt("/consolescreen/virtualconsolescreen3", vcss[2] = new VirtualConsoleScreenFramebuffer(fbs[2], getConsoleFont())); + addAt("/consolescreen/virtualconsolescreen4", vcss[3] = new VirtualConsoleScreenFramebuffer(fbs[3], getConsoleFont())); } { - addAt("/Console/VirtualConsole1", new VirtualConsole(vcss[0])); - addAt("/Console/VirtualConsole2", new VirtualConsole(vcss[1])); - addAt("/Console/VirtualConsole3", new VirtualConsole(vcss[2])); - addAt("/Console/VirtualConsole4", new VirtualConsole(vcss[3])); + addAt("/console/virtualconsole1", new VirtualConsole(vcss[0])); + addAt("/console/virtualconsole2", new VirtualConsole(vcss[1])); + addAt("/console/virtualconsole3", new VirtualConsole(vcss[2])); + addAt("/console/virtualconsole4", new VirtualConsole(vcss[3])); } { - import IO.COM : COM1, COM2, COM3, COM4; + import io.com : com1, com2, com3, com4; - addAt("/Console/SerialConsole1", new SerialConsole(COM1)); - addAt("/Console/SerialConsole2", new SerialConsole(COM2)); - addAt("/Console/SerialConsole3", new SerialConsole(COM3)); - addAt("/Console/SerialConsole4", new SerialConsole(COM4)); + addAt("/console/serialconsole1", new SerialConsole(com1)); + addAt("/console/serialconsole2", new SerialConsole(com2)); + addAt("/console/serialconsole3", new SerialConsole(com3)); + addAt("/console/serialconsole4", new SerialConsole(com4)); } - } } diff --git a/kernel/src/io/fs/io/package.d b/kernel/src/io/fs/io/package.d index b837e11..0724561 100644 --- a/kernel/src/io/fs/io/package.d +++ b/kernel/src/io/fs/io/package.d @@ -1,8 +1,8 @@ -module IO.FS.IO; +module io.fs.io; public { - import IO.FS.IO.Console; - import IO.FS.IO.FSRoot; - import IO.FS.IO.ZeroNode; - import IO.FS.IO.BoolNode; + import io.fs.io.console; + import io.fs.io.fsroot; + import io.fs.io.zeronode; + import io.fs.io.boolnode; } diff --git a/kernel/src/io/fs/io/zeronode.d b/kernel/src/io/fs/io/zeronode.d index 4ed408f..0ab3675 100644 --- a/kernel/src/io/fs/io/zeronode.d +++ b/kernel/src/io/fs/io/zeronode.d @@ -1,27 +1,27 @@ -module IO.FS.IO.ZeroNode; +module io.fs.io.zeronode; -import IO.FS; -import IO.FS.IO; +import io.fs; +import io.fs.io; class ZeroNode : FileNode { public: this() { - super(NodePermissions.DefaultPermissions, 0); + super(NodePermissions.defaultPermissions, 0); } - override ulong Read(ubyte[] buffer, ulong offset) { + override ulong read(ubyte[] buffer, ulong offset) { return 0; } - override ulong Write(ubyte[] buffer, ulong offset) { + override ulong write(ubyte[] buffer, ulong offset) { return -1; } - override bool Open() { + override bool open() { return true; } - override void Close() { + override void close() { } private: diff --git a/kernel/src/io/fs/mountpointnode.d b/kernel/src/io/fs/mountpointnode.d index e932ce6..6e63d34 100644 --- a/kernel/src/io/fs/mountpointnode.d +++ b/kernel/src/io/fs/mountpointnode.d @@ -1,51 +1,51 @@ -module IO.FS.MountPointNode; +module io.fs.mountpointnode; -import IO.FS; +import io.fs; class MountPointNode : DirectoryNode { public: this(DirectoryNode oldNode, FSRoot mount) { - super(oldNode.Permission); - this.oldNode = oldNode; - this.mount = mount; - this.name = oldNode.Name; + super(oldNode.permission); + _oldNode = oldNode; + _mount = mount; + _name = _oldNode.name; } - override Node FindNode(string path) { - return mount.Root.FindNode(path); + override Node findNode(string path) { + return _mount.root.findNode(path); } - override MountPointNode Mount(DirectoryNode node, FSRoot fs) { - return mount.Root.Mount(node, fs); + override MountPointNode mount(DirectoryNode node, FSRoot fs) { + return _mount.root.mount(node, fs); } - override DirectoryNode Unmount(MountPointNode node) { - return mount.Root.Unmount(node); + override DirectoryNode unmount(MountPointNode node) { + return _mount.root.unmount(node); } - @property override Node[] Nodes() { - return mount.Root.Nodes; + @property override Node[] nodes() { + return _mount.root.nodes; } - @property FSRoot RootMount() { - return mount; + @property FSRoot rootMount() { + return _mount; } - @property DirectoryNode OldNode() { - return oldNode; + @property DirectoryNode oldNode() { + return _oldNode; } protected: - DirectoryNode oldNode; - FSRoot mount; + DirectoryNode _oldNode; + FSRoot _mount; - override Node add(Node node) { - node.Root = mount; - return mount.Root.Add(node); + override Node _add(Node node) { + node.root = _mount; + return _mount.root.add(node); } - override Node remove(Node node) { - node.Root = oldNode.Root; - return mount.Root.Remove(node); + override Node _remove(Node node) { + node.root = _oldNode.root; + return _mount.root.remove(node); } } diff --git a/kernel/src/io/fs/node.d b/kernel/src/io/fs/node.d index 8096d1a..b831422 100644 --- a/kernel/src/io/fs/node.d +++ b/kernel/src/io/fs/node.d @@ -1,72 +1,72 @@ -module IO.FS.Node; +module io.fs.node; -import IO.FS; +import io.fs; -import Data.BitField; -import IO.Log; +import data.bitfield; +import io.log; abstract class Node { public: - this(NodePermissions permission) { - this.root = null; - this.id = ulong.max; - this.name = ""; - this.permission = permission; - this.parent = null; + this(NodePermissions _permission) { + _root = null; + _id = ulong.max; + _name = ""; + _permission = _permission; + _parent = null; } - @property FSRoot Root() { - return root; + @property FSRoot root() { + return _root; } - @property FSRoot Root(FSRoot root) { - if (this.root == root) - return root; - if (this.root) - this.root.Remove(this); + @property FSRoot root(FSRoot root) { + if (_root == root) + return _root; + if (_root) + _root.remove(this); if (root) - root.Add(this); - this.root = root; - return root; + root.add(this); + _root = root; + return _root; } - @property ref ulong ID() { - return id; + @property ref ulong id() { + return _id; } - @property ref string Name() { - return name; + @property ref string name() { + return _name; } - @property ref NodePermissions Permission() { - return permission; + @property ref NodePermissions permission() { + return _permission; } - @property DirectoryNode Parent() { - return parent; + @property DirectoryNode parent() { + return _parent; } - @property DirectoryNode Parent(DirectoryNode parent) { - if (this.parent == parent) - return parent; - if (this.parent) - this.parent.Remove(this); + @property DirectoryNode parent(DirectoryNode parent) { + if (_parent == parent) + return _parent; + if (_parent) + _parent.remove(this); if (parent) - parent.Add(this); - this.parent = parent; - return parent; + parent.add(this); + _parent = parent; + return _parent; } override string toString() const { - return name; + return _name; } protected: - FSRoot root; - ulong id; - string name; - NodePermissions permission; - DirectoryNode parent; + FSRoot _root; + ulong _id; + string _name; + NodePermissions _permission; + DirectoryNode _parent; } diff --git a/kernel/src/io/fs/nodepermission.d b/kernel/src/io/fs/nodepermission.d index a1c9a07..7c590ca 100644 --- a/kernel/src/io/fs/nodepermission.d +++ b/kernel/src/io/fs/nodepermission.d @@ -1,62 +1,64 @@ -module IO.FS.NodePermission; +module io.fs.nodepermission; enum Mask { - None = 0, + none = 0, - X = 1, - W = 2, - R = 4, + x = 1, + w = 2, + r = 4, - RW = 6, - RX = 5, - WX = 3, - RWX = 7 + rw = 6, + rx = 5, + wx = 3, + rwx = 7 } struct PermissionMask { - private Mask data; + private Mask _data; + + //TODO: Bitfield this(Mask user, Mask group, Mask everyone) { - data = cast(Mask)((user & 0x7) << 0x6 | (group & 0x7) << 0x3 | (everyone & 0x7) << 0x0); + _data = cast(Mask)((user & 0x7) << 0x6 | (group & 0x7) << 0x3 | (everyone & 0x7) << 0x0); } - @property Mask User() { - return cast(Mask)((data >> 0x6) & 0x7); + @property Mask user() { + return cast(Mask)((_data >> 0x6) & 0x7); } - @property void User(Mask val) { - data = cast(Mask)((data & 0xfffffffffffffe3f) | ((val & 0x7) << 0x6)); + @property void user(Mask val) { + _data = cast(Mask)((_data & 0xfffffffffffffe3f) | ((val & 0x7) << 0x6)); } - @property Mask Group() { - return cast(Mask)((data >> 0x3) & 0x7); + @property Mask group() { + return cast(Mask)((_data >> 0x3) & 0x7); } - @property void Group(Mask val) { - data = cast(Mask)((data & 0xffffffffffffffc7) | ((val & 0x7) << 0x3)); + @property void group(Mask val) { + _data = cast(Mask)((_data & 0xffffffffffffffc7) | ((val & 0x7) << 0x3)); } - @property Mask Everyone() { - return cast(Mask)((data >> 0x0) & 0x7); + @property Mask everyone() { + return cast(Mask)((_data >> 0x0) & 0x7); } - @property void Everyone(Mask val) { - data = cast(Mask)((data & 0xfffffffffffffff8) | ((val & 0x7) << 0x0)); + @property void everyone(Mask val) { + _data = cast(Mask)((_data & 0xfffffffffffffff8) | ((val & 0x7) << 0x0)); } } struct NodePermissions { - @property static NodePermissions DefaultPermissions() { - return NodePermissions(PermissionMask(Mask.RWX, Mask.RX, Mask.RX), 0UL, 0UL); + @property static NodePermissions defaultPermissions() { + return NodePermissions(PermissionMask(Mask.rwx, Mask.rx, Mask.rx), 0UL, 0UL); } - PermissionMask mask; - ulong user; - ulong group; + PermissionMask _mask; + ulong _user; + ulong _group; this(PermissionMask mask, ulong user, ulong group) { - this.mask = mask; - this.user = user; - this.group = group; + _mask = mask; + _user = user; + _group = group; } } diff --git a/kernel/src/io/fs/package.d b/kernel/src/io/fs/package.d index ea1be2e..59fb603 100644 --- a/kernel/src/io/fs/package.d +++ b/kernel/src/io/fs/package.d @@ -1,13 +1,13 @@ -module IO.FS; +module io.fs; public { - import IO.FS.Node; - import IO.FS.NodePermission; - import IO.FS.FileNode; - import IO.FS.DirectoryNode; - import IO.FS.MountPointNode; - import IO.FS.HardLinkNode; - import IO.FS.SoftLinkNode; + import io.fs.node; + import io.fs.nodepermission; + import io.fs.filenode; + import io.fs.directorynode; + import io.fs.mountpointnode; + import io.fs.hardlinknode; + import io.fs.softlinknode; - import IO.FS.FSRoot; + import io.fs.fsroot; } diff --git a/kernel/src/io/fs/softlinknode.d b/kernel/src/io/fs/softlinknode.d index f8460fe..4d0ec09 100644 --- a/kernel/src/io/fs/softlinknode.d +++ b/kernel/src/io/fs/softlinknode.d @@ -1,22 +1,22 @@ -module IO.FS.SoftLinkNode; +module io.fs.softlinknode; -import IO.FS; +import io.fs; class SoftLinkNode : Node { public: this(NodePermissions permission, string path) { super(permission); - this.path = path; + _path = path; } - @property ref string Path() { - return path; + @property ref string path() { + return _path; } - @property Node Target() { - return parent.FindNode(path); + @property Node target() { + return parent.findNode(_path); } private: - string path; + string _path; } diff --git a/kernel/src/io/fs/system/fsroot.d b/kernel/src/io/fs/system/fsroot.d index 67dd519..389e13c 100644 --- a/kernel/src/io/fs/system/fsroot.d +++ b/kernel/src/io/fs/system/fsroot.d @@ -1,14 +1,14 @@ -module IO.FS.System.FSRoot; +module io.fs.system.fsroot; -import IO.FS; -import IO.FS.System; +import io.fs; +import io.fs.system; class SystemFSRoot : FSRoot { public: this() { - auto root = new DirectoryNode(NodePermissions.DefaultPermissions); - root.Name = "System"; - root.ID = idCounter++; + auto root = new DirectoryNode(NodePermissions.defaultPermissions); + root.name = "system"; + root.id = _idCounter++; super(root); addAt("/version", new VersionNode()); diff --git a/kernel/src/io/fs/system/package.d b/kernel/src/io/fs/system/package.d index 5a5add8..28d3e03 100644 --- a/kernel/src/io/fs/system/package.d +++ b/kernel/src/io/fs/system/package.d @@ -1,6 +1,6 @@ -module IO.FS.System; +module io.fs.system; public { - import IO.FS.System.FSRoot; - import IO.FS.System.VersionNode; + import io.fs.system.fsroot; + import io.fs.system.versionnode; } diff --git a/kernel/src/io/fs/system/versionnode.d b/kernel/src/io/fs/system/versionnode.d index 3ad25cb..6c77d7e 100644 --- a/kernel/src/io/fs/system/versionnode.d +++ b/kernel/src/io/fs/system/versionnode.d @@ -1,23 +1,23 @@ -module IO.FS.System.VersionNode; +module io.fs.system.versionnode; -import IO.FS; -import IO.FS.System; -import Data.String; +import io.fs; +import io.fs.system; +import data.string_; -immutable uint major = __VERSION__ / 1000; -immutable uint minor = __VERSION__ % 1000; +private immutable uint _major = __VERSION__ / 1000; +private immutable uint _minor = __VERSION__ % 1000; class VersionNode : FileNode { public: this() { - super(NodePermissions.DefaultPermissions, 0); + super(NodePermissions.defaultPermissions, 0); } - override ulong Read(ubyte[] buffer, ulong offset) { + override ulong read(ubyte[] buffer, ulong offset) { char[16] majorBuf; char[16] minorBuf; - string data = "Compiled using '" ~ __VENDOR__ ~ "' D version " ~ itoa(major, majorBuf) ~ "." ~ itoa(minor, minorBuf) ~ "\n"; + string data = "Compiled using '" ~ __VENDOR__ ~ "' D version " ~ itoa(_major, majorBuf) ~ "." ~ itoa(_minor, minorBuf) ~ "\n"; if (offset >= data.length) return 0; @@ -34,15 +34,15 @@ public: return size; } - override ulong Write(ubyte[] buffer, ulong offset) { + override ulong write(ubyte[] buffer, ulong offset) { return -1; } - override bool Open() { + override bool open() { return true; } - override void Close() { + override void close() { } private: diff --git a/kernel/src/io/log.d b/kernel/src/io/log.d index ac7126c..fca4c88 100644 --- a/kernel/src/io/log.d +++ b/kernel/src/io/log.d @@ -1,9 +1,9 @@ -module IO.Log; +module io.log; -import IO.COM; -import Data.Address; -import Data.String; -import Data.Util; +import io.com; +import data.address; +import data.string_; +import data.util; __gshared Log log; @@ -16,140 +16,140 @@ TODO: FIX THIS!!! */ enum LogLevel { - VERBOSE = '&', - DEBUG = '+', - INFO = '*', - WARNING = '#', - ERROR = '-', - FATAL = '!' + verbose = '&', + debug_ = '+', + info = '*', + warning = '#', + error = '-', + fatal = '!' } struct Log { private struct SymbolDef { align(1): - ulong Start; - ulong End; - ulong NameLength; + ulong start; + ulong end; + ulong nameLength; } private struct SymbolMap { align(1): - char[4] Magic; - ulong Count; - SymbolDef Symbols; + char[4] magic; + ulong count; + SymbolDef symbols; } - private int indent; - private bool enabled; - private SymbolMap* symbols; + private int _indent; + private bool _enabled; + private SymbolMap* _symbols; // XXX: Page fault if this is not wrapped like this! - static ulong Seconds() { - import HW.CMOS.CMOS : GetCMOS; + static ulong seconds() { + import hw.cmos.cmos : getCMOS; - return GetCMOS.TimeStamp(); + return getCMOS.timeStamp(); } - void Init() { - indent = 0; - enabled = true; + void init() { + _indent = 0; + _enabled = true; } - @property ref bool Enabled() return { - return enabled; + @property ref bool enabled() return { + return _enabled; } - void SetSymbolMap(VirtAddress address) { - SymbolMap* map = cast(SymbolMap*)address.Ptr; - if (map.Magic[0 .. 4] != "DSYM") + void setSymbolMap(VirtAddress address) { + SymbolMap* map = cast(SymbolMap*)address.ptr; + if (map.magic[0 .. 4] != "DSYM") return; - symbols = map; + _symbols = map; } void opCall(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(LogLevel level, Arg args) { char[ulong.sizeof * 8] buf; - if (!enabled) + if (!_enabled) return; - for (int i = 0; i < indent; i++) - COM1.Write(' '); + for (int i = 0; i < _indent; i++) + com1.write(' '); - COM1.Write('[', itoa(Seconds(), buf, 10), ']'); - COM1.Write('[', cast(char)level, "] ", file /*, ": ", func*/ , '@'); + com1.write('[', itoa(seconds(), buf, 10), ']'); + com1.write('[', cast(char)level, "] ", file /*, ": ", func*/ , '@'); - COM1.Write(itoa(line, buf, 10)); - COM1.Write("> "); + com1.write(itoa(line, buf, 10)); + com1.write("> "); mainloop: foreach (arg; args) { alias T = Unqual!(typeof(arg)); static if (is(T : const char[])) - COM1.Write(arg); + com1.write(arg); else static if (is(T == enum)) { - foreach (i, e; EnumMembers!T) + foreach (i, e; enumMembers!T) if (arg == e) { - COM1.Write(__traits(allMembers, T)[i]); + com1.write(__traits(allMembers, T)[i]); continue mainloop; } - COM1.Write("cast("); - COM1.Write(T.stringof); - COM1.Write(")"); - COM1.Write(itoa(cast(ulong)arg, buf, 10)); + com1.write("cast("); + com1.write(T.stringof); + com1.write(")"); + com1.write(itoa(cast(ulong)arg, buf, 10)); } else static if (is(T == BinaryInt)) { - COM1.Write("0b"); - COM1.Write(itoa(arg.Int, buf, 2)); + com1.write("0b"); + com1.write(itoa(arg.num, buf, 2)); } else static if (is(T : V*, V)) { - COM1.Write("0x"); - COM1.Write(itoa(cast(ulong)arg, buf, 16)); + com1.write("0x"); + com1.write(itoa(cast(ulong)arg, buf, 16)); } else static if (is(T == VirtAddress) || is(T == PhysAddress) || is(T == PhysAddress32)) { - COM1.Write("0x"); - COM1.Write(itoa(cast(ulong)arg.Int, buf, 16)); + com1.write("0x"); + com1.write(itoa(cast(ulong)arg.num, buf, 16)); } else static if (is(T == bool)) - COM1.Write((arg) ? "true" : "false"); + com1.write((arg) ? "true" : "false"); else static if (is(T : char)) - COM1.Write(arg); + com1.write(arg); else static if (isNumber!T) - COM1.Write(itoa(arg, buf, 10)); + com1.write(itoa(arg, buf, 10)); else static if (is(T : ubyte[])) { - COM1.Write("["); + com1.write("["); foreach (idx, a; arg) { if (idx) - COM1.Write(", "); - COM1.Write(itoa(a, buf, 16)); + com1.write(", "); + com1.write(itoa(a, buf, 16)); } - COM1.Write("]"); + com1.write("]"); } else static if (isFloating!T) - COM1.Write(dtoa(cast(double)arg, buf, 10)); + com1.write(dtoa(cast(double)arg, buf, 10)); else - COM1.Write("UNKNOWN TYPE '", T.stringof, "'"); + com1.write("UNKNOWN TYPE '", T.stringof, "'"); } - COM1.Write("\r\n"); + com1.write("\r\n"); } - void Verbose(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(Arg args) { - this.opCall!(file, func, line)(LogLevel.VERBOSE, args); + void verbose(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(Arg args) { + this.opCall!(file, func, line)(LogLevel.verbose, args); } - void Debug(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(Arg args) { - this.opCall!(file, func, line)(LogLevel.DEBUG, args); + void debug_(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(Arg args) { + this.opCall!(file, func, line)(LogLevel.debug_, args); } - void Info(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(Arg args) { - this.opCall!(file, func, line)(LogLevel.INFO, args); + void info(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(Arg args) { + this.opCall!(file, func, line)(LogLevel.info, args); } - void Warning(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(Arg args) { - this.opCall!(file, func, line)(LogLevel.WARNING, args); + void warning(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(Arg args) { + this.opCall!(file, func, line)(LogLevel.warning, args); } - void Error(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(Arg args) { - this.opCall!(file, func, line)(LogLevel.ERROR, args); + void error(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(Arg args) { + this.opCall!(file, func, line)(LogLevel.error, args); } - void Fatal(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(Arg args) { - this.opCall!(file, func, line)(LogLevel.FATAL, args); - PrintStackTrace(true); - import IO.TextMode : GetScreen; + void fatal(string file = __MODULE__, string func = __PRETTY_FUNCTION__, int line = __LINE__, Arg...)(Arg args) { + this.opCall!(file, func, line)(LogLevel.fatal, args); + printStackTrace(true); + import io.textmode : getScreen; - GetScreen.WriteStatus("\t\tFATAL ERROR, READ COM.LOG!"); + getScreen.writeStatus("\t\tFATAL ERROR, READ COM.LOG!"); asm { forever: hlt; @@ -157,8 +157,8 @@ struct Log { } } - void PrintStackTrace(bool skipFirst = false) { - COM1.Write("\r\nSTACKTRACE:\r\n"); + void printStackTrace(bool skipFirst = false) { + com1.write("\r\nSTACKTRACE:\r\n"); VirtAddress rbp; VirtAddress rip; asm { @@ -167,63 +167,63 @@ struct Log { if (skipFirst) { rip = rbp + ulong.sizeof; - rbp = VirtAddress(*rbp.Ptr!ulong); + rbp = VirtAddress(*rbp.ptr!ulong); } while (rbp && // rbp > 0xFFFF_FFFF_8000_0000 && rbp < 0xFFFF_FFFF_F000_0000 // XXX: Hax fix - && *rip.Ptr!ulong) { + && *rip.ptr!ulong) { rip = rbp + ulong.sizeof; - if (!*rip.Ptr!ulong) + if (!*rip.ptr!ulong) break; - import Task.Scheduler : currentProcess, TablePtr; + import task.scheduler : getScheduler, TablePtr; - TablePtr!(void)* page = currentProcess.threadState.paging.GetPage(rip); - if (!page || !page.Present) + TablePtr!(void)* page = getScheduler.currentProcess.threadState.paging.getPage(rip); + if (!page || !page.present) break; - COM1.Write("\t["); + com1.write("\t["); { char[ulong.sizeof * 8] buf; - COM1.Write("0x"); - COM1.Write(itoa(*rip.Ptr!ulong, buf, 16)); + com1.write("0x"); + com1.write(itoa(*rip.ptr!ulong, buf, 16)); } - COM1.Write("] "); + com1.write("] "); - struct func { + struct Func { string name; ulong diff; } - func getFuncName(ulong addr) { - if (!symbols) - return func("Unknown function", 0); + Func getFuncName(ulong addr) { + if (!_symbols) + return Func("Unknown function", 0); - SymbolDef* symbolDef = &symbols.Symbols; - for (int i = 0; i < symbols.Count; i++) { - if (symbolDef.Start <= addr && addr <= symbolDef.End) - return func(cast(string)(VirtAddress(symbolDef) + SymbolDef.sizeof) - .Ptr[0 .. symbolDef.NameLength], addr - symbolDef.Start); - symbolDef = cast(SymbolDef*)(VirtAddress(symbolDef) + SymbolDef.sizeof + symbolDef.NameLength).Ptr; + SymbolDef* symbolDef = &_symbols.symbols; + for (int i = 0; i < _symbols.count; i++) { + if (symbolDef.start <= addr && addr <= symbolDef.end) + return Func(cast(string)(VirtAddress(symbolDef) + SymbolDef.sizeof) + .ptr[0 .. symbolDef.nameLength], addr - symbolDef.start); + symbolDef = cast(SymbolDef*)(VirtAddress(symbolDef) + SymbolDef.sizeof + symbolDef.nameLength).ptr; } - return func("Symbol not in map!", 0); + return Func("Symbol not in map!", 0); } - func f = getFuncName(*rip.Ptr!ulong); + Func f = getFuncName(*rip.ptr!ulong); - COM1.Write(f.name); + com1.write(f.name); if (f.diff) { char[ulong.sizeof * 8] buf; - COM1.Write("+0x"); - COM1.Write(itoa(f.diff, buf, 16)); + com1.write("+0x"); + com1.write(itoa(f.diff, buf, 16)); } - COM1.Write("\r\n"); - rbp = VirtAddress(*rbp.Ptr!ulong); + com1.write("\r\n"); + rbp = VirtAddress(*rbp.ptr!ulong); } } diff --git a/kernel/src/io/port.d b/kernel/src/io/port.d index 9cb10fa..6c2fa5c 100644 --- a/kernel/src/io/port.d +++ b/kernel/src/io/port.d @@ -1,8 +1,8 @@ -module IO.Port; +module io.port; -import Data.Util; +import data.util; -T In(T = ubyte)(ushort port) { +T inp(T)(ushort port) { T ret; asm { mov DX, port; @@ -29,7 +29,7 @@ T In(T = ubyte)(ushort port) { return ret; } -void Out(T = ubyte)(ushort port, T d) { +void outp(T)(ushort port, T d) { uint data = d; asm { mov EAX, data; diff --git a/kernel/src/io/textmode.d b/kernel/src/io/textmode.d index c5a7320..7ae150b 100644 --- a/kernel/src/io/textmode.d +++ b/kernel/src/io/textmode.d @@ -1,58 +1,59 @@ -module IO.TextMode; +module io.textmode; -import IO.Port; -import Data.Util; -import Data.String; -import Data.TextBuffer; +import io.port; +import data.util; +import data.string_; +import data.textbuffer; enum Colors : ubyte { - Black = 0, - Blue = 1, - Green = 2, - Cyan = 3, - Red = 4, - Magenta = 5, - Brown = 6, - LightGrey = 7, - DarkGrey = 8, - LightBlue = 9, - LightGreen = 10, - LightCyan = 11, - LightRed = 12, - LightMagenta = 13, - Yellow = 14, - White = 15 + black = 0, + blue = 1, + green = 2, + cyan = 3, + red = 4, + magenta = 5, + brown = 6, + lightGrey = 7, + darkGrey = 8, + lightBlue = 9, + lightGreen = 10, + lightCyan = 11, + lightRed = 12, + lightMagenta = 13, + yellow = 14, + white = 15 } struct Color { - private ubyte color; + private ubyte _color; this(Colors fg, Colors bg) { - color = ((bg & 0xF) << 4) | (fg & 0xF); + _color = ((bg & 0xF) << 4) | (fg & 0xF); } - @property Colors Foreground() { - return cast(Colors)(color & 0xF); + @property Colors foreground() { + return cast(Colors)(_color & 0xF); } - @property Colors Foreground(Colors c) { - color = (color & 0xF0) | (c & 0xF); - return cast(Colors)(color & 0xF); + @property Colors foreground(Colors c) { + _color = (_color & 0xF0) | (c & 0xF); + return cast(Colors)(_color & 0xF); } - @property Colors Background() { - return cast(Colors)((color >> 4) & 0xF); + @property Colors background() { + return cast(Colors)((_color >> 4) & 0xF); } - @property Colors Background(Colors c) { - color = ((c & 0xF) << 4) | (color & 0xF); - return cast(Colors)((color >> 4) & 0xF); + @property Colors background(Colors c) { + _color = ((c & 0xF) << 4) | (_color & 0xF); + return cast(Colors)((_color >> 4) & 0xF); } } struct Screen(int w, int h) { - private struct slot { + private struct VideoSlot { + align(1): char ch; Color color; } @@ -60,203 +61,205 @@ struct Screen(int w, int h) { @disable this(); this(Colors fg, Colors bg, long videoMemory) { - this.screen = cast(slot[w * h]*)videoMemory; - this.x = 0; - this.y = 1; - this.color = Color(fg, bg); - this.enabled = true; + _screen = cast(VideoSlot[w * h]*)videoMemory; + _x = 0; + _y = 1; + _color = Color(fg, bg); + _enabled = true; } - void Clear() { - if (!enabled) + void clear() { + if (!_enabled) return; - foreach (ref slot slot; (*screen)[w .. $]) { + + foreach (ref VideoSlot slot; (*_screen)[w .. $]) { slot.ch = ' '; - slot.color = color; + slot.color = _color; } - x = 0; - y = 1; + _x = 0; + _y = 1; } - void Write(Slot[] slots) { - if (!enabled) + void write(Slot[] slots) { + if (!_enabled) return; foreach (slot; slots) - write(cast(char)slot.ch); - MoveCursor(); + _write(cast(char)slot.ch); + _moveCursor(); } - void WriteStatus(Args...)(Args args) { - if (!enabled) + void writeStatus(Args...)(Args args) { + if (!_enabled) return; - blockCursor++; - ubyte oldX = x; - ubyte oldY = y; - Color oldColor = color; - - x = y = 0; - color = Color(Colors.White, Colors.Red); - Write(args); - - while (x < w - 1) - write(' '); - write(' '); - - x = oldX; - y = oldY; - color = oldColor; - blockCursor--; + _blockCursor++; + ubyte oldX = _x; + ubyte oldY = _y; + Color oldColor = _color; + + _x = _y = 0; + _color = Color(Colors.white, Colors.red); + _write(args); + + while (_x < w - 1) + _write(' '); + _write(' '); + + _x = oldX; + _y = oldY; + _color = oldColor; + _blockCursor--; } - void MoveCursor() { - if (!enabled) + void _moveCursor() { + if (!_enabled) return; - if (blockCursor > 0) + if (_blockCursor > 0) return; - ushort pos = y * w + x; - Out!ubyte(0x3D4, 14); - Out!ubyte(0x3D5, pos >> 8); - Out!ubyte(0x3D4, 15); - Out!ubyte(0x3D5, cast(ubyte)pos); + ushort pos = _y * w + _x; + outp!ubyte(0x3D4, 14); + outp!ubyte(0x3D5, pos >> 8); + outp!ubyte(0x3D4, 15); + outp!ubyte(0x3D5, cast(ubyte)pos); } - @property ref Color CurrentColor() { - return color; + @property ref Color currentColor() { + return _color; } - @property ref bool Enabled() { - return enabled; + @property ref bool enabled() { + return _enabled; } private: - slot[w * h]* screen; - bool enabled; - ubyte x, y; - Color color; - int blockCursor; - - void write(char ch) { + VideoSlot[w * h]* _screen; + bool _enabled; + ubyte _x; + ubyte _y; + Color _color; + int _blockCursor; + + void _realWrite(char ch) { if (ch == '\n') { - y++; - x = 0; + _y++; + _x = 0; } else if (ch == '\r') - x = 0; + _x = 0; else if (ch == '\b') { - if (x) - x--; + if (_x) + _x--; } else if (ch == '\t') { - uint goal = (x + 8) & ~7; - for (; x < goal; x++) - (*screen)[y * w + x] = slot(' ', color); - if (x >= w) { - y++; - x %= w; + uint goal = (_x + 8) & ~7; + for (; _x < goal; _x++) + (*_screen)[_y * w + _x] = VideoSlot(' ', _color); + if (_x >= w) { + _y++; + _x %= w; } } else { - (*screen)[y * w + x] = slot(ch, color); - x++; + (*_screen)[_y * w + _x] = VideoSlot(ch, _color); + _x++; - if (x >= w) { - y++; - x = 0; + if (_x >= w) { + _y++; + _x = 0; } } - if (y >= h) { + if (_y >= h) { for (int yy = 1; yy < h - 1; yy++) for (int xx = 0; xx < w; xx++) - (*screen)[yy * w + xx] = (*screen)[(yy + 1) * w + xx]; + (*_screen)[yy * w + xx] = (*_screen)[(yy + 1) * w + xx]; - y--; + _y--; for (int xx = 0; xx < w; xx++) { - auto slot = &(*screen)[y * w + xx]; + auto slot = &(*_screen)[_y * w + xx]; slot.ch = ' '; - slot.color = Color(Colors.Cyan, Colors.Black); //XXX: Stupid hack to fix colors while scrolling + slot.color = Color(Colors.cyan, Colors.black); //XXX: Stupid hack to fix colors while scrolling } } - MoveCursor(); + _moveCursor(); } - void Write(char ch) { - if (!enabled) + void _write(char ch) { + if (!_enabled) return; - write(ch); - MoveCursor(); + _realWrite(ch); + _moveCursor(); } - void Write(in char[] str) { - if (!enabled) + void _write(in char[] str) { + if (!_enabled) return; foreach (char ch; str) - write(ch); - MoveCursor(); + _realWrite(ch); + _moveCursor(); } - void Write(char* str) { - if (!enabled) + void _write(char* str) { + if (!_enabled) return; while (*str) - write(*(str++)); - MoveCursor(); + _realWrite(*(str++)); + _moveCursor(); } - void WriteNumber(S = int)(S value, uint base) if (isNumber!S) { - if (!enabled) + void _writeNumber(S = int)(S value, uint base) if (isNumber!S) { + if (!_enabled) return; char[S.sizeof * 8] buf; - Write(itoa(value, buf, base)); + _write(itoa(value, buf, base)); } - void WriteEnum(T)(T value) if (is(T == enum)) { - if (!enabled) + void _writeEnum(T)(T value) if (is(T == enum)) { + if (!_enabled) return; - foreach (i, e; EnumMembers!T) + foreach (i, e; enumMembers!T) if (value == e) { - Write(__traits(allMembers, T)[i]); + _write(__traits(allMembers, T)[i]); return; } - Write("cast(", T.stringof, ")", value); + _write("cast(", T.stringof, ")", value); } - void Write(Args...)(Args args) { - if (!enabled) + void _write(Args...)(Args args) { + if (!_enabled) return; - blockCursor++; + _blockCursor++; foreach (arg; args) { alias T = Unqual!(typeof(arg)); static if (is(T : const char[])) - Write(arg); + _write(arg); else static if (is(T == BinaryInt)) { - Write("0b"); - WriteNumber(cast(ulong)arg, 2); + _write("0b"); + _writeNumber(cast(ulong)arg, 2); } else static if (is(T : V*, V)) { - Write("0x"); - WriteNumber(cast(ulong)arg, 16); + _write("0x"); + _writeNumber(cast(ulong)arg, 16); } else static if (is(T == enum)) - WriteEnum(arg); + _writeEnum(arg); else static if (is(T == bool)) - Write((arg) ? "true" : "false"); + _write((arg) ? "true" : "false"); else static if (is(T : char)) write(arg); else static if (isNumber!T) - WriteNumber(arg, 10); + _writeNumber(arg, 10); else - Write("UNKNOWN TYPE '", T.stringof, "'"); + _write("UNKNOWN TYPE '", T.stringof, "'"); } - blockCursor--; - MoveCursor(); + _blockCursor--; + _moveCursor(); } - void Writeln(Args...)(Args args) { - if (!enabled) + void _writeln(Args...)(Args args) { + if (!_enabled) return; - blockCursor++; - Write(args, '\n'); - blockCursor--; - MoveCursor(); + _blockCursor++; + _write(args, '\n'); + _blockCursor--; + _moveCursor(); } } -__gshared Screen!(80, 25) GetScreen = Screen!(80, 25)(Colors.Cyan, Colors.Black, 0xFFFF_FFFF_800B_8000); +__gshared Screen!(80, 25) getScreen = Screen!(80, 25)(Colors.cyan, Colors.black, 0xFFFF_FFFF_800B_8000); diff --git a/kernel/src/kmain.d b/kernel/src/kmain.d index 96d05d9..1776175 100644 --- a/kernel/src/kmain.d +++ b/kernel/src/kmain.d @@ -1,4 +1,4 @@ -module KMain; +module kmain; version (PowerNex) { // Good job, you are now able to compile PowerNex! @@ -6,189 +6,197 @@ version (PowerNex) { static assert(0, "Please use the customized toolchain located here: http://wild.tk/PowerNex-Env.tar.xz"); } -import IO.COM; -import IO.Log; -import IO.Keyboard; -import IO.FS; -import CPU.GDT; -import CPU.IDT; -import CPU.PIT; -import Data.Color; -import Data.Multiboot; -import HW.PS2.Keyboard; -import Memory.Paging; -import Memory.FrameAllocator; -import Data.Linker; -import Data.Address; -import Memory.Heap; -import Task.Scheduler; -import ACPI.RSDP; -import HW.PCI.PCI; -import HW.CMOS.CMOS; -import System.SyscallHandler; -import Data.TextBuffer : scr = GetBootTTY; -import Data.ELF; -import IO.ConsoleManager; -import IO.FS.IO.Console; - -immutable uint major = __VERSION__ / 1000; -immutable uint minor = __VERSION__ % 1000; +import io.com; +import io.log; +import io.fs; +import cpu.gdt; +import cpu.idt; +import cpu.pit; +import data.color; +import data.multiboot; +import hw.ps2.keyboard; +import memory.paging; +import memory.frameallocator; +import data.linker; +import data.address; +import memory.heap; +import task.scheduler; +import acpi.rsdp; +import hw.pci.pci; +import hw.cmos.cmos; +import system.syscallhandler; +import data.textbuffer : scr = getBootTTY; +import data.elf; +import io.consolemanager; +import io.fs.io.console; + +private immutable uint _major = __VERSION__ / 1000; +private immutable uint _minor = __VERSION__ % 1000; __gshared FSRoot rootFS; extern (C) int kmain(uint magic, ulong info) { - PreInit(); - Welcome(); - Init(magic, info); + preInit(); + welcome(); + init(magic, info); asm { sti; } - string initFile = "/Binary/Init"; + string initFile = "/bin/init"; - ELF init = new ELF(cast(FileNode)rootFS.Root.FindNode(initFile)); - if (init.Valid) { - scr.Writeln(initFile, " is valid! Loading..."); + ELF init = new ELF(cast(FileNode)rootFS.root.findNode(initFile)); + if (init.valid) { + scr.writeln(initFile, " is valid! Loading..."); - scr.Writeln(); - scr.Foreground = Color(255, 255, 0); - init.MapAndRun([initFile]); + scr.writeln(); + scr.foreground = Color(255, 255, 0); + init.mapAndRun([initFile]); } else { - scr.Writeln("Invalid ELF64 file"); - log.Fatal("Invalid ELF64 file!"); + scr.writeln("Invalid ELF64 file"); + log.fatal("Invalid ELF64 file!"); } - scr.Foreground = Color(255, 0, 255); - scr.Background = Color(255, 255, 0); - scr.Writeln("kmain functions has exited!"); - log.Fatal("kmain functions has exited!"); + scr.foreground = Color(255, 0, 255); + scr.background = Color(255, 255, 0); + scr.writeln("kmain functions has exited!"); + log.fatal("kmain functions has exited!"); return 0; } -void BootTTYToTextmode(size_t start, size_t end) { - import IO.TextMode; +void bootTTYToTextmode(size_t start, size_t end) { + import io.textmode; if (start == -1 && end == -1) - GetScreen.Clear(); + getScreen.clear(); else - GetScreen.Write(scr.Buffer[start .. end]); + getScreen.write(scr.buffer[start .. end]); } -void PreInit() { - import IO.TextMode; - - COM.Init(); +void preInit() { + import io.textmode; + COM.init(); scr; - scr.OnChangedCallback = &BootTTYToTextmode; - GetScreen.Clear(); + scr.onChangedCallback = &bootTTYToTextmode; + getScreen.clear(); - scr.Writeln("ACPI initializing..."); - rsdp.Init(); + scr.writeln("ACPI initializing..."); + rsdp.init(); - scr.Writeln("CMOS initializing..."); - GetCMOS(); + scr.writeln("CMOS initializing..."); + getCMOS(); - scr.Writeln("Log initializing..."); - log.Init(); + scr.writeln("Log initializing..."); + log.init(); - scr.Writeln("GDT initializing..."); - GDT.Init(); + scr.writeln("GDT initializing..."); + GDT.init(); - scr.Writeln("IDT initializing..."); - IDT.Init(); + scr.writeln("IDT initializing..."); + IDT.init(); - scr.Writeln("Syscall Handler initializing..."); - SyscallHandler.Init(); + scr.writeln("Syscall Handler initializing..."); + SyscallHandler.init(); - scr.Writeln("PIT initializing..."); - PIT.Init(); + scr.writeln("PIT initializing..."); + PIT.init(); - scr.Writeln("Keyboard initializing..."); - PS2Keyboard.Init(); + scr.writeln("Keyboard initializing..."); + PS2Keyboard.init(); } -void Welcome() { - scr.Writeln("Welcome to PowerNex!"); - scr.Writeln("\tThe number one D kernel!"); - scr.Writeln("Compiled using '", __VENDOR__, "', D version ", major, ".", minor, "\n"); +void welcome() { + scr.writeln("Welcome to PowerNex!"); + scr.writeln("\tThe number one D kernel!"); + scr.writeln("Compiled using '", __VENDOR__, "', D version ", _major, ".", _minor, "\n"); - log.Info("Welcome to PowerNex's serial console!"); - log.Info("Compiled using '", __VENDOR__, "', D version ", major, ".", minor, "\n"); + log.info("Welcome to PowerNex's serial console!"); + log.info("Compiled using '", __VENDOR__, "', D version ", _major, ".", _minor, "\n"); } -void Init(uint magic, ulong info) { - scr.Writeln("Multiboot parsing..."); - Multiboot.ParseHeader(magic, info); +void init(uint magic, ulong info) { + scr.writeln("Multiboot parsing..."); + log.info("Multiboot parsing..."); + Multiboot.parseHeader(magic, info); - scr.Writeln("FrameAllocator initializing..."); - FrameAllocator.Init(); + scr.writeln("FrameAllocator initializing..."); + log.info("FrameAllocator initializing..."); + FrameAllocator.init(); - scr.Writeln("Paging initializing..."); - GetKernelPaging.RemoveUserspace(false); // Removes all mapping that are not needed for the kernel - GetKernelPaging.Install(); + scr.writeln("Paging initializing..."); + log.info("Paging initializing..."); + getKernelPaging.removeUserspace(false); // Removes all mapping that are not needed for the kernel + getKernelPaging.install(); - scr.Writeln("Heap initializing..."); - GetKernelHeap; + scr.writeln("Heap initializing..."); + log.info("Heap initializing..."); + getKernelHeap; - scr.Writeln("PCI initializing..."); - GetPCI; + scr.writeln("PCI initializing..."); + log.info("PCI initializing..."); + getPCI; - scr.Writeln("Initrd initializing..."); - LoadInitrd(); + scr.writeln("Initrd initializing..."); + log.info("Initrd initializing..."); + loadInitrd(); - scr.Writeln("Starting ConsoleManager..."); - GetConsoleManager.Init(); + scr.writeln("Starting ConsoleManager..."); + log.info("Starting ConsoleManager..."); + getConsoleManager.init(); - scr.Writeln("Scheduler initializing..."); - GetScheduler.Init(); + scr.writeln("Scheduler initializing..."); + log.info("Scheduler initializing..."); + getScheduler.init(); } -void LoadInitrd() { - import IO.FS; - import IO.FS.Initrd; - import IO.FS.System; - import IO.FS.IO; +void loadInitrd() { + import io.fs; + import io.fs.initrd; + import io.fs.system; + import io.fs.io; - auto initrd = Multiboot.GetModule("initrd"); + auto initrd = Multiboot.getModule("initrd"); if (initrd[0] == initrd[1]) { - scr.Writeln("Initrd missing"); - log.Error("Initrd missing"); + scr.writeln("Initrd missing"); + log.error("Initrd missing"); return; } void mount(string path, FSRoot fs) { - Node mp = rootFS.Root.FindNode(path); + Node mp = rootFS.root.findNode(path); if (mp && !cast(DirectoryNode)mp) { - log.Error(path, " is not a DirectoryNode!"); + log.error(path, " is not a DirectoryNode!"); return; } if (!mp) { - mp = new DirectoryNode(NodePermissions.DefaultPermissions); - mp.Name = path[1 .. $]; - mp.Root = rootFS; - mp.Parent = rootFS.Root; + mp = new DirectoryNode(NodePermissions.defaultPermissions); + mp.name = path[1 .. $]; //XXX: + mp.root = rootFS; + mp.parent = rootFS.root; } DirectoryNode mpDir = cast(DirectoryNode)mp; - mpDir.Parent.Mount(mpDir, fs); + mpDir.parent.mount(mpDir, fs); } rootFS = new InitrdFSRoot(initrd[0]); - Node file = rootFS.Root.FindNode("/Data/PowerNex.map"); + Node file = rootFS.root.findNode("/data/powernex.map"); if (!file) { - log.Warning("Could not find the symbol file!"); + log.warning("Could not find the symbol file!"); return; } InitrdFileNode symbols = cast(InitrdFileNode)file; if (!symbols) { - log.Error("Symbol file is not of the type InitrdFileNode! It's a ", typeid(file).name); + log.error("Symbol file is not of the type InitrdFileNode! It's a ", typeid(file).name); return; } - log.SetSymbolMap(VirtAddress(symbols.RawAccess.ptr)); - log.Info("Successfully loaded symbols!"); + log.setSymbolMap(VirtAddress(symbols.rawAccess.ptr)); + log.info("Successfully loaded symbols!"); - mount("/IO", new IOFSRoot()); - mount("/System", new SystemFSRoot()); + log.info("Mounting /io!"); + mount("/io", new IOFSRoot()); + log.info("Mounting /system!"); + mount("/system", new SystemFSRoot()); } diff --git a/kernel/src/memory/frameallocator.d b/kernel/src/memory/frameallocator.d index e9b8f66..b59bc31 100644 --- a/kernel/src/memory/frameallocator.d +++ b/kernel/src/memory/frameallocator.d @@ -1,70 +1,70 @@ -module Memory.FrameAllocator; +module memory.frameallocator; -import Data.Address; -import IO.Log; -import Data.Linker; -import Data.Multiboot; +import data.address; +import io.log; +import data.linker; +import data.multiboot; static struct FrameAllocator { public: - static void Init() { - neverFreeBelow = PhysAddress((Linker.KernelEnd - Linker.KernelStart + Linker.KernelPhysStart.Int).Int); - log.Warning("neverFreeBelow: ", neverFreeBelow); + static void init() { + _neverFreeBelow = PhysAddress((Linker.kernelEnd - Linker.kernelStart + Linker.kernelPhysStart.num).num); + log.warning("_neverFreeBelow: ", _neverFreeBelow); - maxFrames = Multiboot.MemorySize / 4; - foreach (ref ulong frame; preallocated) + _maxFrames = Multiboot.memorySize / 4; + foreach (ref ulong frame; _preallocated) frame = ulong.max; - const ulong kernelUsedAmount = neverFreeBelow.Int / 0x1000; + const ulong kernelUsedAmount = _neverFreeBelow.num / 0x1000; for (ulong i = 0; i < (kernelUsedAmount / 64) + 1; i++) { - bitmaps[i] = ulong.max; - usedFrames += 64; + _bitmaps[i] = ulong.max; + _usedFrames += 64; } - auto maps = Multiboot.MemoryMap; - for (ulong i = 0; i < Multiboot.MemoryMapCount; i++) { + auto maps = Multiboot.memoryMap; + for (ulong i = 0; i < Multiboot.memoryMapCount; i++) { auto m = maps[i]; - if (m.Type != MultibootMemoryType.Available) { - log.Debug("Address: ", cast(void*)m.Address, " Size: ", m.Length, " Frames: ", m.Length / 0x1000); - for (ulong j = 0; j < m.Length / 0x1000; j++) - MarkFrame(m.Address / 0x1000 + j); + if (m.type != MultibootMemoryType.available) { + log.debug_("Address: ", cast(void*)m.address, " Size: ", m.length, " Frames: ", m.length / 0x1000); + for (ulong j = 0; j < m.length / 0x1000; j++) + markFrame(m.address / 0x1000 + j); } } // Mark ACPI frames for (ulong i = 0xE0000; i < 0x100000; i += 0x1000) - MarkFrame(i / 0x1000); + markFrame(i / 0x1000); - foreach (mod; Multiboot.Modules[0 .. Multiboot.ModulesCount]) - for (ulong i = mod.ModStart; i < mod.ModEnd; i += 0x1000) - MarkFrame(i / 0x1000); + foreach (mod; Multiboot.modules[0 .. Multiboot.modulesCount]) + for (ulong i = mod.modStart; i < mod.modEnd; i += 0x1000) + markFrame(i / 0x1000); - allocPreAlloc(); // Add some nodes to preallocated + _allocPreAlloc(); // Add some nodes to _preallocated } - static void MarkFrame(ulong idx) { - foreach (ref ulong frame; preallocated) + static void markFrame(ulong idx) { + foreach (ref ulong frame; _preallocated) if (frame == idx) { frame = ulong.max; return; } const ulong bitmapIdx = idx / 64; - assert(bitmapIdx < bitmaps.length); + assert(bitmapIdx < _bitmaps.length); const ulong bitIdx = idx % 64; - ulong* bitmap = &(bitmaps[bitmapIdx]); + ulong* bitmap = &(_bitmaps[bitmapIdx]); if (!(*bitmap & (1UL << bitIdx))) { - if (idx < maxFrames) - usedFrames++; + if (idx < _maxFrames) + _usedFrames++; *bitmap |= (1UL << bitIdx); } } - static ulong GetFrame() { - ulong getFrame(bool tryAgain) { - foreach (idx, ref ulong frame; preallocated) { + static ulong getFrame() { + ulong getFrameImpl(bool tryAgain) { + foreach (idx, ref ulong frame; _preallocated) { if (frame != ulong.max) { const ulong ret = frame; frame = ulong.max; @@ -73,131 +73,131 @@ public: } if (tryAgain) { - allocPreAlloc(); - return getFrame(false); + _allocPreAlloc(); + return getFrameImpl(false); } bool hasSpacePrealloc = false; - foreach (ulong frame; preallocated) + foreach (ulong frame; _preallocated) hasSpacePrealloc |= frame != ulong.max; bool hasSpaceBitmap = false; - for (ulong i = 0; i < maxFrames && !hasSpaceBitmap; i++) { + for (ulong i = 0; i < _maxFrames && !hasSpaceBitmap; i++) { const ulong bitmapIdx = i / 64; - assert(bitmapIdx < bitmaps.length); + assert(bitmapIdx < _bitmaps.length); const ulong bitIdx = i % 64; - hasSpaceBitmap |= !(bitmaps[bitmapIdx] & (1UL << bitIdx)); + hasSpaceBitmap |= !(_bitmaps[bitmapIdx] & (1UL << bitIdx)); } return 0; } - return getFrame(true); + return getFrameImpl(true); } - static void FreeFrame(ulong idx) { + static void freeFrame(ulong idx) { if (idx == 0) return; - foreach (ref ulong frame; preallocated) + foreach (ref ulong frame; _preallocated) if (frame == ulong.max) { frame = idx; return; } ulong bitmapIdx = idx / 64; - assert(bitmapIdx < bitmaps.length); + assert(bitmapIdx < _bitmaps.length); const ulong bitIdx = idx % 64; - bitmaps[bitmapIdx] &= ~(1UL << bitIdx); - if (idx < maxFrames) - usedFrames--; + _bitmaps[bitmapIdx] &= ~(1UL << bitIdx); + if (idx < _maxFrames) + _usedFrames--; - if (bitmapIdx < currentBitmapIdx) - currentBitmapIdx = bitmapIdx; + if (bitmapIdx < _currentBitmapIdx) + _currentBitmapIdx = bitmapIdx; } - static PhysAddress Alloc() { - return PhysAddress(GetFrame() << 12); + static PhysAddress alloc() { + return PhysAddress(getFrame() << 12); } /// Allocates 512 frames, returns the first one - static PhysAddress Alloc512() { + static PhysAddress alloc512() { ulong firstGood; ulong count; - while (currentBitmapIdx < maxFrames) { - if (bitmaps[currentBitmapIdx]) + while (_currentBitmapIdx < _maxFrames) { + if (_bitmaps[_currentBitmapIdx]) count = 0; else count++; if (count == 1) - firstGood = currentBitmapIdx; + firstGood = _currentBitmapIdx; else if (count == 8) break; - currentBitmapIdx++; + _currentBitmapIdx++; } if (count < 8) return PhysAddress(0); foreach (idx; 0 .. 8) - bitmaps[firstGood + idx] = ulong.max; + _bitmaps[firstGood + idx] = ulong.max; return PhysAddress((firstGood * 64) << 12); } - static void Free(PhysAddress memory) { - if (memory > neverFreeBelow) - FreeFrame(memory.Int / 0x1000); + static void free(PhysAddress memory) { + if (memory > _neverFreeBelow) + freeFrame(memory.num / 0x1000); } - @property static ulong MaxFrames() { - return maxFrames; + @property static ulong maxFrames() { + return _maxFrames; } - @property static ulong UsedFrames() { - return usedFrames; + @property static ulong usedFrames() { + return _usedFrames; } private: - enum ulong maxmem = 0x100_0000_0000 - 1; //pow(2, 40) + enum ulong _maxmem = 0x100_0000_0000 - 1; //pow(2, 40) - __gshared PhysAddress neverFreeBelow; - __gshared ulong maxFrames; - __gshared ulong usedFrames; - __gshared ulong[((maxmem / 8) / 0x1000) / 64 + 1] bitmaps; - __gshared ulong currentBitmapIdx; - __gshared ulong[1] preallocated; + __gshared PhysAddress _neverFreeBelow; + __gshared ulong _maxFrames; + __gshared ulong _usedFrames; + __gshared ulong[((_maxmem / 8) / 0x1000) / 64 + 1] _bitmaps; + __gshared ulong _currentBitmapIdx; + __gshared ulong[1] _preallocated; - static void allocPreAlloc() { + static void _allocPreAlloc() { bool reseted = false; - foreach (ref ulong frame; preallocated) { + foreach (ref ulong frame; _preallocated) { if (frame != ulong.max) continue; - while (bitmaps[currentBitmapIdx] == ulong.max) { - assert(currentBitmapIdx < bitmaps.length); - if (currentBitmapIdx != 0 && (currentBitmapIdx - 1) * 64 >= maxFrames) { + while (_bitmaps[_currentBitmapIdx] == ulong.max) { + assert(_currentBitmapIdx < _bitmaps.length); + if (_currentBitmapIdx != 0 && (_currentBitmapIdx - 1) * 64 >= _maxFrames) { if (reseted) - return; // The error will be handled in GetFrame() + return; // The error will be handled in getFrame() reseted = true; - currentBitmapIdx = 0; + _currentBitmapIdx = 0; } else - currentBitmapIdx++; + _currentBitmapIdx++; } - ulong* bitmap = &(bitmaps[currentBitmapIdx]); + ulong* bitmap = &(_bitmaps[_currentBitmapIdx]); for (ulong i = 0; i < 64; i++) { if (!(*bitmap & (1UL << i))) { - const ulong frameID = currentBitmapIdx * 64 + i; - if (frameID < maxFrames) { + const ulong frameID = _currentBitmapIdx * 64 + i; + if (frameID < _maxFrames) { frame = frameID; *bitmap |= (1UL << i); - usedFrames++; + _usedFrames++; } break; } diff --git a/kernel/src/memory/heap.d b/kernel/src/memory/heap.d index a8cae30..805e9c6 100644 --- a/kernel/src/memory/heap.d +++ b/kernel/src/memory/heap.d @@ -1,168 +1,168 @@ -module Memory.Heap; +module memory.heap; -import Memory.Paging; -import Data.Linker; -import Data.Address; -import IO.Log; -import CPU.IDT; -import Data.Register; -import Task.Mutex.SpinLockMutex; -import Data.BitField; +import memory.paging; +import data.linker; +import data.address; +import io.log; +import cpu.idt; +import data.register; +import task.mutex.spinlockmutex; +import data.bitfield; -enum ulong MAGIC = 0xDEAD_BEEF_DEAD_C0DE; +private enum ulong _magic = 0xDEAD_BEEF_DEAD_C0DE; private struct MemoryHeader { ulong magic; MemoryHeader* prev; MemoryHeader* next; private ulong data; - mixin(Bitfield!(data, "isAllocated", 1, "size", 63)); + mixin(bitfield!(data, "isAllocated", 1, "size", 63)); } class Heap { public: this(Paging paging, MapMode mode, VirtAddress startAddr, VirtAddress maxAddr) { - this.paging = paging; - this.mode = mode; - this.startAddr = this.endAddr = startAddr; - this.maxAddr = maxAddr; - this.root = null; - this.end = null; - - addNewPage(); - root = end; // 'end' will be the latest allocated page + _paging = paging; + _mode = mode; + _startAddr = _endAddr = startAddr; + _maxAddr = maxAddr; + _root = null; + _end = null; + + _addNewPage(); + _root = _end; // 'end' will be the latest allocated page } this(Heap other) { assert(other); - this.paging = other.paging; - this.mode = other.mode; - this.startAddr = other.startAddr; - this.endAddr = other.endAddr; - this.maxAddr = other.maxAddr; - this.root = other.root; - this.end = other.end; + _paging = other._paging; + _mode = other._mode; + _startAddr = other._startAddr; + _endAddr = other._endAddr; + _maxAddr = other._maxAddr; + _root = other._root; + _end = other._end; } ~this() { - for (VirtAddress start = startAddr; start < endAddr; start += 0x1000) - paging.UnmapAndFree(start); + for (VirtAddress start = _startAddr; start < _endAddr; start += 0x1000) + _paging.unmapAndFree(start); } - void* Alloc(ulong size) { - mutex.Lock; + void* alloc(ulong size) { + _mutex.lock; if (!size) return null; - MemoryHeader* freeChunk = root; + MemoryHeader* freeChunk = _root; size += MinimalChunkSize - (size % MinimalChunkSize); // Good alignment maybe? while (freeChunk && (freeChunk.isAllocated || freeChunk.size < size)) freeChunk = freeChunk.next; while (!freeChunk || freeChunk.size < size) { // We are currently at the end chunk - if (!addNewPage()) { // This will work just because there is combine in addNewPage, which will increase the current chunks size - mutex.Unlock; + if (!_addNewPage()) { // This will work just because there is _combine in _addNewPage, which will increase the current chunks size + _mutex.unlock; return null; } - freeChunk = end; // Don't expected that freeChunk is valid, addNewPage runs combine + freeChunk = _end; // Don't expected that freeChunk is valid, _addNewPage runs _combine } - split(freeChunk, size); // Make sure that we don't give away to much memory + _split(freeChunk, size); // Make sure that we don't give away to much memory freeChunk.isAllocated = true; - mutex.Unlock; - return (VirtAddress(freeChunk) + MemoryHeader.sizeof).Ptr; + _mutex.unlock; + return (VirtAddress(freeChunk) + MemoryHeader.sizeof).ptr; } - void Free(void* addr) { - mutex.Lock; + void free(void* addr) { + _mutex.lock; if (!addr) return; - MemoryHeader* hdr = cast(MemoryHeader*)(VirtAddress(addr) - MemoryHeader.sizeof).Ptr; + MemoryHeader* hdr = cast(MemoryHeader*)(VirtAddress(addr) - MemoryHeader.sizeof).ptr; hdr.isAllocated = false; - combine(hdr); + _combine(hdr); - mutex.Unlock; + _mutex.unlock; } - void* Realloc(void* addr, ulong size) { - void* newMem = Alloc(size); - mutex.Lock; + void* realloc(void* addr, ulong size) { + void* newMem = alloc(size); + _mutex.lock; if (addr) { - MemoryHeader* old = cast(MemoryHeader*)(VirtAddress(addr) - MemoryHeader.sizeof).Ptr; + MemoryHeader* old = cast(MemoryHeader*)(VirtAddress(addr) - MemoryHeader.sizeof).ptr; ubyte* src = cast(ubyte*)addr; ubyte* dest = cast(ubyte*)newMem; for (ulong i = 0; i < old.size && i < size; i++) dest[i] = src[i]; - mutex.Unlock; - Free(addr); + _mutex.unlock; + free(addr); } return newMem; } - void PrintLayout() { - for (MemoryHeader* start = root; start; start = start.next) { - log.Info("address: ", start, "\tmagic: ", cast(void*)start.magic, "\thasPrev: ", !!start.prev, + void printLayout() { + for (MemoryHeader* start = _root; start; start = start.next) { + log.info("address: ", start, "\tmagic: ", cast(void*)start.magic, "\thasPrev: ", !!start.prev, "\thasNext: ", !!start.next, "\tisAllocated: ", !!start.isAllocated, "\tsize: ", start.size, "\tnext: ", start.next); - if (start.magic != MAGIC) - log.Fatal("====MAGIC IS WRONG===="); + if (start.magic != _magic) + log.fatal("====MAGIC IS WRONG===="); } - log.Info("\n\n"); + log.info("\n\n"); } - @property ref ulong RefCounter() { - return refCounter; + @property ref ulong refCounter() { + return _refCounter; } private: enum MinimalChunkSize = 32; /// Without header - SpinLockMutex mutex; - Paging paging; - MapMode mode; - MemoryHeader* root; /// Stores the first MemoryHeader - MemoryHeader* end; /// Stores the last MemoryHeader - VirtAddress startAddr; /// The start address of all the allocated data - VirtAddress endAddr; /// The end address of all the allocated data - VirtAddress maxAddr; /// The max address that can be allocated - ulong refCounter; + SpinLockMutex _mutex; + Paging _paging; + MapMode _mode; + MemoryHeader* _root; /// Stores the first MemoryHeader + MemoryHeader* _end; /// Stores the last MemoryHeader + VirtAddress _startAddr; /// The start address of all the allocated data + VirtAddress _endAddr; /// The end address of all the allocated data + VirtAddress _maxAddr; /// The max address that can be allocated + ulong _refCounter; /// Map and add a new page to the list - bool addNewPage() { - MemoryHeader* oldEnd = end; + bool _addNewPage() { + MemoryHeader* oldEnd = _end; - if (endAddr >= maxAddr - 0x1000 /* Do I need this? */ ) + if (_endAddr >= _maxAddr - 0x1000 /* Do I need this? */ ) return false; - if (paging.MapFreeMemory(endAddr, mode).Int == 0) + if (_paging.mapFreeMemory(_endAddr, _mode).num == 0) return false; - _memset64(endAddr.Ptr, 0, 0x1000 / ulong.sizeof); //Defined in object.d + _memset64(_endAddr.ptr, 0, 0x1000 / ulong.sizeof); //Defined in object.d - end = cast(MemoryHeader*)endAddr.Ptr; - *end = MemoryHeader.init; - end.magic = MAGIC; - endAddr += 0x1000; + _end = cast(MemoryHeader*)_endAddr.ptr; + *_end = MemoryHeader.init; + _end.magic = _magic; + _endAddr += 0x1000; - end.prev = oldEnd; + _end.prev = oldEnd; if (oldEnd) - oldEnd.next = end; + oldEnd.next = _end; - end.size = 0x1000 - MemoryHeader.sizeof; - end.next = null; - end.isAllocated = false; + _end.size = 0x1000 - MemoryHeader.sizeof; + _end.next = null; + _end.isAllocated = false; - combine(end); // Combine with other nodes if possible + _combine(_end); // Combine with other nodes if possible return true; } /// 'chunk' should not be expected to be valid after this - MemoryHeader* combine(MemoryHeader* chunk) { + MemoryHeader* _combine(MemoryHeader* chunk) { MemoryHeader* freeChunk = chunk; ulong sizeGain = 0; @@ -179,7 +179,7 @@ private: freeChunk.next.prev = freeChunk; *chunk = MemoryHeader.init; // Set the old header to zero - chunk.magic = MAGIC; + chunk.magic = _magic; chunk = freeChunk; } @@ -199,16 +199,16 @@ private: } if (!chunk.next) - end = chunk; + _end = chunk; return chunk; } /// It will only split if it can, chunk will always be approved to be allocated after the call this this function. - void split(MemoryHeader* chunk, ulong size) { + void _split(MemoryHeader* chunk, ulong size) { if (chunk.size >= size + ( /* The smallest chunk size */ MemoryHeader.sizeof + MinimalChunkSize)) { - MemoryHeader* newChunk = cast(MemoryHeader*)(VirtAddress(chunk) + MemoryHeader.sizeof + size).Ptr; - newChunk.magic = MAGIC; + MemoryHeader* newChunk = cast(MemoryHeader*)(VirtAddress(chunk) + MemoryHeader.sizeof + size).ptr; + newChunk.magic = _magic; newChunk.prev = chunk; newChunk.next = chunk.next; chunk.next = newChunk; @@ -217,49 +217,49 @@ private: chunk.size = size; if (!newChunk.next) - end = newChunk; + _end = newChunk; } } } /// Get the kernel heap object -Heap GetKernelHeap() { - import Data.Util : InplaceClass; +Heap getKernelHeap() { + import data.util : inplaceClass; __gshared ubyte[__traits(classInstanceSize, Heap)] data; __gshared Heap kernelHeap; if (!kernelHeap) { - kernelHeap = InplaceClass!Heap(data, GetKernelPaging, MapMode.DefaultUser, Linker.KernelEnd, VirtAddress(ulong.max)); - IDT.Register(InterruptType.PageFault, &onPageFault); + kernelHeap = inplaceClass!Heap(data, getKernelPaging, MapMode.defaultUser, Linker.kernelEnd, VirtAddress(ulong.max)); + IDT.register(InterruptType.pageFault, &_onPageFault); } return kernelHeap; } -private void onPageFault(Registers* regs) { - import Data.TextBuffer : scr = GetBootTTY; - import IO.Log; +private void _onPageFault(Registers* regs) { + import data.textbuffer : scr = getBootTTY; + import io.log; with (regs) { - import Data.Color; - import Task.Scheduler : GetScheduler; + import data.color; + import task.scheduler : getScheduler; - auto addr = CR2; + auto addr = cr2; TablePtr!(Table!3)* tablePdp; TablePtr!(Table!2)* tablePd; TablePtr!(Table!1)* tablePt; TablePtr!(void)* tablePage; - Paging paging = GetScheduler().CurrentProcess.threadState.paging; - if (paging) { - auto root = paging.RootTable(); - tablePdp = root.Get(cast(ushort)(addr.Int >> 39) & 0x1FF); - if (tablePdp && tablePdp.Present) - tablePd = tablePdp.Data.Virtual.Ptr!(Table!3).Get(cast(ushort)(addr.Int >> 30) & 0x1FF); - if (tablePd && tablePd.Present) - tablePt = tablePd.Data.Virtual.Ptr!(Table!2).Get(cast(ushort)(addr.Int >> 21) & 0x1FF); - if (tablePt && tablePt.Present) - tablePage = tablePt.Data.Virtual.Ptr!(Table!1).Get(cast(ushort)(addr.Int >> 12) & 0x1FF); + Paging _paging = getScheduler.currentProcess.threadState.paging; + if (_paging) { + auto _root = _paging.rootTable(); + tablePdp = _root.get(cast(ushort)(addr.num >> 39) & 0x1FF); + if (tablePdp && tablePdp.present) + tablePd = tablePdp.data.virtual.ptr!(Table!3).get(cast(ushort)(addr.num >> 30) & 0x1FF); + if (tablePd && tablePd.present) + tablePt = tablePd.data.virtual.ptr!(Table!2).get(cast(ushort)(addr.num >> 21) & 0x1FF); + if (tablePt && tablePt.present) + tablePage = tablePt.data.virtual.ptr!(Table!1).get(cast(ushort)(addr.num >> 12) & 0x1FF); } MapMode modePdp; @@ -267,80 +267,80 @@ private void onPageFault(Registers* regs) { MapMode modePt; MapMode modePage; if (tablePdp) - modePdp = tablePdp.Mode; + modePdp = tablePdp.mode; if (tablePd) - modePd = tablePd.Mode; + modePd = tablePd.mode; if (tablePt) - modePt = tablePt.Mode; + modePt = tablePt.mode; if (tablePage) - modePage = tablePage.Mode; - - scr.Foreground = Color(255, 0, 0); - scr.Writeln("===> PAGE FAULT"); - scr.Writeln("IRQ = ", IntNumber, " | RIP = ", cast(void*)RIP); - scr.Writeln("RAX = ", cast(void*)RAX, " | RBX = ", cast(void*)RBX); - scr.Writeln("RCX = ", cast(void*)RCX, " | RDX = ", cast(void*)RDX); - scr.Writeln("RDI = ", cast(void*)RDI, " | RSI = ", cast(void*)RSI); - scr.Writeln("RSP = ", cast(void*)RSP, " | RBP = ", cast(void*)RBP); - scr.Writeln(" R8 = ", cast(void*)R8, " | R9 = ", cast(void*)R9); - scr.Writeln("R10 = ", cast(void*)R10, " | R11 = ", cast(void*)R11); - scr.Writeln("R12 = ", cast(void*)R12, " | R13 = ", cast(void*)R13); - scr.Writeln("R14 = ", cast(void*)R14, " | R15 = ", cast(void*)R15); - scr.Writeln(" CS = ", cast(void*)CS, " | SS = ", cast(void*)SS); - scr.Writeln(" addr = ", cast(void*)addr); - scr.Writeln("Flags: ", cast(void*)Flags); - scr.Writeln("Errorcode: ", cast(void*)ErrorCode, " (", (ErrorCode & (1 << 0) ? " Present" : " NotPresent"), - (ErrorCode & (1 << 1) ? " Write" : " Read"), (ErrorCode & (1 << 2) ? " UserMode" : " KernelMode"), - (ErrorCode & (1 << 3) ? " ReservedWrite" : ""), (ErrorCode & (1 << 4) ? " InstructionFetch" : ""), " )"); - scr.Writeln("PDP Mode: ", (tablePdp && tablePdp.Present) ? "R" : "", (modePdp & MapMode.Writable) ? "W" : "", - (modePdp & MapMode.NoExecute) ? "" : "X", (modePdp & MapMode.User) ? "-User" : ""); - scr.Writeln("PD Mode: ", (tablePd && tablePd.Present) ? "R" : "", (modePd & MapMode.Writable) ? "W" : "", - (modePd & MapMode.NoExecute) ? "" : "X", (modePd & MapMode.User) ? "-User" : ""); - scr.Writeln("PT Mode: ", (tablePt && tablePt.Present) ? "R" : "", (modePt & MapMode.Writable) ? "W" : "", - (modePt & MapMode.NoExecute) ? "" : "X", (modePt & MapMode.User) ? "-User" : ""); - scr.Writeln("Page Mode: ", (tablePage && tablePage.Present) ? "R" : "", (modePage & MapMode.Writable) ? "W" : "", - (modePage & MapMode.NoExecute) ? "" : "X", (modePage & MapMode.User) ? "-User" : ""); + modePage = tablePage.mode; + + scr.foreground = Color(255, 0, 0); + scr.writeln("===> PAGE FAULT"); + scr.writeln("IRQ = ", intNumber, " | RIP = ", cast(void*)rip); + scr.writeln("RAX = ", cast(void*)rax, " | RBX = ", cast(void*)rbx); + scr.writeln("RCX = ", cast(void*)rcx, " | RDX = ", cast(void*)rdx); + scr.writeln("RDI = ", cast(void*)rdi, " | RSI = ", cast(void*)rsi); + scr.writeln("RSP = ", cast(void*)rsp, " | RBP = ", cast(void*)rbp); + scr.writeln(" R8 = ", cast(void*)r8, " | R9 = ", cast(void*)r9); + scr.writeln("R10 = ", cast(void*)r10, " | R11 = ", cast(void*)r11); + scr.writeln("R12 = ", cast(void*)r12, " | R13 = ", cast(void*)r13); + scr.writeln("R14 = ", cast(void*)r14, " | R15 = ", cast(void*)r15); + scr.writeln(" CS = ", cast(void*)cs, " | SS = ", cast(void*)ss); + scr.writeln(" addr = ", cast(void*)addr); + scr.writeln("Flags: ", cast(void*)flags); + scr.writeln("Errorcode: ", cast(void*)errorCode, " (", (errorCode & (1 << 0) ? " Present" : " NotPresent"), + (errorCode & (1 << 1) ? " Write" : " Read"), (errorCode & (1 << 2) ? " UserMode" : " KernelMode"), + (errorCode & (1 << 3) ? " ReservedWrite" : ""), (errorCode & (1 << 4) ? " InstructionFetch" : ""), " )"); + scr.writeln("PDP Mode: ", (tablePdp && tablePdp.present) ? "R" : "", (modePdp & MapMode.writable) ? "W" : "", + (modePdp & MapMode.noExecute) ? "" : "X", (modePdp & MapMode.user) ? "-User" : ""); + scr.writeln("PD Mode: ", (tablePd && tablePd.present) ? "R" : "", (modePd & MapMode.writable) ? "W" : "", + (modePd & MapMode.noExecute) ? "" : "X", (modePd & MapMode.user) ? "-User" : ""); + scr.writeln("PT Mode: ", (tablePt && tablePt.present) ? "R" : "", (modePt & MapMode.writable) ? "W" : "", + (modePt & MapMode.noExecute) ? "" : "X", (modePt & MapMode.user) ? "-User" : ""); + scr.writeln("Page Mode: ", (tablePage && tablePage.present) ? "R" : "", (modePage & MapMode.writable) ? "W" : "", + (modePage & MapMode.noExecute) ? "" : "X", (modePage & MapMode.user) ? "-User" : ""); //dfmt off - log.Fatal("===> PAGE FAULT", "\n", "IRQ = ", IntNumber, " | RIP = ", cast(void*)RIP, "\n", - "RAX = ", cast(void*)RAX, " | RBX = ", cast(void*)RBX, "\n", - "RCX = ", cast(void*)RCX, " | RDX = ", cast(void*)RDX, "\n", - "RDI = ", cast(void*)RDI, " | RSI = ", cast(void*)RSI, "\n", - "RSP = ", cast(void*)RSP, " | RBP = ", cast(void*)RBP, "\n", - " R8 = ", cast(void*)R8, " | R9 = ", cast(void*)R9, "\n", - "R10 = ", cast(void*)R10, " | R11 = ", cast(void*)R11, "\n", - "R12 = ", cast(void*)R12, " | R13 = ", cast(void*)R13, "\n", - "R14 = ", cast(void*)R14, " | R15 = ", cast(void*)R15, "\n", - " CS = ", cast(void*)CS, " | SS = ", cast(void*)SS, "\n", + log.fatal("===> PAGE FAULT", "\n", "IRQ = ", intNumber, " | RIP = ", cast(void*)rip, "\n", + "RAX = ", cast(void*)rax, " | RBX = ", cast(void*)rbx, "\n", + "RCX = ", cast(void*)rcx, " | RDX = ", cast(void*)rdx, "\n", + "RDI = ", cast(void*)rdi, " | RSI = ", cast(void*)rsi, "\n", + "RSP = ", cast(void*)rsp, " | RBP = ", cast(void*)rbp, "\n", + " R8 = ", cast(void*)r8, " | R9 = ", cast(void*)r9, "\n", + "R10 = ", cast(void*)r10, " | R11 = ", cast(void*)r11, "\n", + "R12 = ", cast(void*)r12, " | R13 = ", cast(void*)r13, "\n", + "R14 = ", cast(void*)r14, " | R15 = ", cast(void*)r15, "\n", + " CS = ", cast(void*)cs, " | SS = ", cast(void*)ss, "\n", " addr = ", cast(void*)addr, "\n", - "Flags: ", cast(void*)Flags, "\n", - "Errorcode: ", cast(void*)ErrorCode, " (", - (ErrorCode & (1 << 0) ? " Present" : " NotPresent"), - (ErrorCode & (1 << 1) ? " Write" : " Read"), - (ErrorCode & (1 << 2) ? " UserMode" : " KernelMode"), - (ErrorCode & (1 << 3) ? " ReservedWrite" : ""), - (ErrorCode & (1 << 4) ? " InstructionFetch" : ""), + "Flags: ", cast(void*)flags, "\n", + "Errorcode: ", cast(void*)errorCode, " (", + (errorCode & (1 << 0) ? " Present" : " NotPresent"), + (errorCode & (1 << 1) ? " Write" : " Read"), + (errorCode & (1 << 2) ? " UserMode" : " KernelMode"), + (errorCode & (1 << 3) ? " ReservedWrite" : ""), + (errorCode & (1 << 4) ? " InstructionFetch" : ""), " )", "\n", "PDP Mode: ", - (tablePdp && tablePdp.Present) ? "R" : "", - (modePdp & MapMode.Writable) ? "W" : "", - (modePdp & MapMode.NoExecute) ? "" : "X", - (modePdp & MapMode.User) ? "-User" : "", "\n", + (tablePdp && tablePdp.present) ? "R" : "", + (modePdp & MapMode.writable) ? "W" : "", + (modePdp & MapMode.noExecute) ? "" : "X", + (modePdp & MapMode.user) ? "-User" : "", "\n", "PD Mode: ", - (tablePd && tablePd.Present) ? "R" : "", - (modePd & MapMode.Writable) ? "W" : "", - (modePd & MapMode.NoExecute) ? "" : "X", - (modePd & MapMode.User) ? "-User" : "", "\n", + (tablePd && tablePd.present) ? "R" : "", + (modePd & MapMode.writable) ? "W" : "", + (modePd & MapMode.noExecute) ? "" : "X", + (modePd & MapMode.user) ? "-User" : "", "\n", "PT Mode: ", - (tablePt && tablePt.Present) ? "R" : "", - (modePt & MapMode.Writable) ? "W" : "", - (modePt & MapMode.NoExecute) ? "" : "X", - (modePt & MapMode.User) ? "-User" : "", "\n", + (tablePt && tablePt.present) ? "R" : "", + (modePt & MapMode.writable) ? "W" : "", + (modePt & MapMode.noExecute) ? "" : "X", + (modePt & MapMode.user) ? "-User" : "", "\n", "Page Mode: ", - (tablePage && tablePage.Present) ? "R" : "", - (modePage & MapMode.Writable) ? "W" : "", - (modePage & MapMode.NoExecute) ? "" : "X", - (modePage & MapMode.User) ? "-User" : ""); + (tablePage && tablePage.present) ? "R" : "", + (modePage & MapMode.writable) ? "W" : "", + (modePage & MapMode.noExecute) ? "" : "X", + (modePage & MapMode.user) ? "-User" : ""); //dfmt on } } diff --git a/kernel/src/memory/paging.d b/kernel/src/memory/paging.d index a8255e6..f0029b2 100644 --- a/kernel/src/memory/paging.d +++ b/kernel/src/memory/paging.d @@ -1,102 +1,102 @@ -module Memory.Paging; +module memory.paging; -import Data.Address; -import Data.BitField; -import Memory.FrameAllocator; -import IO.Log; -import Data.Linker; +import data.address; +import data.bitfield; +import memory.frameallocator; +import io.log; +import data.linker; -extern (C) void CPU_flushPage(ulong addr); +extern (C) void cpuFlushPage(ulong addr); enum MapMode : ulong { // TODO: Implement the rest. - Present = 1 << 0, - Writable = 1 << 1, - User = 1 << 2, - Map4M = 1 << 8, - NoExecute = 1UL << 63, - - Empty = 0, - DefaultKernel = Present | Writable, - DefaultUser = Present | User | Writable + present = 1 << 0, + writable = 1 << 1, + user = 1 << 2, + map4M = 1 << 8, + noExecute = 1UL << 63, + + empty = 0, + defaultKernel = present | writable, + defaultUser = present | user | writable } struct TablePtr(T) { - ulong data; + private ulong _data; this(TablePtr!T other) { - data = other.data; + _data = other.data; } - @property PhysAddress Data(PhysAddress address) { - Address = address.Int >> 12; - return Data(); + @property PhysAddress data(PhysAddress address) { + this.address = address.num >> 12; + return data(); } - @property PhysAddress Data() { - return PhysAddress(Address << 12); + @property PhysAddress data() { + return PhysAddress(address << 12); } - @property MapMode Mode(MapMode mode) { - ReadWrite = !!(mode & MapMode.Writable); - User = !!(mode & MapMode.User); + @property MapMode mode(MapMode mode) { + readWrite = !!(mode & MapMode.writable); + user = !!(mode & MapMode.user); static if (!is(T == void)) - Map4M = !!(mode & MapMode.Map4M); - NoExecute = !!(mode & MapMode.NoExecute); + map4M = !!(mode & MapMode.map4M); + noExecute = !!(mode & MapMode.noExecute); - return Mode(); + return this.mode(); } - @property MapMode Mode() { + @property MapMode mode() { MapMode mode; - if (Present) - mode |= MapMode.Present; + if (present) + mode |= MapMode.present; - if (ReadWrite) - mode |= MapMode.Writable; - if (User) - mode |= MapMode.User; + if (readWrite) + mode |= MapMode.writable; + if (user) + mode |= MapMode.user; static if (!is(T == void)) - if (Map4M) - mode |= MapMode.Map4M; - if (NoExecute) - mode |= MapMode.NoExecute; + if (map4M) + mode |= MapMode.map4M; + if (noExecute) + mode |= MapMode.noExecute; return mode; } //dfmt off static if (is(T == void)) { - mixin(Bitfield!(data, - "Present", 1, - "ReadWrite", 1, - "User", 1, - "WriteThrough", 1, - "CacheDisable", 1, - "Accessed", 1, - "Dirty", 1, - "PAT", 1, - "Global", 1, - "Avl", 3, - "Address", 40, - "Available", 11, - "NoExecute", 1 + mixin(bitfield!(_data, + "present", 1, + "readWrite", 1, + "user", 1, + "writeThrough", 1, + "cacheDisable", 1, + "accessed", 1, + "dirty", 1, + "pat", 1, + "global", 1, + "avl", 3, + "address", 40, + "available", 11, + "noExecute", 1 )); } else { - mixin(Bitfield!(data, - "Present", 1, - "ReadWrite", 1, - "User", 1, - "WriteThrough", 1, - "CacheDisable", 1, - "Accessed", 1, - "Reserved", 1, - "Map4M", 1, - "Ignored", 1, - "Avl", 3, - "Address", 40, - "Available", 11, - "NoExecute", 1 + mixin(bitfield!(_data, + "present", 1, + "readWrite", 1, + "user", 1, + "writeThrough", 1, + "cacheDisable", 1, + "accessed", 1, + "reserved", 1, + "map4M", 1, + "ignored", 1, + "avl", 3, + "address", 40, + "available", 11, + "noExecute", 1 )); } //dfmt on @@ -112,27 +112,27 @@ struct Table(int Level) { ChildType[512] children; - ChildType* Get(ushort idx) { + ChildType* get(ushort idx) { assert(idx < children.length); ChildType* child = &children[idx]; return child; } static if (Level != 1) - ChildType* GetOrCreate(ushort idx, MapMode mode) { + ChildType* getOrCreate(ushort idx, MapMode mode) { assert(idx < children.length); ChildType* child = &children[idx]; - if (!child.Present) { - if (mode & MapMode.Map4M) - log.Fatal("Map4M creation is not Allowed in GetOrCreate! Level: ", Level, " Index: ", idx); + if (!child.present) { + if (mode & MapMode.map4M) + log.fatal("Map4M creation is not Allowed in GetOrCreate! Level: ", Level, " Index: ", idx); - child.Data = PhysAddress(FrameAllocator.Alloc()); + child.data = PhysAddress(FrameAllocator.alloc()); - _memset64(child.Data.Virtual.Ptr, 0, 0x200); //Defined in object.d, 0x200 * 8 = 0x1000 + _memset64(child.data.virtual.ptr, 0, 0x200); //Defined in object.d, 0x200 * 8 = 0x1000 - child.Mode = mode; - child.Present = true; + child.mode = mode; + child.present = true; } return child; @@ -141,80 +141,80 @@ struct Table(int Level) { static assert(Table!4.sizeof == (ulong[512]).sizeof); -private extern (C) void CPU_install_cr3(PhysAddress addr); +private extern (C) void cpuInstallCR3(PhysAddress addr); class Paging { public: private this() { - rootPhys = PhysAddress(FrameAllocator.Alloc()); - root = rootPhys.Virtual.Ptr!(Table!4); - _memset64(root, 0, 0x200); //Defined in object.d - refCounter++; + _rootPhys = PhysAddress(FrameAllocator.alloc()); + _root = _rootPhys.virtual.ptr!(Table!4); + _memset64(_root, 0, 0x200); //Defined in object.d + _refCounter++; } this(void* pml4) { - root = cast(Table!4*)pml4; - refCounter++; - rootPhys = GetPage(VirtAddress(root)).Data; + _root = cast(Table!4*)pml4; + _refCounter++; + _rootPhys = getPage(VirtAddress(_root)).data; } this(Paging other) { this(); - Table!4* otherPML4 = other.root; - Table!4* myPML4 = root; + Table!4* otherPML4 = other._root; + Table!4* myPML4 = _root; for (ushort pml4Idx = 0; pml4Idx < 512 - 1 /* Kernel PDP */ ; pml4Idx++) { if (pml4Idx == 256) // See end of function for why continue; TablePtr!(Table!3) otherPDPEntry_ptr = otherPML4.children[pml4Idx]; - if (!otherPDPEntry_ptr.Present) + if (!otherPDPEntry_ptr.present) continue; - Table!3* otherPDPEntry = otherPDPEntry_ptr.Data.Virtual.Ptr!(Table!3); - Table!3* myPDPEntry = myPML4.GetOrCreate(pml4Idx, otherPDPEntry_ptr.Mode).Data.Virtual.Ptr!(Table!3); + Table!3* otherPDPEntry = otherPDPEntry_ptr.data.virtual.ptr!(Table!3); + Table!3* myPDPEntry = myPML4.getOrCreate(pml4Idx, otherPDPEntry_ptr.mode).data.virtual.ptr!(Table!3); for (ushort pdpIdx = 0; pdpIdx < 512; pdpIdx++) { TablePtr!(Table!2) otherPDEntry_ptr = otherPDPEntry.children[pdpIdx]; - if (!otherPDEntry_ptr.Present) + if (!otherPDEntry_ptr.present) continue; - Table!2* otherPDEntry = otherPDEntry_ptr.Data.Virtual.Ptr!(Table!2); - Table!2* myPDEntry = myPDPEntry.GetOrCreate(pdpIdx, otherPDEntry_ptr.Mode).Data.Virtual.Ptr!(Table!2); + Table!2* otherPDEntry = otherPDEntry_ptr.data.virtual.ptr!(Table!2); + Table!2* myPDEntry = myPDPEntry.getOrCreate(pdpIdx, otherPDEntry_ptr.mode).data.virtual.ptr!(Table!2); for (ushort pdIdx = 0; pdIdx < 512; pdIdx++) { TablePtr!(Table!1) otherPTEntry_ptr = otherPDEntry.children[pdIdx]; - if (!otherPTEntry_ptr.Present) + if (!otherPTEntry_ptr.present) continue; - if (otherPTEntry_ptr.Mode & MapMode.Map4M) { - TablePtr!(Table!1)* myPTEntry = myPDEntry.Get(pdIdx); - PhysAddress phys = PhysAddress(FrameAllocator.Alloc512()); - myPTEntry.Data = phys; - myPTEntry.Mode = otherPTEntry_ptr.Mode; - myPTEntry.Present = true; + if (otherPTEntry_ptr.mode & MapMode.map4M) { + TablePtr!(Table!1)* myPTEntry = myPDEntry.get(pdIdx); + PhysAddress phys = PhysAddress(FrameAllocator.alloc512()); + myPTEntry.data = phys; + myPTEntry.mode = otherPTEntry_ptr.mode; + myPTEntry.present = true; VirtAddress addr = VirtAddress(cast(ulong)pml4Idx << 39UL | cast(ulong)pdpIdx << 30UL | cast(ulong)pdIdx << 21UL); - FlushPage(addr); - memcpy(phys.Virtual.Ptr, otherPTEntry_ptr.Data.Virtual.Ptr, 0x1000 * 512); //Defined in object.d, 0x200 * 8 = 0x1000 + flushPage(addr); + memcpy(phys.virtual.ptr, otherPTEntry_ptr.data.virtual.ptr, 0x1000 * 512); //Defined in object.d, 0x200 * 8 = 0x1000 } else { - Table!1* otherPTEntry = otherPTEntry_ptr.Data.Virtual.Ptr!(Table!1); - Table!1* myPTEntry = myPDEntry.GetOrCreate(pdIdx, otherPTEntry_ptr.Mode).Data.Virtual.Ptr!(Table!1); + Table!1* otherPTEntry = otherPTEntry_ptr.data.virtual.ptr!(Table!1); + Table!1* myPTEntry = myPDEntry.getOrCreate(pdIdx, otherPTEntry_ptr.mode).data.virtual.ptr!(Table!1); for (ushort ptIdx = 0; ptIdx < 512; ptIdx++) { - PhysAddress phys = FrameAllocator.Alloc(); - assert(phys.Int); + PhysAddress phys = FrameAllocator.alloc(); + assert(phys.num); with (myPTEntry.children[ptIdx]) { - Data = phys; - Mode = otherPTEntry.children[ptIdx].Mode; - Present = true; + data = phys; + mode = otherPTEntry.children[ptIdx].mode; + present = true; } VirtAddress addr = VirtAddress(cast(ulong)pml4Idx << 39UL | cast(ulong)pdpIdx << 30UL | cast( ulong)pdIdx << 21UL | cast(ulong)ptIdx << 12UL); - FlushPage(addr); + flushPage(addr); - memcpy(phys.Virtual.Ptr, otherPTEntry.children[ptIdx].Data.Virtual.Ptr, 0x1000); // TODO: Implement Copy-on-write, so we can skip this step! + memcpy(phys.virtual.ptr, otherPTEntry.children[ptIdx].data.virtual.ptr, 0x1000); // TODO: Implement Copy-on-write, so we can skip this step! } } } @@ -224,178 +224,178 @@ public: myPML4.children[511] = otherPML4.children[511]; // Map Kernel } - void Map(VirtAddress virt, PhysAddress phys, MapMode pageMode, MapMode tablesMode = MapMode.DefaultUser) { - if (phys.Int == 0) + void map(VirtAddress virt, PhysAddress phys, MapMode pageMode, MapMode tablesMode = MapMode.defaultUser) { + if (phys.num == 0) return; - const ulong virtAddr = virt.Int; + const ulong virtAddr = virt.num; const ushort pml4Idx = (virtAddr >> 39) & 0x1FF; const ushort pdpIdx = (virtAddr >> 30) & 0x1FF; const ushort pdIdx = (virtAddr >> 21) & 0x1FF; const ushort ptIdx = (virtAddr >> 12) & 0x1FF; - Table!3* pdp = root.GetOrCreate(pml4Idx, tablesMode).Data.Virtual.Ptr!(Table!3); - Table!2* pd = pdp.GetOrCreate(pdpIdx, tablesMode).Data.Virtual.Ptr!(Table!2); - Table!1* pt = pd.GetOrCreate(pdIdx, tablesMode).Data.Virtual.Ptr!(Table!1); - TablePtr!void* page = pt.Get(ptIdx); + Table!3* pdp = _root.getOrCreate(pml4Idx, tablesMode).data.virtual.ptr!(Table!3); + Table!2* pd = pdp.getOrCreate(pdpIdx, tablesMode).data.virtual.ptr!(Table!2); + Table!1* pt = pd.getOrCreate(pdIdx, tablesMode).data.virtual.ptr!(Table!1); + TablePtr!void* page = pt.get(ptIdx); - page.Mode = pageMode; - page.Data = phys; - page.Present = true; - FlushPage(virt); + page.mode = pageMode; + page.data = phys; + page.present = true; + flushPage(virt); } - void Unmap(VirtAddress virt) { - auto page = GetPage(virt); + void unmap(VirtAddress virt) { + auto page = getPage(virt); if (!page) return; - page.Mode = MapMode.Empty; - page.Data = PhysAddress(); - page.Present = false; - FlushPage(virt); + page.mode = MapMode.empty; + page.data = PhysAddress(); + page.present = false; + flushPage(virt); } - void UnmapAndFree(VirtAddress virt) { - auto page = GetPage(virt); + void unmapAndFree(VirtAddress virt) { + auto page = getPage(virt); if (!page) return; - FrameAllocator.Free(page.Data); + FrameAllocator.free(page.data); - page.Mode = MapMode.Empty; - page.Data = PhysAddress(); - page.Present = false; - FlushPage(virt); + page.mode = MapMode.empty; + page.data = PhysAddress(); + page.present = false; + flushPage(virt); } - PhysAddress MapFreeMemory(VirtAddress virt, MapMode pageMode, MapMode tablesMode = MapMode.DefaultUser) { - PhysAddress phys = FrameAllocator.Alloc(); - if (!phys.Int) + PhysAddress mapFreeMemory(VirtAddress virt, MapMode pageMode, MapMode tablesMode = MapMode.defaultUser) { + PhysAddress phys = FrameAllocator.alloc(); + if (!phys.num) return phys; // aka Null - Map(virt, phys, pageMode, tablesMode); + map(virt, phys, pageMode, tablesMode); return phys; } - TablePtr!(void)* GetPage(VirtAddress virt) { - if (virt.Int == 0) + TablePtr!(void)* getPage(VirtAddress virt) { + if (virt.num == 0) return null; - const ulong virtAddr = virt.Int; + const ulong virtAddr = virt.num; const ushort pml4Idx = (virtAddr >> 39) & 0x1FF; const ushort pdpIdx = (virtAddr >> 30) & 0x1FF; const ushort pdIdx = (virtAddr >> 21) & 0x1FF; const ushort ptIdx = (virtAddr >> 12) & 0x1FF; - auto pdpAddr = root.Get(pml4Idx); - if (!pdpAddr.Present) + auto pdpAddr = _root.get(pml4Idx); + if (!pdpAddr.present) return null; - Table!3* pdp = pdpAddr.Data.Virtual.Ptr!(Table!3); + Table!3* pdp = pdpAddr.data.virtual.ptr!(Table!3); - auto pdAddr = pdp.Get(pdpIdx); - if (!pdAddr.Present) + auto pdAddr = pdp.get(pdpIdx); + if (!pdAddr.present) return null; - Table!2* pd = pdAddr.Data.Virtual.Ptr!(Table!2); + Table!2* pd = pdAddr.data.virtual.ptr!(Table!2); - auto ptAddr = pd.Get(pdIdx); - if (!ptAddr.Present) + auto ptAddr = pd.get(pdIdx); + if (!ptAddr.present) return null; - Table!1* pt = ptAddr.Data.Virtual.Ptr!(Table!1); + Table!1* pt = ptAddr.data.virtual.ptr!(Table!1); - return pt.Get(ptIdx); + return pt.get(ptIdx); } - void Install() { - CPU_install_cr3(Root); + void install() { + cpuInstallCR3(root()); } - void RemoveUserspace(bool freePages) { - Table!4* myPML4 = root; + void removeUserspace(bool freePages) { + Table!4* myPML4 = _root; for (ushort pml4Idx = 0; pml4Idx < 512 - 1 /* Kernel PDP */ ; pml4Idx++) { if (pml4Idx == 256) // 512GiB Lower mapping continue; - auto pdp_ptr = myPML4.Get(pml4Idx); - if (!pdp_ptr.Present) + auto pdp_ptr = myPML4.get(pml4Idx); + if (!pdp_ptr.present) continue; - Table!3* myPDPEntry = pdp_ptr.Data.Virtual.Ptr!(Table!3); + Table!3* myPDPEntry = pdp_ptr.data.virtual.ptr!(Table!3); for (ushort pdpIdx = 0; pdpIdx < 512; pdpIdx++) { - auto pd_ptr = myPDPEntry.Get(pdpIdx); - if (!pd_ptr.Present) + auto pd_ptr = myPDPEntry.get(pdpIdx); + if (!pd_ptr.present) continue; - Table!2* myPDEntry = pd_ptr.Data.Virtual.Ptr!(Table!2); + Table!2* myPDEntry = pd_ptr.data.virtual.ptr!(Table!2); for (ushort pdIdx = 0; pdIdx < 512; pdIdx++) { - auto pt_ptr = myPDEntry.Get(pdIdx); - if (!pt_ptr.Present) + auto pt_ptr = myPDEntry.get(pdIdx); + if (!pt_ptr.present) continue; - if (pt_ptr.Mode & MapMode.Map4M) { - PhysAddress start = pt_ptr.Data; + if (pt_ptr.mode & MapMode.map4M) { + PhysAddress start = pt_ptr.data; immutable PhysAddress end = start + 512 * 0x1000; while (start < end) - FrameAllocator.Free(start += 0x1000); + FrameAllocator.free(start += 0x1000); } else { - Table!1* myPTEntry = pt_ptr.Data.Virtual.Ptr!(Table!1); + Table!1* myPTEntry = pt_ptr.data.virtual.ptr!(Table!1); if (freePages) for (ushort ptIdx = 0; ptIdx < 512; ptIdx++) - with (myPTEntry.Get(ptIdx)) - if (Present) { + with (myPTEntry.get(ptIdx)) + if (present) { VirtAddress addr = VirtAddress(cast(ulong)pml4Idx << 39UL | cast( ulong)pdpIdx << 30UL | cast(ulong)pdIdx << 21UL | cast(ulong)ptIdx << 12UL); - FrameAllocator.Free(Data); - Present = false; - FlushPage(addr); + FrameAllocator.free(data); + present = false; + flushPage(addr); } - //log.Warning("Freeing Table!1: ", VirtAddress(cast(ulong)pml4Idx << 39UL | cast(ulong)pdpIdx << 30UL | cast(ulong)pdIdx << 21UL)); - FrameAllocator.Free(pt_ptr.Data); + //log.warning("Freeing Table!1: ", VirtAddress(cast(ulong)pml4Idx << 39UL | cast(ulong)pdpIdx << 30UL | cast(ulong)pdIdx << 21UL)); + FrameAllocator.free(pt_ptr.data); } } - //log.Warning("Freeing Table!2: ", VirtAddress(cast(ulong)pml4Idx << 39UL | cast(ulong)pdpIdx << 30UL)); - FrameAllocator.Free(pd_ptr.Data); + //log.warning("Freeing Table!2: ", VirtAddress(cast(ulong)pml4Idx << 39UL | cast(ulong)pdpIdx << 30UL)); + FrameAllocator.free(pd_ptr.data); } - //log.Warning("Freeing Table!3: ", VirtAddress(cast(ulong)pml4Idx << 39UL)); - FrameAllocator.Free(pdp_ptr.Data); - pdp_ptr.Mode = MapMode.Empty; - pdp_ptr.Data = PhysAddress(); - pdp_ptr.Present = false; + //log.warning("Freeing Table!3: ", VirtAddress(cast(ulong)pml4Idx << 39UL)); + FrameAllocator.free(pdp_ptr.data); + pdp_ptr.mode = MapMode.empty; + pdp_ptr.data = PhysAddress(); + pdp_ptr.present = false; } } - void FlushPage(VirtAddress virt) { - CPU_flushPage(virt.Int); + void flushPage(VirtAddress virt) { + cpuFlushPage(virt.num); } - @property Table!4* RootTable() { - return root; + @property Table!4* rootTable() { + return _root; } - @property PhysAddress Root() { - return rootPhys; + @property PhysAddress root() { + return _rootPhys; } - @property ref ulong RefCounter() { - return refCounter; + @property ref ulong refCounter() { + return _refCounter; } private: - Table!4* root; - PhysAddress rootPhys; - ulong refCounter; + Table!4* _root; + PhysAddress _rootPhys; + ulong _refCounter; } private extern (C) extern __gshared { - ubyte PML4; + ubyte PML4; // Reference to PML4 in boot.S } -Paging GetKernelPaging() { - import Data.Util : InplaceClass; +Paging getKernelPaging() { + import data.util : inplaceClass; __gshared ubyte[__traits(classInstanceSize, Paging)] data; __gshared Paging kernelPaging; if (!kernelPaging) - kernelPaging = InplaceClass!Paging(data, &PML4); + kernelPaging = inplaceClass!Paging(data, &PML4); return kernelPaging; } diff --git a/kernel/src/object.d b/kernel/src/object.d index 77b6d08..1cc7cdc 100644 --- a/kernel/src/object.d +++ b/kernel/src/object.d @@ -1,6 +1,6 @@ module object; -import IO.Log; +import io.log; // over 3/4 of this file was copy/pasted from the real druntime with little to no modification @@ -48,7 +48,7 @@ with an empty main: without_custom_runtime_reflection: runtime reflection will be bare minimum, don't use typeinfo except as like an opaque pointer. You also won't need the special linker script if you go without libc with this option. */ -import Data.String : strlen; +import data.string_ : strlen; void main() { } @@ -59,7 +59,7 @@ int callKmain(uint magic, ulong info) { return kmain(magic, info); } catch (Throwable t) { - log.Info("\n**UNCAUGHT EXCEPTION**\n"); + log.info("\n**UNCAUGHT EXCEPTION**\n"); t.print(); t.destroy; return (1); @@ -125,10 +125,10 @@ extern (C) { // the compiler spits this out all the time Object _d_newclass(const ClassInfo ci) { - //log.Debug("Creating a new class of type: ", ci.name); - void* memory = GetKernelHeap.Alloc(ci.init.length); + //log.debug_("Creating a new class of type: ", ci.name); + void* memory = getKernelHeap.alloc(ci.init.length); if (memory is null) { - log.Fatal("\n\n_d_newclass malloc failure\n\n"); + log.fatal("\n\n_d_newclass malloc failure\n\n"); exit(); } @@ -137,7 +137,7 @@ extern (C) { } extern (C) void* _d_newitemU(in TypeInfo ti) { - return GetKernelHeap.Alloc(ti.tsize); + return getKernelHeap.alloc(ti.tsize); } extern (C) void* _d_newitemT(in TypeInfo ti) { @@ -160,7 +160,7 @@ extern (C) { if (!length || !size) return null; else - return GetKernelHeap.Alloc(length * size)[0 .. length]; + return getKernelHeap.alloc(length * size)[0 .. length]; } extern (C) void[] _d_newarrayiT(TypeInfo ti, size_t length) { @@ -202,17 +202,17 @@ extern (C) { if (!length || !size) return null; else - return GetKernelHeap.Alloc(length * size); + return getKernelHeap.alloc(length * size); } void[] _d_arraycatT(TypeInfo ti, void[] x, void[] y) { - log.Fatal(ti.toString); + log.fatal(ti.toString); auto size = ti.next.tsize(); if (!(x.length + y.length) || !size) return null; - ubyte* data = cast(ubyte*)GetKernelHeap.Alloc((x.length + y.length) * size); + ubyte* data = cast(ubyte*)getKernelHeap.alloc((x.length + y.length) * size); memcpy(data, x.ptr, x.length * size); memcpy(data + (x.length * size), y.ptr, y.length * size); return (cast(void*)data)[0 .. x.length + y.length]; @@ -220,13 +220,13 @@ extern (C) { void[] _d_arraysetlengthT(const TypeInfo ti, size_t newlength, void[]* p) { auto size = ti.next.tsize(); - *p = GetKernelHeap.Realloc(p.ptr, newlength * size)[0 .. newlength]; + *p = getKernelHeap.realloc(p.ptr, newlength * size)[0 .. newlength]; return *p; } void[] _d_arraysetlengthiT(const TypeInfo ti, size_t newlength, void[]* p) { auto size = ti.next.tsize(); - *p = GetKernelHeap.Realloc(p.ptr, newlength * size)[0 .. newlength]; + *p = getKernelHeap.realloc(p.ptr, newlength * size)[0 .. newlength]; return *p; } @@ -234,7 +234,7 @@ extern (C) { byte[] _d_arrayappendcTX(const TypeInfo ti, ref byte[] px, size_t n) { auto size = ti.next.tsize(); auto newlength = px.length + n; - void* newPtr = GetKernelHeap.Realloc(px.ptr, newlength * size); + void* newPtr = getKernelHeap.realloc(px.ptr, newlength * size); *cast(size_t*)&px = newlength; (cast(void**)(&px))[1] = newPtr; return px; @@ -245,7 +245,7 @@ extern (C) { if (len % newTypeSize) try - log.Fatal("Can't cast array! newTypeSize: ", newTypeSize, ", curTypeSize: ", curTypeSize, ", len: ", len); + log.fatal("Can't cast array! newTypeSize: ", newTypeSize, ", curTypeSize: ", curTypeSize, ", len: ", len); catch (Exception) { } @@ -263,7 +263,7 @@ extern (C) { if (!length) return null; - void* a = GetKernelHeap.Alloc(length * size); + void* a = getKernelHeap.alloc(length * size); size_t j = 0; foreach (b; arrs) { @@ -278,7 +278,7 @@ extern (C) { // and these came when I started using foreach void _d_unittestm(string file, uint line) { - log.Info("_d_unittest_"); + log.info("_d_unittest_"); exit(1); } @@ -405,7 +405,7 @@ class Throwable : Object { // required by the D compiler } void print() { - log.Fatal(this.classinfo.name, "@", file, "(", line, "): ", message, "\n"); + log.fatal(this.classinfo.name, "@", file, "(", line, "): ", message, "\n"); } } @@ -486,9 +486,9 @@ class TypeInfo { } /// Run the destructor on the object and all its sub-objects void destroy(void* p) const { - import Memory.Heap; + import memory.heap; - GetKernelHeap.Free(p); + getKernelHeap.free(p); } /// Run the postblit on the object and all its sub-objects void postblit(void* p) const { @@ -1628,17 +1628,17 @@ immutable(T)[] immutable_alloc(T)(scope void delegate(T[]) initalizer) { return null; } -import Memory.Heap; +import memory.heap; void destroy(void* memory) { - GetKernelHeap.Free(memory); + getKernelHeap.free(memory); } void destroy(T : Object)(T object) { auto dtor = cast(void function(Object o))object.classinfo.destructor; if (dtor) dtor(object); - GetKernelHeap.Free(cast(void*)object); + getKernelHeap.free(cast(void*)object); } void destroy(T)(T[] array) { @@ -1653,13 +1653,13 @@ void destroy(T)(T[] array) { foreach (el; array) destroy(cast(void*)el); } - GetKernelHeap.Free(cast(void*)array.ptr); + getKernelHeap.free(cast(void*)array.ptr); } // this would be used for automatic heap closures, but there's no way to free it... ///* extern (C) void* _d_allocmemory(size_t bytes) { - return GetKernelHeap.Alloc(bytes); + return getKernelHeap.alloc(bytes); } //*/ @@ -1864,7 +1864,7 @@ private { } void terminate() { - log.Info("Uncaught exception or busted up stack\n"); + log.info("Uncaught exception or busted up stack\n"); exit(); } @@ -2423,15 +2423,15 @@ extern (C) int dstrcmp(char[] s1, char[] s2) { } inout(T)[] dup(T)(inout(T)[] a) { - import Memory.Heap : GetKernelHeap; + import memory.heap : getKernelHeap; - void[] arr = GetKernelHeap.Alloc(T.sizeof * a.length)[0 .. a.length]; + void[] arr = getKernelHeap.alloc(T.sizeof * a.length)[0 .. a.length]; memcpy(arr.ptr, a.ptr, T.sizeof * a.length); return *cast(inout(T)[]*)&arr; } extern (C) Throwable __dmd_begin_catch(_Unwind_Exception* exceptionObject) { - log.Error("STUB"); + log.error("STUB"); return null; } @@ -2450,10 +2450,10 @@ struct _Unwind_Context { alias ulong _Unwind_Exception_Class; extern (C) _Unwind_Reason_Code __dmd_personality_v0(int ver, _Unwind_Action actions, _Unwind_Exception_Class exceptionClass, _Unwind_Exception* exceptionObject, _Unwind_Context* context) { - log.Error("STUB"); + log.error("STUB"); return 0; } extern (C) void _Unwind_Resume(void*) { - log.Error("STUB"); + log.error("STUB"); } diff --git a/kernel/src/system/syscall.d b/kernel/src/system/syscall.d index 6ef88de..29b6b87 100644 --- a/kernel/src/system/syscall.d +++ b/kernel/src/system/syscall.d @@ -1,301 +1,300 @@ -module System.Syscall; +module system.syscall; -import Data.Address; -import Data.String; -import Data.Register; -import System.Utils; -import Task.Scheduler : GetScheduler; -import Task.Process; +import data.address; +import data.string_; +import data.register; +import system.utils; +import task.scheduler : getScheduler; +import task.process; enum SyscallID : ulong { - Nothing = 0, - Exit, - Clone, - Sleep, - Exec, - GetPermissions, - GetCurrentDirectory, - ChangeCurrentDirectory, - GetPid, - GetParentPid, - SendSignal, - Join, + nothing = 0, + exit, + clone, + sleep, + exec, + getPermissions, + getCurrentDirectory, + changeCurrentDirectory, + getPid, + getParentPid, + sendSignal, + join, - Map, - Unmap, + map, + unmap, - Open, - Close, - ReOpen, - Read, - Write, + open, + close, + reOpen, + read, + write, - CreateDirectory, - RemoveDirectory, - ListDirectory, + createDirectory, + removeDirectory, + listDirectory, - Control, + control, - Stats, - Duplicate, + stats, + duplicate, - Link, - Unlink, + link, + unlink, - Mount, - Unmount, + mount, + unmount, - ChangePermissions, - ChangeOwner, + changePermissions, + changeOwner, - UpdateSignalHandler, + updateSignalHandler, - GetTimestamp, - GetHostname, - GetUName, - Shutdown, + getTimestamp, + getHostname, + getUName, + shutdown, //TODO: Remove these - Fork, - Yield, - Alloc, - Free, - Realloc, - GetArguments, + fork, + yield, + alloc, + free, + realloc, + getArguments, } struct SyscallEntry { SyscallID id; } -@SyscallEntry(SyscallID.Exit) -void Exit(long errorcode) { - auto scheduler = GetScheduler; - scheduler.Exit(errorcode); +@SyscallEntry(SyscallID.exit) +void exit(long errorcode) { + auto scheduler = getScheduler; + scheduler.exit(errorcode); - scheduler.CurrentProcess.syscallRegisters.RAX = 0; + scheduler.currentProcess.syscallRegisters.rax = 0; } -@SyscallEntry(SyscallID.Clone) -void Clone(ulong function(void*) func, VirtAddress stack, void* userdata, string name) { - auto scheduler = GetScheduler; - GetScheduler.CurrentProcess.syscallRegisters.RAX = scheduler.Clone(func, stack, userdata, name); +@SyscallEntry(SyscallID.clone) +void clone(ulong function(void*) func, VirtAddress stack, void* userdata, string name) { + auto scheduler = getScheduler; + getScheduler.currentProcess.syscallRegisters.rax = scheduler.clone(func, stack, userdata, name); } -@SyscallEntry(SyscallID.Fork) -void Fork() { - auto scheduler = GetScheduler; +@SyscallEntry(SyscallID.fork) +void fork() { + auto scheduler = getScheduler; - scheduler.CurrentProcess.syscallRegisters.RAX = scheduler.Fork(); + scheduler.currentProcess.syscallRegisters.rax = scheduler.fork(); } -@SyscallEntry(SyscallID.Sleep) -void Sleep(ulong time) { - auto scheduler = GetScheduler; - scheduler.USleep(time); - scheduler.CurrentProcess.syscallRegisters.RAX = 0; +@SyscallEntry(SyscallID.sleep) +void sleep(ulong time) { + auto scheduler = getScheduler; + scheduler.uSleep(time); + scheduler.currentProcess.syscallRegisters.rax = 0; } -@SyscallEntry(SyscallID.Exec) -void Exec(string path, string[] args) { - import IO.FS.FileNode; - import Data.ELF : ELF; +@SyscallEntry(SyscallID.exec) +void exec(string path, string[] args) { + import io.fs.filenode; + import data.elf : ELF; - Process* process = GetScheduler.CurrentProcess; + Process* process = getScheduler.currentProcess; - FileNode file = cast(FileNode)process.currentDirectory.FindNode(path); + FileNode file = cast(FileNode)process.currentDirectory.findNode(path); if (!file) { - process.syscallRegisters.RAX = 1; + process.syscallRegisters.rax = 1; return; } ELF elf = new ELF(file); - if (!elf.Valid) { - process.syscallRegisters.RAX = 2; + if (!elf.valid) { + process.syscallRegisters.rax = 2; return; } - elf.MapAndRun(args); + elf.mapAndRun(args); assert(0); } -@SyscallEntry(SyscallID.Alloc) -void Alloc(ulong size) { - Process* process = GetScheduler.CurrentProcess; - process.syscallRegisters.RAX = process.heap.Alloc(size).VirtAddress; +@SyscallEntry(SyscallID.alloc) +void alloc(ulong size) { + Process* process = getScheduler.currentProcess; + process.syscallRegisters.rax = process.heap.alloc(size).VirtAddress; } -@SyscallEntry(SyscallID.Free) -void Free(void* addr) { - Process* process = GetScheduler.CurrentProcess; - process.heap.Free(addr); - process.syscallRegisters.RAX = 0; +@SyscallEntry(SyscallID.free) +void free(void* addr) { + Process* process = getScheduler.currentProcess; + process.heap.free(addr); + process.syscallRegisters.rax = 0; } -@SyscallEntry(SyscallID.Realloc) -void Realloc(void* addr, ulong newSize) { - Process* process = GetScheduler.CurrentProcess; - process.syscallRegisters.RAX = process.heap.Realloc(addr, newSize).VirtAddress; +@SyscallEntry(SyscallID.realloc) +void realloc(void* addr, ulong newSize) { + Process* process = getScheduler.currentProcess; + process.syscallRegisters.rax = process.heap.realloc(addr, newSize).VirtAddress; } -@SyscallEntry(SyscallID.GetArguments) -void GetArguments(ulong* argc, char*** argv) { //TODO: add Check for userspace pointer - Process* process = GetScheduler.CurrentProcess; - if (!argc.VirtAddress.IsValidToWrite(size_t.sizeof) || !argv.VirtAddress.IsValidToWrite(const(char**).sizeof)) { - process.syscallRegisters.RAX = 1; +@SyscallEntry(SyscallID.getArguments) +void getArguments(ulong* argc, char*** argv) { //TODO: add Check for userspace pointer + Process* process = getScheduler.currentProcess; + if (!argc.VirtAddress.isValidToWrite(size_t.sizeof) || !argv.VirtAddress.isValidToWrite(const(char**).sizeof)) { + process.syscallRegisters.rax = 1; return; } *argc = process.image.arguments.length - 1; // Don't count the null at the end *argv = process.image.arguments.ptr; - process.syscallRegisters.RAX = 0; + process.syscallRegisters.rax = 0; } -@SyscallEntry(SyscallID.Open) -void Open(string file) { - import KMain : rootFS; - import IO.FS; +@SyscallEntry(SyscallID.open) +void open(string file) { + import kmain : rootFS; + import io.fs; - Process* process = GetScheduler.CurrentProcess; - if (false && !(cast(void*)file.ptr).VirtAddress.IsValidToRead(file.length)) { - process.syscallRegisters.RAX = 0; - import IO.Log; + Process* process = getScheduler.currentProcess; + if (false && !(cast(void*)file.ptr).VirtAddress.isValidToRead(file.length)) { + process.syscallRegisters.rax = 0; + import io.log; - log.Warning("Failed to Read!"); + log.warning("Failed to Read!"); return; } - FileNode node = cast(FileNode)rootFS.Root.FindNode(file); + FileNode node = cast(FileNode)rootFS.root.findNode(file); if (!node) { - process.syscallRegisters.RAX = 0; + process.syscallRegisters.rax = 0; return; } - node.Open(); + node.open(); auto id = process.fdCounter++; - process.fileDescriptors.Add(new FileDescriptor(id, node)); - process.syscallRegisters.RAX = id; + process.fileDescriptors.add(new FileDescriptor(id, node)); + process.syscallRegisters.rax = id; } -@SyscallEntry(SyscallID.ReOpen) -void ReOpen(size_t id, string file) { - import KMain : rootFS; - import IO.FS; +@SyscallEntry(SyscallID.reOpen) +void reOpen(size_t id, string file) { + import kmain : rootFS; + import io.fs; - Process* process = GetScheduler.CurrentProcess; - if (false && !(cast(void*)file.ptr).VirtAddress.IsValidToRead(file.length)) { - process.syscallRegisters.RAX = 0; - import IO.Log; + Process* process = getScheduler.currentProcess; + if (false && !(cast(void*)file.ptr).VirtAddress.isValidToRead(file.length)) { + process.syscallRegisters.rax = 0; + import io.log; - log.Warning("Failed to Read!"); + log.warning("Failed to Read!"); return; } - - for (size_t i = 0; i < process.fileDescriptors.Length; i++) { - FileDescriptor* item = process.fileDescriptors.Get(i); + for (size_t i = 0; i < process.fileDescriptors.length; i++) { + FileDescriptor* item = process.fileDescriptors.get(i); if (item.id == id) { - FileNode newNode = cast(FileNode)rootFS.Root.FindNode(file); + FileNode newNode = cast(FileNode)rootFS.root.findNode(file); if (!newNode) { - process.syscallRegisters.RAX = 1; + process.syscallRegisters.rax = 1; return; } - item.node.Close(); + item.node.close(); item.node = newNode; - item.node.Open(); - process.syscallRegisters.RAX = 0; + item.node.open(); + process.syscallRegisters.rax = 0; return; } } - process.syscallRegisters.RAX = 1; + process.syscallRegisters.rax = 1; } -@SyscallEntry(SyscallID.Close) -void Close(size_t id) { - import KMain : rootFS; +@SyscallEntry(SyscallID.close) +void close(size_t id) { + import kmain : rootFS; - Process* process = GetScheduler.CurrentProcess; + Process* process = getScheduler.currentProcess; - for (size_t i = 0; i < process.fileDescriptors.Length; i++) { - FileDescriptor* item = process.fileDescriptors.Get(i); + for (size_t i = 0; i < process.fileDescriptors.length; i++) { + FileDescriptor* item = process.fileDescriptors.get(i); if (item.id == id) { - item.node.Close(); + item.node.close(); item.destroy; - process.fileDescriptors.Remove(i); - process.syscallRegisters.RAX = 0; + process.fileDescriptors.remove(i); + process.syscallRegisters.rax = 0; return; } } - process.syscallRegisters.RAX = 1; + process.syscallRegisters.rax = 1; } -@SyscallEntry(SyscallID.Write) -void Write(size_t id, ubyte[] data, size_t offset) { - import KMain : rootFS; +@SyscallEntry(SyscallID.write) +void write(size_t id, ubyte[] data, size_t offset) { + import kmain : rootFS; - Process* process = GetScheduler.CurrentProcess; + Process* process = getScheduler.currentProcess; - if (false && !data.ptr.VirtAddress.IsValidToRead(data.length)) { - process.syscallRegisters.RAX = 0; - import IO.Log; + if (false && !data.ptr.VirtAddress.isValidToRead(data.length)) { + process.syscallRegisters.rax = 0; + import io.log; - log.Warning("Failed to Read!"); + log.warning("Failed to Read!"); return; } - for (size_t i = 0; i < process.fileDescriptors.Length; i++) { - FileDescriptor* item = process.fileDescriptors.Get(i); + for (size_t i = 0; i < process.fileDescriptors.length; i++) { + FileDescriptor* item = process.fileDescriptors.get(i); if (item.id == id) { - process.syscallRegisters.RAX = item.node.Write(data, offset); + process.syscallRegisters.rax = item.node.write(data, offset); return; } } - process.syscallRegisters.RAX = ulong.max; + process.syscallRegisters.rax = ulong.max; } -@SyscallEntry(SyscallID.Read) -void Read(size_t id, ubyte[] data, size_t offset) { - import KMain : rootFS; +@SyscallEntry(SyscallID.read) +void read(size_t id, ubyte[] data, size_t offset) { + import kmain : rootFS; - Process* process = GetScheduler.CurrentProcess; + Process* process = getScheduler.currentProcess; - if (false && !data.ptr.VirtAddress.IsValidToWrite(data.length)) { - process.syscallRegisters.RAX = 0; - import IO.Log; + if (false && !data.ptr.VirtAddress.isValidToWrite(data.length)) { + process.syscallRegisters.rax = 0; + import io.log; - log.Warning("Failed to Write!"); + log.warning("Failed to Write!"); return; } - for (size_t i = 0; i < process.fileDescriptors.Length; i++) { - FileDescriptor* item = process.fileDescriptors.Get(i); + for (size_t i = 0; i < process.fileDescriptors.length; i++) { + FileDescriptor* item = process.fileDescriptors.get(i); if (item.id == id) { - process.syscallRegisters.RAX = item.node.Read(data, offset); + process.syscallRegisters.rax = item.node.read(data, offset); return; } } - process.syscallRegisters.RAX = ulong.max; + process.syscallRegisters.rax = ulong.max; } -@SyscallEntry(SyscallID.GetTimestamp) -void GetTimestamp() { - import CPU.PIT; - import HW.CMOS.CMOS; +@SyscallEntry(SyscallID.getTimestamp) +void getTimestamp() { + import cpu.pit; + import hw.cmos.cmos; - Process* process = GetScheduler.CurrentProcess; - process.syscallRegisters.RAX = GetCMOS.TimeStamp; + Process* process = getScheduler.currentProcess; + process.syscallRegisters.rax = getCMOS.timeStamp; } struct DirectoryListing { enum Type { - Unknown, - File, - Directory + unknown, + file, + directory } size_t id; @@ -303,82 +302,82 @@ struct DirectoryListing { Type type; } -@SyscallEntry(SyscallID.ListDirectory) -void ListDirectory(void* listings_, size_t len) { - import IO.FS; +@SyscallEntry(SyscallID.listDirectory) +void listDirectory(void* listings_, size_t len) { + import io.fs; DirectoryListing[] listings = (cast(DirectoryListing*)listings_)[0 .. len]; - Process* process = GetScheduler.CurrentProcess; + Process* process = getScheduler.currentProcess; - Node[] nodes = process.currentDirectory.Nodes; + Node[] nodes = process.currentDirectory.nodes; auto length = nodes.length; if (listings.length < length) length = listings.length; foreach (i, ref DirectoryListing listing; listings[0 .. length]) { - listing.id = nodes[i].ID; - auto nLen = nodes[i].Name.length < 256 ? nodes[i].Name.length : 256; - memcpy(listing.name.ptr, nodes[i].Name.ptr, nLen); + listing.id = nodes[i].id; + auto nLen = nodes[i].name.length < 256 ? nodes[i].name.length : 256; + memcpy(listing.name.ptr, nodes[i].name.ptr, nLen); if (nLen < 256) nLen++; listing.name[nLen - 1] = '\0'; if (cast(FileNode)nodes[i]) - listing.type = DirectoryListing.Type.File; + listing.type = DirectoryListing.Type.file; else if (cast(DirectoryNode)nodes[i]) - listing.type = DirectoryListing.Type.Directory; + listing.type = DirectoryListing.Type.directory; else - listing.type = DirectoryListing.Type.Unknown; + listing.type = DirectoryListing.Type.unknown; } - process.syscallRegisters.RAX = length; + process.syscallRegisters.rax = length; } -@SyscallEntry(SyscallID.GetCurrentDirectory) -void GetCurrentDirectory(char[] str) { - import IO.FS; +@SyscallEntry(SyscallID.getCurrentDirectory) +void getCurrentDirectory(char[] str) { + import io.fs; - Process* process = GetScheduler.CurrentProcess; + Process* process = getScheduler.currentProcess; size_t currentOffset = 0; void add(DirectoryNode node) { - if (node.Parent) { - add(node.Parent); + if (node.parent) { + add(node.parent); - auto len = 1 + node.Name.length; + auto len = 1 + node.name.length; if (str.length - currentOffset < len) len = str.length - currentOffset; str[currentOffset++] = '/'; len--; - memcpy(&str[currentOffset], node.Name.ptr, len); + memcpy(&str[currentOffset], node.name.ptr, len); currentOffset += len; } } add(process.currentDirectory); - process.syscallRegisters.RAX = currentOffset; + process.syscallRegisters.rax = currentOffset; } -@SyscallEntry(SyscallID.ChangeCurrentDirectory) -void ChangeCurrentDirectory(string path) { - import IO.FS; +@SyscallEntry(SyscallID.changeCurrentDirectory) +void changeCurrentDirectory(string path) { + import io.fs; - Process* process = GetScheduler.CurrentProcess; - auto newDir = cast(DirectoryNode)process.currentDirectory.FindNode(path); + Process* process = getScheduler.currentProcess; + auto newDir = cast(DirectoryNode)process.currentDirectory.findNode(path); if (newDir) { process.currentDirectory = newDir; - process.syscallRegisters.RAX = 0; + process.syscallRegisters.rax = 0; } else - process.syscallRegisters.RAX = 1; + process.syscallRegisters.rax = 1; } -@SyscallEntry(SyscallID.Join) -void Join(size_t pid) { - import Task.Scheduler; +@SyscallEntry(SyscallID.join) +void join(size_t pid) { + import task.scheduler; - Scheduler s = GetScheduler; - Process* process = s.CurrentProcess; - process.syscallRegisters.RAX = s.Join(pid); + Scheduler s = getScheduler; + Process* process = s.currentProcess; + process.syscallRegisters.rax = s.join(pid); } diff --git a/kernel/src/system/syscallhandler.d b/kernel/src/system/syscallhandler.d index 10d521d..0896485 100644 --- a/kernel/src/system/syscallhandler.d +++ b/kernel/src/system/syscallhandler.d @@ -1,83 +1,91 @@ -module System.SyscallHandler; +module system.syscallhandler; -import CPU.IDT; -import CPU.MSR; -import Data.Register; -import System.Syscall; -import Data.Parameters; -import Data.Address; +import cpu.idt; +import cpu.msr; +import data.register; +import system.syscall; +import data.parameters; +import data.address; extern (C) void onSyscall(); +// for syscallhelper.S +extern (C) void _onSyscallHandler() { + asm { + naked; + jmp SyscallHandler._onSyscallHandler; + } +} + struct SyscallHandler { public: - static void Init() { - enum ulong USER_CS = 0x18 | 0x3; - enum ulong KERNEL_CS = 0x8; - enum ulong EFLAGS_INTERRUPT = 1 << 9; + static void init() { + enum ulong userCS = 0x18 | 0x3; + enum ulong kernelCS = 0x8; + enum ulong eflagsInterrupt = 1 << 9; - MSR.Star = (KERNEL_CS << 32UL | USER_CS << 48UL); - MSR.LStar = cast(ulong)&onSyscall; - MSR.SFMask = EFLAGS_INTERRUPT; + MSR.star = (kernelCS << 32UL | userCS << 48UL); + MSR.lStar = cast(ulong)&onSyscall; + MSR.sfMask = eflagsInterrupt; - IDT.Register(0x80, &onSyscallHandler); + IDT.register(0x80, &_onSyscallHandler); - import Task.Process; + import task.process; //XXX: Make generation of this value - pragma(msg, "Don't forget to update KERNEL_STACK in SyscallHelper.S to this value: ", + pragma(msg, "Don't forget to update kernelStack in syscallhelper.S to this value: ", Process.image.offsetof + ImageInformation.kernelStack.offsetof); } private: - static void onSyscallHandler(Registers* regs) { - import Data.TextBuffer : scr = GetBootTTY; - import Task.Scheduler : GetScheduler; + static void _onSyscallHandler(Registers* regs) { + import data.textbuffer : scr = getBootTTY; + import task.scheduler : getScheduler; - auto process = GetScheduler.CurrentProcess; + auto process = getScheduler.currentProcess; process.syscallRegisters = *regs; with (regs) - outer : switch (cast(SyscallID)RAX) { - foreach (func; __traits(derivedMembers, System.Syscall)) { - static if (is(typeof(mixin("System.Syscall." ~ func)) == function)) - foreach (attr; __traits(getAttributes, mixin("System.Syscall." ~ func))) { + outer : switch (cast(SyscallID)rax) { + foreach (func; __traits(derivedMembers, system.syscall)) { + static if (is(typeof(mixin("system.syscall." ~ func)) == function)) + foreach (attr; __traits(getAttributes, mixin("system.syscall." ~ func))) { static if (is(typeof(attr) == SyscallEntry)) { case attr.id: - mixin(generateFunctionCall!func); + mixin(_generateFunctionCall!func); break outer; } } } default: - scr.Writeln("UNKNOWN SYSCALL: ", cast(void*)RAX); - process.syscallRegisters.RAX = ulong.max; + scr.writeln("UNKNOWN SYSCALL: ", cast(void*)rax); + process.syscallRegisters.rax = ulong.max; break; } *regs = process.syscallRegisters; } - static string generateFunctionCall(alias func)() { + static string _generateFunctionCall(alias func)() { if (!__ctfe) // Without this it tries to use _d_arrayappendT return ""; - import Data.Util : isArray; + import data.util : isArray; - enum ABI = ["RDI", "RSI", "RDX", "R8", "R9", "R10", "R12", "R13", "R14", "R15"]; + enum abi = ["rdi", "rsi", "rdx", "r8", "r9", "r10", "r12", "r13", "r14", "r15"]; - alias p = Parameters!(mixin(func)); - string o = func ~ "("; + alias p = parameters!(mixin("system.syscall." ~ func)); + string o = "system.syscall." ~ func ~ "("; size_t abi_count; foreach (idx, val; p) { - assert(abi_count < ABI.length); + assert(abi_count < abi.length); static if (idx) o ~= ", "; static if (isArray!val) { - o ~= ABI[abi_count++]; - assert(abi_count < ABI.length); - o ~= ".Array!(" ~ val.stringof ~ ")(" ~ ABI[abi_count++] ~ ")"; + o ~= abi[abi_count++]; + assert(abi_count < abi.length); + o ~= ".array!(" ~ val.stringof ~ ")(" ~ abi[abi_count++] ~ ")"; } else - o ~= "cast(" ~ val.stringof ~ ")" ~ ABI[abi_count++] ~ ".Int"; //!(" ~ val.stringof ~ ")"; + o ~= "cast(" ~ val.stringof ~ ")" ~ abi[abi_count++] ~ ".num"; //!(" ~ val.stringof ~ ")"; } o ~= ");"; diff --git a/kernel/src/system/syscallhelper.S b/kernel/src/system/syscallhelper.S new file mode 100644 index 0000000..7c9c14b --- /dev/null +++ b/kernel/src/system/syscallhelper.S @@ -0,0 +1,73 @@ +.text +.code64 +.SET userCS, 0x18 | 0x3 +.SET kernelStack, 632//Process.image.offsetof + ImageInformation.kernelStack.offsetof + +.global _onSyscallHandler +.global _currentProcess + +.global onSyscall +.type onSyscall, %function +onSyscall: + mov %rsp, userStack + movq _currentProcess, %rsp + movq kernelStack(%rsp), %rsp + push (userStack) + + push $(userCS + 8) // SS + push (userStack) // RSP + push %r11 // Flags + push $(userCS) // CS + push %rcx // RIP + + push $0 // ErrorCode + push $0x80 // IntNumber + + push %rax + push %rbx + push %rcx + push %rdx + push %rsi + push %rdi + push %rbp + push %r8 + push %r9 + push %r10 + push %r11 + push %r12 + push %r13 + push %r14 + push %r15 + + mov %rsp, %rdi + call _onSyscallHandler + jmp returnFromSyscall +.size onSyscall, .-onSyscall + +.global returnFromSyscall +.type returnFromSyscall, %function +returnFromSyscall: + pop %r15 + pop %r14 + pop %r13 + pop %r12 + pop %r11 + pop %r10 + pop %r9 + pop %r8 + pop %rbp + pop %rdi + pop %rsi + pop %rdx + pop %rcx + pop %rbx + pop %rax + + add $(8*7), %rsp + + pop %rsp + sysretq +.size returnFromSyscall, .-returnFromSyscall +.bss +userStack: .long 1 +userRIP: .long 1 diff --git a/kernel/src/system/utils.d b/kernel/src/system/utils.d index d687a92..acff092 100644 --- a/kernel/src/system/utils.d +++ b/kernel/src/system/utils.d @@ -1,13 +1,13 @@ -module System.Utils; +module system.utils; -import Data.Address; -import Task.Scheduler; -import Memory.Paging; +import data.address; +import task.scheduler; +import memory.paging; -bool IsValidToRead(VirtAddress addr, ulong size) { +bool isValidToRead(VirtAddress addr, ulong size) { while (size > 0) { - auto page = currentProcess.threadState.paging.GetPage(addr); - if (!page || !page.Present) + auto page = getScheduler.currentProcess.threadState.paging.getPage(addr); + if (!page || !page.present) return false; size -= 0x1000; addr += 0x1000; @@ -15,11 +15,11 @@ bool IsValidToRead(VirtAddress addr, ulong size) { return true; } -bool IsValidToWrite(VirtAddress addr, ulong size) { +bool isValidToWrite(VirtAddress addr, ulong size) { ulong counter = 0; while (size > counter) { - auto page = currentProcess.threadState.paging.GetPage(addr); - if (!page || !page.Present || !(page.Mode & MapMode.Writable)) + auto page = getScheduler.currentProcess.threadState.paging.getPage(addr); + if (!page || !page.present || !(page.mode & MapMode.writable)) return false; counter += 0x1000; addr += 0x1000; diff --git a/kernel/src/task/mutex/assembly.S b/kernel/src/task/mutex/assembly.S new file mode 100644 index 0000000..bb45a96 --- /dev/null +++ b/kernel/src/task/mutex/assembly.S @@ -0,0 +1,24 @@ +.text +.code64 + +.global mutexSpinlock +mutexSpinlock: +1: + mov $1, %RBX; + lock cmpxchgq %RBX, (%RDI) + jnz 1b + ret + +.global mutexTrylock +mutexTrylock: + mov $1, %RBX; + lock cmpxchgq %RBX, (%RDI) + jnz 1f + mov $1, %RAX +1: + ret + +.global mutexUnlock +mutexUnlock: + movq $1, (%RDI) + ret diff --git a/kernel/src/task/mutex/schedulemutex.d b/kernel/src/task/mutex/schedulemutex.d index 3731388..cfc52a6 100644 --- a/kernel/src/task/mutex/schedulemutex.d +++ b/kernel/src/task/mutex/schedulemutex.d @@ -1,33 +1,33 @@ -module Task.Mutex.ScheduleMutex; +module task.mutex.schedulemutex; -import Task.Process; -import Task.Scheduler; +import task.process; +import task.scheduler; -private extern (C) ulong mutex_trylock(ulong* value); -private extern (C) void mutex_unlock(ulong* value); +private extern (C) ulong mutexTrylock(ulong* value); +private extern (C) void mutexUnlock(ulong* value); struct ScheduleMutex { public: - void Lock() { - while(!mutex_trylock(&value)) - GetScheduler.WaitFor(WaitReason.Mutex, cast(ulong)&this); + void lock() { + while (!mutexTrylock(&_value)) + getScheduler.waitFor(WaitReason.mutex, cast(ulong)&this); } - bool TryLock() { - return !!mutex_trylock(&value); + bool tryLock() { + return !!mutexTrylock(&_value); } - void Unlock() { - mutex_unlock(&value); - GetScheduler.WakeUp(WaitReason.Mutex, cast(WakeUpFunc)&mutexWakeUp, &this); + void unlock() { + mutexUnlock(&_value); + getScheduler.wakeUp(WaitReason.mutex, cast(WakeUpFunc)&_mutexWakeUp, &this); } private: - static bool mutexWakeUp(Process* p, ScheduleMutex* self) { - if(p.waitData == cast(ulong)self) + ulong _value; + + static bool _mutexWakeUp(Process* p, ScheduleMutex* self) { + if (p.waitData == cast(ulong)self) return true; return false; } - - ulong value; } diff --git a/kernel/src/task/mutex/spinlockmutex.d b/kernel/src/task/mutex/spinlockmutex.d index 9034a36..412805c 100644 --- a/kernel/src/task/mutex/spinlockmutex.d +++ b/kernel/src/task/mutex/spinlockmutex.d @@ -1,23 +1,23 @@ -module Task.Mutex.SpinLockMutex; +module task.mutex.spinlockmutex; -private extern (C) void mutex_spinlock(ulong* value); -private extern (C) ulong mutex_trylock(ulong* value); -private extern (C) void mutex_unlock(ulong* value); +private extern (C) void mutexSpinlock(ulong* value); +private extern (C) ulong mutexTrylock(ulong* value); +private extern (C) void mutexUnlock(ulong* value); struct SpinLockMutex { public: - void Lock() { - mutex_spinlock(&value); + void lock() { + mutexSpinlock(&_value); } - bool TryLock() { - return !!mutex_trylock(&value); + bool tryLock() { + return !!mutexTrylock(&_value); } - void Unlock() { - mutex_unlock(&value); + void unlock() { + mutexUnlock(&_value); } private: - ulong value; + ulong _value; } diff --git a/kernel/src/task/process.d b/kernel/src/task/process.d index d3e04fc..6820f18 100644 --- a/kernel/src/task/process.d +++ b/kernel/src/task/process.d @@ -1,13 +1,13 @@ -module Task.Process; +module task.process; -import Data.Address; -import Data.LinkedList; -import Memory.Paging; -import Memory.Heap; -import Data.Register; -import IO.FS.FileNode; -import IO.FS.DirectoryNode; -import Data.ELF; +import data.address; +import data.linkedlist; +import memory.paging; +import memory.heap; +import data.register; +import io.fs.filenode; +import io.fs.directorynode; +import data.elf; extern (C) void switchToUserMode(ulong loc, ulong stack); @@ -20,19 +20,19 @@ struct TLS { @disable this(); - static TLS* Init(Process* process, bool currentData = true) { + static TLS* init(Process* process, bool currentData = true) { if (currentData && process.parent) - return Init(process, process.parent.threadState.tls.startOfTLS); + return init(process, process.parent.threadState.tls.startOfTLS); else - return Init(process, process.image.defaultTLS); + return init(process, process.image.defaultTLS); } - static TLS* Init(Process* process, ubyte[] data) { - VirtAddress addr = VirtAddress(process.heap.Alloc(data.length + TLS.sizeof)); - memcpy(addr.Ptr, data.ptr, data.length); - TLS* this_ = (addr + data.length).Ptr!TLS; + static TLS* init(Process* process, ubyte[] data) { + VirtAddress addr = VirtAddress(process.heap.alloc(data.length + TLS.sizeof)); + memcpy(addr.ptr, data.ptr, data.length); + TLS* this_ = (addr + data.length).ptr!TLS; this_.self = this_; - this_.startOfTLS = addr.Ptr!ubyte[0 .. data.length]; + this_.startOfTLS = addr.ptr!ubyte[0 .. data.length]; this_.process = process; return this_; } @@ -61,17 +61,17 @@ struct ImageInformation { } enum ProcessState { - Running, - Ready, - Waiting, - Exited + running, + ready, + waiting, + exited } enum WaitReason { - Keyboard, - Timer, - Mutex, - Join //more e.g. harddrive, networking, mutex... + keyboard, + timer, + mutex, + join //more e.g. harddrive, networking, mutex... } struct FileDescriptor { @@ -80,13 +80,13 @@ struct FileDescriptor { this(FileDescriptor* fd) { this.id = fd.id; this.node = fd.node; - node.Open(); + node.open(); } this(size_t id, FileNode node) { this.id = id; this.node = node; - node.Open(); + node.open(); } } diff --git a/kernel/src/task/scheduler.d b/kernel/src/task/scheduler.d index 7b70393..9d82880 100644 --- a/kernel/src/task/scheduler.d +++ b/kernel/src/task/scheduler.d @@ -1,16 +1,16 @@ -module Task.Scheduler; -import Data.Address; -import Data.Color; -import Data.LinkedList; -import Task.Process; -import CPU.GDT; -import CPU.PIT; -import Task.Mutex.SpinLockMutex; -import Data.TextBuffer : scr = GetBootTTY; -import Memory.Heap; -import Memory.Paging; -import KMain : rootFS; -import IO.ConsoleManager; +module task.scheduler; +import data.address; +import data.color; +import data.linkedlist; +import task.process; +import cpu.gdt; +import cpu.pit; +import task.mutex.spinlockmutex; +import data.textbuffer : scr = getBootTTY; +import memory.heap; +import memory.paging; +import kmain : rootFS; +import io.consolemanager; private extern (C) { extern __gshared ubyte KERNEL_STACK_START; @@ -20,24 +20,24 @@ private extern (C) { void cloneHelper(); } -extern (C) __gshared Process* currentProcess; +extern (C) __gshared Process* _currentProcess; alias WakeUpFunc = bool function(Process*, void*); class Scheduler { public: - void Init() { - allProcesses = new LinkedList!Process(); - readyProcesses = new LinkedList!Process(); - waitingProcesses = new LinkedList!Process(); - initIdle(); // PID 0 - initKernel(); // PID 1 - pidCounter = 2; - currentProcess = initProcess; + void init() { + _allProcesses = new LinkedList!Process(); + _readyProcesses = new LinkedList!Process(); + _waitingProcesses = new LinkedList!Process(); + _initIdle(); // PID 0 + _initKernel(); // PID 1 + _pidCounter = 2; + _currentProcess = _initProcess; } - void SwitchProcess(bool reschedule = true) { - if (!currentProcess) + void switchProcess(bool reschedule = true) { + if (!_currentProcess) return; ulong storeRIP = void; @@ -64,7 +64,7 @@ public: call getRIP; mov storeRIP[RBP], RAX; - mov RCX, SWITCH_MAGIC; + mov RCX, _switchMagic; cmp RCX, RAX; jne noReturn; @@ -81,7 +81,7 @@ public: pop RCX; } - with (currentProcess.threadState) { + with (_currentProcess.threadState) { rbp = storeRBP; rsp = storeRSP; rip = storeRIP; @@ -94,201 +94,201 @@ public: } } - if (reschedule && currentProcess != idleProcess) { - currentProcess.state = ProcessState.Ready; - readyProcesses.Add(currentProcess); + if (reschedule && _currentProcess != _idleProcess) { + _currentProcess.state = ProcessState.ready; + _readyProcesses.add(_currentProcess); } - doSwitching(); + _doSwitching(); } - void WaitFor(WaitReason reason, ulong data = 0) { - currentProcess.state = ProcessState.Waiting; - currentProcess.wait = reason; - currentProcess.waitData = data; - waitingProcesses.Add(currentProcess); - SwitchProcess(false); + void waitFor(WaitReason reason, ulong data = 0) { + _currentProcess.state = ProcessState.waiting; + _currentProcess.wait = reason; + _currentProcess.waitData = data; + _waitingProcesses.add(_currentProcess); + switchProcess(false); } - void WakeUp(WaitReason reason, WakeUpFunc check = &wakeUpDefault, void* data = cast(void*)0) { + void wakeUp(WaitReason reason, WakeUpFunc check = &_wakeUpDefault, void* data = cast(void*)0) { bool wokeUp = false; - for (int i = 0; i < waitingProcesses.Length; i++) { - Process* p = waitingProcesses.Get(i); + for (int i = 0; i < _waitingProcesses.length; i++) { + Process* p = _waitingProcesses.get(i); if (p.wait == reason && check(p, data)) { wokeUp = true; - waitingProcesses.Remove(i); - readyProcesses.Add(p); + _waitingProcesses.remove(i); + _readyProcesses.add(p); } } - if (wokeUp && currentProcess == idleProcess) - SwitchProcess(); + if (wokeUp && _currentProcess == _idleProcess) + switchProcess(); } - void USleep(ulong usecs) { + void uSleep(ulong usecs) { if (!usecs) usecs = 1; - WaitFor(WaitReason.Timer, usecs); + waitFor(WaitReason.timer, usecs); } - PID Fork() { - import IO.Log : log; - import Memory.Paging : Paging; + PID fork() { + import io.log : log; + import memory.paging : Paging; Process* process = new Process(); - VirtAddress kernelStack = VirtAddress(new ubyte[StackSize].ptr) + StackSize; + VirtAddress kernelStack = VirtAddress(new ubyte[_stackSize].ptr) + _stackSize; process.image.kernelStack = kernelStack; - process.image.defaultTLS = currentProcess.image.defaultTLS; + process.image.defaultTLS = _currentProcess.image.defaultTLS; void set(T = ulong)(ref VirtAddress stack, T value) { auto size = T.sizeof; - *(stack - size).Ptr!T = value; + *(stack - size).ptr!T = value; stack -= size; } - process.syscallRegisters = currentProcess.syscallRegisters; - process.syscallRegisters.RAX = 0; + process.syscallRegisters = _currentProcess.syscallRegisters; + process.syscallRegisters.rax = 0; set(kernelStack, process.syscallRegisters); with (process) { - pid = getFreePid; - name = currentProcess.name.dup; + pid = _getFreePid; + name = _currentProcess.name.dup; - uid = currentProcess.uid; - gid = currentProcess.gid; + uid = _currentProcess.uid; + gid = _currentProcess.gid; - parent = currentProcess; - heap = new Heap(currentProcess.heap); + parent = _currentProcess; + heap = new Heap(_currentProcess.heap); threadState.rip = VirtAddress(&cloneHelper); threadState.rbp = kernelStack; threadState.rsp = kernelStack; - threadState.fpuEnabled = currentProcess.threadState.fpuEnabled; - threadState.paging = new Paging(currentProcess.threadState.paging); - threadState.tls = TLS.Init(process); + threadState.fpuEnabled = _currentProcess.threadState.fpuEnabled; + threadState.paging = new Paging(_currentProcess.threadState.paging); + threadState.tls = TLS.init(process); - kernelProcess = currentProcess.kernelProcess; + kernelProcess = _currentProcess.kernelProcess; - currentDirectory = currentProcess.currentDirectory; + currentDirectory = _currentProcess.currentDirectory; fileDescriptors = new LinkedList!FileDescriptor; - for (size_t i = 0; i < currentProcess.fileDescriptors.Length; i++) - fileDescriptors.Add(new FileDescriptor(currentProcess.fileDescriptors.Get(i))); - fdCounter = currentProcess.fdCounter; + for (size_t i = 0; i < _currentProcess.fileDescriptors.length; i++) + fileDescriptors.add(new FileDescriptor(_currentProcess.fileDescriptors.get(i))); + fdCounter = _currentProcess.fdCounter; - state = ProcessState.Ready; + state = ProcessState.ready; } - with (currentProcess) { + with (_currentProcess) { if (!children) children = new LinkedList!Process; - children.Add(process); + children.add(process); } - allProcesses.Add(process); - readyProcesses.Add(process); + _allProcesses.add(process); + _readyProcesses.add(process); return process.pid; } alias CloneFunc = ulong function(void*); - PID Clone(CloneFunc func, VirtAddress userStack, void* userdata, string processName) { + PID clone(CloneFunc func, VirtAddress userStack, void* userdata, string processName) { Process* process = new Process(); - import IO.Log; + import io.log; - log.Debug("userStack: ", userStack); - if (!userStack.Int) // currentProcess.heap will be new the new process heap - userStack = VirtAddress(currentProcess.heap.Alloc(StackSize)) + StackSize; - VirtAddress kernelStack = VirtAddress(new ubyte[StackSize].ptr) + StackSize; + log.debug_("userStack: ", userStack); + if (!userStack.num) // _currentProcess.heap will be new the new process heap + userStack = VirtAddress(_currentProcess.heap.alloc(_stackSize)) + _stackSize; + VirtAddress kernelStack = VirtAddress(new ubyte[_stackSize].ptr) + _stackSize; process.image.userStack = userStack; process.image.kernelStack = kernelStack; - process.image.defaultTLS = currentProcess.image.defaultTLS; + process.image.defaultTLS = _currentProcess.image.defaultTLS; void set(T = ulong)(ref VirtAddress stack, T value) { auto size = T.sizeof; - *(stack - size).Ptr!T = value; + *(stack - size).ptr!T = value; stack -= size; } with (process.syscallRegisters) { - RBP = userStack; - RDI = VirtAddress(userdata); - RAX = 0xDEAD_C0DE; + rbp = userStack; + rdi = VirtAddress(userdata); + rax = 0xDEAD_C0DE; } set(userStack, 0); // Jump to null if it forgot to run exit. with (process.syscallRegisters) { - RIP = VirtAddress(func); - CS = currentProcess.syscallRegisters.CS; - Flags = currentProcess.syscallRegisters.Flags; - RSP = userStack; - SS = currentProcess.syscallRegisters.SS; + rip = VirtAddress(func); + cs = _currentProcess.syscallRegisters.cs; + flags = _currentProcess.syscallRegisters.flags; + rsp = userStack; + ss = _currentProcess.syscallRegisters.ss; } set(kernelStack, process.syscallRegisters); with (process) { - pid = getFreePid; + pid = _getFreePid; name = processName.dup; - uid = currentProcess.uid; - gid = currentProcess.gid; + uid = _currentProcess.uid; + gid = _currentProcess.gid; - parent = currentProcess; - heap = currentProcess.heap; - currentProcess.heap.RefCounter++; + parent = _currentProcess; + heap = _currentProcess.heap; + _currentProcess.heap.refCounter++; threadState.rip = VirtAddress(&cloneHelper); threadState.rbp = kernelStack; threadState.rsp = kernelStack; - threadState.fpuEnabled = currentProcess.threadState.fpuEnabled; - threadState.paging = currentProcess.threadState.paging; - threadState.paging.RefCounter++; - threadState.tls = TLS.Init(process, false); + threadState.fpuEnabled = _currentProcess.threadState.fpuEnabled; + threadState.paging = _currentProcess.threadState.paging; + threadState.paging.refCounter++; + threadState.tls = TLS.init(process, false); // image.stack is set above - kernelProcess = currentProcess.kernelProcess; + kernelProcess = _currentProcess.kernelProcess; - currentDirectory = currentProcess.currentDirectory; + currentDirectory = _currentProcess.currentDirectory; fileDescriptors = new LinkedList!FileDescriptor; - for (size_t i = 0; i < currentProcess.fileDescriptors.Length; i++) - fileDescriptors.Add(new FileDescriptor(currentProcess.fileDescriptors.Get(i))); - fdCounter = currentProcess.fdCounter; + for (size_t i = 0; i < _currentProcess.fileDescriptors.length; i++) + fileDescriptors.add(new FileDescriptor(_currentProcess.fileDescriptors.get(i))); + fdCounter = _currentProcess.fdCounter; - state = ProcessState.Ready; + state = ProcessState.ready; } - with (currentProcess) { + with (_currentProcess) { if (!children) children = new LinkedList!Process; - children.Add(process); + children.add(process); } - allProcesses.Add(process); - readyProcesses.Add(process); + _allProcesses.add(process); + _readyProcesses.add(process); return process.pid; } - ulong Join(PID pid = 0) { - if (!currentProcess.children) + ulong join(PID pid = 0) { + if (!_currentProcess.children) return 0x1000; while (true) { bool foundit; - for (int i = 0; i < currentProcess.children.Length; i++) { - Process* child = currentProcess.children.Get(i); + for (int i = 0; i < _currentProcess.children.length; i++) { + Process* child = _currentProcess.children.get(i); if (pid == 0 || child.pid == pid) { foundit = true; - if (child.state == ProcessState.Exited) { + if (child.state == ProcessState.exited) { ulong code = child.returnCode; - currentProcess.children.Remove(child); - allProcesses.Remove(child); + _currentProcess.children.remove(child); + _allProcesses.remove(child); with (child) { name.destroy; @@ -306,40 +306,40 @@ public: if (pid && !foundit) return 0x1001; - WaitFor(WaitReason.Join, pid); + waitFor(WaitReason.join, pid); } } - void Exit(ulong returncode) { - import IO.Log : log; + void exit(ulong returncode) { + import io.log : log; - currentProcess.returnCode = returncode; - currentProcess.state = ProcessState.Exited; + _currentProcess.returnCode = returncode; + _currentProcess.state = ProcessState.exited; - log.Info(currentProcess.pid, "(", currentProcess.name, ") is now dead! Returncode: ", cast(void*)returncode); + log.info(_currentProcess.pid, "(", _currentProcess.name, ") is now dead! Returncode: ", cast(void*)returncode); - if (currentProcess == initProcess) { - auto fg = scr.Foreground; - auto bg = scr.Background; - scr.Foreground = Color(255, 0, 255); - scr.Background = Color(255, 255, 0); - scr.Writeln("Init process exited. No more work to do."); - scr.Foreground = fg; - scr.Background = bg; - log.Fatal("Init process exited. No more work to do."); + if (_currentProcess == _initProcess) { + auto fg = scr.foreground; + auto bg = scr.background; + scr.foreground = Color(255, 0, 255); + scr.background = Color(255, 255, 0); + scr.writeln("init process exited. No more work to do."); + scr.foreground = fg; + scr.background = bg; + log.fatal("init process exited. No more work to do."); } - for (size_t i = 0; i < currentProcess.fileDescriptors.Length; i++) { - FileDescriptor* fd = currentProcess.fileDescriptors.Get(i); - fd.node.Close(); + for (size_t i = 0; i < _currentProcess.fileDescriptors.length; i++) { + FileDescriptor* fd = _currentProcess.fileDescriptors.get(i); + fd.node.close(); fd.destroy; } - if (currentProcess.children) { - for (int i = 0; i < currentProcess.children.Length; i++) { - Process* child = currentProcess.children[i]; + if (_currentProcess.children) { + for (int i = 0; i < _currentProcess.children.length; i++) { + Process* child = _currentProcess.children[i]; - if (child.state == ProcessState.Exited) { + if (child.state == ProcessState.exited) { child.name.destroy; child.description.destroy; //TODO free stack @@ -347,57 +347,57 @@ public: child.destroy; } else { //TODO send SIGHUP etc. - initProcess.children.Add(child); + _initProcess.children.add(child); } } - currentProcess.children.destroy; + _currentProcess.children.destroy; } - WakeUp(WaitReason.Join, cast(WakeUpFunc)&wakeUpJoin, cast(void*)currentProcess); - SwitchProcess(false); + wakeUp(WaitReason.join, cast(WakeUpFunc)&_wakeUpJoin, cast(void*)_currentProcess); + switchProcess(false); assert(0); } - @property Process* CurrentProcess() { - return currentProcess; + @property Process* currentProcess() { + return _currentProcess; } - @property LinkedList!Process AllProcesses() { - return allProcesses; + @property LinkedList!Process allProcesses() { + return _allProcesses; } private: - enum StackSize = 0x1_0000; - enum ulong SWITCH_MAGIC = 0x1111_DEAD_C0DE_1111; + enum _stackSize = 0x1_0000; + enum ulong _switchMagic = 0x1111_DEAD_C0DE_1111; - ulong pidCounter; - bool initialized; - LinkedList!Process allProcesses; - LinkedList!Process readyProcesses; - LinkedList!Process waitingProcesses; + ulong _pidCounter; + bool _initialized; + LinkedList!Process _allProcesses; + LinkedList!Process _readyProcesses; + LinkedList!Process _waitingProcesses; - Process* idleProcess; - Process* initProcess; + Process* _idleProcess; + Process* _initProcess; - ulong getFreePid() { - import IO.Log : log; + ulong _getFreePid() { + import io.log : log; - if (pidCounter == ulong.max) - log.Fatal("Out of pids!"); - return pidCounter++; + if (_pidCounter == ulong.max) + log.fatal("Out of pids!"); + return _pidCounter++; } - static bool wakeUpDefault(Process* p, void* data) { + static bool _wakeUpDefault(Process* p, void* data) { return true; } - static bool wakeUpJoin(Process* p, Process* child) { + static bool _wakeUpJoin(Process* p, Process* child) { if (p == child.parent && (p.waitData == 0 || p.waitData == child.pid)) return true; return false; } - static void idle() { + static void _idle() { asm { start: sti; @@ -406,22 +406,22 @@ private: } } - void initIdle() { - import Memory.Paging : GetKernelPaging; + void _initIdle() { + import memory.paging : getKernelPaging; - VirtAddress userStack = VirtAddress(new ubyte[StackSize].ptr) + StackSize; - VirtAddress kernelStack = VirtAddress(new ubyte[StackSize].ptr) + StackSize; - idleProcess = new Process(); + VirtAddress userStack = VirtAddress(new ubyte[_stackSize].ptr) + _stackSize; + VirtAddress kernelStack = VirtAddress(new ubyte[_stackSize].ptr) + _stackSize; + _idleProcess = new Process(); - with (idleProcess.syscallRegisters) { - RIP = VirtAddress(&idle); - CS = 0x8; - Flags = 0x202; - RSP = userStack; - SS = CS + 8; + with (_idleProcess.syscallRegisters) { + rip = VirtAddress(&_idle); + cs = 0x8; + flags = 0x202; + rsp = userStack; + ss = cs + 8; } - with (idleProcess) { + with (_idleProcess) { pid = 0; name = "[Idle]"; description = "Idle thread"; @@ -429,40 +429,40 @@ private: uid = 0; gid = 0; - heap = GetKernelHeap; - heap.RefCounter++; + heap = getKernelHeap; + heap.refCounter++; - threadState.rip = VirtAddress(&idle); + threadState.rip = VirtAddress(&_idle); threadState.rbp = userStack; threadState.rsp = userStack; threadState.fpuEnabled = false; - threadState.paging = GetKernelPaging(); - threadState.paging.RefCounter++; - threadState.tls = TLS.Init(idleProcess); // image.defaultTLS is empty + threadState.paging = getKernelPaging(); + threadState.paging.refCounter++; + threadState.tls = TLS.init(_idleProcess); // image.defaultTLS is empty image.userStack = userStack; image.kernelStack = kernelStack; kernelProcess = true; - currentDirectory = rootFS.Root; + currentDirectory = rootFS.root; fileDescriptors = new LinkedList!FileDescriptor; - state = ProcessState.Ready; + state = ProcessState.ready; } - allProcesses.Add(idleProcess); + _allProcesses.add(_idleProcess); } - void initKernel() { - import Memory.Paging : GetKernelPaging; + void _initKernel() { + import memory.paging : getKernelPaging; - initProcess = new Process(); + _initProcess = new Process(); - VirtAddress kernelStack = VirtAddress(new ubyte[StackSize].ptr) + StackSize; - with (initProcess) { + VirtAddress kernelStack = VirtAddress(new ubyte[_stackSize].ptr) + _stackSize; + with (_initProcess) { pid = 1; - name = "Init"; + name = "init"; description = "The init process"; uid = 0; gid = 0; @@ -471,48 +471,48 @@ private: threadState.rbp = VirtAddress(0); threadState.rsp = VirtAddress(0); threadState.fpuEnabled = false; - threadState.paging = GetKernelPaging(); - //threadState.paging.RefCounter++; Not needed. "Is" already +1 for this - threadState.tls = null; // This will be initialized when the init process is loaded + threadState.paging = getKernelPaging(); + //threadState.paging.refCounter++; Not needed. "Is" already +1 for this + threadState.tls = null; // This will be _initialized when the init process is loaded image.userStack = VirtAddress(&KERNEL_STACK_START); image.kernelStack = kernelStack; kernelProcess = false; - currentDirectory = rootFS.Root; + currentDirectory = rootFS.root; fileDescriptors = new LinkedList!FileDescriptor; - fileDescriptors.Add(new FileDescriptor(fdCounter++, GetConsoleManager.VirtualConsoles[0])); + fileDescriptors.add(new FileDescriptor(fdCounter++, getConsoleManager.virtualConsoles[0])); - state = ProcessState.Running; + state = ProcessState.running; - heap = null; // This will be initialized when the init process is loaded + heap = null; // This will be _initialized when the init process is loaded } - allProcesses.Add(initProcess); + _allProcesses.add(_initProcess); } - Process* nextProcess() { - if (readyProcesses.Length) - return readyProcesses.Remove(0); + Process* _nextProcess() { + if (_readyProcesses.length) + return _readyProcesses.remove(0); else - return idleProcess; + return _idleProcess; } - void doSwitching() { - import CPU.MSR; + void _doSwitching() { + import cpu.msr; - currentProcess = nextProcess(); - currentProcess.state = ProcessState.Running; + _currentProcess = _nextProcess(); + _currentProcess.state = ProcessState.running; - ulong storeRIP = currentProcess.threadState.rip; - ulong storeRBP = currentProcess.threadState.rbp; - ulong storeRSP = currentProcess.threadState.rsp; + ulong storeRIP = _currentProcess.threadState.rip; + ulong storeRBP = _currentProcess.threadState.rbp; + ulong storeRSP = _currentProcess.threadState.rsp; - currentProcess.threadState.paging.Install(); + _currentProcess.threadState.paging.install(); - MSR.FSBase = cast(ulong)currentProcess.threadState.tls; + MSR.fsBase = cast(ulong)_currentProcess.threadState.tls; - GDT.tss.RSP0 = currentProcess.image.kernelStack; + GDT.tss.rsp0 = _currentProcess.image.kernelStack; asm { mov RAX, RBP; // RBP will be overritten below @@ -520,18 +520,18 @@ private: mov RCX, storeRIP[RAX]; // RCX is the return address mov RBP, storeRBP[RAX]; mov RSP, storeRSP[RAX]; - mov RAX, SWITCH_MAGIC; + mov RAX, _switchMagic; jmp RCX; } } } -Scheduler GetScheduler() { - import Data.Util : InplaceClass; +Scheduler getScheduler() { + import data.util : inplaceClass; __gshared Scheduler scheduler; __gshared ubyte[__traits(classInstanceSize, Scheduler)] data; if (!scheduler) - scheduler = InplaceClass!Scheduler(data); + scheduler = inplaceClass!Scheduler(data); return scheduler; } diff --git a/kernel/src/task/task.S b/kernel/src/task/task.S new file mode 100644 index 0000000..a85fe08 --- /dev/null +++ b/kernel/src/task/task.S @@ -0,0 +1,125 @@ +.text +.code64 + +.SET userSS, 0x20 | 0x3 +.SET userCS, 0x18 | 0x3 + +.global switchToUserMode +.type switchToUserMode, %function +switchToUserMode: // RIP = %rdi, RSP = %rsi + // Data segmentation registers + mov $userSS, %ax + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + mov %rsi, %rsp + + push $exitHelper + mov %rsp, %rbp + + mov %rsp, %rax + + // Data segmentation SS + push $userSS + + // Stack pointer + push %rax + + // FLAGS, Enabling interrupt + pushfq + pop %rax + orq $0x200, %rax + push %rax + + // Code segmentation register + push $userCS + + // Instruction pointer + push %rdi + + mov $0, %rax + mov %rax, %rbx + mov %rax, %rcx + mov %rax, %rdx + mov %rax, %rsi + mov %rax, %rdi + mov %rax, %rbp + mov %rax, %r8 + mov %rax, %r9 + mov %rax, %r10 + mov %rax, %r11 + mov %rax, %r12 + mov %rax, %r13 + mov %rax, %r14 + mov %rax, %r15 + + iretq + +.size switchToUserMode, .-switchToUserMode + + +.global getRIP +.type getRIP, %function +getRIP: + mov (%rsp), %rax + ret +.size getRIP, .-getRIP + +.global fpuEnable +.type fpuEnable, %function +fpuEnable: + clts + mov %cr0, %rcx + or $0x8, %rcx + movq %rcx, %cr0 + ret +.size fpuEnable, .-fpuEnable + +.global fpuDisable +.type fpuDisable, %function +fpuDisable: + mov %cr4, %rcx + or $600, %rcx + movq %rcx, %cr4 + ret +.size fpuDisable, .-fpuDisable + +.global cloneHelper +.type cloneHelper, %function +cloneHelper: + pop %r15 + pop %r14 + pop %r13 + pop %r12 + pop %r11 + pop %r10 + pop %r9 + pop %r8 + pop %rbp + pop %rdi + pop %rsi + pop %rdx + pop %rcx + pop %rbx + pop %rax + + add $0x10, %rsp + + iretq +.size cloneHelper, .-cloneHelper + +.global exitHelper +.type exitHelper, %function +exitHelper: + mov %rax, %rdi + mov $0, %rax + int $0x80 +.size exitHelper, .-exitHelper + +.global getCS +.type getCS, %function +getCS: + mov %cs, %rax + ret +.size getCS, .-getCS diff --git a/reggaefile.d b/reggaefile.d index fdec1bf..ccac103 100644 --- a/reggaefile.d +++ b/reggaefile.d @@ -6,22 +6,22 @@ import std.range; //dfmt off template AllDFiles(string dir) { - static if (dir == "Kernel/src") - enum files = "Kernel/src/CPU/TSS.d Kernel/src/CPU/GDT.d Kernel/src/CPU/IDT.d Kernel/src/CPU/MSR.d Kernel/src/CPU/PIT.d Kernel/src/Data/BitField.d Kernel/src/Data/Linker.d Kernel/src/Data/Screen.d Kernel/src/Data/Parameters.d Kernel/src/Data/Address.d Kernel/src/Data/BMPImage.d Kernel/src/Data/LinkedList.d Kernel/src/Data/Register.d Kernel/src/Data/String.d Kernel/src/Data/Util.d Kernel/src/Data/Color.d Kernel/src/Data/ELF.d Kernel/src/Data/Multiboot.d Kernel/src/Data/TextBuffer.d Kernel/src/Data/UTF.d Kernel/src/Data/Font.d Kernel/src/Data/PSF.d Kernel/src/Memory/FrameAllocator.d Kernel/src/Memory/Paging.d Kernel/src/Memory/Heap.d Kernel/src/IO/FS/package.d Kernel/src/IO/FS/Node.d Kernel/src/IO/FS/NodePermission.d Kernel/src/IO/FS/Initrd/package.d Kernel/src/IO/FS/Initrd/FSRoot.d Kernel/src/IO/FS/Initrd/FileNode.d Kernel/src/IO/FS/System/package.d Kernel/src/IO/FS/System/FSRoot.d Kernel/src/IO/FS/System/VersionNode.d Kernel/src/IO/FS/HardLinkNode.d Kernel/src/IO/FS/SoftLinkNode.d Kernel/src/IO/FS/DirectoryNode.d Kernel/src/IO/FS/FSRoot.d Kernel/src/IO/FS/FileNode.d Kernel/src/IO/FS/IO/BoolNode.d Kernel/src/IO/FS/IO/Console/Console.d Kernel/src/IO/FS/IO/Console/Screen/FormattedChar.d Kernel/src/IO/FS/IO/Console/Screen/VirtualConsoleScreen.d Kernel/src/IO/FS/IO/Console/Screen/VirtualConsoleScreenFramebuffer.d Kernel/src/IO/FS/IO/Console/Screen/VirtualConsoleScreenTextMode.d Kernel/src/IO/FS/IO/Console/Screen/package.d Kernel/src/IO/FS/IO/Console/SerialConsole.d Kernel/src/IO/FS/IO/Console/VirtualConsole.d Kernel/src/IO/FS/IO/Console/package.d Kernel/src/IO/FS/IO/Framebuffer/BGAFramebuffer.d Kernel/src/IO/FS/IO/Framebuffer/package.d Kernel/src/IO/FS/IO/Framebuffer/Framebuffer.d Kernel/src/IO/FS/IO/ZeroNode.d Kernel/src/IO/FS/IO/package.d Kernel/src/IO/FS/IO/FSRoot.d Kernel/src/IO/FS/MountPointNode.d Kernel/src/IO/Port.d Kernel/src/IO/TextMode.d Kernel/src/IO/COM.d Kernel/src/IO/Keyboard.d Kernel/src/IO/Log.d Kernel/src/IO/ConsoleManager.d Kernel/src/invariant.d Kernel/src/HW/PS2/KBSet.d Kernel/src/HW/PS2/Keyboard.d Kernel/src/HW/PCI/PCI.d Kernel/src/HW/CMOS/CMOS.d Kernel/src/Task/Mutex/ScheduleMutex.d Kernel/src/Task/Mutex/SpinLockMutex.d Kernel/src/Task/Process.d Kernel/src/Task/Scheduler.d Kernel/src/Bin/ConsoleFont.d Kernel/src/ACPI/RSDP.d Kernel/src/System/SyscallHandler.d Kernel/src/System/Utils.d Kernel/src/System/Syscall.d Kernel/src/object.d Kernel/src/KMain.d"; - else static if (dir == "Userspace/libRT/src") - enum files = "Userspace/libRT/src/invariant.d Userspace/libRT/src/object.d"; - else static if (dir == "Userspace/libPowerNex/src") - enum files = "Userspace/libPowerNex/src/PowerNex/Data/Address.d Userspace/libPowerNex/src/PowerNex/Data/Parameters.d Userspace/libPowerNex/src/PowerNex/Data/String.d Userspace/libPowerNex/src/PowerNex/Data/Util.d Userspace/libPowerNex/src/PowerNex/Data/Color.d Userspace/libPowerNex/src/PowerNex/Data/BMPImage.d Userspace/libPowerNex/src/PowerNex/Syscall.d"; - else static if (dir == "Userspace/Init/src") - enum files = "Userspace/Init/src/app.d"; - else static if (dir == "Userspace/Shell/src") - enum files = "Userspace/Shell/src/app.d"; - else static if (dir == "Userspace/HelloWorld/src") - enum files = "Userspace/HelloWorld/src/app.d"; - else static if (dir == "Userspace/Cat/src") - enum files = "Userspace/Cat/src/app.d"; - else static if (dir == "Userspace/DLogo/src") - enum files = "Userspace/DLogo/src/app.d"; + static if (dir == "kernel/src") + enum files = "kernel/src/invariant.d kernel/src/object.d kernel/src/kmain.d kernel/src/acpi/rsdp.d kernel/src/bin/consolefont.d kernel/src/cpu/gdt.d kernel/src/cpu/idt.d kernel/src/cpu/msr.d kernel/src/cpu/tss.d kernel/src/cpu/pit.d kernel/src/data/address.d kernel/src/data/bitfield.d kernel/src/data/bmpimage.d kernel/src/data/color.d kernel/src/data/elf.d kernel/src/data/font.d kernel/src/data/linkedlist.d kernel/src/data/linker.d kernel/src/data/multiboot.d kernel/src/data/parameters.d kernel/src/data/psf.d kernel/src/data/register.d kernel/src/data/screen.d kernel/src/data/textbuffer.d kernel/src/data/utf.d kernel/src/data/util.d kernel/src/data/string_.d kernel/src/hw/cmos/cmos.d kernel/src/hw/pci/pci.d kernel/src/hw/ps2/kbset.d kernel/src/hw/ps2/keyboard.d kernel/src/io/com.d kernel/src/io/port.d kernel/src/io/consolemanager.d kernel/src/io/log.d kernel/src/io/textmode.d kernel/src/io/fs/node.d kernel/src/io/fs/filenode.d kernel/src/io/fs/directorynode.d kernel/src/io/fs/package.d kernel/src/io/fs/softlinknode.d kernel/src/io/fs/hardlinknode.d kernel/src/io/fs/mountpointnode.d kernel/src/io/fs/nodepermission.d kernel/src/io/fs/fsroot.d kernel/src/io/fs/system/fsroot.d kernel/src/io/fs/system/versionnode.d kernel/src/io/fs/system/package.d kernel/src/io/fs/initrd/package.d kernel/src/io/fs/initrd/fsroot.d kernel/src/io/fs/initrd/filenode.d kernel/src/io/fs/io/package.d kernel/src/io/fs/io/boolnode.d kernel/src/io/fs/io/zeronode.d kernel/src/io/fs/io/fsroot.d kernel/src/io/fs/io/framebuffer/package.d kernel/src/io/fs/io/framebuffer/framebuffer.d kernel/src/io/fs/io/framebuffer/bgaframebuffer.d kernel/src/io/fs/io/console/console.d kernel/src/io/fs/io/console/package.d kernel/src/io/fs/io/console/serialconsole.d kernel/src/io/fs/io/console/virtualconsole.d kernel/src/io/fs/io/console/screen/package.d kernel/src/io/fs/io/console/screen/formattedchar.d kernel/src/io/fs/io/console/screen/virtualconsolescreen.d kernel/src/io/fs/io/console/screen/virtualconsolescreentextmode.d kernel/src/io/fs/io/console/screen/virtualconsolescreenframebuffer.d kernel/src/memory/frameallocator.d kernel/src/memory/heap.d kernel/src/memory/paging.d kernel/src/system/utils.d kernel/src/system/syscall.d kernel/src/system/syscallhandler.d kernel/src/task/process.d kernel/src/task/scheduler.d kernel/src/task/mutex/spinlockmutex.d kernel/src/task/mutex/schedulemutex.d"; + else static if (dir == "userspace/librt/src") + enum files = "userspace/librt/src/invariant.d userspace/librt/src/object.d"; + else static if (dir == "userspace/libpowernex/src") + enum files = "userspace/libpowernex/src/powernex/data/address.d userspace/libpowernex/src/powernex/data/parameters.d userspace/libpowernex/src/powernex/data/string_.d userspace/libpowernex/src/powernex/data/util.d userspace/libpowernex/src/powernex/data/color.d userspace/libpowernex/src/powernex/data/bmpimage.d userspace/libpowernex/src/powernex/syscall.d"; + else static if (dir == "userspace/init/src") + enum files = "userspace/init/src/app.d"; + else static if (dir == "userspace/shell/src") + enum files = "userspace/shell/src/app.d"; + else static if (dir == "userspace/helloworld/src") + enum files = "userspace/helloworld/src/app.d"; + else static if (dir == "userspace/cat/src") + enum files = "userspace/cat/src/app.d"; + else static if (dir == "userspace/dlogo/src") + enum files = "userspace/dlogo/src/app.d"; else static assert(0); @@ -29,108 +29,104 @@ template AllDFiles(string dir) { } template AllAFiles(string dir) { - static if (dir == "Kernel/src") - enum files = "Kernel/src/BootX64.S Kernel/src/Task/Mutex/Assembly.S Kernel/src/Task/Task.S Kernel/src/System/SyscallHelper.S Kernel/src/Boot.S Kernel/src/Extra.S"; + static if (dir == "kernel/src") + enum files = "kernel/src/system/syscallhelper.S kernel/src/task/task.S kernel/src/task/mutex/assembly.S kernel/src/boot.S kernel/src/bootx64.S kernel/src/extra.S"; else static assert(0); enum AllAFiles = files.split(" ").map!Target.array; } -enum powerNexIsoName = "PowerNex.iso"; +enum powerNexIsoName = "powernex.iso"; enum objDir = topLevelDirName(Target(powerNexIsoName)); enum CompileCommand : string { - dc = "cc/bin/powernex-dmd -m64 -dip25 -de -color=on -fPIC -debug -c -g -IKernel/src -JKernel/src -defaultlib= -debuglib= -version=bare_metal -debug=allocations -of$out $in", - dc_header = "cc/bin/powernex-dmd -m64 -dip25 -de -color=on -fPIC -debug -c -g -IKernel/src -JKernel/src -defaultlib= -debuglib= -version=bare_metal -debug=allocations -o- -Hf$out $in", + dc = "cc/bin/powernex-dmd -m64 -dip25 -de -color=on -fPIC -debug -c -g -Ikernel/src -I"~objDir~"/kernel/src -Jkernel/src -J"~objDir~"/kernel/src -defaultlib= -debuglib= -version=bare_metal -debug=allocations -of$out $in", + dc_header = "cc/bin/powernex-dmd -m64 -dip25 -de -color=on -fPIC -debug -c -g -Ikernel/src -I"~objDir~"/kernel/src -Jkernel/src -J"~objDir~"/kernel/src -defaultlib= -debuglib= -version=bare_metal -debug=allocations -o- -Hf$out $in", ac = "cc/bin/x86_64-powernex-as --64 -o $out $in", - ld = "cc/bin/x86_64-powernex-ld -o $out -z max-page-size=0x1000 $in -T Kernel/src/Kernel.ld", + ld = "cc/bin/x86_64-powernex-ld -o $out -z max-page-size=0x1000 $in -T kernel/src/kernel.ld", iso = "grub-mkrescue -d /usr/lib/grub/i386-pc -o $out $in", - ndc = "dmd -of$out -odUtils/obj $in", + ndc = "dmd -of$out -od"~objDir ~ "/utils/obj $in", copy = "cp -rf $in $out", ungzip = "gzip -d -c $in > $out", - user_dc = "cc/bin/powernex-dmd -m64 -dip25 -de -color=on -debug -c -g -IUserspace/libRT/src -IUserspace/libPowerNex/src -defaultlib= -debuglib= -version=bare_metal -debug=allocations -of$out $in", + user_dc = "cc/bin/powernex-dmd -m64 -dip25 -de -color=on -debug -c -g -Iuserspace/librt/src -Iuserspace/libpowernex/src -I"~objDir~"/userspace/librt/src -I"~objDir~"/userspace/libpowernex/src -defaultlib= -debuglib= -version=bare_metal -debug=allocations -of$out $in", + user_dc_e = "cc/bin/powernex-dmd -m64 -dip25 -de -color=on -debug -g -Iuserspace/librt/src -Iuserspace/libpowernex/src -I"~objDir~"/userspace/librt/src -I"~objDir~"/userspace/libpowernex/src -defaultlib= -debuglib= -version=bare_metal -debug=allocations -of$out $in", user_ac = "cc/bin/x86_64-powernex-as --64 -o $out $in", user_ar = "cc/bin/x86_64-powernex-ar rcs $out $in", user_ld = "cc/bin/x86_64-powernex-ld -o $out $in" } enum ToolCommand : string { - generateSymbols = objDir ~ "/Utils/GenerateSymbols $in $out", - makeInitrd = objDir ~ "/Utils/MakeInitrd $in $out", - removeImports = "sed -e 's/^import .*//g' -e 's/enum/import PowerNex.Data.Address;\\nenum/' $in > $out", + generateSymbols = objDir ~ "/utils/generatesymbols $in $out", + makeInitrd = objDir ~ "/utils/makeinitrd $in $out", + removeImports = "sed -e 's/^import .*//g' -e 's/enum/import powernex.data.address;\\nenum/' -e 's/module system.syscall;/module powernex.internal.syscall;/' $in > $out", } struct UtilsProgram { static: - enum generatesymbols = Target("Utils/GenerateSymbols", CompileCommand.ndc, [Target("Utils/GenerateSymbols.d")]); - enum makeinitrd = Target("Utils/MakeInitrd", CompileCommand.ndc, [Target("Utils/MakeInitrd.d")]); + enum generatesymbols = Target("utils/generatesymbols", CompileCommand.ndc, [Target("utils/generatesymbols.d")]); + enum makeinitrd = Target("utils/makeinitrd", CompileCommand.ndc, [Target("utils/makeinitrd.d")]); } struct KernelDependency { static: - enum consolefontgz = Target("Kernel/src/Bin/ConsoleFont.psf.gz", CompileCommand.copy, [Target("/usr/share/kbd/consolefonts/lat9w-16.psfu.gz")]); - enum consolefont = Target("Kernel/src/Bin/ConsoleFont.psf", CompileCommand.ungzip, [KernelDependency.consolefontgz]); + enum consolefontgz = Target("kernel/src/bin/consoleFont.psf.gz", CompileCommand.copy, [Target("/usr/share/kbd/consolefonts/lat9w-16.psfu.gz")]); + enum consolefont = Target("kernel/src/bin/consoleFont.psf", CompileCommand.ungzip, [KernelDependency.consolefontgz]); } struct KernelTask { static: - enum kernel_aobj = Target("Kernel/obj/ACode.o", CompileCommand.ac, AllAFiles!"Kernel/src"); - enum kernel_dobj = Target("Kernel/obj/DCode.o", CompileCommand.dc, AllDFiles!"Kernel/src", [KernelDependency.consolefont]); - enum kernel = Target("Disk/boot/PowerNex.krl", CompileCommand.ld, [KernelTask.kernel_aobj, KernelTask.kernel_dobj]); - enum map = Target("Initrd/Data/PowerNex.map", ToolCommand.generateSymbols, [KernelTask.kernel], [UtilsProgram.generatesymbols]); + enum kernel_aobj = Target("kernel/obj/acode.o", CompileCommand.ac, AllAFiles!"kernel/src"); + enum kernel_dobj = Target("kernel/obj/dcode.o", CompileCommand.dc, AllDFiles!"kernel/src", [KernelDependency.consolefont]); + enum kernel = Target("disk/boot/powernex.krl", CompileCommand.ld, [KernelTask.kernel_aobj, KernelTask.kernel_dobj]); + enum map = Target("initrd/data/powernex.map", ToolCommand.generateSymbols, [KernelTask.kernel], [UtilsProgram.generatesymbols]); } struct UserspaceLibrary { static: - enum syscall_di = Target("Userspace/Syscall.di", CompileCommand.dc_header, [Target("Kernel/src/System/Syscall.d")]); - enum syscall = Target("Userspace/libPowerNex/src/PowerNex/Internal/Syscall.di", ToolCommand.removeImports, [UserspaceLibrary.syscall_di]); + enum syscall_di = Target("userspace/syscall.di", CompileCommand.dc_header, [Target("kernel/src/system/syscall.d")]); + enum syscall = Target("userspace/libpowernex/src/powernex/internal/syscall.di", ToolCommand.removeImports, [UserspaceLibrary.syscall_di]); - enum librt_obj = Target("Userspace/libRT/obj/DCode.o", CompileCommand.user_dc, AllDFiles!"Userspace/libRT/src"); - enum librt = Target("Userspace/lib/libRT.a", CompileCommand.user_ar, [UserspaceLibrary.librt_obj], [UserspaceLibrary.libpowernex]); + enum librt_obj = Target("userspace/librt/obj/dcode.o", CompileCommand.user_dc, AllDFiles!"userspace/librt/src", [UserspaceLibrary.syscall]); + enum librt = Target("userspace/lib/librt.a", CompileCommand.user_ar, [UserspaceLibrary.librt_obj], [UserspaceLibrary.libpowernex]); - enum libpowernex_obj = Target("Userspace/libPowerNex/obj/DCode.o", CompileCommand.user_dc, AllDFiles!"Userspace/libPowerNex/src"); - enum libpowernex = Target("Userspace/lib/libPowerNex.a", CompileCommand.user_ar, [UserspaceLibrary.libpowernex_obj], [UserspaceLibrary.syscall]); + enum libpowernex_obj = Target("userspace/libpowernex/obj/dcode.o", CompileCommand.user_dc, AllDFiles!"userspace/libpowernex/src", [UserspaceLibrary.syscall]); + enum libpowernex = Target("userspace/lib/libpowernex.a", CompileCommand.user_ar, [UserspaceLibrary.libpowernex_obj]); } struct UserspaceProgram { static: - enum init_obj = Target("Userspace/Init/obj/DCode.o", CompileCommand.user_dc, AllDFiles!"Userspace/Init/src"); - enum init = Target("Initrd/Binary/Init", CompileCommand.user_ld, [UserspaceProgram.init_obj, UserspaceLibrary.librt, UserspaceLibrary.libpowernex]); + enum init_obj = Target("userspace/init/obj/dcode.o", CompileCommand.user_dc, AllDFiles!"userspace/init/src", [UserspaceLibrary.librt, UserspaceLibrary.libpowernex]); + enum init = Target("initrd/bin/init", CompileCommand.user_ld, [UserspaceProgram.init_obj, UserspaceLibrary.librt, UserspaceLibrary.libpowernex], [UserspaceLibrary.libpowernex]); - enum shell_obj = Target("Userspace/Shell/obj/DCode.o", CompileCommand.user_dc, AllDFiles!"Userspace/Shell/src"); - enum shell = Target("Initrd/Binary/Shell", CompileCommand.user_ld, [UserspaceProgram.shell_obj, UserspaceLibrary.librt, UserspaceLibrary.libpowernex]); + enum shell_obj = Target("userspace/shell/obj/dcode.o", CompileCommand.user_dc, AllDFiles!"userspace/shell/src", [UserspaceLibrary.librt, UserspaceLibrary.libpowernex]); + enum shell = Target("initrd/bin/shell", CompileCommand.user_ld, [UserspaceProgram.shell_obj, UserspaceLibrary.librt, UserspaceLibrary.libpowernex], [UserspaceLibrary.libpowernex]); - enum helloworld_obj = Target("Userspace/HelloWorld/obj/DCode.o", CompileCommand.user_dc, AllDFiles!"Userspace/HelloWorld/src"); - enum helloworld = Target("Initrd/Binary/HelloWorld", CompileCommand.user_ld, [UserspaceProgram.helloworld_obj, UserspaceLibrary.librt, UserspaceLibrary.libpowernex]); + enum helloworld_obj = Target("userspace/helloWorld/obj/dcode.o", CompileCommand.user_dc, AllDFiles!"userspace/helloworld/src", [UserspaceLibrary.librt, UserspaceLibrary.libpowernex]); + enum helloworld = Target("initrd/bin/helloWorld", CompileCommand.user_ld, [UserspaceProgram.helloworld_obj, UserspaceLibrary.librt, UserspaceLibrary.libpowernex], [UserspaceLibrary.libpowernex]); - enum cat_obj = Target("Userspace/Cat/obj/DCode.o", CompileCommand.user_dc, AllDFiles!"Userspace/Cat/src"); - enum cat = Target("Initrd/Binary/Cat", CompileCommand.user_ld, [UserspaceProgram.cat_obj, UserspaceLibrary.librt, UserspaceLibrary.libpowernex]); + enum cat_obj = Target("userspace/cat/obj/dcode.o", CompileCommand.user_dc, AllDFiles!"userspace/cat/src", [UserspaceLibrary.librt, UserspaceLibrary.libpowernex]); + enum cat = Target("initrd/bin/cat", CompileCommand.user_ld, [UserspaceProgram.cat_obj, UserspaceLibrary.librt, UserspaceLibrary.libpowernex], [UserspaceLibrary.libpowernex]); - enum dlogo_obj = Target("Userspace/DLogo/obj/DCode.o", CompileCommand.user_dc, AllDFiles!"Userspace/DLogo/src"); - enum dlogo = Target("Initrd/Binary/DLogo", CompileCommand.user_ld, [UserspaceProgram.dlogo_obj, UserspaceLibrary.librt, UserspaceLibrary.libpowernex]); + enum dlogo_obj = Target("userspace/dlogo/obj/dcode.o", CompileCommand.user_dc, AllDFiles!"userspace/dlogo/src", [UserspaceLibrary.librt, UserspaceLibrary.libpowernex]); + enum dlogo = Target("initrd/bin/dlogo", CompileCommand.user_ld, [UserspaceProgram.dlogo_obj, UserspaceLibrary.librt, UserspaceLibrary.libpowernex], [UserspaceLibrary.libpowernex]); } -enum initrdFiles = Target("Initrd/", CompileCommand.copy, [Target("Initrd/")], [ - Target("Initrd/Data/DLogo.bmp") +enum initrdFiles = Target("initrd/", CompileCommand.copy, [Target("initrd/")], [ + Target("initrd/data/dlogo.bmp") ]); -enum initrd = Target("Disk/boot/PowerNex.dsk", ToolCommand.makeInitrd, [initrdFiles], [ +enum initrd = Target("disk/boot/powernex.dsk", ToolCommand.makeInitrd, [initrdFiles], [ UtilsProgram.makeinitrd, KernelTask.map, - UserspaceProgram.init_obj, UserspaceProgram.init, - UserspaceProgram.shell_obj, UserspaceProgram.shell, - UserspaceProgram.helloworld_obj, UserspaceProgram.helloworld, - UserspaceProgram.cat_obj, UserspaceProgram.cat, - UserspaceProgram.dlogo_obj, UserspaceProgram.dlogo ]); -enum isoFiles = Target("Disk/", CompileCommand.copy, [Target("Disk/")], [ - Target("Disk/boot/grub/grub.cfg") +enum isoFiles = Target("disk/", CompileCommand.copy, [Target("disk/")], [ + Target("disk/boot/grub/grub.cfg") ]); enum powernexIso = Target(powerNexIsoName, CompileCommand.iso, [isoFiles], [KernelTask.kernel, initrd]); diff --git a/userspace/cat/src/app.d b/userspace/cat/src/app.d index 304dc43..bfbb83c 100644 --- a/userspace/cat/src/app.d +++ b/userspace/cat/src/app.d @@ -1,29 +1,29 @@ -import PowerNex.Syscall; -import PowerNex.Data.Address; -import PowerNex.Data.String; +import powernex.syscall; +import powernex.data.address; +import powernex.data.string_; -void Print(string str) { - Syscall.Write(0UL, cast(ubyte[])str, 0UL); +void print(string str) { + Syscall.write(0UL, cast(ubyte[])str, 0UL); } -void Println(string str) { - Print(str); - Print("\n"); +void println(string str) { + print(str); + print("\n"); } int main(string[] args) { if (args.length == 1) { - Print(args[0]); - Println(": ... "); + print(args[0]); + println(": ... "); return 0; } foreach (file; args[1 .. $]) { - Print("*"); - Print(file); - Println("*"); - size_t fd = Syscall.Open(file); + print("*"); + print(file); + println("*"); + size_t fd = Syscall.open(file); if (!fd) { - Println("File not found!"); + println("File not found!"); continue; } ubyte[0x1000] buf; @@ -31,12 +31,12 @@ int main(string[] args) { size_t r = 0; size_t offset = 0; do { - r = Syscall.Read(fd, buf, offset); + r = Syscall.read(fd, buf, offset); offset += r; - Print(cast(string)buf[0 .. r]); + print(cast(string)buf[0 .. r]); } while (r); - Syscall.Close(fd); + Syscall.close(fd); } return 0; } diff --git a/userspace/dlogo/src/app.d b/userspace/dlogo/src/app.d index 23ac856..ea97559 100644 --- a/userspace/dlogo/src/app.d +++ b/userspace/dlogo/src/app.d @@ -1,44 +1,44 @@ -import PowerNex.Syscall; -import PowerNex.Data.Address; -import PowerNex.Data.String; -import PowerNex.Data.BMPImage; -import PowerNex.Data.Color; - -void Print(string str) { - Syscall.Write(0UL, cast(ubyte[])str, 0UL); +import powernex.syscall; +import powernex.data.address; +import powernex.data.string_; +import powernex.data.bmpimage; +import powernex.data.color; + +void print(string str) { + Syscall.write(0UL, cast(ubyte[])str, 0UL); } -void Println(string str) { - Print(str); - Print("\n"); +void println(string str) { + print(str); + print("\n"); } int main(string[] args) { - size_t fb = Syscall.Open("/IO/Framebuffer/Framebuffer1"); + size_t fb = Syscall.open("/io/framebuffer/framebuffer1"); if (!fb) return 1; - size_t fd = Syscall.Open("/Data/DLogo.bmp"); + size_t fd = Syscall.open("/data/dlogo.bmp"); if (!fd) return 2; BMPImage image = new BMPImage(fd); size_t[2] header; - Syscall.Read(fb, cast(ubyte[])header, 0); + Syscall.read(fb, cast(ubyte[])header, 0); - Println("There will be a DLogo in the center of the screen :)"); + println("There will be a DLogo in the center of the screen :)"); - const size_t xoff = header[0] / 2 - image.Width / 2; - const size_t yoff = header[1] / 2 - image.Height / 2; - for (size_t row = 0; row < image.Height; row++) { - auto dataRow = image.Data[row * image.Width .. (row + 1) * image.Width]; + const size_t xoff = header[0] / 2 - image.width / 2; + const size_t yoff = header[1] / 2 - image.height / 2; + for (size_t row = 0; row < image.height; row++) { + auto dataRow = image.data[row * image.width .. (row + 1) * image.width]; size_t yPos = row + yoff; - Syscall.Write(fb, cast(ubyte[])dataRow, (yPos * header[0] + xoff) * Color.sizeof); + Syscall.write(fb, cast(ubyte[])dataRow, (yPos * header[0] + xoff) * Color.sizeof); } - Syscall.Close(fd); - Syscall.Close(fb); + Syscall.close(fd); + Syscall.close(fb); return 0; } diff --git a/userspace/helloworld/src/app.d b/userspace/helloworld/src/app.d index e1ccf18..21468f7 100644 --- a/userspace/helloworld/src/app.d +++ b/userspace/helloworld/src/app.d @@ -1,17 +1,17 @@ -import PowerNex.Syscall; -import PowerNex.Data.Address; -import PowerNex.Data.String; +import powernex.syscall; +import powernex.data.address; +import powernex.data.string_; -void Print(string str) { - Syscall.Write(0UL, cast(ubyte[])str, 0UL); +void print(string str) { + Syscall.write(0UL, cast(ubyte[])str, 0UL); } -void Println(string str) { - Print(str); - Print("\n"); +void println(string str) { + print(str); + print("\n"); } int main(string[] args) { - Println("Hello World from Userspace and D!"); + println("Hello World from Userspace and D!"); return 0; } diff --git a/userspace/init/src/app.d b/userspace/init/src/app.d index 478fd8e..24dcfb0 100644 --- a/userspace/init/src/app.d +++ b/userspace/init/src/app.d @@ -1,9 +1,9 @@ -import PowerNex.Syscall; -import PowerNex.Data.Address; -import PowerNex.Data.String; +import powernex.syscall; +import powernex.data.address; +import powernex.data.string_; -ulong ExitValue = 0; -__gshared align(16) ubyte[0x1000] CloneStack = void; +ulong exitValue = 0; +__gshared align(16) ubyte[0x1000] cloneStack = void; struct StructTest { int a; @@ -12,43 +12,43 @@ struct StructTest { class ClassTest { public: this(int a) { - this.o = a + 10; + _o = a + 10; } - @property int O() { - return o; + @property int o() { + return _o; } private: - int o; + int _o; } -void Print(string str) { - Syscall.Write(0UL, cast(ubyte[])str, 0UL); +void print(string str) { + Syscall.write(0UL, cast(ubyte[])str, 0UL); } -void Println(string str) { - Print(str); - Print("\n"); +void println(string str) { + print(str); + print("\n"); } int main(string[] args) { - Println("Init system loading..."); + println("Init system loading..."); - spawnShell("/IO/Console/VirtualConsole4"); - spawnShell("/IO/Console/VirtualConsole3"); - spawnShell("/IO/Console/VirtualConsole2"); - spawnShell("/IO/Console/VirtualConsole1"); + spawnShell("/io/console/virtualconsole4"); + spawnShell("/io/console/virtualconsole3"); + spawnShell("/io/console/virtualconsole2"); + spawnShell("/io/console/virtualconsole1"); while (true) - Syscall.Join(0); + Syscall.join(0); } void spawnShell(string virtConsole) { - ulong pid = Syscall.Fork(); + ulong pid = Syscall.fork(); if (!pid) { - Syscall.ReOpen(0, virtConsole); - Syscall.Exec("/Binary/Shell", []); - Syscall.Exit(1); + Syscall.reOpen(0, virtConsole); + Syscall.exec("/bin/shell", []); + Syscall.exit(1); } } diff --git a/userspace/libpowernex/src/powernex/data/address.d b/userspace/libpowernex/src/powernex/data/address.d index c28feb8..5e12a13 100644 --- a/userspace/libpowernex/src/powernex/data/address.d +++ b/userspace/libpowernex/src/powernex/data/address.d @@ -1,6 +1,6 @@ -module PowerNex.Data.Address; +module powernex.data.address; -private mixin template AddressBase(Type = ulong) { +private mixin template AddressBase(Type = size_t) { alias Func = void function(); Type addr; @@ -14,8 +14,12 @@ private mixin template AddressBase(Type = ulong) { this.addr = addr; } - this(Func addr) { - this.addr = cast(Type)addr; + this(Func func) { + this.addr = cast(Type)func; + } + + this(T)(T[] arr) { + this.addr = cast(Type)arr.ptr; } typeof(this) opBinary(string op)(void* other) const { @@ -27,7 +31,7 @@ private mixin template AddressBase(Type = ulong) { } typeof(this) opBinary(string op)(typeof(this) other) const { - return opBinary!op(other.Ptr); + return opBinary!op(other.ptr); } typeof(this) opOpAssign(string op)(void* other) { @@ -39,53 +43,62 @@ private mixin template AddressBase(Type = ulong) { } typeof(this) opOpAssign(string op)(typeof(this) other) { - return opOpAssign!op(other.Ptr); + return opOpAssign!op(other.ptr); } int opCmp(typeof(this) other) const { - if (Int < other.Int) + if (num < other.num) return -1; - else if (Int > other.Int) + else if (num > other.num) return 1; else return 0; } int opCmp(Type other) const { - if (Int < other) + if (num < other) return -1; - else if (Int > other) + else if (num > other) return 1; else return 0; } - @property T* Ptr(T = void)() { + @property T* ptr(T = void)() { return cast(T*)addr; } - @property T* Ptr(T = void)(T addr) { + @property T* ptr(T = void)(T addr) { this.addr = cast(Type)addr; return cast(T*)addr; } - @property Type Int() const { + @property Type num() const { return addr; } - @property Type Int(Type addr) { + @property Type num(Type addr) { this.addr = addr; return addr; } - @property Func Function() const { + @property Func func() const { return cast(Func)addr; } - @property Func Function(Func addr) { - this.addr = cast(Type)addr; + @property Func func(Func func) { + this.addr = cast(Type)func; return cast(Func)addr; } + + T array(T : X[], X)(size_t length) const { + return (cast(X*)addr)[0 .. length]; + } + + @property T array(T)(T array_) { + this.addr = cast(Type)array_.ptr; + return array_; + } } struct VirtAddress { @@ -95,16 +108,16 @@ struct VirtAddress { struct PhysAddress { mixin AddressBase; - @property VirtAddress Virtual() const { - return VirtAddress(Int + 0xFFFF_8000_0000_0000); + @property VirtAddress virtual() const { + return VirtAddress(addr + 0xFFFF_8000_0000_0000); } } struct PhysAddress32 { mixin AddressBase!uint; - @property VirtAddress Virtual() const { - return VirtAddress(Int + 0xFFFF_8000_0000_0000); + @property VirtAddress virtual() const { + return VirtAddress(addr + 0xFFFF_8000_0000_0000); } } diff --git a/userspace/libpowernex/src/powernex/data/bmpimage.d b/userspace/libpowernex/src/powernex/data/bmpimage.d index aee946e..e4c0072 100644 --- a/userspace/libpowernex/src/powernex/data/bmpimage.d +++ b/userspace/libpowernex/src/powernex/data/bmpimage.d @@ -1,89 +1,89 @@ -module PowerNex.Data.BMPImage; +module powernex.data.bmpimage; -import PowerNex.Data.Color; -import PowerNex.Syscall; +import powernex.data.color; +import powernex.syscall; private align(1) struct FileHeader { align(1): - char[2] filetype; /* magic - always 'B' 'M' */ - uint filesize; + char[2] fileType; /* magic - always 'B' 'M' */ + uint fileSize; short reserved1; short reserved2; - uint dataoffset; /* offset in bytes to actual bitmap data */ + uint dataOffset; /* offset in bytes to actual bitmap data */ } private align(1) struct BitmapHeader { align(1): - FileHeader fileheader; - uint headersize; + FileHeader fileHeader; + uint headerSize; int width; int height; short planes; - short bitsperpixel; + short bitsPerPixel; uint compression; - uint bitmapsize; - int horizontalres; - int verticalres; - uint numcolors; - uint importantcolors; - uint redmask; - uint greenmask; - uint bluemask; - uint alphamask; + uint bitmapSize; + int horizontalRes; + int verticalRes; + uint numColors; + uint importantColors; + uint redMask; + uint greenMask; + uint blueMask; + uint alphaMask; } class BMPImage { public: this(size_t file) { - Syscall.Read(file, (cast(ubyte*)&bitmap)[0 .. BitmapHeader.sizeof], 0); - data = new Color[bitmap.width * bitmap.height]; - size_t offset = bitmap.fileheader.dataoffset; - int pad = bitmap.width % 4; + Syscall.read(file, (cast(ubyte*)&_bitmap)[0 .. BitmapHeader.sizeof], 0); + _data = new Color[_bitmap.width * _bitmap.height]; + size_t offset = _bitmap.fileHeader.dataOffset; + int pad = _bitmap.width % 4; - switch (bitmap.bitsperpixel) { + switch (_bitmap.bitsPerPixel) { case 32: - readData!32(file, offset, pad); + _readData!32(file, offset, pad); break; case 24: - readData!24(file, offset, pad); + _readData!24(file, offset, pad); break; default: - Syscall.Write(0, cast(ubyte[])"BMPIMAGE: Invalid bitsperpixel", 0); - //log.Error("Can't handle bpp = ", bitmap.bitsperpixel); + Syscall.write(0, cast(ubyte[])"BMPIMAGE: Invalid bitsperpixel", 0); + //log.Error("Can't handle bpp = ", _bitmap.bitsperpixel); return; } } /*this(BMPImage other) { - bitmap = other.bitmap; - data = other.Data.dup; + _bitmap = other._bitmap; + _data = other._data.dup; }*/ ~this() { - data.destroy; + _data.destroy; } - @property BitmapHeader Header() { - return bitmap; + @property BitmapHeader header() { + return _bitmap; } - @property Color[] Data() { - return data; + @property Color[] data() { + return _data; } - @property int Width() { - return bitmap.width; + @property int width() { + return _bitmap.width; } - @property int Height() { - return bitmap.height; + @property int height() { + return _bitmap.height; } private: - BitmapHeader bitmap; - Color[] data; + BitmapHeader _bitmap; + Color[] _data; - void readData(int bpp)(size_t file, size_t offset, int pad) if (bpp == 24 || bpp == 32) { + void _readData(int bpp)(size_t file, size_t offset, int pad) if (bpp == 24 || bpp == 32) { enum bytesPerPixel = bpp / 8; ubyte toIdx(int bitmask) { @@ -91,17 +91,17 @@ private: : (bitmask & 0x00_00_00_01) ? 0 : ubyte.max; } - immutable ubyte rid = toIdx(bitmap.redmask); - immutable ubyte gid = toIdx(bitmap.greenmask); - immutable ubyte bid = toIdx(bitmap.bluemask); - immutable ubyte aid = toIdx(bitmap.alphamask); + immutable ubyte rid = toIdx(_bitmap.redMask); + immutable ubyte gid = toIdx(_bitmap.greenMask); + immutable ubyte bid = toIdx(_bitmap.blueMask); + immutable ubyte aid = toIdx(_bitmap.alphaMask); - //log.Debug("rid: ", cast(int)rid, " gid: ", cast(int)gid, " bid: ", cast(int)bid, " aid: ", cast(int)aid); + //log.debug_("rid: ", cast(int)rid, " gid: ", cast(int)gid, " bid: ", cast(int)bid, " aid: ", cast(int)aid); ubyte[bytesPerPixel] buf = void; - for (int y = bitmap.height - 1; y >= 0; y--) { - for (int x = 0; x < bitmap.width; x++) { - Syscall.Read(file, buf, offset); + for (int y = _bitmap.height - 1; y >= 0; y--) { + for (int x = 0; x < _bitmap.width; x++) { + Syscall.read(file, buf, offset); offset += bytesPerPixel; immutable ubyte r = rid != ubyte.max ? buf[rid] : 0; @@ -113,7 +113,7 @@ private: else immutable ubyte a = 0; - data[y * bitmap.width + x] = Color(r, g, b, a); + _data[y * _bitmap.width + x] = Color(r, g, b, a); } if (pad) diff --git a/userspace/libpowernex/src/powernex/data/color.d b/userspace/libpowernex/src/powernex/data/color.d index c280214..38cc954 100644 --- a/userspace/libpowernex/src/powernex/data/color.d +++ b/userspace/libpowernex/src/powernex/data/color.d @@ -1,4 +1,4 @@ -module PowerNex.Data.Color; +module powernex.data.color; struct Color { align(1): diff --git a/userspace/libpowernex/src/powernex/data/parameters.d b/userspace/libpowernex/src/powernex/data/parameters.d index fab31c5..7f4476f 100644 --- a/userspace/libpowernex/src/powernex/data/parameters.d +++ b/userspace/libpowernex/src/powernex/data/parameters.d @@ -1,9 +1,9 @@ -module PowerNex.Data.Parameters; +module powernex.data.parameters; -template Parameters(func...) { +template parameters(func...) { static if (is(typeof(&func[0]) Fsym : Fsym*) && is(Fsym == function)) static if (is(Fsym P == function)) - alias Parameters = P; + alias parameters = P; else static assert(0, "argument has no parameters"); } diff --git a/userspace/libpowernex/src/powernex/data/string_.d b/userspace/libpowernex/src/powernex/data/string_.d index f267408..77e50a5 100644 --- a/userspace/libpowernex/src/powernex/data/string_.d +++ b/userspace/libpowernex/src/powernex/data/string_.d @@ -1,6 +1,6 @@ -module PowerNex.Data.String; +module powernex.data.string_; -import PowerNex.Data.Util; +import powernex.data.util; nothrow pure size_t strlen(const(char)* str) { if (!str) @@ -60,7 +60,7 @@ string itoa(S)(S v, char[] buf, uint base = 10) if (isNumber!S) { size_t itoa(S)(S v, char* buf, ulong len, uint base = 10) if (isNumber!S) { assert(1 < base && base <= 16); Unqual!S value = v; - immutable char[] BASE_CHARS = cast(immutable char[])"0123456789ABCDEF"; + immutable char[] baseChars = cast(immutable char[])"0123456789ABCDEF"; size_t pos = len; bool sign = false; @@ -70,7 +70,7 @@ size_t itoa(S)(S v, char* buf, ulong len, uint base = 10) if (isNumber!S) { } do { - buf[--pos] = BASE_CHARS[value % base]; + buf[--pos] = baseChars[value % base]; value /= base; } while (value); @@ -83,12 +83,12 @@ size_t itoa(S)(S v, char* buf, ulong len, uint base = 10) if (isNumber!S) { long atoi(string str, uint base = 10) { long result; - immutable char[] BASE_CHARS = cast(immutable char[])"0123456789ABCDEF"; + immutable char[] baseChars = cast(immutable char[])"0123456789ABCDEF"; foreach (ch; str) { long value; for (value = 0; value <= base; value++) - if (BASE_CHARS[value] == ch) + if (baseChars[value] == ch) break; if (value > base) return result; @@ -104,7 +104,7 @@ string dtoa(double v, char[] buf, uint base = 10) { } bool isNan(double value) { - enum ulong NANMASK = 0x7FFUL; + enum ulong nanMask = 0x7FFUL; union storage { double v; ulong i; @@ -113,7 +113,7 @@ bool isNan(double value) { storage s; s.v = value; - return ((s.i >> 51UL) & NANMASK) == NANMASK; + return ((s.i >> 51UL) & nanMask) == nanMask; } size_t dtoa(double value, char* buf, ulong len, uint base = 10) { @@ -146,14 +146,14 @@ size_t dtoa(double value, char* buf, ulong len, uint base = 10) { ulong exponent = cast(ulong)value; double fraction = value - exponent; - immutable char[] BASE_CHARS = cast(immutable char[])"0123456789ABCDEF"; + immutable char[] baseChars = cast(immutable char[])"0123456789ABCDEF"; // Fraction char[16] fracTmp; int fracPos; fraction *= base; do { - fracTmp[fracPos++] = BASE_CHARS[cast(ulong)fraction % base]; + fracTmp[fracPos++] = baseChars[cast(ulong)fraction % base]; fraction *= base; } while (fraction && fracPos < fracTmp.length); @@ -165,7 +165,7 @@ size_t dtoa(double value, char* buf, ulong len, uint base = 10) { buf[--pos] = '.'; // Exponent do { - buf[--pos] = BASE_CHARS[exponent % base]; + buf[--pos] = baseChars[exponent % base]; exponent /= base; } while (exponent); diff --git a/userspace/libpowernex/src/powernex/data/util.d b/userspace/libpowernex/src/powernex/data/util.d index ebdc73d..b55ddfe 100644 --- a/userspace/libpowernex/src/powernex/data/util.d +++ b/userspace/libpowernex/src/powernex/data/util.d @@ -1,4 +1,4 @@ -module PowerNex.Data.Util; +module powernex.data.util; template Unqual(T) { static if (is(T U == shared(const U))) @@ -28,8 +28,8 @@ template TypeTuple(T...) { alias TypeTuple = T; } -template EnumMembers(E) if (is(E == enum)) { - template WithIdentifier(string ident) { +template enumMembers(E) if (is(E == enum)) { + template withIdentifier(string ident) { static if (ident == "Symbolize") { template Symbolize(alias value) { enum Symbolize = value; @@ -39,19 +39,19 @@ template EnumMembers(E) if (is(E == enum)) { } } - template EnumSpecificMembers(names...) { + template enumSpecificMembers(names...) { static if (names.length > 0) { - alias EnumSpecificMembers = TypeTuple!(WithIdentifier!(names[0]).Symbolize!(__traits(getMember, E, - names[0])), EnumSpecificMembers!(names[1 .. $])); + alias enumSpecificMembers = TypeTuple!(withIdentifier!(names[0]).Symbolize!(__traits(getMember, E, + names[0])), enumSpecificMembers!(names[1 .. $])); } else { - alias EnumSpecificMembers = TypeTuple!(); + alias enumSpecificMembers = TypeTuple!(); } } - alias EnumMembers = EnumSpecificMembers!(__traits(allMembers, E)); + alias enumMembers = enumSpecificMembers!(__traits(allMembers, E)); } -T InplaceClass(T, Args...)(void[] chunk, auto ref Args args) if (is(T == class)) { +T inplaceClass(T, Args...)(void[] chunk, auto ref Args args) if (is(T == class)) { static assert(!__traits(isAbstractClass, T), T.stringof ~ " is abstract and it can't be emplaced"); enum classSize = __traits(classInstanceSize, T); @@ -70,10 +70,10 @@ T InplaceClass(T, Args...)(void[] chunk, auto ref Args args) if (is(T == class)) } struct BinaryInt { - ulong Int; + ulong int_; } -void Swap(T)(ref T t1, ref T t2) { +void swap(T)(ref T t1, ref T t2) { T tmp = t1; t1 = t2; t2 = tmp; diff --git a/userspace/libpowernex/src/powernex/syscall.d b/userspace/libpowernex/src/powernex/syscall.d index 5abeecc..7def51d 100644 --- a/userspace/libpowernex/src/powernex/syscall.d +++ b/userspace/libpowernex/src/powernex/syscall.d @@ -1,44 +1,45 @@ -module PowerNex.Syscall; +module powernex.syscall; -import PowerNex.Internal.Syscall; -import PowerNex.Data.Address; +import powernex.internal.syscall; +import powernex.data.address; struct Syscall { public: - mixin(generateFunctions); + mixin(_generateFunctions()); private: - static string generateFunctions() { + static string _generateFunctions() { if (!__ctfe) // Without this it tries to use _d_arrayappendT return ""; string o; - foreach (func; __traits(derivedMembers, PowerNex.Internal.Syscall)) - foreach (attr; __traits(getAttributes, mixin(func))) - static if (is(typeof(attr) == SyscallEntry)) - o ~= generateFunctionDefinition!(func, attr) ~ "\n"; + foreach (func; __traits(derivedMembers, powernex.internal.syscall)) + static if (is(typeof(mixin("powernex.internal.syscall." ~ func)) == function)) + foreach (attr; __traits(getAttributes, mixin("powernex.internal.syscall." ~ func))) + static if (is(typeof(attr) == SyscallEntry)) + o ~= _generateFunctionDefinition!(func, attr) ~ "\n"; return o; } - static string generateFunctionDefinition(alias func, alias attr)() { + static string _generateFunctionDefinition(alias func, alias attr)() { if (!__ctfe) // Without this it tries to use _d_arrayappendT return ""; - import PowerNex.Data.Parameters; - import PowerNex.Data.String : itoa; - import PowerNex.Data.Util : isArray; + import powernex.data.parameters; + import powernex.data.string_ : itoa; + import powernex.data.util : isArray; // These can be used because they will be saved first string[] saveRegisters = ["R12", "R13", "R14", "R15"]; - enum NAME = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]; - enum ABI = ["RDI", "RSI", "RDX", "R8", "R9", "R10", "R12", "R13", "R14", "R15"]; + enum name = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]; + enum abi = ["RDI", "RSI", "RDX", "R8", "R9", "R10", "R12", "R13", "R14", "R15"]; - alias p = Parameters!(mixin(func)); + alias p = parameters!(mixin("powernex.internal.syscall." ~ func)); string o = "static VirtAddress " ~ func ~ "("; foreach (idx, val; p) { static if (idx) o ~= ", "; - o ~= val.stringof ~ " " ~ NAME[idx]; + o ~= val.stringof ~ " " ~ name[idx]; } o ~= ") {\n"; @@ -49,11 +50,11 @@ private: registerCount++; continue; } - o ~= "\tauto " ~ NAME[idx] ~ "_ptr = " ~ NAME[idx] ~ ".ptr;\n"; - o ~= "\tauto " ~ NAME[idx] ~ "_length = " ~ NAME[idx] ~ ".length;\n"; + o ~= "\tauto " ~ name[idx] ~ "_ptr = " ~ name[idx] ~ ".ptr;\n"; + o ~= "\tauto " ~ name[idx] ~ "_length = " ~ name[idx] ~ ".length;\n"; registerCount += 2; } - assert(registerCount < ABI.length); + assert(registerCount < abi.length); char[ulong.sizeof * 8] buf; o ~= "\tasm {\n"; @@ -68,10 +69,10 @@ private: size_t abi_count; foreach (idx, val; p) { static if (isArray!val) { - o ~= "\t\tmov " ~ ABI[abi_count++] ~ ", " ~ NAME[idx] ~ "_ptr;\n"; - o ~= "\t\tmov " ~ ABI[abi_count++] ~ ", " ~ NAME[idx] ~ "_length;\n"; + o ~= "\t\tmov " ~ abi[abi_count++] ~ ", " ~ name[idx] ~ "_ptr;\n"; + o ~= "\t\tmov " ~ abi[abi_count++] ~ ", " ~ name[idx] ~ "_length;\n"; } else - o ~= "\t\tmov " ~ ABI[abi_count++] ~ ", " ~ NAME[idx] ~ ";\n"; + o ~= "\t\tmov " ~ abi[abi_count++] ~ ", " ~ name[idx] ~ ";\n"; } //o ~= "\t\tint 0x80;\n"; o ~= "\t\tsyscall;\n"; diff --git a/userspace/librt/src/object.d b/userspace/librt/src/object.d index e10fb4d..fe0e94b 100644 --- a/userspace/librt/src/object.d +++ b/userspace/librt/src/object.d @@ -1,14 +1,14 @@ module object; -import PowerNex.Data.String : strlen, fromStringz; -import PowerNex.Syscall : Syscall; +import powernex.data.string_ : strlen, fromStringz; +import powernex.syscall : Syscall; int main(string[] args); int callMain() { try { char** argv; size_t argc; - Syscall.GetArguments(&argc, &argv); + Syscall.getArguments(&argc, &argv); string[] args = new string[argc]; foreach (idx, arg; argv[0 .. argc]) @@ -35,7 +35,7 @@ extern (C) void _start() { } void exit(ssize_t code = 0) { - Syscall.Exit(code); + Syscall.exit(code); } extern (C) { @@ -60,7 +60,7 @@ extern (C) { // the compiler spits this out all the time Object _d_newclass(const ClassInfo ci) { - void* memory = Syscall.Alloc(ci.init.length).Ptr; + void* memory = Syscall.alloc(ci.init.length).ptr; if (memory is null) { asm { //log.Fatal("\n\n_d_newclass malloc failure\n\n"); hlt; @@ -73,7 +73,7 @@ extern (C) { } extern (C) void* _d_newitemU(in TypeInfo ti) { - return Syscall.Alloc(ti.tsize).Ptr; + return Syscall.alloc(ti.tsize).ptr; } extern (C) void* _d_newitemT(in TypeInfo ti) { @@ -96,7 +96,7 @@ extern (C) { if (!length || !size) return null; else - return Syscall.Alloc(length * size).Ptr[0 .. length]; + return Syscall.alloc(length * size).ptr[0 .. length]; } extern (C) void[] _d_newarrayiT(TypeInfo ti, size_t length) { @@ -138,7 +138,7 @@ extern (C) { if (!length || !size) return null; else - return Syscall.Alloc(length * size).Ptr; + return Syscall.alloc(length * size).ptr; } void[] _d_arraycatT(TypeInfo ti, void[] x, void[] y) { @@ -150,7 +150,7 @@ extern (C) { if (!(x.length + y.length) || !size) return null; - ubyte* data = Syscall.Alloc((x.length + y.length) * size).Ptr!ubyte; + ubyte* data = Syscall.alloc((x.length + y.length) * size).ptr!ubyte; memcpy(data, x.ptr, x.length * size); memcpy(data + (x.length * size), y.ptr, y.length * size); return (cast(void*)data)[0 .. x.length + y.length]; @@ -158,13 +158,13 @@ extern (C) { void[] _d_arraysetlengthT(const TypeInfo ti, size_t newlength, void[]* p) { auto size = ti.next.tsize(); - *p = Syscall.Realloc(p.ptr, newlength * size).Ptr[0 .. newlength]; + *p = Syscall.realloc(p.ptr, newlength * size).ptr[0 .. newlength]; return *p; } void[] _d_arraysetlengthiT(const TypeInfo ti, size_t newlength, void[]* p) { auto size = ti.next.tsize(); - *p = Syscall.Realloc(p.ptr, newlength * size).Ptr[0 .. newlength]; + *p = Syscall.realloc(p.ptr, newlength * size).ptr[0 .. newlength]; return *p; } @@ -172,7 +172,7 @@ extern (C) { byte[] _d_arrayappendcTX(const TypeInfo ti, ref byte[] px, size_t n) { auto size = ti.next.tsize(); auto newlength = px.length + n; - void* newPtr = Syscall.Realloc(px.ptr, newlength * size).Ptr; + void* newPtr = Syscall.realloc(px.ptr, newlength * size).ptr; *cast(size_t*)&px = newlength; (cast(void**)(&px))[1] = newPtr; return px; @@ -198,7 +198,7 @@ extern (C) { if (!length) return null; - void* a = Syscall.Alloc(length * size).Ptr; + void* a = Syscall.alloc(length * size).ptr; size_t j = 0; foreach (b; arrs) { @@ -340,18 +340,18 @@ class Throwable : Object { // required by the D compiler } void print() { - import PowerNex.Data.String; + import powernex.data.string_; char[ulong.sizeof * 8] buf; - Syscall.Write(0, cast(ubyte[])this.classinfo.name, 0); - Syscall.Write(0, cast(ubyte[])"@", 0); - Syscall.Write(0, cast(ubyte[])file, 0); - Syscall.Write(0, cast(ubyte[])"(", 0); - - Syscall.Write(0, cast(ubyte[])itoa(line, buf, 10), 0); - Syscall.Write(0, cast(ubyte[])"): ", 0); - Syscall.Write(0, cast(ubyte[])message, 0); - Syscall.Write(0, cast(ubyte[])"\n", 0); + Syscall.write(0, cast(ubyte[])this.classinfo.name, 0); + Syscall.write(0, cast(ubyte[])"@", 0); + Syscall.write(0, cast(ubyte[])file, 0); + Syscall.write(0, cast(ubyte[])"(", 0); + + Syscall.write(0, cast(ubyte[])itoa(line, buf, 10), 0); + Syscall.write(0, cast(ubyte[])"): ", 0); + Syscall.write(0, cast(ubyte[])message, 0); + Syscall.write(0, cast(ubyte[])"\n", 0); exit(1); asm { hlt; @@ -436,7 +436,7 @@ class TypeInfo { } /// Run the destructor on the object and all its sub-objects void destroy(void* p) const { - Syscall.Free(p); + Syscall.free(p); } /// Run the postblit on the object and all its sub-objects void postblit(void* p) const { @@ -1577,14 +1577,14 @@ immutable(T)[] immutable_alloc(T)(scope void delegate(T[]) initalizer) { } void destroy(void* memory) { - Syscall.Free(memory); + Syscall.free(memory); } void destroy(T : Object)(T object) { auto dtor = cast(void function(Object o))object.classinfo.destructor; if (dtor) dtor(object); - Syscall.Free(cast(void*)object); + Syscall.free(cast(void*)object); } void destroy(T)(T[] array) { @@ -1599,13 +1599,13 @@ void destroy(T)(T[] array) { foreach (el; array) destroy(cast(void*)el); } - Syscall.Free(cast(void*)array.ptr); + Syscall.free(cast(void*)array.ptr); } // this would be used for automatic heap closures, but there's no way to free it... ///* extern (C) void* _d_allocmemory(size_t bytes) { - return Syscall.Alloc(bytes).Ptr; + return Syscall.alloc(bytes).ptr; } //*/ @@ -2369,7 +2369,7 @@ extern (C) int dstrcmp(char[] s1, char[] s2) { } inout(T)[] dup(T)(inout(T)[] a) { - void[] arr = Syscall.Alloc(T.sizeof * a.length)[0 .. a.length]; + void[] arr = Syscall.alloc(T.sizeof * a.length)[0 .. a.length]; memcpy(arr.ptr, a.ptr, T.sizeof * a.length); return *cast(inout(T)[]*)&arr; } diff --git a/userspace/shell/src/app.d b/userspace/shell/src/app.d index 981c439..6f7e64c 100644 --- a/userspace/shell/src/app.d +++ b/userspace/shell/src/app.d @@ -1,52 +1,52 @@ -import PowerNex.Syscall; -import PowerNex.Data.String; +import powernex.syscall; +import powernex.data.string_; -void Print(string str) { - Syscall.Write(0UL, cast(ubyte[])str, 0UL); +void print(string str) { + Syscall.write(0UL, cast(ubyte[])str, 0UL); } -void Print(char[] str) { - Print(cast(string)str); +void print(char[] str) { + print(cast(string)str); } -void Print(char ch) { - Syscall.Write(0UL, cast(ubyte[])(&ch)[0 .. 1], 0UL); +void print(char ch) { + Syscall.write(0UL, cast(ubyte[])(&ch)[0 .. 1], 0UL); } -void Print(T)(T t) if (is(T == enum)) { - import PowerNex.Data.Util; +void print(T)(T t) if (is(T == enum)) { + import powernex.data.util; char[ulong.sizeof * 8] buf; - foreach (i, e; EnumMembers!T) + foreach (i, e; enumMembers!T) if (t == e) { - Print(__traits(allMembers, T)[i]); + print(__traits(allMembers, T)[i]); goto done; } - Print("cast("); - Print(T.stringof); - Print(")"); - Print(itoa(cast(ulong)t, buf, 10)); + print("cast("); + print(T.stringof); + print(")"); + print(itoa(cast(ulong)t, buf, 10)); done: } -void Println() { - Print("\n"); +void println() { + print("\n"); } -void Println(string str) { - Print(str); - Println(); +void println(string str) { + print(str); + println(); } int main(string[] args) { while (true) { - Println("Booting up shell..."); + println("Booting up shell..."); BasicShell bs = new BasicShell(); - bs.MainLoop(); + bs.mainLoop(); bs.destroy; - Println("\x1B[2J"); + println("\x1B[2J"); } return 0; @@ -54,9 +54,9 @@ int main(string[] args) { struct DirectoryListing { enum Type { - Unknown, - File, - Directory, + unknown, + file, + directory } size_t id; @@ -66,21 +66,21 @@ struct DirectoryListing { class BasicShell { public: - void MainLoop() { + void mainLoop() { char[0x100] cwd; - while (!quit) { - size_t len = Syscall.GetCurrentDirectory(cwd); - Print(cwd[0 .. len]); - Print("/ \u0017 "); - Command* command = parseLine(readLine); + while (!_quit) { + size_t len = Syscall.getCurrentDirectory(cwd); + print(cwd[0 .. len]); + print("/ \u0017 "); + Command* command = _parseLine(_readLine); if (command.args.length) - execute(command); + _execute(command); command.destroy; } } private: - bool quit; + bool _quit; struct Command { char[][] args; @@ -90,13 +90,13 @@ private: } } - char[] readLine() { + char[] _readLine() { __gshared char[1024] line; ubyte[1024] buf; size_t idx = 0; while (idx < 1024) { - size_t r = Syscall.Read(0, buf[idx .. $], 0); + size_t r = Syscall.read(0, buf[idx .. $], 0); for (size_t i = 0; i < r; i++) { char ch = cast(char)buf[idx + i]; if (ch == '\0') @@ -107,22 +107,22 @@ private: if (idx) { idx--; line[idx] = ' '; - Print("\b \b"); // Back ' ' Back + print("\b \b"); // Back ' ' Back } continue; } else if (ch == '\n') goto done; - Print(ch); + print(ch); line[idx++] = ch; } } done: - Print("\n"); + print("\n"); return line[0 .. idx]; } - Command* parseLine(char[] line) { + Command* _parseLine(char[] line) { char[][] args; size_t start = 0; @@ -139,88 +139,87 @@ private: return new Command(args); } - void execute(Command* cmd) { + void _execute(Command* cmd) { switch (cmd.args[0]) { case "help": - Println("Commands: help, echo, clear, exit, time, sleep, ls, cd"); + println("Commands: help, echo, clear, exit, time, sleep, ls, cd"); break; case "exit": - quit = true; + _quit = true; break; case "clear": - Println("\x1B[2J"); + println("\x1B[2J"); break; case "echo": foreach (idx, arg; cmd.args[1 .. $]) { - Print(arg); - Print(" "); + print(arg); + print(" "); } - Println(); + println(); break; case "time": - ulong timestamp = Syscall.GetTimestamp; - Print("Current timestamp: "); + ulong timestamp = Syscall.getTimestamp; + print("Current timestamp: "); char[ulong.sizeof * 8] buf; - Println(itoa(timestamp, buf, 10)); + println(itoa(timestamp, buf, 10)); break; case "sleep": if (cmd.args.length == 1) { - Println("sleep: "); + println("sleep: "); break; } ulong secs = atoi(cast(string)cmd.args[1]); - Syscall.Sleep(secs * 1000); + Syscall.sleep(secs * 1000); break; case "ls": DirectoryListing[32] listings = void; void* ptr = cast(void*)listings.ptr; size_t len = listings.length; - size_t count = Syscall.ListDirectory(ptr, len); - Println("ID\tName\t\tType"); + size_t count = Syscall.listDirectory(ptr, len); + println("ID\tName\t\tType"); foreach (list; listings[0 .. count]) { char[ulong.sizeof * 8] buf; - Print(itoa(list.id, buf, 10)); - Print(":\t"); - Print(list.name.fromStringz); - Print("\t\t"); - Print(list.type); - Println(); + print(itoa(list.id, buf, 10)); + print(":\t"); + print(list.name.fromStringz); + print("\t\t"); + print(list.type); + println(); } break; case "cd": if (cmd.args.length == 1) - Syscall.ChangeCurrentDirectory("/"); + Syscall.changeCurrentDirectory("/"); else - Syscall.ChangeCurrentDirectory(cast(string)cmd.args[1]); + Syscall.changeCurrentDirectory(cast(string)cmd.args[1]); break; default: - size_t ret = SpawnAndWait(cmd); - Println(); - Print("> Program returned: 0x"); + size_t ret = _spawnAndWait(cmd); + println(); + print("> Program returned: 0x"); char[ulong.sizeof * 8] buf; - Println(itoa(ret, buf, 16)); + println(itoa(ret, buf, 16)); break; } } -private: - size_t SpawnAndWait(Command* cmd) { - size_t pid = Syscall.Fork(); + size_t _spawnAndWait(Command* cmd) { + size_t pid = Syscall.fork(); if (!pid) { - size_t status = Syscall.Exec(cast(string)cmd.args[0], cast(string[])cmd.args); - Println("Failed to launch program!"); - Syscall.Exit(status); + size_t status = Syscall.exec(cast(string)cmd.args[0], cast(string[])cmd.args); + println("Failed to launch program!"); + Syscall.exit(status); } - return Syscall.Join(pid); + return Syscall.join(pid); } } diff --git a/utils/generatesymbols.d b/utils/generatesymbols.d index 33f9b59..c7dcbef 100644 --- a/utils/generatesymbols.d +++ b/utils/generatesymbols.d @@ -1,3 +1,5 @@ +module generatesymbols; + import std.stdio; import std.process; import std.demangle; @@ -7,23 +9,23 @@ import std.conv; struct SymbolTable { align(1): - char[] Magic = ['D', 'S', 'Y', 'M']; - ulong Count; + char[] magic = ['D', 'S', 'Y', 'M']; + ulong count; } struct Line { align(1): this(ulong start, ulong end, string name) { - Start = start; - End = end; - NameLength = name.length; - Name = name.dup; + this.start = start; + this.end = end; + this.nameLength = name.length; + this.name = name.dup; } - ulong Start; - ulong End; - ulong NameLength; - char[] Name; + ulong start; + ulong end; + ulong nameLength; + char[] name; } int main(string[] args) { @@ -40,16 +42,16 @@ int main(string[] args) { .array; //dfmt on - lines.each!(x => table.Count++); + lines.each!(x => table.count++); - output.rawWrite(table.Magic); - output.rawWrite((cast(ubyte*)&table.Count)[0 .. ulong.sizeof]); + output.rawWrite(table.magic); + output.rawWrite((cast(ubyte*)&table.count)[0 .. ulong.sizeof]); foreach (Line line; lines) { - output.rawWrite((cast(ubyte*)&line.Start)[0 .. ulong.sizeof]); - output.rawWrite((cast(ubyte*)&line.End)[0 .. ulong.sizeof]); - output.rawWrite((cast(ubyte*)&line.NameLength)[0 .. ulong.sizeof]); - output.rawWrite(line.Name); + output.rawWrite((cast(ubyte*)&line.start)[0 .. ulong.sizeof]); + output.rawWrite((cast(ubyte*)&line.end)[0 .. ulong.sizeof]); + output.rawWrite((cast(ubyte*)&line.nameLength)[0 .. ulong.sizeof]); + output.rawWrite(line.name); } output.close(); diff --git a/utils/makeinitrd.d b/utils/makeinitrd.d index 9669239..6fcd55f 100644 --- a/utils/makeinitrd.d +++ b/utils/makeinitrd.d @@ -1,15 +1,17 @@ +module makeinitrd; + import std.stdio; -enum MAGIC = ['D', 'S', 'K', '0']; +enum magic = ['D', 'S', 'K', '0']; enum Type : ulong { - File, - Folder + file, + folder } struct Initrd { align(1): - char[4] Magic; - ulong Count; + char[4] magic; + ulong count; } struct InitrdEntry { @@ -47,7 +49,7 @@ int main(string[] args) { fp.length = entries.length; foreach (idx, ref entry; entries) { - if (entry.type == Type.File) { + if (entry.type == Type.file) { fp[idx] = File(fullFilename[idx], "rb"); entry.size = fp[idx].size; entry.offset = offset; @@ -60,7 +62,7 @@ int main(string[] args) { foreach (entry; entries) entry.writeln; - Initrd header = Initrd(MAGIC, entries.length); + Initrd header = Initrd(magic, entries.length); f.rawWrite((cast(ubyte*)&header)[0 .. Initrd.sizeof]); f.rawWrite((cast(ubyte*)entries.ptr)[0 .. InitrdEntry.sizeof * entries.length]); @@ -71,7 +73,7 @@ int main(string[] args) { long diff = cast(long)entry.offset - cast(long)f.size; if (diff > 0) f.rawWrite(nullbytes[0 .. diff]); - if (entry.type == Type.File) { + if (entry.type == Type.file) { ubyte[] buf; buf.length = entry.size; if (buf.length) @@ -100,10 +102,10 @@ void addFiles(string path, ulong parent, ref InitrdEntry[] entries, ref string[] foreach (entry; dirEntries(path, SpanMode.shallow)) { fullFilename ~= entry.name; if (entry.isFile) - entries ~= InitrdEntry(entry.name.baseName.strip, 0, 0, Type.File, parent); + entries ~= InitrdEntry(entry.name.baseName.strip, 0, 0, Type.file, parent); else { ulong par = entries.length; - entries ~= InitrdEntry(entry.name.baseName.strip, 0, 0, Type.Folder, parent); + entries ~= InitrdEntry(entry.name.baseName.strip, 0, 0, Type.folder, parent); addFiles(entry.name, par, entries, fullFilename); } }