Repository navigation
Expand file tree
/
Copy pathinit.c
More file actions
1619 lines (1484 loc) · 62.9 KB
/
Copy pathinit.c
File metadata and controls
1619 lines (1484 loc) · 62.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define FDCLOSE_EXTERN
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/mount.h>
#include <sys/reboot.h>
#include <termios.h>
#include <sys/stat.h>
#include <time.h>
#include <errno.h>
#include "schema.h"
#include "engine.h"
#include "service.h"
#include "svc_dropins.h"
#include "check.h"
#include "reexec_state.h"
#include "notify.h"
#include "fdstore.h"
#include "coredump.h"
#include "rail.h"
#include "rail_console.h"
#include <linux/fb.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <linux/capability.h>
#include "group.h"
#include "schema_shm.h"
#include "recorder.h"
#include "static_nodes.h"
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdarg.h>
#include <poll.h>
#include <sys/signalfd.h>
#include <glob.h>
#include <link.h>
#include <stdint.h>
#include <sys/ioctl.h>
#include <grp.h>
#include <sys/inotify.h>
#include <linux/watchdog.h>
#include <dirent.h>
#include <mntent.h>
static int lock_segment(struct dl_phdr_info *info, size_t size, void *arg) {
(void)size;
(void)arg;
long pg = sysconf(_SC_PAGESIZE);
for (int i = 0; i < info->dlpi_phnum; i++) {
const ElfW(Phdr) *ph = &info->dlpi_phdr[i];
if (ph->p_type != PT_LOAD) continue;
uintptr_t a = (info->dlpi_addr + ph->p_vaddr) & ~(uintptr_t)(pg - 1);
uintptr_t e = info->dlpi_addr + ph->p_vaddr + ph->p_memsz;
mlock((void *)a, e - a);
}
return 0;
}
#define MAX_MOUNTS 128 /* shutdown remount-ro sweep */
static uint64_t last_stall_ms = 0;
static uint64_t last_reclaim_ms = 0;
#define CPU_CHECK_MS 2000 /* critical cpu.pressure avg10 read rate */
static int cpu_stalled = 0;
static int stall_causes = 0; /* 1 memory, 2 critical cpu; this episode */
/*
* IEC 62304 / ISO 26262 Safety Audit Traceability:
*
* This function (watchdog_pet) implements the safety-critical "Dead Man's Token" watchdog.
* It ensures that if any critical system service hangs (e.g. motor controller SPI deadlock),
* PID 1 will detect the missed check-in window and intentionally withhold the heartbeats
* to /dev/watchdog, causing the hardware watchdog chip to force-reset the system.
*
* Crucially, if PID 1 itself hangs, deadlocks, or blocks indefinitely (e.g., due to a main
* event loop lockup), no pets will be sent to /dev/watchdog. The hardware watchdog will
* naturally timeout and force-reboot the processor. This guarantees a safe failure cascade
* under all single-point failure modes.
*/
static int modprobe_one(const char *mod) {
pid_t pid = fork();
if (pid == 0) {
execl("/sbin/modprobe", "modprobe", mod, (char *)NULL);
_exit(127);
}
if (pid < 0) return -1;
int status;
waitpid(pid, &status, 0);
return (WIFEXITED(status) && WEXITSTATUS(status) == 0) ? 0 : -1;
}
static unsigned pci_hex(const char *dir, const char *attr) {
char path[300], buf[16] = "";
snprintf(path, sizeof path, "/sys/bus/pci/devices/%s/%s", dir, attr);
FILE *f = fopen(path, "r");
if (!f) return 0;
if (!fgets(buf, sizeof buf, f)) buf[0] = '\0';
fclose(f);
return (unsigned)strtoul(buf, NULL, 16);
}
static int sp5100_present(void) {
static const unsigned ids[][2] = {
{ 0x1002, 0x4385 }, { 0x1022, 0x780b }, { 0x1022, 0x790b }, { 0x1d94, 0x790b },
};
DIR *d = opendir("/sys/bus/pci/devices");
if (!d) return 0;
struct dirent *e;
int found = 0;
while (!found && (e = readdir(d))) {
if (e->d_name[0] == '.') continue;
unsigned v = pci_hex(e->d_name, "vendor"), dv = pci_hex(e->d_name, "device");
for (size_t i = 0; i < sizeof ids / sizeof ids[0]; i++)
if (v == ids[i][0] && dv == ids[i][1]) { found = 1; break; }
}
closedir(d);
return found;
}
/* sp5100_tco only drives the AMD/Hygon FCH SMBus devices in its PCI id
* table; on anything else (an AMD guest on q35 included) modprobe costs a
* fork+exec on the boot path and fails with "No such device". */
static void load_watchdog_module(void) {
if (getpid() != 1) return;
if (access("/sys/module/sp5100_tco", F_OK) == 0 || !sp5100_present()) return;
if (modprobe_one("sp5100_tco") == 0)
printf("[schema-init] loaded watchdog module (sp5100_tco)\n");
else
printf("[schema-init] watchdog module load failed (sp5100_tco)\n");
}
/* systemd-modules-load parity: every module named in the
* kernel command line's modules_load= and the modules-load.d drop-ins
* (*.conf in /etc, /run, /usr/local/lib, /usr/lib, /lib, read in systemd's
* order; one module per line; blanks and
* '#'/';' comments ignored) goes to one `modprobe -a -b` child, started early
* so it loads while the .svc files parse; modules_wait() holds the first
* spawn for it, since a service may need one (sysctl after br_netfilter,
* i2c-dev's nodes). Lets a node declare e.g. `tun` so devtmpfs creates
* /dev/net/tun. Runs after mount_pseudo() has devtmpfs mounted. */
#define MODLOAD_MAX 128
static pid_t modload_pid = -1;
static void load_configured_modules(void) {
if (getpid() != 1) return;
static char names[MODLOAD_MAX][256];
char *argv[MODLOAD_MAX + 4] = { "modprobe", "-a", "-b" };
int n = 0, full = 0;
static const char *const dirs[] = {
"/etc/modules-load.d", "/run/modules-load.d", "/usr/local/lib/modules-load.d",
"/usr/lib/modules-load.d", "/lib/modules-load.d", NULL };
const char *confs[MODLOAD_CONF_MAX];
char cl[4096] = "";
int dropped, nc = modload_conf_list(dirs, confs, MODLOAD_CONF_MAX, &dropped);
if (dropped)
printf("[schema-init] modules-load.d: more than %d drop-ins, %d ignored\n", MODLOAD_CONF_MAX, dropped);
int fd = open("/proc/cmdline", O_RDONLY | O_CLOEXEC);
if (fd >= 0) { ssize_t r = read(fd, cl, sizeof(cl) - 1); if (r > 0) cl[r] = '\0'; close(fd); }
n = cmdline_modules_load(cl, names, MODLOAD_MAX);
for (int i = 0; i < n; i++) argv[3 + i] = names[i];
for (int i = 0; i < nc && !full; i++) {
FILE *f = fopen(confs[i], "r");
if (!f) continue;
char line[256];
int r;
while ((r = svc_read_line(f, line, sizeof line)) != 0) {
char *p = line;
if (r < 0) {
printf("[schema-init] %s: line longer than %zu bytes — ignored\n",
confs[i], sizeof line - 1);
continue;
}
while (*p == ' ' || *p == '\t') p++;
if (*p == '#' || *p == ';' || *p == '\0') continue;
p[strcspn(p, " \t\r\n")] = '\0';
if (*p == '\0') continue;
if (n == MODLOAD_MAX) {
printf("[schema-init] modules-load.d: more than %d modules, '%s' and later ignored\n", MODLOAD_MAX, p);
full = 1;
break;
}
snprintf(names[n], sizeof names[n], "%s", p);
argv[3 + n] = names[n];
n++;
}
fclose(f);
}
if (!n) return;
modload_pid = fork();
if (modload_pid == 0) {
execv("/sbin/modprobe", argv);
_exit(127);
}
if (modload_pid < 0)
printf("[schema-init] modules-load.d: fork failed: %s\n", strerror(errno));
}
static void modules_wait(void) {
int st;
if (modload_pid <= 0) return;
while (waitpid(modload_pid, &st, 0) < 0 && errno == EINTR) ;
if (WIFEXITED(st) && WEXITSTATUS(st) == 0)
printf("[schema-init] modules-load.d: modules loaded\n");
else
printf("[schema-init] modules-load.d: modprobe -a failed (status %#x); its own messages name the module\n", st);
modload_pid = -1;
}
/* Any process left but PID 1 and kernel threads. A zombie counts: it is ours
* to reap until it is gone. So does a usermode helper the kernel started
* (the core_pattern pipe): its parent is kthreadd too. */
static int user_procs_left(void) {
DIR *d = opendir("/proc");
struct dirent *e;
int left = 0;
if (!d) return 1; /* can't look: wait out the cap */
while (!left && (e = readdir(d))) {
char p[64], st[512];
int pid = atoi(e->d_name);
if (pid <= 2) continue;
snprintf(p, sizeof p, "/proc/%d/stat", pid);
int fd = open(p, O_RDONLY | O_CLOEXEC);
if (fd < 0) continue;
ssize_t n = read(fd, st, sizeof st - 1);
close(fd);
if (n <= 0) continue;
st[n] = '\0';
left = proc_stat_is_user(st);
}
closedir(d);
return left;
}
static void pid1_hardening_default(void) {
char cmdline[4096] = "", hd[64] = "";
int fd = open("/proc/cmdline", O_RDONLY | O_CLOEXEC);
if (fd >= 0) { ssize_t n = read(fd, cmdline, sizeof(cmdline) - 1); if (n > 0) cmdline[n] = '\0'; close(fd); }
fd = open("/etc/schema-init/hardening-default", O_RDONLY | O_CLOEXEC);
int have = fd >= 0;
if (have) { ssize_t n = read(fd, hd, sizeof(hd) - 1); if (n > 0) hd[n] = '\0'; close(fd); }
int on = hardening_default_resolve(cmdline, have ? hd : NULL);
service_set_hardening_default(on);
fprintf(stderr, "[schema-init] hardening default: %s\n", on ? "ON" : "off");
}
static void rescue_boot(void) {
char cl[4096] = "";
int fd = open("/proc/cmdline", O_RDONLY | O_CLOEXEC);
if (fd >= 0) { ssize_t n = read(fd, cl, sizeof(cl) - 1); if (n > 0) cl[n] = '\0'; close(fd); }
if (!rescue_cmdline(cl)) return;
fprintf(stderr, "[schema-init] rescue boot requested on the kernel command line\n");
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "[schema-init] rescue shell: fork failed: %s\n", strerror(errno));
return;
}
if (pid == 0) {
service_reset_child_sigmask();
setsid();
int tty = open("/dev/console", O_RDWR);
if (tty >= 0) {
ioctl(tty, TIOCSCTTY, 1);
dup2(tty, STDIN_FILENO);
dup2(tty, STDOUT_FILENO);
dup2(tty, STDERR_FILENO);
if (tty > STDERR_FILENO) close(tty);
}
pid_t q = fork();
if (q == 0) {
execlp("plymouth", "plymouth", "--wait", "quit", (char *)NULL);
_exit(1);
}
if (q > 0) waitpid(q, NULL, 0);
printf("\n*** schema-init: rescue boot ***\n"
"No services are running and /etc/fstab is not mounted (mount -a).\n"
"Exit the shell to continue booting.\n\n");
fflush(stdout);
execl("/usr/sbin/sulogin", "sulogin", (char *)NULL);
execl("/sbin/sulogin", "sulogin", (char *)NULL);
execl("/bin/sh", "sh", (char *)NULL);
_exit(1);
}
while (waitpid(pid, NULL, 0) < 0 && errno == EINTR) ;
fprintf(stderr, "[schema-init] rescue shell exited, continuing boot\n");
}
/* Opt-in, like systemd's RuntimeWatchdogSec=: opening an iTCO arms a 30 s
* hardware reset behind PID 1 and wakes it every timeout/3 for good. */
static void watchdog_init(void) {
const char *paths[] = { "/dev/watchdog0", "/dev/watchdog", NULL };
char cl[4096] = "";
int i, fd = open("/proc/cmdline", O_RDONLY | O_CLOEXEC);
if (fd >= 0) { ssize_t n = read(fd, cl, sizeof(cl) - 1); if (n > 0) cl[n] = '\0'; close(fd); }
const char *why = watchdog_arm_reason(cl, access("/etc/schema-init/watchdog", F_OK) == 0,
services, svc_count);
if (!why) {
printf("[schema-init] hardware watchdog left closed (opt in: schema.watchdog=1, /etc/schema-init/watchdog, or watchdog_timeout_ms=)\n");
return;
}
for (i = 0; paths[i]; i++) {
watchdog_fd = open(paths[i], O_WRONLY | O_CLOEXEC);
if (watchdog_fd >= 0) {
int timeout = 0;
if (ioctl(watchdog_fd, WDIOC_GETTIMEOUT, &timeout) < 0) timeout = 0;
watchdog_pet_ms = wd_pet_ms(timeout);
printf("[schema-init] opened hardware watchdog (%s, timeout %ds, pet every %lldms): %s\n",
paths[i], timeout, (long long)watchdog_pet_ms, why);
break;
}
}
}
static void watchdog_close(void) {
if (watchdog_fd >= 0) {
/* Write 'V' before closing to indicate safe close/disable if supported */
write(watchdog_fd, "V", 1);
close(watchdog_fd);
watchdog_fd = -1;
}
}
static void watchdog_pet(void) {
if (watchdog_fd < 0) return;
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
int i;
int pet_ok = 1;
for (i = 0; i < svc_count && !notify_paused_since; i++) {
service_t *svc = &services[i];
if (svc->watchdog_timeout_ms > 0 && svc->child_pid > 0) {
long elapsed_ms = (now.tv_sec - svc->last_pet.tv_sec) * 1000 +
(now.tv_nsec - svc->last_pet.tv_nsec) / 1000000;
if (elapsed_ms > svc->watchdog_timeout_ms) {
printf("[schema-init] watchdog: service '%s' missed pet window (%ldms > %dms)\n",
svc->name, elapsed_ms, svc->watchdog_timeout_ms);
pet_ok = 0;
break;
}
}
}
if (pet_ok) {
write(watchdog_fd, "\0", 1);
}
}
/* ── PID 1 essentials ───────────────────────────────────────────────── */
static void mount_pseudo(void) {
/* only attempt mounts when we are PID 1 */
if (getpid() != 1) return;
/* kernel mounts rootfs ro for fsck; remount rw before anything else */
mount(NULL, "/", NULL, MS_REMOUNT, NULL);
mount("proc", "/proc", "proc", MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL);
mount("sysfs", "/sys", "sysfs", MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL);
mount("devtmpfs","/dev", "devtmpfs", MS_NOSUID|MS_STRICTATIME, NULL);
/* devtmpfs doesn't create these; userspace init must. Without them bash
* process substitution and /dev/std{in,out,err} fail. */
symlink("/proc/self/fd", "/dev/fd");
symlink("/proc/self/fd/0", "/dev/stdin");
symlink("/proc/self/fd/1", "/dev/stdout");
symlink("/proc/self/fd/2", "/dev/stderr");
mkdir("/dev/pts", 0755);
mount("devpts", "/dev/pts", "devpts", MS_NOSUID|MS_NOEXEC, "gid=5,mode=620,ptmxmode=666");
mkdir("/dev/shm", 01777);
mount("tmpfs", "/dev/shm", "tmpfs", MS_NOSUID|MS_NODEV, "mode=1777,nr_inodes=1m");
mount("tmpfs", "/run", "tmpfs", MS_NOSUID|MS_NODEV, "mode=0755,size=20%,nr_inodes=800k");
mount("cgroup2", "/sys/fs/cgroup", "cgroup2", MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_RELATIME, NULL);
mount("pstore", "/sys/fs/pstore", "pstore", MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL);
int cg_fd = open("/sys/fs/cgroup/cgroup.subtree_control", O_WRONLY);
if (cg_fd >= 0) {
write(cg_fd, "+cpu +memory +cpuset +pids +io", 30);
close(cg_fd);
}
mkdir("/run/dbus", 0755);
/* chmod too: mkdir is masked by the umask, and these must be world-writable */
mkdir("/run/lock", 01777); chmod("/run/lock", 01777);
mkdir("/run/shm", 01777); chmod("/run/shm", 01777);
mkdir("/run/user", 0755);
mkdir("/run/user/0", 0700);
mkdir("/run/systemd", 0755);
mkdir("/run/systemd/system", 0755); /* sd_booted() signal: libsystemd does access() here */
mkdir("/run/systemd/shutdown", 0755);
mkdir("/run/log", 0755);
mkdir("/run/log/schema-init", 0755);
mkdir("/run/sshd", 0755);
/* make / rshared so mount events propagate — podman and GLib/KDE mount
* monitors need this; systemd runs `mount --make-rshared /` at boot. Without
* it / stays private and mount-watching userspace spins (plasmashell 100%). */
mount(NULL, "/", NULL, MS_SHARED|MS_REC, NULL);
}
/* Records the kernel left in pstore (efi-pstore: dmesg of a panic/oops) belong
* to the previous boot. Move them to disk so the next crash finds room in
* NVRAM: a record is unlinked only after its copy is fsync'd. Runs after
* modules load so ramoops/pstore-blk records are there too. Skipped when
* fstab gives /var or /var/lib its own filesystem that is not mounted yet --
* the copy would land under the mount point and vanish. The archive path is
* left in /run so schema-doctor knows this boot harvested something. */
#define PSTORE_DIR "/sys/fs/pstore"
#define PSTORE_ARCHIVE "/var/lib/schema-init/pstore"
#define PSTORE_MARKER "/run/schema-init/pstore-harvested"
static int pstore_var_pending(void) {
struct stat root, st;
struct mntent *m;
int pending = 0;
FILE *f = setmntent("/etc/fstab", "r");
if (!f || stat("/", &root) < 0) { if (f) endmntent(f); return 0; }
while ((m = getmntent(f))) {
if (strcmp(m->mnt_dir, "/var") && strcmp(m->mnt_dir, "/var/lib")) continue;
if (stat(m->mnt_dir, &st) < 0 || st.st_dev == root.st_dev) pending = 1;
}
endmntent(f);
return pending;
}
static int pstore_copy(int dirfd, const char *name, int outdir) {
char buf[8192];
ssize_t n;
int ok = 0;
int in = openat(dirfd, name, O_RDONLY | O_CLOEXEC);
if (in < 0) return 0;
int out = openat(outdir, name, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (out >= 0) {
ok = 1;
while ((n = read(in, buf, sizeof buf)) != 0) {
if (n < 0 || write(out, buf, n) != n) { ok = 0; break; }
}
if (fsync(out) < 0) ok = 0;
close(out);
}
close(in);
return ok;
}
static void pstore_harvest(void) {
struct dirent *de;
struct stat st;
time_t oldest = 0;
char dest[128];
int moved = 0, kept = 0;
DIR *d = opendir(PSTORE_DIR);
if (!d) return;
while ((de = readdir(d))) {
if (de->d_name[0] == '.') continue;
if (fstatat(dirfd(d), de->d_name, &st, 0) == 0 && S_ISREG(st.st_mode) &&
(oldest == 0 || st.st_mtime < oldest))
oldest = st.st_mtime;
}
if (oldest == 0 || pstore_var_pending() || stat("/var/lib/schema-init", &st) < 0) {
closedir(d);
return;
}
struct tm tm;
localtime_r(&oldest, &tm);
mkdir(PSTORE_ARCHIVE, 0700);
strftime(dest, sizeof dest, PSTORE_ARCHIVE "/%Y%m%d-%H%M%S", &tm);
mkdir(dest, 0700);
int outdir = open(dest, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (outdir < 0) { closedir(d); return; }
rewinddir(d);
while ((de = readdir(d))) {
if (de->d_name[0] == '.') continue;
if (pstore_copy(dirfd(d), de->d_name, outdir) &&
unlinkat(dirfd(d), de->d_name, 0) == 0)
moved++;
else
kept++;
}
fsync(outdir);
close(outdir);
closedir(d);
mkdir(engine_paths.run_dir, 0755);
FILE *mk = fopen(PSTORE_MARKER, "w");
if (mk) { fprintf(mk, "%s\n", dest); fclose(mk); }
fprintf(stderr, "schema-init: pstore: %d record(s) from the previous boot -> %s%s\n",
moved, dest, kept ? " (some left in pstore)" : "");
}
static void cleanup_tmp_locks(void) {
glob_t globbuf;
size_t i;
/* Clean up stale Xorg lock files */
if (glob("/tmp/.X*-lock", 0, NULL, &globbuf) == 0) {
for (i = 0; i < globbuf.gl_pathc; i++) {
unlink(globbuf.gl_pathv[i]);
}
globfree(&globbuf);
}
/* Clean up stale Xorg Unix socket files */
if (glob("/tmp/.X11-unix/X*", 0, NULL, &globbuf) == 0) {
for (i = 0; i < globbuf.gl_pathc; i++) {
unlink(globbuf.gl_pathv[i]);
}
globfree(&globbuf);
}
}
static void sig_term(int s) { (void)s; engine_running = 0; engine_do_reboot = 0; if (shm_ptr) shm_ptr->system_state = 13; }
static void sig_int(int s) { (void)s; engine_running = 0; engine_do_reboot = 1; if (shm_ptr) shm_ptr->system_state = 14; }
static void sig_usr1(int s) { (void)s; engine_running = 0; engine_do_reboot = 0; } /* halt */
static void sig_usr2(int s) { (void)s; engine_running = 0; engine_do_reboot = 0; } /* poweroff */
static void setup_signals(void) {
struct sigaction sa;
sigset_t chld;
memset(&sa, 0, sizeof(sa));
/* block SIGCHLD — signalfd will drain it in the epoll loop */
sigemptyset(&chld);
sigaddset(&chld, SIGCHLD);
sigprocmask(SIG_BLOCK, &chld, NULL);
sa.sa_handler = sig_term;
sa.sa_flags = SA_RESTART;
sigaction(SIGTERM, &sa, NULL);
sa.sa_handler = sig_int;
sa.sa_flags = SA_RESTART;
sigaction(SIGINT, &sa, NULL);
sa.sa_handler = sig_usr1;
sa.sa_flags = SA_RESTART;
sigaction(SIGUSR1, &sa, NULL);
sa.sa_handler = sig_usr2;
sa.sa_flags = SA_RESTART;
sigaction(SIGUSR2, &sa, NULL);
/* PID 1 must not die on these */
signal(SIGPIPE, SIG_IGN);
}
/* ── resource pressure and quarantine executive ─────────────────────── */
static double read_cpu_pressure(const char *cgroup_path) {
char path[320];
FILE *f;
double avg10 = 0.0;
if (!cgroup_path[0]) return 0.0;
snprintf(path, sizeof(path), "%s/cpu.pressure", cgroup_path);
f = fopen(path, "r");
if (!f) return 0.0;
char line[256];
if (fgets(line, sizeof(line), f)) {
char *p = strstr(line, "avg10=");
if (p) {
sscanf(p + 6, "%lf", &avg10);
}
}
fclose(f);
return avg10;
}
static double read_system_mem_pressure(void) {
FILE *f = fopen("/proc/pressure/memory", "r");
double avg10 = 0.0;
if (!f) return 0.0;
char line[256];
if (fgets(line, sizeof(line), f)) {
char *p = strstr(line, "avg10=");
if (p) {
sscanf(p + 6, "%lf", &avg10);
}
}
fclose(f);
return avg10;
}
static int critical_cpu_pressure(void) {
int i;
for (i = 0; i < svc_count; i++) {
service_t *svc = &services[i];
if (svc->priority == PRIO_CRITICAL && svc->child_pid > 0 &&
read_cpu_pressure(svc->cgroup_path) > 5.0)
return 1;
}
return 0;
}
/* The kernel NULs the last byte written, so the trigger must go out with its
* terminator or the window loses a digit and the write fails EINVAL. */
static void psi_open(void) {
psi_fd = open("/proc/pressure/memory", O_RDWR | O_NONBLOCK | O_CLOEXEC);
if (psi_fd >= 0 && write(psi_fd, PSI_MEM_TRIGGER, sizeof(PSI_MEM_TRIGGER)) < 0) {
close(psi_fd);
psi_fd = -1;
}
printf("[schema-init] memory pressure: %s\n",
psi_fd >= 0 ? "psi trigger armed (" PSI_MEM_TRIGGER ")" : "avg10 polling");
}
static void set_cgroup_freeze(service_t *svc, int freeze) {
char path[320];
int fd;
if (!svc->cgroup_path[0]) return;
if (svc->is_frozen == freeze) return;
snprintf(path, sizeof(path), "%s/cgroup.freeze", svc->cgroup_path);
fd = open(path, O_WRONLY);
if (fd >= 0) {
write(fd, freeze ? "1\n" : "0\n", 2);
close(fd);
svc->is_frozen = freeze;
service_log(svc, freeze ? "freeze" : "thaw");
} else if (errno == ENOENT) {
if (svc->child_pid > 0) {
kill(svc->child_pid, freeze ? SIGSTOP : SIGCONT);
svc->is_frozen = freeze;
service_log(svc, freeze ? "freeze-sig" : "thaw-sig");
}
}
}
static void set_cgroup_cpu_limit(service_t *svc, const char *limit) {
char path[320];
int fd;
if (!svc->cgroup_path[0]) return;
snprintf(path, sizeof(path), "%s/cpu.max", svc->cgroup_path);
fd = open(path, O_WRONLY);
if (fd >= 0) {
write(fd, limit, strlen(limit));
close(fd);
}
}
/* bytes of cold memory to ask the kernel to reclaim from svc's cgroup, or 0 to
* skip. Critical services and tiny cgroups are left alone. Cheap (a single
* memory.current read) — safe to run inline in PID 1. */
static long reclaim_read_target(const service_t *svc) {
char path[320];
long long cur; /* bytes: > LONG_MAX on 32-bit once a cgroup holds 2 GiB */
FILE *f;
if (!svc->cgroup_path[0]) return 0;
if (svc->priority == PRIO_CRITICAL) return 0;
snprintf(path, sizeof(path), "%s/memory.current", svc->cgroup_path);
f = fopen(path, "r");
if (!f) return 0;
if (fscanf(f, "%lld", &cur) != 1) { fclose(f); return 0; }
fclose(f);
return reclaim_target(cur, RECLAIM_CAP);
}
/* The memory.reclaim write is SYNCHRONOUS — the kernel reclaims in the writer's
* context. Run it only in the forked child (reclaim_pass), never in PID 1. */
static void reclaim_cgroup_write(const service_t *svc, long target) {
char path[320], buf[32];
int fd, n;
snprintf(path, sizeof(path), "%s/memory.reclaim", svc->cgroup_path);
fd = open(path, O_WRONLY);
if (fd < 0) return;
n = snprintf(buf, sizeof(buf), "%ld\n", target);
if (n > 0) write(fd, buf, (size_t)n);
close(fd);
}
/* Fork a helper to reclaim cold pages from non-critical cgroups. The parent
* reads targets and logs (fast, non-blocking); the child performs the
* synchronous memory.reclaim writes and exits, so PID 1 never stalls. */
static void reclaim_pass(void) {
long targets[MAX_SERVICES];
int i, any = 0;
pid_t pid;
for (i = 0; i < svc_count; i++) {
targets[i] = 0;
if (services[i].child_pid <= 0) continue;
targets[i] = reclaim_read_target(&services[i]);
if (targets[i] > 0) { service_log(&services[i], "reclaim"); any = 1; }
}
if (!any) return;
pid = fork();
if (pid != 0) return; /* parent, or fork failure: do not block PID 1 */
service_reset_child_sigmask();
for (i = 0; i < svc_count; i++)
if (targets[i] > 0) reclaim_cgroup_write(&services[i], targets[i]);
_exit(0);
}
static void execute_survival_posture(int under_pressure) {
int i;
rec_event_t ev;
memset(&ev, 0, sizeof ev);
ev.src = REC_SRC_PID1;
rec_copy(ev.kind, sizeof ev.kind, under_pressure ? "survival-enter" : "survival-leave");
rec_send(REC_SOCK_PATH, &ev);
for (i = 0; i < svc_count; i++) {
service_t *svc = &services[i];
if (svc->child_pid <= 0) continue;
if (svc->priority == PRIO_PERIPHERAL) {
set_cgroup_freeze(svc, under_pressure);
} else if (svc->priority == PRIO_STANDARD) {
char q[32];
long quota = survival_cpu_quota(svc->cpu_limit_pct, under_pressure);
if (quota > 0) snprintf(q, sizeof q, "%ld 100000", quota);
else snprintf(q, sizeof q, "max 100000");
set_cgroup_cpu_limit(svc, q);
}
}
}
/* Reclaim cold pages from non-critical cgroups on any memory-stalled pass of a
* survival episode, however it began. Peripheral services are frozen by then,
* so their pages are cold and reclaim cleanly. */
static void reclaim_maybe(void) {
uint64_t now = monotonic_ms();
if (last_reclaim_ms && now - last_reclaim_ms < RECLAIM_MIN_GAP_MS) return;
last_reclaim_ms = now;
reclaim_pass();
}
/* runit's halt, reboot and poweroff (runit-init 0|6, which elogind runs too)
* make /etc/runit/stopit executable, and /etc/runit/reboot as well for a
* reboot, then send PID 1 SIGCONT. */
static void runit_stop_request(void) {
struct stat st;
if (stat("/etc/runit/stopit", &st) != 0 || !(st.st_mode & S_IXUSR))
return;
chmod("/etc/runit/stopit", 0);
engine_do_reboot = stat("/etc/runit/reboot", &st) == 0 && (st.st_mode & S_IXUSR);
printf("[schema-init] runit-init %s: %s\n", engine_do_reboot ? "6" : "0", engine_do_reboot ? "rebooting" : "powering off");
if (shm_ptr) shm_ptr->system_state = engine_do_reboot ? 14 : 13;
engine_running = 0;
}
/* ── boot sequence ──────────────────────────────────────────────────── */
static void schema_boot_log(void) {
printf("[schema-init] boot rail\n");
printf(" [1] kernel core alive\n");
printf(" [2] init\n");
printf(" [3] runlevel\n");
printf(" [4] env load\n");
printf(" [5] env active\n");
printf(" [7] settled — %d service(s) queued\n", svc_count);
fflush(stdout);
}
/* ── main ───────────────────────────────────────────────────────────── */
static void usage(FILE *out) {
fprintf(out,
"Usage: schema-init [SERVICE_DIR]\n"
"\n"
"schema-init is an init system. The kernel starts it as PID 1; it is not\n"
"a command-line tool and refuses to run as any other pid.\n"
"\n"
" SERVICE_DIR service definitions (default: %s)\n"
" -h, --help show this help and exit\n"
" -V, --version show version and exit\n"
" --check --root DIR --cmdline OPTS [--svc-dir DIR]\n"
" load DIR's services as its next boot would and print them\n"
"\n"
"To inspect or control a running schema-init, use schema-ctl:\n"
" schema-ctl status | timing | list | reload | start NAME | stop NAME\n",
engine_paths.svc_dir);
}
/* PID 1 must never be able to block on a tty. /dev/console follows the
* FOREGROUND VT, and a session VT left in KD_TEXT with a live line discipline
* turns one stray ^S into tty->flow.stopped: do_con_write() accepts 0 bytes
* from then on and every write sleeps in n_tty_write() under
* MAX_SCHEDULE_TIMEOUT. No timeout, no signal, no way out. On 2026-07-26 that
* caught PID 1 on the FIRST printf of this path and hung the box -- services
* never signalled, nothing synced, no reboot. Own console fd, O_NONBLOCK,
* TCOON to clear any stop we inherited. A dropped log line beats a dead init. */
static int shut_fd = -1;
/* The console is the only place shutdown has ever reported to, and it scrolls.
* journal-sink is dead by then, so the fifteen seconds that matter most are the
* one stretch with no recoverable log -- on 2026-07-26 the verdict had to be
* read off a phone photo. Buffer the transcript in memory and put it on disk in
* one go, deliberately NOT as we write it: touching the filesystem early would
* hand PID 1 a second way to block. shut_flush_log() runs after bounded_sync()
* and before the mount holding it goes read-only. */
#define SHUT_LOG_PATH "/var/log/schema-init/shutdown.log"
#define SHUT_LOG_MAX 4096
/* ── the styled rail (text VT only; rail.log keeps the plain line) ──── */
#define RAIL_ORIG "/run/schema-init/console-orig"
static int rail_on, rail_shut_styled, rail_out_fd = STDOUT_FILENO;
static int64_t rail_shut_start;
static char rail_cmdline[4096], rail_conf[256];
static int rail_write_out(const char *b, size_t n) {
if (rail_out_fd == STDOUT_FILENO) {
fwrite(b, 1, n, stdout);
fflush(stdout);
return (int)n;
}
return (int)write(rail_out_fd, b, n); /* shutdown's non-blocking console: drop, never wait */
}
static int64_t rail_now(void) { return (int64_t)monotonic_ms(); }
static time_t rail_wall(void) { return time(NULL); }
static const rail_io_t rail_io = { rail_write_out, rail_now, rail_wall };
static void read_small(const char *path, char *buf, size_t sz) {
int fd = open(path, O_RDONLY | O_CLOEXEC);
ssize_t n = fd < 0 ? 0 : read(fd, buf, sz - 1);
if (fd >= 0) close(fd);
buf[n > 0 ? n : 0] = '\0';
}
/* the box's configured console font: vconsole.conf FONT=, Debian FONTFACE= */
static void rail_vconsole_font(char *out, size_t sz) {
static const struct { const char *path, *key; } src[] = {
{ "/etc/vconsole.conf", "FONT=" }, { "/etc/default/console-setup", "FONTFACE=" } };
char buf[2048];
out[0] = '\0';
for (size_t k = 0; k < sizeof src / sizeof *src && !out[0]; k++) {
read_small(src[k].path, buf, sizeof buf);
for (char *l = buf; l && *l; l = strchr(l, '\n') ? strchr(l, '\n') + 1 : NULL) {
size_t kl = strlen(src[k].key);
if (strncmp(l, src[k].key, kl)) continue;
l += kl;
if (*l == '"' || *l == '\'') l++;
snprintf(out, sz, "%.*s", (int)strcspn(l, "\"'\n"), l);
break;
}
}
}
static int rail_fb_xres(void) {
struct fb_var_screeninfo vi;
int fd = open("/dev/fb0", O_RDONLY | O_CLOEXEC), x = -1;
if (fd >= 0 && ioctl(fd, FBIOGET_VSCREENINFO, &vi) == 0) x = (int)vi.xres;
if (fd >= 0) close(fd);
return x;
}
static void rail_fill(rail_svc_t *r, const service_t *s) {
r->name = s->name;
r->state = s->inst.state;
r->pid = s->child_pid;
r->failed = svc_failed(s);
r->starting = rail_is_starting(s->inst.state, s->child_pid, svc_held_on_socket(s));
r->restart_pending = s->inst.state == STATE_RECOVERY && !(s->flags & SVC_NO_RESTART);
r->restart_count = s->restart_count;
}
static void rail_hook(const service_t *svc, const char *event, const char *line, size_t n) {
long i = svc - services;
rail_svc_t r;
if (i < 0 || i >= svc_count) {
rail_write_out(line, n); /* not one of ours: the plain line */
return;
}
rail_fill(&r, svc);
rail_event(&r, (int)i, event);
}
static void rail_setup(int reexeced) {
char vf[64], host[128];
int font = 0;
read_small("/proc/cmdline", rail_cmdline, sizeof rail_cmdline);
read_small("/etc/schema-init/rail", rail_conf, sizeof rail_conf);
if (!rc_styled(STDOUT_FILENO, rail_cmdline, rail_conf)) return;
rail_vconsole_font(vf, sizeof vf);
if (rc_font_wanted(rail_cmdline, rail_conf, vf, rail_fb_xres())) {
rc_font_result_t fr = rc_font_load(STDOUT_FILENO);
if (fr == RC_FONT_OK) font = 1;
else {
/* any ioctl failure: plain lines for the rest of the boot */
service_rail_note(fr == RC_FONT_FAILED_UNRESTORED ? "console font restore FAILED; styled rail off"
: fr == RC_FONT_FAILED_RESTORED ? "console font load failed (put back); styled rail off"
: "console font not saved; styled rail off");
return;
}
}
if (rc_palette_apply(STDOUT_FILENO, RAIL_ORIG) < 0) {
service_rail_note("console palette not set; styled rail off");
return;
}
rail_init(&rail_io, font, reexeced, (int64_t)init_start.tv_sec * 1000 + init_start.tv_nsec / 1000000);
rail_on = 1;
service_log_hook = rail_hook;
read_small("/etc/hostname", host, sizeof host);
host[strcspn(host, " \n")] = '\0';
if (!host[0]) gethostname(host, sizeof host);
rail_banner(SCHEMA_INIT_VERSION, host, svc_count);
}
static int64_t rail_wake(int64_t now_m) {
static rail_svc_t v[MAX_SERVICES];
if (!rail_on) return WAKE_NONE;
for (int i = 0; i < svc_count; i++) rail_fill(&v[i], &services[i]);
return rail_tick(v, svc_count, now_m);
}
static void pid1_shut_outcome(int idx, int outcome) {
static const rail_chip_t chip[] = { [SHUT_STOPPED] = CHIP_STOPPED, [SHUT_KILLED] = CHIP_KILLED,
[SHUT_EXITED] = CHIP_EXITED, [SHUT_STUCK] = CHIP_STUCK };
if (rail_shut_styled && idx >= 0 && idx < svc_count && outcome >= 0 && outcome <= SHUT_STUCK)
rail_shutdown_outcome(services[idx].name, chip[outcome]);
}
static char shut_buf[SHUT_LOG_MAX];
static size_t shut_len = 0;
static size_t shut_flushed = 0;
static void shut_console_open(void) {
time_t now = time(NULL);
struct tm tm;
shut_fd = open("/dev/console", O_WRONLY | O_NONBLOCK | O_NOCTTY);
if (shut_fd >= 0) tcflow(shut_fd, TCOON);
if (rail_on) {
rail_shutdown_begin();
rail_shut_start = (int64_t)monotonic_ms();
/* the decision is per sink: /dev/console may be the serial line */
rail_shut_styled = shut_fd >= 0 && rc_styled(shut_fd, rail_cmdline, rail_conf);
if (rail_shut_styled) {
rail_out_fd = shut_fd;
rail_shutdown_banner();
} else {
service_log_hook = NULL;
rail_on = 0;
}
}
if (localtime_r(&now, &tm))
shut_len = strftime(shut_buf, sizeof(shut_buf),
"=== shutdown %Y-%m-%d %H:%M:%S ===\n", &tm);
}
static void shut_write(const char *s) {
size_t n = strlen(s);
if (shut_fd >= 0 && rail_shut_styled) {
/* the console gets a dim track line; shutdown.log keeps the text as is */
char t[384];
const char *p = s;
if (!strncmp(p, "[schema-init] ", 14)) p += 14;
if (!strncmp(p, "shutdown: ", 10)) p += 10;
snprintf(t, sizeof t, "%.*s", (int)strcspn(p, "\n"), p);
rail_shutdown_note(t);
} else if (shut_fd >= 0) {
ssize_t w = write(shut_fd, s, n);
(void)w; /* short or EAGAIN: drop it, never wait */
} else {
printf("%s", s);
fflush(stdout);
}
if (shut_len + n < sizeof(shut_buf)) {
memcpy(shut_buf + shut_len, s, n);
shut_len += n;
}
}
/* Best effort by design: if this fails the reboot still has to happen. Appends
* only what has not been written yet, so it is safe to call more than once --
* the call before the remount sweep is the one that always lands, the call
* after it adds the sweep's own verdict if the filesystem is still writable. */
static void shut_flush_log(void) {
int fd;
if (shut_len <= shut_flushed) return;
mkdir("/var/log/schema-init", 0755);
fd = open(SHUT_LOG_PATH, O_WRONLY | O_APPEND | O_CREAT, 0600);
if (fd < 0) return;
if (write(fd, shut_buf + shut_flushed, shut_len - shut_flushed) > 0) {
fsync(fd);
shut_flushed = shut_len;
}
close(fd);
}
static void shut_log(const char *msg) {
char buf[384]; /* >= the 320-byte mount-path messages */
snprintf(buf, sizeof(buf), "[schema-init] shutdown: %s\n", msg);
shut_write(buf);
}
/* A FUSE mount whose daemon we just cgroup-killed can leave the connection
* live with nobody to answer it; anything that then touches the superblock
* (sync, umount, remount) waits in D state forever. Abort them first. */
static void fuse_abort_all(void) {
glob_t g;
size_t n;
if (glob("/sys/fs/fuse/connections/*/abort", 0, NULL, &g) != 0) return;
for (n = 0; n < g.gl_pathc; n++) {
int fd = open(g.gl_pathv[n], O_WRONLY);
if (fd >= 0) { write(fd, "1", 1); close(fd); }
}
if (g.gl_pathc) shut_log("fuse connections aborted");
globfree(&g);