Răsfoiți Sursa

acpi: real S5 poweroff on BIOS and UEFI

The kernel only poked the Bochs/QEMU shutdown ports, so poweroff froze
the BSP with the BKL held on real hardware.  Parse the FADT PM1 blocks
and the DSDT \_S5 package, enable ACPI through SMI_CMD when SCI_EN is
clear, and write SLP_TYP first and SLP_EN in a second write while
preserving SCI_EN.

Intel-style southbridges get SMI_EN.SLP_SMI_EN cleared first, since
that bit turns the SLP_EN write into an SMI.  NVIDIA nForce/MCP boards
(the ION) run S5 through the firmware SMM: replicate the DSDT's
_PTS(5) by writing ASSB/AOTB/AAXB/OSTP in the BIOS NVS and arming
PS1S/PS1E in the SMI block before SLP_EN.

A failed poweroff now returns instead of halting; the WM shows a
notice and the netlog carries the FADT/S5/SCI_EN state.  A new
acpidump command writes the mapped DSDT to /share/DSDT.BIN for board
diagnostics.  acpi.o and poweroff.o build with -Oz to stay under the
0x90000 kernel wall.
Johannes Zellner 2 zile în urmă
părinte
comite
75e0dc9ead
9 a modificat fișierele cu 517 adăugiri și 36 ștergeri
  1. 24 4
      AGENTS.md
  2. 4 0
      Makefile
  3. 27 1
      docs/cpu.html
  4. 1 1
      docs/index.html
  5. 395 9
      kernel/acpi.c
  6. 7 0
      kernel/acpi.h
  7. 25 9
      kernel/poweroff.c
  8. 17 11
      kernel/terminal.c
  9. 17 1
      user/apps/wm/ucmd_wm.c

+ 24 - 4
AGENTS.md

@@ -355,7 +355,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   and the shadow flush) or the BKL is held; voluntary blocks/yields go through
   the `int 0x81` gate.
 - **SMP / ACPI**: `acpi.c/h` (RSDP → RSDT/XSDT → MADT; CPU/LAPIC and IOAPIC
-  base lists; 4 MB table page mapping; malformed tables are ignored),
+  base lists; 4 MB table page mapping; the FADT PM1 control blocks, flags and
+  the DSDT (or SSDT) `\_S5` sleep types; malformed tables are ignored),
   `ioapic.c/h` (masks the normal IOAPIC redirection entries after ACPI init so
   the 8259/LINT0 path is deterministic; ExtINT entries are preserved),
   `lapic.c/h`
@@ -375,6 +376,21 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   into `struct process.fpu` and FRSTORs the incoming one (FNINIT for a
   process that never ran); the kernel uses no x87, and its SSE helpers
   touch only XMM registers, which ring 3 (`-mno-sse`) never uses.
+  `acpi_poweroff()` enables ACPI through the FADT SMI command (or the
+  conventional `0xB2`/`0xF1` pair) when `SCI_EN` is clear, then sets
+  `SLP_TYP` and `SLP_EN` in PM1a/PM1b with a read-modify-write that keeps
+  `SCI_EN` set (the type first, `SLP_EN` in a second write).  The values
+  come from the FADT and the decoded `\_S5` package.  Intel-style
+  southbridges also clear `SMI_EN.SLP_SMI_EN` (bit 4 at PMBASE+0x30) so
+  the sleep write is not turned into an SMI.  NVIDIA nForce/MCP boards (the
+  ION) run S5 through the firmware SMM instead: the same path writes the
+  sleep state into the BIOS NVS (ASSB=5, AOTB/OSTP for Linux, AAXB=0) and
+  arms PS1S/PS1E in the SMI block, matching the DSDT's `_PTS(5)`.  So
+  `poweroff` performs a real ACPI S5 shutdown on BIOS and UEFI boots alike
+  (both hand the kernel the same ACPI tables); the Bochs/QEMU ports are
+  only the emulator fallback.  If no path works the command returns instead
+  of halting: the WM shows `poweroff failed` and the FADT/S5/`SCI_EN` state
+  is in the netlog.
 - **Memory**: `phys.h` — `MM_MAX_PHYS` (1 GB, the lowmem/identity-map
   ceiling, also used by the UEFI loader for the pack buffer), `MM_KMAP_VA`
   (`0x4FC00000`) and `MM_HIGH_LIMIT` (4 GB).  Lowmem ends where ring-3 space
@@ -2341,7 +2357,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
 ## Shell commands
 
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
-`mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`,
+`mkdir <path>`, `rmdir <path>`, `hello`, `acpidump` (writes the mapped
+DSDT to `/share/DSDT.BIN`), `reboot`, `poweroff`,
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `disks` (the ngui storage manager), `meminfo`, `top`, `process` (the ngui task manager), `bootscan` (the live boot storage-scan window), `sched`, `format [-y] <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk; `-y` skips the prompt), `install [-y] <target> [source|self]` (clone the live image, or write the running image; auto-detects the source, preferring `usb0`; `auto` targets the only non-USB NebOS disk),
 `ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `membench` (ring-3 speed check: TSC, ALU, heap/BSS memcpy, syscall rates), `backlight [0-100|up|down]` (also `probe`), `keytest` (raw scancode tap), `help`, `clear`, `serial test`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `browser [url|file]` (disk app launcher), and `chat [config-path]` (Cloudron Chat client).
 
@@ -3209,8 +3226,11 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     OVMF delivers the ISA IRQs through the 8259 path; the kernel nevertheless
     masks the IOAPIC's normal redirection entries after ACPI init, so
     firmware-left vectors cannot collide with the PIC or LAPIC timer.
-    UEFI runtime services are not used, so
-    `reboot`/`poweroff` still use the legacy ports.  The image is 17 MB: the
+    UEFI runtime services are not used: `reboot` still pulses the keyboard
+    controller and `poweroff` uses ACPI S5 (the FADT PM1a/PM1b control blocks
+    and the DSDT `\_S5` sleep type, enabling ACPI through the SMI command
+    when `SCI_EN` is clear) on both BIOS and UEFI boots, with the
+    Bochs/QEMU ports as an emulator fallback.  The image is 17 MB: the
     9 MB kernel + rootfs disk and the 8 MB ESP.  Maxwell GPUs such as the
     GTX 960 use the firmware VBE/GOP framebuffer only; there is no native
     NVIDIA driver, and `nv50_probe()` is gated to the ION/nv50 chipsets.

+ 4 - 0
Makefile

@@ -129,6 +129,10 @@ KERNEL_OS = terminal disk fat nvidia nv50 uhci ohci ehci xhci asix rndis \
 	peek ne2000 r8168 blkdev fatdetect fatformat format install usbmsc dbg vfs
 $(addprefix $(B)/kernel/,$(addsuffix .o,$(KERNEL_OS))): OPT = -Os
 $(B)/kernel/e1000e.o: OPT = -Oz
+# The ACPI table/S5 parser and the poweroff path are cold boot/shutdown code
+# and the kernel is close to the low-memory wall; squeeze them hard.
+$(B)/kernel/acpi.o: OPT = -Oz
+$(B)/kernel/poweroff.o: OPT = -Oz
 
 # The AP trampoline is linked at 0x6000 and embedded as a binary blob; ld
 # names its symbols after the input path, so run it inside the build dir

+ 27 - 1
docs/cpu.html

@@ -157,6 +157,31 @@
 			the intended century. Boards without ACPI get no century write and
 			keep the 1970–2069 read window.
 		</p>
+		<p>
+			It also caches the FADT power-management blocks and scans the DSDT
+			(or an SSDT) for <code>\_S5</code>. The <code>poweroff</code> command
+			read-modify-writes the sleep type into PM1a/PM1b, keeping the existing
+			<code>SCI_EN</code> bit set — writing only the sleep bits clears it,
+			and some real chipsets then ignore the request. It writes
+			<code>SLP_TYP</code> first and <code>SLP_EN</code> in a second write.
+			Intel-style southbridges clear <code>SMI_EN.SLP_SMI_EN</code> (bit 4
+			at <code>PMBASE+0x30</code>): while that bit is set the chipset turns
+			the <code>SLP_EN</code> write into an SMI instead of a power
+			transition. NVIDIA nForce/MCP boards (the ION) run S5 through the
+			firmware SMM instead: the kernel writes the sleep state into the
+			BIOS NVS (<code>ASSB=5</code>, Linux <code>AOTB</code>/<code>OSTP</code>,
+			<code>AAXB=0</code>) and arms <code>PS1S</code>/<code>PS1E</code> in
+			the SMI block, matching the DSDT's <code>_PTS(5)</code>, before the
+			<code>SLP_EN</code> write. If <code>SCI_EN</code> is clear it first
+			enables ACPI mode through the FADT SMI command (or the conventional
+			<code>0xB2</code>/<code>0xF1</code> pair). BIOS and UEFI boots share
+			this path because both hand the kernel the same ACPI tables; only the
+			RSDP discovery differs (EBDA scan versus the loader's boot info).
+			Emulators whose tables do not decode <code>\_S5</code> fall back to
+			the Bochs/QEMU shutdown ports. A failed poweroff returns to the
+			desktop instead of halting, and the boot/poweroff log carries the
+			PM1, <code>\_S5</code> and <code>SCI_EN</code> state.
+		</p>
 		<ol>
 			<li>Copy the AP trampoline to <code>0x6000</code> (SIPI vector <code>0x06</code>).</li>
 			<li>Allocate an AP idle PCB and kernel stack via <code>process_init_ap()</code>.</li>
@@ -379,7 +404,8 @@
 			<li><code>kernel/process.c</code>, <code>kernel/process.h</code> — PCBs and lifecycle</li>
 			<li><code>kernel/switch.S</code> — context switch</li>
 			<li><code>kernel/tss.c</code>, <code>kernel/tss.h</code> — per-CPU TSS</li>
-			<li><code>kernel/acpi.c</code>, <code>kernel/ioapic.c</code>, <code>kernel/lapic.c</code>, <code>kernel/smp.c</code> — SMP and IOAPIC masking</li>
+			<li><code>kernel/acpi.c</code>, <code>kernel/ioapic.c</code>, <code>kernel/lapic.c</code>, <code>kernel/smp.c</code> — SMP, IOAPIC masking and the FADT S5 shutdown data</li>
+			<li><code>kernel/poweroff.c</code> — ACPI S5 poweroff with the emulator port fallback</li>
 			<li><code>kernel/ap_tramp.S</code> — AP startup blob</li>
 			<li><code>kernel/timer.S</code>, <code>kernel/idle.c</code>, <code>kernel/power.c</code></li>
 			<li><code>kernel/thermal.c</code> — Intel DTS and AMD D18F3xA4 sampling</li>

+ 1 - 1
docs/index.html

@@ -159,7 +159,7 @@
 			<li><strong>Identity-mapped paging.</strong> Physical and virtual addresses are equal. There is no per-process address space or isolation.</li>
 			<li><strong>1 GB lowmem, 4 GB highmem.</strong> The identity map ends where ring-3 space starts (<code>0x40000000</code>); RAM up to 4 GB backs ring-3 pages through per-CPU <code>kmap</code> slots.</li>
 			<li><strong>Hardcoded low memory.</strong> Boot info, the E820 map, the framebuffer block and the AP trampoline have fixed addresses that every boot path must honour.</li>
-			<li><strong>No firmware runtime.</strong> <code>reboot</code> and <code>poweroff</code> use legacy ports; UEFI runtime services are not called after <code>ExitBootServices</code>.</li>
+			<li><strong>No firmware runtime.</strong> <code>reboot</code> resets through the keyboard controller and <code>poweroff</code> writes ACPI S5 from the FADT/DSDT; UEFI runtime services are not called after <code>ExitBootServices</code>.</li>
 		</ul>
 		<div class="warn">
 			<p><strong>Fresh memory is not zeroed.</strong> <code>mm_alloc_page</code> and <code>kmalloc</code> return whatever RAM contained. Every structure read before it is written must be cleared on allocation; QEMU hides this because its RAM starts clear.</p>

+ 395 - 9
kernel/acpi.c

@@ -9,7 +9,10 @@
 #include "acpi.h"
 #include "bootinfo.h"
 #include "paging.h"
+#include "pci.h"
 #include "serial.h"
+#include "sys_fs.h"
+#include "timer.h"
 
 struct acpi_rsdp {
 	char signature[8];
@@ -51,6 +54,29 @@ static int acpi_ok;
  * when the firmware points at a real CMOS register. */
 static unsigned int rtc_century_reg;
 
+/* FADT power-management state for ACPI S5 (soft off).  The PM1 control
+ * blocks are I/O ports on every x86 machine this kernel targets; the S5
+ * sleep type comes from the DSDT's \_S5 package.  Without it the only
+ * shutdown path is the emulator's Bochs/QEMU port. */
+static int fadt_ok;
+static unsigned int fadt_pm1a_cnt;
+static unsigned int fadt_pm1b_cnt;
+static unsigned int fadt_pm1a_evt;
+static unsigned int fadt_pm1_cnt_len;
+static unsigned int fadt_smi_cmd;
+static unsigned int fadt_acpi_enable;
+static unsigned int fadt_flags;
+static unsigned int dsdt_addr;
+static unsigned int ssdt_addr[4];
+static unsigned int nssdt;
+static unsigned int s5a;
+static unsigned int s5b;
+static int s5_ok;
+static const unsigned char *dsdt_ptr;
+static unsigned int dsdt_len;
+
+static void scan_s5_addr(unsigned int addr, int strict);
+
 /* Kernel address of a firmware table range (write-back RAM mapping). */
 static void *table_ptr(unsigned int addr, unsigned int len)
 {
@@ -136,7 +162,181 @@ static const struct acpi_rsdp *find_rsdp(void)
 	return 0;
 }
 
-static const struct acpi_sdt *find_madt(const struct acpi_rsdp *rsdp)
+/* True when a table signature is one of the four-character ACPI ids. */
+static int sig_is(const struct acpi_sdt *t, const char *sig)
+{
+	return t->signature[0] == sig[0] && t->signature[1] == sig[1] &&
+	       t->signature[2] == sig[2] && t->signature[3] == sig[3];
+}
+
+/* Decode and skip an AML PkgLength field (one to four bytes). */
+static int aml_pkg_length(const unsigned char *p, unsigned int len,
+			  unsigned int *used)
+{
+	unsigned int follow;
+
+	if (!len)
+		return -1;
+	follow = (p[0] >> 6) & 3;
+	if (len < follow + 1)
+		return -1;
+	*used = follow + 1;
+	return 0;
+}
+
+/* Decode one integer package element (0, 1, Byte, Word or DWord prefix). */
+static int s5_elem(const unsigned char *p, unsigned int len, unsigned int *v)
+{
+	if (!len)
+		return -1;
+	switch (p[0]) {
+	case 0x00:
+		*v = 0;
+		return 1;
+	case 0x01:
+		*v = 1;
+		return 1;
+	case 0x0A:
+		if (len < 2)
+			return -1;
+		*v = p[1];
+		return 2;
+	case 0x0B:
+		if (len < 3)
+			return -1;
+		*v = p[1] | ((unsigned int)p[2] << 8);
+		return 3;
+	case 0x0C:
+		if (len < 5)
+			return -1;
+		*v = p[1] | ((unsigned int)p[2] << 8) |
+		     ((unsigned int)p[3] << 16) | ((unsigned int)p[4] << 24);
+		return 5;
+	default:
+		return -1;
+	}
+}
+
+/* Find \_S5 in one DSDT/SSDT image and decode its PM1a/PM1b sleep types.
+ * The AML Name string is 08 5F 53 35 5F (optionally with a root prefix
+ * 5C); the package's first two integers are the PM1a/PM1b SLP_TYP values.
+ * Anything that does not decode cleanly is ignored: guessing a type could
+ * enter S3/S4 instead of powering the machine off. */
+static void scan_s5(const unsigned char *tbl, unsigned int len)
+{
+	unsigned int i;
+
+	if (s5_ok)
+		return;
+	for (i = 0; i + 5 < len; i++) {
+		const unsigned char *p;
+		unsigned int rem, used, nel, v1, v2;
+		int n;
+
+		if (tbl[i] != 0x08)
+			continue;
+		if (tbl[i + 1] == 0x5C && tbl[i + 2] == '_' &&
+		    tbl[i + 3] == 'S' && tbl[i + 4] == '5' &&
+		    tbl[i + 5] == '_')
+			p = tbl + i + 6;
+		else if (tbl[i + 1] == '_' && tbl[i + 2] == 'S' &&
+			 tbl[i + 3] == '5' && tbl[i + 4] == '_')
+			p = tbl + i + 5;
+		else
+			continue;
+		rem = len - (unsigned int)(p - tbl);
+		if (!rem || *p != 0x12)        /* PackageOp */
+			continue;
+		p++;
+		rem--;
+		if (aml_pkg_length(p, rem, &used) != 0)
+			continue;
+		p += used;
+		rem -= used;
+		if (!rem)
+			continue;
+		nel = *p++;
+		rem--;
+		if (nel < 1)
+			continue;
+		n = s5_elem(p, rem, &v1);
+		if (n < 0 || (v1 & ~7u))
+			continue;
+		p += n;
+		rem -= (unsigned int)n;
+		v2 = v1;
+		if (nel >= 2 && rem) {
+			n = s5_elem(p, rem, &v2);
+			if (n < 0 || (v2 & ~7u))
+				continue;
+		}
+		s5a = v1;
+		s5b = v2;
+		s5_ok = 1;
+		return;
+	}
+}
+
+/* Map one DSDT/SSDT by address, validate it and scan for \_S5.  The DSDT
+ * pointed to by the FADT is scanned even with a bad checksum (some firmware
+ * ships one and still expects the OS to use the table); SSDTs from the RSDT
+ * were already checksum-validated by the table walk. */
+static void scan_s5_addr(unsigned int addr, int strict)
+{
+	const struct acpi_sdt *t;
+	unsigned int len;
+
+	if (s5_ok || !addr || !range_ok(addr, sizeof(struct acpi_sdt)))
+		return;
+	t = table_ptr(addr, sizeof(struct acpi_sdt));
+	if (!t)
+		return;
+	if (!sig_is(t, "DSDT") && !sig_is(t, "SSDT"))
+		return;
+	len = t->length;
+	if (len < sizeof(struct acpi_sdt) || len > 0x100000u ||
+	    !range_ok(addr, len))
+		return;
+	t = table_ptr(addr, len);
+	if (!t)
+		return;
+	if (!sum_ok((const unsigned char *)t, len) && strict)
+		return;
+	if (addr == dsdt_addr) {
+		dsdt_ptr = (const unsigned char *)t;
+		dsdt_len = len;
+	}
+	scan_s5((const unsigned char *)t, len);
+}
+
+/* Cache the FADT fields the S5 shutdown needs. */
+static void parse_fadt(const unsigned char *t, unsigned int len)
+{
+	unsigned long long x;
+
+	if (len < 109 || fadt_ok)
+		return;
+	fadt_ok = 1;
+	fadt_pm1a_cnt = *(const unsigned int *)(t + 64);
+	fadt_pm1b_cnt = *(const unsigned int *)(t + 68);
+	fadt_pm1a_evt = *(const unsigned int *)(t + 56);
+	fadt_pm1_cnt_len = t[89];
+	fadt_smi_cmd = *(const unsigned int *)(t + 48);
+	fadt_acpi_enable = t[52];
+	if (len >= 116)
+		fadt_flags = *(const unsigned int *)(t + 112);
+	/* ACPI 2.0+ firmware may publish the DSDT only in X_DSDT. */
+	if (len >= 148) {
+		x = *(const unsigned long long *)(t + 140);
+		if (x && (unsigned int)(x >> 32) == 0)
+			dsdt_addr = (unsigned int)x;
+	}
+	if (!dsdt_addr)
+		dsdt_addr = *(const unsigned int *)(t + 40);
+}
+
+/* Walk the RSDT/XSDT once: pick the MADT, cache the FADT and scan for \_S5. */
+static const struct acpi_sdt *scan_tables(const struct acpi_rsdp *rsdp)
 {
 	unsigned int addr, len, i, step;
 	const struct acpi_sdt *sdt;
@@ -191,8 +391,7 @@ static const struct acpi_sdt *find_madt(const struct acpi_rsdp *rsdp)
 		t = table_ptr(taddr, tlen);
 		if (!t || !sum_ok((const unsigned char *)t, tlen))
 			continue;
-		if (t->signature[0] == 'F' && t->signature[1] == 'A' &&
-		    t->signature[2] == 'C' && t->signature[3] == 'P') {
+		if (sig_is(t, "FACP")) {
 			/* FADT "century" is at offset 108 (ACPI 2.0+); 0 means
 			 * the firmware does not provide a century register. */
 			if (tlen >= 109) {
@@ -202,13 +401,28 @@ static const struct acpi_sdt *find_madt(const struct acpi_rsdp *rsdp)
 				if (c >= 0x0E && c <= 0x7F)
 					rtc_century_reg = c;
 			}
+			parse_fadt((const unsigned char *)t, tlen);
+			continue;
+		}
+		if (sig_is(t, "DSDT")) {
+			if (!dsdt_addr)
+				dsdt_addr = taddr;
+			continue;
+		}
+		if (sig_is(t, "SSDT")) {
+			if (nssdt < 4)
+				ssdt_addr[nssdt++] = taddr;
 			continue;
 		}
-		if (t->signature[0] == 'A' && t->signature[1] == 'P' &&
-		    t->signature[2] == 'I' && t->signature[3] == 'C' &&
-		    !madt)
+		if (sig_is(t, "APIC") && !madt)
 			madt = t;
 	}
+
+	/* \_S5 normally lives in the DSDT; some firmware splits it into an
+	 * SSDT.  Scan after the walk so the FADT's DSDT pointer is known. */
+	scan_s5_addr(dsdt_addr, 0);
+	for (i = 0; i < nssdt && !s5_ok; i++)
+		scan_s5_addr(ssdt_addr[i], 1);
 	return madt;
 }
 
@@ -276,16 +490,35 @@ int acpi_init(void)
 	ncpu = 0;
 	nioapics = 0;
 	rtc_century_reg = 0;
+	fadt_ok = 0;
+	fadt_pm1a_cnt = 0;
+	fadt_pm1b_cnt = 0;
+	fadt_pm1a_evt = 0;
+	fadt_pm1_cnt_len = 0;
+	fadt_smi_cmd = 0;
+	fadt_acpi_enable = 0;
+	fadt_flags = 0;
+	dsdt_addr = 0;
+	nssdt = 0;
+	dsdt_ptr = 0;
+	dsdt_len = 0;
+	s5a = 0;
+	s5b = 0;
+	s5_ok = 0;
 	bsp_apic = cpuid_apic_id();
-	if (bsp_apic == 0xFFFFFFFFu)
-		return 0;
 
 	rsdp = find_rsdp();
 	if (!rsdp) {
 		serial_puts(SERIAL_COM1, "acpi: no RSDP, staying UP\n");
 		return 0;
 	}
-	madt = find_madt(rsdp);
+	/* Walk the tables even when the CPU has no APIC: the FADT also
+	 * carries the S5 shutdown registers. */
+	madt = scan_tables(rsdp);
+	if (bsp_apic == 0xFFFFFFFFu) {
+		serial_puts(SERIAL_COM1, "acpi: no CPUID APIC, staying UP\n");
+		return 0;
+	}
 	if (!madt) {
 		serial_puts(SERIAL_COM1, "acpi: no MADT, staying UP\n");
 		return 0;
@@ -346,10 +579,163 @@ unsigned int acpi_rtc_century_reg(void)
 	return rtc_century_reg;
 }
 
+/* Put the machine into ACPI S5 (soft off) through the FADT PM1 control
+ * blocks.  Returns 0 when the SLP_EN sequence was issued, -1 when the
+ * firmware does not provide a usable path.  The caller must halt either
+ * way: a machine that ignores the write will just keep running. */
+static unsigned int pm1_cnt_read(unsigned int port)
+{
+	if (fadt_pm1_cnt_len >= 4)
+		return port_inl((unsigned short)port);
+	return port_inw((unsigned short)port);
+}
+
+static void pm1_cnt_put(unsigned int port, unsigned int v)
+{
+	if (fadt_pm1_cnt_len >= 4)
+		port_outl((unsigned short)port, v);
+	else
+		port_outw((unsigned short)port, (unsigned short)v);
+}
+
+/* Set the sleep type and optionally SLP_EN.  SCI_EN and the other live bits
+ * are preserved: clearing SCI_EN can make a real chipset ignore the request.
+ * The type is written first and SLP_EN in a second write because some
+ * chipsets sample SLP_TYP only when SLP_EN is asserted. */
+static void pm1_cnt_set(unsigned int port, unsigned int type, int enable)
+{
+	unsigned int v = pm1_cnt_read(port);
+
+	v &= ~(7u << 10);
+	v |= type << 10;
+	if (enable)
+		v |= 1u << 13;
+	pm1_cnt_put(port, v);
+}
+
+/* The ION/nForce DSDT's _PTS(5): record the sleep state in the BIOS NVS
+ * (ASSB/AOTB/AAXB/OSTP at 0xCFF9E064, field offsets from the DSDT's BIOS
+ * OperationRegion) and arm PS1S/PS1E in the SMI block at 0x4400.  The SMM
+ * reads that state when SLP_EN is written; arming PS1E without it hangs. */
+static void nvidia_s5_prepare(unsigned int smi_base)
+{
+	unsigned char *nvs;
+	unsigned char b;
+
+	nvs = ioremap(0xCFF9E064u, 0x100, IOREMAP_RAM);
+	if (!nvs)
+		return;
+	nvs[0x31] = 5;                        /* ASSB: S5 */
+	nvs[0x32] = 3;                        /* AOTB: OSFL() for Linux */
+	*(unsigned int *)(nvs + 0x33) = 0;    /* AAXB */
+	nvs[0x4D] = 1;                        /* OSTP: OSYS() for Linux */
+	port_outb(0x80, 5);                   /* DBG8 */
+	if (smi_base <= 0xFFC0u) {
+		b = port_inb((unsigned short)(smi_base + 1));
+		port_outb((unsigned short)(smi_base + 1),
+			  (unsigned char)(b | 0x80));
+		b = port_inb((unsigned short)(smi_base + 5));
+		port_outb((unsigned short)(smi_base + 5),
+			  (unsigned char)(b | 0x80));
+	}
+}
+
+int acpi_poweroff(void)
+{
+	unsigned int t0, sci, smi, cmd;
+
+	if (!fadt_ok || !s5_ok)
+		return -1;
+	if (fadt_flags & (1u << 4))        /* HW_REDUCED_ACPI */
+		return -1;
+	if (!fadt_pm1a_cnt || fadt_pm1a_cnt > 0xFFFFu)
+		return -1;
+
+	/* Some firmware still has ACPI in legacy mode (SCI_EN clear), where
+	 * PM1_CNT writes are ignored.  Do the SMI handshake first; the FADT
+	 * SMI_CMD is authoritative, but a few boards leave it zero and still
+	 * use the conventional 0xB2/0xF1 pair. */
+	sci = pm1_cnt_read(fadt_pm1a_cnt) & 1;
+	if (!sci) {
+		smi = fadt_smi_cmd;
+		cmd = fadt_acpi_enable;
+		if (!smi || smi > 0xFFFFu)
+			smi = 0xB2;
+		if (!cmd)
+			cmd = 0xF1;
+		port_outb((unsigned short)smi, (unsigned char)cmd);
+		t0 = get_ticks_ms();
+		while (get_ticks_ms() - t0 < 3000) {
+			if (pm1_cnt_read(fadt_pm1a_cnt) & 1)
+				break;
+		}
+		sci = pm1_cnt_read(fadt_pm1a_cnt) & 1;
+	}
+
+	serial_puts(SERIAL_COM1, "poweroff: S5 ");
+	serial_putdec(SERIAL_COM1, s5a);
+	serial_puts(SERIAL_COM1, "/");
+	serial_putdec(SERIAL_COM1, s5b);
+	serial_puts(SERIAL_COM1, " pm1a ");
+	serial_puthex(SERIAL_COM1, fadt_pm1a_cnt);
+	if (fadt_pm1b_cnt) {
+		serial_puts(SERIAL_COM1, " pm1b ");
+		serial_puthex(SERIAL_COM1, fadt_pm1b_cnt);
+	}
+	serial_puts(SERIAL_COM1, " sci ");
+	serial_putdec(SERIAL_COM1, sci);
+	serial_puts(SERIAL_COM1, "\n");
+
+	/* Set SLP_TYP first, then assert SLP_EN in a separate write. */
+	pm1_cnt_set(fadt_pm1a_cnt, s5a, 0);
+	if (fadt_pm1b_cnt && fadt_pm1b_cnt <= 0xFFFFu)
+		pm1_cnt_set(fadt_pm1b_cnt, s5b, 0);
+	/* Intel-style southbridges route SLP_EN through an SMI while
+	 * SMI_EN.SLP_SMI_EN (bit 4 at PMBASE+0x30) is set, so clear it.
+	 * NVIDIA nForce/MCP parts go through their firmware SMM as the
+	 * DSDT's _PTS(5) describes: nvidia_s5_prepare() records the sleep
+	 * state in the BIOS NVS and arms PS1S/PS1E before SLP_EN. */
+	if (fadt_smi_cmd < 0x4000u) {
+		if (fadt_pm1a_evt && fadt_pm1a_evt <= 0xFFC0u) {
+			unsigned int se =
+				port_inl((unsigned short)(fadt_pm1a_evt + 0x30));
+
+			port_outl((unsigned short)(fadt_pm1a_evt + 0x30),
+				  se & ~(1u << 4));
+		}
+	} else {
+		nvidia_s5_prepare(fadt_smi_cmd - 0x2Eu);
+	}
+	pm1_cnt_set(fadt_pm1a_cnt, s5a, 1);
+	if (fadt_pm1b_cnt && fadt_pm1b_cnt <= 0xFFFFu)
+		pm1_cnt_set(fadt_pm1b_cnt, s5b, 1);
+	return 0;
+}
+
+int acpi_dump_dsdt(const char *path)
+{
+	if (!dsdt_ptr || !dsdt_len)
+		return -1;
+	return sys_write_file(path, dsdt_ptr, dsdt_len);
+}
+
 void acpi_dump(void)
 {
 	unsigned int i;
 
+	if (fadt_ok) {
+		serial_puts(SERIAL_COM1, "acpi: fadt pm1a ");
+		serial_puthex(SERIAL_COM1, fadt_pm1a_cnt);
+		serial_puts(SERIAL_COM1, " s5 ");
+		if (s5_ok) {
+			serial_putdec(SERIAL_COM1, s5a);
+			serial_puts(SERIAL_COM1, "/");
+			serial_putdec(SERIAL_COM1, s5b);
+		} else {
+			serial_puts(SERIAL_COM1, "?");
+		}
+		serial_puts(SERIAL_COM1, "\n");
+	}
 	if (!acpi_ok) {
 		serial_puts(SERIAL_COM1, "acpi: unavailable, 1 cpu\n");
 		return;

+ 7 - 0
kernel/acpi.h

@@ -24,6 +24,13 @@ unsigned int acpi_ioapic_base(unsigned int index);
  * firmware does not provide one (old non-ACPI hardware). */
 unsigned int acpi_rtc_century_reg(void);
 
+/* Put the machine into ACPI S5 (soft off).  Returns 0 when the S5 write was
+ * issued, -1 when the firmware provides no usable S5 path. */
+int acpi_poweroff(void);
+
+/* Write the DSDT (as mapped at boot) to a VFS path, for diagnostics. */
+int acpi_dump_dsdt(const char *path);
+
 void acpi_dump(void);
 
 #endif

+ 25 - 9
kernel/poweroff.c

@@ -1,15 +1,31 @@
-/* Poweroff command: shut down the virtual machine (QEMU/Bochs ACPI port). */
+/* Poweroff command: ACPI S5 on real hardware, Bochs/QEMU ports as fallback.
+ *
+ * The ACPI path parses the FADT and the DSDT \_S5 package (acpi.c) and
+ * sets SLP_TYP|SLP_EN in the PM1a/PM1b control blocks.  The Bochs/QEMU
+ * ports are kept for emulators without usable ACPI tables.  If no path
+ * works the command returns instead of halting, so the desktop survives a
+ * failed poweroff and the netlog/kworker can still report the reason. */
 
-static inline void outw(unsigned short port, unsigned short v)
+#include "acpi.h"
+#include "pci.h"
+#include "serial.h"
+#include "timer.h"
+
+static void wait_ms(unsigned int ms)
 {
-	__asm__ volatile ("outw %0, %%dx" : : "a"(v), "d"(port));
+	unsigned int t0 = get_ticks_ms();
+
+	while (get_ticks_ms() - t0 < ms)
+		__asm__ volatile ("hlt");
 }
 
-void program_poweroff_main(void)
+void program_poweroff_main(const char *arg)
 {
-	/* Bochs/QEMU "ACPI" shutdown — see https://wiki.osdev.org/Shutdown */
-	outw(0x604, 0x2000);
-	outw(0xB004, 0x2000);
-	for (;;)
-		__asm__ volatile ("hlt");
+	(void)arg;
+	if (acpi_poweroff() == 0)
+		wait_ms(1000);
+	port_outw(0x604, 0x2000);
+	port_outw(0xB004, 0x2000);
+	wait_ms(200);
+	serial_puts(SERIAL_COM1, "poweroff: failed\n");
 }

+ 17 - 11
kernel/terminal.c

@@ -2,6 +2,7 @@
    Commands are spawned as separate processes for preemptive multitasking. */
 
 #include "io.h"
+#include "acpi.h"
 #include "backlight.h"
 #include "power.h"
 #include "bootcon.h"
@@ -16,7 +17,7 @@
 #include "timer.h"
 
 extern void program_reboot_main(void);
-extern void program_poweroff_main(void);
+extern void program_poweroff_main(const char *arg);
 extern void program_display_main(void);
 extern void program_gfxbench_main(void);
 extern void program_serial_loop_main(const char *arg);
@@ -60,6 +61,7 @@ struct kcmd {
 /* The terminal's spawn/path helpers are defined later in this file. */
 
 static int cmd_bootlog(struct term *t, const char *args);
+static int cmd_acpidump(struct term *t, const char *args);
 static int cmd_dbg(struct term *t, const char *args);
 static int cmd_format(struct term *t, const char *args);
 static int cmd_install(struct term *t, const char *args);
@@ -71,7 +73,6 @@ static int cmd_kexec(struct term *t, const char *args);
 static int cmd_keytest(struct term *t, const char *args);
 static int cmd_kill(struct term *t, const char *args);
 static int cmd_backlight(struct term *t, const char *args);
-static int cmd_poweroff(struct term *t, const char *args);
 static int cmd_ps(struct term *t, const char *args);
 static int cmd_renice(struct term *t, const char *args);
 static int cmd_sched(struct term *t, const char *args);
@@ -83,8 +84,9 @@ static int cmd_serial(struct term *t, const char *args);
 static const struct kcmd cmds[] = {
 	{ "help",       "help",                          CK_CUSTOM, CMD_BUILTIN, 0, 0, 0, cmd_help },
 	{ "bootlog",    "bootlog",                       CK_CUSTOM, CMD_BUILTIN, 0, 0, 0, cmd_bootlog },
+	{ "acpidump",   "acpidump",                      CK_CUSTOM, 0, 0, 0, 0, cmd_acpidump },
 	{ "reboot",     "reboot",                        CK_CUSTOM, 0, 0, 0, 0, cmd_reboot },
-	{ "poweroff",   "poweroff",                      CK_CUSTOM, 0, 0, 0, 0, cmd_poweroff },
+	{ "poweroff",   "poweroff",                      CK_SPAWN_ARG, 0, 0, program_poweroff_main, 0, 0 },
 	{ "display",    "display",                       CK_SPAWN, 0, program_display_main, 0, 0, 0 },
 	{ "gfxbench",   "gfxbench",                      CK_SPAWN, 0, program_gfxbench_main, 0, 0, 0 },
 	{ "backlight",  "backlight [0-100|up|down]",     CK_CUSTOM, 0, 0, 0, 0, cmd_backlight },
@@ -156,6 +158,18 @@ static void help_print(void)
 
 
 
+/* Save the mapped DSDT to /share for offline analysis (acpidump). */
+static int cmd_acpidump(struct term *t, const char *args)
+{
+	(void)t;
+	(void)args;
+	if (acpi_dump_dsdt("/share/DSDT.BIN") == 0)
+		io_putstr("acpi: saved /share/DSDT.BIN\n");
+	else
+		io_putstr("acpi: dump failed\n");
+	return 0;
+}
+
 /* Dump the whole boot console text captured by bootcon_puts().  The ring-3
  * terminal keeps scrollback, so no paging is needed; sleep briefly every
  * 512 bytes so the terminal can drain its tty ring while we write. */
@@ -319,14 +333,6 @@ static int cmd_kill(struct term *t, const char *args)
 	return 0;
 }
 
-static int cmd_poweroff(struct term *t, const char *args)
-{
-	(void)t;
-	(void)args;
-	program_poweroff_main();
-	return 0;
-}
-
 static int cmd_ps(struct term *t, const char *args)
 {
 	(void)t;

+ 17 - 1
user/apps/wm/ucmd_wm.c

@@ -216,6 +216,8 @@ static int sm_power_open;
 static int sm_start_hot;
 static int sm_hot;              /* hovered app index, -1 = none */
 static int sm_power_hot;        /* 0 none, 1 Power, 2 Reboot, 3 Power off */
+static int poweroff_pid;        /* the kcmd spawned by Power off */
+static unsigned int poweroff_deadline;
 
 static void sm_layout_get(struct sm_layout *l);
 static void sm_draw(void);
@@ -2454,9 +2456,16 @@ static void handle_mouse(struct wm_status *st)
 				if (u_spawn_kcmd("reboot", "", 0) < 0)
 					bar_notice("reboot failed");
 			} else if (hit == SM_HIT_POWEROFF) {
+				int pid;
+
 				sm_close();
-				if (u_spawn_kcmd("poweroff", "", 0) < 0)
+				pid = u_spawn_kcmd("poweroff", "", 0);
+				if (pid < 0) {
 					bar_notice("poweroff failed");
+				} else {
+					poweroff_pid = pid;
+					poweroff_deadline = u_ticks_ms() + 6000;
+				}
 			} else if (hit >= 0) {
 				sm_launch(hit);
 			} else if (hit != SM_HIT_MENU) {
@@ -2702,6 +2711,13 @@ void _start(const char *arg)
 
 		if (u_wm_poll(&st) != 0)
 			u_exit(1);
+		/* A poweroff that could not cut the power returns instead of
+		 * halting; tell the user rather than leaving a dead menu. */
+		if (poweroff_pid > 0 &&
+		    (int)(u_ticks_ms() - poweroff_deadline) >= 0) {
+			bar_notice("poweroff failed");
+			poweroff_pid = 0;
+		}
 		if (st.wallpaper_seq != wall_seq_seen) {
 			wall_seq_seen = st.wallpaper_seq;
 			wall_load();