btrfs-progs: move utils code out of header
[btrfs-progs-unstable/devel.git] / utils.c
blob5aab60d378b94e221e68e3381522b34fff4bbd64
1 /*
2 * Copyright (C) 2007 Oracle. All rights reserved.
3 * Copyright (C) 2008 Morey Roof. All rights reserved.
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public
7 * License v2 as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public
15 * License along with this program; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 021110-1307, USA.
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/ioctl.h>
24 #include <sys/mount.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <uuid/uuid.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <mntent.h>
31 #include <ctype.h>
32 #include <linux/loop.h>
33 #include <linux/major.h>
34 #include <linux/kdev_t.h>
35 #include <limits.h>
36 #include <blkid/blkid.h>
37 #include <sys/vfs.h>
38 #include <sys/statfs.h>
39 #include <linux/magic.h>
40 #include <getopt.h>
42 #include "kerncompat.h"
43 #include "radix-tree.h"
44 #include "ctree.h"
45 #include "disk-io.h"
46 #include "transaction.h"
47 #include "crc32c.h"
48 #include "utils.h"
49 #include "volumes.h"
50 #include "ioctl.h"
51 #include "commands.h"
52 #include "mkfs/common.h"
54 #ifndef BLKDISCARD
55 #define BLKDISCARD _IO(0x12,119)
56 #endif
58 static int btrfs_scan_done = 0;
60 static int rand_seed_initlized = 0;
61 static unsigned short rand_seed[3];
63 struct btrfs_config bconf;
66 * Discard the given range in one go
68 static int discard_range(int fd, u64 start, u64 len)
70 u64 range[2] = { start, len };
72 if (ioctl(fd, BLKDISCARD, &range) < 0)
73 return errno;
74 return 0;
78 * Discard blocks in the given range in 1G chunks, the process is interruptible
80 static int discard_blocks(int fd, u64 start, u64 len)
82 while (len > 0) {
83 /* 1G granularity */
84 u64 chunk_size = min_t(u64, len, SZ_1G);
85 int ret;
87 ret = discard_range(fd, start, chunk_size);
88 if (ret)
89 return ret;
90 len -= chunk_size;
91 start += chunk_size;
94 return 0;
97 int test_uuid_unique(char *fs_uuid)
99 int unique = 1;
100 blkid_dev_iterate iter = NULL;
101 blkid_dev dev = NULL;
102 blkid_cache cache = NULL;
104 if (blkid_get_cache(&cache, NULL) < 0) {
105 printf("ERROR: lblkid cache get failed\n");
106 return 1;
108 blkid_probe_all(cache);
109 iter = blkid_dev_iterate_begin(cache);
110 blkid_dev_set_search(iter, "UUID", fs_uuid);
112 while (blkid_dev_next(iter, &dev) == 0) {
113 dev = blkid_verify(cache, dev);
114 if (dev) {
115 unique = 0;
116 break;
120 blkid_dev_iterate_end(iter);
121 blkid_put_cache(cache);
123 return unique;
126 u64 btrfs_device_size(int fd, struct stat *st)
128 u64 size;
129 if (S_ISREG(st->st_mode)) {
130 return st->st_size;
132 if (!S_ISBLK(st->st_mode)) {
133 return 0;
135 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
136 return size;
138 return 0;
141 static int zero_blocks(int fd, off_t start, size_t len)
143 char *buf = malloc(len);
144 int ret = 0;
145 ssize_t written;
147 if (!buf)
148 return -ENOMEM;
149 memset(buf, 0, len);
150 written = pwrite(fd, buf, len, start);
151 if (written != len)
152 ret = -EIO;
153 free(buf);
154 return ret;
157 #define ZERO_DEV_BYTES SZ_2M
159 /* don't write outside the device by clamping the region to the device size */
160 static int zero_dev_clamped(int fd, off_t start, ssize_t len, u64 dev_size)
162 off_t end = max(start, start + len);
164 #ifdef __sparc__
165 /* and don't overwrite the disk labels on sparc */
166 start = max(start, 1024);
167 end = max(end, 1024);
168 #endif
170 start = min_t(u64, start, dev_size);
171 end = min_t(u64, end, dev_size);
173 return zero_blocks(fd, start, end - start);
176 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
177 struct btrfs_root *root, int fd, const char *path,
178 u64 device_total_bytes, u32 io_width, u32 io_align,
179 u32 sectorsize)
181 struct btrfs_super_block *disk_super;
182 struct btrfs_super_block *super = root->fs_info->super_copy;
183 struct btrfs_device *device;
184 struct btrfs_dev_item *dev_item;
185 char *buf = NULL;
186 u64 fs_total_bytes;
187 u64 num_devs;
188 int ret;
190 device_total_bytes = (device_total_bytes / sectorsize) * sectorsize;
192 device = calloc(1, sizeof(*device));
193 if (!device) {
194 ret = -ENOMEM;
195 goto out;
197 buf = calloc(1, sectorsize);
198 if (!buf) {
199 ret = -ENOMEM;
200 goto out;
203 disk_super = (struct btrfs_super_block *)buf;
204 dev_item = &disk_super->dev_item;
206 uuid_generate(device->uuid);
207 device->devid = 0;
208 device->type = 0;
209 device->io_width = io_width;
210 device->io_align = io_align;
211 device->sector_size = sectorsize;
212 device->fd = fd;
213 device->writeable = 1;
214 device->total_bytes = device_total_bytes;
215 device->bytes_used = 0;
216 device->total_ios = 0;
217 device->dev_root = root->fs_info->dev_root;
218 device->name = strdup(path);
219 if (!device->name) {
220 ret = -ENOMEM;
221 goto out;
224 INIT_LIST_HEAD(&device->dev_list);
225 ret = btrfs_add_device(trans, root, device);
226 if (ret)
227 goto out;
229 fs_total_bytes = btrfs_super_total_bytes(super) + device_total_bytes;
230 btrfs_set_super_total_bytes(super, fs_total_bytes);
232 num_devs = btrfs_super_num_devices(super) + 1;
233 btrfs_set_super_num_devices(super, num_devs);
235 memcpy(disk_super, super, sizeof(*disk_super));
237 btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
238 btrfs_set_stack_device_id(dev_item, device->devid);
239 btrfs_set_stack_device_type(dev_item, device->type);
240 btrfs_set_stack_device_io_align(dev_item, device->io_align);
241 btrfs_set_stack_device_io_width(dev_item, device->io_width);
242 btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
243 btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
244 btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
245 memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
247 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
248 BUG_ON(ret != sectorsize);
250 free(buf);
251 list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
252 device->fs_devices = root->fs_info->fs_devices;
253 return 0;
255 out:
256 free(device);
257 free(buf);
258 return ret;
261 static int btrfs_wipe_existing_sb(int fd)
263 const char *off = NULL;
264 size_t len = 0;
265 loff_t offset;
266 char buf[BUFSIZ];
267 int ret = 0;
268 blkid_probe pr = NULL;
270 pr = blkid_new_probe();
271 if (!pr)
272 return -1;
274 if (blkid_probe_set_device(pr, fd, 0, 0)) {
275 ret = -1;
276 goto out;
279 ret = blkid_probe_lookup_value(pr, "SBMAGIC_OFFSET", &off, NULL);
280 if (!ret)
281 ret = blkid_probe_lookup_value(pr, "SBMAGIC", NULL, &len);
283 if (ret || len == 0 || off == NULL) {
285 * If lookup fails, the probe did not find any values, eg. for
286 * a file image or a loop device. Soft error.
288 ret = 1;
289 goto out;
292 offset = strtoll(off, NULL, 10);
293 if (len > sizeof(buf))
294 len = sizeof(buf);
296 memset(buf, 0, len);
297 ret = pwrite(fd, buf, len, offset);
298 if (ret < 0) {
299 error("cannot wipe existing superblock: %s", strerror(errno));
300 ret = -1;
301 } else if (ret != len) {
302 error("cannot wipe existing superblock: wrote %d of %zd", ret, len);
303 ret = -1;
305 fsync(fd);
307 out:
308 blkid_free_probe(pr);
309 return ret;
312 int btrfs_prepare_device(int fd, const char *file, u64 *block_count_ret,
313 u64 max_block_count, unsigned opflags)
315 u64 block_count;
316 struct stat st;
317 int i, ret;
319 ret = fstat(fd, &st);
320 if (ret < 0) {
321 error("unable to stat %s: %s", file, strerror(errno));
322 return 1;
325 block_count = btrfs_device_size(fd, &st);
326 if (block_count == 0) {
327 error("unable to determine size of %s", file);
328 return 1;
330 if (max_block_count)
331 block_count = min(block_count, max_block_count);
333 if (opflags & PREP_DEVICE_DISCARD) {
335 * We intentionally ignore errors from the discard ioctl. It
336 * is not necessary for the mkfs functionality but just an
337 * optimization.
339 if (discard_range(fd, 0, 0) == 0) {
340 if (opflags & PREP_DEVICE_VERBOSE)
341 printf("Performing full device TRIM %s (%s) ...\n",
342 file, pretty_size(block_count));
343 discard_blocks(fd, 0, block_count);
347 ret = zero_dev_clamped(fd, 0, ZERO_DEV_BYTES, block_count);
348 for (i = 0 ; !ret && i < BTRFS_SUPER_MIRROR_MAX; i++)
349 ret = zero_dev_clamped(fd, btrfs_sb_offset(i),
350 BTRFS_SUPER_INFO_SIZE, block_count);
351 if (!ret && (opflags & PREP_DEVICE_ZERO_END))
352 ret = zero_dev_clamped(fd, block_count - ZERO_DEV_BYTES,
353 ZERO_DEV_BYTES, block_count);
355 if (ret < 0) {
356 error("failed to zero device '%s': %s", file, strerror(-ret));
357 return 1;
360 ret = btrfs_wipe_existing_sb(fd);
361 if (ret < 0) {
362 error("cannot wipe superblocks on %s", file);
363 return 1;
366 *block_count_ret = block_count;
367 return 0;
370 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
371 struct btrfs_root *root, u64 objectid)
373 int ret;
374 struct btrfs_inode_item inode_item;
375 time_t now = time(NULL);
377 memset(&inode_item, 0, sizeof(inode_item));
378 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
379 btrfs_set_stack_inode_size(&inode_item, 0);
380 btrfs_set_stack_inode_nlink(&inode_item, 1);
381 btrfs_set_stack_inode_nbytes(&inode_item, root->nodesize);
382 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
383 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
384 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
385 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
386 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
387 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
388 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
389 btrfs_set_stack_timespec_sec(&inode_item.otime, now);
390 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
392 if (root->fs_info->tree_root == root)
393 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
395 ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
396 if (ret)
397 goto error;
399 ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
400 if (ret)
401 goto error;
403 btrfs_set_root_dirid(&root->root_item, objectid);
404 ret = 0;
405 error:
406 return ret;
410 * checks if a path is a block device node
411 * Returns negative errno on failure, otherwise
412 * returns 1 for blockdev, 0 for not-blockdev
414 int is_block_device(const char *path)
416 struct stat statbuf;
418 if (stat(path, &statbuf) < 0)
419 return -errno;
421 return !!S_ISBLK(statbuf.st_mode);
425 * check if given path is a mount point
426 * return 1 if yes. 0 if no. -1 for error
428 int is_mount_point(const char *path)
430 FILE *f;
431 struct mntent *mnt;
432 int ret = 0;
434 f = setmntent("/proc/self/mounts", "r");
435 if (f == NULL)
436 return -1;
438 while ((mnt = getmntent(f)) != NULL) {
439 if (strcmp(mnt->mnt_dir, path))
440 continue;
441 ret = 1;
442 break;
444 endmntent(f);
445 return ret;
448 static int is_reg_file(const char *path)
450 struct stat statbuf;
452 if (stat(path, &statbuf) < 0)
453 return -errno;
454 return S_ISREG(statbuf.st_mode);
458 * This function checks if the given input parameter is
459 * an uuid or a path
460 * return <0 : some error in the given input
461 * return BTRFS_ARG_UNKNOWN: unknown input
462 * return BTRFS_ARG_UUID: given input is uuid
463 * return BTRFS_ARG_MNTPOINT: given input is path
464 * return BTRFS_ARG_REG: given input is regular file
465 * return BTRFS_ARG_BLKDEV: given input is block device
467 int check_arg_type(const char *input)
469 uuid_t uuid;
470 char path[PATH_MAX];
472 if (!input)
473 return -EINVAL;
475 if (realpath(input, path)) {
476 if (is_block_device(path) == 1)
477 return BTRFS_ARG_BLKDEV;
479 if (is_mount_point(path) == 1)
480 return BTRFS_ARG_MNTPOINT;
482 if (is_reg_file(path))
483 return BTRFS_ARG_REG;
485 return BTRFS_ARG_UNKNOWN;
488 if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
489 !uuid_parse(input, uuid))
490 return BTRFS_ARG_UUID;
492 return BTRFS_ARG_UNKNOWN;
496 * Find the mount point for a mounted device.
497 * On success, returns 0 with mountpoint in *mp.
498 * On failure, returns -errno (not mounted yields -EINVAL)
499 * Is noisy on failures, expects to be given a mounted device.
501 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
503 int ret;
504 int fd = -1;
506 ret = is_block_device(dev);
507 if (ret <= 0) {
508 if (!ret) {
509 error("not a block device: %s", dev);
510 ret = -EINVAL;
511 } else {
512 error("cannot check %s: %s", dev, strerror(-ret));
514 goto out;
517 fd = open(dev, O_RDONLY);
518 if (fd < 0) {
519 ret = -errno;
520 error("cannot open %s: %s", dev, strerror(errno));
521 goto out;
524 ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
525 if (!ret) {
526 ret = -EINVAL;
527 } else { /* mounted, all good */
528 ret = 0;
530 out:
531 if (fd != -1)
532 close(fd);
533 return ret;
537 * Given a pathname, return a filehandle to:
538 * the original pathname or,
539 * if the pathname is a mounted btrfs device, to its mountpoint.
541 * On error, return -1, errno should be set.
543 int open_path_or_dev_mnt(const char *path, DIR **dirstream, int verbose)
545 char mp[PATH_MAX];
546 int ret;
548 if (is_block_device(path)) {
549 ret = get_btrfs_mount(path, mp, sizeof(mp));
550 if (ret < 0) {
551 /* not a mounted btrfs dev */
552 error_on(verbose, "'%s' is not a mounted btrfs device",
553 path);
554 errno = EINVAL;
555 return -1;
557 ret = open_file_or_dir(mp, dirstream);
558 error_on(verbose && ret < 0, "can't access '%s': %s",
559 path, strerror(errno));
560 } else {
561 ret = btrfs_open_dir(path, dirstream, 1);
564 return ret;
568 * Do the following checks before calling open_file_or_dir():
569 * 1: path is in a btrfs filesystem
570 * 2: path is a directory
572 int btrfs_open_dir(const char *path, DIR **dirstream, int verbose)
574 struct statfs stfs;
575 struct stat st;
576 int ret;
578 if (statfs(path, &stfs) != 0) {
579 error_on(verbose, "cannot access '%s': %s", path,
580 strerror(errno));
581 return -1;
584 if (stfs.f_type != BTRFS_SUPER_MAGIC) {
585 error_on(verbose, "not a btrfs filesystem: %s", path);
586 return -2;
589 if (stat(path, &st) != 0) {
590 error_on(verbose, "cannot access '%s': %s", path,
591 strerror(errno));
592 return -1;
595 if (!S_ISDIR(st.st_mode)) {
596 error_on(verbose, "not a directory: %s", path);
597 return -3;
600 ret = open_file_or_dir(path, dirstream);
601 if (ret < 0) {
602 error_on(verbose, "cannot access '%s': %s", path,
603 strerror(errno));
606 return ret;
609 /* checks if a device is a loop device */
610 static int is_loop_device (const char* device) {
611 struct stat statbuf;
613 if(stat(device, &statbuf) < 0)
614 return -errno;
616 return (S_ISBLK(statbuf.st_mode) &&
617 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
621 * Takes a loop device path (e.g. /dev/loop0) and returns
622 * the associated file (e.g. /images/my_btrfs.img) using
623 * loopdev API
625 static int resolve_loop_device_with_loopdev(const char* loop_dev, char* loop_file)
627 int fd;
628 int ret;
629 struct loop_info64 lo64;
631 fd = open(loop_dev, O_RDONLY | O_NONBLOCK);
632 if (fd < 0)
633 return -errno;
634 ret = ioctl(fd, LOOP_GET_STATUS64, &lo64);
635 if (ret < 0) {
636 ret = -errno;
637 goto out;
640 memcpy(loop_file, lo64.lo_file_name, sizeof(lo64.lo_file_name));
641 loop_file[sizeof(lo64.lo_file_name)] = 0;
643 out:
644 close(fd);
646 return ret;
649 /* Takes a loop device path (e.g. /dev/loop0) and returns
650 * the associated file (e.g. /images/my_btrfs.img) */
651 static int resolve_loop_device(const char* loop_dev, char* loop_file,
652 int max_len)
654 int ret;
655 FILE *f;
656 char fmt[20];
657 char p[PATH_MAX];
658 char real_loop_dev[PATH_MAX];
660 if (!realpath(loop_dev, real_loop_dev))
661 return -errno;
662 snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
663 if (!(f = fopen(p, "r"))) {
664 if (errno == ENOENT)
666 * It's possibly a partitioned loop device, which is
667 * resolvable with loopdev API.
669 return resolve_loop_device_with_loopdev(loop_dev, loop_file);
670 return -errno;
673 snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
674 ret = fscanf(f, fmt, loop_file);
675 fclose(f);
676 if (ret == EOF)
677 return -errno;
679 return 0;
683 * Checks whether a and b are identical or device
684 * files associated with the same block device
686 static int is_same_blk_file(const char* a, const char* b)
688 struct stat st_buf_a, st_buf_b;
689 char real_a[PATH_MAX];
690 char real_b[PATH_MAX];
692 if (!realpath(a, real_a))
693 strncpy_null(real_a, a);
695 if (!realpath(b, real_b))
696 strncpy_null(real_b, b);
698 /* Identical path? */
699 if (strcmp(real_a, real_b) == 0)
700 return 1;
702 if (stat(a, &st_buf_a) < 0 || stat(b, &st_buf_b) < 0) {
703 if (errno == ENOENT)
704 return 0;
705 return -errno;
708 /* Same blockdevice? */
709 if (S_ISBLK(st_buf_a.st_mode) && S_ISBLK(st_buf_b.st_mode) &&
710 st_buf_a.st_rdev == st_buf_b.st_rdev) {
711 return 1;
714 /* Hardlink? */
715 if (st_buf_a.st_dev == st_buf_b.st_dev &&
716 st_buf_a.st_ino == st_buf_b.st_ino) {
717 return 1;
720 return 0;
723 /* checks if a and b are identical or device
724 * files associated with the same block device or
725 * if one file is a loop device that uses the other
726 * file.
728 static int is_same_loop_file(const char* a, const char* b)
730 char res_a[PATH_MAX];
731 char res_b[PATH_MAX];
732 const char* final_a = NULL;
733 const char* final_b = NULL;
734 int ret;
736 /* Resolve a if it is a loop device */
737 if((ret = is_loop_device(a)) < 0) {
738 if (ret == -ENOENT)
739 return 0;
740 return ret;
741 } else if (ret) {
742 ret = resolve_loop_device(a, res_a, sizeof(res_a));
743 if (ret < 0) {
744 if (errno != EPERM)
745 return ret;
746 } else {
747 final_a = res_a;
749 } else {
750 final_a = a;
753 /* Resolve b if it is a loop device */
754 if ((ret = is_loop_device(b)) < 0) {
755 if (ret == -ENOENT)
756 return 0;
757 return ret;
758 } else if (ret) {
759 ret = resolve_loop_device(b, res_b, sizeof(res_b));
760 if (ret < 0) {
761 if (errno != EPERM)
762 return ret;
763 } else {
764 final_b = res_b;
766 } else {
767 final_b = b;
770 return is_same_blk_file(final_a, final_b);
773 /* Checks if a file exists and is a block or regular file*/
774 static int is_existing_blk_or_reg_file(const char* filename)
776 struct stat st_buf;
778 if(stat(filename, &st_buf) < 0) {
779 if(errno == ENOENT)
780 return 0;
781 else
782 return -errno;
785 return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
788 /* Checks if a file is used (directly or indirectly via a loop device)
789 * by a device in fs_devices
791 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
792 const char* file)
794 int ret;
795 struct list_head *head;
796 struct list_head *cur;
797 struct btrfs_device *device;
799 head = &fs_devices->devices;
800 list_for_each(cur, head) {
801 device = list_entry(cur, struct btrfs_device, dev_list);
803 if((ret = is_same_loop_file(device->name, file)))
804 return ret;
807 return 0;
811 * Resolve a pathname to a device mapper node to /dev/mapper/<name>
812 * Returns NULL on invalid input or malloc failure; Other failures
813 * will be handled by the caller using the input pathame.
815 char *canonicalize_dm_name(const char *ptname)
817 FILE *f;
818 size_t sz;
819 char path[PATH_MAX], name[PATH_MAX], *res = NULL;
821 if (!ptname || !*ptname)
822 return NULL;
824 snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
825 if (!(f = fopen(path, "r")))
826 return NULL;
828 /* read <name>\n from sysfs */
829 if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
830 name[sz - 1] = '\0';
831 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
833 if (access(path, F_OK) == 0)
834 res = strdup(path);
836 fclose(f);
837 return res;
841 * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
842 * to a device mapper pathname.
843 * Returns NULL on invalid input or malloc failure; Other failures
844 * will be handled by the caller using the input pathame.
846 char *canonicalize_path(const char *path)
848 char *canonical, *p;
850 if (!path || !*path)
851 return NULL;
853 canonical = realpath(path, NULL);
854 if (!canonical)
855 return strdup(path);
856 p = strrchr(canonical, '/');
857 if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
858 char *dm = canonicalize_dm_name(p + 1);
860 if (dm) {
861 free(canonical);
862 return dm;
865 return canonical;
869 * returns 1 if the device was mounted, < 0 on error or 0 if everything
870 * is safe to continue.
872 int check_mounted(const char* file)
874 int fd;
875 int ret;
877 fd = open(file, O_RDONLY);
878 if (fd < 0) {
879 error("mount check: cannot open %s: %s", file,
880 strerror(errno));
881 return -errno;
884 ret = check_mounted_where(fd, file, NULL, 0, NULL);
885 close(fd);
887 return ret;
890 int check_mounted_where(int fd, const char *file, char *where, int size,
891 struct btrfs_fs_devices **fs_dev_ret)
893 int ret;
894 u64 total_devs = 1;
895 int is_btrfs;
896 struct btrfs_fs_devices *fs_devices_mnt = NULL;
897 FILE *f;
898 struct mntent *mnt;
900 /* scan the initial device */
901 ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
902 &total_devs, BTRFS_SUPER_INFO_OFFSET, SBREAD_DEFAULT);
903 is_btrfs = (ret >= 0);
905 /* scan other devices */
906 if (is_btrfs && total_devs > 1) {
907 ret = btrfs_scan_devices();
908 if (ret)
909 return ret;
912 /* iterate over the list of currently mounted filesystems */
913 if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
914 return -errno;
916 while ((mnt = getmntent (f)) != NULL) {
917 if(is_btrfs) {
918 if(strcmp(mnt->mnt_type, "btrfs") != 0)
919 continue;
921 ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
922 } else {
923 /* ignore entries in the mount table that are not
924 associated with a file*/
925 if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
926 goto out_mntloop_err;
927 else if(!ret)
928 continue;
930 ret = is_same_loop_file(file, mnt->mnt_fsname);
933 if(ret < 0)
934 goto out_mntloop_err;
935 else if(ret)
936 break;
939 /* Did we find an entry in mnt table? */
940 if (mnt && size && where) {
941 strncpy(where, mnt->mnt_dir, size);
942 where[size-1] = 0;
944 if (fs_dev_ret)
945 *fs_dev_ret = fs_devices_mnt;
947 ret = (mnt != NULL);
949 out_mntloop_err:
950 endmntent (f);
952 return ret;
955 struct pending_dir {
956 struct list_head list;
957 char name[PATH_MAX];
960 int btrfs_register_one_device(const char *fname)
962 struct btrfs_ioctl_vol_args args;
963 int fd;
964 int ret;
966 fd = open("/dev/btrfs-control", O_RDWR);
967 if (fd < 0) {
968 warning(
969 "failed to open /dev/btrfs-control, skipping device registration: %s",
970 strerror(errno));
971 return -errno;
973 memset(&args, 0, sizeof(args));
974 strncpy_null(args.name, fname);
975 ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
976 if (ret < 0) {
977 error("device scan failed on '%s': %s", fname,
978 strerror(errno));
979 ret = -errno;
981 close(fd);
982 return ret;
986 * Register all devices in the fs_uuid list created in the user
987 * space. Ensure btrfs_scan_devices() is called before this func.
989 int btrfs_register_all_devices(void)
991 int err = 0;
992 int ret = 0;
993 struct btrfs_fs_devices *fs_devices;
994 struct btrfs_device *device;
995 struct list_head *all_uuids;
997 all_uuids = btrfs_scanned_uuids();
999 list_for_each_entry(fs_devices, all_uuids, list) {
1000 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1001 if (*device->name)
1002 err = btrfs_register_one_device(device->name);
1004 if (err)
1005 ret++;
1009 return ret;
1012 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1013 int super_offset)
1015 struct btrfs_super_block *disk_super;
1016 char *buf;
1017 int ret = 0;
1019 buf = malloc(BTRFS_SUPER_INFO_SIZE);
1020 if (!buf) {
1021 ret = -ENOMEM;
1022 goto out;
1024 ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1025 if (ret != BTRFS_SUPER_INFO_SIZE)
1026 goto brelse;
1028 ret = 0;
1029 disk_super = (struct btrfs_super_block *)buf;
1031 * Accept devices from the same filesystem, allow partially created
1032 * structures.
1034 if (btrfs_super_magic(disk_super) != BTRFS_MAGIC &&
1035 btrfs_super_magic(disk_super) != BTRFS_MAGIC_PARTIAL)
1036 goto brelse;
1038 if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1039 BTRFS_FSID_SIZE))
1040 ret = 1;
1041 brelse:
1042 free(buf);
1043 out:
1044 return ret;
1048 * Note: this function uses a static per-thread buffer. Do not call this
1049 * function more than 10 times within one argument list!
1051 const char *pretty_size_mode(u64 size, unsigned mode)
1053 static __thread int ps_index = 0;
1054 static __thread char ps_array[10][32];
1055 char *ret;
1057 ret = ps_array[ps_index];
1058 ps_index++;
1059 ps_index %= 10;
1060 (void)pretty_size_snprintf(size, ret, 32, mode);
1062 return ret;
1065 static const char* unit_suffix_binary[] =
1066 { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1067 static const char* unit_suffix_decimal[] =
1068 { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
1070 int pretty_size_snprintf(u64 size, char *str, size_t str_size, unsigned unit_mode)
1072 int num_divs;
1073 float fraction;
1074 u64 base = 0;
1075 int mult = 0;
1076 const char** suffix = NULL;
1077 u64 last_size;
1078 int negative;
1080 if (str_size == 0)
1081 return 0;
1083 negative = !!(unit_mode & UNITS_NEGATIVE);
1084 unit_mode &= ~UNITS_NEGATIVE;
1086 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_RAW) {
1087 if (negative)
1088 snprintf(str, str_size, "%lld", size);
1089 else
1090 snprintf(str, str_size, "%llu", size);
1091 return 0;
1094 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_BINARY) {
1095 base = 1024;
1096 mult = 1024;
1097 suffix = unit_suffix_binary;
1098 } else if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_DECIMAL) {
1099 base = 1000;
1100 mult = 1000;
1101 suffix = unit_suffix_decimal;
1104 /* Unknown mode */
1105 if (!base) {
1106 fprintf(stderr, "INTERNAL ERROR: unknown unit base, mode %d\n",
1107 unit_mode);
1108 assert(0);
1109 return -1;
1112 num_divs = 0;
1113 last_size = size;
1114 switch (unit_mode & UNITS_MODE_MASK) {
1115 case UNITS_TBYTES: base *= mult; num_divs++;
1116 case UNITS_GBYTES: base *= mult; num_divs++;
1117 case UNITS_MBYTES: base *= mult; num_divs++;
1118 case UNITS_KBYTES: num_divs++;
1119 break;
1120 case UNITS_BYTES:
1121 base = 1;
1122 num_divs = 0;
1123 break;
1124 default:
1125 if (negative) {
1126 s64 ssize = (s64)size;
1127 s64 last_ssize = ssize;
1129 while ((ssize < 0 ? -ssize : ssize) >= mult) {
1130 last_ssize = ssize;
1131 ssize /= mult;
1132 num_divs++;
1134 last_size = (u64)last_ssize;
1135 } else {
1136 while (size >= mult) {
1137 last_size = size;
1138 size /= mult;
1139 num_divs++;
1143 * If the value is smaller than base, we didn't do any
1144 * division, in that case, base should be 1, not original
1145 * base, or the unit will be wrong
1147 if (num_divs == 0)
1148 base = 1;
1151 if (num_divs >= ARRAY_SIZE(unit_suffix_binary)) {
1152 str[0] = '\0';
1153 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
1154 num_divs);
1155 assert(0);
1156 return -1;
1159 if (negative) {
1160 fraction = (float)(s64)last_size / base;
1161 } else {
1162 fraction = (float)last_size / base;
1165 return snprintf(str, str_size, "%.2f%s", fraction, suffix[num_divs]);
1169 * __strncpy_null - strncpy with null termination
1170 * @dest: the target array
1171 * @src: the source string
1172 * @n: maximum bytes to copy (size of *dest)
1174 * Like strncpy, but ensures destination is null-terminated.
1176 * Copies the string pointed to by src, including the terminating null
1177 * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1178 * of n bytes. Then ensure that dest is null-terminated.
1180 char *__strncpy_null(char *dest, const char *src, size_t n)
1182 strncpy(dest, src, n);
1183 if (n > 0)
1184 dest[n - 1] = '\0';
1185 return dest;
1189 * Checks to make sure that the label matches our requirements.
1190 * Returns:
1191 0 if everything is safe and usable
1192 -1 if the label is too long
1194 static int check_label(const char *input)
1196 int len = strlen(input);
1198 if (len > BTRFS_LABEL_SIZE - 1) {
1199 error("label %s is too long (max %d)", input,
1200 BTRFS_LABEL_SIZE - 1);
1201 return -1;
1204 return 0;
1207 static int set_label_unmounted(const char *dev, const char *label)
1209 struct btrfs_trans_handle *trans;
1210 struct btrfs_root *root;
1211 int ret;
1213 ret = check_mounted(dev);
1214 if (ret < 0) {
1215 error("checking mount status of %s failed: %d", dev, ret);
1216 return -1;
1218 if (ret > 0) {
1219 error("device %s is mounted, use mount point", dev);
1220 return -1;
1223 /* Open the super_block at the default location
1224 * and as read-write.
1226 root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1227 if (!root) /* errors are printed by open_ctree() */
1228 return -1;
1230 trans = btrfs_start_transaction(root, 1);
1231 __strncpy_null(root->fs_info->super_copy->label, label, BTRFS_LABEL_SIZE - 1);
1233 btrfs_commit_transaction(trans, root);
1235 /* Now we close it since we are done. */
1236 close_ctree(root);
1237 return 0;
1240 static int set_label_mounted(const char *mount_path, const char *labelp)
1242 int fd;
1243 char label[BTRFS_LABEL_SIZE];
1245 fd = open(mount_path, O_RDONLY | O_NOATIME);
1246 if (fd < 0) {
1247 error("unable to access %s: %s", mount_path, strerror(errno));
1248 return -1;
1251 memset(label, 0, sizeof(label));
1252 __strncpy_null(label, labelp, BTRFS_LABEL_SIZE - 1);
1253 if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1254 error("unable to set label of %s: %s", mount_path,
1255 strerror(errno));
1256 close(fd);
1257 return -1;
1260 close(fd);
1261 return 0;
1264 int get_label_unmounted(const char *dev, char *label)
1266 struct btrfs_root *root;
1267 int ret;
1269 ret = check_mounted(dev);
1270 if (ret < 0) {
1271 error("checking mount status of %s failed: %d", dev, ret);
1272 return -1;
1275 /* Open the super_block at the default location
1276 * and as read-only.
1278 root = open_ctree(dev, 0, 0);
1279 if(!root)
1280 return -1;
1282 __strncpy_null(label, root->fs_info->super_copy->label,
1283 BTRFS_LABEL_SIZE - 1);
1285 /* Now we close it since we are done. */
1286 close_ctree(root);
1287 return 0;
1291 * If a partition is mounted, try to get the filesystem label via its
1292 * mounted path rather than device. Return the corresponding error
1293 * the user specified the device path.
1295 int get_label_mounted(const char *mount_path, char *labelp)
1297 char label[BTRFS_LABEL_SIZE];
1298 int fd;
1299 int ret;
1301 fd = open(mount_path, O_RDONLY | O_NOATIME);
1302 if (fd < 0) {
1303 error("unable to access %s: %s", mount_path, strerror(errno));
1304 return -1;
1307 memset(label, '\0', sizeof(label));
1308 ret = ioctl(fd, BTRFS_IOC_GET_FSLABEL, label);
1309 if (ret < 0) {
1310 if (errno != ENOTTY)
1311 error("unable to get label of %s: %s", mount_path,
1312 strerror(errno));
1313 ret = -errno;
1314 close(fd);
1315 return ret;
1318 __strncpy_null(labelp, label, BTRFS_LABEL_SIZE - 1);
1319 close(fd);
1320 return 0;
1323 int get_label(const char *btrfs_dev, char *label)
1325 int ret;
1327 ret = is_existing_blk_or_reg_file(btrfs_dev);
1328 if (!ret)
1329 ret = get_label_mounted(btrfs_dev, label);
1330 else if (ret > 0)
1331 ret = get_label_unmounted(btrfs_dev, label);
1333 return ret;
1336 int set_label(const char *btrfs_dev, const char *label)
1338 int ret;
1340 if (check_label(label))
1341 return -1;
1343 ret = is_existing_blk_or_reg_file(btrfs_dev);
1344 if (!ret)
1345 ret = set_label_mounted(btrfs_dev, label);
1346 else if (ret > 0)
1347 ret = set_label_unmounted(btrfs_dev, label);
1349 return ret;
1353 * A not-so-good version fls64. No fascinating optimization since
1354 * no one except parse_size use it
1356 static int fls64(u64 x)
1358 int i;
1360 for (i = 0; i <64; i++)
1361 if (x << i & (1ULL << 63))
1362 return 64 - i;
1363 return 64 - i;
1366 u64 parse_size(char *s)
1368 char c;
1369 char *endptr;
1370 u64 mult = 1;
1371 u64 ret;
1373 if (!s) {
1374 error("size value is empty");
1375 exit(1);
1377 if (s[0] == '-') {
1378 error("size value '%s' is less equal than 0", s);
1379 exit(1);
1381 ret = strtoull(s, &endptr, 10);
1382 if (endptr == s) {
1383 error("size value '%s' is invalid", s);
1384 exit(1);
1386 if (endptr[0] && endptr[1]) {
1387 error("illegal suffix contains character '%c' in wrong position",
1388 endptr[1]);
1389 exit(1);
1392 * strtoll returns LLONG_MAX when overflow, if this happens,
1393 * need to call strtoull to get the real size
1395 if (errno == ERANGE && ret == ULLONG_MAX) {
1396 error("size value '%s' is too large for u64", s);
1397 exit(1);
1399 if (endptr[0]) {
1400 c = tolower(endptr[0]);
1401 switch (c) {
1402 case 'e':
1403 mult *= 1024;
1404 /* fallthrough */
1405 case 'p':
1406 mult *= 1024;
1407 /* fallthrough */
1408 case 't':
1409 mult *= 1024;
1410 /* fallthrough */
1411 case 'g':
1412 mult *= 1024;
1413 /* fallthrough */
1414 case 'm':
1415 mult *= 1024;
1416 /* fallthrough */
1417 case 'k':
1418 mult *= 1024;
1419 /* fallthrough */
1420 case 'b':
1421 break;
1422 default:
1423 error("unknown size descriptor '%c'", c);
1424 exit(1);
1427 /* Check whether ret * mult overflow */
1428 if (fls64(ret) + fls64(mult) - 1 > 64) {
1429 error("size value '%s' is too large for u64", s);
1430 exit(1);
1432 ret *= mult;
1433 return ret;
1436 u64 parse_qgroupid(const char *p)
1438 char *s = strchr(p, '/');
1439 const char *ptr_src_end = p + strlen(p);
1440 char *ptr_parse_end = NULL;
1441 u64 level;
1442 u64 id;
1443 int fd;
1444 int ret = 0;
1446 if (p[0] == '/')
1447 goto path;
1449 /* Numeric format like '0/257' is the primary case */
1450 if (!s) {
1451 id = strtoull(p, &ptr_parse_end, 10);
1452 if (ptr_parse_end != ptr_src_end)
1453 goto path;
1454 return id;
1456 level = strtoull(p, &ptr_parse_end, 10);
1457 if (ptr_parse_end != s)
1458 goto path;
1460 id = strtoull(s + 1, &ptr_parse_end, 10);
1461 if (ptr_parse_end != ptr_src_end)
1462 goto path;
1464 return (level << BTRFS_QGROUP_LEVEL_SHIFT) | id;
1466 path:
1467 /* Path format like subv at 'my_subvol' is the fallback case */
1468 ret = test_issubvolume(p);
1469 if (ret < 0 || !ret)
1470 goto err;
1471 fd = open(p, O_RDONLY);
1472 if (fd < 0)
1473 goto err;
1474 ret = lookup_path_rootid(fd, &id);
1475 if (ret)
1476 error("failed to lookup root id: %s", strerror(-ret));
1477 close(fd);
1478 if (ret < 0)
1479 goto err;
1480 return id;
1482 err:
1483 error("invalid qgroupid or subvolume path: %s", p);
1484 exit(-1);
1487 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
1489 int ret;
1490 struct stat st;
1491 int fd;
1493 ret = stat(fname, &st);
1494 if (ret < 0) {
1495 return -1;
1497 if (S_ISDIR(st.st_mode)) {
1498 *dirstream = opendir(fname);
1499 if (!*dirstream)
1500 return -1;
1501 fd = dirfd(*dirstream);
1502 } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
1503 fd = open(fname, open_flags);
1504 } else {
1506 * we set this on purpose, in case the caller output
1507 * strerror(errno) as success
1509 errno = EINVAL;
1510 return -1;
1512 if (fd < 0) {
1513 fd = -1;
1514 if (*dirstream) {
1515 closedir(*dirstream);
1516 *dirstream = NULL;
1519 return fd;
1522 int open_file_or_dir(const char *fname, DIR **dirstream)
1524 return open_file_or_dir3(fname, dirstream, O_RDWR);
1527 void close_file_or_dir(int fd, DIR *dirstream)
1529 if (dirstream)
1530 closedir(dirstream);
1531 else if (fd >= 0)
1532 close(fd);
1535 int get_device_info(int fd, u64 devid,
1536 struct btrfs_ioctl_dev_info_args *di_args)
1538 int ret;
1540 di_args->devid = devid;
1541 memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1543 ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1544 return ret < 0 ? -errno : 0;
1547 static u64 find_max_device_id(struct btrfs_ioctl_search_args *search_args,
1548 int nr_items)
1550 struct btrfs_dev_item *dev_item;
1551 char *buf = search_args->buf;
1553 buf += (nr_items - 1) * (sizeof(struct btrfs_ioctl_search_header)
1554 + sizeof(struct btrfs_dev_item));
1555 buf += sizeof(struct btrfs_ioctl_search_header);
1557 dev_item = (struct btrfs_dev_item *)buf;
1559 return btrfs_stack_device_id(dev_item);
1562 static int search_chunk_tree_for_fs_info(int fd,
1563 struct btrfs_ioctl_fs_info_args *fi_args)
1565 int ret;
1566 int max_items;
1567 u64 start_devid = 1;
1568 struct btrfs_ioctl_search_args search_args;
1569 struct btrfs_ioctl_search_key *search_key = &search_args.key;
1571 fi_args->num_devices = 0;
1573 max_items = BTRFS_SEARCH_ARGS_BUFSIZE
1574 / (sizeof(struct btrfs_ioctl_search_header)
1575 + sizeof(struct btrfs_dev_item));
1577 search_key->tree_id = BTRFS_CHUNK_TREE_OBJECTID;
1578 search_key->min_objectid = BTRFS_DEV_ITEMS_OBJECTID;
1579 search_key->max_objectid = BTRFS_DEV_ITEMS_OBJECTID;
1580 search_key->min_type = BTRFS_DEV_ITEM_KEY;
1581 search_key->max_type = BTRFS_DEV_ITEM_KEY;
1582 search_key->min_transid = 0;
1583 search_key->max_transid = (u64)-1;
1584 search_key->nr_items = max_items;
1585 search_key->max_offset = (u64)-1;
1587 again:
1588 search_key->min_offset = start_devid;
1590 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &search_args);
1591 if (ret < 0)
1592 return -errno;
1594 fi_args->num_devices += (u64)search_key->nr_items;
1596 if (search_key->nr_items == max_items) {
1597 start_devid = find_max_device_id(&search_args,
1598 search_key->nr_items) + 1;
1599 goto again;
1602 /* get the lastest max_id to stay consistent with the num_devices */
1603 if (search_key->nr_items == 0)
1605 * last tree_search returns an empty buf, use the devid of
1606 * the last dev_item of the previous tree_search
1608 fi_args->max_id = start_devid - 1;
1609 else
1610 fi_args->max_id = find_max_device_id(&search_args,
1611 search_key->nr_items);
1613 return 0;
1617 * For a given path, fill in the ioctl fs_ and info_ args.
1618 * If the path is a btrfs mountpoint, fill info for all devices.
1619 * If the path is a btrfs device, fill in only that device.
1621 * The path provided must be either on a mounted btrfs fs,
1622 * or be a mounted btrfs device.
1624 * Returns 0 on success, or a negative errno.
1626 int get_fs_info(const char *path, struct btrfs_ioctl_fs_info_args *fi_args,
1627 struct btrfs_ioctl_dev_info_args **di_ret)
1629 int fd = -1;
1630 int ret = 0;
1631 int ndevs = 0;
1632 u64 last_devid = 0;
1633 int replacing = 0;
1634 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1635 struct btrfs_ioctl_dev_info_args *di_args;
1636 struct btrfs_ioctl_dev_info_args tmp;
1637 char mp[PATH_MAX];
1638 DIR *dirstream = NULL;
1640 memset(fi_args, 0, sizeof(*fi_args));
1642 if (is_block_device(path) == 1) {
1643 struct btrfs_super_block *disk_super;
1644 char buf[BTRFS_SUPER_INFO_SIZE];
1646 /* Ensure it's mounted, then set path to the mountpoint */
1647 fd = open(path, O_RDONLY);
1648 if (fd < 0) {
1649 ret = -errno;
1650 error("cannot open %s: %s", path, strerror(errno));
1651 goto out;
1653 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1654 &fs_devices_mnt);
1655 if (!ret) {
1656 ret = -EINVAL;
1657 goto out;
1659 if (ret < 0)
1660 goto out;
1661 path = mp;
1662 /* Only fill in this one device */
1663 fi_args->num_devices = 1;
1665 disk_super = (struct btrfs_super_block *)buf;
1666 ret = btrfs_read_dev_super(fd, disk_super,
1667 BTRFS_SUPER_INFO_OFFSET, 0);
1668 if (ret < 0) {
1669 ret = -EIO;
1670 goto out;
1672 last_devid = btrfs_stack_device_id(&disk_super->dev_item);
1673 fi_args->max_id = last_devid;
1675 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1676 close(fd);
1679 /* at this point path must not be for a block device */
1680 fd = open_file_or_dir(path, &dirstream);
1681 if (fd < 0) {
1682 ret = -errno;
1683 goto out;
1686 /* fill in fi_args if not just a single device */
1687 if (fi_args->num_devices != 1) {
1688 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
1689 if (ret < 0) {
1690 ret = -errno;
1691 goto out;
1695 * The fs_args->num_devices does not include seed devices
1697 ret = search_chunk_tree_for_fs_info(fd, fi_args);
1698 if (ret)
1699 goto out;
1702 * search_chunk_tree_for_fs_info() will lacks the devid 0
1703 * so manual probe for it here.
1705 ret = get_device_info(fd, 0, &tmp);
1706 if (!ret) {
1707 fi_args->num_devices++;
1708 ndevs++;
1709 replacing = 1;
1710 if (last_devid == 0)
1711 last_devid++;
1715 if (!fi_args->num_devices)
1716 goto out;
1718 di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
1719 if (!di_args) {
1720 ret = -errno;
1721 goto out;
1724 if (replacing)
1725 memcpy(di_args, &tmp, sizeof(tmp));
1726 for (; last_devid <= fi_args->max_id; last_devid++) {
1727 ret = get_device_info(fd, last_devid, &di_args[ndevs]);
1728 if (ret == -ENODEV)
1729 continue;
1730 if (ret)
1731 goto out;
1732 ndevs++;
1736 * only when the only dev we wanted to find is not there then
1737 * let any error be returned
1739 if (fi_args->num_devices != 1) {
1740 BUG_ON(ndevs == 0);
1741 ret = 0;
1744 out:
1745 close_file_or_dir(fd, dirstream);
1746 return ret;
1749 static int group_profile_devs_min(u64 flag)
1751 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
1752 case 0: /* single */
1753 case BTRFS_BLOCK_GROUP_DUP:
1754 return 1;
1755 case BTRFS_BLOCK_GROUP_RAID0:
1756 case BTRFS_BLOCK_GROUP_RAID1:
1757 case BTRFS_BLOCK_GROUP_RAID5:
1758 return 2;
1759 case BTRFS_BLOCK_GROUP_RAID6:
1760 return 3;
1761 case BTRFS_BLOCK_GROUP_RAID10:
1762 return 4;
1763 default:
1764 return -1;
1768 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
1769 u64 dev_cnt, int mixed, int ssd)
1771 u64 allowed = 0;
1772 u64 profile = metadata_profile | data_profile;
1774 switch (dev_cnt) {
1775 default:
1776 case 4:
1777 allowed |= BTRFS_BLOCK_GROUP_RAID10;
1778 case 3:
1779 allowed |= BTRFS_BLOCK_GROUP_RAID6;
1780 case 2:
1781 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
1782 BTRFS_BLOCK_GROUP_RAID5;
1783 case 1:
1784 allowed |= BTRFS_BLOCK_GROUP_DUP;
1787 if (dev_cnt > 1 && profile & BTRFS_BLOCK_GROUP_DUP) {
1788 warning("DUP is not recommended on filesystem with multiple devices");
1790 if (metadata_profile & ~allowed) {
1791 fprintf(stderr,
1792 "ERROR: unable to create FS with metadata profile %s "
1793 "(have %llu devices but %d devices are required)\n",
1794 btrfs_group_profile_str(metadata_profile), dev_cnt,
1795 group_profile_devs_min(metadata_profile));
1796 return 1;
1798 if (data_profile & ~allowed) {
1799 fprintf(stderr,
1800 "ERROR: unable to create FS with data profile %s "
1801 "(have %llu devices but %d devices are required)\n",
1802 btrfs_group_profile_str(data_profile), dev_cnt,
1803 group_profile_devs_min(data_profile));
1804 return 1;
1807 if (dev_cnt == 3 && profile & BTRFS_BLOCK_GROUP_RAID6) {
1808 warning("RAID6 is not recommended on filesystem with 3 devices only");
1810 if (dev_cnt == 2 && profile & BTRFS_BLOCK_GROUP_RAID5) {
1811 warning("RAID5 is not recommended on filesystem with 2 devices only");
1813 warning_on(!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP) && ssd,
1814 "DUP may not actually lead to 2 copies on the device, see manual page");
1816 return 0;
1819 int group_profile_max_safe_loss(u64 flags)
1821 switch (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
1822 case 0: /* single */
1823 case BTRFS_BLOCK_GROUP_DUP:
1824 case BTRFS_BLOCK_GROUP_RAID0:
1825 return 0;
1826 case BTRFS_BLOCK_GROUP_RAID1:
1827 case BTRFS_BLOCK_GROUP_RAID5:
1828 case BTRFS_BLOCK_GROUP_RAID10:
1829 return 1;
1830 case BTRFS_BLOCK_GROUP_RAID6:
1831 return 2;
1832 default:
1833 return -1;
1837 int btrfs_scan_devices(void)
1839 int fd = -1;
1840 int ret;
1841 u64 num_devices;
1842 struct btrfs_fs_devices *tmp_devices;
1843 blkid_dev_iterate iter = NULL;
1844 blkid_dev dev = NULL;
1845 blkid_cache cache = NULL;
1846 char path[PATH_MAX];
1848 if (btrfs_scan_done)
1849 return 0;
1851 if (blkid_get_cache(&cache, NULL) < 0) {
1852 error("blkid cache get failed");
1853 return 1;
1855 blkid_probe_all(cache);
1856 iter = blkid_dev_iterate_begin(cache);
1857 blkid_dev_set_search(iter, "TYPE", "btrfs");
1858 while (blkid_dev_next(iter, &dev) == 0) {
1859 dev = blkid_verify(cache, dev);
1860 if (!dev)
1861 continue;
1862 /* if we are here its definitely a btrfs disk*/
1863 strncpy_null(path, blkid_dev_devname(dev));
1865 fd = open(path, O_RDONLY);
1866 if (fd < 0) {
1867 error("cannot open %s: %s", path, strerror(errno));
1868 continue;
1870 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
1871 &num_devices, BTRFS_SUPER_INFO_OFFSET,
1872 SBREAD_DEFAULT);
1873 if (ret) {
1874 error("cannot scan %s: %s", path, strerror(-ret));
1875 close (fd);
1876 continue;
1879 close(fd);
1881 blkid_dev_iterate_end(iter);
1882 blkid_put_cache(cache);
1884 btrfs_scan_done = 1;
1886 return 0;
1890 * This reads a line from the stdin and only returns non-zero if the
1891 * first whitespace delimited token is a case insensitive match with yes
1892 * or y.
1894 int ask_user(const char *question)
1896 char buf[30] = {0,};
1897 char *saveptr = NULL;
1898 char *answer;
1900 printf("%s [y/N]: ", question);
1902 return fgets(buf, sizeof(buf) - 1, stdin) &&
1903 (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
1904 (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
1908 * return 0 if a btrfs mount point is found
1909 * return 1 if a mount point is found but not btrfs
1910 * return <0 if something goes wrong
1912 int find_mount_root(const char *path, char **mount_root)
1914 FILE *mnttab;
1915 int fd;
1916 struct mntent *ent;
1917 int len;
1918 int ret;
1919 int not_btrfs = 1;
1920 int longest_matchlen = 0;
1921 char *longest_match = NULL;
1923 fd = open(path, O_RDONLY | O_NOATIME);
1924 if (fd < 0)
1925 return -errno;
1926 close(fd);
1928 mnttab = setmntent("/proc/self/mounts", "r");
1929 if (!mnttab)
1930 return -errno;
1932 while ((ent = getmntent(mnttab))) {
1933 len = strlen(ent->mnt_dir);
1934 if (strncmp(ent->mnt_dir, path, len) == 0) {
1935 /* match found and use the latest match */
1936 if (longest_matchlen <= len) {
1937 free(longest_match);
1938 longest_matchlen = len;
1939 longest_match = strdup(ent->mnt_dir);
1940 not_btrfs = strcmp(ent->mnt_type, "btrfs");
1944 endmntent(mnttab);
1946 if (!longest_match)
1947 return -ENOENT;
1948 if (not_btrfs) {
1949 free(longest_match);
1950 return 1;
1953 ret = 0;
1954 *mount_root = realpath(longest_match, NULL);
1955 if (!*mount_root)
1956 ret = -errno;
1958 free(longest_match);
1959 return ret;
1963 * Test if path is a directory
1964 * Returns:
1965 * 0 - path exists but it is not a directory
1966 * 1 - path exists and it is a directory
1967 * < 0 - error
1969 int test_isdir(const char *path)
1971 struct stat st;
1972 int ret;
1974 ret = stat(path, &st);
1975 if (ret < 0)
1976 return -errno;
1978 return !!S_ISDIR(st.st_mode);
1981 void units_set_mode(unsigned *units, unsigned mode)
1983 unsigned base = *units & UNITS_MODE_MASK;
1985 *units = base | mode;
1988 void units_set_base(unsigned *units, unsigned base)
1990 unsigned mode = *units & ~UNITS_MODE_MASK;
1992 *units = base | mode;
1995 int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
1997 int level;
1999 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2000 if (!path->nodes[level])
2001 break;
2002 if (path->slots[level] + 1 >=
2003 btrfs_header_nritems(path->nodes[level]))
2004 continue;
2005 if (level == 0)
2006 btrfs_item_key_to_cpu(path->nodes[level], key,
2007 path->slots[level] + 1);
2008 else
2009 btrfs_node_key_to_cpu(path->nodes[level], key,
2010 path->slots[level] + 1);
2011 return 0;
2013 return 1;
2016 const char* btrfs_group_type_str(u64 flag)
2018 u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
2019 BTRFS_SPACE_INFO_GLOBAL_RSV;
2021 switch (flag & mask) {
2022 case BTRFS_BLOCK_GROUP_DATA:
2023 return "Data";
2024 case BTRFS_BLOCK_GROUP_SYSTEM:
2025 return "System";
2026 case BTRFS_BLOCK_GROUP_METADATA:
2027 return "Metadata";
2028 case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
2029 return "Data+Metadata";
2030 case BTRFS_SPACE_INFO_GLOBAL_RSV:
2031 return "GlobalReserve";
2032 default:
2033 return "unknown";
2037 const char* btrfs_group_profile_str(u64 flag)
2039 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2040 case 0:
2041 return "single";
2042 case BTRFS_BLOCK_GROUP_RAID0:
2043 return "RAID0";
2044 case BTRFS_BLOCK_GROUP_RAID1:
2045 return "RAID1";
2046 case BTRFS_BLOCK_GROUP_RAID5:
2047 return "RAID5";
2048 case BTRFS_BLOCK_GROUP_RAID6:
2049 return "RAID6";
2050 case BTRFS_BLOCK_GROUP_DUP:
2051 return "DUP";
2052 case BTRFS_BLOCK_GROUP_RAID10:
2053 return "RAID10";
2054 default:
2055 return "unknown";
2059 u64 disk_size(const char *path)
2061 struct statfs sfs;
2063 if (statfs(path, &sfs) < 0)
2064 return 0;
2065 else
2066 return sfs.f_bsize * sfs.f_blocks;
2069 u64 get_partition_size(const char *dev)
2071 u64 result;
2072 int fd = open(dev, O_RDONLY);
2074 if (fd < 0)
2075 return 0;
2076 if (ioctl(fd, BLKGETSIZE64, &result) < 0) {
2077 close(fd);
2078 return 0;
2080 close(fd);
2082 return result;
2086 * Check if the BTRFS_IOC_TREE_SEARCH_V2 ioctl is supported on a given
2087 * filesystem, opened at fd
2089 int btrfs_tree_search2_ioctl_supported(int fd)
2091 struct btrfs_ioctl_search_args_v2 *args2;
2092 struct btrfs_ioctl_search_key *sk;
2093 int args2_size = 1024;
2094 char args2_buf[args2_size];
2095 int ret;
2097 args2 = (struct btrfs_ioctl_search_args_v2 *)args2_buf;
2098 sk = &(args2->key);
2101 * Search for the extent tree item in the root tree.
2103 sk->tree_id = BTRFS_ROOT_TREE_OBJECTID;
2104 sk->min_objectid = BTRFS_EXTENT_TREE_OBJECTID;
2105 sk->max_objectid = BTRFS_EXTENT_TREE_OBJECTID;
2106 sk->min_type = BTRFS_ROOT_ITEM_KEY;
2107 sk->max_type = BTRFS_ROOT_ITEM_KEY;
2108 sk->min_offset = 0;
2109 sk->max_offset = (u64)-1;
2110 sk->min_transid = 0;
2111 sk->max_transid = (u64)-1;
2112 sk->nr_items = 1;
2113 args2->buf_size = args2_size - sizeof(struct btrfs_ioctl_search_args_v2);
2114 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH_V2, args2);
2115 if (ret == -EOPNOTSUPP)
2116 return 0;
2117 else if (ret == 0)
2118 return 1;
2119 return ret;
2122 int btrfs_check_nodesize(u32 nodesize, u32 sectorsize, u64 features)
2124 if (nodesize < sectorsize) {
2125 error("illegal nodesize %u (smaller than %u)",
2126 nodesize, sectorsize);
2127 return -1;
2128 } else if (nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2129 error("illegal nodesize %u (larger than %u)",
2130 nodesize, BTRFS_MAX_METADATA_BLOCKSIZE);
2131 return -1;
2132 } else if (nodesize & (sectorsize - 1)) {
2133 error("illegal nodesize %u (not aligned to %u)",
2134 nodesize, sectorsize);
2135 return -1;
2136 } else if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS &&
2137 nodesize != sectorsize) {
2138 error("illegal nodesize %u (not equal to %u for mixed block group)",
2139 nodesize, sectorsize);
2140 return -1;
2142 return 0;
2146 * Copy a path argument from SRC to DEST and check the SRC length if it's at
2147 * most PATH_MAX and fits into DEST. DESTLEN is supposed to be exact size of
2148 * the buffer.
2149 * The destination buffer is zero terminated.
2150 * Return < 0 for error, 0 otherwise.
2152 int arg_copy_path(char *dest, const char *src, int destlen)
2154 size_t len = strlen(src);
2156 if (len >= PATH_MAX || len >= destlen)
2157 return -ENAMETOOLONG;
2159 __strncpy_null(dest, src, destlen);
2161 return 0;
2164 unsigned int get_unit_mode_from_arg(int *argc, char *argv[], int df_mode)
2166 unsigned int unit_mode = UNITS_DEFAULT;
2167 int arg_i;
2168 int arg_end;
2170 for (arg_i = 0; arg_i < *argc; arg_i++) {
2171 if (!strcmp(argv[arg_i], "--"))
2172 break;
2174 if (!strcmp(argv[arg_i], "--raw")) {
2175 unit_mode = UNITS_RAW;
2176 argv[arg_i] = NULL;
2177 continue;
2179 if (!strcmp(argv[arg_i], "--human-readable")) {
2180 unit_mode = UNITS_HUMAN_BINARY;
2181 argv[arg_i] = NULL;
2182 continue;
2185 if (!strcmp(argv[arg_i], "--iec")) {
2186 units_set_mode(&unit_mode, UNITS_BINARY);
2187 argv[arg_i] = NULL;
2188 continue;
2190 if (!strcmp(argv[arg_i], "--si")) {
2191 units_set_mode(&unit_mode, UNITS_DECIMAL);
2192 argv[arg_i] = NULL;
2193 continue;
2196 if (!strcmp(argv[arg_i], "--kbytes")) {
2197 units_set_base(&unit_mode, UNITS_KBYTES);
2198 argv[arg_i] = NULL;
2199 continue;
2201 if (!strcmp(argv[arg_i], "--mbytes")) {
2202 units_set_base(&unit_mode, UNITS_MBYTES);
2203 argv[arg_i] = NULL;
2204 continue;
2206 if (!strcmp(argv[arg_i], "--gbytes")) {
2207 units_set_base(&unit_mode, UNITS_GBYTES);
2208 argv[arg_i] = NULL;
2209 continue;
2211 if (!strcmp(argv[arg_i], "--tbytes")) {
2212 units_set_base(&unit_mode, UNITS_TBYTES);
2213 argv[arg_i] = NULL;
2214 continue;
2217 if (!df_mode)
2218 continue;
2220 if (!strcmp(argv[arg_i], "-b")) {
2221 unit_mode = UNITS_RAW;
2222 argv[arg_i] = NULL;
2223 continue;
2225 if (!strcmp(argv[arg_i], "-h")) {
2226 unit_mode = UNITS_HUMAN_BINARY;
2227 argv[arg_i] = NULL;
2228 continue;
2230 if (!strcmp(argv[arg_i], "-H")) {
2231 unit_mode = UNITS_HUMAN_DECIMAL;
2232 argv[arg_i] = NULL;
2233 continue;
2235 if (!strcmp(argv[arg_i], "-k")) {
2236 units_set_base(&unit_mode, UNITS_KBYTES);
2237 argv[arg_i] = NULL;
2238 continue;
2240 if (!strcmp(argv[arg_i], "-m")) {
2241 units_set_base(&unit_mode, UNITS_MBYTES);
2242 argv[arg_i] = NULL;
2243 continue;
2245 if (!strcmp(argv[arg_i], "-g")) {
2246 units_set_base(&unit_mode, UNITS_GBYTES);
2247 argv[arg_i] = NULL;
2248 continue;
2250 if (!strcmp(argv[arg_i], "-t")) {
2251 units_set_base(&unit_mode, UNITS_TBYTES);
2252 argv[arg_i] = NULL;
2253 continue;
2257 for (arg_i = 0, arg_end = 0; arg_i < *argc; arg_i++) {
2258 if (!argv[arg_i])
2259 continue;
2260 argv[arg_end] = argv[arg_i];
2261 arg_end++;
2264 *argc = arg_end;
2266 return unit_mode;
2269 u64 div_factor(u64 num, int factor)
2271 if (factor == 10)
2272 return num;
2273 num *= factor;
2274 num /= 10;
2275 return num;
2278 * Get the length of the string converted from a u64 number.
2280 * Result is equal to log10(num) + 1, but without the use of math library.
2282 int count_digits(u64 num)
2284 int ret = 0;
2286 if (num == 0)
2287 return 1;
2288 while (num > 0) {
2289 ret++;
2290 num /= 10;
2292 return ret;
2295 int string_is_numerical(const char *str)
2297 if (!str)
2298 return 0;
2299 if (!(*str >= '0' && *str <= '9'))
2300 return 0;
2301 while (*str >= '0' && *str <= '9')
2302 str++;
2303 if (*str != '\0')
2304 return 0;
2305 return 1;
2308 /* Subvolume helper functions */
2310 * test if name is a correct subvolume name
2311 * this function return
2312 * 0-> name is not a correct subvolume name
2313 * 1-> name is a correct subvolume name
2315 int test_issubvolname(const char *name)
2317 return name[0] != '\0' && !strchr(name, '/') &&
2318 strcmp(name, ".") && strcmp(name, "..");
2322 * Test if path is a subvolume
2323 * Returns:
2324 * 0 - path exists but it is not a subvolume
2325 * 1 - path exists and it is a subvolume
2326 * < 0 - error
2328 int test_issubvolume(const char *path)
2330 struct stat st;
2331 struct statfs stfs;
2332 int res;
2334 res = stat(path, &st);
2335 if (res < 0)
2336 return -errno;
2338 if (st.st_ino != BTRFS_FIRST_FREE_OBJECTID || !S_ISDIR(st.st_mode))
2339 return 0;
2341 res = statfs(path, &stfs);
2342 if (res < 0)
2343 return -errno;
2345 return (int)stfs.f_type == BTRFS_SUPER_MAGIC;
2348 const char *subvol_strip_mountpoint(const char *mnt, const char *full_path)
2350 int len = strlen(mnt);
2351 if (!len)
2352 return full_path;
2354 if (mnt[len - 1] != '/')
2355 len += 1;
2357 return full_path + len;
2361 * Returns
2362 * <0: Std error
2363 * 0: All fine
2364 * 1: Error; and error info printed to the terminal. Fixme.
2365 * 2: If the fullpath is root tree instead of subvol tree
2367 int get_subvol_info(const char *fullpath, struct root_info *get_ri)
2369 u64 sv_id;
2370 int ret = 1;
2371 int fd = -1;
2372 int mntfd = -1;
2373 char *mnt = NULL;
2374 const char *svpath = NULL;
2375 DIR *dirstream1 = NULL;
2376 DIR *dirstream2 = NULL;
2378 ret = test_issubvolume(fullpath);
2379 if (ret < 0)
2380 return ret;
2381 if (!ret) {
2382 error("not a subvolume: %s", fullpath);
2383 return 1;
2386 ret = find_mount_root(fullpath, &mnt);
2387 if (ret < 0)
2388 return ret;
2389 if (ret > 0) {
2390 error("%s doesn't belong to btrfs mount point", fullpath);
2391 return 1;
2393 ret = 1;
2394 svpath = subvol_strip_mountpoint(mnt, fullpath);
2396 fd = btrfs_open_dir(fullpath, &dirstream1, 1);
2397 if (fd < 0)
2398 goto out;
2400 ret = btrfs_list_get_path_rootid(fd, &sv_id);
2401 if (ret)
2402 goto out;
2404 mntfd = btrfs_open_dir(mnt, &dirstream2, 1);
2405 if (mntfd < 0)
2406 goto out;
2408 memset(get_ri, 0, sizeof(*get_ri));
2409 get_ri->root_id = sv_id;
2411 if (sv_id == BTRFS_FS_TREE_OBJECTID)
2412 ret = btrfs_get_toplevel_subvol(mntfd, get_ri);
2413 else
2414 ret = btrfs_get_subvol(mntfd, get_ri);
2415 if (ret)
2416 error("can't find '%s': %d", svpath, ret);
2418 out:
2419 close_file_or_dir(mntfd, dirstream2);
2420 close_file_or_dir(fd, dirstream1);
2421 free(mnt);
2423 return ret;
2426 /* Set the seed manually */
2427 void init_rand_seed(u64 seed)
2429 int i;
2431 /* only use the last 48 bits */
2432 for (i = 0; i < 3; i++) {
2433 rand_seed[i] = (unsigned short)(seed ^ (unsigned short)(-1));
2434 seed >>= 16;
2436 rand_seed_initlized = 1;
2439 static void __init_seed(void)
2441 struct timeval tv;
2442 int ret;
2443 int fd;
2445 if(rand_seed_initlized)
2446 return;
2447 /* Use urandom as primary seed source. */
2448 fd = open("/dev/urandom", O_RDONLY);
2449 if (fd >= 0) {
2450 ret = read(fd, rand_seed, sizeof(rand_seed));
2451 close(fd);
2452 if (ret < sizeof(rand_seed))
2453 goto fallback;
2454 } else {
2455 fallback:
2456 /* Use time and pid as fallback seed */
2457 warning("failed to read /dev/urandom, use time and pid as random seed");
2458 gettimeofday(&tv, 0);
2459 rand_seed[0] = getpid() ^ (tv.tv_sec & 0xFFFF);
2460 rand_seed[1] = getppid() ^ (tv.tv_usec & 0xFFFF);
2461 rand_seed[2] = (tv.tv_sec ^ tv.tv_usec) >> 16;
2463 rand_seed_initlized = 1;
2466 u32 rand_u32(void)
2468 __init_seed();
2470 * Don't use nrand48, its range is [0,2^31) The highest bit will alwasy
2471 * be 0. Use jrand48 to include the highest bit.
2473 return (u32)jrand48(rand_seed);
2476 /* Return random number in range [0, upper) */
2477 unsigned int rand_range(unsigned int upper)
2479 __init_seed();
2481 * Use the full 48bits to mod, which would be more uniformly
2482 * distributed
2484 return (unsigned int)(jrand48(rand_seed) % upper);
2487 int rand_int(void)
2489 return (int)(rand_u32());
2492 u64 rand_u64(void)
2494 u64 ret = 0;
2496 ret += rand_u32();
2497 ret <<= 32;
2498 ret += rand_u32();
2499 return ret;
2502 u16 rand_u16(void)
2504 return (u16)(rand_u32());
2507 u8 rand_u8(void)
2509 return (u8)(rand_u32());
2512 void btrfs_config_init(void)