Debian Codegraph @

src/shared/btrfs-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <linux/btrfs.h>
5 #include <linux/btrfs_tree.h>
6 #include <linux/magic.h>
7 #include <stdio.h>
8 #include <sys/file.h>
9 #include <sys/ioctl.h>
10 #include <sys/sysmacros.h>
11 #include <unistd.h>
12
13 #include "alloc-util.h"
14 #include "btrfs-util.h"
15 #include "chase.h"
16 #include "chattr-util.h"
17 #include "copy.h"
18 #include "errno-util.h"
19 #include "fd-util.h"
20 #include "fs-util.h"
21 #include "log.h"
22 #include "path-util.h"
23 #include "rm-rf.h"
24 #include "sparse-endian.h"
25 #include "stat-util.h"
26 #include "stdio-util.h"
27 #include "string-util.h"
28 #include "time-util.h"
29
30 /* WARNING: Be careful with file system ioctls! When we get an fd, we
31 * need to make sure it either refers to only a regular file or
32 * directory, or that it is located on btrfs, before invoking any
33 * btrfs ioctls. The ioctl numbers are reused by some device drivers
34 * (such as DRM), and hence might have bad effects when invoked on
35 * device nodes (that reference drivers) rather than fds to normal
36 * files or directories. */
37
38 int btrfs_is_subvol_at(int dir_fd, const char *path) {
39 struct stat st;
40
41 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
42
43 /* On btrfs subvolumes always have the inode 256 */
44
45 if (fstatat(dir_fd, strempty(path), &st, isempty(path) ? AT_EMPTY_PATH : 0) < 0)
46 return -errno;
47
48 if (!btrfs_might_be_subvol(&st))
49 return 0;
50
51 return is_fs_type_at(dir_fd, path, BTRFS_SUPER_MAGIC);
52 }
53
54 int btrfs_subvol_set_read_only_at(int dir_fd, const char *path, bool b) {
55 _cleanup_close_ int fd = -EBADF;
56 uint64_t flags, nflags;
57 struct stat st;
58
59 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
60
61 fd = xopenat(dir_fd, path, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
62 if (fd < 0)
63 return fd;
64
65 if (fstat(fd, &st) < 0)
66 return -errno;
67
68 if (!btrfs_might_be_subvol(&st))
69 return -EINVAL;
70
71 if (ioctl(fd, BTRFS_IOC_SUBVOL_GETFLAGS, &flags) < 0)
72 return -errno;
73
74 nflags = UPDATE_FLAG(flags, BTRFS_SUBVOL_RDONLY, b);
75 if (flags == nflags)
76 return 0;
77
78 return RET_NERRNO(ioctl(fd, BTRFS_IOC_SUBVOL_SETFLAGS, &nflags));
79 }
80
81 int btrfs_subvol_get_read_only_fd(int fd) {
82 uint64_t flags;
83 struct stat st;
84
85 assert(fd >= 0);
86
87 if (fstat(fd, &st) < 0)
88 return -errno;
89
90 if (!btrfs_might_be_subvol(&st))
91 return -EINVAL;
92
93 if (ioctl(fd, BTRFS_IOC_SUBVOL_GETFLAGS, &flags) < 0)
94 return -errno;
95
96 return !!(flags & BTRFS_SUBVOL_RDONLY);
97 }
98
99 int btrfs_get_block_device_at_full(int dir_fd, const char *path, uint64_t *ret_devid, char **ret_path, dev_t *ret) {
100 struct btrfs_ioctl_fs_info_args fsi = {};
101 _cleanup_close_ int fd = -EBADF;
102 uint64_t id;
103 int r;
104
105 /*
106 * Returns:
107 * ret_devid - the device id in the filesystem for the returned block device
108 * ret_path - the path to the returned block device
109 * ret - the returned block device
110 */
111
112 assert(wildcard_fd_is_valid(dir_fd));
113
114 fd = xopenat(dir_fd, path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
115 if (fd < 0)
116 return fd;
117
118 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
119 if (r < 0)
120 return r;
121 if (r == 0)
122 return -ENOTTY;
123
124 if (ioctl(fd, BTRFS_IOC_FS_INFO, &fsi) < 0)
125 return -errno;
126
127 /* We won't do this for btrfs RAID */
128 if (fsi.num_devices != 1) {
129 if (ret_devid)
130 *ret_devid = 0;
131 if (ret_path)
132 *ret_path = NULL;
133 if (ret)
134 *ret = 0;
135 return 0;
136 }
137
138 for (id = 1; id <= fsi.max_id; id++) {
139 struct btrfs_ioctl_dev_info_args di = {
140 .devid = id,
141 };
142 struct stat st;
143 _cleanup_free_ char *device_path = NULL;
144
145 if (ioctl(fd, BTRFS_IOC_DEV_INFO, &di) < 0) {
146 if (errno == ENODEV)
147 continue;
148
149 return -errno;
150 }
151
152 /* For the root fs — when no initrd is involved — btrfs returns /dev/root on any kernels from
153 * the past few years. That sucks, as we have no API to determine the actual root then. let's
154 * return an recognizable error for this case, so that the caller can maybe print a nice
155 * message about this.
156 *
157 * https://bugzilla.kernel.org/show_bug.cgi?id=89721 */
158 if (path_equal((char*) di.path, "/dev/root"))
159 return -EUCLEAN;
160
161 if (stat((char*) di.path, &st) < 0)
162 return -errno;
163
164 r = stat_verify_block(&st);
165 if (r < 0)
166 return r;
167
168 if (major(st.st_rdev) == 0)
169 return -ENODEV;
170
171 device_path = strdup((char*) di.path);
172 if (!device_path)
173 return -ENOMEM;
174
175 if (ret_path)
176 *ret_path = TAKE_PTR(device_path);
177 if (ret)
178 *ret = st.st_rdev;
179 if (ret_devid)
180 *ret_devid = id;
181 return 1;
182 }
183
184 return -ENODEV;
185 }
186
187 int btrfs_subvol_get_id_fd(int fd, uint64_t *ret) {
188 struct btrfs_ioctl_ino_lookup_args args = {
189 .objectid = BTRFS_FIRST_FREE_OBJECTID
190 };
191 int r;
192
193 assert(fd >= 0);
194 assert(ret);
195
196 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
197 if (r < 0)
198 return r;
199 if (r == 0)
200 return -ENOTTY;
201
202 if (ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args) < 0)
203 return -errno;
204
205 *ret = args.treeid;
206 return 0;
207 }
208
209 int btrfs_subvol_get_id(int fd, const char *subvol, uint64_t *ret) {
210 _cleanup_close_ int subvol_fd = -EBADF;
211
212 assert(fd >= 0);
213 assert(ret);
214
215 subvol_fd = openat(fd, subvol, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
216 if (subvol_fd < 0)
217 return -errno;
218
219 return btrfs_subvol_get_id_fd(subvol_fd, ret);
220 }
221
222 static bool btrfs_ioctl_search_args_inc(struct btrfs_ioctl_search_args *args) {
223 assert(args);
224
225 /* the objectid, type, offset together make up the btrfs key,
226 * which is considered a single 136byte integer when
227 * comparing. This call increases the counter by one, dealing
228 * with the overflow between the overflows */
229
230 if (args->key.min_offset < UINT64_MAX) {
231 args->key.min_offset++;
232 return true;
233 }
234
235 if (args->key.min_type < UINT8_MAX) {
236 args->key.min_type++;
237 args->key.min_offset = 0;
238 return true;
239 }
240
241 if (args->key.min_objectid < UINT64_MAX) {
242 args->key.min_objectid++;
243 args->key.min_offset = 0;
244 args->key.min_type = 0;
245 return true;
246 }
247
248 return 0;
249 }
250
251 static void btrfs_ioctl_search_args_set(struct btrfs_ioctl_search_args *args, const struct btrfs_ioctl_search_header *h) {
252 assert(args);
253 assert(h);
254
255 args->key.min_objectid = h->objectid;
256 args->key.min_type = h->type;
257 args->key.min_offset = h->offset;
258 }
259
260 static int btrfs_ioctl_search_args_compare(const struct btrfs_ioctl_search_args *args) {
261 int r;
262
263 assert(args);
264
265 /* Compare min and max */
266
267 r = CMP(args->key.min_objectid, args->key.max_objectid);
268 if (r != 0)
269 return r;
270
271 r = CMP(args->key.min_type, args->key.max_type);
272 if (r != 0)
273 return r;
274
275 return CMP(args->key.min_offset, args->key.max_offset);
276 }
277
278 typedef struct BtrfsForeachIterator {
279 const struct btrfs_ioctl_search_args *args;
280 size_t offset;
281 unsigned index;
282 struct btrfs_ioctl_search_header *header;
283 const void **body;
284 } BtrfsForeachIterator;
285
286 static int btrfs_iterate(BtrfsForeachIterator *i) {
287 assert(i);
288 assert(i->args);
289 assert(i->header);
290 assert(i->body);
291
292 if (i->index >= i->args->key.nr_items)
293 return 0; /* end */
294
295 assert_cc(BTRFS_SEARCH_ARGS_BUFSIZE >= sizeof(struct btrfs_ioctl_search_header));
296 if (i->offset > BTRFS_SEARCH_ARGS_BUFSIZE - sizeof(struct btrfs_ioctl_search_header))
297 return -EBADMSG;
298
299 struct btrfs_ioctl_search_header h;
300 memcpy(&h, (const uint8_t*) i->args->buf + i->offset, sizeof(struct btrfs_ioctl_search_header));
301
302 if (i->offset > BTRFS_SEARCH_ARGS_BUFSIZE - sizeof(struct btrfs_ioctl_search_header) - h.len)
303 return -EBADMSG;
304
305 *i->body = (const uint8_t*) i->args->buf + i->offset + sizeof(struct btrfs_ioctl_search_header);
306 *i->header = h;
307 i->offset += sizeof(struct btrfs_ioctl_search_header) + h.len;
308 i->index++;
309
310 return 1;
311 }
312
313 /* Iterates through a series of struct btrfs_file_extent_item elements. They are unfortunately not aligned,
314 * hence we copy out the header from them */
315 #define FOREACH_BTRFS_IOCTL_SEARCH_HEADER(_sh, _body, _args) \
316 for (BtrfsForeachIterator iterator = { \
317 .args = &(_args), \
318 .header = &(_sh), \
319 .body = &(_body), \
320 }; \
321 btrfs_iterate(&iterator) > 0; )
322
323 int btrfs_subvol_get_info_fd(int fd, uint64_t subvol_id, BtrfsSubvolInfo *ret) {
324 int r;
325
326 assert(fd >= 0);
327 assert(ret);
328
329 /* Make sure this works on O_PATH fds */
330 _cleanup_close_ int fd_close = -EBADF;
331 fd = fd_reopen_condition(fd, O_CLOEXEC|O_RDONLY|O_DIRECTORY, O_PATH, &fd_close);
332 if (fd < 0)
333 return fd;
334
335 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
336 if (r < 0)
337 return r;
338 if (r == 0)
339 return -ENOTTY;
340
341 struct btrfs_ioctl_get_subvol_info_args info;
342 if (ioctl(fd, BTRFS_IOC_GET_SUBVOL_INFO, &info) < 0)
343 return -errno;
344
345 *ret = (BtrfsSubvolInfo) {
346 .subvol_id = info.treeid,
347 .otime = info.otime.sec * USEC_PER_SEC + (info.otime.nsec / NSEC_PER_USEC),
348 .ctime = info.ctime.sec * USEC_PER_SEC + (info.ctime.nsec / NSEC_PER_USEC),
349 .read_only = FLAGS_SET(info.flags, BTRFS_SUBVOL_RDONLY),
350 };
351
352 assert_cc(sizeof(info.uuid) == sizeof(sd_id128_t));
353 memcpy(&ret->uuid, info.uuid, sizeof(sd_id128_t));
354
355 assert_cc(sizeof(info.parent_uuid) == sizeof(sd_id128_t));
356 memcpy(&ret->parent_uuid, info.parent_uuid, sizeof(sd_id128_t));
357
358 return 0;
359 }
360
361 int btrfs_qgroup_get_quota_fd(int fd, uint64_t qgroupid, BtrfsQuotaInfo *ret) {
362
363 struct btrfs_ioctl_search_args args = {
364 /* Tree of quota items */
365 .key.tree_id = BTRFS_QUOTA_TREE_OBJECTID,
366
367 /* The object ID is always 0 */
368 .key.min_objectid = 0,
369 .key.max_objectid = 0,
370
371 /* Look precisely for the quota items */
372 .key.min_type = BTRFS_QGROUP_STATUS_KEY,
373 .key.max_type = BTRFS_QGROUP_LIMIT_KEY,
374
375 /* No restrictions on the other components */
376 .key.min_transid = 0,
377 .key.max_transid = UINT64_MAX,
378 };
379
380 bool found_info = false, found_limit = false;
381 int r;
382
383 assert(fd >= 0);
384 assert(ret);
385
386 if (qgroupid == 0) {
387 r = btrfs_subvol_get_id_fd(fd, &qgroupid);
388 if (r < 0)
389 return r;
390 } else {
391 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
392 if (r < 0)
393 return r;
394 if (r == 0)
395 return -ENOTTY;
396 }
397
398 args.key.min_offset = args.key.max_offset = qgroupid;
399
400 while (btrfs_ioctl_search_args_compare(&args) <= 0) {
401 struct btrfs_ioctl_search_header sh;
402 const void *body;
403
404 args.key.nr_items = 256;
405 if (ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args) < 0) {
406 if (errno == ENOENT) /* quota tree is missing: quota disabled */
407 break;
408
409 return -errno;
410 }
411
412 if (args.key.nr_items <= 0)
413 break;
414
415 FOREACH_BTRFS_IOCTL_SEARCH_HEADER(sh, body, args) {
416
417 /* Make sure we start the next search at least from this entry */
418 btrfs_ioctl_search_args_set(&args, &sh);
419
420 if (sh.objectid != 0)
421 continue;
422 if (sh.offset != qgroupid)
423 continue;
424
425 if (sh.type == BTRFS_QGROUP_INFO_KEY) {
426 const struct btrfs_qgroup_info_item *qii = body;
427
428 ret->referenced = le64toh(qii->rfer);
429 ret->exclusive = le64toh(qii->excl);
430
431 found_info = true;
432
433 } else if (sh.type == BTRFS_QGROUP_LIMIT_KEY) {
434 const struct btrfs_qgroup_limit_item *qli = body;
435
436 if (le64toh(qli->flags) & BTRFS_QGROUP_LIMIT_MAX_RFER)
437 ret->referenced_max = le64toh(qli->max_rfer);
438 else
439 ret->referenced_max = UINT64_MAX;
440
441 if (le64toh(qli->flags) & BTRFS_QGROUP_LIMIT_MAX_EXCL)
442 ret->exclusive_max = le64toh(qli->max_excl);
443 else
444 ret->exclusive_max = UINT64_MAX;
445
446 found_limit = true;
447 }
448
449 if (found_info && found_limit)
450 goto finish;
451 }
452
453 /* Increase search key by one, to read the next item, if we can. */
454 if (!btrfs_ioctl_search_args_inc(&args))
455 break;
456 }
457
458 finish:
459 if (!found_limit && !found_info)
460 return -ENODATA;
461
462 if (!found_info) {
463 ret->referenced = UINT64_MAX;
464 ret->exclusive = UINT64_MAX;
465 }
466
467 if (!found_limit) {
468 ret->referenced_max = UINT64_MAX;
469 ret->exclusive_max = UINT64_MAX;
470 }
471
472 return 0;
473 }
474
475 int btrfs_log_dev_root(int level, int ret, const char *p) {
476 return log_full_errno(level, ret,
477 "File system behind %s is reported by btrfs to be backed by pseudo-device /dev/root, which is not a valid userspace accessible device node. "
478 "Cannot determine correct backing block device.", p);
479 }
480
481 int btrfs_qgroup_get_quota(const char *path, uint64_t qgroupid, BtrfsQuotaInfo *ret) {
482 _cleanup_close_ int fd = -EBADF;
483
484 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
485 if (fd < 0)
486 return -errno;
487
488 return btrfs_qgroup_get_quota_fd(fd, qgroupid, ret);
489 }
490
491 int btrfs_subvol_find_subtree_qgroup(int fd, uint64_t subvol_id, uint64_t *ret) {
492 uint64_t level, lowest = UINT64_MAX, lowest_qgroupid = 0;
493 _cleanup_free_ uint64_t *qgroups = NULL;
494 int r, n;
495
496 assert(fd >= 0);
497 assert(ret);
498
499 /* This finds the "subtree" qgroup for a specific
500 * subvolume. This only works for subvolumes that have been
501 * prepared with btrfs_subvol_auto_qgroup_fd() with
502 * insert_intermediary_qgroup=true (or equivalent). For others
503 * it will return the leaf qgroup instead. The two cases may
504 * be distinguished via the return value, which is 1 in case
505 * an appropriate "subtree" qgroup was found, and 0
506 * otherwise. */
507
508 if (subvol_id == 0) {
509 r = btrfs_subvol_get_id_fd(fd, &subvol_id);
510 if (r < 0)
511 return r;
512 }
513
514 r = btrfs_qgroupid_split(subvol_id, &level, NULL);
515 if (r < 0)
516 return r;
517 if (level != 0) /* Input must be a leaf qgroup */
518 return -EINVAL;
519
520 n = btrfs_qgroup_find_parents(fd, subvol_id, &qgroups);
521 if (n < 0)
522 return n;
523
524 for (int i = 0; i < n; i++) {
525 uint64_t id;
526
527 r = btrfs_qgroupid_split(qgroups[i], &level, &id);
528 if (r < 0)
529 return r;
530
531 if (id != subvol_id)
532 continue;
533
534 if (lowest == UINT64_MAX || level < lowest) {
535 lowest_qgroupid = qgroups[i];
536 lowest = level;
537 }
538 }
539
540 if (lowest == UINT64_MAX) {
541 /* No suitable higher-level qgroup found, let's return
542 * the leaf qgroup instead, and indicate that with the
543 * return value. */
544
545 *ret = subvol_id;
546 return 0;
547 }
548
549 *ret = lowest_qgroupid;
550 return 1;
551 }
552
553 int btrfs_subvol_get_subtree_quota_fd(int fd, uint64_t subvol_id, BtrfsQuotaInfo *ret) {
554 uint64_t qgroupid;
555 int r;
556
557 assert(fd >= 0);
558 assert(ret);
559
560 /* This determines the quota data of the qgroup with the
561 * lowest level, that shares the id part with the specified
562 * subvolume. This is useful for determining the quota data
563 * for entire subvolume subtrees, as long as the subtrees have
564 * been set up with btrfs_qgroup_subvol_auto_fd() or in a
565 * compatible way */
566
567 r = btrfs_subvol_find_subtree_qgroup(fd, subvol_id, &qgroupid);
568 if (r < 0)
569 return r;
570
571 return btrfs_qgroup_get_quota_fd(fd, qgroupid, ret);
572 }
573
574 int btrfs_subvol_get_subtree_quota(const char *path, uint64_t subvol_id, BtrfsQuotaInfo *ret) {
575 _cleanup_close_ int fd = -EBADF;
576
577 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
578 if (fd < 0)
579 return -errno;
580
581 return btrfs_subvol_get_subtree_quota_fd(fd, subvol_id, ret);
582 }
583
584 int btrfs_defrag_fd(int fd) {
585 int r;
586
587 assert(fd >= 0);
588
589 r = fd_verify_regular(fd);
590 if (r < 0)
591 return r;
592
593 return RET_NERRNO(ioctl(fd, BTRFS_IOC_DEFRAG, NULL));
594 }
595
596 int btrfs_defrag(const char *p) {
597 _cleanup_close_ int fd = -EBADF;
598
599 fd = open(p, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
600 if (fd < 0)
601 return -errno;
602
603 return btrfs_defrag_fd(fd);
604 }
605
606 int btrfs_quota_enable_fd(int fd, bool b) {
607 struct btrfs_ioctl_quota_ctl_args args = {
608 .cmd = b ? BTRFS_QUOTA_CTL_ENABLE : BTRFS_QUOTA_CTL_DISABLE,
609 };
610 int r;
611
612 assert(fd >= 0);
613
614 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
615 if (r < 0)
616 return r;
617 if (r == 0)
618 return -ENOTTY;
619
620 return RET_NERRNO(ioctl(fd, BTRFS_IOC_QUOTA_CTL, &args));
621 }
622
623 int btrfs_quota_enable(const char *path, bool b) {
624 _cleanup_close_ int fd = -EBADF;
625
626 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
627 if (fd < 0)
628 return -errno;
629
630 return btrfs_quota_enable_fd(fd, b);
631 }
632
633 int btrfs_qgroup_set_limit_fd(int fd, uint64_t qgroupid, uint64_t referenced_max) {
634
635 struct btrfs_ioctl_qgroup_limit_args args = {
636 .lim.max_rfer = referenced_max,
637 .lim.flags = BTRFS_QGROUP_LIMIT_MAX_RFER,
638 };
639 int r;
640
641 assert(fd >= 0);
642
643 if (qgroupid == 0) {
644 r = btrfs_subvol_get_id_fd(fd, &qgroupid);
645 if (r < 0)
646 return r;
647 } else {
648 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
649 if (r < 0)
650 return r;
651 if (r == 0)
652 return -ENOTTY;
653 }
654
655 args.qgroupid = qgroupid;
656
657 for (unsigned c = 0;; c++) {
658 if (ioctl(fd, BTRFS_IOC_QGROUP_LIMIT, &args) < 0) {
659
660 if (errno == EBUSY && c < 10) {
661 (void) btrfs_quota_scan_wait(fd);
662 continue;
663 }
664
665 return -errno;
666 }
667
668 break;
669 }
670
671 return 0;
672 }
673
674 int btrfs_qgroup_set_limit(const char *path, uint64_t qgroupid, uint64_t referenced_max) {
675 _cleanup_close_ int fd = -EBADF;
676
677 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
678 if (fd < 0)
679 return -errno;
680
681 return btrfs_qgroup_set_limit_fd(fd, qgroupid, referenced_max);
682 }
683
684 int btrfs_subvol_set_subtree_quota_limit_fd(int fd, uint64_t subvol_id, uint64_t referenced_max) {
685 uint64_t qgroupid;
686 int r;
687
688 assert(fd >= 0);
689
690 r = btrfs_subvol_find_subtree_qgroup(fd, subvol_id, &qgroupid);
691 if (r < 0)
692 return r;
693
694 return btrfs_qgroup_set_limit_fd(fd, qgroupid, referenced_max);
695 }
696
697 int btrfs_subvol_set_subtree_quota_limit(const char *path, uint64_t subvol_id, uint64_t referenced_max) {
698 _cleanup_close_ int fd = -EBADF;
699
700 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
701 if (fd < 0)
702 return -errno;
703
704 return btrfs_subvol_set_subtree_quota_limit_fd(fd, subvol_id, referenced_max);
705 }
706
707 int btrfs_qgroupid_make(uint64_t level, uint64_t id, uint64_t *ret) {
708 assert(ret);
709
710 if (level >= (UINT64_C(1) << (64 - BTRFS_QGROUP_LEVEL_SHIFT)))
711 return -EINVAL;
712
713 if (id >= (UINT64_C(1) << BTRFS_QGROUP_LEVEL_SHIFT))
714 return -EINVAL;
715
716 *ret = (level << BTRFS_QGROUP_LEVEL_SHIFT) | id;
717 return 0;
718 }
719
720 int btrfs_qgroupid_split(uint64_t qgroupid, uint64_t *level, uint64_t *id) {
721 assert(level || id);
722
723 if (level)
724 *level = qgroupid >> BTRFS_QGROUP_LEVEL_SHIFT;
725
726 if (id)
727 *id = qgroupid & ((UINT64_C(1) << BTRFS_QGROUP_LEVEL_SHIFT) - 1);
728
729 return 0;
730 }
731
732 static int qgroup_create_or_destroy(int fd, bool b, uint64_t qgroupid) {
733
734 struct btrfs_ioctl_qgroup_create_args args = {
735 .create = b,
736 .qgroupid = qgroupid,
737 };
738 int r;
739
740 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
741 if (r < 0)
742 return r;
743 if (r == 0)
744 return -ENOTTY;
745
746 for (unsigned c = 0;; c++) {
747 if (ioctl(fd, BTRFS_IOC_QGROUP_CREATE, &args) < 0) {
748
749 /* On old kernels if quota is not enabled, we get EINVAL. On newer kernels we get
750 * ENOTCONN. Let's always convert this to ENOTCONN to make this recognizable
751 * everywhere the same way. */
752
753 if (IN_SET(errno, EINVAL, ENOTCONN))
754 return -ENOTCONN;
755
756 if (errno == EBUSY && c < 10) {
757 (void) btrfs_quota_scan_wait(fd);
758 continue;
759 }
760
761 return -errno;
762 }
763
764 break;
765 }
766
767 return 0;
768 }
769
770 int btrfs_qgroup_create(int fd, uint64_t qgroupid) {
771 return qgroup_create_or_destroy(fd, true, qgroupid);
772 }
773
774 int btrfs_qgroup_destroy(int fd, uint64_t qgroupid) {
775 return qgroup_create_or_destroy(fd, false, qgroupid);
776 }
777
778 int btrfs_qgroup_destroy_recursive(int fd, uint64_t qgroupid) {
779 _cleanup_free_ uint64_t *qgroups = NULL;
780 uint64_t subvol_id;
781 int n, r;
782
783 /* Destroys the specified qgroup, but unassigns it from all
784 * its parents first. Also, it recursively destroys all
785 * qgroups it is assigned to that have the same id part of the
786 * qgroupid as the specified group. */
787
788 r = btrfs_qgroupid_split(qgroupid, NULL, &subvol_id);
789 if (r < 0)
790 return r;
791
792 n = btrfs_qgroup_find_parents(fd, qgroupid, &qgroups);
793 if (n < 0)
794 return n;
795
796 for (int i = 0; i < n; i++) {
797 uint64_t id;
798
799 r = btrfs_qgroupid_split(qgroups[i], NULL, &id);
800 if (r < 0)
801 return r;
802
803 r = btrfs_qgroup_unassign(fd, qgroupid, qgroups[i]);
804 if (r < 0)
805 return r;
806
807 if (id != subvol_id)
808 continue;
809
810 /* The parent qgroupid shares the same id part with
811 * us? If so, destroy it too. */
812
813 (void) btrfs_qgroup_destroy_recursive(fd, qgroups[i]);
814 }
815
816 return btrfs_qgroup_destroy(fd, qgroupid);
817 }
818
819 int btrfs_quota_scan_start(int fd) {
820 struct btrfs_ioctl_quota_rescan_args args = {};
821
822 assert(fd >= 0);
823
824 return RET_NERRNO(ioctl(fd, BTRFS_IOC_QUOTA_RESCAN, &args));
825 }
826
827 int btrfs_quota_scan_wait(int fd) {
828 assert(fd >= 0);
829
830 return RET_NERRNO(ioctl(fd, BTRFS_IOC_QUOTA_RESCAN_WAIT));
831 }
832
833 int btrfs_quota_scan_ongoing(int fd) {
834 struct btrfs_ioctl_quota_rescan_args args = {};
835
836 assert(fd >= 0);
837
838 if (ioctl(fd, BTRFS_IOC_QUOTA_RESCAN_STATUS, &args) < 0)
839 return -errno;
840
841 return !!args.flags;
842 }
843
844 static int qgroup_assign_or_unassign(int fd, bool b, uint64_t child, uint64_t parent) {
845 struct btrfs_ioctl_qgroup_assign_args args = {
846 .assign = b,
847 .src = child,
848 .dst = parent,
849 };
850 int r;
851
852 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
853 if (r < 0)
854 return r;
855 if (r == 0)
856 return -ENOTTY;
857
858 for (unsigned c = 0;; c++) {
859 r = ioctl(fd, BTRFS_IOC_QGROUP_ASSIGN, &args);
860 if (r < 0) {
861 if (errno == EBUSY && c < 10) {
862 (void) btrfs_quota_scan_wait(fd);
863 continue;
864 }
865
866 return -errno;
867 }
868
869 if (r == 0)
870 return 0;
871
872 /* If the return value is > 0, we need to request a rescan */
873
874 (void) btrfs_quota_scan_start(fd);
875 return 1;
876 }
877 }
878
879 int btrfs_qgroup_assign(int fd, uint64_t child, uint64_t parent) {
880 return qgroup_assign_or_unassign(fd, true, child, parent);
881 }
882
883 int btrfs_qgroup_unassign(int fd, uint64_t child, uint64_t parent) {
884 return qgroup_assign_or_unassign(fd, false, child, parent);
885 }
886
887 static int subvol_remove_children(int fd, const char *subvolume, uint64_t subvol_id, BtrfsRemoveFlags flags) {
888 struct btrfs_ioctl_vol_args vol_args = {};
889 _cleanup_close_ int subvol_fd = -EBADF;
890 bool made_writable = false;
891 int r;
892
893 assert(fd >= 0);
894 assert(subvolume);
895
896 r = fd_verify_directory(fd);
897 if (r < 0)
898 return r;
899
900 subvol_fd = openat(fd, subvolume, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
901 if (subvol_fd < 0)
902 return -errno;
903
904 /* Let's check if this is actually a subvolume. Note that this is mostly redundant, as BTRFS_IOC_SNAP_DESTROY
905 * would fail anyway if it is not. However, it's a good thing to check this ahead of time so that we can return
906 * ENOTTY unconditionally in this case. This is different from the ioctl() which will return EPERM/EACCES if we
907 * don't have the privileges to remove subvolumes, regardless if the specified directory is actually a
908 * subvolume or not. In order to make it easy for callers to cover the "this is not a btrfs subvolume" case
909 * let's prefer ENOTTY over EPERM/EACCES though. */
910 r = btrfs_is_subvol_fd(subvol_fd);
911 if (r < 0)
912 return r;
913 if (r == 0) /* Not a btrfs subvolume */
914 return -ENOTTY;
915
916 /* Before we try anything, attempt VFS rmdir(). For an empty subvolume btrfs_rmdir dispatches
917 * to btrfs_delete_subvolume; for the non-empty case it returns ENOTEMPTY and we fall through
918 * to the destroy ioctl below. */
919 if (unlinkat(fd, subvolume, AT_REMOVEDIR) >= 0)
920 goto finish;
921
922 if (subvol_id == 0) {
923 r = btrfs_subvol_get_id_fd(subvol_fd, &subvol_id);
924 if (r < 0)
925 return r;
926 }
927
928 /* Try the destroy ioctl. Unlike unlinkat() above, this drops the entire subvolume tree, so
929 * regular files inside don't matter; it only returns ENOTEMPTY when there are nested
930 * subvolumes (BTRFS_ROOT_REF_KEY entries), which we then handle below. */
931 strncpy(vol_args.name, subvolume, sizeof(vol_args.name)-1);
932 for (;;) {
933 if (ioctl(fd, BTRFS_IOC_SNAP_DESTROY, &vol_args) >= 0)
934 goto finish;
935
936 /* Without CAP_SYS_ADMIN the kernel runs an inode_permission(MAY_WRITE) check against
937 * the subvolume root, which btrfs_permission() rejects with EROFS for a read-only
938 * subvolume. Clear the RDONLY flag and retry. */
939 if (errno != EROFS || made_writable)
940 break;
941
942 r = btrfs_subvol_set_read_only_fd(subvol_fd, false);
943 if (r < 0)
944 return r;
945 made_writable = true;
946 }
947 if (!(flags & BTRFS_REMOVE_RECURSIVE) || errno != ENOTEMPTY)
948 return -errno;
949
950 /* OK, there are nested subvolumes — enumerate and recurse into them, then retry.
951 * BTRFS_IOC_GET_SUBVOL_ROOTREF and BTRFS_IOC_INO_LOOKUP_USER (kernel 4.18+) enumerate child
952 * subvolumes without requiring CAP_SYS_ADMIN in the initial user namespace, unlike the older
953 * BTRFS_IOC_TREE_SEARCH ioctl. */
954
955 struct btrfs_ioctl_get_subvol_rootref_args rootref_args = {};
956
957 for (;;) {
958 /* BTRFS_IOC_GET_SUBVOL_ROOTREF returns up to BTRFS_MAX_ROOTREF_BUFFER_NUM entries per
959 * call. If more are available, it returns -EOVERFLOW with num_items filled in and
960 * min_treeid advanced so we can resume on the next iteration. */
961 int ioctl_ret = ioctl(subvol_fd, BTRFS_IOC_GET_SUBVOL_ROOTREF, &rootref_args);
962 if (ioctl_ret < 0 && errno != EOVERFLOW)
963 return -errno;
964
965 for (uint8_t i = 0; i < rootref_args.num_items; i++) {
966 uint64_t child_subvol_id = rootref_args.rootref[i].treeid;
967
968 struct btrfs_ioctl_ino_lookup_user_args lookup_args = {
969 .dirid = rootref_args.rootref[i].dirid,
970 .treeid = child_subvol_id,
971 };
972 if (ioctl(subvol_fd, BTRFS_IOC_INO_LOOKUP_USER, &lookup_args) < 0)
973 return -errno;
974
975 if (!made_writable) {
976 r = btrfs_subvol_set_read_only_fd(subvol_fd, false);
977 if (r < 0)
978 return r;
979
980 made_writable = true;
981 }
982
983 if (isempty(lookup_args.path))
984 /* Subvolume is in the top-level directory of the subvolume. */
985 r = subvol_remove_children(subvol_fd, lookup_args.name, child_subvol_id, flags);
986 else {
987 _cleanup_close_ int child_fd = -EBADF;
988
989 /* Subvolume is somewhere further down, hence we need to open the
990 * containing directory first */
991
992 child_fd = openat(subvol_fd, lookup_args.path, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
993 if (child_fd < 0)
994 return -errno;
995
996 r = subvol_remove_children(child_fd, lookup_args.name, child_subvol_id, flags);
997 }
998 if (r < 0)
999 return r;
1000 }
1001
1002 if (ioctl_ret >= 0)
1003 break;
1004 }
1005
1006 /* OK, the child subvolumes should all be gone now, let's try
1007 * again to remove the subvolume */
1008 if (ioctl(fd, BTRFS_IOC_SNAP_DESTROY, &vol_args) < 0)
1009 return -errno;
1010
1011 finish:
1012 /* for the leaf subvolumes, the qgroup id is identical to the subvol id */
1013 (void) btrfs_qgroup_destroy_recursive(fd, subvol_id);
1014 return 0;
1015 }
1016
1017 int btrfs_subvol_remove_at(int dir_fd, const char *path, BtrfsRemoveFlags flags) {
1018 _cleanup_free_ char *subvolume = NULL;
1019 _cleanup_close_ int fd = -EBADF;
1020 int r;
1021
1022 assert(path);
1023
1024 fd = chase_and_openat(XAT_FDROOT, dir_fd, path, CHASE_PARENT|CHASE_EXTRACT_FILENAME, O_CLOEXEC, &subvolume);
1025 if (fd < 0)
1026 return fd;
1027
1028 r = btrfs_validate_subvolume_name(subvolume);
1029 if (r < 0)
1030 return r;
1031
1032 return subvol_remove_children(fd, subvolume, 0, flags);
1033 }
1034
1035 int btrfs_qgroup_copy_limits(int fd, uint64_t old_qgroupid, uint64_t new_qgroupid) {
1036
1037 struct btrfs_ioctl_search_args args = {
1038 /* Tree of quota items */
1039 .key.tree_id = BTRFS_QUOTA_TREE_OBJECTID,
1040
1041 /* The object ID is always 0 */
1042 .key.min_objectid = 0,
1043 .key.max_objectid = 0,
1044
1045 /* Look precisely for the quota items */
1046 .key.min_type = BTRFS_QGROUP_LIMIT_KEY,
1047 .key.max_type = BTRFS_QGROUP_LIMIT_KEY,
1048
1049 /* For our qgroup */
1050 .key.min_offset = old_qgroupid,
1051 .key.max_offset = old_qgroupid,
1052
1053 /* No restrictions on the other components */
1054 .key.min_transid = 0,
1055 .key.max_transid = UINT64_MAX,
1056 };
1057
1058 int r;
1059
1060 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
1061 if (r < 0)
1062 return r;
1063 if (r == 0)
1064 return -ENOTTY;
1065
1066 while (btrfs_ioctl_search_args_compare(&args) <= 0) {
1067 struct btrfs_ioctl_search_header sh;
1068 const void *body;
1069
1070 args.key.nr_items = 256;
1071 if (ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args) < 0) {
1072 if (errno == ENOENT) /* quota tree missing: quota is not enabled, hence nothing to copy */
1073 break;
1074
1075 return -errno;
1076 }
1077
1078 if (args.key.nr_items <= 0)
1079 break;
1080
1081 FOREACH_BTRFS_IOCTL_SEARCH_HEADER(sh, body, args) {
1082 struct btrfs_ioctl_qgroup_limit_args qargs;
1083 unsigned c;
1084
1085 /* Make sure we start the next search at least from this entry */
1086 btrfs_ioctl_search_args_set(&args, &sh);
1087
1088 if (sh.objectid != 0)
1089 continue;
1090 if (sh.type != BTRFS_QGROUP_LIMIT_KEY)
1091 continue;
1092 if (sh.offset != old_qgroupid)
1093 continue;
1094
1095 /* We found the entry, now copy things over. */
1096
1097 const struct btrfs_qgroup_limit_item *qli = body;
1098 qargs = (struct btrfs_ioctl_qgroup_limit_args) {
1099 .qgroupid = new_qgroupid,
1100
1101 .lim.max_rfer = le64toh(qli->max_rfer),
1102 .lim.max_excl = le64toh(qli->max_excl),
1103 .lim.rsv_rfer = le64toh(qli->rsv_rfer),
1104 .lim.rsv_excl = le64toh(qli->rsv_excl),
1105
1106 .lim.flags = le64toh(qli->flags) & (BTRFS_QGROUP_LIMIT_MAX_RFER|
1107 BTRFS_QGROUP_LIMIT_MAX_EXCL|
1108 BTRFS_QGROUP_LIMIT_RSV_RFER|
1109 BTRFS_QGROUP_LIMIT_RSV_EXCL),
1110 };
1111
1112 for (c = 0;; c++) {
1113 if (ioctl(fd, BTRFS_IOC_QGROUP_LIMIT, &qargs) < 0) {
1114 if (errno == EBUSY && c < 10) {
1115 (void) btrfs_quota_scan_wait(fd);
1116 continue;
1117 }
1118 return -errno;
1119 }
1120
1121 break;
1122 }
1123
1124 return 1;
1125 }
1126
1127 /* Increase search key by one, to read the next item, if we can. */
1128 if (!btrfs_ioctl_search_args_inc(&args))
1129 break;
1130 }
1131
1132 return 0;
1133 }
1134
1135 static int copy_quota_hierarchy(int fd, uint64_t old_subvol_id, uint64_t new_subvol_id) {
1136 _cleanup_free_ uint64_t *old_qgroups = NULL, *old_parent_qgroups = NULL;
1137 bool copy_from_parent = false, insert_intermediary_qgroup = false;
1138 int n_old_qgroups, n_old_parent_qgroups, r;
1139 uint64_t old_parent_id;
1140
1141 assert(fd >= 0);
1142
1143 /* Copies a reduced form of quota information from the old to
1144 * the new subvolume. */
1145
1146 n_old_qgroups = btrfs_qgroup_find_parents(fd, old_subvol_id, &old_qgroups);
1147 if (n_old_qgroups <= 0) /* Nothing to copy */
1148 return n_old_qgroups;
1149
1150 assert(old_qgroups); /* Coverity gets confused by the macro iterator allocating this, add a hint */
1151
1152 r = btrfs_subvol_get_parent(fd, old_subvol_id, &old_parent_id);
1153 if (r == -ENXIO)
1154 /* We have no parent, hence nothing to copy. */
1155 n_old_parent_qgroups = 0;
1156 else if (r < 0)
1157 return r;
1158 else {
1159 n_old_parent_qgroups = btrfs_qgroup_find_parents(fd, old_parent_id, &old_parent_qgroups);
1160 if (n_old_parent_qgroups < 0)
1161 return n_old_parent_qgroups;
1162 }
1163
1164 for (int i = 0; i < n_old_qgroups; i++) {
1165 uint64_t id;
1166
1167 r = btrfs_qgroupid_split(old_qgroups[i], NULL, &id);
1168 if (r < 0)
1169 return r;
1170
1171 if (id == old_subvol_id) {
1172 /* The old subvolume was member of a qgroup
1173 * that had the same id, but a different level
1174 * as it self. Let's set up something similar
1175 * in the destination. */
1176 insert_intermediary_qgroup = true;
1177 break;
1178 }
1179
1180 for (int j = 0; j < n_old_parent_qgroups; j++)
1181 if (old_parent_qgroups[j] == old_qgroups[i])
1182 /* The old subvolume shared a common
1183 * parent qgroup with its parent
1184 * subvolume. Let's set up something
1185 * similar in the destination. */
1186 copy_from_parent = true;
1187 }
1188
1189 if (!insert_intermediary_qgroup && !copy_from_parent)
1190 return 0;
1191
1192 return btrfs_subvol_auto_qgroup_fd(fd, new_subvol_id, insert_intermediary_qgroup);
1193 }
1194
1195 static int copy_subtree_quota_limits(int fd, uint64_t old_subvol, uint64_t new_subvol) {
1196 uint64_t old_subtree_qgroup, new_subtree_qgroup;
1197 bool changed;
1198 int r;
1199
1200 /* First copy the leaf limits */
1201 r = btrfs_qgroup_copy_limits(fd, old_subvol, new_subvol);
1202 if (r < 0)
1203 return r;
1204 changed = r > 0;
1205
1206 /* Then, try to copy the subtree limits, if there are any. */
1207 r = btrfs_subvol_find_subtree_qgroup(fd, old_subvol, &old_subtree_qgroup);
1208 if (r < 0)
1209 return r;
1210 if (r == 0)
1211 return changed;
1212
1213 r = btrfs_subvol_find_subtree_qgroup(fd, new_subvol, &new_subtree_qgroup);
1214 if (r < 0)
1215 return r;
1216 if (r == 0)
1217 return changed;
1218
1219 r = btrfs_qgroup_copy_limits(fd, old_subtree_qgroup, new_subtree_qgroup);
1220 if (r != 0)
1221 return r;
1222
1223 return changed;
1224 }
1225
1226 static int subvol_snapshot_children(
1227 int old_fd,
1228 int new_fd,
1229 const char *subvolume,
1230 uint64_t old_subvol_id,
1231 BtrfsSnapshotFlags flags) {
1232
1233 struct btrfs_ioctl_vol_args_v2 vol_args = {
1234 .flags = flags & BTRFS_SNAPSHOT_READ_ONLY ? BTRFS_SUBVOL_RDONLY : 0,
1235 .fd = old_fd,
1236 };
1237 _cleanup_close_ int subvolume_fd = -EBADF;
1238 uint64_t new_subvol_id;
1239 int r;
1240
1241 assert(old_fd >= 0);
1242 assert(new_fd >= 0);
1243 assert(subvolume);
1244
1245 strncpy(vol_args.name, subvolume, sizeof(vol_args.name)-1);
1246
1247 if (ioctl(new_fd, BTRFS_IOC_SNAP_CREATE_V2, &vol_args) < 0)
1248 return -errno;
1249
1250 if (FLAGS_SET(flags, BTRFS_SNAPSHOT_LOCK_BSD)) {
1251 subvolume_fd = xopenat_lock(new_fd, subvolume,
1252 O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW,
1253 LOCK_BSD,
1254 LOCK_EX);
1255 if (subvolume_fd < 0)
1256 return subvolume_fd;
1257
1258 r = btrfs_is_subvol_fd(subvolume_fd);
1259 if (r < 0)
1260 return r;
1261 if (r == 0)
1262 return -EEXIST;
1263 }
1264
1265 if (!(flags & BTRFS_SNAPSHOT_RECURSIVE) &&
1266 !(flags & BTRFS_SNAPSHOT_QUOTA))
1267 return flags & BTRFS_SNAPSHOT_LOCK_BSD ? TAKE_FD(subvolume_fd) : 0;
1268
1269 if (old_subvol_id == 0) {
1270 r = btrfs_subvol_get_id_fd(old_fd, &old_subvol_id);
1271 if (r < 0)
1272 return r;
1273 }
1274
1275 r = btrfs_subvol_get_id(new_fd, vol_args.name, &new_subvol_id);
1276 if (r < 0)
1277 return r;
1278
1279 if (flags & BTRFS_SNAPSHOT_QUOTA)
1280 (void) copy_quota_hierarchy(new_fd, old_subvol_id, new_subvol_id);
1281
1282 if (!(flags & BTRFS_SNAPSHOT_RECURSIVE)) {
1283
1284 if (flags & BTRFS_SNAPSHOT_QUOTA)
1285 (void) copy_subtree_quota_limits(new_fd, old_subvol_id, new_subvol_id);
1286
1287 return flags & BTRFS_SNAPSHOT_LOCK_BSD ? TAKE_FD(subvolume_fd) : 0;
1288 }
1289
1290 /* Enumerate child subvolumes via BTRFS_IOC_GET_SUBVOL_ROOTREF + BTRFS_IOC_INO_LOOKUP_USER
1291 * (kernel 4.18+), neither of which requires CAP_SYS_ADMIN, unlike BTRFS_IOC_TREE_SEARCH. */
1292
1293 struct btrfs_ioctl_get_subvol_rootref_args rootref_args = {};
1294
1295 for (;;) {
1296 /* BTRFS_IOC_GET_SUBVOL_ROOTREF returns up to BTRFS_MAX_ROOTREF_BUFFER_NUM entries per
1297 * call. If more are available, it returns -EOVERFLOW with num_items filled in and
1298 * min_treeid advanced so we can resume on the next iteration. */
1299 int ioctl_ret = ioctl(old_fd, BTRFS_IOC_GET_SUBVOL_ROOTREF, &rootref_args);
1300 if (ioctl_ret < 0 && errno != EOVERFLOW)
1301 return -errno;
1302
1303 for (uint8_t i = 0; i < rootref_args.num_items; i++) {
1304 _cleanup_free_ char *c = NULL, *np = NULL;
1305 _cleanup_close_ int old_child_fd = -EBADF, new_child_fd = -EBADF;
1306 uint64_t child_subvol_id = rootref_args.rootref[i].treeid;
1307
1308 /* Avoid running into loops if the new subvolume is below the old one. */
1309 if (child_subvol_id == new_subvol_id)
1310 continue;
1311
1312 struct btrfs_ioctl_ino_lookup_user_args lookup_args = {
1313 .dirid = rootref_args.rootref[i].dirid,
1314 .treeid = child_subvol_id,
1315 };
1316 if (ioctl(old_fd, BTRFS_IOC_INO_LOOKUP_USER, &lookup_args) < 0)
1317 return -errno;
1318
1319 c = path_join(lookup_args.path, lookup_args.name);
1320 if (!c)
1321 return -ENOMEM;
1322
1323 old_child_fd = openat(old_fd, c, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
1324 if (old_child_fd < 0)
1325 return -errno;
1326
1327 np = path_join(subvolume, lookup_args.path);
1328 if (!np)
1329 return -ENOMEM;
1330
1331 new_child_fd = openat(new_fd, np, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
1332 if (new_child_fd < 0)
1333 return -errno;
1334
1335 if (flags & BTRFS_SNAPSHOT_READ_ONLY) {
1336 /* If the snapshot is read-only we need to mark it writable temporarily, to
1337 * put the subsnapshot into place. */
1338
1339 if (subvolume_fd < 0) {
1340 subvolume_fd = openat(new_fd, subvolume, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
1341 if (subvolume_fd < 0)
1342 return -errno;
1343 }
1344
1345 r = btrfs_subvol_set_read_only_fd(subvolume_fd, false);
1346 if (r < 0)
1347 return r;
1348 }
1349
1350 /* When btrfs clones the subvolumes, child subvolumes appear as empty
1351 * directories. Remove them, so that we can create a new snapshot in their place */
1352 if (unlinkat(new_child_fd, lookup_args.name, AT_REMOVEDIR) < 0) {
1353 int k = -errno;
1354
1355 if (flags & BTRFS_SNAPSHOT_READ_ONLY)
1356 (void) btrfs_subvol_set_read_only_fd(subvolume_fd, true);
1357
1358 return k;
1359 }
1360
1361 r = subvol_snapshot_children(old_child_fd, new_child_fd, lookup_args.name, child_subvol_id,
1362 flags & ~(BTRFS_SNAPSHOT_FALLBACK_COPY|BTRFS_SNAPSHOT_LOCK_BSD));
1363
1364 /* Restore the readonly flag */
1365 if (flags & BTRFS_SNAPSHOT_READ_ONLY) {
1366 int k;
1367
1368 k = btrfs_subvol_set_read_only_fd(subvolume_fd, true);
1369 if (r >= 0 && k < 0)
1370 return k;
1371 }
1372
1373 if (r < 0)
1374 return r;
1375 }
1376
1377 if (ioctl_ret >= 0)
1378 break;
1379 }
1380
1381 if (flags & BTRFS_SNAPSHOT_QUOTA)
1382 (void) copy_subtree_quota_limits(new_fd, old_subvol_id, new_subvol_id);
1383
1384 return flags & BTRFS_SNAPSHOT_LOCK_BSD ? TAKE_FD(subvolume_fd) : 0;
1385 }
1386
1387 int btrfs_subvol_snapshot_at_full(
1388 int dir_fdf,
1389 const char *from,
1390 int dir_fdt,
1391 const char *to,
1392 BtrfsSnapshotFlags flags,
1393 copy_progress_path_t progress_path,
1394 copy_progress_bytes_t progress_bytes,
1395 void *userdata) {
1396
1397 _cleanup_free_ char *subvolume = NULL;
1398 _cleanup_close_ int old_fd = -EBADF, new_fd = -EBADF, subvolume_fd = -EBADF;
1399 int r;
1400
1401 assert(dir_fdf >= 0 || dir_fdf == AT_FDCWD);
1402 assert(dir_fdt >= 0 || dir_fdt == AT_FDCWD);
1403 assert(to);
1404
1405 old_fd = xopenat(dir_fdf, from, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
1406 if (old_fd < 0)
1407 return old_fd;
1408
1409 new_fd = chase_and_openat(XAT_FDROOT, dir_fdt, to, CHASE_PARENT|CHASE_EXTRACT_FILENAME, O_CLOEXEC, &subvolume);
1410 if (new_fd < 0)
1411 return new_fd;
1412
1413 r = btrfs_validate_subvolume_name(subvolume);
1414 if (r < 0)
1415 return r;
1416
1417 r = btrfs_is_subvol_at(dir_fdf, from);
1418 if (r < 0)
1419 return r;
1420 if (r == 0) {
1421 bool plain_directory = false;
1422
1423 /* If the source isn't a proper subvolume, fail unless fallback is requested */
1424 if (!(flags & BTRFS_SNAPSHOT_FALLBACK_COPY))
1425 return -EISDIR;
1426
1427 r = btrfs_subvol_make(new_fd, subvolume);
1428 if (r < 0) {
1429 if (ERRNO_IS_NOT_SUPPORTED(r) && (flags & BTRFS_SNAPSHOT_FALLBACK_DIRECTORY)) {
1430 /* If the destination doesn't support subvolumes, then use a plain directory, if that's requested. */
1431 if (mkdirat(new_fd, subvolume, 0755) < 0)
1432 return -errno;
1433
1434 plain_directory = true;
1435 } else
1436 return r;
1437 }
1438
1439 if (FLAGS_SET(flags, BTRFS_SNAPSHOT_LOCK_BSD)) {
1440 subvolume_fd = xopenat_lock(new_fd, subvolume,
1441 O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW,
1442 LOCK_BSD,
1443 LOCK_EX);
1444 if (subvolume_fd < 0)
1445 return subvolume_fd;
1446
1447 if (!plain_directory) {
1448 r = btrfs_is_subvol_fd(subvolume_fd);
1449 if (r < 0)
1450 return r;
1451 if (r == 0)
1452 return -EEXIST;
1453 }
1454 }
1455
1456 r = copy_directory_at_full(
1457 dir_fdf, from,
1458 new_fd, subvolume,
1459 /* override_uid= */ UID_INVALID,
1460 /* override_gid= */ GID_INVALID,
1461 COPY_MERGE_EMPTY|
1462 COPY_REFLINK|
1463 COPY_SAME_MOUNT|
1464 COPY_HARDLINKS|
1465 COPY_ALL_XATTRS|
1466 (FLAGS_SET(flags, BTRFS_SNAPSHOT_SIGINT) ? COPY_SIGINT : 0)|
1467 (FLAGS_SET(flags, BTRFS_SNAPSHOT_SIGTERM) ? COPY_SIGTERM : 0),
1468 progress_path,
1469 progress_bytes,
1470 userdata);
1471 if (r < 0)
1472 goto fallback_fail;
1473
1474 if (flags & BTRFS_SNAPSHOT_READ_ONLY) {
1475
1476 if (plain_directory) {
1477 /* Plain directories have no recursive read-only flag, but something pretty close to
1478 * it: the IMMUTABLE bit. Let's use this here, if this is requested. */
1479
1480 if (flags & BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE)
1481 (void) chattr_at(new_fd, subvolume, FS_IMMUTABLE_FL, FS_IMMUTABLE_FL);
1482 } else {
1483 r = btrfs_subvol_set_read_only_at(new_fd, subvolume, true);
1484 if (r < 0)
1485 goto fallback_fail;
1486 }
1487 }
1488
1489 return flags & BTRFS_SNAPSHOT_LOCK_BSD ? TAKE_FD(subvolume_fd) : 0;
1490
1491 fallback_fail:
1492 (void) rm_rf_at(new_fd, subvolume, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME);
1493 return r;
1494 }
1495
1496 return subvol_snapshot_children(old_fd, new_fd, subvolume, 0, flags);
1497 }
1498
1499 int btrfs_qgroup_find_parents(int fd, uint64_t qgroupid, uint64_t **ret) {
1500
1501 struct btrfs_ioctl_search_args args = {
1502 /* Tree of quota items */
1503 .key.tree_id = BTRFS_QUOTA_TREE_OBJECTID,
1504
1505 /* Look precisely for the quota relation items */
1506 .key.min_type = BTRFS_QGROUP_RELATION_KEY,
1507 .key.max_type = BTRFS_QGROUP_RELATION_KEY,
1508
1509 /* No restrictions on the other components */
1510 .key.min_offset = 0,
1511 .key.max_offset = UINT64_MAX,
1512
1513 .key.min_transid = 0,
1514 .key.max_transid = UINT64_MAX,
1515 };
1516
1517 _cleanup_free_ uint64_t *items = NULL;
1518 size_t n_items = 0;
1519 int r;
1520
1521 assert(fd >= 0);
1522 assert(ret);
1523
1524 if (qgroupid == 0) {
1525 r = btrfs_subvol_get_id_fd(fd, &qgroupid);
1526 if (r < 0)
1527 return r;
1528 } else {
1529 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
1530 if (r < 0)
1531 return r;
1532 if (r == 0)
1533 return -ENOTTY;
1534 }
1535
1536 args.key.min_objectid = args.key.max_objectid = qgroupid;
1537
1538 while (btrfs_ioctl_search_args_compare(&args) <= 0) {
1539 struct btrfs_ioctl_search_header sh;
1540 _unused_ const void *body;
1541
1542 args.key.nr_items = 256;
1543 if (ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args) < 0) {
1544 if (errno == ENOENT) /* quota tree missing: quota is disabled */
1545 break;
1546
1547 return -errno;
1548 }
1549
1550 if (args.key.nr_items <= 0)
1551 break;
1552
1553 FOREACH_BTRFS_IOCTL_SEARCH_HEADER(sh, body, args) {
1554
1555 /* Make sure we start the next search at least from this entry */
1556 btrfs_ioctl_search_args_set(&args, &sh);
1557
1558 if (sh.type != BTRFS_QGROUP_RELATION_KEY)
1559 continue;
1560 if (sh.offset < sh.objectid)
1561 continue;
1562 if (sh.objectid != qgroupid)
1563 continue;
1564
1565 if (!GREEDY_REALLOC(items, n_items+1))
1566 return -ENOMEM;
1567
1568 items[n_items++] = sh.offset;
1569 }
1570
1571 /* Increase search key by one, to read the next item, if we can. */
1572 if (!btrfs_ioctl_search_args_inc(&args))
1573 break;
1574 }
1575
1576 assert((n_items > 0) == !!items);
1577 assert(n_items <= INT_MAX);
1578
1579 *ret = TAKE_PTR(items);
1580 return (int) n_items;
1581 }
1582
1583 int btrfs_subvol_auto_qgroup_fd(int fd, uint64_t subvol_id, bool insert_intermediary_qgroup) {
1584 _cleanup_free_ uint64_t *qgroups = NULL;
1585 _cleanup_close_ int real_fd = -EBADF;
1586 uint64_t parent_subvol;
1587 bool changed = false;
1588 int n = 0, r;
1589
1590 assert(fd >= 0);
1591
1592 /*
1593 * Sets up the specified subvolume's qgroup automatically in
1594 * one of two ways:
1595 *
1596 * If insert_intermediary_qgroup is false, the subvolume's
1597 * leaf qgroup will be assigned to the same parent qgroups as
1598 * the subvolume's parent subvolume.
1599 *
1600 * If insert_intermediary_qgroup is true a new intermediary
1601 * higher-level qgroup is created, with a higher level number,
1602 * but reusing the id of the subvolume. The level number is
1603 * picked as one smaller than the lowest level qgroup the
1604 * parent subvolume is a member of. If the parent subvolume's
1605 * leaf qgroup is assigned to no higher-level qgroup a new
1606 * qgroup of level 255 is created instead. Either way, the new
1607 * qgroup is then assigned to the parent's higher-level
1608 * qgroup, and the subvolume itself is assigned to it.
1609 *
1610 * If the subvolume is already assigned to a higher level
1611 * qgroup, no operation is executed.
1612 *
1613 * Effectively this means: regardless if
1614 * insert_intermediary_qgroup is true or not, after this
1615 * function is invoked the subvolume will be accounted within
1616 * the same qgroups as the parent. However, if it is true, it
1617 * will also get its own higher-level qgroup, which may in
1618 * turn be used by subvolumes created beneath this subvolume
1619 * later on.
1620 *
1621 * This hence defines a simple default qgroup setup for
1622 * subvolumes, as long as this function is invoked on each
1623 * created subvolume: each subvolume is always accounting
1624 * together with its immediate parents. Optionally, if
1625 * insert_intermediary_qgroup is true, it will also get a
1626 * qgroup that then includes all its own child subvolumes.
1627 */
1628
1629 /* Turn this into a proper fd, if it is currently O_PATH */
1630 fd = fd_reopen_condition(fd, O_RDONLY|O_CLOEXEC, O_PATH, &real_fd);
1631 if (fd < 0)
1632 return fd;
1633
1634 if (subvol_id == 0) {
1635 r = btrfs_is_subvol_fd(fd);
1636 if (r < 0)
1637 return r;
1638 if (!r)
1639 return -ENOTTY;
1640
1641 r = btrfs_subvol_get_id_fd(fd, &subvol_id);
1642 if (r < 0)
1643 return r;
1644 }
1645
1646 n = btrfs_qgroup_find_parents(fd, subvol_id, &qgroups);
1647 if (n < 0)
1648 return n;
1649 if (n > 0) /* already parent qgroups set up, let's bail */
1650 return 0;
1651
1652 qgroups = mfree(qgroups);
1653
1654 r = btrfs_subvol_get_parent(fd, subvol_id, &parent_subvol);
1655 if (r == -ENXIO)
1656 /* No parent, hence no qgroup memberships */
1657 n = 0;
1658 else if (r < 0)
1659 return r;
1660 else {
1661 n = btrfs_qgroup_find_parents(fd, parent_subvol, &qgroups);
1662 if (n < 0)
1663 return n;
1664 }
1665
1666 if (insert_intermediary_qgroup) {
1667 uint64_t lowest = 256, new_qgroupid;
1668 bool created = false;
1669
1670 /* Determine the lowest qgroup that the parent
1671 * subvolume is assigned to. */
1672
1673 for (int i = 0; i < n; i++) {
1674 uint64_t level;
1675
1676 r = btrfs_qgroupid_split(qgroups[i], &level, NULL);
1677 if (r < 0)
1678 return r;
1679
1680 if (level < lowest)
1681 lowest = level;
1682 }
1683
1684 if (lowest <= 1) /* There are no levels left we could use insert an intermediary qgroup at */
1685 return -EBUSY;
1686
1687 r = btrfs_qgroupid_make(lowest - 1, subvol_id, &new_qgroupid);
1688 if (r < 0)
1689 return r;
1690
1691 /* Create the new intermediary group, unless it already exists */
1692 r = btrfs_qgroup_create(fd, new_qgroupid);
1693 if (r < 0 && r != -EEXIST)
1694 return r;
1695 if (r >= 0)
1696 changed = created = true;
1697
1698 for (int i = 0; i < n; i++) {
1699 r = btrfs_qgroup_assign(fd, new_qgroupid, qgroups[i]);
1700 if (r < 0 && r != -EEXIST) {
1701 if (created)
1702 (void) btrfs_qgroup_destroy_recursive(fd, new_qgroupid);
1703
1704 return r;
1705 }
1706 if (r >= 0)
1707 changed = true;
1708 }
1709
1710 r = btrfs_qgroup_assign(fd, subvol_id, new_qgroupid);
1711 if (r < 0 && r != -EEXIST) {
1712 if (created)
1713 (void) btrfs_qgroup_destroy_recursive(fd, new_qgroupid);
1714 return r;
1715 }
1716 if (r >= 0)
1717 changed = true;
1718
1719 } else {
1720 int i;
1721
1722 /* Assign our subvolume to all the same qgroups as the parent */
1723
1724 for (i = 0; i < n; i++) {
1725 r = btrfs_qgroup_assign(fd, subvol_id, qgroups[i]);
1726 if (r < 0 && r != -EEXIST)
1727 return r;
1728 if (r >= 0)
1729 changed = true;
1730 }
1731 }
1732
1733 return changed;
1734 }
1735
1736 int btrfs_subvol_auto_qgroup(const char *path, uint64_t subvol_id, bool create_intermediary_qgroup) {
1737 _cleanup_close_ int fd = -EBADF;
1738
1739 fd = open(path, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
1740 if (fd < 0)
1741 return -errno;
1742
1743 return btrfs_subvol_auto_qgroup_fd(fd, subvol_id, create_intermediary_qgroup);
1744 }
1745
1746 int btrfs_subvol_make_default(const char *path) {
1747 _cleanup_close_ int fd = -EBADF;
1748 uint64_t id;
1749 int r;
1750
1751 assert(path);
1752
1753 fd = open(path, O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
1754 if (fd < 0)
1755 return -errno;
1756
1757 r = btrfs_subvol_get_id_fd(fd, &id);
1758 if (r < 0)
1759 return r;
1760
1761 return RET_NERRNO(ioctl(fd, BTRFS_IOC_DEFAULT_SUBVOL, &id));
1762 }
1763
1764 int btrfs_subvol_get_parent(int fd, uint64_t subvol_id, uint64_t *ret) {
1765
1766 struct btrfs_ioctl_search_args args = {
1767 /* Tree of tree roots */
1768 .key.tree_id = BTRFS_ROOT_TREE_OBJECTID,
1769
1770 /* Look precisely for the subvolume items */
1771 .key.min_type = BTRFS_ROOT_BACKREF_KEY,
1772 .key.max_type = BTRFS_ROOT_BACKREF_KEY,
1773
1774 /* No restrictions on the other components */
1775 .key.min_offset = 0,
1776 .key.max_offset = UINT64_MAX,
1777
1778 .key.min_transid = 0,
1779 .key.max_transid = UINT64_MAX,
1780 };
1781 int r;
1782
1783 assert(fd >= 0);
1784 assert(ret);
1785
1786 if (subvol_id == 0) {
1787 r = btrfs_subvol_get_id_fd(fd, &subvol_id);
1788 if (r < 0)
1789 return r;
1790 } else {
1791 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
1792 if (r < 0)
1793 return r;
1794 if (r == 0)
1795 return -ENOTTY;
1796 }
1797
1798 args.key.min_objectid = args.key.max_objectid = subvol_id;
1799
1800 while (btrfs_ioctl_search_args_compare(&args) <= 0) {
1801 struct btrfs_ioctl_search_header sh;
1802 _unused_ const void *body = NULL;
1803
1804 args.key.nr_items = 256;
1805 if (ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args) < 0)
1806 return negative_errno();
1807
1808 if (args.key.nr_items <= 0)
1809 break;
1810
1811 FOREACH_BTRFS_IOCTL_SEARCH_HEADER(sh, body, args) {
1812
1813 if (sh.type != BTRFS_ROOT_BACKREF_KEY)
1814 continue;
1815 if (sh.objectid != subvol_id)
1816 continue;
1817
1818 *ret = sh.offset;
1819 return 0;
1820 }
1821 }
1822
1823 return -ENXIO;
1824 }
1825
1826 bool btrfs_might_be_subvol(const struct stat *st) {
1827 if (!st)
1828 return false;
1829
1830 /* Returns true if this 'struct stat' looks like it could refer to a btrfs subvolume. To make a final
1831 * decision, needs to be combined with an fstatfs() check to see if this is actually btrfs. */
1832
1833 return S_ISDIR(st->st_mode) && st->st_ino == 256;
1834 }
1835
1836 int btrfs_forget_device(const char *path) {
1837 _cleanup_close_ int control_fd = -EBADF;
1838 struct btrfs_ioctl_vol_args args = {};
1839
1840 assert(path);
1841
1842 if (strlen(path) > BTRFS_PATH_NAME_MAX)
1843 return -E2BIG;
1844
1845 strcpy(args.name, path);
1846
1847 control_fd = open("/dev/btrfs-control", O_RDWR|O_CLOEXEC);
1848 if (control_fd < 0)
1849 return -errno;
1850
1851 return RET_NERRNO(ioctl(control_fd, BTRFS_IOC_FORGET_DEV, &args));
1852 }
1853
1854 typedef struct BtrfsStripe {
1855 uint64_t devid;
1856 uint64_t offset;
1857 } BtrfsStripe;
1858
1859 typedef struct BtrfsChunk {
1860 uint64_t offset;
1861 uint64_t length;
1862 uint64_t type;
1863
1864 BtrfsStripe *stripes;
1865 uint16_t n_stripes;
1866 uint64_t stripe_len;
1867 } BtrfsChunk;
1868
1869 typedef struct BtrfsChunkTree {
1870 BtrfsChunk **chunks;
1871 size_t n_chunks;
1872 } BtrfsChunkTree;
1873
1874 static BtrfsChunk* btrfs_chunk_free(BtrfsChunk *chunk) {
1875 if (!chunk)
1876 return NULL;
1877
1878 free(chunk->stripes);
1879
1880 return mfree(chunk);
1881 }
1882
1883 DEFINE_TRIVIAL_CLEANUP_FUNC(BtrfsChunk*, btrfs_chunk_free);
1884
1885 static void btrfs_chunk_tree_done(BtrfsChunkTree *tree) {
1886 assert(tree);
1887
1888 FOREACH_ARRAY(i, tree->chunks, tree->n_chunks)
1889 btrfs_chunk_free(*i);
1890
1891 free(tree->chunks);
1892 }
1893
1894 static int btrfs_read_chunk_tree_fd(int fd, BtrfsChunkTree *ret) {
1895
1896 struct btrfs_ioctl_search_args search_args = {
1897 .key.tree_id = BTRFS_CHUNK_TREE_OBJECTID,
1898
1899 .key.min_type = BTRFS_CHUNK_ITEM_KEY,
1900 .key.max_type = BTRFS_CHUNK_ITEM_KEY,
1901
1902 .key.min_objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1903 .key.max_objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1904
1905 .key.min_offset = 0,
1906 .key.max_offset = UINT64_MAX,
1907
1908 .key.min_transid = 0,
1909 .key.max_transid = UINT64_MAX,
1910 };
1911
1912 _cleanup_(btrfs_chunk_tree_done) BtrfsChunkTree tree = {};
1913
1914 assert(fd >= 0);
1915 assert(ret);
1916
1917 while (btrfs_ioctl_search_args_compare(&search_args) <= 0) {
1918 struct btrfs_ioctl_search_header sh;
1919 const void *body;
1920
1921 search_args.key.nr_items = 256;
1922
1923 if (ioctl(fd, BTRFS_IOC_TREE_SEARCH, &search_args) < 0)
1924 return -errno;
1925
1926 if (search_args.key.nr_items == 0)
1927 break;
1928
1929 FOREACH_BTRFS_IOCTL_SEARCH_HEADER(sh, body, search_args) {
1930 _cleanup_(btrfs_chunk_freep) BtrfsChunk *chunk = NULL;
1931
1932 btrfs_ioctl_search_args_set(&search_args, &sh);
1933
1934 if (sh.objectid != BTRFS_FIRST_CHUNK_TREE_OBJECTID)
1935 continue;
1936 if (sh.type != BTRFS_CHUNK_ITEM_KEY)
1937 continue;
1938
1939 chunk = new(BtrfsChunk, 1);
1940 if (!chunk)
1941 return -ENOMEM;
1942
1943 const struct btrfs_chunk *item = body;
1944 *chunk = (BtrfsChunk) {
1945 .offset = sh.offset,
1946 .length = le64toh(item->length),
1947 .type = le64toh(item->type),
1948 .n_stripes = le16toh(item->num_stripes),
1949 .stripe_len = le64toh(item->stripe_len),
1950 };
1951
1952 chunk->stripes = new(BtrfsStripe, chunk->n_stripes);
1953 if (!chunk->stripes)
1954 return -ENOMEM;
1955
1956 for (size_t j = 0; j < chunk->n_stripes; j++) {
1957 const struct btrfs_stripe *stripe = &item->stripe + j;
1958
1959 chunk->stripes[j] = (BtrfsStripe) {
1960 .devid = le64toh(stripe->devid),
1961 .offset = le64toh(stripe->offset),
1962 };
1963 }
1964
1965 if (!GREEDY_REALLOC(tree.chunks, tree.n_chunks + 1))
1966 return -ENOMEM;
1967
1968 tree.chunks[tree.n_chunks++] = TAKE_PTR(chunk);
1969 }
1970
1971 if (!btrfs_ioctl_search_args_inc(&search_args))
1972 break;
1973 }
1974
1975 *ret = TAKE_STRUCT(tree);
1976 return 0;
1977 }
1978
1979 static BtrfsChunk* btrfs_find_chunk_from_logical_address(const BtrfsChunkTree *tree, uint64_t logical) {
1980 size_t min_index, max_index;
1981
1982 assert(tree);
1983 assert(tree->chunks || tree->n_chunks == 0);
1984
1985 if (tree->n_chunks == 0)
1986 return NULL;
1987
1988 /* bisection */
1989 min_index = 0;
1990 max_index = tree->n_chunks - 1;
1991
1992 while (min_index <= max_index) {
1993 size_t mid = (min_index + max_index) / 2;
1994
1995 if (logical < tree->chunks[mid]->offset) {
1996 if (mid < 1)
1997 return NULL;
1998
1999 max_index = mid - 1;
2000 } else if (logical >= tree->chunks[mid]->offset + tree->chunks[mid]->length)
2001 min_index = mid + 1;
2002 else
2003 return tree->chunks[mid];
2004 }
2005
2006 return NULL;
2007 }
2008
2009 static int btrfs_is_nocow_fd(int fd) {
2010 unsigned flags;
2011 int r;
2012
2013 assert(fd >= 0);
2014
2015 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
2016 if (r < 0)
2017 return r;
2018 if (r == 0)
2019 return -ENOTTY;
2020
2021 r = read_attr_fd(fd, &flags);
2022 if (r < 0)
2023 return r;
2024
2025 return FLAGS_SET(flags, FS_NOCOW_FL) && !FLAGS_SET(flags, FS_COMPR_FL);
2026 }
2027
2028 int btrfs_get_file_physical_offset_fd(int fd, uint64_t *ret) {
2029
2030 struct btrfs_ioctl_search_args search_args = {
2031 .key.min_type = BTRFS_EXTENT_DATA_KEY,
2032 .key.max_type = BTRFS_EXTENT_DATA_KEY,
2033
2034 .key.min_offset = 0,
2035 .key.max_offset = UINT64_MAX,
2036
2037 .key.min_transid = 0,
2038 .key.max_transid = UINT64_MAX,
2039 };
2040
2041 _cleanup_(btrfs_chunk_tree_done) BtrfsChunkTree tree = {};
2042 uint64_t subvol_id;
2043 struct stat st;
2044 int r;
2045
2046 assert(fd >= 0);
2047 assert(ret);
2048
2049 if (fstat(fd, &st) < 0)
2050 return -errno;
2051
2052 r = stat_verify_regular(&st);
2053 if (r < 0)
2054 return r;
2055
2056 r = btrfs_is_nocow_fd(fd);
2057 if (r < 0)
2058 return r;
2059 if (r == 0)
2060 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
2061 "Cannot get physical address for btrfs extent: CoW enabled");
2062
2063 r = btrfs_subvol_get_id_fd(fd, &subvol_id);
2064 if (r < 0)
2065 return r;
2066
2067 r = btrfs_read_chunk_tree_fd(fd, &tree);
2068 if (r < 0)
2069 return r;
2070
2071 search_args.key.tree_id = subvol_id;
2072 search_args.key.min_objectid = search_args.key.max_objectid = st.st_ino;
2073
2074 while (btrfs_ioctl_search_args_compare(&search_args) <= 0) {
2075 struct btrfs_ioctl_search_header sh;
2076 const void *body;
2077
2078 search_args.key.nr_items = 256;
2079
2080 if (ioctl(fd, BTRFS_IOC_TREE_SEARCH, &search_args) < 0)
2081 return -errno;
2082
2083 if (search_args.key.nr_items == 0)
2084 break;
2085
2086 FOREACH_BTRFS_IOCTL_SEARCH_HEADER(sh, body, search_args) {
2087 uint64_t logical_offset;
2088 BtrfsChunk *chunk;
2089
2090 btrfs_ioctl_search_args_set(&search_args, &sh);
2091
2092 if (sh.type != BTRFS_EXTENT_DATA_KEY)
2093 continue;
2094
2095 if (sh.objectid != st.st_ino)
2096 continue;
2097
2098 const struct btrfs_file_extent_item *item = body;
2099 if (!IN_SET(item->type, BTRFS_FILE_EXTENT_REG, BTRFS_FILE_EXTENT_PREALLOC))
2100 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
2101 "Cannot get physical address for btrfs extent: invalid type %" PRIu8,
2102 item->type);
2103
2104 if (item->compression != 0 || item->encryption != 0 || item->other_encoding != 0)
2105 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
2106 "Cannot get physical address for btrfs extent: has incompatible property");
2107
2108 logical_offset = le64toh(item->disk_bytenr);
2109 if (logical_offset == 0)
2110 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
2111 "Cannot get physical address for btrfs extent: failed to get logical offset");
2112
2113 chunk = btrfs_find_chunk_from_logical_address(&tree, logical_offset);
2114 if (!chunk)
2115 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
2116 "Cannot get physical address for btrfs extent: no matching chunk found");
2117
2118 if ((chunk->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) != 0)
2119 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
2120 "Cannot get physical address for btrfs extent: unsupported profile");
2121
2122 uint64_t relative_chunk, relative_stripe, stripe_nr;
2123 uint16_t stripe_index;
2124
2125 assert(logical_offset >= chunk->offset);
2126 assert(chunk->n_stripes > 0);
2127 assert(chunk->stripe_len > 0);
2128
2129 relative_chunk = logical_offset - chunk->offset;
2130 stripe_nr = relative_chunk / chunk->stripe_len;
2131 relative_stripe = relative_chunk - stripe_nr * chunk->stripe_len;
2132 stripe_index = stripe_nr % chunk->n_stripes;
2133
2134 *ret = chunk->stripes[stripe_index].offset +
2135 stripe_nr / chunk->n_stripes * chunk->stripe_len +
2136 relative_stripe;
2137
2138 return 0;
2139 }
2140
2141 if (!btrfs_ioctl_search_args_inc(&search_args))
2142 break;
2143 }
2144
2145 return -ENODATA;
2146 }
2147
2148 int btrfs_replace(int fdmntpnt, uint64_t device_id, const char *target) {
2149 struct btrfs_ioctl_dev_replace_args replace = {
2150 .cmd = BTRFS_IOCTL_DEV_REPLACE_CMD_START,
2151 .result = UINT64_MAX,
2152 .start = {
2153 .srcdevid = device_id,
2154 .cont_reading_from_srcdev_mode = BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_ALWAYS,
2155 },
2156 };
2157
2158 assert(fdmntpnt >= 0);
2159 assert(target);
2160
2161 if (strlen(target) >= sizeof(replace.start.tgtdev_name))
2162 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Path to the btrfs replace target is too long");
2163 strncpy((char *)replace.start.tgtdev_name, target, sizeof(replace.start.tgtdev_name));
2164
2165 if (ioctl(fdmntpnt, BTRFS_IOC_DEV_REPLACE, &replace) < 0)
2166 return -errno;
2167
2168 switch (replace.result) {
2169 case BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR:
2170 break;
2171 case BTRFS_IOCTL_DEV_REPLACE_RESULT_NOT_STARTED:
2172 return log_debug_errno(SYNTHETIC_ERRNO(ECANCELED), "btrfs replace was not started");
2173 case BTRFS_IOCTL_DEV_REPLACE_RESULT_ALREADY_STARTED:
2174 return log_debug_errno(SYNTHETIC_ERRNO(EALREADY), "btrfs replace was already started on this device");
2175 case BTRFS_IOCTL_DEV_REPLACE_RESULT_SCRUB_INPROGRESS:
2176 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "btrfs scrub is in progress");
2177 default:
2178 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "An unknown btrfs error status occurred");
2179 }
2180
2181 return 0;
2182 }
2183
2184 int btrfs_resize_max(int fdmntpnt, uint64_t devid) {
2185 struct btrfs_ioctl_vol_args args = {};
2186
2187 assert(fdmntpnt >= 0);
2188
2189 assert_cc(STRLEN(":max") + DECIMAL_STR_MAX(uint64_t) + 1 <= sizeof(args.name));
2190 xsprintf(args.name, "%" PRIu64 ":max", devid);
2191
2192 return RET_NERRNO(ioctl(fdmntpnt, BTRFS_IOC_RESIZE, &args));
2193 }