28 Commits

Author SHA1 Message Date
Mirco De Marchi fb8f820383 Merge branch 'master' into feature/Feature-DeadlockExercise 2021-04-12 02:14:41 +02:00
Mirco De Marchi a8201fcdde Fix MacOS installation instructions 2021-04-12 02:13:23 +02:00
Mirco De Marchi eecb9dcc71 Update README.md with deadlock prevention enablement info 2021-03-26 19:01:34 +01:00
Mirco De Marchi feee0b80db Clean code 2021-03-26 18:28:19 +01:00
Mirco De Marchi a5bc390cf0 Rename available, max, alloc and need deadlock structures 2021-03-26 16:00:39 +01:00
Mirco De Marchi eafaca084f Replace tabs with spaces 2021-03-26 14:53:02 +01:00
Mirco De Marchi f957e05615 Integrate OS compatibility in this brench 2021-03-26 14:48:07 +01:00
Enrico Fraccaroli 05c3f2c033 Add skeleton code for deadlock prevention. 2021-03-23 13:32:46 +01:00
Enrico Fraccaroli 1236941a9c Merge pull request #4 from mentos-team/compatibility
Compatibility
2021-01-26 10:02:28 +01:00
Mirco De Marchi de33947249 Update README.md with prerequisistes install commands and some fix 2021-01-19 21:24:53 +01:00
Mirco De Marchi 05397f24c9 Add compatibility for GCC 10
Insert additional -fcommon C flag to obtain the same behavior of previous versions of GCC compilers, because
now, by default GCC 10 compiler has the -fno-common flag
that give error when omitting extern when declaring
a global variable in a header file.

TODO: for the next MentOS release check the "extern"
keyword in global variable in header files.
2021-01-19 19:17:59 +01:00
Mirco De Marchi 0d8fa6c9cd Remove SDL in qemu command for ubuntu 19 and 20
Add compatibility for ubuntu lsb versions that haven't sdl support
2021-01-19 17:02:56 +01:00
Mirco De Marchi b47110b402 Improve compatibility for Ubuntu 18.04
Disable ASM_NASM language and take only ASM language with third_party nasm tool to avoid errors.
2021-01-19 15:43:53 +01:00
Mirco De Marchi f99b9f739c Add MacOS compatibility with cross-compiler toolchain 2021-01-19 10:42:42 +01:00
Enrico Fraccaroli 6fd063984a Add new defines to vfs types 2019-05-16 17:22:47 +02:00
Enrico Fraccaroli bc2623ce99 Clean up stdlib 2019-05-16 17:22:21 +02:00
Enrico Fraccaroli c16a750251 Use standard limits for VFS file and path length 2019-05-16 17:13:35 +02:00
Enrico Fraccaroli c673fb9351 Improve multiboot code 2019-05-16 17:03:37 +02:00
Enrico Fraccaroli 25ffb602ea Improve multiboot info 2019-05-16 16:19:26 +02:00
Enrico Fraccaroli 552e2a073f Update limit values 2019-05-16 13:59:07 +02:00
Enrico Fraccaroli c0e5808656 Standardize most system calls 2019-05-10 17:18:34 +02:00
Enrico Fraccaroli 9368b0d6eb Canonicalize sys_open and sys_close, add close System Call 2019-05-10 12:26:30 +02:00
Enrico Fraccaroli 3bfa61d189 Re-format the code 2019-05-10 12:07:35 +02:00
Enrico Fraccaroli d9fd3b1646 Clean math code 2019-05-10 12:04:50 +02:00
Enrico Fraccaroli 14d64d25d3 Remove getchar old code 2019-05-10 12:01:10 +02:00
Enrico Fraccaroli dbeed54f2b Just return 0 when passing NULL string to atoi 2019-05-10 12:00:03 +02:00
Enrico Fraccaroli 07bd4d7901 Improve atoi function, safeguard gets function from out-of-bound errors 2019-05-10 11:59:18 +02:00
Enrico Fraccaroli 614d3dfd62 Standardize assert 2019-05-10 11:28:47 +02:00
236 changed files with 25954 additions and 24412 deletions
+36 -2
View File
@@ -1,5 +1,40 @@
# ------------------------------------------------------------------------------
# Initialize the project.
project(MentOs)
cmake_minimum_required(VERSION 2.8.4) cmake_minimum_required(VERSION 2.8.4)
message(STATUS "Crosscompiling: ${CMAKE_CROSSCOMPILING}")
# ------------------------------------------------------------------------------
# Add operating system specific option.
message(STATUS "System name: ${CMAKE_HOST_SYSTEM_NAME}")
message(STATUS "Kernel version: ${CMAKE_SYSTEM_VERSION}")
if ((${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Darwin") OR APPLE)
# Apple MacOSx
elseif ((${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Windows") OR WIN32)
# Windows
set(EMULATOR_FLAGS ${EMULATOR_FLAGS} -sdl)
else()
# Generic Unix System
find_program(LSB_RELEASE_EXEC lsb_release)
execute_process(COMMAND "${LSB_RELEASE_EXEC}" --short --release
OUTPUT_VARIABLE LSB_RELEASE_VERSION_SHORT
OUTPUT_STRIP_TRAILING_WHITESPACE)
message(STATUS "LSB version: ${LSB_RELEASE_VERSION_SHORT}")
if (${LSB_RELEASE_VERSION_SHORT} MATCHES "^18")
# Ubuntu 18
set(EMULATOR_FLAGS ${EMULATOR_FLAGS} -sdl)
elseif (${LSB_RELEASE_VERSION_SHORT} MATCHES "^19")
# Ubuntu 19
set(EMULATOR_FLAGS ${EMULATOR_FLAGS} -display gtk)
elseif (${LSB_RELEASE_VERSION_SHORT} MATCHES "^20")
# Ubuntu 20
set(EMULATOR_FLAGS ${EMULATOR_FLAGS} -display gtk)
else()
set(EMULATOR_FLAGS ${EMULATOR_FLAGS} -sdl)
endif()
endif()
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# Add the debugging option. # Add the debugging option.
set(DEBUGGING_TYPE "DEBUG_STDIO" CACHE STRING set(DEBUGGING_TYPE "DEBUG_STDIO" CACHE STRING
@@ -28,7 +63,7 @@ add_custom_target(
COMMAND echo "---------------------------------------------" COMMAND echo "---------------------------------------------"
COMMAND echo "Initializing 'initfs'..." COMMAND echo "Initializing 'initfs'..."
COMMAND echo "---------------------------------------------" COMMAND echo "---------------------------------------------"
COMMAND initfscp -s ${CMAKE_SOURCE_DIR}/files -t ${CMAKE_BINARY_DIR}/initfs -m /dev COMMAND ./initscp/initfscp -s ${CMAKE_SOURCE_DIR}/files -t ${CMAKE_BINARY_DIR}/initfs -m /dev
COMMAND echo "---------------------------------------------" COMMAND echo "---------------------------------------------"
COMMAND echo "Done!" COMMAND echo "Done!"
COMMAND echo "---------------------------------------------" COMMAND echo "---------------------------------------------"
@@ -49,7 +84,6 @@ elseif (${DEBUGGING_TYPE} STREQUAL DEBUG_STDIO)
endif () endif ()
SET(EMULATOR_FLAGS ${EMULATOR_FLAGS} -vga std) SET(EMULATOR_FLAGS ${EMULATOR_FLAGS} -vga std)
SET(EMULATOR_FLAGS ${EMULATOR_FLAGS} -k it) SET(EMULATOR_FLAGS ${EMULATOR_FLAGS} -k it)
SET(EMULATOR_FLAGS ${EMULATOR_FLAGS} -sdl)
SET(EMULATOR_FLAGS ${EMULATOR_FLAGS} -m ${MEMORY_SIZE}) SET(EMULATOR_FLAGS ${EMULATOR_FLAGS} -m ${MEMORY_SIZE})
SET(EMULATOR_KERNEL -kernel mentos/kernel.bin) SET(EMULATOR_KERNEL -kernel mentos/kernel.bin)
SET(EMULATOR_FS -initrd initfs) SET(EMULATOR_FS -initrd initfs)
+94 -6
View File
@@ -36,6 +36,9 @@ Main Developers:
Prerequisites Prerequisites
----------------- -----------------
MentOS is compatible with the main Unix distribution operating systems. It has been tested with *Ubuntu* and *MacOS*, but specifically tested on *Ubuntu 18.04*.
For compiling the main system: For compiling the main system:
* nasm * nasm
@@ -47,17 +50,44 @@ For compiling the main system:
To run and try: To run and try:
* qemu-system-x86 * qemu-system-i386
For debugging: For debugging:
* ccmake * ccmake
* gdb or cgdb * cgdb
* xterm * xterm
For MacOS, you have additional dependencies:
* i386-elf-binutils (from [i386-elf-toolchain](https://github.com/nativeos/homebrew-i386-elf-toolchain))
* i386-elf-gcc (from [i386-elf-toolchain](https://github.com/nativeos/homebrew-i386-elf-toolchain))
Prerequisites installation commands
-----------------
For Ubuntu:
```
sudo apt-get update && sudo apt-get upgrade -y
sudo apt-get install -y build-essential git cmake qemu-system-i386
sudo apt-get install -y cgdb xterm #<- for debug only
```
For MacOS:
You need to install additionally the i386-elf cross-compiler. The simplest installation method is through Homebrew package manager. Install [Homebrew](https://brew.sh/index_it) if you don't already have and exec the following commands:
```
brew update && brew upgrade
brew tap nativeos/i386-elf-toolchain
brew install i386-elf-binutils i386-elf-gcc git cmake qemu nasm
brew install cgdb xterm #<- for debug only
```
Compiling MentOS Compiling MentOS
----------------- -----------------
Compile and boot MentOS with qemu: Compile and boot MentOS with qemu in Unix systems:
``` ```
cd <clone_directory> cd <clone_directory>
@@ -70,6 +100,12 @@ make qemu
If you want to access to the shell, use one of the usernames listed in files/passwd. If you want to access to the shell, use one of the usernames listed in files/passwd.
**For MacOS**, the steps are the same but instead of `cmake ..`, you have to put an additional argument in order to use the i386-elf cross-compiler:
```
cmake -DCMAKE_TOOLCHAIN_FILE=../toolchain.cmake ..
```
Change the scheduling algorithm Change the scheduling algorithm
----------------- -----------------
@@ -80,6 +116,23 @@ MentOS provides three different scheduling algorithms:
* Completely Fair Scheduling * Completely Fair Scheduling
If you want to change the scheduling algorithm: If you want to change the scheduling algorithm:
```
cd build
# Round Robin scheduling algorithm
cmake -DSCHEDULER_TYPE=SCHEDULER_RR ..
# Priority scheduling algorithm
cmake -DSCHEDULER_TYPE=SCHEDULER_PRIORITY ..
# Completely Fair Scheduling algorithm
cmake -DSCHEDULER_TYPE=SCHEDULER_CFS ..
make
make qemu
```
Otherwise you can use `ccmake`:
``` ```
cd build cd build
cmake .. cmake ..
@@ -107,13 +160,23 @@ make
make qemu make qemu
``` ```
Enable to Buddy System Enable Buddy System
----------------- -----------------
MentOS provides a Buddy System to manage the allocation and deallocation of MentOS provides a Buddy System to manage the allocation and deallocation of
page frames in the physical memory. page frames in physical memory.
If you want to enable MentOS's Buddy System:
```
cd build
cmake -DENABLE_BUDDY_SYSTEM=ON ..
make
make qemu
```
Otherwise you can use `ccmake`:
If you want to enable the MentOS's Buddy System:
``` ```
cd build cd build
cmake .. cmake ..
@@ -150,6 +213,31 @@ make
make qemu make qemu
``` ```
Enable Deadlock Prevention
-----------------
MentOS implements the Banker's Algorithm to perform deadlock prevention for
user-space tasks.
If you want to enable deadlock prevention in MentOS:
```
cd build
cmake -DENABLE_DEADLOCK_PREVENTION=ON ..
make
make qemu
```
Otherwise you can use `ccmake` as shown previously for Buddy System enablement.
You can control the behavior of the deadlock algorithm with a shell command
line that allows you to run two mis-synchronized processes on two shared
resources, bringing the operating system into a possible deadlock state.
Of course the deadlock state is not always reached, because the tasks scheduling
is nondeterministic. The shell command line is `deadlock [-i <iter>]` where the
optional parameter `-i <iter>` specify the number of iterations of created tasks
over the shared resources, by default it will perform only 1 iteration.
Use Debugger Use Debugger
----------------- -----------------
If you want to use GDB to debug MentOS: If you want to use GDB to debug MentOS:
+180 -181
View File
@@ -1,181 +1,180 @@
| EAX | Name | Source | EBX | ECX | EDX | ESX | EDI | | S | EAX | Name | Source | EBX | ECX | EDX | ESX | EDI |
|:----|:---------------------------|:----------------------------|:-------------------------|:-----------------------------|:------------------------|:----------------|:-----------------| |:--|:----|:---------------------------|:----------------------------|:-------------------------|:-----------------------------|:------------------------|:----------------|:-----------------|
| 1 | sys_exit | kernel/exit.c | int | - | - | - | - | | 1 | 1 | sys_exit | kernel/exit.c | int | - | - | - | - |
| 2 | sys_fork | arch/i386/kernel/process.c | struct pt_regs | - | - | - | - | | | 2 | sys_fork | arch/i386/kernel/process.c | struct pt_regs | - | - | - | - |
| 3 | sys_read | fs/read_write.c | unsigned int | char * | size_t | - | - | | 1 | 3 | sys_read | fs/read_write.c | unsigned int | char * | size_t | - | - |
| 4 | sys_write | fs/read_write.c | unsigned int | const char * | size_t | - | - | | 1 | 4 | sys_write | fs/read_write.c | unsigned int | const char * | size_t | - | - |
| 5 | sys_open | fs/open.c | const char * | int | int | - | - | | 1 | 5 | sys_open | fs/open.c | const char * | int | int | - | - |
| 6 | sys_close | fs/open.c | unsigned int | - | - | - | - | | 1 | 6 | sys_close | fs/open.c | int | - | - | - | - |
| 7 | sys_waitpid | kernel/exit.c | pid_t | unsigned int * | int | - | - | | 1 | 7 | sys_waitpid | kernel/exit.c | pid_t | unsigned int * | int | - | - |
| 8 | sys_creat | fs/open.c | const char * | int | - | - | - | | | 8 | sys_creat | fs/open.c | const char * | int | - | - | - |
| 9 | sys_link | fs/namei.c | const char * | const char * | - | - | - | | | 9 | sys_link | fs/namei.c | const char * | const char * | - | - | - |
| 10 | sys_unlink | fs/namei.c | const char * | - | - | - | - | | | 10 | sys_unlink | fs/namei.c | const char * | - | - | - | - |
| 11 | sys_execve | arch/i386/kernel/process.c | struct pt_regs | - | - | - | - | | 1 | 11 | sys_execve | arch/i386/kernel/process.c | struct pt_regs | - | - | - | - |
| 12 | sys_chdir | fs/open.c | const char * | - | - | - | - | | 1 | 12 | sys_chdir | fs/open.c | const char * | - | - | - | - |
| 13 | sys_time | kernel/time.c | int * | - | - | - | - | | | 13 | sys_time | kernel/time.c | int * | - | - | - | - |
| 14 | sys_mknod | fs/namei.c | const char * | int | dev_t | - | - | | | 14 | sys_mknod | fs/namei.c | const char * | int | dev_t | - | - |
| 15 | sys_chmod | fs/open.c | const char * | mode_t | - | - | - | | | 15 | sys_chmod | fs/open.c | const char * | mode_t | - | - | - |
| 16 | sys_lchown | fs/open.c | const char * | uid_t | gid_t | - | - | | | 16 | sys_lchown | fs/open.c | const char * | uid_t | gid_t | - | - |
| 18 | sys_stat | fs/stat.c | char * | struct __old_kernel_stat * | - | - | - | | 1 | 18 | sys_stat | fs/stat.c | char * | struct __old_kernel_stat * | - | - | - |
| 19 | sys_lseek | fs/read_write.c | unsigned int | off_t | unsigned int | - | - | | | 19 | sys_lseek | fs/read_write.c | unsigned int | off_t | unsigned int | - | - |
| 20 | sys_getpid | kernel/sched.c | - | - | - | - | - | | 1 | 20 | sys_getpid | kernel/sched.c | - | - | - | - | - |
| 21 | sys_mount | fs/super.c | char * | char * | char * | - | - | | | 21 | sys_mount | fs/super.c | char * | char * | char * | - | - |
| 22 | sys_oldumount | fs/super.c | char * | - | - | - | - | | | 22 | sys_oldumount | fs/super.c | char * | - | - | - | - |
| 23 | sys_setuid | kernel/sys.c | uid_t | - | - | - | - | | | 23 | sys_setuid | kernel/sys.c | uid_t | - | - | - | - |
| 24 | sys_getuid | kernel/sched.c | - | - | - | - | - | | | 24 | sys_getuid | kernel/sched.c | - | - | - | - | - |
| 25 | sys_stime | kernel/time.c | int * | - | - | - | - | | | 25 | sys_stime | kernel/time.c | int * | - | - | - | - |
| 26 | sys_ptrace | arch/i386/kernel/ptrace.c | long | long | long | long | - | | | 26 | sys_ptrace | arch/i386/kernel/ptrace.c | long | long | long | long | - |
| 27 | sys_alarm | kernel/sched.c | unsigned int | - | - | - | - | | | 27 | sys_alarm | kernel/sched.c | unsigned int | - | - | - | - |
| 28 | sys_fstat | fs/stat.c | unsigned int | struct __old_kernel_stat * | - | - | - | | | 28 | sys_fstat | fs/stat.c | unsigned int | struct __old_kernel_stat * | - | - | - |
| 29 | sys_pause | arch/i386/kernel/sys_i386.c | - | - | - | - | - | | | 29 | sys_pause | arch/i386/kernel/sys_i386.c | - | - | - | - | - |
| 30 | sys_utime | fs/open.c | char * | struct utimbuf * | - | - | - | | | 30 | sys_utime | fs/open.c | char * | struct utimbuf * | - | - | - |
| 33 | sys_access | fs/open.c | const char * | int | - | - | - | | | 33 | sys_access | fs/open.c | const char * | int | - | - | - |
| 34 | sys_nice | kernel/sched.c | int | - | - | - | - | | 1 | 34 | sys_nice | kernel/sched.c | int | - | - | - | - |
| 36 | sys_sync | fs/buffer.c | - | - | - | - | - | | | 36 | sys_sync | fs/buffer.c | - | - | - | - | - |
| 37 | sys_kill | kernel/signal.c | int | int | - | - | - | | | 37 | sys_kill | kernel/signal.c | int | int | - | - | - |
| 38 | sys_rename | fs/namei.c | const char * | const char * | - | - | - | | | 38 | sys_rename | fs/namei.c | const char * | const char * | - | - | - |
| 39 | sys_mkdir | fs/namei.c | const char * | int | - | - | - | | 1 | 39 | sys_mkdir | fs/namei.c | const char * | int | - | - | - |
| 40 | sys_rmdir | fs/namei.c | const char * | - | - | - | - | | | 40 | sys_rmdir | fs/namei.c | const char * | - | - | - | - |
| 41 | sys_dup | fs/fcntl.c | unsigned int | - | - | - | - | | | 41 | sys_dup | fs/fcntl.c | unsigned int | - | - | - | - |
| 42 | sys_pipe | arch/i386/kernel/sys_i386.c | unsigned long * | - | - | - | - | | | 42 | sys_pipe | arch/i386/kernel/sys_i386.c | unsigned long * | - | - | - | - |
| 43 | sys_times | kernel/sys.c | struct tms * | - | - | - | - | | | 43 | sys_times | kernel/sys.c | struct tms * | - | - | - | - |
| 45 | sys_brk | mm/mmap.c | unsigned long | - | - | - | - | | | 45 | sys_brk | mm/mmap.c | unsigned long | - | - | - | - |
| 46 | sys_setgid | kernel/sys.c | gid_t | - | - | - | - | | | 46 | sys_setgid | kernel/sys.c | gid_t | - | - | - | - |
| 47 | sys_getgid | kernel/sched.c | - | - | - | - | - | | | 47 | sys_getgid | kernel/sched.c | - | - | - | - | - |
| 48 | sys_signal | kernel/signal.c | int | __sighandler_t | - | - | - | | | 48 | sys_signal | kernel/signal.c | int | __sighandler_t | - | - | - |
| 49 | sys_geteuid | kernel/sched.c | - | - | - | - | - | | | 49 | sys_geteuid | kernel/sched.c | - | - | - | - | - |
| 50 | sys_getegid | kernel/sched.c | - | - | - | - | - | | | 50 | sys_getegid | kernel/sched.c | - | - | - | - | - |
| 51 | sys_acct | kernel/acct.c | const char * | - | - | - | - | | | 51 | sys_acct | kernel/acct.c | const char * | - | - | - | - |
| 52 | sys_umount | fs/super.c | char * | int | - | - | - | | | 52 | sys_umount | fs/super.c | char * | int | - | - | - |
| 54 | sys_ioctl | fs/ioctl.c | unsigned int | unsigned int | unsigned long | - | - | | | 54 | sys_ioctl | fs/ioctl.c | unsigned int | unsigned int | unsigned long | - | - |
| 55 | sys_fcntl | fs/fcntl.c | unsigned int | unsigned int | unsigned long | - | - | | | 55 | sys_fcntl | fs/fcntl.c | unsigned int | unsigned int | unsigned long | - | - |
| 57 | sys_setpgid | kernel/sys.c | pid_t | pid_t | - | - | - | | | 57 | sys_setpgid | kernel/sys.c | pid_t | pid_t | - | - | - |
| 59 | sys_olduname | arch/i386/kernel/sys_i386.c | struct oldold_utsname * | - | - | - | - | | | 59 | sys_olduname | arch/i386/kernel/sys_i386.c | struct oldold_utsname * | - | - | - | - |
| 60 | sys_umask | kernel/sys.c | int | - | - | - | - | | | 60 | sys_umask | kernel/sys.c | int | - | - | - | - |
| 61 | sys_chroot | fs/open.c | const char * | - | - | - | - | | | 61 | sys_chroot | fs/open.c | const char * | - | - | - | - |
| 62 | sys_ustat | fs/super.c | dev_t | struct ustat * | - | - | - | | | 62 | sys_ustat | fs/super.c | dev_t | struct ustat * | - | - | - |
| 63 | sys_dup2 | fs/fcntl.c | unsigned int | unsigned int | - | - | - | | | 63 | sys_dup2 | fs/fcntl.c | unsigned int | unsigned int | - | - | - |
| 64 | sys_getppid | kernel/sched.c | - | - | - | - | - | | 1 | 64 | sys_getppid | kernel/sched.c | - | - | - | - | - |
| 65 | sys_getpgrp | kernel/sys.c | - | - | - | - | - | | | 65 | sys_getpgrp | kernel/sys.c | - | - | - | - | - |
| 66 | sys_setsid | kernel/sys.c | - | - | - | - | - | | | 66 | sys_setsid | kernel/sys.c | - | - | - | - | - |
| 67 | sys_sigaction | arch/i386/kernel/signal.c | int | const struct old_sigaction * | struct old_sigaction * | - | - | | | 67 | sys_sigaction | arch/i386/kernel/signal.c | int | const struct old_sigaction * | struct old_sigaction * | - | - |
| 68 | sys_sgetmask | kernel/signal.c | - | - | - | - | - | | | 68 | sys_sgetmask | kernel/signal.c | - | - | - | - | - |
| 69 | sys_ssetmask | kernel/signal.c | int | - | - | - | - | | | 69 | sys_ssetmask | kernel/signal.c | int | - | - | - | - |
| 70 | sys_setreuid | kernel/sys.c | uid_t | uid_t | - | - | - | | | 70 | sys_setreuid | kernel/sys.c | uid_t | uid_t | - | - | - |
| 71 | sys_setregid | kernel/sys.c | gid_t | gid_t | - | - | - | | | 71 | sys_setregid | kernel/sys.c | gid_t | gid_t | - | - | - |
| 72 | sys_sigsuspend | arch/i386/kernel/signal.c | int | int | old_sigset_t | - | - | | | 72 | sys_sigsuspend | arch/i386/kernel/signal.c | int | int | old_sigset_t | - | - |
| 73 | sys_sigpending | kernel/signal.c | old_sigset_t * | - | - | - | - | | | 73 | sys_sigpending | kernel/signal.c | old_sigset_t * | - | - | - | - |
| 74 | sys_sethostname | kernel/sys.c | char * | int | - | - | - | | | 74 | sys_sethostname | kernel/sys.c | char * | int | - | - | - |
| 75 | sys_setrlimit | kernel/sys.c | unsigned int | struct rlimit * | - | - | - | | | 75 | sys_setrlimit | kernel/sys.c | unsigned int | struct rlimit * | - | - | - |
| 76 | sys_getrlimit | kernel/sys.c | unsigned int | struct rlimit * | - | - | - | | | 76 | sys_getrlimit | kernel/sys.c | unsigned int | struct rlimit * | - | - | - |
| 77 | sys_getrusage | kernel/sys.c | int | struct rusage * | - | - | - | | | 77 | sys_getrusage | kernel/sys.c | int | struct rusage * | - | - | - |
| 78 | sys_gettimeofday | kernel/time.c | struct timeval * | struct timezone * | - | - | - | | | 78 | sys_gettimeofday | kernel/time.c | struct timeval * | struct timezone * | - | - | - |
| 79 | sys_settimeofday | kernel/time.c | struct timeval * | struct timezone * | - | - | - | | | 79 | sys_settimeofday | kernel/time.c | struct timeval * | struct timezone * | - | - | - |
| 80 | sys_getgroups | kernel/sys.c | int | gid_t * | - | - | - | | | 80 | sys_getgroups | kernel/sys.c | int | gid_t * | - | - | - |
| 81 | sys_setgroups | kernel/sys.c | int | gid_t * | - | - | - | | | 81 | sys_setgroups | kernel/sys.c | int | gid_t * | - | - | - |
| | 83 | sys_symlink | fs/namei.c | const char * | const char * | - | - | - |
| 83 | sys_symlink | fs/namei.c | const char * | const char * | - | - | - | | | 84 | sys_lstat | fs/stat.c | char * | struct __old_kernel_stat * | - | - | - |
| 84 | sys_lstat | fs/stat.c | char * | struct __old_kernel_stat * | - | - | - | | | 85 | sys_readlink | fs/stat.c | const char * | char * | int | - | - |
| 85 | sys_readlink | fs/stat.c | const char * | char * | int | - | - | | | 86 | sys_uselib | fs/exec.c | const char * | - | - | - | - |
| 86 | sys_uselib | fs/exec.c | const char * | - | - | - | - | | | 87 | sys_swapon | mm/swapfile.c | const char * | int | - | - | - |
| 87 | sys_swapon | mm/swapfile.c | const char * | int | - | - | - | | 1 | 88 | sys_reboot | kernel/sys.c | int | int | int | void * | - |
| 88 | sys_reboot | kernel/sys.c | int | int | int | void * | - | | 1 | 89 | old_readdir | fs/readdir.c | unsigned int | void * | unsigned int | - | - |
| 89 | old_readdir | fs/readdir.c | unsigned int | void * | unsigned int | - | - | | | 90 | old_mmap | arch/i386/kernel/sys_i386.c | struct mmap_arg_struct * | - | - | - | - |
| 90 | old_mmap | arch/i386/kernel/sys_i386.c | struct mmap_arg_struct * | - | - | - | - | | | 91 | sys_munmap | mm/mmap.c | unsigned long | size_t | - | - | - |
| 91 | sys_munmap | mm/mmap.c | unsigned long | size_t | - | - | - | | | 92 | sys_truncate | fs/open.c | const char * | unsigned long | - | - | - |
| 92 | sys_truncate | fs/open.c | const char * | unsigned long | - | - | - | | | 93 | sys_ftruncate | fs/open.c | unsigned int | unsigned long | - | - | - |
| 93 | sys_ftruncate | fs/open.c | unsigned int | unsigned long | - | - | - | | | 94 | sys_fchmod | fs/open.c | unsigned int | mode_t | - | - | - |
| 94 | sys_fchmod | fs/open.c | unsigned int | mode_t | - | - | - | | | 95 | sys_fchown | fs/open.c | unsigned int | uid_t | gid_t | - | - |
| 95 | sys_fchown | fs/open.c | unsigned int | uid_t | gid_t | - | - | | | 96 | sys_getpriority | kernel/sys.c | int | int | - | - | - |
| 96 | sys_getpriority | kernel/sys.c | int | int | - | - | - | | | 97 | sys_setpriority | kernel/sys.c | int | int | int | - | - |
| 97 | sys_setpriority | kernel/sys.c | int | int | int | - | - | | | 99 | sys_statfs | fs/open.c | const char * | struct statfs * | - | - | - |
| 99 | sys_statfs | fs/open.c | const char * | struct statfs * | - | - | - | | | 100 | sys_fstatfs | fs/open.c | unsigned int | struct statfs * | - | - | - |
| 100 | sys_fstatfs | fs/open.c | unsigned int | struct statfs * | - | - | - | | | 101 | sys_ioperm | arch/i386/kernel/ioport.c | unsigned long | unsigned long | int | - | - |
| 101 | sys_ioperm | arch/i386/kernel/ioport.c | unsigned long | unsigned long | int | - | - | | | 102 | sys_socketcall | net/socket.c | int | unsigned long * | - | - | - |
| 102 | sys_socketcall | net/socket.c | int | unsigned long * | - | - | - | | | 103 | sys_syslog | kernel/printk.c | int | char * | int | - | - |
| 103 | sys_syslog | kernel/printk.c | int | char * | int | - | - | | | 104 | sys_setitimer | kernel/itimer.c | int | struct itimerval * | struct itimerval * | - | - |
| 104 | sys_setitimer | kernel/itimer.c | int | struct itimerval * | struct itimerval * | - | - | | | 105 | sys_getitimer | kernel/itimer.c | int | struct itimerval * | - | - | - |
| 105 | sys_getitimer | kernel/itimer.c | int | struct itimerval * | - | - | - | | | 106 | sys_newstat | fs/stat.c | char * | struct stat * | - | - | - |
| 106 | sys_newstat | fs/stat.c | char * | struct stat * | - | - | - | | | 107 | sys_newlstat | fs/stat.c | char * | struct stat * | - | - | - |
| 107 | sys_newlstat | fs/stat.c | char * | struct stat * | - | - | - | | | 108 | sys_newfstat | fs/stat.c | unsigned int | struct stat * | - | - | - |
| 108 | sys_newfstat | fs/stat.c | unsigned int | struct stat * | - | - | - | | | 109 | sys_uname | arch/i386/kernel/sys_i386.c | struct old_utsname * | - | - | - | - |
| 109 | sys_uname | arch/i386/kernel/sys_i386.c | struct old_utsname * | - | - | - | - | | | 110 | sys_iopl | arch/i386/kernel/ioport.c | unsigned long | - | - | - | - |
| 110 | sys_iopl | arch/i386/kernel/ioport.c | unsigned long | - | - | - | - | | | 111 | sys_vhangup | fs/open.c | - | - | - | - | - |
| 111 | sys_vhangup | fs/open.c | - | - | - | - | - | | | 112 | sys_idle | arch/i386/kernel/process.c | - | - | - | - | - |
| 112 | sys_idle | arch/i386/kernel/process.c | - | - | - | - | - | | | 113 | sys_vm86old | arch/i386/kernel/vm86.c | unsigned long | struct vm86plus_struct * | - | - | - |
| 113 | sys_vm86old | arch/i386/kernel/vm86.c | unsigned long | struct vm86plus_struct * | - | - | - | | | 114 | sys_wait4 | kernel/exit.c | pid_t | unsigned long * | int options | struct rusage * | - |
| 114 | sys_wait4 | kernel/exit.c | pid_t | unsigned long * | int options | struct rusage * | - | | | 115 | sys_swapoff | mm/swapfile.c | const char * | - | - | - | - |
| 115 | sys_swapoff | mm/swapfile.c | const char * | - | - | - | - | | | 116 | sys_sysinfo | kernel/info.c | struct sysinfo * | - | - | - | - |
| 116 | sys_sysinfo | kernel/info.c | struct sysinfo * | - | - | - | - | | | 117 | sys_ipc(*Note) | arch/i386/kernel/sys_i386.c | uint | int | int | int | void * |
| 117 | sys_ipc(*Note) | arch/i386/kernel/sys_i386.c | uint | int | int | int | void * | | | 118 | sys_fsync | fs/buffer.c | unsigned int | - | - | - | - |
| 118 | sys_fsync | fs/buffer.c | unsigned int | - | - | - | - | | | 119 | sys_sigreturn | arch/i386/kernel/signal.c | unsigned long | - | - | - | - |
| 119 | sys_sigreturn | arch/i386/kernel/signal.c | unsigned long | - | - | - | - | | | 120 | sys_clone | arch/i386/kernel/process.c | struct pt_regs | - | - | - | - |
| 120 | sys_clone | arch/i386/kernel/process.c | struct pt_regs | - | - | - | - | | | 121 | sys_setdomainname | kernel/sys.c | char * | int | - | - | - |
| 121 | sys_setdomainname | kernel/sys.c | char * | int | - | - | - | | | 122 | sys_newuname | kernel/sys.c | struct new_utsname * | - | - | - | - |
| 122 | sys_newuname | kernel/sys.c | struct new_utsname * | - | - | - | - | | | 123 | sys_modify_ldt | arch/i386/kernel/ldt.c | int | void * | unsigned long | - | - |
| 123 | sys_modify_ldt | arch/i386/kernel/ldt.c | int | void * | unsigned long | - | - | | | 124 | sys_adjtimex | kernel/time.c | struct timex * | - | - | - | - |
| 124 | sys_adjtimex | kernel/time.c | struct timex * | - | - | - | - | | | 125 | sys_mprotect | mm/mprotect.c | unsigned long | size_t | unsigned long | - | - |
| 125 | sys_mprotect | mm/mprotect.c | unsigned long | size_t | unsigned long | - | - | | | 126 | sys_sigprocmask | kernel/signal.c | int | old_sigset_t * | old_sigset_t * | - | - |
| 126 | sys_sigprocmask | kernel/signal.c | int | old_sigset_t * | old_sigset_t * | - | - | | | 127 | sys_create_module | kernel/module.c | const char * | size_t | - | - | - |
| 127 | sys_create_module | kernel/module.c | const char * | size_t | - | - | - | | | 128 | sys_init_module | kernel/module.c | const char * | struct module * | - | - | - |
| 128 | sys_init_module | kernel/module.c | const char * | struct module * | - | - | - | | | 129 | sys_delete_module | kernel/module.c | const char * | - | - | - | - |
| 129 | sys_delete_module | kernel/module.c | const char * | - | - | - | - | | | 130 | sys_get_kernel_syms | kernel/module.c | struct kernel_sym * | - | - | - | - |
| 130 | sys_get_kernel_syms | kernel/module.c | struct kernel_sym * | - | - | - | - | | | 131 | sys_quotactl | fs/dquot.c | int | const char * | int | caddr_t | - |
| 131 | sys_quotactl | fs/dquot.c | int | const char * | int | caddr_t | - | | | 132 | sys_getpgid | kernel/sys.c | pid_t | - | - | - | - |
| 132 | sys_getpgid | kernel/sys.c | pid_t | - | - | - | - | | | 133 | sys_fchdir | fs/open.c | unsigned int | - | - | - | - |
| 133 | sys_fchdir | fs/open.c | unsigned int | - | - | - | - | | | 134 | sys_bdflush | fs/buffer.c | int | long | - | - | - |
| 134 | sys_bdflush | fs/buffer.c | int | long | - | - | - | | | 135 | sys_sysfs | fs/super.c | int | unsigned long | unsigned long | - | - |
| 135 | sys_sysfs | fs/super.c | int | unsigned long | unsigned long | - | - | | | 136 | sys_personality | kernel/exec_domain.c | unsigned long | - | - | - | - |
| 136 | sys_personality | kernel/exec_domain.c | unsigned long | - | - | - | - | | | 138 | sys_setfsuid | kernel/sys.c | uid_t | - | - | - | - |
| 138 | sys_setfsuid | kernel/sys.c | uid_t | - | - | - | - | | | 139 | sys_setfsgid | kernel/sys.c | gid_t | - | - | - | - |
| 139 | sys_setfsgid | kernel/sys.c | gid_t | - | - | - | - | | | 140 | sys_llseek | fs/read_write.c | unsigned int | unsigned long | unsigned long | loff_t * | unsigned int |
| 140 | sys_llseek | fs/read_write.c | unsigned int | unsigned long | unsigned long | loff_t * | unsigned int | | | 141 | sys_getdents | fs/readdir.c | unsigned int | void * | unsigned int | - | - |
| 141 | sys_getdents | fs/readdir.c | unsigned int | void * | unsigned int | - | - | | | 142 | sys_select | fs/select.c | int | fd_set * | fd_set * | fd_set * | struct timeval * |
| 142 | sys_select | fs/select.c | int | fd_set * | fd_set * | fd_set * | struct timeval * | | | 143 | sys_flock | fs/locks.c | unsigned int | unsigned int | - | - | - |
| 143 | sys_flock | fs/locks.c | unsigned int | unsigned int | - | - | - | | | 144 | sys_msync | mm/filemap.c | unsigned long | size_t | int | - | - |
| 144 | sys_msync | mm/filemap.c | unsigned long | size_t | int | - | - | | | 145 | sys_readv | fs/read_write.c | unsigned long | const struct iovec * | unsigned long | - | - |
| 145 | sys_readv | fs/read_write.c | unsigned long | const struct iovec * | unsigned long | - | - | | | 146 | sys_writev | fs/read_write.c | unsigned long | const struct iovec * | unsigned long | - | - |
| 146 | sys_writev | fs/read_write.c | unsigned long | const struct iovec * | unsigned long | - | - | | | 147 | sys_getsid | kernel/sys.c | pid_t | - | - | - | - |
| 147 | sys_getsid | kernel/sys.c | pid_t | - | - | - | - | | | 148 | sys_fdatasync | fs/buffer.c | unsigned int | - | - | - | - |
| 148 | sys_fdatasync | fs/buffer.c | unsigned int | - | - | - | - | | | 149 | sys_sysctl | kernel/sysctl.c | struct __sysctl_args * | - | - | - | - |
| 149 | sys_sysctl | kernel/sysctl.c | struct __sysctl_args * | - | - | - | - | | | 150 | sys_mlock | mm/mlock.c | unsigned long | size_t | - | - | - |
| 150 | sys_mlock | mm/mlock.c | unsigned long | size_t | - | - | - | | | 151 | sys_munlock | mm/mlock.c | unsigned long | size_t | - | - | - |
| 151 | sys_munlock | mm/mlock.c | unsigned long | size_t | - | - | - | | | 152 | sys_mlockall | mm/mlock.c | int | - | - | - | - |
| 152 | sys_mlockall | mm/mlock.c | int | - | - | - | - | | | 153 | sys_munlockall | mm/mlock.c | - | - | - | - | - |
| 153 | sys_munlockall | mm/mlock.c | - | - | - | - | - | | | 154 | sys_sched_setparam | kernel/sched.c | pid_t | struct sched_param * | - | - | - |
| 154 | sys_sched_setparam | kernel/sched.c | pid_t | struct sched_param * | - | - | - | | | 155 | sys_sched_getparam | kernel/sched.c | pid_t | struct sched_param * | - | - | - |
| 155 | sys_sched_getparam | kernel/sched.c | pid_t | struct sched_param * | - | - | - | | | 156 | sys_sched_setscheduler | kernel/sched.c | pid_t | int | struct sched_param * | - | - |
| 156 | sys_sched_setscheduler | kernel/sched.c | pid_t | int | struct sched_param * | - | - | | | 157 | sys_sched_getscheduler | kernel/sched.c | pid_t | - | - | - | - |
| 157 | sys_sched_getscheduler | kernel/sched.c | pid_t | - | - | - | - | | | 158 | sys_sched_yield | kernel/sched.c | - | - | - | - | - |
| 158 | sys_sched_yield | kernel/sched.c | - | - | - | - | - | | | 159 | sys_sched_get_priority_max | kernel/sched.c | int | - | - | - | - |
| 159 | sys_sched_get_priority_max | kernel/sched.c | int | - | - | - | - | | | 160 | sys_sched_get_priority_min | kernel/sched.c | int | - | - | - | - |
| 160 | sys_sched_get_priority_min | kernel/sched.c | int | - | - | - | - | | | 161 | sys_sched_rr_get_interval | kernel/sched.c | pid_t | struct timespec * | - | - | - |
| 161 | sys_sched_rr_get_interval | kernel/sched.c | pid_t | struct timespec * | - | - | - | | | 162 | sys_nanosleep | kernel/sched.c | struct timespec * | struct timespec * | - | - | - |
| 162 | sys_nanosleep | kernel/sched.c | struct timespec * | struct timespec * | - | - | - | | | 163 | sys_mremap | mm/mremap.c | unsigned long | unsigned long | unsigned long | unsigned long | - |
| 163 | sys_mremap | mm/mremap.c | unsigned long | unsigned long | unsigned long | unsigned long | - | | | 164 | sys_setresuid | kernel/sys.c | uid_t | uid_t | uid_t | - | - |
| 164 | sys_setresuid | kernel/sys.c | uid_t | uid_t | uid_t | - | - | | | 165 | sys_getresuid | kernel/sys.c | uid_t * | uid_t * | uid_t * | - | - |
| 165 | sys_getresuid | kernel/sys.c | uid_t * | uid_t * | uid_t * | - | - | | | 166 | sys_vm86 | arch/i386/kernel/vm86.c | struct vm86_struct * | - | - | - | - |
| 166 | sys_vm86 | arch/i386/kernel/vm86.c | struct vm86_struct * | - | - | - | - | | | 167 | sys_query_module | kernel/module.c | const char * | int | char * | size_t | size_t * |
| 167 | sys_query_module | kernel/module.c | const char * | int | char * | size_t | size_t * | | | 168 | sys_poll | fs/select.c | struct pollfd * | unsigned int | long | - | - |
| 168 | sys_poll | fs/select.c | struct pollfd * | unsigned int | long | - | - | | | 169 | sys_nfsservctl | fs/filesystems.c | int | void * | void * | - | - |
| 169 | sys_nfsservctl | fs/filesystems.c | int | void * | void * | - | - | | | 170 | sys_setresgid | kernel/sys.c | gid_t | gid_t | gid_t | - | - |
| 170 | sys_setresgid | kernel/sys.c | gid_t | gid_t | gid_t | - | - | | | 171 | sys_getresgid | kernel/sys.c | gid_t * | gid_t * | gid_t * | - | - |
| 171 | sys_getresgid | kernel/sys.c | gid_t * | gid_t * | gid_t * | - | - | | | 172 | sys_prctl | kernel/sys.c | int | unsigned long | unsigned long | unsigned long | unsigned long |
| 172 | sys_prctl | kernel/sys.c | int | unsigned long | unsigned long | unsigned long | unsigned long | | | 173 | sys_rt_sigreturn | arch/i386/kernel/signal.c | unsigned long | - | - | - | - |
| 173 | sys_rt_sigreturn | arch/i386/kernel/signal.c | unsigned long | - | - | - | - | | | 174 | sys_rt_sigaction | kernel/signal.c | int | const struct sigaction * | struct sigaction * | size_t | - |
| 174 | sys_rt_sigaction | kernel/signal.c | int | const struct sigaction * | struct sigaction * | size_t | - | | | 175 | sys_rt_sigprocmask | kernel/signal.c | int | sigset_t * | sigset_t * | size_t | - |
| 175 | sys_rt_sigprocmask | kernel/signal.c | int | sigset_t * | sigset_t * | size_t | - | | | 176 | sys_rt_sigpending | kernel/signal.c | sigset_t * | size_t | - | - | - |
| 176 | sys_rt_sigpending | kernel/signal.c | sigset_t * | size_t | - | - | - | | | 177 | sys_rt_sigtimedwait | kernel/signal.c | const sigset_t * | siginfo_t * | const struct timespec * | size_t | - |
| 177 | sys_rt_sigtimedwait | kernel/signal.c | const sigset_t * | siginfo_t * | const struct timespec * | size_t | - | | | 178 | sys_rt_sigqueueinfo | kernel/signal.c | int | int | siginfo_t * | - | - |
| 178 | sys_rt_sigqueueinfo | kernel/signal.c | int | int | siginfo_t * | - | - | | | 179 | sys_rt_sigsuspend | arch/i386/kernel/signal.c | sigset_t * | size_t | - | - | - |
| 179 | sys_rt_sigsuspend | arch/i386/kernel/signal.c | sigset_t * | size_t | - | - | - | | | 180 | sys_pread | fs/read_write.c | unsigned int | char * | size_t | loff_t | - |
| 180 | sys_pread | fs/read_write.c | unsigned int | char * | size_t | loff_t | - | | | 181 | sys_pwrite | fs/read_write.c | unsigned int | const char * | size_t | loff_t | - |
| 181 | sys_pwrite | fs/read_write.c | unsigned int | const char * | size_t | loff_t | - | | | 182 | sys_chown | fs/open.c | const char * | uid_t | gid_t | - | - |
| 182 | sys_chown | fs/open.c | const char * | uid_t | gid_t | - | - | | 1 | 183 | sys_getcwd | fs/dcache.c | char * | unsigned long | - | - | - |
| 183 | sys_getcwd | fs/dcache.c | char * | unsigned long | - | - | - | | | 184 | sys_capget | kernel/capability.c | cap_user_header_t | cap_user_data_t | - | - | - |
| 184 | sys_capget | kernel/capability.c | cap_user_header_t | cap_user_data_t | - | - | - | | | 185 | sys_capset | kernel/capability.c | cap_user_header_t | const cap_user_data_t | - | - | - |
| 185 | sys_capset | kernel/capability.c | cap_user_header_t | const cap_user_data_t | - | - | - | | | 186 | sys_sigaltstack | arch/i386/kernel/signal.c | const stack_t * | stack_t * | - | - | - |
| 186 | sys_sigaltstack | arch/i386/kernel/signal.c | const stack_t * | stack_t * | - | - | - | | | 187 | sys_sendfile | mm/filemap.c | int | int | off_t * | size_t | - |
| 187 | sys_sendfile | mm/filemap.c | int | int | off_t * | size_t | - | | 1 | 190 | sys_vfork | arch/i386/kernel/process.c | struct pt_regs | - | - | - | - |
| 190 | sys_vfork | arch/i386/kernel/process.c | struct pt_regs | - | - | - | - | | | | | | | | | | |
| | | | | | | | |
+9 -9
View File
@@ -1,9 +1,9 @@
MentOS 0.1 MentOS 0.1
Welcome to the MentOS, the Mentoring Operating System. Welcome to the MentOS, the Mentoring Operating System.
If you want some help enter the "help" command into the cli. If you want some help enter the "help" command into the cli.
Bye, Bye,
The Ment(OS) Team The Ment(OS) Team
+1 -1
View File
@@ -1 +1 @@
io ti vi bi! io ti vi bi!
+1 -1
View File
@@ -1 +1 @@
tanto questa e' solo una prova :\ tanto questa e' solo una prova :\
+3 -3
View File
@@ -1,3 +1,3 @@
root:password root:password
user:computer user:computer
asd:asd asd:asd
+27 -27
View File
@@ -1,28 +1,28 @@
#include <stdio.h> #include <stdio.h>
#include <fcntl.h> #include <fcntl.h>
void main(int argc, char ** argv) void main(int argc, char ** argv)
{ {
if (argc == 2) if (argc == 2)
{ {
// Try to open the file. // Try to open the file.
int fd = open(argv[1], O_RDONLY, 42); int fd = open(argv[1], O_RDONLY, 42);
if (fd > -1) if (fd > -1)
{ {
char c; char c;
// Put on the standard output the characters. // Put on the standard output the characters.
while (read(fd, &c, 1)) putchar(c); while (read(fd, &c, 1)) putchar(c);
putchar('\n'); putchar('\n');
putchar('\n'); putchar('\n');
close(fd); close(fd);
} }
else else
{ {
printf("%s: cannot find the file.\n\n", argv[1]); printf("%s: cannot find the file.\n\n", argv[1]);
} }
} }
else else
{ {
printf("Usage: more file\n\n"); printf("Usage: more file\n\n");
} }
} }
+1 -1
View File
@@ -1 +1 @@
ciao mondo ciao mondo
+1 -1
View File
@@ -1 +1 @@
come va ? come va ?
+1 -1
View File
@@ -1 +1 @@
bho, io credo bene eh eh eh bho, io credo bene eh eh eh
+1 -1
View File
@@ -1 +1 @@
tanto questa e' solo una prova :\ tanto questa e' solo una prova :\
+1 -1
View File
@@ -1 +1 @@
io ti vi bi! io ti vi bi!
+6 -4
View File
@@ -6,6 +6,12 @@ project(initfscp C ASM)
# Set the project name. # Set the project name.
set(PROJECT_NAME initfscp) set(PROJECT_NAME initfscp)
if (CMAKE_CROSSCOMPILING)
set(CMAKE_C_COMPILER gcc)
set(CMAKE_CXX_COMPILER g++)
set(CMAKE_EXE_LINKER_FLAGS "")
endif (CMAKE_CROSSCOMPILING)
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# Set the compiler options (original). # Set the compiler options (original).
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g3") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g3")
@@ -13,10 +19,6 @@ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ggdb")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99")
# ------------------------------------------------------------------------------
# Add the includes.
include_directories(inc)
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# Add the source files. # Add the source files.
set(SOURCE_FILES src/initfscp.c) set(SOURCE_FILES src/initfscp.c)
-42
View File
@@ -1,42 +0,0 @@
/// @file initfscp.h
/// @brief
#pragma once
#define MAX_FILENAME_LENGTH 64
#define MAX_FILES 32
#define INITFSCP_VER "0.3.0"
#define FS_FILE 0x01 ///< Identifies a file.
#define FS_DIRECTORY 0x02 ///< Identifies a directory.
#define FS_CHARDEVICE 0x04 ///< Identifies a character devies.
#define FS_BLOCKDEVICE 0x08 ///< Identifies a block devies.
#define FS_PIPE 0x10 ///< Identifies a pipe.
#define FS_SYMLINK 0x20 ///< Identifies a symbolic link.
#define FS_MOUNTPOINT 0x40 ///< Identifies a mount-point.
#define RESET "\033[00m"
#define BLACK "\033[30m"
#define RED "\033[31m"
#define GREEN "\033[32m"
#define YELLOW "\033[33m"
#define BLUE "\033[34m"
#define MAGENTA "\033[35m"
#define CYAN "\033[36m"
#define WHITE "\033[37m"
/// @brief Information concerning a file.
typedef struct initrd_file_t {
/// Number used as delimiter, it must be set to 0xBF.
int magic;
/// The name of the file.
char fileName[MAX_FILENAME_LENGTH];
/// The type of the file.
short int file_type;
/// The uid of the owner.
int uid;
/// Offset of the starting address.
unsigned int offset;
/// Dimension of the file.
unsigned int length;
} initrd_file_t;
+52 -7
View File
@@ -4,16 +4,60 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <initfscp.h>
#include <stdbool.h> #include <stdbool.h>
#include <stdint.h> #include <stdint.h>
#include <libgen.h> #include <libgen.h>
#include <dirent.h> #include <dirent.h>
#include <assert.h> #include <assert.h>
#define INITFSCP_VER "0.3.0"
#define INITFSCP_NAME_MAX 255
#define INITFSCP_MAX_FILES 32
#define RESET "\033[00m"
#define BLACK "\033[30m"
#define RED "\033[31m"
#define GREEN "\033[32m"
#define YELLOW "\033[33m"
#define BLUE "\033[34m"
#define MAGENTA "\033[35m"
#define CYAN "\033[36m"
#define WHITE "\033[37m"
/// Identifies a file.
#define FS_FILE 0x01
/// Identifies a directory.
#define FS_DIRECTORY 0x02
/// Identifies a character devies.
#define FS_CHARDEVICE 0x04
/// Identifies a block devies.
#define FS_BLOCKDEVICE 0x08
/// Identifies a pipe.
#define FS_PIPE 0x10
/// Identifies a symbolic link.
#define FS_SYMLINK 0x20
/// Identifies a mount-point.
#define FS_MOUNTPOINT 0x40
/// @brief Information concerning a file.
typedef struct initrd_file_t {
/// Number used as delimiter, it must be set to 0xBF.
int magic;
/// The name of the file.
char fileName[INITFSCP_NAME_MAX];
/// The type of the file.
short int file_type;
/// The uid of the owner.
int uid;
/// Offset of the starting address.
unsigned int offset;
/// Dimension of the file.
unsigned int length;
} initrd_file_t;
static FILE *target_fs = NULL; static FILE *target_fs = NULL;
static initrd_file_t headers[MAX_FILES]; static initrd_file_t headers[INITFSCP_MAX_FILES];
static char mount_points[MAX_FILES][MAX_FILENAME_LENGTH]; static char mount_points[INITFSCP_MAX_FILES][INITFSCP_NAME_MAX];
static int mountpoint_idx = 0; static int mountpoint_idx = 0;
static int header_idx = 0; static int header_idx = 0;
static int header_offset = 0; static int header_offset = 0;
@@ -91,9 +135,9 @@ static bool open_target_fs(int argc, char *argv[])
static bool init_headers() static bool init_headers()
{ {
printf("%-64s", "Initializing headers structures..."); printf("%-64s", "Initializing headers structures...");
for (size_t i = 0; i < MAX_FILES; i++) { for (size_t i = 0; i < INITFSCP_MAX_FILES; i++) {
headers[i].magic = 0xBF; headers[i].magic = 0xBF;
memset(headers[i].fileName, 0, MAX_FILENAME_LENGTH); memset(headers[i].fileName, 0, INITFSCP_NAME_MAX);
headers[i].file_type = 0; headers[i].file_type = 0;
headers[i].uid = 0; headers[i].uid = 0;
headers[i].offset = 0; headers[i].offset = 0;
@@ -218,7 +262,7 @@ static bool create_file_headers(char *mountpoint, char *directory)
static bool write_file_system(char *mountpoint) static bool write_file_system(char *mountpoint)
{ {
printf("Copying data to filesystem...\n"); printf("Copying data to filesystem...\n");
for (int i = 0; i < MAX_FILES; i++) { for (int i = 0; i < INITFSCP_MAX_FILES; i++) {
// -------------------------------------------------------------------- // --------------------------------------------------------------------
char absolute_path[256]; char absolute_path[256];
memset(absolute_path, 0, 256); memset(absolute_path, 0, 256);
@@ -288,7 +332,8 @@ int main(int argc, char *argv[])
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// Create file headers. // Create file headers.
header_offset = sizeof(struct initrd_file_t) * MAX_FILES + sizeof(int); header_offset =
sizeof(struct initrd_file_t) * INITFSCP_MAX_FILES + sizeof(int);
printf("Creating headers...\n"); printf("Creating headers...\n");
for (uint32_t i = 1; i < argc; ++i) { for (uint32_t i = 1; i < argc; ++i) {
if (is_option_source(argv[i]) && ((i + 1) < argc)) { if (is_option_source(argv[i]) && ((i + 1) < argc)) {
+370 -331
View File
@@ -1,331 +1,370 @@
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# Initialize the project. # Initialize the project.
project(MentOs C ASM) project(MentOs C ASM)
set(PROJECT_NAME MentOs)
# ------------------------------------------------------------------------------
# Set the project name. # ------------------------------------------------------------------------------
set(PROJECT_NAME MentOs) # Add operating system specific option.
if((${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Darwin") OR APPLE) # Apple MacOSx
# ------------------------------------------------------------------------------ set(CMAKE_ASM_COMPILER nasm)
# Find doxygen elseif ((${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Windows") OR WIN32) # Windows
find_package(Doxygen) set(CMAKE_ASM_COMPILER ${CMAKE_SOURCE_DIR}/third_party/nasm/bin/nasm)
else () # Generic Unix System
# Add option to generate documentation. set(CMAKE_ASM_COMPILER ${CMAKE_SOURCE_DIR}/third_party/nasm/bin/nasm)
option(BUILD_DOCUMENTATION "Create and install the HTML based API documentation (requires Doxygen)" ${DOXYGEN_FOUND}) endif ()
if (BUILD_DOCUMENTATION) # ------------------------------------------------------------------------------
if (NOT DOXYGEN_FOUND) # Find doxygen
message(FATAL_ERROR "Doxygen is needed to build the documentation.") find_package(Doxygen)
endif (NOT DOXYGEN_FOUND)
# Add option to generate documentation.
set(doxyfile_in ${CMAKE_SOURCE_DIR}/doc/dreamos.doxyfile) option(BUILD_DOCUMENTATION "Create and install the HTML based API documentation (requires Doxygen)" ${DOXYGEN_FOUND})
set(doxyfile ${CMAKE_BINARY_DIR}/doxyfile)
if (BUILD_DOCUMENTATION)
configure_file(${doxyfile_in} ${doxyfile} @ONLY) if (NOT DOXYGEN_FOUND)
message(FATAL_ERROR "Doxygen is needed to build the documentation.")
add_custom_target( endif (NOT DOXYGEN_FOUND)
doc
COMMAND ${DOXYGEN_EXECUTABLE} ${doxyfile} set(doxyfile_in ${CMAKE_SOURCE_DIR}/doc/dreamos.doxyfile)
WORKING_DIRECTORY ${CMAKE_BINARY_DIR} set(doxyfile ${CMAKE_BINARY_DIR}/doxyfile)
COMMENT "Generating API documentation with Doxygen"
VERBATIM configure_file(${doxyfile_in} ${doxyfile} @ONLY)
)
install(DIRECTORY ${CMAKE_BINARY_DIR}/html DESTINATION share/doc) add_custom_target(
endif (BUILD_DOCUMENTATION) doc
COMMAND ${DOXYGEN_EXECUTABLE} ${doxyfile}
# ------------------------------------------------------------------------------ WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
# Add the scheduling option. COMMENT "Generating API documentation with Doxygen"
set(SCHEDULER_TYPE VERBATIM
"SCHEDULER_RR" )
CACHE STRING install(DIRECTORY ${CMAKE_BINARY_DIR}/html DESTINATION share/doc)
"Chose the type of scheduler: SCHEDULER_RR SCHEDULER_PRIORITY SCHEDULER_CFS") endif (BUILD_DOCUMENTATION)
set_property(
CACHE SCHEDULER_TYPE PROPERTY STRINGS # ------------------------------------------------------------------------------
SCHEDULER_RR # Add the scheduling option.
SCHEDULER_PRIORITY set(SCHEDULER_TYPE
SCHEDULER_CFS) "SCHEDULER_RR"
if ("${SCHEDULER_TYPE}" STREQUAL "SCHEDULER_RR" OR CACHE STRING
"${SCHEDULER_TYPE}" STREQUAL "SCHEDULER_PRIORITY" OR "Chose the type of scheduler: SCHEDULER_RR SCHEDULER_PRIORITY SCHEDULER_CFS")
"${SCHEDULER_TYPE}" STREQUAL "SCHEDULER_CFS") set_property(
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D${SCHEDULER_TYPE}") CACHE SCHEDULER_TYPE PROPERTY STRINGS
message(STATUS "Setting scheduler type to ${SCHEDULER_TYPE}.") SCHEDULER_RR
else () SCHEDULER_PRIORITY
message(FATAL_ERROR "Scheduler type ${SCHEDULER_TYPE} is not valid.") SCHEDULER_CFS)
endif () if ("${SCHEDULER_TYPE}" STREQUAL "SCHEDULER_RR" OR
"${SCHEDULER_TYPE}" STREQUAL "SCHEDULER_PRIORITY" OR
# ------------------------------------------------------------------------------ "${SCHEDULER_TYPE}" STREQUAL "SCHEDULER_CFS")
# Add the option to enable buddy system. set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D${SCHEDULER_TYPE}")
option(ENABLE_BUDDY_SYSTEM "Enables the buddy system" OFF) message(STATUS "Setting scheduler type to ${SCHEDULER_TYPE}.")
if (ENABLE_BUDDY_SYSTEM) else ()
message(STATUS "Enabling buddy system.") message(FATAL_ERROR "Scheduler type ${SCHEDULER_TYPE} is not valid.")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DENABLE_BUDDYSYSTEM") endif ()
else (ENABLE_BUDDY_SYSTEM)
message(STATUS "Buddy system disabled.") # ------------------------------------------------------------------------------
endif (ENABLE_BUDDY_SYSTEM) # Add the option to enable buddy system.
option(ENABLE_BUDDY_SYSTEM "Enables the buddy system" OFF)
# ------------------------------------------------------------------------------ if (ENABLE_BUDDY_SYSTEM)
# Set the compiler options (original). message(STATUS "Enabling buddy system.")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -nostdlib") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DENABLE_BUDDYSYSTEM")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -nostdinc") else (ENABLE_BUDDY_SYSTEM)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g3") message(STATUS "Buddy system disabled.")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ggdb") endif (ENABLE_BUDDY_SYSTEM)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fomit-frame-pointer")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-builtin") # ------------------------------------------------------------------------------
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-stack-protector") # Add the option to enable deadlock prevention.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall") option(ENABLE_DEADLOCK_PREVENTION "Enables the buddy system" OFF)
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror") if (ENABLE_DEADLOCK_PREVENTION)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -march=i686") message(STATUS "Enabling deadlock prevention.")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DENABLE_DEADLOCK_PREVENTION")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99") else (ENABLE_DEADLOCK_PREVENTION)
message(STATUS "Deadlock prevention disabled.")
# ------------------------------------------------------------------------------ endif (ENABLE_DEADLOCK_PREVENTION)
# Set the compiler options (extra).
set(CMAKE_C_FLAGS"${CMAKE_C_FLAGS} -Wall") # ------------------------------------------------------------------------------
#set(CMAKE_C_FLAGS"${CMAKE_C_FLAGS} -Wpedantic") # Set the compiler options (original).
#set(CMAKE_C_FLAGS"${CMAKE_C_FLAGS} -pedantic-errors") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -nostdlib")
#set(CMAKE_C_FLAGS"${CMAKE_C_FLAGS} -Wextra") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -nostdinc")
#set(CMAKE_C_FLAGS"${CMAKE_C_FLAGS} -Werror") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g3")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g3") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ggdb")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ggdb") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fomit-frame-pointer")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wconversion") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-builtin")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wcast-align") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-stack-protector")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wcast-qual") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wdisabled-optimization") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wfloat-equal") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -march=i686")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wfloat-conversion") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wformat=2") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wformat-nonliteral")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wformat-security") # ------------------------------------------------------------------------------
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wformat-y2k") # Set the compiler options (extra).
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wimport") set(CMAKE_C_FLAGS"${CMAKE_C_FLAGS} -Wall")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Winit-self") #set(CMAKE_C_FLAGS"${CMAKE_C_FLAGS} -Wpedantic")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Winline") #set(CMAKE_C_FLAGS"${CMAKE_C_FLAGS} -pedantic-errors")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Winvalid-pch") #set(CMAKE_C_FLAGS"${CMAKE_C_FLAGS} -Wextra")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-long-long") #set(CMAKE_C_FLAGS"${CMAKE_C_FLAGS} -Werror")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wmissing-field-initializers") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g3")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wmissing-format-attribute") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ggdb")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wmissing-include-dirs") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wconversion")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wpacked") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wcast-align")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wpointer-arith") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wcast-qual")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wredundant-decls") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wdisabled-optimization")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wshadow") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wfloat-equal")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wstack-protector") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wfloat-conversion")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wstrict-aliasing=2") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wformat=2")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wswitch") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wformat-nonliteral")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wswitch-default") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wformat-security")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wswitch-enum") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wformat-y2k")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunreachable-code") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wimport")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunused") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Winit-self")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunused-function") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Winline")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunused-label") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Winvalid-pch")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunused-parameter") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-long-long")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunused-value") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wmissing-field-initializers")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunused-variable") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wmissing-format-attribute")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wvariadic-macros") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wmissing-include-dirs")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wwrite-strings") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wpacked")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wsign-compare") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wpointer-arith")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wsign-conversion") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wredundant-decls")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wuninitialized") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wshadow")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fmessage-length=0") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wstack-protector")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wstrict-aliasing=2")
# ------------------------------------------------------------------------------ #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wswitch")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wswitch-default")
if (CMAKE_BUILD_TYPE MATCHES "Release") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wswitch-enum")
elseif (CMAKE_BUILD_TYPE MATCHES "Debug") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunreachable-code")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DDEBUG") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunused")
endif (CMAKE_BUILD_TYPE MATCHES "Release") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunused-function")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunused-label")
# ------------------------------------------------------------------------------ #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunused-parameter")
# Set the assembly flags. #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunused-value")
enable_language(ASM) #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunused-variable")
set(CMAKE_ASM_COMPILER ${CMAKE_SOURCE_DIR}/third_party/nasm/bin/nasm) #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wvariadic-macros")
SET(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} -g") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wwrite-strings")
SET(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} -O0") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wsign-compare")
SET(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} -f elf") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wsign-conversion")
SET(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} -F dwarf") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wuninitialized")
set(CMAKE_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> <FLAGS> -o <OBJECT> <SOURCE>") #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fmessage-length=0")
# ------------------------------------------------------------------------------ if (CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL 10)
# Add the includes. set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fcommon")
include_directories( endif()
inc
inc/descriptor_tables # ------------------------------------------------------------------------------
inc/devices
inc/drivers if (CMAKE_BUILD_TYPE MATCHES "Release")
inc/drivers/keyboard elseif (CMAKE_BUILD_TYPE MATCHES "Debug")
inc/fs set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DDEBUG")
inc/hardware endif (CMAKE_BUILD_TYPE MATCHES "Release")
inc/io
inc/kernel # ------------------------------------------------------------------------------
inc/libc # Set the assembly flags.
inc/lng set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} -g")
inc/mem set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} -O0")
inc/misc set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} -f elf")
inc/sys set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} -F dwarf")
inc/system set(CMAKE_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> <FLAGS> <SOURCE> -o <OBJECT>")
inc/process
inc/elf # ------------------------------------------------------------------------------
inc/ui # Add the includes.
inc/ui/shell include_directories(
inc/ui/command inc
inc/ui/init inc/descriptor_tables
) inc/devices
inc/drivers
# ------------------------------------------------------------------------------ inc/drivers/keyboard
# Add the source files. inc/fs
set(SOURCE_FILES inc/hardware
boot.asm inc/io
inc/kernel
src/kernel.c inc/libc
src/multiboot.c inc/lng
inc/mem
src/devices/pci.c inc/misc
src/devices/fpu.c inc/sys
inc/experimental
src/drivers/ata.c inc/experimental/math
src/drivers/fdc.c inc/system
src/drivers/mouse.c inc/process
src/drivers/keyboard/keyboard.c inc/elf
src/drivers/keyboard/keymap.c inc/ui
inc/ui/shell
src/fs/fcntl.c inc/ui/command
src/fs/initrd.c inc/ui/init
src/fs/vfs.c )
src/fs/read_write.c
# ------------------------------------------------------------------------------
src/sys/module.c # Add the source files.
src/sys/unistd.c set(SOURCE_FILES
src/hardware/timer.c boot.asm
src/hardware/cpuid.c
src/hardware/pic8259.c src/kernel.c
src/io/port_io.c src/multiboot.c
src/io/mm_io.c
src/io/video.c src/devices/pci.c
src/devices/fpu.c
src/kernel/sys.c
src/drivers/ata.c
src/libc/ctype.c src/drivers/fdc.c
src/libc/stdio.c src/drivers/mouse.c
src/libc/string.c src/drivers/keyboard/keyboard.c
src/libc/vsprintf.c src/drivers/keyboard/keymap.c
src/libc/queue.c
src/libc/stdlib.c src/experimental/smart_sem_kernel.c
src/libc/spinlock.c src/experimental/smart_sem_user.c
src/libc/list.c src/experimental/resource.c
src/libc/ordered_array.c src/experimental/math/arr_math.c
src/libc/mutex.c
src/libc/libgen.c src/fs/fcntl.c
src/libc/strerror.c src/fs/initrd.c
src/libc/tree.c src/fs/vfs.c
src/libc/bitset.c src/fs/read_write.c
src/libc/fcvt.c src/fs/open.c
src/libc/rbtree.c src/fs/stat.c
src/libc/math.c src/fs/readdir.c
src/libc/hashmap.c
src/sys/module.c
src/libc/unistd/getppid.c src/sys/unistd.c
src/libc/unistd/getpid.c src/hardware/timer.c
src/libc/unistd/exit.c src/hardware/cpuid.c
src/libc/unistd/vfork.c src/hardware/pic8259.c
src/libc/unistd/read.c src/io/port_io.c
src/libc/unistd/write.c src/io/mm_io.c
src/libc/unistd/execve.c src/io/video.c
src/libc/unistd/nice.c
src/libc/unistd/open.c src/kernel/sys.c
src/libc/unistd/reboot.c
src/libc/unistd/waitpid.c src/libc/assert.c
src/libc/unistd/chdir.c src/libc/ctype.c
src/libc/unistd/getcwd.c src/libc/stdio.c
src/libc/string.c
src/mem/kheap.c src/libc/vsprintf.c
src/mem/paging.c src/libc/queue.c
src/mem/zone_allocator.c src/libc/stdlib.c
src/libc/spinlock.c
src/misc/bitops.c src/libc/list.c
src/misc/clock.c src/libc/ordered_array.c
src/misc/debug.c src/libc/mutex.c
src/sys/dirent.c src/libc/libgen.c
src/sys/stat.c src/libc/strerror.c
src/sys/utsname.c src/libc/tree.c
#src/sys/shm.c src/libc/bitset.c
src/elf/elf.c src/libc/fcvt.c
src/libc/rbtree.c
src/descriptor_tables/gdt.c src/libc/math.c
src/descriptor_tables/gdt.asm src/libc/hashmap.c
src/descriptor_tables/interrupt.c
src/descriptor_tables/exception.c src/libc/unistd/getppid.c
src/descriptor_tables/interrupt.asm src/libc/unistd/getpid.c
src/descriptor_tables/exception.asm src/libc/unistd/exit.c
src/descriptor_tables/idt.c src/libc/unistd/vfork.c
src/descriptor_tables/idt.asm src/libc/unistd/read.c
src/descriptor_tables/tss.c src/libc/unistd/write.c
src/descriptor_tables/tss.asm src/libc/unistd/execve.c
src/libc/unistd/nice.c
src/process/scheduler.c src/libc/unistd/open.c
src/process/scheduler_algorithm.c src/libc/unistd/reboot.c
src/process/process.c src/libc/unistd/waitpid.c
src/process/user.asm src/libc/unistd/chdir.c
src/libc/unistd/getcwd.c
src/system/errno.c src/libc/unistd/close.c
src/system/panic.c src/libc/unistd/stat.c
src/system/syscall.c src/libc/unistd/mkdir.c
src/system/printk.c
src/mem/kheap.c
src/ui/command/cmd_cd.c src/mem/paging.c
src/ui/command/cmd_clear.c src/mem/zone_allocator.c
src/ui/command/cmd_cpuid.c
src/ui/command/cmd_credits.c src/misc/bitops.c
src/ui/command/cmd_date.c src/misc/clock.c
src/ui/command/cmd_drv_load.c src/misc/debug.c
src/ui/command/cmd_echo.c src/sys/dirent.c
src/ui/command/cmd_logo.c src/sys/utsname.c
src/ui/command/cmd_ls.c src/elf/elf.c
src/ui/command/cmd_mkdir.c
src/ui/command/cmd_more.c src/descriptor_tables/gdt.c
src/ui/command/cmd_newfile.c src/descriptor_tables/gdt.asm
src/ui/command/cmd_poweroff.c src/descriptor_tables/interrupt.c
src/ui/command/cmd_ps.c src/descriptor_tables/exception.c
src/ui/command/cmd_pwd.c src/descriptor_tables/interrupt.asm
src/ui/command/cmd_rm.c src/descriptor_tables/exception.asm
src/ui/command/cmd_rmdir.c src/descriptor_tables/idt.c
src/ui/command/cmd_showpid.c src/descriptor_tables/idt.asm
src/ui/command/cmd_sleep.c src/descriptor_tables/tss.c
#src/ui/command/cmd_tester.c src/descriptor_tables/tss.asm
src/ui/command/cmd_touch.c
src/ui/command/cmd_uname.c src/process/scheduler.c
src/ui/command/cmd_whoami.c src/process/scheduler_algorithm.c
src/ui/command/cmd_ipcs.c src/process/process.c
src/ui/command/cmd_ipcrm.c src/process/user.asm
src/ui/command/cmd_nice.c
src/system/errno.c
src/ui/init/init.c src/system/panic.c
src/system/syscall.c
src/ui/shell/shell.c src/system/printk.c
src/ui/shell/shell_login.c
) src/ui/command/cmd_cd.c
src/ui/command/cmd_clear.c
if (ENABLE_BUDDY_SYSTEM MATCHES "ON") src/ui/command/cmd_cpuid.c
set(SOURCE_FILES src/ui/command/cmd_credits.c
${SOURCE_FILES} src/ui/command/cmd_date.c
src/mem/buddysystem.c) src/ui/command/cmd_drv_load.c
endif (ENABLE_BUDDY_SYSTEM MATCHES "ON") src/ui/command/cmd_echo.c
src/ui/command/cmd_logo.c
# ------------------------------------------------------------------------------ src/ui/command/cmd_ls.c
# Add the executable. src/ui/command/cmd_mkdir.c
add_library(${PROJECT_NAME} ${SOURCE_FILES}) src/ui/command/cmd_more.c
src/ui/command/cmd_newfile.c
# ------------------------------------------------------------------------------ src/ui/command/cmd_poweroff.c
# Build the kernel. src/ui/command/cmd_ps.c
add_custom_command( src/ui/command/cmd_pwd.c
TARGET MentOs src/ui/command/cmd_rm.c
POST_BUILD src/ui/command/cmd_rmdir.c
COMMAND $(LD) src/ui/command/cmd_showpid.c
-melf_i386 src/ui/command/cmd_sleep.c
-static #src/ui/command/cmd_tester.c
--oformat elf32-i386 src/ui/command/cmd_touch.c
-Ttext 0x100000 src/ui/command/cmd_uname.c
--output=${CMAKE_CURRENT_BINARY_DIR}/kernel.bin src/ui/command/cmd_whoami.c
--script=${CMAKE_CURRENT_SOURCE_DIR}/kernel.lds src/ui/command/cmd_ipcs.c
${CMAKE_CURRENT_BINARY_DIR}/lib${PROJECT_NAME}.a src/ui/command/cmd_ipcrm.c
-Map ${CMAKE_CURRENT_BINARY_DIR}/kernel.map src/ui/command/cmd_nice.c
) src/ui/command/cmd_deadlock.c
src/ui/init/init.c
src/ui/shell/shell.c
src/ui/shell/shell_login.c
)
if (ENABLE_BUDDY_SYSTEM MATCHES "ON")
set(SOURCE_FILES
${SOURCE_FILES}
src/mem/buddysystem.c)
endif (ENABLE_BUDDY_SYSTEM MATCHES "ON")
if (ENABLE_DEADLOCK_PREVENTION MATCHES "ON")
set(SOURCE_FILES
${SOURCE_FILES}
src/experimental/deadlock_prevention.c
src/experimental/deadlock_simulation.c)
endif (ENABLE_DEADLOCK_PREVENTION MATCHES "ON")
# ------------------------------------------------------------------------------
# Add the executable.
add_library(${PROJECT_NAME} ${SOURCE_FILES})
# ------------------------------------------------------------------------------
# Build the kernel.
add_custom_command(
TARGET MentOs
POST_BUILD
COMMAND ${CMAKE_LINKER}
-melf_i386
-static
--oformat elf32-i386
-Ttext 0x100000
--output=${CMAKE_CURRENT_BINARY_DIR}/kernel.bin
--script=${CMAKE_CURRENT_SOURCE_DIR}/kernel.lds
${CMAKE_CURRENT_BINARY_DIR}/lib${PROJECT_NAME}.a
-Map ${CMAKE_CURRENT_BINARY_DIR}/kernel.map
)
+97 -89
View File
@@ -1,89 +1,97 @@
; MentOS, The Mentoring Operating system project ; MentOS, The Mentoring Operating system project
; @file boot.asm ; @file boot.asm
; @brief Kernel start location, multiboot header ; @brief Kernel start location, multiboot header
; @copyright (c) 2019 This file is distributed under the MIT License. ; @copyright (c) 2019 This file is distributed under the MIT License.
; See LICENSE.md for details. ; See LICENSE.md for details.
[BITS 32] ; All instructions should be 32-bit. [BITS 32] ; All instructions should be 32-bit.
[EXTERN kmain] ; The start point of our C code [EXTERN kmain] ; The start point of our C code
; Grub is informed with this flag to load ; The magic field should contain this.
; the kernel and kernel modules on a page boundary. MULTIBOOT_HEADER_MAGIC equ 0x1BADB002
MBOOT_PAGE_ALIGN equ 1<<0 ; This should be in %eax.
; Grub is informed with this flag to provide the kernel MULTIBOOT_BOOTLOADER_MAGIC equ 0x2BADB002
; with memory information.
MBOOT_MEM_INFO equ 1<<1 ; = Specify what GRUB should PROVIDE =========================================
; This is the multiboot magic value. ; Align the kernel and kernel modules on i386 page (4KB) boundaries.
MBOOT_HEADER_MAGIC equ 0x1BADB002 MULTIBOOT_PAGE_ALIGN equ 0x00000001
; This is the flag combination that we prepare for Grub ; Provide the kernel with memory information.
; to read at kernel load time. MULTIBOOT_MEMORY_INFO equ 0x00000002
MBOOT_HEADER_FLAGS equ MBOOT_PAGE_ALIGN | MBOOT_MEM_INFO ; Must pass video information to OS.
; Grub reads this value to make sure it loads a kernel MULTIBOOT_VIDEO_MODE equ 0x00000004
; and not just garbage. ; -----------------------------------------------------------------------------
MBOOT_CHECKSUM equ - (MBOOT_HEADER_MAGIC + MBOOT_HEADER_FLAGS)
; This is the flag combination that we prepare for Grub
LOAD_MEMORY_ADDRESS equ 0x00000000 ; to read at kernel load time.
; reserve (1024*1024) for the stack on a doubleword boundary MULTIBOOT_HEADER_FLAGS equ (MULTIBOOT_PAGE_ALIGN | MULTIBOOT_MEMORY_INFO | MULTIBOOT_VIDEO_MODE)
KERNEL_STACK_SIZE equ 0x100000 ; Grub reads this value to make sure it loads a kernel
; and not just garbage.
; ----------------------------------------------------------------------------- MULTIBOOT_CHECKSUM equ -(MULTIBOOT_HEADER_MAGIC + MULTIBOOT_HEADER_FLAGS)
; SECTION (multiboot_header)
; ----------------------------------------------------------------------------- LOAD_MEMORY_ADDRESS equ 0x00000000
section .multiboot_header ; reserve (1024*1024) for the stack on a doubleword boundary
align 4 KERNEL_STACK_SIZE equ 0x100000
; This is the GRUB Multiboot header.
multiboot_header: ; -----------------------------------------------------------------------------
dd MBOOT_HEADER_MAGIC ; SECTION (multiboot_header)
dd MBOOT_HEADER_FLAGS ; -----------------------------------------------------------------------------
dd MBOOT_CHECKSUM section .multiboot_header
align 4
; ----------------------------------------------------------------------------- ; This is the GRUB Multiboot header.
; SECTION (data) multiboot_header:
; ----------------------------------------------------------------------------- ; magic
section .data, nobits dd MULTIBOOT_HEADER_MAGIC
align 4096 ; flags
[GLOBAL boot_page_dir] dd MULTIBOOT_HEADER_FLAGS
boot_page_dir: ; checksum
resb 0x1000 dd MULTIBOOT_CHECKSUM
boot_page_tabl:
resb 0x1000 ; -----------------------------------------------------------------------------
; SECTION (data)
; ----------------------------------------------------------------------------- ; -----------------------------------------------------------------------------
; SECTION (text) section .data, nobits
; ----------------------------------------------------------------------------- align 4096
section .text [GLOBAL boot_page_dir]
[GLOBAL kernel_entry] boot_page_dir:
kernel_entry: resb 0x1000
; Clear interrupt flag [IF = 0]; 0xFA boot_page_tabl:
cli resb 0x1000
; To set up a stack, we simply set the esp register to point to the top of
; our stack (as it grows downwards). ; -----------------------------------------------------------------------------
mov esp, stack_top ; SECTION (text)
; pass the initial ESP ; -----------------------------------------------------------------------------
push esp section .text
;mov ebp, esp [GLOBAL kernel_entry]
; pass Multiboot info structure kernel_entry:
push ebx ; Clear interrupt flag [IF = 0]; 0xFA
; pass Multiboot magic number cli
push eax ; To set up a stack, we simply set the esp register to point to the top of
; Call the kmain() function inside kernel.c ; our stack (as it grows downwards).
call kmain mov esp, stack_top
; Set interrupt flag [IF = 1]; 0xFA ; pass the initial ESP
; Clear interrupts and hang if we return from kmain push esp
cli ; pass Multiboot info structure
hang: push ebx
hlt ; pass Multiboot magic number
jmp hang push eax
; Call the kmain() function inside kernel.c
call kmain
; ----------------------------------------------------------------------------- ; Set interrupt flag [IF = 1]; 0xFA
; SECTION (bss) ; Clear interrupts and hang if we return from kmain
; ----------------------------------------------------------------------------- cli
section .bss hang:
[GLOBAL stack_bottom] hlt
[GLOBAL stack_top] jmp hang
align 16
stack_bottom:
resb KERNEL_STACK_SIZE ; -----------------------------------------------------------------------------
stack_top: ; SECTION (bss)
; the top of the stack is the bottom because the stack counts down ; -----------------------------------------------------------------------------
section .bss
[GLOBAL stack_bottom]
[GLOBAL stack_top]
align 16
stack_bottom:
resb KERNEL_STACK_SIZE
stack_top:
; the top of the stack is the bottom because the stack counts down
+79 -79
View File
@@ -1,79 +1,79 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file gdt.h /// @file gdt.h
/// @brief Data structures concerning the Global Descriptor Table (GDT). /// @brief Data structures concerning the Global Descriptor Table (GDT).
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
/// @brief Access flags, determines what ring this segment can be used in. /// @brief Access flags, determines what ring this segment can be used in.
typedef enum gdt_access_option_t typedef enum gdt_access_option_t
{ {
/// Identifies a kernel segment. /// Identifies a kernel segment.
KERNEL = 0x00, KERNEL = 0x00,
/// Identifies a user segment. /// Identifies a user segment.
USER = 0x03, USER = 0x03,
/// Identifies a code segment. /// Identifies a code segment.
CODE = 0x10, CODE = 0x10,
/// Identifies a data segment. /// Identifies a data segment.
DATA = 0x10, DATA = 0x10,
/// Segment is present. /// Segment is present.
PRESENT = 0x80, PRESENT = 0x80,
} __attribute__ ((__packed__)) gdt_access_option_t; } __attribute__ ((__packed__)) gdt_access_option_t;
/// @brief Options for the second option. /// @brief Options for the second option.
typedef enum gdt_granularity_option_t typedef enum gdt_granularity_option_t
{ {
/// Granularity. /// Granularity.
GRANULARITY = 0x80, GRANULARITY = 0x80,
/// Szbits. /// Szbits.
SZBITS = 0x40 SZBITS = 0x40
} __attribute__ ((__packed__)) gdt_granularity_option_t; } __attribute__ ((__packed__)) gdt_granularity_option_t;
/// @brief Data structure representing a GDT descriptor. /// @brief Data structure representing a GDT descriptor.
typedef struct gdt_descriptor_t typedef struct gdt_descriptor_t
{ {
/// The lower 16 bits of the limit. /// The lower 16 bits of the limit.
uint16_t limit_low; uint16_t limit_low;
/// The lower 16 bits of the base. /// The lower 16 bits of the base.
uint16_t base_low; uint16_t base_low;
/// The next 8 bits of the base. /// The next 8 bits of the base.
uint8_t base_middle; uint8_t base_middle;
/// Access flags, determine what ring this segment can be used in. /// Access flags, determine what ring this segment can be used in.
uint8_t access; uint8_t access;
/// SegLimit_hi(4 bit) AVL(1 bit) L(1 bit) D/B(1 bit) G(1bit). /// SegLimit_hi(4 bit) AVL(1 bit) L(1 bit) D/B(1 bit) G(1bit).
uint8_t granularity; uint8_t granularity;
/// The last 8 bits of the base. /// The last 8 bits of the base.
uint8_t base_high; uint8_t base_high;
} __attribute__((packed)) gdt_descriptor_t; } __attribute__((packed)) gdt_descriptor_t;
/// @brief Data structure used to load the GDT into the GDTR. /// @brief Data structure used to load the GDT into the GDTR.
typedef struct gdt_pointer_t typedef struct gdt_pointer_t
{ {
/// The size of the GDT (entry number). /// The size of the GDT (entry number).
uint16_t limit; uint16_t limit;
/// The starting address of the GDT. /// The starting address of the GDT.
uint32_t base; uint32_t base;
} __attribute__((packed)) gdt_pointer_t; } __attribute__((packed)) gdt_pointer_t;
/// @brief Initialise the GDT. /// @brief Initialise the GDT.
/// @details This will setup the special GDT /// @details This will setup the special GDT
/// pointer, set up the first 3 entries in our GDT, and then /// pointer, set up the first 3 entries in our GDT, and then
/// finally call gdt_flush() in our assembler file in order /// finally call gdt_flush() in our assembler file in order
/// to tell the processor where the new GDT is and update the /// to tell the processor where the new GDT is and update the
/// new segment registers. /// new segment registers.
void init_gdt(); void init_gdt();
/// @brief Sets the value of one GDT entry. /// @brief Sets the value of one GDT entry.
/// @param index The index inside the GDT. /// @param index The index inside the GDT.
/// @param base Memory address where the segment we are defining starts. /// @param base Memory address where the segment we are defining starts.
/// @param limit The memory address which determines the end of the segnment. /// @param limit The memory address which determines the end of the segnment.
/// @param _access Type (4bit) - S (1) bit -DPL (2 bit) - P(1 bit). /// @param _access Type (4bit) - S (1) bit -DPL (2 bit) - P(1 bit).
/// @param _granul SegLimit_hi(4 bit) AVL(1 bit) L(1 bit) D/B(1 bit) G(1bit). /// @param _granul SegLimit_hi(4 bit) AVL(1 bit) L(1 bit) D/B(1 bit) G(1bit).
void gdt_set_gate(uint8_t index, void gdt_set_gate(uint8_t index,
uint32_t base, uint32_t base,
uint32_t limit, uint32_t limit,
uint8_t _access, uint8_t _access,
uint8_t _granul); uint8_t _granul);
+169 -173
View File
@@ -1,173 +1,169 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file idt.h /// @file idt.h
/// @brief Data structures concerning the Interrupt Descriptor Table (IDT). /// @brief Data structures concerning the Interrupt Descriptor Table (IDT).
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "isr.h" #include "isr.h"
#include "stdint.h" #include "stdint.h"
#include <kernel.h> #include <kernel.h>
/// The maximum dimension of the IDT. /// The maximum dimension of the IDT.
#define IDT_SIZE 256 #define IDT_SIZE 256
/// When an exception occurs whose entry is a Task Gate, a task switch results. /// When an exception occurs whose entry is a Task Gate, a task switch results.
#define TASK_GATE 0x5 #define TASK_GATE 0x5
/// Used to specify an interrupt service routine (16-bit). /// Used to specify an interrupt service routine (16-bit).
#define INT16_GATE 0x6 #define INT16_GATE 0x6
/// @brief Similar to an Interrupt gate (16-bit). /// @brief Similar to an Interrupt gate (16-bit).
#define TRAP16_GATE 0x7 #define TRAP16_GATE 0x7
/// Used to specify an interrupt service routine (32-bit). /// Used to specify an interrupt service routine (32-bit).
#define INT32_GATE 0xE #define INT32_GATE 0xE
/// @brief Similar to an Interrupt gate (32-bit). /// @brief Similar to an Interrupt gate (32-bit).
#define TRAP32_GATE 0xF #define TRAP32_GATE 0xF
/* /*
* Trap and Interrupt gates are similar, and their descriptors are * Trap and Interrupt gates are similar, and their descriptors are
* structurally the same, they differ only in the "type" field. The * structurally the same, they differ only in the "type" field. The
* difference is that for interrupt gates, interrupts are automatically * difference is that for interrupt gates, interrupts are automatically
* disabled upon entry and reenabled upon IRET which restores the saved EFLAGS. * disabled upon entry and reenabled upon IRET which restores the saved EFLAGS.
*/ */
/// @brief This structure describes one interrupt gate. /// @brief This structure describes one interrupt gate.
typedef struct idt_descriptor_t typedef struct idt_descriptor_t {
{ unsigned short offset_low;
unsigned short offset_low; unsigned short seg_selector;
unsigned short seg_selector; // This will ALWAYS be set to 0.
// This will ALWAYS be set to 0. unsigned char null_par;
unsigned char null_par; // |P|DPL|01110|.
// |P|DPL|01110|. // P present, DPL required Ring (2bits).
// P present, DPL required Ring (2bits). unsigned char options;
unsigned char options; unsigned short offset_high;
unsigned short offset_high; } __attribute__((packed)) idt_descriptor_t;
} __attribute__((packed)) idt_descriptor_t;
/// @brief A pointer structure used for informing the CPU about our IDT.
/// @brief A pointer structure used for informing the CPU about our IDT. typedef struct idt_pointer_t {
typedef struct idt_pointer_t /// The size of the IDT (entry number).
{ unsigned short int limit;
/// The size of the IDT (entry number). /// The start address of the IDT.
unsigned short int limit; unsigned int base;
/// The start address of the IDT. } __attribute__((packed)) idt_pointer_t;
unsigned int base;
} __attribute__((packed)) idt_pointer_t; /// @brief Initialise the interrupt descriptor table.
void init_idt();
/// @brief Initialise the interrupt descriptor table.
void init_idt(); /// @brief Use this function to set an entry in the IDT.
/// @param index Indice della IDT.
/// @brief Use this function to set an entry in the IDT. /// @param handler Puntatore alla funzione che gestira' l'interrupt/Eccezione
/// @param index Indice della IDT. /// @param options Le opzioni del descrittore (PRESENT,NOTPRESENT,KERNEL,USER)
/// @param handler Puntatore alla funzione che gestira' l'interrupt/Eccezione /// @param seg_sel Il selettore del segmento della GDT.
/// @param options Le opzioni del descrittore (PRESENT,NOTPRESENT,KERNEL,USER) void idt_set_gate(uint8_t index, interrupt_handler_t handler, uint16_t options,
/// @param seg_sel Il selettore del segmento della GDT. uint8_t seg_sel);
void idt_set_gate(uint8_t index,
interrupt_handler_t handler, //==== List of exceptions generated internally by the CPU ======================
uint16_t options, extern void INT_0();
uint8_t seg_sel);
extern void INT_1();
//==== List of exceptions generated internally by the CPU ======================
extern void INT_0(); extern void INT_2();
extern void INT_1(); extern void INT_3();
extern void INT_2(); extern void INT_4();
extern void INT_3(); extern void INT_5();
extern void INT_4(); extern void INT_6();
extern void INT_5(); extern void INT_7();
extern void INT_6(); extern void INT_8();
extern void INT_7(); extern void INT_9();
extern void INT_8(); extern void INT_10();
extern void INT_9(); extern void INT_11();
extern void INT_10(); extern void INT_12();
extern void INT_11(); extern void INT_13();
extern void INT_12(); extern void INT_14();
extern void INT_13(); extern void INT_15();
extern void INT_14(); extern void INT_16();
extern void INT_15(); extern void INT_17();
extern void INT_16(); extern void INT_18();
extern void INT_17(); extern void INT_19();
extern void INT_18(); extern void INT_20();
extern void INT_19(); extern void INT_21();
extern void INT_20(); extern void INT_22();
extern void INT_21(); extern void INT_23();
extern void INT_22(); extern void INT_24();
extern void INT_23(); extern void INT_25();
extern void INT_24(); extern void INT_26();
extern void INT_25(); extern void INT_27();
extern void INT_26(); extern void INT_28();
extern void INT_27(); extern void INT_29();
extern void INT_28(); extern void INT_30();
extern void INT_29(); extern void INT_31();
extern void INT_30(); extern void INT_80();
//==============================================================================
extern void INT_31();
//==== List of interrupts generated by PIC =====================================
extern void INT_80(); extern void IRQ_0();
//==============================================================================
extern void IRQ_1();
//==== List of interrupts generated by PIC =====================================
extern void IRQ_0(); extern void IRQ_2();
extern void IRQ_1(); extern void IRQ_3();
extern void IRQ_2(); extern void IRQ_4();
extern void IRQ_3(); extern void IRQ_5();
extern void IRQ_4(); extern void IRQ_6();
extern void IRQ_5(); extern void IRQ_7();
extern void IRQ_6(); extern void IRQ_8();
extern void IRQ_7(); extern void IRQ_9();
extern void IRQ_8(); extern void IRQ_10();
extern void IRQ_9(); extern void IRQ_11();
extern void IRQ_10(); extern void IRQ_12();
extern void IRQ_11(); extern void IRQ_13();
extern void IRQ_12(); extern void IRQ_14();
extern void IRQ_13(); extern void IRQ_15();
//==============================================================================
extern void IRQ_14();
extern void IRQ_15();
//==============================================================================
+129 -129
View File
@@ -1,129 +1,129 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file isr.h /// @file isr.h
/// @brief Data structures concerning the Interrupt Service Routines (ISRs). /// @brief Data structures concerning the Interrupt Service Routines (ISRs).
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "kernel.h" #include "kernel.h"
// TODO: see interrupt_handler_t in Linux, it is quite different. // TODO: see interrupt_handler_t in Linux, it is quite different.
/// @brief Interrupt handler definition. /// @brief Interrupt handler definition.
/// @details An interrupt handler is an interrupt service routine called /// @details An interrupt handler is an interrupt service routine called
/// to manage interrupt requests, or CPU execptions. /// to manage interrupt requests, or CPU execptions.
/// @param f An interrupt stack frame. /// @param f An interrupt stack frame.
typedef void (*interrupt_handler_t)(pt_regs *f); typedef void (*interrupt_handler_t)(pt_regs *f);
/// @brief For each exceptions isrs_init sets a default handler which /// @brief For each exceptions isrs_init sets a default handler which
/// prints the rose exceptions and stops kernel execution. /// prints the rose exceptions and stops kernel execution.
void isrs_init(); void isrs_init();
/// @brief For each interrupt irqs_init sets a default handler which /// @brief For each interrupt irqs_init sets a default handler which
/// prints the rose IRQ line and stops kernel execution. /// prints the rose IRQ line and stops kernel execution.
void irqs_init(); void irqs_init();
/* Even if an interrupt service routine is called for exceptions and /* Even if an interrupt service routine is called for exceptions and
* interrupts, we use two distinct methods to logically setup an ISR to * interrupts, we use two distinct methods to logically setup an ISR to
* handle theme. Tecnically speacking, exceptions are synchronous interrupts * handle theme. Tecnically speacking, exceptions are synchronous interrupts
* generated by CPU. For an exception we have an ISR. Interrupts are * generated by CPU. For an exception we have an ISR. Interrupts are
* asynchronous events generated by PIC. Furthermore, multiple ISRs can be set * asynchronous events generated by PIC. Furthermore, multiple ISRs can be set
* for a same IRQ. * for a same IRQ.
*/ */
/// @brief Installs an ISR to handle an exception. /// @brief Installs an ISR to handle an exception.
/// @param i Exception identifier. /// @param i Exception identifier.
/// @param handler Exception handler. /// @param handler Exception handler.
/// @return 0 On success, -1 otherwise. /// @return 0 On success, -1 otherwise.
int isr_install_handler(uint32_t i, interrupt_handler_t handler, int isr_install_handler(uint32_t i, interrupt_handler_t handler,
char *description); char *description);
/// @brief Installs an ISR to handle an interrupt. /// @brief Installs an ISR to handle an interrupt.
/// @param i Interrupt identifier. /// @param i Interrupt identifier.
/// @param handler Interrupt handler. /// @param handler Interrupt handler.
/// @return 0 On success, -1 otherwise. /// @return 0 On success, -1 otherwise.
int irq_install_handler(uint32_t i, interrupt_handler_t handler, int irq_install_handler(uint32_t i, interrupt_handler_t handler,
char *description); char *description);
/// @brief Method called by CPU to handle interrupts. /// @brief Method called by CPU to handle interrupts.
/// @param f The interrupt stack frame. /// @param f The interrupt stack frame.
extern void irq_handler(pt_regs *f); extern void irq_handler(pt_regs *f);
/// @brief Method called by CPU to handle exceptions. /// @brief Method called by CPU to handle exceptions.
/// @param f The interrupt stack frame. /// @param f The interrupt stack frame.
extern void isq_handler(pt_regs *f); extern void isq_handler(pt_regs *f);
//==== List of exceptions generated internally by the CPU ====================== //==== List of exceptions generated internally by the CPU ======================
/// @brief DE Divide Error. /// @brief DE Divide Error.
#define DIVIDE_ERROR 0 #define DIVIDE_ERROR 0
/// @brief DB Debug. /// @brief DB Debug.
#define DEBUG_EXC 1 #define DEBUG_EXC 1
/// @brief Non Mascable Interrupt. /// @brief Non Mascable Interrupt.
#define NMI_INTERRUPT 2 #define NMI_INTERRUPT 2
/// @brief BP Breakpoint. /// @brief BP Breakpoint.
#define BREAKPOINT 3 #define BREAKPOINT 3
/// @brief OF Overflow. /// @brief OF Overflow.
#define OVERFLOW 4 #define OVERFLOW 4
/// @brief BR Bound Range Exception. /// @brief BR Bound Range Exception.
#define BOUND_RANGE_EXCEED 5 #define BOUND_RANGE_EXCEED 5
/// @brief UD Invalid OpCode Exception. /// @brief UD Invalid OpCode Exception.
#define INVALID_OPCODE 6 #define INVALID_OPCODE 6
/// @brief NM Device Not Available. /// @brief NM Device Not Available.
#define DEV_NOT_AVL 7 #define DEV_NOT_AVL 7
/// @brief DF Double Fault. /// @brief DF Double Fault.
#define DOUBLE_FAULT 8 #define DOUBLE_FAULT 8
/// @brief Coprocessor Segment Overrun. /// @brief Coprocessor Segment Overrun.
#define COPROC_SEG_OVERRUN 9 #define COPROC_SEG_OVERRUN 9
/// @brief TS Invalid TSS. /// @brief TS Invalid TSS.
#define INVALID_TSS 10 #define INVALID_TSS 10
/// @brief NP Segment Not Present. /// @brief NP Segment Not Present.
#define SEGMENT_NOT_PRESENT 11 #define SEGMENT_NOT_PRESENT 11
/// @brief SS Stack Segment Fault. /// @brief SS Stack Segment Fault.
#define STACK_SEGMENT_FAULT 12 #define STACK_SEGMENT_FAULT 12
/// @brief GP General Protection. /// @brief GP General Protection.
#define GENERAL_PROTECTION 13 #define GENERAL_PROTECTION 13
/// @brief PF Page Fault. /// @brief PF Page Fault.
#define PAGE_FAULT 14 #define PAGE_FAULT 14
/// @brief XX Reserverd. /// @brief XX Reserverd.
#define INT_RSV 15 #define INT_RSV 15
/// @brief MF Floating Point. /// @brief MF Floating Point.
#define FLOATING_POINT_ERR 16 #define FLOATING_POINT_ERR 16
/// @brief AC Alignment Check. /// @brief AC Alignment Check.
#define ALIGNMENT_CHECK 17 #define ALIGNMENT_CHECK 17
/// @brief MC Machine Check. /// @brief MC Machine Check.
#define MACHINE_CHECK 18 #define MACHINE_CHECK 18
/// @brief XF Streaming SIMD Exception. /// @brief XF Streaming SIMD Exception.
#define SIMD_FP_EXC 19 #define SIMD_FP_EXC 19
/// @brief Virtualization Exception. /// @brief Virtualization Exception.
#define VIRT_EXC 20 #define VIRT_EXC 20
/// @brief Reserved [21-29]. /// @brief Reserved [21-29].
/// @brief Security Exception. /// @brief Security Exception.
#define SECURITY_EXC 30 #define SECURITY_EXC 30
/// @brief Triple Fault /// @brief Triple Fault
#define TRIPLE_FAULT 31 #define TRIPLE_FAULT 31
/// @brief System call interrupt. /// @brief System call interrupt.
#define SYSTEM_CALL 80 #define SYSTEM_CALL 80
//============================================================================== //==============================================================================
+61 -61
View File
@@ -1,61 +1,61 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file tss.h /// @file tss.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "gdt.h" #include "gdt.h"
#include "stdio.h" #include "stdio.h"
#include "kernel.h" #include "kernel.h"
// TODO: doxygen comment. // TODO: doxygen comment.
typedef struct tss_entry { typedef struct tss_entry {
uint32_t prevTss; uint32_t prevTss;
uint32_t esp0; uint32_t esp0;
uint32_t ss0; uint32_t ss0;
uint32_t esp1; uint32_t esp1;
uint32_t ss1; uint32_t ss1;
uint32_t esp2; uint32_t esp2;
uint32_t ss2; uint32_t ss2;
uint32_t cr3; uint32_t cr3;
uint32_t eip; uint32_t eip;
uint32_t eflags; uint32_t eflags;
uint32_t eax; uint32_t eax;
uint32_t ecx; uint32_t ecx;
uint32_t edx; uint32_t edx;
uint32_t ebx; uint32_t ebx;
uint32_t esp; uint32_t esp;
uint32_t ebp; uint32_t ebp;
uint32_t esi; uint32_t esi;
uint32_t edi; uint32_t edi;
uint32_t es; uint32_t es;
uint32_t cs; uint32_t cs;
uint32_t ss; uint32_t ss;
uint32_t ds; uint32_t ds;
uint32_t fs; uint32_t fs;
uint32_t gs; uint32_t gs;
uint32_t ldt; uint32_t ldt;
uint16_t trap; uint16_t trap;
uint16_t iomap; uint16_t iomap;
} tss_entry_t; } tss_entry_t;
extern void tss_flush(); extern void tss_flush();
/// @brief We don't need tss to assist task switching, but it's required to /// @brief We don't need tss to assist task switching, but it's required to
/// have one tss for switching back to kernel mode(system call for /// have one tss for switching back to kernel mode(system call for
/// example). /// example).
/// @param idx /// @param idx
/// @param kss /// @param kss
/// @param kesp /// @param kesp
void tss_init(uint8_t idx, uint32_t kss, uint32_t kesp); void tss_init(uint8_t idx, uint32_t kss, uint32_t kesp);
// esp the kernel should be using. // esp the kernel should be using.
/// @brief This function is used to set the tss's esp, so that CPU knows what. /// @brief This function is used to set the tss's esp, so that CPU knows what.
/// @param kss /// @param kss
/// @param kesp /// @param kesp
void tss_set_stack(uint32_t kss, uint32_t kesp); void tss_set_stack(uint32_t kss, uint32_t kesp);
// TODO: doxygen comment. // TODO: doxygen comment.
void print_tss(); void print_tss();
+21 -21
View File
@@ -1,21 +1,21 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file fpu.h /// @file fpu.h
/// @brief Floating Point Unit (FPU). /// @brief Floating Point Unit (FPU).
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#include "stdint.h" #include "stdint.h"
#include "stdbool.h" #include "stdbool.h"
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void switch_fpu(); void switch_fpu();
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void unswitch_fpu(); void unswitch_fpu();
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
/// @return /// @return
bool_t fpu_install(); bool_t fpu_install();
+247 -247
View File
@@ -1,247 +1,247 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file pci.h /// @file pci.h
/// @brief Routines for PCI initialization. /// @brief Routines for PCI initialization.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
/// @defgroup pci_configuration_space The PCI configuration space. /// @defgroup pci_configuration_space The PCI configuration space.
/// The PCI Specification defines the organization of the 256-byte. /// The PCI Specification defines the organization of the 256-byte.
/// Configuration Space registers and imposes a specific template for the /// Configuration Space registers and imposes a specific template for the
/// space. Figures 2 & 3 show the layout of the 256-byte Configuration space. /// space. Figures 2 & 3 show the layout of the 256-byte Configuration space.
/// All PCI compliant devices must support the Vendor ID, Device ID, Command /// All PCI compliant devices must support the Vendor ID, Device ID, Command
/// and Status, Revision ID, Class Code and Header Type fields. Implementation /// and Status, Revision ID, Class Code and Header Type fields. Implementation
/// of the other registers is optional, depending upon the devices /// of the other registers is optional, depending upon the devices
/// functionality. /// functionality.
/// @{ /// @{
/// 16 bits - Identifies the manufacturer of the device. Where valid IDs are /// 16 bits - Identifies the manufacturer of the device. Where valid IDs are
/// allocated by PCI-SIG (the list is here) to ensure uniqueness and 0xFFFF is /// allocated by PCI-SIG (the list is here) to ensure uniqueness and 0xFFFF is
/// an invalid value that will be returned on read accesses to Configuration /// an invalid value that will be returned on read accesses to Configuration
/// Space registers of non-existent devices. /// Space registers of non-existent devices.
#define PCI_VENDOR_ID 0x00 #define PCI_VENDOR_ID 0x00
/// 16 bits - Identifies the particular device. Where valid IDs are allocated /// 16 bits - Identifies the particular device. Where valid IDs are allocated
/// by the vendor. /// by the vendor.
#define PCI_DEVICE_ID 0x02 #define PCI_DEVICE_ID 0x02
/// 16 bits - Provides control over a device's ability to generate and /// 16 bits - Provides control over a device's ability to generate and
/// respond to PCI cycles. Where the only functionality guaranteed to be /// respond to PCI cycles. Where the only functionality guaranteed to be
/// supported by all devices is, when a 0 is written to this register, the /// supported by all devices is, when a 0 is written to this register, the
/// device is disconnected from the PCI bus for all accesses except /// device is disconnected from the PCI bus for all accesses except
/// Configuration Space access. /// Configuration Space access.
#define PCI_COMMAND 0x04 #define PCI_COMMAND 0x04
/// 16 bits - A register used to record status information for PCI bus /// 16 bits - A register used to record status information for PCI bus
/// related events. /// related events.
#define PCI_STATUS 0x06 #define PCI_STATUS 0x06
/// 8 bits - Specifies a revision identifier for a particular device. Where /// 8 bits - Specifies a revision identifier for a particular device. Where
/// valid IDs are allocated by the vendor. /// valid IDs are allocated by the vendor.
#define PCI_REVISION_ID 0x08 #define PCI_REVISION_ID 0x08
/// 8 bits - A read-only register that specifies a register-level /// 8 bits - A read-only register that specifies a register-level
/// programming interface the device has, if it has any at all. /// programming interface the device has, if it has any at all.
#define PCI_PROG_IF 0x09 #define PCI_PROG_IF 0x09
/// 8 bits - A read-only register that specifies the specific function the /// 8 bits - A read-only register that specifies the specific function the
/// device performs. /// device performs.
#define PCI_SUBCLASS 0x0a #define PCI_SUBCLASS 0x0a
/// 8 bits - A read-only register that specifies the type of function the /// 8 bits - A read-only register that specifies the type of function the
/// device performs. /// device performs.
#define PCI_CLASS 0x0b #define PCI_CLASS 0x0b
/// 8 bits - Specifies the system cache line size in 32-bit units. A device /// 8 bits - Specifies the system cache line size in 32-bit units. A device
/// can limit the number of cacheline sizes it can support, if a unsupported /// can limit the number of cacheline sizes it can support, if a unsupported
/// value is written to this field, the device will behave as if a value of 0 /// value is written to this field, the device will behave as if a value of 0
/// was written. /// was written.
#define PCI_CACHE_LINE_SIZE 0x0c #define PCI_CACHE_LINE_SIZE 0x0c
/// 8 bits - Specifies the latency timer in units of PCI bus clocks. /// 8 bits - Specifies the latency timer in units of PCI bus clocks.
#define PCI_LATENCY_TIMER 0x0d #define PCI_LATENCY_TIMER 0x0d
/// 8 bits - Identifies the layout of the rest of the header beginning at /// 8 bits - Identifies the layout of the rest of the header beginning at
/// byte 0x10 of the header and also specifies whether or not the device has /// byte 0x10 of the header and also specifies whether or not the device has
/// multiple functions. Where a value of 0x00 specifies a general device, a /// multiple functions. Where a value of 0x00 specifies a general device, a
/// value of 0x01 specifies a PCI-to-PCI bridge, and a value of 0x02 specifies /// value of 0x01 specifies a PCI-to-PCI bridge, and a value of 0x02 specifies
/// a CardBus bridge. If bit 7 of this register is set, the device has /// a CardBus bridge. If bit 7 of this register is set, the device has
/// multiple functions; otherwise, it is a single function device. /// multiple functions; otherwise, it is a single function device.
#define PCI_HEADER_TYPE 0x0e #define PCI_HEADER_TYPE 0x0e
/// 8 bits - Represents that status and allows control of a devices BIST /// 8 bits - Represents that status and allows control of a devices BIST
/// (built-in self test). /// (built-in self test).
#define PCI_BIST 0x0f #define PCI_BIST 0x0f
/// @defgroup pci_base_addresses The PCI base addresses. /// @defgroup pci_base_addresses The PCI base addresses.
/// Base addresses specify locations in memory or I/O space. /// Base addresses specify locations in memory or I/O space.
/// Decoded size can be determined by writing a value of 0xffffffff to the /// Decoded size can be determined by writing a value of 0xffffffff to the
/// register, and reading it back. Only 1 bits are decoded. /// register, and reading it back. Only 1 bits are decoded.
/// @{ /// @{
#define PCI_BASE_ADDRESS_0 0x10 #define PCI_BASE_ADDRESS_0 0x10
#define PCI_BASE_ADDRESS_1 0x14 #define PCI_BASE_ADDRESS_1 0x14
#define PCI_BASE_ADDRESS_2 0x18 #define PCI_BASE_ADDRESS_2 0x18
#define PCI_BASE_ADDRESS_3 0x1c #define PCI_BASE_ADDRESS_3 0x1c
#define PCI_BASE_ADDRESS_4 0x20 #define PCI_BASE_ADDRESS_4 0x20
#define PCI_BASE_ADDRESS_5 0x24 #define PCI_BASE_ADDRESS_5 0x24
/// @} pci_base_addresses /// @} pci_base_addresses
/// Points to the Card Information Structure and is used by devices that /// Points to the Card Information Structure and is used by devices that
/// share silicon between CardBus and PCI. /// share silicon between CardBus and PCI.
#define PCI_CARDBUS_CIS 0x28 #define PCI_CARDBUS_CIS 0x28
#define PCI_SUBSYSTEM_VENDOR_ID 0x2c #define PCI_SUBSYSTEM_VENDOR_ID 0x2c
#define PCI_SUBSYSTEM_ID 0x2e #define PCI_SUBSYSTEM_ID 0x2e
#define PCI_ROM_ADDRESS 0x30 #define PCI_ROM_ADDRESS 0x30
/// Points to a linked list of new capabilities implemented by the device. /// Points to a linked list of new capabilities implemented by the device.
/// Used if bit 4 of the status register (Capabilities List bit) is set to 1. /// Used if bit 4 of the status register (Capabilities List bit) is set to 1.
/// The bottom two bits are reserved and should be masked before the Pointer /// The bottom two bits are reserved and should be masked before the Pointer
/// is used to access the Configuration Space. /// is used to access the Configuration Space.
#define PCI_CAPABILITY_LIST 0x34 #define PCI_CAPABILITY_LIST 0x34
/// Specifies which input of the system interrupt controllers the device's /// Specifies which input of the system interrupt controllers the device's
/// interrupt pin is connected to and is implemented by any device that makes /// interrupt pin is connected to and is implemented by any device that makes
/// use of an interrupt pin. For the x86 architecture this register /// use of an interrupt pin. For the x86 architecture this register
/// corresponds to the PIC IRQ numbers 0-15 (and not I/O APIC IRQ numbers) and /// corresponds to the PIC IRQ numbers 0-15 (and not I/O APIC IRQ numbers) and
/// a value of 0xFF defines no connection. /// a value of 0xFF defines no connection.
#define PCI_INTERRUPT_LINE 0x3c #define PCI_INTERRUPT_LINE 0x3c
/// Specifies which interrupt pin the device uses. Where a value of 0x01 is /// Specifies which interrupt pin the device uses. Where a value of 0x01 is
/// INTA#, 0x02 is INTB#, 0x03 is INTC#, 0x04 is INTD#, and 0x00 means the /// INTA#, 0x02 is INTB#, 0x03 is INTC#, 0x04 is INTD#, and 0x00 means the
/// device does not use an interrupt pin. /// device does not use an interrupt pin.
#define PCI_INTERRUPT_PIN 0x3d #define PCI_INTERRUPT_PIN 0x3d
/// A read-only register that specifies the burst period length, in 1/4 /// A read-only register that specifies the burst period length, in 1/4
/// microsecond units, that the device needs (assuming a 33 MHz clock rate). /// microsecond units, that the device needs (assuming a 33 MHz clock rate).
#define PCI_MIN_GNT 0x3e #define PCI_MIN_GNT 0x3e
/// A read-only register that specifies how often the device needs access to /// A read-only register that specifies how often the device needs access to
/// the PCI bus (in 1/4 microsecond units). /// the PCI bus (in 1/4 microsecond units).
#define PCI_MAX_LAT 0x3f #define PCI_MAX_LAT 0x3f
/// @} pci_configuration_space /// @} pci_configuration_space
#define PCI_SECONDARY_BUS 0x19 #define PCI_SECONDARY_BUS 0x19
#define PCI_HEADER_TYPE_DEVICE 0 #define PCI_HEADER_TYPE_DEVICE 0
#define PCI_HEADER_TYPE_BRIDGE 1 #define PCI_HEADER_TYPE_BRIDGE 1
#define PCI_HEADER_TYPE_CARDBUS 2 #define PCI_HEADER_TYPE_CARDBUS 2
#define PCI_TYPE_BRIDGE 0x060400 #define PCI_TYPE_BRIDGE 0x060400
#define PCI_TYPE_SATA 0x010600 #define PCI_TYPE_SATA 0x010600
#define PCI_ADDRESS_PORT 0xCF8 #define PCI_ADDRESS_PORT 0xCF8
#define PCI_VALUE_PORT 0xCFC #define PCI_VALUE_PORT 0xCFC
#define PCI_NONE 0xFFFF #define PCI_NONE 0xFFFF
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
typedef void (*pci_func_t)(uint32_t device, uint16_t vendor_id, typedef void (*pci_func_t)(uint32_t device, uint16_t vendor_id,
uint16_t device_id, void *extra); uint16_t device_id, void *extra);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
static inline int pci_extract_bus(uint32_t device) static inline int pci_extract_bus(uint32_t device)
{ {
return (uint8_t)((device >> 16)); return (uint8_t)((device >> 16));
} }
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
static inline int pci_extract_slot(uint32_t device) static inline int pci_extract_slot(uint32_t device)
{ {
return (uint8_t)((device >> 8)); return (uint8_t)((device >> 8));
} }
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
static inline int pci_extract_func(uint32_t device) static inline int pci_extract_func(uint32_t device)
{ {
return (uint8_t)(device); return (uint8_t)(device);
} }
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
static inline uint32_t pci_get_addr(uint32_t device, int field) static inline uint32_t pci_get_addr(uint32_t device, int field)
{ {
return 0x80000000 | (pci_extract_bus(device) << 16) | return 0x80000000 | (pci_extract_bus(device) << 16) |
(pci_extract_slot(device) << 11) | (pci_extract_slot(device) << 11) | (pci_extract_func(device) << 8) |
(pci_extract_func(device) << 8) | ((field)&0xFC); ((field)&0xFC);
} }
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
static inline uint32_t pci_box_device(int bus, int slot, int func) static inline uint32_t pci_box_device(int bus, int slot, int func)
{ {
return (uint32_t)((bus << 16) | (slot << 8) | func); return (uint32_t)((bus << 16) | (slot << 8) | func);
} }
/// @brief Reads a field from the given PCI device. /// @brief Reads a field from the given PCI device.
uint32_t pci_read_field(uint32_t device, int field, int size); uint32_t pci_read_field(uint32_t device, int field, int size);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void pci_write_field(uint32_t device, int field, int size, uint32_t value); void pci_write_field(uint32_t device, int field, int size, uint32_t value);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
uint32_t pci_find_type(uint32_t device); uint32_t pci_find_type(uint32_t device);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
const char *pci_vendor_lookup(unsigned short vendor_id); const char *pci_vendor_lookup(unsigned short vendor_id);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
const char *pci_device_lookup(unsigned short vendor_id, const char *pci_device_lookup(unsigned short vendor_id,
unsigned short device_id); unsigned short device_id);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void pci_scan_hit(pci_func_t f, uint32_t dev, void *extra); void pci_scan_hit(pci_func_t f, uint32_t dev, void *extra);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void pci_scan_func(pci_func_t f, int type, int bus, int slot, int func, void pci_scan_func(pci_func_t f, int type, int bus, int slot, int func,
void *extra); void *extra);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void pci_scan_slot(pci_func_t f, int type, int bus, int slot, void *extra); void pci_scan_slot(pci_func_t f, int type, int bus, int slot, void *extra);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void pci_scan_bus(pci_func_t f, int type, int bus, void *extra); void pci_scan_bus(pci_func_t f, int type, int bus, void *extra);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void pci_scan(pci_func_t f, int type, void *extra); void pci_scan(pci_func_t f, int type, void *extra);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void pci_remap(void); void pci_remap(void);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
int pci_get_interrupt(uint32_t device); int pci_get_interrupt(uint32_t device);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void pci_debug_scan(); void pci_debug_scan();
+199 -199
View File
@@ -1,199 +1,199 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
// @file ata.h // @file ata.h
/// @brief ATA values and data structures. /// @brief ATA values and data structures.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
/// @defgroup ata_defines The ATA configuration registers. /// @defgroup ata_defines The ATA configuration registers.
/// @{ /// @{
/// @defgroup status_register Status register bits /// @defgroup status_register Status register bits
/// @{ /// @{
/// Device Busy /// Device Busy
#define ATA_STAT_BUSY 0x80 #define ATA_STAT_BUSY 0x80
/// Device Ready /// Device Ready
#define ATA_STAT_READY 0x40 #define ATA_STAT_READY 0x40
/// Device Fault /// Device Fault
#define ATA_STAT_FAULT 0x20 #define ATA_STAT_FAULT 0x20
/// Device Seek Complete /// Device Seek Complete
#define ATA_STAT_SEEK 0x10 #define ATA_STAT_SEEK 0x10
/// Data Request (ready) /// Data Request (ready)
#define ATA_STAT_DRQ 0x08 #define ATA_STAT_DRQ 0x08
/// Corrected Data Error /// Corrected Data Error
#define ATA_STAT_CORR 0x04 #define ATA_STAT_CORR 0x04
/// Vendor specific /// Vendor specific
#define ATA_STAT_INDEX 0x02 #define ATA_STAT_INDEX 0x02
/// Error /// Error
#define ATA_STAT_ERR 0x01 #define ATA_STAT_ERR 0x01
/// @} /// @}
/// @defgroup device_registers Device / Head Register Bits /// @defgroup device_registers Device / Head Register Bits
/// @{ /// @{
#define ATA_DEVICE(x) ((x & 1) << 4) #define ATA_DEVICE(x) ((x & 1) << 4)
#define ATA_LBA 0xE0 #define ATA_LBA 0xE0
/// @} /// @}
/// @defgroup ata_commands ATA Commands /// @defgroup ata_commands ATA Commands
/// @{ /// @{
/// Read Sectors (with retries) /// Read Sectors (with retries)
#define ATA_CMD_READ 0x20 #define ATA_CMD_READ 0x20
/// Read Sectors (no retries) /// Read Sectors (no retries)
#define ATA_CMD_READN 0x21 #define ATA_CMD_READN 0x21
/// Write Sectores (with retries) /// Write Sectores (with retries)
#define ATA_CMD_WRITE 0x30 #define ATA_CMD_WRITE 0x30
/// Write Sectors (no retries) /// Write Sectors (no retries)
#define ATA_CMD_WRITEN 0x31 #define ATA_CMD_WRITEN 0x31
/// Read Verify (with retries) /// Read Verify (with retries)
#define ATA_CMD_VRFY 0x40 #define ATA_CMD_VRFY 0x40
/// Read verify (no retries) /// Read verify (no retries)
#define ATA_CMD_VRFYN 0x41 #define ATA_CMD_VRFYN 0x41
/// Seek /// Seek
#define ATA_CMD_SEEK 0x70 #define ATA_CMD_SEEK 0x70
/// Execute Device Diagnostic /// Execute Device Diagnostic
#define ATA_CMD_DIAG 0x90 #define ATA_CMD_DIAG 0x90
/// Initialize Device Parameters /// Initialize Device Parameters
#define ATA_CMD_INIT 0x91 #define ATA_CMD_INIT 0x91
/// Read Multiple /// Read Multiple
#define ATA_CMD_RD_MULT 0xC4 #define ATA_CMD_RD_MULT 0xC4
/// Write Multiple /// Write Multiple
#define ATA_CMD_WR_MULT 0xC5 #define ATA_CMD_WR_MULT 0xC5
/// Set Multiple Mode /// Set Multiple Mode
#define ATA_CMD_SETMULT 0xC6 #define ATA_CMD_SETMULT 0xC6
/// Read DMA (with retries) /// Read DMA (with retries)
#define ATA_CMD_RD_DMA 0xC8 #define ATA_CMD_RD_DMA 0xC8
/// Read DMS (no retries) /// Read DMS (no retries)
#define ATA_CMD_RD_DMAN 0xC9 #define ATA_CMD_RD_DMAN 0xC9
/// Write DMA (with retries) /// Write DMA (with retries)
#define ATA_CMD_WR_DMA 0xCA #define ATA_CMD_WR_DMA 0xCA
/// Write DMA (no retires) /// Write DMA (no retires)
#define ATA_CMD_WR_DMAN 0xCB #define ATA_CMD_WR_DMAN 0xCB
/// Identify Device /// Identify Device
#define ATA_CMD_IDENT 0xEC #define ATA_CMD_IDENT 0xEC
#define ATA_CMD_CH_FLSH 0xE7 #define ATA_CMD_CH_FLSH 0xE7
/// Set Features /// Set Features
#define ATA_CMD_SETF 0xEF #define ATA_CMD_SETF 0xEF
/// Check Power Mode /// Check Power Mode
#define ATA_CMD_CHK_PWR 0xE5 #define ATA_CMD_CHK_PWR 0xE5
/// @} /// @}
/// @defgroup atapi_commands ATAPI Commands /// @defgroup atapi_commands ATAPI Commands
/// @{ /// @{
#define ATAPI_CMD_PACKET 0xA0 #define ATAPI_CMD_PACKET 0xA0
#define ATAPI_CMD_ID_PCKT 0xA1 #define ATAPI_CMD_ID_PCKT 0xA1
/// @} /// @}
#define ATA_IDENT_DEVICETYPE 0 #define ATA_IDENT_DEVICETYPE 0
#define ATA_IDENT_CYLINDERS 2 #define ATA_IDENT_CYLINDERS 2
#define ATA_IDENT_HEADS 6 #define ATA_IDENT_HEADS 6
#define ATA_IDENT_SECTORS 12 #define ATA_IDENT_SECTORS 12
#define ATA_IDENT_SERIAL 20 #define ATA_IDENT_SERIAL 20
#define ATA_IDENT_MODEL 54 #define ATA_IDENT_MODEL 54
#define ATA_IDENT_CAPABILITIES 98 #define ATA_IDENT_CAPABILITIES 98
#define ATA_IDENT_FIELDVALID 106 #define ATA_IDENT_FIELDVALID 106
#define ATA_IDENT_MAX_LBA 120 #define ATA_IDENT_MAX_LBA 120
#define ATA_IDENT_COMMANDSETS 164 #define ATA_IDENT_COMMANDSETS 164
#define ATA_IDENT_MAX_LBA_EXT 200 #define ATA_IDENT_MAX_LBA_EXT 200
#define IDE_ATA 0x00 #define IDE_ATA 0x00
#define IDE_ATAPI 0x01 #define IDE_ATAPI 0x01
#define ATA_MASTER 0x00 #define ATA_MASTER 0x00
#define ATA_SLAVE 0x01 #define ATA_SLAVE 0x01
#define ATA_REG_DATA 0x00 #define ATA_REG_DATA 0x00
#define ATA_REG_ERROR 0x01 #define ATA_REG_ERROR 0x01
#define ATA_REG_FEATURES 0x01 #define ATA_REG_FEATURES 0x01
#define ATA_REG_SECCOUNT0 0x02 #define ATA_REG_SECCOUNT0 0x02
#define ATA_REG_LBA0 0x03 #define ATA_REG_LBA0 0x03
#define ATA_REG_LBA1 0x04 #define ATA_REG_LBA1 0x04
#define ATA_REG_LBA2 0x05 #define ATA_REG_LBA2 0x05
#define ATA_REG_HDDEVSEL 0x06 #define ATA_REG_HDDEVSEL 0x06
#define ATA_REG_COMMAND 0x07 #define ATA_REG_COMMAND 0x07
#define ATA_REG_STATUS 0x07 #define ATA_REG_STATUS 0x07
#define ATA_REG_SECCOUNT1 0x08 #define ATA_REG_SECCOUNT1 0x08
#define ATA_REG_LBA3 0x09 #define ATA_REG_LBA3 0x09
#define ATA_REG_LBA4 0x0A #define ATA_REG_LBA4 0x0A
#define ATA_REG_LBA5 0x0B #define ATA_REG_LBA5 0x0B
#define ATA_REG_CONTROL 0x0C #define ATA_REG_CONTROL 0x0C
#define ATA_REG_ALTSTATUS 0x0C #define ATA_REG_ALTSTATUS 0x0C
#define ATA_REG_DEVADDRESS 0x0D #define ATA_REG_DEVADDRESS 0x0D
// Channels: // Channels:
#define ATA_PRIMARY 0x00 #define ATA_PRIMARY 0x00
#define ATA_SECONDARY 0x01 #define ATA_SECONDARY 0x01
// Directions: // Directions:
#define ATA_READ 0x00 #define ATA_READ 0x00
#define ATA_WRITE 0x01 #define ATA_WRITE 0x01
/// @} /// @}
typedef struct { typedef struct {
uint16_t base; uint16_t base;
uint16_t ctrl; uint16_t ctrl;
uint16_t bmide; uint16_t bmide;
uint16_t nien; uint16_t nien;
} ide_channel_regs_t; } ide_channel_regs_t;
typedef struct { typedef struct {
uint8_t reserved; uint8_t reserved;
uint8_t channel; uint8_t channel;
uint8_t drive; uint8_t drive;
uint16_t type; uint16_t type;
uint16_t signature; uint16_t signature;
uint16_t capabilities; uint16_t capabilities;
uint32_t command_sets; uint32_t command_sets;
uint32_t size; uint32_t size;
uint8_t model[41]; uint8_t model[41];
} ide_device_t; } ide_device_t;
typedef struct { typedef struct {
uint8_t status; uint8_t status;
uint8_t chs_first_sector[3]; uint8_t chs_first_sector[3];
uint8_t type; uint8_t type;
uint8_t chs_last_sector[3]; uint8_t chs_last_sector[3];
uint32_t lba_first_sector; uint32_t lba_first_sector;
uint32_t sector_count; uint32_t sector_count;
} partition_t; } partition_t;
typedef struct { typedef struct {
uint16_t flags; uint16_t flags;
uint16_t unused1[9]; uint16_t unused1[9];
char serial[20]; char serial[20];
uint16_t unused2[3]; uint16_t unused2[3];
char firmware[8]; char firmware[8];
char model[40]; char model[40];
uint16_t sectors_per_int; uint16_t sectors_per_int;
uint16_t unused3; uint16_t unused3;
uint16_t capabilities[2]; uint16_t capabilities[2];
uint16_t unused4[2]; uint16_t unused4[2];
uint16_t valid_ext_data; uint16_t valid_ext_data;
uint16_t unused5[5]; uint16_t unused5[5];
uint16_t size_of_rw_mult; uint16_t size_of_rw_mult;
uint32_t sectors_28; uint32_t sectors_28;
uint16_t unused6[38]; uint16_t unused6[38];
uint64_t sectors_48; uint64_t sectors_48;
uint16_t unused7[152]; uint16_t unused7[152];
} __attribute__((packed)) ata_identify_t; } __attribute__((packed)) ata_identify_t;
typedef struct { typedef struct {
uint8_t boostrap[446]; uint8_t boostrap[446];
partition_t partitions[4]; partition_t partitions[4];
uint8_t signature[2]; uint8_t signature[2];
} __attribute__((packed)) mbr_t; } __attribute__((packed)) mbr_t;
int ata_initialize(); int ata_initialize();
int ata_finalize(); int ata_finalize();
+45 -45
View File
@@ -1,45 +1,45 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file fdc.h /// @file fdc.h
/// @brief Definitions about the floppy. /// @brief Definitions about the floppy.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/// @brief Floppy Disk Controller (FDC) registers. /// @brief Floppy Disk Controller (FDC) registers.
typedef enum fdc_registers_t typedef enum fdc_registers_t
{ {
STATUS_REGISTER_A = 0x3F0, STATUS_REGISTER_A = 0x3F0,
///< This register is read-only and monitors the state of the ///< This register is read-only and monitors the state of the
///< interrupt pin and several disk interface pins. ///< interrupt pin and several disk interface pins.
STATUS_REGISTER_B = 0x3F1, STATUS_REGISTER_B = 0x3F1,
///< This register is read-only and monitors the state of several ///< This register is read-only and monitors the state of several
///< isk interface pins. ///< isk interface pins.
DOR = 0x3F2, DOR = 0x3F2,
///< The Digital Output Register contains the drive select and ///< The Digital Output Register contains the drive select and
///< motor enable bits, a reset bit and a DMA GATE bit. ///< motor enable bits, a reset bit and a DMA GATE bit.
TAPE_DRIVE_REGISTER = 0x3F3, TAPE_DRIVE_REGISTER = 0x3F3,
///< This register allows the user to assign tape support to a ///< This register allows the user to assign tape support to a
///< particular drive during initialization. ///< particular drive during initialization.
MAIN_STATUS_REGISTER = 0x3F4, MAIN_STATUS_REGISTER = 0x3F4,
///< The Main Status Register is a read-only register and is used ///< The Main Status Register is a read-only register and is used
///< for controlling command input and result output for all commands. ///< for controlling command input and result output for all commands.
DATARATE_SELECT_REGISTER = 0x3F4, DATARATE_SELECT_REGISTER = 0x3F4,
///< This register is included for compatibility with the 82072 ///< This register is included for compatibility with the 82072
///< floppy controller and is write-only. ///< floppy controller and is write-only.
DATA_FIFO = 0x3F5, DATA_FIFO = 0x3F5,
///< All command parameter information and disk data transfers go ///< All command parameter information and disk data transfers go
///< through the FIFO. ///< through the FIFO.
DIGITAL_INPUT_REGISTER = 0x3F7, DIGITAL_INPUT_REGISTER = 0x3F7,
///< This register is read only in all modes. ///< This register is read only in all modes.
CONFIGURATION_CONTROL_REGISTER = 0x3F7 CONFIGURATION_CONTROL_REGISTER = 0x3F7
///< This register sets the datarate and is write only. ///< This register sets the datarate and is write only.
} fdc_registers_t; } fdc_registers_t;
/// @brief Allows to enable the motor. /// @brief Allows to enable the motor.
/// @details The motor enable pins are directly controlled via the DOR and /// @details The motor enable pins are directly controlled via the DOR and
/// are a function of the mapping based on BOOTSEL bits in the TDR. /// are a function of the mapping based on BOOTSEL bits in the TDR.
void fdc_enable_motor(void); void fdc_enable_motor(void);
/// @brief Allows to disable the motor. /// @brief Allows to disable the motor.
void fdc_disable_motor(void); void fdc_disable_motor(void);
+51 -51
View File
@@ -1,51 +1,51 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file keyboard.h /// @file keyboard.h
/// @brief Definitions about the keyboard. /// @brief Definitions about the keyboard.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "kernel.h" #include "kernel.h"
#include "stdint.h" #include "stdint.h"
#include "stdbool.h" #include "stdbool.h"
/// @brief The dimension of the circular buffer used to store video history. /// @brief The dimension of the circular buffer used to store video history.
#define BUFSIZE 256 #define BUFSIZE 256
/// @brief Function used to install the keyboard. /// @brief Function used to install the keyboard.
void keyboard_install(); void keyboard_install();
/// @brief The keyboard handler. /// @brief The keyboard handler.
void keyboard_isr(pt_regs *r); void keyboard_isr(pt_regs *r);
/// @brief Enable the keyboard. /// @brief Enable the keyboard.
void keyboard_enable(); void keyboard_enable();
/// @brief Disable the keyboard. /// @brief Disable the keyboard.
void keyboard_disable(); void keyboard_disable();
/// @brief Leds handler. /// @brief Leds handler.
void keyboard_update_leds(); void keyboard_update_leds();
/// @brief Get a char from the buffer. /// @brief Get a char from the buffer.
/// @details It loops until there is something new to read. /// @details It loops until there is something new to read.
/// @return The read character. /// @return The read character.
int keyboard_getc(); int keyboard_getc();
/// @brief Set Keyboard echo Shadow. /// @brief Set Keyboard echo Shadow.
/// @param value 1 if you want enable shadow, 0 otherwise. /// @param value 1 if you want enable shadow, 0 otherwise.
void keyboard_set_shadow(const bool_t value); void keyboard_set_shadow(const bool_t value);
/// @brief Set Keyboard echo Shadow character. /// @brief Set Keyboard echo Shadow character.
/// @param value 1 if you want enable shadow, 0 otherwise. /// @param value 1 if you want enable shadow, 0 otherwise.
void keyboard_set_shadow_character(const char _shadow_character); void keyboard_set_shadow_character(const char _shadow_character);
/// @brief Get Keyboard Shadow information. /// @brief Get Keyboard Shadow information.
bool_t keyboard_get_shadow(); bool_t keyboard_get_shadow();
/// @brief Get ctrl status. /// @brief Get ctrl status.
bool_t keyboard_is_ctrl_pressed(); bool_t keyboard_is_ctrl_pressed();
/// @brief Get shift status. /// @brief Get shift status.
bool_t keyboard_is_shifted(); bool_t keyboard_is_shifted();
+242 -242
View File
@@ -1,242 +1,242 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file keymap.h /// @file keymap.h
/// @brief Keymap for keyboard. /// @brief Keymap for keyboard.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
/// @defgroup keyboardcodes Keyboard Codes /// @defgroup keyboardcodes Keyboard Codes
/// @brief This is the list of keyboard codes. /// @brief This is the list of keyboard codes.
/// @{ /// @{
/// Escape character. /// Escape character.
#define KEY_ESCAPE 0x01 #define KEY_ESCAPE 0x01
/// 1. /// 1.
#define KEY_ONE 0x02 #define KEY_ONE 0x02
/// 2. /// 2.
#define KEY_TWO 0x03 #define KEY_TWO 0x03
/// 3. /// 3.
#define KEY_THREE 0x04 #define KEY_THREE 0x04
/// 4. /// 4.
#define KEY_FOUR 0x05 #define KEY_FOUR 0x05
/// 5. /// 5.
#define KEY_FIVE 0x06 #define KEY_FIVE 0x06
/// 6. /// 6.
#define KEY_SIX 0x07 #define KEY_SIX 0x07
/// 7. /// 7.
#define KEY_SEVEN 0x08 #define KEY_SEVEN 0x08
/// 8. /// 8.
#define KEY_EIGHT 0x09 #define KEY_EIGHT 0x09
/// 9. /// 9.
#define KEY_NINE 0x0A #define KEY_NINE 0x0A
/// 0. /// 0.
#define KEY_ZERO 0x0B #define KEY_ZERO 0x0B
/// '. /// '.
#define KEY_APOSTROPHE 0x0C #define KEY_APOSTROPHE 0x0C
/// i'. /// i'.
#define KEY_I_ACC 0x0D #define KEY_I_ACC 0x0D
/// Backspace. /// Backspace.
#define KEY_BACKSPACE 0x0E #define KEY_BACKSPACE 0x0E
/// Tabular. /// Tabular.
#define KEY_TAB 0x0F #define KEY_TAB 0x0F
/// q. /// q.
#define KEY_Q 0x10 #define KEY_Q 0x10
/// w. /// w.
#define KEY_W 0x11 #define KEY_W 0x11
/// e. /// e.
#define KEY_E 0x12 #define KEY_E 0x12
/// r. /// r.
#define KEY_R 0x13 #define KEY_R 0x13
/// t. /// t.
#define KEY_T 0x14 #define KEY_T 0x14
/// y. /// y.
#define KEY_Y 0x15 #define KEY_Y 0x15
/// u. /// u.
#define KEY_U 0x16 #define KEY_U 0x16
/// i. /// i.
#define KEY_I 0x17 #define KEY_I 0x17
/// o. /// o.
#define KEY_O 0x18 #define KEY_O 0x18
/// p. /// p.
#define KEY_P 0x19 #define KEY_P 0x19
/// (. /// (.
#define KEY_LEFT_BRAKET 0x1A #define KEY_LEFT_BRAKET 0x1A
/// ). /// ).
#define KEY_RIGHT_BRAKET 0x1B #define KEY_RIGHT_BRAKET 0x1B
/// Enter. /// Enter.
#define KEY_ENTER 0x1C #define KEY_ENTER 0x1C
/// Left-ctrl. /// Left-ctrl.
#define KEY_LEFT_CONTROL 0x1D #define KEY_LEFT_CONTROL 0x1D
/// a. /// a.
#define KEY_A 0x1E #define KEY_A 0x1E
/// s. /// s.
#define KEY_S 0x1F #define KEY_S 0x1F
/// d. /// d.
#define KEY_D 0x20 #define KEY_D 0x20
/// f. /// f.
#define KEY_F 0x21 #define KEY_F 0x21
/// g. /// g.
#define KEY_G 0x22 #define KEY_G 0x22
/// h. /// h.
#define KEY_H 0x23 #define KEY_H 0x23
/// j. /// j.
#define KEY_J 0x24 #define KEY_J 0x24
/// k. /// k.
#define KEY_K 0x25 #define KEY_K 0x25
/// l. /// l.
#define KEY_L 0x26 #define KEY_L 0x26
/// '. /// '.
#define KEY_SEMICOLON 0x27 #define KEY_SEMICOLON 0x27
/// ". /// ".
#define KEY_DOUBLE_QUOTES 0x28 #define KEY_DOUBLE_QUOTES 0x28
///` or ~. ///` or ~.
#define KEY_GRAVE 0x29 #define KEY_GRAVE 0x29
/// LShift. /// LShift.
#define KEY_LEFT_SHIFT 0x2A #define KEY_LEFT_SHIFT 0x2A
/// \ or |. /// \ or |.
#define KEY_BACKSLASH 0x2B #define KEY_BACKSLASH 0x2B
/// Z. /// Z.
#define KEY_Z 0x2c #define KEY_Z 0x2c
/// X. /// X.
#define KEY_X 0x2d #define KEY_X 0x2d
/// C. /// C.
#define KEY_C 0x2e #define KEY_C 0x2e
/// V. /// V.
#define KEY_V 0x2f #define KEY_V 0x2f
/// B. /// B.
#define KEY_B 0x30 #define KEY_B 0x30
/// N. /// N.
#define KEY_N 0x31 #define KEY_N 0x31
/// M. /// M.
#define KEY_M 0x32 #define KEY_M 0x32
/// , or <. /// , or <.
#define KEY_COMMA 0x33 #define KEY_COMMA 0x33
/// . or >. /// . or >.
#define KEY_PERIOD 0x34 #define KEY_PERIOD 0x34
/// - or _. /// - or _.
#define KEY_MINUS 0x35 #define KEY_MINUS 0x35
/// RShift. /// RShift.
#define KEY_RIGHT_SHIFT 0x36 #define KEY_RIGHT_SHIFT 0x36
/// NP - *. /// NP - *.
#define KEY_KP_MUL 0x37 #define KEY_KP_MUL 0x37
/// LAlt. /// LAlt.
#define KEY_LEFT_ALT 0x38 #define KEY_LEFT_ALT 0x38
/// Space. /// Space.
#define KEY_SPACE 0x39 #define KEY_SPACE 0x39
/// Caps Lock. /// Caps Lock.
#define KEY_CAPS_LOCK 0x3a #define KEY_CAPS_LOCK 0x3a
/// Function 1. /// Function 1.
#define KEY_F1 0x3B #define KEY_F1 0x3B
/// Function 2. /// Function 2.
#define KEY_F2 0x3C #define KEY_F2 0x3C
/// Function 3. /// Function 3.
#define KEY_F3 0x3D #define KEY_F3 0x3D
/// Function 4. /// Function 4.
#define KEY_F4 0x3E #define KEY_F4 0x3E
/// Function 5. /// Function 5.
#define KEY_F5 0x3F #define KEY_F5 0x3F
/// Function 6. /// Function 6.
#define KEY_F6 0x40 #define KEY_F6 0x40
/// Function 7. /// Function 7.
#define KEY_F7 0x41 #define KEY_F7 0x41
/// Function 8. /// Function 8.
#define KEY_F8 0x42 #define KEY_F8 0x42
/// Function 9. /// Function 9.
#define KEY_F9 0x43 #define KEY_F9 0x43
/// Function 10. /// Function 10.
#define KEY_F10 0x44 #define KEY_F10 0x44
/// Num Lock. /// Num Lock.
#define KEY_NUM_LOCK 0x45 #define KEY_NUM_LOCK 0x45
/// Scroll Lock. /// Scroll Lock.
#define KEY_SCROLL_LOCK 0x46 #define KEY_SCROLL_LOCK 0x46
/// NP - Home. /// NP - Home.
#define KEY_KP7 0x47 #define KEY_KP7 0x47
/// NP - UpArrow. /// NP - UpArrow.
#define KEY_KP8 0x48 #define KEY_KP8 0x48
/// NP - Pgup. /// NP - Pgup.
#define KEY_KP9 0x49 #define KEY_KP9 0x49
/// NP - Grey. /// NP - Grey.
#define KEY_KP_SUB 0x4A #define KEY_KP_SUB 0x4A
/// NP - LArrow. /// NP - LArrow.
#define KEY_KP4 0x4B #define KEY_KP4 0x4B
/// NP - Center. /// NP - Center.
#define KEY_KP5 0x4C #define KEY_KP5 0x4C
/// NP - RArrow. /// NP - RArrow.
#define KEY_KP6 0x4D #define KEY_KP6 0x4D
/// NP - Grey +. /// NP - Grey +.
#define KEY_KP_ADD 0x4E #define KEY_KP_ADD 0x4E
/// NP - End. /// NP - End.
#define KEY_KP1 0x4F #define KEY_KP1 0x4F
/// NP - DArrow. /// NP - DArrow.
#define KEY_KP2 0x50 #define KEY_KP2 0x50
/// NP - Pgdn. /// NP - Pgdn.
#define KEY_KP3 0x51 #define KEY_KP3 0x51
/// NP - Ins. /// NP - Ins.
#define KEY_KP0 0x52 #define KEY_KP0 0x52
/// NP - Del. /// NP - Del.
#define KEY_KP_DEC 0x53 #define KEY_KP_DEC 0x53
/// NP - Del. /// NP - Del.
#define KEY_KP_LESS 0x56 #define KEY_KP_LESS 0x56
/// NP - Enter 57372. /// NP - Enter 57372.
#define KEY_KP_RETURN 0xe01c #define KEY_KP_RETURN 0xe01c
/// Right Ctrl 57373. /// Right Ctrl 57373.
#define KEY_RIGHT_CONTROL 0xE01D #define KEY_RIGHT_CONTROL 0xE01D
/// Divide 57397. /// Divide 57397.
#define KEY_KP_DIV 0xE035 #define KEY_KP_DIV 0xE035
/// Right Alt 57400. /// Right Alt 57400.
#define KEY_RIGHT_ALT 0xe038 #define KEY_RIGHT_ALT 0xe038
/// F11 57431. /// F11 57431.
#define KEY_F11 0xe057 #define KEY_F11 0xe057
/// F12 57432. /// F12 57432.
#define KEY_F12 0xe058 #define KEY_F12 0xe058
/// Left Winkey 57435. /// Left Winkey 57435.
#define KEY_LEFT_WIN 0xe05b #define KEY_LEFT_WIN 0xe05b
/// Right Winkey 57436. /// Right Winkey 57436.
#define KEY_RIGHT_WIN 0xe05c #define KEY_RIGHT_WIN 0xe05c
/// Ins 57426. /// Ins 57426.
#define KEY_INSERT 0xe052 #define KEY_INSERT 0xe052
/// Home 57415. /// Home 57415.
#define KEY_HOME 0xe047 #define KEY_HOME 0xe047
/// Up Arrow 57416. /// Up Arrow 57416.
#define KEY_UP_ARROW 0xe048 #define KEY_UP_ARROW 0xe048
/// Pgup 57417. /// Pgup 57417.
#define KEY_PAGE_UP 0xe049 #define KEY_PAGE_UP 0xe049
/// Left Arrow 57419. /// Left Arrow 57419.
#define KEY_LEFT_ARROW 0xe04b #define KEY_LEFT_ARROW 0xe04b
/// Del 57427. /// Del 57427.
#define KEY_DELETE 0xe053 #define KEY_DELETE 0xe053
/// End 57423. /// End 57423.
#define KEY_END 0xe04f #define KEY_END 0xe04f
/// Pgdn 57425. /// Pgdn 57425.
#define KEY_PAGE_DOWN 0xe051 #define KEY_PAGE_DOWN 0xe051
/// Right Arrow 57421. /// Right Arrow 57421.
#define KEY_RIGHT_ARROW 0xe04d #define KEY_RIGHT_ARROW 0xe04d
/// Down Arrow 57424. /// Down Arrow 57424.
#define KEY_DOWN_ARROW 0xe050 #define KEY_DOWN_ARROW 0xe050
///< Code break code. ///< Code break code.
#define CODE_BREAK 0x80 #define CODE_BREAK 0x80
/// @} /// @}
/// Num Pad Led. /// Num Pad Led.
#define NUM_LED 0x45 #define NUM_LED 0x45
/// Scroll Lock Led. /// Scroll Lock Led.
#define SCROLL_LED 0x46 #define SCROLL_LED 0x46
/// Caps Lock Led. /// Caps Lock Led.
#define CAPS_LED 0x3a #define CAPS_LED 0x3a
/// @brief Defines a set of arrays used to map key to characters. /// @brief Defines a set of arrays used to map key to characters.
typedef struct keymap_t { typedef struct keymap_t {
/// The basic mapping. /// The basic mapping.
int32_t base[65536]; int32_t base[65536];
/// The mapping when shifted. /// The mapping when shifted.
int32_t shift[65536]; int32_t shift[65536];
/// The mapping when numlock is active. /// The mapping when numlock is active.
uint32_t numlock[65536]; uint32_t numlock[65536];
} keymap_t; } keymap_t;
/// @brief Italian keymap. /// @brief Italian keymap.
extern const keymap_t keymap_it; extern const keymap_t keymap_it;
+45 -45
View File
@@ -1,45 +1,45 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file mouse.h /// @file mouse.h
/// @brief Driver for *PS2* Mouses. /// @brief Driver for *PS2* Mouses.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/* The mouse starts sending automatic packets when the mouse moves or is /* The mouse starts sending automatic packets when the mouse moves or is
* clicked. * clicked.
*/ */
#include <kernel.h> #include <kernel.h>
#define MOUSE_ENABLE_PACKET 0xF4 #define MOUSE_ENABLE_PACKET 0xF4
/// The mouse stops sending automatic packets. /// The mouse stops sending automatic packets.
#define MOUSE_DISABLE_PACKET 0xF5 #define MOUSE_DISABLE_PACKET 0xF5
/// Disables streaming, sets the packet rate to 100 per second, and /// Disables streaming, sets the packet rate to 100 per second, and
/// resolution to 4 pixels per mm. /// resolution to 4 pixels per mm.
#define MOUSE_USE_DEFAULT_SETTINGS 0xF6 #define MOUSE_USE_DEFAULT_SETTINGS 0xF6
/// @brief Sets up the mouse by installing the mouse handler into IRQ12. /// @brief Sets up the mouse by installing the mouse handler into IRQ12.
void mouse_install(); void mouse_install();
/// @brief Enable the mouse driver. /// @brief Enable the mouse driver.
void mouse_enable(); void mouse_enable();
/// @brief Disable the mouse driver. /// @brief Disable the mouse driver.
void mouse_disable(); void mouse_disable();
/// @brief Mouse wait for a command. /// @brief Mouse wait for a command.
/// @param type 1 for sending - 0 for receiving. /// @param type 1 for sending - 0 for receiving.
void mouse_waitcmd(unsigned char type); void mouse_waitcmd(unsigned char type);
/// @brief Send data to mouse. /// @brief Send data to mouse.
/// @param data The data to send. /// @param data The data to send.
void mouse_write(unsigned char data); void mouse_write(unsigned char data);
/// @brief Read data from mouse. /// @brief Read data from mouse.
/// @return The data received from mouse. /// @return The data received from mouse.
unsigned char mouse_read(); unsigned char mouse_read();
/// @brief The mouse handler. /// @brief The mouse handler.
void mouse_isr(register_t *r); void mouse_isr(register_t *r);
+60 -60
View File
@@ -1,60 +1,60 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file elf.h /// @file elf.h
/// @brief Function for multiboot support. /// @brief Function for multiboot support.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
#include "multiboot.h" #include "multiboot.h"
// Used to get the symbol type. // Used to get the symbol type.
#define ELF32_ST_TYPE(i) ((i)&0xf) #define ELF32_ST_TYPE(i) ((i)&0xf)
// List of symbol types. // List of symbol types.
#define ELF32_TYPE_FUNCTION (0x02) #define ELF32_TYPE_FUNCTION (0x02)
/// @brief A section header with all kinds of useful information. /// @brief A section header with all kinds of useful information.
typedef struct elf_section_header typedef struct elf_section_header
{ {
uint32_t name_offset_in_shstrtab; uint32_t name_offset_in_shstrtab;
uint32_t type; uint32_t type;
uint32_t flags; uint32_t flags;
uint32_t addr; uint32_t addr;
uint32_t offset; uint32_t offset;
uint32_t size; uint32_t size;
uint32_t link; uint32_t link;
uint32_t info; uint32_t info;
uint32_t addralign; uint32_t addralign;
uint32_t entsize; uint32_t entsize;
} __attribute__((packed)) elf_section_header_t; } __attribute__((packed)) elf_section_header_t;
/// @brief A symbol itself. /// @brief A symbol itself.
typedef struct elf_symbol typedef struct elf_symbol
{ {
uint32_t name_offset_in_strtab; uint32_t name_offset_in_strtab;
uint32_t value; uint32_t value;
uint32_t size; uint32_t size;
uint8_t info; uint8_t info;
uint8_t other; uint8_t other;
uint16_t shndx; uint16_t shndx;
} __attribute__((packed)) elf_symbol_t; } __attribute__((packed)) elf_symbol_t;
// Will hold the array of symbols and their names for us. // Will hold the array of symbols and their names for us.
typedef struct elf_symbols typedef struct elf_symbols
{ {
elf_symbol_t *symtab; elf_symbol_t *symtab;
uint32_t symtab_size; uint32_t symtab_size;
const char *strtab; const char *strtab;
uint32_t strtab_size; uint32_t strtab_size;
} elf_symbols_t; } elf_symbols_t;
/// @brief Builds as the set of elf symbols from a multiboot scructure. /// @brief Builds as the set of elf symbols from a multiboot scructure.
void build_elf_symbols_from_multiboot (multiboot_info_t* mb); void build_elf_symbols_from_multiboot (multiboot_info_t* mb);
/* Locate a symbol (only functions) in the following elf symbols /* Locate a symbol (only functions) in the following elf symbols
* Note that, for now, we'll only use this for the kernel (no other elf things..) * Note that, for now, we'll only use this for the kernel (no other elf things..)
*/ */
const char *elf_lookup_symbol (uint32_t addr, elf_symbols_t *elf); const char *elf_lookup_symbol (uint32_t addr, elf_symbols_t *elf);
@@ -0,0 +1,38 @@
/**
* @author Mirco De Marchi
* @date 2/02/2021
* @brief Header file for deadlock prevention algorithms.
* @copyright (c) University of Verona
*/
#pragma once
#include "stdio.h"
#include "stdlib.h"
#include "stdio.h"
#include "stdbool.h"
#include "string.h"
/// @brief Resource allocation request status enumeration.
typedef enum {
SAFE, ///< State safe.
WAIT, ///< State waiting.
WAIT_UNSAFE, ///< State waiting for unsafe detection.
ERROR, ///< State error.
} deadlock_status_t;
/// @brief Request of resources perfomed by a task.
/// @param req_vec Array pointer of resource request for each task in the
/// system.
/// @param task_i Index of task that perform the request to use as array index.
/// @param arr_available Array of resources instances currently available.
/// @param mat_alloc Matrix of current resources instances allocation of
/// each task.
/// @param mat_need Matrix of current resources instances need of each
/// task. need[i][j] = max[i][j] - alloc[i][j]
/// @param n Number of tasks currently in the system.
/// @param m Number of resource types in the system (length of req_vec).
/// @return Status of the request (see status_t enum).
deadlock_status_t request(uint32_t *req_vec, size_t task_i,
uint32_t *arr_available, uint32_t ** mat_alloc, uint32_t **mat_need,
size_t n, size_t m);
@@ -0,0 +1,11 @@
/**
* @author Mirco De Marchi
* @date 2/02/2021
* @brief Header file for deadlock deterministic simulation.
* @copyright (c) University of Verona
*/
#pragma once
/// @brief Deadlock deterministic simulation start function.
void deadlock_simulation();
+150
View File
@@ -0,0 +1,150 @@
/// MentOS, The Mentoring Operating system project
/// @file arr_math.h
/// @brief Array arithmetic operations source file-
/// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details.
#pragma once
#include "stdio.h"
#include "stdlib.h"
#include "stdio.h"
#include "stdint.h"
#include "stdbool.h"
/// @brief Initialize all memory cells of destination array with a value.
/// @param dst Pointer of destination array.
/// @param value Value to use for array inizialization.
/// @param length Length of destination array.
/// @return The pointer of the destination array.
uint32_t *all(uint32_t *dst, uint32_t value, size_t length);
/// @brief Element wise array subtraction.
/// @param left Pointer of left operator and destination array.
/// @param right Pointer of right operator array.
/// @param length Length of arrays.
/// @return The pointer of the destination array.
/// E.g. [4, 5, 6] - [1, 2, 3] = [3, 3, 3]
uint32_t *arr_sub(uint32_t *left, const uint32_t *right, size_t length);
/// @brief Element wise array addition.
/// @param left Pointer of left operator and destination array.
/// @param right Pointer of right operator array.
/// @param length Length of arrays.
/// @return The pointer of the destination array.
/// E.g. [4, 5, 6] + [1, 2, 3] = [5, 7, 9]
uint32_t *arr_add(uint32_t *left, const uint32_t *right, size_t length);
/// @brief Check if at least one element of an array is greater than another
/// array in relation to the respective index.
/// @param left Pointer of left operator array.
/// @param right Pointer of right operator array.
/// @param length Length of arrays.
/// @return True if there is an element of the left array greater than the
/// respective right one, otherwise false.
/// E.g. [1, 1, 6] g_any [1, 2, 3] = true
/// [1, 1, 3] g_any [1, 2, 3] = false
bool_t arr_g_any(const uint32_t *left, const uint32_t *right, size_t length);
/// @brief Check if at least one element of an array is greater or equal than
/// another array in relation to the respective index.
/// @param left Pointer of left operator array.
/// @param right Pointer of right operator array.
/// @param length Length of arrays.
/// @return True if there is an element of the left array greater or equal than
/// the respective right one, otherwise false.
/// E.g. [1, 1, 6] ge_any [1, 2, 3] = true
/// [0, 1, 3] ge_any [1, 2, 3] = true
/// [0, 1, 2] ge_any [1, 2, 3] = false
bool_t arr_ge_any(const uint32_t *left, const uint32_t *right, size_t length);
/// @brief Check if at least one element of an array is less than another
/// array in relation to the respective index.
/// @param left Pointer of left operator array.
/// @param right Pointer of right operator array.
/// @param length Length of arrays.
/// @return True if there is an element of the left array less than the
/// respective right one, otherwise false.
/// E.g. [1, 2, 3] l_any [1, 1, 6] = true
/// [1, 2, 3] l_any [0, 1, 3] = false
bool_t arr_l_any(const uint32_t *left, const uint32_t *right, size_t length);
/// @brief Check if at least one element of an array is less or equal than
/// another array in relation to the respective index.
/// @param left Pointer of left operator array.
/// @param right Pointer of right operator array.
/// @param length Length of arrays.
/// @return True if there is an element of the left array less or equal than
/// the respective right one, otherwise false.
/// E.g. [1, 2, 3] le_any [1, 1, 6] = true
/// [1, 2, 3] le_any [0, 1, 3] = true
/// [1, 2, 3] le_any [0, 1, 2] = false
bool_t arr_le_any(const uint32_t *left, const uint32_t *right, size_t length);
/// @brief Check if each element of an array is greater than another array in
/// relation to the respective index.
/// @param left Pointer of left operator array.
/// @param right Pointer of right operator array.
/// @param length Length of arrays.
/// @return True if all elements of the left array are greater than the
/// respective right one, otherwise false.
/// E.g. [2, 3, 4] g_all [1, 2, 3] = true
/// [2, 3, 3] g_all [1, 2, 3] = false
bool_t arr_g(const uint32_t *left, const uint32_t *right, size_t length);
/// @brief Check if each element of an array is greater or equal than another
/// array in relation to the respective index.
/// @param left Pointer of left operator array.
/// @param right Pointer of right operator array.
/// @param length Length of arrays.
/// @return True if all elements of the left array are greater or equal than the
/// respective right one, otherwise false.
/// E.g. [2, 3, 4] ge_all [1, 2, 3] = true
/// [2, 3, 3] ge_all [1, 2, 3] = true
/// [2, 3, 3] ge_all [1, 2, 4] = false
bool_t arr_ge(const uint32_t *left, const uint32_t *right, size_t length);
/// @brief Check if each element of an array is less than another array in
/// relation to the respective index.
/// @param left Pointer of left operator array.
/// @param right Pointer of right operator array.
/// @param length Length of arrays.
/// @return True if all elements of the left array are less than the
/// respective right one, otherwise false.
/// E.g. [1, 2, 3] l_all [2, 3, 4] = true
/// [1, 2, 3] l_all [2, 3, 3] = false
bool_t arr_l(const uint32_t *left, const uint32_t *right, size_t length);
/// @brief Check if each element of an array is less or equal than another
/// array in relation to the respective index.
/// @param left Pointer of left operator array.
/// @param right Pointer of right operator array.
/// @param length Length of arrays.
/// @return True if all elements of the left array are less or equal than the
/// respective right one, otherwise false.
/// E.g. [1, 2, 3] le_all [2, 3, 4] = true
/// [1, 2, 3] le_all [2, 3, 3] = true
/// [1, 2, 4] le_all [2, 3, 3] = false
bool_t arr_le(const uint32_t *left, const uint32_t *right, size_t length);
/// @brief Check if each element of an array is equal than another array in
/// relation to the respective index.
/// @param left Pointer of left operator array.
/// @param right Pointer of right operator array.
/// @param length Length of arrays.
/// @return True if all elements of the left array are equal than the respective
/// right one, otherwise false.
/// E.g. [1, 2, 3] e_all [1, 2, 3] = true
/// [1, 2, 3] e_all [1, 2, 1] = false
bool_t arr_e(const uint32_t *left, const uint32_t *right, size_t length);
/// @brief Check if at least one element of an array is not equal than another
/// array in relation to the respective index.
/// @param left Pointer of left operator array.
/// @param right Pointer of right operator array.
/// @param length Length of arrays.
/// @return True if there is an element of the left array not equal than the
/// respective right one, otherwise false.
/// E.g. [1, 2, 3] e_all [1, 2, 1] = true
/// [1, 2, 3] e_all [1, 2, 3] = false
bool_t arr_ne(const uint32_t *left, const uint32_t *right, size_t length);
+101
View File
@@ -0,0 +1,101 @@
/// MentOS, The Mentoring Operating system project
/// @file resource.h
/// @brief Resource definition header code.
/// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details.
#pragma once
#include "process.h"
#include "stdint.h"
#include "types.h"
#include "list_head.h"
/// @brief Resource descriptor.
typedef struct resource {
/// Resource index. The resources indexes has to be continuous: 0, 1, ... M.
size_t rid;
/// List head for tasks that share this resource.
list_head resources_list;
/// Number of instances of this resource. For now, always 1.
size_t n_instances;
/// The category of the resource (added for debug purpose).
const char *category;
/// If the resource has been assigned, it points to the task assigned,
/// otherwise NULL.
task_struct *assigned_task;
/// Number of instances assigned to assigned task.
size_t assigned_instances;
} resource_t;
/// @brief Structure that maintains information about resources currently
/// allocated in the system.
typedef struct resource_list {
/// Number of queued resources.
size_t num_active;
/// Head of resources.
list_head head;
} resource_list_t;
/// @brief Resource creation.
/// @param category Resource category string, used to group resources.
/// @return The pointer to the resource created.
resource_t *resource_create(const char *category);
/// @brief Resource initialization.
/// @param r Pointer to a resource created.
void resource_init(resource_t *r);
/// @brief Resource destruction.
/// @param r Pointer to a resource created.
void resource_destroy(resource_t *r);
/// @brief Assign the ownership of a resource to the current calling task.
/// @param r Pointer to a resource created.
void resource_assign(resource_t *r);
/// @brief Remove the ownership of a resource from the current calling task.
/// @param r Pointer to a resource created.
void resource_deassign(resource_t *r);
/// @brief Initialize deadlock prevention structures.
/// @param available Array of resources instances currently available;
/// @param max Matrix of the maximum resources instances that each
/// task may require;
/// @param alloc Matrix of current resources instances allocation of
/// each task.
/// @param need Matrix of current resources instances need of each task.
/// @param idx_map_task_struct Pointer to the array of index and tasks mapping.
void init_deadlock_structures(uint32_t *available, uint32_t **max,
uint32_t **alloc, uint32_t **need,
task_struct *idx_map_task_struct[]);
/// @brief Reset to zero deadlock prevention structures.
/// @param available Array of resources instances currently available;
/// @param max Matrix of the maximum resources instances that each
/// task may require;
/// @param alloc Matrix of current resources instances allocation of
/// each task.
/// @param idx_map_task_struct Pointer to the array of index and tasks mapping.
/// There is no need to reset the need matrix because it has to be calculated
/// starting from max matrix, which is clean.
void reset_deadlock_structures(uint32_t *available, uint32_t **max,
uint32_t **alloc, task_struct *idx_map_task_struct[]);
/// @brief Get the number of total resources allocated in the system.
/// @return The number of resources.
size_t kernel_get_active_resources();
/// @brief Return the index of the current task contained in the array of index
/// and processes mapping.
/// @param idx_map_task_struct Pointer to the array of index and tasks mapping.
/// @return The index that maps with the current task in the
/// idx_map_task_struct array, or -1 if not found the mapping task.
int32_t get_current_task_idx_from(task_struct *idx_map_task_struct[]);
@@ -0,0 +1,37 @@
/// MentOS, The Mentoring Operating system project
/// @file smart_sem_kernel.h
/// @brief Smart semaphore semaphore kernel-side implementation header code.
/// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details.
/// N.B. Header to use only in kernel space.
#pragma once
#include "stdatomic.h"
/// @brief Smart semaphore creation.
/// @return The semaphore id or -1 if creation failed.
int sys_sem_create();
/// @brief Destruction of a created smart semaphore.
/// @param id Smart semaphore ID.
/// @return Return -1 if destroy failed, otherwise 0.
int sys_sem_destroy(int id);
/// @brief Initialization of a created smart semaphore.
/// @param id Smart semaphore ID.
/// @return Return -1 if initialization failed, otherwise 0.
int sys_sem_init(int id);
/// @brief Tries a safety acquisition of a smart semaphore identified by
/// an ID and, if available, takes the ownership.
/// @param id Smart semaphore ID.
/// @return Return -1 if creation failed, return 0 if semaphore busy or
/// the acquisition is unsafe, otherwise return 1 if semaphore has been
/// acquired.
int sys_sem_try_acquire(int id);
/// @brief Release the ownership of a smart semaphore.
/// @param id Smart semaphore ID.
/// @return Return -1 if release failed, otherwise 0.
int sys_sem_release(int id);
+35
View File
@@ -0,0 +1,35 @@
/// MentOS, The Mentoring Operating system project
/// @file smart_sem_user.h
/// @brief Semaphore user-side implementation header code.
/// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details.
/// N.B. Header to use only in user space.
#pragma once
/// @brief Semaphore creation.
/// @return The semaphore id or -1 if creation failed.
/// Set the errno code if failed.
int sem_create();
/// @brief Destruction of a created semaphore.
/// @param id Semaphore ID.
/// @return Return -1 and set errno if destroy failed, otherwise 0.
int sem_destroy(int id);
/// @brief Initialization of a created semaphore.
/// @param id Semaphore ID.
/// @return Return -1 and set errno if initialization failed, otherwise 0.
int sem_init(int id);
/// @brief Acquire the semaphore ownership if available, otherwise waits that
/// becomes available.
/// @param id Semaphore ID.
/// @return Return -1 and set errno if creation failed, otherwise 0 if
/// semaphore has been successfully acquired.
int sem_acquire(int id);
/// @brief Release the ownership of a Semaphore.
/// @param id Semaphore ID.
/// @return Return -1 and set errno if release failed, otherwise 0.
int sem_release(int id);
+26 -42
View File
@@ -1,42 +1,26 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file fcntl.h /// @file fcntl.h
/// @brief Headers of functions fcntl() and open(). /// @brief Headers of functions fcntl() and open().
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stddef.h" #include "stddef.h"
/// Open for reading only. /// Open for reading only.
#define O_RDONLY 0x00 #define O_RDONLY 0x00
/// Open for writing only.
/// Open for writing only. #define O_WRONLY 0x01
#define O_WRONLY 0x01 /// Open for reading and writing.
#define O_RDWR 0x02
/// Open for reading and writing. /// If the file exists, this flag has no effect. Otherwise, the file is created.
#define O_RDWR 0x02 #define O_CREAT 0x40
/// The file offset will be set to the end of the file prior to each write.
/// If the file exists, this flag has no effect. Otherwise, the file is created. #define O_APPEND 0x400
#define O_CREAT 0x40
/// @brief Deletes the file whose name is specified in filename.
/// The file offset will be set to the end of the file prior to each write. /// @param pathname A path to a file.
#define O_APPEND 0x400 /// @return On success, zero is returned. On error, -1 is returned,
/// and errno is set appropriately.
/// @brief Given a pathname for a file, open() returns a file int remove(const char *pathname);
/// descriptor, a small, nonnegative integer for use in
/// subsequent system calls.
/// @param pathname A pathname for a file.
/// @param flags Used to set the file status flags and file access modes
/// of the open file description.
/// @param mode Specifies the file mode bits be applied when a new file
/// is created.
/// @return Returns a file descriptor, a small, nonnegative integer
/// for use in subsequent system calls.
int sys_open(const char *pathname, int flags, mode_t mode);
/// @brief Deletes the file whose name is specified in filename.
/// @param pathname A path to a file.
/// @return On success, zero is returned. On error, -1 is returned,
/// and errno is set appropriately.
int remove(const char *pathname);
+131 -131
View File
@@ -1,131 +1,131 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file initrd.h /// @file initrd.h
/// @brief Headers of functions for initrd filesystem. /// @brief Headers of functions for initrd filesystem.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stat.h" #include "stat.h"
#include "dirent.h" #include "dirent.h"
#include "unistd.h" #include "unistd.h"
#include "stdint.h" #include "stdint.h"
#include "kernel.h" #include "kernel.h"
/// The maximum number of files. /// The maximum number of files.
#define MAX_FILES 32 #define MAX_FILES 32
/// The maximum number of file descriptors. /// The maximum number of file descriptors.
#define MAX_INITRD_DESCRIPTORS MAX_OPEN_FD #define MAX_INITRD_DESCRIPTORS MAX_OPEN_FD
/// @brief Contains the number of files inside the initrd filesystem. /// @brief Contains the number of files inside the initrd filesystem.
typedef struct initrd_t { typedef struct initrd_t {
/// Number of files. /// Number of files.
uint32_t nfiles; uint32_t nfiles;
} initrd_t; } initrd_t;
/// @brief Information concerning a file. /// @brief Information concerning a file.
typedef struct initrd_file_t { typedef struct initrd_file_t {
/// Number used as delimiter, it must be set to 0xBF. /// Number used as delimiter, it must be set to 0xBF.
int magic; int magic;
/// The name of the file. /// The name of the file.
char fileName[MAX_FILENAME_LENGTH]; char fileName[NAME_MAX];
/// The type of the file. /// The type of the file.
short int file_type; short int file_type;
/// The uid of the owner. /// The uid of the owner.
int uid; int uid;
/// Offset of the starting address. /// Offset of the starting address.
unsigned int offset; unsigned int offset;
/// Dimension of the file. /// Dimension of the file.
unsigned int length; unsigned int length;
} initrd_file_t; } initrd_file_t;
/// @brief Descriptor linked to open files. /// @brief Descriptor linked to open files.
typedef struct initrd_fd { typedef struct initrd_fd {
/// Id of the open file inside the file system. More precisely, its index /// Id of the open file inside the file system. More precisely, its index
/// inside the vector of files. /// inside the vector of files.
int file_descriptor; int file_descriptor;
/// The current position inside the file. Used for writing/reading /// The current position inside the file. Used for writing/reading
/// opeations. /// opeations.
int cur_pos; int cur_pos;
} initrd_fd; } initrd_fd;
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
extern initrd_t *fs_specs; extern initrd_t *fs_specs;
/// @brief File system headers. /// @brief File system headers.
extern initrd_file_t *fs_headers; extern initrd_file_t *fs_headers;
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
extern unsigned int fs_end; extern unsigned int fs_end;
/// Initializes the initrd file system. /// Initializes the initrd file system.
uint32_t initfs_init(); uint32_t initfs_init();
/// @brief Opens a directory at the given path. /// @brief Opens a directory at the given path.
/// @param path The path where the directory resides. /// @param path The path where the directory resides.
/// @return Structure used to access the directory. /// @return Structure used to access the directory.
DIR *initfs_opendir(const char *path); DIR *initfs_opendir(const char *path);
/// @brief Closes the directory stream associated with dirp. /// @brief Closes the directory stream associated with dirp.
/// @param dirp The directory handler. /// @param dirp The directory handler.
/// @return 0 on success. On error, -1 is returned, and errno is set. /// @return 0 on success. On error, -1 is returned, and errno is set.
int initfs_closedir(DIR *dirp); int initfs_closedir(DIR *dirp);
/// @brief Moves the position of the currently readed entry inside the /// @brief Moves the position of the currently readed entry inside the
/// directory. /// directory.
/// @param dirp The directory handler. /// @param dirp The directory handler.
/// @return A pointer to the next entry inside the directory. /// @return A pointer to the next entry inside the directory.
dirent_t *initrd_readdir(DIR *dirp); dirent_t *initrd_readdir(DIR *dirp);
/// @brief Creates a new directory. /// @brief Creates a new directory.
/// @param path The path to the new directory. /// @param path The path to the new directory.
/// @param mode The file mode. /// @param mode The file mode.
/// @return 0 if success. /// @return 0 if success.
int initrd_mkdir(const char *path, mode_t mode); int initrd_mkdir(const char *path, mode_t mode);
/// @brief Removes a directory. /// @brief Removes a directory.
/// @param path The path to the directory. /// @param path The path to the directory.
/// @return 0 if success. /// @return 0 if success.
int initrd_rmdir(const char *path); int initrd_rmdir(const char *path);
/// @brief Open the file at the given path and returns its file descriptor. /// @brief Open the file at the given path and returns its file descriptor.
/// @param path The path to the file. /// @param path The path to the file.
/// @param flags The flags used to determine the behavior of the function. /// @param flags The flags used to determine the behavior of the function.
/// @return The file descriptor of the opened file, otherwise returns -1. /// @return The file descriptor of the opened file, otherwise returns -1.
int initfs_open(const char *path, int flags, ...); int initfs_open(const char *path, int flags, ...);
/// @brief Deletes the file at the given path. /// @brief Deletes the file at the given path.
/// @param path The path to the file. /// @param path The path to the file.
/// @return On success, zero is returned. On error, -1 is returned. /// @return On success, zero is returned. On error, -1 is returned.
int initfs_remove(const char *path); int initfs_remove(const char *path);
/// @brief Reads from the file identified by the file descriptor. /// @brief Reads from the file identified by the file descriptor.
/// @param fildes The file descriptor of the file. /// @param fildes The file descriptor of the file.
/// @param buf Buffer where the read content must be placed. /// @param buf Buffer where the read content must be placed.
/// @param nbyte The number of bytes to read. /// @param nbyte The number of bytes to read.
/// @return T The number of red bytes. /// @return T The number of red bytes.
ssize_t initfs_read(int fildes, char *buf, size_t nbyte); ssize_t initfs_read(int fildes, char *buf, size_t nbyte);
/// @brief Retrieves information concerning the file at the given position. /// @brief Retrieves information concerning the file at the given position.
/// @param path The path where the file resides. /// @param path The path where the file resides.
/// @param stat The structure where the information are stored. /// @param stat The structure where the information are stored.
/// @return 0 if success. /// @return 0 if success.
int initrd_stat(const char *path, stat_t *stat); int initrd_stat(const char *path, stat_t *stat);
/// @brief Writes the given content inside the file. /// @brief Writes the given content inside the file.
/// @param fildes The file descriptor of the file. /// @param fildes The file descriptor of the file.
/// @param buf The content to write. /// @param buf The content to write.
/// @param nbyte The number of bytes to write. /// @param nbyte The number of bytes to write.
/// @return T The number of written bytes. /// @return T The number of written bytes.
ssize_t initrd_write(int fildes, const void *buf, size_t nbyte); ssize_t initrd_write(int fildes, const void *buf, size_t nbyte);
/// @brief Closes the given file. /// @brief Closes the given file.
/// @param fildes The file descriptor of the file. /// @param fildes The file descriptor of the file.
int initrd_close(int fildes); int initrd_close(int fildes);
// TODO: doxygen comment. // TODO: doxygen comment.
size_t initrd_nfiles(); size_t initrd_nfiles();
// TODO: doxygen comment. // TODO: doxygen comment.
void dump_initrd_fs(); void dump_initrd_fs();
-23
View File
@@ -1,23 +0,0 @@
/// MentOS, The Mentoring Operating system project
/// @file read_write.c
/// @brief Read and write functions.
/// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details.
#pragma once
#include "stddef.h"
/// @brief Read data from a file descriptor.
/// @param fd The file descriptor.
/// @param buf The buffer.
/// @param nbytes The number of bytes to read.
/// @return The number of read characters.
ssize_t sys_read(int fd, void *buf, size_t nbytes);
/// @brief Write data into a file descriptor.
/// @param fd The file descriptor.
/// @param buf The buffer collecting data to written.
/// @param nbytes The number of bytes to write.
/// @return The number of written bytes.
ssize_t sys_write(int fd, void *buf, size_t nbytes);
+52 -52
View File
@@ -1,52 +1,52 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file vfs.h /// @file vfs.h
/// @brief Headers for Virtual File System (VFS). /// @brief Headers for Virtual File System (VFS).
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "unistd.h" #include "unistd.h"
#include "vfs_types.h" #include "vfs_types.h"
/// The maximum number of mount points. /// The maximum number of mount points.
#define MAX_MOUNTPOINT 10 #define MAX_MOUNTPOINT 10
/// The currently opened file descriptor. /// The currently opened file descriptor.
extern int current_fd; extern int current_fd;
/// The list of file descriptors. /// The list of file descriptors.
extern file_descriptor_t fd_list[MAX_OPEN_FD]; extern file_descriptor_t fd_list[MAX_OPEN_FD];
/// The list of mount points. /// The list of mount points.
extern mountpoint_t mountpoint_list[MAX_MOUNTPOINT]; extern mountpoint_t mountpoint_list[MAX_MOUNTPOINT];
/// @brief Initialize the Virtual File System (VFS). /// @brief Initialize the Virtual File System (VFS).
void vfs_init(); void vfs_init();
/// @brief Retrieves the id of the mount point where the path resides. /// @brief Retrieves the id of the mount point where the path resides.
/// @param path The path to the mountpoint. /// @param path The path to the mountpoint.
/// @return The id of the mountpoint. /// @return The id of the mountpoint.
int32_t get_mountpoint_id(const char *path); int32_t get_mountpoint_id(const char *path);
// TODO: doxigen comment. // TODO: doxigen comment.
mountpoint_t * get_mountpoint(const char *path); mountpoint_t * get_mountpoint(const char *path);
// TODO: doxigen comment. // TODO: doxigen comment.
mountpoint_t * get_mountpoint_from_id(int32_t mp_id); mountpoint_t * get_mountpoint_from_id(int32_t mp_id);
/// @brief A path is extracted from the relative path, excluding the /// @brief A path is extracted from the relative path, excluding the
/// mountpoint. /// mountpoint.
/// @param mp_id Id of the mountpoint point of the file. /// @param mp_id Id of the mountpoint point of the file.
/// @param path Path to the file to be opened. /// @param path Path to the file to be opened.
/// @return Path without the mountpoint part. /// @return Path without the mountpoint part.
int get_relative_path(uint32_t mp_id, char *path); int get_relative_path(uint32_t mp_id, char *path);
/// @brief Given a path, it extracts its absolute path (starting from /// @brief Given a path, it extracts its absolute path (starting from
/// the current one). /// the current one).
/// @param path Path to the file to be opened. /// @param path Path to the file to be opened.
/// @return Error code. /// @return Error code.
int get_absolute_path(char *path); int get_absolute_path(char *path);
/// @brief Dumps the list of file descriptors. /// @brief Dumps the list of file descriptors.
void vfs_dump(); void vfs_dump();
+136 -137
View File
@@ -1,137 +1,136 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file vfs_types.h /// @file vfs_types.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stat.h" #include "stat.h"
#include "kernel.h" #include "kernel.h"
#include "dirent.h" #include "dirent.h"
/// Identifies a file. #define PATH_SEPARATOR '/'
#define FS_FILE 0x01 #define PATH_SEPARATOR_STRING "/"
#define PATH_UP ".."
/// Identifies a directory. #define PATH_DOT "."
#define FS_DIRECTORY 0x02
/// Identifies a file.
/// Identifies a character devies. #define FS_FILE 0x01U
#define FS_CHARDEVICE 0x04 /// Identifies a directory.
#define FS_DIRECTORY 0x02U
/// Identifies a block devies. /// Identifies a character devies.
#define FS_BLOCKDEVICE 0x08 #define FS_CHARDEVICE 0x04U
/// Identifies a block devies.
/// Identifies a pipe. #define FS_BLOCKDEVICE 0x08U
#define FS_PIPE 0x10 /// Identifies a pipe.
#define FS_PIPE 0x10U
/// Identifies a symbolic link. /// Identifies a symbolic link.
#define FS_SYMLINK 0x20 #define FS_SYMLINK 0x20U
/// Identifies a mount-point.
/// Identifies a mount-point. #define FS_MOUNTPOINT 0x40U
#define FS_MOUNTPOINT 0x40
/// Function used to open a directory.
/// Function used to open a directory. typedef DIR *(*opendir_callback)(const char *);
typedef DIR *(*opendir_callback)(const char *);
/// Function used to close a directory.
/// Function used to close a directory. typedef int (*closedir_callback)(DIR *);
typedef int (*closedir_callback)(DIR *);
/// Function used to create a directory.
/// Function used to create a directory. typedef int (*mkdir_callback)(const char *, mode_t);
typedef int (*mkdir_callback)(const char *, mode_t);
/// Function used to remove a directory.
/// Function used to remove a directory. typedef int (*rmdir_callback)(const char *);
typedef int (*rmdir_callback)(const char *);
/// Function used to read the next entry of a directory.
/// Function used to read the next entry of a directory. typedef dirent_t *(*readdir_callback)(DIR *);
typedef dirent_t *(*readdir_callback)(DIR *);
/// Function used to open a file.
/// Function used to open a file. typedef int (*open_callback)(const char *, int, ...);
typedef int (*open_callback)(const char *, int, ...);
/// Function used to remove a file.
/// Function used to remove a file. typedef int (*remove_callback)(const char *);
typedef int (*remove_callback)(const char *);
/// Function used to close a file.
/// Function used to close a file. typedef int (*close_callback)(int);
typedef int (*close_callback)(int);
/// Function used to read from a file.
/// Function used to read from a file. typedef ssize_t (*read_callback)(int, char *, size_t);
typedef ssize_t (*read_callback)(int, char *, size_t);
/// Function used to write inside a file.
/// Function used to write inside a file. typedef ssize_t (*write_callback)(int, const void *, size_t);
typedef ssize_t (*write_callback)(int, const void *, size_t);
/// Function used to stat fs entries.
/// Function used to stat fs entries. typedef int (*stat_callback)(const char *, stat_t *);
typedef int (*stat_callback)(const char *, stat_t *);
/// @brief Set of functions used to perform operations on directories.
/// @brief Set of functions used to perform operations on directories. typedef struct directory_operations_t {
typedef struct directory_operations_t { /// Identifies a mount-point.
/// Identifies a mount-point. opendir_callback opendir_f;
opendir_callback opendir_f; /// Closes a directory.
/// Closes a directory. closedir_callback closedir_f;
closedir_callback closedir_f; /// Creates a directory.
/// Creates a directory. mkdir_callback mkdir_f;
mkdir_callback mkdir_f; /// Removes a directory.
/// Removes a directory. rmdir_callback rmdir_f;
rmdir_callback rmdir_f; /// Read next entry inside the directory.
/// Read next entry inside the directory. readdir_callback readdir_f;
readdir_callback readdir_f; } directory_operations_t;
} directory_operations_t;
/// @brief Set of functions used to perform operations on files.
/// @brief Set of functions used to perform operations on files. typedef struct super_node_operations_t {
typedef struct super_node_operations_t { /// Open a file.
/// Open a file. open_callback open_f;
open_callback open_f; /// Remove a file.
/// Remove a file. remove_callback remove_f;
remove_callback remove_f; /// Close a file.
/// Close a file. close_callback close_f;
close_callback close_f; /// Read from a file.
/// Read from a file. read_callback read_f;
read_callback read_f; /// Write inside a file.
/// Write inside a file. write_callback write_f;
write_callback write_f; } super_node_operations_t;
} super_node_operations_t;
/// @brief Stat operations.
/// @brief Stat operations. typedef struct stat_operations_t {
typedef struct stat_operations_t { /// Stat function.
/// Stat function. stat_callback stat_f;
stat_callback stat_f; } stat_operations_t;
} stat_operations_t;
/// @brief Data structure that contains information about the mounted filesystems.
/// @brief Data structure that contains information about the mounted filesystems. typedef struct mountpoint_t {
typedef struct mountpoint_t { /// The id of the mountpoint.
/// The id of the mountpoint. int32_t mp_id;
int32_t mp_id; /// Name of the mountpoint.
/// Name of the mountpoint. char mountpoint[NAME_MAX];
char mountpoint[MAX_FILENAME_LENGTH]; /// Maschera dei permessi.
/// Maschera dei permessi. unsigned int pmask;
unsigned int pmask; /// User ID.
/// User ID. unsigned int uid;
unsigned int uid; /// Group ID.
/// Group ID. unsigned int gid;
unsigned int gid; /// Starting address of the FileSystem.
/// Starting address of the FileSystem. unsigned int start_address;
unsigned int start_address; /// Ending address of the FileSystem.
/// Ending address of the FileSystem. unsigned int end_address;
unsigned int end_address; /// Device ID.
/// Device ID. int dev_id;
int dev_id; /// Operations on files.
/// Operations on files. super_node_operations_t operations;
super_node_operations_t operations; /// Operations on directories.
/// Operations on directories. directory_operations_t dir_op;
directory_operations_t dir_op; /// Stat operations.
/// Stat operations. stat_operations_t stat_op;
stat_operations_t stat_op; } mountpoint_t;
} mountpoint_t;
/// @brief Data structure containing information about an open file.
/// @brief Data structure containing information about an open file. typedef struct file_descriptor_t {
typedef struct file_descriptor_t { /// The descriptor of the internal file of the FileSystem.
/// The descriptor of the internal file of the FileSystem. int fs_spec_id;
int fs_spec_id; /// The id of the mountpoint where the.
/// The id of the mountpoint where the. int mountpoint_id;
int mountpoint_id; /// Offset for file reading, for the next read.
/// Offset for file reading, for the next read. int offset;
int offset; /// Flags for file opening modes.
/// Flags for file opening modes. int flags_mask;
int flags_mask; } file_descriptor_t;
} file_descriptor_t;
+86 -86
View File
@@ -1,86 +1,86 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file cpuid.h /// @file cpuid.h
/// @brief CPUID definitions. /// @brief CPUID definitions.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stddef.h" #include "stddef.h"
#include "stdint.h" #include "stdint.h"
#include "kernel.h" #include "kernel.h"
/// Dimension of the exc flags. /// Dimension of the exc flags.
#define ECX_FLAGS_SIZE 24 #define ECX_FLAGS_SIZE 24
/// Dimension of the edx flags. /// Dimension of the edx flags.
#define EDX_FLAGS_SIZE 32 #define EDX_FLAGS_SIZE 32
/// @brief Contains the information concerning the CPU. /// @brief Contains the information concerning the CPU.
typedef struct cpuinfo_t { typedef struct cpuinfo_t {
/// The name of the vendor. /// The name of the vendor.
char cpu_vendor[13]; char cpu_vendor[13];
/// The type of the CPU. /// The type of the CPU.
char *cpu_type; char *cpu_type;
/// The family of the CPU. /// The family of the CPU.
uint32_t cpu_family; uint32_t cpu_family;
/// The model of the CPU. /// The model of the CPU.
uint32_t cpu_model; uint32_t cpu_model;
/// Identifier for individual cores when the CPU is interrogated by the /// Identifier for individual cores when the CPU is interrogated by the
/// CPUID instruction. /// CPUID instruction.
uint32_t apic_id; uint32_t apic_id;
/// Ecx flags. /// Ecx flags.
uint32_t cpuid_ecx_flags[ECX_FLAGS_SIZE]; uint32_t cpuid_ecx_flags[ECX_FLAGS_SIZE];
/// Edx flags. /// Edx flags.
uint32_t cpuid_edx_flags[EDX_FLAGS_SIZE]; uint32_t cpuid_edx_flags[EDX_FLAGS_SIZE];
// TODO: doxygen comment. // TODO: doxygen comment.
int is_brand_string; int is_brand_string;
// TODO: doxygen comment. // TODO: doxygen comment.
char *brand_string; char *brand_string;
} cpuinfo_t; } cpuinfo_t;
/// This will be populated with the information concerning the CPU. /// This will be populated with the information concerning the CPU.
cpuinfo_t sinfo; cpuinfo_t sinfo;
/// @brief Main CPUID procedure. /// @brief Main CPUID procedure.
/// @param cpuinfo Structure to fill with CPUID information. /// @param cpuinfo Structure to fill with CPUID information.
void get_cpuid(cpuinfo_t *cpuinfo); void get_cpuid(cpuinfo_t *cpuinfo);
/// @brief Actual CPUID call. /// @brief Actual CPUID call.
/// @param registers The registers to fill with the result of the call. /// @param registers The registers to fill with the result of the call.
void call_cpuid(register_t *registers); void call_cpuid(register_t *registers);
/// @brief Extract vendor string. /// @brief Extract vendor string.
/// @param cpuinfo The struct containing the CPUID infos. /// @param cpuinfo The struct containing the CPUID infos.
/// @param registers The registers. /// @param registers The registers.
void cpuid_write_vendor(cpuinfo_t *cpuinfo, register_t *registers); void cpuid_write_vendor(cpuinfo_t *cpuinfo, register_t *registers);
// TODO: doxygen documentation. // TODO: doxygen documentation.
/// @brief CPUID is called with EAX=1 /// @brief CPUID is called with EAX=1
/// EAX contains Type, Family, Model and Stepping ID /// EAX contains Type, Family, Model and Stepping ID
/// EBX contains the Brand Index if supported, and the APIC ID /// EBX contains the Brand Index if supported, and the APIC ID
/// ECX/EDX contains feature information /// ECX/EDX contains feature information
/// @param cpuinfo /// @param cpuinfo
/// @param registers /// @param registers
void cpuid_write_proctype(cpuinfo_t *cpuinfo, register_t *registers); void cpuid_write_proctype(cpuinfo_t *cpuinfo, register_t *registers);
/// @brief EAX=1, ECX contains a list of supported features. /// @brief EAX=1, ECX contains a list of supported features.
void cpuid_feature_ecx(cpuinfo_t *, uint32_t); void cpuid_feature_ecx(cpuinfo_t *, uint32_t);
/// @brief EAX=1, EDX contains a list of supported features. /// @brief EAX=1, EDX contains a list of supported features.
void cpuid_feature_edx(cpuinfo_t *, uint32_t); void cpuid_feature_edx(cpuinfo_t *, uint32_t);
// TODO: doxygen documentation. // TODO: doxygen documentation.
/// @brief Extract single byte from a register. /// @brief Extract single byte from a register.
/// @param reg /// @param reg
/// @param position /// @param position
/// @param value /// @param value
/// @return /// @return
uint32_t cpuid_get_byte(const uint32_t reg, const uint32_t position, uint32_t cpuid_get_byte(const uint32_t reg, const uint32_t position,
const uint32_t value); const uint32_t value);
/// @brief Index of brand strings. /// @brief Index of brand strings.
char *cpuid_brand_index(register_t *); char *cpuid_brand_index(register_t *);
/// @brief Brand string is contained in EAX, EBX, ECX and EDX. /// @brief Brand string is contained in EAX, EBX, ECX and EDX.
char *cpuid_brand_string(register_t *); char *cpuid_brand_string(register_t *);
+110 -110
View File
@@ -1,110 +1,110 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file pic8259.h /// @file pic8259.h
/// @brief Pic8259 definitions. /// @brief Pic8259 definitions.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "idt.h" #include "idt.h"
#include "kheap.h" #include "kheap.h"
#include "debug.h" #include "debug.h"
#include "stddef.h" #include "stddef.h"
#include "kernel.h" #include "kernel.h"
#include "bitops.h" #include "bitops.h"
#include "port_io.h" #include "port_io.h"
#include "irqflags.h" #include "irqflags.h"
#include "scheduler.h" #include "scheduler.h"
/// The total number of IRQs. /// The total number of IRQs.
#define IRQ_NUM 16 #define IRQ_NUM 16
/// @defgroup irqs Interrupt Requests (IRQs). /// @defgroup irqs Interrupt Requests (IRQs).
/// @brief This is the list of interrupt requests. /// @brief This is the list of interrupt requests.
/// @{ /// @{
/// @brief System timer. /// @brief System timer.
#define IRQ_TIMER 0 #define IRQ_TIMER 0
/// @brief Keyboard controller. /// @brief Keyboard controller.
#define IRQ_KEYBOARD 1 #define IRQ_KEYBOARD 1
/// @brief cascaded signals from IRQs 815 (any devices configured to use IRQ /// @brief cascaded signals from IRQs 815 (any devices configured to use IRQ
/// 2 will actually be using IRQ 9) /// 2 will actually be using IRQ 9)
#define IRQ_TO_SLAVE_PIC 2 #define IRQ_TO_SLAVE_PIC 2
/// @brief Serial port controller for serial port 2 (and 4). /// @brief Serial port controller for serial port 2 (and 4).
#define IRQ_COM2_4 3 #define IRQ_COM2_4 3
/// @brief Serial port controller for serial port 1 (and 3). /// @brief Serial port controller for serial port 1 (and 3).
#define IRQ_COM1_3 4 #define IRQ_COM1_3 4
/// @brief Parallel port 2 and 3 (or sound card). /// @brief Parallel port 2 and 3 (or sound card).
#define IRQ_LPT2 5 #define IRQ_LPT2 5
/// @brief Floppy disk controller. /// @brief Floppy disk controller.
#define IRQ_FLOPPY 6 #define IRQ_FLOPPY 6
/// @brief Parallel port 1. /// @brief Parallel port 1.
#define IRQ_LPT1 7 #define IRQ_LPT1 7
/// @brief Real-time clock (RTC). /// @brief Real-time clock (RTC).
#define IRQ_REAL_TIME_CLOCK 8 #define IRQ_REAL_TIME_CLOCK 8
/// @brief Advanced Configuration and Power Interface (ACPI) /// @brief Advanced Configuration and Power Interface (ACPI)
/// system control interrupt on Intel chipsets.[1] Other chipset /// system control interrupt on Intel chipsets.[1] Other chipset
/// manufacturers might use another interrupt for this purpose, or /// manufacturers might use another interrupt for this purpose, or
/// make it available for the use of peripherals (any devices configured /// make it available for the use of peripherals (any devices configured
/// to use IRQ 2 will actually be using IRQ 9) /// to use IRQ 2 will actually be using IRQ 9)
#define IRQ_AVAILABLE_1 9 #define IRQ_AVAILABLE_1 9
/// @brief The Interrupt is left open for the use of /// @brief The Interrupt is left open for the use of
/// peripherals (open interrupt/available, SCSI or NIC). /// peripherals (open interrupt/available, SCSI or NIC).
#define IRQ_AVAILABLE_2 10 #define IRQ_AVAILABLE_2 10
/// @brief The Interrupt is left open for the use of /// @brief The Interrupt is left open for the use of
/// peripherals (open interrupt/available, SCSI or NIC). /// peripherals (open interrupt/available, SCSI or NIC).
#define IRQ_AVAILABLE_3 11 #define IRQ_AVAILABLE_3 11
/// @brief Mouse on PS/2 connector. /// @brief Mouse on PS/2 connector.
#define IRQ_MOUSE 12 #define IRQ_MOUSE 12
/// @brief CPU co-processor or integrated floating point unit /// @brief CPU co-processor or integrated floating point unit
/// or inter-processor interrupt (use depends on OS). /// or inter-processor interrupt (use depends on OS).
#define IRQ_MATH_CPU 13 #define IRQ_MATH_CPU 13
/// @brief Primary ATA channel (ATA interface usually serves /// @brief Primary ATA channel (ATA interface usually serves
/// hard disk drives and CD drives). /// hard disk drives and CD drives).
#define IRQ_FIRST_HD 14 #define IRQ_FIRST_HD 14
/// @brief Secondary ATA channel. /// @brief Secondary ATA channel.
#define IRQ_SECOND_HD 15 #define IRQ_SECOND_HD 15
/// @} /// @}
/// @brief Function that initializes the processor pic 8259 that will manage the /// @brief Function that initializes the processor pic 8259 that will manage the
/// interruptions. /// interruptions.
void pic8259_init_irq(); void pic8259_init_irq();
/// @brief This function, enable irqs on the pic. /// @brief This function, enable irqs on the pic.
/// @details This function provide a tool for enabling irq from the pic /// @details This function provide a tool for enabling irq from the pic
/// processor. /// processor.
/// @param irq Number of irq to enable. /// @param irq Number of irq to enable.
/// @return 0 If all OK, -1 on errors. /// @return 0 If all OK, -1 on errors.
int pic8259_irq_enable(uint32_t irq); int pic8259_irq_enable(uint32_t irq);
/// @brief This function, disable irqs on the pic. /// @brief This function, disable irqs on the pic.
/// @details This function provide a tool for enabling irq from the pic /// @details This function provide a tool for enabling irq from the pic
/// processor. /// processor.
/// @param irq Number of irq to enable. /// @param irq Number of irq to enable.
/// @return 0 If all OK, -1 on errors. /// @return 0 If all OK, -1 on errors.
int pic8259_irq_disable(uint32_t irq); int pic8259_irq_disable(uint32_t irq);
/// @brief This is issued to the PIC chips at the end of an IRQ-based /// @brief This is issued to the PIC chips at the end of an IRQ-based
/// interrupt routine. /// interrupt routine.
/// @param irq The interrupt number. /// @param irq The interrupt number.
void pic8259_send_eoi(uint32_t irq); void pic8259_send_eoi(uint32_t irq);
/// @brief This Function return the number of current IRQ Request. /// @brief This Function return the number of current IRQ Request.
/// @return Number of IRQ + 1 currently serving. If 0 there are no IRQ. /// @return Number of IRQ + 1 currently serving. If 0 there are no IRQ.
//int pic8259_irq_get_current(); //int pic8259_irq_get_current();
+85 -85
View File
@@ -1,85 +1,85 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file timer.h /// @file timer.h
/// @brief Programmable Interval Timer (PIT) definitions. /// @brief Programmable Interval Timer (PIT) definitions.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "kernel.h" #include "kernel.h"
#include "stdint.h" #include "stdint.h"
/// @defgroup picregs Programmable Interval Timer Registers /// @defgroup picregs Programmable Interval Timer Registers
/// @brief The list of registers used to set the PIT. /// @brief The list of registers used to set the PIT.
/// @{ /// @{
/// Channel 0 data port (read/write). /// Channel 0 data port (read/write).
#define PIT_DATAREG0 0x40 #define PIT_DATAREG0 0x40
/// Channel 1 data port (read/write). /// Channel 1 data port (read/write).
#define PIT_DATAREG1 0x41 #define PIT_DATAREG1 0x41
/// Channel 2 data port (read/write). /// Channel 2 data port (read/write).
#define PIT_DATAREG2 0x42 #define PIT_DATAREG2 0x42
/// Mode/Command register (write only, a read is ignored). /// Mode/Command register (write only, a read is ignored).
#define PIT_COMREG 0x43 #define PIT_COMREG 0x43
/// @} /// @}
/// @brief Frequency divider value (1.193182 MHz). /// @brief Frequency divider value (1.193182 MHz).
#define PIT_DIVISOR 1193180 #define PIT_DIVISOR 1193180
/// @brief Command used to configure the PIT. /// @brief Command used to configure the PIT.
/// @details /// @details
/// 0x36 = 00110110B. /// 0x36 = 00110110B.
/// Channel | 00 | Select Channel 0. /// Channel | 00 | Select Channel 0.
/// Access mode | 11 | lobyte/hibyte. /// Access mode | 11 | lobyte/hibyte.
/// Operating mode | 011 | Mode 3 (square wave generator). /// Operating mode | 011 | Mode 3 (square wave generator).
/// BCD/Binary mode | 0 | 16-bit binary. /// BCD/Binary mode | 0 | 16-bit binary.
#define PIT_CONFIGURATION 0x36 #define PIT_CONFIGURATION 0x36
#define PIT_MASK 0xFF #define PIT_MASK 0xFF
/// @brief Pointer to a functionality to wake up. /// @brief Pointer to a functionality to wake up.
typedef void (*wakeup_callback_t)(); typedef void (*wakeup_callback_t)();
/// @brief Holds the information about a wake-up functionality. /// @brief Holds the information about a wake-up functionality.
typedef struct wakeup_info { typedef struct wakeup_info {
/// Pointer to the functionality. /// Pointer to the functionality.
wakeup_callback_t func; wakeup_callback_t func;
/// The tick, in the future, when the functionality must be triggered. /// The tick, in the future, when the functionality must be triggered.
__volatile__ uint32_t wakeup_at_jiffy; __volatile__ uint32_t wakeup_at_jiffy;
/// The period in seconds. /// The period in seconds.
uint32_t period; uint32_t period;
} wakeup_info_t; } wakeup_info_t;
/// @brief Handles the timer. /// @brief Handles the timer.
/// @details In this case, it's very simple: We /// @details In this case, it's very simple: We
/// increment the 'timer_ticks' variable every time the /// increment the 'timer_ticks' variable every time the
/// timer fires. By default, the timer fires 18.222 times /// timer fires. By default, the timer fires 18.222 times
/// per second. Why 18.222Hz? Some engineer at IBM must've /// per second. Why 18.222Hz? Some engineer at IBM must've
/// been smoking something funky /// been smoking something funky
void timer_handler(pt_regs *reg); void timer_handler(pt_regs *reg);
/// @brief Sets up the system clock by installing the timer handler into IRQ0. /// @brief Sets up the system clock by installing the timer handler into IRQ0.
void timer_install(); void timer_install();
/// @brief Returns the number of ticks since the system is running. /// @brief Returns the number of ticks since the system is running.
uint64_t timer_get_ticks(); uint64_t timer_get_ticks();
/// @brief Returns the number of ticks since the system is running. /// @brief Returns the number of ticks since the system is running.
uint64_t timer_get_subticks(); uint64_t timer_get_subticks();
/// @brief Registers a function which will be waken up at each tick. /// @brief Registers a function which will be waken up at each tick.
/// @param func The functionality which must be triggered. /// @param func The functionality which must be triggered.
/// @param period The period in second. /// @param period The period in second.
void timer_register_wakeup_call(wakeup_callback_t func, uint32_t period); void timer_register_wakeup_call(wakeup_callback_t func, uint32_t period);
/// @brief Makes the process sleep for the given ammount of time. /// @brief Makes the process sleep for the given ammount of time.
/// @param seconds The ammount of seconds. /// @param seconds The ammount of seconds.
void sleep(unsigned int seconds); void sleep(unsigned int seconds);
/// @brief Allows to set the timer phase to the given frequency. /// @brief Allows to set the timer phase to the given frequency.
/// @param hz The frequency to set. /// @param hz The frequency to set.
void timer_phase(const uint32_t hz); void timer_phase(const uint32_t hz);
+27 -27
View File
@@ -1,27 +1,27 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file mm_io.h /// @file mm_io.h
/// @brief Memory Mapped IO functions. /// @brief Memory Mapped IO functions.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
/// @brief Reads a 8-bit value from the given address. /// @brief Reads a 8-bit value from the given address.
uint8_t in_memb(uint32_t addr); uint8_t in_memb(uint32_t addr);
/// @brief Reads a 16-bit value from the given address. /// @brief Reads a 16-bit value from the given address.
uint16_t in_mems(uint32_t addr); uint16_t in_mems(uint32_t addr);
/// @brief Reads a 32-bit value from the given address. /// @brief Reads a 32-bit value from the given address.
uint32_t in_meml(uint32_t addr); uint32_t in_meml(uint32_t addr);
/// @brief Writes a 8-bit value at the given address. /// @brief Writes a 8-bit value at the given address.
void out_memb(uint32_t addr, uint8_t value); void out_memb(uint32_t addr, uint8_t value);
/// @brief Writes a 16-bit value at the given address. /// @brief Writes a 16-bit value at the given address.
void out_mems(uint32_t addr, uint16_t value); void out_mems(uint32_t addr, uint16_t value);
/// @brief Writes a 32-bit value at the given address. /// @brief Writes a 32-bit value at the given address.
void out_meml(uint32_t addr, uint32_t value); void out_meml(uint32_t addr, uint32_t value);
+43 -43
View File
@@ -1,43 +1,43 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file port_io.h /// @file port_io.h
/// @brief Byte I/O on ports prototypes. /// @brief Byte I/O on ports prototypes.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
/// @brief Used for reading from the I/O ports. /// @brief Used for reading from the I/O ports.
/// @param port The input port. /// @param port The input port.
/// @return The read value. /// @return The read value.
uint8_t inportb(uint16_t port); uint8_t inportb(uint16_t port);
/// @brief Used for reading 2 bytes from the I/O ports. /// @brief Used for reading 2 bytes from the I/O ports.
/// @param port The input port. /// @param port The input port.
/// @return The read value. /// @return The read value.
uint16_t inports(uint16_t port); uint16_t inports(uint16_t port);
void inportsm(uint16_t port, uint8_t *data, unsigned long size); void inportsm(uint16_t port, uint8_t *data, unsigned long size);
/// @brief Used for reading 4 bytes from the I/O ports. /// @brief Used for reading 4 bytes from the I/O ports.
/// @param port The input port. /// @param port The input port.
/// @return The read value. /// @return The read value.
uint32_t inportl(uint16_t port); uint32_t inportl(uint16_t port);
/// @brief Use this to write to I/O ports to send bytes to devices. /// @brief Use this to write to I/O ports to send bytes to devices.
/// @param port The output port. /// @param port The output port.
/// @param data The data to write. /// @param data The data to write.
void outportb(uint16_t port, uint8_t data); void outportb(uint16_t port, uint8_t data);
/// @brief Use this to write to I/O ports to send 2 bytes to devices. /// @brief Use this to write to I/O ports to send 2 bytes to devices.
/// @param port The output port. /// @param port The output port.
/// @param data The data to write. /// @param data The data to write.
void outports(uint16_t port, uint16_t data); void outports(uint16_t port, uint16_t data);
void outportsm(uint16_t port, uint8_t *data, uint16_t size); void outportsm(uint16_t port, uint8_t *data, uint16_t size);
/// @brief Use this to write to I/O ports to send 4 bytes to devices. /// @brief Use this to write to I/O ports to send 4 bytes to devices.
/// @param port The output port. /// @param port The output port.
/// @param data The data to write. /// @param data The data to write.
void outportl(uint16_t port, uint32_t data); void outportl(uint16_t port, uint32_t data);
+132 -132
View File
@@ -1,132 +1,132 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file video.h /// @file video.h
/// @brief Video functions and costants. /// @brief Video functions and costants.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
/// @brief A set of colors. /// @brief A set of colors.
typedef enum video_color_t { typedef enum video_color_t {
///0 : Black ///0 : Black
BLACK, BLACK,
/// 1 : Blue /// 1 : Blue
BLUE, BLUE,
/// 2 : Green /// 2 : Green
GREEN, GREEN,
/// 3 : Cyan /// 3 : Cyan
CYAN, CYAN,
/// 4 : Red /// 4 : Red
RED, RED,
/// 5 : Magenta /// 5 : Magenta
MAGENTA, MAGENTA,
/// 6 : Brown /// 6 : Brown
BROWN, BROWN,
/// 7 : Grey /// 7 : Grey
GREY, GREY,
/// 8 : Dark Grey /// 8 : Dark Grey
DARK_GREY, DARK_GREY,
/// 9 : Bright Blue /// 9 : Bright Blue
BRIGHT_BLUE, BRIGHT_BLUE,
/// 10 : Bright Green /// 10 : Bright Green
BRIGHT_GREEN, BRIGHT_GREEN,
/// 11 : Bright Cyan /// 11 : Bright Cyan
BRIGHT_CYAN, BRIGHT_CYAN,
/// 12 : Bright Red /// 12 : Bright Red
BRIGHT_RED, BRIGHT_RED,
/// 13 : Bright Magenta /// 13 : Bright Magenta
BRIGHT_MAGENTA, BRIGHT_MAGENTA,
/// 14 : Yellow /// 14 : Yellow
YELLOW, YELLOW,
/// 15 : White /// 15 : White
WHITE, WHITE,
} video_color_t; } video_color_t;
/// @brief Initialize the video. /// @brief Initialize the video.
void video_init(); void video_init();
/// @brief Print the given character on the screen. /// @brief Print the given character on the screen.
void video_putc(int); void video_putc(int);
/// @brief Prints the given string on the screen. /// @brief Prints the given string on the screen.
void video_puts(const char *str); void video_puts(const char *str);
/// @brief Change foreground colour. /// @brief Change foreground colour.
void video_set_color(const video_color_t foreground); void video_set_color(const video_color_t foreground);
/// @brief Change background colour. /// @brief Change background colour.
void video_set_background(const video_color_t background); void video_set_background(const video_color_t background);
/// @brief Deletes the last inserted character. /// @brief Deletes the last inserted character.
void video_delete_last_character(); void video_delete_last_character();
/// @brief Move the cursor to the given position. /// @brief Move the cursor to the given position.
void video_set_cursor(const unsigned int x, const unsigned int y); void video_set_cursor(const unsigned int x, const unsigned int y);
/// @brief When something is written in another position, update the cursor. /// @brief When something is written in another position, update the cursor.
void video_set_cursor_auto(); void video_set_cursor_auto();
/// @brief Move the cursor at the position x, y on the screen. /// @brief Move the cursor at the position x, y on the screen.
void video_move_cursor(int, int); void video_move_cursor(int, int);
/// @brief Prints a tab on the screen. /// @brief Prints a tab on the screen.
void video_put_tab(); void video_put_tab();
/// @brief Clears the screen. /// @brief Clears the screen.
void video_clear(); void video_clear();
/// @brief Move to the following line (the effect of \n character). /// @brief Move to the following line (the effect of \n character).
void video_new_line(); void video_new_line();
/// @brief Move to the up line (the effect of \n character). /// @brief Move to the up line (the effect of \n character).
void video_cartridge_return(); void video_cartridge_return();
/// @brief Get the current column number. /// @brief Get the current column number.
uint32_t video_get_column(); uint32_t video_get_column();
/// @brief Get the current row number. /// @brief Get the current row number.
uint32_t video_get_line(); uint32_t video_get_line();
/// @brief The whole screen is shifted up by one line. Used when the cursor /// @brief The whole screen is shifted up by one line. Used when the cursor
/// reaches the last position of the screen. /// reaches the last position of the screen.
void video_shift_one_line(); void video_shift_one_line();
/// @brief The scrolling buffer is updated to contain the screen up the /// @brief The scrolling buffer is updated to contain the screen up the
/// current one. The oldest line is lost to make space for the new one. /// current one. The oldest line is lost to make space for the new one.
void video_rotate_scroll_buffer(); void video_rotate_scroll_buffer();
/// @brief Called by the pression of the PAGEUP key. /// @brief Called by the pression of the PAGEUP key.
/// The screen aboce the current one is printed and the current one is /// The screen aboce the current one is printed and the current one is
/// saved in downbuffer, ready to be restored in future. /// saved in downbuffer, ready to be restored in future.
void video_scroll_up(); void video_scroll_up();
/// @brief Called by the pression of the PAGEDOWN key. /// @brief Called by the pression of the PAGEDOWN key.
/// The content of downbuffer (that is, the screen present when you /// The content of downbuffer (that is, the screen present when you
/// pressed PAGEUP) is printed again. /// pressed PAGEUP) is printed again.
void video_scroll_down(); void video_scroll_down();
/// Determines the lower-bound on the x axis for the video. /// Determines the lower-bound on the x axis for the video.
uint32_t lower_bound_x; uint32_t lower_bound_x;
/// Determines the lower-bound on the y axis for the video. /// Determines the lower-bound on the y axis for the video.
uint32_t lower_bound_y; uint32_t lower_bound_y;
/// Determines the current position of the shell cursor on the x axis. /// Determines the current position of the shell cursor on the x axis.
uint32_t shell_current_x; uint32_t shell_current_x;
/// Determines the current position of the shell cursor on the y axis. /// Determines the current position of the shell cursor on the y axis.
uint32_t shell_current_y; uint32_t shell_current_y;
/// Determines the lower-bound on the x axis for the shell. /// Determines the lower-bound on the x axis for the shell.
uint32_t shell_lower_bound_x; uint32_t shell_lower_bound_x;
/// Determines the lower-bound on the y axis for the shell. /// Determines the lower-bound on the y axis for the shell.
uint32_t shell_lower_bound_y; uint32_t shell_lower_bound_y;
/// @brief Prints [OK] at the current row and column 60. /// @brief Prints [OK] at the current row and column 60.
void video_print_ok(); void video_print_ok();
/// @brief Prints [FAIL] at the current row and column 60. /// @brief Prints [FAIL] at the current row and column 60.
void video_print_fail(); void video_print_fail();
+278 -287
View File
@@ -1,287 +1,278 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file kernel.h /// @file kernel.h
/// @brief Kernel generic data structure and functions. /// @brief Kernel generic data structure and functions.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "elf.h" #include "elf.h"
#include "stddef.h" #include "stddef.h"
#include "stdint.h" #include "stdint.h"
#include "stdbool.h" #include "stdbool.h"
#include "multiboot.h" #include "multiboot.h"
/// The maximum length of a file name. /// The maximum number of modules.
#define MAX_FILENAME_LENGTH 64 #define MAX_MODULES 10
/// The maximum length of a path. /// Our kernel now loads at 0xC0000000, so what low memory address such as
#define MAX_PATH_LENGTH 256 /// 0xb800 you used to access, should be LOAD_MEMORY_ADDRESS + 0xb800
#define LOAD_MEMORY_ADDRESS 0x00000000
/// The maximum number of modules.
#define MAX_MODULES 10 // TODO: doxygen comment.
extern uintptr_t initial_esp;
/// This should be in %eax.
#define MULTIBOOT_BOOTLOADER_MAGIC 0x2BADB002 /// @brief Halt.
inline static void halt()
/// Our kernel now loads at 0xC0000000, so what low memory address such as {
/// 0xb800 you used to access, should be LOAD_MEMORY_ADDRESS + 0xb800 __asm__ __volatile__("hlt" ::: "memory");
#define LOAD_MEMORY_ADDRESS 0x00000000 }
// TODO: doxygen comment. /// @brief Pause.
extern uintptr_t initial_esp; inline static void pause()
{
/// @brief Halt. __asm__ __volatile__("pause" ::: "memory");
inline static void halt() }
{
__asm__ __volatile__("hlt" ::: "memory"); #define K 1024
}
#define M (1024 * K)
/// @brief Pause.
inline static void pause() #define G (1024 * M)
{
__asm__ __volatile__("pause" ::: "memory"); /// Pointer the beging of the module.
} extern char *module_start[MAX_MODULES];
#define K 1024 /// Address to the end of the module.
extern char *module_end[MAX_MODULES];
#define M (1024 * K)
/// Elf symbols of the kernel.
#define G (1024 * M) extern elf_symbols_t kernel_elf;
/// Pointer the beging of the module. /// @brief Entry point of the kernel.
extern char *module_start[MAX_MODULES]; /// @param boot_informations Information concerning the boot.
/// @return The exit status of the kernel.
/// Address to the end of the module. int kmain(uint32_t magic, multiboot_info_t *header, uintptr_t esp);
extern char *module_end[MAX_MODULES];
/// @brief Register structs for interrupt/exception.
/// Elf symbols of the kernel. typedef struct register_t {
extern elf_symbols_t kernel_elf; /// FS and GS have no hardware-assigned uses.
uint32_t gs;
/// @brief Entry point of the kernel. /// FS and GS have no hardware-assigned uses.
/// @param boot_informations Information concerning the boot. uint32_t fs;
/// @return The exit status of the kernel. /// Extra Segment determined by the programmer.
int kmain(uint32_t magic, multiboot_info_t *header, uintptr_t esp); uint32_t es;
/// Data Segment.
/// @brief Register structs for interrupt/exception. uint32_t ds;
typedef struct register_t { /// 32-bit destination register.
/// FS and GS have no hardware-assigned uses. uint32_t edi;
uint32_t gs; /// 32-bit source register.
/// FS and GS have no hardware-assigned uses. uint32_t esi;
uint32_t fs; /// 32-bit base pointer register.
/// Extra Segment determined by the programmer. uint32_t ebp;
uint32_t es; /// 32-bit stack pointer register.
/// Data Segment. uint32_t esp;
uint32_t ds; /// 32-bit base register.
/// 32-bit destination register. uint32_t ebx;
uint32_t edi; /// 32-bit data register.
/// 32-bit source register. uint32_t edx;
uint32_t esi; /// 32-bit counter.
/// 32-bit base pointer register. uint32_t ecx;
uint32_t ebp; /// 32-bit accumulator register.
/// 32-bit stack pointer register. uint32_t eax;
uint32_t esp; /// Interrupt number.
/// 32-bit base register. uint32_t int_no;
uint32_t ebx; /// Error code.
/// 32-bit data register. uint32_t err_code;
uint32_t edx; /// Instruction Pointer Register.
/// 32-bit counter. uint32_t eip;
uint32_t ecx; /// Code Segment.
/// 32-bit accumulator register. uint32_t cs;
uint32_t eax; /// 32-bit flag register.
/// Interrupt number. uint32_t eflags;
uint32_t int_no; // TODO: Check meaning!
/// Error code. uint32_t useresp;
uint32_t err_code; /// Stack Segment.
/// Instruction Pointer Register. uint32_t ss;
uint32_t eip; } register_t;
/// Code Segment.
uint32_t cs; /*
/// 32-bit flag register. * /// @brief Register structs for bios service.
uint32_t eflags; * typedef struct register16_t
// TODO: Check meaning! * {
uint32_t useresp; * /// Destination Index.
/// Stack Segment. * uint16_t di;
uint32_t ss; * /// Source Index.
} register_t; * uint16_t si;
* /// Base Pointer.
/* * uint16_t bp;
* /// @brief Register structs for bios service. * /// Stack Pointer.
* typedef struct register16_t * uint16_t sp;
* { * /// Also known as the base register.
* /// Destination Index. * uint16_t bx;
* uint16_t di; * /// Also known as the data register.
* /// Source Index. * uint16_t dx;
* uint16_t si; * /// Also known as the count register.
* /// Base Pointer. * uint16_t cx;
* uint16_t bp; * /// Is the primary accumulator.
* /// Stack Pointer. * uint16_t ax;
* uint16_t sp; * /// Data Segment.
* /// Also known as the base register. * uint16_t ds;
* uint16_t bx; * /// Extra Segment determined by the programmer.
* /// Also known as the data register. * uint16_t es;
* uint16_t dx; * /// FS and GS have no hardware-assigned uses.
* /// Also known as the count register. * uint16_t fs;
* uint16_t cx; * /// FS and GS have no hardware-assigned uses.
* /// Is the primary accumulator. * uint16_t gs;
* uint16_t ax; * /// Stack Segment.
* /// Data Segment. * uint16_t ss;
* uint16_t ds; * /// 32-bit flag register.
* /// Extra Segment determined by the programmer. * uint16_t eflags;
* uint16_t es; * } register16_t;
* /// FS and GS have no hardware-assigned uses. */
* uint16_t fs;
* /// FS and GS have no hardware-assigned uses. //==== Interrupt stack frame ===================================================
* uint16_t gs; // Interrupt stack frame. When the CPU moves from Ring3 to Ring0 because of
* /// Stack Segment. // an interrupt, the following registes/values are moved into the kernel's stack
* uint16_t ss; // TODO: doxygen comment.
* /// 32-bit flag register. typedef struct pt_regs {
* uint16_t eflags; /// FS and GS have no hardware-assigned uses.
* } register16_t; uint32_t gs;
*/ /// FS and GS have no hardware-assigned uses.
uint32_t fs;
//==== Interrupt stack frame =================================================== /// Extra Segment determined by the programmer.
// Interrupt stack frame. When the CPU moves from Ring3 to Ring0 because of uint32_t es;
// an interrupt, the following registes/values are moved into the kernel's stack /// Data Segment.
// TODO: doxygen comment. uint32_t ds;
typedef struct pt_regs { /// 32-bit destination register.
/// FS and GS have no hardware-assigned uses. uint32_t edi;
uint32_t gs; /// 32-bit source register.
/// FS and GS have no hardware-assigned uses. uint32_t esi;
uint32_t fs; /// 32-bit base pointer register.
/// Extra Segment determined by the programmer. uint32_t ebp;
uint32_t es; /// 32-bit stack pointer register.
/// Data Segment. uint32_t esp;
uint32_t ds; /// 32-bit base register.
/// 32-bit destination register. uint32_t ebx;
uint32_t edi; /// 32-bit data register.
/// 32-bit source register. uint32_t edx;
uint32_t esi; /// 32-bit counter.
/// 32-bit base pointer register. uint32_t ecx;
uint32_t ebp; /// 32-bit accumulator register.
/// 32-bit stack pointer register. uint32_t eax;
uint32_t esp; /// Interrupt number.
/// 32-bit base register. uint32_t int_no;
uint32_t ebx; /// Error code.
/// 32-bit data register. uint32_t err_code;
uint32_t edx; /// Instruction Pointer Register.
/// 32-bit counter. uint32_t eip;
uint32_t ecx; /// Code Segment.
/// 32-bit accumulator register. uint32_t cs;
uint32_t eax; /// 32-bit flag register.
/// Interrupt number. uint32_t eflags;
uint32_t int_no; // TODO: Check meaning!
/// Error code. uint32_t useresp;
uint32_t err_code; /// Stack Segment.
/// Instruction Pointer Register. uint32_t ss;
uint32_t eip; } pt_regs;
/// Code Segment. //==============================================================================
uint32_t cs;
/// 32-bit flag register. //==== Floating Point Unit (FPU) Register ======================================
uint32_t eflags; // Data structure used to save FPU registers.
// TODO: Check meaning! /// @brief Environment information of floating point unit.
uint32_t useresp; typedef struct {
/// Stack Segment. /// Control word (16bits).
uint32_t ss; long en_cw;
} pt_regs; /// Status word (16bits).
//============================================================================== long en_sw;
/// Tag word (16bits).
//==== Floating Point Unit (FPU) Register ====================================== long en_tw;
// Data structure used to save FPU registers. /// Floating point instruction pointer.
/// @brief Environment information of floating point unit. long en_fip;
typedef struct { /// Floating code segment selector.
/// Control word (16bits). unsigned short en_fcs;
long en_cw; /// Opcode last executed (11 bits).
/// Status word (16bits). unsigned short en_opcode;
long en_sw; /// Floating operand offset.
/// Tag word (16bits). long en_foo;
long en_tw; /// Floating operand segment selector.
/// Floating point instruction pointer. long en_fos;
long en_fip; } env87;
/// Floating code segment selector.
unsigned short en_fcs; /// @brief Contents of each floating point accumulator.
/// Opcode last executed (11 bits). typedef struct {
unsigned short en_opcode; unsigned char fp_bytes[10];
/// Floating operand offset. } fpacc87;
long en_foo;
/// Floating operand segment selector. /// @brief Floating point context.
long en_fos; typedef struct {
} env87; /// Floating point control/status.
env87 sv_env;
/// @brief Contents of each floating point accumulator. /// Accumulator contents, 0-7.
typedef struct { fpacc87 sv_ac[8];
unsigned char fp_bytes[10]; /// Padding for (now unused) saved status word.
} fpacc87; unsigned char sv_pad0[4];
/*
/// @brief Floating point context. * Bogus padding for emulators. Emulators should use their own
typedef struct { * struct and arrange to store into this struct (ending here)
/// Floating point control/status. * before it is inspected for ptracing or for core dumps. Some
env87 sv_env; * emulators overwrite the whole struct. We have no good way of
/// Accumulator contents, 0-7. * knowing how much padding to leave. Leave just enough for the
fpacc87 sv_ac[8]; * GPL emulator's i387_union (176 bytes total).
/// Padding for (now unused) saved status word. */
unsigned char sv_pad0[4]; unsigned char sv_pad[64]; // Padding; used by emulators
/* } save87;
* Bogus padding for emulators. Emulators should use their own
* struct and arrange to store into this struct (ending here) // TODO: doxygen comment.
* before it is inspected for ptracing or for core dumps. Some typedef struct {
* emulators overwrite the whole struct. We have no good way of /// Control word (16bits).
* knowing how much padding to leave. Leave just enough for the uint16_t en_cw;
* GPL emulator's i387_union (176 bytes total). /// Status word (16bits).
*/ uint16_t en_sw;
unsigned char sv_pad[64]; // Padding; used by emulators /// Tag word (16bits).
} save87; uint16_t en_tw;
/// Opcode last executed (11 bits).
// TODO: doxygen comment. uint16_t en_opcode;
typedef struct { /// Floating point instruction pointer.
/// Control word (16bits). uint32_t en_fip;
uint16_t en_cw; /// Floating code segment selector.
/// Status word (16bits). uint16_t en_fcs;
uint16_t en_sw; /// Padding.
/// Tag word (16bits). uint16_t en_pad0;
uint16_t en_tw; /// Floating operand offset.
/// Opcode last executed (11 bits). uint32_t en_foo;
uint16_t en_opcode; /// Floating operand segment selector.
/// Floating point instruction pointer. uint16_t en_fos;
uint32_t en_fip; /// Padding.
/// Floating code segment selector. uint16_t en_pad1;
uint16_t en_fcs; /// SSE sontorol/status register.
/// Padding. uint32_t en_mxcsr;
uint16_t en_pad0; /// Valid bits in mxcsr.
/// Floating operand offset. uint32_t en_mxcsr_mask;
uint32_t en_foo; } envxmm;
/// Floating operand segment selector.
uint16_t en_fos; /// @brief Contents of each SSE extended accumulator.
/// Padding. typedef struct {
uint16_t en_pad1; unsigned char xmm_bytes[16];
/// SSE sontorol/status register. } xmmacc;
uint32_t en_mxcsr;
/// Valid bits in mxcsr. // TODO: doxygen comment.
uint32_t en_mxcsr_mask; typedef struct {
} envxmm; envxmm sv_env;
struct {
/// @brief Contents of each SSE extended accumulator. fpacc87 fp_acc;
typedef struct { /// Padding.
unsigned char xmm_bytes[16]; unsigned char fp_pad[6];
} xmmacc; } sv_fp[8];
xmmacc sv_xmm[8];
// TODO: doxygen comment.
typedef struct { /// Padding.
envxmm sv_env; unsigned char sv_pad[224];
struct { } __attribute__((__aligned__(16))) savexmm;
fpacc87 fp_acc;
/// Padding. // TODO: doxygen comment.
unsigned char fp_pad[6]; typedef union {
} sv_fp[8]; save87 sv_87;
xmmacc sv_xmm[8]; savexmm sv_xmm;
} savefpu;
/// Padding. //==============================================================================
unsigned char sv_pad[224];
} __attribute__((__aligned__(16))) savexmm;
// TODO: doxygen comment.
typedef union {
save87 sv_87;
savexmm sv_xmm;
} savefpu;
//==============================================================================
-15
View File
@@ -1,15 +0,0 @@
/// MentOS, The Mentoring Operating system project
/// @file sys.h
/// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details.
#pragma once
// TODO: doxygen comment.
/// @brief
/// @param magic1
/// @param magic2
/// @param cmd
/// @param arg
int sys_reboot(int magic1, int magic2, unsigned int cmd, void *arg);
+24 -34
View File
@@ -1,34 +1,24 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file assert.h /// @file assert.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdio.h" #include "stdio.h"
#include "panic.h" #include "panic.h"
#include "stdarg.h" #include "stdarg.h"
/// @brief Function used to log the information of a failed assertion. /// @brief Function used to log the information of a failed assertion.
/// @param assertion The failed assertion. /// @param assertion The failed assertion.
/// @param file The file where the assertion is located. /// @param file The file where the assertion is located.
/// @param line The line inside the file. /// @param line The line inside the file.
/// @param function The function where the assertion is. /// @param function The function where the assertion is.
static void __assert_fail(const char *assertion, const char *file, void __assert_fail(const char *assertion, const char *file, unsigned int line,
unsigned int line, const char *function) const char *function);
{
char message[1024]; /// @brief Assert function.
sprintf(message, #define assert(expression) \
"FILE: %s\n" ((expression) ? (void)0 : \
"LINE: %d\n" __assert_fail(#expression, __FILE__, __LINE__, __func__))
"FUNC: %s\n\n"
"Assertion `%s` failed.\n",
file, line, (function ? function : "NO_FUN"), assertion);
kernel_panic(message);
}
/// @brief Assert function.
#define assert(expression) \
((expression) ? (void)0 : \
__assert_fail(#expression, __FILE__, __LINE__, __func__))
+42 -42
View File
@@ -1,42 +1,42 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file bitset.h /// @file bitset.h
/// @brief Bitset data structure. /// @brief Bitset data structure.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stddef.h" #include "stddef.h"
#include "stdbool.h" #include "stdbool.h"
/// @brief Bitset structure. /// @brief Bitset structure.
typedef struct { typedef struct {
/// The internal data. /// The internal data.
unsigned char *data; unsigned char *data;
/// The size of the bitset. /// The size of the bitset.
size_t size; size_t size;
} bitset_t; } bitset_t;
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void bitset_init(bitset_t *set, size_t size); void bitset_init(bitset_t *set, size_t size);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void bitset_free(bitset_t *set); void bitset_free(bitset_t *set);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void bitset_set(bitset_t *set, size_t bit); void bitset_set(bitset_t *set, size_t bit);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
void bitset_clear(bitset_t *set, size_t bit); void bitset_clear(bitset_t *set, size_t bit);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
bool_t bitset_test(bitset_t *set, size_t bit); bool_t bitset_test(bitset_t *set, size_t bit);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
signed long bitset_find_first_unset_bit(bitset_t *set); signed long bitset_find_first_unset_bit(bitset_t *set);
+22 -22
View File
@@ -1,22 +1,22 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file compiler.h /// @file compiler.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/* /*
* Prevent the compiler from merging or refetching reads or writes. * Prevent the compiler from merging or refetching reads or writes.
* *
* Ensuring that the compiler does not fold, spindle, or otherwise * Ensuring that the compiler does not fold, spindle, or otherwise
* mutilate accesses that either do not require ordering or that interact * mutilate accesses that either do not require ordering or that interact
* with an explicit memory barrier or atomic instruction that provides the * with an explicit memory barrier or atomic instruction that provides the
* required ordering. * required ordering.
*/ */
/// @brief Assign the value to the given variable. /// @brief Assign the value to the given variable.
#define WRITE_ONCE(var, val) (*((volatile typeof(val) *)(&(var))) = (val)) #define WRITE_ONCE(var, val) (*((volatile typeof(val) *)(&(var))) = (val))
/// @brief Read the value from the given variable. /// @brief Read the value from the given variable.
#define READ_ONCE(var) (*((volatile typeof(var) *)(&(var)))) #define READ_ONCE(var) (*((volatile typeof(var) *)(&(var))))
+34 -34
View File
@@ -1,34 +1,34 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file ctype.h /// @file ctype.h
/// @brief Functions related to character handling. /// @brief Functions related to character handling.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/// @brief Check if the given value is a digit. /// @brief Check if the given value is a digit.
int isdigit(int c); int isdigit(int c);
/// @brief Check if the given value is a letter. /// @brief Check if the given value is a letter.
int isalpha(int c); int isalpha(int c);
/// @brief Check if the given value is either a letter or a digit. /// @brief Check if the given value is either a letter or a digit.
int isalnum(int c); int isalnum(int c);
/// @brief Check if the given value is an hexadecimal digit. /// @brief Check if the given value is an hexadecimal digit.
int isxdigit(int c); int isxdigit(int c);
/// @brief Check if the given value is a lower case letter. /// @brief Check if the given value is a lower case letter.
int islower(int c); int islower(int c);
/// @brief Check if the given value is an upper case letter. /// @brief Check if the given value is an upper case letter.
int isupper(int c); int isupper(int c);
/// @brief Transforms the given value into a lower case letter. /// @brief Transforms the given value into a lower case letter.
int tolower(int c); int tolower(int c);
/// @brief Transforms the given value into an upper case letter. /// @brief Transforms the given value into an upper case letter.
int toupper(int c); int toupper(int c);
/// @brief Check if the given value is a whitespace. /// @brief Check if the given value is a whitespace.
int isspace(int c); int isspace(int c);
+27 -27
View File
@@ -1,27 +1,27 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file fcvt.h /// @file fcvt.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
/// @param arg /// @param arg
/// @param ndigits /// @param ndigits
/// @param decpt /// @param decpt
/// @param sign /// @param sign
/// @param buf /// @param buf
/// @result /// @result
char *ecvtbuf(double arg, int ndigits, int *decpt, int *sign, char *buf); char *ecvtbuf(double arg, int ndigits, int *decpt, int *sign, char *buf);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
/// @param arg /// @param arg
/// @param ndigits /// @param ndigits
/// @param decpt /// @param decpt
/// @param sign /// @param sign
/// @param buf /// @param buf
/// @result /// @result
char *fcvtbuf(double arg, int ndigits, int *decpt, int *sign, char *buf); char *fcvtbuf(double arg, int ndigits, int *decpt, int *sign, char *buf);
+80 -80
View File
@@ -1,80 +1,80 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file hashmap.h /// @file hashmap.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "list.h" #include "list.h"
#include "stdbool.h" #include "stdbool.h"
//============================================================================== //==============================================================================
// Opaque types. // Opaque types.
typedef struct hashmap_entry_t hashmap_entry_t; typedef struct hashmap_entry_t hashmap_entry_t;
typedef struct hashmap_t hashmap_t; typedef struct hashmap_t hashmap_t;
//============================================================================= //=============================================================================
// Hashmap functions. // Hashmap functions.
// TODO: doxygen comment. // TODO: doxygen comment.
typedef size_t (*hashmap_hash_t)(void *key); typedef size_t (*hashmap_hash_t)(void *key);
// TODO: doxygen comment. // TODO: doxygen comment.
typedef bool_t (*hashmap_comp_t)(void *a, void *b); typedef bool_t (*hashmap_comp_t)(void *a, void *b);
// TODO: doxygen comment. // TODO: doxygen comment.
typedef void (*hashmap_free_t)(void *); typedef void (*hashmap_free_t)(void *);
// TODO: doxygen comment. // TODO: doxygen comment.
typedef void *(*hashmap_dupe_t)(void *); typedef void *(*hashmap_dupe_t)(void *);
//============================================================================== //==============================================================================
// Hashmap creation and destruction. // Hashmap creation and destruction.
// TODO: doxygen comment. // TODO: doxygen comment.
extern hashmap_t *hashmap_create(size_t size); extern hashmap_t *hashmap_create(size_t size);
// TODO: doxygen comment. // TODO: doxygen comment.
extern hashmap_t *hashmap_create_int(size_t size); extern hashmap_t *hashmap_create_int(size_t size);
// TODO: doxygen comment. // TODO: doxygen comment.
extern void hashmap_free(hashmap_t *map); extern void hashmap_free(hashmap_t *map);
//============================================================================== //==============================================================================
// Hashmap management. // Hashmap management.
// TODO: doxygen comment. // TODO: doxygen comment.
extern void *hashmap_set(hashmap_t *map, void *key, void *value); extern void *hashmap_set(hashmap_t *map, void *key, void *value);
// TODO: doxygen comment. // TODO: doxygen comment.
extern void *hashmap_get(hashmap_t *map, void *key); extern void *hashmap_get(hashmap_t *map, void *key);
// TODO: doxygen comment. // TODO: doxygen comment.
extern void *hashmap_remove(hashmap_t *map, void *key); extern void *hashmap_remove(hashmap_t *map, void *key);
//============================================================================== //==============================================================================
// Hashmap search. // Hashmap search.
// TODO: doxygen comment. // TODO: doxygen comment.
extern bool_t hashmap_is_empty(hashmap_t *map); extern bool_t hashmap_is_empty(hashmap_t *map);
// TODO: doxygen comment. // TODO: doxygen comment.
extern bool_t hashmap_has(hashmap_t *map, void *key); extern bool_t hashmap_has(hashmap_t *map, void *key);
// TODO: doxygen comment. // TODO: doxygen comment.
extern list_t *hashmap_keys(hashmap_t *map); extern list_t *hashmap_keys(hashmap_t *map);
// TODO: doxygen comment. // TODO: doxygen comment.
extern list_t *hashmap_values(hashmap_t *map); extern list_t *hashmap_values(hashmap_t *map);
// TODO: doxygen comment. // TODO: doxygen comment.
extern size_t hashmap_string_hash(void *key); extern size_t hashmap_string_hash(void *key);
// TODO: doxygen comment. // TODO: doxygen comment.
extern bool_t hashmap_string_comp(void *a, void *b); extern bool_t hashmap_string_comp(void *a, void *b);
// TODO: doxygen comment. // TODO: doxygen comment.
extern void *hashmap_string_dupe(void *key); extern void *hashmap_string_dupe(void *key);
//============================================================================== //==============================================================================
+72 -72
View File
@@ -1,72 +1,72 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file irqflags.h /// @file irqflags.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stddef.h" #include "stddef.h"
#include "stdint.h" #include "stdint.h"
/// @brief Enable IRQs. /// @brief Enable IRQs.
inline static void irq_enable() inline static void irq_enable()
{ {
__asm__ __volatile__("sti" ::: "memory"); __asm__ __volatile__("sti" ::: "memory");
} }
// TODO: doxygen comment. // TODO: doxygen comment.
inline unsigned long get_eflags() inline unsigned long get_eflags()
{ {
unsigned long eflags; unsigned long eflags;
/* "=rm" is safe here, because "pop" adjusts the stack before /* "=rm" is safe here, because "pop" adjusts the stack before
* it evaluates its effective address -- this is part of the * it evaluates its effective address -- this is part of the
* documented behavior of the "pop" instruction. * documented behavior of the "pop" instruction.
*/ */
__asm__ __volatile__("pushf ; pop %0" __asm__ __volatile__("pushf ; pop %0"
: "=rm"(eflags) : "=rm"(eflags)
: /* no input */ : /* no input */
: "memory"); : "memory");
return eflags; return eflags;
} }
/// @brief Enable IRQs (nested). /// @brief Enable IRQs (nested).
/// @details If called after calling irq_nested_disable, this function will /// @details If called after calling irq_nested_disable, this function will
/// not activate IRQs if they were not active before. /// not activate IRQs if they were not active before.
inline static void irq_nested_enable(uint8_t flags) inline static void irq_nested_enable(uint8_t flags)
{ {
if (flags) { if (flags) {
irq_enable(); irq_enable();
} }
} }
/// @brief Disable IRQs. /// @brief Disable IRQs.
inline static void irq_disable() inline static void irq_disable()
{ {
__asm__ __volatile__("cli" ::: "memory"); __asm__ __volatile__("cli" ::: "memory");
} }
/// @brief Disable IRQs (nested). /// @brief Disable IRQs (nested).
/// @details Disable IRQs when unsure if IRQs were enabled at all. /// @details Disable IRQs when unsure if IRQs were enabled at all.
/// This function together with irq_nested_enable can be used in /// This function together with irq_nested_enable can be used in
/// situations when interrupts shouldn't be activated if they were not /// situations when interrupts shouldn't be activated if they were not
/// activated before calling this function. /// activated before calling this function.
inline static uint8_t irq_nested_disable() inline static uint8_t irq_nested_disable()
{ {
size_t flags; size_t flags;
__asm__ __volatile__("pushf; cli; pop %0" : "=r"(flags) : : "memory"); __asm__ __volatile__("pushf; cli; pop %0" : "=r"(flags) : : "memory");
if (flags & (1 << 9)) if (flags & (1 << 9))
return 1; return 1;
return 0; return 0;
} }
/// @brief Determines, if the interrupt flags (IF) is set. /// @brief Determines, if the interrupt flags (IF) is set.
inline static uint8_t is_irq_enabled() inline static uint8_t is_irq_enabled()
{ {
size_t flags; size_t flags;
__asm__ __volatile__("pushf; pop %0" : "=r"(flags) : : "memory"); __asm__ __volatile__("pushf; pop %0" : "=r"(flags) : : "memory");
if (flags & (1 << 9)) { if (flags & (1 << 9)) {
return 1; return 1;
} }
return 0; return 0;
} }
+28 -28
View File
@@ -1,28 +1,28 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file libgen.h /// @file libgen.h
/// @brief String routines. /// @brief String routines.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#include "stddef.h" #include "stddef.h"
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
/// @param out /// @param out
/// @param cur /// @param cur
/// @param sep /// @param sep
/// @param max /// @param max
/// @result /// @result
int parse_path(char *out, char **cur, char sep, size_t max); int parse_path(char *out, char **cur, char sep, size_t max);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
/// @param path /// @param path
/// @result /// @result
char *dirname(const char *path); char *dirname(const char *path);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
/// @param path /// @param path
/// @result /// @result
char *basename(const char *path); char *basename(const char *path);
+47 -41
View File
@@ -1,41 +1,47 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file limits.h /// @file limits.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/// Number of bits in a `char'. /// Number of bits in a `char'.
#define CHAR_BIT 8 #define CHAR_BIT 8
/// Minimum value a `signed char' can hold. /// Minimum value a `signed char' can hold.
#define SCHAR_MIN (-128) #define SCHAR_MIN (-128)
/// Maximum value a `signed char' can hold. /// Maximum value a `signed char' can hold.
#define SCHAR_MAX 127 #define SCHAR_MAX 127
/// Maximum value a `char' can hold. (Minimum is 0.) /// Maximum value a `char' can hold. (Minimum is 0.)
#define CHAR_MAX 255 #define CHAR_MAX 255
/// Minimum value a `signed short int' can hold. /// Minimum value a `signed short int' can hold.
#define SHRT_MIN (-32768) #define SHRT_MIN (-32768)
/// Maximum value a `signed short int' can hold. /// Maximum value a `signed short int' can hold.
#define SHRT_MAX 32767 #define SHRT_MAX 32767
/// Minimum value a `signed int' can hold. /// Minimum value a `signed int' can hold.
#define INT_MIN (-INT_MAX - 1) #define INT_MIN (-INT_MAX - 1)
/// Maximum values a `signed int' can hold. /// Maximum values a `signed int' can hold.
#define INT_MAX 2147483647 #define INT_MAX 2147483647
/// Maximum value an `unsigned int' can hold. (Minimum is 0.) /// Maximum value an `unsigned int' can hold. (Minimum is 0.)
#define UINT_MAX 4294967295U #define UINT_MAX 4294967295U
/// Minimum value a `signed long int' can hold. /// Minimum value a `signed long int' can hold.
#define LONG_MAX 2147483647L #define LONG_MAX 2147483647L
/// Maximum value a `signed long int' can hold. /// Maximum value a `signed long int' can hold.
#define LONG_MIN (-LONG_MAX - 1L) #define LONG_MIN (-LONG_MAX - 1L)
/// Maximum number of characters in a file name.
#define NAME_MAX 255
/// Maximum number of characters in a path name.
#define PATH_MAX 4096
+107 -107
View File
@@ -1,107 +1,107 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file list.h /// @file list.h
/// @brief An implementation for generic list. /// @brief An implementation for generic list.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
#include "stddef.h" #include "stddef.h"
#include "stdbool.h" #include "stdbool.h"
/// @brief Represent the node of a list. /// @brief Represent the node of a list.
typedef struct listnode_t { typedef struct listnode_t {
/// A pointer to the value. /// A pointer to the value.
void *value; void *value;
/// The previous node. /// The previous node.
struct listnode_t *prev; struct listnode_t *prev;
/// The next node. /// The next node.
struct listnode_t *next; struct listnode_t *next;
} listnode_t; } listnode_t;
/// @brief Represent the list. /// @brief Represent the list.
typedef struct list_t { typedef struct list_t {
/// The first element of the list. /// The first element of the list.
listnode_t *head; listnode_t *head;
/// The last element of the list. /// The last element of the list.
listnode_t *tail; listnode_t *tail;
/// The size of the list. /// The size of the list.
size_t size; size_t size;
} list_t; } list_t;
/// @brief Macro used to iterate through a list. /// @brief Macro used to iterate through a list.
#define listnode_foreach(it, list) \ #define listnode_foreach(it, list) \
for (listnode_t * (it) = (list)->head; (it) != NULL; (it) = (it)->next) for (listnode_t * (it) = (list)->head; (it) != NULL; (it) = (it)->next)
/// @brief Create a list and set head, tail to NULL, and size to 0. /// @brief Create a list and set head, tail to NULL, and size to 0.
list_t *list_create(); list_t *list_create();
/// @brief Get list size. /// @brief Get list size.
size_t list_size(list_t *list); size_t list_size(list_t *list);
/// @brief Checks if the list is empty. /// @brief Checks if the list is empty.
bool_t list_empty(list_t *list); bool_t list_empty(list_t *list);
/// @brief Insert a value at the front of list. /// @brief Insert a value at the front of list.
listnode_t *list_insert_front(list_t *list, void *value); listnode_t *list_insert_front(list_t *list, void *value);
/// @brief Insert a value at the back of list. /// @brief Insert a value at the back of list.
listnode_t *list_insert_back(list_t *list, void *value); listnode_t *list_insert_back(list_t *list, void *value);
/// @brief Insert a value at the back of list. /// @brief Insert a value at the back of list.
void list_insert_node_back(list_t *list, listnode_t *item); void list_insert_node_back(list_t *list, listnode_t *item);
/// @brief Given a listnode, remove it from lis. /// @brief Given a listnode, remove it from lis.
void *list_remove_node(list_t *list, listnode_t *node); void *list_remove_node(list_t *list, listnode_t *node);
/// @brief Remove a value at the front of list. /// @brief Remove a value at the front of list.
void *list_remove_front(list_t *list); void *list_remove_front(list_t *list);
/// @brief Remove a value at the back of list. /// @brief Remove a value at the back of list.
void *list_remove_back(list_t *list); void *list_remove_back(list_t *list);
/// @brief Searches the node of the list which points at the given value. /// @brief Searches the node of the list which points at the given value.
listnode_t *list_find(list_t *list, void *value); listnode_t *list_find(list_t *list, void *value);
/// @brief Insert after tail of list(same as insert back). /// @brief Insert after tail of list(same as insert back).
void list_push(list_t *list, void *value); void list_push(list_t *list, void *value);
/// @brief Remove and return the tail of the list. /// @brief Remove and return the tail of the list.
/// @details User is responsible for freeing the returned node and the value. /// @details User is responsible for freeing the returned node and the value.
listnode_t *list_pop_back(list_t *list); listnode_t *list_pop_back(list_t *list);
/// @brief Remove and return the head of the list. /// @brief Remove and return the head of the list.
/// @details User is responsible for freeing the returned node and the value. /// @details User is responsible for freeing the returned node and the value.
listnode_t *list_pop_front(list_t *list); listnode_t *list_pop_front(list_t *list);
/// @brief Insert before head of list(same as insert front). /// @brief Insert before head of list(same as insert front).
void list_enqueue(list_t *list, void *value); void list_enqueue(list_t *list, void *value);
/// @brief Remove and return tail of list(same as list_pop). /// @brief Remove and return tail of list(same as list_pop).
listnode_t *list_dequeue(list_t *list); listnode_t *list_dequeue(list_t *list);
/// @brief Get the value of the first element but not remove it. /// @brief Get the value of the first element but not remove it.
void *list_peek_front(list_t *list); void *list_peek_front(list_t *list);
/// @brief Get the value of the last element but not remove it. /// @brief Get the value of the last element but not remove it.
void *list_peek_back(list_t *list); void *list_peek_back(list_t *list);
/// @brief Destory a list. /// @brief Destory a list.
void list_destroy(list_t *list); void list_destroy(list_t *list);
/// @brief Destroy a node of the list. /// @brief Destroy a node of the list.
void listnode_destroy(listnode_t *node); void listnode_destroy(listnode_t *node);
/// @brief Does the list contain a value (Return -1 if list element is not /// @brief Does the list contain a value (Return -1 if list element is not
/// found). /// found).
int list_contain(list_t *list, void *value); int list_contain(list_t *list, void *value);
/// @brief Returns the node at the given index. /// @brief Returns the node at the given index.
listnode_t *list_get_node_by_index(list_t *list, size_t index); listnode_t *list_get_node_by_index(list_t *list, size_t index);
/// @brief Removes a node from the list at the given index. /// @brief Removes a node from the list at the given index.
void *list_remove_by_index(list_t *list, size_t index); void *list_remove_by_index(list_t *list, size_t index);
/// @brief Append source at the end of target and DESTROY source. /// @brief Append source at the end of target and DESTROY source.
void list_merge(list_t *target, list_t *source); void list_merge(list_t *target, list_t *source);
+129 -133
View File
@@ -1,133 +1,129 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file list_head.h /// @file list_head.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stddef.h" #include "stddef.h"
/// @brief Structure used to implement the list_head data structure. /// @brief Structure used to implement the list_head data structure.
typedef struct list_head typedef struct list_head {
{ /// @brief The previous element.
/// @brief The previous element. struct list_head *prev;
struct list_head * prev; /// @brief The subsequent element.
/// @brief The subsequent element. struct list_head *next;
struct list_head * next; } list_head;
} list_head;
/// @brief Get the struct for this entry.
/// @brief Get the struct for this entry. /// @param ptr The &struct list_head pointer.
/// @param ptr The &struct list_head pointer. /// @param type The type of the struct this is embedded in.
/// @param type The type of the struct this is embedded in. /// @param member The name of the list_head within the struct.
/// @param member The name of the list_head within the struct. #define list_entry(ptr, type, member) \
#define list_entry(ptr, type, member) \ ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member)))
((type *) ((char *) (ptr) - (unsigned long) (&((type *) 0)->member)))
/// @brief Iterates over a list.
/// @brief Iterates over a list. /// @param pos The &struct list_head to use as a loop cursor.
/// @param pos The &struct list_head to use as a loop cursor. /// @param head The head for your list.
/// @param head The head for your list. #define list_for_each(pos, head) \
#define list_for_each(pos, head) \ for ((pos) = (head)->next; (pos) != (head); (pos) = (pos)->next)
for ((pos) = (head)->next; (pos) != (head); (pos) = (pos)->next)
/// @brief Iterates over a list backwards.
/// @brief Iterates over a list backwards. /// @param pos The &struct list_head to use as a loop cursor.
/// @param pos The &struct list_head to use as a loop cursor. /// @param head The head for your list.
/// @param head The head for your list. #define list_for_each_prev(pos, head) \
#define list_for_each_prev(pos, head) \ for ((pos) = (head)->prev; (pos) != (head); (pos) = (pos)->prev)
for ((pos) = (head)->prev; (pos) != (head); (pos) = (pos)->prev)
/// @brief Iterates over a list safe against removal of list entry.
/// @brief Iterates over a list safe against removal of list entry. /// @param pos The &struct list_head to use as a loop cursor.
/// @param pos The &struct list_head to use as a loop cursor. /// @param store Another &struct list_head to use as temporary storage.
/// @param store Another &struct list_head to use as temporary storage. /// @param head The head for your list.
/// @param head The head for your list. #define list_for_each_safe(pos, store, head) \
#define list_for_each_safe(pos, store, head) \ for ((pos) = (head)->next, (store) = (pos)->next; (pos) != (head); \
for ((pos) = (head)->next, (store) = (pos)->next; (pos) != (head); \ (pos) = (store), (store) = (pos)->next)
(pos) = (store), (store) = (pos)->next)
/// @brief Initializes the list_head.
/// @brief Initializes the list_head. /// @param head The head for your list.
/// @param head The head for your list. #define list_head_init(head) (head)->next = (head)->prev = (head)
#define list_head_init(head) \
(head)->next = (head)->prev = (head) /// @brief Insert element l2 after l1.
static inline void list_head_insert_after(list_head *l1, list_head *l2)
/// @brief Insert element l2 after l1. {
static inline void list_head_insert_after(list_head * l1, list_head * l2) // [La]->l1 La<-[l1]->Lb <-[l2]-> l1<-[Lb]
{
// [La]->l1 La<-[l1]->Lb <-[l2]-> l1<-[Lb] list_head *l1_next = l1->next;
// [La]->l1 La<-[l1]->l2 <-[l2]-> l1<-[Lb]
list_head * l1_next = l1->next; l1->next = l2;
// [La]->l1 La<-[l1]->l2 <-[l2]-> l1<-[Lb] // [La]->l1 La<-[l1]->l2 l1<-[l2]-> l1<-[Lb]
l1->next = l2; l2->prev = l1;
// [La]->l1 La<-[l1]->l2 l1<-[l2]-> l1<-[Lb] // [La]->l1 La<-[l1]->l2 l1<-[l2]->Lb l1<-[Lb]
l2->prev = l1; l2->next = l1_next;
// [La]->l1 La<-[l1]->l2 l1<-[l2]->Lb l1<-[Lb] // [La]->l1 La<-[l1]->l2 l1<-[l2]->Lb l2<-[Lb]
l2->next = l1_next; l1_next->prev = l2;
// [La]->l1 La<-[l1]->l2 l1<-[l2]->Lb l2<-[Lb] }
l1_next->prev = l2;
} /// @brief Insert element l2 before l1.
static inline void list_head_insert_before(list_head *l1, list_head *l2)
/// @brief Insert element l2 before l1. {
static inline void list_head_insert_before(list_head * l1, list_head * l2) // [La]->l1 [l2] La<-[l1]->Lb l1<-[Lb]
{
// [La]->l1 [l2] La<-[l1]->Lb l1<-[Lb] list_head *l1_prev = l1->prev;
// [La]->l2 [l2] La<-[l1]->Lb l1<-[Lb]
list_head * l1_prev = l1->prev; l1_prev->next = l2;
// [La]->l2 [l2] La<-[l1]->Lb l1<-[Lb] // [La]->l2 La<-[l2] La<-[l1]->Lb l1<-[Lb]
l1_prev->next = l2; l2->prev = l1_prev;
// [La]->l2 La<-[l2] La<-[l1]->Lb l1<-[Lb] // [La]->l2 La<-[l2]->l1 La<-[l1]->Lb l1<-[Lb]
l2->prev = l1_prev; l2->next = l1;
// [La]->l2 La<-[l2]->l1 La<-[l1]->Lb l1<-[Lb] // [La]->l2 La<-[l2]->l1 l2<-[l1]->Lb l1<-[Lb]
l2->next = l1; l1->prev = l2;
// [La]->l2 La<-[l2]->l1 l2<-[l1]->Lb l1<-[Lb] }
l1->prev = l2;
} /// @brief Remove l from the list.
/// @param l The element to remove.
/// @brief Remove l from the list. static inline void list_head_del(list_head *l)
/// @param l The element to remove. {
static inline void list_head_del(list_head * l) // [La]->l La<-[l]->Lb l<-[Lb]
{
// [La]->l La<-[l]->Lb l<-[Lb] // [La]->Lb La<-[l]->Lb l<-[Lb]
l->prev->next = l->next;
// [La]->Lb La<-[l]->Lb l<-[Lb] // [La]->Lb La<-[l]->Lb La<-[Lb]
l->prev->next = l->next; l->next->prev = l->prev;
// [La]->Lb La<-[l]->Lb La<-[Lb] // [La]->Lb l<-[l]->l La<-[Lb]
l->next->prev = l->prev; l->next = l->prev = l;
// [La]->Lb l<-[l]->l La<-[Lb] }
l->next = l->prev = l;
} /// @brief Tests whether the given list is empty.
/// @param head The list to check.
/// @brief Tests whether the given list is empty. /// @return 1 if empty, 0 otherwise.
/// @param head The list to check. static inline int list_head_empty(list_head const *head)
/// @return 1 if empty, 0 otherwise. {
static inline int list_head_empty(list_head const * head) return head->next == head;
{ }
return head->next == head;
} /// Insert a new entry between two known consecutive entries.
static inline void __list_add(list_head *new, list_head *prev, list_head *next)
/// Insert a new entry between two known consecutive entries. {
static inline void __list_add(list_head * new, // [prev]-> <-[new]-> <-[next]
list_head * prev,
list_head * next) // [prev]-> <-[new]-> new<-[next]
{ next->prev = new;
// [prev]-> <-[new]-> <-[next] // [prev]-> <-[new]->next new<-[next]
new->next = next;
// [prev]-> <-[new]-> new<-[next] // [prev]-> prev<-[new]->next new<-[next]
next->prev = new; new->prev = prev;
// [prev]-> <-[new]->next new<-[next] // [prev]->new prev<-[new]->next new<-[next]
new->next = next; prev->next = new;
// [prev]-> prev<-[new]->next new<-[next] }
new->prev = prev;
// [prev]->new prev<-[new]->next new<-[next] /// @brief Insert element l2 before l1.
prev->next = new; static inline void list_head_add(list_head *new, list_head *head)
} {
__list_add(new, head, head->next);
/// @brief Insert element l2 before l1. }
static inline void list_head_add(list_head * new, list_head * head)
{ /// @brief Insert element l2 before l1.
__list_add(new, head, head->next); static inline void list_head_add_tail(list_head *new, list_head *head)
} {
__list_add(new, head->prev, head);
/// @brief Insert element l2 before l1. }
static inline void list_head_add_tail(list_head * new, list_head * head)
{
__list_add(new, head->prev, head);
}
+131 -131
View File
@@ -1,131 +1,131 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file math.h /// @file math.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/// @brief The absolute value. /// @brief The absolute value.
#define abs(a) (((a) < 0) ? -(a) : (a)) #define abs(a) (((a) < 0) ? -(a) : (a))
/// @brief The max of the two values. /// @brief The max of the two values.
#define max(a, b) (((a) > (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b))
/// @brief The min of the two values. /// @brief The min of the two values.
#define min(a, b) (((a) < (b)) ? (a) : (b)) #define min(a, b) (((a) < (b)) ? (a) : (b))
/// @brief The sign the the passed value. /// @brief The sign the the passed value.
#define sign(x) ((x < 0) ? -1 : ((x > 0) ? 1 : 0)) #define sign(x) ((x < 0) ? -1 : ((x > 0) ? 1 : 0))
/// @brief Returns a rounded up, away from zero, to the nearest multiple of b. /// @brief Returns a rounded up, away from zero, to the nearest multiple of b.
#define ceil(NUMBER, BASE) (((NUMBER) + (BASE)-1) & ~((BASE)-1)) #define ceil(NUMBER, BASE) (((NUMBER) + (BASE)-1) & ~((BASE)-1))
/// @brief e /// @brief e
#define M_E 2.7182818284590452354 #define M_E 2.7182818284590452354
/// @brief log_2 e /// @brief log_2 e
#define M_LOG2E 1.4426950408889634074 #define M_LOG2E 1.4426950408889634074
/// @brief log_10 e /// @brief log_10 e
#define M_LOG10E 0.43429448190325182765 #define M_LOG10E 0.43429448190325182765
/// @brief log_e 2 /// @brief log_e 2
#define M_LN2 0.69314718055994530942 #define M_LN2 0.69314718055994530942
/// @brief log_e 10 /// @brief log_e 10
#define M_LN10 2.30258509299404568402 #define M_LN10 2.30258509299404568402
/// @brief pi /// @brief pi
#define M_PI 3.14159265358979323846 #define M_PI 3.14159265358979323846
/// @brief pi / 2 /// @brief pi / 2
#define M_PI_2 1.57079632679489661923 #define M_PI_2 1.57079632679489661923
/// @brief pi / 4 /// @brief pi / 4
#define M_PI_4 0.78539816339744830962 #define M_PI_4 0.78539816339744830962
/// @brief 1 / pi /// @brief 1 / pi
#define M_1_PI 0.31830988618379067154 #define M_1_PI 0.31830988618379067154
/// @brief 2 / pi /// @brief 2 / pi
#define M_2_PI 0.63661977236758134308 #define M_2_PI 0.63661977236758134308
/// @brief 2 / sqrt(pi) /// @brief 2 / sqrt(pi)
#define M_2_SQRTPI 1.12837916709551257390 #define M_2_SQRTPI 1.12837916709551257390
/// @brief sqrt(2) /// @brief sqrt(2)
#define M_SQRT2 1.41421356237309504880 #define M_SQRT2 1.41421356237309504880
/// @brief 1 / sqrt(2) /// @brief 1 / sqrt(2)
#define M_SQRT1_2 0.70710678118654752440 #define M_SQRT1_2 0.70710678118654752440
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
/// @param x /// @param x
/// @result /// @result
double round(double x); double round(double x);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
/// @param x /// @param x
/// @result /// @result
double floor(double x); double floor(double x);
/// @brief Power function. /// @brief Power function.
/// @param x First number. /// @param x First number.
/// @param y Second number. /// @param y Second number.
/// @result Power between number x and y. /// @result Power between number x and y.
double pow(double x, double y); double pow(double x, double y);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
/// @param base /// @param base
/// @param value /// @param value
/// @result /// @result
long find_nearest_pow_greater(double base, double value); long find_nearest_pow_greater(double base, double value);
/// @brief Exponential function. /// @brief Exponential function.
/// @param x Value of the exponent. /// @param x Value of the exponent.
double exp(double x); double exp(double x);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
/// @param x /// @param x
/// @result /// @result
double fabs(double x); double fabs(double x);
/// @brief Square root function. /// @brief Square root function.
/// @param x Topic of the square root. /// @param x Topic of the square root.
double sqrt(double x); double sqrt(double x);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
/// @param x /// @param x
/// @result /// @result
int isinf(double x); int isinf(double x);
// TODO: doxygen comment. // TODO: doxygen comment.
/// @brief /// @brief
/// @param x /// @param x
/// @result /// @result
int isnan(double x); int isnan(double x);
/// @brief Logarithm function in base 10. /// @brief Logarithm function in base 10.
/// @param x Topic of the logarithm function. /// @param x Topic of the logarithm function.
double log10(double x); double log10(double x);
/// @brief Natural logarithm function. /// @brief Natural logarithm function.
/// @param x Topic of the logarithm function. /// @param x Topic of the logarithm function.
double ln(double x); double ln(double x);
/// @brief Logarithm function in base x. /// @brief Logarithm function in base x.
/// @brief x Base of the logarithm. /// @brief x Base of the logarithm.
/// @param y Topic of the logarithm function. /// @param y Topic of the logarithm function.
double logx(double x, double y); double logx(double x, double y);
/// @brief Breaks x into an integral and a fractional part. /// @brief Breaks x into an integral and a fractional part.
/// The integer part is stored in the object pointed by intpart, and the /// The integer part is stored in the object pointed by intpart, and the
/// fractional part is returned by the function. Both parts have the same /// fractional part is returned by the function. Both parts have the same
/// sign as x. /// sign as x.
double modf(double x, double *intpart); double modf(double x, double *intpart);
+26 -26
View File
@@ -1,26 +1,26 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file mutex.h /// @file mutex.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
/// @brief Structure of a mutex. /// @brief Structure of a mutex.
typedef struct mutex_t { typedef struct mutex_t {
/// The state of the mutex. /// The state of the mutex.
uint8_t state; uint8_t state;
/// The owner of the mutex. /// The owner of the mutex.
uint32_t owner; uint32_t owner;
} mutex_t; } mutex_t;
/// @brief Allows to lock a mutex. /// @brief Allows to lock a mutex.
/// @param mutex The mutex to lock. /// @param mutex The mutex to lock.
/// @param owner The one who request the lock. /// @param owner The one who request the lock.
void mutex_lock(mutex_t *mutex, uint32_t owner); void mutex_lock(mutex_t *mutex, uint32_t owner);
/// @brief Unlocks the mutex. /// @brief Unlocks the mutex.
/// @param mutex The mutex to unlock. /// @param mutex The mutex to unlock.
void mutex_unlock(mutex_t *mutex); void mutex_unlock(mutex_t *mutex);
+53 -53
View File
@@ -1,53 +1,53 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file ordered_array.h /// @file ordered_array.h
/// @brief Interface for creating, inserting and deleting from ordered arrays. /// @brief Interface for creating, inserting and deleting from ordered arrays.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
/// @brief This array is insertion sorted - it always remains in a sorted /// @brief This array is insertion sorted - it always remains in a sorted
/// state (between calls). It can store anything that can be cast to a /// state (between calls). It can store anything that can be cast to a
/// void* -- so a uint32_t, or any pointer. /// void* -- so a uint32_t, or any pointer.
typedef void *array_type_t; typedef void *array_type_t;
/// @brief A predicate should return nonzero if the first argument is less /// @brief A predicate should return nonzero if the first argument is less
/// than the second. Else it should return zero. /// than the second. Else it should return zero.
typedef int8_t (*lessthan_predicate_t)(array_type_t, array_type_t); typedef int8_t (*lessthan_predicate_t)(array_type_t, array_type_t);
/// @brief Structure which holds information concerning an ordered array. /// @brief Structure which holds information concerning an ordered array.
typedef struct ordered_array_t { typedef struct ordered_array_t {
/// Pointer to the array. /// Pointer to the array.
array_type_t *array; array_type_t *array;
/// The size of the array. /// The size of the array.
uint32_t size; uint32_t size;
/// The maximum size of the array. /// The maximum size of the array.
uint32_t max_size; uint32_t max_size;
/// Ordering fucntion. /// Ordering fucntion.
lessthan_predicate_t less_than; lessthan_predicate_t less_than;
} ordered_array_t; } ordered_array_t;
/// @brief A standard less than predicate. /// @brief A standard less than predicate.
int8_t standard_lessthan_predicate(array_type_t a, array_type_t b); int8_t standard_lessthan_predicate(array_type_t a, array_type_t b);
/// @brief Create an ordered array. /// @brief Create an ordered array.
ordered_array_t create_ordered_array(uint32_t max_size, ordered_array_t create_ordered_array(uint32_t max_size,
lessthan_predicate_t less_than); lessthan_predicate_t less_than);
/// @brief Set the ordered array. /// @brief Set the ordered array.
ordered_array_t place_ordered_array(void *addr, uint32_t max_size, ordered_array_t place_ordered_array(void *addr, uint32_t max_size,
lessthan_predicate_t less_than); lessthan_predicate_t less_than);
/// @brief Destroy an ordered array. /// @brief Destroy an ordered array.
void destroy_ordered_array(ordered_array_t *array); void destroy_ordered_array(ordered_array_t *array);
/// @brief Add an item into the array. /// @brief Add an item into the array.
void insert_ordered_array(array_type_t item, ordered_array_t *array); void insert_ordered_array(array_type_t item, ordered_array_t *array);
/// @brief Lookup the item at index i. /// @brief Lookup the item at index i.
array_type_t lookup_ordered_array(uint32_t i, ordered_array_t *array); array_type_t lookup_ordered_array(uint32_t i, ordered_array_t *array);
/// @brief Deletes the item at location i from the array. /// @brief Deletes the item at location i from the array.
void remove_ordered_array(uint32_t i, ordered_array_t *array); void remove_ordered_array(uint32_t i, ordered_array_t *array);
+76 -78
View File
@@ -1,78 +1,76 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file queue.h /// @file queue.h
/// @brief Implementation of queue data structure. /// @brief Implementation of queue data structure.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stddef.h" #include "stddef.h"
#include "stdbool.h" #include "stdbool.h"
/// @brief A node of the queue. /// @brief A node of the queue.
typedef struct queue_node_t typedef struct queue_node_t {
{ /// The wrapped data.
/// The wrapped data. void *data;
void *data; /// The next node of the queue.
/// The next node of the queue. struct queue_node_t *next;
struct queue_node_t *next; } queue_node_t;
} queue_node_t;
/// @brief The queue.
/// @brief The queue. typedef struct queue_t {
typedef struct queue_t /// The front of the queue.
{ queue_node_t *front;
/// The front of the queue. /// The back of the queue.
queue_node_t *front; queue_node_t *back;
/// The back of the queue. /// The size of the data contained inside the queue.
queue_node_t *back; size_t data_size;
/// The size of the data contained inside the queue. } * queue_t;
size_t data_size;
} *queue_t; /// @brief Creates a queue.
/// @param data_size The size of the stored elements.
/// @brief Creates a queue. /// @return The created queue.
/// @param data_size The size of the stored elements. queue_t queue_create(size_t data_size);
/// @return The created queue.
queue_t queue_create(size_t data_size); /// @brief Destroys the queue.
/// @param queue The queue to be destroyed.
/// @brief Destroys the queue. /// @return If the queue is destroyed.
/// @param queue The queue to be destroyed. bool_t queue_destroy(queue_t queue);
/// @return If the queue is destroyed.
bool_t queue_destroy(queue_t queue); /// @brief Returns if the queue is empty.
/// @param queue The queue.
/// @brief Returns if the queue is empty. bool_t queue_is_empty(queue_t queue);
/// @param queue The queue.
bool_t queue_is_empty(queue_t queue); /// @brief Allows to add data to the queue.
/// @param queue The queue.
/// @brief Allows to add data to the queue. /// @param data The data to add.
/// @param queue The queue. /// @return If the data has been pushed inside the queue.
/// @param data The data to add. bool_t queue_enqueue(queue_t queue, void *data);
/// @return If the data has been pushed inside the queue.
bool_t queue_enqueue(queue_t queue, void *data); /// @brief Removes the first element of the queue.
/// @param queue The queue.
/// @brief Removes the first element of the queue. /// @return If the data has been removed.
/// @param queue The queue. bool_t queue_dequeue(queue_t queue);
/// @return If the data has been removed.
bool_t queue_dequeue(queue_t queue); /// @brief Returns the first element of the queue.
/// @param queue The queue.
/// @brief Returns the first element of the queue. /// @param data The data.
/// @param queue The queue. /// @return If the data has been correctly retrieved.
/// @param data The data. bool_t queue_front(queue_t queue, void *data);
/// @return If the data has been correctly retrieved.
bool_t queue_front(queue_t queue, void *data); /// @brief Returns the last element of the queue.
/// @param queue The queue.
/// @brief Returns the last element of the queue. /// @param data The data.
/// @param queue The queue. /// @return If the data has been correctly retrieved.
/// @param data The data. bool_t queue_back(queue_t queue, void *data);
/// @return If the data has been correctly retrieved.
bool_t queue_back(queue_t queue, void *data); /// @brief Returns the first element of the queue and removes it.
/// @param queue The queue.
/// @brief Returns the first element of the queue and removes it. /// @param data The data.
/// @param queue The queue. /// @return If the data has been correctly retrieved.
/// @param data The data. bool_t queue_front_and_dequeue(queue_t queue, void *data);
/// @return If the data has been correctly retrieved.
bool_t queue_front_and_dequeue(queue_t queue, void *data); /// @brief Deletes all the elements inside the queue.
/// @param queue The queue.
/// @brief Deletes all the elements inside the queue. /// @return If the queue has been cleared.
/// @param queue The queue. bool_t queue_clear(queue_t queue);
/// @return If the queue has been cleared.
bool_t queue_clear(queue_t queue);
+134 -134
View File
@@ -1,134 +1,134 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file rbtree.h /// @file rbtree.h
/// @brief Implementation of red black tree data structure. /// @brief Implementation of red black tree data structure.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stddef.h" #include "stddef.h"
#ifndef RBTREE_ITER_MAX_HEIGHT #ifndef RBTREE_ITER_MAX_HEIGHT
/// Tallest allowable tree to iterate. /// Tallest allowable tree to iterate.
#define RBTREE_ITER_MAX_HEIGHT 64 #define RBTREE_ITER_MAX_HEIGHT 64
#endif #endif
//============================================================================== //==============================================================================
// Opaque types. // Opaque types.
// TODO: doxygen comment. // TODO: doxygen comment.
typedef struct rbtree_t rbtree_t; typedef struct rbtree_t rbtree_t;
// TODO: doxygen comment. // TODO: doxygen comment.
typedef struct rbtree_node_t rbtree_node_t; typedef struct rbtree_node_t rbtree_node_t;
// TODO: doxygen comment. // TODO: doxygen comment.
typedef struct rbtree_iter_t rbtree_iter_t; typedef struct rbtree_iter_t rbtree_iter_t;
//============================================================================== //==============================================================================
// Comparison functions. // Comparison functions.
// TODO: doxygen comment. // TODO: doxygen comment.
typedef int (*rbtree_tree_cmp_f)(rbtree_t *self, rbtree_node_t *a, void *arg); typedef int (*rbtree_tree_cmp_f)(rbtree_t *self, rbtree_node_t *a, void *arg);
// TODO: doxygen comment. // TODO: doxygen comment.
typedef int (*rbtree_tree_node_cmp_f)(rbtree_t *self, rbtree_node_t *a, typedef int (*rbtree_tree_node_cmp_f)(rbtree_t *self, rbtree_node_t *a,
rbtree_node_t *b); rbtree_node_t *b);
// TODO: doxygen comment. // TODO: doxygen comment.
typedef void (*rbtree_tree_node_f)(rbtree_t *self, rbtree_node_t *node); typedef void (*rbtree_tree_node_f)(rbtree_t *self, rbtree_node_t *node);
//============================================================================== //==============================================================================
// Node management functions. // Node management functions.
// TODO: doxygen comment. // TODO: doxygen comment.
rbtree_node_t *rbtree_node_alloc(); rbtree_node_t *rbtree_node_alloc();
// TODO: doxygen comment. // TODO: doxygen comment.
rbtree_node_t *rbtree_node_create(void *value); rbtree_node_t *rbtree_node_create(void *value);
// TODO: doxygen comment. // TODO: doxygen comment.
rbtree_node_t *rbtree_node_init(rbtree_node_t *self, void *value); rbtree_node_t *rbtree_node_init(rbtree_node_t *self, void *value);
// TODO: doxygen comment. // TODO: doxygen comment.
void *rbtree_node_get_value(rbtree_node_t *self); void *rbtree_node_get_value(rbtree_node_t *self);
// TODO: doxygen comment. // TODO: doxygen comment.
void rbtree_node_dealloc(rbtree_node_t *self); void rbtree_node_dealloc(rbtree_node_t *self);
//============================================================================== //==============================================================================
// Tree management functions. // Tree management functions.
// TODO: doxygen comment. // TODO: doxygen comment.
rbtree_t *rbtree_tree_alloc(); rbtree_t *rbtree_tree_alloc();
// TODO: doxygen comment. // TODO: doxygen comment.
rbtree_t *rbtree_tree_create(rbtree_tree_node_cmp_f cmp); rbtree_t *rbtree_tree_create(rbtree_tree_node_cmp_f cmp);
// TODO: doxygen comment. // TODO: doxygen comment.
rbtree_t *rbtree_tree_init(rbtree_t *self, rbtree_tree_node_cmp_f cmp); rbtree_t *rbtree_tree_init(rbtree_t *self, rbtree_tree_node_cmp_f cmp);
// TODO: doxygen comment. // TODO: doxygen comment.
void rbtree_tree_dealloc(rbtree_t *self, rbtree_tree_node_f node_cb); void rbtree_tree_dealloc(rbtree_t *self, rbtree_tree_node_f node_cb);
// TODO: doxygen comment. // TODO: doxygen comment.
void *rbtree_tree_find(rbtree_t *self, void *value); void *rbtree_tree_find(rbtree_t *self, void *value);
// TODO: doxygen comment. // TODO: doxygen comment.
void *rbtree_tree_find_by_value(rbtree_t *self, rbtree_tree_cmp_f cmp_fun, void *rbtree_tree_find_by_value(rbtree_t *self, rbtree_tree_cmp_f cmp_fun,
void *value); void *value);
// TODO: doxygen comment. // TODO: doxygen comment.
int rbtree_tree_insert(rbtree_t *self, void *value); int rbtree_tree_insert(rbtree_t *self, void *value);
// TODO: doxygen comment. // TODO: doxygen comment.
int rbtree_tree_remove(rbtree_t *self, void *value); int rbtree_tree_remove(rbtree_t *self, void *value);
// TODO: doxygen comment. // TODO: doxygen comment.
size_t rbtree_tree_size(rbtree_t *self); size_t rbtree_tree_size(rbtree_t *self);
// TODO: doxygen comment. // TODO: doxygen comment.
int rbtree_tree_insert_node(rbtree_t *self, rbtree_node_t *node); int rbtree_tree_insert_node(rbtree_t *self, rbtree_node_t *node);
// TODO: doxygen comment. // TODO: doxygen comment.
int rbtree_tree_remove_with_cb(rbtree_t *self, void *value, int rbtree_tree_remove_with_cb(rbtree_t *self, void *value,
rbtree_tree_node_f node_cb); rbtree_tree_node_f node_cb);
//============================================================================== //==============================================================================
// Iterators. // Iterators.
// TODO: doxygen comment. // TODO: doxygen comment.
rbtree_iter_t *rbtree_iter_alloc(); rbtree_iter_t *rbtree_iter_alloc();
// TODO: doxygen comment. // TODO: doxygen comment.
rbtree_iter_t *rbtree_iter_init(rbtree_iter_t *self); rbtree_iter_t *rbtree_iter_init(rbtree_iter_t *self);
// TODO: doxygen comment. // TODO: doxygen comment.
rbtree_iter_t *rbtree_iter_create(); rbtree_iter_t *rbtree_iter_create();
// TODO: doxygen comment. // TODO: doxygen comment.
void rbtree_iter_dealloc(rbtree_iter_t *self); void rbtree_iter_dealloc(rbtree_iter_t *self);
// TODO: doxygen comment. // TODO: doxygen comment.
void *rbtree_iter_first(rbtree_iter_t *self, rbtree_t *tree); void *rbtree_iter_first(rbtree_iter_t *self, rbtree_t *tree);
// TODO: doxygen comment. // TODO: doxygen comment.
void *rbtree_iter_last(rbtree_iter_t *self, rbtree_t *tree); void *rbtree_iter_last(rbtree_iter_t *self, rbtree_t *tree);
// TODO: doxygen comment. // TODO: doxygen comment.
void *rbtree_iter_next(rbtree_iter_t *self); void *rbtree_iter_next(rbtree_iter_t *self);
// TODO: doxygen comment. // TODO: doxygen comment.
void *rbtree_iter_prev(rbtree_iter_t *self); void *rbtree_iter_prev(rbtree_iter_t *self);
//============================================================================== //==============================================================================
// Tree debugging functions. // Tree debugging functions.
// TODO: doxygen comment. // TODO: doxygen comment.
int rbtree_tree_test(rbtree_t *self, rbtree_node_t *root); int rbtree_tree_test(rbtree_t *self, rbtree_node_t *root);
// TODO: doxygen comment. // TODO: doxygen comment.
void rbtree_tree_print(rbtree_t *self, rbtree_tree_node_f fun); void rbtree_tree_print(rbtree_t *self, rbtree_tree_node_f fun);
//============================================================================== //==============================================================================
+32 -32
View File
@@ -1,32 +1,32 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file spinlock.h /// @file spinlock.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "debug.h" #include "debug.h"
#include "stddef.h" #include "stddef.h"
#include "irqflags.h" #include "irqflags.h"
#include "stdatomic.h" #include "stdatomic.h"
#include "scheduler.h" #include "scheduler.h"
#define SPINLOCK_FREE 0 #define SPINLOCK_FREE 0
#define SPINLOCK_BUSY 1 #define SPINLOCK_BUSY 1
/// @brief Spinlock structure. /// @brief Spinlock structure.
typedef atomic_t spinlock_t; typedef atomic_t spinlock_t;
/// @brief Initialize the spinlock. /// @brief Initialize the spinlock.
void spinlock_init(spinlock_t *spinlock); void spinlock_init(spinlock_t *spinlock);
/// @brief Try to lock the spinlock. /// @brief Try to lock the spinlock.
void spinlock_lock(spinlock_t *spinlock); void spinlock_lock(spinlock_t *spinlock);
/// @brief Try to unlock the spinlock. /// @brief Try to unlock the spinlock.
void spinlock_unlock(spinlock_t *spinlock); void spinlock_unlock(spinlock_t *spinlock);
/// @brief Try to unlock the spinlock. /// @brief Try to unlock the spinlock.
bool_t spinlock_trylock(spinlock_t *spinlock); bool_t spinlock_trylock(spinlock_t *spinlock);
+28 -28
View File
@@ -1,28 +1,28 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file stdarg.h /// @file stdarg.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/// @brief The va_list type is an array containing a single element of one /// @brief The va_list type is an array containing a single element of one
/// structure containing the necessary information to implement the /// structure containing the necessary information to implement the
/// va_arg macro. /// va_arg macro.
typedef char *va_list; typedef char *va_list;
/// @brief The type of the item on the stack. /// @brief The type of the item on the stack.
#define va_item int #define va_item int
/// @brief Amount of space required in an argument list (ie. the stack) for an /// @brief Amount of space required in an argument list (ie. the stack) for an
/// argument of type t. /// argument of type t.
#define va_size(t) \ #define va_size(t) \
(((sizeof(t) + sizeof(va_item) - 1) / sizeof(va_item)) * sizeof(va_item)) (((sizeof(t) + sizeof(va_item) - 1) / sizeof(va_item)) * sizeof(va_item))
/// @brief The start of a variadic list. /// @brief The start of a variadic list.
#define va_start(ap, last_arg) (ap = ((va_list)(&last_arg) + va_size(last_arg))) #define va_start(ap, last_arg) (ap = ((va_list)(&last_arg) + va_size(last_arg)))
/// @brief The end of a variadic list. /// @brief The end of a variadic list.
#define va_end(ap) ((void)0) #define va_end(ap) ((void)0)
/// @brief The argument of a variadic list. /// @brief The argument of a variadic list.
#define va_arg(ap, t) (ap += va_size(t), *((t *)(ap - va_size(t)))) #define va_arg(ap, t) (ap += va_size(t), *((t *)(ap - va_size(t))))
+109 -109
View File
@@ -1,109 +1,109 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file stdatomic.h /// @file stdatomic.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
#include "stdbool.h" #include "stdbool.h"
#include "compiler.h" #include "compiler.h"
/// @brief Standard structure for atomic operations. /// @brief Standard structure for atomic operations.
typedef volatile unsigned atomic_t; typedef volatile unsigned atomic_t;
/// @brief At declaration, initialize an atomic_t to i. /// @brief At declaration, initialize an atomic_t to i.
#define ATOMIC_INIT(i) \ #define ATOMIC_INIT(i) \
{ \ { \
(i) \ (i) \
} }
/// @brief The prefix used to lock. /// @brief The prefix used to lock.
#define LOCK_PREFIX "\n\tlock; " #define LOCK_PREFIX "\n\tlock; "
/// @brief Compile read-write barrier. /// @brief Compile read-write barrier.
#define barrier() asm volatile("" : : : "memory") #define barrier() asm volatile("" : : : "memory")
/// @brief Pause instruction to prevent excess processor bus usage. /// @brief Pause instruction to prevent excess processor bus usage.
#define cpu_relax() asm volatile("pause\n" : : : "memory") #define cpu_relax() asm volatile("pause\n" : : : "memory")
// TODO: doxygen comment. // TODO: doxygen comment.
inline static int32_t atomic_set_and_test(atomic_t const *ptr, int32_t i) inline static int32_t atomic_set_and_test(atomic_t const *ptr, int32_t i)
{ {
__asm__ __volatile__("xchgl %0,%1" __asm__ __volatile__("xchgl %0,%1"
: "=r"(i) : "=r"(i)
: "m"(*(volatile unsigned *)ptr), "0"(i) : "m"(*(volatile unsigned *)ptr), "0"(i)
: "memory"); : "memory");
// __asm__ __volatile__("xchgl %0, %1" : "=r"(i) : "m"(ptr), "0"(i) : "memory"); // __asm__ __volatile__("xchgl %0, %1" : "=r"(i) : "m"(ptr), "0"(i) : "memory");
return i; return i;
} }
/// @brief Atomically set ptr equal to i. /// @brief Atomically set ptr equal to i.
inline static void atomic_set(atomic_t *ptr, int32_t i) inline static void atomic_set(atomic_t *ptr, int32_t i)
{ {
atomic_set_and_test(ptr, i); atomic_set_and_test(ptr, i);
} }
/// @brief Atomically read the integer value of ptr. /// @brief Atomically read the integer value of ptr.
inline static int32_t atomic_read(const atomic_t *ptr) inline static int32_t atomic_read(const atomic_t *ptr)
{ {
return READ_ONCE(*ptr); return READ_ONCE(*ptr);
} }
/// @brief Atomically add i to ptr. /// @brief Atomically add i to ptr.
inline static int32_t atomic_add(atomic_t const *ptr, int32_t i) inline static int32_t atomic_add(atomic_t const *ptr, int32_t i)
{ {
int result = i; int result = i;
asm volatile(LOCK_PREFIX "xaddl %0, %1" asm volatile(LOCK_PREFIX "xaddl %0, %1"
: "=r"(i) : "=r"(i)
: "m"(ptr), "0"(i) : "m"(ptr), "0"(i)
: "memory", "cc"); : "memory", "cc");
return result + i; return result + i;
} }
/// @brief Atomically subtract i from ptr. /// @brief Atomically subtract i from ptr.
inline static int32_t atomic_sub(atomic_t *ptr, int32_t i) inline static int32_t atomic_sub(atomic_t *ptr, int32_t i)
{ {
return atomic_add(ptr, -i); return atomic_add(ptr, -i);
} }
/// @brief Atomically add one to ptr. /// @brief Atomically add one to ptr.
inline static int32_t atomic_inc(atomic_t *ptr) inline static int32_t atomic_inc(atomic_t *ptr)
{ {
return atomic_add(ptr, 1); return atomic_add(ptr, 1);
} }
/// @brief Atomically subtract one from ptr. /// @brief Atomically subtract one from ptr.
inline static int32_t atomic_dec(atomic_t *ptr) inline static int32_t atomic_dec(atomic_t *ptr)
{ {
return atomic_add(ptr, -1); return atomic_add(ptr, -1);
} }
/// @brief Atomically add i to ptr and return true if the result is negative; /// @brief Atomically add i to ptr and return true if the result is negative;
/// otherwise false. /// otherwise false.
inline static bool_t atomic_add_negative(atomic_t *ptr, int32_t i) inline static bool_t atomic_add_negative(atomic_t *ptr, int32_t i)
{ {
return (bool_t)(atomic_add(ptr, i) < 0); return (bool_t)(atomic_add(ptr, i) < 0);
} }
/// @brief Atomically subtract i from ptr and return true if the result is /// @brief Atomically subtract i from ptr and return true if the result is
/// zero; otherwise false. /// zero; otherwise false.
inline static bool_t atomic_sub_and_test(atomic_t *ptr, int32_t i) inline static bool_t atomic_sub_and_test(atomic_t *ptr, int32_t i)
{ {
return (bool_t)(atomic_sub(ptr, i) == 0); return (bool_t)(atomic_sub(ptr, i) == 0);
} }
/// @brief Atomically increment ptr by one and return true if the result is /// @brief Atomically increment ptr by one and return true if the result is
/// zero; false otherwise. /// zero; false otherwise.
inline static int32_t atomic_inc_and_test(atomic_t *ptr) inline static int32_t atomic_inc_and_test(atomic_t *ptr)
{ {
return (bool_t)(atomic_inc(ptr) == 0); return (bool_t)(atomic_inc(ptr) == 0);
} }
/// @brief Atomically decrement ptr by one and return true if zero; false /// @brief Atomically decrement ptr by one and return true if zero; false
/// otherwise. /// otherwise.
inline static int32_t atomic_dec_and_test(atomic_t *ptr) inline static int32_t atomic_dec_and_test(atomic_t *ptr)
{ {
return (bool_t)(atomic_dec(ptr) == 0); return (bool_t)(atomic_dec(ptr) == 0);
} }
+16 -16
View File
@@ -1,16 +1,16 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file stdbool.h /// @file stdbool.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/// @brief Define boolean value. /// @brief Define boolean value.
typedef enum bool_t typedef enum bool_t
{ {
/// [0] False. /// [0] False.
false, false,
/// [1] True. /// [1] True.
true true
} __attribute__ ((__packed__)) bool_t; } __attribute__ ((__packed__)) bool_t;
+87 -87
View File
@@ -1,87 +1,87 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file stddef.h /// @file stddef.h
/// @brief Define basic data types. /// @brief Define basic data types.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#ifndef NULL #ifndef NULL
/// @brief Define NULL. /// @brief Define NULL.
#define NULL ((void*)0) #define NULL ((void *)0)
#endif #endif
#ifndef EOF #ifndef EOF
/// @brief Define End-Of-File. /// @brief Define End-Of-File.
#define EOF (-1) #define EOF (-1)
#endif #endif
/// @brief Define the size of a buffer. /// @brief Define the size of a buffer.
#define BUFSIZ 512 #define BUFSIZ 512
/// @brief Define the size of the kernel. /// @brief Define the size of the kernel.
#define KERNEL_SIZE 0x200 #define KERNEL_SIZE 0x200
#ifndef TRUE #ifndef TRUE
/// @brief Define the value of true. /// @brief Define the value of true.
#define TRUE 1 #define TRUE 1
#endif #endif
#ifndef FALSE #ifndef FALSE
/// @brief Define the value of false. /// @brief Define the value of false.
#define FALSE 0 #define FALSE 0
#endif #endif
/// @brief Define the byte type. /// @brief Define the byte type.
typedef unsigned char byte_t; typedef unsigned char byte_t;
/// @brief Define the generic size type. /// @brief Define the generic size type.
typedef unsigned long size_t; typedef unsigned long size_t;
/// @brief Define the generic signed size type. /// @brief Define the generic signed size type.
typedef long ssize_t; typedef long ssize_t;
/// @brief Define the type of an inode. /// @brief Define the type of an inode.
typedef unsigned int ino_t; typedef unsigned int ino_t;
// TODO: doxygen comment. // TODO: doxygen comment.
typedef unsigned int dev_t; typedef unsigned int dev_t;
/// @brief The type of user-id. /// @brief The type of user-id.
typedef unsigned int uid_t; typedef unsigned int uid_t;
/// @brief The type of group-id. /// @brief The type of group-id.
typedef unsigned int gid_t; typedef unsigned int gid_t;
/// @brief The type of offset. /// @brief The type of offset.
typedef unsigned int off_t; typedef unsigned int off_t;
/// @brief The type of mode. /// @brief The type of mode.
typedef unsigned int mode_t; typedef unsigned int mode_t;
// TODO: doxygen comment. // TODO: doxygen comment.
typedef mode_t pgprot_t; typedef mode_t pgprot_t;
// TODO: doxygen comment. // TODO: doxygen comment.
typedef unsigned long int ulong; typedef unsigned long int ulong;
// TODO: doxygen comment. // TODO: doxygen comment.
typedef unsigned short int ushort; typedef unsigned short int ushort;
// TODO: doxygen comment. // TODO: doxygen comment.
typedef unsigned int uint; typedef unsigned int uint;
// TODO: doxygen comment. // TODO: doxygen comment.
typedef int key_t; typedef int key_t;
// TODO: doxygen comment. // TODO: doxygen comment.
// Check with clock.h // Check with clock.h
typedef long __time_t; typedef long __time_t;
+37 -37
View File
@@ -1,37 +1,37 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file stdint.h /// @file stdint.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/// @brief Define the signed 64-bit integer. /// @brief Define the signed 64-bit integer.
typedef int int64_t; typedef int int64_t;
/// @brief Define the unsigned 64-bit integer. /// @brief Define the unsigned 64-bit integer.
typedef unsigned int uint64_t; typedef unsigned int uint64_t;
/// @brief Define the signed 32-bit integer. /// @brief Define the signed 32-bit integer.
typedef int int32_t; typedef int int32_t;
/// @brief Define the unsigned 32-bit integer. /// @brief Define the unsigned 32-bit integer.
typedef unsigned int uint32_t; typedef unsigned int uint32_t;
/// @brief Define the signed 16-bit integer. /// @brief Define the signed 16-bit integer.
typedef short int16_t; typedef short int16_t;
/// @brief Define the unsigned 16-bit integer. /// @brief Define the unsigned 16-bit integer.
typedef unsigned short uint16_t; typedef unsigned short uint16_t;
/// @brief Define the signed 8-bit integer. /// @brief Define the signed 8-bit integer.
typedef char int8_t; typedef char int8_t;
/// @brief Define the unsigned 8-bit integer. /// @brief Define the unsigned 8-bit integer.
typedef unsigned char uint8_t; typedef unsigned char uint8_t;
/// @brief Define the signed 32-bit pointer. /// @brief Define the signed 32-bit pointer.
typedef signed intptr_t; typedef signed intptr_t;
/// @brief Define the unsigned 32-bit pointer. /// @brief Define the unsigned 32-bit pointer.
typedef unsigned uintptr_t; typedef unsigned uintptr_t;
+50 -48
View File
@@ -1,48 +1,50 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file stdio.h /// @file stdio.h
/// @brief Standard I/0 functions. /// @brief Standard I/0 functions.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdarg.h" #include "stdarg.h"
#include "stddef.h" #include "stddef.h"
/// @brief The maximum number of digits of an integer. /// @brief The maximum number of digits of an integer.
#define MAX_DIGITS_IN_INTEGER 11 #define MAX_DIGITS_IN_INTEGER 11
/// @brief The size of 'gets' buffer.
#ifndef EOF #define GETS_BUFFERSIZE 255
/// @brief Define the End-Of-File.
#define EOF (-1) #ifndef EOF
#endif /// @brief Define the End-Of-File.
#define EOF (-1)
/// @brief Writes the given character to the standard output (stdout). #endif
void putchar(int character);
/// @brief Writes the given character to the standard output (stdout).
/// @brief Writes the string pointed by str to the standard output (stdout) void putchar(int character);
/// and appends a newline character ('\n').
void puts(char *str); /// @brief Writes the string pointed by str to the standard output (stdout)
/// and appends a newline character ('\n').
/// @brief Returns the next character from the standard input (stdin). void puts(char *str);
int getchar(void);
/// @brief Returns the next character from the standard input (stdin).
/// @brief Reads characters from the standard input (stdin) and stores them int getchar(void);
/// as a C string into str until a newline character or the end-of-file is
/// reached. /// @brief Reads characters from the standard input (stdin) and stores them
char *gets(char *str); /// as a C string into str until a newline character or the end-of-file is
/// reached.
/// @brief Convert the given string to an integer. char *gets(char *str);
int atoi(const char *str);
/// @brief Convert the given string to an integer.
/// @brief Write formatted output to stdout. int atoi(const char *str);
int printf(const char *, ...);
/// @brief Write formatted output to stdout.
/// @brief Read formatted input from stdin. int printf(const char *, ...);
size_t scanf(const char *, ...);
/// @brief Read formatted input from stdin.
/// @brief Write formatted output to the string str from argument list ARG. size_t scanf(const char *, ...);
int vsprintf(char *str, const char *fmt, va_list args);
/// @brief Write formatted output to the string str from argument list ARG.
/// @brief Write formatted output to the string str. int vsprintf(char *str, const char *fmt, va_list args);
int sprintf(char *str, const char *fmt, ...);
/// @brief Write formatted output to the string str.
int sprintf(char *str, const char *fmt, ...);
+36 -39
View File
@@ -1,39 +1,36 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file stdlib.h /// @file stdlib.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stddef.h" #include "stddef.h"
/// @brief Malloc based on the number of elements. /// @brief Malloc based on the number of elements.
void *calloc(size_t element_number, size_t element_size); void *calloc(size_t element_number, size_t element_size);
/// @brief Allows to set the seed of the random value generator. void *malloc(unsigned int size);
void srand(int x);
void free(void * p);
void *malloc(unsigned int size);
/// @brief Allocate a matrix with n rows of a specific size.
void free(void * p); /// @param n Number of matrix rows.
/// @param size Size of each matrix row.
/// @return Matrix pointer.
#ifndef MS_RAND void **mmalloc(size_t n, size_t size);
/// @brief The maximum value of the random. /// @brief Free a matrix of n rows.
#define RAND_MAX ((1U << 31) - 1) /// @param src Matrix to free.
/// @param n Number of matrix rows.
/// @brief Generates a random value. void mfree(void **src, size_t n);
int rand();
/// The maximum value returned by the rand function.
// MS rand #define RAND_MAX ((1U << 31U) - 1U)
#else
/// @brief Allows to set the seed of the random value generator.
#define RAND_MAX_32 ((1U << 31) - 1) void srand(int x);
#define RAND_MAX ((1U << 15) - 1) /// @brief Generates a random value.
int rand();
int rand();
#endif
+12 -12
View File
@@ -1,12 +1,12 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file strerror.h /// @file strerror.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "errno.h" #include "errno.h"
// TODO: doxygen comment. // TODO: doxygen comment.
char *strerror(int errnum); char *strerror(int errnum);
+159 -159
View File
@@ -1,159 +1,159 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file string.h /// @file string.h
/// @brief String routines. /// @brief String routines.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "list.h" #include "list.h"
#include "stddef.h" #include "stddef.h"
/// @brief Copies the first num characters of source to destination. /// @brief Copies the first num characters of source to destination.
char *strncpy(char *destination, const char *source, size_t num); char *strncpy(char *destination, const char *source, size_t num);
/// @brief Compares up to n characters of s1 to those of s2. /// @brief Compares up to n characters of s1 to those of s2.
int strncmp(const char *s1, const char *s2, size_t n); int strncmp(const char *s1, const char *s2, size_t n);
/// @brief Case insensitive string compare. /// @brief Case insensitive string compare.
int stricmp(const char *s1, const char *s2); int stricmp(const char *s1, const char *s2);
/// @brief Case-insensitively compare up to n characters of s1 to those of s2. /// @brief Case-insensitively compare up to n characters of s1 to those of s2.
int strnicmp(const char *s1, const char *s2, size_t n); int strnicmp(const char *s1, const char *s2, size_t n);
/// @brief Returns a pointer to the first occurrence of ch in str. /// @brief Returns a pointer to the first occurrence of ch in str.
char *strchr(const char *s, int ch); char *strchr(const char *s, int ch);
/// @brief Returns a pointer to the last occurrence of ch in str. /// @brief Returns a pointer to the last occurrence of ch in str.
char *strrchr(const char *s, int ch); char *strrchr(const char *s, int ch);
/// @brief Returns a pointer to the first occurrence of s2 in s1, or NULL if /// @brief Returns a pointer to the first occurrence of s2 in s1, or NULL if
/// s2 is not part of s1. /// s2 is not part of s1.
char *strstr(const char *s1, const char *s2); char *strstr(const char *s1, const char *s2);
/// @brief Returns the length of the initial portion of string which consists /// @brief Returns the length of the initial portion of string which consists
/// only of characters that are part of control. /// only of characters that are part of control.
size_t strspn(const char *string, const char *control); size_t strspn(const char *string, const char *control);
/// @brief Calculates the length of the initial segment of string which /// @brief Calculates the length of the initial segment of string which
/// consists entirely of characters not in control. /// consists entirely of characters not in control.
size_t strcspn(const char *string, const char *control); size_t strcspn(const char *string, const char *control);
/// @brief Finds the first character in the string string that matches any /// @brief Finds the first character in the string string that matches any
/// character specified in control. /// character specified in control.
char *strpbrk(const char *string, const char *control); char *strpbrk(const char *string, const char *control);
/// @brief Make a copy of the given string. /// @brief Make a copy of the given string.
char *strdup(const char *s); char *strdup(const char *s);
/// @brief Make a copy of the given string. /// @brief Make a copy of the given string.
char *kstrdup(const char *s); char *kstrdup(const char *s);
/// @brief Appends the string pointed to, by s2 to the end of the string /// @brief Appends the string pointed to, by s2 to the end of the string
/// pointed to, by s1 up to n characters long. /// pointed to, by s1 up to n characters long.
char *strncat(char *s1, const char *s2, size_t n); char *strncat(char *s1, const char *s2, size_t n);
/// @brief Fill the string s with the character c, to the given length n. /// @brief Fill the string s with the character c, to the given length n.
char *strnset(char *s, int c, size_t n); char *strnset(char *s, int c, size_t n);
/// @brief Fill the string s with the character c. /// @brief Fill the string s with the character c.
char *strset(char *s, int c); char *strset(char *s, int c);
/// @brief Reverse the string s. /// @brief Reverse the string s.
char *strrev(char *s); char *strrev(char *s);
// TODO: Check behaviour & doxygen comment. // TODO: Check behaviour & doxygen comment.
char *strtok(char *str, const char *delim); char *strtok(char *str, const char *delim);
// TODO: Check behaviour & doxygen comment. // TODO: Check behaviour & doxygen comment.
char *strtok_r(char *string, const char *control, char **lasts); char *strtok_r(char *string, const char *control, char **lasts);
/// @brief Another function to copy n characters from str2 to str1. /// @brief Another function to copy n characters from str2 to str1.
void *memmove(void *dst, const void *src, size_t n); void *memmove(void *dst, const void *src, size_t n);
/// @brief Searches for the first occurrence of the character c (an unsigned /// @brief Searches for the first occurrence of the character c (an unsigned
/// char) in the first n bytes of the string pointed to, by the /// char) in the first n bytes of the string pointed to, by the
/// argument str. /// argument str.
void *memchr(const void *str, int c, size_t n); void *memchr(const void *str, int c, size_t n);
char *strlwr(char *s); char *strlwr(char *s);
char *strupr(char *s); char *strupr(char *s);
/// @brief Copies the first n bytes from memory area src to memory area dest, /// @brief Copies the first n bytes from memory area src to memory area dest,
/// stopping when the character c is found. /// stopping when the character c is found.
void *memccpy(void *dst, const void *src, int c, size_t n); void *memccpy(void *dst, const void *src, int c, size_t n);
/// @brief Copy a block of memory, handling overlap. /// @brief Copy a block of memory, handling overlap.
/// @param _dst Pointer to the destination. /// @param _dst Pointer to the destination.
/// @param _src Pointer to the source. /// @param _src Pointer to the source.
/// @param num Number of bytes to be copied. /// @param num Number of bytes to be copied.
/// @return Pointer to the destination. /// @return Pointer to the destination.
void *memcpy(void *_dst, const void *_src, size_t num); void *memcpy(void *_dst, const void *_src, size_t num);
/// @brief Compares the first n bytes of str1 and str2. /// @brief Compares the first n bytes of str1 and str2.
int memcmp(const void *str1, const void *str2, size_t n); int memcmp(const void *str1, const void *str2, size_t n);
/// @brief Sets the first num bytes of the block of memory pointed by ptr /// @brief Sets the first num bytes of the block of memory pointed by ptr
/// to the specified value. /// to the specified value.
/// @param ptr Pointer to the block of memory to set. /// @param ptr Pointer to the block of memory to set.
/// @param value Value to be set. /// @param value Value to be set.
/// @param num Number of bytes to be set to the given value. /// @param num Number of bytes to be set to the given value.
/// @return The same ptr. /// @return The same ptr.
void *memset(void *ptr, int value, size_t num); void *memset(void *ptr, int value, size_t num);
/// @brief Copy the string src into the array dst. /// @brief Copy the string src into the array dst.
char *strcpy(char *dst, const char *src); char *strcpy(char *dst, const char *src);
/// @brief Appends a copy of the string src to the string dst. /// @brief Appends a copy of the string src to the string dst.
char *strcat(char *dst, const char *src); char *strcat(char *dst, const char *src);
/// @brief Checks if the two strings are equal. /// @brief Checks if the two strings are equal.
int strcmp(const char *s1, const char *s2); int strcmp(const char *s1, const char *s2);
/// @brief Returns the lenght of the string s. /// @brief Returns the lenght of the string s.
size_t strlen(const char *s); size_t strlen(const char *s);
/// @brief Returns the number of characters inside s, excluding the /// @brief Returns the number of characters inside s, excluding the
/// terminating null byte ('\0'), but at most count. /// terminating null byte ('\0'), but at most count.
size_t strnlen(const char *s, size_t count); size_t strnlen(const char *s, size_t count);
/// @brief Separate a string in token according to the delimiter. /// @brief Separate a string in token according to the delimiter.
/// If str is NULL, the scanning will continue for the previous string. /// If str is NULL, the scanning will continue for the previous string.
/// It can be bettered. /// It can be bettered.
char *strtok(char *str, const char *delim); char *strtok(char *str, const char *delim);
/// @brief Compare num characters of s2 and s1. /// @brief Compare num characters of s2 and s1.
int _kstrncmp(const char *s1, const char *s2, size_t num); int _kstrncmp(const char *s1, const char *s2, size_t num);
/// @brief Removes the whitespaces in from of str. /// @brief Removes the whitespaces in from of str.
char *trim(char *str); char *trim(char *str);
/// @brief Create a copy of str. /// @brief Create a copy of str.
char *strdup(const char *src); char *strdup(const char *src);
/// @brief Separate stringp based on delim. /// @brief Separate stringp based on delim.
char *strsep(char **stringp, const char *delim); char *strsep(char **stringp, const char *delim);
/// @brief Split a string into list of strings. /// @brief Split a string into list of strings.
list_t *str_split(const char *str, const char *delim, unsigned int *num); list_t *str_split(const char *str, const char *delim, unsigned int *num);
/// @brief Reconstruct a string from list using delim as delimiter. /// @brief Reconstruct a string from list using delim as delimiter.
char *list2str(list_t *list, const char *delim); char *list2str(list_t *list, const char *delim);
/// @brief Move the number "num" into a string. /// @brief Move the number "num" into a string.
/// @param buffer The string containing the number. /// @param buffer The string containing the number.
/// @param num The number to convert. /// @param num The number to convert.
/// @param base The base used to convert. /// @param base The base used to convert.
void int_to_str(char *buffer, unsigned int num, unsigned int base); void int_to_str(char *buffer, unsigned int num, unsigned int base);
/// @brief Transforms num into a string. /// @brief Transforms num into a string.
void _knntos(char *buffer, int num, int base); void _knntos(char *buffer, int num, int base);
/// @brief Replaces the occurences of find with replace inside str. /// @brief Replaces the occurences of find with replace inside str.
char *replace_char(char *str, char find, char replace); char *replace_char(char *str, char find, char replace);
/// @brief Converts a file mode (the type and permission information associated /// @brief Converts a file mode (the type and permission information associated
/// with an inode) into a symbolic string which is stored in the location /// with an inode) into a symbolic string which is stored in the location
/// referenced by p. /// referenced by p.
void strmode(mode_t mode, char *p); void strmode(mode_t mode, char *p);
+77 -77
View File
@@ -1,77 +1,77 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file tree.h /// @file tree.h
/// @brief General-purpose tree implementation. /// @brief General-purpose tree implementation.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "list.h" #include "list.h"
/// @brief A node of the tree. /// @brief A node of the tree.
typedef struct tree_node_t { typedef struct tree_node_t {
/// The value stored by the node. /// The value stored by the node.
void *value; void *value;
/// Pointer to the list of childrens. /// Pointer to the list of childrens.
list_t *children; list_t *children;
/// Pointer to the parent. /// Pointer to the parent.
struct tree_node_t *parent; struct tree_node_t *parent;
} tree_node_t; } tree_node_t;
/// @brief Represents the tree. /// @brief Represents the tree.
typedef struct tree_t { typedef struct tree_t {
/// Number of nodes inside the tree. /// Number of nodes inside the tree.
size_t nodes; size_t nodes;
/// Pointer to the root of the tree. /// Pointer to the root of the tree.
tree_node_t *root; tree_node_t *root;
} tree_t; } tree_t;
typedef uint8_t (*tree_comparator_t)(void *, void *); typedef uint8_t (*tree_comparator_t)(void *, void *);
/// @brief Creates a new tree. /// @brief Creates a new tree.
tree_t *tree_create(); tree_t *tree_create();
/// @brief Sets the root node for a new tree. /// @brief Sets the root node for a new tree.
tree_node_t *tree_set_root(tree_t *tree, void *value); tree_node_t *tree_set_root(tree_t *tree, void *value);
/// @brief Free the contents of a node and its children, /// @brief Free the contents of a node and its children,
/// but not the nodes themselves. /// but not the nodes themselves.
void tree_node_destroy(tree_node_t *node); void tree_node_destroy(tree_node_t *node);
/// @brief Free the contents of a tree, but not the nodes. /// @brief Free the contents of a tree, but not the nodes.
void tree_destroy(tree_t *tree); void tree_destroy(tree_t *tree);
/// @brief Free all of the nodes in a tree, but not their contents. /// @brief Free all of the nodes in a tree, but not their contents.
void tree_free(tree_t *tree); void tree_free(tree_t *tree);
/// @brief Create a new tree node pointing to the given value. /// @brief Create a new tree node pointing to the given value.
tree_node_t *tree_node_create(void *value); tree_node_t *tree_node_create(void *value);
/// @brief Insert a node as a child of parent. /// @brief Insert a node as a child of parent.
void tree_node_insert_child_node(tree_t *tree, tree_node_t *parent, void tree_node_insert_child_node(tree_t *tree, tree_node_t *parent,
tree_node_t *node); tree_node_t *node);
/// @brief Insert a (fresh) node as a child of parent. /// @brief Insert a (fresh) node as a child of parent.
tree_node_t *tree_node_insert_child(tree_t *tree, tree_node_t *parent, tree_node_t *tree_node_insert_child(tree_t *tree, tree_node_t *parent,
void *value); void *value);
/// @brief Recursive node part of tree_find_parent. /// @brief Recursive node part of tree_find_parent.
tree_node_t *tree_node_find_parent(tree_node_t *haystack, tree_node_t *needle); tree_node_t *tree_node_find_parent(tree_node_t *haystack, tree_node_t *needle);
/// @brief Remove a node when we know its parent; update node counts for the /// @brief Remove a node when we know its parent; update node counts for the
/// tree. /// tree.
void tree_node_parent_remove(tree_t *tree, tree_node_t *parent, void tree_node_parent_remove(tree_t *tree, tree_node_t *parent,
tree_node_t *node); tree_node_t *node);
/// @brief Remove an entire branch given its root. /// @brief Remove an entire branch given its root.
void tree_node_remove(tree_t *tree, tree_node_t *node); void tree_node_remove(tree_t *tree, tree_node_t *node);
/// @brief Remove this node and move its children into its parent's /// @brief Remove this node and move its children into its parent's
/// list of children. /// list of children.
void tree_remove(tree_t *tree, tree_node_t *node); void tree_remove(tree_t *tree, tree_node_t *node);
// TODO: doxygen comment. // TODO: doxygen comment.
void tree_break_off(tree_t *tree, tree_node_t *node); void tree_break_off(tree_t *tree, tree_node_t *node);
/// @brief Searches the given value inside the tree. /// @brief Searches the given value inside the tree.
tree_node_t *tree_find(tree_t *tree, void *value, tree_comparator_t comparator); tree_node_t *tree_find(tree_t *tree, void *value, tree_comparator_t comparator);
+25 -25
View File
@@ -1,25 +1,25 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file buddysystem.h /// @file buddysystem.h
/// @brief Buddy System. /// @brief Buddy System.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "zone_allocator.h" #include "zone_allocator.h"
/// @brief Allocate a block of page frames in a zone of size 2^{order. /// @brief Allocate a block of page frames in a zone of size 2^{order.
/// @param zone A memory zone. /// @param zone A memory zone.
/// @param order The logarithm of the size of the block. /// @param order The logarithm of the size of the block.
/// @return The address of the first page descriptor of the block, or NULL. /// @return The address of the first page descriptor of the block, or NULL.
page_t *bb_alloc_pages(zone_t *zone, unsigned int order); page_t *bb_alloc_pages(zone_t *zone, unsigned int order);
/// @brief Free a block of page frames in a zone of size 2^{order. /// @brief Free a block of page frames in a zone of size 2^{order.
/// @param zone A memory zone. /// @param zone A memory zone.
/// @param page The address of the first page descriptor of the block. /// @param page The address of the first page descriptor of the block.
/// @param order The logarithm of the size of the block. /// @param order The logarithm of the size of the block.
void bb_free_pages(zone_t *zone, page_t *page, unsigned int order); void bb_free_pages(zone_t *zone, page_t *page, unsigned int order);
/// @brief Print the size of free_list of each free_area. /// @brief Print the size of free_list of each free_area.
/// @param zone A memory zone. /// @param zone A memory zone.
void buddy_system_dump(zone_t *zone); void buddy_system_dump(zone_t *zone);
+167 -167
View File
@@ -1,167 +1,167 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file gfp.h /// @file gfp.h
/// @brief List of GFP Flags. /// @brief List of GFP Flags.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/// Type used for GFP_FLAGS. /// Type used for GFP_FLAGS.
typedef unsigned int gfp_t; typedef unsigned int gfp_t;
// Plain integer GFP bitmasks. Do not use this directly. // Plain integer GFP bitmasks. Do not use this directly.
#define ___GFP_DMA 0x01u #define ___GFP_DMA 0x01u
#define ___GFP_HIGHMEM 0x02u #define ___GFP_HIGHMEM 0x02u
#define ___GFP_DMA32 0x04u #define ___GFP_DMA32 0x04u
#define ___GFP_RECLAIMABLE 0x10u #define ___GFP_RECLAIMABLE 0x10u
#define ___GFP_HIGH 0x20u #define ___GFP_HIGH 0x20u
#define ___GFP_IO 0x40u #define ___GFP_IO 0x40u
#define ___GFP_FS 0x80u #define ___GFP_FS 0x80u
#define ___GFP_ZERO 0x100u #define ___GFP_ZERO 0x100u
#define ___GFP_ATOMIC 0x200u #define ___GFP_ATOMIC 0x200u
#define ___GFP_DIRECT_RECLAIM 0x400u #define ___GFP_DIRECT_RECLAIM 0x400u
#define ___GFP_KSWAPD_RECLAIM 0x800u #define ___GFP_KSWAPD_RECLAIM 0x800u
/* /*
* Physical address zone modifiers (see linux/mmzone.h - low four bits) * Physical address zone modifiers (see linux/mmzone.h - low four bits)
* *
* Do not put any conditional on these. If necessary modify the definitions * Do not put any conditional on these. If necessary modify the definitions
* without the underscores and use them consistently. The definitions here may * without the underscores and use them consistently. The definitions here may
* be used in bit comparisons. * be used in bit comparisons.
*/ */
#define __GFP_DMA ___GFP_DMA #define __GFP_DMA ___GFP_DMA
#define __GFP_HIGHMEM ___GFP_HIGHMEM #define __GFP_HIGHMEM ___GFP_HIGHMEM
#define __GFP_DMA32 ___GFP_DMA32 #define __GFP_DMA32 ___GFP_DMA32
#define GFP_ZONEMASK (__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32) #define GFP_ZONEMASK (__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32)
/** /**
* DOC: Watermark modifiers * DOC: Watermark modifiers
* *
* Watermark modifiers -- controls access to emergency reserves * Watermark modifiers -- controls access to emergency reserves
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* *
* %__GFP_HIGH indicates that the caller is high-priority and that granting * %__GFP_HIGH indicates that the caller is high-priority and that granting
* the request is necessary before the system can make forward progress. * the request is necessary before the system can make forward progress.
* For example, creating an IO context to clean pages. * For example, creating an IO context to clean pages.
* *
* %__GFP_ATOMIC indicates that the caller cannot reclaim or sleep and is * %__GFP_ATOMIC indicates that the caller cannot reclaim or sleep and is
* high priority. Users are typically interrupt handlers. This may be * high priority. Users are typically interrupt handlers. This may be
* used in conjunction with %__GFP_HIGH * used in conjunction with %__GFP_HIGH
*/ */
#define __GFP_ATOMIC ___GFP_ATOMIC #define __GFP_ATOMIC ___GFP_ATOMIC
#define __GFP_HIGH ___GFP_HIGH #define __GFP_HIGH ___GFP_HIGH
/** /**
* DOC: Reclaim modifiers * DOC: Reclaim modifiers
* *
* Reclaim modifiers * Reclaim modifiers
* ~~~~~~~~~~~~~~~~~ * ~~~~~~~~~~~~~~~~~
* *
* %__GFP_IO can start physical IO. * %__GFP_IO can start physical IO.
* *
* %__GFP_FS can call down to the low-level FS. Clearing the flag avoids the * %__GFP_FS can call down to the low-level FS. Clearing the flag avoids the
* allocator recursing into the filesystem which might already be holding * allocator recursing into the filesystem which might already be holding
* locks. * locks.
* *
* %__GFP_DIRECT_RECLAIM indicates that the caller may enter direct reclaim. * %__GFP_DIRECT_RECLAIM indicates that the caller may enter direct reclaim.
* This flag can be cleared to avoid unnecessary delays when a fallback * This flag can be cleared to avoid unnecessary delays when a fallback
* option is available. * option is available.
* *
* %__GFP_KSWAPD_RECLAIM indicates that the caller wants to wake kswapd when * %__GFP_KSWAPD_RECLAIM indicates that the caller wants to wake kswapd when
* the low watermark is reached and have it reclaim pages until the high * the low watermark is reached and have it reclaim pages until the high
* watermark is reached. A caller may wish to clear this flag when fallback * watermark is reached. A caller may wish to clear this flag when fallback
* options are available and the reclaim is likely to disrupt the system. The * options are available and the reclaim is likely to disrupt the system. The
* canonical example is THP allocation where a fallback is cheap but * canonical example is THP allocation where a fallback is cheap but
* reclaim/compaction may cause indirect stalls. * reclaim/compaction may cause indirect stalls.
* *
* %__GFP_RECLAIM is shorthand to allow/forbid both direct and kswapd reclaim. * %__GFP_RECLAIM is shorthand to allow/forbid both direct and kswapd reclaim.
*/ */
#define __GFP_IO ___GFP_IO #define __GFP_IO ___GFP_IO
#define __GFP_FS ___GFP_FS #define __GFP_FS ___GFP_FS
// Caller can reclaim. // Caller can reclaim.
#define __GFP_DIRECT_RECLAIM ___GFP_DIRECT_RECLAIM #define __GFP_DIRECT_RECLAIM ___GFP_DIRECT_RECLAIM
// Kswapd can wake. // Kswapd can wake.
#define __GFP_KSWAPD_RECLAIM ___GFP_KSWAPD_RECLAIM #define __GFP_KSWAPD_RECLAIM ___GFP_KSWAPD_RECLAIM
#define __GFP_RECLAIM (___GFP_DIRECT_RECLAIM | ___GFP_KSWAPD_RECLAIM) #define __GFP_RECLAIM (___GFP_DIRECT_RECLAIM | ___GFP_KSWAPD_RECLAIM)
/** /**
* DOC: Useful GFP flag combinations * DOC: Useful GFP flag combinations
* *
* Useful GFP flag combinations * Useful GFP flag combinations
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* *
* Useful GFP flag combinations that are commonly used. It is recommended * Useful GFP flag combinations that are commonly used. It is recommended
* that subsystems start with one of these combinations and then set/clear * that subsystems start with one of these combinations and then set/clear
* %__GFP_FOO flags as necessary. * %__GFP_FOO flags as necessary.
* *
* %GFP_ATOMIC users can not sleep and need the allocation to succeed. A lower * %GFP_ATOMIC users can not sleep and need the allocation to succeed. A lower
* watermark is applied to allow access to "atomic reserves" * watermark is applied to allow access to "atomic reserves"
* *
* %GFP_KERNEL is typical for kernel-internal allocations. The caller requires * %GFP_KERNEL is typical for kernel-internal allocations. The caller requires
* %ZONE_NORMAL or a lower zone for direct access but can direct reclaim. * %ZONE_NORMAL or a lower zone for direct access but can direct reclaim.
* *
* %GFP_NOWAIT is for kernel allocations that should not stall for direct * %GFP_NOWAIT is for kernel allocations that should not stall for direct
* reclaim, start physical IO or use any filesystem callback. * reclaim, start physical IO or use any filesystem callback.
* *
* %GFP_NOIO will use direct reclaim to discard clean pages or slab pages * %GFP_NOIO will use direct reclaim to discard clean pages or slab pages
* that do not require the starting of any physical IO. * that do not require the starting of any physical IO.
* Please try to avoid using this flag directly and instead use * Please try to avoid using this flag directly and instead use
* memalloc_noio_{save,restore} to mark the whole scope which cannot * memalloc_noio_{save,restore} to mark the whole scope which cannot
* perform any IO with a short explanation why. All allocation requests * perform any IO with a short explanation why. All allocation requests
* will inherit GFP_NOIO implicitly. * will inherit GFP_NOIO implicitly.
* *
* %GFP_NOFS will use direct reclaim but will not use any filesystem interfaces. * %GFP_NOFS will use direct reclaim but will not use any filesystem interfaces.
* Please try to avoid using this flag directly and instead use * Please try to avoid using this flag directly and instead use
* memalloc_nofs_{save,restore} to mark the whole scope which cannot/shouldn't * memalloc_nofs_{save,restore} to mark the whole scope which cannot/shouldn't
* recurse into the FS layer with a short explanation why. All allocation * recurse into the FS layer with a short explanation why. All allocation
* requests will inherit GFP_NOFS implicitly. * requests will inherit GFP_NOFS implicitly.
* *
* %GFP_USER is for userspace allocations that also need to be directly * %GFP_USER is for userspace allocations that also need to be directly
* accessibly by the kernel or hardware. It is typically used by hardware * accessibly by the kernel or hardware. It is typically used by hardware
* for buffers that are mapped to userspace (e.g. graphics) that hardware * for buffers that are mapped to userspace (e.g. graphics) that hardware
* still must DMA to. cpuset limits are enforced for these allocations. * still must DMA to. cpuset limits are enforced for these allocations.
* *
* %GFP_DMA exists for historical reasons and should be avoided where possible. * %GFP_DMA exists for historical reasons and should be avoided where possible.
* The flags indicates that the caller requires that the lowest zone be * The flags indicates that the caller requires that the lowest zone be
* used (%ZONE_DMA or 16M on x86-64). Ideally, this would be removed but * used (%ZONE_DMA or 16M on x86-64). Ideally, this would be removed but
* it would require careful auditing as some users really require it and * it would require careful auditing as some users really require it and
* others use the flag to avoid lowmem reserves in %ZONE_DMA and treat the * others use the flag to avoid lowmem reserves in %ZONE_DMA and treat the
* lowest zone as a type of emergency reserve. * lowest zone as a type of emergency reserve.
* *
* %GFP_HIGHUSER is for userspace allocations that may be mapped to userspace, * %GFP_HIGHUSER is for userspace allocations that may be mapped to userspace,
* do not need to be directly accessible by the kernel but that cannot * do not need to be directly accessible by the kernel but that cannot
* move once in use. An example may be a hardware allocation that maps * move once in use. An example may be a hardware allocation that maps
* data directly into userspace but has no addressing limitations. * data directly into userspace but has no addressing limitations.
*/ */
#define GFP_ATOMIC (__GFP_HIGH | __GFP_ATOMIC | __GFP_KSWAPD_RECLAIM) #define GFP_ATOMIC (__GFP_HIGH | __GFP_ATOMIC | __GFP_KSWAPD_RECLAIM)
#define GFP_KERNEL (__GFP_RECLAIM | __GFP_IO | __GFP_FS) #define GFP_KERNEL (__GFP_RECLAIM | __GFP_IO | __GFP_FS)
#define GFP_NOWAIT (__GFP_KSWAPD_RECLAIM) #define GFP_NOWAIT (__GFP_KSWAPD_RECLAIM)
#define GFP_NOIO (__GFP_RECLAIM) #define GFP_NOIO (__GFP_RECLAIM)
#define GFP_NOFS (__GFP_RECLAIM | __GFP_IO) #define GFP_NOFS (__GFP_RECLAIM | __GFP_IO)
#define GFP_USER (__GFP_RECLAIM | __GFP_IO | __GFP_FS) #define GFP_USER (__GFP_RECLAIM | __GFP_IO | __GFP_FS)
#define GFP_DMA (__GFP_DMA) #define GFP_DMA (__GFP_DMA)
#define GFP_HIGHUSER (GFP_USER | __GFP_HIGHMEM) #define GFP_HIGHUSER (GFP_USER | __GFP_HIGHMEM)
+139 -128
View File
@@ -1,128 +1,139 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file kheap.h /// @file kheap.h
/// @brief Interface for kernel heap functions, also provides a placement /// @brief Interface for kernel heap functions, also provides a placement
/// malloc() for use before the heap is initialised. /// malloc() for use before the heap is initialised.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "kernel.h" #include "kernel.h"
#include "scheduler.h" #include "scheduler.h"
//#define KHEAP_START (void*)(LOAD_MEMORY_ADDRESS + 0x00800000) // 0x00800000 = 8M //#define KHEAP_START (void*)(LOAD_MEMORY_ADDRESS + 0x00800000) // 0x00800000 = 8M
//#define KHEAP_MAX_ADDRESS (void*)(LOAD_MEMORY_ADDRESS + 0x0FFFFFFF) // 0x10000000 = 256 M //#define KHEAP_MAX_ADDRESS (void*)(LOAD_MEMORY_ADDRESS + 0x0FFFFFFF) // 0x10000000 = 256 M
// M = 1024 * 1024 = 1MB // M = 1024 * 1024 = 1MB
#define KHEAP_INITIAL_SIZE (4 * M) #define KHEAP_INITIAL_SIZE (4 * M)
#define UHEAP_INITIAL_SIZE (1 * M) #define UHEAP_INITIAL_SIZE (1 * M)
/** /**
* @brief Structure of block_t * @brief Structure of block_t
* size: | 31 bit | 1 bit | * size: | 31 bit | 1 bit |
* | first bits of real size | free/alloc | * | first bits of real size | free/alloc |
* To calculate the real size, set to zero the last bit * To calculate the real size, set to zero the last bit
* prev: -> block_t * prev: -> block_t
* next: -> block_t * next: -> block_t
**/ **/
typedef struct block_t { typedef struct block_t {
unsigned int size; unsigned int size;
struct block_t *nextfree; struct block_t *nextfree;
struct block_t *next; struct block_t *next;
} block_t; } block_t;
/// @brief Initialize heap. /// @brief Initialize heap.
/// @param initial_size Starting size. /// @param initial_size Starting size.
void kheap_init(size_t initial_size); void kheap_init(size_t initial_size);
/// @brief Returns if the kheap is enabled. /// @brief Returns if the kheap is enabled.
bool_t kheap_is_enabled(); bool_t kheap_is_enabled();
void *ksbrk(int increment); void *ksbrk(int increment);
#if 0 #if 0
/// @brief Kmalloc wrapper. /// @brief Kmalloc wrapper.
/// @details When heap is not created, use a placement memory allocator, when /// @details When heap is not created, use a placement memory allocator, when
/// heap is created, use malloc(), the dynamic memory allocator. /// heap is created, use malloc(), the dynamic memory allocator.
/// @param size Size of memory to allocate. /// @param size Size of memory to allocate.
/// @param align Return a page-aligned memory block. /// @param align Return a page-aligned memory block.
/// @param phys Return the physical address of the memory block. /// @param phys Return the physical address of the memory block.
/// @return /// @return
uint32_t kmalloc_int(size_t size, bool_t align, uint32_t *phys); uint32_t kmalloc_int(size_t size, bool_t align, uint32_t *phys);
/// @brief Wrapper for kmalloc, get physical address. /// @brief Wrapper for kmalloc, get physical address.
/// @param sz Size of memory to allocate. /// @param sz Size of memory to allocate.
/// @param phys Pointer to the variable where to place the physical address. /// @param phys Pointer to the variable where to place the physical address.
/// @return /// @return
void *kmalloc_p(unsigned int sz, unsigned int *phys); void *kmalloc_p(unsigned int sz, unsigned int *phys);
/// @brief Wrapper for aligned kmalloc, get physical address. /// @brief Wrapper for aligned kmalloc, get physical address.
/// @param sz Size of memory to allocate. /// @param sz Size of memory to allocate.
/// @param phys Pointer to the variable where to place the physical address. /// @param phys Pointer to the variable where to place the physical address.
/// @return /// @return
void *kmalloc_ap(unsigned int sz, unsigned int *phys); void *kmalloc_ap(unsigned int sz, unsigned int *phys);
#endif #endif
/// @brief Dynamically allocates memory of the given size. /// @brief Dynamically allocates memory of the given size.
/// @param sz Size of memory to allocate. /// @param sz Size of memory to allocate.
/// @return /// @return
void *kmalloc(unsigned int sz); void *kmalloc(unsigned int sz);
/// @brief Wrapper for aligned kmalloc. /// @brief Wrapper for aligned kmalloc.
/// @param size Size of memory to allocate. /// @param size Size of memory to allocate.
/// @return /// @return
void *kmalloc_align(size_t size); void *kmalloc_align(size_t size);
/// @brief Dynamically allocates memory for (size * num) and memset it. /// @brief Dynamically allocates memory for (size * num) and memset it.
/// @param num Multiplier. /// @param num Multiplier.
/// @param size Size of memory to allocate. /// @param size Size of memory to allocate.
/// @return /// @return
void *kcalloc(unsigned int num, unsigned int size); void *kcalloc(unsigned int num, unsigned int size);
/// @brief Wrapper function for realloc. /// @brief Wrapper function for realloc.
/// @param ptr /// @param ptr
/// @param size /// @param size
/// @return /// @return
void *krealloc(void *ptr, unsigned int size); void *krealloc(void *ptr, unsigned int size);
/// @brief Wrapper function for free. /// @brief Allocate a matrix with n rows of a specific size.
/// @param p /// @param n Number of matrix rows.
void kfree(void *p); /// @param size Size of each matrix row.
/// @return Matrix pointer.
/// @brief Allocates size bytes of uninitialized storage. void **kmmalloc(size_t n, size_t size);
//void *malloc(unsigned int size);
/// @brief Wrapper function for free.
// We can't do a user heap brk if we don't enable paging... /// @param p
void *usbrk(int increment); void kfree(void *p);
/// @brief User malloc /// @brief Free a matrix of n rows.
/// @param size The size requested in byte. /// @param src Matrix to free.
/// @return The address of the allocated space. /// @param n Number of matrix rows.
void *umalloc(unsigned int size); void kmfree(void **src, size_t n);
/// @brief User free /// @brief Allocates size bytes of uninitialized storage.
/// @param p Pointer to the space to free. //void *malloc(unsigned int size);
void ufree(void *p);
// We can't do a user heap brk if we don't enable paging...
/// @brief Allocates size bytes of uninitialized storage with block align. void *usbrk(int increment);
//void *malloc_align(struct vm_area_struct *heap, unsigned int size);
/// @brief User malloc
/// @brief Deallocates previously allocated space. /// @param size The size requested in byte.
//void free(void *ptr); /// @return The address of the allocated space.
void *umalloc(unsigned int size);
/// @brief Reallocates the given area of memory. It must be still allocated
/// and not yet freed with a call to free or realloc. /// @brief User free
/// @param ptr /// @param p Pointer to the space to free.
/// @param size void ufree(void *p);
/// @return
//void *realloc(void *ptr, unsigned int size); /// @brief Allocates size bytes of uninitialized storage with block align.
//void *malloc_align(struct vm_area_struct *heap, unsigned int size);
/// @brief Prints the heap visually, for debug.
void kheap_dump(); /// @brief Deallocates previously allocated space.
//void free(void *ptr);
/// @brief Get the pointer to the kernel heap start.
/// @return The kernel heap start pointer. /// @brief Reallocates the given area of memory. It must be still allocated
uint32_t get_kheap_start(); /// and not yet freed with a call to free or realloc.
/// @param ptr
/// @brief Get the pointer to the kernel heap curr. /// @param size
/// @return The kernel heap current pointer. /// @return
uint32_t get_kheap_curr(); //void *realloc(void *ptr, unsigned int size);
/// @brief Prints the heap visually, for debug.
void kheap_dump();
/// @brief Get the pointer to the kernel heap start.
/// @return The kernel heap start pointer.
uint32_t get_kheap_start();
/// @brief Get the pointer to the kernel heap curr.
/// @return The kernel heap current pointer.
uint32_t get_kheap_curr();
+106 -106
View File
@@ -1,106 +1,106 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file paging.h /// @file paging.h
/// @brief Implementation of a memory paging management. /// @brief Implementation of a memory paging management.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "zone_allocator.h" #include "zone_allocator.h"
#include "kernel.h" #include "kernel.h"
#include "stddef.h" #include "stddef.h"
/// Size of a page. /// Size of a page.
#define PAGE_SIZE 4096 #define PAGE_SIZE 4096
/// @brief Virtual Memory Area. /// @brief Virtual Memory Area.
/// Process segments. /// Process segments.
struct vm_area_struct { struct vm_area_struct {
/// Memory descriptor associated. /// Memory descriptor associated.
struct mm_struct *vm_mm; struct mm_struct *vm_mm;
/// Start address of the segment. /// Start address of the segment.
uint32_t vm_start; uint32_t vm_start;
/// End address of the segment. /// End address of the segment.
uint32_t vm_end; uint32_t vm_end;
/// Next memory area of the list. /// Next memory area of the list.
struct vm_area_struct *vm_next; struct vm_area_struct *vm_next;
/// Permissions. /// Permissions.
pgprot_t vm_page_prot; pgprot_t vm_page_prot;
/// Flags. /// Flags.
unsigned short vm_flags; unsigned short vm_flags;
/// rbtree node. /// rbtree node.
// struct rb_node vm_rb; // struct rb_node vm_rb;
}; };
/// @brief Memory Descriptor. /// @brief Memory Descriptor.
/// Memory description of user process. /// Memory description of user process.
struct mm_struct { struct mm_struct {
/// List of memory area. /// List of memory area.
struct vm_area_struct *mmap; struct vm_area_struct *mmap;
// /// rbtree of memory area. // /// rbtree of memory area.
// struct rb_root mm_rb; // struct rb_root mm_rb;
/// Last memory area used. /// Last memory area used.
struct vm_area_struct *mmap_cache; struct vm_area_struct *mmap_cache;
// ///< Process page directory. // ///< Process page directory.
// page_directory_t * pgd; // page_directory_t * pgd;
/// Number of memory area. /// Number of memory area.
int map_count; int map_count;
/// List of mm_struct. /// List of mm_struct.
list_head mmlist; list_head mmlist;
/// CODE. /// CODE.
uint32_t start_code, end_code; uint32_t start_code, end_code;
/// DATA. /// DATA.
uint32_t start_data, end_data; uint32_t start_data, end_data;
/// HEAP. /// HEAP.
uint32_t start_brk, brk; uint32_t start_brk, brk;
/// STACK. /// STACK.
uint32_t start_stack; uint32_t start_stack;
/// ARGS. /// ARGS.
uint32_t arg_start, arg_end; uint32_t arg_start, arg_end;
/// ENVIRONMENT. /// ENVIRONMENT.
uint32_t env_start, env_end; uint32_t env_start, env_end;
/// Number of mapped pages. /// Number of mapped pages.
unsigned int total_vm; unsigned int total_vm;
}; };
/// @brief Returns if paging is enabled. /// @brief Returns if paging is enabled.
bool_t paging_is_enabled(); bool_t paging_is_enabled();
/// @brief Create a Memory Descriptor. /// @brief Create a Memory Descriptor.
/// @param stack_size The size of the stack in byte. /// @param stack_size The size of the stack in byte.
/// @return The Memory Descriptor created. /// @return The Memory Descriptor created.
struct mm_struct *create_process_image(size_t stack_size); struct mm_struct *create_process_image(size_t stack_size);
/// @brief Create a virtual memory area. /// @brief Create a virtual memory area.
/// @param mm The memory descriptor which will contain the new segment. /// @param mm The memory descriptor which will contain the new segment.
/// @param size The size of the segment. /// @param size The size of the segment.
/// @return The virtual address of the starting point of the segment. /// @return The virtual address of the starting point of the segment.
uint32_t create_segment(struct mm_struct *mm, size_t size); uint32_t create_segment(struct mm_struct *mm, size_t size);
/// @brief Free Memory Descriptor with all the memory segment contained. /// @brief Free Memory Descriptor with all the memory segment contained.
/// @param mm The Memory Descriptor to free. /// @param mm The Memory Descriptor to free.
void destroy_process_image(struct mm_struct *mm); void destroy_process_image(struct mm_struct *mm);
/* /*
* /// @brief Free a virtual memory area. * /// @brief Free a virtual memory area.
* /// @param mm The Memory Descriptor that contains the segment. * /// @param mm The Memory Descriptor that contains the segment.
* /// @param segment The segment to free. * /// @param segment The segment to free.
* void destroy_segment(struct mm_struct *mm, struct vm_area_struct *segment); * void destroy_segment(struct mm_struct *mm, struct vm_area_struct *segment);
*/ */
+163 -163
View File
@@ -1,163 +1,163 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file zone_allocator.h /// @file zone_allocator.h
/// @brief Implementation of the Zone Allocator /// @brief Implementation of the Zone Allocator
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "gfp.h" #include "gfp.h"
#include "math.h" #include "math.h"
#include "stdint.h" #include "stdint.h"
#include "stdbool.h" #include "stdbool.h"
#include "list_head.h" #include "list_head.h"
/// Max order of buddysystem blocks. /// Max order of buddysystem blocks.
#define MAX_ORDER 11 #define MAX_ORDER 11
/// @brief Buddy system descriptor: collection of free page blocks. /// @brief Buddy system descriptor: collection of free page blocks.
/// Each block represents 2^k free contiguous page. /// Each block represents 2^k free contiguous page.
typedef struct { typedef struct {
/// free_list collectes the first page descriptors of a blocks of 2^k frames /// free_list collectes the first page descriptors of a blocks of 2^k frames
list_head free_list; list_head free_list;
/// nr_free specifies the number of blocks of free pages. /// nr_free specifies the number of blocks of free pages.
int nr_free; int nr_free;
} free_area_t; } free_area_t;
/// @brief Page descriptor. Use as a bitmap to understand /// @brief Page descriptor. Use as a bitmap to understand
/// the order of the block and if it is free or allocated. /// the order of the block and if it is free or allocated.
typedef struct { typedef struct {
/// Array of flags encoding also the zone number to which the page frame belongs. /// Array of flags encoding also the zone number to which the page frame belongs.
unsigned long flags; unsigned long flags;
/// Page frames reference counter. -1 free, >= 0 used /// Page frames reference counter. -1 free, >= 0 used
int _count; int _count;
/// If the page is free, this field is used by the buddy system. /// If the page is free, this field is used by the buddy system.
unsigned long private; unsigned long private;
/// Contains pointers to the least recently used doubly linked list of pages. /// Contains pointers to the least recently used doubly linked list of pages.
struct list_head lru; struct list_head lru;
} page_t; } page_t;
/// @brief Enumeration for zone_t. /// @brief Enumeration for zone_t.
enum zone_type { enum zone_type {
/* /*
* ZONE_DMA is used when there are devices that are not able * ZONE_DMA is used when there are devices that are not able
* to do DMA to all of addressable memory (ZONE_NORMAL). Then we * to do DMA to all of addressable memory (ZONE_NORMAL). Then we
* carve out the portion of memory that is needed for these devices. * carve out the portion of memory that is needed for these devices.
* The range is arch specific. * The range is arch specific.
* *
* Some examples * Some examples
* *
* Architecture Limit * Architecture Limit
* --------------------------- * ---------------------------
* parisc, ia64, sparc <4G * parisc, ia64, sparc <4G
* s390 <2G * s390 <2G
* arm Various * arm Various
* alpha Unlimited or 0-16MB. * alpha Unlimited or 0-16MB.
* *
* i386, x86_64 and multiple other arches * i386, x86_64 and multiple other arches
* <16M. * <16M.
*/ */
// ///< Direct memory access. // ///< Direct memory access.
// ZONE_DMA, // ZONE_DMA,
/* /*
* Normal addressable memory is in ZONE_NORMAL. DMA operations can be * Normal addressable memory is in ZONE_NORMAL. DMA operations can be
* performed on pages in ZONE_NORMAL if the DMA devices support * performed on pages in ZONE_NORMAL if the DMA devices support
* transfers to all addressable memory. * transfers to all addressable memory.
*/ */
/// Direct mapping. Used by the kernel. /// Direct mapping. Used by the kernel.
ZONE_NORMAL, ZONE_NORMAL,
/* /*
* A memory area that is only addressable by the kernel through * A memory area that is only addressable by the kernel through
* mapping portions into its own address space. This is for example * mapping portions into its own address space. This is for example
* used by i386 to allow the kernel to address the memory beyond * used by i386 to allow the kernel to address the memory beyond
* 900MB. The kernel will set up special mappings (page * 900MB. The kernel will set up special mappings (page
* table entries on i386) for each page that the kernel needs to * table entries on i386) for each page that the kernel needs to
* access. * access.
*/ */
/// Page tables mapping. Used by user processes. /// Page tables mapping. Used by user processes.
ZONE_HIGHMEM, ZONE_HIGHMEM,
__MAX_NR_ZONES __MAX_NR_ZONES
}; };
/// @brief Data structure to differentiate memory zone. /// @brief Data structure to differentiate memory zone.
typedef struct { typedef struct {
/// Number of free pages in the zone. /// Number of free pages in the zone.
unsigned long free_pages; unsigned long free_pages;
/// BuddySystem structure for the zone. /// BuddySystem structure for the zone.
free_area_t free_area[MAX_ORDER]; free_area_t free_area[MAX_ORDER];
/// Pointer to first page descriptor of the zone. /// Pointer to first page descriptor of the zone.
page_t *zone_mem_map; page_t *zone_mem_map;
/// Index of the first page frame of the zone. /// Index of the first page frame of the zone.
uint32_t zone_start_pfn; uint32_t zone_start_pfn;
/// Zone's name. /// Zone's name.
char *name; char *name;
/// Zone's size in number of pages. /// Zone's size in number of pages.
unsigned long size; unsigned long size;
} zone_t; } zone_t;
/// @brief Data structure to rapresent a memory node. /// @brief Data structure to rapresent a memory node.
/// In UMA Architecture there is only one node called /// In UMA Architecture there is only one node called
/// contig_page_data. /// contig_page_data.
typedef struct { typedef struct {
/// Zones of the node. /// Zones of the node.
zone_t node_zones[__MAX_NR_ZONES]; zone_t node_zones[__MAX_NR_ZONES];
/// Number of zones in the node. /// Number of zones in the node.
int nr_zones; int nr_zones;
/// Array of pages of the node. /// Array of pages of the node.
page_t *node_mem_map; page_t *node_mem_map;
/// Physical address of the first page of the node. /// Physical address of the first page of the node.
unsigned long node_start_paddr; unsigned long node_start_paddr;
/// Index on global mem_map for node_mem_map. /// Index on global mem_map for node_mem_map.
unsigned long node_start_mapnr; unsigned long node_start_mapnr;
/// Node's size in number of pages. /// Node's size in number of pages.
unsigned long node_size; unsigned long node_size;
/// NID. /// NID.
int node_id; int node_id;
/// Pointer to the next node. /// Pointer to the next node.
struct pglist_data *node_next; struct pglist_data *node_next;
} pg_data_t; } pg_data_t;
extern page_t *mem_map; extern page_t *mem_map;
extern pg_data_t *contig_page_data; extern pg_data_t *contig_page_data;
/// @brief Find the nearest block's order of size greater /// @brief Find the nearest block's order of size greater
/// than the amount of byte. /// than the amount of byte.
/// @param amount The amount of byte which we want to calculate order. /// @param amount The amount of byte which we want to calculate order.
/// @return The block's order greater and nearest than amount. /// @return The block's order greater and nearest than amount.
uint32_t find_nearest_order_greater(uint32_t amount); uint32_t find_nearest_order_greater(uint32_t amount);
/// @brief Physical memory manager initialization (page_t, zones) /// @brief Physical memory manager initialization (page_t, zones)
/// @param mem_size Size of the memory. /// @param mem_size Size of the memory.
bool_t pmmngr_init(uint32_t mem_size); bool_t pmmngr_init(uint32_t mem_size);
/// @brief Find the first free page frame, set it allocated /// @brief Find the first free page frame, set it allocated
/// and return the memory address of the page frame. /// and return the memory address of the page frame.
/// @param gfp_mask GFP_FLAGS to decide the zone allocation. /// @param gfp_mask GFP_FLAGS to decide the zone allocation.
/// @return Memory address of the first free block. /// @return Memory address of the first free block.
uint32_t __alloc_page(gfp_t gfp_mask); uint32_t __alloc_page(gfp_t gfp_mask);
/// @brief Frees the given page frame address. /// @brief Frees the given page frame address.
/// @param addr The block address. /// @param addr The block address.
void free_page(uint32_t addr); void free_page(uint32_t addr);
/// @brief Find the first free 2^order amount of page frames, /// @brief Find the first free 2^order amount of page frames,
/// set it allocated and return the memory address of the first /// set it allocated and return the memory address of the first
/// page frame allocated. /// page frame allocated.
/// @param gfp_mask GFP_FLAGS to decide the zone allocation. /// @param gfp_mask GFP_FLAGS to decide the zone allocation.
/// @param order The logarithm of the size of the page frame. /// @param order The logarithm of the size of the page frame.
/// @return Memory address of the first free page frame allocated. /// @return Memory address of the first free page frame allocated.
uint32_t __alloc_pages(gfp_t gfp_mask, uint32_t order); uint32_t __alloc_pages(gfp_t gfp_mask, uint32_t order);
/// @brief Frees from the given page frame address up to /// @brief Frees from the given page frame address up to
/// 2^order amount of page frames. /// 2^order amount of page frames.
/// @param addr The page frame address. /// @param addr The page frame address.
/// @param order The logarithm of the size of the block. /// @param order The logarithm of the size of the block.
void free_pages(uint32_t addr, uint32_t order); void free_pages(uint32_t addr, uint32_t order);
/// @brief Get the pointer of the last byte allocated with pmmngr_init() /// @brief Get the pointer of the last byte allocated with pmmngr_init()
/// @return The pointer to the memory. /// @return The pointer to the memory.
uint32_t get_memory_start(); uint32_t get_memory_start();
+30 -30
View File
@@ -1,30 +1,30 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file bitops.h /// @file bitops.h
/// @brief Bitmasks functions. /// @brief Bitmasks functions.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
#include "stdbool.h" #include "stdbool.h"
/// @brief Finds the first bit set in the given irq mask. /// @brief Finds the first bit set in the given irq mask.
int find_first_bit(unsigned short int irq_mask); int find_first_bit(unsigned short int irq_mask);
/// @brief Check if the passed value has the given flag set. /// @brief Check if the passed value has the given flag set.
/// @param flags The value to check. /// @param flags The value to check.
/// @param flag The flag to search. /// @param flag The flag to search.
/// @return True If the value contain the flag, <br> /// @return True If the value contain the flag, <br>
/// False otherwise. /// False otherwise.
bool_t has_flag(uint32_t flags, uint32_t flag); bool_t has_flag(uint32_t flags, uint32_t flag);
/// @brief Set the passed flag to the value. /// @brief Set the passed flag to the value.
/// @param flags The destination value. /// @param flags The destination value.
/// @param flag The flag to set. /// @param flag The flag to set.
void set_flag(uint32_t *flags, uint32_t flag); void set_flag(uint32_t *flags, uint32_t flag);
/// @brief Clear the passed flag to the value. /// @brief Clear the passed flag to the value.
/// @param flags The destination value. /// @param flags The destination value.
/// @param flag The flag to clear. /// @param flag The flag to clear.
void clear_flag(uint32_t *flags, uint32_t flag); void clear_flag(uint32_t *flags, uint32_t flag);
+98 -98
View File
@@ -1,98 +1,98 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file clock.h /// @file clock.h
/// @brief Clock functions. /// @brief Clock functions.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/// Used to store time values. /// Used to store time values.
typedef unsigned int time_t; typedef unsigned int time_t;
/// Used to get information about the current time. /// Used to get information about the current time.
typedef struct tm_t { typedef struct tm_t {
/// Seconds [0 to 59] /// Seconds [0 to 59]
int tm_sec; int tm_sec;
/// Minutes [0 to 59] /// Minutes [0 to 59]
int tm_min; int tm_min;
/// Hours [0 to 23] /// Hours [0 to 23]
int tm_hour; int tm_hour;
/// Day of the month [1 to 31] /// Day of the month [1 to 31]
int tm_mday; int tm_mday;
/// Month [0 to 11] /// Month [0 to 11]
int tm_mon; int tm_mon;
/// Year [since 1900] /// Year [since 1900]
int tm_year; int tm_year;
/// Day of the week [0 to 6] /// Day of the week [0 to 6]
int tm_wday; int tm_wday;
/// Day in the year [0 to 365] /// Day in the year [0 to 365]
int tm_yday; int tm_yday;
/// Is Daylight Saving Time. /// Is Daylight Saving Time.
int tm_isdst; int tm_isdst;
} tm_t; } tm_t;
/// Value used to retrieve the seconds. /// Value used to retrieve the seconds.
#define SECOND_RTC 0x00 #define SECOND_RTC 0x00
/// Value used to retrieve the minutes. /// Value used to retrieve the minutes.
#define MINUTE_RTC 0x02 #define MINUTE_RTC 0x02
/// Value used to retrieve the hours. /// Value used to retrieve the hours.
#define HOUR_RTC 0x04 #define HOUR_RTC 0x04
/// Value used to retrieve the day of the week. /// Value used to retrieve the day of the week.
#define DAY_W_RTC 0x06 #define DAY_W_RTC 0x06
/// Value used to retrieve the day of the month. /// Value used to retrieve the day of the month.
#define DAY_M_RTC 0x07 #define DAY_M_RTC 0x07
/// Value used to retrieve the month. /// Value used to retrieve the month.
#define MONTH_RTC 0x08 #define MONTH_RTC 0x08
/// Value used to retrieve the year. /// Value used to retrieve the year.
#define YEAR_RTC 0x09 #define YEAR_RTC 0x09
/// @brief Returns the milliseconds. /// @brief Returns the milliseconds.
time_t get_millisecond(); time_t get_millisecond();
/// @brief Returns the seconds. /// @brief Returns the seconds.
time_t get_second(); time_t get_second();
/// @brief Returns the hours. /// @brief Returns the hours.
time_t get_hour(); time_t get_hour();
/// @brief Returns the minutes. /// @brief Returns the minutes.
time_t get_minute(); time_t get_minute();
/// @brief Returns the day of the month. /// @brief Returns the day of the month.
time_t get_day_m(); time_t get_day_m();
/// @brief returns the month. /// @brief returns the month.
time_t get_month(); time_t get_month();
/// @brief Returns the year. /// @brief Returns the year.
time_t get_year(); time_t get_year();
/// @brief Returns the day of the week. /// @brief Returns the day of the week.
time_t get_day_w(); time_t get_day_w();
/// @brief Returns the name of the month. /// @brief Returns the name of the month.
char *get_month_lng(); char *get_month_lng();
/// @brief Returns the name of the day. /// @brief Returns the name of the day.
char *get_day_lng(); char *get_day_lng();
/// @brief Returns the current time. /// @brief Returns the current time.
time_t time(time_t *timer); time_t time(time_t *timer);
// TODO: doxygen comment. // TODO: doxygen comment.
time_t difftime(time_t time1, time_t time2); time_t difftime(time_t time1, time_t time2);
// TODO: doxygen comment. // TODO: doxygen comment.
void strhourminutesecond(char *dst); void strhourminutesecond(char *dst);
// TODO: doxygen comment. // TODO: doxygen comment.
void strdaymonthyear(char *dst); void strdaymonthyear(char *dst);
// TODO: doxygen comment. // TODO: doxygen comment.
void strdatehour(char *dst); void strdatehour(char *dst);
+67 -67
View File
@@ -1,67 +1,67 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file debug.h /// @file debug.h
/// @brief Debugging primitives. /// @brief Debugging primitives.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "kernel.h" #include "kernel.h"
#include "port_io.h" #include "port_io.h"
/// @brief Used to enable the device. Any I/O to the debug module before this /// @brief Used to enable the device. Any I/O to the debug module before this
/// command is sent will simply be ignored. /// command is sent will simply be ignored.
#define DBG_ENABLE 0x8A00 #define DBG_ENABLE 0x8A00
/// @brief Disable the I/O interface to the debugger and the memory /// @brief Disable the I/O interface to the debugger and the memory
/// monitoring functions. /// monitoring functions.
#define DBG_DISABLE 0x8AFF #define DBG_DISABLE 0x8AFF
/// @brief Selects register 0: Memory monitoring range start address /// @brief Selects register 0: Memory monitoring range start address
/// (inclusive). /// (inclusive).
#define SELECTS_REG_0 0x8A01 #define SELECTS_REG_0 0x8A01
/// @brief Selects register 1: Memory monitoring range end address (exclusive). /// @brief Selects register 1: Memory monitoring range end address (exclusive).
#define SELECTS_REG_1 0x8A02 #define SELECTS_REG_1 0x8A02
/// @brief Enable address range memory monitoring as indicated by register 0 /// @brief Enable address range memory monitoring as indicated by register 0
/// and 1 and clears both registers. /// and 1 and clears both registers.
#define ENABLE_ADDR_RANGE_MEM_MONITOR 0x8A80 #define ENABLE_ADDR_RANGE_MEM_MONITOR 0x8A80
/// @brief If the debugger is enabled (via --enable-debugger), sending 0x8AE2 /// @brief If the debugger is enabled (via --enable-debugger), sending 0x8AE2
/// to port 0x8A00 after the device has been enabled will enable instruction /// to port 0x8A00 after the device has been enabled will enable instruction
/// tracing. /// tracing.
#define INSTRUCTION_TRACE_ENABLE 0x8AE3 #define INSTRUCTION_TRACE_ENABLE 0x8AE3
/// @brief If the debugger is enabled (via --enable-debugger), sending 0x8AE2 /// @brief If the debugger is enabled (via --enable-debugger), sending 0x8AE2
/// to port 0x8A00 after the device has been enabled will disable instruction /// to port 0x8A00 after the device has been enabled will disable instruction
/// tracing. /// tracing.
#define INSTRUCTION_TRACE_DISABLE 0x8AE2 #define INSTRUCTION_TRACE_DISABLE 0x8AE2
/// @brief If the debugger is enabled (via --enable-debugger), sending 0x8AE5 /// @brief If the debugger is enabled (via --enable-debugger), sending 0x8AE5
/// to port 0x8A00 after the device has been enabled will enable register /// to port 0x8A00 after the device has been enabled will enable register
/// tracing. This currently output the value of all the registers for each /// tracing. This currently output the value of all the registers for each
/// instruction traced. Note: instruction tracing must be enabled to view /// instruction traced. Note: instruction tracing must be enabled to view
/// the register tracing. /// the register tracing.
#define REGISTER_TRACE_ENABLE 0x8AE5 #define REGISTER_TRACE_ENABLE 0x8AE5
/// @brief If the debugger is enabled (via --enable-debugger), sending 0x8AE4 /// @brief If the debugger is enabled (via --enable-debugger), sending 0x8AE4
/// to port 0x8A00 after the device has been enabled will disable register /// to port 0x8A00 after the device has been enabled will disable register
/// tracing. /// tracing.
#define REGISTER_TRACE_DISABLE 0x8AE4 #define REGISTER_TRACE_DISABLE 0x8AE4
/// @brief Prints the given string to the debug output. /// @brief Prints the given string to the debug output.
void _dbg_print(const char *file, const char *fun, int line, const char *msg, void _dbg_print(const char *file, const char *fun, int line, const char *msg,
...); ...);
#define __FILENAME__ \ #define __FILENAME__ \
(__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : \ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : \
__FILE__) __FILE__)
#define dbg_print(...) _dbg_print(__FILENAME__, __func__, __LINE__, __VA_ARGS__) #define dbg_print(...) _dbg_print(__FILENAME__, __func__, __LINE__, __VA_ARGS__)
/// @brief Prints the given registers to the debug output. /// @brief Prints the given registers to the debug output.
void print_reg(register_t *reg); void print_reg(register_t *reg);
/// @brief Prints the given intrframe to the debug output. /// @brief Prints the given intrframe to the debug output.
void print_intrframe(pt_regs *frame); void print_intrframe(pt_regs *frame);
+206 -223
View File
@@ -1,223 +1,206 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file multiboot.h /// @file multiboot.h
/// @brief Data structures used for multiboot. /// @brief Data structures used for multiboot.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
// Do not inc here in boot.s. // Do not inc here in boot.s.
#pragma once #pragma once
#include "stdint.h" #include "stdint.h"
#define MULTIBOOT_FLAG_MEM 0x001 // The magic field should contain this.
#define MULTIBOOT_HEADER_MAGIC 0x1BADB002
#define MULTIBOOT_FLAG_DEVICE 0x002 // This should be in %eax.
#define MULTIBOOT_BOOTLOADER_MAGIC 0x2BADB002
#define MULTIBOOT_FLAG_CMDLINE 0x004
/// Is there basic lower/upper memory information?
#define MULTIBOOT_FLAG_MODS 0x008 #define MULTIBOOT_FLAG_MEM 0x00000001U
/// is there a boot device set?
#define MULTIBOOT_FLAG_AOUT 0x010 #define MULTIBOOT_FLAG_DEVICE 0x00000002U
/// is the command-line defined?
#define MULTIBOOT_FLAG_ELF 0x020 #define MULTIBOOT_FLAG_CMDLINE 0x00000004U
/// are there modules to do something with?
#define MULTIBOOT_FLAG_MMAP 0x040 #define MULTIBOOT_FLAG_MODS 0x00000008U
/// is there a symbol table loaded?
#define MULTIBOOT_FLAG_CONFIG 0x080 #define MULTIBOOT_FLAG_AOUT 0x00000010U
/// is there an ELF section header table?
#define MULTIBOOT_FLAG_LOADER 0x100 #define MULTIBOOT_FLAG_ELF 0x00000020U
/// is there a full memory map?
#define MULTIBOOT_FLAG_APM 0x200 #define MULTIBOOT_FLAG_MMAP 0x00000040U
/// Is there drive info?
#define MULTIBOOT_FLAG_VBE 0x400 #define MULTIBOOT_FLAG_DRIVE_INFO 0x00000080U
/// Is there a config table?
#define MULTIBOOT_FRAMEBUFFER_TYPE_INDEXED 0 #define MULTIBOOT_FLAG_CONFIG_TABLE 0x00000100U
/// Is there a boot loader name?
#define MULTIBOOT_FRAMEBUFFER_TYPE_RGB 1 #define MULTIBOOT_FLAG_BOOT_LOADER_NAME 0x00000200U
/// Is there a APM table?
#define MULTIBOOT_FRAMEBUFFER_TYPE_EGA_TEXT 2 #define MULTIBOOT_FLAG_APM_TABLE 0x00000400U
/// Is there video information?
#define MULTIBOOT_MEMORY_AVAILABLE 1 #define MULTIBOOT_FLAG_VBE_INFO 0x00000800U
#define MULTIBOOT_FLAG_FRAMEBUFFER_INFO 0x00001000U
#define MULTIBOOT_MEMORY_RESERVED 2
#define MULTIBOOT_FRAMEBUFFER_TYPE_INDEXED 0
#define MULTIBOOT_MEMORY_ACPI_RECLAIMABLE 3 #define MULTIBOOT_FRAMEBUFFER_TYPE_RGB 1
#define MULTIBOOT_FRAMEBUFFER_TYPE_EGA_TEXT 2
#define MULTIBOOT_MEMORY_NVS 4
#define MULTIBOOT_MEMORY_AVAILABLE 1
#define MULTIBOOT_MEMORY_BADRAM 5 #define MULTIBOOT_MEMORY_RESERVED 2
#define MULTIBOOT_MEMORY_ACPI_RECLAIMABLE 3
// +-------------------+ #define MULTIBOOT_MEMORY_NVS 4
// 0 | flags | (required) #define MULTIBOOT_MEMORY_BADRAM 5
// +-------------------+
// 4 | mem_lower | (present if flags[0] is set) // +-------------------+
// 8 | mem_upper | (present if flags[0] is set) // 0 | flags | (required)
// +-------------------+ // +-------------------+
// 12 | boot_device | (present if flags[1] is set) // 4 | mem_lower | (present if flags[0] is set)
// +-------------------+ // 8 | mem_upper | (present if flags[0] is set)
// 16 | cmdline | (present if flags[2] is set) // +-------------------+
// +-------------------+ // 12 | boot_device | (present if flags[1] is set)
// 20 | mods_count | (present if flags[3] is set) // +-------------------+
// 24 | mods_addr | (present if flags[3] is set) // 16 | cmdline | (present if flags[2] is set)
// +-------------------+ // +-------------------+
// 28 - 40 | syms | (present if flags[4] or // 20 | mods_count | (present if flags[3] is set)
// | | flags[5] is set) // 24 | mods_addr | (present if flags[3] is set)
// +-------------------+ // +-------------------+
// 44 | mmap_length | (present if flags[6] is set) // 28 - 40 | syms | (present if flags[4] or
// 48 | mmap_addr | (present if flags[6] is set) // | | flags[5] is set)
// +-------------------+ // +-------------------+
// 52 | drives_length | (present if flags[7] is set) // 44 | mmap_length | (present if flags[6] is set)
// 56 | drives_addr | (present if flags[7] is set) // 48 | mmap_addr | (present if flags[6] is set)
// +-------------------+ // +-------------------+
// 60 | config_table | (present if flags[8] is set) // 52 | drives_length | (present if flags[7] is set)
// +-------------------+ // 56 | drives_addr | (present if flags[7] is set)
// 64 | boot_loader_name | (present if flags[9] is set) // +-------------------+
// +-------------------+ // 60 | config_table | (present if flags[8] is set)
// 68 | apm_table | (present if flags[10] is set) // +-------------------+
// +-------------------+ // 64 | boot_loader_name | (present if flags[9] is set)
// 72 | vbe_control_info | (present if flags[11] is set) // +-------------------+
// 76 | vbe_mode_info | // 68 | apm_table | (present if flags[10] is set)
// 80 | vbe_mode | // +-------------------+
// 82 | vbe_interface_seg | // 72 | vbe_control_info | (present if flags[11] is set)
// 84 | vbe_interface_off | // 76 | vbe_mode_info |
// 86 | vbe_interface_len | // 80 | vbe_mode |
// +-------------------+ // 82 | vbe_interface_seg |
// 88 | framebuffer_addr | (present if flags[12] is set) // 84 | vbe_interface_off |
// 96 | framebuffer_pitch | // 86 | vbe_interface_len |
// 100 | framebuffer_width | // +-------------------+
// 104 | framebuffer_height| // 88 | framebuffer_addr | (present if flags[12] is set)
// 108 | framebuffer_bpp | // 96 | framebuffer_pitch |
// 109 | framebuffer_type | // 100 | framebuffer_width |
// 110-115 | color_info | // 104 | framebuffer_height|
// +-------------------+ // 108 | framebuffer_bpp |
// 109 | framebuffer_type |
/// The symbol table for a.out. // 110-115 | color_info |
typedef struct multiboot_aout_symbol_table // +-------------------+
{
uint32_t tabsize; /// The symbol table for a.out.
uint32_t strsize; typedef struct multiboot_aout_symbol_table {
uint32_t addr; uint32_t tabsize;
uint32_t reserved; uint32_t strsize;
} multiboot_aout_symbol_table_t; uint32_t addr;
uint32_t reserved;
/// The section header table for ELF. } multiboot_aout_symbol_table_t;
typedef struct multiboot_elf_section_header_table
{ /// The section header table for ELF.
uint32_t num; typedef struct multiboot_elf_section_header_table {
uint32_t size; uint32_t num;
uint32_t addr; uint32_t size;
uint32_t shndx; uint32_t addr;
} multiboot_elf_section_header_table_t; uint32_t shndx;
} multiboot_elf_section_header_table_t;
// TODO: doxygen comment.
typedef struct multiboot_mod_list // TODO: doxygen comment.
{ typedef struct multiboot_module {
// The memory used goes from bytes 'mod_start' to 'mod_end-1' inclusive. // The memory used goes from bytes 'mod_start' to 'mod_end-1' inclusive.
uint32_t mod_start; uint32_t mod_start;
uint32_t mod_end; uint32_t mod_end;
// Module command line. // Module command line.
uint32_t cmdline; uint32_t cmdline;
// Padding to take it to 16 bytes (must be zero). // Padding to take it to 16 bytes (must be zero).
uint32_t pad; uint32_t pad;
} multiboot_module_t; } multiboot_module_t;
// TODO: doxygen comment. typedef struct multiboot_memory_map {
typedef struct multiboot_mmap_entry uint32_t size;
{ uint32_t base_addr_low;
uint32_t size; uint32_t base_addr_high;
uint64_t addr; uint32_t length_low;
uint64_t len; uint32_t length_high;
uint32_t type; uint32_t type;
} __attribute__((packed)) multiboot_memory_map_t; } multiboot_memory_map_t;
// TODO: doxygen comment. // TODO: doxygen comment.
typedef struct multiboot_info typedef struct multiboot_info {
{ /// Multiboot info version number.
/// Multiboot info version number. uint32_t flags;
uint32_t flags;
/// Available memory from BIOS.
/// Available memory from BIOS. uint32_t mem_lower;
uint32_t mem_lower; uint32_t mem_upper;
uint32_t mem_upper;
/// "root" partition.
/// "root" partition. uint32_t boot_device;
uint32_t boot_device;
/// Kernel command line.
/// Kernel command line. uint32_t cmdline;
uint32_t cmdline;
/// Boot-Module list.
/// Boot-Module list. uint32_t mods_count;
uint32_t mods_count; uint32_t mods_addr;
uint32_t mods_addr;
union {
union multiboot_aout_symbol_table_t aout_sym;
{ multiboot_elf_section_header_table_t elf_sec;
multiboot_aout_symbol_table_t aout_sym; } u;
multiboot_elf_section_header_table_t elf_sec;
} u; /// Memory Mapping buffer.
uint32_t mmap_length;
/// Memory Mapping buffer. uint32_t mmap_addr;
uint32_t mmap_length;
uint32_t mmap_addr; /// Drive Info buffer.
uint32_t drives_length;
/// Drive Info buffer. uint32_t drives_addr;
uint32_t drives_length;
uint32_t drives_addr; /// ROM configuration table.
uint32_t config_table;
/// ROM configuration table.
uint32_t config_table; /// Boot Loader Name.
uint32_t boot_loader_name;
/// Boot Loader Name.
uint32_t boot_loader_name; /// APM table.
uint32_t apm_table;
/// APM table.
uint32_t apm_table; /// Video.
uint32_t vbe_control_info;
/// Video. uint32_t vbe_mode_info;
uint32_t vbe_control_info; uint32_t vbe_mode;
uint32_t vbe_mode_info; uint32_t vbe_interface_seg;
uint32_t vbe_mode; uint32_t vbe_interface_off;
uint32_t vbe_interface_seg; uint32_t vbe_interface_len;
uint32_t vbe_interface_off;
uint32_t vbe_interface_len; uint32_t framebuffer_addr;
uint32_t framebuffer_pitch;
uint32_t framebuffer_addr; uint32_t framebuffer_width;
uint32_t framebuffer_pitch; uint32_t framebuffer_height;
uint32_t framebuffer_width; uint32_t framebuffer_bpp;
uint32_t framebuffer_height; uint32_t framebuffer_type;
uint32_t framebuffer_bpp; union {
uint32_t framebuffer_type; struct {
union uint32_t framebuffer_palette_addr;
{ uint16_t framebuffer_palette_num_colors;
struct };
{ struct {
uint32_t framebuffer_palette_addr; uint8_t framebuffer_red_field_position;
uint16_t framebuffer_palette_num_colors; uint8_t framebuffer_red_mask_size;
}; uint8_t framebuffer_green_field_position;
struct uint8_t framebuffer_green_mask_size;
{ uint8_t framebuffer_blue_field_position;
uint8_t framebuffer_red_field_position; uint8_t framebuffer_blue_mask_size;
uint8_t framebuffer_red_mask_size; };
uint8_t framebuffer_green_field_position; };
uint8_t framebuffer_green_mask_size; } __attribute__((packed)) multiboot_info_t;
uint8_t framebuffer_blue_field_position;
uint8_t framebuffer_blue_mask_size; // TODO: doxygen comment.
}; void dump_multiboot(multiboot_info_t *mboot_ptr);
};
} __attribute__((packed)) multiboot_info_t;
// Be careful that the offset 0 is base_addr_low but no size.
/// @brief The memory map.
typedef struct memory_map
{
uint32_t size;
uint32_t base_addr_low;
uint32_t base_addr_high;
uint32_t length_low;
uint32_t length_high;
uint32_t type;
} memory_map_t;
// TODO: doxygen comment.
void dump_multiboot(multiboot_info_t *mboot_ptr);
+55 -55
View File
@@ -1,55 +1,55 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file prio.h /// @file prio.h
/// @brief Defines processes priority value. /// @brief Defines processes priority value.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#define MAX_NICE +19 #define MAX_NICE +19
#define MIN_NICE -20 #define MIN_NICE -20
#define NICE_WIDTH (MAX_NICE - MIN_NICE + 1) #define NICE_WIDTH (MAX_NICE - MIN_NICE + 1)
// Priority of a process goes from 0..MAX_PRIO-1, valid RT // Priority of a process goes from 0..MAX_PRIO-1, valid RT
// priority is 0..MAX_RT_PRIO-1, and SCHED_NORMAL/SCHED_BATCH // priority is 0..MAX_RT_PRIO-1, and SCHED_NORMAL/SCHED_BATCH
// tasks are in the range MAX_RT_PRIO..MAX_PRIO-1. Priority // tasks are in the range MAX_RT_PRIO..MAX_PRIO-1. Priority
// values are inverted: lower p->prio value means higher priority. // values are inverted: lower p->prio value means higher priority.
// //
// The MAX_USER_RT_PRIO value allows the actual maximum // The MAX_USER_RT_PRIO value allows the actual maximum
// RT priority to be separate from the value exported to // RT priority to be separate from the value exported to
// user-space. This allows kernel threads to set their // user-space. This allows kernel threads to set their
// priority to a value higher than any user task. // priority to a value higher than any user task.
// Note: MAX_RT_PRIO must not be smaller than MAX_USER_RT_PRIO. // Note: MAX_RT_PRIO must not be smaller than MAX_USER_RT_PRIO.
#define MAX_RT_PRIO 100 #define MAX_RT_PRIO 100
#define MAX_PRIO (MAX_RT_PRIO + NICE_WIDTH) #define MAX_PRIO (MAX_RT_PRIO + NICE_WIDTH)
#define DEFAULT_PRIO (MAX_RT_PRIO + NICE_WIDTH / 2) #define DEFAULT_PRIO (MAX_RT_PRIO + NICE_WIDTH / 2)
// Convert user-nice values [ -20 ... 0 ... 19 ] // Convert user-nice values [ -20 ... 0 ... 19 ]
// to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ], // to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
// and back. // and back.
#define NICE_TO_PRIO(nice) ((nice) + DEFAULT_PRIO) #define NICE_TO_PRIO(nice) ((nice) + DEFAULT_PRIO)
#define PRIO_TO_NICE(prio) ((prio) - DEFAULT_PRIO) #define PRIO_TO_NICE(prio) ((prio)-DEFAULT_PRIO)
// 'User priority' is the nice value converted to something we // 'User priority' is the nice value converted to something we
// can work with better when scaling various scheduler parameters, // can work with better when scaling various scheduler parameters,
// it's a [ 0 ... 39 ] range. // it's a [ 0 ... 39 ] range.
#define USER_PRIO(p) ((p)-MAX_RT_PRIO) #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
#define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio) #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
#define MAX_USER_PRIO (USER_PRIO(MAX_PRIO)) #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
static const int prio_to_weight[NICE_WIDTH] = { static const int prio_to_weight[NICE_WIDTH] = {
/* 100 */ 88761, 71755, 56483, 46273, 36291, /* 100 */ 88761, 71755, 56483, 46273, 36291,
/* 105 */ 29154, 23254, 18705, 14949, 11916, /* 105 */ 29154, 23254, 18705, 14949, 11916,
/* 110 */ 9548, 7620, 6100, 4904, 3906, /* 110 */ 9548, 7620, 6100, 4904, 3906,
/* 115 */ 3121, 2501, 1991, 1586, 1277, /* 115 */ 3121, 2501, 1991, 1586, 1277,
/* 120 */ 1024, 820, 655, 526, 423, /* 120 */ 1024, 820, 655, 526, 423,
/* 125 */ 335, 272, 215, 172, 137, /* 125 */ 335, 272, 215, 172, 137,
/* 130 */ 110, 87, 70, 56, 45, /* 130 */ 110, 87, 70, 56, 45,
/* 135 */ 36, 29, 23, 18, 15 /* 135 */ 36, 29, 23, 18, 15
}; };
+209 -214
View File
@@ -1,214 +1,209 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file process.h /// @file process.h
/// @brief Process data structures and functions. /// @brief Process data structures and functions.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "list.h" #include "list.h"
#include "tree.h" #include "tree.h"
#include "clock.h" #include "clock.h"
#include "types.h" #include "types.h"
#include "stdint.h" #include "stdint.h"
#include "stddef.h" #include "stddef.h"
#include "paging.h" #include "paging.h"
#include "kernel.h" #include "kernel.h"
#include "unistd.h" #include "unistd.h"
#include "list_head.h" #include "list_head.h"
#include "signal_defs.h" #include "signal_defs.h"
#include "limits.h"
/// The maximum length of a name for a task_struct.
#define TASK_NAME_MAX_LENGTH 100 /// The maximum length of a name for a task_struct.
#define TASK_NAME_MAX_LENGTH 100
/// The default dimension of the stack of a process (1 MByte).
#define DEFAULT_STACK_SIZE 0x100000 /// The default dimension of the stack of a process (1 MByte).
#define DEFAULT_STACK_SIZE 0x100000
//==== Task state ==============================================================
// Used in tsk->state /// The maximum number of resources for a task.
/// The task is running. #define TASK_RESOURCE_MAX_AMOUNT 32
#define TASK_RUNNING 0x0000
//==== Task state ==============================================================
/// The task is interruptible. // Used in tsk->state
#define TASK_INTERRUPTIBLE 0x0001 /// The task is running.
#define TASK_RUNNING 0x0000
/// The task is uninterruptible.
#define TASK_UNINTERRUPTIBLE 0x0002 /// The task is interruptible.
#define TASK_INTERRUPTIBLE 0x0001
// Used in tsk->exit_state
/// The task is dead. /// The task is uninterruptible.
#define EXIT_DEAD 0x0010 #define TASK_UNINTERRUPTIBLE 0x0002
/// The task is zombie. // Used in tsk->exit_state
#define EXIT_ZOMBIE 0x0020 /// The task is dead.
//============================================================================== #define EXIT_DEAD 0x0010
/// @brief Every task_struck has a sched_entity. This structure is used to track /// The task is zombie.
/// the statistics of a process. While the other variables also play a role in #define EXIT_ZOMBIE 0x0020
/// CFS decisions'algorithm, vruntime is by far the core variable which needs //==============================================================================
/// more attention as to understand the scheduling decision process.
/// @details /// @brief Every task_struck has a sched_entity. This structure is used to track
/// The nice value is a user-space and priority 'prio' is the process's actual /// the statistics of a process. While the other variables also play a role in
/// priority that use by Linux kernel. In linux system priorities are 0 to 139 /// CFS decisions'algorithm, vruntime is by far the core variable which needs
/// in which 0 to 99 for real time and 100 to 139 for users. /// more attention as to understand the scheduling decision process.
/// The nice value range is -20 to +19 where -20 is highest, 0 default and +19 /// @details
/// is lowest. relation between nice value and priority is : PR = 20 + NI. /// The nice value is a user-space and priority 'prio' is the process's actual
typedef struct sched_entity { /// priority that use by Linux kernel. In linux system priorities are 0 to 139
/// Static execution priority. /// in which 0 to 99 for real time and 100 to 139 for users.
int prio; /// The nice value range is -20 to +19 where -20 is highest, 0 default and +19
/// is lowest. relation between nice value and priority is : PR = 20 + NI.
/// Start execution time. typedef struct sched_entity {
time_t start_runtime; /// Static execution priority.
int prio;
/// Last context switch time.
time_t exec_start; /// Start execution time.
time_t start_runtime;
/// Overall execution time.
time_t sum_exec_runtime; /// Last context switch time.
time_t exec_start;
/// weighted execution time.
time_t vruntime; /// Overall execution time.
time_t sum_exec_runtime;
} sched_entity;
/// weighted execution time.
// x86 thread (x86 and FPU registers). time_t vruntime;
typedef struct thread_struct {
/// 32-bit base pointer register. } sched_entity;
uint32_t ebp;
// x86 thread (x86 and FPU registers).
/// 32-bit stack pointer register. typedef struct thread_struct {
uint32_t useresp; /// 32-bit base pointer register.
uint32_t ebp;
/// 32-bit base register.
uint32_t ebx; /// 32-bit stack pointer register.
uint32_t useresp;
/// 32-bit data register.
uint32_t edx; /// 32-bit base register.
uint32_t ebx;
/// 32-bit counter.
uint32_t ecx; /// 32-bit data register.
uint32_t edx;
/// 32-bit accumulator register.
uint32_t eax; /// 32-bit counter.
uint32_t ecx;
/// Instruction Pointer Register.
uint32_t eip; /// 32-bit accumulator register.
uint32_t eax;
/// 32-bit flag register.
uint32_t eflags; /// Instruction Pointer Register.
uint32_t eip;
/// FS and GS have no hardware-assigned uses.
uint32_t gs; /// 32-bit flag register.
uint32_t eflags;
/// FS and GS have no hardware-assigned uses.
uint32_t fs; /// FS and GS have no hardware-assigned uses.
uint32_t gs;
/// Extra Segment determined by the programmer.
uint32_t es; /// FS and GS have no hardware-assigned uses.
uint32_t fs;
/// Data Segment.
uint32_t ds; /// Extra Segment determined by the programmer.
uint32_t es;
/// 32-bit destination register.
uint32_t edi; /// Data Segment.
uint32_t ds;
/// 32-bit source register.
uint32_t esi; /// 32-bit destination register.
uint32_t edi;
// ///< Code Segment.
// uint32_t cs; /// 32-bit source register.
uint32_t esi;
// ///< Stack Segment.
// uint32_t ss; // ///< Code Segment.
// uint32_t cs;
/// Determines if the FPU is enabled.
bool_t fpu_enabled; // ///< Stack Segment.
// uint32_t ss;
/// Data structure used to save FPU registers.
savefpu fpu_register; /// Determines if the FPU is enabled.
} thread_struct; bool_t fpu_enabled;
/// @brief this is our task object. Every process in the system has this, and /// Data structure used to save FPU registers.
/// it holds a lot of information. Itll hold mm information, its name, savefpu fpu_register;
/// statistics, etc.. } thread_struct;
typedef struct task_struct {
/// The pid of the process. /// @brief this is our task object. Every process in the system has this, and
pid_t pid; /// it holds a lot of information. Itll hold mm information, its name,
/// statistics, etc..
// -1 unrunnable, 0 runnable, >0 stopped. typedef struct task_struct {
/// The current state of the process: /// The pid of the process.
__volatile__ long state; pid_t pid;
/// Pointer to process's parent. // -1 unrunnable, 0 runnable, >0 stopped.
struct task_struct *parent; /// The current state of the process:
__volatile__ long state;
/// List head for scheduling purposes.
list_head run_list; /// Pointer to process's parent.
struct task_struct *parent;
/// List of children traced by the process.
list_head children; /// List head for scheduling purposes.
list_head run_list;
/// List of siblings.
list_head sibling; /// List of children traced by the process.
list_head children;
/// The context of the processors.
thread_struct thread; /// List of siblings.
list_head sibling;
/// For scheduling algorithms.
sched_entity se; /// The context of the processors.
thread_struct thread;
/// Exit code of the process. (parameter of _exit() system call).
int exit_code; /// For scheduling algorithms.
sched_entity se;
/// The name of the task (Added for debug purpose).
char name[TASK_NAME_MAX_LENGTH]; /// Exit code of the process. (parameter of _exit() system call).
int exit_code;
/// Task's segments.
struct mm_struct *mm; /// The name of the task (Added for debug purpose).
char name[TASK_NAME_MAX_LENGTH];
/// Task's specific error number.
int error_no; /// Task's segments.
struct mm_struct *mm;
/// The current working directory.
char cwd[MAX_PATH_LENGTH]; /// Task's specific error number.
int error_no;
//==== Future work =========================================================
// - task's attributes: /// The current working directory.
// struct task_struct __rcu *real_parent; char cwd[PATH_MAX];
// int exit_state;
// int exit_signal; /// Array of resource pointers that task need for.
// struct thread_info thread_info; struct resource *resources[TASK_RESOURCE_MAX_AMOUNT];
// List of sibling, namely processes created by parent process
// struct list_head sibling; //==== Future work =========================================================
// - task's attributes:
// - task's file descriptor: // struct task_struct __rcu *real_parent;
// struct files_struct *files; // int exit_state;
// int exit_signal;
// - task's signal handlers: // struct thread_info thread_info;
// struct signal_struct *signal; // List of sibling, namely processes created by parent process
// struct sighand_struct *sighand; // struct list_head sibling;
// sigset_t blocked;
// sigset_t real_blocked; // - task's file descriptor:
// sigset_t saved_sigmask; // struct files_struct *files;
// struct sigpending pending;
//========================================================================== // - task's signal handlers:
// struct signal_struct *signal;
} task_struct; // struct sighand_struct *sighand;
// sigset_t blocked;
/// @brief Create a child process. // sigset_t real_blocked;
pid_t sys_vfork(pt_regs *r); // sigset_t saved_sigmask;
// struct sigpending pending;
// TODO: doxygen comment. //==========================================================================
char *get_current_dir_name();
} task_struct;
// TODO: doxygen comment.
void sys_getcwd(char *path, size_t size); // TODO: doxygen comment.
char *get_current_dir_name();
// TODO: doxygen comment.s
void sys_chdir(char const *path); /// @brief Create and spawn the init process.
struct task_struct *create_init_process();
/// @brief Replaces the current process image with a new process image.
int sys_execve(pt_regs *r);
/// @brief Create and spawn the init process.
struct task_struct *create_init_process();
+68 -82
View File
@@ -1,82 +1,68 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file scheduler.h /// @file scheduler.h
/// @brief Scheduler structures and functions. /// @brief Scheduler structures and functions.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "clock.h" #include "clock.h"
#include "kernel.h" #include "kernel.h"
#include "stdint.h" #include "stdint.h"
#include "process.h" #include "process.h"
typedef struct { typedef struct {
/// Number of queued processes. /// Number of queued processes.
size_t num_active; size_t num_active;
/// Queue of processes. /// Queue of processes.
list_head queue; list_head queue;
/// The current running process. /// The current running process.
task_struct *curr; task_struct *curr;
} runqueue_t; } runqueue_t;
/// @brief Returns a non-decreasing unique process id. /// @brief Returns a non-decreasing unique process id.
/// @return Process identifier (PID). /// @return Process identifier (PID).
uint32_t get_new_pid(); uint32_t get_new_pid();
/// @brief Initialize the scheduler. /// @brief Initialize the scheduler.
void kernel_initialize_scheduler(); void kernel_initialize_scheduler();
/// @brief Activate the given process. /// @brief Activate the given process.
/// @param process Process that has to be activated. /// @param process Process that has to be activated.
void enqueue_task(task_struct *process); void enqueue_task(task_struct *process);
/// @brief Removes the given process from the queue. /// @brief Removes the given process from the queue.
/// @param process Process that has to be activated. /// @param process Process that has to be activated.
void dequeue_task(task_struct *process); void dequeue_task(task_struct *process);
/// @brief Returns the number of active processes. /// @brief Returns the number of active processes.
size_t kernel_get_active_processes(); size_t kernel_get_active_processes();
/// @brief Returns the pointer to the current active process. /// @brief Returns the pointer to the current active process.
task_struct *kernel_get_current_process(); task_struct *kernel_get_current_process();
/// @brief Returns a pointer to the process with the given pid. /// @brief Returns a pointer to the process with the given pid.
task_struct *kernel_get_running_process(pid_t pid); task_struct *kernel_get_running_process(pid_t pid);
task_struct *pick_next_task(runqueue_t *runqueue, time_t delta_exec); task_struct *pick_next_task(runqueue_t *runqueue, time_t delta_exec);
/// @brief The RR implementation of the scheduler. /// @brief The RR implementation of the scheduler.
/// @param f The context of the process. /// @param f The context of the process.
void kernel_schedule(pt_regs *f); void kernel_schedule(pt_regs *f);
/// @birief Values from pt_regs to task_struct process. /// @birief Values from pt_regs to task_struct process.
void update_context(pt_regs *f, task_struct *process); void update_context(pt_regs *f, task_struct *process);
/// @brief Values from task_struct process to pt_regs. /// @brief Values from task_struct process to pt_regs.
void do_switch(task_struct *process, pt_regs *f); void do_switch(task_struct *process, pt_regs *f);
/// @brief Switch CPU to user mode and start running that given process. /// @brief Switch CPU to user mode and start running that given process.
/// @param process The process that has to be executed /// @param process The process that has to be executed
void enter_user_jmp(uintptr_t location, uintptr_t stack); void enter_user_jmp(uintptr_t location, uintptr_t stack);
/// Returns the process ID (PID) of the calling process. /// @brief Sets the priority value of the given task.
pid_t sys_getpid(); int set_user_nice(task_struct *p, long nice);
/// Returns the parent process ID (PPID) of the calling process.
pid_t sys_getppid();
/// @brief Sets the priority value of the given task.
int set_user_nice(task_struct *p, long nice);
/// @brief Adds the increment to the priority value of the task.
int sys_nice(int increment);
/// @brief Suspends execution of the calling thread until a child specified
/// by pid argument has changed state.
pid_t sys_waitpid(pid_t pid, int *status, int options);
/// The exit() function causes normal process termination.
void sys_exit(int exit_code);
+48 -55
View File
@@ -1,55 +1,48 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file dirent.h /// @file dirent.h
/// @brief Functions used to manage directories. /// @brief Functions used to manage directories.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stddef.h" #include "stddef.h"
#include "limits.h"
/// The maximum length for a name.
#define NAME_MAX 30 /// @brief Contains the entries of a directory.
typedef struct dirent_t {
/// @brief Contains the entries of a directory. /// The inode of the entry.
typedef struct dirent_t ino_t d_ino;
{
/// The inode of the entry. /// The type of the entry.
ino_t d_ino; int d_type;
/// The type of the entry. /// The nam of the entry.
int d_type; char d_name[NAME_MAX + 1];
} dirent_t;
/// The nam of the entry.
char d_name[NAME_MAX + 1]; /// @brief Contains information concerning a directory.
} dirent_t; typedef struct DIR {
/// Filesystem directory handle.
/// @brief Contains information concerning a directory. int fd;
typedef struct DIR /// The currently opened entry.
{ ino_t cur_entry;
/// Filesystem directory handle. /// Path to the directory.
int handle; char path[NAME_MAX + 1];
/// Next directory item.
/// The currently opened entry. dirent_t entry;
ino_t cur_entry; } DIR;
/// Path to the directory. /// @brief Opens a directory and returns a handler to it.
char path[NAME_MAX + 1]; /// @param path The path of the directory.
/// @return Pointer to the directory. Otherwise, NULL.
/// Next directory item. DIR *opendir(const char *path);
dirent_t entry;
} DIR; /// @brief Given a pointer to a directory, it closes it.
int closedir(DIR *dirp);
/// @brief Opens a directory and returns a handler to it.
/// @param path The path of the directory. /// @brief At each call of this function, it returns a pointer to the next
/// @return Pointer to the directory. Otherwise, NULL. /// element inside the directory.
DIR *opendir(const char *path); /// @return A pointer to the next element. If there are no more elments, it
/// returns NULL.
/// @brief Given a pointer to a directory, it closes it. dirent_t *readdir(DIR *dirp);
int closedir(DIR *dirp);
/// @brief At each call of this function, it returns a pointer to the next
/// element inside the directory.
/// @return A pointer to the next element. If there are no more elments, it
/// returns NULL.
dirent_t *readdir(DIR *dirp);
+383 -383
View File
@@ -1,383 +1,383 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file process.c /// @file process.c
/// @brief System call errors definition. /// @brief System call errors definition.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
extern int *__geterrno(); extern int *__geterrno();
#define errno (*__geterrno()) #define errno (*__geterrno())
/// Operation not permitted. /// Operation not permitted.
#define EPERM 1 #define EPERM 1
/// No such file or directory. /// No such file or directory.
#define ENOENT 2 #define ENOENT 2
/// No such process. /// No such process.
#define ESRCH 3 #define ESRCH 3
/// Interrupted system call. /// Interrupted system call.
#define EINTR 4 #define EINTR 4
///I/O error. ///I/O error.
#define EIO 5 #define EIO 5
/// No such device or address. /// No such device or address.
#define ENXIO 6 #define ENXIO 6
/// Arg list too long. /// Arg list too long.
#define E2BIG 7 #define E2BIG 7
/// Exec format error. /// Exec format error.
#define ENOEXEC 8 #define ENOEXEC 8
/// Bad file number. /// Bad file number.
#define EBADF 9 #define EBADF 9
/// No child processes. /// No child processes.
#define ECHILD 10 #define ECHILD 10
/// Try again. /// Try again.
#define EAGAIN 11 #define EAGAIN 11
/// Out of memory. /// Out of memory.
#define ENOMEM 12 #define ENOMEM 12
/// Permission denied. /// Permission denied.
#define EACCES 13 #define EACCES 13
/// Bad address. /// Bad address.
#define EFAULT 14 #define EFAULT 14
/// Block device required. /// Block device required.
#define ENOTBLK 15 #define ENOTBLK 15
/// Device or resource busy. /// Device or resource busy.
#define EBUSY 16 #define EBUSY 16
/// File exists. /// File exists.
#define EEXIST 17 #define EEXIST 17
/// Cross-device link. /// Cross-device link.
#define EXDEV 18 #define EXDEV 18
/// No such device. /// No such device.
#define ENODEV 19 #define ENODEV 19
/// Not a directory. /// Not a directory.
#define ENOTDIR 20 #define ENOTDIR 20
/// Is a directory. /// Is a directory.
#define EISDIR 21 #define EISDIR 21
/// Invalid argument. /// Invalid argument.
#define EINVAL 22 #define EINVAL 22
/// File table overflow. /// File table overflow.
#define ENFILE 23 #define ENFILE 23
/// Too many open files. /// Too many open files.
#define EMFILE 24 #define EMFILE 24
/// Not a typewriter. /// Not a typewriter.
#define ENOTTY 25 #define ENOTTY 25
/// Text file busy. /// Text file busy.
#define ETXTBSY 26 #define ETXTBSY 26
/// File too large. /// File too large.
#define EFBIG 27 #define EFBIG 27
/// No space left on device. /// No space left on device.
#define ENOSPC 28 #define ENOSPC 28
/// Illegal seek. /// Illegal seek.
#define ESPIPE 29 #define ESPIPE 29
/// Read-only file system. /// Read-only file system.
#define EROFS 30 #define EROFS 30
/// Too many links. /// Too many links.
#define EMLINK 31 #define EMLINK 31
/// Broken pipe. /// Broken pipe.
#define EPIPE 32 #define EPIPE 32
/// Math argument out of domain of func. /// Math argument out of domain of func.
#define EDOM 33 #define EDOM 33
/// Math result not representable. /// Math result not representable.
#define ERANGE 34 #define ERANGE 34
/// Resource deadlock would occur. /// Resource deadlock would occur.
#define EDEADLK 35 #define EDEADLK 35
/// File name too long. /// File name too long.
#define ENAMETOOLONG 36 #define ENAMETOOLONG 36
/// No record locks available. /// No record locks available.
#define ENOLCK 37 #define ENOLCK 37
/// Function not implemented. /// Function not implemented.
#define ENOSYS 38 #define ENOSYS 38
/// Directory not empty. /// Directory not empty.
#define ENOTEMPTY 39 #define ENOTEMPTY 39
/// Too many symbolic links encountered. /// Too many symbolic links encountered.
#define ELOOP 40 #define ELOOP 40
/// Operation would block. /// Operation would block.
#define EWOULDBLOCK EAGAIN #define EWOULDBLOCK EAGAIN
/// No message of desired type. /// No message of desired type.
#define ENOMSG 42 #define ENOMSG 42
/// Identifier removed. /// Identifier removed.
#define EIDRM 43 #define EIDRM 43
/// Channel number out of range. /// Channel number out of range.
#define ECHRNG 44 #define ECHRNG 44
/// Level 2 not synchronized. /// Level 2 not synchronized.
#define EL2NSYNC 45 #define EL2NSYNC 45
/// Level 3 halted. /// Level 3 halted.
#define EL3HLT 46 #define EL3HLT 46
/// Level 3 reset. /// Level 3 reset.
#define EL3RST 47 #define EL3RST 47
/// Link number out of range. /// Link number out of range.
#define ELNRNG 48 #define ELNRNG 48
/// Protocol driver not attached. /// Protocol driver not attached.
#define EUNATCH 49 #define EUNATCH 49
/// No CSI structure available. /// No CSI structure available.
#define ENOCSI 50 #define ENOCSI 50
/// Level 2 halted. /// Level 2 halted.
#define EL2HLT 51 #define EL2HLT 51
/// Invalid exchange. /// Invalid exchange.
#define EBADE 52 #define EBADE 52
/// Invalid request descriptor. /// Invalid request descriptor.
#define EBADR 53 #define EBADR 53
/// Exchange full. /// Exchange full.
#define EXFULL 54 #define EXFULL 54
/// No anode. /// No anode.
#define ENOANO 55 #define ENOANO 55
/// Invalid request code. /// Invalid request code.
#define EBADRQC 56 #define EBADRQC 56
/// Invalid slot. /// Invalid slot.
#define EBADSLT 57 #define EBADSLT 57
// TODO: doxygen comment. // TODO: doxygen comment.
#define EDEADLOCK EDEADLK #define EDEADLOCK EDEADLK
/// Bad font file format. /// Bad font file format.
#define EBFONT 59 #define EBFONT 59
/// Device not a stream. /// Device not a stream.
#define ENOSTR 60 #define ENOSTR 60
/// No data available. /// No data available.
#define ENODATA 61 #define ENODATA 61
/// Timer expired. /// Timer expired.
#define ETIME 62 #define ETIME 62
/// Out of streams resources. /// Out of streams resources.
#define ENOSR 63 #define ENOSR 63
/// Machine is not on the network. /// Machine is not on the network.
#define ENONET 64 #define ENONET 64
/// Package not installed. /// Package not installed.
#define ENOPKG 65 #define ENOPKG 65
/// Object is remote. /// Object is remote.
#define EREMOTE 66 #define EREMOTE 66
/// Link has been severed. /// Link has been severed.
#define ENOLINK 67 #define ENOLINK 67
/// Advertise error. /// Advertise error.
#define EADV 68 #define EADV 68
/// Srmount error. /// Srmount error.
#define ESRMNT 69 #define ESRMNT 69
/// Communication error on send. /// Communication error on send.
#define ECOMM 70 #define ECOMM 70
/// Protocol error. /// Protocol error.
#define EPROTO 71 #define EPROTO 71
/// Multihop attempted. /// Multihop attempted.
#define EMULTIHOP 72 #define EMULTIHOP 72
/// RFS specific error. /// RFS specific error.
#define EDOTDOT 73 #define EDOTDOT 73
/// Not a data message. /// Not a data message.
#define EBADMSG 74 #define EBADMSG 74
/// Value too large for defined data type. /// Value too large for defined data type.
#define EOVERFLOW 75 #define EOVERFLOW 75
/// Name not unique on network. /// Name not unique on network.
#define ENOTUNIQ 76 #define ENOTUNIQ 76
/// File descriptor in bad state. /// File descriptor in bad state.
#define EBADFD 77 #define EBADFD 77
/// Remote address changed. /// Remote address changed.
#define EREMCHG 78 #define EREMCHG 78
/// Can not access a needed shared library. /// Can not access a needed shared library.
#define ELIBACC 79 #define ELIBACC 79
/// Accessing a corrupted shared library. /// Accessing a corrupted shared library.
#define ELIBBAD 80 #define ELIBBAD 80
/// .lib section in a.out corrupted. /// .lib section in a.out corrupted.
#define ELIBSCN 81 #define ELIBSCN 81
/// Attempting to link in too many shared libraries. /// Attempting to link in too many shared libraries.
#define ELIBMAX 82 #define ELIBMAX 82
/// Cannot exec a shared library directly. /// Cannot exec a shared library directly.
#define ELIBEXEC 83 #define ELIBEXEC 83
/// Illegal byte sequence. /// Illegal byte sequence.
#define EILSEQ 84 #define EILSEQ 84
/// Interrupted system call should be restarted. /// Interrupted system call should be restarted.
#define ERESTART 85 #define ERESTART 85
/// Streams pipe error. /// Streams pipe error.
#define ESTRPIPE 86 #define ESTRPIPE 86
/// Too many users. /// Too many users.
#define EUSERS 87 #define EUSERS 87
///Socket operation on non-socket. ///Socket operation on non-socket.
#define ENOTSOCK 88 #define ENOTSOCK 88
/// Destination address required. /// Destination address required.
#define EDESTADDRREQ 89 #define EDESTADDRREQ 89
/// Message too long. /// Message too long.
#define EMSGSIZE 90 #define EMSGSIZE 90
/// Protocol wrong type for socket. /// Protocol wrong type for socket.
#define EPROTOTYPE 91 #define EPROTOTYPE 91
/// Protocol not available. /// Protocol not available.
#define ENOPROTOOPT 92 #define ENOPROTOOPT 92
/// Protocol not supported. /// Protocol not supported.
#define EPROTONOSUPPORT 93 #define EPROTONOSUPPORT 93
/// Socket type not supported. /// Socket type not supported.
#define ESOCKTNOSUPPORT 94 #define ESOCKTNOSUPPORT 94
/// Operation not supported on transport endpoint. /// Operation not supported on transport endpoint.
#define EOPNOTSUPP 95 #define EOPNOTSUPP 95
/// Protocol family not supported. /// Protocol family not supported.
#define EPFNOSUPPORT 96 #define EPFNOSUPPORT 96
/// Address family not supported by protocol. /// Address family not supported by protocol.
#define EAFNOSUPPORT 97 #define EAFNOSUPPORT 97
/// Address already in use. /// Address already in use.
#define EADDRINUSE 98 #define EADDRINUSE 98
/// Cannot assign requested address. /// Cannot assign requested address.
#define EADDRNOTAVAIL 99 #define EADDRNOTAVAIL 99
/// Network is down. /// Network is down.
#define ENETDOWN 100 #define ENETDOWN 100
/// Network is unreachable. /// Network is unreachable.
#define ENETUNREACH 101 #define ENETUNREACH 101
/// Network dropped connection because of reset. /// Network dropped connection because of reset.
#define ENETRESET 102 #define ENETRESET 102
/// Software caused connection abort. /// Software caused connection abort.
#define ECONNABORTED 103 #define ECONNABORTED 103
/// Connection reset by peer. /// Connection reset by peer.
#define ECONNRESET 104 #define ECONNRESET 104
/// No buffer space available. /// No buffer space available.
#define ENOBUFS 105 #define ENOBUFS 105
/// Transport endpoint is already connected. /// Transport endpoint is already connected.
#define EISCONN 106 #define EISCONN 106
/// Transport endpoint is not connected. /// Transport endpoint is not connected.
#define ENOTCONN 107 #define ENOTCONN 107
/// Cannot send after transport endpoint shutdown. /// Cannot send after transport endpoint shutdown.
#define ESHUTDOWN 108 #define ESHUTDOWN 108
/// Too many references: cannot splice. /// Too many references: cannot splice.
#define ETOOMANYREFS 109 #define ETOOMANYREFS 109
/// Connection timed out. /// Connection timed out.
#define ETIMEDOUT 110 #define ETIMEDOUT 110
/// Connection refused. /// Connection refused.
#define ECONNREFUSED 111 #define ECONNREFUSED 111
/// Host is down. /// Host is down.
#define EHOSTDOWN 112 #define EHOSTDOWN 112
/// No route to host. /// No route to host.
#define EHOSTUNREACH 113 #define EHOSTUNREACH 113
///Operation already in progress. ///Operation already in progress.
#define EALREADY 114 #define EALREADY 114
/// Operation now in progress. /// Operation now in progress.
#define EINPROGRESS 115 #define EINPROGRESS 115
/// Stale NFS file handle. /// Stale NFS file handle.
#define ESTALE 116 #define ESTALE 116
/// Structure needs cleaning. /// Structure needs cleaning.
#define EUCLEAN 117 #define EUCLEAN 117
/// Not a XENIX named type file. /// Not a XENIX named type file.
#define ENOTNAM 118 #define ENOTNAM 118
/// No XENIX semaphores available. /// No XENIX semaphores available.
#define ENAVAIL 119 #define ENAVAIL 119
/// Is a named type file. /// Is a named type file.
#define EISNAM 120 #define EISNAM 120
/// Remote I/O error. /// Remote I/O error.
#define EREMOTEIO 121 #define EREMOTEIO 121
/// Quota exceeded. /// Quota exceeded.
#define EDQUOT 122 #define EDQUOT 122
/// No medium found. /// No medium found.
#define ENOMEDIUM 123 #define ENOMEDIUM 123
/// Wrong medium type. /// Wrong medium type.
#define EMEDIUMTYPE 124 #define EMEDIUMTYPE 124
+53 -53
View File
@@ -1,53 +1,53 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file ipc.h /// @file ipc.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "stddef.h" #include "stddef.h"
/// Create key if key does not exist. /// Create key if key does not exist.
#define IPC_CREAT 01000 #define IPC_CREAT 01000
/// Fail if key exists. /// Fail if key exists.
#define IPC_EXCL 02000 #define IPC_EXCL 02000
/// Return error on wait. /// Return error on wait.
#define IPC_NOWAIT 04000 #define IPC_NOWAIT 04000
/// Remove identifier. /// Remove identifier.
#define IPC_RMID 0 #define IPC_RMID 0
/// Set `ipc_perm' options. /// Set `ipc_perm' options.
#define IPC_SET 1 #define IPC_SET 1
/// Get `ipc_perm' options. /// Get `ipc_perm' options.
#define IPC_STAT 2 #define IPC_STAT 2
/// See ipcs. /// See ipcs.
#define IPC_INFO 3 #define IPC_INFO 3
struct ipc_perm { struct ipc_perm {
/// Creator user id. /// Creator user id.
uid_t cuid; uid_t cuid;
/// Creator group id. /// Creator group id.
gid_t cgid; gid_t cgid;
/// User id. /// User id.
uid_t uid; uid_t uid;
/// Group id. /// Group id.
gid_t gid; gid_t gid;
/// r/w permission. /// r/w permission.
ushort mode; ushort mode;
/// Sequence # (to generate unique msg/sem/shm id). /// Sequence # (to generate unique msg/sem/shm id).
ushort seq; ushort seq;
/// User specified msg/sem/shm key. /// User specified msg/sem/shm key.
key_t key; key_t key;
}; };
+7 -7
View File
@@ -1,7 +1,7 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file module.h /// @file module.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
+43 -43
View File
@@ -1,43 +1,43 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file reboot.h /// @file reboot.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
// Magic values required to use _reboot() system call. // Magic values required to use _reboot() system call.
#define LINUX_REBOOT_MAGIC1 0xfee1dead #define LINUX_REBOOT_MAGIC1 0xfee1dead
#define LINUX_REBOOT_MAGIC2 672274793 #define LINUX_REBOOT_MAGIC2 672274793
#define LINUX_REBOOT_MAGIC2A 85072278 #define LINUX_REBOOT_MAGIC2A 85072278
#define LINUX_REBOOT_MAGIC2B 369367448 #define LINUX_REBOOT_MAGIC2B 369367448
#define LINUX_REBOOT_MAGIC2C 537993216 #define LINUX_REBOOT_MAGIC2C 537993216
// Commands accepted by the _reboot() system call. // Commands accepted by the _reboot() system call.
/// Restart system using default command and mode. /// Restart system using default command and mode.
#define LINUX_REBOOT_CMD_RESTART 0x01234567 #define LINUX_REBOOT_CMD_RESTART 0x01234567
/// Stop OS and give system control to ROM monitor, if any. /// Stop OS and give system control to ROM monitor, if any.
#define LINUX_REBOOT_CMD_HALT 0xCDEF0123 #define LINUX_REBOOT_CMD_HALT 0xCDEF0123
/// Ctrl-Alt-Del sequence causes RESTART command. /// Ctrl-Alt-Del sequence causes RESTART command.
#define LINUX_REBOOT_CMD_CAD_ON 0x89ABCDEF #define LINUX_REBOOT_CMD_CAD_ON 0x89ABCDEF
/// Ctrl-Alt-Del sequence sends SIGINT to init task. /// Ctrl-Alt-Del sequence sends SIGINT to init task.
#define LINUX_REBOOT_CMD_CAD_OFF 0x00000000 #define LINUX_REBOOT_CMD_CAD_OFF 0x00000000
/// Stop OS and remove all power from system, if possible. /// Stop OS and remove all power from system, if possible.
#define LINUX_REBOOT_CMD_POWER_OFF 0x4321FEDC #define LINUX_REBOOT_CMD_POWER_OFF 0x4321FEDC
/// Restart system using given command string. /// Restart system using given command string.
#define LINUX_REBOOT_CMD_RESTART2 0xA1B2C3D4 #define LINUX_REBOOT_CMD_RESTART2 0xA1B2C3D4
/// Suspend system using software suspend if compiled in. /// Suspend system using software suspend if compiled in.
#define LINUX_REBOOT_CMD_SW_SUSPEND 0xD000FCE2 #define LINUX_REBOOT_CMD_SW_SUSPEND 0xD000FCE2
/// Restart system using a previously loaded Linux kernel /// Restart system using a previously loaded Linux kernel
#define LINUX_REBOOT_CMD_KEXEC 0x45584543 #define LINUX_REBOOT_CMD_KEXEC 0x45584543
+132 -132
View File
@@ -1,132 +1,132 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file shm.h /// @file shm.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "ipc.h" #include "ipc.h"
#include "debug.h" #include "debug.h"
#include "clock.h" #include "clock.h"
#include "kheap.h" #include "kheap.h"
#include "stddef.h" #include "stddef.h"
#include "paging.h" #include "paging.h"
#include "syscall.h" #include "syscall.h"
#include "scheduler.h" #include "scheduler.h"
//======== Permission flag for shmget ========================================== //======== Permission flag for shmget ==========================================
// or S_IRUGO from <linux/stat.h>. // or S_IRUGO from <linux/stat.h>.
#define SHM_R 0400 #define SHM_R 0400
// or S_IWUGO from <linux/stat.h>. // or S_IWUGO from <linux/stat.h>.
#define SHM_W 0200 #define SHM_W 0200
//============================================================================== //==============================================================================
//======== Flags for shmat ===================================================== //======== Flags for shmat =====================================================
// Attach read-only else read-write. // Attach read-only else read-write.
#define SHM_RDONLY 010000 #define SHM_RDONLY 010000
// Round attach address to SHMLBA. // Round attach address to SHMLBA.
#define SHM_RND 020000 #define SHM_RND 020000
// Take-over region on attach. // Take-over region on attach.
#define SHM_REMAP 040000 #define SHM_REMAP 040000
// Execution access. // Execution access.
#define SHM_EXEC 0100000 #define SHM_EXEC 0100000
//============================================================================== //==============================================================================
//======== Commands for shmctl ================================================= //======== Commands for shmctl =================================================
// Lock segment (root only). // Lock segment (root only).
#define SHM_LOCK 11 #define SHM_LOCK 11
// Unlock segment (root only). // Unlock segment (root only).
#define SHM_UNLOCK 12 #define SHM_UNLOCK 12
//============================================================================== //==============================================================================
// Ipcs ctl commands. // Ipcs ctl commands.
#define SHM_STAT 13 #define SHM_STAT 13
#define SHM_INFO 14 #define SHM_INFO 14
#define SHM_STAT_ANY 15 #define SHM_STAT_ANY 15
//======== shm_mode upper byte flags =========================================== //======== shm_mode upper byte flags ===========================================
// segment will be destroyed on last detach. // segment will be destroyed on last detach.
#define SHM_DEST 01000 #define SHM_DEST 01000
// Segment will not be swapped. // Segment will not be swapped.
#define SHM_LOCKED 02000 #define SHM_LOCKED 02000
// Segment is mapped via hugetlb. // Segment is mapped via hugetlb.
#define SHM_HUGETLB 04000 #define SHM_HUGETLB 04000
// Don't check for reservations. // Don't check for reservations.
#define SHM_NORESERVE 010000 #define SHM_NORESERVE 010000
typedef unsigned long shmatt_t; typedef unsigned long shmatt_t;
struct shmid_ds { struct shmid_ds {
// Operation permission struct. // Operation permission struct.
struct ipc_perm shm_perm; struct ipc_perm shm_perm;
// Size of segment in bytes. // Size of segment in bytes.
size_t shm_segsz; size_t shm_segsz;
// Time of last shmat(). // Time of last shmat().
time_t shm_atime; time_t shm_atime;
// Time of last shmdt(). // Time of last shmdt().
time_t shm_dtime; time_t shm_dtime;
// Time of last change by shmctl(). // Time of last change by shmctl().
time_t shm_ctime; time_t shm_ctime;
// Pid of creator. // Pid of creator.
pid_t shm_cpid; pid_t shm_cpid;
// Pid of last shmop. // Pid of last shmop.
pid_t shm_lpid; pid_t shm_lpid;
// Number of current attaches. // Number of current attaches.
shmatt_t shm_nattch; shmatt_t shm_nattch;
struct shmid_ds *next; struct shmid_ds *next;
// Where shm created is memorized, should be a file. // Where shm created is memorized, should be a file.
void *shm_location; void *shm_location;
}; };
/// @@brief Syscall Service Routine: Shared memory control operation. /// @@brief Syscall Service Routine: Shared memory control operation.
int syscall_shmctl(int *args); int syscall_shmctl(int *args);
/// @@brief Syscall Service Routine: Get shared memory segment. /// @@brief Syscall Service Routine: Get shared memory segment.
int syscall_shmget(int *args); int syscall_shmget(int *args);
/// @@brief Syscall Service Routine: Attach shared memory segment. /// @@brief Syscall Service Routine: Attach shared memory segment.
void *syscall_shmat(int *args); void *syscall_shmat(int *args);
/// @@brief Syscall Service Routine: Detach shared memory segment. /// @@brief Syscall Service Routine: Detach shared memory segment.
int syscall_shmdt(int *args); int syscall_shmdt(int *args);
/// @@brief User Wrapper: Shared memory control operation. /// @@brief User Wrapper: Shared memory control operation.
int shmctl(int shmid, int cmd, struct shmid_ds *buf); int shmctl(int shmid, int cmd, struct shmid_ds *buf);
/// @@brief User Wrapper: Get shared memory segment. /// @@brief User Wrapper: Get shared memory segment.
int shmget(key_t key, size_t size, int flags); int shmget(key_t key, size_t size, int flags);
/// @@brief User Wrapper: Attach shared memory segment. /// @@brief User Wrapper: Attach shared memory segment.
void *shmat(int shmid, void *shmaddr, int flag); void *shmat(int shmid, void *shmaddr, int flag);
/// @@brief User Wrapper: Detach shared memory segment. /// @@brief User Wrapper: Detach shared memory segment.
int shmdt(void *shmaddr); int shmdt(void *shmaddr);
/// @@brief Find shmid_ds on list. /// @@brief Find shmid_ds on list.
struct shmid_ds *find_shm_fromid(int shmid); struct shmid_ds *find_shm_fromid(int shmid);
/// @@brief Find shmid_ds on list. /// @@brief Find shmid_ds on list.
struct shmid_ds *find_shm_fromkey(key_t key); struct shmid_ds *find_shm_fromkey(key_t key);
/// @@brief shmid_ds on list. /// @@brief shmid_ds on list.
struct shmid_ds *find_shm_fromvaddr(void *shmvaddr); struct shmid_ds *find_shm_fromvaddr(void *shmvaddr);
+41 -42
View File
@@ -1,42 +1,41 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file stat.h /// @file stat.h
/// @brief Stat functions. /// @brief Stat functions.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "clock.h" #include "clock.h"
#include "stddef.h" #include "stddef.h"
/// @brief Data structure which contains information about a file. /// @brief Data structure which contains information about a file.
typedef struct stat_t typedef struct stat_t
{ {
/// ID of device containing file. /// ID of device containing file.
dev_t st_dev; dev_t st_dev;
/// Fle serial number. /// Fle serial number.
ino_t st_ino; ino_t st_ino;
/// Mode of file. /// Mode of file.
mode_t st_mode; mode_t st_mode;
/// User id del file. /// User id del file.
uid_t st_uid; uid_t st_uid;
/// Group id del file. /// Group id del file.
gid_t st_gid; gid_t st_gid;
/// Dimensione del file. /// Dimensione del file.
off_t st_size; off_t st_size;
/// Time of last access. /// Time of last access.
time_t st_atime; time_t st_atime;
/// Time of last data modification. /// Time of last data modification.
time_t st_mtime; time_t st_mtime;
/// Time of last status change. /// Time of last status change.
time_t st_ctime; time_t st_ctime;
} stat_t; } stat_t;
/// @brief Retrieves information about the file at the given location. /// @brief Retrieves information about the file at the given location.
/// @param path The file descriptor of the file that is being inquired. /// @param path The file descriptor of the file that is being inquired.
/// @param buf A structure where data about the file will be stored. /// @param buf A structure where data about the file will be stored.
/// @return Returns a negative value on failure. /// @return Returns a negative value on failure.
int stat(const char *path, stat_t *buf); int stat(const char *path, stat_t *buf);
// TODO: doxygen comment. int mkdir(const char *path, mode_t mode);
int mkdir(const char *path, mode_t mode);
+67 -67
View File
@@ -1,67 +1,67 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file types.h /// @file types.h
/// @brief Collection of Kernel datatype /// @brief Collection of Kernel datatype
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/// The type of process id. /// The type of process id.
typedef signed int pid_t; typedef signed int pid_t;
/// The type of process user variable. /// The type of process user variable.
typedef unsigned int user_t; typedef unsigned int user_t;
/// The type of process status. /// The type of process status.
typedef unsigned int status_t; typedef unsigned int status_t;
/// Defines the list of flags of a process. /// Defines the list of flags of a process.
typedef enum eflags_list { typedef enum eflags_list {
/// Carry flag. /// Carry flag.
EFLAG_CF = (1 << 0), EFLAG_CF = (1 << 0),
/// Parity flag. /// Parity flag.
EFLAG_PF = (1 << 2), EFLAG_PF = (1 << 2),
/// Auxiliary carry flag. /// Auxiliary carry flag.
EFLAG_AF = (1 << 4), EFLAG_AF = (1 << 4),
/// Zero flag. /// Zero flag.
EFLAG_ZF = (1 << 6), EFLAG_ZF = (1 << 6),
/// Sign flag. /// Sign flag.
EFLAG_SF = (1 << 7), EFLAG_SF = (1 << 7),
/// Trap flag. /// Trap flag.
EFLAG_TF = (1 << 8), EFLAG_TF = (1 << 8),
/// Interrupt enable flag. /// Interrupt enable flag.
EFLAG_IF = (1 << 9), EFLAG_IF = (1 << 9),
/// Direction flag. /// Direction flag.
EFLAG_DF = (1 << 10), EFLAG_DF = (1 << 10),
/// Overflow flag. /// Overflow flag.
EFLAG_OF = (1 << 11), EFLAG_OF = (1 << 11),
/// Nested task flag. /// Nested task flag.
EFLAG_NT = (1 << 14), EFLAG_NT = (1 << 14),
/// Resume flag. /// Resume flag.
EFLAG_RF = (1 << 16), EFLAG_RF = (1 << 16),
/// Virtual 8086 mode flag. /// Virtual 8086 mode flag.
EFLAG_VM = (1 << 17), EFLAG_VM = (1 << 17),
/// Alignment check flag (486+). /// Alignment check flag (486+).
EFLAG_AC = (1 << 18), EFLAG_AC = (1 << 18),
/// Virutal interrupt flag. /// Virutal interrupt flag.
EFLAG_VIF = (1 << 19), EFLAG_VIF = (1 << 19),
/// Virtual interrupt pending flag. /// Virtual interrupt pending flag.
EFLAG_VIP = (1 << 20), EFLAG_VIP = (1 << 20),
/// ID flag. /// ID flag.
EFLAG_ID = (1 << 21), EFLAG_ID = (1 << 21),
} eflags_list; } eflags_list;
+95 -95
View File
@@ -1,95 +1,95 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file unistd.h /// @file unistd.h
/// @brief Functions used to manage files. /// @brief Functions used to manage files.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "types.h" #include "types.h"
#include "stddef.h" #include "stddef.h"
//======== Standard file descriptors =========================================== //======== Standard file descriptors ===========================================
/// Standard input. /// Standard input.
#define STDIN_FILENO -3 #define STDIN_FILENO -3
/// Standard output. /// Standard output.
#define STDOUT_FILENO -2 #define STDOUT_FILENO -2
/// Standard error output. /// Standard error output.
#define STDERR_FILENO -1 #define STDERR_FILENO -1
//============================================================================== //==============================================================================
/// Maximum number of opened file. /// Maximum number of opened file.
#define MAX_OPEN_FD 4 #define MAX_OPEN_FD 4
/// @brief Read data from a file descriptor. /// @brief Read data from a file descriptor.
/// @param fd The file descriptor. /// @param fd The file descriptor.
/// @param buf The buffer. /// @param buf The buffer.
/// @param nbytes The number of bytes to read. /// @param nbytes The number of bytes to read.
/// @return The number of read characters. /// @return The number of read characters.
ssize_t read(int fd, void *buf, size_t nbytes); ssize_t read(int fd, void *buf, size_t nbytes);
/// @brief Write data into a file descriptor. /// @brief Write data into a file descriptor.
/// @param fd The file descriptor. /// @param fd The file descriptor.
/// @param buf The buffer collecting data to written. /// @param buf The buffer collecting data to written.
/// @param nbytes The number of bytes to write. /// @param nbytes The number of bytes to write.
/// @return The number of written bytes. /// @return The number of written bytes.
ssize_t write(int fd, void *buf, size_t nbytes); ssize_t write(int fd, void *buf, size_t nbytes);
/// @brief Opens the file specified by pathname. /// @brief Opens the file specified by pathname.
/// @param pathname A pathname for a file. /// @param pathname A pathname for a file.
/// @param flags Used to set the file status flags and file access modes /// @param flags Used to set the file status flags and file access modes
/// of the open file description. /// of the open file description.
/// @param mode Specifies the file mode bits be applied when a new file /// @param mode Specifies the file mode bits be applied when a new file
/// is created. /// is created.
/// @return Returns a file descriptor, a small, nonnegative integer for /// @return Returns a file descriptor, a small, nonnegative integer for
/// use in subsequent system calls. /// use in subsequent system calls.
int open(const char *pathname, int flags, mode_t mode); int open(const char *pathname, int flags, mode_t mode);
/// @brief Close a file descriptor. /// @brief Close a file descriptor.
/// @param fildes The file descriptor. /// @param fd The file descriptor.
/// @return The result of the operation. /// @return The result of the operation.
int close(int fildes); int close(int fd);
/// @brief Removes the given directory. /// @brief Removes the given directory.
/// @param path The path to the directory to remove. /// @param path The path to the directory to remove.
/// @return /// @return
int rmdir(const char *path); int rmdir(const char *path);
/// @brief Wrapper for exit system call. /// @brief Wrapper for exit system call.
extern void exit(int status); extern void exit(int status);
/// @brief Return the process identifier of the calling process. /// @brief Return the process identifier of the calling process.
/// @return pid_t process identifier. /// @return pid_t process identifier.
extern pid_t getpid(); extern pid_t getpid();
/// @brief Clone the calling process, but without copying the whole address space. /// @brief Clone the calling process, but without copying the whole address space.
/// The calling process is suspended until the new process exits or is /// The calling process is suspended until the new process exits or is
/// replaced by a call to `execve'. Return -1 for errors, 0 to the new /// replaced by a call to `execve'. Return -1 for errors, 0 to the new
/// process, and the process ID of the new process to the old process. /// process, and the process ID of the new process to the old process.
/// @return /// @return
extern pid_t vfork(); extern pid_t vfork();
/// @brief Replaces the current process image with a new process image. /// @brief Replaces the current process image with a new process image.
/// @param path The path to the binary file to execute. /// @param path The path to the binary file to execute.
/// @param argv The list of arguments. /// @param argv The list of arguments.
/// @param envp /// @param envp
/// @return /// @return
extern int execve(const char *path, char *const argv[], char *const envp[]); extern int execve(const char *path, char *const argv[], char *const envp[]);
/// @brief Adds inc to the nice value for the calling thread. /// @brief Adds inc to the nice value for the calling thread.
/// @param inc The value to add to the nice. /// @param inc The value to add to the nice.
/// @return On success, the new nice value is returned. On error, -1 is /// @return On success, the new nice value is returned. On error, -1 is
/// returned, and errno is set appropriately. /// returned, and errno is set appropriately.
int nice(int inc); int nice(int inc);
/// @brief Reboot system call. /// @brief Reboot system call.
/// @param cmd /// @param cmd
/// @param arg /// @param arg
/// @return /// @return
int reboot(int magic1, int magic2, unsigned int cmd, void *arg); int reboot(int magic1, int magic2, unsigned int cmd, void *arg);
void getcwd(char *path, size_t size); void getcwd(char *path, size_t size);
void chdir(char const *path); void chdir(char const *path);
+28 -29
View File
@@ -1,29 +1,28 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file utsname.h /// @file utsname.h
/// @brief Functions used to provide information about the machine & OS. /// @brief Functions used to provide information about the machine & OS.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/// Maximum length of the string used by utsname. /// Maximum length of the string used by utsname.
#define SYS_LEN 257 #define SYS_LEN 257
/// @brief Holds information concerning the machine and the os. /// @brief Holds information concerning the machine and the os.
typedef struct utsname_t typedef struct utsname_t {
{ /// The name of the system.
/// The name of the system. char sysname[SYS_LEN];
char sysname[SYS_LEN];
/// The name of the node.
/// The name of the node. char nodename[SYS_LEN];
char nodename[SYS_LEN];
/// The version of the OS.
/// The version of the OS. char version[SYS_LEN];
char version[SYS_LEN];
/// The name of the machine.
/// The name of the machine. char machine[SYS_LEN];
char machine[SYS_LEN]; } utsname_t;
} utsname_t;
/// @brief Sets the values of os_infos.
/// @brief Sets the values of os_infos. int uname(utsname_t *os_infos);
int uname(utsname_t *os_infos);
+60 -60
View File
@@ -1,60 +1,60 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file wait.h /// @file wait.h
/// @brief /// @brief
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
#include "types.h" #include "types.h"
/// @brief Return immediately if no child is there to be waited for. /// @brief Return immediately if no child is there to be waited for.
#define WNOHANG 0x00000001 #define WNOHANG 0x00000001
/// @brief Return for children that are stopped, and whose status has not /// @brief Return for children that are stopped, and whose status has not
/// been reported. /// been reported.
#define WUNTRACED 0x00000002 #define WUNTRACED 0x00000002
/// @brief returns true if the child process exited because of a signal that /// @brief returns true if the child process exited because of a signal that
/// was not caught. /// was not caught.
#define WIFSIGNALED(status) (!WIFSTOPPED(status) && !WIFEXITED(status)) #define WIFSIGNALED(status) (!WIFSTOPPED(status) && !WIFEXITED(status))
/// @brief returns true if the child process that caused the return is /// @brief returns true if the child process that caused the return is
/// currently stopped; this is only possible if the call was done using /// currently stopped; this is only possible if the call was done using
/// WUNTRACED(). /// WUNTRACED().
#define WIFSTOPPED(status) (((status)&0xff) == 0x7f) #define WIFSTOPPED(status) (((status)&0xff) == 0x7f)
/// @brief evaluates to the least significant eight bits of the return code /// @brief evaluates to the least significant eight bits of the return code
/// of the child that terminated, which may have been set as the argument /// of the child that terminated, which may have been set as the argument
/// to a call to exit() or as the argument for a return statement in the /// to a call to exit() or as the argument for a return statement in the
/// main program. This macro can only be evaluated if WIFEXITED() /// main program. This macro can only be evaluated if WIFEXITED()
/// returned nonzero. /// returned nonzero.
#define WEXITSTATUS(status) (((status)&0xff00) >> 8) #define WEXITSTATUS(status) (((status)&0xff00) >> 8)
/// @brief returns the number of the signal that caused the child process to /// @brief returns the number of the signal that caused the child process to
/// terminate. This macro can only be evaluated if WIFSIGNALED() returned /// terminate. This macro can only be evaluated if WIFSIGNALED() returned
/// nonzero. /// nonzero.
#define WTERMSIG(status) ((status)&0x7f) #define WTERMSIG(status) ((status)&0x7f)
/// @brief Is nonzero if the child exited normally. /// @brief Is nonzero if the child exited normally.
#define WIFEXITED(status) (WTERMSIG(status) == 0) #define WIFEXITED(status) (WTERMSIG(status) == 0)
/// @brief returns the number of the signal that caused the child to stop. /// @brief returns the number of the signal that caused the child to stop.
/// This macro can only be evaluated if WIFSTOPPED() returned nonzero. /// This macro can only be evaluated if WIFSTOPPED() returned nonzero.
#define WSTOPSIG(status) (WEXITSTATUS(status)) #define WSTOPSIG(status) (WEXITSTATUS(status))
extern pid_t wait(int *status); extern pid_t wait(int *status);
/// @brief Suspends the execution of the calling thread until a child /// @brief Suspends the execution of the calling thread until a child
/// specified by pid argument has changed state. /// specified by pid argument has changed state.
/// @details /// @details
/// By default, waitpid() waits only for terminated children, but this /// By default, waitpid() waits only for terminated children, but this
/// behavior is modifiable via the options argument, as described below. /// behavior is modifiable via the options argument, as described below.
/// The value of pid can be: /// The value of pid can be:
/// - 1 meaning wait for any child process. /// - 1 meaning wait for any child process.
/// 0 meaning wait for any child process whose process group ID is /// 0 meaning wait for any child process whose process group ID is
/// equal to that of the calling process. /// equal to that of the calling process.
/// > 0 meaning wait for the child whose process ID is equal to the /// > 0 meaning wait for the child whose process ID is equal to the
/// value of pid. /// value of pid.
/// @return On error, -1 is returned. /// @return On error, -1 is returned.
extern pid_t waitpid(pid_t pid, int *status, int options); extern pid_t waitpid(pid_t pid, int *status, int options);
+12 -12
View File
@@ -1,12 +1,12 @@
/// MentOS, The Mentoring Operating system project /// MentOS, The Mentoring Operating system project
/// @file panic.h /// @file panic.h
/// @brief Functions used to manage kernel panic. /// @brief Functions used to manage kernel panic.
/// @copyright (c) 2019 This file is distributed under the MIT License. /// @copyright (c) 2019 This file is distributed under the MIT License.
/// See LICENSE.md for details. /// See LICENSE.md for details.
#pragma once #pragma once
/// @brief Prints the given message and then safely stop the execution of /// @brief Prints the given message and then safely stop the execution of
/// the kernel. /// the kernel.
/// @param msg The message that has to be shown. /// @param msg The message that has to be shown.
void kernel_panic(const char *msg); void kernel_panic(const char *msg);

Some files were not shown because too many files have changed in this diff Show More