]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/partition/repart.c
repart: Add UUID option to config files
[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 EMPTY_CREATE, /* create disk as loopback file, create a partition table always */
62 } arg_empty = EMPTY_REFUSE;
63
64 static bool arg_dry_run = true;
65 static const char *arg_node = NULL;
66 static char *arg_root = NULL;
67 static char *arg_definitions = NULL;
68 static bool arg_discard = true;
69 static bool arg_can_factory_reset = false;
70 static int arg_factory_reset = -1;
71 static sd_id128_t arg_seed = SD_ID128_NULL;
72 static bool arg_randomize = false;
73 static int arg_pretty = -1;
74 static uint64_t arg_size = UINT64_MAX;
75
76 STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
77 STATIC_DESTRUCTOR_REGISTER(arg_definitions, freep);
78
79 typedef struct Partition Partition;
80 typedef struct FreeArea FreeArea;
81 typedef struct Context Context;
82
83 struct Partition {
84 char *definition_path;
85
86 sd_id128_t type_uuid;
87 sd_id128_t current_uuid, new_uuid;
88 char *current_label, *new_label;
89
90 bool dropped;
91 bool factory_reset;
92 int32_t priority;
93
94 uint32_t weight, padding_weight;
95
96 uint64_t current_size, new_size;
97 uint64_t size_min, size_max;
98
99 uint64_t current_padding, new_padding;
100 uint64_t padding_min, padding_max;
101
102 uint64_t partno;
103 uint64_t offset;
104
105 struct fdisk_partition *current_partition;
106 struct fdisk_partition *new_partition;
107 FreeArea *padding_area;
108 FreeArea *allocated_to_area;
109
110 LIST_FIELDS(Partition, partitions);
111 };
112
113 #define PARTITION_IS_FOREIGN(p) (!(p)->definition_path)
114 #define PARTITION_EXISTS(p) (!!(p)->current_partition)
115
116 struct FreeArea {
117 Partition *after;
118 uint64_t size;
119 uint64_t allocated;
120 };
121
122 struct Context {
123 LIST_HEAD(Partition, partitions);
124 size_t n_partitions;
125
126 FreeArea **free_areas;
127 size_t n_free_areas, n_allocated_free_areas;
128
129 uint64_t start, end, total;
130
131 struct fdisk_context *fdisk_context;
132
133 sd_id128_t seed;
134 };
135
136 static uint64_t round_down_size(uint64_t v, uint64_t p) {
137 return (v / p) * p;
138 }
139
140 static uint64_t round_up_size(uint64_t v, uint64_t p) {
141
142 v = DIV_ROUND_UP(v, p);
143
144 if (v > UINT64_MAX / p)
145 return UINT64_MAX; /* overflow */
146
147 return v * p;
148 }
149
150 static Partition *partition_new(void) {
151 Partition *p;
152
153 p = new(Partition, 1);
154 if (!p)
155 return NULL;
156
157 *p = (Partition) {
158 .weight = 1000,
159 .padding_weight = 0,
160 .current_size = UINT64_MAX,
161 .new_size = UINT64_MAX,
162 .size_min = UINT64_MAX,
163 .size_max = UINT64_MAX,
164 .current_padding = UINT64_MAX,
165 .new_padding = UINT64_MAX,
166 .padding_min = UINT64_MAX,
167 .padding_max = UINT64_MAX,
168 .partno = UINT64_MAX,
169 .offset = UINT64_MAX,
170 };
171
172 return p;
173 }
174
175 static Partition* partition_free(Partition *p) {
176 if (!p)
177 return NULL;
178
179 free(p->current_label);
180 free(p->new_label);
181 free(p->definition_path);
182
183 if (p->current_partition)
184 fdisk_unref_partition(p->current_partition);
185 if (p->new_partition)
186 fdisk_unref_partition(p->new_partition);
187
188 return mfree(p);
189 }
190
191 static Partition* partition_unlink_and_free(Context *context, Partition *p) {
192 if (!p)
193 return NULL;
194
195 LIST_REMOVE(partitions, context->partitions, p);
196
197 assert(context->n_partitions > 0);
198 context->n_partitions--;
199
200 return partition_free(p);
201 }
202
203 DEFINE_TRIVIAL_CLEANUP_FUNC(Partition*, partition_free);
204
205 static Context *context_new(sd_id128_t seed) {
206 Context *context;
207
208 context = new(Context, 1);
209 if (!context)
210 return NULL;
211
212 *context = (Context) {
213 .start = UINT64_MAX,
214 .end = UINT64_MAX,
215 .total = UINT64_MAX,
216 .seed = seed,
217 };
218
219 return context;
220 }
221
222 static void context_free_free_areas(Context *context) {
223 assert(context);
224
225 for (size_t i = 0; i < context->n_free_areas; i++)
226 free(context->free_areas[i]);
227
228 context->free_areas = mfree(context->free_areas);
229 context->n_free_areas = 0;
230 context->n_allocated_free_areas = 0;
231 }
232
233 static Context *context_free(Context *context) {
234 if (!context)
235 return NULL;
236
237 while (context->partitions)
238 partition_unlink_and_free(context, context->partitions);
239 assert(context->n_partitions == 0);
240
241 context_free_free_areas(context);
242
243 if (context->fdisk_context)
244 fdisk_unref_context(context->fdisk_context);
245
246 return mfree(context);
247 }
248
249 DEFINE_TRIVIAL_CLEANUP_FUNC(Context*, context_free);
250
251 static int context_add_free_area(
252 Context *context,
253 uint64_t size,
254 Partition *after) {
255
256 FreeArea *a;
257
258 assert(context);
259 assert(!after || !after->padding_area);
260
261 if (!GREEDY_REALLOC(context->free_areas, context->n_allocated_free_areas, context->n_free_areas + 1))
262 return -ENOMEM;
263
264 a = new(FreeArea, 1);
265 if (!a)
266 return -ENOMEM;
267
268 *a = (FreeArea) {
269 .size = size,
270 .after = after,
271 };
272
273 context->free_areas[context->n_free_areas++] = a;
274
275 if (after)
276 after->padding_area = a;
277
278 return 0;
279 }
280
281 static bool context_drop_one_priority(Context *context) {
282 int32_t priority = 0;
283 Partition *p;
284 bool exists = false;
285
286 LIST_FOREACH(partitions, p, context->partitions) {
287 if (p->dropped)
288 continue;
289 if (p->priority < priority)
290 continue;
291 if (p->priority == priority) {
292 exists = exists || PARTITION_EXISTS(p);
293 continue;
294 }
295
296 priority = p->priority;
297 exists = PARTITION_EXISTS(p);
298 }
299
300 /* Refuse to drop partitions with 0 or negative priorities or partitions of priorities that have at
301 * least one existing priority */
302 if (priority <= 0 || exists)
303 return false;
304
305 LIST_FOREACH(partitions, p, context->partitions) {
306 if (p->priority < priority)
307 continue;
308
309 if (p->dropped)
310 continue;
311
312 p->dropped = true;
313 log_info("Can't fit partition %s of priority %" PRIi32 ", dropping.", p->definition_path, p->priority);
314 }
315
316 return true;
317 }
318
319 static uint64_t partition_min_size(const Partition *p) {
320 uint64_t sz;
321
322 /* Calculate the disk space we really need at minimum for this partition. If the partition already
323 * exists the current size is what we really need. If it doesn't exist yet refuse to allocate less
324 * than 4K. */
325
326 if (PARTITION_IS_FOREIGN(p)) {
327 /* Don't allow changing size of partitions not managed by us */
328 assert(p->current_size != UINT64_MAX);
329 return p->current_size;
330 }
331
332 sz = p->current_size != UINT64_MAX ? p->current_size : 4096;
333 if (p->size_min != UINT64_MAX)
334 return MAX(p->size_min, sz);
335
336 return sz;
337 }
338
339 static uint64_t partition_max_size(const Partition *p) {
340 /* Calculate how large the partition may become at max. This is generally the configured maximum
341 * size, except when it already exists and is larger than that. In that case it's the existing size,
342 * since we never want to shrink partitions. */
343
344 if (PARTITION_IS_FOREIGN(p)) {
345 /* Don't allow changing size of partitions not managed by us */
346 assert(p->current_size != UINT64_MAX);
347 return p->current_size;
348 }
349
350 if (p->current_size != UINT64_MAX)
351 return MAX(p->current_size, p->size_max);
352
353 return p->size_max;
354 }
355
356 static uint64_t partition_min_size_with_padding(const Partition *p) {
357 uint64_t sz;
358
359 /* Calculate the disk space we need for this partition plus any free space coming after it. This
360 * takes user configured padding into account as well as any additional whitespace needed to align
361 * the next partition to 4K again. */
362
363 sz = partition_min_size(p);
364
365 if (p->padding_min != UINT64_MAX)
366 sz += p->padding_min;
367
368 if (PARTITION_EXISTS(p)) {
369 /* If the partition wasn't aligned, add extra space so that any we might add will be aligned */
370 assert(p->offset != UINT64_MAX);
371 return round_up_size(p->offset + sz, 4096) - p->offset;
372 }
373
374 /* If this is a new partition we'll place it aligned, hence we just need to round up the required size here */
375 return round_up_size(sz, 4096);
376 }
377
378 static uint64_t free_area_available(const FreeArea *a) {
379 assert(a);
380
381 /* Determines how much of this free area is not allocated yet */
382
383 assert(a->size >= a->allocated);
384 return a->size - a->allocated;
385 }
386
387 static uint64_t free_area_available_for_new_partitions(const FreeArea *a) {
388 uint64_t avail;
389
390 /* Similar to free_area_available(), but takes into account that the required size and padding of the
391 * preceding partition is honoured. */
392
393 avail = free_area_available(a);
394 if (a->after) {
395 uint64_t need, space;
396
397 need = partition_min_size_with_padding(a->after);
398
399 assert(a->after->offset != UINT64_MAX);
400 assert(a->after->current_size != UINT64_MAX);
401
402 space = round_up_size(a->after->offset + a->after->current_size, 4096) - a->after->offset + avail;
403 if (need >= space)
404 return 0;
405
406 return space - need;
407 }
408
409 return avail;
410 }
411
412 static int free_area_compare(FreeArea *const *a, FreeArea *const*b) {
413 return CMP(free_area_available_for_new_partitions(*a),
414 free_area_available_for_new_partitions(*b));
415 }
416
417 static uint64_t charge_size(uint64_t total, uint64_t amount) {
418 uint64_t rounded;
419
420 assert(amount <= total);
421
422 /* Subtract the specified amount from total, rounding up to multiple of 4K if there's room */
423 rounded = round_up_size(amount, 4096);
424 if (rounded >= total)
425 return 0;
426
427 return total - rounded;
428 }
429
430 static uint64_t charge_weight(uint64_t total, uint64_t amount) {
431 assert(amount <= total);
432 return total - amount;
433 }
434
435 static bool context_allocate_partitions(Context *context) {
436 Partition *p;
437
438 assert(context);
439
440 /* A simple first-fit algorithm, assuming the array of free areas is sorted by size in decreasing
441 * order. */
442
443 LIST_FOREACH(partitions, p, context->partitions) {
444 bool fits = false;
445 uint64_t required;
446 FreeArea *a = NULL;
447
448 /* Skip partitions we already dropped or that already exist */
449 if (p->dropped || PARTITION_EXISTS(p))
450 continue;
451
452 /* Sort by size */
453 typesafe_qsort(context->free_areas, context->n_free_areas, free_area_compare);
454
455 /* How much do we need to fit? */
456 required = partition_min_size_with_padding(p);
457 assert(required % 4096 == 0);
458
459 for (size_t i = 0; i < context->n_free_areas; i++) {
460 a = context->free_areas[i];
461
462 if (free_area_available_for_new_partitions(a) >= required) {
463 fits = true;
464 break;
465 }
466 }
467
468 if (!fits)
469 return false; /* 😢 Oh no! We can't fit this partition into any free area! */
470
471 /* Assign the partition to this free area */
472 p->allocated_to_area = a;
473
474 /* Budget the minimal partition size */
475 a->allocated += required;
476 }
477
478 return true;
479 }
480
481 static int context_sum_weights(Context *context, FreeArea *a, uint64_t *ret) {
482 uint64_t weight_sum = 0;
483 Partition *p;
484
485 assert(context);
486 assert(a);
487 assert(ret);
488
489 /* Determine the sum of the weights of all partitions placed in or before the specified free area */
490
491 LIST_FOREACH(partitions, p, context->partitions) {
492 if (p->padding_area != a && p->allocated_to_area != a)
493 continue;
494
495 if (p->weight > UINT64_MAX - weight_sum)
496 goto overflow_sum;
497 weight_sum += p->weight;
498
499 if (p->padding_weight > UINT64_MAX - weight_sum)
500 goto overflow_sum;
501 weight_sum += p->padding_weight;
502 }
503
504 *ret = weight_sum;
505 return 0;
506
507 overflow_sum:
508 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Combined weight of partition exceeds unsigned 64bit range, refusing.");
509 }
510
511 static int scale_by_weight(uint64_t value, uint64_t weight, uint64_t weight_sum, uint64_t *ret) {
512 assert(weight_sum >= weight);
513 assert(ret);
514
515 if (weight == 0) {
516 *ret = 0;
517 return 0;
518 }
519
520 if (value > UINT64_MAX / weight)
521 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Scaling by weight of partition exceeds unsigned 64bit range, refusing.");
522
523 *ret = value * weight / weight_sum;
524 return 0;
525 }
526
527 typedef enum GrowPartitionPhase {
528 /* The first phase: we charge partitions which need more (according to constraints) than their weight-based share. */
529 PHASE_OVERCHARGE,
530
531 /* The second phase: we charge partitions which need less (according to constraints) than their weight-based share. */
532 PHASE_UNDERCHARGE,
533
534 /* The third phase: we distribute what remains among the remaining partitions, according to the weights */
535 PHASE_DISTRIBUTE,
536 } GrowPartitionPhase;
537
538 static int context_grow_partitions_phase(
539 Context *context,
540 FreeArea *a,
541 GrowPartitionPhase phase,
542 uint64_t *span,
543 uint64_t *weight_sum) {
544
545 Partition *p;
546 int r;
547
548 assert(context);
549 assert(a);
550
551 /* Now let's look at the intended weights and adjust them taking the minimum space assignments into
552 * account. i.e. if a partition has a small weight but a high minimum space value set it should not
553 * get any additional room from the left-overs. Similar, if two partitions have the same weight they
554 * should get the same space if possible, even if one has a smaller minimum size than the other. */
555 LIST_FOREACH(partitions, p, context->partitions) {
556
557 /* Look only at partitions associated with this free area, i.e. immediately
558 * preceding it, or allocated into it */
559 if (p->allocated_to_area != a && p->padding_area != a)
560 continue;
561
562 if (p->new_size == UINT64_MAX) {
563 bool charge = false, try_again = false;
564 uint64_t share, rsz, xsz;
565
566 /* Calculate how much this space this partition needs if everyone would get
567 * the weight based share */
568 r = scale_by_weight(*span, p->weight, *weight_sum, &share);
569 if (r < 0)
570 return r;
571
572 rsz = partition_min_size(p);
573 xsz = partition_max_size(p);
574
575 if (phase == PHASE_OVERCHARGE && rsz > share) {
576 /* This partition needs more than its calculated share. Let's assign
577 * it that, and take this partition out of all calculations and start
578 * again. */
579
580 p->new_size = rsz;
581 charge = try_again = true;
582
583 } else if (phase == PHASE_UNDERCHARGE && xsz != UINT64_MAX && xsz < share) {
584 /* This partition accepts less than its calculated
585 * share. Let's assign it that, and take this partition out
586 * of all calculations and start again. */
587
588 p->new_size = xsz;
589 charge = try_again = true;
590
591 } else if (phase == PHASE_DISTRIBUTE) {
592 /* This partition can accept its calculated share. Let's
593 * assign it. There's no need to restart things here since
594 * assigning this shouldn't impact the shares of the other
595 * partitions. */
596
597 if (PARTITION_IS_FOREIGN(p))
598 /* Never change of foreign partitions (i.e. those we don't manage) */
599 p->new_size = p->current_size;
600 else
601 p->new_size = MAX(round_down_size(share, 4096), rsz);
602
603 charge = true;
604 }
605
606 if (charge) {
607 *span = charge_size(*span, p->new_size);
608 *weight_sum = charge_weight(*weight_sum, p->weight);
609 }
610
611 if (try_again)
612 return 0; /* try again */
613 }
614
615 if (p->new_padding == UINT64_MAX) {
616 bool charge = false, try_again = false;
617 uint64_t share;
618
619 r = scale_by_weight(*span, p->padding_weight, *weight_sum, &share);
620 if (r < 0)
621 return r;
622
623 if (phase == PHASE_OVERCHARGE && p->padding_min != UINT64_MAX && p->padding_min > share) {
624 p->new_padding = p->padding_min;
625 charge = try_again = true;
626 } else if (phase == PHASE_UNDERCHARGE && p->padding_max != UINT64_MAX && p->padding_max < share) {
627 p->new_padding = p->padding_max;
628 charge = try_again = true;
629 } else if (phase == PHASE_DISTRIBUTE) {
630
631 p->new_padding = round_down_size(share, 4096);
632 if (p->padding_min != UINT64_MAX && p->new_padding < p->padding_min)
633 p->new_padding = p->padding_min;
634
635 charge = true;
636 }
637
638 if (charge) {
639 *span = charge_size(*span, p->new_padding);
640 *weight_sum = charge_weight(*weight_sum, p->padding_weight);
641 }
642
643 if (try_again)
644 return 0; /* try again */
645 }
646 }
647
648 return 1; /* done */
649 }
650
651 static int context_grow_partitions_on_free_area(Context *context, FreeArea *a) {
652 uint64_t weight_sum = 0, span;
653 int r;
654
655 assert(context);
656 assert(a);
657
658 r = context_sum_weights(context, a, &weight_sum);
659 if (r < 0)
660 return r;
661
662 /* Let's calculate the total area covered by this free area and the partition before it */
663 span = a->size;
664 if (a->after) {
665 assert(a->after->offset != UINT64_MAX);
666 assert(a->after->current_size != UINT64_MAX);
667
668 span += round_up_size(a->after->offset + a->after->current_size, 4096) - a->after->offset;
669 }
670
671 GrowPartitionPhase phase = PHASE_OVERCHARGE;
672 for (;;) {
673 r = context_grow_partitions_phase(context, a, phase, &span, &weight_sum);
674 if (r < 0)
675 return r;
676 if (r == 0) /* not done yet, re-run this phase */
677 continue;
678
679 if (phase == PHASE_OVERCHARGE)
680 phase = PHASE_UNDERCHARGE;
681 else if (phase == PHASE_UNDERCHARGE)
682 phase = PHASE_DISTRIBUTE;
683 else if (phase == PHASE_DISTRIBUTE)
684 break;
685 }
686
687 /* We still have space left over? Donate to preceding partition if we have one */
688 if (span > 0 && a->after && !PARTITION_IS_FOREIGN(a->after)) {
689 uint64_t m, xsz;
690
691 assert(a->after->new_size != UINT64_MAX);
692 m = a->after->new_size + span;
693
694 xsz = partition_max_size(a->after);
695 if (xsz != UINT64_MAX && m > xsz)
696 m = xsz;
697
698 span = charge_size(span, m - a->after->new_size);
699 a->after->new_size = m;
700 }
701
702 /* What? Even still some space left (maybe because there was no preceding partition, or it had a
703 * size limit), then let's donate it to whoever wants it. */
704 if (span > 0) {
705 Partition *p;
706
707 LIST_FOREACH(partitions, p, context->partitions) {
708 uint64_t m, xsz;
709
710 if (p->allocated_to_area != a)
711 continue;
712
713 if (PARTITION_IS_FOREIGN(p))
714 continue;
715
716 assert(p->new_size != UINT64_MAX);
717 m = p->new_size + span;
718
719 xsz = partition_max_size(p);
720 if (xsz != UINT64_MAX && m > xsz)
721 m = xsz;
722
723 span = charge_size(span, m - p->new_size);
724 p->new_size = m;
725
726 if (span == 0)
727 break;
728 }
729 }
730
731 /* Yuck, still no one? Then make it padding */
732 if (span > 0 && a->after) {
733 assert(a->after->new_padding != UINT64_MAX);
734 a->after->new_padding += span;
735 }
736
737 return 0;
738 }
739
740 static int context_grow_partitions(Context *context) {
741 Partition *p;
742 int r;
743
744 assert(context);
745
746 for (size_t i = 0; i < context->n_free_areas; i++) {
747 r = context_grow_partitions_on_free_area(context, context->free_areas[i]);
748 if (r < 0)
749 return r;
750 }
751
752 /* All existing partitions that have no free space after them can't change size */
753 LIST_FOREACH(partitions, p, context->partitions) {
754 if (p->dropped)
755 continue;
756
757 if (!PARTITION_EXISTS(p) || p->padding_area) {
758 /* The algorithm above must have initialized this already */
759 assert(p->new_size != UINT64_MAX);
760 continue;
761 }
762
763 assert(p->new_size == UINT64_MAX);
764 p->new_size = p->current_size;
765
766 assert(p->new_padding == UINT64_MAX);
767 p->new_padding = p->current_padding;
768 }
769
770 return 0;
771 }
772
773 static void context_place_partitions(Context *context) {
774 uint64_t partno = 0;
775 Partition *p;
776
777 assert(context);
778
779 /* Determine next partition number to assign */
780 LIST_FOREACH(partitions, p, context->partitions) {
781 if (!PARTITION_EXISTS(p))
782 continue;
783
784 assert(p->partno != UINT64_MAX);
785 if (p->partno >= partno)
786 partno = p->partno + 1;
787 }
788
789 for (size_t i = 0; i < context->n_free_areas; i++) {
790 FreeArea *a = context->free_areas[i];
791 uint64_t start, left;
792
793 if (a->after) {
794 assert(a->after->offset != UINT64_MAX);
795 assert(a->after->new_size != UINT64_MAX);
796 assert(a->after->new_padding != UINT64_MAX);
797
798 start = a->after->offset + a->after->new_size + a->after->new_padding;
799 } else
800 start = context->start;
801
802 start = round_up_size(start, 4096);
803 left = a->size;
804
805 LIST_FOREACH(partitions, p, context->partitions) {
806 if (p->allocated_to_area != a)
807 continue;
808
809 p->offset = start;
810 p->partno = partno++;
811
812 assert(left >= p->new_size);
813 start += p->new_size;
814 left -= p->new_size;
815
816 assert(left >= p->new_padding);
817 start += p->new_padding;
818 left -= p->new_padding;
819 }
820 }
821 }
822
823 static int config_parse_type(
824 const char *unit,
825 const char *filename,
826 unsigned line,
827 const char *section,
828 unsigned section_line,
829 const char *lvalue,
830 int ltype,
831 const char *rvalue,
832 void *data,
833 void *userdata) {
834
835 sd_id128_t *type_uuid = data;
836 int r;
837
838 assert(rvalue);
839 assert(type_uuid);
840
841 r = gpt_partition_type_uuid_from_string(rvalue, type_uuid);
842 if (r < 0)
843 return log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse partition type: %s", rvalue);
844
845 return 0;
846 }
847
848 static int config_parse_label(
849 const char *unit,
850 const char *filename,
851 unsigned line,
852 const char *section,
853 unsigned section_line,
854 const char *lvalue,
855 int ltype,
856 const char *rvalue,
857 void *data,
858 void *userdata) {
859
860 _cleanup_free_ char16_t *recoded = NULL;
861 char **label = data;
862 int r;
863
864 assert(rvalue);
865 assert(label);
866
867 if (!utf8_is_valid(rvalue)) {
868 log_syntax(unit, LOG_WARNING, filename, line, 0,
869 "Partition label not valid UTF-8, ignoring: %s", rvalue);
870 return 0;
871 }
872
873 recoded = utf8_to_utf16(rvalue, strlen(rvalue));
874 if (!recoded)
875 return log_oom();
876
877 if (char16_strlen(recoded) > 36) {
878 log_syntax(unit, LOG_WARNING, filename, line, 0,
879 "Partition label too long for GPT table, ignoring: %s", rvalue);
880 return 0;
881 }
882
883 r = free_and_strdup(label, rvalue);
884 if (r < 0)
885 return log_oom();
886
887 return 0;
888 }
889
890 static int config_parse_weight(
891 const char *unit,
892 const char *filename,
893 unsigned line,
894 const char *section,
895 unsigned section_line,
896 const char *lvalue,
897 int ltype,
898 const char *rvalue,
899 void *data,
900 void *userdata) {
901
902 uint32_t *priority = data, v;
903 int r;
904
905 assert(rvalue);
906 assert(priority);
907
908 r = safe_atou32(rvalue, &v);
909 if (r < 0) {
910 log_syntax(unit, LOG_WARNING, filename, line, r,
911 "Failed to parse weight value, ignoring: %s", rvalue);
912 return 0;
913 }
914
915 if (v > 1000U*1000U) {
916 log_syntax(unit, LOG_WARNING, filename, line, r,
917 "Weight needs to be in range 0…10000000, ignoring: %" PRIu32, v);
918 return 0;
919 }
920
921 *priority = v;
922 return 0;
923 }
924
925 static int config_parse_size4096(
926 const char *unit,
927 const char *filename,
928 unsigned line,
929 const char *section,
930 unsigned section_line,
931 const char *lvalue,
932 int ltype,
933 const char *rvalue,
934 void *data,
935 void *userdata) {
936
937 uint64_t *sz = data, parsed;
938 int r;
939
940 assert(rvalue);
941 assert(data);
942
943 r = parse_size(rvalue, 1024, &parsed);
944 if (r < 0)
945 return log_syntax(unit, LOG_WARNING, filename, line, r,
946 "Failed to parse size value: %s", rvalue);
947
948 if (ltype > 0)
949 *sz = round_up_size(parsed, 4096);
950 else if (ltype < 0)
951 *sz = round_down_size(parsed, 4096);
952 else
953 *sz = parsed;
954
955 if (*sz != parsed)
956 log_syntax(unit, LOG_NOTICE, filename, line, r, "Rounded %s= size %" PRIu64 " → %" PRIu64 ", a multiple of 4096.", lvalue, parsed, *sz);
957
958 return 0;
959 }
960
961 static int partition_read_definition(Partition *p, const char *path) {
962
963 ConfigTableItem table[] = {
964 { "Partition", "Type", config_parse_type, 0, &p->type_uuid },
965 { "Partition", "Label", config_parse_label, 0, &p->new_label },
966 { "Partition", "UUID", config_parse_id128, 0, &p->new_uuid },
967 { "Partition", "Priority", config_parse_int32, 0, &p->priority },
968 { "Partition", "Weight", config_parse_weight, 0, &p->weight },
969 { "Partition", "PaddingWeight", config_parse_weight, 0, &p->padding_weight },
970 { "Partition", "SizeMinBytes", config_parse_size4096, 1, &p->size_min },
971 { "Partition", "SizeMaxBytes", config_parse_size4096, -1, &p->size_max },
972 { "Partition", "PaddingMinBytes", config_parse_size4096, 1, &p->padding_min },
973 { "Partition", "PaddingMaxBytes", config_parse_size4096, -1, &p->padding_max },
974 { "Partition", "FactoryReset", config_parse_bool, 0, &p->factory_reset },
975 {}
976 };
977 int r;
978
979 r = config_parse(NULL, path, NULL, "Partition\0", config_item_table_lookup, table, CONFIG_PARSE_WARN, p);
980 if (r < 0)
981 return r;
982
983 if (p->size_min != UINT64_MAX && p->size_max != UINT64_MAX && p->size_min > p->size_max)
984 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
985 "SizeMinBytes= larger than SizeMaxBytes=, refusing.");
986
987 if (p->padding_min != UINT64_MAX && p->padding_max != UINT64_MAX && p->padding_min > p->padding_max)
988 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
989 "PaddingMinBytes= larger than PaddingMaxBytes=, refusing.");
990
991 if (sd_id128_is_null(p->type_uuid))
992 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
993 "Type= not defined, refusing.");
994
995 return 0;
996 }
997
998 static int context_read_definitions(
999 Context *context,
1000 const char *directory,
1001 const char *root) {
1002
1003 _cleanup_strv_free_ char **files = NULL;
1004 Partition *last = NULL;
1005 char **f;
1006 int r;
1007
1008 assert(context);
1009
1010 if (directory)
1011 r = conf_files_list_strv(&files, ".conf", NULL, CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, (const char**) STRV_MAKE(directory));
1012 else
1013 r = conf_files_list_strv(&files, ".conf", root, CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, (const char**) CONF_PATHS_STRV("repart.d"));
1014 if (r < 0)
1015 return log_error_errno(r, "Failed to enumerate *.conf files: %m");
1016
1017 STRV_FOREACH(f, files) {
1018 _cleanup_(partition_freep) Partition *p = NULL;
1019
1020 p = partition_new();
1021 if (!p)
1022 return log_oom();
1023
1024 p->definition_path = strdup(*f);
1025 if (!p->definition_path)
1026 return log_oom();
1027
1028 r = partition_read_definition(p, *f);
1029 if (r < 0)
1030 return r;
1031
1032 LIST_INSERT_AFTER(partitions, context->partitions, last, p);
1033 last = TAKE_PTR(p);
1034 context->n_partitions++;
1035 }
1036
1037 return 0;
1038 }
1039
1040 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_context*, fdisk_unref_context);
1041 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_partition*, fdisk_unref_partition);
1042 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_parttype*, fdisk_unref_parttype);
1043 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_table*, fdisk_unref_table);
1044
1045 static int determine_current_padding(
1046 struct fdisk_context *c,
1047 struct fdisk_table *t,
1048 struct fdisk_partition *p,
1049 uint64_t *ret) {
1050
1051 size_t n_partitions;
1052 uint64_t offset, next = UINT64_MAX;
1053
1054 assert(c);
1055 assert(t);
1056 assert(p);
1057
1058 if (!fdisk_partition_has_end(p))
1059 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Partition has no end!");
1060
1061 offset = fdisk_partition_get_end(p);
1062 assert(offset < UINT64_MAX / 512);
1063 offset *= 512;
1064
1065 n_partitions = fdisk_table_get_nents(t);
1066 for (size_t i = 0; i < n_partitions; i++) {
1067 struct fdisk_partition *q;
1068 uint64_t start;
1069
1070 q = fdisk_table_get_partition(t, i);
1071 if (!q)
1072 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read partition metadata: %m");
1073
1074 if (fdisk_partition_is_used(q) <= 0)
1075 continue;
1076
1077 if (!fdisk_partition_has_start(q))
1078 continue;
1079
1080 start = fdisk_partition_get_start(q);
1081 assert(start < UINT64_MAX / 512);
1082 start *= 512;
1083
1084 if (start >= offset && (next == UINT64_MAX || next > start))
1085 next = start;
1086 }
1087
1088 if (next == UINT64_MAX) {
1089 /* No later partition? In that case check the end of the usable area */
1090 next = fdisk_get_last_lba(c);
1091 assert(next < UINT64_MAX);
1092 next++; /* The last LBA is one sector before the end */
1093
1094 assert(next < UINT64_MAX / 512);
1095 next *= 512;
1096
1097 if (offset > next)
1098 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Partition end beyond disk end.");
1099 }
1100
1101 assert(next >= offset);
1102 offset = round_up_size(offset, 4096);
1103 next = round_down_size(next, 4096);
1104
1105 if (next >= offset) /* Check again, rounding might have fucked things up */
1106 *ret = next - offset;
1107 else
1108 *ret = 0;
1109
1110 return 0;
1111 }
1112
1113 static int fdisk_ask_cb(struct fdisk_context *c, struct fdisk_ask *ask, void *data) {
1114 _cleanup_free_ char *ids = NULL;
1115 int r;
1116
1117 if (fdisk_ask_get_type(ask) != FDISK_ASKTYPE_STRING)
1118 return -EINVAL;
1119
1120 ids = new(char, ID128_UUID_STRING_MAX);
1121 if (!ids)
1122 return -ENOMEM;
1123
1124 r = fdisk_ask_string_set_result(ask, id128_to_uuid_string(*(sd_id128_t*) data, ids));
1125 if (r < 0)
1126 return r;
1127
1128 TAKE_PTR(ids);
1129 return 0;
1130 }
1131
1132 static int fdisk_set_disklabel_id_by_uuid(struct fdisk_context *c, sd_id128_t id) {
1133 int r;
1134
1135 r = fdisk_set_ask(c, fdisk_ask_cb, &id);
1136 if (r < 0)
1137 return r;
1138
1139 r = fdisk_set_disklabel_id(c);
1140 if (r < 0)
1141 return r;
1142
1143 return fdisk_set_ask(c, NULL, NULL);
1144 }
1145
1146 #define DISK_UUID_TOKEN "disk-uuid"
1147
1148 static int disk_acquire_uuid(Context *context, sd_id128_t *ret) {
1149 union {
1150 unsigned char md[SHA256_DIGEST_LENGTH];
1151 sd_id128_t id;
1152 } result;
1153
1154 assert(context);
1155 assert(ret);
1156
1157 /* Calculate the HMAC-SHA256 of the string "disk-uuid", keyed off the machine ID. We use the machine
1158 * ID as key (and not as cleartext!) since it's the machine ID we don't want to leak. */
1159
1160 if (!HMAC(EVP_sha256(),
1161 &context->seed, sizeof(context->seed),
1162 (const unsigned char*) DISK_UUID_TOKEN, strlen(DISK_UUID_TOKEN),
1163 result.md, NULL))
1164 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "HMAC-SHA256 calculation failed.");
1165
1166 /* Take the first half, mark it as v4 UUID */
1167 assert_cc(sizeof(result.md) == sizeof(result.id) * 2);
1168 *ret = id128_make_v4_uuid(result.id);
1169 return 0;
1170 }
1171
1172 static int context_load_partition_table(
1173 Context *context,
1174 const char *node,
1175 int *backing_fd) {
1176
1177 _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
1178 _cleanup_(fdisk_unref_tablep) struct fdisk_table *t = NULL;
1179 uint64_t left_boundary = UINT64_MAX, first_lba, last_lba, nsectors;
1180 _cleanup_free_ char *disk_uuid_string = NULL;
1181 bool from_scratch = false;
1182 sd_id128_t disk_uuid;
1183 size_t n_partitions;
1184 int r;
1185
1186 assert(context);
1187 assert(node);
1188 assert(backing_fd);
1189
1190 c = fdisk_new_context();
1191 if (!c)
1192 return log_oom();
1193
1194 /* libfdisk doesn't have an API to operate on arbitrary fds, hence reopen the fd going via the
1195 * /proc/self/fd/ magic path if we have an existing fd. Open the original file otherwise. */
1196 if (*backing_fd < 0)
1197 r = fdisk_assign_device(c, node, arg_dry_run);
1198 else {
1199 char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1200 xsprintf(procfs_path, "/proc/self/fd/%i", *backing_fd);
1201
1202 r = fdisk_assign_device(c, procfs_path, arg_dry_run);
1203 }
1204 if (r < 0)
1205 return log_error_errno(r, "Failed to open device '%s': %m", node);
1206
1207 if (*backing_fd < 0) {
1208 /* If we have no fd referencing the device yet, make a copy of the fd now, so that we have one */
1209 *backing_fd = fcntl(fdisk_get_devfd(c), F_DUPFD_CLOEXEC, 3);
1210 if (*backing_fd < 0)
1211 return log_error_errno(errno, "Failed to duplicate fdisk fd: %m");
1212 }
1213
1214 /* Tell udev not to interfere while we are processing the device */
1215 if (flock(fdisk_get_devfd(c), arg_dry_run ? LOCK_SH : LOCK_EX) < 0)
1216 return log_error_errno(errno, "Failed to lock block device: %m");
1217
1218 switch (arg_empty) {
1219
1220 case EMPTY_REFUSE:
1221 /* Refuse empty disks, insist on an existing GPT partition table */
1222 if (!fdisk_is_labeltype(c, FDISK_DISKLABEL_GPT))
1223 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON), "Disk %s has no GPT disk label, not repartitioning.", node);
1224
1225 break;
1226
1227 case EMPTY_REQUIRE:
1228 /* Require an empty disk, refuse any existing partition table */
1229 r = fdisk_has_label(c);
1230 if (r < 0)
1231 return log_error_errno(r, "Failed to determine whether disk %s has a disk label: %m", node);
1232 if (r > 0)
1233 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON), "Disk %s already has a disk label, refusing.", node);
1234
1235 from_scratch = true;
1236 break;
1237
1238 case EMPTY_ALLOW:
1239 /* Allow both an empty disk and an existing partition table, but only GPT */
1240 r = fdisk_has_label(c);
1241 if (r < 0)
1242 return log_error_errno(r, "Failed to determine whether disk %s has a disk label: %m", node);
1243 if (r > 0) {
1244 if (!fdisk_is_labeltype(c, FDISK_DISKLABEL_GPT))
1245 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON), "Disk %s has non-GPT disk label, not repartitioning.", node);
1246 } else
1247 from_scratch = true;
1248
1249 break;
1250
1251 case EMPTY_FORCE:
1252 case EMPTY_CREATE:
1253 /* Always reinitiaize the disk, don't consider what there was on the disk before */
1254 from_scratch = true;
1255 break;
1256 }
1257
1258 if (from_scratch) {
1259 r = fdisk_enable_wipe(c, true);
1260 if (r < 0)
1261 return log_error_errno(r, "Failed to enable wiping of disk signature: %m");
1262
1263 r = fdisk_create_disklabel(c, "gpt");
1264 if (r < 0)
1265 return log_error_errno(r, "Failed to create GPT disk label: %m");
1266
1267 r = disk_acquire_uuid(context, &disk_uuid);
1268 if (r < 0)
1269 return log_error_errno(r, "Failed to acquire disk GPT uuid: %m");
1270
1271 r = fdisk_set_disklabel_id_by_uuid(c, disk_uuid);
1272 if (r < 0)
1273 return log_error_errno(r, "Failed to set GPT disk label: %m");
1274
1275 goto add_initial_free_area;
1276 }
1277
1278 r = fdisk_get_disklabel_id(c, &disk_uuid_string);
1279 if (r < 0)
1280 return log_error_errno(r, "Failed to get current GPT disk label UUID: %m");
1281
1282 r = sd_id128_from_string(disk_uuid_string, &disk_uuid);
1283 if (r < 0)
1284 return log_error_errno(r, "Failed to parse current GPT disk label UUID: %m");
1285
1286 if (sd_id128_is_null(disk_uuid)) {
1287 r = disk_acquire_uuid(context, &disk_uuid);
1288 if (r < 0)
1289 return log_error_errno(r, "Failed to acquire disk GPT uuid: %m");
1290
1291 r = fdisk_set_disklabel_id(c);
1292 if (r < 0)
1293 return log_error_errno(r, "Failed to set GPT disk label: %m");
1294 }
1295
1296 r = fdisk_get_partitions(c, &t);
1297 if (r < 0)
1298 return log_error_errno(r, "Failed to acquire partition table: %m");
1299
1300 n_partitions = fdisk_table_get_nents(t);
1301 for (size_t i = 0; i < n_partitions; i++) {
1302 _cleanup_free_ char *label_copy = NULL;
1303 Partition *pp, *last = NULL;
1304 struct fdisk_partition *p;
1305 struct fdisk_parttype *pt;
1306 const char *pts, *ids, *label;
1307 uint64_t sz, start;
1308 bool found = false;
1309 sd_id128_t ptid, id;
1310 size_t partno;
1311
1312 p = fdisk_table_get_partition(t, i);
1313 if (!p)
1314 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read partition metadata: %m");
1315
1316 if (fdisk_partition_is_used(p) <= 0)
1317 continue;
1318
1319 if (fdisk_partition_has_start(p) <= 0 ||
1320 fdisk_partition_has_size(p) <= 0 ||
1321 fdisk_partition_has_partno(p) <= 0)
1322 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Found a partition without a position, size or number.");
1323
1324 pt = fdisk_partition_get_type(p);
1325 if (!pt)
1326 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to acquire type of partition: %m");
1327
1328 pts = fdisk_parttype_get_string(pt);
1329 if (!pts)
1330 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to acquire type of partition as string: %m");
1331
1332 r = sd_id128_from_string(pts, &ptid);
1333 if (r < 0)
1334 return log_error_errno(r, "Failed to parse partition type UUID %s: %m", pts);
1335
1336 ids = fdisk_partition_get_uuid(p);
1337 if (!ids)
1338 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Found a partition without a UUID.");
1339
1340 r = sd_id128_from_string(ids, &id);
1341 if (r < 0)
1342 return log_error_errno(r, "Failed to parse partition UUID %s: %m", ids);
1343
1344 label = fdisk_partition_get_name(p);
1345 if (!isempty(label)) {
1346 label_copy = strdup(label);
1347 if (!label_copy)
1348 return log_oom();
1349 }
1350
1351 sz = fdisk_partition_get_size(p);
1352 assert_se(sz <= UINT64_MAX/512);
1353 sz *= 512;
1354
1355 start = fdisk_partition_get_start(p);
1356 assert_se(start <= UINT64_MAX/512);
1357 start *= 512;
1358
1359 partno = fdisk_partition_get_partno(p);
1360
1361 if (left_boundary == UINT64_MAX || left_boundary > start)
1362 left_boundary = start;
1363
1364 /* Assign this existing partition to the first partition of the right type that doesn't have
1365 * an existing one assigned yet. */
1366 LIST_FOREACH(partitions, pp, context->partitions) {
1367 last = pp;
1368
1369 if (!sd_id128_equal(pp->type_uuid, ptid))
1370 continue;
1371
1372 if (!pp->current_partition) {
1373 pp->current_uuid = id;
1374 pp->current_size = sz;
1375 pp->offset = start;
1376 pp->partno = partno;
1377 pp->current_label = TAKE_PTR(label_copy);
1378
1379 pp->current_partition = p;
1380 fdisk_ref_partition(p);
1381
1382 r = determine_current_padding(c, t, p, &pp->current_padding);
1383 if (r < 0)
1384 return r;
1385
1386 if (pp->current_padding > 0) {
1387 r = context_add_free_area(context, pp->current_padding, pp);
1388 if (r < 0)
1389 return r;
1390 }
1391
1392 found = true;
1393 break;
1394 }
1395 }
1396
1397 /* If we have no matching definition, create a new one. */
1398 if (!found) {
1399 _cleanup_(partition_freep) Partition *np = NULL;
1400
1401 np = partition_new();
1402 if (!np)
1403 return log_oom();
1404
1405 np->current_uuid = id;
1406 np->type_uuid = ptid;
1407 np->current_size = sz;
1408 np->offset = start;
1409 np->partno = partno;
1410 np->current_label = TAKE_PTR(label_copy);
1411
1412 np->current_partition = p;
1413 fdisk_ref_partition(p);
1414
1415 r = determine_current_padding(c, t, p, &np->current_padding);
1416 if (r < 0)
1417 return r;
1418
1419 if (np->current_padding > 0) {
1420 r = context_add_free_area(context, np->current_padding, np);
1421 if (r < 0)
1422 return r;
1423 }
1424
1425 LIST_INSERT_AFTER(partitions, context->partitions, last, TAKE_PTR(np));
1426 context->n_partitions++;
1427 }
1428 }
1429
1430 add_initial_free_area:
1431 nsectors = fdisk_get_nsectors(c);
1432 assert(nsectors <= UINT64_MAX/512);
1433 nsectors *= 512;
1434
1435 first_lba = fdisk_get_first_lba(c);
1436 assert(first_lba <= UINT64_MAX/512);
1437 first_lba *= 512;
1438
1439 last_lba = fdisk_get_last_lba(c);
1440 assert(last_lba < UINT64_MAX);
1441 last_lba++;
1442 assert(last_lba <= UINT64_MAX/512);
1443 last_lba *= 512;
1444
1445 assert(last_lba >= first_lba);
1446
1447 if (left_boundary == UINT64_MAX) {
1448 /* No partitions at all? Then the whole disk is up for grabs. */
1449
1450 first_lba = round_up_size(first_lba, 4096);
1451 last_lba = round_down_size(last_lba, 4096);
1452
1453 if (last_lba > first_lba) {
1454 r = context_add_free_area(context, last_lba - first_lba, NULL);
1455 if (r < 0)
1456 return r;
1457 }
1458 } else {
1459 /* Add space left of first partition */
1460 assert(left_boundary >= first_lba);
1461
1462 first_lba = round_up_size(first_lba, 4096);
1463 left_boundary = round_down_size(left_boundary, 4096);
1464 last_lba = round_down_size(last_lba, 4096);
1465
1466 if (left_boundary > first_lba) {
1467 r = context_add_free_area(context, left_boundary - first_lba, NULL);
1468 if (r < 0)
1469 return r;
1470 }
1471 }
1472
1473 context->start = first_lba;
1474 context->end = last_lba;
1475 context->total = nsectors;
1476 context->fdisk_context = TAKE_PTR(c);
1477
1478 return from_scratch;
1479 }
1480
1481 static void context_unload_partition_table(Context *context) {
1482 Partition *p, *next;
1483
1484 assert(context);
1485
1486 LIST_FOREACH_SAFE(partitions, p, next, context->partitions) {
1487
1488 /* Entirely remove partitions that have no configuration */
1489 if (PARTITION_IS_FOREIGN(p)) {
1490 partition_unlink_and_free(context, p);
1491 continue;
1492 }
1493
1494 /* Otherwise drop all data we read off the block device and everything we might have
1495 * calculated based on it */
1496
1497 p->dropped = false;
1498 p->current_size = UINT64_MAX;
1499 p->new_size = UINT64_MAX;
1500 p->current_padding = UINT64_MAX;
1501 p->new_padding = UINT64_MAX;
1502 p->partno = UINT64_MAX;
1503 p->offset = UINT64_MAX;
1504
1505 if (p->current_partition) {
1506 fdisk_unref_partition(p->current_partition);
1507 p->current_partition = NULL;
1508 }
1509
1510 if (p->new_partition) {
1511 fdisk_unref_partition(p->new_partition);
1512 p->new_partition = NULL;
1513 }
1514
1515 p->padding_area = NULL;
1516 p->allocated_to_area = NULL;
1517
1518 p->current_uuid = p->new_uuid = SD_ID128_NULL;
1519 }
1520
1521 context->start = UINT64_MAX;
1522 context->end = UINT64_MAX;
1523 context->total = UINT64_MAX;
1524
1525 if (context->fdisk_context) {
1526 fdisk_unref_context(context->fdisk_context);
1527 context->fdisk_context = NULL;
1528 }
1529
1530 context_free_free_areas(context);
1531 }
1532
1533 static int format_size_change(uint64_t from, uint64_t to, char **ret) {
1534 char format_buffer1[FORMAT_BYTES_MAX], format_buffer2[FORMAT_BYTES_MAX], *buf;
1535
1536 if (from != UINT64_MAX)
1537 format_bytes(format_buffer1, sizeof(format_buffer1), from);
1538 if (to != UINT64_MAX)
1539 format_bytes(format_buffer2, sizeof(format_buffer2), to);
1540
1541 if (from != UINT64_MAX) {
1542 if (from == to || to == UINT64_MAX)
1543 buf = strdup(format_buffer1);
1544 else
1545 buf = strjoin(format_buffer1, " ", special_glyph(SPECIAL_GLYPH_ARROW), " ", format_buffer2);
1546 } else if (to != UINT64_MAX)
1547 buf = strjoin(special_glyph(SPECIAL_GLYPH_ARROW), " ", format_buffer2);
1548 else {
1549 *ret = NULL;
1550 return 0;
1551 }
1552
1553 if (!buf)
1554 return log_oom();
1555
1556 *ret = TAKE_PTR(buf);
1557 return 1;
1558 }
1559
1560 static const char *partition_label(const Partition *p) {
1561 assert(p);
1562
1563 if (p->new_label)
1564 return p->new_label;
1565
1566 if (p->current_label)
1567 return p->current_label;
1568
1569 return gpt_partition_type_uuid_to_string(p->type_uuid);
1570 }
1571
1572 static int context_dump_partitions(Context *context, const char *node) {
1573 _cleanup_(table_unrefp) Table *t = NULL;
1574 uint64_t sum_padding = 0, sum_size = 0;
1575 Partition *p;
1576 int r;
1577
1578 t = table_new("type", "label", "uuid", "file", "node", "offset", "raw size", "size", "raw padding", "padding");
1579 if (!t)
1580 return log_oom();
1581
1582 if (!DEBUG_LOGGING)
1583 (void) table_set_display(t, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4, (size_t) 7, (size_t) 9, (size_t) -1);
1584
1585 (void) table_set_align_percent(t, table_get_cell(t, 0, 4), 100);
1586 (void) table_set_align_percent(t, table_get_cell(t, 0, 5), 100);
1587
1588 LIST_FOREACH(partitions, p, context->partitions) {
1589 _cleanup_free_ char *size_change = NULL, *padding_change = NULL, *partname = NULL;
1590 char uuid_buffer[ID128_UUID_STRING_MAX];
1591 const char *label;
1592
1593 if (p->dropped)
1594 continue;
1595
1596 label = partition_label(p);
1597 partname = p->partno != UINT64_MAX ? fdisk_partname(node, p->partno+1) : NULL;
1598
1599 r = format_size_change(p->current_size, p->new_size, &size_change);
1600 if (r < 0)
1601 return r;
1602
1603 r = format_size_change(p->current_padding, p->new_padding, &padding_change);
1604 if (r < 0)
1605 return r;
1606
1607 if (p->new_size != UINT64_MAX)
1608 sum_size += p->new_size;
1609 if (p->new_padding != UINT64_MAX)
1610 sum_padding += p->new_padding;
1611
1612 r = table_add_many(
1613 t,
1614 TABLE_STRING, gpt_partition_type_uuid_to_string_harder(p->type_uuid, uuid_buffer),
1615 TABLE_STRING, label ?: "-", TABLE_SET_COLOR, label ? NULL : ansi_grey(),
1616 TABLE_UUID, sd_id128_is_null(p->new_uuid) ? p->current_uuid : p->new_uuid,
1617 TABLE_STRING, p->definition_path ? basename(p->definition_path) : "-", TABLE_SET_COLOR, p->definition_path ? NULL : ansi_grey(),
1618 TABLE_STRING, partname ?: "no", TABLE_SET_COLOR, partname ? NULL : ansi_highlight(),
1619 TABLE_UINT64, p->offset,
1620 TABLE_UINT64, p->new_size,
1621 TABLE_STRING, size_change, TABLE_SET_COLOR, !p->partitions_next && sum_size > 0 ? ansi_underline() : NULL,
1622 TABLE_UINT64, p->new_padding,
1623 TABLE_STRING, padding_change, TABLE_SET_COLOR, !p->partitions_next && sum_padding > 0 ? ansi_underline() : NULL);
1624 if (r < 0)
1625 return log_error_errno(r, "Failed to add row to table: %m");
1626 }
1627
1628 if (sum_padding > 0 || sum_size > 0) {
1629 char s[FORMAT_BYTES_MAX];
1630 const char *a, *b;
1631
1632 a = strjoina(special_glyph(SPECIAL_GLYPH_SIGMA), " = ", format_bytes(s, sizeof(s), sum_size));
1633 b = strjoina(special_glyph(SPECIAL_GLYPH_SIGMA), " = ", format_bytes(s, sizeof(s), sum_padding));
1634
1635 r = table_add_many(
1636 t,
1637 TABLE_EMPTY,
1638 TABLE_EMPTY,
1639 TABLE_EMPTY,
1640 TABLE_EMPTY,
1641 TABLE_EMPTY,
1642 TABLE_EMPTY,
1643 TABLE_EMPTY,
1644 TABLE_STRING, a,
1645 TABLE_EMPTY,
1646 TABLE_STRING, b);
1647 if (r < 0)
1648 return log_error_errno(r, "Failed to add row to table: %m");
1649 }
1650
1651 r = table_print(t, stdout);
1652 if (r < 0)
1653 return log_error_errno(r, "Failed to dump table: %m");
1654
1655 return 0;
1656 }
1657
1658 static void context_bar_char_process_partition(
1659 Context *context,
1660 Partition *bar[],
1661 size_t n,
1662 Partition *p,
1663 size_t *ret_start) {
1664
1665 uint64_t from, to, total;
1666 size_t x, y;
1667
1668 assert(context);
1669 assert(bar);
1670 assert(n > 0);
1671 assert(p);
1672
1673 if (p->dropped)
1674 return;
1675
1676 assert(p->offset != UINT64_MAX);
1677 assert(p->new_size != UINT64_MAX);
1678
1679 from = p->offset;
1680 to = from + p->new_size;
1681
1682 assert(context->end >= context->start);
1683 total = context->end - context->start;
1684
1685 assert(from >= context->start);
1686 assert(from <= context->end);
1687 x = (from - context->start) * n / total;
1688
1689 assert(to >= context->start);
1690 assert(to <= context->end);
1691 y = (to - context->start) * n / total;
1692
1693 assert(x <= y);
1694 assert(y <= n);
1695
1696 for (size_t i = x; i < y; i++)
1697 bar[i] = p;
1698
1699 *ret_start = x;
1700 }
1701
1702 static int partition_hint(const Partition *p, const char *node, char **ret) {
1703 _cleanup_free_ char *buf = NULL;
1704 char ids[ID128_UUID_STRING_MAX];
1705 const char *label;
1706 sd_id128_t id;
1707
1708 /* Tries really hard to find a suitable description for this partition */
1709
1710 if (p->definition_path) {
1711 buf = strdup(basename(p->definition_path));
1712 goto done;
1713 }
1714
1715 label = partition_label(p);
1716 if (!isempty(label)) {
1717 buf = strdup(label);
1718 goto done;
1719 }
1720
1721 if (p->partno != UINT64_MAX) {
1722 buf = fdisk_partname(node, p->partno+1);
1723 goto done;
1724 }
1725
1726 if (!sd_id128_is_null(p->new_uuid))
1727 id = p->new_uuid;
1728 else if (!sd_id128_is_null(p->current_uuid))
1729 id = p->current_uuid;
1730 else
1731 id = p->type_uuid;
1732
1733 buf = strdup(id128_to_uuid_string(id, ids));
1734
1735 done:
1736 if (!buf)
1737 return -ENOMEM;
1738
1739 *ret = TAKE_PTR(buf);
1740 return 0;
1741 }
1742
1743 static int context_dump_partition_bar(Context *context, const char *node) {
1744 _cleanup_free_ Partition **bar = NULL;
1745 _cleanup_free_ size_t *start_array = NULL;
1746 Partition *p, *last = NULL;
1747 bool z = false;
1748 size_t c, j = 0;
1749
1750 assert_se((c = columns()) >= 2);
1751 c -= 2; /* We do not use the leftmost and rightmost character cell */
1752
1753 bar = new0(Partition*, c);
1754 if (!bar)
1755 return log_oom();
1756
1757 start_array = new(size_t, context->n_partitions);
1758 if (!start_array)
1759 return log_oom();
1760
1761 LIST_FOREACH(partitions, p, context->partitions)
1762 context_bar_char_process_partition(context, bar, c, p, start_array + j++);
1763
1764 putc(' ', stdout);
1765
1766 for (size_t i = 0; i < c; i++) {
1767 if (bar[i]) {
1768 if (last != bar[i])
1769 z = !z;
1770
1771 fputs(z ? ansi_green() : ansi_yellow(), stdout);
1772 fputs(special_glyph(SPECIAL_GLYPH_DARK_SHADE), stdout);
1773 } else {
1774 fputs(ansi_normal(), stdout);
1775 fputs(special_glyph(SPECIAL_GLYPH_LIGHT_SHADE), stdout);
1776 }
1777
1778 last = bar[i];
1779 }
1780
1781 fputs(ansi_normal(), stdout);
1782 putc('\n', stdout);
1783
1784 for (size_t i = 0; i < context->n_partitions; i++) {
1785 _cleanup_free_ char **line = NULL;
1786
1787 line = new0(char*, c);
1788 if (!line)
1789 return log_oom();
1790
1791 j = 0;
1792 LIST_FOREACH(partitions, p, context->partitions) {
1793 _cleanup_free_ char *d = NULL;
1794 j++;
1795
1796 if (i < context->n_partitions - j) {
1797
1798 if (line[start_array[j-1]]) {
1799 const char *e;
1800
1801 /* Upgrade final corner to the right with a branch to the right */
1802 e = startswith(line[start_array[j-1]], special_glyph(SPECIAL_GLYPH_TREE_RIGHT));
1803 if (e) {
1804 d = strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH), e);
1805 if (!d)
1806 return log_oom();
1807 }
1808 }
1809
1810 if (!d) {
1811 d = strdup(special_glyph(SPECIAL_GLYPH_TREE_VERTICAL));
1812 if (!d)
1813 return log_oom();
1814 }
1815
1816 } else if (i == context->n_partitions - j) {
1817 _cleanup_free_ char *hint = NULL;
1818
1819 (void) partition_hint(p, node, &hint);
1820
1821 if (streq_ptr(line[start_array[j-1]], special_glyph(SPECIAL_GLYPH_TREE_VERTICAL)))
1822 d = strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH), " ", strna(hint));
1823 else
1824 d = strjoin(special_glyph(SPECIAL_GLYPH_TREE_RIGHT), " ", strna(hint));
1825
1826 if (!d)
1827 return log_oom();
1828 }
1829
1830 if (d)
1831 free_and_replace(line[start_array[j-1]], d);
1832 }
1833
1834 putc(' ', stdout);
1835
1836 j = 0;
1837 while (j < c) {
1838 if (line[j]) {
1839 fputs(line[j], stdout);
1840 j += utf8_console_width(line[j]);
1841 } else {
1842 putc(' ', stdout);
1843 j++;
1844 }
1845 }
1846
1847 putc('\n', stdout);
1848
1849 for (j = 0; j < c; j++)
1850 free(line[j]);
1851 }
1852
1853 return 0;
1854 }
1855
1856 static bool context_changed(const Context *context) {
1857 Partition *p;
1858
1859 LIST_FOREACH(partitions, p, context->partitions) {
1860 if (p->dropped)
1861 continue;
1862
1863 if (p->allocated_to_area)
1864 return true;
1865
1866 if (p->new_size != p->current_size)
1867 return true;
1868 }
1869
1870 return false;
1871 }
1872
1873 static int context_wipe_partition(Context *context, Partition *p) {
1874 _cleanup_(blkid_free_probep) blkid_probe probe = NULL;
1875 int r;
1876
1877 assert(context);
1878 assert(p);
1879 assert(!PARTITION_EXISTS(p)); /* Safety check: never wipe existing partitions */
1880
1881 probe = blkid_new_probe();
1882 if (!probe)
1883 return log_oom();
1884
1885 assert(p->offset != UINT64_MAX);
1886 assert(p->new_size != UINT64_MAX);
1887
1888 errno = 0;
1889 r = blkid_probe_set_device(probe, fdisk_get_devfd(context->fdisk_context), p->offset, p->new_size);
1890 if (r < 0)
1891 return log_error_errno(errno ?: SYNTHETIC_ERRNO(EIO), "Failed to allocate device probe for partition %" PRIu64 ".", p->partno);
1892
1893 errno = 0;
1894 if (blkid_probe_enable_superblocks(probe, true) < 0 ||
1895 blkid_probe_set_superblocks_flags(probe, BLKID_SUBLKS_MAGIC|BLKID_SUBLKS_BADCSUM) < 0 ||
1896 blkid_probe_enable_partitions(probe, true) < 0 ||
1897 blkid_probe_set_partitions_flags(probe, BLKID_PARTS_MAGIC) < 0)
1898 return log_error_errno(errno ?: SYNTHETIC_ERRNO(EIO), "Failed to enable superblock and partition probing for partition %" PRIu64 ".", p->partno);
1899
1900 for (;;) {
1901 errno = 0;
1902 r = blkid_do_probe(probe);
1903 if (r < 0)
1904 return log_error_errno(errno ?: SYNTHETIC_ERRNO(EIO), "Failed to probe for file systems.");
1905 if (r > 0)
1906 break;
1907
1908 errno = 0;
1909 if (blkid_do_wipe(probe, false) < 0)
1910 return log_error_errno(errno ?: SYNTHETIC_ERRNO(EIO), "Failed to wipe file system signature.");
1911 }
1912
1913 log_info("Successfully wiped file system signatures from partition %" PRIu64 ".", p->partno);
1914 return 0;
1915 }
1916
1917 static int context_discard_range(Context *context, uint64_t offset, uint64_t size) {
1918 struct stat st;
1919 int fd;
1920
1921 assert(context);
1922 assert(offset != UINT64_MAX);
1923 assert(size != UINT64_MAX);
1924
1925 if (size <= 0)
1926 return 0;
1927
1928 assert_se((fd = fdisk_get_devfd(context->fdisk_context)) >= 0);
1929
1930 if (fstat(fd, &st) < 0)
1931 return -errno;
1932
1933 if (S_ISREG(st.st_mode)) {
1934 if (fallocate(fd, FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE, offset, size) < 0) {
1935 if (ERRNO_IS_NOT_SUPPORTED(errno))
1936 return -EOPNOTSUPP;
1937
1938 return -errno;
1939 }
1940
1941 return 1;
1942 }
1943
1944 if (S_ISBLK(st.st_mode)) {
1945 uint64_t range[2], end;
1946
1947 range[0] = round_up_size(offset, 512);
1948
1949 end = offset + size;
1950 if (end <= range[0])
1951 return 0;
1952
1953 range[1] = round_down_size(end - range[0], 512);
1954 if (range[1] <= 0)
1955 return 0;
1956
1957 if (ioctl(fd, BLKDISCARD, range) < 0) {
1958 if (ERRNO_IS_NOT_SUPPORTED(errno))
1959 return -EOPNOTSUPP;
1960
1961 return -errno;
1962 }
1963
1964 return 1;
1965 }
1966
1967 return -EOPNOTSUPP;
1968 }
1969
1970 static int context_discard_partition(Context *context, Partition *p) {
1971 int r;
1972
1973 assert(context);
1974 assert(p);
1975
1976 assert(p->offset != UINT64_MAX);
1977 assert(p->new_size != UINT64_MAX);
1978 assert(!PARTITION_EXISTS(p)); /* Safety check: never discard existing partitions */
1979
1980 if (!arg_discard)
1981 return 0;
1982
1983 r = context_discard_range(context, p->offset, p->new_size);
1984 if (r == -EOPNOTSUPP) {
1985 log_info("Storage does not support discarding, not discarding data in new partition %" PRIu64 ".", p->partno);
1986 return 0;
1987 }
1988 if (r == 0) {
1989 log_info("Partition %" PRIu64 " too short for discard, skipping.", p->partno);
1990 return 0;
1991 }
1992 if (r < 0)
1993 return log_error_errno(r, "Failed to discard data for new partition %" PRIu64 ".", p->partno);
1994
1995 log_info("Successfully discarded data from partition %" PRIu64 ".", p->partno);
1996 return 1;
1997 }
1998
1999 static int context_discard_gap_after(Context *context, Partition *p) {
2000 uint64_t gap, next = UINT64_MAX;
2001 Partition *q;
2002 int r;
2003
2004 assert(context);
2005 assert(!p || (p->offset != UINT64_MAX && p->new_size != UINT64_MAX));
2006
2007 if (p)
2008 gap = p->offset + p->new_size;
2009 else
2010 gap = context->start;
2011
2012 LIST_FOREACH(partitions, q, context->partitions) {
2013 if (q->dropped)
2014 continue;
2015
2016 assert(q->offset != UINT64_MAX);
2017 assert(q->new_size != UINT64_MAX);
2018
2019 if (q->offset < gap)
2020 continue;
2021
2022 if (next == UINT64_MAX || q->offset < next)
2023 next = q->offset;
2024 }
2025
2026 if (next == UINT64_MAX) {
2027 next = context->end;
2028 if (gap > next)
2029 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Partition end beyond disk end.");
2030 }
2031
2032 assert(next >= gap);
2033 r = context_discard_range(context, gap, next - gap);
2034 if (r == -EOPNOTSUPP) {
2035 if (p)
2036 log_info("Storage does not support discarding, not discarding gap after partition %" PRIu64 ".", p->partno);
2037 else
2038 log_info("Storage does not support discarding, not discarding gap at beginning of disk.");
2039 return 0;
2040 }
2041 if (r == 0) /* Too short */
2042 return 0;
2043 if (r < 0) {
2044 if (p)
2045 return log_error_errno(r, "Failed to discard gap after partition %" PRIu64 ".", p->partno);
2046 else
2047 return log_error_errno(r, "Failed to discard gap at beginning of disk.");
2048 }
2049
2050 if (p)
2051 log_info("Successfully discarded gap after partition %" PRIu64 ".", p->partno);
2052 else
2053 log_info("Successfully discarded gap at beginning of disk.");
2054
2055 return 0;
2056 }
2057
2058 static int context_wipe_and_discard(Context *context, bool from_scratch) {
2059 Partition *p;
2060 int r;
2061
2062 assert(context);
2063
2064 /* Wipe and discard the contents of all partitions we are about to create. We skip the discarding if
2065 * we were supposed to start from scratch anyway, as in that case we just discard the whole block
2066 * device in one go early on. */
2067
2068 LIST_FOREACH(partitions, p, context->partitions) {
2069
2070 if (!p->allocated_to_area)
2071 continue;
2072
2073 if (!from_scratch) {
2074 r = context_discard_partition(context, p);
2075 if (r < 0)
2076 return r;
2077 }
2078
2079 r = context_wipe_partition(context, p);
2080 if (r < 0)
2081 return r;
2082
2083 if (!from_scratch) {
2084 r = context_discard_gap_after(context, p);
2085 if (r < 0)
2086 return r;
2087 }
2088 }
2089
2090 if (!from_scratch) {
2091 r = context_discard_gap_after(context, NULL);
2092 if (r < 0)
2093 return r;
2094 }
2095
2096 return 0;
2097 }
2098
2099 static int partition_acquire_uuid(Context *context, Partition *p, sd_id128_t *ret) {
2100 struct {
2101 sd_id128_t type_uuid;
2102 uint64_t counter;
2103 } _packed_ plaintext = {};
2104 union {
2105 unsigned char md[SHA256_DIGEST_LENGTH];
2106 sd_id128_t id;
2107 } result;
2108
2109 uint64_t k = 0;
2110 Partition *q;
2111 int r;
2112
2113 assert(context);
2114 assert(p);
2115 assert(ret);
2116
2117 /* Calculate a good UUID for the indicated partition. We want a certain degree of reproducibility,
2118 * hence we won't generate the UUIDs randomly. Instead we use a cryptographic hash (precisely:
2119 * HMAC-SHA256) to derive them from a single seed. The seed is generally the machine ID of the
2120 * installation we are processing, but if random behaviour is desired can be random, too. We use the
2121 * seed value as key for the HMAC (since the machine ID is something we generally don't want to leak)
2122 * and the partition type as plaintext. The partition type is suffixed with a counter (only for the
2123 * second and later partition of the same type) if we have more than one partition of the same
2124 * time. Or in other words:
2125 *
2126 * With:
2127 * SEED := /etc/machine-id
2128 *
2129 * If first partition instance of type TYPE_UUID:
2130 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID)
2131 *
2132 * For all later partition instances of type TYPE_UUID with INSTANCE being the LE64 encoded instance number:
2133 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID || INSTANCE)
2134 */
2135
2136 LIST_FOREACH(partitions, q, context->partitions) {
2137 if (p == q)
2138 break;
2139
2140 if (!sd_id128_equal(p->type_uuid, q->type_uuid))
2141 continue;
2142
2143 k++;
2144 }
2145
2146 plaintext.type_uuid = p->type_uuid;
2147 plaintext.counter = htole64(k);
2148
2149 if (!HMAC(EVP_sha256(),
2150 &context->seed, sizeof(context->seed),
2151 (const unsigned char*) &plaintext, k == 0 ? sizeof(sd_id128_t) : sizeof(plaintext),
2152 result.md, NULL))
2153 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "SHA256 calculation failed.");
2154
2155 /* Take the first half, mark it as v4 UUID */
2156 assert_cc(sizeof(result.md) == sizeof(result.id) * 2);
2157 result.id = id128_make_v4_uuid(result.id);
2158
2159 /* Ensure this partition UUID is actually unique, and there's no remaining partition from an earlier run? */
2160 LIST_FOREACH(partitions, q, context->partitions) {
2161 if (p == q)
2162 continue;
2163
2164 if (sd_id128_equal(q->current_uuid, result.id) ||
2165 sd_id128_equal(q->new_uuid, result.id)) {
2166 log_warning("Partition UUID calculated from seed for partition %" PRIu64 " exists already, reverting to randomized UUID.", p->partno);
2167
2168 r = sd_id128_randomize(&result.id);
2169 if (r < 0)
2170 return log_error_errno(r, "Failed to generate randomized UUID: %m");
2171
2172 break;
2173 }
2174 }
2175
2176 *ret = result.id;
2177 return 0;
2178 }
2179
2180 static int partition_acquire_label(Context *context, Partition *p, char **ret) {
2181 _cleanup_free_ char *label = NULL;
2182 const char *prefix;
2183 unsigned k = 1;
2184
2185 assert(context);
2186 assert(p);
2187 assert(ret);
2188
2189 prefix = gpt_partition_type_uuid_to_string(p->type_uuid);
2190 if (!prefix)
2191 prefix = "linux";
2192
2193 for (;;) {
2194 const char *ll = label ?: prefix;
2195 bool retry = false;
2196 Partition *q;
2197
2198 LIST_FOREACH(partitions, q, context->partitions) {
2199 if (p == q)
2200 break;
2201
2202 if (streq_ptr(ll, q->current_label) ||
2203 streq_ptr(ll, q->new_label)) {
2204 retry = true;
2205 break;
2206 }
2207 }
2208
2209 if (!retry)
2210 break;
2211
2212 label = mfree(label);
2213
2214
2215 if (asprintf(&label, "%s-%u", prefix, ++k) < 0)
2216 return log_oom();
2217 }
2218
2219 if (!label) {
2220 label = strdup(prefix);
2221 if (!label)
2222 return log_oom();
2223 }
2224
2225 *ret = TAKE_PTR(label);
2226 return 0;
2227 }
2228
2229 static int context_acquire_partition_uuids_and_labels(Context *context) {
2230 Partition *p;
2231 int r;
2232
2233 assert(context);
2234
2235 LIST_FOREACH(partitions, p, context->partitions) {
2236 /* Never touch foreign partitions */
2237 if (PARTITION_IS_FOREIGN(p)) {
2238 p->new_uuid = p->current_uuid;
2239
2240 if (p->current_label) {
2241 free(p->new_label);
2242 p->new_label = strdup(p->current_label);
2243 if (!p->new_label)
2244 return log_oom();
2245 }
2246
2247 continue;
2248 }
2249
2250 if (!sd_id128_is_null(p->current_uuid))
2251 p->new_uuid = p->current_uuid; /* Never change initialized UUIDs */
2252 else if (sd_id128_is_null(p->new_uuid)) {
2253 /* Not explicitly set by user! */
2254 r = partition_acquire_uuid(context, p, &p->new_uuid);
2255 if (r < 0)
2256 return r;
2257 }
2258
2259 if (!isempty(p->current_label)) {
2260 free(p->new_label);
2261 p->new_label = strdup(p->current_label); /* never change initialized labels */
2262 if (!p->new_label)
2263 return log_oom();
2264 } else if (!p->new_label) {
2265 /* Not explicitly set by user! */
2266
2267 r = partition_acquire_label(context, p, &p->new_label);
2268 if (r < 0)
2269 return r;
2270 }
2271 }
2272
2273 return 0;
2274 }
2275
2276 static int device_kernel_partitions_supported(int fd) {
2277 struct loop_info64 info;
2278 struct stat st;
2279
2280 assert(fd >= 0);
2281
2282 if (fstat(fd, &st) < 0)
2283 return log_error_errno(fd, "Failed to fstat() image file: %m");
2284 if (!S_ISBLK(st.st_mode))
2285 return -ENOTBLK; /* we do not log in this one special case about errors */
2286
2287 if (ioctl(fd, LOOP_GET_STATUS64, &info) < 0) {
2288
2289 if (ERRNO_IS_NOT_SUPPORTED(errno) || errno == EINVAL)
2290 return true; /* not a loopback device, let's assume partition are supported */
2291
2292 return log_error_errno(fd, "Failed to issue LOOP_GET_STATUS64 on block device: %m");
2293 }
2294
2295 #if HAVE_VALGRIND_MEMCHECK_H
2296 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
2297 VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
2298 #endif
2299
2300 return FLAGS_SET(info.lo_flags, LO_FLAGS_PARTSCAN);
2301 }
2302
2303 static int context_write_partition_table(
2304 Context *context,
2305 const char *node,
2306 bool from_scratch) {
2307
2308 _cleanup_(fdisk_unref_tablep) struct fdisk_table *original_table = NULL;
2309 int capable, r;
2310 Partition *p;
2311
2312 assert(context);
2313
2314 if (arg_pretty > 0 ||
2315 (arg_pretty < 0 && isatty(STDOUT_FILENO) > 0)) {
2316
2317 if (context->n_partitions == 0)
2318 puts("Empty partition table.");
2319 else
2320 (void) context_dump_partitions(context, node);
2321
2322 putc('\n', stdout);
2323
2324 (void) context_dump_partition_bar(context, node);
2325 putc('\n', stdout);
2326 fflush(stdout);
2327 }
2328
2329 if (!from_scratch && !context_changed(context)) {
2330 log_info("No changes.");
2331 return 0;
2332 }
2333
2334 if (arg_dry_run) {
2335 log_notice("Refusing to repartition, please re-run with --dry-run=no.");
2336 return 0;
2337 }
2338
2339 log_info("Applying changes.");
2340
2341 if (from_scratch) {
2342 r = context_discard_range(context, 0, context->total);
2343 if (r == -EOPNOTSUPP)
2344 log_info("Storage does not support discarding, not discarding entire block device data.");
2345 else if (r < 0)
2346 return log_error_errno(r, "Failed to discard entire block device: %m");
2347 else if (r > 0)
2348 log_info("Discarded entire block device.");
2349 }
2350
2351 r = fdisk_get_partitions(context->fdisk_context, &original_table);
2352 if (r < 0)
2353 return log_error_errno(r, "Failed to acquire partition table: %m");
2354
2355 /* Wipe fs signatures and discard sectors where the new partitions are going to be placed and in the
2356 * gaps between partitions, just to be sure. */
2357 r = context_wipe_and_discard(context, from_scratch);
2358 if (r < 0)
2359 return r;
2360
2361 LIST_FOREACH(partitions, p, context->partitions) {
2362 if (p->dropped)
2363 continue;
2364
2365 assert(p->new_size != UINT64_MAX);
2366 assert(p->offset != UINT64_MAX);
2367 assert(p->partno != UINT64_MAX);
2368
2369 if (PARTITION_EXISTS(p)) {
2370 bool changed = false;
2371
2372 assert(p->current_partition);
2373
2374 if (p->new_size != p->current_size) {
2375 assert(p->new_size >= p->current_size);
2376 assert(p->new_size % 512 == 0);
2377
2378 r = fdisk_partition_size_explicit(p->current_partition, true);
2379 if (r < 0)
2380 return log_error_errno(r, "Failed to enable explicit sizing: %m");
2381
2382 r = fdisk_partition_set_size(p->current_partition, p->new_size / 512);
2383 if (r < 0)
2384 return log_error_errno(r, "Failed to grow partition: %m");
2385
2386 log_info("Growing existing partition %" PRIu64 ".", p->partno);
2387 changed = true;
2388 }
2389
2390 if (!sd_id128_equal(p->new_uuid, p->current_uuid)) {
2391 char buf[ID128_UUID_STRING_MAX];
2392
2393 assert(!sd_id128_is_null(p->new_uuid));
2394
2395 r = fdisk_partition_set_uuid(p->current_partition, id128_to_uuid_string(p->new_uuid, buf));
2396 if (r < 0)
2397 return log_error_errno(r, "Failed to set partition UUID: %m");
2398
2399 log_info("Initializing UUID of existing partition %" PRIu64 ".", p->partno);
2400 changed = true;
2401 }
2402
2403 if (!streq_ptr(p->new_label, p->current_label)) {
2404 assert(!isempty(p->new_label));
2405
2406 r = fdisk_partition_set_name(p->current_partition, p->new_label);
2407 if (r < 0)
2408 return log_error_errno(r, "Failed to set partition label: %m");
2409
2410 log_info("Setting partition label of existing partition %" PRIu64 ".", p->partno);
2411 changed = true;
2412 }
2413
2414 if (changed) {
2415 assert(!PARTITION_IS_FOREIGN(p)); /* never touch foreign partitions */
2416
2417 r = fdisk_set_partition(context->fdisk_context, p->partno, p->current_partition);
2418 if (r < 0)
2419 return log_error_errno(r, "Failed to update partition: %m");
2420 }
2421 } else {
2422 _cleanup_(fdisk_unref_partitionp) struct fdisk_partition *q = NULL;
2423 _cleanup_(fdisk_unref_parttypep) struct fdisk_parttype *t = NULL;
2424 char ids[ID128_UUID_STRING_MAX];
2425
2426 assert(!p->new_partition);
2427 assert(p->offset % 512 == 0);
2428 assert(p->new_size % 512 == 0);
2429 assert(!sd_id128_is_null(p->new_uuid));
2430 assert(!isempty(p->new_label));
2431
2432 t = fdisk_new_parttype();
2433 if (!t)
2434 return log_oom();
2435
2436 r = fdisk_parttype_set_typestr(t, id128_to_uuid_string(p->type_uuid, ids));
2437 if (r < 0)
2438 return log_error_errno(r, "Failed to initialize partition type: %m");
2439
2440 q = fdisk_new_partition();
2441 if (!q)
2442 return log_oom();
2443
2444 r = fdisk_partition_set_type(q, t);
2445 if (r < 0)
2446 return log_error_errno(r, "Failed to set partition type: %m");
2447
2448 r = fdisk_partition_size_explicit(q, true);
2449 if (r < 0)
2450 return log_error_errno(r, "Failed to enable explicit sizing: %m");
2451
2452 r = fdisk_partition_set_start(q, p->offset / 512);
2453 if (r < 0)
2454 return log_error_errno(r, "Failed to position partition: %m");
2455
2456 r = fdisk_partition_set_size(q, p->new_size / 512);
2457 if (r < 0)
2458 return log_error_errno(r, "Failed to grow partition: %m");
2459
2460 r = fdisk_partition_set_partno(q, p->partno);
2461 if (r < 0)
2462 return log_error_errno(r, "Failed to set partition number: %m");
2463
2464 r = fdisk_partition_set_uuid(q, id128_to_uuid_string(p->new_uuid, ids));
2465 if (r < 0)
2466 return log_error_errno(r, "Failed to set partition UUID: %m");
2467
2468 r = fdisk_partition_set_name(q, p->new_label);
2469 if (r < 0)
2470 return log_error_errno(r, "Failed to set partition label: %m");
2471
2472 log_info("Creating new partition %" PRIu64 ".", p->partno);
2473
2474 r = fdisk_add_partition(context->fdisk_context, q, NULL);
2475 if (r < 0)
2476 return log_error_errno(r, "Failed to add partition: %m");
2477
2478 assert(!p->new_partition);
2479 p->new_partition = TAKE_PTR(q);
2480 }
2481 }
2482
2483 log_info("Writing new partition table.");
2484
2485 r = fdisk_write_disklabel(context->fdisk_context);
2486 if (r < 0)
2487 return log_error_errno(r, "Failed to write partition table: %m");
2488
2489 capable = device_kernel_partitions_supported(fdisk_get_devfd(context->fdisk_context));
2490 if (capable == -ENOTBLK)
2491 log_debug("Not telling kernel to reread partition table, since we are not operating on a block device.");
2492 else if (capable < 0)
2493 return capable;
2494 else if (capable > 0) {
2495 log_info("Telling kernel to reread partition table.");
2496
2497 if (from_scratch)
2498 r = fdisk_reread_partition_table(context->fdisk_context);
2499 else
2500 r = fdisk_reread_changes(context->fdisk_context, original_table);
2501 if (r < 0)
2502 return log_error_errno(r, "Failed to reread partition table: %m");
2503 } else
2504 log_notice("Not telling kernel to reread partition table, because selected image does not support kernel partition block devices.");
2505
2506 log_info("All done.");
2507
2508 return 0;
2509 }
2510
2511 static int context_read_seed(Context *context, const char *root) {
2512 int r;
2513
2514 assert(context);
2515
2516 if (!sd_id128_is_null(context->seed))
2517 return 0;
2518
2519 if (!arg_randomize) {
2520 _cleanup_close_ int fd = -1;
2521
2522 fd = chase_symlinks_and_open("/etc/machine-id", root, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC, NULL);
2523 if (fd == -ENOENT)
2524 log_info("No machine ID set, using randomized partition UUIDs.");
2525 else if (fd < 0)
2526 return log_error_errno(fd, "Failed to determine machine ID of image: %m");
2527 else {
2528 r = id128_read_fd(fd, ID128_PLAIN, &context->seed);
2529 if (r == -ENOMEDIUM)
2530 log_info("No machine ID set, using randomized partition UUIDs.");
2531 else if (r < 0)
2532 return log_error_errno(r, "Failed to parse machine ID of image: %m");
2533
2534 return 0;
2535 }
2536 }
2537
2538 r = sd_id128_randomize(&context->seed);
2539 if (r < 0)
2540 return log_error_errno(r, "Failed to generate randomized seed: %m");
2541
2542 return 0;
2543 }
2544
2545 static int context_factory_reset(Context *context, bool from_scratch) {
2546 Partition *p;
2547 size_t n = 0;
2548 int r;
2549
2550 assert(context);
2551
2552 if (arg_factory_reset <= 0)
2553 return 0;
2554
2555 if (from_scratch) /* Nothing to reset if we start from scratch */
2556 return 0;
2557
2558 if (arg_dry_run) {
2559 log_notice("Refusing to factory reset, please re-run with --dry-run=no.");
2560 return 0;
2561 }
2562
2563 log_info("Applying factory reset.");
2564
2565 LIST_FOREACH(partitions, p, context->partitions) {
2566
2567 if (!p->factory_reset || !PARTITION_EXISTS(p))
2568 continue;
2569
2570 assert(p->partno != UINT64_MAX);
2571
2572 log_info("Removing partition %" PRIu64 " for factory reset.", p->partno);
2573
2574 r = fdisk_delete_partition(context->fdisk_context, p->partno);
2575 if (r < 0)
2576 return log_error_errno(r, "Failed to remove partition %" PRIu64 ": %m", p->partno);
2577
2578 n++;
2579 }
2580
2581 if (n == 0) {
2582 log_info("Factory reset requested, but no partitions to delete found.");
2583 return 0;
2584 }
2585
2586 r = fdisk_write_disklabel(context->fdisk_context);
2587 if (r < 0)
2588 return log_error_errno(r, "Failed to write disk label: %m");
2589
2590 log_info("Successfully deleted %zu partitions.", n);
2591 return 1;
2592 }
2593
2594 static int context_can_factory_reset(Context *context) {
2595 Partition *p;
2596
2597 assert(context);
2598
2599 LIST_FOREACH(partitions, p, context->partitions)
2600 if (p->factory_reset && PARTITION_EXISTS(p))
2601 return true;
2602
2603 return false;
2604 }
2605
2606 static int help(void) {
2607 _cleanup_free_ char *link = NULL;
2608 int r;
2609
2610 r = terminal_urlify_man("systemd-repart", "1", &link);
2611 if (r < 0)
2612 return log_oom();
2613
2614 printf("%s [OPTIONS...] [DEVICE]\n"
2615 "\n%sGrow and add partitions to partition table.%s\n\n"
2616 " -h --help Show this help\n"
2617 " --version Show package version\n"
2618 " --dry-run=BOOL Whether to run dry-run operation\n"
2619 " --empty=MODE One of refuse, allow, require, force, create; controls\n"
2620 " how to handle empty disks lacking partition tables\n"
2621 " --discard=BOOL Whether to discard backing blocks for new partitions\n"
2622 " --pretty=BOOL Whether to show pretty summary before executing operation\n"
2623 " --factory-reset=BOOL Whether to remove data partitions before recreating\n"
2624 " them\n"
2625 " --can-factory-reset Test whether factory reset is defined\n"
2626 " --root=PATH Operate relative to root path\n"
2627 " --definitions=DIR Find partitions in specified directory\n"
2628 " --seed=UUID 128bit seed UUID to derive all UUIDs from\n"
2629 " --size=BYTES Grow loopback file to specified size\n"
2630 "\nSee the %s for details.\n"
2631 , program_invocation_short_name
2632 , ansi_highlight(), ansi_normal()
2633 , link
2634 );
2635
2636 return 0;
2637 }
2638
2639 static int parse_argv(int argc, char *argv[]) {
2640
2641 enum {
2642 ARG_VERSION = 0x100,
2643 ARG_DRY_RUN,
2644 ARG_EMPTY,
2645 ARG_DISCARD,
2646 ARG_FACTORY_RESET,
2647 ARG_CAN_FACTORY_RESET,
2648 ARG_ROOT,
2649 ARG_SEED,
2650 ARG_PRETTY,
2651 ARG_DEFINITIONS,
2652 ARG_SIZE,
2653 };
2654
2655 static const struct option options[] = {
2656 { "help", no_argument, NULL, 'h' },
2657 { "version", no_argument, NULL, ARG_VERSION },
2658 { "dry-run", required_argument, NULL, ARG_DRY_RUN },
2659 { "empty", required_argument, NULL, ARG_EMPTY },
2660 { "discard", required_argument, NULL, ARG_DISCARD },
2661 { "factory-reset", required_argument, NULL, ARG_FACTORY_RESET },
2662 { "can-factory-reset", no_argument, NULL, ARG_CAN_FACTORY_RESET },
2663 { "root", required_argument, NULL, ARG_ROOT },
2664 { "seed", required_argument, NULL, ARG_SEED },
2665 { "pretty", required_argument, NULL, ARG_PRETTY },
2666 { "definitions", required_argument, NULL, ARG_DEFINITIONS },
2667 { "size", required_argument, NULL, ARG_SIZE },
2668 {}
2669 };
2670
2671 int c, r, dry_run = -1;
2672
2673 assert(argc >= 0);
2674 assert(argv);
2675
2676 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
2677
2678 switch (c) {
2679
2680 case 'h':
2681 return help();
2682
2683 case ARG_VERSION:
2684 return version();
2685
2686 case ARG_DRY_RUN:
2687 r = parse_boolean(optarg);
2688 if (r < 0)
2689 return log_error_errno(r, "Failed to parse --dry-run= parameter: %s", optarg);
2690
2691 dry_run = r;
2692 break;
2693
2694 case ARG_EMPTY:
2695 if (isempty(optarg) || streq(optarg, "refuse"))
2696 arg_empty = EMPTY_REFUSE;
2697 else if (streq(optarg, "allow"))
2698 arg_empty = EMPTY_ALLOW;
2699 else if (streq(optarg, "require"))
2700 arg_empty = EMPTY_REQUIRE;
2701 else if (streq(optarg, "force"))
2702 arg_empty = EMPTY_FORCE;
2703 else if (streq(optarg, "create")) {
2704 arg_empty = EMPTY_CREATE;
2705
2706 if (dry_run < 0)
2707 dry_run = false; /* Imply --dry-run=no if we create the loopback file
2708 * anew. After all we cannot really break anyone's
2709 * partition tables that way. */
2710 } else
2711 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2712 "Failed to parse --empty= parameter: %s", optarg);
2713 break;
2714
2715 case ARG_DISCARD:
2716 r = parse_boolean(optarg);
2717 if (r < 0)
2718 return log_error_errno(r, "Failed to parse --discard= parameter: %s", optarg);
2719
2720 arg_discard = r;
2721 break;
2722
2723 case ARG_FACTORY_RESET:
2724 r = parse_boolean(optarg);
2725 if (r < 0)
2726 return log_error_errno(r, "Failed to parse --factory-reset= parameter: %s", optarg);
2727
2728 arg_factory_reset = r;
2729 break;
2730
2731 case ARG_CAN_FACTORY_RESET:
2732 arg_can_factory_reset = true;
2733 break;
2734
2735 case ARG_ROOT:
2736 r = parse_path_argument_and_warn(optarg, false, &arg_root);
2737 if (r < 0)
2738 return r;
2739 break;
2740
2741 case ARG_SEED:
2742 if (isempty(optarg)) {
2743 arg_seed = SD_ID128_NULL;
2744 arg_randomize = false;
2745 } else if (streq(optarg, "random"))
2746 arg_randomize = true;
2747 else {
2748 r = sd_id128_from_string(optarg, &arg_seed);
2749 if (r < 0)
2750 return log_error_errno(r, "Failed to parse seed: %s", optarg);
2751
2752 arg_randomize = false;
2753 }
2754
2755 break;
2756
2757 case ARG_PRETTY:
2758 r = parse_boolean(optarg);
2759 if (r < 0)
2760 return log_error_errno(r, "Failed to parse --pretty= parameter: %s", optarg);
2761
2762 arg_pretty = r;
2763 break;
2764
2765 case ARG_DEFINITIONS:
2766 r = parse_path_argument_and_warn(optarg, false, &arg_definitions);
2767 if (r < 0)
2768 return r;
2769 break;
2770
2771 case ARG_SIZE: {
2772 uint64_t parsed, rounded;
2773
2774 r = parse_size(optarg, 1024, &parsed);
2775 if (r < 0)
2776 return log_error_errno(r, "Failed to parse --size= parameter: %s", optarg);
2777
2778 rounded = round_up_size(parsed, 4096);
2779 if (rounded == 0)
2780 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Specified image size too small, refusing.");
2781 if (rounded == UINT64_MAX)
2782 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Specified image size too large, refusing.");
2783
2784 if (rounded != parsed)
2785 log_warning("Specified size is not a multiple of 4096, rounding up automatically. (%" PRIu64 " → %" PRIu64 ")",
2786 parsed, rounded);
2787
2788 arg_size = rounded;
2789 break;
2790 }
2791
2792 case '?':
2793 return -EINVAL;
2794
2795 default:
2796 assert_not_reached("Unhandled option");
2797 }
2798
2799 if (argc - optind > 1)
2800 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2801 "Expected at most one argument, the path to the block device.");
2802
2803 if (arg_factory_reset > 0 && IN_SET(arg_empty, EMPTY_FORCE, EMPTY_REQUIRE, EMPTY_CREATE))
2804 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2805 "Combination of --factory-reset=yes and --empty=force/--empty=require/--empty=create is invalid.");
2806
2807 if (arg_can_factory_reset)
2808 arg_dry_run = true; /* When --can-factory-reset is specified we don't make changes, hence
2809 * non-dry-run mode makes no sense. Thus, imply dry run mode so that we
2810 * open things strictly read-only. */
2811 else if (dry_run >= 0)
2812 arg_dry_run = dry_run;
2813
2814 if (arg_empty == EMPTY_CREATE && arg_size == UINT64_MAX)
2815 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2816 "If --empty=create is specified, --size= must be specified, too.");
2817
2818 arg_node = argc > optind ? argv[optind] : NULL;
2819
2820 if (IN_SET(arg_empty, EMPTY_FORCE, EMPTY_REQUIRE, EMPTY_CREATE) && !arg_node)
2821 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2822 "A path to a device node or loopback file must be specified when --empty=force, --empty=require or --empty=create are used.");
2823
2824 return 1;
2825 }
2826
2827 static int parse_proc_cmdline_factory_reset(void) {
2828 bool b;
2829 int r;
2830
2831 if (arg_factory_reset >= 0) /* Never override what is specified on the process command line */
2832 return 0;
2833
2834 if (!in_initrd()) /* Never honour kernel command line factory reset request outside of the initrd */
2835 return 0;
2836
2837 r = proc_cmdline_get_bool("systemd.factory_reset", &b);
2838 if (r < 0)
2839 return log_error_errno(r, "Failed to parse systemd.factory_reset kernel command line argument: %m");
2840 if (r > 0) {
2841 arg_factory_reset = b;
2842
2843 if (b)
2844 log_notice("Honouring factory reset requested via kernel command line.");
2845 }
2846
2847 return 0;
2848 }
2849
2850 static int parse_efi_variable_factory_reset(void) {
2851 _cleanup_free_ char *value = NULL;
2852 int r;
2853
2854 if (arg_factory_reset >= 0) /* Never override what is specified on the process command line */
2855 return 0;
2856
2857 if (!in_initrd()) /* Never honour EFI variable factory reset request outside of the initrd */
2858 return 0;
2859
2860 r = efi_get_variable_string(EFI_VENDOR_SYSTEMD, "FactoryReset", &value);
2861 if (r == -ENOENT || ERRNO_IS_NOT_SUPPORTED(r))
2862 return 0;
2863 if (r < 0)
2864 return log_error_errno(r, "Failed to read EFI variable FactoryReset: %m");
2865
2866 r = parse_boolean(value);
2867 if (r < 0)
2868 return log_error_errno(r, "Failed to parse EFI variable FactoryReset: %m");
2869
2870 arg_factory_reset = r;
2871 if (r)
2872 log_notice("Honouring factory reset requested via EFI variable FactoryReset: %m");
2873
2874 return 0;
2875 }
2876
2877 static int remove_efi_variable_factory_reset(void) {
2878 int r;
2879
2880 r = efi_set_variable(EFI_VENDOR_SYSTEMD, "FactoryReset", NULL, 0);
2881 if (r == -ENOENT || ERRNO_IS_NOT_SUPPORTED(r))
2882 return 0;
2883 if (r < 0)
2884 return log_error_errno(r, "Failed to remove EFI variable FactoryReset: %m");
2885
2886 log_info("Successfully unset EFI variable FactoryReset.");
2887 return 0;
2888 }
2889
2890 static int acquire_root_devno(const char *p, int mode, char **ret, int *ret_fd) {
2891 _cleanup_close_ int fd = -1;
2892 struct stat st;
2893 dev_t devno, fd_devno = (mode_t) -1;
2894 int r;
2895
2896 assert(p);
2897 assert(ret);
2898 assert(ret_fd);
2899
2900 fd = open(p, mode);
2901 if (fd < 0)
2902 return -errno;
2903
2904 if (fstat(fd, &st) < 0)
2905 return -errno;
2906
2907 if (S_ISREG(st.st_mode)) {
2908 char *s;
2909
2910 s = strdup(p);
2911 if (!s)
2912 return log_oom();
2913
2914 *ret = s;
2915 *ret_fd = TAKE_FD(fd);
2916
2917 return 0;
2918 }
2919
2920 if (S_ISBLK(st.st_mode))
2921 fd_devno = devno = st.st_rdev;
2922 else if (S_ISDIR(st.st_mode)) {
2923
2924 devno = st.st_dev;
2925 if (major(devno) == 0) {
2926 r = btrfs_get_block_device_fd(fd, &devno);
2927 if (r == -ENOTTY) /* not btrfs */
2928 return -ENODEV;
2929 if (r < 0)
2930 return r;
2931 }
2932 } else
2933 return -ENOTBLK;
2934
2935 /* From dm-crypt to backing partition */
2936 r = block_get_originating(devno, &devno);
2937 if (r < 0)
2938 log_debug_errno(r, "Failed to find underlying block device for '%s', ignoring: %m", p);
2939
2940 /* From partition to whole disk containing it */
2941 r = block_get_whole_disk(devno, &devno);
2942 if (r < 0)
2943 log_debug_errno(r, "Failed to find whole disk block device for '%s', ignoring: %m", p);
2944
2945 r = device_path_make_canonical(S_IFBLK, devno, ret);
2946 if (r < 0)
2947 return log_debug_errno(r, "Failed to determine canonical path for '%s': %m", p);
2948
2949 /* Only if we still lock at the same block device we can reuse the fd. Otherwise return an
2950 * invalidated fd. */
2951 *ret_fd = fd_devno != (mode_t) -1 && fd_devno == devno ? TAKE_FD(fd) : -1;
2952 return 0;
2953 }
2954
2955 static int find_root(char **ret, int *ret_fd) {
2956 const char *t;
2957 int r;
2958
2959 assert(ret);
2960 assert(ret_fd);
2961
2962 if (arg_node) {
2963 if (arg_empty == EMPTY_CREATE) {
2964 _cleanup_close_ int fd = -1;
2965 _cleanup_free_ char *s = NULL;
2966
2967 s = strdup(arg_node);
2968 if (!s)
2969 return log_oom();
2970
2971 fd = open(arg_node, O_RDONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOFOLLOW, 0777);
2972 if (fd < 0)
2973 return log_error_errno(errno, "Failed to create '%s': %m", arg_node);
2974
2975 *ret = TAKE_PTR(s);
2976 *ret_fd = TAKE_FD(fd);
2977 return 0;
2978 }
2979
2980 r = acquire_root_devno(arg_node, O_RDONLY|O_CLOEXEC, ret, ret_fd);
2981 if (r < 0)
2982 return log_error_errno(r, "Failed to determine backing device of %s: %m", arg_node);
2983
2984 return 0;
2985 }
2986
2987 assert(IN_SET(arg_empty, EMPTY_REFUSE, EMPTY_ALLOW));
2988
2989 /* Let's search for the root device. We look for two cases here: first in /, and then in /usr. The
2990 * latter we check for cases where / is a tmpfs and only /usr is an actual persistent block device
2991 * (think: volatile setups) */
2992
2993 FOREACH_STRING(t, "/", "/usr") {
2994 _cleanup_free_ char *j = NULL;
2995 const char *p;
2996
2997 if (in_initrd()) {
2998 j = path_join("/sysroot", t);
2999 if (!j)
3000 return log_oom();
3001
3002 p = j;
3003 } else
3004 p = t;
3005
3006 r = acquire_root_devno(p, O_RDONLY|O_DIRECTORY|O_CLOEXEC, ret, ret_fd);
3007 if (r < 0) {
3008 if (r != -ENODEV)
3009 return log_error_errno(r, "Failed to determine backing device of %s: %m", p);
3010 } else
3011 return 0;
3012 }
3013
3014 return log_error_errno(SYNTHETIC_ERRNO(ENODEV), "Failed to discover root block device.");
3015 }
3016
3017 static int resize_backing_fd(const char *node, int *fd) {
3018 char buf1[FORMAT_BYTES_MAX], buf2[FORMAT_BYTES_MAX];
3019 _cleanup_close_ int writable_fd = -1;
3020 struct stat st;
3021 int r;
3022
3023 assert(node);
3024 assert(fd);
3025
3026 if (arg_size == UINT64_MAX) /* Nothing to do */
3027 return 0;
3028
3029 if (*fd < 0) {
3030 /* Open the file if we haven't opened it yet. Note that we open it read-only here, just to
3031 * keep a reference to the file we can pass around. */
3032 *fd = open(node, O_RDONLY|O_CLOEXEC);
3033 if (*fd < 0)
3034 return log_error_errno(errno, "Failed to open '%s' in order to adjust size: %m", node);
3035 }
3036
3037 if (fstat(*fd, &st) < 0)
3038 return log_error_errno(errno, "Failed to stat '%s': %m", node);
3039
3040 r = stat_verify_regular(&st);
3041 if (r < 0)
3042 return log_error_errno(r, "Specified path '%s' is not a regular file, cannot resize: %m", node);
3043
3044 assert_se(format_bytes(buf1, sizeof(buf1), st.st_size));
3045 assert_se(format_bytes(buf2, sizeof(buf2), arg_size));
3046
3047 if ((uint64_t) st.st_size >= arg_size) {
3048 log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)", node, buf1, buf2);
3049 return 0;
3050 }
3051
3052 /* The file descriptor is read-only. In order to grow the file we need to have a writable fd. We
3053 * reopen the file for that temporarily. We keep the writable fd only open for this operation though,
3054 * as fdisk can't accept it anyway. */
3055
3056 writable_fd = fd_reopen(*fd, O_WRONLY|O_CLOEXEC);
3057 if (writable_fd < 0)
3058 return log_error_errno(writable_fd, "Failed to reopen backing file '%s' writable: %m", node);
3059
3060 if (!arg_discard) {
3061 if (fallocate(writable_fd, 0, 0, arg_size) < 0) {
3062 if (!ERRNO_IS_NOT_SUPPORTED(errno))
3063 return log_error_errno(errno, "Failed to grow '%s' from %s to %s by allocation: %m",
3064 node, buf1, buf2);
3065
3066 /* Fallback to truncation, if fallocate() is not supported. */
3067 log_debug("Backing file system does not support fallocate(), falling back to ftruncate().");
3068 } else {
3069 if (st.st_size == 0) /* Likely regular file just created by us */
3070 log_info("Allocated %s for '%s'.", buf2, node);
3071 else
3072 log_info("File '%s' grown from %s to %s by allocation.", node, buf1, buf2);
3073
3074 return 1;
3075 }
3076 }
3077
3078 if (ftruncate(writable_fd, arg_size) < 0)
3079 return log_error_errno(errno, "Failed to grow '%s' from %s to %s by truncation: %m",
3080 node, buf1, buf2);
3081
3082 if (st.st_size == 0) /* Likely regular file just created by us */
3083 log_info("Sized '%s' to %s.", node, buf2);
3084 else
3085 log_info("File '%s' grown from %s to %s by truncation.", node, buf1, buf2);
3086
3087 return 1;
3088 }
3089
3090 static int run(int argc, char *argv[]) {
3091 _cleanup_(context_freep) Context* context = NULL;
3092 _cleanup_free_ char *node = NULL;
3093 _cleanup_close_ int backing_fd = -1;
3094 bool from_scratch;
3095 int r;
3096
3097 log_show_color(true);
3098 log_parse_environment();
3099 log_open();
3100
3101 if (in_initrd()) {
3102 /* Default to operation on /sysroot when invoked in the initrd! */
3103 arg_root = strdup("/sysroot");
3104 if (!arg_root)
3105 return log_oom();
3106 }
3107
3108 r = parse_argv(argc, argv);
3109 if (r <= 0)
3110 return r;
3111
3112 r = parse_proc_cmdline_factory_reset();
3113 if (r < 0)
3114 return r;
3115
3116 r = parse_efi_variable_factory_reset();
3117 if (r < 0)
3118 return r;
3119
3120 context = context_new(arg_seed);
3121 if (!context)
3122 return log_oom();
3123
3124 r = context_read_definitions(context, arg_definitions, arg_root);
3125 if (r < 0)
3126 return r;
3127
3128 if (context->n_partitions <= 0 && arg_empty == EMPTY_REFUSE) {
3129 log_info("Didn't find any partition definition files, nothing to do.");
3130 return 0;
3131 }
3132
3133 r = find_root(&node, &backing_fd);
3134 if (r < 0)
3135 return r;
3136
3137 if (arg_size != UINT64_MAX) {
3138 r = resize_backing_fd(node, &backing_fd);
3139 if (r < 0)
3140 return r;
3141 }
3142
3143 r = context_load_partition_table(context, node, &backing_fd);
3144 if (r == -EHWPOISON)
3145 return 77; /* Special return value which means "Not GPT, so not doing anything". This isn't
3146 * really an error when called at boot. */
3147 if (r < 0)
3148 return r;
3149 from_scratch = r > 0; /* Starting from scratch */
3150
3151 if (arg_can_factory_reset) {
3152 r = context_can_factory_reset(context);
3153 if (r < 0)
3154 return r;
3155 if (r == 0)
3156 return EXIT_FAILURE;
3157
3158 return 0;
3159 }
3160
3161 r = context_factory_reset(context, from_scratch);
3162 if (r < 0)
3163 return r;
3164 if (r > 0) {
3165 /* We actually did a factory reset! */
3166 r = remove_efi_variable_factory_reset();
3167 if (r < 0)
3168 return r;
3169
3170 /* Reload the reduced partition table */
3171 context_unload_partition_table(context);
3172 r = context_load_partition_table(context, node, &backing_fd);
3173 if (r < 0)
3174 return r;
3175 }
3176
3177 #if 0
3178 (void) context_dump_partitions(context, node);
3179 putchar('\n');
3180 #endif
3181
3182 r = context_read_seed(context, arg_root);
3183 if (r < 0)
3184 return r;
3185
3186 /* First try to fit new partitions in, dropping by priority until it fits */
3187 for (;;) {
3188 if (context_allocate_partitions(context))
3189 break; /* Success! */
3190
3191 if (!context_drop_one_priority(context))
3192 return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
3193 "Can't fit requested partitions into free space, refusing.");
3194 }
3195
3196 /* Now assign free space according to the weight logic */
3197 r = context_grow_partitions(context);
3198 if (r < 0)
3199 return r;
3200
3201 /* Now calculate where each partition gets placed */
3202 context_place_partitions(context);
3203
3204 /* Make sure each partition has a unique UUID and unique label */
3205 r = context_acquire_partition_uuids_and_labels(context);
3206 if (r < 0)
3207 return r;
3208
3209 r = context_write_partition_table(context, node, from_scratch);
3210 if (r < 0)
3211 return r;
3212
3213 return 0;
3214 }
3215
3216 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);