1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 #if HAVE_VALGRIND_MEMCHECK_H
4 #include <valgrind/memcheck.h>
11 #include <linux/loop.h>
13 #include <sys/ioctl.h>
16 #include <openssl/hmac.h>
17 #include <openssl/sha.h>
21 #include "alloc-util.h"
22 #include "blkid-util.h"
23 #include "blockdev-util.h"
24 #include "btrfs-util.h"
25 #include "conf-files.h"
26 #include "conf-parser.h"
29 #include "errno-util.h"
31 #include "format-table.h"
32 #include "format-util.h"
35 #include "id128-util.h"
37 #include "locale-util.h"
38 #include "main-func.h"
39 #include "parse-util.h"
40 #include "path-util.h"
41 #include "pretty-print.h"
42 #include "proc-cmdline.h"
43 #include "sort-util.h"
44 #include "specifier.h"
45 #include "stat-util.h"
46 #include "stdio-util.h"
47 #include "string-util.h"
49 #include "terminal-util.h"
52 /* If not configured otherwise use a minimal partition size of 10M */
53 #define DEFAULT_MIN_SIZE (10*1024*1024)
55 /* Hard lower limit for new partition sizes */
56 #define HARD_MIN_SIZE 4096
58 /* Note: When growing and placing new partitions we always align to 4K sector size. It's how newer hard disks
59 * are designed, and if everything is aligned to that performance is best. And for older hard disks with 512B
60 * sector size devices were generally assumed to have an even number of sectors, hence at the worst we'll
61 * waste 3K per partition, which is probably fine. */
64 EMPTY_REFUSE
, /* refuse empty disks, never create a partition table */
65 EMPTY_ALLOW
, /* allow empty disks, create partition table if necessary */
66 EMPTY_REQUIRE
, /* require an empty disk, create a partition table */
67 EMPTY_FORCE
, /* make disk empty, erase everything, create a partition table always */
68 EMPTY_CREATE
, /* create disk as loopback file, create a partition table always */
69 } arg_empty
= EMPTY_REFUSE
;
71 static bool arg_dry_run
= true;
72 static const char *arg_node
= NULL
;
73 static char *arg_root
= NULL
;
74 static char *arg_definitions
= NULL
;
75 static bool arg_discard
= true;
76 static bool arg_can_factory_reset
= false;
77 static int arg_factory_reset
= -1;
78 static sd_id128_t arg_seed
= SD_ID128_NULL
;
79 static bool arg_randomize
= false;
80 static int arg_pretty
= -1;
81 static uint64_t arg_size
= UINT64_MAX
;
83 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
84 STATIC_DESTRUCTOR_REGISTER(arg_definitions
, freep
);
86 typedef struct Partition Partition
;
87 typedef struct FreeArea FreeArea
;
88 typedef struct Context Context
;
91 char *definition_path
;
94 sd_id128_t current_uuid
, new_uuid
;
95 char *current_label
, *new_label
;
101 uint32_t weight
, padding_weight
;
103 uint64_t current_size
, new_size
;
104 uint64_t size_min
, size_max
;
106 uint64_t current_padding
, new_padding
;
107 uint64_t padding_min
, padding_max
;
112 struct fdisk_partition
*current_partition
;
113 struct fdisk_partition
*new_partition
;
114 FreeArea
*padding_area
;
115 FreeArea
*allocated_to_area
;
117 LIST_FIELDS(Partition
, partitions
);
120 #define PARTITION_IS_FOREIGN(p) (!(p)->definition_path)
121 #define PARTITION_EXISTS(p) (!!(p)->current_partition)
130 LIST_HEAD(Partition
, partitions
);
133 FreeArea
**free_areas
;
134 size_t n_free_areas
, n_allocated_free_areas
;
136 uint64_t start
, end
, total
;
138 struct fdisk_context
*fdisk_context
;
143 static uint64_t round_down_size(uint64_t v
, uint64_t p
) {
147 static uint64_t round_up_size(uint64_t v
, uint64_t p
) {
149 v
= DIV_ROUND_UP(v
, p
);
151 if (v
> UINT64_MAX
/ p
)
152 return UINT64_MAX
; /* overflow */
157 static Partition
*partition_new(void) {
160 p
= new(Partition
, 1);
167 .current_size
= UINT64_MAX
,
168 .new_size
= UINT64_MAX
,
169 .size_min
= UINT64_MAX
,
170 .size_max
= UINT64_MAX
,
171 .current_padding
= UINT64_MAX
,
172 .new_padding
= UINT64_MAX
,
173 .padding_min
= UINT64_MAX
,
174 .padding_max
= UINT64_MAX
,
175 .partno
= UINT64_MAX
,
176 .offset
= UINT64_MAX
,
182 static Partition
* partition_free(Partition
*p
) {
186 free(p
->current_label
);
188 free(p
->definition_path
);
190 if (p
->current_partition
)
191 fdisk_unref_partition(p
->current_partition
);
192 if (p
->new_partition
)
193 fdisk_unref_partition(p
->new_partition
);
198 static Partition
* partition_unlink_and_free(Context
*context
, Partition
*p
) {
202 LIST_REMOVE(partitions
, context
->partitions
, p
);
204 assert(context
->n_partitions
> 0);
205 context
->n_partitions
--;
207 return partition_free(p
);
210 DEFINE_TRIVIAL_CLEANUP_FUNC(Partition
*, partition_free
);
212 static Context
*context_new(sd_id128_t seed
) {
215 context
= new(Context
, 1);
219 *context
= (Context
) {
229 static void context_free_free_areas(Context
*context
) {
232 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
233 free(context
->free_areas
[i
]);
235 context
->free_areas
= mfree(context
->free_areas
);
236 context
->n_free_areas
= 0;
237 context
->n_allocated_free_areas
= 0;
240 static Context
*context_free(Context
*context
) {
244 while (context
->partitions
)
245 partition_unlink_and_free(context
, context
->partitions
);
246 assert(context
->n_partitions
== 0);
248 context_free_free_areas(context
);
250 if (context
->fdisk_context
)
251 fdisk_unref_context(context
->fdisk_context
);
253 return mfree(context
);
256 DEFINE_TRIVIAL_CLEANUP_FUNC(Context
*, context_free
);
258 static int context_add_free_area(
266 assert(!after
|| !after
->padding_area
);
268 if (!GREEDY_REALLOC(context
->free_areas
, context
->n_allocated_free_areas
, context
->n_free_areas
+ 1))
271 a
= new(FreeArea
, 1);
280 context
->free_areas
[context
->n_free_areas
++] = a
;
283 after
->padding_area
= a
;
288 static bool context_drop_one_priority(Context
*context
) {
289 int32_t priority
= 0;
293 LIST_FOREACH(partitions
, p
, context
->partitions
) {
296 if (p
->priority
< priority
)
298 if (p
->priority
== priority
) {
299 exists
= exists
|| PARTITION_EXISTS(p
);
303 priority
= p
->priority
;
304 exists
= PARTITION_EXISTS(p
);
307 /* Refuse to drop partitions with 0 or negative priorities or partitions of priorities that have at
308 * least one existing priority */
309 if (priority
<= 0 || exists
)
312 LIST_FOREACH(partitions
, p
, context
->partitions
) {
313 if (p
->priority
< priority
)
320 log_info("Can't fit partition %s of priority %" PRIi32
", dropping.", p
->definition_path
, p
->priority
);
326 static uint64_t partition_min_size(const Partition
*p
) {
329 /* Calculate the disk space we really need at minimum for this partition. If the partition already
330 * exists the current size is what we really need. If it doesn't exist yet refuse to allocate less
333 * DEFAULT_MIN_SIZE is the default SizeMin= we configure if nothing else is specified. */
335 if (PARTITION_IS_FOREIGN(p
)) {
336 /* Don't allow changing size of partitions not managed by us */
337 assert(p
->current_size
!= UINT64_MAX
);
338 return p
->current_size
;
341 sz
= p
->current_size
!= UINT64_MAX
? p
->current_size
: HARD_MIN_SIZE
;
342 return MAX(p
->size_min
== UINT64_MAX
? DEFAULT_MIN_SIZE
: p
->size_min
, sz
);
345 static uint64_t partition_max_size(const Partition
*p
) {
346 /* Calculate how large the partition may become at max. This is generally the configured maximum
347 * size, except when it already exists and is larger than that. In that case it's the existing size,
348 * since we never want to shrink partitions. */
350 if (PARTITION_IS_FOREIGN(p
)) {
351 /* Don't allow changing size of partitions not managed by us */
352 assert(p
->current_size
!= UINT64_MAX
);
353 return p
->current_size
;
356 if (p
->current_size
!= UINT64_MAX
)
357 return MAX(p
->current_size
, p
->size_max
);
362 static uint64_t partition_min_size_with_padding(const Partition
*p
) {
365 /* Calculate the disk space we need for this partition plus any free space coming after it. This
366 * takes user configured padding into account as well as any additional whitespace needed to align
367 * the next partition to 4K again. */
369 sz
= partition_min_size(p
);
371 if (p
->padding_min
!= UINT64_MAX
)
372 sz
+= p
->padding_min
;
374 if (PARTITION_EXISTS(p
)) {
375 /* If the partition wasn't aligned, add extra space so that any we might add will be aligned */
376 assert(p
->offset
!= UINT64_MAX
);
377 return round_up_size(p
->offset
+ sz
, 4096) - p
->offset
;
380 /* If this is a new partition we'll place it aligned, hence we just need to round up the required size here */
381 return round_up_size(sz
, 4096);
384 static uint64_t free_area_available(const FreeArea
*a
) {
387 /* Determines how much of this free area is not allocated yet */
389 assert(a
->size
>= a
->allocated
);
390 return a
->size
- a
->allocated
;
393 static uint64_t free_area_available_for_new_partitions(const FreeArea
*a
) {
396 /* Similar to free_area_available(), but takes into account that the required size and padding of the
397 * preceding partition is honoured. */
399 avail
= free_area_available(a
);
401 uint64_t need
, space
;
403 need
= partition_min_size_with_padding(a
->after
);
405 assert(a
->after
->offset
!= UINT64_MAX
);
406 assert(a
->after
->current_size
!= UINT64_MAX
);
408 space
= round_up_size(a
->after
->offset
+ a
->after
->current_size
, 4096) - a
->after
->offset
+ avail
;
418 static int free_area_compare(FreeArea
*const *a
, FreeArea
*const*b
) {
419 return CMP(free_area_available_for_new_partitions(*a
),
420 free_area_available_for_new_partitions(*b
));
423 static uint64_t charge_size(uint64_t total
, uint64_t amount
) {
426 assert(amount
<= total
);
428 /* Subtract the specified amount from total, rounding up to multiple of 4K if there's room */
429 rounded
= round_up_size(amount
, 4096);
430 if (rounded
>= total
)
433 return total
- rounded
;
436 static uint64_t charge_weight(uint64_t total
, uint64_t amount
) {
437 assert(amount
<= total
);
438 return total
- amount
;
441 static bool context_allocate_partitions(Context
*context
) {
446 /* A simple first-fit algorithm, assuming the array of free areas is sorted by size in decreasing
449 LIST_FOREACH(partitions
, p
, context
->partitions
) {
454 /* Skip partitions we already dropped or that already exist */
455 if (p
->dropped
|| PARTITION_EXISTS(p
))
459 typesafe_qsort(context
->free_areas
, context
->n_free_areas
, free_area_compare
);
461 /* How much do we need to fit? */
462 required
= partition_min_size_with_padding(p
);
463 assert(required
% 4096 == 0);
465 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
466 a
= context
->free_areas
[i
];
468 if (free_area_available_for_new_partitions(a
) >= required
) {
475 return false; /* 😢 Oh no! We can't fit this partition into any free area! */
477 /* Assign the partition to this free area */
478 p
->allocated_to_area
= a
;
480 /* Budget the minimal partition size */
481 a
->allocated
+= required
;
487 static int context_sum_weights(Context
*context
, FreeArea
*a
, uint64_t *ret
) {
488 uint64_t weight_sum
= 0;
495 /* Determine the sum of the weights of all partitions placed in or before the specified free area */
497 LIST_FOREACH(partitions
, p
, context
->partitions
) {
498 if (p
->padding_area
!= a
&& p
->allocated_to_area
!= a
)
501 if (p
->weight
> UINT64_MAX
- weight_sum
)
503 weight_sum
+= p
->weight
;
505 if (p
->padding_weight
> UINT64_MAX
- weight_sum
)
507 weight_sum
+= p
->padding_weight
;
514 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Combined weight of partition exceeds unsigned 64bit range, refusing.");
517 static int scale_by_weight(uint64_t value
, uint64_t weight
, uint64_t weight_sum
, uint64_t *ret
) {
518 assert(weight_sum
>= weight
);
526 if (value
> UINT64_MAX
/ weight
)
527 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Scaling by weight of partition exceeds unsigned 64bit range, refusing.");
529 *ret
= value
* weight
/ weight_sum
;
533 typedef enum GrowPartitionPhase
{
534 /* The first phase: we charge partitions which need more (according to constraints) than their weight-based share. */
537 /* The second phase: we charge partitions which need less (according to constraints) than their weight-based share. */
540 /* The third phase: we distribute what remains among the remaining partitions, according to the weights */
542 } GrowPartitionPhase
;
544 static int context_grow_partitions_phase(
547 GrowPartitionPhase phase
,
549 uint64_t *weight_sum
) {
557 /* Now let's look at the intended weights and adjust them taking the minimum space assignments into
558 * account. i.e. if a partition has a small weight but a high minimum space value set it should not
559 * get any additional room from the left-overs. Similar, if two partitions have the same weight they
560 * should get the same space if possible, even if one has a smaller minimum size than the other. */
561 LIST_FOREACH(partitions
, p
, context
->partitions
) {
563 /* Look only at partitions associated with this free area, i.e. immediately
564 * preceding it, or allocated into it */
565 if (p
->allocated_to_area
!= a
&& p
->padding_area
!= a
)
568 if (p
->new_size
== UINT64_MAX
) {
569 bool charge
= false, try_again
= false;
570 uint64_t share
, rsz
, xsz
;
572 /* Calculate how much this space this partition needs if everyone would get
573 * the weight based share */
574 r
= scale_by_weight(*span
, p
->weight
, *weight_sum
, &share
);
578 rsz
= partition_min_size(p
);
579 xsz
= partition_max_size(p
);
581 if (phase
== PHASE_OVERCHARGE
&& rsz
> share
) {
582 /* This partition needs more than its calculated share. Let's assign
583 * it that, and take this partition out of all calculations and start
587 charge
= try_again
= true;
589 } else if (phase
== PHASE_UNDERCHARGE
&& xsz
!= UINT64_MAX
&& xsz
< share
) {
590 /* This partition accepts less than its calculated
591 * share. Let's assign it that, and take this partition out
592 * of all calculations and start again. */
595 charge
= try_again
= true;
597 } else if (phase
== PHASE_DISTRIBUTE
) {
598 /* This partition can accept its calculated share. Let's
599 * assign it. There's no need to restart things here since
600 * assigning this shouldn't impact the shares of the other
603 if (PARTITION_IS_FOREIGN(p
))
604 /* Never change of foreign partitions (i.e. those we don't manage) */
605 p
->new_size
= p
->current_size
;
607 p
->new_size
= MAX(round_down_size(share
, 4096), rsz
);
613 *span
= charge_size(*span
, p
->new_size
);
614 *weight_sum
= charge_weight(*weight_sum
, p
->weight
);
618 return 0; /* try again */
621 if (p
->new_padding
== UINT64_MAX
) {
622 bool charge
= false, try_again
= false;
625 r
= scale_by_weight(*span
, p
->padding_weight
, *weight_sum
, &share
);
629 if (phase
== PHASE_OVERCHARGE
&& p
->padding_min
!= UINT64_MAX
&& p
->padding_min
> share
) {
630 p
->new_padding
= p
->padding_min
;
631 charge
= try_again
= true;
632 } else if (phase
== PHASE_UNDERCHARGE
&& p
->padding_max
!= UINT64_MAX
&& p
->padding_max
< share
) {
633 p
->new_padding
= p
->padding_max
;
634 charge
= try_again
= true;
635 } else if (phase
== PHASE_DISTRIBUTE
) {
637 p
->new_padding
= round_down_size(share
, 4096);
638 if (p
->padding_min
!= UINT64_MAX
&& p
->new_padding
< p
->padding_min
)
639 p
->new_padding
= p
->padding_min
;
645 *span
= charge_size(*span
, p
->new_padding
);
646 *weight_sum
= charge_weight(*weight_sum
, p
->padding_weight
);
650 return 0; /* try again */
657 static int context_grow_partitions_on_free_area(Context
*context
, FreeArea
*a
) {
658 uint64_t weight_sum
= 0, span
;
664 r
= context_sum_weights(context
, a
, &weight_sum
);
668 /* Let's calculate the total area covered by this free area and the partition before it */
671 assert(a
->after
->offset
!= UINT64_MAX
);
672 assert(a
->after
->current_size
!= UINT64_MAX
);
674 span
+= round_up_size(a
->after
->offset
+ a
->after
->current_size
, 4096) - a
->after
->offset
;
677 GrowPartitionPhase phase
= PHASE_OVERCHARGE
;
679 r
= context_grow_partitions_phase(context
, a
, phase
, &span
, &weight_sum
);
682 if (r
== 0) /* not done yet, re-run this phase */
685 if (phase
== PHASE_OVERCHARGE
)
686 phase
= PHASE_UNDERCHARGE
;
687 else if (phase
== PHASE_UNDERCHARGE
)
688 phase
= PHASE_DISTRIBUTE
;
689 else if (phase
== PHASE_DISTRIBUTE
)
693 /* We still have space left over? Donate to preceding partition if we have one */
694 if (span
> 0 && a
->after
&& !PARTITION_IS_FOREIGN(a
->after
)) {
697 assert(a
->after
->new_size
!= UINT64_MAX
);
698 m
= a
->after
->new_size
+ span
;
700 xsz
= partition_max_size(a
->after
);
701 if (xsz
!= UINT64_MAX
&& m
> xsz
)
704 span
= charge_size(span
, m
- a
->after
->new_size
);
705 a
->after
->new_size
= m
;
708 /* What? Even still some space left (maybe because there was no preceding partition, or it had a
709 * size limit), then let's donate it to whoever wants it. */
713 LIST_FOREACH(partitions
, p
, context
->partitions
) {
716 if (p
->allocated_to_area
!= a
)
719 if (PARTITION_IS_FOREIGN(p
))
722 assert(p
->new_size
!= UINT64_MAX
);
723 m
= p
->new_size
+ span
;
725 xsz
= partition_max_size(p
);
726 if (xsz
!= UINT64_MAX
&& m
> xsz
)
729 span
= charge_size(span
, m
- p
->new_size
);
737 /* Yuck, still no one? Then make it padding */
738 if (span
> 0 && a
->after
) {
739 assert(a
->after
->new_padding
!= UINT64_MAX
);
740 a
->after
->new_padding
+= span
;
746 static int context_grow_partitions(Context
*context
) {
752 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
753 r
= context_grow_partitions_on_free_area(context
, context
->free_areas
[i
]);
758 /* All existing partitions that have no free space after them can't change size */
759 LIST_FOREACH(partitions
, p
, context
->partitions
) {
763 if (!PARTITION_EXISTS(p
) || p
->padding_area
) {
764 /* The algorithm above must have initialized this already */
765 assert(p
->new_size
!= UINT64_MAX
);
769 assert(p
->new_size
== UINT64_MAX
);
770 p
->new_size
= p
->current_size
;
772 assert(p
->new_padding
== UINT64_MAX
);
773 p
->new_padding
= p
->current_padding
;
779 static void context_place_partitions(Context
*context
) {
785 /* Determine next partition number to assign */
786 LIST_FOREACH(partitions
, p
, context
->partitions
) {
787 if (!PARTITION_EXISTS(p
))
790 assert(p
->partno
!= UINT64_MAX
);
791 if (p
->partno
>= partno
)
792 partno
= p
->partno
+ 1;
795 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
796 FreeArea
*a
= context
->free_areas
[i
];
797 uint64_t start
, left
;
800 assert(a
->after
->offset
!= UINT64_MAX
);
801 assert(a
->after
->new_size
!= UINT64_MAX
);
802 assert(a
->after
->new_padding
!= UINT64_MAX
);
804 start
= a
->after
->offset
+ a
->after
->new_size
+ a
->after
->new_padding
;
806 start
= context
->start
;
808 start
= round_up_size(start
, 4096);
811 LIST_FOREACH(partitions
, p
, context
->partitions
) {
812 if (p
->allocated_to_area
!= a
)
816 p
->partno
= partno
++;
818 assert(left
>= p
->new_size
);
819 start
+= p
->new_size
;
822 assert(left
>= p
->new_padding
);
823 start
+= p
->new_padding
;
824 left
-= p
->new_padding
;
829 static int config_parse_type(
831 const char *filename
,
834 unsigned section_line
,
841 sd_id128_t
*type_uuid
= data
;
847 r
= gpt_partition_type_uuid_from_string(rvalue
, type_uuid
);
849 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to parse partition type: %s", rvalue
);
854 static int config_parse_label(
856 const char *filename
,
859 unsigned section_line
,
866 static const Specifier specifier_table
[] = {
867 { 'm', specifier_machine_id
, NULL
},
868 { 'b', specifier_boot_id
, NULL
},
869 { 'H', specifier_host_name
, NULL
},
870 { 'l', specifier_short_host_name
, NULL
},
871 { 'v', specifier_kernel_release
, NULL
},
872 { 'a', specifier_architecture
, NULL
},
873 { 'o', specifier_os_id
, NULL
},
874 { 'w', specifier_os_version_id
, NULL
},
875 { 'B', specifier_os_build_id
, NULL
},
876 { 'W', specifier_os_variant_id
, NULL
},
880 _cleanup_free_ char16_t
*recoded
= NULL
;
881 _cleanup_free_
char *resolved
= NULL
;
888 r
= specifier_printf(rvalue
, specifier_table
, NULL
, &resolved
);
890 log_syntax(unit
, LOG_ERR
, filename
, line
, r
,
891 "Failed to expand specifiers in Label=, ignoring: %s", rvalue
);
895 if (!utf8_is_valid(resolved
)) {
896 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
897 "Partition label not valid UTF-8, ignoring: %s", rvalue
);
901 recoded
= utf8_to_utf16(resolved
, strlen(resolved
));
905 if (char16_strlen(recoded
) > 36) {
906 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
907 "Partition label too long for GPT table, ignoring: %s", rvalue
);
911 free_and_replace(*label
, resolved
);
915 static int config_parse_weight(
917 const char *filename
,
920 unsigned section_line
,
927 uint32_t *priority
= data
, v
;
933 r
= safe_atou32(rvalue
, &v
);
935 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
936 "Failed to parse weight value, ignoring: %s", rvalue
);
940 if (v
> 1000U*1000U) {
941 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
942 "Weight needs to be in range 0…10000000, ignoring: %" PRIu32
, v
);
950 static int config_parse_size4096(
952 const char *filename
,
955 unsigned section_line
,
962 uint64_t *sz
= data
, parsed
;
968 r
= parse_size(rvalue
, 1024, &parsed
);
970 return log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
971 "Failed to parse size value: %s", rvalue
);
974 *sz
= round_up_size(parsed
, 4096);
976 *sz
= round_down_size(parsed
, 4096);
981 log_syntax(unit
, LOG_NOTICE
, filename
, line
, r
, "Rounded %s= size %" PRIu64
" → %" PRIu64
", a multiple of 4096.", lvalue
, parsed
, *sz
);
986 static int partition_read_definition(Partition
*p
, const char *path
) {
988 ConfigTableItem table
[] = {
989 { "Partition", "Type", config_parse_type
, 0, &p
->type_uuid
},
990 { "Partition", "Label", config_parse_label
, 0, &p
->new_label
},
991 { "Partition", "UUID", config_parse_id128
, 0, &p
->new_uuid
},
992 { "Partition", "Priority", config_parse_int32
, 0, &p
->priority
},
993 { "Partition", "Weight", config_parse_weight
, 0, &p
->weight
},
994 { "Partition", "PaddingWeight", config_parse_weight
, 0, &p
->padding_weight
},
995 { "Partition", "SizeMinBytes", config_parse_size4096
, 1, &p
->size_min
},
996 { "Partition", "SizeMaxBytes", config_parse_size4096
, -1, &p
->size_max
},
997 { "Partition", "PaddingMinBytes", config_parse_size4096
, 1, &p
->padding_min
},
998 { "Partition", "PaddingMaxBytes", config_parse_size4096
, -1, &p
->padding_max
},
999 { "Partition", "FactoryReset", config_parse_bool
, 0, &p
->factory_reset
},
1004 r
= config_parse(NULL
, path
, NULL
,
1006 config_item_table_lookup
, table
,
1013 if (p
->size_min
!= UINT64_MAX
&& p
->size_max
!= UINT64_MAX
&& p
->size_min
> p
->size_max
)
1014 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1015 "SizeMinBytes= larger than SizeMaxBytes=, refusing.");
1017 if (p
->padding_min
!= UINT64_MAX
&& p
->padding_max
!= UINT64_MAX
&& p
->padding_min
> p
->padding_max
)
1018 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1019 "PaddingMinBytes= larger than PaddingMaxBytes=, refusing.");
1021 if (sd_id128_is_null(p
->type_uuid
))
1022 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1023 "Type= not defined, refusing.");
1028 static int context_read_definitions(
1030 const char *directory
,
1033 _cleanup_strv_free_
char **files
= NULL
;
1034 Partition
*last
= NULL
;
1041 r
= conf_files_list_strv(&files
, ".conf", NULL
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, (const char**) STRV_MAKE(directory
));
1043 r
= conf_files_list_strv(&files
, ".conf", root
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, (const char**) CONF_PATHS_STRV("repart.d"));
1045 return log_error_errno(r
, "Failed to enumerate *.conf files: %m");
1047 STRV_FOREACH(f
, files
) {
1048 _cleanup_(partition_freep
) Partition
*p
= NULL
;
1050 p
= partition_new();
1054 p
->definition_path
= strdup(*f
);
1055 if (!p
->definition_path
)
1058 r
= partition_read_definition(p
, *f
);
1062 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, p
);
1064 context
->n_partitions
++;
1070 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_context
*, fdisk_unref_context
);
1071 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_partition
*, fdisk_unref_partition
);
1072 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_parttype
*, fdisk_unref_parttype
);
1073 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_table
*, fdisk_unref_table
);
1075 static int determine_current_padding(
1076 struct fdisk_context
*c
,
1077 struct fdisk_table
*t
,
1078 struct fdisk_partition
*p
,
1081 size_t n_partitions
;
1082 uint64_t offset
, next
= UINT64_MAX
;
1088 if (!fdisk_partition_has_end(p
))
1089 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition has no end!");
1091 offset
= fdisk_partition_get_end(p
);
1092 assert(offset
< UINT64_MAX
/ 512);
1095 n_partitions
= fdisk_table_get_nents(t
);
1096 for (size_t i
= 0; i
< n_partitions
; i
++) {
1097 struct fdisk_partition
*q
;
1100 q
= fdisk_table_get_partition(t
, i
);
1102 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1104 if (fdisk_partition_is_used(q
) <= 0)
1107 if (!fdisk_partition_has_start(q
))
1110 start
= fdisk_partition_get_start(q
);
1111 assert(start
< UINT64_MAX
/ 512);
1114 if (start
>= offset
&& (next
== UINT64_MAX
|| next
> start
))
1118 if (next
== UINT64_MAX
) {
1119 /* No later partition? In that case check the end of the usable area */
1120 next
= fdisk_get_last_lba(c
);
1121 assert(next
< UINT64_MAX
);
1122 next
++; /* The last LBA is one sector before the end */
1124 assert(next
< UINT64_MAX
/ 512);
1128 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
1131 assert(next
>= offset
);
1132 offset
= round_up_size(offset
, 4096);
1133 next
= round_down_size(next
, 4096);
1135 if (next
>= offset
) /* Check again, rounding might have fucked things up */
1136 *ret
= next
- offset
;
1143 static int fdisk_ask_cb(struct fdisk_context
*c
, struct fdisk_ask
*ask
, void *data
) {
1144 _cleanup_free_
char *ids
= NULL
;
1147 if (fdisk_ask_get_type(ask
) != FDISK_ASKTYPE_STRING
)
1150 ids
= new(char, ID128_UUID_STRING_MAX
);
1154 r
= fdisk_ask_string_set_result(ask
, id128_to_uuid_string(*(sd_id128_t
*) data
, ids
));
1162 static int fdisk_set_disklabel_id_by_uuid(struct fdisk_context
*c
, sd_id128_t id
) {
1165 r
= fdisk_set_ask(c
, fdisk_ask_cb
, &id
);
1169 r
= fdisk_set_disklabel_id(c
);
1173 return fdisk_set_ask(c
, NULL
, NULL
);
1176 #define DISK_UUID_TOKEN "disk-uuid"
1178 static int disk_acquire_uuid(Context
*context
, sd_id128_t
*ret
) {
1180 unsigned char md
[SHA256_DIGEST_LENGTH
];
1187 /* Calculate the HMAC-SHA256 of the string "disk-uuid", keyed off the machine ID. We use the machine
1188 * ID as key (and not as cleartext!) since it's the machine ID we don't want to leak. */
1190 if (!HMAC(EVP_sha256(),
1191 &context
->seed
, sizeof(context
->seed
),
1192 (const unsigned char*) DISK_UUID_TOKEN
, strlen(DISK_UUID_TOKEN
),
1194 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "HMAC-SHA256 calculation failed.");
1196 /* Take the first half, mark it as v4 UUID */
1197 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
1198 *ret
= id128_make_v4_uuid(result
.id
);
1202 static int context_load_partition_table(
1207 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
1208 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
1209 uint64_t left_boundary
= UINT64_MAX
, first_lba
, last_lba
, nsectors
;
1210 _cleanup_free_
char *disk_uuid_string
= NULL
;
1211 bool from_scratch
= false;
1212 sd_id128_t disk_uuid
;
1213 size_t n_partitions
;
1220 c
= fdisk_new_context();
1224 /* libfdisk doesn't have an API to operate on arbitrary fds, hence reopen the fd going via the
1225 * /proc/self/fd/ magic path if we have an existing fd. Open the original file otherwise. */
1226 if (*backing_fd
< 0)
1227 r
= fdisk_assign_device(c
, node
, arg_dry_run
);
1229 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1230 xsprintf(procfs_path
, "/proc/self/fd/%i", *backing_fd
);
1232 r
= fdisk_assign_device(c
, procfs_path
, arg_dry_run
);
1235 return log_error_errno(r
, "Failed to open device '%s': %m", node
);
1237 if (*backing_fd
< 0) {
1238 /* If we have no fd referencing the device yet, make a copy of the fd now, so that we have one */
1239 *backing_fd
= fcntl(fdisk_get_devfd(c
), F_DUPFD_CLOEXEC
, 3);
1240 if (*backing_fd
< 0)
1241 return log_error_errno(errno
, "Failed to duplicate fdisk fd: %m");
1244 /* Tell udev not to interfere while we are processing the device */
1245 if (flock(fdisk_get_devfd(c
), arg_dry_run
? LOCK_SH
: LOCK_EX
) < 0)
1246 return log_error_errno(errno
, "Failed to lock block device: %m");
1248 switch (arg_empty
) {
1251 /* Refuse empty disks, insist on an existing GPT partition table */
1252 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
1253 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has no GPT disk label, not repartitioning.", node
);
1258 /* Require an empty disk, refuse any existing partition table */
1259 r
= fdisk_has_label(c
);
1261 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", node
);
1263 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s already has a disk label, refusing.", node
);
1265 from_scratch
= true;
1269 /* Allow both an empty disk and an existing partition table, but only GPT */
1270 r
= fdisk_has_label(c
);
1272 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", node
);
1274 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
1275 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has non-GPT disk label, not repartitioning.", node
);
1277 from_scratch
= true;
1283 /* Always reinitiaize the disk, don't consider what there was on the disk before */
1284 from_scratch
= true;
1289 r
= fdisk_enable_wipe(c
, true);
1291 return log_error_errno(r
, "Failed to enable wiping of disk signature: %m");
1293 r
= fdisk_create_disklabel(c
, "gpt");
1295 return log_error_errno(r
, "Failed to create GPT disk label: %m");
1297 r
= disk_acquire_uuid(context
, &disk_uuid
);
1299 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
1301 r
= fdisk_set_disklabel_id_by_uuid(c
, disk_uuid
);
1303 return log_error_errno(r
, "Failed to set GPT disk label: %m");
1305 goto add_initial_free_area
;
1308 r
= fdisk_get_disklabel_id(c
, &disk_uuid_string
);
1310 return log_error_errno(r
, "Failed to get current GPT disk label UUID: %m");
1312 r
= sd_id128_from_string(disk_uuid_string
, &disk_uuid
);
1314 return log_error_errno(r
, "Failed to parse current GPT disk label UUID: %m");
1316 if (sd_id128_is_null(disk_uuid
)) {
1317 r
= disk_acquire_uuid(context
, &disk_uuid
);
1319 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
1321 r
= fdisk_set_disklabel_id(c
);
1323 return log_error_errno(r
, "Failed to set GPT disk label: %m");
1326 r
= fdisk_get_partitions(c
, &t
);
1328 return log_error_errno(r
, "Failed to acquire partition table: %m");
1330 n_partitions
= fdisk_table_get_nents(t
);
1331 for (size_t i
= 0; i
< n_partitions
; i
++) {
1332 _cleanup_free_
char *label_copy
= NULL
;
1333 Partition
*pp
, *last
= NULL
;
1334 struct fdisk_partition
*p
;
1335 struct fdisk_parttype
*pt
;
1336 const char *pts
, *ids
, *label
;
1339 sd_id128_t ptid
, id
;
1342 p
= fdisk_table_get_partition(t
, i
);
1344 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1346 if (fdisk_partition_is_used(p
) <= 0)
1349 if (fdisk_partition_has_start(p
) <= 0 ||
1350 fdisk_partition_has_size(p
) <= 0 ||
1351 fdisk_partition_has_partno(p
) <= 0)
1352 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a position, size or number.");
1354 pt
= fdisk_partition_get_type(p
);
1356 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to acquire type of partition: %m");
1358 pts
= fdisk_parttype_get_string(pt
);
1360 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to acquire type of partition as string: %m");
1362 r
= sd_id128_from_string(pts
, &ptid
);
1364 return log_error_errno(r
, "Failed to parse partition type UUID %s: %m", pts
);
1366 ids
= fdisk_partition_get_uuid(p
);
1368 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a UUID.");
1370 r
= sd_id128_from_string(ids
, &id
);
1372 return log_error_errno(r
, "Failed to parse partition UUID %s: %m", ids
);
1374 label
= fdisk_partition_get_name(p
);
1375 if (!isempty(label
)) {
1376 label_copy
= strdup(label
);
1381 sz
= fdisk_partition_get_size(p
);
1382 assert_se(sz
<= UINT64_MAX
/512);
1385 start
= fdisk_partition_get_start(p
);
1386 assert_se(start
<= UINT64_MAX
/512);
1389 partno
= fdisk_partition_get_partno(p
);
1391 if (left_boundary
== UINT64_MAX
|| left_boundary
> start
)
1392 left_boundary
= start
;
1394 /* Assign this existing partition to the first partition of the right type that doesn't have
1395 * an existing one assigned yet. */
1396 LIST_FOREACH(partitions
, pp
, context
->partitions
) {
1399 if (!sd_id128_equal(pp
->type_uuid
, ptid
))
1402 if (!pp
->current_partition
) {
1403 pp
->current_uuid
= id
;
1404 pp
->current_size
= sz
;
1406 pp
->partno
= partno
;
1407 pp
->current_label
= TAKE_PTR(label_copy
);
1409 pp
->current_partition
= p
;
1410 fdisk_ref_partition(p
);
1412 r
= determine_current_padding(c
, t
, p
, &pp
->current_padding
);
1416 if (pp
->current_padding
> 0) {
1417 r
= context_add_free_area(context
, pp
->current_padding
, pp
);
1427 /* If we have no matching definition, create a new one. */
1429 _cleanup_(partition_freep
) Partition
*np
= NULL
;
1431 np
= partition_new();
1435 np
->current_uuid
= id
;
1436 np
->type_uuid
= ptid
;
1437 np
->current_size
= sz
;
1439 np
->partno
= partno
;
1440 np
->current_label
= TAKE_PTR(label_copy
);
1442 np
->current_partition
= p
;
1443 fdisk_ref_partition(p
);
1445 r
= determine_current_padding(c
, t
, p
, &np
->current_padding
);
1449 if (np
->current_padding
> 0) {
1450 r
= context_add_free_area(context
, np
->current_padding
, np
);
1455 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, TAKE_PTR(np
));
1456 context
->n_partitions
++;
1460 add_initial_free_area
:
1461 nsectors
= fdisk_get_nsectors(c
);
1462 assert(nsectors
<= UINT64_MAX
/512);
1465 first_lba
= fdisk_get_first_lba(c
);
1466 assert(first_lba
<= UINT64_MAX
/512);
1469 last_lba
= fdisk_get_last_lba(c
);
1470 assert(last_lba
< UINT64_MAX
);
1472 assert(last_lba
<= UINT64_MAX
/512);
1475 assert(last_lba
>= first_lba
);
1477 if (left_boundary
== UINT64_MAX
) {
1478 /* No partitions at all? Then the whole disk is up for grabs. */
1480 first_lba
= round_up_size(first_lba
, 4096);
1481 last_lba
= round_down_size(last_lba
, 4096);
1483 if (last_lba
> first_lba
) {
1484 r
= context_add_free_area(context
, last_lba
- first_lba
, NULL
);
1489 /* Add space left of first partition */
1490 assert(left_boundary
>= first_lba
);
1492 first_lba
= round_up_size(first_lba
, 4096);
1493 left_boundary
= round_down_size(left_boundary
, 4096);
1494 last_lba
= round_down_size(last_lba
, 4096);
1496 if (left_boundary
> first_lba
) {
1497 r
= context_add_free_area(context
, left_boundary
- first_lba
, NULL
);
1503 context
->start
= first_lba
;
1504 context
->end
= last_lba
;
1505 context
->total
= nsectors
;
1506 context
->fdisk_context
= TAKE_PTR(c
);
1508 return from_scratch
;
1511 static void context_unload_partition_table(Context
*context
) {
1512 Partition
*p
, *next
;
1516 LIST_FOREACH_SAFE(partitions
, p
, next
, context
->partitions
) {
1518 /* Entirely remove partitions that have no configuration */
1519 if (PARTITION_IS_FOREIGN(p
)) {
1520 partition_unlink_and_free(context
, p
);
1524 /* Otherwise drop all data we read off the block device and everything we might have
1525 * calculated based on it */
1528 p
->current_size
= UINT64_MAX
;
1529 p
->new_size
= UINT64_MAX
;
1530 p
->current_padding
= UINT64_MAX
;
1531 p
->new_padding
= UINT64_MAX
;
1532 p
->partno
= UINT64_MAX
;
1533 p
->offset
= UINT64_MAX
;
1535 if (p
->current_partition
) {
1536 fdisk_unref_partition(p
->current_partition
);
1537 p
->current_partition
= NULL
;
1540 if (p
->new_partition
) {
1541 fdisk_unref_partition(p
->new_partition
);
1542 p
->new_partition
= NULL
;
1545 p
->padding_area
= NULL
;
1546 p
->allocated_to_area
= NULL
;
1548 p
->current_uuid
= p
->new_uuid
= SD_ID128_NULL
;
1551 context
->start
= UINT64_MAX
;
1552 context
->end
= UINT64_MAX
;
1553 context
->total
= UINT64_MAX
;
1555 if (context
->fdisk_context
) {
1556 fdisk_unref_context(context
->fdisk_context
);
1557 context
->fdisk_context
= NULL
;
1560 context_free_free_areas(context
);
1563 static int format_size_change(uint64_t from
, uint64_t to
, char **ret
) {
1564 char format_buffer1
[FORMAT_BYTES_MAX
], format_buffer2
[FORMAT_BYTES_MAX
], *buf
;
1566 if (from
!= UINT64_MAX
)
1567 format_bytes(format_buffer1
, sizeof(format_buffer1
), from
);
1568 if (to
!= UINT64_MAX
)
1569 format_bytes(format_buffer2
, sizeof(format_buffer2
), to
);
1571 if (from
!= UINT64_MAX
) {
1572 if (from
== to
|| to
== UINT64_MAX
)
1573 buf
= strdup(format_buffer1
);
1575 buf
= strjoin(format_buffer1
, " ", special_glyph(SPECIAL_GLYPH_ARROW
), " ", format_buffer2
);
1576 } else if (to
!= UINT64_MAX
)
1577 buf
= strjoin(special_glyph(SPECIAL_GLYPH_ARROW
), " ", format_buffer2
);
1586 *ret
= TAKE_PTR(buf
);
1590 static const char *partition_label(const Partition
*p
) {
1594 return p
->new_label
;
1596 if (p
->current_label
)
1597 return p
->current_label
;
1599 return gpt_partition_type_uuid_to_string(p
->type_uuid
);
1602 static int context_dump_partitions(Context
*context
, const char *node
) {
1603 _cleanup_(table_unrefp
) Table
*t
= NULL
;
1604 uint64_t sum_padding
= 0, sum_size
= 0;
1608 t
= table_new("type", "label", "uuid", "file", "node", "offset", "raw size", "size", "raw padding", "padding");
1613 (void) table_set_display(t
, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4, (size_t) 7, (size_t) 9, (size_t) -1);
1615 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 4), 100);
1616 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 5), 100);
1618 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1619 _cleanup_free_
char *size_change
= NULL
, *padding_change
= NULL
, *partname
= NULL
;
1620 char uuid_buffer
[ID128_UUID_STRING_MAX
];
1626 label
= partition_label(p
);
1627 partname
= p
->partno
!= UINT64_MAX
? fdisk_partname(node
, p
->partno
+1) : NULL
;
1629 r
= format_size_change(p
->current_size
, p
->new_size
, &size_change
);
1633 r
= format_size_change(p
->current_padding
, p
->new_padding
, &padding_change
);
1637 if (p
->new_size
!= UINT64_MAX
)
1638 sum_size
+= p
->new_size
;
1639 if (p
->new_padding
!= UINT64_MAX
)
1640 sum_padding
+= p
->new_padding
;
1644 TABLE_STRING
, gpt_partition_type_uuid_to_string_harder(p
->type_uuid
, uuid_buffer
),
1645 TABLE_STRING
, label
?: "-", TABLE_SET_COLOR
, label
? NULL
: ansi_grey(),
1646 TABLE_UUID
, sd_id128_is_null(p
->new_uuid
) ? p
->current_uuid
: p
->new_uuid
,
1647 TABLE_STRING
, p
->definition_path
? basename(p
->definition_path
) : "-", TABLE_SET_COLOR
, p
->definition_path
? NULL
: ansi_grey(),
1648 TABLE_STRING
, partname
?: "no", TABLE_SET_COLOR
, partname
? NULL
: ansi_highlight(),
1649 TABLE_UINT64
, p
->offset
,
1650 TABLE_UINT64
, p
->new_size
,
1651 TABLE_STRING
, size_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_size
> 0 ? ansi_underline() : NULL
,
1652 TABLE_UINT64
, p
->new_padding
,
1653 TABLE_STRING
, padding_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_padding
> 0 ? ansi_underline() : NULL
);
1655 return log_error_errno(r
, "Failed to add row to table: %m");
1658 if (sum_padding
> 0 || sum_size
> 0) {
1659 char s
[FORMAT_BYTES_MAX
];
1662 a
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", format_bytes(s
, sizeof(s
), sum_size
));
1663 b
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", format_bytes(s
, sizeof(s
), sum_padding
));
1678 return log_error_errno(r
, "Failed to add row to table: %m");
1681 r
= table_print(t
, stdout
);
1683 return log_error_errno(r
, "Failed to dump table: %m");
1688 static void context_bar_char_process_partition(
1693 size_t *ret_start
) {
1695 uint64_t from
, to
, total
;
1706 assert(p
->offset
!= UINT64_MAX
);
1707 assert(p
->new_size
!= UINT64_MAX
);
1710 to
= from
+ p
->new_size
;
1712 assert(context
->end
>= context
->start
);
1713 total
= context
->end
- context
->start
;
1715 assert(from
>= context
->start
);
1716 assert(from
<= context
->end
);
1717 x
= (from
- context
->start
) * n
/ total
;
1719 assert(to
>= context
->start
);
1720 assert(to
<= context
->end
);
1721 y
= (to
- context
->start
) * n
/ total
;
1726 for (size_t i
= x
; i
< y
; i
++)
1732 static int partition_hint(const Partition
*p
, const char *node
, char **ret
) {
1733 _cleanup_free_
char *buf
= NULL
;
1734 char ids
[ID128_UUID_STRING_MAX
];
1738 /* Tries really hard to find a suitable description for this partition */
1740 if (p
->definition_path
) {
1741 buf
= strdup(basename(p
->definition_path
));
1745 label
= partition_label(p
);
1746 if (!isempty(label
)) {
1747 buf
= strdup(label
);
1751 if (p
->partno
!= UINT64_MAX
) {
1752 buf
= fdisk_partname(node
, p
->partno
+1);
1756 if (!sd_id128_is_null(p
->new_uuid
))
1758 else if (!sd_id128_is_null(p
->current_uuid
))
1759 id
= p
->current_uuid
;
1763 buf
= strdup(id128_to_uuid_string(id
, ids
));
1769 *ret
= TAKE_PTR(buf
);
1773 static int context_dump_partition_bar(Context
*context
, const char *node
) {
1774 _cleanup_free_ Partition
**bar
= NULL
;
1775 _cleanup_free_
size_t *start_array
= NULL
;
1776 Partition
*p
, *last
= NULL
;
1780 assert_se((c
= columns()) >= 2);
1781 c
-= 2; /* We do not use the leftmost and rightmost character cell */
1783 bar
= new0(Partition
*, c
);
1787 start_array
= new(size_t, context
->n_partitions
);
1791 LIST_FOREACH(partitions
, p
, context
->partitions
)
1792 context_bar_char_process_partition(context
, bar
, c
, p
, start_array
+ j
++);
1796 for (size_t i
= 0; i
< c
; i
++) {
1801 fputs(z
? ansi_green() : ansi_yellow(), stdout
);
1802 fputs(special_glyph(SPECIAL_GLYPH_DARK_SHADE
), stdout
);
1804 fputs(ansi_normal(), stdout
);
1805 fputs(special_glyph(SPECIAL_GLYPH_LIGHT_SHADE
), stdout
);
1811 fputs(ansi_normal(), stdout
);
1814 for (size_t i
= 0; i
< context
->n_partitions
; i
++) {
1815 _cleanup_free_
char **line
= NULL
;
1817 line
= new0(char*, c
);
1822 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1823 _cleanup_free_
char *d
= NULL
;
1826 if (i
< context
->n_partitions
- j
) {
1828 if (line
[start_array
[j
-1]]) {
1831 /* Upgrade final corner to the right with a branch to the right */
1832 e
= startswith(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
1834 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), e
);
1841 d
= strdup(special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
));
1846 } else if (i
== context
->n_partitions
- j
) {
1847 _cleanup_free_
char *hint
= NULL
;
1849 (void) partition_hint(p
, node
, &hint
);
1851 if (streq_ptr(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
)))
1852 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), " ", strna(hint
));
1854 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), " ", strna(hint
));
1861 free_and_replace(line
[start_array
[j
-1]], d
);
1869 fputs(line
[j
], stdout
);
1870 j
+= utf8_console_width(line
[j
]);
1879 for (j
= 0; j
< c
; j
++)
1886 static bool context_changed(const Context
*context
) {
1889 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1893 if (p
->allocated_to_area
)
1896 if (p
->new_size
!= p
->current_size
)
1903 static int context_wipe_partition(Context
*context
, Partition
*p
) {
1904 _cleanup_(blkid_free_probep
) blkid_probe probe
= NULL
;
1909 assert(!PARTITION_EXISTS(p
)); /* Safety check: never wipe existing partitions */
1911 probe
= blkid_new_probe();
1915 assert(p
->offset
!= UINT64_MAX
);
1916 assert(p
->new_size
!= UINT64_MAX
);
1919 r
= blkid_probe_set_device(probe
, fdisk_get_devfd(context
->fdisk_context
), p
->offset
, p
->new_size
);
1921 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to allocate device probe for partition %" PRIu64
".", p
->partno
);
1924 if (blkid_probe_enable_superblocks(probe
, true) < 0 ||
1925 blkid_probe_set_superblocks_flags(probe
, BLKID_SUBLKS_MAGIC
|BLKID_SUBLKS_BADCSUM
) < 0 ||
1926 blkid_probe_enable_partitions(probe
, true) < 0 ||
1927 blkid_probe_set_partitions_flags(probe
, BLKID_PARTS_MAGIC
) < 0)
1928 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to enable superblock and partition probing for partition %" PRIu64
".", p
->partno
);
1932 r
= blkid_do_probe(probe
);
1934 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to probe for file systems.");
1939 if (blkid_do_wipe(probe
, false) < 0)
1940 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to wipe file system signature.");
1943 log_info("Successfully wiped file system signatures from partition %" PRIu64
".", p
->partno
);
1947 static int context_discard_range(Context
*context
, uint64_t offset
, uint64_t size
) {
1952 assert(offset
!= UINT64_MAX
);
1953 assert(size
!= UINT64_MAX
);
1958 assert_se((fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
1960 if (fstat(fd
, &st
) < 0)
1963 if (S_ISREG(st
.st_mode
)) {
1964 if (fallocate(fd
, FALLOC_FL_PUNCH_HOLE
|FALLOC_FL_KEEP_SIZE
, offset
, size
) < 0) {
1965 if (ERRNO_IS_NOT_SUPPORTED(errno
))
1974 if (S_ISBLK(st
.st_mode
)) {
1975 uint64_t range
[2], end
;
1977 range
[0] = round_up_size(offset
, 512);
1979 end
= offset
+ size
;
1980 if (end
<= range
[0])
1983 range
[1] = round_down_size(end
- range
[0], 512);
1987 if (ioctl(fd
, BLKDISCARD
, range
) < 0) {
1988 if (ERRNO_IS_NOT_SUPPORTED(errno
))
2000 static int context_discard_partition(Context
*context
, Partition
*p
) {
2006 assert(p
->offset
!= UINT64_MAX
);
2007 assert(p
->new_size
!= UINT64_MAX
);
2008 assert(!PARTITION_EXISTS(p
)); /* Safety check: never discard existing partitions */
2013 r
= context_discard_range(context
, p
->offset
, p
->new_size
);
2014 if (r
== -EOPNOTSUPP
) {
2015 log_info("Storage does not support discarding, not discarding data in new partition %" PRIu64
".", p
->partno
);
2019 log_info("Partition %" PRIu64
" too short for discard, skipping.", p
->partno
);
2023 return log_error_errno(r
, "Failed to discard data for new partition %" PRIu64
".", p
->partno
);
2025 log_info("Successfully discarded data from partition %" PRIu64
".", p
->partno
);
2029 static int context_discard_gap_after(Context
*context
, Partition
*p
) {
2030 uint64_t gap
, next
= UINT64_MAX
;
2035 assert(!p
|| (p
->offset
!= UINT64_MAX
&& p
->new_size
!= UINT64_MAX
));
2038 gap
= p
->offset
+ p
->new_size
;
2040 gap
= context
->start
;
2042 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2046 assert(q
->offset
!= UINT64_MAX
);
2047 assert(q
->new_size
!= UINT64_MAX
);
2049 if (q
->offset
< gap
)
2052 if (next
== UINT64_MAX
|| q
->offset
< next
)
2056 if (next
== UINT64_MAX
) {
2057 next
= context
->end
;
2059 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
2062 assert(next
>= gap
);
2063 r
= context_discard_range(context
, gap
, next
- gap
);
2064 if (r
== -EOPNOTSUPP
) {
2066 log_info("Storage does not support discarding, not discarding gap after partition %" PRIu64
".", p
->partno
);
2068 log_info("Storage does not support discarding, not discarding gap at beginning of disk.");
2071 if (r
== 0) /* Too short */
2075 return log_error_errno(r
, "Failed to discard gap after partition %" PRIu64
".", p
->partno
);
2077 return log_error_errno(r
, "Failed to discard gap at beginning of disk.");
2081 log_info("Successfully discarded gap after partition %" PRIu64
".", p
->partno
);
2083 log_info("Successfully discarded gap at beginning of disk.");
2088 static int context_wipe_and_discard(Context
*context
, bool from_scratch
) {
2094 /* Wipe and discard the contents of all partitions we are about to create. We skip the discarding if
2095 * we were supposed to start from scratch anyway, as in that case we just discard the whole block
2096 * device in one go early on. */
2098 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2100 if (!p
->allocated_to_area
)
2103 if (!from_scratch
) {
2104 r
= context_discard_partition(context
, p
);
2109 r
= context_wipe_partition(context
, p
);
2113 if (!from_scratch
) {
2114 r
= context_discard_gap_after(context
, p
);
2120 if (!from_scratch
) {
2121 r
= context_discard_gap_after(context
, NULL
);
2129 static int partition_acquire_uuid(Context
*context
, Partition
*p
, sd_id128_t
*ret
) {
2131 sd_id128_t type_uuid
;
2133 } _packed_ plaintext
= {};
2135 unsigned char md
[SHA256_DIGEST_LENGTH
];
2147 /* Calculate a good UUID for the indicated partition. We want a certain degree of reproducibility,
2148 * hence we won't generate the UUIDs randomly. Instead we use a cryptographic hash (precisely:
2149 * HMAC-SHA256) to derive them from a single seed. The seed is generally the machine ID of the
2150 * installation we are processing, but if random behaviour is desired can be random, too. We use the
2151 * seed value as key for the HMAC (since the machine ID is something we generally don't want to leak)
2152 * and the partition type as plaintext. The partition type is suffixed with a counter (only for the
2153 * second and later partition of the same type) if we have more than one partition of the same
2154 * time. Or in other words:
2157 * SEED := /etc/machine-id
2159 * If first partition instance of type TYPE_UUID:
2160 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID)
2162 * For all later partition instances of type TYPE_UUID with INSTANCE being the LE64 encoded instance number:
2163 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID || INSTANCE)
2166 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2170 if (!sd_id128_equal(p
->type_uuid
, q
->type_uuid
))
2176 plaintext
.type_uuid
= p
->type_uuid
;
2177 plaintext
.counter
= htole64(k
);
2179 if (!HMAC(EVP_sha256(),
2180 &context
->seed
, sizeof(context
->seed
),
2181 (const unsigned char*) &plaintext
, k
== 0 ? sizeof(sd_id128_t
) : sizeof(plaintext
),
2183 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "SHA256 calculation failed.");
2185 /* Take the first half, mark it as v4 UUID */
2186 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
2187 result
.id
= id128_make_v4_uuid(result
.id
);
2189 /* Ensure this partition UUID is actually unique, and there's no remaining partition from an earlier run? */
2190 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2194 if (sd_id128_equal(q
->current_uuid
, result
.id
) ||
2195 sd_id128_equal(q
->new_uuid
, result
.id
)) {
2196 log_warning("Partition UUID calculated from seed for partition %" PRIu64
" exists already, reverting to randomized UUID.", p
->partno
);
2198 r
= sd_id128_randomize(&result
.id
);
2200 return log_error_errno(r
, "Failed to generate randomized UUID: %m");
2210 static int partition_acquire_label(Context
*context
, Partition
*p
, char **ret
) {
2211 _cleanup_free_
char *label
= NULL
;
2219 prefix
= gpt_partition_type_uuid_to_string(p
->type_uuid
);
2224 const char *ll
= label
?: prefix
;
2228 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2232 if (streq_ptr(ll
, q
->current_label
) ||
2233 streq_ptr(ll
, q
->new_label
)) {
2242 label
= mfree(label
);
2245 if (asprintf(&label
, "%s-%u", prefix
, ++k
) < 0)
2250 label
= strdup(prefix
);
2255 *ret
= TAKE_PTR(label
);
2259 static int context_acquire_partition_uuids_and_labels(Context
*context
) {
2265 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2266 /* Never touch foreign partitions */
2267 if (PARTITION_IS_FOREIGN(p
)) {
2268 p
->new_uuid
= p
->current_uuid
;
2270 if (p
->current_label
) {
2272 p
->new_label
= strdup(p
->current_label
);
2280 if (!sd_id128_is_null(p
->current_uuid
))
2281 p
->new_uuid
= p
->current_uuid
; /* Never change initialized UUIDs */
2282 else if (sd_id128_is_null(p
->new_uuid
)) {
2283 /* Not explicitly set by user! */
2284 r
= partition_acquire_uuid(context
, p
, &p
->new_uuid
);
2289 if (!isempty(p
->current_label
)) {
2291 p
->new_label
= strdup(p
->current_label
); /* never change initialized labels */
2294 } else if (!p
->new_label
) {
2295 /* Not explicitly set by user! */
2297 r
= partition_acquire_label(context
, p
, &p
->new_label
);
2306 static int device_kernel_partitions_supported(int fd
) {
2307 struct loop_info64 info
;
2312 if (fstat(fd
, &st
) < 0)
2313 return log_error_errno(fd
, "Failed to fstat() image file: %m");
2314 if (!S_ISBLK(st
.st_mode
))
2315 return -ENOTBLK
; /* we do not log in this one special case about errors */
2317 if (ioctl(fd
, LOOP_GET_STATUS64
, &info
) < 0) {
2319 if (ERRNO_IS_NOT_SUPPORTED(errno
) || errno
== EINVAL
)
2320 return true; /* not a loopback device, let's assume partition are supported */
2322 return log_error_errno(fd
, "Failed to issue LOOP_GET_STATUS64 on block device: %m");
2325 #if HAVE_VALGRIND_MEMCHECK_H
2326 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
2327 VALGRIND_MAKE_MEM_DEFINED(&info
, sizeof(info
));
2330 return FLAGS_SET(info
.lo_flags
, LO_FLAGS_PARTSCAN
);
2333 static int context_write_partition_table(
2336 bool from_scratch
) {
2338 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*original_table
= NULL
;
2344 if (arg_pretty
> 0 ||
2345 (arg_pretty
< 0 && isatty(STDOUT_FILENO
) > 0)) {
2347 if (context
->n_partitions
== 0)
2348 puts("Empty partition table.");
2350 (void) context_dump_partitions(context
, node
);
2354 (void) context_dump_partition_bar(context
, node
);
2359 if (!from_scratch
&& !context_changed(context
)) {
2360 log_info("No changes.");
2365 log_notice("Refusing to repartition, please re-run with --dry-run=no.");
2369 log_info("Applying changes.");
2372 r
= context_discard_range(context
, 0, context
->total
);
2373 if (r
== -EOPNOTSUPP
)
2374 log_info("Storage does not support discarding, not discarding entire block device data.");
2376 return log_error_errno(r
, "Failed to discard entire block device: %m");
2378 log_info("Discarded entire block device.");
2381 r
= fdisk_get_partitions(context
->fdisk_context
, &original_table
);
2383 return log_error_errno(r
, "Failed to acquire partition table: %m");
2385 /* Wipe fs signatures and discard sectors where the new partitions are going to be placed and in the
2386 * gaps between partitions, just to be sure. */
2387 r
= context_wipe_and_discard(context
, from_scratch
);
2391 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2395 assert(p
->new_size
!= UINT64_MAX
);
2396 assert(p
->offset
!= UINT64_MAX
);
2397 assert(p
->partno
!= UINT64_MAX
);
2399 if (PARTITION_EXISTS(p
)) {
2400 bool changed
= false;
2402 assert(p
->current_partition
);
2404 if (p
->new_size
!= p
->current_size
) {
2405 assert(p
->new_size
>= p
->current_size
);
2406 assert(p
->new_size
% 512 == 0);
2408 r
= fdisk_partition_size_explicit(p
->current_partition
, true);
2410 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
2412 r
= fdisk_partition_set_size(p
->current_partition
, p
->new_size
/ 512);
2414 return log_error_errno(r
, "Failed to grow partition: %m");
2416 log_info("Growing existing partition %" PRIu64
".", p
->partno
);
2420 if (!sd_id128_equal(p
->new_uuid
, p
->current_uuid
)) {
2421 char buf
[ID128_UUID_STRING_MAX
];
2423 assert(!sd_id128_is_null(p
->new_uuid
));
2425 r
= fdisk_partition_set_uuid(p
->current_partition
, id128_to_uuid_string(p
->new_uuid
, buf
));
2427 return log_error_errno(r
, "Failed to set partition UUID: %m");
2429 log_info("Initializing UUID of existing partition %" PRIu64
".", p
->partno
);
2433 if (!streq_ptr(p
->new_label
, p
->current_label
)) {
2434 assert(!isempty(p
->new_label
));
2436 r
= fdisk_partition_set_name(p
->current_partition
, p
->new_label
);
2438 return log_error_errno(r
, "Failed to set partition label: %m");
2440 log_info("Setting partition label of existing partition %" PRIu64
".", p
->partno
);
2445 assert(!PARTITION_IS_FOREIGN(p
)); /* never touch foreign partitions */
2447 r
= fdisk_set_partition(context
->fdisk_context
, p
->partno
, p
->current_partition
);
2449 return log_error_errno(r
, "Failed to update partition: %m");
2452 _cleanup_(fdisk_unref_partitionp
) struct fdisk_partition
*q
= NULL
;
2453 _cleanup_(fdisk_unref_parttypep
) struct fdisk_parttype
*t
= NULL
;
2454 char ids
[ID128_UUID_STRING_MAX
];
2456 assert(!p
->new_partition
);
2457 assert(p
->offset
% 512 == 0);
2458 assert(p
->new_size
% 512 == 0);
2459 assert(!sd_id128_is_null(p
->new_uuid
));
2460 assert(!isempty(p
->new_label
));
2462 t
= fdisk_new_parttype();
2466 r
= fdisk_parttype_set_typestr(t
, id128_to_uuid_string(p
->type_uuid
, ids
));
2468 return log_error_errno(r
, "Failed to initialize partition type: %m");
2470 q
= fdisk_new_partition();
2474 r
= fdisk_partition_set_type(q
, t
);
2476 return log_error_errno(r
, "Failed to set partition type: %m");
2478 r
= fdisk_partition_size_explicit(q
, true);
2480 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
2482 r
= fdisk_partition_set_start(q
, p
->offset
/ 512);
2484 return log_error_errno(r
, "Failed to position partition: %m");
2486 r
= fdisk_partition_set_size(q
, p
->new_size
/ 512);
2488 return log_error_errno(r
, "Failed to grow partition: %m");
2490 r
= fdisk_partition_set_partno(q
, p
->partno
);
2492 return log_error_errno(r
, "Failed to set partition number: %m");
2494 r
= fdisk_partition_set_uuid(q
, id128_to_uuid_string(p
->new_uuid
, ids
));
2496 return log_error_errno(r
, "Failed to set partition UUID: %m");
2498 r
= fdisk_partition_set_name(q
, p
->new_label
);
2500 return log_error_errno(r
, "Failed to set partition label: %m");
2502 log_info("Creating new partition %" PRIu64
".", p
->partno
);
2504 r
= fdisk_add_partition(context
->fdisk_context
, q
, NULL
);
2506 return log_error_errno(r
, "Failed to add partition: %m");
2508 assert(!p
->new_partition
);
2509 p
->new_partition
= TAKE_PTR(q
);
2513 log_info("Writing new partition table.");
2515 r
= fdisk_write_disklabel(context
->fdisk_context
);
2517 return log_error_errno(r
, "Failed to write partition table: %m");
2519 capable
= device_kernel_partitions_supported(fdisk_get_devfd(context
->fdisk_context
));
2520 if (capable
== -ENOTBLK
)
2521 log_debug("Not telling kernel to reread partition table, since we are not operating on a block device.");
2522 else if (capable
< 0)
2524 else if (capable
> 0) {
2525 log_info("Telling kernel to reread partition table.");
2528 r
= fdisk_reread_partition_table(context
->fdisk_context
);
2530 r
= fdisk_reread_changes(context
->fdisk_context
, original_table
);
2532 return log_error_errno(r
, "Failed to reread partition table: %m");
2534 log_notice("Not telling kernel to reread partition table, because selected image does not support kernel partition block devices.");
2536 log_info("All done.");
2541 static int context_read_seed(Context
*context
, const char *root
) {
2546 if (!sd_id128_is_null(context
->seed
))
2549 if (!arg_randomize
) {
2550 _cleanup_close_
int fd
= -1;
2552 fd
= chase_symlinks_and_open("/etc/machine-id", root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
, NULL
);
2554 log_info("No machine ID set, using randomized partition UUIDs.");
2556 return log_error_errno(fd
, "Failed to determine machine ID of image: %m");
2558 r
= id128_read_fd(fd
, ID128_PLAIN
, &context
->seed
);
2559 if (r
== -ENOMEDIUM
)
2560 log_info("No machine ID set, using randomized partition UUIDs.");
2562 return log_error_errno(r
, "Failed to parse machine ID of image: %m");
2568 r
= sd_id128_randomize(&context
->seed
);
2570 return log_error_errno(r
, "Failed to generate randomized seed: %m");
2575 static int context_factory_reset(Context
*context
, bool from_scratch
) {
2582 if (arg_factory_reset
<= 0)
2585 if (from_scratch
) /* Nothing to reset if we start from scratch */
2589 log_notice("Refusing to factory reset, please re-run with --dry-run=no.");
2593 log_info("Applying factory reset.");
2595 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2597 if (!p
->factory_reset
|| !PARTITION_EXISTS(p
))
2600 assert(p
->partno
!= UINT64_MAX
);
2602 log_info("Removing partition %" PRIu64
" for factory reset.", p
->partno
);
2604 r
= fdisk_delete_partition(context
->fdisk_context
, p
->partno
);
2606 return log_error_errno(r
, "Failed to remove partition %" PRIu64
": %m", p
->partno
);
2612 log_info("Factory reset requested, but no partitions to delete found.");
2616 r
= fdisk_write_disklabel(context
->fdisk_context
);
2618 return log_error_errno(r
, "Failed to write disk label: %m");
2620 log_info("Successfully deleted %zu partitions.", n
);
2624 static int context_can_factory_reset(Context
*context
) {
2629 LIST_FOREACH(partitions
, p
, context
->partitions
)
2630 if (p
->factory_reset
&& PARTITION_EXISTS(p
))
2636 static int help(void) {
2637 _cleanup_free_
char *link
= NULL
;
2640 r
= terminal_urlify_man("systemd-repart", "1", &link
);
2644 printf("%s [OPTIONS...] [DEVICE]\n"
2645 "\n%sGrow and add partitions to partition table.%s\n\n"
2646 " -h --help Show this help\n"
2647 " --version Show package version\n"
2648 " --dry-run=BOOL Whether to run dry-run operation\n"
2649 " --empty=MODE One of refuse, allow, require, force, create; controls\n"
2650 " how to handle empty disks lacking partition tables\n"
2651 " --discard=BOOL Whether to discard backing blocks for new partitions\n"
2652 " --pretty=BOOL Whether to show pretty summary before executing operation\n"
2653 " --factory-reset=BOOL Whether to remove data partitions before recreating\n"
2655 " --can-factory-reset Test whether factory reset is defined\n"
2656 " --root=PATH Operate relative to root path\n"
2657 " --definitions=DIR Find partitions in specified directory\n"
2658 " --seed=UUID 128bit seed UUID to derive all UUIDs from\n"
2659 " --size=BYTES Grow loopback file to specified size\n"
2660 "\nSee the %s for details.\n"
2661 , program_invocation_short_name
2662 , ansi_highlight(), ansi_normal()
2669 static int parse_argv(int argc
, char *argv
[]) {
2672 ARG_VERSION
= 0x100,
2677 ARG_CAN_FACTORY_RESET
,
2685 static const struct option options
[] = {
2686 { "help", no_argument
, NULL
, 'h' },
2687 { "version", no_argument
, NULL
, ARG_VERSION
},
2688 { "dry-run", required_argument
, NULL
, ARG_DRY_RUN
},
2689 { "empty", required_argument
, NULL
, ARG_EMPTY
},
2690 { "discard", required_argument
, NULL
, ARG_DISCARD
},
2691 { "factory-reset", required_argument
, NULL
, ARG_FACTORY_RESET
},
2692 { "can-factory-reset", no_argument
, NULL
, ARG_CAN_FACTORY_RESET
},
2693 { "root", required_argument
, NULL
, ARG_ROOT
},
2694 { "seed", required_argument
, NULL
, ARG_SEED
},
2695 { "pretty", required_argument
, NULL
, ARG_PRETTY
},
2696 { "definitions", required_argument
, NULL
, ARG_DEFINITIONS
},
2697 { "size", required_argument
, NULL
, ARG_SIZE
},
2701 int c
, r
, dry_run
= -1;
2706 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
2717 r
= parse_boolean(optarg
);
2719 return log_error_errno(r
, "Failed to parse --dry-run= parameter: %s", optarg
);
2725 if (isempty(optarg
) || streq(optarg
, "refuse"))
2726 arg_empty
= EMPTY_REFUSE
;
2727 else if (streq(optarg
, "allow"))
2728 arg_empty
= EMPTY_ALLOW
;
2729 else if (streq(optarg
, "require"))
2730 arg_empty
= EMPTY_REQUIRE
;
2731 else if (streq(optarg
, "force"))
2732 arg_empty
= EMPTY_FORCE
;
2733 else if (streq(optarg
, "create")) {
2734 arg_empty
= EMPTY_CREATE
;
2737 dry_run
= false; /* Imply --dry-run=no if we create the loopback file
2738 * anew. After all we cannot really break anyone's
2739 * partition tables that way. */
2741 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2742 "Failed to parse --empty= parameter: %s", optarg
);
2746 r
= parse_boolean(optarg
);
2748 return log_error_errno(r
, "Failed to parse --discard= parameter: %s", optarg
);
2753 case ARG_FACTORY_RESET
:
2754 r
= parse_boolean(optarg
);
2756 return log_error_errno(r
, "Failed to parse --factory-reset= parameter: %s", optarg
);
2758 arg_factory_reset
= r
;
2761 case ARG_CAN_FACTORY_RESET
:
2762 arg_can_factory_reset
= true;
2766 r
= parse_path_argument_and_warn(optarg
, false, &arg_root
);
2772 if (isempty(optarg
)) {
2773 arg_seed
= SD_ID128_NULL
;
2774 arg_randomize
= false;
2775 } else if (streq(optarg
, "random"))
2776 arg_randomize
= true;
2778 r
= sd_id128_from_string(optarg
, &arg_seed
);
2780 return log_error_errno(r
, "Failed to parse seed: %s", optarg
);
2782 arg_randomize
= false;
2788 r
= parse_boolean(optarg
);
2790 return log_error_errno(r
, "Failed to parse --pretty= parameter: %s", optarg
);
2795 case ARG_DEFINITIONS
:
2796 r
= parse_path_argument_and_warn(optarg
, false, &arg_definitions
);
2802 uint64_t parsed
, rounded
;
2804 r
= parse_size(optarg
, 1024, &parsed
);
2806 return log_error_errno(r
, "Failed to parse --size= parameter: %s", optarg
);
2808 rounded
= round_up_size(parsed
, 4096);
2810 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too small, refusing.");
2811 if (rounded
== UINT64_MAX
)
2812 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too large, refusing.");
2814 if (rounded
!= parsed
)
2815 log_warning("Specified size is not a multiple of 4096, rounding up automatically. (%" PRIu64
" → %" PRIu64
")",
2826 assert_not_reached("Unhandled option");
2829 if (argc
- optind
> 1)
2830 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2831 "Expected at most one argument, the path to the block device.");
2833 if (arg_factory_reset
> 0 && IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
))
2834 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2835 "Combination of --factory-reset=yes and --empty=force/--empty=require/--empty=create is invalid.");
2837 if (arg_can_factory_reset
)
2838 arg_dry_run
= true; /* When --can-factory-reset is specified we don't make changes, hence
2839 * non-dry-run mode makes no sense. Thus, imply dry run mode so that we
2840 * open things strictly read-only. */
2841 else if (dry_run
>= 0)
2842 arg_dry_run
= dry_run
;
2844 if (arg_empty
== EMPTY_CREATE
&& arg_size
== UINT64_MAX
)
2845 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2846 "If --empty=create is specified, --size= must be specified, too.");
2848 arg_node
= argc
> optind
? argv
[optind
] : NULL
;
2850 if (IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
) && !arg_node
)
2851 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2852 "A path to a device node or loopback file must be specified when --empty=force, --empty=require or --empty=create are used.");
2857 static int parse_proc_cmdline_factory_reset(void) {
2861 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
2864 if (!in_initrd()) /* Never honour kernel command line factory reset request outside of the initrd */
2867 r
= proc_cmdline_get_bool("systemd.factory_reset", &b
);
2869 return log_error_errno(r
, "Failed to parse systemd.factory_reset kernel command line argument: %m");
2871 arg_factory_reset
= b
;
2874 log_notice("Honouring factory reset requested via kernel command line.");
2880 static int parse_efi_variable_factory_reset(void) {
2881 _cleanup_free_
char *value
= NULL
;
2884 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
2887 if (!in_initrd()) /* Never honour EFI variable factory reset request outside of the initrd */
2890 r
= efi_get_variable_string(EFI_VENDOR_SYSTEMD
, "FactoryReset", &value
);
2891 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
2894 return log_error_errno(r
, "Failed to read EFI variable FactoryReset: %m");
2896 r
= parse_boolean(value
);
2898 return log_error_errno(r
, "Failed to parse EFI variable FactoryReset: %m");
2900 arg_factory_reset
= r
;
2902 log_notice("Honouring factory reset requested via EFI variable FactoryReset: %m");
2907 static int remove_efi_variable_factory_reset(void) {
2910 r
= efi_set_variable(EFI_VENDOR_SYSTEMD
, "FactoryReset", NULL
, 0);
2911 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
2914 return log_error_errno(r
, "Failed to remove EFI variable FactoryReset: %m");
2916 log_info("Successfully unset EFI variable FactoryReset.");
2920 static int acquire_root_devno(const char *p
, int mode
, char **ret
, int *ret_fd
) {
2921 _cleanup_close_
int fd
= -1;
2923 dev_t devno
, fd_devno
= (mode_t
) -1;
2934 if (fstat(fd
, &st
) < 0)
2937 if (S_ISREG(st
.st_mode
)) {
2945 *ret_fd
= TAKE_FD(fd
);
2950 if (S_ISBLK(st
.st_mode
))
2951 fd_devno
= devno
= st
.st_rdev
;
2952 else if (S_ISDIR(st
.st_mode
)) {
2955 if (major(devno
) == 0) {
2956 r
= btrfs_get_block_device_fd(fd
, &devno
);
2957 if (r
== -ENOTTY
) /* not btrfs */
2965 /* From dm-crypt to backing partition */
2966 r
= block_get_originating(devno
, &devno
);
2968 log_debug_errno(r
, "Failed to find underlying block device for '%s', ignoring: %m", p
);
2970 /* From partition to whole disk containing it */
2971 r
= block_get_whole_disk(devno
, &devno
);
2973 log_debug_errno(r
, "Failed to find whole disk block device for '%s', ignoring: %m", p
);
2975 r
= device_path_make_canonical(S_IFBLK
, devno
, ret
);
2977 return log_debug_errno(r
, "Failed to determine canonical path for '%s': %m", p
);
2979 /* Only if we still lock at the same block device we can reuse the fd. Otherwise return an
2980 * invalidated fd. */
2981 *ret_fd
= fd_devno
!= (mode_t
) -1 && fd_devno
== devno
? TAKE_FD(fd
) : -1;
2985 static int find_root(char **ret
, int *ret_fd
) {
2993 if (arg_empty
== EMPTY_CREATE
) {
2994 _cleanup_close_
int fd
= -1;
2995 _cleanup_free_
char *s
= NULL
;
2997 s
= strdup(arg_node
);
3001 fd
= open(arg_node
, O_RDONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOFOLLOW
, 0777);
3003 return log_error_errno(errno
, "Failed to create '%s': %m", arg_node
);
3006 *ret_fd
= TAKE_FD(fd
);
3010 r
= acquire_root_devno(arg_node
, O_RDONLY
|O_CLOEXEC
, ret
, ret_fd
);
3012 return log_error_errno(r
, "Failed to determine backing device of %s: %m", arg_node
);
3017 assert(IN_SET(arg_empty
, EMPTY_REFUSE
, EMPTY_ALLOW
));
3019 /* Let's search for the root device. We look for two cases here: first in /, and then in /usr. The
3020 * latter we check for cases where / is a tmpfs and only /usr is an actual persistent block device
3021 * (think: volatile setups) */
3023 FOREACH_STRING(t
, "/", "/usr") {
3024 _cleanup_free_
char *j
= NULL
;
3028 j
= path_join("/sysroot", t
);
3036 r
= acquire_root_devno(p
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, ret
, ret_fd
);
3039 return log_error_errno(r
, "Failed to determine backing device of %s: %m", p
);
3044 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
), "Failed to discover root block device.");
3047 static int resize_backing_fd(const char *node
, int *fd
) {
3048 char buf1
[FORMAT_BYTES_MAX
], buf2
[FORMAT_BYTES_MAX
];
3049 _cleanup_close_
int writable_fd
= -1;
3056 if (arg_size
== UINT64_MAX
) /* Nothing to do */
3060 /* Open the file if we haven't opened it yet. Note that we open it read-only here, just to
3061 * keep a reference to the file we can pass around. */
3062 *fd
= open(node
, O_RDONLY
|O_CLOEXEC
);
3064 return log_error_errno(errno
, "Failed to open '%s' in order to adjust size: %m", node
);
3067 if (fstat(*fd
, &st
) < 0)
3068 return log_error_errno(errno
, "Failed to stat '%s': %m", node
);
3070 r
= stat_verify_regular(&st
);
3072 return log_error_errno(r
, "Specified path '%s' is not a regular file, cannot resize: %m", node
);
3074 assert_se(format_bytes(buf1
, sizeof(buf1
), st
.st_size
));
3075 assert_se(format_bytes(buf2
, sizeof(buf2
), arg_size
));
3077 if ((uint64_t) st
.st_size
>= arg_size
) {
3078 log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)", node
, buf1
, buf2
);
3082 /* The file descriptor is read-only. In order to grow the file we need to have a writable fd. We
3083 * reopen the file for that temporarily. We keep the writable fd only open for this operation though,
3084 * as fdisk can't accept it anyway. */
3086 writable_fd
= fd_reopen(*fd
, O_WRONLY
|O_CLOEXEC
);
3087 if (writable_fd
< 0)
3088 return log_error_errno(writable_fd
, "Failed to reopen backing file '%s' writable: %m", node
);
3091 if (fallocate(writable_fd
, 0, 0, arg_size
) < 0) {
3092 if (!ERRNO_IS_NOT_SUPPORTED(errno
))
3093 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by allocation: %m",
3096 /* Fallback to truncation, if fallocate() is not supported. */
3097 log_debug("Backing file system does not support fallocate(), falling back to ftruncate().");
3099 if (st
.st_size
== 0) /* Likely regular file just created by us */
3100 log_info("Allocated %s for '%s'.", buf2
, node
);
3102 log_info("File '%s' grown from %s to %s by allocation.", node
, buf1
, buf2
);
3108 if (ftruncate(writable_fd
, arg_size
) < 0)
3109 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by truncation: %m",
3112 if (st
.st_size
== 0) /* Likely regular file just created by us */
3113 log_info("Sized '%s' to %s.", node
, buf2
);
3115 log_info("File '%s' grown from %s to %s by truncation.", node
, buf1
, buf2
);
3120 static int run(int argc
, char *argv
[]) {
3121 _cleanup_(context_freep
) Context
* context
= NULL
;
3122 _cleanup_free_
char *node
= NULL
;
3123 _cleanup_close_
int backing_fd
= -1;
3127 log_show_color(true);
3128 log_parse_environment();
3132 /* Default to operation on /sysroot when invoked in the initrd! */
3133 arg_root
= strdup("/sysroot");
3138 r
= parse_argv(argc
, argv
);
3142 r
= parse_proc_cmdline_factory_reset();
3146 r
= parse_efi_variable_factory_reset();
3150 context
= context_new(arg_seed
);
3154 r
= context_read_definitions(context
, arg_definitions
, arg_root
);
3158 if (context
->n_partitions
<= 0 && arg_empty
== EMPTY_REFUSE
) {
3159 log_info("Didn't find any partition definition files, nothing to do.");
3163 r
= find_root(&node
, &backing_fd
);
3167 if (arg_size
!= UINT64_MAX
) {
3168 r
= resize_backing_fd(node
, &backing_fd
);
3173 r
= context_load_partition_table(context
, node
, &backing_fd
);
3174 if (r
== -EHWPOISON
)
3175 return 77; /* Special return value which means "Not GPT, so not doing anything". This isn't
3176 * really an error when called at boot. */
3179 from_scratch
= r
> 0; /* Starting from scratch */
3181 if (arg_can_factory_reset
) {
3182 r
= context_can_factory_reset(context
);
3186 return EXIT_FAILURE
;
3191 r
= context_factory_reset(context
, from_scratch
);
3195 /* We actually did a factory reset! */
3196 r
= remove_efi_variable_factory_reset();
3200 /* Reload the reduced partition table */
3201 context_unload_partition_table(context
);
3202 r
= context_load_partition_table(context
, node
, &backing_fd
);
3208 (void) context_dump_partitions(context
, node
);
3212 r
= context_read_seed(context
, arg_root
);
3216 /* First try to fit new partitions in, dropping by priority until it fits */
3218 if (context_allocate_partitions(context
))
3219 break; /* Success! */
3221 if (!context_drop_one_priority(context
))
3222 return log_error_errno(SYNTHETIC_ERRNO(ENOSPC
),
3223 "Can't fit requested partitions into free space, refusing.");
3226 /* Now assign free space according to the weight logic */
3227 r
= context_grow_partitions(context
);
3231 /* Now calculate where each partition gets placed */
3232 context_place_partitions(context
);
3234 /* Make sure each partition has a unique UUID and unique label */
3235 r
= context_acquire_partition_uuids_and_labels(context
);
3239 r
= context_write_partition_table(context
, node
, from_scratch
);
3246 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);