diff --git a/Documentation/admin-guide/boot.rst b/Documentation/admin-guide/boot.rst index 8d425b38..3050f308 100644 --- a/Documentation/admin-guide/boot.rst +++ b/Documentation/admin-guide/boot.rst @@ -21,6 +21,17 @@ BIOS 入口检查 CPU 能力、建立页表与栈后进入共享 64 位内核。 日志 ==== -启动日志可镜像到 COM1。``logcolor=0`` 关闭内核颜色,``bootlog-pause=1`` -在启动检查点等待输入;普通启动继续进入用户态。文字控制台采用现有 -framebuffer 字形、pitch 和原生 RGB 转换,不假设紧密排列的 32 位像素。 +内核日志使用 ``[启动后秒数] [等级] [组件] 消息`` 格式。默认保留 INFO、WARN、ERROR 和 +FATAL。常见的进程启动、退出、回收及硬件缺席记录仅在 DEBUG 下输出。``debug`` 或 ``loglevel=8`` 开启 +DEBUG,``quiet`` 等效于 ``loglevel=4``。``loglevel=N`` 接受 0–8,输出优先级数值小于 N 的记录。FATAL 和 +panic 始终保留紧急输出。 + +``log=screen,serial`` 是默认值。可用 ``log=screen`` 或 ``log=serial`` 只选一个日志目标,也可用 +``log=none`` 关闭常规内核日志。``logcolor=0`` 关闭普通日志颜色。``bootlog-pause=1`` +在启动检查点等待输入。``syscall-trace=/path/prefix`` 为匹配的程序启用系统调用诊断。 + +COM1 使用 115200 波特、8N1。早期启动和 panic 使用有界轮询。进入用户态后,内核日志和控制台镜像进入 32 KiB 发送队列,由 IRQ4 +批量填充 UART FIFO,定时器负责兜底。队列为 WARN 和 ERROR 预留空间。积压清空后,串口报告丢弃的日志和控制台镜像数量。直接写入 +``/dev/ttyS0`` 时,阻塞写等待可用空间,非阻塞写在无法接收任何字节时返回 ``EAGAIN``。关闭或重启系统前会尝试发送队列中的数据。 + +文字控制台使用现有 framebuffer 字形、pitch 和原生 RGB 转换,可处理带行间填充的帧缓冲。 diff --git a/Documentation/locale/en/LC_MESSAGES/admin-guide/boot.po b/Documentation/locale/en/LC_MESSAGES/admin-guide/boot.po index 7d447cad..80bed251 100644 --- a/Documentation/locale/en/LC_MESSAGES/admin-guide/boot.po +++ b/Documentation/locale/en/LC_MESSAGES/admin-guide/boot.po @@ -46,11 +46,14 @@ msgstr "" msgid "日志" msgstr "Logging" -msgid "" -"启动日志可镜像到 COM1。``logcolor=0`` 关闭内核颜色,``bootlog-pause=1`` 在启动检查点等待输入;普通启动继续进入用户态。文字控制台采用现有 " -"framebuffer 字形、pitch 和原生 RGB 转换,不假设紧密排列的 32 位像素。" -msgstr "" -"Boot logs can be mirrored to COM1. ``logcolor=0`` disables kernel colors, and ``bootlog-pause=1`` " -"waits for input at boot checkpoints; normal boot proceeds into userspace. The text console uses " -"the existing framebuffer glyphs, pitch, and native RGB conversion, without assuming tightly packed" -" 32-bit pixels." +msgid "内核日志使用 ``[启动后秒数] [等级] [组件] 消息`` 格式。默认保留 INFO、WARN、ERROR 和 FATAL。常见的进程启动、退出、回收及硬件缺席记录仅在 DEBUG 下输出。``debug`` 或 ``loglevel=8`` 开启 DEBUG,``quiet`` 等效于 ``loglevel=4``。``loglevel=N`` 接受 0–8,输出优先级数值小于 N 的记录。FATAL 和 panic 始终保留紧急输出。" +msgstr "Kernel records use ``[seconds since boot] [level] [component] message``. INFO, WARN, ERROR, and FATAL are enabled by default. Routine process launches, exits, reaping, and absent hardware are visible at DEBUG. Use ``debug`` or ``loglevel=8`` to enable DEBUG. ``quiet`` is equivalent to ``loglevel=4``. ``loglevel=N`` accepts 0–8 and emits priorities numerically below N. Emergency FATAL and panic output remains enabled." + +msgid "``log=screen,serial`` 是默认值。可用 ``log=screen`` 或 ``log=serial`` 只选一个日志目标,也可用 ``log=none`` 关闭常规内核日志。``logcolor=0`` 关闭普通日志颜色。``bootlog-pause=1`` 在启动检查点等待输入。``syscall-trace=/path/prefix`` 为匹配的程序启用系统调用诊断。" +msgstr "``log=screen,serial`` is the default. Use ``log=screen`` or ``log=serial`` for a single log sink, or ``log=none`` to disable regular kernel records. ``logcolor=0`` disables regular log colors. ``bootlog-pause=1`` waits for input at a boot checkpoint. ``syscall-trace=/path/prefix`` enables syscall diagnostics for matching programs." + +msgid "COM1 使用 115200 波特、8N1。早期启动和 panic 使用有界轮询。进入用户态后,内核日志和控制台镜像进入 32 KiB 发送队列,由 IRQ4 批量填充 UART FIFO,定时器负责兜底。队列为 WARN 和 ERROR 预留空间。积压清空后,串口报告丢弃的日志和控制台镜像数量。直接写入 ``/dev/ttyS0`` 时,阻塞写等待可用空间,非阻塞写在无法接收任何字节时返回 ``EAGAIN``。关闭或重启系统前会尝试发送队列中的数据。" +msgstr "COM1 uses 115200 baud, 8N1. Early boot and panic use bounded polling. After entering userspace, kernel logs and console mirroring use a 32 KiB transmit queue. IRQ4 fills the UART FIFO in batches, and the timer provides a fallback. The queue reserves space for WARN and ERROR. After the backlog drains, serial output reports the number of dropped records and console chunks. Blocking writes to ``/dev/ttyS0`` wait for space. Nonblocking writes return ``EAGAIN`` when no input bytes fit. Shutdown and reboot attempt to flush the queue." + +msgid "文字控制台使用现有 framebuffer 字形、pitch 和原生 RGB 转换,可处理带行间填充的帧缓冲。" +msgstr "The text console uses the existing framebuffer glyphs, pitch, and native RGB conversion and supports framebuffers with row padding." diff --git a/Documentation/locale/ja/LC_MESSAGES/admin-guide/boot.po b/Documentation/locale/ja/LC_MESSAGES/admin-guide/boot.po index 13cb0249..f1e5af1d 100644 --- a/Documentation/locale/ja/LC_MESSAGES/admin-guide/boot.po +++ b/Documentation/locale/ja/LC_MESSAGES/admin-guide/boot.po @@ -41,10 +41,14 @@ msgstr "" msgid "日志" msgstr "ログ" -msgid "" -"启动日志可镜像到 COM1。``logcolor=0`` 关闭内核颜色,``bootlog-pause=1`` 在启动检查点等待输入;普通启动继续进入用户态。文字控制台采用现有 " -"framebuffer 字形、pitch 和原生 RGB 转换,不假设紧密排列的 32 位像素。" -msgstr "" -"起動ログは COM1 にも出力できます。``logcolor=0`` はカーネルの色表示を無効にし、``bootlog-pause=1`` " -"は起動チェックポイントで入力を待ちます。通常の起動はそのままユーザー空間へ進みます。テキストコンソールは既存の framebuffer 字形、pitch、ネイティブ RGB 変換を使い、32 " -"ビットピクセルが隙間なく並ぶことは前提としません。" +msgid "内核日志使用 ``[启动后秒数] [等级] [组件] 消息`` 格式。默认保留 INFO、WARN、ERROR 和 FATAL。常见的进程启动、退出、回收及硬件缺席记录仅在 DEBUG 下输出。``debug`` 或 ``loglevel=8`` 开启 DEBUG,``quiet`` 等效于 ``loglevel=4``。``loglevel=N`` 接受 0–8,输出优先级数值小于 N 的记录。FATAL 和 panic 始终保留紧急输出。" +msgstr "カーネルログは ``[起動後の秒数] [レベル] [コンポーネント] メッセージ`` の形式を使用します。既定では INFO、WARN、ERROR、FATAL が有効です。通常のプロセス起動、終了、回収、およびハードウェア未検出の記録は DEBUG で確認できます。``debug`` または ``loglevel=8`` で DEBUG を有効にできます。``quiet`` は ``loglevel=4`` と同等です。``loglevel=N`` は 0–8 を受け付け、数値が N 未満の優先度を出力します。FATAL と panic の緊急出力は常に有効です。" + +msgid "``log=screen,serial`` 是默认值。可用 ``log=screen`` 或 ``log=serial`` 只选一个日志目标,也可用 ``log=none`` 关闭常规内核日志。``logcolor=0`` 关闭普通日志颜色。``bootlog-pause=1`` 在启动检查点等待输入。``syscall-trace=/path/prefix`` 为匹配的程序启用系统调用诊断。" +msgstr "既定は ``log=screen,serial`` です。``log=screen`` または ``log=serial`` で出力先を一つに絞り、``log=none`` で通常のカーネルログを無効にできます。``logcolor=0`` で通常のログの色を無効にします。``bootlog-pause=1`` は起動中のチェックポイントで入力を待ちます。``syscall-trace=/path/prefix`` は該当するプログラムのシステムコール診断を有効にします。" + +msgid "COM1 使用 115200 波特、8N1。早期启动和 panic 使用有界轮询。进入用户态后,内核日志和控制台镜像进入 32 KiB 发送队列,由 IRQ4 批量填充 UART FIFO,定时器负责兜底。队列为 WARN 和 ERROR 预留空间。积压清空后,串口报告丢弃的日志和控制台镜像数量。直接写入 ``/dev/ttyS0`` 时,阻塞写等待可用空间,非阻塞写在无法接收任何字节时返回 ``EAGAIN``。关闭或重启系统前会尝试发送队列中的数据。" +msgstr "COM1 は 115200 ボー、8N1 を使用します。起動初期と panic では上限付きのポーリングを使います。ユーザー空間に移行すると、カーネルログとコンソールの複製は 32 KiB の送信キューに入ります。IRQ4 が UART FIFO にまとめて書き込み、タイマーはその補助を行います。キューには WARN と ERROR 用の領域を確保します。滞留データの送信後、破棄したログとコンソール出力の件数をシリアルに出力します。``/dev/ttyS0`` のブロッキング書き込みは空き領域を待ちます。ノンブロッキング書き込みで入力を 1 バイトも受け付けられない場合は ``EAGAIN`` を返します。シャットダウンと再起動の前に送信キューの排出を試みます。" + +msgid "文字控制台使用现有 framebuffer 字形、pitch 和原生 RGB 转换,可处理带行间填充的帧缓冲。" +msgstr "テキストコンソールは既存のフレームバッファーのグリフ、ピッチ、およびネイティブ RGB 変換を使用し、行パディングのあるフレームバッファーに対応します。" diff --git a/arch/x86_64/interrupt/idt.c b/arch/x86_64/interrupt/idt.c index 4d4c0f33..a785b91f 100644 --- a/arch/x86_64/interrupt/idt.c +++ b/arch/x86_64/interrupt/idt.c @@ -756,17 +756,11 @@ struct task *page_fault_dispatch(struct trap_frame *frame) bugcheck_exception(14, 0, 0, 0, 0, 0, 0, cr2); } if ((frame->cs & 3ULL) == 3ULL) { - console_fatal("[reliefnt] page fault unhandled cr2=0x%llx error=0x%llx rip=0x%llx cs=0x%llx\n", + console_debug("[reliefnt] user page fault unhandled cr2=0x%llx error=0x%llx rip=0x%llx cs=0x%llx\n", (unsigned long long)cr2, (unsigned long long)frame->error, (unsigned long long)frame->rip, (unsigned long long)frame->cs); - console_fatal("[reliefnt] page fault flags present=%u write=%u user=%u reserved=%u fetch=%u\n", - (unsigned)(frame->error & 1u), - (unsigned)((frame->error >> 1) & 1u), - (unsigned)((frame->error >> 2) & 1u), - (unsigned)((frame->error >> 3) & 1u), - (unsigned)((frame->error >> 4) & 1u)); kernel_spin_unlock(&user_page_fault_lock); memory_wait_cancel(sched_current_task()); signal_user_page_fault(frame, cr2); diff --git a/arch/x86_64/interrupt/irq.c b/arch/x86_64/interrupt/irq.c index 873bb375..69d6a60a 100644 --- a/arch/x86_64/interrupt/irq.c +++ b/arch/x86_64/interrupt/irq.c @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -83,6 +84,7 @@ static void pic_remap(void) io_wait(); uint8_t mask1 = (uint8_t)~((1u << 0) | (1u << 1) | (1u << 2)); + if (serial_com1_available()) mask1 &= (uint8_t)~(1u << 4); uint8_t mask2 = (uint8_t)~(1u << 4); x86_64_outb(mask1, PIC1_DATA); x86_64_outb(mask2, PIC2_DATA); @@ -159,6 +161,7 @@ void irq_init(void) if (routed) { pic_mask_all(); irq_uses_ioapic = true; + serial_tx_set_irq(serial_com1_available() && ioapic_route_irq(4u, 0x24u, apic_bsp_id())); console_info("[reliefnt] IOAPIC owns PIT/keyboard/mouse, PIT=%uHz BSP=%u\n", (unsigned)RELIEFNT_TICK_HZ, (unsigned)apic_bsp_id()); return; @@ -166,11 +169,13 @@ void irq_init(void) /* Fall back to the LAPIC virtual-wire bridge. This keeps legacy PIC * delivery alive after SMP enables the BSP local APIC. */ apic_enable_legacy_pic(); + serial_tx_set_irq(serial_com1_available()); irq_uses_local_apic = apic_enabled(); console_info("[reliefnt] PIC virtual-wire owns IRQ0/1/12, PIT=%uHz\n", (unsigned)RELIEFNT_TICK_HZ); return; } + serial_tx_set_irq(serial_com1_available()); console_info("[reliefnt] PIC remapped, PIT=%uHz, IRQ0/1/12 enabled\n", (unsigned)RELIEFNT_TICK_HZ); } @@ -195,6 +200,7 @@ struct task *irq_dispatch(struct trap_frame *frame) } if (vector == 0x20) { time_on_tick(); + serial_tx_tick(); if (from_user) { uint8_t byte; if (keyboard_led_next(&keyboard_led, input_caps_lock_active() ? 4U : 0U, @@ -264,6 +270,9 @@ struct task *irq_dispatch(struct trap_frame *frame) } } irq_send_eoi(1); + } else if (vector == 0x24) { + serial_tx_irq(); + irq_send_eoi(4); } else if (vector == 0x2c) { driver_manager_mouse_poll(); irq_send_eoi(12); diff --git a/arch/x86_64/platform/power.c b/arch/x86_64/platform/power.c index 3cdc248f..301f1691 100644 --- a/arch/x86_64/platform/power.c +++ b/arch/x86_64/platform/power.c @@ -3,6 +3,7 @@ * Provides shutdown, reboot, and platform-specific fallback mechanisms. */ #include +#include #include #include #include @@ -835,6 +836,7 @@ static int acpi_enable_power_management(void) void power_reboot(void) { console_info("[reliefnt] reboot requested\n"); + serial_tx_flush(); for (;;) { while (x86_64_inb(0x64) & 0x02) { } @@ -849,6 +851,7 @@ void power_reboot(void) void power_shutdown(void) { console_info("[reliefnt] shutdown requested\n"); + serial_tx_flush(); if (acpi_enable_power_management()) { uint16_t sleep_enable = 1U << 13; uint16_t pm1a = x86_64_inw(acpi_power.pm1a_control); diff --git a/drivers/console/core.c b/drivers/console/core.c index c0d734fa..d3eee376 100644 --- a/drivers/console/core.c +++ b/drivers/console/core.c @@ -1,4 +1,5 @@ #include "internal.h" +#include static void vga_console_ansi_feed(char character); @@ -43,8 +44,6 @@ uint32_t fb_row; uint32_t console_ui_theme = 1u; -bool console_line_start = true; - bool console_service_logs_only; static bool console_presenting; @@ -101,27 +100,21 @@ static void vga_console_ansi_feed(char character) } } -void console_emit_raw(char ch) +/** @brief Render one encoded record while the boot console owns the display. */ +void console_emit_display(const char *text, size_t length) { - char s[2] = {ch, 0}; - if (console_vga_text_mode) { - log_store(ch); - serial_write(s); - if (!console_service_logs_only) vga_console_boot_byte(ch); - console_line_start = ch == '\n'; - return; - } - if (!console_service_logs_only) fb_console_hide_tty_cursor(); - log_store(ch); - serial_write(s); - if (vga_console_enabled && !console_service_logs_only) { - vga_putc(ch); + if (console_service_logs_only) return; + if (!console_vga_text_mode) fb_console_hide_tty_cursor(); + for (size_t i = 0; i < length; ++i) { + char ch = text[i]; + if (console_vga_text_mode) vga_console_boot_byte(ch); + else { + if (vga_console_enabled) vga_console_ansi_feed(ch); + if (ch == '\n') fb_console_ansi_feed('\r'); + fb_console_ansi_feed(ch); + } } - if (!console_service_logs_only) { - if (ch == '\n') fb_console_newline(); - else fb_console_putc(ch); - } - console_line_start = ch == '\n'; + console_present(); } /** @brief Draw the cursor and publish an active text grid when not staging. */ @@ -149,54 +142,20 @@ void console_set_ui_theme(uint32_t theme) console_ui_theme = theme == 0u ? 0u : 1u; } -void console_putc(char ch) -{ - if (console_line_start) { - console_emit_timestamp(); - } - console_emit_raw(ch); -} - -void console_write(const char *s) -{ - while (s && *s) { - console_putc(*s++); - } -} - -/** - * @brief Append raw diagnostic output to the kernel log and serial sink. - * @param s Bytes to write; need not be NUL-terminated. - * @param len Number of bytes to write. - */ -void console_write_len(const char *s, size_t len) -{ - for (size_t i = 0; i < len; ++i) { - console_putc(s[i]); - } -} - -/** - * @brief Mirror system-console bytes to serial without creating kernel log records. - * @param s Bytes already accepted by the console terminal. - * @param len Number of bytes to mirror; s need not be NUL-terminated. - */ -void console_serial_write_len(const char *s, size_t len) +void console_serial_write_len(const char *text, size_t length) { - for (size_t i = 0; i < len; ++i) { - char byte[2] = {s[i], 0}; - serial_write(byte); + if (!text) return; + char data[512]; + /* Do not retain user pointers or run their faults in the TX lock. */ + while (length) { + size_t chunk = length < sizeof(data) ? length : sizeof(data); + __builtin_memcpy(data, text, chunk); + serial_tx_record(data, chunk, false); + length -= chunk; + text += chunk; } } -void console_printf(const char *fmt, ...) -{ - va_list arguments; - va_start(arguments, fmt); - console_vlog(CONSOLE_LOG_INFO, fmt, arguments); - va_end(arguments); -} - void console_enable_framebuffer(void) { if (console_vga_text_mode) return; diff --git a/drivers/console/internal.h b/drivers/console/internal.h index c05fcb00..c24761fe 100644 --- a/drivers/console/internal.h +++ b/drivers/console/internal.h @@ -228,7 +228,6 @@ extern uint32_t fb_rows; extern uint32_t fb_col; extern uint32_t fb_row; extern uint32_t console_ui_theme; -extern bool console_line_start; extern bool console_service_logs_only; extern uint32_t fb_saved_col; extern uint32_t fb_saved_row; @@ -348,12 +347,11 @@ void fb_console_stream_restore(const struct fb_console_state *state); /** @brief Reset text state and clear the full active rendering surface. */ void fb_console_initialize_fullscreen(void); -void console_emit_raw(char ch); +void console_emit_display(const char *text, size_t length); /** @brief Draw the cursor and publish an active text grid when not staging. */ void console_present(void); -void console_emit_timestamp(void); void console_init(void); @@ -361,12 +359,10 @@ void console_log_configure(const char *cmdline); void console_set_ui_theme(uint32_t theme); -void console_putc(char ch); -void console_write(const char *s); /** - * @brief Append raw diagnostic output to the kernel log and serial sink. + * @brief Append length-delimited input as INFO records in the kernel log. * @param s Bytes to write; need not be NUL-terminated. * @param len Number of bytes to write. */ diff --git a/drivers/console/log.c b/drivers/console/log.c index 0d0c727b..66a159f3 100644 --- a/drivers/console/log.c +++ b/drivers/console/log.c @@ -1,197 +1,79 @@ +/* SPDX-License-Identifier: Apache-2.0 */ #include "internal.h" #include +#include -static void print_unsigned_raw(uint64_t value, unsigned base, bool upper); +#define CONSOLE_LOG_MESSAGE_BYTES 768u +#define CONSOLE_LOG_RECORD_BYTES (CONSOLE_LOG_MESSAGE_BYTES + 96u) -static void console_log_control(const char *sequence); - -static void console_log_putc(enum console_log_level level, char character); - -static void console_log_string(enum console_log_level level, const char *text); - -static void console_log_number(enum console_log_level level, uint64_t value, - unsigned base, bool upper, unsigned width, - bool zero_pad, bool negative); - -static bool console_log_color_enabled; +static bool console_log_color_enabled = true; +static bool log_screen = true; +static bool log_serial = true; +/* Kernel priorities are Linux loglevel values. Only priorities below the + * console threshold are emitted. FATAL always reaches the emergency sink. */ +static unsigned loglevel = 7; static uint32_t console_log_owner = UINT32_MAX; -static const char *const console_log_prefixes[] = { +static uint64_t last_timestamp; +static bool log_head_fragment; +static const unsigned priorities[] = {7, 6, 4, 3, 0}; +static const char *const prefixes[] = { "[DEBUG] ", "[INFO] ", "[WARN] ", "[ERROR] ", "[FATAL] ", }; -static const char *const console_log_colors[] = { - "\033[38;2;128;144;160m", - "\033[38;2;144;168;160m", - "\033[38;2;192;168;112m", - "\033[38;2;192;128;128m", - "\033[38;2;176;128;160m", +static const char *const colors[] = { + "\033[38;2;128;144;160m", "\033[38;2;144;168;160m", "\033[38;2;192;168;112m", + "\033[38;2;192;128;128m", "\033[38;2;176;128;160m", }; -void log_store(char ch) -{ - if (log_len < CONSOLE_LOG_CAP) { - log_buffer[(log_start + log_len++) % CONSOLE_LOG_CAP] = ch; - } else { - log_buffer[log_start] = ch; - log_start = (log_start + 1u) % CONSOLE_LOG_CAP; - } -} - -size_t console_log_replay_start(void) -{ - size_t first = 0; - if (log_len == CONSOLE_LOG_CAP) { - while (first < log_len && log_buffer[(log_start + first) % CONSOLE_LOG_CAP] != '\n') ++first; - if (first < log_len) ++first; - } - return first; -} - -static void print_unsigned_raw(uint64_t value, unsigned base, bool upper) -{ - char buf[32]; - const char *digits = upper ? "0123456789ABCDEF" : "0123456789abcdef"; - size_t i = 0; - - if (value == 0) { - console_emit_raw('0'); - return; - } - - while (value && i < sizeof(buf)) { - buf[i++] = digits[value % base]; - value /= base; - } - while (i) { - console_emit_raw(buf[--i]); - } -} - -void console_emit_timestamp(void) -{ - uint64_t uptime_us = time_uptime_us(); - uint64_t seconds = uptime_us / 1000000ULL; - uint64_t micros = uptime_us % 1000000ULL; - uint64_t divisor = 1ULL; - uint32_t digits = 1U; - - while (seconds >= divisor * 10ULL && digits < 20U) { - divisor *= 10ULL; - ++digits; - } - console_emit_raw('['); - for (uint32_t i = digits; i < 5U; ++i) { - console_emit_raw(' '); - } - print_unsigned_raw(seconds, 10, false); - console_emit_raw('.'); - console_emit_raw((char)('0' + (micros / 100000ULL) % 10ULL)); - console_emit_raw((char)('0' + (micros / 10000ULL) % 10ULL)); - console_emit_raw((char)('0' + (micros / 1000ULL) % 10ULL)); - console_emit_raw((char)('0' + (micros / 100ULL) % 10ULL)); - console_emit_raw((char)('0' + (micros / 10ULL) % 10ULL)); - console_emit_raw((char)('0' + micros % 10ULL)); - console_emit_raw(']'); - console_emit_raw(' '); -} -void console_log_configure(const char *cmdline) -{ - console_log_color_enabled = true; - const char *cursor = cmdline; - while (cursor && *cursor) { - while (*cursor == ' ' || *cursor == '\t' || *cursor == '\r' || *cursor == '\n') ++cursor; - const char *end = cursor; - while (*end && *end != ' ' && *end != '\t' && *end != '\r' && *end != '\n') ++end; - size_t length = (size_t)(end - cursor); - if (length == sizeof("logcolor=0") - 1u) { - if (__builtin_memcmp(cursor, "logcolor=0", length) == 0) - console_log_color_enabled = false; - else if (__builtin_memcmp(cursor, "logcolor=1", length) == 0) - console_log_color_enabled = true; - } - cursor = end; - } -} - -static void console_log_control(const char *sequence) -{ - serial_write(sequence); - for (const char *cursor = sequence; *cursor; ++cursor) { - log_store(*cursor); - if (!console_service_logs_only) { - if (console_vga_text_mode) vga_console_boot_byte(*cursor); - else fb_console_ansi_feed(*cursor); - } - } -} +struct log_format { + char *data; + size_t length; + size_t capacity; + bool truncated; +}; -static void console_log_putc(enum console_log_level level, char character) +static void format_char(struct log_format *output, char ch) { - if (console_line_start && character != '\n' && character != '\r') { - console_emit_timestamp(); - if (console_log_color_enabled) console_log_control(console_log_colors[level]); - const char *prefix = console_log_prefixes[level]; - while (*prefix) console_emit_raw(*prefix++); - if (console_log_color_enabled) console_log_control("\033[0m"); - } - bool line_start = console_line_start; - console_emit_raw(character); - if (character == '\r' && line_start) console_line_start = true; + if (output->length == output->capacity) output->truncated = true; + else output->data[output->length++] = ch ? ch : '?'; } -static void console_log_string(enum console_log_level level, const char *text) +static void format_string(struct log_format *output, const char *text) { - while (text && *text) console_log_putc(level, *text++); + for (; text && *text && !output->truncated; ++text) format_char(output, *text); } -static void console_log_number(enum console_log_level level, uint64_t value, - unsigned base, bool upper, unsigned width, - bool zero_pad, bool negative) +static void format_number(struct log_format *output, uint64_t value, + unsigned base, bool upper, unsigned width, + bool zero_pad, bool negative) { - char digits_buffer[32]; + char buffer[32]; const char *digits = upper ? "0123456789ABCDEF" : "0123456789abcdef"; unsigned count = 0; do { - digits_buffer[count++] = digits[value % base]; + buffer[count++] = digits[value % base]; value /= base; - } while (value && count < sizeof(digits_buffer)); + } while (value); unsigned length = count + (negative ? 1u : 0u); - if (negative && zero_pad) console_log_putc(level, '-'); + if (negative && zero_pad) format_char(output, '-'); while (width > length) { - console_log_putc(level, zero_pad ? '0' : ' '); + format_char(output, zero_pad ? '0' : ' '); --width; } - if (negative && !zero_pad) console_log_putc(level, '-'); - while (count) console_log_putc(level, digits_buffer[--count]); + if (negative && !zero_pad) format_char(output, '-'); + while (count) format_char(output, buffer[--count]); } -void console_vlog(enum console_log_level level, const char *fmt, va_list arguments) +static void format_message(struct log_format *output, const char *fmt, va_list arguments) { - if (!fmt || !*fmt) return; - if ((unsigned)level > CONSOLE_LOG_FATAL) level = CONSOLE_LOG_INFO; - uint64_t flags = kernel_irq_save(); - uint32_t cpu = smp_current_cpu(); - bool acquired = false; - if (__atomic_load_n(&console_log_owner, __ATOMIC_RELAXED) != cpu) { - do { - uint32_t expected = UINT32_MAX; - acquired = __atomic_compare_exchange_n(&console_log_owner, &expected, - cpu, false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED); - if (acquired || level == CONSOLE_LOG_FATAL) break; - smp_membarrier_poll(); - __asm__ volatile("pause" ::: "memory"); - } while (!acquired); - } - - if (!console_line_start) console_emit_raw('\n'); - for (const char *p = fmt; *p; ++p) { + for (const char *p = fmt; *p && !output->truncated; ++p) { if (*p != '%') { - console_log_putc(level, *p); + format_char(output, *p); continue; } ++p; if (!*p) { - console_log_putc(level, '%'); + format_char(output, '%'); break; } bool zero_pad = *p == '0'; @@ -220,11 +102,11 @@ void console_vlog(enum console_log_level level, const char *fmt, va_list argumen switch (*p) { case 's': { const char *text = va_arg(arguments, const char *); - console_log_string(level, text ? text : "(null)"); + format_string(output, text ? text : "(null)"); break; } case 'c': - console_log_putc(level, (char)va_arg(arguments, int)); + format_char(output, (char)va_arg(arguments, int)); break; case 'd': case 'i': { @@ -233,7 +115,7 @@ void console_vlog(enum console_log_level level, const char *fmt, va_list argumen : size_flag ? va_arg(arguments, ptrdiff_t) : va_arg(arguments, int); uint64_t magnitude = value < 0 ? 0ULL - (uint64_t)value : (uint64_t)value; - console_log_number(level, magnitude, 10, false, width, zero_pad, value < 0); + format_number(output, magnitude, 10, false, width, zero_pad, value < 0); break; } case 'u': { @@ -241,7 +123,7 @@ void console_vlog(enum console_log_level level, const char *fmt, va_list argumen : long_flag ? va_arg(arguments, unsigned long) : size_flag ? va_arg(arguments, size_t) : va_arg(arguments, unsigned int); - console_log_number(level, value, 10, false, width, zero_pad, false); + format_number(output, value, 10, false, width, zero_pad, false); break; } case 'x': @@ -250,39 +132,197 @@ void console_vlog(enum console_log_level level, const char *fmt, va_list argumen : long_flag ? va_arg(arguments, unsigned long) : size_flag ? va_arg(arguments, size_t) : va_arg(arguments, unsigned int); - console_log_number(level, value, 16, *p == 'X', width, zero_pad, false); + format_number(output, value, 16, *p == 'X', width, zero_pad, false); break; } case 'p': { uintptr_t value = (uintptr_t)va_arg(arguments, void *); - console_log_string(level, "0x"); - console_log_number(level, value, 16, false, width, zero_pad, false); + format_string(output, "0x"); + format_number(output, value, 16, false, width, zero_pad, false); break; } case '%': - console_log_putc(level, '%'); + format_char(output, '%'); break; default: - console_log_putc(level, '%'); - console_log_putc(level, *p); + format_char(output, '%'); + format_char(output, *p); break; } } - if (!console_line_start) console_emit_raw('\n'); - console_present(); + if (output->truncated) { + static const char marker[] = " ... [truncated]"; + size_t length = sizeof(marker) - 1u; + __builtin_memcpy(output->data + output->length - length, marker, length); + } +} + +/* Text history is shared with boot-screen replay and the lock-free panic owner. + * Regular producers append complete encoded records while owning the logger. */ +static void log_store_bytes(const char *text, size_t length) +{ + size_t added = log_len + length; + if (added > CONSOLE_LOG_CAP) { + size_t keep = (log_start + added - CONSOLE_LOG_CAP) % CONSOLE_LOG_CAP; + log_head_fragment = log_buffer[(keep + CONSOLE_LOG_CAP - 1u) % CONSOLE_LOG_CAP] != '\n'; + } + size_t end = (log_start + log_len) % CONSOLE_LOG_CAP; + size_t first = CONSOLE_LOG_CAP - end; + if (first > length) first = length; + __builtin_memcpy(log_buffer + end, text, first); + __builtin_memcpy(log_buffer, text + first, length - first); + if (added > CONSOLE_LOG_CAP) { + log_start = (log_start + added - CONSOLE_LOG_CAP) % CONSOLE_LOG_CAP; + added = CONSOLE_LOG_CAP; + } + log_len = added; +} + +void log_store(char ch) +{ + log_store_bytes(&ch, 1); +} + +size_t console_log_replay_start(void) +{ + size_t first = 0; + if (!log_screen) return log_len; + if (log_len == CONSOLE_LOG_CAP && log_head_fragment) { + while (first < log_len && log_buffer[(log_start + first) % CONSOLE_LOG_CAP] != '\n') ++first; + if (first < log_len) ++first; + } + return first; +} + +static bool token_is(const char *token, size_t length, const char *value) +{ + return length == __builtin_strlen(value) && !__builtin_memcmp(token, value, length); +} + +void console_log_configure(const char *cmdline) +{ + loglevel = 7; + console_log_color_enabled = true; + log_screen = log_serial = true; + while (cmdline && *cmdline) { + while (*cmdline && (unsigned char)*cmdline <= ' ') ++cmdline; + const char *start = cmdline; + while ((unsigned char)*cmdline > ' ') ++cmdline; + size_t length = (size_t)(cmdline - start); + if (token_is(start, length, "debug")) loglevel = 8; + else if (token_is(start, length, "quiet")) loglevel = 4; + else if (length == 10 && !__builtin_memcmp(start, "loglevel=", 9) && + start[9] >= '0' && start[9] <= '8') loglevel = (unsigned)(start[9] - '0'); + else if (token_is(start, length, "logcolor=0")) console_log_color_enabled = false; + else if (token_is(start, length, "logcolor=1")) console_log_color_enabled = true; + else if (token_is(start, length, "log=screen")) { log_screen = true; log_serial = false; } + else if (token_is(start, length, "log=serial")) { log_screen = false; log_serial = true; } + else if (token_is(start, length, "log=none")) { log_screen = false; log_serial = false; } + else if (token_is(start, length, "log=serial,screen") || token_is(start, length, "log=screen,serial")) + log_screen = log_serial = true; + } +} + +static enum console_log_level normalize_level(enum console_log_level level) +{ + return (unsigned)level <= CONSOLE_LOG_FATAL ? level : CONSOLE_LOG_INFO; +} + +bool console_log_enabled(enum console_log_level level) +{ + level = normalize_level(level); + return level == CONSOLE_LOG_FATAL || (priorities[level] < loglevel && (log_screen || log_serial)); +} + +static bool has_component(const char *text, size_t length) +{ + if (length < 4 || text[0] != '[') return false; + for (size_t i = 1; i < length && i <= 32; ++i) { + unsigned char ch = (unsigned char)text[i]; + if (ch == ']') return i > 1 && i + 1 < length && text[i + 1] == ' '; + if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') || ch == '-' || ch == '_' || ch == '.')) return false; + } + return false; +} + +static void publish_line(enum console_log_level level, uint64_t uptime, + const char *text, size_t length, bool owned) +{ + char record[CONSOLE_LOG_RECORD_BYTES]; + struct log_format line = {.data = record, .capacity = sizeof(record) - 1u}; + if (owned) { + if (uptime < last_timestamp) uptime = last_timestamp; + last_timestamp = uptime; + } + format_char(&line, '['); + format_number(&line, uptime / 1000000u, 10, false, 5, false, false); + format_char(&line, '.'); + format_number(&line, uptime % 1000000u, 10, false, 6, true, false); + format_string(&line, "] "); + if (console_log_color_enabled) format_string(&line, colors[level]); + format_string(&line, prefixes[level]); + if (console_log_color_enabled) format_string(&line, "\033[0m"); + if (!has_component(text, length)) format_string(&line, "[reliefnt] "); + for (size_t i = 0; i < length; ++i) format_char(&line, text[i]); + format_char(&line, '\n'); + record[line.length] = 0; + if (owned) { + log_store_bytes(record, line.length); + if (log_screen || level == CONSOLE_LOG_FATAL) console_emit_display(record, line.length); + } + if (level == CONSOLE_LOG_FATAL) serial_write_emergency(record, line.length); + else if (log_serial) { + if (console_service_logs_only) serial_tx_record(record, line.length, level >= CONSOLE_LOG_WARN); + else serial_write(record); + } +} + +static void console_publish(enum console_log_level level, const char *text, size_t length) +{ + uint64_t uptime = time_uptime_us(); + uint64_t flags = kernel_irq_save(); + uint32_t cpu = smp_current_cpu(); + bool acquired = false; + bool owned = __atomic_load_n(&console_log_owner, __ATOMIC_RELAXED) == cpu; + if (!owned) { + do { + if (__atomic_load_n(&console_log_owner, __ATOMIC_RELAXED) == UINT32_MAX) { + uint32_t expected = UINT32_MAX; + acquired = __atomic_compare_exchange_n(&console_log_owner, &expected, cpu, + false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED); + } + if (acquired || level == CONSOLE_LOG_FATAL) break; + smp_membarrier_poll(); + __asm__ volatile("pause" ::: "memory"); + } while (!acquired); + owned = acquired; + } + for (size_t from = 0; from < length;) { + size_t end = from; + while (end < length && text[end] != '\n') ++end; + size_t line_length = end - from; + if (line_length && text[end - 1u] == '\r') --line_length; + publish_line(level, uptime, text + from, line_length, owned); + from = end + 1u; + } if (acquired) __atomic_store_n(&console_log_owner, UINT32_MAX, __ATOMIC_RELEASE); kernel_irq_restore(flags); } -/** @brief Append one formatted diagnostic through the permanent console/log core. - * @param level Severity selecting the configured log policy. - * @param fmt Borrowed terminated format string. @param ... Values matching fmt. - * IRQ-safe and bounded by the underlying console policy. No caller storage is - * retained; the core restores incoming IRQ state and serial callback pins. - */ +void console_vlog(enum console_log_level level, const char *fmt, va_list arguments) +{ + if (!console_log_enabled(level) || !fmt || !*fmt) return; + char message[CONSOLE_LOG_MESSAGE_BYTES]; + struct log_format output = {.data = message, .capacity = sizeof(message)}; + format_message(&output, fmt, arguments); + console_publish(normalize_level(level), message, output.length); +} + void console_log(enum console_log_level level, const char *fmt, ...) { + if (!console_log_enabled(level)) return; va_list arguments; va_start(arguments, fmt); console_vlog(level, fmt, arguments); @@ -290,12 +330,20 @@ void console_log(enum console_log_level level, const char *fmt, ...) } EXPORT_SYMBOL(console_log); +void console_printf(const char *fmt, ...) +{ + va_list arguments; + va_start(arguments, fmt); + console_vlog(CONSOLE_LOG_INFO, fmt, arguments); + va_end(arguments); +} + void console_log_write(const char *text) { if (!text) return; enum console_log_level level = CONSOLE_LOG_INFO; for (unsigned candidate = CONSOLE_LOG_DEBUG; candidate <= CONSOLE_LOG_FATAL; ++candidate) { - const char *prefix = console_log_prefixes[candidate]; + const char *prefix = prefixes[candidate]; size_t matched = 0; while (prefix[matched] && text[matched] == prefix[matched]) ++matched; if (!prefix[matched]) { @@ -306,3 +354,17 @@ void console_log_write(const char *text) } console_log(level, "%s", text); } + +void console_write_len(const char *text, size_t length) +{ + if (!text || !console_log_enabled(CONSOLE_LOG_INFO)) return; + /* User buffers may fault. Stage them before acquiring logger ownership. */ + char data[CONSOLE_LOG_MESSAGE_BYTES]; + while (length) { + size_t chunk = length < sizeof(data) ? length : sizeof(data); + __builtin_memcpy(data, text, chunk); + console_publish(CONSOLE_LOG_INFO, data, chunk); + text += chunk; + length -= chunk; + } +} diff --git a/drivers/console/panic.c b/drivers/console/panic.c index a2cfe80d..990374e9 100644 --- a/drivers/console/panic.c +++ b/drivers/console/panic.c @@ -1,4 +1,5 @@ #include "internal.h" +#include #include /** @@ -40,6 +41,7 @@ static void console_panic_store(const char *text, size_t length) */ struct console_panic_context console_panic_begin(void) { + serial_panic_quiesce(); const struct framebuffer *active = framebuffer_get(); /* arch_userland_init may have disabled a GOP buffer that cannot survive * the active identity map. Never undo that decision in a fatal path. */ diff --git a/drivers/console/vga_console.c b/drivers/console/vga_console.c index 9ac258c2..024c66ce 100644 --- a/drivers/console/vga_console.c +++ b/drivers/console/vga_console.c @@ -44,7 +44,6 @@ void vga_console_boot_byte(char ch) { if (ch=='\n') vga_terminal_feed(&vga_screens[0],'\r'); vga_terminal_feed(&vga_screens[0],(uint8_t)ch); - if (ch=='\n') vga_console_present(); } /** @brief Send query replies directly to the addressed VT's input, without echo. */ diff --git a/drivers/tty/serial/Kconfig b/drivers/tty/serial/Kconfig index 774e4b13..5ce1dab5 100644 --- a/drivers/tty/serial/Kconfig +++ b/drivers/tty/serial/Kconfig @@ -3,6 +3,6 @@ config SERIAL_8250 tristate "16550 COM1 serial provider" default y help - Native polled COM1 serial output. M builds serial.ko. The permanent TTY - and emergency serial core keep working when the optional provider is - absent; its service calls are pinned until the final byte is written. + Register the built-in COM1 transmitter with the driver manager. M + builds serial.ko. The serial queue and the early and emergency polling + paths keep working when this optional provider is absent. diff --git a/drivers/tty/serial/serial_main.c b/drivers/tty/serial/serial_main.c index 365c9fc0..96811eed 100644 --- a/drivers/tty/serial/serial_main.c +++ b/drivers/tty/serial/serial_main.c @@ -1,56 +1,16 @@ #include -#define COM1 0x3f8 - -static const struct reliefos_driver_kernel_api *kernel_api; -static int serial_ready; - -static int serial_transmit_empty(void) -{ - return kernel_api->inb(COM1 + 5) & 0x20; -} - -static void serial_hardware_init(void) -{ - kernel_api->outb(COM1 + 1, 0x00); - kernel_api->outb(COM1 + 3, 0x80); - kernel_api->outb(COM1 + 0, 0x03); - kernel_api->outb(COM1 + 1, 0x00); - kernel_api->outb(COM1 + 3, 0x03); - kernel_api->outb(COM1 + 2, 0xc7); - kernel_api->outb(COM1 + 4, 0x0b); - serial_ready = 1; -} +#include +#include static int serial_is_ready(void) { - return serial_ready; + return serial_com1_available(); } -static void serial_putc(char ch) +static void serial_write(const char *text) { - if (!serial_ready) { - return; - } - /* Wait for the transmitter-holding-register to empty before writing the - * next byte. Writing unconditionally drops bytes whenever the host drains - * COM1 slower than the guest produces them (boot logs, console spam). The - * wait is bounded so a wedged or absent 16550 can never block the caller - * that may be running with interrupts masked on the execution transaction. */ - for (uint32_t spins = 0u; spins < 100000u && !serial_transmit_empty(); ++spins) { - __asm__ volatile("pause" : : : "memory"); - } - kernel_api->outb(COM1, (uint8_t)ch); -} - -static void serial_write(const char *s) -{ - while (s && *s) { - if (*s == '\n') { - serial_putc('\r'); - } - serial_putc(*s++); - } + if (text) serial_tx_record(text, __builtin_strlen(text), true); } static int serial_driver_init(const struct reliefos_driver_kernel_api *api) @@ -63,17 +23,8 @@ static int serial_driver_init(const struct reliefos_driver_kernel_api *api) api->struct_size < sizeof(*api)) { return -22; } - kernel_api = api; - serial_hardware_init(); - return kernel_api->register_serial(&ops); -} - -static void serial_driver_fini(void) -{ - if (kernel_api) { - kernel_api->outb(COM1 + 1, 0x00); - } - serial_ready = 0; + if (!serial_com1_available()) return -ENODEV; + return api->register_serial(&ops); } const struct reliefos_driver_module serial_driver_module = { @@ -85,5 +36,5 @@ const struct reliefos_driver_module serial_driver_module = { .version = 1U, .reserved = 0, .init = serial_driver_init, - .fini = serial_driver_fini, + .fini = NULL, }; diff --git a/include/reliefnt/console.h b/include/reliefnt/console.h index e3ab957c..aefc63cb 100644 --- a/include/reliefnt/console.h +++ b/include/reliefnt/console.h @@ -13,15 +13,7 @@ */ void console_init(void); /** - * @brief Write a single character to the active console backend. - */ -void console_putc(char ch); -/** - * @brief Write a NUL-terminated string to the console. - */ -void console_write(const char *s); -/** - * @brief Append raw diagnostics to the kernel log and serial sink. + * @brief Append length-delimited input as INFO records in the kernel log. * @param s Bytes to write; need not be NUL-terminated. * @param len Number of bytes to write. */ @@ -72,12 +64,6 @@ struct console_panic_context console_panic_begin(void); void console_panic_write(const char *text, size_t length, uint32_t foreground); /** @brief Publish panic pixels with bounded hardware polling and no locks. */ void console_panic_flush(void); -/** - * @brief Write directly to COM1 without registered drivers or console locks. - * @param text Bytes to send; newline is expanded to CR/LF. - * @param length Number of bytes; polling per character is bounded. - */ -void serial_write_emergency(const char *text, size_t length); /** @brief Select black VGA text attributes, preserving a valid text cursor. */ void vga_panic_begin(void); /** @@ -87,12 +73,27 @@ void vga_panic_begin(void); */ void vga_panic_putc(char ch, uint8_t foreground); /** - * @brief Format INFO-level kernel diagnostics; raw output uses console_write. + * @brief Format INFO-level kernel diagnostics. */ void console_printf(const char *fmt, ...); +/** @brief Set the logging policy on the BSP before concurrent output begins. + * @param cmdline NUL-terminated boot arguments, or NULL for defaults. + */ void console_log_configure(const char *cmdline); +/** @brief Check the immutable boot logging policy without taking a lock. + * @param level Severity of the proposed record. + * @return True when the record should be formatted. + */ +bool console_log_enabled(enum console_log_level level); +/** @brief Format and publish bounded kernel records to enabled sinks. + * @param level Severity of the record. + * @param fmt NUL-terminated kernel format string, with matching arguments. + */ void console_log(enum console_log_level level, const char *fmt, ...); +/** @brief Submit a literal driver message using its optional legacy level prefix. + * @param text NUL-terminated message or NULL. + */ void console_log_write(const char *text); #define console_debug(...) console_log(CONSOLE_LOG_DEBUG, __VA_ARGS__) @@ -121,14 +122,6 @@ void console_enable_vga_fallback(void); * @brief Select the UI color theme used by the framebuffer console. */ void console_set_ui_theme(uint32_t theme); -/** - * @brief Initialize the COM1 serial port for early diagnostic output. - */ -void serial_init(void); -/** - * @brief Return non-zero when the serial backend is available for output. - */ -int serial_is_ready(void); /** * @brief Write a string to the serial backend (or the early COM1 fallback). */ diff --git a/include/reliefnt/serial.h b/include/reliefnt/serial.h new file mode 100644 index 00000000..be858ff7 --- /dev/null +++ b/include/reliefnt/serial.h @@ -0,0 +1,54 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_SERIAL_H +#define RELIEFNT_SERIAL_H + +#include + +/** @brief Check the COM1 hardware independently of the driver inventory. + * @return True if early initialization found a UART. + */ +bool serial_com1_available(void); +/** @brief Probe and initialize COM1 for early output at 115200 baud, 8N1. */ +void serial_init(void); +/** @brief Record the IRQ4 routing result before starting queued transmission. + * @param routed True when the installed interrupt route can deliver IRQ4. + */ +void serial_tx_set_irq(bool routed); +/** @brief Transfer COM1 from boot polling to the queue before entering userspace. */ +void serial_tx_start(void); +/** @brief Acknowledge the UART interrupt and fill at most one transmit FIFO. */ +void serial_tx_irq(void); +/** @brief Attempt a FIFO refill on a PIT tick when queued bytes remain. */ +void serial_tx_tick(void); +/** @brief Drain pending bytes with bounded polling before reset or poweroff. */ +void serial_tx_flush(void); +/** @brief Check whether a terminal write can enqueue any single byte. + * @return True if COM1 is present and room remains for one byte or CR/LF. + */ +bool serial_tx_writable(void); + +/** @brief Submit a complete best-effort diagnostic record or console chunk. + * @param text Kernel-owned bytes copied before return, or NULL to skip output. + * @param length Number of bytes in the buffer, including any line break. + * @param important Permit using the reserve for warnings and errors. + * Runtime submission is safe with interrupts disabled and never polls the UART. + */ +void serial_tx_record(const char *text, size_t length, bool important); + +/** @brief Enqueue user terminal bytes from a staged kernel buffer. + * @param data Kernel-owned source bytes, preserving embedded NULs. + * @param length Maximum input bytes to consume. + * @return Positive input bytes accepted, zero for an empty write, or + * negative ENODEV/EAGAIN. The syscall layer handles blocking retries. + */ +int serial_tx_user(const void *data, size_t length); + +/** @brief Disable UART interrupts after the panic owner stops its peer CPUs. */ +void serial_panic_quiesce(void); +/** @brief Send emergency bytes directly to COM1 using bounded FIFO polling. + * @param text Kernel-owned bytes to transmit or NULL to skip output. + * @param length Number of bytes available in the buffer. + */ +void serial_write_emergency(const char *text, size_t length); + +#endif diff --git a/kernel/device/Kbuild b/kernel/device/Kbuild index 8ab40e1c..f7dfaafa 100644 --- a/kernel/device/Kbuild +++ b/kernel/device/Kbuild @@ -1,4 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 -obj-y := api.o audio_work.o character.o driver_manager_phase.o driver_resources.o early_serial.o graphics_service.o mapping.o registry.o service.o services.o sound_service.o +obj-y := api.o audio_work.o character.o driver_manager_phase.o driver_resources.o graphics_service.o mapping.o registry.o serial_tx.o service.o services.o sound_service.o include $(srctree)/scripts/Makefile.module diff --git a/kernel/device/early_serial.c b/kernel/device/early_serial.c deleted file mode 100644 index 2036b49e..00000000 --- a/kernel/device/early_serial.c +++ /dev/null @@ -1,40 +0,0 @@ -#include "manager_internal.h" - -static void early_serial_putc(char ch); - - -static void early_serial_putc(char ch) -{ - uint32_t attempts = 100000u; - if (!early_serial_ready) { - return; - } - while (!(x86_64_inb((uint16_t)EARLY_SERIAL_LSR) & 0x20u) && attempts--) { - __asm__ volatile("pause"); - } - x86_64_outb((uint8_t)ch, (uint16_t)EARLY_SERIAL_COM1); -} - -void early_serial_write(const char *text) -{ - while (text && *text) { - if (*text == '\n') { - early_serial_putc('\r'); - } - early_serial_putc(*text++); - } -} - -/** - * @brief Bypass driver registration and locks when reporting a fatal failure. - * @param text Bytes to send through the already initialized COM1 UART. - * @param length Number of bytes, independent of NUL termination. - */ -void serial_write_emergency(const char *text, size_t length) -{ - if (!text) return; - for (size_t index = 0; index < length; ++index) { - if (text[index] == '\n') early_serial_putc('\r'); - early_serial_putc(text[index]); - } -} diff --git a/kernel/device/manager_internal.h b/kernel/device/manager_internal.h index 2ff25d36..5dfbfc5b 100644 --- a/kernel/device/manager_internal.h +++ b/kernel/device/manager_internal.h @@ -25,20 +25,6 @@ #include "../../arch/x86_64/port.h" -#define EARLY_SERIAL_COM1 0x3f8u -#define EARLY_SERIAL_LSR (EARLY_SERIAL_COM1 + 5u) - -/* Kernel diagnostics must be available before the serial driver registers. - * Keep a tiny COM1 backend here; the driver later replaces it through - * register_serial(), without changing the public console API. */ - - - - - - - - struct driver_slot { struct reliefos_driver_info info; const struct reliefos_driver_module *module; @@ -49,7 +35,6 @@ struct driver_slot { }; -extern int early_serial_ready; extern struct driver_slot driver_slots[RELIEFOS_DRIVER_MAX]; extern int32_t loading_slot; extern int32_t cleanup_slot; @@ -65,19 +50,9 @@ extern uint32_t audio_generation, audio_lease_generation; extern struct mouse_state mouse_cache; extern struct kernel_spinlock manager_service_lock; -/** @brief Borrow the immutable driver services used by builtin and native modules. - * @return Permanent kernel-owned service table; no locks or callbacks. - */ -const struct reliefos_driver_kernel_api *driver_kernel_services(void); - -void early_serial_write(const char *text); -/** - * @brief Bypass driver registration and locks when reporting a fatal failure. - * @param text Bytes to send through the already initialized COM1 UART. - * @param length Number of bytes, independent of NUL termination. - */ -void serial_write_emergency(const char *text, size_t length); +/** @brief Borrow the immutable driver services used by builtin and native modules. */ +const struct reliefos_driver_kernel_api *driver_kernel_services(void); /** * @brief Zero size bytes starting at address. @@ -309,25 +284,6 @@ uint8_t driver_manager_mouse_last_ack(void); */ void driver_manager_mouse_poll(void); -/** - * @brief Program the COM1 UART (baud, frame format, FIFO, IRQ) and enable the early serial path. - */ -void serial_init(void); - -/** - * @brief Return 1 when a serial driver is registered and reports ready. - * @return Driver result or 0 while absent/closing; one consistent ops/owner pin - * spans is_ready, with no manager lock held during the callback. - */ -int serial_is_ready(void); - -/** - * @brief Write text through the serial driver, or the built-in COM1 path before one loads. - * @param text Kernel-owned NUL-terminated text borrowed through callback return. - * @return None. The matching local ops/owner snapshot stays pinned across write. - */ -void serial_write(const char *text); - /** * @brief Reserved startup hook; the NIC is brought up by its driver's init(). */ diff --git a/kernel/device/registry.c b/kernel/device/registry.c index 76137023..df5d4511 100644 --- a/kernel/device/registry.c +++ b/kernel/device/registry.c @@ -1,3 +1,4 @@ +#include #include #include "manager_internal.h" #include @@ -65,7 +66,6 @@ static int driver_load_registered(struct driver_slot *slot, -int early_serial_ready; struct driver_slot driver_slots[RELIEFOS_DRIVER_MAX]; @@ -136,9 +136,11 @@ static void driver_set_error(struct driver_slot *slot, int status, const char *e slot->info.state = RELIEFOS_DRIVER_STATE_FAILED; driver_copy_text(slot->info.error, sizeof(slot->info.error), error); if (status < 0) { - console_log(status == -19 ? CONSOLE_LOG_INFO : CONSOLE_LOG_ERROR, - "[driver] %s failed status=%d: %s\n", slot->info.file, - status, slot->info.error); + if (status == -ENODEV) + console_debug("[driver] %s hardware not present\n", slot->info.file); + else + console_error("[driver] %s failed status=%d: %s\n", slot->info.file, + status, slot->info.error); } } @@ -421,7 +423,7 @@ int driver_module_register(const struct reliefos_driver_module *descriptor,struc if(ret) { driver_memzero(slot,sizeof(*slot)); goto done; } } ret=driver_load_registered(slot,descriptor); - if(ret==-19) ret=0; + if(ret==-ENODEV) ret=0; done: driver_manager_phase_leave(); return ret; diff --git a/kernel/device/serial_tx.c b/kernel/device/serial_tx.c new file mode 100644 index 00000000..e01009f2 --- /dev/null +++ b/kernel/device/serial_tx.c @@ -0,0 +1,319 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include +#include +#include +#include +#include +#include +#include +#include "../../arch/x86_64/port.h" + +#define UART_COM1 0x3f8u +#define UART_IER (UART_COM1 + 1u) +#define UART_IIR (UART_COM1 + 2u) +#define UART_FCR (UART_COM1 + 2u) +#define UART_LCR (UART_COM1 + 3u) +#define UART_MCR (UART_COM1 + 4u) +#define UART_LSR (UART_COM1 + 5u) +#define UART_THRE 0x20u +#define UART_TEMT 0x40u +#define UART_TX_IRQ 0x02u +#define UART_FIFO_FLAGS 0xc0u +#define UART_FIFO_BYTES 16u +#define UART_POLL_LIMIT 100000u +#define UART_TX_CAP 32768u +#define UART_LOG_RESERVE 2048u + +static struct kernel_spinlock tx_lock = KERNEL_SPINLOCK_INIT; +static unsigned char tx_bytes[UART_TX_CAP]; +static size_t tx_read, tx_used; +static unsigned fifo_bytes = 1; +static bool uart_present, irq_routed, tx_running, tx_irq_enabled; +static bool last_was_cr, polled_last_was_cr; +static bool tx_pending; +static unsigned dropped_records; + +/** @brief Check the COM1 hardware independently of the driver inventory. + * @return True if early initialization found a UART. + */ +bool serial_com1_available(void) +{ + return uart_present; +} +EXPORT_SYMBOL(serial_com1_available); + +/** @brief Probe and initialize COM1 for early output at 115200 baud, 8N1. */ +void serial_init(void) +{ + if (x86_64_inb(UART_LSR) == 0xffu) return; + x86_64_outb(0, UART_IER); + x86_64_outb(0x80u, UART_LCR); + /* 115200 8N1, matching the GRUB serial terminal. */ + x86_64_outb(1, UART_COM1); + x86_64_outb(0, UART_IER); + x86_64_outb(3, UART_LCR); + x86_64_outb(7, UART_FCR); + if ((x86_64_inb(UART_IIR) & UART_FIFO_FLAGS) == UART_FIFO_FLAGS) + fifo_bytes = UART_FIFO_BYTES; + else + x86_64_outb(0, UART_FCR); + x86_64_outb(0x0bu, UART_MCR); + uart_present = true; +} + +/** @brief Record the IRQ4 routing result before starting queued transmission. + * @param routed True when the installed interrupt route can deliver IRQ4. + */ +void serial_tx_set_irq(bool routed) +{ + irq_routed = routed; +} + +/** @brief Transfer COM1 from boot polling to the queue before entering userspace. */ +void serial_tx_start(void) +{ + last_was_cr = polled_last_was_cr; + __atomic_store_n(&tx_running, uart_present, __ATOMIC_RELEASE); +} + +/** @brief Poll for a transmitter state without sleeping. + * @param mask Status bits sought in the line status register. + * @return True when any requested bit is set before the cap. + */ +static bool uart_wait(unsigned mask) +{ + for (unsigned attempt = 0; attempt < UART_POLL_LIMIT; ++attempt) { + uint8_t status = x86_64_inb(UART_LSR); + if (status == 0xffu) return false; + if (status & mask) return true; + __asm__ volatile("pause" ::: "memory"); + } + return false; +} + +/** @brief Fill the UART in batches during early boot and emergency output. + * @param data Borrowed kernel buffer under boot or emergency ownership. + * @param length Available source bytes, including embedded NULs. + * @return Number of input bytes sent before a timeout. A single-byte UART may + * send the two bytes of a translated newline in separate FIFO refills. + */ +static size_t uart_polled_write(const char *data, size_t length) +{ + size_t consumed = 0; + while (consumed != length && uart_wait(UART_THRE)) { + for (unsigned slot = 0; slot < fifo_bytes && consumed != length; ++slot) { + char byte = data[consumed]; + if (byte == '\n' && !polled_last_was_cr) { + x86_64_outb('\r', UART_COM1); + polled_last_was_cr = true; + continue; + } + x86_64_outb((uint8_t)byte, UART_COM1); + polled_last_was_cr = byte == '\r'; + ++consumed; + } + } + return consumed; +} + +/** @brief Append one byte to the ring with TX locked and space available. + * @param byte Encoded byte to enqueue. + */ +static void queue_byte(unsigned char byte) +{ + tx_bytes[(tx_read + tx_used) & (UART_TX_CAP - 1u)] = byte; + ++tx_used; +} + +/** @brief Publish pending work and enable THRE interrupts only with queued bytes. */ +static void uart_arm_locked(void) +{ + bool pending = tx_used != 0; + bool want_irq = irq_routed && pending; + if (want_irq != tx_irq_enabled) { + x86_64_outb(want_irq ? UART_TX_IRQ : 0, UART_IER); + tx_irq_enabled = want_irq; + } + __atomic_store_n(&tx_pending, pending, __ATOMIC_RELEASE); +} + +/** @brief Check the user write allowance while the TX lock is held. + * @return True if any byte, including a translated LF, can fit outside the reserve. + */ +static bool uart_writable_locked(void) +{ + return UART_TX_CAP - tx_used >= UART_LOG_RESERVE + 2u; +} + +/** @brief Check whether a terminal write can enqueue any single byte. + * @return True if COM1 is present and room remains for one byte or CR/LF. + */ +bool serial_tx_writable(void) +{ + if (!uart_present) return false; + uint64_t flags; + kernel_spin_lock_irqsave(&tx_lock, &flags); + bool writable = uart_writable_locked(); + kernel_spin_unlock_irqrestore(&tx_lock, flags); + return writable; +} + +/** @brief Transfer at most one batch and notify waiters after unlocking. + * @param from_irq True to acknowledge THRE via IIR even if the queue emptied. + */ +static void uart_pump(bool from_irq) +{ + if (!from_irq && !__atomic_load_n(&tx_pending, __ATOMIC_ACQUIRE)) return; + uint64_t flags; + kernel_spin_lock_irqsave(&tx_lock, &flags); + if (from_irq) (void)x86_64_inb(UART_IIR); + bool notify = false; + unsigned dropped = 0; + if (tx_used) { + uint8_t status = x86_64_inb(UART_LSR); + if (status != 0xffu && (status & UART_THRE)) { + bool was_writable = uart_writable_locked(); + size_t count = tx_used < fifo_bytes ? tx_used : fifo_bytes; + for (size_t i = 0; i < count; ++i) { + x86_64_outb(tx_bytes[tx_read], UART_COM1); + tx_read = (tx_read + 1u) & (UART_TX_CAP - 1u); + } + tx_used -= count; + notify = !was_writable && uart_writable_locked(); + if (!tx_used) { + dropped = dropped_records; + dropped_records = 0; + } + } + } + uart_arm_locked(); + kernel_spin_unlock_irqrestore(&tx_lock, flags); + if (notify) { + storage_completion_notify(); + kernel_poll_readiness_notify(); + } + /* The logger can enqueue to this UART. Report lost output only after + * releasing the TX lock, once the preceding backlog has drained. */ + if (dropped) + console_warn("[serial] transmit queue full, dropped %u records or console chunks\n", dropped); +} + +/** @brief Acknowledge the UART interrupt and fill at most one transmit FIFO. */ +void serial_tx_irq(void) +{ + if (uart_present) uart_pump(true); +} + +/** @brief Attempt a FIFO refill on a PIT tick when queued bytes remain. */ +void serial_tx_tick(void) +{ + uart_pump(false); +} + +/** @brief Copy and translate bytes into the bounded ring with local IRQs masked. + * @param data Kernel-owned buffer valid for length bytes. + * @param length Available input bytes. + * @param record Whole-record mode, with drop accounting when it cannot fit. + * @param important Permission to consume the diagnostic reserve. + * @return Number of input bytes enqueued. CR/LF expansion does not count. + */ +static size_t uart_enqueue(const char *data, size_t length, bool record, bool important) +{ + uint64_t flags; + kernel_spin_lock_irqsave(&tx_lock, &flags); + size_t available = UART_TX_CAP - tx_used; + if (!important) + available = available > UART_LOG_RESERVE ? available - UART_LOG_RESERVE : 0; + if (record) { + size_t needed = length; + bool previous_cr = last_was_cr; + for (size_t i = 0; i < length && needed <= available; ++i) { + if (data[i] == '\n' && !previous_cr) ++needed; + previous_cr = data[i] == '\r'; + } + if (needed > available) { + if (dropped_records != UINT32_MAX) ++dropped_records; + kernel_spin_unlock_irqrestore(&tx_lock, flags); + return 0; + } + } + size_t consumed = 0; + while (consumed < length && available) { + char byte = data[consumed]; + if (byte == '\n' && !last_was_cr) { + if (available < 2u) break; + queue_byte('\r'); + --available; + } + queue_byte((unsigned char)byte); + last_was_cr = byte == '\r'; + --available; + ++consumed; + } + uart_arm_locked(); + kernel_spin_unlock_irqrestore(&tx_lock, flags); + return consumed; +} + +/** @brief Submit a complete best-effort diagnostic record or console chunk. + * @param text Kernel-owned bytes copied before return, or NULL to skip output. + * @param length Number of bytes in the buffer, including any line break. + * @param important Permit using the reserve for warnings and errors. + * Runtime submission is safe with interrupts disabled and never polls the UART. + */ +void serial_tx_record(const char *text, size_t length, bool important) +{ + if (!uart_present || !text || !length) return; + if (__atomic_load_n(&tx_running, __ATOMIC_ACQUIRE)) { + (void)uart_enqueue(text, length, true, important); + return; + } + /* Early writers are already serialized by the boot console. */ + (void)uart_polled_write(text, length); +} +EXPORT_SYMBOL(serial_tx_record); + +/** @brief Enqueue user terminal bytes from a staged kernel buffer. + * @param data Kernel-owned source bytes, preserving embedded NULs. + * @param length Maximum input bytes to consume. + * @return Positive input bytes accepted, zero for an empty write, or + * negative ENODEV/EAGAIN. The syscall layer handles blocking retries. + */ +int serial_tx_user(const void *data, size_t length) +{ + if (!length) return 0; + if (!uart_present) return -ENODEV; + size_t written = uart_enqueue(data, length, false, false); + /* The syscall retry path sleeps interruptibly for a blocking descriptor. + * A nonblocking descriptor returns EAGAIN directly to the caller. */ + return written ? (int)written : -EAGAIN; +} + +/** @brief Drain pending bytes with bounded polling before reset or poweroff. */ +void serial_tx_flush(void) +{ + if (!uart_present) return; + /* Shutdown can complete with interrupts disabled. Bound the number of + * successful refills as well as each hardware wait. */ + for (size_t i = 0; i < UART_TX_CAP + UART_LOG_RESERVE && + __atomic_load_n(&tx_pending, __ATOMIC_ACQUIRE); ++i) { + if (!uart_wait(UART_THRE)) break; + uart_pump(false); + } + (void)uart_wait(UART_TEMT); +} + +/** @brief Disable UART interrupts after the panic owner stops its peer CPUs. */ +void serial_panic_quiesce(void) +{ + if (uart_present) x86_64_outb(0, UART_IER); +} + +/** @brief Send emergency bytes directly to COM1 using bounded FIFO polling. + * @param text Kernel-owned bytes to transmit or NULL to skip output. + * @param length Number of bytes available in the buffer. + */ +void serial_write_emergency(const char *text, size_t length) +{ + if (uart_present && text) (void)uart_polled_write(text, length); +} diff --git a/kernel/device/services.c b/kernel/device/services.c index 8e701ebb..ee3c7c94 100644 --- a/kernel/device/services.c +++ b/kernel/device/services.c @@ -1,3 +1,4 @@ +#include #include #include #include @@ -356,52 +357,22 @@ uint8_t mouse_last_ack(void) return state.last_ack; } -/** - * @brief Program the COM1 UART (baud, frame format, FIFO, IRQ) and enable the early serial path. - */ -void serial_init(void) -{ - x86_64_outb(0x00u, (uint16_t)(EARLY_SERIAL_COM1 + 1u)); - x86_64_outb(0x80u, (uint16_t)(EARLY_SERIAL_COM1 + 3u)); - x86_64_outb(0x03u, (uint16_t)(EARLY_SERIAL_COM1 + 0u)); - x86_64_outb(0x00u, (uint16_t)(EARLY_SERIAL_COM1 + 1u)); - x86_64_outb(0x03u, (uint16_t)(EARLY_SERIAL_COM1 + 3u)); - x86_64_outb(0xc7u, (uint16_t)(EARLY_SERIAL_COM1 + 2u)); - x86_64_outb(0x0bu, (uint16_t)(EARLY_SERIAL_COM1 + 4u)); - early_serial_ready = 1; -} - -/** - * @brief Return 1 when a serial driver is registered and reports ready. - * @return Driver result or 0 while absent/closing; one consistent ops/owner pin - * spans is_ready, with no manager lock held during the callback. - */ -int serial_is_ready(void) -{ - uint32_t owner; - const struct reliefos_driver_serial_ops *ops = driver_serial_service_pin(&owner); - if (!ops) return 0; - int ready = ops->is_ready ? ops->is_ready() : 0; - driver_manager_service_unpin(owner); - return ready; -} - /** * @brief Write text through the serial driver, or the built-in COM1 path before one loads. * @param text Kernel-owned NUL-terminated text borrowed through callback return. - * @return None. The matching local ops/owner snapshot stays pinned across write. + * The matching local ops/owner snapshot stays pinned across write. */ void serial_write(const char *text) { uint32_t owner; const struct reliefos_driver_serial_ops *ops = driver_serial_service_pin(&owner); - if (ops && ops->write) { + if (ops && ops->write && (!ops->is_ready || ops->is_ready())) { ops->write(text); driver_manager_service_unpin(owner); return; } if (ops) driver_manager_service_unpin(owner); - early_serial_write(text); + if (text) serial_tx_record(text, __builtin_strlen(text), true); } /** @brief Register a provider context without exposing it before init succeeds. diff --git a/kernel/exec/userland.c b/kernel/exec/userland.c index 57164a8c..cebac3cc 100644 --- a/kernel/exec/userland.c +++ b/kernel/exec/userland.c @@ -644,10 +644,6 @@ static int userland_load_task_image_locked(struct task *task, const struct task } task->flags |= TASK_FLAG_STARTED; - console_debug("[reliefnt] %s prepared lazy Ring-3 image entry=0x%llx cr3=0x%llx\n", - task->name, - (unsigned long long)task->entry, - (unsigned long long)(*sched_task_as(task)).cr3); return 0; } diff --git a/kernel/init/kernel.c b/kernel/init/kernel.c index c006ff1c..0b402a3b 100644 --- a/kernel/init/kernel.c +++ b/kernel/init/kernel.c @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -287,7 +288,7 @@ static void kernel_start(uint32_t magic, uintptr_t multiboot_info) /** * @brief Parse ACPI before the physical allocator can reclaim ACPI memory. */ - console_info("[boot] discovering ACPI power controls and SMBIOS identity\n"); + console_debug("[boot] discovering ACPI power controls and SMBIOS identity\n"); power_init(&boot); if (power_acpi_capture_resources() < 0) panic("Unable to preserve ACPI boot resources"); @@ -298,7 +299,7 @@ static void kernel_start(uint32_t magic, uintptr_t multiboot_info) dmi->values[0], dmi->values[1], dmi->values[3], dmi->values[4]); } - console_info("[boot] discovering interrupt controllers and CPU topology limit=%u\n", SMP_MAX_CPUS); + console_debug("[boot] discovering interrupt controllers and CPU topology limit=%u\n", SMP_MAX_CPUS); arch_init(); apic_init(); ioapic_init(); @@ -308,11 +309,11 @@ static void kernel_start(uint32_t magic, uintptr_t multiboot_info) console_info("[cpu] vendor=%s model=%s family=%u model_id=%u stepping=%u apic=%u\n", cpu_info->vendor, cpu_info->model_name, cpu_info->family, cpu_info->model, cpu_info->stepping, cpu_info->apic_id); - console_info("[cpu] cpuid_features ecx=0x%08x edx=0x%08x base_mhz=%u max_mhz=%u\n", + console_debug("[cpu] cpuid_features ecx=0x%08x edx=0x%08x base_mhz=%u max_mhz=%u\n", cpu_info->leaf1_ecx, cpu_info->leaf1_edx, cpu_info->base_mhz, cpu_info->max_mhz); } - console_info("[boot] initializing display and physical page allocator\n"); + console_debug("[boot] initializing display and physical page allocator\n"); /* Install the shared supervisor direct map before mm_init reads or writes * any physical page through its alias. Initialize it before framebuffer * setup as that path also converts the firmware-provided physical surface. */ @@ -365,7 +366,7 @@ static void kernel_start(uint32_t magic, uintptr_t multiboot_info) console_info("[boot] kernel_console=%s theme=%s serial=%s\n", console_vga_text_mode ? "VGA-text" : framebuffer_get()->available ? "framebuffer" : "VGA", boot_theme == 0u ? "win95" : "metro", - serial_is_ready() ? "driver" : "early-COM1"); + serial_com1_available() ? "COM1" : "unavailable"); sched_init(); sched_create_idle_task(); syscall_init(); @@ -376,7 +377,7 @@ static void kernel_start(uint32_t magic, uintptr_t multiboot_info) * the CPU still holds the firmware IDT, whose gates select firmware GDT * segments and triple fault on delivery after the GDT switch. */ idt_init(); - console_info("[boot] GDT/TSS/IDT installed\n"); + console_debug("[boot] GDT/TSS/IDT installed\n"); irq_init(); driver_manager_init(); { @@ -430,16 +431,16 @@ static void kernel_start(uint32_t magic, uintptr_t multiboot_info) kernel_idle_loop(); } } - console_info("[boot] loading built-in mouse, serial, network and audio drivers\n"); + console_debug("[boot] loading built-in mouse, serial, network and audio drivers\n"); driver_manager_load_builtin(); - console_info("[boot] input providers initialized; initializing IPv4 networking\n"); + console_debug("[boot] input providers initialized; initializing IPv4 networking\n"); net_init(); if (boot_log_pause) boot_log_wait_for_enter(); if (pty_vt_init() < 0) { console_fatal("[reliefnt] unable to initialize six virtual terminals\n"); kernel_idle_loop(); } - console_info("[boot] virtual terminals tty1-tty6 ready; preparing PID 1\n"); + console_debug("[boot] virtual terminals tty1-tty6 ready; preparing PID 1\n"); userland_init(&boot); /* The PM clock and task table are ready, with no shared locks held. * Give the BSP the same local preemption checks as the APs while the PIT @@ -463,6 +464,7 @@ static void kernel_start(uint32_t magic, uintptr_t multiboot_info) console_boot_complete(); console_vt_activate(1, false); + serial_tx_start(); userland_enter_first(); kernel_idle_loop(); } diff --git a/kernel/syscall/device/device_io.c b/kernel/syscall/device/device_io.c index 6faf440a..8b64e89e 100644 --- a/kernel/syscall/device/device_io.c +++ b/kernel/syscall/device/device_io.c @@ -1,3 +1,4 @@ +#include #include "../internal.h" @@ -157,19 +158,21 @@ int task_device_write(struct task *task, struct task_file *file, return (int)length; } if (task_device_is(file, STORAGE_DEV_KIND_SERIAL)) { - const char *src = (const char *)buffer; - uint32_t done = 0; + if (!length) return 0; if (!buffer) return -RELIEFOS_EFAULT; - /* The serial driver exposes a string-oriented backend. Keep each - * temporary chunk bounded and preserve the write length. */ + /* Stage a bounded chunk before taking the TX lock. A user mapping + * must not fault while the interrupt handler's queue lock is held. */ + char bytes[512]; + const char *source = buffer; + size_t done = 0; while (done < length) { - char chunk[128]; - uint32_t take = length - done; - if (take >= sizeof(chunk)) take = sizeof(chunk) - 1u; - for (uint32_t i = 0; i < take; ++i) chunk[i] = src[done + i]; - chunk[take] = 0; - serial_write(chunk); - done += take; + size_t take = length - done; + if (take > sizeof(bytes)) take = sizeof(bytes); + __builtin_memcpy(bytes, source + done, take); + int result = serial_tx_user(bytes, take); + if (result < 0) return done ? (int)done : result; + done += (size_t)result; + if ((size_t)result < take) break; } return (int)done; } diff --git a/kernel/syscall/entry.c b/kernel/syscall/entry.c index 1185e57a..de261764 100644 --- a/kernel/syscall/entry.c +++ b/kernel/syscall/entry.c @@ -103,6 +103,7 @@ static int syscall_eagain_is_nonblocking_device(struct task *task, (task_device_is(file, STORAGE_DEV_KIND_KEYBOARD) || task_device_is(file, STORAGE_DEV_KIND_MOUSE) || task_device_is(file, STORAGE_DEV_KIND_CONSOLE) || + task_device_is(file, STORAGE_DEV_KIND_SERIAL) || task_device_is(file, STORAGE_DEV_KIND_AUDIO) || (file->node.flags & (STORAGE_NODE_FLAG_AUDIO_CONTROL | STORAGE_NODE_FLAG_AUDIO_TIMER)))) { @@ -319,7 +320,7 @@ struct task *syscall_dispatch_frame(struct trap_frame *frame) number = frame->rax; struct task *calling_task = sched_current_task(); bool trace = syscall_trace_task(calling_task); - if (trace) console_debug("[syscall-trace] pid=%u nr=%llu args=%llx,%llx,%llx,%llx,%llx,%llx\n", + if (trace) console_info("[syscall-trace] pid=%u nr=%llu args=%llx,%llx,%llx,%llx,%llx,%llx\n", calling_task->pid, (unsigned long long)number, (unsigned long long)frame->rdi, (unsigned long long)frame->rsi, (unsigned long long)frame->rdx, (unsigned long long)frame->r10, @@ -417,7 +418,7 @@ struct task *syscall_dispatch_frame(struct trap_frame *frame) frame->error = 0; restored_signal_frame = 1; } - if (trace) console_debug("[syscall-trace] pid=%u nr=%llu result=%lld\n", + if (trace) console_info("[syscall-trace] pid=%u nr=%llu result=%lld\n", calling_task->pid, (unsigned long long)number, (long long)result); eagain_from_nonblocking = result == -RELIEFOS_EAGAIN && diff --git a/kernel/syscall/event/poll.c b/kernel/syscall/event/poll.c index 869a2aa9..ba2ce36f 100644 --- a/kernel/syscall/event/poll.c +++ b/kernel/syscall/event/poll.c @@ -1,3 +1,4 @@ +#include #include "../internal.h" #include @@ -114,8 +115,17 @@ static int64_t syscall_poll_impl_core(struct task *task, struct pollfd *fds, } else if (file && file->character_file) { revents=character_file_poll(file->character_file,file,events); } else if (file && (file->flags & TASK_FILE_FLAG_DEV_NODE)) { - if (task_device_is(file, STORAGE_DEV_KIND_KEYBOARD) || - task_device_is(file, STORAGE_DEV_KIND_MOUSE)) { + if (task_device_is(file, STORAGE_DEV_KIND_SERIAL)) { + if (!serial_com1_available()) revents |= POLLERR; + else { + /* This diagnostic device has no receive path. A read + * still completes immediately with EOF. */ + revents |= events & (POLLIN | POLLRDNORM); + if (file_can_write(file) && serial_tx_writable()) + revents |= events & (POLLOUT | POLLWRNORM); + } + } else if (task_device_is(file, STORAGE_DEV_KIND_KEYBOARD) || + task_device_is(file, STORAGE_DEV_KIND_MOUSE)) { task_evdev_bind_vt(task, file); if ((events & POLLIN) && input_evdev_available_vt(file->node.first_cluster, file->aux, @@ -137,6 +147,7 @@ static int64_t syscall_poll_impl_core(struct task *task, struct pollfd *fds, !task_device_is(file, STORAGE_DEV_KIND_TTY) && !task_device_is(file, STORAGE_DEV_KIND_CONSOLE) && !task_device_is(file, STORAGE_DEV_KIND_AUDIO) && + !task_device_is(file, STORAGE_DEV_KIND_SERIAL) && !(file->node.flags & (STORAGE_NODE_FLAG_AUDIO_CONTROL | STORAGE_NODE_FLAG_AUDIO_MIXER))) { revents |= POLLOUT; diff --git a/kernel/syscall/io/io.c b/kernel/syscall/io/io.c index 408cd472..d211d914 100644 --- a/kernel/syscall/io/io.c +++ b/kernel/syscall/io/io.c @@ -185,7 +185,7 @@ int64_t syscall_io_write(uint64_t a0, uint64_t a1, uint64_t a2) request_len = a2 > RELIEFOS_FS_IO_SLICE_BYTES ? RELIEFOS_FS_IO_SLICE_BYTES : (uint32_t)a2; - console_write_len((const char *)(uintptr_t)a1, (size_t)request_len); + console_serial_write_len((const char *)(uintptr_t)a1, (size_t)request_len); return (int64_t)request_len; } struct task_file *file = task_file_for_io(task, (int)a0); diff --git a/tools/test_console.py b/tools/test_console.py index 717effc3..57fa65aa 100644 --- a/tools/test_console.py +++ b/tools/test_console.py @@ -35,6 +35,17 @@ def test_framebuffer_character_edits(self): subprocess.run(command, cwd=ROOT, check=True) subprocess.run([binary], check=True, timeout=30) + def test_serial_transmit_queue(self): + with tempfile.TemporaryDirectory(prefix="reliefnt-serial-") as tmp: + binary = str(Path(tmp) / "serial") + subprocess.run([ + "clang", "-std=c11", "-g", "-O1", "-Wall", "-Wextra", "-Werror", + "-fsanitize=address,undefined", "-fno-sanitize-recover=all", + "-Iinclude", "-Iinclude/uapi", "-no-pie", + "tools/tests/serial_tx_test.c", "kernel/device/serial_tx.c", "-o", binary, + ], cwd=ROOT, check=True) + subprocess.run([binary], check=True, timeout=10) + def test_console_cursor_and_background_output(self): with tempfile.TemporaryDirectory(prefix="reliefos-vt-console-") as tmp: binary = str(Path(tmp) / "console") diff --git a/tools/tests/console_replay_test.c b/tools/tests/console_replay_test.c index b89e4c73..f3938b66 100644 --- a/tools/tests/console_replay_test.c +++ b/tools/tests/console_replay_test.c @@ -102,10 +102,9 @@ static void initialize_console_state(void) vga_console_enabled = false; fb_x = fb_y = fb_cols = fb_rows = fb_col = fb_row = 0; console_ui_theme = 1u; - console_line_start = true; console_service_logs_only = false; console_presenting = false; - console_log_color_enabled = false; + console_log_configure("logcolor=0"); vga_ansi_state = 0; console_log_owner = UINT32_MAX; fb_saved_col = fb_saved_row = 0; diff --git a/tools/tests/descriptor_table_test.c b/tools/tests/descriptor_table_test.c index c621aa0a..8e81db2e 100644 --- a/tools/tests/descriptor_table_test.c +++ b/tools/tests/descriptor_table_test.c @@ -368,7 +368,10 @@ void console_serial_write_len(const char *text, size_t length) { (void)text; (void)length; abort(); } void console_write_len(const char *text, size_t length) { (void)text; (void)length; abort(); } -void serial_write(const char *text) { (void)text; abort(); } +bool serial_com1_available(void) { return false; } +bool serial_tx_writable(void) { abort(); } +int serial_tx_user(const void *bytes, size_t length) +{ (void)bytes; (void)length; abort(); } int task_pipe_write(struct task_file *file, const void *buffer, uint32_t length) { assert(file && file->aux==0xf001 && transfer_pipe_mode); diff --git a/tools/tests/keyboard_irq_ready_test.c b/tools/tests/keyboard_irq_ready_test.c index 5fdd6b6c..4e5a971c 100644 --- a/tools/tests/keyboard_irq_ready_test.c +++ b/tools/tests/keyboard_irq_ready_test.c @@ -30,6 +30,9 @@ void input_handle_scancode(uint8_t key, uint8_t pressed) void pci_irq_dispatch(uint32_t vector) { (void)vector; } void apic_eoi(void) { ++apic_eois; } void time_on_tick(void) { ++global_ticks; } +/* No COM1 is present in this fixture. */ +void serial_tx_tick(void) {} +void serial_tx_irq(void) { assert(0 && "unexpected COM1 interrupt"); } uint64_t time_uptime_us(void) { return 0; } uint8_t input_caps_lock_active(void) { return 0; } struct task *userland_schedule_from_frame(struct trap_frame *frame) diff --git a/tools/tests/modules/console.h b/tools/tests/modules/console.h index 8b84d425..8cc1b5c7 100644 --- a/tools/tests/modules/console.h +++ b/tools/tests/modules/console.h @@ -1,6 +1,8 @@ /* Test-only white-box composition of the separately built production units. */ #ifndef RELIEFNT_TEST_MODULE_CONSOLE_H #define RELIEFNT_TEST_MODULE_CONSOLE_H +#include +#include #include #include #ifndef VGA_CONSOLE_TEST_HW @@ -14,6 +16,22 @@ void vga_text_hw_panic(void) {} void pty_vt_reply(uint32_t n,const char *b,size_t l) {(void)n;(void)b;(void)l;} #endif #endif +/* These fixtures exercise console rendering and record formatting. Only the + * standalone UART fixture supplies hardware port behavior. */ +void serial_tx_record(const char *text, size_t length, bool important) +{ + (void)important; + char terminated[1024]; + assert(length < sizeof(terminated)); + memcpy(terminated, text, length); + terminated[length] = 0; + serial_write(terminated); +} +#ifndef CONSOLE_TEST_PANIC_SERIAL +void serial_write_emergency(const char *text, size_t length) +{ serial_tx_record(text, length, true); } +void serial_panic_quiesce(void) {} +#endif #include "../../../drivers/console/vga_terminal.c" #include "../../../drivers/console/vga_ansi.c" #include "../../../drivers/console/vga_console.c" diff --git a/tools/tests/modules/driver_manager.h b/tools/tests/modules/driver_manager.h index d1395cb5..1e11f9e9 100644 --- a/tools/tests/modules/driver_manager.h +++ b/tools/tests/modules/driver_manager.h @@ -1,5 +1,5 @@ /* Test-only production module composition. */ -#include "../../../kernel/device/early_serial.c" +#include "../../../kernel/device/serial_tx.c" #include "../../../kernel/device/registry.c" #include "../../../kernel/device/services.c" #include "../../../kernel/device/api.c" diff --git a/tools/tests/panic_console_runtime_test.c b/tools/tests/panic_console_runtime_test.c index 62ee8e1f..74a4edd3 100644 --- a/tools/tests/panic_console_runtime_test.c +++ b/tools/tests/panic_console_runtime_test.c @@ -5,6 +5,7 @@ #include #include #include "modules/framebuffer.h" +#define CONSOLE_TEST_PANIC_SERIAL #include "modules/console.h" #include "../../lib/bugcheck.c" @@ -28,6 +29,7 @@ void x86_64_outw(uint16_t value,uint16_t port) {(void)value;(void)port;++vbe_acc uint16_t x86_64_inw(uint16_t port) {(void)port;++vbe_accesses;return 0;} void *kernel_malloc(size_t bytes) {CHECK(!panic_phase);++allocations;return malloc(bytes);} void kernel_free(void *pointer) {CHECK(!panic_phase);free(pointer);} +void serial_panic_quiesce(void) {CHECK(panic_phase);} void serial_write(const char *text) {(void)text;CHECK(!panic_phase);} void serial_write_emergency(const char *text,size_t length) {CHECK(length +#include +#include +#include +#include +#include +#include +#include "../../arch/x86_64/port.h" + +#define UART_COM1 0x3f8u +#define UART_IER (UART_COM1 + 1u) +#define UART_IIR (UART_COM1 + 2u) +#define UART_LCR (UART_COM1 + 3u) +#define UART_LSR (UART_COM1 + 5u) +#define UART_THRE 0x20u +#define UART_TEMT 0x40u +#define UART_TX_IRQ 0x02u +#define UART_FIFO_FLAGS 0xc0u +#define UART_FIFO_BYTES 16u +#define UART_TX_CAP 32768u +#define UART_LOG_RESERVE 2048u + +/* Emulate the port boundary only. A load occupies the FIFO until the test + * advances the wire and is limited to what the UART acknowledged at init. */ +static unsigned char wire[UART_TX_CAP + 1024]; +static size_t wire_length; +static unsigned fifo_load, fifo_capacity = UART_FIFO_BYTES, iir_reads; +static uint8_t uart_ier, uart_lcr; +static unsigned storage_wakes, poll_wakes, overrun_drops; +static bool fifo_ready = true, uart_absent, panic_phase; +static unsigned lock_depth; + +void x86_64_outb(uint8_t byte, uint16_t port) +{ + if (port == UART_LCR) uart_lcr = byte; + if (uart_lcr & 0x80u) { + if (port == UART_COM1) assert(byte == 1); /* 115200 baud */ + if (port == UART_IER) assert(byte == 0); + return; + } + if (port == UART_IER) uart_ier = byte; + if (port != UART_COM1) return; + assert(fifo_ready && fifo_load < fifo_capacity); + assert(wire_length < sizeof(wire)); + wire[wire_length++] = byte; + if (++fifo_load == fifo_capacity) fifo_ready = false; +} + +uint8_t x86_64_inb(uint16_t port) +{ + if (uart_absent) return 0xffu; + if (port == UART_IIR) { + ++iir_reads; + return fifo_capacity == 1 ? 1 : UART_FIFO_FLAGS | 1u; + } + assert(port == UART_LSR); + return fifo_ready ? UART_THRE | UART_TEMT : 0; +} + +void kernel_spin_lock_irqsave(struct kernel_spinlock *lock, uint64_t *flags) +{ assert(!panic_phase && !lock->state); lock->state = ++lock_depth; *flags = 0; } +void kernel_spin_unlock_irqrestore(struct kernel_spinlock *lock, uint64_t flags) +{ assert(lock->state == 1 && !flags); lock->state = 0; --lock_depth; } +void storage_completion_notify(void) { ++storage_wakes; } +void kernel_poll_readiness_notify(void) { ++poll_wakes; } +void console_log(enum console_log_level level, const char *format, ...) +{ + assert(!lock_depth && level == CONSOLE_LOG_WARN); + assert(!strncmp(format, "[serial] transmit queue full", 28)); + va_list args; + va_start(args, format); + overrun_drops += va_arg(args, unsigned); + va_end(args); +} + +static void wire_ready(void) +{ + fifo_load = 0; + fifo_ready = true; +} + +int main(void) +{ + uart_absent = true; + serial_init(); + assert(!serial_com1_available()); + assert(serial_tx_user("X", 1) == -ENODEV); + uart_absent = false; + serial_init(); + assert(serial_com1_available()); + serial_tx_record("early\r", 6, false); + serial_tx_set_irq(true); + serial_tx_start(); + assert(iir_reads == 1 && wire_length == 6 && uart_ier == 0); + + assert(serial_tx_user("\nA\0B\n", 5) == 5); + assert(wire_length == 6 && uart_ier == UART_TX_IRQ); + wire_ready(); + serial_tx_irq(); + assert(iir_reads == 2 && !uart_ier); + assert(wire_length == 12 && !memcmp(wire, "early\r\nA\0B\r\n", 12)); + wire_length = 0; + + static char bulk[UART_TX_CAP]; + memset(bulk, 'U', sizeof(bulk)); + size_t user_capacity = UART_TX_CAP - UART_LOG_RESERVE; + assert(serial_tx_user(bulk, user_capacity - 1u) == (int)user_capacity - 1); + assert(!serial_tx_writable()); + assert(serial_tx_user("\n", 1) == -EAGAIN); /* CR/LF must both fit */ + serial_tx_record("bad", 3, false); + serial_tx_record("kept\n", 5, true); + wire_ready(); + serial_tx_tick(); /* An IRQ may have been missed. */ + assert(wire_length == UART_FIFO_BYTES); + assert(serial_tx_writable() && storage_wakes == 1 && poll_wakes == 1); + assert(serial_tx_user("\n", 1) == 1); + for (size_t i = 0; uart_ier && i < UART_TX_CAP / UART_FIFO_BYTES; ++i) { + wire_ready(); + serial_tx_irq(); + } + assert(!uart_ier && overrun_drops == 1); + assert(wire_length == user_capacity + 7u); + assert(!memcmp(wire, bulk, user_capacity - 1u)); + assert(!memcmp(wire + user_capacity - 1u, "kept\r\n\r\n", 8)); + + wire_length = 0; + wire_ready(); + assert(serial_tx_user("shutdown\n", 9) == 9); + serial_tx_flush(); + assert(wire_length == 10 && !memcmp(wire, "shutdown\r\n", 10)); + + wire_length = 0; + wire_ready(); + serial_tx_record("queued\n", 7, false); + /* Panic output must work even if another CPU died holding TX ownership. */ + panic_phase = true; + serial_panic_quiesce(); + serial_write_emergency("panic\n", 6); + assert(wire_length == 7 && !memcmp(wire, "panic\r\n", 7) && !uart_ier); + puts("PASS serial TX ordering, backpressure, IRQ/PIT drain, shutdown and panic bypass"); + return 0; +} diff --git a/tools/tests/syscall_io_test.c b/tools/tests/syscall_io_test.c index 08c3b6dc..6f4ba03e 100644 --- a/tools/tests/syscall_io_test.c +++ b/tools/tests/syscall_io_test.c @@ -39,7 +39,7 @@ static _Noreturn int io_unexpected(const char *name, ...) #define task_inet_write IO_UNAVAILABLE #define task_inet_read IO_UNAVAILABLE #define syscall_socket_dispatch IO_UNAVAILABLE -#define console_write_len IO_UNAVAILABLE +#define console_serial_write_len IO_UNAVAILABLE #define task_shm_write IO_UNAVAILABLE #define task_shm_read IO_UNAVAILABLE #define task_effective_role IO_UNAVAILABLE diff --git a/tools/tests/vga_console_test.c b/tools/tests/vga_console_test.c index 0526e15e..11d2a653 100644 --- a/tools/tests/vga_console_test.c +++ b/tools/tests/vga_console_test.c @@ -37,7 +37,7 @@ int main(void) vga_console_configure("console=vga",true); assert(console_vga_text_mode && inits==2); uint32_t unchanged[80*48]; memcpy(unchanged,pixels,sizeof(pixels)); console_enable_framebuffer(); assert(!fb_console_enabled); - console_write("BOOT\n"); + console_info("BOOT\n"); assert((aperture[0]&255)=='[' || (aperture[0]&255)=='B'); console_vt_activate(1,false); console_vt_write(1,"\033[2J\033[Hone",11); @@ -66,7 +66,7 @@ int main(void) assert(!console_prepare_vt(true)); console_vt_activate(1,true); assert(presents==previous); pixels[100]=0x123456; memcpy(unchanged,pixels,sizeof(pixels)); - console_vt_write(1,"hidden",6); console_write("kernel diagnostic\n"); + console_vt_write(1,"hidden",6); console_info("kernel diagnostic\n"); assert(presents==previous && !memcmp(unchanged,pixels,sizeof(pixels))); enter_error=-16; assert(console_prepare_vt(false)==-16 && console_vt_graphical); diff --git a/tools/tests/vt_console_test.c b/tools/tests/vt_console_test.c index 9ba87f72..13918347 100644 --- a/tools/tests/vt_console_test.c +++ b/tools/tests/vt_console_test.c @@ -173,9 +173,48 @@ static void test_text_damage(void) expect_damage(16, 0, 16, 16); } -int main(void) +static void test_log_configuration(void) { + /* The default must avoid even timestamp work for suppressed DEBUG. */ + console_log_configure("logcolor=0"); + console_debug("default-filtered-debug\n"); + assert(serial_length == 0 && log_len == 0); + + console_log_configure("logcolor=0 debug log=serial"); + console_debug("[test] first\nsecond\n"); + assert(strstr(serial_output, "[DEBUG] [test] first\n")); + assert(strstr(serial_output, "[DEBUG] [reliefnt] second\n")); + assert(console_log_replay_start() == log_len); + + console_log_configure("logcolor=0 debug quiet log=screen"); + size_t output_before = serial_length; + size_t history_before = log_len; + console_info("quiet-filtered-info\n"); + assert(log_len == history_before); + console_error("[test] retained error\n"); + assert(log_len > history_before && console_log_replay_start() == 0); + assert(serial_length == output_before); + + console_log_configure("logcolor=0 loglevel=5"); + console_info("threshold-filtered-info\n"); + console_warn("[test] kept warning\n"); + assert(!strstr(serial_output, "threshold-filtered-info")); + assert(strstr(serial_output, "[WARN] [test] kept warning\n")); + + console_log_configure("log=none"); + output_before = serial_length; + console_error("sinks-disabled\n"); + assert(serial_length == output_before); + console_fatal("[test] fatal bypass\n"); + assert(strstr(serial_output, "[test] fatal bypass\n")); console_log_configure("logcolor=0"); +} + +int main(void) +{ + test_log_configuration(); + log_start = log_len = serial_length = 0; + serial_output[0] = 0; console_enable_framebuffer(); console_info("boot ready\n"); uint32_t boot_col = fb_col; @@ -186,7 +225,7 @@ int main(void) assert(full_clear_count == boot_clear_count); assert(fb_col == boot_col && fb_row == boot_row); assert(vt_text[0].length == boot_history_length); - assert(strstr(vt_text[0].bytes, "[INFO] boot ready\n") != NULL); + assert(strstr(vt_text[0].bytes, "[INFO] [reliefnt] boot ready\n") != NULL); console_vt_write(1, "init\n", 5); assert(full_clear_count == boot_clear_count); assert(vt_text[0].length == boot_history_length + 5u); @@ -214,7 +253,7 @@ int main(void) console_vt_activate(2, false); console_vt_activate(1, false); assert(vt_text[0].length == startup_history_length); - assert(strstr(vt_text[0].bytes, "[INFO] boot ready\ninit\n") != NULL); + assert(strstr(vt_text[0].bytes, "[INFO] [reliefnt] boot ready\ninit\n") != NULL); assert(strstr(vt_text[0].bytes, openrc_output) != NULL); console_vt_activate(2, false); assert(fb_console_tty_cursor_visible && fb_console_tty_cursor_x == 0); @@ -224,7 +263,7 @@ int main(void) assert(fb_console_tty_cursor_x == 16); uint32_t before[80 * 48]; memcpy(before, pixels, sizeof(pixels)); - console_write("background kernel log\n"); + console_info("background kernel log\n"); console_write_len("kmsg diagnostic\n", sizeof("kmsg diagnostic\n") - 1u); assert(memcmp(before, pixels, sizeof(pixels)) == 0); assert(vt_text[0].length == startup_history_length);