From 16062b1e6684f63c203583cbfa0edec993cf66b2 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Sun, 22 Nov 2026 12:57:05 -0300 Subject: [PATCH 1/7] store: name and place a process by what it became, under cgroup v2 A service's process in a boot changes name and cgroup after bootchart first sees it. systemd execs its executor through a file descriptor, and the kernel names a task exec'd that way after the descriptor, so journald, logind, udevd and every executor were charted as "9": the name was read once from /proc/PID/sched and refreshed only every Hz/4 samples (250 ms at 200 Hz). The cgroup was read once too, before the process moved from init.scope into its unit, and through cgroup-util, which statfs'd /sys/fs/cgroup before systemd had mounted it and gave up, so every label read "(null)". Now the comm, the command line with -C and the cgroup are read again on every sample in which the process ran, which is when an exec or a move can have happened. The cgroup comes from /proc/PID/cgroup itself: systemd's name=systemd hierarchy on v1 or hybrid, the 0:: line on v2. A process is labelled with its unit, the cgroup path without the slices above it, and a table lists CPU time by unit. /proc/PID/sched, whose start time nothing drew, is no longer read, and cgroup-util goes. --proc samples a directory laid out as /proc, which tests/identity builds and changes under the sampler. The pids are sorted before the tree is built, since the tree needs a parent before its children and only /proc itself lists them in that order. Co-Authored-By: Claude Opus 5.5 --- Makefile.am | 9 +- man/bootchart.conf.xml | 3 +- man/systemd-bootchart.xml | 17 ++- src/bootchart.c | 23 +++- src/bootchart.h | 5 +- src/cgroup-util.c | 190 ----------------------------- src/cgroup-util.h | 80 ------------ src/def.h | 1 - src/store.c | 249 +++++++++++++++++++++++--------------- src/store.h | 1 + src/svg.c | 68 ++++++++++- tests/identity | 59 +++++++++ 12 files changed, 315 insertions(+), 390 deletions(-) delete mode 100644 src/cgroup-util.c delete mode 100644 src/cgroup-util.h create mode 100755 tests/identity diff --git a/Makefile.am b/Makefile.am index 9bbc8fa..e2afaf6 100644 --- a/Makefile.am +++ b/Makefile.am @@ -70,7 +70,8 @@ EXTRA_DIST = \ man/standard-conf.xml \ man/standard-options.xml \ units/systemd-bootchart.service.in \ - tests/run + tests/run \ + tests/identity MANPAGES = man/bootchart.conf.5 man/systemd-bootchart.1 MANPAGES_ALIAS = man/bootchart.conf.d.5 @@ -110,8 +111,6 @@ libutils_la_SOURCES = \ src/architecture.h \ src/attributes.h \ src/build.h \ - src/cgroup-util.c \ - src/cgroup-util.h \ src/conf-files.c \ src/conf-files.h \ src/conf-parser.c \ @@ -193,7 +192,9 @@ systemd_bootchart_LDADD = \ ##################################################### -TESTS = tests/run +TESTS = \ + tests/run \ + tests/identity substitutions = \ '|rootlibexecdir=$(rootlibexecdir)|' diff --git a/man/bootchart.conf.xml b/man/bootchart.conf.xml index 6557901..3229b93 100644 --- a/man/bootchart.conf.xml +++ b/man/bootchart.conf.xml @@ -154,7 +154,8 @@ ControlGroup=no - Display process control group. + Label each process with the unit whose control + group it is in, and list the units that used the most CPU time. diff --git a/man/systemd-bootchart.xml b/man/systemd-bootchart.xml index 50a81e8..10e694d 100644 --- a/man/systemd-bootchart.xml +++ b/man/systemd-bootchart.xml @@ -193,9 +193,22 @@ - + - Display process control group + Label each process with the unit whose control + group it is in, such as systemd-journald.service, + and list the units that used the most CPU time. The control group is + read from the cgroup v2 hierarchy, or from systemd's own hierarchy on + a v1 or hybrid one, and read again whenever the process has run, since + a service's processes move into its unit's control group after they + start. + + + + + Sample processes from this directory instead of + /proc. Its layout is + /proc's, and its use is a test's. diff --git a/src/bootchart.c b/src/bootchart.c index 15aaa2e..62f1eca 100644 --- a/src/bootchart.c +++ b/src/bootchart.c @@ -62,6 +62,7 @@ #include "parse-util.h" #include "path-util.h" #include "store.h" +#include "stdio-util.h" #include "string-util.h" #include "strxcpyx.h" #include "svg.h" @@ -75,6 +76,7 @@ static int exiting = 0; #define DEFAULT_SCALE_Y 20.0 /* 16px = 1 process bar */ #define DEFAULT_INIT ROOTLIBEXECDIR "/systemd" #define DEFAULT_OUTPUT "/run/log" +#define DEFAULT_PROC "/proc" /* graph defaults */ bool arg_entropy = false; @@ -92,6 +94,7 @@ double arg_scale_y = DEFAULT_SCALE_Y; char arg_init_path[PATH_MAX] = DEFAULT_INIT; char arg_output_path[PATH_MAX] = DEFAULT_OUTPUT; +char arg_proc_path[PATH_MAX] = DEFAULT_PROC; static void signal_handler(int sig) { exiting = 1; @@ -144,6 +147,7 @@ static void help(void) { " -C --cmdline Display full command lines with arguments\n" " -c --control-group Display process control group\n" " --per-cpu Draw each CPU utilization and wait bar also\n" + " --proc=PATH Sample processes from PATH instead of [%s]\n" " -h --help Display this message\n\n" "See bootchart.conf for more information.\n", program_invocation_short_name, @@ -152,13 +156,15 @@ static void help(void) { DEFAULT_SCALE_X, DEFAULT_SCALE_Y, DEFAULT_OUTPUT, - DEFAULT_INIT); + DEFAULT_INIT, + DEFAULT_PROC); } static int parse_argv(int argc, char *argv[]) { enum { ARG_PERCPU = 0x100, + ARG_PROC, }; static const struct option options[] = { @@ -176,6 +182,7 @@ static int parse_argv(int argc, char *argv[]) { {"scale-y", required_argument, NULL, 'y' }, {"entropy", no_argument, NULL, 'e' }, {"per-cpu", no_argument, NULL, ARG_PERCPU}, + {"proc", required_argument, NULL, ARG_PROC }, {} }; int c, r; @@ -239,6 +246,10 @@ static int parse_argv(int argc, char *argv[]) { case ARG_PERCPU: arg_percpu = true; break; + case ARG_PROC: + path_kill_slashes(optarg); + strscpy(arg_proc_path, sizeof(arg_proc_path), optarg); + break; case 'h': help(); return 0; @@ -333,6 +344,7 @@ int main(int argc, char *argv[]) { .sa_handler = signal_handler, }; bool has_procfs = false; + char vmstat_path[PATH_MAX + 8]; parse_conf(); @@ -394,7 +406,8 @@ int main(int argc, char *argv[]) { return EXIT_FAILURE; } - has_procfs = access("/proc/vmstat", F_OK) == 0; + xsprintf(vmstat_path, "%s/vmstat", arg_proc_path); + has_procfs = access(vmstat_path, F_OK) == 0; LIST_HEAD_INIT(head); @@ -421,11 +434,12 @@ int main(int argc, char *argv[]) { if (!has_procfs) { /* wait for /proc to become available, discarding samples */ - has_procfs = access("/proc/vmstat", F_OK) == 0; + xsprintf(vmstat_path, "%s/vmstat", arg_proc_path); + has_procfs = access(vmstat_path, F_OK) == 0; } else if (proc) { rewinddir(proc); } else { - proc = opendir("/proc"); + proc = opendir(arg_proc_path); } if (proc) { @@ -472,7 +486,6 @@ int main(int argc, char *argv[]) { while (ps->next_running) { ps = ps->next_running; ps->schedstat = safe_close(ps->schedstat); - ps->sched = safe_close(ps->sched); ps->smaps = safe_fclose(ps->smaps); } diff --git a/src/bootchart.h b/src/bootchart.h index 1b0895e..64f6c2f 100644 --- a/src/bootchart.h +++ b/src/bootchart.h @@ -75,7 +75,6 @@ struct ps_struct { char *cgroup; /* cache fd's */ - int sched; int schedstat; FILE *smaps; @@ -86,9 +85,6 @@ struct ps_struct { struct ps_sched_struct *first; struct ps_sched_struct *last; - /* records actual start time, may be way before bootchart runs */ - double starttime; - /* record human readable total cpu time */ double total; @@ -117,3 +113,4 @@ extern double arg_scale_y; extern char arg_output_path[PATH_MAX]; extern char arg_init_path[PATH_MAX]; +extern char arg_proc_path[PATH_MAX]; diff --git a/src/cgroup-util.c b/src/cgroup-util.c deleted file mode 100644 index 7601201..0000000 --- a/src/cgroup-util.c +++ /dev/null @@ -1,190 +0,0 @@ -/*** - This file is part of systemd. - - Copyright 2010 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include -#include -#include -#include - -#include "attributes.h" -#include "cgroup-util.h" -#include "def.h" -#include "fd-util.h" -#include "fileio.h" -#include "macro.h" -#include "missing.h" -#include "parse-util.h" -#include "process-util.h" -#include "string-util.h" - -#define F_TYPE_EQUAL(a, b) (a == (typeof(a)) b) - -int cg_pid_get_path(const char *controller, pid_t pid, char **path) { - _cleanup_fclose_ FILE *f = NULL; - char line[LINE_MAX]; - const char *fs; - size_t cs = 0; - int unified; - - assert(path); - assert(pid >= 0); - - unified = cg_unified(); - if (unified < 0) - return unified; - if (unified == 0) { - if (controller) { - if (!cg_controller_is_valid(controller)) - return -EINVAL; - } else - controller = SYSTEMD_CGROUP_CONTROLLER; - - cs = strlen(controller); - } - - fs = procfs_file_alloca(pid, "cgroup"); - f = fopen(fs, "re"); - if (!f) - return errno == ENOENT ? -ESRCH : -errno; - - FOREACH_LINE(line, f, return -errno) { - char *e, *p; - - truncate_nl(line); - - if (unified) { - e = startswith(line, "0:"); - if (!e) - continue; - - e = strchr(e, ':'); - if (!e) - continue; - } else { - char *l; - size_t k; - const char *word, *state; - bool found = false; - - l = strchr(line, ':'); - if (!l) - continue; - - l++; - e = strchr(l, ':'); - if (!e) - continue; - - *e = 0; - FOREACH_WORD_SEPARATOR(word, k, l, ",", state) { - if (k == cs && memcmp(word, controller, cs) == 0) { - found = true; - break; - } - } - - if (!found) - continue; - } - - p = strdup(e + 1); - if (!p) - return -ENOMEM; - - *path = p; - return 0; - } - - return -ENODATA; -} - -#define CONTROLLER_VALID \ - DIGITS LETTERS \ - "_" - -bool cg_controller_is_valid(const char *p) { - const char *t, *s; - - if (!p) - return false; - - s = startswith(p, "name="); - if (s) - p = s; - - if (*p == 0 || *p == '_') - return false; - - for (t = p; *t; t++) - if (!strchr(CONTROLLER_VALID, *t)) - return false; - - if (t - p > FILENAME_MAX) - return false; - - return true; -} - -static thread_local int unified_cache = -1; - -int cg_unified(void) { - struct statfs fs; - - /* Checks if we support the unified hierarchy. Returns an - * error when the cgroup hierarchies aren't mounted yet or we - * have any other trouble determining if the unified hierarchy - * is supported. */ - - if (unified_cache >= 0) - return unified_cache; - - if (statfs("/sys/fs/cgroup/", &fs) < 0) - return -errno; - - if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)) - unified_cache = true; - else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) - unified_cache = false; - else - return -ENOMEDIUM; - - return unified_cache; -} - -int cg_blkio_weight_parse(const char *s, uint64_t *ret) { - uint64_t u; - int r; - - if (isempty(s)) { - *ret = CGROUP_BLKIO_WEIGHT_INVALID; - return 0; - } - - r = safe_atou64(s, &u); - if (r < 0) - return r; - - if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX) - return -ERANGE; - - *ret = u; - return 0; -} diff --git a/src/cgroup-util.h b/src/cgroup-util.h deleted file mode 100644 index 0fbb7fb..0000000 --- a/src/cgroup-util.h +++ /dev/null @@ -1,80 +0,0 @@ -#pragma once - -/*** - This file is part of systemd. - - Copyright 2010 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include - -/* Special values for the cpu.shares attribute */ -#define CGROUP_CPU_SHARES_INVALID ((uint64_t) -1) -#define CGROUP_CPU_SHARES_MIN UINT64_C(2) -#define CGROUP_CPU_SHARES_MAX UINT64_C(262144) -#define CGROUP_CPU_SHARES_DEFAULT UINT64_C(1024) - -static inline bool CGROUP_CPU_SHARES_IS_OK(uint64_t x) { - return - x == CGROUP_CPU_SHARES_INVALID || - (x >= CGROUP_CPU_SHARES_MIN && x <= CGROUP_CPU_SHARES_MAX); -} - -/* Special values for the blkio.weight attribute */ -#define CGROUP_BLKIO_WEIGHT_INVALID ((uint64_t) -1) -#define CGROUP_BLKIO_WEIGHT_MIN UINT64_C(10) -#define CGROUP_BLKIO_WEIGHT_MAX UINT64_C(1000) -#define CGROUP_BLKIO_WEIGHT_DEFAULT UINT64_C(500) - -static inline bool CGROUP_BLKIO_WEIGHT_IS_OK(uint64_t x) { - return - x == CGROUP_BLKIO_WEIGHT_INVALID || - (x >= CGROUP_BLKIO_WEIGHT_MIN && x <= CGROUP_BLKIO_WEIGHT_MAX); -} - -/* - * General rules: - * - * We accept named hierarchies in the syntax "foo" and "name=foo". - * - * We expect that named hierarchies do not conflict in name with a - * kernel hierarchy, modulo the "name=" prefix. - * - * We always generate "normalized" controller names, i.e. without the - * "name=" prefix. - * - * We require absolute cgroup paths. When returning, we will always - * generate paths with multiple adjacent / removed. - */ - -int cg_migrate(const char *cfrom, const char *pfrom, const char *cto, const char *pto, bool ignore_self); -int cg_migrate_recursive(const char *cfrom, const char *pfrom, const char *cto, const char *pto, bool ignore_self, bool remove); -int cg_migrate_recursive_fallback(const char *cfrom, const char *pfrom, const char *cto, const char *pto, bool ignore_self, bool rem); - -int cg_pid_get_path(const char *controller, pid_t pid, char **path); - -int cg_pid_get_unit(pid_t pid, char **unit); -int cg_pid_get_machine_name(pid_t pid, char **machine); - -bool cg_controller_is_valid(const char *p); - -int cg_slice_to_path(const char *unit, char **ret); - -int cg_unified(void); - -int cg_blkio_weight_parse(const char *s, uint64_t *ret); diff --git a/src/def.h b/src/def.h index 0e43d5a..af5761d 100644 --- a/src/def.h +++ b/src/def.h @@ -36,7 +36,6 @@ /* The default value for the net.unix.max_dgram_qlen sysctl */ #define DEFAULT_UNIX_MAX_DGRAM_QLEN 512UL -#define SYSTEMD_CGROUP_CONTROLLER "name=systemd" #define SIGNALS_CRASH_HANDLER SIGSEGV,SIGILL,SIGFPE,SIGBUS,SIGQUIT,SIGABRT #define SIGNALS_IGNORE SIGPIPE diff --git a/src/store.c b/src/store.c index 785d408..408501f 100644 --- a/src/store.c +++ b/src/store.c @@ -32,7 +32,6 @@ #include "alloc-util.h" #include "bootchart.h" -#include "cgroup-util.h" #include "def.h" #include "dirent-util.h" #include "fd-util.h" @@ -40,6 +39,7 @@ #include "formats-util.h" #include "log.h" #include "parse-util.h" +#include "stdio-util.h" #include "store.h" #include "string-util.h" #include "strxcpyx.h" @@ -95,6 +95,95 @@ static int pid_cmdline_strscpy(int procfd, char *buffer, size_t buf_len, int pid return 0; } +/* Reads the file NAME in the process's directory, NUL-terminated, and returns its length. */ +static ssize_t pid_read(int procfd, int pid, const char *name, char *buf, size_t size) { + char path[64]; + _cleanup_close_ int fd = -1; + ssize_t n; + + xsprintf(path, "%d/%s", pid, name); + fd = openat(procfd, path, O_RDONLY|O_CLOEXEC); + if (fd < 0) + return -errno; + + n = read(fd, buf, size - 1); + if (n < 0) + return -errno; + + buf[n] = '\0'; + return n; +} + +/* The process's cgroup: systemd's own "name=systemd" hierarchy's path on a v1 or hybrid + * hierarchy, and otherwise the cgroup v2 path, from the "0::" line of /proc/PID/cgroup. */ +static char *pid_cgroup(int procfd, int pid) { + char buf[4096]; + char *line, *v2 = NULL; + + if (pid_read(procfd, pid, "cgroup", buf, sizeof(buf)) <= 0) + return NULL; + + for (line = buf; line && *line; line = bufgetline(line)) { + char *p = strstr(line, ":name=systemd:"); + + if (p && p < strchrnul(line, '\n')) { + p += strlen(":name=systemd:"); + return strndup(p, strcspn(p, "\n")); + } + + if (startswith(line, "0::")) + v2 = line + 3; + } + + return v2 ? strndup(v2, strcspn(v2, "\n")) : NULL; +} + +/* Reads what names the process: its comm, its command line with --cmdline, and its cgroup with + * --control-group. All three change while a process lives, and in a boot they change early: + * systemd's executor is exec'd through a file descriptor, so the kernel names it after the + * descriptor ("9") until it execs the service, and the service's cgroup is the init.scope it + * was forked in until it moves itself into its unit's. So they are read again on every sample + * in which the process ran, which is when an exec or a move can have happened. */ +static void pid_read_identity(int procfd, struct ps_struct *ps) { + char comm[64]; + + if (pid_read(procfd, ps->pid, "comm", comm, sizeof(comm)) > 0) + strscpy(ps->name, sizeof(ps->name), truncate_nl(comm)); + + if (arg_show_cmdline) + pid_cmdline_strscpy(procfd, ps->name, sizeof(ps->name), ps->pid); + + if (arg_show_cgroup) { + char *cgroup = pid_cgroup(procfd, ps->pid); + + if (cgroup) { + free(ps->cgroup); + ps->cgroup = cgroup; + } + } +} + +const char *ps_unit(const struct ps_struct *ps) { + const char *p, *slash; + + if (!ps->cgroup) + return NULL; + + /* The slices above a unit say where it was placed, not what it is: + * /system.slice/systemd-journald.service is systemd-journald.service, and + * /user.slice/user-0.slice/user@0.service/init.scope is user@0.service/init.scope. */ + p = ps->cgroup; + while (*p == '/') + p++; + while ((slash = strchr(p, '/'))) { + if (slash - p < 6 || strncmp(slash - 6, ".slice", 6) != 0) + break; + p = slash + 1; + } + + return *p ? p : ps->cgroup; +} + static void garbage_collect_dead_processes(struct ps_struct *ps_first) { struct ps_struct *ps; struct ps_struct *ps_next; @@ -104,7 +193,6 @@ static void garbage_collect_dead_processes(struct ps_struct *ps_first) { if (!ps_next->still_running) { /* close the stream and fds */ ps_next->schedstat = safe_close(ps_next->schedstat); - ps_next->sched = safe_close(ps_next->sched); if (ps_next->smaps) { fclose(ps_next->smaps); ps_next->smaps = NULL; @@ -120,6 +208,38 @@ static void garbage_collect_dead_processes(struct ps_struct *ps_first) { } +static int pid_compare(const void *a, const void *b) { + int x = *(const int *) a, y = *(const int *) b; + + return (x > y) - (x < y); +} + +/* The pids in the proc directory, ascending. The process tree is built in the order processes + * are first seen and needs a parent seen before the processes it forked, which /proc's own order + * gives and a directory standing in for it with --proc need not. */ +static int read_pids(DIR *proc, int **pids, size_t *allocated) { + struct dirent *ent; + int n = 0; + + while ((ent = readdir(proc)) != NULL) { + int pid; + + if ((ent->d_name[0] < '0') || (ent->d_name[0] > '9')) + continue; + + pid = atoi(ent->d_name); + if (pid >= MAXPIDS) + continue; + + if (!GREEDY_REALLOC(*pids, *allocated, n + 1)) + return log_oom(); + (*pids)[n++] = pid; + } + + qsort(*pids, n, sizeof(int), pid_compare); + return n; +} + int log_sample(DIR *proc, int sample, struct ps_struct *ps_first, @@ -129,6 +249,7 @@ int log_sample(DIR *proc, static int vmstat = -1; _cleanup_free_ char *buf_schedstat = NULL; + _cleanup_fclose_ FILE *f_schedstat = NULL; char buf[4096]; char key[256]; char val[256]; @@ -138,7 +259,6 @@ int log_sample(DIR *proc, int r; int c; int p; - int mod; static int e_fd = -1; ssize_t s; ssize_t n; @@ -148,6 +268,9 @@ int log_sample(DIR *proc, struct ps_sched_struct *ps_prev = NULL; int procfd; int taskfd = -1; + static int *pids = NULL; + static size_t pids_allocated = 0; + int n_pids, i; sampledata = *ptr; @@ -189,9 +312,17 @@ int log_sample(DIR *proc, } /* Parse "/proc/schedstat" for overall CPU utilization */ - r = read_full_file("/proc/schedstat", &buf_schedstat, NULL); + fd = openat(procfd, "schedstat", O_RDONLY|O_CLOEXEC); + if (fd < 0) + return log_error_errno(errno, "Unable to open schedstat: %m"); + f_schedstat = fdopen(fd, "re"); + if (!f_schedstat) { + safe_close(fd); + return log_error_errno(errno, "Unable to open schedstat: %m"); + } + r = read_full_stream(f_schedstat, &buf_schedstat, NULL); if (r < 0) - return log_error_errno(r, "Unable to read schedstat: %m"); + return log_error_errno(r, "Unable to read schedstat: %m"); m = buf_schedstat; while (m) { @@ -231,19 +362,16 @@ int log_sample(DIR *proc, } } - while ((ent = readdir(proc)) != NULL) { + r = read_pids(proc, &pids, &pids_allocated); + if (r < 0) + return r; + n_pids = r; + + for (i = 0; i < n_pids; i++) { char filename[PATH_MAX]; - int pid; + int pid = pids[i]; struct ps_struct *ps; - if ((ent->d_name[0] < '0') || (ent->d_name[0] > '9')) - continue; - - pid = atoi(ent->d_name); - - if (pid >= MAXPIDS) - continue; - ps = ps_first; while (ps->next_running) { ps = ps->next_running; @@ -254,7 +382,6 @@ int log_sample(DIR *proc, /* end of our LL? then append a new record */ if (ps->pid != pid) { _cleanup_fclose_ FILE *st = NULL; - char t[32]; struct ps_struct *parent; /* find the insertion point for the last item */ @@ -271,7 +398,6 @@ int log_sample(DIR *proc, ps = *ps_next; ps->pid = pid; - ps->sched = -1; ps->schedstat = -1; ps->sample = new0(struct ps_sched_struct, 1); @@ -285,54 +411,6 @@ int log_sample(DIR *proc, /* mark our first sample */ ps->first = ps->last = ps->sample; - /* get name, start time; requires CONFIG_SCHED_DEBUG in kernel */ - if (ps->sched < 0) { - sprintf(filename, "%d/sched", pid); - ps->sched = openat(procfd, filename, O_RDONLY|O_CLOEXEC); - if (ps->sched < 0) - goto no_sched; - } - - s = pread(ps->sched, buf, sizeof(buf) - 1, 0); - if (s <= 0) { - ps->sched = safe_close(ps->sched); - goto no_sched; - } - buf[s] = '\0'; - - if (!sscanf(buf, "%s %*s %*s", key)) - goto no_sched; - - strscpy(ps->name, sizeof(ps->name), key); - - /* discard line 2 */ - m = bufgetline(buf); - if (!m) - goto no_sched; - - m = bufgetline(m); - if (!m) - goto no_sched; - - if (!sscanf(m, "%*s %*s %s", t)) - goto no_sched; - - r = safe_atod(t, &ps->starttime); - if (r < 0) - goto no_sched; - - ps->starttime /= 1000.0; - -no_sched: - /* cmdline */ - if (arg_show_cmdline) - pid_cmdline_strscpy(procfd, ps->name, sizeof(ps->name), pid); - - if (arg_show_cgroup) - /* if this fails, that's OK */ - cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, - ps->pid, &ps->cgroup); - /* ppid */ sprintf(filename, "%d/stat", pid); fd = openat(procfd, filename, O_RDONLY|O_CLOEXEC); @@ -483,8 +561,12 @@ int log_sample(DIR *proc, } } + if (ps->sample->prev == ps->first || + ps->sample->runtime > ps->sample->prev->runtime) + pid_read_identity(procfd, ps); + if (!arg_pss) - goto catch_rename; + goto next; /* Pss */ if (!ps->smaps) { @@ -497,11 +579,11 @@ int log_sample(DIR *proc, fd = openat(procfd, filename, O_RDONLY|O_CLOEXEC); } if (fd < 0) - goto catch_rename; + goto next; ps->smaps = fdopen(fd, "re"); if (!ps->smaps) { close(fd); - goto catch_rename; + goto next; } setvbuf(ps->smaps, smaps_buf, _IOFBF, sizeof(smaps_buf)); } else { @@ -524,36 +606,7 @@ int log_sample(DIR *proc, if (ps->sample->pss > ps->pss_max) ps->pss_max = ps->sample->pss; -catch_rename: - /* catch process rename, try to randomize time */ - mod = (arg_hz < 4.0) ? 4.0 : (arg_hz / 4.0); - if (((sample - ps->pid) + pid) % (int)(mod) == 0) { - - /* re-fetch name */ - /* get name, start time */ - if (ps->sched < 0) { - sprintf(filename, "%d/sched", pid); - ps->sched = openat(procfd, filename, O_RDONLY|O_CLOEXEC); - if (ps->sched < 0) - goto no_sched2; - } - - s = pread(ps->sched, buf, sizeof(buf) - 1, 0); - if (s <= 0) - continue; - - buf[s] = '\0'; - - if (!sscanf(buf, "%s %*s %*s", key)) - continue; - - strscpy(ps->name, sizeof(ps->name), key); - -no_sched2: - /* cmdline */ - if (arg_show_cmdline) - pid_cmdline_strscpy(procfd, ps->name, sizeof(ps->name), pid); - } +next: ps->still_running = true; } diff --git a/src/store.h b/src/store.h index 6e9acf2..17363eb 100644 --- a/src/store.h +++ b/src/store.h @@ -28,6 +28,7 @@ double gettime_ns(void); void log_uptime(void); +const char *ps_unit(const struct ps_struct *ps); int log_sample(DIR *proc, int sample, struct ps_struct *ps_first, diff --git a/src/svg.c b/src/svg.c index 9183de4..a9465d4 100644 --- a/src/svg.c +++ b/src/svg.c @@ -37,6 +37,8 @@ #include "log.h" #include "macro.h" #include "stdio-util.h" +#include "store.h" +#include "string-util.h" #include "svg.h" #include "utf8.h" @@ -1137,21 +1139,21 @@ static void svg_ps_bars(FILE *of, /* text label of process name */ if ((ps->last->runtime - ps->first->runtime) > 1000000000.0) - fprintf(of, " [%i]%.03fs %s\n", + fprintf(of, " [%i]%.03fs \n", time_to_graph(w - graph_start) + 5.0, ps_to_graph(j) + 14.0, escaped ? escaped : ps->name, ps->pid, (ps->last->runtime - ps->first->runtime) / 1000000000.0, - arg_show_cgroup ? ps->cgroup : ""); + strempty(ps_unit(ps))); else - fprintf(of, " [%i]%.01fms %s\n", + fprintf(of, " [%i]%.01fms \n", time_to_graph(w - graph_start) + 5.0, ps_to_graph(j) + 14.0, escaped ? escaped : ps->name, ps->pid, (ps->last->runtime - ps->first->runtime) / 1000000.0, - arg_show_cgroup ? ps->cgroup : ""); + strempty(ps_unit(ps))); /* paint lines to the parent process */ if (ps->parent) { @@ -1277,6 +1279,56 @@ static void svg_top_ten_cpu(FILE *of, struct ps_struct *ps_first) { top[n]->pid); } +/* CPU time by unit: what the boot spent its CPU on, whichever processes of a unit spent it. */ +static void svg_top_ten_units(FILE *of, struct ps_struct *ps_first) { + struct unit_total { + const char *unit; + double total; + int processes; + } units[256] = {}, *top[10] = {}; + struct ps_struct *ps; + int n_units = 0, n, m; + + ps = ps_first; + while ((ps = get_next_ps(ps, ps_first))) { + const char *unit = ps_unit(ps); + + if (!unit) + continue; + + for (n = 0; n < n_units && !streq(units[n].unit, unit); n++) + ; + if (n == n_units) { + if (n_units == (int) ELEMENTSOF(units)) + continue; + units[n_units++].unit = unit; + } + units[n].total += ps->total; + units[n].processes++; + } + + for (n = 0; n < n_units; n++) + for (m = 0; m < (int) ELEMENTSOF(top); m++) { + int k; + + if (top[m] && units[n].total <= top[m]->total) + continue; + for (k = ELEMENTSOF(top) - 1; k > m; k--) + top[k] = top[k-1]; + top[m] = &units[n]; + break; + } + + fprintf(of, "Top CPU consumers by unit:\n"); + for (n = 0; n < (int) ELEMENTSOF(top) && top[n]; n++) + fprintf(of, "%3.01fms - (%d %s)\n", + 20 + (n * 13), + to_ms(top[n]->total), + top[n]->unit, + top[n]->processes, + top[n]->processes == 1 ? "process" : "processes"); +} + static void svg_top_ten_pss(FILE *of, struct ps_struct *ps_first) { struct ps_struct *top[10]; struct ps_struct emptyps = {}; @@ -1392,6 +1444,12 @@ int svg_do(FILE *of, svg_top_ten_cpu(of, ps_first); fprintf(of, "\n\n"); + if (arg_show_cgroup) { + fprintf(of, "\n"); + svg_top_ten_units(of, ps_first); + fprintf(of, "\n\n"); + } + if (arg_entropy) { fprintf(of, "\n", 400.0 + (arg_scale_y * offset) + ksize + psize); svg_entropy_bar(of, head, graph_start); @@ -1403,7 +1461,7 @@ int svg_do(FILE *of, svg_pss_graph(of, head, ps_first, graph_start); fprintf(of, "\n\n"); - fprintf(of, "\n"); + fprintf(of, "\n", arg_show_cgroup ? 810 : 410); svg_top_ten_pss(of, ps_first); fprintf(of, "\n\n"); } diff --git a/tests/identity b/tests/identity new file mode 100755 index 0000000..9b2de9d --- /dev/null +++ b/tests/identity @@ -0,0 +1,59 @@ +#! /bin/sh +# A process in a boot is named and placed after it starts: systemd's executor is exec'd through a +# file descriptor, so the kernel names it "9" until it execs the service, and it moves from +# init.scope into its unit's cgroup. The chart names it by what it became, under cgroup v2 and v1. +set -e +d=$(mktemp -d) +trap 'rm -rf "$d"' EXIT +proc=$d/proc +mkdir -p "$proc" "$d/out" + +# In place, as /proc changes: the sampler keeps a process's schedstat open and reads it again. +put() { + printf "$2" > "$proc/$1" +} + +process() { # pid ppid comm cgroup-file runtime-ns + mkdir -p "$proc/$1/task" + put "$1/comm" "$3\n" + put "$1/stat" "$1 ($3) S $2 0 0\n" + put "$1/cgroup" "$4" + put "$1/cmdline" "" + put "$1/schedstat" "$5 0 1\n" +} + +put vmstat "pgpgin 0\npgpgout 0\n" +put schedstat "version 15\ntimestamp 0\ncpu0 0 0 0 0 0 0 1000 2000 3\n" +process 1 0 systemd "0::/init.scope\n" 5000000 +process 62 1 9 "0::/init.scope\n" 1000000 +process 70 1 9 "1:name=systemd:/init.scope\n0::/\n" 1000000 +process 71 1 sshd "1:name=systemd:/system.slice/ssh.service\n" 2000000 + +timeout 30 ./systemd-bootchart --proc "$proc" -o "$d/out" -r -c -f 100 -n 50 & +sampler=$! +sleep 0.2 +put 62/comm "systemd-journal\n" +put 62/cgroup "0::/system.slice/systemd-journald.service\n" +put 62/schedstat "3000000 0 2\n" +put 70/comm "systemd-logind\n" +put 70/cgroup "1:name=systemd:/system.slice/systemd-logind.service\n0::/\n" +put 70/schedstat "3000000 0 2\n" +wait $sampler + +svg=$(echo "$d"/out/*.svg) +fail=0 +expect() { + grep -qF -- "$1" "$svg" || { echo "not ok - the chart has no $1"; fail=1; } +} +expect ' [62]' +expect '' +expect ' [70]' +expect '' +expect '' +expect ' (1 process)' +if grep -qF '' "$svg"; then + echo "not ok - a process is still named after the executor's descriptor" + fail=1 +fi +[ $fail -eq 0 ] || grep -F '[CDATA[' "$svg" +exit $fail From 882ef70f44d6aec692f7aae3add3975cf68cbdcb Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Sun, 22 Nov 2026 13:09:22 -0300 Subject: [PATCH 2/7] store: read the parent pid after the comm, which can hold spaces /proc/PID/stat puts the comm in parentheses without quoting it, and bootchart took the parent pid as the fourth word. A comm with a space, such as "Web Content", moved it: the scan failed and the process was never sampled, so it was missing from the chart. The parent pid is now read after the last ')'. Co-Authored-By: Claude Opus 5.5 --- src/store.c | 17 +++++------------ tests/identity | 5 +++++ 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/store.c b/src/store.c index 408501f..aa2bc6f 100644 --- a/src/store.c +++ b/src/store.c @@ -381,7 +381,6 @@ int log_sample(DIR *proc, /* end of our LL? then append a new record */ if (ps->pid != pid) { - _cleanup_fclose_ FILE *st = NULL; struct ps_struct *parent; /* find the insertion point for the last item */ @@ -411,19 +410,13 @@ int log_sample(DIR *proc, /* mark our first sample */ ps->first = ps->last = ps->sample; - /* ppid */ - sprintf(filename, "%d/stat", pid); - fd = openat(procfd, filename, O_RDONLY|O_CLOEXEC); - if (fd < 0) - continue; - - st = fdopen(fd, "re"); - if (!st) { - close(fd); + /* ppid, after the comm in parentheses, which can hold spaces and + * parentheses of its own, so after the last ')' */ + if (pid_read(procfd, pid, "stat", buf, sizeof(buf)) <= 0) continue; - } - if (!fscanf(st, "%*s %*s %*s %i", &p)) + m = strrchr(buf, ')'); + if (!m || sscanf(m + 1, " %*c %i", &p) != 1) continue; ps->ppid = p; diff --git a/tests/identity b/tests/identity index 9b2de9d..5df599e 100755 --- a/tests/identity +++ b/tests/identity @@ -28,6 +28,8 @@ process 1 0 systemd "0::/init.scope\n" 5000000 process 62 1 9 "0::/init.scope\n" 1000000 process 70 1 9 "1:name=systemd:/init.scope\n0::/\n" 1000000 process 71 1 sshd "1:name=systemd:/system.slice/ssh.service\n" 2000000 +# a comm with a space and a parenthesis, which /proc/PID/stat does not quote +process 72 1 "Web (Content" "0::/user.slice/user-0.slice/session-1.scope\n" 2000000 timeout 30 ./systemd-bootchart --proc "$proc" -o "$d/out" -r -c -f 100 -n 50 & sampler=$! @@ -38,6 +40,7 @@ put 62/schedstat "3000000 0 2\n" put 70/comm "systemd-logind\n" put 70/cgroup "1:name=systemd:/system.slice/systemd-logind.service\n0::/\n" put 70/schedstat "3000000 0 2\n" +put 72/schedstat "3000000 0 2\n" wait $sampler svg=$(echo "$d"/out/*.svg) @@ -50,6 +53,8 @@ expect '' expect ' [70]' expect '' expect '' +expect ' [72]' expect ' (1 process)' if grep -qF '' "$svg"; then echo "not ok - a process is still named after the executor's descriptor" From 4986207ecfd03f085a2e78b31677c8b6a2025e53 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Sun, 22 Nov 2026 13:00:31 -0300 Subject: [PATCH 3/7] svg: draw every process that ran while the chart did The filter dropped a process seen in one sample and one that used less than 1 ms of CPU. In a boot of a few hundred milliseconds that is most of systemd's work: generators, executors, (sd-close) and the like. On spin-stack/machine's boot it dropped 62 processes. A process is now dropped only when it used no CPU time while the chart ran: for one already running at the first sample that saw processes, none past that sample. A process seen in a single sample is drawn over the interval before it, in which it started, with the CPU time it used there; before, its bar had no width. Co-Authored-By: Claude Opus 5.5 --- Makefile.am | 6 ++-- man/bootchart.conf.xml | 8 ++---- man/systemd-bootchart.xml | 11 ++++---- src/svg.c | 59 ++++++++++++++++++++++++++++++--------- tests/short-lived | 51 +++++++++++++++++++++++++++++++++ 5 files changed, 110 insertions(+), 25 deletions(-) create mode 100755 tests/short-lived diff --git a/Makefile.am b/Makefile.am index e2afaf6..4d58523 100644 --- a/Makefile.am +++ b/Makefile.am @@ -71,7 +71,8 @@ EXTRA_DIST = \ man/standard-options.xml \ units/systemd-bootchart.service.in \ tests/run \ - tests/identity + tests/identity \ + tests/short-lived MANPAGES = man/bootchart.conf.5 man/systemd-bootchart.1 MANPAGES_ALIAS = man/bootchart.conf.d.5 @@ -194,7 +195,8 @@ systemd_bootchart_LDADD = \ TESTS = \ tests/run \ - tests/identity + tests/identity \ + tests/short-lived substitutions = \ '|rootlibexecdir=$(rootlibexecdir)|' diff --git a/man/bootchart.conf.xml b/man/bootchart.conf.xml index 3229b93..fe1e78a 100644 --- a/man/bootchart.conf.xml +++ b/man/bootchart.conf.xml @@ -104,11 +104,9 @@ Filter=no Configures whether the resulting graph should - omit tasks that did not contribute significantly to the boot. - Processes that are too short-lived (only seen in one sample) - or that do not consume any significant CPU time (less than - 0.001sec) will not be displayed in the output - graph. + omit tasks that did not run while it was recorded, such as idle + kernel threads. A process that used CPU time in any sample's + interval is drawn, however briefly it ran. diff --git a/man/systemd-bootchart.xml b/man/systemd-bootchart.xml index 10e694d..4364653 100644 --- a/man/systemd-bootchart.xml +++ b/man/systemd-bootchart.xml @@ -177,11 +177,12 @@ - Disable filtering of tasks that did not - contribute significantly to the boot. Processes that are too - short-lived (only seen in one sample) or that do not consume - any significant CPU time (less than 0.001 s) will not be - displayed in the output graph. + Disable filtering of tasks that did not run + while the chart was recorded. By default a process is drawn when + it used CPU time in any sample's interval, however briefly, and + processes that did not, such as idle kernel threads, are left out. + A process seen in a single sample is drawn over the interval + before that sample, in which it started. diff --git a/src/svg.c b/src/svg.c index a9465d4..7ceeca6 100644 --- a/src/svg.c +++ b/src/svg.c @@ -21,6 +21,7 @@ ***/ #include +#include #include #include #include @@ -40,6 +41,7 @@ #include "store.h" #include "string-util.h" #include "svg.h" +#include "time-util.h" #include "utf8.h" #define time_to_graph(t) ((t) * arg_scale_x) @@ -65,6 +67,7 @@ static const char * const colorwheel[12] = { static double idletime = -1.0; static int pfiltered = 0; +static int first_counter = 0; static int pcount = 0; static int kcount = 0; static double psize = 0; @@ -899,23 +902,33 @@ static struct ps_struct *get_next_ps(struct ps_struct *ps, struct ps_struct *ps_ return NULL; } +/* Whether the process started while the chart ran: it was not there at the first sample that saw + * any process. Its CPU time is then all the chart's, and it started in the interval before the + * sample that first saw it. */ +static bool ps_born_in_chart(const struct ps_struct *ps) { + return ps->first->sampledata->counter > first_counter; +} + static bool ps_filter(struct ps_struct *ps) { + const struct ps_sched_struct *seen = ps->first->next; + double ran; + if (!arg_filter) return false; - /* can't draw data when there is only 1 sample (need start + stop) */ - if (ps->first == ps->last) + /* no sample of its CPU time to draw */ + if (!seen) return true; /* don't filter kthreadd */ if (ps->pid == 2) return false; - /* drop stuff that doesn't use any real CPU time */ - if (ps->total <= 0.001) - return true; - - return 0; + /* Drop what did not run while the chart did, idle kernel threads mostly. Whatever ran is + * kept however briefly: in a boot of a few hundred milliseconds, a generator's 1 ms or an + * executor's single sample is a part of it. */ + ran = ps_born_in_chart(ps) ? ps->last->runtime : ps->last->runtime - seen->runtime; + return ran <= 0; } static void svg_do_initcall(FILE *of, struct list_sample_data *head, int count_only, double graph_start) { @@ -1059,6 +1072,8 @@ static void svg_ps_bars(FILE *of, ps->ppid, to_ms(ps->total)); starttime = ps->first->sampledata->sampletime; + if (ps_born_in_chart(ps)) + starttime -= interval / NSEC_PER_SEC; if (!ps_filter(ps)) { /* remember where _to_ our children need to draw a line */ @@ -1094,17 +1109,28 @@ static void svg_ps_bars(FILE *of, while (ps->sample->next) { double rt, prt; double wt, wrt; + double from; struct ps_sched_struct *prev; prev = ps->sample; ps->sample = ps->sample->next; + /* The first sample holds what the process ran before it: since it started for + * one that started in the chart, in the interval before the sample, and since + * long before the chart for one already running, which is not drawn. */ + from = prev->sampledata->sampletime; + if (prev == ps->first) { + if (!ps_born_in_chart(ps)) + continue; + from = starttime; + } + /* calculate over interval */ rt = ps->sample->runtime - prev->runtime; wt = ps->sample->waittime - prev->waittime; - prt = (rt / 1000000000) / (ps->sample->sampledata->sampletime - prev->sampledata->sampletime); - wrt = (wt / 1000000000) / (ps->sample->sampledata->sampletime - prev->sampledata->sampletime); + prt = (rt / 1000000000) / (ps->sample->sampledata->sampletime - from); + wrt = (wt / 1000000000) / (ps->sample->sampledata->sampletime - from); /* this can happen if timekeeping isn't accurate enough */ if (prt > 1.0) @@ -1116,16 +1142,16 @@ static void svg_ps_bars(FILE *of, continue; fprintf(of, " \n", - time_to_graph(prev->sampledata->sampletime - graph_start), + time_to_graph(from - graph_start), ps_to_graph(j), - time_to_graph(ps->sample->sampledata->sampletime - prev->sampledata->sampletime), + time_to_graph(ps->sample->sampledata->sampletime - from), ps_to_graph(wrt)); /* draw cpu over wait - TODO figure out how/why run + wait > interval */ fprintf(of, " \n", - time_to_graph(prev->sampledata->sampletime - graph_start), + time_to_graph(from - graph_start), ps_to_graph(j + (1.0 - prt)), - time_to_graph(ps->sample->sampledata->sampletime - prev->sampledata->sampletime), + time_to_graph(ps->sample->sampledata->sampletime - from), ps_to_graph(prt)); t++; } @@ -1386,6 +1412,13 @@ int svg_do(FILE *of, svg_do_initcall(of, head, 1, graph_start); ksize = kcount ? ps_to_graph(kcount) + (arg_scale_y * 2) : 0; + /* the first sample that saw processes, which may be after the first: as PID 1, the + * sampler starts before /proc is mounted */ + first_counter = INT_MAX; + while ((ps = get_next_ps(ps, ps_first))) + first_counter = MIN(first_counter, ps->first->sampledata->counter); + ps = ps_first; + /* then count processes */ while ((ps = get_next_ps(ps, ps_first))) { if (!ps_filter(ps)) diff --git a/tests/short-lived b/tests/short-lived new file mode 100755 index 0000000..af30395 --- /dev/null +++ b/tests/short-lived @@ -0,0 +1,51 @@ +#! /bin/sh +# A boot's generators and executors run for a millisecond or one sample's interval. The chart +# draws every process that ran while it did, however briefly, and drops what did not run. +# A process's bar is labelled "name [pid] "$proc/$1" +} + +process() { # pid ppid comm runtime-ns + mkdir -p "$proc/$1/task" + put "$1/comm" "$3\n" + put "$1/stat" "$1 ($3) S $2 0 0\n" + put "$1/cgroup" "0::/init.scope\n" + put "$1/cmdline" "" + put "$1/schedstat" "$4 0 1\n" +} + +put vmstat "pgpgin 0\npgpgout 0\n" +put schedstat "version 15\ntimestamp 0\ncpu0 0 0 0 0 0 0 1000 2000 3\n" +process 1 0 systemd 5000000 +process 2 0 kthreadd 100000 +process 20 2 kworker-idle 700000 + +timeout 30 ./systemd-bootchart --proc "$proc" -o "$d/out" -r -f 50 -n 25 & +sampler=$! +sleep 0.1 +put 1/schedstat "6000000 0 2\n" +# a generator: 0.3 ms of CPU, gone within two samples +process 80 1 generator 300000 +sleep 0.03 +rm -rf "$proc/80" +wait $sampler + +svg=$(echo "$d"/out/*.svg) +fail=0 +grep -qF ' [80] [1] [20] Date: Sun, 22 Nov 2026 13:03:57 -0300 Subject: [PATCH 4/7] store, svg: what each process read from and wrote to disk The IO graphs show a boot's bursts, 230 MB/s of reads from 0.1 to 0.14 s on spin-stack/machine's, and nothing said whose they were. read_bytes and write_bytes come from /proc/PID/io on every sample in which the process ran: a process submits a read or dirties a page only while it runs, so a sample in which it did not keeps the last values, and costs no read. Each process's label says what it read and wrote, an orange strip under its bar marks the intervals in which it did, a "Top disk I/O" table lists who did the most, and the unit table sums both by unit. Co-Authored-By: Claude Opus 5.5 --- Makefile.am | 6 ++-- src/bootchart.h | 5 +++ src/store.c | 27 ++++++++++++++- src/svg.c | 90 +++++++++++++++++++++++++++++++++++++++---------- tests/io | 51 ++++++++++++++++++++++++++++ 5 files changed, 158 insertions(+), 21 deletions(-) create mode 100755 tests/io diff --git a/Makefile.am b/Makefile.am index 4d58523..1f43f70 100644 --- a/Makefile.am +++ b/Makefile.am @@ -72,7 +72,8 @@ EXTRA_DIST = \ units/systemd-bootchart.service.in \ tests/run \ tests/identity \ - tests/short-lived + tests/short-lived \ + tests/io MANPAGES = man/bootchart.conf.5 man/systemd-bootchart.1 MANPAGES_ALIAS = man/bootchart.conf.d.5 @@ -196,7 +197,8 @@ systemd_bootchart_LDADD = \ TESTS = \ tests/run \ tests/identity \ - tests/short-lived + tests/short-lived \ + tests/io substitutions = \ '|rootlibexecdir=$(rootlibexecdir)|' diff --git a/src/bootchart.h b/src/bootchart.h index 64f6c2f..6d4487f 100644 --- a/src/bootchart.h +++ b/src/bootchart.h @@ -24,6 +24,7 @@ #include #include +#include #include #include "list.h" @@ -42,6 +43,10 @@ struct ps_sched_struct { /* /proc//schedstat fields 1 & 2 */ double runtime; double waittime; + /* /proc//io read_bytes & write_bytes: what the process had the block layer read for + * it, and the bytes it dirtied, since it started */ + uint64_t read_bytes; + uint64_t write_bytes; int pss; struct list_sample_data *sampledata; struct ps_sched_struct *next; diff --git a/src/store.c b/src/store.c index aa2bc6f..ba68dd5 100644 --- a/src/store.c +++ b/src/store.c @@ -163,6 +163,25 @@ static void pid_read_identity(int procfd, struct ps_struct *ps) { } } +/* The process's read_bytes and write_bytes from /proc/PID/io, which a kernel without + * CONFIG_TASK_IO_ACCOUNTING does not have; the sample keeps the last values then. */ +static void pid_read_io(int procfd, int pid, struct ps_sched_struct *sample) { + char buf[512]; + char *line; + + if (pid_read(procfd, pid, "io", buf, sizeof(buf)) <= 0) + return; + + for (line = buf; line && *line; line = bufgetline(line)) { + const char *v; + + if ((v = startswith(line, "read_bytes: "))) + sample->read_bytes = strtoull(v, NULL, 10); + else if ((v = startswith(line, "write_bytes: "))) + sample->write_bytes = strtoull(v, NULL, 10); + } +} + const char *ps_unit(const struct ps_struct *ps) { const char *p, *slash; @@ -554,9 +573,15 @@ int log_sample(DIR *proc, } } + /* A process reads, writes, execs and moves only while it runs, so what it did + * since the last sample is read only when it ran since. */ + ps->sample->read_bytes = ps->sample->prev->read_bytes; + ps->sample->write_bytes = ps->sample->prev->write_bytes; if (ps->sample->prev == ps->first || - ps->sample->runtime > ps->sample->prev->runtime) + ps->sample->runtime > ps->sample->prev->runtime) { pid_read_identity(procfd, ps); + pid_read_io(procfd, ps->pid, ps->sample); + } if (!arg_pss) goto next; diff --git a/src/svg.c b/src/svg.c index 7ceeca6..86a9695 100644 --- a/src/svg.c +++ b/src/svg.c @@ -137,6 +137,7 @@ static void svg_header(FILE *of, struct list_sample_data *head, double graph_sta fprintf(of, " rect.wait { fill: rgb(240,240,0); stroke-width: 0; fill-opacity: 0.7; }\n"); fprintf(of, " rect.bi { fill: rgb(240,128,128); stroke-width: 0; fill-opacity: 0.7; }\n"); fprintf(of, " rect.bo { fill: rgb(192,64,64); stroke-width: 0; fill-opacity: 0.7; }\n"); + fprintf(of, " rect.io { fill: rgb(240,128,0); stroke-width: 0; }\n"); fprintf(of, " rect.ps { fill: rgb(192,192,192); stroke: rgb(128,128,128); fill-opacity: 0.7; }\n"); fprintf(of, " rect.krnl { fill: rgb(240,240,0); stroke: rgb(128,128,128); fill-opacity: 0.7; }\n"); fprintf(of, " rect.box { fill: rgb(240,240,240); stroke: rgb(192,192,192); }\n"); @@ -1032,6 +1033,14 @@ static void svg_do_initcall(FILE *of, struct list_sample_data *head, int count_o } } +/* "12.3MB read, 1.0MB written" after LEAD, leaving out what is zero, and LEAD too when both are */ +static void svg_io_amounts(FILE *of, const char *lead, uint64_t read_bytes, uint64_t write_bytes) { + if (read_bytes > 0) + fprintf(of, "%s%.01fMB read", lead, read_bytes / 1000000.0); + if (write_bytes > 0) + fprintf(of, "%s%.01fMB written", read_bytes > 0 ? ", " : lead, write_bytes / 1000000.0); +} + static void svg_ps_bars(FILE *of, struct list_sample_data *head, int n_samples, @@ -1138,6 +1147,13 @@ static void svg_ps_bars(FILE *of, if (wrt > 1.0) wrt = 1.0; + /* an orange strip under the intervals in which the process read or wrote */ + if (ps->sample->read_bytes > prev->read_bytes || ps->sample->write_bytes > prev->write_bytes) + fprintf(of, " \n", + time_to_graph(from - graph_start), + ps_to_graph(j + 1) - 3, + time_to_graph(ps->sample->sampledata->sampletime - from)); + if ((prt < 0.1) && (wrt < 0.1)) /* =~ 26 (color threshold) */ continue; @@ -1164,22 +1180,17 @@ static void svg_ps_bars(FILE *of, w = starttime; /* text label of process name */ + fprintf(of, " [%i]", + time_to_graph(w - graph_start) + 5.0, + ps_to_graph(j) + 14.0, + escaped ? escaped : ps->name, + ps->pid); if ((ps->last->runtime - ps->first->runtime) > 1000000000.0) - fprintf(of, " [%i]%.03fs \n", - time_to_graph(w - graph_start) + 5.0, - ps_to_graph(j) + 14.0, - escaped ? escaped : ps->name, - ps->pid, - (ps->last->runtime - ps->first->runtime) / 1000000000.0, - strempty(ps_unit(ps))); + fprintf(of, "%.03fs", (ps->last->runtime - ps->first->runtime) / 1000000000.0); else - fprintf(of, " [%i]%.01fms \n", - time_to_graph(w - graph_start) + 5.0, - ps_to_graph(j) + 14.0, - escaped ? escaped : ps->name, - ps->pid, - (ps->last->runtime - ps->first->runtime) / 1000000.0, - strempty(ps_unit(ps))); + fprintf(of, "%.01fms", (ps->last->runtime - ps->first->runtime) / 1000000.0); + svg_io_amounts(of, ", ", ps->last->read_bytes, ps->last->write_bytes); + fprintf(of, " \n", strempty(ps_unit(ps))); /* paint lines to the parent process */ if (ps->parent) { @@ -1310,6 +1321,8 @@ static void svg_top_ten_units(FILE *of, struct ps_struct *ps_first) { struct unit_total { const char *unit; double total; + uint64_t read_bytes; + uint64_t write_bytes; int processes; } units[256] = {}, *top[10] = {}; struct ps_struct *ps; @@ -1330,6 +1343,8 @@ static void svg_top_ten_units(FILE *of, struct ps_struct *ps_first) { units[n_units++].unit = unit; } units[n].total += ps->total; + units[n].read_bytes += ps->last->read_bytes; + units[n].write_bytes += ps->last->write_bytes; units[n].processes++; } @@ -1346,13 +1361,48 @@ static void svg_top_ten_units(FILE *of, struct ps_struct *ps_first) { } fprintf(of, "Top CPU consumers by unit:\n"); - for (n = 0; n < (int) ELEMENTSOF(top) && top[n]; n++) - fprintf(of, "%3.01fms - (%d %s)\n", + for (n = 0; n < (int) ELEMENTSOF(top) && top[n]; n++) { + fprintf(of, "%3.01fms", 20 + (n * 13), - to_ms(top[n]->total), + to_ms(top[n]->total)); + svg_io_amounts(of, ", ", top[n]->read_bytes, top[n]->write_bytes); + fprintf(of, " - (%d %s)\n", top[n]->unit, top[n]->processes, top[n]->processes == 1 ? "process" : "processes"); + } +} + +/* The processes that had the most read from or written to disk for them: who the IO graphs' + * bursts were for. */ +static void svg_top_ten_io(FILE *of, struct ps_struct *ps_first) { + struct ps_struct *top[10] = {}; + struct ps_struct *ps; + int n, m; + + ps = ps_first; + while ((ps = get_next_ps(ps, ps_first))) { + uint64_t io = ps->last->read_bytes + ps->last->write_bytes; + + if (io == 0) + continue; + + for (n = 0; n < (int) ELEMENTSOF(top); n++) { + if (top[n] && io <= top[n]->last->read_bytes + top[n]->last->write_bytes) + continue; + for (m = ELEMENTSOF(top) - 1; m > n; m--) + top[m] = top[m-1]; + top[n] = ps; + break; + } + } + + fprintf(of, "Top disk I/O:\n"); + for (n = 0; n < (int) ELEMENTSOF(top) && top[n]; n++) { + fprintf(of, "", 20 + (n * 13)); + svg_io_amounts(of, "", top[n]->last->read_bytes, top[n]->last->write_bytes); + fprintf(of, " - [%d]\n", top[n]->name, top[n]->pid); + } } static void svg_top_ten_pss(FILE *of, struct ps_struct *ps_first) { @@ -1483,6 +1533,10 @@ int svg_do(FILE *of, fprintf(of, "\n\n"); } + fprintf(of, "\n", arg_show_cgroup ? 810 : 410); + svg_top_ten_io(of, ps_first); + fprintf(of, "\n\n"); + if (arg_entropy) { fprintf(of, "\n", 400.0 + (arg_scale_y * offset) + ksize + psize); svg_entropy_bar(of, head, graph_start); @@ -1494,7 +1548,7 @@ int svg_do(FILE *of, svg_pss_graph(of, head, ps_first, graph_start); fprintf(of, "\n\n"); - fprintf(of, "\n", arg_show_cgroup ? 810 : 410); + fprintf(of, "\n", arg_show_cgroup ? 1210 : 810); svg_top_ten_pss(of, ps_first); fprintf(of, "\n\n"); } diff --git a/tests/io b/tests/io new file mode 100755 index 0000000..dcc7710 --- /dev/null +++ b/tests/io @@ -0,0 +1,51 @@ +#! /bin/sh +# The IO graphs show a boot's read and write bursts; /proc/PID/io says whose they were. The chart +# labels each process with what it read and wrote, and lists who did the most. +set -e +d=$(mktemp -d) +trap 'rm -rf "$d"' EXIT +proc=$d/proc +mkdir -p "$proc" "$d/out" + +put() { + printf "$2" > "$proc/$1" +} + +process() { # pid ppid comm cgroup runtime-ns read-bytes write-bytes + mkdir -p "$proc/$1/task" + put "$1/comm" "$3\n" + put "$1/stat" "$1 ($3) S $2 0 0\n" + put "$1/cgroup" "0::$4\n" + put "$1/cmdline" "" + put "$1/schedstat" "$5 0 1\n" + put "$1/io" "rchar: 0\nwchar: 0\nsyscr: 0\nsyscw: 0\nread_bytes: $6\nwrite_bytes: $7\ncancelled_write_bytes: 0\n" +} + +put vmstat "pgpgin 0\npgpgout 0\n" +put schedstat "version 15\ntimestamp 0\ncpu0 0 0 0 0 0 0 1000 2000 3\n" +process 1 0 systemd /init.scope 5000000 1000000 0 +process 62 1 systemd-journal /system.slice/systemd-journald.service 1000000 0 0 + +timeout 30 ./systemd-bootchart --proc "$proc" -o "$d/out" -r -c -f 100 -n 40 & +sampler=$! +sleep 0.15 +# journald reads 12 MB and writes 2.5 MB while it runs; then it reads more without running, which a +# process cannot do, so the chart keeps what it read while it ran +process 62 1 systemd-journal /system.slice/systemd-journald.service 3000000 12000000 2500000 +put 1/schedstat "6000000 0 2\n" +sleep 0.1 +put 62/io "read_bytes: 99000000\nwrite_bytes: 2500000\n" +wait $sampler + +svg=$(echo "$d"/out/*.svg) +fail=0 +expect() { + grep -qF -- "$1" "$svg" || { echo "not ok - the chart has no $1"; fail=1; } +} +expect ' [62]3.0ms, 12.0MB read, 2.5MB written' +expect ' [1]6.0ms, 1.0MB read' +expect '>12.0MB read, 2.5MB written - [62]' +expect '>3.0ms, 12.0MB read, 2.5MB written - (1 process)' +expect ' Date: Sun, 22 Nov 2026 13:06:43 -0300 Subject: [PATCH 5/7] store, svg: who waited, from PSI and each process's run delay On one vCPU the question a boot chart has to answer is who waited to run. The CPU wait graph sums the run queues' wait, and each process's yellow showed its run delay only past 10% of an interval, with no number anywhere. Three graphs now draw /proc/pressure's cpu, io and memory: the share of each interval in which some task (orange) or every task (red) stalled, from the totals, which unlike the averages are exact over a 5 ms interval. A kernel without PSI draws none. Each process's label, the CPU table and the unit table say how long it waited for a CPU. The run delay was wrong for any process with threads: each thread's run time was added to it in place of the thread's run delay. And the CPU table's total left the threads out, since it was taken before they were added. Co-Authored-By: Claude Opus 5.5 --- Makefile.am | 6 ++- src/bootchart.h | 14 +++++++ src/store.c | 56 ++++++++++++++++++++++++++-- src/svg.c | 98 +++++++++++++++++++++++++++++++++++++++++++++---- tests/pressure | 66 +++++++++++++++++++++++++++++++++ 5 files changed, 228 insertions(+), 12 deletions(-) create mode 100755 tests/pressure diff --git a/Makefile.am b/Makefile.am index 1f43f70..3f57390 100644 --- a/Makefile.am +++ b/Makefile.am @@ -73,7 +73,8 @@ EXTRA_DIST = \ tests/run \ tests/identity \ tests/short-lived \ - tests/io + tests/io \ + tests/pressure MANPAGES = man/bootchart.conf.5 man/systemd-bootchart.1 MANPAGES_ALIAS = man/bootchart.conf.d.5 @@ -198,7 +199,8 @@ TESTS = \ tests/run \ tests/identity \ tests/short-lived \ - tests/io + tests/io \ + tests/pressure substitutions = \ '|rootlibexecdir=$(rootlibexecdir)|' diff --git a/src/bootchart.h b/src/bootchart.h index 6d4487f..8d3427e 100644 --- a/src/bootchart.h +++ b/src/bootchart.h @@ -55,10 +55,24 @@ struct ps_sched_struct { struct ps_struct *ps_new; }; +enum { + PRESSURE_CPU, + PRESSURE_IO, + PRESSURE_MEMORY, + _PRESSURE_MAX, +}; + +enum { + PRESSURE_SOME, + PRESSURE_FULL, +}; + struct list_sample_data { double runtime[MAXCPUS]; double waittime[MAXCPUS]; double sampletime; + /* /proc/pressure/{cpu,io,memory} some and full totals, in microseconds */ + uint64_t pressure[_PRESSURE_MAX][2]; int entropy_avail; struct block_stat_struct blockstat; LIST_FIELDS(struct list_sample_data, link); /* DLL */ diff --git a/src/store.c b/src/store.c index ba68dd5..e393b8a 100644 --- a/src/store.c +++ b/src/store.c @@ -227,6 +227,52 @@ static void garbage_collect_dead_processes(struct ps_struct *ps_first) { } +static const char *const pressure_files[_PRESSURE_MAX] = { + [PRESSURE_CPU] = "pressure/cpu", + [PRESSURE_IO] = "pressure/io", + [PRESSURE_MEMORY] = "pressure/memory", +}; + +/* The stall totals in /proc/pressure: microseconds in which some task, or every task ("full"), + * waited for the resource. A kernel without CONFIG_PSI, or booted with psi=0, has none and the + * totals stay zero. */ +static void read_pressure(int procfd, struct list_sample_data *sampledata) { + static int fds[_PRESSURE_MAX] = { -1, -1, -1 }; + int i; + + for (i = 0; i < _PRESSURE_MAX; i++) { + char buf[256]; + char *line; + ssize_t n; + + if (fds[i] < 0) { + fds[i] = openat(procfd, pressure_files[i], O_RDONLY|O_CLOEXEC); + if (fds[i] < 0) + continue; + } + + n = pread(fds[i], buf, sizeof(buf) - 1, 0); + if (n <= 0) + continue; + buf[n] = '\0'; + + for (line = buf; line && *line; line = bufgetline(line)) { + const char *total = strstr(line, "total="); + int which; + + if (!total) + continue; + if (startswith(line, "some ")) + which = PRESSURE_SOME; + else if (startswith(line, "full ")) + which = PRESSURE_FULL; + else + continue; + sampledata->pressure[i][which] = strtoull(total + strlen("total="), NULL, 10); + } + } +} + static int pid_compare(const void *a, const void *b) { int x = *(const int *) a, y = *(const int *) b; @@ -365,6 +411,8 @@ int log_sample(DIR *proc, break; } + read_pressure(procfd, sampledata); + if (arg_entropy) { if (e_fd < 0) { e_fd = openat(procfd, "sys/kernel/random/entropy_avail", O_RDONLY|O_CLOEXEC); @@ -514,8 +562,6 @@ int log_sample(DIR *proc, ps_prev->cross = ps->sample; ps_prev = ps->sample; - ps->total = (ps->last->runtime - ps->first->runtime) - / 1000000000.0; /* Take into account CPU runtime/waittime spent in non-main threads of the process * by parsing "/proc/[pid]/task/[tid]/schedstat" for all [tid] != [pid] @@ -565,7 +611,7 @@ int log_sample(DIR *proc, r = safe_atolli(rt, &delta_rt); if (r < 0) continue; - r = safe_atolli(rt, &delta_wt); + r = safe_atolli(wt, &delta_wt); if (r < 0) continue; ps->sample->runtime += delta_rt; @@ -573,6 +619,10 @@ int log_sample(DIR *proc, } } + /* after its threads', which the main thread's schedstat leaves out */ + ps->total = (ps->last->runtime - ps->first->runtime) + / 1000000000.0; + /* A process reads, writes, execs and moves only while it runs, so what it did * since the last sample is read only when it ran since. */ ps->sample->read_bytes = ps->sample->prev->read_bytes; diff --git a/src/svg.c b/src/svg.c index 86a9695..bc768a0 100644 --- a/src/svg.c +++ b/src/svg.c @@ -73,6 +73,7 @@ static int kcount = 0; static double psize = 0; static double ksize = 0; static double esize = 0; +static double pressure_size = 0; static struct list_sample_data *sampledata; static struct list_sample_data *prev_sampledata; @@ -95,7 +96,7 @@ static void svg_header(FILE *of, struct list_sample_data *head, double graph_sta /* height is variable based on pss, psize, ksize */ h = 400.0 + (arg_scale_y * 30.0) /* base graphs and title */ + (arg_pss ? (100.0 * arg_scale_y) + (arg_scale_y * 7.0) : 0.0) /* pss estimate */ - + psize + ksize + esize + ((n_cpus+1) * 15 * arg_scale_y); + + psize + ksize + esize + pressure_size + ((n_cpus+1) * 15 * arg_scale_y); fprintf(of, "\n"); fprintf(of, "pressure[r][PRESSURE_SOME] > 0) + return true; + return false; +} + +/* The share of each interval in which some task (orange), or every task (red), stalled waiting + * for the resource, from /proc/pressure. On one CPU, CPU pressure is the share of the time in + * which a task could have run and another one was running instead. */ +static void svg_pressure_bar(FILE *of, struct list_sample_data *head, int resource, double graph_start) { + fprintf(of, "\n", pressure_names[resource]); + fprintf(of, "%s pressure: some tasks stalled (orange), all tasks stalled (red)\n", + pressure_names[resource]); + + svg_graph_box(of, head, 5, graph_start); + + prev_sampledata = head; + LIST_FOREACH_BEFORE(link, sampledata, head) { + double dt = sampledata->sampletime - prev_sampledata->sampletime; + int which; + + for (which = PRESSURE_SOME; which <= PRESSURE_FULL; which++) { + uint64_t now = sampledata->pressure[resource][which]; + uint64_t before = prev_sampledata->pressure[resource][which]; + double share; + + if (dt <= 0 || now <= before) + continue; + + share = ((now - before) / 1000000.0) / dt; + if (share > 1.0) + share = 1.0; + if (share < 0.001) + continue; + + fprintf(of, "\n", + which == PRESSURE_SOME ? "psome" : "pfull", + time_to_graph(prev_sampledata->sampletime - graph_start), + (arg_scale_y * 5) - (share * (arg_scale_y * 5)), + time_to_graph(dt), + share * (arg_scale_y * 5)); + } + + prev_sampledata = sampledata; + } +} + static void svg_entropy_bar(FILE *of, struct list_sample_data *head, double graph_start) { fprintf(of, "\n"); @@ -1033,6 +1094,17 @@ static void svg_do_initcall(FILE *of, struct list_sample_data *head, int count_o } } +/* The time the process spent runnable and waiting for a CPU, its schedstat run_delay, in seconds. */ +static double ps_wait(const struct ps_struct *ps) { + return (ps->last->waittime - ps->first->waittime) / 1000000000.0; +} + +/* ", 1.2ms waiting", or nothing for a process that never waited */ +static void svg_wait_amount(FILE *of, double wait) { + if (wait >= 0.0001) + fprintf(of, ", %.01fms waiting", to_ms(wait)); +} + /* "12.3MB read, 1.0MB written" after LEAD, leaving out what is zero, and LEAD too when both are */ static void svg_io_amounts(FILE *of, const char *lead, uint64_t read_bytes, uint64_t write_bytes) { if (read_bytes > 0) @@ -1189,6 +1261,7 @@ static void svg_ps_bars(FILE *of, fprintf(of, "%.03fs", (ps->last->runtime - ps->first->runtime) / 1000000000.0); else fprintf(of, "%.01fms", (ps->last->runtime - ps->first->runtime) / 1000000.0); + svg_wait_amount(of, ps_wait(ps)); svg_io_amounts(of, ", ", ps->last->read_bytes, ps->last->write_bytes); fprintf(of, " \n", strempty(ps_unit(ps))); @@ -1308,12 +1381,11 @@ static void svg_top_ten_cpu(FILE *of, struct ps_struct *ps_first) { } fprintf(of, "Top CPU consumers:\n"); - for (n = 0; n < 10; n++) - fprintf(of, "%3.01fms - [%d]\n", - 20 + (n * 13), - to_ms(top[n]->total), - top[n]->name, - top[n]->pid); + for (n = 0; n < 10 && top[n] != &emptyps; n++) { + fprintf(of, "%3.01fms", 20 + (n * 13), to_ms(top[n]->total)); + svg_wait_amount(of, ps_wait(top[n])); + fprintf(of, " - [%d]\n", top[n]->name, top[n]->pid); + } } /* CPU time by unit: what the boot spent its CPU on, whichever processes of a unit spent it. */ @@ -1321,6 +1393,7 @@ static void svg_top_ten_units(FILE *of, struct ps_struct *ps_first) { struct unit_total { const char *unit; double total; + double wait; uint64_t read_bytes; uint64_t write_bytes; int processes; @@ -1343,6 +1416,7 @@ static void svg_top_ten_units(FILE *of, struct ps_struct *ps_first) { units[n_units++].unit = unit; } units[n].total += ps->total; + units[n].wait += ps_wait(ps); units[n].read_bytes += ps->last->read_bytes; units[n].write_bytes += ps->last->write_bytes; units[n].processes++; @@ -1365,6 +1439,7 @@ static void svg_top_ten_units(FILE *of, struct ps_struct *ps_first) { fprintf(of, "%3.01fms", 20 + (n * 13), to_ms(top[n]->total)); + svg_wait_amount(of, top[n]->wait); svg_io_amounts(of, ", ", top[n]->read_bytes, top[n]->write_bytes); fprintf(of, " - (%d %s)\n", top[n]->unit, @@ -1479,6 +1554,7 @@ int svg_do(FILE *of, psize = ps_to_graph(pcount) + (arg_scale_y * 2); esize = (arg_entropy ? arg_scale_y * 7 : 0); + pressure_size = svg_has_pressure(head) ? _PRESSURE_MAX * 7 * arg_scale_y : 0; /* after this, we can draw the header with proper sizing */ svg_header(of, head, graph_start, arg_percpu ? n_cpus : 0); @@ -1504,6 +1580,14 @@ int svg_do(FILE *of, fprintf(of, "\n\n"); } + if (pressure_size > 0) + for (c = 0; c < _PRESSURE_MAX; c++) { + offset += 7; + fprintf(of, "\n", 400.0 + (arg_scale_y * offset)); + svg_pressure_bar(of, head, c, graph_start); + fprintf(of, "\n\n"); + } + if (kcount) { offset += 7; fprintf(of, "\n", 400.0 + (arg_scale_y * offset)); diff --git a/tests/pressure b/tests/pressure new file mode 100755 index 0000000..270f62f --- /dev/null +++ b/tests/pressure @@ -0,0 +1,66 @@ +#! /bin/sh +# On one CPU the question is who waits to run. The chart draws /proc/pressure's share of each +# interval in which tasks stalled, and says how long each process waited for a CPU: its +# schedstat run_delay, its threads' included. +set -e +d=$(mktemp -d) +trap 'rm -rf "$d"' EXIT +proc=$d/proc +mkdir -p "$proc/pressure" "$d/out" + +put() { + printf "$2" > "$proc/$1" +} + +pressure() { # resource some-total-us full-total-us + put "pressure/$1" "some avg10=0.00 avg60=0.00 avg300=0.00 total=$2\nfull avg10=0.00 avg60=0.00 avg300=0.00 total=$3\n" +} + +process() { # pid ppid comm runtime-ns waittime-ns + mkdir -p "$proc/$1/task/$1" + put "$1/comm" "$3\n" + put "$1/stat" "$1 ($3) S $2 0 0\n" + put "$1/cgroup" "0::/init.scope\n" + put "$1/cmdline" "" + put "$1/schedstat" "$4 $5 1\n" +} + +put vmstat "pgpgin 0\npgpgout 0\n" +put schedstat "version 15\ntimestamp 0\ncpu0 0 0 0 0 0 0 1000 2000 3\n" +pressure cpu 1000 0 +pressure io 1000 500 +pressure memory 0 0 +process 1 0 systemd 5000000 0 +# udevd's second thread ran 7 ms and waited 1 ms +process 74 1 systemd-udevd 1000000 2000000 +mkdir -p "$proc/74/task/75" +put 74/task/75/schedstat "7000000 1000000 1\n" + +timeout 30 ./systemd-bootchart --proc "$proc" -o "$d/out" -r -f 100 -n 40 & +sampler=$! +sleep 0.15 +# a second of CPU stall in one 10 ms interval fills it; IO stalls some and full +pressure cpu 1001000 0 +pressure io 1201000 1100500 +put 74/schedstat "2000000 2000000 2\n" +put 1/schedstat "6000000 0 2\n" +wait $sampler + +svg=$(echo "$d"/out/*.svg) +fail=0 +expect() { + grep -qF -- "$1" "$svg" || { echo "not ok - the chart has no $1"; fail=1; } +} +graph() { # the rects of one pressure graph + sed -n "//,/<\/g>/p" "$svg" | grep '9.0ms, 3.0ms waiting' +expect '9.0ms, 3.0ms waiting - [74]' +graph CPU | grep -q 'class="psome".*height="100.000"' || + { echo "not ok - CPU pressure does not fill the interval with a second's stall"; fail=1; } +graph IO | grep -q 'class="pfull"' || + { echo "not ok - IO pressure draws no full stall"; fail=1; } +[ -z "$(graph Memory)" ] || + { echo "not ok - Memory pressure draws a stall that never happened"; fail=1; } +[ $fail -eq 0 ] || grep -F -e '[CDATA[' -e 'class="p' "$svg" +exit $fail From 7fa59f7b1b3e200e8c6454e33110c08c1dbbdb54 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Sun, 22 Nov 2026 13:09:02 -0300 Subject: [PATCH 6/7] json: the chart's numbers beside the SVG Two boots are compared by numbers, and the SVG holds its numbers only as rectangles. Beside each bootchart-DATE.svg the sampler now writes bootchart-DATE.json: one row per sample of the system's counters as the kernel keeps them, cumulative (schedstat run and wait summed over the CPUs, vmstat's pgpgin and pgpgout, PSI's some and full totals), and each process's pid, parent, name, cgroup, unit, first and last sample, CPU and wait time, bytes read and written, and largest PSS. Rows of numbers under named columns keep it small: 50 KB for 400 samples, against the SVG's 169 KB, sampling a container's /proc. Co-Authored-By: Claude Opus 5.5 --- Makefile.am | 8 ++- man/systemd-bootchart.xml | 7 +- src/bootchart.c | 18 ++++++ src/json.c | 132 ++++++++++++++++++++++++++++++++++++++ src/json.h | 22 +++++++ src/svg.c | 9 ++- tests/json | 61 ++++++++++++++++++ 7 files changed, 252 insertions(+), 5 deletions(-) create mode 100644 src/json.c create mode 100644 src/json.h create mode 100755 tests/json diff --git a/Makefile.am b/Makefile.am index 3f57390..090e881 100644 --- a/Makefile.am +++ b/Makefile.am @@ -74,7 +74,8 @@ EXTRA_DIST = \ tests/identity \ tests/short-lived \ tests/io \ - tests/pressure + tests/pressure \ + tests/json MANPAGES = man/bootchart.conf.5 man/systemd-bootchart.1 MANPAGES_ALIAS = man/bootchart.conf.d.5 @@ -185,6 +186,8 @@ noinst_LTLIBRARIES = libutils.la systemd_bootchart_SOURCES = \ src/bootchart.c \ src/bootchart.h \ + src/json.c \ + src/json.h \ src/store.c \ src/store.h \ src/svg.c \ @@ -200,7 +203,8 @@ TESTS = \ tests/identity \ tests/short-lived \ tests/io \ - tests/pressure + tests/pressure \ + tests/json substitutions = \ '|rootlibexecdir=$(rootlibexecdir)|' diff --git a/man/systemd-bootchart.xml b/man/systemd-bootchart.xml index 4364653..2f867f7 100644 --- a/man/systemd-bootchart.xml +++ b/man/systemd-bootchart.xml @@ -218,7 +218,12 @@ Specify the output directory for the graphs. By default, bootchart writes the graphs to - /run/log. + /run/log. Beside each + bootchart-date.svg + it writes bootchart-date.json, + the chart's numbers for a program to read: the system's cumulative + counters at every sample, and every process's totals. Its layout is + described at the top of src/json.c. diff --git a/src/bootchart.c b/src/bootchart.c index 62f1eca..5d371fc 100644 --- a/src/bootchart.c +++ b/src/bootchart.c @@ -56,6 +56,7 @@ #include "fd-util.h" #include "fileio.h" #include "io-util.h" +#include "json.h" #include "list.h" #include "log.h" #include "macro.h" @@ -326,12 +327,14 @@ int main(int argc, char *argv[]) { _cleanup_closedir_ DIR *proc = NULL; _cleanup_free_ char *build = NULL; _cleanup_fclose_ FILE *of = NULL; + _cleanup_fclose_ FILE *json = NULL; int schfd; struct ps_struct *ps_first; double graph_start; double log_start; double interval; char output_file[PATH_MAX]; + char json_file[PATH_MAX]; char datestr[200]; int pscount = 0; int n_cpus = 0; @@ -514,6 +517,21 @@ int main(int argc, char *argv[]) { log_info("systemd-bootchart wrote %s\n", output_file); + snprintf(json_file, PATH_MAX, "%s/bootchart-%s.json", arg_output_path, datestr); + json = fopen(json_file, "we"); + if (!json) { + log_error("Error opening output file '%s': %m\n", json_file); + return EXIT_FAILURE; + } + + r = json_do(json, head, ps_first, n_cpus, graph_start, interval, overrun); + if (r < 0) { + log_error_errno(r, "Error writing %s: %m", json_file); + return EXIT_FAILURE; + } + + log_info("systemd-bootchart wrote %s\n", json_file); + r = do_journal_append(output_file); if (r < 0) return EXIT_FAILURE; diff --git a/src/json.c b/src/json.c new file mode 100644 index 0000000..9102a9b --- /dev/null +++ b/src/json.c @@ -0,0 +1,132 @@ +/*** + This file is part of systemd-bootchart. + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. +***/ + +/* + * The chart's numbers, beside the SVG, for a program to compare two boots by: the system's + * counters at every sample, and every process's totals. Counters are written as the kernel + * keeps them, cumulative, so a reader takes the differences it needs over the intervals it + * chooses. Times are seconds on the chart's clock: since boot, or since the sampler started + * with --rel. + * + * "samples" holds one row per sample, oldest first, whose values "sample_columns" names: + * the sample's time; /proc/schedstat's run and wait time summed over the CPUs, in ns; + * /proc/vmstat's pgpgin and pgpgout, in KiB; and /proc/pressure's some and full totals for + * cpu, io and memory, in us. + * + * A process's cpu_ns, wait_ns, read_bytes and write_bytes are its totals at the last sample + * that saw it: for a process already running when the chart started, they include what it did + * before. first_seen and last_seen are the times of the samples that saw it first and last. + */ + +#include +#include +#include + +#include "alloc-util.h" +#include "json.h" +#include "list.h" +#include "store.h" +#include "utf8.h" + +static void json_string(FILE *of, const char *s) { + _cleanup_free_ char *escaped = NULL; + const unsigned char *p; + + if (!s) { + fputs("null", of); + return; + } + + if (!utf8_is_printable(s, strlen(s))) { + escaped = utf8_escape_non_printable(s); + if (escaped) + s = escaped; + } + + fputc('"', of); + for (p = (const unsigned char *) s; *p; p++) { + if (*p == '"' || *p == '\\') + fprintf(of, "\\%c", *p); + else if (*p < 0x20) + fprintf(of, "\\u%04x", *p); + else + fputc(*p, of); + } + fputc('"', of); +} + +static struct list_sample_data *oldest(struct list_sample_data *head) { + struct list_sample_data *tail = head; + + LIST_FIND_TAIL(link, head, tail); + return tail; +} + +int json_do(FILE *of, + struct list_sample_data *head, + struct ps_struct *ps_first, + int n_cpus, + double graph_start, + double interval, + int overrun) { + + struct list_sample_data *s; + struct ps_struct *ps; + const char *sep; + + fprintf(of, "{\"version\": 1, \"hz\": %g, \"interval\": %g, \"overrun\": %d, \"relative\": %s, \"cpus\": %d,\n", + arg_hz, interval / 1000000000.0, overrun, arg_relative ? "true" : "false", n_cpus); + + fputs("\"sample_columns\": [\"time\", \"cpu_run_ns\", \"cpu_wait_ns\", \"pgpgin_kb\", \"pgpgout_kb\", " + "\"cpu_some_us\", \"cpu_full_us\", \"io_some_us\", \"io_full_us\", \"memory_some_us\", \"memory_full_us\"],\n", of); + + fputs("\"samples\": [", of); + sep = "\n"; + for (s = oldest(head); s; s = s->link_prev) { + double run = 0, wait = 0; + int c; + + for (c = 0; c < n_cpus; c++) { + run += s->runtime[c]; + wait += s->waittime[c]; + } + + fprintf(of, "%s[%.4f,%.0f,%.0f,%d,%d,%" PRIu64 ",%" PRIu64 ",%" PRIu64 ",%" PRIu64 ",%" PRIu64 ",%" PRIu64 "]", + sep, s->sampletime - graph_start, run, wait, s->blockstat.bi, s->blockstat.bo, + s->pressure[PRESSURE_CPU][PRESSURE_SOME], s->pressure[PRESSURE_CPU][PRESSURE_FULL], + s->pressure[PRESSURE_IO][PRESSURE_SOME], s->pressure[PRESSURE_IO][PRESSURE_FULL], + s->pressure[PRESSURE_MEMORY][PRESSURE_SOME], s->pressure[PRESSURE_MEMORY][PRESSURE_FULL]); + sep = ",\n"; + } + fputs("\n],\n", of); + + fputs("\"processes\": [", of); + sep = "\n"; + for (ps = ps_first->next_ps; ps; ps = ps->next_ps) { + fprintf(of, "%s{\"pid\": %d, \"ppid\": %d, \"name\": ", sep, ps->pid, ps->ppid); + json_string(of, ps->name); + fputs(", \"cgroup\": ", of); + json_string(of, ps->cgroup); + fputs(", \"unit\": ", of); + json_string(of, ps_unit(ps)); + fprintf(of, ", \"first_seen\": %.4f, \"last_seen\": %.4f, \"cpu_ns\": %.0f, \"wait_ns\": %.0f, " + "\"read_bytes\": %" PRIu64 ", \"write_bytes\": %" PRIu64 ", \"pss_max_kb\": %d}", + ps->first->sampledata->sampletime - graph_start, + ps->last->sampledata->sampletime - graph_start, + ps->last->runtime - ps->first->runtime, + ps->last->waittime - ps->first->waittime, + ps->last->read_bytes, + ps->last->write_bytes, + ps->pss_max); + sep = ",\n"; + } + fputs("\n]}\n", of); + + return ferror(of) ? -EIO : 0; +} diff --git a/src/json.h b/src/json.h new file mode 100644 index 0000000..a1fdee5 --- /dev/null +++ b/src/json.h @@ -0,0 +1,22 @@ +#pragma once + +/*** + This file is part of systemd-bootchart. + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. +***/ + +#include + +#include "bootchart.h" + +int json_do(FILE *of, + struct list_sample_data *head, + struct ps_struct *ps_first, + int n_cpus, + double graph_start, + double interval, + int overrun); diff --git a/src/svg.c b/src/svg.c index bc768a0..2a16f73 100644 --- a/src/svg.c +++ b/src/svg.c @@ -864,12 +864,17 @@ static const char *const pressure_names[_PRESSURE_MAX] = { }; /* Whether the kernel reported pressure: a kernel without it leaves every total at zero, and a - * kernel with it has had some task wait for a CPU by the time a chart ends. */ + * kernel with it has had some task wait for a CPU by the time a chart ends. HEAD is the oldest + * sample, as svg_do() walks them. */ static bool svg_has_pressure(struct list_sample_data *head) { + struct list_sample_data *newest = head; int r; + while (newest->link_prev) + newest = newest->link_prev; + for (r = 0; r < _PRESSURE_MAX; r++) - if (head->pressure[r][PRESSURE_SOME] > 0) + if (newest->pressure[r][PRESSURE_SOME] > 0) return true; return false; } diff --git a/tests/json b/tests/json new file mode 100755 index 0000000..bff6784 --- /dev/null +++ b/tests/json @@ -0,0 +1,61 @@ +#! /bin/sh +# Two boots are compared by numbers, not by eye: the sampler writes the chart's numbers as JSON +# beside the SVG, and a program reads them back. +set -e +d=$(mktemp -d) +trap 'rm -rf "$d"' EXIT +proc=$d/proc +mkdir -p "$proc/pressure" "$d/out" + +put() { + printf "$2" > "$proc/$1" +} + +process() { # pid ppid comm cgroup runtime-ns waittime-ns + mkdir -p "$proc/$1/task" + put "$1/comm" "$3\n" + put "$1/stat" "$1 ($3) S $2 0 0\n" + put "$1/cgroup" "0::$4\n" + put "$1/cmdline" "" + put "$1/schedstat" "$5 $6 1\n" + put "$1/io" "read_bytes: 4096\nwrite_bytes: 0\n" +} + +put vmstat "pgpgin 10\npgpgout 20\n" +put schedstat "version 15\ntimestamp 0\ncpu0 0 0 0 0 0 0 1000 2000 3\n" +put pressure/cpu "some avg10=0.00 avg60=0.00 avg300=0.00 total=500\nfull avg10=0.00 avg60=0.00 avg300=0.00 total=0\n" +process 1 0 systemd /init.scope 5000000 0 +# a name a JSON writer has to escape +process 62 1 'say "hi"\\' /system.slice/systemd-journald.service 1000000 250000 + +timeout 30 ./systemd-bootchart --proc "$proc" -o "$d/out" -r -c -f 100 -n 20 + +python3 - "$d"/out/*.json <<'PY' +import json, sys +chart = json.load(open(sys.argv[1])) +errors = [] +def check(ok, what): + if not ok: + errors.append(what) +cols = chart["sample_columns"] +check(cols[:3] == ["time", "cpu_run_ns", "cpu_wait_ns"], "sample columns start with time, run and wait") +check(all(len(row) == len(cols) for row in chart["samples"]), "every sample row has every column") +check(len(chart["samples"]) >= 10, "a row for each of the samples taken") +times = [row[0] for row in chart["samples"]] +check(times == sorted(times), "samples are oldest first") +last = dict(zip(cols, chart["samples"][-1])) +check(last["cpu_run_ns"] == 1000 and last["pgpgin_kb"] == 10 and last["cpu_some_us"] == 500, + "the counters as /proc/schedstat, vmstat and pressure have them: %s" % last) +ps = {p["pid"]: p for p in chart["processes"]} +j = ps.get(62, {}) +check(j.get("name") == 'say "hi"\\', "the name read back: %r" % j.get("name")) +check(j.get("unit") == "systemd-journald.service", "the unit: %r" % j.get("unit")) +check(j.get("cgroup") == "/system.slice/systemd-journald.service", "the cgroup: %r" % j.get("cgroup")) +check(j.get("cpu_ns") == 1000000 and j.get("wait_ns") == 250000, "cpu and wait: %r" % j) +check(j.get("read_bytes") == 4096, "read_bytes: %r" % j.get("read_bytes")) +check(0 <= j.get("first_seen", -1) <= j.get("last_seen", -2), "first_seen before last_seen: %r" % j) +check(chart["hz"] == 100 and chart["relative"] is True, "the settings: %r" % chart) +for e in errors: + print("not ok - " + e) +sys.exit(1 if errors else 0) +PY From 78dc08c4ecac9e770d953a5f472aedb6f321e661 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Sun, 22 Nov 2026 13:15:42 -0300 Subject: [PATCH 7/7] bootchart, svg: a quieter header that says what sampling cost The sampler runs on the CPUs it charts, and on spin-stack/machine's one vCPU its time is time the boot did not get: ~12 ms of CPU at 200 Hz. The header now says what the samples cost, in total and per sample, and the JSON carries it as sampler_cpu_ns. It is the sampler's own CPU time up to the last sample, before drawing. Every process's task directory was listed on every sample to add its threads' times. procfs counts a process's threads in that directory's link count, so a process with one thread is now skipped after a stat. Sampling this laptop's ~600 processes, a sample's CPU went from 6.0 and 6.4 ms to 5.3 and 5.4 ms (two interleaved runs of three); a boot's processes are mostly single-threaded, where the saving is larger. As PID 1's child the sampler kept the name the kernel gave init, and the chart listed it as "init" beside the systemd it forked from. It is now "bootchart". The header's command line, a few hundred characters on a VM, is cut to 150, and kept whole in a comment. It is read through --proc, and a missing one leaves the line empty instead of failing the chart. "recorded N total" counts the samples taken, not the most that could have been. The tables of top consumers, which overlapped at 400 px apart once they carried wait and IO amounts, sit 560 px apart. Co-Authored-By: Claude Opus 5.5 --- Makefile.am | 6 ++++-- src/bootchart.c | 17 +++++++++++++-- src/json.c | 10 ++++++--- src/json.h | 3 ++- src/store.c | 12 +++++++++-- src/svg.c | 56 ++++++++++++++++++++++++++++++++++++------------- src/svg.h | 3 ++- tests/header | 32 ++++++++++++++++++++++++++++ 8 files changed, 114 insertions(+), 25 deletions(-) create mode 100755 tests/header diff --git a/Makefile.am b/Makefile.am index 090e881..2aac669 100644 --- a/Makefile.am +++ b/Makefile.am @@ -75,7 +75,8 @@ EXTRA_DIST = \ tests/short-lived \ tests/io \ tests/pressure \ - tests/json + tests/json \ + tests/header MANPAGES = man/bootchart.conf.5 man/systemd-bootchart.1 MANPAGES_ALIAS = man/bootchart.conf.d.5 @@ -204,7 +205,8 @@ TESTS = \ tests/short-lived \ tests/io \ tests/pressure \ - tests/json + tests/json \ + tests/header substitutions = \ '|rootlibexecdir=$(rootlibexecdir)|' diff --git a/src/bootchart.c b/src/bootchart.c index 5d371fc..56f13e7 100644 --- a/src/bootchart.c +++ b/src/bootchart.c @@ -41,6 +41,8 @@ #include #include #include +#include +#include #include #include #include @@ -347,6 +349,8 @@ int main(int argc, char *argv[]) { .sa_handler = signal_handler, }; bool has_procfs = false; + struct rusage usage; + double sampler_cpu = 0.0; char vmstat_path[PATH_MAX + 8]; parse_conf(); @@ -368,6 +372,10 @@ int main(int argc, char *argv[]) { if (fork()) /* parent */ execl(arg_init_path, arg_init_path, NULL); + + /* The sampler was exec'd as the kernel's init and would be charted as "init", + * beside the systemd it forked from. */ + (void) prctl(PR_SET_NAME, "bootchart"); } argv[0][0] = '@'; @@ -484,6 +492,11 @@ int main(int argc, char *argv[]) { LIST_PREPEND(link, head, sampledata); } + /* what sampling cost, before drawing adds to it */ + if (getrusage(RUSAGE_SELF, &usage) == 0) + sampler_cpu = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec + + (usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / 1000000.0; + /* do some cleanup, close fd's */ ps = ps_first; while (ps->next_running) { @@ -508,7 +521,7 @@ int main(int argc, char *argv[]) { r = svg_do(of, strna(build), head, ps_first, samples, pscount, n_cpus, graph_start, - log_start, interval, overrun); + log_start, interval, overrun, sampler_cpu); if (r < 0) { log_error_errno(r, "Error generating svg file: %m"); @@ -524,7 +537,7 @@ int main(int argc, char *argv[]) { return EXIT_FAILURE; } - r = json_do(json, head, ps_first, n_cpus, graph_start, interval, overrun); + r = json_do(json, head, ps_first, n_cpus, graph_start, interval, overrun, sampler_cpu); if (r < 0) { log_error_errno(r, "Error writing %s: %m", json_file); return EXIT_FAILURE; diff --git a/src/json.c b/src/json.c index 9102a9b..c826344 100644 --- a/src/json.c +++ b/src/json.c @@ -19,6 +19,9 @@ * /proc/vmstat's pgpgin and pgpgout, in KiB; and /proc/pressure's some and full totals for * cpu, io and memory, in us. * + * sampler_cpu_ns is the CPU time the sampler itself took to take the samples, which the + * system's run time includes and which the processes it charted could not use. + * * A process's cpu_ns, wait_ns, read_bytes and write_bytes are its totals at the last sample * that saw it: for a process already running when the chart started, they include what it did * before. first_seen and last_seen are the times of the samples that saw it first and last. @@ -74,14 +77,15 @@ int json_do(FILE *of, int n_cpus, double graph_start, double interval, - int overrun) { + int overrun, + double sampler_cpu) { struct list_sample_data *s; struct ps_struct *ps; const char *sep; - fprintf(of, "{\"version\": 1, \"hz\": %g, \"interval\": %g, \"overrun\": %d, \"relative\": %s, \"cpus\": %d,\n", - arg_hz, interval / 1000000000.0, overrun, arg_relative ? "true" : "false", n_cpus); + fprintf(of, "{\"version\": 1, \"hz\": %g, \"interval\": %g, \"overrun\": %d, \"relative\": %s, \"cpus\": %d, \"sampler_cpu_ns\": %.0f,\n", + arg_hz, interval / 1000000000.0, overrun, arg_relative ? "true" : "false", n_cpus, sampler_cpu * 1000000000.0); fputs("\"sample_columns\": [\"time\", \"cpu_run_ns\", \"cpu_wait_ns\", \"pgpgin_kb\", \"pgpgout_kb\", " "\"cpu_some_us\", \"cpu_full_us\", \"io_some_us\", \"io_full_us\", \"memory_some_us\", \"memory_full_us\"],\n", of); diff --git a/src/json.h b/src/json.h index a1fdee5..e600680 100644 --- a/src/json.h +++ b/src/json.h @@ -19,4 +19,5 @@ int json_do(FILE *of, int n_cpus, double graph_start, double interval, - int overrun); + int overrun, + double sampler_cpu); diff --git a/src/store.c b/src/store.c index e393b8a..b5fa624 100644 --- a/src/store.c +++ b/src/store.c @@ -27,6 +27,7 @@ #include #include #include +#include #include #include @@ -438,6 +439,7 @@ int log_sample(DIR *proc, char filename[PATH_MAX]; int pid = pids[i]; struct ps_struct *ps; + struct stat task_st; ps = ps_first; while (ps->next_running) { @@ -568,9 +570,15 @@ int log_sample(DIR *proc, * See https://github.com/systemd/systemd/issues/139 */ - /* Browse directory "/proc/[pid]/task" to know the thread ids of process [pid] */ + /* Browse directory "/proc/[pid]/task" to know the thread ids of process [pid], + * when it has threads: procfs counts them in the directory's link count, two + * and one a thread. Most of a boot's processes have one, and listing their task + * directories took most of the sampler's time. */ snprintf(filename, sizeof(filename), PID_FMT "/task", pid); - taskfd = openat(procfd, filename, O_RDONLY|O_DIRECTORY|O_CLOEXEC); + if (fstatat(procfd, filename, &task_st, 0) < 0 || task_st.st_nlink <= 3) + taskfd = -1; + else + taskfd = openat(procfd, filename, O_RDONLY|O_DIRECTORY|O_CLOEXEC); if (taskfd >= 0) { _cleanup_closedir_ DIR *taskdir = NULL; diff --git a/src/svg.c b/src/svg.c index 2a16f73..a3b10e9 100644 --- a/src/svg.c +++ b/src/svg.c @@ -74,6 +74,9 @@ static double psize = 0; static double ksize = 0; static double esize = 0; static double pressure_size = 0; + +/* the width of each table of top consumers, which with IO and wait amounts runs to ~90 characters */ +#define TABLE_WIDTH 560 static struct list_sample_data *sampledata; static struct list_sample_data *prev_sampledata; @@ -89,9 +92,10 @@ static void svg_header(FILE *of, struct list_sample_data *head, double graph_sta sampledata_last = sampledata; } - /* min width is about 1600px due to the label */ + /* min width is about 1600px due to the label, and the tables side by side need theirs */ w = 150.0 + 10.0 + time_to_graph(sampledata_last->sampletime - graph_start) + 500; - w = ((w < 1600.0) ? 1600.0 : w); + w = MAX(w, 1600.0); + w = MAX(w, 20.0 + TABLE_WIDTH * (2 + arg_show_cgroup + arg_pss)); /* height is variable based on pss, psize, ksize */ h = 400.0 + (arg_scale_y * 30.0) /* base graphs and title */ @@ -162,8 +166,13 @@ static void svg_header(FILE *of, struct list_sample_data *head, double graph_sta fprintf(of, " ]]>\n \n\n\n"); } -static int svg_title(FILE *of, const char *build, int pscount, double log_start, int overrun) { +static char* xml_comment_encode(const char* name); + +static int svg_title(FILE *of, const char *build, int pscount, double log_start, int overrun, + int n_samples, double sampler_cpu) { _cleanup_free_ char *cmdline = NULL; + _cleanup_free_ char *enc_cmdline = NULL; + char cmdline_path[PATH_MAX + 8]; _cleanup_free_ char *model = NULL; _cleanup_free_ char *buf = NULL; char date[256] = "Unknown"; @@ -173,10 +182,14 @@ static int svg_title(FILE *of, const char *build, int pscount, double log_start, int r; struct utsname uts; - r = read_one_line_file("/proc/cmdline", &cmdline); + xsprintf(cmdline_path, "%s/cmdline", arg_proc_path); + /* a chart without the command line is still a chart, and a test's --proc has none */ + r = read_one_line_file(cmdline_path, &cmdline); if (r < 0) { - log_error_errno(r, "Unable to read cmdline: %m"); - return r; + log_info_errno(r, "Unable to read %s: %m", cmdline_path); + cmdline = strdup(""); + if (!cmdline) + return log_oom(); } /* extract root fs so we can find disk model name in sysfs */ @@ -221,6 +234,13 @@ static int svg_title(FILE *of, const char *build, int pscount, double log_start, fprintf(of, "CPU: %s\n", cpu); if (model) fprintf(of, "Disk: %s\n", model); + /* The command line in full is in a comment: on a VM it is a few hundred characters + * that crowd everything else in the header. */ + enc_cmdline = xml_comment_encode(cmdline); + if (enc_cmdline) + fprintf(of, "\n", enc_cmdline); + if (strlen(cmdline) > 150) + strcpy(cmdline + 147, "..."); fprintf(of, "Boot options: %s\n", cmdline); fprintf(of, "Build: %s\n", build); fprintf(of, "Log start time: %.03fs\n", log_start); @@ -235,7 +255,10 @@ static int svg_title(FILE *of, const char *build, int pscount, double log_start, fprintf(of, "\n"); fprintf(of, "Graph data: %.03f samples/sec, recorded %i total, dropped %i samples, %i processes, %i filtered\n", - arg_hz, arg_samples_len, overrun, pscount, pfiltered); + arg_hz, n_samples, overrun, pscount, pfiltered); + /* The sampler runs on the CPUs it charts, and its time is time the boot did not get. */ + fprintf(of, "Sampler: %.01fms of CPU for %i samples, %.0fus a sample\n", + to_ms(sampler_cpu), n_samples, n_samples > 0 ? sampler_cpu * 1000000.0 / n_samples : 0.0); return 0; } @@ -1528,11 +1551,12 @@ int svg_do(FILE *of, double graph_start, double log_start, double interval, - int overrun) { + int overrun, + double sampler_cpu) { struct ps_struct *ps; double offset = 7; - int r, c; + int r, c, x; sampledata = head; LIST_FIND_TAIL(link, sampledata, head); @@ -1606,23 +1630,26 @@ int svg_do(FILE *of, fprintf(of, "\n\n"); fprintf(of, "\n"); - r = svg_title(of, build, pscount, log_start, overrun); + r = svg_title(of, build, pscount, log_start, overrun, n_samples, sampler_cpu); fprintf(of, "\n\n"); if (r < 0) return r; - fprintf(of, "\n"); + x = 10; + fprintf(of, "\n", x); svg_top_ten_cpu(of, ps_first); fprintf(of, "\n\n"); if (arg_show_cgroup) { - fprintf(of, "\n"); + x += TABLE_WIDTH; + fprintf(of, "\n", x); svg_top_ten_units(of, ps_first); fprintf(of, "\n\n"); } - fprintf(of, "\n", arg_show_cgroup ? 810 : 410); + x += TABLE_WIDTH; + fprintf(of, "\n", x); svg_top_ten_io(of, ps_first); fprintf(of, "\n\n"); @@ -1637,7 +1664,8 @@ int svg_do(FILE *of, svg_pss_graph(of, head, ps_first, graph_start); fprintf(of, "\n\n"); - fprintf(of, "\n", arg_show_cgroup ? 1210 : 810); + x += TABLE_WIDTH; + fprintf(of, "\n", x); svg_top_ten_pss(of, ps_first); fprintf(of, "\n\n"); } diff --git a/src/svg.h b/src/svg.h index 674c6f6..58004a7 100644 --- a/src/svg.h +++ b/src/svg.h @@ -35,4 +35,5 @@ int svg_do(FILE *of, double graph_start, double log_start, double interval, - int overrun); + int overrun, + double sampler_cpu); diff --git a/tests/header b/tests/header new file mode 100755 index 0000000..3a13a99 --- /dev/null +++ b/tests/header @@ -0,0 +1,32 @@ +#! /bin/sh +# The chart's header says what the sampler cost, since it ran on the CPUs it charted, and the +# JSON carries the same number. A VM's long command line is cut in the header and kept whole in +# a comment, where XML does not allow "--". +set -e +d=$(mktemp -d) +trap 'rm -rf "$d"' EXIT +proc=$d/proc +mkdir -p "$proc/1/task/1" "$d/out" +printf 'pgpgin 0\npgpgout 0\n' > "$proc/vmstat" +printf 'version 15\ntimestamp 0\ncpu0 0 0 0 0 0 0 1000 2000 3\n' > "$proc/schedstat" +printf 'systemd\n' > "$proc/1/comm" +printf '1 (systemd) S 0 0 0\n' > "$proc/1/stat" +printf '0::/init.scope\n' > "$proc/1/cgroup" +printf '5000000 0 1\n' > "$proc/1/schedstat" +cmdline="console=ttyS0 root=/dev/vda -- $(printf 'option%03d ' $(seq 1 40))" +printf '%s\n' "$cmdline" > "$proc/cmdline" + +timeout 30 ./systemd-bootchart --proc "$proc" -o "$d/out" -r -f 100 -n 20 + +fail=0 +grep -qE '>Sampler: [0-9]+\.[0-9]ms of CPU for 20 samples, [0-9]+us a sample<' "$d"/out/*.svg || + { echo "not ok - the header does not say what 20 samples cost"; fail=1; } +grep -qE '"sampler_cpu_ns": [1-9][0-9]*,' "$d"/out/*.json || + { echo "not ok - the JSON does not say what the samples cost"; fail=1; } +grep -qE ']*>Boot options: console=ttyS0 root=/dev/vda .{119}\.\.\.' "$d"/out/*.svg || + { echo "not ok - the header's command line is not cut to 150 characters"; fail=1; } +grep -qF "