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