فهرست منبع

Add ThinkPad battery status and powerinfo

Johannes Zellner 1 هفته پیش
والد
کامیت
6e92b7659e
16فایلهای تغییر یافته به همراه677 افزوده شده و 48 حذف شده
  1. 30 20
      AGENTS.md
  2. 1 1
      Makefile
  3. 1 1
      docs/cpu.html
  4. 1 1
      docs/development.html
  5. 7 4
      docs/drivers.html
  6. 5 4
      docs/graphics.html
  7. 3 2
      docs/userland.html
  8. 45 0
      sys_info.c
  9. 1 0
      sys_info.h
  10. 6 0
      syscall.c
  11. 39 0
      syscall.h
  12. 248 8
      tpec.c
  13. 39 1
      tpec.h
  14. 5 0
      ucmd_lib.h
  15. 159 0
      ucmd_powerinfo.c
  16. 87 6
      ucmd_wm.c

+ 30 - 20
AGENTS.md

@@ -535,22 +535,30 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   Bonnell = 90, otherwise 100).  The 330's 125 °C is Linux coretemp's
   empirical value; Intel only specifies TJ = 90 °C and Tcase-max = 85.2 °C,
   so `sensors` prints the raw delta and the 90/100/125 °C scales as well as
-  the top bar's `CPU 43C` before the clock and `cpuinfo`'s value plus EIST
-  state.  Platforms without DTS (QEMU, Pentium) hide it.
+  the top bar's `CPU 43C` before the clock (with `BAT 87%` to its left on
+  ThinkPads) and `cpuinfo`'s value plus EIST state.  Platforms without DTS
+  (QEMU, Pentium) hide it.
 - **Board sensors**: `it87.c/h` — read-only probe of the IT87xx Super I/O
   (the AT3IONT-I exposes three temperatures and three fan tachometers), used
   by `SYS_SENSORS` and the ring-3 `sensors` command to cross-check the DTS
   and show whether the fans turn.  Nothing is written to the fan control.
   `tpec.c/h` adds the ThinkPad embedded controller of the X201
-  (`SYS_TPEC_SENSORS`): a `_SM_` SMBIOS type 1 check gates the probe to
-  Lenovo/IBM machines, then EC reads through ports 0x62/0x66 return the
-  temperatures at EC 0x78..0x7F / 0xC0..0xC7 (0x80 = absent, 0x00 =
-  unimplemented; revision 3+ at EC 0xEF only uses the first block), the fan
-  tachometer at 0x84 (LSB, always read first) / 0x85 and the 0x2F fan mode.
-  A pending EC output byte (a hotkey event, since there is no SCI handler) is
-  drained before every command, and every wait is bounded; nothing is
-  written to the EC.  `sensors` labels the EC registers and decodes the fan
-  mode (auto / full speed / level).
+  (`SYS_TPEC_SENSORS` for temperatures/fan, `SYS_POWER_INFO` for AC/battery):
+  a `_SM_` SMBIOS type 1 check gates the probe to Lenovo/IBM machines, then
+  EC reads through ports 0x62/0x66 return the temperatures at EC 0x78..0x7F /
+  0xC0..0xC7 (0x80 = absent, 0x00 = unimplemented; revision 3+ at EC 0xEF
+  only uses the first block), the fan tachometer at 0x84 (LSB, always read
+  first) / 0x85 and the 0x2F fan mode.  The power path reads 0x38/0x39
+  (bit 7 present, bit 6 discharging, bit 5 charging) and 0x46 bit 4 (AC
+  online), then selects the 0x81 battery information page (high nibble
+  battery, low nibble page: 0 dynamic, 1 mode, 2 design, 5 manufacturer,
+  6 model) and reads the 16-byte window at 0xA0..0xAF.  A pending EC output
+  byte (a hotkey event, since there is no SCI handler) is drained before
+  every command, and every wait is bounded; the only EC write is the 0x81
+  page selector, restored when it changed.  `sensors` labels the EC
+  registers and decodes the fan mode (auto / full speed / level); the ring-3
+  `powerinfo` command prints AC/battery details and the WM top bar shows the
+  first present battery with a valid percentage.
 - **Ring-3 address space**: the ELF image and 8 KB stack live in the 2 MB
   `USER_BASE` (`0x40000000`)..`USER_STACK_TOP` (`0x40200000`) window, which is
   too small for a full-frame image.  `SYS_MEM_ALLOC`/`SYS_MEM_GROW`/`SYS_MEM_FREE`
@@ -714,7 +722,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`,
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `sched`, `format <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk),
-`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `cpufreq [auto|min|max|off|<ratio>]`, `spin [ms]`, `help`, `clear`, `serial test`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), and `browser [url|file]` (disk app launcher).
+`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<ratio>]`, `spin [ms]`, `help`, `clear`, `serial test`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), and `browser [url|file]` (disk app launcher).
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
 DHCP client), `netdev [name]` (kernel command: show the active NIC driver or
@@ -745,7 +753,7 @@ nested). `/` is the read-only VFS root listing the mounted filesystems (the
 filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 
 `cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`, `spin`,
-`clock`, `colors`, `files`, `gallery`, `view`, `sensors`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
+`clock`, `colors`, `files`, `gallery`, `view`, `sensors`, `powerinfo`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
 `netreset`, `websrv`, `curl`, `solitaire` and `hello` are files in `/ramfs/bin`
 (packed by the Makefile), found through the shell's PATH; the rest are kernel
@@ -1157,9 +1165,9 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    legacy path; a larger pack needs the UEFI/kexec path or a chunked
    high-memory loader.  The browser and its ring-3 dependencies are compiled
    with function sections and linked with `--gc-sections`; the current pack
-   is ~245 KB, leaving ~16 KB under the cap.  Command growth still needs
-   care because `libdeflate-gzip -12` is already required (plain `gzip -9`
-   is over the cap).
+   is ~241 KiB (246711 bytes), leaving ~14 KB under the cap.  Command growth
+   still needs care because `libdeflate-gzip -12` is already required (plain
+   `gzip -9` is over the cap).
 9. SMP is **ACPI/MADT only**: no Intel MP-table fallback, so a Pentium II SMP
     board that exposes only MP tables stays UP (deliberate; there is no test
     hardware).
@@ -1273,10 +1281,12 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     `reboot`/`poweroff` still use the legacy ports.  The image is 17 MB: the
     9 MB kernel + rootfs disk and the 8 MB ESP.
 
-24. ThinkPad EC sensor access (`tpec.c`) runs in legacy/SMM mode because
-    there is no ACPI interpreter: an SMI that touches the EC between our port
-    accesses can produce an occasional bad sample, and EC hotkey events are
-    drained/discarded instead of handled.  The PCH thermal sensor
+24. ThinkPad EC sensor and battery access (`tpec.c`) runs in legacy/SMM mode
+    because there is no ACPI interpreter: an SMI that touches the EC between
+    our port accesses can produce an occasional bad sample (the battery
+    reader validates its values and the next 1 Hz poll corrects the bar), and
+    the 0x81 page-selector write can race the firmware's own battery poll.
+    EC hotkey events are drained/discarded instead of handled.  The PCH thermal sensor
     (`8086:3B32`, the `intel_ips` MMIO block) is not read because it needs
     the ME/BIOS to have enabled thermal reporting; the EC and DTS readings
     cover the package temperature.

+ 1 - 1
Makefile

@@ -527,7 +527,7 @@ UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir \
         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_net100 ucmd_netmac ucmd_curl \
-        ucmd_files ucmd_view ucmd_sensors ucmd_mines ucmd_solitaire \
+        ucmd_files ucmd_view ucmd_sensors ucmd_powerinfo ucmd_mines ucmd_solitaire \
         ucmd_gallery ucmd_websrv ucmd_browser
 
 # Keep the linked ELFs around (make would treat them as disposable

+ 1 - 1
docs/cpu.html

@@ -339,7 +339,7 @@
 		<ul>
 			<li><strong>P-states.</strong> On the allowlisted Nehalem/Westmere models, <code>power_init</code> enables SpeedStep, raises the package C-state limit to C6 when unlocked, reads min/max ratios and starts at the maximum non-turbo ratio.</li>
 			<li><strong>Governor.</strong> A 100 ms window picks min/max/linear target ratios; short busy streaks jump to max immediately. Each CPU writes its own <code>IA32_PERF_CTL</code>.</li>
-			<li><strong>Telemetry.</strong> <code>power</code> prints effective MHz from APERF/MPERF, ratios and C3/C6 residency; <code>sensors</code> prints DTS, board sensors and ThinkPad EC data.</li>
+			<li><strong>Telemetry.</strong> <code>power</code> prints effective MHz from APERF/MPERF, ratios and C3/C6 residency; <code>sensors</code> prints DTS, board sensors and ThinkPad EC temperatures/fan; <code>powerinfo</code> prints the AC adapter and battery state, and the WM top bar shows the battery percentage.</li>
 			<li><strong>Thermal.</strong> Each CPU samples its DTS once a second from its scheduler tick; the hottest core is exposed to ring 3.</li>
 		</ul>
 	</section>

+ 1 - 1
docs/development.html

@@ -264,7 +264,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>Network console.</strong> <code>make netmon</code> listens to UDP 19290 for serial and terminal output; <code>netconsole host &lt;ip&gt;</code> narrows the target.</li>
 			<li><strong>dbg.</strong> The ring-0 serial monitor accepts <code>r addr len</code>, <code>w addr b0 …</code>, <code>i port</code>, <code>o port val</code>, <code>h</code> and <code>q</code>.</li>
 			<li><strong>Panic.</strong> A ring-0 fault dumps vector, error code, registers, CRs, EIP bytes and stack candidates to the LFB and COM1. Resolve addresses with <code>nm kernel.elf</code> / <code>addr2line -e kernel.elf</code>.</li>
-			<li><strong>Profiling.</strong> <code>gfxbench</code> times fill/copy/cell/canvas/flush; <code>top</code>, <code>sched</code>, <code>sensors</code>, <code>power</code> and <code>lspci</code>/<code>lsusb</code> expose live state.</li>
+			<li><strong>Profiling.</strong> <code>gfxbench</code> times fill/copy/cell/canvas/flush; <code>top</code>, <code>sched</code>, <code>sensors</code>, <code>powerinfo</code>, <code>power</code> and <code>lspci</code>/<code>lsusb</code> expose live state.</li>
 			<li><strong>Memory.</strong> <code>peek addr len</code> hex-dumps identity-mapped memory (MMIO too); <code>poke addr val</code> writes one dword and prints the read-back.</li>
 		</ul>
 	</section>

+ 7 - 4
docs/drivers.html

@@ -85,7 +85,7 @@
 					<tr><td>PS/2</td><td><span class="file">mouse.c</span>, <span class="file">io.c</span></td><td>i8042</td><td>IRQ 1 keyboard, IRQ 12 mouse; polling fallback</td></tr>
 					<tr><td>Serial</td><td><span class="file">serial.c</span></td><td>16550 UART, COM1</td><td>IRQ 4 ring buffer + polled transmitter</td></tr>
 					<tr><td>Thermal</td><td><span class="file">thermal.c</span></td><td>Intel DTS MSR</td><td>Sampled once a second from the scheduler tick</td></tr>
-					<tr><td>Board sensors</td><td><span class="file">it87.c</span>, <span class="file">tpec.c</span></td><td>Super I/O, ThinkPad EC</td><td>Polled read-only</td></tr>
+					<tr><td>Board sensors</td><td><span class="file">it87.c</span>, <span class="file">tpec.c</span></td><td>Super I/O, ThinkPad EC (temps, fan, battery, AC)</td><td>Polled; only the EC page selector is written, then restored</td></tr>
 				</tbody>
 			</table>
 		</div>
@@ -316,13 +316,16 @@
 		<ul>
 			<li><strong>DTS.</strong> <span class="file">thermal.c</span> reads <code>IA32_THERM_STATUS</code> on an allowlist of Core/Core 2, Nehalem/Westmere and Bonnell models. TjMax comes from <code>IA32_TEMPERATURE_TARGET</code> on Nehalem and later; Bonnell uses a table.</li>
 			<li><strong>IT87xx.</strong> <span class="file">it87.c</span> reads the Super I/O temperatures and fan tachometers on the ASUS AT3IONT-I. Nothing is written to fan control.</li>
-			<li><strong>ThinkPad EC.</strong> <span class="file">tpec.c</span> is gated on an SMBIOS Lenovo/IBM match and reads temperatures and fan mode through ports <code>0x62/0x66</code>. It drains pending output bytes and uses bounded waits; nothing is written.</li>
+			<li><strong>ThinkPad EC.</strong> <span class="file">tpec.c</span> is gated on an SMBIOS Lenovo/IBM match and reads temperatures and fan mode through ports <code>0x62/0x66</code>. It drains pending output bytes and uses bounded waits. Battery/AC state comes from <code>0x38/0x39</code> (present, charging, discharging), <code>0x46</code> bit 4 (AC online), and the page-selected 16-byte window at <code>0xA0..0xAF</code>; <code>0x81</code> selects the battery and page (0 dynamic, 1 mode, 2 design, 5 manufacturer, 6 model). That page selector is the only EC write, and it is restored when it changed.</li>
 			<li><strong>MTRRs.</strong> <span class="file">mtrr.c</span> manages write-combining ranges for the framebuffer and reports the effective mapping.</li>
 		</ul>
 		<p>
 			<code>sensors</code> prints DTS values on the 90/100/125 °C scales,
-			board sensors and EC registers; <code>power</code> prints ratios,
-			effective MHz and C-state residency.
+			board sensors and EC registers; <code>powerinfo</code> prints the
+			AC adapter and battery state from <code>SYS_POWER_INFO</code>;
+			<code>power</code> prints ratios, effective MHz and C-state
+			residency. The WM top bar shows the first present battery
+			with a valid percentage next to the CPU temperature.
 		</p>
 	</section>
 

+ 5 - 4
docs/graphics.html

@@ -138,10 +138,11 @@
 		<h2>Window manager</h2>
 		<p>
 			The WM is a process that owns the desktop and a fixed array of eight
-			windows. It draws a system bar with the banner, launcher buttons and
-			clock, plus draggable terminal and canvas windows with a title bar and
-			close button. Click-to-focus, drag-by-title-bar and close are routed
-			through the same pointer path.
+			windows. It draws a system bar with the banner, launcher buttons,
+			clock and the CPU temperature/battery percentage, plus draggable
+			terminal and canvas windows with a title bar and close button.
+			Click-to-focus, drag-by-title-bar and close are routed through the
+			same pointer path.
 		</p>
 		<p>
 			The WM is the ring-3 process loaded from

+ 3 - 2
docs/userland.html

@@ -156,7 +156,7 @@
 				<tbody>
 					<tr><td>Console &amp; time</td><td>1–4, 56, 69</td><td>putstr, ticks, sleep, exit, RTC time/date</td></tr>
 					<tr><td>Files</td><td>5–11, 48, 98</td><td>whole-file read/write, list, unlink, mkdir/rmdir, mounts, cwd, stat</td></tr>
-					<tr><td>System info</td><td>12–16, 49–51, 91–92, 102</td><td>memory, E820, mouse, storage, blkdev, procinfo, cursor, CPU temp, sensors, EC</td></tr>
+					<tr><td>System info</td><td>12–16, 49–51, 91–92, 102–103</td><td>memory, E820, mouse, storage, blkdev, procinfo, cursor, CPU temp, sensors, EC sensors, AC/battery</td></tr>
 					<tr><td>Network</td><td>17–47</td><td>NIC config/acquire, raw frames, DHCP/DNS, TCP client, ARP, cwd</td></tr>
 					<tr><td>Window &amp; WM</td><td>55, 57–72, 80, 83–87</td><td>key poll, WM attach/info/map/present/create_term, window create/present/input/resize</td></tr>
 					<tr><td>Process &amp; memory</td><td>73–79, 81, 88–90</td><td>TTY, spawn, alive, kill, chdir, scheduler info, heap alloc/grow/free</td></tr>
@@ -231,7 +231,7 @@
 			</div>
 			<div class="card">
 				<h3>System</h3>
-				<p><code>cpuinfo</code> <code>meminfo</code> <code>storage</code> <code>top</code> <code>mouseinfo</code> <code>sensors</code> <code>spin</code> <code>clock</code> <code>colors</code></p>
+				<p><code>cpuinfo</code> <code>meminfo</code> <code>storage</code> <code>top</code> <code>mouseinfo</code> <code>sensors</code> <code>powerinfo</code> <code>spin</code> <code>clock</code> <code>colors</code></p>
 			</div>
 			<div class="card">
 				<h3>Network</h3>
@@ -295,6 +295,7 @@
 		<h2>Source map</h2>
 		<ul class="filelist">
 			<li><code>syscall.c</code>, <code>syscall_stub.S</code>, <code>syscall.h</code></li>
+			<li><code>sys_info.c</code> — kernel-state snapshots (memory, sensors, power)</li>
 			<li><code>process.c</code> — ELF load and spawn</li>
 			<li><code>elf.c</code> — ELF parser</li>
 			<li><code>ucmd_term.c</code> — windowed shell, scrollback, PATH</li>

+ 45 - 0
sys_info.c

@@ -18,6 +18,8 @@
 
 _Static_assert(TPEC_TEMP_COUNT == SYS_TPEC_TEMP_MAX,
 	       "sys_tpec_sensors.temp_c and tpec_info.temp_c must match");
+_Static_assert(TPEC_BATTERY_COUNT == SYS_POWER_BATT_MAX,
+	       "sys_powerinfo.battery and tpec_power.battery must match");
 
 static void copy_str(char *dst, const char *src, unsigned int size)
 {
@@ -170,3 +172,46 @@ int sys_tpec_sensors(struct sys_tpec_sensors *out)
 	out->fan_level = info.fan_level;
 	return 0;
 }
+
+int sys_powerinfo(struct sys_powerinfo *out, unsigned int flags)
+{
+	struct tpec_power p;
+	unsigned int i;
+
+	if (!out)
+		return -1;
+	tpec_power_read(&p, (flags & SYS_POWER_F_DETAIL) != 0);
+
+	for (i = 0; i < sizeof(*out); i++)
+		((unsigned char *)out)[i] = 0;
+	out->present = p.present ? 1u : 0u;
+	out->ac_online = p.ac_online;
+	out->ec_rev = p.ec_rev;
+	copy_str(out->vendor, p.vendor, sizeof(out->vendor));
+	copy_str(out->product, p.product, sizeof(out->product));
+	copy_str(out->version, p.version, sizeof(out->version));
+	out->battery_count = p.battery_count;
+	for (i = 0; i < SYS_POWER_BATT_MAX; i++) {
+		struct sys_battery *d = &out->battery[i];
+		const struct tpec_battery *s = &p.battery[i];
+
+		d->present = s->present ? 1u : 0u;
+		d->error = s->error ? 1u : 0u;
+		d->status = s->status;
+		d->charging = s->charging ? 1u : 0u;
+		d->discharging = s->discharging ? 1u : 0u;
+		d->percent = s->percent > 0 ? (unsigned int)s->percent : 0u;
+		d->percent_valid = s->percent_valid ? 1u : 0u;
+		d->remaining = s->remaining;
+		d->full = s->full;
+		d->design = s->design;
+		d->voltage_mv = s->voltage_mv;
+		d->rate = s->rate;
+		d->unit_known = s->unit_known ? 1u : 0u;
+		d->unit_mwh = s->unit_mwh ? 1u : 0u;
+		copy_str(d->manufacturer, s->manufacturer,
+			 sizeof(d->manufacturer));
+		copy_str(d->model, s->model, sizeof(d->model));
+	}
+	return 0;
+}

+ 1 - 0
sys_info.h

@@ -12,5 +12,6 @@ int sys_blkdev(unsigned int index, struct sys_blkdev *out);
 int sys_cputemp(struct sys_cputemp *out);
 int sys_sensors(struct sys_sensors *out);
 int sys_tpec_sensors(struct sys_tpec_sensors *out);
+int sys_powerinfo(struct sys_powerinfo *out, unsigned int flags);
 
 #endif

+ 6 - 0
syscall.c

@@ -273,6 +273,12 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 					  sizeof(struct sys_tpec_sensors), 1))
 			return -1;
 		return sys_tpec_sensors((struct sys_tpec_sensors *)a1);
+	case SYS_POWER_INFO:
+		if (!paging_user_range_ok(current_proc()->cr3, (unsigned int)a1,
+					  sizeof(struct sys_powerinfo), 1))
+			return -1;
+		return sys_powerinfo((struct sys_powerinfo *)a1,
+				     (unsigned int)a2);
 	case SYS_WIN_KEY_WAIT:
 		return sys_win_key_wait((unsigned int)a1);
 	case SYS_SCHEDINFO:

+ 39 - 0
syscall.h

@@ -129,6 +129,11 @@
 /* ThinkPad embedded-controller sensors (see tpec.c); read-only. */
 #define SYS_TPEC_SENSORS  102  /* (struct sys_tpec_sensors *out) -> 0/-1 */
 
+/* ThinkPad AC/battery snapshot (see tpec.c).  SYS_POWER_F_DETAIL also reads
+ * design capacity, the capacity unit and the manufacturer/model strings. */
+#define SYS_POWER_INFO     103  /* (struct sys_powerinfo *out, flags) -> 0/-1 */
+#define SYS_POWER_F_DETAIL 0x1
+
 /* Stat one path (the file service has no open handle). */
 #define SYS_FS_STAT        98  /* (path, struct sys_stat *out) -> 0/<0 */
 
@@ -271,6 +276,40 @@ struct sys_tpec_sensors {
 	unsigned int fan_level;
 };
 
+/* ThinkPad AC/battery snapshot.  rate is the signed present rate in the same
+ * unit as the capacities; unit_mwh (when unit_known) selects mWh/mW vs
+ * mAh/mA.  percent is valid only when percent_valid is set. */
+#define SYS_POWER_BATT_MAX 2
+struct sys_battery {
+	unsigned int present;
+	unsigned int error;
+	unsigned int status;      /* raw EC 0x38/0x39 byte */
+	unsigned int charging;
+	unsigned int discharging;
+	unsigned int percent;
+	unsigned int percent_valid;
+	unsigned int remaining;
+	unsigned int full;
+	unsigned int design;
+	unsigned int voltage_mv;
+	int rate;
+	unsigned int unit_known;
+	unsigned int unit_mwh;
+	char manufacturer[16];
+	char model[16];
+};
+
+struct sys_powerinfo {
+	unsigned int present;     /* ThinkPad EC found */
+	int ac_online;            /* -1 unknown, 0 offline, 1 online */
+	unsigned int ec_rev;
+	char vendor[16];
+	char product[32];
+	char version[32];
+	unsigned int battery_count;
+	struct sys_battery battery[SYS_POWER_BATT_MAX];
+};
+
 /* Wall clock for the ring-3 clock (see rtc.c). */
 struct sys_time {
 	unsigned int hour;     /* 0-23 */

+ 248 - 8
tpec.c

@@ -1,10 +1,10 @@
-/* Read-only ThinkPad embedded-controller sensors (see tpec.h).
+/* ThinkPad embedded-controller sensors and power sources (see tpec.h).
  *
  * The X201 (i5 M 520, Arrandale) has no IT87xx Super I/O like the
- * AT3IONT-I.  Its board temperatures and the fan tachometer live behind the
- * ACPI embedded controller, which Linux's thinkpad_acpi reads through the
- * same ports: command/status 0x66, data 0x62.  The EC protocol is simple
- * enough to drive directly:
+ * AT3IONT-I.  Its board temperatures, fan tachometer, battery and AC state
+ * live behind the ACPI embedded controller, which Linux's thinkpad_acpi
+ * reads through the same ports: command/status 0x66, data 0x62.  The EC
+ * protocol is simple enough to drive directly:
  *
  *   write 0x80 (read) to 0x66, then the register index to 0x62,
  *   wait for OBF (0x01) and read the byte back from 0x62.
@@ -18,14 +18,21 @@
  *    never replace it with the register we asked for.
  *  - Firmware keeps running in legacy/SMM mode (we have no ACPI interpreter),
  *    so an SMI can access the EC between our port accesses.  The status
- *    handshake plus bounded polling keeps that to an occasional bad sample;
- *    nothing is written, so the EC state cannot be corrupted.
+ *    handshake plus bounded polling keeps that to an occasional bad sample.
+ *    Temperature/fan reads are read-only; the battery reader writes only the
+ *    H8 information-page selector at 0x81 and restores it afterwards.
  *
- * EC register map (thinkpad_acpi): 0x78..0x7F and 0xC0..0xC7 temperatures
+ * EC register map (thinkpad_acpi/H8): 0x78..0x7F and 0xC0..0xC7 temperatures
  * (0x80 = sensor not present, 0x00 = register not implemented), 0x84/0x85
  * fan tachometer LSB/MSB and 0x2F fan control (bit 7 automatic, bit 6
  * disengaged/full speed, bits 2:0 level).  EC 0xEF is the functional
  * revision: revision 3 and later only implement the 0x78..0x7F sensors.
+ *
+ * Battery/AC: 0x38/0x39 are the battery 0/1 status bytes (bit 7 present,
+ * bit 6 discharging, bit 5 charging) and 0x46 bit 4 is the AC-adapter
+ * state.  Battery data is a 16-byte window at 0xA0..0xAF selected by 0x81:
+ * the high nibble is the battery (0x00/0x10), the low nibble the page
+ * (0 dynamic, 1 mode, 2 static design data, 5 manufacturer, 6 model).
  */
 #include "tpec.h"
 #include "paging.h"
@@ -38,6 +45,7 @@
 #define EC_OBF  0x01   /* output buffer full */
 #define EC_IBF  0x02   /* input buffer full */
 #define EC_READ 0x80
+#define EC_WRITE 0x81
 
 #define TP_FAN_LEVEL  0x2F
 #define TP_FAN_LSB    0x84
@@ -46,6 +54,24 @@
 #define TP_TEMP_HI    0xC0   /* temp_c[8..15] */
 #define TP_EC_REV     0xEF   /* EC functional revision */
 
+#define TP_BAT0_STATUS 0x38  /* bit 7 present, 6 discharging, 5 charging */
+#define TP_BAT1_STATUS 0x39
+#define TP_AC_STATUS   0x46  /* bit 4: AC adapter online */
+#define TP_BAT_PAGE    0x81  /* information-page selector */
+#define TP_BAT_DATA    0xA0  /* 16-byte selected page */
+
+#define TP_BAT_PAGE_DYNAMIC 0
+#define TP_BAT_PAGE_MODE    1
+#define TP_BAT_PAGE_STATIC  2
+#define TP_BAT_PAGE_MFR     5
+#define TP_BAT_PAGE_MODEL   6
+
+#define TP_BAT_REMAINING 0x00
+#define TP_BAT_FULL      0x02
+#define TP_BAT_RSOC      0x06
+#define TP_BAT_RATE      0x08
+#define TP_BAT_VOLTAGE   0x0A
+
 /* Enough for a slow EC command (tens of milliseconds of port polls) but
  * short enough that a dead controller cannot stall the boot or a syscall. */
 #define EC_POLL_MAX 20000
@@ -237,6 +263,68 @@ static int ec_read(unsigned char reg, unsigned char *out)
 	return 0;
 }
 
+/* ACPI EC "write EC RAM": command 0x81, then the register index and value. */
+static int ec_write(unsigned char reg, unsigned char val)
+{
+	if (ec_drain())
+		return -1;
+	if (ec_wait(EC_IBF, 0))
+		return -1;
+	port_outb(EC_STS, EC_WRITE);
+	if (ec_wait(EC_IBF, 0))
+		return -1;
+	port_outb(EC_DATA, reg);
+	if (ec_wait(EC_IBF, 0))
+		return -1;
+	port_outb(EC_DATA, val);
+	if (ec_wait(EC_IBF, 0))
+		return -1;
+	return 0;
+}
+
+static int ec_read16(unsigned char reg, unsigned int *out)
+{
+	unsigned char lo, hi;
+
+	if (ec_read(reg, &lo) != 0 || ec_read((unsigned char)(reg + 1), &hi) != 0)
+		return -1;
+	*out = (unsigned int)lo | ((unsigned int)hi << 8);
+	return 0;
+}
+
+/* Select an H8 battery information page.  Only writes 0x81 when the page
+ * already differs; *dirty remembers that the original page must be restored. */
+static int ec_battery_page(unsigned int battery, unsigned int page, int *dirty)
+{
+	unsigned char cur;
+	unsigned char want = (unsigned char)((battery << 4) | page);
+
+	if (ec_read(TP_BAT_PAGE, &cur) == 0 && cur == want)
+		return 0;
+	if (ec_write(TP_BAT_PAGE, want) != 0)
+		return -1;
+	*dirty = 1;
+	return 0;
+}
+
+static void ec_read_string(char *dst, unsigned int size, unsigned char reg)
+{
+	unsigned int i = 0;
+
+	while (i + 1 < size) {
+		unsigned char b;
+
+		if (ec_read((unsigned char)(reg + i), &b) != 0)
+			break;
+		if (b == 0x00 || b == 0xFF)
+			break;
+		dst[i++] = (char)b;
+	}
+	while (i && dst[i - 1] == ' ')
+		i--;
+	dst[i] = '\0';
+}
+
 static int str_eq(const char *a, const char *b)
 {
 	while (*a && *a == *b) {
@@ -366,3 +454,155 @@ void tpec_read(struct tpec_info *out)
 	if (ec_read(TP_FAN_LEVEL, &b) == 0)
 		out->fan_level = b;
 }
+
+static void tpec_copy_ident(char *dst, unsigned int size, const char *src)
+{
+	unsigned int i;
+
+	for (i = 0; i + 1 < size && src[i]; i++)
+		dst[i] = src[i];
+	dst[i] = '\0';
+}
+
+static void tpec_read_battery(struct tpec_battery *b, unsigned int index,
+			      int detail, int *page_dirty)
+{
+	unsigned char st;
+	unsigned int v;
+	unsigned int remaining = 0, full = 0, rsoc = 0xFFFF;
+	int have_remaining = 0, have_full = 0, have_rsoc = 0;
+	int have_voltage = 0;
+
+	if (ec_read((unsigned char)(TP_BAT0_STATUS + index), &st) != 0) {
+		b->error = 1;
+		return;
+	}
+	b->status = st;
+	b->present = (st & 0x80) ? 1 : 0;
+	b->charging = (st & 0x20) ? 1 : 0;
+	b->discharging = (st & 0x40) ? 1 : 0;
+	if (!b->present)
+		return;
+
+	if (ec_battery_page(index, TP_BAT_PAGE_DYNAMIC, page_dirty) != 0) {
+		b->error = 1;
+		return;
+	}
+	if (ec_read16((unsigned char)(TP_BAT_DATA + TP_BAT_REMAINING), &v) == 0) {
+		remaining = v;
+		have_remaining = (v != 0xFFFF);
+	}
+	if (ec_read16((unsigned char)(TP_BAT_DATA + TP_BAT_FULL), &v) == 0) {
+		full = v;
+		have_full = (v != 0xFFFF);
+	}
+	if (ec_read16((unsigned char)(TP_BAT_DATA + TP_BAT_RSOC), &v) == 0) {
+		rsoc = v;
+		have_rsoc = (v != 0xFFFF);
+	}
+	if (ec_read16((unsigned char)(TP_BAT_DATA + TP_BAT_RATE), &v) == 0) {
+		if (v != 0xFFFF)
+			b->rate = (int)(short)v;
+	} else {
+		b->error = 1;
+	}
+	if (ec_read16((unsigned char)(TP_BAT_DATA + TP_BAT_VOLTAGE), &v) == 0 &&
+	    v != 0xFFFF) {
+		b->voltage_mv = v;
+		have_voltage = 1;
+	} else {
+		b->error = 1;
+	}
+	b->remaining = have_remaining ? remaining : 0;
+	b->full = have_full ? full : 0;
+	if (!have_remaining || !have_full || !have_voltage)
+		b->error = 1;
+
+	/* Percentage is unit-independent (both capacities use the same unit).
+	 * Reject the 0xFFFF "unknown" marker and obviously inconsistent reads;
+	 * fall back to the SBS relative state of charge if that is sane. */
+	if (have_full && have_remaining && full > 0 && full != 0xFFFF &&
+	    remaining != 0xFFFF && remaining <= full + full / 4) {
+		b->percent = (int)((remaining * 100u + full / 2u) / full);
+		if (b->percent > 100)
+			b->percent = 100;
+		b->percent_valid = 1;
+	} else if (have_rsoc && rsoc <= 100) {
+		b->percent = (int)rsoc;
+		b->percent_valid = 1;
+	}
+
+	if (!detail)
+		return;
+	if (ec_battery_page(index, TP_BAT_PAGE_MODE, page_dirty) == 0) {
+		if (ec_read16(TP_BAT_DATA, &v) == 0 && v != 0xFFFF) {
+			b->unit_known = 1;
+			b->unit_mwh = (int)((v >> 15) & 1);
+		}
+	} else {
+		b->error = 1;
+	}
+	if (ec_battery_page(index, TP_BAT_PAGE_STATIC, page_dirty) == 0) {
+		if (ec_read16(TP_BAT_DATA, &v) == 0 && v != 0xFFFF)
+			b->design = v;
+	} else {
+		b->error = 1;
+	}
+
+	/* The vendor DSDT's GBIF/GBST report mWh/mW when the mode bit is set:
+	 * capacities are scaled by 10 (the 10.8 V pack) and the rate by the
+	 * measured voltage.  Match that so powerinfo shows the same units as
+	 * the firmware's ACPI battery interface.  The percentage above was
+	 * already computed from the raw values, so the scale does not matter. */
+	if (b->unit_mwh) {
+		b->remaining *= 10;
+		b->full *= 10;
+		b->design *= 10;
+		if (b->voltage_mv)
+			b->rate = (b->rate * (int)b->voltage_mv) / 1000;
+	}
+	if (ec_battery_page(index, TP_BAT_PAGE_MFR, page_dirty) == 0)
+		ec_read_string(b->manufacturer, sizeof(b->manufacturer),
+			       TP_BAT_DATA);
+	else
+		b->error = 1;
+	if (ec_battery_page(index, TP_BAT_PAGE_MODEL, page_dirty) == 0)
+		ec_read_string(b->model, sizeof(b->model), TP_BAT_DATA);
+	else
+		b->error = 1;
+}
+
+void tpec_power_read(struct tpec_power *out, int detail)
+{
+	unsigned int i;
+	unsigned char saved_page = 0, ac;
+	int have_saved = 0, page_dirty = 0;
+
+	for (i = 0; i < sizeof(*out); i++)
+		((unsigned char *)out)[i] = 0;
+	out->ac_online = -1;
+
+	if (tpec_state < 0)
+		tpec_init();
+	if (!tpec_state)
+		return;
+
+	out->present = 1;
+	out->ec_rev = tpec_ec_rev;
+	tpec_copy_ident(out->vendor, sizeof(out->vendor), tpec_vendor);
+	tpec_copy_ident(out->product, sizeof(out->product), tpec_product);
+	tpec_copy_ident(out->version, sizeof(out->version), tpec_version);
+
+	if (ec_read(TP_AC_STATUS, &ac) == 0)
+		out->ac_online = (ac & 0x10) ? 1 : 0;
+	if (ec_read(TP_BAT_PAGE, &saved_page) == 0)
+		have_saved = 1;
+
+	for (i = 0; i < TPEC_BATTERY_COUNT; i++) {
+		tpec_read_battery(&out->battery[i], i, detail, &page_dirty);
+		if (out->battery[i].present)
+			out->battery_count++;
+	}
+	if (page_dirty)
+		(void)ec_write(TP_BAT_PAGE, have_saved ? saved_page : 0);
+}

+ 39 - 1
tpec.h

@@ -1,8 +1,9 @@
-/* Read-only ThinkPad embedded-controller sensors (X201/Arrandale class). */
+/* ThinkPad embedded-controller sensors and power sources (X201/Arrandale class). */
 #ifndef TPEC_H
 #define TPEC_H
 
 #define TPEC_TEMP_COUNT 16
+#define TPEC_BATTERY_COUNT 2
 
 /* Temperatures are indexed like thinkpad_acpi's temp1..temp16:
  * temp_c[0..7] come from EC 0x78..0x7F, temp_c[8..15] from EC 0xC0..0xC7.
@@ -17,6 +18,37 @@ struct tpec_info {
 	unsigned int fan_level;   /* raw EC 0x2F value */
 };
 
+/* One battery from the H8 battery information area (EC page selector 0x81). */
+struct tpec_battery {
+	int present;
+	int error;                /* at least one EC read failed */
+	unsigned int status;      /* raw EC 0x38/0x39 status byte */
+	int charging;
+	int discharging;
+	int percent;              /* 0..100 when percent_valid */
+	int percent_valid;
+	unsigned int remaining;   /* reported remaining capacity */
+	unsigned int full;        /* reported last full charge capacity */
+	unsigned int design;      /* reported design capacity */
+	unsigned int voltage_mv;
+	int rate;                 /* signed reported present rate */
+	int unit_known;
+	int unit_mwh;             /* 1 = mWh/mW, 0 = mAh/mA */
+	char manufacturer[16];
+	char model[16];
+};
+
+struct tpec_power {
+	int present;              /* ThinkPad EC found */
+	int ac_online;            /* -1 unknown, 0 offline, 1 online */
+	unsigned int ec_rev;
+	char vendor[16];
+	char product[32];
+	char version[32];
+	unsigned int battery_count;
+	struct tpec_battery battery[TPEC_BATTERY_COUNT];
+};
+
 /* Probe SMBIOS + the EC once on the BSP; logs the result to COM1.  Does
  * nothing (present = 0) unless SMBIOS identifies a Lenovo/IBM machine and the
  * EC answers, so boards without one are never touched. */
@@ -26,4 +58,10 @@ void tpec_init(void);
  * no ThinkPad EC was found. */
 void tpec_read(struct tpec_info *out);
 
+/* Read the AC adapter and battery state through the H8 battery information
+ * pages; detail also reads design capacity, the capacity unit and the
+ * manufacturer/model strings.  The only EC write is the page selector at
+ * 0x81, and it is restored when it had to be changed. */
+void tpec_power_read(struct tpec_power *out, int detail);
+
 #endif

+ 5 - 0
ucmd_lib.h

@@ -390,6 +390,11 @@ static inline int u_tpec_sensors(struct sys_tpec_sensors *out)
 	return u_syscall1(SYS_TPEC_SENSORS, (int)out);
 }
 
+static inline int u_power_info(struct sys_powerinfo *out, unsigned int flags)
+{
+	return u_syscall2(SYS_POWER_INFO, (int)out, (int)flags);
+}
+
 /* Per-process anonymous heap: one growable arena, freed at exit. */
 static inline void *u_mem_alloc(unsigned int bytes)
 {

+ 159 - 0
ucmd_powerinfo.c

@@ -0,0 +1,159 @@
+/* powerinfo: AC adapter and battery state from the ThinkPad H8 EC.
+ *
+ * The EC access lives in the kernel (SYS_POWER_INFO); this command only
+ * formats the snapshot.  The same syscall feeds the WM's top-bar percentage.
+ */
+#include "ucmd_lib.h"
+
+static void put_milli(unsigned int v, const char *unit)
+{
+	u_putdec(v / 1000u);
+	u_putc('.');
+	u_putc((char)('0' + (v % 1000u) / 100u));
+	u_puts(unit);
+}
+
+static const char *cap_unit(const struct sys_battery *b)
+{
+	if (!b->unit_known)
+		return "EC units";
+	return b->unit_mwh ? "mWh" : "mAh";
+}
+
+static void show_battery(unsigned int index, const struct sys_battery *b)
+{
+	unsigned int health;
+
+	u_puts("battery ");
+	u_putdec(index);
+	u_puts(": ");
+	if (!b->present) {
+		if (b->error)
+			u_puts("read error\n");
+		else
+			u_puts("not present\n");
+		return;
+	}
+	u_puts("present, ");
+	if (b->charging)
+		u_puts("charging");
+	else if (b->discharging)
+		u_puts("discharging");
+	else if (b->percent_valid && b->percent >= 99)
+		u_puts("full");
+	else
+		u_puts("idle");
+	u_puts(" (status 0x");
+	u_put_hex2(b->status);
+	u_putc(')');
+	if (b->error)
+		u_puts(", read error");
+	u_putc('\n');
+
+	u_puts("  charge: ");
+	if (b->percent_valid) {
+		u_putdec(b->percent);
+		u_putc('%');
+	} else {
+		u_puts("unknown");
+	}
+	u_putc('\n');
+
+	if (b->full && b->percent_valid) {
+		u_puts("  capacity: ");
+		u_putdec(b->remaining);
+		u_puts(" / ");
+		u_putdec(b->full);
+		u_putc(' ');
+		u_puts(cap_unit(b));
+		u_putc('\n');
+		if (b->design) {
+			u_puts("  design: ");
+			u_putdec(b->design);
+			u_putc(' ');
+			u_puts(cap_unit(b));
+			health = (b->full * 100u + b->design / 2u) / b->design;
+			u_puts(", health ");
+			u_putdec(health);
+			u_putc('%');
+			u_putc('\n');
+		}
+	}
+	if (b->voltage_mv) {
+		u_puts("  voltage: ");
+		put_milli(b->voltage_mv, " V");
+		if (b->rate) {
+			unsigned int r = b->rate < 0 ?
+				(unsigned int)(-b->rate) : (unsigned int)b->rate;
+
+			u_puts(", rate: ");
+			if (b->unit_known)
+				put_milli(r, b->unit_mwh ? " W" : " A");
+			else {
+				u_putdec(r);
+				u_puts(" EC units");
+			}
+		}
+		u_putc('\n');
+	}
+	if (b->manufacturer[0] || b->model[0]) {
+		u_puts("  ");
+		if (b->model[0]) {
+			u_puts("model ");
+			u_puts(b->model);
+		}
+		if (b->manufacturer[0]) {
+			if (b->model[0])
+				u_puts(", ");
+			u_puts("manufacturer ");
+			u_puts(b->manufacturer);
+		}
+		u_putc('\n');
+	}
+}
+
+void _start(void)
+{
+	struct sys_powerinfo p;
+	unsigned int i;
+
+	if (u_power_info(&p, SYS_POWER_F_DETAIL) != 0) {
+		u_puts("powerinfo: unavailable\n");
+		u_exit(1);
+	}
+	if (!p.present) {
+		u_puts("no ThinkPad embedded controller detected\n");
+		u_puts("battery/AC status unavailable on this platform\n");
+		u_exit(0);
+	}
+
+	u_puts("thinkpad");
+	if (p.vendor[0]) {
+		u_putc(' ');
+		u_puts(p.vendor);
+	}
+	if (p.product[0]) {
+		u_putc(' ');
+		u_puts(p.product);
+	}
+	if (p.version[0]) {
+		u_putc(' ');
+		u_puts(p.version);
+	}
+	u_puts(", EC rev ");
+	u_putdec(p.ec_rev);
+	u_putc('\n');
+
+	u_puts("ac adapter: ");
+	if (p.ac_online < 0)
+		u_puts("unknown\n");
+	else if (p.ac_online)
+		u_puts("online\n");
+	else
+		u_puts("offline\n");
+
+	for (i = 0; i < SYS_POWER_BATT_MAX; i++)
+		show_battery(i, &p.battery[i]);
+
+	u_exit(0);
+}

+ 87 - 6
ucmd_wm.c

@@ -34,6 +34,9 @@ static int full_redraw = 1;
 static int boot_term_spawned;
 static unsigned int bar_kexec_busy, bar_kexec_progress, bar_kexec_total;
 static int bar_temp_c = -1;
+static int bar_batt_pct = -1;
+static int bar_batt_charging;
+static int bar_batt_ac;
 static char bar_msg[24];
 static unsigned int bar_msg_until;
 static int bar_msg_dirty;
@@ -140,6 +143,36 @@ static unsigned int temp_text(char *b, int c)
 	return n;
 }
 
+/* "BAT 87%" (no libc printf here). */
+static unsigned int batt_text(char *b, int pct)
+{
+	unsigned int n = 0, v = (unsigned int)pct;
+
+	b[n++] = 'B';
+	b[n++] = 'A';
+	b[n++] = 'T';
+	b[n++] = ' ';
+	if (v >= 100)
+		b[n++] = (char)('0' + (v / 100) % 10);
+	if (v >= 10)
+		b[n++] = (char)('0' + (v / 10) % 10);
+	b[n++] = (char)('0' + v % 10);
+	b[n++] = '%';
+	b[n] = '\0';
+	return n;
+}
+
+static unsigned int batt_color(int pct, int charging, int ac)
+{
+	if (pct <= 10)
+		return 0xFF5050u;
+	if (pct <= 20)
+		return 0xFFD250u;
+	if (charging || ac)
+		return 0x55FF55u;
+	return 0x55D2FFu;
+}
+
 static void draw_bar(void)
 {
 	char dt[48];
@@ -192,25 +225,42 @@ static void draw_bar(void)
 			   0xFFC864u, 0, 0, fbw, WM_BAR_H);
 	} else {
 		unsigned int clock_chars = 0;
+		int right = (int)fbw - 4;
+		int min_x = WM_BTN_GALLERY_X + (int)WM_BTN_GALLERY_W + 4;
 
 		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,
+			usurf_text(&screen, right - (int)n * 8, 5, dt,
 				   COL_BANNER, 0, 0, fbw, WM_BAR_H);
 			clock_chars = n;
 		}
+		if (clock_chars)
+			right -= (int)clock_chars * 8 + 8;
 		if (bar_temp_c >= 0) {
 			char tb[12];
 			unsigned int tn = temp_text(tb, bar_temp_c);
-			int tx = (int)fbw - 4 - (int)clock_chars * 8 -
-				 (clock_chars ? 8 : 0) - (int)tn * 8;
+			int tx = right - (int)tn * 8;
 
-			if (tx >= WM_BTN_GALLERY_X + (int)WM_BTN_GALLERY_W + 4)
+			if (tx >= min_x) {
 				usurf_text(&screen, tx, 5, tb,
 					   temp_color(bar_temp_c), 0, 0,
 					   fbw, WM_BAR_H);
+				right = tx - 8;
+			}
+		}
+		if (bar_batt_pct >= 0) {
+			char bb[10];
+			unsigned int bn = batt_text(bb, bar_batt_pct);
+			int bx = right - (int)bn * 8;
+
+			if (bx >= min_x)
+				usurf_text(&screen, bx, 5, bb,
+					   batt_color(bar_batt_pct,
+						      bar_batt_charging,
+						      bar_batt_ac),
+					   0, 0, fbw, WM_BAR_H);
 		}
 	}
 }
@@ -603,8 +653,8 @@ static void do_update(struct wm_status *st)
 			}
 		}
 	}
-	/* The RTC is slow (CMOS polling) and the temperature only changes
-	 * once a second; query both at 1 Hz instead of every 10 ms. */
+	/* The RTC is slow (CMOS polling) and the temperature/battery state only
+	 * changes once a second; query them at 1 Hz instead of every 10 ms. */
 	{
 		static unsigned int last_rtc_ms;
 		unsigned int now_ms = u_ticks_ms();
@@ -629,6 +679,37 @@ static void do_update(struct wm_status *st)
 					bar_dirty = 1;
 				}
 			}
+			{
+				struct sys_powerinfo pi;
+				int pct = -1, charging = 0, ac = 0;
+				unsigned int bi;
+
+				if (u_power_info(&pi, 0) == 0) {
+					ac = pi.ac_online > 0;
+					if (pi.present) {
+						for (bi = 0; bi < SYS_POWER_BATT_MAX;
+						     bi++) {
+							struct sys_battery *b =
+								&pi.battery[bi];
+
+							if (!b->present ||
+							    !b->percent_valid)
+								continue;
+							pct = (int)b->percent;
+							charging = (int)b->charging;
+							break;
+						}
+					}
+					if (pct != bar_batt_pct ||
+					    charging != bar_batt_charging ||
+					    ac != bar_batt_ac) {
+						bar_batt_pct = pct;
+						bar_batt_charging = charging;
+						bar_batt_ac = ac;
+						bar_dirty = 1;
+					}
+				}
+			}
 		}
 	}
 	if (full_redraw) {