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"
22 #include "chase-symlinks.h"
23 #include "conf-files.h"
24 #include "conf-parser.h"
25 #include "cryptsetup-util.h"
27 #include "devnum-util.h"
28 #include "dirent-util.h"
30 #include "errno-util.h"
32 #include "fdisk-util.h"
34 #include "format-table.h"
35 #include "format-util.h"
37 #include "glyph-util.h"
39 #include "hexdecoct.h"
41 #include "id128-util.h"
44 #include "loop-util.h"
45 #include "main-func.h"
47 #include "mkfs-util.h"
48 #include "mount-util.h"
49 #include "mountpoint-util.h"
50 #include "parse-argument.h"
51 #include "parse-helpers.h"
52 #include "pretty-print.h"
53 #include "proc-cmdline.h"
54 #include "process-util.h"
55 #include "random-util.h"
56 #include "resize-fs.h"
57 #include "sort-util.h"
58 #include "specifier.h"
59 #include "stdio-util.h"
60 #include "string-table.h"
61 #include "string-util.h"
63 #include "sync-util.h"
64 #include "terminal-util.h"
65 #include "tpm2-util.h"
66 #include "user-util.h"
69 /* If not configured otherwise use a minimal partition size of 10M */
70 #define DEFAULT_MIN_SIZE (10*1024*1024)
72 /* Hard lower limit for new partition sizes */
73 #define HARD_MIN_SIZE 4096
75 /* libfdisk takes off slightly more than 1M of the disk size when creating a GPT disk label */
76 #define GPT_METADATA_SIZE (1044*1024)
78 /* LUKS2 takes off 16M of the partition size with its metadata by default */
79 #define LUKS2_METADATA_SIZE (16*1024*1024)
81 /* Note: When growing and placing new partitions we always align to 4K sector size. It's how newer hard disks
82 * are designed, and if everything is aligned to that performance is best. And for older hard disks with 512B
83 * sector size devices were generally assumed to have an even number of sectors, hence at the worst we'll
84 * waste 3K per partition, which is probably fine. */
87 EMPTY_REFUSE
, /* refuse empty disks, never create a partition table */
88 EMPTY_ALLOW
, /* allow empty disks, create partition table if necessary */
89 EMPTY_REQUIRE
, /* require an empty disk, create a partition table */
90 EMPTY_FORCE
, /* make disk empty, erase everything, create a partition table always */
91 EMPTY_CREATE
, /* create disk as loopback file, create a partition table always */
92 } arg_empty
= EMPTY_REFUSE
;
94 static bool arg_dry_run
= true;
95 static const char *arg_node
= NULL
;
96 static char *arg_root
= NULL
;
97 static char *arg_image
= NULL
;
98 static char *arg_definitions
= NULL
;
99 static bool arg_discard
= true;
100 static bool arg_can_factory_reset
= false;
101 static int arg_factory_reset
= -1;
102 static sd_id128_t arg_seed
= SD_ID128_NULL
;
103 static bool arg_randomize
= false;
104 static int arg_pretty
= -1;
105 static uint64_t arg_size
= UINT64_MAX
;
106 static bool arg_size_auto
= false;
107 static JsonFormatFlags arg_json_format_flags
= JSON_FORMAT_OFF
;
108 static PagerFlags arg_pager_flags
= 0;
109 static bool arg_legend
= true;
110 static void *arg_key
= NULL
;
111 static size_t arg_key_size
= 0;
112 static char *arg_tpm2_device
= NULL
;
113 static uint32_t arg_tpm2_pcr_mask
= UINT32_MAX
;
115 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
116 STATIC_DESTRUCTOR_REGISTER(arg_image
, freep
);
117 STATIC_DESTRUCTOR_REGISTER(arg_definitions
, freep
);
118 STATIC_DESTRUCTOR_REGISTER(arg_key
, erase_and_freep
);
119 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device
, freep
);
121 typedef struct Partition Partition
;
122 typedef struct FreeArea FreeArea
;
123 typedef struct Context Context
;
125 typedef enum EncryptMode
{
129 ENCRYPT_KEY_FILE_TPM2
,
131 _ENCRYPT_MODE_INVALID
= -EINVAL
,
135 char *definition_path
;
136 char **drop_in_files
;
138 sd_id128_t type_uuid
;
139 sd_id128_t current_uuid
, new_uuid
;
140 char *current_label
, *new_label
;
146 uint32_t weight
, padding_weight
;
148 uint64_t current_size
, new_size
;
149 uint64_t size_min
, size_max
;
151 uint64_t current_padding
, new_padding
;
152 uint64_t padding_min
, padding_max
;
157 struct fdisk_partition
*current_partition
;
158 struct fdisk_partition
*new_partition
;
159 FreeArea
*padding_area
;
160 FreeArea
*allocated_to_area
;
162 char *copy_blocks_path
;
163 bool copy_blocks_auto
;
165 uint64_t copy_blocks_size
;
169 char **make_directories
;
177 LIST_FIELDS(Partition
, partitions
);
180 #define PARTITION_IS_FOREIGN(p) (!(p)->definition_path)
181 #define PARTITION_EXISTS(p) (!!(p)->current_partition)
190 LIST_HEAD(Partition
, partitions
);
193 FreeArea
**free_areas
;
196 uint64_t start
, end
, total
;
198 struct fdisk_context
*fdisk_context
;
199 uint64_t sector_size
;
205 static const char *encrypt_mode_table
[_ENCRYPT_MODE_MAX
] = {
206 [ENCRYPT_OFF
] = "off",
207 [ENCRYPT_KEY_FILE
] = "key-file",
208 [ENCRYPT_TPM2
] = "tpm2",
209 [ENCRYPT_KEY_FILE_TPM2
] = "key-file+tpm2",
212 #if HAVE_LIBCRYPTSETUP
213 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(encrypt_mode
, EncryptMode
, ENCRYPT_KEY_FILE
);
215 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(encrypt_mode
, EncryptMode
, ENCRYPT_KEY_FILE
);
219 static uint64_t round_down_size(uint64_t v
, uint64_t p
) {
223 static uint64_t round_up_size(uint64_t v
, uint64_t p
) {
225 v
= DIV_ROUND_UP(v
, p
);
227 if (v
> UINT64_MAX
/ p
)
228 return UINT64_MAX
; /* overflow */
233 static Partition
*partition_new(void) {
236 p
= new(Partition
, 1);
243 .current_size
= UINT64_MAX
,
244 .new_size
= UINT64_MAX
,
245 .size_min
= UINT64_MAX
,
246 .size_max
= UINT64_MAX
,
247 .current_padding
= UINT64_MAX
,
248 .new_padding
= UINT64_MAX
,
249 .padding_min
= UINT64_MAX
,
250 .padding_max
= UINT64_MAX
,
251 .partno
= UINT64_MAX
,
252 .offset
= UINT64_MAX
,
253 .copy_blocks_fd
= -1,
254 .copy_blocks_size
= UINT64_MAX
,
263 static Partition
* partition_free(Partition
*p
) {
267 free(p
->current_label
);
269 free(p
->definition_path
);
270 strv_free(p
->drop_in_files
);
272 if (p
->current_partition
)
273 fdisk_unref_partition(p
->current_partition
);
274 if (p
->new_partition
)
275 fdisk_unref_partition(p
->new_partition
);
277 free(p
->copy_blocks_path
);
278 safe_close(p
->copy_blocks_fd
);
281 strv_free(p
->copy_files
);
282 strv_free(p
->make_directories
);
287 static Partition
* partition_unlink_and_free(Context
*context
, Partition
*p
) {
291 LIST_REMOVE(partitions
, context
->partitions
, p
);
293 assert(context
->n_partitions
> 0);
294 context
->n_partitions
--;
296 return partition_free(p
);
299 DEFINE_TRIVIAL_CLEANUP_FUNC(Partition
*, partition_free
);
301 static Context
*context_new(sd_id128_t seed
) {
304 context
= new(Context
, 1);
308 *context
= (Context
) {
318 static void context_free_free_areas(Context
*context
) {
321 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
322 free(context
->free_areas
[i
]);
324 context
->free_areas
= mfree(context
->free_areas
);
325 context
->n_free_areas
= 0;
328 static Context
*context_free(Context
*context
) {
332 while (context
->partitions
)
333 partition_unlink_and_free(context
, context
->partitions
);
334 assert(context
->n_partitions
== 0);
336 context_free_free_areas(context
);
338 if (context
->fdisk_context
)
339 fdisk_unref_context(context
->fdisk_context
);
341 return mfree(context
);
344 DEFINE_TRIVIAL_CLEANUP_FUNC(Context
*, context_free
);
346 static int context_add_free_area(
354 assert(!after
|| !after
->padding_area
);
356 if (!GREEDY_REALLOC(context
->free_areas
, context
->n_free_areas
+ 1))
359 a
= new(FreeArea
, 1);
368 context
->free_areas
[context
->n_free_areas
++] = a
;
371 after
->padding_area
= a
;
376 static bool context_drop_one_priority(Context
*context
) {
377 int32_t priority
= 0;
380 LIST_FOREACH(partitions
, p
, context
->partitions
) {
383 if (p
->priority
< priority
)
385 if (p
->priority
== priority
) {
386 exists
= exists
|| PARTITION_EXISTS(p
);
390 priority
= p
->priority
;
391 exists
= PARTITION_EXISTS(p
);
394 /* Refuse to drop partitions with 0 or negative priorities or partitions of priorities that have at
395 * least one existing priority */
396 if (priority
<= 0 || exists
)
399 LIST_FOREACH(partitions
, p
, context
->partitions
) {
400 if (p
->priority
< priority
)
407 log_info("Can't fit partition %s of priority %" PRIi32
", dropping.", p
->definition_path
, p
->priority
);
413 static uint64_t partition_min_size(Context
*context
, const Partition
*p
) {
419 /* Calculate the disk space we really need at minimum for this partition. If the partition already
420 * exists the current size is what we really need. If it doesn't exist yet refuse to allocate less
423 * DEFAULT_MIN_SIZE is the default SizeMin= we configure if nothing else is specified. */
425 if (PARTITION_IS_FOREIGN(p
)) {
426 /* Don't allow changing size of partitions not managed by us */
427 assert(p
->current_size
!= UINT64_MAX
);
428 return p
->current_size
;
431 sz
= p
->current_size
!= UINT64_MAX
? p
->current_size
: HARD_MIN_SIZE
;
433 if (!PARTITION_EXISTS(p
)) {
436 if (p
->encrypt
!= ENCRYPT_OFF
)
437 d
+= round_up_size(LUKS2_METADATA_SIZE
, context
->grain_size
);
439 if (p
->copy_blocks_size
!= UINT64_MAX
)
440 d
+= round_up_size(p
->copy_blocks_size
, context
->grain_size
);
441 else if (p
->format
|| p
->encrypt
!= ENCRYPT_OFF
) {
444 /* If we shall synthesize a file system, take minimal fs size into account (assumed to be 4K if not known) */
445 f
= p
->format
? round_up_size(minimal_size_by_fs_name(p
->format
), context
->grain_size
) : UINT64_MAX
;
446 d
+= f
== UINT64_MAX
? context
->grain_size
: f
;
453 return MAX(round_up_size(p
->size_min
!= UINT64_MAX
? p
->size_min
: DEFAULT_MIN_SIZE
, context
->grain_size
), sz
);
456 static uint64_t partition_max_size(const Context
*context
, const Partition
*p
) {
459 /* Calculate how large the partition may become at max. This is generally the configured maximum
460 * size, except when it already exists and is larger than that. In that case it's the existing size,
461 * since we never want to shrink partitions. */
466 if (PARTITION_IS_FOREIGN(p
)) {
467 /* Don't allow changing size of partitions not managed by us */
468 assert(p
->current_size
!= UINT64_MAX
);
469 return p
->current_size
;
472 sm
= round_down_size(p
->size_max
, context
->grain_size
);
474 if (p
->current_size
!= UINT64_MAX
)
475 return MAX(p
->current_size
, sm
);
480 static uint64_t partition_min_size_with_padding(Context
*context
, const Partition
*p
) {
483 /* Calculate the disk space we need for this partition plus any free space coming after it. This
484 * takes user configured padding into account as well as any additional whitespace needed to align
485 * the next partition to 4K again. */
490 sz
= partition_min_size(context
, p
);
492 if (p
->padding_min
!= UINT64_MAX
)
493 sz
+= p
->padding_min
;
495 if (PARTITION_EXISTS(p
)) {
496 /* If the partition wasn't aligned, add extra space so that any we might add will be aligned */
497 assert(p
->offset
!= UINT64_MAX
);
498 return round_up_size(p
->offset
+ sz
, context
->grain_size
) - p
->offset
;
501 /* If this is a new partition we'll place it aligned, hence we just need to round up the required size here */
502 return round_up_size(sz
, context
->grain_size
);
505 static uint64_t free_area_available(const FreeArea
*a
) {
508 /* Determines how much of this free area is not allocated yet */
510 assert(a
->size
>= a
->allocated
);
511 return a
->size
- a
->allocated
;
514 static uint64_t free_area_available_for_new_partitions(Context
*context
, const FreeArea
*a
) {
520 /* Similar to free_area_available(), but takes into account that the required size and padding of the
521 * preceding partition is honoured. */
523 avail
= free_area_available(a
);
525 uint64_t need
, space_end
, new_end
;
527 need
= partition_min_size_with_padding(context
, a
->after
);
529 assert(a
->after
->offset
!= UINT64_MAX
);
530 assert(a
->after
->current_size
!= UINT64_MAX
);
532 /* Calculate where the free area ends, based on the offset of the partition preceding it */
533 space_end
= round_up_size(a
->after
->offset
+ a
->after
->current_size
, context
->grain_size
) + avail
;
535 /* Calculate where the partition would end when we give it as much as it needs */
536 new_end
= round_up_size(a
->after
->offset
+ need
, context
->grain_size
);
538 /* Calculate saturated difference of the two: that's how much we have free for other partitions */
539 return LESS_BY(space_end
, new_end
);
545 static int free_area_compare(FreeArea
*const *a
, FreeArea
*const*b
, Context
*context
) {
548 return CMP(free_area_available_for_new_partitions(context
, *a
),
549 free_area_available_for_new_partitions(context
, *b
));
552 static uint64_t charge_size(Context
*context
, uint64_t total
, uint64_t amount
) {
554 /* Subtract the specified amount from total, rounding up to multiple of 4K if there's room */
555 assert(amount
<= total
);
556 return LESS_BY(total
, round_up_size(amount
, context
->grain_size
));
559 static uint64_t charge_weight(uint64_t total
, uint64_t amount
) {
560 assert(amount
<= total
);
561 return total
- amount
;
564 static bool context_allocate_partitions(Context
*context
, uint64_t *ret_largest_free_area
) {
567 /* Sort free areas by size, putting smallest first */
568 typesafe_qsort_r(context
->free_areas
, context
->n_free_areas
, free_area_compare
, context
);
570 /* In any case return size of the largest free area (i.e. not the size of all free areas
572 if (ret_largest_free_area
)
573 *ret_largest_free_area
=
574 context
->n_free_areas
== 0 ? 0 :
575 free_area_available_for_new_partitions(context
, context
->free_areas
[context
->n_free_areas
-1]);
577 /* A simple first-fit algorithm. We return true if we can fit the partitions in, otherwise false. */
578 LIST_FOREACH(partitions
, p
, context
->partitions
) {
583 /* Skip partitions we already dropped or that already exist */
584 if (p
->dropped
|| PARTITION_EXISTS(p
))
587 /* How much do we need to fit? */
588 required
= partition_min_size_with_padding(context
, p
);
589 assert(required
% context
->grain_size
== 0);
591 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
592 a
= context
->free_areas
[i
];
594 if (free_area_available_for_new_partitions(context
, a
) >= required
) {
601 return false; /* 😢 Oh no! We can't fit this partition into any free area! */
603 /* Assign the partition to this free area */
604 p
->allocated_to_area
= a
;
606 /* Budget the minimal partition size */
607 a
->allocated
+= required
;
613 static int context_sum_weights(Context
*context
, FreeArea
*a
, uint64_t *ret
) {
614 uint64_t weight_sum
= 0;
620 /* Determine the sum of the weights of all partitions placed in or before the specified free area */
622 LIST_FOREACH(partitions
, p
, context
->partitions
) {
623 if (p
->padding_area
!= a
&& p
->allocated_to_area
!= a
)
626 if (p
->weight
> UINT64_MAX
- weight_sum
)
628 weight_sum
+= p
->weight
;
630 if (p
->padding_weight
> UINT64_MAX
- weight_sum
)
632 weight_sum
+= p
->padding_weight
;
639 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Combined weight of partition exceeds unsigned 64bit range, refusing.");
642 static int scale_by_weight(uint64_t value
, uint64_t weight
, uint64_t weight_sum
, uint64_t *ret
) {
643 assert(weight_sum
>= weight
);
651 if (value
> UINT64_MAX
/ weight
)
652 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Scaling by weight of partition exceeds unsigned 64bit range, refusing.");
654 *ret
= value
* weight
/ weight_sum
;
658 typedef enum GrowPartitionPhase
{
659 /* The first phase: we charge partitions which need more (according to constraints) than their weight-based share. */
662 /* The second phase: we charge partitions which need less (according to constraints) than their weight-based share. */
665 /* The third phase: we distribute what remains among the remaining partitions, according to the weights */
668 _GROW_PARTITION_PHASE_MAX
,
669 } GrowPartitionPhase
;
671 static int context_grow_partitions_phase(
674 GrowPartitionPhase phase
,
676 uint64_t *weight_sum
) {
683 /* Now let's look at the intended weights and adjust them taking the minimum space assignments into
684 * account. i.e. if a partition has a small weight but a high minimum space value set it should not
685 * get any additional room from the left-overs. Similar, if two partitions have the same weight they
686 * should get the same space if possible, even if one has a smaller minimum size than the other. */
687 LIST_FOREACH(partitions
, p
, context
->partitions
) {
689 /* Look only at partitions associated with this free area, i.e. immediately
690 * preceding it, or allocated into it */
691 if (p
->allocated_to_area
!= a
&& p
->padding_area
!= a
)
694 if (p
->new_size
== UINT64_MAX
) {
695 bool charge
= false, try_again
= false;
696 uint64_t share
, rsz
, xsz
;
698 /* Calculate how much this space this partition needs if everyone would get
699 * the weight based share */
700 r
= scale_by_weight(*span
, p
->weight
, *weight_sum
, &share
);
704 rsz
= partition_min_size(context
, p
);
705 xsz
= partition_max_size(context
, p
);
707 if (phase
== PHASE_OVERCHARGE
&& rsz
> share
) {
708 /* This partition needs more than its calculated share. Let's assign
709 * it that, and take this partition out of all calculations and start
713 charge
= try_again
= true;
715 } else if (phase
== PHASE_UNDERCHARGE
&& xsz
!= UINT64_MAX
&& xsz
< share
) {
716 /* This partition accepts less than its calculated
717 * share. Let's assign it that, and take this partition out
718 * of all calculations and start again. */
721 charge
= try_again
= true;
723 } else if (phase
== PHASE_DISTRIBUTE
) {
724 /* This partition can accept its calculated share. Let's
725 * assign it. There's no need to restart things here since
726 * assigning this shouldn't impact the shares of the other
729 if (PARTITION_IS_FOREIGN(p
))
730 /* Never change of foreign partitions (i.e. those we don't manage) */
731 p
->new_size
= p
->current_size
;
733 p
->new_size
= MAX(round_down_size(share
, context
->grain_size
), rsz
);
739 *span
= charge_size(context
, *span
, p
->new_size
);
740 *weight_sum
= charge_weight(*weight_sum
, p
->weight
);
744 return 0; /* try again */
747 if (p
->new_padding
== UINT64_MAX
) {
748 bool charge
= false, try_again
= false;
751 r
= scale_by_weight(*span
, p
->padding_weight
, *weight_sum
, &share
);
755 if (phase
== PHASE_OVERCHARGE
&& p
->padding_min
!= UINT64_MAX
&& p
->padding_min
> share
) {
756 p
->new_padding
= p
->padding_min
;
757 charge
= try_again
= true;
758 } else if (phase
== PHASE_UNDERCHARGE
&& p
->padding_max
!= UINT64_MAX
&& p
->padding_max
< share
) {
759 p
->new_padding
= p
->padding_max
;
760 charge
= try_again
= true;
761 } else if (phase
== PHASE_DISTRIBUTE
) {
763 p
->new_padding
= round_down_size(share
, context
->grain_size
);
764 if (p
->padding_min
!= UINT64_MAX
&& p
->new_padding
< p
->padding_min
)
765 p
->new_padding
= p
->padding_min
;
771 *span
= charge_size(context
, *span
, p
->new_padding
);
772 *weight_sum
= charge_weight(*weight_sum
, p
->padding_weight
);
776 return 0; /* try again */
783 static int context_grow_partitions_on_free_area(Context
*context
, FreeArea
*a
) {
784 uint64_t weight_sum
= 0, span
;
790 r
= context_sum_weights(context
, a
, &weight_sum
);
794 /* Let's calculate the total area covered by this free area and the partition before it */
797 assert(a
->after
->offset
!= UINT64_MAX
);
798 assert(a
->after
->current_size
!= UINT64_MAX
);
800 span
+= round_up_size(a
->after
->offset
+ a
->after
->current_size
, context
->grain_size
) - a
->after
->offset
;
803 for (GrowPartitionPhase phase
= 0; phase
< _GROW_PARTITION_PHASE_MAX
;) {
804 r
= context_grow_partitions_phase(context
, a
, phase
, &span
, &weight_sum
);
807 if (r
== 0) /* not done yet, re-run this phase */
810 phase
++; /* got to next phase */
813 /* We still have space left over? Donate to preceding partition if we have one */
814 if (span
> 0 && a
->after
&& !PARTITION_IS_FOREIGN(a
->after
)) {
817 assert(a
->after
->new_size
!= UINT64_MAX
);
819 /* Calculate new size and align (but ensure this doesn't shrink the size) */
820 m
= MAX(a
->after
->new_size
, round_down_size(a
->after
->new_size
+ span
, context
->grain_size
));
822 xsz
= partition_max_size(context
, a
->after
);
823 if (xsz
!= UINT64_MAX
&& m
> xsz
)
826 span
= charge_size(context
, span
, m
- a
->after
->new_size
);
827 a
->after
->new_size
= m
;
830 /* What? Even still some space left (maybe because there was no preceding partition, or it had a
831 * size limit), then let's donate it to whoever wants it. */
833 LIST_FOREACH(partitions
, p
, context
->partitions
) {
836 if (p
->allocated_to_area
!= a
)
839 if (PARTITION_IS_FOREIGN(p
))
842 assert(p
->new_size
!= UINT64_MAX
);
843 m
= MAX(p
->new_size
, round_down_size(p
->new_size
+ span
, context
->grain_size
));
845 xsz
= partition_max_size(context
, p
);
846 if (xsz
!= UINT64_MAX
&& m
> xsz
)
849 span
= charge_size(context
, span
, m
- p
->new_size
);
856 /* Yuck, still no one? Then make it padding */
857 if (span
> 0 && a
->after
) {
858 assert(a
->after
->new_padding
!= UINT64_MAX
);
859 a
->after
->new_padding
+= span
;
865 static int context_grow_partitions(Context
*context
) {
870 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
871 r
= context_grow_partitions_on_free_area(context
, context
->free_areas
[i
]);
876 /* All existing partitions that have no free space after them can't change size */
877 LIST_FOREACH(partitions
, p
, context
->partitions
) {
881 if (!PARTITION_EXISTS(p
) || p
->padding_area
) {
882 /* The algorithm above must have initialized this already */
883 assert(p
->new_size
!= UINT64_MAX
);
887 assert(p
->new_size
== UINT64_MAX
);
888 p
->new_size
= p
->current_size
;
890 assert(p
->new_padding
== UINT64_MAX
);
891 p
->new_padding
= p
->current_padding
;
897 static void context_place_partitions(Context
*context
) {
902 /* Determine next partition number to assign */
903 LIST_FOREACH(partitions
, p
, context
->partitions
) {
904 if (!PARTITION_EXISTS(p
))
907 assert(p
->partno
!= UINT64_MAX
);
908 if (p
->partno
>= partno
)
909 partno
= p
->partno
+ 1;
912 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
913 FreeArea
*a
= context
->free_areas
[i
];
914 _unused_
uint64_t left
;
918 assert(a
->after
->offset
!= UINT64_MAX
);
919 assert(a
->after
->new_size
!= UINT64_MAX
);
920 assert(a
->after
->new_padding
!= UINT64_MAX
);
922 start
= a
->after
->offset
+ a
->after
->new_size
+ a
->after
->new_padding
;
924 start
= context
->start
;
926 start
= round_up_size(start
, context
->grain_size
);
929 LIST_FOREACH(partitions
, p
, context
->partitions
) {
930 if (p
->allocated_to_area
!= a
)
934 p
->partno
= partno
++;
936 assert(left
>= p
->new_size
);
937 start
+= p
->new_size
;
940 assert(left
>= p
->new_padding
);
941 start
+= p
->new_padding
;
942 left
-= p
->new_padding
;
947 static int config_parse_type(
949 const char *filename
,
952 unsigned section_line
,
959 sd_id128_t
*type_uuid
= data
;
965 r
= gpt_partition_type_uuid_from_string(rvalue
, type_uuid
);
967 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to parse partition type: %s", rvalue
);
972 static int config_parse_label(
974 const char *filename
,
977 unsigned section_line
,
984 _cleanup_free_
char *resolved
= NULL
;
991 /* Nota bene: the empty label is a totally valid one. Let's hence not follow our usual rule of
992 * assigning the empty string to reset to default here, but really accept it as label to set. */
994 r
= specifier_printf(rvalue
, GPT_LABEL_MAX
, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved
);
996 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
997 "Failed to expand specifiers in Label=, ignoring: %s", rvalue
);
1001 if (!utf8_is_valid(resolved
)) {
1002 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1003 "Partition label not valid UTF-8, ignoring: %s", rvalue
);
1007 r
= gpt_partition_label_valid(resolved
);
1009 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1010 "Failed to check if string is valid as GPT partition label, ignoring: \"%s\" (from \"%s\")",
1015 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1016 "Partition label too long for GPT table, ignoring: \"%s\" (from \"%s\")",
1021 free_and_replace(*label
, resolved
);
1025 static int config_parse_weight(
1027 const char *filename
,
1029 const char *section
,
1030 unsigned section_line
,
1037 uint32_t *priority
= data
, v
;
1043 r
= safe_atou32(rvalue
, &v
);
1045 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1046 "Failed to parse weight value, ignoring: %s", rvalue
);
1050 if (v
> 1000U*1000U) {
1051 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1052 "Weight needs to be in range 0…10000000, ignoring: %" PRIu32
, v
);
1060 static int config_parse_size4096(
1062 const char *filename
,
1064 const char *section
,
1065 unsigned section_line
,
1072 uint64_t *sz
= data
, parsed
;
1078 r
= parse_size(rvalue
, 1024, &parsed
);
1080 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
,
1081 "Failed to parse size value: %s", rvalue
);
1084 *sz
= round_up_size(parsed
, 4096);
1086 *sz
= round_down_size(parsed
, 4096);
1091 log_syntax(unit
, LOG_NOTICE
, filename
, line
, r
, "Rounded %s= size %" PRIu64
" %s %" PRIu64
", a multiple of 4096.",
1092 lvalue
, parsed
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), *sz
);
1097 static int config_parse_fstype(
1099 const char *filename
,
1101 const char *section
,
1102 unsigned section_line
,
1109 char **fstype
= data
;
1114 if (!filename_is_valid(rvalue
))
1115 return log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1116 "File system type is not valid, refusing: %s", rvalue
);
1118 return free_and_strdup_warn(fstype
, rvalue
);
1121 static int config_parse_copy_files(
1123 const char *filename
,
1125 const char *section
,
1126 unsigned section_line
,
1133 _cleanup_free_
char *source
= NULL
, *buffer
= NULL
, *resolved_source
= NULL
, *resolved_target
= NULL
;
1134 const char *p
= rvalue
, *target
;
1135 Partition
*partition
= data
;
1141 r
= extract_first_word(&p
, &source
, ":", EXTRACT_CUNESCAPE
|EXTRACT_DONT_COALESCE_SEPARATORS
);
1143 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to extract source path: %s", rvalue
);
1145 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0, "No argument specified: %s", rvalue
);
1149 r
= extract_first_word(&p
, &buffer
, ":", EXTRACT_CUNESCAPE
|EXTRACT_DONT_COALESCE_SEPARATORS
);
1151 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to extract target path: %s", rvalue
);
1153 target
= source
; /* No target, then it's the same as the source */
1158 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
), "Too many arguments: %s", rvalue
);
1160 r
= specifier_printf(source
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_source
);
1162 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1163 "Failed to expand specifiers in CopyFiles= source, ignoring: %s", rvalue
);
1167 r
= path_simplify_and_warn(resolved_source
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1171 r
= specifier_printf(target
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_target
);
1173 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1174 "Failed to expand specifiers in CopyFiles= target, ignoring: %s", resolved_target
);
1178 r
= path_simplify_and_warn(resolved_target
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1182 r
= strv_consume_pair(&partition
->copy_files
, TAKE_PTR(resolved_source
), TAKE_PTR(resolved_target
));
1189 static int config_parse_copy_blocks(
1191 const char *filename
,
1193 const char *section
,
1194 unsigned section_line
,
1201 _cleanup_free_
char *d
= NULL
;
1202 Partition
*partition
= data
;
1208 if (isempty(rvalue
)) {
1209 partition
->copy_blocks_path
= mfree(partition
->copy_blocks_path
);
1210 partition
->copy_blocks_auto
= false;
1214 if (streq(rvalue
, "auto")) {
1215 partition
->copy_blocks_path
= mfree(partition
->copy_blocks_path
);
1216 partition
->copy_blocks_auto
= true;
1220 r
= specifier_printf(rvalue
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &d
);
1222 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1223 "Failed to expand specifiers in CopyBlocks= source path, ignoring: %s", rvalue
);
1227 r
= path_simplify_and_warn(d
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1231 free_and_replace(partition
->copy_blocks_path
, d
);
1232 partition
->copy_blocks_auto
= false;
1236 static int config_parse_make_dirs(
1238 const char *filename
,
1240 const char *section
,
1241 unsigned section_line
,
1248 Partition
*partition
= data
;
1249 const char *p
= rvalue
;
1256 _cleanup_free_
char *word
= NULL
, *d
= NULL
;
1258 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_UNQUOTE
);
1262 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Invalid syntax, ignoring: %s", rvalue
);
1268 r
= specifier_printf(word
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &d
);
1270 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1271 "Failed to expand specifiers in MakeDirectories= parameter, ignoring: %s", word
);
1275 r
= path_simplify_and_warn(d
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1279 r
= strv_consume(&partition
->make_directories
, TAKE_PTR(d
));
1285 static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_encrypt
, encrypt_mode
, EncryptMode
, ENCRYPT_OFF
, "Invalid encryption mode");
1287 static int config_parse_gpt_flags(
1289 const char *filename
,
1291 const char *section
,
1292 unsigned section_line
,
1299 uint64_t *gpt_flags
= data
;
1305 r
= safe_atou64(rvalue
, gpt_flags
);
1307 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1308 "Failed to parse Flags= value, ignoring: %s", rvalue
);
1315 static int partition_read_definition(Partition
*p
, const char *path
, const char *const *conf_file_dirs
) {
1317 ConfigTableItem table
[] = {
1318 { "Partition", "Type", config_parse_type
, 0, &p
->type_uuid
},
1319 { "Partition", "Label", config_parse_label
, 0, &p
->new_label
},
1320 { "Partition", "UUID", config_parse_id128
, 0, &p
->new_uuid
},
1321 { "Partition", "Priority", config_parse_int32
, 0, &p
->priority
},
1322 { "Partition", "Weight", config_parse_weight
, 0, &p
->weight
},
1323 { "Partition", "PaddingWeight", config_parse_weight
, 0, &p
->padding_weight
},
1324 { "Partition", "SizeMinBytes", config_parse_size4096
, 1, &p
->size_min
},
1325 { "Partition", "SizeMaxBytes", config_parse_size4096
, -1, &p
->size_max
},
1326 { "Partition", "PaddingMinBytes", config_parse_size4096
, 1, &p
->padding_min
},
1327 { "Partition", "PaddingMaxBytes", config_parse_size4096
, -1, &p
->padding_max
},
1328 { "Partition", "FactoryReset", config_parse_bool
, 0, &p
->factory_reset
},
1329 { "Partition", "CopyBlocks", config_parse_copy_blocks
, 0, p
},
1330 { "Partition", "Format", config_parse_fstype
, 0, &p
->format
},
1331 { "Partition", "CopyFiles", config_parse_copy_files
, 0, p
},
1332 { "Partition", "MakeDirectories", config_parse_make_dirs
, 0, p
},
1333 { "Partition", "Encrypt", config_parse_encrypt
, 0, &p
->encrypt
},
1334 { "Partition", "Flags", config_parse_gpt_flags
, 0, &p
->gpt_flags
},
1335 { "Partition", "ReadOnly", config_parse_tristate
, 0, &p
->read_only
},
1336 { "Partition", "NoAuto", config_parse_tristate
, 0, &p
->no_auto
},
1337 { "Partition", "GrowFileSystem", config_parse_tristate
, 0, &p
->growfs
},
1341 _cleanup_free_
char *filename
= NULL
;
1342 const char* dropin_dirname
;
1344 r
= path_extract_filename(path
, &filename
);
1346 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);;
1348 dropin_dirname
= strjoina(filename
, ".d");
1350 r
= config_parse_many(
1351 STRV_MAKE_CONST(path
),
1355 config_item_table_lookup
, table
,
1363 if (p
->size_min
!= UINT64_MAX
&& p
->size_max
!= UINT64_MAX
&& p
->size_min
> p
->size_max
)
1364 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1365 "SizeMinBytes= larger than SizeMaxBytes=, refusing.");
1367 if (p
->padding_min
!= UINT64_MAX
&& p
->padding_max
!= UINT64_MAX
&& p
->padding_min
> p
->padding_max
)
1368 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1369 "PaddingMinBytes= larger than PaddingMaxBytes=, refusing.");
1371 if (sd_id128_is_null(p
->type_uuid
))
1372 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1373 "Type= not defined, refusing.");
1375 if ((p
->copy_blocks_path
|| p
->copy_blocks_auto
) &&
1376 (p
->format
|| !strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
)))
1377 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1378 "Format=/CopyFiles=/MakeDirectories= and CopyBlocks= cannot be combined, refusing.");
1380 if ((!strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
)) && streq_ptr(p
->format
, "swap"))
1381 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1382 "Format=swap and CopyFiles= cannot be combined, refusing.");
1384 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
)))) {
1385 /* Pick "ext4" as file system if we are configured to copy files or encrypt the device */
1386 p
->format
= strdup("ext4");
1391 /* Verity partitions are read only, let's imply the RO flag hence, unless explicitly configured otherwise. */
1392 if ((gpt_partition_type_is_root_verity(p
->type_uuid
) ||
1393 gpt_partition_type_is_usr_verity(p
->type_uuid
)) &&
1395 p
->read_only
= true;
1397 /* Default to "growfs" on, unless read-only */
1398 if (gpt_partition_type_knows_growfs(p
->type_uuid
) &&
1405 static int context_read_definitions(
1407 const char *directory
,
1410 _cleanup_strv_free_
char **files
= NULL
;
1411 Partition
*last
= NULL
;
1413 const char *const *dirs
;
1418 STRV_MAKE_CONST(directory
) :
1419 (const char* const*)CONF_PATHS_STRV("repart.d");
1421 r
= conf_files_list_strv(&files
, ".conf", directory
? NULL
: root
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, dirs
);
1423 return log_error_errno(r
, "Failed to enumerate *.conf files: %m");
1425 STRV_FOREACH(f
, files
) {
1426 _cleanup_(partition_freep
) Partition
*p
= NULL
;
1428 p
= partition_new();
1432 p
->definition_path
= strdup(*f
);
1433 if (!p
->definition_path
)
1436 r
= partition_read_definition(p
, *f
, dirs
);
1440 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, p
);
1442 context
->n_partitions
++;
1448 static int determine_current_padding(
1449 struct fdisk_context
*c
,
1450 struct fdisk_table
*t
,
1451 struct fdisk_partition
*p
,
1456 size_t n_partitions
;
1457 uint64_t offset
, next
= UINT64_MAX
;
1463 if (!fdisk_partition_has_end(p
))
1464 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition has no end!");
1466 offset
= fdisk_partition_get_end(p
);
1467 assert(offset
< UINT64_MAX
/ secsz
);
1470 n_partitions
= fdisk_table_get_nents(t
);
1471 for (size_t i
= 0; i
< n_partitions
; i
++) {
1472 struct fdisk_partition
*q
;
1475 q
= fdisk_table_get_partition(t
, i
);
1477 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1479 if (fdisk_partition_is_used(q
) <= 0)
1482 if (!fdisk_partition_has_start(q
))
1485 start
= fdisk_partition_get_start(q
);
1486 assert(start
< UINT64_MAX
/ secsz
);
1489 if (start
>= offset
&& (next
== UINT64_MAX
|| next
> start
))
1493 if (next
== UINT64_MAX
) {
1494 /* No later partition? In that case check the end of the usable area */
1495 next
= fdisk_get_last_lba(c
);
1496 assert(next
< UINT64_MAX
);
1497 next
++; /* The last LBA is one sector before the end */
1499 assert(next
< UINT64_MAX
/ secsz
);
1503 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
1506 assert(next
>= offset
);
1507 offset
= round_up_size(offset
, grainsz
);
1508 next
= round_down_size(next
, grainsz
);
1510 *ret
= LESS_BY(next
, offset
); /* Saturated subtraction, rounding might have fucked things up */
1514 static int fdisk_ask_cb(struct fdisk_context
*c
, struct fdisk_ask
*ask
, void *data
) {
1515 _cleanup_free_
char *ids
= NULL
;
1518 if (fdisk_ask_get_type(ask
) != FDISK_ASKTYPE_STRING
)
1521 ids
= new(char, SD_ID128_UUID_STRING_MAX
);
1525 r
= fdisk_ask_string_set_result(ask
, sd_id128_to_uuid_string(*(sd_id128_t
*) data
, ids
));
1533 static int fdisk_set_disklabel_id_by_uuid(struct fdisk_context
*c
, sd_id128_t id
) {
1536 r
= fdisk_set_ask(c
, fdisk_ask_cb
, &id
);
1540 r
= fdisk_set_disklabel_id(c
);
1544 return fdisk_set_ask(c
, NULL
, NULL
);
1547 static int derive_uuid(sd_id128_t base
, const char *token
, sd_id128_t
*ret
) {
1549 uint8_t md
[SHA256_DIGEST_SIZE
];
1556 /* Derive a new UUID from the specified UUID in a stable and reasonably safe way. Specifically, we
1557 * calculate the HMAC-SHA256 of the specified token string, keyed by the supplied base (typically the
1558 * machine ID). We use the machine ID as key (and not as cleartext!) of the HMAC operation since it's
1559 * the machine ID we don't want to leak. */
1561 hmac_sha256(base
.bytes
, sizeof(base
.bytes
), token
, strlen(token
), result
.md
);
1563 /* Take the first half, mark it as v4 UUID */
1564 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
1565 *ret
= id128_make_v4_uuid(result
.id
);
1569 static int context_load_partition_table(
1574 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
1575 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
1576 uint64_t left_boundary
= UINT64_MAX
, first_lba
, last_lba
, nsectors
;
1577 _cleanup_free_
char *disk_uuid_string
= NULL
;
1578 bool from_scratch
= false;
1579 sd_id128_t disk_uuid
;
1580 size_t n_partitions
;
1581 unsigned long secsz
;
1588 assert(!context
->fdisk_context
);
1589 assert(!context
->free_areas
);
1590 assert(context
->start
== UINT64_MAX
);
1591 assert(context
->end
== UINT64_MAX
);
1592 assert(context
->total
== UINT64_MAX
);
1594 c
= fdisk_new_context();
1598 /* libfdisk doesn't have an API to operate on arbitrary fds, hence reopen the fd going via the
1599 * /proc/self/fd/ magic path if we have an existing fd. Open the original file otherwise. */
1600 if (*backing_fd
< 0)
1601 r
= fdisk_assign_device(c
, node
, arg_dry_run
);
1603 r
= fdisk_assign_device(c
, FORMAT_PROC_FD_PATH(*backing_fd
), arg_dry_run
);
1604 if (r
== -EINVAL
&& arg_size_auto
) {
1607 /* libfdisk returns EINVAL if opening a file of size zero. Let's check for that, and accept
1608 * it if automatic sizing is requested. */
1610 if (*backing_fd
< 0)
1611 r
= stat(node
, &st
);
1613 r
= fstat(*backing_fd
, &st
);
1615 return log_error_errno(errno
, "Failed to stat block device '%s': %m", node
);
1617 if (S_ISREG(st
.st_mode
) && st
.st_size
== 0) {
1618 /* User the fallback values if we have no better idea */
1619 context
->sector_size
= 512;
1620 context
->grain_size
= 4096;
1621 return /* from_scratch = */ true;
1627 return log_error_errno(r
, "Failed to open device '%s': %m", node
);
1629 if (*backing_fd
< 0) {
1630 /* If we have no fd referencing the device yet, make a copy of the fd now, so that we have one */
1631 *backing_fd
= fd_reopen(fdisk_get_devfd(c
), O_RDONLY
|O_CLOEXEC
);
1632 if (*backing_fd
< 0)
1633 return log_error_errno(*backing_fd
, "Failed to duplicate fdisk fd: %m");
1635 /* Tell udev not to interfere while we are processing the device */
1636 if (flock(*backing_fd
, arg_dry_run
? LOCK_SH
: LOCK_EX
) < 0)
1637 return log_error_errno(errno
, "Failed to lock block device: %m");
1640 /* The offsets/sizes libfdisk returns to us will be in multiple of the sector size of the
1641 * device. This is typically 512, and sometimes 4096. Let's query libfdisk once for it, and then use
1642 * it for all our needs. Note that the values we use ourselves always are in bytes though, thus mean
1643 * the same thing universally. Also note that regardless what kind of sector size is in use we'll
1644 * place partitions at multiples of 4K. */
1645 secsz
= fdisk_get_sector_size(c
);
1647 /* Insist on a power of two, and that it's a multiple of 512, i.e. the traditional sector size. */
1648 if (secsz
< 512 || !ISPOWEROF2(secsz
))
1649 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Sector size %lu is not a power of two larger than 512? Refusing.", secsz
);
1651 /* Use at least 4K, and ensure it's a multiple of the sector size, regardless if that is smaller or
1653 grainsz
= secsz
< 4096 ? 4096 : secsz
;
1655 log_debug("Sector size of device is %lu bytes. Using grain size of %" PRIu64
".", secsz
, grainsz
);
1657 switch (arg_empty
) {
1660 /* Refuse empty disks, insist on an existing GPT partition table */
1661 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
1662 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has no GPT disk label, not repartitioning.", node
);
1667 /* Require an empty disk, refuse any existing partition table */
1668 r
= fdisk_has_label(c
);
1670 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", node
);
1672 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s already has a disk label, refusing.", node
);
1674 from_scratch
= true;
1678 /* Allow both an empty disk and an existing partition table, but only GPT */
1679 r
= fdisk_has_label(c
);
1681 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", node
);
1683 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
1684 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has non-GPT disk label, not repartitioning.", node
);
1686 from_scratch
= true;
1692 /* Always reinitiaize the disk, don't consider what there was on the disk before */
1693 from_scratch
= true;
1698 r
= fdisk_create_disklabel(c
, "gpt");
1700 return log_error_errno(r
, "Failed to create GPT disk label: %m");
1702 r
= derive_uuid(context
->seed
, "disk-uuid", &disk_uuid
);
1704 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
1706 r
= fdisk_set_disklabel_id_by_uuid(c
, disk_uuid
);
1708 return log_error_errno(r
, "Failed to set GPT disk label: %m");
1710 goto add_initial_free_area
;
1713 r
= fdisk_get_disklabel_id(c
, &disk_uuid_string
);
1715 return log_error_errno(r
, "Failed to get current GPT disk label UUID: %m");
1717 r
= sd_id128_from_string(disk_uuid_string
, &disk_uuid
);
1719 return log_error_errno(r
, "Failed to parse current GPT disk label UUID: %m");
1721 if (sd_id128_is_null(disk_uuid
)) {
1722 r
= derive_uuid(context
->seed
, "disk-uuid", &disk_uuid
);
1724 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
1726 r
= fdisk_set_disklabel_id(c
);
1728 return log_error_errno(r
, "Failed to set GPT disk label: %m");
1731 r
= fdisk_get_partitions(c
, &t
);
1733 return log_error_errno(r
, "Failed to acquire partition table: %m");
1735 n_partitions
= fdisk_table_get_nents(t
);
1736 for (size_t i
= 0; i
< n_partitions
; i
++) {
1737 _cleanup_free_
char *label_copy
= NULL
;
1738 Partition
*last
= NULL
;
1739 struct fdisk_partition
*p
;
1740 struct fdisk_parttype
*pt
;
1741 const char *pts
, *ids
, *label
;
1744 sd_id128_t ptid
, id
;
1747 p
= fdisk_table_get_partition(t
, i
);
1749 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1751 if (fdisk_partition_is_used(p
) <= 0)
1754 if (fdisk_partition_has_start(p
) <= 0 ||
1755 fdisk_partition_has_size(p
) <= 0 ||
1756 fdisk_partition_has_partno(p
) <= 0)
1757 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a position, size or number.");
1759 pt
= fdisk_partition_get_type(p
);
1761 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to acquire type of partition: %m");
1763 pts
= fdisk_parttype_get_string(pt
);
1765 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to acquire type of partition as string: %m");
1767 r
= sd_id128_from_string(pts
, &ptid
);
1769 return log_error_errno(r
, "Failed to parse partition type UUID %s: %m", pts
);
1771 ids
= fdisk_partition_get_uuid(p
);
1773 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a UUID.");
1775 r
= sd_id128_from_string(ids
, &id
);
1777 return log_error_errno(r
, "Failed to parse partition UUID %s: %m", ids
);
1779 label
= fdisk_partition_get_name(p
);
1780 if (!isempty(label
)) {
1781 label_copy
= strdup(label
);
1786 sz
= fdisk_partition_get_size(p
);
1787 assert(sz
<= UINT64_MAX
/secsz
);
1790 start
= fdisk_partition_get_start(p
);
1791 assert(start
<= UINT64_MAX
/secsz
);
1794 partno
= fdisk_partition_get_partno(p
);
1796 if (left_boundary
== UINT64_MAX
|| left_boundary
> start
)
1797 left_boundary
= start
;
1799 /* Assign this existing partition to the first partition of the right type that doesn't have
1800 * an existing one assigned yet. */
1801 LIST_FOREACH(partitions
, pp
, context
->partitions
) {
1804 if (!sd_id128_equal(pp
->type_uuid
, ptid
))
1807 if (!pp
->current_partition
) {
1808 pp
->current_uuid
= id
;
1809 pp
->current_size
= sz
;
1811 pp
->partno
= partno
;
1812 pp
->current_label
= TAKE_PTR(label_copy
);
1814 pp
->current_partition
= p
;
1815 fdisk_ref_partition(p
);
1817 r
= determine_current_padding(c
, t
, p
, secsz
, grainsz
, &pp
->current_padding
);
1821 if (pp
->current_padding
> 0) {
1822 r
= context_add_free_area(context
, pp
->current_padding
, pp
);
1832 /* If we have no matching definition, create a new one. */
1834 _cleanup_(partition_freep
) Partition
*np
= NULL
;
1836 np
= partition_new();
1840 np
->current_uuid
= id
;
1841 np
->type_uuid
= ptid
;
1842 np
->current_size
= sz
;
1844 np
->partno
= partno
;
1845 np
->current_label
= TAKE_PTR(label_copy
);
1847 np
->current_partition
= p
;
1848 fdisk_ref_partition(p
);
1850 r
= determine_current_padding(c
, t
, p
, secsz
, grainsz
, &np
->current_padding
);
1854 if (np
->current_padding
> 0) {
1855 r
= context_add_free_area(context
, np
->current_padding
, np
);
1860 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, TAKE_PTR(np
));
1861 context
->n_partitions
++;
1865 add_initial_free_area
:
1866 nsectors
= fdisk_get_nsectors(c
);
1867 assert(nsectors
<= UINT64_MAX
/secsz
);
1870 first_lba
= fdisk_get_first_lba(c
);
1871 assert(first_lba
<= UINT64_MAX
/secsz
);
1874 last_lba
= fdisk_get_last_lba(c
);
1875 assert(last_lba
< UINT64_MAX
);
1877 assert(last_lba
<= UINT64_MAX
/secsz
);
1880 assert(last_lba
>= first_lba
);
1882 if (left_boundary
== UINT64_MAX
) {
1883 /* No partitions at all? Then the whole disk is up for grabs. */
1885 first_lba
= round_up_size(first_lba
, grainsz
);
1886 last_lba
= round_down_size(last_lba
, grainsz
);
1888 if (last_lba
> first_lba
) {
1889 r
= context_add_free_area(context
, last_lba
- first_lba
, NULL
);
1894 /* Add space left of first partition */
1895 assert(left_boundary
>= first_lba
);
1897 first_lba
= round_up_size(first_lba
, grainsz
);
1898 left_boundary
= round_down_size(left_boundary
, grainsz
);
1899 last_lba
= round_down_size(last_lba
, grainsz
);
1901 if (left_boundary
> first_lba
) {
1902 r
= context_add_free_area(context
, left_boundary
- first_lba
, NULL
);
1908 context
->start
= first_lba
;
1909 context
->end
= last_lba
;
1910 context
->total
= nsectors
;
1911 context
->sector_size
= secsz
;
1912 context
->grain_size
= grainsz
;
1913 context
->fdisk_context
= TAKE_PTR(c
);
1915 return from_scratch
;
1918 static void context_unload_partition_table(Context
*context
) {
1921 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1923 /* Entirely remove partitions that have no configuration */
1924 if (PARTITION_IS_FOREIGN(p
)) {
1925 partition_unlink_and_free(context
, p
);
1929 /* Otherwise drop all data we read off the block device and everything we might have
1930 * calculated based on it */
1933 p
->current_size
= UINT64_MAX
;
1934 p
->new_size
= UINT64_MAX
;
1935 p
->current_padding
= UINT64_MAX
;
1936 p
->new_padding
= UINT64_MAX
;
1937 p
->partno
= UINT64_MAX
;
1938 p
->offset
= UINT64_MAX
;
1940 if (p
->current_partition
) {
1941 fdisk_unref_partition(p
->current_partition
);
1942 p
->current_partition
= NULL
;
1945 if (p
->new_partition
) {
1946 fdisk_unref_partition(p
->new_partition
);
1947 p
->new_partition
= NULL
;
1950 p
->padding_area
= NULL
;
1951 p
->allocated_to_area
= NULL
;
1953 p
->current_uuid
= SD_ID128_NULL
;
1954 p
->current_label
= mfree(p
->current_label
);
1957 context
->start
= UINT64_MAX
;
1958 context
->end
= UINT64_MAX
;
1959 context
->total
= UINT64_MAX
;
1961 if (context
->fdisk_context
) {
1962 fdisk_unref_context(context
->fdisk_context
);
1963 context
->fdisk_context
= NULL
;
1966 context_free_free_areas(context
);
1969 static int format_size_change(uint64_t from
, uint64_t to
, char **ret
) {
1972 if (from
!= UINT64_MAX
) {
1973 if (from
== to
|| to
== UINT64_MAX
)
1974 t
= strdup(FORMAT_BYTES(from
));
1976 t
= strjoin(FORMAT_BYTES(from
), " ", special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), " ", FORMAT_BYTES(to
));
1977 } else if (to
!= UINT64_MAX
)
1978 t
= strjoin(special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), " ", FORMAT_BYTES(to
));
1991 static const char *partition_label(const Partition
*p
) {
1995 return p
->new_label
;
1997 if (p
->current_label
)
1998 return p
->current_label
;
2000 return gpt_partition_type_uuid_to_string(p
->type_uuid
);
2003 static int context_dump_partitions(Context
*context
, const char *node
) {
2004 _cleanup_(table_unrefp
) Table
*t
= NULL
;
2005 uint64_t sum_padding
= 0, sum_size
= 0;
2007 const size_t dropin_files_col
= 13;
2008 bool no_dropin_files
= true;
2010 if ((arg_json_format_flags
& JSON_FORMAT_OFF
) && context
->n_partitions
== 0) {
2011 log_info("Empty partition table.");
2015 t
= table_new("type", "label", "uuid", "file", "node", "offset", "old size", "raw size", "size", "old padding", "raw padding", "padding", "activity", "drop-in files");
2019 if (!DEBUG_LOGGING
) {
2020 if (arg_json_format_flags
& JSON_FORMAT_OFF
)
2021 (void) table_set_display(t
, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4,
2022 (size_t) 8, (size_t) 11, dropin_files_col
);
2024 (void) table_set_display(t
, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4,
2025 (size_t) 5, (size_t) 6, (size_t) 7, (size_t) 9, (size_t) 10, (size_t) 12,
2029 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 5), 100);
2030 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 6), 100);
2031 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 7), 100);
2032 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 8), 100);
2033 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 9), 100);
2034 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 10), 100);
2035 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 11), 100);
2037 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2038 _cleanup_free_
char *size_change
= NULL
, *padding_change
= NULL
, *partname
= NULL
;
2039 char uuid_buffer
[SD_ID128_UUID_STRING_MAX
];
2040 const char *label
, *activity
= NULL
;
2045 if (p
->current_size
== UINT64_MAX
)
2046 activity
= "create";
2047 else if (p
->current_size
!= p
->new_size
)
2048 activity
= "resize";
2050 label
= partition_label(p
);
2051 partname
= p
->partno
!= UINT64_MAX
? fdisk_partname(node
, p
->partno
+1) : NULL
;
2053 r
= format_size_change(p
->current_size
, p
->new_size
, &size_change
);
2057 r
= format_size_change(p
->current_padding
, p
->new_padding
, &padding_change
);
2061 if (p
->new_size
!= UINT64_MAX
)
2062 sum_size
+= p
->new_size
;
2063 if (p
->new_padding
!= UINT64_MAX
)
2064 sum_padding
+= p
->new_padding
;
2068 TABLE_STRING
, gpt_partition_type_uuid_to_string_harder(p
->type_uuid
, uuid_buffer
),
2069 TABLE_STRING
, empty_to_null(label
) ?: "-", TABLE_SET_COLOR
, empty_to_null(label
) ? NULL
: ansi_grey(),
2070 TABLE_UUID
, sd_id128_is_null(p
->new_uuid
) ? p
->current_uuid
: p
->new_uuid
,
2071 TABLE_STRING
, p
->definition_path
? basename(p
->definition_path
) : "-", TABLE_SET_COLOR
, p
->definition_path
? NULL
: ansi_grey(),
2072 TABLE_STRING
, partname
?: "-", TABLE_SET_COLOR
, partname
? NULL
: ansi_highlight(),
2073 TABLE_UINT64
, p
->offset
,
2074 TABLE_UINT64
, p
->current_size
== UINT64_MAX
? 0 : p
->current_size
,
2075 TABLE_UINT64
, p
->new_size
,
2076 TABLE_STRING
, size_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_size
> 0 ? ansi_underline() : NULL
,
2077 TABLE_UINT64
, p
->current_padding
== UINT64_MAX
? 0 : p
->current_padding
,
2078 TABLE_UINT64
, p
->new_padding
,
2079 TABLE_STRING
, padding_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_padding
> 0 ? ansi_underline() : NULL
,
2080 TABLE_STRING
, activity
?: "unchanged",
2081 TABLE_STRV
, p
->drop_in_files
);
2083 return table_log_add_error(r
);
2085 no_dropin_files
= no_dropin_files
&& strv_isempty(p
->drop_in_files
);
2088 if ((arg_json_format_flags
& JSON_FORMAT_OFF
) && (sum_padding
> 0 || sum_size
> 0)) {
2091 a
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", FORMAT_BYTES(sum_size
));
2092 b
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", FORMAT_BYTES(sum_padding
));
2111 return table_log_add_error(r
);
2114 if (no_dropin_files
) {
2115 r
= table_hide_column_from_display(t
, dropin_files_col
);
2117 return log_error_errno(r
, "Failed to set columns to display: %m");
2120 return table_print_with_pager(t
, arg_json_format_flags
, arg_pager_flags
, arg_legend
);
2123 static void context_bar_char_process_partition(
2128 size_t *ret_start
) {
2130 uint64_t from
, to
, total
;
2141 assert(p
->offset
!= UINT64_MAX
);
2142 assert(p
->new_size
!= UINT64_MAX
);
2145 to
= from
+ p
->new_size
;
2147 assert(context
->total
> 0);
2148 total
= context
->total
;
2150 assert(from
<= total
);
2151 x
= from
* n
/ total
;
2153 assert(to
<= total
);
2159 for (size_t i
= x
; i
< y
; i
++)
2165 static int partition_hint(const Partition
*p
, const char *node
, char **ret
) {
2166 _cleanup_free_
char *buf
= NULL
;
2170 /* Tries really hard to find a suitable description for this partition */
2172 if (p
->definition_path
) {
2173 buf
= strdup(basename(p
->definition_path
));
2177 label
= partition_label(p
);
2178 if (!isempty(label
)) {
2179 buf
= strdup(label
);
2183 if (p
->partno
!= UINT64_MAX
) {
2184 buf
= fdisk_partname(node
, p
->partno
+1);
2188 if (!sd_id128_is_null(p
->new_uuid
))
2190 else if (!sd_id128_is_null(p
->current_uuid
))
2191 id
= p
->current_uuid
;
2195 buf
= strdup(SD_ID128_TO_UUID_STRING(id
));
2201 *ret
= TAKE_PTR(buf
);
2205 static int context_dump_partition_bar(Context
*context
, const char *node
) {
2206 _cleanup_free_ Partition
**bar
= NULL
;
2207 _cleanup_free_
size_t *start_array
= NULL
;
2208 Partition
*last
= NULL
;
2212 assert_se((c
= columns()) >= 2);
2213 c
-= 2; /* We do not use the leftmost and rightmost character cell */
2215 bar
= new0(Partition
*, c
);
2219 start_array
= new(size_t, context
->n_partitions
);
2223 LIST_FOREACH(partitions
, p
, context
->partitions
)
2224 context_bar_char_process_partition(context
, bar
, c
, p
, start_array
+ j
++);
2228 for (size_t i
= 0; i
< c
; i
++) {
2233 fputs(z
? ansi_green() : ansi_yellow(), stdout
);
2234 fputs(special_glyph(SPECIAL_GLYPH_DARK_SHADE
), stdout
);
2236 fputs(ansi_normal(), stdout
);
2237 fputs(special_glyph(SPECIAL_GLYPH_LIGHT_SHADE
), stdout
);
2243 fputs(ansi_normal(), stdout
);
2246 for (size_t i
= 0; i
< context
->n_partitions
; i
++) {
2247 _cleanup_free_
char **line
= NULL
;
2249 line
= new0(char*, c
);
2254 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2255 _cleanup_free_
char *d
= NULL
;
2258 if (i
< context
->n_partitions
- j
) {
2260 if (line
[start_array
[j
-1]]) {
2263 /* Upgrade final corner to the right with a branch to the right */
2264 e
= startswith(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
2266 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), e
);
2273 d
= strdup(special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
));
2278 } else if (i
== context
->n_partitions
- j
) {
2279 _cleanup_free_
char *hint
= NULL
;
2281 (void) partition_hint(p
, node
, &hint
);
2283 if (streq_ptr(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
)))
2284 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), " ", strna(hint
));
2286 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), " ", strna(hint
));
2293 free_and_replace(line
[start_array
[j
-1]], d
);
2301 fputs(line
[j
], stdout
);
2302 j
+= utf8_console_width(line
[j
]);
2311 for (j
= 0; j
< c
; j
++)
2318 static bool context_changed(const Context
*context
) {
2321 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2325 if (p
->allocated_to_area
)
2328 if (p
->new_size
!= p
->current_size
)
2335 static int context_wipe_range(Context
*context
, uint64_t offset
, uint64_t size
) {
2336 _cleanup_(blkid_free_probep
) blkid_probe probe
= NULL
;
2340 assert(offset
!= UINT64_MAX
);
2341 assert(size
!= UINT64_MAX
);
2343 probe
= blkid_new_probe();
2348 r
= blkid_probe_set_device(probe
, fdisk_get_devfd(context
->fdisk_context
), offset
, size
);
2350 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to allocate device probe for wiping.");
2353 if (blkid_probe_enable_superblocks(probe
, true) < 0 ||
2354 blkid_probe_set_superblocks_flags(probe
, BLKID_SUBLKS_MAGIC
|BLKID_SUBLKS_BADCSUM
) < 0 ||
2355 blkid_probe_enable_partitions(probe
, true) < 0 ||
2356 blkid_probe_set_partitions_flags(probe
, BLKID_PARTS_MAGIC
) < 0)
2357 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to enable superblock and partition probing.");
2361 r
= blkid_do_probe(probe
);
2363 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to probe for file systems.");
2368 if (blkid_do_wipe(probe
, false) < 0)
2369 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to wipe file system signature.");
2375 static int context_wipe_partition(Context
*context
, Partition
*p
) {
2380 assert(!PARTITION_EXISTS(p
)); /* Safety check: never wipe existing partitions */
2382 assert(p
->offset
!= UINT64_MAX
);
2383 assert(p
->new_size
!= UINT64_MAX
);
2385 r
= context_wipe_range(context
, p
->offset
, p
->new_size
);
2389 log_info("Successfully wiped file system signatures from future partition %" PRIu64
".", p
->partno
);
2393 static int context_discard_range(
2402 assert(offset
!= UINT64_MAX
);
2403 assert(size
!= UINT64_MAX
);
2408 assert_se((fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
2410 if (fstat(fd
, &st
) < 0)
2413 if (S_ISREG(st
.st_mode
)) {
2414 if (fallocate(fd
, FALLOC_FL_PUNCH_HOLE
|FALLOC_FL_KEEP_SIZE
, offset
, size
) < 0) {
2415 if (ERRNO_IS_NOT_SUPPORTED(errno
))
2424 if (S_ISBLK(st
.st_mode
)) {
2425 uint64_t range
[2], end
;
2427 range
[0] = round_up_size(offset
, context
->sector_size
);
2429 if (offset
> UINT64_MAX
- size
)
2432 end
= offset
+ size
;
2433 if (end
<= range
[0])
2436 range
[1] = round_down_size(end
- range
[0], context
->sector_size
);
2440 if (ioctl(fd
, BLKDISCARD
, range
) < 0) {
2441 if (ERRNO_IS_NOT_SUPPORTED(errno
))
2453 static int context_discard_partition(Context
*context
, Partition
*p
) {
2459 assert(p
->offset
!= UINT64_MAX
);
2460 assert(p
->new_size
!= UINT64_MAX
);
2461 assert(!PARTITION_EXISTS(p
)); /* Safety check: never discard existing partitions */
2466 r
= context_discard_range(context
, p
->offset
, p
->new_size
);
2467 if (r
== -EOPNOTSUPP
) {
2468 log_info("Storage does not support discard, not discarding data in future partition %" PRIu64
".", p
->partno
);
2472 /* Let's handle this gracefully: https://bugzilla.kernel.org/show_bug.cgi?id=211167 */
2473 log_info("Block device is busy, not discarding partition %" PRIu64
" because it probably is mounted.", p
->partno
);
2477 log_info("Partition %" PRIu64
" too short for discard, skipping.", p
->partno
);
2481 return log_error_errno(r
, "Failed to discard data for future partition %" PRIu64
".", p
->partno
);
2483 log_info("Successfully discarded data from future partition %" PRIu64
".", p
->partno
);
2487 static int context_discard_gap_after(Context
*context
, Partition
*p
) {
2488 uint64_t gap
, next
= UINT64_MAX
;
2492 assert(!p
|| (p
->offset
!= UINT64_MAX
&& p
->new_size
!= UINT64_MAX
));
2495 gap
= p
->offset
+ p
->new_size
;
2497 gap
= context
->start
;
2499 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2503 assert(q
->offset
!= UINT64_MAX
);
2504 assert(q
->new_size
!= UINT64_MAX
);
2506 if (q
->offset
< gap
)
2509 if (next
== UINT64_MAX
|| q
->offset
< next
)
2513 if (next
== UINT64_MAX
) {
2514 next
= context
->end
;
2516 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
2519 assert(next
>= gap
);
2520 r
= context_discard_range(context
, gap
, next
- gap
);
2521 if (r
== -EOPNOTSUPP
) {
2523 log_info("Storage does not support discard, not discarding gap after partition %" PRIu64
".", p
->partno
);
2525 log_info("Storage does not support discard, not discarding gap at beginning of disk.");
2528 if (r
== 0) /* Too short */
2532 return log_error_errno(r
, "Failed to discard gap after partition %" PRIu64
".", p
->partno
);
2534 return log_error_errno(r
, "Failed to discard gap at beginning of disk.");
2538 log_info("Successfully discarded gap after partition %" PRIu64
".", p
->partno
);
2540 log_info("Successfully discarded gap at beginning of disk.");
2545 static int context_wipe_and_discard(Context
*context
, bool from_scratch
) {
2550 /* Wipe and discard the contents of all partitions we are about to create. We skip the discarding if
2551 * we were supposed to start from scratch anyway, as in that case we just discard the whole block
2552 * device in one go early on. */
2554 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2556 if (!p
->allocated_to_area
)
2559 r
= context_wipe_partition(context
, p
);
2563 if (!from_scratch
) {
2564 r
= context_discard_partition(context
, p
);
2568 r
= context_discard_gap_after(context
, p
);
2574 if (!from_scratch
) {
2575 r
= context_discard_gap_after(context
, NULL
);
2583 static int partition_encrypt(
2587 struct crypt_device
**ret_cd
,
2590 #if HAVE_LIBCRYPTSETUP
2591 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2592 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
2593 _cleanup_free_
char *dm_name
= NULL
, *vol
= NULL
;
2594 size_t volume_key_size
= 256 / 8;
2600 assert(p
->encrypt
!= ENCRYPT_OFF
);
2602 log_debug("Encryption mode for partition %" PRIu64
": %s", p
->partno
, encrypt_mode_to_string(p
->encrypt
));
2604 r
= dlopen_cryptsetup();
2606 return log_error_errno(r
, "libcryptsetup not found, cannot encrypt: %m");
2608 if (asprintf(&dm_name
, "luks-repart-%08" PRIx64
, random_u64()) < 0)
2612 vol
= path_join("/dev/mapper/", dm_name
);
2617 r
= derive_uuid(p
->new_uuid
, "luks-uuid", &uuid
);
2621 log_info("Encrypting future partition %" PRIu64
"...", p
->partno
);
2623 volume_key
= malloc(volume_key_size
);
2627 r
= crypto_random_bytes(volume_key
, volume_key_size
);
2629 return log_error_errno(r
, "Failed to generate volume key: %m");
2631 r
= sym_crypt_init(&cd
, node
);
2633 return log_error_errno(r
, "Failed to allocate libcryptsetup context: %m");
2635 cryptsetup_enable_logging(cd
);
2637 r
= sym_crypt_format(cd
,
2641 SD_ID128_TO_UUID_STRING(uuid
),
2644 &(struct crypt_params_luks2
) {
2645 .label
= strempty(p
->new_label
),
2646 .sector_size
= context
->sector_size
,
2649 return log_error_errno(r
, "Failed to LUKS2 format future partition: %m");
2651 if (IN_SET(p
->encrypt
, ENCRYPT_KEY_FILE
, ENCRYPT_KEY_FILE_TPM2
)) {
2652 r
= sym_crypt_keyslot_add_by_volume_key(
2660 return log_error_errno(r
, "Failed to add LUKS2 key: %m");
2663 if (IN_SET(p
->encrypt
, ENCRYPT_TPM2
, ENCRYPT_KEY_FILE_TPM2
)) {
2665 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
2666 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
2667 _cleanup_(erase_and_freep
) void *secret
= NULL
;
2668 _cleanup_free_
void *blob
= NULL
, *hash
= NULL
;
2669 size_t secret_size
, blob_size
, hash_size
;
2670 uint16_t pcr_bank
, primary_alg
;
2673 r
= tpm2_seal(arg_tpm2_device
, arg_tpm2_pcr_mask
, NULL
, &secret
, &secret_size
, &blob
, &blob_size
, &hash
, &hash_size
, &pcr_bank
, &primary_alg
);
2675 return log_error_errno(r
, "Failed to seal to TPM2: %m");
2677 r
= base64mem(secret
, secret_size
, &base64_encoded
);
2679 return log_error_errno(r
, "Failed to base64 encode secret key: %m");
2681 r
= cryptsetup_set_minimal_pbkdf(cd
);
2683 return log_error_errno(r
, "Failed to set minimal PBKDF: %m");
2685 keyslot
= sym_crypt_keyslot_add_by_volume_key(
2691 strlen(base64_encoded
));
2693 return log_error_errno(keyslot
, "Failed to add new TPM2 key to %s: %m", node
);
2695 r
= tpm2_make_luks2_json(keyslot
, arg_tpm2_pcr_mask
, pcr_bank
, primary_alg
, blob
, blob_size
, hash
, hash_size
, 0, &v
);
2697 return log_error_errno(r
, "Failed to prepare TPM2 JSON token object: %m");
2699 r
= cryptsetup_add_token_json(cd
, v
);
2701 return log_error_errno(r
, "Failed to add TPM2 JSON token to LUKS2 header: %m");
2703 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2704 "Support for TPM2 enrollment not enabled.");
2708 r
= sym_crypt_activate_by_volume_key(
2713 arg_discard
? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0);
2715 return log_error_errno(r
, "Failed to activate LUKS superblock: %m");
2717 log_info("Successfully encrypted future partition %" PRIu64
".", p
->partno
);
2720 _cleanup_close_
int dev_fd
= -1;
2722 dev_fd
= open(vol
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
);
2724 return log_error_errno(errno
, "Failed to open LUKS volume '%s': %m", vol
);
2726 *ret_fd
= TAKE_FD(dev_fd
);
2730 *ret_cd
= TAKE_PTR(cd
);
2732 *ret_volume
= TAKE_PTR(vol
);
2736 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "libcryptsetup is not supported, cannot encrypt: %m");
2740 static int deactivate_luks(struct crypt_device
*cd
, const char *node
) {
2741 #if HAVE_LIBCRYPTSETUP
2749 /* udev or so might access out block device in the background while we are done. Let's hence force
2750 * detach the volume. We sync'ed before, hence this should be safe. */
2752 r
= sym_crypt_deactivate_by_name(cd
, basename(node
), CRYPT_DEACTIVATE_FORCE
);
2754 return log_error_errno(r
, "Failed to deactivate LUKS device: %m");
2762 static int context_copy_blocks(Context
*context
) {
2763 int whole_fd
= -1, r
;
2767 /* Copy in file systems on the block level */
2769 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2770 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2771 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
2772 _cleanup_free_
char *encrypted
= NULL
;
2773 _cleanup_close_
int encrypted_dev_fd
= -1;
2776 if (p
->copy_blocks_fd
< 0)
2782 if (PARTITION_EXISTS(p
)) /* Never copy over existing partitions */
2785 assert(p
->new_size
!= UINT64_MAX
);
2786 assert(p
->copy_blocks_size
!= UINT64_MAX
);
2787 assert(p
->new_size
>= p
->copy_blocks_size
);
2790 assert_se((whole_fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
2792 if (p
->encrypt
!= ENCRYPT_OFF
) {
2793 r
= loop_device_make(whole_fd
, O_RDWR
, p
->offset
, p
->new_size
, 0, &d
);
2795 return log_error_errno(r
, "Failed to make loopback device of future partition %" PRIu64
": %m", p
->partno
);
2797 r
= loop_device_flock(d
, LOCK_EX
);
2799 return log_error_errno(r
, "Failed to lock loopback device: %m");
2801 r
= partition_encrypt(context
, p
, d
->node
, &cd
, &encrypted
, &encrypted_dev_fd
);
2803 return log_error_errno(r
, "Failed to encrypt device: %m");
2805 if (flock(encrypted_dev_fd
, LOCK_EX
) < 0)
2806 return log_error_errno(errno
, "Failed to lock LUKS device: %m");
2808 target_fd
= encrypted_dev_fd
;
2810 if (lseek(whole_fd
, p
->offset
, SEEK_SET
) == (off_t
) -1)
2811 return log_error_errno(errno
, "Failed to seek to partition offset: %m");
2813 target_fd
= whole_fd
;
2816 log_info("Copying in '%s' (%s) on block level into future partition %" PRIu64
".",
2817 p
->copy_blocks_path
, FORMAT_BYTES(p
->copy_blocks_size
), p
->partno
);
2819 r
= copy_bytes_full(p
->copy_blocks_fd
, target_fd
, p
->copy_blocks_size
, 0, NULL
, NULL
, NULL
, NULL
);
2821 return log_error_errno(r
, "Failed to copy in data from '%s': %m", p
->copy_blocks_path
);
2823 if (fsync(target_fd
) < 0)
2824 return log_error_errno(errno
, "Failed to synchronize copied data blocks: %m");
2826 if (p
->encrypt
!= ENCRYPT_OFF
) {
2827 encrypted_dev_fd
= safe_close(encrypted_dev_fd
);
2829 r
= deactivate_luks(cd
, encrypted
);
2836 r
= loop_device_sync(d
);
2838 return log_error_errno(r
, "Failed to sync loopback device: %m");
2841 log_info("Copying in of '%s' on block level completed.", p
->copy_blocks_path
);
2847 static int do_copy_files(Partition
*p
, const char *fs
) {
2853 STRV_FOREACH_PAIR(source
, target
, p
->copy_files
) {
2854 _cleanup_close_
int sfd
= -1, pfd
= -1, tfd
= -1;
2856 sfd
= chase_symlinks_and_open(*source
, arg_root
, CHASE_PREFIX_ROOT
|CHASE_WARN
, O_CLOEXEC
|O_NOCTTY
, NULL
);
2858 return log_error_errno(sfd
, "Failed to open source file '%s%s': %m", strempty(arg_root
), *source
);
2860 r
= fd_verify_regular(sfd
);
2863 return log_error_errno(r
, "Failed to check type of source file '%s': %m", *source
);
2865 /* We are looking at a directory */
2866 tfd
= chase_symlinks_and_open(*target
, fs
, CHASE_PREFIX_ROOT
|CHASE_WARN
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, NULL
);
2868 _cleanup_free_
char *dn
= NULL
, *fn
= NULL
;
2871 return log_error_errno(tfd
, "Failed to open target directory '%s': %m", *target
);
2873 r
= path_extract_filename(*target
, &fn
);
2875 return log_error_errno(r
, "Failed to extract filename from '%s': %m", *target
);
2877 r
= path_extract_directory(*target
, &dn
);
2879 return log_error_errno(r
, "Failed to extract directory from '%s': %m", *target
);
2881 r
= mkdir_p_root(fs
, dn
, UID_INVALID
, GID_INVALID
, 0755);
2883 return log_error_errno(r
, "Failed to create parent directory '%s': %m", dn
);
2885 pfd
= chase_symlinks_and_open(dn
, fs
, CHASE_PREFIX_ROOT
|CHASE_WARN
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, NULL
);
2887 return log_error_errno(pfd
, "Failed to open parent directory of target: %m");
2892 UID_INVALID
, GID_INVALID
,
2893 COPY_REFLINK
|COPY_MERGE
|COPY_REPLACE
|COPY_SIGINT
|COPY_HARDLINKS
|COPY_ALL_XATTRS
);
2898 UID_INVALID
, GID_INVALID
,
2899 COPY_REFLINK
|COPY_MERGE
|COPY_REPLACE
|COPY_SIGINT
|COPY_HARDLINKS
|COPY_ALL_XATTRS
);
2901 return log_error_errno(r
, "Failed to copy '%s' to '%s%s': %m", *source
, strempty(arg_root
), *target
);
2903 _cleanup_free_
char *dn
= NULL
, *fn
= NULL
;
2905 /* We are looking at a regular file */
2907 r
= path_extract_filename(*target
, &fn
);
2908 if (r
== -EADDRNOTAVAIL
|| r
== O_DIRECTORY
)
2909 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
),
2910 "Target path '%s' refers to a directory, but source path '%s' refers to regular file, can't copy.", *target
, *source
);
2912 return log_error_errno(r
, "Failed to extract filename from '%s': %m", *target
);
2914 r
= path_extract_directory(*target
, &dn
);
2916 return log_error_errno(r
, "Failed to extract directory from '%s': %m", *target
);
2918 r
= mkdir_p_root(fs
, dn
, UID_INVALID
, GID_INVALID
, 0755);
2920 return log_error_errno(r
, "Failed to create parent directory: %m");
2922 pfd
= chase_symlinks_and_open(dn
, fs
, CHASE_PREFIX_ROOT
|CHASE_WARN
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, NULL
);
2924 return log_error_errno(pfd
, "Failed to open parent directory of target: %m");
2926 tfd
= openat(pfd
, fn
, O_CREAT
|O_EXCL
|O_WRONLY
|O_CLOEXEC
, 0700);
2928 return log_error_errno(errno
, "Failed to create target file '%s': %m", *target
);
2930 r
= copy_bytes(sfd
, tfd
, UINT64_MAX
, COPY_REFLINK
|COPY_SIGINT
);
2932 return log_error_errno(r
, "Failed to copy '%s' to '%s%s': %m", *source
, strempty(arg_root
), *target
);
2934 (void) copy_xattr(sfd
, tfd
, COPY_ALL_XATTRS
);
2935 (void) copy_access(sfd
, tfd
);
2936 (void) copy_times(sfd
, tfd
, 0);
2943 static int do_make_directories(Partition
*p
, const char *fs
) {
2949 STRV_FOREACH(d
, p
->make_directories
) {
2951 r
= mkdir_p_root(fs
, *d
, UID_INVALID
, GID_INVALID
, 0755);
2953 return log_error_errno(r
, "Failed to create directory '%s' in file system: %m", *d
);
2959 static int partition_populate(Partition
*p
, const char *node
) {
2965 if (strv_isempty(p
->copy_files
) && strv_isempty(p
->make_directories
))
2968 log_info("Populating partition %" PRIu64
" with files.", p
->partno
);
2970 /* We copy in a child process, since we have to mount the fs for that, and we don't want that fs to
2971 * appear in the host namespace. Hence we fork a child that has its own file system namespace and
2972 * detached mount propagation. */
2974 r
= safe_fork("(sd-copy)", FORK_DEATHSIG
|FORK_LOG
|FORK_WAIT
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, NULL
);
2978 static const char fs
[] = "/run/systemd/mount-root";
2979 /* This is a child process with its own mount namespace and propagation to host turned off */
2981 r
= mkdir_p(fs
, 0700);
2983 log_error_errno(r
, "Failed to create mount point: %m");
2984 _exit(EXIT_FAILURE
);
2987 if (mount_nofollow_verbose(LOG_ERR
, node
, fs
, p
->format
, MS_NOATIME
|MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
) < 0)
2988 _exit(EXIT_FAILURE
);
2990 if (do_copy_files(p
, fs
) < 0)
2991 _exit(EXIT_FAILURE
);
2993 if (do_make_directories(p
, fs
) < 0)
2994 _exit(EXIT_FAILURE
);
2996 r
= syncfs_path(AT_FDCWD
, fs
);
2998 log_error_errno(r
, "Failed to synchronize written files: %m");
2999 _exit(EXIT_FAILURE
);
3002 _exit(EXIT_SUCCESS
);
3005 log_info("Successfully populated partition %" PRIu64
" with files.", p
->partno
);
3009 static int context_mkfs(Context
*context
) {
3014 /* Make a file system */
3016 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3017 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
3018 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
3019 _cleanup_free_
char *encrypted
= NULL
;
3020 _cleanup_close_
int encrypted_dev_fd
= -1;
3027 if (PARTITION_EXISTS(p
)) /* Never format existing partitions */
3033 assert(p
->offset
!= UINT64_MAX
);
3034 assert(p
->new_size
!= UINT64_MAX
);
3037 assert_se((fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
3039 /* Loopback block devices are not only useful to turn regular files into block devices, but
3040 * also to cut out sections of block devices into new block devices. */
3042 r
= loop_device_make(fd
, O_RDWR
, p
->offset
, p
->new_size
, 0, &d
);
3044 return log_error_errno(r
, "Failed to make loopback device of future partition %" PRIu64
": %m", p
->partno
);
3046 r
= loop_device_flock(d
, LOCK_EX
);
3048 return log_error_errno(r
, "Failed to lock loopback device: %m");
3050 if (p
->encrypt
!= ENCRYPT_OFF
) {
3051 r
= partition_encrypt(context
, p
, d
->node
, &cd
, &encrypted
, &encrypted_dev_fd
);
3053 return log_error_errno(r
, "Failed to encrypt device: %m");
3055 if (flock(encrypted_dev_fd
, LOCK_EX
) < 0)
3056 return log_error_errno(errno
, "Failed to lock LUKS device: %m");
3062 log_info("Formatting future partition %" PRIu64
".", p
->partno
);
3064 /* Calculate the UUID for the file system as HMAC-SHA256 of the string "file-system-uuid",
3065 * keyed off the partition UUID. */
3066 r
= derive_uuid(p
->new_uuid
, "file-system-uuid", &fs_uuid
);
3070 r
= make_filesystem(fsdev
, p
->format
, strempty(p
->new_label
), fs_uuid
, arg_discard
);
3072 encrypted_dev_fd
= safe_close(encrypted_dev_fd
);
3073 (void) deactivate_luks(cd
, encrypted
);
3077 log_info("Successfully formatted future partition %" PRIu64
".", p
->partno
);
3079 /* The file system is now created, no need to delay udev further */
3080 if (p
->encrypt
!= ENCRYPT_OFF
)
3081 if (flock(encrypted_dev_fd
, LOCK_UN
) < 0)
3082 return log_error_errno(errno
, "Failed to unlock LUKS device: %m");
3084 r
= partition_populate(p
, fsdev
);
3086 encrypted_dev_fd
= safe_close(encrypted_dev_fd
);
3087 (void) deactivate_luks(cd
, encrypted
);
3091 /* Note that we always sync explicitly here, since mkfs.fat doesn't do that on its own, and
3092 * if we don't sync before detaching a block device the in-flight sectors possibly won't hit
3095 if (p
->encrypt
!= ENCRYPT_OFF
) {
3096 if (fsync(encrypted_dev_fd
) < 0)
3097 return log_error_errno(errno
, "Failed to synchronize LUKS volume: %m");
3098 encrypted_dev_fd
= safe_close(encrypted_dev_fd
);
3100 r
= deactivate_luks(cd
, encrypted
);
3108 r
= loop_device_sync(d
);
3110 return log_error_errno(r
, "Failed to sync loopback device: %m");
3116 static int partition_acquire_uuid(Context
*context
, Partition
*p
, sd_id128_t
*ret
) {
3118 sd_id128_t type_uuid
;
3120 } _packed_ plaintext
= {};
3122 uint8_t md
[SHA256_DIGEST_SIZE
];
3133 /* Calculate a good UUID for the indicated partition. We want a certain degree of reproducibility,
3134 * hence we won't generate the UUIDs randomly. Instead we use a cryptographic hash (precisely:
3135 * HMAC-SHA256) to derive them from a single seed. The seed is generally the machine ID of the
3136 * installation we are processing, but if random behaviour is desired can be random, too. We use the
3137 * seed value as key for the HMAC (since the machine ID is something we generally don't want to leak)
3138 * and the partition type as plaintext. The partition type is suffixed with a counter (only for the
3139 * second and later partition of the same type) if we have more than one partition of the same
3140 * time. Or in other words:
3143 * SEED := /etc/machine-id
3145 * If first partition instance of type TYPE_UUID:
3146 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID)
3148 * For all later partition instances of type TYPE_UUID with INSTANCE being the LE64 encoded instance number:
3149 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID || INSTANCE)
3152 LIST_FOREACH(partitions
, q
, context
->partitions
) {
3156 if (!sd_id128_equal(p
->type_uuid
, q
->type_uuid
))
3162 plaintext
.type_uuid
= p
->type_uuid
;
3163 plaintext
.counter
= htole64(k
);
3165 hmac_sha256(context
->seed
.bytes
, sizeof(context
->seed
.bytes
),
3167 k
== 0 ? sizeof(sd_id128_t
) : sizeof(plaintext
),
3170 /* Take the first half, mark it as v4 UUID */
3171 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
3172 result
.id
= id128_make_v4_uuid(result
.id
);
3174 /* Ensure this partition UUID is actually unique, and there's no remaining partition from an earlier run? */
3175 LIST_FOREACH(partitions
, q
, context
->partitions
) {
3179 if (sd_id128_in_set(result
.id
, q
->current_uuid
, q
->new_uuid
)) {
3180 log_warning("Partition UUID calculated from seed for partition %" PRIu64
" already used, reverting to randomized UUID.", p
->partno
);
3182 r
= sd_id128_randomize(&result
.id
);
3184 return log_error_errno(r
, "Failed to generate randomized UUID: %m");
3194 static int partition_acquire_label(Context
*context
, Partition
*p
, char **ret
) {
3195 _cleanup_free_
char *label
= NULL
;
3203 prefix
= gpt_partition_type_uuid_to_string(p
->type_uuid
);
3208 const char *ll
= label
?: prefix
;
3211 LIST_FOREACH(partitions
, q
, context
->partitions
) {
3215 if (streq_ptr(ll
, q
->current_label
) ||
3216 streq_ptr(ll
, q
->new_label
)) {
3225 label
= mfree(label
);
3226 if (asprintf(&label
, "%s-%u", prefix
, ++k
) < 0)
3231 label
= strdup(prefix
);
3236 *ret
= TAKE_PTR(label
);
3240 static int context_acquire_partition_uuids_and_labels(Context
*context
) {
3245 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3246 /* Never touch foreign partitions */
3247 if (PARTITION_IS_FOREIGN(p
)) {
3248 p
->new_uuid
= p
->current_uuid
;
3250 if (p
->current_label
) {
3251 r
= free_and_strdup_warn(&p
->new_label
, strempty(p
->current_label
));
3259 if (!sd_id128_is_null(p
->current_uuid
))
3260 p
->new_uuid
= p
->current_uuid
; /* Never change initialized UUIDs */
3261 else if (sd_id128_is_null(p
->new_uuid
)) {
3262 /* Not explicitly set by user! */
3263 r
= partition_acquire_uuid(context
, p
, &p
->new_uuid
);
3268 if (!isempty(p
->current_label
)) {
3269 /* never change initialized labels */
3270 r
= free_and_strdup_warn(&p
->new_label
, p
->current_label
);
3273 } else if (!p
->new_label
) {
3274 /* Not explicitly set by user! */
3276 r
= partition_acquire_label(context
, p
, &p
->new_label
);
3285 static int set_gpt_flags(struct fdisk_partition
*q
, uint64_t flags
) {
3286 _cleanup_free_
char *a
= NULL
;
3288 for (unsigned i
= 0; i
< sizeof(flags
) * 8; i
++) {
3289 uint64_t bit
= UINT64_C(1) << i
;
3290 char buf
[DECIMAL_STR_MAX(unsigned)+1];
3292 if (!FLAGS_SET(flags
, bit
))
3295 xsprintf(buf
, "%u", i
);
3296 if (!strextend_with_separator(&a
, ",", buf
))
3300 return fdisk_partition_set_attrs(q
, a
);
3303 static uint64_t partition_merge_flags(Partition
*p
) {
3310 if (p
->no_auto
>= 0) {
3311 if (gpt_partition_type_knows_no_auto(p
->type_uuid
))
3312 SET_FLAG(f
, GPT_FLAG_NO_AUTO
, p
->no_auto
);
3314 char buffer
[SD_ID128_UUID_STRING_MAX
];
3315 log_warning("Configured NoAuto=%s for partition type '%s' that doesn't support it, ignoring.",
3317 gpt_partition_type_uuid_to_string_harder(p
->type_uuid
, buffer
));
3321 if (p
->read_only
>= 0) {
3322 if (gpt_partition_type_knows_read_only(p
->type_uuid
))
3323 SET_FLAG(f
, GPT_FLAG_READ_ONLY
, p
->read_only
);
3325 char buffer
[SD_ID128_UUID_STRING_MAX
];
3326 log_warning("Configured ReadOnly=%s for partition type '%s' that doesn't support it, ignoring.",
3327 yes_no(p
->read_only
),
3328 gpt_partition_type_uuid_to_string_harder(p
->type_uuid
, buffer
));
3332 if (p
->growfs
>= 0) {
3333 if (gpt_partition_type_knows_growfs(p
->type_uuid
))
3334 SET_FLAG(f
, GPT_FLAG_GROWFS
, p
->growfs
);
3336 char buffer
[SD_ID128_UUID_STRING_MAX
];
3337 log_warning("Configured GrowFileSystem=%s for partition type '%s' that doesn't support it, ignoring.",
3339 gpt_partition_type_uuid_to_string_harder(p
->type_uuid
, buffer
));
3346 static int context_mangle_partitions(Context
*context
) {
3351 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3355 assert(p
->new_size
!= UINT64_MAX
);
3356 assert(p
->offset
!= UINT64_MAX
);
3357 assert(p
->partno
!= UINT64_MAX
);
3359 if (PARTITION_EXISTS(p
)) {
3360 bool changed
= false;
3362 assert(p
->current_partition
);
3364 if (p
->new_size
!= p
->current_size
) {
3365 assert(p
->new_size
>= p
->current_size
);
3366 assert(p
->new_size
% context
->sector_size
== 0);
3368 r
= fdisk_partition_size_explicit(p
->current_partition
, true);
3370 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
3372 r
= fdisk_partition_set_size(p
->current_partition
, p
->new_size
/ context
->sector_size
);
3374 return log_error_errno(r
, "Failed to grow partition: %m");
3376 log_info("Growing existing partition %" PRIu64
".", p
->partno
);
3380 if (!sd_id128_equal(p
->new_uuid
, p
->current_uuid
)) {
3381 assert(!sd_id128_is_null(p
->new_uuid
));
3383 r
= fdisk_partition_set_uuid(p
->current_partition
, SD_ID128_TO_UUID_STRING(p
->new_uuid
));
3385 return log_error_errno(r
, "Failed to set partition UUID: %m");
3387 log_info("Initializing UUID of existing partition %" PRIu64
".", p
->partno
);
3391 if (!streq_ptr(p
->new_label
, p
->current_label
)) {
3392 r
= fdisk_partition_set_name(p
->current_partition
, strempty(p
->new_label
));
3394 return log_error_errno(r
, "Failed to set partition label: %m");
3396 log_info("Setting partition label of existing partition %" PRIu64
".", p
->partno
);
3401 assert(!PARTITION_IS_FOREIGN(p
)); /* never touch foreign partitions */
3403 r
= fdisk_set_partition(context
->fdisk_context
, p
->partno
, p
->current_partition
);
3405 return log_error_errno(r
, "Failed to update partition: %m");
3408 _cleanup_(fdisk_unref_partitionp
) struct fdisk_partition
*q
= NULL
;
3409 _cleanup_(fdisk_unref_parttypep
) struct fdisk_parttype
*t
= NULL
;
3411 assert(!p
->new_partition
);
3412 assert(p
->offset
% context
->sector_size
== 0);
3413 assert(p
->new_size
% context
->sector_size
== 0);
3414 assert(!sd_id128_is_null(p
->new_uuid
));
3415 assert(p
->new_label
);
3417 t
= fdisk_new_parttype();
3421 r
= fdisk_parttype_set_typestr(t
, SD_ID128_TO_UUID_STRING(p
->type_uuid
));
3423 return log_error_errno(r
, "Failed to initialize partition type: %m");
3425 q
= fdisk_new_partition();
3429 r
= fdisk_partition_set_type(q
, t
);
3431 return log_error_errno(r
, "Failed to set partition type: %m");
3433 r
= fdisk_partition_size_explicit(q
, true);
3435 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
3437 r
= fdisk_partition_set_start(q
, p
->offset
/ context
->sector_size
);
3439 return log_error_errno(r
, "Failed to position partition: %m");
3441 r
= fdisk_partition_set_size(q
, p
->new_size
/ context
->sector_size
);
3443 return log_error_errno(r
, "Failed to grow partition: %m");
3445 r
= fdisk_partition_set_partno(q
, p
->partno
);
3447 return log_error_errno(r
, "Failed to set partition number: %m");
3449 r
= fdisk_partition_set_uuid(q
, SD_ID128_TO_UUID_STRING(p
->new_uuid
));
3451 return log_error_errno(r
, "Failed to set partition UUID: %m");
3453 r
= fdisk_partition_set_name(q
, strempty(p
->new_label
));
3455 return log_error_errno(r
, "Failed to set partition label: %m");
3457 /* Merge the no auto + read only + growfs setting with the literal flags, and set them for the partition */
3458 r
= set_gpt_flags(q
, partition_merge_flags(p
));
3460 return log_error_errno(r
, "Failed to set GPT partition flags: %m");
3462 log_info("Adding new partition %" PRIu64
" to partition table.", p
->partno
);
3464 r
= fdisk_add_partition(context
->fdisk_context
, q
, NULL
);
3466 return log_error_errno(r
, "Failed to add partition: %m");
3468 assert(!p
->new_partition
);
3469 p
->new_partition
= TAKE_PTR(q
);
3476 static int context_write_partition_table(
3479 bool from_scratch
) {
3481 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*original_table
= NULL
;
3486 if (arg_pretty
> 0 ||
3487 (arg_pretty
< 0 && isatty(STDOUT_FILENO
) > 0) ||
3488 !FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
)) {
3490 (void) context_dump_partitions(context
, node
);
3492 if (arg_json_format_flags
& JSON_FORMAT_OFF
) {
3494 (void) context_dump_partition_bar(context
, node
);
3501 if (!from_scratch
&& !context_changed(context
)) {
3502 log_info("No changes.");
3507 log_notice("Refusing to repartition, please re-run with --dry-run=no.");
3511 log_info("Applying changes.");
3514 r
= context_wipe_range(context
, 0, context
->total
);
3518 log_info("Wiped block device.");
3520 r
= context_discard_range(context
, 0, context
->total
);
3521 if (r
== -EOPNOTSUPP
)
3522 log_info("Storage does not support discard, not discarding entire block device data.");
3524 return log_error_errno(r
, "Failed to discard entire block device: %m");
3526 log_info("Discarded entire block device.");
3529 r
= fdisk_get_partitions(context
->fdisk_context
, &original_table
);
3531 return log_error_errno(r
, "Failed to acquire partition table: %m");
3533 /* Wipe fs signatures and discard sectors where the new partitions are going to be placed and in the
3534 * gaps between partitions, just to be sure. */
3535 r
= context_wipe_and_discard(context
, from_scratch
);
3539 r
= context_copy_blocks(context
);
3543 r
= context_mkfs(context
);
3547 r
= context_mangle_partitions(context
);
3551 log_info("Writing new partition table.");
3553 r
= fdisk_write_disklabel(context
->fdisk_context
);
3555 return log_error_errno(r
, "Failed to write partition table: %m");
3557 capable
= blockdev_partscan_enabled(fdisk_get_devfd(context
->fdisk_context
));
3558 if (capable
== -ENOTBLK
)
3559 log_debug("Not telling kernel to reread partition table, since we are not operating on a block device.");
3560 else if (capable
< 0)
3561 return log_error_errno(capable
, "Failed to check if block device supports partition scanning: %m");
3562 else if (capable
> 0) {
3563 log_info("Telling kernel to reread partition table.");
3566 r
= fdisk_reread_partition_table(context
->fdisk_context
);
3568 r
= fdisk_reread_changes(context
->fdisk_context
, original_table
);
3570 return log_error_errno(r
, "Failed to reread partition table: %m");
3572 log_notice("Not telling kernel to reread partition table, because selected image does not support kernel partition block devices.");
3574 log_info("All done.");
3579 static int context_read_seed(Context
*context
, const char *root
) {
3584 if (!sd_id128_is_null(context
->seed
))
3587 if (!arg_randomize
) {
3588 _cleanup_close_
int fd
= -1;
3590 fd
= chase_symlinks_and_open("/etc/machine-id", root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
, NULL
);
3592 log_info("No machine ID set, using randomized partition UUIDs.");
3594 return log_error_errno(fd
, "Failed to determine machine ID of image: %m");
3596 r
= id128_read_fd(fd
, ID128_PLAIN_OR_UNINIT
, &context
->seed
);
3597 if (r
== -ENOMEDIUM
)
3598 log_info("No machine ID set, using randomized partition UUIDs.");
3600 return log_error_errno(r
, "Failed to parse machine ID of image: %m");
3606 r
= sd_id128_randomize(&context
->seed
);
3608 return log_error_errno(r
, "Failed to generate randomized seed: %m");
3613 static int context_factory_reset(Context
*context
, bool from_scratch
) {
3619 if (arg_factory_reset
<= 0)
3622 if (from_scratch
) /* Nothing to reset if we start from scratch */
3626 log_notice("Refusing to factory reset, please re-run with --dry-run=no.");
3630 log_info("Applying factory reset.");
3632 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3634 if (!p
->factory_reset
|| !PARTITION_EXISTS(p
))
3637 assert(p
->partno
!= UINT64_MAX
);
3639 log_info("Removing partition %" PRIu64
" for factory reset.", p
->partno
);
3641 r
= fdisk_delete_partition(context
->fdisk_context
, p
->partno
);
3643 return log_error_errno(r
, "Failed to remove partition %" PRIu64
": %m", p
->partno
);
3649 log_info("Factory reset requested, but no partitions to delete found.");
3653 r
= fdisk_write_disklabel(context
->fdisk_context
);
3655 return log_error_errno(r
, "Failed to write disk label: %m");
3657 log_info("Successfully deleted %zu partitions.", n
);
3661 static int context_can_factory_reset(Context
*context
) {
3664 LIST_FOREACH(partitions
, p
, context
->partitions
)
3665 if (p
->factory_reset
&& PARTITION_EXISTS(p
))
3671 static int resolve_copy_blocks_auto_candidate(
3672 dev_t partition_devno
,
3673 sd_id128_t partition_type_uuid
,
3674 dev_t restrict_devno
,
3675 sd_id128_t
*ret_uuid
) {
3677 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
3678 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
3679 _cleanup_close_
int fd
= -1;
3680 const char *pttype
, *t
, *p
;
3681 sd_id128_t pt_parsed
, u
;
3687 /* Checks if the specified partition has the specified GPT type UUID, and is located on the specified
3688 * 'restrict_devno' device. The type check is particularly relevant if we have Verity volume which is
3689 * backed by two separate partitions: the data and the hash partitions, and we need to find the right
3690 * one of the two. */
3692 r
= block_get_whole_disk(partition_devno
, &whole_devno
);
3694 return log_error_errno(
3696 "Unable to determine containing block device of partition %u:%u: %m",
3697 major(partition_devno
), minor(partition_devno
));
3699 if (restrict_devno
!= (dev_t
) -1 &&
3700 restrict_devno
!= whole_devno
)
3701 return log_error_errno(
3702 SYNTHETIC_ERRNO(EPERM
),
3703 "Partition %u:%u is located outside of block device %u:%u, refusing.",
3704 major(partition_devno
), minor(partition_devno
),
3705 major(restrict_devno
), minor(restrict_devno
));
3707 r
= sd_device_new_from_devnum(&dev
, 'b', whole_devno
);
3709 return log_error_errno(r
, "Failed to create sd-device for block device %u:%u: %m",
3710 major(whole_devno
), minor(whole_devno
));
3712 r
= sd_device_get_devname(dev
, &p
);
3714 return log_error_errno(r
, "Failed to get name of block device %u:%u: %m",
3715 major(whole_devno
), minor(whole_devno
));
3717 fd
= sd_device_open(dev
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
);
3719 return log_error_errno(fd
, "Failed to open block device %s: %m", p
);
3721 b
= blkid_new_probe();
3726 r
= blkid_probe_set_device(b
, fd
, 0, 0);
3728 return log_error_errno(errno_or_else(ENOMEM
), "Failed to open block device '%s': %m", p
);
3730 (void) blkid_probe_enable_partitions(b
, 1);
3731 (void) blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
3734 r
= blkid_do_safeprobe(b
);
3735 if (IN_SET(r
, -2, 1)) { /* nothing found or ambiguous result */
3736 log_debug("Didn't find partition table on block device '%s'.", p
);
3740 return log_error_errno(errno_or_else(EIO
), "Unable to probe for partition table of '%s': %m", p
);
3742 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
3743 if (!streq_ptr(pttype
, "gpt")) {
3744 log_debug("Didn't find a GPT partition table on '%s'.", p
);
3749 pl
= blkid_probe_get_partitions(b
);
3751 return log_error_errno(errno_or_else(EIO
), "Unable read partition table of '%s': %m", p
);
3754 pp
= blkid_partlist_devno_to_partition(pl
, partition_devno
);
3756 log_debug("Partition %u:%u has no matching partition table entry on '%s'.",
3757 major(partition_devno
), minor(partition_devno
), p
);
3761 t
= blkid_partition_get_type_string(pp
);
3763 log_debug("Partition %u:%u has no type on '%s'.",
3764 major(partition_devno
), minor(partition_devno
), p
);
3768 r
= sd_id128_from_string(t
, &pt_parsed
);
3770 log_debug_errno(r
, "Failed to parse partition type \"%s\": %m", t
);
3774 if (!sd_id128_equal(pt_parsed
, partition_type_uuid
)) {
3775 log_debug("Partition %u:%u has non-matching partition type " SD_ID128_FORMAT_STR
" (needed: " SD_ID128_FORMAT_STR
"), ignoring.",
3776 major(partition_devno
), minor(partition_devno
),
3777 SD_ID128_FORMAT_VAL(pt_parsed
), SD_ID128_FORMAT_VAL(partition_type_uuid
));
3781 t
= blkid_partition_get_uuid(pp
);
3783 log_debug("Partition %u:%u has no UUID.",
3784 major(partition_devno
), minor(partition_devno
));
3788 r
= sd_id128_from_string(t
, &u
);
3790 log_debug_errno(r
, "Failed to parse partition UUID \"%s\": %m", t
);
3794 log_debug("Automatically found partition %u:%u of right type " SD_ID128_FORMAT_STR
".",
3795 major(partition_devno
), minor(partition_devno
),
3796 SD_ID128_FORMAT_VAL(pt_parsed
));
3804 static int find_backing_devno(
3809 _cleanup_free_
char *resolved
= NULL
;
3814 r
= chase_symlinks(path
, root
, CHASE_PREFIX_ROOT
, &resolved
, NULL
);
3818 r
= path_is_mount_point(resolved
, NULL
, 0);
3821 if (r
== 0) /* Not a mount point, then it's not a partition of its own, let's not automatically use it. */
3824 r
= get_block_device(resolved
, ret
);
3827 if (r
== 0) /* Not backed by physical file system, we can't use this */
3833 static int resolve_copy_blocks_auto(
3834 sd_id128_t type_uuid
,
3836 dev_t restrict_devno
,
3838 sd_id128_t
*ret_uuid
) {
3840 const char *try1
= NULL
, *try2
= NULL
;
3841 char p
[SYS_BLOCK_PATH_MAX("/slaves")];
3842 _cleanup_(closedirp
) DIR *d
= NULL
;
3843 sd_id128_t found_uuid
= SD_ID128_NULL
;
3844 dev_t devno
, found
= 0;
3847 /* Enforce some security restrictions: CopyBlocks=auto should not be an avenue to get outside of the
3848 * --root=/--image= confinement. Specifically, refuse CopyBlocks= in combination with --root= at all,
3849 * and restrict block device references in the --image= case to loopback block device we set up.
3851 * restrict_devno contain the dev_t of the loop back device we operate on in case of --image=, and
3852 * thus declares which device (and its partition subdevices) we shall limit access to. If
3853 * restrict_devno is zero no device probing access shall be allowed at all (used for --root=) and if
3854 * it is (dev_t) -1 then free access shall be allowed (if neither switch is used). */
3856 if (restrict_devno
== 0)
3857 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
3858 "Automatic discovery of backing block devices not permitted in --root= mode, refusing.");
3860 /* Handles CopyBlocks=auto, and finds the right source partition to copy from. We look for matching
3861 * partitions in the host, using the appropriate directory as key and ensuring that the partition
3864 if (gpt_partition_type_is_root(type_uuid
))
3866 else if (gpt_partition_type_is_usr(type_uuid
))
3868 else if (gpt_partition_type_is_root_verity(type_uuid
))
3870 else if (gpt_partition_type_is_usr_verity(type_uuid
))
3872 else if (sd_id128_equal(type_uuid
, GPT_ESP
)) {
3875 } else if (sd_id128_equal(type_uuid
, GPT_XBOOTLDR
))
3878 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3879 "Partition type " SD_ID128_FORMAT_STR
" not supported from automatic source block device discovery.",
3880 SD_ID128_FORMAT_VAL(type_uuid
));
3882 r
= find_backing_devno(try1
, root
, &devno
);
3883 if (r
== -ENOENT
&& try2
)
3884 r
= find_backing_devno(try2
, root
, &devno
);
3886 return log_error_errno(r
, "Failed to resolve automatic CopyBlocks= path for partition type " SD_ID128_FORMAT_STR
", sorry: %m",
3887 SD_ID128_FORMAT_VAL(type_uuid
));
3889 xsprintf_sys_block_path(p
, "/slaves", devno
);
3895 _cleanup_free_
char *q
= NULL
, *t
= NULL
;
3900 de
= readdir_no_dot(d
);
3903 return log_error_errno(errno
, "Failed to read directory '%s': %m", p
);
3908 if (!IN_SET(de
->d_type
, DT_LNK
, DT_UNKNOWN
))
3911 q
= path_join(p
, de
->d_name
, "/dev");
3915 r
= read_one_line_file(q
, &t
);
3917 return log_error_errno(r
, "Failed to read %s: %m", q
);
3919 r
= parse_devnum(t
, &sl
);
3921 log_debug_errno(r
, "Failed to parse %s, ignoring: %m", q
);
3924 if (major(sl
) == 0) {
3925 log_debug_errno(r
, "Device backing %s is special, ignoring: %m", q
);
3929 r
= resolve_copy_blocks_auto_candidate(sl
, type_uuid
, restrict_devno
, &u
);
3933 /* We found a matching one! */
3935 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
3936 "Multiple matching partitions found, refusing.");
3942 } else if (errno
!= ENOENT
)
3943 return log_error_errno(errno
, "Failed open %s: %m", p
);
3945 r
= resolve_copy_blocks_auto_candidate(devno
, type_uuid
, restrict_devno
, &found_uuid
);
3953 return log_error_errno(SYNTHETIC_ERRNO(ENXIO
),
3954 "Unable to automatically discover suitable partition to copy blocks from.");
3960 *ret_uuid
= found_uuid
;
3965 static int context_open_copy_block_paths(
3968 dev_t restrict_devno
) {
3974 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3975 _cleanup_close_
int source_fd
= -1;
3976 _cleanup_free_
char *opened
= NULL
;
3977 sd_id128_t uuid
= SD_ID128_NULL
;
3981 assert(p
->copy_blocks_fd
< 0);
3982 assert(p
->copy_blocks_size
== UINT64_MAX
);
3984 if (PARTITION_EXISTS(p
)) /* Never copy over partitions that already exist! */
3987 if (p
->copy_blocks_path
) {
3989 source_fd
= chase_symlinks_and_open(p
->copy_blocks_path
, root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &opened
);
3991 return log_error_errno(source_fd
, "Failed to open '%s': %m", p
->copy_blocks_path
);
3993 if (fstat(source_fd
, &st
) < 0)
3994 return log_error_errno(errno
, "Failed to stat block copy file '%s': %m", opened
);
3996 if (!S_ISREG(st
.st_mode
) && restrict_devno
!= (dev_t
) -1)
3997 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
3998 "Copying from block device node is not permitted in --image=/--root= mode, refusing.");
4000 } else if (p
->copy_blocks_auto
) {
4001 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
4002 const char *devname
;
4005 r
= resolve_copy_blocks_auto(p
->type_uuid
, root
, restrict_devno
, &devno
, &uuid
);
4009 r
= sd_device_new_from_devnum(&dev
, 'b', devno
);
4011 return log_error_errno(r
, "Failed to create sd-device object for device %u:%u: %m", major(devno
), minor(devno
));
4013 r
= sd_device_get_devname(dev
, &devname
);
4015 return log_error_errno(r
, "Failed to get device name of %u:%u: %m", major(devno
), minor(devno
));
4017 opened
= strdup(devname
);
4021 source_fd
= sd_device_open(dev
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
);
4023 return log_error_errno(source_fd
, "Failed to open automatically determined source block copy device '%s': %m", opened
);
4025 if (fstat(source_fd
, &st
) < 0)
4026 return log_error_errno(errno
, "Failed to stat block copy file '%s': %m", opened
);
4030 if (S_ISDIR(st
.st_mode
)) {
4031 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
4034 /* If the file is a directory, automatically find the backing block device */
4036 if (major(st
.st_dev
) != 0)
4037 r
= sd_device_new_from_devnum(&dev
, 'b', st
.st_dev
);
4041 /* Special support for btrfs */
4043 r
= btrfs_get_block_device_fd(source_fd
, &devt
);
4045 return btrfs_log_dev_root(LOG_ERR
, r
, opened
);
4047 return log_error_errno(r
, "Unable to determine backing block device of '%s': %m", opened
);
4049 r
= sd_device_new_from_devnum(&dev
, 'b', devt
);
4052 return log_error_errno(r
, "Failed to create sd-device object for block device backing '%s': %m", opened
);
4054 r
= sd_device_get_devpath(dev
, &bdev
);
4056 return log_error_errno(r
, "Failed to get device name for block device backing '%s': %m", opened
);
4058 safe_close(source_fd
);
4060 source_fd
= sd_device_open(dev
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
);
4062 return log_error_errno(source_fd
, "Failed to open block device '%s': %m", bdev
);
4064 if (fstat(source_fd
, &st
) < 0)
4065 return log_error_errno(errno
, "Failed to stat block device '%s': %m", bdev
);
4068 if (S_ISREG(st
.st_mode
))
4070 else if (S_ISBLK(st
.st_mode
)) {
4071 if (ioctl(source_fd
, BLKGETSIZE64
, &size
) != 0)
4072 return log_error_errno(errno
, "Failed to determine size of block device to copy from: %m");
4074 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
);
4077 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "File to copy bytes from '%s' has zero size, refusing.", opened
);
4078 if (size
% 512 != 0)
4079 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "File to copy bytes from '%s' has size that is not multiple of 512, refusing.", opened
);
4081 p
->copy_blocks_fd
= TAKE_FD(source_fd
);
4082 p
->copy_blocks_size
= size
;
4084 free_and_replace(p
->copy_blocks_path
, opened
);
4086 /* When copying from an existing partition copy that partitions UUID if none is configured explicitly */
4087 if (sd_id128_is_null(p
->new_uuid
) && !sd_id128_is_null(uuid
))
4094 static int help(void) {
4095 _cleanup_free_
char *link
= NULL
;
4098 r
= terminal_urlify_man("systemd-repart", "1", &link
);
4102 printf("%s [OPTIONS...] [DEVICE]\n"
4103 "\n%sGrow and add partitions to partition table.%s\n\n"
4104 " -h --help Show this help\n"
4105 " --version Show package version\n"
4106 " --no-pager Do not pipe output into a pager\n"
4107 " --no-legend Do not show the headers and footers\n"
4108 " --dry-run=BOOL Whether to run dry-run operation\n"
4109 " --empty=MODE One of refuse, allow, require, force, create; controls\n"
4110 " how to handle empty disks lacking partition tables\n"
4111 " --discard=BOOL Whether to discard backing blocks for new partitions\n"
4112 " --pretty=BOOL Whether to show pretty summary before doing changes\n"
4113 " --factory-reset=BOOL Whether to remove data partitions before recreating\n"
4115 " --can-factory-reset Test whether factory reset is defined\n"
4116 " --root=PATH Operate relative to root path\n"
4117 " --image=PATH Operate relative to image file\n"
4118 " --definitions=DIR Find partition definitions in specified directory\n"
4119 " --key-file=PATH Key to use when encrypting partitions\n"
4120 " --tpm2-device=PATH Path to TPM2 device node to use\n"
4121 " --tpm2-pcrs=PCR1+PCR2+PCR3+…\n"
4122 " TPM2 PCR indexes to use for TPM2 enrollment\n"
4123 " --seed=UUID 128bit seed UUID to derive all UUIDs from\n"
4124 " --size=BYTES Grow loopback file to specified size\n"
4125 " --json=pretty|short|off\n"
4126 " Generate JSON output\n"
4127 "\nSee the %s for details.\n",
4128 program_invocation_short_name
,
4136 static int parse_argv(int argc
, char *argv
[]) {
4139 ARG_VERSION
= 0x100,
4146 ARG_CAN_FACTORY_RESET
,
4159 static const struct option options
[] = {
4160 { "help", no_argument
, NULL
, 'h' },
4161 { "version", no_argument
, NULL
, ARG_VERSION
},
4162 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
4163 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
4164 { "dry-run", required_argument
, NULL
, ARG_DRY_RUN
},
4165 { "empty", required_argument
, NULL
, ARG_EMPTY
},
4166 { "discard", required_argument
, NULL
, ARG_DISCARD
},
4167 { "factory-reset", required_argument
, NULL
, ARG_FACTORY_RESET
},
4168 { "can-factory-reset", no_argument
, NULL
, ARG_CAN_FACTORY_RESET
},
4169 { "root", required_argument
, NULL
, ARG_ROOT
},
4170 { "image", required_argument
, NULL
, ARG_IMAGE
},
4171 { "seed", required_argument
, NULL
, ARG_SEED
},
4172 { "pretty", required_argument
, NULL
, ARG_PRETTY
},
4173 { "definitions", required_argument
, NULL
, ARG_DEFINITIONS
},
4174 { "size", required_argument
, NULL
, ARG_SIZE
},
4175 { "json", required_argument
, NULL
, ARG_JSON
},
4176 { "key-file", required_argument
, NULL
, ARG_KEY_FILE
},
4177 { "tpm2-device", required_argument
, NULL
, ARG_TPM2_DEVICE
},
4178 { "tpm2-pcrs", required_argument
, NULL
, ARG_TPM2_PCRS
},
4182 int c
, r
, dry_run
= -1;
4187 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
4198 arg_pager_flags
|= PAGER_DISABLE
;
4206 r
= parse_boolean_argument("--dry-run=", optarg
, &arg_dry_run
);
4212 if (isempty(optarg
) || streq(optarg
, "refuse"))
4213 arg_empty
= EMPTY_REFUSE
;
4214 else if (streq(optarg
, "allow"))
4215 arg_empty
= EMPTY_ALLOW
;
4216 else if (streq(optarg
, "require"))
4217 arg_empty
= EMPTY_REQUIRE
;
4218 else if (streq(optarg
, "force"))
4219 arg_empty
= EMPTY_FORCE
;
4220 else if (streq(optarg
, "create")) {
4221 arg_empty
= EMPTY_CREATE
;
4224 dry_run
= false; /* Imply --dry-run=no if we create the loopback file
4225 * anew. After all we cannot really break anyone's
4226 * partition tables that way. */
4228 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4229 "Failed to parse --empty= parameter: %s", optarg
);
4233 r
= parse_boolean_argument("--discard=", optarg
, &arg_discard
);
4238 case ARG_FACTORY_RESET
:
4239 r
= parse_boolean_argument("--factory-reset=", optarg
, NULL
);
4242 arg_factory_reset
= r
;
4245 case ARG_CAN_FACTORY_RESET
:
4246 arg_can_factory_reset
= true;
4250 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_root
);
4256 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_image
);
4262 if (isempty(optarg
)) {
4263 arg_seed
= SD_ID128_NULL
;
4264 arg_randomize
= false;
4265 } else if (streq(optarg
, "random"))
4266 arg_randomize
= true;
4268 r
= sd_id128_from_string(optarg
, &arg_seed
);
4270 return log_error_errno(r
, "Failed to parse seed: %s", optarg
);
4272 arg_randomize
= false;
4278 r
= parse_boolean_argument("--pretty=", optarg
, NULL
);
4284 case ARG_DEFINITIONS
:
4285 r
= parse_path_argument(optarg
, false, &arg_definitions
);
4291 uint64_t parsed
, rounded
;
4293 if (streq(optarg
, "auto")) {
4294 arg_size
= UINT64_MAX
;
4295 arg_size_auto
= true;
4299 r
= parse_size(optarg
, 1024, &parsed
);
4301 return log_error_errno(r
, "Failed to parse --size= parameter: %s", optarg
);
4303 rounded
= round_up_size(parsed
, 4096);
4305 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too small, refusing.");
4306 if (rounded
== UINT64_MAX
)
4307 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too large, refusing.");
4309 if (rounded
!= parsed
)
4310 log_warning("Specified size is not a multiple of 4096, rounding up automatically. (%" PRIu64
" %s %" PRIu64
")",
4311 parsed
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), rounded
);
4314 arg_size_auto
= false;
4319 r
= parse_json_argument(optarg
, &arg_json_format_flags
);
4325 case ARG_KEY_FILE
: {
4326 _cleanup_(erase_and_freep
) char *k
= NULL
;
4329 r
= read_full_file_full(
4330 AT_FDCWD
, optarg
, UINT64_MAX
, SIZE_MAX
,
4331 READ_FULL_FILE_SECURE
|READ_FULL_FILE_WARN_WORLD_READABLE
|READ_FULL_FILE_CONNECT_SOCKET
,
4335 return log_error_errno(r
, "Failed to read key file '%s': %m", optarg
);
4337 erase_and_free(arg_key
);
4338 arg_key
= TAKE_PTR(k
);
4343 case ARG_TPM2_DEVICE
: {
4344 _cleanup_free_
char *device
= NULL
;
4346 if (streq(optarg
, "list"))
4347 return tpm2_list_devices();
4349 if (!streq(optarg
, "auto")) {
4350 device
= strdup(optarg
);
4355 free(arg_tpm2_device
);
4356 arg_tpm2_device
= TAKE_PTR(device
);
4360 case ARG_TPM2_PCRS
: {
4363 if (isempty(optarg
)) {
4364 arg_tpm2_pcr_mask
= 0;
4368 r
= tpm2_parse_pcrs(optarg
, &mask
);
4372 if (arg_tpm2_pcr_mask
== UINT32_MAX
)
4373 arg_tpm2_pcr_mask
= mask
;
4375 arg_tpm2_pcr_mask
|= mask
;
4384 assert_not_reached();
4387 if (argc
- optind
> 1)
4388 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4389 "Expected at most one argument, the path to the block device.");
4391 if (arg_factory_reset
> 0 && IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
))
4392 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4393 "Combination of --factory-reset=yes and --empty=force/--empty=require/--empty=create is invalid.");
4395 if (arg_can_factory_reset
)
4396 arg_dry_run
= true; /* When --can-factory-reset is specified we don't make changes, hence
4397 * non-dry-run mode makes no sense. Thus, imply dry run mode so that we
4398 * open things strictly read-only. */
4399 else if (dry_run
>= 0)
4400 arg_dry_run
= dry_run
;
4402 if (arg_empty
== EMPTY_CREATE
&& (arg_size
== UINT64_MAX
&& !arg_size_auto
))
4403 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4404 "If --empty=create is specified, --size= must be specified, too.");
4406 if (arg_image
&& arg_root
)
4407 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Please specify either --root= or --image=, the combination of both is not supported.");
4408 else if (!arg_image
&& !arg_root
&& in_initrd()) {
4410 /* By default operate on /sysusr/ or /sysroot/ when invoked in the initrd. We prefer the
4411 * former, if it is mounted, so that we have deterministic behaviour on systems where /usr/
4412 * is vendor-supplied but the root fs formatted on first boot. */
4413 r
= path_is_mount_point("/sysusr/usr", NULL
, 0);
4415 if (r
< 0 && r
!= -ENOENT
)
4416 log_debug_errno(r
, "Unable to determine whether /sysusr/usr is a mount point, assuming it is not: %m");
4418 arg_root
= strdup("/sysroot");
4420 arg_root
= strdup("/sysusr");
4425 arg_node
= argc
> optind
? argv
[optind
] : NULL
;
4427 if (IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
) && !arg_node
&& !arg_image
)
4428 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4429 "A path to a device node or loopback file must be specified when --empty=force, --empty=require or --empty=create are used.");
4431 if (arg_tpm2_pcr_mask
== UINT32_MAX
)
4432 arg_tpm2_pcr_mask
= TPM2_PCR_MASK_DEFAULT
;
4437 static int parse_proc_cmdline_factory_reset(void) {
4441 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
4444 if (!in_initrd()) /* Never honour kernel command line factory reset request outside of the initrd */
4447 r
= proc_cmdline_get_bool("systemd.factory_reset", &b
);
4449 return log_error_errno(r
, "Failed to parse systemd.factory_reset kernel command line argument: %m");
4451 arg_factory_reset
= b
;
4454 log_notice("Honouring factory reset requested via kernel command line.");
4460 static int parse_efi_variable_factory_reset(void) {
4461 _cleanup_free_
char *value
= NULL
;
4464 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
4467 if (!in_initrd()) /* Never honour EFI variable factory reset request outside of the initrd */
4470 r
= efi_get_variable_string(EFI_SYSTEMD_VARIABLE(FactoryReset
), &value
);
4471 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
4474 return log_error_errno(r
, "Failed to read EFI variable FactoryReset: %m");
4476 r
= parse_boolean(value
);
4478 return log_error_errno(r
, "Failed to parse EFI variable FactoryReset: %m");
4480 arg_factory_reset
= r
;
4482 log_notice("Factory reset requested via EFI variable FactoryReset.");
4487 static int remove_efi_variable_factory_reset(void) {
4490 r
= efi_set_variable(EFI_SYSTEMD_VARIABLE(FactoryReset
), NULL
, 0);
4491 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
4494 return log_error_errno(r
, "Failed to remove EFI variable FactoryReset: %m");
4496 log_info("Successfully unset EFI variable FactoryReset.");
4500 static int acquire_root_devno(
4507 _cleanup_free_
char *found_path
= NULL
;
4508 dev_t devno
, fd_devno
= MODE_INVALID
;
4509 _cleanup_close_
int fd
= -1;
4517 fd
= chase_symlinks_and_open(p
, root
, CHASE_PREFIX_ROOT
, mode
, &found_path
);
4521 if (fstat(fd
, &st
) < 0)
4524 if (S_ISREG(st
.st_mode
)) {
4525 *ret
= TAKE_PTR(found_path
);
4526 *ret_fd
= TAKE_FD(fd
);
4530 if (S_ISBLK(st
.st_mode
)) {
4531 /* Refuse referencing explicit block devices if a root dir is specified, after all we should
4532 * not be able to leave the image the root path constrains us to. */
4536 fd_devno
= devno
= st
.st_rdev
;
4537 } else if (S_ISDIR(st
.st_mode
)) {
4540 if (major(devno
) == 0) {
4541 r
= btrfs_get_block_device_fd(fd
, &devno
);
4542 if (r
== -ENOTTY
) /* not btrfs */
4550 /* From dm-crypt to backing partition */
4551 r
= block_get_originating(devno
, &devno
);
4553 log_debug_errno(r
, "Device '%s' has no dm-crypt/dm-verity device, no need to look for underlying block device.", p
);
4555 log_debug_errno(r
, "Failed to find underlying block device for '%s', ignoring: %m", p
);
4557 /* From partition to whole disk containing it */
4558 r
= block_get_whole_disk(devno
, &devno
);
4560 log_debug_errno(r
, "Failed to find whole disk block device for '%s', ignoring: %m", p
);
4562 r
= device_path_make_canonical(S_IFBLK
, devno
, ret
);
4564 return log_debug_errno(r
, "Failed to determine canonical path for '%s': %m", p
);
4566 /* Only if we still look at the same block device we can reuse the fd. Otherwise return an
4567 * invalidated fd. */
4568 *ret_fd
= fd_devno
!= MODE_INVALID
&& fd_devno
== devno
? TAKE_FD(fd
) : -1;
4572 static int find_root(char **ret
, int *ret_fd
) {
4573 _cleanup_free_
char *device
= NULL
;
4580 if (arg_empty
== EMPTY_CREATE
) {
4581 _cleanup_close_
int fd
= -1;
4582 _cleanup_free_
char *s
= NULL
;
4584 s
= strdup(arg_node
);
4588 fd
= open(arg_node
, O_RDONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOFOLLOW
, 0666);
4590 return log_error_errno(errno
, "Failed to create '%s': %m", arg_node
);
4593 *ret_fd
= TAKE_FD(fd
);
4597 /* Note that we don't specify a root argument here: if the user explicitly configured a node
4598 * we'll take it relative to the host, not the image */
4599 r
= acquire_root_devno(arg_node
, NULL
, O_RDONLY
|O_CLOEXEC
, ret
, ret_fd
);
4601 return btrfs_log_dev_root(LOG_ERR
, r
, arg_node
);
4603 return log_error_errno(r
, "Failed to open file or determine backing device of %s: %m", arg_node
);
4608 assert(IN_SET(arg_empty
, EMPTY_REFUSE
, EMPTY_ALLOW
));
4610 /* If the root mount has been replaced by some form of volatile file system (overlayfs), the
4611 * original root block device node is symlinked in /run/systemd/volatile-root. Let's read that
4613 r
= readlink_malloc("/run/systemd/volatile-root", &device
);
4614 if (r
== -ENOENT
) { /* volatile-root not found */
4615 /* Let's search for the root device. We look for two cases here: first in /, and then in /usr. The
4616 * latter we check for cases where / is a tmpfs and only /usr is an actual persistent block device
4617 * (think: volatile setups) */
4619 FOREACH_STRING(p
, "/", "/usr") {
4621 r
= acquire_root_devno(p
, arg_root
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, ret
, ret_fd
);
4624 return btrfs_log_dev_root(LOG_ERR
, r
, p
);
4626 return log_error_errno(r
, "Failed to determine backing device of %s: %m", p
);
4631 return log_error_errno(r
, "Failed to read symlink /run/systemd/volatile-root: %m");
4633 r
= acquire_root_devno(device
, NULL
, O_RDONLY
|O_CLOEXEC
, ret
, ret_fd
);
4635 return btrfs_log_dev_root(LOG_ERR
, r
, device
);
4637 return log_error_errno(r
, "Failed to open file or determine backing device of %s: %m", device
);
4642 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
), "Failed to discover root block device.");
4645 static int resize_pt(int fd
) {
4646 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
4649 /* After resizing the backing file we need to resize the partition table itself too, so that it takes
4650 * possession of the enlarged backing file. For this it suffices to open the device with libfdisk and
4651 * immediately write it again, with no changes. */
4653 c
= fdisk_new_context();
4657 r
= fdisk_assign_device(c
, FORMAT_PROC_FD_PATH(fd
), 0);
4659 return log_error_errno(r
, "Failed to open device '%s': %m", FORMAT_PROC_FD_PATH(fd
));
4661 r
= fdisk_has_label(c
);
4663 return log_error_errno(r
, "Failed to determine whether disk '%s' has a disk label: %m", FORMAT_PROC_FD_PATH(fd
));
4665 log_debug("Not resizing partition table, as there currently is none.");
4669 r
= fdisk_write_disklabel(c
);
4671 return log_error_errno(r
, "Failed to write resized partition table: %m");
4673 log_info("Resized partition table.");
4677 static int resize_backing_fd(
4678 const char *node
, /* The primary way we access the disk image to operate on */
4679 int *fd
, /* An O_RDONLY fd referring to that inode */
4680 const char *backing_file
, /* If the above refers to a loopback device, the backing regular file for that, which we can grow */
4681 LoopDevice
*loop_device
) {
4683 _cleanup_close_
int writable_fd
= -1;
4684 uint64_t current_size
;
4691 if (arg_size
== UINT64_MAX
) /* Nothing to do */
4695 /* Open the file if we haven't opened it yet. Note that we open it read-only here, just to
4696 * keep a reference to the file we can pass around. */
4697 *fd
= open(node
, O_RDONLY
|O_CLOEXEC
);
4699 return log_error_errno(errno
, "Failed to open '%s' in order to adjust size: %m", node
);
4702 if (fstat(*fd
, &st
) < 0)
4703 return log_error_errno(errno
, "Failed to stat '%s': %m", node
);
4705 if (S_ISBLK(st
.st_mode
)) {
4707 return log_error_errno(SYNTHETIC_ERRNO(EBADF
), "Cannot resize block device '%s'.", node
);
4709 assert(loop_device
);
4711 if (ioctl(*fd
, BLKGETSIZE64
, ¤t_size
) < 0)
4712 return log_error_errno(errno
, "Failed to determine size of block device %s: %m", node
);
4714 r
= stat_verify_regular(&st
);
4716 return log_error_errno(r
, "Specified path '%s' is not a regular file or loopback block device, cannot resize: %m", node
);
4718 assert(!backing_file
);
4719 assert(!loop_device
);
4720 current_size
= st
.st_size
;
4723 if (current_size
>= arg_size
) {
4724 log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)",
4725 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
4729 if (S_ISBLK(st
.st_mode
)) {
4730 assert(backing_file
);
4732 /* This is a loopback device. We can't really grow those directly, but we can grow the
4733 * backing file, hence let's do that. */
4735 writable_fd
= open(backing_file
, O_WRONLY
|O_CLOEXEC
|O_NONBLOCK
);
4736 if (writable_fd
< 0)
4737 return log_error_errno(errno
, "Failed to open backing file '%s': %m", backing_file
);
4739 if (fstat(writable_fd
, &st
) < 0)
4740 return log_error_errno(errno
, "Failed to stat() backing file '%s': %m", backing_file
);
4742 r
= stat_verify_regular(&st
);
4744 return log_error_errno(r
, "Backing file '%s' of block device is not a regular file: %m", backing_file
);
4746 if ((uint64_t) st
.st_size
!= current_size
)
4747 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4748 "Size of backing file '%s' of loopback block device '%s' don't match, refusing.",
4749 node
, backing_file
);
4751 assert(S_ISREG(st
.st_mode
));
4752 assert(!backing_file
);
4754 /* The file descriptor is read-only. In order to grow the file we need to have a writable fd. We
4755 * reopen the file for that temporarily. We keep the writable fd only open for this operation though,
4756 * as fdisk can't accept it anyway. */
4758 writable_fd
= fd_reopen(*fd
, O_WRONLY
|O_CLOEXEC
);
4759 if (writable_fd
< 0)
4760 return log_error_errno(writable_fd
, "Failed to reopen backing file '%s' writable: %m", node
);
4764 if (fallocate(writable_fd
, 0, 0, arg_size
) < 0) {
4765 if (!ERRNO_IS_NOT_SUPPORTED(errno
))
4766 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by allocation: %m",
4767 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
4769 /* Fallback to truncation, if fallocate() is not supported. */
4770 log_debug("Backing file system does not support fallocate(), falling back to ftruncate().");
4772 if (current_size
== 0) /* Likely regular file just created by us */
4773 log_info("Allocated %s for '%s'.", FORMAT_BYTES(arg_size
), node
);
4775 log_info("File '%s' grown from %s to %s by allocation.",
4776 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
4782 if (ftruncate(writable_fd
, arg_size
) < 0)
4783 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by truncation: %m",
4784 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
4786 if (current_size
== 0) /* Likely regular file just created by us */
4787 log_info("Sized '%s' to %s.", node
, FORMAT_BYTES(arg_size
));
4789 log_info("File '%s' grown from %s to %s by truncation.",
4790 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
4793 r
= resize_pt(writable_fd
);
4798 r
= loop_device_refresh_size(loop_device
, UINT64_MAX
, arg_size
);
4800 return log_error_errno(r
, "Failed to update loop device size: %m");
4806 static int determine_auto_size(Context
*c
) {
4811 sum
= round_up_size(GPT_METADATA_SIZE
, 4096);
4813 LIST_FOREACH(partitions
, p
, c
->partitions
) {
4819 m
= partition_min_size_with_padding(c
, p
);
4820 if (m
> UINT64_MAX
- sum
)
4821 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Image would grow too large, refusing.");
4826 if (c
->total
!= UINT64_MAX
)
4827 /* Image already allocated? Then show its size. */
4828 log_info("Automatically determined minimal disk image size as %s, current image size is %s.",
4829 FORMAT_BYTES(sum
), FORMAT_BYTES(c
->total
));
4831 /* If the image is being created right now, then it has no previous size, suppress any comment about it hence. */
4832 log_info("Automatically determined minimal disk image size as %s.",
4839 static int run(int argc
, char *argv
[]) {
4840 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
4841 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*decrypted_image
= NULL
;
4842 _cleanup_(umount_and_rmdir_and_freep
) char *mounted_dir
= NULL
;
4843 _cleanup_(context_freep
) Context
* context
= NULL
;
4844 _cleanup_free_
char *node
= NULL
;
4845 _cleanup_close_
int backing_fd
= -1;
4846 bool from_scratch
, node_is_our_loop
= false;
4849 log_show_color(true);
4850 log_parse_environment();
4853 r
= parse_argv(argc
, argv
);
4857 r
= parse_proc_cmdline_factory_reset();
4861 r
= parse_efi_variable_factory_reset();
4865 #if HAVE_LIBCRYPTSETUP
4866 cryptsetup_enable_logging(NULL
);
4872 /* Mount this strictly read-only: we shall modify the partition table, not the file
4874 r
= mount_image_privately_interactively(
4876 DISSECT_IMAGE_MOUNT_READ_ONLY
|
4877 (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) */
4878 DISSECT_IMAGE_GPT_ONLY
|
4879 DISSECT_IMAGE_RELAX_VAR_CHECK
|
4880 DISSECT_IMAGE_USR_NO_ROOT
|
4881 DISSECT_IMAGE_REQUIRE_ROOT
,
4888 arg_root
= strdup(mounted_dir
);
4893 arg_node
= strdup(loop_device
->node
);
4897 /* Remember that the device we are about to manipulate is actually the one we
4898 * allocated here, and thus to increase its backing file we know what to do */
4899 node_is_our_loop
= true;
4903 context
= context_new(arg_seed
);
4907 r
= context_read_definitions(context
, arg_definitions
, arg_root
);
4911 if (context
->n_partitions
<= 0 && arg_empty
== EMPTY_REFUSE
) {
4912 log_info("Didn't find any partition definition files, nothing to do.");
4916 r
= find_root(&node
, &backing_fd
);
4920 if (arg_size
!= UINT64_MAX
) {
4921 r
= resize_backing_fd(
4924 node_is_our_loop
? arg_image
: NULL
,
4925 node_is_our_loop
? loop_device
: NULL
);
4930 r
= context_load_partition_table(context
, node
, &backing_fd
);
4931 if (r
== -EHWPOISON
)
4932 return 77; /* Special return value which means "Not GPT, so not doing anything". This isn't
4933 * really an error when called at boot. */
4936 from_scratch
= r
> 0; /* Starting from scratch */
4938 if (arg_can_factory_reset
) {
4939 r
= context_can_factory_reset(context
);
4943 return EXIT_FAILURE
;
4948 r
= context_factory_reset(context
, from_scratch
);
4952 /* We actually did a factory reset! */
4953 r
= remove_efi_variable_factory_reset();
4957 /* Reload the reduced partition table */
4958 context_unload_partition_table(context
);
4959 r
= context_load_partition_table(context
, node
, &backing_fd
);
4965 (void) context_dump_partitions(context
, node
);
4969 r
= context_read_seed(context
, arg_root
);
4973 /* Open all files to copy blocks from now, since we want to take their size into consideration */
4974 r
= context_open_copy_block_paths(
4977 loop_device
? loop_device
->devno
: /* if --image= is specified, only allow partitions on the loopback device */
4978 arg_root
&& !arg_image
? 0 : /* if --root= is specified, don't accept any block device */
4979 (dev_t
) -1); /* if neither is specified, make no restrictions */
4983 if (arg_size_auto
) {
4984 r
= determine_auto_size(context
);
4988 /* Flush out everything again, and let's grow the file first, then start fresh */
4989 context_unload_partition_table(context
);
4991 assert(arg_size
!= UINT64_MAX
);
4992 r
= resize_backing_fd(
4995 node_is_our_loop
? arg_image
: NULL
,
4996 node_is_our_loop
? loop_device
: NULL
);
5000 r
= context_load_partition_table(context
, node
, &backing_fd
);
5005 /* First try to fit new partitions in, dropping by priority until it fits */
5007 uint64_t largest_free_area
;
5009 if (context_allocate_partitions(context
, &largest_free_area
))
5010 break; /* Success! */
5012 if (!context_drop_one_priority(context
)) {
5013 r
= log_error_errno(SYNTHETIC_ERRNO(ENOSPC
),
5014 "Can't fit requested partitions into available free space (%s), refusing.",
5015 FORMAT_BYTES(largest_free_area
));
5016 determine_auto_size(context
);
5021 /* Now assign free space according to the weight logic */
5022 r
= context_grow_partitions(context
);
5026 /* Now calculate where each new partition gets placed */
5027 context_place_partitions(context
);
5029 /* Make sure each partition has a unique UUID and unique label */
5030 r
= context_acquire_partition_uuids_and_labels(context
);
5034 r
= context_write_partition_table(context
, node
, from_scratch
);
5041 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);