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 } arg_empty
= EMPTY_REFUSE
;
63 static bool arg_dry_run
= true;
64 static const char *arg_node
= NULL
;
65 static char *arg_root
= NULL
;
66 static char *arg_definitions
= NULL
;
67 static bool arg_discard
= true;
68 static bool arg_can_factory_reset
= false;
69 static int arg_factory_reset
= -1;
70 static sd_id128_t arg_seed
= SD_ID128_NULL
;
71 static bool arg_randomize
= false;
72 static int arg_pretty
= -1;
74 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
75 STATIC_DESTRUCTOR_REGISTER(arg_definitions
, freep
);
77 typedef struct Partition Partition
;
78 typedef struct FreeArea FreeArea
;
79 typedef struct Context Context
;
82 char *definition_path
;
85 sd_id128_t current_uuid
, new_uuid
;
86 char *current_label
, *new_label
;
92 uint32_t weight
, padding_weight
;
94 uint64_t current_size
, new_size
;
95 uint64_t size_min
, size_max
;
97 uint64_t current_padding
, new_padding
;
98 uint64_t padding_min
, padding_max
;
103 struct fdisk_partition
*current_partition
;
104 struct fdisk_partition
*new_partition
;
105 FreeArea
*padding_area
;
106 FreeArea
*allocated_to_area
;
108 LIST_FIELDS(Partition
, partitions
);
111 #define PARTITION_IS_FOREIGN(p) (!(p)->definition_path)
112 #define PARTITION_EXISTS(p) (!!(p)->current_partition)
121 LIST_HEAD(Partition
, partitions
);
124 FreeArea
**free_areas
;
125 size_t n_free_areas
, n_allocated_free_areas
;
127 uint64_t start
, end
, total
;
129 struct fdisk_context
*fdisk_context
;
134 static uint64_t round_down_size(uint64_t v
, uint64_t p
) {
138 static uint64_t round_up_size(uint64_t v
, uint64_t p
) {
140 v
= DIV_ROUND_UP(v
, p
);
142 if (v
> UINT64_MAX
/ p
)
143 return UINT64_MAX
; /* overflow */
148 static Partition
*partition_new(void) {
151 p
= new(Partition
, 1);
158 .current_size
= UINT64_MAX
,
159 .new_size
= UINT64_MAX
,
160 .size_min
= UINT64_MAX
,
161 .size_max
= UINT64_MAX
,
162 .current_padding
= UINT64_MAX
,
163 .new_padding
= UINT64_MAX
,
164 .padding_min
= UINT64_MAX
,
165 .padding_max
= UINT64_MAX
,
166 .partno
= UINT64_MAX
,
167 .offset
= UINT64_MAX
,
173 static Partition
* partition_free(Partition
*p
) {
177 free(p
->current_label
);
179 free(p
->definition_path
);
181 if (p
->current_partition
)
182 fdisk_unref_partition(p
->current_partition
);
183 if (p
->new_partition
)
184 fdisk_unref_partition(p
->new_partition
);
189 static Partition
* partition_unlink_and_free(Context
*context
, Partition
*p
) {
193 LIST_REMOVE(partitions
, context
->partitions
, p
);
195 assert(context
->n_partitions
> 0);
196 context
->n_partitions
--;
198 return partition_free(p
);
201 DEFINE_TRIVIAL_CLEANUP_FUNC(Partition
*, partition_free
);
203 static Context
*context_new(sd_id128_t seed
) {
206 context
= new(Context
, 1);
210 *context
= (Context
) {
220 static void context_free_free_areas(Context
*context
) {
223 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
224 free(context
->free_areas
[i
]);
226 context
->free_areas
= mfree(context
->free_areas
);
227 context
->n_free_areas
= 0;
228 context
->n_allocated_free_areas
= 0;
231 static Context
*context_free(Context
*context
) {
235 while (context
->partitions
)
236 partition_unlink_and_free(context
, context
->partitions
);
237 assert(context
->n_partitions
== 0);
239 context_free_free_areas(context
);
241 if (context
->fdisk_context
)
242 fdisk_unref_context(context
->fdisk_context
);
244 return mfree(context
);
247 DEFINE_TRIVIAL_CLEANUP_FUNC(Context
*, context_free
);
249 static int context_add_free_area(
257 assert(!after
|| !after
->padding_area
);
259 if (!GREEDY_REALLOC(context
->free_areas
, context
->n_allocated_free_areas
, context
->n_free_areas
+ 1))
262 a
= new(FreeArea
, 1);
271 context
->free_areas
[context
->n_free_areas
++] = a
;
274 after
->padding_area
= a
;
279 static bool context_drop_one_priority(Context
*context
) {
280 int32_t priority
= 0;
284 LIST_FOREACH(partitions
, p
, context
->partitions
) {
287 if (p
->priority
< priority
)
289 if (p
->priority
== priority
) {
290 exists
= exists
|| PARTITION_EXISTS(p
);
294 priority
= p
->priority
;
295 exists
= PARTITION_EXISTS(p
);
298 /* Refuse to drop partitions with 0 or negative priorities or partitions of priorities that have at
299 * least one existing priority */
300 if (priority
<= 0 || exists
)
303 LIST_FOREACH(partitions
, p
, context
->partitions
) {
304 if (p
->priority
< priority
)
311 log_info("Can't fit partition %s of priority %" PRIi32
", dropping.", p
->definition_path
, p
->priority
);
317 static uint64_t partition_min_size(const Partition
*p
) {
320 /* Calculate the disk space we really need at minimum for this partition. If the partition already
321 * exists the current size is what we really need. If it doesn't exist yet refuse to allocate less
324 if (PARTITION_IS_FOREIGN(p
)) {
325 /* Don't allow changing size of partitions not managed by us */
326 assert(p
->current_size
!= UINT64_MAX
);
327 return p
->current_size
;
330 sz
= p
->current_size
!= UINT64_MAX
? p
->current_size
: 4096;
331 if (p
->size_min
!= UINT64_MAX
)
332 return MAX(p
->size_min
, sz
);
337 static uint64_t partition_max_size(const Partition
*p
) {
338 /* Calculate how large the partition may become at max. This is generally the configured maximum
339 * size, except when it already exists and is larger than that. In that case it's the existing size,
340 * since we never want to shrink partitions. */
342 if (PARTITION_IS_FOREIGN(p
)) {
343 /* Don't allow changing size of partitions not managed by us */
344 assert(p
->current_size
!= UINT64_MAX
);
345 return p
->current_size
;
348 if (p
->current_size
!= UINT64_MAX
)
349 return MAX(p
->current_size
, p
->size_max
);
354 static uint64_t partition_min_size_with_padding(const Partition
*p
) {
357 /* Calculate the disk space we need for this partition plus any free space coming after it. This
358 * takes user configured padding into account as well as any additional whitespace needed to align
359 * the next partition to 4K again. */
361 sz
= partition_min_size(p
);
363 if (p
->padding_min
!= UINT64_MAX
)
364 sz
+= p
->padding_min
;
366 if (PARTITION_EXISTS(p
)) {
367 /* If the partition wasn't aligned, add extra space so that any we might add will be aligned */
368 assert(p
->offset
!= UINT64_MAX
);
369 return round_up_size(p
->offset
+ sz
, 4096) - p
->offset
;
372 /* If this is a new partition we'll place it aligned, hence we just need to round up the required size here */
373 return round_up_size(sz
, 4096);
376 static uint64_t free_area_available(const FreeArea
*a
) {
379 /* Determines how much of this free area is not allocated yet */
381 assert(a
->size
>= a
->allocated
);
382 return a
->size
- a
->allocated
;
385 static uint64_t free_area_available_for_new_partitions(const FreeArea
*a
) {
388 /* Similar to free_area_available(), but takes into account that the required size and padding of the
389 * preceding partition is honoured. */
391 avail
= free_area_available(a
);
393 uint64_t need
, space
;
395 need
= partition_min_size_with_padding(a
->after
);
397 assert(a
->after
->offset
!= UINT64_MAX
);
398 assert(a
->after
->current_size
!= UINT64_MAX
);
400 space
= round_up_size(a
->after
->offset
+ a
->after
->current_size
, 4096) - a
->after
->offset
+ avail
;
410 static int free_area_compare(FreeArea
*const *a
, FreeArea
*const*b
) {
411 return CMP(free_area_available_for_new_partitions(*a
),
412 free_area_available_for_new_partitions(*b
));
415 static uint64_t charge_size(uint64_t total
, uint64_t amount
) {
418 assert(amount
<= total
);
420 /* Subtract the specified amount from total, rounding up to multiple of 4K if there's room */
421 rounded
= round_up_size(amount
, 4096);
422 if (rounded
>= total
)
425 return total
- rounded
;
428 static uint64_t charge_weight(uint64_t total
, uint64_t amount
) {
429 assert(amount
<= total
);
430 return total
- amount
;
433 static bool context_allocate_partitions(Context
*context
) {
438 /* A simple first-fit algorithm, assuming the array of free areas is sorted by size in decreasing
441 LIST_FOREACH(partitions
, p
, context
->partitions
) {
446 /* Skip partitions we already dropped or that already exist */
447 if (p
->dropped
|| PARTITION_EXISTS(p
))
451 typesafe_qsort(context
->free_areas
, context
->n_free_areas
, free_area_compare
);
453 /* How much do we need to fit? */
454 required
= partition_min_size_with_padding(p
);
455 assert(required
% 4096 == 0);
457 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
458 a
= context
->free_areas
[i
];
460 if (free_area_available_for_new_partitions(a
) >= required
) {
467 return false; /* 😢 Oh no! We can't fit this partition into any free area! */
469 /* Assign the partition to this free area */
470 p
->allocated_to_area
= a
;
472 /* Budget the minimal partition size */
473 a
->allocated
+= required
;
479 static int context_sum_weights(Context
*context
, FreeArea
*a
, uint64_t *ret
) {
480 uint64_t weight_sum
= 0;
487 /* Determine the sum of the weights of all partitions placed in or before the specified free area */
489 LIST_FOREACH(partitions
, p
, context
->partitions
) {
490 if (p
->padding_area
!= a
&& p
->allocated_to_area
!= a
)
493 if (p
->weight
> UINT64_MAX
- weight_sum
)
495 weight_sum
+= p
->weight
;
497 if (p
->padding_weight
> UINT64_MAX
- weight_sum
)
499 weight_sum
+= p
->padding_weight
;
506 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Combined weight of partition exceeds unsigned 64bit range, refusing.");
509 static int scale_by_weight(uint64_t value
, uint64_t weight
, uint64_t weight_sum
, uint64_t *ret
) {
510 assert(weight_sum
>= weight
);
518 if (value
> UINT64_MAX
/ weight
)
519 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Scaling by weight of partition exceeds unsigned 64bit range, refusing.");
521 *ret
= value
* weight
/ weight_sum
;
525 typedef enum GrowPartitionPhase
{
526 /* The first phase: we charge partitions which need more (according to constraints) than their weight-based share. */
529 /* The second phase: we charge partitions which need less (according to constraints) than their weight-based share. */
532 /* The third phase: we distribute what remains among the remaining partitions, according to the weights */
534 } GrowPartitionPhase
;
536 static int context_grow_partitions_phase(
539 GrowPartitionPhase phase
,
541 uint64_t *weight_sum
) {
549 /* Now let's look at the intended weights and adjust them taking the minimum space assignments into
550 * account. i.e. if a partition has a small weight but a high minimum space value set it should not
551 * get any additional room from the left-overs. Similar, if two partitions have the same weight they
552 * should get the same space if possible, even if one has a smaller minimum size than the other. */
553 LIST_FOREACH(partitions
, p
, context
->partitions
) {
555 /* Look only at partitions associated with this free area, i.e. immediately
556 * preceding it, or allocated into it */
557 if (p
->allocated_to_area
!= a
&& p
->padding_area
!= a
)
560 if (p
->new_size
== UINT64_MAX
) {
561 bool charge
= false, try_again
= false;
562 uint64_t share
, rsz
, xsz
;
564 /* Calculate how much this space this partition needs if everyone would get
565 * the weight based share */
566 r
= scale_by_weight(*span
, p
->weight
, *weight_sum
, &share
);
570 rsz
= partition_min_size(p
);
571 xsz
= partition_max_size(p
);
573 if (phase
== PHASE_OVERCHARGE
&& rsz
> share
) {
574 /* This partition needs more than its calculated share. Let's assign
575 * it that, and take this partition out of all calculations and start
579 charge
= try_again
= true;
581 } else if (phase
== PHASE_UNDERCHARGE
&& xsz
!= UINT64_MAX
&& xsz
< share
) {
582 /* This partition accepts less than its calculated
583 * share. Let's assign it that, and take this partition out
584 * of all calculations and start again. */
587 charge
= try_again
= true;
589 } else if (phase
== PHASE_DISTRIBUTE
) {
590 /* This partition can accept its calculated share. Let's
591 * assign it. There's no need to restart things here since
592 * assigning this shouldn't impact the shares of the other
595 if (PARTITION_IS_FOREIGN(p
))
596 /* Never change of foreign partitions (i.e. those we don't manage) */
597 p
->new_size
= p
->current_size
;
599 p
->new_size
= MAX(round_down_size(share
, 4096), rsz
);
605 *span
= charge_size(*span
, p
->new_size
);
606 *weight_sum
= charge_weight(*weight_sum
, p
->weight
);
610 return 0; /* try again */
613 if (p
->new_padding
== UINT64_MAX
) {
614 bool charge
= false, try_again
= false;
617 r
= scale_by_weight(*span
, p
->padding_weight
, *weight_sum
, &share
);
621 if (phase
== PHASE_OVERCHARGE
&& p
->padding_min
!= UINT64_MAX
&& p
->padding_min
> share
) {
622 p
->new_padding
= p
->padding_min
;
623 charge
= try_again
= true;
624 } else if (phase
== PHASE_UNDERCHARGE
&& p
->padding_max
!= UINT64_MAX
&& p
->padding_max
< share
) {
625 p
->new_padding
= p
->padding_max
;
626 charge
= try_again
= true;
627 } else if (phase
== PHASE_DISTRIBUTE
) {
629 p
->new_padding
= round_down_size(share
, 4096);
630 if (p
->padding_min
!= UINT64_MAX
&& p
->new_padding
< p
->padding_min
)
631 p
->new_padding
= p
->padding_min
;
637 *span
= charge_size(*span
, p
->new_padding
);
638 *weight_sum
= charge_weight(*weight_sum
, p
->padding_weight
);
642 return 0; /* try again */
649 static int context_grow_partitions_on_free_area(Context
*context
, FreeArea
*a
) {
650 uint64_t weight_sum
= 0, span
;
656 r
= context_sum_weights(context
, a
, &weight_sum
);
660 /* Let's calculate the total area covered by this free area and the partition before it */
663 assert(a
->after
->offset
!= UINT64_MAX
);
664 assert(a
->after
->current_size
!= UINT64_MAX
);
666 span
+= round_up_size(a
->after
->offset
+ a
->after
->current_size
, 4096) - a
->after
->offset
;
669 GrowPartitionPhase phase
= PHASE_OVERCHARGE
;
671 r
= context_grow_partitions_phase(context
, a
, phase
, &span
, &weight_sum
);
674 if (r
== 0) /* not done yet, re-run this phase */
677 if (phase
== PHASE_OVERCHARGE
)
678 phase
= PHASE_UNDERCHARGE
;
679 else if (phase
== PHASE_UNDERCHARGE
)
680 phase
= PHASE_DISTRIBUTE
;
681 else if (phase
== PHASE_DISTRIBUTE
)
685 /* We still have space left over? Donate to preceding partition if we have one */
686 if (span
> 0 && a
->after
&& !PARTITION_IS_FOREIGN(a
->after
)) {
689 assert(a
->after
->new_size
!= UINT64_MAX
);
690 m
= a
->after
->new_size
+ span
;
692 xsz
= partition_max_size(a
->after
);
693 if (xsz
!= UINT64_MAX
&& m
> xsz
)
696 span
= charge_size(span
, m
- a
->after
->new_size
);
697 a
->after
->new_size
= m
;
700 /* What? Even still some space left (maybe because there was no preceding partition, or it had a
701 * size limit), then let's donate it to whoever wants it. */
705 LIST_FOREACH(partitions
, p
, context
->partitions
) {
708 if (p
->allocated_to_area
!= a
)
711 if (PARTITION_IS_FOREIGN(p
))
714 assert(p
->new_size
!= UINT64_MAX
);
715 m
= p
->new_size
+ span
;
717 xsz
= partition_max_size(a
->after
);
718 if (xsz
!= UINT64_MAX
&& m
> xsz
)
721 span
= charge_size(span
, m
- p
->new_size
);
729 /* Yuck, still no one? Then make it padding */
730 if (span
> 0 && a
->after
) {
731 assert(a
->after
->new_padding
!= UINT64_MAX
);
732 a
->after
->new_padding
+= span
;
738 static int context_grow_partitions(Context
*context
) {
744 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
745 r
= context_grow_partitions_on_free_area(context
, context
->free_areas
[i
]);
750 /* All existing partitions that have no free space after them can't change size */
751 LIST_FOREACH(partitions
, p
, context
->partitions
) {
755 if (!PARTITION_EXISTS(p
) || p
->padding_area
) {
756 /* The algorithm above must have initialized this already */
757 assert(p
->new_size
!= UINT64_MAX
);
761 assert(p
->new_size
== UINT64_MAX
);
762 p
->new_size
= p
->current_size
;
764 assert(p
->new_padding
== UINT64_MAX
);
765 p
->new_padding
= p
->current_padding
;
771 static void context_place_partitions(Context
*context
) {
777 /* Determine next partition number to assign */
778 LIST_FOREACH(partitions
, p
, context
->partitions
) {
779 if (!PARTITION_EXISTS(p
))
782 assert(p
->partno
!= UINT64_MAX
);
783 if (p
->partno
>= partno
)
784 partno
= p
->partno
+ 1;
787 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
788 FreeArea
*a
= context
->free_areas
[i
];
789 uint64_t start
, left
;
792 assert(a
->after
->offset
!= UINT64_MAX
);
793 assert(a
->after
->new_size
!= UINT64_MAX
);
794 assert(a
->after
->new_padding
!= UINT64_MAX
);
796 start
= a
->after
->offset
+ a
->after
->new_size
+ a
->after
->new_padding
;
798 start
= context
->start
;
800 start
= round_up_size(start
, 4096);
803 LIST_FOREACH(partitions
, p
, context
->partitions
) {
804 if (p
->allocated_to_area
!= a
)
808 p
->partno
= partno
++;
810 assert(left
>= p
->new_size
);
811 start
+= p
->new_size
;
814 assert(left
>= p
->new_padding
);
815 start
+= p
->new_padding
;
816 left
-= p
->new_padding
;
821 static int config_parse_type(
823 const char *filename
,
826 unsigned section_line
,
833 sd_id128_t
*type_uuid
= data
;
839 r
= gpt_partition_type_uuid_from_string(rvalue
, type_uuid
);
841 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to parse partition type: %s", rvalue
);
846 static int config_parse_label(
848 const char *filename
,
851 unsigned section_line
,
858 _cleanup_free_ char16_t
*recoded
= NULL
;
865 if (!utf8_is_valid(rvalue
)) {
866 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
867 "Partition label not valid UTF-8, ignoring: %s", rvalue
);
871 recoded
= utf8_to_utf16(rvalue
, strlen(rvalue
));
875 if (char16_strlen(recoded
) > 36) {
876 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
877 "Partition label too long for GPT table, ignoring: %s", rvalue
);
881 r
= free_and_strdup(label
, rvalue
);
888 static int config_parse_weight(
890 const char *filename
,
893 unsigned section_line
,
900 uint32_t *priority
= data
, v
;
906 r
= safe_atou32(rvalue
, &v
);
908 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
909 "Failed to parse weight value, ignoring: %s", rvalue
);
913 if (v
> 1000U*1000U) {
914 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
915 "Weight needs to be in range 0…10000000, ignoring: %" PRIu32
, v
);
923 static int config_parse_size4096(
925 const char *filename
,
928 unsigned section_line
,
935 uint64_t *sz
= data
, parsed
;
941 r
= parse_size(rvalue
, 1024, &parsed
);
943 return log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
944 "Failed to parse size value: %s", rvalue
);
947 *sz
= round_up_size(parsed
, 4096);
949 *sz
= round_down_size(parsed
, 4096);
954 log_syntax(unit
, LOG_NOTICE
, filename
, line
, r
, "Rounded %s= size %" PRIu64
" → %" PRIu64
", a multiple of 4096.", lvalue
, parsed
, *sz
);
959 static int partition_read_definition(Partition
*p
, const char *path
) {
961 ConfigTableItem table
[] = {
962 { "Partition", "Type", config_parse_type
, 0, &p
->type_uuid
},
963 { "Partition", "Label", config_parse_label
, 0, &p
->new_label
},
964 { "Partition", "Priority", config_parse_int32
, 0, &p
->priority
},
965 { "Partition", "Weight", config_parse_weight
, 0, &p
->weight
},
966 { "Partition", "PaddingWeight", config_parse_weight
, 0, &p
->padding_weight
},
967 { "Partition", "SizeMinBytes", config_parse_size4096
, 1, &p
->size_min
},
968 { "Partition", "SizeMaxBytes", config_parse_size4096
, -1, &p
->size_max
},
969 { "Partition", "PaddingMinBytes", config_parse_size4096
, 1, &p
->padding_min
},
970 { "Partition", "PaddingMaxBytes", config_parse_size4096
, -1, &p
->padding_max
},
971 { "Partition", "FactoryReset", config_parse_bool
, 0, &p
->factory_reset
},
976 r
= config_parse(NULL
, path
, NULL
, "Partition\0", config_item_table_lookup
, table
, CONFIG_PARSE_WARN
, p
);
980 if (p
->size_min
!= UINT64_MAX
&& p
->size_max
!= UINT64_MAX
&& p
->size_min
> p
->size_max
)
981 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
982 "SizeMinBytes= larger than SizeMaxBytes=, refusing.");
984 if (p
->padding_min
!= UINT64_MAX
&& p
->padding_max
!= UINT64_MAX
&& p
->padding_min
> p
->padding_max
)
985 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
986 "PaddingMinBytes= larger than PaddingMaxBytes=, refusing.");
988 if (sd_id128_is_null(p
->type_uuid
))
989 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
990 "Type= not defined, refusing.");
995 static int context_read_definitions(
997 const char *directory
,
1000 _cleanup_strv_free_
char **files
= NULL
;
1001 Partition
*last
= NULL
;
1008 r
= conf_files_list_strv(&files
, ".conf", NULL
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, (const char**) STRV_MAKE(directory
));
1010 r
= conf_files_list_strv(&files
, ".conf", root
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, (const char**) CONF_PATHS_STRV("repart.d"));
1012 return log_error_errno(r
, "Failed to enumerate *.conf files: %m");
1014 STRV_FOREACH(f
, files
) {
1015 _cleanup_(partition_freep
) Partition
*p
= NULL
;
1017 p
= partition_new();
1021 p
->definition_path
= strdup(*f
);
1022 if (!p
->definition_path
)
1025 r
= partition_read_definition(p
, *f
);
1029 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, p
);
1031 context
->n_partitions
++;
1037 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_context
*, fdisk_unref_context
);
1038 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_partition
*, fdisk_unref_partition
);
1039 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_parttype
*, fdisk_unref_parttype
);
1040 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_table
*, fdisk_unref_table
);
1042 static int determine_current_padding(
1043 struct fdisk_context
*c
,
1044 struct fdisk_table
*t
,
1045 struct fdisk_partition
*p
,
1048 size_t n_partitions
;
1049 uint64_t offset
, next
= UINT64_MAX
;
1055 if (!fdisk_partition_has_end(p
))
1056 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition has no end!");
1058 offset
= fdisk_partition_get_end(p
);
1059 assert(offset
< UINT64_MAX
/ 512);
1062 n_partitions
= fdisk_table_get_nents(t
);
1063 for (size_t i
= 0; i
< n_partitions
; i
++) {
1064 struct fdisk_partition
*q
;
1067 q
= fdisk_table_get_partition(t
, i
);
1069 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1071 if (fdisk_partition_is_used(q
) <= 0)
1074 if (!fdisk_partition_has_start(q
))
1077 start
= fdisk_partition_get_start(q
);
1078 assert(start
< UINT64_MAX
/ 512);
1081 if (start
>= offset
&& (next
== UINT64_MAX
|| next
> start
))
1085 if (next
== UINT64_MAX
) {
1086 /* No later partition? In that case check the end of the usable area */
1087 next
= fdisk_get_last_lba(c
);
1088 assert(next
< UINT64_MAX
);
1089 next
++; /* The last LBA is one sector before the end */
1091 assert(next
< UINT64_MAX
/ 512);
1095 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
1098 assert(next
>= offset
);
1099 offset
= round_up_size(offset
, 4096);
1100 next
= round_down_size(next
, 4096);
1102 if (next
>= offset
) /* Check again, rounding might have fucked things up */
1103 *ret
= next
- offset
;
1110 static int fdisk_ask_cb(struct fdisk_context
*c
, struct fdisk_ask
*ask
, void *data
) {
1111 _cleanup_free_
char *ids
= NULL
;
1114 if (fdisk_ask_get_type(ask
) != FDISK_ASKTYPE_STRING
)
1117 ids
= new(char, ID128_UUID_STRING_MAX
);
1121 r
= fdisk_ask_string_set_result(ask
, id128_to_uuid_string(*(sd_id128_t
*) data
, ids
));
1129 static int fdisk_set_disklabel_id_by_uuid(struct fdisk_context
*c
, sd_id128_t id
) {
1132 r
= fdisk_set_ask(c
, fdisk_ask_cb
, &id
);
1136 r
= fdisk_set_disklabel_id(c
);
1140 return fdisk_set_ask(c
, NULL
, NULL
);
1143 #define DISK_UUID_TOKEN "disk-uuid"
1145 static int disk_acquire_uuid(Context
*context
, sd_id128_t
*ret
) {
1147 unsigned char md
[SHA256_DIGEST_LENGTH
];
1154 /* Calculate the HMAC-SHA256 of the string "disk-uuid", keyed off the machine ID. We use the machine
1155 * ID as key (and not as cleartext!) since it's the machine ID we don't want to leak. */
1157 if (!HMAC(EVP_sha256(),
1158 &context
->seed
, sizeof(context
->seed
),
1159 (const unsigned char*) DISK_UUID_TOKEN
, strlen(DISK_UUID_TOKEN
),
1161 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "HMAC-SHA256 calculation failed.");
1163 /* Take the first half, mark it as v4 UUID */
1164 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
1165 *ret
= id128_make_v4_uuid(result
.id
);
1169 static int context_load_partition_table(Context
*context
, const char *node
) {
1170 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
1171 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
1172 uint64_t left_boundary
= UINT64_MAX
, first_lba
, last_lba
, nsectors
;
1173 _cleanup_free_
char *disk_uuid_string
= NULL
;
1174 bool from_scratch
= false;
1175 sd_id128_t disk_uuid
;
1176 size_t n_partitions
;
1182 c
= fdisk_new_context();
1186 r
= fdisk_assign_device(c
, node
, arg_dry_run
);
1188 return log_error_errno(r
, "Failed to open device: %m");
1190 /* Tell udev not to interfere while we are processing the device */
1191 if (flock(fdisk_get_devfd(c
), arg_dry_run
? LOCK_SH
: LOCK_EX
) < 0)
1192 return log_error_errno(errno
, "Failed to lock block device: %m");
1194 switch (arg_empty
) {
1197 /* Refuse empty disks, insist on an existing GPT partition table */
1198 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
1199 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has no GPT disk label, not repartitioning.", node
);
1204 /* Require an empty disk, refuse any existing partition table */
1205 r
= fdisk_has_label(c
);
1207 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", node
);
1209 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s already has a disk label, refusing.", node
);
1211 from_scratch
= true;
1215 /* Allow both an empty disk and an existing partition table, but only GPT */
1216 r
= fdisk_has_label(c
);
1218 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", node
);
1220 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
1221 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has non-GPT disk label, not repartitioning.", node
);
1223 from_scratch
= true;
1228 /* Always reinitiaize the disk, don't consider what there was on the disk before */
1229 from_scratch
= true;
1234 r
= fdisk_enable_wipe(c
, true);
1236 return log_error_errno(r
, "Failed to enable wiping of disk signature: %m");
1238 r
= fdisk_create_disklabel(c
, "gpt");
1240 return log_error_errno(r
, "Failed to create GPT disk label: %m");
1242 r
= disk_acquire_uuid(context
, &disk_uuid
);
1244 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
1246 r
= fdisk_set_disklabel_id_by_uuid(c
, disk_uuid
);
1248 return log_error_errno(r
, "Failed to set GPT disk label: %m");
1250 goto add_initial_free_area
;
1253 r
= fdisk_get_disklabel_id(c
, &disk_uuid_string
);
1255 return log_error_errno(r
, "Failed to get current GPT disk label UUID: %m");
1257 r
= sd_id128_from_string(disk_uuid_string
, &disk_uuid
);
1259 return log_error_errno(r
, "Failed to parse current GPT disk label UUID: %m");
1261 if (sd_id128_is_null(disk_uuid
)) {
1262 r
= disk_acquire_uuid(context
, &disk_uuid
);
1264 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
1266 r
= fdisk_set_disklabel_id(c
);
1268 return log_error_errno(r
, "Failed to set GPT disk label: %m");
1271 r
= fdisk_get_partitions(c
, &t
);
1273 return log_error_errno(r
, "Failed to acquire partition table: %m");
1275 n_partitions
= fdisk_table_get_nents(t
);
1276 for (size_t i
= 0; i
< n_partitions
; i
++) {
1277 _cleanup_free_
char *label_copy
= NULL
;
1278 Partition
*pp
, *last
= NULL
;
1279 struct fdisk_partition
*p
;
1280 struct fdisk_parttype
*pt
;
1281 const char *pts
, *ids
, *label
;
1284 sd_id128_t ptid
, id
;
1287 p
= fdisk_table_get_partition(t
, i
);
1289 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1291 if (fdisk_partition_is_used(p
) <= 0)
1294 if (fdisk_partition_has_start(p
) <= 0 ||
1295 fdisk_partition_has_size(p
) <= 0 ||
1296 fdisk_partition_has_partno(p
) <= 0)
1297 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a position, size or number.");
1299 pt
= fdisk_partition_get_type(p
);
1301 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to acquire type of partition: %m");
1303 pts
= fdisk_parttype_get_string(pt
);
1305 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to acquire type of partition as string: %m");
1307 r
= sd_id128_from_string(pts
, &ptid
);
1309 return log_error_errno(r
, "Failed to parse partition type UUID %s: %m", pts
);
1311 ids
= fdisk_partition_get_uuid(p
);
1313 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a UUID.");
1315 r
= sd_id128_from_string(ids
, &id
);
1317 return log_error_errno(r
, "Failed to parse partition UUID %s: %m", ids
);
1319 label
= fdisk_partition_get_name(p
);
1320 if (!isempty(label
)) {
1321 label_copy
= strdup(label
);
1326 sz
= fdisk_partition_get_size(p
);
1327 assert_se(sz
<= UINT64_MAX
/512);
1330 start
= fdisk_partition_get_start(p
);
1331 assert_se(start
<= UINT64_MAX
/512);
1334 partno
= fdisk_partition_get_partno(p
);
1336 if (left_boundary
== UINT64_MAX
|| left_boundary
> start
)
1337 left_boundary
= start
;
1339 /* Assign this existing partition to the first partition of the right type that doesn't have
1340 * an existing one assigned yet. */
1341 LIST_FOREACH(partitions
, pp
, context
->partitions
) {
1344 if (!sd_id128_equal(pp
->type_uuid
, ptid
))
1347 if (!pp
->current_partition
) {
1348 pp
->current_uuid
= id
;
1349 pp
->current_size
= sz
;
1351 pp
->partno
= partno
;
1352 pp
->current_label
= TAKE_PTR(label_copy
);
1354 pp
->current_partition
= p
;
1355 fdisk_ref_partition(p
);
1357 r
= determine_current_padding(c
, t
, p
, &pp
->current_padding
);
1361 if (pp
->current_padding
> 0) {
1362 r
= context_add_free_area(context
, pp
->current_padding
, pp
);
1372 /* If we have no matching definition, create a new one. */
1374 _cleanup_(partition_freep
) Partition
*np
= NULL
;
1376 np
= partition_new();
1380 np
->current_uuid
= id
;
1381 np
->type_uuid
= ptid
;
1382 np
->current_size
= sz
;
1384 np
->partno
= partno
;
1385 np
->current_label
= TAKE_PTR(label_copy
);
1387 np
->current_partition
= p
;
1388 fdisk_ref_partition(p
);
1390 r
= determine_current_padding(c
, t
, p
, &np
->current_padding
);
1394 if (np
->current_padding
> 0) {
1395 r
= context_add_free_area(context
, np
->current_padding
, np
);
1400 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, TAKE_PTR(np
));
1401 context
->n_partitions
++;
1405 add_initial_free_area
:
1406 nsectors
= fdisk_get_nsectors(c
);
1407 assert(nsectors
<= UINT64_MAX
/512);
1410 first_lba
= fdisk_get_first_lba(c
);
1411 assert(first_lba
<= UINT64_MAX
/512);
1414 last_lba
= fdisk_get_last_lba(c
);
1415 assert(last_lba
< UINT64_MAX
);
1417 assert(last_lba
<= UINT64_MAX
/512);
1420 assert(last_lba
>= first_lba
);
1422 if (left_boundary
== UINT64_MAX
) {
1423 /* No partitions at all? Then the whole disk is up for grabs. */
1425 first_lba
= round_up_size(first_lba
, 4096);
1426 last_lba
= round_down_size(last_lba
, 4096);
1428 if (last_lba
> first_lba
) {
1429 r
= context_add_free_area(context
, last_lba
- first_lba
, NULL
);
1434 /* Add space left of first partition */
1435 assert(left_boundary
>= first_lba
);
1437 first_lba
= round_up_size(first_lba
, 4096);
1438 left_boundary
= round_down_size(left_boundary
, 4096);
1439 last_lba
= round_down_size(last_lba
, 4096);
1441 if (left_boundary
> first_lba
) {
1442 r
= context_add_free_area(context
, left_boundary
- first_lba
, NULL
);
1448 context
->start
= first_lba
;
1449 context
->end
= last_lba
;
1450 context
->total
= nsectors
;
1451 context
->fdisk_context
= TAKE_PTR(c
);
1453 return from_scratch
;
1456 static void context_unload_partition_table(Context
*context
) {
1457 Partition
*p
, *next
;
1461 LIST_FOREACH_SAFE(partitions
, p
, next
, context
->partitions
) {
1463 /* Entirely remove partitions that have no configuration */
1464 if (PARTITION_IS_FOREIGN(p
)) {
1465 partition_unlink_and_free(context
, p
);
1469 /* Otherwise drop all data we read off the block device and everything we might have
1470 * calculated based on it */
1473 p
->current_size
= UINT64_MAX
;
1474 p
->new_size
= UINT64_MAX
;
1475 p
->current_padding
= UINT64_MAX
;
1476 p
->new_padding
= UINT64_MAX
;
1477 p
->partno
= UINT64_MAX
;
1478 p
->offset
= UINT64_MAX
;
1480 if (p
->current_partition
) {
1481 fdisk_unref_partition(p
->current_partition
);
1482 p
->current_partition
= NULL
;
1485 if (p
->new_partition
) {
1486 fdisk_unref_partition(p
->new_partition
);
1487 p
->new_partition
= NULL
;
1490 p
->padding_area
= NULL
;
1491 p
->allocated_to_area
= NULL
;
1493 p
->current_uuid
= p
->new_uuid
= SD_ID128_NULL
;
1496 context
->start
= UINT64_MAX
;
1497 context
->end
= UINT64_MAX
;
1498 context
->total
= UINT64_MAX
;
1500 if (context
->fdisk_context
) {
1501 fdisk_unref_context(context
->fdisk_context
);
1502 context
->fdisk_context
= NULL
;
1505 context_free_free_areas(context
);
1508 static int format_size_change(uint64_t from
, uint64_t to
, char **ret
) {
1509 char format_buffer1
[FORMAT_BYTES_MAX
], format_buffer2
[FORMAT_BYTES_MAX
], *buf
;
1511 if (from
!= UINT64_MAX
)
1512 format_bytes(format_buffer1
, sizeof(format_buffer1
), from
);
1513 if (to
!= UINT64_MAX
)
1514 format_bytes(format_buffer2
, sizeof(format_buffer2
), to
);
1516 if (from
!= UINT64_MAX
) {
1517 if (from
== to
|| to
== UINT64_MAX
)
1518 buf
= strdup(format_buffer1
);
1520 buf
= strjoin(format_buffer1
, " ", special_glyph(SPECIAL_GLYPH_ARROW
), " ", format_buffer2
);
1521 } else if (to
!= UINT64_MAX
)
1522 buf
= strjoin(special_glyph(SPECIAL_GLYPH_ARROW
), " ", format_buffer2
);
1531 *ret
= TAKE_PTR(buf
);
1535 static const char *partition_label(const Partition
*p
) {
1539 return p
->new_label
;
1541 if (p
->current_label
)
1542 return p
->current_label
;
1544 return gpt_partition_type_uuid_to_string(p
->type_uuid
);
1547 static int context_dump_partitions(Context
*context
, const char *node
) {
1548 _cleanup_(table_unrefp
) Table
*t
= NULL
;
1549 uint64_t sum_padding
= 0, sum_size
= 0;
1553 t
= table_new("type", "label", "uuid", "file", "node", "offset", "raw size", "size", "raw padding", "padding");
1558 (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);
1560 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 4), 100);
1561 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 5), 100);
1563 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1564 _cleanup_free_
char *size_change
= NULL
, *padding_change
= NULL
, *partname
= NULL
;
1565 char uuid_buffer
[ID128_UUID_STRING_MAX
];
1571 label
= partition_label(p
);
1572 partname
= p
->partno
!= UINT64_MAX
? fdisk_partname(node
, p
->partno
+1) : NULL
;
1574 r
= format_size_change(p
->current_size
, p
->new_size
, &size_change
);
1578 r
= format_size_change(p
->current_padding
, p
->new_padding
, &padding_change
);
1582 if (p
->new_size
!= UINT64_MAX
)
1583 sum_size
+= p
->new_size
;
1584 if (p
->new_padding
!= UINT64_MAX
)
1585 sum_padding
+= p
->new_padding
;
1589 TABLE_STRING
, gpt_partition_type_uuid_to_string_harder(p
->type_uuid
, uuid_buffer
),
1590 TABLE_STRING
, label
?: "-", TABLE_SET_COLOR
, label
? NULL
: ansi_grey(),
1591 TABLE_UUID
, sd_id128_is_null(p
->new_uuid
) ? p
->current_uuid
: p
->new_uuid
,
1592 TABLE_STRING
, p
->definition_path
? basename(p
->definition_path
) : "-", TABLE_SET_COLOR
, p
->definition_path
? NULL
: ansi_grey(),
1593 TABLE_STRING
, partname
?: "no", TABLE_SET_COLOR
, partname
? NULL
: ansi_highlight(),
1594 TABLE_UINT64
, p
->offset
,
1595 TABLE_UINT64
, p
->new_size
,
1596 TABLE_STRING
, size_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_size
> 0 ? ansi_underline() : NULL
,
1597 TABLE_UINT64
, p
->new_padding
,
1598 TABLE_STRING
, padding_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_padding
> 0 ? ansi_underline() : NULL
);
1600 return log_error_errno(r
, "Failed to add row to table: %m");
1603 if (sum_padding
> 0 || sum_size
> 0) {
1604 char s
[FORMAT_BYTES_MAX
];
1607 a
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", format_bytes(s
, sizeof(s
), sum_size
));
1608 b
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", format_bytes(s
, sizeof(s
), sum_padding
));
1623 return log_error_errno(r
, "Failed to add row to table: %m");
1626 r
= table_print(t
, stdout
);
1628 return log_error_errno(r
, "Failed to dump table: %m");
1633 static void context_bar_char_process_partition(
1638 size_t *ret_start
) {
1640 uint64_t from
, to
, total
;
1651 assert(p
->offset
!= UINT64_MAX
);
1652 assert(p
->new_size
!= UINT64_MAX
);
1655 to
= from
+ p
->new_size
;
1657 assert(context
->end
>= context
->start
);
1658 total
= context
->end
- context
->start
;
1660 assert(from
>= context
->start
);
1661 assert(from
<= context
->end
);
1662 x
= (from
- context
->start
) * n
/ total
;
1664 assert(to
>= context
->start
);
1665 assert(to
<= context
->end
);
1666 y
= (to
- context
->start
) * n
/ total
;
1671 for (size_t i
= x
; i
< y
; i
++)
1677 static int partition_hint(const Partition
*p
, const char *node
, char **ret
) {
1678 _cleanup_free_
char *buf
= NULL
;
1679 char ids
[ID128_UUID_STRING_MAX
];
1683 /* Tries really hard to find a suitable description for this partition */
1685 if (p
->definition_path
) {
1686 buf
= strdup(basename(p
->definition_path
));
1690 label
= partition_label(p
);
1691 if (!isempty(label
)) {
1692 buf
= strdup(label
);
1696 if (p
->partno
!= UINT64_MAX
) {
1697 buf
= fdisk_partname(node
, p
->partno
+1);
1701 if (!sd_id128_is_null(p
->new_uuid
))
1703 else if (!sd_id128_is_null(p
->current_uuid
))
1704 id
= p
->current_uuid
;
1708 buf
= strdup(id128_to_uuid_string(id
, ids
));
1714 *ret
= TAKE_PTR(buf
);
1718 static int context_dump_partition_bar(Context
*context
, const char *node
) {
1719 _cleanup_free_ Partition
**bar
= NULL
;
1720 _cleanup_free_
size_t *start_array
= NULL
;
1721 Partition
*p
, *last
= NULL
;
1725 assert((c
= columns()) >= 2);
1726 c
-= 2; /* We do not use the leftmost and rightmost character cell */
1728 bar
= new0(Partition
*, c
);
1732 start_array
= new(size_t, context
->n_partitions
);
1736 LIST_FOREACH(partitions
, p
, context
->partitions
)
1737 context_bar_char_process_partition(context
, bar
, c
, p
, start_array
+ j
++);
1741 for (size_t i
= 0; i
< c
; i
++) {
1746 fputs(z
? ansi_green() : ansi_yellow(), stdout
);
1747 fputs(special_glyph(SPECIAL_GLYPH_DARK_SHADE
), stdout
);
1749 fputs(ansi_normal(), stdout
);
1750 fputs(special_glyph(SPECIAL_GLYPH_LIGHT_SHADE
), stdout
);
1756 fputs(ansi_normal(), stdout
);
1759 for (size_t i
= 0; i
< context
->n_partitions
; i
++) {
1760 _cleanup_free_
char **line
= NULL
;
1762 line
= new0(char*, c
);
1767 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1768 _cleanup_free_
char *d
= NULL
;
1771 if (i
< context
->n_partitions
- j
) {
1773 if (line
[start_array
[j
-1]]) {
1776 /* Upgrade final corner to the right with a branch to the right */
1777 e
= startswith(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
1779 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), e
);
1786 d
= strdup(special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
));
1791 } else if (i
== context
->n_partitions
- j
) {
1792 _cleanup_free_
char *hint
= NULL
;
1794 (void) partition_hint(p
, node
, &hint
);
1796 if (streq_ptr(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
)))
1797 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), " ", strna(hint
));
1799 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), " ", strna(hint
));
1806 free_and_replace(line
[start_array
[j
-1]], d
);
1814 fputs(line
[j
], stdout
);
1815 j
+= utf8_console_width(line
[j
]);
1824 for (j
= 0; j
< c
; j
++)
1831 static bool context_changed(const Context
*context
) {
1834 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1838 if (p
->allocated_to_area
)
1841 if (p
->new_size
!= p
->current_size
)
1848 static int context_wipe_partition(Context
*context
, Partition
*p
) {
1849 _cleanup_(blkid_free_probep
) blkid_probe probe
= NULL
;
1854 assert(!PARTITION_EXISTS(p
)); /* Safety check: never wipe existing partitions */
1856 probe
= blkid_new_probe();
1860 assert(p
->offset
!= UINT64_MAX
);
1861 assert(p
->new_size
!= UINT64_MAX
);
1864 r
= blkid_probe_set_device(probe
, fdisk_get_devfd(context
->fdisk_context
), p
->offset
, p
->new_size
);
1866 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to allocate device probe for partition %" PRIu64
".", p
->partno
);
1869 if (blkid_probe_enable_superblocks(probe
, true) < 0 ||
1870 blkid_probe_set_superblocks_flags(probe
, BLKID_SUBLKS_MAGIC
|BLKID_SUBLKS_BADCSUM
) < 0 ||
1871 blkid_probe_enable_partitions(probe
, true) < 0 ||
1872 blkid_probe_set_partitions_flags(probe
, BLKID_PARTS_MAGIC
) < 0)
1873 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to enable superblock and partition probing for partition %" PRIu64
".", p
->partno
);
1877 r
= blkid_do_probe(probe
);
1879 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to probe for file systems.");
1884 if (blkid_do_wipe(probe
, false) < 0)
1885 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to wipe file system signature.");
1888 log_info("Successfully wiped file system signatures from partition %" PRIu64
".", p
->partno
);
1892 static int context_discard_range(Context
*context
, uint64_t offset
, uint64_t size
) {
1897 assert(offset
!= UINT64_MAX
);
1898 assert(size
!= UINT64_MAX
);
1903 fd
= fdisk_get_devfd(context
->fdisk_context
);
1906 if (fstat(fd
, &st
) < 0)
1909 if (S_ISREG(st
.st_mode
)) {
1910 if (fallocate(fd
, FALLOC_FL_PUNCH_HOLE
|FALLOC_FL_KEEP_SIZE
, offset
, size
) < 0) {
1911 if (ERRNO_IS_NOT_SUPPORTED(errno
))
1920 if (S_ISBLK(st
.st_mode
)) {
1921 uint64_t range
[2], end
;
1923 range
[0] = round_up_size(offset
, 512);
1925 end
= offset
+ size
;
1926 if (end
<= range
[0])
1929 range
[1] = round_down_size(end
- range
[0], 512);
1933 if (ioctl(fd
, BLKDISCARD
, range
) < 0) {
1934 if (ERRNO_IS_NOT_SUPPORTED(errno
))
1946 static int context_discard_partition(Context
*context
, Partition
*p
) {
1952 assert(p
->offset
!= UINT64_MAX
);
1953 assert(p
->new_size
!= UINT64_MAX
);
1954 assert(!PARTITION_EXISTS(p
)); /* Safety check: never discard existing partitions */
1959 r
= context_discard_range(context
, p
->offset
, p
->new_size
);
1960 if (r
== -EOPNOTSUPP
) {
1961 log_info("Storage does not support discarding, not discarding data in new partition %" PRIu64
".", p
->partno
);
1965 log_info("Partition %" PRIu64
" too short for discard, skipping.", p
->partno
);
1969 return log_error_errno(r
, "Failed to discard data for new partition %" PRIu64
".", p
->partno
);
1971 log_info("Successfully discarded data from partition %" PRIu64
".", p
->partno
);
1975 static int context_discard_gap_after(Context
*context
, Partition
*p
) {
1976 uint64_t gap
, next
= UINT64_MAX
;
1981 assert(!p
|| (p
->offset
!= UINT64_MAX
&& p
->new_size
!= UINT64_MAX
));
1984 gap
= p
->offset
+ p
->new_size
;
1986 gap
= context
->start
;
1988 LIST_FOREACH(partitions
, q
, context
->partitions
) {
1992 assert(q
->offset
!= UINT64_MAX
);
1993 assert(q
->new_size
!= UINT64_MAX
);
1995 if (q
->offset
< gap
)
1998 if (next
== UINT64_MAX
|| q
->offset
< next
)
2002 if (next
== UINT64_MAX
) {
2003 next
= context
->end
;
2005 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
2008 assert(next
>= gap
);
2009 r
= context_discard_range(context
, gap
, next
- gap
);
2010 if (r
== -EOPNOTSUPP
) {
2012 log_info("Storage does not support discarding, not discarding gap after partition %" PRIu64
".", p
->partno
);
2014 log_info("Storage does not support discarding, not discarding gap at beginning of disk.");
2017 if (r
== 0) /* Too short */
2021 return log_error_errno(r
, "Failed to discard gap after partition %" PRIu64
".", p
->partno
);
2023 return log_error_errno(r
, "Failed to discard gap at beginning of disk.");
2027 log_info("Successfully discarded gap after partition %" PRIu64
".", p
->partno
);
2029 log_info("Successfully discarded gap at beginning of disk.");
2034 static int context_wipe_and_discard(Context
*context
, bool from_scratch
) {
2040 /* Wipe and discard the contents of all partitions we are about to create. We skip the discarding if
2041 * we were supposed to start from scratch anyway, as in that case we just discard the whole block
2042 * device in one go early on. */
2044 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2046 if (!p
->allocated_to_area
)
2049 if (!from_scratch
) {
2050 r
= context_discard_partition(context
, p
);
2055 r
= context_wipe_partition(context
, p
);
2059 if (!from_scratch
) {
2060 r
= context_discard_gap_after(context
, p
);
2066 if (!from_scratch
) {
2067 r
= context_discard_gap_after(context
, NULL
);
2075 static int partition_acquire_uuid(Context
*context
, Partition
*p
, sd_id128_t
*ret
) {
2077 sd_id128_t type_uuid
;
2079 } _packed_ plaintext
= {};
2081 unsigned char md
[SHA256_DIGEST_LENGTH
];
2093 /* Calculate a good UUID for the indicated partition. We want a certain degree of reproducibility,
2094 * hence we won't generate the UUIDs randomly. Instead we use a cryptographic hash (precisely:
2095 * HMAC-SHA256) to derive them from a single seed. The seed is generally the machine ID of the
2096 * installation we are processing, but if random behaviour is desired can be random, too. We use the
2097 * seed value as key for the HMAC (since the machine ID is something we generally don't want to leak)
2098 * and the partition type as plaintext. The partition type is suffixed with a counter (only for the
2099 * second and later partition of the same type) if we have more than one partition of the same
2100 * time. Or in other words:
2103 * SEED := /etc/machine-id
2105 * If first partition instance of type TYPE_UUID:
2106 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID)
2108 * For all later partition instances of type TYPE_UUID with INSTANCE being the LE64 encoded instance number:
2109 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID || INSTANCE)
2112 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2116 if (!sd_id128_equal(p
->type_uuid
, q
->type_uuid
))
2122 plaintext
.type_uuid
= p
->type_uuid
;
2123 plaintext
.counter
= htole64(k
);
2125 if (!HMAC(EVP_sha256(),
2126 &context
->seed
, sizeof(context
->seed
),
2127 (const unsigned char*) &plaintext
, k
== 0 ? sizeof(sd_id128_t
) : sizeof(plaintext
),
2129 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "SHA256 calculation failed.");
2131 /* Take the first half, mark it as v4 UUID */
2132 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
2133 result
.id
= id128_make_v4_uuid(result
.id
);
2135 /* Ensure this partition UUID is actually unique, and there's no remaining partition from an earlier run? */
2136 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2140 if (sd_id128_equal(q
->current_uuid
, result
.id
) ||
2141 sd_id128_equal(q
->new_uuid
, result
.id
)) {
2142 log_warning("Partition UUID calculated from seed for partition %" PRIu64
" exists already, reverting to randomized UUID.", p
->partno
);
2144 r
= sd_id128_randomize(&result
.id
);
2146 return log_error_errno(r
, "Failed to generate randomized UUID: %m");
2156 static int partition_acquire_label(Context
*context
, Partition
*p
, char **ret
) {
2157 _cleanup_free_
char *label
= NULL
;
2165 prefix
= gpt_partition_type_uuid_to_string(p
->type_uuid
);
2170 const char *ll
= label
?: prefix
;
2174 LIST_FOREACH(partitions
, q
, context
->partitions
) {
2178 if (streq_ptr(ll
, q
->current_label
) ||
2179 streq_ptr(ll
, q
->new_label
)) {
2188 label
= mfree(label
);
2191 if (asprintf(&label
, "%s-%u", prefix
, ++k
) < 0)
2196 label
= strdup(prefix
);
2201 *ret
= TAKE_PTR(label
);
2205 static int context_acquire_partition_uuids_and_labels(Context
*context
) {
2211 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2212 assert(sd_id128_is_null(p
->new_uuid
));
2213 assert(!p
->new_label
);
2215 /* Never touch foreign partitions */
2216 if (PARTITION_IS_FOREIGN(p
)) {
2217 p
->new_uuid
= p
->current_uuid
;
2219 if (p
->current_label
) {
2220 p
->new_label
= strdup(p
->current_label
);
2228 if (!sd_id128_is_null(p
->current_uuid
))
2229 p
->new_uuid
= p
->current_uuid
; /* Never change initialized UUIDs */
2231 r
= partition_acquire_uuid(context
, p
, &p
->new_uuid
);
2236 if (!isempty(p
->current_label
)) {
2237 p
->new_label
= strdup(p
->current_label
); /* never change initialized labels */
2241 r
= partition_acquire_label(context
, p
, &p
->new_label
);
2250 static int device_kernel_partitions_supported(int fd
) {
2251 struct loop_info64 info
;
2256 if (fstat(fd
, &st
) < 0)
2257 return log_error_errno(fd
, "Failed to fstat() image file: %m");
2258 if (!S_ISBLK(st
.st_mode
))
2261 if (ioctl(fd
, LOOP_GET_STATUS64
, &info
) < 0) {
2263 if (ERRNO_IS_NOT_SUPPORTED(errno
) || errno
== EINVAL
)
2264 return true; /* not a loopback device, let's assume partition are supported */
2266 return log_error_errno(fd
, "Failed to issue LOOP_GET_STATUS64 on block device: %m");
2269 #if HAVE_VALGRIND_MEMCHECK_H
2270 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
2271 VALGRIND_MAKE_MEM_DEFINED(&info
, sizeof(info
));
2274 return FLAGS_SET(info
.lo_flags
, LO_FLAGS_PARTSCAN
);
2277 static int context_write_partition_table(
2280 bool from_scratch
) {
2282 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*original_table
= NULL
;
2288 if (arg_pretty
> 0 ||
2289 (arg_pretty
< 0 && isatty(STDOUT_FILENO
) > 0)) {
2291 if (context
->n_partitions
== 0)
2292 puts("Empty partition table.");
2294 (void) context_dump_partitions(context
, node
);
2298 (void) context_dump_partition_bar(context
, node
);
2303 if (!from_scratch
&& !context_changed(context
)) {
2304 log_info("No changes.");
2309 log_notice("Refusing to repartition, please re-run with --dry-run=no.");
2313 log_info("Applying changes.");
2316 r
= context_discard_range(context
, 0, context
->total
);
2317 if (r
== -EOPNOTSUPP
)
2318 log_info("Storage does not support discarding, not discarding entire block device data.");
2320 return log_error_errno(r
, "Failed to discard entire block device: %m");
2322 log_info("Discarded entire block device.");
2325 r
= fdisk_get_partitions(context
->fdisk_context
, &original_table
);
2327 return log_error_errno(r
, "Failed to acquire partition table: %m");
2329 /* Wipe fs signatures and discard sectors where the new partitions are going to be placed and in the
2330 * gaps between partitions, just to be sure. */
2331 r
= context_wipe_and_discard(context
, from_scratch
);
2335 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2339 assert(p
->new_size
!= UINT64_MAX
);
2340 assert(p
->offset
!= UINT64_MAX
);
2341 assert(p
->partno
!= UINT64_MAX
);
2343 if (PARTITION_EXISTS(p
)) {
2344 bool changed
= false;
2346 assert(p
->current_partition
);
2348 if (p
->new_size
!= p
->current_size
) {
2349 assert(p
->new_size
>= p
->current_size
);
2350 assert(p
->new_size
% 512 == 0);
2352 r
= fdisk_partition_size_explicit(p
->current_partition
, true);
2354 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
2356 r
= fdisk_partition_set_size(p
->current_partition
, p
->new_size
/ 512);
2358 return log_error_errno(r
, "Failed to grow partition: %m");
2360 log_info("Growing existing partition %" PRIu64
".", p
->partno
);
2364 if (!sd_id128_equal(p
->new_uuid
, p
->current_uuid
)) {
2365 char buf
[ID128_UUID_STRING_MAX
];
2367 assert(!sd_id128_is_null(p
->new_uuid
));
2369 r
= fdisk_partition_set_uuid(p
->current_partition
, id128_to_uuid_string(p
->new_uuid
, buf
));
2371 return log_error_errno(r
, "Failed to set partition UUID: %m");
2373 log_info("Initializing UUID of existing partition %" PRIu64
".", p
->partno
);
2377 if (!streq_ptr(p
->new_label
, p
->current_label
)) {
2378 assert(!isempty(p
->new_label
));
2380 r
= fdisk_partition_set_name(p
->current_partition
, p
->new_label
);
2382 return log_error_errno(r
, "Failed to set partition label: %m");
2384 log_info("Setting partition label of existing partition %" PRIu64
".", p
->partno
);
2389 assert(!PARTITION_IS_FOREIGN(p
)); /* never touch foreign partitions */
2391 r
= fdisk_set_partition(context
->fdisk_context
, p
->partno
, p
->current_partition
);
2393 return log_error_errno(r
, "Failed to update partition: %m");
2396 _cleanup_(fdisk_unref_partitionp
) struct fdisk_partition
*q
= NULL
;
2397 _cleanup_(fdisk_unref_parttypep
) struct fdisk_parttype
*t
= NULL
;
2398 char ids
[ID128_UUID_STRING_MAX
];
2400 assert(!p
->new_partition
);
2401 assert(p
->offset
% 512 == 0);
2402 assert(p
->new_size
% 512 == 0);
2403 assert(!sd_id128_is_null(p
->new_uuid
));
2404 assert(!isempty(p
->new_label
));
2406 t
= fdisk_new_parttype();
2410 r
= fdisk_parttype_set_typestr(t
, id128_to_uuid_string(p
->type_uuid
, ids
));
2412 return log_error_errno(r
, "Failed to initialize partition type: %m");
2414 q
= fdisk_new_partition();
2418 r
= fdisk_partition_set_type(q
, t
);
2420 return log_error_errno(r
, "Failed to set partition type: %m");
2422 r
= fdisk_partition_size_explicit(q
, true);
2424 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
2426 r
= fdisk_partition_set_start(q
, p
->offset
/ 512);
2428 return log_error_errno(r
, "Failed to position partition: %m");
2430 r
= fdisk_partition_set_size(q
, p
->new_size
/ 512);
2432 return log_error_errno(r
, "Failed to grow partition: %m");
2434 r
= fdisk_partition_set_partno(q
, p
->partno
);
2436 return log_error_errno(r
, "Failed to set partition number: %m");
2438 r
= fdisk_partition_set_uuid(q
, id128_to_uuid_string(p
->new_uuid
, ids
));
2440 return log_error_errno(r
, "Failed to set partition UUID: %m");
2442 r
= fdisk_partition_set_name(q
, p
->new_label
);
2444 return log_error_errno(r
, "Failed to set partition label: %m");
2446 log_info("Creating new partition %" PRIu64
".", p
->partno
);
2448 r
= fdisk_add_partition(context
->fdisk_context
, q
, NULL
);
2450 return log_error_errno(r
, "Failed to add partition: %m");
2452 assert(!p
->new_partition
);
2453 p
->new_partition
= TAKE_PTR(q
);
2457 log_info("Writing new partition table.");
2459 r
= fdisk_write_disklabel(context
->fdisk_context
);
2461 return log_error_errno(r
, "Failed to write partition table: %m");
2463 capable
= device_kernel_partitions_supported(fdisk_get_devfd(context
->fdisk_context
));
2467 log_info("Telling kernel to reread partition table.");
2470 r
= fdisk_reread_partition_table(context
->fdisk_context
);
2472 r
= fdisk_reread_changes(context
->fdisk_context
, original_table
);
2474 return log_error_errno(r
, "Failed to reread partition table: %m");
2476 log_notice("Not telling kernel to reread partition table, because selected image does not support kernel partition block devices.");
2478 log_info("All done.");
2483 static int context_read_seed(Context
*context
, const char *root
) {
2488 if (!sd_id128_is_null(context
->seed
))
2491 if (!arg_randomize
) {
2492 _cleanup_close_
int fd
= -1;
2494 fd
= chase_symlinks_and_open("/etc/machine-id", root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
, NULL
);
2496 log_info("No machine ID set, using randomized partition UUIDs.");
2498 return log_error_errno(fd
, "Failed to determine machine ID of image: %m");
2500 r
= id128_read_fd(fd
, ID128_PLAIN
, &context
->seed
);
2501 if (r
== -ENOMEDIUM
)
2502 log_info("No machine ID set, using randomized partition UUIDs.");
2504 return log_error_errno(r
, "Failed to parse machine ID of image: %m");
2510 r
= sd_id128_randomize(&context
->seed
);
2512 return log_error_errno(r
, "Failed to generate randomized seed: %m");
2517 static int context_factory_reset(Context
*context
, bool from_scratch
) {
2524 if (arg_factory_reset
<= 0)
2527 if (from_scratch
) /* Nothing to reset if we start from scratch */
2531 log_notice("Refusing to factory reset, please re-run with --dry-run=no.");
2535 log_info("Applying factory reset.");
2537 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2539 if (!p
->factory_reset
|| !PARTITION_EXISTS(p
))
2542 assert(p
->partno
!= UINT64_MAX
);
2544 log_info("Removing partition %" PRIu64
" for factory reset.", p
->partno
);
2546 r
= fdisk_delete_partition(context
->fdisk_context
, p
->partno
);
2548 return log_error_errno(r
, "Failed to remove partition %" PRIu64
": %m", p
->partno
);
2554 log_info("Factory reset requested, but no partitions to delete found.");
2558 r
= fdisk_write_disklabel(context
->fdisk_context
);
2560 return log_error_errno(r
, "Failed to write disk label: %m");
2562 log_info("Successfully deleted %zu partitions.", n
);
2566 static int context_can_factory_reset(Context
*context
) {
2571 LIST_FOREACH(partitions
, p
, context
->partitions
)
2572 if (p
->factory_reset
&& PARTITION_EXISTS(p
))
2578 static int help(void) {
2579 _cleanup_free_
char *link
= NULL
;
2582 r
= terminal_urlify_man("systemd-repart", "1", &link
);
2586 printf("%s [OPTIONS...] [DEVICE]\n"
2587 "\n%sGrow and add partitions to partition table.%s\n\n"
2588 " -h --help Show this help\n"
2589 " --version Show package version\n"
2590 " --dry-run=BOOL Whether to run dry-run operation\n"
2591 " --empty=MODE One of refuse, allow, require, force; controls how to\n"
2592 " handle empty disks lacking partition table\n"
2593 " --discard=BOOL Whether to discard backing blocks for new partitions\n"
2594 " --pretty=BOOL Whether to show pretty summary before executing operation\n"
2595 " --factory-reset=BOOL Whether to remove data partitions before recreating\n"
2597 " --can-factory-reset Test whether factory reset is defined\n"
2598 " --root=PATH Operate relative to root path\n"
2599 " --definitions=DIR Find partitions in specified directory\n"
2600 " --seed=UUID 128bit seed UUID to derive all UUIDs from\n"
2601 "\nSee the %s for details.\n"
2602 , program_invocation_short_name
2603 , ansi_highlight(), ansi_normal()
2610 static int parse_argv(int argc
, char *argv
[]) {
2613 ARG_VERSION
= 0x100,
2618 ARG_CAN_FACTORY_RESET
,
2625 static const struct option options
[] = {
2626 { "help", no_argument
, NULL
, 'h' },
2627 { "version", no_argument
, NULL
, ARG_VERSION
},
2628 { "dry-run", required_argument
, NULL
, ARG_DRY_RUN
},
2629 { "empty", required_argument
, NULL
, ARG_EMPTY
},
2630 { "discard", required_argument
, NULL
, ARG_DISCARD
},
2631 { "factory-reset", required_argument
, NULL
, ARG_FACTORY_RESET
},
2632 { "can-factory-reset", no_argument
, NULL
, ARG_CAN_FACTORY_RESET
},
2633 { "root", required_argument
, NULL
, ARG_ROOT
},
2634 { "seed", required_argument
, NULL
, ARG_SEED
},
2635 { "pretty", required_argument
, NULL
, ARG_PRETTY
},
2636 { "definitions", required_argument
, NULL
, ARG_DEFINITIONS
},
2645 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
2656 r
= parse_boolean(optarg
);
2658 return log_error_errno(r
, "Failed to parse --dry-run= parameter: %s", optarg
);
2664 if (isempty(optarg
) || streq(optarg
, "refuse"))
2665 arg_empty
= EMPTY_REFUSE
;
2666 else if (streq(optarg
, "allow"))
2667 arg_empty
= EMPTY_ALLOW
;
2668 else if (streq(optarg
, "require"))
2669 arg_empty
= EMPTY_REQUIRE
;
2670 else if (streq(optarg
, "force"))
2671 arg_empty
= EMPTY_FORCE
;
2673 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2674 "Failed to parse --empty= parameter: %s", optarg
);
2678 r
= parse_boolean(optarg
);
2680 return log_error_errno(r
, "Failed to parse --discard= parameter: %s", optarg
);
2685 case ARG_FACTORY_RESET
:
2686 r
= parse_boolean(optarg
);
2688 return log_error_errno(r
, "Failed to parse --factory-reset= parameter: %s", optarg
);
2690 arg_factory_reset
= r
;
2693 case ARG_CAN_FACTORY_RESET
:
2694 arg_can_factory_reset
= true;
2698 r
= parse_path_argument_and_warn(optarg
, false, &arg_root
);
2704 if (isempty(optarg
)) {
2705 arg_seed
= SD_ID128_NULL
;
2706 arg_randomize
= false;
2707 } else if (streq(optarg
, "random"))
2708 arg_randomize
= true;
2710 r
= sd_id128_from_string(optarg
, &arg_seed
);
2712 return log_error_errno(r
, "Failed to parse seed: %s", optarg
);
2714 arg_randomize
= false;
2720 r
= parse_boolean(optarg
);
2722 return log_error_errno(r
, "Failed to parse --pretty= parameter: %s", optarg
);
2727 case ARG_DEFINITIONS
:
2728 r
= parse_path_argument_and_warn(optarg
, false, &arg_definitions
);
2737 assert_not_reached("Unhandled option");
2740 if (argc
- optind
> 1)
2741 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2742 "Expected at most one argument, the path to the block device.");
2744 if (arg_factory_reset
> 0 && IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
))
2745 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2746 "Combination of --factory-reset=yes and --empty=force/--empty=require is invalid.");
2748 if (arg_can_factory_reset
)
2751 arg_node
= argc
> optind
? argv
[optind
] : NULL
;
2755 static int parse_proc_cmdline_factory_reset(void) {
2759 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
2762 if (!in_initrd()) /* Never honour kernel command line factory reset request outside of the initrd */
2765 r
= proc_cmdline_get_bool("systemd.factory_reset", &b
);
2767 return log_error_errno(r
, "Failed to parse systemd.factory_reset kernel command line argument: %m");
2769 arg_factory_reset
= b
;
2772 log_notice("Honouring factory reset requested via kernel command line.");
2778 static int parse_efi_variable_factory_reset(void) {
2779 _cleanup_free_
char *value
= NULL
;
2782 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
2785 if (!in_initrd()) /* Never honour EFI variable factory reset request outside of the initrd */
2788 r
= efi_get_variable_string(EFI_VENDOR_SYSTEMD
, "FactoryReset", &value
);
2789 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
2792 return log_error_errno(r
, "Failed to read EFI variable FactoryReset: %m");
2794 r
= parse_boolean(value
);
2796 return log_error_errno(r
, "Failed to parse EFI variable FactoryReset: %m");
2798 arg_factory_reset
= r
;
2800 log_notice("Honouring factory reset requested via EFI variable FactoryReset: %m");
2805 static int remove_efi_variable_factory_reset(void) {
2808 r
= efi_set_variable(EFI_VENDOR_SYSTEMD
, "FactoryReset", NULL
, 0);
2809 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
2812 return log_error_errno(r
, "Failed to remove EFI variable FactoryReset: %m");
2814 log_info("Successfully unset EFI variable FactoryReset.");
2818 static int acquire_root_devno(const char *p
, int mode
, char **ret
) {
2819 _cleanup_close_
int fd
= -1;
2828 if (fstat(fd
, &st
) < 0)
2831 if (S_ISREG(st
.st_mode
)) {
2842 if (S_ISBLK(st
.st_mode
))
2844 else if (S_ISDIR(st
.st_mode
)) {
2848 if (major(st
.st_dev
) == 0) {
2849 r
= btrfs_get_block_device_fd(fd
, &devno
);
2850 if (r
== -ENOTTY
) /* not btrfs */
2859 /* From dm-crypt to backing partition */
2860 r
= block_get_originating(devno
, &devno
);
2862 log_debug_errno(r
, "Failed to find underlying block device for '%s', ignoring: %m", p
);
2864 /* From partition to whole disk containing it */
2865 r
= block_get_whole_disk(devno
, &devno
);
2867 log_debug_errno(r
, "Failed to find whole disk block device for '%s', ignoring: %m", p
);
2869 return device_path_make_canonical(S_IFBLK
, devno
, ret
);
2872 static int find_root(char **ret
) {
2877 r
= acquire_root_devno(arg_node
, O_RDONLY
|O_CLOEXEC
, ret
);
2879 return log_error_errno(r
, "Failed to determine backing device of %s: %m", arg_node
);
2884 /* Let's search for the root device. We look for two cases here: first in /, and then in /usr. The
2885 * latter we check for cases where / is a tmpfs and only /usr is an actual persistent block device
2886 * (think: volatile setups) */
2888 FOREACH_STRING(t
, "/", "/usr") {
2889 _cleanup_free_
char *j
= NULL
;
2893 j
= path_join("/sysroot", t
);
2901 r
= acquire_root_devno(p
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, ret
);
2904 return log_error_errno(r
, "Failed to determine backing device of %s: %m", p
);
2909 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
), "Failed to discover root block device.");
2912 static int run(int argc
, char *argv
[]) {
2913 _cleanup_(context_freep
) Context
* context
= NULL
;
2914 _cleanup_free_
char *node
= NULL
;
2918 log_show_color(true);
2919 log_parse_environment();
2923 /* Default to operation on /sysroot when invoked in the initrd! */
2924 arg_root
= strdup("/sysroot");
2929 r
= parse_argv(argc
, argv
);
2933 r
= parse_proc_cmdline_factory_reset();
2937 r
= parse_efi_variable_factory_reset();
2941 context
= context_new(arg_seed
);
2945 r
= context_read_definitions(context
, arg_definitions
, arg_root
);
2949 if (context
->n_partitions
<= 0 && arg_empty
!= EMPTY_FORCE
)
2952 r
= find_root(&node
);
2956 r
= context_load_partition_table(context
, node
);
2957 if (r
== -EHWPOISON
)
2958 return 77; /* Special return value which means "Not GPT, so not doing anything". This isn't
2959 * really an error when called at boot. */
2962 from_scratch
= r
> 0; /* Starting from scratch */
2964 if (arg_can_factory_reset
) {
2965 r
= context_can_factory_reset(context
);
2969 return EXIT_FAILURE
;
2974 r
= context_factory_reset(context
, from_scratch
);
2978 /* We actually did a factory reset! */
2979 r
= remove_efi_variable_factory_reset();
2983 /* Reload the reduced partition table */
2984 context_unload_partition_table(context
);
2985 r
= context_load_partition_table(context
, node
);
2991 (void) context_dump_partitions(context
, node
);
2995 r
= context_read_seed(context
, arg_root
);
2999 /* First try to fit new partitions in, dropping by priority until it fits */
3001 if (context_allocate_partitions(context
))
3002 break; /* Success! */
3004 if (!context_drop_one_priority(context
))
3005 return log_error_errno(SYNTHETIC_ERRNO(ENOSPC
),
3006 "Can't fit requested partitions into free space, refusing.");
3009 /* Now assign free space according to the weight logic */
3010 r
= context_grow_partitions(context
);
3014 /* Now calculate where each partition gets placed */
3015 context_place_partitions(context
);
3017 /* Make sure each partition has a unique UUID and unique label */
3018 r
= context_acquire_partition_uuids_and_labels(context
);
3022 r
= context_write_partition_table(context
, node
, from_scratch
);
3029 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);