Просмотр исходного кода

style: reformat all codes with new format

greatbridf 7 месяцев назад
Родитель
Сommit
538244e339
71 измененных файлов с 1739 добавлено и 2289 удалено
  1. 23 132
      .clang-format
  2. 13 14
      include/fs/fat.hpp
  3. 11 11
      include/kernel/async/lock.hpp
  4. 4 4
      include/kernel/async/waitlist.hpp
  5. 3 5
      include/kernel/hw/pci.hpp
  6. 15 33
      include/kernel/hw/port.hpp
  7. 1 1
      include/kernel/hw/timer.hpp
  8. 27 25
      include/kernel/input/keycodes.h
  9. 1 1
      include/kernel/irq.hpp
  10. 9 6
      include/kernel/log.hpp
  11. 28 25
      include/kernel/mem/mm_list.hpp
  12. 50 50
      include/kernel/mem/paging.hpp
  13. 5 15
      include/kernel/mem/phys.hpp
  14. 0 3
      include/kernel/mem/slab.hpp
  15. 3 3
      include/kernel/mem/types.hpp
  16. 28 17
      include/kernel/mem/vm_area.hpp
  17. 2 2
      include/kernel/module.hpp
  18. 30 40
      include/kernel/process.hpp
  19. 16 13
      include/kernel/signal.hpp
  20. 76 77
      include/kernel/syscall.hpp
  21. 1 1
      include/kernel/task/readyqueue.hpp
  22. 13 13
      include/kernel/task/thread.hpp
  23. 8 14
      include/kernel/tty.hpp
  24. 34 25
      include/kernel/vfs.hpp
  25. 5 4
      include/kernel/vfs/dentry.hpp
  26. 21 26
      include/kernel/vfs/file.hpp
  27. 7 6
      include/kernel/vfs/filearr.hpp
  28. 8 8
      include/kernel/vfs/inode.hpp
  29. 19 16
      include/kernel/vfs/vfs.hpp
  30. 7 7
      include/types/allocator.hpp
  31. 17 22
      include/types/bitmap.hpp
  32. 36 62
      include/types/buffer.hpp
  33. 1 1
      include/types/cplusplus.hpp
  34. 4 8
      include/types/hash.hpp
  35. 4 7
      include/types/list.hpp
  36. 16 19
      include/types/path.hpp
  37. 36 48
      src/fs/fat.cpp
  38. 29 41
      src/fs/procfs.cc
  39. 42 60
      src/kernel/allocator.cc
  40. 19 38
      src/kernel/async/lock.cc
  41. 5 10
      src/kernel/async/waitlist.cc
  42. 57 64
      src/kernel/hw/ahci.cc
  43. 18 29
      src/kernel/hw/pci.cc
  44. 19 33
      src/kernel/hw/serial.cc
  45. 3 6
      src/kernel/hw/timer.cc
  46. 26 29
      src/kernel/interrupt.cpp
  47. 38 60
      src/kernel/mem/mm_list.cc
  48. 57 82
      src/kernel/mem/paging.cc
  49. 8 13
      src/kernel/mem/slab.cc
  50. 1 1
      src/kernel/module.cc
  51. 56 66
      src/kernel/process.cpp
  52. 38 43
      src/kernel/signal.cpp
  53. 86 87
      src/kernel/syscall.cpp
  54. 114 137
      src/kernel/syscall/fileops.cc
  55. 7 8
      src/kernel/syscall/infoops.cc
  56. 5 8
      src/kernel/syscall/mount.cc
  57. 89 112
      src/kernel/syscall/procops.cc
  58. 5 10
      src/kernel/task/readyqueue.cc
  59. 61 73
      src/kernel/task/thread.cc
  60. 64 68
      src/kernel/tty.cpp
  61. 4 4
      src/kernel/user/thread_local.cc
  62. 87 127
      src/kernel/vfs.cpp
  63. 29 43
      src/kernel/vfs/dentry.cc
  64. 34 62
      src/kernel/vfs/filearr.cc
  65. 3 5
      src/kernel/vfs/inode.cc
  66. 32 44
      src/kernel/vfs/tmpfs.cc
  67. 29 49
      src/kernel/vfs/vfs.cc
  68. 16 20
      src/kernel/vga.cpp
  69. 49 57
      src/kinit.cpp
  70. 14 25
      src/types/elf.cpp
  71. 13 11
      src/types/libstdcpp.cpp

+ 23 - 132
.clang-format

@@ -1,137 +1,28 @@
 ---
-Language:        Cpp
-# BasedOnStyle:  WebKit
-AccessModifierOffset: -4
-AlignAfterOpenBracket: DontAlign
-AlignConsecutiveMacros: false
-AlignConsecutiveAssignments: false
-AlignConsecutiveDeclarations: false
-AlignEscapedNewlines: Right
-AlignOperands:   false
-AlignTrailingComments: false
-AllowAllArgumentsOnNextLine: true
-AllowAllConstructorInitializersOnNextLine: true
-AllowAllParametersOfDeclarationOnNextLine: true
-AllowShortBlocksOnASingleLine: Empty
-AllowShortCaseLabelsOnASingleLine: false
-AllowShortFunctionsOnASingleLine: All
-AllowShortLambdasOnASingleLine: All
+BasedOnStyle: Google
+AllowShortBlocksOnASingleLine: 'false'
+AllowShortCaseLabelsOnASingleLine: 'false'
+AllowShortFunctionsOnASingleLine: Inline
 AllowShortIfStatementsOnASingleLine: Never
-AllowShortLoopsOnASingleLine: false
-AlwaysBreakAfterDefinitionReturnType: None
-AlwaysBreakAfterReturnType: None
-AlwaysBreakBeforeMultilineStrings: false
-AlwaysBreakTemplateDeclarations: MultiLine
-BinPackArguments: true
-BinPackParameters: true
-BraceWrapping:
-  AfterCaseLabel:  false
-  AfterClass:      false
-  AfterControlStatement: false
-  AfterEnum:       false
-  AfterFunction:   true
-  AfterNamespace:  false
-  AfterObjCDeclaration: false
-  AfterStruct:     false
-  AfterUnion:      false
-  AfterExternBlock: false
-  BeforeCatch:     false
-  BeforeElse:      false
-  IndentBraces:    false
-  SplitEmptyFunction: true
-  SplitEmptyRecord: true
-  SplitEmptyNamespace: true
-BreakBeforeBinaryOperators: All
-BreakBeforeBraces: WebKit
-BreakBeforeInheritanceComma: false
-BreakInheritanceList: BeforeColon
-BreakBeforeTernaryOperators: true
-BreakConstructorInitializersBeforeComma: false
+AllowShortLoopsOnASingleLine: 'false'
 BreakConstructorInitializers: BeforeComma
-BreakAfterJavaFieldAnnotations: false
-BreakStringLiterals: true
-ColumnLimit:     0
-CommentPragmas:  '^ IWYU pragma:'
-CompactNamespaces: false
-ConstructorInitializerAllOnOneLineOrOnePerLine: false
-ConstructorInitializerIndentWidth: 4
-ContinuationIndentWidth: 4
-Cpp11BracedListStyle: false
-DeriveLineEnding: true
-DerivePointerAlignment: false
-DisableFormat:   false
-ExperimentalAutoDetectBinPacking: false
-FixNamespaceComments: false
-ForEachMacros:
-  - foreach
-  - Q_FOREACH
-  - BOOST_FOREACH
-IncludeBlocks:   Preserve
-IncludeCategories:
-  - Regex:           '^"(llvm|llvm-c|clang|clang-c)/'
-    Priority:        2
-    SortPriority:    0
-  - Regex:           '^(<|"(gtest|gmock|isl|json)/)'
-    Priority:        3
-    SortPriority:    0
-  - Regex:           '.*'
-    Priority:        1
-    SortPriority:    0
-IncludeIsMainRegex: '(Test)?$'
-IncludeIsMainSourceRegex: ''
-IndentCaseLabels: false
-IndentGotoLabels: true
-IndentPPDirectives: None
-IndentWidth:     4
-IndentWrappedFunctionNames: false
-JavaScriptQuotes: Leave
-JavaScriptWrapImports: true
-KeepEmptyLinesAtTheStartOfBlocks: true
-MacroBlockBegin: ''
-MacroBlockEnd:   ''
-MaxEmptyLinesToKeep: 1
+FixNamespaceComments: 'true'
+IncludeBlocks: Regroup
+IndentWidth: '4'
 NamespaceIndentation: Inner
-ObjCBinPackProtocolList: Auto
-ObjCBlockIndentWidth: 4
-ObjCSpaceAfterProperty: true
-ObjCSpaceBeforeProtocolList: true
-PenaltyBreakAssignment: 2
-PenaltyBreakBeforeFirstCallParameter: 19
-PenaltyBreakComment: 300
-PenaltyBreakFirstLessLess: 120
-PenaltyBreakString: 1000
-PenaltyBreakTemplateDeclaration: 10
-PenaltyExcessCharacter: 1000000
-PenaltyReturnTypeOnItsOwnLine: 60
-PointerAlignment: Left
-ReflowComments:  true
-SortIncludes:    true
-SortUsingDeclarations: true
-SpaceAfterCStyleCast: false
-SpaceAfterLogicalNot: false
-SpaceAfterTemplateKeyword: true
-SpaceBeforeAssignmentOperators: true
-SpaceBeforeCpp11BracedList: true
-SpaceBeforeCtorInitializerColon: true
-SpaceBeforeInheritanceColon: true
-SpaceBeforeParens: ControlStatements
-SpaceBeforeRangeBasedForLoopColon: true
-SpaceInEmptyBlock: true
-SpaceInEmptyParentheses: false
-SpacesBeforeTrailingComments: 1
-SpacesInAngles:  false
-SpacesInConditionalStatement: false
-SpacesInContainerLiterals: true
-SpacesInCStyleCastParentheses: false
-SpacesInParentheses: false
-SpacesInSquareBrackets: false
-SpaceBeforeSquareBrackets: false
-Standard:        Latest
-StatementMacros:
-  - Q_UNUSED
-  - QT_REQUIRE_VERSION
-TabWidth:        8
-UseCRLF:         false
-UseTab:          Never
-...
+SpacesBeforeTrailingComments: '1'
+Language: Cpp
+Standard: Cpp11
+IncludeCategories:
+  - Regex: '^<types/'
+    Priority: '4'
+  - Regex: '^<(kernel|fs)/'
+    Priority: '5'
+  - Regex: '^<.*\.h>'
+    Priority: '3'
+  - Regex: '^<.*>'
+    Priority: '2'
+  - Regex: '.*'
+    Priority: '1'
 
+...

+ 13 - 14
include/fs/fat.hpp

@@ -107,11 +107,11 @@ struct PACKED directory_entry {
 
 // TODO: deallocate inodes when dentry is destroyed
 class fat32 : public virtual fs::vfs {
-private:
+   private:
     constexpr static size_t SECTOR_SIZE = 512;
     constexpr static cluster_t EOC = 0xffffff8;
 
-private:
+   private:
     uint32_t sector_cnt;
     uint32_t sectors_per_fat;
     uint32_t serial_number;
@@ -138,24 +138,21 @@ private:
     // buf MUST be larger than 4096 bytes
     void _raw_read_cluster(void* buf, cluster_t no);
 
-    ssize_t _read_sector_range(void* buf, size_t buf_size, uint32_t sector_offset, size_t sector_cnt);
+    ssize_t _read_sector_range(void* buf, size_t buf_size,
+                               uint32_t sector_offset, size_t sector_cnt);
 
     // buffered version, release_cluster(cluster_no) after used
     char* read_cluster(cluster_t no);
     void release_cluster(cluster_t no);
 
-    static constexpr cluster_t cl(const inode* ind)
-    {
-        return ind->ino;
-    }
+    static constexpr cluster_t cl(const inode* ind) { return ind->ino; }
 
-    static inline cluster_t _rearrange(directory_entry* d)
-    {
+    static inline cluster_t _rearrange(directory_entry* d) {
         return (((cluster_t)d->cluster_hi) << 16) + d->cluster_lo;
     }
 
-    static inline size_t _write_buf_n(char* buf, size_t buf_size, const char* src, size_t n)
-    {
+    static inline size_t _write_buf_n(char* buf, size_t buf_size,
+                                      const char* src, size_t n) {
         if (n <= buf_size) {
             memcpy(buf, src, n);
             return n;
@@ -165,11 +162,13 @@ private:
         }
     }
 
-public:
+   public:
     explicit fat32(dev_t device);
 
-    virtual ssize_t read(inode* file, char* buf, size_t buf_size, size_t count, off_t offset) override;
-    virtual ssize_t readdir(fs::inode* dir, size_t offset, const vfs::filldir_func& callback) override;
+    virtual ssize_t read(inode* file, char* buf, size_t buf_size, size_t count,
+                         off_t offset) override;
+    virtual ssize_t readdir(fs::inode* dir, size_t offset,
+                            const vfs::filldir_func& callback) override;
 };
 
 }; // namespace fs::fat

+ 11 - 11
include/kernel/async/lock.hpp

@@ -23,11 +23,11 @@ lock_context_t spin_lock_irqsave(spinlock_t& lock);
 void spin_unlock_irqrestore(spinlock_t& lock, lock_context_t context);
 
 class mutex {
-private:
+   private:
     spinlock_t m_lock;
 
-public:
-    constexpr mutex() : m_lock {0} { }
+   public:
+    constexpr mutex() : m_lock{0} {}
     mutex(const mutex&) = delete;
     ~mutex();
 
@@ -39,25 +39,25 @@ public:
 };
 
 class lock_guard {
-private:
+   private:
     mutex& m_mtx;
 
-public:
-    explicit inline lock_guard(mutex& mtx)
-        : m_mtx {mtx} { m_mtx.lock(); }
+   public:
+    explicit inline lock_guard(mutex& mtx) : m_mtx{mtx} { m_mtx.lock(); }
     lock_guard(const lock_guard&) = delete;
 
     inline ~lock_guard() { m_mtx.unlock(); }
 };
 
 class lock_guard_irq {
-private:
+   private:
     mutex& m_mtx;
     lock_context_t state;
 
-public:
-    explicit inline lock_guard_irq(mutex& mtx)
-        : m_mtx {mtx} { state = m_mtx.lock_irq(); }
+   public:
+    explicit inline lock_guard_irq(mutex& mtx) : m_mtx{mtx} {
+        state = m_mtx.lock_irq();
+    }
     lock_guard_irq(const lock_guard_irq&) = delete;
 
     inline ~lock_guard_irq() { m_mtx.unlock_irq(state); }

+ 4 - 4
include/kernel/async/waitlist.hpp

@@ -2,19 +2,19 @@
 
 #include <set>
 
-#include <kernel/task/forward.hpp>
 #include <kernel/async/lock.hpp>
+#include <kernel/task/forward.hpp>
 
 namespace kernel::async {
 
 class wait_list {
-private:
+   private:
     mutex m_mtx;
     std::set<task::thread*> m_subscribers;
 
     wait_list(const wait_list&) = delete;
 
-public:
+   public:
     explicit wait_list() = default;
 
     // @return whether the wait is interrupted
@@ -26,4 +26,4 @@ public:
     void notify_all();
 };
 
-} // namespace kernel
+} // namespace kernel::async

+ 3 - 5
include/kernel/hw/pci.hpp

@@ -33,10 +33,8 @@ union bar {
 struct config_reg {
     uint32_t addr_base;
 
-    explicit constexpr config_reg(
-        uint32_t bus, uint32_t dev, uint32_t func)
-        : addr_base(0x80000000U | (bus << 16) | (dev << 11) | (func << 8))
-    { }
+    explicit constexpr config_reg(uint32_t bus, uint32_t dev, uint32_t func)
+        : addr_base(0x80000000U | (bus << 16) | (dev << 11) | (func << 8)) {}
 
     // offset is in range from 0x00 to 0xff
     uint32_t read32(uint32_t offset) const;
@@ -76,7 +74,7 @@ struct device_header_type0 {
 };
 
 class pci_device {
-public:
+   public:
     config_reg reg;
 
     uint16_t vendor;

+ 15 - 33
include/kernel/hw/port.hpp

@@ -4,61 +4,43 @@
 
 namespace kernel::hw {
 
-inline uint32_t inl(uint16_t pn)
-{
+inline uint32_t inl(uint16_t pn) {
     uint32_t ret;
-    asm volatile("inl %1, %0"
-        : "=a"(ret)
-        : "d"(pn));
+    asm volatile("inl %1, %0" : "=a"(ret) : "d"(pn));
     return ret;
 }
 
-inline uint32_t outl(uint16_t pn, uint32_t n)
-{
-    asm volatile("outl %1, %0"
-        :
-        : "d"(pn), "a"(n));
+inline uint32_t outl(uint16_t pn, uint32_t n) {
+    asm volatile("outl %1, %0" : : "d"(pn), "a"(n));
     return n;
 }
 
-inline uint16_t inw(uint16_t pn)
-{
+inline uint16_t inw(uint16_t pn) {
     uint16_t ret;
-    asm volatile("inw %1, %0"
-        : "=a"(ret)
-        : "d"(pn));
+    asm volatile("inw %1, %0" : "=a"(ret) : "d"(pn));
     return ret;
 }
 
-inline uint16_t outw(uint16_t pn, uint16_t n)
-{
-    asm volatile("outw %1, %0"
-        :
-        : "d"(pn), "a"(n));
+inline uint16_t outw(uint16_t pn, uint16_t n) {
+    asm volatile("outw %1, %0" : : "d"(pn), "a"(n));
     return n;
 }
 
-inline uint8_t inb(uint16_t pn)
-{
+inline uint8_t inb(uint16_t pn) {
     uint8_t ret;
-    asm volatile("inb %1, %0"
-        : "=a"(ret)
-        : "d"(pn));
+    asm volatile("inb %1, %0" : "=a"(ret) : "d"(pn));
     return ret;
 }
 
-inline uint8_t outb(uint16_t pn, uint8_t n)
-{
-    asm volatile("outb %1, %0"
-        :
-        : "d"(pn), "a"(n));
+inline uint8_t outb(uint16_t pn, uint8_t n) {
+    asm volatile("outb %1, %0" : : "d"(pn), "a"(n));
     return n;
 }
 
 struct p32 {
     uint16_t mp;
 
-    explicit constexpr p32(uint16_t p) : mp(p) { }
+    explicit constexpr p32(uint16_t p) : mp(p) {}
     inline uint32_t operator*() const { return inl(mp); }
     inline uint32_t operator=(uint32_t n) const { return outl(mp, n); }
 };
@@ -66,7 +48,7 @@ struct p32 {
 struct p16 {
     uint16_t mp;
 
-    explicit constexpr p16(uint16_t p) : mp(p) { }
+    explicit constexpr p16(uint16_t p) : mp(p) {}
     inline uint16_t operator*() const { return inw(mp); }
     inline uint16_t operator=(uint16_t n) const { return outw(mp, n); }
 };
@@ -74,7 +56,7 @@ struct p16 {
 struct p8 {
     uint16_t mp;
 
-    explicit constexpr p8(uint16_t p) : mp(p) { }
+    explicit constexpr p8(uint16_t p) : mp(p) {}
     inline uint8_t operator*() const { return inb(mp); }
     inline uint8_t operator=(uint8_t n) const { return outb(mp, n); }
 };

+ 1 - 1
include/kernel/hw/timer.hpp

@@ -8,4 +8,4 @@ void inc_tick(void);
 
 std::size_t current_ticks(void);
 
-}
+} // namespace kernel::hw::timer

+ 27 - 25
include/kernel/input/keycodes.h

@@ -135,20 +135,20 @@
 #define KEY_STOP 128 /* AC Stop */
 #define KEY_AGAIN 129
 #define KEY_PROPS 130 /* AC Properties */
-#define KEY_UNDO 131 /* AC Undo */
+#define KEY_UNDO 131  /* AC Undo */
 #define KEY_FRONT 132
-#define KEY_COPY 133 /* AC Copy */
-#define KEY_OPEN 134 /* AC Open */
+#define KEY_COPY 133  /* AC Copy */
+#define KEY_OPEN 134  /* AC Open */
 #define KEY_PASTE 135 /* AC Paste */
-#define KEY_FIND 136 /* AC Search */
-#define KEY_CUT 137 /* AC Cut */
-#define KEY_HELP 138 /* AL Integrated Help Center */
-#define KEY_MENU 139 /* Menu (show menu) */
-#define KEY_CALC 140 /* AL Calculator */
+#define KEY_FIND 136  /* AC Search */
+#define KEY_CUT 137   /* AC Cut */
+#define KEY_HELP 138  /* AL Integrated Help Center */
+#define KEY_MENU 139  /* Menu (show menu) */
+#define KEY_CALC 140  /* AL Calculator */
 #define KEY_SETUP 141
-#define KEY_SLEEP 142 /* SC System Sleep */
+#define KEY_SLEEP 142  /* SC System Sleep */
 #define KEY_WAKEUP 143 /* System Wake Up */
-#define KEY_FILE 144 /* AL Local Machine Browser */
+#define KEY_FILE 144   /* AL Local Machine Browser */
 #define KEY_SENDFILE 145
 #define KEY_DELETEFILE 146
 #define KEY_XFER 147
@@ -164,7 +164,7 @@
 #define KEY_MAIL 155
 #define KEY_BOOKMARKS 156 /* AC Bookmarks */
 #define KEY_COMPUTER 157
-#define KEY_BACK 158 /* AC Back */
+#define KEY_BACK 158    /* AC Back */
 #define KEY_FORWARD 159 /* AC Forward */
 #define KEY_CLOSECD 160
 #define KEY_EJECTCD 161
@@ -177,17 +177,17 @@
 #define KEY_REWIND 168
 #define KEY_PHONE 169 /* Media Select Telephone */
 #define KEY_ISO 170
-#define KEY_CONFIG 171 /* AL Consumer Control Configuration */
+#define KEY_CONFIG 171   /* AL Consumer Control Configuration */
 #define KEY_HOMEPAGE 172 /* AC Home */
-#define KEY_REFRESH 173 /* AC Refresh */
-#define KEY_EXIT 174 /* AC Exit */
+#define KEY_REFRESH 173  /* AC Refresh */
+#define KEY_EXIT 174     /* AC Exit */
 #define KEY_MOVE 175
 #define KEY_EDIT 176
 #define KEY_SCROLLUP 177
 #define KEY_SCROLLDOWN 178
 #define KEY_KPLEFTPAREN 179
 #define KEY_KPRIGHTPAREN 180
-#define KEY_NEW 181 /* AC New */
+#define KEY_NEW 181  /* AC New */
 #define KEY_REDO 182 /* AC Redo/Repeat */
 
 #define KEY_F13 183
@@ -231,16 +231,17 @@
 #define KEY_BRIGHTNESSUP 225
 #define KEY_MEDIA 226
 
-#define KEY_SWITCHVIDEOMODE 227 /* Cycle between available video \
-                                   outputs (Monitor/LCD/TV-out/etc) */
+#define KEY_SWITCHVIDEOMODE              \
+    227 /* Cycle between available video \
+           outputs (Monitor/LCD/TV-out/etc) */
 #define KEY_KBDILLUMTOGGLE 228
 #define KEY_KBDILLUMDOWN 229
 #define KEY_KBDILLUMUP 230
 
-#define KEY_SEND 231 /* AC Send */
-#define KEY_REPLY 232 /* AC Reply */
+#define KEY_SEND 231        /* AC Send */
+#define KEY_REPLY 232       /* AC Reply */
 #define KEY_FORWARDMAIL 233 /* AC Forward Msg */
-#define KEY_SAVE 234 /* AC Save */
+#define KEY_SAVE 234        /* AC Save */
 #define KEY_DOCUMENTS 235
 
 #define KEY_BATTERY 236
@@ -251,12 +252,13 @@
 
 #define KEY_UNKNOWN 240
 
-#define KEY_VIDEO_NEXT 241 /* drive next video source */
-#define KEY_VIDEO_PREV 242 /* drive previous video source */
+#define KEY_VIDEO_NEXT 241       /* drive next video source */
+#define KEY_VIDEO_PREV 242       /* drive previous video source */
 #define KEY_BRIGHTNESS_CYCLE 243 /* brightness up, after max is min */
-#define KEY_BRIGHTNESS_AUTO 244 /* Set Auto Brightness: manual \
-                                  brightness control is off,   \
-                                  rely on ambient */
+#define KEY_BRIGHTNESS_AUTO            \
+    244 /* Set Auto Brightness: manual \
+          brightness control is off,   \
+          rely on ambient */
 #define KEY_BRIGHTNESS_ZERO KEY_BRIGHTNESS_AUTO
 #define KEY_DISPLAY_OFF 245 /* display device to off state */
 

+ 1 - 1
include/kernel/irq.hpp

@@ -8,4 +8,4 @@ using irq_handler_t = std::function<void()>;
 
 void register_handler(int irqno, irq_handler_t handler);
 
-};
+}; // namespace kernel::irq

+ 9 - 6
include/kernel/log.hpp

@@ -4,14 +4,17 @@
 
 #include <kernel/tty.hpp>
 
-#define kmsgf(fmt, ...) \
-    if (1) {\
-        char buf[512]; \
-        snprintf(buf, sizeof(buf), fmt "\n" __VA_OPT__(,) __VA_ARGS__); \
-        if (kernel::tty::console) kernel::tty::console->print(buf); \
+#define kmsgf(fmt, ...)                                                  \
+    if (1) {                                                             \
+        char buf[512];                                                   \
+        snprintf(buf, sizeof(buf), fmt "\n" __VA_OPT__(, ) __VA_ARGS__); \
+        if (kernel::tty::console)                                        \
+            kernel::tty::console->print(buf);                            \
     }
 
-#define kmsg(msg) if (kernel::tty::console) kernel::tty::console->print(msg "\n")
+#define kmsg(msg)             \
+    if (kernel::tty::console) \
+    kernel::tty::console->print(msg "\n")
 
 #ifdef NDEBUG
 #define kmsgf_debug(...)

+ 28 - 25
include/kernel/mem/mm_list.hpp

@@ -1,31 +1,37 @@
 #pragma once
 
+#include "paging.hpp"
+#include "vm_area.hpp"
+
 #include <set>
 
 #include <stdint.h>
 
-#include "vm_area.hpp"
-#include "paging.hpp"
-
 namespace kernel::mem {
 
-constexpr uintptr_t KERNEL_SPACE_START    = 0x8000000000000000ULL;
+constexpr uintptr_t KERNEL_SPACE_START = 0x8000000000000000ULL;
 constexpr uintptr_t USER_SPACE_MEMORY_TOP = 0x0000800000000000ULL;
-constexpr uintptr_t MMAP_MIN_ADDR         = 0x0000000000001000ULL;
-constexpr uintptr_t STACK_MIN_ADDR        = 0x0000700000000000ULL;
+constexpr uintptr_t MMAP_MIN_ADDR = 0x0000000000001000ULL;
+constexpr uintptr_t STACK_MIN_ADDR = 0x0000700000000000ULL;
 
 class mm_list {
-private:
+   private:
     struct comparator {
-        constexpr bool operator()(const vm_area& lhs, const vm_area& rhs) const noexcept
-        { return lhs < rhs; }
-        constexpr bool operator()(const vm_area& lhs, uintptr_t rhs) const noexcept
-        { return lhs < rhs; }
-        constexpr bool operator()(uintptr_t lhs, const vm_area& rhs) const noexcept
-        { return lhs < rhs; }
+        constexpr bool operator()(const vm_area& lhs,
+                                  const vm_area& rhs) const noexcept {
+            return lhs < rhs;
+        }
+        constexpr bool operator()(const vm_area& lhs,
+                                  uintptr_t rhs) const noexcept {
+            return lhs < rhs;
+        }
+        constexpr bool operator()(uintptr_t lhs,
+                                  const vm_area& rhs) const noexcept {
+            return lhs < rhs;
+        }
     };
 
-public:
+   public:
     using list_type = std::set<vm_area, comparator>;
     using iterator = list_type::iterator;
     using const_iterator = list_type::const_iterator;
@@ -43,12 +49,12 @@ public:
         std::size_t file_offset;
     };
 
-private:
+   private:
     list_type m_areas;
     paging::pfn_t m_pt;
-    iterator m_brk {};
+    iterator m_brk{};
 
-public:
+   public:
     // default constructor copies kernel_mms
     explicit mm_list();
     // copies kernel_mms and mirrors user space
@@ -57,7 +63,7 @@ public:
     constexpr mm_list(mm_list&& v)
         : m_areas(std::move(v.m_areas))
         , m_pt(std::exchange(v.m_pt, 0))
-        , m_brk{std::move(v.m_brk)} { }
+        , m_brk{std::move(v.m_brk)} {}
 
     ~mm_list();
 
@@ -82,25 +88,22 @@ public:
 
     int mmap(const map_args& args);
 
-    constexpr vm_area* find(uintptr_t lp)
-    {
+    constexpr vm_area* find(uintptr_t lp) {
         auto iter = m_areas.find(lp);
         if (iter == m_areas.end())
             return nullptr;
         return &iter;
     }
 
-    constexpr const vm_area* find(uintptr_t lp) const
-    {
+    constexpr const vm_area* find(uintptr_t lp) const {
         auto iter = m_areas.find(lp);
         if (iter == m_areas.end())
             return nullptr;
         return &iter;
     }
 
-    constexpr paging::PSE get_page_table() const noexcept
-    {
-        return paging::PSE {m_pt};
+    constexpr paging::PSE get_page_table() const noexcept {
+        return paging::PSE{m_pt};
     }
 };
 

+ 50 - 50
include/kernel/mem/paging.hpp

@@ -1,8 +1,8 @@
 #pragma once
 
 #include <bit>
-#include <tuple>
 #include <cstddef>
+#include <tuple>
 
 #include <stdint.h>
 
@@ -10,15 +10,26 @@
 
 namespace kernel::mem::paging {
 
-constexpr int idx_p5(uintptr_t vaddr) noexcept { return (vaddr >> 48) & 0x1ff; }
-constexpr int idx_p4(uintptr_t vaddr) noexcept { return (vaddr >> 39) & 0x1ff; }
-constexpr int idx_p3(uintptr_t vaddr) noexcept { return (vaddr >> 30) & 0x1ff; }
-constexpr int idx_p2(uintptr_t vaddr) noexcept { return (vaddr >> 21) & 0x1ff; }
-constexpr int idx_p1(uintptr_t vaddr) noexcept { return (vaddr >> 12) & 0x1ff; }
+constexpr int idx_p5(uintptr_t vaddr) noexcept {
+    return (vaddr >> 48) & 0x1ff;
+}
+constexpr int idx_p4(uintptr_t vaddr) noexcept {
+    return (vaddr >> 39) & 0x1ff;
+}
+constexpr int idx_p3(uintptr_t vaddr) noexcept {
+    return (vaddr >> 30) & 0x1ff;
+}
+constexpr int idx_p2(uintptr_t vaddr) noexcept {
+    return (vaddr >> 21) & 0x1ff;
+}
+constexpr int idx_p1(uintptr_t vaddr) noexcept {
+    return (vaddr >> 12) & 0x1ff;
+}
 
-constexpr std::tuple<int, int, int, int, int> idx_all(uintptr_t vaddr) noexcept
-{
-    return {idx_p5(vaddr), idx_p4(vaddr), idx_p3(vaddr), idx_p2(vaddr), idx_p1(vaddr)};
+constexpr std::tuple<int, int, int, int, int> idx_all(
+    uintptr_t vaddr) noexcept {
+    return {idx_p5(vaddr), idx_p4(vaddr), idx_p3(vaddr), idx_p2(vaddr),
+            idx_p1(vaddr)};
 }
 
 // page frame number
@@ -28,19 +39,19 @@ using pfn_t = uintptr_t;
 // paging structure attributes
 using psattr_t = uintptr_t;
 
-constexpr psattr_t PA_P    = 0x0000000000000001ULL;
-constexpr psattr_t PA_RW   = 0x0000000000000002ULL;
-constexpr psattr_t PA_US   = 0x0000000000000004ULL;
-constexpr psattr_t PA_PWT  = 0x0000000000000008ULL;
-constexpr psattr_t PA_PCD  = 0x0000000000000010ULL;
-constexpr psattr_t PA_A    = 0x0000000000000020ULL;
-constexpr psattr_t PA_D    = 0x0000000000000040ULL;
-constexpr psattr_t PA_PS   = 0x0000000000000080ULL;
-constexpr psattr_t PA_G    = 0x0000000000000100ULL;
-constexpr psattr_t PA_COW  = 0x0000000000000200ULL; // copy on write
+constexpr psattr_t PA_P = 0x0000000000000001ULL;
+constexpr psattr_t PA_RW = 0x0000000000000002ULL;
+constexpr psattr_t PA_US = 0x0000000000000004ULL;
+constexpr psattr_t PA_PWT = 0x0000000000000008ULL;
+constexpr psattr_t PA_PCD = 0x0000000000000010ULL;
+constexpr psattr_t PA_A = 0x0000000000000020ULL;
+constexpr psattr_t PA_D = 0x0000000000000040ULL;
+constexpr psattr_t PA_PS = 0x0000000000000080ULL;
+constexpr psattr_t PA_G = 0x0000000000000100ULL;
+constexpr psattr_t PA_COW = 0x0000000000000200ULL;  // copy on write
 constexpr psattr_t PA_MMAP = 0x0000000000000400ULL; // memory mapped
 constexpr psattr_t PA_ANON = 0x0000000000000800ULL; // anonymous map
-constexpr psattr_t PA_NXE  = 0x8000000000000000ULL;
+constexpr psattr_t PA_NXE = 0x8000000000000000ULL;
 constexpr psattr_t PA_MASK = 0xfff0000000000fffULL;
 
 constexpr psattr_t PA_DATA = PA_P | PA_RW | PA_NXE;
@@ -66,38 +77,26 @@ namespace __inner {
 class PSE {
     physaddr<__inner::pse_t> m_ptrbase;
 
-public:
+   public:
     explicit constexpr PSE(uintptr_t pptr) noexcept : m_ptrbase{pptr} {}
 
-    constexpr void clear() noexcept
-    {
-        *m_ptrbase = 0;
-    }
+    constexpr void clear() noexcept { *m_ptrbase = 0; }
 
-    constexpr void set(psattr_t attributes, pfn_t pfn)
-    {
+    constexpr void set(psattr_t attributes, pfn_t pfn) {
         *m_ptrbase = (attributes & PA_MASK) | (pfn & ~PA_MASK);
     }
 
-    constexpr pfn_t pfn() const noexcept
-    {
-        return *m_ptrbase & ~PA_MASK;
-    }
+    constexpr pfn_t pfn() const noexcept { return *m_ptrbase & ~PA_MASK; }
 
-    constexpr psattr_t attributes() const noexcept
-    {
+    constexpr psattr_t attributes() const noexcept {
         return *m_ptrbase & PA_MASK;
     }
 
-    constexpr PSE operator[](std::size_t nth) const noexcept
-    {
+    constexpr PSE operator[](std::size_t nth) const noexcept {
         return PSE{m_ptrbase.phys() + 8 * nth};
     }
 
-    constexpr PSE parse() const noexcept
-    {
-        return PSE{*m_ptrbase & ~PA_MASK};
-    }
+    constexpr PSE parse() const noexcept { return PSE{*m_ptrbase & ~PA_MASK}; }
 };
 
 constexpr pfn_t EMPTY_PAGE_PFN = 0x7f000;
@@ -107,8 +106,8 @@ constexpr physaddr<void> KERNEL_PAGE_TABLE_PHYS_ADDR{KERNEL_PAGE_TABLE_ADDR};
 constexpr PSE KERNEL_PAGE_TABLE{0x100000};
 
 constexpr unsigned long PAGE_PRESENT = 0x00010000;
-constexpr unsigned long PAGE_BUDDY   = 0x00020000;
-constexpr unsigned long PAGE_SLAB    = 0x00040000;
+constexpr unsigned long PAGE_BUDDY = 0x00020000;
+constexpr unsigned long PAGE_SLAB = 0x00040000;
 
 struct page {
     // TODO: use atomic
@@ -144,13 +143,13 @@ page* pfn_to_page(pfn_t pfn);
 
 void increase_refcount(page* page);
 
-constexpr unsigned long PAGE_FAULT_P   = 0x00000001;
-constexpr unsigned long PAGE_FAULT_W   = 0x00000002;
-constexpr unsigned long PAGE_FAULT_U   = 0x00000004;
-constexpr unsigned long PAGE_FAULT_R   = 0x00000008;
-constexpr unsigned long PAGE_FAULT_I   = 0x00000010;
-constexpr unsigned long PAGE_FAULT_PK  = 0x00000020;
-constexpr unsigned long PAGE_FAULT_SS  = 0x00000040;
+constexpr unsigned long PAGE_FAULT_P = 0x00000001;
+constexpr unsigned long PAGE_FAULT_W = 0x00000002;
+constexpr unsigned long PAGE_FAULT_U = 0x00000004;
+constexpr unsigned long PAGE_FAULT_R = 0x00000008;
+constexpr unsigned long PAGE_FAULT_I = 0x00000010;
+constexpr unsigned long PAGE_FAULT_PK = 0x00000020;
+constexpr unsigned long PAGE_FAULT_SS = 0x00000040;
 constexpr unsigned long PAGE_FAULT_SGX = 0x00008000;
 
 void handle_page_fault(unsigned long err);
@@ -173,8 +172,9 @@ class vaddr_range {
 
     bool is_privilege;
 
-public:
-    explicit vaddr_range(pfn_t pt, uintptr_t start, uintptr_t end, bool is_privilege = false);
+   public:
+    explicit vaddr_range(pfn_t pt, uintptr_t start, uintptr_t end,
+                         bool is_privilege = false);
     explicit vaddr_range(std::nullptr_t);
 
     vaddr_range begin() const noexcept;

+ 5 - 15
include/kernel/mem/phys.hpp

@@ -18,31 +18,21 @@ class physaddr {
 
     uintptr_t m_ptr;
 
-public:
+   public:
     explicit constexpr physaddr(uintptr_t ptr) : m_ptr{ptr} {}
     explicit constexpr physaddr(std::nullptr_t) : m_ptr{} {}
 
     // cast to non-pointer types is prohibited
     template <typename U, typename = std::enable_if_t<std::is_pointer_v<U>>>
-    constexpr U cast_to() const noexcept
-    {
+    constexpr U cast_to() const noexcept {
         return std::bit_cast<U>(m_ptr + PHYS_OFFSET);
     }
 
-    constexpr operator T*() const noexcept
-    {
-        return cast_to<T*>();
-    }
+    constexpr operator T*() const noexcept { return cast_to<T*>(); }
 
-    constexpr T* operator->() const noexcept
-    {
-        return *this;
-    }
+    constexpr T* operator->() const noexcept { return *this; }
 
-    constexpr uintptr_t phys() const noexcept
-    {
-        return m_ptr;
-    }
+    constexpr uintptr_t phys() const noexcept { return m_ptr; }
 };
 
 //  gdt[0]:  null

+ 0 - 3
include/kernel/mem/slab.hpp

@@ -5,9 +5,6 @@
 
 #include <stdint.h>
 
-#include "paging.hpp"
-#include "phys.hpp"
-
 namespace kernel::mem {
 
 struct slab_cache;

+ 3 - 3
include/kernel/mem/types.hpp

@@ -1,9 +1,9 @@
 #pragma once
 
-#include <stdint.h>
-
 #include <cstddef>
 
+#include <stdint.h>
+
 namespace kernel::mem {
 
 struct gdt_entry {
@@ -29,7 +29,7 @@ namespace info {
     inline std::size_t memory_size;
     inline std::size_t e820_entry_count;
     inline std::size_t e820_entry_length;
-    inline e820_mem_map_entry e820_entries[(1024-16)/24];
+    inline e820_mem_map_entry e820_entries[(1024 - 16) / 24];
 
 } // namespace info
 

+ 28 - 17
include/kernel/mem/vm_area.hpp

@@ -6,12 +6,12 @@
 
 namespace kernel::mem {
 
-constexpr unsigned long MM_WRITE         = 0x00000000'00000001;
-constexpr unsigned long MM_EXECUTE       = 0x00000000'00000002;
-constexpr unsigned long MM_MAPPED        = 0x00000000'00000004;
-constexpr unsigned long MM_ANONYMOUS     = 0x00000000'00000008;
+constexpr unsigned long MM_WRITE = 0x00000000'00000001;
+constexpr unsigned long MM_EXECUTE = 0x00000000'00000002;
+constexpr unsigned long MM_MAPPED = 0x00000000'00000004;
+constexpr unsigned long MM_ANONYMOUS = 0x00000000'00000008;
 constexpr unsigned long MM_INTERNAL_MASK = 0xffffffff'00000000;
-constexpr unsigned long MM_BREAK         = 0x80000000'00000000;
+constexpr unsigned long MM_BREAK = 0x80000000'00000000;
 
 struct vm_area {
     uintptr_t start;
@@ -22,25 +22,36 @@ struct vm_area {
     fs::inode* mapped_file;
     std::size_t file_offset;
 
-    constexpr bool is_avail(uintptr_t ostart, uintptr_t oend) const noexcept
-    {
+    constexpr bool is_avail(uintptr_t ostart, uintptr_t oend) const noexcept {
         return (ostart >= end || oend <= start);
     }
 
-    constexpr bool operator<(const vm_area& rhs) const noexcept
-    { return end <= rhs.start; }
-    constexpr bool operator<(uintptr_t rhs) const noexcept
-    { return end <= rhs; }
-    friend constexpr bool operator<(uintptr_t lhs, const vm_area& rhs) noexcept
-    { return lhs < rhs.start; }
+    constexpr bool operator<(const vm_area& rhs) const noexcept {
+        return end <= rhs.start;
+    }
+    constexpr bool operator<(uintptr_t rhs) const noexcept {
+        return end <= rhs;
+    }
+    friend constexpr bool operator<(uintptr_t lhs,
+                                    const vm_area& rhs) noexcept {
+        return lhs < rhs.start;
+    }
 
     constexpr vm_area(uintptr_t start, unsigned long flags, uintptr_t end,
-            fs::inode* mapped_file = nullptr, std::size_t offset = 0)
-        : start{start}, end{end}, flags{flags}, mapped_file{mapped_file}, file_offset{offset} { }
+                      fs::inode* mapped_file = nullptr, std::size_t offset = 0)
+        : start{start}
+        , end{end}
+        , flags{flags}
+        , mapped_file{mapped_file}
+        , file_offset{offset} {}
 
     constexpr vm_area(uintptr_t start, unsigned long flags,
-            fs::inode* mapped_file = nullptr, std::size_t offset = 0)
-        : start{start}, end{start}, flags{flags}, mapped_file{mapped_file}, file_offset{offset} { }
+                      fs::inode* mapped_file = nullptr, std::size_t offset = 0)
+        : start{start}
+        , end{start}
+        , flags{flags}
+        , mapped_file{mapped_file}
+        , file_offset{offset} {}
 };
 
 } // namespace kernel::mem

+ 2 - 2
include/kernel/module.hpp

@@ -3,8 +3,8 @@
 #include <types/types.h>
 
 #define INTERNAL_MODULE(name, func) \
-    SECTION(".kmods") __attribute__((used)) \
-    kernel::module::module_loader const name = (func)
+    SECTION(".kmods")               \
+    __attribute__((used)) kernel::module::module_loader const name = (func)
 
 namespace kernel::module {
 

+ 30 - 40
include/kernel/process.hpp

@@ -14,9 +14,6 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <kernel/task/current.hpp>
-#include <kernel/task/thread.hpp>
-
 #include <types/allocator.hpp>
 #include <types/cplusplus.hpp>
 #include <types/path.hpp>
@@ -27,6 +24,8 @@
 #include <kernel/mem/mm_list.hpp>
 #include <kernel/mem/paging.hpp>
 #include <kernel/signal.hpp>
+#include <kernel/task/current.hpp>
+#include <kernel/task/thread.hpp>
 #include <kernel/tty.hpp>
 #include <kernel/user/thread_local.hpp>
 #include <kernel/vfs.hpp>
@@ -46,35 +45,35 @@ struct process_attr {
 };
 
 class process {
-public:
+   public:
     struct wait_obj {
         pid_t pid;
         int code;
     };
 
-public:
-    kernel::mem::mm_list mms {};
+   public:
+    kernel::mem::mm_list mms{};
     std::set<kernel::task::thread> thds;
     kernel::async::wait_list waitlist;
 
     kernel::async::mutex mtx_waitprocs;
     std::list<wait_obj> waitprocs;
 
-    process_attr attr {};
+    process_attr attr{};
     fs::filearray files;
-    fs::dentry_pointer cwd {};
-    mode_t umask { 0022 };
+    fs::dentry_pointer cwd{};
+    mode_t umask{0022};
 
-    pid_t pid {};
-    pid_t ppid {};
-    pid_t pgid {};
-    pid_t sid {};
+    pid_t pid{};
+    pid_t ppid{};
+    pid_t pgid{};
+    pid_t sid{};
 
-    kernel::tty::tty* control_tty {};
+    kernel::tty::tty* control_tty{};
     struct fs::fs_context fs_context;
     std::set<pid_t> children;
 
-public:
+   public:
     process(const process&) = delete;
     explicit process(const process& parent, pid_t pid);
 
@@ -82,37 +81,33 @@ public:
     // DO NOT use this after the system is on
     explicit process(pid_t pid, pid_t ppid);
 
-    constexpr bool is_system(void) const
-    { return attr.system; }
-    constexpr bool is_zombie(void) const
-    { return attr.zombie; }
+    constexpr bool is_system(void) const { return attr.system; }
+    constexpr bool is_zombie(void) const { return attr.zombie; }
 
     void send_signal(kernel::signal_list::signo_type signal);
 };
 
 class proclist final {
-private:
+   private:
     std::map<pid_t, process> m_procs;
     pid_t m_nextpid = 2;
 
     constexpr pid_t next_pid() { return m_nextpid++; }
     process& real_emplace(pid_t pid, pid_t ppid);
 
-public:
+   public:
     proclist();
 
-    constexpr process& copy_from(process& proc)
-    {
+    constexpr process& copy_from(process& proc) {
         pid_t pid = next_pid();
-        auto [ iter, inserted ] = m_procs.try_emplace(pid, proc, pid);
+        auto [iter, inserted] = m_procs.try_emplace(pid, proc, pid);
         assert(inserted);
 
         proc.children.insert(pid);
         return iter->second;
     }
 
-    constexpr void remove(pid_t pid)
-    {
+    constexpr void remove(pid_t pid) {
         make_children_orphans(pid);
 
         auto proc_iter = m_procs.find(pid);
@@ -123,25 +118,22 @@ public:
         m_procs.erase(proc_iter);
     }
 
-    constexpr std::pair<process*, bool> try_find(pid_t pid) const
-    {
+    constexpr std::pair<process*, bool> try_find(pid_t pid) const {
         auto iter = m_procs.find(pid);
         if (iter)
-            return { (process*)&iter->second, true };
+            return {(process*)&iter->second, true};
         else
-            return { nullptr, false };
+            return {nullptr, false};
     }
 
     // if process doesn't exist, the behavior is undefined
-    constexpr process& find(pid_t pid)
-    {
-        auto [ ptr, found] = try_find(pid);
+    constexpr process& find(pid_t pid) {
+        auto [ptr, found] = try_find(pid);
         assert(found);
         return *ptr;
     }
 
-    constexpr void make_children_orphans(pid_t pid)
-    {
+    constexpr void make_children_orphans(pid_t pid) {
         auto& children = find(pid).children;
         auto& init_children = find(1).children;
 
@@ -154,15 +146,13 @@ public:
     }
 
     // the process MUST exist, or the behavior is undefined
-    void send_signal(pid_t pid, kernel::signal_list::signo_type signal)
-    {
+    void send_signal(pid_t pid, kernel::signal_list::signo_type signal) {
         auto& proc = find(pid);
         proc.send_signal(signal);
     }
-    void send_signal_grp(pid_t pgid, kernel::signal_list::signo_type signal)
-    {
+    void send_signal_grp(pid_t pgid, kernel::signal_list::signo_type signal) {
         // TODO: find processes that are in the same session quickly
-        for (auto& [ pid, proc ] : m_procs) {
+        for (auto& [pid, proc] : m_procs) {
             if (proc.pgid != pgid)
                 continue;
             proc.send_signal(signal);

+ 16 - 13
include/kernel/signal.hpp

@@ -1,13 +1,13 @@
 #pragma once
 
-#include <map>
 #include <list>
+#include <map>
 
 #include <signal.h>
 #include <stdint.h>
-#include <types/types.h>
 
 #include <types/cplusplus.hpp>
+#include <types/types.h>
 
 #include <kernel/async/lock.hpp>
 #include <kernel/interrupt.hpp>
@@ -24,31 +24,34 @@ struct sigaction {
 };
 
 class signal_list {
-public:
+   public:
     using signo_type = uint32_t;
     using list_type = std::list<signo_type>;
 
-private:
+   private:
     list_type m_list;
-    sigmask_type m_mask { };
+    sigmask_type m_mask{};
     std::map<signo_type, sigaction> m_handlers;
     async::mutex m_mtx;
 
-public:
-    static constexpr bool check_valid(signo_type sig)
-    {
+   public:
+    static constexpr bool check_valid(signo_type sig) {
         return sig >= 1 && sig <= 64;
     }
 
-public:
+   public:
     constexpr signal_list() = default;
     constexpr signal_list(const signal_list& val)
-        : m_list{val.m_list}, m_mask{val.m_mask}
-        , m_handlers{val.m_handlers}, m_mtx{} { }
+        : m_list{val.m_list}
+        , m_mask{val.m_mask}
+        , m_handlers{val.m_handlers}
+        , m_mtx{} {}
 
     constexpr signal_list(signal_list&& val)
-        : m_list{std::move(val.m_list)}, m_mask{std::move(val.m_mask)}
-        , m_handlers{std::move(val.m_handlers)}, m_mtx{} { }
+        : m_list{std::move(val.m_list)}
+        , m_mask{std::move(val.m_mask)}
+        , m_handlers{std::move(val.m_handlers)}
+        , m_mtx{} {}
 
     void on_exec();
 

+ 76 - 77
include/kernel/syscall.hpp

@@ -31,88 +31,87 @@ void handle_syscall32(int no, interrupt_stack* data, mmx_registers* mmxregs);
 void handle_syscall64(int no, interrupt_stack* data, mmx_registers* mmxregs);
 
 namespace syscall {
-// in fileops.cc
-ssize_t do_write(int fd, const char __user* buf, size_t n);
-ssize_t do_read(int fd, char __user* buf, size_t n);
-int do_close(int fd);
-int do_dup(int old_fd);
-int do_dup2(int old_fd, int new_fd);
-int do_pipe(int __user* pipefd);
-ssize_t do_getdents(int fd, char __user* buf, size_t cnt);
-ssize_t do_getdents64(int fd, char __user* buf, size_t cnt);
-int do_open(const char __user* path, int flags, mode_t mode);
-int do_symlink(const char __user* target, const char __user* linkpath);
-int do_readlink(const char __user* pathname, char __user* buf, size_t buf_size);
-int do_ioctl(int fd, unsigned long request, uintptr_t arg3);
-ssize_t do_readv(int fd, const iovec* iov, int iovcnt);
-ssize_t do_writev(int fd, const iovec* iov, int iovcnt);
-off_t do_lseek(int fd, off_t offset, int whence);
-uintptr_t do_mmap_pgoff(uintptr_t addr, size_t len,
-        int prot, int flags, int fd, off_t pgoffset);
-int do_munmap(uintptr_t addr, size_t len);
-ssize_t do_sendfile(int out_fd, int in_fd, off_t __user* offset, size_t count);
-int do_statx(int dirfd, const char __user* path,
-        int flags, unsigned int mask, statx __user* statxbuf);
-int do_fcntl(int fd, int cmd, unsigned long arg);
-int do_poll(pollfd __user* fds, nfds_t nfds, int timeout);
-int do_mknod(const char __user* pathname, mode_t mode, dev_t dev);
-int do_access(const char __user* pathname, int mode);
-int do_unlink(const char __user* pathname);
-int do_truncate(const char __user* pathname, long length);
-int do_mkdir(const char __user* pathname, mode_t mode);
+    // in fileops.cc
+    ssize_t do_write(int fd, const char __user* buf, size_t n);
+    ssize_t do_read(int fd, char __user* buf, size_t n);
+    int do_close(int fd);
+    int do_dup(int old_fd);
+    int do_dup2(int old_fd, int new_fd);
+    int do_pipe(int __user* pipefd);
+    ssize_t do_getdents(int fd, char __user* buf, size_t cnt);
+    ssize_t do_getdents64(int fd, char __user* buf, size_t cnt);
+    int do_open(const char __user* path, int flags, mode_t mode);
+    int do_symlink(const char __user* target, const char __user* linkpath);
+    int do_readlink(const char __user* pathname, char __user* buf,
+                    size_t buf_size);
+    int do_ioctl(int fd, unsigned long request, uintptr_t arg3);
+    ssize_t do_readv(int fd, const iovec* iov, int iovcnt);
+    ssize_t do_writev(int fd, const iovec* iov, int iovcnt);
+    off_t do_lseek(int fd, off_t offset, int whence);
+    uintptr_t do_mmap_pgoff(uintptr_t addr, size_t len, int prot, int flags,
+                            int fd, off_t pgoffset);
+    int do_munmap(uintptr_t addr, size_t len);
+    ssize_t do_sendfile(int out_fd, int in_fd, off_t __user* offset,
+                        size_t count);
+    int do_statx(int dirfd, const char __user* path, int flags,
+                 unsigned int mask, statx __user* statxbuf);
+    int do_fcntl(int fd, int cmd, unsigned long arg);
+    int do_poll(pollfd __user* fds, nfds_t nfds, int timeout);
+    int do_mknod(const char __user* pathname, mode_t mode, dev_t dev);
+    int do_access(const char __user* pathname, int mode);
+    int do_unlink(const char __user* pathname);
+    int do_truncate(const char __user* pathname, long length);
+    int do_mkdir(const char __user* pathname, mode_t mode);
 
-// in procops.cc
-int do_chdir(const char __user* path);
-[[noreturn]] int do_exit(int status);
-int do_waitpid(pid_t waitpid, int __user* arg1, int options);
-pid_t do_getsid(pid_t pid);
-pid_t do_setsid();
-pid_t do_getpgid(pid_t pid);
-int do_setpgid(pid_t pid, pid_t pgid);
-int do_set_thread_area(user::user_desc __user* ptr);
-pid_t do_set_tid_address(int __user* tidptr);
-int do_prctl(int option, uintptr_t arg2);
-int do_arch_prctl(int option, uintptr_t arg2);
-pid_t do_getpid();
-pid_t do_getppid();
-uid_t do_getuid();
-uid_t do_geteuid();
-gid_t do_getgid();
-pid_t do_gettid();
-int do_getcwd(char __user* buf, size_t buf_size);
-uintptr_t do_brk(uintptr_t addr);
-int do_umask(mode_t mask);
-int do_kill(pid_t pid, int sig);
-int do_tkill(pid_t pid, int sig);
-int do_rt_sigprocmask(int how, const kernel::sigmask_type __user* set,
-        kernel::sigmask_type __user* oldset, size_t sigsetsize);
-int do_rt_sigaction(int signum, const sigaction __user* act,
-        sigaction __user* oldact, size_t sigsetsize);
-int do_newuname(new_utsname __user* buf);
+    // in procops.cc
+    int do_chdir(const char __user* path);
+    [[noreturn]] int do_exit(int status);
+    int do_waitpid(pid_t waitpid, int __user* arg1, int options);
+    pid_t do_getsid(pid_t pid);
+    pid_t do_setsid();
+    pid_t do_getpgid(pid_t pid);
+    int do_setpgid(pid_t pid, pid_t pgid);
+    int do_set_thread_area(user::user_desc __user* ptr);
+    pid_t do_set_tid_address(int __user* tidptr);
+    int do_prctl(int option, uintptr_t arg2);
+    int do_arch_prctl(int option, uintptr_t arg2);
+    pid_t do_getpid();
+    pid_t do_getppid();
+    uid_t do_getuid();
+    uid_t do_geteuid();
+    gid_t do_getgid();
+    pid_t do_gettid();
+    int do_getcwd(char __user* buf, size_t buf_size);
+    uintptr_t do_brk(uintptr_t addr);
+    int do_umask(mode_t mask);
+    int do_kill(pid_t pid, int sig);
+    int do_tkill(pid_t pid, int sig);
+    int do_rt_sigprocmask(int how, const kernel::sigmask_type __user* set,
+                          kernel::sigmask_type __user* oldset,
+                          size_t sigsetsize);
+    int do_rt_sigaction(int signum, const sigaction __user* act,
+                        sigaction __user* oldact, size_t sigsetsize);
+    int do_newuname(new_utsname __user* buf);
 
-struct execve_retval {
-    uintptr_t ip;
-    uintptr_t sp;
-    int status;
-};
+    struct execve_retval {
+        uintptr_t ip;
+        uintptr_t sp;
+        int status;
+    };
 
-execve_retval do_execve(
-        const std::string& exec,
-        const std::vector<std::string>& args,
-        const std::vector<std::string>& envs);
+    execve_retval do_execve(const std::string& exec,
+                            const std::vector<std::string>& args,
+                            const std::vector<std::string>& envs);
 
-// in mount.cc
-int do_mount(
-        const char __user* source,
-        const char __user* target,
-        const char __user* fstype,
-        unsigned long flags,
-        const void __user* _fsdata);
+    // in mount.cc
+    int do_mount(const char __user* source, const char __user* target,
+                 const char __user* fstype, unsigned long flags,
+                 const void __user* _fsdata);
 
-// in infoops.cc
-int do_clock_gettime(clockid_t clk_id, timespec __user* tp);
-int do_gettimeofday(timeval __user* tv, void __user* tz);
+    // in infoops.cc
+    int do_clock_gettime(clockid_t clk_id, timespec __user* tp);
+    int do_gettimeofday(timeval __user* tv, void __user* tz);
 
-} // namespace kernel::syscall
+} // namespace syscall
 
 } // namespace kernel

+ 1 - 1
include/kernel/task/readyqueue.hpp

@@ -13,4 +13,4 @@ void setup_idle(thread* idle_thd);
 
 thread* next();
 
-} // namespace kernel::task
+} // namespace kernel::task::dispatcher

+ 13 - 13
include/kernel/task/thread.hpp

@@ -17,16 +17,16 @@ namespace kernel::task {
 using tid_t = std::size_t;
 
 struct thread {
-public:
+   public:
     using thd_attr_t = uint32_t;
-    static constexpr thd_attr_t SYSTEM  = 0x01;
-    static constexpr thd_attr_t READY   = 0x02;
+    static constexpr thd_attr_t SYSTEM = 0x01;
+    static constexpr thd_attr_t READY = 0x02;
     static constexpr thd_attr_t STOPPED = 0x04;
-    static constexpr thd_attr_t ZOMBIE  = 0x08;
-    static constexpr thd_attr_t ISLEEP  = 0x10;
-    static constexpr thd_attr_t USLEEP  = 0x20;
+    static constexpr thd_attr_t ZOMBIE = 0x08;
+    static constexpr thd_attr_t ISLEEP = 0x10;
+    static constexpr thd_attr_t USLEEP = 0x20;
 
-private:
+   private:
     struct kernel_stack {
         mem::paging::pfn_t pfn;
         uintptr_t sp;
@@ -42,18 +42,18 @@ private:
         void load_interrupt_stack() const;
     };
 
-public:
+   public:
     kernel_stack kstack;
     pid_t owner;
     thd_attr_t attr;
     signal_list signals;
 
-    int* __user set_child_tid {};
-    int* __user clear_child_tid {};
+    int* __user set_child_tid{};
+    int* __user clear_child_tid{};
 
-    std::string name {};
-    uint64_t tls_desc32 {};
-    std::size_t elected_times {};
+    std::string name{};
+    uint64_t tls_desc32{};
+    std::size_t elected_times{};
 
     explicit thread(std::string name, pid_t owner);
     thread(const thread& val, pid_t owner);

+ 8 - 14
include/kernel/tty.hpp

@@ -10,22 +10,22 @@
 #include <types/buffer.hpp>
 #include <types/cplusplus.hpp>
 
-#include <kernel/async/waitlist.hpp>
 #include <kernel/async/lock.hpp>
+#include <kernel/async/waitlist.hpp>
 
 namespace kernel::tty {
 
 class tty : public types::non_copyable {
-public:
+   public:
     static constexpr size_t BUFFER_SIZE = 4096;
 
-private:
+   private:
     void _real_commit_char(int c);
     void _echo_char(int c);
 
     int _do_erase(bool should_echo);
 
-public:
+   public:
     explicit tty(std::string name);
     virtual void putchar(char c) = 0;
     void print(const char* str);
@@ -45,20 +45,14 @@ public:
     // TODO: formal poll support
     int poll();
 
-    constexpr void set_pgrp(pid_t pgid)
-    {
-        fg_pgroup = pgid;
-    }
+    constexpr void set_pgrp(pid_t pgid) { fg_pgroup = pgid; }
 
-    constexpr pid_t get_pgrp(void) const
-    {
-        return fg_pgroup;
-    }
+    constexpr pid_t get_pgrp(void) const { return fg_pgroup; }
 
     termios termio;
     std::string name;
 
-protected:
+   protected:
     async::mutex mtx_buf;
     types::buffer buf;
     async::wait_list waitlist;
@@ -67,7 +61,7 @@ protected:
 };
 
 class vga_tty : public virtual tty {
-public:
+   public:
     vga_tty();
     virtual void putchar(char c) override;
 };

+ 34 - 25
include/kernel/vfs.hpp

@@ -1,34 +1,35 @@
 #pragma once
 
-#include <kernel/vfs/dentry.hpp>
-#include <kernel/vfs/file.hpp>
-#include <kernel/vfs/inode.hpp>
-#include <kernel/vfs/vfs.hpp>
-
 #include <memory>
 
+#include <bits/alltypes.h>
 #include <stdint.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <bits/alltypes.h>
 
 #include <types/path.hpp>
 
+#include <kernel/vfs/dentry.hpp>
+#include <kernel/vfs/file.hpp>
+#include <kernel/vfs/inode.hpp>
+#include <kernel/vfs/vfs.hpp>
+
 #define NODE_MAJOR(node) (((node) >> 8) & 0xFFU)
-#define NODE_MINOR(node) ((node) & 0xFFU)
+#define NODE_MINOR(node) ((node)&0xFFU)
 
 namespace fs {
 
-constexpr dev_t make_device(uint32_t major, uint32_t minor)
-{
+constexpr dev_t make_device(uint32_t major, uint32_t minor) {
     return ((major << 8) & 0xFF00U) | (minor & 0xFFU);
 }
 
 // buf, buf_size, offset, cnt
-using blkdev_read = std::function<ssize_t(char*, std::size_t, std::size_t, std::size_t)>;
+using blkdev_read =
+    std::function<ssize_t(char*, std::size_t, std::size_t, std::size_t)>;
 
 // buf, offset, cnt
-using blkdev_write = std::function<ssize_t(const char*, std::size_t, std::size_t)>;
+using blkdev_write =
+    std::function<ssize_t(const char*, std::size_t, std::size_t)>;
 
 struct blkdev_ops {
     blkdev_read read;
@@ -47,19 +48,19 @@ struct chrdev_ops {
 };
 
 struct PACKED user_dirent {
-    ino_t d_ino; // inode number
-    uint32_t d_off; // ignored
+    ino_t d_ino;       // inode number
+    uint32_t d_off;    // ignored
     uint16_t d_reclen; // length of this struct user_dirent
-    char d_name[1]; // file name with a padding zero
+    char d_name[1];    // file name with a padding zero
     // uint8_t d_type; // file type, with offset of (d_reclen - 1)
 };
 
 struct PACKED user_dirent64 {
-    ino64_t d_ino; // inode number
-    uint64_t d_off; // implementation-defined field, ignored
+    ino64_t d_ino;     // inode number
+    uint64_t d_off;    // implementation-defined field, ignored
     uint16_t d_reclen; // length of this struct user_dirent
-    uint8_t d_type; // file type, with offset of (d_reclen - 1)
-    char d_name[1]; // file name with a padding zero
+    uint8_t d_type;    // file type, with offset of (d_reclen - 1)
+    char d_name[1];    // file name with a padding zero
 };
 
 struct fs_context {
@@ -83,7 +84,8 @@ int register_char_device(dev_t node, const chrdev_ops& ops);
 // 1. const char*: source, such as "/dev/sda" or "proc"
 // 2. unsigned long: flags, such as MS_RDONLY | MS_RELATIME
 // 3. const void*: data, for filesystem use, such as "uid=1000"
-using create_fs_func_t = std::function<vfs*(const char*, unsigned long, const void*)>;
+using create_fs_func_t =
+    std::function<vfs*(const char*, unsigned long, const void*)>;
 
 int register_fs(const char* name, create_fs_func_t);
 
@@ -92,8 +94,10 @@ int register_tmpfs();
 
 void partprobe();
 
-ssize_t block_device_read(dev_t node, char* buf, size_t buf_size, size_t offset, size_t n);
-ssize_t block_device_write(dev_t node, const char* buf, size_t offset, size_t n);
+ssize_t block_device_read(dev_t node, char* buf, size_t buf_size, size_t offset,
+                          size_t n);
+ssize_t block_device_write(dev_t node, const char* buf, size_t offset,
+                           size_t n);
 
 ssize_t char_device_read(dev_t node, char* buf, size_t buf_size, size_t n);
 ssize_t char_device_write(dev_t node, const char* buf, size_t n);
@@ -107,15 +111,20 @@ int symlink(struct dentry* at, const char* target);
 int statx(struct inode* inode, struct statx* stat, unsigned int mask);
 int readlink(struct inode* inode, char* buf, size_t buf_size);
 int truncate(struct inode* file, size_t size);
-size_t read(struct inode* file, char* buf, size_t buf_size, size_t offset, size_t n);
+size_t read(struct inode* file, char* buf, size_t buf_size, size_t offset,
+            size_t n);
 size_t write(struct inode* file, const char* buf, size_t offset, size_t n);
 
 int mount(dentry* mnt, const char* source, const char* mount_point,
-        const char* fstype, unsigned long flags, const void *data);
+          const char* fstype, unsigned long flags, const void* data);
 
-#define current_open(...) fs::open(current_process->fs_context, current_process->cwd.get(), __VA_ARGS__)
+#define current_open(...)                                             \
+    fs::open(current_process->fs_context, current_process->cwd.get(), \
+             __VA_ARGS__)
 std::pair<dentry_pointer, int> open(const fs_context& context, dentry* cwd,
-        types::path_iterator path, bool follow_symlinks = true, int recurs_no = 0);
+                                    types::path_iterator path,
+                                    bool follow_symlinks = true,
+                                    int recurs_no = 0);
 
 } // namespace fs
 

+ 5 - 4
include/kernel/vfs/dentry.hpp

@@ -10,9 +10,9 @@
 #include <kernel/vfs/inode.hpp>
 
 namespace fs {
-static constexpr unsigned long D_PRESENT    = 1 << 0;
-static constexpr unsigned long D_DIRECTORY  = 1 << 1;
-static constexpr unsigned long D_LOADED     = 1 << 2;
+static constexpr unsigned long D_PRESENT = 1 << 0;
+static constexpr unsigned long D_DIRECTORY = 1 << 1;
+static constexpr unsigned long D_LOADED = 1 << 2;
 static constexpr unsigned long D_MOUNTPOINT = 1 << 3;
 
 struct dentry {
@@ -48,7 +48,8 @@ struct dcache {
     std::size_t size;
 };
 
-std::pair<struct dentry*, int> d_find(struct dentry* parent, types::string_view name);
+std::pair<struct dentry*, int> d_find(struct dentry* parent,
+                                      types::string_view name);
 std::string d_path(const struct dentry* dentry, const struct dentry* root);
 
 dentry_pointer d_get(const dentry_pointer& dp);

+ 21 - 26
include/kernel/vfs/file.hpp

@@ -4,22 +4,22 @@
 #include <fcntl.h>
 #include <sys/types.h>
 
-#include <types/types.h>
 #include <types/buffer.hpp>
+#include <types/types.h>
 
-#include <kernel/async/waitlist.hpp>
 #include <kernel/async/lock.hpp>
+#include <kernel/async/waitlist.hpp>
 #include <kernel/vfs/dentry.hpp>
 
 namespace fs {
 
 class pipe : public types::non_copyable {
-private:
+   private:
     static constexpr size_t PIPE_SIZE = 4096;
     static constexpr uint32_t READABLE = 1;
     static constexpr uint32_t WRITABLE = 2;
 
-private:
+   private:
     types::buffer buf;
     uint32_t flags;
     kernel::async::mutex mtx;
@@ -27,7 +27,7 @@ private:
     kernel::async::wait_list waitlist_r;
     kernel::async::wait_list waitlist_w;
 
-public:
+   public:
     pipe();
 
     void close_read();
@@ -36,15 +36,9 @@ public:
     int write(const char* buf, size_t n);
     int read(char* buf, size_t n);
 
-    constexpr bool is_readable() const
-    {
-        return flags & READABLE;
-    }
+    constexpr bool is_readable() const { return flags & READABLE; }
 
-    constexpr bool is_writeable() const
-    {
-        return flags & WRITABLE;
-    }
+    constexpr bool is_writeable() const { return flags & WRITABLE; }
 };
 
 struct file {
@@ -53,21 +47,20 @@ struct file {
         uint32_t read : 1;
         uint32_t write : 1;
         uint32_t append : 1;
-    } flags {};
+    } flags{};
 
-    file(mode_t mode, file_flags flags)
-        : mode(mode), flags(flags) { }
+    file(mode_t mode, file_flags flags) : mode(mode), flags(flags) {}
 
     virtual ~file() = default;
 
     virtual ssize_t read(char* __user buf, size_t n) = 0;
     virtual ssize_t do_write(const char* __user buf, size_t n) = 0;
 
-    virtual off_t seek(off_t n, int whence)
-    { return (void)n, (void)whence, -ESPIPE; }
+    virtual off_t seek(off_t n, int whence) {
+        return (void)n, (void)whence, -ESPIPE;
+    }
 
-    ssize_t write(const char* __user buf, size_t n)
-    {
+    ssize_t write(const char* __user buf, size_t n) {
         if (!flags.write)
             return -EBADF;
 
@@ -79,16 +72,18 @@ struct file {
     }
 
     // regular files should override this method
-    virtual int getdents(char* __user buf, size_t cnt)
-    { return (void)buf, (void)cnt, -ENOTDIR; }
-    virtual int getdents64(char* __user buf, size_t cnt)
-    { return (void)buf, (void)cnt, -ENOTDIR; }
+    virtual int getdents(char* __user buf, size_t cnt) {
+        return (void)buf, (void)cnt, -ENOTDIR;
+    }
+    virtual int getdents64(char* __user buf, size_t cnt) {
+        return (void)buf, (void)cnt, -ENOTDIR;
+    }
 };
 
 struct regular_file : public virtual file {
     virtual ~regular_file() = default;
-    std::size_t cursor { };
-    inode* ind { };
+    std::size_t cursor{};
+    inode* ind{};
 
     regular_file(file_flags flags, size_t cursor, inode* ind);
 

+ 7 - 6
include/kernel/vfs/filearr.hpp

@@ -1,23 +1,23 @@
 #pragma once
 
+#include "dentry.hpp"
+#include "file.hpp"
+
 #include <memory>
 
 #include <types/path.hpp>
 
 #include <kernel/vfs.hpp>
 
-#include "dentry.hpp"
-#include "file.hpp"
-
 namespace fs {
 
 class filearray {
-private:
+   private:
     struct impl;
     std::shared_ptr<impl> pimpl;
     filearray(std::shared_ptr<impl>);
 
-public:
+   public:
     filearray(const fs_context* ctx);
     filearray(filearray&& other) = default;
 
@@ -37,7 +37,8 @@ public:
     int set_flags(int fd, int flags);
 
     int pipe(int (&pipefd)[2]);
-    int open(dentry* cwd, types::path_iterator filepath, int flags, mode_t mode);
+    int open(dentry* cwd, types::path_iterator filepath, int flags,
+             mode_t mode);
     int open(types::path_iterator filepath, int flags, mode_t mode);
 
     int close(int fd);

+ 8 - 8
include/kernel/vfs/inode.hpp

@@ -9,20 +9,20 @@
 namespace fs {
 
 struct inode {
-    ino_t ino {};
-    size_t size {};
-    nlink_t nlink {};
+    ino_t ino{};
+    size_t size{};
+    nlink_t nlink{};
 
-    vfs* fs {};
-    void* fs_data {};
+    vfs* fs{};
+    void* fs_data{};
 
     struct timespec atime {};
     struct timespec ctime {};
     struct timespec mtime {};
 
-    mode_t mode {};
-    uid_t uid {};
-    gid_t gid {};
+    mode_t mode{};
+    uid_t uid{};
+    gid_t gid{};
 };
 
 } // namespace fs

+ 19 - 16
include/kernel/vfs/vfs.hpp

@@ -1,31 +1,31 @@
 #pragma once
 
-#include <kernel/vfs/inode.hpp>
-#include <kernel/vfs/dentry.hpp>
-
 #include <functional>
 #include <map>
 
 #include <stdint.h>
-#include <sys/types.h>
 #include <sys/stat.h>
+#include <sys/types.h>
+
+#include <kernel/vfs/dentry.hpp>
+#include <kernel/vfs/inode.hpp>
 
 namespace fs {
 
 class vfs {
-public:
+   public:
     using filldir_func = std::function<ssize_t(const char*, inode*, uint8_t)>;
 
-private:
+   private:
     struct dcache m_dcache;
-    struct dentry* m_root {};
+    struct dentry* m_root{};
     std::map<ino_t, inode> m_inodes;
 
-protected:
+   protected:
     dev_t m_device;
     size_t m_io_blksize;
 
-protected:
+   protected:
     vfs(dev_t device, size_t io_blksize);
 
     inode* alloc_inode(ino_t ino);
@@ -34,9 +34,9 @@ protected:
     inode* get_inode(ino_t ino);
     void register_root_node(inode* root);
 
-public:
-    static std::pair<vfs*, int> create(const char* source,
-        const char* fstype, unsigned long flags, const void* data);
+   public:
+    static std::pair<vfs*, int> create(const char* source, const char* fstype,
+                                       unsigned long flags, const void* data);
 
     vfs(const vfs&) = delete;
     vfs& operator=(const vfs&) = delete;
@@ -48,7 +48,7 @@ public:
     size_t io_blksize() const noexcept;
 
     int mount(dentry* mnt, const char* source, const char* mount_point,
-            const char* fstype, unsigned long flags, const void* data);
+              const char* fstype, unsigned long flags, const void* data);
 
     // directory operations
     virtual int creat(struct inode* dir, dentry* at, mode_t mode);
@@ -62,8 +62,10 @@ public:
     int statx(inode* ind, struct statx* st, unsigned int mask);
 
     // file operations
-    virtual ssize_t read(inode* file, char* buf, size_t buf_size, size_t count, off_t offset);
-    virtual ssize_t write(inode* file, const char* buf, size_t count, off_t offset);
+    virtual ssize_t read(inode* file, char* buf, size_t buf_size, size_t count,
+                         off_t offset);
+    virtual ssize_t write(inode* file, const char* buf, size_t count,
+                          off_t offset);
 
     virtual dev_t i_device(inode* ind);
     virtual int readlink(inode* file, char* buf, size_t buf_size);
@@ -79,7 +81,8 @@ public:
     // return -1 if an error occurred
     // return 0 if no more entry available
     // otherwise, return bytes to be added to the offset
-    virtual ssize_t readdir(inode* dir, size_t offset, const filldir_func& callback) = 0;
+    virtual ssize_t readdir(inode* dir, size_t offset,
+                            const filldir_func& callback) = 0;
 };
 
 } // namespace fs

+ 7 - 7
include/types/allocator.hpp

@@ -1,11 +1,12 @@
 #pragma once
+#include <cstddef>
 #include <memory>
 #include <new>
-#include <utility>
 #include <type_traits>
-#include <cstddef>
+#include <utility>
 
 #include <stdint.h>
+
 #include <types/cplusplus.hpp>
 #include <types/types.h>
 
@@ -14,11 +15,11 @@
 namespace types::memory {
 
 class brk_memory_allocator {
-public:
+   public:
     using byte = std::byte;
     using size_type = std::size_t;
 
-private:
+   private:
     byte* p_start;
     byte* p_limit;
     byte* p_break;
@@ -28,10 +29,9 @@ private:
     byte* brk(byte* addr);
     byte* sbrk(size_type increment);
 
-    constexpr byte* sbrk() const noexcept
-    { return p_break; }
+    constexpr byte* sbrk() const noexcept { return p_break; }
 
-public:
+   public:
     explicit brk_memory_allocator(byte* start, size_type size);
     brk_memory_allocator(const brk_memory_allocator&) = delete;
 

+ 17 - 22
include/types/bitmap.hpp

@@ -6,46 +6,41 @@
 namespace types {
 
 class bitmap {
-public:
+   public:
     using deleter_type = std::function<void(unsigned char*, std::size_t)>;
 
-private:
+   private:
     deleter_type m_del;
     std::size_t m_size;
     unsigned char* m_bm;
 
     static constexpr std::size_t SZ = sizeof(unsigned char) * 8;
 
-public:
-    constexpr bitmap(const deleter_type& del, unsigned char* bm, std::size_t size)
+   public:
+    constexpr bitmap(const deleter_type& del, unsigned char* bm,
+                     std::size_t size)
         : m_del(del), m_size(size), m_bm(bm) {}
     constexpr bitmap(deleter_type&& del, unsigned char* bm, std::size_t size)
         : m_del(std::move(del)), m_size(size), m_bm(bm) {}
 
     explicit constexpr bitmap(std::size_t size)
-        : m_del { [](unsigned char* bm, std::size_t) {
-            delete[] bm;
-        } }
-        , m_size { (size / SZ) + ((size % SZ) ? 1 : 0) }
-        , m_bm { new unsigned char[m_size] {} }
-    { }
+        : m_del{[](unsigned char* bm, std::size_t) { delete[] bm; }}
+        , m_size{(size / SZ) + ((size % SZ) ? 1 : 0)}
+        , m_bm{new unsigned char[m_size]{}} {}
 
     bitmap(const bitmap&) = delete;
-    
-    constexpr ~bitmap()
-    { m_del(m_bm, m_size); }
-    
-    constexpr bool test(std::size_t n) const
-    { return (m_bm[n / SZ] & (1 << (n % SZ))) != 0; }
 
-    constexpr void set(std::size_t n)
-    { m_bm[n / SZ] |= (1 << (n % SZ)); }
+    constexpr ~bitmap() { m_del(m_bm, m_size); }
 
-    constexpr void clear(std::size_t n)
-    { m_bm[n / SZ] &= (~(1 << (n % SZ))); }
+    constexpr bool test(std::size_t n) const {
+        return (m_bm[n / SZ] & (1 << (n % SZ))) != 0;
+    }
 
-    constexpr std::size_t size() const noexcept
-    { return m_size; }
+    constexpr void set(std::size_t n) { m_bm[n / SZ] |= (1 << (n % SZ)); }
+
+    constexpr void clear(std::size_t n) { m_bm[n / SZ] &= (~(1 << (n % SZ))); }
+
+    constexpr std::size_t size() const noexcept { return m_size; }
 };
 
 } // namespace types

+ 36 - 62
include/types/buffer.hpp

@@ -4,112 +4,95 @@
 
 #include <stdint.h>
 #include <stdio.h>
+
 #include <types/allocator.hpp>
 
 namespace types {
 
 template <typename Allocator>
 class basic_buffer {
-public:
+   public:
     using alloc_traits = std::allocator_traits<Allocator>;
 
-private:
+   private:
     char* const start;
     char* const end;
     char* base;
     char* head;
     size_t count;
-    Allocator alloc { };
+    Allocator alloc{};
 
-private:
-    constexpr char _get_char(char* ptr)
-    {
+   private:
+    constexpr char _get_char(char* ptr) {
         --count;
         return *ptr;
     }
 
-    constexpr void _put_char(char c)
-    {
+    constexpr void _put_char(char c) {
         *head = c;
         ++count;
     }
 
-    constexpr char* _forward(char* ptr)
-    {
+    constexpr char* _forward(char* ptr) {
         if (ptr == end)
             return start;
         else
             return ptr + 1;
     }
 
-    constexpr char* _backward(char* ptr)
-    {
+    constexpr char* _backward(char* ptr) {
         if (ptr == start)
             return end;
         else
             return ptr - 1;
     }
 
-public:
+   public:
     constexpr basic_buffer(size_t size)
-        : start { alloc_traits::allocate(alloc, size) }
-        , end { start + size - 1 }
-        , base { start }
-        , head { start }
-        , count { 0 }
-    {
-    }
+        : start{alloc_traits::allocate(alloc, size)}
+        , end{start + size - 1}
+        , base{start}
+        , head{start}
+        , count{0} {}
 
     constexpr basic_buffer(const basic_buffer& buf)
-        : start { alloc_traits::allocate(alloc, buf.end + 1 - buf.start) }
-        , end { (uint32_t)start + (uint32_t)buf.end - (uint32_t)buf.start }
-        , base { (uint32_t)start + (uint32_t)buf.base - (uint32_t)buf.start }
-        , head { (uint32_t)start + (uint32_t)buf.base - (uint32_t)buf.start }
-        , count { buf.count }
-    {
-    }
+        : start{alloc_traits::allocate(alloc, buf.end + 1 - buf.start)}
+        , end{(uint32_t)start + (uint32_t)buf.end - (uint32_t)buf.start}
+        , base{(uint32_t)start + (uint32_t)buf.base - (uint32_t)buf.start}
+        , head{(uint32_t)start + (uint32_t)buf.base - (uint32_t)buf.start}
+        , count{buf.count} {}
 
     constexpr basic_buffer(basic_buffer&& buf)
-        : start { buf.start }
-        , end { buf.end }
-        , base { buf.base }
-        , head { buf.head }
-        , count { buf.count }
-    {
-    }
+        : start{buf.start}
+        , end{buf.end}
+        , base{buf.base}
+        , head{buf.head}
+        , count{buf.count} {}
 
-    constexpr ~basic_buffer()
-    {
+    constexpr ~basic_buffer() {
         if (start)
             alloc_traits::deallocate(alloc, start, end - start);
     }
 
-    constexpr bool empty(void) const
-    {
-        return count == 0;
-    }
+    constexpr bool empty(void) const { return count == 0; }
 
-    constexpr bool full(void) const
-    {
+    constexpr bool full(void) const {
         return count == static_cast<size_t>(end - start + 1);
     }
 
-    constexpr int front(void)
-    {
+    constexpr int front(void) {
         if (empty())
             return EOF;
         return *base;
     }
 
-    constexpr int back(void)
-    {
+    constexpr int back(void) {
         if (empty())
             return EOF;
         return *_backward(head);
     }
 
-    constexpr int get(void)
-    {
+    constexpr int get(void) {
         if (empty())
             return EOF;
 
@@ -118,8 +101,7 @@ public:
         return c;
     }
 
-    constexpr int pop(void)
-    {
+    constexpr int pop(void) {
         if (empty())
             return EOF;
 
@@ -128,8 +110,7 @@ public:
         return c;
     }
 
-    constexpr int put(char c)
-    {
+    constexpr int put(char c) {
         if (full())
             return EOF;
 
@@ -138,18 +119,11 @@ public:
         return c;
     }
 
-    constexpr size_t size(void) const
-    {
-        return count;
-    }
+    constexpr size_t size(void) const { return count; }
 
-    constexpr size_t avail(void) const
-    {
-        return end - start + 1 - count;
-    }
+    constexpr size_t avail(void) const { return end - start + 1 - count; }
 
-    constexpr void clear(void)
-    {
+    constexpr void clear(void) {
         count = 0;
         head = base;
     }

+ 1 - 1
include/types/cplusplus.hpp

@@ -6,7 +6,7 @@
 namespace types {
 
 class non_copyable {
-public:
+   public:
     virtual ~non_copyable() = default;
     non_copyable() = default;
     non_copyable(const non_copyable&) = delete;

+ 4 - 8
include/types/hash.hpp

@@ -14,19 +14,16 @@ constexpr uint64_t GOLDEN_RATIO_64 = 0x61C8864680B583EBull;
 
 using hash_t = std::size_t;
 
-constexpr hash_t hash(uint64_t val, int bits)
-{
+constexpr hash_t hash(uint64_t val, int bits) {
     // higher bits are more random
     return (val * GOLDEN_RATIO_64) >> (64 - bits);
 }
 
-inline hash_t hash_ptr(void* p, int bits)
-{
+inline hash_t hash_ptr(void* p, int bits) {
     return hash(std::bit_cast<uintptr_t>(p), bits);
 }
 
-inline hash_t hash_str(const char* str, int bits)
-{
+inline hash_t hash_str(const char* str, int bits) {
     constexpr hash_t seed = 131;
     hash_t tmp = 0;
 
@@ -36,8 +33,7 @@ inline hash_t hash_str(const char* str, int bits)
     return hash(tmp, bits);
 };
 
-inline hash_t hash_str(string_view str, int bits)
-{
+inline hash_t hash_str(string_view str, int bits) {
     constexpr hash_t seed = 131;
     hash_t tmp = 0;
 

+ 4 - 7
include/types/list.hpp

@@ -3,8 +3,7 @@
 namespace types::list {
 
 template <typename ListNode>
-void list_insert(ListNode** head, ListNode* node)
-{
+void list_insert(ListNode** head, ListNode* node) {
     node->prev = nullptr;
     node->next = *head;
     if (*head)
@@ -13,8 +12,7 @@ void list_insert(ListNode** head, ListNode* node)
 }
 
 template <typename ListNode>
-ListNode* list_get(ListNode** head)
-{
+ListNode* list_get(ListNode** head) {
     ListNode* node = *head;
     if (node) {
         *head = node->next;
@@ -26,8 +24,7 @@ ListNode* list_get(ListNode** head)
 }
 
 template <typename ListNode>
-void list_remove(ListNode** head, ListNode* node)
-{
+void list_remove(ListNode** head, ListNode* node) {
     if (node->prev)
         node->prev->next = node->next;
     else
@@ -40,4 +37,4 @@ void list_remove(ListNode** head, ListNode* node)
     node->prev = nullptr;
 }
 
-} // namespace types
+} // namespace types::list

+ 16 - 19
include/types/path.hpp

@@ -7,11 +7,11 @@
 namespace types {
 
 class string_view {
-private:
+   private:
     const char* m_str;
     std::size_t m_len;
 
-public:
+   public:
     constexpr string_view() : m_str(nullptr), m_len(0) {}
     constexpr string_view(const char* str, std::size_t len)
         : m_str(str), m_len(len) {}
@@ -27,11 +27,9 @@ public:
     constexpr const char* begin() const { return m_str; }
     constexpr const char* end() const { return m_str + m_len; }
 
-    constexpr char operator[](std::size_t pos) const
-    { return m_str[pos]; }
+    constexpr char operator[](std::size_t pos) const { return m_str[pos]; }
 
-    constexpr bool operator==(const string_view& val) const
-    {
+    constexpr bool operator==(const string_view& val) const {
         if (m_len != val.m_len)
             return false;
         for (std::size_t i = 0; i < m_len; ++i) {
@@ -41,8 +39,7 @@ public:
         return true;
     }
 
-    constexpr bool operator==(const char* str) const
-    {
+    constexpr bool operator==(const char* str) const {
         for (std::size_t i = 0; i < m_len; ++i) {
             if (m_str[i] != str[i])
                 return false;
@@ -50,8 +47,7 @@ public:
         return str[m_len] == '\0';
     }
 
-    constexpr bool operator==(const std::string& str) const
-    {
+    constexpr bool operator==(const std::string& str) const {
         if (m_len != str.size())
             return false;
         return operator==(str.c_str());
@@ -59,29 +55,30 @@ public:
 };
 
 class path_iterator {
-private:
+   private:
     string_view m_all;
     unsigned m_curlen = 0;
     int m_is_absolute;
 
-public:
+   public:
     constexpr path_iterator() = default;
-    constexpr path_iterator(string_view str): m_all{str}
-    {
+    constexpr path_iterator(string_view str) : m_all{str} {
         m_is_absolute = !m_all.empty() && m_all[0] == '/';
         this->operator++();
     }
 
-    constexpr path_iterator(const std::string& str): path_iterator{string_view{str}} { }
-    inline path_iterator(const char* str): path_iterator{string_view{str}} { }
+    constexpr path_iterator(const std::string& str)
+        : path_iterator{string_view{str}} {}
+    inline path_iterator(const char* str) : path_iterator{string_view{str}} {}
 
     constexpr operator bool() const { return !m_all.empty(); }
     constexpr bool is_absolute() const { return m_is_absolute; }
 
-    constexpr string_view operator*() const { return string_view{m_all.data(), m_curlen}; }
+    constexpr string_view operator*() const {
+        return string_view{m_all.data(), m_curlen};
+    }
 
-    constexpr path_iterator& operator++()
-    {
+    constexpr path_iterator& operator++() {
         std::size_t start = m_curlen;
         while (start < m_all.size() && m_all[start] == '/')
             ++start;

+ 36 - 48
src/fs/fat.cpp

@@ -20,52 +20,43 @@
 namespace fs::fat {
 
 // buf MUST be larger than 512 bytes
-void fat32::_raw_read_sector(void* buf, uint32_t sector_no)
-{
-    auto nread = _read_sector_range(
-            buf, SECTOR_SIZE,
-            sector_no, 1
-            );
+void fat32::_raw_read_sector(void* buf, uint32_t sector_no) {
+    auto nread = _read_sector_range(buf, SECTOR_SIZE, sector_no, 1);
 
     assert((size_t)nread == SECTOR_SIZE);
 }
 
 // buf MUST be larger than 4096 bytes
-void fat32::_raw_read_cluster(void* buf, cluster_t no)
-{
+void fat32::_raw_read_cluster(void* buf, cluster_t no) {
     // data cluster start from cluster #2
     no -= 2;
 
     auto nread = _read_sector_range(
-            buf, sectors_per_cluster * SECTOR_SIZE,
-            data_region_offset + no * sectors_per_cluster,
-            sectors_per_cluster);
+        buf, sectors_per_cluster * SECTOR_SIZE,
+        data_region_offset + no * sectors_per_cluster, sectors_per_cluster);
 
     assert((size_t)nread == SECTOR_SIZE * sectors_per_cluster);
 }
 
-ssize_t fat32::_read_sector_range(void* _buf, size_t buf_size, uint32_t sector_offset, size_t sector_cnt)
-{
+ssize_t fat32::_read_sector_range(void* _buf, size_t buf_size,
+                                  uint32_t sector_offset, size_t sector_cnt) {
     buf_size &= ~(SECTOR_SIZE - 1);
 
     sector_cnt = std::min(sector_cnt, buf_size / SECTOR_SIZE);
 
     auto* buf = (char*)_buf;
 
-    auto n = block_device_read(m_device,
-            buf, buf_size,
-            sector_offset * SECTOR_SIZE,
-            sector_cnt * SECTOR_SIZE
-        );
+    auto n =
+        block_device_read(m_device, buf, buf_size, sector_offset * SECTOR_SIZE,
+                          sector_cnt * SECTOR_SIZE);
 
     return n;
 }
 
-char* fat32::read_cluster(cluster_t no)
-{
+char* fat32::read_cluster(cluster_t no) {
     auto iter = buf.find(no);
     if (iter) {
-        auto& [ idx, buf ] = *iter;
+        auto& [idx, buf] = *iter;
         ++buf.ref;
         return buf.data;
     }
@@ -76,22 +67,22 @@ char* fat32::read_cluster(cluster_t no)
 
     char* data = physaddr<char>{page_to_pfn(alloc_page())};
     _raw_read_cluster(data, no);
-    buf.emplace(no, buf_object { data, 1 });
+    buf.emplace(no, buf_object{data, 1});
 
     return data;
 }
 
-void fat32::release_cluster(cluster_t no)
-{
+void fat32::release_cluster(cluster_t no) {
     auto iter = buf.find(no);
     if (iter)
         --iter->second.ref;
 }
 
-ssize_t fat32::readdir(inode* dir, size_t offset, const vfs::filldir_func& filldir)
-{
+ssize_t fat32::readdir(inode* dir, size_t offset,
+                       const vfs::filldir_func& filldir) {
     cluster_t next = cl(dir);
-    for (size_t i = 0; i < (offset / (sectors_per_cluster * SECTOR_SIZE)); ++i) {
+    for (size_t i = 0; i < (offset / (sectors_per_cluster * SECTOR_SIZE));
+         ++i) {
         if (next >= EOC)
             return 0;
         next = fat[next];
@@ -99,9 +90,12 @@ ssize_t fat32::readdir(inode* dir, size_t offset, const vfs::filldir_func& filld
     size_t nread = 0;
     do {
         char* buf = read_cluster(next);
-        auto* d = reinterpret_cast<directory_entry*>(buf) + (offset % (sectors_per_cluster * SECTOR_SIZE)) / sizeof(directory_entry);
+        auto* d = reinterpret_cast<directory_entry*>(buf) +
+                  (offset % (sectors_per_cluster * SECTOR_SIZE)) /
+                      sizeof(directory_entry);
         offset = 0;
-        auto* end = d + (sectors_per_cluster * SECTOR_SIZE / sizeof(directory_entry));
+        auto* end =
+            d + (sectors_per_cluster * SECTOR_SIZE / sizeof(directory_entry));
         for (; d < end && d->filename[0]; ++d) {
             if (d->attributes.volume_label) {
                 nread += sizeof(directory_entry);
@@ -157,10 +151,7 @@ ssize_t fat32::readdir(inode* dir, size_t offset, const vfs::filldir_func& filld
     return nread;
 }
 
-fat32::fat32(dev_t _device)
-    : vfs(_device, 4096)
-    , label { }
-{
+fat32::fat32(dev_t _device) : vfs(_device, 4096), label{} {
     auto* buf = new char[SECTOR_SIZE];
     _raw_read_sector(buf, 0);
 
@@ -178,9 +169,8 @@ fat32::fat32(dev_t _device)
 
     // read file allocation table
     fat.resize(SECTOR_SIZE * sectors_per_fat / sizeof(cluster_t));
-    _read_sector_range(
-            fat.data(), SECTOR_SIZE * sectors_per_fat,
-            reserved_sectors, sectors_per_fat);
+    _read_sector_range(fat.data(), SECTOR_SIZE * sectors_per_fat,
+                       reserved_sectors, sectors_per_fat);
 
     int i = 0;
     while (i < 11 && info->label[i] != 0x20) {
@@ -210,8 +200,8 @@ fat32::fat32(dev_t _device)
     register_root_node(n);
 }
 
-ssize_t fat32::read(inode* file, char* buf, size_t buf_size, size_t n, off_t offset)
-{
+ssize_t fat32::read(inode* file, char* buf, size_t buf_size, size_t n,
+                    off_t offset) {
     uint32_t cluster_size = SECTOR_SIZE * sectors_per_cluster;
     size_t orig_n = n;
 
@@ -239,8 +229,7 @@ ssize_t fat32::read(inode* file, char* buf, size_t buf_size, size_t n, off_t off
     return orig_n - n;
 }
 
-static fat32* create_fat32(const char* source, unsigned long, const void*)
-{
+static fat32* create_fat32(const char* source, unsigned long, const void*) {
     // TODO: flags
     // TODO: parse source
     (void)source;
@@ -248,15 +237,13 @@ static fat32* create_fat32(const char* source, unsigned long, const void*)
 }
 
 class fat32_module : public virtual kernel::module::module {
-public:
-    fat32_module() : module("fat32") { }
-    ~fat32_module()
-    {
+   public:
+    fat32_module() : module("fat32") {}
+    ~fat32_module() {
         // TODO: unregister filesystem
     }
 
-    virtual int init() override
-    {
+    virtual int init() override {
         int ret = fs::register_fs("fat32", create_fat32);
 
         if (ret != 0)
@@ -268,7 +255,8 @@ public:
 
 } // namespace fs::fat
 
-static kernel::module::module* fat32_module_init()
-{ return new fs::fat::fat32_module; }
+static kernel::module::module* fat32_module_init() {
+    return new fs::fat::fat32_module;
+}
 
 INTERNAL_MODULE(fat32_module_loader, fat32_module_init);

+ 29 - 41
src/fs/procfs.cc

@@ -17,16 +17,12 @@ struct mount_flags_opt {
 };
 
 static struct mount_flags_opt mount_opts[] = {
-    {MS_NOSUID, ",nosuid"},
-    {MS_NODEV, ",nodev"},
-    {MS_NOEXEC, ",noexec"},
-    {MS_NOATIME, ",noatime"},
-    {MS_RELATIME, ",relatime"},
-    {MS_LAZYTIME, ",lazytime"},
+    {MS_NOSUID, ",nosuid"},     {MS_NODEV, ",nodev"},
+    {MS_NOEXEC, ",noexec"},     {MS_NOATIME, ",noatime"},
+    {MS_RELATIME, ",relatime"}, {MS_LAZYTIME, ",lazytime"},
 };
 
-static std::string get_mount_opts(unsigned long mnt_flags)
-{
+static std::string get_mount_opts(unsigned long mnt_flags) {
     std::string retval;
 
     if (mnt_flags & MS_RDONLY)
@@ -42,11 +38,10 @@ static std::string get_mount_opts(unsigned long mnt_flags)
     return retval;
 }
 
-static ssize_t mounts_read(char* page, size_t n)
-{
+static ssize_t mounts_read(char* page, size_t n) {
     auto orig_n = n;
 
-    for (const auto& [ _, mdata ] : fs::mounts) {
+    for (const auto& [_, mdata] : fs::mounts) {
         if (n == 0)
             break;
 
@@ -54,8 +49,8 @@ static ssize_t mounts_read(char* page, size_t n)
         auto mount_flags = get_mount_opts(mdata.flags);
 
         int nwrote = snprintf(page, n, "%s %s %s %s 0 0\n",
-                mdata.source.c_str(), mdata.mount_point.c_str(),
-                mdata.fstype.c_str(), mount_flags.c_str());
+                              mdata.source.c_str(), mdata.mount_point.c_str(),
+                              mdata.fstype.c_str(), mount_flags.c_str());
 
         n -= nwrote;
         page += nwrote;
@@ -64,8 +59,7 @@ static ssize_t mounts_read(char* page, size_t n)
     return orig_n - n;
 }
 
-static ssize_t schedstat_read(char* page, size_t n)
-{
+static ssize_t schedstat_read(char* page, size_t n) {
     auto orig_n = n;
 
     if (n == 0)
@@ -76,7 +70,8 @@ static ssize_t schedstat_read(char* page, size_t n)
 
     for (const auto& proc : *procs) {
         for (const auto& thd : proc.second.thds) {
-            int nwrote = snprintf(page, n, "%d %x %d\n", proc.first, thd.tid(), thd.elected_times);
+            int nwrote = snprintf(page, n, "%d %x %d\n", proc.first, thd.tid(),
+                                  thd.elected_times);
 
             n -= nwrote;
             page += nwrote;
@@ -96,27 +91,24 @@ struct proc_file {
 };
 
 class procfs : public virtual fs::vfs {
-private:
+   private:
     std::string source;
     std::map<ino_t, proc_file> files;
 
     ino_t free_ino = 1;
 
-public:
-    static procfs* create(const char* source, unsigned long, const void*)
-    {
+   public:
+    static procfs* create(const char* source, unsigned long, const void*) {
         // TODO: flags
         return new procfs(source);
     }
 
-    int create_file(std::string name,
-            ssize_t (*read_func)(char*, size_t),
-            ssize_t (*write_func)(const char*, size_t))
-    {
+    int create_file(std::string name, ssize_t (*read_func)(char*, size_t),
+                    ssize_t (*write_func)(const char*, size_t)) {
         auto ino = free_ino++;
 
-        auto [ _, inserted ] =
-            files.insert({ino, proc_file {name, read_func, write_func}});
+        auto [_, inserted] =
+            files.insert({ino, proc_file{name, read_func, write_func}});
 
         auto* ind = alloc_inode(ino);
         ind->mode = S_IFREG | 0666;
@@ -125,9 +117,7 @@ public:
     }
 
     procfs(const char* _source)
-        : vfs(make_device(0, 10), 4096)
-        , source{_source}
-    {
+        : vfs(make_device(0, 10), 4096), source{_source} {
         auto* ind = alloc_inode(0);
         ind->mode = S_IFDIR | 0777;
 
@@ -137,8 +127,8 @@ public:
         register_root_node(ind);
     }
 
-    ssize_t read(inode* file, char* buf, size_t buf_size, size_t n, off_t offset) override
-    {
+    ssize_t read(inode* file, char* buf, size_t buf_size, size_t n,
+                 off_t offset) override {
         if (file->ino == 0)
             return -EISDIR;
 
@@ -146,7 +136,7 @@ public:
         if (!iter)
             return -EIO;
 
-        auto& [ ino, pf ] = *iter;
+        auto& [ino, pf] = *iter;
 
         if (!pf.read)
             return -EINVAL;
@@ -173,8 +163,8 @@ public:
         return n;
     }
 
-    ssize_t readdir(inode *dir, size_t offset, const filldir_func &callback) override
-    {
+    ssize_t readdir(inode* dir, size_t offset,
+                    const filldir_func& callback) override {
         if (dir->ino != 0)
             return -ENOTDIR;
 
@@ -183,7 +173,7 @@ public:
             return 0;
 
         int nread = 0;
-        for (const auto& [ ino, pf ] : files) {
+        for (const auto& [ino, pf] : files) {
             auto* ind = get_inode(ino);
             int ret = callback(pf.name.c_str(), ind, ind->mode);
             if (ret != 0)
@@ -196,11 +186,10 @@ public:
 };
 
 class procfs_module : public virtual kernel::module::module {
-public:
-    procfs_module() : module("procfs") { }
+   public:
+    procfs_module() : module("procfs") {}
 
-    virtual int init() override
-    {
+    virtual int init() override {
         int ret = fs::register_fs("procfs", procfs::create);
         if (ret != 0)
             return kernel::module::MODULE_FAILED;
@@ -208,8 +197,7 @@ public:
     }
 };
 
-static kernel::module::module* procfs_init()
-{
+static kernel::module::module* procfs_init() {
     return new procfs_module;
 }
 

+ 42 - 60
src/kernel/allocator.cc

@@ -1,23 +1,23 @@
-#include <types/allocator.hpp>
-
 #include <bit>
 #include <cstddef>
 
 #include <assert.h>
 #include <stdint.h>
 
+#include <types/allocator.hpp>
+
 #include <kernel/async/lock.hpp>
 #include <kernel/mem/paging.hpp>
 #include <kernel/mem/slab.hpp>
 
 constexpr uintptr_t KERNEL_HEAP_START = 0xffff'ff81'8000'0000;
-constexpr uintptr_t KERNEL_HEAP_END   = 0xffff'ffbf'ffff'ffff;
-constexpr uintptr_t KERNEL_HEAP_SIZE  = KERNEL_HEAP_END - KERNEL_HEAP_START;
+constexpr uintptr_t KERNEL_HEAP_END = 0xffff'ffbf'ffff'ffff;
+constexpr uintptr_t KERNEL_HEAP_SIZE = KERNEL_HEAP_END - KERNEL_HEAP_START;
 
 namespace types::memory {
 
 struct mem_blk_flags {
-    unsigned long is_free  : 8;
+    unsigned long is_free : 8;
     unsigned long has_next : 8;
 };
 
@@ -29,14 +29,15 @@ struct mem_blk {
     std::byte data[];
 };
 
-constexpr std::byte* aspbyte(void* pblk)
-{ return std::bit_cast<std::byte*>(pblk);}
+constexpr std::byte* aspbyte(void* pblk) {
+    return std::bit_cast<std::byte*>(pblk);
+}
 
-constexpr mem_blk* aspblk(void* pbyte)
-{ return std::bit_cast<mem_blk*>(pbyte);}
+constexpr mem_blk* aspblk(void* pbyte) {
+    return std::bit_cast<mem_blk*>(pbyte);
+}
 
-constexpr mem_blk* next(mem_blk* blk, std::size_t blk_size)
-{
+constexpr mem_blk* next(mem_blk* blk, std::size_t blk_size) {
     auto* p = aspbyte(blk);
     p += sizeof(mem_blk);
     p += blk_size;
@@ -44,8 +45,7 @@ constexpr mem_blk* next(mem_blk* blk, std::size_t blk_size)
 }
 
 // blk MUST be free
-constexpr void unite_afterwards(mem_blk* blk)
-{
+constexpr void unite_afterwards(mem_blk* blk) {
     while (blk->flags.has_next) {
         auto* blk_next = next(blk, blk->size);
         if (!blk_next->flags.is_free)
@@ -58,8 +58,7 @@ constexpr void unite_afterwards(mem_blk* blk)
 // @param start_pos position where to start finding
 // @param size the size of the block we're looking for
 // @return found block if suitable block exists, if not, the last block
-constexpr mem_blk* find_blk(std::byte** p_start, std::size_t size)
-{
+constexpr mem_blk* find_blk(std::byte** p_start, std::size_t size) {
     mem_blk* start_pos = aspblk(*p_start);
     bool no_free_so_far = true;
 
@@ -83,8 +82,7 @@ constexpr mem_blk* find_blk(std::byte** p_start, std::size_t size)
     return start_pos;
 }
 
-constexpr void split_block(mem_blk* blk, std::size_t this_size)
-{
+constexpr void split_block(mem_blk* blk, std::size_t this_size) {
     // block is too small to get split
     // that is, the block to be split should have enough room
     // for "this_size" bytes and also could contain a new block
@@ -93,9 +91,7 @@ constexpr void split_block(mem_blk* blk, std::size_t this_size)
 
     mem_blk* blk_next = next(blk, this_size);
 
-    blk_next->size = blk->size
-        - this_size
-        - sizeof(mem_blk);
+    blk_next->size = blk->size - this_size - sizeof(mem_blk);
 
     blk_next->flags.has_next = blk->flags.has_next;
     blk_next->flags.is_free = 1;
@@ -104,16 +100,15 @@ constexpr void split_block(mem_blk* blk, std::size_t this_size)
     blk->size = this_size;
 }
 
-std::byte* brk_memory_allocator::brk(byte* addr)
-{
+std::byte* brk_memory_allocator::brk(byte* addr) {
     if (addr >= p_limit)
         return nullptr;
 
     uintptr_t current_allocated = reinterpret_cast<uintptr_t>(p_allocated);
     uintptr_t new_brk = reinterpret_cast<uintptr_t>(addr);
 
-    current_allocated &= ~(0x200000-1);
-    new_brk &= ~(0x200000-1);
+    current_allocated &= ~(0x200000 - 1);
+    new_brk &= ~(0x200000 - 1);
 
     using namespace kernel::mem::paging;
     while (current_allocated <= new_brk) {
@@ -135,8 +130,7 @@ std::byte* brk_memory_allocator::brk(byte* addr)
     return p_break = addr;
 }
 
-std::byte* brk_memory_allocator::sbrk(size_type increment)
-{
+std::byte* brk_memory_allocator::sbrk(size_type increment) {
     return brk(p_break + increment);
 }
 
@@ -144,8 +138,7 @@ brk_memory_allocator::brk_memory_allocator(byte* start, size_type size)
     : p_start(start)
     , p_limit(start + size)
     , p_break(start)
-    , p_allocated(start)
-{
+    , p_allocated(start) {
     auto* p_blk = aspblk(brk(p_start));
     sbrk(sizeof(mem_blk) + 1024); // 1024 bytes (minimum size for a block)
 
@@ -154,15 +147,14 @@ brk_memory_allocator::brk_memory_allocator(byte* start, size_type size)
     p_blk->flags.is_free = 1;
 }
 
-void* brk_memory_allocator::allocate(size_type size)
-{
+void* brk_memory_allocator::allocate(size_type size) {
     kernel::async::lock_guard_irq lck(mtx);
     // align to 1024 bytes boundary
-    size = (size + 1024-1) & ~(1024-1);
+    size = (size + 1024 - 1) & ~(1024 - 1);
 
     auto* block_allocated = find_blk(&p_start, size);
-    if (!block_allocated->flags.has_next
-        && (!block_allocated->flags.is_free || block_allocated->size < size)) {
+    if (!block_allocated->flags.has_next &&
+        (!block_allocated->flags.is_free || block_allocated->size < size)) {
         // 'block_allocated' in the argument list is the pointer
         // pointing to the last block
 
@@ -185,8 +177,7 @@ void* brk_memory_allocator::allocate(size_type size)
     return block_allocated->data;
 }
 
-void brk_memory_allocator::deallocate(void* ptr)
-{
+void brk_memory_allocator::deallocate(void* ptr) {
     kernel::async::lock_guard_irq lck(mtx);
     auto* blk = aspblk(aspbyte(ptr) - sizeof(mem_blk));
 
@@ -199,8 +190,7 @@ void brk_memory_allocator::deallocate(void* ptr)
     unite_afterwards(blk);
 }
 
-bool brk_memory_allocator::allocated(void* ptr) const noexcept
-{
+bool brk_memory_allocator::allocated(void* ptr) const noexcept {
     return (void*)KERNEL_HEAP_START <= aspbyte(ptr) && aspbyte(ptr) < sbrk();
 }
 
@@ -210,8 +200,7 @@ static brk_memory_allocator* k_alloc;
 
 static kernel::mem::slab_cache caches[7];
 
-static constexpr int __cache_index(std::size_t size)
-{
+static constexpr int __cache_index(std::size_t size) {
     if (size <= 32)
         return 0;
     if (size <= 64)
@@ -230,22 +219,20 @@ static constexpr int __cache_index(std::size_t size)
 }
 
 SECTION(".text.kinit")
-void kernel::kinit::init_allocator()
-{
-    mem::init_slab_cache(caches+0, 32);
-    mem::init_slab_cache(caches+1, 64);
-    mem::init_slab_cache(caches+2, 96);
-    mem::init_slab_cache(caches+3, 128);
-    mem::init_slab_cache(caches+4, 192);
-    mem::init_slab_cache(caches+5, 256);
-    mem::init_slab_cache(caches+6, 512);
+void kernel::kinit::init_allocator() {
+    mem::init_slab_cache(caches + 0, 32);
+    mem::init_slab_cache(caches + 1, 64);
+    mem::init_slab_cache(caches + 2, 96);
+    mem::init_slab_cache(caches + 3, 128);
+    mem::init_slab_cache(caches + 4, 192);
+    mem::init_slab_cache(caches + 5, 256);
+    mem::init_slab_cache(caches + 6, 512);
 
     types::memory::k_alloc = new types::memory::brk_memory_allocator(
         (std::byte*)KERNEL_HEAP_START, KERNEL_HEAP_SIZE);
 }
 
-void* operator new(size_t size)
-{
+void* operator new(size_t size) {
     int idx = __cache_index(size);
     void* ptr = nullptr;
     if (idx < 0)
@@ -257,8 +244,7 @@ void* operator new(size_t size)
     return ptr;
 }
 
-void operator delete(void* ptr)
-{
+void operator delete(void* ptr) {
     if (!ptr)
         return;
 
@@ -268,8 +254,7 @@ void operator delete(void* ptr)
         kernel::mem::slab_free(ptr);
 }
 
-void operator delete(void* ptr, std::size_t size)
-{
+void operator delete(void* ptr, std::size_t size) {
     if (!ptr)
         return;
 
@@ -283,17 +268,14 @@ void operator delete(void* ptr, std::size_t size)
     kernel::mem::slab_free(ptr);
 }
 
-void* operator new[](size_t sz)
-{
+void* operator new[](size_t sz) {
     return ::operator new(sz);
 }
 
-void operator delete[](void* ptr)
-{
+void operator delete[](void* ptr) {
     ::operator delete(ptr);
 }
 
-void operator delete[](void* ptr, std::size_t size)
-{
+void operator delete[](void* ptr, std::size_t size) {
     ::operator delete(ptr, size);
 }

+ 19 - 38
src/kernel/async/lock.cc

@@ -5,8 +5,7 @@
 
 namespace kernel::async {
 
-static inline void _raw_spin_lock(spinlock_t* lock_addr)
-{
+static inline void _raw_spin_lock(spinlock_t* lock_addr) {
     asm volatile(
         "%=:\n\t\
          mov $1, %%eax\n\t\
@@ -19,8 +18,7 @@ static inline void _raw_spin_lock(spinlock_t* lock_addr)
         : "eax", "memory");
 }
 
-static inline void _raw_spin_unlock(spinlock_t* lock_addr)
-{
+static inline void _raw_spin_unlock(spinlock_t* lock_addr) {
     asm volatile(
         "mov $0, %%eax\n\
          xchg %%eax, (%0)"
@@ -29,8 +27,7 @@ static inline void _raw_spin_unlock(spinlock_t* lock_addr)
         : "eax", "memory");
 }
 
-static inline lock_context_t _save_interrupt_state()
-{
+static inline lock_context_t _save_interrupt_state() {
     lock_context_t retval;
     asm volatile(
         "pushf\n\t"
@@ -38,60 +35,50 @@ static inline lock_context_t _save_interrupt_state()
         "cli"
         : "=g"(retval)
         :
-        :
-        );
+        :);
 
     return retval;
 }
 
-static inline void _restore_interrupt_state(lock_context_t context)
-{
+static inline void _restore_interrupt_state(lock_context_t context) {
     asm volatile(
         "push %0\n\t"
         "popf"
         :
         : "g"(context)
-        :
-        );
+        :);
 }
 
 // TODO: mark as _per_cpu
-static inline preempt_count_t& _preempt_count()
-{
+static inline preempt_count_t& _preempt_count() {
     static preempt_count_t _preempt_count;
     assert(!(_preempt_count & 0x80000000));
     return _preempt_count;
 }
 
-void preempt_disable()
-{
+void preempt_disable() {
     ++_preempt_count();
 }
 
-void preempt_enable()
-{
+void preempt_enable() {
     --_preempt_count();
 }
 
-preempt_count_t preempt_count()
-{
+preempt_count_t preempt_count() {
     return _preempt_count();
 }
 
-void spin_lock(spinlock_t& lock)
-{
+void spin_lock(spinlock_t& lock) {
     preempt_disable();
     _raw_spin_lock(&lock);
 }
 
-void spin_unlock(spinlock_t& lock)
-{
+void spin_unlock(spinlock_t& lock) {
     _raw_spin_unlock(&lock);
     preempt_enable();
 }
 
-lock_context_t spin_lock_irqsave(spinlock_t& lock)
-{
+lock_context_t spin_lock_irqsave(spinlock_t& lock) {
     auto state = _save_interrupt_state();
     preempt_disable();
 
@@ -100,35 +87,29 @@ lock_context_t spin_lock_irqsave(spinlock_t& lock)
     return state;
 }
 
-void spin_unlock_irqrestore(spinlock_t& lock, lock_context_t state)
-{
+void spin_unlock_irqrestore(spinlock_t& lock, lock_context_t state) {
     _raw_spin_unlock(&lock);
     preempt_enable();
     _restore_interrupt_state(state);
 }
 
-mutex::~mutex()
-{
+mutex::~mutex() {
     assert(m_lock == 0);
 }
 
-void mutex::lock()
-{
+void mutex::lock() {
     spin_lock(m_lock);
 }
 
-void mutex::unlock()
-{
+void mutex::unlock() {
     spin_unlock(m_lock);
 }
 
-lock_context_t mutex::lock_irq()
-{
+lock_context_t mutex::lock_irq() {
     return spin_lock_irqsave(m_lock);
 }
 
-void mutex::unlock_irq(lock_context_t state)
-{
+void mutex::unlock_irq(lock_context_t state) {
     spin_unlock_irqrestore(m_lock, state);
 }
 

+ 5 - 10
src/kernel/async/waitlist.cc

@@ -1,15 +1,13 @@
-#include <kernel/async/waitlist.hpp>
-
 #include <assert.h>
 
 #include <kernel/async/lock.hpp>
+#include <kernel/async/waitlist.hpp>
 #include <kernel/process.hpp>
 #include <kernel/task/thread.hpp>
 
 using namespace kernel::async;
 
-bool wait_list::wait(mutex& lock)
-{
+bool wait_list::wait(mutex& lock) {
     this->subscribe();
 
     auto* curthd = current_thread;
@@ -23,8 +21,7 @@ bool wait_list::wait(mutex& lock)
     return !has_signals;
 }
 
-void wait_list::subscribe()
-{
+void wait_list::subscribe() {
     lock_guard lck(m_mtx);
 
     auto* thd = current_thread;
@@ -35,8 +32,7 @@ void wait_list::subscribe()
     assert(inserted);
 }
 
-void wait_list::notify_one()
-{
+void wait_list::notify_one() {
     lock_guard lck(m_mtx);
 
     if (m_subscribers.empty())
@@ -48,8 +44,7 @@ void wait_list::notify_one()
     m_subscribers.erase(iter);
 }
 
-void wait_list::notify_all()
-{
+void wait_list::notify_all() {
     lock_guard lck(m_mtx);
 
     if (m_subscribers.empty())

+ 57 - 64
src/kernel/hw/ahci.cc

@@ -1,6 +1,9 @@
-#include <vector>
-#include <cstddef>
 #include <algorithm>
+#include <cstddef>
+#include <vector>
+
+#include <errno.h>
+#include <stdint.h>
 
 #include <kernel/hw/pci.hpp>
 #include <kernel/irq.hpp>
@@ -10,12 +13,10 @@
 #include <kernel/module.hpp>
 #include <kernel/vfs.hpp>
 
-#include <stdint.h>
-#include <errno.h>
-
-#define SPIN(cond, spin) \
-    (spin) = 0; \
-    while ((cond) && (spin) < MAX_SPINS) ++(spin); \
+#define SPIN(cond, spin)                 \
+    (spin) = 0;                          \
+    while ((cond) && (spin) < MAX_SPINS) \
+        ++(spin);                        \
     if ((spin) == MAX_SPINS)
 
 using namespace kernel::module;
@@ -175,7 +176,7 @@ struct fis_pio_setup {
     uint8_t fis_type;
 
     uint8_t pm_port : 4;
-    uint8_t : 1; // reserved
+    uint8_t : 1;                         // reserved
     uint8_t data_transfer_direction : 1; // device to host if set
     uint8_t interrupt : 1;
     uint8_t : 1; // reserved
@@ -239,23 +240,20 @@ struct command_table {
     prdt_entry prdt[];
 };
 
-static int stop_command(hba_port* port)
-{
-    port->command_status =
-        port->command_status & ~(PORT_CMD_ST | PORT_CMD_FRE);
+static int stop_command(hba_port* port) {
+    port->command_status = port->command_status & ~(PORT_CMD_ST | PORT_CMD_FRE);
 
     uint32_t spins = 0;
     SPIN(port->command_status & (PORT_CMD_CR | PORT_CMD_FR), spins)
-        return -1;
+    return -1;
 
     return 0;
 }
 
-static int start_command(hba_port* port)
-{
+static int start_command(hba_port* port) {
     uint32_t spins = 0;
     SPIN(port->command_status & PORT_CMD_CR, spins)
-        return -1;
+    return -1;
 
     port->command_status = port->command_status | PORT_CMD_FRE;
     port->command_status = port->command_status | PORT_CMD_ST;
@@ -263,19 +261,17 @@ static int start_command(hba_port* port)
     return 0;
 }
 
-static inline hba_port* port_ptr(hba_ghc* ghc, int i)
-{
+static inline hba_port* port_ptr(hba_ghc* ghc, int i) {
     return (hba_port*)((char*)ghc + 0x100 + i * 0x80);
 }
 
 template <std::size_t N>
 struct quick_queue {
-    std::size_t start { };
-    std::size_t end { };
-    uint8_t arr[N] { };
+    std::size_t start{};
+    std::size_t end{};
+    uint8_t arr[N]{};
 
-    quick_queue()
-    {
+    quick_queue() {
         for (std::size_t i = 0; i < N; ++i)
             arr[i] = i;
     }
@@ -286,15 +282,15 @@ struct quick_queue {
 };
 
 struct ahci_port {
-private:
+   private:
     // quick_queue<32> qu;
     physaddr<command_header, false> cmd_header;
     hba_port* port;
-    received_fis* fis { };
-    std::size_t sectors { -1U };
+    received_fis* fis{};
+    std::size_t sectors{-1U};
 
-    int send_command(physaddr<void> buf, uint64_t lba, uint32_t count, uint8_t cmd, bool write)
-    {
+    int send_command(physaddr<void> buf, uint64_t lba, uint32_t count,
+                     uint8_t cmd, bool write) {
         // count must be a multiple of 512
         if (count & (512 - 1))
             return -1;
@@ -346,24 +342,23 @@ private:
         // wait until port is not busy
         uint32_t spins = 0;
         SPIN(port->task_file_data & (ATA_DEV_BSY | ATA_DEV_DRQ), spins)
-            return -1;
+        return -1;
 
         // TODO: use interrupt
         // issue the command
         port->command_issue = 1 << n;
 
         SPIN(port->command_issue & (1 << n), spins)
-            return -1;
+        return -1;
 
         free_page(command_table_pfn);
         return 0;
     }
 
-    int identify()
-    {
+    int identify() {
         pfn_t buffer_page = page_to_pfn(alloc_page());
-        int ret = send_command(physaddr<void>{buffer_page},
-                0, 512, 0xEC, false);
+        int ret =
+            send_command(physaddr<void>{buffer_page}, 0, 512, 0xEC, false);
 
         free_page(buffer_page);
         if (ret != 0)
@@ -371,19 +366,18 @@ private:
         return 0;
     }
 
-public:
+   public:
     explicit ahci_port(hba_port* port)
-        : cmd_header{page_to_pfn(alloc_page())}, port(port) { }
+        : cmd_header{page_to_pfn(alloc_page())}, port(port) {}
 
-    ~ahci_port()
-    {
+    ~ahci_port() {
         if (!cmd_header)
             return;
         free_page(cmd_header.phys());
     }
 
-    ssize_t read(char* buf, std::size_t buf_size, std::size_t offset, std::size_t cnt)
-    {
+    ssize_t read(char* buf, std::size_t buf_size, std::size_t offset,
+                 std::size_t cnt) {
         cnt = std::min(buf_size, cnt);
 
         pfn_t buffer_page = page_to_pfn(alloc_page());
@@ -413,8 +407,7 @@ public:
         return buf - orig_buf;
     }
 
-    int init()
-    {
+    int init() {
         if (stop_command(port) != 0)
             return -1;
 
@@ -440,15 +433,14 @@ public:
 };
 
 class ahci_module : public virtual kernel::module::module {
-private:
-    hba_ghc* ghc { };
-    pci_device* dev { };
+   private:
+    hba_ghc* ghc{};
+    pci_device* dev{};
     std::vector<ahci_port*> ports;
 
-public:
-    ahci_module() : module("ahci") { }
-    ~ahci_module()
-    {
+   public:
+    ahci_module() : module("ahci") {}
+    ~ahci_module() {
         // TODO: release PCI device
         for (auto& item : ports) {
             if (!item)
@@ -459,8 +451,7 @@ public:
         }
     }
 
-    int probe_disks()
-    {
+    int probe_disks() {
         int ports = this->ghc->ports_implemented;
         for (int n = 0; ports; ports >>= 1, ++n) {
             if (!(ports & 1))
@@ -479,11 +470,13 @@ public:
 
             this->ports[n] = port;
 
-            fs::register_block_device(fs::make_device(8, n * 8), {
-                [port](char* buf, std::size_t buf_size, std::size_t offset, std::size_t cnt) {
-                    return port->read(buf, buf_size, offset, cnt);
-                }, nullptr
-            });
+            fs::register_block_device(
+                fs::make_device(8, n * 8),
+                {[port](char* buf, std::size_t buf_size, std::size_t offset,
+                        std::size_t cnt) {
+                     return port->read(buf, buf_size, offset, cnt);
+                 },
+                 nullptr});
 
             fs::partprobe();
         }
@@ -491,12 +484,11 @@ public:
         return 0;
     }
 
-    virtual int init() override
-    {
+    virtual int init() override {
         ports.resize(32);
 
-        auto ret = kernel::hw::pci::register_driver(VENDOR_INTEL, DEVICE_AHCI,
-            [this](pci_device* dev) -> int {
+        auto ret = kernel::hw::pci::register_driver(
+            VENDOR_INTEL, DEVICE_AHCI, [this](pci_device* dev) -> int {
                 this->dev = dev;
 
                 physaddr<hba_ghc, false> pp_base{dev->reg[PCI_REG_ABAR]};
@@ -506,7 +498,7 @@ public:
                     this->ghc->global_host_control | 2; // set interrupt enable
 
                 return this->probe_disks();
-        });
+            });
 
         if (ret != 0)
             return MODULE_FAILED;
@@ -516,6 +508,7 @@ public:
 
 } // namespace ahci
 
-kernel::module::module* ahci_module_init()
-{ return new ahci::ahci_module(); }
+kernel::module::module* ahci_module_init() {
+    return new ahci::ahci_module();
+}
 INTERNAL_MODULE(ahci_module_loader, ahci_module_init);

+ 18 - 29
src/kernel/hw/pci.cc

@@ -1,22 +1,21 @@
 #include <map>
 
-#include <kernel/hw/pci.hpp>
-#include <kernel/hw/port.hpp>
-
-#include <types/types.h>
-
 #include <assert.h>
 #include <errno.h>
 #include <stdint.h>
 
+#include <types/types.h>
+
+#include <kernel/hw/pci.hpp>
+#include <kernel/hw/port.hpp>
+
 using kernel::hw::p32;
 
 constexpr p32 paddr(0xCF8);
 constexpr p32 pdata(0xCFC);
 
 using device_no = uint32_t;
-constexpr device_no make_device(uint32_t vendor, uint32_t device)
-{
+constexpr device_no make_device(uint32_t vendor, uint32_t device) {
     return (vendor << 16) | device;
 }
 
@@ -27,16 +26,14 @@ std::map<device_no, pci_device>* pci_devices_p;
 std::map<device_no, driver_t>* pci_drivers_p;
 
 // getter of the global variable
-std::map<device_no, pci_device>& pci_devices()
-{
+std::map<device_no, pci_device>& pci_devices() {
     if (!pci_devices_p) [[unlikely]]
         pci_devices_p = new std::map<device_no, pci_device>();
     return *pci_devices_p;
 }
 
 // getter of the global variable
-std::map<device_no, driver_t>& pci_drivers()
-{
+std::map<device_no, driver_t>& pci_drivers() {
     if (!pci_drivers_p) [[unlikely]]
         pci_drivers_p = new std::map<device_no, driver_t>();
     return *pci_drivers_p;
@@ -44,19 +41,16 @@ std::map<device_no, driver_t>& pci_drivers()
 
 // class config_reg
 
-uint32_t config_reg::read32(uint32_t offset) const
-{
+uint32_t config_reg::read32(uint32_t offset) const {
     paddr = (addr_base | (offset & 0xFC));
     return *pdata;
 }
 
-uint16_t config_reg::read16(uint16_t offset) const
-{
+uint16_t config_reg::read16(uint16_t offset) const {
     return (read32(offset) >> ((offset & 2) << 3)) & 0xFFFF;
 }
 
-uint32_t config_reg::operator[](uint32_t n) const
-{
+uint32_t config_reg::operator[](uint32_t n) const {
     return read32(n << 2);
 }
 
@@ -64,9 +58,7 @@ uint32_t config_reg::operator[](uint32_t n) const
 
 // class pci_device
 
-pci_device::pci_device(config_reg reg)
-    : reg(reg)
-{
+pci_device::pci_device(config_reg reg) : reg(reg) {
     uint32_t tmp = reg[0];
 
     vendor = tmp & 0xFFFF;
@@ -83,8 +75,7 @@ pci_device::pci_device(config_reg reg)
 
 // end class pci_device
 
-pci_device* probe_device(uint8_t bus, uint8_t dev, uint8_t func)
-{
+pci_device* probe_device(uint8_t bus, uint8_t dev, uint8_t func) {
     config_reg reg(bus, dev, func);
 
     uint32_t tmp = reg[0];
@@ -94,15 +85,14 @@ pci_device* probe_device(uint8_t bus, uint8_t dev, uint8_t func)
     if (vendor == 0xFFFF)
         return nullptr;
 
-    auto [ iter, inserted ] = hw::pci::pci_devices().emplace(
-        make_device(vendor, device), reg);
+    auto [iter, inserted] =
+        hw::pci::pci_devices().emplace(make_device(vendor, device), reg);
     assert(inserted);
 
     return &iter->second;
 }
 
-int register_driver(uint16_t vendor, uint16_t device, driver_t drv)
-{
+int register_driver(uint16_t vendor, uint16_t device, driver_t drv) {
     auto& drivers = pci_drivers();
     device_no dev = make_device(vendor, device);
 
@@ -110,7 +100,7 @@ int register_driver(uint16_t vendor, uint16_t device, driver_t drv)
     if (iter != drivers.end())
         return -EEXIST;
 
-    auto [ _, inserted ] = drivers.emplace(dev, drv);
+    auto [_, inserted] = drivers.emplace(dev, drv);
     assert(inserted);
 
     auto& devices = pci_devices();
@@ -128,8 +118,7 @@ int register_driver(uint16_t vendor, uint16_t device, driver_t drv)
 namespace kernel::kinit {
 
 SECTION(".text.kinit")
-void init_pci()
-{
+void init_pci() {
     for (int bus = 0; bus < 256; ++bus) {
         for (int dev = 0; dev < 32; ++dev) {
             for (int func = 0; func < 8; ++func) {

+ 19 - 33
src/kernel/hw/serial.cc

@@ -16,37 +16,26 @@ constexpr int PORT1 = 0x2f8;
 using port_group = const p8[6];
 
 constexpr p8 port0[] = {
-    p8{PORT0+0},
-    p8{PORT0+1},
-    p8{PORT0+2},
-    p8{PORT0+3},
-    p8{PORT0+4},
-    p8{PORT0+5},
+    p8{PORT0 + 0}, p8{PORT0 + 1}, p8{PORT0 + 2},
+    p8{PORT0 + 3}, p8{PORT0 + 4}, p8{PORT0 + 5},
 };
 
 constexpr p8 port1[] = {
-    p8{PORT1+0},
-    p8{PORT1+1},
-    p8{PORT1+2},
-    p8{PORT1+3},
-    p8{PORT1+4},
-    p8{PORT1+5},
+    p8{PORT1 + 0}, p8{PORT1 + 1}, p8{PORT1 + 2},
+    p8{PORT1 + 3}, p8{PORT1 + 4}, p8{PORT1 + 5},
 };
 
-static void _serial0_receive_data_interrupt()
-{
+static void _serial0_receive_data_interrupt() {
     while (*port0[5] & 1)
         console->commit_char(*port0[0]);
 }
 
-static void _serial1_receive_data_interrupt()
-{
+static void _serial1_receive_data_interrupt() {
     while (*port1[5] & 1)
         console->commit_char(*port1[0]);
 }
 
-static inline int _init_port(port_group ports)
-{
+static inline int _init_port(port_group ports) {
     // taken from osdev.org
 
     ports[1] = 0x00; // Disable all interrupts
@@ -59,7 +48,8 @@ static inline int _init_port(port_group ports)
     // TODO: IRQ disabled
     ports[4] = 0x0B; // IRQs enabled, RTS/DSR set
     ports[4] = 0x1E; // Set in loopback mode, test the serial chip
-    ports[0] = 0xAE; // Test serial chip (send byte 0xAE and check if serial returns same byte)
+    ports[0] = 0xAE; // Test serial chip (send byte 0xAE and check if serial
+                     // returns same byte)
 
     // Check if serial is faulty (i.e: not same byte as sent)
     if (*ports[0] != 0xAE)
@@ -77,15 +67,12 @@ static inline int _init_port(port_group ports)
 class serial_tty : public virtual tty {
     const p8* ports;
 
-public:
-    serial_tty(port_group ports, int id)
-        : tty{"ttyS"}, ports(ports)
-    {
-        name += '0'+id;
+   public:
+    serial_tty(port_group ports, int id) : tty{"ttyS"}, ports(ports) {
+        name += '0' + id;
     }
 
-    virtual void putchar(char c) override
-    {
+    virtual void putchar(char c) override {
         while (!(*ports[5] & 0x20))
             ; // nop
         ports[0] = c;
@@ -93,11 +80,10 @@ public:
 };
 
 class serial_module : public virtual kernel::module::module {
-public:
-    serial_module() : module("serial-tty") { }
+   public:
+    serial_module() : module("serial-tty") {}
 
-    virtual int init() override
-    {
+    virtual int init() override {
         if (int ret = _init_port(port0); ret == 0) {
             auto* dev = new serial_tty(port0, 0);
             kernel::irq::register_handler(4, _serial0_receive_data_interrupt);
@@ -116,9 +102,9 @@ public:
 
         return kernel::module::MODULE_SUCCESS;
     }
-
 };
 
-kernel::module::module* serial_module_init()
-{ return new serial_module(); }
+kernel::module::module* serial_module_init() {
+    return new serial_module();
+}
 INTERNAL_MODULE(serial_module_loader, serial_module_init);

+ 3 - 6
src/kernel/hw/timer.cc

@@ -9,8 +9,7 @@ constexpr kernel::hw::p8 port_count(0x40);
 static std::size_t _current_ticks = 0;
 
 SECTION(".text.kinit")
-void kernel::hw::timer::init_pit(void)
-{
+void kernel::hw::timer::init_pit(void) {
     // set interval
     port_control = 0x34;
 
@@ -20,12 +19,10 @@ void kernel::hw::timer::init_pit(void)
     port_count = 0x2e;
 }
 
-void kernel::hw::timer::inc_tick(void)
-{
+void kernel::hw::timer::inc_tick(void) {
     ++_current_ticks;
 }
 
-size_t kernel::hw::timer::current_ticks(void)
-{
+size_t kernel::hw::timer::current_ticks(void) {
     return _current_ticks;
 }

+ 26 - 29
src/kernel/interrupt.cpp

@@ -42,9 +42,8 @@ static struct IDT_entry IDT[256];
 extern "C" uintptr_t ISR_START_ADDR;
 
 SECTION(".text.kinit")
-static inline void set_idt_entry(IDT_entry (&idt)[256], int n,
-    uintptr_t offset, uint16_t selector, uint8_t type)
-{
+static inline void set_idt_entry(IDT_entry (&idt)[256], int n, uintptr_t offset,
+                                 uint16_t selector, uint8_t type) {
     idt[n].offset_low = offset & 0xffff;
     idt[n].segment = selector;
     idt[n].IST = 0;
@@ -58,18 +57,19 @@ using kernel::irq::irq_handler_t;
 static std::vector<std::list<irq_handler_t>> s_irq_handlers;
 
 SECTION(".text.kinit")
-void kernel::kinit::init_interrupt()
-{
+void kernel::kinit::init_interrupt() {
     for (int i = 0; i < 0x30; ++i)
-        set_idt_entry(IDT, i, ISR_START_ADDR+8*i, 0x08, KERNEL_INTERRUPT_GATE_TYPE);
-    set_idt_entry(IDT, 0x80, ISR_START_ADDR+8*0x80, 0x08, USER_INTERRUPT_GATE_TYPE);
+        set_idt_entry(IDT, i, ISR_START_ADDR + 8 * i, 0x08,
+                      KERNEL_INTERRUPT_GATE_TYPE);
+    set_idt_entry(IDT, 0x80, ISR_START_ADDR + 8 * 0x80, 0x08,
+                  USER_INTERRUPT_GATE_TYPE);
 
     uint64_t idt_descriptor[2];
     idt_descriptor[0] = (sizeof(IDT_entry) * 256) << 48;
     idt_descriptor[1] = (uintptr_t)IDT;
 
     // initialize PIC
-    asm volatile("lidt (%0)": :"r"((uintptr_t)idt_descriptor + 6): );
+    asm volatile("lidt (%0)" : : "r"((uintptr_t)idt_descriptor + 6) :);
     s_irq_handlers.resize(16);
 
     // TODO: move this to timer driver
@@ -93,35 +93,32 @@ void kernel::kinit::init_interrupt()
     port_pic2_data = 0x00;
 }
 
-void kernel::irq::register_handler(int irqno, irq_handler_t handler)
-{
+void kernel::irq::register_handler(int irqno, irq_handler_t handler) {
     s_irq_handlers[irqno].emplace_back(std::move(handler));
 }
 
-static inline void fault_handler(interrupt_stack* context, mmx_registers*)
-{
+static inline void fault_handler(interrupt_stack* context, mmx_registers*) {
     switch (context->int_no) {
-    case 6:
-    case 8: {
-        if (!current_process->attr.system)
-            kill_current(SIGSEGV); // noreturn
-    } break;
-    case 13: {
-        if (!current_process->attr.system)
-            kill_current(SIGILL); // noreturn
-    } break;
-    case 14: {
-        kernel::mem::paging::handle_page_fault(context->error_code);
-        return;
-    } break;
+        case 6:
+        case 8: {
+            if (!current_process->attr.system)
+                kill_current(SIGSEGV); // noreturn
+        } break;
+        case 13: {
+            if (!current_process->attr.system)
+                kill_current(SIGILL); // noreturn
+        } break;
+        case 14: {
+            kernel::mem::paging::handle_page_fault(context->error_code);
+            return;
+        } break;
     }
 
     // fault can not be resolved
     freeze();
 }
 
-static inline void irq_handler(interrupt_stack* context, mmx_registers*)
-{
+static inline void irq_handler(interrupt_stack* context, mmx_registers*) {
     int irqno = context->int_no - 0x20;
 
     constexpr uint8_t PIC_EOI = 0x20;
@@ -134,8 +131,8 @@ static inline void irq_handler(interrupt_stack* context, mmx_registers*)
         handler();
 }
 
-extern "C" void interrupt_handler(interrupt_stack* context, mmx_registers* mmxregs)
-{
+extern "C" void interrupt_handler(interrupt_stack* context,
+                                  mmx_registers* mmxregs) {
     if (context->int_no < 0x20) // interrupt is a fault
         fault_handler(context, mmxregs);
     else if (context->int_no == 0x80) // syscall by int 0x80

+ 38 - 60
src/kernel/mem/mm_list.cc

@@ -5,21 +5,19 @@
 #include <kernel/mem/paging.hpp>
 #include <kernel/mem/vm_area.hpp>
 
-
 using namespace kernel::mem;
 
-static inline void __invalidate_all_tlb()
-{
+static inline void __invalidate_all_tlb() {
     asm volatile(
-            "mov %%cr3, %%rax\n\t"
-            "mov %%rax, %%cr3\n\t"
-            : : : "rax", "memory"
-            );
+        "mov %%cr3, %%rax\n\t"
+        "mov %%rax, %%cr3\n\t"
+        :
+        :
+        : "rax", "memory");
 }
 
-static inline void __dealloc_page_table_all(
-        paging::pfn_t pt, int depth, int from, int to)
-{
+static inline void __dealloc_page_table_all(paging::pfn_t pt, int depth,
+                                            int from, int to) {
     using namespace paging;
 
     if (depth > 1) {
@@ -29,15 +27,14 @@ static inline void __dealloc_page_table_all(
                 continue;
 
             int pfn = pse.pfn();
-            __dealloc_page_table_all(pfn, depth-1, 0, 512);
+            __dealloc_page_table_all(pfn, depth - 1, 0, 512);
         }
     }
 
     free_page(pt);
 }
 
-static inline void __dealloc_page_table(paging::pfn_t pt)
-{
+static inline void __dealloc_page_table(paging::pfn_t pt) {
     using namespace paging;
     auto start_idx = idx_p4(0);
     auto end_idx = idx_p4(KERNEL_SPACE_START);
@@ -45,16 +42,11 @@ static inline void __dealloc_page_table(paging::pfn_t pt)
     __dealloc_page_table_all(pt, 4, start_idx, end_idx);
 }
 
-mm_list::mm_list()
-    : m_pt{paging::alloc_page_table()}
-    , m_brk{m_areas.end()}
-{
-    memcpy(physaddr<void>{m_pt},
-           paging::KERNEL_PAGE_TABLE_PHYS_ADDR, 0x1000);
+mm_list::mm_list() : m_pt{paging::alloc_page_table()}, m_brk{m_areas.end()} {
+    memcpy(physaddr<void>{m_pt}, paging::KERNEL_PAGE_TABLE_PHYS_ADDR, 0x1000);
 }
 
-mm_list::mm_list(const mm_list& other): mm_list{}
-{
+mm_list::mm_list(const mm_list& other) : mm_list{} {
     m_areas = other.m_areas;
 
     using namespace paging;
@@ -91,8 +83,7 @@ mm_list::mm_list(const mm_list& other): mm_list{}
     __invalidate_all_tlb();
 }
 
-mm_list::~mm_list()
-{
+mm_list::~mm_list() {
     if (!m_pt)
         return;
 
@@ -100,8 +91,7 @@ mm_list::~mm_list()
     __dealloc_page_table(m_pt);
 }
 
-bool mm_list::is_avail(uintptr_t start, std::size_t len) const noexcept
-{
+bool mm_list::is_avail(uintptr_t start, std::size_t len) const noexcept {
     start &= ~0xfff;
     uintptr_t end = (start + len + 0xfff) & ~0xfff;
     len = end - start;
@@ -116,8 +106,7 @@ bool mm_list::is_avail(uintptr_t start, std::size_t len) const noexcept
     return true;
 }
 
-bool mm_list::is_avail(uintptr_t addr) const
-{
+bool mm_list::is_avail(uintptr_t addr) const {
     if (addr >= USER_SPACE_MEMORY_TOP)
         return false;
 
@@ -125,8 +114,7 @@ bool mm_list::is_avail(uintptr_t addr) const
     return iter == m_areas.end();
 }
 
-uintptr_t mm_list::find_avail(uintptr_t hint, size_t len) const
-{
+uintptr_t mm_list::find_avail(uintptr_t hint, size_t len) const {
     auto addr = std::max(hint, MMAP_MIN_ADDR);
 
     while (!is_avail(addr, len)) {
@@ -140,32 +128,29 @@ uintptr_t mm_list::find_avail(uintptr_t hint, size_t len) const
     return addr;
 }
 
-void mm_list::switch_pd() const noexcept
-{
-    asm volatile("mov %0, %%cr3": : "r"(m_pt): "memory");
+void mm_list::switch_pd() const noexcept {
+    asm volatile("mov %0, %%cr3" : : "r"(m_pt) : "memory");
 }
 
-int mm_list::register_brk(uintptr_t addr)
-{
+int mm_list::register_brk(uintptr_t addr) {
     assert(m_brk == m_areas.end());
     if (!is_avail(addr))
         return -ENOMEM;
 
     bool inserted;
-    std::tie(m_brk, inserted) = m_areas.emplace(
-            addr, MM_ANONYMOUS | MM_WRITE | MM_BREAK);
+    std::tie(m_brk, inserted) =
+        m_areas.emplace(addr, MM_ANONYMOUS | MM_WRITE | MM_BREAK);
 
     assert(inserted);
     return 0;
 }
 
-uintptr_t mm_list::set_brk(uintptr_t addr)
-{
+uintptr_t mm_list::set_brk(uintptr_t addr) {
     using namespace paging;
     assert(m_brk != m_areas.end());
     uintptr_t curbrk = m_brk->end;
 
-    addr += 4096-1;
+    addr += 4096 - 1;
     addr &= ~0xfff;
 
     if (addr <= curbrk || !is_avail(curbrk, addr - curbrk))
@@ -178,8 +163,7 @@ uintptr_t mm_list::set_brk(uintptr_t addr)
     return m_brk->end;
 }
 
-void mm_list::clear()
-{
+void mm_list::clear() {
     for (auto iter = m_areas.begin(); iter != m_areas.end(); ++iter)
         unmap(iter, false);
 
@@ -189,8 +173,7 @@ void mm_list::clear()
     m_brk = m_areas.end();
 }
 
-mm_list::iterator mm_list::split(iterator area, uintptr_t addr)
-{
+mm_list::iterator mm_list::split(iterator area, uintptr_t addr) {
     assert(!(addr & 0xfff));
     assert(addr > area->start && addr < area->end);
 
@@ -203,16 +186,14 @@ mm_list::iterator mm_list::split(iterator area, uintptr_t addr)
     auto new_end = area->end;
     area->end = addr;
 
-    auto [ iter, inserted ] =
-        m_areas.emplace(addr, area->flags, new_end,
-                area->mapped_file, new_file_offset);
+    auto [iter, inserted] = m_areas.emplace(addr, area->flags, new_end,
+                                            area->mapped_file, new_file_offset);
 
     assert(inserted);
     return iter;
 }
 
-int mm_list::unmap(iterator area, bool should_invalidate_tlb)
-{
+int mm_list::unmap(iterator area, bool should_invalidate_tlb) {
     using namespace paging;
 
     bool should_use_invlpg = area->end - area->start <= 0x4000;
@@ -225,7 +206,7 @@ int mm_list::unmap(iterator area, bool should_invalidate_tlb)
         pte.clear();
 
         if (should_invalidate_tlb && should_use_invlpg) {
-            asm volatile("invlpg (%0)": : "r"(cur_addr): "memory");
+            asm volatile("invlpg (%0)" : : "r"(cur_addr) : "memory");
             cur_addr += 0x1000;
         }
     }
@@ -236,8 +217,8 @@ int mm_list::unmap(iterator area, bool should_invalidate_tlb)
     return 0;
 }
 
-int mm_list::unmap(uintptr_t start, std::size_t length, bool should_invalidate_tlb)
-{
+int mm_list::unmap(uintptr_t start, std::size_t length,
+                   bool should_invalidate_tlb) {
     // standard says that addr and len MUST be
     // page-aligned or the call is invalid
     if (start & 0xfff)
@@ -295,8 +276,7 @@ int mm_list::unmap(uintptr_t start, std::size_t length, bool should_invalidate_t
     return 0;
 }
 
-int mm_list::mmap(const map_args& args)
-{
+int mm_list::mmap(const map_args& args) {
     auto& vaddr = args.vaddr;
     auto& length = args.length;
     auto& finode = args.file_inode;
@@ -321,26 +301,24 @@ int mm_list::mmap(const map_args& args)
         assert(finode);
         assert(S_ISREG(finode->mode) || S_ISBLK(finode->mode));
 
-        auto [ area, inserted ] = m_areas.emplace(
-                vaddr, flags & ~MM_INTERNAL_MASK, vaddr + length, finode, foff);
+        auto [area, inserted] = m_areas.emplace(
+            vaddr, flags & ~MM_INTERNAL_MASK, vaddr + length, finode, foff);
         assert(inserted);
 
         attributes |= PA_MMAPPED_PAGE;
         for (auto pte : vaddr_range{m_pt, vaddr, vaddr + length})
             pte.set(attributes, EMPTY_PAGE_PFN);
-    }
-    else if (flags & MM_ANONYMOUS) {
+    } else if (flags & MM_ANONYMOUS) {
         // private mapping of zero-filled pages
         // TODO: shared mapping
-        auto [ area, inserted ] =
+        auto [area, inserted] =
             m_areas.emplace(vaddr, (flags & ~MM_INTERNAL_MASK), vaddr + length);
         assert(inserted);
 
         attributes |= PA_ANONYMOUS_PAGE;
         for (auto pte : vaddr_range{m_pt, vaddr, vaddr + length})
             pte.set(attributes, EMPTY_PAGE_PFN);
-    }
-    else {
+    } else {
         return -EINVAL;
     }
 

+ 57 - 82
src/kernel/mem/paging.cc

@@ -16,14 +16,12 @@ using namespace types::list;
 using namespace kernel::async;
 using namespace kernel::mem::paging;
 
-static inline void __page_fault_die(uintptr_t vaddr)
-{
+static inline void __page_fault_die(uintptr_t vaddr) {
     kmsgf("[kernel] kernel panic: invalid memory access to %p", vaddr);
     freeze();
 }
 
-static inline PSE __parse_pse(PSE pse, bool priv)
-{
+static inline PSE __parse_pse(PSE pse, bool priv) {
     auto attr = priv ? PA_KERNEL_PAGE_TABLE : PA_USER_PAGE_TABLE;
     if (!(pse.attributes() & PA_P))
         pse.set(attr, alloc_page_table());
@@ -38,27 +36,23 @@ static struct zone_info {
 
 static mutex zone_lock;
 
-constexpr unsigned _msb(std::size_t x)
-{
+constexpr unsigned _msb(std::size_t x) {
     unsigned n = 0;
     while (x >>= 1)
         n++;
     return n;
 }
 
-constexpr pfn_t buddy(pfn_t pfn, unsigned order)
-{
+constexpr pfn_t buddy(pfn_t pfn, unsigned order) {
     return pfn ^ (1 << (order + 12));
 }
 
-constexpr pfn_t parent(pfn_t pfn, unsigned order)
-{
+constexpr pfn_t parent(pfn_t pfn, unsigned order) {
     return pfn & ~(1 << (order + 12));
 }
 
 // call with zone_lock held
-static inline void _zone_list_insert(unsigned order, page* zone)
-{
+static inline void _zone_list_insert(unsigned order, page* zone) {
     assert(zone->flags & PAGE_PRESENT && zone->flags & PAGE_BUDDY);
     assert((zone->flags & 0xff) == 0);
     zone->flags |= order;
@@ -68,8 +62,7 @@ static inline void _zone_list_insert(unsigned order, page* zone)
 }
 
 // call with zone_lock held
-static inline void _zone_list_remove(unsigned order, page* zone)
-{
+static inline void _zone_list_remove(unsigned order, page* zone) {
     assert(zone->flags & PAGE_PRESENT && zone->flags & PAGE_BUDDY);
     assert(zones[order].count > 0 && (zone->flags & 0xff) == order);
     zone->flags &= ~0xff;
@@ -79,8 +72,7 @@ static inline void _zone_list_remove(unsigned order, page* zone)
 }
 
 // call with zone_lock held
-static inline page* _zone_list_get(unsigned order)
-{
+static inline page* _zone_list_get(unsigned order) {
     if (zones[order].count == 0)
         return nullptr;
 
@@ -93,8 +85,7 @@ static inline page* _zone_list_get(unsigned order)
 
 // where order represents power of 2
 // call with zone_lock held
-static inline page* _create_zone(pfn_t pfn, unsigned order)
-{
+static inline page* _create_zone(pfn_t pfn, unsigned order) {
     page* zone = pfn_to_page(pfn);
 
     assert(zone->flags & PAGE_PRESENT);
@@ -105,8 +96,8 @@ static inline page* _create_zone(pfn_t pfn, unsigned order)
 }
 
 // call with zone_lock held
-static inline void _split_zone(page* zone, unsigned order, unsigned target_order)
-{
+static inline void _split_zone(page* zone, unsigned order,
+                               unsigned target_order) {
     while (order > target_order) {
         pfn_t pfn = page_to_pfn(zone);
         _create_zone(buddy(pfn, order - 1), order - 1);
@@ -119,8 +110,7 @@ static inline void _split_zone(page* zone, unsigned order, unsigned target_order
 }
 
 // call with zone_lock held
-static inline page* _alloc_zone(unsigned order)
-{
+static inline page* _alloc_zone(unsigned order) {
     for (unsigned i = order; i < 52; ++i) {
         auto zone = _zone_list_get(i);
         if (!zone)
@@ -138,8 +128,7 @@ static inline page* _alloc_zone(unsigned order)
     return nullptr;
 }
 
-void kernel::mem::paging::create_zone(uintptr_t start, uintptr_t end)
-{
+void kernel::mem::paging::create_zone(uintptr_t start, uintptr_t end) {
     start += (4096 - 1);
     start >>= 12;
     end >>= 12;
@@ -153,7 +142,7 @@ void kernel::mem::paging::create_zone(uintptr_t start, uintptr_t end)
     for (unsigned i = 0; i < _msb(end); ++i, low >>= 1) {
         if (!(low & 1))
             continue;
-        _create_zone(low << (12+i), i);
+        _create_zone(low << (12 + i), i);
         low++;
     }
 
@@ -165,8 +154,7 @@ void kernel::mem::paging::create_zone(uintptr_t start, uintptr_t end)
     }
 }
 
-void kernel::mem::paging::mark_present(uintptr_t start, uintptr_t end)
-{
+void kernel::mem::paging::mark_present(uintptr_t start, uintptr_t end) {
     start >>= 12;
 
     end += (4096 - 1);
@@ -176,8 +164,7 @@ void kernel::mem::paging::mark_present(uintptr_t start, uintptr_t end)
         PAGE_ARRAY[start++].flags |= PAGE_PRESENT;
 }
 
-page* kernel::mem::paging::alloc_pages(unsigned order)
-{
+page* kernel::mem::paging::alloc_pages(unsigned order) {
     lock_guard_irq lock{zone_lock};
     auto* zone = _alloc_zone(order);
     if (!zone)
@@ -186,13 +173,11 @@ page* kernel::mem::paging::alloc_pages(unsigned order)
     return zone;
 }
 
-page* kernel::mem::paging::alloc_page()
-{
+page* kernel::mem::paging::alloc_page() {
     return alloc_pages(0);
 }
 
-pfn_t kernel::mem::paging::alloc_page_table()
-{
+pfn_t kernel::mem::paging::alloc_page_table() {
     page* zone = alloc_page();
     pfn_t pfn = page_to_pfn(zone);
 
@@ -201,8 +186,7 @@ pfn_t kernel::mem::paging::alloc_page_table()
     return pfn;
 }
 
-void kernel::mem::paging::free_pages(page* pg, unsigned order)
-{
+void kernel::mem::paging::free_pages(page* pg, unsigned order) {
     assert((pg->flags & 0xff) == order);
 
     // TODO: atomic
@@ -237,48 +221,41 @@ void kernel::mem::paging::free_pages(page* pg, unsigned order)
     _zone_list_insert(order, pg);
 }
 
-void kernel::mem::paging::free_page(page* page)
-{
+void kernel::mem::paging::free_page(page* page) {
     return free_pages(page, 0);
 }
 
-void kernel::mem::paging::free_pages(pfn_t pfn, unsigned order)
-{
+void kernel::mem::paging::free_pages(pfn_t pfn, unsigned order) {
     return free_pages(pfn_to_page(pfn), order);
 }
 
-void kernel::mem::paging::free_page(pfn_t pfn)
-{
+void kernel::mem::paging::free_page(pfn_t pfn) {
     return free_page(pfn_to_page(pfn));
 }
 
-pfn_t kernel::mem::paging::page_to_pfn(page* _page)
-{
+pfn_t kernel::mem::paging::page_to_pfn(page* _page) {
     return (pfn_t)(_page - PAGE_ARRAY) * 0x1000;
 }
 
-page* kernel::mem::paging::pfn_to_page(pfn_t pfn)
-{
+page* kernel::mem::paging::pfn_to_page(pfn_t pfn) {
     return PAGE_ARRAY + pfn / 0x1000;
 }
 
-void kernel::mem::paging::increase_refcount(page* pg)
-{
+void kernel::mem::paging::increase_refcount(page* pg) {
     pg->refcount++;
 }
 
-void kernel::mem::paging::handle_page_fault(unsigned long err)
-{
+void kernel::mem::paging::handle_page_fault(unsigned long err) {
     using namespace kernel::mem;
     using namespace paging;
 
     uintptr_t vaddr;
-    asm volatile("mov %%cr2, %0": "=g"(vaddr): : );
+    asm volatile("mov %%cr2, %0" : "=g"(vaddr) : :);
     auto& mms = current_process->mms;
 
     auto* mm_area = mms.find(vaddr);
     if (!mm_area) [[unlikely]] {
-        // user access of address that does not exist
+        // user access to address that does not exist
         if (err & PAGE_FAULT_U)
             kill_current(SIGSEGV);
 
@@ -355,12 +332,8 @@ void kernel::mem::paging::handle_page_fault(unsigned long err)
         size_t offset = (vaddr & ~0xfff) - mm_area->start;
         char* data = physaddr<char>{pfn};
 
-        int n = fs::read(
-            mm_area->mapped_file,
-            data,
-            4096,
-            mm_area->file_offset + offset,
-            4096);
+        int n = fs::read(mm_area->mapped_file, data, 4096,
+                         mm_area->file_offset + offset, 4096);
 
         // TODO: send SIGBUS if offset is greater than real size
         if (n != 4096)
@@ -374,7 +347,7 @@ void kernel::mem::paging::handle_page_fault(unsigned long err)
 }
 
 vaddr_range::vaddr_range(pfn_t pt, uintptr_t start, uintptr_t end, bool priv)
-    : n {start >= end ? 0 : ((end - start) >> 12)}
+    : n{start >= end ? 0 : ((end - start) >> 12)}
     , idx4{!n ? 0 : idx_p4(start)}
     , idx3{!n ? 0 : idx_p3(start)}
     , idx2{!n ? 0 : idx_p2(start)}
@@ -383,46 +356,50 @@ vaddr_range::vaddr_range(pfn_t pt, uintptr_t start, uintptr_t end, bool priv)
     , pdpt{!n ? PSE{0} : __parse_pse(pml4[idx4], priv)}
     , pd{!n ? PSE{0} : __parse_pse(pdpt[idx3], priv)}
     , pt{!n ? PSE{0} : __parse_pse(pd[idx2], priv)}
-    , m_start{!n ? 0 : start}, m_end{!n ? 0 : end}
-    , is_privilege{!n ? false : priv} { }
+    , m_start{!n ? 0 : start}
+    , m_end{!n ? 0 : end}
+    , is_privilege{!n ? false : priv} {}
 
 vaddr_range::vaddr_range(std::nullptr_t)
     : n{}
-    , idx4{}, idx3{}, idx2{}, idx1{}
-    , pml4{0}, pdpt{0}
-    , pd{0}, pt{0}
-    , m_start{}, m_end{}, is_privilege{} { }
-
-vaddr_range vaddr_range::begin() const noexcept
-{
+    , idx4{}
+    , idx3{}
+    , idx2{}
+    , idx1{}
+    , pml4{0}
+    , pdpt{0}
+    , pd{0}
+    , pt{0}
+    , m_start{}
+    , m_end{}
+    , is_privilege{} {}
+
+vaddr_range vaddr_range::begin() const noexcept {
     return *this;
 }
 
-vaddr_range vaddr_range::end() const noexcept
-{
-    return vaddr_range {nullptr};
+vaddr_range vaddr_range::end() const noexcept {
+    return vaddr_range{nullptr};
 }
 
-PSE vaddr_range::operator*() const noexcept
-{
+PSE vaddr_range::operator*() const noexcept {
     return pt[idx1];
 }
 
-vaddr_range& vaddr_range::operator++()
-{
+vaddr_range& vaddr_range::operator++() {
     --n;
 
-    if ((idx1 = (idx1+1)%512) != 0)
+    if ((idx1 = (idx1 + 1) % 512) != 0)
         return *this;
 
     do {
-        if ((idx2 = (idx2+1)%512) != 0)
+        if ((idx2 = (idx2 + 1) % 512) != 0)
             break;
         do {
-            if ((idx3 = (idx3+1)%512) != 0)
+            if ((idx3 = (idx3 + 1) % 512) != 0)
                 break;
 
-            idx4 = (idx4+1) % 512;
+            idx4 = (idx4 + 1) % 512;
 
             // if idx4 is 0 after update, we have an overflow
             assert(idx4 != 0);
@@ -437,12 +414,10 @@ vaddr_range& vaddr_range::operator++()
     return *this;
 }
 
-vaddr_range::operator bool() const noexcept
-{
+vaddr_range::operator bool() const noexcept {
     return n;
 }
 
-bool vaddr_range::operator==(const vaddr_range& other) const noexcept
-{
+bool vaddr_range::operator==(const vaddr_range& other) const noexcept {
     return n == other.n;
 }

+ 8 - 13
src/kernel/mem/slab.cc

@@ -12,18 +12,15 @@ using namespace types::list;
 
 constexpr std::size_t SLAB_PAGE_SIZE = 0x1000; // 4K
 
-std::ptrdiff_t _slab_data_start_offset(std::size_t size)
-{
+std::ptrdiff_t _slab_data_start_offset(std::size_t size) {
     return (sizeof(slab_head) + size - 1) & ~(size - 1);
 }
 
-std::size_t _slab_max_count(std::size_t size)
-{
+std::size_t _slab_max_count(std::size_t size) {
     return (SLAB_PAGE_SIZE - _slab_data_start_offset(size)) / size;
 }
 
-void* _slab_head_alloc(slab_head* slab)
-{
+void* _slab_head_alloc(slab_head* slab) {
     if (slab->free_count == 0)
         return nullptr;
 
@@ -34,8 +31,7 @@ void* _slab_head_alloc(slab_head* slab)
     return ptr;
 }
 
-slab_head* _make_slab(uintptr_t start, std::size_t size)
-{
+slab_head* _make_slab(uintptr_t start, std::size_t size) {
     slab_head* slab = physaddr<slab_head>{start};
 
     slab->obj_size = size;
@@ -48,7 +44,7 @@ slab_head* _make_slab(uintptr_t start, std::size_t size)
     std::byte* ptr = (std::byte*)slab->free;
     for (unsigned i = 0; i < slab->free_count; ++i) {
         void* nextptr = ptr + size;
-        if (i == slab->free_count-1)
+        if (i == slab->free_count - 1)
             *(void**)ptr = nullptr;
         else
             *(void**)ptr = nextptr;
@@ -72,7 +68,7 @@ void _slab_add_page(slab_cache* cache) {
 
 void* kernel::mem::slab_alloc(slab_cache* cache) {
     slab_head* slab = cache->slabs_partial;
-    if (!slab) { // no partial slabs, try to get an empty slab
+    if (!slab) {                 // no partial slabs, try to get an empty slab
         if (!cache->slabs_empty) // no empty slabs, create a new one
             _slab_add_page(cache);
 
@@ -92,7 +88,7 @@ void* kernel::mem::slab_alloc(slab_cache* cache) {
 }
 
 void kernel::mem::slab_free(void* ptr) {
-    slab_head* slab = (slab_head*)((uintptr_t)ptr & ~(SLAB_PAGE_SIZE-1));
+    slab_head* slab = (slab_head*)((uintptr_t)ptr & ~(SLAB_PAGE_SIZE - 1));
 
     *(void**)ptr = slab->free;
     slab->free = ptr;
@@ -114,8 +110,7 @@ void kernel::mem::slab_free(void* ptr) {
     }
 }
 
-void kernel::mem::init_slab_cache(slab_cache* cache, std::size_t obj_size)
-{
+void kernel::mem::init_slab_cache(slab_cache* cache, std::size_t obj_size) {
     cache->obj_size = obj_size;
     cache->slabs_empty = nullptr;
     cache->slabs_partial = nullptr;

+ 1 - 1
src/kernel/module.cc

@@ -2,7 +2,7 @@
 
 namespace kernel::module {
 
-module::module(const char* name) : name(name) { }
+module::module(const char* name) :name(name) {}
 
 int insmod(module* mod) {
     int ret = mod->init();

+ 56 - 66
src/kernel/process.cpp

@@ -27,10 +27,15 @@
 #include <kernel/vfs/dentry.hpp>
 
 process::process(const process& parent, pid_t pid)
-    : mms{parent.mms}, attr{parent.attr}, files{parent.files.copy()}, umask{parent.umask}
-    , pid{pid}, ppid{parent.pid}, pgid{parent.pgid}, sid{parent.sid}
-    , control_tty{parent.control_tty}
-{
+    : mms{parent.mms}
+    , attr{parent.attr}
+    , files{parent.files.copy()}
+    , umask{parent.umask}
+    , pid{pid}
+    , ppid{parent.pid}
+    , pgid{parent.pgid}
+    , sid{parent.sid}
+    , control_tty{parent.control_tty} {
     if (parent.cwd)
         cwd = fs::d_get(parent.cwd);
 
@@ -39,9 +44,7 @@ process::process(const process& parent, pid_t pid)
 }
 
 process::process(pid_t pid, pid_t ppid)
-    : attr { .system = true }, files{&fs_context}
-    , pid { pid } , ppid { ppid }
-{
+    : attr{.system = true}, files{&fs_context}, pid{pid}, ppid{ppid} {
     bool inserted;
     std::tie(std::ignore, inserted) = thds.emplace("", pid);
     assert(inserted);
@@ -49,14 +52,12 @@ process::process(pid_t pid, pid_t ppid)
 
 using signo_type = kernel::signal_list::signo_type;
 
-void process::send_signal(signo_type signal)
-{
+void process::send_signal(signo_type signal) {
     for (auto& thd : thds)
         thd.send_signal(signal);
 }
 
-void kernel_threadd_main(void)
-{
+void kernel_threadd_main(void) {
     kmsg("[kernel] kthread daemon started");
 
     // TODO: create new kthread
@@ -64,26 +65,24 @@ void kernel_threadd_main(void)
         asm volatile("hlt");
 }
 
-static inline void __spawn(kernel::task::thread& thd, uintptr_t entry)
-{
+static inline void __spawn(kernel::task::thread& thd, uintptr_t entry) {
     auto prev_sp = thd.kstack.sp;
 
     // return(start) address
     thd.kstack.pushq(entry);
-    thd.kstack.pushq(0x200);       // flags
-    thd.kstack.pushq(0);           // r15
-    thd.kstack.pushq(0);           // r14
-    thd.kstack.pushq(0);           // r13
-    thd.kstack.pushq(0);           // r12
-    thd.kstack.pushq(0);           // rbp
-    thd.kstack.pushq(0);           // rbx
-    thd.kstack.pushq(0);           // 0 for alignment
-    thd.kstack.pushq(prev_sp);     // previous sp
+    thd.kstack.pushq(0x200);   // flags
+    thd.kstack.pushq(0);       // r15
+    thd.kstack.pushq(0);       // r14
+    thd.kstack.pushq(0);       // r13
+    thd.kstack.pushq(0);       // r12
+    thd.kstack.pushq(0);       // rbp
+    thd.kstack.pushq(0);       // rbx
+    thd.kstack.pushq(0);       // 0 for alignment
+    thd.kstack.pushq(prev_sp); // previous sp
 }
 
 SECTION(".text.kinit")
-proclist::proclist()
-{
+proclist::proclist() {
     // init process has no parent
     auto& init = real_emplace(1, 0);
     assert(init.pid == 1 && init.ppid == 0);
@@ -114,16 +113,14 @@ proclist::proclist()
     }
 }
 
-process& proclist::real_emplace(pid_t pid, pid_t ppid)
-{
-    auto [ iter, inserted ] = m_procs.try_emplace(pid, pid, ppid);
+process& proclist::real_emplace(pid_t pid, pid_t ppid) {
+    auto [iter, inserted] = m_procs.try_emplace(pid, pid, ppid);
     assert(inserted);
 
     return iter->second;
 }
 
-void proclist::kill(pid_t pid, int exit_code)
-{
+void proclist::kill(pid_t pid, int exit_code) {
     auto& proc = this->find(pid);
 
     // init should never exit
@@ -185,7 +182,7 @@ void proclist::kill(pid_t pid, int exit_code)
 
     if (1) {
         lock_guard lck(parent.mtx_waitprocs);
-        parent.waitprocs.push_back({ pid, exit_code });
+        parent.waitprocs.push_back({pid, exit_code});
     }
 
     parent.waitlist.notify_all();
@@ -193,23 +190,21 @@ void proclist::kill(pid_t pid, int exit_code)
     kernel::async::preempt_enable();
 }
 
-static void release_kinit()
-{
+static void release_kinit() {
     // free .kinit
     using namespace kernel::mem::paging;
     extern uintptr_t volatile KINIT_START_ADDR, KINIT_END_ADDR, KINIT_PAGES;
 
     std::size_t pages = KINIT_PAGES;
-    auto range = vaddr_range{KERNEL_PAGE_TABLE_ADDR,
-        KINIT_START_ADDR, KINIT_END_ADDR, true};
+    auto range = vaddr_range{KERNEL_PAGE_TABLE_ADDR, KINIT_START_ADDR,
+                             KINIT_END_ADDR, true};
     for (auto pte : range)
         pte.clear();
 
     create_zone(0x2000, 0x2000 + 0x1000 * pages);
 }
 
-void NORETURN _kernel_init(kernel::mem::paging::pfn_t kernel_stack_pfn)
-{
+void NORETURN _kernel_init(kernel::mem::paging::pfn_t kernel_stack_pfn) {
     kernel::mem::paging::free_pages(kernel_stack_pfn, 9);
     release_kinit();
 
@@ -220,8 +215,8 @@ void NORETURN _kernel_init(kernel::mem::paging::pfn_t kernel_stack_pfn)
     fs::vfs* rootfs;
     if (1) {
         int ret;
-        std::tie(rootfs, ret) = fs::vfs::create("none",
-                "tmpfs", MS_NOATIME, nullptr);
+        std::tie(rootfs, ret) =
+            fs::vfs::create("none", "tmpfs", MS_NOATIME, nullptr);
         assert(ret == 0);
     }
     current_process->fs_context.root = d_get(rootfs->root());
@@ -248,14 +243,15 @@ void NORETURN _kernel_init(kernel::mem::paging::pfn_t kernel_stack_pfn)
     // mount fat32 /mnt directory
     // TODO: parse kernel parameters
     if (1) {
-        auto [ mnt, status ] = fs::open(context, context.root.get(), "/mnt");
+        auto [mnt, status] = fs::open(context, context.root.get(), "/mnt");
         assert(mnt && status == -ENOENT);
 
         if (int ret = fs::mkdir(mnt.get(), 0755); 1)
             assert(ret == 0 && mnt->flags & fs::D_PRESENT);
 
-        int ret = rootfs->mount(mnt.get(), "/dev/sda", "/mnt",
-                "fat32", MS_RDONLY | MS_NOATIME | MS_NODEV | MS_NOSUID, "ro,nodev");
+        int ret = rootfs->mount(mnt.get(), "/dev/sda", "/mnt", "fat32",
+                                MS_RDONLY | MS_NOATIME | MS_NODEV | MS_NOSUID,
+                                "ro,nodev");
         assert(ret == 0);
     }
 
@@ -264,10 +260,10 @@ void NORETURN _kernel_init(kernel::mem::paging::pfn_t kernel_stack_pfn)
 
     types::elf::elf32_load_data d{
         .exec_dent{},
-        .argv{ "/mnt/busybox", "sh", "/mnt/initsh" },
-        .envp{ "LANG=C", "HOME=/root", "PATH=/mnt", "PWD=/" },
-        .ip{}, .sp{}
-    };
+        .argv{"/mnt/busybox", "sh", "/mnt/initsh"},
+        .envp{"LANG=C", "HOME=/root", "PATH=/mnt", "PWD=/"},
+        .ip{},
+        .sp{}};
 
     auto [exec, ret] = fs::open(context, context.root.get(), d.argv[0]);
     if (!exec || ret) {
@@ -296,15 +292,15 @@ void NORETURN _kernel_init(kernel::mem::paging::pfn_t kernel_stack_pfn)
         "push %3\n"
 
         "iretq\n"
-        : : "g"(ds), "g"(cs), "g"(d.sp),
-            "g"(d.ip) : "eax", "memory");
+        :
+        : "g"(ds), "g"(cs), "g"(d.sp), "g"(d.ip)
+        : "eax", "memory");
 
     freeze();
 }
 
 SECTION(".text.kinit")
-void NORETURN init_scheduler(kernel::mem::paging::pfn_t kernel_stack_pfn)
-{
+void NORETURN init_scheduler(kernel::mem::paging::pfn_t kernel_stack_pfn) {
     procs = new proclist;
 
     asm volatile(
@@ -315,8 +311,8 @@ void NORETURN init_scheduler(kernel::mem::paging::pfn_t kernel_stack_pfn)
         "mov %%rbx, (%%rsp)\n"   // return address
         "mov %%rbx, 16(%%rsp)\n" // previous frame return address
         "xor %%rbx, %%rbx\n"
-        "mov %%rbx, 8(%%rsp)\n"  // previous frame rbp
-        "mov %%rsp, %%rbp\n"     // current frame rbp
+        "mov %%rbx, 8(%%rsp)\n" // previous frame rbp
+        "mov %%rsp, %%rbp\n"    // current frame rbp
 
         "push %1\n"
 
@@ -335,7 +331,8 @@ void NORETURN init_scheduler(kernel::mem::paging::pfn_t kernel_stack_pfn)
         "%=:\n"
         "ud2"
         :
-        : "a"(current_thread->kstack.sp), "c"(_kernel_init), "g"(kernel_stack_pfn)
+        : "a"(current_thread->kstack.sp), "c"(_kernel_init),
+          "g"(kernel_stack_pfn)
         : "memory");
 
     freeze();
@@ -343,14 +340,12 @@ void NORETURN init_scheduler(kernel::mem::paging::pfn_t kernel_stack_pfn)
 
 extern "C" void asm_ctx_switch(uintptr_t* curr_sp, uintptr_t* next_sp);
 
-extern "C" void after_ctx_switch()
-{
+extern "C" void after_ctx_switch() {
     current_thread->kstack.load_interrupt_stack();
     current_thread->load_thread_area32();
 }
 
-bool _schedule()
-{
+bool _schedule() {
     auto* next_thd = kernel::task::dispatcher::next();
 
     if (current_thread != next_thd) {
@@ -369,29 +364,24 @@ bool _schedule()
     return current_thread->signals.pending_signal() == 0;
 }
 
-bool schedule()
-{
+bool schedule() {
     if (kernel::async::preempt_count() != 0)
         return true;
 
     return _schedule();
 }
 
-void NORETURN schedule_noreturn(void)
-{
+void NORETURN schedule_noreturn(void) {
     _schedule();
     freeze();
 }
 
-void NORETURN freeze(void)
-{
+void NORETURN freeze(void) {
     for (;;)
         asm volatile("cli\n\thlt");
 }
 
-void NORETURN kill_current(int signo)
-{
-    procs->kill(current_process->pid,
-        (signo + 128) << 8 | (signo & 0xff));
+void NORETURN kill_current(int signo) {
+    procs->kill(current_process->pid, (signo + 128) << 8 | (signo & 0xff));
     schedule_noreturn();
 }

+ 38 - 43
src/kernel/signal.cpp

@@ -1,46 +1,44 @@
+#include <signal.h>
+
 #include <kernel/async/lock.hpp>
 #include <kernel/interrupt.hpp>
 #include <kernel/process.hpp>
 #include <kernel/signal.hpp>
 #include <kernel/task/thread.hpp>
 
-#include <signal.h>
-
 #define sigmask(sig) (1ULL << ((sig)-1))
 
 #define sigmask_now (sigmask(SIGKILL) | sigmask(SIGSTOP))
 
 #define sigmask_ignore (sigmask(SIGCHLD) | sigmask(SIGURG) | sigmask(SIGWINCH))
 
-#define sigmask_coredump (\
-    sigmask(SIGQUIT) | sigmask(SIGILL) | sigmask(SIGTRAP) | sigmask(SIGABRT) | \
-    sigmask(SIGFPE) | sigmask(SIGSEGV) | sigmask(SIGBUS) | sigmask(SIGSYS) | \
-    sigmask(SIGXCPU) | sigmask(SIGXFSZ) )
+#define sigmask_coredump                                                       \
+    (sigmask(SIGQUIT) | sigmask(SIGILL) | sigmask(SIGTRAP) |                   \
+     sigmask(SIGABRT) | sigmask(SIGFPE) | sigmask(SIGSEGV) | sigmask(SIGBUS) | \
+     sigmask(SIGSYS) | sigmask(SIGXCPU) | sigmask(SIGXFSZ))
 
-#define sigmask_stop (\
-    sigmask(SIGSTOP) | sigmask(SIGTSTP) | sigmask(SIGTTIN) | sigmask(SIGTTOU))
+#define sigmask_stop \
+    (sigmask(SIGSTOP) | sigmask(SIGTSTP) | sigmask(SIGTTIN) | sigmask(SIGTTOU))
 
 using kernel::signal_list;
 using signo_type = signal_list::signo_type;
 
-static void continue_process(int signal)
-{
+static void continue_process(int signal) {
     auto& parent = procs->find(current_process->ppid);
 
     // signal parent we're running
-    parent.waitprocs.push_back({ current_process->pid, 0xffff });
+    parent.waitprocs.push_back({current_process->pid, 0xffff});
 
     current_thread->signals.after_signal(signal);
 }
 
-static void stop_process(int signal)
-{
+static void stop_process(int signal) {
     auto& parent = procs->find(current_process->ppid);
 
     current_thread->set_attr(kernel::task::thread::STOPPED);
 
     // signal parent we're stopped
-    parent.waitprocs.push_back({ current_process->pid, 0x7f });
+    parent.waitprocs.push_back({current_process->pid, 0x7f});
     parent.waitlist.notify_all();
 
     while (true) {
@@ -51,54 +49,46 @@ static void stop_process(int signal)
     current_thread->signals.after_signal(signal);
 }
 
-static void terminate_process(int signo)
-{
+static void terminate_process(int signo) {
     kill_current(signo);
 }
 
-static void terminate_process_with_core_dump(int signo)
-{
+static void terminate_process_with_core_dump(int signo) {
     terminate_process(signo & 0x80);
 }
 
-void signal_list::set_handler(signo_type signal, const sigaction& action)
-{
+void signal_list::set_handler(signo_type signal, const sigaction& action) {
     if (action.sa_handler == SIG_DFL)
         m_handlers.erase(signal);
     else
         m_handlers[signal] = action;
 }
 
-void signal_list::get_handler(signo_type signal, sigaction& action) const
-{
+void signal_list::get_handler(signo_type signal, sigaction& action) const {
     auto iter = m_handlers.find(signal);
     if (iter == m_handlers.end()) {
         action.sa_handler = SIG_DFL;
         action.sa_flags = 0;
         action.sa_restorer = nullptr;
         action.sa_mask = 0;
-    }
-    else {
+    } else {
         action = iter->second;
     }
 }
 
-void signal_list::on_exec()
-{
-    std::erase_if(m_handlers, [](auto& pair) {
-        return pair.second.sa_handler != SIG_IGN;
-    });
+void signal_list::on_exec() {
+    std::erase_if(m_handlers,
+                  [](auto& pair) { return pair.second.sa_handler != SIG_IGN; });
 }
 
-bool signal_list::raise(signo_type signal)
-{
+bool signal_list::raise(signo_type signal) {
     async::lock_guard lck{m_mtx};
 
     // TODO: clear pending signals
     if (signal == SIGCONT) {
         m_list.remove_if([](signo_type sig) {
-            return sig == SIGSTOP || sig == SIGTSTP
-                || sig == SIGTTIN || sig == SIGTTOU;
+            return sig == SIGSTOP || sig == SIGTSTP || sig == SIGTTIN ||
+                   sig == SIGTTOU;
         });
         return true;
     }
@@ -123,8 +113,7 @@ bool signal_list::raise(signo_type signal)
     return true;
 }
 
-signo_type signal_list::pending_signal()
-{
+signo_type signal_list::pending_signal() {
     async::lock_guard lck{m_mtx};
     for (auto iter = m_list.begin(); iter != m_list.end(); ++iter) {
         auto iter_handler = m_handlers.find(*iter);
@@ -148,8 +137,7 @@ signo_type signal_list::pending_signal()
     return 0;
 }
 
-void signal_list::handle(interrupt_stack* context, mmx_registers* mmxregs)
-{
+void signal_list::handle(interrupt_stack* context, mmx_registers* mmxregs) {
     unsigned int signal;
     if (1) {
         async::lock_guard lck{m_mtx};
@@ -208,12 +196,19 @@ void signal_list::handle(interrupt_stack* context, mmx_registers* mmxregs)
     context->v_rip = (uintptr_t)handler.sa_handler;
 }
 
-void signal_list::after_signal(signo_type signal)
-{
+void signal_list::after_signal(signo_type signal) {
     m_mask &= ~sigmask(signal);
 }
 
-kernel::sigmask_type signal_list::get_mask() const { return m_mask; }
-void signal_list::set_mask(sigmask_type mask) { m_mask = mask & ~sigmask_now; }
-void signal_list::mask(sigmask_type mask) { set_mask(m_mask | mask); }
-void signal_list::unmask(sigmask_type mask) { set_mask(m_mask & ~mask); }
+kernel::sigmask_type signal_list::get_mask() const {
+    return m_mask;
+}
+void signal_list::set_mask(sigmask_type mask) {
+    m_mask = mask & ~sigmask_now;
+}
+void signal_list::mask(sigmask_type mask) {
+    set_mask(m_mask | mask);
+}
+void signal_list::unmask(sigmask_type mask) {
+    set_mask(m_mask & ~mask);
+}

+ 86 - 87
src/kernel/syscall.cpp

@@ -50,55 +50,62 @@
 #define SYSCALL32_ARG6(type, name) type name = (type)((data)->regs.rbp)
 
 #define _DEFINE_SYSCALL32_ARGS1(type, name, ...) \
-SYSCALL32_ARG1(type, name); \
-__VA_OPT__(_DEFINE_SYSCALL32_ARGS2(__VA_ARGS__))
+    SYSCALL32_ARG1(type, name);                  \
+    __VA_OPT__(_DEFINE_SYSCALL32_ARGS2(__VA_ARGS__))
 
 #define _DEFINE_SYSCALL32_ARGS2(type, name, ...) \
-SYSCALL32_ARG2(type, name); \
-__VA_OPT__(_DEFINE_SYSCALL32_ARGS3(__VA_ARGS__))
+    SYSCALL32_ARG2(type, name);                  \
+    __VA_OPT__(_DEFINE_SYSCALL32_ARGS3(__VA_ARGS__))
 
 #define _DEFINE_SYSCALL32_ARGS3(type, name, ...) \
-SYSCALL32_ARG3(type, name); \
-__VA_OPT__(_DEFINE_SYSCALL32_ARGS4(__VA_ARGS__))
+    SYSCALL32_ARG3(type, name);                  \
+    __VA_OPT__(_DEFINE_SYSCALL32_ARGS4(__VA_ARGS__))
 
 #define _DEFINE_SYSCALL32_ARGS4(type, name, ...) \
-SYSCALL32_ARG4(type, name); \
-__VA_OPT__(_DEFINE_SYSCALL32_ARGS5(__VA_ARGS__))
+    SYSCALL32_ARG4(type, name);                  \
+    __VA_OPT__(_DEFINE_SYSCALL32_ARGS5(__VA_ARGS__))
 
 #define _DEFINE_SYSCALL32_ARGS5(type, name, ...) \
-SYSCALL32_ARG5(type, name); \
-__VA_OPT__(_DEFINE_SYSCALL32_ARGS6(__VA_ARGS__))
-
-#define _DEFINE_SYSCALL32_ARGS6(type, name, ...) \
-SYSCALL32_ARG6(type, name);
-
-#define _DEFINE_SYSCALL32_END_PARAMS1(type, name, ...) name __VA_OPT__(, _DEFINE_SYSCALL32_END_PARAMS2(__VA_ARGS__))
-#define _DEFINE_SYSCALL32_END_PARAMS2(type, name, ...) name __VA_OPT__(, _DEFINE_SYSCALL32_END_PARAMS3(__VA_ARGS__))
-#define _DEFINE_SYSCALL32_END_PARAMS3(type, name, ...) name __VA_OPT__(, _DEFINE_SYSCALL32_END_PARAMS4(__VA_ARGS__))
-#define _DEFINE_SYSCALL32_END_PARAMS4(type, name, ...) name __VA_OPT__(, _DEFINE_SYSCALL32_END_PARAMS5(__VA_ARGS__))
-#define _DEFINE_SYSCALL32_END_PARAMS5(type, name, ...) name __VA_OPT__(, _DEFINE_SYSCALL32_END_PARAMS6(__VA_ARGS__))
+    SYSCALL32_ARG5(type, name);                  \
+    __VA_OPT__(_DEFINE_SYSCALL32_ARGS6(__VA_ARGS__))
+
+#define _DEFINE_SYSCALL32_ARGS6(type, name, ...) SYSCALL32_ARG6(type, name);
+
+#define _DEFINE_SYSCALL32_END_PARAMS1(type, name, ...) \
+    name __VA_OPT__(, _DEFINE_SYSCALL32_END_PARAMS2(__VA_ARGS__))
+#define _DEFINE_SYSCALL32_END_PARAMS2(type, name, ...) \
+    name __VA_OPT__(, _DEFINE_SYSCALL32_END_PARAMS3(__VA_ARGS__))
+#define _DEFINE_SYSCALL32_END_PARAMS3(type, name, ...) \
+    name __VA_OPT__(, _DEFINE_SYSCALL32_END_PARAMS4(__VA_ARGS__))
+#define _DEFINE_SYSCALL32_END_PARAMS4(type, name, ...) \
+    name __VA_OPT__(, _DEFINE_SYSCALL32_END_PARAMS5(__VA_ARGS__))
+#define _DEFINE_SYSCALL32_END_PARAMS5(type, name, ...) \
+    name __VA_OPT__(, _DEFINE_SYSCALL32_END_PARAMS6(__VA_ARGS__))
 #define _DEFINE_SYSCALL32_END_PARAMS6(type, name, ...) name __VA_OPT__(, void)
 
 #define _DEFINE_SYSCALL32_END(name, ...) \
-    kernel::syscall::do_ ## name ( __VA_OPT__(_DEFINE_SYSCALL32_END_PARAMS1(__VA_ARGS__)) )
-
-#define DEFINE_SYSCALL32_TO(name, to, ...) \
-static uint32_t _syscall32_##name(interrupt_stack* data, mmx_registers* mmxregs) \
-{ \
-    (void)data, (void)mmxregs; \
-    __VA_OPT__(_DEFINE_SYSCALL32_ARGS1(__VA_ARGS__);) \
-    return (uint32_t)(uintptr_t)_DEFINE_SYSCALL32_END(to __VA_OPT__(, __VA_ARGS__)); \
-}
+    kernel::syscall::do_##name(          \
+        __VA_OPT__(_DEFINE_SYSCALL32_END_PARAMS1(__VA_ARGS__)))
+
+#define DEFINE_SYSCALL32_TO(name, to, ...)                      \
+    static uint32_t _syscall32_##name(interrupt_stack* data,    \
+                                      mmx_registers* mmxregs) { \
+        (void)data, (void)mmxregs;                              \
+        __VA_OPT__(_DEFINE_SYSCALL32_ARGS1(__VA_ARGS__);)       \
+        return (uint32_t)(uintptr_t)_DEFINE_SYSCALL32_END(      \
+            to __VA_OPT__(, __VA_ARGS__));                      \
+    }
 
-#define DEFINE_SYSCALL32(name, ...) DEFINE_SYSCALL32_TO(name, name __VA_OPT__(,) __VA_ARGS__)
+#define DEFINE_SYSCALL32(name, ...) \
+    DEFINE_SYSCALL32_TO(name, name __VA_OPT__(, ) __VA_ARGS__)
 
-#define DEFINE_SYSCALL32_NORETURN(name, ...) \
-[[noreturn]] static uint32_t _syscall32_##name(interrupt_stack* data, mmx_registers* mmxregs) \
-{ \
-    (void)data, (void)mmxregs; \
-    __VA_OPT__(_DEFINE_SYSCALL32_ARGS1(__VA_ARGS__);) \
-    _DEFINE_SYSCALL32_END(name, __VA_ARGS__); \
-}
+#define DEFINE_SYSCALL32_NORETURN(name, ...)                                 \
+    [[noreturn]] static uint32_t _syscall32_##name(interrupt_stack* data,    \
+                                                   mmx_registers* mmxregs) { \
+        (void)data, (void)mmxregs;                                           \
+        __VA_OPT__(_DEFINE_SYSCALL32_ARGS1(__VA_ARGS__);)                    \
+        _DEFINE_SYSCALL32_END(name, __VA_ARGS__);                            \
+    }
 
 struct syscall_handler_t {
     uint32_t (*handler)(interrupt_stack*, mmx_registers*);
@@ -107,10 +114,11 @@ struct syscall_handler_t {
 
 static syscall_handler_t syscall_handlers[SYSCALL_HANDLERS_SIZE];
 
-static inline void not_implemented(const char* pos, int line)
-{
-    kmsgf("[kernel] the function at %s:%d is not implemented, killing the pid%d...",
-            pos, line, current_process->pid);
+static inline void not_implemented(const char* pos, int line) {
+    kmsgf(
+        "[kernel] the function at %s:%d is not implemented, killing the "
+        "pid%d...",
+        pos, line, current_process->pid);
     current_thread->send_signal(SIGSYS);
 }
 
@@ -124,8 +132,10 @@ DEFINE_SYSCALL32(getdents, int, fd, char __user*, buf, size_t, cnt)
 DEFINE_SYSCALL32(getdents64, int, fd, char __user*, buf, size_t, cnt)
 DEFINE_SYSCALL32(open, const char __user*, path, int, flags, mode_t, mode)
 DEFINE_SYSCALL32(chdir, const char __user*, path)
-DEFINE_SYSCALL32(symlink, const char __user*, target, const char __user*, linkpath)
-DEFINE_SYSCALL32(readlink, const char __user*, pathname, char __user*, buf, size_t, buf_size)
+DEFINE_SYSCALL32(symlink, const char __user*, target, const char __user*,
+                 linkpath)
+DEFINE_SYSCALL32(readlink, const char __user*, pathname, char __user*, buf,
+                 size_t, buf_size)
 DEFINE_SYSCALL32(ioctl, int, fd, unsigned long, request, uintptr_t, arg3)
 DEFINE_SYSCALL32(munmap, uintptr_t, addr, size_t, len)
 DEFINE_SYSCALL32(poll, pollfd __user*, fds, nfds_t, nfds, int, timeout)
@@ -136,22 +146,18 @@ DEFINE_SYSCALL32(truncate, const char __user*, pathname, long, length)
 DEFINE_SYSCALL32(mkdir, const char __user*, pathname, mode_t, mode)
 DEFINE_SYSCALL32_TO(fcntl64, fcntl, int, fd, int, cmd, unsigned long, arg)
 
-DEFINE_SYSCALL32_TO(sendfile64, sendfile,
-        int, out_fd, int, in_fd, off_t __user*, offset, size_t, count)
+DEFINE_SYSCALL32_TO(sendfile64, sendfile, int, out_fd, int, in_fd,
+                    off_t __user*, offset, size_t, count)
 
-DEFINE_SYSCALL32(statx, int, dirfd, const char __user*, path,
-        int, flags, unsigned int, mask, statx __user*, statxbuf)
+DEFINE_SYSCALL32(statx, int, dirfd, const char __user*, path, int, flags,
+                 unsigned int, mask, statx __user*, statxbuf)
 
-DEFINE_SYSCALL32(mmap_pgoff,
-        uintptr_t, addr,
-        size_t, len,
-        int, prot,
-        int, flags,
-        int, fd,
-        off_t, pgoffset)
+DEFINE_SYSCALL32(mmap_pgoff, uintptr_t, addr, size_t, len, int, prot, int,
+                 flags, int, fd, off_t, pgoffset)
 
-DEFINE_SYSCALL32(mount, const char __user*, source, const char __user*,
-        target, const char __user*, fstype, unsigned long, flags, const void __user*, _fsdata)
+DEFINE_SYSCALL32(mount, const char __user*, source, const char __user*, target,
+                 const char __user*, fstype, unsigned long, flags,
+                 const void __user*, _fsdata)
 
 DEFINE_SYSCALL32(waitpid, pid_t, waitpid, int __user*, arg1, int, options)
 DEFINE_SYSCALL32(getsid, pid_t, pid)
@@ -175,25 +181,23 @@ DEFINE_SYSCALL32(brk, uintptr_t, addr)
 DEFINE_SYSCALL32(umask, mode_t, mask)
 DEFINE_SYSCALL32(kill, pid_t, pid, int, sig)
 DEFINE_SYSCALL32(tkill, pid_t, tid, int, sig)
-DEFINE_SYSCALL32(rt_sigprocmask, int, how,
-        const kernel::sigmask_type __user*, set,
-        kernel::sigmask_type __user*, oldset, size_t, sigsetsize)
-DEFINE_SYSCALL32(rt_sigaction, int, signum,
-        const kernel::sigaction __user*, act,
-        kernel::sigaction __user*, oldact, size_t, sigsetsize)
+DEFINE_SYSCALL32(rt_sigprocmask, int, how, const kernel::sigmask_type __user*,
+                 set, kernel::sigmask_type __user*, oldset, size_t, sigsetsize)
+DEFINE_SYSCALL32(rt_sigaction, int, signum, const kernel::sigaction __user*,
+                 act, kernel::sigaction __user*, oldact, size_t, sigsetsize)
 DEFINE_SYSCALL32(newuname, new_utsname __user*, buf)
 
 DEFINE_SYSCALL32_NORETURN(exit, int, status)
 
 DEFINE_SYSCALL32(gettimeofday, timeval __user*, tv, void __user*, tz)
-DEFINE_SYSCALL32_TO(clock_gettime64, clock_gettime,
-        clockid_t, clk_id, timespec __user*, tp)
+DEFINE_SYSCALL32_TO(clock_gettime64, clock_gettime, clockid_t, clk_id,
+                    timespec __user*, tp)
 
 extern "C" void NORETURN ISR_stub_restore();
-static uint32_t _syscall32_fork(interrupt_stack* data, mmx_registers* mmxregs)
-{
+static uint32_t _syscall32_fork(interrupt_stack* data, mmx_registers* mmxregs) {
     auto& newproc = procs->copy_from(*current_process);
-    auto [ iter_newthd, inserted ] = newproc.thds.emplace(*current_thread, newproc.pid);
+    auto [iter_newthd, inserted] =
+        newproc.thds.emplace(*current_thread, newproc.pid);
     assert(inserted);
     auto* newthd = &*iter_newthd;
 
@@ -229,8 +233,7 @@ static uint32_t _syscall32_fork(interrupt_stack* data, mmx_registers* mmxregs)
     return newproc.pid;
 }
 
-static uint32_t _syscall32_llseek(interrupt_stack* data, mmx_registers*)
-{
+static uint32_t _syscall32_llseek(interrupt_stack* data, mmx_registers*) {
     SYSCALL32_ARG1(unsigned int, fd);
     SYSCALL32_ARG2(unsigned long, offset_high);
     SYSCALL32_ARG3(unsigned long, offset_low);
@@ -252,8 +255,7 @@ static uint32_t _syscall32_llseek(interrupt_stack* data, mmx_registers*)
     return 0;
 }
 
-static uint32_t _syscall32_readv(interrupt_stack* data, mmx_registers*)
-{
+static uint32_t _syscall32_readv(interrupt_stack* data, mmx_registers*) {
     SYSCALL32_ARG1(int, fd);
     SYSCALL32_ARG2(const types::iovec32 __user*, _iov);
     SYSCALL32_ARG3(int, iovcnt);
@@ -273,8 +275,7 @@ static uint32_t _syscall32_readv(interrupt_stack* data, mmx_registers*)
     return kernel::syscall::do_readv(fd, iov.data(), iovcnt);
 }
 
-static uint32_t _syscall32_writev(interrupt_stack* data, mmx_registers*)
-{
+static uint32_t _syscall32_writev(interrupt_stack* data, mmx_registers*) {
     SYSCALL32_ARG1(int, fd);
     SYSCALL32_ARG2(const types::iovec32 __user*, _iov);
     SYSCALL32_ARG3(int, iovcnt);
@@ -294,15 +295,13 @@ static uint32_t _syscall32_writev(interrupt_stack* data, mmx_registers*)
     return kernel::syscall::do_writev(fd, iov.data(), iovcnt);
 }
 
-[[noreturn]] static uint32_t _syscall32_exit_group(
-        interrupt_stack* data, mmx_registers* mmxregs)
-{
+[[noreturn]] static uint32_t _syscall32_exit_group(interrupt_stack* data,
+                                                   mmx_registers* mmxregs) {
     // we implement exit_group as exit for now
     _syscall32_exit(data, mmxregs);
 }
 
-static uint32_t _syscall32_execve(interrupt_stack* data, mmx_registers*)
-{
+static uint32_t _syscall32_execve(interrupt_stack* data, mmx_registers*) {
     SYSCALL32_ARG1(const char __user*, exec);
     SYSCALL32_ARG2(const uint32_t __user*, argv);
     SYSCALL32_ARG3(const uint32_t __user*, envp);
@@ -334,8 +333,8 @@ static uint32_t _syscall32_execve(interrupt_stack* data, mmx_registers*)
     return retval.status;
 }
 
-static uint32_t _syscall32_wait4(interrupt_stack* data, mmx_registers* mmxregs)
-{
+static uint32_t _syscall32_wait4(interrupt_stack* data,
+                                 mmx_registers* mmxregs) {
     SYSCALL32_ARG4(void __user*, rusage);
 
     // TODO: getrusage
@@ -345,8 +344,8 @@ static uint32_t _syscall32_wait4(interrupt_stack* data, mmx_registers* mmxregs)
     return _syscall32_waitpid(data, mmxregs);
 }
 
-void kernel::handle_syscall32(int no, interrupt_stack* data, mmx_registers* mmxregs)
-{
+void kernel::handle_syscall32(int no, interrupt_stack* data,
+                              mmx_registers* mmxregs) {
     if (no >= SYSCALL_HANDLERS_SIZE || !syscall_handlers[no].handler) {
         kmsgf("[kernel] syscall %d(%x) isn't implemented", no, no);
         NOT_IMPLEMENTED;
@@ -356,7 +355,8 @@ void kernel::handle_syscall32(int no, interrupt_stack* data, mmx_registers* mmxr
         return;
     }
 
-    // kmsgf_debug("[kernel:debug] (pid\t%d) %s()", current_process->pid, syscall_handlers[no].name);
+    // kmsgf_debug("[kernel:debug] (pid\t%d) %s()", current_process->pid,
+    // syscall_handlers[no].name);
 
     asm volatile("sti");
     data->regs.rax = syscall_handlers[no].handler(data, mmxregs);
@@ -373,13 +373,12 @@ void kernel::handle_syscall32(int no, interrupt_stack* data, mmx_registers* mmxr
         current_thread->signals.handle(data, mmxregs);
 }
 
-#define REGISTER_SYSCALL_HANDLER(no, _name) \
-    syscall_handlers[(no)].handler = _syscall32_ ## _name; \
-    syscall_handlers[(no)].name = #_name; \
+#define REGISTER_SYSCALL_HANDLER(no, _name)              \
+    syscall_handlers[(no)].handler = _syscall32_##_name; \
+    syscall_handlers[(no)].name = #_name;
 
 SECTION(".text.kinit")
-void kernel::init_syscall_table()
-{
+void kernel::init_syscall_table() {
     // 32bit syscalls
     REGISTER_SYSCALL_HANDLER(0x01, exit);
     REGISTER_SYSCALL_HANDLER(0x02, fork);

+ 114 - 137
src/kernel/syscall/fileops.cc

@@ -14,15 +14,15 @@
 
 #define NOT_IMPLEMENTED not_implemented(__FILE__, __LINE__)
 
-static inline void not_implemented(const char* pos, int line)
-{
-    kmsgf("[kernel] the function at %s:%d is not implemented, killing the pid%d...",
-            pos, line, current_process->pid);
+static inline void not_implemented(const char* pos, int line) {
+    kmsgf(
+        "[kernel] the function at %s:%d is not implemented, killing the "
+        "pid%d...",
+        pos, line, current_process->pid);
     current_thread->send_signal(SIGSYS);
 }
 
-ssize_t kernel::syscall::do_write(int fd, const char __user* buf, size_t n)
-{
+ssize_t kernel::syscall::do_write(int fd, const char __user* buf, size_t n) {
     auto* file = current_process->files[fd];
     if (!file)
         return -EBADF;
@@ -30,8 +30,7 @@ ssize_t kernel::syscall::do_write(int fd, const char __user* buf, size_t n)
     return file->write(buf, n);
 }
 
-ssize_t kernel::syscall::do_read(int fd, char __user* buf, size_t n)
-{
+ssize_t kernel::syscall::do_read(int fd, char __user* buf, size_t n) {
     auto* file = current_process->files[fd];
     if (!file)
         return -EBADF;
@@ -39,30 +38,25 @@ ssize_t kernel::syscall::do_read(int fd, char __user* buf, size_t n)
     return file->read(buf, n);
 }
 
-int kernel::syscall::do_close(int fd)
-{
+int kernel::syscall::do_close(int fd) {
     current_process->files.close(fd);
     return 0;
 }
 
-int kernel::syscall::do_dup(int old_fd)
-{
+int kernel::syscall::do_dup(int old_fd) {
     return current_process->files.dup(old_fd);
 }
 
-int kernel::syscall::do_dup2(int old_fd, int new_fd)
-{
+int kernel::syscall::do_dup2(int old_fd, int new_fd) {
     return current_process->files.dup(old_fd, new_fd, 0);
 }
 
-int kernel::syscall::do_pipe(int __user* pipefd)
-{
+int kernel::syscall::do_pipe(int __user* pipefd) {
     // TODO: use copy_from_user and copy_to_user
     return current_process->files.pipe(*(int(*)[2])pipefd);
 }
 
-ssize_t kernel::syscall::do_getdents(int fd, char __user* buf, size_t cnt)
-{
+ssize_t kernel::syscall::do_getdents(int fd, char __user* buf, size_t cnt) {
     auto* dir = current_process->files[fd];
     if (!dir)
         return -EBADF;
@@ -70,8 +64,7 @@ ssize_t kernel::syscall::do_getdents(int fd, char __user* buf, size_t cnt)
     return dir->getdents(buf, cnt);
 }
 
-ssize_t kernel::syscall::do_getdents64(int fd, char __user* buf, size_t cnt)
-{
+ssize_t kernel::syscall::do_getdents64(int fd, char __user* buf, size_t cnt) {
     auto* dir = current_process->files[fd];
     if (!dir)
         return -EBADF;
@@ -79,28 +72,28 @@ ssize_t kernel::syscall::do_getdents64(int fd, char __user* buf, size_t cnt)
     return dir->getdents64(buf, cnt);
 }
 
-int kernel::syscall::do_open(const char __user* path, int flags, mode_t mode)
-{
+int kernel::syscall::do_open(const char __user* path, int flags, mode_t mode) {
     mode &= ~current_process->umask;
 
     // TODO: use copy_from_user
-    return current_process->files.open(current_process->cwd.get(), path, flags, mode);
+    return current_process->files.open(current_process->cwd.get(), path, flags,
+                                       mode);
 }
 
-int kernel::syscall::do_symlink(const char __user* target, const char __user* linkpath)
-{
+int kernel::syscall::do_symlink(const char __user* target,
+                                const char __user* linkpath) {
     // TODO: use copy_from_user
-    auto [ dent, status ] = current_open(linkpath);
+    auto [dent, status] = current_open(linkpath);
     if (!dent || status != -ENOENT)
         return status;
 
     return fs::symlink(dent.get(), target);
 }
 
-int kernel::syscall::do_readlink(const char __user* pathname, char __user* buf, size_t buf_size)
-{
+int kernel::syscall::do_readlink(const char __user* pathname, char __user* buf,
+                                 size_t buf_size) {
     // TODO: use copy_from_user
-    auto [ dent, status ] = current_open(pathname, false);
+    auto [dent, status] = current_open(pathname, false);
 
     if (!dent || status)
         return status;
@@ -112,8 +105,7 @@ int kernel::syscall::do_readlink(const char __user* pathname, char __user* buf,
     return fs::readlink(dent->inode, buf, buf_size);
 }
 
-int kernel::syscall::do_ioctl(int fd, unsigned long request, uintptr_t arg3)
-{
+int kernel::syscall::do_ioctl(int fd, unsigned long request, uintptr_t arg3) {
     // TODO: check fd type and get tty* from fd
     //
     //       we use a trick for now, check whether
@@ -125,69 +117,69 @@ int kernel::syscall::do_ioctl(int fd, unsigned long request, uintptr_t arg3)
         return -ENOTTY;
 
     switch (request) {
-    case TIOCGPGRP: {
-        auto* pgid = (pid_t __user*)arg3;
-        auto* ctrl_tty = current_process->control_tty;
+        case TIOCGPGRP: {
+            auto* pgid = (pid_t __user*)arg3;
+            auto* ctrl_tty = current_process->control_tty;
 
-        if (!ctrl_tty)
-            return -ENOTTY;
+            if (!ctrl_tty)
+                return -ENOTTY;
 
-        // TODO: copy_to_user
-        *pgid = ctrl_tty->get_pgrp();
-        break;
-    }
-    case TIOCSPGRP: {
-        // TODO: copy_from_user
-        auto pgid = *(const pid_t __user*)arg3;
-        auto* ctrl_tty = current_process->control_tty;
+            // TODO: copy_to_user
+            *pgid = ctrl_tty->get_pgrp();
+            break;
+        }
+        case TIOCSPGRP: {
+            // TODO: copy_from_user
+            auto pgid = *(const pid_t __user*)arg3;
+            auto* ctrl_tty = current_process->control_tty;
 
-        if (!ctrl_tty)
-            return -ENOTTY;
+            if (!ctrl_tty)
+                return -ENOTTY;
 
-        ctrl_tty->set_pgrp(pgid);
-        break;
-    }
-    case TIOCGWINSZ: {
-        auto* ws = (winsize __user*)arg3;
-        // TODO: copy_to_user
-        ws->ws_col = 80;
-        ws->ws_row = 10;
-        break;
-    }
-    case TCGETS: {
-        auto* argp = (struct termios __user*)arg3;
+            ctrl_tty->set_pgrp(pgid);
+            break;
+        }
+        case TIOCGWINSZ: {
+            auto* ws = (winsize __user*)arg3;
+            // TODO: copy_to_user
+            ws->ws_col = 80;
+            ws->ws_row = 10;
+            break;
+        }
+        case TCGETS: {
+            auto* argp = (struct termios __user*)arg3;
 
-        auto* ctrl_tty = current_process->control_tty;
-        if (!ctrl_tty)
-            return -EINVAL;
+            auto* ctrl_tty = current_process->control_tty;
+            if (!ctrl_tty)
+                return -EINVAL;
 
-        // TODO: use copy_to_user
-        memcpy(argp, &ctrl_tty->termio, sizeof(ctrl_tty->termio));
+            // TODO: use copy_to_user
+            memcpy(argp, &ctrl_tty->termio, sizeof(ctrl_tty->termio));
 
-        break;
-    }
-    case TCSETS: {
-        auto* argp = (const struct termios __user*)arg3;
+            break;
+        }
+        case TCSETS: {
+            auto* argp = (const struct termios __user*)arg3;
 
-        auto* ctrl_tty = current_process->control_tty;
-        if (!ctrl_tty)
-            return -EINVAL;
+            auto* ctrl_tty = current_process->control_tty;
+            if (!ctrl_tty)
+                return -EINVAL;
 
-        // TODO: use copy_from_user
-        memcpy(&ctrl_tty->termio, argp, sizeof(ctrl_tty->termio));
+            // TODO: use copy_from_user
+            memcpy(&ctrl_tty->termio, argp, sizeof(ctrl_tty->termio));
 
-        break;
-    }
-    default:
-        kmsgf("[error] the ioctl() function %x is not implemented", request);
-        return -EINVAL;
+            break;
+        }
+        default:
+            kmsgf("[error] the ioctl() function %x is not implemented",
+                  request);
+            return -EINVAL;
     }
 
     return 0;
 }
 
-ssize_t kernel::syscall::do_readv(int fd, const iovec* iov, int iovcnt)
-{
+ssize_t kernel::syscall::do_readv(int fd, const iovec* iov, int iovcnt) {
     auto* file = current_process->files[fd];
 
     if (!file)
@@ -196,8 +188,7 @@ ssize_t kernel::syscall::do_readv(int fd, const iovec* iov, int iovcnt)
     // TODO: fix fake EOF
     ssize_t totn = 0;
     for (int i = 0; i < iovcnt; ++i) {
-        ssize_t ret = file->read(
-            (char*)iov[i].iov_base, iov[i].iov_len);
+        ssize_t ret = file->read((char*)iov[i].iov_base, iov[i].iov_len);
 
         if (ret < 0)
             return ret;
@@ -215,8 +206,7 @@ ssize_t kernel::syscall::do_readv(int fd, const iovec* iov, int iovcnt)
 }
 
 // TODO: this operation SHOULD be atomic
-ssize_t kernel::syscall::do_writev(int fd, const iovec* iov, int iovcnt)
-{
+ssize_t kernel::syscall::do_writev(int fd, const iovec* iov, int iovcnt) {
     auto* file = current_process->files[fd];
 
     if (!file)
@@ -224,8 +214,7 @@ ssize_t kernel::syscall::do_writev(int fd, const iovec* iov, int iovcnt)
 
     ssize_t totn = 0;
     for (int i = 0; i < iovcnt; ++i) {
-        ssize_t ret = file->write(
-            (const char*)iov[i].iov_base, iov[i].iov_len);
+        ssize_t ret = file->write((const char*)iov[i].iov_base, iov[i].iov_len);
 
         if (ret < 0)
             return ret;
@@ -235,8 +224,7 @@ ssize_t kernel::syscall::do_writev(int fd, const iovec* iov, int iovcnt)
     return totn;
 }
 
-off_t kernel::syscall::do_lseek(int fd, off_t offset, int whence)
-{
+off_t kernel::syscall::do_lseek(int fd, off_t offset, int whence) {
     auto* file = current_process->files[fd];
     if (!file)
         return -EBADF;
@@ -244,9 +232,8 @@ off_t kernel::syscall::do_lseek(int fd, off_t offset, int whence)
     return file->seek(offset, whence);
 }
 
-uintptr_t kernel::syscall::do_mmap_pgoff(uintptr_t addr, size_t len,
-        int prot, int flags, int fd, off_t pgoffset)
-{
+uintptr_t kernel::syscall::do_mmap_pgoff(uintptr_t addr, size_t len, int prot,
+                                         int flags, int fd, off_t pgoffset) {
     if (addr & 0xfff)
         return -EINVAL;
     if (len == 0)
@@ -274,8 +261,7 @@ uintptr_t kernel::syscall::do_mmap_pgoff(uintptr_t addr, size_t len,
         if (prot == PROT_NONE) {
             if (int ret = mms.unmap(addr, len, true); ret != 0)
                 return ret;
-        }
-        else {
+        } else {
             // TODO: add NULL check in mm_list
             if (!addr || !mms.is_avail(addr, len)) {
                 if (flags & MAP_FIXED)
@@ -306,8 +292,7 @@ uintptr_t kernel::syscall::do_mmap_pgoff(uintptr_t addr, size_t len,
     return addr;
 }
 
-int kernel::syscall::do_munmap(uintptr_t addr, size_t len)
-{
+int kernel::syscall::do_munmap(uintptr_t addr, size_t len) {
     if (addr & 0xfff)
         return -EINVAL;
 
@@ -315,8 +300,7 @@ int kernel::syscall::do_munmap(uintptr_t addr, size_t len)
 }
 
 ssize_t kernel::syscall::do_sendfile(int out_fd, int in_fd,
-        off_t __user* offset, size_t count)
-{
+                                     off_t __user* offset, size_t count) {
     auto* out_file = current_process->files[out_fd];
     auto* in_file = current_process->files[in_fd];
 
@@ -354,9 +338,8 @@ ssize_t kernel::syscall::do_sendfile(int out_fd, int in_fd,
     return totn;
 }
 
-int kernel::syscall::do_statx(int dirfd, const char __user* path,
-        int flags, unsigned int mask, statx __user* statxbuf)
-{
+int kernel::syscall::do_statx(int dirfd, const char __user* path, int flags,
+                              unsigned int mask, statx __user* statxbuf) {
     // AT_STATX_SYNC_AS_STAT is the default value
     if ((flags & AT_STATX_SYNC_TYPE) != AT_STATX_SYNC_AS_STAT) {
         NOT_IMPLEMENTED;
@@ -368,7 +351,7 @@ int kernel::syscall::do_statx(int dirfd, const char __user* path,
         return -EINVAL;
     }
 
-    auto [ dent, status ] = current_open(path, !(flags & AT_SYMLINK_NOFOLLOW));
+    auto [dent, status] = current_open(path, !(flags & AT_SYMLINK_NOFOLLOW));
     if (!dent || status)
         return status;
 
@@ -376,40 +359,37 @@ int kernel::syscall::do_statx(int dirfd, const char __user* path,
     return fs::statx(dent->inode, statxbuf, mask);
 }
 
-int kernel::syscall::do_fcntl(int fd, int cmd, unsigned long arg)
-{
+int kernel::syscall::do_fcntl(int fd, int cmd, unsigned long arg) {
     auto* file = current_process->files[fd];
     if (!file)
         return -EBADF;
 
     switch (cmd) {
-    case F_SETFD:
-        return current_process->files.set_flags(fd, arg);
-    case F_DUPFD:
-    case F_DUPFD_CLOEXEC: {
-        return current_process->files.dupfd(fd, arg, FD_CLOEXEC);
-    }
-    default:
-        NOT_IMPLEMENTED;
-        return -EINVAL;
+        case F_SETFD:
+            return current_process->files.set_flags(fd, arg);
+        case F_DUPFD:
+        case F_DUPFD_CLOEXEC: {
+            return current_process->files.dupfd(fd, arg, FD_CLOEXEC);
+        }
+        default:
+            NOT_IMPLEMENTED;
+            return -EINVAL;
     }
 }
 
-int kernel::syscall::do_mkdir(const char __user* pathname, mode_t mode)
-{
+int kernel::syscall::do_mkdir(const char __user* pathname, mode_t mode) {
     mode &= (~current_process->umask & 0777);
 
     // TODO: use copy_from_user
-    auto [ dent, status ] = current_open(pathname);
+    auto [dent, status] = current_open(pathname);
     if (!dent || status != -ENOENT)
         return status;
 
     return fs::mkdir(dent.get(), mode);
 }
 
-int kernel::syscall::do_truncate(const char __user* pathname, long length)
-{
-    auto [ dent, status ] = current_open(pathname);
+int kernel::syscall::do_truncate(const char __user* pathname, long length) {
+    auto [dent, status] = current_open(pathname);
     if (!dent || status)
         return status;
 
@@ -419,9 +399,8 @@ int kernel::syscall::do_truncate(const char __user* pathname, long length)
     return fs::truncate(dent->inode, length);
 }
 
-int kernel::syscall::do_unlink(const char __user* pathname)
-{
-    auto [ dent, status ] = current_open(pathname, false);
+int kernel::syscall::do_unlink(const char __user* pathname) {
+    auto [dent, status] = current_open(pathname, false);
 
     if (!dent || status)
         return status;
@@ -432,37 +411,35 @@ int kernel::syscall::do_unlink(const char __user* pathname)
     return fs::unlink(dent.get());
 }
 
-int kernel::syscall::do_access(const char __user* pathname, int mode)
-{
-    auto [ dent, status ] = current_open(pathname);
+int kernel::syscall::do_access(const char __user* pathname, int mode) {
+    auto [dent, status] = current_open(pathname);
     if (!dent || status)
         return status;
 
     switch (mode) {
-    case F_OK:
-        return 0;
-    case R_OK:
-    case W_OK:
-    case X_OK:
-        // TODO: check privilege
-        return 0;
-    default:
-        return -EINVAL;
+        case F_OK:
+            return 0;
+        case R_OK:
+        case W_OK:
+        case X_OK:
+            // TODO: check privilege
+            return 0;
+        default:
+            return -EINVAL;
     }
 }
 
-int kernel::syscall::do_mknod(const char __user* pathname, mode_t mode, dev_t dev)
-{
+int kernel::syscall::do_mknod(const char __user* pathname, mode_t mode,
+                              dev_t dev) {
     mode &= S_IFMT | (~current_process->umask & 0777);
-    auto [ dent, status ] = current_open(pathname);
+    auto [dent, status] = current_open(pathname);
     if (!dent || status != -ENOENT)
         return status;
 
     return fs::mknod(dent.get(), mode, dev);
 }
 
-int kernel::syscall::do_poll(pollfd __user* fds, nfds_t nfds, int timeout)
-{
+int kernel::syscall::do_poll(pollfd __user* fds, nfds_t nfds, int timeout) {
     if (nfds == 0)
         return 0;
 

+ 7 - 8
src/kernel/syscall/infoops.cc

@@ -8,15 +8,15 @@
 
 #define NOT_IMPLEMENTED not_implemented(__FILE__, __LINE__)
 
-static inline void not_implemented(const char* pos, int line)
-{
-    kmsgf("[kernel] the function at %s:%d is not implemented, killing the pid%d...",
-            pos, line, current_process->pid);
+static inline void not_implemented(const char* pos, int line) {
+    kmsgf(
+        "[kernel] the function at %s:%d is not implemented, killing the "
+        "pid%d...",
+        pos, line, current_process->pid);
     current_thread->send_signal(SIGSYS);
 }
 
-int kernel::syscall::do_clock_gettime(clockid_t clk_id, timespec __user* tp)
-{
+int kernel::syscall::do_clock_gettime(clockid_t clk_id, timespec __user* tp) {
     if (clk_id != CLOCK_REALTIME && clk_id != CLOCK_MONOTONIC) {
         NOT_IMPLEMENTED;
         return -EINVAL;
@@ -34,8 +34,7 @@ int kernel::syscall::do_clock_gettime(clockid_t clk_id, timespec __user* tp)
     return 0;
 }
 
-int kernel::syscall::do_gettimeofday(timeval __user* tv, void __user* tz)
-{
+int kernel::syscall::do_gettimeofday(timeval __user* tv, void __user* tz) {
     // TODO: return time of the day, not time from this boot
     if (tz) [[unlikely]]
         return -EINVAL;

+ 5 - 8
src/kernel/syscall/mount.cc

@@ -6,18 +6,15 @@
 #include <kernel/syscall.hpp>
 #include <kernel/vfs.hpp>
 
-int kernel::syscall::do_mount(
-        const char __user* source,
-        const char __user* target,
-        const char __user* fstype,
-        unsigned long flags,
-        const void __user* _fsdata)
-{
+int kernel::syscall::do_mount(const char __user* source,
+                              const char __user* target,
+                              const char __user* fstype, unsigned long flags,
+                              const void __user* _fsdata) {
     if (!fstype)
         return -EINVAL;
 
     // TODO: use copy_from_user
-    auto [ mountpoint, status ] = current_open(target);
+    auto [mountpoint, status] = current_open(target);
     if (!mountpoint || status)
         return status;
 

+ 89 - 112
src/kernel/syscall/procops.cc

@@ -19,15 +19,15 @@ using namespace kernel::syscall;
 
 #define NOT_IMPLEMENTED not_implemented(__FILE__, __LINE__)
 
-static inline void not_implemented(const char* pos, int line)
-{
-    kmsgf("[kernel] the function at %s:%d is not implemented, killing the pid%d...",
-            pos, line, current_process->pid);
+static inline void not_implemented(const char* pos, int line) {
+    kmsgf(
+        "[kernel] the function at %s:%d is not implemented, killing the "
+        "pid%d...",
+        pos, line, current_process->pid);
     current_thread->send_signal(SIGSYS);
 }
 
-int kernel::syscall::do_chdir(const char __user* path)
-{
+int kernel::syscall::do_chdir(const char __user* path) {
     // TODO: use copy_from_user
     auto [dir, ret] = current_open(path);
     if (!dir || ret)
@@ -40,16 +40,15 @@ int kernel::syscall::do_chdir(const char __user* path)
     return 0;
 }
 
-execve_retval kernel::syscall::do_execve(
-        const std::string& exec,
-        const std::vector<std::string>& args,
-        const std::vector<std::string>& envs)
-{
+execve_retval kernel::syscall::do_execve(const std::string& exec,
+                                         const std::vector<std::string>& args,
+                                         const std::vector<std::string>& envs) {
     types::elf::elf32_load_data d{
         .exec_dent{},
         .argv{args},
         .envp{envs},
-        .ip{}, .sp{},
+        .ip{},
+        .sp{},
     };
 
     fs::dentry_pointer dent;
@@ -58,7 +57,7 @@ execve_retval kernel::syscall::do_execve(
         std::tie(dent, ret) = current_open(exec);
 
         if (!dent || ret)
-            return { 0, 0, ret };
+            return {0, 0, ret};
 
         d.exec_dent = dent.get();
     }
@@ -75,18 +74,16 @@ execve_retval kernel::syscall::do_execve(
         if (ret == types::elf::ELF_LOAD_FAIL_NORETURN)
             kill_current(SIGSEGV);
 
-        return { 0, 0, ret };
+        return {0, 0, ret};
     }
 
     current_thread->signals.on_exec();
     async::preempt_enable();
 
-    return { d.ip, d.sp, 0 };
+    return {d.ip, d.sp, 0};
 }
 
-
-int kernel::syscall::do_exit(int status)
-{
+int kernel::syscall::do_exit(int status) {
     // TODO: terminating a thread only
     assert(current_process->thds.size() == 1);
 
@@ -97,8 +94,7 @@ int kernel::syscall::do_exit(int status)
     schedule_noreturn();
 }
 
-int kernel::syscall::do_waitpid(pid_t waitpid, int __user* arg1, int options)
-{
+int kernel::syscall::do_waitpid(pid_t waitpid, int __user* arg1, int options) {
     if (waitpid != -1)
         return -EINVAL;
 
@@ -145,11 +141,11 @@ int kernel::syscall::do_waitpid(pid_t waitpid, int __user* arg1, int options)
     return -EINVAL;
 }
 
-int kernel::syscall::do_getcwd(char __user* buf, size_t buf_size)
-{
-    auto path = fs::d_path(current_process->cwd.get(), current_process->fs_context.root.get());
+int kernel::syscall::do_getcwd(char __user* buf, size_t buf_size) {
+    auto path = fs::d_path(current_process->cwd.get(),
+                           current_process->fs_context.root.get());
 
-    int len = std::min(buf_size-1, path.size());
+    int len = std::min(buf_size - 1, path.size());
 
     // TODO: use copy_to_user
     strncpy(buf, path.c_str(), len);
@@ -158,8 +154,7 @@ int kernel::syscall::do_getcwd(char __user* buf, size_t buf_size)
     return len;
 }
 
-pid_t kernel::syscall::do_setsid()
-{
+pid_t kernel::syscall::do_setsid() {
     if (current_process->pid == current_process->pgid)
         return -EPERM;
 
@@ -173,9 +168,8 @@ pid_t kernel::syscall::do_setsid()
     return current_process->pid;
 }
 
-pid_t kernel::syscall::do_getsid(pid_t pid)
-{
-    auto [ pproc, found ] = procs->try_find(pid);
+pid_t kernel::syscall::do_getsid(pid_t pid) {
+    auto [pproc, found] = procs->try_find(pid);
     if (!found)
         return -ESRCH;
     if (pproc->sid != current_process->sid)
@@ -184,8 +178,7 @@ pid_t kernel::syscall::do_getsid(pid_t pid)
     return pproc->sid;
 }
 
-int kernel::syscall::do_setpgid(pid_t pid, pid_t pgid)
-{
+int kernel::syscall::do_setpgid(pid_t pid, pid_t pgid) {
     if (pgid < 0)
         return -EINVAL;
 
@@ -195,7 +188,7 @@ int kernel::syscall::do_setpgid(pid_t pid, pid_t pgid)
     if (pgid == 0)
         pgid = pid;
 
-    auto [ pproc, found ] = procs->try_find(pid);
+    auto [pproc, found] = procs->try_find(pid);
     if (!found)
         return -ESRCH;
 
@@ -207,8 +200,7 @@ int kernel::syscall::do_setpgid(pid_t pid, pid_t pgid)
     return 0;
 }
 
-int kernel::syscall::do_set_thread_area(kernel::user::user_desc __user* ptr)
-{
+int kernel::syscall::do_set_thread_area(kernel::user::user_desc __user* ptr) {
     auto ret = current_thread->set_thread_area(ptr);
     if (ret != 0)
         return ret;
@@ -217,70 +209,65 @@ int kernel::syscall::do_set_thread_area(kernel::user::user_desc __user* ptr)
     return 0;
 }
 
-pid_t kernel::syscall::do_set_tid_address(int __user* tidptr)
-{
+pid_t kernel::syscall::do_set_tid_address(int __user* tidptr) {
     // TODO: copy_from_user
     current_thread->set_child_tid = tidptr;
     return current_thread->tid();
 }
 
-int kernel::syscall::do_prctl(int option, uintptr_t arg2)
-{
+int kernel::syscall::do_prctl(int option, uintptr_t arg2) {
     switch (option) {
-    case PR_SET_NAME: {
-        // TODO: copy_from_user
-        auto* name = (const char __user*)arg2;
-        current_thread->name.assign(name, 15);
-        break;
-    }
-    case PR_GET_NAME: {
-        auto* name = (char __user*)arg2;
-        // TODO: copy_to_user
-        strncpy(name, current_thread->name.c_str(), 16);
-        name[15] = 0;
-        break;
-    }
-    default:
-        return -EINVAL;
+        case PR_SET_NAME: {
+            // TODO: copy_from_user
+            auto* name = (const char __user*)arg2;
+            current_thread->name.assign(name, 15);
+            break;
+        }
+        case PR_GET_NAME: {
+            auto* name = (char __user*)arg2;
+            // TODO: copy_to_user
+            strncpy(name, current_thread->name.c_str(), 16);
+            name[15] = 0;
+            break;
+        }
+        default:
+            return -EINVAL;
     }
 
     return 0;
 }
 
-int kernel::syscall::do_arch_prctl(int option, uintptr_t arg2)
-{
+int kernel::syscall::do_arch_prctl(int option, uintptr_t arg2) {
     switch (option) {
-    case PR_SET_NAME: {
-        // TODO: copy_from_user
-        auto* name = (const char __user*)arg2;
-        current_thread->name.assign(name, 15);
-        break;
-    }
-    case PR_GET_NAME: {
-        auto* name = (char __user*)arg2;
-        // TODO: copy_to_user
-        strncpy(name, current_thread->name.c_str(), 16);
-        name[15] = 0;
-        break;
-    }
-    default:
-        return -EINVAL;
+        case PR_SET_NAME: {
+            // TODO: copy_from_user
+            auto* name = (const char __user*)arg2;
+            current_thread->name.assign(name, 15);
+            break;
+        }
+        case PR_GET_NAME: {
+            auto* name = (char __user*)arg2;
+            // TODO: copy_to_user
+            strncpy(name, current_thread->name.c_str(), 16);
+            name[15] = 0;
+            break;
+        }
+        default:
+            return -EINVAL;
     }
 
     return 0;
 }
 
-int kernel::syscall::do_umask(mode_t mask)
-{
+int kernel::syscall::do_umask(mode_t mask) {
     mode_t old = current_process->umask;
     current_process->umask = mask;
 
     return old;
 }
 
-int kernel::syscall::do_kill(pid_t pid, int sig)
-{
-    auto [ pproc, found ] = procs->try_find(pid);
+int kernel::syscall::do_kill(pid_t pid, int sig) {
+    auto [pproc, found] = procs->try_find(pid);
     if (!found)
         return -ESRCH;
 
@@ -296,12 +283,11 @@ int kernel::syscall::do_kill(pid_t pid, int sig)
     return 0;
 }
 
-int kernel::syscall::do_tkill(pid_t tid, int sig)
-{
+int kernel::syscall::do_tkill(pid_t tid, int sig) {
     NOT_IMPLEMENTED;
     return -EINVAL;
 
-    auto [ pproc, found ] = procs->try_find(tid);
+    auto [pproc, found] = procs->try_find(tid);
     if (!found)
         return -ESRCH;
 
@@ -318,8 +304,8 @@ int kernel::syscall::do_tkill(pid_t tid, int sig)
 }
 
 int kernel::syscall::do_rt_sigprocmask(int how, const sigmask_type __user* set,
-        sigmask_type __user* oldset, size_t sigsetsize)
-{
+                                       sigmask_type __user* oldset,
+                                       size_t sigsetsize) {
     if (sigsetsize != sizeof(sigmask_type))
         return -EINVAL;
 
@@ -334,28 +320,28 @@ int kernel::syscall::do_rt_sigprocmask(int how, const sigmask_type __user* set,
 
     // TODO: use copy_from_user
     switch (how) {
-    case SIG_BLOCK:
-        current_thread->signals.mask(*set);
-        break;
-    case SIG_UNBLOCK:
-        current_thread->signals.unmask(*set);
-        break;
-    case SIG_SETMASK:
-        current_thread->signals.set_mask(*set);
-        break;
+        case SIG_BLOCK:
+            current_thread->signals.mask(*set);
+            break;
+        case SIG_UNBLOCK:
+            current_thread->signals.unmask(*set);
+            break;
+        case SIG_SETMASK:
+            current_thread->signals.set_mask(*set);
+            break;
     }
 
     return 0;
 }
 
 int kernel::syscall::do_rt_sigaction(int signum, const sigaction __user* act,
-        sigaction __user* oldact, size_t sigsetsize)
-{
+                                     sigaction __user* oldact,
+                                     size_t sigsetsize) {
     if (sigsetsize != sizeof(sigmask_type))
         return -EINVAL;
 
-    if (!kernel::signal_list::check_valid(signum)
-        || signum == SIGKILL || signum == SIGSTOP)
+    if (!kernel::signal_list::check_valid(signum) || signum == SIGKILL ||
+        signum == SIGSTOP)
         return -EINVAL;
 
     // TODO: use copy_to_user
@@ -371,8 +357,7 @@ int kernel::syscall::do_rt_sigaction(int signum, const sigaction __user* act,
     return 0;
 }
 
-int kernel::syscall::do_newuname(new_utsname __user* buf)
-{
+int kernel::syscall::do_newuname(new_utsname __user* buf) {
     if (!buf)
         return -EFAULT;
 
@@ -382,49 +367,41 @@ int kernel::syscall::do_newuname(new_utsname __user* buf)
     return 0;
 }
 
-pid_t kernel::syscall::do_getpgid(pid_t pid)
-{
+pid_t kernel::syscall::do_getpgid(pid_t pid) {
     if (pid == 0)
         return current_process->pgid;
 
-    auto [ pproc, found ] = procs->try_find(pid);
+    auto [pproc, found] = procs->try_find(pid);
     if (!found)
         return -ESRCH;
 
     return pproc->pgid;
 }
 
-pid_t kernel::syscall::do_getpid()
-{
+pid_t kernel::syscall::do_getpid() {
     return current_process->pid;
 }
 
-pid_t kernel::syscall::do_getppid()
-{
+pid_t kernel::syscall::do_getppid() {
     return current_process->ppid;
 }
 
-uid_t kernel::syscall::do_getuid()
-{
+uid_t kernel::syscall::do_getuid() {
     return 0; // all users are root for now
 }
 
-uid_t kernel::syscall::do_geteuid()
-{
+uid_t kernel::syscall::do_geteuid() {
     return 0; // all users are root for now
 }
 
-gid_t kernel::syscall::do_getgid()
-{
+gid_t kernel::syscall::do_getgid() {
     return 0; // all users are root for now
 }
 
-pid_t kernel::syscall::do_gettid()
-{
+pid_t kernel::syscall::do_gettid() {
     return current_thread->tid();
 }
 
-uintptr_t kernel::syscall::do_brk(uintptr_t addr)
-{
+uintptr_t kernel::syscall::do_brk(uintptr_t addr) {
     return current_process->mms.set_brk(addr);
 }

+ 5 - 10
src/kernel/task/readyqueue.cc

@@ -1,8 +1,7 @@
-#include <kernel/task/readyqueue.hpp>
-
 #include <list>
 
 #include <kernel/async/lock.hpp>
+#include <kernel/task/readyqueue.hpp>
 #include <kernel/task/thread.hpp>
 
 using namespace kernel::task;
@@ -12,27 +11,23 @@ static mutex dispatcher_mtx;
 static std::list<thread*> dispatcher_thds;
 static thread* idle_task;
 
-void dispatcher::setup_idle(thread* _idle)
-{
+void dispatcher::setup_idle(thread* _idle) {
     idle_task = _idle;
 }
 
-void dispatcher::enqueue(thread* thd)
-{
+void dispatcher::enqueue(thread* thd) {
     lock_guard_irq lck(dispatcher_mtx);
 
     dispatcher_thds.push_back(thd);
 }
 
-void dispatcher::dequeue(thread* thd)
-{
+void dispatcher::dequeue(thread* thd) {
     lock_guard_irq lck(dispatcher_mtx);
 
     dispatcher_thds.remove(thd);
 }
 
-thread* dispatcher::next()
-{
+thread* dispatcher::next() {
     lock_guard_irq lck(dispatcher_mtx);
 
     if (dispatcher_thds.empty()) {

+ 61 - 73
src/kernel/task/thread.cc

@@ -29,41 +29,37 @@ struct PACKED tss64_t {
 constexpr physaddr<tss64_t> tss{0x00000070};
 
 thread::thread(std::string name, pid_t owner)
-    : owner { owner }, attr { READY | SYSTEM }, name { name } { }
+    : owner{owner}, attr{READY | SYSTEM}, name{name} {}
 
 thread::thread(const thread& val, pid_t owner)
-    : owner { owner }, attr { val.attr }, name { val.name }, tls_desc32{val.tls_desc32} { }
+    : owner{owner}
+    , attr{val.attr}
+    , name{val.name}
+    , tls_desc32{val.tls_desc32} {}
 
-tid_t thread::tid() const
-{
+tid_t thread::tid() const {
     return (tid_t)kstack.pfn;
 }
 
-bool thread::operator<(const thread& rhs) const
-{
+bool thread::operator<(const thread& rhs) const {
     return tid() < rhs.tid();
 }
 
-bool thread::operator==(const thread& rhs) const
-{
+bool thread::operator==(const thread& rhs) const {
     return tid() == rhs.tid();
 }
 
-static inline uintptr_t __stack_bottom(pfn_t pfn)
-{
-    return (uintptr_t)(void*)
-        kernel::mem::physaddr<void>{pfn + (1 << KERNEL_STACK_ORDER) * 0x1000};
+static inline uintptr_t __stack_bottom(pfn_t pfn) {
+    return (uintptr_t)(void*)kernel::mem::physaddr<void>{
+        pfn + (1 << KERNEL_STACK_ORDER) * 0x1000};
 }
 
-thread::kernel_stack::kernel_stack()
-{
+thread::kernel_stack::kernel_stack() {
     pfn = page_to_pfn(alloc_pages(KERNEL_STACK_ORDER));
     sp = __stack_bottom(pfn);
 }
 
-thread::kernel_stack::kernel_stack(const kernel_stack& other)
-    : kernel_stack()
-{
+thread::kernel_stack::kernel_stack(const kernel_stack& other) : kernel_stack() {
     auto offset = __stack_bottom(other.pfn) - other.sp;
 
     sp -= offset;
@@ -71,87 +67,80 @@ thread::kernel_stack::kernel_stack(const kernel_stack& other)
 }
 
 thread::kernel_stack::kernel_stack(kernel_stack&& other)
-    : pfn(std::exchange(other.pfn, 0))
-    , sp(std::exchange(other.sp, 0)) { }
+    : pfn(std::exchange(other.pfn, 0)), sp(std::exchange(other.sp, 0)) {}
 
-thread::kernel_stack::~kernel_stack()
-{
+thread::kernel_stack::~kernel_stack() {
     if (!pfn)
         return;
     free_pages(pfn, KERNEL_STACK_ORDER);
 }
 
-uint64_t thread::kernel_stack::pushq(uint64_t val)
-{
+uint64_t thread::kernel_stack::pushq(uint64_t val) {
     sp -= 8;
     *(uint64_t*)sp = val;
     return val;
 }
 
-uint32_t thread::kernel_stack::pushl(uint32_t val)
-{
+uint32_t thread::kernel_stack::pushl(uint32_t val) {
     sp -= 4;
     *(uint32_t*)sp = val;
     return val;
 }
 
-void thread::kernel_stack::load_interrupt_stack() const
-{
+void thread::kernel_stack::load_interrupt_stack() const {
     tss->rsp[0] = sp;
 }
 
-void thread::set_attr(thd_attr_t new_attr)
-{
+void thread::set_attr(thd_attr_t new_attr) {
     switch (new_attr) {
-    case SYSTEM:
-        attr |= SYSTEM;
-        break;
-    case READY:
-        if (attr & ZOMBIE) {
-            kmsgf("[kernel:warn] zombie process pid%d tries to wake up", owner);
+        case SYSTEM:
+            attr |= SYSTEM;
             break;
-        }
+        case READY:
+            if (attr & ZOMBIE) {
+                kmsgf("[kernel:warn] zombie process pid%d tries to wake up",
+                      owner);
+                break;
+            }
 
-        if (attr & READY)
+            if (attr & READY)
+                break;
+
+            attr &= SYSTEM;
+            attr |= READY;
+
+            dispatcher::enqueue(this);
+            break;
+        case ISLEEP:
+            attr &= SYSTEM;
+            attr |= ISLEEP;
+
+            dispatcher::dequeue(this);
             break;
+        case STOPPED:
+            attr &= SYSTEM;
+            attr |= STOPPED;
 
-        attr &= SYSTEM;
-        attr |= READY;
-
-        dispatcher::enqueue(this);
-        break;
-    case ISLEEP:
-        attr &= SYSTEM;
-        attr |= ISLEEP;
-
-        dispatcher::dequeue(this);
-        break;
-    case STOPPED:
-        attr &= SYSTEM;
-        attr |= STOPPED;
-
-        dispatcher::dequeue(this);
-        break;
-    case ZOMBIE:
-        attr &= SYSTEM;
-        attr |= ZOMBIE;
-
-        dispatcher::dequeue(this);
-        break;
-    default:
-        kmsgf("[kernel:warn] unknown thread attribute: %x", new_attr);
-        break;
+            dispatcher::dequeue(this);
+            break;
+        case ZOMBIE:
+            attr &= SYSTEM;
+            attr |= ZOMBIE;
+
+            dispatcher::dequeue(this);
+            break;
+        default:
+            kmsgf("[kernel:warn] unknown thread attribute: %x", new_attr);
+            break;
     }
 }
 
-void thread::send_signal(signal_list::signo_type signal)
-{
+void thread::send_signal(signal_list::signo_type signal) {
     if (signals.raise(signal))
         this->set_attr(READY);
 }
 
-int thread::set_thread_area(kernel::user::user_desc* ptr)
-{
+int thread::set_thread_area(kernel::user::user_desc* ptr) {
     if (ptr->read_exec_only && ptr->seg_not_present) {
         // TODO: use copy_to_user
         auto* dst = (void*)(uintptr_t)ptr->base_addr;
@@ -170,21 +159,20 @@ int thread::set_thread_area(kernel::user::user_desc* ptr)
         return -1;
 
     if ((ptr->limit & 0xffff) != 0xffff) {
-        asm volatile("nop": : : "memory");
+        asm volatile("nop" : : : "memory");
     }
 
-    tls_desc32  = ptr->limit & 0x0'ffff;
+    tls_desc32 = ptr->limit & 0x0'ffff;
     tls_desc32 |= (ptr->base_addr & 0x00'ffffffULL) << 16;
     tls_desc32 |= 0x4'0'f2'000000'0000;
-    tls_desc32 |= (ptr->limit & 0xf'0000ULL) << (48-16);
+    tls_desc32 |= (ptr->limit & 0xf'0000ULL) << (48 - 16);
     tls_desc32 |= ((ptr->limit_in_pages + 0ULL) << 55);
-    tls_desc32 |= (ptr->base_addr & 0xff'000000ULL) << (56-24);
+    tls_desc32 |= (ptr->base_addr & 0xff'000000ULL) << (56 - 24);
 
     return 0;
 }
 
-int thread::load_thread_area32() const
-{
+int thread::load_thread_area32() const {
     kernel::user::load_thread_area32(tls_desc32);
     return 0;
 }

+ 64 - 68
src/kernel/tty.cpp

@@ -5,19 +5,24 @@
 #include <termios.h>
 
 #include <kernel/async/lock.hpp>
+#include <kernel/log.hpp>
 #include <kernel/process.hpp>
 #include <kernel/tty.hpp>
 #include <kernel/vga.hpp>
-#include <kernel/log.hpp>
 
 #define CTRL(key) ((key)-0x40)
 
-#define TERMIOS_ISET(termios, option) ((option) == ((termios).c_iflag & (option)))
-#define TERMIOS_OSET(termios, option) ((option) == ((termios).c_oflag & (option)))
-#define TERMIOS_CSET(termios, option) ((option) == ((termios).c_cflag & (option)))
-#define TERMIOS_LSET(termios, option) ((option) == ((termios).c_lflag & (option)))
+#define TERMIOS_ISET(termios, option) \
+    ((option) == ((termios).c_iflag & (option)))
+#define TERMIOS_OSET(termios, option) \
+    ((option) == ((termios).c_oflag & (option)))
+#define TERMIOS_CSET(termios, option) \
+    ((option) == ((termios).c_cflag & (option)))
+#define TERMIOS_LSET(termios, option) \
+    ((option) == ((termios).c_lflag & (option)))
 
-#define TERMIOS_TESTCC(c, termios, cc) ((c != 0xff) && (c == ((termios).c_cc[cc])))
+#define TERMIOS_TESTCC(c, termios, cc) \
+    ((c != 0xff) && (c == ((termios).c_cc[cc])))
 
 using namespace kernel::tty;
 
@@ -49,14 +54,12 @@ tty::tty(std::string name)
     this->termio.c_cc[VMIN] = 1;
 }
 
-void tty::print(const char* str)
-{
+void tty::print(const char* str) {
     while (*str != '\0')
         this->putchar(*(str++));
 }
 
-int tty::poll()
-{
+int tty::poll() {
     async::lock_guard_irq lck(this->mtx_buf);
     if (this->buf.empty()) {
         bool interrupted = this->waitlist.wait(this->mtx_buf);
@@ -68,8 +71,7 @@ int tty::poll()
     return 1;
 }
 
-ssize_t tty::read(char* buf, size_t buf_size, size_t n)
-{
+ssize_t tty::read(char* buf, size_t buf_size, size_t n) {
     n = std::max(buf_size, n);
     size_t orig_n = n;
 
@@ -94,7 +96,7 @@ ssize_t tty::read(char* buf, size_t buf_size, size_t n)
             break;
         }
 
-        while (n &&!this->buf.empty()) {
+        while (n && !this->buf.empty()) {
             int c = this->buf.get();
 
             --n, *(buf++) = c;
@@ -108,8 +110,7 @@ ssize_t tty::read(char* buf, size_t buf_size, size_t n)
     return orig_n - n;
 }
 
-int tty::_do_erase(bool should_echo)
-{
+int tty::_do_erase(bool should_echo) {
     if (buf.empty())
         return -1;
 
@@ -125,7 +126,7 @@ int tty::_do_erase(bool should_echo)
 
     if (should_echo && TERMIOS_LSET(this->termio, ECHO | ECHOE)) {
         this->show_char('\b'); // backspace
-        this->show_char(' '); // space
+        this->show_char(' ');  // space
         this->show_char('\b'); // backspace
 
         // xterm's way to show backspace
@@ -138,39 +139,40 @@ int tty::_do_erase(bool should_echo)
     return back;
 }
 
-void tty::_real_commit_char(int c)
-{
+void tty::_real_commit_char(int c) {
     switch (c) {
-    case '\n':
-        buf.put(c);
+        case '\n':
+            buf.put(c);
 
-        if (TERMIOS_LSET(this->termio, ECHONL) || TERMIOS_LSET(this->termio, ECHO))
-            this->_echo_char(c);
+            if (TERMIOS_LSET(this->termio, ECHONL) ||
+                TERMIOS_LSET(this->termio, ECHO))
+                this->_echo_char(c);
 
-        // if ICANON is set, we notify all waiting processes
-        // if ICANON is not set, since there are data ready, we notify as well
-        this->waitlist.notify_all();
+            // if ICANON is set, we notify all waiting processes
+            // if ICANON is not set, since there are data ready, we notify as
+            // well
+            this->waitlist.notify_all();
 
-        break;
+            break;
 
-    default:
-        buf.put(c);
+        default:
+            buf.put(c);
 
-        if (TERMIOS_LSET(this->termio, ECHO))
-            this->_echo_char(c);
+            if (TERMIOS_LSET(this->termio, ECHO))
+                this->_echo_char(c);
 
-        if (!TERMIOS_LSET(this->termio, ICANON))
-            this->waitlist.notify_all();
+            if (!TERMIOS_LSET(this->termio, ICANON))
+                this->waitlist.notify_all();
 
-        break;
+            break;
     }
 }
 
-void tty::_echo_char(int c)
-{
+void tty::_echo_char(int c) {
     // ECHOCTL
     do {
-        if (c < 0 || c >= 32 || !TERMIOS_LSET(this->termio, ECHO | ECHOCTL | IEXTEN))
+        if (c < 0 || c >= 32 ||
+            !TERMIOS_LSET(this->termio, ECHO | ECHOCTL | IEXTEN))
             break;
 
         if (c == '\t' || c == '\n' || c == CTRL('Q') || c == CTRL('S'))
@@ -187,8 +189,7 @@ void tty::_echo_char(int c)
 
 // do some ignore and remapping work
 // real commit operation is in _real_commit_char()
-void tty::commit_char(int c)
-{
+void tty::commit_char(int c) {
     // check special control characters
     // if handled, the character is discarded
     if (TERMIOS_LSET(this->termio, ISIG)) {
@@ -234,8 +235,7 @@ void tty::commit_char(int c)
             if (TERMIOS_LSET(this->termio, ECHOKE | IEXTEN)) {
                 while (this->_do_erase(true) != -1)
                     ;
-            }
-            else if (TERMIOS_LSET(this->termio, ECHOK)) {
+            } else if (TERMIOS_LSET(this->termio, ECHOK)) {
                 while (this->_do_erase(false) != -1)
                     ;
                 this->show_char('\n');
@@ -250,54 +250,50 @@ void tty::commit_char(int c)
     }
 
     switch (c) {
-    case '\r':
-        if (TERMIOS_ISET(this->termio, IGNCR))
-            break;
-
-        if (TERMIOS_ISET(this->termio, ICRNL)) {
-            this->_real_commit_char('\n');
-            break;
-        }
+        case '\r':
+            if (TERMIOS_ISET(this->termio, IGNCR))
+                break;
 
-        this->_real_commit_char('\r');
-        break;
+            if (TERMIOS_ISET(this->termio, ICRNL)) {
+                this->_real_commit_char('\n');
+                break;
+            }
 
-    case '\n':
-        if (TERMIOS_ISET(this->termio, INLCR)) {
             this->_real_commit_char('\r');
             break;
-        }
 
-        this->_real_commit_char('\n');
-        break;
+        case '\n':
+            if (TERMIOS_ISET(this->termio, INLCR)) {
+                this->_real_commit_char('\r');
+                break;
+            }
 
-    default:
-        this->_real_commit_char(c);
-        break;
+            this->_real_commit_char('\n');
+            break;
+
+        default:
+            this->_real_commit_char(c);
+            break;
     }
 }
 
-void tty::show_char(int c)
-{
+void tty::show_char(int c) {
     this->putchar(c);
 }
 
-vga_tty::vga_tty(): tty{"ttyVGA"} { }
+vga_tty::vga_tty() : tty{"ttyVGA"} {}
 
-void vga_tty::putchar(char c)
-{
-    static struct vga_char vc = { .c = '\0', .color = VGA_CHAR_COLOR_WHITE };
+void vga_tty::putchar(char c) {
+    static struct vga_char vc = {.c = '\0', .color = VGA_CHAR_COLOR_WHITE};
     vc.c = c;
     vga_put_char(&vc);
 }
 
-void tty::clear_read_buf(void)
-{
+void tty::clear_read_buf(void) {
     this->buf.clear();
 }
 
-int kernel::tty::register_tty(tty* tty_dev)
-{
+int kernel::tty::register_tty(tty* tty_dev) {
     // TODO: manage all ttys
     if (!console)
         console = tty_dev;

+ 4 - 4
src/kernel/user/thread_local.cc

@@ -8,8 +8,7 @@
 
 using namespace kernel::user;
 
-void kernel::user::load_thread_area32(uint64_t desc)
-{
+void kernel::user::load_thread_area32(uint64_t desc) {
     if (!desc)
         return;
 
@@ -18,6 +17,7 @@ void kernel::user::load_thread_area32(uint64_t desc)
     asm volatile(
         "mov %%gs, %%ax\n\t"
         "mov %%ax, %%gs\n\t"
-        : : : "ax"
-    );
+        :
+        :
+        : "ax");
 }

+ 87 - 127
src/kernel/vfs.cpp

@@ -25,16 +25,11 @@
 
 using fs::dentry;
 
-fs::regular_file::regular_file(
-    file_flags flags, size_t cursor, struct inode* ind)
-    : file(ind->mode, flags)
-    , cursor(cursor)
-    , ind(ind)
-{
-}
+fs::regular_file::regular_file(file_flags flags, size_t cursor,
+                               struct inode* ind)
+    : file(ind->mode, flags), cursor(cursor), ind(ind) {}
 
-ssize_t fs::regular_file::read(char* __user buf, size_t n)
-{
+ssize_t fs::regular_file::read(char* __user buf, size_t n) {
     if (!flags.read)
         return -EBADF;
 
@@ -49,8 +44,7 @@ ssize_t fs::regular_file::read(char* __user buf, size_t n)
     return n_wrote;
 }
 
-ssize_t fs::regular_file::do_write(const char* __user buf, size_t n)
-{
+ssize_t fs::regular_file::do_write(const char* __user buf, size_t n) {
     if (S_ISDIR(mode))
         return -EISDIR;
 
@@ -62,24 +56,23 @@ ssize_t fs::regular_file::do_write(const char* __user buf, size_t n)
     return n_wrote;
 }
 
-off_t fs::regular_file::seek(off_t n, int whence)
-{
+off_t fs::regular_file::seek(off_t n, int whence) {
     if (!S_ISREG(mode))
         return -ESPIPE;
 
     size_t pos;
     switch (whence) {
-    case SEEK_SET:
-        pos = n;
-        break;
-    case SEEK_CUR:
-        pos = cursor + n;
-        break;
-    case SEEK_END:
-        pos = ind->size + n;
-        break;
-    default:
-        return -EINVAL;
+        case SEEK_SET:
+            pos = n;
+            break;
+        case SEEK_CUR:
+            pos = cursor + n;
+            break;
+        case SEEK_END:
+            pos = ind->size + n;
+            break;
+        default:
+            return -EINVAL;
     }
 
     if (pos > ind->size)
@@ -90,13 +83,13 @@ off_t fs::regular_file::seek(off_t n, int whence)
     return cursor;
 }
 
-int fs::regular_file::getdents(char* __user buf, size_t cnt)
-{
+int fs::regular_file::getdents(char* __user buf, size_t cnt) {
     if (!S_ISDIR(ind->mode))
         return -ENOTDIR;
 
     size_t orig_cnt = cnt;
-    int nread = ind->fs->readdir(ind, cursor,
+    int nread = ind->fs->readdir(
+        ind, cursor,
         [&buf, &cnt](const char* fn, struct inode* ind, uint8_t type) {
             size_t filename_len = strlen(fn);
 
@@ -125,13 +118,13 @@ int fs::regular_file::getdents(char* __user buf, size_t cnt)
     return orig_cnt - cnt;
 }
 
-int fs::regular_file::getdents64(char* __user buf, size_t cnt)
-{
+int fs::regular_file::getdents64(char* __user buf, size_t cnt) {
     if (!S_ISDIR(ind->mode))
         return -ENOTDIR;
 
     size_t orig_cnt = cnt;
-    int nread = ind->fs->readdir(ind, cursor,
+    int nread = ind->fs->readdir(
+        ind, cursor,
         [&buf, &cnt](const char* fn, struct inode* ind, uint8_t type) {
             size_t filename_len = strlen(fn);
 
@@ -159,28 +152,21 @@ int fs::regular_file::getdents64(char* __user buf, size_t cnt)
     return orig_cnt - cnt;
 }
 
-fs::fifo_file::fifo_file(file_flags flags,
-    std::shared_ptr<fs::pipe> ppipe)
-    : file(S_IFIFO, flags)
-    , ppipe(ppipe)
-{
-}
+fs::fifo_file::fifo_file(file_flags flags, std::shared_ptr<fs::pipe> ppipe)
+    : file(S_IFIFO, flags), ppipe(ppipe) {}
 
-ssize_t fs::fifo_file::read(char* __user buf, size_t n)
-{
+ssize_t fs::fifo_file::read(char* __user buf, size_t n) {
     if (!flags.read)
         return -EBADF;
 
     return ppipe->read(buf, n);
 }
 
-ssize_t fs::fifo_file::do_write(const char* __user buf, size_t n)
-{
+ssize_t fs::fifo_file::do_write(const char* __user buf, size_t n) {
     return ppipe->write(buf, n);
 }
 
-fs::fifo_file::~fifo_file()
-{
+fs::fifo_file::~fifo_file() {
     assert(flags.read ^ flags.write);
     if (flags.read)
         ppipe->close_read();
@@ -191,8 +177,8 @@ fs::fifo_file::~fifo_file()
 static fs::blkdev_ops** blkdevs[256];
 static fs::chrdev_ops** chrdevs[256];
 
-size_t fs::read(struct fs::inode* file, char* buf, size_t buf_size, size_t offset, size_t n)
-{
+size_t fs::read(struct fs::inode* file, char* buf, size_t buf_size,
+                size_t offset, size_t n) {
     if (S_ISDIR(file->mode)) {
         errno = EISDIR;
         return -1U;
@@ -225,8 +211,8 @@ size_t fs::read(struct fs::inode* file, char* buf, size_t buf_size, size_t offse
     errno = EINVAL;
     return -1U;
 }
-size_t fs::write(struct fs::inode* file, const char* buf, size_t offset, size_t n)
-{
+size_t fs::write(struct fs::inode* file, const char* buf, size_t offset,
+                 size_t n) {
     if (S_ISDIR(file->mode)) {
         errno = EISDIR;
         return -1U;
@@ -260,9 +246,10 @@ size_t fs::write(struct fs::inode* file, const char* buf, size_t offset, size_t
     return -1U;
 }
 
-std::pair<fs::dentry_pointer, int> fs::open(const fs_context& context, dentry* _cwd,
-    types::path_iterator path, bool follow, int recurs_no)
-{
+std::pair<fs::dentry_pointer, int> fs::open(const fs_context& context,
+                                            dentry* _cwd,
+                                            types::path_iterator path,
+                                            bool follow, int recurs_no) {
     // too many recursive search layers will cause stack overflow
     // so we use 16 for now
     if (recurs_no >= 16)
@@ -270,7 +257,7 @@ std::pair<fs::dentry_pointer, int> fs::open(const fs_context& context, dentry* _
 
     dentry_pointer cwd{path.is_absolute() ? d_get(context.root) : d_get(_cwd)};
 
-    for ( ; path; ++path) {
+    for (; path; ++path) {
         auto item = *path;
         if (item.empty())
             continue;
@@ -286,7 +273,8 @@ std::pair<fs::dentry_pointer, int> fs::open(const fs_context& context, dentry* _
                 return {nullptr, ret};
             linkpath[ret] = 0;
 
-            std::tie(cwd, ret) = fs::open(context, cwd->parent, linkpath, true, recurs_no + 1);
+            std::tie(cwd, ret) =
+                fs::open(context, cwd->parent, linkpath, true, recurs_no + 1);
             if (!cwd || ret)
                 return {nullptr, ret};
         }
@@ -319,101 +307,89 @@ std::pair<fs::dentry_pointer, int> fs::open(const fs_context& context, dentry* _
             return {nullptr, ret};
         linkpath[ret] = 0;
 
-        return fs::open(context, cwd->parent, linkpath, true, recurs_no+1);
+        return fs::open(context, cwd->parent, linkpath, true, recurs_no + 1);
     }
 
     return {std::move(cwd), 0};
 }
 
-int fs::statx(struct inode* inode, struct statx* stat, unsigned int mask)
-{
+int fs::statx(struct inode* inode, struct statx* stat, unsigned int mask) {
     assert(inode && inode->fs);
     return inode->fs->statx(inode, stat, mask);
 }
 
-int fs::truncate(struct inode *file, size_t size)
-{
+int fs::truncate(struct inode* file, size_t size) {
     assert(file && file->fs);
     return file->fs->truncate(file, size);
 }
 
-int fs::readlink(struct inode* inode, char* buf, size_t size)
-{
+int fs::readlink(struct inode* inode, char* buf, size_t size) {
     assert(inode && inode->fs);
     return inode->fs->readlink(inode, buf, size);
 }
 
-int fs::symlink(struct dentry* at, const char* target)
-{
+int fs::symlink(struct dentry* at, const char* target) {
     assert(at && at->parent && at->parent->fs);
     return at->parent->fs->symlink(at->parent->inode, at, target);
 }
 
-int fs::unlink(struct dentry* at)
-{
+int fs::unlink(struct dentry* at) {
     assert(at && at->parent && at->parent->fs);
     return at->parent->fs->unlink(at->parent->inode, at);
 }
 
-int fs::mknod(struct dentry* at, mode_t mode, dev_t dev)
-{
+int fs::mknod(struct dentry* at, mode_t mode, dev_t dev) {
     assert(at && at->parent && at->parent->fs);
     return at->parent->fs->mknod(at->parent->inode, at, mode, dev);
 }
 
-int fs::creat(struct dentry* at, mode_t mode)
-{
+int fs::creat(struct dentry* at, mode_t mode) {
     assert(at && at->parent && at->parent->fs);
     return at->parent->fs->creat(at->parent->inode, at, mode);
 }
 
 int fs::mount(struct dentry* mnt, const char* source, const char* mount_point,
-        const char* fstype, unsigned long flags, const void *data)
-{
+              const char* fstype, unsigned long flags, const void* data) {
     assert(mnt && mnt->fs);
     return mnt->fs->mount(mnt, source, mount_point, fstype, flags, data);
 }
 
-int fs::mkdir(struct dentry* at, mode_t mode)
-{
+int fs::mkdir(struct dentry* at, mode_t mode) {
     assert(at && at->parent && at->parent->fs);
     return at->parent->fs->mkdir(at->parent->inode, at, mode);
 }
 
 int mount(dentry* mnt, const char* source, const char* mount_point,
-        const char* fstype, unsigned long flags, const void *data)
-{
+          const char* fstype, unsigned long flags, const void* data) {
     assert(mnt && mnt->fs);
     return mnt->fs->mount(mnt, source, mount_point, fstype, flags, data);
 }
 
-int fs::register_block_device(dev_t node, const fs::blkdev_ops& ops)
-{
+int fs::register_block_device(dev_t node, const fs::blkdev_ops& ops) {
     int major = NODE_MAJOR(node);
     int minor = NODE_MINOR(node);
 
     if (!blkdevs[major])
-        blkdevs[major] = new blkdev_ops*[256] {};
+        blkdevs[major] = new blkdev_ops* [256] {};
 
     if (blkdevs[major][minor])
         return -EEXIST;
 
-    blkdevs[major][minor] = new blkdev_ops { ops };
+    blkdevs[major][minor] = new blkdev_ops{ops};
     return 0;
 }
 
-int fs::register_char_device(dev_t node, const fs::chrdev_ops& ops)
-{
+int fs::register_char_device(dev_t node, const fs::chrdev_ops& ops) {
     int major = NODE_MAJOR(node);
     int minor = NODE_MINOR(node);
 
     if (!chrdevs[major])
-        chrdevs[major] = new chrdev_ops*[256] {};
+        chrdevs[major] = new chrdev_ops* [256] {};
 
     if (chrdevs[major][minor])
         return -EEXIST;
 
-    chrdevs[major][minor] = new chrdev_ops { ops };
+    chrdevs[major][minor] = new chrdev_ops{ops};
     return 0;
 }
 
@@ -437,8 +413,7 @@ struct PACKED mbr {
 };
 
 // TODO: devtmpfs
-static int mbr_part_probe(dev_t node)
-{
+static int mbr_part_probe(dev_t node) {
     mbr buf_mbr;
 
     int ret = fs::block_device_read(node, (char*)&buf_mbr, sizeof(mbr), 0, 512);
@@ -456,16 +431,17 @@ static int mbr_part_probe(dev_t node)
         std::size_t part_offset = part.lba_start * 512;
 
         // TODO: add partition offset limit
-        fs::register_block_device(node + n, {
-            [=](char* buf, size_t buf_size, size_t offset, size_t n) -> ssize_t {
-                offset += part_offset;
-                return fs::block_device_read(node, buf, buf_size, offset, n);
-            },
-            [=](const char* buf, size_t offset, size_t n) -> ssize_t {
-                offset += part_offset;
-                return fs::block_device_write(node, buf, offset, n);
-            }
-        });
+        fs::register_block_device(
+            node + n,
+            {[=](char* buf, size_t buf_size, size_t offset,
+                 size_t n) -> ssize_t {
+                 offset += part_offset;
+                 return fs::block_device_read(node, buf, buf_size, offset, n);
+             },
+             [=](const char* buf, size_t offset, size_t n) -> ssize_t {
+                 offset += part_offset;
+                 return fs::block_device_write(node, buf, offset, n);
+             }});
 
         ++n;
     }
@@ -473,8 +449,7 @@ static int mbr_part_probe(dev_t node)
     return 0;
 }
 
-void fs::partprobe()
-{
+void fs::partprobe() {
     for (int i = 0; i < 256; i += 16) {
         int ret = mbr_part_probe(make_device(8, i));
 
@@ -485,8 +460,8 @@ void fs::partprobe()
     }
 }
 
-ssize_t fs::block_device_read(dev_t node, char* buf, size_t buf_size, size_t offset, size_t n)
-{
+ssize_t fs::block_device_read(dev_t node, char* buf, size_t buf_size,
+                              size_t offset, size_t n) {
     int major = NODE_MAJOR(node);
     int minor = NODE_MINOR(node);
 
@@ -500,8 +475,8 @@ ssize_t fs::block_device_read(dev_t node, char* buf, size_t buf_size, size_t off
     return read(buf, buf_size, offset, n);
 }
 
-ssize_t fs::block_device_write(dev_t node, const char* buf, size_t offset, size_t n)
-{
+ssize_t fs::block_device_write(dev_t node, const char* buf, size_t offset,
+                               size_t n) {
     int major = NODE_MAJOR(node);
     int minor = NODE_MINOR(node);
 
@@ -515,8 +490,7 @@ ssize_t fs::block_device_write(dev_t node, const char* buf, size_t offset, size_
     return write(buf, offset, n);
 }
 
-ssize_t fs::char_device_read(dev_t node, char* buf, size_t buf_size, size_t n)
-{
+ssize_t fs::char_device_read(dev_t node, char* buf, size_t buf_size, size_t n) {
     int major = NODE_MAJOR(node);
     int minor = NODE_MINOR(node);
 
@@ -530,8 +504,7 @@ ssize_t fs::char_device_read(dev_t node, char* buf, size_t buf_size, size_t n)
     return read(buf, buf_size, n);
 }
 
-ssize_t fs::char_device_write(dev_t node, const char* buf, size_t n)
-{
+ssize_t fs::char_device_write(dev_t node, const char* buf, size_t n) {
     int major = NODE_MAJOR(node);
     int minor = NODE_MINOR(node);
 
@@ -545,23 +518,19 @@ ssize_t fs::char_device_write(dev_t node, const char* buf, size_t n)
     return write(buf, n);
 }
 
-ssize_t b_null_read(char*, size_t, size_t)
-{
+ssize_t b_null_read(char*, size_t, size_t) {
     return 0;
 }
 
-ssize_t b_null_write(const char*, size_t n)
-{
+ssize_t b_null_write(const char*, size_t n) {
     return n;
 }
 
-static ssize_t console_read(char* buf, size_t buf_size, size_t n)
-{
+static ssize_t console_read(char* buf, size_t buf_size, size_t n) {
     return kernel::tty::console->read(buf, buf_size, n);
 }
 
-static ssize_t console_write(const char* buf, size_t n)
-{
+static ssize_t console_write(const char* buf, size_t n) {
     size_t orig_n = n;
     while (n--)
         kernel::tty::console->putchar(*(buf++));
@@ -569,28 +538,21 @@ static ssize_t console_write(const char* buf, size_t n)
     return orig_n;
 }
 
-fs::pipe::pipe(void)
-    : buf { PIPE_SIZE }
-    , flags { READABLE | WRITABLE }
-{
-}
+fs::pipe::pipe(void) : buf{PIPE_SIZE}, flags{READABLE | WRITABLE} {}
 
-void fs::pipe::close_read(void)
-{
+void fs::pipe::close_read(void) {
     kernel::async::lock_guard lck{mtx};
     flags &= (~READABLE);
     waitlist_w.notify_all();
 }
 
-void fs::pipe::close_write(void)
-{
+void fs::pipe::close_write(void) {
     kernel::async::lock_guard lck{mtx};
     flags &= (~WRITABLE);
     waitlist_r.notify_all();
 }
 
-int fs::pipe::write(const char* buf, size_t n)
-{
+int fs::pipe::write(const char* buf, size_t n) {
     // TODO: check privilege
     // TODO: check EPIPE
     kernel::async::lock_guard lck{mtx};
@@ -647,8 +609,7 @@ int fs::pipe::write(const char* buf, size_t n)
     return orig_n - n;
 }
 
-int fs::pipe::read(char* buf, size_t n)
-{
+int fs::pipe::read(char* buf, size_t n) {
     // TODO: check privilege
     kernel::async::lock_guard lck{mtx};
     size_t orig_n = n;
@@ -672,14 +633,13 @@ int fs::pipe::read(char* buf, size_t n)
 }
 
 SECTION(".text.kinit")
-void init_vfs(void)
-{
+void init_vfs(void) {
     using namespace fs;
     // null
-    register_char_device(make_device(1, 0), { b_null_read, b_null_write });
+    register_char_device(make_device(1, 0), {b_null_read, b_null_write});
     // console (supports serial console only for now)
     // TODO: add interface to bind console device to other devices
-    register_char_device(make_device(2, 0), { console_read, console_write });
+    register_char_device(make_device(2, 0), {console_read, console_write});
 
     // register tmpfs
     fs::register_tmpfs();

+ 29 - 43
src/kernel/vfs/dentry.cc

@@ -12,48 +12,41 @@
 using namespace fs;
 using types::hash_t, types::hash_str, types::hash_ptr;
 
-static inline struct dentry* __d_parent(struct dentry* dentry)
-{
+static inline struct dentry* __d_parent(struct dentry* dentry) {
     if (dentry->parent)
         return dentry->parent;
     return dentry;
 }
 
-static inline bool __d_is_present(struct dentry* dentry)
-{
+static inline bool __d_is_present(struct dentry* dentry) {
     return dentry->flags & D_PRESENT;
 }
 
-static inline bool __d_is_dir(struct dentry* dentry)
-{
+static inline bool __d_is_dir(struct dentry* dentry) {
     return dentry->flags & D_DIRECTORY;
 }
 
-static inline bool __d_is_loaded(struct dentry* dentry)
-{
+static inline bool __d_is_loaded(struct dentry* dentry) {
     return dentry->flags & D_LOADED;
 }
 
-static inline bool __d_equal(struct dentry* dentry, struct dentry* parent, types::string_view name)
-{
+static inline bool __d_equal(struct dentry* dentry, struct dentry* parent,
+                             types::string_view name) {
     return dentry->parent == parent && dentry->name == name;
 }
 
-static inline hash_t __d_hash(struct dentry* parent, types::string_view name)
-{
+static inline hash_t __d_hash(struct dentry* parent, types::string_view name) {
     assert(parent && parent->cache);
     int bits = parent->cache->hash_bits;
 
     return hash_str(name, bits) ^ hash_ptr(parent, bits);
 }
 
-static inline struct dentry*& __d_first(struct dcache* cache, hash_t hash)
-{
+static inline struct dentry*& __d_first(struct dcache* cache, hash_t hash) {
     return cache->arr[hash & ((1 << cache->hash_bits) - 1)];
 }
 
-static inline void __d_add(struct dentry* parent, struct dentry* dentry)
-{
+static inline void __d_add(struct dentry* parent, struct dentry* dentry) {
     assert(!dentry->parent);
     assert(parent->refcount && dentry->refcount);
 
@@ -65,13 +58,14 @@ static inline void __d_add(struct dentry* parent, struct dentry* dentry)
     parent->cache->size++;
 }
 
-static inline struct dentry* __d_find_fast(struct dentry* parent, types::string_view name)
-{
+static inline struct dentry* __d_find_fast(struct dentry* parent,
+                                           types::string_view name) {
     auto* cache = parent->cache;
     assert(cache);
 
     hash_t hash = __d_hash(parent, name);
-    for (struct dentry* dentry = __d_first(cache, hash); dentry; dentry = dentry->next) {
+    for (struct dentry* dentry = __d_first(cache, hash); dentry;
+         dentry = dentry->next) {
         if (!__d_equal(dentry, parent, name))
             continue;
 
@@ -81,8 +75,7 @@ static inline struct dentry* __d_find_fast(struct dentry* parent, types::string_
     return nullptr;
 }
 
-static inline int __d_load(struct dentry* parent)
-{
+static inline int __d_load(struct dentry* parent) {
     if (__d_is_loaded(parent))
         return 0;
 
@@ -98,7 +91,8 @@ static inline int __d_load(struct dentry* parent)
 
     size_t offset = 0;
     while (true) {
-        ssize_t off = fs->readdir(inode, offset,
+        ssize_t off = fs->readdir(
+            inode, offset,
             [parent](const char* fn, struct inode* inode, uint8_t mode) -> int {
                 struct dentry* dentry = dcache_alloc(parent->cache);
 
@@ -129,8 +123,8 @@ static inline int __d_load(struct dentry* parent)
     return 0;
 }
 
-std::pair<struct dentry*, int> fs::d_find(struct dentry* parent, types::string_view name)
-{
+std::pair<struct dentry*, int> fs::d_find(struct dentry* parent,
+                                          types::string_view name) {
     assert(__d_is_present(parent));
     if (!__d_is_dir(parent))
         return {nullptr, -ENOTDIR};
@@ -165,8 +159,7 @@ std::pair<struct dentry*, int> fs::d_find(struct dentry* parent, types::string_v
     return {ret, 0};
 }
 
-std::string fs::d_path(const struct dentry* dentry, const struct dentry* root)
-{
+std::string fs::d_path(const struct dentry* dentry, const struct dentry* root) {
     const struct dentry* dents[32];
     int cnt = 0;
 
@@ -186,55 +179,48 @@ std::string fs::d_path(const struct dentry* dentry, const struct dentry* root)
     return ret;
 }
 
-dentry_pointer fs::d_get(const dentry_pointer& dentry)
-{
+dentry_pointer fs::d_get(const dentry_pointer& dentry) {
     return d_get(dentry.get());
 }
 
-struct dentry* fs::d_get(struct dentry* dentry)
-{
+struct dentry* fs::d_get(struct dentry* dentry) {
     assert(dentry);
     ++dentry->refcount;
     return dentry;
 }
 
-struct dentry* fs::d_put(struct dentry* dentry)
-{
+struct dentry* fs::d_put(struct dentry* dentry) {
     assert(dentry);
 
     // TODO: if refcount is zero, mark dentry as unused
     --dentry->refcount;
-    return dentry;;
+    return dentry;
+    ;
 }
 
-void dentry_deleter::operator()(struct dentry* dentry) const
-{
+void dentry_deleter::operator()(struct dentry* dentry) const {
     fs::d_put(dentry);
 }
 
-void fs::dcache_init(struct dcache* cache, int hash_bits)
-{
+void fs::dcache_init(struct dcache* cache, int hash_bits) {
     cache->hash_bits = hash_bits;
     cache->arr = new struct dentry*[1 << hash_bits]();
     cache->size = 0;
 }
 
-void fs::dcache_drop(struct dcache* cache)
-{
+void fs::dcache_drop(struct dcache* cache) {
     assert(cache->size == 0);
     delete[] cache->arr;
 }
 
-struct dentry* fs::dcache_alloc(struct dcache* cache)
-{
+struct dentry* fs::dcache_alloc(struct dcache* cache) {
     struct dentry* dentry = new struct dentry();
     dentry->cache = cache;
 
     return d_get(dentry);
 }
 
-void fs::dcache_init_root(struct dcache* cache, struct dentry* root)
-{
+void fs::dcache_init_root(struct dcache* cache, struct dentry* root) {
     assert(cache->size == 0);
 
     root->prev = root->next = nullptr;

+ 34 - 62
src/kernel/vfs/filearr.cc

@@ -18,18 +18,15 @@ struct fditem {
 };
 
 struct fditem_comparator {
-    constexpr bool operator()(const fditem& lhs, const fditem& rhs) const
-    {
+    constexpr bool operator()(const fditem& lhs, const fditem& rhs) const {
         return lhs.fd < rhs.fd;
     }
 
-    constexpr bool operator()(int fd, const fditem& rhs) const
-    {
+    constexpr bool operator()(int fd, const fditem& rhs) const {
         return fd < rhs.fd;
     }
 
-    constexpr bool operator()(const fditem& lhs, int fd) const
-    {
+    constexpr bool operator()(const fditem& lhs, int fd) const {
         return lhs.fd < fd;
     }
 };
@@ -50,8 +47,7 @@ struct filearray::impl {
     int place_new_file(std::shared_ptr<file> pfile, int flags);
 };
 
-int filearray::impl::allocate_fd(int from)
-{
+int filearray::impl::allocate_fd(int from) {
     if (from < min_avail)
         from = min_avail;
 
@@ -74,19 +70,16 @@ int filearray::impl::allocate_fd(int from)
     return fd;
 }
 
-void filearray::impl::release_fd(int fd)
-{
+void filearray::impl::release_fd(int fd) {
     if (fd < min_avail)
         min_avail = fd;
 }
 
-int filearray::impl::next_fd()
-{
+int filearray::impl::next_fd() {
     return allocate_fd(min_avail);
 }
 
-int filearray::impl::do_dup(const fditem& oldfile, int new_fd, int flags)
-{
+int filearray::impl::do_dup(const fditem& oldfile, int new_fd, int flags) {
     bool inserted;
     std::tie(std::ignore, inserted) = arr.emplace(new_fd, flags, oldfile.pfile);
     assert(inserted);
@@ -94,8 +87,7 @@ int filearray::impl::do_dup(const fditem& oldfile, int new_fd, int flags)
     return new_fd;
 }
 
-int filearray::impl::place_new_file(std::shared_ptr<file> pfile, int flags)
-{
+int filearray::impl::place_new_file(std::shared_ptr<file> pfile, int flags) {
     int fd = next_fd();
 
     bool inserted;
@@ -105,8 +97,7 @@ int filearray::impl::place_new_file(std::shared_ptr<file> pfile, int flags)
     return fd;
 }
 
-int filearray::dup(int old_fd)
-{
+int filearray::dup(int old_fd) {
     lock_guard lck{pimpl->mtx};
 
     auto iter = pimpl->arr.find(old_fd);
@@ -117,8 +108,7 @@ int filearray::dup(int old_fd)
     return pimpl->do_dup(*iter, fd, 0);
 }
 
-int filearray::dup(int old_fd, int new_fd, int flags)
-{
+int filearray::dup(int old_fd, int new_fd, int flags) {
     lock_guard lck{pimpl->mtx};
 
     auto iter_old = pimpl->arr.find(old_fd);
@@ -138,8 +128,7 @@ int filearray::dup(int old_fd, int new_fd, int flags)
     return pimpl->do_dup(*iter_old, fd, flags);
 }
 
-int filearray::dupfd(int fd, int min_fd, int flags)
-{
+int filearray::dupfd(int fd, int min_fd, int flags) {
     lock_guard lck{pimpl->mtx};
 
     auto iter = pimpl->arr.find(fd);
@@ -150,8 +139,7 @@ int filearray::dupfd(int fd, int min_fd, int flags)
     return pimpl->do_dup(*iter, new_fd, flags);
 }
 
-int filearray::set_flags(int fd, int flags)
-{
+int filearray::set_flags(int fd, int flags) {
     lock_guard lck{pimpl->mtx};
 
     auto iter = pimpl->arr.find(fd);
@@ -162,8 +150,7 @@ int filearray::set_flags(int fd, int flags)
     return 0;
 }
 
-int filearray::close(int fd)
-{
+int filearray::close(int fd) {
     lock_guard lck{pimpl->mtx};
 
     auto iter = pimpl->arr.find(fd);
@@ -176,10 +163,10 @@ int filearray::close(int fd)
     return 0;
 }
 
-static inline std::pair<dentry_pointer, int>
-_open_file(const fs_context& context, dentry* cwd, types::path_iterator filepath, int flags, mode_t mode)
-{
-    auto [ dent, ret ] = fs::open(context, cwd, filepath);
+static inline std::pair<dentry_pointer, int> _open_file(
+    const fs_context& context, dentry* cwd, types::path_iterator filepath,
+    int flags, mode_t mode) {
+    auto [dent, ret] = fs::open(context, cwd, filepath);
     if (!dent)
         return {nullptr, ret};
 
@@ -200,8 +187,8 @@ _open_file(const fs_context& context, dentry* cwd, types::path_iterator filepath
 }
 
 // TODO: file opening permissions check
-int filearray::open(dentry* cwd, types::path_iterator filepath, int flags, mode_t mode)
-{
+int filearray::open(dentry* cwd, types::path_iterator filepath, int flags,
+                    mode_t mode) {
     lock_guard lck{pimpl->mtx};
 
     auto [dent, ret] = _open_file(*pimpl->context, cwd, filepath, flags, mode);
@@ -238,46 +225,35 @@ int filearray::open(dentry* cwd, types::path_iterator filepath, int flags, mode_
     }
 
     return pimpl->place_new_file(
-        std::make_shared<regular_file>(fflags, 0, dent->inode),
-        fdflag);
+        std::make_shared<regular_file>(fflags, 0, dent->inode), fdflag);
 }
 
-int filearray::pipe(int (&pipefd)[2])
-{
+int filearray::pipe(int (&pipefd)[2]) {
     lock_guard lck{pimpl->mtx};
 
     if (1) {
-        std::shared_ptr<fs::pipe> ppipe { new fs::pipe };
+        std::shared_ptr<fs::pipe> ppipe{new fs::pipe};
 
         pipefd[0] = pimpl->place_new_file(
-            std::make_shared<fifo_file>(
-                file::file_flags { 1, 0, 0 }, ppipe),
-            0);
+            std::make_shared<fifo_file>(file::file_flags{1, 0, 0}, ppipe), 0);
 
         pipefd[1] = pimpl->place_new_file(
-            std::make_shared<fifo_file>(
-                file::file_flags { 0, 1, 0 }, ppipe),
-            0);
+            std::make_shared<fifo_file>(file::file_flags{0, 1, 0}, ppipe), 0);
     }
 
     return 0;
 }
 
-filearray::filearray(std::shared_ptr<impl> ptr)
-    : pimpl { ptr }
-{
-}
+filearray::filearray(std::shared_ptr<impl> ptr) : pimpl{ptr} {}
 
 filearray::filearray(const fs_context* context)
-    : filearray { std::make_shared<impl>() }
-{
+    : filearray{std::make_shared<impl>()} {
     pimpl->context = context;
 }
 
-filearray filearray::copy() const
-{
-    lock_guard lck { pimpl->mtx };
-    filearray ret { pimpl->context };
+filearray filearray::copy() const {
+    lock_guard lck{pimpl->mtx};
+    filearray ret{pimpl->context};
 
     ret.pimpl->min_avail = pimpl->min_avail;
     ret.pimpl->arr = pimpl->arr;
@@ -285,18 +261,15 @@ filearray filearray::copy() const
     return ret;
 }
 
-filearray filearray::share() const
-{
-    return filearray { pimpl };
+filearray filearray::share() const {
+    return filearray{pimpl};
 }
 
-void filearray::clear()
-{
+void filearray::clear() {
     pimpl.reset();
 }
 
-void filearray::onexec()
-{
+void filearray::onexec() {
     lock_guard lck{pimpl->mtx};
 
     for (auto iter = pimpl->arr.begin(); iter;) {
@@ -309,8 +282,7 @@ void filearray::onexec()
     }
 }
 
-file* filearray::operator[](int i) const
-{
+file* filearray::operator[](int i) const {
     lock_guard lck{pimpl->mtx};
 
     auto iter = pimpl->arr.find(i);

+ 3 - 5
src/kernel/vfs/inode.cc

@@ -5,8 +5,7 @@
 
 using namespace fs;
 
-int vfs::statx(inode* ind, struct statx* st, unsigned int mask)
-{
+int vfs::statx(inode* ind, struct statx* st, unsigned int mask) {
     st->stx_mask = 0;
 
     if (mask & STATX_NLINK) {
@@ -64,7 +63,7 @@ int vfs::statx(inode* ind, struct statx* st, unsigned int mask)
     }
 
     if (mask & STATX_BLOCKS) {
-        st->stx_blocks = (ind->size + 512-1) / 512;
+        st->stx_blocks = (ind->size + 512 - 1) / 512;
         st->stx_blksize = io_blksize();
         st->stx_mask |= STATX_BLOCKS;
     }
@@ -88,7 +87,6 @@ int vfs::statx(inode* ind, struct statx* st, unsigned int mask)
     return 0;
 }
 
-dev_t vfs::i_device(inode*)
-{
+dev_t vfs::i_device(inode*) {
     return -ENODEV;
 }

+ 32 - 44
src/kernel/vfs/tmpfs.cc

@@ -16,35 +16,31 @@ struct tmpfs_file_entry {
 };
 
 class tmpfs : public virtual vfs {
-private:
+   private:
     using fe_t = tmpfs_file_entry;
     using vfe_t = std::vector<fe_t>;
     using fdata_t = std::vector<char>;
 
-private:
+   private:
     ino_t m_next_ino;
 
-private:
-    ino_t assign_ino()
-    {
-        return m_next_ino++;
-    }
+   private:
+    ino_t assign_ino() { return m_next_ino++; }
 
-protected:
+   protected:
     inline vfe_t* make_vfe() { return new vfe_t{}; }
     inline fdata_t* make_fdata() { return new fdata_t{}; }
 
-    void mklink(inode* dir, inode* ind, std::string filename)
-    {
+    void mklink(inode* dir, inode* ind, std::string filename) {
         auto& fes = *(vfe_t*)dir->fs_data;
-        fes.emplace_back(fe_t { ind->ino, std::move(filename) });
+        fes.emplace_back(fe_t{ind->ino, std::move(filename)});
 
         dir->size += sizeof(fe_t);
         ++ind->nlink;
     }
 
-    virtual ssize_t readdir(inode* dir, size_t offset, const vfs::filldir_func& filldir) override
-    {
+    virtual ssize_t readdir(inode* dir, size_t offset,
+                            const vfs::filldir_func& filldir) override {
         if (!S_ISDIR(dir->mode))
             return -ENOTDIR;
 
@@ -66,11 +62,8 @@ protected:
         return nread;
     }
 
-public:
-    explicit tmpfs()
-        : vfs(make_device(0, 2), 4096)
-        , m_next_ino{1}
-    {
+   public:
+    explicit tmpfs() : vfs(make_device(0, 2), 4096), m_next_ino{1} {
         auto* in = alloc_inode(assign_ino());
 
         in->fs_data = make_vfe();
@@ -82,8 +75,8 @@ public:
         register_root_node(in);
     }
 
-    virtual ssize_t read(struct inode* file, char* buf, size_t buf_size, size_t count, off_t offset) override
-    {
+    virtual ssize_t read(struct inode* file, char* buf, size_t buf_size,
+                         size_t count, off_t offset) override {
         if (!S_ISREG(file->mode))
             return -EINVAL;
 
@@ -102,15 +95,15 @@ public:
         return count;
     }
 
-    virtual ssize_t write(struct inode* file, const char* buf, size_t count, off_t offset) override
-    {
+    virtual ssize_t write(struct inode* file, const char* buf, size_t count,
+                          off_t offset) override {
         if (!S_ISREG(file->mode))
             return -EINVAL;
 
         auto* data = (fdata_t*)file->fs_data;
 
         if (data->size() < offset + count)
-            data->resize(offset+count);
+            data->resize(offset + count);
         memcpy(data->data() + offset, buf, count);
 
         file->size = data->size();
@@ -118,8 +111,8 @@ public:
         return count;
     }
 
-    virtual int creat(struct inode* dir, struct dentry* at, mode_t mode) override
-    {
+    virtual int creat(struct inode* dir, struct dentry* at,
+                      mode_t mode) override {
         if (!S_ISDIR(dir->mode))
             return -ENOTDIR;
         assert(at->parent && at->parent->inode == dir);
@@ -135,8 +128,8 @@ public:
         return 0;
     }
 
-    virtual int mknod(struct inode* dir, struct dentry* at, mode_t mode, dev_t dev) override
-    {
+    virtual int mknod(struct inode* dir, struct dentry* at, mode_t mode,
+                      dev_t dev) override {
         if (!S_ISDIR(dir->mode))
             return -ENOTDIR;
         assert(at->parent && at->parent->inode == dir);
@@ -158,8 +151,8 @@ public:
         return 0;
     }
 
-    virtual int mkdir(struct inode* dir, struct dentry* at, mode_t mode) override
-    {
+    virtual int mkdir(struct inode* dir, struct dentry* at,
+                      mode_t mode) override {
         if (!S_ISDIR(dir->mode))
             return -ENOTDIR;
         assert(at->parent && at->parent->inode == dir);
@@ -178,8 +171,8 @@ public:
         return 0;
     }
 
-    virtual int symlink(struct inode* dir, struct dentry* at, const char* target) override
-    {
+    virtual int symlink(struct inode* dir, struct dentry* at,
+                        const char* target) override {
         if (!S_ISDIR(dir->mode))
             return -ENOTDIR;
         assert(at->parent && at->parent->inode == dir);
@@ -200,8 +193,8 @@ public:
         return 0;
     }
 
-    virtual int readlink(struct inode* file, char* buf, size_t buf_size) override
-    {
+    virtual int readlink(struct inode* file, char* buf,
+                         size_t buf_size) override {
         if (!S_ISLNK(file->mode))
             return -EINVAL;
 
@@ -215,8 +208,7 @@ public:
         return size;
     }
 
-    virtual int unlink(struct inode* dir, struct dentry* at) override
-    {
+    virtual int unlink(struct inode* dir, struct dentry* at) override {
         if (!S_ISDIR(dir->mode))
             return -ENOTDIR;
         assert(at->parent && at->parent->inode == dir);
@@ -224,7 +216,7 @@ public:
         auto* vfe = (vfe_t*)dir->fs_data;
         assert(vfe);
 
-        for (auto iter = vfe->begin(); iter != vfe->end(); ) {
+        for (auto iter = vfe->begin(); iter != vfe->end();) {
             if (iter->ino != at->inode->ino) {
                 ++iter;
                 continue;
@@ -254,15 +246,13 @@ public:
         return -EIO;
     }
 
-    virtual dev_t i_device(inode* file) override
-    {
+    virtual dev_t i_device(inode* file) override {
         if (file->mode & S_IFMT & (S_IFBLK | S_IFCHR))
             return (dev_t)(uintptr_t)file->fs_data;
         return -ENODEV;
     }
 
-    virtual int truncate(inode* file, size_t size) override
-    {
+    virtual int truncate(inode* file, size_t size) override {
         if (!S_ISREG(file->mode))
             return -EINVAL;
 
@@ -273,14 +263,12 @@ public:
     }
 };
 
-static tmpfs* create_tmpfs(const char*, unsigned long, const void*)
-{
+static tmpfs* create_tmpfs(const char*, unsigned long, const void*) {
     // TODO: flags
     return new tmpfs;
 }
 
-int fs::register_tmpfs()
-{
+int fs::register_tmpfs() {
     fs::register_fs("tmpfs", {create_tmpfs});
     return 0;
 }

+ 29 - 49
src/kernel/vfs/vfs.cc

@@ -10,27 +10,24 @@ using namespace fs;
 
 static std::map<std::string, fs::create_fs_func_t> fs_list;
 
-int fs::register_fs(const char* name, fs::create_fs_func_t func)
-{
+int fs::register_fs(const char* name, fs::create_fs_func_t func) {
     fs_list.emplace(name, func);
 
     return 0;
 }
 
 vfs::vfs(dev_t device, size_t io_blksize)
-    : m_device(device), m_io_blksize(io_blksize)
-{
+    : m_device(device), m_io_blksize(io_blksize) {
     dcache_init(&m_dcache, 8);
 }
 
-std::pair<vfs*, int> vfs::create(const char* source,
-    const char* fstype, unsigned long flags, const void* data)
-{
+std::pair<vfs*, int> vfs::create(const char* source, const char* fstype,
+                                 unsigned long flags, const void* data) {
     auto iter = fs_list.find(fstype);
     if (!iter)
         return {nullptr, -ENODEV};
 
-    auto& [ _, func ] = *iter;
+    auto& [_, func] = *iter;
 
     if (!(flags & MS_NOATIME))
         flags |= MS_RELATIME;
@@ -41,8 +38,7 @@ std::pair<vfs*, int> vfs::create(const char* source,
     return {func(source, flags, data), 0};
 }
 
-fs::inode* vfs::alloc_inode(ino_t ino)
-{
+fs::inode* vfs::alloc_inode(ino_t ino) {
     auto [iter, inserted] = m_inodes.try_emplace(ino);
     iter->second.ino = ino;
     iter->second.fs = this;
@@ -51,14 +47,12 @@ fs::inode* vfs::alloc_inode(ino_t ino)
     return &iter->second;
 }
 
-void vfs::free_inode(ino_t ino)
-{
+void vfs::free_inode(ino_t ino) {
     int n = m_inodes.erase(ino);
     assert(n == 1);
 }
 
-fs::inode* vfs::get_inode(ino_t ino)
-{
+fs::inode* vfs::get_inode(ino_t ino) {
     auto iter = m_inodes.find(ino);
     // TODO: load inode from disk if not found
     if (iter)
@@ -67,8 +61,7 @@ fs::inode* vfs::get_inode(ino_t ino)
         return nullptr;
 }
 
-void vfs::register_root_node(struct inode* root_inode)
-{
+void vfs::register_root_node(struct inode* root_inode) {
     assert(!root());
 
     m_root = fs::dcache_alloc(&m_dcache);
@@ -81,8 +74,7 @@ void vfs::register_root_node(struct inode* root_inode)
 }
 
 int vfs::mount(dentry* mnt, const char* source, const char* mount_point,
-        const char* fstype, unsigned long flags, const void *data)
-{
+               const char* fstype, unsigned long flags, const void* data) {
     if (!(mnt->flags & D_DIRECTORY))
         return -ENOTDIR;
 
@@ -90,13 +82,13 @@ int vfs::mount(dentry* mnt, const char* source, const char* mount_point,
     if (ret != 0)
         return ret;
 
-    mounts.emplace(d_get(mnt), mount_data {
-                            .fs = new_fs,
-                            .source = source,
-                            .mount_point = mount_point,
-                            .fstype = fstype,
-                            .flags = flags,
-                        });
+    mounts.emplace(d_get(mnt), mount_data{
+                                   .fs = new_fs,
+                                   .source = source,
+                                   .mount_point = mount_point,
+                                   .fstype = fstype,
+                                   .flags = flags,
+                               });
     mnt->flags |= D_MOUNTPOINT;
 
     auto* new_ent = new_fs->root();
@@ -112,62 +104,50 @@ int vfs::mount(dentry* mnt, const char* source, const char* mount_point,
 // return -EINVAL to show that the operation
 // is not supported by the fs
 
-ssize_t vfs::read(inode*, char*, size_t, size_t, off_t)
-{
+ssize_t vfs::read(inode*, char*, size_t, size_t, off_t) {
     return -EINVAL;
 }
 
-ssize_t vfs::write(inode*, const char*, size_t, off_t)
-{
+ssize_t vfs::write(inode*, const char*, size_t, off_t) {
     return -EINVAL;
 }
 
-int vfs::creat(inode*, dentry*, mode_t)
-{
+int vfs::creat(inode*, dentry*, mode_t) {
     return -EINVAL;
 }
 
-int vfs::mknod(inode*, dentry*, mode_t, dev_t)
-{
+int vfs::mknod(inode*, dentry*, mode_t, dev_t) {
     return -EINVAL;
 }
 
-int vfs::unlink(inode*, dentry*)
-{
+int vfs::unlink(inode*, dentry*) {
     return -EINVAL;
 }
 
-int vfs::mkdir(inode*, dentry*, mode_t)
-{
+int vfs::mkdir(inode*, dentry*, mode_t) {
     return -EINVAL;
 }
 
-int vfs::symlink(inode*, dentry*, const char*)
-{
+int vfs::symlink(inode*, dentry*, const char*) {
     return -EINVAL;
 }
 
-int vfs::readlink(inode*, char*, size_t)
-{
+int vfs::readlink(inode*, char*, size_t) {
     return -EINVAL;
 }
 
-int vfs::truncate(inode*, size_t)
-{
+int vfs::truncate(inode*, size_t) {
     return -EINVAL;
 }
 
-struct dentry* vfs::root() const noexcept
-{
+struct dentry* vfs::root() const noexcept {
     return m_root;
 }
 
-dev_t vfs::fs_device() const noexcept
-{
+dev_t vfs::fs_device() const noexcept {
     return m_device;
 }
 
-size_t vfs::io_blksize() const noexcept
-{
+size_t vfs::io_blksize() const noexcept {
     return m_io_blksize;
 }

+ 16 - 20
src/kernel/vga.cpp

@@ -1,19 +1,18 @@
 #define _KERNEL_VGA_C_
 
-#include <kernel/vga.hpp>
 #include <stdint.h>
 #include <string.h>
 
+#include <kernel/vga.hpp>
+
 static struct vga_char* p_vga_head = VGA_MEM;
 
-static inline void vga_return()
-{
+static inline void vga_return() {
     const int32_t offset = p_vga_head - VGA_MEM;
     p_vga_head -= (offset % VGA_SCREEN_WIDTH_IN_CHARS);
 }
 
-static inline void vga_new_line()
-{
+static inline void vga_new_line() {
     int32_t offset = p_vga_head - VGA_MEM;
     offset %= VGA_SCREEN_WIDTH_IN_CHARS;
     p_vga_head += (VGA_SCREEN_WIDTH_IN_CHARS - offset);
@@ -22,8 +21,7 @@ static inline void vga_new_line()
     }
 }
 
-static inline void real_vga_put_char(struct vga_char* c)
-{
+static inline void real_vga_put_char(struct vga_char* c) {
     *p_vga_head = *c;
     ++p_vga_head;
     if ((p_vga_head - VGA_MEM) == 80 * 25) {
@@ -31,23 +29,21 @@ static inline void real_vga_put_char(struct vga_char* c)
     }
 }
 
-void vga_put_char(struct vga_char* c)
-{
+void vga_put_char(struct vga_char* c) {
     switch (c->c) {
-    case CR:
-        vga_return();
-        break;
-    case LF:
-        vga_new_line();
-        break;
-    default:
-        real_vga_put_char(c);
-        break;
+        case CR:
+            vga_return();
+            break;
+        case LF:
+            vga_new_line();
+            break;
+        default:
+            real_vga_put_char(c);
+            break;
     }
 }
 
-void vga_print(const char* str, uint8_t color)
-{
+void vga_print(const char* str, uint8_t color) {
     struct vga_char s_c;
     s_c.color = color;
     while ((s_c.c = *(str++)) != 0x00) {

+ 49 - 57
src/kinit.cpp

@@ -29,8 +29,7 @@ struct PACKED bootloader_data {
     uint32_t meminfo_64k_blocks;
 
     // meminfo entries
-    kernel::mem::e820_mem_map_entry
-        meminfo_entries[(1024-4*4)/24];
+    kernel::mem::e820_mem_map_entry meminfo_entries[(1024 - 4 * 4) / 24];
 };
 
 extern void init_vfs();
@@ -38,25 +37,22 @@ extern void init_vfs();
 namespace kernel::kinit {
 
 SECTION(".text.kinit")
-static inline void enable_sse()
-{
+static inline void enable_sse() {
     asm volatile(
-            "mov %%cr0, %%rax\n\t"
-            "and $(~0xc), %%rax\n\t"
-            "or $0x22, %%rax\n\t"
-            "mov %%rax, %%cr0\n\t"
-            "\n\t"
-            "mov %%cr4, %%rax\n\t"
-            "or $0x600, %%rax\n\t"
-            "mov %%rax, %%cr4\n\t"
-            "fninit\n\t"
-            ::: "rax"
-            );
+        "mov %%cr0, %%rax\n\t"
+        "and $(~0xc), %%rax\n\t"
+        "or $0x22, %%rax\n\t"
+        "mov %%rax, %%cr0\n\t"
+        "\n\t"
+        "mov %%cr4, %%rax\n\t"
+        "or $0x600, %%rax\n\t"
+        "mov %%rax, %%cr4\n\t"
+        "fninit\n\t" ::
+            : "rax");
 }
 
 SECTION(".text.kinit")
-static inline void set_uname()
-{
+static inline void set_uname() {
     kernel::sys_utsname = new new_utsname;
     strcpy(kernel::sys_utsname->sysname, "Linux"); // linux compatible
     strcpy(kernel::sys_utsname->nodename, "(none)");
@@ -67,8 +63,7 @@ static inline void set_uname()
 }
 
 SECTION(".text.kinit")
-void NORETURN real_kernel_init(mem::paging::pfn_t kernel_stack_pfn)
-{
+void NORETURN real_kernel_init(mem::paging::pfn_t kernel_stack_pfn) {
     // call global constructors
     // NOTE: the initializer of global objects MUST NOT contain
     // all kinds of memory allocations
@@ -90,8 +85,7 @@ void NORETURN real_kernel_init(mem::paging::pfn_t kernel_stack_pfn)
 }
 
 SECTION(".text.kinit")
-static inline void setup_early_kernel_page_table()
-{
+static inline void setup_early_kernel_page_table() {
     using namespace kernel::mem::paging;
 
     // remove temporary mapping
@@ -113,8 +107,7 @@ static inline void setup_early_kernel_page_table()
 }
 
 SECTION(".text.kinit")
-static inline void setup_buddy(uintptr_t addr_max)
-{
+static inline void setup_buddy(uintptr_t addr_max) {
     using namespace kernel::mem;
     using namespace kernel::mem::paging;
     constexpr auto idx = idx_all(0xffffff8040000000ULL);
@@ -132,7 +125,7 @@ static inline void setup_buddy(uintptr_t addr_max)
 
     auto pd = pdpte.parse();
     for (int i = 0; i < count; ++i, start_pfn += 0x200000)
-        pd[std::get<3>(idx)+i].set(PA_KERNEL_DATA_HUGE, start_pfn);
+        pd[std::get<3>(idx) + i].set(PA_KERNEL_DATA_HUGE, start_pfn);
 
     PAGE_ARRAY = (page*)0xffffff8040000000ULL;
     memset(PAGE_ARRAY, 0x00, addr_max * sizeof(page));
@@ -165,34 +158,33 @@ static inline void setup_buddy(uintptr_t addr_max)
 }
 
 SECTION(".text.kinit")
-static inline void save_memory_info(bootloader_data* data)
-{
+static inline void save_memory_info(bootloader_data* data) {
     kernel::mem::info::memory_size = 1ULL * 1024ULL * 1024ULL + // initial 1M
-        1024ULL * data->meminfo_1k_blocks + 64ULL * 1024ULL * data->meminfo_64k_blocks;
+                                     1024ULL * data->meminfo_1k_blocks +
+                                     64ULL * 1024ULL * data->meminfo_64k_blocks;
     kernel::mem::info::e820_entry_count = data->meminfo_entry_count;
     kernel::mem::info::e820_entry_length = data->meminfo_entry_length;
 
     memcpy(kernel::mem::info::e820_entries, data->meminfo_entries,
-        sizeof(kernel::mem::info::e820_entries));
+           sizeof(kernel::mem::info::e820_entries));
 }
 
 SECTION(".text.kinit")
-void setup_gdt()
-{
+void setup_gdt() {
     // user code
-    mem::gdt[3]  = 0x0020'fa00'0000'0000;
+    mem::gdt[3] = 0x0020'fa00'0000'0000;
     // user data
-    mem::gdt[4]  = 0x0000'f200'0000'0000;
+    mem::gdt[4] = 0x0000'f200'0000'0000;
     // user code32
-    mem::gdt[5]  = 0x00cf'fa00'0000'ffff;
+    mem::gdt[5] = 0x00cf'fa00'0000'ffff;
     // user data32
-    mem::gdt[6]  = 0x00cf'f200'0000'ffff;
+    mem::gdt[6] = 0x00cf'f200'0000'ffff;
     // thread load 32bit
-    mem::gdt[7]  = 0x0000'0000'0000'0000;
+    mem::gdt[7] = 0x0000'0000'0000'0000;
 
     // TSS descriptor
-    mem::gdt[8]  = 0x0000'8900'0070'0067;
-    mem::gdt[9]  = 0x0000'0000'ffff'ff00;
+    mem::gdt[8] = 0x0000'8900'0070'0067;
+    mem::gdt[9] = 0x0000'0000'ffff'ff00;
 
     // LDT descriptor
     mem::gdt[10] = 0x0000'8200'0060'001f;
@@ -203,23 +195,22 @@ void setup_gdt()
     // thread local 64bit
     mem::gdt[13] = 0x0000'0000'0000'0000;
 
-    uint64_t descriptor[] = {
-        0x005f'0000'0000'0000, (uintptr_t)(uint64_t*)mem::gdt
-    };
+    uint64_t descriptor[] = {0x005f'0000'0000'0000,
+                             (uintptr_t)(uint64_t*)mem::gdt};
 
     asm volatile(
-            "lgdt (%0)\n\t"
-            "mov $0x50, %%ax\n\t"
-            "lldt %%ax\n\t"
-            "mov $0x40, %%ax\n\t"
-            "ltr %%ax\n\t"
-            : : "r"((uintptr_t)descriptor+6): "ax", "memory"
-    );
+        "lgdt (%0)\n\t"
+        "mov $0x50, %%ax\n\t"
+        "lldt %%ax\n\t"
+        "mov $0x40, %%ax\n\t"
+        "ltr %%ax\n\t"
+        :
+        : "r"((uintptr_t)descriptor + 6)
+        : "ax", "memory");
 }
 
-extern "C" SECTION(".text.kinit")
-void NORETURN kernel_init(bootloader_data* data)
-{
+extern "C" SECTION(".text.kinit") void NORETURN
+    kernel_init(bootloader_data* data) {
     enable_sse();
 
     setup_early_kernel_page_table();
@@ -240,15 +231,16 @@ void NORETURN kernel_init(bootloader_data* data)
     using namespace mem::paging;
     auto kernel_stack_pfn = page_to_pfn(alloc_pages(9));
     auto kernel_stack_ptr =
-        mem::physaddr<std::byte>{kernel_stack_pfn} + (1<<9) * 0x1000;
+        mem::physaddr<std::byte>{kernel_stack_pfn} + (1 << 9) * 0x1000;
 
     asm volatile(
-            "mov %1, %%rdi\n\t"
-            "mov %2, %%rsp\n\t"
-            "xor %%rbp, %%rbp\n\t"
-            "call *%0\n\t"
-            : : "r"(real_kernel_init), "g"(kernel_stack_pfn), "g"(kernel_stack_ptr):
-    );
+        "mov %1, %%rdi\n\t"
+        "mov %2, %%rsp\n\t"
+        "xor %%rbp, %%rbp\n\t"
+        "call *%0\n\t"
+        :
+        : "r"(real_kernel_init), "g"(kernel_stack_pfn), "g"(kernel_stack_ptr)
+        :);
 
     freeze();
 }

+ 14 - 25
src/types/elf.cpp

@@ -14,14 +14,12 @@
 #include <kernel/process.hpp>
 #include <kernel/vfs.hpp>
 
-static inline void __user_push32(uintptr_t* sp, uint32_t d)
-{
+static inline void __user_push32(uintptr_t* sp, uint32_t d) {
     // TODO: use copy_to_user
     *(--*(uint32_t**)sp) = d;
 }
 
-static inline void __user_push_string32(uintptr_t* sp, const char* str)
-{
+static inline void __user_push_string32(uintptr_t* sp, const char* str) {
     size_t len = strlen(str);
 
     *sp -= (len + 1);
@@ -30,45 +28,36 @@ static inline void __user_push_string32(uintptr_t* sp, const char* str)
     memcpy((void*)*sp, str, len + 1);
 }
 
-int types::elf::elf32_load(types::elf::elf32_load_data& d)
-{
+int types::elf::elf32_load(types::elf::elf32_load_data& d) {
     auto& exec = d.exec_dent;
     if (!exec)
         return -ENOENT;
 
-    types::elf::elf32_header hdr {};
-    auto n_read = fs::read(
-        exec->inode,
-        (char*)&hdr,
-        sizeof(types::elf::elf32_header),
-        0, sizeof(types::elf::elf32_header));
+    types::elf::elf32_header hdr{};
+    auto n_read =
+        fs::read(exec->inode, (char*)&hdr, sizeof(types::elf::elf32_header), 0,
+                 sizeof(types::elf::elf32_header));
 
     if (n_read != sizeof(types::elf::elf32_header))
         return -EINVAL;
 
-    if (hdr.magic[0] != 0x7f || hdr.magic[1] != 'E'
-            || hdr.magic[2] != 'L' || hdr.magic[3] != 'F')
+    if (hdr.magic[0] != 0x7f || hdr.magic[1] != 'E' || hdr.magic[2] != 'L' ||
+        hdr.magic[3] != 'F')
         return -EINVAL;
 
     size_t phents_size = hdr.phentsize * hdr.phnum;
     size_t shents_size = hdr.shentsize * hdr.shnum;
     std::vector<types::elf::elf32_program_header_entry> phents(hdr.phnum);
-    n_read = fs::read(
-        exec->inode,
-        (char*)phents.data(),
-        phents_size,
-        hdr.phoff, phents_size);
+    n_read = fs::read(exec->inode, (char*)phents.data(), phents_size, hdr.phoff,
+                      phents_size);
 
     // broken file or I/O error
     if (n_read != phents_size)
         return -EINVAL;
 
     std::vector<types::elf::elf32_section_header_entry> shents(hdr.shnum);
-    n_read = fs::read(
-        exec->inode,
-        (char*)shents.data(),
-        shents_size,
-        hdr.shoff, shents_size);
+    n_read = fs::read(exec->inode, (char*)shents.data(), shents_size, hdr.shoff,
+                      shents_size);
 
     // broken file or I/O error
     if (n_read != shents_size)
@@ -182,7 +171,7 @@ int types::elf::elf32_load(types::elf::elf32_load_data& d)
     __user_push32(sp, 0);
 
     // push argv
-    for (int i = args.size()-1; i >= 0; --i)
+    for (int i = args.size() - 1; i >= 0; --i)
         __user_push32(sp, args[i]);
 
     // push argc

+ 13 - 11
src/types/libstdcpp.cpp

@@ -1,23 +1,25 @@
 #include <assert.h>
+
+#include <types/types.h>
+
 #include <kernel/log.hpp>
 #include <kernel/process.hpp>
-#include <types/types.h>
 
-extern "C" void NORETURN __stack_chk_fail(void)
-{
+extern "C" void NORETURN __stack_chk_fail(void) {
     assert(false);
-    for (;;) ;
+    for (;;)
+        ;
 }
 
-extern "C" void NORETURN __cxa_pure_virtual(void)
-{
+extern "C" void NORETURN __cxa_pure_virtual(void) {
     assert(false);
-    for (;;) ;
+    for (;;)
+        ;
 }
 
-void NORETURN
-__assert_fail(const char* statement, const char* file, int line, const char* func)
-{
-    kmsgf("Kernel assertion failed: (%s), %s:%d, %s", statement, file, line, func);
+void NORETURN __assert_fail(const char* statement, const char* file, int line,
+                            const char* func) {
+    kmsgf("Kernel assertion failed: (%s), %s:%d, %s", statement, file, line,
+          func);
     freeze();
 }