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 "stat-util.h"
45 #include "stdio-util.h"
46 #include "string-util.h"
48 #include "terminal-util.h"
51 /* Note: When growing and placing new partitions we always align to 4K sector size. It's how newer hard disks
52 * are designed, and if everything is aligned to that performance is best. And for older hard disks with 512B
53 * sector size devices were generally assumed to have an even number of sectors, hence at the worst we'll
54 * waste 3K per partition, which is probably fine. */
57 EMPTY_REFUSE
, /* refuse empty disks, never create a partition table */
58 EMPTY_ALLOW
, /* allow empty disks, create partition table if necessary */
59 EMPTY_REQUIRE
, /* require an empty disk, create a partition table */
60 EMPTY_FORCE
, /* make disk empty, erase everything, create a partition table always */
61 EMPTY_CREATE
, /* create disk as loopback file, create a partition table always */
62 } arg_empty
= EMPTY_REFUSE
;
64 static bool arg_dry_run
= true;
65 static const char *arg_node
= NULL
;
66 static char *arg_root
= NULL
;
67 static char *arg_definitions
= NULL
;
68 static bool arg_discard
= true;
69 static bool arg_can_factory_reset
= false;
70 static int arg_factory_reset
= -1;
71 static sd_id128_t arg_seed
= SD_ID128_NULL
;
72 static bool arg_randomize
= false;
73 static int arg_pretty
= -1;
74 static uint64_t arg_size
= UINT64_MAX
;
76 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
77 STATIC_DESTRUCTOR_REGISTER(arg_definitions
, freep
);
79 typedef struct Partition Partition
;
80 typedef struct FreeArea FreeArea
;
81 typedef struct Context Context
;
84 char *definition_path
;
87 sd_id128_t current_uuid
, new_uuid
;
88 char *current_label
, *new_label
;
94 uint32_t weight
, padding_weight
;
96 uint64_t current_size
, new_size
;
97 uint64_t size_min
, size_max
;
99 uint64_t current_padding
, new_padding
;
100 uint64_t padding_min
, padding_max
;
105 struct fdisk_partition
*current_partition
;
106 struct fdisk_partition
*new_partition
;
107 FreeArea
*padding_area
;
108 FreeArea
*allocated_to_area
;
110 LIST_FIELDS(Partition
, partitions
);
113 #define PARTITION_IS_FOREIGN(p) (!(p)->definition_path)
114 #define PARTITION_EXISTS(p) (!!(p)->current_partition)
123 LIST_HEAD(Partition
, partitions
);
126 FreeArea
**free_areas
;
127 size_t n_free_areas
, n_allocated_free_areas
;
129 uint64_t start
, end
, total
;
131 struct fdisk_context
*fdisk_context
;
136 static uint64_t round_down_size(uint64_t v
, uint64_t p
) {
140 static uint64_t round_up_size(uint64_t v
, uint64_t p
) {
142 v
= DIV_ROUND_UP(v
, p
);
144 if (v
> UINT64_MAX
/ p
)
145 return UINT64_MAX
; /* overflow */
150 static Partition
*partition_new(void) {
153 p
= new(Partition
, 1);
160 .current_size
= UINT64_MAX
,
161 .new_size
= UINT64_MAX
,
162 .size_min
= UINT64_MAX
,
163 .size_max
= UINT64_MAX
,
164 .current_padding
= UINT64_MAX
,
165 .new_padding
= UINT64_MAX
,
166 .padding_min
= UINT64_MAX
,
167 .padding_max
= UINT64_MAX
,
168 .partno
= UINT64_MAX
,
169 .offset
= UINT64_MAX
,
175 static Partition
* partition_free(Partition
*p
) {
179 free(p
->current_label
);
181 free(p
->definition_path
);
183 if (p
->current_partition
)
184 fdisk_unref_partition(p
->current_partition
);
185 if (p
->new_partition
)
186 fdisk_unref_partition(p
->new_partition
);
191 static Partition
* partition_unlink_and_free(Context
*context
, Partition
*p
) {
195 LIST_REMOVE(partitions
, context
->partitions
, p
);
197 assert(context
->n_partitions
> 0);
198 context
->n_partitions
--;
200 return partition_free(p
);
203 DEFINE_TRIVIAL_CLEANUP_FUNC(Partition
*, partition_free
);
205 static Context
*context_new(sd_id128_t seed
) {
208 context
= new(Context
, 1);
212 *context
= (Context
) {
222 static void context_free_free_areas(Context
*context
) {
225 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
226 free(context
->free_areas
[i
]);
228 context
->free_areas
= mfree(context
->free_areas
);
229 context
->n_free_areas
= 0;
230 context
->n_allocated_free_areas
= 0;
233 static Context
*context_free(Context
*context
) {
237 while (context
->partitions
)
238 partition_unlink_and_free(context
, context
->partitions
);
239 assert(context
->n_partitions
== 0);
241 context_free_free_areas(context
);
243 if (context
->fdisk_context
)
244 fdisk_unref_context(context
->fdisk_context
);
246 return mfree(context
);
249 DEFINE_TRIVIAL_CLEANUP_FUNC(Context
*, context_free
);
251 static int context_add_free_area(
259 assert(!after
|| !after
->padding_area
);
261 if (!GREEDY_REALLOC(context
->free_areas
, context
->n_allocated_free_areas
, context
->n_free_areas
+ 1))
264 a
= new(FreeArea
, 1);
273 context
->free_areas
[context
->n_free_areas
++] = a
;
276 after
->padding_area
= a
;
281 static bool context_drop_one_priority(Context
*context
) {
282 int32_t priority
= 0;
286 LIST_FOREACH(partitions
, p
, context
->partitions
) {
289 if (p
->priority
< priority
)
291 if (p
->priority
== priority
) {
292 exists
= exists
|| PARTITION_EXISTS(p
);
296 priority
= p
->priority
;
297 exists
= PARTITION_EXISTS(p
);
300 /* Refuse to drop partitions with 0 or negative priorities or partitions of priorities that have at
301 * least one existing priority */
302 if (priority
<= 0 || exists
)
305 LIST_FOREACH(partitions
, p
, context
->partitions
) {
306 if (p
->priority
< priority
)
313 log_info("Can't fit partition %s of priority %" PRIi32
", dropping.", p
->definition_path
, p
->priority
);
319 static uint64_t partition_min_size(const Partition
*p
) {
322 /* Calculate the disk space we really need at minimum for this partition. If the partition already
323 * exists the current size is what we really need. If it doesn't exist yet refuse to allocate less
326 if (PARTITION_IS_FOREIGN(p
)) {
327 /* Don't allow changing size of partitions not managed by us */
328 assert(p
->current_size
!= UINT64_MAX
);
329 return p
->current_size
;
332 sz
= p
->current_size
!= UINT64_MAX
? p
->current_size
: 4096;
333 if (p
->size_min
!= UINT64_MAX
)
334 return MAX(p
->size_min
, sz
);
339 static uint64_t partition_max_size(const Partition
*p
) {
340 /* Calculate how large the partition may become at max. This is generally the configured maximum
341 * size, except when it already exists and is larger than that. In that case it's the existing size,
342 * since we never want to shrink partitions. */
344 if (PARTITION_IS_FOREIGN(p
)) {
345 /* Don't allow changing size of partitions not managed by us */
346 assert(p
->current_size
!= UINT64_MAX
);
347 return p
->current_size
;
350 if (p
->current_size
!= UINT64_MAX
)
351 return MAX(p
->current_size
, p
->size_max
);
356 static uint64_t partition_min_size_with_padding(const Partition
*p
) {
359 /* Calculate the disk space we need for this partition plus any free space coming after it. This
360 * takes user configured padding into account as well as any additional whitespace needed to align
361 * the next partition to 4K again. */
363 sz
= partition_min_size(p
);
365 if (p
->padding_min
!= UINT64_MAX
)
366 sz
+= p
->padding_min
;
368 if (PARTITION_EXISTS(p
)) {
369 /* If the partition wasn't aligned, add extra space so that any we might add will be aligned */
370 assert(p
->offset
!= UINT64_MAX
);
371 return round_up_size(p
->offset
+ sz
, 4096) - p
->offset
;
374 /* If this is a new partition we'll place it aligned, hence we just need to round up the required size here */
375 return round_up_size(sz
, 4096);
378 static uint64_t free_area_available(const FreeArea
*a
) {
381 /* Determines how much of this free area is not allocated yet */
383 assert(a
->size
>= a
->allocated
);
384 return a
->size
- a
->allocated
;
387 static uint64_t free_area_available_for_new_partitions(const FreeArea
*a
) {
390 /* Similar to free_area_available(), but takes into account that the required size and padding of the
391 * preceding partition is honoured. */
393 avail
= free_area_available(a
);
395 uint64_t need
, space
;
397 need
= partition_min_size_with_padding(a
->after
);
399 assert(a
->after
->offset
!= UINT64_MAX
);
400 assert(a
->after
->current_size
!= UINT64_MAX
);
402 space
= round_up_size(a
->after
->offset
+ a
->after
->current_size
, 4096) - a
->after
->offset
+ avail
;
412 static int free_area_compare(FreeArea
*const *a
, FreeArea
*const*b
) {
413 return CMP(free_area_available_for_new_partitions(*a
),
414 free_area_available_for_new_partitions(*b
));
417 static uint64_t charge_size(uint64_t total
, uint64_t amount
) {
420 assert(amount
<= total
);
422 /* Subtract the specified amount from total, rounding up to multiple of 4K if there's room */
423 rounded
= round_up_size(amount
, 4096);
424 if (rounded
>= total
)
427 return total
- rounded
;
430 static uint64_t charge_weight(uint64_t total
, uint64_t amount
) {
431 assert(amount
<= total
);
432 return total
- amount
;
435 static bool context_allocate_partitions(Context
*context
) {
440 /* A simple first-fit algorithm, assuming the array of free areas is sorted by size in decreasing
443 LIST_FOREACH(partitions
, p
, context
->partitions
) {
448 /* Skip partitions we already dropped or that already exist */
449 if (p
->dropped
|| PARTITION_EXISTS(p
))
453 typesafe_qsort(context
->free_areas
, context
->n_free_areas
, free_area_compare
);
455 /* How much do we need to fit? */
456 required
= partition_min_size_with_padding(p
);
457 assert(required
% 4096 == 0);
459 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
460 a
= context
->free_areas
[i
];
462 if (free_area_available_for_new_partitions(a
) >= required
) {
469 return false; /* 😢 Oh no! We can't fit this partition into any free area! */
471 /* Assign the partition to this free area */
472 p
->allocated_to_area
= a
;
474 /* Budget the minimal partition size */
475 a
->allocated
+= required
;
481 static int context_sum_weights(Context
*context
, FreeArea
*a
, uint64_t *ret
) {
482 uint64_t weight_sum
= 0;
489 /* Determine the sum of the weights of all partitions placed in or before the specified free area */
491 LIST_FOREACH(partitions
, p
, context
->partitions
) {
492 if (p
->padding_area
!= a
&& p
->allocated_to_area
!= a
)
495 if (p
->weight
> UINT64_MAX
- weight_sum
)
497 weight_sum
+= p
->weight
;
499 if (p
->padding_weight
> UINT64_MAX
- weight_sum
)
501 weight_sum
+= p
->padding_weight
;
508 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Combined weight of partition exceeds unsigned 64bit range, refusing.");
511 static int scale_by_weight(uint64_t value
, uint64_t weight
, uint64_t weight_sum
, uint64_t *ret
) {
512 assert(weight_sum
>= weight
);
520 if (value
> UINT64_MAX
/ weight
)
521 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Scaling by weight of partition exceeds unsigned 64bit range, refusing.");
523 *ret
= value
* weight
/ weight_sum
;
527 typedef enum GrowPartitionPhase
{
528 /* The first phase: we charge partitions which need more (according to constraints) than their weight-based share. */
531 /* The second phase: we charge partitions which need less (according to constraints) than their weight-based share. */
534 /* The third phase: we distribute what remains among the remaining partitions, according to the weights */
536 } GrowPartitionPhase
;
538 static int context_grow_partitions_phase(
541 GrowPartitionPhase phase
,
543 uint64_t *weight_sum
) {
551 /* Now let's look at the intended weights and adjust them taking the minimum space assignments into
552 * account. i.e. if a partition has a small weight but a high minimum space value set it should not
553 * get any additional room from the left-overs. Similar, if two partitions have the same weight they
554 * should get the same space if possible, even if one has a smaller minimum size than the other. */
555 LIST_FOREACH(partitions
, p
, context
->partitions
) {
557 /* Look only at partitions associated with this free area, i.e. immediately
558 * preceding it, or allocated into it */
559 if (p
->allocated_to_area
!= a
&& p
->padding_area
!= a
)
562 if (p
->new_size
== UINT64_MAX
) {
563 bool charge
= false, try_again
= false;
564 uint64_t share
, rsz
, xsz
;
566 /* Calculate how much this space this partition needs if everyone would get
567 * the weight based share */
568 r
= scale_by_weight(*span
, p
->weight
, *weight_sum
, &share
);
572 rsz
= partition_min_size(p
);
573 xsz
= partition_max_size(p
);
575 if (phase
== PHASE_OVERCHARGE
&& rsz
> share
) {
576 /* This partition needs more than its calculated share. Let's assign
577 * it that, and take this partition out of all calculations and start
581 charge
= try_again
= true;
583 } else if (phase
== PHASE_UNDERCHARGE
&& xsz
!= UINT64_MAX
&& xsz
< share
) {
584 /* This partition accepts less than its calculated
585 * share. Let's assign it that, and take this partition out
586 * of all calculations and start again. */
589 charge
= try_again
= true;
591 } else if (phase
== PHASE_DISTRIBUTE
) {
592 /* This partition can accept its calculated share. Let's
593 * assign it. There's no need to restart things here since
594 * assigning this shouldn't impact the shares of the other
597 if (PARTITION_IS_FOREIGN(p
))
598 /* Never change of foreign partitions (i.e. those we don't manage) */
599 p
->new_size
= p
->current_size
;
601 p
->new_size
= MAX(round_down_size(share
, 4096), rsz
);
607 *span
= charge_size(*span
, p
->new_size
);
608 *weight_sum
= charge_weight(*weight_sum
, p
->weight
);
612 return 0; /* try again */
615 if (p
->new_padding
== UINT64_MAX
) {
616 bool charge
= false, try_again
= false;
619 r
= scale_by_weight(*span
, p
->padding_weight
, *weight_sum
, &share
);
623 if (phase
== PHASE_OVERCHARGE
&& p
->padding_min
!= UINT64_MAX
&& p
->padding_min
> share
) {
624 p
->new_padding
= p
->padding_min
;
625 charge
= try_again
= true;
626 } else if (phase
== PHASE_UNDERCHARGE
&& p
->padding_max
!= UINT64_MAX
&& p
->padding_max
< share
) {
627 p
->new_padding
= p
->padding_max
;
628 charge
= try_again
= true;
629 } else if (phase
== PHASE_DISTRIBUTE
) {
631 p
->new_padding
= round_down_size(share
, 4096);
632 if (p
->padding_min
!= UINT64_MAX
&& p
->new_padding
< p
->padding_min
)
633 p
->new_padding
= p
->padding_min
;
639 *span
= charge_size(*span
, p
->new_padding
);
640 *weight_sum
= charge_weight(*weight_sum
, p
->padding_weight
);
644 return 0; /* try again */
651 static int context_grow_partitions_on_free_area(Context
*context
, FreeArea
*a
) {
652 uint64_t weight_sum
= 0, span
;
658 r
= context_sum_weights(context
, a
, &weight_sum
);
662 /* Let's calculate the total area covered by this free area and the partition before it */
665 assert(a
->after
->offset
!= UINT64_MAX
);
666 assert(a
->after
->current_size
!= UINT64_MAX
);
668 span
+= round_up_size(a
->after
->offset
+ a
->after
->current_size
, 4096) - a
->after
->offset
;
671 GrowPartitionPhase phase
= PHASE_OVERCHARGE
;
673 r
= context_grow_partitions_phase(context
, a
, phase
, &span
, &weight_sum
);
676 if (r
== 0) /* not done yet, re-run this phase */
679 if (phase
== PHASE_OVERCHARGE
)
680 phase
= PHASE_UNDERCHARGE
;
681 else if (phase
== PHASE_UNDERCHARGE
)
682 phase
= PHASE_DISTRIBUTE
;
683 else if (phase
== PHASE_DISTRIBUTE
)
687 /* We still have space left over? Donate to preceding partition if we have one */
688 if (span
> 0 && a
->after
&& !PARTITION_IS_FOREIGN(a
->after
)) {
691 assert(a
->after
->new_size
!= UINT64_MAX
);
692 m
= a
->after
->new_size
+ span
;
694 xsz
= partition_max_size(a
->after
);
695 if (xsz
!= UINT64_MAX
&& m
> xsz
)
698 span
= charge_size(span
, m
- a
->after
->new_size
);
699 a
->after
->new_size
= m
;
702 /* What? Even still some space left (maybe because there was no preceding partition, or it had a
703 * size limit), then let's donate it to whoever wants it. */
707 LIST_FOREACH(partitions
, p
, context
->partitions
) {
710 if (p
->allocated_to_area
!= a
)
713 if (PARTITION_IS_FOREIGN(p
))
716 assert(p
->new_size
!= UINT64_MAX
);
717 m
= p
->new_size
+ span
;
719 xsz
= partition_max_size(p
);
720 if (xsz
!= UINT64_MAX
&& m
> xsz
)
723 span
= charge_size(span
, m
- p
->new_size
);
731 /* Yuck, still no one? Then make it padding */
732 if (span
> 0 && a
->after
) {
733 assert(a
->after
->new_padding
!= UINT64_MAX
);
734 a
->after
->new_padding
+= span
;
740 static int context_grow_partitions(Context
*context
) {
746 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
747 r
= context_grow_partitions_on_free_area(context
, context
->free_areas
[i
]);
752 /* All existing partitions that have no free space after them can't change size */
753 LIST_FOREACH(partitions
, p
, context
->partitions
) {
757 if (!PARTITION_EXISTS(p
) || p
->padding_area
) {
758 /* The algorithm above must have initialized this already */
759 assert(p
->new_size
!= UINT64_MAX
);
763 assert(p
->new_size
== UINT64_MAX
);
764 p
->new_size
= p
->current_size
;
766 assert(p
->new_padding
== UINT64_MAX
);
767 p
->new_padding
= p
->current_padding
;
773 static void context_place_partitions(Context
*context
) {
779 /* Determine next partition number to assign */
780 LIST_FOREACH(partitions
, p
, context
->partitions
) {
781 if (!PARTITION_EXISTS(p
))
784 assert(p
->partno
!= UINT64_MAX
);
785 if (p
->partno
>= partno
)
786 partno
= p
->partno
+ 1;
789 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
790 FreeArea
*a
= context
->free_areas
[i
];
791 uint64_t start
, left
;
794 assert(a
->after
->offset
!= UINT64_MAX
);
795 assert(a
->after
->new_size
!= UINT64_MAX
);
796 assert(a
->after
->new_padding
!= UINT64_MAX
);
798 start
= a
->after
->offset
+ a
->after
->new_size
+ a
->after
->new_padding
;
800 start
= context
->start
;
802 start
= round_up_size(start
, 4096);
805 LIST_FOREACH(partitions
, p
, context
->partitions
) {
806 if (p
->allocated_to_area
!= a
)
810 p
->partno
= partno
++;
812 assert(left
>= p
->new_size
);
813 start
+= p
->new_size
;
816 assert(left
>= p
->new_padding
);
817 start
+= p
->new_padding
;
818 left
-= p
->new_padding
;
823 static int config_parse_type(
825 const char *filename
,
828 unsigned section_line
,
835 sd_id128_t
*type_uuid
= data
;
841 r
= gpt_partition_type_uuid_from_string(rvalue
, type_uuid
);
843 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to parse partition type: %s", rvalue
);
848 static int config_parse_label(
850 const char *filename
,
853 unsigned section_line
,
860 _cleanup_free_ char16_t
*recoded
= NULL
;
867 if (!utf8_is_valid(rvalue
)) {
868 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
869 "Partition label not valid UTF-8, ignoring: %s", rvalue
);
873 recoded
= utf8_to_utf16(rvalue
, strlen(rvalue
));
877 if (char16_strlen(recoded
) > 36) {
878 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
879 "Partition label too long for GPT table, ignoring: %s", rvalue
);
883 r
= free_and_strdup(label
, rvalue
);
890 static int config_parse_weight(
892 const char *filename
,
895 unsigned section_line
,
902 uint32_t *priority
= data
, v
;
908 r
= safe_atou32(rvalue
, &v
);
910 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
911 "Failed to parse weight value, ignoring: %s", rvalue
);
915 if (v
> 1000U*1000U) {
916 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
917 "Weight needs to be in range 0…10000000, ignoring: %" PRIu32
, v
);
925 static int config_parse_size4096(
927 const char *filename
,
930 unsigned section_line
,
937 uint64_t *sz
= data
, parsed
;
943 r
= parse_size(rvalue
, 1024, &parsed
);
945 return log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
946 "Failed to parse size value: %s", rvalue
);
949 *sz
= round_up_size(parsed
, 4096);
951 *sz
= round_down_size(parsed
, 4096);
956 log_syntax(unit
, LOG_NOTICE
, filename
, line
, r
, "Rounded %s= size %" PRIu64
" → %" PRIu64
", a multiple of 4096.", lvalue
, parsed
, *sz
);
961 static int partition_read_definition(Partition
*p
, const char *path
) {
963 ConfigTableItem table
[] = {
964 { "Partition", "Type", config_parse_type
, 0, &p
->type_uuid
},
965 { "Partition", "Label", config_parse_label
, 0, &p
->new_label
},
966 { "Partition", "Priority", config_parse_int32
, 0, &p
->priority
},
967 { "Partition", "Weight", config_parse_weight
, 0, &p
->weight
},
968 { "Partition", "PaddingWeight", config_parse_weight
, 0, &p
->padding_weight
},
969 { "Partition", "SizeMinBytes", config_parse_size4096
, 1, &p
->size_min
},
970 { "Partition", "SizeMaxBytes", config_parse_size4096
, -1, &p
->size_max
},
971 { "Partition", "PaddingMinBytes", config_parse_size4096
, 1, &p
->padding_min
},
972 { "Partition", "PaddingMaxBytes", config_parse_size4096
, -1, &p
->padding_max
},
973 { "Partition", "FactoryReset", config_parse_bool
, 0, &p
->factory_reset
},
978 r
= config_parse(NULL
, path
, NULL
, "Partition\0", config_item_table_lookup
, table
, CONFIG_PARSE_WARN
, p
);
982 if (p
->size_min
!= UINT64_MAX
&& p
->size_max
!= UINT64_MAX
&& p
->size_min
> p
->size_max
)
983 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
984 "SizeMinBytes= larger than SizeMaxBytes=, refusing.");
986 if (p
->padding_min
!= UINT64_MAX
&& p
->padding_max
!= UINT64_MAX
&& p
->padding_min
> p
->padding_max
)
987 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
988 "PaddingMinBytes= larger than PaddingMaxBytes=, refusing.");
990 if (sd_id128_is_null(p
->type_uuid
))
991 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
992 "Type= not defined, refusing.");
997 static int context_read_definitions(
999 const char *directory
,
1002 _cleanup_strv_free_
char **files
= NULL
;
1003 Partition
*last
= NULL
;
1010 r
= conf_files_list_strv(&files
, ".conf", NULL
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, (const char**) STRV_MAKE(directory
));
1012 r
= conf_files_list_strv(&files
, ".conf", root
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, (const char**) CONF_PATHS_STRV("repart.d"));
1014 return log_error_errno(r
, "Failed to enumerate *.conf files: %m");
1016 STRV_FOREACH(f
, files
) {
1017 _cleanup_(partition_freep
) Partition
*p
= NULL
;
1019 p
= partition_new();
1023 p
->definition_path
= strdup(*f
);
1024 if (!p
->definition_path
)
1027 r
= partition_read_definition(p
, *f
);
1031 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, p
);
1033 context
->n_partitions
++;
1039 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_context
*, fdisk_unref_context
);
1040 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_partition
*, fdisk_unref_partition
);
1041 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_parttype
*, fdisk_unref_parttype
);
1042 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_table
*, fdisk_unref_table
);
1044 static int determine_current_padding(
1045 struct fdisk_context
*c
,
1046 struct fdisk_table
*t
,
1047 struct fdisk_partition
*p
,
1050 size_t n_partitions
;
1051 uint64_t offset
, next
= UINT64_MAX
;
1057 if (!fdisk_partition_has_end(p
))
1058 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition has no end!");
1060 offset
= fdisk_partition_get_end(p
);
1061 assert(offset
< UINT64_MAX
/ 512);
1064 n_partitions
= fdisk_table_get_nents(t
);
1065 for (size_t i
= 0; i
< n_partitions
; i
++) {
1066 struct fdisk_partition
*q
;
1069 q
= fdisk_table_get_partition(t
, i
);
1071 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1073 if (fdisk_partition_is_used(q
) <= 0)
1076 if (!fdisk_partition_has_start(q
))
1079 start
= fdisk_partition_get_start(q
);
1080 assert(start
< UINT64_MAX
/ 512);
1083 if (start
>= offset
&& (next
== UINT64_MAX
|| next
> start
))
1087 if (next
== UINT64_MAX
) {
1088 /* No later partition? In that case check the end of the usable area */
1089 next
= fdisk_get_last_lba(c
);
1090 assert(next
< UINT64_MAX
);
1091 next
++; /* The last LBA is one sector before the end */
1093 assert(next
< UINT64_MAX
/ 512);
1097 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
1100 assert(next
>= offset
);
1101 offset
= round_up_size(offset
, 4096);
1102 next
= round_down_size(next
, 4096);
1104 if (next
>= offset
) /* Check again, rounding might have fucked things up */
1105 *ret
= next
- offset
;
1112 static int fdisk_ask_cb(struct fdisk_context
*c
, struct fdisk_ask
*ask
, void *data
) {
1113 _cleanup_free_
char *ids
= NULL
;
1116 if (fdisk_ask_get_type(ask
) != FDISK_ASKTYPE_STRING
)
1119 ids
= new(char, ID128_UUID_STRING_MAX
);
1123 r
= fdisk_ask_string_set_result(ask
, id128_to_uuid_string(*(sd_id128_t
*) data
, ids
));
1131 static int fdisk_set_disklabel_id_by_uuid(struct fdisk_context
*c
, sd_id128_t id
) {
1134 r
= fdisk_set_ask(c
, fdisk_ask_cb
, &id
);
1138 r
= fdisk_set_disklabel_id(c
);
1142 return fdisk_set_ask(c
, NULL
, NULL
);
1145 #define DISK_UUID_TOKEN "disk-uuid"
1147 static int disk_acquire_uuid(Context
*context
, sd_id128_t
*ret
) {
1149 unsigned char md
[SHA256_DIGEST_LENGTH
];
1156 /* Calculate the HMAC-SHA256 of the string "disk-uuid", keyed off the machine ID. We use the machine
1157 * ID as key (and not as cleartext!) since it's the machine ID we don't want to leak. */
1159 if (!HMAC(EVP_sha256(),
1160 &context
->seed
, sizeof(context
->seed
),
1161 (const unsigned char*) DISK_UUID_TOKEN
, strlen(DISK_UUID_TOKEN
),
1163 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "HMAC-SHA256 calculation failed.");
1165 /* Take the first half, mark it as v4 UUID */
1166 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
1167 *ret
= id128_make_v4_uuid(result
.id
);
1171 static int context_load_partition_table(
1176 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
1177 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
1178 uint64_t left_boundary
= UINT64_MAX
, first_lba
, last_lba
, nsectors
;
1179 _cleanup_free_
char *disk_uuid_string
= NULL
;
1180 bool from_scratch
= false;
1181 sd_id128_t disk_uuid
;
1182 size_t n_partitions
;
1189 c
= fdisk_new_context();
1193 /* libfdisk doesn't have an API to operate on arbitrary fds, hence reopen the fd going via the
1194 * /proc/self/fd/ magic path if we have an existing fd. Open the original file otherwise. */
1195 if (*backing_fd
< 0)
1196 r
= fdisk_assign_device(c
, node
, arg_dry_run
);
1198 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1199 xsprintf(procfs_path
, "/proc/self/fd/%i", *backing_fd
);
1201 r
= fdisk_assign_device(c
, procfs_path
, arg_dry_run
);
1204 return log_error_errno(r
, "Failed to open device '%s': %m", node
);
1206 if (*backing_fd
< 0) {
1207 /* If we have no fd referencing the device yet, make a copy of the fd now, so that we have one */
1208 *backing_fd
= fcntl(fdisk_get_devfd(c
), F_DUPFD_CLOEXEC
, 3);
1209 if (*backing_fd
< 0)
1210 return log_error_errno(errno
, "Failed to duplicate fdisk fd: %m");
1213 /* Tell udev not to interfere while we are processing the device */
1214 if (flock(fdisk_get_devfd(c
), arg_dry_run
? LOCK_SH
: LOCK_EX
) < 0)
1215 return log_error_errno(errno
, "Failed to lock block device: %m");
1217 switch (arg_empty
) {
1220 /* Refuse empty disks, insist on an existing GPT partition table */
1221 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
1222 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has no GPT disk label, not repartitioning.", node
);
1227 /* Require an empty disk, refuse any existing partition table */
1228 r
= fdisk_has_label(c
);
1230 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", node
);
1232 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s already has a disk label, refusing.", node
);
1234 from_scratch
= true;
1238 /* Allow both an empty disk and an existing partition table, but only GPT */
1239 r
= fdisk_has_label(c
);
1241 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", node
);
1243 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
1244 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has non-GPT disk label, not repartitioning.", node
);
1246 from_scratch
= true;
1252 /* Always reinitiaize the disk, don't consider what there was on the disk before */
1253 from_scratch
= true;
1258 r
= fdisk_enable_wipe(c
, true);
1260 return log_error_errno(r
, "Failed to enable wiping of disk signature: %m");
1262 r
= fdisk_create_disklabel(c
, "gpt");
1264 return log_error_errno(r
, "Failed to create GPT disk label: %m");
1266 r
= disk_acquire_uuid(context
, &disk_uuid
);
1268 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
1270 r
= fdisk_set_disklabel_id_by_uuid(c
, disk_uuid
);
1272 return log_error_errno(r
, "Failed to set GPT disk label: %m");
1274 goto add_initial_free_area
;
1277 r
= fdisk_get_disklabel_id(c
, &disk_uuid_string
);
1279 return log_error_errno(r
, "Failed to get current GPT disk label UUID: %m");
1281 r
= sd_id128_from_string(disk_uuid_string
, &disk_uuid
);
1283 return log_error_errno(r
, "Failed to parse current GPT disk label UUID: %m");
1285 if (sd_id128_is_null(disk_uuid
)) {
1286 r
= disk_acquire_uuid(context
, &disk_uuid
);
1288 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
1290 r
= fdisk_set_disklabel_id(c
);
1292 return log_error_errno(r
, "Failed to set GPT disk label: %m");
1295 r
= fdisk_get_partitions(c
, &t
);
1297 return log_error_errno(r
, "Failed to acquire partition table: %m");
1299 n_partitions
= fdisk_table_get_nents(t
);
1300 for (size_t i
= 0; i
< n_partitions
; i
++) {
1301 _cleanup_free_
char *label_copy
= NULL
;
1302 Partition
*pp
, *last
= NULL
;
1303 struct fdisk_partition
*p
;
1304 struct fdisk_parttype
*pt
;
1305 const char *pts
, *ids
, *label
;
1308 sd_id128_t ptid
, id
;
1311 p
= fdisk_table_get_partition(t
, i
);
1313 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1315 if (fdisk_partition_is_used(p
) <= 0)
1318 if (fdisk_partition_has_start(p
) <= 0 ||
1319 fdisk_partition_has_size(p
) <= 0 ||
1320 fdisk_partition_has_partno(p
) <= 0)
1321 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a position, size or number.");
1323 pt
= fdisk_partition_get_type(p
);
1325 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to acquire type of partition: %m");
1327 pts
= fdisk_parttype_get_string(pt
);
1329 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to acquire type of partition as string: %m");
1331 r
= sd_id128_from_string(pts
, &ptid
);
1333 return log_error_errno(r
, "Failed to parse partition type UUID %s: %m", pts
);
1335 ids
= fdisk_partition_get_uuid(p
);
1337 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a UUID.");
1339 r
= sd_id128_from_string(ids
, &id
);
1341 return log_error_errno(r
, "Failed to parse partition UUID %s: %m", ids
);
1343 label
= fdisk_partition_get_name(p
);
1344 if (!isempty(label
)) {
1345 label_copy
= strdup(label
);
1350 sz
= fdisk_partition_get_size(p
);
1351 assert_se(sz
<= UINT64_MAX
/512);
1354 start
= fdisk_partition_get_start(p
);
1355 assert_se(start
<= UINT64_MAX
/512);
1358 partno
= fdisk_partition_get_partno(p
);
1360 if (left_boundary
== UINT64_MAX
|| left_boundary
> start
)
1361 left_boundary
= start
;
1363 /* Assign this existing partition to the first partition of the right type that doesn't have
1364 * an existing one assigned yet. */
1365 LIST_FOREACH(partitions
, pp
, context
->partitions
) {
1368 if (!sd_id128_equal(pp
->type_uuid
, ptid
))
1371 if (!pp
->current_partition
) {
1372 pp
->current_uuid
= id
;
1373 pp
->current_size
= sz
;
1375 pp
->partno
= partno
;
1376 pp
->current_label
= TAKE_PTR(label_copy
);
1378 pp
->current_partition
= p
;
1379 fdisk_ref_partition(p
);
1381 r
= determine_current_padding(c
, t
, p
, &pp
->current_padding
);
1385 if (pp
->current_padding
> 0) {
1386 r
= context_add_free_area(context
, pp
->current_padding
, pp
);
1396 /* If we have no matching definition, create a new one. */
1398 _cleanup_(partition_freep
) Partition
*np
= NULL
;
1400 np
= partition_new();
1404 np
->current_uuid
= id
;
1405 np
->type_uuid
= ptid
;
1406 np
->current_size
= sz
;
1408 np
->partno
= partno
;
1409 np
->current_label
= TAKE_PTR(label_copy
);
1411 np
->current_partition
= p
;
1412 fdisk_ref_partition(p
);
1414 r
= determine_current_padding(c
, t
, p
, &np
->current_padding
);
1418 if (np
->current_padding
> 0) {
1419 r
= context_add_free_area(context
, np
->current_padding
, np
);
1424 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, TAKE_PTR(np
));
1425 context
->n_partitions
++;
1429 add_initial_free_area
:
1430 nsectors
= fdisk_get_nsectors(c
);
1431 assert(nsectors
<= UINT64_MAX
/512);
1434 first_lba
= fdisk_get_first_lba(c
);
1435 assert(first_lba
<= UINT64_MAX
/512);
1438 last_lba
= fdisk_get_last_lba(c
);
1439 assert(last_lba
< UINT64_MAX
);
1441 assert(last_lba
<= UINT64_MAX
/512);
1444 assert(last_lba
>= first_lba
);
1446 if (left_boundary
== UINT64_MAX
) {
1447 /* No partitions at all? Then the whole disk is up for grabs. */
1449 first_lba
= round_up_size(first_lba
, 4096);
1450 last_lba
= round_down_size(last_lba
, 4096);
1452 if (last_lba
> first_lba
) {
1453 r
= context_add_free_area(context
, last_lba
- first_lba
, NULL
);
1458 /* Add space left of first partition */
1459 assert(left_boundary
>= first_lba
);
1461 first_lba
= round_up_size(first_lba
, 4096);
1462 left_boundary
= round_down_size(left_boundary
, 4096);
1463 last_lba
= round_down_size(last_lba
, 4096);
1465 if (left_boundary
> first_lba
) {
1466 r
= context_add_free_area(context
, left_boundary
- first_lba
, NULL
);
1472 context
->start
= first_lba
;
1473 context
->end
= last_lba
;
1474 context
->total
= nsectors
;
1475 context
->fdisk_context
= TAKE_PTR(c
);
1477 return from_scratch
;
1480 static void context_unload_partition_table(Context
*context
) {
1481 Partition
*p
, *next
;
1485 LIST_FOREACH_SAFE(partitions
, p
, next
, context
->partitions
) {
1487 /* Entirely remove partitions that have no configuration */
1488 if (PARTITION_IS_FOREIGN(p
)) {
1489 partition_unlink_and_free(context
, p
);
1493 /* Otherwise drop all data we read off the block device and everything we might have
1494 * calculated based on it */
1497 p
->current_size
= UINT64_MAX
;
1498 p
->new_size
= UINT64_MAX
;
1499 p
->current_padding
= UINT64_MAX
;
1500 p
->new_padding
= UINT64_MAX
;
1501 p
->partno
= UINT64_MAX
;
1502 p
->offset
= UINT64_MAX
;
1504 if (p
->current_partition
) {
1505 fdisk_unref_partition(p
->current_partition
);
1506 p
->current_partition
= NULL
;
1509 if (p
->new_partition
) {
1510 fdisk_unref_partition(p
->new_partition
);
1511 p
->new_partition
= NULL
;
1514 p
->padding_area
= NULL
;
1515 p
->allocated_to_area
= NULL
;
1517 p
->current_uuid
= p
->new_uuid
= SD_ID128_NULL
;
1520 context
->start
= UINT64_MAX
;
1521 context
->end
= UINT64_MAX
;
1522 context
->total
= UINT64_MAX
;
1524 if (context
->fdisk_context
) {
1525 fdisk_unref_context(context
->fdisk_context
);
1526 context
->fdisk_context
= NULL
;
1529 context_free_free_areas(context
);
1532 static int format_size_change(uint64_t from
, uint64_t to
, char **ret
) {
1533 char format_buffer1
[FORMAT_BYTES_MAX
], format_buffer2
[FORMAT_BYTES_MAX
], *buf
;
1535 if (from
!= UINT64_MAX
)
1536 format_bytes(format_buffer1
, sizeof(format_buffer1
), from
);
1537 if (to
!= UINT64_MAX
)
1538 format_bytes(format_buffer2
, sizeof(format_buffer2
), to
);
1540 if (from
!= UINT64_MAX
) {
1541 if (from
== to
|| to
== UINT64_MAX
)
1542 buf
= strdup(format_buffer1
);
1544 buf
= strjoin(format_buffer1
, " ", special_glyph(SPECIAL_GLYPH_ARROW
), " ", format_buffer2
);
1545 } else if (to
!= UINT64_MAX
)
1546 buf
= strjoin(special_glyph(SPECIAL_GLYPH_ARROW
), " ", format_buffer2
);
1555 *ret
= TAKE_PTR(buf
);
1559 static const char *partition_label(const Partition
*p
) {
1563 return p
->new_label
;
1565 if (p
->current_label
)
1566 return p
->current_label
;
1568 return gpt_partition_type_uuid_to_string(p
->type_uuid
);
1571 static int context_dump_partitions(Context
*context
, const char *node
) {
1572 _cleanup_(table_unrefp
) Table
*t
= NULL
;
1573 uint64_t sum_padding
= 0, sum_size
= 0;
1577 t
= table_new("type", "label", "uuid", "file", "node", "offset", "raw size", "size", "raw padding", "padding");
1582 (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);
1584 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 4), 100);
1585 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 5), 100);
1587 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1588 _cleanup_free_
char *size_change
= NULL
, *padding_change
= NULL
, *partname
= NULL
;
1589 char uuid_buffer
[ID128_UUID_STRING_MAX
];
1595 label
= partition_label(p
);
1596 partname
= p
->partno
!= UINT64_MAX
? fdisk_partname(node
, p
->partno
+1) : NULL
;
1598 r
= format_size_change(p
->current_size
, p
->new_size
, &size_change
);
1602 r
= format_size_change(p
->current_padding
, p
->new_padding
, &padding_change
);
1606 if (p
->new_size
!= UINT64_MAX
)
1607 sum_size
+= p
->new_size
;
1608 if (p
->new_padding
!= UINT64_MAX
)
1609 sum_padding
+= p
->new_padding
;
1613 TABLE_STRING
, gpt_partition_type_uuid_to_string_harder(p
->type_uuid
, uuid_buffer
),
1614 TABLE_STRING
, label
?: "-", TABLE_SET_COLOR
, label
? NULL
: ansi_grey(),
1615 TABLE_UUID
, sd_id128_is_null(p
->new_uuid
) ? p
->current_uuid
: p
->new_uuid
,
1616 TABLE_STRING
, p
->definition_path
? basename(p
->definition_path
) : "-", TABLE_SET_COLOR
, p
->definition_path
? NULL
: ansi_grey(),
1617 TABLE_STRING
, partname
?: "no", TABLE_SET_COLOR
, partname
? NULL
: ansi_highlight(),
1618 TABLE_UINT64
, p
->offset
,
1619 TABLE_UINT64
, p
->new_size
,
1620 TABLE_STRING
, size_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_size
> 0 ? ansi_underline() : NULL
,
1621 TABLE_UINT64
, p
->new_padding
,
1622 TABLE_STRING
, padding_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_padding
> 0 ? ansi_underline() : NULL
);
1624 return log_error_errno(r
, "Failed to add row to table: %m");
1627 if (sum_padding
> 0 || sum_size
> 0) {
1628 char s
[FORMAT_BYTES_MAX
];
1631 a
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", format_bytes(s
, sizeof(s
), sum_size
));
1632 b
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", format_bytes(s
, sizeof(s
), sum_padding
));
1647 return log_error_errno(r
, "Failed to add row to table: %m");
1650 r
= table_print(t
, stdout
);
1652 return log_error_errno(r
, "Failed to dump table: %m");
1657 static void context_bar_char_process_partition(
1662 size_t *ret_start
) {
1664 uint64_t from
, to
, total
;
1675 assert(p
->offset
!= UINT64_MAX
);
1676 assert(p
->new_size
!= UINT64_MAX
);
1679 to
= from
+ p
->new_size
;
1681 assert(context
->end
>= context
->start
);
1682 total
= context
->end
- context
->start
;
1684 assert(from
>= context
->start
);
1685 assert(from
<= context
->end
);
1686 x
= (from
- context
->start
) * n
/ total
;
1688 assert(to
>= context
->start
);
1689 assert(to
<= context
->end
);
1690 y
= (to
- context
->start
) * n
/ total
;
1695 for (size_t i
= x
; i
< y
; i
++)
1701 static int partition_hint(const Partition
*p
, const char *node
, char **ret
) {
1702 _cleanup_free_
char *buf
= NULL
;
1703 char ids
[ID128_UUID_STRING_MAX
];
1707 /* Tries really hard to find a suitable description for this partition */
1709 if (p
->definition_path
) {
1710 buf
= strdup(basename(p
->definition_path
));
1714 label
= partition_label(p
);
1715 if (!isempty(label
)) {
1716 buf
= strdup(label
);
1720 if (p
->partno
!= UINT64_MAX
) {
1721 buf
= fdisk_partname(node
, p
->partno
+1);
1725 if (!sd_id128_is_null(p
->new_uuid
))
1727 else if (!sd_id128_is_null(p
->current_uuid
))
1728 id
= p
->current_uuid
;
1732 buf
= strdup(id128_to_uuid_string(id
, ids
));
1738 *ret
= TAKE_PTR(buf
);
1742 static int context_dump_partition_bar(Context
*context
, const char *node
) {
1743 _cleanup_free_ Partition
**bar
= NULL
;
1744 _cleanup_free_
size_t *start_array
= NULL
;
1745 Partition
*p
, *last
= NULL
;
1749 assert_se((c
= columns()) >= 2);
1750 c
-= 2; /* We do not use the leftmost and rightmost character cell */
1752 bar
= new0(Partition
*, c
);
1756 start_array
= new(size_t, context
->n_partitions
);
1760 LIST_FOREACH(partitions
, p
, context
->partitions
)
1761 context_bar_char_process_partition(context
, bar
, c
, p
, start_array
+ j
++);
1765 for (size_t i
= 0; i
< c
; i
++) {
1770 fputs(z
? ansi_green() : ansi_yellow(), stdout
);
1771 fputs(special_glyph(SPECIAL_GLYPH_DARK_SHADE
), stdout
);
1773 fputs(ansi_normal(), stdout
);
1774 fputs(special_glyph(SPECIAL_GLYPH_LIGHT_SHADE
), stdout
);
1780 fputs(ansi_normal(), stdout
);
1783 for (size_t i
= 0; i
< context
->n_partitions
; i
++) {
1784 _cleanup_free_
char **line
= NULL
;
1786 line
= new0(char*, c
);
1791 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1792 _cleanup_free_
char *d
= NULL
;
1795 if (i
< context
->n_partitions
- j
) {
1797 if (line
[start_array
[j
-1]]) {
1800 /* Upgrade final corner to the right with a branch to the right */
1801 e
= startswith(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
1803 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), e
);
1810 d
= strdup(special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
));
1815 } else if (i
== context
->n_partitions
- j
) {
1816 _cleanup_free_
char *hint
= NULL
;
1818 (void) partition_hint(p
, node
, &hint
);
1820 if (streq_ptr(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
)))
1821 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), " ", strna(hint
));
1823 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), " ", strna(hint
));
1830 free_and_replace(line
[start_array
[j
-1]], d
);
1838 fputs(line
[j
], stdout
);
1839 j
+= utf8_console_width(line
[j
]);
1848 for (j
= 0; j
< c
; j
++)
1855 static bool context_changed(const Context
*context
) {
1858 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1862 if (p
->allocated_to_area
)
1865 if (p
->new_size
!= p
->current_size
)
1872 static int context_wipe_partition(Context
*context
, Partition
*p
) {
1873 _cleanup_(blkid_free_probep
) blkid_probe probe
= NULL
;
1878 assert(!PARTITION_EXISTS(p
)); /* Safety check: never wipe existing partitions */
1880 probe
= blkid_new_probe();
1884 assert(p
->offset
!= UINT64_MAX
);
1885 assert(p
->new_size
!= UINT64_MAX
);
1888 r
= blkid_probe_set_device(probe
, fdisk_get_devfd(context
->fdisk_context
), p
->offset
, p
->new_size
);
1890 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to allocate device probe for partition %" PRIu64
".", p
->partno
);
1893 if (blkid_probe_enable_superblocks(probe
, true) < 0 ||
1894 blkid_probe_set_superblocks_flags(probe
, BLKID_SUBLKS_MAGIC
|BLKID_SUBLKS_BADCSUM
) < 0 ||
1895 blkid_probe_enable_partitions(probe
, true) < 0 ||
1896 blkid_probe_set_partitions_flags(probe
, BLKID_PARTS_MAGIC
) < 0)
1897 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to enable superblock and partition probing for partition %" PRIu64
".", p
->partno
);
1901 r
= blkid_do_probe(probe
);
1903 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to probe for file systems.");
1908 if (blkid_do_wipe(probe
, false) < 0)
1909 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to wipe file system signature.");
1912 log_info("Successfully wiped file system signatures from partition %" PRIu64
".", p
->partno
);
1916 static int context_discard_range(Context
*context
, uint64_t offset
, uint64_t size
) {
1921 assert(offset
!= UINT64_MAX
);
1922 assert(size
!= UINT64_MAX
);
1927 assert_se((fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
1929 if (fstat(fd
, &st
) < 0)
1932 if (S_ISREG(st
.st_mode
)) {
1933 if (fallocate(fd
, FALLOC_FL_PUNCH_HOLE
|FALLOC_FL_KEEP_SIZE
, offset
, size
) < 0) {
1934 if (ERRNO_IS_NOT_SUPPORTED(errno
))
1943 if (S_ISBLK(st
.st_mode
)) {
1944 uint64_t range
[2], end
;
1946 range
[0] = round_up_size(offset
, 512);
1948 end
= offset
+ size
;
1949 if (end
<= range
[0])
1952 range
[1] = round_down_size(end
- range
[0], 512);
1956 if (ioctl(fd
, BLKDISCARD
, range
) < 0) {
1957 if (ERRNO_IS_NOT_SUPPORTED(errno
))
1969 static int context_discard_partition(Context
*context
, Partition
*p
) {
1975 assert(p
->offset
!= UINT64_MAX
);
1976 assert(p
->new_size
!= UINT64_MAX
);
1977 assert(!PARTITION_EXISTS(p
)); /* Safety check: never discard existing partitions */
1982 r
= context_discard_range(context
, p
->offset
, p
->new_size
);
1983 if (r
== -EOPNOTSUPP
) {
1984 log_info("Storage does not support discarding, not discarding data in new partition %" PRIu64
".", p
->partno
);
1988 log_info("Partition %" PRIu64
" too short for discard, skipping.", p
->partno
);
1992 return log_error_errno(r
, "Failed to discard data for new partition %" PRIu64
".", p
->partno
);
1994 log_info("Successfully discarded data from partition %" PRIu64
".", p
->partno
);
1998 static int context_discard_gap_after(Context
*context
, Partition
*p
) {
1999 uint64_t gap
, next
= UINT64_MAX
;
2004 assert(!p
|| (p
->offset
!= UINT64_MAX
&& p
->new_size
!= UINT64_MAX
));
2007 gap
= p
->offset
+ p
->new_size
;
2009 gap
= context
->start
;
2011 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2015 assert(q
->offset
!= UINT64_MAX
);
2016 assert(q
->new_size
!= UINT64_MAX
);
2018 if (q
->offset
< gap
)
2021 if (next
== UINT64_MAX
|| q
->offset
< next
)
2025 if (next
== UINT64_MAX
) {
2026 next
= context
->end
;
2028 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
2031 assert(next
>= gap
);
2032 r
= context_discard_range(context
, gap
, next
- gap
);
2033 if (r
== -EOPNOTSUPP
) {
2035 log_info("Storage does not support discarding, not discarding gap after partition %" PRIu64
".", p
->partno
);
2037 log_info("Storage does not support discarding, not discarding gap at beginning of disk.");
2040 if (r
== 0) /* Too short */
2044 return log_error_errno(r
, "Failed to discard gap after partition %" PRIu64
".", p
->partno
);
2046 return log_error_errno(r
, "Failed to discard gap at beginning of disk.");
2050 log_info("Successfully discarded gap after partition %" PRIu64
".", p
->partno
);
2052 log_info("Successfully discarded gap at beginning of disk.");
2057 static int context_wipe_and_discard(Context
*context
, bool from_scratch
) {
2063 /* Wipe and discard the contents of all partitions we are about to create. We skip the discarding if
2064 * we were supposed to start from scratch anyway, as in that case we just discard the whole block
2065 * device in one go early on. */
2067 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2069 if (!p
->allocated_to_area
)
2072 if (!from_scratch
) {
2073 r
= context_discard_partition(context
, p
);
2078 r
= context_wipe_partition(context
, p
);
2082 if (!from_scratch
) {
2083 r
= context_discard_gap_after(context
, p
);
2089 if (!from_scratch
) {
2090 r
= context_discard_gap_after(context
, NULL
);
2098 static int partition_acquire_uuid(Context
*context
, Partition
*p
, sd_id128_t
*ret
) {
2100 sd_id128_t type_uuid
;
2102 } _packed_ plaintext
= {};
2104 unsigned char md
[SHA256_DIGEST_LENGTH
];
2116 /* Calculate a good UUID for the indicated partition. We want a certain degree of reproducibility,
2117 * hence we won't generate the UUIDs randomly. Instead we use a cryptographic hash (precisely:
2118 * HMAC-SHA256) to derive them from a single seed. The seed is generally the machine ID of the
2119 * installation we are processing, but if random behaviour is desired can be random, too. We use the
2120 * seed value as key for the HMAC (since the machine ID is something we generally don't want to leak)
2121 * and the partition type as plaintext. The partition type is suffixed with a counter (only for the
2122 * second and later partition of the same type) if we have more than one partition of the same
2123 * time. Or in other words:
2126 * SEED := /etc/machine-id
2128 * If first partition instance of type TYPE_UUID:
2129 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID)
2131 * For all later partition instances of type TYPE_UUID with INSTANCE being the LE64 encoded instance number:
2132 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID || INSTANCE)
2135 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2139 if (!sd_id128_equal(p
->type_uuid
, q
->type_uuid
))
2145 plaintext
.type_uuid
= p
->type_uuid
;
2146 plaintext
.counter
= htole64(k
);
2148 if (!HMAC(EVP_sha256(),
2149 &context
->seed
, sizeof(context
->seed
),
2150 (const unsigned char*) &plaintext
, k
== 0 ? sizeof(sd_id128_t
) : sizeof(plaintext
),
2152 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "SHA256 calculation failed.");
2154 /* Take the first half, mark it as v4 UUID */
2155 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
2156 result
.id
= id128_make_v4_uuid(result
.id
);
2158 /* Ensure this partition UUID is actually unique, and there's no remaining partition from an earlier run? */
2159 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2163 if (sd_id128_equal(q
->current_uuid
, result
.id
) ||
2164 sd_id128_equal(q
->new_uuid
, result
.id
)) {
2165 log_warning("Partition UUID calculated from seed for partition %" PRIu64
" exists already, reverting to randomized UUID.", p
->partno
);
2167 r
= sd_id128_randomize(&result
.id
);
2169 return log_error_errno(r
, "Failed to generate randomized UUID: %m");
2179 static int partition_acquire_label(Context
*context
, Partition
*p
, char **ret
) {
2180 _cleanup_free_
char *label
= NULL
;
2188 prefix
= gpt_partition_type_uuid_to_string(p
->type_uuid
);
2193 const char *ll
= label
?: prefix
;
2197 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2201 if (streq_ptr(ll
, q
->current_label
) ||
2202 streq_ptr(ll
, q
->new_label
)) {
2211 label
= mfree(label
);
2214 if (asprintf(&label
, "%s-%u", prefix
, ++k
) < 0)
2219 label
= strdup(prefix
);
2224 *ret
= TAKE_PTR(label
);
2228 static int context_acquire_partition_uuids_and_labels(Context
*context
) {
2234 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2235 assert(sd_id128_is_null(p
->new_uuid
));
2237 /* Never touch foreign partitions */
2238 if (PARTITION_IS_FOREIGN(p
)) {
2239 p
->new_uuid
= p
->current_uuid
;
2241 if (p
->current_label
) {
2242 p
->new_label
= strdup(p
->current_label
);
2250 if (!sd_id128_is_null(p
->current_uuid
))
2251 p
->new_uuid
= p
->current_uuid
; /* Never change initialized UUIDs */
2253 r
= partition_acquire_uuid(context
, p
, &p
->new_uuid
);
2258 if (p
->new_label
) /* Explicitly set by user? */
2261 if (!isempty(p
->current_label
)) {
2262 p
->new_label
= strdup(p
->current_label
); /* never change initialized labels */
2266 r
= partition_acquire_label(context
, p
, &p
->new_label
);
2275 static int device_kernel_partitions_supported(int fd
) {
2276 struct loop_info64 info
;
2281 if (fstat(fd
, &st
) < 0)
2282 return log_error_errno(fd
, "Failed to fstat() image file: %m");
2283 if (!S_ISBLK(st
.st_mode
))
2284 return -ENOTBLK
; /* we do not log in this one special case about errors */
2286 if (ioctl(fd
, LOOP_GET_STATUS64
, &info
) < 0) {
2288 if (ERRNO_IS_NOT_SUPPORTED(errno
) || errno
== EINVAL
)
2289 return true; /* not a loopback device, let's assume partition are supported */
2291 return log_error_errno(fd
, "Failed to issue LOOP_GET_STATUS64 on block device: %m");
2294 #if HAVE_VALGRIND_MEMCHECK_H
2295 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
2296 VALGRIND_MAKE_MEM_DEFINED(&info
, sizeof(info
));
2299 return FLAGS_SET(info
.lo_flags
, LO_FLAGS_PARTSCAN
);
2302 static int context_write_partition_table(
2305 bool from_scratch
) {
2307 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*original_table
= NULL
;
2313 if (arg_pretty
> 0 ||
2314 (arg_pretty
< 0 && isatty(STDOUT_FILENO
) > 0)) {
2316 if (context
->n_partitions
== 0)
2317 puts("Empty partition table.");
2319 (void) context_dump_partitions(context
, node
);
2323 (void) context_dump_partition_bar(context
, node
);
2328 if (!from_scratch
&& !context_changed(context
)) {
2329 log_info("No changes.");
2334 log_notice("Refusing to repartition, please re-run with --dry-run=no.");
2338 log_info("Applying changes.");
2341 r
= context_discard_range(context
, 0, context
->total
);
2342 if (r
== -EOPNOTSUPP
)
2343 log_info("Storage does not support discarding, not discarding entire block device data.");
2345 return log_error_errno(r
, "Failed to discard entire block device: %m");
2347 log_info("Discarded entire block device.");
2350 r
= fdisk_get_partitions(context
->fdisk_context
, &original_table
);
2352 return log_error_errno(r
, "Failed to acquire partition table: %m");
2354 /* Wipe fs signatures and discard sectors where the new partitions are going to be placed and in the
2355 * gaps between partitions, just to be sure. */
2356 r
= context_wipe_and_discard(context
, from_scratch
);
2360 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2364 assert(p
->new_size
!= UINT64_MAX
);
2365 assert(p
->offset
!= UINT64_MAX
);
2366 assert(p
->partno
!= UINT64_MAX
);
2368 if (PARTITION_EXISTS(p
)) {
2369 bool changed
= false;
2371 assert(p
->current_partition
);
2373 if (p
->new_size
!= p
->current_size
) {
2374 assert(p
->new_size
>= p
->current_size
);
2375 assert(p
->new_size
% 512 == 0);
2377 r
= fdisk_partition_size_explicit(p
->current_partition
, true);
2379 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
2381 r
= fdisk_partition_set_size(p
->current_partition
, p
->new_size
/ 512);
2383 return log_error_errno(r
, "Failed to grow partition: %m");
2385 log_info("Growing existing partition %" PRIu64
".", p
->partno
);
2389 if (!sd_id128_equal(p
->new_uuid
, p
->current_uuid
)) {
2390 char buf
[ID128_UUID_STRING_MAX
];
2392 assert(!sd_id128_is_null(p
->new_uuid
));
2394 r
= fdisk_partition_set_uuid(p
->current_partition
, id128_to_uuid_string(p
->new_uuid
, buf
));
2396 return log_error_errno(r
, "Failed to set partition UUID: %m");
2398 log_info("Initializing UUID of existing partition %" PRIu64
".", p
->partno
);
2402 if (!streq_ptr(p
->new_label
, p
->current_label
)) {
2403 assert(!isempty(p
->new_label
));
2405 r
= fdisk_partition_set_name(p
->current_partition
, p
->new_label
);
2407 return log_error_errno(r
, "Failed to set partition label: %m");
2409 log_info("Setting partition label of existing partition %" PRIu64
".", p
->partno
);
2414 assert(!PARTITION_IS_FOREIGN(p
)); /* never touch foreign partitions */
2416 r
= fdisk_set_partition(context
->fdisk_context
, p
->partno
, p
->current_partition
);
2418 return log_error_errno(r
, "Failed to update partition: %m");
2421 _cleanup_(fdisk_unref_partitionp
) struct fdisk_partition
*q
= NULL
;
2422 _cleanup_(fdisk_unref_parttypep
) struct fdisk_parttype
*t
= NULL
;
2423 char ids
[ID128_UUID_STRING_MAX
];
2425 assert(!p
->new_partition
);
2426 assert(p
->offset
% 512 == 0);
2427 assert(p
->new_size
% 512 == 0);
2428 assert(!sd_id128_is_null(p
->new_uuid
));
2429 assert(!isempty(p
->new_label
));
2431 t
= fdisk_new_parttype();
2435 r
= fdisk_parttype_set_typestr(t
, id128_to_uuid_string(p
->type_uuid
, ids
));
2437 return log_error_errno(r
, "Failed to initialize partition type: %m");
2439 q
= fdisk_new_partition();
2443 r
= fdisk_partition_set_type(q
, t
);
2445 return log_error_errno(r
, "Failed to set partition type: %m");
2447 r
= fdisk_partition_size_explicit(q
, true);
2449 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
2451 r
= fdisk_partition_set_start(q
, p
->offset
/ 512);
2453 return log_error_errno(r
, "Failed to position partition: %m");
2455 r
= fdisk_partition_set_size(q
, p
->new_size
/ 512);
2457 return log_error_errno(r
, "Failed to grow partition: %m");
2459 r
= fdisk_partition_set_partno(q
, p
->partno
);
2461 return log_error_errno(r
, "Failed to set partition number: %m");
2463 r
= fdisk_partition_set_uuid(q
, id128_to_uuid_string(p
->new_uuid
, ids
));
2465 return log_error_errno(r
, "Failed to set partition UUID: %m");
2467 r
= fdisk_partition_set_name(q
, p
->new_label
);
2469 return log_error_errno(r
, "Failed to set partition label: %m");
2471 log_info("Creating new partition %" PRIu64
".", p
->partno
);
2473 r
= fdisk_add_partition(context
->fdisk_context
, q
, NULL
);
2475 return log_error_errno(r
, "Failed to add partition: %m");
2477 assert(!p
->new_partition
);
2478 p
->new_partition
= TAKE_PTR(q
);
2482 log_info("Writing new partition table.");
2484 r
= fdisk_write_disklabel(context
->fdisk_context
);
2486 return log_error_errno(r
, "Failed to write partition table: %m");
2488 capable
= device_kernel_partitions_supported(fdisk_get_devfd(context
->fdisk_context
));
2489 if (capable
== -ENOTBLK
)
2490 log_debug("Not telling kernel to reread partition table, since we are not operating on a block device.");
2491 else if (capable
< 0)
2493 else if (capable
> 0) {
2494 log_info("Telling kernel to reread partition table.");
2497 r
= fdisk_reread_partition_table(context
->fdisk_context
);
2499 r
= fdisk_reread_changes(context
->fdisk_context
, original_table
);
2501 return log_error_errno(r
, "Failed to reread partition table: %m");
2503 log_notice("Not telling kernel to reread partition table, because selected image does not support kernel partition block devices.");
2505 log_info("All done.");
2510 static int context_read_seed(Context
*context
, const char *root
) {
2515 if (!sd_id128_is_null(context
->seed
))
2518 if (!arg_randomize
) {
2519 _cleanup_close_
int fd
= -1;
2521 fd
= chase_symlinks_and_open("/etc/machine-id", root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
, NULL
);
2523 log_info("No machine ID set, using randomized partition UUIDs.");
2525 return log_error_errno(fd
, "Failed to determine machine ID of image: %m");
2527 r
= id128_read_fd(fd
, ID128_PLAIN
, &context
->seed
);
2528 if (r
== -ENOMEDIUM
)
2529 log_info("No machine ID set, using randomized partition UUIDs.");
2531 return log_error_errno(r
, "Failed to parse machine ID of image: %m");
2537 r
= sd_id128_randomize(&context
->seed
);
2539 return log_error_errno(r
, "Failed to generate randomized seed: %m");
2544 static int context_factory_reset(Context
*context
, bool from_scratch
) {
2551 if (arg_factory_reset
<= 0)
2554 if (from_scratch
) /* Nothing to reset if we start from scratch */
2558 log_notice("Refusing to factory reset, please re-run with --dry-run=no.");
2562 log_info("Applying factory reset.");
2564 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2566 if (!p
->factory_reset
|| !PARTITION_EXISTS(p
))
2569 assert(p
->partno
!= UINT64_MAX
);
2571 log_info("Removing partition %" PRIu64
" for factory reset.", p
->partno
);
2573 r
= fdisk_delete_partition(context
->fdisk_context
, p
->partno
);
2575 return log_error_errno(r
, "Failed to remove partition %" PRIu64
": %m", p
->partno
);
2581 log_info("Factory reset requested, but no partitions to delete found.");
2585 r
= fdisk_write_disklabel(context
->fdisk_context
);
2587 return log_error_errno(r
, "Failed to write disk label: %m");
2589 log_info("Successfully deleted %zu partitions.", n
);
2593 static int context_can_factory_reset(Context
*context
) {
2598 LIST_FOREACH(partitions
, p
, context
->partitions
)
2599 if (p
->factory_reset
&& PARTITION_EXISTS(p
))
2605 static int help(void) {
2606 _cleanup_free_
char *link
= NULL
;
2609 r
= terminal_urlify_man("systemd-repart", "1", &link
);
2613 printf("%s [OPTIONS...] [DEVICE]\n"
2614 "\n%sGrow and add partitions to partition table.%s\n\n"
2615 " -h --help Show this help\n"
2616 " --version Show package version\n"
2617 " --dry-run=BOOL Whether to run dry-run operation\n"
2618 " --empty=MODE One of refuse, allow, require, force, create; controls\n"
2619 " how to handle empty disks lacking partition tables\n"
2620 " --discard=BOOL Whether to discard backing blocks for new partitions\n"
2621 " --pretty=BOOL Whether to show pretty summary before executing operation\n"
2622 " --factory-reset=BOOL Whether to remove data partitions before recreating\n"
2624 " --can-factory-reset Test whether factory reset is defined\n"
2625 " --root=PATH Operate relative to root path\n"
2626 " --definitions=DIR Find partitions in specified directory\n"
2627 " --seed=UUID 128bit seed UUID to derive all UUIDs from\n"
2628 " --size=BYTES Grow loopback file to specified size\n"
2629 "\nSee the %s for details.\n"
2630 , program_invocation_short_name
2631 , ansi_highlight(), ansi_normal()
2638 static int parse_argv(int argc
, char *argv
[]) {
2641 ARG_VERSION
= 0x100,
2646 ARG_CAN_FACTORY_RESET
,
2654 static const struct option options
[] = {
2655 { "help", no_argument
, NULL
, 'h' },
2656 { "version", no_argument
, NULL
, ARG_VERSION
},
2657 { "dry-run", required_argument
, NULL
, ARG_DRY_RUN
},
2658 { "empty", required_argument
, NULL
, ARG_EMPTY
},
2659 { "discard", required_argument
, NULL
, ARG_DISCARD
},
2660 { "factory-reset", required_argument
, NULL
, ARG_FACTORY_RESET
},
2661 { "can-factory-reset", no_argument
, NULL
, ARG_CAN_FACTORY_RESET
},
2662 { "root", required_argument
, NULL
, ARG_ROOT
},
2663 { "seed", required_argument
, NULL
, ARG_SEED
},
2664 { "pretty", required_argument
, NULL
, ARG_PRETTY
},
2665 { "definitions", required_argument
, NULL
, ARG_DEFINITIONS
},
2666 { "size", required_argument
, NULL
, ARG_SIZE
},
2670 int c
, r
, dry_run
= -1;
2675 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
2686 r
= parse_boolean(optarg
);
2688 return log_error_errno(r
, "Failed to parse --dry-run= parameter: %s", optarg
);
2694 if (isempty(optarg
) || streq(optarg
, "refuse"))
2695 arg_empty
= EMPTY_REFUSE
;
2696 else if (streq(optarg
, "allow"))
2697 arg_empty
= EMPTY_ALLOW
;
2698 else if (streq(optarg
, "require"))
2699 arg_empty
= EMPTY_REQUIRE
;
2700 else if (streq(optarg
, "force"))
2701 arg_empty
= EMPTY_FORCE
;
2702 else if (streq(optarg
, "create")) {
2703 arg_empty
= EMPTY_CREATE
;
2706 dry_run
= false; /* Imply --dry-run=no if we create the loopback file
2707 * anew. After all we cannot really break anyone's
2708 * partition tables that way. */
2710 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2711 "Failed to parse --empty= parameter: %s", optarg
);
2715 r
= parse_boolean(optarg
);
2717 return log_error_errno(r
, "Failed to parse --discard= parameter: %s", optarg
);
2722 case ARG_FACTORY_RESET
:
2723 r
= parse_boolean(optarg
);
2725 return log_error_errno(r
, "Failed to parse --factory-reset= parameter: %s", optarg
);
2727 arg_factory_reset
= r
;
2730 case ARG_CAN_FACTORY_RESET
:
2731 arg_can_factory_reset
= true;
2735 r
= parse_path_argument_and_warn(optarg
, false, &arg_root
);
2741 if (isempty(optarg
)) {
2742 arg_seed
= SD_ID128_NULL
;
2743 arg_randomize
= false;
2744 } else if (streq(optarg
, "random"))
2745 arg_randomize
= true;
2747 r
= sd_id128_from_string(optarg
, &arg_seed
);
2749 return log_error_errno(r
, "Failed to parse seed: %s", optarg
);
2751 arg_randomize
= false;
2757 r
= parse_boolean(optarg
);
2759 return log_error_errno(r
, "Failed to parse --pretty= parameter: %s", optarg
);
2764 case ARG_DEFINITIONS
:
2765 r
= parse_path_argument_and_warn(optarg
, false, &arg_definitions
);
2771 uint64_t parsed
, rounded
;
2773 r
= parse_size(optarg
, 1024, &parsed
);
2775 return log_error_errno(r
, "Failed to parse --size= parameter: %s", optarg
);
2777 rounded
= round_up_size(parsed
, 4096);
2779 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too small, refusing.");
2780 if (rounded
== UINT64_MAX
)
2781 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too large, refusing.");
2783 if (rounded
!= parsed
)
2784 log_warning("Specified size is not a multiple of 4096, rounding up automatically. (%" PRIu64
" → %" PRIu64
")",
2795 assert_not_reached("Unhandled option");
2798 if (argc
- optind
> 1)
2799 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2800 "Expected at most one argument, the path to the block device.");
2802 if (arg_factory_reset
> 0 && IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
))
2803 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2804 "Combination of --factory-reset=yes and --empty=force/--empty=require/--empty=create is invalid.");
2806 if (arg_can_factory_reset
)
2807 arg_dry_run
= true; /* When --can-factory-reset is specified we don't make changes, hence
2808 * non-dry-run mode makes no sense. Thus, imply dry run mode so that we
2809 * open things strictly read-only. */
2810 else if (dry_run
>= 0)
2811 arg_dry_run
= dry_run
;
2813 if (arg_empty
== EMPTY_CREATE
&& arg_size
== UINT64_MAX
)
2814 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2815 "If --empty=create is specified, --size= must be specified, too.");
2817 arg_node
= argc
> optind
? argv
[optind
] : NULL
;
2819 if (IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
) && !arg_node
)
2820 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2821 "A path to a device node or loopback file must be specified when --empty=force, --empty=require or --empty=create are used.");
2826 static int parse_proc_cmdline_factory_reset(void) {
2830 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
2833 if (!in_initrd()) /* Never honour kernel command line factory reset request outside of the initrd */
2836 r
= proc_cmdline_get_bool("systemd.factory_reset", &b
);
2838 return log_error_errno(r
, "Failed to parse systemd.factory_reset kernel command line argument: %m");
2840 arg_factory_reset
= b
;
2843 log_notice("Honouring factory reset requested via kernel command line.");
2849 static int parse_efi_variable_factory_reset(void) {
2850 _cleanup_free_
char *value
= NULL
;
2853 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
2856 if (!in_initrd()) /* Never honour EFI variable factory reset request outside of the initrd */
2859 r
= efi_get_variable_string(EFI_VENDOR_SYSTEMD
, "FactoryReset", &value
);
2860 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
2863 return log_error_errno(r
, "Failed to read EFI variable FactoryReset: %m");
2865 r
= parse_boolean(value
);
2867 return log_error_errno(r
, "Failed to parse EFI variable FactoryReset: %m");
2869 arg_factory_reset
= r
;
2871 log_notice("Honouring factory reset requested via EFI variable FactoryReset: %m");
2876 static int remove_efi_variable_factory_reset(void) {
2879 r
= efi_set_variable(EFI_VENDOR_SYSTEMD
, "FactoryReset", NULL
, 0);
2880 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
2883 return log_error_errno(r
, "Failed to remove EFI variable FactoryReset: %m");
2885 log_info("Successfully unset EFI variable FactoryReset.");
2889 static int acquire_root_devno(const char *p
, int mode
, char **ret
, int *ret_fd
) {
2890 _cleanup_close_
int fd
= -1;
2892 dev_t devno
, fd_devno
= (mode_t
) -1;
2903 if (fstat(fd
, &st
) < 0)
2906 if (S_ISREG(st
.st_mode
)) {
2914 *ret_fd
= TAKE_FD(fd
);
2919 if (S_ISBLK(st
.st_mode
))
2920 fd_devno
= devno
= st
.st_rdev
;
2921 else if (S_ISDIR(st
.st_mode
)) {
2924 if (major(devno
) == 0) {
2925 r
= btrfs_get_block_device_fd(fd
, &devno
);
2926 if (r
== -ENOTTY
) /* not btrfs */
2934 /* From dm-crypt to backing partition */
2935 r
= block_get_originating(devno
, &devno
);
2937 log_debug_errno(r
, "Failed to find underlying block device for '%s', ignoring: %m", p
);
2939 /* From partition to whole disk containing it */
2940 r
= block_get_whole_disk(devno
, &devno
);
2942 log_debug_errno(r
, "Failed to find whole disk block device for '%s', ignoring: %m", p
);
2944 r
= device_path_make_canonical(S_IFBLK
, devno
, ret
);
2946 return log_debug_errno(r
, "Failed to determine canonical path for '%s': %m", p
);
2948 /* Only if we still lock at the same block device we can reuse the fd. Otherwise return an
2949 * invalidated fd. */
2950 *ret_fd
= fd_devno
!= (mode_t
) -1 && fd_devno
== devno
? TAKE_FD(fd
) : -1;
2954 static int find_root(char **ret
, int *ret_fd
) {
2962 if (arg_empty
== EMPTY_CREATE
) {
2963 _cleanup_close_
int fd
= -1;
2964 _cleanup_free_
char *s
= NULL
;
2966 s
= strdup(arg_node
);
2970 fd
= open(arg_node
, O_RDONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOFOLLOW
, 0777);
2972 return log_error_errno(errno
, "Failed to create '%s': %m", arg_node
);
2975 *ret_fd
= TAKE_FD(fd
);
2979 r
= acquire_root_devno(arg_node
, O_RDONLY
|O_CLOEXEC
, ret
, ret_fd
);
2981 return log_error_errno(r
, "Failed to determine backing device of %s: %m", arg_node
);
2986 assert(IN_SET(arg_empty
, EMPTY_REFUSE
, EMPTY_ALLOW
));
2988 /* Let's search for the root device. We look for two cases here: first in /, and then in /usr. The
2989 * latter we check for cases where / is a tmpfs and only /usr is an actual persistent block device
2990 * (think: volatile setups) */
2992 FOREACH_STRING(t
, "/", "/usr") {
2993 _cleanup_free_
char *j
= NULL
;
2997 j
= path_join("/sysroot", t
);
3005 r
= acquire_root_devno(p
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, ret
, ret_fd
);
3008 return log_error_errno(r
, "Failed to determine backing device of %s: %m", p
);
3013 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
), "Failed to discover root block device.");
3016 static int resize_backing_fd(const char *node
, int *fd
) {
3017 char buf1
[FORMAT_BYTES_MAX
], buf2
[FORMAT_BYTES_MAX
];
3018 _cleanup_close_
int writable_fd
= -1;
3025 if (arg_size
== UINT64_MAX
) /* Nothing to do */
3029 /* Open the file if we haven't opened it yet. Note that we open it read-only here, just to
3030 * keep a reference to the file we can pass around. */
3031 *fd
= open(node
, O_RDONLY
|O_CLOEXEC
);
3033 return log_error_errno(errno
, "Failed to open '%s' in order to adjust size: %m", node
);
3036 if (fstat(*fd
, &st
) < 0)
3037 return log_error_errno(errno
, "Failed to stat '%s': %m", node
);
3039 r
= stat_verify_regular(&st
);
3041 return log_error_errno(r
, "Specified path '%s' is not a regular file, cannot resize: %m", node
);
3043 assert_se(format_bytes(buf1
, sizeof(buf1
), st
.st_size
));
3044 assert_se(format_bytes(buf2
, sizeof(buf2
), arg_size
));
3046 if ((uint64_t) st
.st_size
>= arg_size
) {
3047 log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)", node
, buf1
, buf2
);
3051 /* The file descriptor is read-only. In order to grow the file we need to have a writable fd. We
3052 * reopen the file for that temporarily. We keep the writable fd only open for this operation though,
3053 * as fdisk can't accept it anyway. */
3055 writable_fd
= fd_reopen(*fd
, O_WRONLY
|O_CLOEXEC
);
3056 if (writable_fd
< 0)
3057 return log_error_errno(writable_fd
, "Failed to reopen backing file '%s' writable: %m", node
);
3060 if (fallocate(writable_fd
, 0, 0, arg_size
) < 0) {
3061 if (!ERRNO_IS_NOT_SUPPORTED(errno
))
3062 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by allocation: %m",
3065 /* Fallback to truncation, if fallocate() is not supported. */
3066 log_debug("Backing file system does not support fallocate(), falling back to ftruncate().");
3068 if (st
.st_size
== 0) /* Likely regular file just created by us */
3069 log_info("Allocated %s for '%s'.", buf2
, node
);
3071 log_info("File '%s' grown from %s to %s by allocation.", node
, buf1
, buf2
);
3077 if (ftruncate(writable_fd
, arg_size
) < 0)
3078 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by truncation: %m",
3081 if (st
.st_size
== 0) /* Likely regular file just created by us */
3082 log_info("Sized '%s' to %s.", node
, buf2
);
3084 log_info("File '%s' grown from %s to %s by truncation.", node
, buf1
, buf2
);
3089 static int run(int argc
, char *argv
[]) {
3090 _cleanup_(context_freep
) Context
* context
= NULL
;
3091 _cleanup_free_
char *node
= NULL
;
3092 _cleanup_close_
int backing_fd
= -1;
3096 log_show_color(true);
3097 log_parse_environment();
3101 /* Default to operation on /sysroot when invoked in the initrd! */
3102 arg_root
= strdup("/sysroot");
3107 r
= parse_argv(argc
, argv
);
3111 r
= parse_proc_cmdline_factory_reset();
3115 r
= parse_efi_variable_factory_reset();
3119 context
= context_new(arg_seed
);
3123 r
= context_read_definitions(context
, arg_definitions
, arg_root
);
3127 if (context
->n_partitions
<= 0 && arg_empty
== EMPTY_REFUSE
) {
3128 log_info("Didn't find any partition definition files, nothing to do.");
3132 r
= find_root(&node
, &backing_fd
);
3136 if (arg_size
!= UINT64_MAX
) {
3137 r
= resize_backing_fd(node
, &backing_fd
);
3142 r
= context_load_partition_table(context
, node
, &backing_fd
);
3143 if (r
== -EHWPOISON
)
3144 return 77; /* Special return value which means "Not GPT, so not doing anything". This isn't
3145 * really an error when called at boot. */
3148 from_scratch
= r
> 0; /* Starting from scratch */
3150 if (arg_can_factory_reset
) {
3151 r
= context_can_factory_reset(context
);
3155 return EXIT_FAILURE
;
3160 r
= context_factory_reset(context
, from_scratch
);
3164 /* We actually did a factory reset! */
3165 r
= remove_efi_variable_factory_reset();
3169 /* Reload the reduced partition table */
3170 context_unload_partition_table(context
);
3171 r
= context_load_partition_table(context
, node
, &backing_fd
);
3177 (void) context_dump_partitions(context
, node
);
3181 r
= context_read_seed(context
, arg_root
);
3185 /* First try to fit new partitions in, dropping by priority until it fits */
3187 if (context_allocate_partitions(context
))
3188 break; /* Success! */
3190 if (!context_drop_one_priority(context
))
3191 return log_error_errno(SYNTHETIC_ERRNO(ENOSPC
),
3192 "Can't fit requested partitions into free space, refusing.");
3195 /* Now assign free space according to the weight logic */
3196 r
= context_grow_partitions(context
);
3200 /* Now calculate where each partition gets placed */
3201 context_place_partitions(context
);
3203 /* Make sure each partition has a unique UUID and unique label */
3204 r
= context_acquire_partition_uuids_and_labels(context
);
3208 r
= context_write_partition_table(context
, node
, from_scratch
);
3215 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);