HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/repart/repart.c

483,181 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: b40c7a91acf99c5ac898f4de16e45b142c19fa8c

Lines 11001–11995 of 11,995

 
        if ((S_ISREG(st.st_mode) || S_ISBLK(st.st_mode)) && (mode & O_ACCMODE_STRICT) != O_RDONLY) {
                _cleanup_close_ int new_fd = fd_reopen(fd, mode);
                if (new_fd < 0)
                        return new_fd;
 
                close_and_replace(fd, new_fd);
        }
 
        if (S_ISREG(st.st_mode)) {
                *ret = TAKE_PTR(found_path);
                *ret_fd = TAKE_FD(fd);
                return 0;
        }
 
        if (S_ISBLK(st.st_mode)) {
                /* Refuse referencing explicit block devices if a root dir is specified, after all we should
                 * not be able to leave the image the root path constrains us to. */
                if (root)
                        return -EPERM;
 
                fd_devno = devno = st.st_rdev;
        } else if (S_ISDIR(st.st_mode)) {
 
                devno = st.st_dev;
                if (major(devno) == 0) {
                        r = btrfs_get_block_device_fd(fd, &devno);
                        if (r == -ENOTTY) /* not btrfs */
                                return -ENODEV;
                        if (r < 0)
                                return r;
                }
        } else
                return -ENOTBLK;
 
        /* From dm-crypt to backing partition */
        r = block_get_originating(devno, &devno, /* recursive= */ false);
        if (r == -ENOENT)
                log_debug_errno(r, "Device '%s' has no dm-crypt/dm-verity device, no need to look for underlying block device.", p);
        else if (r < 0)
                log_debug_errno(r, "Failed to find underlying block device for '%s', ignoring: %m", p);
 
        /* From partition to whole disk containing it */
        r = block_get_whole_disk(devno, &devno);
        if (r < 0)
                log_debug_errno(r, "Failed to find whole disk block device for '%s', ignoring: %m", p);
 
        r = devname_from_devnum(S_IFBLK, devno, &node);
        if (r < 0)
                return log_debug_errno(r, "Failed to determine canonical path for '%s': %m", p);
 
        /* Only if we still look at the same block device we can reuse the fd. Otherwise return an
         * invalidated fd. */
        if (fd_devno != MODE_INVALID && fd_devno == devno) {
                /* Tell udev not to interfere while we are processing the device */
                if (flock(fd, arg_dry_run ? LOCK_SH : LOCK_EX) < 0)
                        return log_error_errno(errno, "Failed to lock device '%s': %m", node);
 
                *ret_fd = TAKE_FD(fd);
        } else
                *ret_fd = -EBADF;
 
        *ret = TAKE_PTR(node);
        return 0;
}
 
static int find_root(Context *context) {
        _cleanup_free_ char *device = NULL;
        int r, open_flags = O_CLOEXEC|context_open_mode(context);
 
        assert(context);
 
        if (arg_node_none)
                return 0;
 
        if (arg_node) {
                if (context->empty == EMPTY_CREATE) {
                        _cleanup_close_ int fd = -EBADF;
                        _cleanup_free_ char *s = NULL;
 
                        s = strdup(arg_node);
                        if (!s)
                                return log_oom();
 
                        fd = xopenat_full(
                                        AT_FDCWD,
                                        arg_node,
                                        open_flags|O_CREAT|O_EXCL|O_NOFOLLOW,
                                        arg_cow < 0 ? 0 : (arg_cow > 0 ? XO_COW : XO_NOCOW),
                                        0666);
                        if (fd < 0)
                                return log_error_errno(fd, "Failed to create '%s': %m", arg_node);
 
                        context->node = TAKE_PTR(s);
                        context->node_is_our_file = true;
                        context->backing_fd = TAKE_FD(fd);
                        return 0;
                }
 
                /* Note that we don't specify a root argument here: if the user explicitly configured a node
                 * we'll take it relative to the host, not the image */
                r = acquire_root_devno(arg_node, NULL, open_flags, &context->node, &context->backing_fd);
                if (r == -EUCLEAN)
                        return btrfs_log_dev_root(LOG_ERR, r, arg_node);
                if (r < 0)
                        return log_error_errno(r, "Failed to open file or determine backing device of %s: %m", arg_node);
 
                return 0;
        }
 
        assert(IN_SET(context->empty, EMPTY_REFUSE, EMPTY_ALLOW));
 
        /* If the root mount has been replaced by some form of volatile file system (overlayfs), the
         * original root block device node is symlinked in /run/systemd/volatile-root. Let's read that
         * here. */
        r = readlink_malloc("/run/systemd/volatile-root", &device);
        if (r == -ENOENT) { /* volatile-root not found */
                /* Let's search for the root device. We look for two cases here: first in /, and then in /usr. The
                * latter we check for cases where / is a tmpfs and only /usr is an actual persistent block device
                * (think: volatile setups) */
 
                FOREACH_STRING(p, "/", "/usr") {
 
                        r = acquire_root_devno(p, arg_root, open_flags|O_DIRECTORY, &context->node,
                                               &context->backing_fd);
                        if (r < 0) {
                                if (r == -EUCLEAN)
                                        return btrfs_log_dev_root(LOG_ERR, r, p);
                                if (r != -ENODEV)
                                        return log_error_errno(r, "Failed to determine backing device of %s%s: %m", strempty(arg_root), p);
                        } else
                                return 0;
                }
        } else if (r < 0)
                return log_error_errno(r, "Failed to read symlink /run/systemd/volatile-root: %m");
        else {
                r = acquire_root_devno(device, /* root= */ NULL, open_flags, &context->node, &context->backing_fd);
                if (r == -EUCLEAN)
                        return btrfs_log_dev_root(LOG_ERR, r, device);
                if (r < 0)
                        return log_error_errno(r, "Failed to open file or determine backing device of %s: %m", device);
 
                return 0;
        }
 
        return log_error_errno(SYNTHETIC_ERRNO(ENODEV), "Failed to discover root block device.");
}
 
static int resize_pt(int fd, uint64_t sector_size) {
        _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
        int r;
 
        /* After resizing the backing file we need to resize the partition table itself too, so that it takes
         * possession of the enlarged backing file. For this it suffices to open the device with libfdisk and
         * immediately write it again, with no changes. */
 
        r = fdisk_new_context_at(fd, /* path= */ NULL, /* read_only= */ false, sector_size, &c);
        if (r < 0)
                return log_error_errno(r, "Failed to open device '%s': %m", FORMAT_PROC_FD_PATH(fd));
 
        r = sym_fdisk_has_label(c);
        if (r < 0)
                return log_error_errno(r, "Failed to determine whether disk '%s' has a disk label: %m", FORMAT_PROC_FD_PATH(fd));
        if (r == 0) {
                log_debug("Not resizing partition table, as there currently is none.");
                return 0;
        }
 
        r = sym_fdisk_write_disklabel(c);
        if (r < 0)
                return log_error_errno(r, "Failed to write resized partition table: %m");
 
        log_info("Resized partition table.");
        return 1;
}
 
static int resize_backing_fd(
                const char *node,           /* The primary way we access the disk image to operate on */
                int *fd,                    /* An O_RDONLY fd referring to that inode */
                const char *backing_file,   /* If the above refers to a loopback device, the backing regular file for that, which we can grow */
                LoopDevice *loop_device,
                uint64_t sector_size) {
 
        _cleanup_close_ int writable_fd = -EBADF;
        uint64_t current_size;
        struct stat st;
        int r;
 
        assert(node);
        assert(fd);
 
        if (arg_size == UINT64_MAX) /* Nothing to do */
                return 0;
 
        if (*fd < 0) {
                /* Open the file if we haven't opened it yet. Note that we open it read-only here, just to
                 * keep a reference to the file we can pass around. */
                *fd = open(node, O_RDONLY|O_CLOEXEC);
                if (*fd < 0)
                        return log_error_errno(errno, "Failed to open '%s' in order to adjust size: %m", node);
        }
 
        if (fstat(*fd, &st) < 0)
                return log_error_errno(errno, "Failed to stat '%s': %m", node);
 
        if (S_ISBLK(st.st_mode)) {
                if (!backing_file)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Cannot resize block device '%s'.", node);
 
                assert(loop_device);
 
                r = blockdev_get_device_size(*fd, &current_size);
                if (r < 0)
                        return log_error_errno(r, "Failed to determine size of block device %s: %m", node);
        } else {
                r = stat_verify_regular(&st);
                if (r < 0)
                        return log_error_errno(r, "Specified path '%s' is not a regular file or loopback block device, cannot resize: %m", node);
 
                assert(!backing_file);
                assert(!loop_device);
                current_size = st.st_size;
        }
 
        if (current_size >= arg_size) {
                log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)",
                         node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
                return 0;
        }
 
        if (S_ISBLK(st.st_mode)) {
                assert(backing_file);
 
                /* This is a loopback device. We can't really grow those directly, but we can grow the
                 * backing file, hence let's do that. */
 
                writable_fd = open(backing_file, O_WRONLY|O_CLOEXEC|O_NONBLOCK);
                if (writable_fd < 0)
                        return log_error_errno(errno, "Failed to open backing file '%s': %m", backing_file);
 
                if (fstat(writable_fd, &st) < 0)
                        return log_error_errno(errno, "Failed to stat() backing file '%s': %m", backing_file);
 
                r = stat_verify_regular(&st);
                if (r < 0)
                        return log_error_errno(r, "Backing file '%s' of block device is not a regular file: %m", backing_file);
 
                if ((uint64_t) st.st_size != current_size)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Size of backing file '%s' of loopback block device '%s' don't match, refusing.",
                                               node, backing_file);
        } else {
                assert(S_ISREG(st.st_mode));
                assert(!backing_file);
 
                /* The file descriptor is read-only. In order to grow the file we need to have a writable fd. We
                 * reopen the file for that temporarily. We keep the writable fd only open for this operation though,
                 * as fdisk can't accept it anyway. */
 
                writable_fd = fd_reopen(*fd, O_WRONLY|O_CLOEXEC);
                if (writable_fd < 0)
                        return log_error_errno(writable_fd, "Failed to reopen backing file '%s' writable: %m", node);
        }
 
        if (!arg_discard) {
                if (fallocate(writable_fd, 0, 0, arg_size) < 0) {
                        if (!ERRNO_IS_NOT_SUPPORTED(errno))
                                return log_error_errno(errno, "Failed to grow '%s' from %s to %s by allocation: %m",
                                                       node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
 
                        /* Fallback to truncation, if fallocate() is not supported. */
                        log_debug("Backing file system does not support fallocate(), falling back to ftruncate().");
                } else {
                        if (current_size == 0) /* Likely regular file just created by us */
                                log_info("Allocated %s for '%s'.", FORMAT_BYTES(arg_size), node);
                        else
                                log_info("File '%s' grown from %s to %s by allocation.",
                                         node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
 
                        goto done;
                }
        }
 
        if (ftruncate(writable_fd, arg_size) < 0)
                return log_error_errno(errno, "Failed to grow '%s' from %s to %s by truncation: %m",
                                       node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
 
        if (current_size == 0) /* Likely regular file just created by us */
                log_info("Sized '%s' to %s.", node, FORMAT_BYTES(arg_size));
        else
                log_info("File '%s' grown from %s to %s by truncation.",
                         node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
 
done:
        r = resize_pt(writable_fd, sector_size);
        if (r < 0)
                return r;
 
        if (loop_device) {
                r = loop_device_refresh_size(loop_device, UINT64_MAX, arg_size);
                if (r < 0)
                        return log_error_errno(r, "Failed to update loop device size: %m");
        }
 
        return 1;
}
 
static int determine_auto_size(
                Context *c,
                int level,
                uint64_t *ret_current_size,
                uint64_t *ret_foreign_size,
                uint64_t *ret_minimal_size) {
 
        uint64_t current_size, foreign_size, minimal_size;
 
        assert(c);
 
        /* At the beginning of the image, some size is reserved for:
         * Protective MBR (1 block) + GPT header (1 block) +
         * Primary partition table (minimum 16KiB) = (2 * c->sector_size) + (16 * 1024)
         *
         * Note that fdisk usually sets the first usable block to 1MiB (at least for
         * disks larger than 4MiB), so we just force it to that as well. If fdisk
         * decides to set it lower, we made the image a bit larger than necessary,
         * if it sets it higher, we'd have a problem. */
        minimal_size = 1024 * 1024;
        /* Of course need to align the start to our grain size as well */
        minimal_size = round_up_size(minimal_size, c->grain_size);
 
        /* At the end of the image, there is size reserved for:
         * Secondary partition table (minimum 16KiB) + GPT header (1 block) */
        minimal_size += (16 * 1024) + c->sector_size;
 
        if (c->from_scratch)
                current_size = 0;
        else
                current_size = minimal_size;
 
        foreign_size = 0;
 
        LIST_FOREACH(partitions, p, c->partitions) {
                uint64_t m;
 
                if (PARTITION_IS_FOREIGN(p))
                        foreign_size += p->current_size;
 
                if (PARTITION_EXISTS(p))
                        current_size += p->current_size;
 
                if (p->dropped || PARTITION_SUPPRESSED(p))
                        continue;
 
                m = partition_min_size_with_padding(c, p);
                if (m > UINT64_MAX - minimal_size)
                        return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Image would grow too large, refusing.");
 
                minimal_size += m;
        }
 
        if (current_size != 0)
                /* Image already allocated? Then show its size. */
                log_full(level,
                         "Automatically determined minimal disk image size as %s, current block device/image size is %s.",
                         FORMAT_BYTES(minimal_size), FORMAT_BYTES(current_size));
        else
                /* If the image is being created right now, then it has no previous size, suppress any comment about it hence. */
                log_full(level,
                         "Automatically determined minimal disk image size as %s.",
                         FORMAT_BYTES(minimal_size));
 
        if (ret_current_size)
                *ret_current_size = current_size;
        if (ret_foreign_size)
                *ret_foreign_size = foreign_size;
        if (ret_minimal_size)
                *ret_minimal_size = minimal_size;
 
        return 0;
}
 
static void context_sort_partitions(Context *context) {
        assert(context);
 
        Partition *p;
        LIST_HEAD(Partition, new_partitions) = NULL;
        LIST_HEAD(Partition, existing_partitions) = NULL;
        LIST_HEAD(Partition, dropped_partitions) = NULL;
 
        while ((p = LIST_POP(partitions, context->partitions))) {
                if (p->allocated_to_area)
                        LIST_APPEND(partitions, new_partitions, p);
                else if (p->dropped)
                        LIST_APPEND(partitions, dropped_partitions, p);
                else
                        LIST_APPEND(partitions, existing_partitions, p);
        }
 
        /* First sort existing partitions by their offset */
        while ((p = LIST_POP(partitions, existing_partitions))) {
                Partition *cursor = NULL;
 
                assert(p->offset != UINT64_MAX);
 
                LIST_FOREACH(partitions, q, context->partitions)
                        if (p->offset > q->offset)
                                cursor = q;
 
                LIST_INSERT_AFTER(partitions, context->partitions, cursor, p);
        }
 
        /* Then insert the partitions we'll newly create in the free areas */
        while ((p = LIST_POP(partitions, new_partitions))) {
                FreeArea *a = p->allocated_to_area;
                Partition *cursor = a->after;
 
                /* Advance past partitions of this area that we already inserted */
                LIST_FOREACH(partitions, q, context->partitions)
                        if (q->allocated_to_area == a)
                                cursor = q;
 
                LIST_INSERT_AFTER(partitions, context->partitions, cursor, p);
        }
 
        /* Finally append any dropped partitions to the end of the list */
        while ((p = LIST_POP(partitions, dropped_partitions))) {
                assert(p->offset == UINT64_MAX);
 
                LIST_APPEND(partitions, context->partitions, p);
        }
}
 
static int context_ponder(Context *context) {
        int r;
 
        assert(context);
 
        (void) context_notify(context, PROGRESS_PLACING, /* object= */ NULL, UINT_MAX);
 
        /* First try to fit new partitions in, dropping by priority until it fits */
        for (;;) {
                uint64_t largest_free_area;
 
                if (context_allocate_partitions(context, &largest_free_area))
                        break; /* Success! */
 
                if (context_unmerge_and_allocate_partitions(context))
                        break; /* We had to un-suppress a supplement or few, but still success! */
 
                if (context_drop_or_foreignize_one_priority(context))
                        continue; /* Still no luck. Let's drop a priority and try again. */
 
                /* No more priorities left to drop. This configuration just doesn't fit on this disk...
                 * In Varlink service mode the failure is reported to the client as a structured error,
                 * hence only log at debug level here. */
                return log_full_errno(arg_varlink ? LOG_DEBUG : LOG_ERR,
                                      SYNTHETIC_ERRNO(ENOSPC),
                                      "Can't fit requested partitions into available free space (%s), refusing.",
                                      FORMAT_BYTES(largest_free_area));
        }
 
        LIST_FOREACH(partitions, p, context->partitions) {
                if (!p->supplement_for)
                        continue;
 
                if (PARTITION_SUPPRESSED(p)) {
                        assert(!p->allocated_to_area);
                        p->dropped = true;
 
                        log_debug("Partition %s can be merged into %s, suppressing supplement.",
                                  p->definition_path, p->supplement_for->definition_path);
                } else if (PARTITION_EXISTS(p))
                        log_info("Partition %s already exists on disk, using supplement verbatim.",
                                 p->definition_path);
                else
                        log_info("Couldn't allocate partitions with %s merged into %s, using supplement verbatim.",
                                 p->definition_path, p->supplement_for->definition_path);
        }
 
        /* Now that we know which new partition goes into which free area, reorder
         * the partitions list so that the list is in the right order. */
        context_sort_partitions(context);
 
        /* Now assign free space according to the weight logic */
        r = context_grow_partitions(context);
        if (r < 0)
                return r;
 
        /* Now calculate where each new partition gets placed */
        context_place_partitions(context);
 
        return 0;
}
 
static JSON_DISPATCH_ENUM_DEFINE(json_dispatch_empty_mode, EmptyMode, empty_mode_from_string);
 
typedef struct RunParameters {
        char *node;
        EmptyMode empty;
        bool dry_run;
        sd_id128_t seed;
        char **definitions;
        bool defer_partitions_empty;
        bool defer_partitions_factory_reset;
} RunParameters;
 
static void run_parameters_done(RunParameters *p) {
        assert(p);
 
        p->node = mfree(p->node);
        p->definitions = strv_free(p->definitions);
}
 
static int vl_method_run(
                sd_varlink *link,
                sd_json_variant *parameters,
                sd_varlink_method_flags_t flags,
                void *userdata) {
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "node",                        SD_JSON_VARIANT_STRING,  sd_json_dispatch_string,  offsetof(RunParameters, node),                           SD_JSON_NULLABLE  },
                { "empty",                       SD_JSON_VARIANT_STRING,  json_dispatch_empty_mode, offsetof(RunParameters, empty),                          SD_JSON_MANDATORY },
                { "seed",                        SD_JSON_VARIANT_STRING,  sd_json_dispatch_id128,   offsetof(RunParameters, seed),                           SD_JSON_NULLABLE  },
                { "dryRun",                      SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(RunParameters, dry_run),                        SD_JSON_MANDATORY },
                { "definitions",                 SD_JSON_VARIANT_ARRAY,   json_dispatch_strv_path,  offsetof(RunParameters, definitions),                    SD_JSON_STRICT    },
                { "deferPartitionsEmpty",        SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(RunParameters, defer_partitions_empty),         SD_JSON_NULLABLE  },
                { "deferPartitionsFactoryReset", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(RunParameters, defer_partitions_factory_reset), SD_JSON_NULLABLE  },
                {}
        };
 
        int r;
 
        assert(link);
 
        _cleanup_(run_parameters_done) RunParameters p = {
                .empty = _EMPTY_MODE_INVALID,
                .dry_run = true,
        };
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
        if (r != 0)
                return r;
 
        /* If no device node is specified, this is a dry run. Refuse if the caller claims otherwise. */
        if (!p.node && !p.dry_run)
                return sd_varlink_error_invalid_parameter_name(link, "dryRun");
 
        _cleanup_(context_freep) Context* context = NULL;
        context = context_new(
                        p.definitions,
                        p.empty,
                        p.dry_run,
                        p.seed);
        if (!context)
                return log_oom();
 
        context->defer_partitions_empty = p.defer_partitions_empty;
        context->defer_partitions_factory_reset = p.defer_partitions_factory_reset;
 
        if (FLAGS_SET(flags, SD_VARLINK_METHOD_MORE))
                context->link = sd_varlink_ref(link);
 
        r = context_read_seed(context, arg_root);
        if (r < 0)
                return r;
 
        r = context_read_definitions(context);
        if (r < 0)
                return r;
 
        if (p.node) {
                r = acquire_root_devno(p.node, NULL, O_CLOEXEC|context_open_mode(context), &context->node, &context->backing_fd);
                if (r < 0)
                        return log_error_errno(r, "Failed to open file or determine backing device of %s: %m", p.node);
 
                r = context_load_partition_table(context);
                if (r == -EHWPOISON)
                        return sd_varlink_error(link, "io.systemd.Repart.ConflictingDiskLabelPresent", NULL);
        } else
                r = context_load_fallback_metrics(context);
        if (r < 0)
                return r;
        context->from_scratch = r > 0; /* Starting from scratch */
 
        r = context_open_copy_block_paths(context, (dev_t) -1);
        if (r < 0)
                return r;
 
        r = context_open_btrfs_filesystems(context);
        if (r < 0)
                return r;
 
        r = context_acquire_partition_uuids_and_labels(context);
        if (r < 0)
                return r;
 
        r = context_update_verity_size(context);
        if (r < 0)
                return r;
 
        r = context_minimize(context);
        if (r < 0)
                return r;
 
        /* If we have no node, just sum up how much space we need */
        if (!context->node) {
                /* Check if space issue is caused by the whole disk being too small */
                uint64_t minimal_size;
                r = determine_auto_size(context, LOG_DEBUG, /* ret_current_size= */ NULL, /* ret_foreign_size= */ NULL, &minimal_size);
                if (r < 0)
                        return r;
 
                return sd_varlink_replybo(
                                link,
                                SD_JSON_BUILD_PAIR_UNSIGNED("minimalSizeBytes", minimal_size));
        }
 
        r = context_verify_eltorito_overlap(context);
        if (r < 0)
                return r;
 
        r = context_ponder(context);
        if (r == -ENOSPC) {
                uint64_t current_size, foreign_size, minimal_size;
 
                r = determine_auto_size(context, LOG_DEBUG, &current_size, &foreign_size, &minimal_size);
                if (r < 0)
                        return r;
 
                uint64_t needed_size = LESS_BY(minimal_size, foreign_size);
 
                /* Check if space issue is caused by the whole disk being too small */
                if (needed_size > context->total)
                        return sd_varlink_errorbo(
                                        link,
                                        "io.systemd.Repart.DiskTooSmall",
                                        SD_JSON_BUILD_PAIR_UNSIGNED("currentSizeBytes", context->total),
                                        SD_JSON_BUILD_PAIR_UNSIGNED("minimalSizeBytes", minimal_size));
 
                /* Or if the disk would fit, but theres's not enough unallocated space */
                uint64_t need_free = LESS_BY(minimal_size, current_size);
                return sd_varlink_errorbo(
                                link,
                                "io.systemd.Repart.InsufficientFreeSpace",
                                SD_JSON_BUILD_PAIR_UNSIGNED("currentSizeBytes", context->total),
                                JSON_BUILD_PAIR_UNSIGNED_NON_ZERO("needFreeBytes", need_free),
                                SD_JSON_BUILD_PAIR_UNSIGNED("minimalSizeBytes", minimal_size));
        }
        if (r < 0)
                return r;
 
        if (p.dry_run) {
                uint64_t minimal_size;
 
                /* If we are doing a dry-run, report the minimal size. */
                r = determine_auto_size(context, LOG_DEBUG, /* ret_current_size= */ NULL, /* ret_foreign_size= */ NULL, &minimal_size);
                if (r < 0)
                        return r;
 
                bool count_partitions = IN_SET(context->empty, EMPTY_REFUSE, EMPTY_ALLOW);
                uint64_t n_partitions = 0;
 
                if (count_partitions)
                        LIST_FOREACH(partitions, pp, context->partitions)
                                n_partitions += PARTITION_EXISTS(pp);
 
                /* In 'force' and 'require' modes the existing partition table is not read, hence we don't
                 * know how many partitions the disk contains, and say nothing about it. */
                return sd_varlink_replybo(
                                link,
                                SD_JSON_BUILD_PAIR_UNSIGNED("minimalSizeBytes", minimal_size),
                                SD_JSON_BUILD_PAIR_UNSIGNED("currentSizeBytes", context->total),
                                SD_JSON_BUILD_PAIR_CONDITION(count_partitions,
                                                             "partitionCount", SD_JSON_BUILD_UNSIGNED(n_partitions)));
        }
 
        r = context_write_partition_table(context);
        if (r < 0)
                return r;
 
        r = context_write_eltorito(context);
        if (r < 0)
                return r;
 
        context_disarm_auto_removal(context);
 
        return sd_varlink_reply(link, NULL);
}
 
static int vl_server(void) {
        _cleanup_(sd_varlink_server_unrefp) sd_varlink_server *varlink_server = NULL;
        int r;
 
        /* Invocation as Varlink service */
 
        r = varlink_server_new(&varlink_server,
                               SD_VARLINK_SERVER_ROOT_ONLY | SD_VARLINK_SERVER_MYSELF_ONLY,
                               /* userdata= */ NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate Varlink server: %m");
 
        r = sd_varlink_server_add_interface(varlink_server, &vl_interface_io_systemd_Repart);
        if (r < 0)
                return log_error_errno(r, "Failed to add Varlink interface: %m");
 
        r = sd_varlink_server_bind_method_many(
                        varlink_server,
                        "io.systemd.Repart.ListCandidateDevices", vl_method_list_candidate_devices,
                        "io.systemd.Repart.Run",                  vl_method_run);
        if (r < 0)
                return log_error_errno(r, "Failed to bind Varlink methods: %m");
 
        r = sd_varlink_server_loop_auto(varlink_server);
        if (r < 0)
                return log_error_errno(r, "Failed to run Varlink event loop: %m");
 
        return 0;
}
 
static int run(int argc, char *argv[]) {
        _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
        _cleanup_(umount_and_freep) char *mounted_dir = NULL;
        _cleanup_(context_freep) Context* context = NULL;
        bool node_is_our_loop = false;
        int r;
 
        LIBBLKID_NOTE(required);
        LIBCRYPTO_NOTE(recommended);
        LIBCRYPTSETUP_NOTE(recommended);
        LIBFDISK_NOTE(required);
        LIBMOUNT_NOTE(required);
        LIBSELINUX_NOTE(recommended);
        TPM2_NOTE(suggested);
 
        log_setup();
 
        r = parse_argv(argc, argv);
        if (r <= 0)
                return r;
 
        r = dlopen_fdisk(LOG_ERR);
        if (r < 0)
                return r;
 
        if (arg_varlink)
                return vl_server();
 
        r = parse_proc_cmdline_factory_reset();
        if (r < 0)
                return r;
 
        if (arg_image) {
                assert(!arg_root);
 
                /* Mount this strictly read-only: we shall modify the partition table, not the file
                 * systems */
                r = mount_image_privately_interactively(
                                arg_image,
                                arg_image_policy,
                                DISSECT_IMAGE_MOUNT_READ_ONLY |
                                (arg_node ? DISSECT_IMAGE_DEVICE_READ_ONLY : 0) | /* If a different node to make changes to is specified let's open the device in read-only mode) */
                                DISSECT_IMAGE_GPT_ONLY |
                                DISSECT_IMAGE_RELAX_VAR_CHECK |
                                DISSECT_IMAGE_USR_NO_ROOT |
                                DISSECT_IMAGE_REQUIRE_ROOT |
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY,
                                &mounted_dir,
                                /* ret_dir_fd= */ NULL,
                                &loop_device);
                if (r < 0)
                        return r;
 
                arg_root = strdup(mounted_dir);
                if (!arg_root)
                        return log_oom();
 
                if (!arg_node && !arg_node_none) {
                        arg_node = strdup(loop_device->node);
                        if (!arg_node)
                                return log_oom();
 
                        /* Remember that the device we are about to manipulate is actually the one we
                         * allocated here, and thus to increase its backing file we know what to do */
                        node_is_our_loop = true;
                }
        }
 
        if (!arg_copy_source && arg_root) {
                /* If no explicit copy source is specified, then use --root=/--image= */
                arg_copy_source = strdup(arg_root);
                if (!arg_copy_source)
                        return log_oom();
        }
 
        context = context_new(
                        arg_definitions,
                        arg_empty,
                        arg_dry_run,
                        arg_seed);
        if (!context)
                return log_oom();
 
        r = context_load_keys(context);
        if (r < 0)
                return r;
 
        context->defer_partitions_empty = arg_defer_partitions_empty;
        context->defer_partitions_factory_reset = arg_defer_partitions_factory_reset;
 
        r = context_read_seed(context, arg_root);
        if (r < 0)
                return r;
 
        r = context_copy_from(context);
        if (r < 0)
                return r;
 
        if (arg_make_ddi) {
                _cleanup_free_ char *d = NULL, *dp = NULL;
                assert(!context->definitions);
 
                d = strjoin(arg_make_ddi, ".repart.d/");
                if (!d)
                        return log_oom();
 
                r = search_and_access(d, F_OK, NULL, CONF_PATHS_STRV("systemd/repart/definitions"), &dp);
                if (r < 0)
                        return log_error_errno(r, "DDI type '%s' is not defined: %m", arg_make_ddi);
 
                if (strv_consume(&context->definitions, TAKE_PTR(dp)) < 0)
                        return log_oom();
        } else
                strv_uniq(context->definitions);
 
        r = context_read_definitions(context);
        if (r < 0)
                return r;
 
        r = find_root(context);
        if (r == -ENODEV)
                return 76; /* Special return value which means "Root block device not found, so not doing
                            * anything". This isn't really an error when called at boot. */
        if (r < 0)
                return r;
 
        if (context->node) {
                if (arg_size != UINT64_MAX) {
                        r = resize_backing_fd(
                                        context->node,
                                        &context->backing_fd,
                                        node_is_our_loop ? arg_image : NULL,
                                        node_is_our_loop ? loop_device : NULL,
                                        context->sector_size);
                        if (r < 0)
                                return r;
                }
 
                r = context_load_partition_table(context);
                if (r == -EHWPOISON)
                        return 77; /* Special return value which means "Not GPT, so not doing anything". This isn't
                                    * really an error when called at boot. */
        } else
                r = context_load_fallback_metrics(context);
        if (r < 0)
                return r;
        context->from_scratch = r > 0; /* Starting from scratch */
 
        r = check_mkfs(context);
        if (r < 0)
                return r;
 
        if (arg_can_factory_reset) {
                r = context_can_factory_reset(context);
                if (r < 0)
                        return r;
                if (r == 0)
                        return EXIT_FAILURE;
 
                return 0;
        }
 
        r = context_factory_reset(context);
        if (r < 0)
                return r;
        if (r > 0) {
                /* Reload the reduced partition table */
                context_unload_partition_table(context);
                r = context_load_partition_table(context);
                if (r < 0)
                        return r;
        }
 
        /* Open all files to copy blocks from now, since we want to take their size into consideration */
        r = context_open_copy_block_paths(
                        context,
                        loop_device ? loop_device->devno :         /* if --image= is specified, only allow partitions on the loopback device */
                                      /* if --root= is specified, don't accept any block device, unless it
                                       * was set automatically because we are in the initrd  */
                                      arg_root && !arg_image && !arg_relax_copy_block_security ? 0 :
                                      (dev_t) -1);                 /* if neither is specified, make no restrictions */
        if (r < 0)
                return r;
 
        r = context_open_btrfs_filesystems(context);
        if (r < 0)
                return r;
 
        /* Make sure each partition has a unique UUID and unique label */
        r = context_acquire_partition_uuids_and_labels(context);
        if (r < 0)
                return r;
 
        r = context_fstab(context);
        if (r < 0)
                return r;
 
        r = context_crypttab(context, /* late= */ false);
        if (r < 0)
                return r;
 
        r = context_update_verity_size(context);
        if (r < 0)
                return r;
 
        r = context_minimize(context);
        if (r < 0)
                return r;
 
        if (arg_node_none) {
                (void) determine_auto_size(context, LOG_INFO, /* ret_current_size= */ NULL, /* ret_foreign_size= */ NULL, /* ret_minimal_size= */ NULL);
                return 0;
        }
 
        if (arg_size_auto) {
                r = determine_auto_size(context, LOG_INFO, /* ret_current_size= */ NULL, /* ret_foreign_size= */ NULL, &arg_size);
                if (r < 0)
                        return r;
 
                /* Flush out everything again, and let's grow the file first, then start fresh */
                context_unload_partition_table(context);
 
                assert(arg_size != UINT64_MAX);
                r = resize_backing_fd(
                                context->node,
                                &context->backing_fd,
                                node_is_our_loop ? arg_image : NULL,
                                node_is_our_loop ? loop_device : NULL,
                                context->sector_size);
                if (r < 0)
                        return r;
 
                r = context_load_partition_table(context);
                if (r < 0)
                        return r;
        }
 
        r = context_verify_eltorito_overlap(context);
        if (r < 0)
                return r;
 
        r = context_ponder(context);
        if (r == -ENOSPC) {
                /* When we hit space issues, tell the user the minimal size. */
                (void) determine_auto_size(context, LOG_INFO, /* ret_current_size= */ NULL, /* ret_foreign_size= */ NULL, /* ret_minimal_size= */ NULL);
                return r;
        }
        if (r < 0)
                return r;
 
        (void) context_dump(context, /* late= */ false);
 
        r = context_write_partition_table(context);
        if (r < 0)
                return r;
 
        r = context_write_eltorito(context);
        if (r < 0)
                return r;
 
        r = context_split(context);
        if (r < 0)
                return r;
 
        r = context_crypttab(context, /* late= */ true);
        if (r < 0)
                return r;
 
        (void) context_dump(context, /* late= */ true);
 
        context_disarm_auto_removal(context);
 
        return 0;
}
 
DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);