Explorar el Código

Add Chrome EC power sources and Braswell P-state support

The HP Chromebook 11 G5 exposes battery, AC, temperatures, fans and the
lid/power switches through the Chrome EC ACPI memmap.  Add a shared ACPI
EC protocol (ec.c), the cros_ec backend, the power_src dispatcher, and
the SYS_CROS_EC_SENSORS snapshot; powerinfo, sensors and the WM top bar
now understand both the ThinkPad H8 and Chrome EC backends.

On Airmont/Braswell (family 6 model 0x4C), read the Atom ratio/VID MSRs
and MSR_FSB_FREQ, write IA32_PERF_CTL with the Linux VID interpolation,
and run the existing race-to-idle governor at pstates 6..20.  The default
is auto (480 MHz idle, 1600 MHz max on the N3060); turbo pstate 31 is
detected but not requested.  Enable the C6N MWAIT hint, use the coretemp
90 C TjMax table, and keep package C-state/S0ix setup firmware-managed.

Validated on the N3060: PERF_CTL 0x062D/0x143C, 479/476 MHz idle,
46 C DTS (down from 48 C at 2480 MHz), AC online/offline, 3891/4050 mAh.
Johannes Zellner hace 1 semana
padre
commit
920c8a9187
Se han modificado 27 ficheros con 1464 adiciones y 263 borrados
  1. 98 38
      AGENTS.md
  2. 14 5
      Makefile
  3. 454 0
      cros_ec.c
  4. 39 0
      cros_ec.h
  5. 10 8
      docs/cpu.html
  6. 15 10
      docs/drivers.html
  7. 1 1
      docs/index.html
  8. 1 1
      docs/userland.html
  9. 92 0
      ec.c
  10. 28 0
      ec.h
  11. 9 7
      idle.c
  12. 7 2
      kernel.c
  13. 416 31
      power.c
  14. 8 5
      power.h
  15. 13 0
      power_src.c
  16. 56 0
      power_src.h
  17. 36 5
      sys_info.c
  18. 1 0
      sys_info.h
  19. 5 0
      syscall.c
  20. 36 7
      syscall.h
  21. 7 3
      thermal.c
  22. 12 94
      tpec.c
  23. 9 36
      tpec.h
  24. 5 0
      ucmd_lib.h
  25. 20 4
      ucmd_powerinfo.c
  26. 69 3
      ucmd_sensors.c
  27. 3 3
      ucmd_wm.c

+ 98 - 38
AGENTS.md

@@ -575,47 +575,67 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   re-enumerates the bus, after which `usbhid` re-inits itself via a scan
   re-enumerates the bus, after which `usbhid` re-inits itself via a scan
   generation counter.
   generation counter.
 - **Power/idle**: `idle.c` — `idle auto` (the default) asks `power.c` for
 - **Power/idle**: `idle.c` — `idle auto` (the default) asks `power.c` for
-  the MWAIT hint: C6 (`0x20`) on the Nehalem/Westmere allowlist, HLT
-  everywhere else.  `idle hlt|c1e|c3|c6` (and the `c3ap`/`c6ap` AP-only
-  variants) are explicit overrides for testing; the Atom boards keep HLT
-  because of the old USB-legacy SMM hang (the UHCI/OHCI `0xC0` legacy-SMI
-  disable addresses it).  Arrandale hints are C1 `0x00`, C1E `0x01`, C3
-  `0x10`, C6 `0x20`.  The BSP PIT and each AP's LAPIC timer run at 1 kHz
-  while a process runs and drop to 100 Hz/10 ms while the CPU is idle
-  (`timer_set_hz`, `lapic_timer_set_ms`); the PIT stub advances the global
-  millisecond clock by `timer_tick_advance()`, and `smp_resched_wake()`
-  shortens the idle period when new work arrives.
-- **Frequency/package power**: `power.c/h` — Nehalem/Westmere P-states and
-  C-state setup, gated on the model allowlist (`0x1A/1E/1F/25/2C/2E/2F`)
-  because the MSRs must not be touched elsewhere.  `power_init()` enables
-  SpeedStep (`MISC_ENABLE` bit 16) and C1E (`POWER_CTL` bit 1), raises the
-  package C-state limit in `PKG_CST_CONFIG_CONTROL` to C6 only when it is
-  unlocked (bit 15), reads min/max ratios from `PLATFORM_INFO`, and starts at
-  the maximum non-turbo ratio.  The per-CPU tick runs a race-to-idle
-  governor: 100 ms windows pick min/max/linear target ratios (short busy
-  streaks jump to max immediately) and each CPU writes its own
-  `IA32_PERF_CTL`.  Nehalem/Westmere take the target ratio in bits 15:8 and
-  the low byte is written as zero (a preserved VID byte made the request
-  silently ineffective); `IA32_PERF_STATUS` reports the current ratio in
-  bits 7:0 (the X201 boot dump shows 0x12 at the 18x max non-turbo ratio).
-  The `power` command prints effective MHz (`APERF`/`MPERF`), the current
-  and requested ratios, per-core C3/C6 residency and package C3/C6;
-  `cpufreq [auto|min|max|off|<ratio>]` overrides the governor.
+  the MWAIT hint.  Nehalem/Westmere use C6 (`0x20`); Airmont/Braswell uses
+  C6N (`0x58`) when CPUID.5:EDX advertises the C6 substates and the MWAIT
+  interrupt-break extension is present; older Bonnell Atoms and APs without
+  ARAT keep HLT because of the old USB-legacy SMM hang (the UHCI/OHCI `0xC0`
+  legacy-SMI disable addresses it).  `idle hlt|c1e|c3|c6` (and the
+  `c3ap`/`c6ap` AP-only variants) are explicit overrides for testing.
+  Arrandale hints are C1 `0x00`, C1E `0x01`, C3 `0x10`, C6 `0x20`; the
+  Airmont auto path uses the Cherry Trail C6N hint.  The BSP PIT and each
+  AP's LAPIC timer run at 1 kHz while a process runs and drop to 100 Hz/10 ms
+  while the CPU is idle (`timer_set_hz`, `lapic_timer_set_ms`); the PIT stub
+  advances the global millisecond clock by `timer_tick_advance()`, and
+  `smp_resched_wake()` shortens the idle period when new work arrives.
+- **P-state/frequency power**: `power.c/h` — two platform paths, gated on
+  the model allowlist so the MSRs are not touched elsewhere.
+  Nehalem/Westmere (`0x1A/1E/1F/25/2C/2E/2F`) enable SpeedStep
+  (`MISC_ENABLE` bit 16) and C1E (`POWER_CTL` bit 1), raise the package
+  C-state limit in `PKG_CST_CONFIG_CONTROL` to C6 only when it is unlocked
+  (bit 15), read min/max ratios from `PLATFORM_INFO`, and start at the
+  maximum non-turbo ratio.  Their target ratio goes in bits 15:8 of
+  `IA32_PERF_CTL` with the low byte zero (a preserved VID byte made the
+  request silently ineffective); `IA32_PERF_STATUS` reports the current
+  ratio in bits 7:0 (the X201 boot dump shows 0x12 at the 18x max non-turbo
+  ratio).
+  Airmont/Braswell (family 6 model `0x4C`) reads `MSR_ATOM_CORE_RATIOS`
+  `0x66A` (min/max pstate), `MSR_ATOM_CORE_VIDS` `0x66B` (VID range),
+  `MSR_ATOM_CORE_TURBO_RATIOS/VIDS` `0x66C/0x66D`, `MSR_FSB_FREQ` `0xCD`
+  (the Airmont BCLK table) and `MSR_PLATFORM_INFO` as a fallback.  The
+  N3060 reports pstates 6..20, BCLK 80 MHz (1600 MHz nominal), turbo pstate
+  31 (2480 MHz) and VID 0x2D..0x3C.  It writes `IA32_PERF_CTL` as pstate in
+  15:8 and the Linux-interpolated VID in 7:0; the governor starts at max
+  non-turbo (pstate 20) and drops to min (pstate 6, 480 MHz).  Turbo is
+  detected but deliberately not requested, so `cpufreq max` means max
+  non-turbo.  No C1E/package-CST/auto-demotion MSR writes (coreboot
+  configures them) and no package-energy MSR reads; APERF/MPERF are used
+  only when CPUID.06H:ECX[0] says they exist.  C3/C6 residency is not read
+  on Airmont.
+  The per-CPU tick runs a race-to-idle governor: 100 ms windows pick
+  min/max/linear target pstates (short busy streaks jump to max immediately)
+  and each CPU writes its own `IA32_PERF_CTL`.  The `power` command prints
+  the platform, effective MHz (`APERF`/`MPERF`), current/requested pstate,
+  and on Nehalem the C3/C6 and package residency; the Airmont line adds the
+  FSB, nominal MHz, turbo pstate/VID, VID range and the live `PERF_CTL`.
+  `cpufreq [auto|min|max|off|<pstate>]` overrides the governor on both.
 - **CPU temperature**: `thermal.c/h` — Intel DTS through `IA32_THERM_STATUS`
 - **CPU temperature**: `thermal.c/h` — Intel DTS through `IA32_THERM_STATUS`
   (MSR `0x19C`).  Each CPU samples itself once a second from its scheduler
   (MSR `0x19C`).  Each CPU samples itself once a second from its scheduler
   tick (`struct cpu.temp_c`), and `SYS_CPU_TEMP` (`sys_info.c`) exposes the
   tick (`struct cpu.temp_c`), and `SYS_CPU_TEMP` (`sys_info.c`) exposes the
   hottest core plus TjMax to ring 3.  The model allowlist follows coretemp
   hottest core plus TjMax to ring 3.  The model allowlist follows coretemp
-  (Core/Core 2, Nehalem/Westmere including the X201's Arrandale `0x25`, and
-  Bonnell) and is what keeps `rdmsr` away from CPUs that lack the MSR.
-  Nehalem and later read TjMax from `IA32_TEMPERATURE_TARGET` (MSR `0x1A2`,
-  bits 23:16; the X201's i5 M 520 reports 105 °C); Bonnell has no such MSR,
-  so its TjMax stays table-driven (Atom 330 = 125 °C, 230 = 100, other
-  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 (with `AC on`/`AC off` and
-  `BAT 87%` to its left on ThinkPads) and `cpuinfo`'s value plus EIST state.
-  Platforms without DTS (QEMU, Pentium) hide it.
+  (Core/Core 2, Nehalem/Westmere including the X201's Arrandale `0x25`,
+  Bonnell, and Airmont/Braswell model `0x4C`) and is what keeps `rdmsr` away
+  from CPUs that lack the MSR.  Nehalem/Westmere read TjMax from
+  `IA32_TEMPERATURE_TARGET` (MSR `0x1A2`, bits 23:16; the X201's i5 M 520
+  reports 105 °C); Airmont uses the coretemp 90 °C table instead of reading
+  `0x1A2` (a missing MSR before the IDT is installed would triple-fault);
+  Bonnell has no such MSR, so its TjMax stays table-driven (Atom 330 =
+  125 °C, 230 = 100, other 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 (with
+  `AC on`/`AC off` and `BAT 87%` to its left on ThinkPads and the HP
+  Chromebook) 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
 - **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
   (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
   by `SYS_SENSORS` and the ring-3 `sensors` command to cross-check the DTS
@@ -638,6 +658,24 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `powerinfo` command prints AC/battery details and the WM top bar shows the
   `powerinfo` command prints AC/battery details and the WM top bar shows the
   AC adapter state plus the first present battery with a valid percentage.
   AC adapter state plus the first present battery with a valid percentage.
   Machines without the EC show neither.
   Machines without the EC show neither.
+  `ec.c/h` is the shared ACPI EC protocol (ports 0x62/0x66, command 0x80
+  read / 0x81 write, OBF/IBF waits, stale-byte drain, bounded polls); both
+  `tpec.c` and `cros_ec.c` use it.  `cros_ec.c/h` probes the Chrome OS EC:
+  ACPI memory version 2, the `'E','C'` memmap id, the device feature bits,
+  and skips the probe when the ThinkPad EC is present.  The ACPI window
+  0x20..0xFF mirrors memmap 0x00..0xDF: temperature sensors 0x00..0x0f and
+  0x18..0x1f (raw - 73 °C), fans 0x10..0x17 (0xffff = absent), switches
+  0x30 (lid/power button), and the battery block 0x40..0x7f (AC/present/
+  charging/discharging flags at 0x4c, voltage 0x40, rate 0x44, remaining
+  0x48, design 0x50, design voltage 0x54, last full 0x58, cycle count 0x5c,
+  and the 8-byte manufacturer/model/serial/type strings at 0x60..0x7f).
+  `EC_ACPI_MEM_BATTERY_INDEX` 0x12 selects the battery and waits for
+  `BATT_INDEX` 0x4e; `EC_ACPI_MEM_STRINGS_FIFO` 0x16 supplies longer strings
+  when supported.  The Cyan full-charge workaround is applied and the units
+  are mAh/mA.  `SYS_CROS_EC_SENSORS` (107) exposes temperatures, fans, fan
+  duty and switches; `SYS_POWER_INFO` reports source `SYS_POWER_SRC_CROS`.
+  `power_src.c` tries the ThinkPad backend first, then the Chrome EC, so the
+  WM top bar and the `powerinfo`/`sensors` commands work on both.
 - **Ring-3 address space**: the ELF image and 128 KB (32-page) stack live in
 - **Ring-3 address space**: the ELF image and 128 KB (32-page) stack live in
   the 4 MB `USER_BASE` (`0x40000000`)..`USER_STACK_TOP` (`0x40400000`)
   the 4 MB `USER_BASE` (`0x40000000`)..`USER_STACK_TOP` (`0x40400000`)
   window, which is too small for a full-frame image.  `SYS_MEM_ALLOC`/`SYS_MEM_GROW`/`SYS_MEM_FREE`
   window, which is too small for a full-frame image.  `SYS_MEM_ALLOC`/`SYS_MEM_GROW`/`SYS_MEM_FREE`
@@ -874,7 +912,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>`,
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`,
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad`, `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),
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad`, `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`, `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).
+`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `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
 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
 DHCP client), `netdev [name]` (kernel command: show the active NIC driver or
@@ -1539,3 +1577,25 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     scale is fixed (no pointer-acceleration curve).  The device stalls if
     scale is fixed (no pointer-acceleration curve).  The device stalls if
     the input register is read back-to-back, so a GPIO interrupt (or a
     the input register is read back-to-back, so a GPIO interrupt (or a
     larger minimum gap) is the prerequisite for a higher report rate.
     larger minimum gap) is the prerequisite for a higher report rate.
+
+29. Airmont/Braswell power management: the governor caps at the maximum
+    non-turbo pstate (N3060: 20 = 1600 MHz) and never requests turbo pstate
+    31 (2480 MHz), so `cpufreq max` means max non-turbo.  C6N is enabled but
+    the kernel does not program package C-states/S0ix, does not read package
+    RAPL energy, and does not write the package C-state/auto-demotion MSRs
+    (coreboot/FSP configures them).  The Airmont probe deliberately avoids
+    package/power-SKU MSRs because an unsupported `rdmsr` before the IDT
+    triple-faults; the first read-only build hung at `power_init` that way.
+    C3/C6 residency is not reported on Airmont, and the explicit `idle c6`
+    override still uses the Nehalem `0x20` hint; use `idle auto` for the
+    validated Airmont C6N (`0x58`) path.
+
+30. Chrome EC limits: only the ACPI v2 memmap interface is used; the MEC
+    host-command/EMI interface, EC SCI events, charger current/voltage,
+    charging limit and EC firmware version are not implemented.  The
+    battery/AC values are polled (WM at 1 Hz), so a plug event can take up
+    to a second to appear.  Battery strings fall back to the 8-byte memmap
+    and can be truncated; fan entries may read 0 on fanless models instead
+    of 0xffff.  The lid/power-button switches are read by `sensors` but do
+    not trigger a power-off or display blank; suspend/S0ix is not
+    implemented.

+ 14 - 5
Makefile

@@ -73,7 +73,7 @@ all: floppy.img usb.img final.bin root.img
 boot.o: boot.S
 boot.o: boot.S
 	$(AS) $(ASFLAGS) -o $@ $<
 	$(AS) $(ASFLAGS) -o $@ $<
 
 
-kernel.o: kernel.c acpi.h cpu.h idle.h io.h lapic.h mouse.h panic.h phys.h process.h sched.h smp.h terminal.h timer.h serial.h tss.h usbhid.h version.h vga.h
+kernel.o: kernel.c acpi.h cpu.h cros_ec.h idle.h io.h lapic.h mouse.h panic.h phys.h process.h sched.h smp.h terminal.h timer.h serial.h tss.h usbhid.h version.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -o $@ $<
 
 
 screen.o: screen.c screen.h
 screen.o: screen.c screen.h
@@ -145,7 +145,16 @@ thermal.o: thermal.c thermal.h cpu.h sched.h serial.h
 power.o: power.c power.h cpu.h idle.h io.h sched.h serial.h
 power.o: power.c power.h cpu.h idle.h io.h sched.h serial.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -o $@ $<
 
 
-tpec.o: tpec.c tpec.h paging.h pci.h serial.h
+tpec.o: tpec.c tpec.h power_src.h ec.h paging.h serial.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+ec.o: ec.c ec.h pci.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+cros_ec.o: cros_ec.c cros_ec.h power_src.h ec.h tpec.h serial.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+power_src.o: power_src.c power_src.h tpec.h cros_ec.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -o $@ $<
 
 
 it87.o: it87.c it87.h pci.h
 it87.o: it87.c it87.h pci.h
@@ -367,7 +376,7 @@ sys_mem.o: sys_mem.c sys_mem.h mm.h paging.h process.h
 inflate.o: inflate.c inflate.h
 inflate.o: inflate.c inflate.h
 	$(CC) $(CFLAGS) $(SECTION_CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) $(SECTION_CFLAGS) -o $@ $<
 
 
-sys_info.o: sys_info.c sys_info.h syscall.h ahci.h blkdev.h it87.h mm.h mouse.h thermal.h tpec.h usbhid.h vfs.h
+sys_info.o: sys_info.c sys_info.h syscall.h ahci.h blkdev.h cros_ec.h it87.h mm.h mouse.h power_src.h thermal.h tpec.h usbhid.h vfs.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -o $@ $<
 
 
 sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netdev.h netlog.h ntp.h process.h sched.h
 sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netdev.h netlog.h ntp.h process.h sched.h
@@ -376,7 +385,7 @@ sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netdev.h netlog.h nt
 syscall_stub.o: syscall_stub.S irqret.inc
 syscall_stub.o: syscall_stub.S irqret.inc
 	$(AS) $(ASFLAGS) -o $@ $<
 	$(AS) $(ASFLAGS) -o $@ $<
 
 
-kernel.elf: kernel.ld vesa_stage.o entry.o kernel.o timer.o switch.o sched.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 serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp_embed.o inflate.o ramfs.o share.o payload.o
+kernel.elf: kernel.ld vesa_stage.o entry.o kernel.o timer.o switch.o sched.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 serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o ec.o cros_ec.o power_src.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp_embed.o inflate.o ramfs.o share.o payload.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $(filter-out kernel.ld,$^)
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $(filter-out kernel.ld,$^)
 
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -1155,4 +1164,4 @@ kernel-net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 
 clean:
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.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 disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.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 hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test format_test math_test div64_test setjmp_test mujs_test js_browser.o $(MUJS_DIR)/mujs.o ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.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 disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o ec.o cros_ec.o power_src.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.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 hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test format_test math_test div64_test setjmp_test mujs_test js_browser.o $(MUJS_DIR)/mujs.o ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan

+ 454 - 0
cros_ec.c

@@ -0,0 +1,454 @@
+/* Chrome OS embedded controller: battery, AC adapter and board sensors.
+ *
+ * Chromebooks do not expose ACPI _BIF/_BST through an interpreter we could
+ * run; instead the Chrome EC implements the standard ACPI EC command
+ * interface at ports 0x62/0x66, and its ACPI memory window 0x20..0xFF
+ * mirrors the EC memmap 0x00..0xDF.  That gives us the same data the
+ * firmware's DSDT reads:
+ *
+ *   EC_MEMMAP_TEMP_SENSOR 0x00..0x0f   temperatures (value + 200 = Kelvin)
+ *   EC_MEMMAP_FAN         0x10..0x17   fan tachometers (16-bit, 0xffff none)
+ *   EC_MEMMAP_TEMP_SENSOR_B 0x18..0x1f more temperatures (thermal version 2)
+ *   EC_MEMMAP_SWITCHES    0x30         lid open / power button
+ *   EC_MEMMAP_BATT_VOLT   0x40         present voltage (mV)
+ *   EC_MEMMAP_BATT_RATE   0x44         present rate (mA, ACPI power unit)
+ *   EC_MEMMAP_BATT_CAP    0x48         remaining capacity (mAh)
+ *   EC_MEMMAP_BATT_FLAG   0x4c         AC/battery/charging state
+ *   EC_MEMMAP_BATT_COUNT  0x4d         battery count
+ *   EC_MEMMAP_BATT_INDEX  0x4e         selected battery
+ *   EC_MEMMAP_BATT_DCAP   0x50         design capacity (mAh)
+ *   EC_MEMMAP_BATT_DVLT   0x54         design voltage (mV)
+ *   EC_MEMMAP_BATT_LFCC   0x58         last full charge capacity (mAh)
+ *   EC_MEMMAP_BATT_CCNT   0x5c         cycle count
+ *   EC_MEMMAP_BATT_MFGR/MODEL/SERIAL/TYPE 0x60..0x7f  (8-byte strings)
+ *
+ * The battery index is selected through EC_ACPI_MEM_BATTERY_INDEX (0x12);
+ * longer strings come from EC_ACPI_MEM_STRINGS_FIFO (0x16).  The memmap is
+ * read-only from the AP, so the only writes are the documented selector and
+ * FIFO commands.
+ *
+ * The probe is gated on the EC ACPI version and the 'E','C' memmap id; the
+ * ThinkPad backend is tried first and skips this one on Lenovo machines.
+ */
+#include "cros_ec.h"
+#include "ec.h"
+#include "tpec.h"
+#include "serial.h"
+
+#define CROS_ACPI_VERSION        0x00
+#define CROS_ACPI_BATTERY_INDEX  0x12
+#define CROS_ACPI_STRINGS_FIFO   0x16
+#define CROS_ACPI_FAN_DUTY       0x04
+
+#define CROS_MEM_ACPI_BASE       0x20
+#define CROS_MEM_TEMP_SENSOR     0x00
+#define CROS_MEM_TEMP_SENSOR_B   0x18
+#define CROS_MEM_FAN             0x10
+#define CROS_MEM_ID              0x20
+#define CROS_MEM_ID_VERSION      0x22
+#define CROS_MEM_THERMAL_VERSION 0x23
+#define CROS_MEM_BATTERY_VERSION 0x24
+#define CROS_MEM_SWITCHES        0x30
+#define CROS_MEM_BATT_VOLT       0x40
+#define CROS_MEM_BATT_RATE       0x44
+#define CROS_MEM_BATT_CAP        0x48
+#define CROS_MEM_BATT_FLAG       0x4c
+#define CROS_MEM_BATT_COUNT      0x4d
+#define CROS_MEM_BATT_INDEX      0x4e
+#define CROS_MEM_BATT_DCAP       0x50
+#define CROS_MEM_BATT_DVLT       0x54
+#define CROS_MEM_BATT_LFCC       0x58
+#define CROS_MEM_BATT_CCNT       0x5c
+#define CROS_MEM_BATT_MFGR       0x60
+#define CROS_MEM_BATT_MODEL      0x68
+#define CROS_MEM_BATT_SERIAL     0x70
+
+/* EC_MEMMAP_BATT_FLAG bits. */
+#define CROS_BATT_AC_PRESENT     0x01
+#define CROS_BATT_PRESENT        0x02
+#define CROS_BATT_DISCHARGING    0x04
+#define CROS_BATT_CHARGING       0x08
+#define CROS_BATT_INVALID_DATA   0x20
+#define CROS_BATT_CUT_OFF        0x40
+
+/* EC_MEMMAP_SWITCHES bits. */
+#define CROS_SWITCH_LID_OPEN     0x01
+#define CROS_SWITCH_POWER_BUTTON 0x02
+
+/* Device feature bits (EC_ACPI_MEM_DEVICE_FEATURES, 8 bytes). */
+#define CROS_FEATURE_BATT        (1u << 17)
+#define CROS_FEATURE_DFUD        (1u << 0)
+
+#define CROS_UNKNOWN32 0xFFFFFFFFu
+#define CROS_TEMP_OFFSET 73   /* raw + 200 = Kelvin, so raw - 73 = C */
+
+static int cros_state = -1;   /* -1 unprobed, 0 absent, 1 present */
+static unsigned int cros_acpi_version;
+static unsigned int cros_id_version;
+static unsigned int cros_battery_version;
+static unsigned int cros_thermal_version;
+static unsigned int cros_features;
+static int cros_fifo = -1;    /* -1 unprobed, 0 absent, 1 present */
+
+static int mem_read(unsigned int off, unsigned char *out)
+{
+	return ec_read((unsigned char)(CROS_MEM_ACPI_BASE + off), out);
+}
+
+static int mem_read16(unsigned int off, unsigned int *out)
+{
+	unsigned char lo, hi;
+
+	if (mem_read(off, &lo) != 0 || mem_read(off + 1, &hi) != 0)
+		return -1;
+	*out = (unsigned int)lo | ((unsigned int)hi << 8);
+	return 0;
+}
+
+static int mem_read32(unsigned int off, unsigned int *out)
+{
+	unsigned char b0, b1, b2, b3;
+
+	if (mem_read(off, &b0) != 0 || mem_read(off + 1, &b1) != 0 ||
+	    mem_read(off + 2, &b2) != 0 || mem_read(off + 3, &b3) != 0)
+		return -1;
+	*out = (unsigned int)b0 | ((unsigned int)b1 << 8) |
+	       ((unsigned int)b2 << 16) | ((unsigned int)b3 << 24);
+	return 0;
+}
+
+/* Read one of the 8-byte fixed strings from the memmap. */
+static void read_short_string(unsigned int off, char *dst, unsigned int size)
+{
+	unsigned int i, n = 8;
+
+	if (n > size - 1)
+		n = size - 1;
+	for (i = 0; i < n; i++) {
+		unsigned char b;
+
+		if (mem_read(off + i, &b) != 0)
+			break;
+		if (b == 0 || b == 0xFF)
+			break;
+		dst[i] = (char)b;
+	}
+	while (i && dst[i - 1] == ' ')
+		i--;
+	dst[i] = '\0';
+}
+
+/* Long strings from EC_ACPI_MEM_STRINGS_FIFO, when the EC supports them. */
+static void read_fifo_string(unsigned int id, char *dst, unsigned int size)
+{
+	unsigned int i;
+
+	if (ec_write(CROS_ACPI_STRINGS_FIFO, (unsigned char)id) != 0) {
+		dst[0] = '\0';
+		return;
+	}
+	for (i = 0; i + 1 < size; i++) {
+		unsigned char b;
+
+		if (ec_read(CROS_ACPI_STRINGS_FIFO, &b) != 0)
+			break;
+		if (b == 0)
+			break;
+		dst[i] = (char)b;
+	}
+	while (i && dst[i - 1] == ' ')
+		i--;
+	dst[i] = '\0';
+}
+
+static void read_string(unsigned int off, unsigned int fifo_id, char *dst,
+			unsigned int size)
+{
+	if (cros_fifo > 0) {
+		read_fifo_string(fifo_id, dst, size);
+		if (dst[0])
+			return;
+	}
+	read_short_string(off, dst, size);
+}
+
+static int battery_select(unsigned int index)
+{
+	unsigned char cur;
+	unsigned int i;
+
+	if (mem_read(CROS_MEM_BATT_INDEX, &cur) == 0 &&
+	    cur == (unsigned char)index)
+		return 0;
+	if (ec_write(CROS_ACPI_BATTERY_INDEX, (unsigned char)index) != 0)
+		return -1;
+	/* The DSDT's BTSW waits 5 ms for BTIX to follow BTID.  Each read is
+	 * already several port handshakes, so a bounded retry is enough. */
+	for (i = 0; i < 50; i++) {
+		if (mem_read(CROS_MEM_BATT_INDEX, &cur) == 0 &&
+		    cur == (unsigned char)index)
+			return 0;
+	}
+	return -1;
+}
+
+static void read_temp(unsigned int off, int *out)
+{
+	unsigned char b;
+
+	if (mem_read(off, &b) != 0 || b >= 0xFC) {
+		*out = -128;
+		return;
+	}
+	*out = (int)b - CROS_TEMP_OFFSET;
+}
+
+void cros_ec_init(void)
+{
+	unsigned char ver = 0, id0 = 0, id1 = 0, b;
+	unsigned int i, feature = 0;
+
+	cros_state = 0;
+	cros_acpi_version = 0;
+	cros_id_version = 0;
+	cros_battery_version = 0;
+	cros_thermal_version = 0;
+	cros_features = 0;
+	cros_fifo = -1;
+
+	/* The ThinkPad H8 has its own driver and the first claim on 0x62/0x66. */
+	if (tpec_present()) {
+		serial_puts(SERIAL_COM1, "cros_ec: ThinkPad EC present, skipped\n");
+		return;
+	}
+
+	if (ec_read(CROS_ACPI_VERSION, &ver) != 0) {
+		serial_puts(SERIAL_COM1, "cros_ec: no ACPI EC at 0x62/0x66\n");
+		return;
+	}
+	if (mem_read(CROS_MEM_ID, &id0) != 0 ||
+	    mem_read(CROS_MEM_ID + 1, &id1) != 0 ||
+	    id0 != 'E' || id1 != 'C') {
+		serial_puts(SERIAL_COM1, "cros_ec: no Chrome EC signature\n");
+		return;
+	}
+
+	for (i = 0; i < 4; i++) {
+		unsigned char f;
+
+		if (mem_read(0x0A + i, &f) != 0) {
+			feature = 0;
+			break;
+		}
+		feature |= (unsigned int)f << (8 * i);
+	}
+	if (feature & CROS_FEATURE_DFUD)
+		feature = 0;
+	if (mem_read(CROS_MEM_ID_VERSION, &b) == 0)
+		cros_id_version = b;
+	if (mem_read(CROS_MEM_THERMAL_VERSION, &b) == 0)
+		cros_thermal_version = b;
+	if (mem_read(CROS_MEM_BATTERY_VERSION, &b) == 0)
+		cros_battery_version = b;
+
+	cros_acpi_version = ver;
+	cros_features = feature;
+	cros_state = 1;
+
+	/* Probe the extended-string FIFO once (write 0, read the version). */
+	{
+		unsigned char fifo = 0xFF;
+
+		if (ec_write(CROS_ACPI_STRINGS_FIFO, 0) == 0)
+			(void)ec_read(CROS_ACPI_STRINGS_FIFO, &fifo);
+		cros_fifo = (fifo >= 1 && fifo < 0xFF) ? 1 : 0;
+	}
+
+	serial_puts(SERIAL_COM1, "cros_ec: Chrome EC, ACPI v");
+	serial_putdec(SERIAL_COM1, cros_acpi_version);
+	serial_puts(SERIAL_COM1, ", id v");
+	serial_putdec(SERIAL_COM1, cros_id_version);
+	serial_puts(SERIAL_COM1, ", battery v");
+	serial_putdec(SERIAL_COM1, cros_battery_version);
+	serial_puts(SERIAL_COM1, ", thermal v");
+	serial_putdec(SERIAL_COM1, cros_thermal_version);
+	serial_puts(SERIAL_COM1, ", features ");
+	serial_puthex(SERIAL_COM1, cros_features);
+	serial_puts(SERIAL_COM1, ", fifo ");
+	serial_puts(SERIAL_COM1, cros_fifo ? "yes" : "no");
+	serial_puts(SERIAL_COM1, "\n");
+
+	if (mem_read(CROS_MEM_BATT_COUNT, &b) == 0) {
+		serial_puts(SERIAL_COM1, "cros_ec: batteries ");
+		serial_putdec(SERIAL_COM1, b);
+		serial_puts(SERIAL_COM1, ", feature batt ");
+		serial_puts(SERIAL_COM1,
+			    (cros_features & CROS_FEATURE_BATT) ? "yes" : "no");
+		serial_puts(SERIAL_COM1, "\n");
+	}
+}
+
+int cros_ec_present(void)
+{
+	if (cros_state < 0)
+		cros_ec_init();
+	return cros_state > 0;
+}
+
+void cros_ec_power_read(struct power_info *out, int detail)
+{
+	unsigned int i, count;
+	unsigned char flags = 0;
+	unsigned char count_byte = 0;
+	int ac = -1;
+
+	for (i = 0; i < sizeof(*out); i++)
+		((unsigned char *)out)[i] = 0;
+	out->ac_online = -1;
+
+	if (cros_state < 0)
+		cros_ec_init();
+	if (!cros_state)
+		return;
+
+	out->present = 1;
+	out->source = SYS_POWER_SRC_CROS;
+	out->ec_rev = cros_acpi_version;
+
+	if (mem_read(CROS_MEM_BATT_FLAG, &flags) == 0)
+		ac = (flags & CROS_BATT_AC_PRESENT) ? 1 : 0;
+	out->ac_online = ac;
+
+	if (mem_read(CROS_MEM_BATT_COUNT, &count_byte) != 0 ||
+	    count_byte == 0 || count_byte > POWER_BATT_MAX)
+		count = 1;
+	else
+		count = count_byte;
+
+	for (i = 0; i < count; i++) {
+		struct power_battery *b = &out->battery[i];
+		unsigned int volt = 0, rate = 0, cap = 0, lfcc = 0;
+		unsigned int design = 0, dvlt = 0, cycles = 0;
+		unsigned int full;
+		unsigned char f = 0;
+
+		if (battery_select(i) != 0) {
+			b->error = 1;
+			continue;
+		}
+		if (mem_read(CROS_MEM_BATT_FLAG, &f) != 0) {
+			b->error = 1;
+			continue;
+		}
+
+		b->status = f;
+		b->present = (f & CROS_BATT_PRESENT) ? 1 : 0;
+		b->charging = (f & CROS_BATT_CHARGING) ? 1 : 0;
+		b->discharging = (f & CROS_BATT_DISCHARGING) ? 1 : 0;
+		if (f & (CROS_BATT_INVALID_DATA | CROS_BATT_CUT_OFF))
+			b->error = 1;
+		if (!b->present)
+			continue;
+
+		if (mem_read32(CROS_MEM_BATT_VOLT, &volt) != 0 ||
+		    mem_read32(CROS_MEM_BATT_RATE, &rate) != 0 ||
+		    mem_read32(CROS_MEM_BATT_CAP, &cap) != 0 ||
+		    mem_read32(CROS_MEM_BATT_LFCC, &lfcc) != 0)
+			b->error = 1;
+
+		if (volt != CROS_UNKNOWN32)
+			b->voltage_mv = volt;
+		if (rate != CROS_UNKNOWN32)
+			b->rate = (int)rate;
+		if (cap != CROS_UNKNOWN32)
+			b->remaining = cap;
+		if (lfcc != CROS_UNKNOWN32)
+			b->full = lfcc;
+
+		if (detail) {
+			if (mem_read32(CROS_MEM_BATT_DCAP, &design) != 0 ||
+			    mem_read32(CROS_MEM_BATT_DVLT, &dvlt) != 0 ||
+			    mem_read32(CROS_MEM_BATT_CCNT, &cycles) != 0)
+				b->error = 1;
+			if (design != CROS_UNKNOWN32)
+				b->design = design;
+			if (cycles != CROS_UNKNOWN32)
+				b->cycle_count = cycles;
+			(void)dvlt;   /* design voltage is informational */
+		}
+
+		/* _BIF declares mAh/mA on Chromebooks. */
+		b->unit_known = 1;
+		b->unit_mwh = 0;
+
+		/* The Cyan DSDT compensates a full pack that the EC reports as
+		 * neither charging nor discharging while AC is present. */
+		full = b->full ? b->full : b->design;
+		if (ac > 0 && !(b->discharging && b->charging) && full &&
+		    b->remaining > full - full / 16 &&
+		    b->remaining < full + full / 16)
+			b->remaining = full;
+
+		if (full && b->remaining &&
+		    b->remaining <= full + full / 4) {
+			unsigned int pct =
+				(b->remaining * 100u + full / 2u) / full;
+
+			if (pct > 100)
+				pct = 100;
+			b->percent = (int)pct;
+			b->percent_valid = 1;
+		}
+
+		if (detail) {
+			read_string(CROS_MEM_BATT_MFGR, 3, b->manufacturer,
+				    sizeof(b->manufacturer));
+			read_string(CROS_MEM_BATT_MODEL, 1, b->model,
+				    sizeof(b->model));
+			read_string(CROS_MEM_BATT_SERIAL, 2, b->serial,
+				    sizeof(b->serial));
+		}
+
+		out->battery_count++;
+	}
+}
+
+void cros_ec_sensors_read(struct cros_ec_sensors *out)
+{
+	unsigned int i;
+	unsigned char b;
+
+	for (i = 0; i < sizeof(*out); i++)
+		((unsigned char *)out)[i] = 0;
+	for (i = 0; i < CROS_EC_TEMP_MAX; i++)
+		out->temp_c[i] = -128;
+
+	if (cros_state < 0)
+		cros_ec_init();
+	if (!cros_state)
+		return;
+
+	out->present = 1;
+	out->acpi_version = cros_acpi_version;
+	out->battery_version = cros_battery_version;
+	out->thermal_version = cros_thermal_version;
+
+	for (i = 0; i < 16; i++)
+		read_temp(CROS_MEM_TEMP_SENSOR + i, &out->temp_c[i]);
+	for (i = 0; i < 8; i++)
+		read_temp(CROS_MEM_TEMP_SENSOR_B + i, &out->temp_c[16 + i]);
+
+	for (i = 0; i < CROS_EC_FAN_MAX; i++) {
+		unsigned int v;
+
+		if (mem_read16(CROS_MEM_FAN + 2 * i, &v) == 0 &&
+		    v != 0xFFFF) {
+			out->fan_rpm[i] = v;
+			out->fan_present |= 1u << i;
+		}
+	}
+	if (ec_read(CROS_ACPI_FAN_DUTY, &b) == 0)
+		out->fan_duty = b;
+	if (mem_read(CROS_MEM_SWITCHES, &b) == 0)
+		out->switches = b;
+}

+ 39 - 0
cros_ec.h

@@ -0,0 +1,39 @@
+/* Chrome OS embedded controller power/sensor backend. */
+#ifndef CROS_EC_H
+#define CROS_EC_H
+
+#include "power_src.h"
+
+#define CROS_EC_TEMP_MAX 24
+#define CROS_EC_FAN_MAX 4
+
+/* -128 means the EC reports the sensor as absent/unavailable.  fan_present
+ * is a bitmask over fan_rpm[]; fan_duty is the raw EC_ACPI_MEM_FAN_DUTY
+ * value (0xff means automatic).  switches follows EC_MEMMAP_SWITCHES
+ * (bit 0 lid open, bit 1 power button pressed). */
+struct cros_ec_sensors {
+	int present;
+	unsigned int acpi_version;
+	unsigned int battery_version;
+	unsigned int thermal_version;
+	int temp_c[CROS_EC_TEMP_MAX];
+	unsigned int fan_rpm[CROS_EC_FAN_MAX];
+	unsigned int fan_present;
+	unsigned int fan_duty;
+	unsigned int switches;
+};
+
+/* Probe once on the BSP; skips the probe when the ThinkPad EC is present.
+ * Logs the result to COM1. */
+void cros_ec_init(void);
+
+int cros_ec_present(void);
+
+/* Fill the generic AC/battery snapshot; detail also reads design data and
+ * the manufacturer/model/serial strings. */
+void cros_ec_power_read(struct power_info *out, int detail);
+
+/* Read the EC temperature/fan/switch snapshot. */
+void cros_ec_sensors_read(struct cros_ec_sensors *out);
+
+#endif

+ 10 - 8
docs/cpu.html

@@ -338,16 +338,18 @@
 		<h2>Idle, power &amp; thermals</h2>
 		<h2>Idle, power &amp; thermals</h2>
 		<p>
 		<p>
 			<code>idle auto</code> is the default. It asks <span class="file">power.c</span>
 			<code>idle auto</code> is the default. It asks <span class="file">power.c</span>
-			for the deepest usable hint: C6 (<code>0x20</code>) on the
-			Nehalem/Westmere allowlist, HLT everywhere else. The Atom boards keep
-			HLT because of an old USB-legacy SMM hang; the UHCI/OHCI
-			<code>0xC0</code> legacy-SMI disable addresses it.
+			for the deepest usable hint: C6 (<code>0x20</code>) on
+			Nehalem/Westmere, C6N (<code>0x58</code>) on Airmont/Braswell when
+			CPUID advertises the C6 substates, and HLT on the older Atom boards
+			where an old USB-legacy SMM hang made deep states risky.
 		</p>
 		</p>
 		<ul>
 		<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 temperatures/fan; <code>powerinfo</code> prints the AC adapter and battery state, and the WM top bar shows the AC adapter state and battery percentage on ThinkPads.</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>
+			<li><strong>Nehalem/Westmere P-states.</strong> <code>power_init</code> enables SpeedStep, raises the package C-state limit to C6 when unlocked, reads min/max ratios from <code>PLATFORM_INFO</code> and starts at the maximum non-turbo ratio. The target ratio goes in bits 15:8 of <code>IA32_PERF_CTL</code> with the low byte zero.</li>
+			<li><strong>Airmont/Braswell P-states.</strong> Family 6 model <code>0x4C</code> reads the Atom ratio/VID MSRs (<code>0x66A..0x66D</code>), <code>MSR_FSB_FREQ</code> and the FSB table. The N3060 reports pstates 6..20, BCLK 80 MHz (1600 MHz nominal), turbo pstate 31 (2480 MHz) and VID 0x2D..0x3C. <code>power_init</code> enters at max non-turbo and the governor drops to pstate 6 (480 MHz); <code>IA32_PERF_CTL</code> carries the pstate in 15:8 and the Linux-interpolated VID in 7:0. Turbo is detected but not requested. The probe deliberately avoids package/power-SKU MSRs; an unsupported <code>rdmsr</code> before the IDT triple-faults.</li>
+			<li><strong>Governor.</strong> A 100 ms window picks min/max/linear target pstates; short busy streaks jump to max immediately. Each CPU writes its own <code>IA32_PERF_CTL</code>; <code>cpufreq [auto|min|max|off|&lt;pstate&gt;]</code> overrides it.</li>
+			<li><strong>Telemetry.</strong> <code>power</code> prints effective MHz from APERF/MPERF, the current/requested pstate and, on Airmont, the FSB, nominal MHz, turbo pstate/VID, VID range and live <code>PERF_CTL</code>; <code>sensors</code> prints DTS, board sensors and both EC types; <code>powerinfo</code> prints the AC adapter and battery state, and the WM top bar shows AC and battery percentage on ThinkPads and Chromebooks.</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. TjMax comes from <code>IA32_TEMPERATURE_TARGET</code> on Nehalem/Westmere, the coretemp 90 °C table on Airmont, and the Bonnell table on older Atoms.</li>
+			<li><strong>Limits.</strong> Package C-states/S0ix remain firmware-managed; Airmont reports no C3/C6 residency and does not request the turbo pstate. The explicit <code>idle c6</code> override is the Nehalem <code>0x20</code> hint; use <code>idle auto</code> for the Airmont C6N (<code>0x58</code>) path.</li>
 		</ul>
 		</ul>
 	</section>
 	</section>
 
 

+ 15 - 10
docs/drivers.html

@@ -87,7 +87,7 @@
 					<tr><td>Touchpad</td><td><span class="file">i2c.c</span>, <span class="file">touchpad.c</span></td><td>LPSS DesignWare I2C, slave <code>0x15</code></td><td>Polled input register every 25 ms; no GPIO interrupt driver</td></tr>
 					<tr><td>Touchpad</td><td><span class="file">i2c.c</span>, <span class="file">touchpad.c</span></td><td>LPSS DesignWare I2C, slave <code>0x15</code></td><td>Polled input register every 25 ms; no GPIO interrupt driver</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>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>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 (temps, fan, battery, AC)</td><td>Polled; only the EC page selector is written, then restored</td></tr>
+					<tr><td>Board sensors / EC</td><td><span class="file">it87.c</span>, <span class="file">tpec.c</span>, <span class="file">ec.c</span>, <span class="file">cros_ec.c</span></td><td>Super I/O, ThinkPad H8 EC, Chrome OS EC (temps, fans, battery, AC, switches)</td><td>Polled; EC battery-index/FIFO/page-selector writes only</td></tr>
 					<tr><td>Wall clock</td><td><span class="file">rtc.c</span></td><td>CMOS RTC ports <code>0x70/0x71</code></td><td>Read/write under the BKL; update-cycle retries and a 1970–2069 two-digit year window</td></tr>
 					<tr><td>Wall clock</td><td><span class="file">rtc.c</span></td><td>CMOS RTC ports <code>0x70/0x71</code></td><td>Read/write under the BKL; update-cycle retries and a 1970–2069 two-digit year window</td></tr>
 				</tbody>
 				</tbody>
 			</table>
 			</table>
@@ -345,19 +345,22 @@
 	<section id="sensors">
 	<section id="sensors">
 		<h2>Sensors, power &amp; thermals</h2>
 		<h2>Sensors, power &amp; thermals</h2>
 		<ul>
 		<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>DTS.</strong> <span class="file">thermal.c</span> reads <code>IA32_THERM_STATUS</code> on an allowlist of Core/Core 2, Nehalem/Westmere, Bonnell and Airmont/Braswell models. TjMax comes from <code>IA32_TEMPERATURE_TARGET</code> on Nehalem/Westmere; Airmont uses coretemp's 90 °C table (the kernel does not read the MSR before the IDT exists), and Bonnell uses the 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>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. 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>ThinkPad EC.</strong> <span class="file">tpec.c</span> is gated on an SMBIOS Lenovo/IBM match and reads temperatures and fan mode through the shared ACPI EC protocol in <span class="file">ec.c</span> (ports <code>0x62/0x66</code>, command <code>0x80</code> read / <code>0x81</code> write, OBF/IBF waits, stale-byte drain, bounded polls). 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>Chrome EC.</strong> <span class="file">cros_ec.c</span> probes the Chrome OS EC, gated on the ACPI memory version, the <code>'E','C'</code> memmap id and the device feature bits; it skips the probe when the ThinkPad EC is present. Its ACPI window <code>0x20..0xFF</code> mirrors memmap <code>0x00..0xDF</code>: temperature sensors <code>0x00..0x0f</code>/<code>0x18..0x1f</code> (raw − 73 °C), fans <code>0x10..0x17</code> (<code>0xffff</code> absent), switches <code>0x30</code> (lid/power button), and the battery block <code>0x40..0x7f</code> (AC/present/charging flags at <code>0x4c</code>, voltage/rate/remaining/design/last-full/cycle count, and the 8-byte strings). <code>EC_ACPI_MEM_BATTERY_INDEX</code> <code>0x12</code> selects the battery and waits for <code>BATT_INDEX</code> <code>0x4e</code>; <code>EC_ACPI_MEM_STRINGS_FIFO</code> <code>0x16</code> returns longer strings when supported. The Cyan full-charge workaround is applied, and the units are mAh/mA. <span class="file">power_src.c</span> picks the ThinkPad backend first, then the Chrome EC; <code>SYS_CROS_EC_SENSORS</code> (107) exposes the EC temperature/fan/switch snapshot.</li>
 			<li><strong>MTRRs.</strong> <span class="file">mtrr.c</span> manages write-combining ranges for the framebuffer and reports the effective mapping.</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>
 		</ul>
 		<p>
 		<p>
 			<code>sensors</code> prints DTS values on the 90/100/125 °C scales,
 			<code>sensors</code> prints DTS values on the 90/100/125 °C scales,
-			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 AC adapter state and the first
-			present battery with a valid percentage next to the CPU
-			temperature; machines without the EC show neither.
+			board sensors and both EC types; <code>powerinfo</code> prints the
+			source (<code>thinkpad</code> or <code>chrome ec</code>), the AC
+			adapter, battery model/manufacturer/serial, capacities, voltage,
+			rate and cycle count through <code>SYS_POWER_INFO</code>;
+			<code>power</code> prints ratios, effective MHz and C-state hints.
+			The WM top bar shows the AC adapter state and the first present
+			battery with a valid percentage next to the CPU temperature on
+			both ThinkPads and Chromebooks; machines without an EC show neither.
 		</p>
 		</p>
 	</section>
 	</section>
 
 
@@ -419,6 +422,8 @@
 			<li><strong>HID.</strong> Report IDs are not handled, absolute pointers/tablets are ignored, and there is no wheel support.</li>
 			<li><strong>HID.</strong> Report IDs are not handled, absolute pointers/tablets are ignored, and there is no wheel support.</li>
 			<li><strong>AHCI.</strong> First controller only, no hotplug after boot, disks above 2 TB are clamped to 32-bit LBA.</li>
 			<li><strong>AHCI.</strong> First controller only, no hotplug after boot, disks above 2 TB are clamped to 32-bit LBA.</li>
 			<li><strong>Storage serialization.</strong> A FAT/floppy operation sets <code>sys_fs_busy</code> and stalls process switching for its duration; the PIT keeps ticking.</li>
 			<li><strong>Storage serialization.</strong> A FAT/floppy operation sets <code>sys_fs_busy</code> and stalls process switching for its duration; the PIT keeps ticking.</li>
+			<li><strong>EC.</strong> The Chrome EC path uses the ACPI v2 memmap only: no MEC host-command interface, EC SCI events, charger current/voltage, charging limit or EC firmware version. The ThinkPad H8 path is limited to its page-selected battery window and has no SCI handler. Battery/AC is polled by the WM once a second.</li>
+			<li><strong>Suspend.</strong> There is no S0ix/suspend path; package C-states and the EC sleep handshake remain firmware-managed.</li>
 		</ul>
 		</ul>
 	</section>
 	</section>
 
 
@@ -435,7 +440,7 @@
 			<li><code>i2c.c</code>, <code>i2c.h</code> — DesignWare/LPSS I2C master</li>
 			<li><code>i2c.c</code>, <code>i2c.h</code> — DesignWare/LPSS I2C master</li>
 			<li><code>touchpad.c</code>, <code>touchpad.h</code> — Elan HID-over-I2C touchpad</li>
 			<li><code>touchpad.c</code>, <code>touchpad.h</code> — Elan HID-over-I2C touchpad</li>
 			<li><code>serial.c</code>, <code>serial_ring_buf.c</code></li>
 			<li><code>serial.c</code>, <code>serial_ring_buf.c</code></li>
-			<li><code>thermal.c</code>, <code>it87.c</code>, <code>tpec.c</code>, <code>mtrr.c</code></li>
+			<li><code>thermal.c</code>, <code>it87.c</code>, <code>tpec.c</code>, <code>ec.c</code>, <code>cros_ec.c</code>, <code>power_src.c</code>, <code>mtrr.c</code></li>
 			<li><code>rtc.c</code> — CMOS wall clock read/write</li>
 			<li><code>rtc.c</code> — CMOS wall clock read/write</li>
 			<li><code>panic.c</code>, <code>timer.S</code> — fatal exceptions</li>
 			<li><code>panic.c</code>, <code>timer.S</code> — fatal exceptions</li>
 		</ul>
 		</ul>

+ 1 - 1
docs/index.html

@@ -202,7 +202,7 @@
 			</a>
 			</a>
 			<a class="card" href="drivers.html">
 			<a class="card" href="drivers.html">
 				<h3>Drivers &amp; buses</h3>
 				<h3>Drivers &amp; buses</h3>
-				<p>PCI enumeration, FDC/PATA/SATA, the USB core and four host controllers, HID, the I2C touchpad, serial and board sensors.</p>
+				<p>PCI enumeration, FDC/PATA/SATA, the USB core and four host controllers, HID, the I2C touchpad, serial, board sensors and the ThinkPad/Chrome EC power sources.</p>
 				<span class="card-tag">drivers.html</span>
 				<span class="card-tag">drivers.html</span>
 			</a>
 			</a>
 			<a class="card" href="filesystems.html">
 			<a class="card" href="filesystems.html">

+ 1 - 1
docs/userland.html

@@ -221,7 +221,7 @@
 				<tbody>
 				<tbody>
 					<tr><td>Console &amp; time</td><td>1–4, 56, 69, 104–105</td><td>putstr, ticks, sleep, exit, RTC time/date get/set</td></tr>
 					<tr><td>Console &amp; time</td><td>1–4, 56, 69, 104–105</td><td>putstr, ticks, sleep, exit, RTC time/date get/set</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>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–103</td><td>memory, E820, mouse, storage, blkdev, procinfo, cursor, CPU temp, sensors, EC sensors, AC/battery</td></tr>
+					<tr><td>System info</td><td>12–16, 49–51, 91–92, 102–103, 107</td><td>memory, E820, mouse, storage, blkdev, procinfo, cursor, CPU temp, sensors, EC sensors, Chrome EC sensors, AC/battery</td></tr>
 					<tr><td>Network</td><td>17–47, 106</td><td>NIC config/acquire, raw frames, DHCP/DNS/NTP, TCP client, ARP, cwd</td></tr>
 					<tr><td>Network</td><td>17–47, 106</td><td>NIC config/acquire, raw frames, DHCP/DNS/NTP, 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>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>
 					<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>

+ 92 - 0
ec.c

@@ -0,0 +1,92 @@
+/* ACPI embedded-controller access; see ec.h. */
+#include "ec.h"
+#include "pci.h"
+
+#define EC_DATA 0x62
+#define EC_STS  0x66
+
+#define EC_OBF  0x01   /* output buffer full */
+#define EC_IBF  0x02   /* input buffer full */
+#define EC_READ 0x80
+#define EC_WRITE 0x81
+
+/* 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
+
+static int ec_wait(unsigned char mask, int set)
+{
+	unsigned int i;
+
+	for (i = 0; i < EC_POLL_MAX; i++) {
+		unsigned char st = port_inb(EC_STS);
+
+		if (st == 0xFF)           /* no controller on these ports */
+			return -1;
+		if (set ? (st & mask) != 0 : (st & mask) == 0)
+			return 0;
+	}
+	return -1;
+}
+
+/* Keep a stale output byte (a hotkey event) from shadowing the register we
+ * are about to read. */
+static int ec_drain(void)
+{
+	unsigned int i;
+
+	for (i = 0; i < 64; i++) {
+		unsigned char st = port_inb(EC_STS);
+
+		if (st == 0xFF)
+			return -1;
+		if (!(st & EC_OBF))
+			return 0;
+		(void)port_inb(EC_DATA);
+	}
+	return -1;
+}
+
+int ec_read(unsigned char reg, unsigned char *out)
+{
+	if (ec_drain())
+		return -1;
+	if (ec_wait(EC_IBF, 0))
+		return -1;
+	port_outb(EC_STS, EC_READ);
+	if (ec_wait(EC_IBF, 0))
+		return -1;
+	port_outb(EC_DATA, reg);
+	if (ec_wait(EC_OBF, 1))
+		return -1;
+	*out = port_inb(EC_DATA);
+	return 0;
+}
+
+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;
+}
+
+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;
+}

+ 28 - 0
ec.h

@@ -0,0 +1,28 @@
+/* ACPI embedded-controller access (ports 0x62/0x66).
+ *
+ * The kernel has no ACPI interpreter, but the standard EC command interface
+ * is simple enough to drive directly.  Both the ThinkPad H8 (tpec.c) and the
+ * Chrome OS EC (cros_ec.c) sit behind the same protocol:
+ *
+ *   0x80 read:  command 0x80, register index, read the data byte
+ *   0x81 write: command 0x81, register index, value
+ *
+ * The status port carries IBF (input buffer full) and OBF (output buffer
+ * full).  A pending output byte (an EC event) is drained before each command,
+ * and every wait is bounded so a dead controller cannot stall the kernel.
+ */
+#ifndef EC_H
+#define EC_H
+
+/* Read one EC RAM byte.  Returns 0 on success, -1 when the EC did not
+ * answer (no controller, timeout, or a stale output byte that never
+ * cleared). */
+int ec_read(unsigned char reg, unsigned char *out);
+
+/* Write one EC RAM byte (ACPI "write EC RAM", command 0x81). */
+int ec_write(unsigned char reg, unsigned char val);
+
+/* Read a little-endian 16-bit value from two consecutive EC registers. */
+int ec_read16(unsigned char reg, unsigned int *out);
+
+#endif

+ 9 - 7
idle.c

@@ -1,14 +1,16 @@
-/* CPU idle: automatic deep C-states on Nehalem/Westmere, HLT elsewhere.
+/* CPU idle: automatic deep C-states on Nehalem/Westmere and Airmont/Braswell,
+ * HLT elsewhere.
  *
  *
  * The default is IDLE_AUTO, which asks power.c for the MWAIT hint of the
  * The default is IDLE_AUTO, which asks power.c for the MWAIT hint of the
- * CPU: C6 (0x20) on the Arrandale/Nehalem family, and -1 (HLT) on the
- * Atom, where the old USB-legacy SMM hang made deep states risky.  The
- * explicit c1e/c3/c6 modes remain for testing; the c3ap/c6ap variants only
- * apply to the APs.
+ * CPU: C6 (0x20) on the Arrandale/Nehalem family, C6N (0x58) on Braswell,
+ * and -1 (HLT) on the older Atom, where the old USB-legacy SMM hang made
+ * deep states risky.  The explicit c1e/c3/c6 modes remain for testing; the
+ * c3ap/c6ap variants only apply to the APs.
  *
  *
  * Arrandale MWAIT state hints (coreboot model_2065x): C1 0x00, C1E 0x01,
  * Arrandale MWAIT state hints (coreboot model_2065x): C1 0x00, C1E 0x01,
- * C3 0x10, C6 0x20.  The MWAIT ECX bit 0 (interrupts break the state) is
- * set so a wake-up never waits for the full hint duration.
+ * C3 0x10, C6 0x20.  Airmont uses the Cherry Trail C6N hint 0x58.  The
+ * MWAIT ECX bit 0 (interrupts break the state) is set so a wake-up never
+ * waits for the full hint duration.
  */
  */
 #include "idle.h"
 #include "idle.h"
 #include "power.h"
 #include "power.h"

+ 7 - 2
kernel.c

@@ -5,6 +5,7 @@
 #include "bootcon.h"
 #include "bootcon.h"
 #include "bootinfo.h"
 #include "bootinfo.h"
 #include "cpu.h"
 #include "cpu.h"
+#include "cros_ec.h"
 #include "idle.h"
 #include "idle.h"
 #include "io.h"
 #include "io.h"
 #include "lapic.h"
 #include "lapic.h"
@@ -412,11 +413,15 @@ void kernel_main(void)
 	 * the power module (deep MWAIT on Nehalem, HLT elsewhere). */
 	 * the power module (deep MWAIT on Nehalem, HLT elsewhere). */
 	power_init();
 	power_init();
 	idle_init();
 	idle_init();
+	boot_trace("power");
 	thermal_init();
 	thermal_init();
+	boot_trace("thermal");
 	/* Board sensors: the ThinkPad EC probe is gated on SMBIOS identifying a
 	/* Board sensors: the ThinkPad EC probe is gated on SMBIOS identifying a
-	 * Lenovo/IBM machine, so it is a no-op everywhere else. */
+	 * Lenovo/IBM machine, so it is a no-op everywhere else.  The Chrome EC
+	 * probe is skipped when the ThinkPad EC was found. */
 	tpec_init();
 	tpec_init();
-	boot_trace("idle");
+	cros_ec_init();
+	boot_trace("ec");
 
 
 	/* process_init must run before timer_init: once the PIT is started (sti
 	/* process_init must run before timer_init: once the PIT is started (sti
 	 * in timer_init) the context-switch stub runs on every tick and reads
 	 * in timer_init) the context-switch stub runs on every tick and reads

+ 416 - 31
power.c

@@ -1,22 +1,25 @@
-/* Intel Nehalem/Westmere power management: P-states and deep C-states.
+/* Intel P-state and deep C-state management.
  *
  *
- * The kernel has no ACPI interpreter and no cpufreq driver, so the CPU used
- * to stay at whatever P-state the BIOS left (the maximum non-turbo ratio)
- * and only ever reached C1 (HLT).  An idle X201 therefore ran at 2.4 GHz
- * with all four threads in C1, which kept the package near 65 C and the EC
- * fan around 3700 RPM.
+ * Nehalem/Westmere (the X201) get the full race-to-idle P-state governor:
+ * the module writes IA32_PERF_CTL (lowest ratio for idle CPUs, maximum
+ * non-turbo ratio for a CPU that is running something, linear in between for
+ * mixed windows) and idle.c uses C1E/C3/C6 MWAIT hints.
  *
  *
- * This module adds the two things the hardware needs from the OS:
- *  - a small race-to-idle P-state governor writing IA32_PERF_CTL (lowest
- *    ratio for idle CPUs, maximum non-turbo ratio for a CPU that is running
- *    something, linear in between for mixed windows), and
- *  - deep C-state hints for idle.c (C1E/C3/C6 through MONITOR/MWAIT).
+ * Braswell/Airmont (the HP Chromebook, family 6 model 0x4C) reads the Atom
+ * ratio/VID MSRs and MSR_FSB_FREQ, writes IA32_PERF_CTL with the pstate in
+ * 15:8 and the Linux-interpolated VID in 7:0, and runs the same race-to-idle
+ * governor.  It enters at the maximum non-turbo pstate (pstate 20 = 1600 MHz
+ * on the N3060) and drops to pstate 6 (480 MHz) when idle; the turbo pstate
+ * is detected but not requested.  The package/power-SKU and auto-demotion
+ * MSRs are deliberately not touched (coreboot configures them, and an
+ * unsupported rdmsr before the IDT exists triple-faults).  APERF/MPERF are
+ * used only when CPUID.06H:ECX[0] says they exist.
  *
  *
- * Everything is gated on the Nehalem/Westmere model list: those are the
- * parts known to implement the MSRs used here, and the Atom boards keep
- * their old HLT behaviour.  The module only touches documented MSRs.
+ * The module only touches documented MSRs and is gated on the model list;
+ * unknown CPUs keep the old HLT behaviour.
  */
  */
 #include "power.h"
 #include "power.h"
+#include "bootcon.h"
 #include "cpu.h"
 #include "cpu.h"
 #include "idle.h"
 #include "idle.h"
 #include "io.h"
 #include "io.h"
@@ -26,6 +29,7 @@
 #define MSR_IA32_PERF_STATUS   0x198
 #define MSR_IA32_PERF_STATUS   0x198
 #define MSR_IA32_PERF_CTL      0x199
 #define MSR_IA32_PERF_CTL      0x199
 #define MSR_PLATFORM_INFO      0x0CE
 #define MSR_PLATFORM_INFO      0x0CE
+#define MSR_FSB_FREQ           0x0CD
 #define MSR_MISC_ENABLE        0x1A0
 #define MSR_MISC_ENABLE        0x1A0
 #define MSR_MISC_PWR_MGMT      0x1AA
 #define MSR_MISC_PWR_MGMT      0x1AA
 #define MSR_POWER_CTL          0x1FC
 #define MSR_POWER_CTL          0x1FC
@@ -37,10 +41,20 @@
 #define MSR_APERF              0x0E8
 #define MSR_APERF              0x0E8
 #define MSR_MPERF              0x0E7
 #define MSR_MPERF              0x0E7
 #define MSR_TSC                0x010
 #define MSR_TSC                0x010
+#define MSR_ATOM_CORE_RATIOS   0x66A
+#define MSR_ATOM_CORE_VIDS     0x66B
+#define MSR_ATOM_CORE_TURBO_RATIOS 0x66C
+#define MSR_ATOM_CORE_TURBO_VIDS   0x66D
 
 
 /* P-state ratios are the bus-ratio multipliers (133.33 MHz on Arrandale). */
 /* P-state ratios are the bus-ratio multipliers (133.33 MHz on Arrandale). */
 #define BCLK_MHZ 133u
 #define BCLK_MHZ 133u
 
 
+#define PLAT_NEHALEM 1
+#define PLAT_AIRMONT 2
+
+/* Airmont MWAIT C6N hint from Linux's intel_idle cht_cstates table. */
+#define MWAIT_C6N 0x58
+
 struct power_cpu {
 struct power_cpu {
 	/* Governor state (100 ms windows). */
 	/* Governor state (100 ms windows). */
 	unsigned int div;              /* ms in this window */
 	unsigned int div;              /* ms in this window */
@@ -60,8 +74,11 @@ struct power_cpu {
 
 
 static struct power_cpu pcs[MAX_CPUS];
 static struct power_cpu pcs[MAX_CPUS];
 
 
+static int platform;
+static int pstate_writes;
 static int supported;
 static int supported;
 static int has_arat;
 static int has_arat;
+static int has_aperf;
 static int eist_on;
 static int eist_on;
 static int turbo_disabled;
 static int turbo_disabled;
 static int c1e_on;
 static int c1e_on;
@@ -77,6 +94,18 @@ static unsigned long long pkg_c3_last, pkg_c6_last;
 static unsigned int pkg_pc3, pkg_pc6;
 static unsigned int pkg_pc3, pkg_pc6;
 static int pkg_have_last;
 static int pkg_have_last;
 
 
+/* Airmont probe values (kept for the `power` output and the follow-up that
+ * enables the governor). */
+static unsigned int fsb_khz;
+static unsigned int turbo_ratio;
+static unsigned int turbo_vid;
+static unsigned int atom_vid_min;
+static unsigned int atom_vid_max;
+static int atom_vid_valid;
+static unsigned int c6n_ok;
+static int c6n_enabled;
+static unsigned int plat_info_lo, plat_info_hi;
+
 static void cpuid_leaf(unsigned int leaf, unsigned int *a, unsigned int *b,
 static void cpuid_leaf(unsigned int leaf, unsigned int *a, unsigned int *b,
 		       unsigned int *c, unsigned int *d)
 		       unsigned int *c, unsigned int *d)
 {
 {
@@ -103,9 +132,10 @@ static unsigned long long rdmsr64(unsigned int msr)
 	return ((unsigned long long)hi << 32) | lo;
 	return ((unsigned long long)hi << 32) | lo;
 }
 }
 
 
-/* Model allowlist: the Nehalem/Westmere family that implements the MSRs
- * above.  Bonnell (0x1C/0x1D) is deliberately absent. */
-static int power_model(unsigned int model)
+/* Model allowlist.  Nehalem/Westmere implement the P-state/C-state MSRs
+ * used here; Braswell is Airmont family 6 model 0x4C.  Bonnell
+ * (0x1C/0x1D) is deliberately absent. */
+static int power_platform(unsigned int model)
 {
 {
 	switch (model) {
 	switch (model) {
 	case 0x1A:   /* Nehalem */
 	case 0x1A:   /* Nehalem */
@@ -115,15 +145,38 @@ static int power_model(unsigned int model)
 	case 0x2C:   /* Westmere-EP */
 	case 0x2C:   /* Westmere-EP */
 	case 0x2E:   /* Nehalem-EX */
 	case 0x2E:   /* Nehalem-EX */
 	case 0x2F:   /* Westmere-EX */
 	case 0x2F:   /* Westmere-EX */
-		return 1;
+		return PLAT_NEHALEM;
+	case 0x4C:   /* Airmont: Braswell / Cherry Trail */
+		return PLAT_AIRMONT;
 	default:
 	default:
 		return 0;
 		return 0;
 	}
 	}
 }
 }
 
 
+/* Airmont P-state VID for a target pstate.  Linux intel_pstate interpolates
+ * linearly between the min/max VID from MSR_ATOM_CORE_VIDS; the P-unit uses
+ * the low byte of IA32_PERF_CTL together with the ratio in 15:8. */
+static unsigned int atom_vid_for(unsigned int ratio)
+{
+	unsigned int span = max_ratio - min_ratio;
+	unsigned int v;
+
+	if (!atom_vid_valid || !span)
+		return 0;
+	if (ratio <= min_ratio)
+		return atom_vid_min & 0x7F;
+	if (ratio >= max_ratio)
+		return atom_vid_max & 0x7F;
+	v = atom_vid_min +
+	    ((ratio - min_ratio) * (atom_vid_max - atom_vid_min) +
+	     span / 2) / span;
+	return v & 0x7F;
+}
+
 /* Write one target ratio.  Nehalem/Westmere use bits 15:8 of
 /* Write one target ratio.  Nehalem/Westmere use bits 15:8 of
  * IA32_PERF_CTL for the target ratio; the low byte is reserved and written
  * IA32_PERF_CTL for the target ratio; the low byte is reserved and written
- * as zero (coreboot does the same). */
+ * as zero (coreboot does the same).  Airmont takes the ratio in 15:8 and the
+ * interpolated VID in 7:0. */
 static void power_write_ratio(unsigned int ratio)
 static void power_write_ratio(unsigned int ratio)
 {
 {
 	unsigned int lo, hi;
 	unsigned int lo, hi;
@@ -133,7 +186,10 @@ static void power_write_ratio(unsigned int ratio)
 	if (ratio > max_ratio)
 	if (ratio > max_ratio)
 		ratio = max_ratio;
 		ratio = max_ratio;
 	rdmsr(MSR_IA32_PERF_CTL, &lo, &hi);
 	rdmsr(MSR_IA32_PERF_CTL, &lo, &hi);
-	if (ratio_shift) {
+	if (platform == PLAT_AIRMONT) {
+		lo = (lo & 0xFFFF0000u) | ((ratio & 0xFF) << 8) |
+		     atom_vid_for(ratio);
+	} else if (ratio_shift) {
 		/* Bits 15:8 carry the ratio and 7:0 are reserved (the old VID
 		/* Bits 15:8 carry the ratio and 7:0 are reserved (the old VID
 		 * slot); coreboot writes them as zero.  Keeping the BIOS VID
 		 * slot); coreboot writes them as zero.  Keeping the BIOS VID
 		 * byte here made the request silently ineffective. */
 		 * byte here made the request silently ineffective. */
@@ -156,6 +212,174 @@ static void power_apply(struct power_cpu *p, unsigned int ratio)
 	p->req = ratio;
 	p->req = ratio;
 }
 }
 
 
+/* Airmont FSB frequencies in kHz, SDM Table 35-10 (index in MSR_FSB_FREQ). */
+static unsigned int airmont_fsb(unsigned int index)
+{
+	static const unsigned int table[9] = {
+		83300, 100000, 133300, 116700, 80000,
+		93300, 90000, 88900, 87500
+	};
+
+	if (index >= sizeof(table) / sizeof(table[0]))
+		return 100000;
+	return table[index];
+}
+
+static void power_init_airmont(unsigned int max_leaf)
+{
+	unsigned int lo, hi, vlo, vhi, tlo, thi, slo, shi;
+	unsigned int misc_lo, misc_hi;
+	unsigned int idx, r, i;
+
+	bootcon_puts("power: airmont init\n");
+	rdmsr(MSR_PLATFORM_INFO, &plat_info_lo, &plat_info_hi);
+	rdmsr(MSR_ATOM_CORE_RATIOS, &lo, &hi);
+	min_ratio = (lo >> 8) & 0x7F;
+	max_ratio = (lo >> 16) & 0x7F;
+
+	/* If the Atom-specific MSR is not populated, fall back to the
+	 * architectural PLATFORM_INFO fields. */
+	if (max_ratio < 5 || max_ratio > 60 || min_ratio < 3 ||
+	    min_ratio > max_ratio) {
+		max_ratio = (plat_info_lo >> 8) & 0xFF;
+		min_ratio = (plat_info_hi >> 8) & 0xFF;
+	}
+	if (max_ratio < 5 || max_ratio > 60 || min_ratio < 3 ||
+	    min_ratio > max_ratio) {
+		serial_puts(SERIAL_COM1,
+			    "power: implausible Atom ratios, disabled\n");
+		return;
+	}
+	bootcon_puts("power: ratios ok\n");
+
+	rdmsr(MSR_FSB_FREQ, &lo, &hi);
+	idx = lo & 0xF;
+	fsb_khz = airmont_fsb(idx);
+	nominal_mhz = (max_ratio * fsb_khz + 500) / 1000;
+	if (!nominal_mhz) {
+		serial_puts(SERIAL_COM1, "power: zero nominal frequency, disabled\n");
+		return;
+	}
+
+	rdmsr(MSR_ATOM_CORE_VIDS, &vlo, &vhi);
+	atom_vid_min = (vlo >> 8) & 0x7F;
+	atom_vid_max = (vlo >> 16) & 0x7F;
+	atom_vid_valid = (max_ratio > min_ratio &&
+			  atom_vid_min <= atom_vid_max);
+
+	rdmsr(MSR_ATOM_CORE_TURBO_RATIOS, &tlo, &thi);
+	turbo_ratio = tlo & 0x7F;
+	rdmsr(MSR_ATOM_CORE_TURBO_VIDS, &slo, &shi);
+	turbo_vid = slo & 0x7F;
+
+	rdmsr(MSR_MISC_ENABLE, &misc_lo, &misc_hi);
+	eist_on = (misc_lo >> 16) & 1;
+	turbo_disabled = (misc_hi >> 6) & 1;
+
+	rdmsr(MSR_IA32_PERF_STATUS, &lo, &hi);
+	r = (lo >> 8) & 0xFF;
+	if (r >= min_ratio && r <= max_ratio) {
+		pcs[0].ratio = r;
+		pcs[0].req = r;
+	} else {
+		pcs[0].ratio = max_ratio;
+		pcs[0].req = max_ratio;
+	}
+	pcs[0].status = lo & 0xFFFF;
+	bootcon_puts("power: msrs ok\n");
+
+	has_arat = 0;
+	c6n_ok = 0;
+	if (max_leaf >= 5) {
+		unsigned int a, b, c, d;
+
+		cpuid_leaf(5, &a, &b, &c, &d);
+		c6n_ok = ((d >> 24) & 0xF) ? 1 : 0;
+	}
+	if (max_leaf >= 6) {
+		unsigned int a, b, c, d;
+
+		cpuid_leaf(6, &a, &b, &c, &d);
+		has_arat = (a & 4u) ? 1 : 0;
+		has_aperf = (c & 1u) ? 1 : 0;
+	}
+
+	c1e_on = 0;
+	cst_limit = 0;
+	cst_locked = 0;
+	pkg_have_last = 0;
+	/* The governor starts in auto: enter at max non-turbo, then drop to
+	 * pstate 6 after the first idle window.  C6N is enabled when CPUID
+	 * advertises the C6 substates. */
+	cpufreq_mode = POWER_CPUFREQ_AUTO;
+	supported = 1;
+	pstate_writes = 1;
+	for (i = 0; i < MAX_CPUS; i++) {
+		pcs[i].req = 0;
+		pcs[i].ratio = max_ratio;
+	}
+	c6n_enabled = c6n_ok ? 1 : 0;
+
+	if (has_aperf) {
+		pcs[0].aperf = rdmsr64(MSR_APERF);
+		pcs[0].mperf = rdmsr64(MSR_MPERF);
+	}
+	pcs[0].have_last = 1;
+	bootcon_puts("power: apis ok\n");
+
+	/* Enter at the maximum non-turbo pstate; the race-to-idle governor
+	 * drops to the minimum after the first idle window. */
+	pcs[0].req = max_ratio;
+	power_write_ratio(max_ratio);
+	bootcon_puts("power: pstate writes enabled\n");
+	if (c6n_enabled)
+		bootcon_puts("power: c6n enabled\n");
+
+	serial_puts(SERIAL_COM1,
+		    "power: Airmont/Braswell, P-states auto");
+	if (c6n_enabled)
+		serial_puts(SERIAL_COM1, ", C6N enabled");
+	else
+		serial_puts(SERIAL_COM1, ", C6N disabled");
+	serial_puts(SERIAL_COM1, "\n");
+	serial_puts(SERIAL_COM1, "power: pstates ");
+	serial_putdec(SERIAL_COM1, min_ratio);
+	serial_puts(SERIAL_COM1, "..");
+	serial_putdec(SERIAL_COM1, max_ratio);
+	serial_puts(SERIAL_COM1, ", fsb ");
+	serial_putdec(SERIAL_COM1, fsb_khz);
+	serial_puts(SERIAL_COM1, " kHz, nominal ");
+	serial_putdec(SERIAL_COM1, nominal_mhz);
+	serial_puts(SERIAL_COM1, " MHz, vid ");
+	serial_puthex(SERIAL_COM1, atom_vid_min);
+	serial_puts(SERIAL_COM1, "..");
+	serial_puthex(SERIAL_COM1, atom_vid_max);
+	serial_puts(SERIAL_COM1, atom_vid_valid ? "" : " (invalid)");
+	serial_puts(SERIAL_COM1, "\npower: turbo p");
+	serial_putdec(SERIAL_COM1, turbo_ratio);
+	serial_puts(SERIAL_COM1, " vid ");
+	serial_puthex(SERIAL_COM1, turbo_vid);
+	serial_puts(SERIAL_COM1, ", eist ");
+	serial_puts(SERIAL_COM1, eist_on ? "on" : "off");
+	serial_puts(SERIAL_COM1, ", turbo ");
+	serial_puts(SERIAL_COM1, turbo_disabled ? "disabled" : "enabled");
+	serial_puts(SERIAL_COM1, ", arat ");
+	serial_puts(SERIAL_COM1, has_arat ? "yes" : "no");
+	serial_puts(SERIAL_COM1, ", c6n ");
+	serial_puts(SERIAL_COM1, c6n_ok ? "yes" : "no");
+	serial_puts(SERIAL_COM1, "\npower: platform info ");
+	serial_puthex(SERIAL_COM1, plat_info_hi);
+	serial_puthex(SERIAL_COM1, plat_info_lo);
+	serial_puts(SERIAL_COM1, ", perf status ");
+	serial_puthex(SERIAL_COM1, pcs[0].status);
+	serial_puts(SERIAL_COM1, ", perf ctl ");
+	rdmsr(MSR_IA32_PERF_CTL, &lo, &hi);
+	serial_puthex(SERIAL_COM1, lo);
+	serial_puts(SERIAL_COM1, "\npower: misc enable ");
+	serial_puthex(SERIAL_COM1, misc_lo);
+	serial_puts(SERIAL_COM1, "\n");
+}
+
 void power_init(void)
 void power_init(void)
 {
 {
 	unsigned int max_leaf, a, b, c, d;
 	unsigned int max_leaf, a, b, c, d;
@@ -163,8 +387,35 @@ void power_init(void)
 	unsigned int lo, hi;
 	unsigned int lo, hi;
 
 
 	supported = 0;
 	supported = 0;
+	pstate_writes = 0;
+	platform = 0;
 	has_arat = 0;
 	has_arat = 0;
+	has_aperf = 0;
+	eist_on = 0;
+	turbo_disabled = 0;
+	c1e_on = 0;
+	cst_limit = 0;
+	cst_locked = 0;
+	min_ratio = 6;
+	max_ratio = 0;
+	ratio_shift = 0;
+	nominal_mhz = 0;
 	cpufreq_mode = POWER_CPUFREQ_AUTO;
 	cpufreq_mode = POWER_CPUFREQ_AUTO;
+	fixed_ratio = 0;
+	fsb_khz = 0;
+	turbo_ratio = 0;
+	turbo_vid = 0;
+	atom_vid_min = 0;
+	atom_vid_max = 0;
+	atom_vid_valid = 0;
+	c6n_ok = 0;
+	c6n_enabled = 0;
+	plat_info_lo = 0;
+	plat_info_hi = 0;
+	pkg_have_last = 0;
+	pkg_pc3 = 0;
+	pkg_pc6 = 0;
+
 	if (!cpu_has_cpuid()) {
 	if (!cpu_has_cpuid()) {
 		serial_puts(SERIAL_COM1, "power: no CPUID, disabled\n");
 		serial_puts(SERIAL_COM1, "power: no CPUID, disabled\n");
 		return;
 		return;
@@ -182,12 +433,18 @@ void power_init(void)
 		family += (a >> 20) & 0xFF;
 		family += (a >> 20) & 0xFF;
 	if (family == 0x6 || family == 0xF)
 	if (family == 0x6 || family == 0xF)
 		model += ((a >> 16) & 0xF) << 4;
 		model += ((a >> 16) & 0xF) << 4;
-	if (family != 0x6 || !power_model(model)) {
+	platform = (family == 0x6) ? power_platform(model) : 0;
+	if (!platform) {
 		serial_puts(SERIAL_COM1, "power: CPU family ");
 		serial_puts(SERIAL_COM1, "power: CPU family ");
 		serial_putdec(SERIAL_COM1, family);
 		serial_putdec(SERIAL_COM1, family);
 		serial_puts(SERIAL_COM1, " model ");
 		serial_puts(SERIAL_COM1, " model ");
 		serial_putdec(SERIAL_COM1, model);
 		serial_putdec(SERIAL_COM1, model);
-		serial_puts(SERIAL_COM1, ", no Nehalem/Westmere PM\n");
+		serial_puts(SERIAL_COM1, ", no supported PM\n");
+		return;
+	}
+
+	if (platform == PLAT_AIRMONT) {
+		power_init_airmont(max_leaf);
 		return;
 		return;
 	}
 	}
 
 
@@ -239,6 +496,8 @@ void power_init(void)
 
 
 	rdmsr(MSR_MISC_PWR_MGMT, &lo, &hi);
 	rdmsr(MSR_MISC_PWR_MGMT, &lo, &hi);
 	supported = 1;
 	supported = 1;
+	pstate_writes = 1;
+	has_aperf = 1;
 
 
 	/* Start at the maximum non-turbo ratio; the governor drops to the
 	/* Start at the maximum non-turbo ratio; the governor drops to the
 	 * minimum after the first idle window. */
 	 * minimum after the first idle window. */
@@ -292,6 +551,17 @@ int power_idle_hint(void)
 {
 {
 	if (!supported)
 	if (!supported)
 		return -1;
 		return -1;
+	if (platform == PLAT_AIRMONT) {
+		/* C6N is reported by CPUID, but the hint stays disabled
+		 * until the read-only probe has booted cleanly on target. */
+		if (!c6n_enabled || !c6n_ok)
+			return -1;
+		/* An AP without ARAT may lose its local APIC timer, so it
+		 * falls back to HLT (C1). */
+		if (this_cpu()->id != 0 && !has_arat)
+			return -1;
+		return MWAIT_C6N;
+	}
 	/* An AP can only use C3/C6 when its local APIC timer keeps running
 	/* An AP can only use C3/C6 when its local APIC timer keeps running
 	 * there (ARAT); otherwise C1E is the deepest safe state and the BSP
 	 * there (ARAT); otherwise C1E is the deepest safe state and the BSP
 	 * PIT still wakes it up via IPIs. */
 	 * PIT still wakes it up via IPIs. */
@@ -311,7 +581,7 @@ void power_tick(int idle, unsigned int ms)
 	p = &pcs[c->id];
 	p = &pcs[c->id];
 
 
 	/* ---- P-state governor (100 ms windows) ---- */
 	/* ---- P-state governor (100 ms windows) ---- */
-	if (cpufreq_mode == POWER_CPUFREQ_AUTO) {
+	if (pstate_writes && cpufreq_mode == POWER_CPUFREQ_AUTO) {
 		if (idle) {
 		if (idle) {
 			p->streak_ms = 0;
 			p->streak_ms = 0;
 		} else {
 		} else {
@@ -338,7 +608,7 @@ void power_tick(int idle, unsigned int ms)
 				    (max_ratio - min_ratio) * load / 100u;
 				    (max_ratio - min_ratio) * load / 100u;
 			power_apply(p, r);
 			power_apply(p, r);
 		}
 		}
-	} else if (cpufreq_mode != POWER_CPUFREQ_OFF) {
+	} else if (pstate_writes && cpufreq_mode != POWER_CPUFREQ_OFF) {
 		if (cpufreq_mode == POWER_CPUFREQ_MIN)
 		if (cpufreq_mode == POWER_CPUFREQ_MIN)
 			r = min_ratio;
 			r = min_ratio;
 		else if (cpufreq_mode == POWER_CPUFREQ_MAX)
 		else if (cpufreq_mode == POWER_CPUFREQ_MAX)
@@ -348,11 +618,49 @@ void power_tick(int idle, unsigned int ms)
 		power_apply(p, r);
 		power_apply(p, r);
 	}
 	}
 
 
-	/* ---- once-a-second residency/clock statistics ---- */
+	/* ---- once-a-second clock statistics ---- */
 	p->stat_div += ms;
 	p->stat_div += ms;
 	if (p->stat_div < 1000)
 	if (p->stat_div < 1000)
 		return;
 		return;
 	p->stat_div = 0;
 	p->stat_div = 0;
+	if (platform == PLAT_AIRMONT) {
+		unsigned long long aperf, mperf;
+		unsigned int da, dm;
+
+		if (!has_aperf) {
+			/* The CLOCK_MODULATION/APERF capability is absent;
+			 * report the PERF_STATUS ratio only. */
+			rdmsr(MSR_IA32_PERF_STATUS, &da, &dm);
+			p->status = da & 0xFFFFu;
+			r = (p->status >> 8) & 0xFFu;
+			if (r >= min_ratio && r <= max_ratio)
+				p->ratio = r;
+			else
+				p->ratio = p->req;
+			return;
+		}
+		aperf = rdmsr64(MSR_APERF);
+		mperf = rdmsr64(MSR_MPERF);
+		if (!p->have_last) {
+			p->aperf = aperf;
+			p->mperf = mperf;
+			p->have_last = 1;
+			return;
+		}
+		da = (unsigned int)((aperf - p->aperf) >> 12);
+		dm = (unsigned int)((mperf - p->mperf) >> 12);
+		p->aperf = aperf;
+		p->mperf = mperf;
+		p->mhz = dm ? da * nominal_mhz / dm : 0;
+		rdmsr(MSR_IA32_PERF_STATUS, &da, &dm);
+		p->status = da & 0xFFFFu;
+		r = (p->status >> 8) & 0xFFu;
+		if (r >= min_ratio && r <= max_ratio)
+			p->ratio = r;
+		else
+			p->ratio = p->req;
+		return;
+	}
 	{
 	{
 		unsigned long long aperf = rdmsr64(MSR_APERF);
 		unsigned long long aperf = rdmsr64(MSR_APERF);
 		unsigned long long mperf = rdmsr64(MSR_MPERF);
 		unsigned long long mperf = rdmsr64(MSR_MPERF);
@@ -462,24 +770,93 @@ static void put_pct(unsigned int permille)
 void power_print(void)
 void power_print(void)
 {
 {
 	unsigned int i;
 	unsigned int i;
+	unsigned int lo, hi;
 
 
 	if (!supported) {
 	if (!supported) {
 		io_putstr("power: not available on this CPU\n");
 		io_putstr("power: not available on this CPU\n");
 		return;
 		return;
 	}
 	}
-	io_putstr("power: nehalem/westmere, idle ");
+	io_putstr("power: ");
+	io_putstr(platform == PLAT_AIRMONT ? "airmont/braswell" :
+					    "nehalem/westmere");
+	if (!pstate_writes)
+		io_putstr(" (probe only)");
+	io_putstr(", idle ");
 	io_putstr(idle_mode_name(idle_mode()));
 	io_putstr(idle_mode_name(idle_mode()));
+	if (platform == PLAT_AIRMONT)
+		io_putstr((c6n_enabled && idle_mwait_supported()) ?
+			  " (mwait c6n)" : " (hlt)");
 	io_putstr(", cpufreq ");
 	io_putstr(", cpufreq ");
-	io_putstr(power_cpufreq_name());
-	if (cpufreq_mode == POWER_CPUFREQ_FIXED) {
-		io_putchar(' ');
-		put_dec(fixed_ratio);
+	if (!pstate_writes)
+		io_putstr("probe");
+	else {
+		io_putstr(power_cpufreq_name());
+		if (cpufreq_mode == POWER_CPUFREQ_FIXED) {
+			io_putchar(' ');
+			put_dec(fixed_ratio);
+		}
 	}
 	}
-	io_putstr(" (ratios ");
+	io_putstr(" (pstates ");
 	put_dec(min_ratio);
 	put_dec(min_ratio);
 	io_putstr("..");
 	io_putstr("..");
 	put_dec(max_ratio);
 	put_dec(max_ratio);
 	io_putstr(")\n");
 	io_putstr(")\n");
+
+	if (platform == PLAT_AIRMONT) {
+		io_putstr("eist ");
+		io_putstr(eist_on ? "on" : "off");
+		io_putstr(", turbo ");
+		io_putstr(turbo_disabled ? "disabled" : "enabled");
+		io_putstr(", arat ");
+		io_putstr(has_arat ? "yes" : "no");
+		io_putstr(", c6n ");
+		if (!c6n_ok)
+			io_putstr("no");
+		else if (c6n_enabled)
+			io_putstr("yes");
+		else
+			io_putstr("yes (disabled)");
+		io_putstr("\nfsb ");
+		put_dec(fsb_khz);
+		io_putstr(" kHz, nominal ");
+		put_dec(nominal_mhz);
+		io_putstr(" MHz, turbo p");
+		put_dec(turbo_ratio);
+		io_putstr(" vid 0x");
+		io_puthex(turbo_vid);
+		io_putstr(", vid 0x");
+		io_puthex(atom_vid_min);
+		io_putstr("..0x");
+		io_puthex(atom_vid_max);
+		io_putstr(atom_vid_valid ? "" : " (invalid)");
+		rdmsr(MSR_IA32_PERF_CTL, &lo, &hi);
+		io_putstr(", perf ctl 0x");
+		io_puthex(lo);
+		io_putchar('\n');
+		for (i = 0; i < cpu_count && i < MAX_CPUS; i++) {
+			struct power_cpu *p = &pcs[i];
+
+			io_putstr("cpu");
+			put_dec(i);
+			io_putchar(' ');
+			put_dec(p->mhz);
+			io_putstr(" MHz  cur r");
+			if (p->ratio >= min_ratio && p->ratio <= max_ratio) {
+				if (p->ratio < 10)
+					io_putchar('0');
+				put_dec(p->ratio);
+			} else {
+				io_putstr("--");
+			}
+			io_putstr("  req r");
+			if (p->req < 10)
+				io_putchar('0');
+			put_dec(p->req);
+			io_putchar('\n');
+		}
+		return;
+	}
+
 	io_putstr("cst ");
 	io_putstr("cst ");
 	put_dec(cst_limit);
 	put_dec(cst_limit);
 	io_putstr(cst_locked ? " locked" : " unlocked");
 	io_putstr(cst_locked ? " locked" : " unlocked");
@@ -530,6 +907,14 @@ int power_cpufreq_command(const char *arg)
 		io_putstr("cpufreq: not available on this CPU\n");
 		io_putstr("cpufreq: not available on this CPU\n");
 		return -1;
 		return -1;
 	}
 	}
+	if (!pstate_writes) {
+		if (!*arg) {
+			io_putstr("cpufreq probe (P-state writes disabled)\n");
+			return 0;
+		}
+		io_putstr("cpufreq: P-state writes are disabled in this probe build\n");
+		return -1;
+	}
 	if (!*arg) {
 	if (!*arg) {
 		io_putstr("cpufreq ");
 		io_putstr("cpufreq ");
 		io_putstr(power_cpufreq_name());
 		io_putstr(power_cpufreq_name());

+ 8 - 5
power.h

@@ -1,4 +1,4 @@
-/* Intel Nehalem/Westmere P-state and deep C-state management. */
+/* Intel P-state and deep C-state management. */
 #ifndef POWER_H
 #ifndef POWER_H
 #define POWER_H
 #define POWER_H
 
 
@@ -8,16 +8,19 @@
 #define POWER_CPUFREQ_FIXED 3
 #define POWER_CPUFREQ_FIXED 3
 #define POWER_CPUFREQ_OFF   4
 #define POWER_CPUFREQ_OFF   4
 
 
-/* Probe the CPU and MSRs, enable SpeedStep/C1E/C6 and start at the maximum
- * non-turbo ratio.  Called once on the BSP before idle_init(); logs to COM1
- * and is a no-op on CPUs outside the Nehalem/Westmere allowlist. */
+/* Probe the CPU and MSRs.  Nehalem/Westmere and Airmont/Braswell run the
+ * race-to-idle P-state governor; Airmont uses the Linux Atom VID encoding
+ * (pstate in 15:8, interpolated VID in 7:0) and caps at max non-turbo.
+ * Called once on the BSP before idle_init(); logs to COM1 and is a no-op on
+ * CPUs outside the allowlist. */
 void power_init(void);
 void power_init(void);
 
 
 /* Once per scheduler tick with the CPU's idle flag and the tick length. */
 /* Once per scheduler tick with the CPU's idle flag and the tick length. */
 void power_tick(int idle, unsigned int ms);
 void power_tick(int idle, unsigned int ms);
 
 
 /* Deep C-state hint for idle.c's automatic mode: -1 = use HLT, otherwise
 /* Deep C-state hint for idle.c's automatic mode: -1 = use HLT, otherwise
- * the MWAIT hint (0x20 C6; 0x01 C1E on an AP whose local timer stops). */
+ * the MWAIT hint.  Airmont returns C6N (0x58), or -1 on an AP without ARAT;
+ * Nehalem returns C6 (0x20), or C1E on an AP whose local timer stops. */
 int power_idle_hint(void);
 int power_idle_hint(void);
 
 
 /* `power` / `cpufreq` command support (terminal.c). */
 /* `power` / `cpufreq` command support (terminal.c). */

+ 13 - 0
power_src.c

@@ -0,0 +1,13 @@
+/* AC/battery backend selection; see power_src.h. */
+#include "power_src.h"
+#include "cros_ec.h"
+#include "tpec.h"
+
+void power_source_read(struct power_info *out, int detail)
+{
+	if (tpec_present()) {
+		tpec_power_read(out, detail);
+		return;
+	}
+	cros_ec_power_read(out, detail);
+}

+ 56 - 0
power_src.h

@@ -0,0 +1,56 @@
+/* Shared AC/battery snapshot for the board embedded controllers.
+ *
+ * Two backends fill this: the ThinkPad H8 EC (tpec.c) and the Chrome OS EC
+ * (cros_ec.c).  sys_info.c copies it into struct sys_powerinfo for
+ * SYS_POWER_INFO, so the WM top bar and the powerinfo command do not need to
+ * know which laptop they are running on.
+ */
+#ifndef POWER_SRC_H
+#define POWER_SRC_H
+
+#include "syscall.h"
+
+#define POWER_BATT_MAX SYS_POWER_BATT_MAX
+
+/* One battery.  rate is the signed present rate in the unit selected by
+ * unit_mwh: mW when set, mA when clear.  Capacities use the matching
+ * mWh/mAh unit.  percent is valid only when percent_valid is set. */
+struct power_battery {
+	int present;
+	int error;                /* at least one EC read failed */
+	unsigned int status;      /* raw EC status/flags 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 */
+	unsigned int cycle_count;
+	char manufacturer[16];
+	char model[16];
+	char serial[16];
+};
+
+struct power_info {
+	int present;
+	int source;               /* SYS_POWER_SRC_* */
+	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 power_battery battery[POWER_BATT_MAX];
+};
+
+/* Fill out from the first available backend (ThinkPad EC, then Chrome EC).
+ * detail also reads design data and the manufacturer/model/serial strings;
+ * the periodic WM query passes 0. */
+void power_source_read(struct power_info *out, int detail);
+
+#endif

+ 36 - 5
sys_info.c

@@ -5,9 +5,11 @@
 #include "syscall.h"
 #include "syscall.h"
 #include "ahci.h"
 #include "ahci.h"
 #include "blkdev.h"
 #include "blkdev.h"
+#include "cros_ec.h"
 #include "it87.h"
 #include "it87.h"
 #include "mm.h"
 #include "mm.h"
 #include "mouse.h"
 #include "mouse.h"
+#include "power_src.h"
 #include "sched.h"
 #include "sched.h"
 #include "sys_fs.h"
 #include "sys_fs.h"
 #include "thermal.h"
 #include "thermal.h"
@@ -19,8 +21,12 @@
 
 
 _Static_assert(TPEC_TEMP_COUNT == SYS_TPEC_TEMP_MAX,
 _Static_assert(TPEC_TEMP_COUNT == SYS_TPEC_TEMP_MAX,
 	       "sys_tpec_sensors.temp_c and tpec_info.temp_c must match");
 	       "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_assert(POWER_BATT_MAX == SYS_POWER_BATT_MAX,
+	       "sys_powerinfo.battery and power_info.battery must match");
+_Static_assert(CROS_EC_TEMP_MAX == SYS_CROS_TEMP_MAX,
+	       "sys_cros_sensors.temp_c and cros_ec_sensors.temp_c must match");
+_Static_assert(CROS_EC_FAN_MAX == SYS_CROS_FAN_MAX,
+	       "sys_cros_sensors.fan_rpm and cros_ec_sensors.fan_rpm must match");
 
 
 static void copy_str(char *dst, const char *src, unsigned int size)
 static void copy_str(char *dst, const char *src, unsigned int size)
 {
 {
@@ -181,16 +187,17 @@ int sys_tpec_sensors(struct sys_tpec_sensors *out)
 
 
 int sys_powerinfo(struct sys_powerinfo *out, unsigned int flags)
 int sys_powerinfo(struct sys_powerinfo *out, unsigned int flags)
 {
 {
-	struct tpec_power p;
+	struct power_info p;
 	unsigned int i;
 	unsigned int i;
 
 
 	if (!out)
 	if (!out)
 		return -1;
 		return -1;
-	tpec_power_read(&p, (flags & SYS_POWER_F_DETAIL) != 0);
+	power_source_read(&p, (flags & SYS_POWER_F_DETAIL) != 0);
 
 
 	for (i = 0; i < sizeof(*out); i++)
 	for (i = 0; i < sizeof(*out); i++)
 		((unsigned char *)out)[i] = 0;
 		((unsigned char *)out)[i] = 0;
 	out->present = p.present ? 1u : 0u;
 	out->present = p.present ? 1u : 0u;
+	out->source = (unsigned int)p.source;
 	out->ac_online = p.ac_online;
 	out->ac_online = p.ac_online;
 	out->ec_rev = p.ec_rev;
 	out->ec_rev = p.ec_rev;
 	copy_str(out->vendor, p.vendor, sizeof(out->vendor));
 	copy_str(out->vendor, p.vendor, sizeof(out->vendor));
@@ -199,7 +206,7 @@ int sys_powerinfo(struct sys_powerinfo *out, unsigned int flags)
 	out->battery_count = p.battery_count;
 	out->battery_count = p.battery_count;
 	for (i = 0; i < SYS_POWER_BATT_MAX; i++) {
 	for (i = 0; i < SYS_POWER_BATT_MAX; i++) {
 		struct sys_battery *d = &out->battery[i];
 		struct sys_battery *d = &out->battery[i];
-		const struct tpec_battery *s = &p.battery[i];
+		const struct power_battery *s = &p.battery[i];
 
 
 		d->present = s->present ? 1u : 0u;
 		d->present = s->present ? 1u : 0u;
 		d->error = s->error ? 1u : 0u;
 		d->error = s->error ? 1u : 0u;
@@ -215,9 +222,33 @@ int sys_powerinfo(struct sys_powerinfo *out, unsigned int flags)
 		d->rate = s->rate;
 		d->rate = s->rate;
 		d->unit_known = s->unit_known ? 1u : 0u;
 		d->unit_known = s->unit_known ? 1u : 0u;
 		d->unit_mwh = s->unit_mwh ? 1u : 0u;
 		d->unit_mwh = s->unit_mwh ? 1u : 0u;
+		d->cycle_count = s->cycle_count;
 		copy_str(d->manufacturer, s->manufacturer,
 		copy_str(d->manufacturer, s->manufacturer,
 			 sizeof(d->manufacturer));
 			 sizeof(d->manufacturer));
 		copy_str(d->model, s->model, sizeof(d->model));
 		copy_str(d->model, s->model, sizeof(d->model));
+		copy_str(d->serial, s->serial, sizeof(d->serial));
 	}
 	}
 	return 0;
 	return 0;
 }
 }
+
+int sys_cros_sensors(struct sys_cros_sensors *out)
+{
+	struct cros_ec_sensors info;
+	unsigned int i;
+
+	if (!out)
+		return -1;
+	cros_ec_sensors_read(&info);
+	out->present = info.present ? 1u : 0u;
+	out->acpi_version = info.acpi_version;
+	out->battery_version = info.battery_version;
+	out->thermal_version = info.thermal_version;
+	for (i = 0; i < SYS_CROS_TEMP_MAX; i++)
+		out->temp_c[i] = info.temp_c[i];
+	for (i = 0; i < SYS_CROS_FAN_MAX; i++)
+		out->fan_rpm[i] = info.fan_rpm[i];
+	out->fan_present = info.fan_present;
+	out->fan_duty = info.fan_duty;
+	out->switches = info.switches;
+	return 0;
+}

+ 1 - 0
sys_info.h

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

+ 5 - 0
syscall.c

@@ -313,6 +313,11 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 					  sizeof(struct sys_tpec_sensors), 1))
 					  sizeof(struct sys_tpec_sensors), 1))
 			return -1;
 			return -1;
 		return sys_tpec_sensors((struct sys_tpec_sensors *)a1);
 		return sys_tpec_sensors((struct sys_tpec_sensors *)a1);
+	case SYS_CROS_EC_SENSORS:
+		if (!paging_user_range_ok(current_proc()->cr3, (unsigned int)a1,
+					  sizeof(struct sys_cros_sensors), 1))
+			return -1;
+		return sys_cros_sensors((struct sys_cros_sensors *)a1);
 	case SYS_POWER_INFO:
 	case SYS_POWER_INFO:
 		if (!paging_user_range_ok(current_proc()->cr3, (unsigned int)a1,
 		if (!paging_user_range_ok(current_proc()->cr3, (unsigned int)a1,
 					  sizeof(struct sys_powerinfo), 1))
 					  sizeof(struct sys_powerinfo), 1))

+ 36 - 7
syscall.h

@@ -146,11 +146,19 @@
 /* ThinkPad embedded-controller sensors (see tpec.c); read-only. */
 /* ThinkPad embedded-controller sensors (see tpec.c); read-only. */
 #define SYS_TPEC_SENSORS  102  /* (struct sys_tpec_sensors *out) -> 0/-1 */
 #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. */
+/* AC/battery snapshot from the board EC (see power_src.c, tpec.c and
+ * cros_ec.c).  SYS_POWER_F_DETAIL also reads design capacity, the capacity
+ * unit and the manufacturer/model/serial strings. */
 #define SYS_POWER_INFO     103  /* (struct sys_powerinfo *out, flags) -> 0/-1 */
 #define SYS_POWER_INFO     103  /* (struct sys_powerinfo *out, flags) -> 0/-1 */
 #define SYS_POWER_F_DETAIL 0x1
 #define SYS_POWER_F_DETAIL 0x1
 
 
+#define SYS_POWER_SRC_NONE 0
+#define SYS_POWER_SRC_TPEC 1   /* ThinkPad H8 EC */
+#define SYS_POWER_SRC_CROS 2   /* Chrome OS EC */
+
+/* Chrome OS EC temperature/fan/switch snapshot (see cros_ec.c). */
+#define SYS_CROS_EC_SENSORS 107  /* (struct sys_cros_sensors *out) -> 0/-1 */
+
 /* Stat one path (the file service has no open handle). */
 /* Stat one path (the file service has no open handle). */
 #define SYS_FS_STAT        98  /* (path, struct sys_stat *out) -> 0/<0 */
 #define SYS_FS_STAT        98  /* (path, struct sys_stat *out) -> 0/<0 */
 
 
@@ -293,14 +301,15 @@ struct sys_tpec_sensors {
 	unsigned int fan_level;
 	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. */
+/* 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.  cycle_count/serial are
+ * zero/empty when the backend does not provide them. */
 #define SYS_POWER_BATT_MAX 2
 #define SYS_POWER_BATT_MAX 2
 struct sys_battery {
 struct sys_battery {
 	unsigned int present;
 	unsigned int present;
 	unsigned int error;
 	unsigned int error;
-	unsigned int status;      /* raw EC 0x38/0x39 byte */
+	unsigned int status;      /* raw EC status/flags byte */
 	unsigned int charging;
 	unsigned int charging;
 	unsigned int discharging;
 	unsigned int discharging;
 	unsigned int percent;
 	unsigned int percent;
@@ -314,10 +323,13 @@ struct sys_battery {
 	unsigned int unit_mwh;
 	unsigned int unit_mwh;
 	char manufacturer[16];
 	char manufacturer[16];
 	char model[16];
 	char model[16];
+	unsigned int cycle_count;
+	char serial[16];
 };
 };
 
 
 struct sys_powerinfo {
 struct sys_powerinfo {
-	unsigned int present;     /* ThinkPad EC found */
+	unsigned int present;     /* a supported EC was found */
+	unsigned int source;      /* SYS_POWER_SRC_* */
 	int ac_online;            /* -1 unknown, 0 offline, 1 online */
 	int ac_online;            /* -1 unknown, 0 offline, 1 online */
 	unsigned int ec_rev;
 	unsigned int ec_rev;
 	char vendor[16];
 	char vendor[16];
@@ -327,6 +339,23 @@ struct sys_powerinfo {
 	struct sys_battery battery[SYS_POWER_BATT_MAX];
 	struct sys_battery battery[SYS_POWER_BATT_MAX];
 };
 };
 
 
+/* Chrome OS EC board sensors (see cros_ec.c).  temp_c[] is -128 when the
+ * sensor is absent/unavailable; fan_present is a bitmask over fan_rpm[].
+ * switches follows EC_MEMMAP_SWITCHES (bit 0 lid open, bit 1 power button). */
+#define SYS_CROS_TEMP_MAX 24
+#define SYS_CROS_FAN_MAX 4
+struct sys_cros_sensors {
+	unsigned int present;
+	unsigned int acpi_version;
+	unsigned int battery_version;
+	unsigned int thermal_version;
+	int temp_c[SYS_CROS_TEMP_MAX];
+	unsigned int fan_rpm[SYS_CROS_FAN_MAX];
+	unsigned int fan_present;
+	unsigned int fan_duty;     /* 0xff = automatic */
+	unsigned int switches;
+};
+
 /* Wall clock for the ring-3 clock (see rtc.c). */
 /* Wall clock for the ring-3 clock (see rtc.c). */
 struct sys_time {
 struct sys_time {
 	unsigned int hour;     /* 0-23 */
 	unsigned int hour;     /* 0-23 */

+ 7 - 3
thermal.c

@@ -4,9 +4,10 @@
  * below TjMax in bits 22:16.  Bonnell (Atom 230/330) has no
  * below TjMax in bits 22:16.  Bonnell (Atom 230/330) has no
  * IA32_TEMPERATURE_TARGET MSR, so TjMax has to come from a table; these are
  * IA32_TEMPERATURE_TARGET MSR, so TjMax has to come from a table; these are
  * the same values Linux's coretemp uses (the 330's DTS is calibrated against
  * the same values Linux's coretemp uses (the 330's DTS is calibrated against
- * 125 C, other Bonnell parts against 90 C).  Nehalem and later (including the
- * X201's Arrandale) publish TjMax in bits 23:16 of MSR 0x1A2, which is read
- * for the models that implement it; the table remains the fallback.  The DTS
+ * 125 C, other Bonnell parts against 90 C).  Nehalem and Westmere (including
+ * the X201's Arrandale) publish TjMax in bits 23:16 of MSR 0x1A2, which is
+ * read for those models; Airmont/Braswell uses coretemp's 90 C table instead
+ * (an unsupported rdmsr before the IDT exists would triple-fault).  The DTS
  * "valid" bit is ignored on purpose: coretemp does the same because the delta
  * "valid" bit is ignored on purpose: coretemp does the same because the delta
  * stays meaningful (the bit can be clear at temperatures below the sensor's
  * stays meaningful (the bit can be clear at temperatures below the sensor's
  * range).
  * range).
@@ -75,6 +76,7 @@ static int model_has_dts(unsigned int model)
 	case 0x2C:   /* Westmere-EP */
 	case 0x2C:   /* Westmere-EP */
 	case 0x2E:   /* Nehalem-EX */
 	case 0x2E:   /* Nehalem-EX */
 	case 0x2F:   /* Westmere-EX */
 	case 0x2F:   /* Westmere-EX */
+	case 0x4C:   /* Airmont: Braswell / Cherry Trail */
 		return 1;
 		return 1;
 	default:
 	default:
 		return 0;
 		return 0;
@@ -146,6 +148,8 @@ static int pick_tjmax(unsigned int model, unsigned int stepping,
 			return 100;
 			return 100;
 		return 90;
 		return 90;
 	}
 	}
+	if (model == 0x4C)          /* Airmont (coretemp: 90 C) */
+		return 90;
 	return 100;
 	return 100;
 }
 }
 
 

+ 12 - 94
tpec.c

@@ -35,18 +35,10 @@
  * (0 dynamic, 1 mode, 2 static design data, 5 manufacturer, 6 model).
  * (0 dynamic, 1 mode, 2 static design data, 5 manufacturer, 6 model).
  */
  */
 #include "tpec.h"
 #include "tpec.h"
+#include "ec.h"
 #include "paging.h"
 #include "paging.h"
-#include "pci.h"      /* port_inb/port_outb */
 #include "serial.h"
 #include "serial.h"
 
 
-#define EC_DATA 0x62
-#define EC_STS  0x66
-
-#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_LEVEL  0x2F
 #define TP_FAN_LSB    0x84
 #define TP_FAN_LSB    0x84
 #define TP_FAN_MSB    0x85
 #define TP_FAN_MSB    0x85
@@ -72,10 +64,6 @@
 #define TP_BAT_RATE      0x08
 #define TP_BAT_RATE      0x08
 #define TP_BAT_VOLTAGE   0x0A
 #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
-
 static int tpec_state = -1;   /* -1 unprobed, 0 absent, 1 present */
 static int tpec_state = -1;   /* -1 unprobed, 0 absent, 1 present */
 static unsigned int tpec_ec_rev;
 static unsigned int tpec_ec_rev;
 static char tpec_vendor[16];
 static char tpec_vendor[16];
@@ -214,84 +202,6 @@ static int smbios_type1(char vendor[16], char product[32], char version[32])
 	return -1;
 	return -1;
 }
 }
 
 
-static int ec_wait(unsigned char mask, int set)
-{
-	unsigned int i;
-
-	for (i = 0; i < EC_POLL_MAX; i++) {
-		unsigned char st = port_inb(EC_STS);
-
-		if (st == 0xFF)           /* no controller on these ports */
-			return -1;
-		if (set ? (st & mask) != 0 : (st & mask) == 0)
-			return 0;
-	}
-	return -1;
-}
-
-/* Keep a stale output byte (a hotkey event) from shadowing the register we
- * are about to read. */
-static int ec_drain(void)
-{
-	unsigned int i;
-
-	for (i = 0; i < 64; i++) {
-		unsigned char st = port_inb(EC_STS);
-
-		if (st == 0xFF)
-			return -1;
-		if (!(st & EC_OBF))
-			return 0;
-		(void)port_inb(EC_DATA);
-	}
-	return -1;
-}
-
-static int ec_read(unsigned char reg, unsigned char *out)
-{
-	if (ec_drain())
-		return -1;
-	if (ec_wait(EC_IBF, 0))
-		return -1;
-	port_outb(EC_STS, EC_READ);
-	if (ec_wait(EC_IBF, 0))
-		return -1;
-	port_outb(EC_DATA, reg);
-	if (ec_wait(EC_OBF, 1))
-		return -1;
-	*out = port_inb(EC_DATA);
-	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
 /* Select an H8 battery information page.  Only writes 0x81 when the page
  * already differs; *dirty remembers that the original page must be restored. */
  * already differs; *dirty remembers that the original page must be restored. */
 static int ec_battery_page(unsigned int battery, unsigned int page, int *dirty)
 static int ec_battery_page(unsigned int battery, unsigned int page, int *dirty)
@@ -392,6 +302,13 @@ void tpec_init(void)
 	serial_puts(SERIAL_COM1, "\n");
 	serial_puts(SERIAL_COM1, "\n");
 }
 }
 
 
+int tpec_present(void)
+{
+	if (tpec_state < 0)
+		tpec_init();
+	return tpec_state > 0;
+}
+
 void tpec_read(struct tpec_info *out)
 void tpec_read(struct tpec_info *out)
 {
 {
 	unsigned char b;
 	unsigned char b;
@@ -464,7 +381,7 @@ static void tpec_copy_ident(char *dst, unsigned int size, const char *src)
 	dst[i] = '\0';
 	dst[i] = '\0';
 }
 }
 
 
-static void tpec_read_battery(struct tpec_battery *b, unsigned int index,
+static void tpec_read_battery(struct power_battery *b, unsigned int index,
 			      int detail, int *page_dirty)
 			      int detail, int *page_dirty)
 {
 {
 	unsigned char st;
 	unsigned char st;
@@ -572,7 +489,7 @@ static void tpec_read_battery(struct tpec_battery *b, unsigned int index,
 		b->error = 1;
 		b->error = 1;
 }
 }
 
 
-void tpec_power_read(struct tpec_power *out, int detail)
+void tpec_power_read(struct power_info *out, int detail)
 {
 {
 	unsigned int i;
 	unsigned int i;
 	unsigned char saved_page = 0, ac;
 	unsigned char saved_page = 0, ac;
@@ -588,6 +505,7 @@ void tpec_power_read(struct tpec_power *out, int detail)
 		return;
 		return;
 
 
 	out->present = 1;
 	out->present = 1;
+	out->source = SYS_POWER_SRC_TPEC;
 	out->ec_rev = tpec_ec_rev;
 	out->ec_rev = tpec_ec_rev;
 	tpec_copy_ident(out->vendor, sizeof(out->vendor), tpec_vendor);
 	tpec_copy_ident(out->vendor, sizeof(out->vendor), tpec_vendor);
 	tpec_copy_ident(out->product, sizeof(out->product), tpec_product);
 	tpec_copy_ident(out->product, sizeof(out->product), tpec_product);
@@ -598,7 +516,7 @@ void tpec_power_read(struct tpec_power *out, int detail)
 	if (ec_read(TP_BAT_PAGE, &saved_page) == 0)
 	if (ec_read(TP_BAT_PAGE, &saved_page) == 0)
 		have_saved = 1;
 		have_saved = 1;
 
 
-	for (i = 0; i < TPEC_BATTERY_COUNT; i++) {
+	for (i = 0; i < POWER_BATT_MAX; i++) {
 		tpec_read_battery(&out->battery[i], i, detail, &page_dirty);
 		tpec_read_battery(&out->battery[i], i, detail, &page_dirty);
 		if (out->battery[i].present)
 		if (out->battery[i].present)
 			out->battery_count++;
 			out->battery_count++;

+ 9 - 36
tpec.h

@@ -2,8 +2,9 @@
 #ifndef TPEC_H
 #ifndef TPEC_H
 #define TPEC_H
 #define TPEC_H
 
 
+#include "power_src.h"
+
 #define TPEC_TEMP_COUNT 16
 #define TPEC_TEMP_COUNT 16
-#define TPEC_BATTERY_COUNT 2
 
 
 /* Temperatures are indexed like thinkpad_acpi's temp1..temp16:
 /* 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.
  * temp_c[0..7] come from EC 0x78..0x7F, temp_c[8..15] from EC 0xC0..0xC7.
@@ -18,50 +19,22 @@ struct tpec_info {
 	unsigned int fan_level;   /* raw EC 0x2F value */
 	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
 /* 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
  * nothing (present = 0) unless SMBIOS identifies a Lenovo/IBM machine and the
  * EC answers, so boards without one are never touched. */
  * EC answers, so boards without one are never touched. */
 void tpec_init(void);
 void tpec_init(void);
 
 
+/* Whether the ThinkPad EC was found; probes on first use. */
+int tpec_present(void);
+
 /* Read the current temperatures, fan speed and fan level.  present is 0 when
 /* Read the current temperatures, fan speed and fan level.  present is 0 when
  * no ThinkPad EC was found. */
  * no ThinkPad EC was found. */
 void tpec_read(struct tpec_info *out);
 void tpec_read(struct tpec_info *out);
 
 
 /* Read the AC adapter and battery state through the H8 battery information
 /* 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);
+ * pages into the shared snapshot; 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 power_info *out, int detail);
 
 
 #endif
 #endif

+ 5 - 0
ucmd_lib.h

@@ -410,6 +410,11 @@ static inline int u_tpec_sensors(struct sys_tpec_sensors *out)
 	return u_syscall1(SYS_TPEC_SENSORS, (int)out);
 	return u_syscall1(SYS_TPEC_SENSORS, (int)out);
 }
 }
 
 
+static inline int u_cros_sensors(struct sys_cros_sensors *out)
+{
+	return u_syscall1(SYS_CROS_EC_SENSORS, (int)out);
+}
+
 static inline int u_power_info(struct sys_powerinfo *out, unsigned int flags)
 static inline int u_power_info(struct sys_powerinfo *out, unsigned int flags)
 {
 {
 	return u_syscall2(SYS_POWER_INFO, (int)out, (int)flags);
 	return u_syscall2(SYS_POWER_INFO, (int)out, (int)flags);

+ 20 - 4
ucmd_powerinfo.c

@@ -1,8 +1,9 @@
-/* powerinfo: AC adapter and battery state from the ThinkPad H8 EC.
+/* powerinfo: AC adapter and battery state from the board EC.
  *
  *
  * The EC access lives in the kernel (SYS_POWER_INFO); this command only
  * 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 AC and
  * formats the snapshot.  The same syscall feeds the WM's top-bar AC and
- * battery indicators.
+ * battery indicators.  Both the ThinkPad H8 EC and the Chrome OS EC fill
+ * the same snapshot.
  */
  */
 #include "ucmd_lib.h"
 #include "ucmd_lib.h"
 
 
@@ -111,6 +112,16 @@ static void show_battery(unsigned int index, const struct sys_battery *b)
 		}
 		}
 		u_putc('\n');
 		u_putc('\n');
 	}
 	}
+	if (b->serial[0]) {
+		u_puts("  serial ");
+		u_puts(b->serial);
+		u_putc('\n');
+	}
+	if (b->cycle_count) {
+		u_puts("  cycles ");
+		u_putdec(b->cycle_count);
+		u_putc('\n');
+	}
 }
 }
 
 
 void _start(void)
 void _start(void)
@@ -123,12 +134,17 @@ void _start(void)
 		u_exit(1);
 		u_exit(1);
 	}
 	}
 	if (!p.present) {
 	if (!p.present) {
-		u_puts("no ThinkPad embedded controller detected\n");
+		u_puts("no supported embedded controller detected\n");
 		u_puts("battery/AC status unavailable on this platform\n");
 		u_puts("battery/AC status unavailable on this platform\n");
 		u_exit(0);
 		u_exit(0);
 	}
 	}
 
 
-	u_puts("thinkpad");
+	if (p.source == SYS_POWER_SRC_CROS)
+		u_puts("chrome ec");
+	else if (p.source == SYS_POWER_SRC_TPEC)
+		u_puts("thinkpad");
+	else
+		u_puts("embedded controller");
 	if (p.vendor[0]) {
 	if (p.vendor[0]) {
 		u_putc(' ');
 		u_putc(' ');
 		u_puts(p.vendor);
 		u_puts(p.vendor);

+ 69 - 3
ucmd_sensors.c

@@ -1,8 +1,9 @@
 /* sensors: CPU DTS plus the board's hardware monitor.
 /* sensors: CPU DTS plus the board's hardware monitor.
  *
  *
- * Two board sources exist: the IT87xx Super I/O (AT3IONT-I, three
- * temperatures and fan tachometers) and the ThinkPad embedded controller
- * (X201, temperatures at EC 0x78..0x7F / 0xC0..0xC7 plus the fan tachometer).
+ * Board sources: the IT87xx Super I/O (AT3IONT-I, three temperatures and fan
+ * tachometers), the ThinkPad embedded controller (X201, temperatures at EC
+ * 0x78..0x7F / 0xC0..0xC7 plus the fan tachometer) and the Chrome OS EC on
+ * Chromebooks (EC memmap temperatures/fans, lid and power-button switches).
  *
  *
  * The DTS TjMax of the Atom 330 is not published; Intel only specifies
  * The DTS TjMax of the Atom 330 is not published; Intel only specifies
  * TJ = 90 C and Tcase-max = 85.2 C, while Linux coretemp uses 125 C for this
  * TJ = 90 C and Tcase-max = 85.2 C, while Linux coretemp uses 125 C for this
@@ -206,6 +207,70 @@ static int show_tpec(void)
 	return 1;
 	return 1;
 }
 }
 
 
+static int show_cros(void)
+{
+	struct sys_cros_sensors s;
+	unsigned int i, shown = 0;
+
+	if (u_cros_sensors(&s) != 0 || !s.present)
+		return 0;
+	u_puts("chrome ec (ACPI v");
+	u_putdec(s.acpi_version);
+	u_puts(", battery v");
+	u_putdec(s.battery_version);
+	u_puts(", thermal v");
+	u_putdec(s.thermal_version);
+	u_puts(")\n");
+	for (i = 0; i < SYS_CROS_TEMP_MAX; i++) {
+		unsigned int reg = i < 16 ? i : 0x18 + (i - 16);
+
+		if (s.temp_c[i] <= -50)
+			continue;
+		if (shown)
+			u_puts(", ");
+		u_puts("temp");
+		u_putdec(i + 1);
+		u_puts(" (0x");
+		u_put_hex2(reg);
+		u_puts(") ");
+		put_temp(s.temp_c[i]);
+		u_puts(" C");
+		shown++;
+	}
+	if (!shown)
+		u_puts("no EC temperature sensors");
+	u_putc('\n');
+	shown = 0;
+	for (i = 0; i < SYS_CROS_FAN_MAX; i++) {
+		if (!(s.fan_present & (1u << i)))
+			continue;
+		if (shown)
+			u_puts(", ");
+		u_puts("fan");
+		u_putdec(i + 1);
+		u_puts(" ");
+		u_putdec(s.fan_rpm[i]);
+		u_puts(" RPM");
+		shown++;
+	}
+	if (!shown)
+		u_puts("no EC fan tachometer");
+	u_putc('\n');
+	u_puts("fan duty ");
+	if (s.fan_duty == 0xFF) {
+		u_puts("auto");
+	} else {
+		u_putdec(s.fan_duty);
+		u_putc('%');
+	}
+	u_puts(", lid ");
+	u_puts((s.switches & 0x01) ? "open" : "closed");
+	u_puts(", power button ");
+	u_puts((s.switches & 0x02) ? "pressed" : "released");
+	u_putc('\n');
+	return 1;
+}
+
 void _start(void)
 void _start(void)
 {
 {
 	int any;
 	int any;
@@ -213,6 +278,7 @@ void _start(void)
 	show_dts();
 	show_dts();
 	any = show_it87();
 	any = show_it87();
 	any |= show_tpec();
 	any |= show_tpec();
+	any |= show_cros();
 	if (!any)
 	if (!any)
 		u_puts("no board sensors found\n");
 		u_puts("no board sensors found\n");
 	u_exit(0);
 	u_exit(0);

+ 3 - 3
ucmd_wm.c

@@ -874,9 +874,9 @@ static void do_update(struct wm_status *st)
 				unsigned int bi;
 				unsigned int bi;
 
 
 				if (u_power_info(&pi, 0) == 0) {
 				if (u_power_info(&pi, 0) == 0) {
-					/* The ThinkPad EC is the laptop marker:
-					 * desktops have no EC, so neither the
-					 * AC state nor a battery is shown. */
+					/* A laptop EC (ThinkPad or Chrome
+					 * EC) marks a machine with AC/battery;
+					 * desktops show neither. */
 					if (pi.present) {
 					if (pi.present) {
 						ac = pi.ac_online;
 						ac = pi.ac_online;
 						for (bi = 0; bi < SYS_POWER_BATT_MAX;
 						for (bi = 0; bi < SYS_POWER_BATT_MAX;