HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/home/homework-luks.c

162,356 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: d4ce674c3601e23183894548a8204dc282786674

Lines 3001–4000 of 4,048

        struct statfs sfs;
        int r;
 
        assert(fd >= 0);
        assert(st);
        assert(ret);
 
        /* Determines the maximum file size we might be able to grow the image file referenced by the fd to. */
 
        r = stat_verify_regular(st);
        if (r < 0)
                return log_error_errno(r, "Image file is not a regular file, refusing: %m");
 
        if (syncfs(fd) < 0)
                return log_error_errno(errno, "Failed to synchronize file system backing image file: %m");
 
        if (fstatfs(fd, &sfs) < 0)
                return log_error_errno(errno, "Failed to statfs() image file: %m");
 
        used = (uint64_t) st->st_blocks * 512;
        avail = (uint64_t) sfs.f_bsize * sfs.f_bavail;
 
        if (avail > UINT64_MAX - used)
                sum = UINT64_MAX;
        else
                sum = avail + used;
 
        *ret = DISK_SIZE_ROUND_DOWN(MIN(sum, USER_DISK_SIZE_MAX));
        return 0;
}
 
static int resize_fs_loop(
                UserRecord *h,
                HomeSetup *setup,
                int resize_type,
                uint64_t old_fs_size,
                uint64_t new_fs_size,
                uint64_t *ret_fs_size) {
 
        uint64_t current_fs_size;
        unsigned n_iterations = 0;
        int r;
 
        assert(h);
        assert(setup);
        assert(setup->root_fd >= 0);
 
        /* A bisection loop trying to find the closest size to what the user asked for. (Well, we bisect like
         * this only when we *shrink* the fs — if we grow the fs there's no need to bisect.) */
 
        current_fs_size = old_fs_size;
        for (uint64_t lower_boundary = new_fs_size, upper_boundary = old_fs_size, try_fs_size = new_fs_size;;) {
                bool worked;
 
                n_iterations++;
 
                /* Now resize the file system */
                if (resize_type == CAN_RESIZE_ONLINE) {
                        r = resize_fs(setup->root_fd, try_fs_size, NULL);
                        if (r < 0) {
                                if (!ERRNO_IS_DISK_SPACE(r) || new_fs_size > old_fs_size) /* Not a disk space issue? Not trying to shrink? */
                                        return log_error_errno(r, "Failed to resize file system: %m");
 
                                log_debug_errno(r, "Shrinking from %s to %s didn't work, not enough space for contained data.", FORMAT_BYTES(current_fs_size), FORMAT_BYTES(try_fs_size));
                                worked = false;
                        } else {
                                log_debug("Successfully resized from %s to %s.", FORMAT_BYTES(current_fs_size), FORMAT_BYTES(try_fs_size));
                                current_fs_size = try_fs_size;
                                worked = true;
                        }
 
                        /* If we hit a disk space issue and are shrinking the fs, then maybe it helps to
                         * increase the image size. */
                } else {
                        r = ext4_offline_resize_fs(setup, try_fs_size, user_record_luks_discard(h), user_record_mount_flags(h), h->luks_extra_mount_options);
                        if (r < 0)
                                return r;
 
                        /* For now, when we fail to shrink an ext4 image we'll not try again via the
                         * bisection logic. We might add that later, but given this involves shelling out
                         * multiple programs, it's a bit too cumbersome for my taste. */
 
                        worked = true;
                        current_fs_size = try_fs_size;
                }
 
                if (new_fs_size > old_fs_size) /* If we are growing we are done after one iteration */
                        break;
 
                /* If we are shrinking then let's adjust our bisection boundaries and try again. */
                if (worked)
                        upper_boundary = MIN(upper_boundary, try_fs_size);
                else
                        lower_boundary = MAX(lower_boundary, try_fs_size);
 
                /* OK, this attempt to shrink didn't work. Let's try between the old size and what worked. */
                if (lower_boundary >= upper_boundary) {
                        log_debug("Image can't be shrunk further (range to try is empty).");
                        break;
                }
 
                /* Let's find a new value to try half-way between the lower boundary and the upper boundary
                 * to try now. */
                try_fs_size = DISK_SIZE_ROUND_DOWN(lower_boundary + (upper_boundary - lower_boundary) / 2);
                if (try_fs_size <= lower_boundary || try_fs_size >= upper_boundary) {
                        log_debug("Image can't be shrunk further (remaining range to try too small).");
                        break;
                }
        }
 
        log_debug("Bisection loop completed after %u iterations.", n_iterations);
 
        if (ret_fs_size)
                *ret_fs_size = current_fs_size;
 
        return 0;
}
 
static int resize_image_loop(
                UserRecord *h,
                HomeSetup *setup,
                uint64_t old_image_size,
                uint64_t new_image_size,
                uint64_t *ret_image_size) {
 
        uint64_t current_image_size;
        unsigned n_iterations = 0;
        int r;
 
        assert(h);
        assert(setup);
        assert(setup->image_fd >= 0);
 
        /* A bisection loop trying to find the closest size to what the user asked for. (Well, we bisect like
         * this only when we *grow* the image — if we shrink the image then there's no need to bisect.) */
 
        current_image_size = old_image_size;
        for (uint64_t lower_boundary = old_image_size, upper_boundary = new_image_size, try_image_size = new_image_size;;) {
                bool worked;
 
                n_iterations++;
 
                r = home_truncate(h, setup->image_fd, try_image_size);
                if (r < 0) {
                        if (!ERRNO_IS_DISK_SPACE(r) || new_image_size < old_image_size) /* Not a disk space issue? Not trying to grow? */
                                return r;
 
                        log_debug_errno(r, "Growing from %s to %s didn't work, not enough space on backing disk.", FORMAT_BYTES(current_image_size), FORMAT_BYTES(try_image_size));
                        worked = false;
                } else if (r > 0) { /* Success: allocation worked */
                        log_debug("Resizing from %s to %s via allocation worked successfully.", FORMAT_BYTES(current_image_size), FORMAT_BYTES(try_image_size));
                        current_image_size = try_image_size;
                        worked = true;
                } else { /* Success, but through truncation, not allocation. */
                        log_debug("Resizing from %s to %s via truncation worked successfully.", FORMAT_BYTES(old_image_size), FORMAT_BYTES(try_image_size));
                        current_image_size = try_image_size;
                        break; /* there's no point in the bisection logic if this was plain truncation and
                                * not allocation, let's exit immediately. */
                }
 
                if (new_image_size < old_image_size) /* If we are shrinking we are done after one iteration */
                        break;
 
                /* If we are growing then let's adjust our bisection boundaries and try again */
                if (worked)
                        lower_boundary = MAX(lower_boundary, try_image_size);
                else
                        upper_boundary = MIN(upper_boundary, try_image_size);
 
                if (lower_boundary >= upper_boundary) {
                        log_debug("Image can't be grown further (range to try is empty).");
                        break;
                }
 
                try_image_size = DISK_SIZE_ROUND_DOWN(lower_boundary + (upper_boundary - lower_boundary) / 2);
                if (try_image_size <= lower_boundary || try_image_size >= upper_boundary) {
                        log_debug("Image can't be grown further (remaining range to try too small).");
                        break;
                }
        }
 
        log_debug("Bisection loop completed after %u iterations.", n_iterations);
 
        if (ret_image_size)
                *ret_image_size = current_image_size;
 
        return 0;
}
 
int home_resize_luks(
                UserRecord *h,
                HomeSetupFlags flags,
                HomeSetup *setup,
                PasswordCache *cache,
                UserRecord **ret_home) {
 
        uint64_t old_image_size, new_image_size, old_fs_size, new_fs_size, crypto_offset, crypto_offset_bytes,
                new_partition_size, smallest_fs_size, resized_fs_size;
        _cleanup_(user_record_unrefp) UserRecord *header_home = NULL, *embedded_home = NULL, *new_home = NULL;
        _cleanup_(fdisk_unref_tablep) struct fdisk_table *table = NULL;
        struct fdisk_partition *partition = NULL;
        _cleanup_close_ int opened_image_fd = -EBADF;
        _cleanup_free_ char *whole_disk = NULL;
        int r, resize_type, image_fd = -EBADF, reconciled = USER_RECONCILE_IDENTICAL;
        sd_id128_t disk_uuid;
        const char *ip, *ipo;
        struct statfs sfs;
        struct stat st;
        enum {
                INTENTION_DONT_KNOW = 0,    /* These happen to match the return codes of CMP() */
                INTENTION_SHRINK = -1,
                INTENTION_GROW = 1,
        } intention = INTENTION_DONT_KNOW;
 
        assert(h);
        assert(user_record_storage(h) == USER_LUKS);
        assert(setup);
 
        r = dlopen_fdisk(LOG_DEBUG);
        if (r < 0)
                return r;
 
        r = dlopen_cryptsetup(LOG_DEBUG);
        if (r < 0)
                return r;
 
        assert_se(ipo = user_record_image_path(h));
        ip = strdupa_safe(ipo); /* copy out since original might change later in home record object */
 
        if (setup->image_fd < 0) {
                setup->image_fd = open_image_file(h, NULL, &st);
                if (setup->image_fd < 0)
                        return setup->image_fd;
        } else {
                if (fstat(setup->image_fd, &st) < 0)
                        return log_error_errno(errno, "Failed to stat image file %s: %m", ip);
        }
 
        image_fd = setup->image_fd;
 
        if (S_ISBLK(st.st_mode)) {
                dev_t parent;
 
                r = block_get_whole_disk(st.st_rdev, &parent);
                if (r < 0)
                        return log_error_errno(r, "Failed to acquire whole block device for %s: %m", ip);
                if (r > 0) {
                        /* If we shall resize a file system on a partition device, then let's figure out the
                         * whole disk device and operate on that instead, since we need to rewrite the
                         * partition table to resize the partition. */
 
                        log_info("Operating on partition device %s, using parent device.", ip);
 
                        opened_image_fd = r = device_open_from_devnum(S_IFBLK, parent, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK, &whole_disk);
                        if (r < 0)
                                return log_error_errno(r, "Failed to open whole block device for %s: %m", ip);
 
                        image_fd = opened_image_fd;
 
                        if (fstat(image_fd, &st) < 0)
                                return log_error_errno(errno, "Failed to stat whole block device %s: %m", whole_disk);
                } else
                        log_info("Operating on whole block device %s.", ip);
 
                r = blockdev_get_device_size(image_fd, &old_image_size);
                if (r < 0)
                        return log_error_errno(r, "Failed to determine size of original block device: %m");
 
                if (flock(image_fd, LOCK_EX) < 0) /* make sure udev doesn't read from it while we operate on the device */
                        return log_error_errno(errno, "Failed to lock block device %s: %m", ip);
 
                new_image_size = old_image_size; /* we can't resize physical block devices */
        } else {
                r = stat_verify_regular(&st);
                if (r < 0)
                        return log_error_errno(r, "Image %s is not a block device nor regular file: %m", ip);
 
                old_image_size = st.st_size;
 
                /* Note an asymmetry here: when we operate on loopback files the specified disk size we get we
                 * apply onto the loopback file as a whole. When we operate on block devices we instead apply
                 * to the partition itself only. */
 
                if (FLAGS_SET(flags, HOME_SETUP_RESIZE_MINIMIZE)) {
                        new_image_size = 0;
                        intention = INTENTION_SHRINK;
                } else {
                        uint64_t new_image_size_rounded;
 
                        new_image_size_rounded = DISK_SIZE_ROUND_DOWN(h->disk_size);
 
                        if (old_image_size >= new_image_size_rounded && old_image_size <= h->disk_size) {
                                /* If exact match, or a match after we rounded down, don't do a thing */
                                log_info("Image size already matching, skipping operation.");
                                return 0;
                        }
 
                        new_image_size = new_image_size_rounded;
                        intention = CMP(new_image_size, old_image_size); /* Is this a shrink */
                }
        }
 
        r = home_setup_luks(
                        h,
                        flags,
                        whole_disk,
                        setup,
                        cache,
                        FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES) ? NULL : &header_home);
        if (r < 0)
                return r;
 
        if (!FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES)) {
                reconciled = home_load_embedded_identity(h, setup->root_fd, header_home, USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL, cache, &embedded_home, &new_home);
                if (reconciled < 0)
                        return reconciled;
        }
 
        r = home_maybe_shift_uid(h, flags, setup);
        if (r < 0)
                return r;
 
        log_info("offset = %" PRIu64 ", size = %" PRIu64 ", image = %" PRIu64, setup->partition_offset, setup->partition_size, old_image_size);
 
        if ((UINT64_MAX - setup->partition_offset) < setup->partition_size ||
            setup->partition_offset + setup->partition_size > old_image_size)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Old partition doesn't fit in backing storage, refusing.");
 
        /* Get target partition information in here for new_partition_size calculation */
        r = prepare_resize_partition(
                        image_fd,
                        setup->partition_offset,
                        setup->partition_size,
                        &disk_uuid,
                        &table,
                        &partition);
        if (r < 0)
                return r;
 
        if (S_ISREG(st.st_mode)) {
                uint64_t partition_table_extra, largest_size;
 
                partition_table_extra = old_image_size - setup->partition_size;
 
                r = get_largest_image_size(setup->image_fd, &st, &largest_size);
                if (r < 0)
                        return r;
                if (new_image_size > largest_size)
                        new_image_size = largest_size;
 
                if (new_image_size < partition_table_extra)
                        new_image_size = partition_table_extra;
 
                new_partition_size = DISK_SIZE_ROUND_DOWN(new_image_size - partition_table_extra);
        } else {
                assert(S_ISBLK(st.st_mode));
 
                if (FLAGS_SET(flags, HOME_SETUP_RESIZE_MINIMIZE)) {
                        new_partition_size = 0;
                        intention = INTENTION_SHRINK;
                } else {
                        uint64_t new_partition_size_rounded = DISK_SIZE_ROUND_DOWN(h->disk_size);
 
                        if (h->disk_size == UINT64_MAX && partition) {
                                r = get_maximum_partition_size(image_fd, partition, &new_partition_size_rounded);
                                if (r < 0)
                                        return r;
                        }
 
                        if (setup->partition_size >= new_partition_size_rounded &&
                            setup->partition_size <= h->disk_size) {
                                log_info("Partition size already matching, skipping operation.");
                                return 0;
                        }
 
                        new_partition_size = new_partition_size_rounded;
                        intention = CMP(new_partition_size, setup->partition_size);
                }
        }
 
        if ((UINT64_MAX - setup->partition_offset) < new_partition_size ||
            setup->partition_offset + new_partition_size > new_image_size)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "New partition doesn't fit into backing storage, refusing.");
 
        crypto_offset = sym_crypt_get_data_offset(setup->crypt_device);
        if (crypto_offset > UINT64_MAX/512U)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "LUKS2 data offset out of range, refusing.");
        crypto_offset_bytes = crypto_offset * 512U;
        if (setup->partition_size <= crypto_offset_bytes)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Weird, old crypto payload offset doesn't actually fit in partition size?");
 
        /* Make sure at least the LUKS header fit in */
        if (new_partition_size <= crypto_offset_bytes) {
                uint64_t add;
 
                add = DISK_SIZE_ROUND_UP(crypto_offset_bytes) - new_partition_size;
                new_partition_size += add;
                if (S_ISREG(st.st_mode))
                        new_image_size += add;
        }
 
        old_fs_size = setup->partition_size - crypto_offset_bytes;
        new_fs_size = DISK_SIZE_ROUND_DOWN(new_partition_size - crypto_offset_bytes);
 
        r = get_smallest_fs_size(setup->root_fd, &smallest_fs_size);
        if (r < 0)
                return r;
 
        if (new_fs_size < smallest_fs_size) {
                uint64_t add;
 
                add = DISK_SIZE_ROUND_UP(smallest_fs_size) - new_fs_size;
                new_fs_size += add;
                new_partition_size += add;
                if (S_ISREG(st.st_mode))
                        new_image_size += add;
        }
 
        if (new_fs_size == old_fs_size) {
                log_info("New file system size identical to old file system size, skipping operation.");
                return 0;
        }
 
        if (FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_GROW) && new_fs_size > old_fs_size) {
                log_info("New file system size would be larger than old, but shrinking requested, skipping operation.");
                return 0;
        }
 
        if (FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_SHRINK) && new_fs_size < old_fs_size) {
                log_info("New file system size would be smaller than old, but growing requested, skipping operation.");
                return 0;
        }
 
        if (CMP(new_fs_size, old_fs_size) != intention) {
                if (intention < 0)
                        log_info("Shrink operation would enlarge file system, skipping operation.");
                else {
                        assert(intention > 0);
                        log_info("Grow operation would shrink file system, skipping operation.");
                }
                return 0;
        }
 
        /* Before we start doing anything, let's figure out if we actually can */
        resize_type = can_resize_fs(setup->root_fd, old_fs_size, new_fs_size);
        if (resize_type < 0)
                return resize_type;
        if (resize_type == CAN_RESIZE_OFFLINE && FLAGS_SET(flags, HOME_SETUP_ALREADY_ACTIVATED))
                return log_error_errno(SYNTHETIC_ERRNO(ETXTBSY), "File systems of this type can only be resized offline, but is currently online.");
 
        log_info("Ready to resize image size %s %s %s, partition size %s %s %s, file system size %s %s %s.",
                 FORMAT_BYTES(old_image_size),
                 glyph(GLYPH_ARROW_RIGHT),
                 FORMAT_BYTES(new_image_size),
                 FORMAT_BYTES(setup->partition_size),
                 glyph(GLYPH_ARROW_RIGHT),
                 FORMAT_BYTES(new_partition_size),
                 FORMAT_BYTES(old_fs_size),
                 glyph(GLYPH_ARROW_RIGHT),
                 FORMAT_BYTES(new_fs_size));
 
        if (new_fs_size > old_fs_size) { /* → Grow */
 
                if (S_ISREG(st.st_mode)) {
                        uint64_t resized_image_size;
 
                        /* Grow file size */
                        r = resize_image_loop(h, setup, old_image_size, new_image_size, &resized_image_size);
                        if (r < 0)
                                return r;
 
                        if (resized_image_size == old_image_size) {
                                log_info("Couldn't change image size.");
                                return 0;
                        }
 
                        assert(resized_image_size > old_image_size);
 
                        log_info("Growing of image file from %s to %s completed.", FORMAT_BYTES(old_image_size), FORMAT_BYTES(resized_image_size));
 
                        if (resized_image_size < new_image_size) {
                                uint64_t sub;
 
                                /* If the growing we managed to do is smaller than what we wanted we need to
                                 * adjust the partition/file system sizes we are going for, too */
                                sub = new_image_size - resized_image_size;
                                assert(new_partition_size >= sub);
                                new_partition_size -= sub;
                                assert(new_fs_size >= sub);
                                new_fs_size -= sub;
                        }
 
                        new_image_size = resized_image_size;
                } else {
                        assert(S_ISBLK(st.st_mode));
                        assert(new_image_size == old_image_size);
                }
 
                /* Make sure loopback device sees the new bigger size */
                r = loop_device_refresh_size(setup->loop, UINT64_MAX, new_partition_size);
                if (r == -ENOTTY)
                        log_debug_errno(r, "Device is not a loopback device, not refreshing size.");
                else if (r < 0)
                        return log_error_errno(r, "Failed to refresh loopback device size: %m");
                else
                        log_info("Refreshing loop device size completed.");
 
                r = apply_resize_partition(image_fd, disk_uuid, table, partition, new_partition_size);
                if (r < 0)
                        return r;
                if (r > 0)
                        log_info("Growing of partition completed.");
 
                if (S_ISBLK(st.st_mode))
                        (void) reread_partition_table_fd(image_fd, /* flags= */ 0);
 
                /* Tell LUKS about the new bigger size too */
                /* libcrypsetup uses units of 512B sectors for size */
                r = sym_crypt_resize(setup->crypt_device, setup->dm_name, new_fs_size / 512U);
                if (r < 0)
                        return log_error_errno(r, "Failed to grow LUKS device: %m");
 
                log_info("LUKS device growing completed.");
        } else {
                /* → Shrink */
 
                if (!FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES)) {
                        r = home_store_embedded_identity(new_home, setup->root_fd, embedded_home);
                        if (r < 0)
                                return r;
 
                        r = home_reconcile_blob_dirs(new_home, setup->root_fd, reconciled);
                        if (r < 0)
                                return r;
                }
 
                if (S_ISREG(st.st_mode)) {
                        if (user_record_luks_discard(h))
                                /* Before we shrink, let's trim the file system, so that we need less space on disk during the shrinking */
                                (void) run_fitrim(setup->root_fd);
                        else {
                                /* If discard is off, let's ensure all backing blocks are allocated, so that our resize operation doesn't fail half-way */
                                r = run_fallocate(image_fd, &st);
                                if (r < 0)
                                        return r;
                        }
                }
        }
 
        /* Now try to resize the file system. The requested size might not always be possible, in which case
         * we'll try to get as close as we can get. The result is returned in 'resized_fs_size' */
        r = resize_fs_loop(h, setup, resize_type, old_fs_size, new_fs_size, &resized_fs_size);
        if (r < 0)
                return r;
 
        if (resized_fs_size == old_fs_size) {
                log_info("Couldn't change file system size.");
                return 0;
        }
 
        log_info("File system resizing from %s to %s completed.", FORMAT_BYTES(old_fs_size), FORMAT_BYTES(resized_fs_size));
 
        if (resized_fs_size > new_fs_size) {
                uint64_t add;
 
                /* If the shrinking we managed to do is larger than what we wanted we need to adjust the partition/image sizes. */
                add = resized_fs_size - new_fs_size;
                new_partition_size += add;
                if (S_ISREG(st.st_mode))
                        new_image_size += add;
        }
 
        new_fs_size = resized_fs_size;
 
        /* Immediately sync afterwards */
        r = home_sync_and_statfs(setup->root_fd, NULL);
        if (r < 0)
                return r;
 
        if (new_fs_size < old_fs_size) { /* → Shrink */
 
                /* Shrink the LUKS device now, matching the new file system size */
                /* libcrypsetup uses units of 512B sectors for size */
                r = sym_crypt_resize(setup->crypt_device, setup->dm_name, new_fs_size / 512U);
                if (r < 0)
                        return log_error_errno(r, "Failed to shrink LUKS device: %m");
 
                log_info("LUKS device shrinking completed.");
 
                /* Refresh the loop devices size */
                r = loop_device_refresh_size(setup->loop, UINT64_MAX, new_partition_size);
                if (r == -ENOTTY)
                        log_debug_errno(r, "Device is not a loopback device, not refreshing size.");
                else if (r < 0)
                        return log_error_errno(r, "Failed to refresh loopback device size: %m");
                else
                        log_info("Refreshing loop device size completed.");
 
                if (S_ISREG(st.st_mode)) {
                        /* Shrink the image file */
                        if (ftruncate(image_fd, new_image_size) < 0)
                                return log_error_errno(errno, "Failed to shrink image file %s: %m", ip);
 
                        log_info("Shrinking of image file completed.");
                } else {
                        assert(S_ISBLK(st.st_mode));
                        assert(new_image_size == old_image_size);
                }
 
                r = apply_resize_partition(image_fd, disk_uuid, table, partition, new_partition_size);
                if (r < 0)
                        return r;
                if (r > 0)
                        log_info("Shrinking of partition completed.");
 
                if (S_ISBLK(st.st_mode))
                        (void) reread_partition_table_fd(image_fd, /* flags= */ 0);
 
        } else { /* → Grow */
                if (!FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES)) {
                        r = home_store_embedded_identity(new_home, setup->root_fd, embedded_home);
                        if (r < 0)
                                return r;
 
                        r = home_reconcile_blob_dirs(new_home, setup->root_fd, reconciled);
                        if (r < 0)
                                return r;
                }
        }
 
        if (!FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES)) {
                r = home_store_header_identity_luks(new_home, setup, header_home);
                if (r < 0)
                        return r;
 
                r = home_extend_embedded_identity(new_home, h, setup);
                if (r < 0)
                        return r;
        }
 
        if (user_record_luks_discard(h))
                (void) run_fitrim(setup->root_fd);
 
        r = home_sync_and_statfs(setup->root_fd, &sfs);
        if (r < 0)
                return r;
 
        if (!FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_UNDO)) {
                r = home_setup_done(setup);
                if (r < 0)
                        return r;
        }
 
        log_info("Resizing completed.");
 
        print_size_summary(new_image_size, new_fs_size, &sfs);
 
        if (ret_home)
                *ret_home = TAKE_PTR(new_home);
 
        return 0;
}
 
int home_passwd_luks(
                UserRecord *h,
                HomeSetupFlags flags,
                HomeSetup *setup,
                const PasswordCache *cache, /* the passwords acquired via PKCS#11/FIDO2 security tokens */
                char **effective_passwords  /* new passwords */) {
 
        size_t volume_key_size, max_key_slots, n_effective, n_occupied = 0;
        _cleanup_(erase_and_freep) void *volume_key = NULL;
        struct crypt_pbkdf_type good_pbkdf, minimal_pbkdf;
        const char *type;
        int r;
 
        assert(h);
        assert(user_record_storage(h) == USER_LUKS);
        assert(setup);
 
        r = dlopen_cryptsetup(LOG_DEBUG);
        if (r < 0)
                return r;
 
        type = sym_crypt_get_type(setup->crypt_device);
        if (!type)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine crypto device type.");
 
        r = sym_crypt_keyslot_max(type);
        if (r <= 0)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine number of key slots.");
        max_key_slots = r;
 
        r = sym_crypt_get_volume_key_size(setup->crypt_device);
        if (r <= 0)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine volume key size.");
        volume_key_size = (size_t) r;
 
        volume_key = malloc(volume_key_size);
        if (!volume_key)
                return log_oom();
 
        r = luks_get_volume_key(h, setup->crypt_device, cache, volume_key, &volume_key_size, NULL);
        if (r == -ENOKEY)
                return log_error_errno(SYNTHETIC_ERRNO(ENOKEY), "Failed to unlock LUKS superblock with supplied passwords.");
        if (r < 0)
                return log_error_errno(r, "Failed to unlock LUKS superblock: %m");
 
        n_effective = strv_length(effective_passwords);
 
        for (size_t i = 0; i < max_key_slots; i++)
                switch (sym_crypt_keyslot_status(setup->crypt_device, i)) {
                case CRYPT_SLOT_INACTIVE:
                        break;
                case CRYPT_SLOT_ACTIVE:
                case CRYPT_SLOT_ACTIVE_LAST:
                case CRYPT_SLOT_UNBOUND:
                        n_occupied++;
                        break;
                default:
                        return log_error_errno(SYNTHETIC_ERRNO(EIO),
                                               "Failed to determine state of LUKS key slot %zu.", i);
                }
 
        if (n_effective > max_key_slots - n_occupied)
                return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
                                       "Not enough free LUKS key slots (%zu required, %zu available).",
                                       n_effective, max_key_slots - n_occupied);
 
        build_good_pbkdf(&good_pbkdf, h);
        build_minimal_pbkdf(&minimal_pbkdf, h);
 
        /* Rotate the LUKS key slots in two passes, so that at every on-disk state at least one valid key slot
         * exists for each password the user currently holds. First add all new passwords into free key slots
         * (purely additive, hence non-destructive), and only once that fully succeeded destroy the old slots.
         * If an add fails (e.g. the argon2 PBKDF, which is intentionally memory hungry, hits OOM), we roll
         * back the slots added so far and return with the pre-existing slots untouched. The reverse order
         * (destroy a slot first, then add its replacement at the same index) would, on such a failure, leave
         * the slot destroyed with no replacement, permanently locking the user out. */
 
        _cleanup_free_ int *new_slots = new(int, n_effective);
        if (!new_slots)
                return log_oom();
 
        size_t n_added = 0;
        for (size_t i = 0; i < n_effective; i++) {
                if (password_cache_contains(cache, effective_passwords[i])) { /* Is this a FIDO2 or PKCS#11 password? */
                        log_debug("Using minimal PBKDF for new key slot.");
                        r = sym_crypt_set_pbkdf_type(setup->crypt_device, &minimal_pbkdf);
                } else {
                        log_debug("Using good PBKDF for new key slot.");
                        r = sym_crypt_set_pbkdf_type(setup->crypt_device, &good_pbkdf);
                }
                if (r < 0) {
                        log_error_errno(r, "Failed to tweak PBKDF for new key slot: %m");
                        goto rollback;
                }
 
                r = sym_crypt_keyslot_add_by_volume_key(
                                setup->crypt_device,
                                CRYPT_ANY_SLOT,
                                volume_key,
                                volume_key_size,
                                effective_passwords[i],
                                strlen(effective_passwords[i]));
                if (r < 0) {
                        log_error_errno(r, "Failed to set up LUKS password: %m");
                        goto rollback;
                }
 
                new_slots[n_added++] = r;
                log_info("Added LUKS key slot %i.", r);
        }
 
        /* All replacement slots are committed now; drop every slot that isn't one we just added. */
        for (size_t i = 0; i < max_key_slots; i++) {
                bool keep = false;
 
                for (size_t j = 0; j < n_added; j++)
                        if (new_slots[j] == (int) i) {
                                keep = true;
                                break;
                        }
                if (keep)
                        continue;
 
                r = sym_crypt_keyslot_destroy(setup->crypt_device, i);
                if (r < 0 && !IN_SET(r, -ENOENT, -EINVAL)) /* Returns EINVAL or ENOENT if there's no key in this slot already */
                        return log_error_errno(r, "Failed to destroy LUKS password: %m");
                if (r >= 0)
                        log_info("Destroyed LUKS key slot %zu.", i);
        }
 
        return 1;
 
rollback:
        /* Undo the slots added in this call, so that the header is left exactly as we found it. */
        for (size_t i = 0; i < n_added; i++)
                (void) sym_crypt_keyslot_destroy(setup->crypt_device, new_slots[i]);
 
        return r;
}
 
int home_lock_luks(UserRecord *h, HomeSetup *setup) {
        const char *p;
        int r;
 
        assert(h);
        assert(setup);
        assert(setup->root_fd < 0);
        assert(!setup->crypt_device);
 
        r = acquire_open_luks_device(h, setup, /* graceful= */ false);
        if (r < 0)
                return r;
 
        log_info("Discovered used LUKS device %s.", setup->dm_node);
 
        assert_se(p = user_record_home_directory(h));
        r = syncfs_path(AT_FDCWD, p);
        if (r < 0) /* Snake oil, but let's better be safe than sorry */
                return log_error_errno(r, "Failed to synchronize file system %s: %m", p);
 
        log_info("File system synchronized.");
 
        /* Note that we don't invoke FIFREEZE here, it appears libcryptsetup/device-mapper already does that on its own for us */
 
        r = sym_crypt_suspend(setup->crypt_device, setup->dm_name);
        if (r < 0)
                return log_error_errno(r, "Failed to suspend cryptsetup device: %s: %m", setup->dm_node);
 
        log_info("LUKS device suspended.");
        return 0;
}
 
int home_unlock_luks(UserRecord *h, HomeSetup *setup, const PasswordCache *cache) {
        _cleanup_(keyring_unlinkp) key_serial_t key_serial = -1;
        _cleanup_(erase_and_freep) void *vk = NULL;
        size_t vks;
        int r;
 
        assert(h);
        assert(setup);
        assert(!setup->crypt_device);
 
        r = acquire_open_luks_device(h, setup, /* graceful= */ false);
        if (r < 0)
                return r;
 
        log_info("Discovered used LUKS device %s.", setup->dm_node);
 
        r = sym_crypt_get_volume_key_size(setup->crypt_device);
        if (r <= 0)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine LUKS volume key size.");
        vks = (size_t) r;
 
        vk = malloc(vks);
        if (!vk)
                return log_oom();
 
        r = luks_get_volume_key(h, setup->crypt_device, cache, vk, &vks, &key_serial);
        if (r == -ENOKEY)
                return log_error_errno(r, "No valid password for LUKS superblock.");
        if (r < 0)
                return log_error_errno(r, "Failed to unlock LUKS superblock: %m");
 
        r = sym_crypt_resume_by_volume_key(setup->crypt_device, setup->dm_name, vk, vks);
        if (r < 0)
                return log_error_errno(r, "Failed to resume LUKS superblock: %m");
 
        TAKE_KEY_SERIAL(key_serial); /* Leave key in kernel keyring */
 
        log_info("LUKS device resumed.");
        return 0;
}
 
static int device_is_gone(HomeSetup *setup) {
        _cleanup_(sd_device_unrefp) sd_device *d = NULL;
        struct stat st;
        int r;
 
        assert(setup);
 
        if (!setup->dm_node)
                return true;
 
        if (stat(setup->dm_node, &st) < 0) {
                if (errno != ENOENT)
                        return log_error_errno(errno, "Failed to stat block device node %s: %m", setup->dm_node);
 
                return true;
        }
 
        r = sd_device_new_from_stat_rdev(&d, &st);
        if (r < 0) {
                if (r != -ENODEV)
                        return log_error_errno(r, "Failed to allocate device object from block device node %s: %m", setup->dm_node);
 
                return true;
        }
 
        return false;
}
 
static int device_monitor_handler(sd_device_monitor *monitor, sd_device *device, void *userdata) {
        HomeSetup *setup = ASSERT_PTR(userdata);
        int r;
 
        if (!device_for_action(device, SD_DEVICE_REMOVE))
                return 0;
 
        /* We don't really care for the device object passed to us, we just check if the device node still
         * exists */
 
        r = device_is_gone(setup);
        if (r < 0)
                return r;
        if (r > 0) /* Yay! we are done! */
                (void) sd_event_exit(sd_device_monitor_get_event(monitor), 0);
 
        return 0;
}
 
int wait_for_block_device_gone(HomeSetup *setup, usec_t timeout_usec) {
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *m = NULL;
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
        int r;
 
        assert(setup);
 
        /* So here's the thing: we enable "deferred deactivation" on our dm-crypt volumes. This means they
         * are automatically torn down once not used anymore (i.e. once unmounted). Which is great. It also
         * means that when we deactivate a home directory and try to tear down the volume that backs it, it
         * possibly is already torn down or in the process of being torn down, since we race against the
         * automatic tearing down. Which is fine, we handle errors from that. However, we lose the ability to
         * naturally wait for the tear down operation to complete: if we are not the ones who tear down the
         * device we are also not the ones who naturally block on that operation. Hence let's add some code
         * to actively wait for the device to go away, via sd-device. We'll call this whenever tearing down a
         * LUKS device, to ensure the device is really really gone before we proceed. Net effect: "homectl
         * deactivate foo && homectl activate foo" will work reliably, i.e. deactivation immediately followed
         * by activation will work. Also, by the time deactivation completes we can guarantee that all data
         * is sync'ed down to the lowest block layer as all higher levels are fully and entirely
         * destructed. */
 
        if (!setup->dm_name)
                return 0;
 
        assert(setup->dm_node);
        log_debug("Waiting until %s disappears.", setup->dm_node);
 
        r = sd_event_new(&event);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate event loop: %m");
 
        r = sd_device_monitor_new(&m);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate device monitor: %m");
 
        r = sd_device_monitor_filter_add_match_subsystem_devtype(m, "block", "disk");
        if (r < 0)
                return log_error_errno(r, "Failed to configure device monitor match: %m");
 
        r = sd_device_monitor_attach_event(m, event);
        if (r < 0)
                return log_error_errno(r, "Failed to attach device monitor to event loop: %m");
 
        r = sd_device_monitor_start(m, device_monitor_handler, setup);
        if (r < 0)
                return log_error_errno(r, "Failed to start device monitor: %m");
 
        r = device_is_gone(setup);
        if (r < 0)
                return r;
        if (r > 0) {
                log_debug("%s has already disappeared before entering wait loop.", setup->dm_node);
                return 0; /* gone already */
        }
 
        if (timeout_usec != USEC_INFINITY) {
                r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, timeout_usec, 0, NULL, NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to add timer event: %m");
        }
 
        r = sd_event_loop(event);
        if (r < 0)
                return log_error_errno(r, "Failed to run event loop: %m");
 
        r = device_is_gone(setup);
        if (r < 0)
                return r;
        if (r == 0)
                return log_error_errno(SYNTHETIC_ERRNO(EBUSY), "Device %s still around.", setup->dm_node);
 
        log_debug("Successfully waited until device %s disappeared.", setup->dm_node);
        return 0;
}
 
int home_auto_shrink_luks(UserRecord *h, HomeSetup *setup, PasswordCache *cache) {
        struct statfs sfs;