1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #if HAVE_VALGRIND_MEMCHECK_H
4 #include <valgrind/memcheck.h>
10 #include <linux/loop.h>
12 #include <sys/ioctl.h>
15 #include "sd-device.h"
18 #include "alloc-util.h"
19 #include "blkid-util.h"
20 #include "blockdev-util.h"
21 #include "btrfs-util.h"
24 #include "conf-files.h"
25 #include "conf-parser.h"
26 #include "constants.h"
27 #include "cryptsetup-util.h"
28 #include "device-util.h"
29 #include "devnum-util.h"
30 #include "dirent-util.h"
32 #include "errno-util.h"
34 #include "fdisk-util.h"
36 #include "format-table.h"
37 #include "format-util.h"
39 #include "glyph-util.h"
41 #include "hexdecoct.h"
43 #include "id128-util.h"
44 #include "initrd-util.h"
48 #include "loop-util.h"
49 #include "main-func.h"
51 #include "mkfs-util.h"
52 #include "mount-util.h"
53 #include "mountpoint-util.h"
54 #include "nulstr-util.h"
55 #include "openssl-util.h"
56 #include "parse-argument.h"
57 #include "parse-helpers.h"
58 #include "pretty-print.h"
59 #include "proc-cmdline.h"
60 #include "process-util.h"
61 #include "random-util.h"
62 #include "resize-fs.h"
64 #include "sort-util.h"
65 #include "specifier.h"
66 #include "stdio-util.h"
67 #include "string-table.h"
68 #include "string-util.h"
70 #include "sync-util.h"
71 #include "tmpfile-util.h"
72 #include "terminal-util.h"
74 #include "tpm2-util.h"
75 #include "user-util.h"
78 /* If not configured otherwise use a minimal partition size of 10M */
79 #define DEFAULT_MIN_SIZE (10ULL*1024ULL*1024ULL)
81 /* Hard lower limit for new partition sizes */
82 #define HARD_MIN_SIZE 4096ULL
84 /* We know up front we're never going to put more than this in a verity sig partition. */
85 #define VERITY_SIG_SIZE (HARD_MIN_SIZE*4ULL)
87 /* libfdisk takes off slightly more than 1M of the disk size when creating a GPT disk label */
88 #define GPT_METADATA_SIZE (1044ULL*1024ULL)
90 /* LUKS2 takes off 16M of the partition size with its metadata by default */
91 #define LUKS2_METADATA_SIZE (16ULL*1024ULL*1024ULL)
93 /* To do LUKS2 offline encryption, we need to keep some extra free space at the end of the partition. */
94 #define LUKS2_METADATA_KEEP_FREE (LUKS2_METADATA_SIZE*2ULL)
96 /* LUKS2 volume key size. */
97 #define VOLUME_KEY_SIZE (512ULL/8ULL)
99 /* Note: When growing and placing new partitions we always align to 4K sector size. It's how newer hard disks
100 * are designed, and if everything is aligned to that performance is best. And for older hard disks with 512B
101 * sector size devices were generally assumed to have an even number of sectors, hence at the worst we'll
102 * waste 3K per partition, which is probably fine. */
105 EMPTY_REFUSE
, /* refuse empty disks, never create a partition table */
106 EMPTY_ALLOW
, /* allow empty disks, create partition table if necessary */
107 EMPTY_REQUIRE
, /* require an empty disk, create a partition table */
108 EMPTY_FORCE
, /* make disk empty, erase everything, create a partition table always */
109 EMPTY_CREATE
, /* create disk as loopback file, create a partition table always */
110 } arg_empty
= EMPTY_REFUSE
;
112 typedef enum FilterPartitionType
{
113 FILTER_PARTITIONS_NONE
,
114 FILTER_PARTITIONS_EXCLUDE
,
115 FILTER_PARTITIONS_INCLUDE
,
116 _FILTER_PARTITIONS_MAX
,
117 _FILTER_PARTITIONS_INVALID
= -EINVAL
,
118 } FilterPartitionsType
;
120 static bool arg_dry_run
= true;
121 static const char *arg_node
= NULL
;
122 static char *arg_root
= NULL
;
123 static char *arg_image
= NULL
;
124 static char **arg_definitions
= NULL
;
125 static bool arg_discard
= true;
126 static bool arg_can_factory_reset
= false;
127 static int arg_factory_reset
= -1;
128 static sd_id128_t arg_seed
= SD_ID128_NULL
;
129 static bool arg_randomize
= false;
130 static int arg_pretty
= -1;
131 static uint64_t arg_size
= UINT64_MAX
;
132 static bool arg_size_auto
= false;
133 static JsonFormatFlags arg_json_format_flags
= JSON_FORMAT_OFF
;
134 static PagerFlags arg_pager_flags
= 0;
135 static bool arg_legend
= true;
136 static void *arg_key
= NULL
;
137 static size_t arg_key_size
= 0;
138 static EVP_PKEY
*arg_private_key
= NULL
;
139 static X509
*arg_certificate
= NULL
;
140 static char *arg_tpm2_device
= NULL
;
141 static uint32_t arg_tpm2_pcr_mask
= UINT32_MAX
;
142 static char *arg_tpm2_public_key
= NULL
;
143 static uint32_t arg_tpm2_public_key_pcr_mask
= UINT32_MAX
;
144 static bool arg_split
= false;
145 static sd_id128_t
*arg_filter_partitions
= NULL
;
146 static size_t arg_n_filter_partitions
= 0;
147 static FilterPartitionsType arg_filter_partitions_type
= FILTER_PARTITIONS_NONE
;
148 static sd_id128_t
*arg_defer_partitions
= NULL
;
149 static size_t arg_n_defer_partitions
= 0;
150 static uint64_t arg_sector_size
= 0;
151 static ImagePolicy
*arg_image_policy
= NULL
;
153 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
154 STATIC_DESTRUCTOR_REGISTER(arg_image
, freep
);
155 STATIC_DESTRUCTOR_REGISTER(arg_definitions
, strv_freep
);
156 STATIC_DESTRUCTOR_REGISTER(arg_key
, erase_and_freep
);
157 STATIC_DESTRUCTOR_REGISTER(arg_private_key
, EVP_PKEY_freep
);
158 STATIC_DESTRUCTOR_REGISTER(arg_certificate
, X509_freep
);
159 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device
, freep
);
160 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_public_key
, freep
);
161 STATIC_DESTRUCTOR_REGISTER(arg_filter_partitions
, freep
);
162 STATIC_DESTRUCTOR_REGISTER(arg_image_policy
, image_policy_freep
);
164 typedef struct FreeArea FreeArea
;
166 typedef enum EncryptMode
{
170 ENCRYPT_KEY_FILE_TPM2
,
172 _ENCRYPT_MODE_INVALID
= -EINVAL
,
175 typedef enum VerityMode
{
181 _VERITY_MODE_INVALID
= -EINVAL
,
184 typedef enum MinimizeMode
{
189 _MINIMIZE_MODE_INVALID
= -EINVAL
,
192 typedef struct Partition
{
193 char *definition_path
;
194 char **drop_in_files
;
196 GptPartitionType type
;
197 sd_id128_t current_uuid
, new_uuid
;
198 bool new_uuid_is_set
;
199 char *current_label
, *new_label
;
200 sd_id128_t fs_uuid
, luks_uuid
;
206 uint32_t weight
, padding_weight
;
208 uint64_t current_size
, new_size
;
209 uint64_t size_min
, size_max
;
211 uint64_t current_padding
, new_padding
;
212 uint64_t padding_min
, padding_max
;
217 struct fdisk_partition
*current_partition
;
218 struct fdisk_partition
*new_partition
;
219 FreeArea
*padding_area
;
220 FreeArea
*allocated_to_area
;
222 char *copy_blocks_path
;
223 bool copy_blocks_path_is_our_file
;
224 bool copy_blocks_auto
;
225 const char *copy_blocks_root
;
227 uint64_t copy_blocks_size
;
231 char **exclude_files
;
232 char **make_directories
;
235 char *verity_match_key
;
236 MinimizeMode minimize
;
244 size_t roothash_size
;
246 char *split_name_format
;
249 struct Partition
*siblings
[_VERITY_MODE_MAX
];
251 LIST_FIELDS(struct Partition
, partitions
);
254 #define PARTITION_IS_FOREIGN(p) (!(p)->definition_path)
255 #define PARTITION_EXISTS(p) (!!(p)->current_partition)
263 typedef struct Context
{
264 LIST_HEAD(Partition
, partitions
);
267 FreeArea
**free_areas
;
270 uint64_t start
, end
, total
;
272 struct fdisk_context
*fdisk_context
;
273 uint64_t sector_size
;
279 bool node_is_our_file
;
285 static const char *encrypt_mode_table
[_ENCRYPT_MODE_MAX
] = {
286 [ENCRYPT_OFF
] = "off",
287 [ENCRYPT_KEY_FILE
] = "key-file",
288 [ENCRYPT_TPM2
] = "tpm2",
289 [ENCRYPT_KEY_FILE_TPM2
] = "key-file+tpm2",
292 static const char *verity_mode_table
[_VERITY_MODE_MAX
] = {
293 [VERITY_OFF
] = "off",
294 [VERITY_DATA
] = "data",
295 [VERITY_HASH
] = "hash",
296 [VERITY_SIG
] = "signature",
299 static const char *minimize_mode_table
[_MINIMIZE_MODE_MAX
] = {
300 [MINIMIZE_OFF
] = "off",
301 [MINIMIZE_BEST
] = "best",
302 [MINIMIZE_GUESS
] = "guess",
305 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(encrypt_mode
, EncryptMode
, ENCRYPT_KEY_FILE
);
306 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(verity_mode
, VerityMode
);
307 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(minimize_mode
, MinimizeMode
, MINIMIZE_BEST
);
309 static uint64_t round_down_size(uint64_t v
, uint64_t p
) {
313 static uint64_t round_up_size(uint64_t v
, uint64_t p
) {
315 v
= DIV_ROUND_UP(v
, p
);
317 if (v
> UINT64_MAX
/ p
)
318 return UINT64_MAX
; /* overflow */
323 static Partition
*partition_new(void) {
326 p
= new(Partition
, 1);
333 .current_size
= UINT64_MAX
,
334 .new_size
= UINT64_MAX
,
335 .size_min
= UINT64_MAX
,
336 .size_max
= UINT64_MAX
,
337 .current_padding
= UINT64_MAX
,
338 .new_padding
= UINT64_MAX
,
339 .padding_min
= UINT64_MAX
,
340 .padding_max
= UINT64_MAX
,
341 .partno
= UINT64_MAX
,
342 .offset
= UINT64_MAX
,
343 .copy_blocks_fd
= -EBADF
,
344 .copy_blocks_size
= UINT64_MAX
,
353 static Partition
* partition_free(Partition
*p
) {
357 free(p
->current_label
);
359 free(p
->definition_path
);
360 strv_free(p
->drop_in_files
);
362 if (p
->current_partition
)
363 fdisk_unref_partition(p
->current_partition
);
364 if (p
->new_partition
)
365 fdisk_unref_partition(p
->new_partition
);
367 if (p
->copy_blocks_path_is_our_file
)
368 unlink_and_free(p
->copy_blocks_path
);
370 free(p
->copy_blocks_path
);
371 safe_close(p
->copy_blocks_fd
);
374 strv_free(p
->copy_files
);
375 strv_free(p
->exclude_files
);
376 strv_free(p
->make_directories
);
377 free(p
->verity_match_key
);
381 free(p
->split_name_format
);
382 unlink_and_free(p
->split_path
);
387 static void partition_foreignize(Partition
*p
) {
389 assert(PARTITION_EXISTS(p
));
391 /* Reset several parameters set through definition file to make the partition foreign. */
393 p
->definition_path
= mfree(p
->definition_path
);
394 p
->drop_in_files
= strv_free(p
->drop_in_files
);
396 p
->copy_blocks_path
= mfree(p
->copy_blocks_path
);
397 p
->copy_blocks_fd
= safe_close(p
->copy_blocks_fd
);
398 p
->copy_blocks_root
= NULL
;
400 p
->format
= mfree(p
->format
);
401 p
->copy_files
= strv_free(p
->copy_files
);
402 p
->exclude_files
= strv_free(p
->exclude_files
);
403 p
->make_directories
= strv_free(p
->make_directories
);
404 p
->verity_match_key
= mfree(p
->verity_match_key
);
408 p
->padding_weight
= 0;
409 p
->size_min
= UINT64_MAX
;
410 p
->size_max
= UINT64_MAX
;
411 p
->padding_min
= UINT64_MAX
;
412 p
->padding_max
= UINT64_MAX
;
416 p
->verity
= VERITY_OFF
;
419 static bool partition_exclude(const Partition
*p
) {
422 if (arg_filter_partitions_type
== FILTER_PARTITIONS_NONE
)
425 for (size_t i
= 0; i
< arg_n_filter_partitions
; i
++)
426 if (sd_id128_equal(p
->type
.uuid
, arg_filter_partitions
[i
]))
427 return arg_filter_partitions_type
== FILTER_PARTITIONS_EXCLUDE
;
429 return arg_filter_partitions_type
== FILTER_PARTITIONS_INCLUDE
;
432 static bool partition_defer(const Partition
*p
) {
435 for (size_t i
= 0; i
< arg_n_defer_partitions
; i
++)
436 if (sd_id128_equal(p
->type
.uuid
, arg_defer_partitions
[i
]))
442 static Partition
* partition_unlink_and_free(Context
*context
, Partition
*p
) {
446 LIST_REMOVE(partitions
, context
->partitions
, p
);
448 assert(context
->n_partitions
> 0);
449 context
->n_partitions
--;
451 return partition_free(p
);
454 DEFINE_TRIVIAL_CLEANUP_FUNC(Partition
*, partition_free
);
456 static Context
*context_new(sd_id128_t seed
) {
459 context
= new(Context
, 1);
463 *context
= (Context
) {
473 static void context_free_free_areas(Context
*context
) {
476 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
477 free(context
->free_areas
[i
]);
479 context
->free_areas
= mfree(context
->free_areas
);
480 context
->n_free_areas
= 0;
483 static Context
*context_free(Context
*context
) {
487 while (context
->partitions
)
488 partition_unlink_and_free(context
, context
->partitions
);
489 assert(context
->n_partitions
== 0);
491 context_free_free_areas(context
);
493 if (context
->fdisk_context
)
494 fdisk_unref_context(context
->fdisk_context
);
496 safe_close(context
->backing_fd
);
497 if (context
->node_is_our_file
)
498 unlink_and_free(context
->node
);
502 return mfree(context
);
505 DEFINE_TRIVIAL_CLEANUP_FUNC(Context
*, context_free
);
507 static int context_add_free_area(
515 assert(!after
|| !after
->padding_area
);
517 if (!GREEDY_REALLOC(context
->free_areas
, context
->n_free_areas
+ 1))
520 a
= new(FreeArea
, 1);
529 context
->free_areas
[context
->n_free_areas
++] = a
;
532 after
->padding_area
= a
;
537 static void partition_drop_or_foreignize(Partition
*p
) {
538 if (!p
|| p
->dropped
|| PARTITION_IS_FOREIGN(p
))
541 if (PARTITION_EXISTS(p
)) {
542 log_info("Can't grow existing partition %s of priority %" PRIi32
", ignoring.",
543 strna(p
->current_label
?: p
->new_label
), p
->priority
);
545 /* Handle the partition as foreign. Do not set dropped flag. */
546 partition_foreignize(p
);
548 log_info("Can't fit partition %s of priority %" PRIi32
", dropping.",
549 p
->definition_path
, p
->priority
);
552 p
->allocated_to_area
= NULL
;
556 static bool context_drop_or_foreignize_one_priority(Context
*context
) {
557 int32_t priority
= 0;
559 LIST_FOREACH(partitions
, p
, context
->partitions
) {
563 priority
= MAX(priority
, p
->priority
);
566 /* Refuse to drop partitions with 0 or negative priorities or partitions of priorities that have at
567 * least one existing priority */
571 LIST_FOREACH(partitions
, p
, context
->partitions
) {
572 if (p
->priority
< priority
)
575 partition_drop_or_foreignize(p
);
577 /* We ensure that all verity sibling partitions have the same priority, so it's safe
578 * to drop all siblings here as well. */
580 for (VerityMode mode
= VERITY_OFF
+ 1; mode
< _VERITY_MODE_MAX
; mode
++)
581 partition_drop_or_foreignize(p
->siblings
[mode
]);
587 static uint64_t partition_min_size(const Context
*context
, const Partition
*p
) {
593 /* Calculate the disk space we really need at minimum for this partition. If the partition already
594 * exists the current size is what we really need. If it doesn't exist yet refuse to allocate less
597 * DEFAULT_MIN_SIZE is the default SizeMin= we configure if nothing else is specified. */
599 if (PARTITION_IS_FOREIGN(p
)) {
600 /* Don't allow changing size of partitions not managed by us */
601 assert(p
->current_size
!= UINT64_MAX
);
602 return p
->current_size
;
605 if (p
->verity
== VERITY_SIG
)
606 return VERITY_SIG_SIZE
;
608 sz
= p
->current_size
!= UINT64_MAX
? p
->current_size
: HARD_MIN_SIZE
;
610 if (!PARTITION_EXISTS(p
)) {
613 if (p
->encrypt
!= ENCRYPT_OFF
)
614 d
+= round_up_size(LUKS2_METADATA_KEEP_FREE
, context
->grain_size
);
616 if (p
->copy_blocks_size
!= UINT64_MAX
)
617 d
+= round_up_size(p
->copy_blocks_size
, context
->grain_size
);
618 else if (p
->format
|| p
->encrypt
!= ENCRYPT_OFF
) {
621 /* If we shall synthesize a file system, take minimal fs size into account (assumed to be 4K if not known) */
622 f
= p
->format
? round_up_size(minimal_size_by_fs_name(p
->format
), context
->grain_size
) : UINT64_MAX
;
623 d
+= f
== UINT64_MAX
? context
->grain_size
: f
;
630 return MAX(round_up_size(p
->size_min
!= UINT64_MAX
? p
->size_min
: DEFAULT_MIN_SIZE
, context
->grain_size
), sz
);
633 static uint64_t partition_max_size(const Context
*context
, const Partition
*p
) {
636 /* Calculate how large the partition may become at max. This is generally the configured maximum
637 * size, except when it already exists and is larger than that. In that case it's the existing size,
638 * since we never want to shrink partitions. */
643 if (PARTITION_IS_FOREIGN(p
)) {
644 /* Don't allow changing size of partitions not managed by us */
645 assert(p
->current_size
!= UINT64_MAX
);
646 return p
->current_size
;
649 if (p
->verity
== VERITY_SIG
)
650 return VERITY_SIG_SIZE
;
652 if (p
->size_max
== UINT64_MAX
)
655 sm
= round_down_size(p
->size_max
, context
->grain_size
);
657 if (p
->current_size
!= UINT64_MAX
)
658 sm
= MAX(p
->current_size
, sm
);
660 return MAX(partition_min_size(context
, p
), sm
);
663 static uint64_t partition_min_padding(const Partition
*p
) {
665 return p
->padding_min
!= UINT64_MAX
? p
->padding_min
: 0;
668 static uint64_t partition_max_padding(const Partition
*p
) {
670 return p
->padding_max
;
673 static uint64_t partition_min_size_with_padding(Context
*context
, const Partition
*p
) {
676 /* Calculate the disk space we need for this partition plus any free space coming after it. This
677 * takes user configured padding into account as well as any additional whitespace needed to align
678 * the next partition to 4K again. */
683 sz
= partition_min_size(context
, p
) + partition_min_padding(p
);
685 if (PARTITION_EXISTS(p
)) {
686 /* If the partition wasn't aligned, add extra space so that any we might add will be aligned */
687 assert(p
->offset
!= UINT64_MAX
);
688 return round_up_size(p
->offset
+ sz
, context
->grain_size
) - p
->offset
;
691 /* If this is a new partition we'll place it aligned, hence we just need to round up the required size here */
692 return round_up_size(sz
, context
->grain_size
);
695 static uint64_t free_area_available(const FreeArea
*a
) {
698 /* Determines how much of this free area is not allocated yet */
700 assert(a
->size
>= a
->allocated
);
701 return a
->size
- a
->allocated
;
704 static uint64_t free_area_current_end(Context
*context
, const FreeArea
*a
) {
709 return free_area_available(a
);
711 assert(a
->after
->offset
!= UINT64_MAX
);
712 assert(a
->after
->current_size
!= UINT64_MAX
);
714 /* Calculate where the free area ends, based on the offset of the partition preceding it. */
715 return round_up_size(a
->after
->offset
+ a
->after
->current_size
, context
->grain_size
) + free_area_available(a
);
718 static uint64_t free_area_min_end(Context
*context
, const FreeArea
*a
) {
725 assert(a
->after
->offset
!= UINT64_MAX
);
726 assert(a
->after
->current_size
!= UINT64_MAX
);
728 /* Calculate where the partition would end when we give it as much as it needs. */
729 return round_up_size(a
->after
->offset
+ partition_min_size_with_padding(context
, a
->after
), context
->grain_size
);
732 static uint64_t free_area_available_for_new_partitions(Context
*context
, const FreeArea
*a
) {
736 /* Similar to free_area_available(), but takes into account that the required size and padding of the
737 * preceding partition is honoured. */
739 return LESS_BY(free_area_current_end(context
, a
), free_area_min_end(context
, a
));
742 static int free_area_compare(FreeArea
*const *a
, FreeArea
*const*b
, Context
*context
) {
745 return CMP(free_area_available_for_new_partitions(context
, *a
),
746 free_area_available_for_new_partitions(context
, *b
));
749 static uint64_t charge_size(Context
*context
, uint64_t total
, uint64_t amount
) {
751 /* Subtract the specified amount from total, rounding up to multiple of 4K if there's room */
752 assert(amount
<= total
);
753 return LESS_BY(total
, round_up_size(amount
, context
->grain_size
));
756 static uint64_t charge_weight(uint64_t total
, uint64_t amount
) {
757 assert(amount
<= total
);
758 return total
- amount
;
761 static bool context_allocate_partitions(Context
*context
, uint64_t *ret_largest_free_area
) {
764 /* This may be called multiple times. Reset previous assignments. */
765 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
766 context
->free_areas
[i
]->allocated
= 0;
768 /* Sort free areas by size, putting smallest first */
769 typesafe_qsort_r(context
->free_areas
, context
->n_free_areas
, free_area_compare
, context
);
771 /* In any case return size of the largest free area (i.e. not the size of all free areas
773 if (ret_largest_free_area
)
774 *ret_largest_free_area
=
775 context
->n_free_areas
== 0 ? 0 :
776 free_area_available_for_new_partitions(context
, context
->free_areas
[context
->n_free_areas
-1]);
778 /* Check that each existing partition can fit its area. */
779 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
780 if (free_area_current_end(context
, context
->free_areas
[i
]) <
781 free_area_min_end(context
, context
->free_areas
[i
]))
784 /* A simple first-fit algorithm. We return true if we can fit the partitions in, otherwise false. */
785 LIST_FOREACH(partitions
, p
, context
->partitions
) {
790 /* Skip partitions we already dropped or that already exist */
791 if (p
->dropped
|| PARTITION_EXISTS(p
))
794 /* How much do we need to fit? */
795 required
= partition_min_size_with_padding(context
, p
);
796 assert(required
% context
->grain_size
== 0);
798 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
799 a
= context
->free_areas
[i
];
801 if (free_area_available_for_new_partitions(context
, a
) >= required
) {
808 return false; /* 😢 Oh no! We can't fit this partition into any free area! */
810 /* Assign the partition to this free area */
811 p
->allocated_to_area
= a
;
813 /* Budget the minimal partition size */
814 a
->allocated
+= required
;
820 static int context_sum_weights(Context
*context
, FreeArea
*a
, uint64_t *ret
) {
821 uint64_t weight_sum
= 0;
827 /* Determine the sum of the weights of all partitions placed in or before the specified free area */
829 LIST_FOREACH(partitions
, p
, context
->partitions
) {
830 if (p
->padding_area
!= a
&& p
->allocated_to_area
!= a
)
833 if (p
->weight
> UINT64_MAX
- weight_sum
)
835 weight_sum
+= p
->weight
;
837 if (p
->padding_weight
> UINT64_MAX
- weight_sum
)
839 weight_sum
+= p
->padding_weight
;
846 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Combined weight of partition exceeds unsigned 64bit range, refusing.");
849 static uint64_t scale_by_weight(uint64_t value
, uint64_t weight
, uint64_t weight_sum
) {
850 assert(weight_sum
>= weight
);
855 if (weight
== weight_sum
)
857 if (value
<= UINT64_MAX
/ weight
)
858 return value
* weight
/ weight_sum
;
860 /* Rescale weight and weight_sum to make not the calculation overflow. To satisfy the
861 * following conditions, 'weight_sum' is rounded up but 'weight' is rounded down:
862 * - the sum of scale_by_weight() for all weights must not be larger than the input value,
863 * - scale_by_weight() must not be larger than the ideal value (i.e. calculated with uint128_t). */
864 weight_sum
= DIV_ROUND_UP(weight_sum
, 2);
869 typedef enum GrowPartitionPhase
{
870 /* The zeroth phase: do not touch foreign partitions (i.e. those we don't manage). */
873 /* The first phase: we charge partitions which need more (according to constraints) than their weight-based share. */
876 /* The second phase: we charge partitions which need less (according to constraints) than their weight-based share. */
879 /* The third phase: we distribute what remains among the remaining partitions, according to the weights */
882 _GROW_PARTITION_PHASE_MAX
,
883 } GrowPartitionPhase
;
885 static bool context_grow_partitions_phase(
888 GrowPartitionPhase phase
,
890 uint64_t *weight_sum
) {
892 bool try_again
= false;
899 /* Now let's look at the intended weights and adjust them taking the minimum space assignments into
900 * account. i.e. if a partition has a small weight but a high minimum space value set it should not
901 * get any additional room from the left-overs. Similar, if two partitions have the same weight they
902 * should get the same space if possible, even if one has a smaller minimum size than the other. */
903 LIST_FOREACH(partitions
, p
, context
->partitions
) {
905 /* Look only at partitions associated with this free area, i.e. immediately
906 * preceding it, or allocated into it */
907 if (p
->allocated_to_area
!= a
&& p
->padding_area
!= a
)
910 if (p
->new_size
== UINT64_MAX
) {
911 uint64_t share
, rsz
, xsz
;
914 /* Calculate how much this space this partition needs if everyone would get
915 * the weight based share */
916 share
= scale_by_weight(*span
, p
->weight
, *weight_sum
);
918 rsz
= partition_min_size(context
, p
);
919 xsz
= partition_max_size(context
, p
);
921 if (phase
== PHASE_FOREIGN
&& PARTITION_IS_FOREIGN(p
)) {
922 /* Never change of foreign partitions (i.e. those we don't manage) */
924 p
->new_size
= p
->current_size
;
927 } else if (phase
== PHASE_OVERCHARGE
&& rsz
> share
) {
928 /* This partition needs more than its calculated share. Let's assign
929 * it that, and take this partition out of all calculations and start
933 charge
= try_again
= true;
935 } else if (phase
== PHASE_UNDERCHARGE
&& xsz
< share
) {
936 /* This partition accepts less than its calculated
937 * share. Let's assign it that, and take this partition out
938 * of all calculations and start again. */
941 charge
= try_again
= true;
943 } else if (phase
== PHASE_DISTRIBUTE
) {
944 /* This partition can accept its calculated share. Let's
945 * assign it. There's no need to restart things here since
946 * assigning this shouldn't impact the shares of the other
949 assert(share
>= rsz
);
950 p
->new_size
= CLAMP(round_down_size(share
, context
->grain_size
), rsz
, xsz
);
955 *span
= charge_size(context
, *span
, p
->new_size
);
956 *weight_sum
= charge_weight(*weight_sum
, p
->weight
);
960 if (p
->new_padding
== UINT64_MAX
) {
961 uint64_t share
, rsz
, xsz
;
964 share
= scale_by_weight(*span
, p
->padding_weight
, *weight_sum
);
966 rsz
= partition_min_padding(p
);
967 xsz
= partition_max_padding(p
);
969 if (phase
== PHASE_OVERCHARGE
&& rsz
> share
) {
970 p
->new_padding
= rsz
;
971 charge
= try_again
= true;
972 } else if (phase
== PHASE_UNDERCHARGE
&& xsz
< share
) {
973 p
->new_padding
= xsz
;
974 charge
= try_again
= true;
975 } else if (phase
== PHASE_DISTRIBUTE
) {
976 assert(share
>= rsz
);
977 p
->new_padding
= CLAMP(round_down_size(share
, context
->grain_size
), rsz
, xsz
);
982 *span
= charge_size(context
, *span
, p
->new_padding
);
983 *weight_sum
= charge_weight(*weight_sum
, p
->padding_weight
);
991 static void context_grow_partition_one(Context
*context
, FreeArea
*a
, Partition
*p
, uint64_t *span
) {
1002 if (p
->allocated_to_area
!= a
)
1005 if (PARTITION_IS_FOREIGN(p
))
1008 assert(p
->new_size
!= UINT64_MAX
);
1010 /* Calculate new size and align. */
1011 m
= round_down_size(p
->new_size
+ *span
, context
->grain_size
);
1012 /* But ensure this doesn't shrink the size. */
1013 m
= MAX(m
, p
->new_size
);
1014 /* And ensure this doesn't exceed the maximum size. */
1015 m
= MIN(m
, partition_max_size(context
, p
));
1017 assert(m
>= p
->new_size
);
1019 *span
= charge_size(context
, *span
, m
- p
->new_size
);
1023 static int context_grow_partitions_on_free_area(Context
*context
, FreeArea
*a
) {
1024 uint64_t weight_sum
= 0, span
;
1030 r
= context_sum_weights(context
, a
, &weight_sum
);
1034 /* Let's calculate the total area covered by this free area and the partition before it */
1037 assert(a
->after
->offset
!= UINT64_MAX
);
1038 assert(a
->after
->current_size
!= UINT64_MAX
);
1040 span
+= round_up_size(a
->after
->offset
+ a
->after
->current_size
, context
->grain_size
) - a
->after
->offset
;
1043 for (GrowPartitionPhase phase
= 0; phase
< _GROW_PARTITION_PHASE_MAX
;)
1044 if (context_grow_partitions_phase(context
, a
, phase
, &span
, &weight_sum
))
1045 phase
++; /* go to the next phase */
1047 /* We still have space left over? Donate to preceding partition if we have one */
1048 if (span
> 0 && a
->after
)
1049 context_grow_partition_one(context
, a
, a
->after
, &span
);
1051 /* What? Even still some space left (maybe because there was no preceding partition, or it had a
1052 * size limit), then let's donate it to whoever wants it. */
1054 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1055 context_grow_partition_one(context
, a
, p
, &span
);
1060 /* Yuck, still no one? Then make it padding */
1061 if (span
> 0 && a
->after
) {
1062 assert(a
->after
->new_padding
!= UINT64_MAX
);
1063 a
->after
->new_padding
+= span
;
1069 static int context_grow_partitions(Context
*context
) {
1074 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
1075 r
= context_grow_partitions_on_free_area(context
, context
->free_areas
[i
]);
1080 /* All existing partitions that have no free space after them can't change size */
1081 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1085 if (!PARTITION_EXISTS(p
) || p
->padding_area
) {
1086 /* The algorithm above must have initialized this already */
1087 assert(p
->new_size
!= UINT64_MAX
);
1091 assert(p
->new_size
== UINT64_MAX
);
1092 p
->new_size
= p
->current_size
;
1094 assert(p
->new_padding
== UINT64_MAX
);
1095 p
->new_padding
= p
->current_padding
;
1101 static uint64_t find_first_unused_partno(Context
*context
) {
1102 uint64_t partno
= 0;
1106 for (partno
= 0;; partno
++) {
1108 LIST_FOREACH(partitions
, p
, context
->partitions
)
1109 if (p
->partno
!= UINT64_MAX
&& p
->partno
== partno
)
1118 static void context_place_partitions(Context
*context
) {
1122 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
1123 FreeArea
*a
= context
->free_areas
[i
];
1124 _unused_
uint64_t left
;
1128 assert(a
->after
->offset
!= UINT64_MAX
);
1129 assert(a
->after
->new_size
!= UINT64_MAX
);
1130 assert(a
->after
->new_padding
!= UINT64_MAX
);
1132 start
= a
->after
->offset
+ a
->after
->new_size
+ a
->after
->new_padding
;
1134 start
= context
->start
;
1136 start
= round_up_size(start
, context
->grain_size
);
1139 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1140 if (p
->allocated_to_area
!= a
)
1144 p
->partno
= find_first_unused_partno(context
);
1146 assert(left
>= p
->new_size
);
1147 start
+= p
->new_size
;
1148 left
-= p
->new_size
;
1150 assert(left
>= p
->new_padding
);
1151 start
+= p
->new_padding
;
1152 left
-= p
->new_padding
;
1157 static int config_parse_type(
1159 const char *filename
,
1161 const char *section
,
1162 unsigned section_line
,
1169 GptPartitionType
*type
= ASSERT_PTR(data
);
1174 r
= gpt_partition_type_from_string(rvalue
, type
);
1176 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to parse partition type: %s", rvalue
);
1181 static int config_parse_label(
1183 const char *filename
,
1185 const char *section
,
1186 unsigned section_line
,
1193 _cleanup_free_
char *resolved
= NULL
;
1194 char **label
= ASSERT_PTR(data
);
1199 /* Nota bene: the empty label is a totally valid one. Let's hence not follow our usual rule of
1200 * assigning the empty string to reset to default here, but really accept it as label to set. */
1202 r
= specifier_printf(rvalue
, GPT_LABEL_MAX
, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved
);
1204 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1205 "Failed to expand specifiers in Label=, ignoring: %s", rvalue
);
1209 if (!utf8_is_valid(resolved
)) {
1210 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1211 "Partition label not valid UTF-8, ignoring: %s", rvalue
);
1215 r
= gpt_partition_label_valid(resolved
);
1217 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1218 "Failed to check if string is valid as GPT partition label, ignoring: \"%s\" (from \"%s\")",
1223 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1224 "Partition label too long for GPT table, ignoring: \"%s\" (from \"%s\")",
1229 free_and_replace(*label
, resolved
);
1233 static int config_parse_weight(
1235 const char *filename
,
1237 const char *section
,
1238 unsigned section_line
,
1245 uint32_t *w
= ASSERT_PTR(data
), v
;
1250 r
= safe_atou32(rvalue
, &v
);
1252 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1253 "Failed to parse weight value, ignoring: %s", rvalue
);
1257 if (v
> 1000U*1000U) {
1258 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1259 "Weight needs to be in range 0…10000000, ignoring: %" PRIu32
, v
);
1267 static int config_parse_size4096(
1269 const char *filename
,
1271 const char *section
,
1272 unsigned section_line
,
1279 uint64_t *sz
= data
, parsed
;
1285 r
= parse_size(rvalue
, 1024, &parsed
);
1287 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
,
1288 "Failed to parse size value: %s", rvalue
);
1291 *sz
= round_up_size(parsed
, 4096);
1293 *sz
= round_down_size(parsed
, 4096);
1298 log_syntax(unit
, LOG_NOTICE
, filename
, line
, r
, "Rounded %s= size %" PRIu64
" %s %" PRIu64
", a multiple of 4096.",
1299 lvalue
, parsed
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), *sz
);
1304 static int config_parse_fstype(
1306 const char *filename
,
1308 const char *section
,
1309 unsigned section_line
,
1316 char **fstype
= ASSERT_PTR(data
);
1320 if (!filename_is_valid(rvalue
))
1321 return log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1322 "File system type is not valid, refusing: %s", rvalue
);
1324 return free_and_strdup_warn(fstype
, rvalue
);
1327 static int config_parse_copy_files(
1329 const char *filename
,
1331 const char *section
,
1332 unsigned section_line
,
1339 _cleanup_free_
char *source
= NULL
, *buffer
= NULL
, *resolved_source
= NULL
, *resolved_target
= NULL
;
1340 const char *p
= rvalue
, *target
;
1341 char ***copy_files
= ASSERT_PTR(data
);
1346 r
= extract_first_word(&p
, &source
, ":", EXTRACT_CUNESCAPE
|EXTRACT_DONT_COALESCE_SEPARATORS
);
1348 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to extract source path: %s", rvalue
);
1350 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0, "No argument specified: %s", rvalue
);
1354 r
= extract_first_word(&p
, &buffer
, ":", EXTRACT_CUNESCAPE
|EXTRACT_DONT_COALESCE_SEPARATORS
);
1356 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to extract target path: %s", rvalue
);
1358 target
= source
; /* No target, then it's the same as the source */
1363 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
), "Too many arguments: %s", rvalue
);
1365 r
= specifier_printf(source
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_source
);
1367 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1368 "Failed to expand specifiers in CopyFiles= source, ignoring: %s", rvalue
);
1372 r
= path_simplify_and_warn(resolved_source
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1376 r
= specifier_printf(target
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_target
);
1378 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1379 "Failed to expand specifiers in CopyFiles= target, ignoring: %s", resolved_target
);
1383 r
= path_simplify_and_warn(resolved_target
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1387 r
= strv_consume_pair(copy_files
, TAKE_PTR(resolved_source
), TAKE_PTR(resolved_target
));
1394 static int config_parse_exclude_files(
1396 const char *filename
,
1398 const char *section
,
1399 unsigned section_line
,
1405 _cleanup_free_
char *resolved
= NULL
;
1406 char ***exclude_files
= ASSERT_PTR(data
);
1409 if (isempty(rvalue
)) {
1410 *exclude_files
= strv_free(*exclude_files
);
1414 r
= specifier_printf(rvalue
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved
);
1416 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1417 "Failed to expand specifiers in ExcludeFiles= path, ignoring: %s", rvalue
);
1421 r
= path_simplify_and_warn(resolved
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1425 if (strv_consume(exclude_files
, TAKE_PTR(resolved
)) < 0)
1431 static int config_parse_copy_blocks(
1433 const char *filename
,
1435 const char *section
,
1436 unsigned section_line
,
1443 _cleanup_free_
char *d
= NULL
;
1444 Partition
*partition
= ASSERT_PTR(data
);
1449 if (isempty(rvalue
)) {
1450 partition
->copy_blocks_path
= mfree(partition
->copy_blocks_path
);
1451 partition
->copy_blocks_auto
= false;
1455 if (streq(rvalue
, "auto")) {
1456 partition
->copy_blocks_path
= mfree(partition
->copy_blocks_path
);
1457 partition
->copy_blocks_auto
= true;
1458 partition
->copy_blocks_root
= arg_root
;
1462 r
= specifier_printf(rvalue
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &d
);
1464 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1465 "Failed to expand specifiers in CopyBlocks= source path, ignoring: %s", rvalue
);
1469 r
= path_simplify_and_warn(d
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1473 free_and_replace(partition
->copy_blocks_path
, d
);
1474 partition
->copy_blocks_auto
= false;
1475 partition
->copy_blocks_root
= arg_root
;
1479 static int config_parse_make_dirs(
1481 const char *filename
,
1483 const char *section
,
1484 unsigned section_line
,
1491 Partition
*partition
= ASSERT_PTR(data
);
1492 const char *p
= ASSERT_PTR(rvalue
);
1496 _cleanup_free_
char *word
= NULL
, *d
= NULL
;
1498 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_UNQUOTE
);
1502 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Invalid syntax, ignoring: %s", rvalue
);
1508 r
= specifier_printf(word
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &d
);
1510 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1511 "Failed to expand specifiers in MakeDirectories= parameter, ignoring: %s", word
);
1515 r
= path_simplify_and_warn(d
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1519 r
= strv_consume(&partition
->make_directories
, TAKE_PTR(d
));
1525 static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_encrypt
, encrypt_mode
, EncryptMode
, ENCRYPT_OFF
, "Invalid encryption mode");
1527 static int config_parse_gpt_flags(
1529 const char *filename
,
1531 const char *section
,
1532 unsigned section_line
,
1539 uint64_t *gpt_flags
= ASSERT_PTR(data
);
1544 r
= safe_atou64(rvalue
, gpt_flags
);
1546 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1547 "Failed to parse Flags= value, ignoring: %s", rvalue
);
1554 static int config_parse_uuid(
1556 const char *filename
,
1558 const char *section
,
1559 unsigned section_line
,
1566 Partition
*partition
= ASSERT_PTR(data
);
1569 if (isempty(rvalue
)) {
1570 partition
->new_uuid
= SD_ID128_NULL
;
1571 partition
->new_uuid_is_set
= false;
1575 if (streq(rvalue
, "null")) {
1576 partition
->new_uuid
= SD_ID128_NULL
;
1577 partition
->new_uuid_is_set
= true;
1581 r
= sd_id128_from_string(rvalue
, &partition
->new_uuid
);
1583 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse 128bit ID/UUID, ignoring: %s", rvalue
);
1587 partition
->new_uuid_is_set
= true;
1592 static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_verity
, verity_mode
, VerityMode
, VERITY_OFF
, "Invalid verity mode");
1593 static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_minimize
, minimize_mode
, MinimizeMode
, MINIMIZE_OFF
, "Invalid minimize mode");
1595 static int partition_read_definition(Partition
*p
, const char *path
, const char *const *conf_file_dirs
) {
1597 ConfigTableItem table
[] = {
1598 { "Partition", "Type", config_parse_type
, 0, &p
->type
},
1599 { "Partition", "Label", config_parse_label
, 0, &p
->new_label
},
1600 { "Partition", "UUID", config_parse_uuid
, 0, p
},
1601 { "Partition", "Priority", config_parse_int32
, 0, &p
->priority
},
1602 { "Partition", "Weight", config_parse_weight
, 0, &p
->weight
},
1603 { "Partition", "PaddingWeight", config_parse_weight
, 0, &p
->padding_weight
},
1604 { "Partition", "SizeMinBytes", config_parse_size4096
, 1, &p
->size_min
},
1605 { "Partition", "SizeMaxBytes", config_parse_size4096
, -1, &p
->size_max
},
1606 { "Partition", "PaddingMinBytes", config_parse_size4096
, 1, &p
->padding_min
},
1607 { "Partition", "PaddingMaxBytes", config_parse_size4096
, -1, &p
->padding_max
},
1608 { "Partition", "FactoryReset", config_parse_bool
, 0, &p
->factory_reset
},
1609 { "Partition", "CopyBlocks", config_parse_copy_blocks
, 0, p
},
1610 { "Partition", "Format", config_parse_fstype
, 0, &p
->format
},
1611 { "Partition", "CopyFiles", config_parse_copy_files
, 0, &p
->copy_files
},
1612 { "Partition", "ExcludeFiles", config_parse_exclude_files
, 0, &p
->exclude_files
},
1613 { "Partition", "MakeDirectories", config_parse_make_dirs
, 0, p
},
1614 { "Partition", "Encrypt", config_parse_encrypt
, 0, &p
->encrypt
},
1615 { "Partition", "Verity", config_parse_verity
, 0, &p
->verity
},
1616 { "Partition", "VerityMatchKey", config_parse_string
, 0, &p
->verity_match_key
},
1617 { "Partition", "Flags", config_parse_gpt_flags
, 0, &p
->gpt_flags
},
1618 { "Partition", "ReadOnly", config_parse_tristate
, 0, &p
->read_only
},
1619 { "Partition", "NoAuto", config_parse_tristate
, 0, &p
->no_auto
},
1620 { "Partition", "GrowFileSystem", config_parse_tristate
, 0, &p
->growfs
},
1621 { "Partition", "SplitName", config_parse_string
, 0, &p
->split_name_format
},
1622 { "Partition", "Minimize", config_parse_minimize
, 0, &p
->minimize
},
1626 _cleanup_free_
char *filename
= NULL
;
1627 const char* dropin_dirname
;
1629 r
= path_extract_filename(path
, &filename
);
1631 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1633 dropin_dirname
= strjoina(filename
, ".d");
1635 r
= config_parse_many(
1636 STRV_MAKE_CONST(path
),
1640 config_item_table_lookup
, table
,
1648 if (partition_exclude(p
))
1651 if (p
->size_min
!= UINT64_MAX
&& p
->size_max
!= UINT64_MAX
&& p
->size_min
> p
->size_max
)
1652 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1653 "SizeMinBytes= larger than SizeMaxBytes=, refusing.");
1655 if (p
->padding_min
!= UINT64_MAX
&& p
->padding_max
!= UINT64_MAX
&& p
->padding_min
> p
->padding_max
)
1656 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1657 "PaddingMinBytes= larger than PaddingMaxBytes=, refusing.");
1659 if (sd_id128_is_null(p
->type
.uuid
))
1660 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1661 "Type= not defined, refusing.");
1663 if ((p
->copy_blocks_path
|| p
->copy_blocks_auto
) &&
1664 (p
->format
|| !strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
)))
1665 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1666 "Format=/CopyFiles=/MakeDirectories= and CopyBlocks= cannot be combined, refusing.");
1668 if ((!strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
)) && streq_ptr(p
->format
, "swap"))
1669 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1670 "Format=swap and CopyFiles= cannot be combined, refusing.");
1672 if (!p
->format
&& (!strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
) || (p
->encrypt
!= ENCRYPT_OFF
&& !(p
->copy_blocks_path
|| p
->copy_blocks_auto
)))) {
1673 /* Pick "ext4" as file system if we are configured to copy files or encrypt the device */
1674 p
->format
= strdup("ext4");
1679 if (p
->minimize
!= MINIMIZE_OFF
&& !p
->format
)
1680 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1681 "Minimize= can only be enabled if Format= is set");
1683 if (p
->minimize
== MINIMIZE_BEST
&& !fstype_is_ro(p
->format
))
1684 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1685 "Minimize=best can only be used with read-only filesystems");
1687 if ((!strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
)) && !mkfs_supports_root_option(p
->format
) && geteuid() != 0)
1688 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EPERM
),
1689 "Need to be root to populate %s filesystems with CopyFiles=/MakeDirectories=",
1692 if (p
->format
&& fstype_is_ro(p
->format
) && strv_isempty(p
->copy_files
) && strv_isempty(p
->make_directories
))
1693 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1694 "Cannot format %s filesystem without source files, refusing", p
->format
);
1696 if (p
->verity
!= VERITY_OFF
|| p
->encrypt
!= ENCRYPT_OFF
) {
1697 r
= dlopen_cryptsetup();
1699 return log_syntax(NULL
, LOG_ERR
, path
, 1, r
,
1700 "libcryptsetup not found, Verity=/Encrypt= are not supported: %m");
1703 if (p
->verity
!= VERITY_OFF
&& !p
->verity_match_key
)
1704 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1705 "VerityMatchKey= must be set if Verity=%s", verity_mode_to_string(p
->verity
));
1707 if (p
->verity
== VERITY_OFF
&& p
->verity_match_key
)
1708 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1709 "VerityMatchKey= can only be set if Verity= is not \"%s\"",
1710 verity_mode_to_string(p
->verity
));
1712 if (IN_SET(p
->verity
, VERITY_HASH
, VERITY_SIG
) &&
1713 (p
->copy_files
|| p
->copy_blocks_path
|| p
->copy_blocks_auto
|| p
->format
|| p
->make_directories
))
1714 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1715 "CopyBlocks=/CopyFiles=/Format=/MakeDirectories= cannot be used with Verity=%s",
1716 verity_mode_to_string(p
->verity
));
1718 if (p
->verity
!= VERITY_OFF
&& p
->encrypt
!= ENCRYPT_OFF
)
1719 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1720 "Encrypting verity hash/data partitions is not supported");
1722 if (p
->verity
== VERITY_SIG
&& !arg_private_key
)
1723 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1724 "Verity signature partition requested but no private key provided (--private-key=)");
1726 if (p
->verity
== VERITY_SIG
&& !arg_certificate
)
1727 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1728 "Verity signature partition requested but no PEM certificate provided (--certificate=)");
1730 if (p
->verity
== VERITY_SIG
&& (p
->size_min
!= UINT64_MAX
|| p
->size_max
!= UINT64_MAX
))
1731 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1732 "SizeMinBytes=/SizeMaxBytes= cannot be used with Verity=%s",
1733 verity_mode_to_string(p
->verity
));
1735 /* Verity partitions are read only, let's imply the RO flag hence, unless explicitly configured otherwise. */
1736 if (IN_SET(p
->type
.designator
, PARTITION_ROOT_VERITY
, PARTITION_USR_VERITY
) && p
->read_only
< 0)
1737 p
->read_only
= true;
1739 /* Default to "growfs" on, unless read-only */
1740 if (gpt_partition_type_knows_growfs(p
->type
) &&
1744 if (!p
->split_name_format
) {
1745 char *s
= strdup("%t");
1749 p
->split_name_format
= s
;
1750 } else if (streq(p
->split_name_format
, "-"))
1751 p
->split_name_format
= mfree(p
->split_name_format
);
1756 static int find_verity_sibling(Context
*context
, Partition
*p
, VerityMode mode
, Partition
**ret
) {
1757 Partition
*s
= NULL
;
1760 assert(p
->verity
!= VERITY_OFF
);
1761 assert(p
->verity_match_key
);
1762 assert(mode
!= VERITY_OFF
);
1763 assert(p
->verity
!= mode
);
1766 /* Try to find the matching sibling partition of the given type for a verity partition. For a data
1767 * partition, this is the corresponding hash partition with the same verity name (and vice versa for
1768 * the hash partition). */
1770 LIST_FOREACH(partitions
, q
, context
->partitions
) {
1774 if (q
->verity
!= mode
)
1777 assert(q
->verity_match_key
);
1779 if (!streq(p
->verity_match_key
, q
->verity_match_key
))
1796 static int context_read_definitions(
1801 _cleanup_strv_free_
char **files
= NULL
;
1802 Partition
*last
= NULL
;
1804 const char *const *dirs
;
1808 dirs
= (const char* const*) (directories
?: CONF_PATHS_STRV("repart.d"));
1810 r
= conf_files_list_strv(&files
, ".conf", directories
? NULL
: root
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, dirs
);
1812 return log_error_errno(r
, "Failed to enumerate *.conf files: %m");
1814 STRV_FOREACH(f
, files
) {
1815 _cleanup_(partition_freep
) Partition
*p
= NULL
;
1817 p
= partition_new();
1821 p
->definition_path
= strdup(*f
);
1822 if (!p
->definition_path
)
1825 r
= partition_read_definition(p
, *f
, dirs
);
1831 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, p
);
1833 context
->n_partitions
++;
1836 /* Check that each configured verity hash/data partition has a matching verity data/hash partition. */
1838 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1839 if (p
->verity
== VERITY_OFF
)
1842 for (VerityMode mode
= VERITY_OFF
+ 1; mode
< _VERITY_MODE_MAX
; mode
++) {
1843 Partition
*q
= NULL
;
1845 if (p
->verity
== mode
)
1848 if (p
->siblings
[mode
])
1851 r
= find_verity_sibling(context
, p
, mode
, &q
);
1853 if (mode
!= VERITY_SIG
)
1854 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1855 "Missing verity %s partition for verity %s partition with VerityMatchKey=%s",
1856 verity_mode_to_string(mode
), verity_mode_to_string(p
->verity
), p
->verity_match_key
);
1857 } else if (r
== -ENOTUNIQ
)
1858 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1859 "Multiple verity %s partitions found for verity %s partition with VerityMatchKey=%s",
1860 verity_mode_to_string(mode
), verity_mode_to_string(p
->verity
), p
->verity_match_key
);
1862 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, r
,
1863 "Failed to find verity %s partition for verity %s partition with VerityMatchKey=%s",
1864 verity_mode_to_string(mode
), verity_mode_to_string(p
->verity
), p
->verity_match_key
);
1867 if (q
->priority
!= p
->priority
)
1868 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1869 "Priority mismatch (%i != %i) for verity sibling partitions with VerityMatchKey=%s",
1870 p
->priority
, q
->priority
, p
->verity_match_key
);
1872 p
->siblings
[mode
] = q
;
1880 static int determine_current_padding(
1881 struct fdisk_context
*c
,
1882 struct fdisk_table
*t
,
1883 struct fdisk_partition
*p
,
1888 size_t n_partitions
;
1889 uint64_t offset
, next
= UINT64_MAX
;
1895 if (!fdisk_partition_has_end(p
))
1896 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition has no end!");
1898 offset
= fdisk_partition_get_end(p
);
1899 assert(offset
< UINT64_MAX
/ secsz
);
1902 n_partitions
= fdisk_table_get_nents(t
);
1903 for (size_t i
= 0; i
< n_partitions
; i
++) {
1904 struct fdisk_partition
*q
;
1907 q
= fdisk_table_get_partition(t
, i
);
1909 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1911 if (fdisk_partition_is_used(q
) <= 0)
1914 if (!fdisk_partition_has_start(q
))
1917 start
= fdisk_partition_get_start(q
);
1918 assert(start
< UINT64_MAX
/ secsz
);
1921 if (start
>= offset
&& (next
== UINT64_MAX
|| next
> start
))
1925 if (next
== UINT64_MAX
) {
1926 /* No later partition? In that case check the end of the usable area */
1927 next
= fdisk_get_last_lba(c
);
1928 assert(next
< UINT64_MAX
);
1929 next
++; /* The last LBA is one sector before the end */
1931 assert(next
< UINT64_MAX
/ secsz
);
1935 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
1938 assert(next
>= offset
);
1939 offset
= round_up_size(offset
, grainsz
);
1940 next
= round_down_size(next
, grainsz
);
1942 *ret
= LESS_BY(next
, offset
); /* Saturated subtraction, rounding might have fucked things up */
1946 static int fdisk_ask_cb(struct fdisk_context
*c
, struct fdisk_ask
*ask
, void *data
) {
1947 _cleanup_free_
char *ids
= NULL
;
1950 if (fdisk_ask_get_type(ask
) != FDISK_ASKTYPE_STRING
)
1953 ids
= new(char, SD_ID128_UUID_STRING_MAX
);
1957 r
= fdisk_ask_string_set_result(ask
, sd_id128_to_uuid_string(*(sd_id128_t
*) data
, ids
));
1965 static int fdisk_set_disklabel_id_by_uuid(struct fdisk_context
*c
, sd_id128_t id
) {
1968 r
= fdisk_set_ask(c
, fdisk_ask_cb
, &id
);
1972 r
= fdisk_set_disklabel_id(c
);
1976 return fdisk_set_ask(c
, NULL
, NULL
);
1979 static int derive_uuid(sd_id128_t base
, const char *token
, sd_id128_t
*ret
) {
1981 uint8_t md
[SHA256_DIGEST_SIZE
];
1988 /* Derive a new UUID from the specified UUID in a stable and reasonably safe way. Specifically, we
1989 * calculate the HMAC-SHA256 of the specified token string, keyed by the supplied base (typically the
1990 * machine ID). We use the machine ID as key (and not as cleartext!) of the HMAC operation since it's
1991 * the machine ID we don't want to leak. */
1993 hmac_sha256(base
.bytes
, sizeof(base
.bytes
), token
, strlen(token
), result
.md
);
1995 /* Take the first half, mark it as v4 UUID */
1996 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
1997 *ret
= id128_make_v4_uuid(result
.id
);
2001 static int context_load_partition_table(Context
*context
) {
2002 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
2003 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
2004 uint64_t left_boundary
= UINT64_MAX
, first_lba
, last_lba
, nsectors
;
2005 _cleanup_free_
char *disk_uuid_string
= NULL
;
2006 bool from_scratch
= false;
2007 sd_id128_t disk_uuid
;
2008 size_t n_partitions
;
2009 unsigned long secsz
;
2014 assert(!context
->fdisk_context
);
2015 assert(!context
->free_areas
);
2016 assert(context
->start
== UINT64_MAX
);
2017 assert(context
->end
== UINT64_MAX
);
2018 assert(context
->total
== UINT64_MAX
);
2020 c
= fdisk_new_context();
2024 if (arg_sector_size
> 0)
2025 r
= fdisk_save_user_sector_size(c
, /* phy= */ 0, arg_sector_size
);
2029 if (context
->backing_fd
< 0) {
2030 context
->backing_fd
= open(context
->node
, O_RDONLY
|O_CLOEXEC
);
2031 if (context
->backing_fd
< 0)
2032 return log_error_errno(errno
, "Failed to open device '%s': %m", context
->node
);
2035 /* Auto-detect sector size if not specified. */
2036 r
= probe_sector_size_prefer_ioctl(context
->backing_fd
, &ssz
);
2038 return log_error_errno(r
, "Failed to probe sector size of '%s': %m", context
->node
);
2040 r
= fdisk_save_user_sector_size(c
, /* phy= */ 0, ssz
);
2043 return log_error_errno(r
, "Failed to set sector size: %m");
2045 /* libfdisk doesn't have an API to operate on arbitrary fds, hence reopen the fd going via the
2046 * /proc/self/fd/ magic path if we have an existing fd. Open the original file otherwise. */
2047 r
= fdisk_assign_device(
2049 context
->backing_fd
>= 0 ? FORMAT_PROC_FD_PATH(context
->backing_fd
) : context
->node
,
2051 if (r
== -EINVAL
&& arg_size_auto
) {
2054 /* libfdisk returns EINVAL if opening a file of size zero. Let's check for that, and accept
2055 * it if automatic sizing is requested. */
2057 if (context
->backing_fd
< 0)
2058 r
= stat(context
->node
, &st
);
2060 r
= fstat(context
->backing_fd
, &st
);
2062 return log_error_errno(errno
, "Failed to stat block device '%s': %m", context
->node
);
2064 if (S_ISREG(st
.st_mode
) && st
.st_size
== 0) {
2065 /* User the fallback values if we have no better idea */
2066 context
->sector_size
= arg_sector_size
?: 512;
2067 context
->grain_size
= 4096;
2068 return /* from_scratch = */ true;
2074 return log_error_errno(r
, "Failed to open device '%s': %m", context
->node
);
2076 if (context
->backing_fd
< 0) {
2077 /* If we have no fd referencing the device yet, make a copy of the fd now, so that we have one */
2078 context
->backing_fd
= fd_reopen(fdisk_get_devfd(c
), O_RDONLY
|O_CLOEXEC
);
2079 if (context
->backing_fd
< 0)
2080 return log_error_errno(context
->backing_fd
, "Failed to duplicate fdisk fd: %m");
2082 /* Tell udev not to interfere while we are processing the device */
2083 if (flock(context
->backing_fd
, arg_dry_run
? LOCK_SH
: LOCK_EX
) < 0)
2084 return log_error_errno(errno
, "Failed to lock block device: %m");
2087 /* The offsets/sizes libfdisk returns to us will be in multiple of the sector size of the
2088 * device. This is typically 512, and sometimes 4096. Let's query libfdisk once for it, and then use
2089 * it for all our needs. Note that the values we use ourselves always are in bytes though, thus mean
2090 * the same thing universally. Also note that regardless what kind of sector size is in use we'll
2091 * place partitions at multiples of 4K. */
2092 secsz
= fdisk_get_sector_size(c
);
2094 /* Insist on a power of two, and that it's a multiple of 512, i.e. the traditional sector size. */
2095 if (secsz
< 512 || !ISPOWEROF2(secsz
))
2096 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Sector size %lu is not a power of two larger than 512? Refusing.", secsz
);
2098 /* Use at least 4K, and ensure it's a multiple of the sector size, regardless if that is smaller or
2100 grainsz
= secsz
< 4096 ? 4096 : secsz
;
2102 log_debug("Sector size of device is %lu bytes. Using grain size of %" PRIu64
".", secsz
, grainsz
);
2104 switch (arg_empty
) {
2107 /* Refuse empty disks, insist on an existing GPT partition table */
2108 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
2109 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has no GPT disk label, not repartitioning.", context
->node
);
2114 /* Require an empty disk, refuse any existing partition table */
2115 r
= fdisk_has_label(c
);
2117 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", context
->node
);
2119 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s already has a disk label, refusing.", context
->node
);
2121 from_scratch
= true;
2125 /* Allow both an empty disk and an existing partition table, but only GPT */
2126 r
= fdisk_has_label(c
);
2128 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", context
->node
);
2130 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
2131 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has non-GPT disk label, not repartitioning.", context
->node
);
2133 from_scratch
= true;
2139 /* Always reinitiaize the disk, don't consider what there was on the disk before */
2140 from_scratch
= true;
2145 r
= fdisk_create_disklabel(c
, "gpt");
2147 return log_error_errno(r
, "Failed to create GPT disk label: %m");
2149 r
= derive_uuid(context
->seed
, "disk-uuid", &disk_uuid
);
2151 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
2153 r
= fdisk_set_disklabel_id_by_uuid(c
, disk_uuid
);
2155 return log_error_errno(r
, "Failed to set GPT disk label: %m");
2157 goto add_initial_free_area
;
2160 r
= fdisk_get_disklabel_id(c
, &disk_uuid_string
);
2162 return log_error_errno(r
, "Failed to get current GPT disk label UUID: %m");
2164 r
= sd_id128_from_string(disk_uuid_string
, &disk_uuid
);
2166 return log_error_errno(r
, "Failed to parse current GPT disk label UUID: %m");
2168 if (sd_id128_is_null(disk_uuid
)) {
2169 r
= derive_uuid(context
->seed
, "disk-uuid", &disk_uuid
);
2171 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
2173 r
= fdisk_set_disklabel_id(c
);
2175 return log_error_errno(r
, "Failed to set GPT disk label: %m");
2178 r
= fdisk_get_partitions(c
, &t
);
2180 return log_error_errno(r
, "Failed to acquire partition table: %m");
2182 n_partitions
= fdisk_table_get_nents(t
);
2183 for (size_t i
= 0; i
< n_partitions
; i
++) {
2184 _cleanup_free_
char *label_copy
= NULL
;
2185 Partition
*last
= NULL
;
2186 struct fdisk_partition
*p
;
2190 sd_id128_t ptid
, id
;
2193 p
= fdisk_table_get_partition(t
, i
);
2195 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
2197 if (fdisk_partition_is_used(p
) <= 0)
2200 if (fdisk_partition_has_start(p
) <= 0 ||
2201 fdisk_partition_has_size(p
) <= 0 ||
2202 fdisk_partition_has_partno(p
) <= 0)
2203 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a position, size or number.");
2205 r
= fdisk_partition_get_type_as_id128(p
, &ptid
);
2207 return log_error_errno(r
, "Failed to query partition type UUID: %m");
2209 r
= fdisk_partition_get_uuid_as_id128(p
, &id
);
2211 return log_error_errno(r
, "Failed to query partition UUID: %m");
2213 label
= fdisk_partition_get_name(p
);
2214 if (!isempty(label
)) {
2215 label_copy
= strdup(label
);
2220 sz
= fdisk_partition_get_size(p
);
2221 assert(sz
<= UINT64_MAX
/secsz
);
2224 start
= fdisk_partition_get_start(p
);
2225 assert(start
<= UINT64_MAX
/secsz
);
2228 partno
= fdisk_partition_get_partno(p
);
2230 if (left_boundary
== UINT64_MAX
|| left_boundary
> start
)
2231 left_boundary
= start
;
2233 /* Assign this existing partition to the first partition of the right type that doesn't have
2234 * an existing one assigned yet. */
2235 LIST_FOREACH(partitions
, pp
, context
->partitions
) {
2238 if (!sd_id128_equal(pp
->type
.uuid
, ptid
))
2241 if (!pp
->current_partition
) {
2242 pp
->current_uuid
= id
;
2243 pp
->current_size
= sz
;
2245 pp
->partno
= partno
;
2246 pp
->current_label
= TAKE_PTR(label_copy
);
2248 pp
->current_partition
= p
;
2249 fdisk_ref_partition(p
);
2251 r
= determine_current_padding(c
, t
, p
, secsz
, grainsz
, &pp
->current_padding
);
2255 if (pp
->current_padding
> 0) {
2256 r
= context_add_free_area(context
, pp
->current_padding
, pp
);
2266 /* If we have no matching definition, create a new one. */
2268 _cleanup_(partition_freep
) Partition
*np
= NULL
;
2270 np
= partition_new();
2274 np
->current_uuid
= id
;
2275 np
->type
= gpt_partition_type_from_uuid(ptid
);
2276 np
->current_size
= sz
;
2278 np
->partno
= partno
;
2279 np
->current_label
= TAKE_PTR(label_copy
);
2281 np
->current_partition
= p
;
2282 fdisk_ref_partition(p
);
2284 r
= determine_current_padding(c
, t
, p
, secsz
, grainsz
, &np
->current_padding
);
2288 if (np
->current_padding
> 0) {
2289 r
= context_add_free_area(context
, np
->current_padding
, np
);
2294 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, TAKE_PTR(np
));
2295 context
->n_partitions
++;
2299 add_initial_free_area
:
2300 nsectors
= fdisk_get_nsectors(c
);
2301 assert(nsectors
<= UINT64_MAX
/secsz
);
2304 first_lba
= fdisk_get_first_lba(c
);
2305 assert(first_lba
<= UINT64_MAX
/secsz
);
2308 last_lba
= fdisk_get_last_lba(c
);
2309 assert(last_lba
< UINT64_MAX
);
2311 assert(last_lba
<= UINT64_MAX
/secsz
);
2314 assert(last_lba
>= first_lba
);
2316 if (left_boundary
== UINT64_MAX
) {
2317 /* No partitions at all? Then the whole disk is up for grabs. */
2319 first_lba
= round_up_size(first_lba
, grainsz
);
2320 last_lba
= round_down_size(last_lba
, grainsz
);
2322 if (last_lba
> first_lba
) {
2323 r
= context_add_free_area(context
, last_lba
- first_lba
, NULL
);
2328 /* Add space left of first partition */
2329 assert(left_boundary
>= first_lba
);
2331 first_lba
= round_up_size(first_lba
, grainsz
);
2332 left_boundary
= round_down_size(left_boundary
, grainsz
);
2333 last_lba
= round_down_size(last_lba
, grainsz
);
2335 if (left_boundary
> first_lba
) {
2336 r
= context_add_free_area(context
, left_boundary
- first_lba
, NULL
);
2342 context
->start
= first_lba
;
2343 context
->end
= last_lba
;
2344 context
->total
= nsectors
;
2345 context
->sector_size
= secsz
;
2346 context
->grain_size
= grainsz
;
2347 context
->fdisk_context
= TAKE_PTR(c
);
2349 return from_scratch
;
2352 static void context_unload_partition_table(Context
*context
) {
2355 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2357 /* Entirely remove partitions that have no configuration */
2358 if (PARTITION_IS_FOREIGN(p
)) {
2359 partition_unlink_and_free(context
, p
);
2363 /* Otherwise drop all data we read off the block device and everything we might have
2364 * calculated based on it */
2367 p
->current_size
= UINT64_MAX
;
2368 p
->new_size
= UINT64_MAX
;
2369 p
->current_padding
= UINT64_MAX
;
2370 p
->new_padding
= UINT64_MAX
;
2371 p
->partno
= UINT64_MAX
;
2372 p
->offset
= UINT64_MAX
;
2374 if (p
->current_partition
) {
2375 fdisk_unref_partition(p
->current_partition
);
2376 p
->current_partition
= NULL
;
2379 if (p
->new_partition
) {
2380 fdisk_unref_partition(p
->new_partition
);
2381 p
->new_partition
= NULL
;
2384 p
->padding_area
= NULL
;
2385 p
->allocated_to_area
= NULL
;
2387 p
->current_uuid
= SD_ID128_NULL
;
2388 p
->current_label
= mfree(p
->current_label
);
2391 context
->start
= UINT64_MAX
;
2392 context
->end
= UINT64_MAX
;
2393 context
->total
= UINT64_MAX
;
2395 if (context
->fdisk_context
) {
2396 fdisk_unref_context(context
->fdisk_context
);
2397 context
->fdisk_context
= NULL
;
2400 context_free_free_areas(context
);
2403 static int format_size_change(uint64_t from
, uint64_t to
, char **ret
) {
2406 if (from
!= UINT64_MAX
) {
2407 if (from
== to
|| to
== UINT64_MAX
)
2408 t
= strdup(FORMAT_BYTES(from
));
2410 t
= strjoin(FORMAT_BYTES(from
), " ", special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), " ", FORMAT_BYTES(to
));
2411 } else if (to
!= UINT64_MAX
)
2412 t
= strjoin(special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), " ", FORMAT_BYTES(to
));
2425 static const char *partition_label(const Partition
*p
) {
2429 return p
->new_label
;
2431 if (p
->current_label
)
2432 return p
->current_label
;
2434 return gpt_partition_type_uuid_to_string(p
->type
.uuid
);
2437 static int context_dump_partitions(Context
*context
) {
2438 _cleanup_(table_unrefp
) Table
*t
= NULL
;
2439 uint64_t sum_padding
= 0, sum_size
= 0;
2441 const size_t roothash_col
= 13, dropin_files_col
= 14, split_path_col
= 15;
2442 bool has_roothash
= false, has_dropin_files
= false, has_split_path
= false;
2444 if ((arg_json_format_flags
& JSON_FORMAT_OFF
) && context
->n_partitions
== 0) {
2445 log_info("Empty partition table.");
2449 t
= table_new("type",
2468 if (!DEBUG_LOGGING
) {
2469 if (arg_json_format_flags
& JSON_FORMAT_OFF
)
2470 (void) table_set_display(t
, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4,
2471 (size_t) 8, (size_t) 11, roothash_col
, dropin_files_col
,
2474 (void) table_set_display(t
, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4,
2475 (size_t) 5, (size_t) 6, (size_t) 7, (size_t) 9, (size_t) 10,
2476 (size_t) 12, roothash_col
, dropin_files_col
,
2480 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 5), 100);
2481 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 6), 100);
2482 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 7), 100);
2483 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 8), 100);
2484 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 9), 100);
2485 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 10), 100);
2486 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 11), 100);
2488 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2489 _cleanup_free_
char *size_change
= NULL
, *padding_change
= NULL
, *partname
= NULL
, *rh
= NULL
;
2490 char uuid_buffer
[SD_ID128_UUID_STRING_MAX
];
2491 const char *label
, *activity
= NULL
;
2496 if (p
->current_size
== UINT64_MAX
)
2497 activity
= "create";
2498 else if (p
->current_size
!= p
->new_size
)
2499 activity
= "resize";
2501 label
= partition_label(p
);
2502 partname
= p
->partno
!= UINT64_MAX
? fdisk_partname(context
->node
, p
->partno
+1) : NULL
;
2504 r
= format_size_change(p
->current_size
, p
->new_size
, &size_change
);
2508 r
= format_size_change(p
->current_padding
, p
->new_padding
, &padding_change
);
2512 if (p
->new_size
!= UINT64_MAX
)
2513 sum_size
+= p
->new_size
;
2514 if (p
->new_padding
!= UINT64_MAX
)
2515 sum_padding
+= p
->new_padding
;
2517 if (p
->verity
!= VERITY_OFF
) {
2518 Partition
*hp
= p
->verity
== VERITY_HASH
? p
: p
->siblings
[VERITY_HASH
];
2520 rh
= hp
->roothash
? hexmem(hp
->roothash
, hp
->roothash_size
) : strdup("TBD");
2527 TABLE_STRING
, gpt_partition_type_uuid_to_string_harder(p
->type
.uuid
, uuid_buffer
),
2528 TABLE_STRING
, empty_to_null(label
) ?: "-", TABLE_SET_COLOR
, empty_to_null(label
) ? NULL
: ansi_grey(),
2529 TABLE_UUID
, p
->new_uuid_is_set
? p
->new_uuid
: p
->current_uuid
,
2530 TABLE_PATH_BASENAME
, p
->definition_path
, TABLE_SET_COLOR
, p
->definition_path
? NULL
: ansi_grey(),
2531 TABLE_STRING
, partname
?: "-", TABLE_SET_COLOR
, partname
? NULL
: ansi_highlight(),
2532 TABLE_UINT64
, p
->offset
,
2533 TABLE_UINT64
, p
->current_size
== UINT64_MAX
? 0 : p
->current_size
,
2534 TABLE_UINT64
, p
->new_size
,
2535 TABLE_STRING
, size_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_size
> 0 ? ansi_underline() : NULL
,
2536 TABLE_UINT64
, p
->current_padding
== UINT64_MAX
? 0 : p
->current_padding
,
2537 TABLE_UINT64
, p
->new_padding
,
2538 TABLE_STRING
, padding_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_padding
> 0 ? ansi_underline() : NULL
,
2539 TABLE_STRING
, activity
?: "unchanged",
2541 TABLE_STRV
, p
->drop_in_files
,
2542 TABLE_STRING
, empty_to_null(p
->split_path
) ?: "-");
2544 return table_log_add_error(r
);
2546 has_roothash
= has_roothash
|| !isempty(rh
);
2547 has_dropin_files
= has_dropin_files
|| !strv_isempty(p
->drop_in_files
);
2548 has_split_path
= has_split_path
|| !isempty(p
->split_path
);
2551 if ((arg_json_format_flags
& JSON_FORMAT_OFF
) && (sum_padding
> 0 || sum_size
> 0)) {
2554 a
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", FORMAT_BYTES(sum_size
));
2555 b
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", FORMAT_BYTES(sum_padding
));
2576 return table_log_add_error(r
);
2579 if (!has_roothash
) {
2580 r
= table_hide_column_from_display(t
, roothash_col
);
2582 return log_error_errno(r
, "Failed to set columns to display: %m");
2585 if (!has_dropin_files
) {
2586 r
= table_hide_column_from_display(t
, dropin_files_col
);
2588 return log_error_errno(r
, "Failed to set columns to display: %m");
2591 if (!has_split_path
) {
2592 r
= table_hide_column_from_display(t
, split_path_col
);
2594 return log_error_errno(r
, "Failed to set columns to display: %m");
2597 return table_print_with_pager(t
, arg_json_format_flags
, arg_pager_flags
, arg_legend
);
2600 static void context_bar_char_process_partition(
2605 size_t *ret_start
) {
2607 uint64_t from
, to
, total
;
2618 assert(p
->offset
!= UINT64_MAX
);
2619 assert(p
->new_size
!= UINT64_MAX
);
2622 to
= from
+ p
->new_size
;
2624 assert(context
->total
> 0);
2625 total
= context
->total
;
2627 assert(from
<= total
);
2628 x
= from
* n
/ total
;
2630 assert(to
<= total
);
2636 for (size_t i
= x
; i
< y
; i
++)
2642 static int partition_hint(const Partition
*p
, const char *node
, char **ret
) {
2643 _cleanup_free_
char *buf
= NULL
;
2647 /* Tries really hard to find a suitable description for this partition */
2649 if (p
->definition_path
)
2650 return path_extract_filename(p
->definition_path
, ret
);
2652 label
= partition_label(p
);
2653 if (!isempty(label
)) {
2654 buf
= strdup(label
);
2658 if (p
->partno
!= UINT64_MAX
) {
2659 buf
= fdisk_partname(node
, p
->partno
+1);
2663 if (p
->new_uuid_is_set
)
2665 else if (!sd_id128_is_null(p
->current_uuid
))
2666 id
= p
->current_uuid
;
2670 buf
= strdup(SD_ID128_TO_UUID_STRING(id
));
2676 *ret
= TAKE_PTR(buf
);
2680 static int context_dump_partition_bar(Context
*context
) {
2681 _cleanup_free_ Partition
**bar
= NULL
;
2682 _cleanup_free_
size_t *start_array
= NULL
;
2683 Partition
*last
= NULL
;
2687 assert_se((c
= columns()) >= 2);
2688 c
-= 2; /* We do not use the leftmost and rightmost character cell */
2690 bar
= new0(Partition
*, c
);
2694 start_array
= new(size_t, context
->n_partitions
);
2698 LIST_FOREACH(partitions
, p
, context
->partitions
)
2699 context_bar_char_process_partition(context
, bar
, c
, p
, start_array
+ j
++);
2703 for (size_t i
= 0; i
< c
; i
++) {
2708 fputs(z
? ansi_green() : ansi_yellow(), stdout
);
2709 fputs(special_glyph(SPECIAL_GLYPH_DARK_SHADE
), stdout
);
2711 fputs(ansi_normal(), stdout
);
2712 fputs(special_glyph(SPECIAL_GLYPH_LIGHT_SHADE
), stdout
);
2718 fputs(ansi_normal(), stdout
);
2721 for (size_t i
= 0; i
< context
->n_partitions
; i
++) {
2722 _cleanup_free_
char **line
= NULL
;
2724 line
= new0(char*, c
);
2729 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2730 _cleanup_free_
char *d
= NULL
;
2733 if (i
< context
->n_partitions
- j
) {
2735 if (line
[start_array
[j
-1]]) {
2738 /* Upgrade final corner to the right with a branch to the right */
2739 e
= startswith(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
2741 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), e
);
2748 d
= strdup(special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
));
2753 } else if (i
== context
->n_partitions
- j
) {
2754 _cleanup_free_
char *hint
= NULL
;
2756 (void) partition_hint(p
, context
->node
, &hint
);
2758 if (streq_ptr(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
)))
2759 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), " ", strna(hint
));
2761 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), " ", strna(hint
));
2768 free_and_replace(line
[start_array
[j
-1]], d
);
2776 fputs(line
[j
], stdout
);
2777 j
+= utf8_console_width(line
[j
]);
2786 for (j
= 0; j
< c
; j
++)
2793 static bool context_has_roothash(Context
*context
) {
2794 LIST_FOREACH(partitions
, p
, context
->partitions
)
2801 static int context_dump(Context
*context
, bool late
) {
2806 if (arg_pretty
== 0 && FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
))
2809 /* If we're outputting JSON, only dump after doing all operations so we can include the roothashes
2811 if (!late
&& !FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
))
2814 /* If we're not outputting JSON, only dump again after doing all operations if there are any
2815 * roothashes that we need to communicate to the user. */
2816 if (late
&& FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
) && !context_has_roothash(context
))
2819 r
= context_dump_partitions(context
);
2823 /* Make sure we only write the partition bar once, even if we're writing the partition table twice to
2824 * communicate roothashes. */
2825 if (FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
) && !late
) {
2828 r
= context_dump_partition_bar(context
);
2841 static bool context_changed(const Context
*context
) {
2844 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2848 if (p
->allocated_to_area
)
2851 if (p
->new_size
!= p
->current_size
)
2858 static int context_wipe_range(Context
*context
, uint64_t offset
, uint64_t size
) {
2859 _cleanup_(blkid_free_probep
) blkid_probe probe
= NULL
;
2863 assert(offset
!= UINT64_MAX
);
2864 assert(size
!= UINT64_MAX
);
2866 probe
= blkid_new_probe();
2871 r
= blkid_probe_set_device(probe
, fdisk_get_devfd(context
->fdisk_context
), offset
, size
);
2873 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to allocate device probe for wiping.");
2876 if (blkid_probe_enable_superblocks(probe
, true) < 0 ||
2877 blkid_probe_set_superblocks_flags(probe
, BLKID_SUBLKS_MAGIC
|BLKID_SUBLKS_BADCSUM
) < 0 ||
2878 blkid_probe_enable_partitions(probe
, true) < 0 ||
2879 blkid_probe_set_partitions_flags(probe
, BLKID_PARTS_MAGIC
) < 0)
2880 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to enable superblock and partition probing.");
2884 r
= blkid_do_probe(probe
);
2886 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to probe for file systems.");
2891 if (blkid_do_wipe(probe
, false) < 0)
2892 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to wipe file system signature.");
2898 static int context_wipe_partition(Context
*context
, Partition
*p
) {
2903 assert(!PARTITION_EXISTS(p
)); /* Safety check: never wipe existing partitions */
2905 assert(p
->offset
!= UINT64_MAX
);
2906 assert(p
->new_size
!= UINT64_MAX
);
2908 r
= context_wipe_range(context
, p
->offset
, p
->new_size
);
2912 log_info("Successfully wiped file system signatures from future partition %" PRIu64
".", p
->partno
);
2916 static int context_discard_range(
2925 assert(offset
!= UINT64_MAX
);
2926 assert(size
!= UINT64_MAX
);
2931 assert_se((fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
2933 if (fstat(fd
, &st
) < 0)
2936 if (S_ISREG(st
.st_mode
)) {
2937 if (fallocate(fd
, FALLOC_FL_PUNCH_HOLE
|FALLOC_FL_KEEP_SIZE
, offset
, size
) < 0) {
2938 if (ERRNO_IS_NOT_SUPPORTED(errno
))
2947 if (S_ISBLK(st
.st_mode
)) {
2948 uint64_t range
[2], end
;
2950 range
[0] = round_up_size(offset
, context
->sector_size
);
2952 if (offset
> UINT64_MAX
- size
)
2955 end
= offset
+ size
;
2956 if (end
<= range
[0])
2959 range
[1] = round_down_size(end
- range
[0], context
->sector_size
);
2963 if (ioctl(fd
, BLKDISCARD
, range
) < 0) {
2964 if (ERRNO_IS_NOT_SUPPORTED(errno
))
2976 static int context_discard_partition(Context
*context
, Partition
*p
) {
2982 assert(p
->offset
!= UINT64_MAX
);
2983 assert(p
->new_size
!= UINT64_MAX
);
2984 assert(!PARTITION_EXISTS(p
)); /* Safety check: never discard existing partitions */
2989 r
= context_discard_range(context
, p
->offset
, p
->new_size
);
2990 if (r
== -EOPNOTSUPP
) {
2991 log_info("Storage does not support discard, not discarding data in future partition %" PRIu64
".", p
->partno
);
2995 /* Let's handle this gracefully: https://bugzilla.kernel.org/show_bug.cgi?id=211167 */
2996 log_info("Block device is busy, not discarding partition %" PRIu64
" because it probably is mounted.", p
->partno
);
3000 log_info("Partition %" PRIu64
" too short for discard, skipping.", p
->partno
);
3004 return log_error_errno(r
, "Failed to discard data for future partition %" PRIu64
".", p
->partno
);
3006 log_info("Successfully discarded data from future partition %" PRIu64
".", p
->partno
);
3010 static int context_discard_gap_after(Context
*context
, Partition
*p
) {
3011 uint64_t gap
, next
= UINT64_MAX
;
3015 assert(!p
|| (p
->offset
!= UINT64_MAX
&& p
->new_size
!= UINT64_MAX
));
3021 gap
= p
->offset
+ p
->new_size
;
3023 gap
= context
->start
;
3025 LIST_FOREACH(partitions
, q
, context
->partitions
) {
3029 assert(q
->offset
!= UINT64_MAX
);
3030 assert(q
->new_size
!= UINT64_MAX
);
3032 if (q
->offset
< gap
)
3035 if (next
== UINT64_MAX
|| q
->offset
< next
)
3039 if (next
== UINT64_MAX
) {
3040 next
= context
->end
;
3042 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
3045 assert(next
>= gap
);
3046 r
= context_discard_range(context
, gap
, next
- gap
);
3047 if (r
== -EOPNOTSUPP
) {
3049 log_info("Storage does not support discard, not discarding gap after partition %" PRIu64
".", p
->partno
);
3051 log_info("Storage does not support discard, not discarding gap at beginning of disk.");
3054 if (r
== 0) /* Too short */
3058 return log_error_errno(r
, "Failed to discard gap after partition %" PRIu64
".", p
->partno
);
3060 return log_error_errno(r
, "Failed to discard gap at beginning of disk.");
3064 log_info("Successfully discarded gap after partition %" PRIu64
".", p
->partno
);
3066 log_info("Successfully discarded gap at beginning of disk.");
3071 static int context_wipe_and_discard(Context
*context
) {
3076 /* Wipe and discard the contents of all partitions we are about to create. We skip the discarding if
3077 * we were supposed to start from scratch anyway, as in that case we just discard the whole block
3078 * device in one go early on. */
3080 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3082 if (!p
->allocated_to_area
)
3085 if (partition_defer(p
))
3088 r
= context_wipe_partition(context
, p
);
3092 if (!context
->from_scratch
) {
3093 r
= context_discard_partition(context
, p
);
3097 r
= context_discard_gap_after(context
, p
);
3103 if (!context
->from_scratch
) {
3104 r
= context_discard_gap_after(context
, NULL
);
3119 static int partition_target_fd(PartitionTarget
*t
) {
3121 assert(t
->loop
|| t
->fd
>= 0 || t
->whole_fd
>= 0);
3122 return t
->loop
? t
->loop
->fd
: t
->fd
>= 0 ? t
->fd
: t
->whole_fd
;
3125 static const char* partition_target_path(PartitionTarget
*t
) {
3127 assert(t
->loop
|| t
->path
);
3128 return t
->loop
? t
->loop
->node
: t
->path
;
3131 static PartitionTarget
*partition_target_free(PartitionTarget
*t
) {
3135 loop_device_unref(t
->loop
);
3137 unlink_and_free(t
->path
);
3142 DEFINE_TRIVIAL_CLEANUP_FUNC(PartitionTarget
*, partition_target_free
);
3144 static int prepare_temporary_file(PartitionTarget
*t
, uint64_t size
) {
3145 _cleanup_(unlink_and_freep
) char *temp
= NULL
;
3146 _cleanup_close_
int fd
= -EBADF
;
3152 r
= var_tmp_dir(&vt
);
3154 return log_error_errno(r
, "Could not determine temporary directory: %m");
3156 temp
= path_join(vt
, "repart-XXXXXX");
3160 fd
= mkostemp_safe(temp
);
3162 return log_error_errno(fd
, "Failed to create temporary file: %m");
3164 if (ftruncate(fd
, size
) < 0)
3165 return log_error_errno(errno
, "Failed to truncate temporary file to %s: %m",
3166 FORMAT_BYTES(size
));
3168 t
->fd
= TAKE_FD(fd
);
3169 t
->path
= TAKE_PTR(temp
);
3174 static int partition_target_prepare(
3179 PartitionTarget
**ret
) {
3181 _cleanup_(partition_target_freep
) PartitionTarget
*t
= NULL
;
3182 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
3189 assert_se((whole_fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
3191 t
= new(PartitionTarget
, 1);
3194 *t
= (PartitionTarget
) {
3200 if (lseek(whole_fd
, p
->offset
, SEEK_SET
) == (off_t
) -1)
3201 return log_error_errno(errno
, "Failed to seek to partition offset: %m");
3203 t
->whole_fd
= whole_fd
;
3208 /* Loopback block devices are not only useful to turn regular files into block devices, but
3209 * also to cut out sections of block devices into new block devices. */
3211 r
= loop_device_make(whole_fd
, O_RDWR
, p
->offset
, size
, 0, 0, LOCK_EX
, &d
);
3212 if (r
< 0 && r
!= -ENOENT
&& !ERRNO_IS_PRIVILEGE(r
))
3213 return log_error_errno(r
, "Failed to make loopback device of future partition %" PRIu64
": %m", p
->partno
);
3215 t
->loop
= TAKE_PTR(d
);
3220 /* If we can't allocate a loop device, let's write to a regular file that we copy into the final
3221 * image so we can run in containers and without needing root privileges. On filesystems with
3222 * reflinking support, we can take advantage of this and just reflink the result into the image.
3225 log_debug_errno(r
, "No access to loop devices, falling back to a regular file");
3227 r
= prepare_temporary_file(t
, size
);
3236 static int partition_target_grow(PartitionTarget
*t
, uint64_t size
) {
3242 r
= loop_device_refresh_size(t
->loop
, UINT64_MAX
, size
);
3244 return log_error_errno(r
, "Failed to refresh loopback device size: %m");
3245 } else if (t
->fd
>= 0) {
3246 if (ftruncate(t
->fd
, size
) < 0)
3247 return log_error_errno(errno
, "Failed to grow '%s' to %s by truncation: %m",
3248 t
->path
, FORMAT_BYTES(size
));
3254 static int partition_target_sync(Context
*context
, Partition
*p
, PartitionTarget
*t
) {
3261 assert_se((whole_fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
3264 r
= loop_device_sync(t
->loop
);
3266 return log_error_errno(r
, "Failed to sync loopback device: %m");
3267 } else if (t
->fd
>= 0) {
3270 if (lseek(whole_fd
, p
->offset
, SEEK_SET
) == (off_t
) -1)
3271 return log_error_errno(errno
, "Failed to seek to partition offset: %m");
3273 if (lseek(t
->fd
, 0, SEEK_SET
) == (off_t
) -1)
3274 return log_error_errno(errno
, "Failed to seek to start of temporary file: %m");
3276 if (fstat(t
->fd
, &st
) < 0)
3277 return log_error_errno(errno
, "Failed to stat temporary file: %m");
3279 if (st
.st_size
> (off_t
) p
->new_size
)
3280 return log_error_errno(SYNTHETIC_ERRNO(ENOSPC
),
3281 "Partition %" PRIu64
"'s contents (%s) don't fit in the partition (%s)",
3282 p
->partno
, FORMAT_BYTES(st
.st_size
), FORMAT_BYTES(p
->new_size
));
3284 r
= copy_bytes(t
->fd
, whole_fd
, UINT64_MAX
, COPY_REFLINK
|COPY_HOLES
|COPY_FSYNC
);
3286 return log_error_errno(r
, "Failed to copy bytes to partition: %m");
3288 if (fsync(t
->whole_fd
) < 0)
3289 return log_error_errno(errno
, "Failed to sync changes: %m");
3295 static int partition_encrypt(Context
*context
, Partition
*p
, const char *node
) {
3296 #if HAVE_LIBCRYPTSETUP && HAVE_CRYPT_SET_DATA_OFFSET && HAVE_CRYPT_REENCRYPT_INIT_BY_PASSPHRASE && HAVE_CRYPT_REENCRYPT
3297 struct crypt_params_luks2 luks_params
= {
3298 .label
= strempty(ASSERT_PTR(p
)->new_label
),
3299 .sector_size
= ASSERT_PTR(context
)->sector_size
,
3300 .data_device
= node
,
3302 struct crypt_params_reencrypt reencrypt_params
= {
3303 .mode
= CRYPT_REENCRYPT_ENCRYPT
,
3304 .direction
= CRYPT_REENCRYPT_BACKWARD
,
3305 .resilience
= "datashift",
3306 .data_shift
= LUKS2_METADATA_SIZE
/ 512,
3307 .luks2
= &luks_params
,
3308 .flags
= CRYPT_REENCRYPT_INITIALIZE_ONLY
|CRYPT_REENCRYPT_MOVE_FIRST_SEGMENT
,
3310 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
3311 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
3312 _cleanup_fclose_
FILE *h
= NULL
;
3313 _cleanup_free_
char *hp
= NULL
;
3314 const char *passphrase
= NULL
;
3315 size_t passphrase_size
= 0;
3321 assert(p
->encrypt
!= ENCRYPT_OFF
);
3323 r
= dlopen_cryptsetup();
3325 return log_error_errno(r
, "libcryptsetup not found, cannot encrypt: %m");
3327 log_info("Encrypting future partition %" PRIu64
"...", p
->partno
);
3329 r
= var_tmp_dir(&vt
);
3331 return log_error_errno(r
, "Failed to determine temporary files directory: %m");
3333 r
= fopen_temporary_child(vt
, &h
, &hp
);
3335 return log_error_errno(r
, "Failed to create temporary LUKS header file: %m");
3337 /* Weird cryptsetup requirement which requires the header file to be the size of at least one sector. */
3338 r
= ftruncate(fileno(h
), context
->sector_size
);
3340 return log_error_errno(r
, "Failed to grow temporary LUKS header file: %m");
3342 r
= sym_crypt_init(&cd
, hp
);
3344 return log_error_errno(r
, "Failed to allocate libcryptsetup context for %s: %m", hp
);
3346 cryptsetup_enable_logging(cd
);
3348 /* Disable kernel keyring usage by libcryptsetup as a workaround for
3349 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/273. This makes sure that we can do
3350 * offline encryption even when repart is running in a container. */
3351 r
= sym_crypt_volume_key_keyring(cd
, false);
3353 return log_error_errno(r
, "Failed to disable kernel keyring: %m");
3355 r
= sym_crypt_metadata_locking(cd
, false);
3357 return log_error_errno(r
, "Failed to disable metadata locking: %m");
3359 r
= sym_crypt_set_data_offset(cd
, LUKS2_METADATA_SIZE
/ 512);
3361 return log_error_errno(r
, "Failed to set data offset: %m");
3363 r
= sym_crypt_format(cd
,
3367 SD_ID128_TO_UUID_STRING(p
->luks_uuid
),
3372 return log_error_errno(r
, "Failed to LUKS2 format future partition: %m");
3374 if (IN_SET(p
->encrypt
, ENCRYPT_KEY_FILE
, ENCRYPT_KEY_FILE_TPM2
)) {
3375 r
= sym_crypt_keyslot_add_by_volume_key(
3383 return log_error_errno(r
, "Failed to add LUKS2 key: %m");
3385 passphrase
= strempty(arg_key
);
3386 passphrase_size
= arg_key_size
;
3389 if (IN_SET(p
->encrypt
, ENCRYPT_TPM2
, ENCRYPT_KEY_FILE_TPM2
)) {
3391 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
3392 _cleanup_(erase_and_freep
) void *secret
= NULL
;
3393 _cleanup_free_
void *pubkey
= NULL
;
3394 _cleanup_free_
void *blob
= NULL
, *hash
= NULL
, *srk_buf
= NULL
;
3395 size_t secret_size
, blob_size
, hash_size
, pubkey_size
= 0, srk_buf_size
= 0;
3396 ssize_t base64_encoded_size
;
3397 uint16_t pcr_bank
, primary_alg
;
3400 if (arg_tpm2_public_key_pcr_mask
!= 0) {
3401 r
= tpm2_load_pcr_public_key(arg_tpm2_public_key
, &pubkey
, &pubkey_size
);
3403 if (arg_tpm2_public_key
|| r
!= -ENOENT
)
3404 return log_error_errno(r
, "Failed read TPM PCR public key: %m");
3406 log_debug_errno(r
, "Failed to read TPM2 PCR public key, proceeding without: %m");
3407 arg_tpm2_public_key_pcr_mask
= 0;
3411 r
= tpm2_seal(arg_tpm2_device
,
3413 pubkey
, pubkey_size
,
3414 arg_tpm2_public_key_pcr_mask
,
3416 &secret
, &secret_size
,
3424 return log_error_errno(r
, "Failed to seal to TPM2: %m");
3426 base64_encoded_size
= base64mem(secret
, secret_size
, &base64_encoded
);
3427 if (base64_encoded_size
< 0)
3428 return log_error_errno(base64_encoded_size
, "Failed to base64 encode secret key: %m");
3430 r
= cryptsetup_set_minimal_pbkdf(cd
);
3432 return log_error_errno(r
, "Failed to set minimal PBKDF: %m");
3434 keyslot
= sym_crypt_keyslot_add_by_volume_key(
3440 base64_encoded_size
);
3442 return log_error_errno(keyslot
, "Failed to add new TPM2 key: %m");
3444 r
= tpm2_make_luks2_json(
3448 pubkey
, pubkey_size
,
3449 arg_tpm2_public_key_pcr_mask
,
3453 NULL
, 0, /* no salt because tpm2_seal has no pin */
3454 srk_buf
, srk_buf_size
,
3458 return log_error_errno(r
, "Failed to prepare TPM2 JSON token object: %m");
3460 r
= cryptsetup_add_token_json(cd
, v
);
3462 return log_error_errno(r
, "Failed to add TPM2 JSON token to LUKS2 header: %m");
3464 passphrase
= base64_encoded
;
3465 passphrase_size
= strlen(base64_encoded
);
3467 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3468 "Support for TPM2 enrollment not enabled.");
3472 r
= sym_crypt_reencrypt_init_by_passphrase(
3479 sym_crypt_get_cipher(cd
),
3480 sym_crypt_get_cipher_mode(cd
),
3483 return log_error_errno(r
, "Failed to prepare for reencryption: %m");
3485 /* crypt_reencrypt_init_by_passphrase() doesn't actually put the LUKS header at the front, we have
3486 * to do that ourselves. */
3491 r
= sym_crypt_init(&cd
, node
);
3493 return log_error_errno(r
, "Failed to allocate libcryptsetup context for %s: %m", node
);
3495 r
= sym_crypt_header_restore(cd
, CRYPT_LUKS2
, hp
);
3497 return log_error_errno(r
, "Failed to place new LUKS header at head of %s: %m", node
);
3499 reencrypt_params
.flags
&= ~CRYPT_REENCRYPT_INITIALIZE_ONLY
;
3501 r
= sym_crypt_reencrypt_init_by_passphrase(
3512 return log_error_errno(r
, "Failed to load reencryption context: %m");
3514 r
= sym_crypt_reencrypt(cd
, NULL
);
3516 return log_error_errno(r
, "Failed to encrypt %s: %m", node
);
3518 log_info("Successfully encrypted future partition %" PRIu64
".", p
->partno
);
3522 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3523 "libcryptsetup is not supported or is missing required symbols, cannot encrypt: %m");
3527 static int partition_format_verity_hash(
3530 const char *data_node
) {
3532 #if HAVE_LIBCRYPTSETUP
3534 _cleanup_(partition_target_freep
) PartitionTarget
*t
= NULL
;
3535 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
3536 _cleanup_free_
uint8_t *rh
= NULL
;
3547 if (PARTITION_EXISTS(p
)) /* Never format existing partitions */
3550 if (p
->verity
!= VERITY_HASH
)
3553 if (partition_defer(p
))
3556 assert_se(dp
= p
->siblings
[VERITY_DATA
]);
3557 assert(!dp
->dropped
);
3559 r
= dlopen_cryptsetup();
3561 return log_error_errno(r
, "libcryptsetup not found, cannot setup verity: %m");
3563 r
= partition_target_prepare(context
, p
, p
->new_size
, /*need_path=*/ true, &t
);
3567 r
= sym_crypt_init(&cd
, partition_target_path(t
));
3569 return log_error_errno(r
, "Failed to allocate libcryptsetup context: %m");
3571 cryptsetup_enable_logging(cd
);
3573 r
= sym_crypt_format(
3574 cd
, CRYPT_VERITY
, NULL
, NULL
, NULL
, NULL
, 0,
3575 &(struct crypt_params_verity
){
3576 .data_device
= data_node
,
3577 .flags
= CRYPT_VERITY_CREATE_HASH
,
3578 .hash_name
= "sha256",
3580 .data_block_size
= context
->sector_size
,
3581 .hash_block_size
= context
->sector_size
,
3585 /* libcryptsetup reports non-descriptive EIO errors for every I/O failure. Luckily, it
3586 * doesn't clobber errno so let's check for ENOSPC so we can report a better error if the
3587 * partition is too small. */
3588 if (r
== -EIO
&& errno
== ENOSPC
)
3589 return log_error_errno(errno
,
3590 "Verity hash data does not fit in partition %"PRIu64
" with size %s",
3591 p
->partno
, FORMAT_BYTES(p
->new_size
));
3593 return log_error_errno(r
, "Failed to setup verity hash data: %m");
3596 r
= partition_target_sync(context
, p
, t
);
3600 r
= sym_crypt_get_volume_key_size(cd
);
3602 return log_error_errno(r
, "Failed to determine verity root hash size: %m");
3609 r
= sym_crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, (char *) rh
, &rhs
, NULL
, 0);
3611 return log_error_errno(r
, "Failed to get verity root hash: %m");
3613 assert(rhs
>= sizeof(sd_id128_t
) * 2);
3615 if (!dp
->new_uuid_is_set
) {
3616 memcpy_safe(dp
->new_uuid
.bytes
, rh
, sizeof(sd_id128_t
));
3617 dp
->new_uuid_is_set
= true;
3620 if (!p
->new_uuid_is_set
) {
3621 memcpy_safe(p
->new_uuid
.bytes
, rh
+ rhs
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
3622 p
->new_uuid_is_set
= true;
3625 p
->roothash
= TAKE_PTR(rh
);
3626 p
->roothash_size
= rhs
;
3630 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "libcryptsetup is not supported, cannot setup verity hashes: %m");
3634 static int sign_verity_roothash(
3635 const uint8_t *roothash
,
3636 size_t roothash_size
,
3637 uint8_t **ret_signature
,
3638 size_t *ret_signature_size
) {
3641 _cleanup_(BIO_freep
) BIO
*rb
= NULL
;
3642 _cleanup_(PKCS7_freep
) PKCS7
*p7
= NULL
;
3643 _cleanup_free_
char *hex
= NULL
;
3644 _cleanup_free_
uint8_t *sig
= NULL
;
3648 assert(roothash_size
> 0);
3649 assert(ret_signature
);
3650 assert(ret_signature_size
);
3652 hex
= hexmem(roothash
, roothash_size
);
3656 rb
= BIO_new_mem_buf(hex
, -1);
3660 p7
= PKCS7_sign(arg_certificate
, arg_private_key
, NULL
, rb
, PKCS7_DETACHED
|PKCS7_NOATTR
|PKCS7_BINARY
);
3662 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to calculate PKCS7 signature: %s",
3663 ERR_error_string(ERR_get_error(), NULL
));
3665 sigsz
= i2d_PKCS7(p7
, &sig
);
3667 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to convert PKCS7 signature to DER: %s",
3668 ERR_error_string(ERR_get_error(), NULL
));
3670 *ret_signature
= TAKE_PTR(sig
);
3671 *ret_signature_size
= sigsz
;
3675 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "openssl is not supported, cannot setup verity signature: %m");
3679 static int partition_format_verity_sig(Context
*context
, Partition
*p
) {
3680 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
3681 _cleanup_free_
uint8_t *sig
= NULL
;
3682 _cleanup_free_
char *text
= NULL
;
3684 uint8_t fp
[X509_FINGERPRINT_SIZE
];
3685 size_t sigsz
= 0; /* avoid false maybe-uninitialized warning */
3688 assert(p
->verity
== VERITY_SIG
);
3693 if (PARTITION_EXISTS(p
))
3696 if (partition_defer(p
))
3699 assert_se(hp
= p
->siblings
[VERITY_HASH
]);
3700 assert(!hp
->dropped
);
3702 assert(arg_certificate
);
3704 assert_se((whole_fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
3706 r
= sign_verity_roothash(hp
->roothash
, hp
->roothash_size
, &sig
, &sigsz
);
3710 r
= x509_fingerprint(arg_certificate
, fp
);
3712 return log_error_errno(r
, "Unable to calculate X509 certificate fingerprint: %m");
3716 JSON_BUILD_PAIR("rootHash", JSON_BUILD_HEX(hp
->roothash
, hp
->roothash_size
)),
3718 "certificateFingerprint",
3719 JSON_BUILD_HEX(fp
, sizeof(fp
))
3721 JSON_BUILD_PAIR("signature", JSON_BUILD_BASE64(sig
, sigsz
))
3725 return log_error_errno(r
, "Failed to build JSON object: %m");
3727 r
= json_variant_format(v
, 0, &text
);
3729 return log_error_errno(r
, "Failed to format JSON object: %m");
3731 r
= strgrowpad0(&text
, p
->new_size
);
3733 return log_error_errno(r
, "Failed to pad string to %s", FORMAT_BYTES(p
->new_size
));
3735 if (lseek(whole_fd
, p
->offset
, SEEK_SET
) == (off_t
) -1)
3736 return log_error_errno(errno
, "Failed to seek to partition offset: %m");
3738 r
= loop_write(whole_fd
, text
, p
->new_size
, /*do_poll=*/ false);
3740 return log_error_errno(r
, "Failed to write verity signature to partition: %m");
3742 if (fsync(whole_fd
) < 0)
3743 return log_error_errno(errno
, "Failed to synchronize verity signature JSON: %m");
3748 static int context_copy_blocks(Context
*context
) {
3753 /* Copy in file systems on the block level */
3755 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3756 _cleanup_(partition_target_freep
) PartitionTarget
*t
= NULL
;
3758 if (p
->copy_blocks_fd
< 0)
3764 if (PARTITION_EXISTS(p
)) /* Never copy over existing partitions */
3767 if (partition_defer(p
))
3770 assert(p
->new_size
!= UINT64_MAX
);
3771 assert(p
->copy_blocks_size
!= UINT64_MAX
);
3772 assert(p
->new_size
>= p
->copy_blocks_size
+ (p
->encrypt
!= ENCRYPT_OFF
? LUKS2_METADATA_KEEP_FREE
: 0));
3774 r
= partition_target_prepare(context
, p
, p
->new_size
,
3775 /*need_path=*/ p
->encrypt
!= ENCRYPT_OFF
|| p
->siblings
[VERITY_HASH
],
3780 log_info("Copying in '%s' (%s) on block level into future partition %" PRIu64
".",
3781 p
->copy_blocks_path
, FORMAT_BYTES(p
->copy_blocks_size
), p
->partno
);
3783 r
= copy_bytes(p
->copy_blocks_fd
, partition_target_fd(t
), p
->copy_blocks_size
, COPY_REFLINK
);
3785 return log_error_errno(r
, "Failed to copy in data from '%s': %m", p
->copy_blocks_path
);
3787 if (p
->encrypt
!= ENCRYPT_OFF
) {
3788 r
= partition_encrypt(context
, p
, partition_target_path(t
));
3793 r
= partition_target_sync(context
, p
, t
);
3797 log_info("Copying in of '%s' on block level completed.", p
->copy_blocks_path
);
3799 if (p
->siblings
[VERITY_HASH
]) {
3800 r
= partition_format_verity_hash(context
, p
->siblings
[VERITY_HASH
],
3801 partition_target_path(t
));
3806 if (p
->siblings
[VERITY_SIG
]) {
3807 r
= partition_format_verity_sig(context
, p
->siblings
[VERITY_SIG
]);
3816 static int do_copy_files(Partition
*p
, const char *root
, Hashmap
*denylist
) {
3822 /* copy_tree_at() automatically copies the permissions of source directories to target directories if
3823 * it created them. However, the root directory is created by us, so we have to manually take care
3824 * that it is initialized. We use the first source directory targeting "/" as the metadata source for
3825 * the root directory. */
3826 STRV_FOREACH_PAIR(source
, target
, p
->copy_files
) {
3827 _cleanup_close_
int rfd
= -EBADF
, sfd
= -EBADF
;
3829 if (!path_equal(*target
, "/"))
3832 rfd
= open(root
, O_DIRECTORY
|O_CLOEXEC
|O_NOFOLLOW
);
3836 sfd
= chase_and_open(*source
, arg_root
, CHASE_PREFIX_ROOT
, O_PATH
|O_DIRECTORY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
3838 return log_error_errno(sfd
, "Failed to open source file '%s%s': %m", strempty(arg_root
), *source
);
3840 (void) copy_xattr(sfd
, NULL
, rfd
, NULL
, COPY_ALL_XATTRS
);
3841 (void) copy_access(sfd
, rfd
);
3842 (void) copy_times(sfd
, rfd
, 0);
3847 STRV_FOREACH_PAIR(source
, target
, p
->copy_files
) {
3848 _cleanup_close_
int sfd
= -EBADF
, pfd
= -EBADF
, tfd
= -EBADF
;
3850 sfd
= chase_and_open(*source
, arg_root
, CHASE_PREFIX_ROOT
, O_CLOEXEC
|O_NOCTTY
, NULL
);
3852 return log_error_errno(sfd
, "Failed to open source file '%s%s': %m", strempty(arg_root
), *source
);
3854 r
= fd_verify_regular(sfd
);
3857 return log_error_errno(r
, "Failed to check type of source file '%s': %m", *source
);
3859 /* We are looking at a directory */
3860 tfd
= chase_and_open(*target
, root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, NULL
);
3862 _cleanup_free_
char *dn
= NULL
, *fn
= NULL
;
3865 return log_error_errno(tfd
, "Failed to open target directory '%s': %m", *target
);
3867 r
= path_extract_filename(*target
, &fn
);
3869 return log_error_errno(r
, "Failed to extract filename from '%s': %m", *target
);
3871 r
= path_extract_directory(*target
, &dn
);
3873 return log_error_errno(r
, "Failed to extract directory from '%s': %m", *target
);
3875 r
= mkdir_p_root(root
, dn
, UID_INVALID
, GID_INVALID
, 0755);
3877 return log_error_errno(r
, "Failed to create parent directory '%s': %m", dn
);
3879 pfd
= chase_and_open(dn
, root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, NULL
);
3881 return log_error_errno(pfd
, "Failed to open parent directory of target: %m");
3886 UID_INVALID
, GID_INVALID
,
3887 COPY_REFLINK
|COPY_HOLES
|COPY_MERGE
|COPY_REPLACE
|COPY_SIGINT
|COPY_HARDLINKS
|COPY_ALL_XATTRS
|COPY_GRACEFUL_WARN
,
3893 UID_INVALID
, GID_INVALID
,
3894 COPY_REFLINK
|COPY_HOLES
|COPY_MERGE
|COPY_REPLACE
|COPY_SIGINT
|COPY_HARDLINKS
|COPY_ALL_XATTRS
|COPY_GRACEFUL_WARN
,
3897 return log_error_errno(r
, "Failed to copy '%s%s' to '%s%s': %m",
3898 strempty(arg_root
), *source
, strempty(root
), *target
);
3900 _cleanup_free_
char *dn
= NULL
, *fn
= NULL
;
3902 /* We are looking at a regular file */
3904 r
= path_extract_filename(*target
, &fn
);
3905 if (r
== -EADDRNOTAVAIL
|| r
== O_DIRECTORY
)
3906 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
),
3907 "Target path '%s' refers to a directory, but source path '%s' refers to regular file, can't copy.", *target
, *source
);
3909 return log_error_errno(r
, "Failed to extract filename from '%s': %m", *target
);
3911 r
= path_extract_directory(*target
, &dn
);
3913 return log_error_errno(r
, "Failed to extract directory from '%s': %m", *target
);
3915 r
= mkdir_p_root(root
, dn
, UID_INVALID
, GID_INVALID
, 0755);
3917 return log_error_errno(r
, "Failed to create parent directory: %m");
3919 pfd
= chase_and_open(dn
, root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, NULL
);
3921 return log_error_errno(pfd
, "Failed to open parent directory of target: %m");
3923 tfd
= openat(pfd
, fn
, O_CREAT
|O_EXCL
|O_WRONLY
|O_CLOEXEC
, 0700);
3925 return log_error_errno(errno
, "Failed to create target file '%s': %m", *target
);
3927 r
= copy_bytes(sfd
, tfd
, UINT64_MAX
, COPY_REFLINK
|COPY_HOLES
|COPY_SIGINT
);
3929 return log_error_errno(r
, "Failed to copy '%s' to '%s%s': %m", *source
, strempty(arg_root
), *target
);
3931 (void) copy_xattr(sfd
, NULL
, tfd
, NULL
, COPY_ALL_XATTRS
);
3932 (void) copy_access(sfd
, tfd
);
3933 (void) copy_times(sfd
, tfd
, 0);
3940 static int do_make_directories(Partition
*p
, const char *root
) {
3946 STRV_FOREACH(d
, p
->make_directories
) {
3948 r
= mkdir_p_root(root
, *d
, UID_INVALID
, GID_INVALID
, 0755);
3950 return log_error_errno(r
, "Failed to create directory '%s' in file system: %m", *d
);
3956 static bool partition_needs_populate(Partition
*p
) {
3958 return !strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
);
3961 static int partition_populate_directory(Partition
*p
, Hashmap
*denylist
, char **ret
) {
3962 _cleanup_(rm_rf_physical_and_freep
) char *root
= NULL
;
3968 log_info("Populating %s filesystem.", p
->format
);
3970 r
= var_tmp_dir(&vt
);
3972 return log_error_errno(r
, "Could not determine temporary directory: %m");
3974 r
= tempfn_random_child(vt
, "repart", &root
);
3976 return log_error_errno(r
, "Failed to generate temporary directory: %m");
3978 r
= mkdir(root
, 0755);
3980 return log_error_errno(errno
, "Failed to create temporary directory: %m");
3982 r
= do_copy_files(p
, root
, denylist
);
3986 r
= do_make_directories(p
, root
);
3990 log_info("Successfully populated %s filesystem.", p
->format
);
3992 *ret
= TAKE_PTR(root
);
3996 static int partition_populate_filesystem(Partition
*p
, const char *node
, Hashmap
*denylist
) {
4002 log_info("Populating %s filesystem.", p
->format
);
4004 /* We copy in a child process, since we have to mount the fs for that, and we don't want that fs to
4005 * appear in the host namespace. Hence we fork a child that has its own file system namespace and
4006 * detached mount propagation. */
4008 r
= safe_fork("(sd-copy)", FORK_DEATHSIG
|FORK_LOG
|FORK_WAIT
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, NULL
);
4012 static const char fs
[] = "/run/systemd/mount-root";
4013 /* This is a child process with its own mount namespace and propagation to host turned off */
4015 r
= mkdir_p(fs
, 0700);
4017 log_error_errno(r
, "Failed to create mount point: %m");
4018 _exit(EXIT_FAILURE
);
4021 if (mount_nofollow_verbose(LOG_ERR
, node
, fs
, p
->format
, MS_NOATIME
|MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
) < 0)
4022 _exit(EXIT_FAILURE
);
4024 if (do_copy_files(p
, fs
, denylist
) < 0)
4025 _exit(EXIT_FAILURE
);
4027 if (do_make_directories(p
, fs
) < 0)
4028 _exit(EXIT_FAILURE
);
4030 r
= syncfs_path(AT_FDCWD
, fs
);
4032 log_error_errno(r
, "Failed to synchronize written files: %m");
4033 _exit(EXIT_FAILURE
);
4036 _exit(EXIT_SUCCESS
);
4039 log_info("Successfully populated %s filesystem.", p
->format
);
4043 static int add_exclude_path(const char *path
, Hashmap
**denylist
, DenyType type
) {
4044 _cleanup_free_
struct stat
*st
= NULL
;
4050 st
= new(struct stat
, 1);
4054 r
= chase_and_stat(path
, arg_root
, CHASE_PREFIX_ROOT
, NULL
, st
);
4058 return log_error_errno(r
, "Failed to stat source file '%s%s': %m",
4059 strempty(arg_root
), path
);
4061 if (hashmap_contains(*denylist
, st
))
4064 if (hashmap_ensure_put(denylist
, &inode_hash_ops
, st
, INT_TO_PTR(type
)) < 0)
4072 static int make_copy_files_denylist(Context
*context
, const Partition
*p
, Hashmap
**ret
) {
4073 _cleanup_hashmap_free_ Hashmap
*denylist
= NULL
;
4080 LIST_FOREACH(partitions
, q
, context
->partitions
) {
4084 const char *sources
= gpt_partition_type_mountpoint_nulstr(q
->type
);
4088 NULSTR_FOREACH(s
, sources
) {
4089 /* Exclude the children of partition mount points so that the nested partition mount
4090 * point itself still ends up in the upper partition. */
4092 r
= add_exclude_path(s
, &denylist
, DENY_CONTENTS
);
4098 FOREACH_STRING(s
, "proc", "sys", "dev", "tmp", "run", "var/tmp") {
4099 r
= add_exclude_path(s
, &denylist
, DENY_CONTENTS
);
4104 STRV_FOREACH(e
, p
->exclude_files
) {
4105 r
= add_exclude_path(*e
, &denylist
, endswith(*e
, "/") ? DENY_CONTENTS
: DENY_INODE
);
4110 *ret
= TAKE_PTR(denylist
);
4114 static int context_mkfs(Context
*context
) {
4119 /* Make a file system */
4121 LIST_FOREACH(partitions
, p
, context
->partitions
) {
4122 _cleanup_hashmap_free_ Hashmap
*denylist
= NULL
;
4123 _cleanup_(rm_rf_physical_and_freep
) char *root
= NULL
;
4124 _cleanup_(partition_target_freep
) PartitionTarget
*t
= NULL
;
4125 _cleanup_strv_free_
char **extra_mkfs_options
= NULL
;
4130 if (PARTITION_EXISTS(p
)) /* Never format existing partitions */
4136 /* Minimized partitions will use the copy blocks logic so let's make sure to skip those here. */
4137 if (p
->copy_blocks_fd
>= 0)
4140 if (partition_defer(p
))
4143 assert(p
->offset
!= UINT64_MAX
);
4144 assert(p
->new_size
!= UINT64_MAX
);
4145 assert(p
->new_size
>= (p
->encrypt
!= ENCRYPT_OFF
? LUKS2_METADATA_KEEP_FREE
: 0));
4147 r
= make_copy_files_denylist(context
, p
, &denylist
);
4151 /* If we're doing encryption, we make sure we keep free space at the end which is required
4152 * for cryptsetup's offline encryption. */
4153 r
= partition_target_prepare(context
, p
,
4154 p
->new_size
- (p
->encrypt
!= ENCRYPT_OFF
? LUKS2_METADATA_KEEP_FREE
: 0),
4155 /*need_path=*/ true,
4160 log_info("Formatting future partition %" PRIu64
".", p
->partno
);
4162 /* If we're not writing to a loop device or if we're populating a read-only filesystem, we
4163 * have to populate using the filesystem's mkfs's --root (or equivalent) option. To do that,
4164 * we need to set up the final directory tree beforehand. */
4166 if (partition_needs_populate(p
) && (!t
->loop
|| fstype_is_ro(p
->format
))) {
4167 if (!mkfs_supports_root_option(p
->format
))
4168 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
),
4169 "Loop device access is required to populate %s filesystems.",
4172 r
= partition_populate_directory(p
, denylist
, &root
);
4177 r
= mkfs_options_from_env("REPART", p
->format
, &extra_mkfs_options
);
4179 return log_error_errno(r
,
4180 "Failed to determine mkfs command line options for '%s': %m",
4183 r
= make_filesystem(partition_target_path(t
), p
->format
, strempty(p
->new_label
), root
,
4184 p
->fs_uuid
, arg_discard
, context
->sector_size
, extra_mkfs_options
);
4188 log_info("Successfully formatted future partition %" PRIu64
".", p
->partno
);
4190 /* If we're writing to a loop device, we can now mount the empty filesystem and populate it. */
4191 if (partition_needs_populate(p
) && !root
) {
4194 r
= partition_populate_filesystem(p
, t
->loop
->node
, denylist
);
4199 if (p
->encrypt
!= ENCRYPT_OFF
) {
4200 r
= partition_target_grow(t
, p
->new_size
);
4204 r
= partition_encrypt(context
, p
, partition_target_path(t
));
4206 return log_error_errno(r
, "Failed to encrypt device: %m");
4209 /* Note that we always sync explicitly here, since mkfs.fat doesn't do that on its own, and
4210 * if we don't sync before detaching a block device the in-flight sectors possibly won't hit
4213 r
= partition_target_sync(context
, p
, t
);
4217 if (p
->siblings
[VERITY_HASH
]) {
4218 r
= partition_format_verity_hash(context
, p
->siblings
[VERITY_HASH
],
4219 partition_target_path(t
));
4224 if (p
->siblings
[VERITY_SIG
]) {
4225 r
= partition_format_verity_sig(context
, p
->siblings
[VERITY_SIG
]);
4234 static int parse_x509_certificate(const char *certificate
, size_t certificate_size
, X509
**ret
) {
4236 _cleanup_(X509_freep
) X509
*cert
= NULL
;
4237 _cleanup_(BIO_freep
) BIO
*cb
= NULL
;
4239 assert(certificate
);
4240 assert(certificate_size
> 0);
4243 cb
= BIO_new_mem_buf(certificate
, certificate_size
);
4247 cert
= PEM_read_bio_X509(cb
, NULL
, NULL
, NULL
);
4249 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Failed to parse X.509 certificate: %s",
4250 ERR_error_string(ERR_get_error(), NULL
));
4253 *ret
= TAKE_PTR(cert
);
4257 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "openssl is not supported, cannot parse X509 certificate.");
4261 static int parse_private_key(const char *key
, size_t key_size
, EVP_PKEY
**ret
) {
4263 _cleanup_(BIO_freep
) BIO
*kb
= NULL
;
4264 _cleanup_(EVP_PKEY_freep
) EVP_PKEY
*pk
= NULL
;
4267 assert(key_size
> 0);
4270 kb
= BIO_new_mem_buf(key
, key_size
);
4274 pk
= PEM_read_bio_PrivateKey(kb
, NULL
, NULL
, NULL
);
4276 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse PEM private key: %s",
4277 ERR_error_string(ERR_get_error(), NULL
));
4280 *ret
= TAKE_PTR(pk
);
4284 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "openssl is not supported, cannot parse private key.");
4288 static int partition_acquire_uuid(Context
*context
, Partition
*p
, sd_id128_t
*ret
) {
4290 sd_id128_t type_uuid
;
4292 } _packed_ plaintext
= {};
4294 uint8_t md
[SHA256_DIGEST_SIZE
];
4305 /* Calculate a good UUID for the indicated partition. We want a certain degree of reproducibility,
4306 * hence we won't generate the UUIDs randomly. Instead we use a cryptographic hash (precisely:
4307 * HMAC-SHA256) to derive them from a single seed. The seed is generally the machine ID of the
4308 * installation we are processing, but if random behaviour is desired can be random, too. We use the
4309 * seed value as key for the HMAC (since the machine ID is something we generally don't want to leak)
4310 * and the partition type as plaintext. The partition type is suffixed with a counter (only for the
4311 * second and later partition of the same type) if we have more than one partition of the same
4312 * time. Or in other words:
4315 * SEED := /etc/machine-id
4317 * If first partition instance of type TYPE_UUID:
4318 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID)
4320 * For all later partition instances of type TYPE_UUID with INSTANCE being the LE64 encoded instance number:
4321 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID || INSTANCE)
4324 LIST_FOREACH(partitions
, q
, context
->partitions
) {
4328 if (!sd_id128_equal(p
->type
.uuid
, q
->type
.uuid
))
4334 plaintext
.type_uuid
= p
->type
.uuid
;
4335 plaintext
.counter
= htole64(k
);
4337 hmac_sha256(context
->seed
.bytes
, sizeof(context
->seed
.bytes
),
4339 k
== 0 ? sizeof(sd_id128_t
) : sizeof(plaintext
),
4342 /* Take the first half, mark it as v4 UUID */
4343 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
4344 result
.id
= id128_make_v4_uuid(result
.id
);
4346 /* Ensure this partition UUID is actually unique, and there's no remaining partition from an earlier run? */
4347 LIST_FOREACH(partitions
, q
, context
->partitions
) {
4351 if (sd_id128_in_set(result
.id
, q
->current_uuid
, q
->new_uuid
)) {
4352 log_warning("Partition UUID calculated from seed for partition %" PRIu64
" already used, reverting to randomized UUID.", p
->partno
);
4354 r
= sd_id128_randomize(&result
.id
);
4356 return log_error_errno(r
, "Failed to generate randomized UUID: %m");
4366 static int partition_acquire_label(Context
*context
, Partition
*p
, char **ret
) {
4367 _cleanup_free_
char *label
= NULL
;
4375 prefix
= gpt_partition_type_uuid_to_string(p
->type
.uuid
);
4380 const char *ll
= label
?: prefix
;
4383 LIST_FOREACH(partitions
, q
, context
->partitions
) {
4387 if (streq_ptr(ll
, q
->current_label
) ||
4388 streq_ptr(ll
, q
->new_label
)) {
4397 label
= mfree(label
);
4398 if (asprintf(&label
, "%s-%u", prefix
, ++k
) < 0)
4403 label
= strdup(prefix
);
4408 *ret
= TAKE_PTR(label
);
4412 static int context_acquire_partition_uuids_and_labels(Context
*context
) {
4417 LIST_FOREACH(partitions
, p
, context
->partitions
) {
4420 /* Never touch foreign partitions */
4421 if (PARTITION_IS_FOREIGN(p
)) {
4422 p
->new_uuid
= p
->current_uuid
;
4424 if (p
->current_label
) {
4425 r
= free_and_strdup_warn(&p
->new_label
, strempty(p
->current_label
));
4433 if (!sd_id128_is_null(p
->current_uuid
))
4434 p
->new_uuid
= uuid
= p
->current_uuid
; /* Never change initialized UUIDs */
4435 else if (p
->new_uuid_is_set
)
4438 /* Not explicitly set by user! */
4439 r
= partition_acquire_uuid(context
, p
, &uuid
);
4443 /* The final verity hash/data UUIDs can only be determined after formatting the
4444 * verity hash partition. However, we still want to use the generated partition UUID
4445 * to derive other UUIDs to keep things unique and reproducible, so we always
4446 * generate a UUID if none is set, but we only use it as the actual partition UUID if
4447 * verity is not configured. */
4448 if (!IN_SET(p
->verity
, VERITY_DATA
, VERITY_HASH
)) {
4450 p
->new_uuid_is_set
= true;
4454 /* Calculate the UUID for the file system as HMAC-SHA256 of the string "file-system-uuid",
4455 * keyed off the partition UUID. */
4456 r
= derive_uuid(uuid
, "file-system-uuid", &p
->fs_uuid
);
4460 if (p
->encrypt
!= ENCRYPT_OFF
) {
4461 r
= derive_uuid(uuid
, "luks-uuid", &p
->luks_uuid
);
4466 if (!isempty(p
->current_label
)) {
4467 /* never change initialized labels */
4468 r
= free_and_strdup_warn(&p
->new_label
, p
->current_label
);
4471 } else if (!p
->new_label
) {
4472 /* Not explicitly set by user! */
4474 r
= partition_acquire_label(context
, p
, &p
->new_label
);
4483 static int set_gpt_flags(struct fdisk_partition
*q
, uint64_t flags
) {
4484 _cleanup_free_
char *a
= NULL
;
4486 for (unsigned i
= 0; i
< sizeof(flags
) * 8; i
++) {
4487 uint64_t bit
= UINT64_C(1) << i
;
4488 char buf
[DECIMAL_STR_MAX(unsigned)+1];
4490 if (!FLAGS_SET(flags
, bit
))
4493 xsprintf(buf
, "%u", i
);
4494 if (!strextend_with_separator(&a
, ",", buf
))
4498 return fdisk_partition_set_attrs(q
, a
);
4501 static uint64_t partition_merge_flags(Partition
*p
) {
4508 if (p
->no_auto
>= 0) {
4509 if (gpt_partition_type_knows_no_auto(p
->type
))
4510 SET_FLAG(f
, SD_GPT_FLAG_NO_AUTO
, p
->no_auto
);
4512 char buffer
[SD_ID128_UUID_STRING_MAX
];
4513 log_warning("Configured NoAuto=%s for partition type '%s' that doesn't support it, ignoring.",
4515 gpt_partition_type_uuid_to_string_harder(p
->type
.uuid
, buffer
));
4519 if (p
->read_only
>= 0) {
4520 if (gpt_partition_type_knows_read_only(p
->type
))
4521 SET_FLAG(f
, SD_GPT_FLAG_READ_ONLY
, p
->read_only
);
4523 char buffer
[SD_ID128_UUID_STRING_MAX
];
4524 log_warning("Configured ReadOnly=%s for partition type '%s' that doesn't support it, ignoring.",
4525 yes_no(p
->read_only
),
4526 gpt_partition_type_uuid_to_string_harder(p
->type
.uuid
, buffer
));
4530 if (p
->growfs
>= 0) {
4531 if (gpt_partition_type_knows_growfs(p
->type
))
4532 SET_FLAG(f
, SD_GPT_FLAG_GROWFS
, p
->growfs
);
4534 char buffer
[SD_ID128_UUID_STRING_MAX
];
4535 log_warning("Configured GrowFileSystem=%s for partition type '%s' that doesn't support it, ignoring.",
4537 gpt_partition_type_uuid_to_string_harder(p
->type
.uuid
, buffer
));
4544 static int context_mangle_partitions(Context
*context
) {
4549 LIST_FOREACH(partitions
, p
, context
->partitions
) {
4553 if (partition_defer(p
))
4556 assert(p
->new_size
!= UINT64_MAX
);
4557 assert(p
->offset
!= UINT64_MAX
);
4558 assert(p
->partno
!= UINT64_MAX
);
4560 if (PARTITION_EXISTS(p
)) {
4561 bool changed
= false;
4563 assert(p
->current_partition
);
4565 if (p
->new_size
!= p
->current_size
) {
4566 assert(p
->new_size
>= p
->current_size
);
4567 assert(p
->new_size
% context
->sector_size
== 0);
4569 r
= fdisk_partition_size_explicit(p
->current_partition
, true);
4571 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
4573 r
= fdisk_partition_set_size(p
->current_partition
, p
->new_size
/ context
->sector_size
);
4575 return log_error_errno(r
, "Failed to grow partition: %m");
4577 log_info("Growing existing partition %" PRIu64
".", p
->partno
);
4581 if (!sd_id128_equal(p
->new_uuid
, p
->current_uuid
)) {
4582 r
= fdisk_partition_set_uuid(p
->current_partition
, SD_ID128_TO_UUID_STRING(p
->new_uuid
));
4584 return log_error_errno(r
, "Failed to set partition UUID: %m");
4586 log_info("Initializing UUID of existing partition %" PRIu64
".", p
->partno
);
4590 if (!streq_ptr(p
->new_label
, p
->current_label
)) {
4591 r
= fdisk_partition_set_name(p
->current_partition
, strempty(p
->new_label
));
4593 return log_error_errno(r
, "Failed to set partition label: %m");
4595 log_info("Setting partition label of existing partition %" PRIu64
".", p
->partno
);
4600 assert(!PARTITION_IS_FOREIGN(p
)); /* never touch foreign partitions */
4602 r
= fdisk_set_partition(context
->fdisk_context
, p
->partno
, p
->current_partition
);
4604 return log_error_errno(r
, "Failed to update partition: %m");
4607 _cleanup_(fdisk_unref_partitionp
) struct fdisk_partition
*q
= NULL
;
4608 _cleanup_(fdisk_unref_parttypep
) struct fdisk_parttype
*t
= NULL
;
4610 assert(!p
->new_partition
);
4611 assert(p
->offset
% context
->sector_size
== 0);
4612 assert(p
->new_size
% context
->sector_size
== 0);
4613 assert(p
->new_label
);
4615 t
= fdisk_new_parttype();
4619 r
= fdisk_parttype_set_typestr(t
, SD_ID128_TO_UUID_STRING(p
->type
.uuid
));
4621 return log_error_errno(r
, "Failed to initialize partition type: %m");
4623 q
= fdisk_new_partition();
4627 r
= fdisk_partition_set_type(q
, t
);
4629 return log_error_errno(r
, "Failed to set partition type: %m");
4631 r
= fdisk_partition_size_explicit(q
, true);
4633 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
4635 r
= fdisk_partition_set_start(q
, p
->offset
/ context
->sector_size
);
4637 return log_error_errno(r
, "Failed to position partition: %m");
4639 r
= fdisk_partition_set_size(q
, p
->new_size
/ context
->sector_size
);
4641 return log_error_errno(r
, "Failed to grow partition: %m");
4643 r
= fdisk_partition_set_partno(q
, p
->partno
);
4645 return log_error_errno(r
, "Failed to set partition number: %m");
4647 r
= fdisk_partition_set_uuid(q
, SD_ID128_TO_UUID_STRING(p
->new_uuid
));
4649 return log_error_errno(r
, "Failed to set partition UUID: %m");
4651 r
= fdisk_partition_set_name(q
, strempty(p
->new_label
));
4653 return log_error_errno(r
, "Failed to set partition label: %m");
4655 /* Merge the no auto + read only + growfs setting with the literal flags, and set them for the partition */
4656 r
= set_gpt_flags(q
, partition_merge_flags(p
));
4658 return log_error_errno(r
, "Failed to set GPT partition flags: %m");
4660 log_info("Adding new partition %" PRIu64
" to partition table.", p
->partno
);
4662 r
= fdisk_add_partition(context
->fdisk_context
, q
, NULL
);
4664 return log_error_errno(r
, "Failed to add partition: %m");
4666 assert(!p
->new_partition
);
4667 p
->new_partition
= TAKE_PTR(q
);
4674 static int split_name_printf(Partition
*p
, char **ret
) {
4677 const Specifier table
[] = {
4678 { 't', specifier_string
, GPT_PARTITION_TYPE_UUID_TO_STRING_HARDER(p
->type
.uuid
) },
4679 { 'T', specifier_id128
, &p
->type
.uuid
},
4680 { 'U', specifier_id128
, &p
->new_uuid
},
4681 { 'n', specifier_uint64
, &p
->partno
},
4683 COMMON_SYSTEM_SPECIFIERS
,
4687 return specifier_printf(p
->split_name_format
, NAME_MAX
, table
, arg_root
, p
, ret
);
4690 static int split_node(const char *node
, char **ret_base
, char **ret_ext
) {
4691 _cleanup_free_
char *base
= NULL
, *ext
= NULL
;
4699 r
= path_extract_filename(node
, &base
);
4700 if (r
== O_DIRECTORY
|| r
== -EADDRNOTAVAIL
)
4701 return log_error_errno(r
, "Device node %s cannot be a directory", node
);
4703 return log_error_errno(r
, "Failed to extract filename from %s: %m", node
);
4705 e
= endswith(base
, ".raw");
4714 *ret_base
= TAKE_PTR(base
);
4715 *ret_ext
= TAKE_PTR(ext
);
4720 static int split_name_resolve(Context
*context
) {
4721 _cleanup_free_
char *parent
= NULL
, *base
= NULL
, *ext
= NULL
;
4726 r
= path_extract_directory(context
->node
, &parent
);
4727 if (r
< 0 && r
!= -EDESTADDRREQ
)
4728 return log_error_errno(r
, "Failed to extract directory from %s: %m", context
->node
);
4730 r
= split_node(context
->node
, &base
, &ext
);
4734 LIST_FOREACH(partitions
, p
, context
->partitions
) {
4735 _cleanup_free_
char *resolved
= NULL
;
4740 if (!p
->split_name_format
)
4743 r
= split_name_printf(p
, &resolved
);
4745 return log_error_errno(r
, "Failed to resolve specifiers in %s: %m", p
->split_name_format
);
4748 p
->split_path
= strjoin(parent
, "/", base
, ".", resolved
, ext
);
4750 p
->split_path
= strjoin(base
, ".", resolved
, ext
);
4755 LIST_FOREACH(partitions
, p
, context
->partitions
) {
4759 LIST_FOREACH(partitions
, q
, context
->partitions
) {
4766 if (!streq(p
->split_path
, q
->split_path
))
4769 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
4770 "%s and %s have the same resolved split name \"%s\", refusing",
4771 p
->definition_path
, q
->definition_path
, p
->split_path
);
4778 static int context_split(Context
*context
) {
4786 /* We can't do resolution earlier because the partition UUIDs for verity partitions are only filled
4787 * in after they've been generated. */
4789 r
= split_name_resolve(context
);
4793 LIST_FOREACH(partitions
, p
, context
->partitions
) {
4794 _cleanup_close_
int fdt
= -EBADF
;
4802 if (partition_defer(p
))
4805 fdt
= open(p
->split_path
, O_WRONLY
|O_NOCTTY
|O_CLOEXEC
|O_NOFOLLOW
|O_CREAT
|O_EXCL
, 0666);
4807 return log_error_errno(fdt
, "Failed to open split partition file %s: %m", p
->split_path
);
4810 assert_se((fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
4812 if (lseek(fd
, p
->offset
, SEEK_SET
) < 0)
4813 return log_error_errno(errno
, "Failed to seek to partition offset: %m");
4815 r
= copy_bytes(fd
, fdt
, p
->new_size
, COPY_REFLINK
|COPY_HOLES
);
4817 return log_error_errno(r
, "Failed to copy to split partition %s: %m", p
->split_path
);
4823 static int context_write_partition_table(Context
*context
) {
4824 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*original_table
= NULL
;
4829 if (!context
->from_scratch
&& !context_changed(context
)) {
4830 log_info("No changes.");
4835 log_notice("Refusing to repartition, please re-run with --dry-run=no.");
4839 log_info("Applying changes.");
4841 if (context
->from_scratch
) {
4842 r
= context_wipe_range(context
, 0, context
->total
);
4846 log_info("Wiped block device.");
4849 r
= context_discard_range(context
, 0, context
->total
);
4850 if (r
== -EOPNOTSUPP
)
4851 log_info("Storage does not support discard, not discarding entire block device data.");
4853 return log_error_errno(r
, "Failed to discard entire block device: %m");
4855 log_info("Discarded entire block device.");
4859 r
= fdisk_get_partitions(context
->fdisk_context
, &original_table
);
4861 return log_error_errno(r
, "Failed to acquire partition table: %m");
4863 /* Wipe fs signatures and discard sectors where the new partitions are going to be placed and in the
4864 * gaps between partitions, just to be sure. */
4865 r
= context_wipe_and_discard(context
);
4869 r
= context_copy_blocks(context
);
4873 r
= context_mkfs(context
);
4877 r
= context_mangle_partitions(context
);
4881 log_info("Writing new partition table.");
4883 r
= fdisk_write_disklabel(context
->fdisk_context
);
4885 return log_error_errno(r
, "Failed to write partition table: %m");
4887 capable
= blockdev_partscan_enabled(fdisk_get_devfd(context
->fdisk_context
));
4888 if (capable
== -ENOTBLK
)
4889 log_debug("Not telling kernel to reread partition table, since we are not operating on a block device.");
4890 else if (capable
< 0)
4891 return log_error_errno(capable
, "Failed to check if block device supports partition scanning: %m");
4892 else if (capable
> 0) {
4893 log_info("Telling kernel to reread partition table.");
4895 if (context
->from_scratch
)
4896 r
= fdisk_reread_partition_table(context
->fdisk_context
);
4898 r
= fdisk_reread_changes(context
->fdisk_context
, original_table
);
4900 return log_error_errno(r
, "Failed to reread partition table: %m");
4902 log_notice("Not telling kernel to reread partition table, because selected image does not support kernel partition block devices.");
4904 log_info("All done.");
4909 static int context_read_seed(Context
*context
, const char *root
) {
4914 if (!sd_id128_is_null(context
->seed
))
4917 if (!arg_randomize
) {
4918 r
= id128_get_machine(root
, &context
->seed
);
4922 if (!ERRNO_IS_MACHINE_ID_UNSET(r
))
4923 return log_error_errno(r
, "Failed to parse machine ID of image: %m");
4925 log_info("No machine ID set, using randomized partition UUIDs.");
4928 r
= sd_id128_randomize(&context
->seed
);
4930 return log_error_errno(r
, "Failed to generate randomized seed: %m");
4935 static int context_factory_reset(Context
*context
) {
4941 if (arg_factory_reset
<= 0)
4944 if (context
->from_scratch
) /* Nothing to reset if we start from scratch */
4948 log_notice("Refusing to factory reset, please re-run with --dry-run=no.");
4952 log_info("Applying factory reset.");
4954 LIST_FOREACH(partitions
, p
, context
->partitions
) {
4956 if (!p
->factory_reset
|| !PARTITION_EXISTS(p
))
4959 assert(p
->partno
!= UINT64_MAX
);
4961 log_info("Removing partition %" PRIu64
" for factory reset.", p
->partno
);
4963 r
= fdisk_delete_partition(context
->fdisk_context
, p
->partno
);
4965 return log_error_errno(r
, "Failed to remove partition %" PRIu64
": %m", p
->partno
);
4971 log_info("Factory reset requested, but no partitions to delete found.");
4975 r
= fdisk_write_disklabel(context
->fdisk_context
);
4977 return log_error_errno(r
, "Failed to write disk label: %m");
4979 log_info("Successfully deleted %zu partitions.", n
);
4983 static int context_can_factory_reset(Context
*context
) {
4986 LIST_FOREACH(partitions
, p
, context
->partitions
)
4987 if (p
->factory_reset
&& PARTITION_EXISTS(p
))
4993 static int resolve_copy_blocks_auto_candidate(
4994 dev_t partition_devno
,
4995 GptPartitionType partition_type
,
4996 dev_t restrict_devno
,
4997 sd_id128_t
*ret_uuid
) {
4999 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
5000 _cleanup_close_
int fd
= -EBADF
;
5001 _cleanup_free_
char *p
= NULL
;
5002 const char *pttype
, *t
;
5003 sd_id128_t pt_parsed
, u
;
5009 /* Checks if the specified partition has the specified GPT type UUID, and is located on the specified
5010 * 'restrict_devno' device. The type check is particularly relevant if we have Verity volume which is
5011 * backed by two separate partitions: the data and the hash partitions, and we need to find the right
5012 * one of the two. */
5014 r
= block_get_whole_disk(partition_devno
, &whole_devno
);
5016 return log_error_errno(
5018 "Unable to determine containing block device of partition %u:%u: %m",
5019 major(partition_devno
), minor(partition_devno
));
5021 if (restrict_devno
!= (dev_t
) -1 &&
5022 restrict_devno
!= whole_devno
)
5023 return log_error_errno(
5024 SYNTHETIC_ERRNO(EPERM
),
5025 "Partition %u:%u is located outside of block device %u:%u, refusing.",
5026 major(partition_devno
), minor(partition_devno
),
5027 major(restrict_devno
), minor(restrict_devno
));
5029 fd
= r
= device_open_from_devnum(S_IFBLK
, whole_devno
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &p
);
5031 return log_error_errno(r
, "Failed to open block device " DEVNUM_FORMAT_STR
": %m",
5032 DEVNUM_FORMAT_VAL(whole_devno
));
5034 b
= blkid_new_probe();
5039 r
= blkid_probe_set_device(b
, fd
, 0, 0);
5041 return log_error_errno(errno_or_else(ENOMEM
), "Failed to open block device '%s': %m", p
);
5043 (void) blkid_probe_enable_partitions(b
, 1);
5044 (void) blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
5047 r
= blkid_do_safeprobe(b
);
5048 if (r
== _BLKID_SAFEPROBE_ERROR
)
5049 return log_error_errno(errno_or_else(EIO
), "Unable to probe for partition table of '%s': %m", p
);
5050 if (IN_SET(r
, _BLKID_SAFEPROBE_AMBIGUOUS
, _BLKID_SAFEPROBE_NOT_FOUND
)) {
5051 log_debug("Didn't find partition table on block device '%s'.", p
);
5055 assert(r
== _BLKID_SAFEPROBE_FOUND
);
5057 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
5058 if (!streq_ptr(pttype
, "gpt")) {
5059 log_debug("Didn't find a GPT partition table on '%s'.", p
);
5064 pl
= blkid_probe_get_partitions(b
);
5066 return log_error_errno(errno_or_else(EIO
), "Unable read partition table of '%s': %m", p
);
5068 pp
= blkid_partlist_devno_to_partition(pl
, partition_devno
);
5070 log_debug("Partition %u:%u has no matching partition table entry on '%s'.",
5071 major(partition_devno
), minor(partition_devno
), p
);
5075 t
= blkid_partition_get_type_string(pp
);
5077 log_debug("Partition %u:%u has no type on '%s'.",
5078 major(partition_devno
), minor(partition_devno
), p
);
5082 r
= sd_id128_from_string(t
, &pt_parsed
);
5084 log_debug_errno(r
, "Failed to parse partition type \"%s\": %m", t
);
5088 if (!sd_id128_equal(pt_parsed
, partition_type
.uuid
)) {
5089 log_debug("Partition %u:%u has non-matching partition type " SD_ID128_FORMAT_STR
" (needed: " SD_ID128_FORMAT_STR
"), ignoring.",
5090 major(partition_devno
), minor(partition_devno
),
5091 SD_ID128_FORMAT_VAL(pt_parsed
), SD_ID128_FORMAT_VAL(partition_type
.uuid
));
5095 r
= blkid_partition_get_uuid_id128(pp
, &u
);
5097 log_debug_errno(r
, "Partition " DEVNUM_FORMAT_STR
" has no UUID.", DEVNUM_FORMAT_VAL(partition_devno
));
5101 log_debug_errno(r
, "Failed to read partition UUID of " DEVNUM_FORMAT_STR
": %m", DEVNUM_FORMAT_VAL(partition_devno
));
5105 log_debug("Automatically found partition " DEVNUM_FORMAT_STR
" of right type " SD_ID128_FORMAT_STR
".",
5106 DEVNUM_FORMAT_VAL(partition_devno
),
5107 SD_ID128_FORMAT_VAL(pt_parsed
));
5115 static int find_backing_devno(
5120 _cleanup_free_
char *resolved
= NULL
;
5125 r
= chase(path
, root
, CHASE_PREFIX_ROOT
, &resolved
, NULL
);
5129 r
= path_is_mount_point(resolved
, NULL
, 0);
5132 if (r
== 0) /* Not a mount point, then it's not a partition of its own, let's not automatically use it. */
5135 r
= get_block_device(resolved
, ret
);
5138 if (r
== 0) /* Not backed by physical file system, we can't use this */
5144 static int resolve_copy_blocks_auto(
5145 GptPartitionType type
,
5147 dev_t restrict_devno
,
5149 sd_id128_t
*ret_uuid
) {
5151 const char *try1
= NULL
, *try2
= NULL
;
5152 char p
[SYS_BLOCK_PATH_MAX("/slaves")];
5153 _cleanup_(closedirp
) DIR *d
= NULL
;
5154 sd_id128_t found_uuid
= SD_ID128_NULL
;
5155 dev_t devno
, found
= 0;
5158 /* Enforce some security restrictions: CopyBlocks=auto should not be an avenue to get outside of the
5159 * --root=/--image= confinement. Specifically, refuse CopyBlocks= in combination with --root= at all,
5160 * and restrict block device references in the --image= case to loopback block device we set up.
5162 * restrict_devno contain the dev_t of the loop back device we operate on in case of --image=, and
5163 * thus declares which device (and its partition subdevices) we shall limit access to. If
5164 * restrict_devno is zero no device probing access shall be allowed at all (used for --root=) and if
5165 * it is (dev_t) -1 then free access shall be allowed (if neither switch is used). */
5167 if (restrict_devno
== 0)
5168 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
5169 "Automatic discovery of backing block devices not permitted in --root= mode, refusing.");
5171 /* Handles CopyBlocks=auto, and finds the right source partition to copy from. We look for matching
5172 * partitions in the host, using the appropriate directory as key and ensuring that the partition
5175 if (type
.designator
== PARTITION_ROOT
)
5177 else if (type
.designator
== PARTITION_USR
)
5179 else if (type
.designator
== PARTITION_ROOT_VERITY
)
5181 else if (type
.designator
== PARTITION_USR_VERITY
)
5183 else if (type
.designator
== PARTITION_ESP
) {
5186 } else if (type
.designator
== PARTITION_XBOOTLDR
)
5189 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
5190 "Partition type " SD_ID128_FORMAT_STR
" not supported from automatic source block device discovery.",
5191 SD_ID128_FORMAT_VAL(type
.uuid
));
5193 r
= find_backing_devno(try1
, root
, &devno
);
5194 if (r
== -ENOENT
&& try2
)
5195 r
= find_backing_devno(try2
, root
, &devno
);
5197 return log_error_errno(r
, "Failed to resolve automatic CopyBlocks= path for partition type " SD_ID128_FORMAT_STR
", sorry: %m",
5198 SD_ID128_FORMAT_VAL(type
.uuid
));
5200 xsprintf_sys_block_path(p
, "/slaves", devno
);
5206 _cleanup_free_
char *q
= NULL
, *t
= NULL
;
5211 de
= readdir_no_dot(d
);
5214 return log_error_errno(errno
, "Failed to read directory '%s': %m", p
);
5219 if (!IN_SET(de
->d_type
, DT_LNK
, DT_UNKNOWN
))
5222 q
= path_join(p
, de
->d_name
, "/dev");
5226 r
= read_one_line_file(q
, &t
);
5228 return log_error_errno(r
, "Failed to read %s: %m", q
);
5230 r
= parse_devnum(t
, &sl
);
5232 log_debug_errno(r
, "Failed to parse %s, ignoring: %m", q
);
5235 if (major(sl
) == 0) {
5236 log_debug("Device backing %s is special, ignoring.", q
);
5240 r
= resolve_copy_blocks_auto_candidate(sl
, type
, restrict_devno
, &u
);
5244 /* We found a matching one! */
5246 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
5247 "Multiple matching partitions found, refusing.");
5253 } else if (errno
!= ENOENT
)
5254 return log_error_errno(errno
, "Failed open %s: %m", p
);
5256 r
= resolve_copy_blocks_auto_candidate(devno
, type
, restrict_devno
, &found_uuid
);
5264 return log_error_errno(SYNTHETIC_ERRNO(ENXIO
),
5265 "Unable to automatically discover suitable partition to copy blocks from.");
5271 *ret_uuid
= found_uuid
;
5276 static int context_open_copy_block_paths(
5278 dev_t restrict_devno
) {
5284 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5285 _cleanup_close_
int source_fd
= -EBADF
;
5286 _cleanup_free_
char *opened
= NULL
;
5287 sd_id128_t uuid
= SD_ID128_NULL
;
5291 assert(p
->copy_blocks_fd
< 0);
5292 assert(p
->copy_blocks_size
== UINT64_MAX
);
5294 if (PARTITION_EXISTS(p
)) /* Never copy over partitions that already exist! */
5297 if (p
->copy_blocks_path
) {
5299 source_fd
= chase_and_open(p
->copy_blocks_path
, p
->copy_blocks_root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &opened
);
5301 return log_error_errno(source_fd
, "Failed to open '%s': %m", p
->copy_blocks_path
);
5303 if (fstat(source_fd
, &st
) < 0)
5304 return log_error_errno(errno
, "Failed to stat block copy file '%s': %m", opened
);
5306 if (!S_ISREG(st
.st_mode
) && restrict_devno
!= (dev_t
) -1)
5307 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
5308 "Copying from block device node is not permitted in --image=/--root= mode, refusing.");
5310 } else if (p
->copy_blocks_auto
) {
5311 dev_t devno
= 0; /* Fake initialization to appease gcc. */
5313 r
= resolve_copy_blocks_auto(p
->type
, p
->copy_blocks_root
, restrict_devno
, &devno
, &uuid
);
5318 source_fd
= r
= device_open_from_devnum(S_IFBLK
, devno
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &opened
);
5320 return log_error_errno(r
, "Failed to open automatically determined source block copy device " DEVNUM_FORMAT_STR
": %m",
5321 DEVNUM_FORMAT_VAL(devno
));
5323 if (fstat(source_fd
, &st
) < 0)
5324 return log_error_errno(errno
, "Failed to stat block copy file '%s': %m", opened
);
5328 if (S_ISDIR(st
.st_mode
)) {
5329 _cleanup_free_
char *bdev
= NULL
;
5332 /* If the file is a directory, automatically find the backing block device */
5334 if (major(st
.st_dev
) != 0)
5337 /* Special support for btrfs */
5338 r
= btrfs_get_block_device_fd(source_fd
, &devt
);
5340 return btrfs_log_dev_root(LOG_ERR
, r
, opened
);
5342 return log_error_errno(r
, "Unable to determine backing block device of '%s': %m", opened
);
5345 safe_close(source_fd
);
5347 source_fd
= r
= device_open_from_devnum(S_IFBLK
, devt
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &bdev
);
5349 return log_error_errno(r
, "Failed to open block device backing '%s': %m", opened
);
5351 if (fstat(source_fd
, &st
) < 0)
5352 return log_error_errno(errno
, "Failed to stat block device '%s': %m", bdev
);
5355 if (S_ISREG(st
.st_mode
))
5357 else if (S_ISBLK(st
.st_mode
)) {
5358 if (ioctl(source_fd
, BLKGETSIZE64
, &size
) != 0)
5359 return log_error_errno(errno
, "Failed to determine size of block device to copy from: %m");
5361 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Specified path to copy blocks from '%s' is not a regular file, block device or directory, refusing: %m", opened
);
5364 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "File to copy bytes from '%s' has zero size, refusing.", opened
);
5365 if (size
% 512 != 0)
5366 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "File to copy bytes from '%s' has size that is not multiple of 512, refusing.", opened
);
5368 p
->copy_blocks_fd
= TAKE_FD(source_fd
);
5369 p
->copy_blocks_size
= size
;
5371 free_and_replace(p
->copy_blocks_path
, opened
);
5373 /* When copying from an existing partition copy that partitions UUID if none is configured explicitly */
5374 if (!p
->new_uuid_is_set
&& !sd_id128_is_null(uuid
)) {
5376 p
->new_uuid_is_set
= true;
5383 static int fd_apparent_size(int fd
, uint64_t *ret
) {
5390 initial
= lseek(fd
, 0, SEEK_CUR
);
5392 return log_error_errno(errno
, "Failed to get file offset: %m");
5394 for (off_t off
= 0;;) {
5397 r
= lseek(fd
, off
, SEEK_DATA
);
5398 if (r
< 0 && errno
== ENXIO
)
5399 /* If errno == ENXIO, that means we've reached the final hole of the file and
5400 * that hole isn't followed by more data. */
5403 return log_error_errno(errno
, "Failed to seek data in file from offset %"PRIi64
": %m", off
);
5405 off
= r
; /* Set the offset to the start of the data segment. */
5407 /* After copying a potential hole, find the end of the data segment by looking for
5408 * the next hole. If we get ENXIO, we're at EOF. */
5409 r
= lseek(fd
, off
, SEEK_HOLE
);
5413 return log_error_errno(errno
, "Failed to seek hole in file from offset %"PRIi64
": %m", off
);
5420 if (lseek(fd
, initial
, SEEK_SET
) < 0)
5421 return log_error_errno(errno
, "Failed to reset file offset: %m");
5428 static int context_minimize(Context
*context
) {
5434 r
= var_tmp_dir(&vt
);
5436 return log_error_errno(r
, "Could not determine temporary directory: %m");
5438 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5439 _cleanup_hashmap_free_ Hashmap
*denylist
= NULL
;
5440 _cleanup_(rm_rf_physical_and_freep
) char *root
= NULL
;
5441 _cleanup_(unlink_and_freep
) char *temp
= NULL
;
5442 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
5443 _cleanup_strv_free_
char **extra_mkfs_options
= NULL
;
5444 _cleanup_close_
int fd
= -EBADF
;
5445 _cleanup_free_
char *hint
= NULL
;
5452 if (PARTITION_EXISTS(p
)) /* Never format existing partitions */
5458 if (p
->minimize
== MINIMIZE_OFF
)
5461 if (!partition_needs_populate(p
))
5464 assert(!p
->copy_blocks_path
);
5466 (void) partition_hint(p
, context
->node
, &hint
);
5468 log_info("Pre-populating %s filesystem of partition %s twice to calculate minimal partition size",
5469 p
->format
, strna(hint
));
5471 r
= make_copy_files_denylist(context
, p
, &denylist
);
5475 r
= tempfn_random_child(vt
, "repart", &temp
);
5477 return log_error_errno(r
, "Failed to generate temporary file path: %m");
5479 if (fstype_is_ro(p
->format
))
5480 fs_uuid
= p
->fs_uuid
;
5482 fd
= open(temp
, O_CREAT
|O_EXCL
|O_CLOEXEC
|O_RDWR
|O_NOCTTY
, 0600);
5484 return log_error_errno(errno
, "Failed to open temporary file %s: %m", temp
);
5486 /* This may seem huge but it will be created sparse so it doesn't take up any space
5487 * on disk until written to. */
5488 if (ftruncate(fd
, 1024ULL * 1024ULL * 1024ULL * 1024ULL) < 0)
5489 return log_error_errno(errno
, "Failed to truncate temporary file to %s: %m",
5490 FORMAT_BYTES(1024ULL * 1024ULL * 1024ULL * 1024ULL));
5492 r
= loop_device_make(fd
, O_RDWR
, 0, UINT64_MAX
, 0, 0, LOCK_EX
, &d
);
5493 if (r
< 0 && r
!= -ENOENT
&& !ERRNO_IS_PRIVILEGE(r
))
5494 return log_error_errno(r
, "Failed to make loopback device of %s: %m", temp
);
5496 /* We're going to populate this filesystem twice so use a random UUID the first time
5497 * to avoid UUID conflicts. */
5498 r
= sd_id128_randomize(&fs_uuid
);
5503 if (!d
|| fstype_is_ro(p
->format
)) {
5504 if (!mkfs_supports_root_option(p
->format
))
5505 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
),
5506 "Loop device access is required to populate %s filesystems",
5509 r
= partition_populate_directory(p
, denylist
, &root
);
5514 r
= mkfs_options_from_env("REPART", p
->format
, &extra_mkfs_options
);
5516 return log_error_errno(r
,
5517 "Failed to determine mkfs command line options for '%s': %m",
5520 r
= make_filesystem(d
? d
->node
: temp
, p
->format
, strempty(p
->new_label
), root
, fs_uuid
,
5521 arg_discard
, context
->sector_size
, extra_mkfs_options
);
5525 /* Read-only filesystems are minimal from the first try because they create and size the
5526 * loopback file for us. */
5527 if (fstype_is_ro(p
->format
)) {
5530 if (stat(temp
, &st
) < 0)
5531 return log_error_errno(errno
, "Failed to stat temporary file: %m");
5533 log_info("Minimal partition size of %s filesystem of partition %s is %s",
5534 p
->format
, strna(hint
), FORMAT_BYTES(st
.st_size
));
5536 p
->copy_blocks_path
= TAKE_PTR(temp
);
5537 p
->copy_blocks_path_is_our_file
= true;
5544 r
= partition_populate_filesystem(p
, d
->node
, denylist
);
5549 /* Other filesystems need to be provided with a pre-sized loopback file and will adapt to
5550 * fully occupy it. Because we gave the filesystem a 1T sparse file, we need to shrink the
5551 * filesystem down to a reasonable size again to fit it in the disk image. While there are
5552 * some filesystems that support shrinking, it doesn't always work properly (e.g. shrinking
5553 * btrfs gives us a 2.0G filesystem regardless of what we put in it). Instead, let's populate
5554 * the filesystem again, but this time, instead of providing the filesystem with a 1T sparse
5555 * loopback file, let's size the loopback file based on the actual data used by the
5556 * filesystem in the sparse file after the first attempt. This should be a good guess of the
5557 * minimal amount of space needed in the filesystem to fit all the required data.
5559 r
= fd_apparent_size(fd
, &fsz
);
5563 /* Massage the size a bit because just going by actual data used in the sparse file isn't
5565 fsz
= round_up_size(fsz
+ (fsz
/ 2), context
->grain_size
);
5566 if (minimal_size_by_fs_name(p
->format
) != UINT64_MAX
)
5567 fsz
= MAX(minimal_size_by_fs_name(p
->format
), fsz
);
5569 log_info("Minimal partition size of %s filesystem of partition %s is %s",
5570 p
->format
, strna(hint
), FORMAT_BYTES(fsz
));
5572 d
= loop_device_unref(d
);
5574 /* Erase the previous filesystem first. */
5575 if (ftruncate(fd
, 0))
5576 return log_error_errno(errno
, "Failed to erase temporary file: %m");
5578 if (ftruncate(fd
, fsz
))
5579 return log_error_errno(errno
, "Failed to truncate temporary file to %s: %m", FORMAT_BYTES(fsz
));
5581 r
= loop_device_make(fd
, O_RDWR
, 0, UINT64_MAX
, 0, 0, LOCK_EX
, &d
);
5582 if (r
< 0 && r
!= -ENOENT
&& !ERRNO_IS_PRIVILEGE(r
))
5583 return log_error_errno(r
, "Failed to make loopback device of %s: %m", temp
);
5585 r
= make_filesystem(d
? d
->node
: temp
, p
->format
, strempty(p
->new_label
), root
, p
->fs_uuid
,
5586 arg_discard
, context
->sector_size
, extra_mkfs_options
);
5593 r
= partition_populate_filesystem(p
, d
->node
, denylist
);
5598 p
->copy_blocks_path
= TAKE_PTR(temp
);
5599 p
->copy_blocks_path_is_our_file
= true;
5605 static int parse_partition_types(const char *p
, sd_id128_t
**partitions
, size_t *n_partitions
) {
5609 assert(n_partitions
);
5612 _cleanup_free_
char *name
= NULL
;
5613 GptPartitionType type
;
5615 r
= extract_first_word(&p
, &name
, ",", EXTRACT_CUNESCAPE
|EXTRACT_DONT_COALESCE_SEPARATORS
);
5619 return log_error_errno(r
, "Failed to extract partition type identifier or GUID: %s", p
);
5621 r
= gpt_partition_type_from_string(name
, &type
);
5623 return log_error_errno(r
, "'%s' is not a valid partition type identifier or GUID", name
);
5625 if (!GREEDY_REALLOC(*partitions
, *n_partitions
+ 1))
5628 (*partitions
)[(*n_partitions
)++] = type
.uuid
;
5634 static int help(void) {
5635 _cleanup_free_
char *link
= NULL
;
5638 r
= terminal_urlify_man("systemd-repart", "8", &link
);
5642 printf("%s [OPTIONS...] [DEVICE]\n"
5643 "\n%sGrow and add partitions to partition table.%s\n\n"
5644 " -h --help Show this help\n"
5645 " --version Show package version\n"
5646 " --no-pager Do not pipe output into a pager\n"
5647 " --no-legend Do not show the headers and footers\n"
5648 " --dry-run=BOOL Whether to run dry-run operation\n"
5649 " --empty=MODE One of refuse, allow, require, force, create; controls\n"
5650 " how to handle empty disks lacking partition tables\n"
5651 " --discard=BOOL Whether to discard backing blocks for new partitions\n"
5652 " --pretty=BOOL Whether to show pretty summary before doing changes\n"
5653 " --factory-reset=BOOL Whether to remove data partitions before recreating\n"
5655 " --can-factory-reset Test whether factory reset is defined\n"
5656 " --root=PATH Operate relative to root path\n"
5657 " --image=PATH Operate relative to image file\n"
5658 " --image-policy=POLICY\n"
5659 " Specify disk image dissection policy\n"
5660 " --definitions=DIR Find partition definitions in specified directory\n"
5661 " --key-file=PATH Key to use when encrypting partitions\n"
5662 " --private-key=PATH Private key to use when generating verity roothash\n"
5664 " --certificate=PATH PEM certificate to use when generating verity\n"
5665 " roothash signatures\n"
5666 " --tpm2-device=PATH Path to TPM2 device node to use\n"
5667 " --tpm2-pcrs=PCR1+PCR2+PCR3+…\n"
5668 " TPM2 PCR indexes to use for TPM2 enrollment\n"
5669 " --tpm2-public-key=PATH\n"
5670 " Enroll signed TPM2 PCR policy against PEM public key\n"
5671 " --tpm2-public-key-pcrs=PCR1+PCR2+PCR3+…\n"
5672 " Enroll signed TPM2 PCR policy for specified TPM2 PCRs\n"
5673 " --seed=UUID 128bit seed UUID to derive all UUIDs from\n"
5674 " --size=BYTES Grow loopback file to specified size\n"
5675 " --json=pretty|short|off\n"
5676 " Generate JSON output\n"
5677 " --split=BOOL Whether to generate split artifacts\n"
5678 " --include-partitions=PARTITION1,PARTITION2,PARTITION3,…\n"
5679 " Ignore partitions not of the specified types\n"
5680 " --exclude-partitions=PARTITION1,PARTITION2,PARTITION3,…\n"
5681 " Ignore partitions of the specified types\n"
5682 " --defer-partitions=PARTITION1,PARTITION2,PARTITION3,…\n"
5683 " Take partitions of the specified types into account\n"
5684 " but don't populate them yet\n"
5685 " --sector-size=SIZE Set the logical sector size for the image\n"
5686 "\nSee the %s for details.\n",
5687 program_invocation_short_name
,
5695 static int parse_argv(int argc
, char *argv
[]) {
5698 ARG_VERSION
= 0x100,
5705 ARG_CAN_FACTORY_RESET
,
5718 ARG_TPM2_PUBLIC_KEY
,
5719 ARG_TPM2_PUBLIC_KEY_PCRS
,
5721 ARG_INCLUDE_PARTITIONS
,
5722 ARG_EXCLUDE_PARTITIONS
,
5723 ARG_DEFER_PARTITIONS
,
5725 ARG_SKIP_PARTITIONS
,
5729 static const struct option options
[] = {
5730 { "help", no_argument
, NULL
, 'h' },
5731 { "version", no_argument
, NULL
, ARG_VERSION
},
5732 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
5733 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
5734 { "dry-run", required_argument
, NULL
, ARG_DRY_RUN
},
5735 { "empty", required_argument
, NULL
, ARG_EMPTY
},
5736 { "discard", required_argument
, NULL
, ARG_DISCARD
},
5737 { "factory-reset", required_argument
, NULL
, ARG_FACTORY_RESET
},
5738 { "can-factory-reset", no_argument
, NULL
, ARG_CAN_FACTORY_RESET
},
5739 { "root", required_argument
, NULL
, ARG_ROOT
},
5740 { "image", required_argument
, NULL
, ARG_IMAGE
},
5741 { "seed", required_argument
, NULL
, ARG_SEED
},
5742 { "pretty", required_argument
, NULL
, ARG_PRETTY
},
5743 { "definitions", required_argument
, NULL
, ARG_DEFINITIONS
},
5744 { "size", required_argument
, NULL
, ARG_SIZE
},
5745 { "json", required_argument
, NULL
, ARG_JSON
},
5746 { "key-file", required_argument
, NULL
, ARG_KEY_FILE
},
5747 { "private-key", required_argument
, NULL
, ARG_PRIVATE_KEY
},
5748 { "certificate", required_argument
, NULL
, ARG_CERTIFICATE
},
5749 { "tpm2-device", required_argument
, NULL
, ARG_TPM2_DEVICE
},
5750 { "tpm2-pcrs", required_argument
, NULL
, ARG_TPM2_PCRS
},
5751 { "tpm2-public-key", required_argument
, NULL
, ARG_TPM2_PUBLIC_KEY
},
5752 { "tpm2-public-key-pcrs", required_argument
, NULL
, ARG_TPM2_PUBLIC_KEY_PCRS
},
5753 { "split", required_argument
, NULL
, ARG_SPLIT
},
5754 { "include-partitions", required_argument
, NULL
, ARG_INCLUDE_PARTITIONS
},
5755 { "exclude-partitions", required_argument
, NULL
, ARG_EXCLUDE_PARTITIONS
},
5756 { "defer-partitions", required_argument
, NULL
, ARG_DEFER_PARTITIONS
},
5757 { "sector-size", required_argument
, NULL
, ARG_SECTOR_SIZE
},
5758 { "image-policy", required_argument
, NULL
, ARG_IMAGE_POLICY
},
5762 int c
, r
, dry_run
= -1;
5767 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
5778 arg_pager_flags
|= PAGER_DISABLE
;
5786 r
= parse_boolean_argument("--dry-run=", optarg
, &arg_dry_run
);
5792 if (isempty(optarg
) || streq(optarg
, "refuse"))
5793 arg_empty
= EMPTY_REFUSE
;
5794 else if (streq(optarg
, "allow"))
5795 arg_empty
= EMPTY_ALLOW
;
5796 else if (streq(optarg
, "require"))
5797 arg_empty
= EMPTY_REQUIRE
;
5798 else if (streq(optarg
, "force"))
5799 arg_empty
= EMPTY_FORCE
;
5800 else if (streq(optarg
, "create")) {
5801 arg_empty
= EMPTY_CREATE
;
5804 dry_run
= false; /* Imply --dry-run=no if we create the loopback file
5805 * anew. After all we cannot really break anyone's
5806 * partition tables that way. */
5808 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5809 "Failed to parse --empty= parameter: %s", optarg
);
5813 r
= parse_boolean_argument("--discard=", optarg
, &arg_discard
);
5818 case ARG_FACTORY_RESET
:
5819 r
= parse_boolean_argument("--factory-reset=", optarg
, NULL
);
5822 arg_factory_reset
= r
;
5825 case ARG_CAN_FACTORY_RESET
:
5826 arg_can_factory_reset
= true;
5830 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_root
);
5836 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_image
);
5842 if (isempty(optarg
)) {
5843 arg_seed
= SD_ID128_NULL
;
5844 arg_randomize
= false;
5845 } else if (streq(optarg
, "random"))
5846 arg_randomize
= true;
5848 r
= sd_id128_from_string(optarg
, &arg_seed
);
5850 return log_error_errno(r
, "Failed to parse seed: %s", optarg
);
5852 arg_randomize
= false;
5858 r
= parse_boolean_argument("--pretty=", optarg
, NULL
);
5864 case ARG_DEFINITIONS
: {
5865 _cleanup_free_
char *path
= NULL
;
5866 r
= parse_path_argument(optarg
, false, &path
);
5869 if (strv_consume(&arg_definitions
, TAKE_PTR(path
)) < 0)
5875 uint64_t parsed
, rounded
;
5877 if (streq(optarg
, "auto")) {
5878 arg_size
= UINT64_MAX
;
5879 arg_size_auto
= true;
5883 r
= parse_size(optarg
, 1024, &parsed
);
5885 return log_error_errno(r
, "Failed to parse --size= parameter: %s", optarg
);
5887 rounded
= round_up_size(parsed
, 4096);
5889 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too small, refusing.");
5890 if (rounded
== UINT64_MAX
)
5891 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too large, refusing.");
5893 if (rounded
!= parsed
)
5894 log_warning("Specified size is not a multiple of 4096, rounding up automatically. (%" PRIu64
" %s %" PRIu64
")",
5895 parsed
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), rounded
);
5898 arg_size_auto
= false;
5903 r
= parse_json_argument(optarg
, &arg_json_format_flags
);
5909 case ARG_KEY_FILE
: {
5910 _cleanup_(erase_and_freep
) char *k
= NULL
;
5913 r
= read_full_file_full(
5914 AT_FDCWD
, optarg
, UINT64_MAX
, SIZE_MAX
,
5915 READ_FULL_FILE_SECURE
|READ_FULL_FILE_WARN_WORLD_READABLE
|READ_FULL_FILE_CONNECT_SOCKET
,
5919 return log_error_errno(r
, "Failed to read key file '%s': %m", optarg
);
5921 erase_and_free(arg_key
);
5922 arg_key
= TAKE_PTR(k
);
5927 case ARG_PRIVATE_KEY
: {
5928 _cleanup_(erase_and_freep
) char *k
= NULL
;
5931 r
= read_full_file_full(
5932 AT_FDCWD
, optarg
, UINT64_MAX
, SIZE_MAX
,
5933 READ_FULL_FILE_SECURE
|READ_FULL_FILE_WARN_WORLD_READABLE
|READ_FULL_FILE_CONNECT_SOCKET
,
5937 return log_error_errno(r
, "Failed to read key file '%s': %m", optarg
);
5939 EVP_PKEY_free(arg_private_key
);
5940 arg_private_key
= NULL
;
5941 r
= parse_private_key(k
, n
, &arg_private_key
);
5947 case ARG_CERTIFICATE
: {
5948 _cleanup_free_
char *cert
= NULL
;
5951 r
= read_full_file_full(
5952 AT_FDCWD
, optarg
, UINT64_MAX
, SIZE_MAX
,
5953 READ_FULL_FILE_CONNECT_SOCKET
,
5957 return log_error_errno(r
, "Failed to read certificate file '%s': %m", optarg
);
5959 X509_free(arg_certificate
);
5960 arg_certificate
= NULL
;
5961 r
= parse_x509_certificate(cert
, n
, &arg_certificate
);
5967 case ARG_TPM2_DEVICE
: {
5968 _cleanup_free_
char *device
= NULL
;
5970 if (streq(optarg
, "list"))
5971 return tpm2_list_devices();
5973 if (!streq(optarg
, "auto")) {
5974 device
= strdup(optarg
);
5979 free(arg_tpm2_device
);
5980 arg_tpm2_device
= TAKE_PTR(device
);
5985 r
= tpm2_parse_pcr_argument(optarg
, &arg_tpm2_pcr_mask
);
5991 case ARG_TPM2_PUBLIC_KEY
:
5992 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_tpm2_public_key
);
5998 case ARG_TPM2_PUBLIC_KEY_PCRS
:
5999 r
= tpm2_parse_pcr_argument(optarg
, &arg_tpm2_public_key_pcr_mask
);
6006 r
= parse_boolean_argument("--split=", optarg
, NULL
);
6013 case ARG_INCLUDE_PARTITIONS
:
6014 if (arg_filter_partitions_type
== FILTER_PARTITIONS_EXCLUDE
)
6015 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6016 "Combination of --include-partitions= and --exclude-partitions= is invalid.");
6018 r
= parse_partition_types(optarg
, &arg_filter_partitions
, &arg_n_filter_partitions
);
6022 arg_filter_partitions_type
= FILTER_PARTITIONS_INCLUDE
;
6026 case ARG_EXCLUDE_PARTITIONS
:
6027 if (arg_filter_partitions_type
== FILTER_PARTITIONS_INCLUDE
)
6028 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6029 "Combination of --include-partitions= and --exclude-partitions= is invalid.");
6031 r
= parse_partition_types(optarg
, &arg_filter_partitions
, &arg_n_filter_partitions
);
6035 arg_filter_partitions_type
= FILTER_PARTITIONS_EXCLUDE
;
6039 case ARG_DEFER_PARTITIONS
:
6040 r
= parse_partition_types(optarg
, &arg_defer_partitions
, &arg_n_defer_partitions
);
6046 case ARG_SECTOR_SIZE
:
6047 r
= parse_sector_size(optarg
, &arg_sector_size
);
6053 case ARG_IMAGE_POLICY
: {
6054 _cleanup_(image_policy_freep
) ImagePolicy
*p
= NULL
;
6056 r
= image_policy_from_string(optarg
, &p
);
6058 return log_error_errno(r
, "Failed to parse image policy: %s", optarg
);
6060 image_policy_free(arg_image_policy
);
6061 arg_image_policy
= TAKE_PTR(p
);
6069 assert_not_reached();
6072 if (argc
- optind
> 1)
6073 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6074 "Expected at most one argument, the path to the block device.");
6076 if (arg_factory_reset
> 0 && IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
))
6077 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6078 "Combination of --factory-reset=yes and --empty=force/--empty=require/--empty=create is invalid.");
6080 if (arg_can_factory_reset
)
6081 arg_dry_run
= true; /* When --can-factory-reset is specified we don't make changes, hence
6082 * non-dry-run mode makes no sense. Thus, imply dry run mode so that we
6083 * open things strictly read-only. */
6084 else if (dry_run
>= 0)
6085 arg_dry_run
= dry_run
;
6087 if (arg_empty
== EMPTY_CREATE
&& (arg_size
== UINT64_MAX
&& !arg_size_auto
))
6088 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6089 "If --empty=create is specified, --size= must be specified, too.");
6091 if (arg_image
&& arg_root
)
6092 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Please specify either --root= or --image=, the combination of both is not supported.");
6093 else if (!arg_image
&& !arg_root
&& in_initrd()) {
6095 /* By default operate on /sysusr/ or /sysroot/ when invoked in the initrd. We prefer the
6096 * former, if it is mounted, so that we have deterministic behaviour on systems where /usr/
6097 * is vendor-supplied but the root fs formatted on first boot. */
6098 r
= path_is_mount_point("/sysusr/usr", NULL
, 0);
6100 if (r
< 0 && r
!= -ENOENT
)
6101 log_debug_errno(r
, "Unable to determine whether /sysusr/usr is a mount point, assuming it is not: %m");
6103 arg_root
= strdup("/sysroot");
6105 arg_root
= strdup("/sysusr");
6110 arg_node
= argc
> optind
? argv
[optind
] : NULL
;
6112 if (IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
) && !arg_node
&& !arg_image
)
6113 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6114 "A path to a device node or loopback file must be specified when --empty=force, --empty=require or --empty=create are used.");
6116 if (arg_split
&& !arg_node
)
6117 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6118 "A path to a loopback file must be specified when --split is used.");
6120 if (arg_tpm2_pcr_mask
== UINT32_MAX
)
6121 arg_tpm2_pcr_mask
= TPM2_PCR_MASK_DEFAULT
;
6122 if (arg_tpm2_public_key_pcr_mask
== UINT32_MAX
)
6123 arg_tpm2_public_key_pcr_mask
= UINT32_C(1) << TPM_PCR_INDEX_KERNEL_IMAGE
;
6125 if (arg_pretty
< 0 && isatty(STDOUT_FILENO
))
6131 static int parse_proc_cmdline_factory_reset(void) {
6135 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
6138 if (!in_initrd()) /* Never honour kernel command line factory reset request outside of the initrd */
6141 r
= proc_cmdline_get_bool("systemd.factory_reset", &b
);
6143 return log_error_errno(r
, "Failed to parse systemd.factory_reset kernel command line argument: %m");
6145 arg_factory_reset
= b
;
6148 log_notice("Honouring factory reset requested via kernel command line.");
6154 static int parse_efi_variable_factory_reset(void) {
6155 _cleanup_free_
char *value
= NULL
;
6158 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
6161 if (!in_initrd()) /* Never honour EFI variable factory reset request outside of the initrd */
6164 r
= efi_get_variable_string(EFI_SYSTEMD_VARIABLE(FactoryReset
), &value
);
6165 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
6168 return log_error_errno(r
, "Failed to read EFI variable FactoryReset: %m");
6170 r
= parse_boolean(value
);
6172 return log_error_errno(r
, "Failed to parse EFI variable FactoryReset: %m");
6174 arg_factory_reset
= r
;
6176 log_notice("Factory reset requested via EFI variable FactoryReset.");
6181 static int remove_efi_variable_factory_reset(void) {
6184 r
= efi_set_variable(EFI_SYSTEMD_VARIABLE(FactoryReset
), NULL
, 0);
6185 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
6188 return log_error_errno(r
, "Failed to remove EFI variable FactoryReset: %m");
6190 log_info("Successfully unset EFI variable FactoryReset.");
6194 static int acquire_root_devno(
6201 _cleanup_free_
char *found_path
= NULL
;
6202 dev_t devno
, fd_devno
= MODE_INVALID
;
6203 _cleanup_close_
int fd
= -EBADF
;
6211 fd
= chase_and_open(p
, root
, CHASE_PREFIX_ROOT
, mode
, &found_path
);
6215 if (fstat(fd
, &st
) < 0)
6218 if (S_ISREG(st
.st_mode
)) {
6219 *ret
= TAKE_PTR(found_path
);
6220 *ret_fd
= TAKE_FD(fd
);
6224 if (S_ISBLK(st
.st_mode
)) {
6225 /* Refuse referencing explicit block devices if a root dir is specified, after all we should
6226 * not be able to leave the image the root path constrains us to. */
6230 fd_devno
= devno
= st
.st_rdev
;
6231 } else if (S_ISDIR(st
.st_mode
)) {
6234 if (major(devno
) == 0) {
6235 r
= btrfs_get_block_device_fd(fd
, &devno
);
6236 if (r
== -ENOTTY
) /* not btrfs */
6244 /* From dm-crypt to backing partition */
6245 r
= block_get_originating(devno
, &devno
);
6247 log_debug_errno(r
, "Device '%s' has no dm-crypt/dm-verity device, no need to look for underlying block device.", p
);
6249 log_debug_errno(r
, "Failed to find underlying block device for '%s', ignoring: %m", p
);
6251 /* From partition to whole disk containing it */
6252 r
= block_get_whole_disk(devno
, &devno
);
6254 log_debug_errno(r
, "Failed to find whole disk block device for '%s', ignoring: %m", p
);
6256 r
= devname_from_devnum(S_IFBLK
, devno
, ret
);
6258 return log_debug_errno(r
, "Failed to determine canonical path for '%s': %m", p
);
6260 /* Only if we still look at the same block device we can reuse the fd. Otherwise return an
6261 * invalidated fd. */
6262 *ret_fd
= fd_devno
!= MODE_INVALID
&& fd_devno
== devno
? TAKE_FD(fd
) : -1;
6266 static int find_root(Context
*context
) {
6267 _cleanup_free_
char *device
= NULL
;
6273 if (arg_empty
== EMPTY_CREATE
) {
6274 _cleanup_close_
int fd
= -EBADF
;
6275 _cleanup_free_
char *s
= NULL
;
6277 s
= strdup(arg_node
);
6281 fd
= open(arg_node
, O_RDONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOFOLLOW
, 0666);
6283 return log_error_errno(errno
, "Failed to create '%s': %m", arg_node
);
6285 context
->node
= TAKE_PTR(s
);
6286 context
->node_is_our_file
= true;
6287 context
->backing_fd
= TAKE_FD(fd
);
6291 /* Note that we don't specify a root argument here: if the user explicitly configured a node
6292 * we'll take it relative to the host, not the image */
6293 r
= acquire_root_devno(arg_node
, NULL
, O_RDONLY
|O_CLOEXEC
, &context
->node
, &context
->backing_fd
);
6295 return btrfs_log_dev_root(LOG_ERR
, r
, arg_node
);
6297 return log_error_errno(r
, "Failed to open file or determine backing device of %s: %m", arg_node
);
6302 assert(IN_SET(arg_empty
, EMPTY_REFUSE
, EMPTY_ALLOW
));
6304 /* If the root mount has been replaced by some form of volatile file system (overlayfs), the
6305 * original root block device node is symlinked in /run/systemd/volatile-root. Let's read that
6307 r
= readlink_malloc("/run/systemd/volatile-root", &device
);
6308 if (r
== -ENOENT
) { /* volatile-root not found */
6309 /* Let's search for the root device. We look for two cases here: first in /, and then in /usr. The
6310 * latter we check for cases where / is a tmpfs and only /usr is an actual persistent block device
6311 * (think: volatile setups) */
6313 FOREACH_STRING(p
, "/", "/usr") {
6315 r
= acquire_root_devno(p
, arg_root
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, &context
->node
,
6316 &context
->backing_fd
);
6319 return btrfs_log_dev_root(LOG_ERR
, r
, p
);
6321 return log_error_errno(r
, "Failed to determine backing device of %s: %m", p
);
6326 return log_error_errno(r
, "Failed to read symlink /run/systemd/volatile-root: %m");
6328 r
= acquire_root_devno(device
, NULL
, O_RDONLY
|O_CLOEXEC
, &context
->node
, &context
->backing_fd
);
6330 return btrfs_log_dev_root(LOG_ERR
, r
, device
);
6332 return log_error_errno(r
, "Failed to open file or determine backing device of %s: %m", device
);
6337 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
), "Failed to discover root block device.");
6340 static int resize_pt(int fd
, uint64_t sector_size
) {
6341 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
6344 /* After resizing the backing file we need to resize the partition table itself too, so that it takes
6345 * possession of the enlarged backing file. For this it suffices to open the device with libfdisk and
6346 * immediately write it again, with no changes. */
6348 r
= fdisk_new_context_fd(fd
, /* read_only= */ false, sector_size
, &c
);
6350 return log_error_errno(r
, "Failed to open device '%s': %m", FORMAT_PROC_FD_PATH(fd
));
6352 r
= fdisk_has_label(c
);
6354 return log_error_errno(r
, "Failed to determine whether disk '%s' has a disk label: %m", FORMAT_PROC_FD_PATH(fd
));
6356 log_debug("Not resizing partition table, as there currently is none.");
6360 r
= fdisk_write_disklabel(c
);
6362 return log_error_errno(r
, "Failed to write resized partition table: %m");
6364 log_info("Resized partition table.");
6368 static int resize_backing_fd(
6369 const char *node
, /* The primary way we access the disk image to operate on */
6370 int *fd
, /* An O_RDONLY fd referring to that inode */
6371 const char *backing_file
, /* If the above refers to a loopback device, the backing regular file for that, which we can grow */
6372 LoopDevice
*loop_device
,
6373 uint64_t sector_size
) {
6375 _cleanup_close_
int writable_fd
= -EBADF
;
6376 uint64_t current_size
;
6383 if (arg_size
== UINT64_MAX
) /* Nothing to do */
6387 /* Open the file if we haven't opened it yet. Note that we open it read-only here, just to
6388 * keep a reference to the file we can pass around. */
6389 *fd
= open(node
, O_RDONLY
|O_CLOEXEC
);
6391 return log_error_errno(errno
, "Failed to open '%s' in order to adjust size: %m", node
);
6394 if (fstat(*fd
, &st
) < 0)
6395 return log_error_errno(errno
, "Failed to stat '%s': %m", node
);
6397 if (S_ISBLK(st
.st_mode
)) {
6399 return log_error_errno(SYNTHETIC_ERRNO(EBADF
), "Cannot resize block device '%s'.", node
);
6401 assert(loop_device
);
6403 if (ioctl(*fd
, BLKGETSIZE64
, ¤t_size
) < 0)
6404 return log_error_errno(errno
, "Failed to determine size of block device %s: %m", node
);
6406 r
= stat_verify_regular(&st
);
6408 return log_error_errno(r
, "Specified path '%s' is not a regular file or loopback block device, cannot resize: %m", node
);
6410 assert(!backing_file
);
6411 assert(!loop_device
);
6412 current_size
= st
.st_size
;
6415 if (current_size
>= arg_size
) {
6416 log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)",
6417 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
6421 if (S_ISBLK(st
.st_mode
)) {
6422 assert(backing_file
);
6424 /* This is a loopback device. We can't really grow those directly, but we can grow the
6425 * backing file, hence let's do that. */
6427 writable_fd
= open(backing_file
, O_WRONLY
|O_CLOEXEC
|O_NONBLOCK
);
6428 if (writable_fd
< 0)
6429 return log_error_errno(errno
, "Failed to open backing file '%s': %m", backing_file
);
6431 if (fstat(writable_fd
, &st
) < 0)
6432 return log_error_errno(errno
, "Failed to stat() backing file '%s': %m", backing_file
);
6434 r
= stat_verify_regular(&st
);
6436 return log_error_errno(r
, "Backing file '%s' of block device is not a regular file: %m", backing_file
);
6438 if ((uint64_t) st
.st_size
!= current_size
)
6439 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6440 "Size of backing file '%s' of loopback block device '%s' don't match, refusing.",
6441 node
, backing_file
);
6443 assert(S_ISREG(st
.st_mode
));
6444 assert(!backing_file
);
6446 /* The file descriptor is read-only. In order to grow the file we need to have a writable fd. We
6447 * reopen the file for that temporarily. We keep the writable fd only open for this operation though,
6448 * as fdisk can't accept it anyway. */
6450 writable_fd
= fd_reopen(*fd
, O_WRONLY
|O_CLOEXEC
);
6451 if (writable_fd
< 0)
6452 return log_error_errno(writable_fd
, "Failed to reopen backing file '%s' writable: %m", node
);
6456 if (fallocate(writable_fd
, 0, 0, arg_size
) < 0) {
6457 if (!ERRNO_IS_NOT_SUPPORTED(errno
))
6458 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by allocation: %m",
6459 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
6461 /* Fallback to truncation, if fallocate() is not supported. */
6462 log_debug("Backing file system does not support fallocate(), falling back to ftruncate().");
6464 if (current_size
== 0) /* Likely regular file just created by us */
6465 log_info("Allocated %s for '%s'.", FORMAT_BYTES(arg_size
), node
);
6467 log_info("File '%s' grown from %s to %s by allocation.",
6468 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
6474 if (ftruncate(writable_fd
, arg_size
) < 0)
6475 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by truncation: %m",
6476 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
6478 if (current_size
== 0) /* Likely regular file just created by us */
6479 log_info("Sized '%s' to %s.", node
, FORMAT_BYTES(arg_size
));
6481 log_info("File '%s' grown from %s to %s by truncation.",
6482 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
6485 r
= resize_pt(writable_fd
, sector_size
);
6490 r
= loop_device_refresh_size(loop_device
, UINT64_MAX
, arg_size
);
6492 return log_error_errno(r
, "Failed to update loop device size: %m");
6498 static int determine_auto_size(Context
*c
) {
6503 sum
= round_up_size(GPT_METADATA_SIZE
, 4096);
6505 LIST_FOREACH(partitions
, p
, c
->partitions
) {
6511 m
= partition_min_size_with_padding(c
, p
);
6512 if (m
> UINT64_MAX
- sum
)
6513 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Image would grow too large, refusing.");
6518 if (c
->total
!= UINT64_MAX
)
6519 /* Image already allocated? Then show its size. */
6520 log_info("Automatically determined minimal disk image size as %s, current image size is %s.",
6521 FORMAT_BYTES(sum
), FORMAT_BYTES(c
->total
));
6523 /* If the image is being created right now, then it has no previous size, suppress any comment about it hence. */
6524 log_info("Automatically determined minimal disk image size as %s.",
6531 static int run(int argc
, char *argv
[]) {
6532 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
6533 _cleanup_(umount_and_rmdir_and_freep
) char *mounted_dir
= NULL
;
6534 _cleanup_(context_freep
) Context
* context
= NULL
;
6535 bool node_is_our_loop
= false;
6538 log_show_color(true);
6539 log_parse_environment();
6542 r
= parse_argv(argc
, argv
);
6546 r
= parse_proc_cmdline_factory_reset();
6550 r
= parse_efi_variable_factory_reset();
6554 #if HAVE_LIBCRYPTSETUP
6555 cryptsetup_enable_logging(NULL
);
6561 /* Mount this strictly read-only: we shall modify the partition table, not the file
6563 r
= mount_image_privately_interactively(
6566 DISSECT_IMAGE_MOUNT_READ_ONLY
|
6567 (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) */
6568 DISSECT_IMAGE_GPT_ONLY
|
6569 DISSECT_IMAGE_RELAX_VAR_CHECK
|
6570 DISSECT_IMAGE_USR_NO_ROOT
|
6571 DISSECT_IMAGE_REQUIRE_ROOT
,
6573 /* ret_dir_fd= */ NULL
,
6578 arg_root
= strdup(mounted_dir
);
6583 arg_node
= strdup(loop_device
->node
);
6587 /* Remember that the device we are about to manipulate is actually the one we
6588 * allocated here, and thus to increase its backing file we know what to do */
6589 node_is_our_loop
= true;
6593 context
= context_new(arg_seed
);
6597 strv_uniq(arg_definitions
);
6599 r
= context_read_definitions(context
, arg_definitions
, arg_root
);
6603 r
= find_root(context
);
6607 if (arg_size
!= UINT64_MAX
) {
6608 r
= resize_backing_fd(
6610 &context
->backing_fd
,
6611 node_is_our_loop
? arg_image
: NULL
,
6612 node_is_our_loop
? loop_device
: NULL
,
6613 context
->sector_size
);
6618 r
= context_load_partition_table(context
);
6619 if (r
== -EHWPOISON
)
6620 return 77; /* Special return value which means "Not GPT, so not doing anything". This isn't
6621 * really an error when called at boot. */
6624 context
->from_scratch
= r
> 0; /* Starting from scratch */
6626 if (arg_can_factory_reset
) {
6627 r
= context_can_factory_reset(context
);
6631 return EXIT_FAILURE
;
6636 r
= context_factory_reset(context
);
6640 /* We actually did a factory reset! */
6641 r
= remove_efi_variable_factory_reset();
6645 /* Reload the reduced partition table */
6646 context_unload_partition_table(context
);
6647 r
= context_load_partition_table(context
);
6652 r
= context_read_seed(context
, arg_root
);
6656 /* Make sure each partition has a unique UUID and unique label */
6657 r
= context_acquire_partition_uuids_and_labels(context
);
6661 r
= context_minimize(context
);
6665 /* Open all files to copy blocks from now, since we want to take their size into consideration */
6666 r
= context_open_copy_block_paths(
6668 loop_device
? loop_device
->devno
: /* if --image= is specified, only allow partitions on the loopback device */
6669 arg_root
&& !arg_image
? 0 : /* if --root= is specified, don't accept any block device */
6670 (dev_t
) -1); /* if neither is specified, make no restrictions */
6674 if (arg_size_auto
) {
6675 r
= determine_auto_size(context
);
6679 /* Flush out everything again, and let's grow the file first, then start fresh */
6680 context_unload_partition_table(context
);
6682 assert(arg_size
!= UINT64_MAX
);
6683 r
= resize_backing_fd(
6685 &context
->backing_fd
,
6686 node_is_our_loop
? arg_image
: NULL
,
6687 node_is_our_loop
? loop_device
: NULL
,
6688 context
->sector_size
);
6692 r
= context_load_partition_table(context
);
6697 /* First try to fit new partitions in, dropping by priority until it fits */
6699 uint64_t largest_free_area
;
6701 if (context_allocate_partitions(context
, &largest_free_area
))
6702 break; /* Success! */
6704 if (!context_drop_or_foreignize_one_priority(context
)) {
6705 r
= log_error_errno(SYNTHETIC_ERRNO(ENOSPC
),
6706 "Can't fit requested partitions into available free space (%s), refusing.",
6707 FORMAT_BYTES(largest_free_area
));
6708 determine_auto_size(context
);
6713 /* Now assign free space according to the weight logic */
6714 r
= context_grow_partitions(context
);
6718 /* Now calculate where each new partition gets placed */
6719 context_place_partitions(context
);
6721 (void) context_dump(context
, /*late=*/ false);
6723 r
= context_write_partition_table(context
);
6727 r
= context_split(context
);
6731 (void) context_dump(context
, /*late=*/ true);
6733 context
->node
= mfree(context
->node
);
6735 LIST_FOREACH(partitions
, p
, context
->partitions
)
6736 p
->split_path
= mfree(p
->split_path
);
6741 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);