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", "UUID", config_parse_id128
, 0, &p
->new_uuid
},
967 { "Partition", "Priority", config_parse_int32
, 0, &p
->priority
},
968 { "Partition", "Weight", config_parse_weight
, 0, &p
->weight
},
969 { "Partition", "PaddingWeight", config_parse_weight
, 0, &p
->padding_weight
},
970 { "Partition", "SizeMinBytes", config_parse_size4096
, 1, &p
->size_min
},
971 { "Partition", "SizeMaxBytes", config_parse_size4096
, -1, &p
->size_max
},
972 { "Partition", "PaddingMinBytes", config_parse_size4096
, 1, &p
->padding_min
},
973 { "Partition", "PaddingMaxBytes", config_parse_size4096
, -1, &p
->padding_max
},
974 { "Partition", "FactoryReset", config_parse_bool
, 0, &p
->factory_reset
},
979 r
= config_parse(NULL
, path
, NULL
, "Partition\0", config_item_table_lookup
, table
, CONFIG_PARSE_WARN
, p
);
983 if (p
->size_min
!= UINT64_MAX
&& p
->size_max
!= UINT64_MAX
&& p
->size_min
> p
->size_max
)
984 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
985 "SizeMinBytes= larger than SizeMaxBytes=, refusing.");
987 if (p
->padding_min
!= UINT64_MAX
&& p
->padding_max
!= UINT64_MAX
&& p
->padding_min
> p
->padding_max
)
988 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
989 "PaddingMinBytes= larger than PaddingMaxBytes=, refusing.");
991 if (sd_id128_is_null(p
->type_uuid
))
992 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
993 "Type= not defined, refusing.");
998 static int context_read_definitions(
1000 const char *directory
,
1003 _cleanup_strv_free_
char **files
= NULL
;
1004 Partition
*last
= NULL
;
1011 r
= conf_files_list_strv(&files
, ".conf", NULL
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, (const char**) STRV_MAKE(directory
));
1013 r
= conf_files_list_strv(&files
, ".conf", root
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, (const char**) CONF_PATHS_STRV("repart.d"));
1015 return log_error_errno(r
, "Failed to enumerate *.conf files: %m");
1017 STRV_FOREACH(f
, files
) {
1018 _cleanup_(partition_freep
) Partition
*p
= NULL
;
1020 p
= partition_new();
1024 p
->definition_path
= strdup(*f
);
1025 if (!p
->definition_path
)
1028 r
= partition_read_definition(p
, *f
);
1032 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, p
);
1034 context
->n_partitions
++;
1040 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_context
*, fdisk_unref_context
);
1041 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_partition
*, fdisk_unref_partition
);
1042 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_parttype
*, fdisk_unref_parttype
);
1043 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_table
*, fdisk_unref_table
);
1045 static int determine_current_padding(
1046 struct fdisk_context
*c
,
1047 struct fdisk_table
*t
,
1048 struct fdisk_partition
*p
,
1051 size_t n_partitions
;
1052 uint64_t offset
, next
= UINT64_MAX
;
1058 if (!fdisk_partition_has_end(p
))
1059 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition has no end!");
1061 offset
= fdisk_partition_get_end(p
);
1062 assert(offset
< UINT64_MAX
/ 512);
1065 n_partitions
= fdisk_table_get_nents(t
);
1066 for (size_t i
= 0; i
< n_partitions
; i
++) {
1067 struct fdisk_partition
*q
;
1070 q
= fdisk_table_get_partition(t
, i
);
1072 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1074 if (fdisk_partition_is_used(q
) <= 0)
1077 if (!fdisk_partition_has_start(q
))
1080 start
= fdisk_partition_get_start(q
);
1081 assert(start
< UINT64_MAX
/ 512);
1084 if (start
>= offset
&& (next
== UINT64_MAX
|| next
> start
))
1088 if (next
== UINT64_MAX
) {
1089 /* No later partition? In that case check the end of the usable area */
1090 next
= fdisk_get_last_lba(c
);
1091 assert(next
< UINT64_MAX
);
1092 next
++; /* The last LBA is one sector before the end */
1094 assert(next
< UINT64_MAX
/ 512);
1098 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
1101 assert(next
>= offset
);
1102 offset
= round_up_size(offset
, 4096);
1103 next
= round_down_size(next
, 4096);
1105 if (next
>= offset
) /* Check again, rounding might have fucked things up */
1106 *ret
= next
- offset
;
1113 static int fdisk_ask_cb(struct fdisk_context
*c
, struct fdisk_ask
*ask
, void *data
) {
1114 _cleanup_free_
char *ids
= NULL
;
1117 if (fdisk_ask_get_type(ask
) != FDISK_ASKTYPE_STRING
)
1120 ids
= new(char, ID128_UUID_STRING_MAX
);
1124 r
= fdisk_ask_string_set_result(ask
, id128_to_uuid_string(*(sd_id128_t
*) data
, ids
));
1132 static int fdisk_set_disklabel_id_by_uuid(struct fdisk_context
*c
, sd_id128_t id
) {
1135 r
= fdisk_set_ask(c
, fdisk_ask_cb
, &id
);
1139 r
= fdisk_set_disklabel_id(c
);
1143 return fdisk_set_ask(c
, NULL
, NULL
);
1146 #define DISK_UUID_TOKEN "disk-uuid"
1148 static int disk_acquire_uuid(Context
*context
, sd_id128_t
*ret
) {
1150 unsigned char md
[SHA256_DIGEST_LENGTH
];
1157 /* Calculate the HMAC-SHA256 of the string "disk-uuid", keyed off the machine ID. We use the machine
1158 * ID as key (and not as cleartext!) since it's the machine ID we don't want to leak. */
1160 if (!HMAC(EVP_sha256(),
1161 &context
->seed
, sizeof(context
->seed
),
1162 (const unsigned char*) DISK_UUID_TOKEN
, strlen(DISK_UUID_TOKEN
),
1164 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "HMAC-SHA256 calculation failed.");
1166 /* Take the first half, mark it as v4 UUID */
1167 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
1168 *ret
= id128_make_v4_uuid(result
.id
);
1172 static int context_load_partition_table(
1177 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
1178 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
1179 uint64_t left_boundary
= UINT64_MAX
, first_lba
, last_lba
, nsectors
;
1180 _cleanup_free_
char *disk_uuid_string
= NULL
;
1181 bool from_scratch
= false;
1182 sd_id128_t disk_uuid
;
1183 size_t n_partitions
;
1190 c
= fdisk_new_context();
1194 /* libfdisk doesn't have an API to operate on arbitrary fds, hence reopen the fd going via the
1195 * /proc/self/fd/ magic path if we have an existing fd. Open the original file otherwise. */
1196 if (*backing_fd
< 0)
1197 r
= fdisk_assign_device(c
, node
, arg_dry_run
);
1199 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1200 xsprintf(procfs_path
, "/proc/self/fd/%i", *backing_fd
);
1202 r
= fdisk_assign_device(c
, procfs_path
, arg_dry_run
);
1205 return log_error_errno(r
, "Failed to open device '%s': %m", node
);
1207 if (*backing_fd
< 0) {
1208 /* If we have no fd referencing the device yet, make a copy of the fd now, so that we have one */
1209 *backing_fd
= fcntl(fdisk_get_devfd(c
), F_DUPFD_CLOEXEC
, 3);
1210 if (*backing_fd
< 0)
1211 return log_error_errno(errno
, "Failed to duplicate fdisk fd: %m");
1214 /* Tell udev not to interfere while we are processing the device */
1215 if (flock(fdisk_get_devfd(c
), arg_dry_run
? LOCK_SH
: LOCK_EX
) < 0)
1216 return log_error_errno(errno
, "Failed to lock block device: %m");
1218 switch (arg_empty
) {
1221 /* Refuse empty disks, insist on an existing GPT partition table */
1222 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
1223 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has no GPT disk label, not repartitioning.", node
);
1228 /* Require an empty disk, refuse any existing partition table */
1229 r
= fdisk_has_label(c
);
1231 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", node
);
1233 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s already has a disk label, refusing.", node
);
1235 from_scratch
= true;
1239 /* Allow both an empty disk and an existing partition table, but only GPT */
1240 r
= fdisk_has_label(c
);
1242 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", node
);
1244 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
1245 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has non-GPT disk label, not repartitioning.", node
);
1247 from_scratch
= true;
1253 /* Always reinitiaize the disk, don't consider what there was on the disk before */
1254 from_scratch
= true;
1259 r
= fdisk_enable_wipe(c
, true);
1261 return log_error_errno(r
, "Failed to enable wiping of disk signature: %m");
1263 r
= fdisk_create_disklabel(c
, "gpt");
1265 return log_error_errno(r
, "Failed to create GPT disk label: %m");
1267 r
= disk_acquire_uuid(context
, &disk_uuid
);
1269 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
1271 r
= fdisk_set_disklabel_id_by_uuid(c
, disk_uuid
);
1273 return log_error_errno(r
, "Failed to set GPT disk label: %m");
1275 goto add_initial_free_area
;
1278 r
= fdisk_get_disklabel_id(c
, &disk_uuid_string
);
1280 return log_error_errno(r
, "Failed to get current GPT disk label UUID: %m");
1282 r
= sd_id128_from_string(disk_uuid_string
, &disk_uuid
);
1284 return log_error_errno(r
, "Failed to parse current GPT disk label UUID: %m");
1286 if (sd_id128_is_null(disk_uuid
)) {
1287 r
= disk_acquire_uuid(context
, &disk_uuid
);
1289 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
1291 r
= fdisk_set_disklabel_id(c
);
1293 return log_error_errno(r
, "Failed to set GPT disk label: %m");
1296 r
= fdisk_get_partitions(c
, &t
);
1298 return log_error_errno(r
, "Failed to acquire partition table: %m");
1300 n_partitions
= fdisk_table_get_nents(t
);
1301 for (size_t i
= 0; i
< n_partitions
; i
++) {
1302 _cleanup_free_
char *label_copy
= NULL
;
1303 Partition
*pp
, *last
= NULL
;
1304 struct fdisk_partition
*p
;
1305 struct fdisk_parttype
*pt
;
1306 const char *pts
, *ids
, *label
;
1309 sd_id128_t ptid
, id
;
1312 p
= fdisk_table_get_partition(t
, i
);
1314 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1316 if (fdisk_partition_is_used(p
) <= 0)
1319 if (fdisk_partition_has_start(p
) <= 0 ||
1320 fdisk_partition_has_size(p
) <= 0 ||
1321 fdisk_partition_has_partno(p
) <= 0)
1322 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a position, size or number.");
1324 pt
= fdisk_partition_get_type(p
);
1326 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to acquire type of partition: %m");
1328 pts
= fdisk_parttype_get_string(pt
);
1330 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to acquire type of partition as string: %m");
1332 r
= sd_id128_from_string(pts
, &ptid
);
1334 return log_error_errno(r
, "Failed to parse partition type UUID %s: %m", pts
);
1336 ids
= fdisk_partition_get_uuid(p
);
1338 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a UUID.");
1340 r
= sd_id128_from_string(ids
, &id
);
1342 return log_error_errno(r
, "Failed to parse partition UUID %s: %m", ids
);
1344 label
= fdisk_partition_get_name(p
);
1345 if (!isempty(label
)) {
1346 label_copy
= strdup(label
);
1351 sz
= fdisk_partition_get_size(p
);
1352 assert_se(sz
<= UINT64_MAX
/512);
1355 start
= fdisk_partition_get_start(p
);
1356 assert_se(start
<= UINT64_MAX
/512);
1359 partno
= fdisk_partition_get_partno(p
);
1361 if (left_boundary
== UINT64_MAX
|| left_boundary
> start
)
1362 left_boundary
= start
;
1364 /* Assign this existing partition to the first partition of the right type that doesn't have
1365 * an existing one assigned yet. */
1366 LIST_FOREACH(partitions
, pp
, context
->partitions
) {
1369 if (!sd_id128_equal(pp
->type_uuid
, ptid
))
1372 if (!pp
->current_partition
) {
1373 pp
->current_uuid
= id
;
1374 pp
->current_size
= sz
;
1376 pp
->partno
= partno
;
1377 pp
->current_label
= TAKE_PTR(label_copy
);
1379 pp
->current_partition
= p
;
1380 fdisk_ref_partition(p
);
1382 r
= determine_current_padding(c
, t
, p
, &pp
->current_padding
);
1386 if (pp
->current_padding
> 0) {
1387 r
= context_add_free_area(context
, pp
->current_padding
, pp
);
1397 /* If we have no matching definition, create a new one. */
1399 _cleanup_(partition_freep
) Partition
*np
= NULL
;
1401 np
= partition_new();
1405 np
->current_uuid
= id
;
1406 np
->type_uuid
= ptid
;
1407 np
->current_size
= sz
;
1409 np
->partno
= partno
;
1410 np
->current_label
= TAKE_PTR(label_copy
);
1412 np
->current_partition
= p
;
1413 fdisk_ref_partition(p
);
1415 r
= determine_current_padding(c
, t
, p
, &np
->current_padding
);
1419 if (np
->current_padding
> 0) {
1420 r
= context_add_free_area(context
, np
->current_padding
, np
);
1425 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, TAKE_PTR(np
));
1426 context
->n_partitions
++;
1430 add_initial_free_area
:
1431 nsectors
= fdisk_get_nsectors(c
);
1432 assert(nsectors
<= UINT64_MAX
/512);
1435 first_lba
= fdisk_get_first_lba(c
);
1436 assert(first_lba
<= UINT64_MAX
/512);
1439 last_lba
= fdisk_get_last_lba(c
);
1440 assert(last_lba
< UINT64_MAX
);
1442 assert(last_lba
<= UINT64_MAX
/512);
1445 assert(last_lba
>= first_lba
);
1447 if (left_boundary
== UINT64_MAX
) {
1448 /* No partitions at all? Then the whole disk is up for grabs. */
1450 first_lba
= round_up_size(first_lba
, 4096);
1451 last_lba
= round_down_size(last_lba
, 4096);
1453 if (last_lba
> first_lba
) {
1454 r
= context_add_free_area(context
, last_lba
- first_lba
, NULL
);
1459 /* Add space left of first partition */
1460 assert(left_boundary
>= first_lba
);
1462 first_lba
= round_up_size(first_lba
, 4096);
1463 left_boundary
= round_down_size(left_boundary
, 4096);
1464 last_lba
= round_down_size(last_lba
, 4096);
1466 if (left_boundary
> first_lba
) {
1467 r
= context_add_free_area(context
, left_boundary
- first_lba
, NULL
);
1473 context
->start
= first_lba
;
1474 context
->end
= last_lba
;
1475 context
->total
= nsectors
;
1476 context
->fdisk_context
= TAKE_PTR(c
);
1478 return from_scratch
;
1481 static void context_unload_partition_table(Context
*context
) {
1482 Partition
*p
, *next
;
1486 LIST_FOREACH_SAFE(partitions
, p
, next
, context
->partitions
) {
1488 /* Entirely remove partitions that have no configuration */
1489 if (PARTITION_IS_FOREIGN(p
)) {
1490 partition_unlink_and_free(context
, p
);
1494 /* Otherwise drop all data we read off the block device and everything we might have
1495 * calculated based on it */
1498 p
->current_size
= UINT64_MAX
;
1499 p
->new_size
= UINT64_MAX
;
1500 p
->current_padding
= UINT64_MAX
;
1501 p
->new_padding
= UINT64_MAX
;
1502 p
->partno
= UINT64_MAX
;
1503 p
->offset
= UINT64_MAX
;
1505 if (p
->current_partition
) {
1506 fdisk_unref_partition(p
->current_partition
);
1507 p
->current_partition
= NULL
;
1510 if (p
->new_partition
) {
1511 fdisk_unref_partition(p
->new_partition
);
1512 p
->new_partition
= NULL
;
1515 p
->padding_area
= NULL
;
1516 p
->allocated_to_area
= NULL
;
1518 p
->current_uuid
= p
->new_uuid
= SD_ID128_NULL
;
1521 context
->start
= UINT64_MAX
;
1522 context
->end
= UINT64_MAX
;
1523 context
->total
= UINT64_MAX
;
1525 if (context
->fdisk_context
) {
1526 fdisk_unref_context(context
->fdisk_context
);
1527 context
->fdisk_context
= NULL
;
1530 context_free_free_areas(context
);
1533 static int format_size_change(uint64_t from
, uint64_t to
, char **ret
) {
1534 char format_buffer1
[FORMAT_BYTES_MAX
], format_buffer2
[FORMAT_BYTES_MAX
], *buf
;
1536 if (from
!= UINT64_MAX
)
1537 format_bytes(format_buffer1
, sizeof(format_buffer1
), from
);
1538 if (to
!= UINT64_MAX
)
1539 format_bytes(format_buffer2
, sizeof(format_buffer2
), to
);
1541 if (from
!= UINT64_MAX
) {
1542 if (from
== to
|| to
== UINT64_MAX
)
1543 buf
= strdup(format_buffer1
);
1545 buf
= strjoin(format_buffer1
, " ", special_glyph(SPECIAL_GLYPH_ARROW
), " ", format_buffer2
);
1546 } else if (to
!= UINT64_MAX
)
1547 buf
= strjoin(special_glyph(SPECIAL_GLYPH_ARROW
), " ", format_buffer2
);
1556 *ret
= TAKE_PTR(buf
);
1560 static const char *partition_label(const Partition
*p
) {
1564 return p
->new_label
;
1566 if (p
->current_label
)
1567 return p
->current_label
;
1569 return gpt_partition_type_uuid_to_string(p
->type_uuid
);
1572 static int context_dump_partitions(Context
*context
, const char *node
) {
1573 _cleanup_(table_unrefp
) Table
*t
= NULL
;
1574 uint64_t sum_padding
= 0, sum_size
= 0;
1578 t
= table_new("type", "label", "uuid", "file", "node", "offset", "raw size", "size", "raw padding", "padding");
1583 (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);
1585 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 4), 100);
1586 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 5), 100);
1588 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1589 _cleanup_free_
char *size_change
= NULL
, *padding_change
= NULL
, *partname
= NULL
;
1590 char uuid_buffer
[ID128_UUID_STRING_MAX
];
1596 label
= partition_label(p
);
1597 partname
= p
->partno
!= UINT64_MAX
? fdisk_partname(node
, p
->partno
+1) : NULL
;
1599 r
= format_size_change(p
->current_size
, p
->new_size
, &size_change
);
1603 r
= format_size_change(p
->current_padding
, p
->new_padding
, &padding_change
);
1607 if (p
->new_size
!= UINT64_MAX
)
1608 sum_size
+= p
->new_size
;
1609 if (p
->new_padding
!= UINT64_MAX
)
1610 sum_padding
+= p
->new_padding
;
1614 TABLE_STRING
, gpt_partition_type_uuid_to_string_harder(p
->type_uuid
, uuid_buffer
),
1615 TABLE_STRING
, label
?: "-", TABLE_SET_COLOR
, label
? NULL
: ansi_grey(),
1616 TABLE_UUID
, sd_id128_is_null(p
->new_uuid
) ? p
->current_uuid
: p
->new_uuid
,
1617 TABLE_STRING
, p
->definition_path
? basename(p
->definition_path
) : "-", TABLE_SET_COLOR
, p
->definition_path
? NULL
: ansi_grey(),
1618 TABLE_STRING
, partname
?: "no", TABLE_SET_COLOR
, partname
? NULL
: ansi_highlight(),
1619 TABLE_UINT64
, p
->offset
,
1620 TABLE_UINT64
, p
->new_size
,
1621 TABLE_STRING
, size_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_size
> 0 ? ansi_underline() : NULL
,
1622 TABLE_UINT64
, p
->new_padding
,
1623 TABLE_STRING
, padding_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_padding
> 0 ? ansi_underline() : NULL
);
1625 return log_error_errno(r
, "Failed to add row to table: %m");
1628 if (sum_padding
> 0 || sum_size
> 0) {
1629 char s
[FORMAT_BYTES_MAX
];
1632 a
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", format_bytes(s
, sizeof(s
), sum_size
));
1633 b
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", format_bytes(s
, sizeof(s
), sum_padding
));
1648 return log_error_errno(r
, "Failed to add row to table: %m");
1651 r
= table_print(t
, stdout
);
1653 return log_error_errno(r
, "Failed to dump table: %m");
1658 static void context_bar_char_process_partition(
1663 size_t *ret_start
) {
1665 uint64_t from
, to
, total
;
1676 assert(p
->offset
!= UINT64_MAX
);
1677 assert(p
->new_size
!= UINT64_MAX
);
1680 to
= from
+ p
->new_size
;
1682 assert(context
->end
>= context
->start
);
1683 total
= context
->end
- context
->start
;
1685 assert(from
>= context
->start
);
1686 assert(from
<= context
->end
);
1687 x
= (from
- context
->start
) * n
/ total
;
1689 assert(to
>= context
->start
);
1690 assert(to
<= context
->end
);
1691 y
= (to
- context
->start
) * n
/ total
;
1696 for (size_t i
= x
; i
< y
; i
++)
1702 static int partition_hint(const Partition
*p
, const char *node
, char **ret
) {
1703 _cleanup_free_
char *buf
= NULL
;
1704 char ids
[ID128_UUID_STRING_MAX
];
1708 /* Tries really hard to find a suitable description for this partition */
1710 if (p
->definition_path
) {
1711 buf
= strdup(basename(p
->definition_path
));
1715 label
= partition_label(p
);
1716 if (!isempty(label
)) {
1717 buf
= strdup(label
);
1721 if (p
->partno
!= UINT64_MAX
) {
1722 buf
= fdisk_partname(node
, p
->partno
+1);
1726 if (!sd_id128_is_null(p
->new_uuid
))
1728 else if (!sd_id128_is_null(p
->current_uuid
))
1729 id
= p
->current_uuid
;
1733 buf
= strdup(id128_to_uuid_string(id
, ids
));
1739 *ret
= TAKE_PTR(buf
);
1743 static int context_dump_partition_bar(Context
*context
, const char *node
) {
1744 _cleanup_free_ Partition
**bar
= NULL
;
1745 _cleanup_free_
size_t *start_array
= NULL
;
1746 Partition
*p
, *last
= NULL
;
1750 assert_se((c
= columns()) >= 2);
1751 c
-= 2; /* We do not use the leftmost and rightmost character cell */
1753 bar
= new0(Partition
*, c
);
1757 start_array
= new(size_t, context
->n_partitions
);
1761 LIST_FOREACH(partitions
, p
, context
->partitions
)
1762 context_bar_char_process_partition(context
, bar
, c
, p
, start_array
+ j
++);
1766 for (size_t i
= 0; i
< c
; i
++) {
1771 fputs(z
? ansi_green() : ansi_yellow(), stdout
);
1772 fputs(special_glyph(SPECIAL_GLYPH_DARK_SHADE
), stdout
);
1774 fputs(ansi_normal(), stdout
);
1775 fputs(special_glyph(SPECIAL_GLYPH_LIGHT_SHADE
), stdout
);
1781 fputs(ansi_normal(), stdout
);
1784 for (size_t i
= 0; i
< context
->n_partitions
; i
++) {
1785 _cleanup_free_
char **line
= NULL
;
1787 line
= new0(char*, c
);
1792 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1793 _cleanup_free_
char *d
= NULL
;
1796 if (i
< context
->n_partitions
- j
) {
1798 if (line
[start_array
[j
-1]]) {
1801 /* Upgrade final corner to the right with a branch to the right */
1802 e
= startswith(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
1804 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), e
);
1811 d
= strdup(special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
));
1816 } else if (i
== context
->n_partitions
- j
) {
1817 _cleanup_free_
char *hint
= NULL
;
1819 (void) partition_hint(p
, node
, &hint
);
1821 if (streq_ptr(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
)))
1822 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), " ", strna(hint
));
1824 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), " ", strna(hint
));
1831 free_and_replace(line
[start_array
[j
-1]], d
);
1839 fputs(line
[j
], stdout
);
1840 j
+= utf8_console_width(line
[j
]);
1849 for (j
= 0; j
< c
; j
++)
1856 static bool context_changed(const Context
*context
) {
1859 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1863 if (p
->allocated_to_area
)
1866 if (p
->new_size
!= p
->current_size
)
1873 static int context_wipe_partition(Context
*context
, Partition
*p
) {
1874 _cleanup_(blkid_free_probep
) blkid_probe probe
= NULL
;
1879 assert(!PARTITION_EXISTS(p
)); /* Safety check: never wipe existing partitions */
1881 probe
= blkid_new_probe();
1885 assert(p
->offset
!= UINT64_MAX
);
1886 assert(p
->new_size
!= UINT64_MAX
);
1889 r
= blkid_probe_set_device(probe
, fdisk_get_devfd(context
->fdisk_context
), p
->offset
, p
->new_size
);
1891 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to allocate device probe for partition %" PRIu64
".", p
->partno
);
1894 if (blkid_probe_enable_superblocks(probe
, true) < 0 ||
1895 blkid_probe_set_superblocks_flags(probe
, BLKID_SUBLKS_MAGIC
|BLKID_SUBLKS_BADCSUM
) < 0 ||
1896 blkid_probe_enable_partitions(probe
, true) < 0 ||
1897 blkid_probe_set_partitions_flags(probe
, BLKID_PARTS_MAGIC
) < 0)
1898 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to enable superblock and partition probing for partition %" PRIu64
".", p
->partno
);
1902 r
= blkid_do_probe(probe
);
1904 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to probe for file systems.");
1909 if (blkid_do_wipe(probe
, false) < 0)
1910 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to wipe file system signature.");
1913 log_info("Successfully wiped file system signatures from partition %" PRIu64
".", p
->partno
);
1917 static int context_discard_range(Context
*context
, uint64_t offset
, uint64_t size
) {
1922 assert(offset
!= UINT64_MAX
);
1923 assert(size
!= UINT64_MAX
);
1928 assert_se((fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
1930 if (fstat(fd
, &st
) < 0)
1933 if (S_ISREG(st
.st_mode
)) {
1934 if (fallocate(fd
, FALLOC_FL_PUNCH_HOLE
|FALLOC_FL_KEEP_SIZE
, offset
, size
) < 0) {
1935 if (ERRNO_IS_NOT_SUPPORTED(errno
))
1944 if (S_ISBLK(st
.st_mode
)) {
1945 uint64_t range
[2], end
;
1947 range
[0] = round_up_size(offset
, 512);
1949 end
= offset
+ size
;
1950 if (end
<= range
[0])
1953 range
[1] = round_down_size(end
- range
[0], 512);
1957 if (ioctl(fd
, BLKDISCARD
, range
) < 0) {
1958 if (ERRNO_IS_NOT_SUPPORTED(errno
))
1970 static int context_discard_partition(Context
*context
, Partition
*p
) {
1976 assert(p
->offset
!= UINT64_MAX
);
1977 assert(p
->new_size
!= UINT64_MAX
);
1978 assert(!PARTITION_EXISTS(p
)); /* Safety check: never discard existing partitions */
1983 r
= context_discard_range(context
, p
->offset
, p
->new_size
);
1984 if (r
== -EOPNOTSUPP
) {
1985 log_info("Storage does not support discarding, not discarding data in new partition %" PRIu64
".", p
->partno
);
1989 log_info("Partition %" PRIu64
" too short for discard, skipping.", p
->partno
);
1993 return log_error_errno(r
, "Failed to discard data for new partition %" PRIu64
".", p
->partno
);
1995 log_info("Successfully discarded data from partition %" PRIu64
".", p
->partno
);
1999 static int context_discard_gap_after(Context
*context
, Partition
*p
) {
2000 uint64_t gap
, next
= UINT64_MAX
;
2005 assert(!p
|| (p
->offset
!= UINT64_MAX
&& p
->new_size
!= UINT64_MAX
));
2008 gap
= p
->offset
+ p
->new_size
;
2010 gap
= context
->start
;
2012 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2016 assert(q
->offset
!= UINT64_MAX
);
2017 assert(q
->new_size
!= UINT64_MAX
);
2019 if (q
->offset
< gap
)
2022 if (next
== UINT64_MAX
|| q
->offset
< next
)
2026 if (next
== UINT64_MAX
) {
2027 next
= context
->end
;
2029 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
2032 assert(next
>= gap
);
2033 r
= context_discard_range(context
, gap
, next
- gap
);
2034 if (r
== -EOPNOTSUPP
) {
2036 log_info("Storage does not support discarding, not discarding gap after partition %" PRIu64
".", p
->partno
);
2038 log_info("Storage does not support discarding, not discarding gap at beginning of disk.");
2041 if (r
== 0) /* Too short */
2045 return log_error_errno(r
, "Failed to discard gap after partition %" PRIu64
".", p
->partno
);
2047 return log_error_errno(r
, "Failed to discard gap at beginning of disk.");
2051 log_info("Successfully discarded gap after partition %" PRIu64
".", p
->partno
);
2053 log_info("Successfully discarded gap at beginning of disk.");
2058 static int context_wipe_and_discard(Context
*context
, bool from_scratch
) {
2064 /* Wipe and discard the contents of all partitions we are about to create. We skip the discarding if
2065 * we were supposed to start from scratch anyway, as in that case we just discard the whole block
2066 * device in one go early on. */
2068 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2070 if (!p
->allocated_to_area
)
2073 if (!from_scratch
) {
2074 r
= context_discard_partition(context
, p
);
2079 r
= context_wipe_partition(context
, p
);
2083 if (!from_scratch
) {
2084 r
= context_discard_gap_after(context
, p
);
2090 if (!from_scratch
) {
2091 r
= context_discard_gap_after(context
, NULL
);
2099 static int partition_acquire_uuid(Context
*context
, Partition
*p
, sd_id128_t
*ret
) {
2101 sd_id128_t type_uuid
;
2103 } _packed_ plaintext
= {};
2105 unsigned char md
[SHA256_DIGEST_LENGTH
];
2117 /* Calculate a good UUID for the indicated partition. We want a certain degree of reproducibility,
2118 * hence we won't generate the UUIDs randomly. Instead we use a cryptographic hash (precisely:
2119 * HMAC-SHA256) to derive them from a single seed. The seed is generally the machine ID of the
2120 * installation we are processing, but if random behaviour is desired can be random, too. We use the
2121 * seed value as key for the HMAC (since the machine ID is something we generally don't want to leak)
2122 * and the partition type as plaintext. The partition type is suffixed with a counter (only for the
2123 * second and later partition of the same type) if we have more than one partition of the same
2124 * time. Or in other words:
2127 * SEED := /etc/machine-id
2129 * If first partition instance of type TYPE_UUID:
2130 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID)
2132 * For all later partition instances of type TYPE_UUID with INSTANCE being the LE64 encoded instance number:
2133 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID || INSTANCE)
2136 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2140 if (!sd_id128_equal(p
->type_uuid
, q
->type_uuid
))
2146 plaintext
.type_uuid
= p
->type_uuid
;
2147 plaintext
.counter
= htole64(k
);
2149 if (!HMAC(EVP_sha256(),
2150 &context
->seed
, sizeof(context
->seed
),
2151 (const unsigned char*) &plaintext
, k
== 0 ? sizeof(sd_id128_t
) : sizeof(plaintext
),
2153 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "SHA256 calculation failed.");
2155 /* Take the first half, mark it as v4 UUID */
2156 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
2157 result
.id
= id128_make_v4_uuid(result
.id
);
2159 /* Ensure this partition UUID is actually unique, and there's no remaining partition from an earlier run? */
2160 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2164 if (sd_id128_equal(q
->current_uuid
, result
.id
) ||
2165 sd_id128_equal(q
->new_uuid
, result
.id
)) {
2166 log_warning("Partition UUID calculated from seed for partition %" PRIu64
" exists already, reverting to randomized UUID.", p
->partno
);
2168 r
= sd_id128_randomize(&result
.id
);
2170 return log_error_errno(r
, "Failed to generate randomized UUID: %m");
2180 static int partition_acquire_label(Context
*context
, Partition
*p
, char **ret
) {
2181 _cleanup_free_
char *label
= NULL
;
2189 prefix
= gpt_partition_type_uuid_to_string(p
->type_uuid
);
2194 const char *ll
= label
?: prefix
;
2198 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2202 if (streq_ptr(ll
, q
->current_label
) ||
2203 streq_ptr(ll
, q
->new_label
)) {
2212 label
= mfree(label
);
2215 if (asprintf(&label
, "%s-%u", prefix
, ++k
) < 0)
2220 label
= strdup(prefix
);
2225 *ret
= TAKE_PTR(label
);
2229 static int context_acquire_partition_uuids_and_labels(Context
*context
) {
2235 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2236 /* Never touch foreign partitions */
2237 if (PARTITION_IS_FOREIGN(p
)) {
2238 p
->new_uuid
= p
->current_uuid
;
2240 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 */
2252 else if (sd_id128_is_null(p
->new_uuid
)) {
2253 /* Not explicitly set by user! */
2254 r
= partition_acquire_uuid(context
, p
, &p
->new_uuid
);
2259 if (!isempty(p
->current_label
)) {
2261 p
->new_label
= strdup(p
->current_label
); /* never change initialized labels */
2264 } else if (!p
->new_label
) {
2265 /* Not explicitly set by user! */
2267 r
= partition_acquire_label(context
, p
, &p
->new_label
);
2276 static int device_kernel_partitions_supported(int fd
) {
2277 struct loop_info64 info
;
2282 if (fstat(fd
, &st
) < 0)
2283 return log_error_errno(fd
, "Failed to fstat() image file: %m");
2284 if (!S_ISBLK(st
.st_mode
))
2285 return -ENOTBLK
; /* we do not log in this one special case about errors */
2287 if (ioctl(fd
, LOOP_GET_STATUS64
, &info
) < 0) {
2289 if (ERRNO_IS_NOT_SUPPORTED(errno
) || errno
== EINVAL
)
2290 return true; /* not a loopback device, let's assume partition are supported */
2292 return log_error_errno(fd
, "Failed to issue LOOP_GET_STATUS64 on block device: %m");
2295 #if HAVE_VALGRIND_MEMCHECK_H
2296 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
2297 VALGRIND_MAKE_MEM_DEFINED(&info
, sizeof(info
));
2300 return FLAGS_SET(info
.lo_flags
, LO_FLAGS_PARTSCAN
);
2303 static int context_write_partition_table(
2306 bool from_scratch
) {
2308 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*original_table
= NULL
;
2314 if (arg_pretty
> 0 ||
2315 (arg_pretty
< 0 && isatty(STDOUT_FILENO
) > 0)) {
2317 if (context
->n_partitions
== 0)
2318 puts("Empty partition table.");
2320 (void) context_dump_partitions(context
, node
);
2324 (void) context_dump_partition_bar(context
, node
);
2329 if (!from_scratch
&& !context_changed(context
)) {
2330 log_info("No changes.");
2335 log_notice("Refusing to repartition, please re-run with --dry-run=no.");
2339 log_info("Applying changes.");
2342 r
= context_discard_range(context
, 0, context
->total
);
2343 if (r
== -EOPNOTSUPP
)
2344 log_info("Storage does not support discarding, not discarding entire block device data.");
2346 return log_error_errno(r
, "Failed to discard entire block device: %m");
2348 log_info("Discarded entire block device.");
2351 r
= fdisk_get_partitions(context
->fdisk_context
, &original_table
);
2353 return log_error_errno(r
, "Failed to acquire partition table: %m");
2355 /* Wipe fs signatures and discard sectors where the new partitions are going to be placed and in the
2356 * gaps between partitions, just to be sure. */
2357 r
= context_wipe_and_discard(context
, from_scratch
);
2361 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2365 assert(p
->new_size
!= UINT64_MAX
);
2366 assert(p
->offset
!= UINT64_MAX
);
2367 assert(p
->partno
!= UINT64_MAX
);
2369 if (PARTITION_EXISTS(p
)) {
2370 bool changed
= false;
2372 assert(p
->current_partition
);
2374 if (p
->new_size
!= p
->current_size
) {
2375 assert(p
->new_size
>= p
->current_size
);
2376 assert(p
->new_size
% 512 == 0);
2378 r
= fdisk_partition_size_explicit(p
->current_partition
, true);
2380 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
2382 r
= fdisk_partition_set_size(p
->current_partition
, p
->new_size
/ 512);
2384 return log_error_errno(r
, "Failed to grow partition: %m");
2386 log_info("Growing existing partition %" PRIu64
".", p
->partno
);
2390 if (!sd_id128_equal(p
->new_uuid
, p
->current_uuid
)) {
2391 char buf
[ID128_UUID_STRING_MAX
];
2393 assert(!sd_id128_is_null(p
->new_uuid
));
2395 r
= fdisk_partition_set_uuid(p
->current_partition
, id128_to_uuid_string(p
->new_uuid
, buf
));
2397 return log_error_errno(r
, "Failed to set partition UUID: %m");
2399 log_info("Initializing UUID of existing partition %" PRIu64
".", p
->partno
);
2403 if (!streq_ptr(p
->new_label
, p
->current_label
)) {
2404 assert(!isempty(p
->new_label
));
2406 r
= fdisk_partition_set_name(p
->current_partition
, p
->new_label
);
2408 return log_error_errno(r
, "Failed to set partition label: %m");
2410 log_info("Setting partition label of existing partition %" PRIu64
".", p
->partno
);
2415 assert(!PARTITION_IS_FOREIGN(p
)); /* never touch foreign partitions */
2417 r
= fdisk_set_partition(context
->fdisk_context
, p
->partno
, p
->current_partition
);
2419 return log_error_errno(r
, "Failed to update partition: %m");
2422 _cleanup_(fdisk_unref_partitionp
) struct fdisk_partition
*q
= NULL
;
2423 _cleanup_(fdisk_unref_parttypep
) struct fdisk_parttype
*t
= NULL
;
2424 char ids
[ID128_UUID_STRING_MAX
];
2426 assert(!p
->new_partition
);
2427 assert(p
->offset
% 512 == 0);
2428 assert(p
->new_size
% 512 == 0);
2429 assert(!sd_id128_is_null(p
->new_uuid
));
2430 assert(!isempty(p
->new_label
));
2432 t
= fdisk_new_parttype();
2436 r
= fdisk_parttype_set_typestr(t
, id128_to_uuid_string(p
->type_uuid
, ids
));
2438 return log_error_errno(r
, "Failed to initialize partition type: %m");
2440 q
= fdisk_new_partition();
2444 r
= fdisk_partition_set_type(q
, t
);
2446 return log_error_errno(r
, "Failed to set partition type: %m");
2448 r
= fdisk_partition_size_explicit(q
, true);
2450 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
2452 r
= fdisk_partition_set_start(q
, p
->offset
/ 512);
2454 return log_error_errno(r
, "Failed to position partition: %m");
2456 r
= fdisk_partition_set_size(q
, p
->new_size
/ 512);
2458 return log_error_errno(r
, "Failed to grow partition: %m");
2460 r
= fdisk_partition_set_partno(q
, p
->partno
);
2462 return log_error_errno(r
, "Failed to set partition number: %m");
2464 r
= fdisk_partition_set_uuid(q
, id128_to_uuid_string(p
->new_uuid
, ids
));
2466 return log_error_errno(r
, "Failed to set partition UUID: %m");
2468 r
= fdisk_partition_set_name(q
, p
->new_label
);
2470 return log_error_errno(r
, "Failed to set partition label: %m");
2472 log_info("Creating new partition %" PRIu64
".", p
->partno
);
2474 r
= fdisk_add_partition(context
->fdisk_context
, q
, NULL
);
2476 return log_error_errno(r
, "Failed to add partition: %m");
2478 assert(!p
->new_partition
);
2479 p
->new_partition
= TAKE_PTR(q
);
2483 log_info("Writing new partition table.");
2485 r
= fdisk_write_disklabel(context
->fdisk_context
);
2487 return log_error_errno(r
, "Failed to write partition table: %m");
2489 capable
= device_kernel_partitions_supported(fdisk_get_devfd(context
->fdisk_context
));
2490 if (capable
== -ENOTBLK
)
2491 log_debug("Not telling kernel to reread partition table, since we are not operating on a block device.");
2492 else if (capable
< 0)
2494 else if (capable
> 0) {
2495 log_info("Telling kernel to reread partition table.");
2498 r
= fdisk_reread_partition_table(context
->fdisk_context
);
2500 r
= fdisk_reread_changes(context
->fdisk_context
, original_table
);
2502 return log_error_errno(r
, "Failed to reread partition table: %m");
2504 log_notice("Not telling kernel to reread partition table, because selected image does not support kernel partition block devices.");
2506 log_info("All done.");
2511 static int context_read_seed(Context
*context
, const char *root
) {
2516 if (!sd_id128_is_null(context
->seed
))
2519 if (!arg_randomize
) {
2520 _cleanup_close_
int fd
= -1;
2522 fd
= chase_symlinks_and_open("/etc/machine-id", root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
, NULL
);
2524 log_info("No machine ID set, using randomized partition UUIDs.");
2526 return log_error_errno(fd
, "Failed to determine machine ID of image: %m");
2528 r
= id128_read_fd(fd
, ID128_PLAIN
, &context
->seed
);
2529 if (r
== -ENOMEDIUM
)
2530 log_info("No machine ID set, using randomized partition UUIDs.");
2532 return log_error_errno(r
, "Failed to parse machine ID of image: %m");
2538 r
= sd_id128_randomize(&context
->seed
);
2540 return log_error_errno(r
, "Failed to generate randomized seed: %m");
2545 static int context_factory_reset(Context
*context
, bool from_scratch
) {
2552 if (arg_factory_reset
<= 0)
2555 if (from_scratch
) /* Nothing to reset if we start from scratch */
2559 log_notice("Refusing to factory reset, please re-run with --dry-run=no.");
2563 log_info("Applying factory reset.");
2565 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2567 if (!p
->factory_reset
|| !PARTITION_EXISTS(p
))
2570 assert(p
->partno
!= UINT64_MAX
);
2572 log_info("Removing partition %" PRIu64
" for factory reset.", p
->partno
);
2574 r
= fdisk_delete_partition(context
->fdisk_context
, p
->partno
);
2576 return log_error_errno(r
, "Failed to remove partition %" PRIu64
": %m", p
->partno
);
2582 log_info("Factory reset requested, but no partitions to delete found.");
2586 r
= fdisk_write_disklabel(context
->fdisk_context
);
2588 return log_error_errno(r
, "Failed to write disk label: %m");
2590 log_info("Successfully deleted %zu partitions.", n
);
2594 static int context_can_factory_reset(Context
*context
) {
2599 LIST_FOREACH(partitions
, p
, context
->partitions
)
2600 if (p
->factory_reset
&& PARTITION_EXISTS(p
))
2606 static int help(void) {
2607 _cleanup_free_
char *link
= NULL
;
2610 r
= terminal_urlify_man("systemd-repart", "1", &link
);
2614 printf("%s [OPTIONS...] [DEVICE]\n"
2615 "\n%sGrow and add partitions to partition table.%s\n\n"
2616 " -h --help Show this help\n"
2617 " --version Show package version\n"
2618 " --dry-run=BOOL Whether to run dry-run operation\n"
2619 " --empty=MODE One of refuse, allow, require, force, create; controls\n"
2620 " how to handle empty disks lacking partition tables\n"
2621 " --discard=BOOL Whether to discard backing blocks for new partitions\n"
2622 " --pretty=BOOL Whether to show pretty summary before executing operation\n"
2623 " --factory-reset=BOOL Whether to remove data partitions before recreating\n"
2625 " --can-factory-reset Test whether factory reset is defined\n"
2626 " --root=PATH Operate relative to root path\n"
2627 " --definitions=DIR Find partitions in specified directory\n"
2628 " --seed=UUID 128bit seed UUID to derive all UUIDs from\n"
2629 " --size=BYTES Grow loopback file to specified size\n"
2630 "\nSee the %s for details.\n"
2631 , program_invocation_short_name
2632 , ansi_highlight(), ansi_normal()
2639 static int parse_argv(int argc
, char *argv
[]) {
2642 ARG_VERSION
= 0x100,
2647 ARG_CAN_FACTORY_RESET
,
2655 static const struct option options
[] = {
2656 { "help", no_argument
, NULL
, 'h' },
2657 { "version", no_argument
, NULL
, ARG_VERSION
},
2658 { "dry-run", required_argument
, NULL
, ARG_DRY_RUN
},
2659 { "empty", required_argument
, NULL
, ARG_EMPTY
},
2660 { "discard", required_argument
, NULL
, ARG_DISCARD
},
2661 { "factory-reset", required_argument
, NULL
, ARG_FACTORY_RESET
},
2662 { "can-factory-reset", no_argument
, NULL
, ARG_CAN_FACTORY_RESET
},
2663 { "root", required_argument
, NULL
, ARG_ROOT
},
2664 { "seed", required_argument
, NULL
, ARG_SEED
},
2665 { "pretty", required_argument
, NULL
, ARG_PRETTY
},
2666 { "definitions", required_argument
, NULL
, ARG_DEFINITIONS
},
2667 { "size", required_argument
, NULL
, ARG_SIZE
},
2671 int c
, r
, dry_run
= -1;
2676 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
2687 r
= parse_boolean(optarg
);
2689 return log_error_errno(r
, "Failed to parse --dry-run= parameter: %s", optarg
);
2695 if (isempty(optarg
) || streq(optarg
, "refuse"))
2696 arg_empty
= EMPTY_REFUSE
;
2697 else if (streq(optarg
, "allow"))
2698 arg_empty
= EMPTY_ALLOW
;
2699 else if (streq(optarg
, "require"))
2700 arg_empty
= EMPTY_REQUIRE
;
2701 else if (streq(optarg
, "force"))
2702 arg_empty
= EMPTY_FORCE
;
2703 else if (streq(optarg
, "create")) {
2704 arg_empty
= EMPTY_CREATE
;
2707 dry_run
= false; /* Imply --dry-run=no if we create the loopback file
2708 * anew. After all we cannot really break anyone's
2709 * partition tables that way. */
2711 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2712 "Failed to parse --empty= parameter: %s", optarg
);
2716 r
= parse_boolean(optarg
);
2718 return log_error_errno(r
, "Failed to parse --discard= parameter: %s", optarg
);
2723 case ARG_FACTORY_RESET
:
2724 r
= parse_boolean(optarg
);
2726 return log_error_errno(r
, "Failed to parse --factory-reset= parameter: %s", optarg
);
2728 arg_factory_reset
= r
;
2731 case ARG_CAN_FACTORY_RESET
:
2732 arg_can_factory_reset
= true;
2736 r
= parse_path_argument_and_warn(optarg
, false, &arg_root
);
2742 if (isempty(optarg
)) {
2743 arg_seed
= SD_ID128_NULL
;
2744 arg_randomize
= false;
2745 } else if (streq(optarg
, "random"))
2746 arg_randomize
= true;
2748 r
= sd_id128_from_string(optarg
, &arg_seed
);
2750 return log_error_errno(r
, "Failed to parse seed: %s", optarg
);
2752 arg_randomize
= false;
2758 r
= parse_boolean(optarg
);
2760 return log_error_errno(r
, "Failed to parse --pretty= parameter: %s", optarg
);
2765 case ARG_DEFINITIONS
:
2766 r
= parse_path_argument_and_warn(optarg
, false, &arg_definitions
);
2772 uint64_t parsed
, rounded
;
2774 r
= parse_size(optarg
, 1024, &parsed
);
2776 return log_error_errno(r
, "Failed to parse --size= parameter: %s", optarg
);
2778 rounded
= round_up_size(parsed
, 4096);
2780 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too small, refusing.");
2781 if (rounded
== UINT64_MAX
)
2782 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too large, refusing.");
2784 if (rounded
!= parsed
)
2785 log_warning("Specified size is not a multiple of 4096, rounding up automatically. (%" PRIu64
" → %" PRIu64
")",
2796 assert_not_reached("Unhandled option");
2799 if (argc
- optind
> 1)
2800 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2801 "Expected at most one argument, the path to the block device.");
2803 if (arg_factory_reset
> 0 && IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
))
2804 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2805 "Combination of --factory-reset=yes and --empty=force/--empty=require/--empty=create is invalid.");
2807 if (arg_can_factory_reset
)
2808 arg_dry_run
= true; /* When --can-factory-reset is specified we don't make changes, hence
2809 * non-dry-run mode makes no sense. Thus, imply dry run mode so that we
2810 * open things strictly read-only. */
2811 else if (dry_run
>= 0)
2812 arg_dry_run
= dry_run
;
2814 if (arg_empty
== EMPTY_CREATE
&& arg_size
== UINT64_MAX
)
2815 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2816 "If --empty=create is specified, --size= must be specified, too.");
2818 arg_node
= argc
> optind
? argv
[optind
] : NULL
;
2820 if (IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
) && !arg_node
)
2821 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2822 "A path to a device node or loopback file must be specified when --empty=force, --empty=require or --empty=create are used.");
2827 static int parse_proc_cmdline_factory_reset(void) {
2831 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
2834 if (!in_initrd()) /* Never honour kernel command line factory reset request outside of the initrd */
2837 r
= proc_cmdline_get_bool("systemd.factory_reset", &b
);
2839 return log_error_errno(r
, "Failed to parse systemd.factory_reset kernel command line argument: %m");
2841 arg_factory_reset
= b
;
2844 log_notice("Honouring factory reset requested via kernel command line.");
2850 static int parse_efi_variable_factory_reset(void) {
2851 _cleanup_free_
char *value
= NULL
;
2854 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
2857 if (!in_initrd()) /* Never honour EFI variable factory reset request outside of the initrd */
2860 r
= efi_get_variable_string(EFI_VENDOR_SYSTEMD
, "FactoryReset", &value
);
2861 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
2864 return log_error_errno(r
, "Failed to read EFI variable FactoryReset: %m");
2866 r
= parse_boolean(value
);
2868 return log_error_errno(r
, "Failed to parse EFI variable FactoryReset: %m");
2870 arg_factory_reset
= r
;
2872 log_notice("Honouring factory reset requested via EFI variable FactoryReset: %m");
2877 static int remove_efi_variable_factory_reset(void) {
2880 r
= efi_set_variable(EFI_VENDOR_SYSTEMD
, "FactoryReset", NULL
, 0);
2881 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
2884 return log_error_errno(r
, "Failed to remove EFI variable FactoryReset: %m");
2886 log_info("Successfully unset EFI variable FactoryReset.");
2890 static int acquire_root_devno(const char *p
, int mode
, char **ret
, int *ret_fd
) {
2891 _cleanup_close_
int fd
= -1;
2893 dev_t devno
, fd_devno
= (mode_t
) -1;
2904 if (fstat(fd
, &st
) < 0)
2907 if (S_ISREG(st
.st_mode
)) {
2915 *ret_fd
= TAKE_FD(fd
);
2920 if (S_ISBLK(st
.st_mode
))
2921 fd_devno
= devno
= st
.st_rdev
;
2922 else if (S_ISDIR(st
.st_mode
)) {
2925 if (major(devno
) == 0) {
2926 r
= btrfs_get_block_device_fd(fd
, &devno
);
2927 if (r
== -ENOTTY
) /* not btrfs */
2935 /* From dm-crypt to backing partition */
2936 r
= block_get_originating(devno
, &devno
);
2938 log_debug_errno(r
, "Failed to find underlying block device for '%s', ignoring: %m", p
);
2940 /* From partition to whole disk containing it */
2941 r
= block_get_whole_disk(devno
, &devno
);
2943 log_debug_errno(r
, "Failed to find whole disk block device for '%s', ignoring: %m", p
);
2945 r
= device_path_make_canonical(S_IFBLK
, devno
, ret
);
2947 return log_debug_errno(r
, "Failed to determine canonical path for '%s': %m", p
);
2949 /* Only if we still lock at the same block device we can reuse the fd. Otherwise return an
2950 * invalidated fd. */
2951 *ret_fd
= fd_devno
!= (mode_t
) -1 && fd_devno
== devno
? TAKE_FD(fd
) : -1;
2955 static int find_root(char **ret
, int *ret_fd
) {
2963 if (arg_empty
== EMPTY_CREATE
) {
2964 _cleanup_close_
int fd
= -1;
2965 _cleanup_free_
char *s
= NULL
;
2967 s
= strdup(arg_node
);
2971 fd
= open(arg_node
, O_RDONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOFOLLOW
, 0777);
2973 return log_error_errno(errno
, "Failed to create '%s': %m", arg_node
);
2976 *ret_fd
= TAKE_FD(fd
);
2980 r
= acquire_root_devno(arg_node
, O_RDONLY
|O_CLOEXEC
, ret
, ret_fd
);
2982 return log_error_errno(r
, "Failed to determine backing device of %s: %m", arg_node
);
2987 assert(IN_SET(arg_empty
, EMPTY_REFUSE
, EMPTY_ALLOW
));
2989 /* Let's search for the root device. We look for two cases here: first in /, and then in /usr. The
2990 * latter we check for cases where / is a tmpfs and only /usr is an actual persistent block device
2991 * (think: volatile setups) */
2993 FOREACH_STRING(t
, "/", "/usr") {
2994 _cleanup_free_
char *j
= NULL
;
2998 j
= path_join("/sysroot", t
);
3006 r
= acquire_root_devno(p
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, ret
, ret_fd
);
3009 return log_error_errno(r
, "Failed to determine backing device of %s: %m", p
);
3014 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
), "Failed to discover root block device.");
3017 static int resize_backing_fd(const char *node
, int *fd
) {
3018 char buf1
[FORMAT_BYTES_MAX
], buf2
[FORMAT_BYTES_MAX
];
3019 _cleanup_close_
int writable_fd
= -1;
3026 if (arg_size
== UINT64_MAX
) /* Nothing to do */
3030 /* Open the file if we haven't opened it yet. Note that we open it read-only here, just to
3031 * keep a reference to the file we can pass around. */
3032 *fd
= open(node
, O_RDONLY
|O_CLOEXEC
);
3034 return log_error_errno(errno
, "Failed to open '%s' in order to adjust size: %m", node
);
3037 if (fstat(*fd
, &st
) < 0)
3038 return log_error_errno(errno
, "Failed to stat '%s': %m", node
);
3040 r
= stat_verify_regular(&st
);
3042 return log_error_errno(r
, "Specified path '%s' is not a regular file, cannot resize: %m", node
);
3044 assert_se(format_bytes(buf1
, sizeof(buf1
), st
.st_size
));
3045 assert_se(format_bytes(buf2
, sizeof(buf2
), arg_size
));
3047 if ((uint64_t) st
.st_size
>= arg_size
) {
3048 log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)", node
, buf1
, buf2
);
3052 /* The file descriptor is read-only. In order to grow the file we need to have a writable fd. We
3053 * reopen the file for that temporarily. We keep the writable fd only open for this operation though,
3054 * as fdisk can't accept it anyway. */
3056 writable_fd
= fd_reopen(*fd
, O_WRONLY
|O_CLOEXEC
);
3057 if (writable_fd
< 0)
3058 return log_error_errno(writable_fd
, "Failed to reopen backing file '%s' writable: %m", node
);
3061 if (fallocate(writable_fd
, 0, 0, arg_size
) < 0) {
3062 if (!ERRNO_IS_NOT_SUPPORTED(errno
))
3063 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by allocation: %m",
3066 /* Fallback to truncation, if fallocate() is not supported. */
3067 log_debug("Backing file system does not support fallocate(), falling back to ftruncate().");
3069 if (st
.st_size
== 0) /* Likely regular file just created by us */
3070 log_info("Allocated %s for '%s'.", buf2
, node
);
3072 log_info("File '%s' grown from %s to %s by allocation.", node
, buf1
, buf2
);
3078 if (ftruncate(writable_fd
, arg_size
) < 0)
3079 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by truncation: %m",
3082 if (st
.st_size
== 0) /* Likely regular file just created by us */
3083 log_info("Sized '%s' to %s.", node
, buf2
);
3085 log_info("File '%s' grown from %s to %s by truncation.", node
, buf1
, buf2
);
3090 static int run(int argc
, char *argv
[]) {
3091 _cleanup_(context_freep
) Context
* context
= NULL
;
3092 _cleanup_free_
char *node
= NULL
;
3093 _cleanup_close_
int backing_fd
= -1;
3097 log_show_color(true);
3098 log_parse_environment();
3102 /* Default to operation on /sysroot when invoked in the initrd! */
3103 arg_root
= strdup("/sysroot");
3108 r
= parse_argv(argc
, argv
);
3112 r
= parse_proc_cmdline_factory_reset();
3116 r
= parse_efi_variable_factory_reset();
3120 context
= context_new(arg_seed
);
3124 r
= context_read_definitions(context
, arg_definitions
, arg_root
);
3128 if (context
->n_partitions
<= 0 && arg_empty
== EMPTY_REFUSE
) {
3129 log_info("Didn't find any partition definition files, nothing to do.");
3133 r
= find_root(&node
, &backing_fd
);
3137 if (arg_size
!= UINT64_MAX
) {
3138 r
= resize_backing_fd(node
, &backing_fd
);
3143 r
= context_load_partition_table(context
, node
, &backing_fd
);
3144 if (r
== -EHWPOISON
)
3145 return 77; /* Special return value which means "Not GPT, so not doing anything". This isn't
3146 * really an error when called at boot. */
3149 from_scratch
= r
> 0; /* Starting from scratch */
3151 if (arg_can_factory_reset
) {
3152 r
= context_can_factory_reset(context
);
3156 return EXIT_FAILURE
;
3161 r
= context_factory_reset(context
, from_scratch
);
3165 /* We actually did a factory reset! */
3166 r
= remove_efi_variable_factory_reset();
3170 /* Reload the reduced partition table */
3171 context_unload_partition_table(context
);
3172 r
= context_load_partition_table(context
, node
, &backing_fd
);
3178 (void) context_dump_partitions(context
, node
);
3182 r
= context_read_seed(context
, arg_root
);
3186 /* First try to fit new partitions in, dropping by priority until it fits */
3188 if (context_allocate_partitions(context
))
3189 break; /* Success! */
3191 if (!context_drop_one_priority(context
))
3192 return log_error_errno(SYNTHETIC_ERRNO(ENOSPC
),
3193 "Can't fit requested partitions into free space, refusing.");
3196 /* Now assign free space according to the weight logic */
3197 r
= context_grow_partitions(context
);
3201 /* Now calculate where each partition gets placed */
3202 context_place_partitions(context
);
3204 /* Make sure each partition has a unique UUID and unique label */
3205 r
= context_acquire_partition_uuids_and_labels(context
);
3209 r
= context_write_partition_table(context
, node
, from_scratch
);
3216 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);