Przeglądaj źródła

Move the window manager and terminals to ring 3

Johannes Zellner 2 tygodni temu
rodzic
commit
60c307e7f2
35 zmienionych plików z 3654 dodań i 129 usunięć
  1. 49 25
      Makefile
  2. 39 18
      elf.c
  3. 71 2
      io.c
  4. 27 1
      kernel.c
  5. 11 0
      mouse.c
  6. 5 0
      mouse.h
  7. 91 0
      paging.c
  8. 17 0
      paging.h
  9. 77 14
      process.c
  10. 16 1
      process.h
  11. 3 0
      screen.c
  12. 1 0
      screen.h
  13. 1 1
      switch.S
  14. 23 6
      sys_gfx.c
  15. 170 0
      sys_wm.c
  16. 24 0
      sys_wm.h
  17. 145 0
      syscall.c
  18. 35 0
      syscall.h
  19. 98 0
      terminal.c
  20. 4 0
      terminal.h
  21. 150 0
      tty.c
  22. 19 0
      tty.h
  23. 5 5
      ucmd_clock.c
  24. 9 6
      ucmd_colors.c
  25. 5 5
      ucmd_edit.c
  26. 141 0
      ucmd_lib.h
  27. 530 0
      ucmd_term.c
  28. 497 0
      ucmd_wm.c
  29. 256 0
      uwm_lib.c
  30. 39 0
      uwm_lib.h
  31. 47 18
      vga.c
  32. 4 0
      vga.h
  33. 890 15
      wm.c
  34. 49 12
      wm.h
  35. 106 0
      wm_abi.h

+ 49 - 25
Makefile

@@ -26,7 +26,10 @@ kernel.o: kernel.c idle.h io.h mouse.h panic.h process.h terminal.h timer.h seri
 screen.o: screen.c screen.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-io.o: io.c io.h fbtext.h process.h screen.h
+io.o: io.c io.h fbtext.h process.h screen.h tty.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+tty.o: tty.c tty.h process.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 font_8x8.o: font_8x8.c font_8x8.h
@@ -38,7 +41,10 @@ fbtext.o: fbtext.c fbtext.h font_8x8.h vga.h
 terminal.o: terminal.c terminal.h screen.h vfs.h fat.h blkdev.h io.h dbg.h kexec.h process.h timer.h
 	$(CC) $(CFLAGS) -Os -o $@ $<
 
-wm.o: wm.c wm.h terminal.h screen.h fbtext.h idle.h io.h mouse.h process.h rtc.h timer.h version.h vga.h
+wm.o: wm.c wm.h wm_abi.h terminal.h screen.h fbtext.h idle.h io.h mouse.h process.h paging.h rtc.h timer.h version.h vga.h vfs.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+sys_wm.o: sys_wm.c sys_wm.h wm_abi.h wm.h paging.h process.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 hello.o: hello.c
@@ -242,7 +248,7 @@ elf.o: elf.c elf.h mm.h paging.h
 tss.o: tss.c tss.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-syscall.o: syscall.c syscall.h io.h process.h timer.h
+syscall.o: syscall.c syscall.h io.h process.h timer.h sys_wm.h wm_abi.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 sys_fs.o: sys_fs.c sys_fs.h syscall.h fat.h vfs.h
@@ -257,7 +263,7 @@ sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netdev.h netlog.h
 syscall_stub.o: syscall_stub.S irqret.inc
 	$(AS) $(ASFLAGS) -o $@ $<
 
-kernel.elf: vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o screen.o io.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o prog_embed.o space_embed.o cmds_pack.o ramfs.o payload.o
+kernel.elf: vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o prog_embed.o space_embed.o cmds_pack.o ramfs.o payload.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -295,35 +301,35 @@ BPB_TOTAL_OFFSET = 32
 
 floppy.img: boot.bin kernel.bin
 	SECTORS=$$(( ($$(stat -c%s kernel.bin) + 511) / 512 )); \
-	cp boot.bin boot.bin.patched; \
-	printf "$$(printf '\\x%02x\\x%02x' $$((SECTORS & 0xFF)) $$((SECTORS >> 8)))" | dd of=boot.bin.patched bs=1 seek=$(KERNEL_SECTORS_OFFSET) conv=notrunc 2>/dev/null; \
-	cat boot.bin.patched kernel.bin > $@; \
+	cp boot.bin $@.boot.tmp; \
+	printf "$$(printf '\\x%02x\\x%02x' $$((SECTORS & 0xFF)) $$((SECTORS >> 8)))" | dd of=$@.boot.tmp bs=1 seek=$(KERNEL_SECTORS_OFFSET) conv=notrunc 2>/dev/null; \
+	cat $@.boot.tmp kernel.bin > $@; \
 	truncate -s 1474560 $@; \
-	rm -f boot.bin.patched
+	rm -f $@.boot.tmp
 
 usb.img: mbr.bin boot.bin kernel.bin
 	SECTORS=$$(( ($$(stat -c%s kernel.bin) + 511) / 512 )); \
-	cp boot.bin boot.bin.patched; \
-	printf "$$(printf '\\x%02x\\x%02x' $$((SECTORS & 0xFF)) $$((SECTORS >> 8)))" | dd of=boot.bin.patched bs=1 seek=$(KERNEL_SECTORS_OFFSET) conv=notrunc 2>/dev/null; \
-	printf '\x40' | dd of=boot.bin.patched bs=1 seek=$(BOOT_SECTOR_START_OFFSET) conv=notrunc 2>/dev/null; \
-	printf '\xff\x00' | dd of=boot.bin.patched bs=1 seek=$(BPB_HEADS_OFFSET) conv=notrunc 2>/dev/null; \
-	printf '\x3f\x00\x00\x00' | dd of=boot.bin.patched bs=1 seek=$(BPB_HIDDEN_OFFSET) conv=notrunc 2>/dev/null; \
-	printf '\x08\xb7\x01\x00' | dd of=boot.bin.patched bs=1 seek=$(BPB_TOTAL_OFFSET) conv=notrunc 2>/dev/null; \
+	cp boot.bin $@.boot.tmp; \
+	printf "$$(printf '\\x%02x\\x%02x' $$((SECTORS & 0xFF)) $$((SECTORS >> 8)))" | dd of=$@.boot.tmp bs=1 seek=$(KERNEL_SECTORS_OFFSET) conv=notrunc 2>/dev/null; \
+	printf '\x40' | dd of=$@.boot.tmp bs=1 seek=$(BOOT_SECTOR_START_OFFSET) conv=notrunc 2>/dev/null; \
+	printf '\xff\x00' | dd of=$@.boot.tmp bs=1 seek=$(BPB_HEADS_OFFSET) conv=notrunc 2>/dev/null; \
+	printf '\x3f\x00\x00\x00' | dd of=$@.boot.tmp bs=1 seek=$(BPB_HIDDEN_OFFSET) conv=notrunc 2>/dev/null; \
+	printf '\x08\xb7\x01\x00' | dd of=$@.boot.tmp bs=1 seek=$(BPB_TOTAL_OFFSET) conv=notrunc 2>/dev/null; \
 	cat mbr.bin > $@; \
 	dd if=/dev/zero bs=512 count=62 2>/dev/null >> $@; \
-	cat boot.bin.patched kernel.bin >> $@; \
+	cat $@.boot.tmp kernel.bin >> $@; \
 	truncate -s 64M $@; \
-	rm -f boot.bin.patched
+	rm -f $@.boot.tmp
 
 image.bin: floppy.img
 	cp floppy.img image.bin
 
 final.bin: boot.bin kernel.bin
 	SECTORS=$$(( ($$(stat -c%s kernel.bin) + 511) / 512 )); \
-	cp boot.bin boot.bin.patched; \
-	printf "$$(printf '\\x%02x\\x%02x' $$((SECTORS & 0xFF)) $$((SECTORS >> 8)))" | dd of=boot.bin.patched bs=1 seek=$(KERNEL_SECTORS_OFFSET) conv=notrunc 2>/dev/null; \
-	cat boot.bin.patched kernel.bin > $@; \
-	rm -f boot.bin.patched
+	cp boot.bin $@.boot.tmp; \
+	printf "$$(printf '\\x%02x\\x%02x' $$((SECTORS & 0xFF)) $$((SECTORS >> 8)))" | dd of=$@.boot.tmp bs=1 seek=$(KERNEL_SECTORS_OFFSET) conv=notrunc 2>/dev/null; \
+	cat $@.boot.tmp kernel.bin > $@; \
+	rm -f $@.boot.tmp
 
 prog.o: prog.c run_api.h
 	$(CC) $(CFLAGS) -o $@ $<
@@ -343,7 +349,7 @@ prog: prog.bin
 # ucmd_<name>.c to UCMDS; the pack is rebuilt automatically.
 UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir \
         ucmd_meminfo ucmd_mouseinfo ucmd_storage ucmd_top \
-        ucmd_clock ucmd_colors ucmd_edit \
+        ucmd_clock ucmd_colors ucmd_edit ucmd_wm ucmd_term \
         ucmd_netinfo ucmd_netip ucmd_netdns ucmd_host ucmd_dhcp \
         ucmd_netsend ucmd_netrecv ucmd_ping ucmd_pong ucmd_netlog \
         ucmd_netconsole ucmd_netregs ucmd_netloop ucmd_netreset ucmd_curl
@@ -356,7 +362,7 @@ ucmd_%.o: ucmd_%.c ucmd_lib.h syscall.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 ucmd_%.elf: ucmd_%.o ucmd.ld
-	$(LD) -T ucmd.ld -nostdlib -m elf_i386 -o $@ $<
+	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $<
 	$(OBJCOPY) --strip-all $@ $@
 
 # edit draws text itself, so it links the kernel's 8x8 font into its ELF.
@@ -364,7 +370,25 @@ ucmd_edit.o: ucmd_edit.c ucmd_lib.h syscall.h font_8x8.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 ucmd_edit.elf: ucmd_edit.o font_8x8.o ucmd.ld
-	$(LD) -T ucmd.ld -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
+	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
+	$(OBJCOPY) --strip-all $@ $@
+
+# The ring-3 WM draws its own chrome and terminal cells.
+ucmd_wm.o: ucmd_wm.c ucmd_lib.h syscall.h wm_abi.h uwm_lib.h version.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+uwm_lib.o: uwm_lib.c uwm_lib.h font_8x8.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+ucmd_wm.elf: ucmd_wm.o uwm_lib.o font_8x8.o ucmd.ld
+	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
+	$(OBJCOPY) --strip-all $@ $@
+
+ucmd_term.o: ucmd_term.c ucmd_lib.h syscall.h wm_abi.h uwm_lib.h io.h vfs.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+ucmd_term.elf: ucmd_term.o uwm_lib.o font_8x8.o ucmd.ld
+	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
 # TLS 1.3 client library (ring-3, linked into ucmd_curl; see tls.h).  The
@@ -373,7 +397,7 @@ ucmd_edit.elf: ucmd_edit.o font_8x8.o ucmd.ld
 TLSLIB_OBJS = tls_sha256.o tls_chacha20.o tls_x25519.o tls_rng.o tls.o
 
 ucmd_curl.elf: ucmd_curl.o $(TLSLIB_OBJS) ucmd.ld
-	$(LD) -T ucmd.ld -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
+	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
 tls_sha256.o: tls_sha256.c tls_sha256.h
@@ -600,4 +624,4 @@ net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack.o ramfs.o payload.o mkpack $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack.o ramfs.o payload.o mkpack uwm_lib.o *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor

+ 39 - 18
elf.c

@@ -68,7 +68,7 @@ unsigned int elf_load(unsigned int cr3, const void *image, unsigned int size)
 	ph = (const struct elf32_phdr *)((const char *)image + h->phoff);
 
 	for (i = 0; i < h->phnum; i++) {
-		unsigned int va, memsz, filesz, off, npages;
+		unsigned int va, memsz, filesz, off, pbase, npages;
 
 		if (ph[i].type != PT_LOAD || ph[i].memsz == 0)
 			continue;
@@ -77,26 +77,47 @@ unsigned int elf_load(unsigned int cr3, const void *image, unsigned int size)
 		memsz = ph[i].memsz;
 		filesz = ph[i].filesz;
 		off = ph[i].offset;
-		npages = (memsz + 0xFFF) >> 12;
+		pbase = va & 0xFFFFF000u;
+		npages = ((va - pbase) + memsz + 0xFFF) >> 12;
 
 		for (p = 0; p < npages; p++) {
-			unsigned int phys = mm_alloc_page();
-			unsigned int src = p * 0x1000;
-			unsigned int n;
-
-			if (!phys)
-				return 0;
-			memzero((void *)phys, 0x1000);
-			if (src < filesz) {
-				n = filesz - src;
-				if (n > 0x1000)
-					n = 0x1000;
-				memcopy((void *)phys,
-					(const char *)image + off + src, n);
+			unsigned int pva = pbase + p * 0x1000;
+			unsigned int phys = paging_page_phys(cr3, pva);
+			unsigned int start, end, dst, src, n;
+
+			if (!phys) {
+				phys = mm_alloc_page();
+				if (!phys)
+					return 0;
+				memzero((void *)phys, 0x1000);
+				if (!paging_map_page(cr3, pva, phys,
+						     PTE_USER | PTE_WRITABLE | PTE_PRESENT))
+					return 0;
 			}
-			if (!paging_map_page(cr3, va + src, phys,
-					     PTE_USER | PTE_WRITABLE | PTE_PRESENT))
-				return 0;
+
+			/* Copy the file-backed part that falls in this page. */
+			start = (va + filesz > pva) ? ((va > pva) ? va : pva) : 0;
+			end = va + filesz;
+			if (end > pva + 0x1000)
+				end = pva + 0x1000;
+			if (start && end > start) {
+				dst = start - pva;
+				src = off + (start - va);
+				n = end - start;
+				memcopy((void *)(phys + dst),
+					(const char *)image + src, n);
+			}
+
+			/* Zero the BSS tail of this segment in this page. */
+			start = va + filesz;
+			end = va + memsz;
+			if (start < pva)
+				start = pva;
+			if (end > pva + 0x1000)
+				end = pva + 0x1000;
+			if (end > start)
+				memzero((void *)(phys + (start - pva)),
+					end - start);
 		}
 	}
 

+ 71 - 2
io.c

@@ -7,6 +7,7 @@
 #include "process.h"
 #include "screen.h"
 #include "timer.h"
+#include "tty.h"
 
 #define VGA_ATTR 0x0A
 
@@ -158,57 +159,125 @@ void io_init(void)
 	io_drain_keyboard();
 }
 
+/* A process with a tty writes there; the kernel terminal/boot fallback keeps
+ * the old cell-screen path until the ring-3 terminal is running. */
+static int io_tty(void)
+{
+	int id = procs[current_pid].tty;
+
+	return tty_valid(id) ? id : 0;
+}
+
 void io_clear_screen(void)
 {
+	int id = io_tty();
+
+	if (id) {
+		tty_write_str(id, "\x1b[2J\x1b[H");
+		return;
+	}
 	screen_clear(io_current_screen());
 }
 
 int io_did_scroll(void)
 {
+	if (io_tty())
+		return 0;
 	return screen_did_scroll(io_current_screen());
 }
 
 void io_putchar(char c)
 {
+	int id = io_tty();
+
+	if (id) {
+		tty_write(id, &c, 1);
+		return;
+	}
 	screen_putchar(io_current_screen(), c);
 }
 
 void io_putstr(const char *s)
 {
+	int id = io_tty();
+
+	if (id) {
+		tty_write_str(id, s);
+		return;
+	}
 	screen_putstr(io_current_screen(), s);
 }
 
 void io_puthex(unsigned int n)
 {
+	if (io_tty()) {
+		static const char hex[] = "0123456789ABCDEF";
+		char buf[9];
+		unsigned int i = 8;
+
+		buf[8] = '\0';
+		do {
+			buf[--i] = hex[n & 0xF];
+			n >>= 4;
+		} while (i > 0);
+		io_putstr(buf);
+		return;
+	}
 	screen_puthex(io_current_screen(), n);
 }
 
 unsigned int io_get_cursor(void)
 {
+	if (io_tty())
+		return 0;
 	return screen_get_cursor(io_current_screen());
 }
 
 void io_set_cursor(unsigned int pos)
 {
+	if (io_tty()) {
+		char buf[16];
+		unsigned int row = pos / 64 + 1, col = pos % 64 + 1, i = 0;
+
+		buf[i++] = 0x1B; buf[i++] = '[';
+		buf[i++] = (char)('0' + row / 10);
+		buf[i++] = (char)('0' + row % 10);
+		buf[i++] = ';';
+		buf[i++] = (char)('0' + col / 10);
+		buf[i++] = (char)('0' + col % 10);
+		buf[i++] = 'H'; buf[i] = '\0';
+		io_putstr(buf);
+		return;
+	}
 	screen_set_cursor(io_current_screen(), pos);
 }
 
 void io_cursor_show_block(void)
 {
-	struct text_screen *s = io_current_screen();
+	struct text_screen *s;
+
+	if (io_tty())
+		return;
+	s = io_current_screen();
 	s->cursor_visible = 1;
 	screen_damage_cursor(s);
 }
 
 void io_cursor_hide_block(void)
 {
-	struct text_screen *s = io_current_screen();
+	struct text_screen *s;
+
+	if (io_tty())
+		return;
+	s = io_current_screen();
 	s->cursor_visible = 0;
 	screen_damage_cursor(s);
 }
 
 void io_vga_write(unsigned int pos, unsigned short value)
 {
+	if (io_tty())
+		return;
 	screen_put_at(io_current_screen(), pos, value);
 }
 

+ 27 - 1
kernel.c

@@ -12,6 +12,7 @@
 #include "paging.h"
 #include "process.h"
 #include "ramfs.h"
+#include "sys_gfx.h"
 #include "timer.h"
 #include "tss.h"
 #include "usbhid.h"
@@ -161,6 +162,27 @@ static void timer_init(void)
 
 extern unsigned char __bss_start[], __bss_end[];
 
+/* The idle process: keeps the parts of the system that must not depend on
+ * the window manager running.  Input routing, cursor blink, kexec recovery,
+ * netlog flushing and gfx-session cleanup live here; the WM process only
+ * handles window state and drawing. */
+static void kernel_idle_loop(void)
+{
+	for (;;) {
+		mouse_poll_update();
+		wm_pump_keyboard();
+		wm_blink_cursor();
+		netlog_flush();
+		wm_handle_kexec();
+		wm_server_supervise();
+		if (wm_server_can_reap())
+			sys_gfx_collect();
+		if (!wm_server_frame_active())
+			vga_fb_flush_budget(VGA_FLUSH_BUDGET_BYTES);
+		cpu_idle();
+	}
+}
+
 void kernel_main(void);
 void kernel_main(void)
 {
@@ -217,5 +239,9 @@ void kernel_main(void)
 	/* With a NIC present, try DHCP; on failure the static default stays. */
 	if (netdev_active())
 		dhcp_run(3000);
-	wm_run();
+	/* Slot 0 is the idle loop; the window server is initialized before the
+	 * ring-3 WM is spawned from /ramfs/bin/wm. */
+	wm_server_init();
+	wm_server_start();
+	kernel_idle_loop();
 }

+ 11 - 0
mouse.c

@@ -43,6 +43,7 @@ static const unsigned short mouse_pointer_bits[MOUSE_CUR_H] = {
 
 static int mouse_present_flag;
 static int mouse_streaming_flag;
+static int mouse_auto_draw = 1;   /* 0 while a WM frame owns the shadow */
 static unsigned int mouse_id;
 static int mouse_cursor_flag;
 static unsigned int mouse_pkt_size;
@@ -287,6 +288,11 @@ static void mouse_move(int dx, int dy)
 			radeon_cursor_move(cur_x, cur_y);
 		else
 			cirrus_cursor_move(cur_x, cur_y);
+	} else if (!mouse_auto_draw) {
+		/* A WM frame is between BEGIN and PRESENT: it erased the
+		 * software cursor and will redraw it at the new position. */
+		cur_x = (unsigned int)nx;
+		cur_y = (unsigned int)ny;
 	} else {
 		vga_fb_write_rect(cur_x, cur_y, MOUSE_CUR_W, MOUSE_CUR_H,
 			cur_saved);
@@ -427,3 +433,8 @@ void mouse_cursor_erase(void)
 		return;
 	vga_fb_write_rect(cur_x, cur_y, MOUSE_CUR_W, MOUSE_CUR_H, cur_saved);
 }
+
+void mouse_set_auto_draw(int on)
+{
+	mouse_auto_draw = on ? 1 : 0;
+}

+ 5 - 0
mouse.h

@@ -29,4 +29,9 @@ void mouse_cursor_erase(void);
    redraws windows underneath a stationary cursor). */
 void mouse_redraw_cursor(void);
 
+/* While a WM frame owns the shadow buffer, movement must update the position
+ * and buttons without drawing a software cursor underneath the frame.  The
+ * WM erases/redraws the cursor itself at BEGIN/PRESENT. */
+void mouse_set_auto_draw(int on);
+
 #endif

+ 91 - 0
paging.c

@@ -193,6 +193,21 @@ int paging_map_page(unsigned int cr3, unsigned int va, unsigned int phys,
 	return 1;
 }
 
+unsigned int paging_page_phys(unsigned int cr3, unsigned int va)
+{
+	unsigned int *pd = (unsigned int *)cr3;
+	unsigned int pde = pd[va >> 22];
+	unsigned int pte = (va >> 12) & 0x3FF;
+
+	if (!(pde & PDE_PRESENT) || (pde & PDE_PS))
+		return 0;
+	{
+		unsigned int e = ((unsigned int *)(pde & 0xFFFFF000))[pte];
+
+		return (e & PTE_PRESENT) ? (e & 0xFFFFF000) : 0;
+	}
+}
+
 void paging_unmap_page(unsigned int cr3, unsigned int va)
 {
 	unsigned int *pd = (unsigned int *)cr3;
@@ -204,6 +219,82 @@ void paging_unmap_page(unsigned int cr3, unsigned int va)
 	((unsigned int *)(pd[pde] & 0xFFFFF000))[pte] = 0;
 }
 
+int paging_user_range_ok(unsigned int cr3, unsigned int va,
+			 unsigned int size, int write)
+{
+	unsigned int *pd = (unsigned int *)cr3;
+	unsigned int end = va + size;
+	unsigned int p;
+
+	if (!pd || size == 0 || end < va)
+		return 0;
+	for (p = va & 0xFFFFF000u; p < end; p += PAGE_SIZE) {
+		unsigned int pde = pd[p >> 22];
+		unsigned int *pt;
+		unsigned int pte;
+
+		if (!(pde & PDE_PRESENT) || (pde & PDE_PS) || !(pde & PDE_USER))
+			return 0;
+		pt = (unsigned int *)(pde & 0xFFFFF000);
+		pte = pt[(p >> 12) & 0x3FF];
+		if (!(pte & PTE_PRESENT) || !(pte & PTE_USER))
+			return 0;
+		if (write && !(pte & PTE_WRITABLE))
+			return 0;
+	}
+	return 1;
+}
+
+void paging_release_user_range(unsigned int cr3, unsigned int va,
+			       unsigned int size, int free_phys)
+{
+	unsigned int *pd = (unsigned int *)cr3;
+	unsigned int end = va + size;
+	unsigned int first, last, i, j;
+
+	if (!pd || size == 0 || end < va)
+		return;
+	first = va >> 22;
+	last = (end - 1) >> 22;
+
+	for (i = first; i <= last && i < 1024; i++) {
+		unsigned int pde = pd[i];
+		unsigned int *pt;
+		int empty = 1;
+
+		/* Kernel identity mappings are 4 MB pages and must never be
+		 * touched here. */
+		if (!(pde & PDE_PRESENT) || (pde & PDE_PS))
+			continue;
+		pt = (unsigned int *)(pde & 0xFFFFF000);
+
+		for (j = 0; j < 1024; j++) {
+			unsigned int pva = (i << 22) | (j << 12);
+
+			if (pva < va || pva >= end)
+				continue;
+			if (pt[j] & PTE_PRESENT) {
+				/* Only user pages are owned by the process; a
+				 * supervisor mapping in this range is left for
+				 * its owner. */
+				if (free_phys && (pt[j] & PTE_USER))
+					mm_free_page(pt[j] & 0xFFFFF000);
+				pt[j] = 0;
+			}
+		}
+
+		for (j = 0; j < 1024; j++)
+			if (pt[j] & PTE_PRESENT) {
+				empty = 0;
+				break;
+			}
+		if (empty) {
+			mm_free_page(pde & 0xFFFFF000);
+			pd[i] = 0;
+		}
+	}
+}
+
 /* Identity-map an MMIO range uncacheable into one page directory (4 MB pages;
  * the range is rounded up to a whole number of them). */
 void paging_map_mmio_cr3(unsigned int cr3, unsigned int phys_base, unsigned int size)

+ 17 - 0
paging.h

@@ -30,10 +30,27 @@ unsigned int paging_new_directory(void);
 int paging_map_page(unsigned int cr3, unsigned int va, unsigned int phys,
 		    unsigned int flags);
 
+/* Physical address mapped at `va`, or 0 when the page is not present. */
+unsigned int paging_page_phys(unsigned int cr3, unsigned int va);
+
 /* Clear one 4 KB page (va) in page directory `cr3` (no-op when the page
  * table is absent). */
 void paging_unmap_page(unsigned int cr3, unsigned int va);
 
+/* Release the user mappings in [va, va+size): clear the PTEs, free empty page
+ * tables and, when `free_phys` is set, free the mapped physical pages.  With
+ * `free_phys` clear the pages belong to someone else (e.g. a mapped window
+ * canvas) and only the mapping/page tables are released.  Used by the process
+ * reaper; ranges should cover the user-owned mappings only. */
+void paging_release_user_range(unsigned int cr3, unsigned int va,
+			       unsigned int size, int free_phys);
+
+/* 1 when every page in [va, va+size) is a user-accessible 4 KB mapping in
+ * `cr3` (and writable when `write` is set).  Syscall services use this before
+ * touching a pointer supplied by ring 3. */
+int paging_user_range_ok(unsigned int cr3, unsigned int va,
+			 unsigned int size, int write);
+
 /* Identity-map an MMIO range (e.g. a GPU register aperture) uncacheable into
  * the current page directory.  Uses 4 MB pages; the range is rounded up to a
  * whole number of 4 MB pages. */

+ 77 - 14
process.c

@@ -13,6 +13,9 @@
 #include "sys_net.h"
 #include "syscall.h"
 #include "timer.h"
+#include "tty.h"
+#include "vga.h"
+#include "wm_abi.h"
 
 struct process *procs;               /* dynamically-sized process table */
 volatile unsigned int current_pid;
@@ -28,7 +31,7 @@ extern char __boot_stack_top[];
 
 /* switch.S addresses the table entries with an immediate PCB_SIZE/PCB_CPU_TICKS
  * and cannot see this struct; keep the two in sync. */
-_Static_assert(sizeof(struct process) == 120,
+_Static_assert(sizeof(struct process) == 124,
 	       "struct process layout changed: update PCB_SIZE/PCB_CPU_TICKS in switch.S");
 
 /* ---- interrupt flag save/restore (for short critical sections) ---- */
@@ -89,6 +92,15 @@ static void name_copy(char *dst, const char *src)
 	dst[i] = '\0';
 }
 
+static void inherit_cwd(struct process *p)
+{
+	unsigned int i;
+
+	for (i = 0; i + 1 < sizeof(p->cwd) && procs[current_pid].cwd[i]; i++)
+		p->cwd[i] = procs[current_pid].cwd[i];
+	p->cwd[i] = '\0';
+}
+
 /* Double the process table.  Called with interrupts disabled. */
 static int grow_proc_table(void)
 {
@@ -110,7 +122,7 @@ static int grow_proc_table(void)
 }
 
 /* Find a free process slot (1..proc_cap-1), growing the table if needed.
- * Slot 0 is the window manager and is never returned.  Called with interrupts
+ * Slot 0 is the kernel idle process and is never returned.  Called with interrupts
  * disabled.  Returns the slot index, or -1 on failure. */
 static int alloc_slot(void)
 {
@@ -149,7 +161,7 @@ void process_init(void)
 	procs[0].kstack_top = (unsigned int)__boot_stack_top;
 	procs[0].cpu_ticks  = 0;
 	procs[0].start_ticks = 0;  /* the WM "starts" at boot */
-	name_copy(procs[0].name, "wm");
+	name_copy(procs[0].name, "idle");
 	current_pid = 0;
 }
 
@@ -240,9 +252,11 @@ static int setup_process(const char *name, unsigned int entry,
 	procs[slot].cpu_ticks  = 0;
 	procs[slot].start_ticks = get_ticks_ms();
 	name_copy(procs[slot].name, name);
-	/* Child inherits the parent's output screen (command output lands in the
-	   terminal that spawned it). */
+	/* Child inherits the parent's output screen/tty (command output lands
+	   in the terminal that spawned it). */
 	procs[slot].screen = procs[current_pid].screen;
+	procs[slot].tty = procs[current_pid].tty;
+	inherit_cwd(&procs[slot]);
 
 	irq_restore(flags);
 	return (int)procs[slot].pid;
@@ -307,13 +321,15 @@ int process_create_ptr(const char *name, void (*entry)(void *), void *arg)
 	procs[slot].start_ticks = get_ticks_ms();
 	name_copy(procs[slot].name, name);
 	procs[slot].screen = procs[current_pid].screen;
+	procs[slot].tty = procs[current_pid].tty;
+	inherit_cwd(&procs[slot]);
 	irq_restore(flags);
 	return (int)procs[slot].pid;
 }
 
 /* Load an ELF image into a fresh address space and run it as a ring-3 process. */
-int process_create_user(const char *name, const void *image, unsigned int size,
-			const char *arg, const char *cwd)
+int process_create_user_tty(const char *name, const void *image, unsigned int size,
+			    const char *arg, const char *cwd, unsigned int tty)
 {
 	int slot, owned;
 	unsigned int base, top, *sp, cr3, entry;
@@ -419,6 +435,7 @@ int process_create_user(const char *name, const void *image, unsigned int size,
 	procs[slot].start_ticks = get_ticks_ms();
 	name_copy(procs[slot].name, name);
 	procs[slot].screen = procs[current_pid].screen;
+	procs[slot].tty = tty ? (int)tty : procs[current_pid].tty;
 	{
 		unsigned int k;
 
@@ -431,6 +448,12 @@ int process_create_user(const char *name, const void *image, unsigned int size,
 	return (int)procs[slot].pid;
 }
 
+int process_create_user(const char *name, const void *image, unsigned int size,
+			const char *arg, const char *cwd)
+{
+	return process_create_user_tty(name, image, size, arg, cwd, 0);
+}
+
 /* Set the output screen of the currently-running process (used by a terminal
    at startup to bind itself to its own screen). */
 void process_set_screen(struct text_screen *screen)
@@ -491,20 +514,41 @@ void schedule(void)
 		if (procs[i].state == PROC_DEAD && i != current_pid) {
 			sys_net_reap(procs[i].pid);   /* release a held NIC */
 			sys_gfx_reap(procs[i].pid);   /* flag a gfx session dead */
+			tty_reap(procs[i].pid);       /* drop its terminal queue */
 			if (procs[i].stack_base)
 				mm_free_page(procs[i].stack_base);
-			if (procs[i].cr3 && procs[i].cr3 != paging_current_cr3())
+			if (procs[i].cr3 &&
+			    procs[i].cr3 != paging_current_cr3()) {
+				/* User code/stack pages belong to the process.
+				 * The gfx canvas mapping is only a window into
+				 * pages owned by the session: release the PTEs
+				 * and page tables, not the pages. */
+				paging_release_user_range(procs[i].cr3,
+					USER_BASE, USER_STACK_TOP - USER_BASE, 1);
+				paging_release_user_range(procs[i].cr3,
+					USER_GFX_BASE, USER_GFX_RANGE, 0);
+				/* WM surface mappings: page tables only; the
+				 * shadow/terminal/canvas pages belong to the
+				 * window server. */
+				paging_release_user_range(procs[i].cr3,
+					WM_SHADOW_VA, 0x00800000, 0);
+				paging_release_user_range(procs[i].cr3,
+					WM_CONTENT_VA_BASE,
+					WM_CONTENT_SLOT * WM_MAX_WINDOWS, 0);
 				mm_free_page(procs[i].cr3);
+			}
 			procs[i].stack_base = 0;
 			procs[i].cr3 = 0;
 			procs[i].state = PROC_UNUSED;
 		}
 	}
 
-	/* A file syscall is in progress: stay on the current process so the FAT
-	 * driver's static state is never touched concurrently (see sys_fs.c).
-	 * Interrupts stay enabled, so the disk's IRQs are still serviced. */
-	if (sys_fs_busy) {
+	/* A file syscall or a shadow-buffer flush is in progress: stay on the
+	 * current process.  The FAT driver has static state, and the flush walks
+	 * and trims a shared damage list (and must not be abandoned halfway
+	 * through by a context switch).  Interrupts stay enabled, so IRQs are
+	 * still serviced. */
+	if (sys_fs_busy || vga_present_busy()) {
 		if (procs[current_pid].state == PROC_READY)
 			procs[current_pid].state = PROC_RUNNING;
 		return;
@@ -538,7 +582,7 @@ void schedule(void)
 		return;
 	}
 
-	/* Everything dead: fall back to slot 0 (window manager). */
+	/* Everything dead: fall back to slot 0 (kernel idle). */
 	procs[0].state = PROC_RUNNING;
 	current_pid = 0;
 }
@@ -649,7 +693,7 @@ int process_kill(unsigned int pid)
 {
 	unsigned int i;
 	if (pid == 0)
-		return -1; /* cannot kill window manager */
+		return -1; /* cannot kill the kernel idle process */
 	for (i = 1; i < proc_cap; i++) {
 		if (procs[i].state != PROC_UNUSED && procs[i].state != PROC_DEAD &&
 		    procs[i].pid == pid) {
@@ -673,6 +717,25 @@ int process_is_alive(unsigned int pid)
 	return 0;
 }
 
+int process_is_sleeping(unsigned int pid)
+{
+	unsigned int i;
+	for (i = 0; i < proc_cap; i++)
+		if (procs[i].pid == pid)
+			return procs[i].state == PROC_SLEEPING;
+	return 0;
+}
+
+void process_set_tty(unsigned int pid, int tty)
+{
+	unsigned int i;
+	for (i = 0; i < proc_cap; i++)
+		if (procs[i].pid == pid && procs[i].state != PROC_UNUSED) {
+			procs[i].tty = tty;
+			return;
+		}
+}
+
 /* Block the current process for `ms` milliseconds.  Marks it sleeping and
  * yields to the scheduler; it is woken when its deadline passes. */
 void process_sleep_ms(unsigned int ms)

+ 16 - 1
process.h

@@ -42,14 +42,21 @@ struct process {
 	unsigned int start_ticks;    /* get_ticks_ms() at creation */
 	/* Render target override: 0 = the screen.  Set while the window manager
 	 * draws into a layer, so another process's drawing can never land in
-	 * it.  Kept last so the PIT hot path offsets stay put. */
+	 * it.  Kept before tty so the PIT hot path offsets stay put. */
 	struct surface *target;
+	/* TTY output id inherited by children (0 = none, use the old screen). */
+	int tty;
 };
 
 /* User-mode virtual address layout (ring-3 processes). */
 #define USER_BASE        0x40000000   /* user program link/load address */
 #define USER_STACK_TOP   0x40200000   /* user stack top (grows down) */
 #define USER_STACK_PAGES 2            /* user stack size in 4 KB pages */
+/* Where sys_gfx maps a command's canvas back buffer (see sys_gfx.c).  The
+ * mapping is released by the reaper without freeing the canvas pages: the
+ * gfx session owns those. */
+#define USER_GFX_BASE    0x50000000
+#define USER_GFX_RANGE   0x00400000   /* one 4 MB slot */
 
 /* Dynamically-sized process table (grown on demand; see process.c). */
 extern struct process *procs;
@@ -66,6 +73,10 @@ int  process_create_ptr(const char *name, void (*entry)(void *), void *arg);
  * loadable ELF. */
 int process_create_user(const char *name, const void *image, unsigned int size,
 			const char *arg, const char *cwd);
+/* Same, but with an explicit tty id (0 = inherit the caller's tty). */
+int process_create_user_tty(const char *name, const void *image,
+			unsigned int size, const char *arg, const char *cwd,
+			unsigned int tty);
 void process_set_screen(struct text_screen *screen);
 /* Render target override for the running process (0 = the screen). */
 struct surface *process_render_target(void);
@@ -86,6 +97,10 @@ void process_ps(void);
 int  process_procinfo(unsigned int index, struct sys_procinfo *out);
 int  process_kill(unsigned int pid);
 int  process_is_alive(unsigned int pid);
+/* 1 while the process is in PROC_SLEEPING (the WM uses this to tell when it
+ * is safe to reap another window's canvas). */
+int  process_is_sleeping(unsigned int pid);
+void process_set_tty(unsigned int pid, int tty);
 void process_wait(unsigned int pid);
 
 /* Block the current process for `ms` milliseconds (yields the CPU). */

+ 3 - 0
screen.c

@@ -15,6 +15,7 @@
  */
 static void screen_damage_cell(struct text_screen *s, unsigned int col, unsigned int row)
 {
+	s->damage_seq++;
 	if (!s->dirty) {
 		s->dirty = 1;
 		s->dmg_col0 = s->dmg_col1 = col;
@@ -33,6 +34,7 @@ static void screen_damage_cell(struct text_screen *s, unsigned int col, unsigned
 
 static void screen_damage_all(struct text_screen *s)
 {
+	s->damage_seq++;
 	s->dirty = 1;
 	s->dmg_col0 = 0;
 	s->dmg_col1 = s->cols - 1;
@@ -76,6 +78,7 @@ void screen_init(struct text_screen *s)
 	s->cursor_attr = (SCREEN_ATTR << 8);
 	s->cursor_visible = 0;
 	s->scrolled = 0;
+	s->damage_seq = 0;
 	screen_clear(s);
 }
 

+ 1 - 0
screen.h

@@ -22,6 +22,7 @@ struct text_screen {
 	int dirty;                    /* content changed since last WM render */
 	unsigned int dmg_col0, dmg_col1;
 	unsigned int dmg_row0, dmg_row1;
+	unsigned int damage_seq;      /* bumped on every damage mark (WM ACK) */
 	int scrolled;                 /* one-shot, replaces io_did_scroll */
 };
 

+ 1 - 1
switch.S

@@ -29,7 +29,7 @@
 .equ PCB_CR3,   32
 .equ PCB_KSTACK_TOP, 36
 .equ PCB_CPU_TICKS, 108  /* after cwd[64] */
-.equ PCB_SIZE,  120     /* sizeof(struct process): 44 + cwd[64] + 2*4 + target */
+.equ PCB_SIZE,  124     /* sizeof(struct process): 44 + cwd[64] + 2*4 + target + tty */
 
 .equ TIMESLICE, 20
 

+ 23 - 6
sys_gfx.c

@@ -14,7 +14,7 @@
 #include "wm.h"
 
 #define GFX_MAX_SESSIONS MAX_WINDOWS
-#define GFX_USER_BASE    0x50000000   /* canvas mapping for the owner */
+#define GFX_USER_BASE    USER_GFX_BASE   /* canvas mapping for the owner */
 #define GFX_KEY_RING     16
 
 struct gfx_session {
@@ -141,6 +141,8 @@ int sys_gfx_begin(struct sys_gfx_info *info)
 	s->term = t;
 	s->key_head = s->key_tail = 0;
 
+	wm_content_changed(&t->screen);   /* the WM switches to the canvas */
+
 	info->width = w;
 	info->height = h;
 	info->fb = (void *)GFX_USER_BASE;
@@ -180,10 +182,10 @@ int sys_gfx_end(void)
 	if (!s)
 		return -1;
 	unmap_all(s);
-	gfx_free(&s->c);
-	free_back(s);
-	s->used = 0;
-	wm_request_redraw();       /* the window falls back to its text cells */
+	/* The front canvas is still mapped into the WM.  Mark the session dead
+	 * and let sys_gfx_collect() unmap it from the WM before freeing it. */
+	s->dead = 1;
+	wm_content_changed(&s->term->screen);
 	return 0;
 }
 
@@ -192,7 +194,9 @@ int sys_gfx_key_poll(void)
 	struct gfx_session *s = by_pid(procs[current_pid].pid);
 	int k;
 
-	if (!s || s->key_tail == s->key_head)
+	if (!s)
+		return wm_server_key_poll();   /* generic canvas window */
+	if (s->key_tail == s->key_head)
 		return 0;
 	k = s->keys[s->key_tail];
 	s->key_tail = (s->key_tail + 1) % GFX_KEY_RING;
@@ -232,6 +236,7 @@ void sys_gfx_kill_for_screen(struct text_screen *screen)
 		return;
 	process_kill(s->pid);
 	s->dead = 1;   /* freed by the next sys_gfx_collect() */
+	wm_content_changed(screen);
 }
 
 /* Reaper hook (schedule(), IRQ context): only flag the session. */
@@ -251,11 +256,23 @@ void sys_gfx_collect(void)
 	unsigned int i;
 	int freed = 0;
 
+	/* The WM may still be composing the front canvas we are about to free.
+	 * It calls back after PRESENT; the idle loop also retries. */
+	if (wm_server_frame_active())
+		return;
+
 	for (i = 0; i < GFX_MAX_SESSIONS; i++) {
 		if (sessions[i].used && sessions[i].dead) {
+			struct text_screen *screen = &sessions[i].term->screen;
+
+			/* Drop the WM's read-only mapping before the canvas pages
+			 * can be reused.  Only this session's canvas: a newer
+			 * session may already be mapped for the same screen. */
+			wm_server_unmap_canvas(screen, sessions[i].c.px);
 			gfx_free(&sessions[i].c);
 			free_back(&sessions[i]);
 			sessions[i].used = 0;
+			wm_content_changed(screen);
 			freed = 1;
 		}
 	}

+ 170 - 0
sys_wm.c

@@ -0,0 +1,170 @@
+/* Syscall wrappers for the ring-3 window manager.  User pointers are checked
+ * against the caller's page tables and copied before the kernel touches them;
+ * a buggy WM returns -1 instead of faulting in ring 0. */
+
+#include "sys_wm.h"
+#include "paging.h"
+#include "process.h"
+#include "wm.h"
+
+static int user_ok(const void *p, unsigned int size, int write)
+{
+	return paging_user_range_ok(procs[current_pid].cr3,
+				    (unsigned int)p, size, write);
+}
+
+static void copy_to_user(void *dst, const void *src, unsigned int n)
+{
+	unsigned char *d = (unsigned char *)dst;
+	const unsigned char *s = (const unsigned char *)src;
+	while (n--)
+		*d++ = *s++;
+}
+
+static void copy_from_user(void *dst, const void *src, unsigned int n)
+{
+	unsigned char *d = (unsigned char *)dst;
+	const unsigned char *s = (const unsigned char *)src;
+	while (n--)
+		*d++ = *s++;
+}
+
+static void zero_struct(void *p, unsigned int n)
+{
+	unsigned char *d = (unsigned char *)p;
+	while (n--)
+		*d++ = 0;
+}
+
+int sys_wm_attach(struct wm_screen_info *out)
+{
+	struct wm_screen_info info;
+	int r;
+
+	if (!user_ok(out, sizeof(info), 1))
+		return -1;
+	zero_struct(&info, sizeof(info));
+	r = wm_server_attach(&info);
+	if (r == 0)
+		copy_to_user(out, &info, sizeof(info));
+	return r;
+}
+
+int sys_wm_info(unsigned int index, struct wm_window_info *out)
+{
+	struct wm_window_info info;
+	int r;
+
+	if (!user_ok(out, sizeof(info), 1))
+		return -1;
+	zero_struct(&info, sizeof(info));
+	r = wm_server_info(index, &info);
+	if (r >= 0)
+		copy_to_user(out, &info, sizeof(info));
+	return r;
+}
+
+int sys_wm_map(unsigned int index, struct wm_map_info *out)
+{
+	struct wm_map_info info;
+	int r;
+
+	if (!user_ok(out, sizeof(info), 1))
+		return -1;
+	zero_struct(&info, sizeof(info));
+	r = wm_server_map(index, &info);
+	if (r == 0)
+		copy_to_user(out, &info, sizeof(info));
+	return r;
+}
+
+int sys_wm_ack(unsigned int index, unsigned int seq)
+{
+	return wm_server_ack(index, seq);
+}
+
+int sys_wm_focus(unsigned int index)
+{
+	return wm_server_focus(index);
+}
+
+int sys_wm_set_geom(unsigned int index, const struct wm_geom *in)
+{
+	struct wm_geom g;
+
+	if (!user_ok(in, sizeof(g), 0))
+		return -1;
+	copy_from_user(&g, in, sizeof(g));
+	return wm_server_set_geom(index, g.x, g.y);
+}
+
+int sys_wm_create_term(void)
+{
+	return wm_server_create_term();
+}
+
+int sys_wm_close(unsigned int index)
+{
+	return wm_server_close(index);
+}
+
+int sys_wm_poll(struct wm_status *out)
+{
+	struct wm_status st;
+	int r;
+
+	if (!user_ok(out, sizeof(st), 1))
+		return -1;
+	zero_struct(&st, sizeof(st));
+	r = wm_server_poll(&st);
+	if (r == 0)
+		copy_to_user(out, &st, sizeof(st));
+	return r;
+}
+
+int sys_wm_begin(void)
+{
+	return wm_server_begin();
+}
+
+int sys_wm_present(const struct wm_present_info *in)
+{
+	struct wm_present_info p;
+
+	if (!user_ok(in, sizeof(p), 0))
+		return -1;
+	copy_from_user(&p, in, sizeof(p));
+	return wm_server_present(&p);
+}
+
+int sys_wm_sync(void)
+{
+	return wm_server_sync();
+}
+
+int sys_win_create(const struct win_create *in, struct win_info *out)
+{
+	struct win_create create;
+	struct win_info info;
+	int r;
+
+	if (!user_ok(in, sizeof(create), 0) ||
+	    !user_ok(out, sizeof(info), 1))
+		return -1;
+	copy_from_user(&create, in, sizeof(create));
+	zero_struct(&info, sizeof(info));
+	r = wm_server_win_create(&create, &info);
+	if (r == 0)
+		copy_to_user(out, &info, sizeof(info));
+	return r;
+}
+
+int sys_win_present(void)
+{
+	return wm_server_win_present();
+}
+
+int sys_win_close(void)
+{
+	return wm_server_win_close();
+}

+ 24 - 0
sys_wm.h

@@ -0,0 +1,24 @@
+/* Ring-3 window-manager syscall service (see wm_abi.h / wm.c). */
+#ifndef SYS_WM_H
+#define SYS_WM_H
+
+#include "wm_abi.h"
+
+int sys_wm_attach(struct wm_screen_info *out);
+int sys_wm_info(unsigned int index, struct wm_window_info *out);
+int sys_wm_map(unsigned int index, struct wm_map_info *out);
+int sys_wm_ack(unsigned int index, unsigned int seq);
+int sys_wm_focus(unsigned int index);
+int sys_wm_set_geom(unsigned int index, const struct wm_geom *in);
+int sys_wm_create_term(void);
+int sys_wm_close(unsigned int index);
+int sys_wm_poll(struct wm_status *out);
+int sys_wm_begin(void);
+int sys_wm_present(const struct wm_present_info *in);
+int sys_wm_sync(void);
+
+int sys_win_create(const struct win_create *in, struct win_info *out);
+int sys_win_present(void);
+int sys_win_close(void);
+
+#endif

+ 145 - 0
syscall.c

@@ -2,6 +2,7 @@
 
 #include "syscall.h"
 #include "io.h"
+#include "paging.h"
 #include "process.h"
 #include "rtc.h"
 #include "serial.h"
@@ -9,7 +10,25 @@
 #include "sys_gfx.h"
 #include "sys_info.h"
 #include "sys_net.h"
+#include "sys_wm.h"
+#include "terminal.h"
 #include "timer.h"
+#include "tty.h"
+#include "vfs.h"
+
+static int copy_user_string(char *dst, unsigned int max, const char *src)
+{
+	unsigned int i;
+
+	if (!src || !max ||
+	    !paging_user_range_ok(procs[current_pid].cr3, (unsigned int)src,
+				  max, 0))
+		return -1;
+	for (i = 0; i + 1 < max && src[i]; i++)
+		dst[i] = src[i];
+	dst[i] = '\0';
+	return 0;
+}
 
 int syscall_dispatch(int num, int a1, int a2, int a3)
 {
@@ -165,6 +184,132 @@ int syscall_dispatch(int num, int a1, int a2, int a3)
 		out->second = s;
 		return 0;
 	}
+	case SYS_RTC_DATETIME: {
+		char buf[20];
+		char *out = (char *)a1;
+		unsigned int i;
+
+		if ((unsigned int)a2 < sizeof(buf) ||
+		    !paging_user_range_ok(procs[current_pid].cr3,
+					  (unsigned int)out, sizeof(buf), 1))
+			return -1;
+		rtc_read_datetime(buf);
+		for (i = 0; i < sizeof(buf); i++)
+			out[i] = buf[i];
+		return 0;
+	}
+	case SYS_WM_ATTACH:
+		return sys_wm_attach((struct wm_screen_info *)a1);
+	case SYS_WM_INFO:
+		return sys_wm_info((unsigned int)a1,
+				   (struct wm_window_info *)a2);
+	case SYS_WM_MAP:
+		return sys_wm_map((unsigned int)a1,
+				  (struct wm_map_info *)a2);
+	case SYS_WM_ACK:
+		return sys_wm_ack((unsigned int)a1, (unsigned int)a2);
+	case SYS_WM_FOCUS:
+		return sys_wm_focus((unsigned int)a1);
+	case SYS_WM_SET_GEOM:
+		return sys_wm_set_geom((unsigned int)a1,
+				       (const struct wm_geom *)a2);
+	case SYS_WM_CREATE_TERM:
+		return sys_wm_create_term();
+	case SYS_WM_CLOSE:
+		return sys_wm_close((unsigned int)a1);
+	case SYS_WM_POLL:
+		return sys_wm_poll((struct wm_status *)a1);
+	case SYS_WM_BEGIN:
+		return sys_wm_begin();
+	case SYS_WM_PRESENT:
+		return sys_wm_present((const struct wm_present_info *)a1);
+	case SYS_WM_SYNC:
+		return sys_wm_sync();
+	case SYS_WIN_CREATE:
+		return sys_win_create((const struct win_create *)a1,
+				      (struct win_info *)a2);
+	case SYS_WIN_PRESENT:
+		return sys_win_present();
+	case SYS_WIN_CLOSE:
+		return sys_win_close();
+	case SYS_TTY_CREATE:
+		return tty_create();
+	case SYS_TTY_READ: {
+		int id = a1;
+		char *buf = (char *)a2;
+		unsigned int max = (unsigned int)a3;
+
+		if (!tty_valid(id) || !buf || !max ||
+		    !paging_user_range_ok(procs[current_pid].cr3,
+					  (unsigned int)buf, max, 1))
+			return -1;
+		return tty_read(id, buf, max);
+	}
+	case SYS_SPAWN: {
+		struct sys_spawn in;
+		struct vfs_file f;
+		struct vfs_mount *m = 0;
+		char path[VFS_PATH_MAX], arg[VFS_PATH_MAX], cwd[VFS_PATH_MAX];
+		int pid;
+
+		if (!paging_user_range_ok(procs[current_pid].cr3,
+					  (unsigned int)a1, sizeof(in), 0))
+			return -1;
+		{
+			const char *p = (const char *)a1;
+			unsigned int i;
+			unsigned char *d = (unsigned char *)&in;
+
+			for (i = 0; i < sizeof(in); i++)
+				d[i] = (unsigned char)p[i];
+		}
+		if (in.tty && !tty_valid((int)in.tty))
+			return -1;
+		if (copy_user_string(path, sizeof(path), in.path) != 0 ||
+		    copy_user_string(arg, sizeof(arg), in.arg) != 0 ||
+		    copy_user_string(cwd, sizeof(cwd), in.cwd) != 0)
+			return -1;
+		if (vfs_load_file(path, &f, &m) != 0)
+			return -1;
+		pid = process_create_user_tty(path, f.data, f.size, arg, cwd,
+					      in.tty);
+		vfs_release_file(m, &f);
+		return pid;
+	}
+	case SYS_SPAWN_KCMD: {
+		char name[16], arg[VFS_PATH_MAX];
+
+		if (copy_user_string(name, sizeof(name), (const char *)a1) != 0 ||
+		    copy_user_string(arg, sizeof(arg), (const char *)a2) != 0)
+			return -1;
+		if (a3 && !tty_valid(a3))
+			return -1;
+		return term_kcmd_spawn(name, arg, (unsigned int)a3);
+	}
+	case SYS_ALIVE:
+		return process_is_alive((unsigned int)a1);
+	case SYS_KILL:
+		return process_kill((unsigned int)a1);
+	case SYS_CHDIR: {
+		char arg[VFS_PATH_MAX], abs[VFS_PATH_MAX];
+		unsigned int size;
+		int is_dir;
+
+		if (copy_user_string(arg, sizeof(arg), (const char *)a1) != 0)
+			return -1;
+		if (vfs_join_path(procs[current_pid].cwd, arg[0] ? arg : ".",
+				  abs, sizeof(abs)) != 0)
+			return -1;
+		if (vfs_stat(abs, &size, &is_dir) != 0 || !is_dir)
+			return -1;
+		{
+			unsigned int i;
+			for (i = 0; abs[i] && i + 1 < sizeof(procs[current_pid].cwd); i++)
+				procs[current_pid].cwd[i] = abs[i];
+			procs[current_pid].cwd[i] = '\0';
+		}
+		return 0;
+	}
 	default:
 		return -1;
 	}

+ 35 - 0
syscall.h

@@ -85,6 +85,41 @@
 #define SYS_KEY_POLL     55  /* () -> 0 none, ASCII, or IO_KEY_*; gfx session only */
 #define SYS_RTC_HMS      56  /* (struct sys_time *out) -> 0/-1 */
 
+/* Window-manager service (see wm_abi.h).  Only the kernel-spawned WM process
+ * may call the WM_* entries; ordinary commands get -1. */
+#define SYS_WM_ATTACH      57  /* (struct wm_screen_info *out) -> 0/-1 */
+#define SYS_WM_INFO        58  /* (index, struct wm_window_info *out) -> 1/0/-1 */
+#define SYS_WM_MAP         59  /* (index, struct wm_map_info *out) -> 0/-1 */
+#define SYS_WM_ACK         60  /* (index, dirty_seq) -> 0/-1 */
+#define SYS_WM_FOCUS       61  /* (index) -> 0/-1 */
+#define SYS_WM_SET_GEOM    62  /* (index, struct wm_geom *in) -> 0/-1 */
+#define SYS_WM_CREATE_TERM 63  /* () -> index / -1 */
+#define SYS_WM_CLOSE       64  /* (index) -> 0/-1 */
+#define SYS_WM_POLL        65  /* (struct wm_status *out) -> 0/-1 */
+#define SYS_WM_BEGIN       66  /* () -> 0/-1; erase cursor, frame active */
+#define SYS_WM_PRESENT     67  /* (struct wm_present_info *in) -> 0/-1 */
+#define SYS_WM_SYNC        68  /* () -> 0/-1; run deferred gfx cleanup */
+#define SYS_RTC_DATETIME   69  /* (char *buf, unsigned max) -> 0/-1 */
+#define SYS_WIN_CREATE     70  /* (struct win_create *in, struct win_info *out) */
+#define SYS_WIN_PRESENT    71  /* () -> 0/-1; publish the back canvas */
+#define SYS_WIN_CLOSE      72  /* () -> 0/-1; close the caller's window */
+
+/* Terminal / process services used by the ring-3 shell. */
+#define SYS_TTY_CREATE     73  /* () -> tty id 1..TTY_MAX / -1 */
+#define SYS_TTY_READ       74  /* (id, buf, max) -> bytes / 0 / -1 */
+#define SYS_SPAWN          75  /* (path, arg, tty, cwd) -> pid / <0 */
+#define SYS_SPAWN_KCMD     76  /* (name, arg, tty) -> pid / <0 */
+#define SYS_ALIVE          77  /* (pid) -> 1/0 */
+#define SYS_KILL           78  /* (pid) -> 0/-1 */
+#define SYS_CHDIR          79  /* (path) -> 0/-1 */
+
+struct sys_spawn {
+	const char *path;
+	const char *arg;
+	const char *cwd;
+	unsigned int tty;
+};
+
 struct sys_netinfo {
 	unsigned int present;
 	unsigned char mac[6];

+ 98 - 0
terminal.c

@@ -4,6 +4,8 @@
 #include "io.h"
 #include "dbg.h"
 #include "kexec.h"
+#include "kmalloc.h"
+#include "mm.h"
 #include "process.h"
 #include "terminal.h"
 #include "timer.h"
@@ -1291,6 +1293,102 @@ void term_run(struct term *t)
 }
 }
 
+struct kcmd_ctx {
+	char name[16];
+	char args[VFS_PATH_MAX];
+};
+
+static const struct kcmd *kcmd_find(const char *name)
+{
+	unsigned int i;
+
+	for (i = 0; i < NCMDS; i++)
+		if (cmds[i].name[0] == name[0]) {
+			unsigned int j = 0;
+			while (cmds[i].name[j] && name[j] && cmds[i].name[j] == name[j])
+				j++;
+			if (!cmds[i].name[j] && !name[j])
+				return &cmds[i];
+		}
+	return 0;
+}
+
+static void kcmd_entry(void *arg)
+{
+	struct kcmd_ctx *ctx = (struct kcmd_ctx *)arg;
+	const struct kcmd *c = kcmd_find(ctx->name);
+
+	if (c) {
+		if (c->kind == CK_CUSTOM) {
+			struct term *t = (struct term *)mm_alloc_pages(2);
+			unsigned int i;
+
+			if (!t) {
+				io_putstr("kcmd: out of memory\n");
+			} else {
+				unsigned char *p = (unsigned char *)t;
+
+				for (i = 0; i < 2 * PAGE_SIZE; i++)
+					p[i] = 0;
+				t->fg_pid = -1;
+				for (i = 0; i + 1 < sizeof(t->cwd) &&
+					    procs[current_pid].cwd[i]; i++)
+					t->cwd[i] = procs[current_pid].cwd[i];
+				t->cwd[i] = '\0';
+				{
+					const char *def = "/ramfs/bin";
+					for (i = 0; def[i] && i + 1 < sizeof(t->path); i++)
+						t->path[i] = def[i];
+					t->path[i] = '\0';
+				}
+				c->custom(t, ctx->args);
+				mm_free_page((unsigned int)t);
+				mm_free_page((unsigned int)t + PAGE_SIZE);
+			}
+		} else if (c->kind == CK_SPAWN) {
+			if (c->fixed)
+				c->fn_arg(c->fixed);
+			else
+				c->fn();
+		} else if (c->kind == CK_SPAWN_ARG) {
+			c->fn_arg(ctx->args);
+		}
+	} else {
+		io_putstr(ctx->name);
+		io_putstr(": no such kernel command\n");
+	}
+	kfree(ctx);
+	process_exit();
+}
+
+int term_kcmd_spawn(const char *name, const char *args, unsigned int tty)
+{
+	const struct kcmd *c = kcmd_find(name);
+	struct kcmd_ctx *ctx;
+	unsigned int i;
+	int pid;
+
+	if (!c || (c->flags & CMD_BUILTIN))
+		return -1;
+	ctx = (struct kcmd_ctx *)kmalloc(sizeof(*ctx));
+	if (!ctx)
+		return -1;
+	for (i = 0; i + 1 < sizeof(ctx->name) && name[i]; i++)
+		ctx->name[i] = name[i];
+	ctx->name[i] = '\0';
+	for (i = 0; i + 1 < sizeof(ctx->args) && args[i]; i++)
+		ctx->args[i] = args[i];
+	ctx->args[i] = '\0';
+	pid = process_create_ptr("kcmd", kcmd_entry, ctx);
+	if (pid < 0) {
+		kfree(ctx);
+		return -1;
+	}
+	if (tty)
+		process_set_tty((unsigned int)pid, (int)tty);
+	return pid;
+}
+
 void term_entry(void *arg)
 {
 	struct term *t = (struct term *)arg;

+ 4 - 0
terminal.h

@@ -33,6 +33,10 @@ struct term {
 void term_entry(void *arg);
 void term_run(struct term *t);
 
+/* Ring-3 terminal: run a privileged kernel command as a kernel process with
+ * output on `tty` (the command table and handlers stay in terminal.c). */
+int term_kcmd_spawn(const char *name, const char *args, unsigned int tty);
+
 /* Single-producer (WM) / single-consumer (terminal) key queue. */
 static inline void term_key_push(struct term *t, int k)
 {

+ 150 - 0
tty.c

@@ -0,0 +1,150 @@
+/* TTY output rings.  Commands write bytes; the terminal process drains and
+ * renders them.  A full ring blocks the writer (a terminal that is not
+ * scheduled will drain shortly), so `cat`/helpers cannot silently lose output. */
+
+#include "tty.h"
+#include "mm.h"
+#include "process.h"
+
+#define TTY_STRIDE (2 * PAGE_SIZE)
+
+struct tty {
+	int used;
+	unsigned int owner;
+	unsigned char buf[TTY_BUF];
+	unsigned int head, tail;
+};
+
+_Static_assert(sizeof(struct tty) <= TTY_STRIDE,
+	       "tty state no longer fits its two-page slot");
+
+/* The rings are 16 KB of state; keep them out of BSS so the kernel image
+ * stays below the run area. */
+static struct tty *ttys;
+static int tty_ready;
+
+static int tty_init(void)
+{
+	unsigned int base, i;
+	unsigned char *p;
+
+	if (tty_ready)
+		return 1;
+	base = mm_alloc_pages(TTY_MAX * (TTY_STRIDE / PAGE_SIZE));
+	if (!base)
+		return 0;
+	p = (unsigned char *)base;
+	for (i = 0; i < TTY_MAX * TTY_STRIDE; i++)
+		p[i] = 0;
+	ttys = (struct tty *)base;
+	tty_ready = 1;
+	return 1;
+}
+
+static struct tty *tty_slot(unsigned int i)
+{
+	return (struct tty *)((unsigned char *)ttys + i * TTY_STRIDE);
+}
+
+static struct tty *tty_get(int id)
+{
+	if (!ttys || id <= 0 || id > TTY_MAX)
+		return 0;
+	return tty_slot((unsigned int)(id - 1));
+}
+
+int tty_valid(int id)
+{
+	struct tty *t = tty_get(id);
+
+	return t && t->used;
+}
+
+int tty_create(void)
+{
+	unsigned int i;
+
+	if (!tty_init())
+		return -1;
+	for (i = 0; i < TTY_MAX; i++) {
+		struct tty *t = tty_slot(i);
+
+		if (!t->used) {
+			t->used = 1;
+			t->owner = procs[current_pid].pid;
+			t->head = t->tail = 0;
+			procs[current_pid].tty = (int)(i + 1);
+			return (int)(i + 1);
+		}
+	}
+	return -1;
+}
+
+void tty_close(int id)
+{
+	struct tty *t = tty_get(id);
+
+	if (t) {
+		t->used = 0;
+		t->head = t->tail = 0;
+	}
+}
+
+int tty_write(int id, const char *buf, unsigned int len)
+{
+	struct tty *t;
+	unsigned int i = 0;
+
+	if (!(t = tty_get(id)) || !t->used)
+		return -1;
+	while (i < len) {
+		unsigned int next = (t->head + 1) % TTY_BUF;
+
+		if (next == t->tail) {
+			if (!process_is_alive(t->owner))
+				return -1;
+			process_sleep_ms(1);
+			continue;
+		}
+		t->buf[t->head] = (unsigned char)buf[i++];
+		t->head = next;
+	}
+	return 0;
+}
+
+int tty_write_str(int id, const char *s)
+{
+	unsigned int n = 0;
+
+	while (s[n])
+		n++;
+	return tty_write(id, s, n);
+}
+
+int tty_read(int id, char *buf, unsigned int max)
+{
+	struct tty *t;
+	unsigned int n = 0;
+
+	if (!(t = tty_get(id)) || !t->used)
+		return -1;
+	while (n < max && t->tail != t->head) {
+		buf[n++] = (char)t->buf[t->tail];
+		t->tail = (t->tail + 1) % TTY_BUF;
+	}
+	return (int)n;
+}
+
+void tty_reap(unsigned int pid)
+{
+	unsigned int i;
+
+	if (!ttys)
+		return;
+	for (i = 0; i < TTY_MAX; i++) {
+		struct tty *t = tty_slot(i);
+
+		if (t->used && t->owner == pid)
+			t->used = 0;
+	}
+}

+ 19 - 0
tty.h

@@ -0,0 +1,19 @@
+/* Per-terminal output queues for ring-3 commands.
+ *
+ * The terminal process owns the display; commands write bytes here and the
+ * terminal reads/renders them.  One tty per terminal, inherited by children. */
+#ifndef TTY_H
+#define TTY_H
+
+#define TTY_MAX 4
+#define TTY_BUF 4096
+
+int  tty_create(void);                    /* owner = current process */
+void tty_close(int id);
+int  tty_write(int id, const char *buf, unsigned int len); /* 0/-1, blocks */
+int  tty_write_str(int id, const char *s);
+int  tty_read(int id, char *buf, unsigned int max);        /* bytes, 0 if none */
+int  tty_valid(int id);
+void tty_reap(unsigned int pid);          /* schedule() reaper hook */
+
+#endif

+ 5 - 5
ucmd_clock.c

@@ -157,12 +157,12 @@ static void draw_hands(unsigned int h, unsigned int m, unsigned int s)
 
 void _start(const char *arg)
 {
-	struct sys_gfx_info info;
+	struct win_info info;
 	struct sys_time tm;
 	unsigned int last_sec = 99;
 
 	(void)arg;
-	if (u_gfx_begin(&info) != 0) {
+	if (u_win_create(512, 320, "clock", &info) != 0) {
 		u_puts("clock: no graphics window\n");
 		u_exit(1);
 	}
@@ -185,7 +185,7 @@ void _start(const char *arg)
 	for (;;) {
 		int k = u_key_poll();
 
-		if (k == 0x1B)
+		if (k == 0x1B || k == 0x03)
 			break;
 		u_rtc_hms(&tm);
 		if (tm.hour > 23 || tm.minute > 59 || tm.second > 59) {
@@ -198,10 +198,10 @@ void _start(const char *arg)
 			draw_face();
 			draw_hands(tm.hour, tm.minute, tm.second);
 			last_sec = tm.second;
-			u_gfx_present();
+			u_win_present();
 		}
 		u_sleep_ms(50);
 	}
-	u_gfx_end();
+	u_win_close();
 	u_exit(0);
 }

+ 9 - 6
ucmd_colors.c

@@ -137,13 +137,13 @@ static void format_fps(unsigned int fps, char *buf)
 
 void _start(const char *arg)
 {
-	struct sys_gfx_info info;
+	struct win_info info;
 	unsigned short *px;
 	unsigned int w, h, phase = 0, frames = 0, last_fps, displayed = 0;
 	char fps_buf[8];
 
 	(void)arg;
-	if (u_gfx_begin(&info) != 0) {
+	if (u_win_create(512, 320, "colors", &info) != 0) {
 		u_puts("colors: no graphics window\n");
 		u_exit(1);
 	}
@@ -156,8 +156,11 @@ void _start(const char *arg)
 	for (;;) {
 		unsigned int frame_start, elapsed;
 
-		if (u_key_poll() == 0x1B)
-			break;
+		{
+			int k = u_key_poll();
+			if (k == 0x1B || k == 0x03)
+				break;
+		}
 		frame_start = u_ticks_ms();
 
 		draw_frame(px, w, h, phase);
@@ -171,12 +174,12 @@ void _start(const char *arg)
 		}
 		format_fps(displayed, fps_buf);
 		draw_string(px, w, h, 0, 0, fps_buf);
-		u_gfx_present();
+		u_win_present();
 
 		elapsed = u_ticks_ms() - frame_start;
 		if (elapsed < FRAME_MS)
 			u_sleep_ms(FRAME_MS - elapsed);
 	}
-	u_gfx_end();
+	u_win_close();
 	u_exit(0);
 }

+ 5 - 5
ucmd_edit.c

@@ -499,7 +499,7 @@ static void redraw(void)
 	draw_text_area();
 	draw_cursor(line, disp);
 	draw_status(line, disp);
-	u_gfx_present();
+	u_win_present();
 }
 
 /* ---- input ---- */
@@ -568,7 +568,7 @@ static int handle_key(int k)
 
 void _start(const char *arg)
 {
-	struct sys_gfx_info info;
+	struct win_info info;
 	int r, new_file;
 
 	if (parse_arg(arg) != 0) {
@@ -587,7 +587,7 @@ void _start(const char *arg)
 	}
 	new_file = (r == 1);
 
-	if (u_gfx_begin(&info) != 0) {
+	if (u_win_create(512, 320, "edit", &info) != 0) {
 		u_puts("edit: no graphics window\n");
 		u_exit(1);
 	}
@@ -597,7 +597,7 @@ void _start(const char *arg)
 	cols = fb_w / CELL_W;
 	rows = fb_h / CELL_H;
 	if (cols == 0 || rows < 2) {
-		u_gfx_end();
+		u_win_close();
 		u_puts("edit: window too small\n");
 		u_exit(1);
 	}
@@ -637,6 +637,6 @@ void _start(const char *arg)
 		u_sleep_ms(15);
 	}
 
-	u_gfx_end();
+	u_win_close();
 	u_exit(0);
 }

+ 141 - 0
ucmd_lib.h

@@ -4,6 +4,7 @@
 #define UCMD_LIB_H
 
 #include "syscall.h"
+#include "wm_abi.h"
 
 static inline int u_syscall1(int num, int a1)
 {
@@ -186,6 +187,146 @@ static inline int u_rtc_hms(struct sys_time *t)
 	return u_syscall1(SYS_RTC_HMS, (int)t);
 }
 
+static inline int u_rtc_datetime(char *buf, unsigned int max)
+{
+	return u_syscall2(SYS_RTC_DATETIME, (int)buf, (int)max);
+}
+
+/* Window-manager service (only the kernel-spawned /ramfs/bin/wm may use it). */
+static inline int u_wm_attach(struct wm_screen_info *out)
+{
+	return u_syscall1(SYS_WM_ATTACH, (int)out);
+}
+
+static inline int u_wm_info(unsigned int index, struct wm_window_info *out)
+{
+	return u_syscall2(SYS_WM_INFO, (int)index, (int)out);
+}
+
+static inline int u_wm_map(unsigned int index, struct wm_map_info *out)
+{
+	return u_syscall2(SYS_WM_MAP, (int)index, (int)out);
+}
+
+static inline int u_wm_ack(unsigned int index, unsigned int seq)
+{
+	return u_syscall2(SYS_WM_ACK, (int)index, (int)seq);
+}
+
+static inline int u_wm_focus(unsigned int index)
+{
+	return u_syscall1(SYS_WM_FOCUS, (int)index);
+}
+
+static inline int u_wm_set_geom(unsigned int index, int x, int y)
+{
+	struct wm_geom g;
+
+	g.x = x;
+	g.y = y;
+	return u_syscall2(SYS_WM_SET_GEOM, (int)index, (int)&g);
+}
+
+static inline int u_wm_create_term(void)
+{
+	return u_syscall0(SYS_WM_CREATE_TERM);
+}
+
+static inline int u_wm_close(unsigned int index)
+{
+	return u_syscall1(SYS_WM_CLOSE, (int)index);
+}
+
+static inline int u_wm_poll(struct wm_status *out)
+{
+	return u_syscall1(SYS_WM_POLL, (int)out);
+}
+
+static inline int u_wm_begin(void)
+{
+	return u_syscall0(SYS_WM_BEGIN);
+}
+
+static inline int u_wm_present(struct wm_present_info *in)
+{
+	return u_syscall1(SYS_WM_PRESENT, (int)in);
+}
+
+static inline int u_wm_sync(void)
+{
+	return u_syscall0(SYS_WM_SYNC);
+}
+
+/* Generic canvas window (gfx commands own a window instead of replacing a
+ * terminal's content). */
+static inline int u_win_create(unsigned int w, unsigned int h, const char *title,
+			       struct win_info *out)
+{
+	struct win_create in;
+	unsigned int i = 0;
+
+	in.w = w;
+	in.h = h;
+	while (title && title[i] && i < sizeof(in.title) - 1) {
+		in.title[i] = title[i];
+		i++;
+	}
+	in.title[i] = '\0';
+	return u_syscall2(SYS_WIN_CREATE, (int)&in, (int)out);
+}
+
+static inline int u_win_present(void)
+{
+	return u_syscall0(SYS_WIN_PRESENT);
+}
+
+static inline int u_win_close(void)
+{
+	return u_syscall0(SYS_WIN_CLOSE);
+}
+
+static inline int u_tty_create(void)
+{
+	return u_syscall0(SYS_TTY_CREATE);
+}
+
+static inline int u_tty_read(int id, char *buf, unsigned int max)
+{
+	return u_syscall3(SYS_TTY_READ, id, (int)buf, (int)max);
+}
+
+static inline int u_spawn(const char *path, const char *arg, int tty,
+			  const char *cwd)
+{
+	struct sys_spawn s;
+
+	s.path = path;
+	s.arg = arg;
+	s.cwd = cwd;
+	s.tty = (unsigned int)tty;
+	return u_syscall1(SYS_SPAWN, (int)&s);
+}
+
+static inline int u_spawn_kcmd(const char *name, const char *arg, int tty)
+{
+	return u_syscall3(SYS_SPAWN_KCMD, (int)name, (int)arg, tty);
+}
+
+static inline int u_alive(unsigned int pid)
+{
+	return u_syscall1(SYS_ALIVE, (int)pid);
+}
+
+static inline int u_kill(unsigned int pid)
+{
+	return u_syscall1(SYS_KILL, (int)pid);
+}
+
+static inline int u_chdir(const char *path)
+{
+	return u_syscall1(SYS_CHDIR, (int)path);
+}
+
 static inline int u_gfx_begin(struct sys_gfx_info *info)
 {
 	return u_syscall1(SYS_GFX_BEGIN, (int)info);

+ 530 - 0
ucmd_term.c

@@ -0,0 +1,530 @@
+/* Ring-3 terminal: owns a canvas window, a cell grid and the shell.  Text
+ * commands write bytes to the tty; this process drains and renders them.
+ * Privileged kernel commands are spawned as kernel processes (term_kcmd). */
+
+#include "ucmd_lib.h"
+#include "uwm_lib.h"
+#include "io.h"
+#include "vfs.h"
+
+#define COLS 64
+#define ROWS 32
+#define BUF_MAX 256
+#define LINE_MAX 128
+#define HIST_MAX 16
+
+static struct win_info wi;
+static struct usurf surf;
+static int tty;
+static unsigned short cells[COLS * ROWS];
+static unsigned int cx, cy;
+static char line[LINE_MAX];
+static unsigned int line_len;
+static char cwd[VFS_PATH_MAX];
+static char path[VFS_PATH_MAX];
+static char hist[HIST_MAX][LINE_MAX];
+static unsigned int hist_count, hist_next;
+static int fg_pid = -1;
+static int dirty = 1;
+static int cursor_on = 1;
+static unsigned int last_blink;
+
+static unsigned short *cell_at(unsigned int x, unsigned int y)
+{
+	return &cells[y * COLS + x];
+}
+
+static void cell_put(unsigned int x, unsigned int y, char ch)
+{
+	*cell_at(x, y) = (unsigned short)(0x0A00 | (unsigned char)ch);
+}
+
+static void scroll_up(void)
+{
+	unsigned int i;
+
+	for (i = 0; i < (ROWS - 1) * COLS; i++)
+		cells[i] = cells[i + COLS];
+	for (; i < ROWS * COLS; i++)
+		cells[i] = 0x0A20;
+}
+
+static void term_newline(void)
+{
+	cx = 0;
+	cy++;
+	if (cy >= ROWS) {
+		scroll_up();
+		cy = ROWS - 1;
+	}
+	dirty = 1;
+}
+
+static void term_putc(char c)
+{
+	if (c == '\n') {
+		term_newline();
+		return;
+	}
+	if (c == '\r') {
+		cx = 0;
+		dirty = 1;
+		return;
+	}
+	if (c == '\b') {
+		if (cx > 0)
+			cx--;
+		cell_put(cx, cy, ' ');
+		dirty = 1;
+		return;
+	}
+	if (c == '\t') {
+		unsigned int n = 8 - (cx % 8);
+		while (n--)
+			term_putc(' ');
+		return;
+	}
+	if (c < 0x20 || c > 0x7E)
+		return;
+	cell_put(cx, cy, c);
+	cx++;
+	if (cx >= COLS)
+		term_newline();
+	dirty = 1;
+}
+
+static void term_puts(const char *s)
+{
+	while (*s)
+		term_putc(*s++);
+}
+
+static void term_clear(void)
+{
+	unsigned int i;
+
+	for (i = 0; i < COLS * ROWS; i++)
+		cells[i] = 0x0A20;
+	cx = cy = 0;
+	dirty = 1;
+}
+
+static void cursor_set(unsigned int row, unsigned int col)
+{
+	if (row >= ROWS) row = ROWS - 1;
+	if (col >= COLS) col = COLS - 1;
+	cy = row;
+	cx = col;
+	dirty = 1;
+}
+
+/* Parse the exact "ESC[row;colH" cursor sequence used by io_set_cursor. */
+static int esc_cursor(const char *p, unsigned int n)
+{
+	unsigned int row = 0, col = 0, i = 0;
+
+	if (n < 5 || p[0] != 0x1B || p[1] != '[')
+		return 0;
+	while (i < n && p[i] >= '0' && p[i] <= '9')
+		row = row * 10 + (unsigned int)(p[i++] - '0');
+	if (i >= n || p[i++] != ';')
+		return 0;
+	while (i < n && p[i] >= '0' && p[i] <= '9')
+		col = col * 10 + (unsigned int)(p[i++] - '0');
+	if (i >= n || p[i] != 'H')
+		return 0;
+	if (row < 1 || col < 1)
+		return 0;
+	cursor_set(row - 1, col - 1);
+	return 1;
+}
+
+static void tty_feed(const char *buf, unsigned int n)
+{
+	unsigned int i = 0;
+
+	while (i < n) {
+		if (buf[i] == 0x1B) {
+			unsigned int j = i + 1;
+			char seq[24];
+			unsigned int sn = 0;
+
+			while (j < n && sn + 1 < sizeof(seq)) {
+				seq[sn++] = buf[j];
+				if ((buf[j] >= 'A' && buf[j] <= 'Z') ||
+				    (buf[j] >= 'a' && buf[j] <= 'z'))
+					break;
+				j++;
+			}
+			seq[sn] = '\0';
+			/* Rebuild with ESC prefix for the helper. */
+			{
+				char full[28];
+				unsigned int m;
+
+				full[0] = 0x1B;
+				for (m = 0; m < sn && m + 1 < sizeof(full); m++)
+					full[m + 1] = seq[m];
+				full[sn + 1] = '\0';
+				if (esc_cursor(full, sn + 1)) {
+					i = j + 1;
+					continue;
+				}
+			}
+			if (sn > 1 && seq[sn - 1] == 'J' && seq[1] == '2') {
+				term_clear();
+			} else if (sn && seq[sn - 1] == 'H') {
+				cursor_set(0, 0);
+			}
+			i = j < n ? j + 1 : n;
+			continue;
+		}
+		term_putc(buf[i++]);
+	}
+}
+
+static void drain_tty(void)
+{
+	char buf[BUF_MAX];
+	int n;
+
+	while ((n = u_tty_read(tty, buf, sizeof(buf))) > 0) {
+		tty_feed(buf, (unsigned int)n);
+		dirty = 1;
+	}
+}
+
+static void render(void)
+{
+	if (!dirty)
+		return;
+	usurf_fill(&surf, 0, 0, wi.width, wi.height, 0x000000u);
+	usurf_cells(&surf, cells, COLS, ROWS, 0, 0, 0, 0, wi.width, wi.height);
+	if (cursor_on && cx < COLS && cy < ROWS)
+		usurf_fill(&surf, (int)cx * 8, (int)cy * 10, 2, 10, 0xFFFFFFu);
+	u_win_present();
+	dirty = 0;
+}
+
+static void prompt(void)
+{
+	term_putc('[');
+	term_puts(cwd);
+	term_puts("] > ");
+	line_len = 0;
+	line[0] = '\0';
+	dirty = 1;
+}
+
+static void print_num(unsigned int n)
+{
+	char b[12];
+	unsigned int i = 0;
+
+	if (!n) {
+		term_putc('0');
+		return;
+	}
+	while (n) {
+		b[i++] = (char)('0' + n % 10);
+		n /= 10;
+	}
+	while (i)
+		term_putc(b[--i]);
+}
+
+static unsigned int parse_num(const char *s)
+{
+	unsigned int n = 0;
+
+	while (*s == ' ')
+		s++;
+	while (*s >= '0' && *s <= '9')
+		n = n * 10 + (unsigned int)(*s++ - '0');
+	return n;
+}
+
+static void split_line(char *word, unsigned int wsz, char *args,
+		       unsigned int asz)
+{
+	unsigned int i = 0, n = 0;
+
+	while (line[i] == ' ')
+		i++;
+	while (line[i] && line[i] != ' ' && n + 1 < wsz)
+		word[n++] = line[i++];
+	word[n] = '\0';
+	while (line[i] == ' ')
+		i++;
+	n = 0;
+	while (line[i] && n + 1 < asz)
+		args[n++] = line[i++];
+	while (n && args[n - 1] == ' ')
+		n--;
+	args[n] = '\0';
+}
+
+static int make_path(const char *dir, const char *word, char *out,
+		     unsigned int max)
+{
+	unsigned int i = 0, j;
+
+	if (word[0] == '/') {
+		for (j = 0; word[j] && j + 1 < max; j++)
+			out[j] = word[j];
+		out[j] = '\0';
+		return 0;
+	}
+	while (dir[i] && i + 1 < max)
+		out[i] = dir[i], i++;
+	if (i && out[i - 1] != '/' && i + 1 < max)
+		out[i++] = '/';
+	for (j = 0; word[j] && i + 1 < max; j++)
+		out[i++] = word[j];
+	out[i] = '\0';
+	return 0;
+}
+
+static int try_spawn(const char *word, const char *args, char *used_path,
+		     unsigned int used_size)
+{
+	char p[VFS_PATH_MAX];
+	int pid;
+
+	if (word[0] == '/') {
+		for (unsigned int i = 0; word[i] && i + 1 < used_size; i++)
+			used_path[i] = word[i];
+		return u_spawn(word, args, tty, cwd);
+	}
+	/* Try each PATH component. */
+	{
+		unsigned int i = 0, start = 0;
+
+		while (1) {
+			unsigned int n = 0;
+			char dir[VFS_PATH_MAX];
+
+			while (path[i] && path[i] != ':') {
+				if (n + 1 < sizeof(dir))
+					dir[n++] = path[i];
+				i++;
+			}
+			dir[n] = '\0';
+			if (dir[0]) {
+				make_path(dir, word, p, sizeof(p));
+				pid = u_spawn(p, args, tty, cwd);
+				if (pid >= 0) {
+					for (n = 0; p[n] && n + 1 < used_size; n++)
+						used_path[n] = p[n];
+					used_path[n] = '\0';
+					return pid;
+				}
+				if (pid == -2)
+					return -2;
+			}
+			if (!path[i])
+				break;
+			i++;
+			start = i;
+			(void)start;
+		}
+	}
+	return -1;
+}
+
+static void run_line(void)
+{
+	char word[LINE_MAX], args[LINE_MAX];
+	char used[VFS_PATH_MAX];
+	int pid;
+
+	split_line(word, sizeof(word), args, sizeof(args));
+	if (!word[0]) {
+		prompt();
+		return;
+	}
+	if (word[0] == 'c' && word[1] == 'd' && !word[2]) {
+		if (u_chdir(args[0] ? args : "/") != 0)
+			term_puts("cd: no such directory\n");
+		u_getcwd(cwd, sizeof(cwd));
+		prompt();
+		return;
+	}
+	if (word[0] == 'p' && word[1] == 'a' && word[2] == 't' && !word[3]) {
+		unsigned int i;
+		if (!args[0]) {
+			term_puts(path);
+			term_putc('\n');
+		} else {
+			for (i = 0; args[i] && i + 1 < sizeof(path); i++)
+				path[i] = args[i];
+			path[i] = '\0';
+		}
+		prompt();
+		return;
+	}
+	if (word[0] == 'h' && word[1] == 'e' && word[2] == 'l' &&
+	    word[3] == 'p' && !word[4]) {
+		term_puts("builtins: cd path help clear ps kill\n");
+		term_puts("commands: files in ");
+		term_puts(path);
+		term_putc('\n');
+		prompt();
+		return;
+	}
+	if (word[0] == 'c' && word[1] == 'l' && word[2] == 'e' &&
+	    word[3] == 'a' && word[4] == 'r' && !word[5]) {
+		term_clear();
+		prompt();
+		return;
+	}
+	if (word[0] == 'p' && word[1] == 's' && !word[2]) {
+		struct sys_procinfo pi;
+		unsigned int i = 0;
+
+		term_puts("PID  STATE  NAME\n");
+		while (u_syscall2(SYS_PROCINFO, (int)i, (int)&pi) == 1) {
+			print_num(pi.pid);
+			term_puts("  ");
+			if (pi.state == 1) term_puts("ready");
+			else if (pi.state == 2) term_puts("run  ");
+			else if (pi.state == 4) term_puts("sleep");
+			else term_puts("?    ");
+			term_puts("  ");
+			term_puts(pi.name);
+			term_putc('\n');
+			i++;
+		}
+		prompt();
+		return;
+	}
+	if (word[0] == 'k' && word[1] == 'i' && word[2] == 'l' &&
+	    word[3] == 'l' && !word[4]) {
+		unsigned int pid = parse_num(args);
+		if (!pid || u_kill(pid) != 0)
+			term_puts("kill: no such process\n");
+		prompt();
+		return;
+	}
+
+	pid = try_spawn(word, args, used, sizeof(used));
+	if (pid == -2)
+		term_puts("not an executable\n");
+	else if (pid < 0) {
+		pid = u_spawn_kcmd(word, args, tty);
+		if (pid < 0)
+			term_puts("command not found\n");
+	}
+	if (pid > 0)
+		fg_pid = pid;
+	else
+		prompt();
+}
+
+static void submit_line(void)
+{
+	term_putc('\n');
+	if (line_len) {
+		unsigned int i;
+		for (i = 0; line[i] && i < sizeof(hist[hist_next]) - 1; i++)
+			hist[hist_next][i] = line[i];
+		hist[hist_next][i] = '\0';
+		hist_next = (hist_next + 1) % HIST_MAX;
+		if (hist_count < HIST_MAX)
+			hist_count++;
+	}
+	run_line();
+}
+
+static void handle_key(int k)
+{
+	if (k == 0x03) {
+		if (fg_pid > 0) {
+			u_kill((unsigned int)fg_pid);
+			fg_pid = -1;
+			term_puts("^C\n");
+			prompt();
+		} else {
+			line_len = 0;
+			line[0] = '\0';
+			term_puts("^C\n");
+			prompt();
+		}
+		return;
+	}
+	if (k == '\n' || k == '\r') {
+		submit_line();
+		return;
+	}
+	if (k == '\b') {
+		if (line_len) {
+			line_len--;
+			line[line_len] = '\0';
+			term_putc('\b');
+		}
+		return;
+	}
+	if (k < 0x20 || k > 0x7E)
+		return;
+	if (line_len + 1 < LINE_MAX) {
+		line[line_len++] = (char)k;
+		line[line_len] = '\0';
+		term_putc((char)k);
+	}
+}
+
+void _start(const char *arg)
+{
+	unsigned int now;
+
+	(void)arg;
+	tty = u_tty_create();
+	if (tty <= 0)
+		u_exit(1);
+	if (u_win_create(512, 320, "term", &wi) != 0)
+		u_exit(1);
+	usurf_init(&surf, wi.fb, wi.width, wi.height, wi.width * 2, 16);
+	term_clear();
+	u_getcwd(cwd, sizeof(cwd));
+	{
+		const char *def = "/ramfs/bin";
+		unsigned int i;
+		for (i = 0; def[i] && i + 1 < sizeof(path); i++)
+			path[i] = def[i];
+		path[i] = '\0';
+	}
+	prompt();
+	render();
+
+	for (;;) {
+		int got = 0;
+
+		drain_tty();
+		if (fg_pid > 0) {
+			if (!u_alive((unsigned int)fg_pid)) {
+				fg_pid = -1;
+				drain_tty();
+				prompt();
+			} else {
+				int k = u_key_poll();
+				if (k == 0x03)
+					handle_key(k);
+			}
+		} else {
+			int k = u_key_poll();
+			while (k) {
+				handle_key(k);
+				got = 1;
+				k = u_key_poll();
+			}
+		}
+		now = u_ticks_ms();
+		if (now - last_blink >= 500) {
+			last_blink = now;
+			cursor_on = !cursor_on;
+			dirty = 1;
+		}
+		render();
+		u_sleep_ms(got ? 1 : 10);
+	}
+}

+ 497 - 0
ucmd_wm.c

@@ -0,0 +1,497 @@
+/* Ring-3 window manager: maps the shadow buffer and each window's content,
+ * draws the desktop/chrome and composites the terminal cell grids or gfx
+ * canvases.  All glyphs and colours are userland; the kernel only routes
+ * input, stores window state and copies damage to VRAM. */
+
+#include "ucmd_lib.h"
+#include "uwm_lib.h"
+#include "version.h"
+
+#define COL_BG        0x202030u
+#define COL_BORDER    0xC8C8C8u
+#define COL_TITLE_ON  0x465A96u
+#define COL_TITLE_OFF 0x646464u
+#define COL_CLOSE     0xBE3C3Cu
+#define COL_WHITE     0xFFFFFFu
+#define COL_BANNER    0x55FF55u
+
+struct uwin {
+	struct wm_window_info info;
+	struct wm_map_info map;
+	int mapped;
+	unsigned int ack_seq;
+};
+
+static struct usurf screen;
+static struct uwin wins[WM_MAX_WINDOWS];
+static unsigned int fbw, fbh;
+static int drag_id = -1;
+static int drag_dx, drag_dy;
+static unsigned int prev_buttons;
+static int full_redraw = 1;
+static unsigned int bar_kexec_busy, bar_kexec_progress, bar_kexec_total;
+
+static unsigned int rgb16(unsigned int r, unsigned int g, unsigned int b)
+{
+	return (r << 16) | (g << 8) | b;
+}
+
+static void fill_clip(int x, int y, unsigned int w, unsigned int h,
+		      unsigned int rgb, int cx, int cy,
+		      unsigned int cw, unsigned int ch)
+{
+	int x0 = x, y0 = y, x1 = x + (int)w, y1 = y + (int)h;
+
+	if (x0 < cx) x0 = cx;
+	if (y0 < cy) y0 = cy;
+	if (x1 > cx + (int)cw) x1 = cx + (int)cw;
+	if (y1 > cy + (int)ch) y1 = cy + (int)ch;
+	if (x1 > x0 && y1 > y0)
+		usurf_fill(&screen, x0, y0, (unsigned int)(x1 - x0),
+			   (unsigned int)(y1 - y0), rgb);
+}
+
+static void draw_bar(void)
+{
+	char dt[48];
+	unsigned int n, i, x, y;
+
+	usurf_fill(&screen, 0, 0, fbw, WM_BAR_H, COL_BG);
+	usurf_text(&screen, 4, 5, OS_NAME " v" OS_VERSION, COL_BANNER,
+		   0, 0, fbw, WM_BAR_H);
+	usurf_fill(&screen, WM_BTN_X, WM_BTN_Y, WM_BTN_W, WM_BTN_H, 0x963CD2u);
+	usurf_text(&screen, WM_BTN_X + 4, WM_BTN_Y + 3, "+ New", COL_WHITE,
+		   0, 0, fbw, WM_BAR_H);
+
+	/* Rainbow separator (same y as the kernel's old bar). */
+	for (x = 0; x < fbw; x++) {
+		unsigned int seg = (x * (6 * 256)) / (fbw ? fbw : 1);
+		unsigned int s = seg / 256, f = seg % 256;
+		unsigned int r1, g1, b1, r2, g2, b2, r, g, b;
+
+		switch (s) {
+		case 0: r1=255; g1=0;   b1=0;   r2=255; g2=255; b2=0;   break;
+		case 1: r1=255; g1=255; b1=0;   r2=0;   g2=255; b2=0;   break;
+		case 2: r1=0;   g1=255; b1=0;   r2=0;   g2=255; b2=255; break;
+		case 3: r1=0;   g1=255; b1=255; r2=0;   g2=0;   b2=255; break;
+		case 4: r1=0;   g1=0;   b1=255; r2=255; g2=0;   b2=255; break;
+		default:r1=255; g1=0;   b1=255; r2=255; g2=0;   b2=0;   break;
+		}
+		r = (r1 * (256 - f) + r2 * f) / 256;
+		g = (g1 * (256 - f) + g2 * f) / 256;
+		b = (b1 * (256 - f) + b2 * f) / 256;
+		for (y = 18; y < 20; y++)
+			usurf_fill(&screen, (int)x, (int)y, 1, 1, rgb16(r, g, b));
+	}
+
+	if (bar_kexec_busy) {
+		static const char msg[] = "loading new kernel over serial";
+		unsigned int dots = bar_kexec_total ?
+			(bar_kexec_progress * 12 / bar_kexec_total) : 0;
+
+		n = 0;
+		while (msg[n])
+			dt[n] = msg[n], n++;
+		for (i = 0; i < 12; i++)
+			dt[n + i] = (i < dots) ? '.' : ' ';
+		n += 12;
+		dt[n] = '\0';
+		usurf_text(&screen, (int)fbw - (int)n * 8 - 4, 5, dt,
+			   0xFFC864u, 0, 0, fbw, WM_BAR_H);
+	} else if (u_rtc_datetime(dt, sizeof(dt)) == 0) {
+		n = 0;
+		while (dt[n] && n < sizeof(dt) - 1)
+			n++;
+		usurf_text(&screen, (int)fbw - (int)n * 8 - 4, 5, dt,
+			   COL_BANNER, 0, 0, fbw, WM_BAR_H);
+	}
+}
+
+static void draw_window_clip(unsigned int idx, int cx, int cy,
+			     unsigned int cw, unsigned int ch)
+{
+	struct uwin *u = &wins[idx];
+	struct wm_window_info *w = &u->info;
+	int x = w->x, y = w->y;
+	unsigned int pw = w->w, ph = w->h;
+	unsigned int bx = (unsigned int)(x + (int)pw - 1 - WM_CLOSE_W);
+	unsigned int cony = (unsigned int)(y + 1 + WM_TITLE_H);
+	unsigned int content_x = (unsigned int)(x + 1);
+	unsigned int content_w = w->content_w;
+	unsigned int content_h = w->content_h;
+
+	/* Border, title bar, close button. */
+	fill_clip(x, y, pw, ph, COL_BORDER, cx, cy, cw, ch);
+	fill_clip(x + 1, y + 1, pw - 2, WM_TITLE_H,
+		  w->focused ? COL_TITLE_ON : COL_TITLE_OFF, cx, cy, cw, ch);
+	usurf_text(&screen, x + 4, y + 3, w->title, COL_WHITE,
+		   cx, cy, cw, ch);
+	fill_clip((int)bx, y + 1, WM_CLOSE_W, WM_TITLE_H, COL_CLOSE,
+		  cx, cy, cw, ch);
+	usurf_text(&screen, (int)bx + 3, y + 3, "x", COL_WHITE,
+		   cx, cy, cw, ch);
+
+	/* Content. */
+	fill_clip((int)content_x, (int)cony, content_w, content_h,
+		  0x000000u, cx, cy, cw, ch);
+	if (u->mapped) {
+		if (w->kind == WM_KIND_GFX) {
+			struct uwm_canvas c;
+
+			c.px = (const unsigned short *)u->map.va;
+			c.w = u->map.w;
+			c.h = u->map.h;
+			usurf_canvas(&screen, &c, (int)content_x, (int)cony,
+				     cx, cy, cw, ch);
+		} else if (u->map.kind == WM_KIND_TEXT) {
+			usurf_cells(&screen, (const unsigned short *)u->map.va,
+				    w->cols, w->rows, (int)content_x, (int)cony,
+				    cx, cy, cw, ch);
+		}
+	}
+
+	/* Text cursor overlay (only for the focused terminal). */
+	if (w->kind == WM_KIND_TEXT && w->focused && w->cursor_visible &&
+	    w->cols && w->rows && w->cursor < w->cols * w->rows) {
+		unsigned int col = w->cursor % w->cols;
+		unsigned int row = w->cursor / w->cols;
+		unsigned int px = content_x + col * 8;
+		unsigned int py = cony + row * 10;
+
+		fill_clip((int)px, (int)py, 2, 10, COL_WHITE,
+			  cx, cy, cw, ch);
+	}
+}
+
+static void draw_rect(int x, int y, unsigned int w, unsigned int h)
+{
+	unsigned int i;
+
+	if (w == 0 || h == 0 || x >= (int)fbw || y >= (int)fbh)
+		return;
+	usurf_fill(&screen, x, y, w, h, COL_BG);
+	for (i = 0; i < WM_MAX_WINDOWS; i++)
+		if (wins[i].info.used && !wins[i].info.focused &&
+		    x < wins[i].info.x + (int)wins[i].info.w &&
+		    x + (int)w > wins[i].info.x &&
+		    y < wins[i].info.y + (int)wins[i].info.h &&
+		    y + (int)h > wins[i].info.y)
+			draw_window_clip(i, x, y, w, h);
+	for (i = 0; i < WM_MAX_WINDOWS; i++)
+		if (wins[i].info.used && wins[i].info.focused &&
+		    x < wins[i].info.x + (int)wins[i].info.w &&
+		    x + (int)w > wins[i].info.x &&
+		    y < wins[i].info.y + (int)wins[i].info.h &&
+		    y + (int)h > wins[i].info.y)
+			draw_window_clip(i, x, y, w, h);
+}
+
+static int window_at(unsigned int mx, unsigned int my)
+{
+	unsigned int i;
+
+	for (i = 0; i < WM_MAX_WINDOWS; i++)
+		if (wins[i].info.used && wins[i].info.focused &&
+		    mx >= (unsigned int)wins[i].info.x &&
+		    my >= (unsigned int)wins[i].info.y &&
+		    mx < (unsigned int)(wins[i].info.x + (int)wins[i].info.w) &&
+		    my < (unsigned int)(wins[i].info.y + (int)wins[i].info.h))
+			return (int)i;
+	for (i = 0; i < WM_MAX_WINDOWS; i++)
+		if (wins[i].info.used && !wins[i].info.focused &&
+		    mx >= (unsigned int)wins[i].info.x &&
+		    my >= (unsigned int)wins[i].info.y &&
+		    mx < (unsigned int)(wins[i].info.x + (int)wins[i].info.w) &&
+		    my < (unsigned int)(wins[i].info.y + (int)wins[i].info.h))
+			return (int)i;
+	return -1;
+}
+
+static void clamp_geom(struct uwin *u, int *x, int *y)
+{
+	int maxx = (int)fbw - (int)u->info.w;
+	int maxy = (int)fbh - (int)u->info.h;
+
+	if (*x < 0) *x = 0;
+	if (*y < WM_BAR_H) *y = WM_BAR_H;
+	if (maxx < 0) maxx = 0;
+	if (maxy < WM_BAR_H) maxy = WM_BAR_H;
+	if (*x > maxx) *x = maxx;
+	if (*y > maxy) *y = maxy;
+}
+
+static void add_rect(struct wm_present_info *p, int x, int y,
+		     unsigned int w, unsigned int h)
+{
+	if (w == 0 || h == 0)
+		return;
+	if (p->count < 4) {
+		p->rect[p->count].x = x;
+		p->rect[p->count].y = y;
+		p->rect[p->count].w = w;
+		p->rect[p->count].h = h;
+		p->count++;
+	} else {
+		/* Four is enough for normal updates; fold the rest into the
+		 * last rect rather than dropping pixels. */
+		int x0 = p->rect[3].x, y0 = p->rect[3].y;
+		int x1 = x0 + (int)p->rect[3].w, y1 = y0 + (int)p->rect[3].h;
+		int nx1 = x + (int)w, ny1 = y + (int)h;
+
+		if (x < x0) x0 = x;
+		if (y < y0) y0 = y;
+		if (nx1 > x1) x1 = nx1;
+		if (ny1 > y1) y1 = ny1;
+		p->rect[3].x = x0;
+		p->rect[3].y = y0;
+		p->rect[3].w = (unsigned int)(x1 - x0);
+		p->rect[3].h = (unsigned int)(y1 - y0);
+	}
+}
+
+static void do_update(struct wm_status *st)
+{
+	struct wm_present_info present;
+	int need = 0;
+	int bar_dirty = 0;
+	unsigned int i;
+	char dt[20];
+	static char last_dt[20];
+	int kexec_changed = (st->kexec_busy != bar_kexec_busy) ||
+		(st->kexec_busy && st->kexec_progress != bar_kexec_progress);
+
+	bar_kexec_busy = st->kexec_busy;
+	bar_kexec_progress = st->kexec_progress;
+	bar_kexec_total = st->kexec_total;
+	if (kexec_changed)
+		bar_dirty = 1;
+
+	/* Refresh cached window state and mappings before opening a frame:
+	 * MAP may unmap/remap content. */
+	for (i = 0; i < WM_MAX_WINDOWS; i++) {
+		struct wm_window_info info;
+		int r = u_wm_info(i, &info);
+
+		if (r < 0) {
+			u_exit(1);
+		}
+		if (r == 0 || !info.used) {
+			if (wins[i].info.used)
+				full_redraw = 1;
+			wins[i].info.used = 0;
+			wins[i].mapped = 0;
+			continue;
+		}
+		if (!wins[i].info.used || info.content_gen != wins[i].info.content_gen ||
+		    info.kind != wins[i].info.kind)
+			full_redraw = 1;
+		wins[i].info = info;
+		if (!wins[i].mapped || wins[i].map.kind != info.kind ||
+		    wins[i].map.generation != info.content_gen) {
+			struct wm_map_info map;
+
+			if (u_wm_map(i, &map) == 0) {
+				wins[i].map = map;
+				wins[i].mapped = 1;
+			} else {
+				wins[i].mapped = 0;
+			}
+		}
+	}
+	if (u_rtc_datetime(dt, sizeof(dt)) == 0) {
+		for (i = 0; i < sizeof(dt); i++)
+			if (dt[i] != last_dt[i]) {
+				for (i = 0; i < sizeof(dt); i++)
+					last_dt[i] = dt[i];
+				bar_dirty = 1;
+				break;
+			}
+	}
+	if (full_redraw) {
+		if (u_wm_begin() != 0) {
+			full_redraw = 1;
+			return;
+		}
+		full_redraw = 0;
+		need = 1;
+		{
+			usurf_fill(&screen, 0, 0, fbw, fbh, COL_BG);
+			for (i = 0; i < WM_MAX_WINDOWS; i++)
+				if (wins[i].info.used && !wins[i].info.focused)
+					draw_window_clip(i, 0, 0, fbw, fbh);
+			for (i = 0; i < WM_MAX_WINDOWS; i++)
+				if (wins[i].info.used && wins[i].info.focused)
+					draw_window_clip(i, 0, 0, fbw, fbh);
+			draw_bar();
+			present.count = 0;
+			add_rect(&present, 0, 0, fbw, fbh);
+			present.immediate = 0;
+			u_wm_present(&present);
+			/* Ack every window that was clean at the time of the
+			 * redraw.  If new damage arrived during it, its seq
+			 * differs and the kernel leaves it dirty. */
+			for (i = 0; i < WM_MAX_WINDOWS; i++)
+				if (wins[i].info.used && wins[i].mapped)
+					u_wm_ack(i, wins[i].info.dirty_seq);
+		}
+		return;
+	}
+
+	/* Partial cell/canvas updates and the bar clock. */
+	present.count = 0;
+	present.immediate = 0;
+	if (bar_dirty) {
+		need = 1;
+		add_rect(&present, 0, 0, fbw, WM_BAR_H);
+	}
+	for (i = 0; i < WM_MAX_WINDOWS; i++) {
+		struct uwin *u = &wins[i];
+		struct wm_window_info *w = &u->info;
+		int rx, ry;
+		unsigned int rw, rh;
+
+		if (!w->used || !w->dirty)
+			continue;
+		if (w->kind == WM_KIND_GFX) {
+			rx = w->x + 1;
+			ry = w->y + 1 + WM_TITLE_H;
+			rw = w->content_w;
+			rh = w->content_h;
+		} else {
+			if (!w->dmg_cols || !w->dmg_rows)
+				continue;
+			rx = w->x + 1 + (int)w->dmg_col0 * 8;
+			ry = w->y + 1 + WM_TITLE_H + (int)w->dmg_row0 * 10;
+			rw = w->dmg_cols * 8;
+			rh = w->dmg_rows * 10;
+		}
+		add_rect(&present, rx, ry, rw, rh);
+		u->ack_seq = u->mapped ? w->dirty_seq : 0;
+		need = 1;
+	}
+
+	if (!need) {
+		/* Drag movement is handled below; a stationary mouse can be
+		 * left to the kernel's cursor overlay. */
+		return;
+	}
+	if (u_wm_begin() != 0)
+		return;
+
+	for (i = 0; i < present.count; i++)
+		draw_rect(present.rect[i].x, present.rect[i].y,
+			  present.rect[i].w, present.rect[i].h);
+	if (bar_dirty)
+		draw_bar();
+
+	for (i = 0; i < WM_MAX_WINDOWS; i++) {
+		struct uwin *u = &wins[i];
+
+		if (!u->info.used || !u->info.dirty || !u->mapped ||
+		    !u->ack_seq)
+			continue;
+		if (u->ack_seq == u->info.dirty_seq)
+			u_wm_ack(i, u->info.dirty_seq);
+	}
+	u_wm_present(&present);
+}
+
+static void handle_mouse(struct wm_status *st)
+{
+	unsigned int buttons = st->mouse.buttons;
+	unsigned int mx = st->mouse.x, my = st->mouse.y;
+	int down = (buttons & 1) != 0;
+	int was = (prev_buttons & 1) != 0;
+
+	if (down && !was) {
+		if (mx >= WM_BTN_X && my >= WM_BTN_Y &&
+		    mx < WM_BTN_X + WM_BTN_W && my < WM_BTN_Y + WM_BTN_H) {
+			u_wm_create_term();
+			full_redraw = 1;
+		} else {
+			int idx = window_at(mx, my);
+
+			if (idx >= 0) {
+				struct uwin *u = &wins[idx];
+
+				u_wm_focus((unsigned int)idx);
+				if (mx >= (unsigned int)(u->info.x + (int)u->info.w -
+							 1 - WM_CLOSE_W) &&
+				    mx < (unsigned int)(u->info.x + (int)u->info.w) &&
+				    my >= (unsigned int)(u->info.y + 1) &&
+				    my < (unsigned int)(u->info.y + 1 + WM_TITLE_H)) {
+					u_wm_close((unsigned int)idx);
+					full_redraw = 1;
+				} else if (my < (unsigned int)(u->info.y + WM_TITLE_H)) {
+					drag_id = idx;
+					drag_dx = (int)mx - u->info.x;
+					drag_dy = (int)my - u->info.y;
+				}
+			}
+		}
+	} else if (down && was && drag_id >= 0) {
+		struct uwin *u = &wins[drag_id];
+
+		if (u->info.used) {
+			int ox = u->info.x, oy = u->info.y;
+			int nx = (int)mx - drag_dx;
+			int ny = (int)my - drag_dy;
+
+			clamp_geom(u, &nx, &ny);
+			if (nx != ox || ny != oy) {
+				struct wm_present_info present;
+				unsigned int i;
+
+				u_wm_set_geom((unsigned int)drag_id, nx, ny);
+				u->info.x = nx;
+				u->info.y = ny;
+				present.count = 0;
+				present.immediate = 1;
+				add_rect(&present, ox, oy, u->info.w, u->info.h);
+				add_rect(&present, nx, ny, u->info.w, u->info.h);
+				if (u_wm_begin() == 0) {
+					for (i = 0; i < present.count; i++)
+						draw_rect(present.rect[i].x,
+							  present.rect[i].y,
+							  present.rect[i].w,
+							  present.rect[i].h);
+					u_wm_present(&present);
+				}
+			}
+		} else {
+			drag_id = -1;
+		}
+	} else if (!down && was) {
+		drag_id = -1;
+	}
+	prev_buttons = buttons;
+}
+
+void _start(const char *arg)
+{
+	struct wm_screen_info si;
+	struct wm_status st;
+	unsigned int i;
+
+	(void)arg;
+	if (u_wm_attach(&si) != 0)
+		u_exit(1);
+	usurf_init(&screen, si.fb, si.width, si.height, si.pitch, si.bpp);
+	fbw = si.width;
+	fbh = si.height;
+	for (i = 0; i < WM_MAX_WINDOWS; i++) {
+		wins[i].info.used = 0;
+		wins[i].mapped = 0;
+	}
+	full_redraw = 1;
+
+	for (;;) {
+		if (u_wm_poll(&st) != 0)
+			u_exit(1);
+		if (st.full_redraw)
+			full_redraw = 1;
+		handle_mouse(&st);
+		do_update(&st);
+		u_sleep_ms(10);
+	}
+}

+ 256 - 0
uwm_lib.c

@@ -0,0 +1,256 @@
+/* Userland drawing primitives for the ring-3 WM.  Mirrors the kernel's
+ * fbtext/gfx byte order so the mapped shadow matches the kernel console. */
+
+#include "uwm_lib.h"
+#include "font_8x8.h"
+
+#define FONT_H 8
+
+static const unsigned char pal_r[16] = {
+	0, 0, 0, 0, 170, 170, 170, 170, 85, 85, 85, 85, 255, 255, 255, 255
+};
+static const unsigned char pal_g[16] = {
+	0, 0, 0, 170, 0, 0, 85, 170, 85, 85, 255, 255, 85, 85, 255, 255
+};
+static const unsigned char pal_b[16] = {
+	0, 0, 170, 0, 170, 170, 0, 170, 85, 255, 85, 255, 85, 255, 85, 255
+};
+
+void usurf_init(struct usurf *s, void *px, unsigned int w, unsigned int h,
+		unsigned int pitch, unsigned int bpp)
+{
+	s->px = (unsigned char *)px;
+	s->w = w;
+	s->h = h;
+	s->pitch = pitch;
+	s->bpp = bpp;
+}
+
+static void put_px(struct usurf *s, unsigned int x, unsigned int y,
+		   unsigned int r, unsigned int g, unsigned int b)
+{
+	unsigned char *p;
+
+	if (x >= s->w || y >= s->h)
+		return;
+	p = s->px + (unsigned long)y * s->pitch;
+	if (s->bpp == 16) {
+		unsigned int v = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
+		unsigned short *d = (unsigned short *)p;
+		d[x] = (unsigned short)v;
+	} else {
+		p += x * (s->bpp / 8);
+		p[0] = (unsigned char)b;
+		p[1] = (unsigned char)g;
+		p[2] = (unsigned char)r;
+		if (s->bpp == 32)
+			p[3] = 0xFF;
+	}
+}
+
+void usurf_fill(struct usurf *s, int x, int y, unsigned int w,
+		unsigned int h, unsigned int rgb)
+{
+	unsigned int r = (rgb >> 16) & 0xFF;
+	unsigned int g = (rgb >> 8) & 0xFF;
+	unsigned int b = rgb & 0xFF;
+	unsigned int i, j;
+
+	if (x < 0) {
+		w -= (unsigned int)(-x);
+		x = 0;
+	}
+	if (y < 0) {
+		h -= (unsigned int)(-y);
+		y = 0;
+	}
+	if ((unsigned int)x >= s->w || (unsigned int)y >= s->h)
+		return;
+	if ((unsigned int)x + w > s->w)
+		w = s->w - (unsigned int)x;
+	if ((unsigned int)y + h > s->h)
+		h = s->h - (unsigned int)y;
+
+	if (s->bpp == 16) {
+		unsigned short v = (unsigned short)(((r >> 3) << 11) |
+					((g >> 2) << 5) | (b >> 3));
+		for (j = 0; j < h; j++) {
+			unsigned short *p = (unsigned short *)(s->px +
+				(unsigned long)((unsigned int)y + j) * s->pitch) +
+				(unsigned int)x;
+			for (i = 0; i < w; i++)
+				p[i] = v;
+		}
+	} else {
+		unsigned int pb = s->bpp / 8;
+		for (j = 0; j < h; j++) {
+			unsigned char *p = s->px +
+				(unsigned long)((unsigned int)y + j) * s->pitch +
+				(unsigned int)x * pb;
+			for (i = 0; i < w; i++) {
+				p[0] = (unsigned char)b;
+				p[1] = (unsigned char)g;
+				p[2] = (unsigned char)r;
+				if (pb == 4)
+					p[3] = 0xFF;
+				p += pb;
+			}
+		}
+	}
+}
+
+void usurf_copy(struct usurf *s, int dx, int dy, int sx, int sy,
+		unsigned int w, unsigned int h)
+{
+	unsigned int pb = s->bpp / 8;
+	int backwards;
+
+	if (w == 0 || h == 0 || dx < 0 || dy < 0 || sx < 0 || sy < 0)
+		return;
+	if ((unsigned int)dx + w > s->w || (unsigned int)sx + w > s->w ||
+	    (unsigned int)dy + h > s->h || (unsigned int)sy + h > s->h)
+		return;
+
+	backwards = (dy > sy) || (dy == sy && dx > sx);
+	{
+		unsigned int i;
+		for (i = 0; i < h; i++) {
+			unsigned int syy = backwards ? (unsigned int)(sy + (int)h - 1 - (int)i)
+						     : (unsigned int)sy + i;
+			unsigned int dyy = backwards ? (unsigned int)(dy + (int)h - 1 - (int)i)
+						     : (unsigned int)dy + i;
+			unsigned char *src = s->px + (unsigned long)syy * s->pitch +
+					     (unsigned int)sx * pb;
+			unsigned char *dst = s->px + (unsigned long)dyy * s->pitch +
+					     (unsigned int)dx * pb;
+			unsigned int n = w * pb;
+
+			if (backwards) {
+				while (n--)
+					dst[n] = src[n];
+			} else {
+				unsigned int k;
+				for (k = 0; k < n; k++)
+					dst[k] = src[k];
+			}
+		}
+	}
+}
+
+void usurf_glyph(struct usurf *s, int x, int y, unsigned char c,
+		 unsigned int fg, unsigned int bg, int transparent,
+		 unsigned int height,
+		 int cx, int cy, unsigned int cw, unsigned int ch)
+{
+	const unsigned char *glyph = &font_8x8[(unsigned int)c * FONT_8X8_ROWS];
+	unsigned int fr = (fg >> 16) & 0xFF, fgn = (fg >> 8) & 0xFF, fb = fg & 0xFF;
+	unsigned int br = (bg >> 16) & 0xFF, bgn = (bg >> 8) & 0xFF, bb = bg & 0xFF;
+	unsigned int py, px;
+
+	for (py = 0; py < height; py++) {
+		unsigned char bits = (py < FONT_H) ? glyph[py] : 0;
+		int yy = y + (int)py;
+
+		if (yy < cy || yy >= cy + (int)ch)
+			continue;
+		for (px = 0; px < 8; px++) {
+			int xx = x + (int)px;
+			int on = (bits & (0x80u >> px)) != 0;
+
+			if (xx < cx || xx >= cx + (int)cw)
+				continue;
+			if (on)
+				put_px(s, (unsigned int)xx, (unsigned int)yy,
+				       fr, fgn, fb);
+			else if (!transparent)
+				put_px(s, (unsigned int)xx, (unsigned int)yy,
+				       br, bgn, bb);
+		}
+	}
+}
+
+void usurf_text(struct usurf *s, int x, int y, const char *str,
+		unsigned int fg,
+		int cx, int cy, unsigned int cw, unsigned int ch)
+{
+	unsigned int i = 0;
+
+	while (str[i]) {
+		usurf_glyph(s, x + (int)i * 8, y, (unsigned char)str[i],
+			    fg, 0, 1, FONT_H, cx, cy, cw, ch);
+		i++;
+	}
+}
+
+void usurf_cells(struct usurf *s, const unsigned short *cells,
+		 unsigned int cols, unsigned int rows,
+		 int x0, int y0,
+		 int cx, int cy, unsigned int cw, unsigned int ch)
+{
+	int col0 = (cx - x0) / 8;
+	int col1 = (cx + (int)cw - x0 + 7) / 8;
+	int row0 = (cy - y0) / 10;
+	int row1 = (cy + (int)ch - y0 + 9) / 10;
+	int row, col;
+
+	if (col0 < 0) col0 = 0;
+	if (row0 < 0) row0 = 0;
+	if (col1 > (int)cols) col1 = (int)cols;
+	if (row1 > (int)rows) row1 = (int)rows;
+	if (col1 <= col0 || row1 <= row0)
+		return;
+
+	for (row = row0; row < row1; row++) {
+		for (col = col0; col < col1; col++) {
+			unsigned short cell = cells[(unsigned int)row * cols +
+						    (unsigned int)col];
+			unsigned char c = (unsigned char)(cell & 0xFF);
+			unsigned char attr = (unsigned char)(cell >> 8);
+			unsigned int fg = ((unsigned int)pal_r[attr & 15] << 16) |
+				((unsigned int)pal_g[attr & 15] << 8) |
+				pal_b[attr & 15];
+			unsigned int bg = ((unsigned int)pal_r[(attr >> 4) & 15] << 16) |
+				((unsigned int)pal_g[(attr >> 4) & 15] << 8) |
+				pal_b[(attr >> 4) & 15];
+
+			usurf_glyph(s, x0 + col * 8, y0 + row * 10, c,
+				    fg, bg, 0, 10, cx, cy, cw, ch);
+		}
+	}
+}
+
+void usurf_canvas(struct usurf *s, const struct uwm_canvas *c,
+		  int x0, int y0,
+		  int cx, int cy, unsigned int cw, unsigned int ch)
+{
+	int x, y;
+	int sx0 = 0, sy0 = 0;
+	int sx1 = (int)c->w, sy1 = (int)c->h;
+
+	if (cx > x0)
+		sx0 = cx - x0;
+	if (cy > y0)
+		sy0 = cy - y0;
+	if (cx + (int)cw < x0 + sx1)
+		sx1 = cx + (int)cw - x0;
+	if (cy + (int)ch < y0 + sy1)
+		sy1 = cy + (int)ch - y0;
+	if (sx1 <= sx0 || sy1 <= sy0)
+		return;
+
+	for (y = sy0; y < sy1; y++) {
+		for (x = sx0; x < sx1; x++) {
+			unsigned int p = c->px[(unsigned int)y * c->w +
+					       (unsigned int)x];
+			unsigned int r5 = (p >> 11) & 0x1F;
+			unsigned int g6 = (p >> 5) & 0x3F;
+			unsigned int b5 = p & 0x1F;
+			unsigned int r = (r5 << 3) | (r5 >> 2);
+			unsigned int g = (g6 << 2) | (g6 >> 4);
+			unsigned int b = (b5 << 3) | (b5 >> 2);
+
+			put_px(s, (unsigned int)(x0 + x),
+			       (unsigned int)(y0 + y), r, g, b);
+		}
+	}
+}

+ 39 - 0
uwm_lib.h

@@ -0,0 +1,39 @@
+/* Small userland drawing library for the ring-3 WM: bpp-aware fills, copies,
+ * 8x8 glyphs, VGA cell grids and RGB565 canvas blits.  No kernel dependencies;
+ * the WM maps the shadow buffer and calls these functions directly. */
+#ifndef UWM_LIB_H
+#define UWM_LIB_H
+
+struct usurf {
+	unsigned char *px;
+	unsigned int w, h, pitch;
+	unsigned int bpp;          /* 16, 24 or 32 */
+};
+
+struct uwm_canvas {
+	const unsigned short *px;  /* RGB565, tightly packed */
+	unsigned int w, h;
+};
+
+void usurf_init(struct usurf *s, void *px, unsigned int w, unsigned int h,
+		unsigned int pitch, unsigned int bpp);
+void usurf_fill(struct usurf *s, int x, int y, unsigned int w,
+		unsigned int h, unsigned int rgb);
+void usurf_copy(struct usurf *s, int dx, int dy, int sx, int sy,
+		unsigned int w, unsigned int h);
+void usurf_glyph(struct usurf *s, int x, int y, unsigned char c,
+		 unsigned int fg, unsigned int bg, int transparent,
+		 unsigned int height,
+		 int cx, int cy, unsigned int cw, unsigned int ch);
+void usurf_text(struct usurf *s, int x, int y, const char *str,
+		unsigned int fg,
+		int cx, int cy, unsigned int cw, unsigned int ch);
+void usurf_cells(struct usurf *s, const unsigned short *cells,
+		 unsigned int cols, unsigned int rows,
+		 int x0, int y0,
+		 int cx, int cy, unsigned int cw, unsigned int ch);
+void usurf_canvas(struct usurf *s, const struct uwm_canvas *c,
+		  int x0, int y0,
+		  int cx, int cy, unsigned int cw, unsigned int ch);
+
+#endif

+ 47 - 18
vga.c

@@ -38,8 +38,28 @@ struct damage_rect {
 static struct damage_rect damage_rects[DAMAGE_SLOTS];
 static unsigned int damage_count;
 
-static void damage_add(unsigned int x0, unsigned int y0,
-		       unsigned int x1, unsigned int y1)
+/* Set while a process is inside shadow_copy_damage(): the flush walks and
+ * trims the shared damage list, so it must not be entered twice and the
+ * scheduler must not switch away from it halfway.  Marks made while a flush
+ * is active are deferred to one full-screen rect. */
+static int present_busy;
+static int damage_deferred;
+
+static inline unsigned int irq_save_disable(void)
+{
+	unsigned int flags;
+
+	__asm__ volatile ("pushfl; popl %0; cli" : "=r"(flags));
+	return flags;
+}
+
+static inline void irq_restore(unsigned int flags)
+{
+	__asm__ volatile ("pushl %0; popfl" :: "r"(flags));
+}
+
+static void damage_add_locked(unsigned int x0, unsigned int y0,
+			      unsigned int x1, unsigned int y1)
 {
 	unsigned int i;
 
@@ -124,6 +144,22 @@ static void damage_add(unsigned int x0, unsigned int y0,
 	}
 }
 
+static void damage_add(unsigned int x0, unsigned int y0,
+		       unsigned int x1, unsigned int y1)
+{
+	unsigned int flags = irq_save_disable();
+
+	if (present_busy) {
+		/* The flush owns the list right now.  Re-mark the whole screen
+		 * once it finishes so the new pixels are not lost. */
+		damage_deferred = 1;
+		irq_restore(flags);
+		return;
+	}
+	damage_add_locked(x0, y0, x1, y1);
+	irq_restore(flags);
+}
+
 static int damage_any(void)
 {
 	return damage_count != 0;
@@ -132,6 +168,7 @@ static int damage_any(void)
 static void damage_clear(void)
 {
 	damage_count = 0;
+	damage_deferred = 0;
 }
 
 static void mark_dirty_rect_xy(unsigned int y, unsigned int h,
@@ -607,26 +644,12 @@ static unsigned int shadow_copy_damage(unsigned int max_bytes)
 	return bytes;
 }
 
-/* Set while a process is inside shadow_copy_damage().  The flush walks and
- * trims a shared damage list, so it must not be entered twice: a process can
- * be preempted mid-flush (a full-screen copy takes several milliseconds) and
- * the scheduler may well run another process that flushes too. */
-static int present_busy;
-
 /* Bytes copied by the presenter so far (see vga.h). */
 unsigned int vga_present_copied;
 
-static inline unsigned int irq_save_disable(void)
+int vga_present_busy(void)
 {
-	unsigned int flags;
-
-	__asm__ volatile ("pushfl; popl %0; cli" : "=r"(flags));
-	return flags;
-}
-
-static inline void irq_restore(unsigned int flags)
-{
-	__asm__ volatile ("pushl %0; popfl" :: "r"(flags));
+	return present_busy;
 }
 
 /* Copy up to `max_bytes` of the pending damage to VRAM.  Called by the main
@@ -652,7 +675,13 @@ void vga_present_shadow(unsigned int max_bytes)
 	present_busy = 1;
 	irq_restore(flags);
 	vga_present_copied += shadow_copy_damage(max_bytes);
+	flags = irq_save_disable();
 	present_busy = 0;
+	if (damage_deferred) {
+		damage_deferred = 0;
+		damage_add_locked(0, 0, vga_fb_w, vga_fb_h);
+	}
+	irq_restore(flags);
 }
 
 /* Make drawn content visible: the backend's present() (the software one copies

+ 4 - 0
vga.h

@@ -100,6 +100,10 @@ void vga_fb_flush(void);
  * within one loop, large ones are chunked so they cannot stall input. */
 void vga_fb_flush_budget(unsigned int max_bytes);
 
+/* 1 while the presenter is copying damage to VRAM.  The scheduler must not
+ * switch away from that context: the flush trims a shared damage list. */
+int vga_present_busy(void);
+
 /* Low-level row helpers from vga_copy.S (the blit backend uses the fill). */
 void vga_fb_copy_row(void *dst, const void *src, unsigned int dwords);
 void vga_fb_copy_row_nt(void *dst, const void *src, unsigned int dwords);

Plik diff jest za duży
+ 890 - 15
wm.c


+ 49 - 12
wm.h

@@ -3,19 +3,10 @@
 #define WM_H
 
 #include "terminal.h"
+#include "gfx.h"
+#include "wm_abi.h"
 
-#define MAX_WINDOWS 4
-
-/* System bar (banner + "+ New" button + clock + rainbow) at the top. */
-#define WM_BAR_H 25
-#define WM_BTN_X 132
-#define WM_BTN_Y 3
-#define WM_BTN_W 56
-#define WM_BTN_H 14
-
-/* Window chrome. */
-#define WM_TITLE_H 16
-#define WM_CLOSE_W 14
+#define MAX_WINDOWS WM_MAX_WINDOWS
 
 struct window {
 	int used;
@@ -25,10 +16,56 @@ struct window {
 	int focused;
 	unsigned int pid;        /* owning terminal process pid (0 = none) */
 	struct term *term;
+	/* Generic canvas window (gfx commands): no terminal, own front/back. */
+	int canvas_window;
+	struct gfx_canvas canvas;
+	unsigned short *back;
+	unsigned int back_pages;
+	unsigned int owner_cr3;
+	int keys[16];
+	unsigned int key_head, key_tail;
+	/* Ring-3 WM content mapping/bookkeeping. */
+	unsigned int content_gen; /* bumped when the content kind/session changes */
+	unsigned int mapped_kind;
+	unsigned int mapped_gen;
+	unsigned int mapped_pages;
+	const void *mapped_src;
 };
 
 void wm_run(void);
+/* Idle-loop services: these stay in the kernel even while the WM process is
+ * stopped, so keyboard routing, cursor blink and kexec recovery keep working. */
+void wm_pump_keyboard(void);
+void wm_blink_cursor(void);
+void wm_handle_kexec(void);
 int  wm_spawn_terminal(void);
+
+/* Kernel window server / ring-3 WM ABI (see wm_abi.h). */
+void wm_server_init(void);
+void wm_server_start(void);
+void wm_server_supervise(void);
+int  wm_server_is_wm(void);
+int  wm_server_frame_active(void);
+int  wm_server_can_reap(void);
+int  wm_server_attach(struct wm_screen_info *out);
+int  wm_server_info(unsigned int index, struct wm_window_info *out);
+int  wm_server_map(unsigned int index, struct wm_map_info *out);
+int  wm_server_ack(unsigned int index, unsigned int seq);
+int  wm_server_focus(unsigned int index);
+int  wm_server_set_geom(unsigned int index, int x, int y);
+int  wm_server_create_term(void);
+int  wm_server_close(unsigned int index);
+int  wm_server_poll(struct wm_status *out);
+int  wm_server_begin(void);
+int  wm_server_present(const struct wm_present_info *in);
+int  wm_server_sync(void);
+int  wm_server_win_create(const struct win_create *in, struct win_info *out);
+int  wm_server_win_present(void);
+int  wm_server_win_close(void);
+int  wm_server_key_poll(void);
+void wm_content_changed(struct text_screen *screen);
+void wm_server_unmap_screen(struct text_screen *screen);
+void wm_server_unmap_canvas(struct text_screen *screen, const void *canvas);
 struct window *wm_focused_window(void);
 int  wm_is_focused(const struct window *w);
 void wm_request_redraw(void);

+ 106 - 0
wm_abi.h

@@ -0,0 +1,106 @@
+/* Shared window-manager ABI: kernel <-> ring-3 WM.
+ * Only plain types and syscall numbers live here; the kernel window state and
+ * all font/pixel decisions stay elsewhere. */
+#ifndef WM_ABI_H
+#define WM_ABI_H
+
+#define WM_MAX_WINDOWS 4
+
+/* Shared chrome layout (the WM draws it, the kernel only stores geometry). */
+#define WM_BAR_H   25
+#define WM_BTN_X   132
+#define WM_BTN_Y   3
+#define WM_BTN_W   56
+#define WM_BTN_H   14
+#define WM_TITLE_H 16
+#define WM_CLOSE_W 14
+
+/* Fixed user virtual addresses for the WM's mappings.  The shadow is one
+ * mapping; each window gets a private content slot (large enough for the
+ * current canvas and future bigger ones). */
+#define WM_SHADOW_VA        0x58000000u
+#define WM_CONTENT_VA_BASE  0x59000000u
+#define WM_CONTENT_SLOT     0x00200000u   /* 2 MB per window */
+
+/* Window content kind. */
+#define WM_KIND_NONE 0
+#define WM_KIND_TEXT 1
+#define WM_KIND_GFX  2
+
+struct wm_screen_info {
+	unsigned int width;
+	unsigned int height;
+	unsigned int pitch;
+	unsigned int bpp;
+	unsigned int bytes;
+	void *fb;
+};
+
+struct wm_mouse_info {
+	unsigned int x;
+	unsigned int y;
+	unsigned int buttons;      /* bit0 left, bit1 right, bit2 middle */
+};
+
+struct wm_status {
+	struct wm_mouse_info mouse;
+	unsigned int full_redraw;
+	unsigned int kexec_busy;
+	unsigned int kexec_progress;
+	unsigned int kexec_total;
+};
+
+struct wm_window_info {
+	unsigned int used;
+	unsigned int kind;         /* WM_KIND_* */
+	unsigned int focused;
+	unsigned int pid;
+	int x, y;
+	unsigned int w, h;         /* outer window rectangle */
+	unsigned int content_w, content_h;
+	unsigned int cols, rows;   /* text cells (0 for gfx) */
+	unsigned int cursor;
+	unsigned int cursor_visible;
+	unsigned int dirty;
+	unsigned int dirty_seq;
+	unsigned int dmg_col0, dmg_row0, dmg_cols, dmg_rows;
+	unsigned int content_gen;
+	char title[16];
+};
+
+struct wm_map_info {
+	void *va;
+	unsigned int kind;
+	unsigned int w, h;
+	unsigned int stride;       /* bytes per row for gfx, cells*2 for text */
+	unsigned int generation;
+};
+
+struct wm_rect {
+	int x, y;
+	unsigned int w, h;
+};
+
+struct wm_present_info {
+	unsigned int count;        /* 0..4 */
+	unsigned int immediate;    /* 1: flush now (drag); 0: budgeted */
+	struct wm_rect rect[4];
+};
+
+struct wm_geom {
+	int x, y;
+};
+
+/* Generic canvas-window client API (gfx commands own their own window). */
+struct win_create {
+	unsigned int w, h;
+	char title[16];
+};
+
+struct win_info {
+	void *fb;                  /* mapped RGB565 back buffer */
+	unsigned int width, height;
+	unsigned int id;
+};
+
+#endif

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików