diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..81f3bd3 --- /dev/null +++ b/.clang-format @@ -0,0 +1,123 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# clang-format configuration file. Intended for clang-format >= 11. +# +# For more information, see: +# +# Documentation/process/clang-format.rst +# https://clang.llvm.org/docs/ClangFormat.html +# https://clang.llvm.org/docs/ClangFormatStyleOptions.html +# +--- +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Left +AlignOperands: true +AlignTrailingComments: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: false +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: false +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: false +ColumnLimit: 132 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 8 +ContinuationIndentWidth: 8 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: false + +# Taken from: +# git grep -h '^#define [^[:space:]]*for_each[^[:space:]]*(' include/ tools/ \ +# | sed "s,^#define \([^[:space:]]*for_each[^[:space:]]*\)(.*$, - '\1'," \ +# | LC_ALL=C sort -u +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '.*' + Priority: 1 +IncludeIsMainRegex: '(Test)?$' +IndentCaseLabels: false +IndentGotoLabels: false +IndentPPDirectives: None +IndentWidth: 8 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 8 +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: true + +# Taken from git's rules +PenaltyBreakAssignment: 10 +PenaltyBreakBeforeFirstCallParameter: 30 +PenaltyBreakComment: 10 +PenaltyBreakFirstLessLess: 0 +PenaltyBreakString: 10 +PenaltyExcessCharacter: 100 +PenaltyReturnTypeOnItsOwnLine: 60 + +PointerAlignment: Right +ReflowComments: false +SortIncludes: false +SortUsingDeclarations: false +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatementsExceptForEachMacros +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: false +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp03 +TabWidth: 8 +UseTab: Always +... diff --git a/.gdbinit b/.gdbinit new file mode 100644 index 0000000..54e4e4c --- /dev/null +++ b/.gdbinit @@ -0,0 +1,2 @@ +file kernel.elf +target remote localhost:1234 diff --git a/.gitignore b/.gitignore index 3c30d89..4c4c601 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,10 @@ +iso_root/ +limine/ .cache *.o *.d *.elf compile_commands.json bin +boot.iso +edk2-ovmf/ diff --git a/COPYING b/COPYING deleted file mode 100644 index 39ab328..0000000 --- a/COPYING +++ /dev/null @@ -1,340 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. diff --git a/Makefile b/Makefile index 8985fe9..3cb70bd 100644 --- a/Makefile +++ b/Makefile @@ -1,10 +1,22 @@ -MAKEFLAGS += -rR +ARCH := x86_64 +LIMINE_VERSION=v11.2.0 KERNEL := kernel.elf -CC := x86_64-elf-gcc -LD := x86_64-elf-ld +IMG := boot.iso -CFLAGS := -g -O0 -pipe -Wall +QEMUFLAGS := -m 16G + +HOST_CC := gcc +HOST_CFLAGS := -O2 -pipe +HOST_LDFLAGS := +HOST_LIBS := + +MAKEFLAGS += -rR + +CC := $(ARCH)-elf-gcc +LD := $(ARCH)-elf-ld + +CFLAGS := -g3 -O0 -pipe -Wall CFLAGS += \ -std=gnu99 \ @@ -20,37 +32,44 @@ CFLAGS += \ -march=x86-64 \ -mabi=sysv \ -mno-80387 \ - -mno-mmx \ - -mno-sse \ - -mno-sse2 \ -mno-red-zone \ -mcmodel=kernel \ - -Iinclude \ + -Iinclude \ -MMD LDFLAGS := \ -nostdlib \ -static \ - -m elf_x86_64 \ + -m elf_$(ARCH) \ -z max-page-size=0x1000 \ -T linker.ld \ -no-pie \ -KDIRS := dev/ fs/ lib/ mem/ sched/ init/ +KDIRS := mem/ lib/ drivers/ kernel/ fs/ init/ + +ifeq ($(ARCH),x86_64) + CFLAGS += -Iamd64/include + KDIRS += amd64/ +endif CFILES := $(shell find $(KDIRS) -type f -name '*.c') ASFILES := $(shell find $(KDIRS) -type f -name '*.S') OBJ := $(CFILES:.c=.o) $(ASFILES:.S=.o) HEADER_DEPS := $(CFILES:.c=.d) $(ASFILES:.S=.d) +print-%: + @echo $($(*)) + +.PHONY: default +default: + @compiledb -n make $(IMG) + @make $(IMG) -j$(shell nproc) + .PHONY: all -all: $(KERNEL) +all: $(IMG) + @compiledb -n make -.PHONY: _usr -_usr: - @cd usr.bin && ./make.sh install - -$(KERNEL): $(OBJ) _usr linker.ld +$(KERNEL): $(OBJ) linker.ld @echo " LD $@" @$(LD) $(OBJ) $(LDFLAGS) -o $@ @@ -68,17 +87,70 @@ $(KERNEL): $(OBJ) _usr linker.ld clean: @echo " CLEAN kernel" @rm -rf $(KERNEL) $(OBJ) $(HEADER_DEPS) bin - @echo " CLEAN usr.bin" - @cd usr.bin && ./make.sh clean + @echo " CLEAN $(IMG)" + @rm -rf $(IMG) + @echo " CLEAN iso_root" + @rm -rf iso_root + @echo " CLEAN os_root" + @rm -rf os_root -.PHONY: distclean -distclean: clean - rm -f +$(IMG): limine/limine $(KERNEL) limine.conf + rm -rf iso_root + mkdir -p iso_root/boot + cp -v $(KERNEL) iso_root/ + mkdir -p iso_root/boot/limine + cp -v limine.conf iso_root/boot/limine/ + mkdir -p iso_root/EFI/BOOT + + cp -v limine/limine-bios.sys limine/limine-bios-cd.bin limine/limine-uefi-cd.bin iso_root/boot/limine/ + cp -v limine/BOOTX64.EFI iso_root/EFI/BOOT/ + cp -v limine/BOOTIA32.EFI iso_root/EFI/BOOT/ + + mkdir -p os_root/ + mke2fs -d os_root -t ext2 os_root.img 512M + + xorriso -as mkisofs -R -r -J \ + --efi-boot boot/limine/limine-uefi-cd.bin \ + -efi-boot-part --efi-boot-image --protective-msdos-label \ + --partition_offset 16 \ + -append_partition 2 0x83 os_root.img \ + iso_root -o $(IMG) + + rm -rf os_root.img + +limine/limine: + rm -rf limine + git clone https://codeberg.org/Limine/Limine.git limine --branch=$(LIMINE_VERSION)-binary --depth=1 + $(MAKE) -C limine \ + CC="$(HOST_CC)" \ + CFLAGS="$(HOST_CFLAGS)" \ + CPPFLAGS="$(HOST_CPPFLAGS)" \ + LDFLAGS="$(HOST_LDFLAGS)" \ + LIBS="$(HOST_LIBS)" .PHONY += run -run: - make -C .. run +run: edk2-ovmf $(IMG) + qemu-system-$(ARCH) \ + -M q35 \ + -drive if=pflash,unit=0,format=raw,file=edk2-ovmf/ovmf-code-$(ARCH).fd,readonly=on \ + -nographic \ + -cdrom $(IMG) \ + $(QEMUFLAGS) .PHONY += debug -debug: - make -C .. run-debug +debug: edk2-ovmf $(IMG) + qemu-system-$(ARCH) \ + -S -s \ + -M q35 \ + -drive if=pflash,unit=0,format=raw,file=edk2-ovmf/ovmf-code-$(ARCH).fd,readonly=on \ + -nographic \ + -cdrom $(IMG) \ + $(QEMUFLAGS) + +edk2-ovmf: + curl -L https://github.com/osdev0/edk2-ovmf-nightly/releases/latest/download/edk2-ovmf.tar.gz | gunzip | tar -xf - + +.PHONY += distclean +distclean: + make clean + rm -rf limine diff --git a/README.md b/README.md deleted file mode 100644 index 3409823..0000000 --- a/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# vbos - very bad os - now with executables! - -``` -"Don't reinvent the wheel" - Some idiot, probably -``` - -For-fun operating system created by me! - -## Compilation - -You will need to acquire a copy of `x86_64-elf-gcc`. This can be done by either -compiling it yourself, or through your distribution's package manager. A version -of `x86_64-elf-gcc` is available in the AUR that I maintain. - -## Installation - -You will need to deploy limine onto a filesystem image, the limine barebones -project will suffice for creating this. In addition, you must also have an -ext2 filesystem image. - -After compilation, the bin folder contains the userspace binaries that can be -copied into your filesystem image. - -NOTE: For versions of limine >=5.x, multiple images must be used. Limine will -no longer accept ext2 filesystems for booting kernel images, and this OS as of -yet only supports ext2. - -Be sure to set `SERIAL=yes` at the top of your limine.cfg as well as the -`KERNEL_CMDLINE=` parameter `root=` as your root filesystem (not necessarily -the boot filesystem). Booting without the `root=` parameter will cause a panic -giving you a list of available block devices to mount. Only ext2 is supported -for mounting filesystems. - -If you wish to use a partition scheme, it must be GPT. If not, mounting the bare -block device should (probably) work fine. - -## License - -This project is licensed under `SPDX-License-Identifier: GPL-2.0-only`, a copy -of which can be found in the COPYING file. All source files, except for -`limine.h` are released under this license. - -Copyright 2023-2025 Michael Shaw. diff --git a/amd64/arch/msr.S b/amd64/arch/msr.S new file mode 100644 index 0000000..97f1466 --- /dev/null +++ b/amd64/arch/msr.S @@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +.intel_syntax noprefix + +.global rdmsr +rdmsr: + mov ecx, edi + rdmsr + shl rdx, 0x20 + or rax, rdx + ret + +.global wrmsr +wrmsr: + mov rdx, rsi + shr rdx, 0x20 + mov eax, esi + mov ecx, edi + wrmsr + + ret + diff --git a/amd64/arch/page.c b/amd64/arch/page.c new file mode 100644 index 0000000..aed7a3c --- /dev/null +++ b/amd64/arch/page.c @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include +#include +#include + +#include +#include "reg.h" + +void pgd_load(pgd_t *pgd) +{ + uintptr_t i = (uintptr_t)pgd; + + cr3_write(TO_PHYS(i)); +} + +pgd_t *pgd_get() +{ + uintptr_t ret = cr3_read() | hhdm_start; + return (void *)ret; +} diff --git a/amd64/arch/reg.S b/amd64/arch/reg.S new file mode 100644 index 0000000..e1fce8d --- /dev/null +++ b/amd64/arch/reg.S @@ -0,0 +1,12 @@ +.intel_syntax noprefix + +.global cr3_write +cr3_write: + mov cr3, rdi + ret + +.global cr3_read +cr3_read: + mov rax, cr3 + ret + diff --git a/amd64/arch/reg.h b/amd64/arch/reg.h new file mode 100644 index 0000000..b8f8740 --- /dev/null +++ b/amd64/arch/reg.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _REG_H_ +#define _REG_H_ + +#include + +void cr3_write(); +u64 cr3_read(); + +#endif /* _REG_H_ */ diff --git a/dev/apic.c b/amd64/drivers/apic.c similarity index 68% rename from dev/apic.c rename to amd64/drivers/apic.c index 24b0b34..d516a14 100644 --- a/dev/apic.c +++ b/amd64/drivers/apic.c @@ -1,12 +1,12 @@ -#include +/* SPDX-License-Identifier: GPL-2.0-only */ #include -#include -#include +#include +#include #include static uintptr_t ioapic_addr = 0xFEC00000; -static uintptr_t lapic_addr = 0; +static uintptr_t lapic_addr = 0xFEE00000; static uint8_t lapic_id = 0; static struct ioapic { @@ -47,28 +47,6 @@ uint32_t lapic_write(uintptr_t addr, unsigned int regoffset, uint32_t value) return lapic[regoffset >> 2]; } -int madt_parse_next_entry(int offset) -{ - if ((unsigned)offset >= (__madt->h.length - 1)) - return 0; - - uint8_t *madt = (uint8_t *)__madt; - int type = madt[offset]; - int len = madt[offset + 1]; - - /* Can't declare variables inside switch statement */ - struct madt_lapic *m_lapic = (struct madt_lapic *)madt; - - switch (type) { - case MADT_LAPIC: - lapic_id = m_lapic->acpi_cpu_id; - default: - break; - } - - return offset + len; -} - void apic_eoi() { lapic_write(lapic_addr, 0xB0, 0); @@ -92,20 +70,8 @@ uint8_t lapic_idno() void apic_init() { - if (__madt == NULL) { - kprintf(LOG_WARN "No MADT found\n"); - return; - } - - int offset = 0x2C; - - while ((offset = madt_parse_next_entry(offset))) - ; - - lapic_addr = __madt->lapic_addr; - - lapic_addr = (uintptr_t)kmap_device((void *)lapic_addr, 0x1000); - ioapic_addr = (uintptr_t)kmap_device((void *)ioapic_addr, 0x1000); + ioapic_addr += hhdm_start; + lapic_addr += hhdm_start; ioapic = (void *)ioapic_addr; @@ -113,7 +79,6 @@ void apic_init() r |= 0x04000000; ioapic_write(0, r); - /* get ioapic version */ lapic_id = lapic_read(lapic_addr, 0x20); ioapic_redirect_insert(4, 0x24, 0, 0); @@ -125,7 +90,7 @@ void apic_init() lapic_eoi(); - kprintf(LOG_SUCCESS "APIC initialized\n"); + krdy("APIC initialized\n"); } void apic_enable_timer() diff --git a/amd64/drivers/pio.S b/amd64/drivers/pio.S new file mode 100644 index 0000000..6ac36c3 --- /dev/null +++ b/amd64/drivers/pio.S @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +.intel_syntax noprefix + +.global outb +outb: + mov ax, si + mov dx, di + out dx, al + ret + +.global inb +inb: + mov dx, di + in al, dx + ret + +.global outw +outw: + mov ax, si + mov dx, di + out dx, ax + ret + +.global inw +inw: + mov dx, di + in ax, dx + ret diff --git a/amd64/drivers/serial.c b/amd64/drivers/serial.c new file mode 100644 index 0000000..9f75863 --- /dev/null +++ b/amd64/drivers/serial.c @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include +#include + +#include +#include + +#include + +#include + +struct serial_port { + dev_t dev; + int port; +}; + +static int num_serial_ports = 0; +static struct serial_port serial_ports[32]; + +static dev_t init_serial_port(int port) +{ + outb(port | 1, 0x00); + outb(port | 3, 0x80); + outb(port | 0, 0x01); + outb(port | 1, 0x00); + outb(port | 3, 0x03); + outb(port | 2, 0xC7); + outb(port | 4, 0x0B); + outb(port | 4, 0x1E); + + outb(port | 0, 0xAE); /* Enable loopback mode */ + if (inb(port | 0) != 0xAE) { /* Loopback test */ + kwarn("Serial port 0x%04x loopback test failed\n", port); + return 1; + } + + outb(port | 1, 0x01); /* Enable interrupts */ + outb(port | 4, 0x0F); /* Enter normal operation */ + + char name[256]; + + snprintf(name, sizeof(name) - 1, "tty%04x", port); + name[sizeof(name) - 1] = 0; + + dev_t serial_device = device_create(&serial_ports[num_serial_ports], DEV_CLASS_NATIVE_SERIAL, name); + + if (num_serial_ports + 1 < ARRAY_SIZE(serial_ports)) { + serial_ports[num_serial_ports].dev = serial_device; + serial_ports[num_serial_ports].port = port; + num_serial_ports += 1; + } + + return serial_device; +} + +dev_t arch_serial_init() +{ + dev_t com1 = init_serial_port(COM1); + return com1; +} + +void arch_serial_write(struct tty *tty, char c) +{ + /* Wait for line to be clear */ + struct serial_port *serial_port = tty->serial_device_private; + while ((inb(serial_port->port + 5) & 0x20) == 0) + ; + outb(serial_port->port, c); +} + +char arch_serial_read(struct tty *tty) +{ + struct serial_port *serial_port = tty->serial_device_private; + + while ((inb(serial_port->port + 5) & 1) == 0) + ; + + return inb(serial_port->port); +} diff --git a/amd64/include/arch/msr.h b/amd64/include/arch/msr.h new file mode 100644 index 0000000..dfead50 --- /dev/null +++ b/amd64/include/arch/msr.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _MSR_H_ +#define _MSR_H_ + +#include + +u64 rdmsr(u32 msr); +void wrmsr(u32 msr, u64 val); + +#endif /* _MSR_H_ */ diff --git a/amd64/include/arch/page.h b/amd64/include/arch/page.h new file mode 100644 index 0000000..3cf288c --- /dev/null +++ b/amd64/include/arch/page.h @@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _AMD64_PAGE_H_ +#define _AMD64_PAGE_H_ + +#include + +#define PAGE_SIZE 0x1000ull + +#define PAGE_MASK_LOWER (~(PAGE_SIZE - 1)) +#define PAGE_MASK_UPPER ((PAGE_SIZE - 1)) + +#define PAGE_ALIGN (~(PAGE_SIZE - 1)) + +#define PAGE_PRESENT 0x001 +#define PAGE_RW 0x002 +#define PAGE_USER 0x004 +#define PAGE_WRITE_THRU 0x008 +#define PAGE_CACHE_DISABLE 0x010 +#define PAGE_ACCESSED 0x020 +#define PAGE_DIRTY 0x040 +#define PAGE_4MB_ENABLE 0x080 + +#define pgd_index(address) (((address) >> 39) & 0x1FF) +#define pud_index(address) (((address) >> 30) & 0x1FF) +#define pmd_index(address) (((address) >> 21) & 0x1FF) +#define pte_index(address) (((address) >> 12) & 0x1FF) + +void pgd_load(pgd_t *pgd); +u64 *_pt_read(u64 *dir, size_t index, u64 *flags); +void _pt_write(u64 *dir, size_t index, u64 *val, u64 flags); + +#endif /* _AMD64_PAGE_H_ */ diff --git a/amd64/include/drivers/apic.h b/amd64/include/drivers/apic.h new file mode 100644 index 0000000..92102d2 --- /dev/null +++ b/amd64/include/drivers/apic.h @@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _APIC_H_ +#define _APIC_H_ + +#define MADT_LAPIC 0 +#define MADT_IOAPIC 1 +#define MADT_IOAPIC_OVRD 2 +#define MADT_IOAPIC_NMI 3 +#define MADT_LAPIC_NMI 4 +#define MADT_LAPIC_OVRD 5 +#define MADT_X2_LAPIC 9 + +#define LAPIC_ID 0x20 +#define LAPIC_VERSION 0x30 +#define LAPIC_TPR 0x80 +#define LAPIC_APR 0x90 +#define LAPIC_PPR 0xA0 +#define LAPIC_EOI 0xB0 +#define LAPIC_RRD 0xC0 +#define LAPIC_LDR 0xD0 +#define LAPIC_DFR 0xE0 +#define LAPIC_SIVR 0xF0 +#define LAPIC_ISR 0x100 +#define LAPIC_TMR 0x180 +#define LAPIC_IRR 0x200 +#define LAPIC_ERR 0x280 +#define LAPIC_CMCI 0x2F0 +#define LAPIC_ICR 0x300 +#define LAPIC_THERMAL 0x330 +#define LAPIC_LVT_PERF_MON_COUNT 0x340 +#define LAPIC_LVT_LINT0 0x350 +#define LAPIC_LVT_LINT1 0x360 +#define LAPIC_LVT_ERR 0x370 +#define LAPIC_INIT_COUNT 0x380 +#define LAPIC_CUR_COUNT 0x390 + +#define LAPIC_TIMER 0x320 +#define LAPIC_TIMER_DIV 0x3E0 +#define LAPIC_TIMER_INIT_COUNT 0x380 +#define MSR_IA32_APIC_BASE 0x1B + +void apic_init(); + +#endif /* _APIC_H_ */ diff --git a/amd64/include/drivers/pio.h b/amd64/include/drivers/pio.h new file mode 100644 index 0000000..9765f04 --- /dev/null +++ b/amd64/include/drivers/pio.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _PIO_H_ +#define _PIO_H_ + +#include + +void outb(u16 port, u8 byte); +u8 inb(u16 port); + +void outw(u16 port, u16 word); +u16 inw(u16 port); + +#endif /* _PIO_H_ */ diff --git a/amd64/include/drivers/serial.h b/amd64/include/drivers/serial.h new file mode 100644 index 0000000..faa5bfb --- /dev/null +++ b/amd64/include/drivers/serial.h @@ -0,0 +1,14 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _SERIAL_H_ +#define _SERIAL_H_ + +#define COM1 0x3F8 +#define COM2 0x2F8 + +#define DEV_CLASS_NATIVE_SERIAL 0x9000 + +#include + +dev_t arch_serial_init(); + +#endif /* _SERIAL_H_ */ diff --git a/amd64/include/kernel/spinlock.h b/amd64/include/kernel/spinlock.h new file mode 100644 index 0000000..4311967 --- /dev/null +++ b/amd64/include/kernel/spinlock.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _SPINLOCK_H_ +#define _SPINLOCK_H_ + +#include + +typedef u64 spinlock_t; + +void spinlock_acquire(spinlock_t *lock); +void spinlock_release(spinlock_t *lock); + +#endif /* _SPINLOCK_H_ */ diff --git a/amd64/init/amd64_init.c b/amd64/init/amd64_init.c new file mode 100644 index 0000000..a4a0edb --- /dev/null +++ b/amd64/init/amd64_init.c @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +void yield() +{ + for (;;) { + asm("hlt"); + } +} + +void _panic() +{ + yield(); +} diff --git a/amd64/kernel/atomic.S b/amd64/kernel/atomic.S new file mode 100644 index 0000000..b7fde6d --- /dev/null +++ b/amd64/kernel/atomic.S @@ -0,0 +1,13 @@ +.intel_syntax noprefix +.global atomic_cmpxchg +atomic_cmpxchg: + mov eax, esi + lock cmpxchg [rdi], edx + + jnz nz + xor eax, eax + ret +nz: + mov eax, 1 + ret + diff --git a/lib/lock.c b/amd64/kernel/spinlock.c similarity index 60% rename from lib/lock.c rename to amd64/kernel/spinlock.c index 0aff9fe..7e11692 100644 --- a/lib/lock.c +++ b/amd64/kernel/spinlock.c @@ -1,7 +1,8 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ #include -#include +#include -#include +int atomic_cmpxchg(spinlock_t *lock, int a, int b); static uint64_t spinlock_attempt_acquire(spinlock_t *lock) { @@ -18,14 +19,3 @@ void spinlock_release(spinlock_t *lock) { atomic_cmpxchg(lock, 1, 0); } - -void mtx_acquire(mtx_t *mtx) -{ - while (spinlock_attempt_acquire(mtx)) - sswtch(); -} - -void mtx_release(mtx_t *mtx) -{ - spinlock_release(mtx); -} diff --git a/dev/ahci.c b/dev/ahci.c deleted file mode 100644 index bd5fe06..0000000 --- a/dev/ahci.c +++ /dev/null @@ -1,319 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include -#include -#include -#include - -#include -#include - -static int ahci_block_read(struct block_device *dev, void *buf, size_t offset, size_t sector_count); -static int ahci_block_write(struct block_device *dev, void *buf, size_t offset, size_t sector_count); - -static struct block_device_ops ahci_block_ops = { - .read = ahci_block_read, - .write = ahci_block_write, -}; - -static hbamem_t *abar = NULL; - -static uint8_t sata_device_count = 0; -static struct sata_device sata_devices[32] = { 0 }; - -static paddr_t ahci_pbase = 0; -static uintptr_t ahci_vbase = 0; - -static void ahci_irq_handler() -{ - kprintf(LOG_ERROR "AHCI INTERRUPT\n"); -} - -static int ahci_port_type(hbaport_t *port) -{ - uint32_t ssts = port->ssts; - uint8_t det = ssts & 0x0F; - - if (det != HBA_PORT_DET_PRESENT) - return AHCI_DEV_NULL; - - if (port->clb == 0) - return AHCI_DEV_NULL; - - switch (port->sig) { - case SATA_SIG_ATAPI: - return AHCI_DEV_SATAPI; - case SATA_SIG_SEMB: - return AHCI_DEV_SEMB; - case SATA_SIG_PM: - return AHCI_DEV_PM; - default: - return AHCI_DEV_SATA; - } -} - -static void halt_cmd(hbaport_t *port) -{ - port->cmd &= ~HBA_PORT_CMD_ST; - port->cmd &= ~HBA_PORT_CMD_FRE; - - while (port->cmd & (HBA_PORT_CMD_FR | HBA_PORT_CMD_CR)) - ; -} - -static void start_cmd(hbaport_t *port) -{ - while (port->cmd & HBA_PORT_CMD_CR) - ; - - port->cmd |= HBA_PORT_CMD_FRE; - port->cmd |= HBA_PORT_CMD_ST; -} - -static void ahci_rebase(hbaport_t *port, int n) -{ - halt_cmd(port); - - port->clb = (ahci_pbase) + (n << 10); - memset((void *)(port->clb | hhdm_start), 0, 1024); - - port->fb = ahci_pbase + (32 << 10) + (n << 8); - memset((void *)(port->fb | hhdm_start), 0, 256); - - struct hba_cmd_header *cmdheader = (struct hba_cmd_header *)(port->clb | hhdm_start); - for (int i = 0; i < 32; i++) { - cmdheader[i].prdt_len = 8; - cmdheader[i].cmd_table_base = (ahci_pbase) + (n << 13) + (40 << 10) + (i << 8); - - void *ctba = (void *)((uintptr_t)cmdheader[i].cmd_table_base | hhdm_start); - memset(ctba, 0, 256); - } - - start_cmd(port); -} - -static void ahci_probe_ports(struct pci_device *dev, hbamem_t *abar) -{ - uint32_t pi = abar->pi; - for (int i = 0; i < 32; i++) { - if (pi & 1) { - uint32_t type = ahci_port_type(&abar->ports[i]); - if (type == AHCI_DEV_SATA) { - struct sata_device *sdev = &sata_devices[sata_device_count]; - sdev->port = i; - sdev->controller = dev; - sdev->abar = abar; - - char *name = kzalloc(16, ALLOC_KERN); - name[15] = 0; - - snprintf(name, "ahci%d", 15, sata_device_count); - - size_t sector_count = ((size_t)abar->ports[i].ssts) << 32 | abar->ports[i].ssts; - sdev->sector_count = sector_count; - - sdev->sector_size = 512; - - struct block_device *bdev; - bdev = block_register(name, &ahci_block_ops, sdev, sector_count, sdev->sector_size); - block_gpt_init(bdev); - - ahci_rebase(&abar->ports[i], i); - sata_device_count++; - kprintf(LOG_INFO "SATA drive found at port %d\n", i); - } else if (type == AHCI_DEV_SATAPI) { - kprintf(LOG_INFO "SATAPI drive found at port %d\n", i); - } else if (type == AHCI_DEV_SEMB) { - kprintf(LOG_INFO "SEMB drive found at port %d\n", i); - } else if (type == AHCI_DEV_PM) { - kprintf(LOG_INFO "PM drive found at port %d\n", i); - } - } - pi >>= 1; - } -} - -static int cmdslot(hbaport_t *port) -{ - uint32_t slots = (port->sact | port->ci); - for (int i = 0; i < 32; i++) { - if ((slots & 1)) - slots >>= 1; - else - return i; - } - - return -1; -} - -bool ahci_access_sectors(struct sata_device *dev, paddr_t lba, uint16_t count, paddr_t buf, bool write) -{ - hbaport_t *port = &dev->abar->ports[dev->port]; - - /* clear pending interrupt */ - port->is = (uint32_t)-1; - - int spin = 0; - int slot = cmdslot(port); - if (slot == -1) - return false; - - struct hba_cmd_header *cmdheader = (struct hba_cmd_header *)(port->clb | hhdm_start); - cmdheader += slot; - cmdheader->cmd_fis_len = sizeof(struct fis_reg_h2d) / sizeof(uint32_t); - cmdheader->write = 0; - cmdheader->prdt_len = (uint16_t)((count - 1) >> 4) + 1; - - struct hba_cmd_tbl *cmdtbl = (struct hba_cmd_tbl *)(cmdheader->cmd_table_base | hhdm_start); - memset(cmdtbl, 0, sizeof(struct hba_cmd_tbl) + (cmdheader->prdt_len - 1) * sizeof(struct hba_prdt_entry)); - - struct fis_reg_h2d *cmdfis = (struct fis_reg_h2d *)(&cmdtbl->cfis); - cmdfis->fis_type = FIS_REG_H2D; - cmdfis->cmd_mode = 1; - cmdfis->command = write ? ATA_CMD_WRITE_DMA_EX : ATA_CMD_READ_DMA_EX; - - cmdfis->lba0 = (uint8_t)lba; - cmdfis->lba1 = (uint8_t)(lba >> 8); - cmdfis->lba2 = (uint8_t)(lba >> 16); - cmdfis->device = 1 << 6; /* LBA mode */ - cmdfis->lba3 = (uint8_t)(lba >> 24); - cmdfis->lba4 = (uint8_t)(lba >> 32); - cmdfis->lba5 = (uint8_t)(lba >> 40); - - cmdfis->count_low = count & 0xff; - cmdfis->count_high = (count >> 8) & 0xff; - - int i; - for (i = 0; i < cmdheader->prdt_len; i++) { - cmdtbl->prdt_entry[i].data_base = buf; - cmdtbl->prdt_entry[i].byte_count = 8 * 1024 - 1; - cmdtbl->prdt_entry[i].interrupt = 1; - buf += 8 * 1024; - count -= 16; - } - - /* wait until port is free */ - while ((port->tfd & (ATA_DEV_BUSY | ATA_DEV_DRQ)) && spin < 1000000) { - spin++; - } - - if (spin == 1000000) { - kprintf(LOG_ERROR "AHCI: Port is hung\n"); - return false; - } - - /* issue command */ - port->ci = 1 << slot; - - /* wait for completion */ - struct proc *proc = proc_find(getpid()); - while (1) { - if (port->is & HBA_PORT_IS_TFES) { - kprintf(LOG_ERROR "AHCI: Read disk error\n"); - return false; - } - - if ((port->ci & (1 << slot)) == 0) - break; - else if (proc->buddy_proc) - sswtch(); - - } - - /* check again */ - if (port->is & HBA_PORT_IS_TFES) { - kprintf(LOG_ERROR "AHCI: Read disk error\n"); - return false; - } - - return true; -} - -static int ahci_block_read(struct block_device *dev, void *buf, size_t offset, size_t sector_count) -{ - struct sata_device *sdev = (struct sata_device *)dev->data; - - /* repeat every 64K, due to the current limitations of this driver */ - while (sector_count > 0) { - size_t n = MIN(sector_count, 128u); - if (!ahci_access_sectors(sdev, offset, n, (paddr_t)buf & ~hhdm_start, false)) - return -1; - if (sector_count <= 128) - break; - sector_count -= 128ull; - offset += 128; - buf += (128 << 9); - } - - return 0; -} - -static int ahci_block_write(struct block_device *dev, void *buf, size_t offset, size_t sector_count) -{ - struct sata_device *sdev = (struct sata_device *)dev->data; - - /* repeat every 64K, same as above */ - while (sector_count > 0) { - size_t n = MIN(sector_count, 128u); - if (!ahci_access_sectors(sdev, offset, n, (paddr_t)buf & ~hhdm_start, true)) - return -1; - if (sector_count <= 128) - break; - sector_count -= 128ull; - offset += 128; - buf += (128 << 9); - } - - return 0; -} - -void ahci_init() -{ - struct pci_device *dev = pci_find_device(0x01, 0x06); - /* check interrupt number */ - if (dev == NULL) { - kprintf(LOG_WARN "No SATA controllers found\n"); - return; - } - - abar = (hbamem_t *)((uintptr_t)dev->bar5); - abar = kmap_device((void *)abar, sizeof(hbamem_t)); - - if (!(abar->ghc & (1 << 31))) { - kprintf(LOG_WARN "AHCI controller not enabled\n"); - return; - } - - /* enable AHCI interrupts */ - abar->ghc |= AHCI_GHC_IE; - abar->ghc |= AHCI_GHC_AE; - - size_t ahci_zone_size = 0x100000; - ahci_pbase = (paddr_t)buddy_alloc(ahci_zone_size) & (~hhdm_start); /* 1 MiB */ - ahci_probe_ports(dev, abar); - - ahci_vbase = mmap_find_unmapped(kmap_tree, &kmap_lock, hhdm_start, ahci_zone_size); - - /* map ahci zone with cache disabled (pcd=1) */ - struct page attrs; - attrs.val = 1; - attrs.rw = 1; - attrs.pcd = 1; - kmap(ahci_pbase, ahci_vbase, ahci_zone_size, attrs.val); - - if (sata_device_count == 0) { - kprintf(LOG_WARN "No SATA devices found\n"); - return; - } - - /* setup device irq number */ - uint16_t irq = irq_highest_free(); - uint32_t tmp = pci_config_read_long(dev->bus, dev->slot, dev->func, 0x3C); - tmp &= 0xFFFFFF00; - tmp |= irq; - pci_config_write_long(dev->bus, dev->slot, dev->func, 0x3C, tmp); - irq_map(irq, ahci_irq_handler); - - kprintf(LOG_SUCCESS "AHCI controller ready\n"); -} diff --git a/dev/block.c b/dev/block.c deleted file mode 100644 index 30379d7..0000000 --- a/dev/block.c +++ /dev/null @@ -1,70 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include -#include - -#define MAX_BLOCK_DEVICES 24 - -struct block_device *block_devices[MAX_BLOCK_DEVICES]; -size_t block_devices_count = 0; - -struct block_device *block_register(char *name, struct block_device_ops *ops, void *data, size_t block_count, size_t block_size) -{ - struct block_device *bdev; - - bdev = kmalloc(sizeof(struct block_device), ALLOC_KERN); - if (!bdev) - return NULL; - - bdev->name = name; - bdev->data = data; - bdev->block_count = block_count; - bdev->block_size = block_size; - bdev->lba_start = 0; - bdev->fs = NULL; - memcpy(&bdev->ops, ops, sizeof(struct block_device_ops)); - - block_devices[block_devices_count] = bdev; - block_devices_count++; - -#ifdef KDEBUG - kprintf(LOG_DEBUG "Registered block device %s\n", name); -#endif - - return bdev; -} - -struct block_device **block_get_all_devices(int *n) -{ - *n = block_devices_count; - return block_devices; -} - -struct block_device *block_get_device(const char *name) -{ - for (size_t i = 0; i < block_devices_count; i++) { - if (!strcmp(block_devices[i]->name, name)) - return block_devices[i]; - } - - return NULL; -} - -inline int block_read(struct block_device *bdev, void *buf, size_t offset, size_t size) -{ - return bdev->ops.read(bdev, buf, offset + bdev->lba_start, size); -} - -inline int block_write(struct block_device *bdev, void *buf, size_t offset, size_t size) -{ - return bdev->ops.write(bdev, buf, offset + bdev->lba_start, size); -} - -void kerror_print_blkdevs() -{ - kprintf(LOG_ERROR "List of available block devices:\n"); - for (size_t i = 0; i < block_devices_count; i++) { - kprintf(LOG_ERROR " %s\n", block_devices[i]->name); - } -} diff --git a/dev/char.c b/dev/char.c deleted file mode 100644 index d0dc077..0000000 --- a/dev/char.c +++ /dev/null @@ -1,22 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ - -#include -#include -#include - -#include - -struct char_device *char_device_create(const char *name, void *data) -{ - size_t name_len = strlen(name); - struct char_device *cd = kmalloc(sizeof(struct char_device), ALLOC_KERN); - cd->name = kzalloc(name_len + 1, ALLOC_KERN); - cd->data = data; - return cd; -} - -void char_device_destroy(struct char_device *cd) -{ - ATTEMPT_FREE(cd->name); - ATTEMPT_FREE(cd); -} diff --git a/dev/pci.c b/dev/pci.c deleted file mode 100644 index bd31a98..0000000 --- a/dev/pci.c +++ /dev/null @@ -1,117 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include - -#define MAX_PCI_DEVICES 256 - -static struct pci_device *pci_devices; -static uint8_t pci_device_count; - -uint32_t pci_config_read_long(uint8_t bus, uint8_t slot, uint8_t func, uint8_t offset) -{ - uint32_t addr; - uint32_t lbus = bus; - uint32_t lslot = slot; - uint32_t lfunc = func; - - addr = (lbus << 16) | (lslot << 11) | (lfunc << 8) | (offset & 0xfc) | 0x80000000; - - outl(PCIPM_CONFIG_ADDRESS, addr); - return inl(PCIPM_CONFIG_DATA); -} - -void pci_config_write_long(uint8_t bus, uint8_t slot, uint8_t func, uint8_t offset, uint16_t data) -{ - uint32_t addr; - uint32_t lbus = bus; - uint32_t lslot = slot; - uint32_t lfunc = func; - - addr = (lbus << 16) | (lslot << 11) | (lfunc << 8) | (offset & 0xfc) | 0x80000000; - - outl(PCIPM_CONFIG_ADDRESS, addr); - outl(PCIPM_CONFIG_DATA, data); -} - -static struct pci_device *pci_scan_function(uint8_t bus, uint8_t slot, uint8_t func) -{ - uint32_t vendor_device = pci_config_read_long(bus, slot, func, 0x0); - uint16_t vendor_id = vendor_device & 0xFFFF; - uint16_t device_id = vendor_device >> 16; - - uint32_t class_subclass = pci_config_read_long(bus, slot, func, 0x8); - uint8_t class = (class_subclass >> 24) & 0xFF; - uint8_t subclass = (class_subclass >> 16) & 0xFF; - - if (vendor_id == 0xFFFF || class == 0xFF) - return NULL; - - struct pci_device *dev = &pci_devices[pci_device_count]; - dev->bus = bus; - dev->slot = slot; - dev->func = func; - dev->vendor_id = vendor_id; - dev->device_id = device_id; - dev->class = class; - dev->subclass = subclass; - - dev->bar0 = pci_config_read_long(bus, slot, func, 0x10); - dev->bar1 = pci_config_read_long(bus, slot, func, 0x14); - - uint8_t header_type = (pci_config_read_long(bus, slot, 0, 0xC) >> 16) & 0xFF; - dev->header_type = header_type; - - if ((header_type & 0x0F) == 0) { - dev->bar2 = pci_config_read_long(bus, slot, func, 0x18); - dev->bar3 = pci_config_read_long(bus, slot, func, 0x1C); - dev->bar4 = pci_config_read_long(bus, slot, func, 0x20); - dev->bar5 = pci_config_read_long(bus, slot, func, 0x24); - } - - pci_device_count++; - - return dev; -} - -static void pci_scan_bus(uint8_t bus) -{ - for (uint8_t slot = 0; slot < 32; slot++) { - struct pci_device *dev = pci_scan_function(bus, slot, 0); - if (dev != NULL && dev->header_type & 0x80) { - for (uint8_t func = 1; func < 8; func++) { - if (pci_config_read_long(bus, slot, func, 0) != 0xFFFFFFFF) - pci_scan_function(bus, slot, func); - } - } - } -} - -struct pci_device *pci_find_device(uint8_t class, uint8_t subclass) -{ - for (int i = 0; i < pci_device_count; i++) { - if (pci_devices[i].class == class && pci_devices[i].subclass == subclass) - return &pci_devices[i]; - } - - return NULL; -} - -void pci_init() -{ - pci_devices = kzalloc(sizeof(struct pci_device) * MAX_PCI_DEVICES, ALLOC_KERN); - pci_device_count = 0; - - for (int bus = 0; bus < 256; bus++) - pci_scan_bus(bus); - -#ifdef KDEBUG - /* Print PCI devices */ - for (int i = 0; i < pci_device_count; i++) { - struct pci_device *dev = &pci_devices[i]; - const char fmt[] = LOG_DEBUG "PCI device BUS[%d:%d] CLASS[%d:%d] vendor_id=%xh device_id=%xh, header_type=%d\n"; - - kprintf(fmt, dev->bus, dev->slot, dev->class, dev->subclass, dev->vendor_id, dev->device_id, dev->header_type); - } -#endif /* KDEBUG */ -} diff --git a/dev/pic.c b/dev/pic.c deleted file mode 100644 index 4ea5ddc..0000000 --- a/dev/pic.c +++ /dev/null @@ -1,40 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include -#include - -void pic_mask(uint8_t irq, uint8_t i) -{ - uint16_t port; - uint8_t val; - - i = !(!i); - - if (irq < 8) { - port = PIC1_DATA; - } else { - port = PIC2_DATA; - irq -= 8; - } - - val = inb(port) & ~(1 << irq); - val |= (i << irq); - - outb(port, val); -} - -void pic_eoi(uint8_t irq) -{ - if (irq > 8) - outb(PIC2_CMD, 0x20); - - outb(PIC1_CMD, 0x20); -} - -void pic_init() -{ - /* disable the PIC */ - outb(PIC1_DATA, 0xFF); - outb(PIC2_DATA, 0xFF); -} diff --git a/dev/serial.c b/dev/serial.c deleted file mode 100644 index 57e6590..0000000 --- a/dev/serial.c +++ /dev/null @@ -1,113 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include "fs/devfs.h" -#include "fs/vfs.h" -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -struct char_device *tty0; -ssize_t serial_write_dev(void *dev, void *buf, size_t offset, size_t count); -ssize_t serial_read_dev(void *dev, void *buf, size_t offset, size_t count); - -struct devfs_dev_info serial_dev_ops = { - .read = serial_read_dev, - .write = serial_write_dev, -}; - -int serial_init() -{ - outb(COM1 | 1, 0x00); - outb(COM1 | 3, 0x80); - outb(COM1 | 0, 0x01); - outb(COM1 | 1, 0x00); - outb(COM1 | 3, 0x03); - outb(COM1 | 2, 0xC7); - outb(COM1 | 4, 0x0B); - outb(COM1 | 4, 0x1E); - - outb(COM1 | 0, 0xAE); /* Enable loopback mode */ - if (inb(COM1 | 0) != 0xAE) { /* Loopback test */ - kprintf(LOG_WARN "Serial COM1 loopback test failed\n"); - return 1; - } - - outb(COM1 | 1, 0x01); /* Enable interrupts */ - outb(COM1 | 4, 0x0F); /* Enter normal operation */ - kprintf(LOG_SUCCESS "Serial COM1 initialized\n"); - - tty0 = char_device_create("tty0", ringbuf_create(1024)); - serial_dev_ops.dev = tty0; - - devfs_insert(NULL, "tty0", VFS_VNO_CHARDEV, &serial_dev_ops); - - /* register char device */ - return 0; -} - -inline void serial_putchar(char c) -{ - /* Wait for line to be clear */ - while ((inb(COM1 | 5) & 0x20) == 0) - ; - - outb(COM1, c); -} - -void serial_read_line() -{ - if ((inb(COM1 | 5) & 0x01) == 0) - return; - - char c = inb(COM1); - - ringbuf_write(tty0->data, &c, 1); -} - -void serial_trap() -{ - serial_read_line(); - lapic_eoi(); -} - -ssize_t serial_read(char *buf) -{ - ssize_t ret; - - char c; - - serial_read_line(); - - struct proc *proc = proc_find(getpid()); - - while ((ret = ringbuf_read(tty0->data, &c, 1)) == 0) { - sswtch(); - } - - copy_to_user(proc, buf, &c, 1); - - return ret; -} - -ssize_t serial_write(const char *buf, size_t count) -{ - for (size_t i = 0; i < count; i++) - serial_putchar(buf[i]); - return count; -} - -ssize_t serial_write_dev(void *dev, void *buf, size_t offset, size_t count) -{ - return serial_write(buf, count); -} - -ssize_t serial_read_dev(void *dev, void *buf, size_t offset, size_t count) -{ - return serial_read(buf); -} diff --git a/drivers/tty/tty.c b/drivers/tty/tty.c new file mode 100644 index 0000000..ad38201 --- /dev/null +++ b/drivers/tty/tty.c @@ -0,0 +1,58 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include +#include +#include +#include +#include + +static mem_cache_t *tty_slab; + +static struct tty_serial_ops arch_serial_ops = { .serial_getchar = arch_serial_read, .serial_putchar = arch_serial_write }; + +struct tty *tty_create(const char *name, dev_t serial_device) +{ + struct tty *tty = slab_alloc(tty_slab); + + dev_t tty_device = device_create(tty, DEV_CLASS_TTY, name); + + tty->dev = tty_device; + tty->serial_device = serial_device; + tty->serial_device_private = device_private_info(serial_device); + + switch (device_class(serial_device)) { + case DEV_CLASS_NATIVE_SERIAL: + tty->serial_ops = &arch_serial_ops; + break; + default: + kwarn("unknown serial device: %s", name); + break; + } + + return tty; +} + +void tty_putchar(struct tty *tty, char c) +{ + tty->serial_ops->serial_putchar(tty, c); +} + +char tty_getchar(struct tty *tty) +{ + return tty->serial_ops->serial_getchar(tty); +} + +void tty_write(struct tty *tty, const char *s) +{ + char c; + while ((c = *s++)) + tty_putchar(tty, c); +} + +void tty_layer_init() +{ + tty_slab = slab_create(sizeof(struct tty), 256 * KB, 8); + + if (!tty_slab) { + panic("tty_slab alloc failed\n"); + } +} diff --git a/drivers/tty/vt100.c b/drivers/tty/vt100.c new file mode 100644 index 0000000..8598a41 --- /dev/null +++ b/drivers/tty/vt100.c @@ -0,0 +1,87 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include +#include +#include + +void tty_send_dsr(struct tty *tty) +{ + tty_write(tty, "\033[6n"); +} + +void tty_set_origin_mode(struct tty *tty) +{ + tty_write(tty, "\033[?6h"); +} + +void tty_clear_screen(struct tty *tty) +{ + tty_write(tty, "\033[2J"); +} + +void tty_set_cursor_pos(struct tty *tty, int r, int c) +{ + if (r > 999) + r = 999; + if (c > 999) + c = 999; + + char str[12] = { 0 }; + snprintf(str, 11, "\033[%d;%dH", r, c); + tty_write(tty, str); +} + +void tty_get_cursor_pos(struct tty *tty, int *row, int *col) +{ + tty_send_dsr(tty); + + char c; + int n = 0; + + char ro[128] = { 0 }; + char co[128] = { 0 }; + + bool sem = false; + bool begin = false; + + while ((c = tty_getchar(tty))) { + if (c == '\033') + continue; + + if (c == ';') { + sem = true; + n = 0; + } + + if (!begin) { + if (c == '[') + begin = true; + continue; + } + + if (c >= '0' && c <= '9') { + if (!sem) + ro[n] = c; + else + co[n] = c; + + n++; + } + + if (c == 'R') + break; + } + + *row = atoi(ro); + *col = atoi(co); +} + +void tty_get_size(struct tty *tty, int *rows, int *cols) +{ + tty_set_cursor_pos(tty, 999, 999); + tty_get_cursor_pos(tty, rows, cols); +} + +void tty_setlf(struct tty *tty) +{ + tty_write(tty, "\033[20l"); +} diff --git a/fs/devfs.c b/fs/devfs.c deleted file mode 100644 index 2d49410..0000000 --- a/fs/devfs.c +++ /dev/null @@ -1,130 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include -#include -#include - -static struct fs *devfs; - -static int devfs_read(struct vnode *vnode, void *buf, size_t offset, size_t size) -{ - if (!vnode->priv_data) - return -EINVAL; - struct devfs_dev_info *ops = vnode->priv_data; - return ops->read(vnode->priv_data, buf, offset, size); -} - -static int devfs_write(struct vnode *vnode, void *buf, size_t offset, size_t size) -{ - if (!vnode->priv_data) - return -EINVAL; - struct devfs_dev_info *ops = vnode->priv_data; - return ops->write(vnode->priv_data, buf, offset, size); -} - -/* devfs does not support unlink */ -static int devfs_unlink(struct vnode *parent, const char *path) -{ - return -EINVAL; -} - -/* vnodes are permanent and therefore these functions should never be called */ -static int devfs_open_vno(struct fs *fs, struct vnode *out, ino_t ino_num) -{ - return -EINVAL; -} - -static int devfs_readdir(struct vnode *vnode, struct dirent **dir) -{ - return -EINVAL; -} - -static int devfs_open_dir(struct fs *fs, struct vnode *out) -{ - return -EINVAL; -} - -int devfs_insert(struct vnode *dir, const char *name, uint32_t flags, struct devfs_dev_info *ops) -{ - if (!name || !ops) - return -EINVAL; - - if (!dir) - dir = devfs->root; - - struct vnode *dev_vnode = vfs_create_vno(); - if (!dev_vnode) - return -ENOMEM; - - dev_vnode->fs = dir->fs; - dev_vnode->flags = flags; - dev_vnode->no_free = true; - dev_vnode->priv_data = ops; - - spinlock_acquire(&dir->lock); - - dir->num_dirents++; - dir->dirents = krealloc(dir->dirents, dir->num_dirents * sizeof(struct dirent), ALLOC_KERN); - - struct dirent *dirent = &dir->dirents[dir->num_dirents - 1]; - - memcpy(dirent->name, name, MIN(sizeof(dirent->name) - 1, strlen(name) + 1)); - dirent->name[MIN(sizeof(dirent->name) - 1, strlen(name))] = '\0'; - dirent->vnode = dev_vnode; - dirent->reclen = sizeof(struct dirent); - dirent->inode = 0; - - spinlock_release(&dir->lock); - - return 0; -} - -struct fs *devfs_init() -{ - devfs = vfs_create(); - if (!devfs) - goto out; - - devfs->ops->read = devfs_read; - devfs->ops->write = devfs_write; - devfs->ops->unlink = devfs_unlink; - devfs->ops->open_vno = devfs_open_vno; - - devfs->root->flags = VFS_VNO_DIR; - devfs->root->fs = devfs; - - int res = vfs_mount(devfs, "dev"); - - if (res < 0) { - kprintf(LOG_ERROR "devfs: failed to mount devfs: %s\n", strerror(-res)); - goto out; - } - - /* get all block devices */ - struct block_device **block_get_all_devices(int *n); - - int n; - struct block_device **bdevs = block_get_all_devices(&n); - - if (n > 0) { - for (int i = 0; i < n; i++) { - struct devfs_dev_info *block_dev_info = kmalloc(sizeof(struct devfs_dev_info), ALLOC_KERN); - if (!block_dev_info) - goto out; - - block_dev_info->dev = &bdevs[i]; - block_dev_info->read = (void *)block_read; - block_dev_info->write = (void *)block_write; - - devfs_insert(devfs->root, bdevs[i]->name, VFS_VNO_BLKDEV, block_dev_info); - } - } - - return devfs; -out: - kprintf(LOG_ERROR "devfs: failed to mount devfs\n"); - panic(); - - return NULL; /* cannot possibly happen */ -} diff --git a/fs/ext2.c b/fs/ext2.c deleted file mode 100644 index 4062728..0000000 --- a/fs/ext2.c +++ /dev/null @@ -1,1061 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include - -#include -#include - -#define N_DIRECT 12 -#define N_INDIR (fs->block_size / sizeof(uint32_t)) -#define N_DINDIR (N_INDIR * N_INDIR) -#define N_TINDIR (N_DINDIR * N_INDIR + N_DINDIR + N_INDIR) -#define N_PER_INDIRECT (fs->block_size / sizeof(uint32_t)) - -#define ITYPE_DECL(_ino, _de) [(_ino >> 12)] = (_de) -#define DTYPE_DECL(_de, _ino) [(_de)] = (_ino) - -struct ext2_block_index { - uint32_t n_indirs; - uint32_t indices[4]; -}; - -static struct fs_ops *ext2_ops; - -static uint8_t inode_to_ftype[] = { - ITYPE_DECL(EXT2_INO_FIFO, EXT2_DE_FIFO), ITYPE_DECL(EXT2_INO_CHARDEV, EXT2_DE_CHRDEV), - ITYPE_DECL(EXT2_INO_DIR, EXT2_DE_DIR), ITYPE_DECL(EXT2_INO_BLKDEV, EXT2_DE_BLKDEV), - ITYPE_DECL(EXT2_INO_REG, EXT2_DE_FILE), ITYPE_DECL(EXT2_INO_SYMLINK, EXT2_DE_SYMLINK), - ITYPE_DECL(EXT2_INO_SOCK, EXT2_DE_SOCK), -}; - -#undef ITYPE_DECL -#undef DTYPE_DECL - -/* Base ext2 operations: - * ----------------------------------------------------------------------------- - * Superblock - * R/W block - * BGDT_write - * ----------------------------------------------------------------------------- - */ -static int ext2_read_super(struct block_device *bdev, struct ext2_superblock *sb_struct) -{ - char *buf = kmalloc(1024, ALLOC_DMA); - if (!buf) - return -ENOMEM; - -#ifdef KDEBUG - kprintf(LOG_DEBUG "Reading superblock from device %s, start_lba: %X\n", bdev->name, bdev->lba_start); -#endif - - int ret = block_read(bdev, buf, 2, 2); - if (ret < 0) { - kfree(buf); - return ret; - } - - struct ext2_superblock *sb = (struct ext2_superblock *)buf; - if (sb->magic != EXT2_SUPER_MAGIC) { - kfree(buf); - return -EINVAL; - } - - memcpy(sb_struct, buf, sizeof(*sb_struct)); - kfree(buf); - - return ret; -} - -/* PCD must be 1 for buf */ -static int ext2_read_block(struct ext2fs *fs, void *buf, size_t block) -{ - uint32_t bdev_block_size = fs->bdev->block_size; - uint32_t num_blocks_read = fs->block_size / bdev_block_size; - - uint32_t bdev_block = block * num_blocks_read; - - return block_read(fs->bdev, buf, bdev_block, num_blocks_read); -} - -static int ext2_write_block(struct ext2fs *fs, void *buf, size_t block) -{ - uint32_t bdev_block_size = fs->bdev->block_size; - uint32_t num_blocks_read = fs->block_size / bdev_block_size; - - uint32_t bdev_block = block * num_blocks_read; - - return block_write(fs->bdev, buf, bdev_block, num_blocks_read); -} - -static int ext2_write_super(struct ext2fs *fs) -{ - return ext2_write_block(fs, &fs->sb, 1); -} - -static int ext2_write_bgdt(struct ext2fs *fs) -{ - for (size_t i = 0; i < fs->bgdt_num_blocks; i++) { - void *buf = (void *)fs->bgdt + fs->block_size * i; - int ret = ext2_write_block(fs, buf, fs->bgdt_blockno + i); - if (ret < 0) - return ret; - } - - return 0; -} - -static long ext2_find_free_block(struct ext2fs *fs, size_t block_group) -{ - struct ext2_group_desc *bg = &fs->bgdt[block_group]; - - if (!bg->free_blocks_count) - return -ENOSPC; - - uint32_t block = bg->block_bitmap; - uint32_t block_offset = 0; - - char *buf = kmalloc(fs->block_size, ALLOC_DMA); - if (!buf) - return -ENOMEM; - - ext2_read_block(fs, buf, block); - - uint8_t *byte; - while (block_offset < fs->block_size) { - byte = (uint8_t *)buf + block_offset; - if (*byte == 0xFF) { - block_offset += 8; - } else { - break; - } - } - int j; - for (j = 0; j < 8; j++) { - if (!(*byte & (1 << j))) - break; - } - - *byte |= (1 << j); - bg->free_blocks_count--; - fs->sb.free_blocks_count--; - - ext2_write_block(fs, buf, block); - - /* update superblock and bgdt */ - ext2_write_super(fs); - ext2_write_bgdt(fs); - - kfree(buf); - - uint32_t block_ret_no = (block_group * fs->sb.blocks_per_group) + (block_offset * 8) + j + 1; - - /* zero out the block */ - char *block_buf = kmalloc(fs->block_size, ALLOC_DMA); - if (!block_buf) - return -ENOMEM; - - memset(block_buf, 0, fs->block_size); - ext2_write_block(fs, block_buf, block_ret_no); - kfree(block_buf); - - return block_ret_no; -} - -static long ext2_alloc_block(struct ext2fs *fs) -{ - uint32_t num_groups = fs->sb.blocks_count / fs->sb.blocks_per_group; - if (fs->sb.blocks_count % fs->sb.blocks_per_group) - num_groups++; - - spinlock_acquire(&fs->lock); - for (int i = 0; i < num_groups; i++) { - long ret = ext2_find_free_block(fs, i); - if (ret >= 0) - return ret; - } - spinlock_release(&fs->lock); - - return -ENOSPC; -} - -static long ext2_free_block(struct ext2fs *fs, uint32_t block) -{ - uint32_t block_group = (block - 1) / fs->sb.blocks_per_group; - uint32_t block_offset = (block - 1) % fs->sb.blocks_per_group; - - struct ext2_group_desc *bg = &fs->bgdt[block_group]; - - uint32_t block_bitmap_block = bg->block_bitmap; - uint32_t block_bitmap_offset = block_offset >> 3; - - char *buf = kmalloc(fs->block_size, ALLOC_DMA); - if (!buf) - return -ENOMEM; - - spinlock_acquire(&fs->lock); - ext2_read_block(fs, buf, block_bitmap_block); - - uint8_t *byte = (uint8_t *)buf + block_bitmap_offset; - *byte &= ~(1 << (block_offset & 7)); - bg->free_blocks_count++; - fs->sb.free_blocks_count++; - ext2_write_block(fs, buf, block_bitmap_block); - - ext2_write_super(fs); - ext2_write_bgdt(fs); - - spinlock_release(&fs->lock); - - kfree(buf); - return 0; -} - -/* inode operations: - * ----------------------------------------------------------------------------- - * alloc inode - * free inode - * R/W inode - * Get block index (helper) - * Get block number (helper) - * - * inode block operations: - * ext2_ino_read_block - * ext2_ino_write_block - * - * ext2_dno_find (helper) - * ext2_ino_find_by_name: search for a file by name - * ----------------------------------------------------------------------------- - */ -static long ext2_alloc_inode(struct ext2fs *fs, struct ext2_inode *out) -{ - uint32_t num_groups = fs->sb.blocks_count / fs->sb.blocks_per_group; - if (fs->sb.blocks_count % fs->sb.blocks_per_group) - num_groups++; - - for (size_t i = 0; i < num_groups; i++) { - struct ext2_group_desc *bg = &fs->bgdt[i]; - - if (!bg->free_inodes_count) - continue; - - uint32_t block = bg->inode_bitmap; - uint32_t block_offset = 0; - - char *buf = kmalloc(fs->block_size, ALLOC_DMA); - if (!buf) - return -ENOMEM; - - ext2_read_block(fs, buf, block); - - spinlock_acquire(&fs->lock); - uint8_t *byte; - while (block_offset < fs->block_size) { - byte = (uint8_t *)buf + block_offset; - if (*byte == 0xFF) - block_offset += 8; - else - break; - } - int j; - for (j = 0; j < 8; j++) { - if (!(*byte & (1 << j))) - break; - } - - *byte |= (1 << j); - bg->free_inodes_count--; - fs->sb.free_inodes_count--; - - ext2_write_block(fs, buf, block); - - /* update superblock and bgdt */ - ext2_write_super(fs); - ext2_write_bgdt(fs); - - kfree(buf); - spinlock_release(&fs->lock); - - uint32_t inode_no = (i * fs->sb.inodes_per_group) + (block_offset << 3) + j + 1; - return inode_no; - } - - return -ENOSPC; -} - -static int ext2_free_inode(struct ext2fs *fs, ino_t inode) -{ - uint32_t group = (inode - 1) / fs->sb.inodes_per_group; - uint32_t index = (inode - 1) % fs->sb.inodes_per_group; - - struct ext2_group_desc *bg = &fs->bgdt[group]; - - uint32_t block = bg->inode_bitmap; - uint32_t offset = index >> 3; - - char *buf = kmalloc(fs->block_size, ALLOC_DMA); - if (!buf) - return -ENOMEM; - - ext2_read_block(fs, buf, block); - - spinlock_acquire(&fs->lock); - uint8_t *byte = (uint8_t *)buf + offset; - *byte &= ~(1 << (index & 7)); - bg->free_inodes_count++; - fs->sb.free_inodes_count++; - ext2_write_block(fs, buf, block); - - ext2_write_super(fs); - ext2_write_bgdt(fs); - - spinlock_release(&fs->lock); - - kfree(buf); - return 0; -} - -static int ext2_read_inode(struct ext2fs *fs, struct ext2_inode *out, ino_t inode) -{ - uint32_t group = (inode - 1) / fs->sb.inodes_per_group; - uint32_t index = (inode - 1) % fs->sb.inodes_per_group; - - struct ext2_group_desc *bg = &fs->bgdt[group]; - - uint32_t block = bg->inode_table + (index * sizeof(struct ext2_inode)) / fs->block_size; - uint32_t offset = (index * sizeof(struct ext2_inode)) % fs->block_size; - - char *buf = kmalloc(fs->block_size, ALLOC_DMA); - if (!buf) - return -ENOMEM; - - int ret = ext2_read_block(fs, buf, block); - if (ret < 0) { - kfree(buf); - return ret; - } - - memcpy(out, buf + offset, sizeof(struct ext2_inode)); - kfree(buf); - - return 0; -} - -static int ext2_write_inode(struct ext2fs *fs, struct ext2_inode *in, ino_t inode) -{ - uint32_t group = (inode - 1) / fs->sb.inodes_per_group; - uint32_t index = (inode - 1) % fs->sb.inodes_per_group; - - struct ext2_group_desc *bg = &fs->bgdt[group]; - - uint32_t block = bg->inode_table + (index * sizeof(struct ext2_inode)) / fs->block_size; - uint32_t offset = (index * sizeof(struct ext2_inode)) % fs->block_size; - - char *buf = kmalloc(fs->block_size, ALLOC_DMA); - if (!buf) - return -ENOMEM; - - int ret = ext2_read_block(fs, buf, block); - if (ret < 0) { - kfree(buf); - return ret; - } - - memcpy(buf + offset, in, sizeof(struct ext2_inode)); - - ret = ext2_write_block(fs, buf, block); - if (ret < 0) { - kfree(buf); - return ret; - } - - kfree(buf); - - return 0; -} - -static void ext2_get_block_idx(struct ext2fs *fs, struct ext2_block_index *ret, uint32_t block) -{ - const uint32_t limit_direct = N_DIRECT; - const uint32_t limit_indirect = limit_direct + N_INDIR; - const uint32_t limit_dindirect = limit_indirect + N_DINDIR; - const uint32_t limit = limit_dindirect + N_TINDIR; - - if (block < N_DIRECT) { - ret->n_indirs = 0; - ret->indices[0] = block; - } else if (block < limit_indirect) { - ret->n_indirs = 1; - ret->indices[0] = N_DIRECT; - ret->indices[1] = block - N_DIRECT; - } else if (block < limit_dindirect) { - ret->n_indirs = 2; - ret->indices[0] = N_DIRECT + 1; - ret->indices[1] = (block - (N_DIRECT)) / N_PER_INDIRECT; - ret->indices[2] = (block - (N_DIRECT)) % N_PER_INDIRECT; - } else if (block < limit) { - ret->n_indirs = 3; - /* tindir block */ - ret->indices[0] = N_DIRECT + 2; - ret->indices[1] = (block - (N_DIRECT + N_DINDIR)) / N_PER_INDIRECT / N_PER_INDIRECT; - ret->indices[2] = (block - (N_DIRECT + N_DINDIR)) / N_PER_INDIRECT % N_PER_INDIRECT; - ret->indices[3] = (block - (N_DIRECT + N_DINDIR)) % N_PER_INDIRECT; - } else { - ret->n_indirs = -1; - } -} - -static long ext2_ino_get_blocknum(struct ext2fs *fs, struct ext2_inode *ino, uint32_t ino_blocknum, bool alloc) -{ - const uint32_t limit_direct = N_DIRECT; - const uint32_t limit_indirect = limit_direct + N_INDIR; - const uint32_t limit_dindirect = limit_indirect + N_DINDIR; - const uint32_t limit = limit_dindirect + N_TINDIR; - - struct ext2_block_index idx; - ext2_get_block_idx(fs, &idx, ino_blocknum); - - if (idx.n_indirs == -1) - return -EINVAL; - - long ret; - long last = 0; - - ret = ino->block[idx.indices[0]]; - if (ret == 0) { - if (!alloc) - return -ENOENT; - - ret = ext2_alloc_block(fs); - if (ret < 0) - return ret; - - ino->block[idx.indices[0]] = ret; - } - - for (int i = 1; i <= idx.n_indirs; i++) { - last = ret; - uint32_t *buf = kmalloc(fs->block_size, ALLOC_DMA); - if (!buf) - return -ENOMEM; - - ext2_read_block(fs, buf, last); - - ret = buf[idx.indices[i]]; - - if (ret == 0) { - if (!alloc) { - kfree(buf); - return -ENOENT; - } - - ret = ext2_alloc_block(fs); - if (ret < 0) { - kfree(buf); - return ret; - } - - buf[idx.indices[i]] = ret; - ext2_write_block(fs, buf, last); - - kfree(buf); - } - } - - return ret; -} - -static long ext2_ino_read_block(struct ext2fs *fs, struct ext2_inode *ino, void *buf, uint32_t ino_blocknum) -{ - long ret = ext2_ino_get_blocknum(fs, ino, ino_blocknum, false); - if (ret < 0) - return ret; - - ext2_read_block(fs, buf, ret); - return 0; -} - -static long ext2_ino_write_block(struct ext2fs *fs, struct ext2_inode *ino, void *buf, uint32_t ino_blocknum) -{ - long ret = ext2_ino_get_blocknum(fs, ino, ino_blocknum, true); - if (ret < 0) - return ret; - - ext2_write_block(fs, buf, ret); - return 0; -} - -static long ext2_dno_find(struct ext2fs *fs, struct ext2_inode *ino, char *name) -{ - size_t n_blocks = ino->size; - if (n_blocks % fs->block_size) - n_blocks += fs->block_size; - n_blocks /= fs->block_size; - - struct ext2_dir_entry *entry = kmalloc(fs->block_size * n_blocks, ALLOC_DMA); - char *entry_buf = (char *)entry; - if (!entry) - return -ENOMEM; - - size_t ino_num_blocks = (ino->blocks * fs->bdev->block_size) / fs->block_size; - - uint32_t rec_offset = 0; - for (int i = 0; i < ino_num_blocks; i++) { - /* since this ino is a directory, we just read the blocks - * sequentially until we find the file we're looking for - */ - - long ret = ext2_ino_read_block(fs, ino, entry_buf + fs->block_size * i, i); - - if (ret < 0) { - kfree(entry); - return ret; - } - } - - while (entry->inode && rec_offset < fs->block_size * n_blocks) { - size_t name_len = strlen(name); - int res = strncmp(entry->name, name, MIN(entry->name_len, name_len)); - - if (!res && (name_len == entry->name_len || name_len == 0)) { - kfree(entry); - return entry->inode; - } - } - - kfree(entry); - return -ENOENT; -} - -static long ext2_ino_find_by_name(struct ext2fs *fs, const char *path) -{ - struct ext2_inode *inode = kmalloc(sizeof(struct ext2_inode), ALLOC_DMA); - - ino_t inode_no = 2; - int ret = ext2_read_inode(fs, inode, inode_no); - if (ret < 0) { - kfree(inode); - return ret; - } - - char *path_copy = kzalloc(strlen(path) + 1, ALLOC_KERN); - if (!path_copy) { - kfree(inode); - return -ENOMEM; - } - - strcpy(path_copy, path); - - char *strtok_last = NULL; - char *token = strtok(path_copy, "/", &strtok_last); - - while (token) { - /* inode blocks value is number of BDEV blocks, not EXT2 blocks. so we convert it */ - - ret = ext2_dno_find(fs, inode, token); - if (ret < 0) { - break; - } - - ext2_read_inode(fs, inode, ret); - token = strtok(NULL, "/", &strtok_last); - } - - kfree(path_copy); - kfree(inode); - - return ret; -} - -static int ext2_ino_add_dirent(struct ext2fs *fs, struct ext2_inode *ino, const char *name, ino_t ino_num, uint8_t type) -{ - size_t n_blocks = ino->size; - if (n_blocks % fs->block_size) - n_blocks += fs->block_size; - n_blocks /= fs->block_size; - - struct ext2_dir_entry *entry = kzalloc(fs->block_size * n_blocks, ALLOC_DMA); - if (!entry) - return -ENOMEM; - - size_t this_len = sizeof(struct ext2_dir_entry) + strlen(name); - - /* read all entries */ - size_t offset = 0; - for (int i = 0; i < n_blocks; i++) { - long ret = ext2_ino_read_block(fs, ino, entry + offset, i); - if (ret < 0) { - kfree(entry); - return ret; - } - - offset += fs->block_size; - } - - offset = 0; - struct ext2_dir_entry *cur = entry; - while (cur->inode && offset < fs->block_size * n_blocks) { - cur = (struct ext2_dir_entry *)((char *)entry + offset); - if (!cur->inode && cur->rec_len <= this_len) - break; - offset += cur->rec_len; - } - - if (offset + strlen(name) + sizeof(struct ext2_dir_entry) >= fs->block_size * n_blocks) { - /* easier to do it this way */ - entry = krealloc(entry, (n_blocks + 1) * fs->block_size, ALLOC_DMA); - memset(entry + n_blocks * fs->block_size, 0, fs->block_size); - /* this adds a new block */ - ext2_ino_write_block(fs, ino, ((char *)entry) + n_blocks, n_blocks); - ino->size += fs->block_size; - n_blocks++; - } - - cur->inode = ino_num; - cur->name_len = strlen(name); - cur->rec_len = fs->block_size - offset; - cur->file_type = type; - memcpy(cur->name, name, cur->name_len); - - uint32_t starting_block = offset / fs->block_size; - for (int i = starting_block; i < n_blocks; i++) { - ext2_ino_write_block(fs, ino, ((char *)entry) + i * fs->block_size, i); - } - - kfree(entry); - - return 0; -} - -static int ext2_ino_del_dirent(struct ext2fs *fs, struct ext2_inode *ino, const char *name) -{ - size_t n_blocks = ino->size; - if (n_blocks % fs->block_size) - n_blocks += fs->block_size; - n_blocks /= fs->block_size; - - struct ext2_dir_entry *entry = kmalloc(fs->block_size * n_blocks, ALLOC_DMA); - if (!entry) - return -ENOMEM; - - /* read all entries */ - - size_t offset = 0; - for (int i = 0; i < n_blocks; i++) { - long ret = ext2_ino_read_block(fs, ino, entry + offset, i); - if (ret < 0) { - kfree(entry); - return ret; - } - - offset += fs->block_size; - } - - /* find the dirent */ - offset = 0; - struct ext2_dir_entry *cur = NULL; - struct ext2_dir_entry *prev = NULL; - - spinlock_acquire(&fs->lock); - while (cur && offset < fs->block_size * n_blocks && cur->inode) { - cur = (struct ext2_dir_entry *)((char *)entry + offset); - - /* check if the name matches */ - if (!strncmp(cur->name, name, cur->name_len)) { - /* remove the dirent */ - cur->inode = 0; - cur->name_len = 0; - cur->file_type = 0; - memset(cur->name, 0, cur->name_len); - - /* update the previous dirent */ - if (prev) { - /* if there is a previous dirent, we need to update the rec_len */ - prev->rec_len += cur->rec_len; - cur->rec_len = 0; - } else { - /* if there is no previous dirent, we need to update the first dirent */ - struct ext2_dir_entry *next = (struct ext2_dir_entry *)((char *)cur + cur->rec_len); - next->rec_len += cur->rec_len; - - if (next->inode == 0) - cur->rec_len = n_blocks * fs->block_size - offset; - } - - /* write all the blocks */ - uint32_t starting_block = offset / fs->block_size; - for (int i = starting_block; i < n_blocks; i++) - ext2_ino_write_block(fs, ino, ((char *)entry) + i * fs->block_size, i); - - spinlock_release(&fs->lock); - return 0; - } - - prev = cur; - offset += cur->rec_len; - } - - spinlock_release(&fs->lock); - return -ENOENT; -} - -static int ino_type_to_dent(uint32_t ino_flags) -{ - /* convert from ext2 inode type to dirent type */ - switch (ino_flags & 0xF000) { - case EXT2_INO_REG: - return EXT2_DE_FILE; - case EXT2_INO_DIR: - return EXT2_DE_DIR; - case EXT2_INO_CHARDEV: - return EXT2_DE_CHRDEV; - case EXT2_INO_BLKDEV: - return EXT2_DE_BLKDEV; - case EXT2_INO_FIFO: - return EXT2_DE_FIFO; - case EXT2_INO_SOCK: - return EXT2_DE_SOCK; - case EXT2_INO_SYMLINK: - return EXT2_DE_SYMLINK; - } - - return -1; -} - -/* VFS operations: - * ----------------------------------------------------------------------------- - * read dirs (helper) - * open vno - * read file - * write file - * unlink - * mkdir - * creat - * ----------------------------------------------------------------------------- - */ - -static long ext2_vno_read_dirs(struct ext2fs *fs, struct ext2_inode *inode, struct vnode *out) -{ - size_t n_blocks = inode->size; - if (n_blocks % fs->block_size) - n_blocks += fs->block_size; - n_blocks /= fs->block_size; - - void *entry_buf = kmalloc(fs->block_size * n_blocks, ALLOC_DMA); - if (!entry_buf) - return -ENOMEM; - - /* read the directory entries */ - for (int i = 0; i < n_blocks; i++) { - long ret = ext2_ino_read_block(fs, inode, entry_buf + fs->block_size * i, i); - if (ret < 0) { - kfree(entry_buf); - return ret; - } - } - - void *oe = entry_buf; - size_t offset = 0; - - while (offset < fs->block_size * n_blocks) { - struct ext2_dir_entry *entry = (struct ext2_dir_entry *)((char *)entry_buf + offset); - struct dirent dentry = { 0 }; - - if (entry->inode == 0 || entry->name_len == 0) { - break; - } - - memcpy(&dentry.name, entry->name, entry->name_len); - dentry.name[entry->name_len] = '\0'; - dentry.inode = entry->inode; - dentry.type = entry->file_type; - - /* insert into dirents linked list */ - out->dirents = krealloc(out->dirents, (out->num_dirents + 1) * sizeof(struct dirent), ALLOC_KERN); - if (!out->dirents) { - kfree(oe); - return -ENOMEM; - } - - memcpy(&out->dirents[out->num_dirents], &dentry, sizeof(struct dirent)); - - out->num_dirents++; - offset += entry->rec_len; - } - - kfree(entry_buf); - - return 0; -} - -static int ext2_open_vno(struct fs *vfs, struct vnode *out, ino_t ino_num) -{ - struct ext2fs *fs = (struct ext2fs *)vfs->fs; - struct ext2_inode inode; - - int res = ext2_read_inode(fs, &inode, ino_num); - if (res < 0) - return res; - - out->flags = inode.mode; - out->uid = inode.uid; - out->gid = inode.gid; - out->size = inode.size; - out->ino_num = ino_num; - - out->fs = vfs; - - /* Init to NULL, allow vfs to fill in */ - out->ptr = NULL; - out->next = NULL; - - if (inode.mode & EXT2_INO_DIR) { - /* read the directory entries */ - if ((res = ext2_vno_read_dirs(fs, &inode, out)) < 0) - return res; - } - - return 0; -} - -static int ext2_read_file(struct vnode *vnode, void *buf, size_t offset, size_t size) -{ - struct fs *fs = vnode->fs; - struct ext2fs *extfs = (struct ext2fs *)fs->fs; - - struct ext2_inode inode; - int res = ext2_read_inode(extfs, &inode, vnode->ino_num); - if (res < 0) - return res; - - if (offset > inode.size) - return -EINVAL; - - if (offset + size > inode.size) - size = inode.size - offset; - - size_t first_block = offset / extfs->block_size; - size_t last_block = (offset + size) / extfs->block_size; - size_t n_blocks_read = (last_block - first_block) + 1; - - char *block_buf = kmalloc(n_blocks_read * extfs->block_size, ALLOC_DMA); - if (!block_buf) - return -ENOMEM; - - for (size_t i = first_block; i <= last_block; i++) { - long ret = ext2_ino_read_block(extfs, &inode, block_buf + (i * extfs->block_size), i); - if (ret < 0) { - kfree(block_buf); - return ret; - } - } - - memcpy(buf, block_buf + (offset % extfs->block_size), size); - kfree(block_buf); - - return size; -} - -static int ext2_write_file(struct vnode *vnode, void *buf, size_t offset, size_t size) -{ - struct fs *fs = vnode->fs; - struct ext2fs *extfs = (struct ext2fs *)fs->fs; - - struct ext2_inode inode; - int res = ext2_read_inode(extfs, &inode, vnode->ino_num); - if (res < 0) - return res; - - if (offset + size > inode.size) - inode.size = offset + size; - - size_t first_block = offset / extfs->block_size; - size_t last_block = (offset + size) / extfs->block_size; - size_t n_blocks_read = (last_block - first_block) + 1; - - char *block_buf = kzalloc(n_blocks_read * extfs->block_size, ALLOC_DMA); - if (!block_buf) - return -ENOMEM; - - for (size_t i = first_block; i <= last_block; i++) { - long ret = ext2_ino_read_block(extfs, &inode, block_buf + (i * extfs->block_size), i); - if (ret < 0 && ret != -ENOENT) { - kfree(block_buf); - return ret; - } - } - - size_t start_offset = offset % extfs->block_size; - memcpy(block_buf + start_offset, buf, size); - - for (size_t i = first_block; i <= last_block; i++) { - long ret = ext2_ino_write_block(extfs, &inode, block_buf + (i * extfs->block_size), i); - if (ret < 0) { - kfree(block_buf); - return ret; - } - } - - kfree(block_buf); - - return size; -} - -static int ext2_unlink_file(struct vnode *parent, const char *name) -{ - struct fs *fs = parent->fs; - struct ext2fs *extfs = (struct ext2fs *)fs->fs; - - char *name_cpy = kzalloc(strlen(name) + 1, ALLOC_KERN); - if (!name_cpy) - return -ENOMEM; - - strcpy(name_cpy, name); - - struct ext2_inode inode; - int res = ext2_read_inode(extfs, &inode, parent->ino_num); - if (res < 0) - return res; - - res = ext2_ino_del_dirent(extfs, &inode, name_cpy); - if (res < 0) - return res; - - return 0; -} - -static int ext2_create_file(struct vnode *parent, const char *name, mode_t mode) -{ - struct fs *fs = parent->fs; - struct ext2fs *extfs = (struct ext2fs *)fs->fs; - - char *name_cpy = kzalloc(strlen(name) + 1, ALLOC_KERN); - if (!name_cpy) - return -ENOMEM; - - strcpy(name_cpy, name); - - struct ext2_inode inode; - int res = ext2_read_inode(extfs, &inode, parent->ino_num); - if (res < 0) - return res; - - /* check if file already exists */ - long ret = ext2_dno_find(extfs, &inode, name_cpy); - if (ret >= 0) - return -EEXIST; - - /* allocate inode */ - ret = ext2_alloc_inode(extfs, &inode); - if (ret < 0) - return ret; - - struct ext2_inode inode_new = { 0 }; - /* notably we do no mode conversion since ext2 is the same as the kernel vfs */ - inode_new.mode = mode; - inode_new.uid = 0; - inode_new.gid = 0; - inode_new.size = 0; - inode_new.blocks = 0; - - /* write inode */ - res = ext2_write_inode(extfs, &inode_new, ret); - - if (res < 0) - return res; - - /* write directory entry */ - res = ext2_ino_add_dirent(extfs, &inode, name_cpy, ret, ino_type_to_dent(mode)); - if (res < 0) - return res; - - return 0; -} - -struct fs *ext2_init_fs(struct block_device *bdev) -{ - struct ext2fs *extfs = kmalloc(sizeof(*extfs), ALLOC_KERN); - - if (!extfs) - return NULL; - - if (ext2_read_super(bdev, &extfs->sb) < 0) { - kfree(extfs); - return NULL; - } - - extfs->bdev = bdev; - extfs->block_size = 1024 << extfs->sb.log_block_size; - extfs->indir_block_size = extfs->block_size / sizeof(uint32_t); - - bdev->fs = extfs; - - /* read block group descriptor table */ - uint32_t num_groups = extfs->sb.blocks_count / extfs->sb.blocks_per_group; - if (extfs->sb.blocks_count % extfs->sb.blocks_per_group) - num_groups++; - - uint32_t bgdt_block = 2 + (extfs->sb.first_data_block / extfs->sb.blocks_per_group); - uint32_t bgdt_size = num_groups * sizeof(struct ext2_group_desc); - - char *buf = kmalloc(bgdt_size, ALLOC_DMA); - - ext2_read_block(bdev->fs, buf, bgdt_block); - - extfs->bgdt = (struct ext2_group_desc *)kmalloc(bgdt_size, ALLOC_KERN); - extfs->bgdt_blockno = bgdt_block; - extfs->bgdt_num_blocks = npow2(bgdt_size) / extfs->block_size; - memcpy(extfs->bgdt, buf, bgdt_size); - - kfree(buf); - - struct fs *ret = vfs_create(); - ret->fs = extfs; - ret->type = VFS_TYPE_EXT2; - - ext2_ops = kmalloc(sizeof(struct fs_ops), ALLOC_KERN); - - if (!ext2_ops) - goto out; - - ext2_ops->open_vno = ext2_open_vno; - ext2_ops->read = ext2_read_file; - ext2_ops->write = ext2_write_file; - ext2_ops->creat = ext2_create_file; - ext2_ops->unlink = ext2_unlink_file; - - ret->ops = ext2_ops; - - struct ext2_inode *root_inode = kmalloc(sizeof(struct ext2_inode), ALLOC_DMA); - if (!root_inode) - goto out_2; - - ext2_read_inode(ret->fs, root_inode, EXT2_ROOT_INO); - - ret->root = vfs_create_vno(); - if (!ret->root) - goto out_3; - - ret->root->name[0] = '/'; - ret->root->fs = ret; - ret->root->size = root_inode->size; - ret->root->uid = root_inode->uid; - ret->root->gid = root_inode->gid; - ret->root->flags = root_inode->mode; - ret->root->ino_num = EXT2_ROOT_INO; - ret->root->no_free = true; - - ext2_vno_read_dirs(extfs, root_inode, ret->root); - - return ret; - -out_3: - kfree(ret); - kfree(root_inode); -out_2: - kfree(ext2_ops); -out: - kfree(extfs->bgdt); - kfree(extfs); - - return NULL; -} diff --git a/fs/gpt.c b/fs/gpt.c deleted file mode 100644 index 7199495..0000000 --- a/fs/gpt.c +++ /dev/null @@ -1,88 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include - -#include - -#define GPT_HEADER_SIGNATURE 0x5452415020494645ull /* "EFI PART" */ - -void block_gpt_init(struct block_device *dev) -{ - size_t block_size = dev->block_size; - - /* Verify that this is a GPT partition table */ - struct gpt_header *header = kmalloc(block_size, ALLOC_DMA); - if (!header) - return; - - struct gpt_entry *entries = kmalloc(block_size, ALLOC_DMA); - if (!entries) - goto free_header; - - if (block_read(dev, header, 1, 1)) { - kprintf(LOG_ERROR "Failed to read GPT header for device %s\n", dev->name); - goto free_entries; - } - - if (header->signature != GPT_HEADER_SIGNATURE) { - kprintf(LOG_ERROR "Invalid GPT header signature for device %s\n", dev->name); - goto free_entries; - } - - if (header->entry_size != sizeof(struct gpt_entry)) { - kprintf(LOG_ERROR "Invalid GPT entry size for device %s\n", dev->name); - goto free_entries; - } - - if (block_read(dev, entries, header->lba_table, 1)) { - kprintf(LOG_ERROR "Failed to read GPT entries for device %s\n", dev->name); - goto free_entries; - } - - /* Parse the GPT entries and create block devices for each partition - * that is found. - */ - size_t used_count = 0; - struct block_device **list = &dev->next_part; - for (size_t i = 0; i < header->entry_count; i++) { - struct gpt_entry *entry = &entries[i]; - - if (entry->type_guid[1] == 0) - continue; - - used_count++; - - if (entry->lba_first == 0) - continue; - - if (entry->lba_first >= dev->block_count) - continue; - - /* Name and register the partition */ - char *buf = kzalloc(64, ALLOC_KERN); - snprintf(buf, "%sp%d", 63, dev->name, used_count - 1); - - struct block_device *bdev = block_register(buf, &dev->ops, dev->data, dev->block_count, dev->block_size); - if (!bdev) { - kfree(buf); - continue; - } - - bdev->lba_start = entry->lba_first; - bdev->block_count = entry->lba_last - entry->lba_first + 1; - bdev->parent = dev; - *list = bdev; - list = &bdev->next_part; - } - dev->partition_count = used_count; - -#ifdef KDEBUG - kprintf(LOG_DEBUG "GPT header for device %s loaded\n", dev->name); -#endif - -free_entries: - kfree(entries); -free_header: - kfree(header); -} diff --git a/fs/vfs.c b/fs/vfs.c deleted file mode 100644 index 0dddeb2..0000000 --- a/fs/vfs.c +++ /dev/null @@ -1,511 +0,0 @@ -/* SDPX-License-Identifier: GPL-2.0-only */ -#include -#include -#include -#include - -#include -#include -#include - -#include - -static struct fs *rootfs; -static slab_t *file_slab; -static slab_t *vnode_slab; - -typedef struct fs *(*vfs_init_t)(struct block_device *); - -static void vfs_vnode_dec_ref(struct vnode *vnode); -static void vfs_vnode_dealloc(struct vnode *vnode); - -static void vfs_vnode_dealloc(struct vnode *vnode) -{ - if (!vnode) - return; - - if (vnode->no_free) - return; - - if (vnode->parent) { - spinlock_acquire(&vnode->parent->lock); - for (size_t i = 0; i < vnode->parent->num_dirents; i++) { - if (vnode->parent->dirents[i].vnode == vnode) { - vnode->parent->dirents[i].vnode = NULL; - break; - } - } - spinlock_release(&vnode->parent->lock); - - vfs_vnode_dec_ref(vnode->parent); - } - - ATTEMPT_FREE(vnode->dirents); - - slab_free(vnode_slab, vnode); -} - -static void vfs_vnode_dec_ref(struct vnode *vnode) -{ - if (!vnode) - return; - - if (vnode->no_free) - return; - - spinlock_acquire(&vnode->lock); - vnode->refcount--; - spinlock_release(&vnode->lock); - - /* will recursively free all vnodes */ - if (vnode->refcount == 0) - vfs_vnode_dealloc(vnode); -} - -struct vnode *vfs_lookup(const char *name, int *err) -{ - struct vnode *cur_vnode = rootfs->root; - struct fs *fs = rootfs; - - char *path_copy = kzalloc(strlen(name) + 1, ALLOC_KERN); - strcpy(path_copy, name); - - char *tok_last = NULL; - char *tok = strtok(path_copy, "/", &tok_last); - - struct dirent *entry = NULL; - - while (!strempty(tok)) { - bool found = false; - for (int i = 0; i < cur_vnode->num_dirents; i++) { - entry = &cur_vnode->dirents[i]; - if (strcmp(entry->name, tok) == 0) { - if (entry->vnode) { - /* go to next vnode */ - cur_vnode = entry->vnode; - - if (cur_vnode->mount_ptr) { - fs = cur_vnode->ptr->fs; - cur_vnode = cur_vnode->ptr; - } - - spinlock_acquire(&cur_vnode->lock); - cur_vnode->refcount++; - spinlock_release(&cur_vnode->lock); - } else { - /* try to open the vnode */ - struct vnode *new_vnode = slab_alloc(vnode_slab); - if (!new_vnode) { - ATTEMPT_WRITE(err, -ENOMEM); - kfree(path_copy); - return NULL; - } - memset(new_vnode, 0, sizeof(struct vnode)); - new_vnode->refcount = 1; - new_vnode->parent = cur_vnode; - - int res = fs->ops->open_vno(fs, new_vnode, entry->inode); - if (res < 0) { - ATTEMPT_WRITE(err, res); - slab_free(vnode_slab, new_vnode); - kfree(path_copy); - return NULL; - } - - cur_vnode = new_vnode; - entry->vnode = cur_vnode; - } - - found = true; - break; - } - } - - if (!found) { - ATTEMPT_WRITE(err, -ENOENT); - vfs_vnode_dec_ref(cur_vnode); - kfree(path_copy); - return NULL; - } - - /* get next token */ - tok = strtok(NULL, "/", &tok_last); - } - - kfree(path_copy); - return cur_vnode; -} - -struct file *vfs_open(const char *pathname, int *err) -{ - /* allocate a file */ - struct file *file = slab_alloc(file_slab); - - if (!file) { - kprintf(LOG_ERROR "Failed to allocate file struct\n"); - return NULL; - } - memset(file, 0, sizeof(struct file)); - - int len = strlen(pathname); - int inc = 0; - for (int i = 0; i < len; i++) { - if (pathname[i] == '/') - inc++; - else - break; - } - - if (inc < len) - pathname += inc; - - struct vnode *vno = vfs_lookup(pathname, err); - if (!vno) { - slab_free(file_slab, file); - return NULL; - } - - file->vnode = vno; - file->type = vno->flags & VFS_VTYPE_MASK; - file->size = vno->size; - file->ino_num = vno->ino_num; - - return file; -} - -int vfs_close(struct file *file) -{ - if (!file) - return -EBADF; - - vfs_vnode_dec_ref(file->vnode); - - slab_free(file_slab, file); - return 0; -} - -ssize_t vfs_write(struct file *file, void *buf, off_t off, size_t count) -{ - if ((file->vnode->flags & VFS_VTYPE_MASK) == VFS_VNO_DIR) - return -EISDIR; - - if (file->vnode->flags & VFS_VNO_FIFO) { - return ringbuf_write(file->vnode->priv_data, buf, count); - } - - return file->vnode->fs->ops->write(file->vnode, buf, off, count); -} - -ssize_t vfs_read(struct file *file, void *buf, off_t off, size_t count) -{ - if ((file->vnode->flags & VFS_VTYPE_MASK) == VFS_VNO_DIR) - return -EISDIR; - - if (off >= file->vnode->size && file->type == VFS_VNO_REG) - return 0; - - /* read from fifo */ - if (file->vnode->flags & VFS_VNO_FIFO) { - return ringbuf_read(file->vnode->priv_data, buf, count); - } - - if (off + count > file->vnode->size) - count = file->vnode->size - off; - - return file->vnode->fs->ops->read(file->vnode, buf, off, count); -} - -struct vnode *vfs_create_file(struct vnode *parent, const char *path, mode_t mode) -{ - struct fs *fs = parent->fs; - - int res = fs->ops->creat(parent, path, mode); - if (res < 0) - return NULL; - - /* find the new vnode */ - struct vnode *vnode = NULL; - for (int i = 0; i < parent->num_dirents; i++) { - if (strcmp(parent->dirents[i].name, path) == 0) { - vnode = parent->dirents[i].vnode; - break; - } - } - - return vnode; -} - -int vfs_statf(struct file *file, struct statbuf *statbuf) -{ - statbuf->size = file->vnode->size; - - return 0; -} - -char *basename(char *path) -{ - char *ret = path; - for (int i = 0; path[i]; i++) { - if (path[i] == '/') - ret = path + i + 1; - } - - return ret; -} - -char *dirname(char *path) -{ - char *ret = path; - for (int i = 0; path[i]; i++) { - if (path[i] == '/') - ret = path + i; - } - - if (ret == path) - return NULL; - - *ret = 0; - - return path; -} - -inline uint64_t vfs_file_type(struct file *file) -{ - return file->vnode->flags & VFS_VTYPE_MASK; -} - -inline void *vfs_file_dev(struct file *file) -{ - return ((struct devfs_dev_info *)file->vnode->priv_data)->dev; -} - -struct vnode *vfs_mknod(const char *pathname, mode_t mode) -{ - char *pathcpy = kzalloc(strlen(pathname) + 1, ALLOC_KERN); - strcpy(pathcpy, pathname); - - char *name = basename(pathcpy); - char *dir = dirname(pathcpy); - - struct file *dir_file = vfs_open(dir, NULL); - if (!dir_file) - return NULL; - - struct vnode *dir_vnode = dir_file->vnode; - - struct vnode *vnode = vfs_create_vno(); - if (!vnode) { - vfs_close(dir_file); - return NULL; - } - - switch (mode & VFS_VTYPE_MASK) { - case VFS_VNO_FIFO: - case VFS_VNO_BLKDEV: - case VFS_VNO_CHARDEV: - break; - default: - return NULL; - } - - vnode->refcount = 1; - vnode->fs = dir_vnode->fs; - vnode->flags = mode; - vnode->priv_data = ringbuf_create(0x4000); - - /* create directory entry */ - struct dirent *dirents = dir_vnode->dirents; - int num_dirents = dir_vnode->num_dirents; - - /* search for existing entry */ - for (int i = 0; i < num_dirents; i++) { - if (strcmp(dirents[i].name, name) == 0) { - vfs_close(dir_file); - slab_free(vnode_slab, vnode); - return NULL; - } - } - - spinlock_acquire(&dir_vnode->lock); - - dirents = krealloc(dirents, (num_dirents + 1) * sizeof(struct dirent), ALLOC_KERN); - if (!dirents) { - vfs_close(dir_file); - slab_free(vnode_slab, vnode); - return NULL; - } - - dir_vnode->dirents = dirents; - - struct dirent *dirent = &dirents[num_dirents]; - memset(dirent, 0, sizeof(struct dirent)); - dirent->vnode = vnode; - dirent->reclen = sizeof(struct dirent); - dirent->inode = 0; - strcpy(dirent->name, name); - - dir_vnode->num_dirents++; - spinlock_release(&dir_vnode->lock); - - vfs_close(dir_file); - - return vnode; -} - -struct vnode *vfs_create_vno() -{ - struct vnode *vnode = slab_alloc(vnode_slab); - if (!vnode) - return NULL; - - memset(vnode, 0, sizeof(struct vnode)); - - return vnode; -} - -struct fs *vfs_create() -{ - struct fs *fs = kzalloc(sizeof(struct fs), ALLOC_KERN); - if (!fs) - return NULL; - - fs->root = vfs_create_vno(); - if (!fs->root) - goto out_root; - - fs->ops = kzalloc(sizeof(struct fs_ops), ALLOC_KERN); - if (!fs->ops) - goto out_ops; - - fs->root->no_free = true; - fs->root->refcount = 1; - - return fs; - -out_ops: - kfree(fs->root); -out_root: - kfree(fs); - return NULL; -} - -void vfs_dealloc(struct fs *fs) -{ - ATTEMPT_FREE(fs->ops); - if (fs->root) - ATTEMPT_FREE(fs->root->dirents); - slab_free(vnode_slab, fs->root); - - ATTEMPT_FREE(fs->mount_point); - ATTEMPT_FREE(fs); -} - -void vfs_no_free_r(struct vnode *vnode) -{ - if (!vnode) - return; - - while (vnode && !vnode->no_free) { - vnode->no_free = true; - vnode = vnode->parent; - } -} - -int vfs_mount(struct fs *fs, const char *mount_point) -{ - struct vnode *vnode = fs->root; - - /* find vnode of mount_point */ - int err; - struct file *file = vfs_open(mount_point, &err); - if (!file) - return err; - - struct vnode *mp_vnode = file->vnode; - - /* mount point is a directory */ - if ((mp_vnode->flags & VFS_VTYPE_MASK) != VFS_VNO_DIR) { - vfs_close(file); - return -ENOTDIR; - } - - /* mount point is empty */ - for (int i = 0; i < mp_vnode->num_dirents; i++) { - struct dirent *dirent = &mp_vnode->dirents[i]; - if (strcmp(".", dirent->name) == 0 || strcmp("..", dirent->name) == 0) - continue; - kprintf("dirent: %s\n", dirent->name); - } - - /* mount */ - spinlock_acquire(&mp_vnode->lock); - spinlock_acquire(&vnode->lock); - - mp_vnode->ptr = vnode; - mp_vnode->mount_ptr = true; - - vnode->parent = mp_vnode; - vfs_no_free_r(vnode); - - spinlock_release(&vnode->lock); - spinlock_release(&mp_vnode->lock); - - return 0; -} - -struct fs *vfs_mount_root(const char *dev, const char *mount_point) -{ - /* TODO: detect filesystem type */ - /* for now, assume ext2 */ - struct block_device *bdev = block_get_device(dev); - if (!dev) { - kprintf(LOG_ERROR "Failed to find device %s\n", dev); - kerror_print_blkdevs(); - panic(); - } - struct fs *fs = ext2_init_fs(bdev); - - if (!fs) - goto out; - - fs->type = FS_TYPE_EXT2; - - fs->mount_point = kmalloc(strlen(mount_point) + 1, ALLOC_KERN); - if (!fs->mount_point) - goto out_dealloc_fs; - - strcpy(fs->mount_point, mount_point); - - struct vnode *root = fs->root; - root->no_free = true; - - return fs; - -out_dealloc_fs: - vfs_dealloc(fs); -out: - return NULL; -} - -void vfs_init(const char *rootdev_name) -{ - file_slab = slab_create(sizeof(struct file), 16 * KB, 0); - vnode_slab = slab_create(sizeof(struct vnode), 16 * KB, 0); - -#ifdef KDEBUG - kprintf(LOG_DEBUG "Found root device %s\n", rootdev_name); -#endif - - struct fs *fs = vfs_mount_root(rootdev_name, "/"); - if (!fs) { - kprintf(LOG_ERROR "Failed to mount root device %s\n", rootdev_name); - kerror_print_blkdevs(); - panic(); - } else { -#ifdef KDEBUG - kprintf(LOG_DEBUG "Mounted root device %s\n", rootdev_name); -#endif - } - - rootfs = fs; -} diff --git a/include/dev/ahci.h b/include/dev/ahci.h deleted file mode 100644 index b163a1e..0000000 --- a/include/dev/ahci.h +++ /dev/null @@ -1,345 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _AHCI_H_ -#define _AHCI_H_ - -#include -#include - -/* Frame information structure (FIS) */ -#define FIS_REG_H2D 0x27 -#define FIS_REG_D2H 0x34 -#define FIS_DMA_ACT 0x39 -#define FIS_DMA_SETUP 0x41 -#define FIS_DATA 0x46 -#define FIS_BIST 0x58 -#define FIS_PIO_SETUP 0x5F -#define FIS_DEV_BITS 0xA1 - -#define ATA_DEV_BUSY 0x80 -#define ATA_DEV_DRQ 0x08 - -#define ATA_CMD_READ_DMA_EX 0x25 -#define ATA_CMD_WRITE_DMA_EX 0x35 -#define ATA_CMD_IDENT 0xEC - -#define SATA_SIG_ATA 0x00000101 -#define SATA_SIG_ATAPI 0xEB140101 -#define SATA_SIG_SEMB 0xC33C0101 -#define SATA_SIG_PM 0x96690101 - -#define AHCI_DEV_NULL 0 -#define AHCI_DEV_SATA 1 -#define AHCI_DEV_SEMB 2 -#define AHCI_DEV_PM 3 -#define AHCI_DEV_SATAPI 4 - -#define AHCI_GHC_IE 0x2 -#define AHCI_GHC_AE 0x80000000 - -#define HBA_PORT_IPM_ACTIVE 0x1 -#define HBA_PORT_DET_PRESENT 0x3 - -#define HBA_PORT_CMD_ST 0x1 -#define HBA_PORT_CMD_FRE 0x10 -#define HBA_PORT_CMD_FR 0x4000 -#define HBA_PORT_CMD_CR 0x8000 -#define HBA_PORT_IS_TFES 0x40000000 - -struct fis_reg_h2d { - /* 0x00 */ - uint8_t fis_type; - - uint8_t pmult : 4; - uint8_t reserved : 3; - uint8_t cmd_mode : 1; /* high: command, low: control */ - - uint8_t command; - uint8_t feature_low; - - /* 0x04 */ - uint8_t lba0; - uint8_t lba1; - uint8_t lba2; - uint8_t device; - - /* 0x08 */ - uint8_t lba3; - uint8_t lba4; - uint8_t lba5; - uint8_t feature_high; - - /* 0x0C */ - uint8_t count_low; - uint8_t count_high; - uint8_t icc; - uint8_t control; - - /* 0x10 */ - uint32_t reserved2; -} PACKED; - -struct fis_reg_d2h { - /* 0x00 */ - uint8_t fis_type; - - uint8_t pmult : 4; - uint8_t reserved : 2; - uint8_t intr : 1; - uint8_t reserved2 : 1; - - uint8_t status; - uint8_t error; - - /* 0x04 */ - uint8_t lba0; - uint8_t lba1; - uint8_t lba2; - uint8_t device; - - /* 0x08 */ - uint8_t lba3; - uint8_t lba4; - uint8_t lba5; - uint8_t feature_high; - - /* 0x0C */ - uint8_t count_low; - uint8_t count_high; - uint8_t icc; - uint8_t control; - - /* 0x10 */ - uint32_t reserved3; -} PACKED; - -struct fis_data { - /* 0x00 */ - uint8_t fis_type; - - uint8_t pmult : 4; - uint8_t reserved : 4; - - uint8_t reserved2[2]; - - /* 0x04 */ - uint32_t data[1]; /* Variable length */ -} PACKED; - -struct fis_dma_setup { - /* 0x00 */ - uint8_t fis_type; - - uint8_t pmult : 4; - uint8_t reserved : 1; - uint8_t data_dir : 1; - uint8_t intr : 1; - uint8_t auto_act : 1; - - uint16_t reserved2; - - /* 0x04 */ - uint64_t dma_buffer_id; - - /* 0x0C */ - uint32_t reserved3; - - /* 0x10 */ - uint32_t dma_buffer_offset; - - /* 0x14 */ - uint32_t transfer_count; - - /* 0x18 */ - uint32_t reserved4; -} PACKED; - -struct fis_pio_setup { - /* 0x00 */ - uint8_t fis_type; - - uint8_t pmult : 4; - uint8_t reserved : 1; - uint8_t data_dir : 1; - uint8_t intr : 1; - uint8_t reserved2 : 1; - - uint8_t status; - uint8_t error; - - /* 0x04 */ - uint8_t lba0; - uint8_t lba1; - uint8_t lba2; - uint8_t device; - - /* 0x08 */ - uint8_t lba3; - uint8_t lba4; - uint8_t lba5; - uint8_t reserved3; - - /* 0x0C */ - uint8_t count_low; - uint8_t count_high; - uint8_t reserved4; - uint8_t e_status; - - /* 0x10 */ - uint16_t transfer_count; - uint16_t reserved5; -} PACKED; - -struct fis_set_device_bits { - /* 0x00 */ - uint8_t fis_type; - - uint8_t pmult : 4; - uint8_t reserved : 2; - uint8_t interrupt : 1; - uint8_t n : 1; - - uint8_t statusl : 3; - uint8_t reserved2 : 1; - uint8_t statush : 3; - uint8_t reserved3 : 1; - - /* 0x04 */ - uint8_t errorl : 3; -} PACKED; - -struct hba_cmd_header { - uint8_t cmd_fis_len : 5; - uint8_t atapi : 1; - uint8_t write : 1; - uint8_t prefetch : 1; - - uint8_t reset : 1; - uint8_t bist : 1; - uint8_t clear_busy : 1; - uint8_t reserved : 1; - uint8_t pmp : 4; - - uint16_t prdt_len; - - volatile uint32_t prdb_count; - - paddr_t cmd_table_base; - - uint32_t reserved2[4]; -} PACKED; - -struct hba_prdt_entry { - paddr_t data_base; - - uint32_t reserved; - - uint32_t byte_count : 22; - uint32_t reserved2 : 9; - uint32_t interrupt : 1; -} PACKED; - -struct hba_cmd_tbl { - uint8_t cfis[64]; - - uint8_t acmd[16]; - - uint8_t reserved[48]; - - struct hba_prdt_entry prdt_entry[1]; -} PACKED; - -typedef volatile struct { - /* 0x00 */ - paddr_t clb; - - paddr_t fb; - - /* 0x10 */ - uint32_t is; - uint32_t ie; - uint32_t cmd; - uint32_t reserved; - - /* 0x20 */ - uint32_t tfd; - uint32_t sig; - uint32_t ssts; - uint32_t sctl; - - /* 0x30 */ - uint32_t serr; - uint32_t sact; - uint32_t ci; - uint32_t sntf; - - /* 0x40 */ - uint32_t fbs; - - uint32_t reserved1[11]; - uint32_t vendor[4]; -} PACKED hbaport_t; - -typedef volatile struct { - /* 0x00 */ - uint32_t cap; - uint32_t ghc; - uint32_t is; - uint32_t pi; - uint32_t vs; - - /* 0x14 */ - uint32_t ccc_ctl; - uint32_t ccc_ports; - uint32_t em_loc; - uint32_t em_ctl; - uint32_t cap2; - - /* 0x28 */ - uint32_t bohc; - - /* 0x2C */ - uint8_t reserved[0x74]; - - /* 0xA0 */ - uint8_t vendor[0x60]; - - /* 0x100 */ - hbaport_t ports[32]; -} PACKED hbamem_t; - -typedef volatile struct { - /* 0x00 */ - struct fis_dma_setup dfis; - uint32_t reserved; - - /* 0x20 */ - struct fis_pio_setup pfis; - uint32_t reserved1[3]; - - /* 0x40 */ - struct fis_reg_d2h rfis; - uint32_t reserved2; - - struct fis_set_device_bits sdbfis; - - /* 0x60 */ - uint8_t ufis[64]; - - /* 0xA0 */ - uint8_t reserved3[0x60]; - -} PACKED hbafis_t; - -struct sata_device { - struct pci_device *controller; - uint8_t port; - - size_t sector_size; - size_t sector_count; - hbamem_t *abar; -}; - -void ahci_init(); -bool ahci_access_sectors(struct sata_device *dev, paddr_t lba, uint16_t count, paddr_t buf, bool write); - -#endif /* _AHCI_H_ */ diff --git a/include/dev/apic.h b/include/dev/apic.h deleted file mode 100644 index 4b8319d..0000000 --- a/include/dev/apic.h +++ /dev/null @@ -1,140 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _APIC_H_ -#define _APIC_H_ - -#define MADT_LAPIC 0 -#define MADT_IOAPIC 1 -#define MADT_IOAPIC_OVRD 2 -#define MADT_IOAPIC_NMI 3 -#define MADT_LAPIC_NMI 4 -#define MADT_LAPIC_OVRD 5 -#define MADT_X2_LAPIC 9 - -#define LAPIC_ID 0x20 -#define LAPIC_VERSION 0x30 -#define LAPIC_TPR 0x80 -#define LAPIC_APR 0x90 -#define LAPIC_PPR 0xA0 -#define LAPIC_EOI 0xB0 -#define LAPIC_RRD 0xC0 -#define LAPIC_LDR 0xD0 -#define LAPIC_DFR 0xE0 -#define LAPIC_SIVR 0xF0 -#define LAPIC_ISR 0x100 -#define LAPIC_TMR 0x180 -#define LAPIC_IRR 0x200 -#define LAPIC_ERR 0x280 -#define LAPIC_CMCI 0x2F0 -#define LAPIC_ICR 0x300 -#define LAPIC_THERMAL 0x330 -#define LAPIC_LVT_PERF_MON_COUNT 0x340 -#define LAPIC_LVT_LINT0 0x350 -#define LAPIC_LVT_LINT1 0x360 -#define LAPIC_LVT_ERR 0x370 -#define LAPIC_INIT_COUNT 0x380 -#define LAPIC_CUR_COUNT 0x390 - -#define LAPIC_TIMER 0x320 -#define LAPIC_TIMER_DIV 0x3E0 -#define LAPIC_TIMER_INIT_COUNT 0x380 - -#define MSR_IA32_APIC_BASE 0x1B - -#ifndef __ASM__ - -#include -#include - -struct madt { - struct acpi_sdt_header h; - uint32_t lapic_addr; - uint32_t flags; -} PACKED; - -struct madt_header { - uint8_t type; - uint8_t length; -} PACKED; - -struct madt_lapic { - struct madt_header h; - uint8_t acpi_cpu_id; - uint8_t apic_id; - uint32_t flags; -} PACKED; - -struct madt_ioapic { - struct madt_header h; - uint8_t ioapic_id; - uint8_t reserved; - uint32_t ioapic_addr; - uint32_t intr_base; -} PACKED; - -struct madt_ioapic_ovrd { - struct madt_header h; - uint8_t bus; - uint8_t irq; - uint32_t intr; - uint16_t flags; -} PACKED; - -struct madt_ioapic_nmi { - struct madt_header h; - uint8_t nmi; - uint8_t reserved; - uint16_t flags; - uint32_t intr; -} PACKED; - -struct madt_lapic_nmi { - struct madt_header h; - uint8_t acpi_cpu_id; - uint16_t flags; - uint8_t lint; -} PACKED; - -struct madt_lapic_ovrd { - struct madt_header h; - uint16_t reserved; - uint64_t lapic_addr; -} PACKED; - -struct madt_x2_lapic { - struct madt_header h; - uint16_t reserved; - uint32_t lapic_id; - uint32_t flags; - uint32_t acpi_id; -} PACKED; - -struct apic_redirect { - union { - struct { - uint64_t isr : 8; - uint64_t delv_mode : 3; - uint64_t dest_mode : 1; - uint64_t delv_status : 1; - uint64_t polarity : 1; - uint64_t remote_irr : 1; - uint64_t trigger : 1; - uint64_t mask : 1; - uint64_t reserved : 39; - uint64_t dest : 8; - } PACKED; - struct { - uint32_t low; - uint32_t high; - } PACKED; - }; -} PACKED; - -void apic_init(); -void lapic_eoi(); -int madt_parse_next_entry(int offset); -void lapic_enable(); -void apic_enable_timer(); -uint8_t lapic_idno(); - -#endif /* __ASM__ */ -#endif /* _APIC_H_ */ diff --git a/include/dev/pci.h b/include/dev/pci.h deleted file mode 100644 index 5db9f93..0000000 --- a/include/dev/pci.h +++ /dev/null @@ -1,120 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _PCI_H_ -#define _PCI_H_ - -#include - -#define PCIPM_CONFIG_ADDRESS 0xCF8 -#define PCIPM_CONFIG_DATA 0xCFC - -struct pci_device { - uint8_t bus; - uint8_t slot; - - uint8_t func; - - uint8_t class; - uint8_t subclass; - - uint16_t vendor_id; - uint16_t device_id; - - uint16_t segment_group; - - uint8_t header_type; - - paddr32_t bar0; - paddr32_t bar1; - paddr32_t bar2; - paddr32_t bar3; - paddr32_t bar4; - paddr32_t bar5; -}; - -struct pci_header_base { - uint16_t vendor_id; - uint16_t device_id; - - uint16_t command; - uint16_t status; - - uint8_t revision_id; - uint8_t prog_if; - uint8_t subclass; - uint8_t class; - - uint8_t cache_line_size; - uint8_t latency_timer; - uint8_t header_type; - uint8_t bist; -} PACKED; - -struct pci_header_type_0 { - struct pci_header_base base; - - paddr32_t bar0; - paddr32_t bar1; - paddr32_t bar2; - paddr32_t bar3; - paddr32_t bar4; - paddr32_t bar5; - - uint32_t cardbus_cis_pointer; - - uint16_t subsystem_vendor_id; - uint16_t subsystem_id; - - uint32_t expansion_rom_base_address; - - uint8_t capabilities_pointer; - uint8_t reserved[7]; - - uint8_t interrupt_line; - uint8_t interrupt_pin; - uint8_t min_grant; - uint8_t max_latency; -} PACKED; - -struct pci_header_type_1 { - struct pci_header_base base; - - paddr32_t bar0; - paddr32_t bar1; - - uint8_t primary_bus_number; - uint8_t secondary_bus_number; - uint8_t subordinate_bus_number; - uint8_t secondary_latency_timer; - - uint8_t io_base; - uint8_t io_limit; - uint16_t secondary_status; - - uint16_t memory_base; - uint16_t memory_limit; - - uint16_t prefetchable_memory_base; - uint16_t prefetchable_memory_limit; - - uint32_t prefetchable_base_upper; - uint32_t prefetchable_limit_upper; - - uint16_t io_base_upper; - uint16_t io_limit_upper; - - uint8_t capabilities_pointer; - uint8_t reserved[3]; - - uint32_t expansion_rom_base_address; - - uint8_t interrupt_line; - uint8_t interrupt_pin; - uint16_t bridge_control; -} PACKED; - -void pci_init(); -uint32_t pci_config_read_long(uint8_t bus, uint8_t slot, uint8_t func, uint8_t offset); -void pci_config_write_long(uint8_t bus, uint8_t slot, uint8_t func, uint8_t offset, uint16_t data); -struct pci_device *pci_find_device(uint8_t class, uint8_t subclass); - -#endif /* _PCI_H_ */ diff --git a/include/dev/pic.h b/include/dev/pic.h deleted file mode 100644 index 0ff1831..0000000 --- a/include/dev/pic.h +++ /dev/null @@ -1,19 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _PIC_H_ -#define _PIC_H_ - -#include - -#define PIC1_CMD 0x20 -#define PIC1_DATA 0x21 -#define PIC2_CMD 0xA0 -#define PIC2_DATA 0xA1 - -#ifndef __ASM__ - -void pic_mask(uint8_t irq, uint8_t i); -void pic_eoi(uint8_t irq); -void pic_init(); - -#endif /* __ASM__ */ -#endif /* _PIC_H_ */ diff --git a/include/dev/serial.h b/include/dev/serial.h deleted file mode 100644 index e709775..0000000 --- a/include/dev/serial.h +++ /dev/null @@ -1,20 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _SERIAL_H_ -#define _SERIAL_H_ - -#define COM1 0x3F8 - -#ifndef __ASM__ - -#include - -void isr_serial_input(); -void isr_serial_input_1(); -ssize_t serial_write(const char *buf, size_t count); -void serial_putchar(char c); -void serial_trap(); -int serial_init(); - -#endif - -#endif /* _SERIAL_H_ */ diff --git a/include/drivers/tty.h b/include/drivers/tty.h new file mode 100644 index 0000000..203ce0f --- /dev/null +++ b/include/drivers/tty.h @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _TTY_H_ +#define _TTY_H_ + +#include + +#define DEV_CLASS_TTY 0x01 + +struct tty_serial_ops { + void (*serial_putchar)(struct tty *tty, char c); + char (*serial_getchar)(struct tty *tty); +}; + +struct tty { + dev_t dev; + dev_t serial_device; + void *serial_device_private; + + struct tty_serial_ops *serial_ops; +}; + +void tty_layer_init(); + +struct tty *tty_create(const char *name, dev_t serial_device); +void tty_putchar(struct tty *tty, char c); +char tty_getchar(struct tty *tty); +void tty_write(struct tty *tty, const char *s); + +void arch_serial_write(struct tty *tty, char c); +char arch_serial_read(struct tty *tty); + +void tty_send_dsr(struct tty *tty); +void tty_set_origin_mode(struct tty *tty); +void tty_clear_screen(struct tty *tty); +void tty_set_cursor_pos(struct tty *tty, int x, int y); +void tty_get_cursor_pos(struct tty *tty, int *row, int *col); +void tty_get_size(struct tty *tty, int *rows, int *cols); +void tty_setlf(struct tty *tty); + +#endif /* _TTY_H_ */ diff --git a/include/fs/devfs.h b/include/fs/devfs.h deleted file mode 100644 index 93db5fe..0000000 --- a/include/fs/devfs.h +++ /dev/null @@ -1,17 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _DEVFS_H_ -#define _DEVFS_H_ - -#include - -struct vnode; -struct devfs_dev_info { - void *dev; - ssize_t (*read)(void *dev, void *buf, size_t offset, size_t size); - ssize_t (*write)(void *dev, void *buf, size_t offset, size_t size); -}; - -struct fs *devfs_init(); -int devfs_insert(struct vnode *dir, const char *name, uint32_t flags, struct devfs_dev_info *ops); - -#endif /* _DEVFS_H_ */ diff --git a/include/fs/ext2.h b/include/fs/ext2.h deleted file mode 100644 index f87d1a5..0000000 --- a/include/fs/ext2.h +++ /dev/null @@ -1,158 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _EXT2_H_ -#define _EXT2_H_ - -#include -#include -#include - -#include - -#define EXT2_SUPER_MAGIC 0xEF53 -#define EXT2_ROOT_INO 2 -#define EXT2_SUPERBLOCK_BLOCKNO 1 - -#define EXT2_DE_UNKNOWN 0 -#define EXT2_DE_FILE 1 -#define EXT2_DE_DIR 2 -#define EXT2_DE_CHRDEV 3 -#define EXT2_DE_BLKDEV 4 -#define EXT2_DE_FIFO 5 -#define EXT2_DE_SOCK 6 -#define EXT2_DE_SYMLINK 7 - -#define EXT2_INO_FIFO 0x1000 -#define EXT2_INO_CHARDEV 0x2000 -#define EXT2_INO_DIR 0x4000 -#define EXT2_INO_BLKDEV 0x6000 -#define EXT2_INO_REG 0x8000 -#define EXT2_INO_SYMLINK 0xA000 -#define EXT2_INO_SOCK 0xC000 - -#define EXT2_FLAG_LONG_FILESIZE 0x0002 - -struct ext2_superblock { - uint32_t inodes_count; - uint32_t blocks_count; - uint32_t u_blocks_count; - uint32_t free_blocks_count; - uint32_t free_inodes_count; - uint32_t first_data_block; - - uint32_t log_block_size; - uint32_t log_frag_size; - - uint32_t blocks_per_group; - uint32_t frags_per_group; - uint32_t inodes_per_group; - - uint32_t mtime; - uint32_t wtime; - - uint16_t mnt_count; - uint16_t max_mnt_count; - uint16_t magic; - uint16_t state; - uint16_t errors; - uint16_t minor_rev_level; - - uint32_t lastcheck; - uint32_t checkinterval; - uint32_t creator_os; - uint32_t rev_level; - - uint16_t def_resuid; - uint16_t def_resgid; - - /* extended superblock fields - * if rev_level >= 1 - */ - uint32_t first_ino; - uint16_t inode_size; - uint16_t block_group_nr; - uint32_t feature_compat; - uint32_t feature_incompat; - uint32_t feature_ro_compat; - uint8_t uuid[16]; - char volume_name[16]; - char last_mounted[64]; - uint32_t algo_bitmap; - - /* performance hints */ - uint8_t prealloc_blocks; - uint8_t prealloc_dir_blocks; - uint16_t padding1; - - /* journaling support */ - uint8_t journal_uuid[16]; - uint32_t journal_inum; - uint32_t journal_dev; - uint32_t last_orphan; -} PACKED; - -struct ext2_inode { - uint16_t mode; - uint16_t uid; - uint32_t size; - - uint32_t atime; - uint32_t ctime; - uint32_t mtime; - uint32_t dtime; - - uint16_t gid; - uint16_t links_count; - uint32_t blocks; - uint32_t flags; - uint32_t osd1; - uint32_t block[15]; - - uint32_t generation; - uint32_t file_acl; - uint32_t dir_acl; - uint32_t faddr; - - uint8_t frag_number; - uint8_t frag_size; - uint16_t padding1; - uint16_t user_high; - uint16_t group_high; - uint32_t padding2; -} PACKED; - -struct ext2_group_desc { - uint32_t block_bitmap; - uint32_t inode_bitmap; - uint32_t inode_table; - uint16_t free_blocks_count; - uint16_t free_inodes_count; - uint16_t used_dirs_count; - uint16_t padding[7]; -} PACKED; - -struct ext2_dir_entry { - uint32_t inode; - uint16_t rec_len; - uint8_t name_len; - ftype_t file_type; - char name[]; -} PACKED; - -struct ext2fs { - struct ext2_superblock sb; - struct block_device *bdev; - - uint32_t bgdt_blockno; - uint32_t bgdt_num_blocks; - struct ext2_group_desc *bgdt; - - spinlock_t lock; - - uint32_t indir_block_size; - - uint32_t block_size; -}; - -struct fs *ext2_init_fs(struct block_device *bdev); - -#endif /* _EXT2_H_ */ diff --git a/include/fs/vfs.h b/include/fs/vfs.h deleted file mode 100644 index 89168ca..0000000 --- a/include/fs/vfs.h +++ /dev/null @@ -1,162 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _VFS_H_ -#define _VFS_H_ - -#include - -#define VFSE_IS_BDEV 0xFFFA - -#define VFS_TYPE_EXT2 0x0001 - -/* same as EXT2_INO_* */ -#define VFS_VNO_FIFO 0x1000 -#define VFS_VNO_CHARDEV 0x2000 -#define VFS_VNO_DIR 0x4000 -#define VFS_VNO_BLKDEV 0x6000 -#define VFS_VNO_REG 0x8000 -#define VFS_VNO_SYMLINK 0xA000 -#define VFS_VNO_SOCK 0xC000 -#define VFS_VTYPE_MASK 0xF000 - -#define FTYPE_CHARDEV VFS_VNO_CHARDEV -#define FTYPE_DIR VFS_VNO_DIR -#define FTYPE_BLKDEV VFS_VNO_BLKDEV -#define FTYPE_REG VFS_VNO_REG -#define FTYPE_SYMLINK VFS_VNO_SYMLINK -#define FTYPE_SOCK VFS_VNO_SOCK -#define FTYPE_FIFO VFS_VNO_FIFO - -#define VFS_DE_UNKNOWN 0 -#define VFS_DE_FILE 1 -#define VFS_DE_DIR 2 -#define VFS_DE_CHRDEV 3 -#define VFS_DE_BLKDEV 4 -#define VFS_DE_FIFO 5 -#define VFS_DE_SOCK 6 -#define VFS_DE_SYMLINK 7 - -#define SEEK_SET 0 -#define SEEK_CUR 1 -#define SEEK_END 2 - -#define O_RDONLY 0x0001 -#define O_WRONLY 0x0002 -#define O_RDWR 0x0004 -#define O_CREAT 0x0008 -#define O_TRUNC 0x0010 -#define O_APPEND 0x0020 - -#define S_IFIFO 0x1000 - -#define FS_TYPE_EXT2 0x0001 -#define FS_TYPE_PFS 0x0002 /* pseudo fs */ - -typedef uint32_t ino_t; -typedef uint8_t ftype_t; -typedef size_t off_t; - -struct vnode { - char name[256]; - uint32_t flags; - uint32_t gid; - uint32_t uid; - uint32_t size; - uint32_t ino_num; - - struct fs *fs; - struct vnode *ptr; - struct vnode *next; - - struct vnode *parent; - - struct dirent *dirents; /* for directories */ - size_t num_dirents; - - bool mount_ptr; /* does this node point to a root of a mounted fs? */ - bool no_free; /* permanently cached vnodes */ - - void *priv_data; - - size_t refcount; - spinlock_t lock; -}; - -struct dirent { - uint64_t inode; /* fs-specific inode number */ - uint16_t reclen; /* length of this record */ - ftype_t type; /* type: file, dir, chrdev, blkdev, etc. */ - char name[256]; - - struct vnode *vnode; /* we don't want duplicate vnodes */ -}; - -struct file { - struct vnode *vnode; - - spinlock_t ref_lock; - uint64_t refcount; - - ino_t ino_num; /* inode number */ - uint32_t type; /* type of the file */ - uint64_t size; /* size of the file */ -}; - -struct file_descriptor { - struct file *file; - - int fd; - uint64_t pos; - uint32_t flags; - - char *buf; - size_t buf_len; - - struct fs *fs; -}; - -struct fs_ops { - int (*read)(struct vnode *vnode, void *buf, size_t offset, size_t size); - int (*write)(struct vnode *vnode, void *buf, size_t offset, size_t size); - int (*unlink)(struct vnode *parent, const char *name); - int (*creat)(struct vnode *parent, const char *path, mode_t mode); - int (*open_vno)(struct fs *vfs, struct vnode *out, ino_t ino_num); -}; - -struct fs { - struct vnode *root; - void *fs; - uint32_t type; - struct fs_ops *ops; - - char *mount_point; -}; - -struct statbuf { - size_t size; -}; - -void vfs_init(const char *rootfs); -ssize_t vfs_write(struct file *file, void *buf, off_t off, size_t count); -ssize_t vfs_read(struct file *file, void *buf, off_t off, size_t count); -int vfs_statf(struct file *file, struct statbuf *statbuf); -struct file *vfs_open(const char *pathname, int *err); -struct vnode *vfs_create_file(struct vnode *parent, const char *path, mode_t mode); -struct vnode *vfs_mknod(const char *pathname, mode_t mode); -int vfs_close(struct file *file); -int unlink(const char *pathname); -int statfd(struct file_descriptor *fdesc, struct statbuf *statbuf); - -char *basename(char *path); -char *dirname(char *path); - -struct fs *vfs_create(); -struct vnode *vfs_create_vno(); -void vfs_dealloc(struct fs *fs); -int vfs_mount(struct fs *fs, const char *mount_point); - -uint64_t vfs_file_type(struct file *file); -void *vfs_file_dev(struct file *file); - -int stdout_write(struct file_descriptor *fdesc, void *buf, size_t len); - -#endif /* _VFS_H_ */ diff --git a/include/kernel/acpi.h b/include/kernel/acpi.h deleted file mode 100644 index 4f01ae5..0000000 --- a/include/kernel/acpi.h +++ /dev/null @@ -1,52 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _ACPI_H_ -#define _ACPI_H_ - -#ifndef __ASM__ - -#include - -struct rsdp { - char signature[8]; - uint8_t checksum; - char oemid[6]; - uint8_t revision; - uint32_t rsdt_addr; -} PACKED; - -struct acpi_sdt_header { - char signature[4]; - uint32_t length; - uint8_t revision; - uint8_t checksum; - char oem_id[6]; - char oem_table_id[8]; - uint32_t oem_revision; - uint32_t creator_id; - uint32_t creator_revision; -} PACKED; - -struct rsdt { - struct acpi_sdt_header h; - uint32_t sdt[]; -} PACKED; - -struct mcfg { - struct acpi_sdt_header h; - uint64_t reserved; - struct { - uint64_t base_addr; - uint16_t seg_group; - uint8_t start_bus; - uint8_t end_bus; - uint32_t reserved; - } PACKED cfg[]; -} PACKED; - -void acpi_init(); - -extern struct madt *__madt; -extern struct mcfg *__mcfg; - -#endif /* __ASM__ */ -#endif /* _ACPI_H_ */ diff --git a/include/kernel/block.h b/include/kernel/block.h deleted file mode 100644 index 5232751..0000000 --- a/include/kernel/block.h +++ /dev/null @@ -1,41 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _BLOCK_H_ -#define _BLOCK_H_ - -#include -#include - -struct block_device; - -struct block_device_ops { - int (*read)(struct block_device *bdev, void *buf, size_t offset, size_t size); - int (*write)(struct block_device *bdev, void *buf, size_t offset, size_t size); -}; - -struct block_device { - char *name; - struct block_device_ops ops; - void *data; - size_t size; - - size_t block_count; - size_t block_size; - size_t lba_start; - - size_t partition_count; - - void *fs; - struct block_device *parent; - struct block_device *next_part; /* singly linked list */ -}; - -struct block_device *block_register(char *name, struct block_device_ops *ops, void *data, size_t block_count, size_t block_size); -struct block_device *block_get_device(const char *name); -int block_read(struct block_device *bdev, void *buf, size_t offset, size_t size); -int block_write(struct block_device *bdev, void *buf, size_t offset, size_t size); -void kerror_print_blkdevs(); - -extern struct block_device *block_devices[]; -extern size_t block_devices_count; - -#endif /* _BLOCK_H_ */ diff --git a/include/kernel/buddy.h b/include/kernel/buddy.h new file mode 100644 index 0000000..b025133 --- /dev/null +++ b/include/kernel/buddy.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _BUDDY_H_ +#define _BUDDY_H_ + +#include + +void *buddy_alloc(size_t size); +void buddy_free(void *ptr); +void buddy_init(); + +#endif /* _BUDDY_H_ */ diff --git a/include/kernel/char.h b/include/kernel/char.h deleted file mode 100644 index 3d14105..0000000 --- a/include/kernel/char.h +++ /dev/null @@ -1,15 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _CHAR_H_ -#define _CHAR_H_ - -#include - -struct char_device { - char *name; - void *data; -}; - -struct char_device *char_device_create(const char *name, void *data); -void char_device_destroy(struct char_device *cd); - -#endif /* _CHAR_H_ */ diff --git a/include/kernel/common.h b/include/kernel/common.h index fbb5582..0ce3609 100644 --- a/include/kernel/common.h +++ b/include/kernel/common.h @@ -6,43 +6,27 @@ #include -#include -#include -#include -#include -#include -#include -#include -#include +#include -#include +#include #define PACKED __attribute__((packed)) #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #define ATTEMPT_WRITE(_x, _y) \ if (_x) { \ - *(_x) = _y; \ + *(_x) = _y; \ } -#define KB (1024ull) -#define MB (KB * KB) -#define GB (KB * MB) - #define RFLAGS_IF (1 << 9) -void yield(); -void panic(); -void cli(); -void sti(); -void _save_context(); -void reboot(); -void load_stack_and_jump(uintptr_t rsp, uintptr_t rbp, void *func, void *arg); +#define panic(...) \ + { \ + kprintf(LOG_PANIC __VA_ARGS__); \ + _panic(); \ + } -typedef uintptr_t paddr_t; -typedef uint32_t paddr32_t; -typedef int64_t ssize_t; -typedef int mode_t; -typedef long dev_t; +void yield(); +void _panic(); #endif /* _COMMON_H_ */ diff --git a/include/kernel/device.h b/include/kernel/device.h new file mode 100644 index 0000000..21decb2 --- /dev/null +++ b/include/kernel/device.h @@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _DEVICE_H_ +#define _DEVICE_H_ + +#include + + +typedef u64 dev_t; +typedef u64 dev_class_t; + + +dev_t device_create(void *private, dev_class_t class, const char *name); +void device_destroy(dev_t device); +dev_class_t device_class(dev_t dev); +void *device_private_info(dev_t dev); + +void device_layer_init(); + +#endif /* _DEVICE_H_ */ diff --git a/include/kernel/elf.h b/include/kernel/elf.h deleted file mode 100644 index b54a7e8..0000000 --- a/include/kernel/elf.h +++ /dev/null @@ -1,136 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _ELF_H_ -#define _ELF_H_ - -#include -#include - -#define ET_NONE 0 -#define ET_REL 1 -#define ET_EXEC 2 - -#define EI_CLASS 4 -#define EI_DATA 5 -#define EI_VERSION 6 -#define EI_OSABI 7 -#define EI_ABIVERSION 8 -#define EI_PAD 9 - -#define EI_CLASS_64 2 -#define EI_OSABI_SYSV 0 - -#define EM_X86_64 62 - -#define EI_VERSION_CURRENT 1 - -#define ELFCLASS64 2 -#define ELFDATA2LSB 1 /* Little endian, two's complement */ - -#define PT_NULL 0 -#define PT_LOAD 1 -#define PT_DYNAMIC 2 -#define PT_INTERP 3 -#define PT_NOTE 4 -#define PT_SHLIB 5 - -#define R_X86_64_NONE 0 -#define R_X86_64_64 1 -#define R_X86_64_PC32 2 -#define R_X86_64_RELATIVE 8 - -#define SHT_NULL 0x0 -#define SHT_PROGBITS 0x1 -#define SHT_SYMTAB 0x2 -#define SHT_STRTAB 0x3 -#define SHT_RELA 0x4 -#define SHT_HASH 0x5 -#define SHT_DYNAMIC 0x6 -#define SHT_NOTE 0x7 -#define SHT_NOBITS 0x8 -#define SHT_REL 0x9 -#define SHT_SHLIB 0x0A -#define SHT_DYNSYM 0x0B -#define SHT_INIT_ARRAY 0x0E -#define SHT_FINI_ARRAY 0x0F -#define SHT_PREINIT_ARRAY 0x10 - -#define SHF_WRITE 1 -#define SHF_ALLOC 2 -#define SHF_EXECINSTR 4 - -#define STB_LOCAL 0 -#define STB_GLOBAL 1 -#define STB_WEAK 2 - -#define STT_NOTYPE 0 -#define STT_OBJECT 1 -#define STT_FUNC 2 - -#define SHN_UNDEF 0 -#define SHN_ABS 0xFFF1 -#define SHN_COMMON 0xFFF2 - -#define PF_X 0x1 -#define PF_W 0x2 -#define PF_R 0x4 - -#define ELF64_R_TYPE(i) ((i) & 0xffffffff) -#define ELF64_R_SYM(i) ((i) >> 32) - -#define ELF_RELOC_ERR -1 - -typedef uint64_t Elf64_Addr; -typedef uint64_t Elf64_Off; -typedef uint16_t Elf64_Section; -typedef uint16_t Elf64_Versym; -typedef unsigned char Elf_Byte; -typedef uint16_t Elf64_Half; -typedef int32_t Elf64_Sword; -typedef uint32_t Elf64_Word; -typedef int64_t Elf64_Sxword; -typedef uint64_t Elf64_Xword; - -typedef struct { - unsigned char e_ident[16]; - uint16_t e_type; - uint16_t e_machine; - uint32_t e_version; - Elf64_Addr e_entry; - Elf64_Off e_phoff; - Elf64_Off e_shoff; - uint32_t e_flags; - uint16_t e_ehsize; - uint16_t e_phentsize; - uint16_t e_phnum; - uint16_t e_shentsize; - uint16_t e_shnum; - uint16_t e_shstrndx; -} PACKED Elf64_Ehdr; - -typedef struct { - uint32_t p_type; - uint32_t p_flags; - Elf64_Off p_offset; - Elf64_Addr p_vaddr; - Elf64_Addr p_paddr; - uint64_t p_filesz; - uint64_t p_memsz; - uint64_t p_align; -} PACKED Elf64_Phdr; - -typedef struct { - uint32_t sh_name; - uint32_t sh_type; - uint64_t sh_flags; - Elf64_Addr sh_addr; - Elf64_Off sh_offset; - uint64_t sh_size; - uint32_t sh_link; - uint32_t sh_info; - uint64_t sh_addralign; - uint64_t sh_entsize; -} PACKED Elf64_Shdr; - -pid_t elf_load_proc(char *fname); - -#endif /* _ELF_H_ */ diff --git a/include/kernel/gdt.h b/include/kernel/gdt.h deleted file mode 100644 index 9bdbace..0000000 --- a/include/kernel/gdt.h +++ /dev/null @@ -1,75 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _GDT_H_ -#define _GDT_H_ - -#define GDT_NUMDESC 192 -#define GDT_SIZE (64 * GDT_NUMDESC) - -#define GDT_ACCESS_DATA_RING0 0b10010010 -#define GDT_ACCESS_CODE_RING0 0b10011010 - -#define GDT_ACCESS_DATA_RING3 0b11110010 -#define GDT_ACCESS_CODE_RING3 0b11111010 - -#define GDT_SEGMENT_CODE_RING0 0x28 -#define GDT_SEGMENT_DATA_RING0 0x30 - -#define GDT_SEGMENT_DATA_RING3 0x38 -#define GDT_SEGMENT_CODE_RING3 0x40 - -#ifndef __ASM__ - -#include - -struct gdt_desc { - uint16_t limit; - uint16_t base; - uint8_t base_2; - uint8_t access; - uint8_t flags; - uint8_t base_3; -} PACKED; - -struct gdt_desc_sys { - uint16_t limit; - uint16_t base; - uint8_t base_2; - uint8_t access; - uint8_t flags; - uint8_t base_3; - uint32_t base_4; - uint32_t reserved; -} PACKED; - -struct tss { - uint32_t reserved; - uint64_t rsp0; - uint64_t rsp1; - uint64_t rsp2; - uint64_t reserved2; - uint64_t ist1; - uint64_t ist2; - uint64_t ist3; - uint64_t ist4; - uint64_t ist5; - uint64_t ist6; - uint64_t ist7; - uint64_t reserved3; - uint16_t reserved4; - uint16_t iomap_base; -} PACKED; - -struct gdtr { - uint16_t size; - uint64_t offset; -} PACKED; - -extern struct gdtr __gdtr; -extern struct gdt_desc __gdt[GDT_NUMDESC]; - -void gdt_init(); -uint16_t gdt_insert_tss(uintptr_t rsp0); -void ltr(uint16_t selector); - -#endif /* __ASM__ */ -#endif /* _GDT_H_ */ diff --git a/include/kernel/gpt.h b/include/kernel/gpt.h deleted file mode 100644 index ba846cd..0000000 --- a/include/kernel/gpt.h +++ /dev/null @@ -1,52 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _GPT_H_ -#define _GPT_H_ - -#include - -struct block_device; - -/* GPT LBA 0 */ -struct gpt_mbr_prot { - uint8_t boot[1]; - uint8_t chs_start[3]; - uint8_t type[1]; - uint8_t chs_end[3]; - uint8_t lba_start[4]; - uint8_t lba_size[4]; -} PACKED; - -/* GPT LBA 1 - * checksums use CRC32 - */ -struct gpt_header { - uint64_t signature; - uint8_t revision[4]; - uint8_t header_size[4]; - uint8_t checksum[4]; - uint8_t reserved[4]; - uint64_t lba_this; - uint64_t lba_alt; - uint64_t lba_first; - uint64_t lba_last; - uint8_t guid[16]; - uint64_t lba_table; - uint32_t entry_count; - uint32_t entry_size; - uint32_t checksum_table; -} PACKED; - -/* GPT LBA 2 */ -struct gpt_entry { - uint64_t type_guid[2]; - uint64_t unique_guid[2]; - uint64_t lba_first; - uint64_t lba_last; - uint64_t flags; - uint8_t name[72]; -} PACKED; - -void block_gpt_init(struct block_device *dev); - -#endif /* _GPT_H_ */ - diff --git a/include/kernel/idt.h b/include/kernel/idt.h deleted file mode 100644 index d5c2637..0000000 --- a/include/kernel/idt.h +++ /dev/null @@ -1,41 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _IDT_H_ -#define _IDT_H_ - -#define GATE_INTR 0x8E -#define GATE_TRAP 0x8F - -#define GATE_INTR_DPL3 0xEE - -#define IDT_GATE_SIZE 16 -#define IDT_NUM_VECTORS 256 -#define IDT_SIZE (IDT_GATE_SIZE * IDT_NUM_VECTORS) - -#ifndef __ASM__ - -#include - -struct irqdesc { - uint16_t offset_low; - uint16_t segment; - uint8_t ist; - uint8_t attrs; - uint16_t offset_mid; - uint32_t offset_high; - uint32_t reserved; -} PACKED; - -struct idtr { - uint16_t size; - uint64_t offset; -} PACKED; - -void idt_init(); -void cli(); -void sti(); - -extern struct idtr __idtr; -extern struct irqdesc __idt[IDT_NUM_VECTORS]; - -#endif /* __ASM__ */ -#endif /* _IDT_H_ */ diff --git a/include/kernel/irq.h b/include/kernel/irq.h deleted file mode 100644 index a5d1375..0000000 --- a/include/kernel/irq.h +++ /dev/null @@ -1,11 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _IRQ_H_ -#define _IRQ_H_ - -#include - -int irq_map(uint8_t irq, void *func); -void irq_unmap(uint8_t irq); -int irq_highest_free(); - -#endif /* _IRQ_H_ */ diff --git a/include/kernel/lock.h b/include/kernel/lock.h deleted file mode 100644 index e97b593..0000000 --- a/include/kernel/lock.h +++ /dev/null @@ -1,15 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _LOCK_H_ -#define _LOCK_H_ - -typedef int spinlock_t; -typedef spinlock_t mtx_t; - -int atomic_cmpxchg(volatile int *ptr, int cmpval, int newval); -void spinlock_acquire(spinlock_t *lock); -void spinlock_release(spinlock_t *lock); - -void mtx_acquire(mtx_t *mtx); -void mtx_release(mtx_t *mtx); - -#endif /* _LOCK_H_ */ diff --git a/include/kernel/mem.h b/include/kernel/mem.h index 88252c0..0705071 100644 --- a/include/kernel/mem.h +++ b/include/kernel/mem.h @@ -3,25 +3,12 @@ #define _MEM_H_ #include -#include - -#define BBMAP_FREE 0 -#define BBMAP_SPLIT 1 -#define BBMAP_USED 2 - -#define PAGE_PRESENT 0x1 -#define PAGE_RW 0x2 -#define PAGE_USER 0x4 -#define PAGE_XD 0x8000000000000000 - -#define PAGE_PWT 0x8 -#define PAGE_PCD 0x10 - -#define MAP_ANONYMOUS 0x20 - -#ifndef __ASM__ +#include #define ALIGN(_a) __attribute__((aligned(_a))) +#define PHYSICAL_PAGE_MASK (~(hhdm_start)) +#define TO_VIRT(addr) ((addr) | hhdm_start) +#define TO_PHYS(addr) ((addr) & PHYSICAL_PAGE_MASK) #define genrw(reg) \ uint64_t reg##_read(); \ @@ -35,90 +22,14 @@ genrw(ds); #undef genrw -struct proc; - -struct page { /* I would rather refer to this as a struct */ - union { - struct { - uint64_t present : 1; - uint64_t rw : 1; - uint64_t usermode : 1; - uint64_t pwt : 1; - uint64_t pcd : 1; - uint64_t accessed : 1; - uint64_t ignored : 1; - uint64_t zero : 1; - uint64_t ignored_2 : 4; - uint64_t addr : 36; - uint64_t reserved : 4; - uint64_t ignored_3 : 11; - uint64_t xd : 1; - }; - uint64_t val; - }; -}; - -struct cr3 { - union { - struct { - uint64_t ignored : 3; - uint64_t pwt : 1; - uint64_t pcd : 1; - uint64_t ignored_2 : 7; - uint64_t pml4_addr : 52; - }; - uint64_t val; - }; -}; - -struct mem_region { - paddr_t base; +struct mem_zone { + uintptr_t virt_base; size_t len; - bool usable; }; -struct buddy_region_header { - paddr_t usable_base; - size_t usable_len; - size_t max_depth; - - size_t bitmap_len; - char bitmap[]; -}; - -extern uintptr_t __data_end; -extern uintptr_t __bss_start; -extern uintptr_t __bss_end; +size_t mem_get_zones(struct mem_zone **ret); +void mem_init(); extern uintptr_t hhdm_start; -extern uintptr_t data_end; -extern uintptr_t bss_start; -extern uintptr_t bss_end; -extern struct mem_region *regions; -extern size_t num_regions; -extern size_t max_regions; - -extern struct rbtree *kmap_tree; -extern spinlock_t kmap_lock; - -extern struct page *pml4; -extern paddr_t kcr3; -extern struct page kdefault_attrs; - -void *buddy_alloc(size_t size); -void buddy_free(void *paddr_hhdm); -uintptr_t mmap_find_unmapped(struct rbtree *tree, spinlock_t *lock, uintptr_t start, size_t len); -void kmap(paddr_t paddr, uintptr_t vaddr, size_t len, uint64_t attr); -void *proc_mmap(struct proc *proc, paddr_t paddr, uintptr_t vaddr, size_t len, uint64_t attr); -void *kmap_device(void *dev_paddr, size_t len); -void proc_munmap(struct proc *proc, uintptr_t vaddr); -paddr_t proc_clone_mmap(struct proc *in, struct proc *out); -paddr_t virt_to_phys(uintptr_t vaddr, paddr_t page_base); -void mem_early_init(char *mem, size_t len); -uint64_t phys_read(paddr_t paddr); -void phys_write(paddr_t paddr, uint64_t data); -void *phys_memcpy(void *dest, paddr_t src, size_t num); - -#endif /* __ASM__ */ #endif /* _MEM_H_ */ diff --git a/include/kernel/msr.h b/include/kernel/msr.h deleted file mode 100644 index 85363d6..0000000 --- a/include/kernel/msr.h +++ /dev/null @@ -1,20 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _MSR_H_ -#define _MSR_H_ - -#include - -#define MSR_APIC_BASE 0x1B - -#define MSR_IA32_EFER 0xC0000080 -#define MSR_IA32_STAR 0xC0000081 -#define MSR_IA32_LSTAR 0xC0000082 -#define MSR_IA32_FMASK 0xC0000084 - -#ifndef __ASM__ - -uint64_t rdmsr(uint32_t msr); -void wrmsr(uint32_t msr, uint64_t val); - -#endif /* __ASM__ */ -#endif /* _MSR_H_ */ diff --git a/include/kernel/page.h b/include/kernel/page.h new file mode 100644 index 0000000..4e5e97d --- /dev/null +++ b/include/kernel/page.h @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _PAGE_H_ +#define _PAGE_H_ + +#include + +#define PAGE_FLAGS_EMPTY(flags) (!((flags) & PAGE_PRESENT)) + +typedef struct { + u64 pgd; +} pgd_t; /* PML4 entries */ +typedef struct { + u64 pud; +} pud_t; /* PDPT entries */ +typedef struct { + u64 pmd; +} pmd_t; /* PD entries */ +typedef struct { + u64 pte; +} pte_t; /* page table entries */ + +void page_init(); +pgd_t *pgd_get(); + +#endif /* _PAGE_H_ */ diff --git a/include/kernel/pio.h b/include/kernel/pio.h deleted file mode 100644 index f841c0c..0000000 --- a/include/kernel/pio.h +++ /dev/null @@ -1,19 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _PIO_H_ -#define _PIO_H_ - -#include - -#define genio(suffix, type) \ - void out##suffix(uint16_t port, type value); \ - type in##suffix(uint16_t port); - -genio(b, uint8_t); -genio(w, uint16_t); -genio(l, uint32_t); - -#undef genio - -void iowait(); - -#endif /* _PIO_H_ */ diff --git a/include/kernel/proc.h b/include/kernel/proc.h deleted file mode 100644 index 5bd84d5..0000000 --- a/include/kernel/proc.h +++ /dev/null @@ -1,139 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _PROC_H_ -#define _PROC_H_ - -#include -#include - -#include -#include -#include - -#include - -#define PROC_RUNNING 0 -#define PROC_STOPPED 1 -#define PROC_ALLOWSCHED 1 -#define PROC_BLOCKED 2 -#define PROC_YIELD 3 -#define PROC_ZOMBIE 4 - -#define PT_USER 0 -#define PT_KERN 1 - -#define STDIN_FILENO 0 -#define STDOUT_FILENO 1 -#define STDERR_FILENO 2 - -#define USER_STACK_BASE 0x0000070000000000 -#define USER_HEAP_BASE 0x0000000100000000 /* 4GB */ - -#define PM_BUD 0 -#define PM_SLB 1 - -typedef int64_t pid_t; - -struct proc_mmap_entry { - uintptr_t vaddr; - paddr_t paddr; - size_t len; - uint64_t attr; - uint64_t type; -}; - -struct procregs { - uint64_t rax; - uint64_t rbx; - uint64_t rcx; - uint64_t rdx; - uint64_t rsi; - uint64_t rdi; - uint64_t rbp; - uint64_t r8; - uint64_t r9; - uint64_t r10; - uint64_t r11; - uint64_t r12; - uint64_t r13; - uint64_t r14; - uint64_t r15; - - /* IRETQ stack frame */ - uint64_t rip; - uint64_t cs; - uint64_t rflags; - uint64_t rsp; - uint64_t ss; - -} PACKED; - -struct proc_mapping { - uintptr_t vaddr; - paddr_t paddr; - size_t len; - uint64_t attr; - uint64_t type; - slab_t *slab; - struct proc_mapping *next; -}; - -struct proc_allocation { - struct proc_mapping *mappings; - struct proc_mapping *last; - size_t num_mappings; -}; - -struct proc { - struct procregs regs; - uint8_t state; - pid_t pid; - pid_t ppid; - uint64_t cr3; - spinlock_t lock; - - bool is_kernel; - - struct rbtree page_map; - spinlock_t page_map_lock; - - struct rbtree fd_map; - spinlock_t fd_map_lock; - - struct proc *parent; - struct rbtree children; - - struct proc *buddy_proc; - - uintptr_t stack_start; - uintptr_t stack_size; - - uintptr_t heap_start; - - struct rbtree umalloc_tree; -}; - -struct procregs *proc_current_regs(); -struct proc *proc_create(); -struct proc *proc_createv(int flags); -void proc_init_memory(struct proc *proc, uint64_t mem_flags); -void proc_init_page_tables(struct proc *proc); -struct proc *proc_fork(struct proc *parent); -struct proc *proc_get(pid_t pid); -pid_t getpid(); -pid_t getupid(); -void proc_term(pid_t pid); -struct proc *proc_find(pid_t pid); -void proc_save_state(); -void proc_set_current(pid_t pid); -void proc_init(unsigned num_cpus); -void trap_sched(); -void schedule(); -void syscall_block(); -void proc_set_exec_addr(struct proc *proc, uintptr_t addr); -void proc_set_flags(struct proc *proc, uint64_t flags); -void proc_set_stack(struct proc *proc, uintptr_t base, size_t size); -void proc_set_state(pid_t pid, uint8_t state); - -void sswtch(); - -#endif /* _PROC_H_ */ diff --git a/include/kernel/rbtree.h b/include/kernel/rbtree.h deleted file mode 100644 index 5e8d1c6..0000000 --- a/include/kernel/rbtree.h +++ /dev/null @@ -1,43 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _RBTREE_H_ -#define _RBTREE_H_ - -#include -#include - -#define RB_RED 0 -#define RB_BLACK 1 - -struct rbnode { - struct rbnode *parent; - struct rbnode *left; - struct rbnode *right; - int color; - - uint64_t key; - uint64_t value; /* extra values */ - uint64_t value2; - uint64_t value3; -}; - -/* we use this rbtree structure because the root node will potentially be - * changed when we insert or delete a node - */ -struct rbtree { - struct rbnode *root; - spinlock_t lock; - size_t num_nodes; -}; - -struct rbnode *rbt_insert(struct rbtree *tree, uint64_t key); -void rbt_delete(struct rbtree *tree, struct rbnode *del); -void rbt_destroy(struct rbtree *tree); -struct rbnode *rbt_search(struct rbtree *tree, uint64_t key); -struct rbnode *rbt_successor(struct rbnode *node); -uint64_t rbt_next_key(struct rbtree *tree); -struct rbnode *rbt_range_val2(struct rbtree *tree, uint64_t sval, uint64_t len); -struct rbnode *rbt_minimum(struct rbnode *node); - -void rbt_slab_init(); - -#endif /* _RBTREE_H_ */ diff --git a/include/kernel/requests.h b/include/kernel/requests.h new file mode 100644 index 0000000..af6d539 --- /dev/null +++ b/include/kernel/requests.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _REQUESTS_H_ +#define _REQUESTS_H_ + +#include + +extern struct limine_executable_address_response *kern_addr_res; +extern struct limine_memmap_response *kern_map_res; +extern struct limine_hhdm_response *kern_hhdm_res; + +void requests_init(); + +#endif /* _REQUESTS_H_ */ diff --git a/include/kernel/ringbuf.h b/include/kernel/ringbuf.h deleted file mode 100644 index 0795241..0000000 --- a/include/kernel/ringbuf.h +++ /dev/null @@ -1,20 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _RINGBUF_H -#define _RINGBUF_H - -#include - -typedef struct _ringbuf { - char *buf; - size_t size; - size_t head; - size_t tail; -} ringbuf_t; - -ringbuf_t *ringbuf_create(size_t size); -void ringbuf_destroy(ringbuf_t *rb); - -size_t ringbuf_write(ringbuf_t *rb, const char *buf, size_t count); -size_t ringbuf_read(ringbuf_t *rb, char *buf, size_t count); - -#endif /* _RINGBUF_H */ diff --git a/include/kernel/slab.h b/include/kernel/slab.h index 3122fee..0bc8a5a 100644 --- a/include/kernel/slab.h +++ b/include/kernel/slab.h @@ -3,62 +3,23 @@ #define _SLAB_H_ #include -#include -#include +#include -#define SLAB_PAGE_ALIGN 0x01 -#define SLAB_DMA_64K 0x02 +typedef struct _mem_cache_t { + size_t item_size; + size_t cache_size; + size_t offset; + size_t alignment; /* must be a power of 2 */ + size_t num_members; + size_t num_free; + uintptr_t next_free; + spinlock_t lock; + struct _mem_cache_t *next; +} mem_cache_t; -#define ALLOC_KERN 0x01 -#define ALLOC_DMA 0x02 - -#define UA_SLAB 0x1 -#define UA_BUD 0x2 - -#define ALLOC_USER 0x0 -#define ALLOC_USER_STACK 0x1 -#define ALLOC_USER_RDONLY 0x2 -#define ALLOC_USER_EXEC 0x4 - -#define ATTEMPT_FREE(_x) \ - if (_x) { \ - kfree(_x); \ - _x = NULL; \ - } - -typedef struct _slab { - size_t size; /* size of each object */ - size_t tsize; /* total size of this slab */ - size_t num; /* number of objects in this slab */ - size_t free; /* number of free objects */ - uint64_t flags; - size_t align; - uintptr_t *nextfree; - struct _slab *next; - struct _slab *prev; - - spinlock_t lock; -} slab_t; - -struct kmap_entry { - uintptr_t *ptr; - size_t size; - slab_t *slab; - struct kmap_entry *next; -}; - -slab_t *slab_create(size_t size, size_t cache_size, uint64_t flags); -void *slab_alloc(slab_t *slab); -void slab_free(slab_t *slab, void *ptr); - -void kmalloc_init(); -void *kmalloc(size_t size, uint64_t flags); -void *kzalloc(size_t size, uint64_t flags); -void *krealloc(void *ptr, size_t size, uint64_t flags); -void kfree(void *ptr); -void *umalloc(struct proc *proc, size_t size, uint64_t opts, uintptr_t req_addr); -void ufree(struct proc *proc, void *ptr); - -void slabtypes_init(); +mem_cache_t *slab_create(size_t item_size, size_t cache_size, size_t alignment); +void *slab_alloc(mem_cache_t *cache); +void slab_free(mem_cache_t *cache, void *ptr); #endif /* _SLAB_H_ */ + diff --git a/include/kernel/syscall.h b/include/kernel/syscall.h deleted file mode 100644 index 514a437..0000000 --- a/include/kernel/syscall.h +++ /dev/null @@ -1,22 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _SYSCALL_H_ -#define _SYSCALL_H_ - -#define SYS_READ 0 -#define SYS_WRITE 1 -#define SYS_OPEN 2 -#define SYS_MMAP 9 -#define SYS_MUNMAP 11 -#define SYS_FORK 57 -#define SYS_EXIT 60 -#define SYS_MKDIR 83 -#define SYS_MKNOD 133 -#define SYS_LSDIR 254 - -#include -#include - -void sys_set_return(struct proc *proc, uint64_t ret); -void sswtch(); /* save and switch */ - -#endif /* _SYSCALL_H_ */ diff --git a/include/kernel/trap.h b/include/kernel/trap.h deleted file mode 100644 index 0e9c6e7..0000000 --- a/include/kernel/trap.h +++ /dev/null @@ -1,8 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _TRAP_H_ -#define _TRAP_H_ - -void exception(int vector, int error); -void exception_init(); - -#endif diff --git a/include/kernel/types.h b/include/kernel/types.h new file mode 100644 index 0000000..27372db --- /dev/null +++ b/include/kernel/types.h @@ -0,0 +1,27 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _TYPES_H_ +#define _TYPES_H_ + +#include +#include +#include + +#define KB (1024ull) +#define MB (KB * KB) +#define GB (MB * MB) + +typedef uintptr_t paddr_t; +typedef uint32_t paddr32_t; +typedef int64_t ssize_t; + +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; +typedef uint64_t u64; + +typedef int32_t i8; +typedef int16_t i16; +typedef int32_t i32; +typedef int64_t i64; + +#endif /* _TYPES_H_ */ diff --git a/include/kernel/umem.h b/include/kernel/umem.h deleted file mode 100644 index fe1deaa..0000000 --- a/include/kernel/umem.h +++ /dev/null @@ -1,9 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _UMEM_H_ -#define _UMEM_H_ - -#include - -void copy_to_user(struct proc *proc, void *dst, const void *src, size_t size); - -#endif /* _UMEM_H_ */ diff --git a/include/lib/assert.h b/include/lib/assert.h deleted file mode 100644 index f8e65a3..0000000 --- a/include/lib/assert.h +++ /dev/null @@ -1,17 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _ASSERT_H_ -#define _ASSERT_H_ - -#ifdef KDEBUG -#define assert(expr) \ - do { \ - if (!(expr)) { \ - kprintf(LOG_ERROR "assertion failed: %s, file %s, line %d\n", #expr, __FILE__, __LINE__); \ - yield(); \ - } \ - } while (0) -#else -#define assert(expr) ((void)0) -#endif - -#endif /* _ASSERT_H_ */ diff --git a/include/kernel/bitwise.h b/include/lib/bitwise.h similarity index 100% rename from include/kernel/bitwise.h rename to include/lib/bitwise.h diff --git a/include/lib/rbtree.h b/include/lib/rbtree.h new file mode 100644 index 0000000..f922475 --- /dev/null +++ b/include/lib/rbtree.h @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _RBTREE_H_ +#define _RBTREE_H_ + +#include +#include + +#define RB_RED 0 +#define RB_BLACK 1 + +typedef struct _rbnode { + struct _rbnode *parent; + struct _rbnode *left; + struct _rbnode *right; + int color; + + u64 key; + u64 value; +} rbnode; + +/* we use this rbtree structure because the root node will potentially be + * changed when we insert or delete a node + */ +typedef struct _rbtree { + rbnode *root; + spinlock_t lock; + size_t num_nodes; +} rbtree; + +rbnode *rbt_insert(rbtree *tree, u64 key); +void rbt_delete(rbtree *tree, rbnode *del); +void rbt_destroy(rbtree *tree); +rbnode *rbt_search(rbtree *tree, u64 key); +rbnode *rbt_successor(rbnode *node); +u64 rbt_next_key(rbtree *tree); +rbnode *rbt_minimum(rbnode *node); + +void rbt_slab_init(); + +#endif /* _RBTREE_H_ */ diff --git a/include/lib/sem.h b/include/lib/sem.h deleted file mode 100644 index 8808a8c..0000000 --- a/include/lib/sem.h +++ /dev/null @@ -1,18 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _SEM_H_ -#define _SEM_H_ - -#include - -typedef struct { - int count; - spinlock_t lock; -} sem_t; - -sem_t *sem_create(int count); -void sem_destroy(sem_t *sem); - -int sem_trywait(sem_t *sem); -void sem_post(sem_t *sem); - -#endif /* _SEM_H_ */ diff --git a/include/lib/sort.h b/include/lib/sort.h deleted file mode 100644 index 5b1483d..0000000 --- a/include/lib/sort.h +++ /dev/null @@ -1,9 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _SORT_H_ -#define _SORT_H_ - -#include - -void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); - -#endif /* _SORT_H_ */ diff --git a/include/lib/stack.h b/include/lib/stack.h deleted file mode 100644 index 0a83fe8..0000000 --- a/include/lib/stack.h +++ /dev/null @@ -1,24 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#ifndef _STACK_H_ -#define _STACK_H_ - -#include - -struct stack_node { - struct stack_node *next; - void *data; -}; - -struct stack { - struct stack_node *top; - size_t size; -}; - -void stack_init(); -struct stack *stack_create(); -void stack_destroy(struct stack *stack); -void stack_push(struct stack *stack, void *data); -void *stack_pop(struct stack *stack); -void *stack_peek(struct stack *stack); - -#endif /* _STACK_H_ */ diff --git a/include/lib/stdio.h b/include/lib/stdio.h index e9d6ecf..503afbb 100644 --- a/include/lib/stdio.h +++ b/include/lib/stdio.h @@ -2,24 +2,42 @@ #ifndef _STDIO_H_ #define _STDIO_H_ -#define COL_RED_BLACK "\e[31m" -#define COL_YELLOW_BLACK "\e[33m" -#define COL_GREEN_BLACK "\e[32m" -#define COL_MAGENTA_BLACK "\e[35m" +#include -#define COL_RESET "\e[m" +struct tty; + +#define COL_RED_BLACK "\033[31m" +#define COL_YELLOW_BLACK "\033[33m" +#define COL_GREEN_BLACK "\033[32m" +#define COL_MAGENTA_BLACK "\033[35m" +#define COL_BLUE_BLACK "\033[34m" +#define COL_CYAN_BLACK "\033[36m" +#define COL_WHITE_BLACK "\033[37m" + +#define COL_RESET "\033[m" #define LOG_ERROR "[" COL_RED_BLACK "ERR" COL_RESET "] " +#define LOG_PANIC "[" COL_RED_BLACK "PANIC" COL_RESET "] " #define LOG_WARN "[" COL_YELLOW_BLACK "WRN" COL_RESET "] " #define LOG_DEBUG "[" COL_MAGENTA_BLACK "DBG" COL_RESET "] " -#define LOG_SUCCESS "[" COL_GREEN_BLACK "RDY" COL_RESET "] " +#define LOG_READY "[" COL_GREEN_BLACK "RDY" COL_RESET "] " #define LOG_INFO "[LOG] " -#include -#include +#define kprintf(...) (printf_(__VA_ARGS__)) +#define kinfo(...) (kprintf(LOG_INFO __VA_ARGS__)) +#define kwarn(...) (kprintf(LOG_WARN __VA_ARGS__)) +#define kerr(...) (kprintf(LOG_ERROR __VA_ARGS__)) +#define krdy(...) (kprintf(LOG_READY __VA_ARGS__)) +#ifdef KDEBUG +#define kdebug(...) (kprintf(LOG_DEBUG __VA_ARGS__)) +#else +#define kdebug(...) (void)0; +#endif /* KDEBUG */ +#define snprintf(...) (snprintf_(__VA_ARGS__)) -int kprintf(const char *restrict fmt, ...); -int snprintf(char *str, const char *restrict fmt, size_t size, ...); -int vsnprintf(char *str, const char *restrict fmt, size_t size, va_list args); +int printf_(const char *fmt, ...); +int snprintf_(char *buffer, size_t count, const char *format, ...); -#endif /* _SDTIO_H_ */ +extern struct tty *tty_printf; + +#endif /* _STDIO_H_ */ diff --git a/include/lib/string.h b/include/lib/string.h index 6bcd8a6..723c063 100644 --- a/include/lib/string.h +++ b/include/lib/string.h @@ -8,7 +8,6 @@ #include #include -#include void *memcpy(void *dest, const void *src, size_t num); int memcmp(const void *aa, const void *bb, size_t num); @@ -23,7 +22,5 @@ char **strsplit(const char *str, char delim, int *num); size_t strlen(const char *c); int atoi(const char *a); -extern spinlock_t strtok_lock; - #endif /* __ASM__ */ #endif /* _STRING_H_ */ diff --git a/include/limine/limine.h b/include/limine/limine.h deleted file mode 100644 index 2714e80..0000000 --- a/include/limine/limine.h +++ /dev/null @@ -1,468 +0,0 @@ -/* BSD Zero Clause License */ - -/* Copyright (C) 2022-2023 mintsuki and contributors. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * SPDX-License-Identifier: 0BSD - */ - -#ifndef _LIMINE_H -#define _LIMINE_H 1 - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -/* Misc */ - -#ifdef LIMINE_NO_POINTERS -# define LIMINE_PTR(TYPE) uint64_t -#else -# define LIMINE_PTR(TYPE) TYPE -#endif - -#define LIMINE_COMMON_MAGIC 0xc7b1dd30df4c8b88, 0x0a82e883a194f07b - -struct limine_uuid { - uint32_t a; - uint16_t b; - uint16_t c; - uint8_t d[8]; -}; - -#define LIMINE_MEDIA_TYPE_GENERIC 0 -#define LIMINE_MEDIA_TYPE_OPTICAL 1 -#define LIMINE_MEDIA_TYPE_TFTP 2 - -struct limine_file { - uint64_t revision; - LIMINE_PTR(void *) address; - uint64_t size; - LIMINE_PTR(char *) path; - LIMINE_PTR(char *) cmdline; - uint32_t media_type; - uint32_t unused; - uint32_t tftp_ip; - uint32_t tftp_port; - uint32_t partition_index; - uint32_t mbr_disk_id; - struct limine_uuid gpt_disk_uuid; - struct limine_uuid gpt_part_uuid; - struct limine_uuid part_uuid; -}; - -/* Boot info */ - -#define LIMINE_BOOTLOADER_INFO_REQUEST { LIMINE_COMMON_MAGIC, 0xf55038d8e2a1202f, 0x279426fcf5f59740 } - -struct limine_bootloader_info_response { - uint64_t revision; - LIMINE_PTR(char *) name; - LIMINE_PTR(char *) version; -}; - -struct limine_bootloader_info_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_bootloader_info_response *) response; -}; - -/* Stack size */ - -#define LIMINE_STACK_SIZE_REQUEST { LIMINE_COMMON_MAGIC, 0x224ef0460a8e8926, 0xe1cb0fc25f46ea3d } - -struct limine_stack_size_response { - uint64_t revision; -}; - -struct limine_stack_size_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_stack_size_response *) response; - uint64_t stack_size; -}; - -/* HHDM */ - -#define LIMINE_HHDM_REQUEST { LIMINE_COMMON_MAGIC, 0x48dcf1cb8ad2b852, 0x63984e959a98244b } - -struct limine_hhdm_response { - uint64_t revision; - uint64_t offset; -}; - -struct limine_hhdm_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_hhdm_response *) response; -}; - -/* Framebuffer */ - -#define LIMINE_FRAMEBUFFER_REQUEST { LIMINE_COMMON_MAGIC, 0x9d5827dcd881dd75, 0xa3148604f6fab11b } - -#define LIMINE_FRAMEBUFFER_RGB 1 - -struct limine_video_mode { - uint64_t pitch; - uint64_t width; - uint64_t height; - uint16_t bpp; - uint8_t memory_model; - uint8_t red_mask_size; - uint8_t red_mask_shift; - uint8_t green_mask_size; - uint8_t green_mask_shift; - uint8_t blue_mask_size; - uint8_t blue_mask_shift; -}; - -struct limine_framebuffer { - LIMINE_PTR(void *) address; - uint64_t width; - uint64_t height; - uint64_t pitch; - uint16_t bpp; - uint8_t memory_model; - uint8_t red_mask_size; - uint8_t red_mask_shift; - uint8_t green_mask_size; - uint8_t green_mask_shift; - uint8_t blue_mask_size; - uint8_t blue_mask_shift; - uint8_t unused[7]; - uint64_t edid_size; - LIMINE_PTR(void *) edid; - /* Response revision 1 */ - uint64_t mode_count; - LIMINE_PTR(struct limine_video_mode **) modes; -}; - -struct limine_framebuffer_response { - uint64_t revision; - uint64_t framebuffer_count; - LIMINE_PTR(struct limine_framebuffer **) framebuffers; -}; - -struct limine_framebuffer_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_framebuffer_response *) response; -}; - -/* Terminal */ - -#define LIMINE_TERMINAL_REQUEST { LIMINE_COMMON_MAGIC, 0xc8ac59310c2b0844, 0xa68d0c7265d38878 } - -#define LIMINE_TERMINAL_CB_DEC 10 -#define LIMINE_TERMINAL_CB_BELL 20 -#define LIMINE_TERMINAL_CB_PRIVATE_ID 30 -#define LIMINE_TERMINAL_CB_STATUS_REPORT 40 -#define LIMINE_TERMINAL_CB_POS_REPORT 50 -#define LIMINE_TERMINAL_CB_KBD_LEDS 60 -#define LIMINE_TERMINAL_CB_MODE 70 -#define LIMINE_TERMINAL_CB_LINUX 80 - -#define LIMINE_TERMINAL_CTX_SIZE ((uint64_t)(-1)) -#define LIMINE_TERMINAL_CTX_SAVE ((uint64_t)(-2)) -#define LIMINE_TERMINAL_CTX_RESTORE ((uint64_t)(-3)) -#define LIMINE_TERMINAL_FULL_REFRESH ((uint64_t)(-4)) - -/* Response revision 1 */ -#define LIMINE_TERMINAL_OOB_OUTPUT_GET ((uint64_t)(-10)) -#define LIMINE_TERMINAL_OOB_OUTPUT_SET ((uint64_t)(-11)) - -#define LIMINE_TERMINAL_OOB_OUTPUT_OCRNL (1 << 0) -#define LIMINE_TERMINAL_OOB_OUTPUT_OFDEL (1 << 1) -#define LIMINE_TERMINAL_OOB_OUTPUT_OFILL (1 << 2) -#define LIMINE_TERMINAL_OOB_OUTPUT_OLCUC (1 << 3) -#define LIMINE_TERMINAL_OOB_OUTPUT_ONLCR (1 << 4) -#define LIMINE_TERMINAL_OOB_OUTPUT_ONLRET (1 << 5) -#define LIMINE_TERMINAL_OOB_OUTPUT_ONOCR (1 << 6) -#define LIMINE_TERMINAL_OOB_OUTPUT_OPOST (1 << 7) - -struct limine_terminal; - -typedef void (*limine_terminal_write)(struct limine_terminal *, const char *, uint64_t); -typedef void (*limine_terminal_callback)(struct limine_terminal *, uint64_t, uint64_t, uint64_t, uint64_t); - -struct limine_terminal { - uint64_t columns; - uint64_t rows; - LIMINE_PTR(struct limine_framebuffer *) framebuffer; -}; - -struct limine_terminal_response { - uint64_t revision; - uint64_t terminal_count; - LIMINE_PTR(struct limine_terminal **) terminals; - LIMINE_PTR(limine_terminal_write) write; -}; - -struct limine_terminal_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_terminal_response *) response; - LIMINE_PTR(limine_terminal_callback) callback; -}; - -/* 5-level paging */ - -#define LIMINE_5_LEVEL_PAGING_REQUEST { LIMINE_COMMON_MAGIC, 0x94469551da9b3192, 0xebe5e86db7382888 } - -struct limine_5_level_paging_response { - uint64_t revision; -}; - -struct limine_5_level_paging_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_5_level_paging_response *) response; -}; - -/* SMP */ - -#define LIMINE_SMP_REQUEST { LIMINE_COMMON_MAGIC, 0x95a67b819a1b857e, 0xa0b61b723b6a73e0 } - -struct limine_smp_info; - -typedef void (*limine_goto_address)(struct limine_smp_info *); - -#if defined (__x86_64__) || defined (__i386__) - -#define LIMINE_SMP_X2APIC (1 << 0) - -struct limine_smp_info { - uint32_t processor_id; - uint32_t lapic_id; - uint64_t reserved; - LIMINE_PTR(limine_goto_address) goto_address; - uint64_t extra_argument; -}; - -struct limine_smp_response { - uint64_t revision; - uint32_t flags; - uint32_t bsp_lapic_id; - uint64_t cpu_count; - LIMINE_PTR(struct limine_smp_info **) cpus; -}; - -#elif defined (__aarch64__) - -struct limine_smp_info { - uint32_t processor_id; - uint32_t gic_iface_no; - uint64_t mpidr; - uint64_t reserved; - LIMINE_PTR(limine_goto_address) goto_address; - uint64_t extra_argument; -}; - -struct limine_smp_response { - uint64_t revision; - uint32_t flags; - uint64_t bsp_mpidr; - uint64_t cpu_count; - LIMINE_PTR(struct limine_smp_info **) cpus; -}; - -#else -#error Unknown architecture -#endif - -struct limine_smp_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_smp_response *) response; - uint64_t flags; -}; - -/* Memory map */ - -#define LIMINE_MEMMAP_REQUEST { LIMINE_COMMON_MAGIC, 0x67cf3d9d378a806f, 0xe304acdfc50c3c62 } - -#define LIMINE_MEMMAP_USABLE 0 -#define LIMINE_MEMMAP_RESERVED 1 -#define LIMINE_MEMMAP_ACPI_RECLAIMABLE 2 -#define LIMINE_MEMMAP_ACPI_NVS 3 -#define LIMINE_MEMMAP_BAD_MEMORY 4 -#define LIMINE_MEMMAP_BOOTLOADER_RECLAIMABLE 5 -#define LIMINE_MEMMAP_KERNEL_AND_MODULES 6 -#define LIMINE_MEMMAP_FRAMEBUFFER 7 - -struct limine_memmap_entry { - uint64_t base; - uint64_t length; - uint64_t type; -}; - -struct limine_memmap_response { - uint64_t revision; - uint64_t entry_count; - LIMINE_PTR(struct limine_memmap_entry **) entries; -}; - -struct limine_memmap_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_memmap_response *) response; -}; - -/* Entry point */ - -#define LIMINE_ENTRY_POINT_REQUEST { LIMINE_COMMON_MAGIC, 0x13d86c035a1cd3e1, 0x2b0caa89d8f3026a } - -typedef void (*limine_entry_point)(void); - -struct limine_entry_point_response { - uint64_t revision; -}; - -struct limine_entry_point_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_entry_point_response *) response; - LIMINE_PTR(limine_entry_point) entry; -}; - -/* Kernel File */ - -#define LIMINE_KERNEL_FILE_REQUEST { LIMINE_COMMON_MAGIC, 0xad97e90e83f1ed67, 0x31eb5d1c5ff23b69 } - -struct limine_kernel_file_response { - uint64_t revision; - LIMINE_PTR(struct limine_file *) kernel_file; -}; - -struct limine_kernel_file_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_kernel_file_response *) response; -}; - -/* Module */ - -#define LIMINE_MODULE_REQUEST { LIMINE_COMMON_MAGIC, 0x3e7e279702be32af, 0xca1c4f3bd1280cee } - -struct limine_module_response { - uint64_t revision; - uint64_t module_count; - LIMINE_PTR(struct limine_file **) modules; -}; - -struct limine_module_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_module_response *) response; -}; - -/* RSDP */ - -#define LIMINE_RSDP_REQUEST { LIMINE_COMMON_MAGIC, 0xc5e77b6b397e7b43, 0x27637845accdcf3c } - -struct limine_rsdp_response { - uint64_t revision; - LIMINE_PTR(void *) address; -}; - -struct limine_rsdp_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_rsdp_response *) response; -}; - -/* SMBIOS */ - -#define LIMINE_SMBIOS_REQUEST { LIMINE_COMMON_MAGIC, 0x9e9046f11e095391, 0xaa4a520fefbde5ee } - -struct limine_smbios_response { - uint64_t revision; - LIMINE_PTR(void *) entry_32; - LIMINE_PTR(void *) entry_64; -}; - -struct limine_smbios_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_smbios_response *) response; -}; - -/* EFI system table */ - -#define LIMINE_EFI_SYSTEM_TABLE_REQUEST { LIMINE_COMMON_MAGIC, 0x5ceba5163eaaf6d6, 0x0a6981610cf65fcc } - -struct limine_efi_system_table_response { - uint64_t revision; - LIMINE_PTR(void *) address; -}; - -struct limine_efi_system_table_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_efi_system_table_response *) response; -}; - -/* Boot time */ - -#define LIMINE_BOOT_TIME_REQUEST { LIMINE_COMMON_MAGIC, 0x502746e184c088aa, 0xfbc5ec83e6327893 } - -struct limine_boot_time_response { - uint64_t revision; - int64_t boot_time; -}; - -struct limine_boot_time_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_boot_time_response *) response; -}; - -/* Kernel address */ - -#define LIMINE_KERNEL_ADDRESS_REQUEST { LIMINE_COMMON_MAGIC, 0x71ba76863cc55f63, 0xb2644a48c516a487 } - -struct limine_kernel_address_response { - uint64_t revision; - uint64_t physical_base; - uint64_t virtual_base; -}; - -struct limine_kernel_address_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_kernel_address_response *) response; -}; - -/* Device Tree Blob */ - -#define LIMINE_DTB_REQUEST { LIMINE_COMMON_MAGIC, 0xb40ddb48fb54bac7, 0x545081493f81ffb7 } - -struct limine_dtb_response { - uint64_t revision; - LIMINE_PTR(void *) dtb_ptr; -}; - -struct limine_dtb_request { - uint64_t id[4]; - uint64_t revision; - LIMINE_PTR(struct limine_dtb_response *) response; -}; - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/init/acpi.c b/init/acpi.c deleted file mode 100644 index 5834312..0000000 --- a/init/acpi.c +++ /dev/null @@ -1,57 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include - -#include - -struct limine_rsdp_request rsdp_req = { .id = LIMINE_RSDP_REQUEST, .revision = 0 }; - -static struct rsdp *rsdp = NULL; -struct madt *__madt = NULL; -struct mcfg *__mcfg = NULL; - -static void rsdt_parse(struct rsdt *rsdt) -{ - int num_sdt = (rsdt->h.length - sizeof(rsdt->h)) >> 2; - -#ifdef KDEBUG - kprintf(LOG_DEBUG "Number of RSDT entries: %d\n", num_sdt); -#endif /* KDEBUG */ - - for (int i = 0; i < num_sdt; i++) { - /* 2 steps silences warning */ - uintptr_t sdt_addr = (uintptr_t)(rsdt->sdt[i] | hhdm_start); - struct acpi_sdt_header *h = (struct acpi_sdt_header *)sdt_addr; - - if (!(memcmp(h->signature, "APIC", 4))) { - __madt = (struct madt *)h; - } - - if (!(memcmp(h->signature, "MCFG", 4))) { - __mcfg = (struct mcfg *)h; - } - -#ifdef KDEBUG - char buf[8] = { 0 }; - memcpy(buf, h->signature, 4); - kprintf(LOG_DEBUG "RSDT entry: %s %d %x \n", buf, h->revision, h->checksum); -#endif /* KDEBUG */ - } -} - -void acpi_init() -{ - rsdp_req.response->address = (void *)((uintptr_t)rsdp_req.response->address & ~(hhdm_start)); - rsdp = kmap_device(rsdp_req.response->address, 0x1000); - - /* 2 steps silences warning */ - uintptr_t rsdt_addr = (uintptr_t)(rsdp->rsdt_addr & ~(hhdm_start)); - struct rsdt *rsdt = kmap_device((void *)rsdt_addr, 0x4000); - rsdt_parse(rsdt); - -#ifdef KDEBUG - kprintf(LOG_DEBUG "ACPI version: %d\n", rsdp->revision); -#endif /* KDEBUG */ - kprintf(LOG_SUCCESS "ACPI initialized\n"); -} diff --git a/init/descriptor.S b/init/descriptor.S deleted file mode 100644 index 98e4be6..0000000 --- a/init/descriptor.S +++ /dev/null @@ -1,45 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#define __ASM__ -#include -#include - -/* - * Data section - */ -.data - -.global __gdtr -__gdtr: - .word 0 - .quad 0 -.global __gdt -__gdt: - .skip GDT_SIZE - -.global __idtr -__idtr: - .word 0 - .quad 0 -.global __idt -__idt: - .skip IDT_SIZE - -/* - * Code Section - */ -.text - -.global gdt_load -gdt_load: - lgdt __gdtr - ret - -.global idt_load -idt_load: - lidt __idtr - ret - -.global ltr -ltr: - ltr %di - ret diff --git a/init/gdt.c b/init/gdt.c deleted file mode 100644 index c914768..0000000 --- a/init/gdt.c +++ /dev/null @@ -1,72 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include - -void gdt_load(); - -static int gdt_index = 0; -static int tss_index = 0; -static struct tss *tss_table = NULL; - -spinlock_t gdt_lock = 0; - -void gdt_insert(uint8_t offset, uint8_t access, uint8_t flags) -{ - struct gdt_desc *desc = (__gdt + offset); - desc->limit = 0; - desc->base = 0; - desc->base_2 = 0; - desc->base_3 = 0; - - desc->access = access; - desc->flags = flags; - gdt_index++; -} - -uint16_t gdt_insert_tss(uintptr_t rsp0) -{ - spinlock_acquire(&gdt_lock); - - tss_table[tss_index].rsp0 = rsp0; - - struct gdt_desc_sys *desc = (struct gdt_desc_sys *)((struct gdt_desc *)__gdt + gdt_index); - - paddr_t tss_addr = (paddr_t)(tss_table + tss_index); - desc->limit = sizeof(struct tss) - 1; - desc->base = tss_addr & 0xFFFFFF; - desc->base_2 = (tss_addr >> 16) & 0xFF; - desc->base_3 = (tss_addr >> 24) & 0xFF; - desc->base_4 = (tss_addr >> 32) & 0xFFFFFFFF; - desc->access = 0xE9; - desc->flags = 0x00; - - tss_index += 1; - gdt_index += 2; - - spinlock_release(&gdt_lock); - /* return the index of the TSS descriptor */ - return (gdt_index - 2) * sizeof(struct gdt_desc); -} - -void gdt_init() -{ - tss_table = kzalloc(sizeof(struct tss) * 128, ALLOC_KERN); - - gdt_insert(0, 0, 0); - gdt_insert(1, GDT_ACCESS_CODE_RING0, 0xA0); - gdt_insert(2, GDT_ACCESS_DATA_RING0, 0xC0); - gdt_insert(3, GDT_ACCESS_CODE_RING0, 0xA0); - gdt_insert(4, GDT_ACCESS_DATA_RING0, 0xC0); - gdt_insert(5, GDT_ACCESS_CODE_RING0, 0xA0); - gdt_insert(6, GDT_ACCESS_DATA_RING0, 0xC0); - gdt_insert(7, GDT_ACCESS_DATA_RING3, 0xC0); - gdt_insert(8, GDT_ACCESS_CODE_RING3, 0xA0); - - __gdtr.size = (sizeof(__gdt) - 1); - __gdtr.offset = (uint64_t)__gdt; - - gdt_load(); - - kprintf(LOG_SUCCESS "GDT initialized\n"); -} diff --git a/init/irq.c b/init/irq.c deleted file mode 100644 index 70a6327..0000000 --- a/init/irq.c +++ /dev/null @@ -1,182 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include -#include -#include -#include - -#define exception(_i) _exception_##_i -#define exception_decl(_j) void exception(_j)() - -#define irq_decl(_i) void _irq_##_i() -#define __irq(_i) _irq_##_i - -static bool irq_mapped[16] = { false }; -static void *irq_handlers[16] = { NULL }; - -void gate_syscall_int80(); - -exception_decl(0x00); -exception_decl(0x01); -exception_decl(0x02); -exception_decl(0x03); -exception_decl(0x04); -exception_decl(0x05); -exception_decl(0x06); -exception_decl(0x07); -exception_decl(0x08); -exception_decl(0x09); -exception_decl(0x0A); -exception_decl(0x0B); -exception_decl(0x0C); -exception_decl(0x0D); -exception_decl(0x0E); -exception_decl(0x0F); -exception_decl(0x10); -exception_decl(0x11); -exception_decl(0x12); -exception_decl(0x13); -exception_decl(0x14); -exception_decl(0x15); -exception_decl(0x16); -exception_decl(0x17); -exception_decl(0x18); -exception_decl(0x19); -exception_decl(0x1A); -exception_decl(0x1B); -exception_decl(0x1C); -exception_decl(0x1D); -exception_decl(0x1E); -exception_decl(0x1F); - -irq_decl(0x00); -irq_decl(0x01); -irq_decl(0x02); -irq_decl(0x03); -irq_decl(0x04); -irq_decl(0x05); -irq_decl(0x06); -irq_decl(0x07); -irq_decl(0x08); -irq_decl(0x09); -irq_decl(0x0A); -irq_decl(0x0B); -irq_decl(0x0C); -irq_decl(0x0D); -irq_decl(0x0E); -irq_decl(0x0F); - -void idt_load(); /* descriptor.S */ - -void idt_insert(uint16_t gate, uint8_t type, uint8_t ist, uint16_t segment, void *func) -{ - uintptr_t f = (uintptr_t)(func); - struct irqdesc *irqdesc = (__idt + gate); - irqdesc->offset_low = f & 0xFFFF; - irqdesc->offset_mid = ((f >> 0x10) & 0xFFFF); - irqdesc->offset_high = ((f >> 0x20) & 0xFFFFFFFF); - - irqdesc->segment = segment; - irqdesc->ist = ist; - irqdesc->attrs = type; -} - -int irq_map(uint8_t irq, void *func) -{ - if (irq_mapped[irq]) - return 1; - - irq_mapped[irq] = true; - irq_handlers[irq] = func; - - return 0; -} - -void irq_unmap(uint8_t irq) -{ - irq_mapped[irq] = false; - irq_handlers[irq] = NULL; - idt_insert(irq + 0x20, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, NULL); -} - -int irq_highest_free() -{ - for (int i = 14; i >= 0; i--) { - if (!irq_mapped[i]) - return i; - } - - return -1; -} - -void irq(int irq) -{ - if (irq_handlers[irq] != NULL) { - void (*handler)() = irq_handlers[irq]; - handler(); - } -} - -void idt_init() -{ - idt_insert(0x00, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x00)); - idt_insert(0x01, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x01)); - idt_insert(0x02, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x02)); - idt_insert(0x03, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x03)); - idt_insert(0x04, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x04)); - idt_insert(0x05, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x05)); - idt_insert(0x06, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x06)); - idt_insert(0x07, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x07)); - idt_insert(0x08, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x08)); - idt_insert(0x09, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x09)); - idt_insert(0x0A, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x0A)); - idt_insert(0x0B, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x0B)); - idt_insert(0x0C, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x0C)); - idt_insert(0x0D, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x0D)); - idt_insert(0x0E, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x0E)); - idt_insert(0x0F, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x0F)); - idt_insert(0x10, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x10)); - idt_insert(0x11, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x11)); - idt_insert(0x12, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x12)); - idt_insert(0x13, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x13)); - idt_insert(0x14, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x14)); - idt_insert(0x15, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x15)); - idt_insert(0x16, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x16)); - idt_insert(0x17, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x17)); - idt_insert(0x18, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x18)); - idt_insert(0x19, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x19)); - idt_insert(0x1A, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x1A)); - idt_insert(0x1B, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x1B)); - idt_insert(0x1C, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x1C)); - idt_insert(0x1D, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x1D)); - idt_insert(0x1E, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x1E)); - idt_insert(0x1F, GATE_TRAP, 0, GDT_SEGMENT_CODE_RING0, exception(0x1F)); - - idt_insert(0x20, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x00)); - idt_insert(0x21, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x01)); - idt_insert(0x22, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x02)); - idt_insert(0x23, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x03)); - idt_insert(0x24, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x04)); - idt_insert(0x25, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x05)); - idt_insert(0x26, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x06)); - idt_insert(0x27, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x07)); - idt_insert(0x28, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x08)); - idt_insert(0x29, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x09)); - idt_insert(0x2A, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x0A)); - idt_insert(0x2B, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x0B)); - idt_insert(0x2C, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x0C)); - idt_insert(0x2D, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x0D)); - idt_insert(0x2E, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x0E)); - idt_insert(0x2F, GATE_INTR, 0, GDT_SEGMENT_CODE_RING0, __irq(0x0F)); - - idt_insert(0x80, GATE_INTR_DPL3, 0, GDT_SEGMENT_CODE_RING0, gate_syscall_int80); - - irq_map(4, serial_trap); - - __idtr.size = (IDT_SIZE - 1); - __idtr.offset = (uint64_t)__idt; - idt_load(); - - kprintf(LOG_SUCCESS "IDT successfully loaded\n"); -} diff --git a/init/main.c b/init/main.c index 5154e3e..4277070 100644 --- a/init/main.c +++ b/init/main.c @@ -1,264 +1,46 @@ /* SPDX-License-Identifier: GPL-2.0-only */ #include -#include -#include -#include -#include +#include #include -#include -#include -#include -#include -#include -#include +#include +#include -#include -#include -#include -#include -#include +#include -#include -#include +#include +#include -#include -#include +#include -#define LIMINE_INTERNAL_MODULE_REQUIRED (1 << 0) -#include +#include +#include -struct limine_hhdm_request hhdm_req = { .id = LIMINE_HHDM_REQUEST, .revision = 0 }; -struct limine_kernel_file_request module_req = { .id = LIMINE_KERNEL_FILE_REQUEST, .revision = 0 }; -struct limine_smp_request smp_req = { .id = LIMINE_SMP_REQUEST, .revision = 0 }; +struct tty *tty_printf = NULL; -static char *kcmdline; -static char *kpath; -static struct limine_uuid kroot_disk; -static struct limine_uuid kroot_part; - -uintptr_t hhdm_start; -uintptr_t data_end; -uintptr_t bss_start; -uintptr_t bss_end; - -void gdt_load(); -void idt_load(); -void yield(); -void ap_kmain(struct limine_smp_info *info); -void load_stack_and_jump(uintptr_t rsp, uintptr_t rbp, void *func, void *arg); - -uintptr_t kstacks[256] = { 0 }; - -static void do_dummy_proc() -{ - sti(); - while (1) - ; -} - -static inline void kexec(char *cmd) -{ - pid_t pid = elf_load_proc(cmd); - - if (pid < 0) { - kprintf("Failed to load %s: %s\n", cmd, strerror(-pid)); - return; - } - - kprintf("Loaded %s as PID %d\n", cmd, pid); - - struct proc *proc = proc_get(pid); - if (!proc) { - kprintf("Failed to get proc %d\n", pid); - return; - } - - void _return_to_user(struct procregs * regs, paddr_t cr3); - proc_set_current(pid); - _return_to_user(&proc->regs, proc->cr3); -} - -void panic() -{ - kprintf(LOG_ERROR "KERNEL PANIC\n"); - cli(); - while (1) - yield(); -} - -char *kcmdline_get_symbol(const char *sym) -{ - /* symbol=value */ - /* only parse until the space after the value */ - size_t sym_len = strlen(sym); - size_t cmd_len = strlen(kcmdline); - - char *cmdline_copy = kmalloc(cmd_len + 1, ALLOC_KERN); - if (!cmdline_copy) { - return NULL; - } - - strcpy(cmdline_copy, kcmdline); - - char *strtok_last = NULL; - char *token = strtok(cmdline_copy, " ", &strtok_last); - while (token) { - if (!strncmp(token, sym, sym_len)) { - size_t ret_len = strlen(token + sym_len + 1); - char *ret = kzalloc(ret_len + 1, ALLOC_KERN); - if (!ret) { - kfree(cmdline_copy); - return NULL; - } - - strcpy(ret, token + sym_len + 1); - - kfree(cmdline_copy); - return ret; - } - token = strtok(NULL, " ", &strtok_last); - } - - return NULL; -} - -/* kmain - * - * main kernel entry point, executed solely by the BSP - */ void kmain() { - cli(); - hhdm_start = hhdm_req.response->offset; - data_end = (uintptr_t)(&__data_end); - bss_start = (uintptr_t)(&__bss_start); - bss_end = (uintptr_t)(&__bss_end); + /* init tty ASAP */ + requests_init(); + mem_init(); + buddy_init(); + rbt_slab_init(); + device_layer_init(); + tty_layer_init(); - /* Initialize early kernel memory array */ - const uintptr_t one_gb = 0x40000000; - char kmem[one_gb] ALIGN(0x1000); - mem_early_init(kmem, one_gb); + dev_t serial_port = arch_serial_init(); + tty_printf = tty_create("ttyS0", serial_port); - stack_init(); - gdt_init(); - idt_init(); + int rows; + int cols; - struct limine_kernel_file_response *resp = module_req.response; + tty_get_size(tty_printf, &rows, &cols); + tty_setlf(tty_printf); + tty_clear_screen(tty_printf); + tty_set_cursor_pos(tty_printf, 0, 0); - struct limine_file *kfile = (struct limine_file *)((paddr_t)resp->kernel_file | hhdm_start); + /* start the kernel */ - kcmdline = kzalloc(strlen(kfile->cmdline) + 1, ALLOC_KERN); - strcpy(kcmdline, kfile->cmdline); - - kpath = kzalloc(strlen(kfile->path) + 1, ALLOC_KERN); - strcpy(kpath, kfile->path); - - kroot_disk = kfile->gpt_disk_uuid; - kroot_part = kfile->gpt_part_uuid; - -#ifdef KDEBUG - kprintf(LOG_DEBUG "Kernel file: path='%s' cmdline='%s'\n", kpath, kcmdline); - kprintf(LOG_DEBUG "Root partition: disk=%X-%X part=%X-%X\n", kroot_disk.a, kroot_disk.b, kroot_part.a, kroot_part.b); -#endif /* KDEBUG */ - - acpi_init(); - - pci_init(); - /* finished init, now load TSS */ -#ifdef KDEBUG - kprintf(LOG_DEBUG "Inserting TSS for BSP\n"); -#endif - - void *kstack = buddy_alloc(KSTACK_SIZE); - uintptr_t ptr = (uintptr_t)kstack + KSTACK_SIZE - 8; - - uint16_t tss = gdt_insert_tss(ptr); - ltr(tss); - - pic_init(); - apic_init(); - - /* init the application processors */ - struct limine_smp_response *smp_resp = smp_req.response; - proc_init(smp_resp->cpu_count); - void syscall_init(); - syscall_init(); - - ahci_init(); - - char *root_path = kcmdline_get_symbol("root"); - if (!root_path) { - kprintf(LOG_ERROR "No root= parameter specified\n"); - - kerror_print_blkdevs(); - panic(); - } else { - vfs_init(root_path); - } - - devfs_init(); - - sem_t *init_sem = sem_create(0); - - for (unsigned i = 0; i < smp_resp->cpu_count; i++) { - struct limine_smp_info *info = smp_resp->cpus[i]; - info->extra_argument = (uint64_t)init_sem; - - if (info->lapic_id == smp_resp->bsp_lapic_id) - continue; - - info->goto_address = ap_kmain; - } - - /* wait for the application processors to finish their initialization */ - for (unsigned i = 0; i < smp_resp->cpu_count - 1; i++) { - while (sem_trywait(init_sem)) - (void)0; - } - - sem_destroy(init_sem); - exception_init(); - serial_init(); - irq_map(0, trap_sched); - apic_enable_timer(); - - struct proc *dummy_proc = proc_createv(PT_KERN); - proc_init_memory(dummy_proc, 0); - proc_set_flags(dummy_proc, 0x46); - proc_set_exec_addr(dummy_proc, (uintptr_t)do_dummy_proc); - proc_set_state(dummy_proc->pid, PROC_ALLOWSCHED); - - load_stack_and_jump(ptr, ptr, kexec, "/bin/shtest.elf"); -} - -/* kmain for application processors - * - * This code enables basic processor functions and parks the processor, waiting - * for future scheduling - */ -void ap_kmain(struct limine_smp_info *info) -{ - gdt_load(); - idt_load(); - cr3_write(kcr3); - - /* enable the APIC */ - lapic_enable(); - - void *kstack = buddy_alloc(KSTACK_SIZE); - uintptr_t ptr = (uintptr_t)kstack + KSTACK_SIZE - 8; - - kstacks[info->lapic_id] = (uintptr_t)ptr; - - /* insert the TSS for each processor into the GDT */ -#ifdef KDEBUG - kprintf(LOG_DEBUG "Inserting TSS for AP #%d\n", info->lapic_id); -#endif - uint16_t tss = gdt_insert_tss(ptr); - ltr(tss); - - sem_t *init_sem = (sem_t *)info->extra_argument; - sem_post(init_sem); - - load_stack_and_jump(ptr, ptr, yield, NULL); + page_init(); + kprintf(COL_CYAN_BLACK "Welcome to vbos!\n" COL_RESET); + yield(); } diff --git a/init/msr.S b/init/msr.S deleted file mode 100644 index eda137f..0000000 --- a/init/msr.S +++ /dev/null @@ -1,19 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -.global rdmsr -rdmsr: - movl %edi, %ecx - rdmsr - shlq $0x20, %rdx - orq %rdx, %rax - - ret - -.global wrmsr -wrmsr: - movq %rsi, %rdx - shrq $0x20, %rdx - movl %esi, %eax - movl %edi, %ecx - wrmsr - - ret diff --git a/init/pio.c b/init/pio.c deleted file mode 100644 index 56e3285..0000000 --- a/init/pio.c +++ /dev/null @@ -1,23 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include - -#define genio(suffix, type) \ - inline void out##suffix(uint16_t port, type value) \ - { \ - __asm__ volatile("out" #suffix " %0, %1" : : "a"(value), "Nd"(port)); \ - } \ - inline type in##suffix(uint16_t port) \ - { \ - type ret; \ - __asm__ volatile("in" #suffix " %1, %0" : "=a"(ret) : "Nd"(port)); \ - return ret; \ - } - -inline void iowait() -{ - outb(0x80, 0); -} - -genio(b, uint8_t); -genio(w, uint16_t); -genio(l, uint32_t); diff --git a/init/requests.c b/init/requests.c new file mode 100644 index 0000000..7d15cad --- /dev/null +++ b/init/requests.c @@ -0,0 +1,27 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "kernel/requests.h" +#include "limine/limine.h" +#include + +#define REQUEST __attribute__((used, section(".limine_requests"))) static volatile + +REQUEST struct limine_executable_address_request kern_addr_req = { .id = LIMINE_EXECUTABLE_ADDRESS_REQUEST_ID, .revision = 0 }; +REQUEST struct limine_memmap_request memmap_req = { .id = LIMINE_MEMMAP_REQUEST_ID, .revision = 0 }; +REQUEST struct limine_hhdm_request hhdm_req = { .id = LIMINE_HHDM_REQUEST_ID, .revision = 0 }; + +REQUEST u64 limine_base_revision[] = LIMINE_BASE_REVISION(6); + +struct limine_executable_address_response *kern_addr_res = NULL; +struct limine_memmap_response *kern_map_res = NULL; +struct limine_hhdm_response *kern_hhdm_res = NULL; + +uintptr_t hhdm_start = 0; + +void requests_init() +{ + kern_addr_res = kern_addr_req.response; + kern_map_res = memmap_req.response; + kern_hhdm_res = hhdm_req.response; + + hhdm_start = kern_hhdm_res->offset; +} diff --git a/init/trap.c b/init/trap.c deleted file mode 100644 index 4fb2029..0000000 --- a/init/trap.c +++ /dev/null @@ -1,72 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include - -/* explicit handle list */ -void (*exception_handlers[32])(int error) = { NULL }; - -static const char *exception_names[] = { - "Divide-by-zero Error", - "Debug", - "Non-maskable Interrupt", - "Breakpoint", - "Overflow", - "Bound Range Exceeded", - "Invalid Opcode", - "Device Not Available", - "Double Fault", - "Coprocessor Segment Overrun", - "Invalid TSS", - "Segment Not Present", - "Stack-Segment Fault", - "General Protection Fault", - "Page Fault", - "Reserved", - "x87 Floating-Point Exception", - "Alignment Check", - "Machine Check", - "SIMD Floating-Point Exception", - "Virtualization Exception", - "Invalid exception", - "Invalid exception", - "Invalid exception", - "Invalid exception", - "Invalid exception", - "Invalid exception", - "Invalid exception", - "Security Exception", - "Reserved", - "Triple Fault", -}; - -static void exception_page_fault(int err) -{ - uint64_t cr2 = cr2_read(); - - kprintf(LOG_ERROR "Page fault at %Xh, error code %xh\n", cr2, err); -} - -void exception(int vector, int error) -{ - pid_t pid = getpid(); - - kprintf("Process %d terminated: %s(%xh)\n", pid, exception_names[vector], error); - - struct proc *proc = proc_find(pid); - - if (exception_handlers[vector]) - exception_handlers[vector](error); - - if(proc->pid == 0) - panic(); - - proc_set_current(0); - proc_term(pid); - schedule(); -} - -void exception_init() -{ - exception_handlers[0x0E] = exception_page_fault; -} diff --git a/kernel/device.c b/kernel/device.c new file mode 100644 index 0000000..3b5e979 --- /dev/null +++ b/kernel/device.c @@ -0,0 +1,68 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include +#include +#include +#include +#include + +struct dev_info { + dev_t dev; + dev_class_t class; + void *private; + char name[256]; +}; + +static mem_cache_t *dev_info_cache = NULL; + +static rbtree device_tree = { 0 }; + +dev_t device_create(void *private, dev_class_t class, const char *name) +{ + dev_t key = rbt_next_key(&device_tree); + rbnode *node = rbt_insert(&device_tree, key); + + size_t name_len = strlen(name); + + struct dev_info *info = slab_alloc(dev_info_cache); + info->dev = key; + info->private = private; + info->class = class; + memcpy(info->name, name, MIN(name_len, sizeof(info->name) - 1)); + + node->value = (uintptr_t)info; + + return key; +} + +void device_destroy(dev_t dev) +{ + rbnode *dev_node = rbt_search(&device_tree, dev); + struct dev_info *devinfo = (void *)dev_node->value; + + slab_free(dev_info_cache, devinfo); + rbt_delete(&device_tree, dev_node); +} + +dev_class_t device_class(dev_t dev) +{ + rbnode *dev_node = rbt_search(&device_tree, dev); + struct dev_info *devinfo = (void *)dev_node->value; + + return devinfo->class; +} + +void *device_private_info(dev_t dev) +{ + rbnode *dev_node = rbt_search(&device_tree, dev); + struct dev_info *devinfo = (void *)dev_node->value; + + return devinfo->private; +} + +void device_layer_init() +{ + dev_info_cache = slab_create(sizeof(struct dev_info), 16 * KB, 8); + + if (!dev_info_cache) + panic("dev_info_cache allocation failure!\n"); +} diff --git a/lib/atomic.S b/lib/atomic.S deleted file mode 100644 index 6cf4dd9..0000000 --- a/lib/atomic.S +++ /dev/null @@ -1,17 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#define __ASM__ - -/* int atomic_cmpxchg(volatile int *ptr, int cmpval, int newval) */ -.global atomic_cmpxchg -atomic_cmpxchg: - /* if (*ptr == cmpval) *ptr = newval, but atomic :) */ - movl %esi, %eax - lock cmpxchg %edx, (%rdi) - - /* if ZF is set, the exchange was successful */ - jnz nz - xorl %eax, %eax - ret -nz: - movl $1, %eax - ret diff --git a/lib/printf.c b/lib/printf.c new file mode 100644 index 0000000..3634229 --- /dev/null +++ b/lib/printf.c @@ -0,0 +1,925 @@ +/* SPDX-License-Identifier: MIT */ +/////////////////////////////////////////////////////////////////////////////// +// \author (c) Marco Paland (info@paland.com) +// 2014-2019, PALANDesign Hannover, Germany +// +// \license The MIT License (MIT) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// \brief Tiny printf, sprintf and (v)snprintf implementation, optimized for speed on +// embedded systems with a very limited resources. These routines are thread +// safe and reentrant! +// Use this instead of the bloated standard/newlib printf cause these use +// malloc for printf (and may not be thread safe). +// +/////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include + +#include + +#include +#include + +// define this globally (e.g. gcc -DPRINTF_INCLUDE_CONFIG_H ...) to include the +// printf_config.h header file +// default: undefined +#ifdef PRINTF_INCLUDE_CONFIG_H +#include "printf_config.h" +#endif + +// 'ntoa' conversion buffer size, this must be big enough to hold one converted +// numeric number including padded zeros (dynamically created on stack) +// default: 32 byte +#ifndef PRINTF_NTOA_BUFFER_SIZE +#define PRINTF_NTOA_BUFFER_SIZE 32U +#endif + +// 'ftoa' conversion buffer size, this must be big enough to hold one converted +// float number including padded zeros (dynamically created on stack) +// default: 32 byte +#ifndef PRINTF_FTOA_BUFFER_SIZE +#define PRINTF_FTOA_BUFFER_SIZE 32U +#endif + +// support for the floating point type (%f) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_FLOAT +#define PRINTF_SUPPORT_FLOAT +#endif + +// support for exponential floating point notation (%e/%g) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL +#define PRINTF_SUPPORT_EXPONENTIAL +#endif + +// define the default floating point precision +// default: 6 digits +#ifndef PRINTF_DEFAULT_FLOAT_PRECISION +#define PRINTF_DEFAULT_FLOAT_PRECISION 6U +#endif + +// define the largest float suitable to print with %f +// default: 1e9 +#ifndef PRINTF_MAX_FLOAT +#define PRINTF_MAX_FLOAT 1e9 +#endif + +// support for the long long types (%llu or %p) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_LONG_LONG +#define PRINTF_SUPPORT_LONG_LONG +#endif + +// support for the ptrdiff_t type (%t) +// ptrdiff_t is normally defined in as long or long long type +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_PTRDIFF_T +#define PRINTF_SUPPORT_PTRDIFF_T +#endif + +/////////////////////////////////////////////////////////////////////////////// + +// internal flag definitions +#define FLAGS_ZEROPAD (1U << 0U) +#define FLAGS_LEFT (1U << 1U) +#define FLAGS_PLUS (1U << 2U) +#define FLAGS_SPACE (1U << 3U) +#define FLAGS_HASH (1U << 4U) +#define FLAGS_UPPERCASE (1U << 5U) +#define FLAGS_CHAR (1U << 6U) +#define FLAGS_SHORT (1U << 7U) +#define FLAGS_LONG (1U << 8U) +#define FLAGS_LONG_LONG (1U << 9U) +#define FLAGS_PRECISION (1U << 10U) +#define FLAGS_ADAPT_EXP (1U << 11U) + +// import float.h for DBL_MAX +#if defined(PRINTF_SUPPORT_FLOAT) +#include +#endif + +// output function type +typedef void (*out_fct_type)(char character, void *buffer, size_t idx, size_t maxlen); + +// wrapper (used as buffer) for output function type +typedef struct { + void (*fct)(char character, void *arg); + void *arg; +} out_fct_wrap_type; + +// internal buffer output +static inline void _out_buffer(char character, void *buffer, size_t idx, size_t maxlen) +{ + if (idx < maxlen) { + ((char *)buffer)[idx] = character; + } +} + +// internal null output +static inline void _out_null(char character, void *buffer, size_t idx, size_t maxlen) +{ + (void)character; + (void)buffer; + (void)idx; + (void)maxlen; +} + +static inline void _out_char(char character, void *buffer, size_t idx, size_t maxlen) +{ + (void)buffer; + (void)idx; + (void)maxlen; + if (character) { + if (tty_printf) { + tty_putchar(tty_printf, character); + } + } +} + +// internal output function wrapper +static inline void _out_fct(char character, void *buffer, size_t idx, size_t maxlen) +{ + (void)idx; + (void)maxlen; + if (character) { + // buffer is the output fct pointer + ((out_fct_wrap_type *)buffer)->fct(character, ((out_fct_wrap_type *)buffer)->arg); + } +} + +// internal secure strlen +// \return The length of the string (excluding the terminating 0) limited by 'maxsize' +static inline unsigned int _strnlen_s(const char *str, size_t maxsize) +{ + const char *s; + for (s = str; *s && maxsize--; ++s) + ; + return (unsigned int)(s - str); +} + +// internal test if char is a digit (0-9) +// \return true if char is a digit +static inline bool _is_digit(char ch) +{ + return (ch >= '0') && (ch <= '9'); +} + +// internal ASCII string to unsigned int conversion +static unsigned int _atoi(const char **str) +{ + unsigned int i = 0U; + while (_is_digit(**str)) { + i = i * 10U + (unsigned int)(*((*str)++) - '0'); + } + return i; +} + +// output the specified string in reverse, taking care of any zero-padding +static size_t _out_rev(out_fct_type out, char *buffer, size_t idx, size_t maxlen, const char *buf, size_t len, unsigned int width, + unsigned int flags) +{ + const size_t start_idx = idx; + + // pad spaces up to given width + if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) { + for (size_t i = len; i < width; i++) { + out(' ', buffer, idx++, maxlen); + } + } + + // reverse string + while (len) { + out(buf[--len], buffer, idx++, maxlen); + } + + // append pad spaces up to given width + if (flags & FLAGS_LEFT) { + while (idx - start_idx < width) { + out(' ', buffer, idx++, maxlen); + } + } + + return idx; +} + +// internal itoa format +static size_t _ntoa_format(out_fct_type out, char *buffer, size_t idx, size_t maxlen, char *buf, size_t len, bool negative, + unsigned int base, unsigned int prec, unsigned int width, unsigned int flags) +{ + // pad leading zeros + if (!(flags & FLAGS_LEFT)) { + if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { + width--; + } + while ((len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + } + + // handle hash + if (flags & FLAGS_HASH) { + if (!(flags & FLAGS_PRECISION) && len && ((len == prec) || (len == width))) { + len--; + if (len && (base == 16U)) { + len--; + } + } + if ((base == 16U) && !(flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'x'; + } else if ((base == 16U) && (flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'X'; + } else if ((base == 2U) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'b'; + } + if (len < PRINTF_NTOA_BUFFER_SIZE) { + buf[len++] = '0'; + } + } + + if (len < PRINTF_NTOA_BUFFER_SIZE) { + if (negative) { + buf[len++] = '-'; + } else if (flags & FLAGS_PLUS) { + buf[len++] = '+'; // ignore the space if the '+' exists + } else if (flags & FLAGS_SPACE) { + buf[len++] = ' '; + } + } + + return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); +} + +// internal itoa for 'long' type +static size_t _ntoa_long(out_fct_type out, char *buffer, size_t idx, size_t maxlen, unsigned long value, bool negative, + unsigned long base, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_NTOA_BUFFER_SIZE]; + size_t len = 0U; + + // no hash for 0 values + if (!value) { + flags &= ~FLAGS_HASH; + } + + // write if precision != 0 and value is != 0 + if (!(flags & FLAGS_PRECISION) || value) { + do { + const char digit = (char)(value % base); + buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; + value /= base; + } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); + } + + return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); +} + +// internal itoa for 'long long' type +#if defined(PRINTF_SUPPORT_LONG_LONG) +static size_t _ntoa_long_long(out_fct_type out, char *buffer, size_t idx, size_t maxlen, unsigned long long value, bool negative, + unsigned long long base, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_NTOA_BUFFER_SIZE]; + size_t len = 0U; + + // no hash for 0 values + if (!value) { + flags &= ~FLAGS_HASH; + } + + // write if precision != 0 and value is != 0 + if (!(flags & FLAGS_PRECISION) || value) { + do { + const char digit = (char)(value % base); + buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; + value /= base; + } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); + } + + return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); +} +#endif // PRINTF_SUPPORT_LONG_LONG + +#if defined(PRINTF_SUPPORT_FLOAT) + +#if defined(PRINTF_SUPPORT_EXPONENTIAL) +// forward declaration so that _ftoa can switch to exp notation for values > PRINTF_MAX_FLOAT +static size_t _etoa(out_fct_type out, char *buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, + unsigned int flags); +#endif + +// internal ftoa for fixed decimal floating point +static size_t _ftoa(out_fct_type out, char *buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, + unsigned int flags) +{ + char buf[PRINTF_FTOA_BUFFER_SIZE]; + size_t len = 0U; + double diff = 0.0; + + // powers of 10 + static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; + + // test for special values + if (value != value) + return _out_rev(out, buffer, idx, maxlen, "nan", 3, width, flags); + if (value < -DBL_MAX) + return _out_rev(out, buffer, idx, maxlen, "fni-", 4, width, flags); + if (value > DBL_MAX) + return _out_rev(out, buffer, idx, maxlen, (flags & FLAGS_PLUS) ? "fni+" : "fni", (flags & FLAGS_PLUS) ? 4U : 3U, + width, flags); + + // test for very large values + // standard printf behavior is to print EVERY whole number digit -- which could be 100s of characters overflowing your buffers == bad + if ((value > PRINTF_MAX_FLOAT) || (value < -PRINTF_MAX_FLOAT)) { +#if defined(PRINTF_SUPPORT_EXPONENTIAL) + return _etoa(out, buffer, idx, maxlen, value, prec, width, flags); +#else + return 0U; +#endif + } + + // test for negative + bool negative = false; + if (value < 0) { + negative = true; + value = 0 - value; + } + + // set default precision, if not set explicitly + if (!(flags & FLAGS_PRECISION)) { + prec = PRINTF_DEFAULT_FLOAT_PRECISION; + } + // limit precision to 9, cause a prec >= 10 can lead to overflow errors + while ((len < PRINTF_FTOA_BUFFER_SIZE) && (prec > 9U)) { + buf[len++] = '0'; + prec--; + } + + int whole = (int)value; + double tmp = (value - whole) * pow10[prec]; + unsigned long frac = (unsigned long)tmp; + diff = tmp - frac; + + if (diff > 0.5) { + ++frac; + // handle rollover, e.g. case 0.99 with prec 1 is 1.0 + if (frac >= pow10[prec]) { + frac = 0; + ++whole; + } + } else if (diff < 0.5) { + } else if ((frac == 0U) || (frac & 1U)) { + // if halfway, round up if odd OR if last digit is 0 + ++frac; + } + + if (prec == 0U) { + diff = value - (double)whole; + if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) { + // exactly 0.5 and ODD, then round up + // 1.5 -> 2, but 2.5 -> 2 + ++whole; + } + } else { + unsigned int count = prec; + // now do fractional part, as an unsigned number + while (len < PRINTF_FTOA_BUFFER_SIZE) { + --count; + buf[len++] = (char)(48U + (frac % 10U)); + if (!(frac /= 10U)) { + break; + } + } + // add extra 0s + while ((len < PRINTF_FTOA_BUFFER_SIZE) && (count-- > 0U)) { + buf[len++] = '0'; + } + if (len < PRINTF_FTOA_BUFFER_SIZE) { + // add decimal + buf[len++] = '.'; + } + } + + // do whole part, number is reversed + while (len < PRINTF_FTOA_BUFFER_SIZE) { + buf[len++] = (char)(48 + (whole % 10)); + if (!(whole /= 10)) { + break; + } + } + + // pad leading zeros + if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) { + if (width && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { + width--; + } + while ((len < width) && (len < PRINTF_FTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + } + + if (len < PRINTF_FTOA_BUFFER_SIZE) { + if (negative) { + buf[len++] = '-'; + } else if (flags & FLAGS_PLUS) { + buf[len++] = '+'; // ignore the space if the '+' exists + } else if (flags & FLAGS_SPACE) { + buf[len++] = ' '; + } + } + + return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); +} + +#if defined(PRINTF_SUPPORT_EXPONENTIAL) +// internal ftoa variant for exponential floating-point type, contributed by Martijn Jasperse +static size_t _etoa(out_fct_type out, char *buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, + unsigned int flags) +{ + // check for NaN and special values + if ((value != value) || (value > DBL_MAX) || (value < -DBL_MAX)) { + return _ftoa(out, buffer, idx, maxlen, value, prec, width, flags); + } + + // determine the sign + const bool negative = value < 0; + if (negative) { + value = -value; + } + + // default precision + if (!(flags & FLAGS_PRECISION)) { + prec = PRINTF_DEFAULT_FLOAT_PRECISION; + } + + // determine the decimal exponent + // based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c) + union { + uint64_t U; + double F; + } conv; + + conv.F = value; + int exp2 = (int)((conv.U >> 52U) & 0x07FFU) - 1023; // effectively log2 + conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U); // drop the exponent so conv.F is now in [1,2) + // now approximate log10 from the log2 integer part and an expansion of ln around 1.5 + int expval = (int)(0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168); + // now we want to compute 10^expval but we want to be sure it won't overflow + exp2 = (int)(expval * 3.321928094887362 + 0.5); + const double z = expval * 2.302585092994046 - exp2 * 0.6931471805599453; + const double z2 = z * z; + conv.U = (uint64_t)(exp2 + 1023) << 52U; + // compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex + conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14))))); + // correct for rounding errors + if (value < conv.F) { + expval--; + conv.F /= 10; + } + + // the exponent format is "%+03d" and largest value is "307", so set aside 4-5 characters + unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U; + + // in "%g" mode, "prec" is the number of *significant figures* not decimals + if (flags & FLAGS_ADAPT_EXP) { + // do we want to fall-back to "%f" mode? + if ((value >= 1e-4) && (value < 1e6)) { + if ((int)prec > expval) { + prec = (unsigned)((int)prec - expval - 1); + } else { + prec = 0; + } + flags |= FLAGS_PRECISION; // make sure _ftoa respects precision + // no characters in exponent + minwidth = 0U; + expval = 0; + } else { + // we use one sigfig for the whole part + if ((prec > 0) && (flags & FLAGS_PRECISION)) { + --prec; + } + } + } + + // will everything fit? + unsigned int fwidth = width; + if (width > minwidth) { + // we didn't fall-back so subtract the characters required for the exponent + fwidth -= minwidth; + } else { + // not enough characters, so go back to default sizing + fwidth = 0U; + } + if ((flags & FLAGS_LEFT) && minwidth) { + // if we're padding on the right, DON'T pad the floating part + fwidth = 0U; + } + + // rescale the float value + if (expval) { + value /= conv.F; + } + + // output the floating part + const size_t start_idx = idx; + idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP); + + // output the exponent part + if (minwidth) { + // output the exponential symbol + out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen); + // output the exponent value + idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth - 1, + FLAGS_ZEROPAD | FLAGS_PLUS); + // might need to right-pad spaces + if (flags & FLAGS_LEFT) { + while (idx - start_idx < width) + out(' ', buffer, idx++, maxlen); + } + } + return idx; +} +#endif // PRINTF_SUPPORT_EXPONENTIAL +#endif // PRINTF_SUPPORT_FLOAT + +// internal vsnprintf +static int _vsnprintf(out_fct_type out, char *buffer, const size_t maxlen, const char *format, va_list va) +{ + unsigned int flags, width, precision, n; + size_t idx = 0U; + + if (!buffer) { + // use null output function + out = _out_null; + } + + while (*format) { + // format specifier? %[flags][width][.precision][length] + if (*format != '%') { + // no + out(*format, buffer, idx++, maxlen); + format++; + continue; + } else { + // yes, evaluate it + format++; + } + + // evaluate flags + flags = 0U; + do { + switch (*format) { + case '0': + flags |= FLAGS_ZEROPAD; + format++; + n = 1U; + break; + case '-': + flags |= FLAGS_LEFT; + format++; + n = 1U; + break; + case '+': + flags |= FLAGS_PLUS; + format++; + n = 1U; + break; + case ' ': + flags |= FLAGS_SPACE; + format++; + n = 1U; + break; + case '#': + flags |= FLAGS_HASH; + format++; + n = 1U; + break; + default: + n = 0U; + break; + } + } while (n); + + // evaluate width field + width = 0U; + if (_is_digit(*format)) { + width = _atoi(&format); + } else if (*format == '*') { + const int w = va_arg(va, int); + if (w < 0) { + flags |= FLAGS_LEFT; // reverse padding + width = (unsigned int)-w; + } else { + width = (unsigned int)w; + } + format++; + } + + // evaluate precision field + precision = 0U; + if (*format == '.') { + flags |= FLAGS_PRECISION; + format++; + if (_is_digit(*format)) { + precision = _atoi(&format); + } else if (*format == '*') { + const int prec = (int)va_arg(va, int); + precision = prec > 0 ? (unsigned int)prec : 0U; + format++; + } + } + + // evaluate length field + switch (*format) { + case 'l': + flags |= FLAGS_LONG; + format++; + if (*format == 'l') { + flags |= FLAGS_LONG_LONG; + format++; + } + break; + case 'h': + flags |= FLAGS_SHORT; + format++; + if (*format == 'h') { + flags |= FLAGS_CHAR; + format++; + } + break; +#if defined(PRINTF_SUPPORT_PTRDIFF_T) + case 't': + flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; +#endif + case 'j': + flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; + case 'z': + flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; + default: + break; + } + + // evaluate specifier + switch (*format) { + case 'd': + case 'i': + case 'u': + case 'x': + case 'X': + case 'o': + case 'b': { + // set the base + unsigned int base; + if (*format == 'x' || *format == 'X') { + base = 16U; + } else if (*format == 'o') { + base = 8U; + } else if (*format == 'b') { + base = 2U; + } else { + base = 10U; + flags &= ~FLAGS_HASH; // no hash for dec format + } + // uppercase + if (*format == 'X') { + flags |= FLAGS_UPPERCASE; + } + + // no plus or space flag for u, x, X, o, b + if ((*format != 'i') && (*format != 'd')) { + flags &= ~(FLAGS_PLUS | FLAGS_SPACE); + } + + // ignore '0' flag when precision is given + if (flags & FLAGS_PRECISION) { + flags &= ~FLAGS_ZEROPAD; + } + + // convert the integer + if ((*format == 'i') || (*format == 'd')) { + // signed + if (flags & FLAGS_LONG_LONG) { +#if defined(PRINTF_SUPPORT_LONG_LONG) + const long long value = va_arg(va, long long); + idx = _ntoa_long_long(out, buffer, idx, maxlen, + (unsigned long long)(value > 0 ? value : 0 - value), value < 0, base, + precision, width, flags); +#endif + } else if (flags & FLAGS_LONG) { + const long value = va_arg(va, long); + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), + value < 0, base, precision, width, flags); + } else { + const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : + (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : + va_arg(va, int); + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), + value < 0, base, precision, width, flags); + } + } else { + // unsigned + if (flags & FLAGS_LONG_LONG) { +#if defined(PRINTF_SUPPORT_LONG_LONG) + idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, + precision, width, flags); +#endif + } else if (flags & FLAGS_LONG) { + idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, + precision, width, flags); + } else { + const unsigned int value = + (flags & FLAGS_CHAR) ? (unsigned char)va_arg(va, unsigned int) : + (flags & FLAGS_SHORT) ? (unsigned short int)va_arg(va, unsigned int) : + va_arg(va, unsigned int); + idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags); + } + } + format++; + break; + } +#if defined(PRINTF_SUPPORT_FLOAT) + case 'f': + case 'F': + if (*format == 'F') + flags |= FLAGS_UPPERCASE; + idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); + format++; + break; +#if defined(PRINTF_SUPPORT_EXPONENTIAL) + case 'e': + case 'E': + case 'g': + case 'G': + if ((*format == 'g') || (*format == 'G')) + flags |= FLAGS_ADAPT_EXP; + if ((*format == 'E') || (*format == 'G')) + flags |= FLAGS_UPPERCASE; + idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); + format++; + break; +#endif // PRINTF_SUPPORT_EXPONENTIAL +#endif // PRINTF_SUPPORT_FLOAT + case 'c': { + unsigned int l = 1U; + // pre padding + if (!(flags & FLAGS_LEFT)) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + // char output + out((char)va_arg(va, int), buffer, idx++, maxlen); + // post padding + if (flags & FLAGS_LEFT) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + format++; + break; + } + + case 's': { + const char *p = va_arg(va, char *); + unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1); + // pre padding + if (flags & FLAGS_PRECISION) { + l = (l < precision ? l : precision); + } + if (!(flags & FLAGS_LEFT)) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + // string output + while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) { + out(*(p++), buffer, idx++, maxlen); + } + // post padding + if (flags & FLAGS_LEFT) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + format++; + break; + } + + case 'p': { + width = sizeof(void *) * 2U; + flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE; +#if defined(PRINTF_SUPPORT_LONG_LONG) + const bool is_ll = sizeof(uintptr_t) == sizeof(long long); + if (is_ll) { + idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void *), false, 16U, + precision, width, flags); + } else { +#endif + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void *)), false, + 16U, precision, width, flags); +#if defined(PRINTF_SUPPORT_LONG_LONG) + } +#endif + format++; + break; + } + + case '%': + out('%', buffer, idx++, maxlen); + format++; + break; + + default: + out(*format, buffer, idx++, maxlen); + format++; + break; + } + } + + // termination + out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen); + + // return written chars without terminating \0 + return (int)idx; +} + +/////////////////////////////////////////////////////////////////////////////// + +int printf_(const char *format, ...) +{ + va_list va; + va_start(va, format); + char buffer[1]; + const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va); + va_end(va); + return ret; +} + +int sprintf_(char *buffer, const char *format, ...) +{ + va_list va; + va_start(va, format); + const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va); + va_end(va); + return ret; +} + +int snprintf_(char *buffer, size_t count, const char *format, ...) +{ + va_list va; + va_start(va, format); + const int ret = _vsnprintf(_out_buffer, buffer, count, format, va); + va_end(va); + return ret; +} + +int vprintf_(const char *format, va_list va) +{ + char buffer[1]; + return _vsnprintf(_out_char, buffer, (size_t)-1, format, va); +} + +int vsnprintf_(char *buffer, size_t count, const char *format, va_list va) +{ + return _vsnprintf(_out_buffer, buffer, count, format, va); +} + +int fctprintf(void (*out)(char character, void *arg), void *arg, const char *format, ...) +{ + va_list va; + va_start(va, format); + const out_fct_wrap_type out_fct_wrap = { out, arg }; + const int ret = _vsnprintf(_out_fct, (char *)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va); + va_end(va); + return ret; +} diff --git a/lib/rbtree.c b/lib/rbtree.c index 302c7fa..26ef94f 100644 --- a/lib/rbtree.c +++ b/lib/rbtree.c @@ -1,19 +1,20 @@ + /* SPDX-License-Identifier: GPL-2.0-only */ #include #include #include -#include +#include -static slab_t *rbt_slab; +static mem_cache_t *rbt_slab; void rbt_slab_init() { - rbt_slab = slab_create(sizeof(struct rbnode), 1 * MB, 0); + rbt_slab = slab_create(sizeof(rbnode), 1 * MB, 8); } -static void rbt_rotate_right(struct rbtree *tree, struct rbnode *node) +static void rbt_rotate_right(rbtree *tree, rbnode *node) { - struct rbnode *left = node->left; + rbnode *left = node->left; node->left = left->right; if (left->right != NULL) @@ -32,9 +33,9 @@ static void rbt_rotate_right(struct rbtree *tree, struct rbnode *node) node->parent = left; } -static void rbt_rotate_left(struct rbtree *tree, struct rbnode *node) +static void rbt_rotate_left(rbtree *tree, rbnode *node) { - struct rbnode *right = node->right; + rbnode *right = node->right; node->right = right->left; if (right->left != NULL) @@ -54,7 +55,7 @@ static void rbt_rotate_left(struct rbtree *tree, struct rbnode *node) node->parent = right; } -static struct rbnode *rbt_uncle(struct rbnode *node) +static rbnode *rbt_uncle(rbnode *node) { if (node->parent == NULL || node->parent->parent == NULL) return NULL; @@ -65,11 +66,11 @@ static struct rbnode *rbt_uncle(struct rbnode *node) return node->parent->parent->left; } -static void rbt_insert_fixup(struct rbtree *tree, struct rbnode *node) +static void rbt_insert_fixup(rbtree *tree, rbnode *node) { while (node->parent && node->parent->color == RB_RED) { if (node->parent->parent && node->parent == node->parent->parent->left) { - struct rbnode *uncle = rbt_uncle(node); + rbnode *uncle = rbt_uncle(node); if (uncle && uncle->color == RB_RED) { uncle->color = RB_BLACK; node->parent->color = RB_BLACK; @@ -84,7 +85,7 @@ static void rbt_insert_fixup(struct rbtree *tree, struct rbnode *node) rbt_rotate_right(tree, node->parent->parent); } } else { - struct rbnode *uncle = rbt_uncle(node); + rbnode *uncle = rbt_uncle(node); if (uncle && uncle->color == RB_RED) { uncle->color = RB_BLACK; node->parent->color = RB_BLACK; @@ -104,10 +105,10 @@ static void rbt_insert_fixup(struct rbtree *tree, struct rbnode *node) tree->root->color = RB_BLACK; } -struct rbnode *rbt_insert(struct rbtree *tree, uint64_t key) +rbnode *rbt_insert(rbtree *tree, u64 key) { - struct rbnode *node = tree->root; - struct rbnode *parent = NULL; + rbnode *node = tree->root; + rbnode *parent = NULL; while (node != NULL) { parent = node; @@ -120,7 +121,7 @@ struct rbnode *rbt_insert(struct rbtree *tree, uint64_t key) } } - struct rbnode *new = slab_alloc(rbt_slab); + rbnode *new = slab_alloc(rbt_slab); if (new == NULL) return NULL; @@ -131,8 +132,6 @@ struct rbnode *rbt_insert(struct rbtree *tree, uint64_t key) new->color = RB_RED; new->value = 0; - new->value2 = 0; - new->value3 = 0; spinlock_acquire(&tree->lock); @@ -150,7 +149,7 @@ struct rbnode *rbt_insert(struct rbtree *tree, uint64_t key) return new; } -static void rbt_transplant(struct rbtree *tree, struct rbnode *old, struct rbnode *new) +static void rbt_transplant(rbtree *tree, rbnode *old, rbnode *new) { if (old->parent == NULL) tree->root = new; @@ -163,12 +162,12 @@ static void rbt_transplant(struct rbtree *tree, struct rbnode *old, struct rbnod new->parent = old->parent; } -static void rbt_delete_fixup(struct rbtree *tree, struct rbnode *node) +static void rbt_delete_fixup(rbtree *tree, rbnode *node) { if (!node) return; - struct rbnode *sibling = NULL; + rbnode *sibling = NULL; while (node != tree->root && node->color == RB_BLACK) { if (node == node->parent->left) { sibling = node->parent->right; @@ -243,7 +242,7 @@ static void rbt_delete_fixup(struct rbtree *tree, struct rbnode *node) tree->root->color = RB_BLACK; } -struct rbnode *rbt_minimum(struct rbnode *node) +rbnode *rbt_minimum(rbnode *node) { if (node == NULL) return NULL; @@ -254,7 +253,7 @@ struct rbnode *rbt_minimum(struct rbnode *node) return node; } -void rbt_delete(struct rbtree *tree, struct rbnode *del) +void rbt_delete(rbtree *tree, rbnode *del) { spinlock_acquire(&tree->lock); if (!del->left) { @@ -273,8 +272,8 @@ void rbt_delete(struct rbtree *tree, struct rbnode *del) } else { /* case 2: neither is NULL */ - struct rbnode *y = rbt_minimum(del->right); - struct rbnode *x = y->right; + rbnode *y = rbt_minimum(del->right); + rbnode *x = y->right; int orig_color = y->color; if (y->parent == del) { @@ -301,7 +300,7 @@ void rbt_delete(struct rbtree *tree, struct rbnode *del) spinlock_release(&tree->lock); } -void rbt_destroy(struct rbtree *tree) +void rbt_destroy(rbtree *tree) { if (!tree) return; @@ -310,46 +309,9 @@ void rbt_destroy(struct rbtree *tree) rbt_delete(tree, tree->root); } -struct rbnode *rbt_range_val2(struct rbtree *tree, uint64_t sval, uint64_t len) +rbnode *rbt_search(rbtree *tree, u64 key) { - /* find closest node to sval */ - struct rbnode *node = tree->root; - struct rbnode *closest = NULL; - - while (node != NULL) { - if (node->key == sval) { - closest = node; - break; - } else if (node->key < sval) { - closest = node; - node = node->right; - } else { - node = node->left; - } - } - - if (closest == NULL) - return NULL; - - /* check if closest node is in range */ - if (closest->key + closest->value2 > sval) - return closest; - - /* find next node */ - node = rbt_successor(closest); - if (node == NULL) - return NULL; - - /* check if next node is in range */ - if (node->key < sval + len) - return node; - - return NULL; -} - -struct rbnode *rbt_search(struct rbtree *tree, uint64_t key) -{ - struct rbnode *node = tree->root; + rbnode *node = tree->root; while (node != NULL) { if (key < node->key) { @@ -364,13 +326,13 @@ struct rbnode *rbt_search(struct rbtree *tree, uint64_t key) return NULL; } -struct rbnode *rbt_successor(struct rbnode *node) +rbnode *rbt_successor(rbnode *node) { if (node->right != NULL) { return rbt_minimum(node->right); } - struct rbnode *parent = node->parent; + rbnode *parent = node->parent; while (parent != NULL && node == parent->right) { node = parent; parent = parent->parent; @@ -379,10 +341,10 @@ struct rbnode *rbt_successor(struct rbnode *node) return parent; } -uint64_t rbt_next_key(struct rbtree *tree) +u64 rbt_next_key(rbtree *tree) { /* find first available key */ - struct rbnode *node = tree->root; + rbnode *node = tree->root; if (node == NULL) return 0; @@ -391,7 +353,7 @@ uint64_t rbt_next_key(struct rbtree *tree) node = node->left; while (true) { - struct rbnode *next = rbt_successor(node); + rbnode *next = rbt_successor(node); if (next == NULL) { return node->key + 1; } else { @@ -404,7 +366,7 @@ uint64_t rbt_next_key(struct rbtree *tree) } } -void rbtree_print_diagram_fancy(struct rbtree *tree, struct rbnode *node, int indent) +void rbtree_print_diagram_fancy(rbtree *tree, rbnode *node, int indent) { if (node == NULL) { kprintf("\n"); diff --git a/lib/ringbuf.c b/lib/ringbuf.c deleted file mode 100644 index f999977..0000000 --- a/lib/ringbuf.c +++ /dev/null @@ -1,46 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include "kernel/slab.h" -#include -#include - -ringbuf_t *ringbuf_create(size_t size) -{ - ringbuf_t *rb = kzalloc(sizeof(ringbuf_t), ALLOC_KERN); - rb->buf = kmalloc(size, ALLOC_KERN); - rb->size = size; - rb->head = 0; - rb->tail = 0; - return rb; -} - -void ringbuf_destroy(ringbuf_t *rb) -{ - ATTEMPT_FREE(rb->buf); - ATTEMPT_FREE(rb); -} - -size_t ringbuf_write(ringbuf_t *rb, const char *buf, size_t count) -{ - size_t written = 0; - while (count--) { - if ((rb->head + 1) % rb->size == rb->tail) - break; - rb->buf[rb->head] = *buf++; - rb->head = (rb->head + 1) % rb->size; - written++; - } - return written; -} - -size_t ringbuf_read(ringbuf_t *rb, char *buf, size_t count) -{ - size_t read = 0; - while (count--) { - if (rb->head == rb->tail) - break; - *buf++ = rb->buf[rb->tail]; - rb->tail = (rb->tail + 1) % rb->size; - read++; - } - return read; -} diff --git a/lib/sem.c b/lib/sem.c deleted file mode 100644 index e18e2ba..0000000 --- a/lib/sem.c +++ /dev/null @@ -1,38 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include - -sem_t *sem_create(int count) -{ - sem_t *sem = kmalloc(sizeof(sem_t), ALLOC_KERN); - sem->count = count; - sem->lock = 0; - return sem; -} - -void sem_destroy(sem_t *sem) -{ - ATTEMPT_FREE(sem); -} - -int sem_trywait(sem_t *sem) -{ - int ret = 1; - spinlock_acquire(&sem->lock); - - if (sem->count > 0) { - sem->count--; - ret = 0; - } - - spinlock_release(&sem->lock); - return ret; -} - -void sem_post(sem_t *sem) -{ - spinlock_acquire(&sem->lock); - sem->count++; - spinlock_release(&sem->lock); -} diff --git a/lib/sort.c b/lib/sort.c index 07cc0e5..8b6e96f 100644 --- a/lib/sort.c +++ b/lib/sort.c @@ -1,5 +1,6 @@ /* SPDX-License-Identifier: GPL-2.0-only */ -#include +#include +#include static void swap(void *a, void *b, size_t size) { diff --git a/lib/stack.c b/lib/stack.c deleted file mode 100644 index 7818a2c..0000000 --- a/lib/stack.c +++ /dev/null @@ -1,61 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include - -slab_t *stack_slab; - -void stack_init() -{ - stack_slab = slab_create(sizeof(struct stack_node), 16 * KB, 0); -} - -struct stack *stack_create() -{ - struct stack *stack = kmalloc(sizeof(struct stack), ALLOC_KERN); - if (!stack) - return NULL; - - stack->top = NULL; - - return stack; -} - -void stack_push(struct stack *stack, void *data) -{ - struct stack_node *node = slab_alloc(stack_slab); - if (!node) - return; - - node->data = data; - node->next = stack->top; - stack->top = node; -} - -void *stack_pop(struct stack *stack) -{ - if (!stack->top) - return NULL; - - struct stack_node *node = stack->top; - stack->top = node->next; - void *data = node->data; - slab_free(stack_slab, node); - - return data; -} - -void *stack_peek(struct stack *stack) -{ - if (!stack->top) - return NULL; - - return stack->top->data; -} - -void stack_destroy(struct stack *stack) -{ - while (stack->top) - stack_pop(stack); - - kfree(stack); -} diff --git a/lib/stdio.c b/lib/stdio.c deleted file mode 100644 index 901ad27..0000000 --- a/lib/stdio.c +++ /dev/null @@ -1,164 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include - -#include - -#include - -spinlock_t printf_lock = 0; - -static inline void printf_out(char c) -{ - if(c == '\n') - serial_putchar('\r'); - serial_putchar(c); -} - -static int printf_write(const char *restrict s) -{ - char c; - int ret = 0; - while ((c = *s++)) { - printf_out(c); - ret++; - } - return ret; -} - -int vsnprintf(char *str, const char *restrict fmt, size_t size, va_list args) -{ - int ret = 0; - char c; - char *s; - int i; - long l; - unsigned int u; - - int n; - - const char *convert = "0123456789ABCDEF"; - char buf[16] = { 0 }; - char *bufstr = NULL; - - while ((c = *fmt++) && (size_t)ret < size) { - if (c == '%') { - c = *fmt++; - switch (c) { - case '\0': - str[ret] = '\0'; - ret++; - goto out; - case 'd': - i = va_arg(args, int); - - if (i < 0) { - str[ret] = '-'; - ret++; - i = -i; - } - - n = 0; - memset(buf, 0, sizeof(buf)); - - do { - buf[n] = convert[i % 10]; - n++; - } while ((i /= 10)); - - goto printf_reverse; - case 's': - s = va_arg(args, char *); - - bufstr = s; - while ((c = *bufstr++)) { - if ((size_t)ret >= size) - goto out; - str[ret] = c; - ret++; - } - break; - case 'c': - i = va_arg(args, int); - ret++; - str[ret] = i & 0xFF; - break; - case 'x': - u = va_arg(args, int); - - n = 0; - - memset(buf, 0, sizeof(buf)); - - do { - buf[n] = convert[u & 0xF]; - n++; - } while ((u >>= 4)); - - goto printf_reverse; - break; - case 'b': - u = va_arg(args, int); - - n = 0; - - memset(buf, 0, sizeof(buf)); - - str[0] = convert[(u>>4)&0xF]; - str[1] = convert[u&0xF]; - ret += 2; - break; - case 'X': - l = va_arg(args, long); - for (uint64_t j = 0; j < (sizeof(l) << 1); j++) { - int sel = ((sizeof(l) << 1) - j - 1) << 2; - int num = (l >> sel) & 0xF; - if ((size_t)ret >= size) - goto out; - str[ret] = convert[num]; - ret++; - } - break; - default: - printf_out(c); - ret++; - break; -printf_reverse: - for (int j = 0; j < n; j++) { - if ((size_t)ret >= size) - goto out; - str[ret] = buf[(n - 1) - j]; - ret++; - } - break; - } - } else { - str[ret] = c; - ret++; - } - } -out: - va_end(args); - return ret; -} - -int snprintf(char *str, const char *restrict fmt, size_t size, ...) -{ - va_list args; - va_start(args, size); - int ret = vsnprintf(str, fmt, size, args); - va_end(args); - return ret; -} - -int kprintf(const char *restrict fmt, ...) -{ - spinlock_acquire(&printf_lock); - char buf[2048] = { 0 }; - va_list args; - va_start(args, fmt); - int ret = vsnprintf(buf, fmt, 1024, args); - va_end(args); - printf_write(buf); - spinlock_release(&printf_lock); - return ret; -} diff --git a/lib/string.c b/lib/string.c index ed52648..2aca8e5 100644 --- a/lib/string.c +++ b/lib/string.c @@ -1,7 +1,4 @@ /* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include - #include void *memcpy(void *dest, const void *src, size_t num) @@ -161,37 +158,3 @@ bool strempty(const char *s) return true; } -char **strsplit(const char *s, char delim, int *n) -{ - int num = 0; - for (int i = 0; s[i]; i++) { - if (s[i] == delim) - num++; - } - - char **ret = kmalloc((num + 2) * sizeof(char *), ALLOC_KERN); - int idx = 0; - int last = 0; - for (int i = 0; s[i]; i++) { - if (s[i] == delim) { - ret[idx] = kmalloc(i - last + 1, ALLOC_KERN); - memcpy(ret[idx], s + last, i - last); - ret[idx][i - last] = 0; - idx++; - last = i + 1; - - if(ret[idx - 1][0] == 0) { - kfree(ret[idx - 1]); - idx--; - } - } - } - ret[idx] = kmalloc(strlen(s) - last + 1, ALLOC_KERN); - memcpy(ret[idx], s + last, strlen(s) - last); - ret[idx][strlen(s) - last] = 0; - idx++; - ret[idx] = NULL; - if (n) - *n = idx; - return ret; -} diff --git a/limine.conf b/limine.conf new file mode 100644 index 0000000..fce490e --- /dev/null +++ b/limine.conf @@ -0,0 +1,7 @@ +serial: yes +timeout: 1 + +# The entry name that will be displayed in the boot menu. +/vbos + protocol: limine + kernel_path: boot():/kernel.elf diff --git a/linker.ld b/linker.ld index f6db680..20f2952 100644 --- a/linker.ld +++ b/linker.ld @@ -1,12 +1,9 @@ -/* Tell the linker that we want an x86_64 ELF64 output file */ +/* SPDX-License-Identifier: GPL-2.0-only */ OUTPUT_FORMAT(elf64-x86-64) OUTPUT_ARCH(i386:x86-64) -/* We want the symbol _start to be our entry point */ ENTRY(kmain) -/* Define the program headers we want so the bootloader gives us the right */ -/* MMU permissions */ PHDRS { text PT_LOAD FLAGS((1 << 0) | (1 << 2)) ; /* Execute + Read */ @@ -16,24 +13,19 @@ PHDRS SECTIONS { - /* We wanna be placed in the topmost 2GiB of the address space, for optimisations */ - /* and because that is what the Limine spec mandates. */ - /* Any address in this region will do, but often 0xffffffff80000000 is chosen as */ - /* that is the beginning of the region. */ . = 0xffffffff80000000; + __kernel_start = .; .text : { *(.text .text.*) } :text - /* Move to the next memory page for .rodata */ . += CONSTANT(MAXPAGESIZE); .rodata ALIGN (0x1000) : { *(.rodata .rodata.*) } :rodata - /* Move to the next memory page for .data */ . += CONSTANT(MAXPAGESIZE); .data ALIGN (0x1000) : { @@ -41,10 +33,6 @@ SECTIONS __data_end = .; } :data - /* NOTE: .bss needs to be the last thing mapped to :data, otherwise lots of */ - /* unnecessary zeros will be written to the binary. */ - /* If you need, for example, .init_array and .fini_array, those should be placed */ - /* above this. */ .bss : { __bss_start = .; *(COMMON) @@ -52,7 +40,9 @@ SECTIONS __bss_end = .; } :data - /* Discard .note.* and .eh_frame since they may cause issues on some hosts. */ + . = ALIGN(CONSTANT(MAXPAGESIZE)); + __kernel_end = .; + /DISCARD/ : { *(.eh_frame) *(.note .note.*) diff --git a/mem/buddy.c b/mem/buddy.c index 9be6ef9..a726547 100644 --- a/mem/buddy.c +++ b/mem/buddy.c @@ -2,35 +2,33 @@ #include #include -#include +#include #include -#include -#include +#include +#include +#include +#include +#include +#include -struct limine_memmap_request map_req = { .id = LIMINE_MEMMAP_REQUEST, .revision = 0 }; -struct limine_kernel_address_request kern_req = { .id = LIMINE_KERNEL_ADDRESS_REQUEST, .revision = 0 }; +#define BBMAP_FREE 0 +#define BBMAP_SPLIT 1 +#define BBMAP_FULL 2 -#ifdef KDEBUG -static const char *limine_types[] = { "USABLE", "RESERVED", "ACPI_RECLAIMABLE", - "ACPI_NVS", "BAD_MEMORY", "BOOTLOADER_RECLAIMABLE", - "KERN", "FRAMEBUFFER" }; -#endif +#define LEFT 0 +#define RIGHT 1 -static char *kmem; -static size_t kmem_len; +struct buddy_zone { + size_t length; + size_t bitmap_length; + size_t bitmap_max_depth; + size_t pow2len; + spinlock_t lock; + char bitmap[]; +}; -struct page *pml4; - -struct mem_region *mem_regions; -size_t num_regions; - -struct page kdefault_attrs; - -paddr_t kcr3 = 0; - -void *(*alloc_page)(void); - -void page_init(paddr_t kpaddr, uintptr_t kvaddr, size_t kernel_size, struct mem_region *regions, size_t num_regions); +static struct mem_zone *zones; +static size_t n_zones; static void buddy_bitmap_set(char *bitmap, size_t depth, size_t n, int val) { @@ -66,303 +64,214 @@ static uint8_t buddy_bitmap_get(char *bitmap, size_t depth, size_t n) return ret; } -static void buddy_init_region(struct mem_region *region) +static void buddy_bitmap_mark_allocated(struct buddy_zone *zone, uintptr_t addr, size_t size) { - /* 2 bits per page */ - if (!region->usable) + if (npow2(size) != size) { + kerr( "buddy_bitmap_mark_allocated: bad size\n"); return; - - size_t bitmap_size_bytes = (region->len >> 13) + 1; - - struct buddy_region_header *head = (void *)(region->base | hhdm_start); - memset(head->bitmap, 0, bitmap_size_bytes); - - paddr_t usable_end = region->base + region->len; - paddr_t curpos = region->base + sizeof(struct buddy_region_header) + bitmap_size_bytes; - /* align to 4K */ - curpos |= 0xFFF; - curpos += 1; - - head->usable_base = curpos; - head->usable_len = (npow2(usable_end - curpos) >> 1); - head->max_depth = log2(head->usable_len >> 12); -} - -static paddr_t buddy_get_slab(struct buddy_region_header *head, size_t depth, size_t n) -{ - if (depth == 0) { - return head->usable_base; } - return head->usable_base + (n * (head->usable_len >> depth)); + size_t offset = addr - (uintptr_t)zone; + size_t depth = log2(npow2(zone->length)) - log2(size); + size_t n = offset / size; + + buddy_bitmap_set(zone->bitmap, depth, n, BBMAP_FULL); + while (depth > 0) { + size_t buddy_n = n ^ 1; + u8 buddy_state = buddy_bitmap_get(zone->bitmap, depth, buddy_n); + + depth -= 1; + n >>= 1; + + if (buddy_state == BBMAP_FULL) { + buddy_bitmap_set(zone->bitmap, depth, n, BBMAP_FULL); + } else { + u8 parent_state = buddy_bitmap_get(zone->bitmap, depth, n); + + if (parent_state == BBMAP_SPLIT) + break; + + buddy_bitmap_set(zone->bitmap, depth, n, BBMAP_SPLIT); + } + } } -static paddr_t buddy_alloc_traverse(struct buddy_region_header *head, size_t depth, size_t n, size_t tgt_depth) +static void buddy_bitmap_mark_free(struct buddy_zone *zone, uintptr_t addr, size_t size) { - if (depth > tgt_depth) - return 0; - if (tgt_depth > head->max_depth) - return 0; + if (npow2(size) != size) { + kerr( "buddy_bitmap_mark_free: bad size\n"); + return; + } - uint8_t val = buddy_bitmap_get(head->bitmap, depth, n); + size_t offset = addr - ((uintptr_t)zone); + size_t depth = log2(npow2(zone->length)) - log2(size); + size_t n = offset / size; - switch (val) { - case BBMAP_USED: - if (n & 1) + buddy_bitmap_set(zone->bitmap, depth, n, BBMAP_FREE); + + while (depth > 0) { + size_t buddy_n = n ^ 1; + depth -= 1; + n >>= 1; + + u8 buddy_val = buddy_bitmap_get(zone->bitmap, depth + 1, buddy_n); + + if (buddy_val == BBMAP_FREE) { + buddy_bitmap_set(zone->bitmap, depth, n, BBMAP_FREE); + } else { + buddy_bitmap_set(zone->bitmap, depth, n, BBMAP_SPLIT); + break; + } + } +} + +static int buddy_find_recursive(struct buddy_zone *zone, size_t depth, size_t n, size_t tgt_depth, size_t *out_n) +{ + u8 state = buddy_bitmap_get(zone->bitmap, depth, n); + + if (state == BBMAP_FULL) + return -1; + + if (depth == tgt_depth) { + if (state == BBMAP_FREE) { + *out_n = n; return 0; - else - return buddy_alloc_traverse(head, depth, n + 1, tgt_depth); - - break; - case BBMAP_SPLIT: - if (depth == tgt_depth) { - if (n & 1) - return 0; - else - return buddy_alloc_traverse(head, depth, n + 1, tgt_depth); - } else { - paddr_t ret = buddy_alloc_traverse(head, depth + 1, n << 1, tgt_depth); - if (ret) - return ret; - else - return buddy_alloc_traverse(head, depth + 1, (n << 1) + 1, tgt_depth); - } - break; - case BBMAP_FREE: - if (depth == tgt_depth) { - buddy_bitmap_set(head->bitmap, depth, n, BBMAP_USED); - return buddy_get_slab(head, depth, n); - } else { - buddy_bitmap_set(head->bitmap, depth, n, BBMAP_SPLIT); - return buddy_alloc_traverse(head, depth + 1, n << 1, tgt_depth); } + return -1; + } - break; + if (buddy_find_recursive(zone, depth + 1, n << 1, tgt_depth, out_n) == 0) + return 0; + + if (buddy_find_recursive(zone, depth + 1, (n << 1) | 1, tgt_depth, out_n) == 0) + return 0; + + return -1; +} + +static uintptr_t buddy_bitmap_find_free(struct buddy_zone *zone, size_t size) +{ + if (size == 0 || size > zone->pow2len) + return 0; + + size_t s = npow2(size); + size_t tgt_depth = log2(zone->pow2len) - log2(s); + size_t n = 0; + + if (buddy_find_recursive(zone, 0, 0, tgt_depth, &n) == 0) { + return ((uintptr_t)zone) + (n * s); } return 0; } -static paddr_t buddy_alloc_helper(struct buddy_region_header *head, size_t size) +static size_t get_allocation_size(struct buddy_zone *zone, uintptr_t addr) { - if (npow2(size) != size) { - kprintf(LOG_WARN "buddy_alloc: size not a power of 2\n"); + size_t offset = addr - (uintptr_t)zone; + size_t depth = zone->bitmap_max_depth; + + while (depth >= 0) { + size_t n = offset / (PAGE_SIZE << (zone->bitmap_max_depth - depth)); + if (buddy_bitmap_get(zone->bitmap, depth, n) == BBMAP_FULL) + return (PAGE_SIZE << (zone->bitmap_max_depth - depth)); + if (depth == 0) + break; + depth--; } - - if (size < 0x1000) { - kprintf(LOG_WARN "buddy_alloc: size too small\n"); - return 0; - } - - size_t tgt_depth = head->max_depth - log2(size >> 12); - - return buddy_alloc_traverse(head, 0, 0, tgt_depth); + return 0; } -static void buddy_free_helper(struct buddy_region_header *head, paddr_t paddr) +static void *alloc_zone(struct buddy_zone *zone, size_t size) { - /* find the region in the bitmap */ - paddr_t offset = paddr - head->usable_base; - size_t curlen = head->usable_len; - size_t depth = 0; - size_t n = 0; + if (size > npow2(zone->length) >> 1) + return NULL; - size_t lastn = 0; - size_t lastdepth = 0; + size = npow2(size); + uintptr_t ret = buddy_bitmap_find_free(zone, size); + if (ret) + buddy_bitmap_mark_allocated(zone, ret, size); - while (buddy_bitmap_get(head->bitmap, depth, n)) { - lastn = n; - lastdepth = depth; - - depth++; - n <<= 1; - curlen >>= 1; - - if (offset >= curlen) { - offset -= curlen; - n++; - } - } - - n = lastn; - depth = lastdepth; - - /* mark the region as free */ - buddy_bitmap_set(head->bitmap, depth, n, BBMAP_FREE); - - /* merge with adjacent regions */ - while (depth > 0 && (buddy_bitmap_get(head->bitmap, depth, n ^ 1) == BBMAP_FREE)) { - n >>= 1; - depth--; - - buddy_bitmap_set(head->bitmap, depth, n, BBMAP_FREE); - } + return (void *)ret; } void *buddy_alloc(size_t size) { - if (size == 0) - return NULL; + for (int i = 0; i < n_zones; i++) { + struct buddy_zone *zone = (void *)zones[i].virt_base; - /* Linear search because array is small */ - for (size_t i = 0; i < num_regions; i++) { - struct buddy_region_header *head = (void *)(mem_regions[num_regions - i - 1].base | hhdm_start); + spinlock_acquire(&zone->lock); + void *ret = alloc_zone(zone, size); + spinlock_release(&zone->lock); - paddr_t ret = buddy_alloc_helper(head, size); - if (ret != 0) - return (void *)(ret | hhdm_start); + if (ret) + return ret; } - return NULL; } void buddy_free(void *ptr) { - if (ptr == NULL) - return; + uintptr_t addr = (uintptr_t)ptr; - paddr_t paddr = (paddr_t)ptr & ~hhdm_start; + for (int i = 0; i < n_zones; i++) { + struct buddy_zone *zone = (void *)zones[i].virt_base; + uintptr_t start = zones[i].virt_base; + uintptr_t end = start + zones[i].len; - /* Linear search because array is small */ - for (size_t i = 0; i < num_regions; i++) { - struct buddy_region_header *head = (void *)(mem_regions[num_regions - i - 1].base | hhdm_start); - - if (paddr >= head->usable_base && paddr < (head->usable_base + head->usable_len)) { - buddy_free_helper(head, paddr); - return; + spinlock_acquire(&zone->lock); + if (addr >= start && addr <= end) { + size_t alloc_size = get_allocation_size(zone, addr); + buddy_bitmap_mark_free(zone, addr, alloc_size); } + spinlock_release(&zone->lock); } - - /* should never happen */ - assert(0); } -static void *alloc_page_early() +static void buddy_init_zone(struct mem_zone *zone) { - static uintptr_t hwm = 0; - void *r = (void *)(hwm + kmem); - if (hwm >= kmem_len) - kprintf(LOG_ERROR "Out of early kmem\n"); - hwm += 0x1000; - return r; + struct buddy_zone *header = (void *)zone->virt_base; + memset(header, 0, sizeof(*header)); + + header->length = zone->len; + + size_t pow2len = npow2(header->length); + header->bitmap_length = pow2len >> 13; /* 4 bits per page */ + header->pow2len = pow2len; + header->bitmap_max_depth = log2(pow2len / PAGE_SIZE); + memset(header->bitmap, 0, header->bitmap_length); + + size_t zone_meta_size = sizeof(struct buddy_zone) + header->bitmap_length; + buddy_bitmap_mark_allocated(header, zone->virt_base, npow2(zone_meta_size)); + + size_t current_offset = zone->len; + size_t total_end = pow2len; + + while (current_offset < total_end) { + size_t remaining = total_end - current_offset; + + size_t block_size = current_offset & -current_offset; + + if (current_offset == 0) + block_size = pow2len; + + while (block_size > remaining) + block_size >>= 1; + + buddy_bitmap_mark_allocated(header, zone->virt_base + current_offset, block_size); + current_offset += block_size; + } } -static size_t limine_parse_memregions() +static inline void buddy_init_zones() { - size_t ret = 0; - bool last_usable = false; - struct limine_memmap_response *res = map_req.response; - - for (unsigned int i = 0; i < res->entry_count; i++) { - struct limine_memmap_entry *entry = res->entries[i]; - -#ifdef KDEBUG - const char *type_str = "base=%X, len=%X %s\n"; - kprintf(LOG_DEBUG "Memmap entry: "); - kprintf(type_str, entry->base, entry->length, limine_types[entry->type]); -#endif - - switch (entry->type) { - case LIMINE_MEMMAP_KERNEL_AND_MODULES: - ret = entry->length; - last_usable = false; - break; - case LIMINE_MEMMAP_USABLE: - case LIMINE_MEMMAP_ACPI_RECLAIMABLE: - case LIMINE_MEMMAP_BOOTLOADER_RECLAIMABLE: - if (last_usable) { - mem_regions[num_regions - 1].len += entry->length; - } else { - mem_regions[num_regions].base = entry->base; - mem_regions[num_regions].len = entry->length; - mem_regions[num_regions].usable = (entry->type != LIMINE_MEMMAP_KERNEL_AND_MODULES); - num_regions++; - } - - last_usable = true; - break; - default: - if (!last_usable) { - mem_regions[num_regions - 1].len += entry->length; - } else { - mem_regions[num_regions].base = entry->base; - mem_regions[num_regions].len = entry->length; - mem_regions[num_regions].usable = false; - num_regions++; - } - - last_usable = false; - break; - } + for (int i = 0; i < n_zones; i++) { + struct mem_zone *zone = zones + i; + buddy_init_zone(zone); } - - return ret; } -void mem_early_init(char *mem, size_t len) +void buddy_init() { - alloc_page = alloc_page_early; - kmem = mem; - kmem_len = len; - - struct mem_region regions[64]; - mem_regions = regions; - - /* Parse limine physical memory map and build a list of usable regions */ - size_t kernel_size = limine_parse_memregions(); - - uint64_t kpaddr = kern_req.response->physical_base; - uint64_t kvaddr = kern_req.response->virtual_base; - - struct page attrs; - attrs.val = 1; - attrs.rw = 1; - attrs.xd = 0; - - kdefault_attrs.val = attrs.val; - - /* These page tables are initialized on the kernel stack - * - * These will be used to initialize the new memory regions we have - * parsed from the bootloader, at which point we will switch to page - * tables that are allocated in the new regions. - */ - kmap(kpaddr, kvaddr, kernel_size, attrs.val); - - /* Identity map the regions */ - for (unsigned int i = 0; i < num_regions; i++) { - kmap(regions[i].base, regions[i].base | hhdm_start, regions[i].len, attrs.val); - } - - /* Switch to the temporary page tables */ - uintptr_t pml4_paddr = (uintptr_t)pml4; - pml4_paddr &= (~hhdm_start); - struct cr3 cr3 = { .pml4_addr = pml4_paddr >> 12 }; - cr3_write(cr3.val); - - /* Initialize the new regions and allocate space for the permanent - * regions table - */ - bool page_found = false; - for (unsigned int i = 0; i < num_regions; i++) { - if (!regions[i].usable) - continue; - - buddy_init_region(®ions[i]); - - if (!page_found) { - struct buddy_region_header *head = (struct buddy_region_header *)(regions[i].base | hhdm_start); - paddr_t r_alloc = buddy_alloc_helper(head, 0x1000); - if (r_alloc != 0) { - page_found = true; - mem_regions = (void *)(r_alloc | hhdm_start); - } - } - } - - /* copy the regions to the permanent regions table */ - memcpy(mem_regions, regions, sizeof(struct mem_region) * num_regions); - - kprintf(LOG_SUCCESS "Buddy allocator initialized\n"); - page_init(kpaddr, kvaddr, kernel_size, regions, num_regions); + n_zones = mem_get_zones(&zones); + buddy_init_zones(); } diff --git a/mem/mem.c b/mem/mem.c new file mode 100644 index 0000000..dfa72cf --- /dev/null +++ b/mem/mem.c @@ -0,0 +1,58 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include +#include + +static struct mem_zone zones[128]; +static size_t n_zones; + +size_t mem_get_zones(struct mem_zone **ret) +{ + *ret = zones; + return n_zones; +} + +static void mem_init_zones() +{ + struct limine_memmap_response *map = kern_map_res; + + bool last_usable = false; + struct mem_zone *last; + for (int i = 0; i < map->entry_count; i++) { + struct limine_memmap_entry *ent = kern_map_res->entries[i]; + + bool usable; + switch (ent->type) { + case LIMINE_MEMMAP_USABLE: + usable = true; + break; + default: + usable = false; + break; + } + + if (usable) { + struct mem_zone *zone; + size_t zone_vbase = ent->base | hhdm_start; + if (last_usable && last->virt_base + last->len == zone_vbase) { + zone = &zones[n_zones - 1]; + zone->len += ent->length; + } else { + zone = &zones[n_zones]; + zone->virt_base = zone_vbase; + zone->len = ent->length; + n_zones += 1; + } + + last = zone; + } else { + last = NULL; + } + + last_usable = usable; + } +} + +void mem_init() +{ + mem_init_zones(); +} diff --git a/mem/page.c b/mem/page.c index 47cefca..9b166eb 100644 --- a/mem/page.c +++ b/mem/page.c @@ -1,346 +1,133 @@ /* SPDX-License-Identifier: GPL-2.0-only */ -#include "kernel/lock.h" -#include +#include "limine/limine.h" #include +#include #include -#include -#include +#include +#include +#include +#include -static slab_t *page_slab; +struct alloc_entry { + uintptr_t vaddr; + uintptr_t paddr; -extern void *(*alloc_page)(); + size_t len; +}; -struct rbtree *kmap_tree = NULL; -spinlock_t kmap_lock = 0; +static rbtree kmap_tree = { 0 }; +static mem_cache_t *alloc_entry_cache = NULL; +static pgd_t *kpgd; -static void *kmap_alloc_page() +static const char *limine_types[] = { "USABLE", "RESERVED", "ACPI_RECLAIMABLE", + "ACPI_NVS", "BAD_MEMORY", "BOOTLOADER_RECLAIMABLE", + "KERN", "FRAMEBUFFER", "RESERVED_MAPPED" }; + +extern struct limine_executable_address_response *kern_addr_res; +extern struct limine_memmap_response *kern_map_res; + +extern char __kernel_start[]; +extern char __kernel_end[]; + +static void *pt_alloc() { - return slab_alloc(page_slab); -} - -static uint64_t *pagemap_traverse(uint64_t *this_level, size_t next_num, uint64_t attr) -{ - uint64_t *r; - if (!(this_level[next_num] & 1)) { - if (!attr) - return NULL; - r = alloc_page(); - memset(r, 0, 4096); - this_level[next_num] = (((uintptr_t)r | 3) & ~hhdm_start) | (attr & (PAGE_PRESENT | PAGE_USER)); - } else { - r = (void *)((this_level[next_num] & -4096ull) | hhdm_start); - } - return r; -} - -uintptr_t mmap_find_unmapped(struct rbtree *tree, spinlock_t *lock, uintptr_t start, size_t len) -{ - bool kern = len >= hhdm_start; - len = MAX(len, 0x1000); - len = len | 0xFFF; - len += 1; - - spinlock_acquire(lock); - if (tree == NULL) { - spinlock_release(lock); - return 0; - } - - struct rbnode *node = tree->root; - if (node == NULL) { - spinlock_release(lock); - return 0; - } - - /* find the lowest address that is mapped */ - while (node->left != NULL) - node = node->left; - - size_t ret = start; - - while (node != NULL) { - if (ret + len <= node->key) { - struct rbnode *node2 = rbt_successor(node); - if (node2->key <= ret + len) { - ret = node2->key + node2->value2; - node = node2; - continue; - } - spinlock_release(lock); - return ret; - } - - ret = node->key + node->value2; - node = rbt_successor(node); - } - - spinlock_release(lock); - - if (ret >= hhdm_start && !kern) - return 0; + void *ret = buddy_alloc(PAGE_SIZE); + if (!ret) + return NULL; + memset(ret, 0, PAGE_SIZE); return ret; } -void mmap(uintptr_t pml4, struct rbtree *tree, paddr_t paddr, uintptr_t vaddr, size_t len, uint64_t attr) +void page_map(pgd_t *pgd_table, paddr_t paddr, uintptr_t vaddr, size_t len, u64 flags, rbtree *map_tree) { - uint64_t *pdpt; - uint64_t *pdt; - uint64_t *pt; + uintptr_t cur_vaddr = vaddr & PAGE_MASK_LOWER; + paddr_t cur_paddr = paddr & PAGE_MASK_LOWER; - size_t pdpn; - size_t pdn; - size_t ptn; - size_t pn; + size_t num_pages = (len + (vaddr & (PAGE_SIZE - 1)) + (PAGE_SIZE - 1)) / PAGE_SIZE; - len += paddr & 4095; - paddr &= -4096ull; - vaddr &= -4096ull; - - len = (len + 4095) & -4096ull; - - if (tree != NULL) { - struct rbnode *test = NULL; - if ((test = rbt_range_val2(tree, vaddr, len))) { - kprintf(LOG_WARN "mmap: Tried to map already mapped address %X\n", vaddr); - kprintf(LOG_WARN "mmap: overlapping with mapping: %X-%X\n", test->key, test->key + test->value2); - return; + for (size_t i = 0; i < num_pages; i++) { + pgd_t *pgd_entry = &pgd_table[pgd_index(cur_vaddr)]; + if (!(pgd_entry->pgd & PAGE_PRESENT)) { + pgd_entry->pgd = (u64)pt_alloc() | PAGE_PRESENT | PAGE_RW | PAGE_USER; } + pud_t *pud_table = (pud_t *)TO_VIRT(pgd_entry->pgd & PAGE_MASK_LOWER); - struct rbnode *node = rbt_insert(tree, vaddr); - if (node == NULL) { - kprintf(LOG_WARN "mmap: failed to insert node\n"); - return; + pud_t *pud_entry = &pud_table[pud_index(cur_vaddr)]; + if (!(pud_entry->pud & PAGE_PRESENT)) { + pud_entry->pud = (u64)pt_alloc() | PAGE_PRESENT | PAGE_RW | PAGE_USER; } + pmd_t *pmd_table = (pmd_t *)TO_VIRT(pud_entry->pud & PAGE_MASK_LOWER); - node->value = paddr; - node->value2 = len; - node->value3 = attr; - } - - for (; len; len -= 4096, vaddr += 4096, paddr += 4096) { - pn = (vaddr >> 12) & 0x1FF; - ptn = (vaddr >> 21) & 0x1FF; - pdn = (vaddr >> 30) & 0x1FF; - pdpn = (vaddr >> 39) & 0x1FF; - - pdpt = pagemap_traverse((uint64_t *)pml4, pdpn, attr); - pdt = pagemap_traverse(pdpt, pdn, attr); - pt = pagemap_traverse(pdt, ptn, attr); - pt[pn] = paddr | attr; - } -} - -void *proc_mmap(struct proc *proc, paddr_t paddr, uintptr_t vaddr, size_t len, uint64_t attr) -{ - if (vaddr + len >= hhdm_start) { - /* higher-half addresses are only for kernel use, so we need to find a lower address to map to */ - vaddr = mmap_find_unmapped(&proc->page_map, &proc->page_map_lock, 0, len); - } - - /* if the memory address is already mapped */ - if (rbt_search(&proc->page_map, vaddr) != NULL) { - kprintf(LOG_WARN "proc_mmap: Tried to map already mapped address %X\n", vaddr); - return NULL; - } - - spinlock_acquire(&proc->page_map_lock); - mmap(proc->cr3 | hhdm_start, &proc->page_map, paddr, vaddr, len, attr); - spinlock_release(&proc->page_map_lock); - - return (void *)vaddr; -} - -void kmap(paddr_t paddr, uintptr_t vaddr, size_t len, uint64_t attr) -{ - if (pml4 == NULL) { - pml4 = alloc_page(); - assert(pml4 != NULL); - memset(pml4, 0, 0x1000); - } - - spinlock_acquire(&kmap_lock); - mmap((uintptr_t)pml4, kmap_tree, paddr, vaddr, len, attr); - spinlock_release(&kmap_lock); - - /* flush TLB */ - uint64_t cr3 = cr3_read(); - cr3_write(cr3); -} - -void *kmap_device(void *dev_paddr, size_t len) -{ - paddr_t dev = (paddr_t)dev_paddr; - paddr_t dev_page = dev & ~(0xFFF); - uintptr_t vaddr = mmap_find_unmapped(kmap_tree, &kmap_lock, hhdm_start, len); - kmap(dev_page, vaddr, len, PAGE_PCD | PAGE_PWT | PAGE_RW | PAGE_PRESENT); - - vaddr |= (dev & 0xFFF); - return (void *)vaddr; -} - -static bool munmap_check_table(uint64_t *table, uint64_t *parent, size_t n) -{ - for (size_t i = 0; i < 512; i++) { - if (table[i] & 1) { - return false; + pmd_t *pmd_entry = &pmd_table[pmd_index(cur_vaddr)]; + if (!(pmd_entry->pmd & PAGE_PRESENT)) { + pmd_entry->pmd = (u64)pt_alloc() | PAGE_PRESENT | PAGE_RW | PAGE_USER; } + pte_t *pte_table = (pte_t *)TO_VIRT(pmd_entry->pmd & PAGE_MASK_LOWER); + + pte_t *pte_entry = &pte_table[pte_index(cur_vaddr)]; + pte_entry->pte = cur_paddr | flags | PAGE_PRESENT; } - slab_free(page_slab, table); - - if (parent != NULL) - parent[n] = 0; - - return true; } -void munmap(struct rbtree *map_tree, uintptr_t vaddr, uintptr_t pml4_vaddr) +static void map_zones(pgd_t *pgd_table, rbtree *tree, struct alloc_entry *entries, size_t n_entries, u64 flags) { - if (kmap_tree == NULL) - return; + for (size_t i = 0; i < n_entries; i++) { + struct alloc_entry *entry = entries + i; - uint64_t *pdpt; - uint64_t *pdt; - uint64_t *pt; - - size_t pdpn; - size_t pdn; - size_t ptn; - size_t pn; - - struct rbnode *node = rbt_search(map_tree, vaddr); - - if (node == NULL) { - kprintf("kunmap: Tried to unmap unmapped address %X\n", vaddr); - return; + page_map(pgd_table, entry->paddr, entry->vaddr, entry->len, flags, tree); } +} - size_t len = node->value2; - - for (; len; len -= 4096, vaddr += 4096) { - pn = (vaddr >> 12) & 0x1FF; - ptn = (vaddr >> 21) & 0x1FF; - pdn = (vaddr >> 30) & 0x1FF; - pdpn = (vaddr >> 39) & 0x1FF; - - pdpt = pagemap_traverse((uint64_t *)pml4_vaddr, pdpn, 0); - pdt = pagemap_traverse(pdpt, pdn, 0); - pt = pagemap_traverse(pdt, ptn, 0); - pt[pn] = 0; - - if (!munmap_check_table(pt, pdt, ptn)) - continue; - if (!munmap_check_table(pdt, pdpt, pdn)) +static size_t load_hhdm_zones(struct alloc_entry *out, paddr_t *kernel_addr) +{ + size_t n = 0; + struct alloc_entry *last = NULL; + for (size_t i = 0; i < kern_map_res->entry_count; i++) { + struct limine_memmap_entry *entry = kern_map_res->entries[i]; + switch (entry->type) { + case LIMINE_MEMMAP_EXECUTABLE_AND_MODULES: + *kernel_addr = entry->base; + case LIMINE_MEMMAP_USABLE: + case LIMINE_MEMMAP_FRAMEBUFFER: + case LIMINE_MEMMAP_RESERVED_MAPPED: + case LIMINE_MEMMAP_ACPI_RECLAIMABLE: + case LIMINE_MEMMAP_ACPI_NVS: + break; + default: continue; + } - munmap_check_table(pdpt, (uint64_t *)pml4, pdpn); + /* only hhdm-eligible zones make it here */ + + if (last && last->paddr + last->len == entry->base) { + last->len += entry->length; + } else { + last = out + n; + last->paddr = entry->base; + last->vaddr = entry->base | hhdm_start; + last->len = entry->length; + n += 1; + } } - rbt_delete(map_tree, node); + return n; } -void proc_munmap(struct proc *proc, uintptr_t vaddr) +void page_init() { - spinlock_acquire(&proc->page_map_lock); - munmap(&proc->page_map, vaddr, proc->cr3 | hhdm_start); - spinlock_release(&proc->page_map_lock); -} - -paddr_t proc_clone_mmap(struct proc *in, struct proc *out) -{ - /* allocate a new page table */ - out->cr3 = (uintptr_t)buddy_alloc(0x1000); - phys_memcpy((void *)out->cr3, kcr3, 0x1000); - out->cr3 = virt_to_phys(out->cr3, kcr3); - - /* copy all mappings */ - spinlock_acquire(&in->lock); - spinlock_acquire(&out->lock); - - struct rbnode *node = rbt_minimum(in->page_map.root); - - while (node) { - uintptr_t vaddr = node->key; - size_t len = node->value2; - - paddr_t o_paddr = (paddr_t)node->value; - paddr_t paddr = (paddr_t)buddy_alloc(len); - phys_memcpy((void *)paddr, o_paddr, len); - paddr = virt_to_phys(paddr, kcr3); - uint64_t attr = node->value3; - - proc_mmap(out, paddr, vaddr, len, attr); - - node = rbt_successor(node); - } - - spinlock_release(&in->lock); - spinlock_release(&out->lock); - - return out->cr3; -} - -inline uint64_t phys_read(paddr_t paddr) -{ - return *(uint64_t *)(paddr | hhdm_start); -} - -inline void phys_write(paddr_t paddr, uint64_t data) -{ - *(uint64_t *)(paddr | hhdm_start) = data; -} - -inline void *phys_memcpy(void *dest, paddr_t src, size_t num) -{ - memcpy(dest, (void *)(src | hhdm_start), num); - return dest; -} - -paddr_t virt_to_phys(uintptr_t vaddr, paddr_t page_base) -{ - size_t pn = (vaddr >> 12) & 0x1FF; - size_t ptn = (vaddr >> 21) & 0x1FF; - size_t pdn = (vaddr >> 30) & 0x1FF; - size_t pdpn = (vaddr >> 39) & 0x1FF; - - uint64_t *cur = (uint64_t *)(page_base | hhdm_start); - cur = (uint64_t *)((cur[pdpn] & -4096ull) | hhdm_start); - cur = (uint64_t *)((cur[pdn] & -4096ull) | hhdm_start); - cur = (uint64_t *)((cur[ptn] & -4096ull) | hhdm_start); - cur = (uint64_t *)((cur[pn] & -4096ull)); - - return (paddr_t)cur & (~hhdm_start); -} - -void page_init(paddr_t kpaddr, uintptr_t kvaddr, size_t kernel_size, struct mem_region *regions, size_t num_regions) -{ - page_slab = slab_create(0x1000, 4 * MB, SLAB_PAGE_ALIGN); - - /* this inits kmalloc */ - slabtypes_init(); - - /* kmalloc is available after this point */ - kmap_tree = kzalloc(sizeof(struct rbtree), ALLOC_KERN); - - /* initialize and populate the new permanent kernel page tables */ - alloc_page = kmap_alloc_page; - pml4 = NULL; - - uint64_t attrs = PAGE_PRESENT | PAGE_RW; - kmap(kpaddr, kvaddr, kernel_size, attrs); - - attrs |= PAGE_XD; - for (unsigned int i = 0; i < num_regions; i++) { - kmap(regions[i].base, regions[i].base | hhdm_start, regions[i].len, attrs); - } - - paddr_t pml4_paddr = (uintptr_t)pml4; - pml4_paddr &= (~hhdm_start); - - kcr3 = pml4_paddr; - - cr3_write(kcr3); - - /* done */ - kprintf(LOG_SUCCESS "Paging initialized\n"); + alloc_entry_cache = slab_create(sizeof(struct alloc_entry), 64 * KB, 0x8); + kpgd = pt_alloc(); + + struct alloc_entry hhdm_zones[128]; + paddr_t kernel_paddr = 0; + size_t n_hhdm_zones = load_hhdm_zones(hhdm_zones, &kernel_paddr); + + map_zones(kpgd, &kmap_tree, hhdm_zones, n_hhdm_zones, PAGE_PRESENT | PAGE_RW); + + size_t kernel_size = (size_t)__kernel_end - (size_t)__kernel_start; + uintptr_t kernel_start = ((size_t)__kernel_start) & PAGE_MASK_LOWER; + page_map(kpgd, kernel_paddr, kernel_start, kernel_size, PAGE_PRESENT | PAGE_RW, &kmap_tree); + + pgd_load(kpgd); } diff --git a/mem/reg.S b/mem/reg.S deleted file mode 100644 index e9b4bd0..0000000 --- a/mem/reg.S +++ /dev/null @@ -1,34 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ - -#define genrw(reg) \ -.global reg##_read; \ -reg##_read: \ - movq %##reg, %rax; \ - ret; \ -.global reg##_write; \ -reg##_write: \ - movq %rdi, %##reg; \ - ret; - -#define genrww(reg) \ -.global reg##_read; \ -reg##_read: \ - movw %##reg, %ax; \ - ret; \ -.global reg##_write; \ -reg##_write: \ - movw %di, %##reg; \ - ret; - -genrw(rsp) -genrw(rbp) -genrw(cr2) -genrw(cr3) -genrww(ds) - -.global load_stack_and_jump -load_stack_and_jump: - movq %rdi, %rsp - movq %rsi, %rbp - movq %rcx, %rdi - jmp *%rdx diff --git a/mem/slab.c b/mem/slab.c index eb7ee16..5283c55 100644 --- a/mem/slab.c +++ b/mem/slab.c @@ -1,478 +1,107 @@ /* SPDX-License-Identifier: GPL-2.0-only */ -#include #include -#include +#include #include -#include +#include -#define SLAB_ALIGN 7 +#include +#include +#include -#define KMT_DMA 0xDE11A000 - -static size_t slab_sizes[] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096 }; -static slab_t *kslab_cache[ARRAY_SIZE(slab_sizes)]; -static size_t dma_sizes[] = { 0x1000, 0x10000, 0x100000, 0x1000000 }; -static slab_t *slab_cache_dma[ARRAY_SIZE(slab_sizes)]; -static size_t uslab_sizes[] = { 0x1000, 0x4000, 0x8000, 0x10000, 0x20000 }; -static slab_t *uslab_cache[ARRAY_SIZE(slab_sizes)]; - -static struct rbtree kmalloc_tree = { NULL, 0, 0 }; -static struct rbtree umalloc_tree = { NULL, 0, 0 }; - -static inline void slab_range(slab_t *slab, uintptr_t *o_start, uintptr_t *o_end) +mem_cache_t *slab_create(size_t item_size, size_t cache_size, size_t alignment) { - uintptr_t sslab = (uintptr_t)slab; - sslab = (sslab | slab->align) + 1; + mem_cache_t *cache = buddy_alloc(npow2(cache_size)); - *o_start = sslab; - *o_end = sslab + (slab->size * slab->num); -} - -slab_t *slab_create(size_t size, size_t cache_size, uint64_t flags) -{ - if (size < sizeof(uintptr_t)) + if (!cache) return NULL; - slab_t *ret = buddy_alloc(cache_size); - if (ret == NULL) + memset(cache, 0, sizeof(mem_cache_t)); + + size_t pos = (uintptr_t)cache + sizeof(mem_cache_t); + pos -= 1; + pos |= (alignment - 1); + pos += 1; + + pos -= (uintptr_t)cache; + + cache->item_size = item_size; + cache->cache_size = cache_size; + cache->alignment = alignment; + cache->offset = pos; + cache->num_members = (cache_size - pos) / item_size; + cache->num_free = cache->num_members; + cache->next_free = ((uintptr_t)cache) + pos; + + uintptr_t cur_ptr = 0; + for (size_t i = 0; i < cache->num_members - 1; i++) { + cur_ptr = ((uintptr_t)cache) + pos + i * item_size; + *(uintptr_t *)cur_ptr = cur_ptr + item_size; + } + + cur_ptr = (uintptr_t)cache + pos + cache->num_members * item_size; + *(uintptr_t *)cur_ptr = 0; + + return cache; +} + +void *slab_alloc(mem_cache_t *cache) +{ + if (!cache) return NULL; - cache_size = npow2(cache_size); - - /* slab area start position */ - - uintptr_t aret = (uintptr_t)ret; - uintptr_t start = (uintptr_t)ret + sizeof(slab_t); - - if (flags & SLAB_PAGE_ALIGN) { - ret->align = 0xFFF; - } else if (flags & SLAB_DMA_64K) { - ret->align = 0xFFFF; - struct page attrs = kdefault_attrs; - attrs.pcd = 1; - kmap((paddr_t)(ret) & (~hhdm_start), (paddr_t)ret, cache_size, attrs.val); - } else { - ret->align = SLAB_ALIGN; - } - - start -= 1; - start |= ret->align; - start += 1; - - ret->num = (((aret + cache_size) - start) / size); - ret->size = size; - ret->tsize = cache_size; - ret->next = NULL; - ret->prev = NULL; - ret->flags = flags; - ret->nextfree = (uintptr_t *)start; - ret->free = ret->num; - ret->lock = 0; - - uintptr_t *ptr = (uintptr_t *)start; - for (size_t i = 0; i < ret->num; i++) { - *ptr = (uintptr_t)ptr + size; - if (i == ret->num - 1) - *ptr = 0; - ptr = (uintptr_t *)*ptr; - } - - return ret; -} - -void *slab_alloc(slab_t *slab) -{ - if (slab == NULL) - return NULL; - - spinlock_t *lock = &slab->lock; - spinlock_acquire(lock); - if (slab->nextfree == NULL) { - if (slab->next == NULL) { - slab->next = slab_create(slab->size, slab->tsize, slab->flags); - if (slab->next == NULL) { - spinlock_release(lock); - return NULL; - } - slab->next->prev = slab; - } - - void *ret = slab_alloc(slab->next); - spinlock_release(lock); - - return ret; - } - - slab->free--; - uintptr_t *ret = slab->nextfree; - slab->nextfree = (uintptr_t *)*slab->nextfree; - - spinlock_release(lock); - - return ret; -} - -void slab_free(slab_t *slab, void *ptr) -{ - if (slab == NULL) - return; - if (ptr == NULL) - return; - - uintptr_t low = 0; - uintptr_t high = 0; - - spinlock_t *lock = &slab->lock; - spinlock_acquire(lock); - - slab_range(slab, &low, &high); - while ((uintptr_t)ptr < low || (uintptr_t)ptr > high) { - slab_range(slab, &low, &high); - slab = slab->next; - if (slab == NULL) { - spinlock_release(lock); - return; - } - } - - *(uintptr_t *)ptr = (uintptr_t)slab->nextfree; - slab->nextfree = ptr; - slab->free++; - - /* delete the slab if it's empty and not a root slab */ - if (slab->free == slab->num && slab->prev != NULL) { - slab_t *next = slab->next; - slab_t *prev = slab->prev; - - prev->next = next; - if (next != NULL) - next->prev = prev; - - if (slab->flags & SLAB_DMA_64K) { - struct page attrs = kdefault_attrs; - attrs.pcd = 0; - kmap((paddr_t)slab & (~hhdm_start), (paddr_t)slab, slab->tsize, attrs.val); - } - - buddy_free(slab); - } - - spinlock_release(lock); -} - -void kmalloc_init() -{ - for (size_t i = 0; i < ARRAY_SIZE(slab_sizes); i++) - kslab_cache[i] = slab_create(slab_sizes[i], 128 * KB, 0); - for (size_t i = 0; i < ARRAY_SIZE(dma_sizes); i++) - slab_cache_dma[i] = slab_create(dma_sizes[i], 8 * MB, SLAB_DMA_64K); -} - -static void *kmalloc_table(size_t size, size_t *sizes, size_t nsizes, slab_t **cache, bool fb_disable) -{ - slab_t *slab = NULL; void *ret = NULL; - if (size > sizes[nsizes - 1] && !fb_disable) { - ret = buddy_alloc(npow2(size)); + spinlock_acquire(&cache->lock); + + if (cache->num_free > 0) { + u64 *next = (u64 *)cache->next_free; + cache->next_free = *next; + ret = next; + + cache->num_free -= 1; } else { - for (size_t i = 0; i < nsizes; i++) { - if (size <= sizes[i]) { - size = sizes[i]; - slab = cache[i]; - ret = slab_alloc(slab); - break; - } - } - } - - if (ret == NULL) - return NULL; - - struct rbnode *n = rbt_insert(&kmalloc_tree, (uint64_t)ret); - if (n == NULL) { - if (slab != NULL) - slab_free(slab, ret); - else - buddy_free(ret); - return NULL; - } - n->value = (uint64_t)slab; - n->value2 = size; - - return ret; -} - -void *kmalloc(size_t size, uint64_t flags) -{ - void *ret = NULL; - - if (flags & ALLOC_DMA) { - ret = kmalloc_table(size, dma_sizes, ARRAY_SIZE(dma_sizes), slab_cache_dma, true); - if (ret == NULL) { - ret = buddy_alloc(npow2(size)); - if (ret == NULL) - return NULL; - - struct rbnode *n = rbt_insert(&kmalloc_tree, (uint64_t)ret); - if (n == NULL) { - buddy_free(ret); - return NULL; - } - - n->value = 0; - n->value2 = size; - n->value3 = KMT_DMA; + if (!cache->next) { + mem_cache_t *new = slab_create(cache->item_size, cache->cache_size, cache->alignment); + cache->next = new; } - } else { - ret = kmalloc_table(size, slab_sizes, ARRAY_SIZE(slab_sizes), kslab_cache, false); + ret = slab_alloc(cache->next); } + spinlock_release(&cache->lock); + return ret; } -void *kzalloc(size_t size, uint64_t flags) +void slab_free(mem_cache_t *cache, void *ptr) { - void *ret = kmalloc(size, flags); - if (ret == NULL) - return NULL; - - memset(ret, 0, size); - return ret; -} - -void *krealloc(void *ptr, size_t size, uint64_t flags) -{ - /* invalid case 1: ptr is NULL */ - if (ptr == NULL) - return kmalloc(size, flags); - - /* invalid case 2: size is 0 */ - if (size == 0) { - return ptr; - } - - /* invalid case 3: ptr is not allocated by kmalloc */ - struct rbnode *n = rbt_search(&kmalloc_tree, (uint64_t)ptr); - if (n == NULL) { - kprintf(LOG_ERROR "kmalloc: invalid realloc: %X\n", ptr); - return NULL; - } - - /* invalid case 4: size is smaller than the original size */ - size_t old_size = n->value2; - if (size <= old_size) - return ptr; - - /* valid case */ - void *ret = kmalloc(size, flags); - if (ret == NULL) - return NULL; - - memcpy(ret, ptr, old_size); - kfree(ptr); - - return ret; -} - -void kfree(void *ptr) -{ - if (ptr == NULL) - return; - - struct rbnode *n = rbt_search(&kmalloc_tree, (uint64_t)ptr); - if (n == NULL) { - kprintf(LOG_ERROR "kmalloc: invalid free: %X\n", ptr); + if (cache->num_free == cache->num_members) { + kerr( "Invalid free\n"); return; } - slab_t *slab = (slab_t *)n->value; - if (slab != NULL) { - slab_free(slab, ptr); - } else { - buddy_free(ptr); + uintptr_t pptr = (uintptr_t)ptr; + uintptr_t pcache = (uintptr_t)cache; + uintptr_t pcache_start = pcache + cache->offset; - if (n->value3 == KMT_DMA) { - uintptr_t p = (uintptr_t)ptr; - kmap(p & (~hhdm_start), p, n->value2, kdefault_attrs.val); - } - } + spinlock_acquire(&cache->lock); - rbt_delete(&kmalloc_tree, n); -} - -void ufree(struct proc *proc, void *addr) -{ - struct rbnode *n = rbt_search(&proc->umalloc_tree, (uint64_t)addr); - if (n == NULL) { - kprintf(LOG_ERROR "umalloc: invalid free: %X\n", addr); - panic(); - } - - struct proc_allocation *a = (struct proc_allocation *)n->value; - struct proc_mapping *m = a->mappings; - - while (m) { - struct proc_mapping *next = m->next; - if (m->type == PM_BUD) { - buddy_free((void *)(m->paddr | hhdm_start)); - proc_munmap(proc, m->vaddr); - } else if (m->type == PM_SLB) { - slab_free(m->slab, (void *)(m->paddr | hhdm_start)); - proc_munmap(proc, m->vaddr); - } - - kfree(m); - m = next; - } - - rbt_delete(&umalloc_tree, n); - n->value = 0; - kfree(a); -} - -/* It is implied that when you're calling this function, the process is not running */ -void *umalloc(struct proc *proc, size_t size, uint64_t opts, uintptr_t req_addr) -{ - struct proc_allocation *a = kzalloc(sizeof(struct proc_allocation), 0); - - if (a == NULL) - return NULL; - - const size_t max_slab_size = uslab_sizes[ARRAY_SIZE(uslab_sizes) - 1]; - uintptr_t vaddr; - - if (opts & ALLOC_USER_STACK) { - vaddr = proc->stack_start - size; - if (vaddr & 0xFFF) { - kprintf(LOG_ERROR "umalloc: invalid stack size: %X\n", size); - return NULL; - } - proc->stack_start = vaddr; - } else { - if (req_addr) { - vaddr = mmap_find_unmapped(&proc->page_map, &proc->page_map_lock, req_addr, size); + if (pptr >= pcache_start && pptr <= pcache_start + (cache->num_members - 1) * cache->item_size) { + if ((pptr - pcache_start) % cache->item_size) { + kerr( "Invalid_free, slab offset wrong\n"); } else { - vaddr = mmap_find_unmapped(&proc->page_map, &proc->page_map_lock, USER_HEAP_BASE, size); + uintptr_t *p = ptr; + *p = cache->next_free; + cache->next_free = pptr; + + cache->num_free += 1; } - } - - uint64_t attr; - - attr = PAGE_USER | PAGE_PRESENT; - - if (!(opts & ALLOC_USER_RDONLY)) - attr |= PAGE_RW; - - if (!(opts & ALLOC_USER_EXEC)) - attr |= PAGE_XD; - - if (vaddr == 0) - return NULL; - - /* Do the allocation - * - * This part of the allocator decides whether to chain slabs, or to use a buddy allocator - * - * Slab chaining is only used in userspace allocations, and this is the only allocator that - * does it. - */ - if (size > max_slab_size * 256) { - /* Case 1: - * Huge allocation: Just do a buddy_alloc - */ - struct proc_mapping *m = kzalloc(sizeof(struct proc_mapping), 0); - if (m == NULL) { - ufree(proc, a); - return NULL; - } - size = npow2(size); - void *ret = buddy_alloc(size); - - if (ret == NULL) - return NULL; - - a->mappings = m; - a->num_mappings = 1; - - m->vaddr = vaddr; - m->paddr = ((paddr_t)(ret) & (~hhdm_start)); - m->len = size; - m->type = PM_BUD; - m->attr = attr; - - proc_mmap(proc, m->paddr, vaddr, size, attr); } else { - /* Case 2: - * Regular sized allocation: Use slabs - */ - size_t total_alloc = 0; - while (total_alloc < size) { - struct proc_mapping *m = kzalloc(sizeof(struct proc_mapping), 0); - - if (m == NULL) { - ufree(proc, a); - return NULL; - } - - if (a->num_mappings == 0) - a->mappings = m; - else - a->last->next = m; - - a->last = m; - - a->num_mappings++; - - size_t remaining = size - total_alloc; - size_t this_size = uslab_sizes[ARRAY_SIZE(uslab_sizes) - 1]; - size_t this_index = ARRAY_SIZE(uslab_sizes) - 1; - - if (this_size > remaining) { - for (size_t i = 0; i < ARRAY_SIZE(uslab_sizes); i++) { - if (uslab_sizes[i] >= remaining) { - this_size = uslab_sizes[i]; - this_index = i; - break; - } - } - } - - void *ret = slab_alloc(uslab_cache[this_index]); - m->type = PM_SLB; - m->vaddr = vaddr + total_alloc; - m->paddr = ((paddr_t)(ret) & (~hhdm_start)); - m->len = this_size; - m->slab = uslab_cache[this_index]; - m->attr = attr; - - proc_mmap(proc, m->paddr, m->vaddr, m->len, attr); - - total_alloc += this_size; + if (cache->next) { + slab_free(cache->next, ptr); + } else { + kerr( "invalid free: %p\n", ptr); } - - if (opts & ALLOC_USER_STACK) - proc->stack_size += total_alloc; } - struct rbnode *n = rbt_insert(&proc->umalloc_tree, (uint64_t)vaddr); - n->value = (uint64_t)a; - - return (void *)vaddr; -} - -static void umalloc_init() -{ - for (size_t i = 0; i < ARRAY_SIZE(uslab_sizes); i++) - uslab_cache[i] = slab_create(uslab_sizes[i], 4 * MB, SLAB_PAGE_ALIGN); -} - -void slabtypes_init() -{ - rbt_slab_init(); - - umalloc_init(); - - /* LAST! */ - kmalloc_init(); + spinlock_release(&cache->lock); } diff --git a/mem/umem.c b/mem/umem.c deleted file mode 100644 index cdb38d1..0000000 --- a/mem/umem.c +++ /dev/null @@ -1,18 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include - -void copy_to_user(struct proc *proc, void *dst, const void *src, size_t size) -{ - paddr_t ucr3 = proc->cr3; - paddr_t kcr3 = cr3_read(); - - if (kcr3 != ucr3) - cr3_write(ucr3); - - memcpy(dst, src, size); - - if (kcr3 != ucr3) - cr3_write(kcr3); -} diff --git a/sched/entry.S b/sched/entry.S deleted file mode 100644 index c382417..0000000 --- a/sched/entry.S +++ /dev/null @@ -1,447 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ - -#define __ASM__ -#include -#include - -.macro save_context - pushq %rax - pushq %rcx - pushq %rdx - pushq %rsi - pushq %rdi - pushq %r8 - pushq %r9 - pushq %r10 - pushq %r11 - - /* get current task registers */ - call proc_current_regs - - /* save current task registers */ - popq %rdi - movq %rdi, 80(%rax) /* r11 */ - popq %rdi - movq %rdi, 72(%rax) /* r10 */ - popq %rdi - movq %rdi, 64(%rax) /* r9 */ - popq %rdi - movq %rdi, 56(%rax) /* r8 */ - popq %rdi - movq %rdi, 40(%rax) /* rdi */ - popq %rdi - movq %rdi, 32(%rax) /* rsi */ - popq %rdi - movq %rdi, 24(%rax) /* rdx */ - popq %rdi - movq %rdi, 16(%rax) /* rcx */ - popq %rdi - movq %rdi, 0(%rax) /* rax */ - - /* save remaining registers */ - movq %rbx, 8(%rax) - movq %rbp, 48(%rax) - movq %r12, 88(%rax) - movq %r13, 96(%rax) - movq %r14, 104(%rax) - movq %r15, 112(%rax) -.endm - -.macro restore_context - call proc_current_regs - movq 8(%rax), %rbx - movq 16(%rax), %rcx - movq 24(%rax), %rdx - movq 32(%rax), %rsi - movq 40(%rax), %rdi - movq 48(%rax), %rbp - movq 56(%rax), %r8 - movq 64(%rax), %r9 - movq 72(%rax), %r10 - movq 80(%rax), %r11 - movq 88(%rax), %r12 - movq 96(%rax), %r13 - movq 104(%rax), %r14 - movq 112(%rax), %r15 - movq 0(%rax), %rax -.endm - -.macro save_sysretq_frame - movq %rsp, 144(%rax) - pushfq - popq %rdi - movq %rdi, 136(%rax) -.endm - -.macro save_iretq_frame - /* save IRETQ frame */ - popq %rdi - movq %rdi, 120(%rax) - popq %rdi - movq %rdi, 128(%rax) - popq %rdi - /* enable interrupts */ - movq %rdi, 136(%rax) - popq %rdi - movq %rdi, 144(%rax) - popq %rdi - movq %rdi, 152(%rax) -.endm - -.macro restore_iretq_frame - /* restore IRETQ frame */ - pushq %rax - call proc_current_regs - popq %rdi - pushq 152(%rax) - pushq 144(%rax) - pushq 136(%rax) - pushq 128(%rax) - pushq 120(%rax) - movq %rdi, %rax -.endm - -.macro push_regs - pushq %rax - pushq %rbx - pushq %rcx - pushq %rdx - pushq %rsi - pushq %rdi - pushq %rbp - pushq %r8 - pushq %r9 - pushq %r10 - pushq %r11 - pushq %r12 - pushq %r13 - pushq %r14 - pushq %r15 -.endm - -.macro pop_regs - popq %r15 - popq %r14 - popq %r13 - popq %r12 - popq %r11 - popq %r10 - popq %r9 - popq %r8 - popq %rbp - popq %rdi - popq %rsi - popq %rdx - popq %rcx - popq %rbx - popq %rax -.endm - -.macro exception nr - .global _exception_\nr - _exception_\nr: - cli - save_context - save_iretq_frame - movq $\nr, %rdi - movq $0, %rsi - call exception - restore_iretq_frame - restore_context - iretq -.endm - -.macro exception_err nr - .global _exception_\nr - _exception_\nr: - cli - save_context - save_iretq_frame - popq %rsi - pushq %rsi - movq $\nr, %rdi - call exception - restore_iretq_frame - restore_context - iretq -.endm - -.macro irq nr - .global _irq_\nr - _irq_\nr: - cli - save_context - save_iretq_frame - /* call irq handler */ - movq $\nr, %rdi - call irq - restore_iretq_frame - restore_context - iretq -.endm - -.global sti -sti: - sti - ret - -.global cli -cli: - cli - ret - -exception 0x00 -exception 0x01 -exception 0x02 -exception 0x03 -exception 0x04 -exception 0x05 -exception 0x06 -exception 0x07 -exception_err 0x08 -exception 0x09 -exception_err 0x0A -exception_err 0x0B -exception_err 0x0C -exception_err 0x0D -exception_err 0x0E -exception 0x0F -exception 0x10 -exception_err 0x11 -exception 0x12 -exception 0x13 -exception 0x14 -exception_err 0x15 -exception 0x16 -exception 0x17 -exception 0x18 -exception 0x19 -exception 0x1A -exception 0x1B -exception 0x1C -exception_err 0x1D -exception_err 0x1E -exception 0x1F - -irq 0x00 -irq 0x01 -irq 0x02 -irq 0x03 -irq 0x04 -irq 0x05 -irq 0x06 -irq 0x07 -irq 0x08 -irq 0x09 -irq 0x0A -irq 0x0B -irq 0x0C -irq 0x0D -irq 0x0E -irq 0x0F - -.global gate_syscall -gate_syscall: - cli - save_context - save_sysretq_frame - - /* switch to a kernel process */ - movq %rax, %rdi - movq $_gate_syscall_entry_ret, %rsi - call proc_enter_kernel -_gate_syscall_entry_ret: - movq %rdi, %rax - - /* restore argument registers */ - movq 40(%rax), %rdi - movq 32(%rax), %rsi - movq 24(%rax), %rdx - movq 72(%rax), %r10 - movq 56(%rax), %r8 - movq 0(%rax), %rax - - movq %r10, %rcx - movq %rax, %r9 - - call syscall - - /* switch back to user process */ - movq %rax, %rdi - movq $1, %rsi - cli - call proc_leave_kernel - - pushq %rax - - call proc_current_regs - - /* restore sysretq frame */ - movq 120(%rax), %rcx /* RIP */ - movq 136(%rax), %r11 /* RFLAGS */ - - /* switch to user stack */ - popq %rbp - movq 144(%rax), %rsp - - restore_context - - pushq %rbp - movq 48(%rax), %rbp - - /* syscall return code */ - popq %rax - - sysretq - -.global gate_syscall_int80 -gate_syscall_int80: - cli - save_context - save_iretq_frame - - /* switch to a kernel process */ - movq %rax, %rdi - movq $_gate_syscall_int80_entry_ret, %rsi - call proc_enter_kernel -_gate_syscall_int80_entry_ret: - movq %rdi, %rax - - /* restore argument registers */ - movq 40(%rax), %rdi - movq 32(%rax), %rsi - movq 24(%rax), %rdx - movq 72(%rax), %r10 - movq 56(%rax), %r8 - movq 0(%rax), %rax - - movq %r10, %rcx - movq %rax, %r9 - - call syscall - - /* switch back to user process */ - movq %rax, %rdi - movq $1, %rsi - cli - call proc_leave_kernel - - restore_iretq_frame - pushq %rax - restore_context - popq %rax - - iretq - -.global sswtch -sswtch: - save_context - - xorq %rdi, %rdi - movw %ss, %di - movq %rdi, 152(%rax) - pushfq - popq %rdi - movq %rsp, 144(%rax) - movq %rdi, 136(%rax) - xorq %rdi, %rdi - movw %cs, %di - movq %rdi, 128(%rax) - movq $_sswtch_ret, 120(%rax) - - call getpid - movq %rax, %rdi - movq $1, %rsi /* PROC_STOPPED: allow to be scheduled */ - call proc_set_state - - call schedule -_sswtch_ret: - ret - -/* void return_from_irq(struct procregs *regs, paddr_t cr3); */ -.global _return_to_user -_return_to_user: - /* restore IRETQ frame */ - pushq 152(%rdi) - pushq 144(%rdi) - pushq 136(%rdi) - pushq 128(%rdi) - pushq 120(%rdi) - - /* restore task registers */ - movq 0(%rdi), %rax - movq 8(%rdi), %rbx - movq 16(%rdi), %rcx - movq 24(%rdi), %rdx - movq 48(%rdi), %rbp - movq 56(%rdi), %r8 - movq 64(%rdi), %r9 - movq 72(%rdi), %r10 - movq 80(%rdi), %r11 - movq 88(%rdi), %r12 - movq 96(%rdi), %r13 - movq 104(%rdi), %r14 - movq 112(%rdi), %r15 - - /* load new page tables */ - movq %rsi, %cr3 - - /* restore argument registers */ - movq 32(%rdi), %rsi - movq 40(%rdi), %rdi - - iretq - -.global _save_context -_save_context: - pushq %rax - pushq %rcx - pushq %rdx - pushq %rsi - pushq %rdi - pushq %r8 - pushq %r9 - pushq %r10 - pushq %r11 - - /* get current task registers */ - call proc_current_regs - - /* save current task registers */ - popq %rdi - movq %rdi, 80(%rax) /* r11 */ - popq %rdi - movq %rdi, 72(%rax) /* r10 */ - popq %rdi - movq %rdi, 64(%rax) /* r9 */ - popq %rdi - movq %rdi, 56(%rax) /* r8 */ - popq %rdi - movq %rdi, 40(%rax) /* rdi */ - popq %rdi - movq %rdi, 32(%rax) /* rsi */ - popq %rdi - movq %rdi, 24(%rax) /* rdx */ - popq %rdi - movq %rdi, 16(%rax) /* rcx */ - popq %rdi - movq %rdi, 0(%rax) /* rax */ - - /* save remaining registers */ - movq %rbx, 8(%rax) - movq %rbp, 48(%rax) - movq %r12, 88(%rax) - movq %r13, 96(%rax) - movq %r14, 104(%rax) - movq %r15, 112(%rax) - ret - -.global yield -yield: - hlt - ret - -.global reboot -reboot: - movq $0, %rax - movq %rax, %cr3 diff --git a/sched/load.c b/sched/load.c deleted file mode 100644 index 9fb2e9f..0000000 --- a/sched/load.c +++ /dev/null @@ -1,132 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -/* ELF loader */ -#include -#include -#include -#include - -#include - -static const char elf_magic[] = { 0x7F, 'E', 'L', 'F' }; - -int elf_check_compat(char *buf) -{ - if (strncmp(buf, elf_magic, 4)) - return -ENOEXEC; - - Elf64_Ehdr *hdr = (Elf64_Ehdr *)buf; - - /* must be 64-bit */ - if (hdr->e_ident[EI_CLASS] != ELFCLASS64) - return -ENOEXEC; - - /* must be little endian */ - if (hdr->e_ident[EI_DATA] != ELFDATA2LSB) - return -ENOEXEC; - - /* must be executable */ - if (hdr->e_type != ET_EXEC) - return -ENOEXEC; - - /* must be x86_64 */ - if (hdr->e_machine != EM_X86_64) - return -ENOEXEC; - - return 0; -} - -Elf64_Shdr *elf_shdr(Elf64_Ehdr *hdr) -{ - return (Elf64_Shdr *)((uintptr_t)hdr + hdr->e_shoff); -} - -pid_t elf_load_proc(char *fname) -{ - int err; - struct file *file = vfs_open(fname, &err); - - if (!file) - return -ENOENT; - - size_t size = file->vnode->size; - - char *buf = kmalloc(size, ALLOC_KERN); - if (!buf) - return -ENOMEM; - - vfs_read(file, buf, 0, size); - vfs_close(file); - - int ret; - - if ((ret = elf_check_compat(buf))) { - kfree(buf); - return ret; - } - - Elf64_Ehdr *hdr = (Elf64_Ehdr *)buf; - - /* read data and text segments */ - - struct proc *proc = proc_create(); - /* allocate page tables */ - spinlock_acquire(&proc->lock); - proc->cr3 = (uintptr_t)buddy_alloc(0x1000); - - /* map kernel pages */ - memcpy((void *)proc->cr3, (void *)(kcr3 | hhdm_start), 0x1000); - - proc->cr3 &= (~hhdm_start); - - Elf64_Phdr *phdr = (Elf64_Phdr *)(buf + hdr->e_phoff); - for (unsigned int i = 0; i < hdr->e_phnum; i++) { - if (phdr[i].p_type != PT_LOAD) - continue; - - uintptr_t vaddr = phdr[i].p_vaddr; - size_t len = MAX(0x1000, npow2(phdr[i].p_filesz)); - uintptr_t paddr = (uintptr_t)buddy_alloc(len); - uint64_t flags = PAGE_PRESENT | PAGE_USER; - - if (phdr[i].p_flags & PF_W) - flags |= PAGE_RW; - - if (!(phdr[i].p_flags & PF_X)) - flags |= PAGE_XD; - - (void)proc_mmap(proc, paddr & (~hhdm_start), vaddr, len, flags); - memcpy((void *)paddr + (vaddr & 0xFFF), buf + phdr[i].p_offset, phdr[i].p_filesz); - } - - Elf64_Shdr *shdr_list = (Elf64_Shdr *)(buf + hdr->e_shoff); - Elf64_Shdr *shdr_str = &shdr_list[hdr->e_shstrndx]; - - for (unsigned int i = 0; i < hdr->e_shnum; i++) { - Elf64_Shdr *section = &shdr_list[i]; - char *name = buf + shdr_str->sh_offset + section->sh_name; - } - - /* set entry point */ - proc->regs.rip = hdr->e_entry; - proc->regs.rflags = 0x242; - - /* descriptor #7 is the user code segment */ - proc->regs.cs = GDT_SEGMENT_CODE_RING3 | 3; - proc->regs.ss = GDT_SEGMENT_DATA_RING3 | 3; - ds_write(GDT_SEGMENT_DATA_RING3 | 3); - - /* allocate user stack */ - proc->stack_start = USER_STACK_BASE; - proc->stack_size = 0; /* umalloc will grow the stack */ - void *ustack = umalloc(proc, 0x10000, ALLOC_USER_STACK, 0); - - /* set stack pointer */ - proc->regs.rsp = proc->stack_start + proc->stack_size; - proc->regs.rbp = proc->regs.rsp; - - kfree(buf); - - spinlock_release(&proc->lock); - - return proc->pid; -} diff --git a/sched/proc.c b/sched/proc.c deleted file mode 100644 index 7faae9e..0000000 --- a/sched/proc.c +++ /dev/null @@ -1,409 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -#include - -static slab_t *proc_slab; -static struct rbtree *proc_tree; -static pid_t *proc_current; - -static struct proc kernel_procs[256] = { 0 }; - -void _return_to_user(struct procregs *regs, paddr_t cr3); -extern uintptr_t kstacks[256]; -extern slab_t *fd_slab; - -static pid_t pid_counter = 0; -static pid_t kpid_counter = 0; - -struct procregs *proc_current_regs() -{ - if (proc_current[lapic_idno()] == 0) - return &kernel_procs[lapic_idno()].regs; - - struct rbnode *proc_node = rbt_search(proc_tree, proc_current[lapic_idno()]); - - if (proc_node) { - struct proc *ret = (void *)proc_node->value; - - return &ret->regs; - } else { - return NULL; - } -} - -pid_t getpid() -{ - return proc_current[lapic_idno()]; -} - -pid_t getupid() -{ - struct proc *proc = proc_find(getpid()); - - if (proc && proc->buddy_proc) - return proc->buddy_proc->pid; - else - return 0; -} - -void proc_set_state(pid_t pid, uint8_t state) -{ - struct proc *proc = proc_find(pid); - spinlock_acquire(&proc->lock); - proc->state = state; - spinlock_release(&proc->lock); -} - -struct proc *proc_find(pid_t pid) -{ - if (pid == 0) - return &kernel_procs[lapic_idno()]; - - struct rbnode *proc_node = rbt_search(proc_tree, pid); - - if (proc_node) - return (void *)proc_node->value; - else - return NULL; -} - -struct proc *proc_next(struct proc *proc) -{ - struct rbnode *proc_node = rbt_search(proc_tree, proc->pid); - - if (proc_node) - proc_node = rbt_successor(proc_node); - - if (proc_node) { - if (proc_node->key == 0) - goto kernel_proc; - - return (void *)proc_node->value; - } else { -kernel_proc: - return &kernel_procs[lapic_idno()]; - } -} - -void proc_set_current(pid_t pid) -{ - proc_current[lapic_idno()] = pid; -} - -void proc_set_stack(struct proc *proc, uintptr_t base, size_t size) -{ - proc->stack_start = base; - proc->stack_size = size; - - proc->regs.rsp = base + size - 0x10; - proc->regs.rbp = base + size - 0x10; -} - -void proc_set_flags(struct proc *proc, uint64_t flags) -{ - proc->regs.rflags = flags; -} - -void proc_set_exec_addr(struct proc *proc, uintptr_t addr) -{ - proc->regs.rip = addr; -} - -void proc_term(pid_t pid) -{ - if (pid == 1) { - /* reboot */ - reboot(); - } - - struct rbnode *proc_node = rbt_search(proc_tree, pid); - - if (proc_node) { - struct proc *proc = (void *)proc_node->value; - spinlock_acquire(&proc->lock); - - rbt_delete(proc_tree, proc_node); - - struct rbnode *node = rbt_minimum(proc->umalloc_tree.root); - while (node) { - struct rbnode *next = rbt_successor(node); - ufree(proc, (void *)node->key); - node = next; - } - - node = rbt_minimum(proc->page_map.root); - while (node) { - struct rbnode *next = rbt_successor(node); - proc_munmap(proc, node->key); - node = next; - } - - node = rbt_minimum(proc->fd_map.root); - while (node) { - struct rbnode *next = rbt_successor(node); - struct file_descriptor *fdesc = (void *)node->value; - - spinlock_acquire(&fdesc->file->ref_lock); - fdesc->file->refcount--; - if (fdesc->file->refcount == 0) - vfs_close(fdesc->file); - spinlock_release(&fdesc->file->ref_lock); - slab_free(fd_slab, fdesc); - node = next; - } - - buddy_free((void *)((paddr_t)proc->cr3 | hhdm_start)); - rbt_destroy(&proc->page_map); - rbt_destroy(&proc->fd_map); - - slab_free(proc_slab, proc); - } else { - kprintf(LOG_ERROR "proc: proc_term: proc %d not found\n", pid); - panic(); - } -} - -void proc_yield() -{ - struct proc *proc = proc_find(getpid()); - proc_set_current(0); - spinlock_acquire(&proc->lock); - proc->state = PROC_STOPPED; - spinlock_release(&proc->lock); - sti(); - yield(); -} - -void trap_sched() -{ - lapic_eoi(); - schedule(); -} - -void schedule() -{ - uint8_t id = lapic_idno(); - - struct proc *proc = proc_find(proc_current[id]); - - if (proc && proc->state == PROC_RUNNING) { - spinlock_acquire(&proc->lock); - proc->state = PROC_STOPPED; - spinlock_release(&proc->lock); - } - - size_t num_procs = proc_tree->num_nodes; - size_t counter = 0; - size_t limit = num_procs * 2; - while (counter < limit) { - /* next process */ - proc = proc_next(proc); - - if (proc->pid == 0) - continue; - - spinlock_acquire(&proc->lock); - - switch (proc->state) { - case PROC_STOPPED: - - proc->state = PROC_RUNNING; - proc_set_current(proc->pid); - spinlock_release(&proc->lock); - _return_to_user(&proc->regs, proc->cr3); - break; - case PROC_ZOMBIE: - case PROC_BLOCKED: - case PROC_RUNNING: - spinlock_release(&proc->lock); - break; - } - } - - /* no process to run */ - sti(); - yield(); -} - -void proc_init_page_tables(struct proc *proc) -{ - proc->cr3 = (uintptr_t)buddy_alloc(0x1000); - phys_memcpy((void *)proc->cr3, kcr3, 0x1000); - proc->cr3 = virt_to_phys(proc->cr3, kcr3); -} - -void proc_init_memory(struct proc *proc, uint64_t mem_flags) -{ - if (proc->is_kernel && proc->buddy_proc) { - proc->cr3 = proc->buddy_proc->cr3; - } else { - proc->cr3 = (uintptr_t)buddy_alloc(0x1000); - memcpy((void *)proc->cr3, (void *)(kcr3 | hhdm_start), 0x1000); - proc->cr3 &= ~(hhdm_start); - } - - uintptr_t stackaddr = (uintptr_t)buddy_alloc(0x4000); - proc->stack_start = stackaddr; - - if (!proc->is_kernel) { - - proc->regs.cs = GDT_SEGMENT_CODE_RING3 | 3; - proc->regs.ss = GDT_SEGMENT_DATA_RING3 | 3; - } else { - proc->regs.cs = GDT_SEGMENT_CODE_RING0 | 0; - proc->regs.ss = GDT_SEGMENT_DATA_RING0 | 0; - } - - proc->regs.rflags = 0x246; - proc_set_stack(proc, stackaddr, 0x4000); -} - -struct proc *proc_createv(int flags) -{ - struct proc *proc = slab_alloc(proc_slab); - memset(proc, 0, sizeof(struct proc)); - - spinlock_acquire(&proc->lock); - - if (flags & PT_KERN) { - kpid_counter++; - proc->pid = -kpid_counter; - proc->is_kernel = true; - proc->regs.cs = GDT_SEGMENT_CODE_RING0 | 0; - proc->regs.ss = GDT_SEGMENT_DATA_RING0 | 0; - } else { - pid_counter++; - proc->pid = pid_counter; - proc->is_kernel = false; - proc->regs.cs = GDT_SEGMENT_CODE_RING3 | 3; - proc->regs.ss = GDT_SEGMENT_DATA_RING3 | 3; - } - - proc->state = PROC_RUNNING; /* prevent immediate scheduling */ - struct rbnode *proc_node = rbt_insert(proc_tree, proc->pid); - proc_node->value = (uintptr_t)proc; - - spinlock_release(&proc->lock); - - return proc; -} - -struct proc *proc_create() -{ - return proc_createv(PT_USER); -} - -struct proc *proc_get(pid_t pid) -{ - struct rbnode *proc_node = rbt_search(proc_tree, pid); - - if (proc_node) - return (void *)proc_node->value; - else - return NULL; -} - -void proc_enter_kernel(uint64_t save, void *ret) -{ - struct proc *proc = proc_find(getpid()); - - if (proc->is_kernel) { - kprintf(LOG_ERROR "proc: proc_enter_kernel: process %d is already a kernel process\n", getpid()); - panic(); - } - - struct proc *kernel_proc; - if (proc->buddy_proc) { - kernel_proc = proc->buddy_proc; - } else { - kernel_proc = proc_createv(PT_KERN); - - kernel_proc->is_kernel = true; - kernel_proc->buddy_proc = proc; - } - - proc_init_memory(kernel_proc, PAGE_PRESENT | PAGE_RW); - - spinlock_acquire(&proc->lock); - proc->state = PROC_BLOCKED; - spinlock_release(&proc->lock); - - proc->buddy_proc = kernel_proc; - kernel_proc->buddy_proc = proc; - - /* move the save value into RAX */ - kernel_proc->regs.rax = save; - proc_set_current(kernel_proc->pid); - load_stack_and_jump(kernel_proc->regs.rsp, kernel_proc->regs.rbp, ret, (void *)save); -} - -uint64_t proc_leave_kernel(uint64_t ret, bool shouldret) -{ - struct proc *proc = proc_find(getpid()); - - if (!proc->is_kernel) { - kprintf(LOG_ERROR "proc: proc_leave_kernel: process %d is not a kernel process\n", getpid()); - panic(); - } - - struct proc *uproc = proc->buddy_proc; - - if (shouldret) { - uproc->regs.rax = ret; - } - - proc_set_current(uproc->pid); - - spinlock_acquire(&proc->lock); - proc->state = PROC_BLOCKED; - spinlock_release(&proc->lock); - - spinlock_acquire(&uproc->lock); - uproc->state = PROC_RUNNING; - spinlock_release(&uproc->lock); - - return ret; -} - -void proc_init(unsigned num_cpus) -{ - /* allocate current process structs */ - proc_current = kzalloc(num_cpus * sizeof(pid_t), ALLOC_KERN); - proc_tree = kzalloc(sizeof(struct rbtree), ALLOC_KERN); - proc_slab = slab_create(sizeof(struct proc), 32 * KB, 0); - - for (unsigned i = 0; i < num_cpus; i++) { - proc_current[i] = -1; - - struct proc *proc = &kernel_procs[i]; - - proc->pid = 0; - proc->is_kernel = true; - proc->cr3 = kcr3; - - proc->regs.rip = (uint64_t)yield; - proc->regs.cs = 0x28; - proc->regs.rflags = 0x246; - proc->regs.rsp = kstacks[i] + 0xFF0; - - proc_current[i] = 0; - } - - /* ensure that the first process has PID 0 - * this value is never actually used, it prevents other processes from - * having PID 0 - */ - proc_set_current(0); - (void)rbt_insert(proc_tree, 0); -} diff --git a/sched/syscall.c b/sched/syscall.c deleted file mode 100644 index 0535148..0000000 --- a/sched/syscall.c +++ /dev/null @@ -1,333 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define SYSCALL_MAX 0x100 - -typedef uint64_t (*syscall_t)(uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5); - -syscall_t syscall_table[SYSCALL_MAX]; -slab_t *fd_slab; - -void gate_syscall(); - -uint64_t syscall(uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5, uint64_t syscall_no) -{ - syscall_t sc_sel = (void *)syscall_table[syscall_no]; - - if (sc_sel == NULL) - return -ENOSYS; - - struct proc *proc = proc_find(getpid()); - if (proc == NULL) - return -1; - - uint64_t ret = sc_sel(arg1, arg2, arg3, arg4, arg5); - - return ret; -} - -void sys_set_return(struct proc *proc, uint64_t ret) -{ - if (proc == NULL) - return; - - proc->regs.rax = ret; -} - -ssize_t sys_read(int fd, void *buf, size_t count) -{ - if ((uintptr_t)buf >= hhdm_start) - return -EFAULT; - - struct proc *proc = proc_find(getupid()); - if (proc == NULL) - return -1; - - struct rbnode *fdesc_node = rbt_search(&proc->fd_map, fd); - - if (fdesc_node == NULL) - return -EBADF; - - struct file_descriptor *fdesc = (void *)fdesc_node->value; - struct file *file = fdesc->file; - void *tmp_buf = kzalloc(count, ALLOC_KERN); - if (tmp_buf == NULL) - return -ENOMEM; - - ssize_t ret = vfs_read(file, tmp_buf, fdesc->pos, count); - - if (ret > 0) - memcpy(buf, tmp_buf, count); - else - ret = -1; - - fdesc->pos += ret; - - kfree(tmp_buf); - return ret; -} - -ssize_t sys_write(int fd, void *buf, size_t count) -{ - if ((uintptr_t)buf >= hhdm_start) - return -EFAULT; - - struct proc *proc = proc_find(getupid()); - if (proc == NULL) - return -1; - - struct rbnode *fdesc_node = rbt_search(&proc->fd_map, fd); - - if (fdesc_node == NULL) - return -EBADF; - - struct file_descriptor *fdesc = (void *)fdesc_node->value; - struct file *file = fdesc->file; - - void *tmp_buf = kzalloc(count, ALLOC_KERN); - if (tmp_buf == NULL) - return -ENOMEM; - - memcpy(tmp_buf, buf, count); - ssize_t ret = vfs_write(file, tmp_buf, fdesc->pos, count); - - if (ret < 0) - ret = -1; - kfree(tmp_buf); - return ret; -} - -int sys_open(const char *pathname, int flags) -{ - if ((uintptr_t)pathname >= hhdm_start) - return -EFAULT; - - struct proc *proc = proc_find(getupid()); - if (proc == NULL) - return -1; - - int err; - struct file *file = vfs_open(pathname, &err); - if (file == NULL) - return err; - - struct file_descriptor *fdesc = slab_alloc(fd_slab); - uint64_t fdno = rbt_next_key(&proc->fd_map); - - fdesc->fd = fdno; - fdesc->file = file; - fdesc->pos = 0; - fdesc->flags = flags; - - spinlock_acquire(&file->ref_lock); - file->refcount++; - spinlock_release(&file->ref_lock); - - struct rbnode *node = rbt_insert(&proc->fd_map, fdno); - node->value = (uintptr_t)fdesc; - - return fdno; -} - -void sys_exit(int status) -{ - pid_t pid = getupid(); - struct proc *proc = proc_find(pid); - if (proc == NULL) - return; - - proc_term(pid); - - proc_set_current(0); - schedule(); -} - -pid_t sys_fork() -{ - struct proc *parent = proc_find(getupid()); - struct proc *proc = proc_create(); - - proc_clone_mmap(parent, proc); - - /* copy file descriptors */ - struct rbnode *node = rbt_minimum(parent->fd_map.root); - while (node) { - struct file_descriptor *fdesc = (void *)node->value; - struct file *file = fdesc->file; - - struct file_descriptor *new_fdesc = slab_alloc(fd_slab); - new_fdesc->fd = fdesc->fd; - new_fdesc->file = file; - new_fdesc->pos = fdesc->pos; - new_fdesc->flags = fdesc->flags; - - spinlock_acquire(&file->ref_lock); - file->refcount++; - spinlock_release(&file->ref_lock); - - struct rbnode *new_node = rbt_insert(&proc->fd_map, fdesc->fd); - new_node->value = (uintptr_t)new_fdesc; - - node = rbt_successor(node); - } - - /* copy parent */ - proc->parent = parent; - proc->regs = parent->regs; - sys_set_return(proc, 0); - - proc->state = PROC_STOPPED; - - return proc->pid; -} - -int sys_lsdir(int dirfd, struct dirent *dirents, size_t buf_size) -{ - struct proc *proc = proc_find(getupid()); - if (proc == NULL) - return -1; - - struct rbnode *fdesc_node = rbt_search(&proc->fd_map, dirfd); - - if (fdesc_node == NULL) - return -EBADF; - - struct file_descriptor *fdesc = (void *)fdesc_node->value; - struct file *file = fdesc->file; - struct vnode *vnode = file->vnode; - - if (vnode == NULL) - return -1; - - if ((vnode->flags & VFS_VTYPE_MASK) != VFS_VNO_DIR) - return -ENOTDIR; - - size_t num_dirents = vnode->num_dirents; - int ret = MIN(num_dirents, buf_size / sizeof(struct dirent)); - - for(int i = 0; i < ret; i++) { - struct dirent *dirent = &vnode->dirents[i]; - memcpy(&dirents[i], dirent, sizeof(struct dirent)); - - /* don't leak kernel pointers */ - dirents[i].vnode = NULL; - } - - return ret; -} - -int sys_mkdir(const char *pathname, mode_t mode) -{ - struct vnode *parent; - - char *path_copy = kzalloc(strlen(pathname) + 1, ALLOC_KERN); - strcpy(path_copy, pathname); - - char *name = basename(path_copy); - char *dir = dirname(path_copy); - - struct file *parent_file; - int err; - - if (strempty(dir)) - parent_file = vfs_open("/", &err); - else - parent_file = vfs_open(dir, &err); - - if (parent_file == NULL) - return err; - - parent = parent_file->vnode; - - if (vfs_create_file(parent, name, mode)) - return -1; - - vfs_close(parent_file); - - return 0; -} - -int sys_mknod(const char *pathname, mode_t mode, dev_t dev) -{ - if (mode != S_IFIFO) - return -ENOSYS; - - struct vnode *vnode = vfs_mknod(pathname, mode); - - if (vnode == NULL) - return -1; - - return 0; -} - -void *sys_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset) -{ - if (!(flags & MAP_ANONYMOUS)) - return (void *)-ENOSYS; - - struct proc *proc = proc_find(getupid()); - if (proc == NULL) - return (void *)-1; - - void *ret = umalloc(proc, len, UA_SLAB, (uintptr_t)addr); - - if (ret == NULL) - return (void *)-ENOMEM; - - return ret; -} - -void *sys_munmap(void *addr, size_t len) -{ - struct proc *proc = proc_find(getupid()); - if (proc == NULL) - return (void *)-1; - - ufree(proc, addr); - - return 0; -} - -static void syscall_insert(uint64_t syscall_no, syscall_t syscall) -{ - syscall_table[syscall_no] = syscall; -} - -void syscall_init() -{ - fd_slab = slab_create(sizeof(struct file_descriptor), 16 * KB, 0); - - memset(syscall_table, 0, sizeof(syscall_table)); - syscall_insert(SYS_READ, (syscall_t)sys_read); - syscall_insert(SYS_WRITE, (syscall_t)sys_write); - syscall_insert(SYS_OPEN, (syscall_t)sys_open); - syscall_insert(SYS_FORK, (syscall_t)sys_fork); - syscall_insert(SYS_EXIT, (syscall_t)sys_exit); - syscall_insert(SYS_LSDIR, (syscall_t)sys_lsdir); - syscall_insert(SYS_MMAP, (syscall_t)sys_mmap); - syscall_insert(SYS_MUNMAP, (syscall_t)sys_munmap); - syscall_insert(SYS_MKDIR, (syscall_t)sys_mkdir); - syscall_insert(SYS_MKNOD, (syscall_t)sys_mknod); - - /* init syscall instruction */ - uint64_t star = rdmsr(MSR_IA32_STAR); - star |= ((uint64_t)GDT_SEGMENT_CODE_RING0 << 32); - star |= ((uint64_t)(GDT_SEGMENT_CODE_RING3 - 16) << 48); - wrmsr(MSR_IA32_STAR, star); - - wrmsr(MSR_IA32_LSTAR, (uint64_t)gate_syscall); - - uint64_t efer = rdmsr(MSR_IA32_EFER); - wrmsr(MSR_IA32_EFER, efer | 0x1); - - wrmsr(MSR_IA32_FMASK, 0x200); /* disable interrupts */ -} diff --git a/usr.bin/ftest/Makefile b/usr.bin/ftest/Makefile deleted file mode 100644 index def76f0..0000000 --- a/usr.bin/ftest/Makefile +++ /dev/null @@ -1,36 +0,0 @@ - - -CC := x86_64-elf-gcc -LD := x86_64-elf-ld - -OUT := ftest.elf -CSRC := -SSRC := ftest.S -OBJ := $(CSRC:.c=.o) $(SSRC:.S=.o) -DEP := $(OBJ:.o=.d) - -CFLAGS := -Wall -ffreestanding -mno-mmx -mno-sse2 -mno-sse -m64 -MMD -g -LDFLAGS := -nostdlib -static -m elf_x86_64 - -CURDIR := $(shell pwd | awk -F '/' '{print $$(NF-1),"/",$$NF}' | sed 's/ //g') - -$(OUT): $(OBJ) - @$(LD) $^ $(LDFLAGS) -o $@ - @echo " USR.LD $(CURDIR)/$@" - --include $(DEP) - -%.o: %.S - @$(CC) $(CFLAGS) -c $< -o $@ - @echo " USR.CC $(CURDIR)/$@" - -%.o: %.c - @$(CC) $(CFLAGS) -c $< -o $@ - @echo " USR.CC $(CURDIR)/$@" - -clean: - @rm -rf $(OUT) $(OBJ) $(DEP) - -install: $(OUT) - @cp $(OUT) ../../bin - @echo " INSTALL $(CURDIR)/$(OUT)" diff --git a/usr.bin/ftest/ftest.S b/usr.bin/ftest/ftest.S deleted file mode 100644 index 4a7bef4..0000000 --- a/usr.bin/ftest/ftest.S +++ /dev/null @@ -1,103 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ - -/* ftest/ftest.S - * - * Test the read and write system calls. - */ - -sys_read = 0 -sys_write = 1 -sys_open = 2 -sys_exit = 60 - -.macro print text text_size - movl $sys_write, %eax - movl $1, %edi - movq $\text, %rsi - movl $\text_size, %edx - int $0x80 -.endm - -.text -.global _start -_start: - /* Open the file */ - movl $sys_open, %eax - movq $filename, %rdi - int $0x80 - - cmpl $-1, %eax - je _error_open - - /* Read the file */ - movq %rax, %rdi - movl $sys_read, %eax - movq $buf, %rsi - movl $buf_size, %edx - int $0x80 - - cmpl $-1, %eax - je _error_read - - /* Write the file */ - movl $sys_write, %eax - movl $1, %edi - movq $buf, %rsi - movl $buf_size, %edx - int $0x80 - - cmpl $-1, %eax - je _error_write - - print exit_message exit_message_size - movl $0, %edi - jmp _exit - -_error_open: - pushq %rax - print error_open error_open_size - popq %rdi - jmp _exit - -_error_read: - pushq %rax - print error_read error_read_size - popq %rdi - jmp _exit - -_error_write: - pushq %rax - print error_write error_write_size - popq %rdi - jmp _exit - -_exit: - - /* Exit */ - movl $sys_exit, %eax - int $0x80 - -.data -filename: - .asciz "test.txt" - -error_open: - .asciz "Error opening file\n" -error_open_size = . - error_open - -error_read: - .asciz "Error reading file\n" -error_read_size = . - error_read - -error_write: - .asciz "Error writing file\n" -error_write_size = . - error_write - -exit_message: - .asciz "Exiting successfully\n" -exit_message_size = . - exit_message - -.bss -buf: - .skip 1024 -buf_size = . - buf diff --git a/usr.bin/make.sh b/usr.bin/make.sh deleted file mode 100755 index 5f3f85c..0000000 --- a/usr.bin/make.sh +++ /dev/null @@ -1,6 +0,0 @@ -usrprog=('ftest' 'test1' 'vfs' 'shtest') - -mkdir -p ../bin -for prog in ${usrprog[@]}; do - make -C $prog $1 --no-print-directory -done diff --git a/usr.bin/shtest/Makefile b/usr.bin/shtest/Makefile deleted file mode 100644 index aedad1f..0000000 --- a/usr.bin/shtest/Makefile +++ /dev/null @@ -1,38 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-only - -# shtest: simple userspace shell test - -CC := x86_64-elf-gcc -LD := x86_64-elf-ld - -OUT := shtest.elf -CSRC := shtest.c -SSRC := syscall.S -OBJ := $(CSRC:.c=.o) $(SSRC:.S=.o) -DEP := $(OBJ:.o=.d) - -CFLAGS := -Wall -ffreestanding -mno-mmx -mno-sse2 -mno-sse -m64 -MMD -LDFLAGS := -nostdlib -static -m elf_x86_64 - -CURDIR := $(shell pwd | awk -F '/' '{print $$(NF-1),"/",$$NF}' | sed 's/ //g') - -$(OUT): $(OBJ) - @$(LD) $^ $(LDFLAGS) -o $@ - @echo " USR.LD $(CURDIR)/$@" - --include $(DEP) - -%.o: %.S - @$(CC) $(CFLAGS) -c $< -o $@ - @echo " USR.CC $(CURDIR)/$@" - -%.o: %.c - @$(CC) $(CFLAGS) -c $< -o $@ - @echo " USR.CC $(CURDIR)/$@" - -clean: - @rm -rf $(OUT) $(OBJ) $(DEP) - -install: $(OUT) - @cp $(OUT) ../../bin - @echo " INSTALL $(CURDIR)/$(OUT)" diff --git a/usr.bin/shtest/shtest.c b/usr.bin/shtest/shtest.c deleted file mode 100644 index a7630f2..0000000 --- a/usr.bin/shtest/shtest.c +++ /dev/null @@ -1,65 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -/* shtest: simple userland shell test */ -#include -#include -#include - -#define S_IFIFO 0x1000 - -typedef int64_t ssize_t; -typedef int64_t pid_t; - -int open(const char *pathname, int flags); -ssize_t read(int fd, void *buf, int count); -ssize_t write(int fd, void *buf, int count); -int close(int fd); -pid_t fork(); -int exit(int status); -int mknod(const char *pathname, int mode, int dev); - -void promptfd(int fd) -{ - write(fd, "shtest> ", 8); -} - -void _start() -{ - int term = open("/dev/tty0", 0); - if (term < 0) - exit(1); - - char buf[256]; - int n; - - /* FIFOs!!!!!!!!! */ - write(term, "mknod\n", 5); - mknod("/dev/pts", S_IFIFO, 0); - write(term, "open\n", 5); - int fifofd = open("/dev/pts", 0); - - if (fifofd < 0) - write(term, "open failed\n", 12); - - /* write hello to fifo */ - write(term, "write\n", 6); - int i = write(fifofd, "hello\n", 6); - /* read back from fifo */ - write(term, "read\n", 5); - i = read(fifofd, buf, 6); - - /* print output to terminal */ - - write(term, "read back from fifo: ", 22); - write(term, buf, i); - promptfd(term); - - /* fork test */ - while ((n = read(term, buf, 256)) > 0) { - write(term, buf, n); - - if (buf[0] == 'q') - break; - } - - exit(1234); -} diff --git a/usr.bin/shtest/syscall.S b/usr.bin/shtest/syscall.S deleted file mode 100644 index 09893ca..0000000 --- a/usr.bin/shtest/syscall.S +++ /dev/null @@ -1,21 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -/* syscall handler for simple userland shell test */ - -#define __ASM__ - -.macro _sc_define name, num -.global \name -\name: - movq $\num, %rax - movq %rcx, %r10 - int $0x80 - ret -.endm - -_sc_define read, 0 -_sc_define write, 1 -_sc_define open, 2 -_sc_define close, 3 -_sc_define fork, 57 -_sc_define exit, 60 -_sc_define mknod, 133 diff --git a/usr.bin/test1/Makefile b/usr.bin/test1/Makefile deleted file mode 100644 index 99e376f..0000000 --- a/usr.bin/test1/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-only - -# usr.bin/test1/Makefile -# -# test1 is the first test program, to be removed later. -# -# This Makefile also serves as a template for other user programs. - -CC := x86_64-elf-gcc -LD := x86_64-elf-ld - -OUT := test1.elf -CSRC := -SSRC := start.S -OBJ := $(CSRC:.c=.o) $(SSRC:.S=.o) -DEP := $(OBJ:.o=.d) - -CFLAGS := -Wall -ffreestanding -mno-mmx -mno-sse2 -mno-sse -m64 -MMD -g -LDFLAGS := -nostdlib -static -m elf_x86_64 - -CURDIR := $(shell pwd | awk -F '/' '{print $$(NF-1),"/",$$NF}' | sed 's/ //g') - -$(OUT): $(OBJ) - @$(LD) $^ $(LDFLAGS) -o $@ - @echo " USR.LD $(CURDIR)/$@" - --include $(DEP) - -%.o: %.S - @$(CC) $(CFLAGS) -c $< -o $@ - @echo " USR.CC $(CURDIR)/$@" - -%.o: %.c - @$(CC) $(CFLAGS) -c $< -o $@ - @echo " USR.CC $(CURDIR)/$@" - -clean: - @rm -rf $(OUT) $(OBJ) $(DEP) - -install: $(OUT) - @cp $(OUT) ../../bin - @echo " INSTALL $(CURDIR)/$(OUT)" diff --git a/usr.bin/test1/start.S b/usr.bin/test1/start.S deleted file mode 100644 index 6c312af..0000000 --- a/usr.bin/test1/start.S +++ /dev/null @@ -1,29 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ - -/* test1/start.S - * - * Test the basic functionality of the kernel loader - */ - -sys_write = 1 -sys_exit = 60 - -.global _start -_start: - movl $sys_write, %eax - movl $1, %edi - movq $test_string, %rsi - movl $test_string_len, %edx - int $0x80 - - movl $sys_exit, %eax - movl $0xDEADC0DE, %edi - int $0x80 -_no_exit: - movq $0, %rbx - jmp _no_exit - -.data -test_string: - .ascii "hello, world\n\n" -test_string_len = . - test_string diff --git a/usr.bin/vfs/Makefile b/usr.bin/vfs/Makefile deleted file mode 100644 index c2310a8..0000000 --- a/usr.bin/vfs/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-only - -# usr.bin/test1/Makefile -# -# test1 is the first test program, to be removed later. -# -# This Makefile also serves as a template for other user programs. - -CC := x86_64-elf-gcc -LD := x86_64-elf-ld - -OUT := vfs.elf -CSRC := -SSRC := vfs.S -OBJ := $(CSRC:.c=.o) $(SSRC:.S=.o) -DEP := $(OBJ:.o=.d) - -CFLAGS := -Wall -ffreestanding -mno-mmx -mno-sse2 -mno-sse -m64 -MMD -g -LDFLAGS := -nostdlib -static -m elf_x86_64 - -CURDIR := $(shell pwd | awk -F '/' '{print $$(NF-1),"/",$$NF}' | sed 's/ //g') - -$(OUT): $(OBJ) - @$(LD) $^ $(LDFLAGS) -o $@ - @echo " USR.LD $(CURDIR)/$@" - --include $(DEP) - -%.o: %.S - @$(CC) $(CFLAGS) -c $< -o $@ - @echo " USR.CC $(CURDIR)/$@" - -%.o: %.c - @$(CC) $(CFLAGS) -c $< -o $@ - @echo " USR.CC $(CURDIR)/$@" - -clean: - @rm -rf $(OUT) $(OBJ) $(DEP) - -install: $(OUT) - @cp $(OUT) ../../bin - @echo " INSTALL $(CURDIR)/$(OUT)" diff --git a/usr.bin/vfs/vfs.S b/usr.bin/vfs/vfs.S deleted file mode 100644 index 85ae623..0000000 --- a/usr.bin/vfs/vfs.S +++ /dev/null @@ -1,35 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only */ -sys_write = 1 -sys_open = 2 -sys_exit = 60 - -.global _start -_start: - movq $sys_open, %rax - movq $tty_file, %rdi - movq $0, %rsi - movq $0, %rdx - int $0x80 - - movq %rax, %rbx - - movq $sys_write, %rax - movq %rbx, %rdi - leaq test_string(%rip), %rsi - movq $test_string_len, %rdx - int $0x80 - - movq $sys_exit, %rax - movq $0, %rdi - int $0x80 -_no_exit: - movq $0, %rbx - jmp _no_exit - -.data -test_string: - .ascii "hello, world\n\n" -test_string_len = . - test_string - -tty_file: - .asciz "/dev/tty"