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 1001–2000 of 11,995

                .backing_fd = -EBADF,
                .fdisk_context_fd = -EBADF,
        };
 
        return context;
}
 
static void context_free_free_areas(Context *context) {
        assert(context);
 
        for (size_t i = 0; i < context->n_free_areas; i++)
                free(context->free_areas[i]);
 
        context->free_areas = mfree(context->free_areas);
        context->n_free_areas = 0;
}
 
static Context* context_free(Context *context) {
        if (!context)
                return NULL;
 
        strv_free(context->definitions);
 
        while (context->partitions)
                partition_unlink_and_free(context, context->partitions);
        assert(context->n_partitions == 0);
 
        context_free_free_areas(context);
 
        if (context->fdisk_context)
                sym_fdisk_unref_context(context->fdisk_context);
        safe_close(context->fdisk_context_fd);
 
        safe_close(context->backing_fd);
        if (context->node_is_our_file)
                unlink_and_free(context->node);
        else
                free(context->node);
 
#if HAVE_OPENSSL
        if (context->certificate)
                sym_X509_free(context->certificate);
        openssl_ask_password_ui_free(context->ui);
        if (context->private_key)
                sym_EVP_PKEY_free(context->private_key);
#endif
 
        context->link = sd_varlink_unref(context->link);
 
        return mfree(context);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(Context*, context_free);
 
static void context_disarm_auto_removal(Context *context) {
        assert(context);
 
        /* Make sure automatic removal of half-written artifacts is disarmed */
        context->node = mfree(context->node);
 
        LIST_FOREACH(partitions, p, context->partitions)
                p->split_path = mfree(p->split_path);
}
 
static int context_add_free_area(
                Context *context,
                uint64_t size,
                Partition *after) {
 
        FreeArea *a;
 
        assert(context);
        assert(!after || !after->padding_area);
 
        if (!GREEDY_REALLOC(context->free_areas, context->n_free_areas + 1))
                return -ENOMEM;
 
        a = new(FreeArea, 1);
        if (!a)
                return -ENOMEM;
 
        *a = (FreeArea) {
                .size = size,
                .after = after,
        };
 
        context->free_areas[context->n_free_areas++] = a;
 
        if (after)
                after->padding_area = a;
 
        return 0;
}
 
static void partition_drop_or_foreignize(Partition *p) {
        if (!p || p->dropped || PARTITION_IS_FOREIGN(p))
                return;
 
        if (PARTITION_EXISTS(p)) {
                log_info("Can't grow existing partition %s of priority %" PRIi32 ", ignoring.",
                         strna(p->current_label ?: p->new_label), p->priority);
 
                /* Handle the partition as foreign. Do not set dropped flag. */
                partition_foreignize(p);
        } else {
                log_info("Can't fit partition %s of priority %" PRIi32 ", dropping.",
                         p->definition_path, p->priority);
 
                p->dropped = true;
                p->allocated_to_area = NULL;
 
                /* If a supplement partition is dropped, we don't want to merge in its settings. */
                if (PARTITION_SUPPRESSED(p))
                        p->supplement_for->suppressing_supplement = false;
        }
}
 
static bool context_drop_or_foreignize_one_priority(Context *context) {
        int32_t priority = 0;
 
        LIST_FOREACH(partitions, p, context->partitions) {
                if (p->dropped)
                        continue;
 
                priority = MAX(priority, p->priority);
        }
 
        /* Refuse to drop partitions with 0 or negative priorities or partitions of priorities that have at
         * least one existing priority */
        if (priority <= 0)
                return false;
 
        LIST_FOREACH(partitions, p, context->partitions) {
                if (p->priority < priority)
                        continue;
 
                partition_drop_or_foreignize(p);
 
                /* We ensure that all verity sibling partitions have the same priority, so it's safe
                 * to drop all siblings here as well. */
 
                for (VerityMode mode = VERITY_OFF + 1; mode < _VERITY_MODE_MAX; mode++)
                        partition_drop_or_foreignize(p->siblings[mode]);
        }
 
        return true;
}
 
static uint64_t partition_fs_sector_size(const Context *c, const Partition *p) {
        assert(c);
        assert(p);
 
        uint64_t ss;
 
        if (p->fs_sector_size != UINT64_MAX)
                /* Prefer explicitly configured value */
                ss = p->fs_sector_size;
        else
                /* Otherwise follow the default sector size */
                ss = c->default_fs_sector_size;
 
        /* never allow the fs sector size to be picked smaller than the physical sector size */
        return MAX(ss, c->sector_size);
}
 
static uint64_t partition_fstype_min_size(const Context *c, const Partition *p) {
        assert(c);
        assert(p);
 
        /* If a file system type is configured, then take it into consideration for the minimum partition
         * size */
 
        if (IN_SET(p->type.designator, PARTITION_ESP, PARTITION_XBOOTLDR) && streq_ptr(p->format, "vfat")) {
                uint64_t ss = partition_fs_sector_size(c, p);
                return ss >= 4096 ? ESP_MIN_SIZE_4K : ESP_MIN_SIZE;
        }
 
        return minimal_size_by_fs_name(p->format);
}
 
static uint64_t partition_min_size(const Context *context, const Partition *p) {
        uint64_t sz;
 
        assert(context);
        assert(p);
 
        /* Calculate the disk space we really need at minimum for this partition. If the partition already
         * exists the current size is what we really need. If it doesn't exist yet refuse to allocate less
         * than 4K.
         *
         * DEFAULT_MIN_SIZE is the default SizeMinBytes= we configure if nothing else is specified. */
 
        if (PARTITION_IS_FOREIGN(p)) {
                /* Don't allow changing size of partitions not managed by us */
                assert(p->current_size != UINT64_MAX);
                return p->current_size;
        }
 
        if (partition_designator_is_verity_sig(p->type.designator))
                return VERITY_SIG_SIZE;
 
        sz = p->current_size != UINT64_MAX ? p->current_size : HARD_MIN_SIZE;
 
        if (!PARTITION_EXISTS(p)) {
                uint64_t d = 0;
 
                if (p->encrypt != ENCRYPT_OFF)
                        assert_se(INC_SAFE(&d, round_up_size(LUKS2_METADATA_KEEP_FREE, context->grain_size)));
 
                if (p->copy_blocks_size != UINT64_MAX)
                        assert_se(INC_SAFE(&d, round_up_size(p->copy_blocks_size, context->grain_size)));
                else if (p->btrfs_replaced)
                        assert_se(INC_SAFE(&d, round_up_size(p->btrfs_replaced->source_size, context->grain_size)));
                else if (p->format || p->encrypt != ENCRYPT_OFF) {
                        uint64_t f;
 
                        /* If we shall synthesize a file system, take minimal fs size into account (assumed to be 4K if not known) */
                        f = partition_fstype_min_size(context, p);
                        assert_se(INC_SAFE(&d, f == UINT64_MAX ? context->grain_size : round_up_size(f, context->grain_size)));
                }
 
                if (d > sz)
                        sz = d;
        }
 
        uint64_t min_size = p->size_min;
        if (p->suppressing_supplement && (min_size == UINT64_MAX || p->supplemented_by->size_min > min_size))
                min_size = p->supplemented_by->size_min;
 
        /* Default to 10M min size, except if the file system is read-only, in which case let's not enforce a
         * minimum size, because even if we wanted to we couldn't take possession of the extra space
         * allocated. */
        if (min_size == UINT64_MAX)
                min_size = (p->format && fstype_is_ro(p->format)) || p->verity != VERITY_OFF ? 1 : DEFAULT_MIN_SIZE;
 
        return MAX(round_up_size(min_size, context->grain_size), sz);
}
 
static uint64_t partition_max_size(const Context *context, const Partition *p) {
        uint64_t sm, override_max;
 
        /* Calculate how large the partition may become at max. This is generally the configured maximum
         * size, except when it already exists and is larger than that. In that case it's the existing size,
         * since we never want to shrink partitions. */
 
        assert(context);
        assert(p);
 
        if (PARTITION_IS_FOREIGN(p)) {
                /* Don't allow changing size of partitions not managed by us */
                assert(p->current_size != UINT64_MAX);
                return p->current_size;
        }
 
        if (partition_designator_is_verity_sig(p->type.designator))
                return VERITY_SIG_SIZE;
 
        override_max = p->suppressing_supplement ? MIN(p->size_max, p->supplemented_by->size_max) : p->size_max;
        if (override_max == UINT64_MAX)
                return UINT64_MAX;
 
        sm = round_down_size(override_max, context->grain_size);
 
        if (p->current_size != UINT64_MAX)
                sm = MAX(p->current_size, sm);
 
        return MAX(partition_min_size(context, p), sm);
}
 
static uint64_t partition_min_padding(const Partition *p) {
        uint64_t override_min;
 
        assert(p);
 
        override_min = p->suppressing_supplement ? MAX(p->padding_min, p->supplemented_by->padding_min) : p->padding_min;
        return override_min != UINT64_MAX ? override_min : 0;
}
 
static uint64_t partition_max_padding(const Partition *p) {
        assert(p);
        return p->suppressing_supplement ? MIN(p->padding_max, p->supplemented_by->padding_max) : p->padding_max;
}
 
static uint64_t partition_min_size_with_padding(const Context *context, const Partition *p) {
        uint64_t sz;
 
        /* Calculate the disk space we need for this partition plus any free space coming after it. This
         * takes user configured padding into account as well as any additional whitespace needed to align
         * the next partition to 4K again. */
 
        assert(context);
        assert(p);
 
        sz = partition_min_size(context, p) + partition_min_padding(p);
 
        if (PARTITION_EXISTS(p)) {
                /* If the partition wasn't aligned, add extra space so that any we might add will be aligned */
                assert(p->offset != UINT64_MAX);
                return round_up_size(p->offset + sz, context->grain_size) - p->offset;
        }
 
        /* If this is a new partition we'll place it aligned, hence we just need to round up the required size here */
        return round_up_size(sz, context->grain_size);
}
 
static uint64_t free_area_available(const FreeArea *a) {
        assert(a);
 
        /* Determines how much of this free area is not allocated yet */
 
        assert(a->size >= a->allocated);
        return a->size - a->allocated;
}
 
static uint64_t free_area_current_end(const Context *context, const FreeArea *a) {
        assert(context);
        assert(a);
 
        if (!a->after)
                return free_area_available(a);
 
        assert(a->after->offset != UINT64_MAX);
        assert(a->after->current_size != UINT64_MAX);
        /* Silence static analyzers */
        assert(a->after->current_size <= UINT64_MAX - a->after->offset);
 
        /* Calculate where the free area ends, based on the offset of the partition preceding it. */
        return round_up_size(a->after->offset + a->after->current_size, context->grain_size) + free_area_available(a);
}
 
static uint64_t free_area_min_end(const Context *context, const FreeArea *a) {
        assert(context);
        assert(a);
 
        if (!a->after)
                return 0;
 
        assert(a->after->offset != UINT64_MAX);
        assert(a->after->current_size != UINT64_MAX);
 
        /* Calculate where the partition would end when we give it as much as it needs. */
        return round_up_size(a->after->offset + partition_min_size_with_padding(context, a->after), context->grain_size);
}
 
static uint64_t free_area_available_for_new_partitions(const Context *context, const FreeArea *a) {
        assert(context);
        assert(a);
 
        /* Similar to free_area_available(), but takes into account that the required size and padding of the
         * preceding partition is honoured. */
 
        return LESS_BY(free_area_current_end(context, a), free_area_min_end(context, a));
}
 
static int free_area_compare(FreeArea *const *a, FreeArea *const*b, Context *context) {
        assert(a);
        assert(b);
        assert(context);
 
        return CMP(free_area_available_for_new_partitions(context, *a),
                   free_area_available_for_new_partitions(context, *b));
}
 
static uint64_t charge_size(const Context *context, uint64_t total, uint64_t amount) {
        assert(context);
        /* Subtract the specified amount from total, rounding up to multiple of 4K if there's room */
        assert(amount <= total);
        return LESS_BY(total, round_up_size(amount, context->grain_size));
}
 
static uint64_t charge_weight(uint64_t total, uint64_t amount) {
        assert(amount <= total);
        return total - amount;
}
 
static bool context_allocate_partitions(Context *context, uint64_t *ret_largest_free_area) {
        assert(context);
 
        /* This may be called multiple times. Reset previous assignments. */
        for (size_t i = 0; i < context->n_free_areas; i++)
                context->free_areas[i]->allocated = 0;
 
        /* Sort free areas by size, putting smallest first */
        typesafe_qsort_r(context->free_areas, context->n_free_areas, free_area_compare, context);
 
        /* In any case return size of the largest free area (i.e. not the size of all free areas
         * combined!) */
        if (ret_largest_free_area)
                *ret_largest_free_area =
                        context->n_free_areas == 0 ? 0 :
                        free_area_available_for_new_partitions(context, context->free_areas[context->n_free_areas-1]);
 
        /* Check that each existing partition can fit its area. */
        for (size_t i = 0; i < context->n_free_areas; i++)
                if (free_area_current_end(context, context->free_areas[i]) <
                    free_area_min_end(context, context->free_areas[i]))
                        return false;
 
        /* A simple first-fit algorithm. We return true if we can fit the partitions in, otherwise false. */
        LIST_FOREACH(partitions, p, context->partitions) {
                bool fits = false;
                uint64_t required;
                FreeArea *a = NULL;
 
                if (p->dropped || PARTITION_IS_FOREIGN(p) || PARTITION_SUPPRESSED(p))
                        continue;
 
                /* How much do we need to fit? */
                required = partition_min_size_with_padding(context, p);
 
                /* For existing partitions, we should verify that they'll actually fit */
                if (PARTITION_EXISTS(p)) {
                        if (p->current_size + p->current_padding < required)
                                return false; /* 😢 We won't be able to grow to the required min size! */
 
                        continue;
                }
 
                /* For new partitions, see if there's a free area big enough */
                for (size_t i = 0; i < context->n_free_areas; i++) {
                        a = context->free_areas[i];
 
                        if (free_area_available_for_new_partitions(context, a) >= required) {
                                fits = true;
                                break;
                        }
                }
 
                if (!fits)
                        return false; /* 😢 Oh no! We can't fit this partition into any free area! */
 
                /* Assign the partition to this free area */
                p->allocated_to_area = a;
 
                /* Budget the minimal partition size */
                a->allocated += required;
        }
 
        return true;
}
 
static bool context_unmerge_and_allocate_partitions(Context *context) {
        assert(context);
 
        /* This should only be called after plain context_allocate_partitions fails. This algorithm will
         * try, in the order that minimizes the number of created supplement partitions, all combinations of
         * un-suppressing supplement partitions until it finds one that works. */
 
        /* First, let's try to un-suppress just one supplement partition and see if that gets us anywhere */
        LIST_FOREACH(partitions, p, context->partitions) {
                if (!p->suppressing_supplement)
                        continue;
 
                p->suppressing_supplement = false;
 
                if (context_allocate_partitions(context, NULL))
                        return true;
 
                p->suppressing_supplement = true;
        }
 
        /* Looks like not. So we have to un-suppress at least two partitions. We can do this recursively */
        LIST_FOREACH(partitions, p, context->partitions) {
                if (!p->suppressing_supplement)
                        continue;
 
                p->suppressing_supplement = false;
 
                if (context_unmerge_and_allocate_partitions(context))
                        return true;
 
                p->suppressing_supplement = true;
        }
 
        /* No combination of un-suppressed supplements made it possible to fit the partitions */
        return false;
}
 
static uint32_t partition_weight(const Partition *p) {
        assert(p);
        return p->suppressing_supplement ? p->supplemented_by->weight : p->weight;
}
 
static uint32_t partition_padding_weight(const Partition *p) {
        assert(p);
        return p->suppressing_supplement ? p->supplemented_by->padding_weight : p->padding_weight;
}
 
static int context_sum_weights(const Context *context, const FreeArea *a, uint64_t *ret) {
        uint64_t weight_sum = 0;
 
        assert(context);
        assert(a);
        assert(ret);
 
        /* Determine the sum of the weights of all partitions placed in or before the specified free area */
 
        LIST_FOREACH(partitions, p, context->partitions) {
                if (p->padding_area != a && p->allocated_to_area != a)
                        continue;
 
                if (!INC_SAFE(&weight_sum, partition_weight(p)))
                        goto overflow_sum;
 
                if (!INC_SAFE(&weight_sum, partition_padding_weight(p)))
                        goto overflow_sum;
        }
 
        *ret = weight_sum;
        return 0;
 
overflow_sum:
        return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Combined weight of partition exceeds unsigned 64-bit range, refusing.");
}
 
static uint64_t scale_by_weight(uint64_t value, uint64_t weight, uint64_t weight_sum) {
        assert(weight_sum >= weight);
 
        for (;;) {
                if (weight == 0)
                        return 0;
                if (weight == weight_sum)
                        return value;
                if (value <= UINT64_MAX / weight)
                        return value * weight / weight_sum;
 
                /* Rescale weight and weight_sum to make not the calculation overflow. To satisfy the
                 * following conditions, 'weight_sum' is rounded up but 'weight' is rounded down:
                 * - the sum of scale_by_weight() for all weights must not be larger than the input value,
                 * - scale_by_weight() must not be larger than the ideal value (i.e. calculated with uint128_t). */
                weight_sum = DIV_ROUND_UP(weight_sum, 2);
                weight /= 2;
        }
}
 
typedef enum GrowPartitionPhase {
        /* The zeroth phase: do not touch foreign partitions (i.e. those we don't manage). */
        PHASE_FOREIGN,
 
        /* The first phase: we charge partitions which need more (according to constraints) than their weight-based share. */
        PHASE_OVERCHARGE,
 
        /* The second phase: we charge partitions which need less (according to constraints) than their weight-based share. */
        PHASE_UNDERCHARGE,
 
        /* The third phase: we distribute what remains among the remaining partitions, according to the weights */
        PHASE_DISTRIBUTE,
 
        _GROW_PARTITION_PHASE_MAX,
} GrowPartitionPhase;
 
static bool context_grow_partitions_phase(
                const Context *context,
                const FreeArea *a,
                GrowPartitionPhase phase,
                uint64_t *span,
                uint64_t *weight_sum) {
 
        bool try_again = false;
 
        assert(context);
        assert(a);
        assert(span);
        assert(weight_sum);
 
        /* Now let's look at the intended weights and adjust them taking the minimum space assignments into
         * account. i.e. if a partition has a small weight but a high minimum space value set it should not
         * get any additional room from the left-overs. Similar, if two partitions have the same weight they
         * should get the same space if possible, even if one has a smaller minimum size than the other. */
        LIST_FOREACH(partitions, p, context->partitions) {
                /* Look only at partitions associated with this free area, i.e. immediately
                 * preceding it, or allocated into it */
                if (p->allocated_to_area != a && p->padding_area != a)
                        continue;
 
                if (p->new_size == UINT64_MAX) {
                        uint64_t share, rsz, xsz;
                        uint32_t weight;
                        bool charge = false;
 
                        weight = partition_weight(p);
 
                        /* Calculate how much this space this partition needs if everyone would get
                         * the weight based share */
                        share = scale_by_weight(*span, weight, *weight_sum);
 
                        rsz = partition_min_size(context, p);
                        xsz = partition_max_size(context, p);
 
                        if (phase == PHASE_FOREIGN && PARTITION_IS_FOREIGN(p)) {
                                /* Never change of foreign partitions (i.e. those we don't manage) */
 
                                p->new_size = p->current_size;
                                charge = true;
 
                        } else if (phase == PHASE_OVERCHARGE && rsz > share) {
                                /* This partition needs more than its calculated share. Let's assign
                                 * it that, and take this partition out of all calculations and start
                                 * again. */
 
                                p->new_size = rsz;
                                charge = try_again = true;
 
                        } else if (phase == PHASE_UNDERCHARGE && xsz < share) {
                                /* This partition accepts less than its calculated
                                 * share. Let's assign it that, and take this partition out
                                 * of all calculations and start again. */
 
                                p->new_size = xsz;
                                charge = try_again = true;
 
                        } else if (phase == PHASE_DISTRIBUTE) {
                                /* This partition can accept its calculated share. Let's
                                 * assign it. There's no need to restart things here since
                                 * assigning this shouldn't impact the shares of the other
                                 * partitions. */
 
                                assert(share >= rsz);
                                p->new_size = CLAMP(round_down_size(share, context->grain_size), rsz, xsz);
                                charge = true;
                        }
 
                        if (charge) {
                                *span = charge_size(context, *span, p->new_size);
                                *weight_sum = charge_weight(*weight_sum, weight);
                        }
                }
 
                if (p->new_padding == UINT64_MAX) {
                        uint64_t share, rsz, xsz;
                        uint32_t padding_weight;
                        bool charge = false;
 
                        padding_weight = partition_padding_weight(p);
 
                        share = scale_by_weight(*span, padding_weight, *weight_sum);
 
                        rsz = partition_min_padding(p);
                        xsz = partition_max_padding(p);
 
                        if (phase == PHASE_OVERCHARGE && rsz > share) {
                                p->new_padding = rsz;
                                charge = try_again = true;
                        } else if (phase == PHASE_UNDERCHARGE && xsz < share) {
                                p->new_padding = xsz;
                                charge = try_again = true;
                        } else if (phase == PHASE_DISTRIBUTE) {
                                assert(share >= rsz);
                                p->new_padding = CLAMP(round_down_size(share, context->grain_size), rsz, xsz);
                                charge = true;
                        }
 
                        if (charge) {
                                *span = charge_size(context, *span, p->new_padding);
                                *weight_sum = charge_weight(*weight_sum, padding_weight);
                        }
                }
        }
 
        return !try_again;
}
 
static void context_grow_partition_one(Context *context, Partition *p, uint64_t *span) {
        uint64_t m;
 
        assert(context);
        assert(p);
        assert(span);
 
        assert(*span > 0);
        assert(p->new_size != UINT64_MAX);
 
        /* Calculate new size and align. */
        m = round_down_size(p->new_size + *span, context->grain_size);
        /* But ensure this doesn't shrink the size. */
        m = MAX(m, p->new_size);
        /* And ensure this doesn't exceed the maximum size. */
        m = MIN(m, partition_max_size(context, p));
 
        assert(m >= p->new_size);
 
        *span = charge_size(context, *span, m - p->new_size);
        p->new_size = m;
}
 
static int context_grow_partitions_on_free_area(Context *context, FreeArea *a) {
        uint64_t weight_sum = 0, span;
        int r;
 
        assert(context);
        assert(a);
 
        r = context_sum_weights(context, a, &weight_sum);
        if (r < 0)
                return r;
 
        /* Let's calculate the total area covered by this free area and the partition before it */
        span = a->size;
        if (a->after) {
                assert(a->after->offset != UINT64_MAX);
                assert(a->after->current_size != UINT64_MAX);
 
                span += round_up_size(a->after->offset + a->after->current_size, context->grain_size) - a->after->offset;
        }
 
        for (GrowPartitionPhase phase = 0; phase < _GROW_PARTITION_PHASE_MAX;)
                if (context_grow_partitions_phase(context, a, phase, &span, &weight_sum))
                        phase++; /* go to the next phase */
 
 
        /* What? Even still some space left (because one partition had max_size < share
         * and another had min_size > share), then let's donate it to whoever wants it. */
        if (span > 0)
                LIST_FOREACH(partitions, p, context->partitions) {
                        if (p->allocated_to_area != a && p->padding_area != a)
                                continue;
 
                        context_grow_partition_one(context, p, &span);
                        if (span == 0)
                                break;
                }
 
        /* Partitions didn't want all the space? Then make it padding */
        if (span > 0) {
                Partition *last_partition = NULL;
 
                LIST_FOREACH(partitions, p, context->partitions)
                        if (p->allocated_to_area == a || p->padding_area == a)
                                last_partition = p;
 
                if (last_partition) {
                        assert(last_partition->new_padding != UINT64_MAX);
                        last_partition->new_padding += round_down_size(span, context->grain_size);
                }
        }
 
        return 0;
}
 
static int context_grow_partitions(Context *context) {
        int r;
 
        assert(context);
 
        for (size_t i = 0; i < context->n_free_areas; i++) {
                r = context_grow_partitions_on_free_area(context, context->free_areas[i]);
                if (r < 0)
                        return r;
        }
 
        /* All existing partitions that have no free space after them can't change size */
        LIST_FOREACH(partitions, p, context->partitions) {
                if (p->dropped)
                        continue;
 
                if (!PARTITION_EXISTS(p) || p->padding_area) {
                        /* The algorithm above must have initialized this already */
                        assert(p->new_size != UINT64_MAX);
                        continue;
                }
 
                assert(p->new_size == UINT64_MAX);
                p->new_size = p->current_size;
 
                assert(p->new_padding == UINT64_MAX);
                p->new_padding = p->current_padding;
        }
 
        return 0;
}
 
static uint64_t find_unused_partno(Context *context, const Partition *partition) {
        uint64_t partno = 0;
        size_t nents;
 
        assert(context);
        assert(partition);
 
        /* Keep new partitions after existing partitions of the same type, as those are matched
         * to definitions in partition number order. */
        LIST_FOREACH(partitions, p, context->partitions)
                if (PARTITION_EXISTS(p) && p->partno != UINT64_MAX &&
                    sd_id128_equal(p->type.uuid, partition->type.uuid))
                        partno = MAX(partno, p->partno + 1);
 
        nents = sym_fdisk_get_npartitions(context->fdisk_context);
 
        /* Prefer a free slot after all existing partitions of the same type. */
        for (; partno < nents; partno++) {
                bool found = false;
                LIST_FOREACH(partitions, p, context->partitions)
                        if (p->partno != UINT64_MAX && p->partno == partno) {
                                found = true;
                                break;
                        }
                if (!found)
                        return partno;
        }
 
        /* Fall back to the first unused slot if there is no such slot. */
        for (partno = 0;; partno++) {
                bool found = false;
                LIST_FOREACH(partitions, p, context->partitions)
                        if (p->partno != UINT64_MAX && p->partno == partno) {
                                found = true;
                                break;
                        }
                if (!found)
                        break;
        }
 
        return partno;
}
 
static void context_place_partitions(Context *context) {
 
        assert(context);
 
        for (size_t i = 0; i < context->n_free_areas; i++) {
                FreeArea *a = context->free_areas[i];
                uint64_t left;
                uint64_t start;
 
                if (a->after) {
                        assert(a->after->offset != UINT64_MAX);
                        assert(a->after->new_size != UINT64_MAX);
                        assert(a->after->new_padding != UINT64_MAX);
 
                        start = a->after->offset + a->after->new_size + a->after->new_padding;
                } else
                        start = context->start;
 
                start = round_up_size(start, context->grain_size);
                left = a->size;
 
                LIST_FOREACH(partitions, p, context->partitions) {
                        uint64_t gap;
 
                        if (p->allocated_to_area != a)
                                continue;
 
                        p->offset = start;
                        p->partno = find_unused_partno(context, p);
 
                        assert(left >= p->new_size);
                        start += p->new_size;
                        left -= p->new_size;
 
                        assert(left >= p->new_padding);
                        start += p->new_padding;
                        left -= p->new_padding;
 
                        /* Re-align start to the grain after each partition, so that the next
                         * partition placed into this free area also starts on a grain boundary.
                         * This matters when the grain is larger than the default (e.g. 1 MiB via
                         * --grain-size=) and a small partition like verity-sig (16 KiB) precedes
                         * a larger one: without this, the successor would start at an unaligned
                         * offset. */
                        gap = round_up_size(start, context->grain_size) - start;
                        if (gap > left) {
                                log_warning("Not enough space left in free area to re-align partition start to grain size, "
                                            "next partition may start at an unaligned offset.");
                                gap = 0;
                        }
                        start += gap;
                        left -= gap;
                }
        }
}
 
static int config_parse_type(
                const char *unit,
                const char *filename,
                unsigned line,
                const char *section,
                unsigned section_line,
                const char *lvalue,
                int ltype,
                const char *rvalue,
                void *data,
                void *userdata) {
 
        GptPartitionType *type = ASSERT_PTR(data);
        int r;
 
        assert(rvalue);
 
        r = gpt_partition_type_from_string(rvalue, type);
        if (r < 0)
                return log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse partition type: %s", rvalue);
 
        if (arg_architecture >= 0)
                *type = gpt_partition_type_override_architecture(*type, arg_architecture);
 
        return 0;
}
 
static int config_parse_label(
                const char *unit,
                const char *filename,
                unsigned line,
                const char *section,
                unsigned section_line,
                const char *lvalue,
                int ltype,
                const char *rvalue,
                void *data,
                void *userdata) {
 
        _cleanup_free_ char *resolved = NULL;
        char **label = ASSERT_PTR(data);
        int r;
 
        assert(rvalue);
 
        /* Nota bene: the empty label is a totally valid one. Let's hence not follow our usual rule of
         * assigning the empty string to reset to default here, but really accept it as label to set. */
 
        r = specifier_printf(rvalue, GPT_LABEL_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved);
        if (r < 0) {
                log_syntax(unit, LOG_WARNING, filename, line, r,
                           "Failed to expand specifiers in Label=, ignoring: %s", rvalue);
                return 0;
        }
 
        if (!utf8_is_valid(resolved)) {
                log_syntax(unit, LOG_WARNING, filename, line, 0,
                           "Partition label not valid UTF-8, ignoring: %s", rvalue);
                return 0;
        }
 
        r = gpt_partition_label_valid(resolved);
        if (r < 0) {
                log_syntax(unit, LOG_WARNING, filename, line, r,
                           "Failed to check if string is valid as GPT partition label, ignoring: \"%s\" (from \"%s\")",
                           resolved, rvalue);
                return 0;
        }
        if (!r) {
                log_syntax(unit, LOG_WARNING, filename, line, 0,
                           "Partition label too long for GPT table, ignoring: \"%s\" (from \"%s\")",
                           resolved, rvalue);
                return 0;
        }
 
        free_and_replace(*label, resolved);
        return 0;
}
 
static int config_parse_volume_label(
                const char *unit,
                const char *filename,
                unsigned line,
                const char *section,
                unsigned section_line,
                const char *lvalue,
                int ltype,
                const char *rvalue,
                void *data,
                void *userdata) {
 
        _cleanup_free_ char *resolved = NULL;
        char **label = ASSERT_PTR(data);
        int r;
 
        assert(rvalue);
 
        /* Like config_parse_label(), but for the LUKS2 superblock label, which is limited in bytes, not
         * UTF-16 code units. Again, the empty label is a valid one. */
 
        r = specifier_printf(rvalue, LUKS2_LABEL_MAX, system_and_tmp_specifier_table, arg_root, /* userdata= */ NULL, &resolved);
        if (r < 0) {
                log_syntax(unit, LOG_WARNING, filename, line, r,
                           "Failed to expand specifiers in %s=, or result too long for LUKS2 superblock, ignoring: %s", lvalue, rvalue);
                return 0;
        }
 
        if (!string_is_safe(resolved, STRING_ALLOW_EMPTY|STRING_ALLOW_BACKSLASHES|STRING_ALLOW_QUOTES|STRING_ALLOW_GLOBS)) {
                log_syntax(unit, LOG_WARNING, filename, line, 0,
                           "Volume label not valid UTF-8 or contains control characters, ignoring: \"%s\" (from \"%s\")",
                           resolved, rvalue);
                return 0;
        }
 
        free_and_replace(*label, resolved);
        return 0;
}
 
static int config_parse_weight(
                const char *unit,
                const char *filename,
                unsigned line,
                const char *section,
                unsigned section_line,
                const char *lvalue,
                int ltype,
                const char *rvalue,
                void *data,
                void *userdata) {