Compare commits

...

11 Commits

Author SHA1 Message Date
Bananymous 00c6820825 LibC: Make {open,sys,close}log use their own FILE instead of stddbg 2025-06-06 11:59:15 +03:00
Bananymous 6beaafcf11 LibC: Define std{in,out,err,dbg} with their actual names 2025-06-06 11:56:39 +03:00
Bananymous e92f039a17 Kernel: Fix tcp sending with already sent unacknowledged bytes 2025-06-06 11:55:44 +03:00
Bananymous ef76ffa1c1 Kernel: Remove unnecessary hack
This is no longer needed as thread unlocks its spinlock before calling
Process::exit() on terminating signal
2025-06-06 11:13:55 +03:00
Bananymous 652eb2346c Kernel: Fix syscall interrupt disabling
If thread had a terminating signal, syscall leaving would try to lock
process's mutex while not having interrupts enabled
2025-06-06 11:12:48 +03:00
Bananymous 66726090ec Kenrel: Fix TCP connection closing
If TCP socket was connected with connect() instead of accept() it would
never send FIN to other end when it was closed.
2025-06-06 11:10:29 +03:00
Bananymous b668173cba Kernel: Fix pseudo terminal writability 2025-06-06 11:09:50 +03:00
Bananymous a7e20d6e85 LibC: Fix getnameinfo port endianness 2025-06-06 06:52:56 +03:00
Bananymous c6ded82406 Kernel: Fix a deadlock when thread is executing terminating signal 2025-06-06 06:52:27 +03:00
Bananymous a76c6faffc Kernel: Fix a deadlock when process is exiting 2025-06-06 06:52:02 +03:00
Bananymous 81ff71a97f Kernel: Track the number of recursive spinlocks a thread is holding 2025-06-06 06:51:15 +03:00
18 changed files with 205 additions and 118 deletions

View File

@ -43,36 +43,11 @@ namespace Kernel
public:
RecursiveSpinLock() = default;
InterruptState lock()
{
auto state = Processor::get_interrupt_state();
Processor::set_interrupt_state(InterruptState::Disabled);
InterruptState lock();
auto id = Processor::current_id().as_u32();
bool try_lock_interrupts_disabled();
ProcessorID::value_type expected = PROCESSOR_NONE.as_u32();
while (!m_locker.compare_exchange(expected, id, BAN::MemoryOrder::memory_order_acq_rel))
{
if (expected == id)
break;
Processor::pause();
expected = PROCESSOR_NONE.as_u32();
}
m_lock_depth++;
return state;
}
void unlock(InterruptState state)
{
ASSERT(Processor::get_interrupt_state() == InterruptState::Disabled);
ASSERT(current_processor_has_lock());
ASSERT(m_lock_depth > 0);
if (--m_lock_depth == 0)
m_locker.store(PROCESSOR_NONE.as_u32(), BAN::MemoryOrder::memory_order_release);
Processor::set_interrupt_state(state);
}
void unlock(InterruptState state);
uint32_t lock_depth() const { return m_lock_depth; }

View File

@ -27,10 +27,12 @@ namespace Kernel
BAN::ErrorOr<size_t> write_impl(off_t, BAN::ConstByteSpan) override;
bool can_read_impl() const override { SpinLockGuard _(m_buffer_lock); return m_buffer_size > 0; }
bool can_write_impl() const override { SpinLockGuard _(m_buffer_lock); return m_buffer_size < m_buffer->size(); }
bool can_write_impl() const override { return true; }
bool has_error_impl() const override { return false; }
bool has_hungup_impl() const override { return !m_slave.valid(); }
void on_close(int) override;
BAN::ErrorOr<long> ioctl_impl(int, void*) override;
private:
@ -48,6 +50,7 @@ namespace Kernel
const dev_t m_rdev;
friend class PseudoTerminalSlave;
friend class BAN::RefPtr<PseudoTerminalMaster>;
};
@ -62,8 +65,11 @@ namespace Kernel
void clear() override;
protected:
bool master_has_closed() const override { return !m_master.valid(); }
bool putchar_impl(uint8_t ch) override;
bool can_write_impl() const override;
bool has_hungup_impl() const override { return !m_master.valid(); }
BAN::ErrorOr<long> ioctl_impl(int, void*) override;

View File

@ -42,18 +42,19 @@ namespace Kernel
public:
static BAN::ErrorOr<BAN::RefPtr<SerialTTY>> create(Serial);
virtual uint32_t width() const override;
virtual uint32_t height() const override;
uint32_t width() const override;
uint32_t height() const override;
virtual void clear() override { putchar_impl('\e'); putchar_impl('['); putchar_impl('2'); putchar_impl('J'); }
void clear() override { putchar_impl('\e'); putchar_impl('['); putchar_impl('2'); putchar_impl('J'); }
virtual void update() override;
void update() override;
virtual void handle_irq() override;
void handle_irq() override;
protected:
virtual BAN::StringView name() const override { return m_name; }
virtual bool putchar_impl(uint8_t) override;
BAN::StringView name() const override { return m_name; }
bool putchar_impl(uint8_t) override;
bool can_write_impl() const override { return true; }
private:
SerialTTY(Serial);

View File

@ -66,18 +66,19 @@ namespace Kernel
virtual BAN::ErrorOr<long> ioctl_impl(int, void*) override;
virtual bool can_read_impl() const override { return m_output.flush; }
virtual bool can_write_impl() const override { return true; }
virtual bool has_error_impl() const override { return false; }
virtual bool has_hungup_impl() const override { return false; }
virtual bool master_has_closed() const { return false; }
protected:
TTY(termios termios, mode_t mode, uid_t uid, gid_t gid);
virtual bool putchar_impl(uint8_t ch) = 0;
virtual void update_cursor() {}
virtual void after_write() {}
virtual BAN::ErrorOr<size_t> read_impl(off_t, BAN::ByteSpan) override;
virtual BAN::ErrorOr<size_t> write_impl(off_t, BAN::ConstByteSpan) override;
virtual BAN::ErrorOr<size_t> read_impl(off_t, BAN::ByteSpan) final override;
virtual BAN::ErrorOr<size_t> write_impl(off_t, BAN::ConstByteSpan) final override;
private:
bool putchar(uint8_t ch);
@ -110,6 +111,7 @@ namespace Kernel
protected:
RecursiveSpinLock m_write_lock;
ThreadBlocker m_write_blocker;
};
}

View File

@ -17,17 +17,18 @@ namespace Kernel
public:
static BAN::ErrorOr<BAN::RefPtr<VirtualTTY>> create(BAN::RefPtr<TerminalDriver>);
virtual BAN::ErrorOr<void> set_font(LibFont::Font&&) override;
BAN::ErrorOr<void> set_font(LibFont::Font&&) override;
virtual uint32_t height() const override { return m_height; }
virtual uint32_t width() const override { return m_width; }
uint32_t height() const override { return m_height; }
uint32_t width() const override { return m_width; }
virtual void clear() override;
void clear() override;
protected:
virtual BAN::StringView name() const override { return m_name; }
virtual bool putchar_impl(uint8_t ch) override;
void update_cursor() override;
BAN::StringView name() const override { return m_name; }
bool putchar_impl(uint8_t ch) override;
bool can_write_impl() const override { return true; }
void after_write() override;
private:
VirtualTTY(BAN::RefPtr<TerminalDriver>);

View File

@ -377,6 +377,9 @@ namespace Kernel::ACPI::AML
return result;
}
// FIXME: WHY TF IS THIS USING OVER 1 KiB of stack
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstack-usage="
static BAN::ErrorOr<Node> parse_logical_op(ParseContext& context)
{
dprintln_if(AML_DUMP_FUNCTION_CALLS, "parse_logical_op");
@ -467,6 +470,7 @@ namespace Kernel::ACPI::AML
return result;
}
#pragma GCC diagnostic pop
static BAN::ErrorOr<Node> parse_index_op(ParseContext& context);
@ -1537,6 +1541,9 @@ namespace Kernel::ACPI::AML
return result;
}
// FIXME: WHY TF IS THIS USING OVER 1 KiB of stack
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstack-usage="
static BAN::ErrorOr<Node> parse_explicit_conversion(ParseContext& context)
{
dprintln_if(AML_DUMP_FUNCTION_CALLS, "parse_explicit_conversion");
@ -1689,6 +1696,7 @@ namespace Kernel::ACPI::AML
return result;
}
#pragma GCC diagnostic pop
static BAN::ErrorOr<Node> parse_to_string_op(ParseContext& context)
{
@ -2750,7 +2758,9 @@ namespace Kernel::ACPI::AML
return method_call(scope, method, BAN::move(args));
}
// FIXME: WHY TF IS THIS USING OVER 2 KiB of stack
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstack-usage="
BAN::ErrorOr<Node> parse_node(ParseContext& context, bool return_ref)
{
if (context.aml_data.empty())
@ -2961,13 +2971,11 @@ namespace Kernel::ACPI::AML
reference.as.reference->ref_count++;
return reference;
}
#pragma GCC diagnostic pop
// FIXME: WHY TF IS THIS USING ALMOST 2 KiB of stack
#pragma GCC diagnostic push
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic ignored "-Wstack-usage="
#endif
BAN::ErrorOr<ExecutionFlowResult> parse_node_or_execution_flow(ParseContext& context)
{
if (context.aml_data.empty())
@ -3103,7 +3111,6 @@ namespace Kernel::ACPI::AML
.elem2 = BAN::move(node)
};
}
#pragma GCC diagnostic pop
BAN::ErrorOr<NameString> NameString::from_string(BAN::StringView name)

View File

@ -52,4 +52,59 @@ namespace Kernel
Processor::set_interrupt_state(state);
}
InterruptState RecursiveSpinLock::lock()
{
auto state = Processor::get_interrupt_state();
Processor::set_interrupt_state(InterruptState::Disabled);
auto id = Processor::current_id().as_u32();
ProcessorID::value_type expected = PROCESSOR_NONE.as_u32();
while (!m_locker.compare_exchange(expected, id, BAN::MemoryOrder::memory_order_acq_rel))
{
if (expected == id)
break;
Processor::pause();
expected = PROCESSOR_NONE.as_u32();
}
m_lock_depth++;
if (Thread::current_tid())
Thread::current().add_spinlock();
return state;
}
bool RecursiveSpinLock::try_lock_interrupts_disabled()
{
ASSERT(Processor::get_interrupt_state() == InterruptState::Disabled);
auto id = Processor::current_id().as_u32();
ProcessorID::value_type expected = PROCESSOR_NONE.as_u32();
if (!m_locker.compare_exchange(expected, id, BAN::MemoryOrder::memory_order_acq_rel))
if (expected != id)
return false;
m_lock_depth++;
if (Thread::current_tid())
Thread::current().add_spinlock();
return true;
}
void RecursiveSpinLock::unlock(InterruptState state)
{
ASSERT(Processor::get_interrupt_state() == InterruptState::Disabled);
ASSERT(current_processor_has_lock());
ASSERT(m_lock_depth > 0);
if (--m_lock_depth == 0)
m_locker.store(PROCESSOR_NONE.as_u32(), BAN::MemoryOrder::memory_order_release);
if (Thread::current_tid())
Thread::current().remove_spinlock();
Processor::set_interrupt_state(state);
}
}

View File

@ -645,6 +645,8 @@ namespace Kernel
static constexpr uint32_t retransmit_timeout_ms = 1000;
BAN::RefPtr<TCPSocket> keep_alive { this };
// socket's creation did a manual ref(), let's undo it here
this->unref();
LockGuard _(m_mutex);
@ -653,25 +655,31 @@ namespace Kernel
{
const uint64_t current_ms = SystemTimer::get().ms_since_boot();
if (m_state == State::TimeWait && current_ms >= m_time_wait_start_ms + 30'000)
switch (m_state)
{
set_connection_as_closed();
continue;
}
// This is the last instance
if (ref_count() == 1)
{
if (m_state == State::Listen)
{
case State::TimeWait:
if (current_ms < m_time_wait_start_ms + 30'000)
break;
// TimeWait timeout
set_connection_as_closed();
continue;
}
if (m_state == State::Established)
{
case State::Listen:
if (ref_count() > 1)
break;
// Listen socket closed
// ref_count = keep_alieve
set_connection_as_closed();
continue;
case State::Established:
if (ref_count() > static_cast<uint32_t>(1 + !!m_listen_parent))
break;
// Connected socket closed
// ref_count = keep_alive + listen's hashmap
m_next_flags = FIN | ACK;
m_next_state = State::FinWait1;
}
break;
default:
break;
}
if (m_next_flags)
@ -725,7 +733,7 @@ namespace Kernel
const uint32_t total_send = BAN::Math::min<uint32_t>(m_send_window.data_size - send_base, m_send_window.scaled_size());
m_send_window.current_seq = m_send_window.start_seq;
m_send_window.current_seq = m_send_window.start_seq + m_send_window.sent_size;
auto* send_buffer = reinterpret_cast<const uint8_t*>(m_send_window.buffer->vaddr() + send_base);
for (uint32_t i = 0; i < total_send;)

View File

@ -360,7 +360,7 @@ namespace Kernel
{
LockGuard _(inode->m_mutex);
if (is_nonblock && !inode->can_read())
return 0;
return BAN::Error::from_errno(EAGAIN);
nread = TRY(inode->read(offset, buffer));
}
@ -395,7 +395,7 @@ namespace Kernel
{
LockGuard _(inode->m_mutex);
if (is_nonblock && !inode->can_write())
return BAN::Error::from_errno(EWOULDBLOCK);
return BAN::Error::from_errno(EAGAIN);
nwrite = TRY(inode->write(offset, buffer));
}

View File

@ -273,34 +273,39 @@ namespace Kernel
{
if (m_parent)
{
Process* parent_process = nullptr;
for_each_process(
[&](Process& parent) -> BAN::Iteration
{
if (parent.pid() != m_parent)
return BAN::Iteration::Continue;
LockGuard _(parent.m_process_lock);
for (auto& child : parent.m_child_exit_statuses)
{
if (child.pid != pid())
continue;
child.exit_code = __WGENEXITCODE(status, signal);
child.exited = true;
parent.add_pending_signal(SIGCHLD);
if (!parent.m_threads.empty())
Processor::scheduler().unblock_thread(parent.m_threads.front());
parent.m_child_exit_blocker.unblock();
break;
}
parent_process = &parent;
return BAN::Iteration::Break;
}
);
if (parent_process)
{
LockGuard _(parent_process->m_process_lock);
for (auto& child : parent_process->m_child_exit_statuses)
{
if (child.pid != pid())
continue;
child.exit_code = __WGENEXITCODE(status, signal);
child.exited = true;
parent_process->add_pending_signal(SIGCHLD);
if (!parent_process->m_threads.empty())
Processor::scheduler().unblock_thread(parent_process->m_threads.front());
parent_process->m_child_exit_blocker.unblock();
break;
}
}
}
for (size_t i = 0; i < m_threads.size(); i++)

View File

@ -62,14 +62,10 @@ namespace Kernel
ret = sys_fork_trampoline();
else
#pragma GCC diagnostic push
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic warning "-Wmaybe-uninitialized"
#endif
ret = (Process::current().*s_syscall_handlers[syscall])(arg1, arg2, arg3, arg4, arg5);
#pragma GCC diagnostic pop
Processor::set_interrupt_state(InterruptState::Disabled);
#if DUMP_ALL_SYSCALLS
if (ret.is_error())
dprintln("{} pid {}: {}: {}", process_path, Process::current().pid(), s_syscall_names[syscall], ret.error());
@ -100,6 +96,8 @@ namespace Kernel
if (ret.is_error() && ret.error().get_error_code() == EINTR)
ret = BAN::Error::from_errno(ERESTART);
Processor::set_interrupt_state(InterruptState::Disabled);
ASSERT(Kernel::Thread::current().state() == Kernel::Thread::State::Executing);
if (ret.is_error())

View File

@ -130,6 +130,9 @@ namespace Kernel
m_buffer_size -= to_copy;
m_buffer_tail = (m_buffer_tail + to_copy) % m_buffer->size();
if (auto slave = m_slave.lock())
slave->m_write_blocker.unblock();
epoll_notify(EPOLLOUT);
return to_copy;
@ -139,12 +142,18 @@ namespace Kernel
{
auto slave = m_slave.lock();
if (!slave)
return BAN::Error::from_errno(ENODEV);
return BAN::Error::from_errno(EIO);
for (size_t i = 0; i < buffer.size(); i++)
slave->handle_input_byte(buffer[i]);
return buffer.size();
}
void PseudoTerminalMaster::on_close(int)
{
if (auto slave = m_slave.lock())
slave->m_write_blocker.unblock();
}
BAN::ErrorOr<long> PseudoTerminalMaster::ioctl_impl(int request, void* argument)
{
auto slave = m_slave.lock();
@ -186,6 +195,15 @@ namespace Kernel
return false;
}
bool PseudoTerminalSlave::can_write_impl() const
{
auto master = m_master.lock();
if (!master)
return false;
SpinLockGuard _(master->m_buffer_lock);
return master->m_buffer_size < master->m_buffer->size();
}
BAN::ErrorOr<long> PseudoTerminalSlave::ioctl_impl(int request, void* argument)
{
switch (request)

View File

@ -219,7 +219,7 @@ namespace Kernel
auto* ptr = reinterpret_cast<const uint8_t*>(ansi_c_str);
while (*ptr)
handle_input_byte(*ptr++);
update_cursor();
after_write();
}
}
@ -297,12 +297,8 @@ namespace Kernel
if (should_append)
{
// FIXME: don't ignore these bytes
if (m_output.bytes >= m_output.buffer.size())
{
dwarnln("TTY input full");
return;
}
m_output.buffer[m_output.bytes++] = ch;
}
@ -405,6 +401,8 @@ namespace Kernel
if (m_output.bytes == 0)
{
if (master_has_closed())
return 0;
m_output.flush = false;
return 0;
}
@ -431,6 +429,13 @@ namespace Kernel
BAN::ErrorOr<size_t> TTY::write_impl(off_t, BAN::ConstByteSpan buffer)
{
while (!can_write_impl())
{
if (master_has_closed())
return BAN::Error::from_errno(EIO);
TRY(Thread::current().block_or_eintr_indefinite(m_write_blocker, &m_mutex));
}
size_t written = 0;
{
@ -438,7 +443,7 @@ namespace Kernel
for (; written < buffer.size(); written++)
if (!putchar(buffer[written]))
break;
update_cursor();
after_write();
}
if (can_write_impl())
@ -452,7 +457,7 @@ namespace Kernel
ASSERT(s_tty);
SpinLockGuard _(s_tty->m_write_lock);
s_tty->putchar(ch);
s_tty->update_cursor();
s_tty->after_write();
}
bool TTY::is_initialized()

View File

@ -577,7 +577,7 @@ namespace Kernel
return true;
}
void VirtualTTY::update_cursor()
void VirtualTTY::after_write()
{
if (m_cursor_shown != m_last_cursor_shown)
m_terminal_driver->set_cursor_shown(m_cursor_shown);

View File

@ -442,7 +442,7 @@ namespace Kernel
ASSERT(&Thread::current() == this);
ASSERT(is_userspace());
SpinLockGuard _(m_signal_lock);
auto state = m_signal_lock.lock();
auto& interrupt_stack = *reinterpret_cast<InterruptStack*>(kernel_stack_top() - sizeof(InterruptStack));
ASSERT(GDT::is_user_segment(interrupt_stack.cs));
@ -504,8 +504,9 @@ namespace Kernel
case SIGTRAP:
case SIGXCPU:
case SIGXFSZ:
m_signal_lock.unlock(state);
process().exit(128 + signal, signal | 0x80);
break;
ASSERT_NOT_REACHED();
// Abnormal termination of the process
case SIGALRM:
@ -519,8 +520,9 @@ namespace Kernel
case SIGPOLL:
case SIGPROF:
case SIGVTALRM:
m_signal_lock.unlock(state);
process().exit(128 + signal, signal);
break;
ASSERT_NOT_REACHED();
// Ignore the signal
case SIGCHLD:
@ -541,6 +543,8 @@ namespace Kernel
}
}
m_signal_lock.unlock(state);
return has_sa_restart;
}
@ -623,9 +627,6 @@ namespace Kernel
{
Processor::set_interrupt_state(InterruptState::Disabled);
setup_process_cleanup();
// This is super hacky but prevents a crash in yield :D
if (m_signal_lock.current_processor_has_lock())
m_signal_lock.unlock(InterruptState::Disabled);
Processor::yield();
ASSERT_NOT_REACHED();
}

View File

@ -160,7 +160,7 @@ int getnameinfo(const struct sockaddr* __restrict sa, socklen_t salen, char* __r
const sockaddr_in* sa_in = reinterpret_cast<const sockaddr_in*>(sa);
if (node && !inet_ntop(sa_in->sin_family, &sa_in->sin_addr, node, nodelen))
return EAI_SYSTEM;
if (service && snprintf(service, servicelen, "%d", sa_in->sin_port) < 0)
if (service && snprintf(service, servicelen, "%d", ntohs(sa_in->sin_port)) < 0)
return EAI_SYSTEM;
break;
}
@ -171,7 +171,7 @@ int getnameinfo(const struct sockaddr* __restrict sa, socklen_t salen, char* __r
const sockaddr_in6* sa_in6 = reinterpret_cast<const sockaddr_in6*>(sa);
if (node && !inet_ntop(sa_in6->sin6_family, &sa_in6->sin6_addr, node, nodelen))
return EAI_SYSTEM;
if (service && snprintf(service, servicelen, "%d", sa_in6->sin6_port) < 0)
if (service && snprintf(service, servicelen, "%d", ntohs(sa_in6->sin6_port)) < 0)
return EAI_SYSTEM;
break;
}

View File

@ -60,10 +60,10 @@ struct ScopeLock
static FILE s_files[FOPEN_MAX];
FILE* stdin = &s_files[0];
FILE* stdout = &s_files[1];
FILE* stderr = &s_files[2];
FILE* stddbg = &s_files[3];
FILE* __stdin = &s_files[0];
FILE* __stdout = &s_files[1];
FILE* __stderr = &s_files[2];
FILE* __stddbg = &s_files[3];
static void init_closed_file(FILE* file)
{

View File

@ -1,13 +1,16 @@
#include <BAN/Assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <syslog.h>
static const char* s_ident = nullptr;
static FILE* s_log_file = nullptr;
void openlog(const char* ident, int option, int facility)
{
if (s_log_file == nullptr)
s_log_file = fopen("/dev/debug", "w");
(void)option;
(void)facility;
s_ident = ident;
@ -17,14 +20,16 @@ void syslog(int priority, const char* format, ...)
{
(void)priority;
if (s_ident)
fprintf(stddbg, "%s", s_ident);
fprintf(s_log_file, "%s", s_ident);
va_list args;
va_start(args, format);
vfprintf(stddbg, format, args);
vfprintf(s_log_file, format, args);
va_end(args);
}
void closelog()
{
fclose(s_log_file);
s_log_file = nullptr;
s_ident = nullptr;
}