diff --git a/dtmerge/dtoverlay.c b/dtmerge/dtoverlay.c index 1cbb5ab..7c7d147 100644 --- a/dtmerge/dtoverlay.c +++ b/dtmerge/dtoverlay.c @@ -2972,18 +2972,23 @@ int dtoverlay_save_dtb(const DTBLOB_T *dtb, const char *filename) { dtoverlay_error("fwrite failed"); err = -2; - goto error_exit; } - if (dtb->trailer_len && - (fwrite(dtb->trailer, dtb->trailer_len, 1, fp) != 1)) + else if (dtb->trailer_len && + (fwrite(dtb->trailer, dtb->trailer_len, 1, fp) != 1)) { dtoverlay_error("fwrite failed"); err = -2; - goto error_exit; } - dtoverlay_debug("wrote %ld bytes to '%s'", len, filename); - fclose(fp); + /* Buffered data is only written (and the error reported) here */ + if ((fclose(fp) != 0) && !err) + { + dtoverlay_error("failed to write '%s'", filename); + err = -2; + } + + if (!err) + dtoverlay_debug("wrote %d bytes to '%s'", len, filename); } else { @@ -2991,7 +2996,6 @@ int dtoverlay_save_dtb(const DTBLOB_T *dtb, const char *filename) err = -1; } - error_exit: return err; } diff --git a/dtmerge/dtoverlay_main.c b/dtmerge/dtoverlay_main.c index 081d6f4..6fd11aa 100644 --- a/dtmerge/dtoverlay_main.c +++ b/dtmerge/dtoverlay_main.c @@ -33,22 +33,32 @@ modification, are permitted provided that the following conditions are met: #include #include #include +#include +#include +#include +#include +#include #include #include "dtoverlay.h" #include "utils.h" - -#define CFG_DIR_1 "/sys/kernel/config" -#define CFG_DIR_2 "/config" +#define CFG_DIR "/sys/kernel/config" +/* Where to mount configfs if it isn't at CFG_DIR (relative to WORK_DIR) */ +#define CFG_MOUNT_SUBDIR "configfs" #define DT_SUBDIR "/device-tree" -#define WORK_DIR "/tmp/.dtoverlays" +#define WORK_DIR "/run/dtoverlays" #define OVERLAY_SRC_SUBDIR "overlays" #define README_FILE "README" #define DT_OVERLAYS_SUBDIR "overlays" #define DTOVERLAY_PATH_MAX 128 #define DIR_MODE 0755 +#define LOCK_FILE "lock" +#define LOCK_POLL_MS 50 +#define LOCK_TIMEOUT_MS 30000 +/* Set in the environment of the dtoverlay-pre/post hooks */ +#define HOOK_ENV "DTOVERLAY_IN_HOOK" enum { @@ -88,10 +98,16 @@ static int dtoverlay_list(STATE_T *state); static int dtoverlay_list_all(STATE_T *state); static void usage(void); static void root_check(void); +static int check_work_dir(const char *dir, int create); +static void lock_state(int exclusive); +static void defer_signals(int defer); +static int read_live_dt(const char *dtb_file); static void overlay_help(const char *overlay, const char **params); static int apply_overlay(const char *overlay_file, const char *overlay); +static int save_dtb_atomic(DTBLOB_T *dtb, const char *filename); +static void discard_overlay_file(const char *filename); static int overlay_applied(const char *overlay_dir); static STATE_T *read_state(const char *dir); @@ -106,6 +122,7 @@ const char *error_file = NULL; const char *platform_string; int platform_string_len; int dry_run = 0; +static int lock_fd = -1; char cell_source_loc[DTOVERLAY_MAX_PATH]; int cell_source_loc_len; @@ -120,6 +137,9 @@ int main(int argc, const char **argv) int ret = 0; STATE_T *state = NULL; const char *cfg_dir; + int have_work_dir = 1; + int modifying; + int in_hook; cmd_name = argv[0]; if (strrchr(cmd_name, '/')) @@ -219,6 +239,16 @@ int main(int argc, const char **argv) dtoverlay_enable_debug(opt_verbose); + modifying = !dry_run && ((opt == OPT_ADD) || (opt == OPT_REMOVE) || + (opt == OPT_REMOVE_FROM)); + in_hook = (getenv(HOOK_ENV) != NULL); + + /* The hooks run while the state is locked, so any attempt to change it + from a hook would deadlock (and risks infinite recursion) */ + if (modifying && in_hook) + fatal_error("%s can't add or remove overlays from a dtoverlay-pre or " + "dtoverlay-post hook", cmd_name); + if (!overlay_src_dir) { /* Find the overlays and README */ @@ -251,30 +281,56 @@ int main(int argc, const char **argv) goto orderly_exit; } - if (!dir_exists(work_dir)) + if (modifying) + root_check(); + + if (!dry_run) { - if (mkdir(work_dir, DIR_MODE) != 0) - fatal_error("Failed to create '%s' - %d", work_dir, errno); + /* Only root may create the state directory. Others can still list + the active overlays if it exists. */ + have_work_dir = check_work_dir(work_dir, getuid() == 0); + + /* Serialise against other instances, holding the lock until exit. + A hook runs while its parent holds the lock exclusively, so the + state can't change under it and it must not wait for the lock. */ + if (have_work_dir && !in_hook) + lock_state(modifying); } error_file = sprintf_dup("%s/%s", work_dir, "error.dtb"); - cfg_dir = CFG_DIR_1 DT_SUBDIR; + cfg_dir = CFG_DIR DT_SUBDIR; if (!dry_run && !dir_exists(cfg_dir)) { + /* configfs isn't mounted in the usual place, so mount it in the + state directory, which is on a tmpfs */ + const char *mount_dir = sprintf_dup("%s/%s", work_dir, + CFG_MOUNT_SUBDIR); + root_check(); - cfg_dir = CFG_DIR_2; + /* Only one instance may mount configfs. Listing only holds a shared + lock, so upgrade it (by now the root user has a lock file). */ + if (!modifying && !in_hook) + lock_state(1); + + cfg_dir = sprintf_dup("%s%s", mount_dir, DT_SUBDIR); if (!dir_exists(cfg_dir)) { - if (mkdir(cfg_dir, DIR_MODE) != 0) - fatal_error("Failed to create '%s' - %d", cfg_dir, errno); + if ((mkdir(mount_dir, DIR_MODE) != 0) && (errno != EEXIST)) + fatal_error("Failed to create '%s' - %s", mount_dir, + strerror(errno)); + if (mount("configfs", mount_dir, "configfs", + MS_NOSUID | MS_NODEV | MS_NOEXEC, NULL) != 0) + fatal_error("Failed to mount configfs on '%s' - %s", + mount_dir, strerror(errno)); + if (!dir_exists(cfg_dir)) + { + umount(mount_dir); + fatal_error("configfs has no '%s' folder - incompatible kernel", + DT_SUBDIR + 1); + } } - - cfg_dir = CFG_DIR_2 DT_SUBDIR; - if (!dir_exists(cfg_dir) && - (run_cmd("mount -t configfs none '%s'", cfg_dir) != 0)) - fatal_error("Failed to mount configfs - %d", errno); } if (!platform_string) @@ -290,7 +346,7 @@ int main(int argc, const char **argv) if (!dir_exists(dt_overlays_dir)) fatal_error("configfs overlays folder not found - incompatible kernel"); - state = read_state(work_dir); + state = read_state(have_work_dir ? work_dir : NULL); if (!state) fatal_error("Failed to read state"); } @@ -302,7 +358,7 @@ int main(int argc, const char **argv) case OPT_REMOVE_FROM: if (!dry_run) { - root_check(); + setenv(HOOK_ENV, "1", 1); run_cmd("which dtoverlay-pre >/dev/null 2>&1 && dtoverlay-pre"); } break; @@ -310,6 +366,11 @@ int main(int argc, const char **argv) break; } + /* Don't let a signal leave configfs and the state directory out of + step - act on it once they agree again */ + if (modifying) + defer_signals(1); + switch (opt) { case OPT_ADD: @@ -332,6 +393,10 @@ int main(int argc, const char **argv) break; } + /* Any pending signal is delivered here, and the hook doesn't run */ + if (modifying) + defer_signals(0); + switch (opt) { case OPT_ADD: @@ -616,8 +681,7 @@ static int dtoverlay_add(STATE_T *state, const char *overlay, { /* Convert /proc/device-tree to a .dtb and load it */ overlay_file = sprintf_dup("%s/%s", work_dir, "base.dtb"); - if (run_cmd("dtc -I fs -O dtb -o '%s' /proc/device-tree 1>/dev/null 2>&1", - overlay_file) != 0) + if (read_live_dt(overlay_file) != 0) return error("Failed to read active DTB"); } else if ((len > 0) && (strcmp(overlay + len, ".dtbo") == 0)) @@ -758,16 +822,14 @@ static int dtoverlay_add(STATE_T *state, const char *overlay, /* then write the overlay to the file */ dtoverlay_pack_dtb(overlay_dtb); - dtoverlay_save_dtb(overlay_dtb, overlay_file); + err = save_dtb_atomic(overlay_dtb, overlay_file); dtoverlay_free_dtb(overlay_dtb); + if (err) + return error("Failed to write '%s'", overlay_file); if (!dry_run && !apply_overlay(overlay_file, overlay_name)) { - if (error_file) - { - rename(overlay_file, error_file); - free_string(error_file); - } + discard_overlay_file(overlay_file); return 1; } @@ -781,6 +843,7 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) char *end; int overlay_len; int count = state->count; + int failed = 0; int rmpos; int i; @@ -894,6 +957,7 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) if (!dtb) { error("Failed to re-apply dtparam"); + failed++; continue; } @@ -902,6 +966,7 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) { error("Failed to re-apply dtparam"); dtoverlay_free_dtb(dtb); + failed++; continue; } @@ -922,6 +987,7 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) { error("out of memory re-applying dtparam"); dtoverlay_free_dtb(dtb); + failed++; continue; } @@ -932,7 +998,8 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) } paramv[j] = NULL; - /* Create the new overlay */ + /* Create the new overlay. If it can't be applied, the + file is discarded. */ ret = dtoverlay_add(state, "dtparam", paramc, paramv); free(paramv); dtoverlay_free_dtb(dtb); @@ -941,10 +1008,18 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) { rename(filename, new_file); ret = !apply_overlay(new_file, new_name); + if (ret != 0) + discard_overlay_file(new_file); } + free_string(new_file); + free_string(new_name); if (ret != 0) { - error("Failed to re-apply dtparam"); + /* Its file has gone, so the next overlay takes its + number */ + error("Failed to re-apply '%.*s' - it is no longer loaded", + len, left); + failed++; continue; } state->count++; @@ -952,7 +1027,7 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) } } - return 0; + return failed ? 1 : 0; } static int dtoverlay_list(STATE_T *state) @@ -981,15 +1056,19 @@ static int dtoverlay_list(STATE_T *state) saved_overlay = sprintf_dup("%s/%s", work_dir, name); dtb = dtoverlay_load_dtb(saved_overlay, 0); + free_string(saved_overlay); - if (dtoverlay_dtb_trailer(dtb)) + if (!dtb) + printf("%d: %.*s \n", i, (int)(right - left), left); + else if (dtoverlay_dtb_trailer(dtb)) printf("%d: %.*s %.*s\n", i, (int)(right - left), left, dtoverlay_dtb_trailer_len(dtb), (char *)dtoverlay_dtb_trailer(dtb)); else printf("%d: %.*s\n", i, (int)(right - left), left); - dtoverlay_free_dtb(dtb); + if (dtb) + dtoverlay_free_dtb(dtb); } } @@ -1128,6 +1207,157 @@ static void root_check(void) fatal_error("Must be run as root - try 'sudo %s ...'", cmd_name); } +/* Returns 1 if the directory exists (creating it if requested), 0 if it + doesn't. Exits if it exists but can't be trusted. */ +static int check_work_dir(const char *dir, int create) +{ + struct stat st; + + if (create && (mkdir(dir, DIR_MODE) != 0) && (errno != EEXIST)) + fatal_error("Failed to create '%s' - %s", dir, strerror(errno)); + + if (lstat(dir, &st) != 0) + { + if (errno == ENOENT) + return 0; + fatal_error("Failed to stat '%s' - %s", dir, strerror(errno)); + } + + /* The contents are replayed into the kernel, so they must only be + writable by root */ + if (!S_ISDIR(st.st_mode) || (st.st_uid != 0) || + (st.st_mode & (S_IWGRP | S_IWOTH))) + fatal_error("'%s' is not a directory owned and only writable by root", + dir); + + return 1; +} + +/* Take a shared or exclusive lock on the state. It is released when the + process exits, however that happens. */ +static void lock_state(int exclusive) +{ + int op = (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB; + int waited_ms = 0; + + if (lock_fd < 0) + { + const char *lock_path = sprintf_dup("%s/%s", work_dir, LOCK_FILE); + + if (getuid() == 0) + lock_fd = open(lock_path, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, + 0644); + else + lock_fd = open(lock_path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + + if (lock_fd < 0) + { + /* Root has never modified the state, so there is nothing to + protect */ + if ((errno == ENOENT) && (getuid() != 0)) + return; + fatal_error("Failed to open '%s' - %s", lock_path, + strerror(errno)); + } + free_string(lock_path); + } + + while (flock(lock_fd, op) != 0) + { + if (errno == EINTR) + continue; + if (errno != EWOULDBLOCK) + fatal_error("Failed to lock '%s' - %s", work_dir, strerror(errno)); + if (waited_ms == 0) + dtoverlay_debug("waiting for another instance to finish"); + if (waited_ms >= LOCK_TIMEOUT_MS) + fatal_error("Timed out waiting for another dtoverlay or dtparam " + "to finish"); + usleep(LOCK_POLL_MS * 1000); + waited_ms += LOCK_POLL_MS; + } +} + +/* Block (or unblock) the signals that would normally terminate the process + when sent by a user or a terminal. Unblocking delivers any that arrived + in the meantime. SIGKILL can't be blocked. Child processes (dtc, when a + dtparam is regenerated) inherit the blocked set. */ +static const int deferred_signals[] = +{ + SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGPIPE +}; + +#define NUM_DEFERRED_SIGNALS \ + (int)(sizeof(deferred_signals) / sizeof(deferred_signals[0])) + +static void defer_signals(int defer) +{ + static sigset_t old_set; + sigset_t set; + int i; + + if (defer) + { + sigemptyset(&set); + for (i = 0; i < NUM_DEFERRED_SIGNALS; i++) + sigaddset(&set, deferred_signals[i]); + sigprocmask(SIG_BLOCK, &set, &old_set); + } + else + { + sigprocmask(SIG_SETMASK, &old_set, NULL); + } +} + +/* Snapshot the live device tree into a .dtb file using dtc. Signals sent + to the process group (Ctrl-C, timeout) would otherwise kill dtc even + while they are deferred here, losing a dtparam that is being regenerated, + so while they are deferred the child ignores them - an ignored signal + stays ignored across exec. Running dtc directly also avoids passing the + filename through a shell. */ +static int read_live_dt(const char *dtb_file) +{ + sigset_t blocked; + int status; + pid_t pid; + int i; + + dtoverlay_debug("dtc -I fs -O dtb -o %s /proc/device-tree", dtb_file); + + pid = fork(); + if (pid < 0) + return -1; + + if (pid == 0) + { + int fd = open("/dev/null", O_RDWR); + if (fd >= 0) + { + dup2(fd, STDOUT_FILENO); + dup2(fd, STDERR_FILENO); + } + + sigprocmask(SIG_BLOCK, NULL, &blocked); + for (i = 0; i < NUM_DEFERRED_SIGNALS; i++) + { + if (sigismember(&blocked, deferred_signals[i])) + signal(deferred_signals[i], SIG_IGN); + } + + execlp("dtc", "dtc", "-I", "fs", "-O", "dtb", "-o", dtb_file, + "/proc/device-tree", (char *)NULL); + _exit(127); + } + + while (waitpid(pid, &status, 0) < 0) + { + if (errno != EINTR) + return -1; + } + + return (WIFEXITED(status) && (WEXITSTATUS(status) == 0)) ? 0 : -1; +} + static void overlay_help(const char *overlay, const char **params) { OVERLAY_HELP_STATE_T *state; @@ -1243,6 +1473,42 @@ static int apply_overlay(const char *overlay_file, const char *overlay) return ret; } +/* Write a DTB so that a reader never sees a partial file, even if this + process is killed. The state lives on a tmpfs that doesn't survive a + power cut, so there is no need to fsync. The file must be in work_dir; + the temporary name is hidden from seq_filter. */ +static int save_dtb_atomic(DTBLOB_T *dtb, const char *filename) +{ + const char *tmp_file = sprintf_dup("%s/.new.dtbo", work_dir); + int err; + + err = dtoverlay_save_dtb(dtb, tmp_file); + if (!err && (rename(tmp_file, filename) != 0)) + err = -1; + if (err) + unlink(tmp_file); + free_string(tmp_file); + + return err; +} + +/* Remove the file of an overlay that failed to apply from the sequence. + The first failure is kept as error.dtb for diagnosis. */ +static void discard_overlay_file(const char *filename) +{ + if (error_file) + { + rename(filename, error_file); + free_string(error_file); + /* Don't delete it on exit */ + error_file = NULL; + } + else + { + unlink(filename); + } +} + static int overlay_applied(const char *overlay_dir) { char status[7] = { '\0' }; @@ -1284,7 +1550,18 @@ static STATE_T *read_state(const char *dir) if (state) { - state->count = scandir(dir, &state->namelist, seq_filter, seq_compare); + state->count = 0; + state->namelist = NULL; + if (dir) + { + state->count = scandir(dir, &state->namelist, seq_filter, + seq_compare); + if (state->count < 0) + { + free(state); + return NULL; + } + } for (i = 0; i < state->count; i++) {