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>
40 #include <sys/utsname.h>
41 #include <linux/version.h>
43 #include "kerncompat.h"
44 #include "radix-tree.h"
47 #include "transaction.h"
53 #include "fsfeatures.h"
56 #define BLKDISCARD _IO(0x12,119)
59 static int btrfs_scan_done = 0;
61 static int rand_seed_initlized = 0;
62 static unsigned short rand_seed[3];
64 struct btrfs_config bconf;
67 * Discard the given range in one go
69 static int discard_range(int fd, u64 start, u64 len)
71 u64 range[2] = { start, len };
73 if (ioctl(fd, BLKDISCARD, &range) < 0)
79 * Discard blocks in the given range in 1G chunks, the process is interruptible
81 static int discard_blocks(int fd, u64 start, u64 len)
85 u64 chunk_size = min_t(u64, len, SZ_1G);
88 ret = discard_range(fd, start, chunk_size);
98 int test_uuid_unique(char *fs_uuid)
101 blkid_dev_iterate iter = NULL;
102 blkid_dev dev = NULL;
103 blkid_cache cache = NULL;
105 if (blkid_get_cache(&cache, NULL) < 0) {
106 printf("ERROR: lblkid cache get failed\n");
109 blkid_probe_all(cache);
110 iter = blkid_dev_iterate_begin(cache);
111 blkid_dev_set_search(iter, "UUID", fs_uuid);
113 while (blkid_dev_next(iter, &dev) == 0) {
114 dev = blkid_verify(cache, dev);
121 blkid_dev_iterate_end(iter);
122 blkid_put_cache(cache);
128 * Insert a root item for temporary tree root
130 * Only used in make_btrfs_v2().
132 #define VERSION_TO_STRING3(a,b,c) #a "." #b "." #c, KERNEL_VERSION(a,b,c)
133 #define VERSION_TO_STRING2(a,b) #a "." #b, KERNEL_VERSION(a,b,0)
136 * Feature stability status and versions: compat <= safe <= default
138 static const struct btrfs_fs_feature {
141 const char *sysfs_name;
143 * Compatibility with kernel of given version. Filesystem can be
146 const char *compat_str;
149 * Considered safe for use, but is not on by default, even if the
150 * kernel supports the feature.
152 const char *safe_str;
155 * Considered safe for use and will be turned on by default if
156 * supported by the running kernel.
158 const char *default_str;
161 } mkfs_features[] = {
162 { "mixed-bg", BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS,
164 VERSION_TO_STRING3(2,6,37),
165 VERSION_TO_STRING3(2,6,37),
167 "mixed data and metadata block groups" },
168 { "extref", BTRFS_FEATURE_INCOMPAT_EXTENDED_IREF,
170 VERSION_TO_STRING2(3,7),
171 VERSION_TO_STRING2(3,12),
172 VERSION_TO_STRING2(3,12),
173 "increased hardlink limit per file to 65536" },
174 { "raid56", BTRFS_FEATURE_INCOMPAT_RAID56,
176 VERSION_TO_STRING2(3,9),
179 "raid56 extended format" },
180 { "skinny-metadata", BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA,
182 VERSION_TO_STRING2(3,10),
183 VERSION_TO_STRING2(3,18),
184 VERSION_TO_STRING2(3,18),
185 "reduced-size metadata extent refs" },
186 { "no-holes", BTRFS_FEATURE_INCOMPAT_NO_HOLES,
188 VERSION_TO_STRING2(3,14),
189 VERSION_TO_STRING2(4,0),
191 "no explicit hole extents for files" },
192 /* Keep this one last */
193 { "list-all", BTRFS_FEATURE_LIST_ALL, NULL }
196 static int parse_one_fs_feature(const char *name, u64 *flags)
201 for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
202 if (name[0] == '^' &&
203 !strcmp(mkfs_features[i].name, name + 1)) {
204 *flags &= ~ mkfs_features[i].flag;
206 } else if (!strcmp(mkfs_features[i].name, name)) {
207 *flags |= mkfs_features[i].flag;
215 void btrfs_parse_features_to_string(char *buf, u64 flags)
221 for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
222 if (flags & mkfs_features[i].flag) {
225 strcat(buf, mkfs_features[i].name);
230 void btrfs_process_fs_features(u64 flags)
234 for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
235 if (flags & mkfs_features[i].flag) {
236 printf("Turning ON incompat feature '%s': %s\n",
237 mkfs_features[i].name,
238 mkfs_features[i].desc);
243 void btrfs_list_all_fs_features(u64 mask_disallowed)
247 fprintf(stderr, "Filesystem features available:\n");
248 for (i = 0; i < ARRAY_SIZE(mkfs_features) - 1; i++) {
249 const struct btrfs_fs_feature *feat = &mkfs_features[i];
251 if (feat->flag & mask_disallowed)
253 fprintf(stderr, "%-20s- %s (0x%llx", feat->name, feat->desc,
255 if (feat->compat_ver)
256 fprintf(stderr, ", compat=%s", feat->compat_str);
258 fprintf(stderr, ", safe=%s", feat->safe_str);
259 if (feat->default_ver)
260 fprintf(stderr, ", default=%s", feat->default_str);
261 fprintf(stderr, ")\n");
266 * Return NULL if all features were parsed fine, otherwise return the name of
267 * the first unparsed.
269 char* btrfs_parse_fs_features(char *namelist, u64 *flags)
272 char *save_ptr = NULL; /* Satisfy static checkers */
274 for (this_char = strtok_r(namelist, ",", &save_ptr);
276 this_char = strtok_r(NULL, ",", &save_ptr)) {
277 if (parse_one_fs_feature(this_char, flags))
284 void print_kernel_version(FILE *stream, u32 version)
288 v[0] = version & 0xFF;
289 v[1] = (version >> 8) & 0xFF;
290 v[2] = version >> 16;
291 fprintf(stream, "%u.%u", v[2], v[1]);
293 fprintf(stream, ".%u", v[0]);
296 u32 get_running_kernel_version(void)
298 struct utsname utsbuf;
300 char *saveptr = NULL;
304 if (strcmp(utsbuf.sysname, "Linux") != 0) {
305 error("unsupported system: %s", utsbuf.sysname);
309 tmp = strchr(utsbuf.release, '-');
313 tmp = strtok_r(utsbuf.release, ".", &saveptr);
314 if (!string_is_numerical(tmp))
316 version = atoi(tmp) << 16;
317 tmp = strtok_r(NULL, ".", &saveptr);
318 if (!string_is_numerical(tmp))
320 version |= atoi(tmp) << 8;
321 tmp = strtok_r(NULL, ".", &saveptr);
323 if (!string_is_numerical(tmp))
325 version |= atoi(tmp);
331 u64 btrfs_device_size(int fd, struct stat *st)
334 if (S_ISREG(st->st_mode)) {
337 if (!S_ISBLK(st->st_mode)) {
340 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
346 static int zero_blocks(int fd, off_t start, size_t len)
348 char *buf = malloc(len);
355 written = pwrite(fd, buf, len, start);
362 #define ZERO_DEV_BYTES SZ_2M
364 /* don't write outside the device by clamping the region to the device size */
365 static int zero_dev_clamped(int fd, off_t start, ssize_t len, u64 dev_size)
367 off_t end = max(start, start + len);
370 /* and don't overwrite the disk labels on sparc */
371 start = max(start, 1024);
372 end = max(end, 1024);
375 start = min_t(u64, start, dev_size);
376 end = min_t(u64, end, dev_size);
378 return zero_blocks(fd, start, end - start);
381 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
382 struct btrfs_root *root, int fd, const char *path,
383 u64 device_total_bytes, u32 io_width, u32 io_align,
386 struct btrfs_super_block *disk_super;
387 struct btrfs_super_block *super = root->fs_info->super_copy;
388 struct btrfs_device *device;
389 struct btrfs_dev_item *dev_item;
395 device_total_bytes = (device_total_bytes / sectorsize) * sectorsize;
397 device = calloc(1, sizeof(*device));
402 buf = calloc(1, sectorsize);
408 disk_super = (struct btrfs_super_block *)buf;
409 dev_item = &disk_super->dev_item;
411 uuid_generate(device->uuid);
414 device->io_width = io_width;
415 device->io_align = io_align;
416 device->sector_size = sectorsize;
418 device->writeable = 1;
419 device->total_bytes = device_total_bytes;
420 device->bytes_used = 0;
421 device->total_ios = 0;
422 device->dev_root = root->fs_info->dev_root;
423 device->name = strdup(path);
429 INIT_LIST_HEAD(&device->dev_list);
430 ret = btrfs_add_device(trans, root, device);
434 fs_total_bytes = btrfs_super_total_bytes(super) + device_total_bytes;
435 btrfs_set_super_total_bytes(super, fs_total_bytes);
437 num_devs = btrfs_super_num_devices(super) + 1;
438 btrfs_set_super_num_devices(super, num_devs);
440 memcpy(disk_super, super, sizeof(*disk_super));
442 btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
443 btrfs_set_stack_device_id(dev_item, device->devid);
444 btrfs_set_stack_device_type(dev_item, device->type);
445 btrfs_set_stack_device_io_align(dev_item, device->io_align);
446 btrfs_set_stack_device_io_width(dev_item, device->io_width);
447 btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
448 btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
449 btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
450 memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
452 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
453 BUG_ON(ret != sectorsize);
456 list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
457 device->fs_devices = root->fs_info->fs_devices;
466 static int btrfs_wipe_existing_sb(int fd)
468 const char *off = NULL;
473 blkid_probe pr = NULL;
475 pr = blkid_new_probe();
479 if (blkid_probe_set_device(pr, fd, 0, 0)) {
484 ret = blkid_probe_lookup_value(pr, "SBMAGIC_OFFSET", &off, NULL);
486 ret = blkid_probe_lookup_value(pr, "SBMAGIC", NULL, &len);
488 if (ret || len == 0 || off == NULL) {
490 * If lookup fails, the probe did not find any values, eg. for
491 * a file image or a loop device. Soft error.
497 offset = strtoll(off, NULL, 10);
498 if (len > sizeof(buf))
502 ret = pwrite(fd, buf, len, offset);
504 error("cannot wipe existing superblock: %s", strerror(errno));
506 } else if (ret != len) {
507 error("cannot wipe existing superblock: wrote %d of %zd", ret, len);
513 blkid_free_probe(pr);
517 int btrfs_prepare_device(int fd, const char *file, u64 *block_count_ret,
518 u64 max_block_count, unsigned opflags)
524 ret = fstat(fd, &st);
526 error("unable to stat %s: %s", file, strerror(errno));
530 block_count = btrfs_device_size(fd, &st);
531 if (block_count == 0) {
532 error("unable to determine size of %s", file);
536 block_count = min(block_count, max_block_count);
538 if (opflags & PREP_DEVICE_DISCARD) {
540 * We intentionally ignore errors from the discard ioctl. It
541 * is not necessary for the mkfs functionality but just an
544 if (discard_range(fd, 0, 0) == 0) {
545 if (opflags & PREP_DEVICE_VERBOSE)
546 printf("Performing full device TRIM %s (%s) ...\n",
547 file, pretty_size(block_count));
548 discard_blocks(fd, 0, block_count);
552 ret = zero_dev_clamped(fd, 0, ZERO_DEV_BYTES, block_count);
553 for (i = 0 ; !ret && i < BTRFS_SUPER_MIRROR_MAX; i++)
554 ret = zero_dev_clamped(fd, btrfs_sb_offset(i),
555 BTRFS_SUPER_INFO_SIZE, block_count);
556 if (!ret && (opflags & PREP_DEVICE_ZERO_END))
557 ret = zero_dev_clamped(fd, block_count - ZERO_DEV_BYTES,
558 ZERO_DEV_BYTES, block_count);
561 error("failed to zero device '%s': %s", file, strerror(-ret));
565 ret = btrfs_wipe_existing_sb(fd);
567 error("cannot wipe superblocks on %s", file);
571 *block_count_ret = block_count;
575 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
576 struct btrfs_root *root, u64 objectid)
579 struct btrfs_inode_item inode_item;
580 time_t now = time(NULL);
582 memset(&inode_item, 0, sizeof(inode_item));
583 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
584 btrfs_set_stack_inode_size(&inode_item, 0);
585 btrfs_set_stack_inode_nlink(&inode_item, 1);
586 btrfs_set_stack_inode_nbytes(&inode_item, root->nodesize);
587 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
588 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
589 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
590 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
591 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
592 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
593 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
594 btrfs_set_stack_timespec_sec(&inode_item.otime, now);
595 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
597 if (root->fs_info->tree_root == root)
598 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
600 ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
604 ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
608 btrfs_set_root_dirid(&root->root_item, objectid);
615 * checks if a path is a block device node
616 * Returns negative errno on failure, otherwise
617 * returns 1 for blockdev, 0 for not-blockdev
619 int is_block_device(const char *path)
623 if (stat(path, &statbuf) < 0)
626 return !!S_ISBLK(statbuf.st_mode);
630 * check if given path is a mount point
631 * return 1 if yes. 0 if no. -1 for error
633 int is_mount_point(const char *path)
639 f = setmntent("/proc/self/mounts", "r");
643 while ((mnt = getmntent(f)) != NULL) {
644 if (strcmp(mnt->mnt_dir, path))
653 static int is_reg_file(const char *path)
657 if (stat(path, &statbuf) < 0)
659 return S_ISREG(statbuf.st_mode);
663 * This function checks if the given input parameter is
665 * return <0 : some error in the given input
666 * return BTRFS_ARG_UNKNOWN: unknown input
667 * return BTRFS_ARG_UUID: given input is uuid
668 * return BTRFS_ARG_MNTPOINT: given input is path
669 * return BTRFS_ARG_REG: given input is regular file
670 * return BTRFS_ARG_BLKDEV: given input is block device
672 int check_arg_type(const char *input)
680 if (realpath(input, path)) {
681 if (is_block_device(path) == 1)
682 return BTRFS_ARG_BLKDEV;
684 if (is_mount_point(path) == 1)
685 return BTRFS_ARG_MNTPOINT;
687 if (is_reg_file(path))
688 return BTRFS_ARG_REG;
690 return BTRFS_ARG_UNKNOWN;
693 if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
694 !uuid_parse(input, uuid))
695 return BTRFS_ARG_UUID;
697 return BTRFS_ARG_UNKNOWN;
701 * Find the mount point for a mounted device.
702 * On success, returns 0 with mountpoint in *mp.
703 * On failure, returns -errno (not mounted yields -EINVAL)
704 * Is noisy on failures, expects to be given a mounted device.
706 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
711 ret = is_block_device(dev);
714 error("not a block device: %s", dev);
717 error("cannot check %s: %s", dev, strerror(-ret));
722 fd = open(dev, O_RDONLY);
725 error("cannot open %s: %s", dev, strerror(errno));
729 ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
732 } else { /* mounted, all good */
742 * Given a pathname, return a filehandle to:
743 * the original pathname or,
744 * if the pathname is a mounted btrfs device, to its mountpoint.
746 * On error, return -1, errno should be set.
748 int open_path_or_dev_mnt(const char *path, DIR **dirstream, int verbose)
753 if (is_block_device(path)) {
754 ret = get_btrfs_mount(path, mp, sizeof(mp));
756 /* not a mounted btrfs dev */
757 error_on(verbose, "'%s' is not a mounted btrfs device",
762 ret = open_file_or_dir(mp, dirstream);
763 error_on(verbose && ret < 0, "can't access '%s': %s",
764 path, strerror(errno));
766 ret = btrfs_open_dir(path, dirstream, 1);
773 * Do the following checks before calling open_file_or_dir():
774 * 1: path is in a btrfs filesystem
775 * 2: path is a directory
777 int btrfs_open_dir(const char *path, DIR **dirstream, int verbose)
783 if (statfs(path, &stfs) != 0) {
784 error_on(verbose, "cannot access '%s': %s", path,
789 if (stfs.f_type != BTRFS_SUPER_MAGIC) {
790 error_on(verbose, "not a btrfs filesystem: %s", path);
794 if (stat(path, &st) != 0) {
795 error_on(verbose, "cannot access '%s': %s", path,
800 if (!S_ISDIR(st.st_mode)) {
801 error_on(verbose, "not a directory: %s", path);
805 ret = open_file_or_dir(path, dirstream);
807 error_on(verbose, "cannot access '%s': %s", path,
814 /* checks if a device is a loop device */
815 static int is_loop_device (const char* device) {
818 if(stat(device, &statbuf) < 0)
821 return (S_ISBLK(statbuf.st_mode) &&
822 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
826 * Takes a loop device path (e.g. /dev/loop0) and returns
827 * the associated file (e.g. /images/my_btrfs.img) using
830 static int resolve_loop_device_with_loopdev(const char* loop_dev, char* loop_file)
834 struct loop_info64 lo64;
836 fd = open(loop_dev, O_RDONLY | O_NONBLOCK);
839 ret = ioctl(fd, LOOP_GET_STATUS64, &lo64);
845 memcpy(loop_file, lo64.lo_file_name, sizeof(lo64.lo_file_name));
846 loop_file[sizeof(lo64.lo_file_name)] = 0;
854 /* Takes a loop device path (e.g. /dev/loop0) and returns
855 * the associated file (e.g. /images/my_btrfs.img) */
856 static int resolve_loop_device(const char* loop_dev, char* loop_file,
863 char real_loop_dev[PATH_MAX];
865 if (!realpath(loop_dev, real_loop_dev))
867 snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
868 if (!(f = fopen(p, "r"))) {
871 * It's possibly a partitioned loop device, which is
872 * resolvable with loopdev API.
874 return resolve_loop_device_with_loopdev(loop_dev, loop_file);
878 snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
879 ret = fscanf(f, fmt, loop_file);
888 * Checks whether a and b are identical or device
889 * files associated with the same block device
891 static int is_same_blk_file(const char* a, const char* b)
893 struct stat st_buf_a, st_buf_b;
894 char real_a[PATH_MAX];
895 char real_b[PATH_MAX];
897 if (!realpath(a, real_a))
898 strncpy_null(real_a, a);
900 if (!realpath(b, real_b))
901 strncpy_null(real_b, b);
903 /* Identical path? */
904 if (strcmp(real_a, real_b) == 0)
907 if (stat(a, &st_buf_a) < 0 || stat(b, &st_buf_b) < 0) {
913 /* Same blockdevice? */
914 if (S_ISBLK(st_buf_a.st_mode) && S_ISBLK(st_buf_b.st_mode) &&
915 st_buf_a.st_rdev == st_buf_b.st_rdev) {
920 if (st_buf_a.st_dev == st_buf_b.st_dev &&
921 st_buf_a.st_ino == st_buf_b.st_ino) {
928 /* checks if a and b are identical or device
929 * files associated with the same block device or
930 * if one file is a loop device that uses the other
933 static int is_same_loop_file(const char* a, const char* b)
935 char res_a[PATH_MAX];
936 char res_b[PATH_MAX];
937 const char* final_a = NULL;
938 const char* final_b = NULL;
941 /* Resolve a if it is a loop device */
942 if((ret = is_loop_device(a)) < 0) {
947 ret = resolve_loop_device(a, res_a, sizeof(res_a));
958 /* Resolve b if it is a loop device */
959 if ((ret = is_loop_device(b)) < 0) {
964 ret = resolve_loop_device(b, res_b, sizeof(res_b));
975 return is_same_blk_file(final_a, final_b);
978 /* Checks if a file exists and is a block or regular file*/
979 static int is_existing_blk_or_reg_file(const char* filename)
983 if(stat(filename, &st_buf) < 0) {
990 return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
993 /* Checks if a file is used (directly or indirectly via a loop device)
994 * by a device in fs_devices
996 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
1000 struct list_head *head;
1001 struct list_head *cur;
1002 struct btrfs_device *device;
1004 head = &fs_devices->devices;
1005 list_for_each(cur, head) {
1006 device = list_entry(cur, struct btrfs_device, dev_list);
1008 if((ret = is_same_loop_file(device->name, file)))
1016 * Resolve a pathname to a device mapper node to /dev/mapper/<name>
1017 * Returns NULL on invalid input or malloc failure; Other failures
1018 * will be handled by the caller using the input pathame.
1020 char *canonicalize_dm_name(const char *ptname)
1024 char path[PATH_MAX], name[PATH_MAX], *res = NULL;
1026 if (!ptname || !*ptname)
1029 snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
1030 if (!(f = fopen(path, "r")))
1033 /* read <name>\n from sysfs */
1034 if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
1035 name[sz - 1] = '\0';
1036 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
1038 if (access(path, F_OK) == 0)
1046 * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
1047 * to a device mapper pathname.
1048 * Returns NULL on invalid input or malloc failure; Other failures
1049 * will be handled by the caller using the input pathame.
1051 char *canonicalize_path(const char *path)
1053 char *canonical, *p;
1055 if (!path || !*path)
1058 canonical = realpath(path, NULL);
1060 return strdup(path);
1061 p = strrchr(canonical, '/');
1062 if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
1063 char *dm = canonicalize_dm_name(p + 1);
1074 * returns 1 if the device was mounted, < 0 on error or 0 if everything
1075 * is safe to continue.
1077 int check_mounted(const char* file)
1082 fd = open(file, O_RDONLY);
1084 error("mount check: cannot open %s: %s", file,
1089 ret = check_mounted_where(fd, file, NULL, 0, NULL);
1095 int check_mounted_where(int fd, const char *file, char *where, int size,
1096 struct btrfs_fs_devices **fs_dev_ret)
1101 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1105 /* scan the initial device */
1106 ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
1107 &total_devs, BTRFS_SUPER_INFO_OFFSET, SBREAD_DEFAULT);
1108 is_btrfs = (ret >= 0);
1110 /* scan other devices */
1111 if (is_btrfs && total_devs > 1) {
1112 ret = btrfs_scan_devices();
1117 /* iterate over the list of currently mounted filesystems */
1118 if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
1121 while ((mnt = getmntent (f)) != NULL) {
1123 if(strcmp(mnt->mnt_type, "btrfs") != 0)
1126 ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
1128 /* ignore entries in the mount table that are not
1129 associated with a file*/
1130 if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
1131 goto out_mntloop_err;
1135 ret = is_same_loop_file(file, mnt->mnt_fsname);
1139 goto out_mntloop_err;
1144 /* Did we find an entry in mnt table? */
1145 if (mnt && size && where) {
1146 strncpy(where, mnt->mnt_dir, size);
1150 *fs_dev_ret = fs_devices_mnt;
1152 ret = (mnt != NULL);
1160 struct pending_dir {
1161 struct list_head list;
1162 char name[PATH_MAX];
1165 int btrfs_register_one_device(const char *fname)
1167 struct btrfs_ioctl_vol_args args;
1171 fd = open("/dev/btrfs-control", O_RDWR);
1174 "failed to open /dev/btrfs-control, skipping device registration: %s",
1178 memset(&args, 0, sizeof(args));
1179 strncpy_null(args.name, fname);
1180 ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
1182 error("device scan failed on '%s': %s", fname,
1191 * Register all devices in the fs_uuid list created in the user
1192 * space. Ensure btrfs_scan_devices() is called before this func.
1194 int btrfs_register_all_devices(void)
1198 struct btrfs_fs_devices *fs_devices;
1199 struct btrfs_device *device;
1200 struct list_head *all_uuids;
1202 all_uuids = btrfs_scanned_uuids();
1204 list_for_each_entry(fs_devices, all_uuids, list) {
1205 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1207 err = btrfs_register_one_device(device->name);
1217 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1220 struct btrfs_super_block *disk_super;
1224 buf = malloc(BTRFS_SUPER_INFO_SIZE);
1229 ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1230 if (ret != BTRFS_SUPER_INFO_SIZE)
1234 disk_super = (struct btrfs_super_block *)buf;
1236 * Accept devices from the same filesystem, allow partially created
1239 if (btrfs_super_magic(disk_super) != BTRFS_MAGIC &&
1240 btrfs_super_magic(disk_super) != BTRFS_MAGIC_PARTIAL)
1243 if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1253 * Note: this function uses a static per-thread buffer. Do not call this
1254 * function more than 10 times within one argument list!
1256 const char *pretty_size_mode(u64 size, unsigned mode)
1258 static __thread int ps_index = 0;
1259 static __thread char ps_array[10][32];
1262 ret = ps_array[ps_index];
1265 (void)pretty_size_snprintf(size, ret, 32, mode);
1270 static const char* unit_suffix_binary[] =
1271 { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1272 static const char* unit_suffix_decimal[] =
1273 { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
1275 int pretty_size_snprintf(u64 size, char *str, size_t str_size, unsigned unit_mode)
1281 const char** suffix = NULL;
1288 negative = !!(unit_mode & UNITS_NEGATIVE);
1289 unit_mode &= ~UNITS_NEGATIVE;
1291 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_RAW) {
1293 snprintf(str, str_size, "%lld", size);
1295 snprintf(str, str_size, "%llu", size);
1299 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_BINARY) {
1302 suffix = unit_suffix_binary;
1303 } else if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_DECIMAL) {
1306 suffix = unit_suffix_decimal;
1311 fprintf(stderr, "INTERNAL ERROR: unknown unit base, mode %d\n",
1319 switch (unit_mode & UNITS_MODE_MASK) {
1320 case UNITS_TBYTES: base *= mult; num_divs++;
1321 case UNITS_GBYTES: base *= mult; num_divs++;
1322 case UNITS_MBYTES: base *= mult; num_divs++;
1323 case UNITS_KBYTES: num_divs++;
1331 s64 ssize = (s64)size;
1332 s64 last_ssize = ssize;
1334 while ((ssize < 0 ? -ssize : ssize) >= mult) {
1339 last_size = (u64)last_ssize;
1341 while (size >= mult) {
1348 * If the value is smaller than base, we didn't do any
1349 * division, in that case, base should be 1, not original
1350 * base, or the unit will be wrong
1356 if (num_divs >= ARRAY_SIZE(unit_suffix_binary)) {
1358 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
1365 fraction = (float)(s64)last_size / base;
1367 fraction = (float)last_size / base;
1370 return snprintf(str, str_size, "%.2f%s", fraction, suffix[num_divs]);
1374 * __strncpy_null - strncpy with null termination
1375 * @dest: the target array
1376 * @src: the source string
1377 * @n: maximum bytes to copy (size of *dest)
1379 * Like strncpy, but ensures destination is null-terminated.
1381 * Copies the string pointed to by src, including the terminating null
1382 * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1383 * of n bytes. Then ensure that dest is null-terminated.
1385 char *__strncpy_null(char *dest, const char *src, size_t n)
1387 strncpy(dest, src, n);
1394 * Checks to make sure that the label matches our requirements.
1396 0 if everything is safe and usable
1397 -1 if the label is too long
1399 static int check_label(const char *input)
1401 int len = strlen(input);
1403 if (len > BTRFS_LABEL_SIZE - 1) {
1404 error("label %s is too long (max %d)", input,
1405 BTRFS_LABEL_SIZE - 1);
1412 static int set_label_unmounted(const char *dev, const char *label)
1414 struct btrfs_trans_handle *trans;
1415 struct btrfs_root *root;
1418 ret = check_mounted(dev);
1420 error("checking mount status of %s failed: %d", dev, ret);
1424 error("device %s is mounted, use mount point", dev);
1428 /* Open the super_block at the default location
1429 * and as read-write.
1431 root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1432 if (!root) /* errors are printed by open_ctree() */
1435 trans = btrfs_start_transaction(root, 1);
1436 __strncpy_null(root->fs_info->super_copy->label, label, BTRFS_LABEL_SIZE - 1);
1438 btrfs_commit_transaction(trans, root);
1440 /* Now we close it since we are done. */
1445 static int set_label_mounted(const char *mount_path, const char *labelp)
1448 char label[BTRFS_LABEL_SIZE];
1450 fd = open(mount_path, O_RDONLY | O_NOATIME);
1452 error("unable to access %s: %s", mount_path, strerror(errno));
1456 memset(label, 0, sizeof(label));
1457 __strncpy_null(label, labelp, BTRFS_LABEL_SIZE - 1);
1458 if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1459 error("unable to set label of %s: %s", mount_path,
1469 int get_label_unmounted(const char *dev, char *label)
1471 struct btrfs_root *root;
1474 ret = check_mounted(dev);
1476 error("checking mount status of %s failed: %d", dev, ret);
1480 /* Open the super_block at the default location
1483 root = open_ctree(dev, 0, 0);
1487 __strncpy_null(label, root->fs_info->super_copy->label,
1488 BTRFS_LABEL_SIZE - 1);
1490 /* Now we close it since we are done. */
1496 * If a partition is mounted, try to get the filesystem label via its
1497 * mounted path rather than device. Return the corresponding error
1498 * the user specified the device path.
1500 int get_label_mounted(const char *mount_path, char *labelp)
1502 char label[BTRFS_LABEL_SIZE];
1506 fd = open(mount_path, O_RDONLY | O_NOATIME);
1508 error("unable to access %s: %s", mount_path, strerror(errno));
1512 memset(label, '\0', sizeof(label));
1513 ret = ioctl(fd, BTRFS_IOC_GET_FSLABEL, label);
1515 if (errno != ENOTTY)
1516 error("unable to get label of %s: %s", mount_path,
1523 __strncpy_null(labelp, label, BTRFS_LABEL_SIZE - 1);
1528 int get_label(const char *btrfs_dev, char *label)
1532 ret = is_existing_blk_or_reg_file(btrfs_dev);
1534 ret = get_label_mounted(btrfs_dev, label);
1536 ret = get_label_unmounted(btrfs_dev, label);
1541 int set_label(const char *btrfs_dev, const char *label)
1545 if (check_label(label))
1548 ret = is_existing_blk_or_reg_file(btrfs_dev);
1550 ret = set_label_mounted(btrfs_dev, label);
1552 ret = set_label_unmounted(btrfs_dev, label);
1558 * A not-so-good version fls64. No fascinating optimization since
1559 * no one except parse_size use it
1561 static int fls64(u64 x)
1565 for (i = 0; i <64; i++)
1566 if (x << i & (1ULL << 63))
1571 u64 parse_size(char *s)
1579 error("size value is empty");
1583 error("size value '%s' is less equal than 0", s);
1586 ret = strtoull(s, &endptr, 10);
1588 error("size value '%s' is invalid", s);
1591 if (endptr[0] && endptr[1]) {
1592 error("illegal suffix contains character '%c' in wrong position",
1597 * strtoll returns LLONG_MAX when overflow, if this happens,
1598 * need to call strtoull to get the real size
1600 if (errno == ERANGE && ret == ULLONG_MAX) {
1601 error("size value '%s' is too large for u64", s);
1605 c = tolower(endptr[0]);
1628 error("unknown size descriptor '%c'", c);
1632 /* Check whether ret * mult overflow */
1633 if (fls64(ret) + fls64(mult) - 1 > 64) {
1634 error("size value '%s' is too large for u64", s);
1641 u64 parse_qgroupid(const char *p)
1643 char *s = strchr(p, '/');
1644 const char *ptr_src_end = p + strlen(p);
1645 char *ptr_parse_end = NULL;
1654 /* Numeric format like '0/257' is the primary case */
1656 id = strtoull(p, &ptr_parse_end, 10);
1657 if (ptr_parse_end != ptr_src_end)
1661 level = strtoull(p, &ptr_parse_end, 10);
1662 if (ptr_parse_end != s)
1665 id = strtoull(s + 1, &ptr_parse_end, 10);
1666 if (ptr_parse_end != ptr_src_end)
1669 return (level << BTRFS_QGROUP_LEVEL_SHIFT) | id;
1672 /* Path format like subv at 'my_subvol' is the fallback case */
1673 ret = test_issubvolume(p);
1674 if (ret < 0 || !ret)
1676 fd = open(p, O_RDONLY);
1679 ret = lookup_path_rootid(fd, &id);
1681 error("failed to lookup root id: %s", strerror(-ret));
1688 error("invalid qgroupid or subvolume path: %s", p);
1692 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
1698 ret = stat(fname, &st);
1702 if (S_ISDIR(st.st_mode)) {
1703 *dirstream = opendir(fname);
1706 fd = dirfd(*dirstream);
1707 } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
1708 fd = open(fname, open_flags);
1711 * we set this on purpose, in case the caller output
1712 * strerror(errno) as success
1720 closedir(*dirstream);
1727 int open_file_or_dir(const char *fname, DIR **dirstream)
1729 return open_file_or_dir3(fname, dirstream, O_RDWR);
1732 void close_file_or_dir(int fd, DIR *dirstream)
1735 closedir(dirstream);
1740 int get_device_info(int fd, u64 devid,
1741 struct btrfs_ioctl_dev_info_args *di_args)
1745 di_args->devid = devid;
1746 memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1748 ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1749 return ret < 0 ? -errno : 0;
1752 static u64 find_max_device_id(struct btrfs_ioctl_search_args *search_args,
1755 struct btrfs_dev_item *dev_item;
1756 char *buf = search_args->buf;
1758 buf += (nr_items - 1) * (sizeof(struct btrfs_ioctl_search_header)
1759 + sizeof(struct btrfs_dev_item));
1760 buf += sizeof(struct btrfs_ioctl_search_header);
1762 dev_item = (struct btrfs_dev_item *)buf;
1764 return btrfs_stack_device_id(dev_item);
1767 static int search_chunk_tree_for_fs_info(int fd,
1768 struct btrfs_ioctl_fs_info_args *fi_args)
1772 u64 start_devid = 1;
1773 struct btrfs_ioctl_search_args search_args;
1774 struct btrfs_ioctl_search_key *search_key = &search_args.key;
1776 fi_args->num_devices = 0;
1778 max_items = BTRFS_SEARCH_ARGS_BUFSIZE
1779 / (sizeof(struct btrfs_ioctl_search_header)
1780 + sizeof(struct btrfs_dev_item));
1782 search_key->tree_id = BTRFS_CHUNK_TREE_OBJECTID;
1783 search_key->min_objectid = BTRFS_DEV_ITEMS_OBJECTID;
1784 search_key->max_objectid = BTRFS_DEV_ITEMS_OBJECTID;
1785 search_key->min_type = BTRFS_DEV_ITEM_KEY;
1786 search_key->max_type = BTRFS_DEV_ITEM_KEY;
1787 search_key->min_transid = 0;
1788 search_key->max_transid = (u64)-1;
1789 search_key->nr_items = max_items;
1790 search_key->max_offset = (u64)-1;
1793 search_key->min_offset = start_devid;
1795 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &search_args);
1799 fi_args->num_devices += (u64)search_key->nr_items;
1801 if (search_key->nr_items == max_items) {
1802 start_devid = find_max_device_id(&search_args,
1803 search_key->nr_items) + 1;
1807 /* get the lastest max_id to stay consistent with the num_devices */
1808 if (search_key->nr_items == 0)
1810 * last tree_search returns an empty buf, use the devid of
1811 * the last dev_item of the previous tree_search
1813 fi_args->max_id = start_devid - 1;
1815 fi_args->max_id = find_max_device_id(&search_args,
1816 search_key->nr_items);
1822 * For a given path, fill in the ioctl fs_ and info_ args.
1823 * If the path is a btrfs mountpoint, fill info for all devices.
1824 * If the path is a btrfs device, fill in only that device.
1826 * The path provided must be either on a mounted btrfs fs,
1827 * or be a mounted btrfs device.
1829 * Returns 0 on success, or a negative errno.
1831 int get_fs_info(const char *path, struct btrfs_ioctl_fs_info_args *fi_args,
1832 struct btrfs_ioctl_dev_info_args **di_ret)
1839 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1840 struct btrfs_ioctl_dev_info_args *di_args;
1841 struct btrfs_ioctl_dev_info_args tmp;
1843 DIR *dirstream = NULL;
1845 memset(fi_args, 0, sizeof(*fi_args));
1847 if (is_block_device(path) == 1) {
1848 struct btrfs_super_block *disk_super;
1849 char buf[BTRFS_SUPER_INFO_SIZE];
1851 /* Ensure it's mounted, then set path to the mountpoint */
1852 fd = open(path, O_RDONLY);
1855 error("cannot open %s: %s", path, strerror(errno));
1858 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1867 /* Only fill in this one device */
1868 fi_args->num_devices = 1;
1870 disk_super = (struct btrfs_super_block *)buf;
1871 ret = btrfs_read_dev_super(fd, disk_super,
1872 BTRFS_SUPER_INFO_OFFSET, 0);
1877 last_devid = btrfs_stack_device_id(&disk_super->dev_item);
1878 fi_args->max_id = last_devid;
1880 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1884 /* at this point path must not be for a block device */
1885 fd = open_file_or_dir(path, &dirstream);
1891 /* fill in fi_args if not just a single device */
1892 if (fi_args->num_devices != 1) {
1893 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
1900 * The fs_args->num_devices does not include seed devices
1902 ret = search_chunk_tree_for_fs_info(fd, fi_args);
1907 * search_chunk_tree_for_fs_info() will lacks the devid 0
1908 * so manual probe for it here.
1910 ret = get_device_info(fd, 0, &tmp);
1912 fi_args->num_devices++;
1915 if (last_devid == 0)
1920 if (!fi_args->num_devices)
1923 di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
1930 memcpy(di_args, &tmp, sizeof(tmp));
1931 for (; last_devid <= fi_args->max_id; last_devid++) {
1932 ret = get_device_info(fd, last_devid, &di_args[ndevs]);
1941 * only when the only dev we wanted to find is not there then
1942 * let any error be returned
1944 if (fi_args->num_devices != 1) {
1950 close_file_or_dir(fd, dirstream);
1954 #define isoctal(c) (((c) & ~7) == '0')
1956 static inline void translate(char *f, char *t)
1958 while (*f != '\0') {
1960 isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
1961 *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
1971 * Checks if the swap device.
1972 * Returns 1 if swap device, < 0 on error or 0 if not swap device.
1974 static int is_swap_device(const char *file)
1985 if (stat(file, &st_buf) < 0)
1987 if (S_ISBLK(st_buf.st_mode))
1988 dev = st_buf.st_rdev;
1989 else if (S_ISREG(st_buf.st_mode)) {
1990 dev = st_buf.st_dev;
1991 ino = st_buf.st_ino;
1995 if ((f = fopen("/proc/swaps", "r")) == NULL)
1998 /* skip the first line */
1999 if (fgets(tmp, sizeof(tmp), f) == NULL)
2002 while (fgets(tmp, sizeof(tmp), f) != NULL) {
2003 if ((cp = strchr(tmp, ' ')) != NULL)
2005 if ((cp = strchr(tmp, '\t')) != NULL)
2007 translate(tmp, buf);
2008 if (stat(buf, &st_buf) != 0)
2010 if (S_ISBLK(st_buf.st_mode)) {
2011 if (dev == st_buf.st_rdev) {
2015 } else if (S_ISREG(st_buf.st_mode)) {
2016 if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
2030 * Check for existing filesystem or partition table on device.
2032 * 1 for existing fs or partition
2033 * 0 for nothing found
2034 * -1 for internal error
2036 static int check_overwrite(const char *device)
2039 blkid_probe pr = NULL;
2043 if (!device || !*device)
2046 ret = -1; /* will reset on success of all setup calls */
2048 pr = blkid_new_probe_from_filename(device);
2052 size = blkid_probe_get_size(pr);
2056 /* nothing to overwrite on a 0-length device */
2062 ret = blkid_probe_enable_partitions(pr, 1);
2066 ret = blkid_do_fullprobe(pr);
2071 * Blkid returns 1 for nothing found and 0 when it finds a signature,
2072 * but we want the exact opposite, so reverse the return value here.
2074 * In addition print some useful diagnostics about what actually is
2082 if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
2084 "%s appears to contain an existing "
2085 "filesystem (%s).\n", device, type);
2086 } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
2088 "%s appears to contain a partition "
2089 "table (%s).\n", device, type);
2092 "%s appears to contain something weird "
2093 "according to blkid\n", device);
2099 blkid_free_probe(pr);
2102 "probe of %s failed, cannot detect "
2103 "existing filesystem.\n", device);
2107 static int group_profile_devs_min(u64 flag)
2109 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2110 case 0: /* single */
2111 case BTRFS_BLOCK_GROUP_DUP:
2113 case BTRFS_BLOCK_GROUP_RAID0:
2114 case BTRFS_BLOCK_GROUP_RAID1:
2115 case BTRFS_BLOCK_GROUP_RAID5:
2117 case BTRFS_BLOCK_GROUP_RAID6:
2119 case BTRFS_BLOCK_GROUP_RAID10:
2126 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
2127 u64 dev_cnt, int mixed, int ssd)
2130 u64 profile = metadata_profile | data_profile;
2135 allowed |= BTRFS_BLOCK_GROUP_RAID10;
2137 allowed |= BTRFS_BLOCK_GROUP_RAID6;
2139 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2140 BTRFS_BLOCK_GROUP_RAID5;
2142 allowed |= BTRFS_BLOCK_GROUP_DUP;
2145 if (dev_cnt > 1 && profile & BTRFS_BLOCK_GROUP_DUP) {
2146 warning("DUP is not recommended on filesystem with multiple devices");
2148 if (metadata_profile & ~allowed) {
2150 "ERROR: unable to create FS with metadata profile %s "
2151 "(have %llu devices but %d devices are required)\n",
2152 btrfs_group_profile_str(metadata_profile), dev_cnt,
2153 group_profile_devs_min(metadata_profile));
2156 if (data_profile & ~allowed) {
2158 "ERROR: unable to create FS with data profile %s "
2159 "(have %llu devices but %d devices are required)\n",
2160 btrfs_group_profile_str(data_profile), dev_cnt,
2161 group_profile_devs_min(data_profile));
2165 if (dev_cnt == 3 && profile & BTRFS_BLOCK_GROUP_RAID6) {
2166 warning("RAID6 is not recommended on filesystem with 3 devices only");
2168 if (dev_cnt == 2 && profile & BTRFS_BLOCK_GROUP_RAID5) {
2169 warning("RAID5 is not recommended on filesystem with 2 devices only");
2171 warning_on(!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP) && ssd,
2172 "DUP may not actually lead to 2 copies on the device, see manual page");
2177 int group_profile_max_safe_loss(u64 flags)
2179 switch (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2180 case 0: /* single */
2181 case BTRFS_BLOCK_GROUP_DUP:
2182 case BTRFS_BLOCK_GROUP_RAID0:
2184 case BTRFS_BLOCK_GROUP_RAID1:
2185 case BTRFS_BLOCK_GROUP_RAID5:
2186 case BTRFS_BLOCK_GROUP_RAID10:
2188 case BTRFS_BLOCK_GROUP_RAID6:
2196 * Check if a device is suitable for btrfs
2198 * 1: something is wrong, an error is printed
2201 int test_dev_for_mkfs(const char *file, int force_overwrite)
2206 ret = is_swap_device(file);
2208 error("checking status of %s: %s", file, strerror(-ret));
2212 error("%s is a swap device", file);
2215 if (!force_overwrite) {
2216 if (check_overwrite(file)) {
2217 error("use the -f option to force overwrite of %s",
2222 ret = check_mounted(file);
2224 error("cannot check mount status of %s: %s", file,
2229 error("%s is mounted", file);
2232 /* check if the device is busy */
2233 fd = open(file, O_RDWR|O_EXCL);
2235 error("unable to open %s: %s", file, strerror(errno));
2238 if (fstat(fd, &st)) {
2239 error("unable to stat %s: %s", file, strerror(errno));
2243 if (!S_ISBLK(st.st_mode)) {
2244 error("%s is not a block device", file);
2252 int btrfs_scan_devices(void)
2257 struct btrfs_fs_devices *tmp_devices;
2258 blkid_dev_iterate iter = NULL;
2259 blkid_dev dev = NULL;
2260 blkid_cache cache = NULL;
2261 char path[PATH_MAX];
2263 if (btrfs_scan_done)
2266 if (blkid_get_cache(&cache, NULL) < 0) {
2267 error("blkid cache get failed");
2270 blkid_probe_all(cache);
2271 iter = blkid_dev_iterate_begin(cache);
2272 blkid_dev_set_search(iter, "TYPE", "btrfs");
2273 while (blkid_dev_next(iter, &dev) == 0) {
2274 dev = blkid_verify(cache, dev);
2277 /* if we are here its definitely a btrfs disk*/
2278 strncpy_null(path, blkid_dev_devname(dev));
2280 fd = open(path, O_RDONLY);
2282 error("cannot open %s: %s", path, strerror(errno));
2285 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
2286 &num_devices, BTRFS_SUPER_INFO_OFFSET,
2289 error("cannot scan %s: %s", path, strerror(-ret));
2296 blkid_dev_iterate_end(iter);
2297 blkid_put_cache(cache);
2299 btrfs_scan_done = 1;
2304 int is_vol_small(const char *file)
2311 fd = open(file, O_RDONLY);
2314 if (fstat(fd, &st) < 0) {
2319 size = btrfs_device_size(fd, &st);
2324 if (size < BTRFS_MKFS_SMALL_VOLUME_SIZE) {
2334 * This reads a line from the stdin and only returns non-zero if the
2335 * first whitespace delimited token is a case insensitive match with yes
2338 int ask_user(const char *question)
2340 char buf[30] = {0,};
2341 char *saveptr = NULL;
2344 printf("%s [y/N]: ", question);
2346 return fgets(buf, sizeof(buf) - 1, stdin) &&
2347 (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
2348 (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
2352 * return 0 if a btrfs mount point is found
2353 * return 1 if a mount point is found but not btrfs
2354 * return <0 if something goes wrong
2356 int find_mount_root(const char *path, char **mount_root)
2364 int longest_matchlen = 0;
2365 char *longest_match = NULL;
2367 fd = open(path, O_RDONLY | O_NOATIME);
2372 mnttab = setmntent("/proc/self/mounts", "r");
2376 while ((ent = getmntent(mnttab))) {
2377 len = strlen(ent->mnt_dir);
2378 if (strncmp(ent->mnt_dir, path, len) == 0) {
2379 /* match found and use the latest match */
2380 if (longest_matchlen <= len) {
2381 free(longest_match);
2382 longest_matchlen = len;
2383 longest_match = strdup(ent->mnt_dir);
2384 not_btrfs = strcmp(ent->mnt_type, "btrfs");
2393 free(longest_match);
2398 *mount_root = realpath(longest_match, NULL);
2402 free(longest_match);
2406 int test_minimum_size(const char *file, u32 nodesize)
2409 struct stat statbuf;
2411 fd = open(file, O_RDONLY);
2414 if (stat(file, &statbuf) < 0) {
2418 if (btrfs_device_size(fd, &statbuf) < btrfs_min_dev_size(nodesize)) {
2428 * Test if path is a directory
2430 * 0 - path exists but it is not a directory
2431 * 1 - path exists and it is a directory
2434 int test_isdir(const char *path)
2439 ret = stat(path, &st);
2443 return !!S_ISDIR(st.st_mode);
2446 void units_set_mode(unsigned *units, unsigned mode)
2448 unsigned base = *units & UNITS_MODE_MASK;
2450 *units = base | mode;
2453 void units_set_base(unsigned *units, unsigned base)
2455 unsigned mode = *units & ~UNITS_MODE_MASK;
2457 *units = base | mode;
2460 int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
2464 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2465 if (!path->nodes[level])
2467 if (path->slots[level] + 1 >=
2468 btrfs_header_nritems(path->nodes[level]))
2471 btrfs_item_key_to_cpu(path->nodes[level], key,
2472 path->slots[level] + 1);
2474 btrfs_node_key_to_cpu(path->nodes[level], key,
2475 path->slots[level] + 1);
2481 const char* btrfs_group_type_str(u64 flag)
2483 u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
2484 BTRFS_SPACE_INFO_GLOBAL_RSV;
2486 switch (flag & mask) {
2487 case BTRFS_BLOCK_GROUP_DATA:
2489 case BTRFS_BLOCK_GROUP_SYSTEM:
2491 case BTRFS_BLOCK_GROUP_METADATA:
2493 case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
2494 return "Data+Metadata";
2495 case BTRFS_SPACE_INFO_GLOBAL_RSV:
2496 return "GlobalReserve";
2502 const char* btrfs_group_profile_str(u64 flag)
2504 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2507 case BTRFS_BLOCK_GROUP_RAID0:
2509 case BTRFS_BLOCK_GROUP_RAID1:
2511 case BTRFS_BLOCK_GROUP_RAID5:
2513 case BTRFS_BLOCK_GROUP_RAID6:
2515 case BTRFS_BLOCK_GROUP_DUP:
2517 case BTRFS_BLOCK_GROUP_RAID10:
2524 u64 disk_size(const char *path)
2528 if (statfs(path, &sfs) < 0)
2531 return sfs.f_bsize * sfs.f_blocks;
2534 u64 get_partition_size(const char *dev)
2537 int fd = open(dev, O_RDONLY);
2541 if (ioctl(fd, BLKGETSIZE64, &result) < 0) {
2551 * Check if the BTRFS_IOC_TREE_SEARCH_V2 ioctl is supported on a given
2552 * filesystem, opened at fd
2554 int btrfs_tree_search2_ioctl_supported(int fd)
2556 struct btrfs_ioctl_search_args_v2 *args2;
2557 struct btrfs_ioctl_search_key *sk;
2558 int args2_size = 1024;
2559 char args2_buf[args2_size];
2562 args2 = (struct btrfs_ioctl_search_args_v2 *)args2_buf;
2566 * Search for the extent tree item in the root tree.
2568 sk->tree_id = BTRFS_ROOT_TREE_OBJECTID;
2569 sk->min_objectid = BTRFS_EXTENT_TREE_OBJECTID;
2570 sk->max_objectid = BTRFS_EXTENT_TREE_OBJECTID;
2571 sk->min_type = BTRFS_ROOT_ITEM_KEY;
2572 sk->max_type = BTRFS_ROOT_ITEM_KEY;
2574 sk->max_offset = (u64)-1;
2575 sk->min_transid = 0;
2576 sk->max_transid = (u64)-1;
2578 args2->buf_size = args2_size - sizeof(struct btrfs_ioctl_search_args_v2);
2579 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH_V2, args2);
2580 if (ret == -EOPNOTSUPP)
2587 int btrfs_check_nodesize(u32 nodesize, u32 sectorsize, u64 features)
2589 if (nodesize < sectorsize) {
2590 error("illegal nodesize %u (smaller than %u)",
2591 nodesize, sectorsize);
2593 } else if (nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2594 error("illegal nodesize %u (larger than %u)",
2595 nodesize, BTRFS_MAX_METADATA_BLOCKSIZE);
2597 } else if (nodesize & (sectorsize - 1)) {
2598 error("illegal nodesize %u (not aligned to %u)",
2599 nodesize, sectorsize);
2601 } else if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS &&
2602 nodesize != sectorsize) {
2603 error("illegal nodesize %u (not equal to %u for mixed block group)",
2604 nodesize, sectorsize);
2611 * Copy a path argument from SRC to DEST and check the SRC length if it's at
2612 * most PATH_MAX and fits into DEST. DESTLEN is supposed to be exact size of
2614 * The destination buffer is zero terminated.
2615 * Return < 0 for error, 0 otherwise.
2617 int arg_copy_path(char *dest, const char *src, int destlen)
2619 size_t len = strlen(src);
2621 if (len >= PATH_MAX || len >= destlen)
2622 return -ENAMETOOLONG;
2624 __strncpy_null(dest, src, destlen);
2629 unsigned int get_unit_mode_from_arg(int *argc, char *argv[], int df_mode)
2631 unsigned int unit_mode = UNITS_DEFAULT;
2635 for (arg_i = 0; arg_i < *argc; arg_i++) {
2636 if (!strcmp(argv[arg_i], "--"))
2639 if (!strcmp(argv[arg_i], "--raw")) {
2640 unit_mode = UNITS_RAW;
2644 if (!strcmp(argv[arg_i], "--human-readable")) {
2645 unit_mode = UNITS_HUMAN_BINARY;
2650 if (!strcmp(argv[arg_i], "--iec")) {
2651 units_set_mode(&unit_mode, UNITS_BINARY);
2655 if (!strcmp(argv[arg_i], "--si")) {
2656 units_set_mode(&unit_mode, UNITS_DECIMAL);
2661 if (!strcmp(argv[arg_i], "--kbytes")) {
2662 units_set_base(&unit_mode, UNITS_KBYTES);
2666 if (!strcmp(argv[arg_i], "--mbytes")) {
2667 units_set_base(&unit_mode, UNITS_MBYTES);
2671 if (!strcmp(argv[arg_i], "--gbytes")) {
2672 units_set_base(&unit_mode, UNITS_GBYTES);
2676 if (!strcmp(argv[arg_i], "--tbytes")) {
2677 units_set_base(&unit_mode, UNITS_TBYTES);
2685 if (!strcmp(argv[arg_i], "-b")) {
2686 unit_mode = UNITS_RAW;
2690 if (!strcmp(argv[arg_i], "-h")) {
2691 unit_mode = UNITS_HUMAN_BINARY;
2695 if (!strcmp(argv[arg_i], "-H")) {
2696 unit_mode = UNITS_HUMAN_DECIMAL;
2700 if (!strcmp(argv[arg_i], "-k")) {
2701 units_set_base(&unit_mode, UNITS_KBYTES);
2705 if (!strcmp(argv[arg_i], "-m")) {
2706 units_set_base(&unit_mode, UNITS_MBYTES);
2710 if (!strcmp(argv[arg_i], "-g")) {
2711 units_set_base(&unit_mode, UNITS_GBYTES);
2715 if (!strcmp(argv[arg_i], "-t")) {
2716 units_set_base(&unit_mode, UNITS_TBYTES);
2722 for (arg_i = 0, arg_end = 0; arg_i < *argc; arg_i++) {
2725 argv[arg_end] = argv[arg_i];
2734 int string_is_numerical(const char *str)
2738 if (!(*str >= '0' && *str <= '9'))
2740 while (*str >= '0' && *str <= '9')
2747 /* Subvolume helper functions */
2749 * test if name is a correct subvolume name
2750 * this function return
2751 * 0-> name is not a correct subvolume name
2752 * 1-> name is a correct subvolume name
2754 int test_issubvolname(const char *name)
2756 return name[0] != '\0' && !strchr(name, '/') &&
2757 strcmp(name, ".") && strcmp(name, "..");
2761 * Test if path is a subvolume
2763 * 0 - path exists but it is not a subvolume
2764 * 1 - path exists and it is a subvolume
2767 int test_issubvolume(const char *path)
2773 res = stat(path, &st);
2777 if (st.st_ino != BTRFS_FIRST_FREE_OBJECTID || !S_ISDIR(st.st_mode))
2780 res = statfs(path, &stfs);
2784 return (int)stfs.f_type == BTRFS_SUPER_MAGIC;
2787 const char *subvol_strip_mountpoint(const char *mnt, const char *full_path)
2789 int len = strlen(mnt);
2793 if (mnt[len - 1] != '/')
2796 return full_path + len;
2803 * 1: Error; and error info printed to the terminal. Fixme.
2804 * 2: If the fullpath is root tree instead of subvol tree
2806 int get_subvol_info(const char *fullpath, struct root_info *get_ri)
2813 const char *svpath = NULL;
2814 DIR *dirstream1 = NULL;
2815 DIR *dirstream2 = NULL;
2817 ret = test_issubvolume(fullpath);
2821 error("not a subvolume: %s", fullpath);
2825 ret = find_mount_root(fullpath, &mnt);
2829 error("%s doesn't belong to btrfs mount point", fullpath);
2833 svpath = subvol_strip_mountpoint(mnt, fullpath);
2835 fd = btrfs_open_dir(fullpath, &dirstream1, 1);
2839 ret = btrfs_list_get_path_rootid(fd, &sv_id);
2843 mntfd = btrfs_open_dir(mnt, &dirstream2, 1);
2847 memset(get_ri, 0, sizeof(*get_ri));
2848 get_ri->root_id = sv_id;
2850 if (sv_id == BTRFS_FS_TREE_OBJECTID)
2851 ret = btrfs_get_toplevel_subvol(mntfd, get_ri);
2853 ret = btrfs_get_subvol(mntfd, get_ri);
2855 error("can't find '%s': %d", svpath, ret);
2858 close_file_or_dir(mntfd, dirstream2);
2859 close_file_or_dir(fd, dirstream1);
2865 void init_rand_seed(u64 seed)
2869 /* only use the last 48 bits */
2870 for (i = 0; i < 3; i++) {
2871 rand_seed[i] = (unsigned short)(seed ^ (unsigned short)(-1));
2874 rand_seed_initlized = 1;
2877 static void __init_seed(void)
2883 if(rand_seed_initlized)
2885 /* Use urandom as primary seed source. */
2886 fd = open("/dev/urandom", O_RDONLY);
2888 ret = read(fd, rand_seed, sizeof(rand_seed));
2890 if (ret < sizeof(rand_seed))
2894 /* Use time and pid as fallback seed */
2895 warning("failed to read /dev/urandom, use time and pid as random seed");
2896 gettimeofday(&tv, 0);
2897 rand_seed[0] = getpid() ^ (tv.tv_sec & 0xFFFF);
2898 rand_seed[1] = getppid() ^ (tv.tv_usec & 0xFFFF);
2899 rand_seed[2] = (tv.tv_sec ^ tv.tv_usec) >> 16;
2901 rand_seed_initlized = 1;
2908 * Don't use nrand48, its range is [0,2^31) The highest bit will alwasy
2909 * be 0. Use jrand48 to include the highest bit.
2911 return (u32)jrand48(rand_seed);
2914 unsigned int rand_range(unsigned int upper)
2918 * Use the full 48bits to mod, which would be more uniformly
2921 return (unsigned int)(jrand48(rand_seed) % upper);
2924 void btrfs_config_init(void)