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.
23 #include <sys/ioctl.h>
24 #include <sys/mount.h>
25 #include <sys/types.h>
27 #include <uuid/uuid.h>
32 #include <linux/loop.h>
33 #include <linux/major.h>
34 #include <linux/kdev_t.h>
36 #include <blkid/blkid.h>
38 #include <sys/statfs.h>
39 #include <linux/magic.h>
42 #include "kerncompat.h"
43 #include "radix-tree.h"
46 #include "transaction.h"
54 #define BLKDISCARD _IO(0x12,119)
57 static int btrfs_scan_done = 0;
59 static int rand_seed_initlized = 0;
60 static unsigned short rand_seed[3];
62 struct btrfs_config bconf;
65 * Discard the given range in one go
67 static int discard_range(int fd, u64 start, u64 len)
69 u64 range[2] = { start, len };
71 if (ioctl(fd, BLKDISCARD, &range) < 0)
77 * Discard blocks in the given range in 1G chunks, the process is interruptible
79 static int discard_blocks(int fd, u64 start, u64 len)
83 u64 chunk_size = min_t(u64, len, SZ_1G);
86 ret = discard_range(fd, start, chunk_size);
96 int test_uuid_unique(char *fs_uuid)
99 blkid_dev_iterate iter = NULL;
100 blkid_dev dev = NULL;
101 blkid_cache cache = NULL;
103 if (blkid_get_cache(&cache, NULL) < 0) {
104 printf("ERROR: lblkid cache get failed\n");
107 blkid_probe_all(cache);
108 iter = blkid_dev_iterate_begin(cache);
109 blkid_dev_set_search(iter, "UUID", fs_uuid);
111 while (blkid_dev_next(iter, &dev) == 0) {
112 dev = blkid_verify(cache, dev);
119 blkid_dev_iterate_end(iter);
120 blkid_put_cache(cache);
125 u64 btrfs_device_size(int fd, struct stat *st)
128 if (S_ISREG(st->st_mode)) {
131 if (!S_ISBLK(st->st_mode)) {
134 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
140 static int zero_blocks(int fd, off_t start, size_t len)
142 char *buf = malloc(len);
149 written = pwrite(fd, buf, len, start);
156 #define ZERO_DEV_BYTES SZ_2M
158 /* don't write outside the device by clamping the region to the device size */
159 static int zero_dev_clamped(int fd, off_t start, ssize_t len, u64 dev_size)
161 off_t end = max(start, start + len);
164 /* and don't overwrite the disk labels on sparc */
165 start = max(start, 1024);
166 end = max(end, 1024);
169 start = min_t(u64, start, dev_size);
170 end = min_t(u64, end, dev_size);
172 return zero_blocks(fd, start, end - start);
175 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
176 struct btrfs_root *root, int fd, const char *path,
177 u64 device_total_bytes, u32 io_width, u32 io_align,
180 struct btrfs_super_block *disk_super;
181 struct btrfs_super_block *super = root->fs_info->super_copy;
182 struct btrfs_device *device;
183 struct btrfs_dev_item *dev_item;
189 device_total_bytes = (device_total_bytes / sectorsize) * sectorsize;
191 device = calloc(1, sizeof(*device));
196 buf = calloc(1, sectorsize);
202 disk_super = (struct btrfs_super_block *)buf;
203 dev_item = &disk_super->dev_item;
205 uuid_generate(device->uuid);
208 device->io_width = io_width;
209 device->io_align = io_align;
210 device->sector_size = sectorsize;
212 device->writeable = 1;
213 device->total_bytes = device_total_bytes;
214 device->bytes_used = 0;
215 device->total_ios = 0;
216 device->dev_root = root->fs_info->dev_root;
217 device->name = strdup(path);
223 INIT_LIST_HEAD(&device->dev_list);
224 ret = btrfs_add_device(trans, root, device);
228 fs_total_bytes = btrfs_super_total_bytes(super) + device_total_bytes;
229 btrfs_set_super_total_bytes(super, fs_total_bytes);
231 num_devs = btrfs_super_num_devices(super) + 1;
232 btrfs_set_super_num_devices(super, num_devs);
234 memcpy(disk_super, super, sizeof(*disk_super));
236 btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
237 btrfs_set_stack_device_id(dev_item, device->devid);
238 btrfs_set_stack_device_type(dev_item, device->type);
239 btrfs_set_stack_device_io_align(dev_item, device->io_align);
240 btrfs_set_stack_device_io_width(dev_item, device->io_width);
241 btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
242 btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
243 btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
244 memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
246 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
247 BUG_ON(ret != sectorsize);
250 list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
251 device->fs_devices = root->fs_info->fs_devices;
260 static int btrfs_wipe_existing_sb(int fd)
262 const char *off = NULL;
267 blkid_probe pr = NULL;
269 pr = blkid_new_probe();
273 if (blkid_probe_set_device(pr, fd, 0, 0)) {
278 ret = blkid_probe_lookup_value(pr, "SBMAGIC_OFFSET", &off, NULL);
280 ret = blkid_probe_lookup_value(pr, "SBMAGIC", NULL, &len);
282 if (ret || len == 0 || off == NULL) {
284 * If lookup fails, the probe did not find any values, eg. for
285 * a file image or a loop device. Soft error.
291 offset = strtoll(off, NULL, 10);
292 if (len > sizeof(buf))
296 ret = pwrite(fd, buf, len, offset);
298 error("cannot wipe existing superblock: %s", strerror(errno));
300 } else if (ret != len) {
301 error("cannot wipe existing superblock: wrote %d of %zd", ret, len);
307 blkid_free_probe(pr);
311 int btrfs_prepare_device(int fd, const char *file, u64 *block_count_ret,
312 u64 max_block_count, unsigned opflags)
318 ret = fstat(fd, &st);
320 error("unable to stat %s: %s", file, strerror(errno));
324 block_count = btrfs_device_size(fd, &st);
325 if (block_count == 0) {
326 error("unable to determine size of %s", file);
330 block_count = min(block_count, max_block_count);
332 if (opflags & PREP_DEVICE_DISCARD) {
334 * We intentionally ignore errors from the discard ioctl. It
335 * is not necessary for the mkfs functionality but just an
338 if (discard_range(fd, 0, 0) == 0) {
339 if (opflags & PREP_DEVICE_VERBOSE)
340 printf("Performing full device TRIM %s (%s) ...\n",
341 file, pretty_size(block_count));
342 discard_blocks(fd, 0, block_count);
346 ret = zero_dev_clamped(fd, 0, ZERO_DEV_BYTES, block_count);
347 for (i = 0 ; !ret && i < BTRFS_SUPER_MIRROR_MAX; i++)
348 ret = zero_dev_clamped(fd, btrfs_sb_offset(i),
349 BTRFS_SUPER_INFO_SIZE, block_count);
350 if (!ret && (opflags & PREP_DEVICE_ZERO_END))
351 ret = zero_dev_clamped(fd, block_count - ZERO_DEV_BYTES,
352 ZERO_DEV_BYTES, block_count);
355 error("failed to zero device '%s': %s", file, strerror(-ret));
359 ret = btrfs_wipe_existing_sb(fd);
361 error("cannot wipe superblocks on %s", file);
365 *block_count_ret = block_count;
369 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
370 struct btrfs_root *root, u64 objectid)
373 struct btrfs_inode_item inode_item;
374 time_t now = time(NULL);
376 memset(&inode_item, 0, sizeof(inode_item));
377 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
378 btrfs_set_stack_inode_size(&inode_item, 0);
379 btrfs_set_stack_inode_nlink(&inode_item, 1);
380 btrfs_set_stack_inode_nbytes(&inode_item, root->nodesize);
381 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
382 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
383 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
384 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
385 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
386 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
387 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
388 btrfs_set_stack_timespec_sec(&inode_item.otime, now);
389 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
391 if (root->fs_info->tree_root == root)
392 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
394 ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
398 ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
402 btrfs_set_root_dirid(&root->root_item, objectid);
409 * checks if a path is a block device node
410 * Returns negative errno on failure, otherwise
411 * returns 1 for blockdev, 0 for not-blockdev
413 int is_block_device(const char *path)
417 if (stat(path, &statbuf) < 0)
420 return !!S_ISBLK(statbuf.st_mode);
424 * check if given path is a mount point
425 * return 1 if yes. 0 if no. -1 for error
427 int is_mount_point(const char *path)
433 f = setmntent("/proc/self/mounts", "r");
437 while ((mnt = getmntent(f)) != NULL) {
438 if (strcmp(mnt->mnt_dir, path))
447 static int is_reg_file(const char *path)
451 if (stat(path, &statbuf) < 0)
453 return S_ISREG(statbuf.st_mode);
457 * This function checks if the given input parameter is
459 * return <0 : some error in the given input
460 * return BTRFS_ARG_UNKNOWN: unknown input
461 * return BTRFS_ARG_UUID: given input is uuid
462 * return BTRFS_ARG_MNTPOINT: given input is path
463 * return BTRFS_ARG_REG: given input is regular file
464 * return BTRFS_ARG_BLKDEV: given input is block device
466 int check_arg_type(const char *input)
474 if (realpath(input, path)) {
475 if (is_block_device(path) == 1)
476 return BTRFS_ARG_BLKDEV;
478 if (is_mount_point(path) == 1)
479 return BTRFS_ARG_MNTPOINT;
481 if (is_reg_file(path))
482 return BTRFS_ARG_REG;
484 return BTRFS_ARG_UNKNOWN;
487 if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
488 !uuid_parse(input, uuid))
489 return BTRFS_ARG_UUID;
491 return BTRFS_ARG_UNKNOWN;
495 * Find the mount point for a mounted device.
496 * On success, returns 0 with mountpoint in *mp.
497 * On failure, returns -errno (not mounted yields -EINVAL)
498 * Is noisy on failures, expects to be given a mounted device.
500 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
505 ret = is_block_device(dev);
508 error("not a block device: %s", dev);
511 error("cannot check %s: %s", dev, strerror(-ret));
516 fd = open(dev, O_RDONLY);
519 error("cannot open %s: %s", dev, strerror(errno));
523 ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
526 } else { /* mounted, all good */
536 * Given a pathname, return a filehandle to:
537 * the original pathname or,
538 * if the pathname is a mounted btrfs device, to its mountpoint.
540 * On error, return -1, errno should be set.
542 int open_path_or_dev_mnt(const char *path, DIR **dirstream, int verbose)
547 if (is_block_device(path)) {
548 ret = get_btrfs_mount(path, mp, sizeof(mp));
550 /* not a mounted btrfs dev */
551 error_on(verbose, "'%s' is not a mounted btrfs device",
556 ret = open_file_or_dir(mp, dirstream);
557 error_on(verbose && ret < 0, "can't access '%s': %s",
558 path, strerror(errno));
560 ret = btrfs_open_dir(path, dirstream, 1);
567 * Do the following checks before calling open_file_or_dir():
568 * 1: path is in a btrfs filesystem
569 * 2: path is a directory
571 int btrfs_open_dir(const char *path, DIR **dirstream, int verbose)
577 if (statfs(path, &stfs) != 0) {
578 error_on(verbose, "cannot access '%s': %s", path,
583 if (stfs.f_type != BTRFS_SUPER_MAGIC) {
584 error_on(verbose, "not a btrfs filesystem: %s", path);
588 if (stat(path, &st) != 0) {
589 error_on(verbose, "cannot access '%s': %s", path,
594 if (!S_ISDIR(st.st_mode)) {
595 error_on(verbose, "not a directory: %s", path);
599 ret = open_file_or_dir(path, dirstream);
601 error_on(verbose, "cannot access '%s': %s", path,
608 /* checks if a device is a loop device */
609 static int is_loop_device (const char* device) {
612 if(stat(device, &statbuf) < 0)
615 return (S_ISBLK(statbuf.st_mode) &&
616 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
620 * Takes a loop device path (e.g. /dev/loop0) and returns
621 * the associated file (e.g. /images/my_btrfs.img) using
624 static int resolve_loop_device_with_loopdev(const char* loop_dev, char* loop_file)
628 struct loop_info64 lo64;
630 fd = open(loop_dev, O_RDONLY | O_NONBLOCK);
633 ret = ioctl(fd, LOOP_GET_STATUS64, &lo64);
639 memcpy(loop_file, lo64.lo_file_name, sizeof(lo64.lo_file_name));
640 loop_file[sizeof(lo64.lo_file_name)] = 0;
648 /* Takes a loop device path (e.g. /dev/loop0) and returns
649 * the associated file (e.g. /images/my_btrfs.img) */
650 static int resolve_loop_device(const char* loop_dev, char* loop_file,
657 char real_loop_dev[PATH_MAX];
659 if (!realpath(loop_dev, real_loop_dev))
661 snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
662 if (!(f = fopen(p, "r"))) {
665 * It's possibly a partitioned loop device, which is
666 * resolvable with loopdev API.
668 return resolve_loop_device_with_loopdev(loop_dev, loop_file);
672 snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
673 ret = fscanf(f, fmt, loop_file);
682 * Checks whether a and b are identical or device
683 * files associated with the same block device
685 static int is_same_blk_file(const char* a, const char* b)
687 struct stat st_buf_a, st_buf_b;
688 char real_a[PATH_MAX];
689 char real_b[PATH_MAX];
691 if (!realpath(a, real_a))
692 strncpy_null(real_a, a);
694 if (!realpath(b, real_b))
695 strncpy_null(real_b, b);
697 /* Identical path? */
698 if (strcmp(real_a, real_b) == 0)
701 if (stat(a, &st_buf_a) < 0 || stat(b, &st_buf_b) < 0) {
707 /* Same blockdevice? */
708 if (S_ISBLK(st_buf_a.st_mode) && S_ISBLK(st_buf_b.st_mode) &&
709 st_buf_a.st_rdev == st_buf_b.st_rdev) {
714 if (st_buf_a.st_dev == st_buf_b.st_dev &&
715 st_buf_a.st_ino == st_buf_b.st_ino) {
722 /* checks if a and b are identical or device
723 * files associated with the same block device or
724 * if one file is a loop device that uses the other
727 static int is_same_loop_file(const char* a, const char* b)
729 char res_a[PATH_MAX];
730 char res_b[PATH_MAX];
731 const char* final_a = NULL;
732 const char* final_b = NULL;
735 /* Resolve a if it is a loop device */
736 if((ret = is_loop_device(a)) < 0) {
741 ret = resolve_loop_device(a, res_a, sizeof(res_a));
752 /* Resolve b if it is a loop device */
753 if ((ret = is_loop_device(b)) < 0) {
758 ret = resolve_loop_device(b, res_b, sizeof(res_b));
769 return is_same_blk_file(final_a, final_b);
772 /* Checks if a file exists and is a block or regular file*/
773 static int is_existing_blk_or_reg_file(const char* filename)
777 if(stat(filename, &st_buf) < 0) {
784 return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
787 /* Checks if a file is used (directly or indirectly via a loop device)
788 * by a device in fs_devices
790 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
794 struct list_head *head;
795 struct list_head *cur;
796 struct btrfs_device *device;
798 head = &fs_devices->devices;
799 list_for_each(cur, head) {
800 device = list_entry(cur, struct btrfs_device, dev_list);
802 if((ret = is_same_loop_file(device->name, file)))
810 * Resolve a pathname to a device mapper node to /dev/mapper/<name>
811 * Returns NULL on invalid input or malloc failure; Other failures
812 * will be handled by the caller using the input pathame.
814 char *canonicalize_dm_name(const char *ptname)
818 char path[PATH_MAX], name[PATH_MAX], *res = NULL;
820 if (!ptname || !*ptname)
823 snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
824 if (!(f = fopen(path, "r")))
827 /* read <name>\n from sysfs */
828 if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
830 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
832 if (access(path, F_OK) == 0)
840 * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
841 * to a device mapper pathname.
842 * Returns NULL on invalid input or malloc failure; Other failures
843 * will be handled by the caller using the input pathame.
845 char *canonicalize_path(const char *path)
852 canonical = realpath(path, NULL);
855 p = strrchr(canonical, '/');
856 if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
857 char *dm = canonicalize_dm_name(p + 1);
868 * returns 1 if the device was mounted, < 0 on error or 0 if everything
869 * is safe to continue.
871 int check_mounted(const char* file)
876 fd = open(file, O_RDONLY);
878 error("mount check: cannot open %s: %s", file,
883 ret = check_mounted_where(fd, file, NULL, 0, NULL);
889 int check_mounted_where(int fd, const char *file, char *where, int size,
890 struct btrfs_fs_devices **fs_dev_ret)
895 struct btrfs_fs_devices *fs_devices_mnt = NULL;
899 /* scan the initial device */
900 ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
901 &total_devs, BTRFS_SUPER_INFO_OFFSET, SBREAD_DEFAULT);
902 is_btrfs = (ret >= 0);
904 /* scan other devices */
905 if (is_btrfs && total_devs > 1) {
906 ret = btrfs_scan_devices();
911 /* iterate over the list of currently mounted filesystems */
912 if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
915 while ((mnt = getmntent (f)) != NULL) {
917 if(strcmp(mnt->mnt_type, "btrfs") != 0)
920 ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
922 /* ignore entries in the mount table that are not
923 associated with a file*/
924 if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
925 goto out_mntloop_err;
929 ret = is_same_loop_file(file, mnt->mnt_fsname);
933 goto out_mntloop_err;
938 /* Did we find an entry in mnt table? */
939 if (mnt && size && where) {
940 strncpy(where, mnt->mnt_dir, size);
944 *fs_dev_ret = fs_devices_mnt;
955 struct list_head list;
959 int btrfs_register_one_device(const char *fname)
961 struct btrfs_ioctl_vol_args args;
965 fd = open("/dev/btrfs-control", O_RDWR);
968 "failed to open /dev/btrfs-control, skipping device registration: %s",
972 memset(&args, 0, sizeof(args));
973 strncpy_null(args.name, fname);
974 ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
976 error("device scan failed on '%s': %s", fname,
985 * Register all devices in the fs_uuid list created in the user
986 * space. Ensure btrfs_scan_devices() is called before this func.
988 int btrfs_register_all_devices(void)
992 struct btrfs_fs_devices *fs_devices;
993 struct btrfs_device *device;
994 struct list_head *all_uuids;
996 all_uuids = btrfs_scanned_uuids();
998 list_for_each_entry(fs_devices, all_uuids, list) {
999 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1001 err = btrfs_register_one_device(device->name);
1011 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1014 struct btrfs_super_block *disk_super;
1018 buf = malloc(BTRFS_SUPER_INFO_SIZE);
1023 ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1024 if (ret != BTRFS_SUPER_INFO_SIZE)
1028 disk_super = (struct btrfs_super_block *)buf;
1030 * Accept devices from the same filesystem, allow partially created
1033 if (btrfs_super_magic(disk_super) != BTRFS_MAGIC &&
1034 btrfs_super_magic(disk_super) != BTRFS_MAGIC_PARTIAL)
1037 if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1047 * Note: this function uses a static per-thread buffer. Do not call this
1048 * function more than 10 times within one argument list!
1050 const char *pretty_size_mode(u64 size, unsigned mode)
1052 static __thread int ps_index = 0;
1053 static __thread char ps_array[10][32];
1056 ret = ps_array[ps_index];
1059 (void)pretty_size_snprintf(size, ret, 32, mode);
1064 static const char* unit_suffix_binary[] =
1065 { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1066 static const char* unit_suffix_decimal[] =
1067 { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
1069 int pretty_size_snprintf(u64 size, char *str, size_t str_size, unsigned unit_mode)
1075 const char** suffix = NULL;
1082 negative = !!(unit_mode & UNITS_NEGATIVE);
1083 unit_mode &= ~UNITS_NEGATIVE;
1085 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_RAW) {
1087 snprintf(str, str_size, "%lld", size);
1089 snprintf(str, str_size, "%llu", size);
1093 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_BINARY) {
1096 suffix = unit_suffix_binary;
1097 } else if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_DECIMAL) {
1100 suffix = unit_suffix_decimal;
1105 fprintf(stderr, "INTERNAL ERROR: unknown unit base, mode %d\n",
1113 switch (unit_mode & UNITS_MODE_MASK) {
1114 case UNITS_TBYTES: base *= mult; num_divs++;
1115 case UNITS_GBYTES: base *= mult; num_divs++;
1116 case UNITS_MBYTES: base *= mult; num_divs++;
1117 case UNITS_KBYTES: num_divs++;
1125 s64 ssize = (s64)size;
1126 s64 last_ssize = ssize;
1128 while ((ssize < 0 ? -ssize : ssize) >= mult) {
1133 last_size = (u64)last_ssize;
1135 while (size >= mult) {
1142 * If the value is smaller than base, we didn't do any
1143 * division, in that case, base should be 1, not original
1144 * base, or the unit will be wrong
1150 if (num_divs >= ARRAY_SIZE(unit_suffix_binary)) {
1152 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
1159 fraction = (float)(s64)last_size / base;
1161 fraction = (float)last_size / base;
1164 return snprintf(str, str_size, "%.2f%s", fraction, suffix[num_divs]);
1168 * __strncpy_null - strncpy with null termination
1169 * @dest: the target array
1170 * @src: the source string
1171 * @n: maximum bytes to copy (size of *dest)
1173 * Like strncpy, but ensures destination is null-terminated.
1175 * Copies the string pointed to by src, including the terminating null
1176 * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1177 * of n bytes. Then ensure that dest is null-terminated.
1179 char *__strncpy_null(char *dest, const char *src, size_t n)
1181 strncpy(dest, src, n);
1188 * Checks to make sure that the label matches our requirements.
1190 0 if everything is safe and usable
1191 -1 if the label is too long
1193 static int check_label(const char *input)
1195 int len = strlen(input);
1197 if (len > BTRFS_LABEL_SIZE - 1) {
1198 error("label %s is too long (max %d)", input,
1199 BTRFS_LABEL_SIZE - 1);
1206 static int set_label_unmounted(const char *dev, const char *label)
1208 struct btrfs_trans_handle *trans;
1209 struct btrfs_root *root;
1212 ret = check_mounted(dev);
1214 error("checking mount status of %s failed: %d", dev, ret);
1218 error("device %s is mounted, use mount point", dev);
1222 /* Open the super_block at the default location
1223 * and as read-write.
1225 root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1226 if (!root) /* errors are printed by open_ctree() */
1229 trans = btrfs_start_transaction(root, 1);
1230 __strncpy_null(root->fs_info->super_copy->label, label, BTRFS_LABEL_SIZE - 1);
1232 btrfs_commit_transaction(trans, root);
1234 /* Now we close it since we are done. */
1239 static int set_label_mounted(const char *mount_path, const char *labelp)
1242 char label[BTRFS_LABEL_SIZE];
1244 fd = open(mount_path, O_RDONLY | O_NOATIME);
1246 error("unable to access %s: %s", mount_path, strerror(errno));
1250 memset(label, 0, sizeof(label));
1251 __strncpy_null(label, labelp, BTRFS_LABEL_SIZE - 1);
1252 if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1253 error("unable to set label of %s: %s", mount_path,
1263 int get_label_unmounted(const char *dev, char *label)
1265 struct btrfs_root *root;
1268 ret = check_mounted(dev);
1270 error("checking mount status of %s failed: %d", dev, ret);
1274 /* Open the super_block at the default location
1277 root = open_ctree(dev, 0, 0);
1281 __strncpy_null(label, root->fs_info->super_copy->label,
1282 BTRFS_LABEL_SIZE - 1);
1284 /* Now we close it since we are done. */
1290 * If a partition is mounted, try to get the filesystem label via its
1291 * mounted path rather than device. Return the corresponding error
1292 * the user specified the device path.
1294 int get_label_mounted(const char *mount_path, char *labelp)
1296 char label[BTRFS_LABEL_SIZE];
1300 fd = open(mount_path, O_RDONLY | O_NOATIME);
1302 error("unable to access %s: %s", mount_path, strerror(errno));
1306 memset(label, '\0', sizeof(label));
1307 ret = ioctl(fd, BTRFS_IOC_GET_FSLABEL, label);
1309 if (errno != ENOTTY)
1310 error("unable to get label of %s: %s", mount_path,
1317 __strncpy_null(labelp, label, BTRFS_LABEL_SIZE - 1);
1322 int get_label(const char *btrfs_dev, char *label)
1326 ret = is_existing_blk_or_reg_file(btrfs_dev);
1328 ret = get_label_mounted(btrfs_dev, label);
1330 ret = get_label_unmounted(btrfs_dev, label);
1335 int set_label(const char *btrfs_dev, const char *label)
1339 if (check_label(label))
1342 ret = is_existing_blk_or_reg_file(btrfs_dev);
1344 ret = set_label_mounted(btrfs_dev, label);
1346 ret = set_label_unmounted(btrfs_dev, label);
1352 * A not-so-good version fls64. No fascinating optimization since
1353 * no one except parse_size use it
1355 static int fls64(u64 x)
1359 for (i = 0; i <64; i++)
1360 if (x << i & (1ULL << 63))
1365 u64 parse_size(char *s)
1373 error("size value is empty");
1377 error("size value '%s' is less equal than 0", s);
1380 ret = strtoull(s, &endptr, 10);
1382 error("size value '%s' is invalid", s);
1385 if (endptr[0] && endptr[1]) {
1386 error("illegal suffix contains character '%c' in wrong position",
1391 * strtoll returns LLONG_MAX when overflow, if this happens,
1392 * need to call strtoull to get the real size
1394 if (errno == ERANGE && ret == ULLONG_MAX) {
1395 error("size value '%s' is too large for u64", s);
1399 c = tolower(endptr[0]);
1422 error("unknown size descriptor '%c'", c);
1426 /* Check whether ret * mult overflow */
1427 if (fls64(ret) + fls64(mult) - 1 > 64) {
1428 error("size value '%s' is too large for u64", s);
1435 u64 parse_qgroupid(const char *p)
1437 char *s = strchr(p, '/');
1438 const char *ptr_src_end = p + strlen(p);
1439 char *ptr_parse_end = NULL;
1448 /* Numeric format like '0/257' is the primary case */
1450 id = strtoull(p, &ptr_parse_end, 10);
1451 if (ptr_parse_end != ptr_src_end)
1455 level = strtoull(p, &ptr_parse_end, 10);
1456 if (ptr_parse_end != s)
1459 id = strtoull(s + 1, &ptr_parse_end, 10);
1460 if (ptr_parse_end != ptr_src_end)
1463 return (level << BTRFS_QGROUP_LEVEL_SHIFT) | id;
1466 /* Path format like subv at 'my_subvol' is the fallback case */
1467 ret = test_issubvolume(p);
1468 if (ret < 0 || !ret)
1470 fd = open(p, O_RDONLY);
1473 ret = lookup_path_rootid(fd, &id);
1475 error("failed to lookup root id: %s", strerror(-ret));
1482 error("invalid qgroupid or subvolume path: %s", p);
1486 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
1492 ret = stat(fname, &st);
1496 if (S_ISDIR(st.st_mode)) {
1497 *dirstream = opendir(fname);
1500 fd = dirfd(*dirstream);
1501 } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
1502 fd = open(fname, open_flags);
1505 * we set this on purpose, in case the caller output
1506 * strerror(errno) as success
1514 closedir(*dirstream);
1521 int open_file_or_dir(const char *fname, DIR **dirstream)
1523 return open_file_or_dir3(fname, dirstream, O_RDWR);
1526 void close_file_or_dir(int fd, DIR *dirstream)
1529 closedir(dirstream);
1534 int get_device_info(int fd, u64 devid,
1535 struct btrfs_ioctl_dev_info_args *di_args)
1539 di_args->devid = devid;
1540 memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1542 ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1543 return ret < 0 ? -errno : 0;
1546 static u64 find_max_device_id(struct btrfs_ioctl_search_args *search_args,
1549 struct btrfs_dev_item *dev_item;
1550 char *buf = search_args->buf;
1552 buf += (nr_items - 1) * (sizeof(struct btrfs_ioctl_search_header)
1553 + sizeof(struct btrfs_dev_item));
1554 buf += sizeof(struct btrfs_ioctl_search_header);
1556 dev_item = (struct btrfs_dev_item *)buf;
1558 return btrfs_stack_device_id(dev_item);
1561 static int search_chunk_tree_for_fs_info(int fd,
1562 struct btrfs_ioctl_fs_info_args *fi_args)
1566 u64 start_devid = 1;
1567 struct btrfs_ioctl_search_args search_args;
1568 struct btrfs_ioctl_search_key *search_key = &search_args.key;
1570 fi_args->num_devices = 0;
1572 max_items = BTRFS_SEARCH_ARGS_BUFSIZE
1573 / (sizeof(struct btrfs_ioctl_search_header)
1574 + sizeof(struct btrfs_dev_item));
1576 search_key->tree_id = BTRFS_CHUNK_TREE_OBJECTID;
1577 search_key->min_objectid = BTRFS_DEV_ITEMS_OBJECTID;
1578 search_key->max_objectid = BTRFS_DEV_ITEMS_OBJECTID;
1579 search_key->min_type = BTRFS_DEV_ITEM_KEY;
1580 search_key->max_type = BTRFS_DEV_ITEM_KEY;
1581 search_key->min_transid = 0;
1582 search_key->max_transid = (u64)-1;
1583 search_key->nr_items = max_items;
1584 search_key->max_offset = (u64)-1;
1587 search_key->min_offset = start_devid;
1589 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &search_args);
1593 fi_args->num_devices += (u64)search_key->nr_items;
1595 if (search_key->nr_items == max_items) {
1596 start_devid = find_max_device_id(&search_args,
1597 search_key->nr_items) + 1;
1601 /* get the lastest max_id to stay consistent with the num_devices */
1602 if (search_key->nr_items == 0)
1604 * last tree_search returns an empty buf, use the devid of
1605 * the last dev_item of the previous tree_search
1607 fi_args->max_id = start_devid - 1;
1609 fi_args->max_id = find_max_device_id(&search_args,
1610 search_key->nr_items);
1616 * For a given path, fill in the ioctl fs_ and info_ args.
1617 * If the path is a btrfs mountpoint, fill info for all devices.
1618 * If the path is a btrfs device, fill in only that device.
1620 * The path provided must be either on a mounted btrfs fs,
1621 * or be a mounted btrfs device.
1623 * Returns 0 on success, or a negative errno.
1625 int get_fs_info(const char *path, struct btrfs_ioctl_fs_info_args *fi_args,
1626 struct btrfs_ioctl_dev_info_args **di_ret)
1633 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1634 struct btrfs_ioctl_dev_info_args *di_args;
1635 struct btrfs_ioctl_dev_info_args tmp;
1637 DIR *dirstream = NULL;
1639 memset(fi_args, 0, sizeof(*fi_args));
1641 if (is_block_device(path) == 1) {
1642 struct btrfs_super_block *disk_super;
1643 char buf[BTRFS_SUPER_INFO_SIZE];
1645 /* Ensure it's mounted, then set path to the mountpoint */
1646 fd = open(path, O_RDONLY);
1649 error("cannot open %s: %s", path, strerror(errno));
1652 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1661 /* Only fill in this one device */
1662 fi_args->num_devices = 1;
1664 disk_super = (struct btrfs_super_block *)buf;
1665 ret = btrfs_read_dev_super(fd, disk_super,
1666 BTRFS_SUPER_INFO_OFFSET, 0);
1671 last_devid = btrfs_stack_device_id(&disk_super->dev_item);
1672 fi_args->max_id = last_devid;
1674 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1678 /* at this point path must not be for a block device */
1679 fd = open_file_or_dir(path, &dirstream);
1685 /* fill in fi_args if not just a single device */
1686 if (fi_args->num_devices != 1) {
1687 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
1694 * The fs_args->num_devices does not include seed devices
1696 ret = search_chunk_tree_for_fs_info(fd, fi_args);
1701 * search_chunk_tree_for_fs_info() will lacks the devid 0
1702 * so manual probe for it here.
1704 ret = get_device_info(fd, 0, &tmp);
1706 fi_args->num_devices++;
1709 if (last_devid == 0)
1714 if (!fi_args->num_devices)
1717 di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
1724 memcpy(di_args, &tmp, sizeof(tmp));
1725 for (; last_devid <= fi_args->max_id; last_devid++) {
1726 ret = get_device_info(fd, last_devid, &di_args[ndevs]);
1735 * only when the only dev we wanted to find is not there then
1736 * let any error be returned
1738 if (fi_args->num_devices != 1) {
1744 close_file_or_dir(fd, dirstream);
1748 #define isoctal(c) (((c) & ~7) == '0')
1750 static inline void translate(char *f, char *t)
1752 while (*f != '\0') {
1754 isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
1755 *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
1765 * Checks if the swap device.
1766 * Returns 1 if swap device, < 0 on error or 0 if not swap device.
1768 static int is_swap_device(const char *file)
1779 if (stat(file, &st_buf) < 0)
1781 if (S_ISBLK(st_buf.st_mode))
1782 dev = st_buf.st_rdev;
1783 else if (S_ISREG(st_buf.st_mode)) {
1784 dev = st_buf.st_dev;
1785 ino = st_buf.st_ino;
1789 if ((f = fopen("/proc/swaps", "r")) == NULL)
1792 /* skip the first line */
1793 if (fgets(tmp, sizeof(tmp), f) == NULL)
1796 while (fgets(tmp, sizeof(tmp), f) != NULL) {
1797 if ((cp = strchr(tmp, ' ')) != NULL)
1799 if ((cp = strchr(tmp, '\t')) != NULL)
1801 translate(tmp, buf);
1802 if (stat(buf, &st_buf) != 0)
1804 if (S_ISBLK(st_buf.st_mode)) {
1805 if (dev == st_buf.st_rdev) {
1809 } else if (S_ISREG(st_buf.st_mode)) {
1810 if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
1824 * Check for existing filesystem or partition table on device.
1826 * 1 for existing fs or partition
1827 * 0 for nothing found
1828 * -1 for internal error
1830 static int check_overwrite(const char *device)
1833 blkid_probe pr = NULL;
1837 if (!device || !*device)
1840 ret = -1; /* will reset on success of all setup calls */
1842 pr = blkid_new_probe_from_filename(device);
1846 size = blkid_probe_get_size(pr);
1850 /* nothing to overwrite on a 0-length device */
1856 ret = blkid_probe_enable_partitions(pr, 1);
1860 ret = blkid_do_fullprobe(pr);
1865 * Blkid returns 1 for nothing found and 0 when it finds a signature,
1866 * but we want the exact opposite, so reverse the return value here.
1868 * In addition print some useful diagnostics about what actually is
1876 if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
1878 "%s appears to contain an existing "
1879 "filesystem (%s).\n", device, type);
1880 } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
1882 "%s appears to contain a partition "
1883 "table (%s).\n", device, type);
1886 "%s appears to contain something weird "
1887 "according to blkid\n", device);
1893 blkid_free_probe(pr);
1896 "probe of %s failed, cannot detect "
1897 "existing filesystem.\n", device);
1901 static int group_profile_devs_min(u64 flag)
1903 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
1904 case 0: /* single */
1905 case BTRFS_BLOCK_GROUP_DUP:
1907 case BTRFS_BLOCK_GROUP_RAID0:
1908 case BTRFS_BLOCK_GROUP_RAID1:
1909 case BTRFS_BLOCK_GROUP_RAID5:
1911 case BTRFS_BLOCK_GROUP_RAID6:
1913 case BTRFS_BLOCK_GROUP_RAID10:
1920 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
1921 u64 dev_cnt, int mixed, int ssd)
1924 u64 profile = metadata_profile | data_profile;
1929 allowed |= BTRFS_BLOCK_GROUP_RAID10;
1931 allowed |= BTRFS_BLOCK_GROUP_RAID6;
1933 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
1934 BTRFS_BLOCK_GROUP_RAID5;
1936 allowed |= BTRFS_BLOCK_GROUP_DUP;
1939 if (dev_cnt > 1 && profile & BTRFS_BLOCK_GROUP_DUP) {
1940 warning("DUP is not recommended on filesystem with multiple devices");
1942 if (metadata_profile & ~allowed) {
1944 "ERROR: unable to create FS with metadata profile %s "
1945 "(have %llu devices but %d devices are required)\n",
1946 btrfs_group_profile_str(metadata_profile), dev_cnt,
1947 group_profile_devs_min(metadata_profile));
1950 if (data_profile & ~allowed) {
1952 "ERROR: unable to create FS with data profile %s "
1953 "(have %llu devices but %d devices are required)\n",
1954 btrfs_group_profile_str(data_profile), dev_cnt,
1955 group_profile_devs_min(data_profile));
1959 if (dev_cnt == 3 && profile & BTRFS_BLOCK_GROUP_RAID6) {
1960 warning("RAID6 is not recommended on filesystem with 3 devices only");
1962 if (dev_cnt == 2 && profile & BTRFS_BLOCK_GROUP_RAID5) {
1963 warning("RAID5 is not recommended on filesystem with 2 devices only");
1965 warning_on(!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP) && ssd,
1966 "DUP may not actually lead to 2 copies on the device, see manual page");
1971 int group_profile_max_safe_loss(u64 flags)
1973 switch (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
1974 case 0: /* single */
1975 case BTRFS_BLOCK_GROUP_DUP:
1976 case BTRFS_BLOCK_GROUP_RAID0:
1978 case BTRFS_BLOCK_GROUP_RAID1:
1979 case BTRFS_BLOCK_GROUP_RAID5:
1980 case BTRFS_BLOCK_GROUP_RAID10:
1982 case BTRFS_BLOCK_GROUP_RAID6:
1990 * Check if a device is suitable for btrfs
1992 * 1: something is wrong, an error is printed
1995 int test_dev_for_mkfs(const char *file, int force_overwrite)
2000 ret = is_swap_device(file);
2002 error("checking status of %s: %s", file, strerror(-ret));
2006 error("%s is a swap device", file);
2009 if (!force_overwrite) {
2010 if (check_overwrite(file)) {
2011 error("use the -f option to force overwrite of %s",
2016 ret = check_mounted(file);
2018 error("cannot check mount status of %s: %s", file,
2023 error("%s is mounted", file);
2026 /* check if the device is busy */
2027 fd = open(file, O_RDWR|O_EXCL);
2029 error("unable to open %s: %s", file, strerror(errno));
2032 if (fstat(fd, &st)) {
2033 error("unable to stat %s: %s", file, strerror(errno));
2037 if (!S_ISBLK(st.st_mode)) {
2038 error("%s is not a block device", file);
2046 int btrfs_scan_devices(void)
2051 struct btrfs_fs_devices *tmp_devices;
2052 blkid_dev_iterate iter = NULL;
2053 blkid_dev dev = NULL;
2054 blkid_cache cache = NULL;
2055 char path[PATH_MAX];
2057 if (btrfs_scan_done)
2060 if (blkid_get_cache(&cache, NULL) < 0) {
2061 error("blkid cache get failed");
2064 blkid_probe_all(cache);
2065 iter = blkid_dev_iterate_begin(cache);
2066 blkid_dev_set_search(iter, "TYPE", "btrfs");
2067 while (blkid_dev_next(iter, &dev) == 0) {
2068 dev = blkid_verify(cache, dev);
2071 /* if we are here its definitely a btrfs disk*/
2072 strncpy_null(path, blkid_dev_devname(dev));
2074 fd = open(path, O_RDONLY);
2076 error("cannot open %s: %s", path, strerror(errno));
2079 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
2080 &num_devices, BTRFS_SUPER_INFO_OFFSET,
2083 error("cannot scan %s: %s", path, strerror(-ret));
2090 blkid_dev_iterate_end(iter);
2091 blkid_put_cache(cache);
2093 btrfs_scan_done = 1;
2098 int is_vol_small(const char *file)
2105 fd = open(file, O_RDONLY);
2108 if (fstat(fd, &st) < 0) {
2113 size = btrfs_device_size(fd, &st);
2118 if (size < BTRFS_MKFS_SMALL_VOLUME_SIZE) {
2128 * This reads a line from the stdin and only returns non-zero if the
2129 * first whitespace delimited token is a case insensitive match with yes
2132 int ask_user(const char *question)
2134 char buf[30] = {0,};
2135 char *saveptr = NULL;
2138 printf("%s [y/N]: ", question);
2140 return fgets(buf, sizeof(buf) - 1, stdin) &&
2141 (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
2142 (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
2146 * return 0 if a btrfs mount point is found
2147 * return 1 if a mount point is found but not btrfs
2148 * return <0 if something goes wrong
2150 int find_mount_root(const char *path, char **mount_root)
2158 int longest_matchlen = 0;
2159 char *longest_match = NULL;
2161 fd = open(path, O_RDONLY | O_NOATIME);
2166 mnttab = setmntent("/proc/self/mounts", "r");
2170 while ((ent = getmntent(mnttab))) {
2171 len = strlen(ent->mnt_dir);
2172 if (strncmp(ent->mnt_dir, path, len) == 0) {
2173 /* match found and use the latest match */
2174 if (longest_matchlen <= len) {
2175 free(longest_match);
2176 longest_matchlen = len;
2177 longest_match = strdup(ent->mnt_dir);
2178 not_btrfs = strcmp(ent->mnt_type, "btrfs");
2187 free(longest_match);
2192 *mount_root = realpath(longest_match, NULL);
2196 free(longest_match);
2200 int test_minimum_size(const char *file, u32 nodesize)
2203 struct stat statbuf;
2205 fd = open(file, O_RDONLY);
2208 if (stat(file, &statbuf) < 0) {
2212 if (btrfs_device_size(fd, &statbuf) < btrfs_min_dev_size(nodesize)) {
2222 * Test if path is a directory
2224 * 0 - path exists but it is not a directory
2225 * 1 - path exists and it is a directory
2228 int test_isdir(const char *path)
2233 ret = stat(path, &st);
2237 return !!S_ISDIR(st.st_mode);
2240 void units_set_mode(unsigned *units, unsigned mode)
2242 unsigned base = *units & UNITS_MODE_MASK;
2244 *units = base | mode;
2247 void units_set_base(unsigned *units, unsigned base)
2249 unsigned mode = *units & ~UNITS_MODE_MASK;
2251 *units = base | mode;
2254 int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
2258 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2259 if (!path->nodes[level])
2261 if (path->slots[level] + 1 >=
2262 btrfs_header_nritems(path->nodes[level]))
2265 btrfs_item_key_to_cpu(path->nodes[level], key,
2266 path->slots[level] + 1);
2268 btrfs_node_key_to_cpu(path->nodes[level], key,
2269 path->slots[level] + 1);
2275 const char* btrfs_group_type_str(u64 flag)
2277 u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
2278 BTRFS_SPACE_INFO_GLOBAL_RSV;
2280 switch (flag & mask) {
2281 case BTRFS_BLOCK_GROUP_DATA:
2283 case BTRFS_BLOCK_GROUP_SYSTEM:
2285 case BTRFS_BLOCK_GROUP_METADATA:
2287 case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
2288 return "Data+Metadata";
2289 case BTRFS_SPACE_INFO_GLOBAL_RSV:
2290 return "GlobalReserve";
2296 const char* btrfs_group_profile_str(u64 flag)
2298 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2301 case BTRFS_BLOCK_GROUP_RAID0:
2303 case BTRFS_BLOCK_GROUP_RAID1:
2305 case BTRFS_BLOCK_GROUP_RAID5:
2307 case BTRFS_BLOCK_GROUP_RAID6:
2309 case BTRFS_BLOCK_GROUP_DUP:
2311 case BTRFS_BLOCK_GROUP_RAID10:
2318 u64 disk_size(const char *path)
2322 if (statfs(path, &sfs) < 0)
2325 return sfs.f_bsize * sfs.f_blocks;
2328 u64 get_partition_size(const char *dev)
2331 int fd = open(dev, O_RDONLY);
2335 if (ioctl(fd, BLKGETSIZE64, &result) < 0) {
2345 * Check if the BTRFS_IOC_TREE_SEARCH_V2 ioctl is supported on a given
2346 * filesystem, opened at fd
2348 int btrfs_tree_search2_ioctl_supported(int fd)
2350 struct btrfs_ioctl_search_args_v2 *args2;
2351 struct btrfs_ioctl_search_key *sk;
2352 int args2_size = 1024;
2353 char args2_buf[args2_size];
2356 args2 = (struct btrfs_ioctl_search_args_v2 *)args2_buf;
2360 * Search for the extent tree item in the root tree.
2362 sk->tree_id = BTRFS_ROOT_TREE_OBJECTID;
2363 sk->min_objectid = BTRFS_EXTENT_TREE_OBJECTID;
2364 sk->max_objectid = BTRFS_EXTENT_TREE_OBJECTID;
2365 sk->min_type = BTRFS_ROOT_ITEM_KEY;
2366 sk->max_type = BTRFS_ROOT_ITEM_KEY;
2368 sk->max_offset = (u64)-1;
2369 sk->min_transid = 0;
2370 sk->max_transid = (u64)-1;
2372 args2->buf_size = args2_size - sizeof(struct btrfs_ioctl_search_args_v2);
2373 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH_V2, args2);
2374 if (ret == -EOPNOTSUPP)
2381 int btrfs_check_nodesize(u32 nodesize, u32 sectorsize, u64 features)
2383 if (nodesize < sectorsize) {
2384 error("illegal nodesize %u (smaller than %u)",
2385 nodesize, sectorsize);
2387 } else if (nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2388 error("illegal nodesize %u (larger than %u)",
2389 nodesize, BTRFS_MAX_METADATA_BLOCKSIZE);
2391 } else if (nodesize & (sectorsize - 1)) {
2392 error("illegal nodesize %u (not aligned to %u)",
2393 nodesize, sectorsize);
2395 } else if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS &&
2396 nodesize != sectorsize) {
2397 error("illegal nodesize %u (not equal to %u for mixed block group)",
2398 nodesize, sectorsize);
2405 * Copy a path argument from SRC to DEST and check the SRC length if it's at
2406 * most PATH_MAX and fits into DEST. DESTLEN is supposed to be exact size of
2408 * The destination buffer is zero terminated.
2409 * Return < 0 for error, 0 otherwise.
2411 int arg_copy_path(char *dest, const char *src, int destlen)
2413 size_t len = strlen(src);
2415 if (len >= PATH_MAX || len >= destlen)
2416 return -ENAMETOOLONG;
2418 __strncpy_null(dest, src, destlen);
2423 unsigned int get_unit_mode_from_arg(int *argc, char *argv[], int df_mode)
2425 unsigned int unit_mode = UNITS_DEFAULT;
2429 for (arg_i = 0; arg_i < *argc; arg_i++) {
2430 if (!strcmp(argv[arg_i], "--"))
2433 if (!strcmp(argv[arg_i], "--raw")) {
2434 unit_mode = UNITS_RAW;
2438 if (!strcmp(argv[arg_i], "--human-readable")) {
2439 unit_mode = UNITS_HUMAN_BINARY;
2444 if (!strcmp(argv[arg_i], "--iec")) {
2445 units_set_mode(&unit_mode, UNITS_BINARY);
2449 if (!strcmp(argv[arg_i], "--si")) {
2450 units_set_mode(&unit_mode, UNITS_DECIMAL);
2455 if (!strcmp(argv[arg_i], "--kbytes")) {
2456 units_set_base(&unit_mode, UNITS_KBYTES);
2460 if (!strcmp(argv[arg_i], "--mbytes")) {
2461 units_set_base(&unit_mode, UNITS_MBYTES);
2465 if (!strcmp(argv[arg_i], "--gbytes")) {
2466 units_set_base(&unit_mode, UNITS_GBYTES);
2470 if (!strcmp(argv[arg_i], "--tbytes")) {
2471 units_set_base(&unit_mode, UNITS_TBYTES);
2479 if (!strcmp(argv[arg_i], "-b")) {
2480 unit_mode = UNITS_RAW;
2484 if (!strcmp(argv[arg_i], "-h")) {
2485 unit_mode = UNITS_HUMAN_BINARY;
2489 if (!strcmp(argv[arg_i], "-H")) {
2490 unit_mode = UNITS_HUMAN_DECIMAL;
2494 if (!strcmp(argv[arg_i], "-k")) {
2495 units_set_base(&unit_mode, UNITS_KBYTES);
2499 if (!strcmp(argv[arg_i], "-m")) {
2500 units_set_base(&unit_mode, UNITS_MBYTES);
2504 if (!strcmp(argv[arg_i], "-g")) {
2505 units_set_base(&unit_mode, UNITS_GBYTES);
2509 if (!strcmp(argv[arg_i], "-t")) {
2510 units_set_base(&unit_mode, UNITS_TBYTES);
2516 for (arg_i = 0, arg_end = 0; arg_i < *argc; arg_i++) {
2519 argv[arg_end] = argv[arg_i];
2528 int string_is_numerical(const char *str)
2532 if (!(*str >= '0' && *str <= '9'))
2534 while (*str >= '0' && *str <= '9')
2541 /* Subvolume helper functions */
2543 * test if name is a correct subvolume name
2544 * this function return
2545 * 0-> name is not a correct subvolume name
2546 * 1-> name is a correct subvolume name
2548 int test_issubvolname(const char *name)
2550 return name[0] != '\0' && !strchr(name, '/') &&
2551 strcmp(name, ".") && strcmp(name, "..");
2555 * Test if path is a subvolume
2557 * 0 - path exists but it is not a subvolume
2558 * 1 - path exists and it is a subvolume
2561 int test_issubvolume(const char *path)
2567 res = stat(path, &st);
2571 if (st.st_ino != BTRFS_FIRST_FREE_OBJECTID || !S_ISDIR(st.st_mode))
2574 res = statfs(path, &stfs);
2578 return (int)stfs.f_type == BTRFS_SUPER_MAGIC;
2581 const char *subvol_strip_mountpoint(const char *mnt, const char *full_path)
2583 int len = strlen(mnt);
2587 if (mnt[len - 1] != '/')
2590 return full_path + len;
2597 * 1: Error; and error info printed to the terminal. Fixme.
2598 * 2: If the fullpath is root tree instead of subvol tree
2600 int get_subvol_info(const char *fullpath, struct root_info *get_ri)
2607 const char *svpath = NULL;
2608 DIR *dirstream1 = NULL;
2609 DIR *dirstream2 = NULL;
2611 ret = test_issubvolume(fullpath);
2615 error("not a subvolume: %s", fullpath);
2619 ret = find_mount_root(fullpath, &mnt);
2623 error("%s doesn't belong to btrfs mount point", fullpath);
2627 svpath = subvol_strip_mountpoint(mnt, fullpath);
2629 fd = btrfs_open_dir(fullpath, &dirstream1, 1);
2633 ret = btrfs_list_get_path_rootid(fd, &sv_id);
2637 mntfd = btrfs_open_dir(mnt, &dirstream2, 1);
2641 memset(get_ri, 0, sizeof(*get_ri));
2642 get_ri->root_id = sv_id;
2644 if (sv_id == BTRFS_FS_TREE_OBJECTID)
2645 ret = btrfs_get_toplevel_subvol(mntfd, get_ri);
2647 ret = btrfs_get_subvol(mntfd, get_ri);
2649 error("can't find '%s': %d", svpath, ret);
2652 close_file_or_dir(mntfd, dirstream2);
2653 close_file_or_dir(fd, dirstream1);
2659 void init_rand_seed(u64 seed)
2663 /* only use the last 48 bits */
2664 for (i = 0; i < 3; i++) {
2665 rand_seed[i] = (unsigned short)(seed ^ (unsigned short)(-1));
2668 rand_seed_initlized = 1;
2671 static void __init_seed(void)
2677 if(rand_seed_initlized)
2679 /* Use urandom as primary seed source. */
2680 fd = open("/dev/urandom", O_RDONLY);
2682 ret = read(fd, rand_seed, sizeof(rand_seed));
2684 if (ret < sizeof(rand_seed))
2688 /* Use time and pid as fallback seed */
2689 warning("failed to read /dev/urandom, use time and pid as random seed");
2690 gettimeofday(&tv, 0);
2691 rand_seed[0] = getpid() ^ (tv.tv_sec & 0xFFFF);
2692 rand_seed[1] = getppid() ^ (tv.tv_usec & 0xFFFF);
2693 rand_seed[2] = (tv.tv_sec ^ tv.tv_usec) >> 16;
2695 rand_seed_initlized = 1;
2702 * Don't use nrand48, its range is [0,2^31) The highest bit will alwasy
2703 * be 0. Use jrand48 to include the highest bit.
2705 return (u32)jrand48(rand_seed);
2708 unsigned int rand_range(unsigned int upper)
2712 * Use the full 48bits to mod, which would be more uniformly
2715 return (unsigned int)(jrand48(rand_seed) % upper);
2718 void btrfs_config_init(void)