Explorar o código

Add RTC clock setting and a date command

The top-bar date/time is now a clickable target: it highlights on hover and
spawns /ramfs/bin/settime, a small ngui Date & Time editor with date/time
fields, a live current-time line and Set/Now buttons.

rtc.c gains a full read/write path: BCD/binary and 12/24-hour decoding,
update-cycle retries, register-B SET sequencing and calendar validation.
The two-digit year is expanded over a 1970-2069 window so a dead-battery
default such as 1980/1990 stays in the past instead of becoming 2080/2090;
on ACPI machines the FADT century byte is written too, so other software sees
the intended century.  New SYS_RTC_GET/SET (104/105) expose the complete
struct sys_datetime.

The new date command prints the classic Linux line, e.g.
"Sun Nov  8 19:45:46 2026", and supports a +FORMAT subset (%Y %m %d %H %M %S
%a %A %b %B %p %F %T).

Verified in QEMU: clicking the clock opens settime; setting 1999-12-31
23:59:00 and 2026-11-08 20:00:00 updates the top bar, the app and date, and
QEMU's rtc-time property reports the matching century.  A boot with
-rtc base=1980-01-01T00:00:00 shows 1980 in both the top bar and date.
make all passes and the command pack stays under its cap.  AGENTS.md and the
userland, graphics, drivers and CPU pages are updated.
Johannes Zellner hai 1 semana
pai
achega
e9978cf96f
Modificáronse 16 ficheiros con 966 adicións e 80 borrados
  1. 17 2
      AGENTS.md
  2. 10 2
      Makefile
  3. 29 3
      acpi.c
  4. 4 0
      acpi.h
  5. 7 0
      docs/cpu.html
  6. 31 0
      docs/drivers.html
  7. 6 3
      docs/graphics.html
  8. 8 6
      docs/userland.html
  9. 259 59
      rtc.c
  10. 12 0
      rtc.h
  11. 24 0
      syscall.c
  12. 16 0
      syscall.h
  13. 142 0
      ucmd_date.c
  14. 12 0
      ucmd_lib.h
  15. 346 0
      ucmd_settime.c
  16. 43 5
      ucmd_wm.c

+ 17 - 2
AGENTS.md

@@ -289,6 +289,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   repainted and the stack is not drawn back-to-front.  A focused-window drag
   copies its shadow block (`usurf_copy`) and repaints only the old strips the
   new rectangle does not cover.  The kernel hit-test uses the same order.
+  The right-aligned date/time text is itself a click target: `draw_bar()`
+  records its rectangle, the pointer highlights it, and a click spawns
+  `/ramfs/bin/settime` (the `Clock` launcher still opens the analog clock).
   `terminal.c` keeps the privileged kernel command
   registry for the ring-3 terminal (`SYS_SPAWN_KCMD` / `term_kcmd_spawn`),
   but the kernel terminal entry/shell and the cell-window ABI are gone.
@@ -308,7 +311,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `SYS_WIN_KEY_WAIT` and the generic `SYS_KEY_POLL` handle input.  The WM
   composites the front canvas; presented frames carry monotonic seq
   counters, so the WM can never lose one.  Closing a window kills its owner;
-  the reaper frees the canvas.  `clock`, `colors`,
+  the reaper frees the canvas.  `clock`, `colors`, `settime`,
   `term`, `files` and the other apps are canvas clients.  The old
   `SYS_GFX_BEGIN/PRESENT/END` terminal-takeover service and the kernel
   text-canvas renderer are removed.  Pointer input: `SYS_WIN_POINTER` reports
@@ -379,6 +382,18 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   manager has no text-cell content path.  `screen_damage_*` remains for the
   boot console's own bookkeeping.  The kernel console stays 8×8; userland
   proportional text uses `ufont` (below).
+- **Wall clock**: `rtc.c/h` reads and writes the CMOS RTC.  Reads honour the
+  register-B BCD/binary and 12/24-hour modes, retry around the update cycle,
+  and expand the two-digit year with a 1970-2069 window (70-99 -> 1900s,
+  00-69 -> 2000s), so a dead-battery default such as 1980 or 1990 reads
+  correctly.  Writes use the RTC's SET bit, preserve its mode bits and
+  validate leap years and 1970-2069; on ACPI machines the FADT century byte
+  (exposed by `acpi_rtc_century_reg()`) is written too, so other software
+  sees the right century.  `SYS_RTC_GET`/`SYS_RTC_SET` (104/105)
+  expose the full `struct sys_datetime`; `SYS_RTC_HMS`/`SYS_RTC_DATETIME`
+  (56/69) stay the small read-only views.  The WM top-bar date/time is a
+  click target that spawns `/ramfs/bin/settime`; the `date` command prints
+  the classic `date` line and a small `+FORMAT` subset.
 - **Fonts**: `ufont.c/h`, `ufont_ttf.c`, `ufont_draw.c`, `ufont_file.c` — a
   fixed-point (26.6, no FPU) TrueType parser and antialiased rasterizer for
   ring-3 text.  Latin-1 only for now; the faces are the Arimo regular/bold/
@@ -798,7 +813,7 @@ nested). `/` is the read-only VFS root listing the mounted filesystems (the
 filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 
 `cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`, `spin`,
-`clock`, `colors`, `files`, `gallery`, `view`, `sensors`, `powerinfo`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
+`clock`, `colors`, `settime`, `date`, `files`, `gallery`, `view`, `sensors`, `powerinfo`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
 `netreset`, `websrv`, `curl`, `solitaire` and `hello` are files in `/ramfs/bin`
 (packed by the Makefile), found through the shell's PATH; the rest are kernel

+ 10 - 2
Makefile

@@ -101,7 +101,7 @@ disk.o: disk.c disk.h io.h timer.h
 fat.o: fat.c fat.h blkdev.h io.h
 	$(CC) $(CFLAGS) -Os -o $@ $<
 
-rtc.o: rtc.c rtc.h
+rtc.o: rtc.c rtc.h acpi.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 serial.o: serial.c serial.h serial_ring_buf.h pci.h idle.h sched.h timer.h
@@ -552,7 +552,7 @@ UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir \
         ucmd_netsend ucmd_netrecv ucmd_ping ucmd_pong ucmd_netlog \
         ucmd_netconsole ucmd_netregs ucmd_netloop ucmd_netreset ucmd_net100 ucmd_netmac ucmd_curl \
         ucmd_files ucmd_view ucmd_sensors ucmd_powerinfo ucmd_mines ucmd_solitaire \
-        ucmd_gallery ucmd_websrv ucmd_browser
+        ucmd_settime ucmd_date ucmd_gallery ucmd_websrv ucmd_browser
 
 # Keep the linked ELFs around (make would treat them as disposable
 # intermediates between the pattern rules).
@@ -651,6 +651,14 @@ ucmd_mines.elf: ucmd_mines.o ngui.o font_8x16.o $(UFONT_OBJS) ucmd.ld libc.a
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
+# settime: Date & Time editor (RTC read/write) on the same canvas toolkit.
+ucmd_settime.o: ucmd_settime.c ucmd_lib.h syscall.h wm_abi.h ngui.h
+	$(CC) $(CFLAGS) -Os -o $@ $<
+
+ucmd_settime.elf: ucmd_settime.o ngui.o font_8x16.o $(UFONT_OBJS) ucmd.ld libc.a
+	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
+	$(OBJCOPY) --strip-all $@ $@
+
 # solitaire: a Windows 95 style Klondike game on the same canvas toolkit.
 ucmd_solitaire.o: ucmd_solitaire.c ucmd_lib.h syscall.h wm_abi.h ngui.h
 	$(CC) $(CFLAGS) -Os -o $@ $<

+ 29 - 3
acpi.c

@@ -44,6 +44,10 @@ static unsigned int ncpu;
 static unsigned int bsp_apic;
 static unsigned int lapic_base;
 static int acpi_ok;
+/* FADT "century" register (offset 108), 0 when absent.  The RTC uses it to
+ * keep the two-digit CMOS year in the right century; rtc.c only writes it
+ * when the firmware points at a real CMOS register. */
+static unsigned int rtc_century_reg;
 
 static void *phys_ptr(unsigned int addr)
 {
@@ -149,6 +153,7 @@ static const struct acpi_sdt *find_madt(const struct acpi_rsdp *rsdp)
 {
 	unsigned int addr, len, i, step;
 	const struct acpi_sdt *sdt;
+	const struct acpi_sdt *madt = 0;
 
 	/* Prefer the 64-bit XSDT when it is reachable from the 32-bit
 	 * identity map; otherwise fall back to the ACPI 1.0 RSDT. */
@@ -193,12 +198,27 @@ static const struct acpi_sdt *find_madt(const struct acpi_rsdp *rsdp)
 		if (tlen < sizeof(struct acpi_sdt) || tlen > 0x100000u)
 			continue;
 		map_table(taddr, tlen);
+		if (!sum_ok((const unsigned char *)t, tlen))
+			continue;
+		if (t->signature[0] == 'F' && t->signature[1] == 'A' &&
+		    t->signature[2] == 'C' && t->signature[3] == 'P') {
+			/* FADT "century" is at offset 108 (ACPI 2.0+); 0 means
+			 * the firmware does not provide a century register. */
+			if (tlen >= 109) {
+				unsigned char c =
+					((const unsigned char *)t)[108];
+
+				if (c >= 0x0E && c <= 0x7F)
+					rtc_century_reg = c;
+			}
+			continue;
+		}
 		if (t->signature[0] == 'A' && t->signature[1] == 'P' &&
 		    t->signature[2] == 'I' && t->signature[3] == 'C' &&
-		    sum_ok((const unsigned char *)t, tlen))
-			return t;
+		    !madt)
+			madt = t;
 	}
-	return 0;
+	return madt;
 }
 
 static unsigned int cpuid_apic_id(void)
@@ -257,6 +277,7 @@ int acpi_init(void)
 
 	acpi_ok = 0;
 	ncpu = 0;
+	rtc_century_reg = 0;
 	bsp_apic = cpuid_apic_id();
 	if (bsp_apic == 0xFFFFFFFFu)
 		return 0;
@@ -312,6 +333,11 @@ unsigned int acpi_lapic_base(void)
 	return lapic_base;
 }
 
+unsigned int acpi_rtc_century_reg(void)
+{
+	return rtc_century_reg;
+}
+
 void acpi_dump(void)
 {
 	unsigned int i;

+ 4 - 0
acpi.h

@@ -17,6 +17,10 @@ unsigned int acpi_cpu_apic_id(unsigned int index);
 unsigned int acpi_bsp_apic_id(void);
 unsigned int acpi_lapic_base(void);
 
+/* CMOS register holding the RTC century byte from the FADT, or 0 when the
+ * firmware does not provide one (old non-ACPI hardware). */
+unsigned int acpi_rtc_century_reg(void);
+
 void acpi_dump(void);
 
 #endif

+ 7 - 0
docs/cpu.html

@@ -147,6 +147,13 @@
 			usable MADT, the CPUID APIC bit or a LAPIC stays uniprocessor and
 			follows exactly the old 8259/PIT path.
 		</p>
+		<p>
+			The same table walk reads the FADT's <code>century</code> byte (offset
+			108) and exposes the CMOS register to <span class="file">rtc.c</span>,
+			which writes it when setting the clock so the two-digit year stays in
+			the intended century. Boards without ACPI get no century write and
+			keep the 1970–2069 read window.
+		</p>
 		<ol>
 			<li>Copy the AP trampoline to <code>0x6000</code> (SIPI vector <code>0x06</code>).</li>
 			<li>Allocate an AP idle PCB and kernel stack via <code>process_init_ap()</code>.</li>

+ 31 - 0
docs/drivers.html

@@ -58,6 +58,7 @@
 			<li><a href="#hid">Input</a></li>
 			<li><a href="#serial">Serial</a></li>
 			<li><a href="#sensors">Sensors &amp; power</a></li>
+			<li><a href="#rtc">Wall clock (RTC)</a></li>
 			<li><a href="#panic">Panic screen</a></li>
 			<li><a href="#limits">Limits</a></li>
 			<li><a href="#sources">Source map</a></li>
@@ -86,6 +87,7 @@
 					<tr><td>Serial</td><td><span class="file">serial.c</span></td><td>16550 UART, COM1</td><td>IRQ 4 ring buffer + polled transmitter</td></tr>
 					<tr><td>Thermal</td><td><span class="file">thermal.c</span></td><td>Intel DTS MSR</td><td>Sampled once a second from the scheduler tick</td></tr>
 					<tr><td>Board sensors</td><td><span class="file">it87.c</span>, <span class="file">tpec.c</span></td><td>Super I/O, ThinkPad EC (temps, fan, battery, AC)</td><td>Polled; only the EC page selector is written, then restored</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>
 			</table>
 		</div>
@@ -329,6 +331,34 @@
 		</p>
 	</section>
 
+	<section id="rtc">
+		<h2>Wall clock (RTC)</h2>
+		<p>
+			<span class="file">rtc.c</span> talks to the MC146818-compatible
+			CMOS clock through ports <code>0x70/0x71</code>. Reads honour the
+			register-B BCD/binary and 12/24-hour modes, retry when the
+			update-in-progress bit is set, and decode the hour's PM flag. The
+			RTC only stores a two-digit year, so the kernel expands it over a
+			1970–2069 window (70–99 → 1900s, 00–69 → 2000s); a board whose
+			dead battery left 1980 or 1990 therefore reads correctly instead of
+			being pushed a century forward. Writes validate the calendar (leap
+			years included), raise the register-B SET bit, preserve the mode
+			bits and write the computed weekday. On ACPI machines the FADT
+			century register (offset 108, normally CMOS <code>0x32</code>) is
+			written as well, so the firmware and other operating systems see
+			the intended century; boards without ACPI get no arbitrary NVRAM
+			write.
+		</p>
+		<p>
+			<code>SYS_RTC_GET</code>/<code>SYS_RTC_SET</code> (104/105) expose
+			the full <code>struct sys_datetime</code>; the older
+			<code>SYS_RTC_HMS</code>/<code>SYS_RTC_DATETIME</code> calls remain
+			the small read-only views. The WM’s top-bar date/time is a click
+			target that opens <code>bin/settime</code>, and the <code>date</code>
+			command prints the same clock in the classic Linux format.
+		</p>
+	</section>
+
 	<section id="panic">
 		<h2>Panic screen</h2>
 		<p>
@@ -371,6 +401,7 @@
 			<li><code>usbhid.c</code>, <code>mouse.c</code>, <code>io.c</code> — input</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>rtc.c</code> — CMOS wall clock read/write</li>
 			<li><code>panic.c</code>, <code>timer.S</code> — fatal exceptions</li>
 		</ul>
 	</section>

+ 6 - 3
docs/graphics.html

@@ -142,7 +142,9 @@
 			clock and the CPU temperature/battery percentage, plus draggable
 			terminal and canvas windows with a title bar and close button.
 			Click-to-focus, drag-by-title-bar and close are routed through the
-			same pointer path.
+			same pointer path. The right-aligned date/time text is also a
+			target: it highlights on hover and opens the Date &amp; Time editor
+			(<code>bin/settime</code>) on a click.
 		</p>
 		<p>
 			The WM is the ring-3 process loaded from
@@ -304,8 +306,8 @@
 				<p>Image viewer with fit, 1:1, zoom, pan, EXIF orientation and animated GIF playback.</p>
 			</div>
 			<div class="card">
-				<h3>clock / colors</h3>
-				<p>Small canvas demos: a clock and a colour test window. Both are early users of the window canvas API.</p>
+				<h3>clock / colors / settime</h3>
+				<p>Small canvas demos: an analog clock, a colour test window, and the Date &amp; Time editor. Clicking the top-bar date/time opens <code>settime</code>, which reads and writes the CMOS RTC.</p>
 			</div>
 			<div class="card">
 				<h3>browser</h3>
@@ -349,6 +351,7 @@
 			<li><code>cpu.c</code> — SSE2 probing</li>
 			<li><code>wm.c</code>, <code>wm.h</code> — kernel window server</li>
 			<li><code>ucmd_wm.c</code>, <code>uwm_lib.c</code> — ring-3 WM</li>
+			<li><code>ucmd_settime.c</code>, <code>rtc.c</code> — Date &amp; Time editor and RTC access</li>
 			<li><code>gfx.c</code>, <code>gfx.h</code> — RGB565 window canvases</li>
 			<li><code>sys_wm.c</code>, <code>sys_wm.h</code> — WM/window ABI</li>
 			<li><code>browser.c</code>, <code>browser_html.c</code> — HTML/CSS renderer and inline SVG</li>

+ 8 - 6
docs/userland.html

@@ -4,7 +4,7 @@
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Userland | NebOS Architecture</title>
-<meta name="description" content="NebOS userland: ring-3 address space, ELF loading, the syscall ABI, the shell and PATH dispatch, the 42-command pack, GUI applications and the browser.">
+<meta name="description" content="NebOS userland: ring-3 address space, ELF loading, the syscall ABI, the shell and PATH dispatch, the 45-command pack, GUI applications and the browser.">
 <link rel="icon" href="favicon.svg" type="image/svg+xml">
 <link rel="stylesheet" href="style.css">
 </head>
@@ -38,12 +38,12 @@
 			Ring-3 programs are static ELFs linked at <code>0x40000000</code>.
 			The shell resolves a command name against builtins, the per-terminal
 			PATH and the kernel command registry, then spawns it with one
-			argument string. The command pack supplies 42 PATH commands by default.
+			argument string. The command pack supplies 45 PATH commands by default.
 		</p>
 		<div class="meta">
 			<span class="pill">int 0x80</span>
 			<span class="pill">one string argument</span>
-			<span class="pill">42 PATH commands</span>
+			<span class="pill">45 PATH commands</span>
 			<span class="pill">8 TTYs · 8 windows</span>
 		</div>
 	</div>
@@ -193,7 +193,7 @@
 					<tr><th>Group</th><th>Numbers</th><th>Purpose</th></tr>
 				</thead>
 				<tbody>
-					<tr><td>Console &amp; time</td><td>1–4, 56, 69</td><td>putstr, ticks, sleep, exit, RTC time/date</td></tr>
+					<tr><td>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>System info</td><td>12–16, 49–51, 91–92, 102–103</td><td>memory, E820, mouse, storage, blkdev, procinfo, cursor, CPU temp, sensors, EC sensors, AC/battery</td></tr>
 					<tr><td>Network</td><td>17–47</td><td>NIC config/acquire, raw frames, DHCP/DNS, TCP client, ARP, cwd</td></tr>
@@ -270,7 +270,7 @@
 			</div>
 			<div class="card">
 				<h3>System</h3>
-				<p><code>cpuinfo</code> <code>meminfo</code> <code>storage</code> <code>top</code> <code>mouseinfo</code> <code>sensors</code> <code>powerinfo</code> <code>spin</code> <code>clock</code> <code>colors</code></p>
+				<p><code>cpuinfo</code> <code>meminfo</code> <code>storage</code> <code>top</code> <code>mouseinfo</code> <code>sensors</code> <code>powerinfo</code> <code>date</code> <code>spin</code> <code>clock</code> <code>colors</code></p>
 			</div>
 			<div class="card">
 				<h3>Network</h3>
@@ -278,7 +278,7 @@
 			</div>
 			<div class="card">
 				<h3>GUI</h3>
-				<p><code>wm</code> <code>term</code> <code>files</code> <code>view</code> <code>mines</code> <code>solitaire</code> <code>gallery</code> <code>browser</code> <code>clock</code> <code>colors</code></p>
+				<p><code>wm</code> <code>term</code> <code>files</code> <code>view</code> <code>mines</code> <code>solitaire</code> <code>gallery</code> <code>browser</code> <code>clock</code> <code>colors</code> <code>settime</code></p>
 			</div>
 		</div>
 		<p>
@@ -301,6 +301,7 @@
 			<li><strong>view</strong> — fit/1:1/zoom/pan image viewer, animated GIF playback.</li>
 			<li><strong>edit</strong> — text editor that draws its own text with the 8x16 font.</li>
 			<li><strong>clock</strong> / <strong>colors</strong> — small window canvas demos.</li>
+			<li><strong>settime</strong> — Date &amp; Time editor opened by clicking the top-bar clock. It reads and writes the CMOS RTC through <code>SYS_RTC_GET</code>/<code>SYS_RTC_SET</code>; the two-digit RTC year is expanded over 1970–2069 so dead-battery defaults such as 1980/1990 can be corrected.</li>
 			<li><strong>wm</strong> / <strong>term</strong> — the ring-3 window manager and terminal launcher used by the desktop.</li>
 		</ul>
 		<p>
@@ -347,6 +348,7 @@
 		<ul class="filelist">
 			<li><code>syscall.c</code>, <code>syscall_stub.S</code>, <code>syscall.h</code></li>
 			<li><code>sys_info.c</code> — kernel-state snapshots (memory, sensors, power)</li>
+			<li><code>rtc.c</code> — CMOS RTC read/write, format decoding and the 1970–2069 year window</li>
 			<li><code>process.c</code> — ELF load and spawn</li>
 			<li><code>elf.c</code> — ELF parser</li>
 			<li><code>ucmd_term.c</code> — windowed shell, scrollback, PATH</li>

+ 259 - 59
rtc.c

@@ -1,10 +1,25 @@
-/* RTC (CMOS) date/time read. */
+/* RTC (CMOS) date/time read and write. */
 
 #include "rtc.h"
+#include "acpi.h"
 
 #define CMOS_ADDR  0x70
 #define CMOS_DATA  0x71
 
+#define RTC_SEC    0x00
+#define RTC_MIN    0x02
+#define RTC_HOUR   0x04
+#define RTC_WDAY   0x06
+#define RTC_DAY    0x07
+#define RTC_MON    0x08
+#define RTC_YEAR   0x09
+#define RTC_REGA   0x0A
+#define RTC_REGB   0x0B
+
+/* Last good value, used when a read straddles the update cycle and no retry
+ * produces a complete, valid set.  Initialised to 2000-01-01 (a Saturday). */
+static struct sys_datetime last_dt = { 2000, 1, 1, 0, 0, 0, 6 };
+
 static inline unsigned char cmos_read(unsigned char reg)
 {
 	unsigned char v;
@@ -14,9 +29,10 @@ static inline unsigned char cmos_read(unsigned char reg)
 	return v;
 }
 
-static unsigned int bcd_to_bin(unsigned char bcd)
+static inline void cmos_write(unsigned char reg, unsigned char val)
 {
-	return (unsigned int)((bcd >> 4) * 10 + (bcd & 0x0F));
+	__asm__ volatile ("outb %b1, %w0" : : "Nd"(CMOS_ADDR), "a"((unsigned char)(reg | 0x80)));
+	__asm__ volatile ("outb %b1, %w0" : : "Nd"(CMOS_DATA), "a"(val));
 }
 
 static int bcd_digits(unsigned char bcd)
@@ -24,78 +40,174 @@ static int bcd_digits(unsigned char bcd)
 	return (bcd & 0x0F) <= 9 && ((bcd >> 4) & 0x0F) <= 9;
 }
 
-/* Read hour/minute/second out of the CMOS.  A read that straddles the RTC's
- * update cycle can tear (invalid BCD, or a value out of range), which used to
- * feed nonsense into callers - retry a few times and fall back to the last
- * values that validated.  Handles the 12-hour PM flag (hour bit 7). */
-static void rtc_read_time(unsigned int *hour, unsigned int *minute,
-			  unsigned int *second)
+static unsigned int rtc_decode(unsigned char v, int bcd)
+{
+	if (!bcd)
+		return v;
+	return (unsigned int)((v >> 4) * 10 + (v & 0x0F));
+}
+
+static unsigned char rtc_encode(unsigned int v, int bcd)
+{
+	if (!bcd)
+		return (unsigned char)v;
+	return (unsigned char)(((v / 10) << 4) | (v % 10));
+}
+
+static int digits_ok(unsigned char v, int bcd)
+{
+	return !bcd || bcd_digits(v);
+}
+
+/* The RTC's update-in-progress bit stays set for about 2 ms. */
+static int rtc_wait_ready(void)
+{
+	unsigned int n = 0;
+
+	while ((cmos_read(RTC_REGA) & 0x80) && ++n < 10000)
+		;
+	return (cmos_read(RTC_REGA) & 0x80) ? -1 : 0;
+}
+
+static unsigned int days_in_month(unsigned int y, unsigned int m)
+{
+	static const unsigned char dm[12] = {
+		31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
+	};
+
+	if (m < 1 || m > 12)
+		return 0;
+	if (m == 2 && ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0))
+		return 29;
+	return dm[m - 1];
+}
+
+/* Sakamoto's algorithm; 0 = Sunday. */
+static unsigned int weekday_of(unsigned int y, unsigned int m, unsigned int d)
+{
+	static const unsigned char t[12] = {
+		0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4
+	};
+
+	if (m < 3)
+		y -= 1;
+	return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;
+}
+
+/* The RTC only stores two digits.  A dead CMOS battery commonly leaves 1980
+ * or 1990, so decode with the usual 1970-2069 window instead of assuming
+ * 20xx: 70..99 -> 19xx, 00..69 -> 20xx.  This keeps pre-2000 defaults in the
+ * past and still maps the current date correctly. */
+static unsigned int expand_year(unsigned int yy)
+{
+	return (yy >= 70) ? 1900 + yy : 2000 + yy;
+}
+
+struct rtc_raw {
+	unsigned char sec, min, hour, day, mon, year;
+};
+
+static void rtc_read_raw(struct rtc_raw *r)
 {
-	static unsigned int last_h, last_m, last_s;
+	r->sec  = cmos_read(RTC_SEC);
+	r->min  = cmos_read(RTC_MIN);
+	r->hour = cmos_read(RTC_HOUR);
+	r->day  = cmos_read(RTC_DAY);
+	r->mon  = cmos_read(RTC_MON);
+	r->year = cmos_read(RTC_YEAR);
+}
+
+/* Read all fields twice and require the raw bytes to agree, so a read that
+ * straddles an update is retried rather than decoded as a torn value.
+ * Register B selects BCD/binary and 12/24-hour mode; both are honoured. */
+static int rtc_read_fields(struct sys_datetime *out)
+{
+	struct rtc_raw a, b;
+	unsigned char regb;
 	unsigned int tries;
 
+	regb = cmos_read(RTC_REGB);
 	for (tries = 0; tries < 4; tries++) {
-		unsigned int n = 0;
-		unsigned char s, m, h;
-		unsigned int sv, mv, hv;
-
-		while ((cmos_read(0x0A) & 0x80) && ++n < 10000)
-			;
+		int is_bcd = !(regb & 0x04);
+		/* Register B bit 1 is the 24-hour select: 1 = 24-hour,
+		 * 0 = 12-hour with bit 7 of the hour as the PM flag. */
+		int is_12h = (regb & 0x02) == 0;
+		unsigned int sec, min, hour, day, mon, yy, year;
+		unsigned int pm;
 
-		s = cmos_read(0x00);
-		m = cmos_read(0x02);
-		h = (unsigned char)(cmos_read(0x04) & 0x7F);   /* drop the PM flag */
+		if (rtc_wait_ready() != 0)
+			continue;
+		rtc_read_raw(&a);
+		if (rtc_wait_ready() != 0)
+			continue;
+		rtc_read_raw(&b);
+		if (a.sec != b.sec || a.min != b.min || a.hour != b.hour ||
+		    a.day != b.day || a.mon != b.mon || a.year != b.year)
+			continue;
 
-		if (!bcd_digits(s) || !bcd_digits(m) || !bcd_digits(h))
+		if (!digits_ok(a.sec, is_bcd) ||
+		    !digits_ok(a.min, is_bcd) ||
+		    !digits_ok((unsigned char)(a.hour & 0x7F), is_bcd) ||
+		    !digits_ok(a.day, is_bcd) ||
+		    !digits_ok(a.mon, is_bcd) ||
+		    !digits_ok(a.year, is_bcd))
 			continue;
 
-		sv = bcd_to_bin(s);
-		mv = bcd_to_bin(m);
-		hv = bcd_to_bin(h);
-		if (sv > 59 || mv > 59 || hv > 23)
+		sec = rtc_decode(a.sec, is_bcd);
+		min = rtc_decode(a.min, is_bcd);
+		pm = (is_12h && (a.hour & 0x80)) ? 1 : 0;
+		hour = rtc_decode((unsigned char)(a.hour & 0x7F), is_bcd);
+		if (is_12h) {
+			if (hour == 12)
+				hour = pm ? 12 : 0;
+			else if (pm)
+				hour += 12;
+		}
+		day = rtc_decode(a.day, is_bcd);
+		mon = rtc_decode(a.mon, is_bcd);
+		yy = rtc_decode(a.year, is_bcd);
+		year = expand_year(yy);
+
+		if (sec > 59 || min > 59 || hour > 23 ||
+		    mon < 1 || mon > 12 || yy > 99 ||
+		    day < 1 || day > days_in_month(year, mon))
 			continue;
 
-		last_h = hv;
-		last_m = mv;
-		last_s = sv;
-		break;
+		out->year = year;
+		out->month = mon;
+		out->day = day;
+		out->hour = hour;
+		out->minute = min;
+		out->second = sec;
+		out->wday = weekday_of(year, mon, day);
+		return 0;
 	}
+	return -1;
+}
 
-	*hour = last_h;
-	*minute = last_m;
-	*second = last_s;
+void rtc_read_datetime_full(struct sys_datetime *out)
+{
+	if (!out)
+		return;
+	if (rtc_read_fields(out) == 0) {
+		last_dt = *out;
+		return;
+	}
+	*out = last_dt;
 }
 
 void rtc_read_datetime(char *buf)
 {
-	static unsigned int last_d = 1, last_mo = 1, last_y = 2000;
-	unsigned int s, m, h, d, mo, y;
-	unsigned char dd, mm, yy;
+	struct sys_datetime dt;
+	unsigned int y, mo, d, h, m, s;
 
-	rtc_read_time(&h, &m, &s);
-
-	/* Date registers (a torn read keeps the last good values). */
-	{
-		unsigned int n = 0;
-
-		while ((cmos_read(0x0A) & 0x80) && ++n < 10000)
-			;
-	}
-	dd = cmos_read(0x07);
-	mm = cmos_read(0x08);
-	yy = cmos_read(0x09);
-	if (bcd_digits(dd) && bcd_to_bin(dd) >= 1 && bcd_to_bin(dd) <= 31)
-		last_d = bcd_to_bin(dd);
-	if (bcd_digits(mm) && bcd_to_bin(mm) >= 1 && bcd_to_bin(mm) <= 12)
-		last_mo = bcd_to_bin(mm);
-	if (bcd_digits(yy))
-		last_y = 2000 + bcd_to_bin(yy);
-
-	d = last_d;
-	mo = last_mo;
-	y = last_y;
-	if (y < 2000)
-		y += 100;
+	rtc_read_datetime_full(&dt);
+	y = dt.year;
+	mo = dt.month;
+	d = dt.day;
+	h = dt.hour;
+	m = dt.minute;
+	s = dt.second;
 
 	buf[0]  = (char)('0' + (y / 1000));
 	buf[1]  = (char)('0' + ((y / 100) % 10));
@@ -121,5 +233,93 @@ void rtc_read_datetime(char *buf)
 
 void rtc_read_hms(unsigned int *hour, unsigned int *minute, unsigned int *second)
 {
-	rtc_read_time(hour, minute, second);
+	struct sys_datetime dt;
+
+	rtc_read_datetime_full(&dt);
+	if (hour)
+		*hour = dt.hour;
+	if (minute)
+		*minute = dt.minute;
+	if (second)
+		*second = dt.second;
+}
+
+int rtc_set_datetime(const struct sys_datetime *in)
+{
+	unsigned int year, mon, day, hour, min, sec, wday, yy, century_reg;
+	unsigned char regb, hour_raw;
+	int is_bcd, is_12h;
+
+	if (!in)
+		return -1;
+	year = in->year;
+	mon = in->month;
+	day = in->day;
+	hour = in->hour;
+	min = in->minute;
+	sec = in->second;
+
+	if (year < 1970 || year > 2069 ||
+	    mon < 1 || mon > 12 ||
+	    day < 1 || day > days_in_month(year, mon) ||
+	    hour > 23 || min > 59 || sec > 59)
+		return -1;
+
+	/* Read register B before the SET sequence so the RTC's BCD/binary and
+	 * 12/24-hour mode survive the write. */
+	regb = cmos_read(RTC_REGB);
+	if (rtc_wait_ready() != 0)
+		return -1;
+	is_bcd = !(regb & 0x04);
+	is_12h = (regb & 0x02) == 0;
+
+	if (is_12h) {
+		unsigned int h12, pm = 0;
+
+		if (hour == 0) {
+			h12 = 12;
+		} else if (hour < 12) {
+			h12 = hour;
+		} else if (hour == 12) {
+			h12 = 12;
+			pm = 1;
+		} else {
+			h12 = hour - 12;
+			pm = 1;
+		}
+		hour_raw = (unsigned char)(rtc_encode(h12, is_bcd) |
+					   (pm ? 0x80 : 0));
+	} else {
+		hour_raw = rtc_encode(hour, is_bcd);
+	}
+
+	wday = weekday_of(year, mon, day);
+	yy = year % 100;
+	/* The FADT points at the RTC century byte on ACPI machines.  Writing it
+	 * keeps the two-digit year in the intended century for the firmware and
+	 * any other OS; old non-ACPI boards do not get an arbitrary NVRAM write,
+	 * and the kernel's 1970-2069 read window still gives 19xx years. */
+	century_reg = acpi_rtc_century_reg();
+
+	cmos_write(RTC_REGB, (unsigned char)(regb | 0x80));
+	cmos_write(RTC_SEC, rtc_encode(sec, is_bcd));
+	cmos_write(RTC_MIN, rtc_encode(min, is_bcd));
+	cmos_write(RTC_HOUR, hour_raw);
+	cmos_write(RTC_WDAY, rtc_encode(wday + 1, is_bcd));
+	cmos_write(RTC_DAY, rtc_encode(day, is_bcd));
+	cmos_write(RTC_MON, rtc_encode(mon, is_bcd));
+	cmos_write(RTC_YEAR, rtc_encode(yy, is_bcd));
+	if (century_reg)
+		cmos_write((unsigned char)century_reg,
+			   rtc_encode(year / 100, is_bcd));
+	cmos_write(RTC_REGB, (unsigned char)(regb & 0x7F));
+
+	last_dt.year = year;
+	last_dt.month = mon;
+	last_dt.day = day;
+	last_dt.hour = hour;
+	last_dt.minute = min;
+	last_dt.second = sec;
+	last_dt.wday = wday;
+	return 0;
 }

+ 12 - 0
rtc.h

@@ -1,10 +1,22 @@
 #ifndef RTC_H
 #define RTC_H
 
+#include "syscall.h"
+
 /* Write formatted date/time into buf: "YYYY-MM-DD HH:MM:SS" (19 chars + NUL). */
 void rtc_read_datetime(char *buf);
 
 /* Read current hour (0-23), minute (0-59), second (0-59). */
 void rtc_read_hms(unsigned int *hour, unsigned int *minute, unsigned int *second);
 
+/* Read the full date/time.  The two-digit RTC year is expanded with a
+ * 1970-2069 window (70-99 -> 1900s, 00-69 -> 2000s), so a dead-battery
+ * default such as 1980 or 1990 stays in the past.  A failed read keeps the
+ * last good value. */
+void rtc_read_datetime_full(struct sys_datetime *out);
+
+/* Validate and write the RTC; returns 0 on success, -1 on a bad field or a
+ * write that could not be sequenced (see rtc.c).  Accepts 1970-2069. */
+int rtc_set_datetime(const struct sys_datetime *in);
+
 #endif

+ 24 - 0
syscall.c

@@ -207,6 +207,30 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 			out[i] = buf[i];
 		return 0;
 	}
+	case SYS_RTC_GET: {
+		struct sys_datetime dt;
+		struct sys_datetime *out = (struct sys_datetime *)a1;
+
+		if (!paging_user_range_ok(current_proc()->cr3, (unsigned int)out,
+					  sizeof(dt), 1))
+			return -1;
+		rtc_read_datetime_full(&dt);
+		*out = dt;
+		return 0;
+	}
+	case SYS_RTC_SET: {
+		struct sys_datetime dt;
+		const unsigned char *in = (const unsigned char *)a1;
+		unsigned char *d = (unsigned char *)&dt;
+		unsigned int i;
+
+		if (!paging_user_range_ok(current_proc()->cr3, (unsigned int)in,
+					  sizeof(dt), 0))
+			return -1;
+		for (i = 0; i < sizeof(dt); i++)
+			d[i] = in[i];
+		return rtc_set_datetime(&dt);
+	}
 	case SYS_WM_ATTACH:
 		return sys_wm_attach((struct wm_screen_info *)a1);
 	case SYS_WM_INFO:

+ 16 - 0
syscall.h

@@ -74,6 +74,8 @@
 				-> 1 when found, 0 at the end of the table */
 #define SYS_KEY_POLL     55  /* () -> 0 none, ASCII, or IO_KEY_* for the caller's window */
 #define SYS_RTC_HMS      56  /* (struct sys_time *out) -> 0/-1 */
+#define SYS_RTC_GET     104  /* (struct sys_datetime *out) -> 0/-1 */
+#define SYS_RTC_SET     105  /* (const struct sys_datetime *in) -> 0/-1 */
 
 /* Window-manager service (see wm_abi.h).  Only the kernel-spawned WM process
  * may call the WM_* entries; ordinary commands get -1. */
@@ -319,6 +321,20 @@ struct sys_time {
 	unsigned int second;   /* 0-59 */
 };
 
+/* Full RTC wall clock for `date` and the Date & Time app.  The CMOS RTC
+ * stores a two-digit year; the kernel expands it with a 1970-2069 window
+ * (70-99 -> 1900s, 00-69 -> 2000s), so a dead-battery default such as 1980
+ * or 1990 reads correctly.  SYS_RTC_SET accepts the same range. */
+struct sys_datetime {
+	unsigned int year;     /* 1970-2069 */
+	unsigned int month;    /* 1-12 */
+	unsigned int day;      /* 1-31 */
+	unsigned int hour;     /* 0-23 */
+	unsigned int minute;   /* 0-59 */
+	unsigned int second;   /* 0-59 */
+	unsigned int wday;     /* 0 = Sunday */
+};
+
 struct sys_e820 {
 	unsigned int base;      /* low 32 bits, as meminfo always printed */
 	unsigned int length;

+ 142 - 0
ucmd_date.c

@@ -0,0 +1,142 @@
+/* date: print the RTC date and time in the classic Linux format.
+ *
+ * No timezone database exists in NebOS, so the default output has no zone
+ * suffix; the CMOS RTC is the system's wall clock.  A small +FORMAT subset
+ * is supported for scripts and quick checks. */
+
+#include "ucmd_lib.h"
+
+static const char *const wday_abbr[7] = {
+	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+};
+static const char *const wday_full[7] = {
+	"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
+	"Saturday"
+};
+static const char *const mon_abbr[12] = {
+	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
+	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+};
+static const char *const mon_full[12] = {
+	"January", "February", "March", "April", "May", "June",
+	"July", "August", "September", "October", "November", "December"
+};
+
+static void put2(unsigned int v)
+{
+	u_putc((char)('0' + (v / 10) % 10));
+	u_putc((char)('0' + v % 10));
+}
+
+static void put_year(unsigned int y)
+{
+	u_putc((char)('0' + (y / 1000) % 10));
+	u_putc((char)('0' + (y / 100) % 10));
+	u_putc((char)('0' + (y / 10) % 10));
+	u_putc((char)('0' + y % 10));
+}
+
+static void put_e(unsigned int d)
+{
+	if (d < 10)
+		u_putc(' ');
+	else
+		u_putc((char)('0' + d / 10));
+	u_putc((char)('0' + d % 10));
+}
+
+static void format(const char *fmt, const struct sys_datetime *dt)
+{
+	for (; *fmt; fmt++) {
+		char c;
+
+		if (*fmt != '%') {
+			u_putc(*fmt);
+			continue;
+		}
+		fmt++;
+		c = *fmt;
+		if (!c)
+			return;
+		switch (c) {
+		case 'Y':
+			put_year(dt->year);
+			break;
+		case 'y':
+			put2(dt->year % 100);
+			break;
+		case 'm':
+			put2(dt->month);
+			break;
+		case 'd':
+			put2(dt->day);
+			break;
+		case 'e':
+			put_e(dt->day);
+			break;
+		case 'H':
+			put2(dt->hour);
+			break;
+		case 'M':
+			put2(dt->minute);
+			break;
+		case 'S':
+			put2(dt->second);
+			break;
+		case 'a':
+			u_puts(wday_abbr[dt->wday % 7]);
+			break;
+		case 'A':
+			u_puts(wday_full[dt->wday % 7]);
+			break;
+		case 'b':
+			u_puts(mon_abbr[(dt->month - 1) % 12]);
+			break;
+		case 'B':
+			u_puts(mon_full[(dt->month - 1) % 12]);
+			break;
+		case 'p':
+			u_puts(dt->hour < 12 ? "AM" : "PM");
+			break;
+		case 'F':
+			format("%Y-%m-%d", dt);
+			break;
+		case 'T':
+			format("%H:%M:%S", dt);
+			break;
+		case '%':
+			u_putc('%');
+			break;
+		default:
+			u_putc('%');
+			u_putc(c);
+			break;
+		}
+	}
+}
+
+void _start(const char *arg)
+{
+	struct sys_datetime dt;
+	const char *fmt = "%a %b %e %H:%M:%S %Y";
+
+	if (u_rtc_get(&dt) != 0) {
+		u_puts("date: cannot read the RTC\n");
+		u_exit(1);
+	}
+
+	if (arg) {
+		while (*arg == ' ' || *arg == '\t')
+			arg++;
+		if (*arg == '+') {
+			fmt = arg + 1;
+		} else if (*arg) {
+			u_puts("usage: date [+FORMAT]\n");
+			u_exit(1);
+		}
+	}
+
+	format(fmt, &dt);
+	u_putc('\n');
+	u_exit(0);
+}

+ 12 - 0
ucmd_lib.h

@@ -182,6 +182,18 @@ static inline int u_rtc_datetime(char *buf, unsigned int max)
 	return u_syscall2(SYS_RTC_DATETIME, (int)buf, (int)max);
 }
 
+/* Full RTC date/time (year 1970-2069) and its setter.  The setter validates
+ * the fields and returns 0 on success. */
+static inline int u_rtc_get(struct sys_datetime *t)
+{
+	return u_syscall1(SYS_RTC_GET, (int)t);
+}
+
+static inline int u_rtc_set(const struct sys_datetime *t)
+{
+	return u_syscall1(SYS_RTC_SET, (int)t);
+}
+
 /* Window-manager service (only the kernel-spawned /ramfs/bin/wm may use it). */
 static inline int u_wm_attach(struct wm_screen_info *out)
 {

+ 346 - 0
ucmd_settime.c

@@ -0,0 +1,346 @@
+/* settime: Date & Time editor.
+ *
+ * A small ngui canvas window that reads the CMOS RTC through SYS_RTC_GET and
+ * writes it through SYS_RTC_SET.  The RTC stores a two-digit year, so the
+ * kernel expands it with a 1970-2069 window; this app accepts the same range
+ * so a dead-battery default such as 1980 or 1990 can be corrected. */
+
+#include "ucmd_lib.h"
+#include "ngui.h"
+
+#define ID_DATE 1
+#define ID_TIME 2
+#define ID_SET  3
+#define ID_NOW  4
+
+#define ACT_SET (1u << 0)
+#define ACT_NOW (1u << 1)
+
+static struct ngui ui;
+static struct ngui_input date_in;
+static struct ngui_input time_in;
+static struct sys_datetime current;
+static char status[64];
+static int status_error;
+static unsigned int status_until;
+static unsigned int last_second;
+
+static unsigned int s_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s && s[n])
+		n++;
+	return n;
+}
+
+static unsigned int days_in_month(unsigned int y, unsigned int m)
+{
+	static const unsigned char dm[12] = {
+		31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
+	};
+
+	if (m < 1 || m > 12)
+		return 0;
+	if (m == 2 && ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0))
+		return 29;
+	return dm[m - 1];
+}
+
+static char *put_2(char *p, unsigned int v)
+{
+	*p++ = (char)('0' + (v / 10) % 10);
+	*p++ = (char)('0' + v % 10);
+	return p;
+}
+
+static char *put_date(char *p, const struct sys_datetime *dt)
+{
+	*p++ = (char)('0' + (dt->year / 1000) % 10);
+	*p++ = (char)('0' + (dt->year / 100) % 10);
+	*p++ = (char)('0' + (dt->year / 10) % 10);
+	*p++ = (char)('0' + dt->year % 10);
+	*p++ = '-';
+	p = put_2(p, dt->month);
+	*p++ = '-';
+	p = put_2(p, dt->day);
+	return p;
+}
+
+static char *put_time(char *p, const struct sys_datetime *dt)
+{
+	p = put_2(p, dt->hour);
+	*p++ = ':';
+	p = put_2(p, dt->minute);
+	*p++ = ':';
+	p = put_2(p, dt->second);
+	return p;
+}
+
+static void set_status(const char *msg, int err)
+{
+	unsigned int i;
+
+	for (i = 0; msg[i] && i + 1 < sizeof(status); i++)
+		status[i] = msg[i];
+	status[i] = '\0';
+	status_error = err;
+	status_until = u_ticks_ms() + 4000;
+	ngui_invalidate(&ui);
+}
+
+static void load_current(int fill_fields)
+{
+	struct sys_datetime dt;
+	char b[24];
+	char *p;
+
+	if (u_rtc_get(&dt) != 0) {
+		set_status("Cannot read the RTC", 1);
+		return;
+	}
+	current = dt;
+	if (!fill_fields)
+		return;
+	p = put_date(b, &dt);
+	*p = '\0';
+	ngui_input_set(&date_in, b);
+	p = put_time(b, &dt);
+	*p = '\0';
+	ngui_input_set(&time_in, b);
+}
+
+static int parse_num(const char *s, unsigned int n, unsigned int *out)
+{
+	unsigned int v = 0, i;
+
+	if (!n)
+		return -1;
+	for (i = 0; i < n; i++) {
+		if (s[i] < '0' || s[i] > '9')
+			return -1;
+		v = v * 10 + (unsigned int)(s[i] - '0');
+	}
+	*out = v;
+	return 0;
+}
+
+static int parse_date(const char *s, unsigned int *y, unsigned int *mo,
+		      unsigned int *d)
+{
+	if (s_len(s) != 10)
+		return -1;
+	if ((s[4] != '-' && s[4] != '/') ||
+	    (s[7] != '-' && s[7] != '/'))
+		return -1;
+	if (parse_num(s, 4, y) != 0 ||
+	    parse_num(s + 5, 2, mo) != 0 ||
+	    parse_num(s + 8, 2, d) != 0)
+		return -1;
+	return 0;
+}
+
+static int parse_time(const char *s, unsigned int *h, unsigned int *mi,
+		      unsigned int *sec)
+{
+	unsigned int len = s_len(s);
+
+	if (len == 5) {
+		*sec = 0;
+	} else if (len == 8) {
+		if (s[5] != ':' || parse_num(s + 6, 2, sec) != 0)
+			return -1;
+	} else {
+		return -1;
+	}
+	if (s[2] != ':' ||
+	    parse_num(s, 2, h) != 0 ||
+	    parse_num(s + 3, 2, mi) != 0)
+		return -1;
+	return 0;
+}
+
+static void apply_now(void)
+{
+	struct sys_datetime dt;
+	unsigned int y, mo, d, h, mi, s;
+
+	if (parse_date(date_in.text, &y, &mo, &d) != 0) {
+		set_status("Date must be YYYY-MM-DD", 1);
+		return;
+	}
+	if (parse_time(time_in.text, &h, &mi, &s) != 0) {
+		set_status("Time must be HH:MM:SS", 1);
+		return;
+	}
+	if (y < 1970 || y > 2069) {
+		set_status("Year must be 1970-2069", 1);
+		return;
+	}
+	if (mo < 1 || mo > 12) {
+		set_status("Month must be 1-12", 1);
+		return;
+	}
+	if (d < 1 || d > days_in_month(y, mo)) {
+		set_status("Day is not valid for that month", 1);
+		return;
+	}
+	if (h > 23 || mi > 59 || s > 59) {
+		set_status("Time is out of range", 1);
+		return;
+	}
+
+	dt.year = y;
+	dt.month = mo;
+	dt.day = d;
+	dt.hour = h;
+	dt.minute = mi;
+	dt.second = s;
+	dt.wday = 0;             /* the kernel recomputes the weekday */
+	if (u_rtc_set(&dt) != 0) {
+		set_status("RTC write failed", 1);
+		return;
+	}
+	load_current(1);
+	set_status("Date and time updated", 0);
+}
+
+static unsigned int draw(void)
+{
+	struct ngui_rect body, r, date_r, time_r, set_r, now_r;
+	unsigned int action = 0;
+	char line[64];
+	char *p;
+
+	body.x = 0;
+	body.y = 0;
+	body.w = ui.w;
+	body.h = ui.h;
+	ngui_fill_rect(&ui, body, ui.theme.bg);
+	ngui_inset(&body, 16);
+
+	r = ngui_cut_top(&body, 24);
+	ngui_text(&ui, r.x, r.y, "System date and time", ui.theme.text);
+
+	p = line;
+	{
+		static const char prefix[] = "Current: ";
+		unsigned int i;
+
+		for (i = 0; prefix[i]; i++)
+			*p++ = prefix[i];
+	}
+	p = put_date(p, &current);
+	*p++ = ' ';
+	p = put_time(p, &current);
+	*p = '\0';
+	r = ngui_cut_top(&body, 24);
+	ngui_text(&ui, r.x, r.y, line, ui.theme.text_dim);
+
+	r = ngui_cut_top(&body, 18);
+	ngui_text(&ui, r.x, r.y, "Date (YYYY-MM-DD)", ui.theme.text_dim);
+	date_r = ngui_cut_top(&body, 32);
+	ngui_cut_top(&body, 8);
+	r = ngui_cut_top(&body, 18);
+	ngui_text(&ui, r.x, r.y, "Time (HH:MM:SS)", ui.theme.text_dim);
+	time_r = ngui_cut_top(&body, 32);
+	ngui_cut_top(&body, 8);
+
+	if (ngui_text_input(&ui, ID_DATE, date_r, &date_in) &
+	    NGUI_INPUT_SUBMIT)
+		action |= ACT_SET;
+	if (ngui_text_input(&ui, ID_TIME, time_r, &time_in) &
+	    NGUI_INPUT_SUBMIT)
+		action |= ACT_SET;
+
+	r = ngui_cut_top(&body, 40);
+	set_r = r;
+	set_r.w = 96;
+	now_r = r;
+	now_r.x = r.x + 104;
+	now_r.w = 96;
+	if (ngui_button(&ui, ID_SET, set_r, "Set"))
+		action |= ACT_SET;
+	if (ngui_button(&ui, ID_NOW, now_r, "Now"))
+		action |= ACT_NOW;
+
+	r = ngui_cut_top(&body, 24);
+	if (status[0] && status_until &&
+	    (int)(u_ticks_ms() - status_until) < 0)
+		ngui_text(&ui, r.x, r.y, status,
+			  status_error ? ui.theme.error : ui.theme.accent);
+
+	r = ngui_cut_top(&body, 20);
+	ngui_text(&ui, r.x, r.y,
+		  "RTC year range: 1970-2069.  Enter applies the change.",
+		  ui.theme.text_dim);
+
+	return action;
+}
+
+void _start(const char *arg)
+{
+	struct win_info wi;
+	int quit = 0;
+
+	(void)arg;
+	if (u_win_create(460, 320, "Date & Time", &wi) != 0) {
+		u_puts("settime: no graphics window\n");
+		u_exit(1);
+	}
+	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
+	ngui_font_attach(&ui);
+	date_in.placeholder = "YYYY-MM-DD";
+	time_in.placeholder = "HH:MM:SS";
+
+	if (u_rtc_get(&current) == 0) {
+		char b[24];
+		char *p;
+
+		p = put_date(b, &current);
+		*p = '\0';
+		ngui_input_set(&date_in, b);
+		p = put_time(b, &current);
+		*p = '\0';
+		ngui_input_set(&time_in, b);
+	} else {
+		set_status("Cannot read the RTC", 1);
+	}
+
+	for (;;) {
+		unsigned int now = u_ticks_ms();
+		unsigned int action = 0;
+
+		if (status_until && (int)(now - status_until) >= 0) {
+			status[0] = '\0';
+			status_until = 0;
+			status_error = 0;
+			ngui_invalidate(&ui);
+		}
+		if (now - last_second >= 1000) {
+			last_second = now;
+			load_current(0);
+			ngui_invalidate(&ui);
+		}
+
+		if (!ngui_begin(&ui)) {
+			u_sleep_ms(10);
+			continue;
+		}
+		action = draw();
+		if (ui.focus == 0 && ngui_key_peek(&ui) == NGUI_KEY_ESC) {
+			ngui_key(&ui);
+			quit = 1;
+		}
+		ngui_end(&ui);
+		if (action & ACT_SET)
+			apply_now();
+		if (action & ACT_NOW)
+			load_current(1);
+		if (quit)
+			break;
+		u_sleep_ms(10);
+	}
+	u_win_close();
+	u_exit(0);
+}

+ 43 - 5
ucmd_wm.c

@@ -40,6 +40,11 @@ static int bar_batt_ac;
 static char bar_msg[24];
 static unsigned int bar_msg_until;
 static int bar_msg_dirty;
+/* Rectangle of the right-aligned date/time text, so a click there can open
+ * the Date & Time app.  w == 0 means "not drawn" (e.g. kexec banner). */
+static int bar_clock_x = -1;
+static unsigned int bar_clock_w;
+static int bar_clock_hot;
 static unsigned int stat_frames, stat_ms, stat_px, stat_max, stat_last;
 
 static void bar_notice(const char *msg)
@@ -212,6 +217,9 @@ static void draw_bar(void)
 		unsigned int dots = bar_kexec_total ?
 			(bar_kexec_progress * 12 / bar_kexec_total) : 0;
 
+		bar_clock_x = -1;
+		bar_clock_w = 0;
+		bar_clock_hot = 0;
 		n = 0;
 		while (msg[n])
 			dt[n] = msg[n], n++;
@@ -227,14 +235,24 @@ static void draw_bar(void)
 		int right = (int)fbw - 4;
 		int min_x = WM_BTN_GALLERY_X + (int)WM_BTN_GALLERY_W + 4;
 
+		bar_clock_x = -1;
+		bar_clock_w = 0;
 		if (u_rtc_datetime(dt, sizeof(dt)) == 0) {
+			int tw = (int)usurf_text_width(&screen, dt);
+			int tx = right - tw;
+
 			n = 0;
 			while (dt[n] && n < sizeof(dt) - 1)
 				n++;
-			usurf_text(&screen,
-				   right - (int)usurf_text_width(&screen, dt),
-				   5, dt, COL_BANNER, 0, 0, fbw, WM_BAR_H);
-			clock_chars = (unsigned int)usurf_text_width(&screen, dt);
+			bar_clock_x = tx;
+			bar_clock_w = (unsigned int)tw;
+			if (bar_clock_hot)
+				usurf_fill(&screen, tx - 5, 2,
+					   (unsigned int)tw + 10,
+					   WM_BAR_H - 4, 0x3A3A55u);
+			usurf_text(&screen, tx, 5, dt, COL_BANNER, 0, 0,
+				   fbw, WM_BAR_H);
+			clock_chars = (unsigned int)tw;
 		}
 		if (clock_chars)
 			right -= (int)clock_chars + 8;
@@ -584,6 +602,15 @@ static void move_window_pixels(struct uwin *u, int ox, int oy, int nx, int ny)
 	u_wm_present(&present);
 }
 
+/* The top-bar date/time text is also a button: it opens the Date & Time
+ * editor.  The rectangle is recorded by draw_bar(). */
+static int bar_clock_hit(unsigned int mx, unsigned int my)
+{
+	return bar_clock_w && bar_clock_x >= 0 && my < WM_BAR_H &&
+	       (int)mx >= bar_clock_x - 5 &&
+	       (int)mx < bar_clock_x + (int)bar_clock_w + 5;
+}
+
 static void do_update(struct wm_status *st)
 {
 	struct wm_present_info present;
@@ -625,6 +652,15 @@ static void do_update(struct wm_status *st)
 	if (kexec_changed)
 		bar_dirty = 1;
 
+	{
+		int hot = bar_clock_hit(st->mouse.x, st->mouse.y);
+
+		if (hot != bar_clock_hot) {
+			bar_clock_hot = hot;
+			bar_dirty = 1;
+		}
+	}
+
 	/* Refresh cached window state and mappings before opening a frame:
 	 * MAP may unmap/remap content. */
 	for (i = 0; i < WM_MAX_WINDOWS; i++) {
@@ -822,7 +858,9 @@ static void handle_mouse(struct wm_status *st)
 	int was = (prev_buttons & 1) != 0;
 
 	if (down && !was) {
-		if (mx >= WM_BTN_X && my >= WM_BTN_Y &&
+		if (bar_clock_hit(mx, my)) {
+			spawn_app_checked("/ramfs/bin/settime");
+		} else if (mx >= WM_BTN_X && my >= WM_BTN_Y &&
 		    mx < WM_BTN_X + WM_BTN_W && my < WM_BTN_Y + WM_BTN_H) {
 			if (!free_window_slot()) {
 				bar_notice("window limit");