]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/partition/repart.c
Merge pull request #15454 from keszybz/codespell-fixes
[thirdparty/systemd.git] / src / partition / repart.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #if HAVE_VALGRIND_MEMCHECK_H
4 #include <valgrind/memcheck.h>
5 #endif
6
7 #include <fcntl.h>
8 #include <getopt.h>
9 #include <libfdisk.h>
10 #include <linux/fs.h>
11 #include <linux/loop.h>
12 #include <sys/file.h>
13 #include <sys/ioctl.h>
14 #include <sys/stat.h>
15
16 #include <openssl/hmac.h>
17 #include <openssl/sha.h>
18
19 #include "sd-id128.h"
20
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"
27 #include "def.h"
28 #include "efivars.h"
29 #include "errno-util.h"
30 #include "fd-util.h"
31 #include "format-table.h"
32 #include "format-util.h"
33 #include "fs-util.h"
34 #include "gpt.h"
35 #include "id128-util.h"
36 #include "list.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"
47 #include "strv.h"
48 #include "terminal-util.h"
49 #include "utf8.h"
50
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. */
55
56 static enum {
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;
62
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;
73
74 STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
75 STATIC_DESTRUCTOR_REGISTER(arg_definitions, freep);
76
77 typedef struct Partition Partition;
78 typedef struct FreeArea FreeArea;
79 typedef struct Context Context;
80
81 struct Partition {
82 char *definition_path;
83
84 sd_id128_t type_uuid;
85 sd_id128_t current_uuid, new_uuid;
86 char *current_label, *new_label;
87
88 bool dropped;
89 bool factory_reset;
90 int32_t priority;
91
92 uint32_t weight, padding_weight;
93
94 uint64_t current_size, new_size;
95 uint64_t size_min, size_max;
96
97 uint64_t current_padding, new_padding;
98 uint64_t padding_min, padding_max;
99
100 uint64_t partno;
101 uint64_t offset;
102
103 struct fdisk_partition *current_partition;
104 struct fdisk_partition *new_partition;
105 FreeArea *padding_area;
106 FreeArea *allocated_to_area;
107
108 LIST_FIELDS(Partition, partitions);
109 };
110
111 #define PARTITION_IS_FOREIGN(p) (!(p)->definition_path)
112 #define PARTITION_EXISTS(p) (!!(p)->current_partition)
113
114 struct FreeArea {
115 Partition *after;
116 uint64_t size;
117 uint64_t allocated;
118 };
119
120 struct Context {
121 LIST_HEAD(Partition, partitions);
122 size_t n_partitions;
123
124 FreeArea **free_areas;
125 size_t n_free_areas, n_allocated_free_areas;
126
127 uint64_t start, end, total;
128
129 struct fdisk_context *fdisk_context;
130
131 sd_id128_t seed;
132 };
133
134 static uint64_t round_down_size(uint64_t v, uint64_t p) {
135 return (v / p) * p;
136 }
137
138 static uint64_t round_up_size(uint64_t v, uint64_t p) {
139
140 v = DIV_ROUND_UP(v, p);
141
142 if (v > UINT64_MAX / p)
143 return UINT64_MAX; /* overflow */
144
145 return v * p;
146 }
147
148 static Partition *partition_new(void) {
149 Partition *p;
150
151 p = new(Partition, 1);
152 if (!p)
153 return NULL;
154
155 *p = (Partition) {
156 .weight = 1000,
157 .padding_weight = 0,
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,
168 };
169
170 return p;
171 }
172
173 static Partition* partition_free(Partition *p) {
174 if (!p)
175 return NULL;
176
177 free(p->current_label);
178 free(p->new_label);
179 free(p->definition_path);
180
181 if (p->current_partition)
182 fdisk_unref_partition(p->current_partition);
183 if (p->new_partition)
184 fdisk_unref_partition(p->new_partition);
185
186 return mfree(p);
187 }
188
189 static Partition* partition_unlink_and_free(Context *context, Partition *p) {
190 if (!p)
191 return NULL;
192
193 LIST_REMOVE(partitions, context->partitions, p);
194
195 assert(context->n_partitions > 0);
196 context->n_partitions--;
197
198 return partition_free(p);
199 }
200
201 DEFINE_TRIVIAL_CLEANUP_FUNC(Partition*, partition_free);
202
203 static Context *context_new(sd_id128_t seed) {
204 Context *context;
205
206 context = new(Context, 1);
207 if (!context)
208 return NULL;
209
210 *context = (Context) {
211 .start = UINT64_MAX,
212 .end = UINT64_MAX,
213 .total = UINT64_MAX,
214 .seed = seed,
215 };
216
217 return context;
218 }
219
220 static void context_free_free_areas(Context *context) {
221 assert(context);
222
223 for (size_t i = 0; i < context->n_free_areas; i++)
224 free(context->free_areas[i]);
225
226 context->free_areas = mfree(context->free_areas);
227 context->n_free_areas = 0;
228 context->n_allocated_free_areas = 0;
229 }
230
231 static Context *context_free(Context *context) {
232 if (!context)
233 return NULL;
234
235 while (context->partitions)
236 partition_unlink_and_free(context, context->partitions);
237 assert(context->n_partitions == 0);
238
239 context_free_free_areas(context);
240
241 if (context->fdisk_context)
242 fdisk_unref_context(context->fdisk_context);
243
244 return mfree(context);
245 }
246
247 DEFINE_TRIVIAL_CLEANUP_FUNC(Context*, context_free);
248
249 static int context_add_free_area(
250 Context *context,
251 uint64_t size,
252 Partition *after) {
253
254 FreeArea *a;
255
256 assert(context);
257 assert(!after || !after->padding_area);
258
259 if (!GREEDY_REALLOC(context->free_areas, context->n_allocated_free_areas, context->n_free_areas + 1))
260 return -ENOMEM;
261
262 a = new(FreeArea, 1);
263 if (!a)
264 return -ENOMEM;
265
266 *a = (FreeArea) {
267 .size = size,
268 .after = after,
269 };
270
271 context->free_areas[context->n_free_areas++] = a;
272
273 if (after)
274 after->padding_area = a;
275
276 return 0;
277 }
278
279 static bool context_drop_one_priority(Context *context) {
280 int32_t priority = 0;
281 Partition *p;
282 bool exists = false;
283
284 LIST_FOREACH(partitions, p, context->partitions) {
285 if (p->dropped)
286 continue;
287 if (p->priority < priority)
288 continue;
289 if (p->priority == priority) {
290 exists = exists || PARTITION_EXISTS(p);
291 continue;
292 }
293
294 priority = p->priority;
295 exists = PARTITION_EXISTS(p);
296 }
297
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)
301 return false;
302
303 LIST_FOREACH(partitions, p, context->partitions) {
304 if (p->priority < priority)
305 continue;
306
307 if (p->dropped)
308 continue;
309
310 p->dropped = true;
311 log_info("Can't fit partition %s of priority %" PRIi32 ", dropping.", p->definition_path, p->priority);
312 }
313
314 return true;
315 }
316
317 static uint64_t partition_min_size(const Partition *p) {
318 uint64_t sz;
319
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
322 * than 4K. */
323
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;
328 }
329
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);
333
334 return sz;
335 }
336
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. */
341
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;
346 }
347
348 if (p->current_size != UINT64_MAX)
349 return MAX(p->current_size, p->size_max);
350
351 return p->size_max;
352 }
353
354 static uint64_t partition_min_size_with_padding(const Partition *p) {
355 uint64_t sz;
356
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. */
360
361 sz = partition_min_size(p);
362
363 if (p->padding_min != UINT64_MAX)
364 sz += p->padding_min;
365
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;
370 }
371
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);
374 }
375
376 static uint64_t free_area_available(const FreeArea *a) {
377 assert(a);
378
379 /* Determines how much of this free area is not allocated yet */
380
381 assert(a->size >= a->allocated);
382 return a->size - a->allocated;
383 }
384
385 static uint64_t free_area_available_for_new_partitions(const FreeArea *a) {
386 uint64_t avail;
387
388 /* Similar to free_area_available(), but takes into account that the required size and padding of the
389 * preceding partition is honoured. */
390
391 avail = free_area_available(a);
392 if (a->after) {
393 uint64_t need, space;
394
395 need = partition_min_size_with_padding(a->after);
396
397 assert(a->after->offset != UINT64_MAX);
398 assert(a->after->current_size != UINT64_MAX);
399
400 space = round_up_size(a->after->offset + a->after->current_size, 4096) - a->after->offset + avail;
401 if (need >= space)
402 return 0;
403
404 return space - need;
405 }
406
407 return avail;
408 }
409
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));
413 }
414
415 static uint64_t charge_size(uint64_t total, uint64_t amount) {
416 uint64_t rounded;
417
418 assert(amount <= total);
419
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)
423 return 0;
424
425 return total - rounded;
426 }
427
428 static uint64_t charge_weight(uint64_t total, uint64_t amount) {
429 assert(amount <= total);
430 return total - amount;
431 }
432
433 static bool context_allocate_partitions(Context *context) {
434 Partition *p;
435
436 assert(context);
437
438 /* A simple first-fit algorithm, assuming the array of free areas is sorted by size in decreasing
439 * order. */
440
441 LIST_FOREACH(partitions, p, context->partitions) {
442 bool fits = false;
443 uint64_t required;
444 FreeArea *a = NULL;
445
446 /* Skip partitions we already dropped or that already exist */
447 if (p->dropped || PARTITION_EXISTS(p))
448 continue;
449
450 /* Sort by size */
451 typesafe_qsort(context->free_areas, context->n_free_areas, free_area_compare);
452
453 /* How much do we need to fit? */
454 required = partition_min_size_with_padding(p);
455 assert(required % 4096 == 0);
456
457 for (size_t i = 0; i < context->n_free_areas; i++) {
458 a = context->free_areas[i];
459
460 if (free_area_available_for_new_partitions(a) >= required) {
461 fits = true;
462 break;
463 }
464 }
465
466 if (!fits)
467 return false; /* 😢 Oh no! We can't fit this partition into any free area! */
468
469 /* Assign the partition to this free area */
470 p->allocated_to_area = a;
471
472 /* Budget the minimal partition size */
473 a->allocated += required;
474 }
475
476 return true;
477 }
478
479 static int context_sum_weights(Context *context, FreeArea *a, uint64_t *ret) {
480 uint64_t weight_sum = 0;
481 Partition *p;
482
483 assert(context);
484 assert(a);
485 assert(ret);
486
487 /* Determine the sum of the weights of all partitions placed in or before the specified free area */
488
489 LIST_FOREACH(partitions, p, context->partitions) {
490 if (p->padding_area != a && p->allocated_to_area != a)
491 continue;
492
493 if (p->weight > UINT64_MAX - weight_sum)
494 goto overflow_sum;
495 weight_sum += p->weight;
496
497 if (p->padding_weight > UINT64_MAX - weight_sum)
498 goto overflow_sum;
499 weight_sum += p->padding_weight;
500 }
501
502 *ret = weight_sum;
503 return 0;
504
505 overflow_sum:
506 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Combined weight of partition exceeds unsigned 64bit range, refusing.");
507 }
508
509 static int scale_by_weight(uint64_t value, uint64_t weight, uint64_t weight_sum, uint64_t *ret) {
510 assert(weight_sum >= weight);
511 assert(ret);
512
513 if (weight == 0) {
514 *ret = 0;
515 return 0;
516 }
517
518 if (value > UINT64_MAX / weight)
519 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Scaling by weight of partition exceeds unsigned 64bit range, refusing.");
520
521 *ret = value * weight / weight_sum;
522 return 0;
523 }
524
525 typedef enum GrowPartitionPhase {
526 /* The first phase: we charge partitions which need more (according to constraints) than their weight-based share. */
527 PHASE_OVERCHARGE,
528
529 /* The second phase: we charge partitions which need less (according to constraints) than their weight-based share. */
530 PHASE_UNDERCHARGE,
531
532 /* The third phase: we distribute what remains among the remaining partitions, according to the weights */
533 PHASE_DISTRIBUTE,
534 } GrowPartitionPhase;
535
536 static int context_grow_partitions_phase(
537 Context *context,
538 FreeArea *a,
539 GrowPartitionPhase phase,
540 uint64_t *span,
541 uint64_t *weight_sum) {
542
543 Partition *p;
544 int r;
545
546 assert(context);
547 assert(a);
548
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) {
554
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)
558 continue;
559
560 if (p->new_size == UINT64_MAX) {
561 bool charge = false, try_again = false;
562 uint64_t share, rsz, xsz;
563
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);
567 if (r < 0)
568 return r;
569
570 rsz = partition_min_size(p);
571 xsz = partition_max_size(p);
572
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
576 * again. */
577
578 p->new_size = rsz;
579 charge = try_again = true;
580
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. */
585
586 p->new_size = xsz;
587 charge = try_again = true;
588
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
593 * partitions. */
594
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;
598 else
599 p->new_size = MAX(round_down_size(share, 4096), rsz);
600
601 charge = true;
602 }
603
604 if (charge) {
605 *span = charge_size(*span, p->new_size);
606 *weight_sum = charge_weight(*weight_sum, p->weight);
607 }
608
609 if (try_again)
610 return 0; /* try again */
611 }
612
613 if (p->new_padding == UINT64_MAX) {
614 bool charge = false, try_again = false;
615 uint64_t share;
616
617 r = scale_by_weight(*span, p->padding_weight, *weight_sum, &share);
618 if (r < 0)
619 return r;
620
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) {
628
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;
632
633 charge = true;
634 }
635
636 if (charge) {
637 *span = charge_size(*span, p->new_padding);
638 *weight_sum = charge_weight(*weight_sum, p->padding_weight);
639 }
640
641 if (try_again)
642 return 0; /* try again */
643 }
644 }
645
646 return 1; /* done */
647 }
648
649 static int context_grow_partitions_on_free_area(Context *context, FreeArea *a) {
650 uint64_t weight_sum = 0, span;
651 int r;
652
653 assert(context);
654 assert(a);
655
656 r = context_sum_weights(context, a, &weight_sum);
657 if (r < 0)
658 return r;
659
660 /* Let's calculate the total area covered by this free area and the partition before it */
661 span = a->size;
662 if (a->after) {
663 assert(a->after->offset != UINT64_MAX);
664 assert(a->after->current_size != UINT64_MAX);
665
666 span += round_up_size(a->after->offset + a->after->current_size, 4096) - a->after->offset;
667 }
668
669 GrowPartitionPhase phase = PHASE_OVERCHARGE;
670 for (;;) {
671 r = context_grow_partitions_phase(context, a, phase, &span, &weight_sum);
672 if (r < 0)
673 return r;
674 if (r == 0) /* not done yet, re-run this phase */
675 continue;
676
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)
682 break;
683 }
684
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)) {
687 uint64_t m, xsz;
688
689 assert(a->after->new_size != UINT64_MAX);
690 m = a->after->new_size + span;
691
692 xsz = partition_max_size(a->after);
693 if (xsz != UINT64_MAX && m > xsz)
694 m = xsz;
695
696 span = charge_size(span, m - a->after->new_size);
697 a->after->new_size = m;
698 }
699
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. */
702 if (span > 0) {
703 Partition *p;
704
705 LIST_FOREACH(partitions, p, context->partitions) {
706 uint64_t m, xsz;
707
708 if (p->allocated_to_area != a)
709 continue;
710
711 if (PARTITION_IS_FOREIGN(p))
712 continue;
713
714 assert(p->new_size != UINT64_MAX);
715 m = p->new_size + span;
716
717 xsz = partition_max_size(a->after);
718 if (xsz != UINT64_MAX && m > xsz)
719 m = xsz;
720
721 span = charge_size(span, m - p->new_size);
722 p->new_size = m;
723
724 if (span == 0)
725 break;
726 }
727 }
728
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;
733 }
734
735 return 0;
736 }
737
738 static int context_grow_partitions(Context *context) {
739 Partition *p;
740 int r;
741
742 assert(context);
743
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]);
746 if (r < 0)
747 return r;
748 }
749
750 /* All existing partitions that have no free space after them can't change size */
751 LIST_FOREACH(partitions, p, context->partitions) {
752 if (p->dropped)
753 continue;
754
755 if (!PARTITION_EXISTS(p) || p->padding_area) {
756 /* The algorithm above must have initialized this already */
757 assert(p->new_size != UINT64_MAX);
758 continue;
759 }
760
761 assert(p->new_size == UINT64_MAX);
762 p->new_size = p->current_size;
763
764 assert(p->new_padding == UINT64_MAX);
765 p->new_padding = p->current_padding;
766 }
767
768 return 0;
769 }
770
771 static void context_place_partitions(Context *context) {
772 uint64_t partno = 0;
773 Partition *p;
774
775 assert(context);
776
777 /* Determine next partition number to assign */
778 LIST_FOREACH(partitions, p, context->partitions) {
779 if (!PARTITION_EXISTS(p))
780 continue;
781
782 assert(p->partno != UINT64_MAX);
783 if (p->partno >= partno)
784 partno = p->partno + 1;
785 }
786
787 for (size_t i = 0; i < context->n_free_areas; i++) {
788 FreeArea *a = context->free_areas[i];
789 uint64_t start, left;
790
791 if (a->after) {
792 assert(a->after->offset != UINT64_MAX);
793 assert(a->after->new_size != UINT64_MAX);
794 assert(a->after->new_padding != UINT64_MAX);
795
796 start = a->after->offset + a->after->new_size + a->after->new_padding;
797 } else
798 start = context->start;
799
800 start = round_up_size(start, 4096);
801 left = a->size;
802
803 LIST_FOREACH(partitions, p, context->partitions) {
804 if (p->allocated_to_area != a)
805 continue;
806
807 p->offset = start;
808 p->partno = partno++;
809
810 assert(left >= p->new_size);
811 start += p->new_size;
812 left -= p->new_size;
813
814 assert(left >= p->new_padding);
815 start += p->new_padding;
816 left -= p->new_padding;
817 }
818 }
819 }
820
821 static int config_parse_type(
822 const char *unit,
823 const char *filename,
824 unsigned line,
825 const char *section,
826 unsigned section_line,
827 const char *lvalue,
828 int ltype,
829 const char *rvalue,
830 void *data,
831 void *userdata) {
832
833 sd_id128_t *type_uuid = data;
834 int r;
835
836 assert(rvalue);
837 assert(type_uuid);
838
839 r = gpt_partition_type_uuid_from_string(rvalue, type_uuid);
840 if (r < 0)
841 return log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse partition type: %s", rvalue);
842
843 return 0;
844 }
845
846 static int config_parse_label(
847 const char *unit,
848 const char *filename,
849 unsigned line,
850 const char *section,
851 unsigned section_line,
852 const char *lvalue,
853 int ltype,
854 const char *rvalue,
855 void *data,
856 void *userdata) {
857
858 _cleanup_free_ char16_t *recoded = NULL;
859 char **label = data;
860 int r;
861
862 assert(rvalue);
863 assert(label);
864
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);
868 return 0;
869 }
870
871 recoded = utf8_to_utf16(rvalue, strlen(rvalue));
872 if (!recoded)
873 return log_oom();
874
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);
878 return 0;
879 }
880
881 r = free_and_strdup(label, rvalue);
882 if (r < 0)
883 return log_oom();
884
885 return 0;
886 }
887
888 static int config_parse_weight(
889 const char *unit,
890 const char *filename,
891 unsigned line,
892 const char *section,
893 unsigned section_line,
894 const char *lvalue,
895 int ltype,
896 const char *rvalue,
897 void *data,
898 void *userdata) {
899
900 uint32_t *priority = data, v;
901 int r;
902
903 assert(rvalue);
904 assert(priority);
905
906 r = safe_atou32(rvalue, &v);
907 if (r < 0) {
908 log_syntax(unit, LOG_WARNING, filename, line, r,
909 "Failed to parse weight value, ignoring: %s", rvalue);
910 return 0;
911 }
912
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);
916 return 0;
917 }
918
919 *priority = v;
920 return 0;
921 }
922
923 static int config_parse_size4096(
924 const char *unit,
925 const char *filename,
926 unsigned line,
927 const char *section,
928 unsigned section_line,
929 const char *lvalue,
930 int ltype,
931 const char *rvalue,
932 void *data,
933 void *userdata) {
934
935 uint64_t *sz = data, parsed;
936 int r;
937
938 assert(rvalue);
939 assert(data);
940
941 r = parse_size(rvalue, 1024, &parsed);
942 if (r < 0)
943 return log_syntax(unit, LOG_WARNING, filename, line, r,
944 "Failed to parse size value: %s", rvalue);
945
946 if (ltype > 0)
947 *sz = round_up_size(parsed, 4096);
948 else if (ltype < 0)
949 *sz = round_down_size(parsed, 4096);
950 else
951 *sz = parsed;
952
953 if (*sz != parsed)
954 log_syntax(unit, LOG_NOTICE, filename, line, r, "Rounded %s= size %" PRIu64 " → %" PRIu64 ", a multiple of 4096.", lvalue, parsed, *sz);
955
956 return 0;
957 }
958
959 static int partition_read_definition(Partition *p, const char *path) {
960
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 },
972 {}
973 };
974 int r;
975
976 r = config_parse(NULL, path, NULL, "Partition\0", config_item_table_lookup, table, CONFIG_PARSE_WARN, p);
977 if (r < 0)
978 return r;
979
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.");
983
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.");
987
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.");
991
992 return 0;
993 }
994
995 static int context_read_definitions(
996 Context *context,
997 const char *directory,
998 const char *root) {
999
1000 _cleanup_strv_free_ char **files = NULL;
1001 Partition *last = NULL;
1002 char **f;
1003 int r;
1004
1005 assert(context);
1006
1007 if (directory)
1008 r = conf_files_list_strv(&files, ".conf", NULL, CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, (const char**) STRV_MAKE(directory));
1009 else
1010 r = conf_files_list_strv(&files, ".conf", root, CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, (const char**) CONF_PATHS_STRV("repart.d"));
1011 if (r < 0)
1012 return log_error_errno(r, "Failed to enumerate *.conf files: %m");
1013
1014 STRV_FOREACH(f, files) {
1015 _cleanup_(partition_freep) Partition *p = NULL;
1016
1017 p = partition_new();
1018 if (!p)
1019 return log_oom();
1020
1021 p->definition_path = strdup(*f);
1022 if (!p->definition_path)
1023 return log_oom();
1024
1025 r = partition_read_definition(p, *f);
1026 if (r < 0)
1027 return r;
1028
1029 LIST_INSERT_AFTER(partitions, context->partitions, last, p);
1030 last = TAKE_PTR(p);
1031 context->n_partitions++;
1032 }
1033
1034 return 0;
1035 }
1036
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);
1041
1042 static int determine_current_padding(
1043 struct fdisk_context *c,
1044 struct fdisk_table *t,
1045 struct fdisk_partition *p,
1046 uint64_t *ret) {
1047
1048 size_t n_partitions;
1049 uint64_t offset, next = UINT64_MAX;
1050
1051 assert(c);
1052 assert(t);
1053 assert(p);
1054
1055 if (!fdisk_partition_has_end(p))
1056 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Partition has no end!");
1057
1058 offset = fdisk_partition_get_end(p);
1059 assert(offset < UINT64_MAX / 512);
1060 offset *= 512;
1061
1062 n_partitions = fdisk_table_get_nents(t);
1063 for (size_t i = 0; i < n_partitions; i++) {
1064 struct fdisk_partition *q;
1065 uint64_t start;
1066
1067 q = fdisk_table_get_partition(t, i);
1068 if (!q)
1069 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read partition metadata: %m");
1070
1071 if (fdisk_partition_is_used(q) <= 0)
1072 continue;
1073
1074 if (!fdisk_partition_has_start(q))
1075 continue;
1076
1077 start = fdisk_partition_get_start(q);
1078 assert(start < UINT64_MAX / 512);
1079 start *= 512;
1080
1081 if (start >= offset && (next == UINT64_MAX || next > start))
1082 next = start;
1083 }
1084
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 */
1090
1091 assert(next < UINT64_MAX / 512);
1092 next *= 512;
1093
1094 if (offset > next)
1095 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Partition end beyond disk end.");
1096 }
1097
1098 assert(next >= offset);
1099 offset = round_up_size(offset, 4096);
1100 next = round_down_size(next, 4096);
1101
1102 if (next >= offset) /* Check again, rounding might have fucked things up */
1103 *ret = next - offset;
1104 else
1105 *ret = 0;
1106
1107 return 0;
1108 }
1109
1110 static int fdisk_ask_cb(struct fdisk_context *c, struct fdisk_ask *ask, void *data) {
1111 _cleanup_free_ char *ids = NULL;
1112 int r;
1113
1114 if (fdisk_ask_get_type(ask) != FDISK_ASKTYPE_STRING)
1115 return -EINVAL;
1116
1117 ids = new(char, ID128_UUID_STRING_MAX);
1118 if (!ids)
1119 return -ENOMEM;
1120
1121 r = fdisk_ask_string_set_result(ask, id128_to_uuid_string(*(sd_id128_t*) data, ids));
1122 if (r < 0)
1123 return r;
1124
1125 TAKE_PTR(ids);
1126 return 0;
1127 }
1128
1129 static int fdisk_set_disklabel_id_by_uuid(struct fdisk_context *c, sd_id128_t id) {
1130 int r;
1131
1132 r = fdisk_set_ask(c, fdisk_ask_cb, &id);
1133 if (r < 0)
1134 return r;
1135
1136 r = fdisk_set_disklabel_id(c);
1137 if (r < 0)
1138 return r;
1139
1140 return fdisk_set_ask(c, NULL, NULL);
1141 }
1142
1143 #define DISK_UUID_TOKEN "disk-uuid"
1144
1145 static int disk_acquire_uuid(Context *context, sd_id128_t *ret) {
1146 union {
1147 unsigned char md[SHA256_DIGEST_LENGTH];
1148 sd_id128_t id;
1149 } result;
1150
1151 assert(context);
1152 assert(ret);
1153
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. */
1156
1157 if (!HMAC(EVP_sha256(),
1158 &context->seed, sizeof(context->seed),
1159 (const unsigned char*) DISK_UUID_TOKEN, strlen(DISK_UUID_TOKEN),
1160 result.md, NULL))
1161 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "HMAC-SHA256 calculation failed.");
1162
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);
1166 return 0;
1167 }
1168
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;
1177 int r;
1178
1179 assert(context);
1180 assert(node);
1181
1182 c = fdisk_new_context();
1183 if (!c)
1184 return log_oom();
1185
1186 r = fdisk_assign_device(c, node, arg_dry_run);
1187 if (r < 0)
1188 return log_error_errno(r, "Failed to open device: %m");
1189
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");
1193
1194 switch (arg_empty) {
1195
1196 case EMPTY_REFUSE:
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);
1200
1201 break;
1202
1203 case EMPTY_REQUIRE:
1204 /* Require an empty disk, refuse any existing partition table */
1205 r = fdisk_has_label(c);
1206 if (r < 0)
1207 return log_error_errno(r, "Failed to determine whether disk %s has a disk label: %m", node);
1208 if (r > 0)
1209 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON), "Disk %s already has a disk label, refusing.", node);
1210
1211 from_scratch = true;
1212 break;
1213
1214 case EMPTY_ALLOW:
1215 /* Allow both an empty disk and an existing partition table, but only GPT */
1216 r = fdisk_has_label(c);
1217 if (r < 0)
1218 return log_error_errno(r, "Failed to determine whether disk %s has a disk label: %m", node);
1219 if (r > 0) {
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);
1222 } else
1223 from_scratch = true;
1224
1225 break;
1226
1227 case EMPTY_FORCE:
1228 /* Always reinitiaize the disk, don't consider what there was on the disk before */
1229 from_scratch = true;
1230 break;
1231 }
1232
1233 if (from_scratch) {
1234 r = fdisk_enable_wipe(c, true);
1235 if (r < 0)
1236 return log_error_errno(r, "Failed to enable wiping of disk signature: %m");
1237
1238 r = fdisk_create_disklabel(c, "gpt");
1239 if (r < 0)
1240 return log_error_errno(r, "Failed to create GPT disk label: %m");
1241
1242 r = disk_acquire_uuid(context, &disk_uuid);
1243 if (r < 0)
1244 return log_error_errno(r, "Failed to acquire disk GPT uuid: %m");
1245
1246 r = fdisk_set_disklabel_id_by_uuid(c, disk_uuid);
1247 if (r < 0)
1248 return log_error_errno(r, "Failed to set GPT disk label: %m");
1249
1250 goto add_initial_free_area;
1251 }
1252
1253 r = fdisk_get_disklabel_id(c, &disk_uuid_string);
1254 if (r < 0)
1255 return log_error_errno(r, "Failed to get current GPT disk label UUID: %m");
1256
1257 r = sd_id128_from_string(disk_uuid_string, &disk_uuid);
1258 if (r < 0)
1259 return log_error_errno(r, "Failed to parse current GPT disk label UUID: %m");
1260
1261 if (sd_id128_is_null(disk_uuid)) {
1262 r = disk_acquire_uuid(context, &disk_uuid);
1263 if (r < 0)
1264 return log_error_errno(r, "Failed to acquire disk GPT uuid: %m");
1265
1266 r = fdisk_set_disklabel_id(c);
1267 if (r < 0)
1268 return log_error_errno(r, "Failed to set GPT disk label: %m");
1269 }
1270
1271 r = fdisk_get_partitions(c, &t);
1272 if (r < 0)
1273 return log_error_errno(r, "Failed to acquire partition table: %m");
1274
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;
1282 uint64_t sz, start;
1283 bool found = false;
1284 sd_id128_t ptid, id;
1285 size_t partno;
1286
1287 p = fdisk_table_get_partition(t, i);
1288 if (!p)
1289 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read partition metadata: %m");
1290
1291 if (fdisk_partition_is_used(p) <= 0)
1292 continue;
1293
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.");
1298
1299 pt = fdisk_partition_get_type(p);
1300 if (!pt)
1301 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to acquire type of partition: %m");
1302
1303 pts = fdisk_parttype_get_string(pt);
1304 if (!pts)
1305 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to acquire type of partition as string: %m");
1306
1307 r = sd_id128_from_string(pts, &ptid);
1308 if (r < 0)
1309 return log_error_errno(r, "Failed to parse partition type UUID %s: %m", pts);
1310
1311 ids = fdisk_partition_get_uuid(p);
1312 if (!ids)
1313 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Found a partition without a UUID.");
1314
1315 r = sd_id128_from_string(ids, &id);
1316 if (r < 0)
1317 return log_error_errno(r, "Failed to parse partition UUID %s: %m", ids);
1318
1319 label = fdisk_partition_get_name(p);
1320 if (!isempty(label)) {
1321 label_copy = strdup(label);
1322 if (!label_copy)
1323 return log_oom();
1324 }
1325
1326 sz = fdisk_partition_get_size(p);
1327 assert_se(sz <= UINT64_MAX/512);
1328 sz *= 512;
1329
1330 start = fdisk_partition_get_start(p);
1331 assert_se(start <= UINT64_MAX/512);
1332 start *= 512;
1333
1334 partno = fdisk_partition_get_partno(p);
1335
1336 if (left_boundary == UINT64_MAX || left_boundary > start)
1337 left_boundary = start;
1338
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) {
1342 last = pp;
1343
1344 if (!sd_id128_equal(pp->type_uuid, ptid))
1345 continue;
1346
1347 if (!pp->current_partition) {
1348 pp->current_uuid = id;
1349 pp->current_size = sz;
1350 pp->offset = start;
1351 pp->partno = partno;
1352 pp->current_label = TAKE_PTR(label_copy);
1353
1354 pp->current_partition = p;
1355 fdisk_ref_partition(p);
1356
1357 r = determine_current_padding(c, t, p, &pp->current_padding);
1358 if (r < 0)
1359 return r;
1360
1361 if (pp->current_padding > 0) {
1362 r = context_add_free_area(context, pp->current_padding, pp);
1363 if (r < 0)
1364 return r;
1365 }
1366
1367 found = true;
1368 break;
1369 }
1370 }
1371
1372 /* If we have no matching definition, create a new one. */
1373 if (!found) {
1374 _cleanup_(partition_freep) Partition *np = NULL;
1375
1376 np = partition_new();
1377 if (!np)
1378 return log_oom();
1379
1380 np->current_uuid = id;
1381 np->type_uuid = ptid;
1382 np->current_size = sz;
1383 np->offset = start;
1384 np->partno = partno;
1385 np->current_label = TAKE_PTR(label_copy);
1386
1387 np->current_partition = p;
1388 fdisk_ref_partition(p);
1389
1390 r = determine_current_padding(c, t, p, &np->current_padding);
1391 if (r < 0)
1392 return r;
1393
1394 if (np->current_padding > 0) {
1395 r = context_add_free_area(context, np->current_padding, np);
1396 if (r < 0)
1397 return r;
1398 }
1399
1400 LIST_INSERT_AFTER(partitions, context->partitions, last, TAKE_PTR(np));
1401 context->n_partitions++;
1402 }
1403 }
1404
1405 add_initial_free_area:
1406 nsectors = fdisk_get_nsectors(c);
1407 assert(nsectors <= UINT64_MAX/512);
1408 nsectors *= 512;
1409
1410 first_lba = fdisk_get_first_lba(c);
1411 assert(first_lba <= UINT64_MAX/512);
1412 first_lba *= 512;
1413
1414 last_lba = fdisk_get_last_lba(c);
1415 assert(last_lba < UINT64_MAX);
1416 last_lba++;
1417 assert(last_lba <= UINT64_MAX/512);
1418 last_lba *= 512;
1419
1420 assert(last_lba >= first_lba);
1421
1422 if (left_boundary == UINT64_MAX) {
1423 /* No partitions at all? Then the whole disk is up for grabs. */
1424
1425 first_lba = round_up_size(first_lba, 4096);
1426 last_lba = round_down_size(last_lba, 4096);
1427
1428 if (last_lba > first_lba) {
1429 r = context_add_free_area(context, last_lba - first_lba, NULL);
1430 if (r < 0)
1431 return r;
1432 }
1433 } else {
1434 /* Add space left of first partition */
1435 assert(left_boundary >= first_lba);
1436
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);
1440
1441 if (left_boundary > first_lba) {
1442 r = context_add_free_area(context, left_boundary - first_lba, NULL);
1443 if (r < 0)
1444 return r;
1445 }
1446 }
1447
1448 context->start = first_lba;
1449 context->end = last_lba;
1450 context->total = nsectors;
1451 context->fdisk_context = TAKE_PTR(c);
1452
1453 return from_scratch;
1454 }
1455
1456 static void context_unload_partition_table(Context *context) {
1457 Partition *p, *next;
1458
1459 assert(context);
1460
1461 LIST_FOREACH_SAFE(partitions, p, next, context->partitions) {
1462
1463 /* Entirely remove partitions that have no configuration */
1464 if (PARTITION_IS_FOREIGN(p)) {
1465 partition_unlink_and_free(context, p);
1466 continue;
1467 }
1468
1469 /* Otherwise drop all data we read off the block device and everything we might have
1470 * calculated based on it */
1471
1472 p->dropped = false;
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;
1479
1480 if (p->current_partition) {
1481 fdisk_unref_partition(p->current_partition);
1482 p->current_partition = NULL;
1483 }
1484
1485 if (p->new_partition) {
1486 fdisk_unref_partition(p->new_partition);
1487 p->new_partition = NULL;
1488 }
1489
1490 p->padding_area = NULL;
1491 p->allocated_to_area = NULL;
1492
1493 p->current_uuid = p->new_uuid = SD_ID128_NULL;
1494 }
1495
1496 context->start = UINT64_MAX;
1497 context->end = UINT64_MAX;
1498 context->total = UINT64_MAX;
1499
1500 if (context->fdisk_context) {
1501 fdisk_unref_context(context->fdisk_context);
1502 context->fdisk_context = NULL;
1503 }
1504
1505 context_free_free_areas(context);
1506 }
1507
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;
1510
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);
1515
1516 if (from != UINT64_MAX) {
1517 if (from == to || to == UINT64_MAX)
1518 buf = strdup(format_buffer1);
1519 else
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);
1523 else {
1524 *ret = NULL;
1525 return 0;
1526 }
1527
1528 if (!buf)
1529 return log_oom();
1530
1531 *ret = TAKE_PTR(buf);
1532 return 1;
1533 }
1534
1535 static const char *partition_label(const Partition *p) {
1536 assert(p);
1537
1538 if (p->new_label)
1539 return p->new_label;
1540
1541 if (p->current_label)
1542 return p->current_label;
1543
1544 return gpt_partition_type_uuid_to_string(p->type_uuid);
1545 }
1546
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;
1550 Partition *p;
1551 int r;
1552
1553 t = table_new("type", "label", "uuid", "file", "node", "offset", "raw size", "size", "raw padding", "padding");
1554 if (!t)
1555 return log_oom();
1556
1557 if (!DEBUG_LOGGING)
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);
1559
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);
1562
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];
1566 const char *label;
1567
1568 if (p->dropped)
1569 continue;
1570
1571 label = partition_label(p);
1572 partname = p->partno != UINT64_MAX ? fdisk_partname(node, p->partno+1) : NULL;
1573
1574 r = format_size_change(p->current_size, p->new_size, &size_change);
1575 if (r < 0)
1576 return r;
1577
1578 r = format_size_change(p->current_padding, p->new_padding, &padding_change);
1579 if (r < 0)
1580 return r;
1581
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;
1586
1587 r = table_add_many(
1588 t,
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);
1599 if (r < 0)
1600 return log_error_errno(r, "Failed to add row to table: %m");
1601 }
1602
1603 if (sum_padding > 0 || sum_size > 0) {
1604 char s[FORMAT_BYTES_MAX];
1605 const char *a, *b;
1606
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));
1609
1610 r = table_add_many(
1611 t,
1612 TABLE_EMPTY,
1613 TABLE_EMPTY,
1614 TABLE_EMPTY,
1615 TABLE_EMPTY,
1616 TABLE_EMPTY,
1617 TABLE_EMPTY,
1618 TABLE_EMPTY,
1619 TABLE_STRING, a,
1620 TABLE_EMPTY,
1621 TABLE_STRING, b);
1622 if (r < 0)
1623 return log_error_errno(r, "Failed to add row to table: %m");
1624 }
1625
1626 r = table_print(t, stdout);
1627 if (r < 0)
1628 return log_error_errno(r, "Failed to dump table: %m");
1629
1630 return 0;
1631 }
1632
1633 static void context_bar_char_process_partition(
1634 Context *context,
1635 Partition *bar[],
1636 size_t n,
1637 Partition *p,
1638 size_t *ret_start) {
1639
1640 uint64_t from, to, total;
1641 size_t x, y;
1642
1643 assert(context);
1644 assert(bar);
1645 assert(n > 0);
1646 assert(p);
1647
1648 if (p->dropped)
1649 return;
1650
1651 assert(p->offset != UINT64_MAX);
1652 assert(p->new_size != UINT64_MAX);
1653
1654 from = p->offset;
1655 to = from + p->new_size;
1656
1657 assert(context->end >= context->start);
1658 total = context->end - context->start;
1659
1660 assert(from >= context->start);
1661 assert(from <= context->end);
1662 x = (from - context->start) * n / total;
1663
1664 assert(to >= context->start);
1665 assert(to <= context->end);
1666 y = (to - context->start) * n / total;
1667
1668 assert(x <= y);
1669 assert(y <= n);
1670
1671 for (size_t i = x; i < y; i++)
1672 bar[i] = p;
1673
1674 *ret_start = x;
1675 }
1676
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];
1680 const char *label;
1681 sd_id128_t id;
1682
1683 /* Tries really hard to find a suitable description for this partition */
1684
1685 if (p->definition_path) {
1686 buf = strdup(basename(p->definition_path));
1687 goto done;
1688 }
1689
1690 label = partition_label(p);
1691 if (!isempty(label)) {
1692 buf = strdup(label);
1693 goto done;
1694 }
1695
1696 if (p->partno != UINT64_MAX) {
1697 buf = fdisk_partname(node, p->partno+1);
1698 goto done;
1699 }
1700
1701 if (!sd_id128_is_null(p->new_uuid))
1702 id = p->new_uuid;
1703 else if (!sd_id128_is_null(p->current_uuid))
1704 id = p->current_uuid;
1705 else
1706 id = p->type_uuid;
1707
1708 buf = strdup(id128_to_uuid_string(id, ids));
1709
1710 done:
1711 if (!buf)
1712 return -ENOMEM;
1713
1714 *ret = TAKE_PTR(buf);
1715 return 0;
1716 }
1717
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;
1722 bool z = false;
1723 size_t c, j = 0;
1724
1725 assert((c = columns()) >= 2);
1726 c -= 2; /* We do not use the leftmost and rightmost character cell */
1727
1728 bar = new0(Partition*, c);
1729 if (!bar)
1730 return log_oom();
1731
1732 start_array = new(size_t, context->n_partitions);
1733 if (!start_array)
1734 return log_oom();
1735
1736 LIST_FOREACH(partitions, p, context->partitions)
1737 context_bar_char_process_partition(context, bar, c, p, start_array + j++);
1738
1739 putc(' ', stdout);
1740
1741 for (size_t i = 0; i < c; i++) {
1742 if (bar[i]) {
1743 if (last != bar[i])
1744 z = !z;
1745
1746 fputs(z ? ansi_green() : ansi_yellow(), stdout);
1747 fputs(special_glyph(SPECIAL_GLYPH_DARK_SHADE), stdout);
1748 } else {
1749 fputs(ansi_normal(), stdout);
1750 fputs(special_glyph(SPECIAL_GLYPH_LIGHT_SHADE), stdout);
1751 }
1752
1753 last = bar[i];
1754 }
1755
1756 fputs(ansi_normal(), stdout);
1757 putc('\n', stdout);
1758
1759 for (size_t i = 0; i < context->n_partitions; i++) {
1760 _cleanup_free_ char **line = NULL;
1761
1762 line = new0(char*, c);
1763 if (!line)
1764 return log_oom();
1765
1766 j = 0;
1767 LIST_FOREACH(partitions, p, context->partitions) {
1768 _cleanup_free_ char *d = NULL;
1769 j++;
1770
1771 if (i < context->n_partitions - j) {
1772
1773 if (line[start_array[j-1]]) {
1774 const char *e;
1775
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));
1778 if (e) {
1779 d = strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH), e);
1780 if (!d)
1781 return log_oom();
1782 }
1783 }
1784
1785 if (!d) {
1786 d = strdup(special_glyph(SPECIAL_GLYPH_TREE_VERTICAL));
1787 if (!d)
1788 return log_oom();
1789 }
1790
1791 } else if (i == context->n_partitions - j) {
1792 _cleanup_free_ char *hint = NULL;
1793
1794 (void) partition_hint(p, node, &hint);
1795
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));
1798 else
1799 d = strjoin(special_glyph(SPECIAL_GLYPH_TREE_RIGHT), " ", strna(hint));
1800
1801 if (!d)
1802 return log_oom();
1803 }
1804
1805 if (d)
1806 free_and_replace(line[start_array[j-1]], d);
1807 }
1808
1809 putc(' ', stdout);
1810
1811 j = 0;
1812 while (j < c) {
1813 if (line[j]) {
1814 fputs(line[j], stdout);
1815 j += utf8_console_width(line[j]);
1816 } else {
1817 putc(' ', stdout);
1818 j++;
1819 }
1820 }
1821
1822 putc('\n', stdout);
1823
1824 for (j = 0; j < c; j++)
1825 free(line[j]);
1826 }
1827
1828 return 0;
1829 }
1830
1831 static bool context_changed(const Context *context) {
1832 Partition *p;
1833
1834 LIST_FOREACH(partitions, p, context->partitions) {
1835 if (p->dropped)
1836 continue;
1837
1838 if (p->allocated_to_area)
1839 return true;
1840
1841 if (p->new_size != p->current_size)
1842 return true;
1843 }
1844
1845 return false;
1846 }
1847
1848 static int context_wipe_partition(Context *context, Partition *p) {
1849 _cleanup_(blkid_free_probep) blkid_probe probe = NULL;
1850 int r;
1851
1852 assert(context);
1853 assert(p);
1854 assert(!PARTITION_EXISTS(p)); /* Safety check: never wipe existing partitions */
1855
1856 probe = blkid_new_probe();
1857 if (!probe)
1858 return log_oom();
1859
1860 assert(p->offset != UINT64_MAX);
1861 assert(p->new_size != UINT64_MAX);
1862
1863 errno = 0;
1864 r = blkid_probe_set_device(probe, fdisk_get_devfd(context->fdisk_context), p->offset, p->new_size);
1865 if (r < 0)
1866 return log_error_errno(errno ?: SYNTHETIC_ERRNO(EIO), "Failed to allocate device probe for partition %" PRIu64 ".", p->partno);
1867
1868 errno = 0;
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);
1874
1875 for (;;) {
1876 errno = 0;
1877 r = blkid_do_probe(probe);
1878 if (r < 0)
1879 return log_error_errno(errno ?: SYNTHETIC_ERRNO(EIO), "Failed to probe for file systems.");
1880 if (r > 0)
1881 break;
1882
1883 errno = 0;
1884 if (blkid_do_wipe(probe, false) < 0)
1885 return log_error_errno(errno ?: SYNTHETIC_ERRNO(EIO), "Failed to wipe file system signature.");
1886 }
1887
1888 log_info("Successfully wiped file system signatures from partition %" PRIu64 ".", p->partno);
1889 return 0;
1890 }
1891
1892 static int context_discard_range(Context *context, uint64_t offset, uint64_t size) {
1893 struct stat st;
1894 int fd;
1895
1896 assert(context);
1897 assert(offset != UINT64_MAX);
1898 assert(size != UINT64_MAX);
1899
1900 if (size <= 0)
1901 return 0;
1902
1903 fd = fdisk_get_devfd(context->fdisk_context);
1904 assert(fd >= 0);
1905
1906 if (fstat(fd, &st) < 0)
1907 return -errno;
1908
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))
1912 return -EOPNOTSUPP;
1913
1914 return -errno;
1915 }
1916
1917 return 1;
1918 }
1919
1920 if (S_ISBLK(st.st_mode)) {
1921 uint64_t range[2], end;
1922
1923 range[0] = round_up_size(offset, 512);
1924
1925 end = offset + size;
1926 if (end <= range[0])
1927 return 0;
1928
1929 range[1] = round_down_size(end - range[0], 512);
1930 if (range[1] <= 0)
1931 return 0;
1932
1933 if (ioctl(fd, BLKDISCARD, range) < 0) {
1934 if (ERRNO_IS_NOT_SUPPORTED(errno))
1935 return -EOPNOTSUPP;
1936
1937 return -errno;
1938 }
1939
1940 return 1;
1941 }
1942
1943 return -EOPNOTSUPP;
1944 }
1945
1946 static int context_discard_partition(Context *context, Partition *p) {
1947 int r;
1948
1949 assert(context);
1950 assert(p);
1951
1952 assert(p->offset != UINT64_MAX);
1953 assert(p->new_size != UINT64_MAX);
1954 assert(!PARTITION_EXISTS(p)); /* Safety check: never discard existing partitions */
1955
1956 if (!arg_discard)
1957 return 0;
1958
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);
1962 return 0;
1963 }
1964 if (r == 0) {
1965 log_info("Partition %" PRIu64 " too short for discard, skipping.", p->partno);
1966 return 0;
1967 }
1968 if (r < 0)
1969 return log_error_errno(r, "Failed to discard data for new partition %" PRIu64 ".", p->partno);
1970
1971 log_info("Successfully discarded data from partition %" PRIu64 ".", p->partno);
1972 return 1;
1973 }
1974
1975 static int context_discard_gap_after(Context *context, Partition *p) {
1976 uint64_t gap, next = UINT64_MAX;
1977 Partition *q;
1978 int r;
1979
1980 assert(context);
1981 assert(!p || (p->offset != UINT64_MAX && p->new_size != UINT64_MAX));
1982
1983 if (p)
1984 gap = p->offset + p->new_size;
1985 else
1986 gap = context->start;
1987
1988 LIST_FOREACH(partitions, q, context->partitions) {
1989 if (q->dropped)
1990 continue;
1991
1992 assert(q->offset != UINT64_MAX);
1993 assert(q->new_size != UINT64_MAX);
1994
1995 if (q->offset < gap)
1996 continue;
1997
1998 if (next == UINT64_MAX || q->offset < next)
1999 next = q->offset;
2000 }
2001
2002 if (next == UINT64_MAX) {
2003 next = context->end;
2004 if (gap > next)
2005 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Partition end beyond disk end.");
2006 }
2007
2008 assert(next >= gap);
2009 r = context_discard_range(context, gap, next - gap);
2010 if (r == -EOPNOTSUPP) {
2011 if (p)
2012 log_info("Storage does not support discarding, not discarding gap after partition %" PRIu64 ".", p->partno);
2013 else
2014 log_info("Storage does not support discarding, not discarding gap at beginning of disk.");
2015 return 0;
2016 }
2017 if (r == 0) /* Too short */
2018 return 0;
2019 if (r < 0) {
2020 if (p)
2021 return log_error_errno(r, "Failed to discard gap after partition %" PRIu64 ".", p->partno);
2022 else
2023 return log_error_errno(r, "Failed to discard gap at beginning of disk.");
2024 }
2025
2026 if (p)
2027 log_info("Successfully discarded gap after partition %" PRIu64 ".", p->partno);
2028 else
2029 log_info("Successfully discarded gap at beginning of disk.");
2030
2031 return 0;
2032 }
2033
2034 static int context_wipe_and_discard(Context *context, bool from_scratch) {
2035 Partition *p;
2036 int r;
2037
2038 assert(context);
2039
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. */
2043
2044 LIST_FOREACH(partitions, p, context->partitions) {
2045
2046 if (!p->allocated_to_area)
2047 continue;
2048
2049 if (!from_scratch) {
2050 r = context_discard_partition(context, p);
2051 if (r < 0)
2052 return r;
2053 }
2054
2055 r = context_wipe_partition(context, p);
2056 if (r < 0)
2057 return r;
2058
2059 if (!from_scratch) {
2060 r = context_discard_gap_after(context, p);
2061 if (r < 0)
2062 return r;
2063 }
2064 }
2065
2066 if (!from_scratch) {
2067 r = context_discard_gap_after(context, NULL);
2068 if (r < 0)
2069 return r;
2070 }
2071
2072 return 0;
2073 }
2074
2075 static int partition_acquire_uuid(Context *context, Partition *p, sd_id128_t *ret) {
2076 struct {
2077 sd_id128_t type_uuid;
2078 uint64_t counter;
2079 } _packed_ plaintext = {};
2080 union {
2081 unsigned char md[SHA256_DIGEST_LENGTH];
2082 sd_id128_t id;
2083 } result;
2084
2085 uint64_t k = 0;
2086 Partition *q;
2087 int r;
2088
2089 assert(context);
2090 assert(p);
2091 assert(ret);
2092
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:
2101 *
2102 * With:
2103 * SEED := /etc/machine-id
2104 *
2105 * If first partition instance of type TYPE_UUID:
2106 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID)
2107 *
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)
2110 */
2111
2112 LIST_FOREACH(partitions, q, context->partitions) {
2113 if (p == q)
2114 break;
2115
2116 if (!sd_id128_equal(p->type_uuid, q->type_uuid))
2117 continue;
2118
2119 k++;
2120 }
2121
2122 plaintext.type_uuid = p->type_uuid;
2123 plaintext.counter = htole64(k);
2124
2125 if (!HMAC(EVP_sha256(),
2126 &context->seed, sizeof(context->seed),
2127 (const unsigned char*) &plaintext, k == 0 ? sizeof(sd_id128_t) : sizeof(plaintext),
2128 result.md, NULL))
2129 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "SHA256 calculation failed.");
2130
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);
2134
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) {
2137 if (p == q)
2138 continue;
2139
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);
2143
2144 r = sd_id128_randomize(&result.id);
2145 if (r < 0)
2146 return log_error_errno(r, "Failed to generate randomized UUID: %m");
2147
2148 break;
2149 }
2150 }
2151
2152 *ret = result.id;
2153 return 0;
2154 }
2155
2156 static int partition_acquire_label(Context *context, Partition *p, char **ret) {
2157 _cleanup_free_ char *label = NULL;
2158 const char *prefix;
2159 unsigned k = 1;
2160
2161 assert(context);
2162 assert(p);
2163 assert(ret);
2164
2165 prefix = gpt_partition_type_uuid_to_string(p->type_uuid);
2166 if (!prefix)
2167 prefix = "linux";
2168
2169 for (;;) {
2170 const char *ll = label ?: prefix;
2171 bool retry = false;
2172 Partition *q;
2173
2174 LIST_FOREACH(partitions, q, context->partitions) {
2175 if (p == q)
2176 break;
2177
2178 if (streq_ptr(ll, q->current_label) ||
2179 streq_ptr(ll, q->new_label)) {
2180 retry = true;
2181 break;
2182 }
2183 }
2184
2185 if (!retry)
2186 break;
2187
2188 label = mfree(label);
2189
2190
2191 if (asprintf(&label, "%s-%u", prefix, ++k) < 0)
2192 return log_oom();
2193 }
2194
2195 if (!label) {
2196 label = strdup(prefix);
2197 if (!label)
2198 return log_oom();
2199 }
2200
2201 *ret = TAKE_PTR(label);
2202 return 0;
2203 }
2204
2205 static int context_acquire_partition_uuids_and_labels(Context *context) {
2206 Partition *p;
2207 int r;
2208
2209 assert(context);
2210
2211 LIST_FOREACH(partitions, p, context->partitions) {
2212 assert(sd_id128_is_null(p->new_uuid));
2213 assert(!p->new_label);
2214
2215 /* Never touch foreign partitions */
2216 if (PARTITION_IS_FOREIGN(p)) {
2217 p->new_uuid = p->current_uuid;
2218
2219 if (p->current_label) {
2220 p->new_label = strdup(p->current_label);
2221 if (!p->new_label)
2222 return log_oom();
2223 }
2224
2225 continue;
2226 }
2227
2228 if (!sd_id128_is_null(p->current_uuid))
2229 p->new_uuid = p->current_uuid; /* Never change initialized UUIDs */
2230 else {
2231 r = partition_acquire_uuid(context, p, &p->new_uuid);
2232 if (r < 0)
2233 return r;
2234 }
2235
2236 if (!isempty(p->current_label)) {
2237 p->new_label = strdup(p->current_label); /* never change initialized labels */
2238 if (!p->new_label)
2239 return log_oom();
2240 } else {
2241 r = partition_acquire_label(context, p, &p->new_label);
2242 if (r < 0)
2243 return r;
2244 }
2245 }
2246
2247 return 0;
2248 }
2249
2250 static int device_kernel_partitions_supported(int fd) {
2251 struct loop_info64 info;
2252 struct stat st;
2253
2254 assert(fd >= 0);
2255
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))
2259 return false;
2260
2261 if (ioctl(fd, LOOP_GET_STATUS64, &info) < 0) {
2262
2263 if (ERRNO_IS_NOT_SUPPORTED(errno) || errno == EINVAL)
2264 return true; /* not a loopback device, let's assume partition are supported */
2265
2266 return log_error_errno(fd, "Failed to issue LOOP_GET_STATUS64 on block device: %m");
2267 }
2268
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));
2272 #endif
2273
2274 return FLAGS_SET(info.lo_flags, LO_FLAGS_PARTSCAN);
2275 }
2276
2277 static int context_write_partition_table(
2278 Context *context,
2279 const char *node,
2280 bool from_scratch) {
2281
2282 _cleanup_(fdisk_unref_tablep) struct fdisk_table *original_table = NULL;
2283 int capable, r;
2284 Partition *p;
2285
2286 assert(context);
2287
2288 if (arg_pretty > 0 ||
2289 (arg_pretty < 0 && isatty(STDOUT_FILENO) > 0)) {
2290
2291 if (context->n_partitions == 0)
2292 puts("Empty partition table.");
2293 else
2294 (void) context_dump_partitions(context, node);
2295
2296 putc('\n', stdout);
2297
2298 (void) context_dump_partition_bar(context, node);
2299 putc('\n', stdout);
2300 fflush(stdout);
2301 }
2302
2303 if (!from_scratch && !context_changed(context)) {
2304 log_info("No changes.");
2305 return 0;
2306 }
2307
2308 if (arg_dry_run) {
2309 log_notice("Refusing to repartition, please re-run with --dry-run=no.");
2310 return 0;
2311 }
2312
2313 log_info("Applying changes.");
2314
2315 if (from_scratch) {
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.");
2319 else if (r < 0)
2320 return log_error_errno(r, "Failed to discard entire block device: %m");
2321 else if (r > 0)
2322 log_info("Discarded entire block device.");
2323 }
2324
2325 r = fdisk_get_partitions(context->fdisk_context, &original_table);
2326 if (r < 0)
2327 return log_error_errno(r, "Failed to acquire partition table: %m");
2328
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);
2332 if (r < 0)
2333 return r;
2334
2335 LIST_FOREACH(partitions, p, context->partitions) {
2336 if (p->dropped)
2337 continue;
2338
2339 assert(p->new_size != UINT64_MAX);
2340 assert(p->offset != UINT64_MAX);
2341 assert(p->partno != UINT64_MAX);
2342
2343 if (PARTITION_EXISTS(p)) {
2344 bool changed = false;
2345
2346 assert(p->current_partition);
2347
2348 if (p->new_size != p->current_size) {
2349 assert(p->new_size >= p->current_size);
2350 assert(p->new_size % 512 == 0);
2351
2352 r = fdisk_partition_size_explicit(p->current_partition, true);
2353 if (r < 0)
2354 return log_error_errno(r, "Failed to enable explicit sizing: %m");
2355
2356 r = fdisk_partition_set_size(p->current_partition, p->new_size / 512);
2357 if (r < 0)
2358 return log_error_errno(r, "Failed to grow partition: %m");
2359
2360 log_info("Growing existing partition %" PRIu64 ".", p->partno);
2361 changed = true;
2362 }
2363
2364 if (!sd_id128_equal(p->new_uuid, p->current_uuid)) {
2365 char buf[ID128_UUID_STRING_MAX];
2366
2367 assert(!sd_id128_is_null(p->new_uuid));
2368
2369 r = fdisk_partition_set_uuid(p->current_partition, id128_to_uuid_string(p->new_uuid, buf));
2370 if (r < 0)
2371 return log_error_errno(r, "Failed to set partition UUID: %m");
2372
2373 log_info("Initializing UUID of existing partition %" PRIu64 ".", p->partno);
2374 changed = true;
2375 }
2376
2377 if (!streq_ptr(p->new_label, p->current_label)) {
2378 assert(!isempty(p->new_label));
2379
2380 r = fdisk_partition_set_name(p->current_partition, p->new_label);
2381 if (r < 0)
2382 return log_error_errno(r, "Failed to set partition label: %m");
2383
2384 log_info("Setting partition label of existing partition %" PRIu64 ".", p->partno);
2385 changed = true;
2386 }
2387
2388 if (changed) {
2389 assert(!PARTITION_IS_FOREIGN(p)); /* never touch foreign partitions */
2390
2391 r = fdisk_set_partition(context->fdisk_context, p->partno, p->current_partition);
2392 if (r < 0)
2393 return log_error_errno(r, "Failed to update partition: %m");
2394 }
2395 } else {
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];
2399
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));
2405
2406 t = fdisk_new_parttype();
2407 if (!t)
2408 return log_oom();
2409
2410 r = fdisk_parttype_set_typestr(t, id128_to_uuid_string(p->type_uuid, ids));
2411 if (r < 0)
2412 return log_error_errno(r, "Failed to initialize partition type: %m");
2413
2414 q = fdisk_new_partition();
2415 if (!q)
2416 return log_oom();
2417
2418 r = fdisk_partition_set_type(q, t);
2419 if (r < 0)
2420 return log_error_errno(r, "Failed to set partition type: %m");
2421
2422 r = fdisk_partition_size_explicit(q, true);
2423 if (r < 0)
2424 return log_error_errno(r, "Failed to enable explicit sizing: %m");
2425
2426 r = fdisk_partition_set_start(q, p->offset / 512);
2427 if (r < 0)
2428 return log_error_errno(r, "Failed to position partition: %m");
2429
2430 r = fdisk_partition_set_size(q, p->new_size / 512);
2431 if (r < 0)
2432 return log_error_errno(r, "Failed to grow partition: %m");
2433
2434 r = fdisk_partition_set_partno(q, p->partno);
2435 if (r < 0)
2436 return log_error_errno(r, "Failed to set partition number: %m");
2437
2438 r = fdisk_partition_set_uuid(q, id128_to_uuid_string(p->new_uuid, ids));
2439 if (r < 0)
2440 return log_error_errno(r, "Failed to set partition UUID: %m");
2441
2442 r = fdisk_partition_set_name(q, p->new_label);
2443 if (r < 0)
2444 return log_error_errno(r, "Failed to set partition label: %m");
2445
2446 log_info("Creating new partition %" PRIu64 ".", p->partno);
2447
2448 r = fdisk_add_partition(context->fdisk_context, q, NULL);
2449 if (r < 0)
2450 return log_error_errno(r, "Failed to add partition: %m");
2451
2452 assert(!p->new_partition);
2453 p->new_partition = TAKE_PTR(q);
2454 }
2455 }
2456
2457 log_info("Writing new partition table.");
2458
2459 r = fdisk_write_disklabel(context->fdisk_context);
2460 if (r < 0)
2461 return log_error_errno(r, "Failed to write partition table: %m");
2462
2463 capable = device_kernel_partitions_supported(fdisk_get_devfd(context->fdisk_context));
2464 if (capable < 0)
2465 return capable;
2466 if (capable > 0) {
2467 log_info("Telling kernel to reread partition table.");
2468
2469 if (from_scratch)
2470 r = fdisk_reread_partition_table(context->fdisk_context);
2471 else
2472 r = fdisk_reread_changes(context->fdisk_context, original_table);
2473 if (r < 0)
2474 return log_error_errno(r, "Failed to reread partition table: %m");
2475 } else
2476 log_notice("Not telling kernel to reread partition table, because selected image does not support kernel partition block devices.");
2477
2478 log_info("All done.");
2479
2480 return 0;
2481 }
2482
2483 static int context_read_seed(Context *context, const char *root) {
2484 int r;
2485
2486 assert(context);
2487
2488 if (!sd_id128_is_null(context->seed))
2489 return 0;
2490
2491 if (!arg_randomize) {
2492 _cleanup_close_ int fd = -1;
2493
2494 fd = chase_symlinks_and_open("/etc/machine-id", root, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC, NULL);
2495 if (fd == -ENOENT)
2496 log_info("No machine ID set, using randomized partition UUIDs.");
2497 else if (fd < 0)
2498 return log_error_errno(fd, "Failed to determine machine ID of image: %m");
2499 else {
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.");
2503 else if (r < 0)
2504 return log_error_errno(r, "Failed to parse machine ID of image: %m");
2505
2506 return 0;
2507 }
2508 }
2509
2510 r = sd_id128_randomize(&context->seed);
2511 if (r < 0)
2512 return log_error_errno(r, "Failed to generate randomized seed: %m");
2513
2514 return 0;
2515 }
2516
2517 static int context_factory_reset(Context *context, bool from_scratch) {
2518 Partition *p;
2519 size_t n = 0;
2520 int r;
2521
2522 assert(context);
2523
2524 if (arg_factory_reset <= 0)
2525 return 0;
2526
2527 if (from_scratch) /* Nothing to reset if we start from scratch */
2528 return 0;
2529
2530 if (arg_dry_run) {
2531 log_notice("Refusing to factory reset, please re-run with --dry-run=no.");
2532 return 0;
2533 }
2534
2535 log_info("Applying factory reset.");
2536
2537 LIST_FOREACH(partitions, p, context->partitions) {
2538
2539 if (!p->factory_reset || !PARTITION_EXISTS(p))
2540 continue;
2541
2542 assert(p->partno != UINT64_MAX);
2543
2544 log_info("Removing partition %" PRIu64 " for factory reset.", p->partno);
2545
2546 r = fdisk_delete_partition(context->fdisk_context, p->partno);
2547 if (r < 0)
2548 return log_error_errno(r, "Failed to remove partition %" PRIu64 ": %m", p->partno);
2549
2550 n++;
2551 }
2552
2553 if (n == 0) {
2554 log_info("Factory reset requested, but no partitions to delete found.");
2555 return 0;
2556 }
2557
2558 r = fdisk_write_disklabel(context->fdisk_context);
2559 if (r < 0)
2560 return log_error_errno(r, "Failed to write disk label: %m");
2561
2562 log_info("Successfully deleted %zu partitions.", n);
2563 return 1;
2564 }
2565
2566 static int context_can_factory_reset(Context *context) {
2567 Partition *p;
2568
2569 assert(context);
2570
2571 LIST_FOREACH(partitions, p, context->partitions)
2572 if (p->factory_reset && PARTITION_EXISTS(p))
2573 return true;
2574
2575 return false;
2576 }
2577
2578 static int help(void) {
2579 _cleanup_free_ char *link = NULL;
2580 int r;
2581
2582 r = terminal_urlify_man("systemd-repart", "1", &link);
2583 if (r < 0)
2584 return log_oom();
2585
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"
2596 " them\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()
2604 , link
2605 );
2606
2607 return 0;
2608 }
2609
2610 static int parse_argv(int argc, char *argv[]) {
2611
2612 enum {
2613 ARG_VERSION = 0x100,
2614 ARG_DRY_RUN,
2615 ARG_EMPTY,
2616 ARG_DISCARD,
2617 ARG_FACTORY_RESET,
2618 ARG_CAN_FACTORY_RESET,
2619 ARG_ROOT,
2620 ARG_SEED,
2621 ARG_PRETTY,
2622 ARG_DEFINITIONS,
2623 };
2624
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 },
2637 {}
2638 };
2639
2640 int c, r;
2641
2642 assert(argc >= 0);
2643 assert(argv);
2644
2645 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
2646
2647 switch (c) {
2648
2649 case 'h':
2650 return help();
2651
2652 case ARG_VERSION:
2653 return version();
2654
2655 case ARG_DRY_RUN:
2656 r = parse_boolean(optarg);
2657 if (r < 0)
2658 return log_error_errno(r, "Failed to parse --dry-run= parameter: %s", optarg);
2659
2660 arg_dry_run = r;
2661 break;
2662
2663 case ARG_EMPTY:
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;
2672 else
2673 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2674 "Failed to parse --empty= parameter: %s", optarg);
2675 break;
2676
2677 case ARG_DISCARD:
2678 r = parse_boolean(optarg);
2679 if (r < 0)
2680 return log_error_errno(r, "Failed to parse --discard= parameter: %s", optarg);
2681
2682 arg_discard = r;
2683 break;
2684
2685 case ARG_FACTORY_RESET:
2686 r = parse_boolean(optarg);
2687 if (r < 0)
2688 return log_error_errno(r, "Failed to parse --factory-reset= parameter: %s", optarg);
2689
2690 arg_factory_reset = r;
2691 break;
2692
2693 case ARG_CAN_FACTORY_RESET:
2694 arg_can_factory_reset = true;
2695 break;
2696
2697 case ARG_ROOT:
2698 r = parse_path_argument_and_warn(optarg, false, &arg_root);
2699 if (r < 0)
2700 return r;
2701 break;
2702
2703 case ARG_SEED:
2704 if (isempty(optarg)) {
2705 arg_seed = SD_ID128_NULL;
2706 arg_randomize = false;
2707 } else if (streq(optarg, "random"))
2708 arg_randomize = true;
2709 else {
2710 r = sd_id128_from_string(optarg, &arg_seed);
2711 if (r < 0)
2712 return log_error_errno(r, "Failed to parse seed: %s", optarg);
2713
2714 arg_randomize = false;
2715 }
2716
2717 break;
2718
2719 case ARG_PRETTY:
2720 r = parse_boolean(optarg);
2721 if (r < 0)
2722 return log_error_errno(r, "Failed to parse --pretty= parameter: %s", optarg);
2723
2724 arg_pretty = r;
2725 break;
2726
2727 case ARG_DEFINITIONS:
2728 r = parse_path_argument_and_warn(optarg, false, &arg_definitions);
2729 if (r < 0)
2730 return r;
2731 break;
2732
2733 case '?':
2734 return -EINVAL;
2735
2736 default:
2737 assert_not_reached("Unhandled option");
2738 }
2739
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.");
2743
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.");
2747
2748 if (arg_can_factory_reset)
2749 arg_dry_run = true;
2750
2751 arg_node = argc > optind ? argv[optind] : NULL;
2752 return 1;
2753 }
2754
2755 static int parse_proc_cmdline_factory_reset(void) {
2756 bool b;
2757 int r;
2758
2759 if (arg_factory_reset >= 0) /* Never override what is specified on the process command line */
2760 return 0;
2761
2762 if (!in_initrd()) /* Never honour kernel command line factory reset request outside of the initrd */
2763 return 0;
2764
2765 r = proc_cmdline_get_bool("systemd.factory_reset", &b);
2766 if (r < 0)
2767 return log_error_errno(r, "Failed to parse systemd.factory_reset kernel command line argument: %m");
2768 if (r > 0) {
2769 arg_factory_reset = b;
2770
2771 if (b)
2772 log_notice("Honouring factory reset requested via kernel command line.");
2773 }
2774
2775 return 0;
2776 }
2777
2778 static int parse_efi_variable_factory_reset(void) {
2779 _cleanup_free_ char *value = NULL;
2780 int r;
2781
2782 if (arg_factory_reset >= 0) /* Never override what is specified on the process command line */
2783 return 0;
2784
2785 if (!in_initrd()) /* Never honour EFI variable factory reset request outside of the initrd */
2786 return 0;
2787
2788 r = efi_get_variable_string(EFI_VENDOR_SYSTEMD, "FactoryReset", &value);
2789 if (r == -ENOENT || ERRNO_IS_NOT_SUPPORTED(r))
2790 return 0;
2791 if (r < 0)
2792 return log_error_errno(r, "Failed to read EFI variable FactoryReset: %m");
2793
2794 r = parse_boolean(value);
2795 if (r < 0)
2796 return log_error_errno(r, "Failed to parse EFI variable FactoryReset: %m");
2797
2798 arg_factory_reset = r;
2799 if (r)
2800 log_notice("Honouring factory reset requested via EFI variable FactoryReset: %m");
2801
2802 return 0;
2803 }
2804
2805 static int remove_efi_variable_factory_reset(void) {
2806 int r;
2807
2808 r = efi_set_variable(EFI_VENDOR_SYSTEMD, "FactoryReset", NULL, 0);
2809 if (r == -ENOENT || ERRNO_IS_NOT_SUPPORTED(r))
2810 return 0;
2811 if (r < 0)
2812 return log_error_errno(r, "Failed to remove EFI variable FactoryReset: %m");
2813
2814 log_info("Successfully unset EFI variable FactoryReset.");
2815 return 0;
2816 }
2817
2818 static int acquire_root_devno(const char *p, int mode, char **ret) {
2819 _cleanup_close_ int fd = -1;
2820 struct stat st;
2821 dev_t devno;
2822 int r;
2823
2824 fd = open(p, mode);
2825 if (fd < 0)
2826 return -errno;
2827
2828 if (fstat(fd, &st) < 0)
2829 return -errno;
2830
2831 if (S_ISREG(st.st_mode)) {
2832 char *s;
2833
2834 s = strdup(p);
2835 if (!s)
2836 return log_oom();
2837
2838 *ret = s;
2839 return 0;
2840 }
2841
2842 if (S_ISBLK(st.st_mode))
2843 devno = st.st_rdev;
2844 else if (S_ISDIR(st.st_mode)) {
2845
2846 devno = st.st_dev;
2847
2848 if (major(st.st_dev) == 0) {
2849 r = btrfs_get_block_device_fd(fd, &devno);
2850 if (r == -ENOTTY) /* not btrfs */
2851 return -ENODEV;
2852 if (r < 0)
2853 return r;
2854 }
2855
2856 } else
2857 return -ENOTBLK;
2858
2859 /* From dm-crypt to backing partition */
2860 r = block_get_originating(devno, &devno);
2861 if (r < 0)
2862 log_debug_errno(r, "Failed to find underlying block device for '%s', ignoring: %m", p);
2863
2864 /* From partition to whole disk containing it */
2865 r = block_get_whole_disk(devno, &devno);
2866 if (r < 0)
2867 log_debug_errno(r, "Failed to find whole disk block device for '%s', ignoring: %m", p);
2868
2869 return device_path_make_canonical(S_IFBLK, devno, ret);
2870 }
2871
2872 static int find_root(char **ret) {
2873 const char *t;
2874 int r;
2875
2876 if (arg_node) {
2877 r = acquire_root_devno(arg_node, O_RDONLY|O_CLOEXEC, ret);
2878 if (r < 0)
2879 return log_error_errno(r, "Failed to determine backing device of %s: %m", arg_node);
2880
2881 return 0;
2882 }
2883
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) */
2887
2888 FOREACH_STRING(t, "/", "/usr") {
2889 _cleanup_free_ char *j = NULL;
2890 const char *p;
2891
2892 if (in_initrd()) {
2893 j = path_join("/sysroot", t);
2894 if (!j)
2895 return log_oom();
2896
2897 p = j;
2898 } else
2899 p = t;
2900
2901 r = acquire_root_devno(p, O_RDONLY|O_DIRECTORY|O_CLOEXEC, ret);
2902 if (r < 0) {
2903 if (r != -ENODEV)
2904 return log_error_errno(r, "Failed to determine backing device of %s: %m", p);
2905 } else
2906 return 0;
2907 }
2908
2909 return log_error_errno(SYNTHETIC_ERRNO(ENODEV), "Failed to discover root block device.");
2910 }
2911
2912 static int run(int argc, char *argv[]) {
2913 _cleanup_(context_freep) Context* context = NULL;
2914 _cleanup_free_ char *node = NULL;
2915 bool from_scratch;
2916 int r;
2917
2918 log_show_color(true);
2919 log_parse_environment();
2920 log_open();
2921
2922 if (in_initrd()) {
2923 /* Default to operation on /sysroot when invoked in the initrd! */
2924 arg_root = strdup("/sysroot");
2925 if (!arg_root)
2926 return log_oom();
2927 }
2928
2929 r = parse_argv(argc, argv);
2930 if (r <= 0)
2931 return r;
2932
2933 r = parse_proc_cmdline_factory_reset();
2934 if (r < 0)
2935 return r;
2936
2937 r = parse_efi_variable_factory_reset();
2938 if (r < 0)
2939 return r;
2940
2941 context = context_new(arg_seed);
2942 if (!context)
2943 return log_oom();
2944
2945 r = context_read_definitions(context, arg_definitions, arg_root);
2946 if (r < 0)
2947 return r;
2948
2949 if (context->n_partitions <= 0 && arg_empty != EMPTY_FORCE)
2950 return 0;
2951
2952 r = find_root(&node);
2953 if (r < 0)
2954 return r;
2955
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. */
2960 if (r < 0)
2961 return r;
2962 from_scratch = r > 0; /* Starting from scratch */
2963
2964 if (arg_can_factory_reset) {
2965 r = context_can_factory_reset(context);
2966 if (r < 0)
2967 return r;
2968 if (r == 0)
2969 return EXIT_FAILURE;
2970
2971 return 0;
2972 }
2973
2974 r = context_factory_reset(context, from_scratch);
2975 if (r < 0)
2976 return r;
2977 if (r > 0) {
2978 /* We actually did a factory reset! */
2979 r = remove_efi_variable_factory_reset();
2980 if (r < 0)
2981 return r;
2982
2983 /* Reload the reduced partition table */
2984 context_unload_partition_table(context);
2985 r = context_load_partition_table(context, node);
2986 if (r < 0)
2987 return r;
2988 }
2989
2990 #if 0
2991 (void) context_dump_partitions(context, node);
2992 putchar('\n');
2993 #endif
2994
2995 r = context_read_seed(context, arg_root);
2996 if (r < 0)
2997 return r;
2998
2999 /* First try to fit new partitions in, dropping by priority until it fits */
3000 for (;;) {
3001 if (context_allocate_partitions(context))
3002 break; /* Success! */
3003
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.");
3007 }
3008
3009 /* Now assign free space according to the weight logic */
3010 r = context_grow_partitions(context);
3011 if (r < 0)
3012 return r;
3013
3014 /* Now calculate where each partition gets placed */
3015 context_place_partitions(context);
3016
3017 /* Make sure each partition has a unique UUID and unique label */
3018 r = context_acquire_partition_uuids_and_labels(context);
3019 if (r < 0)
3020 return r;
3021
3022 r = context_write_partition_table(context, node, from_scratch);
3023 if (r < 0)
3024 return r;
3025
3026 return 0;
3027 }
3028
3029 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);